File size: 4,062 Bytes
0671a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90aef7e
 
 
0671a8c
90aef7e
 
 
 
 
 
0671a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90aef7e
0671a8c
 
 
 
90aef7e
0671a8c
 
 
 
 
 
90aef7e
0671a8c
 
 
 
 
 
 
 
 
 
90aef7e
 
 
 
 
 
 
0671a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* «يقبل الرسالة متنسقة» (2026-11-15): a design copied out of Word, or out of
   ChatGPT or Claude, carries its structure in the clipboard's HTML - headings,
   lists inside lists, Word's numbered paragraphs - and a plain text box keeps
   only the words, so three levels arrive as one column of lines. This turns
   that HTML into Markdown, which keeps every level as `#` or as indentation,
   and is what the box receives instead.

   String-based on purpose: no DOM is needed, so it is tested as it is. */

const ENTITIES: Record<string, string> = {
  "&nbsp;": " ", "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&#39;": "'",
  "&rlm;": "", "&lrm;": "",
};

function decode(text: string): string {
  return text
    .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
    .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
    .replace(/&[a-z]+;/gi, (e) => ENTITIES[e.toLowerCase()] ?? e);
}

/** Whether the HTML carries structure worth keeping - else the plain paste is
    left alone. */
export function hasStructure(html: string): boolean {
  return /<(h[1-6]|li)\b/i.test(html) || /mso-list\s*:\s*l\d+\s+level\d/i.test(html);
}

/** The clipboard's HTML as Markdown: headings as `#`, list items indented two
    spaces a level with `-`, Word's list paragraphs by their `level`. */
export function htmlToMarkdown(html: string): string {
  const body = html
    .replace(/<!--[\s\S]*?-->/g, "")                       // Word's [if !supportLists]
    .replace(/<(style|script|head|title)\b[\s\S]*?<\/\1>/gi, "");
  const tokens = body.match(/<[^>]+>|[^<]+/g) ?? [];
  const lines: string[] = [];
  let line = "";
  let prefix = "";
  const lists: ("ul" | "ol")[] = [];
  let ignore = 0;          // inside Word's «mso-list:Ignore» span: the drawn bullet

  // A line is written when it has words. An element that opens with none -
  // the <p> ChatGPT and Claude put inside every <li> - keeps the marker the
  // list item set, or the bullets vanished (TAZA brief, 2026-11-16).
  const flush = () => {
    const text = decode(line).replace(/\s+/g, " ").replace(/\*\*\s*\*\*/g, "")
      .replace(/\*\*\s+/g, "**").replace(/\s+\*\*(?=\s|$)/g, "**").trim();
    if (text && text !== "**") {
      lines.push(prefix + text);
      prefix = "";
    }
    line = "";
  };

  for (const token of tokens) {
    if (!token.startsWith("<")) {
      if (!ignore) line += token;
      continue;
    }
    const closing = token.startsWith("</");
    const tag = (token.match(/^<\/?\s*([a-z0-9]+)/i)?.[1] ?? "").toLowerCase();
    if (tag === "span") {
      if (!closing && /mso-list\s*:\s*ignore/i.test(token)) ignore += 1;
      else if (closing && ignore) ignore -= 1;
      continue;
    }
    if (/^h[1-6]$/.test(tag)) {
      flush();
      prefix = closing ? "" : "#".repeat(Number(tag[1])) + " ";
      continue;
    }
    if (tag === "ul" || tag === "ol") {
      flush();
      prefix = "";
      if (closing) lists.pop();
      else lists.push(tag);
      continue;
    }
    if (tag === "li") {
      flush();
      prefix = "";
      if (!closing) {
        const depth = Math.max(lists.length - 1, 0);
        prefix = "  ".repeat(depth) + (lists[lists.length - 1] === "ol" ? "1. " : "- ");
      }
      continue;
    }
    if (tag === "p" || tag === "div") {
      flush();
      const level = !closing ? token.match(/mso-list\s*:\s*l\d+\s+level(\d+)/i) : null;
      if (level) prefix = "  ".repeat(Number(level[1]) - 1) + "- ";
      else if (closing) prefix = "";
      continue;
    }
    // a bold run stays bold: a section title written as a bold paragraph
    // («**1. فكرة المشروع**») still reads as a title to whoever reads it next
    if (tag === "strong" || tag === "b") {
      line += "**";
      continue;
    }
    if (tag === "br" || tag === "tr") {
      flush();
      continue;
    }
    if (tag === "td" || tag === "th") {
      if (closing) line += " | ";
      continue;
    }
  }
  flush();
  return lines.join("\n").replace(/ \| *$/gm, "");
}