Files
Docwell/Packages/editor/src/embeds.ts
T
tajniak81andClaude Opus 5.5 40d515d15b Add toggles, embeds, link cards, block links, archive, version diff, space export and desktop 1.0
Editor:
- Toggles (Tiptap Details). Open state is per reader, not saved.
- Embeds for YouTube, Vimeo, Loom, Figma, CodePen, Spotify, Google Docs
  and Maps, in sandboxed frames. Other addresses become link cards.
- Link cards with title, description and picture read by docwell-server
  (GET /link-preview). The fetcher refuses private, loopback, link-local
  and CGNAT addresses after DNS resolution, redirects included.
- Block links: a margin button gives a block a short id and copies
  /p/<id>#b-<block>. Opening one jumps to the block and flashes it.
- Markdown, HTML and PDF exports handle the new blocks; HTML import reads
  <details> as a toggle.

Pages and spaces:
- History gets a Changes view: block and word diff against the previous
  version or the page as it is now.
- Archive: archived pages leave the tree and become read-only but stay
  readable; a space's Archive lists them with Unarchive. New migration
  (pages.archived_at) and page.archived / page.unarchived webhook events.
- Full space export (GET /spaces/{id}/export): a zip of Markdown or HTML
  files with subpages in folders, an index, and attachments under _files/.
  Links between exported pages and to attachments become relative paths.

Desktop 1.0:
- Several servers, each with its own sign-in; old settings files carry over.
- Session tokens in the system keychain (go-keyring), moved out of
  localStorage on first start.
- Native menu bar (File, Edit, View, Window, Help) with a Server submenu.
- docwell:// links may point at a block.
- Release workflow builds Windows NSIS, macOS DMG and Linux deb, rpm and
  AppImage installers and attaches them to the release;
  build/set-version.mjs stamps the version into their metadata.

Not yet run: the release workflow, the desktop menus by eye, and macOS or
Linux builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:14:14 +01:00

