Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Keep the whole-character helpers working in older browsers

Claudecd306bd62e1f
diff --git a/src/lib/initials-old-browser.test.ts b/src/lib/initials-old-browser.test.ts
new file mode 100644
index 0000000..69a9466
--- /dev/null
+++ b/src/lib/initials-old-browser.test.ts
@@ -0,0 +1,32 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+// Firefox 115 ESR has neither Intl.Segmenter nor String.prototype.toWellFormed.
+// Remove both before the helpers load, so this file runs the code path those
+// browsers take. Each test file runs in its own process.
+Reflect.deleteProperty(Intl, "Segmenter");
+Reflect.deleteProperty(String.prototype, "toWellFormed");
+
+const { getInitials } = await import("./initials.ts");
+const { truncateToWholeCharacters } = await import("./text-truncate.ts");
+
+function isWellFormed(value: string): boolean {
+ return !/[\uD800-\uDFFF]/.test(
+ value.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, ""),
+ );
+}
+
+test("initials load and stay whole without Intl.Segmenter", () => {
+ assert.equal(typeof Intl.Segmenter, "undefined");
+ assert.equal(getInitials("Robin Casey πŸ˜€", { max: 4 }), "RC");
+ assert.equal(getInitials("Robin Casey D", { max: 4 }), "RCD");
+ assert.equal(getInitials("πŸ‘©πŸ½β€πŸ’»", { max: 4 }), "πŸ‘©πŸ½β€πŸ’»");
+ assert.equal(getInitials("\ud83d Robin", { max: 4 }), "R");
+});
+
+test("typed initials are cut at whole characters without Intl.Segmenter", () => {
+ const cut = truncateToWholeCharacters("ABπŸ˜€C", 3);
+
+ assert.ok(isWellFormed(cut), JSON.stringify(cut));
+ assert.equal(cut, "AB");
+});
diff --git a/src/lib/initials.ts b/src/lib/initials.ts
index bf53ddc..6c2a414 100644
--- a/src/lib/initials.ts
+++ b/src/lib/initials.ts
@@ -1,13 +1,10 @@
-const graphemeSegmenter = new Intl.Segmenter(undefined, {
- granularity: "grapheme",
-});
+import {
+ splitIntoWholeCharacters,
+ toWellFormedText,
+} from "./whole-characters.ts";
const startsWithLetterOrDigit = /^[\p{L}\p{N}]/u;
-function wholeCharacters(word: string): string[] {
- return Array.from(graphemeSegmenter.segment(word), ({ segment }) => segment);
-}
-
type InitialsOptions = {
// Most initials to return.
max: number;
@@ -22,7 +19,7 @@ type InitialsOptions = {
// do not start with a letter or digit (an emoji, a dash) are skipped, unless
// the name has nothing else.
export function getInitials(name: string, options: InitialsOptions): string {
- const words = name.toWellFormed().trim().split(/\s+/).filter(Boolean);
+ const words = toWellFormedText(name).trim().split(/\s+/).filter(Boolean);
if (words.length === 0) {
return "";
@@ -32,7 +29,7 @@ export function getInitials(name: string, options: InitialsOptions): string {
const sourceWords = namedWords.length > 0 ? namedWords : words.slice(0, 1);
if (sourceWords.length === 1 && options.singleWordLength) {
- return wholeCharacters(sourceWords[0]!)
+ return splitIntoWholeCharacters(sourceWords[0]!)
.slice(0, Math.min(options.singleWordLength, options.max))
.join("")
.toUpperCase();
@@ -40,7 +37,7 @@ export function getInitials(name: string, options: InitialsOptions): string {
return sourceWords
.slice(0, options.max)
- .map((word) => wholeCharacters(word)[0] ?? "")
+ .map((word) => splitIntoWholeCharacters(word)[0] ?? "")
.join("")
.toUpperCase();
}
diff --git a/src/lib/text-truncate.ts b/src/lib/text-truncate.ts
index 3fe8a2b..52a92a7 100644
--- a/src/lib/text-truncate.ts
+++ b/src/lib/text-truncate.ts
@@ -1,6 +1,7 @@
-const graphemeSegmenter = new Intl.Segmenter(undefined, {
- granularity: "grapheme",
-});
+import {
+ splitIntoWholeCharacters,
+ toWellFormedText,
+} from "./whole-characters.ts";
// Shortens text to at most maxLength UTF-16 code units, cutting only between
// whole characters, so an emoji (or a letter with its accent) is kept or
@@ -10,7 +11,7 @@ export function truncateToWholeCharacters(
value: string,
maxLength: number,
): string {
- const wellFormed = value.toWellFormed();
+ const wellFormed = toWellFormedText(value);
if (wellFormed.length <= maxLength) {
return wellFormed;
@@ -18,7 +19,7 @@ export function truncateToWholeCharacters(
let result = "";
- for (const { segment } of graphemeSegmenter.segment(wellFormed)) {
+ for (const segment of splitIntoWholeCharacters(wellFormed)) {
if (result.length + segment.length > maxLength) {
break;
}
diff --git a/src/lib/whole-characters.test.ts b/src/lib/whole-characters.test.ts
new file mode 100644
index 0000000..0bcad76
--- /dev/null
+++ b/src/lib/whole-characters.test.ts
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ splitIntoWholeCharacters,
+ splitWithoutSegmenter,
+ toWellFormedWithoutBuiltIn,
+} from "./whole-characters.ts";
+
+const samples = [
+ "Robin Casey πŸ˜€",
+ "élodie",
+ "πŸ‘πŸ½ ok",
+ "πŸ‘©πŸ½β€πŸ’» dev",
+ "❀️ love",
+ "🏴󠁧󠁒󠁳󠁣󠁴󠁿 flag",
+];
+
+// Browsers without Intl.Segmenter (Firefox 115 ESR) take the fallback path,
+// which must agree with the segmenter on accents and common emoji.
+test("the fallback splits like Intl.Segmenter on accents and emoji", () => {
+ for (const sample of samples) {
+ assert.deepEqual(
+ splitWithoutSegmenter(sample),
+ splitIntoWholeCharacters(sample),
+ sample,
+ );
+ }
+});
+
+test("the toWellFormed fallback matches the built-in", () => {
+ for (const sample of [
+ ...samples,
+ "\ud83d",
+ "a\ud83db",
+ "\ude00x",
+ "xπŸ˜€\ud83d",
+ ]) {
+ assert.equal(toWellFormedWithoutBuiltIn(sample), sample.toWellFormed());
+ }
+});
diff --git a/src/lib/whole-characters.ts b/src/lib/whole-characters.ts
new file mode 100644
index 0000000..2b7d9ed
--- /dev/null
+++ b/src/lib/whole-characters.ts
@@ -0,0 +1,78 @@
+// Helpers for cutting text only between whole characters. They run in the
+// browser too, so they don't rely on Intl.Segmenter (Firefox 125+) or
+// String.prototype.toWellFormed (Firefox 119+) being present: Firefox 115 ESR
+// has neither.
+
+const graphemeSegmenter =
+ typeof Intl !== "undefined" && typeof Intl.Segmenter === "function"
+ ? new Intl.Segmenter(undefined, { granularity: "grapheme" })
+ : null;
+
+const replacementCharacter = String.fromCharCode(0xfffd);
+
+// Swaps each lone surrogate for U+FFFD, like toWellFormed().
+export function toWellFormedText(value: string): string {
+ if (typeof value.toWellFormed === "function") {
+ return value.toWellFormed();
+ }
+
+ return toWellFormedWithoutBuiltIn(value);
+}
+
+// Exported for tests. Iterating a string by code point yields a lone
+// surrogate as a one-unit string, which is how it is found here (no regex
+// lookbehind, which Safari before 16.4 can't parse).
+export function toWellFormedWithoutBuiltIn(value: string): string {
+ let result = "";
+
+ for (const codePoint of value) {
+ const unit = codePoint.charCodeAt(0);
+ const isLone = codePoint.length === 1 && unit >= 0xd800 && unit <= 0xdfff;
+
+ result += isLone ? replacementCharacter : codePoint;
+ }
+
+ return result;
+}
+
+// Code points that belong to the character before them: combining marks,
+// variation selectors, emoji skin tones, tag characters and the zero-width
+// joiner, plus the code point a joiner glues on.
+const extendsCharacter = /^[\p{M}‍︀-️\u{1F3FB}-\u{1F3FF}\u{E0020}-\u{E007F}]$/u;
+
+// Splits text into whole characters (grapheme clusters). Without
+// Intl.Segmenter it keeps marks, joiners and modifiers with their base
+// character, which covers accents and most emoji.
+export function splitIntoWholeCharacters(value: string): string[] {
+ const text = toWellFormedText(value);
+
+ if (graphemeSegmenter) {
+ return Array.from(
+ graphemeSegmenter.segment(text),
+ ({ segment }) => segment,
+ );
+ }
+
+ return splitWithoutSegmenter(text);
+}
+
+// Exported for tests: the path browsers without Intl.Segmenter take.
+export function splitWithoutSegmenter(text: string): string[] {
+ const characters: string[] = [];
+ let joinNext = false;
+
+ for (const codePoint of text) {
+ if (
+ characters.length > 0 &&
+ (joinNext || extendsCharacter.test(codePoint))
+ ) {
+ characters[characters.length - 1] += codePoint;
+ } else {
+ characters.push(codePoint);
+ }
+
+ joinNext = codePoint === "‍";
+ }
+
+ return characters;
+}