Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/truncate-surrogate-safe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': patch
---

Stop `truncateWithEndVisible` from splitting characters outside the BMP (such as CJK Extension B kanji and emoji) into a broken replacement character when truncating to a very small width. The short-width fallback now slices by code point, matching the main truncation path.
15 changes: 15 additions & 0 deletions packages/ui/src/utils/__tests__/truncateTextWithEndVisible.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ describe('truncateWithEndVisible', () => {
expect(truncateWithEndVisible('1234567890', 5, 3)).toBe('...890');
});

test('should not split surrogate pairs when maxLength is too small', () => {
// The short-maxLength fallback must stay code-point-safe like the main path.
// Slicing on UTF-16 code units cuts characters outside the BMP (CJK Extension B,
// emoji) mid-surrogate, leaving a replacement character.
expect(truncateWithEndVisible('𠮷𠮷𠮷𠮷𠮷𠮷', 5, 5)).toBe('...𠮷𠮷𠮷𠮷𠮷');
expect(truncateWithEndVisible('🍣🍣🍣🍣🍣🍣', 5, 5)).toBe('...🍣🍣🍣🍣🍣');
});

test('should measure length by code point, not UTF-16 unit', () => {
// 5 astral characters are 10 UTF-16 code units but fit within maxLength 8,
// so the string is returned unchanged rather than truncated.
expect(truncateWithEndVisible('𠮷𠮷𠮷𠮷𠮷', 8, 5)).toBe('𠮷𠮷𠮷𠮷𠮷');
expect(truncateWithEndVisible('🍣🍣🍣🍣🍣', 8, 5)).toBe('🍣🍣🍣🍣🍣');
});

test('should handle email addresses', () => {
expect(truncateWithEndVisible('test@example.com', 10)).toBe('te...e.com');
});
Expand Down
10 changes: 5 additions & 5 deletions packages/ui/src/utils/truncateTextWithEndVisible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,21 @@ export function truncateWithEndVisible(str: string, maxLength = 20, endChars = 5
const ELLIPSIS = '...';
const ELLIPSIS_LENGTH = ELLIPSIS.length;

if (!str || str.length <= maxLength) {
if (!str) {
return str;
}

if (maxLength <= endChars + ELLIPSIS_LENGTH) {
return ELLIPSIS + str.slice(-endChars);
}

const chars = Array.from(str);
const totalChars = chars.length;

if (totalChars <= maxLength) {
return str;
}

if (maxLength <= endChars + ELLIPSIS_LENGTH) {
return ELLIPSIS + chars.slice(-endChars).join('');
}

const beginLength = maxLength - endChars - ELLIPSIS_LENGTH;
const beginPortion = chars.slice(0, beginLength).join('');
const endPortion = chars.slice(-endChars).join('');
Expand Down
Loading