Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): keep the image when going back to a world map

Elian Doranbe42097e82f6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 16bf2b84ca..331a455a89 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3169,7 +3169,8 @@
"background-map": "Vector & Raster",
"background-image": "Custom image",
"background-map-description": "A world map in one of the vector or raster styles.",
- "background-image-description": "An image of your own, such as a floor plan or a fantasy map, with markers and shapes placed on it."
+ "background-image-description": "An image of your own, such as a floor plan or a fantasy map, with markers and shapes placed on it.",
+ "background-image-inherited": "This map's image comes from a parent note or a template, so it can only be switched off there."
},
"embedded_note": {
"open-note": "Open note",
diff --git a/apps/client/src/widgets/collections/geomap/GeoMapProperties.spec.tsx b/apps/client/src/widgets/collections/geomap/GeoMapProperties.spec.tsx
index 4f03125783..6f618b59ec 100644
--- a/apps/client/src/widgets/collections/geomap/GeoMapProperties.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/GeoMapProperties.spec.tsx
@@ -4,6 +4,7 @@ import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type FNote from "../../../entities/fnote";
+import froca from "../../../services/froca";
import { buildNote } from "../../../test/easy-froca";
import GeoMapProperties, { type GeoMapImageState } from "./GeoMapProperties";
@@ -20,7 +21,8 @@ const mocks = vi.hoisted(() => ({
setLabel: vi.fn(async () => {}),
removeOwnedLabelByName: vi.fn(async () => {}),
removeOwnedRelationByName: vi.fn(async () => {}),
- setAttribute: vi.fn(async () => {})
+ setAttribute: vi.fn(async () => {}),
+ toggleDangerousAttribute: vi.fn(async () => {})
}));
vi.mock("../../../services/attributes", () => ({
@@ -29,6 +31,7 @@ vi.mock("../../../services/attributes", () => ({
removeOwnedLabelByName: mocks.removeOwnedLabelByName,
removeOwnedRelationByName: mocks.removeOwnedRelationByName,
setAttribute: mocks.setAttribute,
+ toggleDangerousAttribute: mocks.toggleDangerousAttribute,
isAffecting: () => true
}
}));
@@ -52,7 +55,10 @@ describe("GeoMapProperties", () => {
let container: HTMLElement;
function draw(labels: Record<string, string>, image: GeoMapImageState = { status: "geo" }) {
- const note = buildNote({ title: "Map", ...labels }) as unknown as FNote;
+ return drawNote(buildNote({ title: "Map", ...labels }) as unknown as FNote, image);
+ }
+
+ function drawNote(note: FNote, image: GeoMapImageState = { status: "geo" }) {
act(() => {
render(<GeoMapProperties note={note} image={image} onClose={() => {}} />, container);
});
@@ -190,17 +196,53 @@ describe("GeoMapProperties", () => {
expect(mocks.setAttribute).toHaveBeenCalledWith(note, "relation", "map:image", "image2");
});
- it("goes back to a world map by removing the image", () => {
+ it("goes back to a world map by disabling the image, which it keeps", () => {
const note = draw({ "~map:image": "image1" }, LOADED_IMAGE);
expect(backgroundType()).toBe("geo-map.background-image");
choose("geo-map.background-map");
- expect(mocks.removeOwnedRelationByName).toHaveBeenCalledWith(note, "map:image");
+ expect(mocks.toggleDangerousAttribute)
+ .toHaveBeenCalledExactlyOnceWith(note, "relation", "map:image", false);
+ expect(mocks.removeOwnedRelationByName).not.toHaveBeenCalled();
expect(optionTitles(".geo-map-properties-background")).toEqual([
"geo-map.background-type", "book_properties_config.map-style"
]);
});
+ it("enables a disabled image again, and replaces it when another one is picked", () => {
+ const note = draw({ "~disabled:map:image": "image1" });
+ expect(backgroundType()).toBe("geo-map.background-map");
+
+ choose("geo-map.background-image");
+ expect(mocks.toggleDangerousAttribute)
+ .toHaveBeenCalledExactlyOnceWith(note, "relation", "map:image", true);
+
+ act(() => query(".autocomplete-stub")?.click());
+ expect(mocks.setAttribute).toHaveBeenCalledWith(note, "relation", "map:image", "image2");
+ expect(mocks.removeOwnedRelationByName).toHaveBeenCalledWith(note, "disabled:map:image");
+ });
+
+ it("keeps an inherited image, which only its owner can switch off", () => {
+ const parent = buildNote({
+ title: "Maps",
+ "~map:image(inheritable)": "image1",
+ children: [ { id: "inheritingMap", title: "Map" } ]
+ });
+ expect(parent.children).toContain("inheritingMap");
+ const note = drawNote(froca.notes.inheritingMap, LOADED_IMAGE);
+ expect(backgroundType()).toBe("geo-map.background-image");
+ expect(query(".geo-map-background-type .tn-card-option-description")?.textContent)
+ .toBe("geo-map.background-image-inherited");
+
+ const worldMap = openBackgroundTypes().find((item) =>
+ item.textContent?.trim().startsWith("geo-map.background-map"));
+ expect(worldMap?.classList.contains("disabled")).toBe(true);
+ act(() => worldMap?.click());
+ expect(mocks.toggleDangerousAttribute).not.toHaveBeenCalled();
+ expect(backgroundType()).toBe("geo-map.background-image");
+ expect(note.noteId).toBe("inheritingMap");
+ });
+
it("measures in pixels until custom corners are chosen, starting them at the size", () => {
const note = draw({ "~map:image": "image1" }, LOADED_IMAGE);
expect(query(".autocomplete-stub")?.dataset.noteId).toBe("image1");
diff --git a/apps/client/src/widgets/collections/geomap/GeoMapProperties.tsx b/apps/client/src/widgets/collections/geomap/GeoMapProperties.tsx
index 860f4a9722..c4af8c096d 100644
--- a/apps/client/src/widgets/collections/geomap/GeoMapProperties.tsx
+++ b/apps/client/src/widgets/collections/geomap/GeoMapProperties.tsx
@@ -34,6 +34,8 @@ interface BackgroundOption {
title: string;
description: string;
icon: string;
+ /** Why the option cannot be chosen, if it cannot. */
+ unavailable?: string;
}
/** The longest side, in pixels, that practically every graphics card can draw an image at. */
@@ -80,12 +82,22 @@ function isMapStyle(property: BookProperty) {
}
/**
- * A world map with its style, or an image with its coordinates. Choosing the image writes nothing
- * until an image note is picked, so the map stays drawn as it was until then.
+ * A world map with its style, or an image with its coordinates.
+ *
+ * Going back to a world map disables `~map:image` as `~disabled:map:image` rather than removing it,
+ * and choosing the image enables it again. Without a disabled image, choosing the image writes
+ * nothing until an image note is picked, so the map stays drawn as it was until then. An inherited
+ * image can only be disabled on the note that owns it.
*/
function BackgroundCard({ note, image }: { note: FNote; image: GeoMapImageState }) {
const [ imageNoteId, setImageNoteId ] = useNoteRelation(note, "map:image");
+ // Read so that the card follows the relation being disabled and enabled.
+ useNoteRelation(note, "disabled:map:image");
const [ kind, setKind ] = useState<BackgroundKind>(imageNoteId ? "image" : "map");
+ const isInherited = !!imageNoteId && !note.getOwnedRelation("map:image");
+ const inheritedReason = isInherited ? t("geo-map.background-image-inherited") : undefined;
+ const options = BACKGROUND_OPTIONS.map((option) =>
+ option.value === "map" ? { ...option, unavailable: inheritedReason } : option);
useEffect(() => {
if (imageNoteId) setKind("image");
@@ -93,8 +105,20 @@ function BackgroundCard({ note, image }: { note: FNote; image: GeoMapImageState
function changeKind(newKind: BackgroundKind) {
setKind(newKind);
- if (newKind === "map") {
- void attributes.removeOwnedRelationByName(note, "map:image");
+ const ownsImage = !!note.getOwnedRelation("map:image");
+ const ownsDisabledImage = !!note.getOwnedRelation("disabled:map:image");
+ if (newKind === "map" && ownsImage) {
+ void attributes.toggleDangerousAttribute(note, "relation", "map:image", false);
+ } else if (newKind === "image" && !imageNoteId && ownsDisabledImage) {
+ void attributes.toggleDangerousAttribute(note, "relation", "map:image", true);
+ }
+ }
+
+ function pickImage(noteId: string) {
+ setImageNoteId(noteId);
+ // The note holds one image at a time, so a disabled one does not outlive its replacement.
+ if (note.getOwnedRelation("disabled:map:image")) {
+ void attributes.removeOwnedRelationByName(note, "disabled:map:image");
}
}
@@ -103,13 +127,15 @@ function BackgroundCard({ note, image }: { note: FNote; image: GeoMapImageState
<OptionCardSection
className="geo-map-background-type"
label={t("geo-map.background-type")}
+ description={inheritedReason}
>
<FormDropdownList
- values={BACKGROUND_OPTIONS}
+ values={options}
keyProperty="value"
titleProperty="title"
descriptionProperty="description"
iconProperty="icon"
+ disabledProperty="unavailable"
currentValue={kind}
onChange={(value) => changeKind(value as BackgroundKind)}
/>
@@ -124,7 +150,7 @@ function BackgroundCard({ note, image }: { note: FNote; image: GeoMapImageState
note={note}
image={image}
imageNoteId={imageNoteId}
- onPickImage={setImageNoteId}
+ onPickImage={pickImage}
/>
)}
</Card>
diff --git a/apps/client/src/widgets/react/FormDropdownList.spec.tsx b/apps/client/src/widgets/react/FormDropdownList.spec.tsx
index 9c77833bf7..d0ddc56e10 100644
--- a/apps/client/src/widgets/react/FormDropdownList.spec.tsx
+++ b/apps/client/src/widgets/react/FormDropdownList.spec.tsx
@@ -32,6 +32,7 @@ interface Entry {
icon?: string;
hint?: string;
startsGroup?: boolean;
+ unavailable?: string;
}
const ENTRIES: Entry[] = [
@@ -121,6 +122,24 @@ describe("FormDropdownList", () => {
expect(document.querySelectorAll(".dropdown-divider")).toHaveLength(0);
});
+ it("shows an item with a reason against it as disabled, and reports no press on it", () => {
+ const onChange = vi.fn();
+ renderOpened(
+ <FormDropdownList
+ values={[ ENTRIES[0], { ...ENTRIES[1], unavailable: "Not here" } ]}
+ keyProperty="value"
+ titleProperty="title"
+ disabledProperty="unavailable"
+ currentValue="text"
+ onChange={onChange}
+ />);
+
+ const items = [ ...document.querySelectorAll<HTMLElement>(".dropdown-item") ];
+ expect(items.map((item) => item.classList.contains("disabled"))).toEqual([ false, true ]);
+ act(() => items[1].click());
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
/** The menu only renders its items once Bootstrap reports it open, which nothing does here. */
function renderOpened(vnode: preact.ComponentChild) {
act(() => render(vnode, container));
diff --git a/apps/client/src/widgets/react/FormDropdownList.tsx b/apps/client/src/widgets/react/FormDropdownList.tsx
index 1feebc2657..854a45bf10 100644
--- a/apps/client/src/widgets/react/FormDropdownList.tsx
+++ b/apps/client/src/widgets/react/FormDropdownList.tsx
@@ -18,11 +18,16 @@ interface FormDropdownList<T> extends Omit<DropdownProps, "children"> {
* whose entries are not all the same sort of choice, e.g. one that changes more than the others do.
*/
dividerBeforeProperty?: keyof T;
+ /**
+ * Property holding why an item cannot be chosen. An item with a reason is shown disabled, with the
+ * reason as its tooltip.
+ */
+ disabledProperty?: keyof T;
currentValue: string;
onChange(newValue: string): void;
}
-export default function FormDropdownList<T>({ values, keyProperty, titleProperty, titleSuffixProperty, descriptionProperty, iconProperty, dividerBeforeProperty, currentValue, onChange, ...restProps }: FormDropdownList<T>) {
+export default function FormDropdownList<T>({ values, keyProperty, titleProperty, titleSuffixProperty, descriptionProperty, iconProperty, dividerBeforeProperty, disabledProperty, currentValue, onChange, ...restProps }: FormDropdownList<T>) {
const currentValueData = values.find(value => value[keyProperty] === currentValue);
const renderTitle = (item: T) => {
@@ -44,6 +49,9 @@ export default function FormDropdownList<T>({ values, keyProperty, titleProperty
<Dropdown text={currentValueData ? renderLabel(currentValueData) : ""} {...restProps}>
{values.map(item => {
const isCurrent = currentValue === item[keyProperty];
+ const disabledReason = disabledProperty
+ ? item[disabledProperty] as string | undefined
+ : undefined;
return (
<Fragment key={item[keyProperty] as string}>
{dividerBeforeProperty && !!item[dividerBeforeProperty] && <FormDropdownDivider />}
@@ -56,6 +64,8 @@ export default function FormDropdownList<T>({ values, keyProperty, titleProperty
checked={!iconProperty && isCurrent}
active={!!iconProperty && isCurrent}
description={descriptionProperty && item[descriptionProperty] as string}
+ disabled={!!disabledReason}
+ disabledTooltip={disabledReason}
selected={isCurrent}
>
{renderTitle(item)}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html
index 9347ca2d52..76e3d74d9a 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html
@@ -17,8 +17,12 @@
choose the image note in <em>Image note</em>.</li>
</ol>
<p>The map then shows the image instead of the world map and opens with the
- whole image in view. To go back to a world map, set <em>Type</em> back to <em>Vector &amp; Raster</em>,
- which removes the image.</p>
+ whole image in view. To go back to a world map, set <em>Type</em> back to <em>Vector &amp; Raster</em>.
+ The image is switched off rather than removed: its relation is renamed
+ to <code>~disabled:map:image</code>, so setting <em>Type</em> to <em>Custom image</em> again
+ brings back the same image, with its coordinates. An image that the geo
+ map inherits from a parent note or a template can only be switched off
+ on the note that holds it.</p>
<p>The image note is stored in a <code>~map:image</code> <a href="#root/_help_Cq5X6iKQop6R">relation</a> of
the geo map, which can also be added by hand.</p>
<h2>Image size</h2>
diff --git a/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md b/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md
index e48ed2f040..eedb6a3d92 100644
--- a/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md
+++ b/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md
@@ -8,7 +8,7 @@ An image map is a geo map drawn over an image of your own instead of a world map
3. Open the <span class="tn-icon bx bx-cog"></span>_Geo map properties_ dialog from the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20menu.md">Note menu</a> or from the settings menu of the <a class="reference-link" href="../Collection%20Properties.md">Collection Properties</a>.
4. Under _Background_, set _Type_ to _Custom image_, then choose the image note in _Image note_.
-The map then shows the image instead of the world map and opens with the whole image in view. To go back to a world map, set _Type_ back to _Vector & Raster_, which removes the image.
+The map then shows the image instead of the world map and opens with the whole image in view. To go back to a world map, set _Type_ back to _Vector & Raster_. The image is switched off rather than removed: its relation is renamed to `~disabled:map:image`, so setting _Type_ to _Custom image_ again brings back the same image, with its coordinates. An image that the geo map inherits from a parent note or a template can only be switched off on the note that holds it.
The image note is stored in a `~map:image` [relation](../../Advanced%20Usage/Attributes/Relations.md) of the geo map, which can also be added by hand.
diff --git a/packages/commons/src/lib/builtin_attributes.spec.ts b/packages/commons/src/lib/builtin_attributes.spec.ts
index dc00e2ff2c..20992a3f1d 100644
--- a/packages/commons/src/lib/builtin_attributes.spec.ts
+++ b/packages/commons/src/lib/builtin_attributes.spec.ts
@@ -65,6 +65,8 @@ describe("derived name types", () => {
// Dangerous attributes get their `disabled:` form generated, rather than enumerated by hand.
const disabledLabel: LabelNames = "disabled:webViewSrc";
const disabledRelation: RelationNames = "disabled:renderNote";
+ // So do the harmless ones that opt in to being switched off.
+ const disabledImage: RelationNames = "disabled:map:image";
const flag: FilterLabelsByType<boolean> = "archived";
const text: FilterLabelsByType<string> = "searchString";
@@ -76,7 +78,9 @@ describe("derived name types", () => {
// @ts-expect-error `archived` is a flag, so it is absent from the string-valued subset
const wrongValueType: FilterLabelsByType<string> = "archived";
- expect([ label, relation, disabledLabel, disabledRelation, flag, text, count, unknown, wrongValueType ])
- .toHaveLength(9);
+ expect([
+ label, relation, disabledLabel, disabledRelation, disabledImage, flag, text, count, unknown,
+ wrongValueType
+ ]).toHaveLength(10);
});
});
diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.ts
index e67fb70061..60f5c859dc 100644
--- a/packages/commons/src/lib/builtin_attributes.ts
+++ b/packages/commons/src/lib/builtin_attributes.ts
@@ -72,6 +72,12 @@ export interface BuiltinRelation {
type: "relation";
name: string;
isDangerous?: boolean;
+ /**
+ * Whether the relation can be switched off by a `disabled:` prefix, keeping its target, although
+ * it is not dangerous. Gives it a `disabled:*` member of {@link RelationNames}, as a dangerous
+ * one has.
+ */
+ canBeDisabled?: boolean;
}
const BUILTIN_ATTRIBUTES = [
@@ -365,8 +371,9 @@ const BUILTIN_ATTRIBUTES = [
{ type: "relation", name: "runOnChildNoteCreation", isDangerous: true },
{ type: "relation", name: "runOnAttributeCreation", isDangerous: true },
{ type: "relation", name: "runOnAttributeChange", isDangerous: true },
- // The image a geo map draws in place of a world map.
- { type: "relation", name: "map:image" },
+ // The image a geo map draws in place of a world map. Switched off rather than removed when the
+ // map goes back to a world map, so the image is kept for switching back.
+ { type: "relation", name: "map:image", canBeDisabled: true },
{ type: "relation", name: "template" },
// Set on a template: where a note created from it goes when no parent is picked explicitly.
{ type: "relation", name: "template:newNoteDefaultParent" },
@@ -408,10 +415,11 @@ type RelationEntry = Extract<BuiltinAttributeEntry, { type: "relation" }>;
/**
* The `disabled:`-prefixed forms of the dangerous entries in `T`, which is how a dangerous attribute is
- * neutralised without losing its value. Derived rather than enumerated, so marking an attribute
- * dangerous is enough to make its disabled form known to the type system.
+ * neutralised without losing its value, and of the ones that opt in with `canBeDisabled`. Derived
+ * rather than enumerated, so either flag makes the disabled form known to the type system.
*/
-type DisabledForms<T extends { name: string }> = `disabled:${Extract<T, { isDangerous: true }>["name"]}`;
+type DisabledForms<T extends { name: string }> =
+ `disabled:${Extract<T, { isDangerous: true } | { canBeDisabled: true }>["name"]}`;
/**
* What each label type is read as in TypeScript. Written as a mapped type over {@link LabelType} so a