Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): place a field's suggestions in a Popup

Elian Doran5bf2400cfc35
diff --git a/apps/client/src/widgets/react/FormAutocomplete.css b/apps/client/src/widgets/react/FormAutocomplete.css
index 55e71e2066..bd1f3d237f 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.css
+++ b/apps/client/src/widgets/react/FormAutocomplete.css
@@ -11,15 +11,10 @@
* out, falls back to the value those themes use for their own menus.
*/
.form-autocomplete-dropdown {
- position: fixed;
- z-index: 2000;
- margin: 0;
- /* The entries sit inside the rounded border rather than against it, so a highlighted one is a
- rounded chip within the menu instead of a band across it. */
- padding: var(--suggestion-list-padding);
- scroll-padding-block: var(--suggestion-list-padding);
- list-style: none;
- overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ /* Twice `VIEWPORT_PADDING` in Popup.tsx, whose `shift()` then keeps the list on screen. */
+ max-width: calc(100vw - 10px);
font-size: 0.9rem;
color: var(--menu-text-color);
background-color: var(--menu-background-color);
@@ -28,6 +23,26 @@
border: 1px solid var(--dropdown-border-color);
border-radius: var(--dropdown-border-radius, 6px);
box-shadow: 0 10px 20px rgba(0, 0, 0, var(--dropdown-shadow-opacity, 0.2));
+ /* Keeps the list's scrollbar inside the rounded corners. */
+ overflow: hidden;
+}
+
+/* Over a prompt (2000), which can hold a field; `body .tn-popup` sets 1200 (Popup.css). */
+body .tn-popup.form-autocomplete-dropdown {
+ z-index: 2000;
+}
+
+/* Scrolls inside the frame, whose height `placeFloating()` caps to the room on its side. */
+.form-autocomplete-dropdown > .form-autocomplete-list {
+ min-height: 0;
+ max-height: 300px;
+ margin: 0;
+ /* The entries sit inside the rounded border rather than against it, so a highlighted one is a
+ rounded chip within the menu instead of a band across it. */
+ padding: var(--suggestion-list-padding);
+ scroll-padding-block: var(--suggestion-list-padding);
+ list-style: none;
+ overflow-y: auto;
}
.form-autocomplete-dropdown .form-autocomplete-item {
diff --git a/apps/client/src/widgets/react/FormAutocomplete.spec.tsx b/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
index dd18a762da..3df298a889 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
@@ -1,38 +1,9 @@
-/**
- * Where the suggestion list is placed and how wide it is drawn. Everything the placement reads is
- * measured from the layout, which a headless DOM has none of, so the field and the viewport are
- * given the measurements a browser would have taken.
- */
import { useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderInto } from "../../test/render";
-import FormAutocomplete, { computeDropdownPosition, stepOver } from "./FormAutocomplete";
-
-/** The room the placement keeps between the list and the edge of the screen. */
-const MARGIN = 8;
-
-function fieldAt({ left = 20, top = 100, width = 240, height = 30 } = {}) {
- const element = document.createElement("div");
- element.getBoundingClientRect = () => ({
- left, top, width, height, right: left + width, bottom: top + height,
- x: left, y: top, toJSON: () => ({})
- });
- return element;
-}
-
-function setViewport(width: number, height: number) {
- for (const [ name, value ] of [ [ "clientWidth", width ], [ "clientHeight", height ] ] as const) {
- Object.defineProperty(document.documentElement, name, { value, configurable: true });
- }
-}
-
-afterEach(() => {
- for (const name of [ "clientWidth", "clientHeight" ]) {
- Reflect.deleteProperty(document.documentElement, name);
- }
-});
+import FormAutocomplete, { stepOver } from "./FormAutocomplete";
describe("stepping through a list with headings in it", () => {
const items = [ "Nearby", "a", "b", "Far away", "c" ];
@@ -59,48 +30,32 @@ describe("stepping through a list with headings in it", () => {
});
});
-describe("computeDropdownPosition", () => {
- it("hangs the list under the field, at the field's own width", () => {
- setViewport(1200, 800);
-
- expect(computeDropdownPosition(fieldAt())).toMatchObject({
- left: "20px",
- top: "130px",
- width: "240px"
- });
- });
-
- it("draws the list wider where the caller asks for more than the field", () => {
- setViewport(1200, 800);
-
- expect(computeDropdownPosition(fieldAt({ width: 240 }), 440)).toMatchObject({ width: "440px" });
- // The field is the floor: a minimum under it asks for nothing.
- expect(computeDropdownPosition(fieldAt({ width: 240 }), 100)).toMatchObject({ width: "240px" });
+describe("the dropdown", () => {
+ afterEach(() => {
+ vi.useRealTimers();
});
- it("keeps a wider list on the screen rather than running it off the far edge", () => {
- setViewport(600, 800);
-
- // Asked for more than there is room for, it takes the room there is.
- expect(computeDropdownPosition(fieldAt({ left: 20 }), 2000)).toMatchObject({
- left: `${MARGIN}px`,
- width: `${600 - 2 * MARGIN}px`
- });
+ async function open(dropdownMinWidth?: number) {
+ vi.useFakeTimers();
+ const container = renderInto(<FormAutocomplete currentValue="" onChange={() => {}} openOnFocus
+ source={async () => [ "a", "b" ]} dropdownMinWidth={dropdownMinWidth} />);
+ const input = container.querySelector("input");
+ if (!input) throw new Error("no input rendered");
+ input.getBoundingClientRect = () => DOMRect.fromRect({ x: 20, y: 100, width: 240, height: 30 });
- // Wide enough to fit, but not where the field stands, so it is pulled back to fit.
- expect(computeDropdownPosition(fieldAt({ left: 400 }), 440)).toMatchObject({
- left: `${600 - MARGIN - 440}px`,
- width: "440px"
- });
- });
+ await act(async () => { input.focus(); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });
+ const dropdowns = document.querySelectorAll<HTMLElement>(".tn-popup.form-autocomplete-dropdown");
+ return dropdowns[dropdowns.length - 1];
+ }
- it("flips above the field only where the room below is too little to be useful", () => {
- setViewport(1200, 800);
- expect(computeDropdownPosition(fieldAt({ top: 100 }))).toMatchObject({ top: "130px" });
+ it("is a popup under the field, as wide as the field or as the minimum asked for where that is more", async () => {
+ const atField = await open();
+ expect(atField.querySelectorAll(".form-autocomplete-list > .form-autocomplete-item")).toHaveLength(2);
+ expect(atField.style.width).toBe("240px");
- // Near the foot of the screen, where what is under the field would show barely an entry.
- setViewport(1200, 200);
- expect(computeDropdownPosition(fieldAt({ top: 150 })).top).not.toBe("180px");
+ expect((await open(440)).style.width).toBe("440px");
+ expect((await open(100)).style.width).toBe("240px");
});
});
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index c60027d1ac..ed5190a91f 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -1,25 +1,22 @@
import "./FormAutocomplete.css";
+import type { ReferenceElement } from "@floating-ui/dom";
import type { ComponentChildren, RefObject } from "preact";
-import { createPortal, type CSSProperties } from "preact/compat";
-import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
+import { type MutableRef, useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import FormTextBox from "./FormTextBox";
import { useUniqueName } from "./hooks";
+import Popup, { type PopupProps } from "./Popup";
/** Marks the dropdown, which is portalled to the body: popups checking for outside clicks must ignore it. */
export const AUTOCOMPLETE_DROPDOWN_SELECTOR = ".form-autocomplete-dropdown";
const DEBOUNCE_MS = 150;
-const MAX_DROPDOWN_HEIGHT = 300;
-/** Below this the space under the input is considered unusable, and the dropdown flips above it. */
-const MIN_DROPDOWN_HEIGHT = 120;
-const VIEWPORT_MARGIN = 8;
type FormTextBoxProps = Parameters<typeof FormTextBox>[0];
/** What the dropdown is placed under: an element, or a rect such as a caret's. */
-type DropdownAnchor = Pick<Element, "getBoundingClientRect">;
+type DropdownAnchor = HTMLElement | ReferenceElement;
interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
currentValue: string;
@@ -73,8 +70,8 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
* Content rendered inside the field, after the input. Use it for a button that commits what the
* input holds, as {@link FormAutocompleteProps.leading} carries the chips that precede it.
*
- * Passing either prop wraps the input in a `tn-field` element, which
- * {@link computeDropdownPosition} then measures the dropdown against.
+ * Passing either prop wraps the input in a `tn-field` element, which the dropdown is then placed
+ * under and spans.
*/
trailing?: ComponentChildren;
/**
@@ -110,10 +107,6 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
const inputEl = inputRef ?? ownInputRef;
const fieldRef = useRef<HTMLDivElement>(null);
const isDisabled = !!(restProps.readOnly || restProps.disabled);
- // The wrapper where there is one, so a field carrying chips is spanned whole.
- const anchor = useMemo<DropdownAnchor>(() => ({
- getBoundingClientRect: () => (fieldRef.current ?? inputEl.current)?.getBoundingClientRect() ?? new DOMRect()
- }), [ inputEl ]);
const autocomplete = useAutocomplete({
query: currentValue,
@@ -173,7 +166,8 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
<AutocompleteDropdown
autocomplete={autocomplete}
- anchor={anchor}
+ // The wrapper where there is one, so a field carrying chips is spanned whole.
+ anchor={fieldRef.current ?? inputEl.current}
minWidth={dropdownMinWidth}
renderItem={renderItem}
isHeading={isHeading}
@@ -202,7 +196,7 @@ export function AutocompleteList({ query, source, anchor, minWidth, renderItem,
renderItem?(item: string): ComponentChildren;
onPick(item: string): void;
handleRef: MutableRef<AutocompleteListHandle | null>;
- elementRef?(element: HTMLElement | null): void;
+ elementRef?: PopupProps["elementRef"];
}) {
// The focus stays where the query is typed, so there is no field to return it to.
const inputRef = useRef<HTMLInputElement>(null);
@@ -246,65 +240,58 @@ export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocompl
}
/**
- * The list of a {@link useAutocomplete}, portalled to the body and kept under `anchor` as the page
- * scrolls or resizes.
+ * The list of a {@link useAutocomplete}, in a {@link Popup} under `anchor`, which places it again as
+ * the list or the anchor changes size or moves.
*/
-function AutocompleteDropdown({ autocomplete, anchor, minWidth, renderItem, isHeading, elementRef }: {
+function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem, isHeading, elementRef }: {
autocomplete: ReturnType<typeof useAutocomplete<string>>;
- anchor: DropdownAnchor;
+ anchor: DropdownAnchor | null;
minWidth?: number;
renderItem?(item: string): ComponentChildren;
isHeading?(item: string): boolean;
- elementRef?(element: HTMLElement | null): void;
+ elementRef?: PopupProps["elementRef"];
}) {
- const [ position, setPosition ] = useState<CSSProperties>();
const { isShown, items, activeIndex, itemId, pick } = autocomplete;
- useLayoutEffect(() => {
- if (!isShown) {
- return;
- }
-
- const reposition = () => setPosition(computeDropdownPosition(anchor, minWidth));
- reposition();
- window.addEventListener("resize", reposition);
- // Capture: the anchor can live inside a scrolling container rather than the document.
- window.addEventListener("scroll", reposition, true);
- return () => {
- window.removeEventListener("resize", reposition);
- window.removeEventListener("scroll", reposition, true);
- };
- }, [ isShown, items.length, anchor, minWidth ]);
+ if (!isShown || !anchor) {
+ return null;
+ }
- return isShown && position ? createPortal(
- <ul
- ref={elementRef}
+ return (
+ <Popup
+ anchor={anchor}
className="form-autocomplete-dropdown"
- role="listbox"
- style={position}
- // Keeps the focus where the query is typed, so its blur does not close the dropdown
- // before the click lands on an item.
- onMouseDown={(e) => e.preventDefault()}
+ elementRef={elementRef}
+ // As wide as the field, or as `minWidth` where that is more.
+ style={{ width: `${Math.max(anchor.getBoundingClientRect().width, minWidth)}px` }}
>
- {items.map((item, index) => (
- isHeading?.(item)
- ? <li key={item} className="form-autocomplete-heading" role="presentation">
- {renderItem ? renderItem(item) : item}
- </li>
- : <li
- key={item}
- id={itemId(index)}
- className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
- role="option"
- aria-selected={index === activeIndex}
- onMouseMove={(e) => autocomplete.hover(index, e)}
- onClick={() => pick(item)}
- >
- {renderItem ? renderItem(item) : item}
- </li>
- ))}
- </ul>,
- document.body) : null;
+ <ul
+ className="form-autocomplete-list"
+ role="listbox"
+ // Keeps the focus where the query is typed, so its blur does not close the dropdown
+ // before the click lands on an item.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {items.map((item, index) => (
+ isHeading?.(item)
+ ? <li key={item} className="form-autocomplete-heading" role="presentation">
+ {renderItem ? renderItem(item) : item}
+ </li>
+ : <li
+ key={item}
+ id={itemId(index)}
+ className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
+ role="option"
+ aria-selected={index === activeIndex}
+ onMouseMove={(e) => autocomplete.hover(index, e)}
+ onClick={() => pick(item)}
+ >
+ {renderItem ? renderItem(item) : item}
+ </li>
+ ))}
+ </ul>
+ </Popup>
+ );
}
interface UseAutocompleteOptions<T> {
@@ -598,37 +585,3 @@ export function stepOver<T>(items: T[], from: number, delta: number, isHeading?:
return -1;
}
-
-/**
- * Places the dropdown under the input, flipping above it only when the space below is too small to
- * be useful. Preferring below matters for inputs sitting in a panel docked to the bottom of the
- * screen: the room under them is limited but ample, while flipping would cover the panel itself.
- *
- * As wide as the field, or as wide as `minWidth` asks where that is more, and never wider than the
- * viewport. A list grown past the far edge is pulled back onto the screen rather than left running
- * off it, since it is placed from the field's leading edge.
- *
- * Exported for its own tests: everything it reads is measured from the layout, which is what a
- * component test in a headless DOM has none of.
- */
-export function computeDropdownPosition(anchor: DropdownAnchor, minWidth = 0): CSSProperties {
- const rect = anchor.getBoundingClientRect();
- const viewportHeight = document.documentElement.clientHeight;
- const viewportWidth = document.documentElement.clientWidth;
- const spaceBelow = viewportHeight - rect.bottom - VIEWPORT_MARGIN;
- const spaceAbove = rect.top - VIEWPORT_MARGIN;
- const flipAbove = spaceBelow < MIN_DROPDOWN_HEIGHT && spaceAbove > spaceBelow;
- const available = flipAbove ? spaceAbove : spaceBelow;
- const maxHeight = Math.min(MAX_DROPDOWN_HEIGHT, Math.max(available, 0));
-
- const room = Math.max(viewportWidth - 2 * VIEWPORT_MARGIN, 0);
- const width = Math.min(Math.max(rect.width, minWidth), room);
- const left = Math.max(VIEWPORT_MARGIN, Math.min(rect.left, viewportWidth - VIEWPORT_MARGIN - width));
-
- return {
- left: `${left}px`,
- top: `${flipAbove ? rect.top - maxHeight : rect.bottom}px`,
- width: `${width}px`,
- maxHeight: `${maxHeight}px`
- };
-}
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
index 621d14ccaf..8f759d783b 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
@@ -117,7 +117,7 @@ export function createAutocompleteMentionList({ source, renderItem, toMention }:
query={state.query}
source={source}
// A new anchor each time the query changes, so it is placed again at the caret.
- anchor={{ getBoundingClientRect: state.caretRect }}
+ anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}
minWidth={AUTOCOMPLETE_MENTION_MIN_WIDTH}
renderItem={renderItem}
onPick={(item) => state.commit(toMention(item))}