⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(web): improve Mermaid diagram rendering and error handling
Slaind19da38dab13
diff --git a/apps/web/package.json b/apps/web/package.jsonindex f1663271a..a5c19991f 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -70,6 +70,7 @@"clsx": "^2.1.1","cmdk": "^1.1.1","date-fns": "^4.4.0",+ "dompurify": "^3.4.12","file-saver": "^2.0.5","framer-motion": "^12.42.2","highlight.js": "^11.11.1",diff --git a/apps/web/src/components/task/extensions/mermaid-block.ts b/apps/web/src/components/task/extensions/mermaid-block.tsindex c4963fff7..42b8a6d33 100644--- a/apps/web/src/components/task/extensions/mermaid-block.ts+++ b/apps/web/src/components/task/extensions/mermaid-block.ts@@ -3,7 +3,10 @@ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";import type { EditorState, Transaction } from "@tiptap/pm/state";import { Plugin, PluginKey } from "@tiptap/pm/state";import { Decoration, DecorationSet } from "@tiptap/pm/view";+import DOMPurify from "dompurify";import debounce from "@/lib/debounce";+import { i18n } from "@/lib/i18n";+import { toast } from "@/lib/toast";import { isDarkTheme, SHIKI_CODEBLOCK_REFRESH_META } from "./shiki-code-block";const MERMAID_LANGUAGE = "mermaid";@@ -17,9 +20,16 @@ type RenderState =| { status: "error"; message: string };type Scheduler = {- want: (cacheKey: string, code: string, dark: boolean) => void;+ want: (+ cacheKey: string,+ code: string,+ dark: boolean,+ explicit: boolean,+ ) => void;reset: () => void;flush: () => void;+ cancel: () => void;+ destroy: () => void;};const MERMAID_OPENERS =@@ -30,8 +40,12 @@ let mermaidIdCounter = 0;let initializedTheme: "dark" | "default" | null = null;function isMermaid(code: string) {- const firstLine = code.split("\n", 1)[0].trim();- return MERMAID_OPENERS.test(firstLine);+ const opener = code+ .split("\n")+ .map((line) => line.trim())+ .find((line) => line.length > 0 && !line.startsWith("%%"));++ return opener !== undefined && MERMAID_OPENERS.test(opener);}function cacheRender(cacheKey: string, state: RenderState) {@@ -52,6 +66,8 @@ async function renderMermaid(code: string, dark: boolean) {securityLevel: "strict",theme,fontFamily: "inherit",+ htmlLabels: false,+ flowchart: { htmlLabels: false },});initializedTheme = theme;}@@ -61,18 +77,27 @@ async function renderMermaid(code: string, dark: boolean) {`kaneo-mermaid-${mermaidIdCounter}`,code,);- return svg;++ return DOMPurify.sanitize(svg, {+ USE_PROFILES: { svg: true, svgFilters: true },+ });}function createScheduler(onSettled: () => void): Scheduler {- const wanted = new Map<string, { code: string; dark: boolean }>();+ const wanted = new Map<+ string,+ { code: string; dark: boolean; explicit: boolean }+ >();+ let active = true;const flush = debounce(async () => {+ if (!active) return;+const batch = [...wanted].filter(([key]) => !renderCache.has(key));if (batch.length === 0) return;await Promise.all(- batch.map(async ([key, { code, dark }]) => {+ batch.map(async ([key, { code, dark, explicit }]) => {renderCache.set(key, null);try {cacheRender(key, {@@ -80,23 +105,34 @@ function createScheduler(onSettled: () => void): Scheduler {svg: await renderMermaid(code, dark),});} catch (error) {- cacheRender(key, {- status: "error",- message: error instanceof Error ? error.message : String(error),- });+ const message =+ error instanceof Error ? error.message : String(error);+ cacheRender(key, { status: "error", message });+ if (explicit && active) {+ toast.error(i18n.t("tasks:detail.editor.mermaid.renderFailed"), {+ description: message,+ });+ }}}),);- onSettled();+ if (active) onSettled();}, RENDER_DEBOUNCE_MS);return {- want: (cacheKey, code, dark) => wanted.set(cacheKey, { code, dark }),+ want: (cacheKey, code, dark, explicit) =>+ wanted.set(cacheKey, { code, dark, explicit }),reset: () => wanted.clear(),flush: () => {if (wanted.size > 0) flush();},+ cancel: () => flush.cancel(),+ destroy: () => {+ active = false;+ flush.cancel();+ wanted.clear();+ },};}@@ -105,17 +141,11 @@ function createPreviewElement(state: RenderState | null) {container.className = "kaneo-mermaid-preview";container.contentEditable = "false";- if (!state) {+ if (!state || state.status === "error") {container.dataset.state = "loading";return container;}- if (state.status === "error") {- container.dataset.state = "error";- container.textContent = state.message;- return container;- }-container.dataset.state = "done";container.innerHTML = state.svg;return container;@@ -142,8 +172,10 @@ function getDecorations(doc: ProseMirrorNode, scheduler: Scheduler) {const cacheKey = `${dark ? "dark" : "light"}:${code}`;const state = renderCache.get(cacheKey) ?? null;- if (state?.status === "error" && !explicit) return;- if (!renderCache.has(cacheKey)) scheduler.want(cacheKey, code, dark);+ if (state?.status === "error") return;+ if (!renderCache.has(cacheKey)) {+ scheduler.want(cacheKey, code, dark, explicit);+ }decorations.push(Decoration.widget(@@ -172,6 +204,8 @@ export const MermaidBlock = Extension.create({view.dispatch(view.state.tr.setMeta(MERMAID_REFRESH_META, true));});+ editor.once("destroy", () => scheduler.destroy());+return [new Plugin({key: mermaidPluginKey,@@ -190,6 +224,7 @@ export const MermaidBlock = Extension.create({return decorationSet.map(transaction.mapping, transaction.doc);},},+ view: () => ({ destroy: () => scheduler.cancel() }),props: {decorations(state: EditorState) {return mermaidPluginKey.getState(state);diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 8b3feadb8..e8b333733 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -697,14 +697,6 @@ input:-webkit-autofill:active {display: none;}- .kaneo-mermaid-preview[data-state="error"] {- font-family: var(--font-mono);- font-size: 0.8rem;- text-align: left;- white-space: pre-wrap;- color: var(--destructive);- }-.kaneo-tiptap-content .ProseMirror blockquote {margin: 0.5rem 0;border-left: 2px solid var(--border);diff --git a/apps/web/src/lib/debounce.ts b/apps/web/src/lib/debounce.tsindex 0096705a8..8f60eff12 100644--- a/apps/web/src/lib/debounce.ts+++ b/apps/web/src/lib/debounce.ts@@ -3,10 +3,14 @@ function debounce<Args extends unknown[], R>(delay: number,) {let timeout: ReturnType<typeof setTimeout>;- return (...args: Args) => {+ const debounced = (...args: Args) => {clearTimeout(timeout);timeout = setTimeout(() => func(...args), delay);};++ debounced.cancel = () => clearTimeout(timeout);++ return debounced;}export default debounce;diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 330489e32..0f7b63b4f 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -1440,6 +1440,9 @@"onlyYoutube": "Nur YouTube-Links können eingebettet werden."},"onlyYoutubeInline": "Nur YouTube-URLs können eingebettet werden. Verwende stattdessen den Link-Modus."+ },+ "mermaid": {+ "renderFailed": "Mermaid-Diagramm konnte nicht gerendert werden"}}},diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex 6bb1297c6..d9d05cf94 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -1398,6 +1398,9 @@"onlyYoutube": "Μόνο σύνδεσμοι YouTube μπορούν να ενσωματωθούν."},"onlyYoutubeInline": "Μόνο URLs YouTube μπορούν να ενσωματωθούν. Χρησιμοποιήστε λειτουργία συνδέσμου."+ },+ "mermaid": {+ "renderFailed": "Δεν ήταν δυνατή η απόδοση του διαγράμματος Mermaid"}}},diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 981cfec25..0723a3cae 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -1604,6 +1604,9 @@"onlyYoutube": "Only YouTube links can be embedded."},"onlyYoutubeInline": "Only YouTube URLs can be embedded. Use link mode instead."+ },+ "mermaid": {+ "renderFailed": "Mermaid diagram couldn't be rendered"}}},diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex aee67749c..5314f84dd 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -1183,6 +1183,9 @@"onlyYoutube": "Sólo los enlaces de YouTube pueden ser incrustados."},"onlyYoutubeInline": "Sólo los enlaces de YouTube pueden ser incrustados. Añádelo como enlace."+ },+ "mermaid": {+ "renderFailed": "No se pudo renderizar el diagrama de Mermaid"}}},diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex e2e1efe8a..75bb0a3cb 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -1406,6 +1406,9 @@"onlyYoutube": "Seuls les liens YouTube peuvent être intégrés."},"onlyYoutubeInline": "Seuls les liens YouTube peuvent être intégrés. Utilisez le mode lien à la place."+ },+ "mermaid": {+ "renderFailed": "Impossible d'afficher le diagramme Mermaid"}}},diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 9cc92bcf4..4204182a7 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -1543,6 +1543,9 @@"onlyYoutube": "Hanya tautan YouTube yang dapat disematkan."},"onlyYoutubeInline": "Hanya URL YouTube yang dapat disematkan. Gunakan mode tautan."+ },+ "mermaid": {+ "renderFailed": "Diagram Mermaid tidak dapat dirender"}}},diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex 50c6f8b58..d495e7168 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -1400,6 +1400,9 @@"onlyYoutube": "YouTube 링크만 임베드할 수 있습니다."},"onlyYoutubeInline": "YouTube URL만 임베드할 수 있습니다. 대신 링크 모드를 사용하세요."+ },+ "mermaid": {+ "renderFailed": "Mermaid 다이어그램을 렌더링할 수 없습니다"}}},diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 4dfb164ae..74bc4b5e0 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -1398,6 +1398,9 @@"onlyYoutube": "Само YouTube линкови може да се вградат."},"onlyYoutubeInline": "Само YouTube URL може да се вградат. Користи режим на линк наместо тоа."+ },+ "mermaid": {+ "renderFailed": "Mermaid дијаграмот не можеше да се прикаже"}}},diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 87228c857..e0c69c16e 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -1184,6 +1184,9 @@"onlyYoutube": "Alleen YouTube-links kunnen worden ingesloten."},"onlyYoutubeInline": "Alleen YouTube URL's kunnen worden ingesloten. Gebruik link-modus."+ },+ "mermaid": {+ "renderFailed": "Mermaid-diagram kon niet worden weergegeven"}}},diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex c581ddd15..6f397ca55 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -1401,6 +1401,9 @@"onlyYoutube": "Можно встраивать только ссылки YouTube."},"onlyYoutubeInline": "Можно встраивать только URL YouTube. Используйте режим ссылки."+ },+ "mermaid": {+ "renderFailed": "Не удалось отобразить диаграмму Mermaid"}}},diff --git a/i18n/schema.json b/i18n/schema.jsonindex f82f0efe3..31be942ab 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -6072,6 +6072,16 @@"yaml"]},+ "mermaid": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "renderFailed": {+ "type": "string"+ }+ },+ "required": ["renderFailed"]+ },"embed": {"type": "object","additionalProperties": false,@@ -6144,7 +6154,8 @@"upload","slash","languages",- "embed"+ "embed",+ "mermaid"]}},diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex 62829ad77..cdb35de7d 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -1405,6 +1405,9 @@"onlyYoutube": "Yalnızca YouTube bağlantıları gömülebilir."},"onlyYoutubeInline": "Yalnızca YouTube URL'leri gömülebilir. Bağlantı modunu kullanın."+ },+ "mermaid": {+ "renderFailed": "Mermaid diyagramı oluşturulamadı"}}},diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 64b93caa2..061b94c6c 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -1395,6 +1395,9 @@"onlyYoutube": "Можна вбудовувати лише посилання YouTube."},"onlyYoutubeInline": "Можна вбудовувати лише URL-адреси YouTube. Натомість використовуйте режим посилання."+ },+ "mermaid": {+ "renderFailed": "Не вдалося відобразити діаграму Mermaid"}}},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 13ecfe3c6..ba81998cb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -419,6 +419,9 @@ importers:date-fns:specifier: ^4.4.0version: 4.4.0+ dompurify:+ specifier: ^3.4.12+ version: 3.4.12file-saver:specifier: ^2.0.5version: 2.0.5