All files / packages/design-system-2-site/src/lib/zeroheight convert.js

91.06% Statements 163/179
82.56% Branches 90/109
94.33% Functions 50/53
93.1% Lines 135/145

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471                                    2x     2x   2x 2x 2x   2x 2x 2x     2x   2x     2x   2x                                   50x 50x 50x 50x 50x 50x                     200x 200x 200x   789x 789x           80x       76x                       38x               17x 54x 36x 17x                 13x 13x       13x 7x 13x 2x                                         5x             5x                       50x 50x 208x 11x 11x 1x 1x   11x 1x 1x 1x   10x   50x                         50x 50x 50x 50x 216x 216x 216x 216x 216x   25x   20x     25x 25x 191x 25x   166x 166x     50x 50x                   137x                   8x 8x       52x     2x 64x               135x                 13x   3x   5x 5x 5x     1x   4x                           3x                 3x 3x 8x 8x 8x 8x     8x             3x 3x                         1x 4x 2x 2x 10x 2x     2x 2x                 2x                           4x 4x 4x       4x 4x 1x   4x       16x     4x 4x                                 50x                   24x 24x 24x                     50x 50x 187x 187x 187x 187x 187x                         50x 187x 15x           15x 15x                         50x 50x 187x 2x   187x   50x    
/**
 * Convert one tab of Zeroheight MCP markdown to site markdown. One function
 * per construct, run in a fixed order by `convertContent`:
 *
 *   1. table cells: inline `<design>` -> plain image; Storybook links get a
 *      demo after the table
 *   2. block tags -> directives: `<shortcut_tiles>` -> card grid, `<callout>`,
 *      `<tabs>` -> inline tabs, `<design>` / `<notes>` / `<annotations>` ->
 *      image + caption (+ ordered list)
 *   3. standalone Storybook links -> `::component-demo`
 *   4. Zeroheight page links -> site routes (`resolveLink`)
 *   5. leftover HTML tags -> warnings
 *
 * Fenced code is never touched. Images stay as `zeroheight://` refs here;
 * `images.js` rehosts them afterwards.
 */
 
/** `<callout background="N">` -> `:::callout{type}`, matched by color on the live site. */
export const CALLOUT_TYPES = { 1: 'warning', 2: 'info', 3: 'success', 4: 'error' };
 
/** Storybook hosts whose links become `::component-demo` embeds. */
const STORYBOOK_HOST_RE = /^(sds-site-docs|slds2-metadata-stories)-[0-9a-f]+\.herokuapp\.com$/;
 
