Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

Grapheme-safe text: count characters the way people do (#4776)

AK86a7f1752707
diff --git a/.changeset/character-safe-strings.md b/.changeset/character-safe-strings.md
new file mode 100644
index 0000000000..fc15b127d9
--- /dev/null
+++ b/.changeset/character-safe-strings.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Count and cut text the way people read it: the TextArea character counter (and its over-limit state and screen-reader announcements) counts user-perceived characters — an emoji is 1, not 2; PowerSearch token truncation no longer cuts an emoji or accented letter in half; Table's auto-generated headers capitalize astral-plane letters correctly; Avatar's initials now use the shared character utilities.
+
+@AKnassa
diff --git a/.changeset/character-utils-api.md b/.changeset/character-utils-api.md
new file mode 100644
index 0000000000..e970f55397
--- /dev/null
+++ b/.changeset/character-utils-api.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] New string utilities: `characterCount`, `firstCharacter`, and `truncateCharacters` — replacements for `.length`, `.charAt(0)`, and slice-based truncation that measure and cut user-visible strings by whole characters, so an emoji, flag, or accented letter counts as one and never gets split. Built on `Intl.Segmenter` with a code-point fallback.
+
+@AKnassa
diff --git a/packages/core/src/Avatar/Avatar.test.tsx b/packages/core/src/Avatar/Avatar.test.tsx
index 1d9dc5cc24..7ece01e6af 100644
--- a/packages/core/src/Avatar/Avatar.test.tsx
+++ b/packages/core/src/Avatar/Avatar.test.tsx
@@ -91,11 +91,16 @@ describe('Avatar', () => {
expect(screen.getByTestId('avatar')).toHaveTextContent('😀A');
});
- it('preserves a complete grapheme when generating initials', () => {
+ it('preserves a complete character when generating initials', () => {
render(<Avatar name="🇬🇧 Ada" data-testid="avatar" />);
expect(screen.getByTestId('avatar')).toHaveTextContent('🇬🇧A');
});
+ it('keeps a ZWJ family emoji intact 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.tsx
index 2e54ad2251..32525dd58e 100644
--- a/packages/core/src/Avatar/Avatar.tsx
+++ b/packages/core/src/Avatar/Avatar.tsx
@@ -31,6 +31,7 @@ import {AvatarSizeContext} from './AvatarSizeContext';
import {useAvatarGroup} from '../AvatarGroup/AvatarGroupContext';
import {mergeProps, mergeRefs} from '../utils';
import {themeProps} from '../utils/themeProps';
+import {firstCharacter} from '../utils/characters';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useTooltip} from '../Tooltip/useTooltip';
import {useDevWarning} from '../hooks/useDevWarning';
@@ -317,25 +318,6 @@ 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.
@@ -351,10 +333,10 @@ function getInitials(name: string): string {
return '';
}
if (words.length === 1) {
- return firstGrapheme(words[0]).toUpperCase();
+ return firstCharacter(words[0]).toUpperCase();
}
return (
- firstGrapheme(words[0]) + firstGrapheme(words[words.length - 1])
+ firstCharacter(words[0]) + firstCharacter(words[words.length - 1])
).toUpperCase();
}
diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsx
index 86b51cc616..e7c8861696 100644
--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx
@@ -158,6 +158,41 @@ describe('PowerSearch', () => {
expect(screen.getByRole('combobox')).toHaveFocus();
});
+ describe('token value truncation (#4759)', () => {
+ it('truncates token values by characters, not code units', () => {
+ const truncConfig: PowerSearchConfig = {
+ name: 'trunc',
+ fields: [
+ {
+ key: 'status',
+ label: 'Status',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ };
+ // 14 emoji = 28 code units but 14 user-perceived characters.
+ // adjustedMaxLength = max(15 - 'Status'.length - 'is'.length, 10) = 10,
+ // so the value truncates only past 13 characters, cutting at 10.
+ render(
+ <PowerSearch
+ config={truncConfig}
+ filters={[
+ {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'string', value: '\u{1F600}'.repeat(14)},
+ },
+ ]}
+ onChange={() => {}}
+ maxTokenLength={15}
+ />,
+ );
+ expect(
+ screen.getByText('\u{1F600}'.repeat(10) + '...'),
+ ).toBeInTheDocument();
+ });
+ });
+
describe('startIcon', () => {
it('does not render a start icon when omitted', () => {
render(<PowerSearch config={config} filters={[]} onChange={() => {}} />);
@@ -425,11 +460,15 @@ describe('PowerSearch', () => {
});
});
-
describe('PowerSearch statusVariant forwarding', () => {
it('defaults to attached (status renders with data-variant="attached")', () => {
const {container} = render(
- <PowerSearch config={config} filters={[]} onChange={() => {}} status={{type: 'error', message: 'Required'}} />,
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={() => {}}
+ status={{type: 'error', message: 'Required'}}
+ />,
);
expect(container.querySelector('.astryx-field-status')).toHaveAttribute(
'data-variant',
@@ -439,7 +478,13 @@ describe('PowerSearch statusVariant forwarding', () => {
it('forwards statusVariant="detached" to the underlying Field status', () => {
const {container} = render(
- <PowerSearch config={config} filters={[]} onChange={() => {}} status={{type: 'error', message: 'Required'}} statusVariant="detached" />,
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={() => {}}
+ status={{type: 'error', message: 'Required'}}
+ statusVariant="detached"
+ />,
);
expect(container.querySelector('.astryx-field-status')).toHaveAttribute(
'data-variant',
diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsx
index 9bcb8f7371..0635cd1ddb 100644
--- a/packages/core/src/PowerSearch/PowerSearch.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.tsx
@@ -54,6 +54,7 @@ import {formatFilterValue} from './formatFilterValue';
import {PowerSearchEditPopover} from './PowerSearchEditPopover';
import {resolveOperatorLabel} from './resolveOperatorLabel';
import {themeProps} from '../utils/themeProps';
+import {truncateCharacters} from '../utils/characters';
import {useTranslator} from '../i18n';
import type {
PowerSearchConfig,
@@ -117,7 +118,9 @@ const resultCountStyles = stylex.create({
});
function truncateString(value: string, limit: number): string {
- return value.length > limit + 3 ? value.slice(0, limit) + '...' : value;
+ // Same semantics as before — strings within limit + 3 pass through, longer
+ // ones cut to limit + '...' — but counted in characters, not code units.
+ return truncateCharacters(value, limit + 3, '...');
}
function getEnumLabel(values: ReadonlyArray<EnumItem>, value: string): string {
diff --git a/packages/core/src/PowerSearch/formatFilterValue.test.ts b/packages/core/src/PowerSearch/formatFilterValue.test.ts
index 9bbc4be084..4e7fa91716 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.test.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.test.ts
@@ -62,6 +62,28 @@ describe('formatFilterValue', () => {
'abcde',
);
});
+
+ it('truncates by characters, never splitting an emoji (#4759)', () => {
+ // Four surrogate-pair emoji: 8 code units, 4 user-perceived characters.
+ // The exact-string assertion also proves no surrogate pair was split.
+ const out = fmt(
+ {type: 'string'},
+ {type: 'string', value: '\u{1F600}'.repeat(4)},
+ 3,
+ );
+ expect(out).toBe('\u{1F600}'.repeat(2) + ELLIPSIS);
+ });
+
+ it('keeps multi-unit characters within maxLength intact (#4759)', () => {
+ // Three emoji are 6 code units but only 3 user-perceived characters.
+ expect(
+ fmt(
+ {type: 'string'},
+ {type: 'string', value: '\u{1F600}'.repeat(3)},
+ 3,
+ ),
+ ).toBe('\u{1F600}'.repeat(3));
+ });
});
describe('integer / float', () => {
diff --git a/packages/core/src/PowerSearch/formatFilterValue.ts b/packages/core/src/PowerSearch/formatFilterValue.ts
index 8398990766..3b98c2141e 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.ts
@@ -13,12 +13,10 @@
import type {OperatorValue, FilterValue, EnumItem} from './types';
import type {InternalConfig} from './useInternalConfig';
import type {TranslatorFn} from '../i18n';
+import {truncateCharacters} from '../utils/characters';
function truncate(str: string, maxLength: number): string {
- if (str.length <= maxLength) {
- return str;
- }
- return str.slice(0, maxLength - 1) + '\u2026';
+ return truncateCharacters(str, maxLength);
}
function formatEnumLabel(
diff --git a/packages/core/src/Table/Table.test.tsx b/packages/core/src/Table/Table.test.tsx
index b23d870412..4922462b5b 100644
--- a/packages/core/src/Table/Table.test.tsx
+++ b/packages/core/src/Table/Table.test.tsx
@@ -95,6 +95,12 @@ describe('columnUtils', () => {
it('handles single character', () => {
expect(capitalize('a')).toBe('A');
});
+
+ it('uppercases an astral-plane letter without splitting it (#4759)', () => {
+ // Deseret 𐐨 (U+10428) uppercases to 𐐀 (U+10400); charAt(0) would grab
+ // half the surrogate pair and leave the string unchanged.
+ expect(capitalize('\u{10428}pple')).toBe('\u{10400}pple');
+ });
});
describe('generateColumns', () => {
diff --git a/packages/core/src/Table/columnUtils.ts b/packages/core/src/Table/columnUtils.ts
index b4d85858be..8a15b2af61 100644
--- a/packages/core/src/Table/columnUtils.ts
+++ b/packages/core/src/Table/columnUtils.ts
@@ -13,6 +13,7 @@
import type {CSSProperties, ReactNode} from 'react';
import type {TableColumn, ProportionalWidth, PixelWidth} from './types';
+import {firstCharacter} from '../utils/characters';
/** Default minimum width (in px) for proportional columns. */
export const DEFAULT_MIN_COLUMN_WIDTH = 120;
@@ -168,7 +169,8 @@ export function capitalize(str: string): string {
if (str.length === 0) {
return str;
}
- return str.charAt(0).toUpperCase() + str.slice(1);
+ const first = firstCharacter(str);
+ return first.toUpperCase() + str.slice(first.length);
}
/**
diff --git a/packages/core/src/TextArea/TextArea.doc.mjs b/packages/core/src/TextArea/TextArea.doc.mjs
index 9297211a89..95d037d242 100644
--- a/packages/core/src/TextArea/TextArea.doc.mjs
+++ b/packages/core/src/TextArea/TextArea.doc.mjs
@@ -105,7 +105,7 @@ export const docs = {
name: 'maxLength',
type: 'number',
description:
- 'Maximum number of characters allowed. When set, a character counter (current/max) is displayed inside the input container, anchored to the bottom-right beneath the text. Does not enforce the limit natively; when exceeded the counter turns red and shows a warning icon (a non-color cue), and screen-reader users hear the remaining/over-limit count announced.',
+ 'Maximum number of characters allowed, counted as user-perceived characters — an emoji or flag sequence counts as one. When set, a character counter (current/max) is displayed inside the input container, anchored to the bottom-right beneath the text. Does not enforce the limit natively; when exceeded the counter turns red and shows a warning icon (a non-color cue), and screen-reader users hear the remaining/over-limit count announced. Consumers validating the limit should count with characterCount (exported from the package) so enforcement matches the displayed count.',
},
{
name: 'status',
diff --git a/packages/core/src/TextArea/TextArea.test.tsx b/packages/core/src/TextArea/TextArea.test.tsx
index fc4dc33113..9218a91ae8 100644
--- a/packages/core/src/TextArea/TextArea.test.tsx
+++ b/packages/core/src/TextArea/TextArea.test.tsx
@@ -504,6 +504,33 @@ describe('TextArea', () => {
expect(screen.getByRole('textbox')).not.toHaveAttribute('maxlength');
});
+ it('counts user-perceived characters, not code units (#4759)', () => {
+ // Two surrogate-pair emoji: 4 code units, but 2 user-perceived characters.
+ render(
+ <TextArea
+ label="Description"
+ value={'\u{1F600}\u{1F600}'}
+ onChange={() => {}}
+ maxLength={5}
+ />,
+ );
+ expect(screen.getByText('2/5')).toBeInTheDocument();
+ });
+
+ it('measures the over-limit state in characters (#4759)', () => {
+ // Three ZWJ family emoji: 33 code units, 3 user-perceived characters.
+ const family = '\u{1F468}‍\u{1F469}‍\u{1F467}‍\u{1F466}';
+ render(
+ <TextArea
+ label="Description"
+ value={family.repeat(3)}
+ onChange={() => {}}
+ maxLength={2}
+ />,
+ );
+ expect(screen.getByText('3/2')).toBeInTheDocument();
+ });
+
it('counter updates as user types (controlled)', async () => {
const user = userEvent.setup();
function Wrapper() {
@@ -570,6 +597,51 @@ describe('TextArea', () => {
});
});
+ it('announces zone transitions using character counts (#4759)', async () => {
+ function Wrapper() {
+ const [val, setVal] = useState('x'.repeat(7));
+ return (
+ <TextArea
+ label="Description"
+ value={val}
+ onChange={setVal}
+ maxLength={10}
+ />
+ );
+ }
+ render(<Wrapper />);
+ // Appending two emoji makes 9 characters (11 code units): near the limit
+ // with 1 remaining. Code-unit counting would call this over the limit
+ // and announce assertively instead.
+ fireEvent.change(screen.getByRole('textbox'), {
+ target: {value: 'x'.repeat(7) + '\u{1F600}\u{1F600}'},
+ });
+ const politeRegion = () =>
+ document.querySelector('[data-astryx-live-region="polite"]');
+ const assertiveRegion = () =>
+ document.querySelector('[data-astryx-live-region="assertive"]');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('1 character remaining');
+ });
+ expect(assertiveRegion()).not.toHaveTextContent('over the limit');
+ });
+
+ it('does not flag over-limit while characters fit, even when code units exceed (#4759)', () => {
+ // Three emoji: 6 code units but 3 user-perceived characters — within a
+ // maxLength of 4, so no error state anywhere.
+ render(
+ <TextArea
+ label="Description"
+ value={'\u{1F600}'.repeat(3)}
+ onChange={() => {}}
+ maxLength={4}
+ />,
+ );
+ const counter = screen.getByText('3/4');
+ expect(counter.querySelector('svg')).toBeNull();
+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-invalid');
+ });
+
it('shows a non-color over-limit indicator icon when exceeded', () => {
const {container} = render(
<TextArea
diff --git a/packages/core/src/TextArea/TextArea.tsx b/packages/core/src/TextArea/TextArea.tsx
index ac109a354c..5846bdf0eb 100644
--- a/packages/core/src/TextArea/TextArea.tsx
+++ b/packages/core/src/TextArea/TextArea.tsx
@@ -22,6 +22,7 @@ import {
useTransition,
useRef,
useCallback,
+ useMemo,
type ChangeEvent,
type ClipboardEvent,
type FocusEvent,
@@ -53,6 +54,7 @@ import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
import {useAnnounce} from '../hooks/useAnnounce';
import {useSize} from '../SizeContext/SizeContext';
import {themeProps} from '../utils/themeProps';
+import {characterCount} from '../utils/characters';
import {useTranslator} from '../i18n';
const COUNTER_WARNING_THRESHOLD = 0.8;
@@ -312,10 +314,13 @@ export interface TextAreaProps extends Omit<
*/
onPaste?: (e: ClipboardEvent<HTMLTextAreaElement>) => void;
/**
- * Maximum number of characters allowed.
- * When set, displays a character counter below the textarea.
+ * Maximum number of characters allowed, counted as user-perceived
+ * characters — an emoji or flag sequence counts as one. When set,
+ * displays a character counter below the textarea.
* Does not enforce the limit natively — the counter shows error styling
- * when exceeded, and the consumer can validate via onChange.
+ * when exceeded, and the consumer can validate via onChange. Validate with
+ * `characterCount` (exported from this package) rather than `value.length`
+ * so enforcement matches the displayed count.
*/
maxLength?: number;
/**
@@ -482,7 +487,11 @@ export function TextArea({
return;
}
const newValue = e.target.value;
- announceCounter(newValue.length);
+ // Guarded here, not just inside announceCounter, so textareas without a
+ // maxLength never pay for segmenting the whole value on each keystroke.
+ if (maxLength != null) {
+ announceCounter(characterCount(newValue));
+ }
onChange?.(newValue, e);
if (changeAction && !e.defaultPrevented) {
startTransition(async () => {
@@ -492,6 +501,15 @@ export function TextArea({
}
};
+ // Counter semantics count user-perceived characters, so an emoji or flag
+ // sequence counts as one character, not its code units.
+ // Only measured when a counter exists — segmentation is O(value length),
+ // and memoized so re-renders that keep the same value skip it entirely.
+ const valueLength = useMemo(
+ () => (maxLength != null ? characterCount(optimisticValue) : 0),
+ [maxLength, optimisticValue],
+ );
+
const effectivelyDisabled = isDisabled || isBusy;
// Focus textarea when clicking anywhere on the wrapper (icons, padding, etc.)
@@ -583,7 +601,7 @@ export function TextArea({
aria-required={isRequired && !isOptional ? 'true' : undefined}
aria-invalid={
status?.type === 'error' ||
- (maxLength != null && optimisticValue.length > maxLength)
+ (maxLength != null && valueLength > maxLength)
? 'true'
: undefined
}
@@ -614,15 +632,15 @@ export function TextArea({
id={counterID}
{...stylex.props(
styles.counter,
- optimisticValue.length > maxLength && styles.counterError,
+ valueLength > maxLength && styles.counterError,
)}>
- {optimisticValue.length > maxLength && (
+ {valueLength > maxLength && (
// Non-color cue so the over-limit state isn't conveyed by the red
// color alone (WCAG 1.4.1). Decorative — the count text and the
// live-region announcement carry the meaning.
<Icon icon="warning" size="sm" />
)}
- {optimisticValue.length}/{maxLength}
+ {valueLength}/{maxLength}
</div>
)}
</div>
diff --git a/packages/core/src/utils/characters.test.ts b/packages/core/src/utils/characters.test.ts
new file mode 100644
index 0000000000..f5e7fcd4bb
--- /dev/null
+++ b/packages/core/src/utils/characters.test.ts
@@ -0,0 +1,141 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file characters.test.ts
+ * @input character-counting utilities
+ * @output Tests for characterCount, firstCharacter, truncateCharacters
+ */
+
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {characterCount, firstCharacter, truncateCharacters} from './characters';
+
+// Multi-code-unit fixtures: an emoji surrogate pair (2 units), a flag
+// sequence (4 units), a ZWJ family (11 units), and a combining mark (2 units).
+const EMOJI = '\u{1F600}'; // 😀
+const FLAG = '\u{1F1F9}\u{1F1F7}'; // 🇹🇷
+const FAMILY = '\u{1F468}‍\u{1F469}‍\u{1F467}‍\u{1F466}'; // 👨‍👩‍👧‍👦
+// é as base + combining mark, spelled as an escape so NFC-normalizing
+// tools cannot silently precompose the fixture into single-code-unit é.
+const E_ACUTE = 'e\u0301';
+
+describe('characterCount', () => {
+ it('returns 0 for the empty string', () => {
+ expect(characterCount('')).toBe(0);
+ });
+
+ it('counts ASCII one per character', () => {
+ expect(characterCount('hello')).toBe(5);
+ });
+
+ it('counts an emoji surrogate pair as one', () => {
+ expect(characterCount(EMOJI.repeat(2))).toBe(2);
+ expect(EMOJI.repeat(2).length).toBe(4); // sanity: code units differ
+ });
+
+ it('counts a flag sequence as one', () => {
+ expect(characterCount(FLAG)).toBe(1);
+ });
+
+ it('counts a ZWJ family emoji as one', () => {
+ expect(characterCount(FAMILY)).toBe(1);
+ expect(FAMILY.length).toBe(11); // sanity: code units differ
+ });
+
+ it('counts a combining-mark character as one', () => {
+ expect(characterCount(E_ACUTE)).toBe(1);
+ expect(E_ACUTE.length).toBe(2); // sanity: code units differ
+ });
+
+ it('counts mixed content by user-perceived characters', () => {
+ expect(characterCount(`a${EMOJI}b`)).toBe(3);
+ });
+});
+
+describe('firstCharacter', () => {
+ it('returns the empty string for the empty string', () => {
+ expect(firstCharacter('')).toBe('');
+ });
+
+ it('returns the first ASCII character', () => {
+ expect(firstCharacter('abc')).toBe('a');
+ });
+
+ it('returns a whole emoji, not half a surrogate pair', () => {
+ expect(firstCharacter(`${EMOJI}x`)).toBe(EMOJI);
+ });
+
+ it('returns a whole ZWJ family emoji', () => {
+ expect(firstCharacter(`${FAMILY}x`)).toBe(FAMILY);
+ });
+
+ it('keeps a combining mark attached to its base', () => {
+ expect(firstCharacter(`${E_ACUTE}cole`)).toBe(E_ACUTE);
+ });
+});
+
+describe('truncateCharacters', () => {
+ it('returns strings within max unchanged', () => {
+ expect(truncateCharacters('abc', 5)).toBe('abc');
+ });
+
+ it('returns strings exactly at max unchanged', () => {
+ expect(truncateCharacters('abcde', 5)).toBe('abcde');
+ });
+
+ it('truncates so the result, including the ellipsis, is max characters', () => {
+ expect(truncateCharacters('abcdefghij', 5)).toBe('abcd…');
+ });
+
+ it('counts a multi-character ellipsis against max', () => {
+ // "..." is 3 characters, so 5 content characters remain.
+ expect(truncateCharacters('aaaaaaaaaa', 8, '...')).toBe('aaaaa...');
+ });
+
+ it('passes strings within max through under a multi-character ellipsis', () => {
+ expect(truncateCharacters('aaaaaaaa', 8, '...')).toBe('aaaaaaaa');
+ });
+
+ it('cuts between characters, never splitting an emoji', () => {
+ // The exact-string assertion also proves no surrogate pair was split.
+ expect(truncateCharacters(EMOJI.repeat(4), 3)).toBe(`${EMOJI.repeat(2)}…`);
+ });
+
+ it('treats a ZWJ family emoji as a single unit when cutting', () => {
+ expect(truncateCharacters(`${FAMILY}abc`, 2)).toBe(`${FAMILY}…`);
+ });
+
+ it('returns the empty string unchanged', () => {
+ expect(truncateCharacters('', 5)).toBe('');
+ });
+
+ it('degrades to just the ellipsis when max is smaller than the ellipsis', () => {
+ // Documented degenerate behavior: no consumer passes max below the
+ // ellipsis length, but the clamp must stay predictable.
+ expect(truncateCharacters('abcdef', 2, '...')).toBe('...');
+ expect(truncateCharacters('abcdef', 0)).toBe('…');
+ });
+});
+
+describe('code-point fallback (no Intl.Segmenter)', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.resetModules();
+ });
+
+ it('keeps surrogate pairs intact while counting by code points', async () => {
+ vi.resetModules();
+ // characters.ts only reads Intl.Segmenter, so a minimal stub suffices.
+ vi.stubGlobal('Intl', {Segmenter: undefined});
+ const fallback = await import('./characters');
+
+ expect(fallback.characterCount(EMOJI.repeat(2))).toBe(2);
+ expect(fallback.firstCharacter(`${EMOJI}x`)).toBe(EMOJI);
+ expect(fallback.firstCharacter('')).toBe('');
+ expect(fallback.truncateCharacters(EMOJI.repeat(4), 3)).toBe(
+ `${EMOJI.repeat(2)}…`,
+ );
+ // Documented degradation: a flag sequence splits into its two
+ // regional-indicator code points under the fallback.
+ expect(fallback.characterCount(FLAG)).toBe(2);
+ });
+});
diff --git a/packages/core/src/utils/characters.ts b/packages/core/src/utils/characters.ts
new file mode 100644
index 0000000000..dc0f06d093
--- /dev/null
+++ b/packages/core/src/utils/characters.ts
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file characters.ts
+ * @input Strings that may contain characters made of several code units
+ * (emoji, flags, joined emoji sequences, accented letters)
+ * @output Exports characterCount, firstCharacter, truncateCharacters —
+ * replacements for .length / .charAt(0) / .slice(0, n) that measure
+ * and cut user-visible strings the way a person reads them
+ * @position Shared utility; consumed by Avatar, TextArea, PowerSearch, Table
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/utils/characters.test.ts
+ * - /packages/core/src/utils/index.ts
+ */
+
+/**
+ * Reuse a single segmenter when the runtime supports Intl.Segmenter.
+ * `grapheme` is the Intl granularity name for a user-perceived character.
+ */
+const characterSegmenter =
+ typeof Intl.Segmenter === 'function'
+ ? new Intl.Segmenter(undefined, {granularity: 'grapheme'})
+ : null;
+
+/**
+ * Split a string into user-perceived characters. The code-point fallback
+ * keeps surrogate pairs intact but may split joined emoji sequences and flag
+ * pairs on runtimes without Intl.Segmenter.
+ */
+function splitCharacters(str: string): string[] {
+ if (characterSegmenter) {
+ return [...characterSegmenter.segment(str)].map(s => s.segment);
+ }
+ return [...str];
+}
+
+/**
+ * Number of characters in a string — the count a person would give, where one
+ * emoji, flag, or accented letter is one character. Replacement for `.length`
+ * on user-visible strings, which counts internal storage units instead.
+ */
+export function characterCount(str: string): number {
+ if (str === '') {
+ return 0;
+ }
+ return splitCharacters(str).length;
+}
+
+/**
+ * The first character of a string, or '' when empty. Replacement for
+ * `.charAt(0)`, which can return half of an emoji. Reads only the first
+ * character, so cost does not scale with the length of the string.
+ */
+export function firstCharacter(str: string): string {
+ if (characterSegmenter) {
+ const first = characterSegmenter.segment(str)[Symbol.iterator]().next();
+ return first.done ? '' : first.value.segment;
+ }
+ const codePoint = str.codePointAt(0);
+ return codePoint == null ? '' : String.fromCodePoint(codePoint);
+}
+
+/**
+ * Truncate to at most `max` characters, ellipsis included: strings within
+ * `max` characters pass through unchanged; longer strings are cut so the
+ * result — content plus `ellipsis` — is exactly `max` characters (or just the
+ * ellipsis, when `max` is smaller than the ellipsis itself). Replacement for
+ * `str.slice(0, n) + '…'`, which can cut an emoji in half.
+ *
+ * @example
+ * ```
+ * truncateCharacters('abcdefghij', 5) // 'abcd…'
+ * truncateCharacters('abcdefghij', 8, '...') // 'abcde...'
+ * ```
+ */
+export function truncateCharacters(
+ str: string,
+ max: number,
+ ellipsis = '…',
+): string {
+ const characters = splitCharacters(str);
+ if (characters.length <= max) {
+ return str;
+ }
+ const keep = Math.max(max - characterCount(ellipsis), 0);
+ return characters.slice(0, keep).join('') + ellipsis;
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 1c77663a63..c8737164e7 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -70,6 +70,8 @@ export type {ISOTimeString, ParsedTime} from './timeParser';
export {parseStyleKey} from './parseStyleKey';
export {getKey, type Key, type KeyFallback} from './getKey';
+export {characterCount, firstCharacter, truncateCharacters} from './characters';
+
export {mergeProps} from './mergeProps';
export {mergeRefs} from './mergeRefs';
export {isFocusDetached} from './focusReturn';