Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(signing): render Type and Draw signature tabpanels (#240)
Kevin Rose387001370ecb
diff --git a/src/components/signing/signature-mode-tabs.test.ts b/src/components/signing/signature-mode-tabs.test.tsnew file mode 100644index 0000000..6838e8a--- /dev/null+++ b/src/components/signing/signature-mode-tabs.test.ts@@ -0,0 +1,212 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";++import {+ SignatureModeTabs,+ type SignatureMode,+} from "./signature-mode-tabs.ts";++type ParsedElement = {+ attributes: Record<string, string>;+ innerHtml: string;+ tag: string;+};++function parseAttributes(raw: string): Record<string, string> {+ const attributes: Record<string, string> = {};+ const attrPattern = /([a-zA-Z0-9_-]+)(?:="([^"]*)")?/g;++ for (const match of raw.matchAll(attrPattern)) {+ const [, name, value] = match;+ attributes[name] = value ?? "";+ }++ return attributes;+}++function findElementsByRole(html: string, role: string): ParsedElement[] {+ const results: ParsedElement[] = [];+ const openTagPattern = /<(button|div)\b([^>]*)>/g;++ for (const match of html.matchAll(openTagPattern)) {+ const [fullMatch, tag, rawAttrs] = match;+ const attributes = parseAttributes(rawAttrs);++ if (attributes.role !== role) {+ continue;+ }++ const startIndex = (match.index ?? 0) + fullMatch.length;+ const tagPattern = new RegExp(`<(/?)${tag}\\b[^>]*>`, "g");+ tagPattern.lastIndex = startIndex;++ let depth = 1;+ let endIndex = html.length;++ for (const innerMatch of html.matchAll(tagPattern)) {+ if ((innerMatch.index ?? 0) < startIndex) {+ continue;+ }++ depth += innerMatch[1] === "/" ? -1 : 1;++ if (depth === 0) {+ endIndex = innerMatch.index ?? html.length;+ break;+ }+ }++ results.push({+ attributes,+ innerHtml: html.slice(startIndex, endIndex),+ tag,+ });+ }++ return results;+}++function renderSignatureTabs(mode: SignatureMode, fieldType = "signature") {+ return renderToStaticMarkup(+ createElement(SignatureModeTabs, {+ drawnPanel: createElement(+ "div",+ null,+ createElement("canvas", { "aria-label": "Draw signature canvas" }),+ createElement("button", { type: "button" }, "Clear"),+ ),+ mode,+ onModeChange: () => undefined,+ typedPanel: createElement("input", {+ id: `signature-modal-${fieldType}`,+ name: `signature-modal-${fieldType}`,+ }),+ }),+ );+}++test("Type mode links both Type and Draw tabs to existing tabpanels and exposes only Type content", () => {+ const html = renderSignatureTabs("typed");+ const tablists = findElementsByRole(html, "tablist");+ const tabs = findElementsByRole(html, "tab");+ const panels = findElementsByRole(html, "tabpanel");++ assert.equal(tablists.length, 1);+ assert.equal(tabs.length, 2);+ assert.equal(panels.length, 2);++ const panelsById = new Map(+ panels.map((panel) => [panel.attributes.id, panel] as const),+ );+ const tabsByLabel = new Map(+ tabs.map((tab) => [tab.innerHtml.trim(), tab] as const),+ );++ for (const tab of tabs) {+ const tabId = tab.attributes.id;+ const controlsId = tab.attributes["aria-controls"];++ assert.ok(tabId, "tab must have an id");+ assert.ok(controlsId, "tab must have aria-controls");++ const panel = panelsById.get(controlsId);++ assert.ok(+ panel,+ `tab "${tab.innerHtml.trim()}" aria-controls="${controlsId}" must resolve to a tabpanel`,+ );+ assert.equal(+ panel.attributes["aria-labelledby"],+ tabId,+ "tabpanel aria-labelledby must point back to its tab id",+ );+ assert.equal(+ "tabindex" in panel.attributes,+ false,+ "tabpanel should not add an extra Tab stop before focusable controls",+ );+ }++ const typeTab = tabsByLabel.get("Type")!;+ const drawTab = tabsByLabel.get("Draw")!;+ const typePanel = panelsById.get(typeTab.attributes["aria-controls"])!;+ const drawPanel = panelsById.get(drawTab.attributes["aria-controls"])!;++ assert.equal(typeTab.attributes["aria-selected"], "true");+ assert.equal(drawTab.attributes["aria-selected"], "false");+ assert.equal("hidden" in typePanel.attributes, false);+ assert.equal("hidden" in drawPanel.attributes, true);+ assert.match(typePanel.innerHtml, /id="signature-modal-signature"/);+ assert.doesNotMatch(typePanel.innerHtml, /Draw signature canvas/);+ assert.equal(drawPanel.innerHtml, "");+});++test("Draw mode switches selection and keeps every tab aria-controls target resolved", () => {+ const html = renderSignatureTabs("drawn");+ const tabs = findElementsByRole(html, "tab");+ const panels = findElementsByRole(html, "tabpanel");++ assert.equal(tabs.length, 2);+ assert.equal(panels.length, 2);++ const panelsById = new Map(+ panels.map((panel) => [panel.attributes.id, panel] as const),+ );+ const tabsByLabel = new Map(+ tabs.map((tab) => [tab.innerHtml.trim(), tab] as const),+ );+ const typeTab = tabsByLabel.get("Type")!;+ const drawTab = tabsByLabel.get("Draw")!;+ const typePanel = panelsById.get(typeTab.attributes["aria-controls"])!;+ const drawPanel = panelsById.get(drawTab.attributes["aria-controls"])!;++ assert.ok(typePanel);+ assert.ok(drawPanel);+ assert.equal(typePanel.attributes["aria-labelledby"], typeTab.attributes.id);+ assert.equal(drawPanel.attributes["aria-labelledby"], drawTab.attributes.id);+ assert.equal(typeTab.attributes["aria-selected"], "false");+ assert.equal(drawTab.attributes["aria-selected"], "true");+ assert.equal("hidden" in typePanel.attributes, true);+ assert.equal("hidden" in drawPanel.attributes, false);+ assert.equal(typePanel.innerHtml, "");+ assert.match(drawPanel.innerHtml, /aria-label="Draw signature canvas"/);+ assert.match(drawPanel.innerHtml, />Clear</);+});++test("initials dialog mode tabs keep valid tabpanel linkage", () => {+ const html = renderSignatureTabs("typed", "initials");+ const tabs = findElementsByRole(html, "tab");+ const panels = findElementsByRole(html, "tabpanel");++ assert.equal(tabs.length, 2);+ assert.equal(panels.length, 2);++ const panelsById = new Map(+ panels.map((panel) => [panel.attributes.id, panel] as const),+ );++ for (const tab of tabs) {+ const panel = panelsById.get(tab.attributes["aria-controls"]);+ assert.ok(panel);+ assert.equal(panel.attributes["aria-labelledby"], tab.attributes.id);+ }++ assert.match(html, /id="signature-modal-initials"/);+});++test("signing live shell wires SignatureModeTabs with TabsContent", async () => {+ const source = await readFile(+ new URL("./signing-live-shell.tsx", import.meta.url),+ "utf8",+ );++ assert.match(+ source,+ /import\s*\{[^}]*TabsContent[^}]*\}\s*from\s*"@\/components\/ui\/tabs"/,+ );+ assert.match(source, /<SignatureModeTabs\b/);+ assert.match(source, /Content:\s*TabsContent/);+});diff --git a/src/components/signing/signature-mode-tabs.ts b/src/components/signing/signature-mode-tabs.tsnew file mode 100644index 0000000..e7fc4df--- /dev/null+++ b/src/components/signing/signature-mode-tabs.ts@@ -0,0 +1,101 @@+"use client";++import {+ createElement,+ type ComponentProps,+ type ComponentType,+ type ReactNode,+} from "react";+import { Tabs as TabsPrimitive } from "radix-ui";++export type SignatureMode = "drawn" | "typed";++export type SignatureModeTabsPrimitives = {+ Content: ComponentType<ComponentProps<typeof TabsPrimitive.Content>>;+ List: ComponentType<ComponentProps<typeof TabsPrimitive.List>>;+ Root: ComponentType<ComponentProps<typeof TabsPrimitive.Root>>;+ Trigger: ComponentType<ComponentProps<typeof TabsPrimitive.Trigger>>;+};++export type SignatureModeTabsProps = {+ drawnPanel: ReactNode;+ mode: SignatureMode;+ onModeChange: (mode: SignatureMode) => void;+ primitives?: SignatureModeTabsPrimitives;+ typedPanel: ReactNode;+};++const defaultPrimitives: SignatureModeTabsPrimitives = {+ Content: TabsPrimitive.Content,+ List: TabsPrimitive.List,+ Root: TabsPrimitive.Root,+ Trigger: TabsPrimitive.Trigger,+};++const triggerClassName =+ "segmented-item h-auto min-h-10 flex-1 data-active:bg-white data-active:text-(--fg) data-active:shadow-[0_1px_3px_rgba(28,29,43,0.12)] after:hidden";++export function SignatureModeTabs({+ drawnPanel,+ mode,+ onModeChange,+ primitives = defaultPrimitives,+ typedPanel,+}: SignatureModeTabsProps) {+ return createElement(+ primitives.Root,+ {+ className: "min-w-0 gap-5",+ onValueChange: (value: string) => {+ if (value === "typed" || value === "drawn") {+ onModeChange(value);+ }+ },+ value: mode,+ },+ createElement(+ primitives.List,+ {+ className:+ "segmented flex h-auto w-full p-1 group-data-horizontal/tabs:h-auto",+ },+ createElement(+ primitives.Trigger,+ { className: triggerClassName, value: "typed" },+ "Type",+ ),+ createElement(+ primitives.Trigger,+ { className: triggerClassName, value: "drawn" },+ "Draw",+ ),+ ),+ // Both tabpanels stay mounted in the DOM so every tab's aria-controls+ // target always resolves. The inactive panel is hidden and its contents+ // unmount so the drawing canvas re-seeds cleanly when revisited, and+ // omitting tabindex lets Tab move straight into the active panel's+ // focusable control.+ createElement(+ primitives.Content,+ {+ className: "min-w-0 space-y-4",+ forceMount: true,+ hidden: mode !== "typed",+ tabIndex: undefined,+ value: "typed",+ },+ mode === "typed" ? typedPanel : null,+ ),+ createElement(+ primitives.Content,+ {+ className: "well min-w-0 p-3",+ forceMount: true,+ hidden: mode !== "drawn",+ tabIndex: undefined,+ value: "drawn",+ },+ mode === "drawn" ? drawnPanel : null,+ ),+ );+}diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsxindex dad6ad4..6acefcd 100644--- a/src/components/signing/signing-live-shell.tsx+++ b/src/components/signing/signing-live-shell.tsx@@ -39,8 +39,12 @@ import {DialogTitle,} from "@/components/ui/dialog";import { Checkbox } from "@/components/ui/checkbox";-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Textarea } from "@/components/ui/textarea";+import {+ SignatureModeTabs,+ type SignatureModeTabsPrimitives,+} from "@/components/signing/signature-mode-tabs";import { SigningStateScreen } from "@/components/signing/signing-state-screen";import {type SigningCurrentField,@@ -2079,6 +2083,13 @@ function VisibleFieldStamp({ field }: { field: SigningVisibleField }) {);}+const signatureModeTabsPrimitives: SignatureModeTabsPrimitives = {+ Content: TabsContent,+ List: TabsList,+ Root: Tabs,+ Trigger: TabsTrigger,+};+function SignatureModal({existingEntry,drawnSignatureVersion,@@ -2147,87 +2158,72 @@ function SignatureModal({}onClose={onClose}>- <Tabs- className="gap-4"- onValueChange={(value) => onModeChange(value as "typed" | "drawn")}- value={signatureMode}- >- <TabsList className="segmented flex h-auto w-full p-1 group-data-horizontal/tabs:h-auto">- <TabsTrigger- className="segmented-item h-auto min-h-10 flex-1 data-active:bg-white data-active:text-(--fg) data-active:shadow-[0_1px_3px_rgba(28,29,43,0.12)] after:hidden"- value="typed"- >- Type- </TabsTrigger>- <TabsTrigger- className="segmented-item h-auto min-h-10 flex-1 data-active:bg-white data-active:text-(--fg) data-active:shadow-[0_1px_3px_rgba(28,29,43,0.12)] after:hidden"- value="drawn"- >- Draw- </TabsTrigger>- </TabsList>- </Tabs>-- {signatureMode === "typed" ? (- <div className="space-y-4">- <label className="grid gap-1.5">- <span className="text-[0.8125rem] font-semibold text-(--secondary)">- {fieldType === "initials" ? "Type initials" : "Type signature"}- </span>- <input- autoFocus- className="field-input"- id={`signature-modal-${fieldType}`}- maxLength={fieldType === "initials" ? 4 : 80}- name={`signature-modal-${fieldType}`}- onChange={(event) =>- handleTypedSignatureValueChange(event.target.value)- }- placeholder={typedPlaceholder}- value={typedSignatureValue}+ <SignatureModeTabs+ drawnPanel={+ <>+ <SignatureDrawCanvas+ emptyMessage={drawPreviewMessage}+ // The canvas unmounts while the Type tab is shown, so it is seeded+ // from the drawing that Apply would use, never a stale one.+ initialDataUrl={drawnSignatureDataUrl}+ key={drawnSignatureVersion}+ onChange={setDrawnSignatureDataUrl}/>- </label>-- <div className="well px-6 py-8 text-center">- <p- className={`text-[40px] leading-none sm:text-[52px] ${- normalizedTypedSignatureValue- ? "text-(--fg)"- : "text-(--placeholder)"- }`}- style={{ fontFamily: typedSignatureFont }}- >- {normalizedTypedSignatureValue || typedPlaceholder}- </p>- <p className="mt-4 text-xs font-medium text-(--tertiary)">- Rendered in signature style- </p>- </div>- </div>- ) : (- <div className="well p-3">- <SignatureDrawCanvas- emptyMessage={drawPreviewMessage}- // The canvas unmounts while the Type tab is shown, so it is seeded- // from the drawing that Apply would use, never a stale one.- initialDataUrl={drawnSignatureDataUrl}- key={drawnSignatureVersion}- onChange={setDrawnSignatureDataUrl}- />- <div className="mt-2 flex justify-end">- <ShellButton- className="min-h-10 px-4 text-sm"- onClick={() => {- setDrawnSignatureDataUrl(null);- onClearDrawnSignature();- }}- variant="ghost"- >- Clear- </ShellButton>- </div>- </div>- )}+ <div className="mt-2 flex justify-end">+ <ShellButton+ className="min-h-10 px-4 text-sm"+ onClick={() => {+ setDrawnSignatureDataUrl(null);+ onClearDrawnSignature();+ }}+ variant="ghost"+ >+ Clear+ </ShellButton>+ </div>+ </>+ }+ mode={signatureMode}+ onModeChange={onModeChange}+ primitives={signatureModeTabsPrimitives}+ typedPanel={+ <>+ <label className="grid gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ {fieldType === "initials" ? "Type initials" : "Type signature"}+ </span>+ <input+ autoFocus+ className="field-input"+ id={`signature-modal-${fieldType}`}+ maxLength={fieldType === "initials" ? 4 : 80}+ name={`signature-modal-${fieldType}`}+ onChange={(event) =>+ handleTypedSignatureValueChange(event.target.value)+ }+ placeholder={typedPlaceholder}+ value={typedSignatureValue}+ />+ </label>++ <div className="well px-6 py-8 text-center">+ <p+ className={`text-[40px] leading-none sm:text-[52px] ${+ normalizedTypedSignatureValue+ ? "text-(--fg)"+ : "text-(--placeholder)"+ }`}+ style={{ fontFamily: typedSignatureFont }}+ >+ {normalizedTypedSignatureValue || typedPlaceholder}+ </p>+ <p className="mt-4 text-xs font-medium text-(--tertiary)">+ Rendered in signature style+ </p>+ </div>+ </>+ }+ /><div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end"><ShellButton onClick={onClose} variant="secondary">