Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Build avatar initials from whole characters
Claude3c34910a6b62
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsxindex bb06df4..44b8895 100644--- a/src/components/envelopes/prepare-live-shell.tsx+++ b/src/components/envelopes/prepare-live-shell.tsx@@ -35,6 +35,7 @@ import {optionsTextToShow,parseOptionLines,} from "@/lib/field-choices";+import { getInitials } from "@/lib/initials";import {type FieldPlacement,type ReplaceFieldsResponse,@@ -1257,10 +1258,7 @@ function SignerCard({color: signer.color,}}>- {signer.name- .split(" ")- .map((part) => part[0])- .join("")}+ {getInitials(signer.name, { max: 4 })}</span><div className="min-w-0"><p className="truncate text-sm font-bold text-(--fg)">{signer.name}</p>@@ -1323,10 +1321,7 @@ function SelectedSignerPanel({color: selectedSigner.color,}}>- {selectedSigner.name- .split(" ")- .map((part) => part[0])- .join("")}+ {getInitials(selectedSigner.name, { max: 4 })}</span><div className="min-w-0"><p className="truncate text-sm font-bold text-(--fg)">diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsxindex c836770..5095625 100644--- a/src/components/layout/app-shell.tsx+++ b/src/components/layout/app-shell.tsx@@ -19,6 +19,7 @@ import {} from "@/components/ui/dropdown-menu";import { authClient } from "@/lib/auth/client";import { cn } from "@/lib/cn";+import { getInitials } from "@/lib/initials";type AppShellProps = {children: ReactNode;@@ -42,7 +43,7 @@ export function AppShell({const router = useRouter();const [isSigningOut, setIsSigningOut] = useState(false);const currentSection = resolveSection(pathname);- const initials = getInitials(user.name);+ const initials = getInitials(user.name, { max: 2 }) || "SU";async function handleSignOut() {if (isSigningOut) {@@ -216,17 +217,3 @@ function resolveSection(pathname: string): ShellSection {return "workspace";}--function getInitials(name: string) {- const segments = name- .split(/\s+/)- .map((segment) => segment.trim())- .filter(Boolean)- .slice(0, 2);-- if (segments.length === 0) {- return "SU";- }-- return segments.map((segment) => segment[0]?.toUpperCase() ?? "").join("");-}diff --git a/src/components/layout/public-session-menu.tsx b/src/components/layout/public-session-menu.tsxindex 31939f2..b80eff3 100644--- a/src/components/layout/public-session-menu.tsx+++ b/src/components/layout/public-session-menu.tsx@@ -14,6 +14,7 @@ import {} from "@/components/ui/dropdown-menu";import { authClient } from "@/lib/auth/client";import { cn } from "@/lib/cn";+import { getInitials } from "@/lib/initials";type PublicSessionMenuProps = {align?: "center" | "end" | "start";@@ -35,7 +36,10 @@ export function PublicSessionMenu({return <>{children}</>;}- const initials = getInitials(session.user.name);+ const initials = getInitials(session.user.name, {+ max: 2,+ singleWordLength: 2,+ });async function handleSignOut() {if (isSigningOut) {@@ -99,15 +103,3 @@ export function PublicSessionMenu({</DropdownMenu>);}--function getInitials(name: string) {- const trimmedName = name.trim();-- if (!trimmedName) {- return "";- }-- const [first = "", second = ""] = trimmedName.split(/\s+/, 2);-- return `${first[0] ?? ""}${second[0] ?? first[1] ?? ""}`.toUpperCase();-}diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsxindex 6d4c435..ed661a6 100644--- a/src/components/signing/signing-live-shell.tsx+++ b/src/components/signing/signing-live-shell.tsx@@ -53,6 +53,8 @@ import {isNumberEntry,NUMBER_ENTRY_MESSAGE,} from "@/lib/field-choices";+import { getInitials } from "@/lib/initials";+import { truncateToWholeCharacters } from "@/lib/text-truncate";const typedSignatureFont ='"Snell Roundhand", "Brush Script MT", "Segoe Script", cursive';@@ -94,14 +96,8 @@ export const declinedConfirmation = {const compactFieldHeightThreshold = 0.045;const compactFieldWidthThreshold = 0.12;-function getInitials(name: string): string {- return name- .split(/\s+/)- .filter(Boolean)- .map((part) => part[0])- .join("")- .slice(0, 4)- .toUpperCase();+function getSignerInitials(name: string): string {+ return getInitials(name, { max: 4 });}function getFieldFrame(field: SigningCurrentField | SigningVisibleField) {@@ -1178,7 +1174,7 @@ export function SigningLiveShell({<p className="section-eyebrow">Current signer</p><div className="mt-3 flex items-center gap-3"><span className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-(--accent-soft) text-[0.9375rem] font-bold text-(--accent-ink)">- {getInitials(record.signer.name)}+ {getSignerInitials(record.signer.name)}</span><div className="min-w-0"><p className="truncate text-[0.9375rem] font-bold text-(--fg)">@@ -1992,7 +1988,9 @@ function SignatureModal({return existingEntry.value;}- return fieldType === "initials" ? getInitials(signerName) : signerName;+ return fieldType === "initials"+ ? getSignerInitials(signerName)+ : signerName;});const drawPreviewMessage =drawnSignatureVersion === 0@@ -2008,7 +2006,7 @@ function SignatureModal({function handleTypedSignatureValueChange(value: string) {if (fieldType === "initials") {- setTypedSignatureValue(value.toUpperCase().slice(0, 4));+ setTypedSignatureValue(truncateToWholeCharacters(value.toUpperCase(), 4));return;}diff --git a/src/lib/initials.test.ts b/src/lib/initials.test.tsnew file mode 100644index 0000000..9d37a7b--- /dev/null+++ b/src/lib/initials.test.ts@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import { getInitials } from "./initials.ts";++function isWellFormed(value: string): boolean {+ return value === value.toWellFormed();+}++// The name from issue #115: the emoji is a word of its own.+test("an emoji word does not leave half an emoji in the initials", () => {+ const initials = getInitials("Robin Casey π", { max: 4 });++ assert.ok(isWellFormed(initials), JSON.stringify(initials));+ assert.equal(initials, "RC");+});++test("the control name from issue #115 still gives three initials", () => {+ assert.equal(getInitials("Robin Casey D", { max: 4 }), "RCD");+});++test("a word that starts with an emoji keeps the emoji whole", () => {+ for (const name of ["π", "π π", "π©π½βπ»"]) {+ const initials = getInitials(name, { max: 4 });++ assert.ok(isWellFormed(initials), JSON.stringify(initials));+ assert.ok(initials.length > 0);+ assert.ok(name.startsWith(initials), `${name} -> ${initials}`);+ }+});++test("a letter with a combining accent stays in one piece", () => {+ assert.equal(getInitials("eΜlodie Roy", { max: 2 }), "EΜR");+});++test("a lone surrogate in a stored name is never copied out", () => {+ const initials = getInitials("\ud83d Robin", { max: 4 });++ assert.ok(isWellFormed(initials), JSON.stringify(initials));+ assert.equal(initials, "R");+});++test("max and single-word length match each avatar", () => {+ assert.equal(getInitials("Ana Bea Cruz Dee Eve", { max: 4 }), "ABCD");+ assert.equal(getInitials("Ana Bea Cruz", { max: 2 }), "AB");+ assert.equal(getInitials("Robin", { max: 2 }), "R");+ assert.equal(getInitials("Robin", { max: 2, singleWordLength: 2 }), "RO");+ assert.equal(getInitials("Robin π", { max: 2, singleWordLength: 2 }), "RO");+ assert.equal(getInitials(" ", { max: 2 }), "");+});diff --git a/src/lib/initials.ts b/src/lib/initials.tsnew file mode 100644index 0000000..bf53ddc--- /dev/null+++ b/src/lib/initials.ts@@ -0,0 +1,46 @@+const graphemeSegmenter = new Intl.Segmenter(undefined, {+ granularity: "grapheme",+});++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;+ // For a one-word name, how many of its characters to use ("Robin" -> "RO").+ singleWordLength?: number;+};++// Builds the initials shown in a person's avatar from their name, one whole+// character per word. Taking part[0] of a word reads one UTF-16 code unit,+// which is half of an emoji: the server then renders U+FFFD while the browser+// keeps the lone surrogate, and React reports a hydration mismatch. Words that+// 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);++ if (words.length === 0) {+ return "";+ }++ const namedWords = words.filter((word) => startsWithLetterOrDigit.test(word));+ const sourceWords = namedWords.length > 0 ? namedWords : words.slice(0, 1);++ if (sourceWords.length === 1 && options.singleWordLength) {+ return wholeCharacters(sourceWords[0]!)+ .slice(0, Math.min(options.singleWordLength, options.max))+ .join("")+ .toUpperCase();+ }++ return sourceWords+ .slice(0, options.max)+ .map((word) => wholeCharacters(word)[0] ?? "")+ .join("")+ .toUpperCase();+}