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(spreadsheet): keep custom sort dialog open when picking a column (closes #11897)
Elian Doran261c144e1240
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsxindex cb8ea2ef90..a38b72050b 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx@@ -36,6 +36,7 @@ import useSpreadsheetExport from "./export";import { loadUniverLocale, UniverLocale } from "./locales";import useClampEdgeNavigation from "./navigation";import usePersistence from "./persistence";+import useFixRadixPortals from "./radix_portals";function buildReadOnlyLocaleOverrides() {const msg = t("spreadsheet.read-only");@@ -117,38 +118,6 @@ function SpreadsheetEditor({ note, noteContext, readOnly, locale }: TypeWidgetPrreturn <div ref={containerRef} className="spreadsheet" />;}-/**- * Univer's design system uses Radix UI primitives whose DismissableLayer detects- * "outside" clicks/focus via document-level pointerdown/focusin listeners combined- * with a React capture-phase flag. In React, portal events bubble through the- * component tree so onPointerDownCapture fires on the DismissableLayer, setting an- * internal flag that suppresses the "outside" detection. With preact/compat, portal- * events don't bubble through the React tree, so the flag never gets set and Radix- * immediately dismisses popups.- *- * Radix dispatches cancelable custom events ("dismissableLayer.pointerDownOutside"- * and "dismissableLayer.focusOutside") on the original event target before calling- * onDismiss. The dismiss is skipped if defaultPrevented is true. This hook intercepts- * those custom events in the capture phase and prevents default when the target is- * inside a Radix portal, restoring the expected behavior.- */-function useFixRadixPortals() {- useEffect(() => {- function preventDismiss(e: Event) {- if (e.target instanceof HTMLElement && e.target.closest("[id^='radix-']")) {- e.preventDefault();- }- }-- document.addEventListener("dismissableLayer.pointerDownOutside", preventDismiss, true);- document.addEventListener("dismissableLayer.focusOutside", preventDismiss, true);- return () => {- document.removeEventListener("dismissableLayer.pointerDownOutside", preventDismiss, true);- document.removeEventListener("dismissableLayer.focusOutside", preventDismiss, true);- };- }, []);-}-// Univer binds Ctrl+R to fill-right and Ctrl+D to fill-down, which shadow the// browser/Electron refresh (Ctrl+R) and bookmark (Ctrl+D) shortcuts.const FILL_SHORTCUT_COMMAND_IDS = new Set([diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/radix_portals.spec.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/radix_portals.spec.tsxnew file mode 100644index 0000000000..b36ce0ce60--- /dev/null+++ b/apps/client/src/widgets/type_widgets/spreadsheet/radix_portals.spec.tsx@@ -0,0 +1,155 @@+import { Dialog, Dropdown } from "@univerjs/design";+import { options, render } from "preact";+import { useState } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { installRadixPortalFixes } from "./radix_portals";++describe("installRadixPortalFixes", () => {+ let uninstall: () => void;+ let container: HTMLElement | undefined;++ beforeEach(() => {+ uninstall = installRadixPortalFixes(document);+ });++ afterEach(() => {+ if (container) {+ const mounted = container;+ act(() => render(null, mounted));+ container = undefined;+ }+ uninstall();+ document.body.replaceChildren();+ });++ it("keeps Univer's dialog open when an item in a dropdown inside it is picked", async () => {+ const onClose = vi.fn();+ const onSelect = vi.fn();++ // Mirrors `SortOptionItem` in `@univerjs/sheets-sort-ui`, which closes its dropdown on pick.+ function Panel() {+ const [ visible, setVisible ] = useState(false);+ const pick = () => {+ onSelect();+ setVisible(false);+ };+ return (+ <Dialog open mask draggable onClose={onClose}>+ <Dropdown+ open={visible}+ onOpenChange={setVisible}+ overlay={<ul><li id="option" onClick={pick}>Column B</li></ul>}+ >+ <button id="trigger">Column A</button>+ </Dropdown>+ </Dialog>+ );+ }++ const mounted = document.createElement("div");+ container = mounted;+ const sheet = document.createElement("div");+ document.body.append(mounted, sheet);+ act(() => render(<Panel />, mounted));+ await waitForRadix();++ await click(getElement("#trigger"));+ await click(getElement("#option"));+ expect(onSelect).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();++ await click(sheet);+ expect(onClose).toHaveBeenCalledOnce();+ });++ it("keeps a layer open when a dropdown portaled out of it is focused", () => {+ document.body.innerHTML = `+ <div id="radix-dialog"><button aria-controls="radix-dropdown">Column A</button></div>+ <div id="radix-dropdown"><ul><li id="option">Column B</li></ul></div>+ <div id="sheet"></div>+ `;+ const name = "dismissableLayer.focusOutside";++ const inPortal = dispatchOutsideEvent(getElement("#option"), name);+ expect(inPortal.onFocusOutside).not.toHaveBeenCalled();+ expect(inPortal.onDismiss).not.toHaveBeenCalled();++ const onSheet = dispatchOutsideEvent(getElement("#sheet"), name);+ expect(onSheet.onFocusOutside).toHaveBeenCalledOnce();+ expect(onSheet.onDismiss).toHaveBeenCalledOnce();+ });++ it("keeps a cell popup open while a menu opened from inside it is clicked", () => {+ document.body.innerHTML = `+ <section data-u-comp="rect-popup">+ <div data-u-comp="select" aria-controls="radix-select">Contains</div>+ </section>+ <div id="radix-select">+ <div id="condition">Equals</div>+ <div id="submenu-trigger" aria-controls="radix-submenu">More</div>+ </div>+ <div id="radix-submenu"><div id="nested">Begins with</div></div>+ <div data-u-comp="toolbar"><button aria-controls="radix-toolbar-menu">Sort</button></div>+ <div id="radix-toolbar-menu"><div id="toolbar-item">Sort A to Z</div></div>+ `;+ const onWindowPointerDown = vi.fn();+ window.addEventListener("pointerdown", onWindowPointerDown);+ try {+ for (const selector of [ "#condition", "#nested", "#toolbar-item" ]) {+ getElement(selector).dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ }+ expect(onWindowPointerDown).toHaveBeenCalledOnce();+ expect(onWindowPointerDown.mock.calls[0][0].target).toBe(getElement("#toolbar-item"));+ } finally {+ window.removeEventListener("pointerdown", onWindowPointerDown);+ }+ });+});++/** Radix registers its document `pointerdown` listener in a `setTimeout(0)` after mounting. */+async function waitForRadix() {+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));+}++/**+ * Dispatches the event sequence of a primary-button mouse click.+ *+ * A browser runs microtasks, and with them Preact's renders, between the listeners of an event it+ * dispatches itself, so a state change in a listener reaches the DOM before the next listener runs.+ * `debounceRendering` renders synchronously to match, which a script-dispatched event does not.+ */+async function click(target: HTMLElement) {+ const previousDebounce = options.debounceRendering;+ options.debounceRendering = (callback) => callback();+ try {+ const init = { bubbles: true, cancelable: true, button: 0 };+ target.dispatchEvent(new PointerEvent("pointerdown", { ...init, pointerType: "mouse" }));+ target.dispatchEvent(new MouseEvent("mousedown", init));+ target.dispatchEvent(new PointerEvent("pointerup", { ...init, pointerType: "mouse" }));+ target.dispatchEvent(new MouseEvent("mouseup", init));+ target.dispatchEvent(new MouseEvent("click", init));+ } finally {+ options.debounceRendering = previousDebounce;+ }+ await waitForRadix();+}++/** Dispatches an outside event the way Radix's `DismissableLayer` does, returning its callbacks. */+function dispatchOutsideEvent(target: Element, name: string) {+ const onFocusOutside = vi.fn();+ const onDismiss = vi.fn();+ target.addEventListener(name, (e) => {+ onFocusOutside(e);+ if (!e.defaultPrevented) onDismiss();+ }, { once: true });+ target.dispatchEvent(new CustomEvent(name, { bubbles: false, cancelable: true }));+ return { onFocusOutside, onDismiss };+}++function getElement(selector: string) {+ const element = document.querySelector(selector);+ expect(element).toBeInstanceOf(HTMLElement);+ return element as HTMLElement;+}diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/radix_portals.ts b/apps/client/src/widgets/type_widgets/spreadsheet/radix_portals.tsnew file mode 100644index 0000000000..1e01922212--- /dev/null+++ b/apps/client/src/widgets/type_widgets/spreadsheet/radix_portals.ts@@ -0,0 +1,76 @@+import { useEffect } from "preact/hooks";++const RADIX_PORTAL_SELECTOR = "[id^='radix-']";+const RECT_POPUP_SELECTOR = "[data-u-comp='rect-popup']";++/**+ * Stops Univer's popups from closing when a dropdown they opened is used.+ *+ * In React, an event inside a portal bubbles through the component tree, so the components+ * that open a dropdown see clicks on it as their own. With preact/compat, portal events follow+ * the DOM only, and Univer's popups treat a click in a portaled dropdown as outside:+ *+ * - Radix's `DismissableLayer` (Univer's `Dialog`, `Dropdown`, `DropdownMenu`) dispatches+ * `dismissableLayer.pointerDownOutside` / `dismissableLayer.focusOutside` on the target.+ * Univer's `Dialog` closes from its `onPointerDownOutside` without checking+ * `defaultPrevented`, so these events are stopped before they reach the target.+ * - Radix's `Dialog` defers its outside event to the `click`, by which time the picked item has+ * closed its dropdown and left the DOM, out of reach of a `document` listener. Radix skips the+ * deferred event when a `mousedown` or `touchstart` in between never bubbles back to+ * `document`, so those are stopped at `body` inside a dropdown opened from another layer.+ * - `RectPopup` (the filter panel and other cell popups) closes on any `pointerdown` that+ * reaches `window`, and relies on its own `onPointerDown` to stop the ones inside it.+ */+export default function useFixRadixPortals() {+ useEffect(() => installRadixPortalFixes(document), []);+}++export function installRadixPortalFixes(doc: Document) {+ function stopOutsideEvent(e: Event) {+ if (e.target instanceof Element && e.target.closest(RADIX_PORTAL_SELECTOR)) {+ e.stopPropagation();+ }+ }++ function stopDeferredDismiss(e: Event) {+ if (e.target instanceof Element && isOpenedFrom(doc, e.target, RADIX_PORTAL_SELECTOR)) {+ e.stopPropagation();+ }+ }++ function stopRectPopupDismiss(e: Event) {+ if (e.target instanceof Element && isOpenedFrom(doc, e.target, RECT_POPUP_SELECTOR)) {+ e.stopPropagation();+ }+ }++ doc.addEventListener("dismissableLayer.pointerDownOutside", stopOutsideEvent, true);+ doc.addEventListener("dismissableLayer.focusOutside", stopOutsideEvent, true);+ doc.body.addEventListener("mousedown", stopDeferredDismiss);+ doc.body.addEventListener("touchstart", stopDeferredDismiss);+ doc.addEventListener("pointerdown", stopRectPopupDismiss);+ return () => {+ doc.removeEventListener("dismissableLayer.pointerDownOutside", stopOutsideEvent, true);+ doc.removeEventListener("dismissableLayer.focusOutside", stopOutsideEvent, true);+ doc.body.removeEventListener("mousedown", stopDeferredDismiss);+ doc.body.removeEventListener("touchstart", stopDeferredDismiss);+ doc.removeEventListener("pointerdown", stopRectPopupDismiss);+ };+}++/**+ * Follows each Radix portal back to the trigger whose `aria-controls` names it, until a trigger+ * lies inside an element matching `openerSelector` or outside any portal.+ */+function isOpenedFrom(doc: Document, target: Element, openerSelector: string) {+ const visited = new Set<Element>();+ let portal = target.closest(RADIX_PORTAL_SELECTOR);+ while (portal && !visited.has(portal)) {+ visited.add(portal);+ const trigger = doc.querySelector(`[aria-controls="${portal.id}"]`);+ if (!trigger) return false;+ if (trigger.closest(openerSelector)) return true;+ portal = trigger.closest(RADIX_PORTAL_SELECTOR);+ }+ return false;+}diff --git a/apps/client/vite.config.mts b/apps/client/vite.config.mtsindex 4f47f9bfee..068a53a242 100644--- a/apps/client/vite.config.mts+++ b/apps/client/vite.config.mts@@ -148,7 +148,18 @@ export default defineConfig(() => ({deps: {// The plugin reads `rrule` through a namespace import, which Node resolves to the// package's CommonJS build with no named exports. Bundling it applies Vite's interop.- inline: ["@fullcalendar/rrule"]+ inline: [+ "@fullcalendar/rrule",+ // Univer's components and the React libraries under them run on preact/compat+ // in the app, so specs bundle them to apply the same `react` alias.+ /@univerjs\/design/,+ /@radix-ui\//,+ /@floating-ui\/react-dom/,+ /react-remove-scroll/,+ /react-style-singleton/,+ /use-callback-ref/,+ /use-sidecar/+ ]}},reporters: [