Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): widen the result list and give a place two lines

Elian Doranfceddd0e0083
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
index 2a566bed77..bbc2f0caa8 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.css
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -39,11 +39,12 @@ body.mobile .geo-map-container .geo-search-toolbar {
opacity: 0.6;
}
-/* Every row reads as icon + label, whether it offers a marker, a place, the geocoder or a report on
- it. Scoped to the portalled dropdown, which is a body child rather than part of the map. */
+/* Every row reads as icon + what it says, whether it offers a marker, a place, the geocoder or a
+ report on it. Scoped to the portalled dropdown, which is a body child rather than part of the map. */
.form-autocomplete-dropdown .geo-search-entry {
display: flex;
- align-items: center;
+ /* The mark sits on the first line rather than in the middle of a row that runs to two. */
+ align-items: flex-start;
gap: 6px;
overflow: hidden;
}
@@ -51,6 +52,33 @@ body.mobile .geo-map-container .geo-search-toolbar {
.form-autocomplete-dropdown .geo-search-entry .tn-icon {
flex-shrink: 0;
opacity: 0.7;
+ /* Set against the line beside it, the mark being drawn taller than the text it stands with. */
+ line-height: 1.4;
+}
+
+/* A place says what it is called and then where it is, so the row is given the height of both and
+ the address wraps instead of ending in an ellipsis a word in. */
+.form-autocomplete-dropdown .form-autocomplete-item:has(.geo-search-entry) {
+ white-space: normal;
+ padding-block: 6px;
+}
+
+.form-autocomplete-dropdown .geo-search-entry-lines {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.form-autocomplete-dropdown .geo-search-entry-address {
+ font-size: 0.85em;
+ opacity: 0.7;
+ /* Two lines of address and no more: past that the list is a page, and what is cut is the part of
+ an address that names a postcode or a country. */
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
}
/* The geocoder row and its reports are set apart from the places they produce. */
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index f7068f8f2d..272b9919f7 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -97,8 +97,10 @@ function entries() {
return [ ...document.querySelectorAll<HTMLElement>(".form-autocomplete-dropdown .form-autocomplete-item") ];
}
+/** What each row is called: the first line of a place, and the whole of any other row. */
function labels() {
- return entries().map((entry) => entry.textContent);
+ return entries().map((entry) =>
+ entry.querySelector(".geo-search-entry-name")?.textContent ?? entry.textContent);
}
/** Picks a row and lets whatever it started settle. */
@@ -148,7 +150,7 @@ describe("geo map SearchBox", () => {
expect(search).toHaveBeenCalledWith("tokyo");
// The row is replaced by what it found, the markers still standing above it.
- expect(labels()).toEqual([ "Tokyo trip", "Tokyo, Japan" ]);
+ expect(labels()).toEqual([ "Tokyo trip", "Tokyo" ]);
});
it("flies to a marker, and closes the list rather than leaving it open over the map", async () => {
@@ -223,7 +225,7 @@ describe("geo map SearchBox", () => {
await type(container, "berlin");
await pick(0);
- expect(labels()).toEqual([ "Berlin, Germany" ]);
+ expect(labels()).toEqual([ "Berlin" ]);
await type(container, "berlin de");
expect(labels()).toEqual([ "geo-map.search-online(berlin de)" ]);
@@ -282,6 +284,27 @@ describe("geo map SearchBox", () => {
expect(container.querySelector(".place-marker")).toBeNull();
});
+ it("gives a place two lines: what it is called, and the address that places it", async () => {
+ mockGeocoder([
+ { ...TOKYO, label: "Tokyo, Ōta, Japan" },
+ // A label that does not begin with the name has nothing to repeat, so it is left whole.
+ { id: "3", label: "Shibuya Crossing", name: "Scramble", lat: 35.6, lng: 139.7 }
+ ]);
+ const container = renderSearchBox(fakeMap(), []);
+
+ await type(container, "tokyo");
+ await pick(0);
+
+ const lines = entries().map((entry) => [
+ entry.querySelector(".geo-search-entry-name")?.textContent,
+ entry.querySelector(".geo-search-entry-address")?.textContent
+ ]);
+ expect(lines).toEqual([
+ [ "Tokyo", "Ōta, Japan" ],
+ [ "Scramble", "Shibuya Crossing" ]
+ ]);
+ });
+
it("takes the pin off the map once the field is emptied", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), []);
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index c5f6038d44..f72e52a809 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -31,6 +31,12 @@ const PLACE_PADDING = 60;
/** The zoom level a marker is shown at, closer in since a note marks a spot rather than an area. */
const MARKER_ZOOM = 15;
+/**
+ * How wide the result list is drawn. The field is a corner of the map, while what it offers is whole
+ * addresses, which at the field's own width is mostly an ellipsis.
+ */
+const RESULT_LIST_WIDTH = 500;
+
/** Caps how many of the map's own notes the list offers. */
const MAX_MARKER_RESULTS = 8;
@@ -192,10 +198,19 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
const entry = entriesByKey.current.get(key);
if (!entry) return key;
+ // A place reads over two lines: what it is called, and the address that places it. Every
+ // other row is one thing said once.
+ const address = entry.kind === "place" ? addressOf(entry.label, entry.name) : null;
+
return (
<span className={`geo-search-entry geo-search-entry-${entry.kind}`}>
<Icon icon={entry.icon} />
- {entry.label}
+ {entry.kind === "place"
+ ? <span className="geo-search-entry-lines">
+ <span className="geo-search-entry-name">{entry.name}</span>
+ {address && <span className="geo-search-entry-address">{address}</span>}
+ </span>
+ : entry.label}
</span>
);
}, []);
@@ -218,6 +233,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
onPick={pickEntry}
source={source}
renderItem={renderEntry}
+ dropdownMinWidth={RESULT_LIST_WIDTH}
keepOpenOnPick
placeholder={t("geo-map.search-placeholder")}
aria-label={t("geo-map.search")}
@@ -227,6 +243,16 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
);
}
+/**
+ * What a label says beyond the place's own name, which is the address around it — "Ōta, Japan" of
+ * "Tokyo, Ōta, Japan". A label that does not begin with the name is left whole, having nothing to
+ * repeat.
+ */
+function addressOf(label: string, name: string) {
+ const rest = label.startsWith(name) ? label.slice(name.length) : label;
+ return rest.replace(/^[\s,]+/, "");
+}
+
/** The notes on the map whose title contains the query and that are drawn somewhere. */
function matchMarkers(notes: FNote[], query: string): SearchEntry[] {
const needle = query.toLowerCase();
diff --git a/apps/client/src/widgets/react/FormAutocomplete.spec.tsx b/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
new file mode 100644
index 0000000000..6c56f32edc
--- /dev/null
+++ b/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
@@ -0,0 +1,77 @@
+/**
+ * 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 { afterEach, describe, expect, it } from "vitest";
+
+import { computeDropdownPosition } 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);
+ }
+});
+
+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" });
+ });
+
+ 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`
+ });
+
+ // 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"
+ });
+ });
+
+ 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" });
+
+ // 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");
+ });
+});
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 4bd2308ab0..f5c92e5547 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -57,6 +57,12 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
* the whole field instead of only the stretch of it left over for typing.
*/
leading?: ComponentChildren;
+ /**
+ * The least the list is drawn at, in pixels, for a field too narrow for what its entries have to
+ * say — a search box in the corner of a map offering whole addresses. The field's own width is
+ * still the floor and the viewport the ceiling, so the list never runs off the screen.
+ */
+ dropdownMinWidth?: number;
/**
* Opens the list with an entry already picked out — the one the field's text names, or failing
* that the first — so that Enter takes it without arrowing down to it first.
@@ -74,7 +80,7 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
* The dropdown is portalled to the body and positioned over everything else, so it is not clipped
* by scrolling ancestors. Selecting a suggestion reports it through `onChange`, exactly like typing.
*/
-export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, onPick, keepOpenOnPick, renderItem, leading, autoActivate, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {
+export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, onPick, keepOpenOnPick, renderItem, leading, autoActivate, dropdownMinWidth, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {
const ownInputRef = useRef<HTMLInputElement>(null);
const inputEl = inputRef ?? ownInputRef;
const fieldRef = useRef<HTMLDivElement>(null);
@@ -140,7 +146,7 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
// The wrapper where there is one, so a field carrying chips is spanned whole.
const anchor = fieldRef.current ?? inputEl.current;
if (anchor) {
- setPosition(computeDropdownPosition(anchor));
+ setPosition(computeDropdownPosition(anchor, dropdownMinWidth));
}
};
@@ -152,7 +158,7 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
window.removeEventListener("resize", reposition);
window.removeEventListener("scroll", reposition, true);
};
- }, [ isOpen, items.length, inputEl ]);
+ }, [ isOpen, items.length, inputEl, dropdownMinWidth ]);
function selectItem(item: string) {
(onPick ?? onChange)(item);
@@ -287,20 +293,32 @@ function bestMatchIndex(items: string[], text: string) {
* 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.
*/
-function computeDropdownPosition(input: HTMLElement): CSSProperties {
+export function computeDropdownPosition(input: HTMLElement, minWidth = 0): CSSProperties {
const rect = input.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: `${rect.left}px`,
+ left: `${left}px`,
top: `${flipAbove ? rect.top - maxHeight : rect.bottom}px`,
- width: `${rect.width}px`,
+ width: `${width}px`,
maxHeight: `${maxHeight}px`
};
}