feat(packages): extract build logic to @lucide/shared, still wip

This commit is contained in:
Karsa
2026-05-22 21:59:12 +02:00
parent 071e4d2738
commit 2189ae0f55
70 changed files with 1125 additions and 596 deletions
@@ -0,0 +1,30 @@
import type { LucideBuildParams, LucideIconData } from './types';
import buildLucideSvg from './buildLucideSvg';
/**
* Creates a base64 encoded data URI from a Lucide icon object.
*
* @param icon The icon to build.
* @param params Additional build parameters.
*/
function buildLucideDataUri(icon: LucideIconData, params: LucideBuildParams = {}) {
const svg = buildLucideSvg(icon, params);
// Browser
if (typeof btoa === 'function') {
// Ensure proper UTF-8 handling before base64
const utf8Bytes = new TextEncoder().encode(svg);
let binary = '';
for (const element of utf8Bytes) binary += String.fromCodePoint(element);
return `data:image/svg+xml;base64,${btoa(binary)}`;
}
// Node.js (and other JS runtimes with Buffer)
if (typeof Buffer !== 'undefined') {
return `data:image/svg+xml;base64,${Buffer.from(svg, 'utf8').toString('base64')}`;
}
throw new Error('No base64 encoder available in this environment.');
}
export default buildLucideDataUri;
@@ -0,0 +1,36 @@
import buildLucideIconNode from './buildLucideIconNode';
import type { LucideBuildParams, LucideIconData, LucideIconNode } from './types';
const buildDomElement = (
document: Document,
[tagName, attributes, children = []]: LucideIconNode,
): Element => {
const element = document.createElementNS('http://www.w3.org/2000/svg', tagName);
for (const [attrName, value] of Object.entries(attributes)) {
if (value !== undefined && value !== null) {
element.setAttribute(attrName, String(value));
}
}
for (const node of children) {
const childNode = buildDomElement(document, node);
element.appendChild(childNode);
}
return element;
};
/**
* Creates an SvgElement from a Lucide icon object.
*
* @param document The document to create the Element in.
* @param icon The icon to build.
* @param params Additional build parameters.
*/
function buildLucideIconElement(
document: Document,
icon: LucideIconData,
params: LucideBuildParams = {},
) {
return buildDomElement(document, buildLucideIconNode(icon, params));
}
export default buildLucideIconElement;
@@ -0,0 +1,89 @@
import type { LucideBuildParams, LucideIconData, LucideIconNode, SVGProps } from './types';
export type { LucideBuildParams, LucideIconData, LucideIconNode, SVGProps } from './types';
const defaultAttributes: SVGProps = {
xmlns: 'http://www.w3.org/2000/svg',
width: '24',
height: '24',
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
'stroke-width': '2',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
};
const mergeClasses = (...classes: Array<string | undefined>) =>
classes
.filter(
(className, index, array): className is string =>
typeof className === 'string' &&
className.trim() !== '' &&
array.indexOf(className) === index,
)
.join(' ')
.trim();
const toString = (value: string | number) =>
typeof value === 'number' ? value.toString(10) : value.toString();
/**
* Creates a Lucide icon node (an svgson-like format) from a Lucide icon object.
*
* @param icon The icon to build.
* @param params Additional build parameters.
*/
function buildLucideIconNode(icon: LucideIconData, params: LucideBuildParams = {}): LucideIconNode {
const viewBoxWidth =
('size' in icon && icon.size !== undefined
? icon.size
: 'width' in icon
? icon.width
: undefined) ?? defaultAttributes['width'];
const viewBoxHeight =
('size' in icon && icon.size !== undefined
? icon.size
: 'height' in icon
? icon.height
: undefined) ?? defaultAttributes['height'];
const aliasClassNames =
icon.aliases
?.filter((alias): alias is string => typeof alias === 'string' && alias.trim() !== '')
.map((alias) => `lucide-${alias}`) ?? [];
const iconClassNames = [...(icon.name ? [`lucide-${icon.name}`] : []), ...aliasClassNames];
const classNamesFromClassName = params.className?.split(' ').filter(Boolean) ?? [];
const className =
params.includeDefaultClasses === false
? mergeClasses(...classNamesFromClassName)
: mergeClasses('lucide', ...iconClassNames, ...classNamesFromClassName);
const attributes = {
...defaultAttributes,
...('color' in params && params.color && { stroke: params.color }),
...('size' in params &&
params.size && {
width: toString(params.size),
height: toString(params.size),
}),
...('width' in params && params.width && { width: toString(params.width) }),
...('height' in params && params.height && { height: toString(params.height) }),
...('strokeWidth' in params &&
params.strokeWidth && { 'stroke-width': toString(params.strokeWidth) }),
...(className && { class: className }),
viewBox: `0 0 ${viewBoxWidth} ${viewBoxHeight}`,
...(params.hasA11yProp === false ? { 'aria-hidden': 'true' } : {}),
...('attributes' in params && params.attributes),
};
return [
'svg',
attributes,
icon.node.map(([name, attrs]) => [
name,
params.absoluteStrokeWidth ? { 'vector-effect': 'non-scaling-stroke', ...attrs } : attrs,
]),
];
}
export default buildLucideIconNode;
@@ -0,0 +1,20 @@
import buildLucideIconNode from './buildLucideIconNode';
import type { LucideBuildParams, LucideIconData, LucideIconNode } from './types';
const buildDomNode = ([tagName, attributes, children = []]: LucideIconNode): string =>
`<${tagName} ${Object.entries(attributes)
.filter(([, value]) => value !== undefined && value !== null)
.map(([attrName, value]) => `${attrName}="${String(value)}"`)
.join(' ')}>${children?.map((child) => buildDomNode(child)).join('')}</${tagName}>`;
/**
* Creates an SVG string from a Lucide icon object.
*
* @param icon The icon to build.
* @param params Additional build parameters.
*/
function buildLucideSvg(icon: LucideIconData, params: LucideBuildParams = {}) {
return buildDomNode(buildLucideIconNode(icon, params));
}
export default buildLucideSvg;
+54
View File
@@ -0,0 +1,54 @@
export type SVGProps = Record<string, any>;
/**
* A Lucide icon node (an svgson-like internal format)
*/
export type LucideIconNode =
| [attrName: string, attributes: SVGProps]
| [attrName: string, attributes: SVGProps, children: LucideIconNode[]];
/**
* A Lucide icon object that fully describes an icon to be displayed.
*/
export type LucideIconData = {
name?: string;
node: LucideIconNode[];
aliases?: string[];
} & ({ size?: number } | { width?: number; height?: number });
/**
* Build parameters for creating a Lucide icon instance for display.
*/
export type LucideBuildParams = {
/**
* The color of the icon.
*/
color?: string;
/**
* The stroke width.
*/
strokeWidth?: string | number;
/**
* Adds [`vector-effect="non-scaling-stroke"`](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/vector-effect) to child elements.
*/
absoluteStrokeWidth?: boolean;
/**
* Extra CSS class names to pass to the SVG element.
*/
className?: string;
/**
* Include default Lucide classes on the SVG element.
*
* @default true
*/
includeDefaultClasses?: boolean;
/**
* Whether the rendered icon already has accessibility props.
* If false, `aria-hidden="true"` is added automatically.
*/
hasA11yProp?: boolean;
/**
* Any extra attributes to pass to the SVG element.
*/
attributes?: SVGProps;
} & ({ size?: string | number } | { width?: string | number; height?: string | number });
+6
View File
@@ -1,7 +1,13 @@
export { default as buildLucideDataUri } from './build/buildLucideDataUri';
export { default as buildLucideIconElement } from './build/buildLucideIconElement';
export { default as buildLucideIconNode } from './build/buildLucideIconNode';
export { default as buildLucideSvg } from './build/buildLucideSvg';
export type { LucideBuildParams, LucideIconData, LucideIconNode, SVGProps } from './build/types';
export * from './utils/hasA11yProp';
export * from './utils/isEmptyString';
export * from './utils/mergeClasses';
export * from './utils/toCamelCase';
export * from './utils/toKebabCase';
export * from './utils/toLucideIconData';
export * from './utils/toPascalCase';
export * from './utility-types';
@@ -0,0 +1,22 @@
import { toKebabCase } from './toKebabCase';
import type { LucideIconData, LucideIconNode } from '../build/types';
/**
* Converts legacy `(name, iconNode, aliases?)` icon arguments into icon data object format.
*/
export function toLucideIconData(
iconName: string,
iconNode: LucideIconNode[],
aliases: string[] = [],
): LucideIconData {
if (iconNode == null) {
throw new Error('[lucide]: iconNode is required when icon name is used');
}
return {
name: toKebabCase(iconName),
size: 24,
node: iconNode,
...(aliases.length > 0 ? { aliases } : {}),
};
}
@@ -0,0 +1,31 @@
import { describe, it, expect } from 'vitest';
import { toLucideIconData } from '../src/utils/toLucideIconData';
describe('toLucideIconData', () => {
it('converts legacy name and node to icon data object', () => {
const iconNode = [['path', { d: 'M0 0h1' }]];
expect(toLucideIconData('AirVent', iconNode)).toEqual({
name: 'air-vent',
size: 24,
node: iconNode,
});
});
it('adds aliases when provided for legacy input', () => {
const iconNode = [['path', { d: 'M0 0h1' }]];
expect(toLucideIconData('AirVent', iconNode, ['vent'])).toEqual({
name: 'air-vent',
size: 24,
node: iconNode,
aliases: ['vent'],
});
});
it('throws when icon node is missing for legacy string input', () => {
expect(() => toLucideIconData('AirVent', undefined as never)).toThrowError(
'[lucide]: iconNode is required when icon name is used',
);
});
});