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/text): keep the toolbar above the keyboard in Safari
Elian Doran63b41282053e
diff --git a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsxindex 2b813d5190..3b50007565 100644--- a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx+++ b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx@@ -1,4 +1,6 @@+import { render } from "preact";import { act } from "preact/test-utils";+import { useRef } from "preact/hooks";import { afterEach, describe, expect, it, vi } from "vitest";import { renderInto } from "../../test/render";@@ -7,8 +9,12 @@ vi.mock("../react/hooks", async (importOriginal) => ({...(await importOriginal<typeof import("../react/hooks")>()),useStaticTooltip: vi.fn()}));+vi.mock("../../services/utils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../services/utils")>()),+ isIOS: () => true+}));-import HideKeyboardButton from "./hide_keyboard_button";+import HideKeyboardButton, { usePositioningOniOS } from "./hide_keyboard_button";describe("HideKeyboardButton", () => {let input: HTMLInputElement | undefined;@@ -36,3 +42,109 @@ describe("HideKeyboardButton", () => {expect(document.activeElement).not.toBe(input);});});++describe("usePositioningOniOS", () => {+ const originalViewport = Object.getOwnPropertyDescriptor(window, "visualViewport");+ const originalInnerHeight = Object.getOwnPropertyDescriptor(window, "innerHeight");++ afterEach(() => {+ for (const [ key, descriptor ] of [+ [ "visualViewport", originalViewport ], [ "innerHeight", originalInnerHeight ]+ ] as const) {+ if (descriptor) {+ Object.defineProperty(window, key, descriptor);+ } else {+ Reflect.deleteProperty(window, key);+ }+ }+ });++ it("lifts a fixed element above the keyboard, also when Safari pans the viewport", () => {+ const viewport = fakeViewport(800);+ const { element, unmount } = renderPositioned(false);++ act(() => viewport.set({ height: 500, offsetTop: 0 }, "resize"));+ expect(element().style.bottom).toBe("300px");++ // Safari pans the visual viewport towards the caret without resizing it.+ act(() => viewport.set({ height: 500, offsetTop: 120 }, "scroll"));+ expect(element().style.bottom).toBe("180px");++ act(() => viewport.set({ height: 800, offsetTop: 0 }, "resize"));+ expect(element().style.bottom).toBe("");++ unmount();+ act(() => viewport.set({ height: 500, offsetTop: 0 }, "resize"));+ expect(viewport.listenerCount()).toBe(0);+ });++ it("lifts an element by what the keyboard covers of its anchor, not of the window", () => {+ const viewport = fakeViewport(800);+ const { element, anchor } = renderPositioned(true);++ // The anchor ends mid-screen, as the top note split does, above the keyboard.+ anchor().getBoundingClientRect = () => new DOMRect(0, 0, 400, 400);+ act(() => viewport.set({ height: 500, offsetTop: 0 }, "resize"));+ expect(element().style.bottom).toBe("");++ // The anchor ends 53px above the window's bottom, as above a bottom bar left in place.+ anchor().getBoundingClientRect = () => new DOMRect(0, 0, 400, 747);+ act(() => viewport.set({ height: 500, offsetTop: 0 }, "resize"));+ expect(element().style.bottom).toBe("247px");+ });+});++function fakeViewport(innerHeight: number) {+ const target = new EventTarget();+ let listeners = 0;+ const viewport = Object.assign(target, { height: innerHeight, offsetTop: 0 });+ const add = target.addEventListener.bind(target);+ const remove = target.removeEventListener.bind(target);+ viewport.addEventListener = (...args: Parameters<typeof add>) => {+ listeners++;+ add(...args);+ };+ viewport.removeEventListener = (...args: Parameters<typeof remove>) => {+ listeners--;+ remove(...args);+ };+ Object.defineProperty(window, "innerHeight", { configurable: true, value: innerHeight });+ Object.defineProperty(window, "visualViewport", { configurable: true, value: viewport });+ return {+ set(values: { height: number; offsetTop: number }, event: "resize" | "scroll") {+ Object.assign(viewport, values);+ viewport.dispatchEvent(new Event(event));+ },+ listenerCount: () => listeners+ };+}++function renderPositioned(withAnchor: boolean) {+ const host = document.createElement("div");+ document.body.append(host);+ function Harness() {+ const anchorRef = useRef<HTMLDivElement>(null);+ const elementRef = useRef<HTMLDivElement>(null);+ usePositioningOniOS(elementRef, withAnchor ? anchorRef : undefined);+ return (+ <div ref={anchorRef} className="anchor">+ <div ref={elementRef} className="element" />+ </div>+ );+ }+ act(() => render(<Harness />, host));++ const find = (selector: string) => {+ const found = host.querySelector<HTMLElement>(selector);+ if (!found) throw new Error(`${selector} is not rendered`);+ return found;+ };+ return {+ element: () => find(".element"),+ anchor: () => find(".anchor"),+ unmount: () => {+ act(() => render(null, host));+ host.remove();+ }+ };+}diff --git a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsxindex cfed1a616a..2a1944ba79 100644--- a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx+++ b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx@@ -46,22 +46,26 @@ export function HideKeyboardAction({ className, containerRef }: {}/**- * Lifts an element anchored to the bottom of the screen above the keyboard in plain mobile Safari,- * which does not resize the page for the keyboard.+ * Lifts an element at the bottom of its `anchorRef`, or of the screen for a fixed element, above+ * the keyboard in plain mobile Safari, which does not resize the page for the keyboard.*/-export function usePositioningOniOS(wrapperRef: RefObject<HTMLDivElement | null>) {- // Fallback path for plain mobile Safari (no Capacitor): the WKWebView- // isn't resized when the keyboard opens, so visualViewport.height- // shrinks while window.innerHeight stays the same. Push the element- // up by the difference. Under Capacitor `resize: native` both values- // shrink together, so `obscured` is 0 and we leave CSS in charge.+export function usePositioningOniOS(+ wrapperRef: RefObject<HTMLDivElement | null>,+ anchorRef?: RefObject<HTMLElement | null>+) {+ // Safari shrinks `visualViewport` and pans it (`offsetTop`) inside the unchanged layout+ // viewport, so the element rises by how far its anchor reaches below the visible bottom. Under+ // Capacitor `resize: native` the layout viewport shrinks too, so `obscured` is 0 and CSS stays+ // in charge.const adjustPosition = useCallback(() => {if (!wrapperRef.current) return;const viewport = window.visualViewport;if (!viewport) return;+ const anchorBottom = anchorRef?.current?.getBoundingClientRect().bottom+ ?? window.innerHeight;const obscured = Math.max(0, Math.round(- window.innerHeight - viewport.height - viewport.offsetTop+ anchorBottom - viewport.height - viewport.offsetTop));if (obscured <= 1) {@@ -76,9 +80,12 @@ export function usePositioningOniOS(wrapperRef: RefObject<HTMLDivElement | null>// Run once in case the keyboard is already up when mounting// (e.g. returning from a dialog).adjustPosition();- window.visualViewport?.addEventListener("resize", adjustPosition);+ const viewport = window.visualViewport;+ viewport?.addEventListener("resize", adjustPosition);+ viewport?.addEventListener("scroll", adjustPosition);return () => {- window.visualViewport?.removeEventListener("resize", adjustPosition);+ viewport?.removeEventListener("resize", adjustPosition);+ viewport?.removeEventListener("scroll", adjustPosition);};}, [ adjustPosition ]);}diff --git a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsxindex 68e76f1e34..c959d86255 100644--- a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx+++ b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx@@ -16,6 +16,7 @@ import { useNestedEditor } from "./editable_embed";* - On Android, the viewport change makes the keyboard resize the content area, all we have to do is to hide the tab bar and global menu (handled in the global style).*/export default function MobileEditorToolbar() {+ const outerRef = useRef<HTMLDivElement>(null);const islandRef = useRef<HTMLDivElement>(null);const containerRef = useRef<HTMLDivElement>(null);const { note, noteContext, ntxId } = useNoteContext();@@ -29,7 +30,7 @@ export default function MobileEditorToolbar() {const toolbarElement = useShownToolbarElement(editor);const isActive = useEditorsFocused(noteEditor, nestedEditor) || dropdownActive;- usePositioningOniOS(islandRef);+ usePositioningOniOS(islandRef, outerRef);// Attach the toolbar from the CKEditor.useTriliumEvent("textEditorRefreshed", ({ ntxId: eventNtxId, editor }) => {@@ -70,10 +71,14 @@ export default function MobileEditorToolbar() {}, []);return (- <div className={clsx("classic-toolbar-outer-container", shouldDisplay ? "visible" : "hidden-ext", {- active: shouldDisplay && isActive,- ios: isIOS()- })}>+ <div+ ref={outerRef}+ className={clsx(+ "classic-toolbar-outer-container",+ shouldDisplay ? "visible" : "hidden-ext",+ { active: shouldDisplay && isActive, ios: isIOS() }+ )}+ ><div ref={islandRef} className="classic-toolbar-island"><div ref={containerRef} className={`classic-toolbar-widget ${dropdownActive ? "dropdown-active" : ""}`} /><HideKeyboardAction className="hide-keyboard-action" />