Skip to content

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

TypeScript

fix(prepare): scope Backspace/Delete field removal to canvas focus (#239)

Kevin Rose244de1ef9134
diff --git a/src/components/envelopes/interactive-placed-field.tsx b/src/components/envelopes/interactive-placed-field.tsx
index 43705ca..d33b22b 100644
--- a/src/components/envelopes/interactive-placed-field.tsx
+++ b/src/components/envelopes/interactive-placed-field.tsx
@@ -6,6 +6,7 @@ import {
type PointerEvent as ReactPointerEvent,
} from "react";
+import { releaseStaleFocusForCanvas } from "@/lib/prepare-shortcuts";
import { type FieldResizeHandle } from "@/lib/utils/pdf-coords";
const dragThresholdPx = 4;
@@ -117,6 +118,11 @@ export function InteractivePlacedField({
event.preventDefault();
event.stopPropagation();
+ const placedField = event.currentTarget.closest(
+ "[data-placed-field='true']",
+ );
+
+ releaseStaleFocusForCanvas(document.activeElement, placedField);
onSelect();
if (typeof event.currentTarget.setPointerCapture === "function") {
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsx
index 41e0d9b..5bd0de0 100644
--- a/src/components/envelopes/prepare-live-shell.tsx
+++ b/src/components/envelopes/prepare-live-shell.tsx
@@ -37,6 +37,10 @@ import {
parseOptionLines,
} from "@/lib/field-choices";
import { getInitials } from "@/lib/initials";
+import {
+ releaseStaleFocusForCanvas,
+ shouldDeleteSelectedFieldOnKeydown,
+} from "@/lib/prepare-shortcuts";
import { toWellFormedText } from "@/lib/whole-characters";
import {
type FieldPlacement,
@@ -311,18 +315,6 @@ function roundNormalized(value: number) {
return Math.round(value * 1_000_000) / 1_000_000;
}
-function isTextEntryTarget(target: EventTarget | null) {
- if (
- target instanceof HTMLInputElement ||
- target instanceof HTMLTextAreaElement ||
- target instanceof HTMLSelectElement
- ) {
- return true;
- }
-
- return target instanceof HTMLElement && target.isContentEditable;
-}
-
function clearSelectedFieldFromViewportClick(
event: ReactPointerEvent<HTMLElement>,
armedTool: PrepareFieldType | null,
@@ -691,19 +683,20 @@ function PrepareLiveShellContent({
const fieldId = selectedFieldId;
function handleDeleteFieldKeydown(event: KeyboardEvent) {
- if (event.defaultPrevented || isFieldInteracting) {
- return;
- }
-
- if (event.key !== "Backspace" && event.key !== "Delete") {
- return;
- }
-
- if (event.altKey || event.ctrlKey || event.metaKey) {
- return;
- }
-
- if (isTextEntryTarget(event.target)) {
+ if (
+ !shouldDeleteSelectedFieldOnKeydown({
+ activeElement: document.activeElement,
+ altKey: event.altKey,
+ ctrlKey: event.ctrlKey,
+ defaultPrevented: event.defaultPrevented,
+ isComposing: event.isComposing,
+ isDialogOpen: isMobileToolsOpen,
+ isFieldInteracting,
+ key: event.key,
+ metaKey: event.metaKey,
+ target: event.target,
+ })
+ ) {
return;
}
@@ -716,7 +709,7 @@ function PrepareLiveShellContent({
return () => {
window.removeEventListener("keydown", handleDeleteFieldKeydown);
};
- }, [isFieldInteracting, selectedFieldId]);
+ }, [isFieldInteracting, isMobileToolsOpen, selectedFieldId]);
useEffect(() => {
if (zoomLevel > DEFAULT_DOCUMENT_ZOOM_LEVEL) {
@@ -1959,6 +1952,7 @@ function placeField(
type: tool.type,
};
+ releaseStaleFocusForCanvas(document.activeElement);
setFields((currentFields) => [...currentFields, nextField]);
setSelectedFieldId(nextField.id);
setArmedTool(null);
diff --git a/src/lib/prepare-shortcuts.test.ts b/src/lib/prepare-shortcuts.test.ts
new file mode 100644
index 0000000..a4fb9e0
--- /dev/null
+++ b/src/lib/prepare-shortcuts.test.ts
@@ -0,0 +1,476 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ releaseStaleFocusForCanvas,
+ shouldDeleteSelectedFieldOnKeydown,
+ type ShortcutTargetElement,
+} from "./prepare-shortcuts.ts";
+
+type MockElement = ShortcutTargetElement & {
+ attributes: Record<string, string>;
+ blur: () => void;
+ blurred: boolean;
+ contains: (node: MockElement | null) => boolean;
+ parent: MockElement | null;
+};
+
+function matchesSingleSelector(
+ element: MockElement,
+ rawSelector: string,
+): boolean {
+ const selector = rawSelector.trim();
+
+ if (!selector) {
+ return false;
+ }
+
+ const attrMatch = /^\[([a-zA-Z0-9_-]+)(?:=['"]([^'"]*)['"])?\]$/.exec(
+ selector,
+ );
+
+ if (attrMatch) {
+ const [, attrName, expectedValue] = attrMatch;
+ const actualValue = element.getAttribute(attrName);
+
+ if (actualValue === null) {
+ return false;
+ }
+
+ return expectedValue === undefined || actualValue === expectedValue;
+ }
+
+ return element.tagName.toLowerCase() === selector.toLowerCase();
+}
+
+function createElement(
+ tagName: string,
+ options: {
+ attributes?: Record<string, string>;
+ isContentEditable?: boolean;
+ parent?: MockElement | null;
+ } = {},
+): MockElement {
+ const attributes = options.attributes ?? {};
+ const element: MockElement = {
+ attributes,
+ blur() {
+ element.blurred = true;
+ },
+ blurred: false,
+ closest(selectorList: string): ShortcutTargetElement | null {
+ const selectors = selectorList.split(",").map((part) => part.trim());
+ let current: MockElement | null = element;
+
+ while (current !== null) {
+ if (
+ selectors.some((selector) =>
+ matchesSingleSelector(current!, selector),
+ )
+ ) {
+ return current;
+ }
+
+ current = current.parent;
+ }
+
+ return null;
+ },
+ contains(node: MockElement | null): boolean {
+ let current = node;
+
+ while (current !== null) {
+ if (current === element) {
+ return true;
+ }
+
+ current = current.parent;
+ }
+
+ return false;
+ },
+ getAttribute(name: string): string | null {
+ return Object.prototype.hasOwnProperty.call(attributes, name)
+ ? attributes[name]
+ : null;
+ },
+ isContentEditable: options.isContentEditable ?? false,
+ parent: options.parent ?? null,
+ tagName: tagName.toUpperCase(),
+ };
+
+ return element;
+}
+
+test("Backspace and Delete do not delete the selected field from Field settings controls", () => {
+ const body = createElement("body");
+ const fieldSettings = createElement("section", {
+ attributes: { "aria-label": "Field settings", role: "region" },
+ parent: body,
+ });
+ const requiredButton = createElement("button", {
+ attributes: { "aria-pressed": "true", type: "button" },
+ parent: fieldSettings,
+ });
+ const optionalButton = createElement("button", {
+ attributes: { "aria-pressed": "false", type: "button" },
+ parent: fieldSettings,
+ });
+ const assignSignerButton = createElement("button", {
+ attributes: { "aria-pressed": "true", type: "button" },
+ parent: fieldSettings,
+ });
+ const deleteButton = createElement("button", {
+ attributes: { type: "button" },
+ parent: fieldSettings,
+ });
+ const choicesTextarea = createElement("textarea", {
+ parent: fieldSettings,
+ });
+ const radioLabelInput = createElement("input", {
+ parent: fieldSettings,
+ });
+ const customSwitch = createElement("div", {
+ attributes: { role: "switch" },
+ parent: fieldSettings,
+ });
+ const customCheckbox = createElement("div", {
+ attributes: { role: "checkbox" },
+ parent: fieldSettings,
+ });
+ const fieldSettingsHeading = createElement("p", {
+ parent: fieldSettings,
+ });
+
+ for (const key of ["Backspace", "Delete"] as const) {
+ for (const target of [
+ requiredButton,
+ optionalButton,
+ assignSignerButton,
+ deleteButton,
+ choicesTextarea,
+ radioLabelInput,
+ customSwitch,
+ customCheckbox,
+ fieldSettingsHeading,
+ ]) {
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: target,
+ key,
+ target,
+ }),
+ false,
+ `${key} should not delete when focused on ${target.tagName}`,
+ );
+ }
+ }
+});
+
+test("Backspace and Delete do not delete from toolbars, header navigation, dialogs, or editable elements", () => {
+ const body = createElement("body");
+ const header = createElement("header", { parent: body });
+ const backLink = createElement("a", {
+ attributes: { href: "/envelopes/1/signers" },
+ parent: header,
+ });
+ const nextButton = createElement("button", { parent: header });
+
+ const sidebar = createElement("aside", { parent: body });
+ const fieldToolButton = createElement("button", {
+ attributes: { "aria-pressed": "false" },
+ parent: sidebar,
+ });
+ const fieldToolIcon = createElement("svg", { parent: fieldToolButton });
+ const signerCardButton = createElement("button", {
+ attributes: { "aria-pressed": "true" },
+ parent: sidebar,
+ });
+
+ const signerSelect = createElement("select", { parent: body });
+ const contentEditableDiv = createElement("div", {
+ attributes: { contenteditable: "true" },
+ isContentEditable: true,
+ parent: body,
+ });
+ const contentEditableChild = createElement("span", {
+ parent: contentEditableDiv,
+ });
+
+ const dialog = createElement("div", {
+ attributes: { "aria-modal": "true", role: "dialog" },
+ parent: body,
+ });
+ const dialogButton = createElement("button", { parent: dialog });
+ const dialogSurface = createElement("div", { parent: dialog });
+
+ for (const target of [
+ backLink,
+ nextButton,
+ fieldToolButton,
+ fieldToolIcon,
+ signerCardButton,
+ signerSelect,
+ contentEditableDiv,
+ contentEditableChild,
+ dialogButton,
+ dialogSurface,
+ ]) {
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: target,
+ key: "Backspace",
+ target,
+ }),
+ false,
+ );
+ }
+
+ // Even if focus falls on body while a modal dialog is open, do not delete.
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: body,
+ isDialogOpen: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+});
+
+test("Backspace and Delete delete the selected field only when focus is on the canvas or the selected placed field", () => {
+ const html = createElement("html");
+ const body = createElement("body", { parent: html });
+ const paperGrid = createElement("div", {
+ attributes: { "data-paper-grid": "" },
+ parent: body,
+ });
+ const viewport = createElement("div", {
+ attributes: { "data-field-viewport": "" },
+ parent: paperGrid,
+ });
+ const pdfCanvas = createElement("canvas", { parent: viewport });
+ const armedPlaceOverlay = createElement("button", {
+ attributes: { "aria-label": "Place Text on page 1", type: "button" },
+ parent: viewport,
+ });
+ const selectedField = createElement("div", {
+ attributes: {
+ "aria-pressed": "true",
+ "data-placed-field": "true",
+ role: "button",
+ },
+ parent: viewport,
+ });
+ const selectedFieldLabel = createElement("span", { parent: selectedField });
+ const selectedFieldResizeHandle = createElement("button", {
+ attributes: { type: "button" },
+ parent: selectedField,
+ });
+ const unselectedField = createElement("div", {
+ attributes: {
+ "aria-pressed": "false",
+ "data-placed-field": "true",
+ role: "button",
+ },
+ parent: viewport,
+ });
+
+ for (const key of ["Backspace", "Delete"] as const) {
+ for (const target of [
+ html,
+ body,
+ paperGrid,
+ viewport,
+ pdfCanvas,
+ selectedField,
+ selectedFieldLabel,
+ selectedFieldResizeHandle,
+ ]) {
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: target,
+ key,
+ target,
+ }),
+ true,
+ `${key} should delete when focused on ${target.tagName}`,
+ );
+ }
+
+ // Focus on another, unselected placed field or the armed placement overlay must not delete.
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: unselectedField,
+ key,
+ target: unselectedField,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: armedPlaceOverlay,
+ key,
+ target: armedPlaceOverlay,
+ }),
+ false,
+ );
+ }
+});
+
+test("guards reject non-delete keys, modifiers, composing, drag interactions, and mismatched focus", () => {
+ const body = createElement("body");
+ const requiredButton = createElement("button", {
+ attributes: { "aria-pressed": "true" },
+ parent: body,
+ });
+
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({ key: " ", target: body }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({ key: "Enter", target: body }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ altKey: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ ctrlKey: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ metaKey: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ defaultPrevented: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ isComposing: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ isFieldInteracting: true,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({ key: "Backspace", target: null }),
+ false,
+ );
+ // Synthetic event dispatched on window/body while focus is still on Required.
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: requiredButton,
+ key: "Backspace",
+ target: {},
+ }),
+ false,
+ );
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: requiredButton,
+ key: "Backspace",
+ target: body,
+ }),
+ false,
+ );
+ // Synthetic event dispatched on window while focus is on body.
+ assert.equal(
+ shouldDeleteSelectedFieldOnKeydown({
+ activeElement: body,
+ key: "Backspace",
+ target: {},
+ }),
+ true,
+ );
+});
+
+test("releaseStaleFocusForCanvas clears focus from prior fields, inspector controls, and sidebar tools", () => {
+ const html = createElement("html");
+ const body = createElement("body", { parent: html });
+ const viewport = createElement("div", {
+ attributes: { "data-field-viewport": "" },
+ parent: body,
+ });
+ const fieldA = createElement("div", {
+ attributes: {
+ "aria-pressed": "false",
+ "data-placed-field": "true",
+ role: "button",
+ },
+ parent: viewport,
+ });
+ const fieldB = createElement("div", {
+ attributes: {
+ "aria-pressed": "true",
+ "data-placed-field": "true",
+ role: "button",
+ },
+ parent: viewport,
+ });
+ const fieldBHandle = createElement("button", {
+ attributes: { type: "button" },
+ parent: fieldB,
+ });
+ const requiredButton = createElement("button", {
+ attributes: { "aria-pressed": "true", type: "button" },
+ parent: body,
+ });
+ const sidebarToolButton = createElement("button", {
+ attributes: { "aria-pressed": "true", type: "button" },
+ parent: body,
+ });
+
+ // Clicking Field B while Field A holds keyboard focus blurs Field A.
+ assert.equal(releaseStaleFocusForCanvas(fieldA, fieldB), true);
+ assert.equal(fieldA.blurred, true);
+
+ // Clicking Field B while focus is already on Field B (or its resize handle) keeps focus.
+ assert.equal(releaseStaleFocusForCanvas(fieldB, fieldB), false);
+ assert.equal(fieldB.blurred, false);
+ assert.equal(releaseStaleFocusForCanvas(fieldBHandle, fieldB), false);
+ assert.equal(fieldBHandle.blurred, false);
+
+ // Clicking a placed field while focus is on Required in Field settings blurs Required.
+ assert.equal(releaseStaleFocusForCanvas(requiredButton, fieldB), true);
+ assert.equal(requiredButton.blurred, true);
+
+ // Placing a field while a sidebar tool button retains focus (Safari/Firefox) blurs it.
+ assert.equal(releaseStaleFocusForCanvas(sidebarToolButton), true);
+ assert.equal(sidebarToolButton.blurred, true);
+
+ // Never blurs body, html, or null.
+ assert.equal(releaseStaleFocusForCanvas(body, fieldB), false);
+ assert.equal(body.blurred, false);
+ assert.equal(releaseStaleFocusForCanvas(html), false);
+ assert.equal(html.blurred, false);
+ assert.equal(releaseStaleFocusForCanvas(null, fieldB), false);
+});
diff --git a/src/lib/prepare-shortcuts.ts b/src/lib/prepare-shortcuts.ts
new file mode 100644
index 0000000..4917d51
--- /dev/null
+++ b/src/lib/prepare-shortcuts.ts
@@ -0,0 +1,211 @@
+// Keyboard shortcuts on the Prepare page. Backspace and Delete only remove the
+// selected field when focus is on the document canvas itself (the page, the
+// viewport, or the selected placed field), never while focus is on a control
+// in Field settings, a toolbar, header navigation, or a dialog.
+
+export type ShortcutTargetElement = {
+ closest: (selector: string) => ShortcutTargetElement | null;
+ getAttribute: (name: string) => string | null;
+ isContentEditable?: boolean;
+ tagName: string;
+};
+
+export type CanvasFocusContainer<TNode> = {
+ contains: (node: TNode) => boolean;
+};
+
+type BlurTargetElement = {
+ blur: () => void;
+ tagName: string;
+};
+
+export type DeleteFieldKeydownContext = {
+ activeElement?: unknown;
+ altKey?: boolean;
+ ctrlKey?: boolean;
+ defaultPrevented?: boolean;
+ isComposing?: boolean;
+ isDialogOpen?: boolean;
+ isFieldInteracting?: boolean;
+ key: string;
+ metaKey?: boolean;
+ target: unknown;
+};
+
+const TEXT_ENTRY_SELECTOR = [
+ "input",
+ "textarea",
+ "select",
+ "[contenteditable='']",
+ "[contenteditable='true']",
+ "[contenteditable='plaintext-only']",
+ "[role='textbox']",
+ "[role='searchbox']",
+ "[role='combobox']",
+ "[role='spinbutton']",
+].join(", ");
+
+const DIALOG_SELECTOR =
+ "[role='dialog'], [role='alertdialog'], [aria-modal='true']";
+
+const PLACED_FIELD_SELECTOR = "[data-placed-field='true']";
+const CANVAS_CONTAINER_SELECTOR = "[data-field-viewport], [data-paper-grid]";
+
+const NON_CANVAS_INTERACTIVE_SELECTOR = [
+ "a",
+ "button",
+ "input",
+ "select",
+ "summary",
+ "textarea",
+ "[contenteditable='']",
+ "[contenteditable='true']",
+ "[contenteditable='plaintext-only']",
+ "[role='button']",
+ "[role='checkbox']",
+ "[role='combobox']",
+ "[role='link']",
+ "[role='listbox']",
+ "[role='menu']",
+ "[role='menuitem']",
+ "[role='menuitemcheckbox']",
+ "[role='menuitemradio']",
+ "[role='option']",
+ "[role='radio']",
+ "[role='searchbox']",
+ "[role='slider']",
+ "[role='spinbutton']",
+ "[role='switch']",
+ "[role='tab']",
+ "[role='textbox']",
+].join(", ");
+
+function asTargetElement(value: unknown): ShortcutTargetElement | null {
+ if (!value || typeof value !== "object") {
+ return null;
+ }
+
+ const candidate = value as Partial<ShortcutTargetElement>;
+
+ if (
+ typeof candidate.tagName !== "string" ||
+ typeof candidate.closest !== "function" ||
+ typeof candidate.getAttribute !== "function"
+ ) {
+ return null;
+ }
+
+ return candidate as ShortcutTargetElement;
+}
+
+/**
+ * True when an element represents the document canvas or the currently
+ * selected placed field, so Backspace/Delete may safely remove that field.
+ */
+export function isCanvasDeleteTarget(element: ShortcutTargetElement): boolean {
+ if (
+ element.isContentEditable ||
+ element.closest(TEXT_ENTRY_SELECTOR) !== null ||
+ element.closest(DIALOG_SELECTOR) !== null
+ ) {
+ return false;
+ }
+
+ const tagName = element.tagName.toUpperCase();
+
+ if (tagName === "BODY" || tagName === "HTML") {
+ return true;
+ }
+
+ const placedField = element.closest(PLACED_FIELD_SELECTOR);
+
+ if (placedField !== null) {
+ return placedField.getAttribute("aria-pressed") === "true";
+ }
+
+ if (element.closest(CANVAS_CONTAINER_SELECTOR) !== null) {
+ return element.closest(NON_CANVAS_INTERACTIVE_SELECTOR) === null;
+ }
+
+ return false;
+}
+
+/**
+ * True when a window-level keydown event should delete the currently selected
+ * field on the Prepare page.
+ */
+export function shouldDeleteSelectedFieldOnKeydown(
+ context: DeleteFieldKeydownContext,
+): boolean {
+ if (
+ context.defaultPrevented ||
+ context.isComposing ||
+ context.isFieldInteracting ||
+ context.isDialogOpen
+ ) {
+ return false;
+ }
+
+ if (context.key !== "Backspace" && context.key !== "Delete") {
+ return false;
+ }
+
+ if (context.altKey || context.ctrlKey || context.metaKey) {
+ return false;
+ }
+
+ const targetElement = asTargetElement(context.target);
+ const activeElement = asTargetElement(context.activeElement);
+
+ if (targetElement === null) {
+ return activeElement !== null && isCanvasDeleteTarget(activeElement);
+ }
+
+ if (!isCanvasDeleteTarget(targetElement)) {
+ return false;
+ }
+
+ if (activeElement !== null && activeElement !== targetElement) {
+ return isCanvasDeleteTarget(activeElement);
+ }
+
+ return true;
+}
+
+/**
+ * Clears focus from a non-body element unless it is already inside `keepWithin`.
+ * Used when clicking or placing a field on the document canvas so browsers that
+ * do not move focus on prevented pointerdowns or button clicks (such as Safari
+ * and Firefox) do not leave focus stuck on a sidebar tool, inspector control,
+ * or previously focused field.
+ */
+export function releaseStaleFocusForCanvas<TNode>(
+ activeElement: TNode,
+ keepWithin?: CanvasFocusContainer<TNode> | null,
+): boolean {
+ if (!activeElement || typeof activeElement !== "object") {
+ return false;
+ }
+
+ const candidate = activeElement as Partial<BlurTargetElement>;
+
+ if (
+ typeof candidate.tagName !== "string" ||
+ typeof candidate.blur !== "function"
+ ) {
+ return false;
+ }
+
+ const tagName = candidate.tagName.toUpperCase();
+
+ if (tagName === "BODY" || tagName === "HTML") {
+ return false;
+ }
+
+ if (keepWithin && keepWithin.contains(activeElement)) {
+ return false;
+ }
+
+ candidate.blur();
+ return true;
+}