⚡ 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
fix(mobile): show older HTML task descriptions as formatted text
Tin Severd417df144115
diff --git a/apps/mobile/src/lib/legacy-html.test.ts b/apps/mobile/src/lib/legacy-html.test.tsnew file mode 100644index 000000000..43281752c--- /dev/null+++ b/apps/mobile/src/lib/legacy-html.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vite-plus/test";++import { isLegacyHtml, legacyHtmlToMarkdown } from "./legacy-html";++describe("legacy HTML descriptions", () => {+ it("only treats text that starts with a block tag as HTML", () => {+ expect(isLegacyHtml("<p>Hello</p>")).toBe(true);+ expect(isLegacyHtml(' <ul class="x"><li>a</li></ul>')).toBe(true);+ expect(isLegacyHtml("Hello <p> world")).toBe(false);+ expect(isLegacyHtml("```html\n<p>x</p>\n```")).toBe(false);+ expect(isLegacyHtml('<kaneo-mention id="1"></kaneo-mention>')).toBe(false);+ });++ it("converts paragraphs and inline marks", () => {+ expect(+ legacyHtmlToMarkdown(+ "<p>Hello <strong>bold</strong> and <em>soft</em> & <code>x < y</code></p><p>Next<br>line</p>",+ ),+ ).toBe("Hello **bold** and _soft_ & `x < y`\n\nNext \nline");+ });++ it("converts editor task lists with their checked state", () => {+ const html =+ '<ul class="not-prose pl-2" data-type="taskList"><li class="flex gap-2 items-start" data-checked="false" data-type="taskItem"><label><input type="checkbox"><span></span></label><div><p>Move the instances.json</p></div></li><li data-checked="true" data-type="taskItem"><label><input type="checkbox" checked="checked"><span></span></label><div><p>Use a $schema</p></div></li></ul>';+ expect(legacyHtmlToMarkdown(html)).toBe(+ "- [ ] Move the instances.json\n- [x] Use a $schema",+ );+ });++ it("keeps nested and ordered lists", () => {+ expect(+ legacyHtmlToMarkdown(+ '<ol start="3"><li><p>One</p><ul><li><p>Inner</p></li></ul></li><li><p>Two</p></li></ol><p>After</p>',+ ),+ ).toBe("3. One\n - Inner\n4. Two\n\nAfter");+ });++ it("converts headings, links, quotes, and code blocks", () => {+ expect(+ legacyHtmlToMarkdown(+ '<h2>Title</h2><p>See <a href="https://kaneo.app" target="_blank">site</a></p><blockquote><p>Quote</p><p>More</p></blockquote><pre><code class="language-ts">const a = 1 < 2;\n</code></pre>',+ ),+ ).toBe(+ "## Title\n\nSee [site](https://kaneo.app)\n\n> Quote\n>\n> More\n\n```\nconst a = 1 < 2;\n\n```",+ );+ });++ it("keeps images and Kaneo tags for the display rewrite", () => {+ expect(+ legacyHtmlToMarkdown(+ '<p>Hi <kaneo-mention id="u1" label="Ana">@Ana</kaneo-mention></p><img src="/api/asset/1" alt="shot">',+ ),+ ).toBe(+ 'Hi <kaneo-mention id="u1" label="Ana">@Ana</kaneo-mention>\n\n<img src="/api/asset/1" alt="shot">',+ );+ });+});diff --git a/apps/mobile/src/lib/legacy-html.ts b/apps/mobile/src/lib/legacy-html.tsnew file mode 100644index 000000000..7f515c1f0--- /dev/null+++ b/apps/mobile/src/lib/legacy-html.ts@@ -0,0 +1,148 @@+/**+ * Older task descriptions were saved as editor HTML. The web editor still reads it, but the+ * app's Markdown renderer shows tags as text, so such descriptions are converted for display.+ */+const legacyHtmlStart = /^\s*<(p|h[1-6]|ul|ol|blockquote|pre|div|table)\b/i;+const tagToken = /(<\/?[a-zA-Z][^>]*>)/;+const tagParts = /^<(\/?)([a-zA-Z][\w-]*)([^>]*)>$/;+const entities: Record<string, string> = {+ amp: "&",+ lt: "<",+ gt: ">",+ quot: '"',+ apos: "'",+ nbsp: " ",+};+const marks: Record<string, string> = {+ strong: "**",+ b: "**",+ em: "_",+ i: "_",+ s: "~~",+ del: "~~",+ strike: "~~",+};+const framed = new Set(["ul", "ol", "li", "blockquote", "a"]);++type Frame = { tag: string; attrs: string; out: string; items: number };++export function isLegacyHtml(text: string): boolean {+ return legacyHtmlStart.test(text);+}++function decode(text: string): string {+ return text.replace(+ /&(#x[\da-f]+|#\d+|[a-z]+);/gi,+ (match, entity: string) => {+ if (entity[0] !== "#") return entities[entity.toLowerCase()] ?? match;+ const hex = entity[1] === "x" || entity[1] === "X";+ const code = Number.parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10);+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;+ },+ );+}++function attr(raw: string, name: string): string | undefined {+ const match = new RegExp(+ `\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,+ "i",+ ).exec(raw);+ return match ? decode(match[1] ?? match[2]) : undefined;+}++function finish(frame: Frame, parent: Frame): string {+ const body = frame.out.trim();+ switch (frame.tag) {+ case "li": {+ parent.items += 1;+ const start = Number(attr(parent.attrs, "start") ?? "1");+ const marker =+ parent.tag === "ol"+ ? `${(Number.isFinite(start) ? start : 1) + parent.items - 1}. `+ : "- ";+ const checkbox =+ attr(frame.attrs, "data-type") === "taskItem"+ ? attr(frame.attrs, "data-checked") === "true"+ ? "[x] "+ : "[ ] "+ : "";+ const indent = " ".repeat(marker.length);+ const content = body+ .replace(/\n{2,}/g, "\n")+ .replace(/\n/g, `\n${indent}`);+ return `${marker}${checkbox}${content}\n`;+ }+ case "ul":+ case "ol":+ return parent.tag === "li" ? `\n${frame.out}` : `${frame.out}\n`;+ case "blockquote":+ return `${body+ .split("\n")+ .map((line) => (line ? `> ${line}` : ">"))+ .join("\n")}\n\n`;+ default: {+ const href = attr(frame.attrs, "href");+ return href ? `[${frame.out}](${href})` : frame.out;+ }+ }+}++/** Converts editor HTML to Markdown, keeping `img` and `kaneo-*` tags for the display rewrite. */+export function legacyHtmlToMarkdown(html: string): string {+ const stack: Frame[] = [{ tag: "", attrs: "", out: "", items: 0 }];+ const top = () => stack[stack.length - 1];+ const emit = (text: string) => {+ top().out += text;+ };+ let pre = 0;++ for (const token of html.split(tagToken)) {+ const tag = tagParts.exec(token);+ if (!tag) {+ if (pre) emit(decode(token));+ else if (token.trim()) emit(decode(token.replace(/\s+/g, " ")));+ else if (token && !/\s$/.test(top().out)) emit(" ");+ continue;+ }++ const [, closing, rawName, rawAttrs] = tag;+ const name = rawName.toLowerCase();+ if (name === "img" || name.startsWith("kaneo-")) {+ emit(token);+ } else if (framed.has(name)) {+ if (!closing) {+ stack.push({ tag: name, attrs: rawAttrs, out: "", items: 0 });+ } else if (stack.some((frame, i) => i > 0 && frame.tag === name)) {+ let frame: Frame;+ do {+ frame = stack.pop() as Frame;+ top().out += finish(frame, top());+ } while (frame.tag !== name);+ }+ } else if (marks[name]) {+ emit(marks[name]);+ } else if (name === "code") {+ if (!pre) emit("`");+ } else if (name === "pre") {+ pre = Math.max(0, pre + (closing ? -1 : 1));+ emit(closing ? "\n```\n\n" : "```\n");+ } else if (/^h[1-6]$/.test(name)) {+ emit(closing ? "\n\n" : `${"#".repeat(Number(name[1]))} `);+ } else if (name === "br") {+ emit(" \n");+ } else if (name === "hr") {+ emit("\n\n---\n\n");+ } else if (closing && (name === "p" || name === "div" || name === "tr")) {+ emit("\n\n");+ }+ }++ while (stack.length > 1) {+ const frame = stack.pop() as Frame;+ top().out += finish(frame, top());+ }+ return top()+ .out.replace(/[ \t]+\n\n/g, "\n\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}diff --git a/apps/mobile/src/lib/markdown.ts b/apps/mobile/src/lib/markdown.tsindex fb628fc6b..374313ddf 100644--- a/apps/mobile/src/lib/markdown.ts+++ b/apps/mobile/src/lib/markdown.ts@@ -1,6 +1,7 @@import { i18n } from "@/lib/i18n";import { resolveUrl } from "./api/client";+import { isLegacyHtml, legacyHtmlToMarkdown } from "./legacy-html";/*** The web editor serializes rich nodes into Markdown as custom HTML tags. Markdown renderers@@ -27,7 +28,10 @@ function attrs(raw: string): Record<string, string> {}export function toDisplayMarkdown(markdown: string, serverUrl: string): string {- let text = markdown.replace(+ const source = isLegacyHtml(markdown)+ ? legacyHtmlToMarkdown(markdown)+ : markdown;+ let text = source.replace(mentionRegex,(_, rawAttrs: string, inner: string) => {const label = attrs(rawAttrs).label || inner.replace(/^@/, "");