summaryrefslogtreecommitdiffstats
path: root/_writing/lib/markdown.mjs
blob: 16f6ca0fa2a2194404a51044578a76027ea7961d (plain)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/* Markdown renderer shared by the build script and the live editor preview.
   Deliberately dependency-free: the site ships as hand-written static files and
   an npm tree in the repo would get rsynced to production along with it. */

const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ESCAPES[c]);

const isExternal = (href) => /^https?:\/\//i.test(href) && !/(^|\/\/|\.)ericzou\.dev/i.test(href);

/* ---------- inline ----------
   Sentinels are built from char codes rather than typed literally, so they
   survive escapeHtml, never collide with prose, and don't depend on the source
   file preserving raw control bytes. */

const SENT_CODE = String.fromCharCode(0xe000);
const SENT_LINK = String.fromCharCode(0xe001);
const SENT_END = String.fromCharCode(0xe002);

const RE_CODE_SLOT = new RegExp(SENT_CODE + "(\\d+)" + SENT_CODE, "g");
const RE_LINK_SLOT = new RegExp(SENT_LINK + "(\\d+)" + SENT_LINK + "([\\s\\S]*?)" + SENT_END, "g");

function renderInline(src) {
  const stash = [];
  const hold = (html) => SENT_CODE + (stash.push(html) - 1) + SENT_CODE;
  let s = String(src);

  // Code spans win over everything, so pull them out before any other pass.
  s = s.replace(/(`+)([\s\S]+?)\1/g, (_m, _t, code) => hold(`<code>${escapeHtml(code.trim())}</code>`));

  // Bare URLs become links, but only where a markdown link isn't already doing it.
  s = s.replace(
    /(^|[\s(])(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])/g,
    (_m, pre, url) => `${pre}[${url}](${url})`
  );

  s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_m, alt, url) =>
    hold(`<img src="${escapeHtml(url)}" alt="${escapeHtml(alt)}" loading="lazy" decoding="async">`)
  );

  // Links are split into open/close markers so the link text still gets emphasis.
  const links = [];
  s = s.replace(/\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_m, text, href, title) => {
    links.push({ href, title });
    return SENT_LINK + (links.length - 1) + SENT_LINK + text + SENT_END;
  });

  s = escapeHtml(s);

  s = s
    .replace(/\*\*\*([^*]+)\*\*\*/g, "<strong><em>$1</em></strong>")
    .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
    .replace(/__([^_]+)__/g, "<strong>$1</strong>")
    .replace(/(^|[^*\w])\*([^*\n]+)\*/g, "$1<em>$2</em>")
    .replace(/(^|[^_\w])_([^_\n]+)_(?!\w)/g, "$1<em>$2</em>")
    .replace(/~~([^~]+)~~/g, "<del>$1</del>");

  s = s.replace(RE_LINK_SLOT, (_m, i, text) => {
    const { href, title } = links[+i];
    const attrs = [
      `href="${escapeHtml(href)}"`,
      title ? `title="${escapeHtml(title)}"` : "",
      isExternal(href) ? 'rel="noopener"' : "",
    ]
      .filter(Boolean)
      .join(" ");
    return `<a ${attrs}>${text}</a>`;
  });

  return s.replace(RE_CODE_SLOT, (_m, i) => stash[+i]);
}

/* ---------- blocks ---------- */

const RE_FENCE = /^\s*(```+|~~~+)\s*([\w+#.-]*)\s*$/;
const RE_HR = /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/;
const RE_HEADING = /^(#{1,4})\s+(.+?)\s*#*$/;
const RE_BULLET = /^(\s*)([-*+])\s+(.*)$/;
const RE_ORDERED = /^(\s*)(\d+)[.)]\s+(.*)$/;
const RE_IMAGE_LINE = /^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)$/;
const RE_HTML_BLOCK = /^\s*<(figure|video|iframe|div|table|details|section|aside|pre|blockquote|p|img|hr|ul|ol)\b/i;
const RE_TABLE_SEP = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$/;

function listItemMatch(line) {
  const b = line.match(RE_BULLET);
  if (b) return { indent: b[1].length, ordered: false, text: b[3] };
  const o = line.match(RE_ORDERED);
  if (o) return { indent: o[1].length, ordered: true, text: o[3], start: Number(o[2]) };
  return null;
}

function parseList(lines, start) {
  const first = listItemMatch(lines[start]);
  const baseIndent = first.indent;
  const ordered = first.ordered;
  const items = [];
  let i = start;

  while (i < lines.length) {
    const line = lines[i];

    if (!line.trim()) {
      // A blank line only ends the list if what follows isn't still part of it.
      const next = lines[i + 1];
      const m = next != null ? listItemMatch(next) : null;
      const continues = (m && m.indent >= baseIndent) || (next && /^\s{2,}\S/.test(next));
      if (!continues) break;
      i++;
      continue;
    }

    const m = listItemMatch(line);
    if (m && m.indent <= baseIndent) {
      items.push([m.text]);
      i++;
      continue;
    }
    if (!items.length) break;
    if (m || /^\s{2,}\S/.test(line)) {
      items[items.length - 1].push(line.slice(baseIndent + 2));
      i++;
      continue;
    }
    break;
  }

  const html = items
    .map((chunk) => {
      const [head, ...rest] = chunk;
      const nested = rest.join("\n").trim();
      return `<li>${renderInline(head)}${nested ? renderBlocks(nested.split("\n")) : ""}</li>`;
    })
    .join("\n");

  const tag = ordered ? "ol" : "ul";
  const startAttr = ordered && first.start !== 1 ? ` start="${first.start}"` : "";
  return { html: `<${tag}${startAttr}>\n${html}\n</${tag}>`, next: i };
}

function parseTable(lines, start) {
  const cells = (row) => row.replace(/^\s*\|/, "").replace(/\|\s*$/, "").split("|").map((c) => c.trim());
  const aligns = cells(lines[start + 1]).map((c) =>
    c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : "left"
  );
  const head = cells(lines[start])
    .map((c, n) => `<th style="text-align:${aligns[n] || "left"}">${renderInline(c)}</th>`)
    .join("");

  const body = [];
  let i = start + 2;
  while (i < lines.length && lines[i].trim() && lines[i].includes("|")) {
    const row = cells(lines[i])
      .map((c, n) => `<td style="text-align:${aligns[n] || "left"}">${renderInline(c)}</td>`)
      .join("");
    body.push(`<tr>${row}</tr>`);
    i++;
  }

  return {
    html:
      `<div class="tablewrap"><table><thead><tr>${head}</tr></thead>` +
      `<tbody>${body.join("")}</tbody></table></div>`,
    next: i,
  };
}

function renderBlocks(lines) {
  const out = [];
  let i = 0;

  while (i < lines.length) {
    const line = lines[i];
    if (!line.trim()) {
      i++;
      continue;
    }

    const fence = line.match(RE_FENCE);
    if (fence) {
      const marker = fence[1];
      const lang = fence[2];
      const body = [];
      i++;
      while (i < lines.length && !lines[i].trim().startsWith(marker)) body.push(lines[i++]);
      i++;
      const label = lang ? `<span class="code__lang">${escapeHtml(lang)}</span>` : "";
      out.push(`<div class="code">${label}<pre><code>${escapeHtml(body.join("\n"))}</code></pre></div>`);
      continue;
    }

    if (RE_HR.test(line)) {
      out.push("<hr>");
      i++;
      continue;
    }

    const heading = line.match(RE_HEADING);
    if (heading) {
      const level = heading[1].length;
      out.push(`<h${level}>${renderInline(heading[2])}</h${level}>`);
      i++;
      continue;
    }

    if (/^\s*>/.test(line)) {
      const body = [];
      while (i < lines.length && /^\s*>/.test(lines[i])) body.push(lines[i++].replace(/^\s*>\s?/, ""));
      out.push(`<blockquote>${renderBlocks(body)}</blockquote>`);
      continue;
    }

    if (lines[i + 1] && line.includes("|") && RE_TABLE_SEP.test(lines[i + 1])) {
      const table = parseTable(lines, i);
      out.push(table.html);
      i = table.next;
      continue;
    }

    if (listItemMatch(line)) {
      const list = parseList(lines, i);
      out.push(list.html);
      i = list.next;
      continue;
    }

    // A line that is nothing but an image becomes a real figure, and the
    // optional markdown title turns into the caption.
    const img = line.trim().match(RE_IMAGE_LINE);
    if (img) {
      const [, alt, src, caption] = img;
      const media = /\.(mp4|webm|mov)$/i.test(src)
        ? `<video src="${escapeHtml(src)}" controls playsinline preload="metadata"></video>`
        : `<img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}" loading="lazy" decoding="async">`;
      out.push(`<figure>${media}${caption ? `<figcaption>${escapeHtml(caption)}</figcaption>` : ""}</figure>`);
      i++;
      continue;
    }

    if (RE_HTML_BLOCK.test(line)) {
      const body = [];
      while (i < lines.length && lines[i].trim()) body.push(lines[i++]);
      out.push(body.join("\n"));
      continue;
    }

    const para = [];
    while (
      i < lines.length &&
      lines[i].trim() &&
      !RE_FENCE.test(lines[i]) &&
      !RE_HR.test(lines[i]) &&
      !RE_HEADING.test(lines[i]) &&
      !/^\s*>/.test(lines[i]) &&
      !listItemMatch(lines[i]) &&
      !RE_HTML_BLOCK.test(lines[i]) &&
      !RE_IMAGE_LINE.test(lines[i].trim())
    ) {
      para.push(lines[i++]);
    }
    if (para.length) out.push(`<p>${renderInline(para.join("\n").replace(/\s+$/, ""))}</p>`);
    else i++;
  }

  return out.join("\n");
}

export function renderMarkdown(src) {
  return renderBlocks(String(src).replace(/\r\n?/g, "\n").split("\n"));
}

/* ---------- derived metadata ---------- */

export function plainText(src) {
  return String(src)
    .replace(/```[\s\S]*?```/g, " ")
    .replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
    .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
    .replace(/[#>*_`~|-]/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

export function readingTime(src) {
  const words = plainText(src).split(" ").filter(Boolean).length;
  return Math.max(1, Math.round(words / 200));
}

export function excerpt(src, limit = 160) {
  const text = plainText(src);
  if (text.length <= limit) return text;
  const cut = text.lastIndexOf(" ", limit);
  return text.slice(0, cut > 0 ? cut : limit).replace(/[.,;:]$/, "") + "…";
}

export { escapeHtml };