Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/shared/src/String.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vite-plus/test";

import { truncate } from "./String.ts";

describe("truncate", () => {
it("cuts before a surrogate pair that would be split", () => {
expect(truncate("abcd😀 more", 5)).toBe("abcd...");
});

it("keeps a surrogate pair that fits exactly", () => {
expect(truncate("abc😀 more", 5)).toBe("abc😀...");
});

it("keeps ASCII and BMP truncation lengths", () => {
expect(truncate(" hello world ", 5)).toBe("hello...");
expect(truncate("日本語のテキスト", 3)).toBe("日本語...");
expect(truncate("short", 5)).toBe("short");
});
});
13 changes: 12 additions & 1 deletion packages/shared/src/String.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;

export function truncate(text: string, maxLength = 50): string {
const trimmed = text.trim();
if (trimmed.length <= maxLength) {
return trimmed;
}

return `${trimmed.slice(0, maxLength)}...`;
let head = trimmed.slice(0, maxLength);
// Cutting between the halves of a surrogate pair leaves a lone surrogate that renders as U+FFFD.
if (
isHighSurrogate(head.charCodeAt(head.length - 1)) &&
isLowSurrogate(trimmed.charCodeAt(head.length))
) {
head = head.slice(0, -1);
}
return `${head}...`;
}
Loading