All files / packages/icons/scripts generate-all-icons-html.ts

23.4% Statements 11/47
36.36% Branches 8/22
30.76% Functions 4/13
25% Lines 11/44

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                                                1x                                                                       1x     2x                       1x 1x 1x     1x 1x                                                                                                                                                 2x 2x                 2x                                                                                      
/*
 * Compiles a self-contained `public/index.html` from the React catalog view.
 * No previewer header/nav — the catalog is the home page. Asset paths are
 * relative so the file works via file://; sprites are inlined because browsers
 * block external SVG `<use>` on local files.
 */
import fs from 'node:fs';
import path from 'node:path';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { AllIconsView } from '../src/all-icons-view.js';
import {
  ICONS_ZIP_FALLBACK_URL,
  ICONS_ZIP_FILENAME,
  ICONS_ZIP_RELATIVE_PATH,
  ICON_SETS,
  inlineSpriteSymbolId,
  buildCatalog,
  type IconSet,
  type IconsData,
} from '../src/icon-catalog.js';
import { keywordsFromMetadata } from '../src/icon-keywords.js';
import { readIconPaletteCss } from './icon-palette.js';
 
const PAGE_SCRIPT = `
(function () {
  var searchInput = document.getElementById('icon-search');
  var noResults = document.getElementById('no-results');
  var sections = document.querySelectorAll('.catalog-section');
  function filterIcons(query) {
    var q = query.trim().toLowerCase();
    var visibleCount = 0;
    document.querySelectorAll('.catalog-item').forEach(function (icon) {
      var name = (icon.getAttribute('data-name') || '').toLowerCase();
      var keywords = (icon.getAttribute('data-keywords') || '').toLowerCase();
      var matches = !q || name.indexOf(q) !== -1 || keywords.indexOf(q) !== -1;
      icon.classList.toggle('hidden', !matches);
      if (matches) visibleCount++;
    });
    sections.forEach(function (section) {
      var visible = section.querySelectorAll('.catalog-item:not(.hidden)').length;
      section.classList.toggle('hidden', visible === 0);
    });
    noResults.classList.toggle('visible', visibleCount === 0 && q.length > 0);
  }
  searchInput.addEventListener('input', function (e) {
    filterIcons(e.target.value);
  });
  document.querySelectorAll('.catalog-jump').forEach(function (button) {
    button.addEventListener('click', function () {
      var id = button.getAttribute('data-section');
      var target = id && document.getElementById(id);
      if (target) {
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  });
})();
`;
 
const STALE_CATALOG_FILES = ['public/all-icons.html', 'out/all-icons.html'];
 
function standalonePageCss(catalogCss: string, paletteCss: string): string {
  return `* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
  font-family: system-ui, -apple-system, sans-serif;
  background: #fff;
}
.catalog-page { min-height: 100vh; }
${catalogCss}
${paletteCss}`;
}
 
export function prefixSpriteSymbolIds(svg: string, set: IconSet): string {
  return svg.replace(/<symbol\b([^>]*)>/gi, (full, attrs: string) => {
    const idMatch = attrs.match(/\bid="([^"]+)"/i);
    Iif (!idMatch) {
      return full;
    }
    const prefixed = attrs.replace(/\bid="[^"]+"/i, `id="${inlineSpriteSymbolId(set, idMatch[1])}"`);
    return `<symbol${prefixed}>`;
  });
}
 
export function spriteInnerMarkup(svg: string): string {
  return svg
    .replace(/^\uFEFF/, '')
    .replace(/^[\s\S]*?<svg\b[^>]*>/i, '')
    .replace(/<\/svg>\s*$/i, '');
}
 
