diff --git a/packages/design-system/src/utils/labelUtil.spec.ts b/packages/design-system/src/utils/labelUtil.spec.ts index 51289d1736..99f961d485 100644 --- a/packages/design-system/src/utils/labelUtil.spec.ts +++ b/packages/design-system/src/utils/labelUtil.spec.ts @@ -1,3 +1,5 @@ +import type { MockInstance } from 'vitest'; + import { getInitials } from './labelUtil'; describe('labelUtil.getInitials', () => { @@ -26,4 +28,29 @@ describe('labelUtil.getInitials', () => { ])('turns "%s" into "%s"', (input, output) => { expect(getInitials(input)).toBe(output); }); + + describe('when Intl.Segmenter is not supported', () => { + let intlSpy: MockInstance; + + beforeEach(() => { + // No Intl.Segmenter support + intlSpy = vi.spyOn(globalThis, 'Intl', 'get'); + intlSpy.mockImplementation(() => ({})); + }); + + it.each([ + ['', ''], + + // simple words + ['Hello', 'He'], + ['Hello World', 'HW'], + ['H', 'H'], + + // multiple spaces + ['Double Space', 'DS'], + [' ', ''], + ])('turns "%s" into "%s"', (input, output) => { + expect(getInitials(input)).toBe(output); + }); + }); }); diff --git a/packages/design-system/src/utils/labelUtil.ts b/packages/design-system/src/utils/labelUtil.ts index ee6f8903f6..073b06179c 100644 --- a/packages/design-system/src/utils/labelUtil.ts +++ b/packages/design-system/src/utils/labelUtil.ts @@ -1,25 +1,19 @@ export const getInitials = (label: string): string => { - const words = label - .split(' ') - .filter((word) => word !== '') - .map((word) => [...new Intl.Segmenter().segment(word)]); + const isSegmenterSupported = typeof Intl !== 'undefined' && 'Segmenter' in Intl; - if (words.length === 0) { - return ''; - } else if (words.length === 1) { - // first two segments of the first word - return ( - words - .at(0) - ?.slice(0, 2) - .map((grapheme) => grapheme.segment) - .join('') ?? '' - ); - } else { - // first segment ok the first two words - return words - .slice(0, 2) - .map((word) => word.at(0)?.segment ?? '') - .join(''); - } + const segmentWord = (word: string): string[] => { + if (isSegmenterSupported) { + return [...new Intl.Segmenter().segment(word)].map((s) => s.segment); + } + return word.split(''); + }; + + const getFirstSegment = (word: string[]): string => word[0] || ''; + const getFirstTwoSegments = (word: string[]): string => word.slice(0, 2).join(''); + + const words = label.split(' ').filter(Boolean).map(segmentWord); + + if (words.length === 0) return ''; + if (words.length === 1) return getFirstTwoSegments(words[0]); + return words.slice(0, 2).map(getFirstSegment).join(''); };