An open source design system that's fully customizable and agent ready
TypeScript
fix(avatar): preserve grapheme clusters when generating initials (#4750)
alex-js-ltd8c64f9916354
diff --git a/.changeset/avatar-initials-grapheme-clusters.md b/.changeset/avatar-initials-grapheme-clusters.mdnew file mode 100644index 0000000000..ce37a673bd--- /dev/null+++ b/.changeset/avatar-initials-grapheme-clusters.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Avatar: fallback initials no longer break for names containing emoji or other multi-codepoint characters.++@alex-js-ltddiff --git a/packages/core/src/Avatar/Avatar.test.tsx b/packages/core/src/Avatar/Avatar.test.tsxindex 3989209ccd..f91daa50ab 100644--- a/packages/core/src/Avatar/Avatar.test.tsx+++ b/packages/core/src/Avatar/Avatar.test.tsx@@ -65,6 +65,16 @@ describe('Avatar', () => {expect(icon?.querySelector('svg')).not.toBeNull();});+ it('does not split an emoji surrogate pair when generating initials', () => {+ render(<Avatar name="π Ada" data-testid="avatar" />);+ expect(screen.getByTestId('avatar')).toHaveTextContent('πA');+ });++ it('preserves a complete grapheme when generating initials', () => {+ render(<Avatar name="π¬π§ Ada" data-testid="avatar" />);+ expect(screen.getByTestId('avatar')).toHaveTextContent('π¬π§A');+ });+it('retries a new src after a previous src failed to load', () => {const {rerender} = render(<Avatar name="Ada" src="https://example.com/broken.jpg" />,diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsxindex 602e79f03d..56d29185b4 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -337,6 +337,25 @@ export interface AvatarProps extends BaseProps<HTMLDivElement> {onClick?: React.MouseEventHandler<HTMLElement>;}+/**+ * Reuse a single segmenter when the runtime supports Intl.Segmenter.+ */+const graphemeSegmenter =+ typeof Intl.Segmenter === 'function'+ ? new Intl.Segmenter(undefined, {granularity: 'grapheme'})+ : null;++/**+ * Return the first user-perceived character, with a code-point fallback.+ */+function firstGrapheme(word: string): string {+ if (graphemeSegmenter) {+ return [...graphemeSegmenter.segment(word)][0]?.segment ?? '';+ }++ return [...word][0] ?? '';+}+/*** Generates initials from a name string.* Takes the first letter of the first two words.@@ -352,9 +371,11 @@ function getInitials(name: string): string {return '';}if (words.length === 1) {- return words[0].charAt(0).toUpperCase();+ return firstGrapheme(words[0]).toUpperCase();}- return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();+ return (+ firstGrapheme(words[0]) + firstGrapheme(words[words.length - 1])+ ).toUpperCase();}/**