fix(editor): Fix getInitials when Intl.Segmenter is not supported (#11103)
Some checks failed
Test Master / install-and-build (push) Has been cancelled
Test Master / Unit tests (18.x) (push) Has been cancelled
Test Master / Unit tests (20.x) (push) Has been cancelled
Test Master / Unit tests (22.4) (push) Has been cancelled
Test Master / Lint (push) Has been cancelled
Test Master / Notify Slack on failure (push) Has been cancelled

This commit is contained in:
Elias Meire 2024-10-04 16:55:41 +02:00 committed by GitHub
parent bb59cc71ac
commit 7e8955b322
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 43 additions and 22 deletions

View file

@ -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);
});
});
});

View file

@ -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('');
};