export function buildInlineSpriteSheet(sprites: { set: IconSet; svg: string }[]): string {
  if (sprites.length === 0) {
    return '';
  }
  const inner = sprites.map(({ set, svg }) => prefixSpriteSymbolIds(spriteInnerMarkup(svg), set)).join('');
  return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="catalog-sprite-sheet" aria-hidden="true" focusable="false">${inner}</svg>`;
}
 
function readCategorySprites(rootDir: string): { set: IconSet; svg: string }[] {
  const sprites: { set: IconSet; svg: string }[] = [];
  for (const set of ICON_SETS) {
    const candidates = [
      path.join(
        rootDir,
        'public',
        'icons',
        'dist',
        'salesforce-lightning-design-system-icons',
        `${set}-sprite`,
        'svg',
        'symbols.svg',
      ),
      path.join(
        rootDir,
        'dist',
        'salesforce-lightning-design-system-icons',
        `${set}-sprite`,
        'svg',
        'symbols.svg',
      ),
    ];
    const spritePath = candidates.find((candidate) => fs.existsSync(candidate));
    if (!spritePath) {
      console.warn(
        `No ${set} sprite found — ${set} icons will be empty in the static catalog until yarn build.`,
      );
      continue;
    }
    sprites.push({ set, svg: fs.readFileSync(spritePath, 'utf8') });
  }
  return sprites;
}
 
function removeStaleCatalogFiles(rootDir: string): void {
  for (const relativePath of STALE_CATALOG_FILES) {
    const stalePath = path.join(rootDir, relativePath);
    if (fs.existsSync(stalePath)) {
      fs.unlinkSync(stalePath);
    }
  }
}
 
export function generateAllIconsHtml(
  iconsData: IconsData,
  keywordsFor: (set: IconSet, name: string) => string,
  options?: {
    paletteCss?: string;
    catalogCss?: string;
    zipHref?: string;
    spriteSheet?: string;
  },
): string {
  const sections = buildCatalog(iconsData, keywordsFor);
  const body = renderToStaticMarkup(
    createElement(AllIconsView, {
      sections,
      zipHref: options?.zipHref ?? ICONS_ZIP_RELATIVE_PATH,
      relativeAssets: true,
      inlineSprites: true,
      showStaticChrome: true,
    }),
  );
  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Salesforce Icons</title>
  <style>${standalonePageCss(options?.catalogCss ?? '', options?.paletteCss ?? '')}</style>
</head>
<body>
${options?.spriteSheet ?? ''}
${body}
<script>${PAGE_SCRIPT}</script>
</body>
</html>
`;
}
 
export function writeAllIconsHtml(rootDir: string, iconsData: IconsData): string {
  const catalogCss = fs.readFileSync(path.join(rootDir, 'app', 'styles', 'all-icons.css'), 'utf8');
  const zipPath = path.join(rootDir, 'public', 'icons', 'dist', ICONS_ZIP_FILENAME);
  const builtZip = path.join(rootDir, 'dist', ICONS_ZIP_FILENAME);
  const zipHref =
    fs.existsSync(zipPath) || fs.existsSync(builtZip) ? ICONS_ZIP_RELATIVE_PATH : ICONS_ZIP_FALLBACK_URL;
  const html = generateAllIconsHtml(iconsData, (set, name) => keywordsFromMetadata(rootDir, set, name), {
    catalogCss,
    paletteCss: readIconPaletteCss(),
    zipHref,
    spriteSheet: buildInlineSpriteSheet(readCategorySprites(rootDir)),
  });
  const outputPath = path.join(rootDir, 'public', 'index.html');
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
  fs.writeFileSync(outputPath, html, 'utf8');
  const outDir = path.join(rootDir, 'out');
  if (fs.existsSync(outDir)) {
    fs.writeFileSync(path.join(outDir, 'index.html'), html, 'utf8');
  }
  removeStaleCatalogFiles(rootDir);
  return outputPath;
}
 
export function loadStagedIconsData(rootDir: string): IconsData {
  return JSON.parse(fs.readFileSync(path.join(rootDir, 'public', 'icons-all.json'), 'utf8')) as IconsData;
}