const BLOCK_TAGS = ['shortcut_tiles', 'shortcut_tile', 'callout', 'tabs', 'tab', 'design', 'notes', 'annotations'];
const OPEN_TAG_RE = new RegExp(`^<(${BLOCK_TAGS.join('|')})((?:\\s+[\\w-]+="[^"]*")*)\\s*>\\s*$`);
const CLOSE_TAG_RE = new RegExp(`^</(${BLOCK_TAGS.join('|')})>\\s*$`);
// The lookbehind keeps a failed name from being retried at every later character.
const ATTR_RE = /(?<![\w-])([\w-]+)="([^"]*)"/g;
const FENCE_RE = /^\s*(```|~~~)/;
const IMAGE_RE = /!\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)/;
 
/** Figma inspect data in a `<design>`: a bold heading and a table. Zeroheight doesn't show it. */
const INSPECT_TABLE_RE = /^\*\*(?:Style|Attributes)\*\*\n+(?:\|.*\|(?:\n|$))+/gm;
/** `<design>` lines Zeroheight doesn't show: an empty frame name and the annotations label. */
const DROPPED_DESIGN_LINES = new Set(['****', '**Annotations**']);
 
const ZH_LINK_RE =
  /https:\/\/(?:(?:www\.lightningdesignsystem|zeroheight)\.com\/2e1ef8501(?:\/v\/(?:\d+|latest))?|salesforce\.zeroheight\.com\/styleguide\/s\/\d+)\/p\/([0-9a-f]{6})[\w-]*(?:\/([bt])\/([0-9a-f]+))?/g;
/** Inline HTML the site renders as-is. */
const ALLOWED_TAGS = new Set(['br', 'sup', 'sub', 'kbd', 'mark', 'abbr']);
 
/**
 * @typedef {{ page: string, tab: string | null, heading: string | null, url: string }} ZhLink
 * @typedef {{
 *   pageTitle: string,
 *   resolveLink: (link: ZhLink) => string | null,
 *   warn: (msg: string) => void,
 * }} ConvertContext
 * @typedef {{ tag: string, attrs: Record<string, string>, children: (string | TagNode)[] }} TagNode
 */
 
/**
 * @param {string} md one tab's (or an untabbed page's) MCP markdown
 * @param {ConvertContext} ctx
 * @returns {string}
 */
export function convertContent(md, ctx) {
  let out = convertTables(md, ctx);
  out = convertBlocks(out, ctx);
  out = convertStorybookLinks(out, ctx);
  out = convertZhLinks(out, ctx);
  warnUnknownTags(out, ctx);
  return `${out.replace(/\n{3,}/g, '\n\n').trim()}\n`;
}
 
// --- helpers ---------------------------------------------------------------
 
/**
 * Apply `fn` to each line outside fenced code.
 * @param {string} md
 * @param {(line: string, index: number, lines: string[]) => string} fn
 */
function mapLines(md, fn) {
  let inCode = false;
  const lines = md.split('\n');
  return lines
    .map((line, i) => {
      if (FENCE_RE.test(line)) inCode = !inCode;
      return inCode || FENCE_RE.test(line) ? line : fn(line, i, lines);
    })
    .join('\n');
}
 
/** @param {string} s */
const unescapeMd = (s) => s.replace(/\\([\\`*_{}[\]()#+\-.!|])/g, '$1');
 
/** Markdown inline -> plain text (for directive attributes). @param {string} s */
export function plainText(s) {
  return unescapeMd(
    s
      .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
      // `[` is excluded so a run of unmatched brackets can't make this quadratic.
      .replace(/\[([^[\]]*)\]\([^)[]*\)/g, '$1')
      .replace(/(\*\*|__|\*|_|`)/g, '')
      .replace(/\s+/g, ' ')
      .trim(),
  );
}
 
/** @param {string} value */
const attr = (value) => `"${value.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}"`;
 
/**
 * `::name{a="1" b="2"}`, dropping empty values.
 * @param {string} name
 * @param {Record<string, string | undefined>} attrs
 */
function leaf(name, attrs) {
  const parts = Object.entries(attrs)
    .filter(([, v]) => v)
    .map(([k, v]) => `${k}=${attr(/** @type {string} */ (v))}`);
  return `::${name}{${parts.join(' ')}}`;
}
 
/**
 * Storybook `iframe.html` URL for a story link, or null if it isn't one.
 * @param {string} url
 */
export function storybookIframeUrl(url) {
  let parsed;
  try {
    parsed = new URL(url);
  } catch {
    return null;
  }
  if (!STORYBOOK_HOST_RE.test(parsed.hostname)) return null;
  const story = parsed.searchParams.get('path')?.match(/^\/story\/(.+)$/)?.[1];
  if (story) return `${parsed.origin}/iframe.html?id=${story}`;
  Eif (parsed.pathname.endsWith('/iframe.html') && parsed.searchParams.get('id')) return url;
  return null;
}
 
/** `components-tree-grid--base-expanded` -> `Base Expanded`. @param {string} url */
function storyName(url) {
  const id = new URL(url).searchParams.get('id') ?? '';
  return id
    .split('--')
    .pop()
    ?.split('-')
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}
 
/**
 * @param {string} iframeUrl
 * @param {string | null} label heading or link text
 * @param {ConvertContext} ctx
 */
function componentDemo(iframeUrl, label, ctx) {
  return leaf('component-demo', {
    storybook: iframeUrl,
    title: `${ctx.pageTitle} - ${label || storyName(iframeUrl)}`,
  });
}
 
/** Link text that names the story (not "Storybook" or the bare URL). @param {string} text */
const storyLabel = (text) => (!text || /^storybook$/i.test(text) || /^https?:\/\//.test(text) ? null : plainText(text));
 
// --- 1. tables -------------------------------------------------------------
 
/**
 * Inline `<design>` cells become plain images (the bold label repeats the alt
 * text). Storybook links in cells stay links; their demos follow the table.
 * @param {string} md
 * @param {ConvertContext} ctx
 */
export function convertTables(md, ctx) {
  /** @type {string[]} */
  let demos = [];
  const lines = mapLines(md, (line, i, all) => {
    if (!line.startsWith('|')) return line;
    const row = line.replace(/<design(?: [^>]*)?>\s*(!\[[^\]]*\]\([^)]*\))[\s\S]*?<\/design>/g, '$1');
    for (const m of row.matchAll(/\[([^[\]]*)\]\((https:\/\/[^)\s[]+)\)/g)) {
      const iframe = storybookIframeUrl(m[2]);
      Eif (iframe) demos.push(componentDemo(iframe, storyLabel(m[1]), ctx));
    }
    if (demos.length && !all[i + 1]?.startsWith('|')) {
      const tail = `${row}\n\n${demos.join('\n\n')}\n`;
      demos = [];
      return tail;
    }
    return row;
  });
  return lines;
}
 
// --- 2. block tags ---------------------------------------------------------
 
/**
 * Parse own-line block tags into a tree. Mismatched tags stay as text.
 * @param {string} md
 * @param {ConvertContext} ctx
 * @returns {TagNode}
 */
export function parseBlocks(md, ctx) {
  /** @type {TagNode} */
  const root = { tag: 'root', attrs: {}, children: [] };
  const stack = [root];
  let inCode = false;
  for (const line of md.split('\n')) {
    const top = stack[stack.length - 1];
    if (FENCE_RE.test(line)) inCode = !inCode;
    const open = !inCode && line.match(OPEN_TAG_RE);
    const close = !inCode && line.match(CLOSE_TAG_RE);
    if (open) {
      /** @type {TagNode} */
      const node = {
        tag: open[1],
        attrs: Object.fromEntries([...open[2].matchAll(ATTR_RE)].map((m) => [m[1], m[2]])),
        children: [],
      };
      top.children.push(node);
      stack.push(node);
    } else if (close && close[1] === top.tag) {
      stack.pop();
    } else {
      Iif (close) ctx.warn(`unmatched </${close[1]}>`);
      top.children.push(line);
    }
  }
  Iif (stack.length > 1) ctx.warn(`unclosed <${stack[stack.length - 1].tag}>`);
  return root;
}
 
/**
 * @typedef {{ lines: string[], height: number }} Rendered
 * `height` is the directive nesting depth, so outer fences get more colons.
 */
 
/** @param {Rendered[]} parts */
function join(parts) {
  return { lines: parts.flatMap((p) => p.lines), height: Math.max(0, ...parts.map((p) => p.height)) };
}
 
/**
 * @param {string} open e.g. `callout{type=info}`
 * @param {Rendered} inner
 * @param {number} [height] fence depth, when siblings share one
 * @returns {Rendered}
 */
function container(open, inner, height = inner.height) {
  const fence = ':'.repeat(3 + height);
  return { lines: ['', `${fence}${open}`, ...inner.lines, fence, ''], height: height + 1 };
}
 
/** @param {TagNode} node @returns {string[]} */
const textOf = (node) => node.children.filter((c) => typeof c === 'string');
 
/** @param {TagNode} node @param {string} tag @returns {TagNode[]} */
const childTags = (node, tag) =>
  /** @type {TagNode[]} */ (node.children.filter((c) => typeof c !== 'string' && c.tag === tag));
 
/**
 * @param {TagNode} node
 * @param {ConvertContext} ctx
 * @returns {Rendered}
 */
function renderChildren(node, ctx) {
  return join(node.children.map((c) => (typeof c === 'string' ? { lines: [c], height: 0 } : renderNode(c, ctx))));
}
 
/**
 * @param {TagNode} node
 * @param {ConvertContext} ctx
 * @returns {Rendered}
 */
function renderNode(node, ctx) {
  switch (node.tag) {
    case 'shortcut_tiles':
      return renderTiles(node, ctx);
    case 'callout': {
      const type = CALLOUT_TYPES[/** @type {1 | 2 | 3 | 4} */ (Number(node.attrs.background))];
      Iif (!type) ctx.warn(`callout background="${node.attrs.background}" -> info`);
      return container(`callout{type=${type ?? 'info'}}`, renderChildren(node, ctx));
    }
    case 'tabs':
      return renderTabs(node, ctx);
    case 'design':
      return renderDesign(node, ctx);
    case 'annotations':
      return { lines: renderAnnotations(node), height: 0 };
    default:
      // A stray <tab>, <shortcut_tile> or <notes>: keep its content.
      ctx.warn(`<${node.tag}> outside its parent`);
      return renderChildren(node, ctx);
  }
}
 
/**
 * Card columns: 3 for 3, 5, 6+ tiles; 2 otherwise (so 4 is a 2x2 grid).
 * @param {number} count
 */
const cardColumns = (count) => (count >= 3 && count !== 4 ? 3 : 2);
 
/**
 * `<shortcut_tile url>` holds an image, a bold title and a description.
 * @param {TagNode} node
 * @param {ConvertContext} ctx
 * @returns {Rendered}
 */
function renderTiles(node, ctx) {
  const tiles = childTags(node, 'shortcut_tile');
  const cards = tiles.map((tile) => {
    const text = textOf(tile).join('\n');
    const image = text.match(IMAGE_RE);
    const title = text.match(/^\*\*(.+)\*\*\s*$/m)?.[1];
    const description = text
      .replace(new RegExp(IMAGE_RE.source, 'g'), '')
      .replace(/^\*\*.+\*\*\s*$/m, '');
    return leaf('card', {
      title: plainText(title ?? image?.[1] ?? ''),
      description: plainText(description),
      href: tile.attrs.url,
      image: image?.[2],
    });
  });
  Iif (textOf(node).some((l) => l.trim())) ctx.warn('text between shortcut tiles dropped');
  return {
    lines: ['', `:::card-grid{columns="${cardColumns(tiles.length)}"}`, ...cards, ':::', ''],
    height: 1,
  };
}
 
/**
 * `<tab>` children start with `<tab-title>**Title**</tab-title>`.
 * @param {TagNode} node
 * @param {ConvertContext} ctx
 * @returns {Rendered}
 */
function renderTabs(node, ctx) {
  const panels = childTags(node, 'tab').map((tab) => {
    const titleLine = tab.children.findIndex((c) => typeof c === 'string' && c.includes('<tab-title>'));
    const title = titleLine === -1 ? '' : String(tab.children[titleLine]).match(/<tab-title>(.*?)<\/tab-title>/)?.[1];
    Iif (!title) ctx.warn('inline tab without a <tab-title>');
    const body = { ...tab, children: tab.children.filter((_, i) => i !== titleLine) };
    return { title: plainText(title ?? ''), inner: renderChildren(body, ctx) };
  });
  // Sibling tabs share one fence length.
  const height = Math.max(0, ...panels.map((p) => p.inner.height));
  return container('tabs', join(panels.map((p) => container(`tab{title=${attr(p.title)}}`, p.inner, height))));
}
 
/**
 * `<annotations>`: numbered `<annotation data-marker-*>label</annotation>`
 * items. Markers are dropped; the labels stay as an ordered list.
 * @param {TagNode} node
 */
function renderAnnotations(node) {
  return ['', ...textOf(node).map((l) => l.replace(/<annotation[^>]*>(.*?)<\/annotation>/g, '$1')), ''];
}
 
/**
 * `<design>`: a Figma frame image, its name in bold (always the alt text, so
 * dropped), optional `<notes>` (the caption) and `<annotations>`. Figma
 * inspect tables, an empty name (`****`) and the `**Annotations**` label
 * (Zeroheight shows none of them) are dropped; anything else is kept after
 * the image.
 * @param {TagNode} node
 * @param {ConvertContext} ctx
 * @returns {Rendered}
 */
function renderDesign(node, ctx) {
  const text = textOf(node).join('\n');
  const image = text.match(IMAGE_RE);
  Iif (!image) {
    ctx.warn('<design> without an image');
    return renderChildren(node, ctx);
  }
  const alt = unescapeMd(image[1]);
  const notes = childTags(node, 'notes')
    .map((n) => plainText(textOf(n).join(' ')))
    .join(' ');
  const rest = text
    .replace(image[0], '')
    .replace(INSPECT_TABLE_RE, '')
    .split('\n')
    .filter((l) => !DROPPED_DESIGN_LINES.has(l.trim()) && plainText(l) !== plainText(alt))
    .join('\n')
    .trim();
  if (rest) ctx.warn(`<design> "${alt}" has extra content, kept after the image`);
  return {
    lines: [
      '',
      leaf('image', { src: image[2], alt, caption: notes }),
      ...childTags(node, 'annotations').flatMap(renderAnnotations),
      ...(rest ? ['', rest] : []),
      '',
    ],
    height: 0,
  };
}
 
/**
 * @param {string} md
 * @param {ConvertContext} ctx
 */
export function convertBlocks(md, ctx) {
  return renderChildren(parseBlocks(md, ctx), ctx).lines.join('\n');
}
 
// --- 3. Storybook links ----------------------------------------------------
 
/**
 * Heading text without its optional closing `#`s (`## Title ##` -> `Title`).
 * @param {string} s
 */
function stripClosingHashes(s) {
  let end = s.length;
  while (end > 0 && s[end - 1] === '#') end--;
  return s.slice(0, end).trimEnd();
}
 
/**
 * A line holding only a Storybook link becomes a demo titled after the link
 * text, or the nearest heading above it when the text is "Storybook" / a URL.
 * @param {string} md
 * @param {ConvertContext} ctx
 */
export function convertStorybookLinks(md, ctx) {
  /** @type {string | null} */
  let heading = null;
  return mapLines(md, (line) => {
    const h = /^#{2,6}\s/.exec(line);
    if (h) heading = plainText(stripClosingHashes(line.slice(h[0].length).trim()));
    const m = line.match(/^\[([^\]]*)\]\((https:\/\/[^)\s]+)\)\s*$/);
    const iframe = m && storybookIframeUrl(m[2]);
    return iframe ? componentDemo(iframe, storyLabel(m[1]) ?? heading, ctx) : line;
  });
}
 
// --- 4. Zeroheight links ---------------------------------------------------
 
/**
 * Zeroheight page URLs (`/p/<page>`, `/b/<tab>`, `/t/<heading>`) -> site
 * routes. Unresolved links are kept and reported.
 * @param {string} md
 * @param {ConvertContext} ctx
 */
export function convertZhLinks(md, ctx) {
  return mapLines(md, (line) =>
    line.replace(ZH_LINK_RE, (url, page, kind, id) => {
      const route = ctx.resolveLink({
        page,
        tab: kind === 'b' ? id : null,
        heading: kind === 't' ? id : null,
        url,
      });
      if (!route) ctx.warn(`unresolved link ${url}`);
      return route ?? url;
    }),
  );
}
 
// --- 5. leftovers ----------------------------------------------------------
 
/**
 * @param {string} md
 * @param {ConvertContext} ctx
 */
export function warnUnknownTags(md, ctx) {
  /** @type {Map<string, number>} */
  const counts = new Map();
  mapLines(md, (line) => {
    for (const m of line.replace(/`[^`]*`/g, '').matchAll(/<([a-z][\w-]*)[\s>/]/g)) {
      Eif (!ALLOWED_TAGS.has(m[1])) counts.set(m[1], (counts.get(m[1]) ?? 0) + 1);
    }
    return line;
  });
  for (const [tag, n] of counts) ctx.warn(`unconverted <${tag}> (${n})`);
}