Skip to content

Commit 05b63d5

Browse files
committed
fix(shared): truncate never splits an emoji
1 parent b2b43be commit 05b63d5

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎packages/shared/src/String.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { truncate } from "./String.ts";
4+
5+
describe("truncate", () => {
6+
it("keeps short text and trims whitespace", () => {
7+
expect(truncate(" hello ", 10)).toBe("hello");
8+
});
9+
10+
it("cuts long text at the limit", () => {
11+
expect(truncate("abcdefgh", 5)).toBe("abcde...");
12+
});
13+
14+
it("never leaves half of an emoji at the cut", () => {
15+
expect(truncate("abcd😀 more", 5)).toBe("abcd...");
16+
expect(truncate("abc😀 more", 5)).toBe("abc😀...");
17+
});
18+
});

‎packages/shared/src/String.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,8 @@ export function truncate(text: string, maxLength = 50): string {
44
return trimmed;
55
}
66

7-
return `${trimmed.slice(0, maxLength)}...`;
7+
// Back off one unit rather than cut a surrogate pair (most emoji) in half.
8+
const lastCode = trimmed.charCodeAt(maxLength - 1);
9+
const end = lastCode >= 0xd800 && lastCode <= 0xdbff ? maxLength - 1 : maxLength;
10+
return `${trimmed.slice(0, end)}...`;
811
}

0 commit comments

Comments
 (0)