ci(icon-preview): Show icon previews in the PR description (#5338)

* ci: show icon previews in the PR description

Replace the icon-preview comment action with a workflow that writes a
preview image per added or changed icon into the PR description, between
the "Icon preview" markers from the PR template. The images are served by
review.lucide.dev, so the workflow no longer needs dependencies or the
PR's SVGs.

- scripts/updatePullRequestDescriptionPreview.mts renders the markup and
  replaces it between the markers (idempotent, keeps CRLF bodies and the
  surrounding text as is), and updates the body through the REST API.
- .github/workflows/pull-request-description-preview.yml runs it on
  pull_request_target from the base branch only.
- Add the "Icon preview" section with the markers to the PR template.
- Remove the pull-request-icon-preview workflow and the icon-preview action.

Co-Authored-By: Claude <noreply@anthropic.com>

* ci: move the PR description preview into the icon-preview action

Move the description preview script and its tests from scripts/ into
.github/actions/icon-preview, a composite action like the old one, with a
package.json (start, debug, test) and an .env.example for local runs. The
workflow now calls the action with the PR number, head SHA, changed files
and token as inputs.

Co-Authored-By: Claude <noreply@anthropic.com>

* ci: adjust the icon-preview action instead of adding a new workflow

Restore the icon-preview action and its workflow from main and adjust
them in place: the action now runs updatePullRequestDescriptionPreview.mts
(Node built-ins only, so no dependencies or install step) to write the
previews into the PR description, and the workflow calls it with the PR
number, head SHA, changed files and token. The separate
pull-request-description-preview workflow is removed.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(icon-preview): remove a lone marker before adding a fresh pair

When only the start or the end marker is left in the description, remove
it (with its line break) before prepending a new marker pair, so the
body never keeps an orphan marker.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Eric Fennis
2026-11-30 14:06:14 +01:00
committed by GitHub
co-authored by Claude
parent b4f90bf3dc
commit 3a699de8e6
10 changed files with 491 additions and 338 deletions
+13 -2
View File
@@ -1,7 +1,18 @@
# Local testing for the icon-preview action.
# Copy to `.env` in this folder and run `pnpm --filter @lucide/icon-preview-action debug`.
# The comment markup is printed to stdout.
# This edits the description of a real pull request, so point it at a test PR.
# Required
# Space-separated list of changed icon files, relative to the repo root
# The pull request to update
PR_NUMBER=
# Head commit SHA of the pull request, used to bust GitHub's image cache
HEAD_SHA=
# Space-separated list of added icon files, relative to the repo root
ADDED_FILES=icons/heart.svg
# Space-separated list of added, modified and renamed icon files, relative to the repo root
CHANGED_FILES=icons/heart.svg icons/star.svg
# The `owner/name` of the repository (set by the runner in GitHub Actions)
GITHUB_REPOSITORY=lucide-icons/lucide
# A token with write access to pull requests, used by the `gh` CLI
# (can be left out when `gh auth login` was used)
GH_TOKEN=
+22 -55
View File
@@ -1,67 +1,34 @@
name: Icon preview
description: Generates the icon preview comment markup for changed icons in a pull request.
description: Writes a preview image for every added or changed icon into the pull request description, between the "Icon preview" markers.
inputs:
changed-files:
description: Space-separated list of changed icon files, relative to the repository root.
pr-number:
description: Number of the pull request to update.
required: true
ref:
head-sha:
description: Head commit SHA of the pull request, used to bust GitHub's image cache.
required: true
added-files:
description: Space-separated list of added icon files, relative to the repository root.
required: true
changed-files:
description: >-
Commit to read the changed icons from, e.g. the pull request head SHA. Only the changed SVG
files are taken from it with `git show`, nothing is checked out. Defaults to the working tree.
required: false
default: ''
output-file:
description: File the comment markup is written to.
required: false
default: comment-markup.md
outputs:
has-changes:
description: Whether any changed icons were found. When `false`, no output file is written.
value: ${{ steps.generate.outputs.has-changes }}
Space-separated list of added, modified and renamed icon files, relative to the repository
root. Deleted files should be left out.
required: true
github-token:
description: 'GitHub token with `pull-requests: write` permission to edit the description.'
required: true
runs:
using: composite
steps:
- name: Read changed icons from ref
id: read-ref
if: inputs.ref != ''
- name: Update PR description
shell: bash
run: |
git fetch --no-tags --depth=1 origin "$REF"
for file in $CHANGED_FILES; do
# Only plain icon file names, so nothing from the pull request ends up in a path or the markup
if [[ ! "$file" =~ ^icons/[a-z0-9-]+\.svg$ ]]; then
echo "::error::Unexpected changed file: $file"
exit 1
fi
mkdir -p "$RUNNER_TEMP/icon-preview/icons"
git show "$REF:$file" > "$RUNNER_TEMP/icon-preview/$file"
done
echo "dir=$RUNNER_TEMP/icon-preview" >> "$GITHUB_OUTPUT"
run: node "$GITHUB_ACTION_PATH/updatePullRequestDescriptionPreview.mts"
env:
GH_TOKEN: ${{ inputs.github-token }}
PR_NUMBER: ${{ inputs.pr-number }}
HEAD_SHA: ${{ inputs.head-sha }}
ADDED_FILES: ${{ inputs.added-files }}
CHANGED_FILES: ${{ inputs.changed-files }}
REF: ${{ inputs.ref }}
- name: Generate comment markup
id: generate
shell: bash
run: |
markup="$(node "$GITHUB_ACTION_PATH/generateChangedIconsCommentMarkup.mts")"
if [ -z "$markup" ]; then
echo "has-changes=false" >> "$GITHUB_OUTPUT"
exit 0
fi
mkdir -p "$(dirname "$OUTPUT_FILE")"
printf '%s\n' "$markup" > "$OUTPUT_FILE"
echo "has-changes=true" >> "$GITHUB_OUTPUT"
env:
CHANGED_FILES: ${{ inputs.changed-files }}
CHANGED_FILES_DIR: ${{ steps.read-ref.outputs.dir }}
OUTPUT_FILE: ${{ inputs.output-file }}
@@ -1,232 +0,0 @@
import fs from 'fs';
import path from 'path';
import { parseSync } from 'svgson';
import {
shuffleArray,
readSvgDirectory,
getCurrentDirPath,
minifySvg,
toPascalCase,
} from '@lucide/helpers';
// The script lives in `.github/actions/icon-preview`, three levels below the repo root.
const REPO_ROOT = path.resolve(getCurrentDirPath(import.meta.url), '../../..');
const ICONS_DIR = path.join(REPO_ROOT, 'icons');
// The changed SVGs can be read from another directory, e.g. files taken from the pull request head
const CHANGED_FILES_DIR = process.env.CHANGED_FILES_DIR || REPO_ROOT;
const BASE_URL = 'https://lucide.dev/api/gh-icon';
const changedFilesPathString = process.env.CHANGED_FILES;
if (changedFilesPathString == null) {
console.error('CHANGED_FILES env variable is not set');
process.exit(1);
}
const changedFiles = changedFilesPathString
.split(' ')
.filter((file) => file.includes('.svg'))
.filter((file, idx, arr) => arr.indexOf(file) === idx)
.map((file) => path.join(CHANGED_FILES_DIR, file));
// Print nothing to stdout, so the action writes no comment markup
if (changedFiles.length === 0) {
console.error('No changed icons found');
process.exit(0);
}
const getImageTagsByFiles = (
files: string[],
getBaseUrl: (file: string) => string,
width?: number,
linkToLucideStudio = false,
) =>
files.map((file) => {
const svgContent = fs.readFileSync(file, 'utf-8');
const strippedAttrsSVG = svgContent.replace(/<svg[^>]*>/, '<svg>');
const minifiedSvg = minifySvg(strippedAttrsSVG);
const name = path.basename(file, '.svg');
const base64 = Buffer.from(minifiedSvg).toString('base64');
const url = getBaseUrl(file);
const widthAttr = width ? `width="${width}"` : '';
return `${linkToLucideStudio ? `<a title="Open ${name} in lucide studio" target="_blank" href="https://studio.lucide.dev/edit?value=${encodeURI(minifiedSvg)}&name=${name}&utm_source=github.com&utm_medium=pr-comment">` : ''}<img title="${name}" alt="${name}" ${widthAttr} src="${url}/${base64}.svg"/>${linkToLucideStudio ? '</a>' : ''}`;
});
const svgFiles = await readSvgDirectory(ICONS_DIR);
const svgFilePaths = svgFiles.map((file) => path.join(ICONS_DIR, file));
const iconsFilteredByName = (search: string) =>
svgFilePaths.filter((file) => path.basename(file).includes(search));
const cohesionRandomImageTags = getImageTagsByFiles(
shuffleArray(svgFilePaths).slice(0, changedFiles.length),
() => `${BASE_URL}/stroke-width/2`,
).join('');
const cohesionSquaresImageTags = getImageTagsByFiles(
shuffleArray(iconsFilteredByName('square')).slice(0, changedFiles.length),
() => `${BASE_URL}/stroke-width/2`,
).join('');
const changeFiles1pxStrokeImageTags = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/stroke-width/1`,
).join('');
const changeFiles2pxStrokeImageTags = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/stroke-width/2`,
).join('');
const changeFiles3pxStrokeImageTags = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/stroke-width/3`,
).join('');
const changeFilesLowDPIImageTags16 = getImageTagsByFiles(changedFiles, (file) => {
const iconName = path.basename(file, '.svg');
return `${BASE_URL}/dpi/${iconName}/16`;
}).join(' ');
const changeFilesLowDPIImageTags24 = getImageTagsByFiles(changedFiles, (file) => {
const iconName = path.basename(file, '.svg');
return `${BASE_URL}/dpi/${iconName}/24`;
}).join(' ');
const changeFilesLowDPIImageTags32 = getImageTagsByFiles(changedFiles, (file) => {
const iconName = path.basename(file, '.svg');
return `${BASE_URL}/dpi/${iconName}/32`;
}).join(' ');
const changeFilesLowDPIImageTags48 = getImageTagsByFiles(changedFiles, (file) => {
const iconName = path.basename(file, '.svg');
return `${BASE_URL}/dpi/${iconName}/48`;
}).join(' ');
const changeFilesXRayImageTags = getImageTagsByFiles(
changedFiles,
(file) => {
const iconName = path.basename(file, '.svg');
return `${BASE_URL}/${iconName}`;
},
400,
true,
).join(' ');
const changeFilesDiffImageTags = getImageTagsByFiles(
changedFiles,
(file) => {
const iconName = path.basename(file, '.svg');
return `${BASE_URL}/diff/${iconName}`;
},
400,
).join(' ');
const changeFilesSymmetryImageTagsRotate180 = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/symmetry/rotate-180`,
400,
).join(' ');
const changeFilesSymmetryImageTagsFlipHorizontal = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/symmetry/flip-horizontal`,
400,
).join(' ');
const changeFilesSymmetryImageTagsFlipVertical = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/symmetry/flip-vertical`,
400,
).join(' ');
const changeFilesSymmetryImageTagsFlipSlash = getImageTagsByFiles(
changedFiles,
() => `${BASE_URL}/symmetry/flip-slash`,
400,
).join(' ');
const readyToUseCode = changedFiles
.map((changedFile) => {
const svgContent = fs.readFileSync(changedFile, 'utf-8');
const name = path.basename(changedFile, '.svg');
return `const ${toPascalCase(name)}Icon = createLucideIcon('${toPascalCase(name)}', [
${parseSync(svgContent)
.children.map(({ name, attributes }) => JSON.stringify([name, attributes]))
.join(',\n ')}
])`;
})
.join('\n\n');
const commentMarkup = `\
### Added or changed icons
${
changedFiles.length >= 8
? `<details>
<summary>Icon X-rays</summary>
${changeFilesXRayImageTags}
</details>
`
: ''
}${changeFiles2pxStrokeImageTags}
<details>
<summary>Preview cohesion</summary>
${cohesionSquaresImageTags}<br/>
${changeFiles2pxStrokeImageTags}<br/>
${cohesionRandomImageTags}<br/>
</details>
<details>
<summary>Preview stroke widths</summary>
${changeFiles1pxStrokeImageTags}<br/>
${changeFiles2pxStrokeImageTags}<br/>
${changeFiles3pxStrokeImageTags}<br/>
</details>
<details>
<summary>DPI Preview</summary>
<h4>16px (shadcn/ui)</h4>
${changeFilesLowDPIImageTags16}
<h4>24px (default)</h4>
${changeFilesLowDPIImageTags24}
<h4>32px (shadcn/ui + retina)</h4>
${changeFilesLowDPIImageTags32}
<h4>48px (default + retina)</h4>
${changeFilesLowDPIImageTags48}
</details>${
changedFiles.length < 8
? `
<details>
<summary>Icon X-rays</summary>
${changeFilesXRayImageTags}
</details>`
: ''
}
<details>
<summary>Icon Diffs</summary>
${changeFilesDiffImageTags}
</details>
<details>
<summary>Icon Symmetry</summary>
<h4>Flip Horizontal</h4>
${changeFilesSymmetryImageTagsFlipHorizontal}
<h4>Flip Vertical</h4>
${changeFilesSymmetryImageTagsFlipVertical}
<h4>Flip Diagonal</h4>
${changeFilesSymmetryImageTagsFlipSlash}
<h4>Rotate 180°</h4>
${changeFilesSymmetryImageTagsRotate180}
</details>
<details>
<summary>Icons as code</summary>
Works for: \`lucide-react\`, \`lucide-react-native\`, \`lucide-preact\`, \`lucide-vue-next\`
\`\`\`ts
${readyToUseCode}
\`\`\`
</details>`;
console.log(commentMarkup);
+4 -7
View File
@@ -2,13 +2,10 @@
"name": "@lucide/icon-preview-action",
"private": true,
"type": "module",
"description": "GitHub action that generates the icon preview comment markup for changed icons in a pull request",
"description": "GitHub action that writes a preview of the added or changed icons into the pull request description",
"scripts": {
"start": "node ./generateChangedIconsCommentMarkup.mts",
"debug": "node --env-file .env ./generateChangedIconsCommentMarkup.mts"
},
"dependencies": {
"@lucide/helpers": "workspace:*",
"svgson": "catalog:"
"start": "node ./updatePullRequestDescriptionPreview.mts",
"debug": "node --env-file .env ./updatePullRequestDescriptionPreview.mts",
"test": "node --test ./*.test.mts"
}
}
@@ -0,0 +1,208 @@
/**
* Writes a preview image for every added or changed icon into the description
* of a pull request, between the "Icon preview" markers from the PR template.
*
* The images are rendered by review.lucide.dev, so this script only writes
* markup that points to them. Like `scripts/updateSponsors.mts`, it replaces
* whatever is between the markers and leaves the rest of the description
* untouched.
*
* The markup is built by pure functions, and the CLI wrapper at the bottom
* reads its input from the environment (see `action.yml` and `.env.example`).
* It only imports Node built-ins, so the action runs it natively as an `.mts`
* file without a `pnpm install` step.
*
* Env input (CLI wrapper at the bottom):
* - `PR_NUMBER`: the pull request number.
* - `HEAD_SHA`: the head commit of the pull request, used to bust GitHub's image cache.
* - `ADDED_FILES`: a space-separated list of added files.
* - `CHANGED_FILES`: a space-separated list of added, modified and renamed files.
* - `GITHUB_REPOSITORY`: the `owner/name` of the repository.
*
* Writes the description with the `gh` CLI, which needs `GH_TOKEN`.
*/
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
export const startMarker = '[//]: <> (Icon preview start)';
export const endMarker = '[//]: <> (Icon preview end)';
const REVIEW_URL = 'https://review.lucide.dev';
// How many icons to show before linking to the review site for the rest.
export const MAX_ICONS = 40;
const VALID_NAME = /^[a-z0-9-]+$/;
export type IconStatus = 'added' | 'changed';
export type Icon = {
name: string;
status: IconStatus;
};
type IconPreviewInput = {
pr: number;
sha: string;
icons: Icon[];
};
const escapeHtml = (value: string) =>
value
.replaceAll('&', '&amp;')
.replaceAll('"', '&quot;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;');
/**
* One linked `<picture>` per icon. The `<picture>` has to be on its own line
* inside the `<a>`, otherwise GitHub doesn't render the link around it.
* The sources switch to a larger preview on wider screens.
*/
const renderIcon = (pr: number, sha: string, { name, status }: Icon) => {
const imageUrl = (view?: string) => {
const params = new URLSearchParams();
if (view) params.set('view', view);
params.set('v', sha);
return `${REVIEW_URL}/api/pr/${pr}/${name}/preview.svg?${params}`;
};
const href = `${REVIEW_URL}/pr/${pr}?icon=${name}`;
return [
`<a href="${escapeHtml(href)}" target="_blank">`,
`<picture>`,
` <source media="(min-width: 1280px)" srcset="${escapeHtml(imageUrl('full'))}" />`,
` <source media="(min-width: 768px)" srcset="${escapeHtml(imageUrl('medium'))}" />`,
` <img alt="${escapeHtml(`${name} (${status})`)}" src="${escapeHtml(imageUrl())}" />`,
`</picture>`,
`</a>`,
].join('\n');
};
/**
* Pure markup function: renders the preview of the given icons, sorted by name.
* Names that are not valid icon names are dropped. Returns an empty string when
* there are no icons.
*/
export const renderIconPreview = ({ pr, sha, icons }: IconPreviewInput): string => {
const shortSha = sha.slice(0, 7);
const validIcons = icons
.filter(({ name }) => VALID_NAME.test(name))
.filter((icon, index, all) => all.findIndex(({ name }) => name === icon.name) === index)
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
if (validIcons.length === 0) return '';
const blocks = validIcons.slice(0, MAX_ICONS).map((icon) => renderIcon(pr, shortSha, icon));
const remaining = validIcons.length - MAX_ICONS;
if (remaining > 0) {
blocks.push(
`…and ${remaining} more ${remaining === 1 ? 'icon' : 'icons'}, see all on [review.lucide.dev](${REVIEW_URL}/pr/${pr}).`,
);
}
return blocks.join('\n\n');
};
/**
* Removes every occurrence of `marker` together with the line break after it
* (or before it, when it's on the last line), so no empty line is left behind.
*/
const removeMarker = (body: string, marker: string): string => {
const escaped = marker.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
return body.replaceAll(new RegExp(`${escaped}\\r?\\n|\\r?\\n${escaped}$|${escaped}`, 'g'), '');
};
/**
* Replaces everything between the markers with `markup`, like
* `scripts/updateSponsors.mts` does for the README. The text around the
* markers is kept as is. When the markers are missing they are added, with the
* markup, at the start of the body; a lone start or end marker is removed
* first. CRLF bodies (as written by the GitHub web editor) keep their line
* endings.
*/
export const replaceBetweenMarkers = (body: string, markup: string): string => {
const eol = body.includes('\r\n') ? '\r\n' : '\n';
const separator = `${eol}${eol}`;
const content = markup.replaceAll(/\r?\n/g, eol);
const startIndex = body.indexOf(startMarker);
const endIndex = body.indexOf(endMarker);
if (startIndex === -1 || endIndex === -1) {
// A lone marker is removed, so the body ends up with exactly one pair.
const orphan = startIndex !== -1 ? startMarker : endIndex !== -1 ? endMarker : null;
const rest = orphan == null ? body : removeMarker(body, orphan);
const block = [startMarker, content, endMarker].filter(Boolean).join(separator);
return rest === '' ? block : `${block}${separator}${rest}`;
}
if (endIndex < startIndex) {
throw new Error(`"${endMarker}" comes before "${startMarker}" in the description`);
}
return [body.slice(0, startIndex + startMarker.length), content, body.slice(endIndex)]
.filter(Boolean)
.join(separator);
};
// --- CLI wrapper -----------------------------------------------------------
// Only runs when executed directly, keeping the functions above unit-testable.
const iconNames = (list: string | undefined): string[] =>
(list ?? '')
.split(/\s+/)
.map((file) => /^icons\/([^/]+)\.svg$/.exec(file.trim())?.[1])
.filter((name) => name != null);
if (import.meta.main) {
const { PR_NUMBER, HEAD_SHA, ADDED_FILES, CHANGED_FILES, GITHUB_REPOSITORY } = process.env;
const pr = Number(PR_NUMBER);
if (!Number.isInteger(pr) || pr <= 0) throw new Error(`Invalid PR_NUMBER: ${PR_NUMBER}`);
if (!HEAD_SHA) throw new Error('HEAD_SHA is required');
if (!GITHUB_REPOSITORY) throw new Error('GITHUB_REPOSITORY is required');
const added = iconNames(ADDED_FILES);
const changed = iconNames(CHANGED_FILES).filter((name) => !added.includes(name));
const icons: Icon[] = [
...added.map((name) => ({ name, status: 'added' as const })),
...changed.map((name) => ({ name, status: 'changed' as const })),
];
const markup = renderIconPreview({ pr, sha: HEAD_SHA, icons });
const endpoint = `repos/${GITHUB_REPOSITORY}/pulls/${pr}`;
// Fetch the current body right before writing, so edits made since the
// workflow was triggered are not overwritten.
const pullRequest = JSON.parse(execFileSync('gh', ['api', endpoint], { encoding: 'utf-8' }));
const body: string = pullRequest.body ?? '';
const hasMarkers = body.includes(startMarker) || body.includes(endMarker);
if (markup === '' && !hasMarkers) {
console.log('No icon previews and no markers, leaving the description alone.');
} else {
const newBody = replaceBetweenMarkers(body, markup);
if (newBody === body) {
console.log('Icon preview is up to date.');
} else {
// The body goes through a file, so it never ends up in a shell argument.
const tempDir = mkdtempSync(join(tmpdir(), 'pr-description-'));
const bodyPath = join(tempDir, 'body.md');
try {
writeFileSync(bodyPath, newBody);
execFileSync('gh', ['api', '-X', 'PATCH', endpoint, '-F', `body=@${bodyPath}`], {
stdio: ['ignore', 'ignore', 'inherit'],
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
console.log(`Updated the icon preview of #${pr} with ${icons.length} icon(s).`);
}
}
}
@@ -0,0 +1,222 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import {
endMarker,
MAX_ICONS,
renderIconPreview,
replaceBetweenMarkers,
startMarker,
} from './updatePullRequestDescriptionPreview.mts';
const SHA = 'abc1234def5678';
describe('renderIconPreview', () => {
it('renders a linked picture per icon', () => {
assert.equal(
renderIconPreview({ pr: 42, sha: SHA, icons: [{ name: 'heart', status: 'added' }] }),
[
'<a href="https://review.lucide.dev/pr/42?icon=heart" target="_blank">',
'<picture>',
' <source media="(min-width: 1280px)" srcset="https://review.lucide.dev/api/pr/42/heart/preview.svg?view=full&amp;v=abc1234" />',
' <source media="(min-width: 768px)" srcset="https://review.lucide.dev/api/pr/42/heart/preview.svg?view=medium&amp;v=abc1234" />',
' <img alt="heart (added)" src="https://review.lucide.dev/api/pr/42/heart/preview.svg?v=abc1234" />',
'</picture>',
'</a>',
].join('\n'),
);
});
it('uses the status in the alt text', () => {
const markup = renderIconPreview({
pr: 1,
sha: SHA,
icons: [
{ name: 'heart', status: 'changed' },
{ name: 'star', status: 'added' },
],
});
assert.match(markup, /alt="heart \(changed\)"/);
assert.match(markup, /alt="star \(added\)"/);
});
it('sorts by name and separates icons with a blank line', () => {
const markup = renderIconPreview({
pr: 1,
sha: SHA,
icons: [
{ name: 'zap', status: 'added' },
{ name: 'anchor', status: 'changed' },
],
});
const blocks = markup.split('\n\n');
assert.equal(blocks.length, 2);
assert.match(blocks[0], /icon=anchor"/);
assert.match(blocks[1], /icon=zap"/);
});
it('drops invalid icon names', () => {
const markup = renderIconPreview({
pr: 1,
sha: SHA,
icons: [
{ name: 'heart', status: 'added' },
{ name: 'Heart', status: 'added' },
{ name: '"><script>', status: 'added' },
{ name: '../secret', status: 'changed' },
{ name: '', status: 'changed' },
],
});
assert.equal(markup.split('\n\n').length, 1);
assert.match(markup, /icon=heart"/);
assert.doesNotMatch(markup, /script|secret|Heart/);
});
it('returns an empty string without icons', () => {
assert.equal(renderIconPreview({ pr: 1, sha: SHA, icons: [] }), '');
assert.equal(
renderIconPreview({ pr: 1, sha: SHA, icons: [{ name: 'Not Valid', status: 'added' }] }),
'',
);
});
it(`caps the preview at ${MAX_ICONS} icons and links to the rest`, () => {
const icons = Array.from({ length: MAX_ICONS + 3 }, (_, index) => ({
name: `icon-${String(index).padStart(2, '0')}`,
status: 'added' as const,
}));
const markup = renderIconPreview({ pr: 7, sha: SHA, icons });
const blocks = markup.split('\n\n');
assert.equal(blocks.length, MAX_ICONS + 1);
assert.equal(blocks.filter((block) => block.startsWith('<a ')).length, MAX_ICONS);
assert.doesNotMatch(markup, /icon=icon-40"/);
assert.match(blocks.at(-1)!, /3 more icons/);
assert.match(blocks.at(-1)!, /\(https:\/\/review\.lucide\.dev\/pr\/7\)/);
});
it('does not add the overflow line at exactly the cap', () => {
const icons = Array.from({ length: MAX_ICONS }, (_, index) => ({
name: `icon-${index}`,
status: 'added' as const,
}));
const blocks = renderIconPreview({ pr: 7, sha: SHA, icons }).split('\n\n');
assert.equal(blocks.length, MAX_ICONS);
});
});
describe('replaceBetweenMarkers', () => {
const markup = 'MARKUP\nLINE 2';
it('replaces the content between the markers', () => {
const body = `Intro\n\n${startMarker}\n\nold preview\n\n${endMarker}\n\nOutro`;
assert.equal(
replaceBetweenMarkers(body, markup),
`Intro\n\n${startMarker}\n\n${markup}\n\n${endMarker}\n\nOutro`,
);
});
it('keeps the text around the markers byte for byte', () => {
const before = '## Description\n trailing spaces \n\t<!-- comment -->\n\n\n## Icon preview\n';
const after = '\n\n## Icon use cases \n- one\n\n\n';
const body = `${before}${startMarker}${endMarker}${after}`;
const result = replaceBetweenMarkers(body, markup);
assert.ok(result.startsWith(`${before}${startMarker}`));
assert.ok(result.endsWith(`${endMarker}${after}`));
});
it('keeps the markers with nothing between them for empty markup', () => {
const body = `Intro\n\n${startMarker}\n\nold preview\n\n${endMarker}\n\nOutro`;
assert.equal(
replaceBetweenMarkers(body, ''),
`Intro\n\n${startMarker}\n\n${endMarker}\n\nOutro`,
);
});
it('adds the markers at the start when they are missing', () => {
assert.equal(
replaceBetweenMarkers('Some description', markup),
`${startMarker}\n\n${markup}\n\n${endMarker}\n\nSome description`,
);
});
it('adds the markers to an empty body', () => {
assert.equal(replaceBetweenMarkers('', markup), `${startMarker}\n\n${markup}\n\n${endMarker}`);
});
it('throws when the end marker comes before the start marker', () => {
const body = `${endMarker}\n\n${startMarker}`;
assert.throws(() => replaceBetweenMarkers(body, markup), /comes before/);
});
const count = (text: string, search: string) => text.split(search).length - 1;
for (const [name, orphan] of [
['start', startMarker],
['end', endMarker],
]) {
it(`replaces a lone ${name} marker with a fresh pair`, () => {
const body = `Intro\n\n${orphan}\nOutro`;
const result = replaceBetweenMarkers(body, markup);
assert.equal(result, `${startMarker}\n\n${markup}\n\n${endMarker}\n\nIntro\n\nOutro`);
assert.equal(count(result, startMarker), 1);
assert.equal(count(result, endMarker), 1);
assert.equal(replaceBetweenMarkers(result, markup), result);
});
it(`removes a lone ${name} marker from a CRLF body`, () => {
const body = `Intro\r\n\r\n${orphan}\r\nOutro\r\n`;
const result = replaceBetweenMarkers(body, '');
assert.equal(result, `${startMarker}\r\n\r\n${endMarker}\r\n\r\nIntro\r\n\r\nOutro\r\n`);
assert.equal(count(result, startMarker), 1);
assert.equal(count(result, endMarker), 1);
assert.equal(replaceBetweenMarkers(result, ''), result);
});
it(`removes a lone ${name} marker on the last line`, () => {
const result = replaceBetweenMarkers(`Intro\n${orphan}`, markup);
assert.equal(result, `${startMarker}\n\n${markup}\n\n${endMarker}\n\nIntro`);
assert.equal(replaceBetweenMarkers(result, markup), result);
});
}
it('keeps CRLF line endings', () => {
const body = `Intro\r\n\r\n${startMarker}\r\n${endMarker}\r\n\r\nOutro\r\n`;
assert.equal(
replaceBetweenMarkers(body, markup),
`Intro\r\n\r\n${startMarker}\r\n\r\nMARKUP\r\nLINE 2\r\n\r\n${endMarker}\r\n\r\nOutro\r\n`,
);
});
it('is idempotent', () => {
const bodies = [
`Intro\n\n${startMarker}\n${endMarker}\nOutro`,
`Intro\r\n${startMarker}\r\n${endMarker}\r\nOutro`,
'No markers yet',
'',
];
for (const body of bodies) {
for (const content of [markup, '']) {
const once = replaceBetweenMarkers(body, content);
assert.equal(replaceBetweenMarkers(once, content), once);
}
}
});
it('is idempotent with real preview markup', () => {
const preview = renderIconPreview({
pr: 1,
sha: SHA,
icons: [
{ name: 'heart', status: 'added' },
{ name: 'star', status: 'changed' },
],
});
const once = replaceBetweenMarkers('## Description\n\nText', preview);
assert.equal(replaceBetweenMarkers(once, preview), once);
});
});