Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(mobile): toggle checklists without opening the keyboard
Elian Doranc353bcc23653
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 0770d6339e..364bb592a4 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -57,6 +57,7 @@ import {openContentEmbedMenu,refreshEmbeddedNote,setupImageOpening,+ setupTodoCheckboxTaps,watchContentEmbeds} from "./utils";@@ -85,6 +86,7 @@ export default function EditableText({const focusedAttachmentIdRef = useRef<string | undefined>(undefined);const editorRef = useRef<CKTextEditor>(null);const stopWatchingEmbedsRef = useRef<(() => void) | undefined>(undefined);+ const stopTodoCheckboxTapsRef = useRef<(() => void) | undefined>(undefined);const editorApiRef = useRef<CKEditorApi>(null);/** The open icon picker request and its balloon container, or `null` when none is open. */const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerOpts & { container: HTMLElement } | null>(null);@@ -418,7 +420,10 @@ export default function EditableText({});});- useEffect(() => () => stopWatchingEmbedsRef.current?.(), []);+ useEffect(() => () => {+ stopWatchingEmbedsRef.current?.();+ stopTodoCheckboxTapsRef.current?.();+ }, []);useTriliumEvent("entitiesReloaded", ({ loadResults }) => {const editor = editorRef.current;@@ -568,78 +573,6 @@ export default function EditableText({};}, []);- // Mobile-only: toggle todo-list checkboxes on the first tap and widen the- // hit area so finger taps don't have to land precisely on the ~16px box.- // Two problems are being solved:- // 1. iOS WKWebView doesn't dispatch `change` on the first tap inside a- // contenteditable that isn't focused — users have to tap twice.- // 2. The native checkbox is too small to hit reliably with a finger.- // We accept any tap whose point lands within ~14px of the checkbox's- // bounding box (roughly a 44px touch target, matching Apple HIG), flip- // the checkbox, and fire a synthetic change event that CKEditor's- // TodoCheckboxChangeObserver picks up.- useEffect(() => {- const container = containerRef.current;- if (!container || !isMobile()) return;-- const HIT_PAD = 14;- let tapped: HTMLInputElement | null = null;-- const findCheckboxFromTap = (e: TouchEvent): HTMLInputElement | null => {- const target = e.target as HTMLElement | null;- if (!target) return null;-- // Direct hit on the checkbox.- const direct = target.closest<HTMLInputElement>(- '.todo-list__label input[type="checkbox"]'- );- if (direct) return direct;-- // Near-miss: tap landed on the label or its surroundings. Accept- // if the touch point is within HIT_PAD of the checkbox rect.- const label = target.closest(".todo-list__label");- if (!label) return null;- const checkbox = label.querySelector<HTMLInputElement>(- 'input[type="checkbox"]'- );- if (!checkbox) return null;-- const touch = e.touches[0] ?? e.changedTouches[0];- if (!touch) return null;- const rect = checkbox.getBoundingClientRect();- if (- touch.clientX >= rect.left - HIT_PAD &&- touch.clientX <= rect.right + HIT_PAD &&- touch.clientY >= rect.top - HIT_PAD &&- touch.clientY <= rect.bottom + HIT_PAD- ) {- return checkbox;- }- return null;- };-- const onTouchStart = (e: TouchEvent) => {- tapped = findCheckboxFromTap(e);- };-- const onTouchEnd = (e: TouchEvent) => {- if (!tapped) return;- const checkbox = tapped;- tapped = null;- // Suppress the synthesised click so we don't toggle twice.- e.preventDefault();- checkbox.checked = !checkbox.checked;- checkbox.dispatchEvent(new Event("change", { bubbles: true }));- };-- container.addEventListener("touchstart", onTouchStart, { passive: true });- container.addEventListener("touchend", onTouchEnd, { passive: false });- return () => {- container.removeEventListener("touchstart", onTouchStart);- container.removeEventListener("touchend", onTouchEnd);- };- }, []);-return (<>{note && !!templates && <CKEditor@@ -670,6 +603,10 @@ export default function EditableText({containerRef.current,editor);+ stopTodoCheckboxTapsRef.current?.();+ stopTodoCheckboxTapsRef.current = isMobile()+ ? setupTodoCheckboxTaps(containerRef.current)+ : undefined;}editor.plugins.get("FileUploadEditing")diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex a93ba0de5e..eac765e9b0 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -55,6 +55,7 @@ import {loadEmbeddedNote,openContentEmbedMenu,refreshEmbeddedNote,+ setupTodoCheckboxTaps,watchContentEmbeds} from "./utils";@@ -544,3 +545,114 @@ describe("getAttachmentHref", () => {expect(await getAttachmentHref("att1")).toBeNull();});});++describe("setupTodoCheckboxTaps", () => {+ let container: HTMLDivElement;+ let cleanup: () => void;++ beforeEach(() => {+ // Two items, their 16px checkboxes in the gutter of the list, 24px apart.+ container = document.createElement("div");+ container.innerHTML = `+ <ul class="todo-list">+ <li><span class="todo-list__label"><span contenteditable="false"><input type="checkbox"></span></span>First</li>+ <li><span class="todo-list__label"><span contenteditable="false"><input type="checkbox"></span></span>Second</li>+ </ul>`;+ document.body.appendChild(container);+ for (const [ index, checkbox ] of checkboxes().entries()) {+ const top = 100 + index * 24;+ vi.spyOn(checkbox, "getBoundingClientRect").mockReturnValue(+ { left: 15, right: 31, top, bottom: top + 16, width: 16, height: 16 } as DOMRect);+ }+ cleanup = setupTodoCheckboxTaps(container);+ });++ afterEach(() => {+ cleanup();+ container.remove();+ document.getElementById("root-widget")?.remove();+ });++ function checkboxes() {+ return [ ...container.querySelectorAll<HTMLInputElement>("input[type=checkbox]") ];+ }++ function touch(target: Element, type: string, clientX: number, clientY: number) {+ const event = new Event(type, { bubbles: true, cancelable: true });+ const point = [ { clientX, clientY } ];+ Object.defineProperty(event, "touches", { value: type === "touchend" ? [] : point });+ Object.defineProperty(event, "changedTouches", { value: point });+ target.dispatchEvent(event);+ return event;+ }++ function tap(target: Element, clientX: number, clientY: number) {+ const start = touch(target, "touchstart", clientX, clientY);+ const end = touch(target, "touchend", clientX, clientY);+ return { start, end };+ }++ it("toggles the nearest checkbox, cancelling the touch so the editor does not take the focus", () => {+ const list = container.querySelector("ul");+ expect(list).not.toBeNull();+ if (!list) return;+ const onChange = vi.fn();+ container.addEventListener("change", onChange);+ const [ first, second ] = checkboxes();++ const direct = tap(first, 23, 108);+ expect(first.checked).toBe(true);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(direct.start.defaultPrevented).toBe(true);+ expect(direct.end.defaultPrevented).toBe(true);++ // 6px left of the first box, outside every label.+ const nearMiss = tap(list, 9, 108);+ expect(first.checked).toBe(false);+ expect(second.checked).toBe(false);+ expect(nearMiss.start.defaultPrevented).toBe(true);++ // Between the rows, closer to the second box.+ tap(list, 23, 122);+ expect(first.checked).toBe(false);+ expect(second.checked).toBe(true);+ });++ it("blurs a focused editor whose keyboard is closed, so the toggle does not bring it back", () => {+ const editable = document.createElement("div");+ editable.tabIndex = 0;+ container.appendChild(editable);+ const root = document.createElement("div");+ root.id = "root-widget";+ document.body.appendChild(root);+ const [ first ] = checkboxes();++ root.classList.add("virtual-keyboard-opened");+ editable.focus();+ tap(first, 23, 108);+ expect(first.checked).toBe(true);+ expect(document.activeElement).toBe(editable);++ root.classList.remove("virtual-keyboard-opened");+ tap(first, 23, 108);+ expect(first.checked).toBe(false);+ expect(document.activeElement).not.toBe(editable);+ });++ it("leaves taps away from a checkbox and drags alone", () => {+ const [ first ] = checkboxes();+ const text = container.querySelector("li");+ expect(text).not.toBeNull();+ if (!text) return;++ const away = tap(text, 120, 108);+ expect(first.checked).toBe(false);+ expect(away.start.defaultPrevented).toBe(false);+ expect(away.end.defaultPrevented).toBe(false);++ touch(first, "touchstart", 23, 108);+ touch(first, "touchmove", 23, 140);+ touch(first, "touchend", 23, 140);+ expect(first.checked).toBe(false);+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex df294d5e7e..c393f5bbc3 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -354,6 +354,89 @@ export function setupImageOpening(container: HTMLDivElement, singleClickOpens: b});}+/**+ * Toggles a to-do checkbox on a tap within `TODO_CHECKBOX_HIT_PAD` of it, about a 44px target.+ * The touch is cancelled from `touchstart` on, as the browser focuses the editor before `touchend`+ * and so opens the keyboard. The iOS WebView also dispatches no `change` on a first tap into an+ * unfocused editor. The synthetic `change` reaches CKEditor's `TodoCheckboxChangeObserver`.+ */+export function setupTodoCheckboxTaps(container: HTMLElement) {+ let tapped: HTMLInputElement | null = null;+ let startX = 0;+ let startY = 0;++ const onTouchStart = (e: TouchEvent) => {+ const touch = e.touches[0];+ const target = e.target instanceof Element ? e.target : null;+ // The checkbox sits in the list's gutter, outside its label and item, so the tap is+ // matched by position rather than by its target.+ tapped = touch && e.touches.length === 1 && target?.closest(".todo-list")+ ? findTodoCheckboxAt(container, touch.clientX, touch.clientY)+ : null;+ startX = touch?.clientX ?? 0;+ startY = touch?.clientY ?? 0;+ if (tapped) {+ e.preventDefault();+ }+ };++ const onTouchMove = (e: TouchEvent) => {+ const touch = e.touches[0];+ if (touch && Math.hypot(touch.clientX - startX, touch.clientY - startY) > TAP_SLOP) {+ tapped = null;+ }+ };++ const onTouchEnd = (e: TouchEvent) => {+ if (!tapped) return;+ const checkbox = tapped;+ tapped = null;+ e.preventDefault();+ // The system back gesture closes the keyboard but leaves the editor focused, and the+ // browser opens the keyboard again as the toggle re-renders the focused editor.+ const active = document.activeElement;+ const isKeyboardOpen = document.getElementById("root-widget")+ ?.classList.contains("virtual-keyboard-opened");+ if (active instanceof HTMLElement && container.contains(active) && !isKeyboardOpen) {+ active.blur();+ }+ checkbox.checked = !checkbox.checked;+ checkbox.dispatchEvent(new Event("change", { bubbles: true }));+ };++ container.addEventListener("touchstart", onTouchStart, { passive: false });+ container.addEventListener("touchmove", onTouchMove, { passive: true });+ container.addEventListener("touchend", onTouchEnd, { passive: false });+ return () => {+ container.removeEventListener("touchstart", onTouchStart);+ container.removeEventListener("touchmove", onTouchMove);+ container.removeEventListener("touchend", onTouchEnd);+ };+}++const TODO_CHECKBOX_HIT_PAD = 14;+/** How far a touch can move and still count as a tap rather than a scroll. */+const TAP_SLOP = 10;++/** The to-do checkbox nearest to the point, if it lies within `TODO_CHECKBOX_HIT_PAD` of it. */+function findTodoCheckboxAt(container: HTMLElement, x: number, y: number) {+ let nearest: HTMLInputElement | null = null;+ let nearestDistance = Infinity;+ const checkboxes = container.querySelectorAll<HTMLInputElement>(+ '.todo-list__label input[type="checkbox"]');+ for (const checkbox of checkboxes) {+ const rect = checkbox.getBoundingClientRect();+ const dx = Math.max(rect.left - x, 0, x - rect.right);+ const dy = Math.max(rect.top - y, 0, y - rect.bottom);+ const distance = Math.hypot(dx, dy);+ if (dx <= TODO_CHECKBOX_HIT_PAD && dy <= TODO_CHECKBOX_HIT_PAD && distance < nearestDistance) {+ nearest = checkbox;+ nearestDistance = distance;+ }+ }+ return nearest;+}+async function openImageInCurrentTab($img: JQuery<HTMLElement>) {const parsedImage = await parseFromImage($img);