Lucide 0.15.0 (#272)

* add configs

* Add vue components

* Add documentation

* add alpha release version

* improve npm ignore files

* add tests

* Make style and class attrs work

* 📦 bump version

* Add Icon suffix for component names

* bump version

* Add icon component example

* remove space

* add new build strategy

* Write a better intro

* add other node design

* fix

* add new default template

* add tempalte

* improve code

* small improvements

* small improvements

* move files

* Connect lucide with lucide-react

* Add support for vue

* Add licenses to packages

* Fix tests

* refactor build scripts

* Minor code fixes

* update homepage readme

* Update footer text

* Add a better introduction to packages

* Split up in tempaltes

* Add new types build file

* Setup workflow file

* update readme

* update

* Fix build

* remove debug code

* Add check if svgs have duplicated children

* Add check if their are no children

* small fixes

* last fixes in the build

* Move script to packages folder

* Fix tests and add types for lucide

* Add rule to package.json

* add types in build

* add npm ignore

* update package.jsons
This commit is contained in:
Eric Fennis
2021-03-23 19:26:50 +01:00
committed by GitHub
parent 9d101a5275
commit b4e4f002f2
81 changed files with 5804 additions and 1655 deletions

View File

@@ -4,24 +4,28 @@ import path from 'path';
import prettier from 'prettier';
import { toPascalCase } from '../helpers';
export default function(iconNode, outputDirectory, template) {
const icons = Object.keys(iconNode);
export default function(iconNodes, outputDirectory, template, { showLog = true }) {
const icons = Object.keys(iconNodes);
const iconsDistDirectory = path.join(outputDirectory, `icons`);
if (!fs.existsSync(iconsDistDirectory)) {
fs.mkdirSync(iconsDistDirectory);
}
icons.forEach(icon => {
const location = path.join(iconsDistDirectory, `${icon}.js`);
const componentName = toPascalCase(icon);
icons.forEach(iconName => {
const location = path.join(iconsDistDirectory, `${iconName}.js`);
const componentName = toPascalCase(iconName);
const node = JSON.stringify(iconNode[icon]);
let { children } = iconNodes[iconName];
children = children.map(({name, attributes}) => ([name, attributes]))
const elementTemplate = template({ componentName, node });
const elementTemplate = template({ componentName, iconName, children });
fs.writeFileSync(location, prettier.format(elementTemplate, { parser: 'babel' }), 'utf-8');
console.log('Successfully built', componentName);
fs.writeFileSync(location, prettier.format(elementTemplate, { singleQuote: true, trailingComma: 'all', parser: 'babel' }), 'utf-8');
if(showLog) {
console.log('Successfully built', componentName);
}
});
}

View File

@@ -1,35 +0,0 @@
import path from 'path';
import { readSvgDirectory, resetFile, appendFile, toPascalCase } from './helpers';
const ICONS_DIR = path.resolve(__dirname, '../icons');
const DTS_FILE_NAME = 'index.d.ts';
const DTS_FILE_ROOT = path.resolve(__dirname, '../');
resetFile(DTS_FILE_NAME, DTS_FILE_ROOT);
// Generates header of d.ts file include some types and functions
appendFile(
`
export type IconData = readonly [string, object, IconData?];
export type IconString = string;
export function createElement(ico: IconData): SVGSVGElement;
export declare const icons: { [key: string]: IconData };
// Generated icons
`,
DTS_FILE_NAME,
DTS_FILE_ROOT,
);
const svgFiles = readSvgDirectory(ICONS_DIR);
svgFiles.forEach(svgFile => {
const nameSvg = path.basename(svgFile, '.svg');
const namePascal = toPascalCase(nameSvg);
appendFile(`export declare const ${namePascal}: IconData;\n`, DTS_FILE_NAME, DTS_FILE_ROOT);
});
console.log(`Successfully generated '${DTS_FILE_NAME}'.`);

View File

@@ -1,15 +1,12 @@
import fs from 'fs';
import path from 'path';
// eslint-disable-next-line import/no-extraneous-dependencies
import getArgumentOptions from 'minimist';
import getArgumentOptions from 'minimist'; // eslint-disable-line import/no-extraneous-dependencies
import renderIconsObject from './render/renderIconsObject';
import renderIconNodes from './render/renderIconNodes';
import generateIconFiles from './build/generateIconFiles';
import generateExportsFile from './build/generateExportsFile';
import { readSvgDirectory } from './helpers';
/* eslint-disable import/no-dynamic-require */
import { readSvgDirectory } from './helpers';
const cliArguments = getArgumentOptions(process.argv.slice(2));
@@ -23,26 +20,14 @@ if (!fs.existsSync(OUTPUT_DIR)) {
const svgFiles = readSvgDirectory(ICONS_DIR);
const icons = renderIconsObject(svgFiles, ICONS_DIR);
const icons = renderIconsObject(svgFiles, ICONS_DIR, cliArguments.renderUniqueKey);
const iconVNodes = renderIconNodes(icons, cliArguments);
const defaultIconFileTemplate = ({ componentName, node }) => `
const ${componentName} = ${node};
export default ${componentName};
`;
const iconFileTemplate = cliArguments.templateSrc
? require(cliArguments.templateSrc).default
: defaultIconFileTemplate;
const defaultIconFileTemplate = './templates/defaultIconFileTemplate';
// eslint-disable-next-line import/no-dynamic-require
const iconFileTemplate = require(cliArguments.templateSrc || defaultIconFileTemplate).default;
// Generates iconsNodes files for each icon
generateIconFiles(iconVNodes, OUTPUT_DIR, iconFileTemplate);
generateIconFiles(icons, OUTPUT_DIR, iconFileTemplate, { showLog: !cliArguments.silent });
// Generates entry files for the compiler filled with icons exports
generateExportsFile(
path.join(SRC_DIR, 'icons/index.js'),
path.join(OUTPUT_DIR, 'icons'),
iconVNodes,
);
generateExportsFile(path.join(SRC_DIR, 'icons/index.js'), path.join(OUTPUT_DIR, 'icons'), icons);

View File

@@ -2,9 +2,10 @@ import fs from 'fs';
import path from 'path';
/**
* Converts string to PascalCase
* Converts string to CamelCase
*
* @param {string} string
* @returns {string} A camelized string
*/
export const toCamelCase = string =>
string.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2) =>
@@ -15,6 +16,7 @@ export const toCamelCase = string =>
* Converts string to PascalCase
*
* @param {string} string
* @returns {string} A pascalized string
*/
export const toPascalCase = string => {
const camelCase = toCamelCase(string);
@@ -23,9 +25,10 @@ export const toPascalCase = string => {
};
/**
* Converts string to PascalCase
* Converts string to KebabCase
*
* @param {string} string
* @returns {string} A kebabized string
*/
export const toKebabCase = string => string.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
@@ -42,6 +45,7 @@ export const resetFile = (fileName, outputDirectory) =>
* Reads the file contents.
*
* @param {string} path
* @returns {string} The contents of a file
*/
export const readFile = entry => fs.readFileSync(path.resolve(__dirname, '../', entry), 'utf-8');
@@ -69,6 +73,7 @@ export const writeFile = (content, fileName, outputDirectory) =>
* reads the icon directory
*
* @param {string} directory
* @returns {array} An array of file paths containig svgs
*/
export const readSvgDirectory = directory =>
fs.readdirSync(directory).filter(file => path.extname(file) === '.svg');
@@ -79,7 +84,8 @@ export const readSvgDirectory = directory =>
* @param {string} fileName
* @param {string} directory
*/
export const readSvg = (fileName, directory) => fs.readFileSync(path.join(directory, fileName));
export const readSvg = (fileName, directory) =>
fs.readFileSync(path.join(directory, fileName), 'utf-8');
/**
* writes content to a file
@@ -91,7 +97,13 @@ export const readSvg = (fileName, directory) => fs.readFileSync(path.join(direct
export const writeSvgFile = (fileName, outputDirectory, content) =>
fs.writeFileSync(path.join(outputDirectory, fileName), content, 'utf-8');
// This is a djb2 hashing function
/**
* djb2 hashing function
*
* @param {string} string
* @param {number} seed
* @returns {string} A hashed string of 6 characters
*/
export const hash = (string, seed = 5381) => {
let i = string.length;
@@ -103,3 +115,27 @@ export const hash = (string, seed = 5381) => {
// eslint-disable-next-line no-bitwise
return (seed >>> 0).toString(36).substr(0, 6);
};
/**
* Generate Hashed string based on name and attributes
*
* @param {object} seed
* @param {string} seed.name A name, for example an icon name
* @param {object} seed.attributes An object of SVGElement Attrbutes
* @returns {string} A hashed string of 6 characters
*/
export const generateHashedKey = ({ name, attributes }) => hash(JSON.stringify([name, attributes]));
/**
* Checks if array of items contains duplicated items
*
* @param {array} children an array of items
* @returns {Boolean} if items contains duplicated items.
*/
export const hasDuplicatedChildren = children => {
const hashedKeys = children.map(generateHashedKey);
return !hashedKeys.every(
(key, index) => index === hashedKeys.findIndex(childKey => childKey === key),
);
};

View File

@@ -1,6 +1,6 @@
const { promises: fs } = require("fs");
const outlineStroke = require("svg-outline-stroke");
const { parse, stringify } = require("svgson");
const { promises: fs } = require('fs');
const outlineStroke = require('svg-outline-stroke');
const { parse, stringify } = require('svgson');
const inputDir = `./icons/`;
const outputDir = `./converted_icons/`;
@@ -8,19 +8,16 @@ const outputDir = `./converted_icons/`;
async function init() {
try {
const files = await fs.readdir(inputDir);
for (let file of files) {
for (const file of files) {
const icon = await fs.readFile(`${inputDir}${file}`);
const scaled = await parse(icon.toString(), {
transformNode: transformForward
transformNode: transformForward,
});
const outlined = await outlineStroke(stringify(scaled));
const outlinedWithoutAttrs = await parse(outlined, {
transformNode: transformBackwards
transformNode: transformBackwards,
});
await fs.writeFile(
`${outputDir}${file}`,
stringify(outlinedWithoutAttrs)
);
await fs.writeFile(`${outputDir}${file}`, stringify(outlinedWithoutAttrs));
}
} catch (err) {
console.log(err);
@@ -30,25 +27,25 @@ async function init() {
init();
function transformForward(node) {
if (node.name === "svg") {
if (node.name === 'svg') {
return {
...node,
attributes: {
...node.attributes,
width: 960,
height: 960
}
height: 960,
},
};
}
return node;
}
function transformBackwards(node) {
if (node.name === "svg") {
if (node.name === 'svg') {
const { width, height, ...attributes } = node.attributes;
return {
...node,
attributes
attributes,
};
}
return node;

View File

@@ -1,30 +1,13 @@
/* eslint-disable import/no-extraneous-dependencies */
import Svgo from 'svgo';
import cheerio from 'cheerio';
import { format } from 'prettier';
import { parseSync, stringify } from 'svgson';
import DEFAULT_ATTRS from './default-attrs.json';
/**
* Process SVG string.
* @param {string} svg - An SVG string.
* @param {Promise<string>}
*/
function processSvg(svg) {
return (
optimize(svg)
.then(setAttrs)
.then(optimizedSvg => format(optimizedSvg, { parser: 'babel' }))
// remove semicolon inserted by prettier
// because prettier thinks it's formatting JSX not HTML
.then(svg => svg.replace(/;/g, ''))
);
}
/**
* Optimize SVG with `svgo`.
* @param {string} svg - An SVG string.
* @returns {Promise<string>}
* @returns {Promise<string>} An optimized svg
*/
function optimize(svg) {
const svgo = new Svgo({
@@ -42,14 +25,30 @@ function optimize(svg) {
/**
* Set default attibutes on SVG.
* @param {string} svg - An SVG string.
* @returns {string}
* @returns {string} An SVG string, included with the default attributes.
*/
function setAttrs(svg) {
const $ = cheerio.load(svg);
const contents = parseSync(svg);
Object.keys(DEFAULT_ATTRS).forEach(key => $('svg').attr(key, DEFAULT_ATTRS[key]));
contents.attributes = DEFAULT_ATTRS;
return $('body').html();
return stringify(contents);
}
/**
* Process SVG string.
* @param {string} svg An SVG string.
* @returns {Promise<string>} An optimized svg
*/
function processSvg(svg) {
return (
optimize(svg)
.then(setAttrs)
.then(optimizedSvg => format(optimizedSvg, { parser: 'babel' }))
// remove semicolon inserted by prettier
// because prettier thinks it's formatting JSX not HTML
.then(svg => svg.replace(/;/g, ''))
);
}
export default processSvg;

View File

@@ -1,53 +0,0 @@
/* eslint-disable import/no-extraneous-dependencies */
import { parseDOM } from 'htmlparser2';
import DEFAULT_ATTRS from './default-attrs.json';
import { toCamelCase, hash } from '../helpers';
const camelizeAttrs = attrs =>
Object.keys(attrs).reduce((newAttrs, attr) => {
const attrKey = toCamelCase(attr);
newAttrs[attrKey] = attrs[attr];
return newAttrs;
}, {});
export default (iconsObject, options) => {
const iconNodes = {};
Object.keys(iconsObject).forEach(icon => {
const svgString = iconsObject[icon];
const dom = parseDOM(svgString);
const children = dom.map(element => {
if (options.renderUniqueKey) {
const hashSource = {
name: element.name,
...element.attribs,
};
const uniqueKey = hash(JSON.stringify(hashSource));
element.attribs.key = uniqueKey;
}
return [
element.name,
{
...(options.camelizeAttrs ? camelizeAttrs(element.attribs) : element.attribs),
},
];
});
iconNodes[icon] = !options.noDefaultAttrs
? [
'svg',
{
...(options.camelizeAttrs ? camelizeAttrs(DEFAULT_ATTRS) : DEFAULT_ATTRS),
},
children,
]
: children;
});
return iconNodes;
};

View File

@@ -1,19 +1,7 @@
/* eslint-disable import/no-extraneous-dependencies */
import path from 'path';
import cheerio from 'cheerio';
import { minify } from 'html-minifier';
import { readSvg } from '../helpers';
/**
* Get contents between opening and closing `<svg>` tags.
* @param {string} svg
* @returns {string}
*/
function getSvgContents(svg) {
const $ = cheerio.load(svg);
return minify($('svg').html(), { collapseWhitespace: true });
}
import { basename } from 'path';
import { parseSync } from 'svgson';
import { generateHashedKey, readSvg, hasDuplicatedChildren } from '../helpers';
/**
* Build an object in the format: `{ <name>: <contents> }`.
@@ -21,12 +9,29 @@ function getSvgContents(svg) {
* @param {Function} getSvg - A function that returns the contents of an SVG file given a filename.
* @returns {Object}
*/
export default (svgFiles, iconsDirectory) =>
export default (svgFiles, iconsDirectory, renderUniqueKey = false) =>
svgFiles
.map(svgFile => {
const name = path.basename(svgFile, '.svg');
const name = basename(svgFile, '.svg');
const svg = readSvg(svgFile, iconsDirectory);
const contents = getSvgContents(svg);
const contents = parseSync(svg);
if (!(contents.children && contents.children.length)) {
throw new Error(`${name}.svg has no children!`);
}
if (hasDuplicatedChildren(contents.children)) {
throw new Error(`Duplicated children in ${name}.svg`);
}
if (renderUniqueKey) {
contents.children = contents.children.map(child => {
child.attributes.key = generateHashedKey(child);
return child;
});
}
return { name, contents };
})
.reduce((icons, icon) => {

View File

@@ -0,0 +1,11 @@
export default ({ componentName, children }) => `
import defaultAttributes from '../defaultAttributes';
const ${componentName} = [
'svg',
defaultAttributes,
${JSON.stringify(children)}
];
export default ${componentName};
`;