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
feat(share): show shared collections through the app's note list
Elian Doranabaa4565f9e5
diff --git a/apps/client/src/entities/fnote.ts b/apps/client/src/entities/fnote.tsindex 5765267837..16d5348af5 100644--- a/apps/client/src/entities/fnote.ts+++ b/apps/client/src/entities/fnote.ts@@ -259,8 +259,8 @@ export default class FNote {const isHiddenNote = this.noteId.startsWith("_");const isSearchNote = this.type === "search";if (!includeArchived && !isHiddenNote && !isSearchNote) {- const { default: search } = await import("../services/search.js");- const unorderedIds = new Set(await search.searchForNoteIds(`note.parents.noteId="${this.noteId}" #!archived`));+ const query = `note.parents.noteId="${this.noteId}" #!archived`;+ const unorderedIds = new Set(await this.froca.searchNoteIds(query, this.noteId));const results: string[] = [];for (const id of this.children) {if (unorderedIds.has(id)) {diff --git a/apps/client/src/services/froca-interface.ts b/apps/client/src/services/froca-interface.tsindex 3058c1bff3..ee01483e7f 100644--- a/apps/client/src/services/froca-interface.ts+++ b/apps/client/src/services/froca-interface.ts@@ -27,6 +27,8 @@ export interface FrocaSource {getSiblingAttachments(attachmentId: string): Promise<FAttachmentRow[]>;getAttachments(noteId: string): Promise<FAttachmentRow[]>;getBlob(entityType: string, entityId: string): Promise<FBlobRow>;+ /** The ids of the notes below `ancestorNoteId` that match the search `query`. */+ searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;}export interface Froca {@@ -46,4 +48,5 @@ export interface Froca {getBranches(branchIds: string[], silentNotFoundError?: boolean): FBranch[];getAttachmentsForNote(noteId: string): Promise<FAttachment[]>;+ searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;}diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.tsindex acfd20a6be..189a027637 100644--- a/apps/client/src/services/froca.ts+++ b/apps/client/src/services/froca.ts@@ -399,6 +399,10 @@ class FrocaImpl implements Froca {});}+ searchNoteIds(query: string, ancestorNoteId: string) {+ return this.source.searchNoteIds(query, ancestorNoteId);+ }+async getBlob(entityType: string, entityId: string): Promise<FBlob | null> {// I'm not sure why we're not using blobIds directly, it would save us this composite key ...// perhaps one benefit is that we're always requesting the latest blob, not relying on perhaps faulty/slow@@ -431,7 +435,11 @@ const SERVER_SOURCE: FrocaSource = {server.getWithSilentNotFound<FAttachmentRow[]>(`attachments/${attachmentId}/all`),getAttachments: (noteId) => server.get<FAttachmentRow[]>(`notes/${noteId}/attachments`),getBlob: (entityType, entityId) =>- server.getWithSilentNotFound<FBlobRow>(`${entityType}/${entityId}/blob`)+ server.getWithSilentNotFound<FBlobRow>(`${entityType}/${entityId}/blob`),+ searchNoteIds: async (query) => {+ const { default: search } = await import("./search.js");+ return await search.searchForNoteIds(query);+ }};const froca = new FrocaImpl();diff --git a/apps/client/src/widgets/collections/NoteList.tsx b/apps/client/src/widgets/collections/NoteList.tsxindex 28064916c1..eca49e22d7 100644--- a/apps/client/src/widgets/collections/NoteList.tsx+++ b/apps/client/src/widgets/collections/NoteList.tsx@@ -32,6 +32,7 @@ interface NoteListProps {onReady?: (data: PrintReport) => void;onProgressChanged?(progress: number): void;showTextRepresentation?: boolean;+ onOpenNote?: (noteId: string) => void;}type LazyLoadedComponent = ((props: ViewModeProps<any>) => VNode<any> | undefined);diff --git a/apps/client/src/widgets/collections/view_mode_storage.spec.ts b/apps/client/src/widgets/collections/view_mode_storage.spec.tsindex a7073f5650..ca66b50388 100644--- a/apps/client/src/widgets/collections/view_mode_storage.spec.ts+++ b/apps/client/src/widgets/collections/view_mode_storage.spec.ts@@ -28,7 +28,12 @@ interface Config extends Record<string, unknown> {/** A note carrying one `viewConfig` attachment, as a collection view's owner does. */function noteWithStoredConfig(content: string | undefined) {- const attachment = { attachmentId: "att-1", title: "geoMap.json" };+ // The blob is read through `server.get`'s mock, which each test points at the stored content.+ const attachment = {+ attachmentId: "att-1",+ title: "geoMap.json",+ getBlob: () => server.get("attachments/att-1/blob")+ };vi.mocked(server.get).mockResolvedValue(content === undefined ? null : { content });return {noteId: "note-1",diff --git a/apps/client/src/widgets/collections/view_mode_storage.ts b/apps/client/src/widgets/collections/view_mode_storage.tsindex c9a3c99544..a3eba2a166 100644--- a/apps/client/src/widgets/collections/view_mode_storage.ts+++ b/apps/client/src/widgets/collections/view_mode_storage.ts@@ -125,7 +125,7 @@ export default class ViewModeStorage<T extends object> {}const attachment = existingAttachments[0];- const attachmentData = await server.get<{ content: string } | null>(`attachments/${attachment.attachmentId}/blob`);- return attachmentData?.content ?? "{}";+ const blob = await attachment.getBlob();+ return blob?.content ?? "{}";}}diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex 62c9cb53da..bc534d83f3 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -136,12 +136,9 @@ const LAZY_MODULES: Record<string, { specifier: string; importer: string }[]> ={ specifier: "mermaid", importer: "content/mermaid.ts" },{ specifier: "./mermaid_zoom.js", importer: "content/mermaid.ts" }],- calendar: [- { specifier: "./calendar_view.js", importer: "content/calendar.ts" }- ],- geomap: [+ collection: [{ specifier: "./app_globals.js", importer: "content/app_view.ts" },- { specifier: "./content/geomap_view.js", importer: "index.ts" }+ { specifier: "./content/collection_view.js", importer: "index.ts" }]};diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsxindex 59d0b7ed8e..e30378389a 100644--- a/packages/share-theme/src/content/app_host.tsx+++ b/packages/share-theme/src/content/app_host.tsx@@ -13,8 +13,6 @@ import { createShareFrocaSource, type ShareFrocaRows } from "./share_froca_sourc/** What core embeds next to an app view on a shared page. */export interface AppPayload extends ShareFrocaRows {options: Record<string, OptionValue | null>;- /** The view the collection saved, such as a map's position, for the view to start from. */- viewConfig?: unknown;}export interface HostedApp {@@ -54,7 +52,7 @@ export default function ShareAppHost({ noteId, payload, children }: ShareAppHost}function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {- const { options: optionValues, links, viewConfig: _viewConfig, ...rows } = payload;+ const { options: optionValues, links, ...rows } = payload;options.load(Object.fromEntries(Object.entries(optionValues).flatMap(([ name, value ]) => (value === null ? [] : [ [ name, value ] ]))));diff --git a/packages/share-theme/src/content/calendar.ts b/packages/share-theme/src/content/calendar.tsdeleted file mode 100644index 9935cfaeb2..0000000000--- a/packages/share-theme/src/content/calendar.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Draws the calendar collection on the page, if there is one, with the app's own calendar. The- * view and FullCalendar load on demand, as only a calendar page needs them.- */-export default async function setupCalendar() {- const container = document.querySelector<HTMLElement>("#content .share-calendar");- const data = document.querySelector("#content .share-froca");- if (!container || !data?.textContent) {- return;- }-- const { default: mountCalendar } = await import("./calendar_view.js");- await mountCalendar(container, JSON.parse(data.textContent));-}diff --git a/packages/share-theme/src/content/calendar_view.tsx b/packages/share-theme/src/content/calendar_view.tsxdeleted file mode 100644index 20dfc6f37e..0000000000--- a/packages/share-theme/src/content/calendar_view.tsx+++ /dev/null@@ -1,68 +0,0 @@-import "fullcalendar/skeleton.css";-import "fullcalendar/themes/forma/theme.css";-import "@triliumnext/client/src/widgets/collections/calendar/palette.css";--import froca from "@triliumnext/client/src/services/froca.js";-import Calendar from "@triliumnext/client/src/widgets/collections/calendar/calendar.js";-import { buildEvents } from "@triliumnext/client/src/widgets/collections/calendar/event_builder.js";-import type { EventClickInfo, EventInput, PluginInput } from "fullcalendar";-import { render } from "preact";--type SubtreeResponse = Parameters<typeof froca.addResp>[0];--/** The notes of a calendar, as core's `buildFrocaPayload()` embeds them in the page. */-export interface FrocaPayload extends SubtreeResponse {- links: Record<string, string>;-}--/**- * Loads the notes of the calendar into froca, so that the app's `buildEvents()` reads them as it- * does in the app, and draws the app's calendar from its events. A click on an event opens the- * note's shared page.- */-export default async function mountCalendar(container: HTMLElement, payload: FrocaPayload) {- froca.addResp(payload);- const noteId = container.dataset.noteId ?? "";- const childNoteIds = froca.getNoteFromCache(noteId)?.getChildNoteIds() ?? [];- const [ events, plugins ] = await Promise.all([ buildEvents(childNoteIds), loadPlugins() ]);-- render(<ShareCalendar events={events} plugins={plugins} links={payload.links} />, container);-}--interface ShareCalendarProps {- events: EventInput[];- plugins: PluginInput[];- links: Record<string, string>;-}--function ShareCalendar({ events, plugins, links }: ShareCalendarProps) {- const onEventClick = (info: EventClickInfo) => {- info.jsEvent.preventDefault();- const link = links[String(info.event.extendedProps.noteId)];- if (link) {- window.location.href = link;- }- };-- return (- <Calendar- events={events}- plugins={plugins}- initialView="dayGridMonth"- headerToolbar={{ start: "title", end: "today prev,next" }}- height="100%"- editable={false}- eventClick={onEventClick}- />- );-}--/** The read-only subset of the plugins the app's calendar loads. */-async function loadPlugins(): Promise<PluginInput[]> {- const modules = await Promise.all([- import("fullcalendar/themes/forma"),- import("fullcalendar/daygrid"),- import("@fullcalendar/rrule")- ]);- return modules.map((module) => module.default);-}diff --git a/packages/share-theme/src/content/collection_view.css b/packages/share-theme/src/content/collection_view.cssindex 7f80ec2e66..13ad7f996c 100644--- a/packages/share-theme/src/content/collection_view.css+++ b/packages/share-theme/src/content/collection_view.css@@ -17,10 +17,17 @@ body:has(#content.collection-view) {min-height: 0;}- #content > .share-calendar,- #content > .share-geomap {+ #content > .share-collection {+ position: relative;+ display: flex;+ flex-direction: column;flex: 1;min-height: 0;++ > .note-list-widget {+ flex: 1;+ min-height: 0;+ }}@media (max-width: 48em) {diff --git a/packages/share-theme/src/content/collection_view.tsx b/packages/share-theme/src/content/collection_view.tsxnew file mode 100644index 0000000000..7968771977--- /dev/null+++ b/packages/share-theme/src/content/collection_view.tsx@@ -0,0 +1,25 @@+import { EmbeddedNoteList } from "@triliumnext/client/src/widgets/collections/NoteList.js";+import { render } from "preact";++import ShareAppHost, { type AppPayload } from "./app_host.js";++/**+ * Mounts the app's note list over the collection, which picks the collection's view from its+ * `#viewType` and opens the notes the view selects on their shared pages.+ */+export default function mountCollection(container: HTMLElement, payload: AppPayload) {+ render(+ <ShareAppHost noteId={container.dataset.noteId ?? ""} payload={payload}>+ {({ note, openNote }) => (+ <EmbeddedNoteList+ note={note}+ notePath={note.noteId}+ ntxId={null}+ media="screen"+ onOpenNote={openNote}+ />+ )}+ </ShareAppHost>,+ container+ );+}diff --git a/packages/share-theme/src/content/geomap_view.css b/packages/share-theme/src/content/geomap_view.cssdeleted file mode 100644index 2850334986..0000000000--- a/packages/share-theme/src/content/geomap_view.css+++ /dev/null@@ -1,3 +0,0 @@-.share-geomap {- position: relative;-}diff --git a/packages/share-theme/src/content/geomap_view.tsx b/packages/share-theme/src/content/geomap_view.tsxdeleted file mode 100644index 9e8b1394f0..0000000000--- a/packages/share-theme/src/content/geomap_view.tsx+++ /dev/null@@ -1,28 +0,0 @@-import "./geomap_view.css";--import GeoView, { type MapData } from "@triliumnext/client/src/widgets/collections/geomap/index.js";-import { render } from "preact";--import ShareAppHost, { type AppPayload } from "./app_host.js";--/** Mounts the app's `GeoView` over the map's notes and its saved view. */-export default function mountGeoMap(container: HTMLElement, payload: AppPayload) {- render(- <ShareAppHost noteId={container.dataset.noteId ?? ""} payload={payload}>- {({ note, openNote }) => (- <GeoView- note={note}- notePath={note.noteId}- noteIds={note.getChildNoteIds()}- highlightedTokens={null}- viewConfig={payload.viewConfig as MapData | undefined}- saveConfig={() => {}}- media="screen"- onReady={() => {}}- onOpenNote={openNote}- />- )}- </ShareAppHost>,- container- );-}diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.tsindex 5fad501457..a049a3df79 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -21,7 +21,12 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSourgetJson(`api/attachments/${encodeURIComponent(attachmentId)}/all`),getAttachments: (noteId) => getJson(`api/notes/${encodeURIComponent(noteId)}/attachments`),getBlob: (entityType, entityId) =>- getJson(`api/${entityType}/${encodeURIComponent(entityId)}/blob`)+ getJson(`api/${entityType}/${encodeURIComponent(entityId)}/blob`),+ searchNoteIds: async (query, ancestorNoteId) => {+ const params = new URLSearchParams({ search: query, ancestorNoteId });+ const { results } = await getJson<{ results: { noteId: string }[] }>(`api/notes?${params}`);+ return results.map((result) => result.noteId);+ }};}diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex 798827658b..72caf40b20 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -18,7 +18,6 @@ import "./content/adaptive_colors.css";import "./content/link_embed.css";import "./content/collection_view.css";import setupMath from "./content/math.js";-import setupCalendar from "./content/calendar.js";import setupAppView from "./content/app_view.js";import setupMermaid from "./content/mermaid.js";import "virtual:code-themes.css";@@ -74,8 +73,7 @@ document.addEventListener("DOMContentLoaded", () => {} else if (classList.contains("type-mermaid")) {$try(setupMermaid);} else if (classList.contains("type-book")) {- $try(setupCalendar);- $try(() => setupAppView(".share-geomap", () => import("./content/geomap_view.js")));+ $try(() => setupAppView(".share-collection", () => import("./content/collection_view.js")));}});diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex f2d57e9240..8c38276da2 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -494,11 +494,8 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}} else if (note.type === "file") {renderFile(note, result);} else if (note.type === "book" && !(note instanceof BNote)- && getViewType(note) === "calendar") {- renderCalendar(result, note);- } else if (note.type === "book" && !(note instanceof BNote)- && getViewType(note) === "geoMap") {- renderGeoMap(result, note);+ && HOSTED_VIEW_TYPES.has(getViewType(note) ?? "")) {+ renderCollectionView(result, note);} else if (note.type === "book") {result.isEmpty = true;} else if (note.type === "webView") {@@ -908,48 +905,22 @@ function getViewType(note: SNote) {}/**- * Renders a calendar collection as an element the share theme's script draws the client's calendar- * into, from the notes `buildFrocaPayload()` embeds next to it.+ * Renders a collection the share theme shows with the app's own view, through its note list: an+ * element to mount it into, beside the notes and the display options it starts from.*/-function renderCalendar(result: Result, note: SNote) {- const payload = JSON.stringify(buildFrocaPayload(note)).replace(/</g, "\\u003c");- result.isCollectionView = true;- result.content = `<div class="share-calendar" data-note-id="${note.noteId}"></div>`- + `<script type="application/json" class="share-froca">${payload}</script>`;-}--/**- * Renders a geo map collection as an element the share theme's script mounts the app's whole map- * view into, read-only, from the notes, the display options and the saved view embedded next to it.- */-function renderGeoMap(result: Result, note: SNote) {+function renderCollectionView(result: Result, note: SNote) {const payload = {...buildFrocaPayload(note),- viewConfig: getViewConfig(note, "geoMap"),options: Object.fromEntries(SHARED_OPTIONS.map((name) => [ name, options.getOptionOrNull(name) ]))};const json = JSON.stringify(payload).replace(/</g, "\\u003c");result.isCollectionView = true;- result.content = `<div class="share-geomap" data-note-id="${note.noteId}"></div>`+ result.content = `<div class="share-collection" data-note-id="${note.noteId}"></div>`+ `<script type="application/json" class="share-froca">${json}</script>`;}-/**- * The view a collection saved, such as a map's position and zoom, which the app keeps in a- * `<viewType>.json` attachment.- */-function getViewConfig(note: SNote, viewType: string): unknown {- const attachment = note.getAttachmentByTitle(`${viewType}.json`);- if (attachment?.role !== "viewConfig") {- return undefined;- }-- try {- return JSON.parse(String(attachment.getContent()));- } catch {- return undefined;- }-}+/** The view types of the collections the share theme shows with the app's own view. */+const HOSTED_VIEW_TYPES = new Set([ "calendar", "geoMap" ]);/** The options the app's collection views read, which a shared page needs to draw them alike. */const SHARED_OPTIONS = [ "locale", "formattingLocale", "firstDayOfWeek" ] as const;diff --git a/packages/trilium-core/src/share/froca_payload.ts b/packages/trilium-core/src/share/froca_payload.tsindex 1de724bea0..54997d769f 100644--- a/packages/trilium-core/src/share/froca_payload.ts+++ b/packages/trilium-core/src/share/froca_payload.ts@@ -1,5 +1,7 @@import { getShareLink } from "@triliumnext/share-theme/model/page";+import becca from "../becca/becca.js";+import type BNote from "../becca/entities/bnote.js";import * as sanitize from "../services/sanitizer.js";import type SAttachment from "./shaca/entities/sattachment.js";import type SNote from "./shaca/entities/snote.js";@@ -24,7 +26,8 @@ export function buildFrocaPayload(note: SNote) {* Collects `roots`, their visible children and the notes their relations point to (templates and* `#calendar:title` relations), with their owned attributes and the branches between them. Shaca* holds only shared notes, so a relation to a note outside the share is left out, as is every note- * that is protected or that `canAccess` refuses.+ * that is protected or that `canAccess` refuses. A built-in template such as `_template_calendar`+ * is read from becca instead, as it lives in the hidden subtree, so the notes inherit its labels.*/export function buildFrocaRows(roots: SNote[], canAccess: (note: SNote) => boolean = () => true): FrocaRows {const notes = new Map<string, SNote>();@@ -49,6 +52,24 @@ export function buildFrocaRows(roots: SNote[], canAccess: (note: SNote) => boole}const rows: FrocaRows = { notes: [], branches: [], attributes: [], links: {} };+ const templates = new Map<string, BNote>();+ for (const owner of notes.values()) {+ for (const relation of owner.ownedAttributes) {+ const template = relation.type === "relation" && relation.value.startsWith("_template_")+ ? becca.getNote(relation.value) : null;+ if (template && !notes.has(template.noteId)) {+ templates.set(template.noteId, template);+ }+ }+ }+ for (const template of templates.values()) {+ rows.notes.push(getNoteRow(template));+ for (const attribute of template.getOwnedAttributes()) {+ const { attributeId, noteId, type, name, value, position, isInheritable } = attribute;+ rows.attributes.push({ attributeId, noteId, type, name, value, position, isInheritable: !!isInheritable });+ }+ }+for (const included of notes.values()) {rows.notes.push(getNoteRow(included));rows.links[included.noteId] = getShareLink(included, sanitize.sanitizeUrl).href;@@ -58,7 +79,7 @@ export function buildFrocaRows(roots: SNote[], canAccess: (note: SNote) => boole}}for (const attribute of included.ownedAttributes) {- if (attribute.type === "label" || notes.has(attribute.value)) {+ if (attribute.type === "label" || notes.has(attribute.value) || templates.has(attribute.value)) {rows.attributes.push(attribute.getPojo());}}@@ -91,13 +112,13 @@ export function getBlobRow(entity: SNote | SAttachment) {};}-function getNoteRow(note: SNote) {+function getNoteRow(note: SNote | BNote) {return {noteId: note.noteId,title: note.title,- isProtected: note.isProtected,+ isProtected: !!note.isProtected,type: note.type,mime: note.mime,- blobId: note.utcDateModified+ blobId: note.utcDateModified ?? ""};}diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.tsindex 443a1a8420..221876bd5e 100644--- a/packages/trilium-core/src/share/handlers.spec.ts+++ b/packages/trilium-core/src/share/handlers.spec.ts@@ -457,6 +457,7 @@ describe("share handlers", () => {expect(JSON.parse(String(anonymous.body))).toEqual({results: [ {id: "visible",+ noteId: "visible",title: "Visible",score: 7,path: "Docs / Visible",diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsindex 0e93b232f1..37a48dcc8c 100644--- a/packages/trilium-core/src/share/handlers.ts+++ b/packages/trilium-core/src/share/handlers.ts@@ -325,6 +325,7 @@ function searchNotes(req: ShareRequest): ShareReply {return {id: fullNote.shareId,+ noteId: fullNote.noteId,title: fullNote.title,score: sr.score,path: pathTitle,