// SPDX-License-Identifier: AGPL-3.0-or-later // Links to one record of a database: the page's address plus // "#r--". Opening one scrolls to the database and // opens the record beside the page. Records stay part of their page: the // link needs the page's own access, nothing more. import type { Editor } from "@tiptap/core"; const ID = "[A-Za-z0-9]{1,32}"; /** The #fragment of a link to a record. */ export const recordHash = (database: string, row: string) => `#r-${database}-${row}`; /** The database and record in a link's #fragment, or null. */ export function linkedRecord(hash: string): { database: string; row: string } | null { const m = new RegExp(`^#?r-(${ID})-(${ID})$`).exec(hash); return m ? { database: m[1]!, row: m[2]! } : null; } /** The event a database block listens for to open one of its records. */ export const OPEN_RECORD = "dw-open-record"; export interface OpenRecordDetail { row: string; /** Set by the block when it has the record and opened it. */ found?: boolean; } /** * Opens a record of the page's database. Returns false while the page does * not show it (yet): the document may still be loading, or it was deleted. */ export function openRecord(editor: Editor, database: string, row: string): boolean { let pos = -1; editor.state.doc.descendants((n, p) => { if (pos >= 0) return false; if (n.type.name === "database" && n.attrs.id === database) pos = p; return true; }); if (pos < 0) return false; const dom = editor.view.nodeDOM(pos); if (!(dom instanceof HTMLElement)) return false; const detail: OpenRecordDetail = { row }; dom.dispatchEvent(new CustomEvent(OPEN_RECORD, { detail })); return !!detail.found; } /** Copies text to the clipboard; resolves false when the browser refused. */ export async function copyText(text: string): Promise { try { await navigator.clipboard.writeText(text); return true; } catch { return false; } }