Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

improvement: load visible mobile link previews with backend caching (#393)

Ahmad Othman Ammar Adif3bd992c000a
diff --git a/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts b/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts
index 3443a164..41f25293 100644
--- a/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts
+++ b/apps/api/src/modules/link-previews/__tests__/integration/link-previews.test.ts
@@ -13,8 +13,15 @@ describe('link previews', () => {
'not a URL',
'file:///etc/passwd',
'https://user:[email protected]',
+ 'https://[email protected]',
'http://127.0.0.1',
+ 'http://127.0.0.1#cached-fragment',
+ 'http://2130706433',
+ 'http://[::ffff:127.0.0.1]',
+ 'http://localhost',
'https://169.254.169.254',
+ 'http://100.64.0.1',
+ 'https://192.0.2.1',
]) {
const result = await client['link-previews'].get({ query: { url } });
expect(result.status).toBe(400);
diff --git a/apps/api/src/modules/link-previews/__tests__/unit/cache.test.ts b/apps/api/src/modules/link-previews/__tests__/unit/cache.test.ts
new file mode 100644
index 00000000..f98ff048
--- /dev/null
+++ b/apps/api/src/modules/link-previews/__tests__/unit/cache.test.ts
@@ -0,0 +1,221 @@
+import { afterEach, beforeEach, describe, expect, it, setSystemTime } from 'bun:test';
+import { LinkPreviewCache, linkPreviewMaxAge } from '../../cache';
+import type { LinkPreview } from '../../metadata';
+
+const START = new Date('2026-01-01T00:00:00Z').getTime();
+
+function preview(url: URL, fields: Partial<LinkPreview> = {}): LinkPreview {
+ return {
+ url: url.href,
+ title: 'Example',
+ description: null,
+ image: null,
+ siteName: null,
+ ...fields,
+ };
+}
+
+describe('LinkPreviewCache', () => {
+ beforeEach(() => setSystemTime(START));
+ afterEach(() => setSystemTime());
+
+ it('reuses metadata for five minutes without extending its lifetime on reads', async () => {
+ const cache = new LinkPreviewCache();
+ const url = new URL('https://example.com/article');
+ let loads = 0;
+ const load = async (url: URL) => preview(url, { title: `Version ${++loads}` });
+
+ expect((await cache.get(url, load)).title).toBe('Version 1');
+ setSystemTime(START + 299_999);
+ expect((await cache.get(url, load)).title).toBe('Version 1');
+ setSystemTime(START + 300_000);
+ expect((await cache.get(url, load)).title).toBe('Version 2');
+ expect(loads).toBe(2);
+ });
+
+ it('starts the lifetime when loading finishes', async () => {
+ const cache = new LinkPreviewCache();
+ const url = new URL('https://example.com/article');
+ let finish!: (value: LinkPreview) => void;
+ const response = new Promise<LinkPreview>((resolve) => {
+ finish = resolve;
+ });
+ let loads = 0;
+ const load = async () => {
+ loads++;
+ return response;
+ };
+
+ const pending = cache.get(url, load);
+ setSystemTime(START + 4000);
+ finish(preview(url));
+ await pending;
+ setSystemTime(START + 303_999);
+ await cache.get(url, load);
+ expect(loads).toBe(1);
+ setSystemTime(START + 304_000);
+ await cache.get(url, load);
+ expect(loads).toBe(2);
+ });
+
+ it('retries empty or failed previews after fifteen seconds', async () => {
+ const cache = new LinkPreviewCache();
+ const url = new URL('https://example.com/article');
+ let loads = 0;
+ const load = async (url: URL) => {
+ loads++;
+ return preview(url, { title: null });
+ };
+
+ const empty = await cache.get(url, load);
+ expect(linkPreviewMaxAge(empty)).toBe(15);
+ setSystemTime(START + 14_999);
+ await cache.get(url, load);
+ expect(loads).toBe(1);
+ setSystemTime(START + 15_000);
+ await cache.get(url, load);
+ expect(loads).toBe(2);
+ });
+
+ it('caches image-only, description-only and site-name-only metadata for five minutes', () => {
+ const url = new URL('https://example.com/');
+ for (const fields of [
+ { image: 'data:image/png;base64,AA==' },
+ { description: 'Description' },
+ { siteName: 'Example' },
+ ]) {
+ expect(linkPreviewMaxAge(preview(url, { title: null, ...fields }))).toBe(300);
+ }
+ });
+
+ it('normalizes URL serialization and fragments while retaining query order and values', async () => {
+ const cache = new LinkPreviewCache();
+ const loaded: string[] = [];
+ const load = async (url: URL) => {
+ loaded.push(url.href);
+ return preview(url);
+ };
+
+ await cache.get(new URL('https://EXAMPLE.com:443/article?b=2&a=1#first'), load);
+ await cache.get(new URL('https://example.com/article?b=2&a=1#second'), load);
+ await cache.get(new URL('https://example.com/article?a=1&b=2'), load);
+ await cache.get(new URL('https://example.com/article?b=3&a=1'), load);
+ await cache.get(new URL('http://example.com/article?b=2&a=1'), load);
+
+ expect(loaded).toEqual([
+ 'https://example.com/article?b=2&a=1',
+ 'https://example.com/article?a=1&b=2',
+ 'https://example.com/article?b=3&a=1',
+ 'http://example.com/article?b=2&a=1',
+ ]);
+ });
+
+ it('shares a pending request across fragment variants', async () => {
+ const cache = new LinkPreviewCache();
+ const url = new URL('https://example.com/article');
+ let finish!: (value: LinkPreview) => void;
+ const response = new Promise<LinkPreview>((resolve) => {
+ finish = resolve;
+ });
+ let loads = 0;
+ const load = async () => {
+ loads++;
+ return response;
+ };
+
+ const first = cache.get(new URL(`${url.href}#first`), load);
+ const second = cache.get(new URL(`${url.href}#second`), load);
+ await Promise.resolve();
+ expect(loads).toBe(1);
+ finish(preview(url));
+ expect(await Promise.all([first, second])).toEqual([preview(url), preview(url)]);
+ await cache.get(url, load);
+ expect(loads).toBe(1);
+ });
+
+ it('releases rejected pending requests so the next call can succeed', async () => {
+ const cache = new LinkPreviewCache();
+ const url = new URL('https://example.com/article');
+ let reject!: (reason: Error) => void;
+ const response = new Promise<LinkPreview>((_resolve, rejectResponse) => {
+ reject = rejectResponse;
+ });
+ let loads = 0;
+ const load = async () => {
+ loads++;
+ return response;
+ };
+ const pending = Promise.allSettled([cache.get(url, load), cache.get(url, load)]);
+ await Promise.resolve();
+ reject(new Error('Request failed'));
+
+ expect((await pending).map((result) => result.status)).toEqual(['rejected', 'rejected']);
+ expect(loads).toBe(1);
+ expect(await cache.get(url, async (url) => preview(url))).toEqual(preview(url));
+ });
+
+ it('also releases a loader that throws before returning a promise', async () => {
+ const cache = new LinkPreviewCache();
+ const url = new URL('https://example.com/article');
+ await expect(
+ cache.get(url, () => {
+ throw new Error('Request failed');
+ }),
+ ).rejects.toThrow('Request failed');
+ expect(await cache.get(url, async (url) => preview(url))).toEqual(preview(url));
+ });
+
+ it('evicts the least recently read preview at the 128-entry limit', async () => {
+ const cache = new LinkPreviewCache();
+ const loaded = new Map<string, number>();
+ const load = async (url: URL) => {
+ loaded.set(url.href, (loaded.get(url.href) ?? 0) + 1);
+ return preview(url);
+ };
+ const url = (id: number) => new URL(`https://example.com/${id}`);
+
+ for (let id = 0; id < 128; id++) await cache.get(url(id), load);
+ await cache.get(url(0), load);
+ await cache.get(url(128), load);
+ await cache.get(url(0), load);
+ await cache.get(url(1), load);
+
+ expect(loaded.get(url(0).href)).toBe(1);
+ expect(loaded.get(url(1).href)).toBe(2);
+ expect(loaded.get(url(128).href)).toBe(1);
+ });
+
+ it('evicts image-heavy previews before exceeding the 16 MiB string budget', async () => {
+ const cache = new LinkPreviewCache();
+ const loaded: string[] = [];
+ const load = async (url: URL) => {
+ loaded.push(url.href);
+ return preview(url, { image: `data:image/png;base64,${'A'.repeat(2 * 1024 * 1024)}` });
+ };
+ const url = (id: number) => new URL(`https://example.com/${id}`);
+
+ for (let id = 0; id < 4; id++) await cache.get(url(id), load);
+ await cache.get(url(1), load);
+ expect(loaded).toHaveLength(4);
+ await cache.get(url(0), load);
+ expect(loaded).toHaveLength(5);
+ expect(loaded.at(-1)).toBe(url(0).href);
+ });
+
+ it('does not retain an oversized preview or evict useful entries for it', async () => {
+ const cache = new LinkPreviewCache();
+ const small = new URL('https://example.com/small');
+ const large = new URL('https://example.com/large');
+ const loaded: string[] = [];
+ const load = async (url: URL) => {
+ loaded.push(url.href);
+ return preview(url, { image: url.href === large.href ? 'A'.repeat(8 * 1024 * 1024) : null });
+ };
+
+ await cache.get(small, load);
+ await cache.get(large, load);
+ await cache.get(large, load);
+ await cache.get(small, load);
+ expect(loaded).toEqual([small.href, large.href, large.href]);
+ });
+});
diff --git a/apps/api/src/modules/link-previews/cache.ts b/apps/api/src/modules/link-previews/cache.ts
new file mode 100644
index 00000000..1836253f
--- /dev/null
+++ b/apps/api/src/modules/link-previews/cache.ts
@@ -0,0 +1,71 @@
+import type { LinkPreview } from './metadata';
+
+const MAX_ENTRIES = 128;
+const MAX_BYTES = 16 * 1024 * 1024;
+
+export function linkPreviewMaxAge(preview: LinkPreview): number {
+ return preview.title || preview.description || preview.image || preview.siteName ? 300 : 15;
+}
+
+interface CacheEntry {
+ preview: LinkPreview;
+ expiresAt: number;
+ bytes: number;
+}
+
+export class LinkPreviewCache {
+ private entries = new Map<string, CacheEntry>();
+ private pending = new Map<string, Promise<LinkPreview>>();
+ private bytes = 0;
+
+ async get(url: URL, load: (url: URL) => Promise<LinkPreview>): Promise<LinkPreview> {
+ const normalized = new URL(url);
+ normalized.hash = '';
+ const key = normalized.href;
+ const entry = this.entries.get(key);
+ if (entry && entry.expiresAt > Date.now()) {
+ this.entries.delete(key);
+ this.entries.set(key, entry);
+ return entry.preview;
+ }
+ if (entry) this.remove(key, entry);
+
+ const pending = this.pending.get(key);
+ if (pending) return pending;
+ if (this.pending.size >= MAX_ENTRIES) return load(normalized);
+
+ const request = Promise.resolve()
+ .then(() => load(normalized))
+ .then((preview) => {
+ this.store(key, preview);
+ return preview;
+ })
+ .finally(() => this.pending.delete(key));
+ this.pending.set(key, request);
+ return request;
+ }
+
+ private store(key: string, preview: LinkPreview) {
+ // Count UTF-16 storage conservatively, including the base64 image and both URLs.
+ const bytes =
+ 2 *
+ (key.length + Object.values(preview).reduce((size, value) => size + (value?.length ?? 0), 0));
+ if (bytes > MAX_BYTES) return;
+
+ const now = Date.now();
+ for (const [entryKey, entry] of this.entries) {
+ if (entry.expiresAt <= now) this.remove(entryKey, entry);
+ }
+ for (const [entryKey, entry] of this.entries) {
+ if (this.entries.size < MAX_ENTRIES && this.bytes + bytes <= MAX_BYTES) break;
+ this.remove(entryKey, entry);
+ }
+ this.entries.set(key, { preview, expiresAt: now + linkPreviewMaxAge(preview) * 1000, bytes });
+ this.bytes += bytes;
+ }
+
+ private remove(key: string, entry: CacheEntry) {
+ this.entries.delete(key);
+ this.bytes -= entry.bytes;
+ }
+}
diff --git a/apps/api/src/modules/link-previews/index.ts b/apps/api/src/modules/link-previews/index.ts
index 3b92d73c..b0cce521 100644
--- a/apps/api/src/modules/link-previews/index.ts
+++ b/apps/api/src/modules/link-previews/index.ts
@@ -1,6 +1,7 @@
import { Elysia } from 'elysia';
import { authContext } from '#shared/auth-context';
import { errors } from '#shared/responses';
+import { linkPreviewMaxAge } from './cache';
import { linkPreviewQuery, LinkPreviewResponse } from './model';
import { getLinkPreview } from './service';
@@ -11,9 +12,10 @@ export const linkPreviewRoutes = new Elysia({
.use(authContext)
.get(
'/link-previews',
- ({ query, set }) => {
- set.headers['Cache-Control'] = 'private, max-age=300';
- return getLinkPreview(query.url);
+ async ({ query, set }) => {
+ const preview = await getLinkPreview(query.url);
+ set.headers['Cache-Control'] = `private, max-age=${linkPreviewMaxAge(preview)}`;
+ return preview;
},
{
query: linkPreviewQuery,
diff --git a/apps/api/src/modules/link-previews/service.ts b/apps/api/src/modules/link-previews/service.ts
index 96077a4a..0a316bc1 100644
--- a/apps/api/src/modules/link-previews/service.ts
+++ b/apps/api/src/modules/link-previews/service.ts
@@ -1,8 +1,10 @@
import { assertPublicHttpUrl, pinnedFetch, UrlNotAllowedError } from '@repo/net';
import { HttpError } from '#shared/lib';
+import { LinkPreviewCache } from './cache';
import { parseLinkMetadata, type LinkPreview } from './metadata';
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+const previewCache = new LinkPreviewCache();
async function fetchPublic(
url: URL,
@@ -62,7 +64,10 @@ export async function getLinkPreview(raw: string): Promise<LinkPreview> {
if (error instanceof UrlNotAllowedError) throw new HttpError(400, error.message);
throw new HttpError(400, 'The link could not be resolved');
}
- url.hash = '';
+ return previewCache.get(url, (normalized) => fetchLinkPreview(normalized, signal));
+}
+
+async function fetchLinkPreview(url: URL, signal: AbortSignal): Promise<LinkPreview> {
const fallback: LinkPreview = {
url: url.href,
title: null,
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index bd2782ee..226ef529 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "معاينة الرابط",
+ "previewLinks": "معاينة الروابط ({count})",
+ "previewNamedLink": "معاينة {name}",
+ "backToLinks": "العودة إلى الروابط",
+ "openLink": "فتح الرابط",
+ "copyLink": "نسخ الرابط",
+ "copiedLink": "تم النسخ",
+ "editLink": "تعديل الرابط",
+ "retryPreview": "إعادة المحاولة",
+ "copyLinkFailed": "تعذّر نسخ الرابط. حدّد عنوان URL أعلاه وانسخه."
},
"chart": {
"download": "احفظ الرسم البياني",
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index 1f511990..adfa0eba 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "Preview link",
+ "previewLinks": "Preview links ({count})",
+ "previewNamedLink": "Preview {name}",
+ "backToLinks": "Back to links",
+ "openLink": "Open link",
+ "copyLink": "Copy link",
+ "copiedLink": "Copied",
+ "editLink": "Edit link",
+ "retryPreview": "Try again",
+ "copyLinkFailed": "Could not copy the link. Select and copy the URL above."
},
"chart": {
"download": "Save chart",
diff --git a/apps/web/messages/es-ES/common.json b/apps/web/messages/es-ES/common.json
index c5a5f29e..b2766d9f 100644
--- a/apps/web/messages/es-ES/common.json
+++ b/apps/web/messages/es-ES/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Campo personalizado",
"previewAllWorkItems": "Todos los elementos de trabajo",
"previewUpdated": "Actualizado {date}",
- "previewOtherValues": "({count} más)"
+ "previewOtherValues": "({count} más)",
+ "previewLink": "Ver vista previa del enlace",
+ "previewLinks": "Ver vistas previas de los enlaces ({count})",
+ "previewNamedLink": "Ver vista previa de {name}",
+ "backToLinks": "Volver a los enlaces",
+ "openLink": "Abrir enlace",
+ "copyLink": "Copiar enlace",
+ "copiedLink": "Copiado",
+ "editLink": "Editar enlace",
+ "retryPreview": "Intentar de nuevo",
+ "copyLinkFailed": "No se ha podido copiar el enlace. Selecciona y copia la URL de arriba."
},
"chart": {
"download": "Guardar gráfico",
diff --git a/apps/web/messages/fr/common.json b/apps/web/messages/fr/common.json
index 4f08824d..441931de 100644
--- a/apps/web/messages/fr/common.json
+++ b/apps/web/messages/fr/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "Aperçu du lien",
+ "previewLinks": "Aperçu des liens ({count})",
+ "previewNamedLink": "Aperçu de {name}",
+ "backToLinks": "Retour aux liens",
+ "openLink": "Ouvrir le lien",
+ "copyLink": "Copier le lien",
+ "copiedLink": "Copié",
+ "editLink": "Modifier le lien",
+ "retryPreview": "Réessayer",
+ "copyLinkFailed": "Impossible de copier le lien. Sélectionnez et copiez l’URL ci-dessus."
},
"chart": {
"download": "Enregistrer le graphique",
diff --git a/apps/web/messages/id/common.json b/apps/web/messages/id/common.json
index bf685384..198b2aa3 100644
--- a/apps/web/messages/id/common.json
+++ b/apps/web/messages/id/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Bidang kustom",
"previewAllWorkItems": "Semua item pekerjaan",
"previewUpdated": "Diperbarui {date}",
- "previewOtherValues": "({count} lainnya)"
+ "previewOtherValues": "({count} lainnya)",
+ "previewLink": "Pratinjau tautan",
+ "previewLinks": "Pratinjau tautan ({count})",
+ "previewNamedLink": "Pratinjau {name}",
+ "backToLinks": "Kembali ke tautan",
+ "openLink": "Buka tautan",
+ "copyLink": "Salin tautan",
+ "copiedLink": "Tersalin",
+ "editLink": "Edit tautan",
+ "retryPreview": "Coba lagi",
+ "copyLinkFailed": "Tautan tidak dapat disalin. Pilih dan salin URL di atas."
},
"chart": {
"download": "Simpan grafik",
diff --git a/apps/web/messages/pt-BR/common.json b/apps/web/messages/pt-BR/common.json
index 061adbaf..4b50efc8 100644
--- a/apps/web/messages/pt-BR/common.json
+++ b/apps/web/messages/pt-BR/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "Pré-visualizar link",
+ "previewLinks": "Pré-visualizar links ({count})",
+ "previewNamedLink": "Pré-visualizar {name}",
+ "backToLinks": "Voltar aos links",
+ "openLink": "Abrir link",
+ "copyLink": "Copiar link",
+ "copiedLink": "Copiado",
+ "editLink": "Editar link",
+ "retryPreview": "Tentar novamente",
+ "copyLinkFailed": "Não foi possível copiar o link. Selecione e copie a URL acima."
},
"chart": {
"download": "Salvar gráfico",
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index c750ad7f..af03dde7 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "Предпросмотр ссылки",
+ "previewLinks": "Предпросмотр ссылок ({count})",
+ "previewNamedLink": "Предпросмотр: {name}",
+ "backToLinks": "Назад к ссылкам",
+ "openLink": "Открыть ссылку",
+ "copyLink": "Копировать ссылку",
+ "copiedLink": "Скопировано",
+ "editLink": "Изменить ссылку",
+ "retryPreview": "Повторить",
+ "copyLinkFailed": "Не удалось скопировать ссылку. Выделите и скопируйте URL выше."
},
"chart": {
"download": "Сохранить график",
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index 449097c1..5a641e01 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "Перегляд посилання",
+ "previewLinks": "Перегляд посилань ({count})",
+ "previewNamedLink": "Перегляд: {name}",
+ "backToLinks": "Назад до посилань",
+ "openLink": "Відкрити посилання",
+ "copyLink": "Копіювати посилання",
+ "copiedLink": "Скопійовано",
+ "editLink": "Редагувати посилання",
+ "retryPreview": "Спробувати ще раз",
+ "copyLinkFailed": "Не вдалося скопіювати посилання. Виділіть і скопіюйте URL вище."
},
"chart": {
"download": "Зберегти графік",
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index f4644001..5e31c836 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -188,7 +188,17 @@
"previewCustomField": "Custom field",
"previewAllWorkItems": "All work items",
"previewUpdated": "Updated {date}",
- "previewOtherValues": "({count} more)"
+ "previewOtherValues": "({count} more)",
+ "previewLink": "预览链接",
+ "previewLinks": "预览链接({count})",
+ "previewNamedLink": "预览 {name}",
+ "backToLinks": "返回链接列表",
+ "openLink": "打开链接",
+ "copyLink": "复制链接",
+ "copiedLink": "已复制",
+ "editLink": "编辑链接",
+ "retryPreview": "重试",
+ "copyLinkFailed": "无法复制链接。请选择并复制上方的 URL。"
},
"chart": {
"download": "保存图表",
diff --git a/apps/web/src/components/common/Markdown.tsx b/apps/web/src/components/common/Markdown.tsx
index 7a1d85fb..4236aa16 100644
--- a/apps/web/src/components/common/Markdown.tsx
+++ b/apps/web/src/components/common/Markdown.tsx
@@ -4,6 +4,8 @@ import { useMemo } from 'react';
import dynamic from 'next/dynamic';
import { markdownSegments } from '@/lib/markdown';
import { Skeleton } from '@/components/ui/skeleton';
+import MarkdownLinkContent from './editor/MarkdownLinkContent';
+import { bareMarkdownUrls } from './editor/linkPresentation';
// recharts is loaded only by the answers that actually carry a chart, so the views
// that just show markdown do not pull it in.
@@ -17,8 +19,18 @@ const AgentChatImportCard = dynamic(() => import('./agent-chat/AgentChatImportCa
// sizing the markdown table cell adds. Links open in a new tab so following one
// does not replace the view the reader was on. A ```chart fence is drawn as a chart
// where it sits in the text (see markdownSegments).
-export default function Markdown({ children }: { children: string }) {
+export default function Markdown({
+ children,
+ complete = true,
+}: {
+ children: string;
+ complete?: boolean;
+}) {
const segments = useMemo(() => markdownSegments(children, { newTabLinks: true }), [children]);
+ const bareUrls = useMemo(
+ () => (complete ? bareMarkdownUrls(children) : new Set<string>()),
+ [children, complete],
+ );
// `dir="auto"` reads the direction from the text itself, so an Arabic comment in
// an English interface — and the reverse — is laid out the way it was written.
return (
@@ -36,10 +48,11 @@ export default function Markdown({ children }: { children: string }) {
return <Skeleton key={index} className="my-3 h-[220px] w-full" />;
}
return (
- <div
+ <MarkdownLinkContent
key={index}
- className="md-content"
- dangerouslySetInnerHTML={{ __html: segment.html }}
+ html={segment.html}
+ bareUrls={bareUrls}
+ complete={complete}
/>
);
})}
diff --git a/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx b/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx
index c2d4199d..3a5a3fdc 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx
@@ -34,9 +34,11 @@ function blocksOf(parts: AiChatPart[]): Block[] {
export default function AgentChatMessage({
message,
showDate,
+ complete = true,
}: {
message: ChatMessage;
showDate: boolean;
+ complete?: boolean;
}) {
const t = useTranslations('common.agentChat');
const isUser = message.role === 'user';
@@ -63,7 +65,7 @@ export default function AgentChatMessage({
{isUser ? (
<AgentChatUserText text={block.text} />
) : (
- <Markdown>{block.text}</Markdown>
+ <Markdown complete={complete}>{block.text}</Markdown>
)}
</BubbleContent>
),
diff --git a/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx b/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
index 05a96075..92043f37 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
@@ -97,6 +97,7 @@ export function AgentChatTranscript({
<AgentChatMessage
key={message.id}
message={message}
+ complete={status === 'ready' || index < messages.length - 1}
showDate={!previous || dayKey(previous.createdAt) !== dayKey(message.createdAt)}
/>
);
diff --git a/apps/web/src/components/common/editor/EditorLinkPresentation.test.tsx b/apps/web/src/components/common/editor/EditorLinkPresentation.test.tsx
new file mode 100644
index 00000000..94413b22
--- /dev/null
+++ b/apps/web/src/components/common/editor/EditorLinkPresentation.test.tsx
@@ -0,0 +1,354 @@
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act, StrictMode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { Editor, EditorContent } from '@tiptap/react';
+import Link from '@tiptap/extension-link';
+import StarterKit from '@tiptap/starter-kit';
+import { Markdown } from 'tiptap-markdown';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import * as auth from '@/lib/auth-client';
+import common from '../../../../messages/en/common.json';
+
+const spyOn = createRequire(import.meta.url)('bun:test').spyOn as (
+ target: object,
+ method: string,
+) => {
+ mockReturnValue(value: unknown): { mockRestore(): void };
+ mockImplementation(fn: (...args: unknown[]) => unknown): { mockRestore(): void };
+};
+
+const source =
+ 'https://example.com/guide?key=A%2FB#part\n\nRead [the guide](https://example.com/other).';
+let dom: JSDOM;
+let root: Root;
+let editor: Editor;
+let client: QueryClient;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let restoreSession: () => void;
+let restoreConsole: () => void;
+let originalFetch: typeof fetch;
+let EditorLinkPreview: (typeof import('./EditorLinkPreview'))['default'];
+let requests: string[];
+let warnings: string[];
+
+const settle = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 20)));
+
+async function render({ compact = true, strict = true } = {}) {
+ const content = (
+ <NextIntlClientProvider locale="en" timeZone="UTC" messages={{ common }}>
+ <QueryClientProvider client={client}>
+ <EditorContent editor={editor} />
+ <EditorLinkPreview editor={editor} source={source} compact={compact} />
+ </QueryClientProvider>
+ </NextIntlClientProvider>
+ );
+ await act(() => root.render(strict ? <StrictMode>{content}</StrictMode> : content));
+ await settle();
+}
+
+beforeEach(async () => {
+ dom = new JSDOM('<div id="root"></div><div id="editor"></div>', {
+ url: 'https://planner.test',
+ pretendToBeVisual: true,
+ });
+ dom.window.matchMedia = (media) => ({
+ media,
+ matches: true,
+ onchange: null,
+ addEventListener() {},
+ removeEventListener() {},
+ addListener() {},
+ removeListener() {},
+ dispatchEvent: () => true,
+ });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ navigator: dom.window.navigator,
+ DOMParser: dom.window.DOMParser,
+ Node: dom.window.Node,
+ NodeFilter: dom.window.NodeFilter,
+ Element: dom.window.Element,
+ HTMLElement: dom.window.HTMLElement,
+ HTMLAnchorElement: dom.window.HTMLAnchorElement,
+ HTMLInputElement: dom.window.HTMLInputElement,
+ MutationObserver: dom.window.MutationObserver,
+ CustomEvent: dom.window.CustomEvent,
+ PointerEvent: dom.window.MouseEvent,
+ Image: dom.window.Image,
+ IntersectionObserver: undefined,
+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
+ requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window),
+ cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window),
+ IS_REACT_ACT_ENVIRONMENT: true,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+ ({ default: EditorLinkPreview } = await import('./EditorLinkPreview'));
+ const session = spyOn(auth, 'useSession').mockReturnValue({
+ data: { user: { id: 'reader' } },
+ isPending: false,
+ error: null,
+ } as ReturnType<typeof auth.useSession>);
+ restoreSession = () => session.mockRestore();
+ warnings = [];
+ const logging = spyOn(console, 'error').mockImplementation((...args) =>
+ warnings.push(args.join(' ')),
+ );
+ restoreConsole = () => logging.mockRestore();
+ originalFetch = globalThis.fetch;
+ requests = [];
+ globalThis.fetch = (async (input) => {
+ requests.push(String(input));
+ return Response.json({
+ url: 'https://example.com/guide',
+ title: 'Fetched guide title',
+ description: 'Description',
+ siteName: 'Site',
+ image: null,
+ });
+ }) as typeof fetch;
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ editor = new Editor({
+ element: document.getElementById('editor')!,
+ extensions: [
+ StarterKit.configure({ link: false }),
+ Link.configure({ openOnClick: false }),
+ Markdown.configure({ html: true, linkify: true, breaks: true }),
+ ],
+ content: source,
+ editorProps: { handleScrollToSelection: () => true },
+ });
+ root = createRoot(document.getElementById('root')!);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ editor.destroy();
+ await settle();
+ client.clear();
+ globalThis.fetch = originalFetch;
+ restoreSession();
+ restoreConsole();
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+describe('mounted EditorContent link presentation', () => {
+ it('loads only visible compact cards without changing the document or undo history', async () => {
+ const observers: { show(): void; disconnected: boolean }[] = [];
+ class Observer {
+ disconnected = false;
+ constructor(readonly callback: IntersectionObserverCallback) {
+ observers.push(this);
+ }
+ observe() {}
+ disconnect() {
+ this.disconnected = true;
+ }
+ show() {
+ this.callback(
+ [
+ {
+ isIntersecting: true,
+ intersectionRect: { width: 100, height: 64 },
+ } as IntersectionObserverEntry,
+ ],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ }
+ Object.defineProperty(globalThis, 'IntersectionObserver', { value: Observer });
+ const json = editor.getJSON();
+ const markdown = editor.storage.markdown.getMarkdown();
+ let updates = 0;
+ editor.on('update', () => updates++);
+ await render();
+ assert.equal(requests.length, 0);
+ const observer = observers.findLast((entry) => !entry.disconnected)!;
+ await act(() => observer.show());
+ await settle();
+ assert.equal(requests.length, 1);
+ assert.match(document.querySelector('[data-link-row]')!.textContent!, /Fetched guide title/);
+ const trigger = document.querySelector<HTMLButtonElement>('[data-link-preview-control]')!;
+ await act(() => trigger.click());
+ await settle();
+ assert.equal(requests.length, 1);
+ assert.ok(document.querySelector('[role="dialog"]'));
+ assert.equal(updates, 0);
+ assert.deepEqual(editor.getJSON(), json);
+ assert.equal(editor.storage.markdown.getMarkdown(), markdown);
+ assert.equal(editor.can().undo(), false);
+ });
+
+ it('disconnects visibility observation and cancels a pending preview when editing starts', async () => {
+ let show!: () => void;
+ let disconnected = false;
+ let requestSignal: AbortSignal | null | undefined;
+ Object.defineProperty(globalThis, 'IntersectionObserver', {
+ value: class {
+ constructor(callback: IntersectionObserverCallback) {
+ show = () =>
+ callback(
+ [
+ {
+ isIntersecting: true,
+ intersectionRect: { width: 100, height: 64 },
+ } as IntersectionObserverEntry,
+ ],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ observe() {}
+ disconnect() {
+ disconnected = true;
+ }
+ },
+ });
+ globalThis.fetch = (async (_input, init) => {
+ requestSignal = init?.signal;
+ return new Promise((_resolve, reject) => {
+ requestSignal?.addEventListener('abort', () => reject(requestSignal?.reason));
+ });
+ }) as typeof fetch;
+ await render({ strict: false });
+ await act(() => show());
+ await settle();
+ assert.equal(requestSignal?.aborted, false);
+ await act(() => editor.view.dom.focus());
+ await settle();
+ assert.equal(disconnected, true);
+ assert.equal(requestSignal?.aborted, true);
+ assert.equal(document.querySelector('[data-link-row]'), null);
+ });
+
+ for (const type of ['pointerdown', 'mousedown']) {
+ it(`keeps reading controls mounted when ${type} would focus the editing host`, async () => {
+ await render();
+ const json = editor.getJSON();
+ const markdown = editor.storage.markdown.getMarkdown();
+ let updates = 0;
+ editor.on('update', () => updates++);
+ const link = document.querySelector<HTMLAnchorElement>('[data-link-row]')!;
+ const trigger = document.querySelector<HTMLButtonElement>('[data-link-preview-control]')!;
+ const targets = [...link.querySelectorAll('span, svg'), trigger.querySelector('svg')!];
+ for (const button of [0, 1, 2]) {
+ for (const target of targets) {
+ await act(() => {
+ const press = new dom.window.MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ button,
+ });
+ if (target.dispatchEvent(press)) editor.view.dom.focus();
+ });
+ assert.equal(
+ link.isConnected,
+ true,
+ `destination removed after pressing ${target.tagName}`,
+ );
+ assert.equal(trigger.isConnected, true);
+ assert.notEqual(document.activeElement, editor.view.dom);
+ }
+ }
+ for (const action of ['auxclick', 'contextmenu']) {
+ const event = new dom.window.MouseEvent(action, { bubbles: true, cancelable: true });
+ assert.equal(link.dispatchEvent(event), true);
+ }
+ const click = new dom.window.MouseEvent('click', { bubbles: true, cancelable: true });
+ let nativeActivation = false;
+ link.addEventListener('click', (event) => {
+ nativeActivation = !event.defaultPrevented;
+ event.preventDefault();
+ });
+ await act(() => link.dispatchEvent(click));
+ assert.equal(nativeActivation, true);
+ assert.equal(link.href, 'https://example.com/guide?key=A%2FB#part');
+ await act(() => trigger.click());
+ await settle();
+ assert.equal(document.querySelectorAll('[role="dialog"]').length, 1);
+ assert.equal(updates, 0);
+ assert.deepEqual(editor.getJSON(), json);
+ assert.equal(editor.storage.markdown.getMarkdown(), markdown);
+ assert.equal(editor.can().undo(), false);
+ });
+ }
+
+ it('keeps keyboard focus and deliberate body editing available', async () => {
+ await render();
+ const link = document.querySelector<HTMLAnchorElement>('[data-link-row]')!;
+ await act(() => link.focus());
+ assert.equal(document.activeElement, link);
+ assert.equal(link.isConnected, true);
+ const text = editor.view.dom.querySelectorAll('p')[1]!;
+ await act(() => {
+ const press = new dom.window.MouseEvent('pointerdown', { bubbles: true, cancelable: true });
+ assert.equal(text.dispatchEvent(press), true);
+ editor.view.dom.focus();
+ });
+ assert.equal(document.querySelector('[data-link-row]'), null);
+ assert.equal(document.activeElement, editor.view.dom);
+ });
+
+ it('mounts and changes capability presentation without lifecycle flushes or source updates', async () => {
+ const json = editor.getJSON();
+ const markdown = editor.storage.markdown.getMarkdown();
+ let updates = 0;
+ editor.on('update', () => updates++);
+ await render();
+ assert.equal(document.querySelectorAll('[data-link-row]').length, 1);
+ assert.equal(document.querySelectorAll('[data-link-preview-control]').length, 2);
+ assert.equal(requests.length, 0);
+ await render({ compact: false });
+ assert.equal(document.querySelectorAll('[data-link-row]').length, 0);
+ assert.equal(document.querySelectorAll('[data-link-preview-control]').length, 2);
+ await render();
+ assert.equal(document.querySelectorAll('[data-link-row]').length, 1);
+ assert.equal(
+ warnings.some((warning) => /flushSync|lifecycle|Maximum update depth/.test(warning)),
+ false,
+ warnings.join('\n'),
+ );
+ assert.equal(updates, 0);
+ assert.deepEqual(editor.getJSON(), json);
+ assert.equal(editor.storage.markdown.getMarkdown(), markdown);
+ assert.equal(editor.can().undo(), false);
+ });
+
+ it('opens a mounted widget preview and restores focus without editing the document', async () => {
+ const json = editor.getJSON();
+ const markdown = editor.storage.markdown.getMarkdown();
+ let updates = 0;
+ editor.on('update', () => updates++);
+ await render({ strict: false });
+ const trigger = document.querySelector<HTMLButtonElement>('[data-link-preview-control]')!;
+ await act(() => trigger.click());
+ await settle();
+ assert.equal(document.querySelectorAll('[role="dialog"]').length, 1);
+ assert.equal(requests.length, 1);
+ assert.match(document.body.textContent!, /Fetched guide title/);
+ const close = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!;
+ await act(() => close.click());
+ await settle();
+ assert.equal(document.querySelector('[role="dialog"]'), null);
+ assert.equal(document.activeElement, trigger);
+ assert.equal(updates, 0);
+ assert.deepEqual(editor.getJSON(), json);
+ assert.equal(editor.storage.markdown.getMarkdown(), markdown);
+ assert.equal(
+ warnings.some((warning) => /flushSync|lifecycle|Maximum update depth/.test(warning)),
+ false,
+ warnings.join('\n'),
+ );
+ });
+});
diff --git a/apps/web/src/components/common/editor/EditorLinkPreview.tsx b/apps/web/src/components/common/editor/EditorLinkPreview.tsx
index 0fe301f6..12df38e2 100644
--- a/apps/web/src/components/common/editor/EditorLinkPreview.tsx
+++ b/apps/web/src/components/common/editor/EditorLinkPreview.tsx
@@ -5,15 +5,31 @@ import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover'
import { useEditorLinkPreview } from './useEditorLinkPreview';
import { useLinkPreviewQuery } from './useLinkPreviewQuery';
import EditorLinkPreviewCard from './EditorLinkPreviewCard';
+import LinkPreviewDialog from './LinkPreviewDialog';
+import { useEditorLinkPresentation } from './useEditorLinkPresentation';
import styles from './EditorLinkPreview.module.css';
-export default function EditorLinkPreview({ editor }: { editor: Editor }) {
+export default function EditorLinkPreview({
+ editor,
+ source = '',
+ compact = true,
+}: {
+ editor: Editor;
+ source?: string;
+ compact?: boolean;
+}) {
const t = useTranslations('common.editor');
- const { anchor, candidateAnchor, open, close, keepOpen, leave } = useEditorLinkPreview(editor);
+ const { dialog, closeDialog } = useEditorLinkPresentation(editor, source, compact);
+ const { anchor, candidateAnchor, open, close, keepOpen, leave } = useEditorLinkPreview(
+ editor,
+ !!dialog,
+ );
const virtualRef = useRef({ getBoundingClientRect: () => new DOMRect() });
virtualRef.current.getBoundingClientRect = () => anchor?.getBoundingClientRect() ?? new DOMRect();
useLinkPreviewQuery(candidateAnchor?.href);
const { data, isPending } = useLinkPreviewQuery(anchor?.href);
+ if (dialog)
+ return <LinkPreviewDialog {...dialog} onClose={closeDialog} container={editor.view.dom} />;
if (!anchor) return null;
return (
diff --git a/apps/web/src/components/common/editor/LinkBlockControls.test.tsx b/apps/web/src/components/common/editor/LinkBlockControls.test.tsx
new file mode 100644
index 00000000..ea89889d
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkBlockControls.test.tsx
@@ -0,0 +1,328 @@
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act, useSyncExternalStore } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import * as auth from '@/lib/auth-client';
+import common from '../../../../messages/en/common.json';
+import LinkBlockControls from './LinkBlockControls';
+
+type SessionSnapshot = ReturnType<typeof auth.useSession>;
+const { spyOn } = createRequire(import.meta.url)('bun:test') as {
+ spyOn(
+ target: object,
+ method: string,
+ ): {
+ mockImplementation(fn: () => SessionSnapshot): { mockRestore(): void };
+ };
+};
+
+class Observer {
+ static instances: Observer[] = [];
+ element?: Element;
+ disconnected = false;
+ constructor(
+ readonly callback: IntersectionObserverCallback,
+ readonly options: IntersectionObserverInit,
+ ) {
+ Observer.instances.push(this);
+ }
+ observe(element: Element) {
+ this.element = element;
+ }
+ disconnect() {
+ this.disconnected = true;
+ }
+ emit(visible: boolean, width = 100, height = 64) {
+ this.callback(
+ [
+ {
+ target: this.element,
+ isIntersecting: visible,
+ intersectionRect: { width, height },
+ } as IntersectionObserverEntry,
+ ],
+ this as unknown as IntersectionObserver,
+ );
+ }
+}
+
+let dom: JSDOM;
+let root: Root;
+let client: QueryClient;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let originalFetch: typeof fetch;
+let restoreSession: () => void;
+let session: SessionSnapshot;
+const listeners = new Set<() => void>();
+let requests: { url: URL; signal?: AbortSignal | null }[];
+let respond: (url: URL, signal?: AbortSignal | null) => Promise<Response>;
+const settle = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 20)));
+const preview = (title: string) => ({
+ url: 'https://example.test/',
+ title,
+ description: 'Description',
+ image: null,
+ siteName: 'Example',
+});
+
+function setSession(userId: string | null, isPending = false, sessionId = `session-${userId}`) {
+ session = {
+ data: userId ? { user: { id: userId }, session: { id: sessionId } } : null,
+ isPending,
+ error: null,
+ } as SessionSnapshot;
+ for (const listener of listeners) listener();
+}
+
+async function render(urls = ['https://example.test/guide'], compact = true) {
+ await act(() =>
+ root.render(
+ <NextIntlClientProvider locale="en" timeZone="UTC" messages={{ common }}>
+ <QueryClientProvider client={client}>
+ {urls.map((url, index) => (
+ <LinkBlockControls
+ key={index}
+ links={[{ url, label: url }]}
+ compact={compact}
+ onPreview={() => {}}
+ />
+ ))}
+ </QueryClientProvider>
+ </NextIntlClientProvider>,
+ ),
+ );
+ await settle();
+}
+
+async function intersect(observer: Observer, visible: boolean, width?: number, height?: number) {
+ await act(() => observer.emit(visible, width, height));
+ await settle();
+}
+
+beforeEach(() => {
+ dom = new JSDOM('<div id="root"></div>', { url: 'https://planner.test' });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ Element: dom.window.Element,
+ HTMLElement: dom.window.HTMLElement,
+ IntersectionObserver: Observer,
+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
+ IS_REACT_ACT_ENVIRONMENT: true,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+ Observer.instances = [];
+ originalFetch = globalThis.fetch;
+ requests = [];
+ respond = async () => Response.json(preview('Visible card title'));
+ globalThis.fetch = (async (input, init) => {
+ const url = new URL(String(input));
+ requests.push({ url, signal: init?.signal });
+ return respond(url, init?.signal);
+ }) as typeof fetch;
+ const mock = spyOn(auth, 'useSession').mockImplementation(function useTestSession() {
+ return useSyncExternalStore(
+ (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ () => session,
+ () => session,
+ );
+ });
+ restoreSession = () => mock.mockRestore();
+ setSession('reader');
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 120_000 } } });
+ root = createRoot(document.getElementById('root')!);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ client.clear();
+ restoreSession();
+ listeners.clear();
+ globalThis.fetch = originalFetch;
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+describe('visible compact link cards', () => {
+ it('requests metadata only after a positive viewport intersection', async () => {
+ await render();
+ const observer = Observer.instances[0]!;
+ assert.equal(observer.options.rootMargin, '0px');
+ assert.equal(requests.length, 0);
+ await intersect(observer, false);
+ await intersect(observer, true, 0, 64);
+ await intersect(observer, true, 100, 0);
+ assert.equal(requests.length, 0);
+ await intersect(observer, true);
+ assert.equal(requests.length, 1);
+ assert.match(document.body.textContent!, /Visible card title/);
+ assert.equal(requests[0]!.url.searchParams.get('url'), 'https://example.test/guide');
+ });
+
+ it('deduplicates normalized URLs and reuses external metadata after scrolling back', async () => {
+ await render(['https://EXAMPLE.test:443/guide', 'https://example.test/guide']);
+ await act(() => {
+ for (const observer of Observer.instances) observer.emit(true);
+ });
+ await settle();
+ assert.equal(requests.length, 1);
+ assert.equal(document.querySelectorAll('[data-link-row]').length, 2);
+ assert.equal(document.body.textContent!.split('Visible card title').length - 1, 2);
+ await intersect(Observer.instances[0]!, false);
+ await intersect(Observer.instances[0]!, true);
+ assert.equal(requests.length, 1);
+ });
+
+ it('keeps inline controls and browsers without an observer on demand', async () => {
+ await render(undefined, false);
+ assert.equal(Observer.instances.length, 0);
+ assert.equal(requests.length, 0);
+ Object.defineProperty(globalThis, 'IntersectionObserver', { value: undefined });
+ await render();
+ assert.equal(requests.length, 0);
+ assert.ok(document.querySelector('[data-link-preview-control]'));
+ });
+
+ it('refreshes expired external metadata when the card becomes visible again', async () => {
+ const url = 'https://example.test/guide';
+ client.setQueryData(['link-preview', 'reader', url], preview('Cached title'));
+ await render([url]);
+ await intersect(Observer.instances[0]!, true);
+ assert.equal(requests.length, 0);
+ assert.match(document.body.textContent!, /Cached title/);
+ await intersect(Observer.instances[0]!, false);
+ client.setQueryData(['link-preview', 'reader', url], preview('Cached title'), {
+ updatedAt: Date.now() - 300_001,
+ });
+ await intersect(Observer.instances[0]!, true);
+ assert.equal(requests.length, 1);
+ assert.match(document.body.textContent!, /Visible card title/);
+ });
+
+ it('retries an empty external response after its short cache lifetime', async () => {
+ const url = 'https://example.test/guide';
+ client.setQueryData(
+ ['link-preview', 'reader', url],
+ { url, title: null, description: null, image: null, siteName: null },
+ { updatedAt: Date.now() - 15_001 },
+ );
+ await render([url]);
+ assert.equal(requests.length, 0);
+ await intersect(Observer.instances[0]!, true);
+ assert.equal(requests.length, 1);
+ assert.match(document.body.textContent!, /Visible card title/);
+ });
+
+ it('ignores hidden cards and callbacks delivered after a capability change', async () => {
+ await render();
+ const observer = Observer.instances[0]!;
+ (observer.element as HTMLElement).style.visibility = 'hidden';
+ await intersect(observer, true);
+ assert.equal(requests.length, 0);
+ (observer.element as HTMLElement).style.visibility = 'visible';
+ await render(undefined, false);
+ assert.equal(observer.disconnected, true);
+ await intersect(observer, true);
+ assert.equal(requests.length, 0);
+ await render();
+ assert.equal(requests.length, 0);
+ await intersect(Observer.instances.at(-1)!, true);
+ assert.equal(requests.length, 1);
+ });
+
+ it('cancels requests when a card leaves view or its URL changes', async () => {
+ respond = (_url, signal) =>
+ new Promise((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(signal.reason));
+ });
+ await render();
+ await intersect(Observer.instances[0]!, true);
+ await intersect(Observer.instances[0]!, false);
+ assert.equal(requests[0]!.signal?.aborted, true);
+ await intersect(Observer.instances[0]!, true);
+ await render(['https://example.test/replacement']);
+ assert.equal(requests[1]!.signal?.aborted, true);
+ assert.equal(requests.length, 2);
+ await intersect(Observer.instances.at(-1)!, true);
+ assert.equal(requests[2]!.url.searchParams.get('url'), 'https://example.test/replacement');
+ await render([]);
+ assert.equal(requests[2]!.signal?.aborted, true);
+ });
+
+ it('hides cached internal details until access is revalidated on each visibility change', async () => {
+ const url = 'https://planner.test/project/PRIVATE';
+ client.setQueryData(
+ ['link-preview', 'reader', url, 'session-reader'],
+ preview('Old private title'),
+ );
+ let resolve!: (response: Response) => void;
+ respond = () => new Promise((done) => (resolve = done));
+ await render(['/project/PRIVATE']);
+ assert.doesNotMatch(document.body.textContent!, /Old private title/);
+ await intersect(Observer.instances[0]!, true);
+ assert.equal(requests[0]!.url.pathname, '/projects/PRIVATE');
+ assert.doesNotMatch(document.body.textContent!, /Old private title/);
+ await act(() =>
+ resolve(
+ Response.json({ project: { key: 'PRIVATE', name: 'Private title', description: '' } }),
+ ),
+ );
+ await settle();
+ assert.match(document.body.textContent!, /Private title/);
+ await intersect(Observer.instances[0]!, false);
+ await intersect(Observer.instances[0]!, true);
+ assert.equal(requests.length, 2);
+ assert.doesNotMatch(document.body.textContent!, /Private title/);
+ await act(() => resolve(Response.json({ error: 'Forbidden' }, { status: 403 })));
+ await settle();
+ assert.doesNotMatch(document.body.textContent!, /Private title/);
+ assert.ok(document.querySelector('a[href="/project/PRIVATE"]'));
+ });
+
+ it('hides metadata for pending, changed and signed-out sessions', async () => {
+ await render();
+ await intersect(Observer.instances[0]!, true);
+ assert.match(document.body.textContent!, /Visible card title/);
+ await act(() => setSession('reader', true));
+ assert.doesNotMatch(document.body.textContent!, /Visible card title/);
+ respond = () => new Promise(() => {});
+ await act(() => setSession('other-reader'));
+ await settle();
+ assert.equal(requests.length, 2);
+ assert.doesNotMatch(document.body.textContent!, /Visible card title/);
+ await act(() => setSession(null));
+ assert.doesNotMatch(document.body.textContent!, /Visible card title/);
+ assert.equal(requests[1]!.signal?.aborted, true);
+ });
+
+ it('revalidates internal access when the same account receives a new session', async () => {
+ respond = async () =>
+ Response.json({ project: { key: 'PRIVATE', name: 'Private title', description: '' } });
+ await render(['/project/PRIVATE']);
+ await intersect(Observer.instances[0]!, true);
+ assert.match(document.body.textContent!, /Private title/);
+ let resolve!: (response: Response) => void;
+ respond = () => new Promise((done) => (resolve = done));
+ await act(() => setSession('reader', false, 'replacement-session'));
+ await settle();
+ assert.equal(requests.length, 2);
+ assert.doesNotMatch(document.body.textContent!, /Private title/);
+ await act(() => resolve(Response.json({ error: 'Forbidden' }, { status: 403 })));
+ await settle();
+ assert.doesNotMatch(document.body.textContent!, /Private title/);
+ });
+});
diff --git a/apps/web/src/components/common/editor/LinkBlockControls.tsx b/apps/web/src/components/common/editor/LinkBlockControls.tsx
new file mode 100644
index 00000000..18e8eee8
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkBlockControls.tsx
@@ -0,0 +1,85 @@
+import { Eye } from 'lucide-react';
+import type { MouseEvent } from 'react';
+import { useTranslations } from 'next-intl';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+import LinkPreviewThumbnail from './LinkPreviewThumbnail';
+import { useVisibleLinkPreview } from './useVisibleLinkPreview';
+import { linkDestination } from './linkPresentation';
+import { internalLinkTarget } from './internalLinkTarget';
+import styles from './LinkPresentation.module.css';
+
+function preventEditorFocus(event: MouseEvent<HTMLElement>) {
+ // Safari can focus the editing host and remove this widget before its click.
+ event.preventDefault();
+ event.stopPropagation();
+}
+
+export default function LinkBlockControls({
+ links,
+ compact,
+ onPreview,
+ expanded = false,
+}: {
+ links: LinkPreviewItem[];
+ compact: boolean;
+ onPreview: (links: LinkPreviewItem[], trigger: HTMLButtonElement) => void;
+ expanded?: boolean;
+}) {
+ const t = useTranslations('common.editor');
+ const link = links[0];
+ const { ref, preview } = useVisibleLinkPreview(compact ? link.url : undefined);
+ const destination = linkDestination(link.url, window.location.origin);
+ const name = preview?.title || destination.hostname;
+ const url = new URL(link.url, window.location.origin);
+ const internal = url.origin === window.location.origin ? internalLinkTarget(url) : null;
+ const kind = internal?.kind === 'issueId' ? 'issue' : internal?.kind;
+ let detail = destination.pathname === '/' ? '\u00a0' : destination.pathname;
+ if (preview?.title) detail = destination.hostname;
+ return (
+ <span
+ ref={ref}
+ className={compact ? styles.row : styles.blockAction}
+ contentEditable={false}
+ data-link-presentation=""
+ onPointerDown={preventEditorFocus}
+ onMouseDown={preventEditorFocus}
+ onClick={(event) => event.stopPropagation()}
+ onAuxClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ {compact && (
+ <a
+ href={link.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ referrerPolicy="no-referrer"
+ className={styles.destination}
+ data-link-row={link.label}
+ >
+ <LinkPreviewThumbnail image={preview?.image} kind={kind} />
+ <span className={styles.text}>
+ <span className={styles.title} dir="auto">
+ {name}
+ </span>
+ <span className={styles.subtitle} dir="ltr">
+ {detail}
+ </span>
+ </span>
+ </a>
+ )}
+ <button
+ type="button"
+ className={compact ? styles.iconButton : styles.previewButton}
+ data-link-preview-control=""
+ aria-label={compact ? t('previewNamedLink', { name }) : undefined}
+ aria-haspopup="dialog"
+ aria-expanded={expanded}
+ onClick={(event) => onPreview(links, event.currentTarget)}
+ >
+ <Eye size={16} aria-hidden="true" />
+ {!compact &&
+ (links.length === 1 ? t('previewLink') : t('previewLinks', { count: links.length }))}
+ </button>
+ </span>
+ );
+}
diff --git a/apps/web/src/components/common/editor/LinkPresentation.module.css b/apps/web/src/components/common/editor/LinkPresentation.module.css
new file mode 100644
index 00000000..e5a75932
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPresentation.module.css
@@ -0,0 +1,157 @@
+.row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ min-height: 4rem;
+ padding: 0.5rem;
+ border-radius: calc(var(--radius) * 0.8);
+ background: color-mix(in oklab, var(--muted) 50%, transparent);
+ color: var(--foreground);
+ text-align: start;
+}
+
+.destination {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ min-width: 0;
+ min-height: 2.75rem;
+ flex: 1;
+ border-radius: calc(var(--radius) * 0.6);
+ color: var(--foreground) !important;
+ text-decoration: none !important;
+}
+
+.thumbnail {
+ display: grid;
+ place-items: center;
+ width: 2.5rem;
+ height: 2.5rem;
+ flex-shrink: 0;
+ color: var(--muted-foreground);
+}
+
+.row .thumbnail img {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ border-radius: calc(var(--radius) * 0.6);
+ object-fit: cover;
+ outline: 1px solid rgb(0 0 0 / 10%);
+ outline-offset: -1px;
+}
+
+:global(.dark) .thumbnail img {
+ outline-color: rgb(255 255 255 / 10%);
+}
+.text {
+ display: grid;
+ min-width: 0;
+ flex: 1;
+}
+.title,
+.subtitle {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 0.875rem;
+ line-height: 1.5;
+}
+.title {
+ font-weight: 500;
+}
+.subtitle {
+ color: color-mix(in oklab, var(--muted-foreground) 85%, var(--foreground) 15%);
+ unicode-bidi: isolate;
+ text-align: start;
+}
+.blockAction {
+ display: block;
+ margin-top: 0.25rem;
+ user-select: none;
+}
+.iconButton,
+.previewButton {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ min-width: 2.75rem;
+ min-height: 2.75rem;
+ flex-shrink: 0;
+ border-radius: calc(var(--radius) * 0.8);
+ color: var(--muted-foreground);
+ font-size: 0.875rem;
+ line-height: 1.5;
+ cursor: pointer;
+ user-select: none;
+ transition:
+ color 120ms,
+ background-color 120ms,
+ transform 120ms;
+}
+.previewButton {
+ padding-inline: 0.5rem;
+}
+.iconButton:active,
+.previewButton:active {
+ transform: scale(0.96);
+ background: var(--accent);
+}
+.destination:focus-visible,
+.iconButton:focus-visible,
+.previewButton:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+}
+.compactBlock {
+ margin-block: 0.25rem !important;
+}
+.compactBlock > :not([data-link-widget]) {
+ display: none;
+}
+.widget {
+ display: block;
+}
+.staticBlock {
+ display: contents;
+}
+.staticCompact {
+ margin-block: 0.25rem;
+}
+.original {
+ display: none;
+}
+
+@media (hover: hover) {
+ .destination:hover,
+ .iconButton:hover,
+ .previewButton:hover {
+ background: var(--accent);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .iconButton,
+ .previewButton {
+ transition: none;
+ }
+ .iconButton:active,
+ .previewButton:active {
+ transform: none;
+ }
+}
+
+@media print {
+ .row,
+ .blockAction,
+ .widget {
+ display: none;
+ }
+ .compactBlock > :not([data-link-widget]) {
+ display: revert;
+ }
+ .original {
+ display: block;
+ }
+}
diff --git a/apps/web/src/components/common/editor/LinkPreviewActions.tsx b/apps/web/src/components/common/editor/LinkPreviewActions.tsx
new file mode 100644
index 00000000..47d0f926
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewActions.tsx
@@ -0,0 +1,86 @@
+import { useEffect, useRef, useState } from 'react';
+import { ArrowUpRight, Check, Copy, Pencil } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { linkPreviewDestination } from './linkPreviewDestination';
+import styles from './LinkPreviewDialog.module.css';
+
+export default function LinkPreviewActions({ url, onEdit }: { url: string; onEdit?: () => void }) {
+ const t = useTranslations('common.editor');
+ const origin = typeof window === 'undefined' ? undefined : window.location.origin;
+ const openable = !!linkPreviewDestination(url, origin);
+ const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>('idle');
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ clearTimeout(timer.current);
+ };
+ }, []);
+
+ async function copyLink() {
+ try {
+ if (!navigator.clipboard?.writeText) throw new Error('Clipboard is unavailable');
+ await navigator.clipboard.writeText(url);
+ if (!mounted.current) return;
+ clearTimeout(timer.current);
+ setCopyState('copied');
+ timer.current = setTimeout(() => setCopyState('idle'), 2000);
+ } catch {
+ if (!mounted.current) return;
+ clearTimeout(timer.current);
+ setCopyState('failed');
+ }
+ }
+
+ let copyMessage = '';
+ if (copyState === 'copied') copyMessage = t('copiedLink');
+ if (copyState === 'failed') copyMessage = t('copyLinkFailed');
+
+ return (
+ <div className="shrink-0 space-y-2">
+ <div className={`grid gap-2 ${openable ? 'grid-cols-2' : 'grid-cols-1'}`}>
+ {openable && (
+ <Button asChild className={styles.control}>
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ referrerPolicy="no-referrer"
+ data-link-preview-primary=""
+ >
+ {t('openLink')}
+ <ArrowUpRight className="size-4" aria-hidden="true" />
+ </a>
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="secondary"
+ className={styles.control}
+ data-link-preview-primary={openable ? undefined : ''}
+ onClick={() => void copyLink()}
+ >
+ {copyState === 'copied' ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
+ {copyState === 'copied' ? t('copiedLink') : t('copyLink')}
+ </Button>
+ {onEdit && (
+ <Button
+ type="button"
+ variant="ghost"
+ className={`${styles.control} col-span-full justify-start`}
+ onClick={onEdit}
+ >
+ <Pencil aria-hidden="true" />
+ {t('editLink')}
+ </Button>
+ )}
+ </div>
+ <p role="status" className={copyState === 'failed' ? 'text-sm' : 'sr-only'}>
+ {copyMessage}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/common/editor/LinkPreviewContent.tsx b/apps/web/src/components/common/editor/LinkPreviewContent.tsx
new file mode 100644
index 00000000..8595e654
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewContent.tsx
@@ -0,0 +1,96 @@
+import {
+ CircleDot,
+ FileText,
+ FolderKanban,
+ Globe,
+ LayoutList,
+ LoaderCircle,
+ StickyNote,
+} from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+import { useLinkPreviewQuery } from './useLinkPreviewQuery';
+import { linkPreviewDestination } from './linkPreviewDestination';
+import { isRetryableLinkPreviewError } from './isRetryableLinkPreviewError';
+import EditorLinkPreviewImage from './EditorLinkPreviewImage';
+import EditorLinkPreviewDetails from './EditorLinkPreviewDetails';
+import styles from './LinkPreviewDialog.module.css';
+
+const previewIcons = {
+ project: FolderKanban,
+ issue: CircleDot,
+ document: FileText,
+ notes: StickyNote,
+ view: LayoutList,
+};
+
+export default function LinkPreviewContent({ link }: { link: LinkPreviewItem }) {
+ const t = useTranslations('common.editor');
+ const origin = typeof window === 'undefined' ? undefined : window.location.origin;
+ const destination = linkPreviewDestination(link.url, origin);
+ const query = useLinkPreviewQuery(destination?.href);
+ const preview = query.data;
+ const internal = !!destination && destination.origin === origin;
+ const loading = query.isPending || query.isFetching;
+ const Icon = preview?.kind ? previewIcons[preview.kind] : Globe;
+ let fallbackTitle = internal ? t('internalPage') : destination?.hostname;
+ if (link.label && link.label !== link.url && link.label !== destination?.href)
+ fallbackTitle = link.label;
+ const title = preview?.title || fallbackTitle;
+ return (
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Icon className="size-4 shrink-0" aria-hidden="true" />
+ <span className="min-w-0 wrap-anywhere" dir="ltr">
+ {destination?.hostname}
+ </span>
+ </p>
+ <h3 className="text-base font-medium text-pretty wrap-anywhere" dir="auto">
+ {title}
+ </h3>
+ </div>
+ {loading ? (
+ <div className="space-y-3" role="status">
+ <div className="h-3 w-4/5 animate-pulse rounded bg-muted motion-reduce:animate-none" />
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
+ <LoaderCircle
+ className="size-4 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ {t('loadingPreview')}
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {preview?.image && <EditorLinkPreviewImage key={preview.image} src={preview.image} />}
+ {preview?.description && (
+ <p className="line-clamp-3 text-base text-pretty wrap-anywhere" dir="auto">
+ {preview.description}
+ </p>
+ )}
+ {preview?.kind && <EditorLinkPreviewDetails preview={preview} />}
+ {!preview?.title && !preview?.description && (
+ <p className="text-sm text-muted-foreground">
+ {internal ? t('internalPreviewUnavailable') : t('previewUnavailable')}
+ </p>
+ )}
+ {isRetryableLinkPreviewError(query.error) && (
+ <Button
+ type="button"
+ variant="ghost"
+ className={styles.control}
+ onClick={() => void query.refetch()}
+ >
+ {t('retryPreview')}
+ </Button>
+ )}
+ </div>
+ )}
+ <p className="rounded-md bg-muted/50 p-3 text-sm wrap-anywhere select-text" dir="ltr">
+ {link.url}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/common/editor/LinkPreviewDialog.module.css b/apps/web/src/components/common/editor/LinkPreviewDialog.module.css
new file mode 100644
index 00000000..51d197b2
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewDialog.module.css
@@ -0,0 +1,100 @@
+.dialog {
+ position: fixed;
+ inset-inline: 0;
+ bottom: 0;
+ z-index: 50;
+ width: 100%;
+ max-height: min(80dvh, 640px);
+ padding: 24px;
+ padding-bottom: calc(24px + env(safe-area-inset-bottom, 0px));
+ border-start-start-radius: calc(var(--radius) * 1.8);
+ border-start-end-radius: calc(var(--radius) * 1.8);
+}
+
+.dialog[data-state='open'] {
+ animation: preview-in 250ms cubic-bezier(0.2, 0, 0, 1);
+}
+
+.dialog[data-state='closed'] {
+ animation: preview-out 120ms cubic-bezier(0.2, 0, 0, 1);
+}
+
+.overlay[data-state='open'] {
+ animation: overlay-in 250ms cubic-bezier(0.2, 0, 0, 1);
+}
+
+.overlay[data-state='closed'] {
+ animation: overlay-out 120ms cubic-bezier(0.2, 0, 0, 1);
+}
+
+.control {
+ min-width: 44px;
+ min-height: 44px;
+ height: auto;
+ white-space: normal;
+ transition-property: background-color, color, opacity;
+ transition-duration: 120ms;
+}
+
+.control:focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+ box-shadow: none;
+}
+
+@media (min-width: 768px) {
+ .dialog {
+ inset-inline: auto;
+ top: 50%;
+ left: 50%;
+ bottom: auto;
+ width: 440px;
+ translate: -50% -50%;
+ border-radius: var(--radius);
+ padding-bottom: 24px;
+ }
+}
+
+@keyframes preview-in {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes preview-out {
+ to {
+ opacity: 0;
+ transform: translateY(4px);
+ }
+}
+
+@keyframes overlay-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+@keyframes overlay-out {
+ to {
+ opacity: 0;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dialog[data-state],
+ .overlay[data-state] {
+ animation: none;
+ }
+
+ .control {
+ transition: none;
+ }
+}
diff --git a/apps/web/src/components/common/editor/LinkPreviewDialog.test.tsx b/apps/web/src/components/common/editor/LinkPreviewDialog.test.tsx
new file mode 100644
index 00000000..3ac4a90d
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewDialog.test.tsx
@@ -0,0 +1,408 @@
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act, StrictMode, useSyncExternalStore } from 'react';
+import type { Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import common from '../../../../messages/en/common.json';
+import filters from '../../../../messages/en/filters.json';
+import display from '../../../../messages/en/display.json';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+import { linkPreviewDestination } from './linkPreviewDestination';
+
+let dom: JSDOM;
+let root: Root;
+let queryClient: QueryClient;
+let LinkPreviewDialog: (typeof import('./LinkPreviewDialog'))['default'];
+let originalFetch: typeof fetch;
+type SessionSnapshot = ReturnType<(typeof import('@/lib/auth-client'))['useSession']>;
+// Loading the test helper without Bun's globals preserves the web app's fetch type.
+const { spyOn } = createRequire(import.meta.url)('bun:test') as {
+ spyOn: (
+ target: object,
+ method: string,
+ ) => {
+ mockImplementation: (implementation: () => SessionSnapshot) => { mockRestore: () => void };
+ };
+};
+let sessionSnapshot: SessionSnapshot;
+let restoreSession: () => void;
+const sessionListeners = new Set<() => void>();
+let originals: Map<string, PropertyDescriptor | undefined>;
+let calls: { url: URL; signal: AbortSignal | null | undefined }[];
+let respond: (url: URL, signal?: AbortSignal | null) => Promise<Response>;
+let sessionUser: string | null;
+let closeCount: number;
+let trigger: HTMLElement;
+let container: HTMLElement;
+
+const wait = (ms = 20) => act(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
+const preview = (title: string) => ({
+ url: 'https://example.test',
+ title,
+ description: 'Description',
+ image: null,
+ siteName: 'Metadata site name',
+});
+const sessionData = () =>
+ sessionUser ? { user: { id: sessionUser }, session: { id: `session-${sessionUser}` } } : null;
+
+function setSession(userId: string | null, pending = false) {
+ sessionUser = userId;
+ sessionSnapshot = { data: sessionData(), isPending: pending, error: null } as SessionSnapshot;
+ for (const listener of sessionListeners) listener();
+}
+
+function subscribeSession(listener: () => void) {
+ sessionListeners.add(listener);
+ return () => sessionListeners.delete(listener);
+}
+
+async function render(links: LinkPreviewItem[], strict = false) {
+ await act(() => {
+ const dialog = (
+ <NextIntlClientProvider locale="en" timeZone="UTC" messages={{ common, filters, display }}>
+ <QueryClientProvider client={queryClient}>
+ <LinkPreviewDialog
+ links={links}
+ trigger={trigger}
+ container={container}
+ onClose={() => closeCount++}
+ />
+ </QueryClientProvider>
+ </NextIntlClientProvider>
+ );
+ root.render(strict ? <StrictMode>{dialog}</StrictMode> : dialog);
+ });
+ await wait();
+}
+
+function button(label: string) {
+ const result = [...document.querySelectorAll('button')].find(
+ (element) =>
+ element.textContent?.trim() === label || element.getAttribute('aria-label') === label,
+ );
+ assert.ok(result, `Missing button: ${label}`);
+ return result;
+}
+
+async function click(element: HTMLElement) {
+ await act(async () => {
+ element.click();
+ await new Promise<void>((resolve) => setTimeout(resolve, 20));
+ });
+}
+
+beforeEach(async () => {
+ dom = new JSDOM(
+ '<div id="root"></div><div id="content"><button id="trigger">Preview</button></div>',
+ {
+ url: 'https://planner.test',
+ pretendToBeVisual: true,
+ },
+ );
+ dom.window.__ITSAPLAN_ENV__ = { apiUrl: 'http://api.test', privacyUrl: '', termsUrl: '' };
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ navigator: dom.window.navigator,
+ HTMLElement: dom.window.HTMLElement,
+ HTMLInputElement: dom.window.HTMLInputElement,
+ Element: dom.window.Element,
+ Node: dom.window.Node,
+ NodeFilter: dom.window.NodeFilter,
+ CustomEvent: dom.window.CustomEvent,
+ MutationObserver: dom.window.MutationObserver,
+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
+ requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window),
+ cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window),
+ IS_REACT_ACT_ENVIRONMENT: true,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+ originalFetch = globalThis.fetch;
+ calls = [];
+ respond = async () => Response.json(preview('Resolved title'));
+ globalThis.fetch = (async (input, init) => {
+ const url = new URL(String(input));
+ if (url.pathname.endsWith('/get-session')) return Response.json(sessionData());
+ calls.push({ url, signal: init?.signal });
+ return respond(url, init?.signal);
+ }) as typeof fetch;
+ const auth = await import('@/lib/auth-client');
+ // better-auth captures fetch at module import, which can precede this fixture in a combined run.
+ const sessionSpy = spyOn(auth, 'useSession').mockImplementation(function useTestSession() {
+ return useSyncExternalStore(
+ subscribeSession,
+ () => sessionSnapshot,
+ () => sessionSnapshot,
+ );
+ });
+ restoreSession = () => sessionSpy.mockRestore();
+ setSession('reader-1');
+ ({ default: LinkPreviewDialog } = await import('./LinkPreviewDialog'));
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ closeCount = 0;
+ trigger = document.getElementById('trigger')!;
+ container = document.getElementById('content')!;
+ trigger.focus();
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ await wait(5);
+ queryClient.clear();
+ restoreSession();
+ sessionListeners.clear();
+ globalThis.fetch = originalFetch;
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+describe('explicit link preview dialog', () => {
+ it('stays open during the development Strict Mode mount check', async () => {
+ await render(
+ [
+ { url: 'https://first.test', label: 'First' },
+ { url: 'https://second.test', label: 'Second' },
+ ],
+ true,
+ );
+ assert.equal(closeCount, 0);
+ assert.ok(document.querySelector('[role="dialog"]'));
+ await click(button('Close'));
+ assert.equal(closeCount, 1);
+ });
+ it('fetches only the selected destination and returns focus to its list row', async () => {
+ await render([
+ { url: 'https://first.test/a', label: 'First link' },
+ { url: 'https://second.test/b?token=exact#part', label: 'Second link' },
+ ]);
+ assert.equal(calls.length, 0);
+ const rows = [...document.querySelectorAll('li button')] as HTMLButtonElement[];
+ assert.equal(document.activeElement, rows[0]);
+ await click(rows[1]!);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0]!.url.searchParams.get('url'), 'https://second.test/b?token=exact#part');
+ assert.equal(document.activeElement?.textContent?.trim(), 'Open link');
+ assert.match(document.body.textContent!, /second.test/);
+ await click(button('Back to links'));
+ assert.equal(calls.length, 1);
+ assert.match(document.activeElement?.textContent ?? '', /Second link/);
+ });
+
+ it('keeps focused actions outside the scrolling metadata and URL', async () => {
+ const url = 'https://github.com/croffasia/itsaplan?tab=readme#installation';
+ queryClient.setQueryData(['link-preview', 'reader-1', url], {
+ ...preview('A long repository title with installation, deployment and configuration details'),
+ description: 'Repository documentation and installation instructions. '.repeat(12),
+ image: 'data:image/png;base64,iVBORw0KGgo=',
+ });
+ await render([{ url, label: url, onEdit: () => {} }]);
+ const scrollArea = document.querySelector('h3')!.closest('.overflow-y-auto')!;
+ const open = document.querySelector<HTMLAnchorElement>('a[data-link-preview-primary]')!;
+ assert.ok(scrollArea);
+ assert.ok(scrollArea.querySelector('img'));
+ assert.ok([...scrollArea.querySelectorAll('p')].some((element) => element.textContent === url));
+ assert.equal(scrollArea.contains(open), false);
+ assert.equal(scrollArea.contains(button('Copy link')), false);
+ assert.equal(scrollArea.contains(button('Edit link')), false);
+ assert.equal(document.activeElement, open);
+ });
+
+ it('uses destinations for bare URL headings and preserves author-written labels', async () => {
+ const links = [
+ {
+ url: 'https://github.com/project/repo?tab=readme#part',
+ label: 'https://github.com/project/repo?tab=readme#part',
+ },
+ { url: 'https://GITHUB.COM/project/other', label: 'https://github.com/project/other' },
+ { url: '/project/DEMO', label: '/project/DEMO' },
+ { url: '/project/PLAN', label: 'The project plan' },
+ ];
+ respond = (_url, signal) =>
+ new Promise((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(signal.reason));
+ });
+ await render(links);
+ const titles = ['github.com', 'github.com', 'ItsAPlan page', 'The project plan'];
+ for (const [index, title] of titles.entries()) {
+ const rows = [...document.querySelectorAll<HTMLButtonElement>('li button')];
+ await click(rows[index]!);
+ assert.equal(document.querySelector('h3')!.textContent, title);
+ assert.ok(
+ [...document.querySelectorAll('p')].some(
+ (element) => element.textContent === links[index]!.url,
+ ),
+ );
+ await click(button('Back to links'));
+ }
+ });
+
+ it('keeps the authored URL for opening and copying and reports clipboard failure', async () => {
+ const url = '/project/DEMO?token=A%2FB#exact';
+ let copied = '';
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {
+ writeText: async (value: string) => {
+ copied = value;
+ },
+ },
+ });
+ respond = async () =>
+ Response.json({ project: { key: 'DEMO', name: 'Project', description: '' } });
+ await render([{ url, label: 'Project label' }]);
+ const open = document.querySelector<HTMLAnchorElement>('a[data-link-preview-primary]')!;
+ assert.equal(open.getAttribute('href'), url);
+ assert.equal(open.target, '_blank');
+ assert.equal(open.rel, 'noopener noreferrer');
+ assert.equal(open.getAttribute('referrerpolicy'), 'no-referrer');
+ assert.equal(calls[0]!.url.pathname, '/projects/DEMO');
+ await click(button('Copy link'));
+ assert.equal(copied, url);
+ assert.ok(button('Copied'));
+ await wait(2020);
+ assert.ok(button('Copy link'));
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });
+ await click(button('Copy link'));
+ assert.match(document.querySelector('[role="status"]')!.textContent!, /Could not copy/);
+ assert.ok(button('Copy link'));
+ assert.ok(
+ [...document.querySelectorAll('p')].some(
+ (element) => element.textContent === url && element.dir === 'ltr',
+ ),
+ );
+ });
+
+ it('dismisses on Escape, aborts the pending query and restores focus without scrolling', async () => {
+ let aborted = false;
+ respond = (_url, signal) =>
+ new Promise((_resolve, reject) => {
+ signal?.addEventListener('abort', () => {
+ aborted = true;
+ reject(signal.reason);
+ });
+ });
+ await render([{ url: 'https://pending.test', label: 'Pending' }]);
+ assert.equal(calls.length, 1);
+ assert.match(document.body.textContent!, /Loading preview/);
+ let focusOptions: FocusOptions | undefined;
+ const focus = trigger.focus.bind(trigger);
+ trigger.focus = (options) => {
+ focusOptions = options;
+ focus(options);
+ };
+ await act(() =>
+ document.dispatchEvent(
+ new dom.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
+ ),
+ );
+ await wait();
+ assert.equal(closeCount, 1);
+ assert.equal(document.querySelector('[role="dialog"]'), null);
+ assert.equal(aborted, true);
+ assert.equal(document.activeElement, trigger);
+ assert.equal(focusOptions?.preventScroll, true);
+ });
+
+ it('focuses the content container when the trigger is gone', async () => {
+ await render([{ url: 'https://example.test', label: 'Example' }]);
+ trigger.remove();
+ await click(button('Close'));
+ assert.equal(closeCount, 1);
+ assert.equal(document.activeElement, container);
+ assert.equal(container.hasAttribute('tabindex'), false);
+ });
+
+ it('revalidates cached internal metadata and hides permission failures', async () => {
+ const url = 'https://planner.test/project/PRIVATE';
+ queryClient.setQueryData(
+ ['link-preview', 'reader-1', url, 'session-reader-1'],
+ preview('Previously permitted title'),
+ );
+ let resolve!: (response: Response) => void;
+ respond = () =>
+ new Promise((done) => {
+ resolve = done;
+ });
+ await render([{ url, label: 'Private link' }]);
+ assert.equal(calls.length, 1);
+ assert.doesNotMatch(document.body.textContent!, /Previously permitted title/);
+ await act(() => resolve(Response.json({ error: 'Forbidden' }, { status: 403 })));
+ await wait();
+ assert.doesNotMatch(document.body.textContent!, /Previously permitted title|Try again/);
+ assert.match(document.body.textContent!, /unavailable or you do not have access/);
+ assert.ok(document.querySelector('a[data-link-preview-primary]'));
+ });
+
+ it('reuses fresh external cache but clears it when the account or session changes', async () => {
+ const url = 'https://example.test/cached';
+ queryClient.setQueryData(['link-preview', 'reader-1', url], preview('Account one title'));
+ await render([{ url, label: 'External link' }]);
+ assert.equal(calls.length, 0);
+ assert.match(document.body.textContent!, /Account one title/);
+ respond = () => new Promise(() => {});
+ await act(() => setSession('reader-2'));
+ await wait();
+ assert.doesNotMatch(document.body.textContent!, /Account one title/);
+ assert.equal(calls.length, 1);
+ await act(() => setSession(null));
+ assert.doesNotMatch(document.body.textContent!, /Account one title/);
+ });
+
+ it('retries a network failure only on request and omits the action for 404', async () => {
+ respond = async () => {
+ throw new TypeError('Network failed');
+ };
+ await render([{ url: 'https://network.test', label: 'Network' }]);
+ assert.equal(calls.length, 1);
+ await wait(30);
+ assert.equal(calls.length, 1);
+ respond = async () => Response.json({ error: 'Not found' }, { status: 404 });
+ await click(button('Try again'));
+ assert.equal(calls.length, 2);
+ assert.doesNotMatch(document.body.textContent!, /Try again/);
+ });
+
+ it('offers editing only for a mapped occurrence and runs it after dismissal', async () => {
+ let edited = false;
+ await render([
+ {
+ url: 'https://example.test',
+ label: 'Example',
+ onEdit: () => {
+ assert.equal(document.querySelector('[role="dialog"]'), null);
+ assert.equal(closeCount, 1);
+ edited = true;
+ },
+ },
+ ]);
+ await click(button('Edit link'));
+ assert.equal(edited, true);
+ });
+
+ it('normalizes preview requests while rejecting unsupported and credential-bearing destinations', () => {
+ assert.equal(
+ linkPreviewDestination('/project/A?x=%2F#part', 'https://planner.test')?.href,
+ 'https://planner.test/project/A?x=%2F#part',
+ );
+ for (const url of [
+ 'javascript:alert(1)',
+ 'mailto:[email protected]',
+ 'https://user:[email protected]',
+ 'http://[',
+ ])
+ assert.equal(linkPreviewDestination(url), null);
+ });
+});
diff --git a/apps/web/src/components/common/editor/LinkPreviewDialog.tsx b/apps/web/src/components/common/editor/LinkPreviewDialog.tsx
new file mode 100644
index 00000000..5df89e6d
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewDialog.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { Content as DialogContent } from '@radix-ui/react-dialog';
+import { ArrowLeft, X } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogClose,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import LinkPreviewContent from './LinkPreviewContent';
+import LinkPreviewList from './LinkPreviewList';
+import LinkPreviewActions from './LinkPreviewActions';
+import { useLinkPreviewDialog } from './useLinkPreviewDialog';
+import styles from './LinkPreviewDialog.module.css';
+
+export type LinkPreviewItem = { url: string; label: string; onEdit?: () => void };
+
+export default function LinkPreviewDialog({
+ links,
+ onClose,
+ trigger,
+ container,
+}: {
+ links: LinkPreviewItem[];
+ onClose: () => void;
+ trigger: HTMLElement | null;
+ container: HTMLElement | null;
+}) {
+ const t = useTranslations('common');
+ const dialog = useLinkPreviewDialog({ linkCount: links.length, onClose, trigger, container });
+ const link = dialog.selected === null ? undefined : links[dialog.selected];
+
+ return (
+ <Dialog open={dialog.open} onOpenChange={dialog.setOpen}>
+ <DialogPortal>
+ <DialogOverlay className={styles.overlay} />
+ <DialogContent
+ ref={dialog.body}
+ data-slot="dialog-content"
+ className={`${styles.dialog} flex flex-col gap-4 overflow-hidden bg-card text-card-foreground outline-none`}
+ aria-describedby={undefined}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ dialog.focusAction();
+ }}
+ onCloseAutoFocus={dialog.closeAutoFocus}
+ onEscapeKeyDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <div className="flex shrink-0 items-center gap-4">
+ <DialogTitle className="min-w-0 flex-1 text-start text-base leading-normal">
+ {t('editor.linkPreview')}
+ </DialogTitle>
+ <DialogClose asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className={styles.control}
+ aria-label={t('close')}
+ >
+ <X aria-hidden="true" />
+ </Button>
+ </DialogClose>
+ </div>
+ <div className="flex min-h-0 flex-col gap-4 overflow-y-auto overscroll-contain">
+ {link && links.length > 1 && (
+ <Button
+ type="button"
+ variant="ghost"
+ className={`${styles.control} self-start`}
+ onClick={dialog.backToLinks}
+ >
+ <ArrowLeft className="rtl:rotate-180" aria-hidden="true" />
+ {t('editor.backToLinks')}
+ </Button>
+ )}
+ {link ? (
+ <LinkPreviewContent key={link.url} link={link} />
+ ) : (
+ <LinkPreviewList
+ links={links}
+ focusIndex={dialog.focusIndex}
+ onSelect={dialog.select}
+ />
+ )}
+ </div>
+ {link && (
+ <LinkPreviewActions
+ key={link.url}
+ url={link.url}
+ onEdit={link.onEdit ? () => dialog.editLink(link.onEdit!) : undefined}
+ />
+ )}
+ </DialogContent>
+ </DialogPortal>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/common/editor/LinkPreviewList.tsx b/apps/web/src/components/common/editor/LinkPreviewList.tsx
new file mode 100644
index 00000000..46664d27
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewList.tsx
@@ -0,0 +1,42 @@
+import { ChevronRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+import { linkPreviewDestination } from './linkPreviewDestination';
+import styles from './LinkPreviewDialog.module.css';
+
+export default function LinkPreviewList({
+ links,
+ focusIndex,
+ onSelect,
+}: {
+ links: LinkPreviewItem[];
+ focusIndex: number;
+ onSelect: (index: number) => void;
+}) {
+ const origin = typeof window === 'undefined' ? undefined : window.location.origin;
+ return (
+ <ul className="space-y-1">
+ {links.map((link, index) => (
+ <li key={`${index}:${link.url}`}>
+ <Button
+ type="button"
+ variant="ghost"
+ className={`${styles.control} w-full justify-start gap-4 p-3 text-start`}
+ data-link-preview-primary={index === focusIndex ? '' : undefined}
+ onClick={() => onSelect(index)}
+ >
+ <span className="min-w-0 flex-1 space-y-1">
+ <span className="block wrap-anywhere" dir="auto">
+ {link.label || link.url}
+ </span>
+ <span className="block text-sm font-normal text-muted-foreground" dir="ltr">
+ {linkPreviewDestination(link.url, origin)?.hostname}
+ </span>
+ </span>
+ <ChevronRight className="size-4 rtl:rotate-180" aria-hidden="true" />
+ </Button>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/web/src/components/common/editor/LinkPreviewThumbnail.tsx b/apps/web/src/components/common/editor/LinkPreviewThumbnail.tsx
new file mode 100644
index 00000000..75b13517
--- /dev/null
+++ b/apps/web/src/components/common/editor/LinkPreviewThumbnail.tsx
@@ -0,0 +1,33 @@
+import { useState } from 'react';
+import { CircleDot, FileText, FolderKanban, Globe, LayoutList, StickyNote } from 'lucide-react';
+import type { ResolvedLinkPreview } from './resolveLinkPreview';
+import styles from './LinkPresentation.module.css';
+
+const icons = {
+ project: FolderKanban,
+ issue: CircleDot,
+ document: FileText,
+ notes: StickyNote,
+ view: LayoutList,
+};
+
+export default function LinkPreviewThumbnail({
+ image,
+ kind,
+}: {
+ image?: string | null;
+ kind?: ResolvedLinkPreview['kind'];
+}) {
+ const [failed, setFailed] = useState<string>();
+ const Icon = kind ? icons[kind] : Globe;
+ return (
+ <span className={styles.thumbnail} aria-hidden="true">
+ {image && failed !== image ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={image} alt="" referrerPolicy="no-referrer" onError={() => setFailed(image)} />
+ ) : (
+ <Icon size={16} />
+ )}
+ </span>
+ );
+}
diff --git a/apps/web/src/components/common/editor/MarkdownEditor.tsx b/apps/web/src/components/common/editor/MarkdownEditor.tsx
index 4e855015..fcaac450 100644
--- a/apps/web/src/components/common/editor/MarkdownEditor.tsx
+++ b/apps/web/src/components/common/editor/MarkdownEditor.tsx
@@ -46,6 +46,7 @@ export default function MarkdownEditor({
editable = true,
uploadFile,
imageAttachments,
+ readingLinks = true,
}: {
defaultValue: string;
onChange?: (markdown: string) => void;
@@ -64,6 +65,7 @@ export default function MarkdownEditor({
// Offered in a picker, to embed an upload again. Omitted where there is nothing
// stored to read them from yet (a create dialog), which drops the picker.
imageAttachments?: Embeddable[];
+ readingLinks?: boolean;
}) {
const t = useTranslations('common.editor');
const editorRef = useRef<Editor | null>(null);
@@ -196,7 +198,7 @@ export default function MarkdownEditor({
{/* Grows with the text rather than being pinned to the container's height,
so a container that scrolls measures the overflow and shows a bar. */}
<EditorContent editor={editor} className="flex min-h-full flex-col" />
- <EditorLinkPreview editor={editor} />
+ <EditorLinkPreview editor={editor} source={defaultValue} compact={readingLinks} />
{imageAttachments && (
<EditorImagePicker
open={imagePickerOpen}
diff --git a/apps/web/src/components/common/editor/MarkdownLinkContent.tsx b/apps/web/src/components/common/editor/MarkdownLinkContent.tsx
new file mode 100644
index 00000000..9446010b
--- /dev/null
+++ b/apps/web/src/components/common/editor/MarkdownLinkContent.tsx
@@ -0,0 +1,68 @@
+import { useMemo, useRef, useState } from 'react';
+import { useLinkInputCapabilities } from './useLinkInputCapabilities';
+import { copyPresentedLinks, staticLinkBlocks } from './staticLinkPresentation';
+import LinkBlockControls from './LinkBlockControls';
+import LinkPreviewDialog, { type LinkPreviewItem } from './LinkPreviewDialog';
+import styles from './LinkPresentation.module.css';
+
+export default function MarkdownLinkContent({
+ html,
+ bareUrls,
+ complete,
+}: {
+ html: string;
+ bareUrls: ReadonlySet<string>;
+ complete: boolean;
+}) {
+ const capabilities = useLinkInputCapabilities();
+ const ref = useRef<HTMLDivElement>(null);
+ const [dialog, setDialog] = useState<{
+ links: LinkPreviewItem[];
+ trigger: HTMLButtonElement;
+ } | null>(null);
+ const blocks = useMemo(
+ () =>
+ complete && capabilities.explicit
+ ? staticLinkBlocks(html, bareUrls, window.location.origin)
+ : null,
+ [html, bareUrls, complete, capabilities.explicit],
+ );
+ return (
+ <div ref={ref} className="md-content" tabIndex={-1} onCopy={copyPresentedLinks}>
+ {blocks ? (
+ blocks.map((block, index) => (
+ <div
+ key={index}
+ className={
+ block.bare && capabilities.compact ? styles.staticCompact : styles.staticBlock
+ }
+ >
+ {!(block.bare && capabilities.compact) && (
+ <div dangerouslySetInnerHTML={{ __html: block.html }} />
+ )}
+ {block.bare && capabilities.compact && (
+ <div
+ data-link-original=""
+ className={styles.original}
+ dangerouslySetInnerHTML={{ __html: block.html }}
+ />
+ )}
+ {block.links.length > 0 && (
+ <LinkBlockControls
+ links={block.links}
+ compact={block.bare && capabilities.compact}
+ expanded={dialog?.links === block.links}
+ onPreview={(links, trigger) => setDialog({ links, trigger })}
+ />
+ )}
+ </div>
+ ))
+ ) : (
+ <div dangerouslySetInnerHTML={{ __html: html }} />
+ )}
+ {dialog && (
+ <LinkPreviewDialog {...dialog} container={ref.current} onClose={() => setDialog(null)} />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/common/editor/editorLinkPresentation.ts b/apps/web/src/components/common/editor/editorLinkPresentation.ts
new file mode 100644
index 00000000..79fd6c74
--- /dev/null
+++ b/apps/web/src/components/common/editor/editorLinkPresentation.ts
@@ -0,0 +1,144 @@
+import type { Editor } from '@tiptap/react';
+import { ReactRenderer } from '@tiptap/react';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import LinkBlockControls from './LinkBlockControls';
+import { bareMarkdownUrls, editorLinkBlocks, type EditorLinkBlock } from './linkPresentation';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+import styles from './LinkPresentation.module.css';
+
+type PresentationOptions = { enabled: boolean; compact: boolean; suspended: boolean };
+type PresentationState = { blocks: EditorLinkBlock[]; sourceUnchanged: boolean };
+
+export function createEditorLinkPresentation(
+ editor: Editor,
+ source: string,
+ onPreview: (links: LinkPreviewItem[], trigger: HTMLButtonElement) => void,
+) {
+ const key = new PluginKey<PresentationState>('linkPresentation');
+ const bareUrls = bareMarkdownUrls(source);
+ const originalDoc = editor.state.doc;
+ let options: PresentationOptions = { enabled: false, compact: false, suspended: false };
+ let decorations = DecorationSet.empty;
+ let destroyed = false;
+ let refreshQueued = false;
+
+ function refresh() {
+ if (destroyed || editor.isDestroyed) return;
+ const state = key.getState(editor.state);
+ if (!state) return;
+ decorations = build(state.blocks, state.sourceUnchanged);
+ editor.view.updateState(editor.state);
+ }
+
+ function scheduleRefresh() {
+ if (refreshQueued) return;
+ refreshQueued = true;
+ // ReactRenderer flushes synchronously when EditorContent is mounted.
+ queueMicrotask(() => {
+ refreshQueued = false;
+ refresh();
+ });
+ }
+
+ function build(blocks: EditorLinkBlock[], sourceUnchanged: boolean) {
+ if (!options.enabled || options.suspended) return DecorationSet.empty;
+ const result: Decoration[] = [];
+ for (const block of blocks) {
+ const compact = options.compact && block.bare && sourceUnchanged;
+ if (compact)
+ result.push(Decoration.node(block.from, block.to, { class: styles.compactBlock }));
+ result.push(
+ Decoration.widget(
+ block.to - 1,
+ () => {
+ const sourceDoc = editor.state.doc;
+ const links = block.links.map((link) => ({
+ url: link.url,
+ label: link.label,
+ onEdit: editor.isEditable
+ ? () => {
+ if (editor.isDestroyed || !editor.isEditable || !sourceDoc.eq(editor.state.doc))
+ return;
+ editor.chain().focus().setTextSelection({ from: link.from, to: link.to }).run();
+ }
+ : undefined,
+ }));
+ const renderer = new ReactRenderer(LinkBlockControls, {
+ editor,
+ as: 'span',
+ className: styles.widget,
+ props: { links, compact, onPreview },
+ });
+ renderer.element.setAttribute('data-link-widget', '');
+ renderers.set(renderer.element, renderer);
+ return renderer.element;
+ },
+ {
+ side: 1,
+ marks: [],
+ stopEvent: () => true,
+ ignoreSelection: true,
+ destroy: (node) => {
+ renderers.get(node)?.destroy();
+ renderers.delete(node);
+ },
+ },
+ ),
+ );
+ }
+ return DecorationSet.create(editor.state.doc, result);
+ }
+
+ const renderers = new Map<Node, ReactRenderer>();
+ const plugin = new Plugin<PresentationState>({
+ key,
+ state: {
+ init: (_, state) => ({
+ blocks: editorLinkBlocks(state.doc, bareUrls, window.location.origin),
+ sourceUnchanged: true,
+ }),
+ apply: (transaction, previous) => {
+ if (!transaction.docChanged) return previous;
+ decorations = DecorationSet.empty;
+ return {
+ blocks: editorLinkBlocks(transaction.doc, bareUrls, window.location.origin),
+ sourceUnchanged: transaction.doc.eq(originalDoc),
+ };
+ },
+ },
+ props: { decorations: () => decorations },
+ view: (view) => {
+ let previous = key.getState(view.state)!;
+ return {
+ update: (nextView) => {
+ const next = key.getState(nextView.state)!;
+ if (previous === next) return;
+ previous = next;
+ scheduleRefresh();
+ },
+ destroy: () => {
+ destroyed = true;
+ for (const renderer of renderers.values()) renderer.destroy();
+ renderers.clear();
+ },
+ };
+ },
+ });
+
+ return {
+ plugin,
+ key,
+ configure(next: PresentationOptions) {
+ if (
+ options.enabled === next.enabled &&
+ options.compact === next.compact &&
+ options.suspended === next.suspended
+ )
+ return;
+ options = next;
+ if (!next.enabled || next.suspended) refresh();
+ else scheduleRefresh();
+ },
+ };
+}
diff --git a/apps/web/src/components/common/editor/isRetryableLinkPreviewError.ts b/apps/web/src/components/common/editor/isRetryableLinkPreviewError.ts
new file mode 100644
index 00000000..8d3bcef2
--- /dev/null
+++ b/apps/web/src/components/common/editor/isRetryableLinkPreviewError.ts
@@ -0,0 +1,9 @@
+import { ApiError } from '@/lib/api/core/client';
+
+export function isRetryableLinkPreviewError(error: unknown) {
+ return (
+ error instanceof TypeError ||
+ (error instanceof Error && error.name === 'TimeoutError') ||
+ (error instanceof ApiError && [408, 502, 503, 504].includes(error.status))
+ );
+}
diff --git a/apps/web/src/components/common/editor/linkPresentation.test.ts b/apps/web/src/components/common/editor/linkPresentation.test.ts
new file mode 100644
index 00000000..6062a72e
--- /dev/null
+++ b/apps/web/src/components/common/editor/linkPresentation.test.ts
@@ -0,0 +1,266 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { Editor } from '@tiptap/core';
+import Link from '@tiptap/extension-link';
+import StarterKit from '@tiptap/starter-kit';
+import { Markdown } from 'tiptap-markdown';
+import { JSDOM } from 'jsdom';
+import {
+ bareMarkdownUrls,
+ editorLinkBlocks,
+ linkDestination,
+ previewUrl,
+} from './linkPresentation';
+import { createEditorLinkPresentation } from './editorLinkPresentation';
+import { copyPresentedLinks, staticLinkBlocks } from './staticLinkPresentation';
+import type { ClipboardEvent } from 'react';
+import { renderMarkdown } from '@/lib/markdown';
+
+let dom: JSDOM;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let editor: Editor | undefined;
+
+beforeEach(() => {
+ dom = new JSDOM('<div id="editor"></div>', { url: 'https://planner.test' });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ navigator: dom.window.navigator,
+ DOMParser: dom.window.DOMParser,
+ Node: dom.window.Node,
+ Element: dom.window.Element,
+ HTMLElement: dom.window.HTMLElement,
+ HTMLAnchorElement: dom.window.HTMLAnchorElement,
+ getComputedStyle: dom.window.getComputedStyle,
+ requestAnimationFrame: (fn: FrameRequestCallback) => setTimeout(fn, 0),
+ cancelAnimationFrame: clearTimeout,
+ };
+ originals = new Map(
+ Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
+ );
+ for (const [key, value] of Object.entries(globals))
+ Object.defineProperty(globalThis, key, { configurable: true, value });
+});
+
+afterEach(() => {
+ editor?.destroy();
+ editor = undefined;
+ dom.window.close();
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+function makeEditor(source: string) {
+ editor = new Editor({
+ element: dom.window.document.getElementById('editor')!,
+ extensions: [
+ StarterKit.configure({ link: false }),
+ Link.configure({ openOnClick: false }),
+ Markdown.configure({ html: true, linkify: true, breaks: true }),
+ ],
+ content: source,
+ editorProps: { handleScrollToSelection: () => true },
+ });
+ return editor;
+}
+
+describe('link presentation classification', () => {
+ it('retains named labels and only compacts parsed standalone exact URLs', () => {
+ const source = [
+ 'https://docs.example.com/API/Guide?token=A%2FB#Part-2',
+ '<https://example.com/autolink>',
+ '[installation steps](https://example.com/guide)',
+ '[https://example.com/guide](https://other.example/path)',
+ 'Source: https://example.com/source',
+ 'https://example.com/first\nhttps://example.com/second',
+ '`https://example.com/code`',
+ ].join('\n\n');
+ const urls = bareMarkdownUrls(source);
+ assert.deepEqual(
+ [...urls],
+ ['https://docs.example.com/API/Guide?token=A%2FB#Part-2', 'https://example.com/autolink'],
+ );
+ const current = makeEditor(source);
+ const blocks = editorLinkBlocks(current.state.doc, urls, 'https://planner.test');
+ assert.equal(blocks.filter((block) => block.bare).length, 2);
+ assert.equal(
+ blocks.find((block) => block.links[0].label === 'installation steps')?.bare,
+ false,
+ );
+ assert.equal(
+ blocks.find((block) => block.links[0].url === 'https://other.example/path')?.links[0].label,
+ 'https://example.com/guide',
+ );
+ assert.equal(
+ blocks.some((block) => block.links.some((link) => link.url.endsWith('/code'))),
+ false,
+ );
+ });
+
+ it('keeps ambiguous named URL labels and JSON without source in native text', () => {
+ const source =
+ 'https://example.com/guide\n\n[https://example.com/guide](https://example.com/guide)';
+ assert.equal(bareMarkdownUrls(source).size, 0);
+ const current = makeEditor('https://example.com/guide');
+ assert.equal(
+ editorLinkBlocks(current.state.doc, new Set(), 'https://planner.test')[0].bare,
+ false,
+ );
+ });
+
+ it('retains authored URL spelling while deriving display-only host and path', () => {
+ const url = 'https://www.docs.example.com/Case/A%2FB?signature=abc#Header';
+ assert.deepEqual(linkDestination(url, 'https://planner.test'), {
+ hostname: 'docs.example.com',
+ pathname: '/Case/A%2FB',
+ });
+ assert.equal(
+ previewUrl('/project/EX', 'https://planner.test')?.href,
+ 'https://planner.test/project/EX',
+ );
+ for (const unsafe of [
+ 'javascript:alert(1)',
+ 'mailto:[email protected]',
+ 'tel:123',
+ 'https://user:[email protected]',
+ '/media/file/raw',
+ 'https://example.com/file?download=1',
+ ])
+ assert.equal(previewUrl(unsafe, 'https://planner.test'), null);
+ });
+
+ it('keeps static sanitizer output and excludes code, images, downloads and tables', () => {
+ const source =
+ 'https://example.com/one\n\n[human label](https://example.com/two)\n\n`https://example.com/code`';
+ const html = renderMarkdown(source, { newTabLinks: true });
+ const blocks = staticLinkBlocks(html, bareMarkdownUrls(source), 'https://planner.test');
+ assert.equal(blocks.filter((block) => block.bare).length, 1);
+ assert.equal(blocks.flatMap((block) => block.links).length, 2);
+ assert.equal(blocks.flatMap((block) => block.links)[1].label, 'human label');
+ const excluded = staticLinkBlocks(
+ '<p><a href="https://example.com/file" download>File</a></p><table><tr><td><a href="https://example.com/table">Table</a></td></tr></table><p><a href="https://example.com/image"><img src="/image"></a></p>',
+ new Set(),
+ 'https://planner.test',
+ );
+ assert.equal(excluded.flatMap((block) => block.links).length, 0);
+ });
+
+ it('preserves safe new-tab navigation through the actual static render path', () => {
+ const source = '[Outside](https://example.com/A?key=%2F#part)';
+ const html = renderMarkdown(source, { newTabLinks: true });
+ const blocks = staticLinkBlocks(html, bareMarkdownUrls(source), 'https://planner.test');
+ const parsed = new DOMParser().parseFromString(blocks[0].html, 'text/html');
+ const link = parsed.querySelector('a')!;
+ assert.equal(link.getAttribute('target'), '_blank');
+ assert.equal(link.getAttribute('rel'), 'noreferrer');
+ assert.equal(link.getAttribute('href'), 'https://example.com/A?key=%2F#part');
+ });
+
+ it('copies actual static selections with block and hard-break separators', () => {
+ const element = document.getElementById('editor')!;
+ element.innerHTML =
+ '<div><p>First <a href="https://first.test">Alpha</a></p><span data-link-presentation><button data-link-preview-control>Preview link</button></span></div><div><p>Second <a href="https://second.test">Beta</a><br>Third line</p></div>';
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ window.getSelection()!.addRange(range);
+ const copied = new Map<string, string>();
+ let prevented = false;
+ copyPresentedLinks({
+ preventDefault: () => {
+ prevented = true;
+ },
+ clipboardData: { setData: (type: string, value: string) => copied.set(type, value) },
+ } as unknown as ClipboardEvent<HTMLElement>);
+ assert.equal(prevented, true);
+ assert.equal(copied.get('text/plain'), 'First Alpha\nSecond Beta\nThird line');
+ assert.doesNotMatch(copied.get('text/html')!, /Preview link/);
+ });
+
+ it('copies compact source labels once without metadata or hidden duplicates', () => {
+ const element = document.getElementById('editor')!;
+ element.innerHTML =
+ '<div><div data-link-original>https://first.test/A?key=%2F#part</div><span data-link-presentation><a href="https://first.test/A?key=%2F#part" data-link-row="https://first.test/A?key=%2F#part">Fetched title first.test</a><button data-link-preview-control>Preview</button></span></div><div><p>Original second paragraph</p></div>';
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ window.getSelection()!.addRange(range);
+ const copied = new Map<string, string>();
+ copyPresentedLinks({
+ preventDefault() {},
+ clipboardData: { setData: (type: string, value: string) => copied.set(type, value) },
+ } as unknown as ClipboardEvent<HTMLElement>);
+ assert.equal(
+ copied.get('text/plain'),
+ 'https://first.test/A?key=%2F#part\nOriginal second paragraph',
+ );
+ assert.doesNotMatch(
+ copied.get('text/html')!,
+ /Fetched title|data-link-original|data-link-preview-control/,
+ );
+ });
+});
+
+describe('ProseMirror reading decorations preserve the source', () => {
+ it('adds and removes presentation without transactions, autosave, history or serialized UI', async () => {
+ const source =
+ 'https://example.com/guide?key=a%2Fb#Section\n\n[Named label](https://example.com/named)';
+ const current = makeEditor(source);
+ const json = current.getJSON();
+ const markdown = current.storage.markdown.getMarkdown();
+ let updates = 0;
+ let transactions = 0;
+ current.on('update', () => updates++);
+ current.on('transaction', () => transactions++);
+ const presentation = createEditorLinkPresentation(current, source, () => {});
+ current.registerPlugin(presentation.plugin);
+ for (const suspended of [false, true, false, true, false]) {
+ presentation.configure({ enabled: true, compact: true, suspended });
+ await Promise.resolve();
+ assert.deepEqual(current.getJSON(), json);
+ assert.equal(current.storage.markdown.getMarkdown(), markdown);
+ }
+ assert.equal(current.view.dom.querySelectorAll('[data-link-widget]').length, 2);
+ const copied = current.view.serializeForClipboard(
+ current.state.doc.slice(0, current.state.doc.content.size),
+ );
+ assert.equal(copied.dom.querySelector('[data-link-widget]'), null);
+ assert.equal(copied.dom.textContent, 'https://example.com/guide?key=a%2Fb#SectionNamed label');
+ assert.equal(updates, 0);
+ assert.equal(transactions, 0);
+ assert.equal(current.can().undo(), false);
+ });
+
+ it('preserves selection and undo after composition-style content changes', async () => {
+ const source = 'https://example.com/guide';
+ const current = makeEditor(source);
+ const before = current.getJSON();
+ const presentation = createEditorLinkPresentation(current, source, () => {});
+ current.registerPlugin(presentation.plugin);
+ presentation.configure({ enabled: true, compact: true, suspended: false });
+ await Promise.resolve();
+ current.commands.setTextSelection(5);
+ const selection = current.state.selection.toJSON();
+ presentation.configure({ enabled: true, compact: true, suspended: true });
+ assert.deepEqual(current.state.selection.toJSON(), selection);
+ current.view.dispatch(current.state.tr.insertText('文字').setMeta('composition', 1));
+ assert.notDeepEqual(current.getJSON(), before);
+ presentation.configure({ enabled: true, compact: true, suspended: false });
+ current.commands.undo();
+ assert.deepEqual(current.getJSON(), before);
+ assert.equal(current.storage.markdown.getMarkdown(), '<https://example.com/guide>');
+ });
+
+ it('keeps actual edits intact while recomputing presentation', async () => {
+ const source = 'https://example.com/guide';
+ const current = makeEditor(source);
+ const presentation = createEditorLinkPresentation(current, source, () => {});
+ current.registerPlugin(presentation.plugin);
+ presentation.configure({ enabled: true, compact: true, suspended: false });
+ await Promise.resolve();
+ current.commands.insertContentAt(1, 'prefix ');
+ await Promise.resolve();
+ assert.equal(current.view.dom.querySelectorAll('[data-link-widget]').length, 1);
+ assert.equal(current.storage.markdown.getMarkdown().includes('prefix'), true);
+ });
+});
diff --git a/apps/web/src/components/common/editor/linkPresentation.ts b/apps/web/src/components/common/editor/linkPresentation.ts
new file mode 100644
index 00000000..6dfe7fca
--- /dev/null
+++ b/apps/web/src/components/common/editor/linkPresentation.ts
@@ -0,0 +1,94 @@
+import { marked, type Token, type Tokens } from 'marked';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { linkPreviewDestination } from './linkPreviewDestination';
+
+export type LinkOccurrence = { url: string; label: string; from: number; to: number };
+export type EditorLinkBlock = {
+ from: number;
+ to: number;
+ links: LinkOccurrence[];
+ bare: boolean;
+};
+
+export function previewUrl(url: string, origin: string): URL | null {
+ const parsed = linkPreviewDestination(url, origin);
+ if (
+ !parsed ||
+ /\/(?:raw|download)(?:\/|$)/i.test(parsed.pathname) ||
+ parsed.searchParams.has('download')
+ )
+ return null;
+ return parsed;
+}
+
+export function bareMarkdownUrls(source: string): Set<string> {
+ const bare = new Set<string>();
+ const named = new Set<string>();
+ const tokens = marked.lexer(source, { breaks: true, gfm: true });
+ marked.walkTokens(tokens, (token: Token) => {
+ if (token.type === 'link' && token.raw.startsWith('[')) named.add((token as Tokens.Link).href);
+ if (token.type !== 'paragraph') return;
+ const parts = (token as Tokens.Paragraph).tokens.filter(
+ (part) => part.type !== 'text' || part.raw.trim() !== '',
+ );
+ if (parts.length !== 1 || parts[0].type !== 'link') return;
+ const link = parts[0] as Tokens.Link;
+ if (link.text === link.href && (link.raw === link.href || link.raw === `<${link.href}>`))
+ bare.add(link.href);
+ });
+ for (const url of named) bare.delete(url);
+ return bare;
+}
+
+export function editorLinkBlocks(
+ doc: ProseMirrorNode,
+ bareUrls: ReadonlySet<string>,
+ origin: string,
+): EditorLinkBlock[] {
+ const blocks: EditorLinkBlock[] = [];
+ doc.descendants((node, position) => {
+ if (node.type.name === 'table' || node.type.name === 'codeBlock') return false;
+ if (!node.isTextblock) return;
+ const links: LinkOccurrence[] = [];
+ let onlyLinkText = true;
+ node.forEach((child, offset) => {
+ const mark = child.marks.find((item) => item.type.name === 'link');
+ const url = typeof mark?.attrs.href === 'string' ? mark.attrs.href : '';
+ if (
+ !child.isText ||
+ child.marks.some((item) => item.type.name === 'code') ||
+ !previewUrl(url, origin) ||
+ !url
+ ) {
+ if (!child.isText || child.text?.trim()) onlyLinkText = false;
+ return;
+ }
+ const from = position + 1 + offset;
+ const previous = links.at(-1);
+ if (previous?.url === url && previous.to === from) {
+ previous.label += child.text ?? '';
+ previous.to += child.nodeSize;
+ } else links.push({ url, label: child.text ?? '', from, to: from + child.nodeSize });
+ });
+ if (links.length) {
+ blocks.push({
+ from: position,
+ to: position + node.nodeSize,
+ links,
+ bare:
+ node.type.name === 'paragraph' &&
+ onlyLinkText &&
+ links.length === 1 &&
+ node.textContent.trim() === links[0].url &&
+ bareUrls.has(links[0].url),
+ });
+ }
+ return false;
+ });
+ return blocks;
+}
+
+export function linkDestination(url: string, origin: string) {
+ const parsed = new URL(url, origin);
+ return { hostname: parsed.hostname.replace(/^www\./, ''), pathname: parsed.pathname };
+}
diff --git a/apps/web/src/components/common/editor/linkPreviewDestination.ts b/apps/web/src/components/common/editor/linkPreviewDestination.ts
new file mode 100644
index 00000000..fe6e9d51
--- /dev/null
+++ b/apps/web/src/components/common/editor/linkPreviewDestination.ts
@@ -0,0 +1,14 @@
+export function linkPreviewDestination(url: string, origin?: string) {
+ try {
+ const destination = new URL(url, origin);
+ if (
+ !['http:', 'https:'].includes(destination.protocol) ||
+ destination.username ||
+ destination.password
+ )
+ return null;
+ return destination;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/src/components/common/editor/staticLinkPresentation.ts b/apps/web/src/components/common/editor/staticLinkPresentation.ts
new file mode 100644
index 00000000..683668d7
--- /dev/null
+++ b/apps/web/src/components/common/editor/staticLinkPresentation.ts
@@ -0,0 +1,84 @@
+import DOMPurify from 'isomorphic-dompurify';
+import type { ClipboardEvent } from 'react';
+import { previewUrl } from './linkPresentation';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+
+export type StaticLinkBlock = { html: string; links: LinkPreviewItem[]; bare: boolean };
+
+export function staticLinkBlocks(html: string, bareUrls: ReadonlySet<string>, origin: string) {
+ const fragment = DOMPurify.sanitize(html, { RETURN_DOM_FRAGMENT: true, ADD_ATTR: ['target'] });
+ return Array.from(fragment.childNodes).map((node): StaticLinkBlock => {
+ if (node.nodeType !== 1) {
+ const wrapper = fragment.ownerDocument.createElement('span');
+ wrapper.textContent = node.textContent;
+ return { html: wrapper.innerHTML, links: [], bare: false };
+ }
+ const element = node as Element;
+ const links = Array.from(element.querySelectorAll<HTMLAnchorElement>('a[href]'))
+ .filter(
+ (link) =>
+ !link.hasAttribute('download') &&
+ !link.closest('code, pre, table, [data-mention]') &&
+ !link.querySelector('img') &&
+ previewUrl(link.getAttribute('href')!, origin),
+ )
+ .map((link) => ({ url: link.getAttribute('href')!, label: link.textContent ?? '' }));
+ return {
+ html: element.outerHTML,
+ links,
+ bare:
+ element.tagName === 'P' &&
+ links.length === 1 &&
+ element.textContent?.trim() === links[0].url &&
+ bareUrls.has(links[0].url) &&
+ Array.from(element.childNodes).every(
+ (child) =>
+ (child.nodeType === 3 && !child.textContent?.trim()) ||
+ (child.nodeType === 1 && (child as Element).tagName === 'A'),
+ ),
+ };
+ });
+}
+
+export function copyPresentedLinks(event: ClipboardEvent<HTMLElement>) {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed || !selection.rangeCount) return;
+ const fragment = selection.getRangeAt(0).cloneContents();
+ if (!fragment.querySelector('[data-link-presentation]')) return;
+ for (const source of fragment.querySelectorAll('[data-link-original]')) source.remove();
+ for (const control of fragment.querySelectorAll('[data-link-preview-control]')) control.remove();
+ for (const link of fragment.querySelectorAll('[data-link-row]'))
+ link.textContent = link.getAttribute('data-link-row');
+ const wrapper = document.createElement('div');
+ wrapper.append(fragment);
+ event.preventDefault();
+ event.clipboardData.setData('text/plain', clipboardText(wrapper));
+ event.clipboardData.setData('text/html', wrapper.innerHTML);
+}
+
+function clipboardText(root: Node) {
+ let text = '';
+ const boundary = () => {
+ if (text && !text.endsWith('\n')) text += '\n';
+ };
+ const visit = (node: Node) => {
+ if (node.nodeType === 3) {
+ text += node.textContent ?? '';
+ return;
+ }
+ if (node.nodeName === 'BR') {
+ text += '\n';
+ return;
+ }
+ const block =
+ /^(ADDRESS|ARTICLE|ASIDE|BLOCKQUOTE|DIV|H[1-6]|HR|LI|OL|P|PRE|SECTION|TABLE|TR|UL)$/.test(
+ node.nodeName,
+ );
+ if (block) boundary();
+ for (const child of node.childNodes) visit(child);
+ if (block) boundary();
+ if (node.nodeName === 'TD' || node.nodeName === 'TH') text += '\t';
+ };
+ visit(root);
+ return text.replace(/\n$/, '');
+}
diff --git a/apps/web/src/components/common/editor/useEditorLinkPresentation.ts b/apps/web/src/components/common/editor/useEditorLinkPresentation.ts
new file mode 100644
index 00000000..c2629da4
--- /dev/null
+++ b/apps/web/src/components/common/editor/useEditorLinkPresentation.ts
@@ -0,0 +1,101 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { Editor } from '@tiptap/react';
+import { createEditorLinkPresentation } from './editorLinkPresentation';
+import { useLinkInputCapabilities } from './useLinkInputCapabilities';
+import type { LinkPreviewItem } from './LinkPreviewDialog';
+
+type PreviewSelection = { links: LinkPreviewItem[]; trigger: HTMLButtonElement };
+
+export function useEditorLinkPresentation(editor: Editor, source: string, compactAllowed: boolean) {
+ const { compact, explicit } = useLinkInputCapabilities();
+ const [dialog, setDialog] = useState<PreviewSelection | null>(null);
+ const presentation = useRef<ReturnType<typeof createEditorLinkPresentation> | null>(null);
+ const sourceRef = useRef(source);
+ const capabilityRef = useRef({ compact, explicit });
+ const compactRef = useRef(compactAllowed);
+ const dialogRef = useRef(dialog);
+ dialogRef.current = dialog;
+ const suspended = useRef(false);
+
+ const refresh = useCallback(() => {
+ presentation.current?.configure({
+ enabled: capabilityRef.current.explicit,
+ compact: capabilityRef.current.compact && compactRef.current,
+ suspended: suspended.current,
+ });
+ }, []);
+
+ useEffect(() => {
+ const instance = createEditorLinkPresentation(editor, sourceRef.current, (links, trigger) => {
+ setDialog({ links, trigger });
+ });
+ presentation.current = instance;
+ editor.registerPlugin(instance.plugin);
+ const root = editor.view.dom;
+ const suspend = () => {
+ suspended.current = true;
+ refresh();
+ };
+ const resume = () => {
+ if (dialogRef.current || editor.isFocused || editor.view.composing) return;
+ const selection = window.getSelection();
+ if (selection && !selection.isCollapsed && root.contains(selection.anchorNode)) return;
+ suspended.current = false;
+ refresh();
+ };
+ const focus = (event: FocusEvent) => {
+ if ((event.target as Element | null)?.closest('[data-link-presentation]')) return;
+ if (editor.isEditable) suspend();
+ };
+ const pointer = (event: PointerEvent) => {
+ if ((event.target as Element | null)?.closest('a, [data-link-presentation]')) return;
+ suspend();
+ };
+ const selection = () => {
+ const range = window.getSelection();
+ if (
+ range &&
+ !range.isCollapsed &&
+ (root.contains(range.anchorNode) || root.contains(range.focusNode))
+ )
+ suspend();
+ };
+ const changed = () => setDialog(null);
+ root.addEventListener('focusin', focus);
+ root.addEventListener('pointerdown', pointer, true);
+ root.addEventListener('compositionstart', suspend);
+ root.addEventListener('compositionend', resume);
+ root.addEventListener('focusout', resume);
+ root.addEventListener('blur', resume);
+ document.addEventListener('selectionchange', selection);
+ editor.on('update', changed);
+ refresh();
+ return () => {
+ root.removeEventListener('focusin', focus);
+ root.removeEventListener('pointerdown', pointer, true);
+ root.removeEventListener('compositionstart', suspend);
+ root.removeEventListener('compositionend', resume);
+ root.removeEventListener('focusout', resume);
+ root.removeEventListener('blur', resume);
+ document.removeEventListener('selectionchange', selection);
+ editor.off('update', changed);
+ editor.unregisterPlugin(instance.key);
+ presentation.current = null;
+ };
+ }, [editor, refresh]);
+
+ useEffect(() => {
+ if (!dialog) return;
+ dialog.trigger.setAttribute('aria-expanded', 'true');
+ return () => dialog.trigger.setAttribute('aria-expanded', 'false');
+ }, [dialog]);
+
+ useEffect(() => {
+ if (dialog) return;
+ capabilityRef.current = { compact, explicit };
+ compactRef.current = compactAllowed;
+ refresh();
+ }, [compact, explicit, compactAllowed, dialog, refresh]);
+
+ return { dialog, closeDialog: () => setDialog(null) };
+}
diff --git a/apps/web/src/components/common/editor/useEditorLinkPreview.ts b/apps/web/src/components/common/editor/useEditorLinkPreview.ts
index 2ac1032f..66741389 100644
--- a/apps/web/src/components/common/editor/useEditorLinkPreview.ts
+++ b/apps/web/src/components/common/editor/useEditorLinkPreview.ts
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import type { Editor } from '@tiptap/react';
import { previewableLink } from './previewableLink';
-export function useEditorLinkPreview(editor: Editor) {
+export function useEditorLinkPreview(editor: Editor, disabled = false) {
const [anchor, setAnchor] = useState<HTMLAnchorElement | null>(null);
const [candidateAnchor, setCandidateAnchor] = useState<HTMLAnchorElement | null>(null);
const [open, setOpen] = useState(false);
@@ -38,9 +38,21 @@ export function useEditorLinkPreview(editor: Editor) {
}, [close]);
useEffect(() => {
+ if (disabled) {
+ close();
+ return;
+ }
const root = editor.view.dom;
+ let touchFocus = false;
+ const pointerDown = (event: PointerEvent) => {
+ touchFocus = event.pointerType === 'touch' || event.pointerType === 'pen';
+ };
+ const keyDown = () => {
+ touchFocus = false;
+ };
const enter = (event: Event) => {
if (event instanceof PointerEvent && event.pointerType === 'touch') return;
+ if (event.type === 'focusin' && touchFocus) return;
const link = previewableLink(event.target, root);
if (!link) return;
keepOpen();
@@ -70,6 +82,8 @@ export function useEditorLinkPreview(editor: Editor) {
close();
};
root.addEventListener('pointerover', enter);
+ root.addEventListener('pointerdown', pointerDown, true);
+ root.addEventListener('keydown', keyDown, true);
root.addEventListener('pointerout', exit);
root.addEventListener('focusin', enter);
root.addEventListener('focusout', exit);
@@ -77,6 +91,8 @@ export function useEditorLinkPreview(editor: Editor) {
window.addEventListener('scroll', close, true);
return () => {
root.removeEventListener('pointerover', enter);
+ root.removeEventListener('pointerdown', pointerDown, true);
+ root.removeEventListener('keydown', keyDown, true);
root.removeEventListener('pointerout', exit);
root.removeEventListener('focusin', enter);
root.removeEventListener('focusout', exit);
@@ -86,7 +102,14 @@ export function useEditorLinkPreview(editor: Editor) {
clearTimeout(closeTimer.current);
clearTimeout(clearTimer.current);
};
- }, [editor, close, leave, keepOpen]);
+ }, [editor, close, leave, keepOpen, disabled]);
- return { anchor, candidateAnchor, open, keepOpen, leave, close };
+ return {
+ anchor: disabled ? null : anchor,
+ candidateAnchor: disabled ? null : candidateAnchor,
+ open: !disabled && open,
+ keepOpen,
+ leave,
+ close,
+ };
}
diff --git a/apps/web/src/components/common/editor/useLinkInputCapabilities.ts b/apps/web/src/components/common/editor/useLinkInputCapabilities.ts
new file mode 100644
index 00000000..b22f2654
--- /dev/null
+++ b/apps/web/src/components/common/editor/useLinkInputCapabilities.ts
@@ -0,0 +1,32 @@
+import { useSyncExternalStore } from 'react';
+
+const compactQuery = '(pointer: coarse), (hover: none)';
+const explicitQuery = '(pointer: coarse), (hover: none), (any-pointer: coarse)';
+let penAvailable = false;
+
+function subscribe(notify: () => void) {
+ if (typeof window.matchMedia !== 'function') return () => {};
+ const queries = [window.matchMedia(compactQuery), window.matchMedia(explicitQuery)];
+ const pointer = (event: PointerEvent) => {
+ if (event.pointerType !== 'pen') return;
+ penAvailable = true;
+ notify();
+ };
+ for (const query of queries) query.addEventListener('change', notify);
+ window.addEventListener('pointerdown', pointer, true);
+ return () => {
+ for (const query of queries) query.removeEventListener('change', notify);
+ window.removeEventListener('pointerdown', pointer, true);
+ };
+}
+
+function snapshot() {
+ if (typeof window.matchMedia !== 'function') return 'none';
+ if (window.matchMedia(compactQuery).matches) return 'compact';
+ return penAvailable || window.matchMedia(explicitQuery).matches ? 'explicit' : 'none';
+}
+
+export function useLinkInputCapabilities() {
+ const value = useSyncExternalStore(subscribe, snapshot, () => 'none');
+ return { compact: value === 'compact', explicit: value !== 'none' };
+}
diff --git a/apps/web/src/components/common/editor/useLinkPreviewDialog.ts b/apps/web/src/components/common/editor/useLinkPreviewDialog.ts
new file mode 100644
index 00000000..ac0670fc
--- /dev/null
+++ b/apps/web/src/components/common/editor/useLinkPreviewDialog.ts
@@ -0,0 +1,62 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export function useLinkPreviewDialog({
+ linkCount,
+ onClose,
+ trigger,
+ container,
+}: {
+ linkCount: number;
+ onClose: () => void;
+ trigger: HTMLElement | null;
+ container: HTMLElement | null;
+}) {
+ const [open, setOpen] = useState(true);
+ const [selected, setSelected] = useState<number | null>(linkCount === 1 ? 0 : null);
+ const body = useRef<HTMLDivElement>(null);
+ const lastSelected = useRef(0);
+ const editAfterClose = useRef<(() => void) | undefined>(undefined);
+ const focusAction = useCallback(() => {
+ body.current
+ ?.querySelector<HTMLElement>('[data-link-preview-primary]')
+ ?.focus({ preventScroll: true });
+ }, []);
+
+ useEffect(() => {
+ if (open) focusAction();
+ }, [open, selected, focusAction]);
+
+ function closeAutoFocus(event: Event) {
+ event.preventDefault();
+ const target = trigger?.isConnected ? trigger : container;
+ if (target?.isConnected) {
+ const tabIndex = target.getAttribute('tabindex');
+ if (tabIndex === null) target.setAttribute('tabindex', '-1');
+ target.focus({ preventScroll: true });
+ if (tabIndex === null) target.removeAttribute('tabindex');
+ }
+ onClose();
+ editAfterClose.current?.();
+ }
+
+ return {
+ open,
+ setOpen,
+ selected,
+ body,
+ focusIndex: lastSelected.current,
+ focusAction,
+ closeAutoFocus,
+ select(index: number) {
+ lastSelected.current = index;
+ setSelected(index);
+ },
+ backToLinks() {
+ setSelected(null);
+ },
+ editLink(onEdit: () => void) {
+ editAfterClose.current = onEdit;
+ setOpen(false);
+ },
+ };
+}
diff --git a/apps/web/src/components/common/editor/useLinkPreviewQuery.ts b/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
index fde2cc53..c58e3eb5 100644
--- a/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
+++ b/apps/web/src/components/common/editor/useLinkPreviewQuery.ts
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { useSession } from '@/lib/auth-client';
import { resolveLinkPreview } from './resolveLinkPreview';
+import { linkPreviewDestination } from './linkPreviewDestination';
async function preloadImage(src: string, signal: AbortSignal) {
await new Promise<void>((resolve) => {
@@ -24,29 +25,44 @@ async function preloadImage(src: string, signal: AbortSignal) {
export function useLinkPreviewQuery(url: string | undefined) {
const { data: session, isPending: sessionPending } = useSession();
- const internal =
- !!url && typeof window !== 'undefined' && new URL(url).origin === window.location.origin;
- const enabled = !!url && !!session?.user.id;
+ const origin = typeof window === 'undefined' ? undefined : window.location.origin;
+ const destination = url ? linkPreviewDestination(url, origin) : null;
+ const href = destination?.href;
+ const internal = !!destination && destination.origin === origin;
+ const enabled = !!href && !!session?.user.id && !sessionPending;
+ const queryKey = ['link-preview', session?.user.id, href];
+ if (internal) queryKey.push(session?.session?.id);
const query = useQuery({
- queryKey: ['link-preview', session?.user.id, url],
+ queryKey,
enabled,
queryFn: async ({ signal }) => {
- const preview = await resolveLinkPreview(url!, window.location.origin, signal);
+ const preview = await resolveLinkPreview(href!, window.location.origin, signal);
if (preview.image && !signal.aborted) {
await preloadImage(preview.image, signal);
}
signal.throwIfAborted();
return preview;
},
- staleTime: internal ? 0 : 5 * 60_000,
+ staleTime: (query) => {
+ if (internal) return 0;
+ const preview = query.state.data;
+ return preview?.title || preview?.description || preview?.image || preview?.siteName
+ ? 5 * 60_000
+ : 15_000;
+ },
gcTime: internal ? 0 : 2 * 60_000,
retry: false,
- refetchOnMount: false,
+ refetchOnMount: internal ? 'always' : true,
refetchOnWindowFocus: false,
});
return {
...query,
- data: query.isError ? undefined : query.data,
- isPending: sessionPending || (enabled && query.isPending),
+ data:
+ !enabled || query.isError || (internal && query.fetchStatus !== 'idle')
+ ? undefined
+ : query.data,
+ isPending:
+ sessionPending ||
+ (enabled && (query.isPending || (internal && query.fetchStatus !== 'idle'))),
};
}
diff --git a/apps/web/src/components/common/editor/useVisibleLinkPreview.ts b/apps/web/src/components/common/editor/useVisibleLinkPreview.ts
new file mode 100644
index 00000000..b2931b87
--- /dev/null
+++ b/apps/web/src/components/common/editor/useVisibleLinkPreview.ts
@@ -0,0 +1,35 @@
+import { useEffect, useRef, useState } from 'react';
+import { useLinkPreviewQuery } from './useLinkPreviewQuery';
+
+export function useVisibleLinkPreview(url: string | undefined) {
+ const ref = useRef<HTMLSpanElement>(null);
+ const [visibleUrl, setVisibleUrl] = useState<string>();
+
+ useEffect(() => {
+ const element = ref.current;
+ if (!url || !element || typeof IntersectionObserver === 'undefined') return;
+ let active = true;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (!active) return;
+ const entry = entries.at(-1);
+ const visible =
+ entry?.isIntersecting &&
+ entry.intersectionRect.width > 0 &&
+ entry.intersectionRect.height > 0 &&
+ getComputedStyle(element).visibility !== 'hidden';
+ setVisibleUrl(visible ? url : undefined);
+ },
+ { rootMargin: '0px', threshold: [0, 0.01] },
+ );
+ observer.observe(element);
+ return () => {
+ active = false;
+ observer.disconnect();
+ setVisibleUrl(undefined);
+ };
+ }, [url]);
+
+ const { data: preview } = useLinkPreviewQuery(url === visibleUrl ? url : undefined);
+ return { ref, preview };
+}
diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
index 28949600..6e4d0394 100644
--- a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
@@ -263,7 +263,7 @@ export default function DocumentMarkdownEditor({
)}
{editable && <EditorTableMenu editor={editor} />}
<EditorContent editor={editor} className="flex min-h-full flex-col" />
- <EditorLinkPreview editor={editor} />
+ <EditorLinkPreview editor={editor} source={defaultJson ? '' : defaultValue} />
</div>
);
}
diff --git a/apps/web/src/features/issue/components/create/NewIssueBody.tsx b/apps/web/src/features/issue/components/create/NewIssueBody.tsx
index 135a2bb5..033850e4 100644
--- a/apps/web/src/features/issue/components/create/NewIssueBody.tsx
+++ b/apps/web/src/features/issue/components/create/NewIssueBody.tsx
@@ -57,6 +57,7 @@ export default function NewIssueBody({
const descriptionEditor = (
<MarkdownEditor
+ readingLinks={false}
className={cn(bodyDefs.length === 0 && 'mt-3', editorClass)}
placeholder={tEditor('descriptionPlaceholder')}
defaultValue={description}
@@ -106,6 +107,7 @@ export default function NewIssueBody({
{markdownDefs.map((def) => (
<div key={def.id} className={sectionClass(fieldSection(def.id))}>
<MarkdownEditor
+ readingLinks={false}
className={editorClass}
defaultValue={(fieldValues[def.id]?.value as string) ?? ''}
placeholder={tFields('empty')}
diff --git a/apps/web/src/features/notes/components/StickerEditor.tsx b/apps/web/src/features/notes/components/StickerEditor.tsx
index e2271c64..8b5be294 100644
--- a/apps/web/src/features/notes/components/StickerEditor.tsx
+++ b/apps/web/src/features/notes/components/StickerEditor.tsx
@@ -45,7 +45,7 @@ export default function StickerEditor({
return (
<>
<EditorContent editor={editor} />
- <EditorLinkPreview editor={editor} />
+ <EditorLinkPreview editor={editor} compact={false} />
</>
);
}