375 lines
12 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { Node, mergeAttributes, type Editor } from "@tiptap/core";
import type { EditorLabels } from "./labels";
import { editSource } from "./source";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
embeds: {
insertEmbed: (url: string) => ReturnType;
insertLinkCard: (card: LinkPreview) => ReturnType;
};
}
}
/** What a link card shows. Stored in the document, so readers fetch nothing. */
export interface LinkPreview {
url: string;
title?: string;
description?: string;
image?: string;
site?: string;
}
/**
* Fetches a page's title, description and picture for a link card. Pages on
* other sites can't be read from the browser, so hosts ask docwell-server.
*/
export interface LinkHost {
preview(url: string): Promise<LinkPreview>;
}
// Each provider turns a page address into its player address. Only these
// sites are framed; any other address becomes a link card instead.
const providers: { pattern: RegExp; src: (m: RegExpExecArray, url: URL) => string; ratio?: string }[] = [
{
pattern: /^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,
src: (m) => `https://www.youtube-nocookie.com/embed/${m[1]}`,
},
{ pattern: /^https:\/\/youtu\.be\/([\w-]{11})/, src: (m) => `https://www.youtube-nocookie.com/embed/${m[1]}` },
{
pattern: /^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,
src: (m) => `https://player.vimeo.com/video/${m[1]}`,
},
{
pattern: /^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,
src: (m) => `https://www.loom.com/embed/${m[1]}`,
},
{
pattern: /^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,
src: (_m, url) => `https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(url.href)}`,
},
{
pattern: /^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,
src: (m) => `https://codepen.io/${m[1]}/embed/${m[2]}?default-tab=result`,
},
{
pattern: /^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,
src: (m) => `https://open.spotify.com/embed/${m[1]}/${m[2]}`,
ratio: "audio",
},
{
pattern: /^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,
src: (m) => `https://docs.google.com/${m[1]}/d/${m[2]}/preview`,
ratio: "tall",
},
{ pattern: /^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/, src: (_m, url) => url.href },
];
/** The player address for a page on a supported site, or null. */
export function embedSource(raw: string): { src: string; ratio: string } | null {
let url: URL;
try {
url = new URL(raw.trim());
} catch {
return null;
}
for (const p of providers) {
const m = p.pattern.exec(url.href);
if (m) return { src: p.src(m, url), ratio: p.ratio ?? "video" };
}
return null;
}
/** An http(s) address, or "" for anything else (javascript:, data:, typos). */
export function webUrl(raw: string): string {
try {
const url = new URL(raw.trim());
return url.protocol === "https:" || url.protocol === "http:" ? url.href : "";
} catch {
return "";
}
}
const hostOf = (url: string) => {
try {
return new URL(url).hostname.replace(/^www\./, "");
} catch {
return url;
}
};
/** Asks for an address under anchor and resolves with it ("" when cancelled). */
function askUrl(editor: Editor, labels: EditorLabels, label: string): Promise<string> {
const { node } = editor.view.domAtPos(editor.state.selection.from);
const el = node instanceof HTMLElement ? node : (node.parentElement ?? editor.view.dom);
return new Promise((resolve) => {
const l = labels.blocks;
editSource({
anchor: el,
value: "https://",
label,
labels: { done: l.done, cancel: l.cancel, remove: l.remove },
onSave: (v) => resolve(webUrl(v)),
onCancel: () => resolve(""),
});
});
}
/** "/embed": asks for an address and frames it, or makes a card when the site can't be framed. */
export async function promptEmbed(
editor: Editor,
labels: EditorLabels,
links?: LinkHost,
onError?: (e: unknown) => void,
) {
const url = await askUrl(editor, labels, labels.blocks.embedUrl);
if (!url) return;
if (embedSource(url)) editor.chain().focus().insertEmbed(url).run();
else await insertCard(editor, url, links, onError);
}
/** "/bookmark": asks for an address and inserts a link card for it. */
export async function promptLinkCard(
editor: Editor,
labels: EditorLabels,
links?: LinkHost,
onError?: (e: unknown) => void,
) {
const url = await askUrl(editor, labels, labels.blocks.linkUrl);
if (url) await insertCard(editor, url, links, onError);
}
async function insertCard(editor: Editor, url: string, links?: LinkHost, onError?: (e: unknown) => void) {
let card: LinkPreview = { url };
if (links) {
try {
card = { ...(await links.preview(url)), url };
} catch (e) {
// A card with just the address is still useful.
onError?.(e);
}
}
editor.chain().focus().insertLinkCard(card).run();
}
/**
* A video, design or document from a supported site, shown in a sandboxed
* frame. Only the page address is stored; each client works out the player.
*/
export const Embed = Node.create<{ labels: EditorLabels | null }>({
name: "embed",
group: "block",
atom: true,
draggable: true,
addOptions() {
return { labels: null };
},
addAttributes() {
return {
url: {
default: "",
parseHTML: (el) => el.getAttribute("data-url") ?? "",
renderHTML: (attrs) => ({ "data-url": attrs.url }),
},
};
},
parseHTML() {
return [{ tag: "div[data-type='embed']" }];
},
renderHTML({ node, HTMLAttributes }) {
const url = webUrl(String(node.attrs.url));
return ["div", mergeAttributes(HTMLAttributes, { "data-type": "embed" }), ["a", { href: url }, url]];
},
addCommands() {
return {
insertEmbed:
(url) =>
({ commands }) =>
commands.insertContent({ type: this.name, attrs: { url } }),
};
},
addNodeView() {
return ({ node }) => {
const labels = this.options.labels!.blocks;
const dom = document.createElement("figure");
dom.className = "dw-embed";
dom.setAttribute("data-type", "embed");
dom.contentEditable = "false";
const draw = (raw: string) => {
const url = webUrl(raw);
const source = embedSource(url);
dom.replaceChildren();
if (!source) {
// Not framable (any more): keep the address as a link.
const a = document.createElement("a");
a.href = url;
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = url || labels.embedInvalid;
dom.append(a);
return;
}
dom.dataset.ratio = source.ratio;
const frame = document.createElement("iframe");
frame.className = "dw-embed__frame";
frame.src = source.src;
frame.title = `${labels.embed}: ${hostOf(url)}`;
frame.loading = "lazy";
frame.allow = "fullscreen; picture-in-picture; encrypted-media; clipboard-write";
frame.referrerPolicy = "strict-origin-when-cross-origin";
// The players need scripts and their own origin; nothing else.
frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-presentation");
const caption = document.createElement("figcaption");
caption.className = "dw-embed__caption";
const a = document.createElement("a");
a.href = url;
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = hostOf(url);
caption.append(a);
dom.append(frame, caption);
};
let current = String(node.attrs.url);
draw(current);
return {
dom,
update: (n) => {
if (n.type.name !== "embed") return false;
if (n.attrs.url !== current) draw((current = String(n.attrs.url)));
return true;
},
ignoreMutation: () => true,
stopEvent: (e) => e.target instanceof Element && !!e.target.closest("a"),
};
};
},
});
/** A link shown as a card with the page's title, description and picture. */
export const LinkCard = Node.create<{ labels: EditorLabels | null }>({
name: "linkCard",
group: "block",
atom: true,
draggable: true,
addOptions() {
return { labels: null };
},
addAttributes() {
const attr = (name: string) => ({
default: "",
parseHTML: (el: HTMLElement) => el.getAttribute(`data-${name}`) ?? "",
renderHTML: (attrs: Record<string, unknown>) => ({ [`data-${name}`]: attrs[name] }),
});
return {
url: attr("url"),
title: attr("title"),
description: attr("description"),
image: attr("image"),
site: attr("site"),
};
},
parseHTML() {
return [{ tag: "div[data-type='link-card']" }];
},
renderHTML({ node, HTMLAttributes }) {
const url = webUrl(String(node.attrs.url));
return [
"div",
mergeAttributes(HTMLAttributes, { "data-type": "link-card" }),
["a", { href: url }, String(node.attrs.title || url)],
];
},
addCommands() {
return {
insertLinkCard:
(card) =>
({ commands }) =>
commands.insertContent({
type: this.name,
attrs: {
url: card.url,
title: card.title ?? "",
description: card.description ?? "",
image: card.image ?? "",
site: card.site ?? "",
},
}),
};
},
addNodeView() {
return ({ node }) => {
const dom = document.createElement("a");
dom.className = "dw-linkcard";
dom.setAttribute("data-type", "link-card");
dom.contentEditable = "false";
dom.target = "_blank";
dom.rel = "noopener noreferrer";
const draw = (attrs: Record<string, unknown>) => {
const url = webUrl(String(attrs.url));
dom.href = url;
dom.replaceChildren();
const text = document.createElement("span");
text.className = "dw-linkcard__text";
const title = document.createElement("span");
title.className = "dw-linkcard__title";
title.textContent = String(attrs.title || "") || hostOf(url);
text.append(title);
if (attrs.description) {
const desc = document.createElement("span");
desc.className = "dw-linkcard__desc";
desc.textContent = String(attrs.description);
text.append(desc);
}
const site = document.createElement("span");
site.className = "dw-linkcard__site";
site.textContent = String(attrs.site || "") || hostOf(url);
text.append(site);
dom.append(text);
const image = webUrl(String(attrs.image || ""));
if (image.startsWith("https:")) {
const img = document.createElement("img");
img.className = "dw-linkcard__image";
img.src = image;
img.alt = "";
img.loading = "lazy";
// Other sites don't learn which page their picture is shown on.
img.referrerPolicy = "no-referrer";
img.onerror = () => img.remove();
dom.append(img);
}
};
let current = node;
draw(node.attrs);
// Editing places the caret; following the link needs Ctrl/Cmd, as with text links.
dom.addEventListener("click", (e) => {
const view = this.editor.view;
if (view.editable && !(e.ctrlKey || e.metaKey)) e.preventDefault();
});
return {
dom,
update: (n) => {
if (n.type.name !== "linkCard") return false;
if (n.attrs !== current.attrs) draw(n.attrs);
current = n;
return true;
},
ignoreMutation: () => true,
};
};
},
});