feature: vor und nachteile

This commit is contained in:
Hikyu
2026-05-31 13:54:31 +02:00
parent 552a947a1c
commit e3dad17446
23270 changed files with 3024794 additions and 200 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-PRESENT Anthony Fu<https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because it is too large Load Diff
+437
View File
@@ -0,0 +1,437 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _chunkORVFCRDGcjs = require('./chunk-ORVFCRDG.cjs');
// src/index.ts
var _unplugin = require('unplugin');
// src/core/loader.ts
var _nodeloader = require('@iconify/utils/lib/loader/node-loader');
// src/core/compilers/astro.ts
var AstroCompiler = (svg) => {
const svgWithProps = svg.replace("<svg", "<svg {...props}");
return `---
interface Props extends astroHTML.JSX.SVGAttributes {};
const props = Astro.props;
---
${svgWithProps}`;
};
// src/core/compilers/jsx.ts
var _strings = require('@iconify/utils/lib/misc/strings');
var _localpkg = require('local-pkg');
var JSXCompiler = async (svg, collection, icon, options) => {
var _a;
const svgrCore = await _localpkg.importModule.call(void 0, "@svgr/core");
const svgr = svgrCore.transform || (svgrCore.default ? (_a = svgrCore.default.transform) != null ? _a : svgrCore.default : svgrCore.default) || svgrCore;
let res = await svgr(
svg,
{
plugins: ["@svgr/plugin-jsx"],
ref: options.jsx === "react"
},
{ componentName: _strings.camelize.call(void 0, `${collection}-${icon}`) }
);
if (options.jsx !== "react")
res = res.replace('import * as React from "react";', "");
return res;
};
// src/core/compilers/marko.ts
var MarkoCompiler = (svg) => {
const openTagEnd = svg.indexOf(">", svg.indexOf("<svg "));
const closeTagStart = svg.lastIndexOf("</svg");
const openTag = `${svg.slice(0, openTagEnd)} ...input>`;
const content = `$!{\`${escapeTemplateLiteral(svg.slice(openTagEnd + 1, closeTagStart))}\`}`;
const closeTag = svg.slice(closeTagStart);
return `${openTag}${content}${closeTag}`;
};
function escapeTemplateLiteral(str) {
return str.replace(/\\.|[$`]/g, (m) => {
switch (m) {
case "$":
return "&#36";
case "`":
return "&#96;";
default:
return m;
}
});
}
// src/core/compilers/none.ts
var NoneCompiler = (svg) => {
return svg;
};
// src/core/compilers/qwik.ts
var QwikCompiler = async (svg, collection, icon, options) => {
const defaultOptions = {
importSource: "@builder.io/qwik",
runtime: "automatic",
componentName: _strings.camelize.call(void 0, `${collection}-${icon}`)
};
const mergedOptions = Object.assign({}, defaultOptions, options);
const svgx = await _localpkg.importModule.call(void 0, "@svgx/core");
const toJsxComponent = svgx.toJsxComponent;
const res = toJsxComponent(svg, _chunkORVFCRDGcjs.__spreadProps.call(void 0, _chunkORVFCRDGcjs.__spreadValues.call(void 0, {}, mergedOptions), {
defaultExport: true
}));
return res;
};
// src/core/compilers/raw.ts
var RawCompiler = (svg) => {
return `export default ${JSON.stringify(svg)}`;
};
// src/core/compilers/solid.ts
var SolidCompiler = (svg) => {
const svgWithProps = svg.replace(/([{}])/g, "{'$1'}").replace(new RegExp("(?<=<svg[\\s\\S]*?)(>)", "i"), "{...props}>");
return `export default (props = {}) => ${svgWithProps}`;
};
// src/core/compilers/svelte.ts
var svelteRunes;
var SvelteCompiler = async (svg) => {
if (svelteRunes == null) {
try {
const { VERSION } = await Promise.resolve().then(() => _interopRequireWildcard(require("svelte/compiler")));
svelteRunes = Number(VERSION.split(".")[0]) >= 5;
} catch (e) {
svelteRunes = false;
}
}
const openTagEnd = svg.indexOf(">", svg.indexOf("<svg "));
const closeTagStart = svg.lastIndexOf("</svg");
let sfc = `${svg.slice(0, openTagEnd)} {...${svelteRunes ? "p" : "$$props"}}>`;
if (svelteRunes)
sfc += svg.slice(openTagEnd + 1, closeTagStart);
else
sfc += `{@html \`${escapeSvelte(svg.slice(openTagEnd + 1, closeTagStart))}\`}`;
sfc += svg.slice(closeTagStart);
return svelteRunes ? `<script>const{...p}=$props()</script>${sfc}` : sfc;
};
function escapeSvelte(str) {
return str.replace(/\{/g, "&#123;").replace(/\}/g, "&#125;").replace(/`/g, "&#96;").replace(/\\([trn])/g, " ");
}
// src/core/compilers/vue2.ts
// src/core/svgId.ts
var randIdFn = "const __randId = () => Math.random().toString(36).substr(2, 10);";
function handleSVGId(svg) {
const hasID = /="url\(#/.test(svg);
const idMap = {};
let injectScripts = "";
if (hasID) {
svg = svg.replace(/\b([\w-]+)="url\(#(.+?)\)"/g, (_, s, id) => {
idMap[id] = `'${id}':'uicons-'+__randId()`;
return `:${s}="'url(#'+idMap['${id}']+')'"`;
}).replace(/\bid="(.+?)"/g, (full, id) => {
if (idMap[id])
return `:id="idMap['${id}']"`;
return full;
});
injectScripts = `${randIdFn}const idMap = {${Object.values(idMap).join(",")}};`;
}
return {
hasID,
svg,
injectScripts
};
}
// src/core/compilers/vue2.ts
var Vue2Compiler = async (svg, collection, icon) => {
const { compile } = await _localpkg.importModule.call(void 0, "vue-template-compiler");
const transpileMod = await _localpkg.importModule.call(void 0, "vue-template-es2015-compiler");
const transpile = transpileMod.default || transpileMod;
const { injectScripts, svg: handled } = handleSVGId(svg);
const { render } = compile(handled);
const toFunction = (code2) => {
return `function () {${code2}}`;
};
let code = transpile(`var __render__ = ${toFunction(render)}
`, {});
code = code.replace(/\s__(render|staticRenderFns)__\s/g, " $1 ");
code += `
/* vite-plugin-components disabled */
export default {
render: render,
${injectScripts ? `data() {${injectScripts};return { idMap }},` : ""}
name: '${collection}-${icon}',
}
`;
return code;
};
// src/core/compilers/vue3.ts
var Vue3Compiler = async (svg, collection, icon) => {
const { compileTemplate } = await _localpkg.importModule.call(void 0, "@vue/compiler-sfc");
const { injectScripts, svg: handled } = handleSVGId(svg);
let { code } = compileTemplate({
source: handled,
id: `${collection}:${icon}`,
filename: `${collection}-${icon}.vue`
});
code = `import { markRaw } from 'vue'
${code}`;
code = code.replace(/^export /gm, "");
code += `
export default markRaw({ name: '${collection}-${icon}', render${injectScripts ? `, setup() {${injectScripts};return { idMap }}` : ""} })`;
code += "\n/* vite-plugin-components disabled */";
return code;
};
// src/core/compilers/web-components.ts
var WebComponentsCompiler = (svg, collection, icon, { webComponents: options }) => {
let id = `${collection}-${icon}`;
if (options.iconPrefix)
id = `${options.iconPrefix}-${id}`;
const name = _strings.camelize.call(void 0, id);
let code = `export default class ${name} extends HTMLElement {`;
if (options.shadow) {
code += `constructor() {
super()
this.attachShadow({ mode: 'open' }).innerHTML = ${JSON.stringify(svg)}
}`;
} else {
code += `connectedCallback() { this.innerHTML = ${JSON.stringify(svg)} }`;
}
code += "}";
if (options.autoDefine)
code += `
customElements.define('${id}', ${name})`;
return code;
};
// src/core/compilers/index.ts
var compilers = {
"astro": AstroCompiler,
"jsx": JSXCompiler,
"marko": MarkoCompiler,
"none": NoneCompiler,
"raw": RawCompiler,
"solid": SolidCompiler,
"svelte": SvelteCompiler,
"vue2": Vue2Compiler,
"vue3": Vue3Compiler,
"web-components": WebComponentsCompiler,
"qwik": QwikCompiler
};
// src/core/loader.ts
var URL_PREFIXES = ["/~icons/", "~icons/", "virtual:icons/", "virtual/icons/"];
var iconPathRE = new RegExp(`${URL_PREFIXES.map((v) => `^${v}`).join("|")}`);
function isIconPath(path) {
return iconPathRE.test(path);
}
function normalizeIconPath(path) {
return path.replace(iconPathRE, URL_PREFIXES[0]);
}
function resolveIconsPath(path) {
if (!isIconPath(path))
return null;
path = path.replace(iconPathRE, "");
const query = {};
const queryIndex = path.indexOf("?");
if (queryIndex !== -1) {
const queryRaw = path.slice(queryIndex + 1);
path = path.slice(0, queryIndex);
new URLSearchParams(queryRaw).forEach((value, key) => {
if (key === "raw")
query.raw = value === "" || value === "true" ? "true" : "false";
else
query[key] = value;
});
}
path = path.replace(/\.\w+$/, "");
const [collection, icon] = path.split("/");
return {
collection,
icon,
query
};
}
async function generateComponent({ collection, icon, query }, options) {
const warn = `${collection}/${icon}`;
const {
scale,
defaultStyle,
defaultClass,
customCollections,
iconCustomizer: providedIconCustomizer,
transform,
autoInstall = false,
collectionsNodeResolvePath
} = options;
const iconifyLoaderOptions = {
addXmlNs: false,
scale,
customCollections,
autoInstall,
defaultClass,
defaultStyle,
cwd: collectionsNodeResolvePath,
// there is no need to warn since we throw an error below
warn: void 0,
customizations: {
transform,
async iconCustomizer(collection2, icon2, props) {
await (providedIconCustomizer == null ? void 0 : providedIconCustomizer(collection2, icon2, props));
Object.keys(query).forEach((p) => {
const v = query[p];
if (p !== "raw" && v !== void 0 && v !== null)
props[p] = v;
});
}
}
};
const svg = await _nodeloader.loadNodeIcon.call(void 0, collection, icon, iconifyLoaderOptions);
if (!svg)
throw new Error(`Icon \`${warn}\` not found`);
const _compiler = query.raw === "true" ? "raw" : options.compiler;
if (_compiler) {
const compiler = typeof _compiler === "string" ? compilers[_compiler] : await _compiler.compiler;
if (compiler)
return compiler(svg, collection, icon, options);
}
throw new Error(`Unknown compiler: ${_compiler}`);
}
async function generateComponentFromPath(path, options) {
const resolved = resolveIconsPath(path);
if (!resolved)
return null;
return generateComponent(resolved, options);
}
// src/core/options.ts
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
var debug = _debug2.default.call(void 0, "unplugin-icons:options");
async function resolveOptions(options) {
const {
scale = 1.2,
defaultStyle = "",
defaultClass = "",
compiler = await guessCompiler(),
jsx = guessJSX(),
customCollections = {},
iconCustomizer = () => {
},
transform,
autoInstall = false,
collectionsNodeResolvePath = _process2.default.cwd()
} = options;
const webComponents = Object.assign({
autoDefine: false,
iconPrefix: "icon"
}, options.webComponents);
debug("compiler", compiler);
return {
scale,
defaultStyle,
defaultClass,
customCollections,
iconCustomizer,
compiler,
jsx,
webComponents,
transform,
autoInstall,
collectionsNodeResolvePath
};
}
async function guessCompiler() {
return await getVueVersion() || (_localpkg.isPackageExists.call(void 0, "@svgr/core") ? "jsx" : "vue3");
}
function guessJSX() {
if (_localpkg.isPackageExists.call(void 0, "preact"))
return "preact";
return "react";
}
async function getVueVersion() {
var _a;
try {
const result = await _localpkg.getPackageInfo.call(void 0, "vue");
if (!result || !result.version)
return null;
return ((_a = result.version) == null ? void 0 : _a.startsWith("2.")) ? "vue2" : "vue3";
} catch (e) {
return null;
}
}
// src/index.ts
var unplugin = _unplugin.createUnplugin.call(void 0, (options = {}) => {
const resolved = resolveOptions(options);
return {
name: "unplugin-icons",
enforce: "pre",
resolveId(id) {
var _a;
if (isIconPath(id)) {
const normalizedId = normalizeIconPath(id);
const queryIndex = normalizedId.indexOf("?");
const res = `${(queryIndex > -1 ? normalizedId.slice(0, queryIndex) : normalizedId).replace(/\.\w+$/, "").replace(/^\//, "")}${queryIndex > -1 ? `?${normalizedId.slice(queryIndex + 1)}` : ""}`;
const resolved2 = resolveIconsPath(res);
const compiler = ((_a = resolved2 == null ? void 0 : resolved2.query) == null ? void 0 : _a.raw) === "true" ? "raw" : options.compiler;
if (compiler && typeof compiler !== "string") {
const ext = compiler.extension;
if (ext)
return `${res}.${ext.startsWith(".") ? ext.slice(1) : ext}`;
} else {
switch (compiler) {
case "astro":
return `${res}.astro`;
case "jsx":
return `${res}.jsx`;
case "qwik":
return `${res}.jsx`;
case "marko":
return `${res}.marko`;
case "svelte":
return `${res}.svelte`;
case "solid":
return `${res}.tsx`;
}
}
return res;
}
return null;
},
loadInclude(id) {
return isIconPath(id);
},
async load(id) {
const config = await resolved;
const code = await generateComponentFromPath(id, config) || null;
if (code) {
return {
code,
map: { version: 3, mappings: "", sources: [] }
};
}
},
rollup: {
api: {
config: options
}
}
};
});
var src_default = unplugin;
exports.src_default = src_default;
View File
+437
View File
@@ -0,0 +1,437 @@
import {
__spreadProps,
__spreadValues
} from "./chunk-N3ETBM74.js";
// src/index.ts
import { createUnplugin } from "unplugin";
// src/core/loader.ts
import { loadNodeIcon } from "@iconify/utils/lib/loader/node-loader";
// src/core/compilers/astro.ts
var AstroCompiler = (svg) => {
const svgWithProps = svg.replace("<svg", "<svg {...props}");
return `---
interface Props extends astroHTML.JSX.SVGAttributes {};
const props = Astro.props;
---
${svgWithProps}`;
};
// src/core/compilers/jsx.ts
import { camelize } from "@iconify/utils/lib/misc/strings";
import { importModule } from "local-pkg";
var JSXCompiler = async (svg, collection, icon, options) => {
var _a;
const svgrCore = await importModule("@svgr/core");
const svgr = svgrCore.transform || (svgrCore.default ? (_a = svgrCore.default.transform) != null ? _a : svgrCore.default : svgrCore.default) || svgrCore;
let res = await svgr(
svg,
{
plugins: ["@svgr/plugin-jsx"],
ref: options.jsx === "react"
},
{ componentName: camelize(`${collection}-${icon}`) }
);
if (options.jsx !== "react")
res = res.replace('import * as React from "react";', "");
return res;
};
// src/core/compilers/marko.ts
var MarkoCompiler = (svg) => {
const openTagEnd = svg.indexOf(">", svg.indexOf("<svg "));
const closeTagStart = svg.lastIndexOf("</svg");
const openTag = `${svg.slice(0, openTagEnd)} ...input>`;
const content = `$!{\`${escapeTemplateLiteral(svg.slice(openTagEnd + 1, closeTagStart))}\`}`;
const closeTag = svg.slice(closeTagStart);
return `${openTag}${content}${closeTag}`;
};
function escapeTemplateLiteral(str) {
return str.replace(/\\.|[$`]/g, (m) => {
switch (m) {
case "$":
return "&#36";
case "`":
return "&#96;";
default:
return m;
}
});
}
// src/core/compilers/none.ts
var NoneCompiler = (svg) => {
return svg;
};
// src/core/compilers/qwik.ts
import { camelize as camelize2 } from "@iconify/utils/lib/misc/strings";
import { importModule as importModule2 } from "local-pkg";
var QwikCompiler = async (svg, collection, icon, options) => {
const defaultOptions = {
importSource: "@builder.io/qwik",
runtime: "automatic",
componentName: camelize2(`${collection}-${icon}`)
};
const mergedOptions = Object.assign({}, defaultOptions, options);
const svgx = await importModule2("@svgx/core");
const toJsxComponent = svgx.toJsxComponent;
const res = toJsxComponent(svg, __spreadProps(__spreadValues({}, mergedOptions), {
defaultExport: true
}));
return res;
};
// src/core/compilers/raw.ts
var RawCompiler = (svg) => {
return `export default ${JSON.stringify(svg)}`;
};
// src/core/compilers/solid.ts
var SolidCompiler = (svg) => {
const svgWithProps = svg.replace(/([{}])/g, "{'$1'}").replace(new RegExp("(?<=<svg[\\s\\S]*?)(>)", "i"), "{...props}>");
return `export default (props = {}) => ${svgWithProps}`;
};
// src/core/compilers/svelte.ts
var svelteRunes;
var SvelteCompiler = async (svg) => {
if (svelteRunes == null) {
try {
const { VERSION } = await import("svelte/compiler");
svelteRunes = Number(VERSION.split(".")[0]) >= 5;
} catch (e) {
svelteRunes = false;
}
}
const openTagEnd = svg.indexOf(">", svg.indexOf("<svg "));
const closeTagStart = svg.lastIndexOf("</svg");
let sfc = `${svg.slice(0, openTagEnd)} {...${svelteRunes ? "p" : "$$props"}}>`;
if (svelteRunes)
sfc += svg.slice(openTagEnd + 1, closeTagStart);
else
sfc += `{@html \`${escapeSvelte(svg.slice(openTagEnd + 1, closeTagStart))}\`}`;
sfc += svg.slice(closeTagStart);
return svelteRunes ? `<script>const{...p}=$props()</script>${sfc}` : sfc;
};
function escapeSvelte(str) {
return str.replace(/\{/g, "&#123;").replace(/\}/g, "&#125;").replace(/`/g, "&#96;").replace(/\\([trn])/g, " ");
}
// src/core/compilers/vue2.ts
import { importModule as importModule3 } from "local-pkg";
// src/core/svgId.ts
var randIdFn = "const __randId = () => Math.random().toString(36).substr(2, 10);";
function handleSVGId(svg) {
const hasID = /="url\(#/.test(svg);
const idMap = {};
let injectScripts = "";
if (hasID) {
svg = svg.replace(/\b([\w-]+)="url\(#(.+?)\)"/g, (_, s, id) => {
idMap[id] = `'${id}':'uicons-'+__randId()`;
return `:${s}="'url(#'+idMap['${id}']+')'"`;
}).replace(/\bid="(.+?)"/g, (full, id) => {
if (idMap[id])
return `:id="idMap['${id}']"`;
return full;
});
injectScripts = `${randIdFn}const idMap = {${Object.values(idMap).join(",")}};`;
}
return {
hasID,
svg,
injectScripts
};
}
// src/core/compilers/vue2.ts
var Vue2Compiler = async (svg, collection, icon) => {
const { compile } = await importModule3("vue-template-compiler");
const transpileMod = await importModule3("vue-template-es2015-compiler");
const transpile = transpileMod.default || transpileMod;
const { injectScripts, svg: handled } = handleSVGId(svg);
const { render } = compile(handled);
const toFunction = (code2) => {
return `function () {${code2}}`;
};
let code = transpile(`var __render__ = ${toFunction(render)}
`, {});
code = code.replace(/\s__(render|staticRenderFns)__\s/g, " $1 ");
code += `
/* vite-plugin-components disabled */
export default {
render: render,
${injectScripts ? `data() {${injectScripts};return { idMap }},` : ""}
name: '${collection}-${icon}',
}
`;
return code;
};
// src/core/compilers/vue3.ts
import { importModule as importModule4 } from "local-pkg";
var Vue3Compiler = async (svg, collection, icon) => {
const { compileTemplate } = await importModule4("@vue/compiler-sfc");
const { injectScripts, svg: handled } = handleSVGId(svg);
let { code } = compileTemplate({
source: handled,
id: `${collection}:${icon}`,
filename: `${collection}-${icon}.vue`
});
code = `import { markRaw } from 'vue'
${code}`;
code = code.replace(/^export /gm, "");
code += `
export default markRaw({ name: '${collection}-${icon}', render${injectScripts ? `, setup() {${injectScripts};return { idMap }}` : ""} })`;
code += "\n/* vite-plugin-components disabled */";
return code;
};
// src/core/compilers/web-components.ts
import { camelize as camelize3 } from "@iconify/utils/lib/misc/strings";
var WebComponentsCompiler = (svg, collection, icon, { webComponents: options }) => {
let id = `${collection}-${icon}`;
if (options.iconPrefix)
id = `${options.iconPrefix}-${id}`;
const name = camelize3(id);
let code = `export default class ${name} extends HTMLElement {`;
if (options.shadow) {
code += `constructor() {
super()
this.attachShadow({ mode: 'open' }).innerHTML = ${JSON.stringify(svg)}
}`;
} else {
code += `connectedCallback() { this.innerHTML = ${JSON.stringify(svg)} }`;
}
code += "}";
if (options.autoDefine)
code += `
customElements.define('${id}', ${name})`;
return code;
};
// src/core/compilers/index.ts
var compilers = {
"astro": AstroCompiler,
"jsx": JSXCompiler,
"marko": MarkoCompiler,
"none": NoneCompiler,
"raw": RawCompiler,
"solid": SolidCompiler,
"svelte": SvelteCompiler,
"vue2": Vue2Compiler,
"vue3": Vue3Compiler,
"web-components": WebComponentsCompiler,
"qwik": QwikCompiler
};
// src/core/loader.ts
var URL_PREFIXES = ["/~icons/", "~icons/", "virtual:icons/", "virtual/icons/"];
var iconPathRE = new RegExp(`${URL_PREFIXES.map((v) => `^${v}`).join("|")}`);
function isIconPath(path) {
return iconPathRE.test(path);
}
function normalizeIconPath(path) {
return path.replace(iconPathRE, URL_PREFIXES[0]);
}
function resolveIconsPath(path) {
if (!isIconPath(path))
return null;
path = path.replace(iconPathRE, "");
const query = {};
const queryIndex = path.indexOf("?");
if (queryIndex !== -1) {
const queryRaw = path.slice(queryIndex + 1);
path = path.slice(0, queryIndex);
new URLSearchParams(queryRaw).forEach((value, key) => {
if (key === "raw")
query.raw = value === "" || value === "true" ? "true" : "false";
else
query[key] = value;
});
}
path = path.replace(/\.\w+$/, "");
const [collection, icon] = path.split("/");
return {
collection,
icon,
query
};
}
async function generateComponent({ collection, icon, query }, options) {
const warn = `${collection}/${icon}`;
const {
scale,
defaultStyle,
defaultClass,
customCollections,
iconCustomizer: providedIconCustomizer,
transform,
autoInstall = false,
collectionsNodeResolvePath
} = options;
const iconifyLoaderOptions = {
addXmlNs: false,
scale,
customCollections,
autoInstall,
defaultClass,
defaultStyle,
cwd: collectionsNodeResolvePath,
// there is no need to warn since we throw an error below
warn: void 0,
customizations: {
transform,
async iconCustomizer(collection2, icon2, props) {
await (providedIconCustomizer == null ? void 0 : providedIconCustomizer(collection2, icon2, props));
Object.keys(query).forEach((p) => {
const v = query[p];
if (p !== "raw" && v !== void 0 && v !== null)
props[p] = v;
});
}
}
};
const svg = await loadNodeIcon(collection, icon, iconifyLoaderOptions);
if (!svg)
throw new Error(`Icon \`${warn}\` not found`);
const _compiler = query.raw === "true" ? "raw" : options.compiler;
if (_compiler) {
const compiler = typeof _compiler === "string" ? compilers[_compiler] : await _compiler.compiler;
if (compiler)
return compiler(svg, collection, icon, options);
}
throw new Error(`Unknown compiler: ${_compiler}`);
}
async function generateComponentFromPath(path, options) {
const resolved = resolveIconsPath(path);
if (!resolved)
return null;
return generateComponent(resolved, options);
}
// src/core/options.ts
import process from "node:process";
import createDebugger from "debug";
import { getPackageInfo, isPackageExists } from "local-pkg";
var debug = createDebugger("unplugin-icons:options");
async function resolveOptions(options) {
const {
scale = 1.2,
defaultStyle = "",
defaultClass = "",
compiler = await guessCompiler(),
jsx = guessJSX(),
customCollections = {},
iconCustomizer = () => {
},
transform,
autoInstall = false,
collectionsNodeResolvePath = process.cwd()
} = options;
const webComponents = Object.assign({
autoDefine: false,
iconPrefix: "icon"
}, options.webComponents);
debug("compiler", compiler);
return {
scale,
defaultStyle,
defaultClass,
customCollections,
iconCustomizer,
compiler,
jsx,
webComponents,
transform,
autoInstall,
collectionsNodeResolvePath
};
}
async function guessCompiler() {
return await getVueVersion() || (isPackageExists("@svgr/core") ? "jsx" : "vue3");
}
function guessJSX() {
if (isPackageExists("preact"))
return "preact";
return "react";
}
async function getVueVersion() {
var _a;
try {
const result = await getPackageInfo("vue");
if (!result || !result.version)
return null;
return ((_a = result.version) == null ? void 0 : _a.startsWith("2.")) ? "vue2" : "vue3";
} catch (e) {
return null;
}
}
// src/index.ts
var unplugin = createUnplugin((options = {}) => {
const resolved = resolveOptions(options);
return {
name: "unplugin-icons",
enforce: "pre",
resolveId(id) {
var _a;
if (isIconPath(id)) {
const normalizedId = normalizeIconPath(id);
const queryIndex = normalizedId.indexOf("?");
const res = `${(queryIndex > -1 ? normalizedId.slice(0, queryIndex) : normalizedId).replace(/\.\w+$/, "").replace(/^\//, "")}${queryIndex > -1 ? `?${normalizedId.slice(queryIndex + 1)}` : ""}`;
const resolved2 = resolveIconsPath(res);
const compiler = ((_a = resolved2 == null ? void 0 : resolved2.query) == null ? void 0 : _a.raw) === "true" ? "raw" : options.compiler;
if (compiler && typeof compiler !== "string") {
const ext = compiler.extension;
if (ext)
return `${res}.${ext.startsWith(".") ? ext.slice(1) : ext}`;
} else {
switch (compiler) {
case "astro":
return `${res}.astro`;
case "jsx":
return `${res}.jsx`;
case "qwik":
return `${res}.jsx`;
case "marko":
return `${res}.marko`;
case "svelte":
return `${res}.svelte`;
case "solid":
return `${res}.tsx`;
}
}
return res;
}
return null;
},
loadInclude(id) {
return isIconPath(id);
},
async load(id) {
const config = await resolved;
const code = await generateComponentFromPath(id, config) || null;
if (code) {
return {
code,
map: { version: 3, mappings: "", sources: [] }
};
}
},
rollup: {
api: {
config: options
}
}
};
});
var src_default = unplugin;
export {
src_default
};
+24
View File
@@ -0,0 +1,24 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
export {
__spreadValues,
__spreadProps
};
+24
View File
@@ -0,0 +1,24 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
exports.__spreadValues = __spreadValues; exports.__spreadProps = __spreadProps;
+1
View File
@@ -0,0 +1 @@
"use strict";
+11
View File
@@ -0,0 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/esbuild.ts
var esbuild_default = _chunk2ZA4SHTDcjs.src_default.esbuild;
exports.default = esbuild_default;
+7
View File
@@ -0,0 +1,7 @@
import * as unplugin from 'unplugin';
import { Options } from './types.cjs';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => unplugin.EsbuildPlugin;
export { _default as default };
+7
View File
@@ -0,0 +1,7 @@
import * as unplugin from 'unplugin';
import { Options } from './types.js';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => unplugin.EsbuildPlugin;
export { _default as default };
+11
View File
@@ -0,0 +1,11 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
// src/esbuild.ts
var esbuild_default = src_default.esbuild;
export {
esbuild_default as default
};
+8
View File
@@ -0,0 +1,8 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
exports.default = _chunk2ZA4SHTDcjs.src_default;
+8
View File
@@ -0,0 +1,8 @@
import * as unplugin$1 from 'unplugin';
import { Options } from './types.cjs';
export { CustomCompiler, CustomIconLoader, IconCustomizer, InlineCollection, ResolvedOptions } from './types.cjs';
import '@antfu/utils';
declare const unplugin: unplugin$1.UnpluginInstance<Options | undefined, boolean>;
export { Options, unplugin as default };
+8
View File
@@ -0,0 +1,8 @@
import * as unplugin$1 from 'unplugin';
import { Options } from './types.js';
export { CustomCompiler, CustomIconLoader, IconCustomizer, InlineCollection, ResolvedOptions } from './types.js';
import '@antfu/utils';
declare const unplugin: unplugin$1.UnpluginInstance<Options | undefined, boolean>;
export { Options, unplugin as default };
+8
View File
@@ -0,0 +1,8 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
export {
src_default as default
};
+15
View File
@@ -0,0 +1,15 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-ORVFCRDG.cjs');
// src/loaders.ts
var _externalpkg = require('@iconify/utils/lib/loader/external-pkg');
var _nodeloaders = require('@iconify/utils/lib/loader/node-loaders');
function FileSystemIconLoader(dir, transform) {
return _nodeloaders.FileSystemIconLoader.call(void 0, dir, transform);
}
function ExternalPackageIconLoader(packageName, autoInstall) {
return _externalpkg.createExternalPackageIconLoader.call(void 0, packageName, autoInstall);
}
exports.ExternalPackageIconLoader = ExternalPackageIconLoader; exports.FileSystemIconLoader = FileSystemIconLoader;
+8
View File
@@ -0,0 +1,8 @@
import { Awaitable } from '@antfu/utils';
import { ExternalPkgName, AutoInstall } from '@iconify/utils/lib/loader/types';
import { CustomIconLoader } from './types.cjs';
declare function FileSystemIconLoader(dir: string, transform?: (svg: string) => Awaitable<string>): CustomIconLoader;
declare function ExternalPackageIconLoader(packageName: ExternalPkgName, autoInstall?: AutoInstall): Record<string, CustomIconLoader>;
export { ExternalPackageIconLoader, FileSystemIconLoader };
+8
View File
@@ -0,0 +1,8 @@
import { Awaitable } from '@antfu/utils';
import { ExternalPkgName, AutoInstall } from '@iconify/utils/lib/loader/types';
import { CustomIconLoader } from './types.js';
declare function FileSystemIconLoader(dir: string, transform?: (svg: string) => Awaitable<string>): CustomIconLoader;
declare function ExternalPackageIconLoader(packageName: ExternalPkgName, autoInstall?: AutoInstall): Record<string, CustomIconLoader>;
export { ExternalPackageIconLoader, FileSystemIconLoader };
+15
View File
@@ -0,0 +1,15 @@
import "./chunk-N3ETBM74.js";
// src/loaders.ts
import { createExternalPackageIconLoader } from "@iconify/utils/lib/loader/external-pkg";
import { FileSystemIconLoader as IconifyFileSystemIconLoader } from "@iconify/utils/lib/loader/node-loaders";
function FileSystemIconLoader(dir, transform) {
return IconifyFileSystemIconLoader(dir, transform);
}
function ExternalPackageIconLoader(packageName, autoInstall) {
return createExternalPackageIconLoader(packageName, autoInstall);
}
export {
ExternalPackageIconLoader,
FileSystemIconLoader
};
+32
View File
@@ -0,0 +1,32 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/nuxt.ts
function nuxt_default(options = {}, nuxt) {
var _a, _b, _c, _d, _e;
const nuxtApp = (this == null ? void 0 : this.nuxt) || nuxt;
if ((_a = nuxtApp == null ? void 0 : nuxtApp._version) == null ? void 0 : _a.startsWith("3.")) {
options.compiler = "vue3";
(_b = nuxtApp.options).typescript || (_b.typescript = {});
(_c = nuxtApp.options.typescript).tsConfig || (_c.tsConfig = {});
(_d = nuxtApp.options.typescript.tsConfig).compilerOptions || (_d.compilerOptions = {});
(_e = nuxtApp.options.typescript.tsConfig.compilerOptions).types || (_e.types = []);
nuxtApp.options.typescript.tsConfig.compilerOptions.types.push("unplugin-icons/types/vue");
}
nuxtApp.hook("webpack:config", (configs) => {
configs.forEach((config) => {
config.plugins = config.plugins || [];
config.plugins.unshift(_chunk2ZA4SHTDcjs.src_default.webpack(options));
});
});
nuxtApp.hook("vite:extend", async (vite) => {
vite.config.plugins = vite.config.plugins || [];
vite.config.plugins.push(_chunk2ZA4SHTDcjs.src_default.vite(options));
});
}
exports.default = nuxt_default;
+6
View File
@@ -0,0 +1,6 @@
import { Options } from './types.cjs';
import '@antfu/utils';
declare function export_default(this: any, options: Options | undefined, nuxt: any): void;
export { export_default as default };
+6
View File
@@ -0,0 +1,6 @@
import { Options } from './types.js';
import '@antfu/utils';
declare function export_default(this: any, options: Options | undefined, nuxt: any): void;
export { export_default as default };
+32
View File
@@ -0,0 +1,32 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
// src/nuxt.ts
function nuxt_default(options = {}, nuxt) {
var _a, _b, _c, _d, _e;
const nuxtApp = (this == null ? void 0 : this.nuxt) || nuxt;
if ((_a = nuxtApp == null ? void 0 : nuxtApp._version) == null ? void 0 : _a.startsWith("3.")) {
options.compiler = "vue3";
(_b = nuxtApp.options).typescript || (_b.typescript = {});
(_c = nuxtApp.options.typescript).tsConfig || (_c.tsConfig = {});
(_d = nuxtApp.options.typescript.tsConfig).compilerOptions || (_d.compilerOptions = {});
(_e = nuxtApp.options.typescript.tsConfig.compilerOptions).types || (_e.types = []);
nuxtApp.options.typescript.tsConfig.compilerOptions.types.push("unplugin-icons/types/vue");
}
nuxtApp.hook("webpack:config", (configs) => {
configs.forEach((config) => {
config.plugins = config.plugins || [];
config.plugins.unshift(src_default.webpack(options));
});
});
nuxtApp.hook("vite:extend", async (vite) => {
vite.config.plugins = vite.config.plugins || [];
vite.config.plugins.push(src_default.vite(options));
});
}
export {
nuxt_default as default
};
+255
View File
@@ -0,0 +1,255 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-ORVFCRDG.cjs');
// src/resolver.ts
var _utils = require('@antfu/utils');
var _strings = require('@iconify/utils/lib/misc/strings');
// src/core/icon-sets.json
var icon_sets_default = [
"academicons",
"akar-icons",
"ant-design",
"arcticons",
"basil",
"bi",
"bitcoin-icons",
"bpmn",
"brandico",
"bx",
"bxl",
"bxs",
"bytesize",
"carbon",
"catppuccin",
"cbi",
"charm",
"ci",
"cib",
"cif",
"cil",
"circle-flags",
"circum",
"clarity",
"codicon",
"covid",
"cryptocurrency",
"cryptocurrency-color",
"cuida",
"dashicons",
"devicon",
"devicon-plain",
"duo-icons",
"ei",
"el",
"emojione",
"emojione-monotone",
"emojione-v1",
"entypo",
"entypo-social",
"eos-icons",
"ep",
"et",
"eva",
"f7",
"fa",
"fa-brands",
"fa-regular",
"fa-solid",
"fa6-brands",
"fa6-regular",
"fa6-solid",
"fad",
"fe",
"feather",
"file-icons",
"flag",
"flagpack",
"flat-color-icons",
"flat-ui",
"flowbite",
"fluent",
"fluent-color",
"fluent-emoji",
"fluent-emoji-flat",
"fluent-emoji-high-contrast",
"fluent-mdl2",
"fontelico",
"fontisto",
"formkit",
"foundation",
"fxemoji",
"gala",
"game-icons",
"geo",
"gg",
"gis",
"gravity-ui",
"gridicons",
"grommet-icons",
"guidance",
"healthicons",
"heroicons",
"heroicons-outline",
"heroicons-solid",
"hugeicons",
"humbleicons",
"ic",
"icomoon-free",
"icon-park",
"icon-park-outline",
"icon-park-solid",
"icon-park-twotone",
"iconamoon",
"iconoir",
"icons8",
"il",
"ion",
"iwwa",
"ix",
"jam",
"la",
"lets-icons",
"line-md",
"lineicons",
"logos",
"ls",
"lsicon",
"lucide",
"lucide-lab",
"mage",
"majesticons",
"maki",
"map",
"marketeq",
"material-symbols",
"material-symbols-light",
"mdi",
"mdi-light",
"medical-icon",
"memory",
"meteocons",
"meteor-icons",
"mi",
"mingcute",
"mono-icons",
"mynaui",
"nimbus",
"nonicons",
"noto",
"noto-v1",
"nrk",
"octicon",
"oi",
"ooui",
"openmoji",
"oui",
"pajamas",
"pepicons",
"pepicons-pencil",
"pepicons-pop",
"pepicons-print",
"ph",
"pixelarticons",
"prime",
"proicons",
"ps",
"qlementine-icons",
"quill",
"radix-icons",
"raphael",
"ri",
"rivet-icons",
"si",
"si-glyph",
"simple-icons",
"simple-line-icons",
"skill-icons",
"solar",
"stash",
"streamline",
"streamline-emojis",
"subway",
"svg-spinners",
"system-uicons",
"tabler",
"tdesign",
"teenyicons",
"token",
"token-branded",
"topcoat",
"twemoji",
"typcn",
"uil",
"uim",
"uis",
"uit",
"uiw",
"unjs",
"vaadin",
"vs",
"vscode-icons",
"websymbol",
"weui",
"whh",
"wi",
"wpf",
"zmdi",
"zondicons"
];
// src/resolver.ts
function ComponentsResolver(options = {}) {
var _a;
const {
prefix: rawPrefix = (_a = options.componentPrefix) != null ? _a : "i",
enabledCollections = icon_sets_default,
alias = {},
customCollections = [],
extension,
strict = false
} = options;
const prefix = rawPrefix ? `${_strings.camelToKebab.call(void 0, rawPrefix)}-` : "";
const ext = extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
const collections = _utils.uniq.call(void 0, [
..._utils.toArray.call(void 0, enabledCollections),
..._utils.toArray.call(void 0, customCollections),
..._utils.toArray.call(void 0, Object.keys(alias))
]);
collections.sort((a, b) => b.length - a.length);
return (name) => {
let collection;
let icon;
if (name.includes(":")) {
const [iconPrefix, iconSuffix] = name.split(":");
collection = _strings.camelToKebab.call(void 0, iconPrefix);
if (!collection.startsWith(prefix))
return;
const slice = collection.slice(prefix.length);
const resolvedCollection2 = collections.find((i) => slice === i);
if (!resolvedCollection2)
return;
collection = resolvedCollection2;
icon = _strings.camelToKebab.call(void 0, iconSuffix);
} else {
const kebab = _strings.camelToKebab.call(void 0, name);
if (!kebab.startsWith(prefix))
return;
const slice = kebab.slice(prefix.length);
const resolvedCollection2 = collections.find((i) => slice.startsWith(`${i}-`)) || !strict && collections.find((i) => slice.startsWith(i));
if (!resolvedCollection2)
return;
collection = resolvedCollection2;
icon = slice.slice(resolvedCollection2.length);
}
if (icon[0] === "-")
icon = icon.slice(1);
if (!icon)
return;
const resolvedCollection = alias[collection] || collection;
if (collections.includes(resolvedCollection))
return `~icons/${resolvedCollection}/${icon}${ext}`;
};
}
exports.default = ComponentsResolver;
+53
View File
@@ -0,0 +1,53 @@
interface ComponentResolverOption {
/**
* Prefix for resolving components name.
* Set '' to disable prefix.
*
* @default 'i'
*/
prefix?: string | false;
/**
* Iconify collection names to that enable for resolving.
*
* @default [all collections]
*/
enabledCollections?: string | string[];
/**
* Icon collections aliases.
*
* The `aliases` keys are the `alias` and the values are the `name` for the collection.
*
* Instead using `<i-icon-park-abnormal />` we can use `<i-park-abnormal />` configuring:
* `alias: { park: 'icon-park' }`
*/
alias?: Record<string, string>;
/**
* Name for custom collections provide by loaders.
*/
customCollections?: string | string[];
/**
* Extension for the resolved id
* Set `jsx` for JSX components
*
* @default ''
*/
extension?: string;
/**
* @deprecated renamed to `prefix`
*/
componentPrefix?: string;
/**
* For collections strict matching.
* Default is `false`, not side effect.
* Set `true` to enable strict matching with `-` suffix for all collections.
*/
strict?: boolean;
}
/**
* Resolver for unplugin-vue-components and unplugin-auto-import
*
* @param options
*/
declare function ComponentsResolver(options?: ComponentResolverOption): (name: string) => string | undefined;
export { type ComponentResolverOption, ComponentsResolver as default };
+53
View File
@@ -0,0 +1,53 @@
interface ComponentResolverOption {
/**
* Prefix for resolving components name.
* Set '' to disable prefix.
*
* @default 'i'
*/
prefix?: string | false;
/**
* Iconify collection names to that enable for resolving.
*
* @default [all collections]
*/
enabledCollections?: string | string[];
/**
* Icon collections aliases.
*
* The `aliases` keys are the `alias` and the values are the `name` for the collection.
*
* Instead using `<i-icon-park-abnormal />` we can use `<i-park-abnormal />` configuring:
* `alias: { park: 'icon-park' }`
*/
alias?: Record<string, string>;
/**
* Name for custom collections provide by loaders.
*/
customCollections?: string | string[];
/**
* Extension for the resolved id
* Set `jsx` for JSX components
*
* @default ''
*/
extension?: string;
/**
* @deprecated renamed to `prefix`
*/
componentPrefix?: string;
/**
* For collections strict matching.
* Default is `false`, not side effect.
* Set `true` to enable strict matching with `-` suffix for all collections.
*/
strict?: boolean;
}
/**
* Resolver for unplugin-vue-components and unplugin-auto-import
*
* @param options
*/
declare function ComponentsResolver(options?: ComponentResolverOption): (name: string) => string | undefined;
export { type ComponentResolverOption, ComponentsResolver as default };
+255
View File
@@ -0,0 +1,255 @@
import "./chunk-N3ETBM74.js";
// src/resolver.ts
import { toArray, uniq } from "@antfu/utils";
import { camelToKebab } from "@iconify/utils/lib/misc/strings";
// src/core/icon-sets.json
var icon_sets_default = [
"academicons",
"akar-icons",
"ant-design",
"arcticons",
"basil",
"bi",
"bitcoin-icons",
"bpmn",
"brandico",
"bx",
"bxl",
"bxs",
"bytesize",
"carbon",
"catppuccin",
"cbi",
"charm",
"ci",
"cib",
"cif",
"cil",
"circle-flags",
"circum",
"clarity",
"codicon",
"covid",
"cryptocurrency",
"cryptocurrency-color",
"cuida",
"dashicons",
"devicon",
"devicon-plain",
"duo-icons",
"ei",
"el",
"emojione",
"emojione-monotone",
"emojione-v1",
"entypo",
"entypo-social",
"eos-icons",
"ep",
"et",
"eva",
"f7",
"fa",
"fa-brands",
"fa-regular",
"fa-solid",
"fa6-brands",
"fa6-regular",
"fa6-solid",
"fad",
"fe",
"feather",
"file-icons",
"flag",
"flagpack",
"flat-color-icons",
"flat-ui",
"flowbite",
"fluent",
"fluent-color",
"fluent-emoji",
"fluent-emoji-flat",
"fluent-emoji-high-contrast",
"fluent-mdl2",
"fontelico",
"fontisto",
"formkit",
"foundation",
"fxemoji",
"gala",
"game-icons",
"geo",
"gg",
"gis",
"gravity-ui",
"gridicons",
"grommet-icons",
"guidance",
"healthicons",
"heroicons",
"heroicons-outline",
"heroicons-solid",
"hugeicons",
"humbleicons",
"ic",
"icomoon-free",
"icon-park",
"icon-park-outline",
"icon-park-solid",
"icon-park-twotone",
"iconamoon",
"iconoir",
"icons8",
"il",
"ion",
"iwwa",
"ix",
"jam",
"la",
"lets-icons",
"line-md",
"lineicons",
"logos",
"ls",
"lsicon",
"lucide",
"lucide-lab",
"mage",
"majesticons",
"maki",
"map",
"marketeq",
"material-symbols",
"material-symbols-light",
"mdi",
"mdi-light",
"medical-icon",
"memory",
"meteocons",
"meteor-icons",
"mi",
"mingcute",
"mono-icons",
"mynaui",
"nimbus",
"nonicons",
"noto",
"noto-v1",
"nrk",
"octicon",
"oi",
"ooui",
"openmoji",
"oui",
"pajamas",
"pepicons",
"pepicons-pencil",
"pepicons-pop",
"pepicons-print",
"ph",
"pixelarticons",
"prime",
"proicons",
"ps",
"qlementine-icons",
"quill",
"radix-icons",
"raphael",
"ri",
"rivet-icons",
"si",
"si-glyph",
"simple-icons",
"simple-line-icons",
"skill-icons",
"solar",
"stash",
"streamline",
"streamline-emojis",
"subway",
"svg-spinners",
"system-uicons",
"tabler",
"tdesign",
"teenyicons",
"token",
"token-branded",
"topcoat",
"twemoji",
"typcn",
"uil",
"uim",
"uis",
"uit",
"uiw",
"unjs",
"vaadin",
"vs",
"vscode-icons",
"websymbol",
"weui",
"whh",
"wi",
"wpf",
"zmdi",
"zondicons"
];
// src/resolver.ts
function ComponentsResolver(options = {}) {
var _a;
const {
prefix: rawPrefix = (_a = options.componentPrefix) != null ? _a : "i",
enabledCollections = icon_sets_default,
alias = {},
customCollections = [],
extension,
strict = false
} = options;
const prefix = rawPrefix ? `${camelToKebab(rawPrefix)}-` : "";
const ext = extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
const collections = uniq([
...toArray(enabledCollections),
...toArray(customCollections),
...toArray(Object.keys(alias))
]);
collections.sort((a, b) => b.length - a.length);
return (name) => {
let collection;
let icon;
if (name.includes(":")) {
const [iconPrefix, iconSuffix] = name.split(":");
collection = camelToKebab(iconPrefix);
if (!collection.startsWith(prefix))
return;
const slice = collection.slice(prefix.length);
const resolvedCollection2 = collections.find((i) => slice === i);
if (!resolvedCollection2)
return;
collection = resolvedCollection2;
icon = camelToKebab(iconSuffix);
} else {
const kebab = camelToKebab(name);
if (!kebab.startsWith(prefix))
return;
const slice = kebab.slice(prefix.length);
const resolvedCollection2 = collections.find((i) => slice.startsWith(`${i}-`)) || !strict && collections.find((i) => slice.startsWith(i));
if (!resolvedCollection2)
return;
collection = resolvedCollection2;
icon = slice.slice(resolvedCollection2.length);
}
if (icon[0] === "-")
icon = icon.slice(1);
if (!icon)
return;
const resolvedCollection = alias[collection] || collection;
if (collections.includes(resolvedCollection))
return `~icons/${resolvedCollection}/${icon}${ext}`;
};
}
export {
ComponentsResolver as default
};
+11
View File
@@ -0,0 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/rollup.ts
var rollup_default = _chunk2ZA4SHTDcjs.src_default.rollup;
exports.default = rollup_default;
+7
View File
@@ -0,0 +1,7 @@
import * as rollup from 'rollup';
import { Options } from './types.cjs';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => rollup.Plugin<any> | rollup.Plugin<any>[];
export { _default as default };
+7
View File
@@ -0,0 +1,7 @@
import * as rollup from 'rollup';
import { Options } from './types.js';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => rollup.Plugin<any> | rollup.Plugin<any>[];
export { _default as default };
+11
View File
@@ -0,0 +1,11 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
// src/rollup.ts
var rollup_default = src_default.rollup;
export {
rollup_default as default
};
+11
View File
@@ -0,0 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/rspack.ts
var rspack_default = _chunk2ZA4SHTDcjs.src_default.rspack;
exports.default = rspack_default;
+6
View File
@@ -0,0 +1,6 @@
import { Options } from './types.cjs';
import '@antfu/utils';
declare const _default: (options?: Options) => any;
export { _default as default };
+6
View File
@@ -0,0 +1,6 @@
import { Options } from './types.js';
import '@antfu/utils';
declare const _default: (options?: Options) => any;
export { _default as default };
+11
View File
@@ -0,0 +1,11 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
// src/rspack.ts
var rspack_default = src_default.rspack;
export {
rspack_default as default
};
+1
View File
@@ -0,0 +1 @@
"use strict";require('./chunk-ZBPRDZS4.cjs');
+103
View File
@@ -0,0 +1,103 @@
import { Awaitable } from '@antfu/utils';
type Compiler = (svg: string, collection: string, icon: string, options: ResolvedOptions) => string | Promise<string>;
interface CustomCompiler {
compiler: Awaitable<Compiler>;
extension?: string;
}
type CustomIconLoader = (name: string) => Awaitable<string | undefined>;
type IconCustomizer = (collection: string, icon: string, props: Record<string, string>) => Awaitable<void>;
type InlineCollection = Record<string, string | (() => Awaitable<string | undefined>)>;
interface Options {
/**
* Scale of icons against 1em
*
* @default 1.2
*/
scale?: number;
/**
* Style apply to icons by default
*
* @default ''
*/
defaultStyle?: string;
/**
* Class names apply to icons by default
*
* @default ''
*/
defaultClass?: string;
/**
* Loader for custom loaders
*/
customCollections?: Record<string, CustomIconLoader | InlineCollection>;
/**
* Icon customizer
*/
iconCustomizer?: IconCustomizer;
/**
* Current working directory for resolving collections from node_modules
*/
collectionsNodeResolvePath?: string | string[];
/**
* Transform raw `svg`.
*
* **WARNING**: `transform` will be only applied when using `custom` icon collection.
*
* @param svg The loaded `svg`
* @param collection The name of the collection
* @param icon The name of the icon
* @return The transformed `svg`.
*/
transform?: (svg: string, collection: string, icon: string) => Awaitable<string>;
/**
* Auto install icon sources package when the usages is detected
*
* @default false
*/
autoInstall?: boolean;
/**
* Compiler
*
* - none: plain SVG content
* - raw: an ESM module with a default exported string of the SVG HTML
*
* @default (detect automatically, fallback to 'vue3')
*/
compiler?: 'astro' | 'jsx' | 'marko' | 'none' | 'solid' | 'svelte' | 'raw' | 'vue2' | 'vue3' | 'web-components' | 'qwik' | CustomCompiler;
/**
* JSX style, works only when compiler set to `jsx`
*
* @default (detect automatically, fallback to 'react')
*/
jsx?: 'react' | 'preact' | 'qwik';
/**
* Config for Web Components compiler
*/
webComponents?: {
/**
* Call `customElements.define` automatically on module importing
*/
autoDefine?: boolean;
/**
* Prefix for auto defining
*
* @default 'icon'
*/
iconPrefix?: string;
/**
* Use shadow DOM
* @default false
*/
shadow?: boolean;
};
/**
* @deprecated no longer needed
*/
iconSource?: 'legacy' | 'modern' | 'auto';
}
type ResolvedOptions = Omit<Required<Options>, 'iconSource' | 'transform'> & Pick<Options, 'transform'>;
export type { CustomCompiler, CustomIconLoader, IconCustomizer, InlineCollection, Options, ResolvedOptions };
+103
View File
@@ -0,0 +1,103 @@
import { Awaitable } from '@antfu/utils';
type Compiler = (svg: string, collection: string, icon: string, options: ResolvedOptions) => string | Promise<string>;
interface CustomCompiler {
compiler: Awaitable<Compiler>;
extension?: string;
}
type CustomIconLoader = (name: string) => Awaitable<string | undefined>;
type IconCustomizer = (collection: string, icon: string, props: Record<string, string>) => Awaitable<void>;
type InlineCollection = Record<string, string | (() => Awaitable<string | undefined>)>;
interface Options {
/**
* Scale of icons against 1em
*
* @default 1.2
*/
scale?: number;
/**
* Style apply to icons by default
*
* @default ''
*/
defaultStyle?: string;
/**
* Class names apply to icons by default
*
* @default ''
*/
defaultClass?: string;
/**
* Loader for custom loaders
*/
customCollections?: Record<string, CustomIconLoader | InlineCollection>;
/**
* Icon customizer
*/
iconCustomizer?: IconCustomizer;
/**
* Current working directory for resolving collections from node_modules
*/
collectionsNodeResolvePath?: string | string[];
/**
* Transform raw `svg`.
*
* **WARNING**: `transform` will be only applied when using `custom` icon collection.
*
* @param svg The loaded `svg`
* @param collection The name of the collection
* @param icon The name of the icon
* @return The transformed `svg`.
*/
transform?: (svg: string, collection: string, icon: string) => Awaitable<string>;
/**
* Auto install icon sources package when the usages is detected
*
* @default false
*/
autoInstall?: boolean;
/**
* Compiler
*
* - none: plain SVG content
* - raw: an ESM module with a default exported string of the SVG HTML
*
* @default (detect automatically, fallback to 'vue3')
*/
compiler?: 'astro' | 'jsx' | 'marko' | 'none' | 'solid' | 'svelte' | 'raw' | 'vue2' | 'vue3' | 'web-components' | 'qwik' | CustomCompiler;
/**
* JSX style, works only when compiler set to `jsx`
*
* @default (detect automatically, fallback to 'react')
*/
jsx?: 'react' | 'preact' | 'qwik';
/**
* Config for Web Components compiler
*/
webComponents?: {
/**
* Call `customElements.define` automatically on module importing
*/
autoDefine?: boolean;
/**
* Prefix for auto defining
*
* @default 'icon'
*/
iconPrefix?: string;
/**
* Use shadow DOM
* @default false
*/
shadow?: boolean;
};
/**
* @deprecated no longer needed
*/
iconSource?: 'legacy' | 'modern' | 'auto';
}
type ResolvedOptions = Omit<Required<Options>, 'iconSource' | 'transform'> & Pick<Options, 'transform'>;
export type { CustomCompiler, CustomIconLoader, IconCustomizer, InlineCollection, Options, ResolvedOptions };
+1
View File
@@ -0,0 +1 @@
import "./chunk-6F4PWJZI.js";
+11
View File
@@ -0,0 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/vite.ts
var vite_default = _chunk2ZA4SHTDcjs.src_default.vite;
exports.default = vite_default;
+7
View File
@@ -0,0 +1,7 @@
import * as vite from 'vite';
import { Options } from './types.cjs';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => vite.Plugin<any> | vite.Plugin<any>[];
export { _default as default };
+7
View File
@@ -0,0 +1,7 @@
import * as vite from 'vite';
import { Options } from './types.js';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => vite.Plugin<any> | vite.Plugin<any>[];
export { _default as default };
+11
View File
@@ -0,0 +1,11 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
// src/vite.ts
var vite_default = src_default.vite;
export {
vite_default as default
};
+11
View File
@@ -0,0 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk2ZA4SHTDcjs = require('./chunk-2ZA4SHTD.cjs');
require('./chunk-ORVFCRDG.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/webpack.ts
var webpack_default = _chunk2ZA4SHTDcjs.src_default.webpack;
exports.default = webpack_default;
+6
View File
@@ -0,0 +1,6 @@
import { Options } from './types.cjs';
import '@antfu/utils';
declare const _default: (options?: Options) => any;
export { _default as default };
+6
View File
@@ -0,0 +1,6 @@
import { Options } from './types.js';
import '@antfu/utils';
declare const _default: (options?: Options) => any;
export { _default as default };
+11
View File
@@ -0,0 +1,11 @@
import {
src_default
} from "./chunk-F5V4FZDM.js";
import "./chunk-N3ETBM74.js";
import "./chunk-6F4PWJZI.js";
// src/webpack.ts
var webpack_default = src_default.webpack;
export {
webpack_default as default
};
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,27 @@
# install-pkg
[![NPM version](https://img.shields.io/npm/v/@antfu/install-pkg?color=a1b858&label=)](https://www.npmjs.com/package/@antfu/install-pkg)
Install package programmatically. Detect package managers automatically (`npm`, `yarn`, `bun` and `pnpm`).
```bash
npm i @antfu/install-pkg
```
```ts
import { installPackage } from '@antfu/install-pkg'
await installPackage('vite', { silent: true })
```
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu)
@@ -0,0 +1,100 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
detectPackageManager: () => detectPackageManager,
installPackage: () => installPackage
});
module.exports = __toCommonJS(src_exports);
// src/detect.ts
var import_node_process = __toESM(require("process"), 1);
var import_detect = require("package-manager-detector/detect");
async function detectPackageManager(cwd = import_node_process.default.cwd()) {
const result = await (0, import_detect.detect)({
cwd,
onUnknown(packageManager) {
console.warn("[@antfu/install-pkg] Unknown packageManager:", packageManager);
return void 0;
}
});
return result?.agent || null;
}
// src/install.ts
var import_node_fs = require("fs");
var import_node_path = require("path");
var import_node_process2 = __toESM(require("process"), 1);
var import_tinyexec = require("tinyexec");
async function installPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = (typeof options.additionalArgs === "function" ? options.additionalArgs(agent, detectedAgent) : options.additionalArgs) || [];
if (options.preferOffline) {
if (detectedAgent === "yarn@berry")
args.unshift("--cached");
else
args.unshift("--prefer-offline");
}
if (agent === "pnpm" && (0, import_node_fs.existsSync)((0, import_node_path.resolve)(options.cwd ?? import_node_process2.default.cwd(), "pnpm-workspace.yaml"))) {
args.unshift(
"-w",
/**
* Prevent pnpm from removing installed devDeps while `NODE_ENV` is `production`
* @see https://pnpm.io/cli/install#--prod--p
*/
"--prod=false"
);
}
return (0, import_tinyexec.x)(
agent,
[
agent === "yarn" ? "add" : "install",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
detectPackageManager,
installPackage
});
@@ -0,0 +1,18 @@
import { Agent } from 'package-manager-detector';
export { Agent } from 'package-manager-detector';
import * as tinyexec from 'tinyexec';
type PackageManager = 'pnpm' | 'yarn' | 'npm' | 'bun';
declare function detectPackageManager(cwd?: string): Promise<Agent | null>;
interface InstallPackageOptions {
cwd?: string;
dev?: boolean;
silent?: boolean;
packageManager?: string;
preferOffline?: boolean;
additionalArgs?: string[] | ((agent: string, detectedAgent: string) => string[] | undefined);
}
declare function installPackage(names: string | string[], options?: InstallPackageOptions): Promise<tinyexec.Output>;
export { type InstallPackageOptions, type PackageManager, detectPackageManager, installPackage };
@@ -0,0 +1,18 @@
import { Agent } from 'package-manager-detector';
export { Agent } from 'package-manager-detector';
import * as tinyexec from 'tinyexec';
type PackageManager = 'pnpm' | 'yarn' | 'npm' | 'bun';
declare function detectPackageManager(cwd?: string): Promise<Agent | null>;
interface InstallPackageOptions {
cwd?: string;
dev?: boolean;
silent?: boolean;
packageManager?: string;
preferOffline?: boolean;
additionalArgs?: string[] | ((agent: string, detectedAgent: string) => string[] | undefined);
}
declare function installPackage(names: string | string[], options?: InstallPackageOptions): Promise<tinyexec.Output>;
export { type InstallPackageOptions, type PackageManager, detectPackageManager, installPackage };
@@ -0,0 +1,62 @@
// src/detect.ts
import process from "node:process";
import { detect } from "package-manager-detector/detect";
async function detectPackageManager(cwd = process.cwd()) {
const result = await detect({
cwd,
onUnknown(packageManager) {
console.warn("[@antfu/install-pkg] Unknown packageManager:", packageManager);
return void 0;
}
});
return result?.agent || null;
}
// src/install.ts
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import process2 from "node:process";
import { x } from "tinyexec";
async function installPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = (typeof options.additionalArgs === "function" ? options.additionalArgs(agent, detectedAgent) : options.additionalArgs) || [];
if (options.preferOffline) {
if (detectedAgent === "yarn@berry")
args.unshift("--cached");
else
args.unshift("--prefer-offline");
}
if (agent === "pnpm" && existsSync(resolve(options.cwd ?? process2.cwd(), "pnpm-workspace.yaml"))) {
args.unshift(
"-w",
/**
* Prevent pnpm from removing installed devDeps while `NODE_ENV` is `production`
* @see https://pnpm.io/cli/install#--prod--p
*/
"--prod=false"
);
}
return x(
agent,
[
agent === "yarn" ? "add" : "install",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
export {
detectPackageManager,
installPackage
};
@@ -0,0 +1,59 @@
{
"name": "@antfu/install-pkg",
"type": "module",
"version": "0.5.0",
"description": "Install package programmatically.",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/install-pkg#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/install-pkg.git"
},
"bugs": {
"url": "https://github.com/antfu/install-pkg/issues"
},
"keywords": [],
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"dependencies": {
"package-manager-detector": "^0.2.5",
"tinyexec": "^0.3.1"
},
"devDependencies": {
"@antfu/eslint-config": "^3.10.0",
"@antfu/ni": "^0.23.1",
"@types/node": "^22.10.0",
"bumpp": "^9.8.1",
"eslint": "^9.15.0",
"esno": "^4.8.0",
"publint": "^0.2.12",
"tsup": "^8.3.5",
"typescript": "^5.7.2"
},
"scripts": {
"dev": "nr build --watch",
"start": "esno src/index.ts",
"build": "tsup src/index.ts --format cjs,esm --dts --no-splitting",
"release": "bumpp --commit --push --tag && pnpm publish",
"lint": "eslint ."
}
}
@@ -0,0 +1,355 @@
'use strict';
const colors_keywords = require('./keywords.cjs');
function rgb2hsl(rgb) {
const c1 = rgb.r / 255, c2 = rgb.g / 255, c3 = rgb.b / 255, kmin = Math.min(c1, Math.min(c2, c3)), kmax = Math.max(c1, Math.max(c2, c3)), l = (kmax + kmin) / 2;
let s, h, delta;
if (kmax === kmin) {
s = h = 0;
} else {
if (l < 0.5) {
s = (kmax - kmin) / (kmax + kmin);
} else {
s = (kmax - kmin) / (2 - kmax - kmin);
}
delta = kmax - kmin;
if (kmax === c1) {
h = (c2 - c3) / delta;
} else if (kmax === c2) {
h = 2 + (c3 - c1) / delta;
} else {
h = 4 + (c1 - c2) / delta;
}
h = h * 60;
if (h < 0) {
h += 360;
}
}
return {
type: "hsl",
h,
s: s * 100,
l: l * 100,
alpha: rgb.alpha
};
}
function fromFunction(value) {
if (value.slice(-1) !== ")") {
return null;
}
const parts = value.slice(0, value.length - 1).split("(");
if (parts.length !== 2) {
return null;
}
const func = parts[0].trim();
const content = parts[1].trim();
let values;
let alphaStr;
switch (func) {
case "lch":
case "lab": {
const parts2 = content.split("/");
switch (parts2.length) {
case 2:
alphaStr = parts2[1].trim();
break;
case 1:
break;
default:
return null;
}
values = parts2[0].trim().split(/[\s,]+/);
break;
}
case "rgb":
case "rgba":
case "hsl":
case "hsla": {
values = content.trim().split(/[\s,]+/);
if (values.length === 4) {
alphaStr = values.pop().trim();
}
break;
}
default: {
return {
type: "function",
func,
value: content
};
}
}
let alpha = 1;
if (typeof alphaStr === "string") {
alpha = parseFloat(alphaStr);
const index = alphaStr.indexOf("%");
const hasPercentage = index !== -1;
if (isNaN(alpha) || hasPercentage && index !== alphaStr.length - 1) {
return null;
}
if (hasPercentage) {
alpha /= 100;
}
}
if (alpha < 0 || alpha > 1 || values.length !== 3) {
return null;
}
if (alpha === 0) {
return {
type: "transparent"
};
}
const isPercentage = [];
const numbers = [];
for (let i = 0; i < 3; i++) {
const colorStr = values[i];
const index = colorStr.indexOf("%");
const hasPercentage = index !== -1;
if (hasPercentage && index !== colorStr.length - 1) {
return null;
}
const colorNum = parseFloat(colorStr);
if (isNaN(colorNum)) {
return null;
}
isPercentage.push(hasPercentage);
numbers.push(colorNum);
}
switch (func) {
case "rgb":
case "rgba": {
const hasPercengage = isPercentage[0];
if (hasPercengage !== isPercentage[1] || hasPercengage !== isPercentage[2]) {
return null;
}
let r = numbers[0];
let g = numbers[1];
let b = numbers[2];
if (hasPercengage) {
r = r * 255 / 100;
g = g * 255 / 100;
b = b * 255 / 100;
}
return {
type: "rgb",
r,
g,
b,
alpha
};
}
case "hsl":
case "hsla": {
if (isPercentage[0] || !isPercentage[1] || !isPercentage[2]) {
return null;
}
return {
type: "hsl",
h: numbers[0],
s: numbers[1],
l: numbers[2],
alpha
};
}
case "lab":
case "lch": {
if (!isPercentage[0] || isPercentage[1] || isPercentage[2]) {
return null;
}
return func === "lab" ? {
type: "lab",
l: numbers[0],
a: numbers[1],
b: numbers[2],
alpha
} : {
type: "lch",
l: numbers[0],
c: numbers[1],
h: numbers[2],
alpha
};
}
}
return null;
}
function fromHex(value) {
if (value.slice(0, 1) === "#") {
value = value.slice(1);
}
if (!/^[\da-f]+$/i.test(value)) {
return null;
}
let alpha = 1;
const hex = ["", "", ""];
switch (value.length) {
case 4: {
alpha = parseInt(value[3] + value[3], 16) / 255;
}
case 3: {
hex[0] = value[0] + value[0];
hex[1] = value[1] + value[1];
hex[2] = value[2] + value[2];
break;
}
case 8: {
alpha = parseInt(value[6] + value[7], 16) / 255;
}
case 6: {
hex[0] = value[0] + value[1];
hex[1] = value[2] + value[3];
hex[2] = value[4] + value[5];
break;
}
default:
return null;
}
return alpha === 0 ? {
type: "transparent"
} : {
type: "rgb",
r: parseInt(hex[0], 16),
g: parseInt(hex[1], 16),
b: parseInt(hex[2], 16),
alpha
};
}
function stringToColor(value) {
value = value.toLowerCase().trim();
if (colors_keywords.colorKeywords[value]) {
return { ...colors_keywords.colorKeywords[value] };
}
if (value.indexOf("(") !== -1) {
return fromFunction(value);
}
return fromHex(value);
}
function compareColors(color1, color2) {
if (color1.type === color2.type) {
let testKeys = new Set(Object.keys(color1));
switch (color1.type) {
case "hsl": {
if (color1.s === 0) {
testKeys.delete("h");
}
if (color1.l === 0 || color1.l === 100) {
testKeys.delete("h");
testKeys.delete("s");
}
}
case "rgb":
if (color1.alpha === 0) {
testKeys = /* @__PURE__ */ new Set(["a"]);
}
}
const keys = Array.from(testKeys);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (color1[key] !== color2[key]) {
return false;
}
}
return true;
}
const list = [color1, color2].sort((a, b) => a.type.localeCompare(b.type));
const item1 = list[0];
const item2 = list[1];
switch (item1.type) {
case "hsl": {
switch (item2.type) {
case "rgb": {
return compareColors(item1, rgb2hsl(item2));
}
case "transparent":
return item1.alpha === 0;
}
return false;
}
case "rgb": {
switch (item2.type) {
case "transparent":
return item1.alpha === 0;
}
}
}
return false;
}
function colorToHexString(color, canCompact = true) {
if (color.alpha !== 1) {
return null;
}
let result = "";
const attrs = ["r", "g", "b"];
for (let i = 0; i < attrs.length; i++) {
const value = color[attrs[i]];
if (Math.round(value) !== value) {
return null;
}
const hex = value.toString(16);
result += (value < 16 ? "0" : "") + hex;
}
if (result.length !== 6) {
return null;
}
if (canCompact && result[0] === result[1] && result[2] === result[3] && result[4] === result[5]) {
result = result[0] + result[2] + result[4];
}
return "#" + result;
}
function colorToString(color) {
if (color.alpha === 0) {
return "transparent";
}
switch (color.type) {
case "none":
case "transparent":
return color.type;
case "current":
return "currentColor";
case "rgb": {
const hex = colorToHexString(color);
if (hex !== null) {
return hex;
}
const list = [color.r, color.g, color.b];
if (color.alpha !== 1) {
list.push(color.alpha);
}
return "rgb" + (list.length === 4 ? "a(" : "(") + list.join(", ") + ")";
}
case "hsl": {
const list = [
color.h,
color.s.toString() + "%",
color.l.toString() + "%"
];
if (color.alpha !== 1) {
list.push(color.alpha);
}
return "hsl" + (list.length === 4 ? "a(" : "(") + list.join(", ") + ")";
}
case "lab": {
const list = [color.l.toString() + "%", color.a, color.b];
if (color.alpha !== 1) {
list.push("/ " + color.alpha.toString());
}
return "lab(" + list.join(" ") + ")";
}
case "lch": {
const list = [color.l.toString() + "%", color.c, color.h];
if (color.alpha !== 1) {
list.push("/ " + color.alpha.toString());
}
return "lch(" + list.join(" ") + ")";
}
case "function": {
return color.func + "(" + color.value + ")";
}
}
}
exports.colorToHexString = colorToHexString;
exports.colorToString = colorToString;
exports.compareColors = compareColors;
exports.stringToColor = stringToColor;
@@ -0,0 +1,20 @@
import { Color, RGBColor } from './types.cjs';
/**
* String to color
*/
declare function stringToColor(value: string): Color | null;
/**
* Check if colors are identical
*/
declare function compareColors(color1: Color, color2: Color): boolean;
/**
* Color to hex
*/
declare function colorToHexString(color: RGBColor, canCompact?: boolean): string | null;
/**
* Convert color to string
*/
declare function colorToString(color: Color): string;
export { colorToHexString, colorToString, compareColors, stringToColor };
@@ -0,0 +1,20 @@
import { Color, RGBColor } from './types.mjs';
/**
* String to color
*/
declare function stringToColor(value: string): Color | null;
/**
* Check if colors are identical
*/
declare function compareColors(color1: Color, color2: Color): boolean;
/**
* Color to hex
*/
declare function colorToHexString(color: RGBColor, canCompact?: boolean): string | null;
/**
* Convert color to string
*/
declare function colorToString(color: Color): string;
export { colorToHexString, colorToString, compareColors, stringToColor };
@@ -0,0 +1,20 @@
import { Color, RGBColor } from './types.js';
/**
* String to color
*/
declare function stringToColor(value: string): Color | null;
/**
* Check if colors are identical
*/
declare function compareColors(color1: Color, color2: Color): boolean;
/**
* Color to hex
*/
declare function colorToHexString(color: RGBColor, canCompact?: boolean): string | null;
/**
* Convert color to string
*/
declare function colorToString(color: Color): string;
export { colorToHexString, colorToString, compareColors, stringToColor };
@@ -0,0 +1,350 @@
import { colorKeywords } from './keywords.mjs';
function rgb2hsl(rgb) {
const c1 = rgb.r / 255, c2 = rgb.g / 255, c3 = rgb.b / 255, kmin = Math.min(c1, Math.min(c2, c3)), kmax = Math.max(c1, Math.max(c2, c3)), l = (kmax + kmin) / 2;
let s, h, delta;
if (kmax === kmin) {
s = h = 0;
} else {
if (l < 0.5) {
s = (kmax - kmin) / (kmax + kmin);
} else {
s = (kmax - kmin) / (2 - kmax - kmin);
}
delta = kmax - kmin;
if (kmax === c1) {
h = (c2 - c3) / delta;
} else if (kmax === c2) {
h = 2 + (c3 - c1) / delta;
} else {
h = 4 + (c1 - c2) / delta;
}
h = h * 60;
if (h < 0) {
h += 360;
}
}
return {
type: "hsl",
h,
s: s * 100,
l: l * 100,
alpha: rgb.alpha
};
}
function fromFunction(value) {
if (value.slice(-1) !== ")") {
return null;
}
const parts = value.slice(0, value.length - 1).split("(");
if (parts.length !== 2) {
return null;
}
const func = parts[0].trim();
const content = parts[1].trim();
let values;
let alphaStr;
switch (func) {
case "lch":
case "lab": {
const parts2 = content.split("/");
switch (parts2.length) {
case 2:
alphaStr = parts2[1].trim();
break;
case 1:
break;
default:
return null;
}
values = parts2[0].trim().split(/[\s,]+/);
break;
}
case "rgb":
case "rgba":
case "hsl":
case "hsla": {
values = content.trim().split(/[\s,]+/);
if (values.length === 4) {
alphaStr = values.pop().trim();
}
break;
}
default: {
return {
type: "function",
func,
value: content
};
}
}
let alpha = 1;
if (typeof alphaStr === "string") {
alpha = parseFloat(alphaStr);
const index = alphaStr.indexOf("%");
const hasPercentage = index !== -1;
if (isNaN(alpha) || hasPercentage && index !== alphaStr.length - 1) {
return null;
}
if (hasPercentage) {
alpha /= 100;
}
}
if (alpha < 0 || alpha > 1 || values.length !== 3) {
return null;
}
if (alpha === 0) {
return {
type: "transparent"
};
}
const isPercentage = [];
const numbers = [];
for (let i = 0; i < 3; i++) {
const colorStr = values[i];
const index = colorStr.indexOf("%");
const hasPercentage = index !== -1;
if (hasPercentage && index !== colorStr.length - 1) {
return null;
}
const colorNum = parseFloat(colorStr);
if (isNaN(colorNum)) {
return null;
}
isPercentage.push(hasPercentage);
numbers.push(colorNum);
}
switch (func) {
case "rgb":
case "rgba": {
const hasPercengage = isPercentage[0];
if (hasPercengage !== isPercentage[1] || hasPercengage !== isPercentage[2]) {
return null;
}
let r = numbers[0];
let g = numbers[1];
let b = numbers[2];
if (hasPercengage) {
r = r * 255 / 100;
g = g * 255 / 100;
b = b * 255 / 100;
}
return {
type: "rgb",
r,
g,
b,
alpha
};
}
case "hsl":
case "hsla": {
if (isPercentage[0] || !isPercentage[1] || !isPercentage[2]) {
return null;
}
return {
type: "hsl",
h: numbers[0],
s: numbers[1],
l: numbers[2],
alpha
};
}
case "lab":
case "lch": {
if (!isPercentage[0] || isPercentage[1] || isPercentage[2]) {
return null;
}
return func === "lab" ? {
type: "lab",
l: numbers[0],
a: numbers[1],
b: numbers[2],
alpha
} : {
type: "lch",
l: numbers[0],
c: numbers[1],
h: numbers[2],
alpha
};
}
}
return null;
}
function fromHex(value) {
if (value.slice(0, 1) === "#") {
value = value.slice(1);
}
if (!/^[\da-f]+$/i.test(value)) {
return null;
}
let alpha = 1;
const hex = ["", "", ""];
switch (value.length) {
case 4: {
alpha = parseInt(value[3] + value[3], 16) / 255;
}
case 3: {
hex[0] = value[0] + value[0];
hex[1] = value[1] + value[1];
hex[2] = value[2] + value[2];
break;
}
case 8: {
alpha = parseInt(value[6] + value[7], 16) / 255;
}
case 6: {
hex[0] = value[0] + value[1];
hex[1] = value[2] + value[3];
hex[2] = value[4] + value[5];
break;
}
default:
return null;
}
return alpha === 0 ? {
type: "transparent"
} : {
type: "rgb",
r: parseInt(hex[0], 16),
g: parseInt(hex[1], 16),
b: parseInt(hex[2], 16),
alpha
};
}
function stringToColor(value) {
value = value.toLowerCase().trim();
if (colorKeywords[value]) {
return { ...colorKeywords[value] };
}
if (value.indexOf("(") !== -1) {
return fromFunction(value);
}
return fromHex(value);
}
function compareColors(color1, color2) {
if (color1.type === color2.type) {
let testKeys = new Set(Object.keys(color1));
switch (color1.type) {
case "hsl": {
if (color1.s === 0) {
testKeys.delete("h");
}
if (color1.l === 0 || color1.l === 100) {
testKeys.delete("h");
testKeys.delete("s");
}
}
case "rgb":
if (color1.alpha === 0) {
testKeys = /* @__PURE__ */ new Set(["a"]);
}
}
const keys = Array.from(testKeys);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (color1[key] !== color2[key]) {
return false;
}
}
return true;
}
const list = [color1, color2].sort((a, b) => a.type.localeCompare(b.type));
const item1 = list[0];
const item2 = list[1];
switch (item1.type) {
case "hsl": {
switch (item2.type) {
case "rgb": {
return compareColors(item1, rgb2hsl(item2));
}
case "transparent":
return item1.alpha === 0;
}
return false;
}
case "rgb": {
switch (item2.type) {
case "transparent":
return item1.alpha === 0;
}
}
}
return false;
}
function colorToHexString(color, canCompact = true) {
if (color.alpha !== 1) {
return null;
}
let result = "";
const attrs = ["r", "g", "b"];
for (let i = 0; i < attrs.length; i++) {
const value = color[attrs[i]];
if (Math.round(value) !== value) {
return null;
}
const hex = value.toString(16);
result += (value < 16 ? "0" : "") + hex;
}
if (result.length !== 6) {
return null;
}
if (canCompact && result[0] === result[1] && result[2] === result[3] && result[4] === result[5]) {
result = result[0] + result[2] + result[4];
}
return "#" + result;
}
function colorToString(color) {
if (color.alpha === 0) {
return "transparent";
}
switch (color.type) {
case "none":
case "transparent":
return color.type;
case "current":
return "currentColor";
case "rgb": {
const hex = colorToHexString(color);
if (hex !== null) {
return hex;
}
const list = [color.r, color.g, color.b];
if (color.alpha !== 1) {
list.push(color.alpha);
}
return "rgb" + (list.length === 4 ? "a(" : "(") + list.join(", ") + ")";
}
case "hsl": {
const list = [
color.h,
color.s.toString() + "%",
color.l.toString() + "%"
];
if (color.alpha !== 1) {
list.push(color.alpha);
}
return "hsl" + (list.length === 4 ? "a(" : "(") + list.join(", ") + ")";
}
case "lab": {
const list = [color.l.toString() + "%", color.a, color.b];
if (color.alpha !== 1) {
list.push("/ " + color.alpha.toString());
}
return "lab(" + list.join(" ") + ")";
}
case "lch": {
const list = [color.l.toString() + "%", color.c, color.h];
if (color.alpha !== 1) {
list.push("/ " + color.alpha.toString());
}
return "lch(" + list.join(" ") + ")";
}
case "function": {
return color.func + "(" + color.value + ")";
}
}
}
export { colorToHexString, colorToString, compareColors, stringToColor };
@@ -0,0 +1,190 @@
'use strict';
const colorKeywords = {
transparent: {
type: "transparent"
},
none: {
type: "none"
},
currentcolor: {
type: "current"
}
};
function add(keyword, colors) {
const type = "rgb";
const r = colors[0];
const length = colors.length;
colorKeywords[keyword] = {
type,
r,
g: length > 1 ? colors[1] : r,
b: length > 2 ? colors[2] : r,
alpha: length > 3 ? colors[3] : 1
};
}
add("silver", [192]);
add("gray", [128]);
add("white", [255]);
add("maroon", [128, 0, 0]);
add("red", [255, 0, 0]);
add("purple", [128, 0]);
add("fuchsia", [255, 0]);
add("green", [0, 128]);
add("lime", [0, 255]);
add("olive", [128, 128, 0]);
add("yellow", [255, 255, 0]);
add("navy", [0, 0, 128]);
add("blue", [0, 0, 255]);
add("teal", [0, 128, 128]);
add("aqua", [0, 255, 255]);
add("aliceblue", [240, 248, 255]);
add("antiquewhite", [250, 235, 215]);
add("aqua", [0, 255, 255]);
add("aquamarine", [127, 255, 212]);
add("azure", [240, 255, 255]);
add("beige", [245, 245, 220]);
add("bisque", [255, 228, 196]);
add("black", [0]);
add("blanchedalmond", [255, 235, 205]);
add("blue", [0, 0, 255]);
add("blueviolet", [138, 43, 226]);
add("brown", [165, 42, 42]);
add("burlywood", [222, 184, 135]);
add("cadetblue", [95, 158, 160]);
add("chartreuse", [127, 255, 0]);
add("chocolate", [210, 105, 30]);
add("coral", [255, 127, 80]);
add("cornflowerblue", [100, 149, 237]);
add("cornsilk", [255, 248, 220]);
add("crimson", [220, 20, 60]);
add("cyan", [0, 255, 255]);
add("darkblue", [0, 0, 139]);
add("darkcyan", [0, 139, 139]);
add("darkgoldenrod", [184, 134, 11]);
add("darkgray", [169]);
add("darkgreen", [0, 100]);
add("darkgrey", [169]);
add("darkkhaki", [189, 183, 107]);
add("darkmagenta", [139, 0]);
add("darkolivegreen", [85, 107, 47]);
add("darkorange", [255, 140, 0]);
add("darkorchid", [153, 50, 204]);
add("darkred", [139, 0, 0]);
add("darksalmon", [233, 150, 122]);
add("darkseagreen", [143, 188]);
add("darkslateblue", [72, 61, 139]);
add("darkslategray", [47, 79, 79]);
add("darkslategrey", [47, 79, 79]);
add("darkturquoise", [0, 206, 209]);
add("darkviolet", [148, 0, 211]);
add("deeppink", [255, 20, 147]);
add("deepskyblue", [0, 191, 255]);
add("dimgray", [105]);
add("dimgrey", [105]);
add("dodgerblue", [30, 144, 255]);
add("firebrick", [178, 34, 34]);
add("floralwhite", [255, 250, 240]);
add("forestgreen", [34, 139]);
add("fuchsia", [255, 0]);
add("gainsboro", [220]);
add("ghostwhite", [248, 248, 255]);
add("gold", [255, 215, 0]);
add("goldenrod", [218, 165, 32]);
add("gray", [128]);
add("green", [0, 128]);
add("greenyellow", [173, 255, 47]);
add("grey", [128]);
add("honeydew", [240, 255]);
add("hotpink", [255, 105, 180]);
add("indianred", [205, 92, 92]);
add("indigo", [75, 0, 130]);
add("ivory", [255, 255, 240]);
add("khaki", [240, 230, 140]);
add("lavender", [230, 230, 250]);
add("lavenderblush", [255, 240, 245]);
add("lawngreen", [124, 252, 0]);
add("lemonchiffon", [255, 250, 205]);
add("lightblue", [173, 216, 230]);
add("lightcoral", [240, 128, 128]);
add("lightcyan", [224, 255, 255]);
add("lightgoldenrodyellow", [250, 250, 210]);
add("lightgray", [211]);
add("lightgreen", [144, 238]);
add("lightgrey", [211]);
add("lightpink", [255, 182, 193]);
add("lightsalmon", [255, 160, 122]);
add("lightseagreen", [32, 178, 170]);
add("lightskyblue", [135, 206, 250]);
add("lightslategray", [119, 136, 153]);
add("lightslategrey", [119, 136, 153]);
add("lightsteelblue", [176, 196, 222]);
add("lightyellow", [255, 255, 224]);
add("lime", [0, 255]);
add("limegreen", [50, 205]);
add("linen", [250, 240, 230]);
add("magenta", [255, 0]);
add("maroon", [128, 0, 0]);
add("mediumaquamarine", [102, 205, 170]);
add("mediumblue", [0, 0, 205]);
add("mediumorchid", [186, 85, 211]);
add("mediumpurple", [147, 112, 219]);
add("mediumseagreen", [60, 179, 113]);
add("mediumslateblue", [123, 104, 238]);
add("mediumspringgreen", [0, 250, 154]);
add("mediumturquoise", [72, 209, 204]);
add("mediumvioletred", [199, 21, 133]);
add("midnightblue", [25, 25, 112]);
add("mintcream", [245, 255, 250]);
add("mistyrose", [255, 228, 225]);
add("moccasin", [255, 228, 181]);
add("navajowhite", [255, 222, 173]);
add("navy", [0, 0, 128]);
add("oldlace", [253, 245, 230]);
add("olive", [128, 128, 0]);
add("olivedrab", [107, 142, 35]);
add("orange", [255, 165, 0]);
add("orangered", [255, 69, 0]);
add("orchid", [218, 112, 214]);
add("palegoldenrod", [238, 232, 170]);
add("palegreen", [152, 251]);
add("paleturquoise", [175, 238, 238]);
add("palevioletred", [219, 112, 147]);
add("papayawhip", [255, 239, 213]);
add("peachpuff", [255, 218, 185]);
add("peru", [205, 133, 63]);
add("pink", [255, 192, 203]);
add("plum", [221, 160]);
add("powderblue", [176, 224, 230]);
add("purple", [128, 0]);
add("rebeccapurple", [102, 51, 153]);
add("red", [255, 0, 0]);
add("rosybrown", [188, 143, 143]);
add("royalblue", [65, 105, 225]);
add("saddlebrown", [139, 69, 19]);
add("salmon", [250, 128, 114]);
add("sandybrown", [244, 164, 96]);
add("seagreen", [46, 139, 87]);
add("seashell", [255, 245, 238]);
add("sienna", [160, 82, 45]);
add("silver", [192]);
add("skyblue", [135, 206, 235]);
add("slateblue", [106, 90, 205]);
add("slategray", [112, 128, 144]);
add("slategrey", [112, 128, 144]);
add("snow", [255, 250, 250]);
add("springgreen", [0, 255, 127]);
add("steelblue", [70, 130, 180]);
add("tan", [210, 180, 140]);
add("teal", [0, 128, 128]);
add("thistle", [216, 191]);
add("tomato", [255, 99, 71]);
add("turquoise", [64, 224, 208]);
add("violet", [238, 130]);
add("wheat", [245, 222, 179]);
add("white", [255]);
add("whitesmoke", [245]);
add("yellow", [255, 255, 0]);
add("yellowgreen", [154, 205, 50]);
exports.colorKeywords = colorKeywords;
@@ -0,0 +1,8 @@
import { Color } from './types.cjs';
/**
* Color keywords
*/
declare const colorKeywords: Record<string, Color>;
export { colorKeywords };
@@ -0,0 +1,8 @@
import { Color } from './types.mjs';
/**
* Color keywords
*/
declare const colorKeywords: Record<string, Color>;
export { colorKeywords };
@@ -0,0 +1,8 @@
import { Color } from './types.js';
/**
* Color keywords
*/
declare const colorKeywords: Record<string, Color>;
export { colorKeywords };
@@ -0,0 +1,188 @@
const colorKeywords = {
transparent: {
type: "transparent"
},
none: {
type: "none"
},
currentcolor: {
type: "current"
}
};
function add(keyword, colors) {
const type = "rgb";
const r = colors[0];
const length = colors.length;
colorKeywords[keyword] = {
type,
r,
g: length > 1 ? colors[1] : r,
b: length > 2 ? colors[2] : r,
alpha: length > 3 ? colors[3] : 1
};
}
add("silver", [192]);
add("gray", [128]);
add("white", [255]);
add("maroon", [128, 0, 0]);
add("red", [255, 0, 0]);
add("purple", [128, 0]);
add("fuchsia", [255, 0]);
add("green", [0, 128]);
add("lime", [0, 255]);
add("olive", [128, 128, 0]);
add("yellow", [255, 255, 0]);
add("navy", [0, 0, 128]);
add("blue", [0, 0, 255]);
add("teal", [0, 128, 128]);
add("aqua", [0, 255, 255]);
add("aliceblue", [240, 248, 255]);
add("antiquewhite", [250, 235, 215]);
add("aqua", [0, 255, 255]);
add("aquamarine", [127, 255, 212]);
add("azure", [240, 255, 255]);
add("beige", [245, 245, 220]);
add("bisque", [255, 228, 196]);
add("black", [0]);
add("blanchedalmond", [255, 235, 205]);
add("blue", [0, 0, 255]);
add("blueviolet", [138, 43, 226]);
add("brown", [165, 42, 42]);
add("burlywood", [222, 184, 135]);
add("cadetblue", [95, 158, 160]);
add("chartreuse", [127, 255, 0]);
add("chocolate", [210, 105, 30]);
add("coral", [255, 127, 80]);
add("cornflowerblue", [100, 149, 237]);
add("cornsilk", [255, 248, 220]);
add("crimson", [220, 20, 60]);
add("cyan", [0, 255, 255]);
add("darkblue", [0, 0, 139]);
add("darkcyan", [0, 139, 139]);
add("darkgoldenrod", [184, 134, 11]);
add("darkgray", [169]);
add("darkgreen", [0, 100]);
add("darkgrey", [169]);
add("darkkhaki", [189, 183, 107]);
add("darkmagenta", [139, 0]);
add("darkolivegreen", [85, 107, 47]);
add("darkorange", [255, 140, 0]);
add("darkorchid", [153, 50, 204]);
add("darkred", [139, 0, 0]);
add("darksalmon", [233, 150, 122]);
add("darkseagreen", [143, 188]);
add("darkslateblue", [72, 61, 139]);
add("darkslategray", [47, 79, 79]);
add("darkslategrey", [47, 79, 79]);
add("darkturquoise", [0, 206, 209]);
add("darkviolet", [148, 0, 211]);
add("deeppink", [255, 20, 147]);
add("deepskyblue", [0, 191, 255]);
add("dimgray", [105]);
add("dimgrey", [105]);
add("dodgerblue", [30, 144, 255]);
add("firebrick", [178, 34, 34]);
add("floralwhite", [255, 250, 240]);
add("forestgreen", [34, 139]);
add("fuchsia", [255, 0]);
add("gainsboro", [220]);
add("ghostwhite", [248, 248, 255]);
add("gold", [255, 215, 0]);
add("goldenrod", [218, 165, 32]);
add("gray", [128]);
add("green", [0, 128]);
add("greenyellow", [173, 255, 47]);
add("grey", [128]);
add("honeydew", [240, 255]);
add("hotpink", [255, 105, 180]);
add("indianred", [205, 92, 92]);
add("indigo", [75, 0, 130]);
add("ivory", [255, 255, 240]);
add("khaki", [240, 230, 140]);
add("lavender", [230, 230, 250]);
add("lavenderblush", [255, 240, 245]);
add("lawngreen", [124, 252, 0]);
add("lemonchiffon", [255, 250, 205]);
add("lightblue", [173, 216, 230]);
add("lightcoral", [240, 128, 128]);
add("lightcyan", [224, 255, 255]);
add("lightgoldenrodyellow", [250, 250, 210]);
add("lightgray", [211]);
add("lightgreen", [144, 238]);
add("lightgrey", [211]);
add("lightpink", [255, 182, 193]);
add("lightsalmon", [255, 160, 122]);
add("lightseagreen", [32, 178, 170]);
add("lightskyblue", [135, 206, 250]);
add("lightslategray", [119, 136, 153]);
add("lightslategrey", [119, 136, 153]);
add("lightsteelblue", [176, 196, 222]);
add("lightyellow", [255, 255, 224]);
add("lime", [0, 255]);
add("limegreen", [50, 205]);
add("linen", [250, 240, 230]);
add("magenta", [255, 0]);
add("maroon", [128, 0, 0]);
add("mediumaquamarine", [102, 205, 170]);
add("mediumblue", [0, 0, 205]);
add("mediumorchid", [186, 85, 211]);
add("mediumpurple", [147, 112, 219]);
add("mediumseagreen", [60, 179, 113]);
add("mediumslateblue", [123, 104, 238]);
add("mediumspringgreen", [0, 250, 154]);
add("mediumturquoise", [72, 209, 204]);
add("mediumvioletred", [199, 21, 133]);
add("midnightblue", [25, 25, 112]);
add("mintcream", [245, 255, 250]);
add("mistyrose", [255, 228, 225]);
add("moccasin", [255, 228, 181]);
add("navajowhite", [255, 222, 173]);
add("navy", [0, 0, 128]);
add("oldlace", [253, 245, 230]);
add("olive", [128, 128, 0]);
add("olivedrab", [107, 142, 35]);
add("orange", [255, 165, 0]);
add("orangered", [255, 69, 0]);
add("orchid", [218, 112, 214]);
add("palegoldenrod", [238, 232, 170]);
add("palegreen", [152, 251]);
add("paleturquoise", [175, 238, 238]);
add("palevioletred", [219, 112, 147]);
add("papayawhip", [255, 239, 213]);
add("peachpuff", [255, 218, 185]);
add("peru", [205, 133, 63]);
add("pink", [255, 192, 203]);
add("plum", [221, 160]);
add("powderblue", [176, 224, 230]);
add("purple", [128, 0]);
add("rebeccapurple", [102, 51, 153]);
add("red", [255, 0, 0]);
add("rosybrown", [188, 143, 143]);
add("royalblue", [65, 105, 225]);
add("saddlebrown", [139, 69, 19]);
add("salmon", [250, 128, 114]);
add("sandybrown", [244, 164, 96]);
add("seagreen", [46, 139, 87]);
add("seashell", [255, 245, 238]);
add("sienna", [160, 82, 45]);
add("silver", [192]);
add("skyblue", [135, 206, 235]);
add("slateblue", [106, 90, 205]);
add("slategray", [112, 128, 144]);
add("slategrey", [112, 128, 144]);
add("snow", [255, 250, 250]);
add("springgreen", [0, 255, 127]);
add("steelblue", [70, 130, 180]);
add("tan", [210, 180, 140]);
add("teal", [0, 128, 128]);
add("thistle", [216, 191]);
add("tomato", [255, 99, 71]);
add("turquoise", [64, 224, 208]);
add("violet", [238, 130]);
add("wheat", [245, 222, 179]);
add("white", [255]);
add("whitesmoke", [245]);
add("yellow", [255, 255, 0]);
add("yellowgreen", [154, 205, 50]);
export { colorKeywords };
@@ -0,0 +1,2 @@
'use strict';
@@ -0,0 +1,45 @@
interface RGBColor {
type: 'rgb';
r: number;
g: number;
b: number;
alpha: number;
}
interface HSLColor {
type: 'hsl';
h: number;
s: number;
l: number;
alpha: number;
}
interface LABColor {
type: 'lab';
l: number;
a: number;
b: number;
alpha: number;
}
interface LCHColor {
type: 'lch';
l: number;
c: number;
h: number;
alpha: number;
}
interface FunctionColor {
type: 'function';
func: string;
value: string;
}
interface TransparentColor {
type: 'transparent';
}
interface NoColor {
type: 'none';
}
interface CurrentColor {
type: 'current';
}
type Color = RGBColor | HSLColor | LABColor | LCHColor | FunctionColor | TransparentColor | NoColor | CurrentColor;
export type { Color, CurrentColor, FunctionColor, HSLColor, LABColor, LCHColor, NoColor, RGBColor, TransparentColor };
@@ -0,0 +1,45 @@
interface RGBColor {
type: 'rgb';
r: number;
g: number;
b: number;
alpha: number;
}
interface HSLColor {
type: 'hsl';
h: number;
s: number;
l: number;
alpha: number;
}
interface LABColor {
type: 'lab';
l: number;
a: number;
b: number;
alpha: number;
}
interface LCHColor {
type: 'lch';
l: number;
c: number;
h: number;
alpha: number;
}
interface FunctionColor {
type: 'function';
func: string;
value: string;
}
interface TransparentColor {
type: 'transparent';
}
interface NoColor {
type: 'none';
}
interface CurrentColor {
type: 'current';
}
type Color = RGBColor | HSLColor | LABColor | LCHColor | FunctionColor | TransparentColor | NoColor | CurrentColor;
export type { Color, CurrentColor, FunctionColor, HSLColor, LABColor, LCHColor, NoColor, RGBColor, TransparentColor };
@@ -0,0 +1,45 @@
interface RGBColor {
type: 'rgb';
r: number;
g: number;
b: number;
alpha: number;
}
interface HSLColor {
type: 'hsl';
h: number;
s: number;
l: number;
alpha: number;
}
interface LABColor {
type: 'lab';
l: number;
a: number;
b: number;
alpha: number;
}
interface LCHColor {
type: 'lch';
l: number;
c: number;
h: number;
alpha: number;
}
interface FunctionColor {
type: 'function';
func: string;
value: string;
}
interface TransparentColor {
type: 'transparent';
}
interface NoColor {
type: 'none';
}
interface CurrentColor {
type: 'current';
}
type Color = RGBColor | HSLColor | LABColor | LCHColor | FunctionColor | TransparentColor | NoColor | CurrentColor;
export type { Color, CurrentColor, FunctionColor, HSLColor, LABColor, LCHColor, NoColor, RGBColor, TransparentColor };
@@ -0,0 +1,94 @@
'use strict';
const svg_html = require('../svg/html.cjs');
const svg_size = require('../svg/size.cjs');
const svg_url = require('../svg/url.cjs');
const icon_square = require('../icon/square.cjs');
const svg_build = require('../svg/build.cjs');
require('../icon/defaults.cjs');
require('../customisations/defaults.cjs');
require('../svg/defs.cjs');
function getCommonCSSRules(options) {
const result = {
display: "inline-block",
width: "1em",
height: "1em"
};
const varName = options.varName;
if (options.pseudoSelector) {
result["content"] = "''";
}
switch (options.mode) {
case "background":
if (varName) {
result["background-image"] = "var(--" + varName + ")";
}
result["background-repeat"] = "no-repeat";
result["background-size"] = "100% 100%";
break;
case "mask":
result["background-color"] = "currentColor";
if (varName) {
result["mask-image"] = result["-webkit-mask-image"] = "var(--" + varName + ")";
}
result["mask-repeat"] = result["-webkit-mask-repeat"] = "no-repeat";
result["mask-size"] = result["-webkit-mask-size"] = "100% 100%";
break;
}
return result;
}
function generateItemCSSRules(icon, options) {
const result = {};
const varName = options.varName;
const buildResult = svg_build.iconToSVG(icon);
let viewBox = buildResult.viewBox;
if (viewBox[2] !== viewBox[3]) {
if (options.forceSquare) {
viewBox = icon_square.makeViewBoxSquare(viewBox);
} else {
result["width"] = svg_size.calculateSize("1em", viewBox[2] / viewBox[3]);
}
}
const svg = svg_html.iconToHTML(
buildResult.body.replace(/currentColor/g, options.color || "black"),
{
viewBox: `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`,
width: `${viewBox[2]}`,
height: `${viewBox[3]}`
}
);
const url = svg_url.svgToURL(svg);
if (varName) {
result["--" + varName] = url;
} else {
switch (options.mode) {
case "background":
result["background-image"] = url;
break;
case "mask":
result["mask-image"] = result["-webkit-mask-image"] = url;
break;
}
}
return result;
}
function generateItemContent(icon, options) {
const buildResult = svg_build.iconToSVG(icon);
const viewBox = buildResult.viewBox;
const height = options.height;
const width = options.width ?? svg_size.calculateSize(height, viewBox[2] / viewBox[3]);
const svg = svg_html.iconToHTML(
buildResult.body.replace(/currentColor/g, options.color || "black"),
{
viewBox: `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`,
width: width.toString(),
height: height.toString()
}
);
return svg_url.svgToURL(svg);
}
exports.generateItemCSSRules = generateItemCSSRules;
exports.generateItemContent = generateItemContent;
exports.getCommonCSSRules = getCommonCSSRules;
@@ -0,0 +1,19 @@
import { IconifyIcon } from '@iconify/types';
import { IconCSSCommonCodeOptions, IconCSSItemOptions, IconContentItemOptions } from './types.cjs';
/**
* Generates common CSS rules for multiple icons, rendered as background/mask
*/
declare function getCommonCSSRules(options: IconCSSCommonCodeOptions): Record<string, string>;
/**
* Generate CSS rules for one icon, rendered as background/mask
*
* This function excludes common rules
*/
declare function generateItemCSSRules(icon: Required<IconifyIcon>, options: IconCSSItemOptions): Record<string, string>;
/**
* Generate content for one icon, rendered as content of pseudo-selector
*/
declare function generateItemContent(icon: Required<IconifyIcon>, options: IconContentItemOptions): string;
export { generateItemCSSRules, generateItemContent, getCommonCSSRules };
@@ -0,0 +1,19 @@
import { IconifyIcon } from '@iconify/types';
import { IconCSSCommonCodeOptions, IconCSSItemOptions, IconContentItemOptions } from './types.mjs';
/**
* Generates common CSS rules for multiple icons, rendered as background/mask
*/
declare function getCommonCSSRules(options: IconCSSCommonCodeOptions): Record<string, string>;
/**
* Generate CSS rules for one icon, rendered as background/mask
*
* This function excludes common rules
*/
declare function generateItemCSSRules(icon: Required<IconifyIcon>, options: IconCSSItemOptions): Record<string, string>;
/**
* Generate content for one icon, rendered as content of pseudo-selector
*/
declare function generateItemContent(icon: Required<IconifyIcon>, options: IconContentItemOptions): string;
export { generateItemCSSRules, generateItemContent, getCommonCSSRules };
@@ -0,0 +1,19 @@
import { IconifyIcon } from '@iconify/types';
import { IconCSSCommonCodeOptions, IconCSSItemOptions, IconContentItemOptions } from './types.js';
/**
* Generates common CSS rules for multiple icons, rendered as background/mask
*/
declare function getCommonCSSRules(options: IconCSSCommonCodeOptions): Record<string, string>;
/**
* Generate CSS rules for one icon, rendered as background/mask
*
* This function excludes common rules
*/
declare function generateItemCSSRules(icon: Required<IconifyIcon>, options: IconCSSItemOptions): Record<string, string>;
/**
* Generate content for one icon, rendered as content of pseudo-selector
*/
declare function generateItemContent(icon: Required<IconifyIcon>, options: IconContentItemOptions): string;
export { generateItemCSSRules, generateItemContent, getCommonCSSRules };
@@ -0,0 +1,90 @@
import { iconToHTML } from '../svg/html.mjs';
import { calculateSize } from '../svg/size.mjs';
import { svgToURL } from '../svg/url.mjs';
import { makeViewBoxSquare } from '../icon/square.mjs';
import { iconToSVG } from '../svg/build.mjs';
import '../icon/defaults.mjs';
import '../customisations/defaults.mjs';
import '../svg/defs.mjs';
function getCommonCSSRules(options) {
const result = {
display: "inline-block",
width: "1em",
height: "1em"
};
const varName = options.varName;
if (options.pseudoSelector) {
result["content"] = "''";
}
switch (options.mode) {
case "background":
if (varName) {
result["background-image"] = "var(--" + varName + ")";
}
result["background-repeat"] = "no-repeat";
result["background-size"] = "100% 100%";
break;
case "mask":
result["background-color"] = "currentColor";
if (varName) {
result["mask-image"] = result["-webkit-mask-image"] = "var(--" + varName + ")";
}
result["mask-repeat"] = result["-webkit-mask-repeat"] = "no-repeat";
result["mask-size"] = result["-webkit-mask-size"] = "100% 100%";
break;
}
return result;
}
function generateItemCSSRules(icon, options) {
const result = {};
const varName = options.varName;
const buildResult = iconToSVG(icon);
let viewBox = buildResult.viewBox;
if (viewBox[2] !== viewBox[3]) {
if (options.forceSquare) {
viewBox = makeViewBoxSquare(viewBox);
} else {
result["width"] = calculateSize("1em", viewBox[2] / viewBox[3]);
}
}
const svg = iconToHTML(
buildResult.body.replace(/currentColor/g, options.color || "black"),
{
viewBox: `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`,
width: `${viewBox[2]}`,
height: `${viewBox[3]}`
}
);
const url = svgToURL(svg);
if (varName) {
result["--" + varName] = url;
} else {
switch (options.mode) {
case "background":
result["background-image"] = url;
break;
case "mask":
result["mask-image"] = result["-webkit-mask-image"] = url;
break;
}
}
return result;
}
function generateItemContent(icon, options) {
const buildResult = iconToSVG(icon);
const viewBox = buildResult.viewBox;
const height = options.height;
const width = options.width ?? calculateSize(height, viewBox[2] / viewBox[3]);
const svg = iconToHTML(
buildResult.body.replace(/currentColor/g, options.color || "black"),
{
viewBox: `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`,
width: width.toString(),
height: height.toString()
}
);
return svgToURL(svg);
}
export { generateItemCSSRules, generateItemContent, getCommonCSSRules };
@@ -0,0 +1,40 @@
'use strict';
const format = {
selectorStart: {
compressed: "{",
compact: " {",
expanded: " {"
},
selectorEnd: {
compressed: "}",
compact: "; }\n",
expanded: ";\n}\n"
},
rule: {
compressed: "{key}:",
compact: " {key}: ",
expanded: "\n {key}: "
}
};
function formatCSS(data, mode = "expanded") {
const results = [];
for (let i = 0; i < data.length; i++) {
const { selector, rules } = data[i];
const fullSelector = selector instanceof Array ? selector.join(mode === "compressed" ? "," : ", ") : selector;
let entry = fullSelector + format.selectorStart[mode];
let firstRule = true;
for (const key in rules) {
if (!firstRule) {
entry += ";";
}
entry += format.rule[mode].replace("{key}", key) + rules[key];
firstRule = false;
}
entry += format.selectorEnd[mode];
results.push(entry);
}
return results.join(mode === "compressed" ? "" : "\n");
}
exports.formatCSS = formatCSS;
@@ -0,0 +1,10 @@
import { CSSUnformattedItem, CSSFormatMode } from './types.cjs';
/**
* Format data
*
* Key is selector, value is list of rules
*/
declare function formatCSS(data: CSSUnformattedItem[], mode?: CSSFormatMode): string;
export { formatCSS };
@@ -0,0 +1,10 @@
import { CSSUnformattedItem, CSSFormatMode } from './types.mjs';
/**
* Format data
*
* Key is selector, value is list of rules
*/
declare function formatCSS(data: CSSUnformattedItem[], mode?: CSSFormatMode): string;
export { formatCSS };
@@ -0,0 +1,10 @@
import { CSSUnformattedItem, CSSFormatMode } from './types.js';
/**
* Format data
*
* Key is selector, value is list of rules
*/
declare function formatCSS(data: CSSUnformattedItem[], mode?: CSSFormatMode): string;
export { formatCSS };
@@ -0,0 +1,38 @@
const format = {
selectorStart: {
compressed: "{",
compact: " {",
expanded: " {"
},
selectorEnd: {
compressed: "}",
compact: "; }\n",
expanded: ";\n}\n"
},
rule: {
compressed: "{key}:",
compact: " {key}: ",
expanded: "\n {key}: "
}
};
function formatCSS(data, mode = "expanded") {
const results = [];
for (let i = 0; i < data.length; i++) {
const { selector, rules } = data[i];
const fullSelector = selector instanceof Array ? selector.join(mode === "compressed" ? "," : ", ") : selector;
let entry = fullSelector + format.selectorStart[mode];
let firstRule = true;
for (const key in rules) {
if (!firstRule) {
entry += ";";
}
entry += format.rule[mode].replace("{key}", key) + rules[key];
firstRule = false;
}
entry += format.selectorEnd[mode];
results.push(entry);
}
return results.join(mode === "compressed" ? "" : "\n");
}
export { formatCSS };
@@ -0,0 +1,79 @@
'use strict';
const icon_defaults = require('../icon/defaults.cjs');
const css_common = require('./common.cjs');
const css_format = require('./format.cjs');
require('../svg/html.cjs');
require('../svg/size.cjs');
require('../svg/url.cjs');
require('../icon/square.cjs');
require('../svg/build.cjs');
require('../customisations/defaults.cjs');
require('../svg/defs.cjs');
function getIconCSS(icon, options = {}) {
const body = options.customise ? options.customise(icon.body) : icon.body;
const mode = options.mode || (options.color || !body.includes("currentColor") ? "background" : "mask");
let varName = options.varName;
if (varName === void 0 && mode === "mask") {
varName = "svg";
}
const newOptions = {
...options,
// Override mode and varName
mode,
varName
};
if (mode === "background") {
delete newOptions.varName;
}
const rules = {
...options.rules,
...css_common.getCommonCSSRules(newOptions),
...css_common.generateItemCSSRules(
{
...icon_defaults.defaultIconProps,
...icon,
body
},
newOptions
)
};
const selector = options.iconSelector || ".icon";
return css_format.formatCSS(
[
{
selector,
rules
}
],
newOptions.format
);
}
function getIconContentCSS(icon, options) {
const body = options.customise ? options.customise(icon.body) : icon.body;
const content = css_common.generateItemContent(
{
...icon_defaults.defaultIconProps,
...icon,
body
},
options
);
const selector = options.iconSelector || ".icon::after";
return css_format.formatCSS(
[
{
selector,
rules: {
...options.rules,
content
}
}
],
options.format
);
}
exports.getIconCSS = getIconCSS;
exports.getIconContentCSS = getIconContentCSS;
@@ -0,0 +1,13 @@
import { IconifyIcon } from '@iconify/types';
import { IconCSSIconOptions, IconContentIconOptions } from './types.cjs';
/**
* Get CSS for icon, rendered as background or mask
*/
declare function getIconCSS(icon: IconifyIcon, options?: IconCSSIconOptions): string;
/**
* Get CSS for icon, rendered as content
*/
declare function getIconContentCSS(icon: IconifyIcon, options: IconContentIconOptions): string;
export { getIconCSS, getIconContentCSS };
@@ -0,0 +1,13 @@
import { IconifyIcon } from '@iconify/types';
import { IconCSSIconOptions, IconContentIconOptions } from './types.mjs';
/**
* Get CSS for icon, rendered as background or mask
*/
declare function getIconCSS(icon: IconifyIcon, options?: IconCSSIconOptions): string;
/**
* Get CSS for icon, rendered as content
*/
declare function getIconContentCSS(icon: IconifyIcon, options: IconContentIconOptions): string;
export { getIconCSS, getIconContentCSS };
@@ -0,0 +1,13 @@
import { IconifyIcon } from '@iconify/types';
import { IconCSSIconOptions, IconContentIconOptions } from './types.js';
/**
* Get CSS for icon, rendered as background or mask
*/
declare function getIconCSS(icon: IconifyIcon, options?: IconCSSIconOptions): string;
/**
* Get CSS for icon, rendered as content
*/
declare function getIconContentCSS(icon: IconifyIcon, options: IconContentIconOptions): string;
export { getIconCSS, getIconContentCSS };
@@ -0,0 +1,76 @@
import { defaultIconProps } from '../icon/defaults.mjs';
import { getCommonCSSRules, generateItemCSSRules, generateItemContent } from './common.mjs';
import { formatCSS } from './format.mjs';
import '../svg/html.mjs';
import '../svg/size.mjs';
import '../svg/url.mjs';
import '../icon/square.mjs';
import '../svg/build.mjs';
import '../customisations/defaults.mjs';
import '../svg/defs.mjs';
function getIconCSS(icon, options = {}) {
const body = options.customise ? options.customise(icon.body) : icon.body;
const mode = options.mode || (options.color || !body.includes("currentColor") ? "background" : "mask");
let varName = options.varName;
if (varName === void 0 && mode === "mask") {
varName = "svg";
}
const newOptions = {
...options,
// Override mode and varName
mode,
varName
};
if (mode === "background") {
delete newOptions.varName;
}
const rules = {
...options.rules,
...getCommonCSSRules(newOptions),
...generateItemCSSRules(
{
...defaultIconProps,
...icon,
body
},
newOptions
)
};
const selector = options.iconSelector || ".icon";
return formatCSS(
[
{
selector,
rules
}
],
newOptions.format
);
}
function getIconContentCSS(icon, options) {
const body = options.customise ? options.customise(icon.body) : icon.body;
const content = generateItemContent(
{
...defaultIconProps,
...icon,
body
},
options
);
const selector = options.iconSelector || ".icon::after";
return formatCSS(
[
{
selector,
rules: {
...options.rules,
content
}
}
],
options.format
);
}
export { getIconCSS, getIconContentCSS };
@@ -0,0 +1,172 @@
'use strict';
const iconSet_getIcon = require('../icon-set/get-icon.cjs');
const icon_defaults = require('../icon/defaults.cjs');
const css_common = require('./common.cjs');
const css_format = require('./format.cjs');
require('../icon/merge.cjs');
require('../icon/transformations.cjs');
require('../icon-set/tree.cjs');
require('../svg/html.cjs');
require('../svg/size.cjs');
require('../svg/url.cjs');
require('../icon/square.cjs');
require('../svg/build.cjs');
require('../customisations/defaults.cjs');
require('../svg/defs.cjs');
const commonSelector = ".icon--{prefix}";
const iconSelector = ".icon--{prefix}--{name}";
const contentSelector = ".icon--{prefix}--{name}::after";
const defaultSelectors = {
commonSelector,
iconSelector,
overrideSelector: commonSelector + iconSelector
};
function getIconsCSSData(iconSet, names, options = {}) {
const css = [];
const errors = [];
const palette = options.color ? true : void 0;
let mode = options.mode || typeof palette === "boolean" && (palette ? "background" : "mask");
if (!mode) {
for (let i = 0; i < names.length; i++) {
const name = names[i];
const icon = iconSet_getIcon.getIconData(iconSet, name);
if (icon) {
const body = options.customise ? options.customise(icon.body, name) : icon.body;
mode = body.includes("currentColor") ? "mask" : "background";
break;
}
}
if (!mode) {
mode = "mask";
errors.push(
"/* cannot detect icon mode: not set in options and icon set is missing info, rendering as " + mode + " */"
);
}
}
let varName = options.varName;
if (varName === void 0 && mode === "mask") {
varName = "svg";
}
const newOptions = {
...options,
// Override mode and varName
mode,
varName
};
const { commonSelector: commonSelector2, iconSelector: iconSelector2, overrideSelector } = newOptions.iconSelector ? newOptions : defaultSelectors;
const iconSelectorWithPrefix = iconSelector2.replace(
/{prefix}/g,
iconSet.prefix
);
const commonRules = {
...options.rules,
...css_common.getCommonCSSRules(newOptions)
};
const hasCommonRules = commonSelector2 && commonSelector2 !== iconSelector2;
const commonSelectors = /* @__PURE__ */ new Set();
if (hasCommonRules) {
css.push({
selector: commonSelector2.replace(/{prefix}/g, iconSet.prefix),
rules: commonRules
});
}
for (let i = 0; i < names.length; i++) {
const name = names[i];
const iconData = iconSet_getIcon.getIconData(iconSet, name);
if (!iconData) {
errors.push("/* Could not find icon: " + name + " */");
continue;
}
const body = options.customise ? options.customise(iconData.body, name) : iconData.body;
const rules = css_common.generateItemCSSRules(
{
...icon_defaults.defaultIconProps,
...iconData,
body
},
newOptions
);
let requiresOverride = false;
if (hasCommonRules && overrideSelector) {
for (const key in rules) {
if (key in commonRules) {
requiresOverride = true;
}
}
}
const selector = (requiresOverride && overrideSelector ? overrideSelector.replace(/{prefix}/g, iconSet.prefix) : iconSelectorWithPrefix).replace(/{name}/g, name);
css.push({
selector,
rules
});
if (!hasCommonRules) {
commonSelectors.add(selector);
}
}
const result = {
css,
errors
};
if (!hasCommonRules && commonSelectors.size) {
const selector = Array.from(commonSelectors).join(
newOptions.format === "compressed" ? "," : ", "
);
result.common = {
selector,
rules: commonRules
};
}
return result;
}
function getIconsCSS(iconSet, names, options = {}) {
const { css, errors, common } = getIconsCSSData(iconSet, names, options);
if (common) {
if (css.length === 1 && css[0].selector === common.selector) {
css[0].rules = {
// Common first, override later
...common.rules,
...css[0].rules
};
} else {
css.unshift(common);
}
}
return css_format.formatCSS(css, options.format) + (errors.length ? "\n" + errors.join("\n") + "\n" : "");
}
function getIconsContentCSS(iconSet, names, options) {
const errors = [];
const css = [];
const iconSelectorWithPrefix = (options.iconSelector ?? contentSelector).replace(/{prefix}/g, iconSet.prefix);
for (let i = 0; i < names.length; i++) {
const name = names[i];
const iconData = iconSet_getIcon.getIconData(iconSet, name);
if (!iconData) {
errors.push("/* Could not find icon: " + name + " */");
continue;
}
const body = options.customise ? options.customise(iconData.body, name) : iconData.body;
const content = css_common.generateItemContent(
{
...icon_defaults.defaultIconProps,
...iconData,
body
},
options
);
const selector = iconSelectorWithPrefix.replace(/{name}/g, name);
css.push({
selector,
rules: {
...options.rules,
content
}
});
}
return css_format.formatCSS(css, options.format) + (errors.length ? "\n" + errors.join("\n") + "\n" : "");
}
exports.getIconsCSS = getIconsCSS;
exports.getIconsCSSData = getIconsCSSData;
exports.getIconsContentCSS = getIconsContentCSS;
@@ -0,0 +1,22 @@
import { IconifyJSON } from '@iconify/types';
import { IconCSSIconSetOptions, IconContentIconSetOptions, CSSUnformattedItem } from './types.cjs';
interface CSSData {
common?: CSSUnformattedItem;
css: CSSUnformattedItem[];
errors: string[];
}
/**
* Get data for getIconsCSS()
*/
declare function getIconsCSSData(iconSet: IconifyJSON, names: string[], options?: IconCSSIconSetOptions): CSSData;
/**
* Get CSS for icons as background/mask
*/
declare function getIconsCSS(iconSet: IconifyJSON, names: string[], options?: IconCSSIconSetOptions): string;
/**
* Get CSS for icons as content
*/
declare function getIconsContentCSS(iconSet: IconifyJSON, names: string[], options: IconContentIconSetOptions): string;
export { getIconsCSS, getIconsCSSData, getIconsContentCSS };
@@ -0,0 +1,22 @@
import { IconifyJSON } from '@iconify/types';
import { IconCSSIconSetOptions, IconContentIconSetOptions, CSSUnformattedItem } from './types.mjs';
interface CSSData {
common?: CSSUnformattedItem;
css: CSSUnformattedItem[];
errors: string[];
}
/**
* Get data for getIconsCSS()
*/
declare function getIconsCSSData(iconSet: IconifyJSON, names: string[], options?: IconCSSIconSetOptions): CSSData;
/**
* Get CSS for icons as background/mask
*/
declare function getIconsCSS(iconSet: IconifyJSON, names: string[], options?: IconCSSIconSetOptions): string;
/**
* Get CSS for icons as content
*/
declare function getIconsContentCSS(iconSet: IconifyJSON, names: string[], options: IconContentIconSetOptions): string;
export { getIconsCSS, getIconsCSSData, getIconsContentCSS };
@@ -0,0 +1,22 @@
import { IconifyJSON } from '@iconify/types';
import { IconCSSIconSetOptions, IconContentIconSetOptions, CSSUnformattedItem } from './types.js';
interface CSSData {
common?: CSSUnformattedItem;
css: CSSUnformattedItem[];
errors: string[];
}
/**
* Get data for getIconsCSS()
*/
declare function getIconsCSSData(iconSet: IconifyJSON, names: string[], options?: IconCSSIconSetOptions): CSSData;
/**
* Get CSS for icons as background/mask
*/
declare function getIconsCSS(iconSet: IconifyJSON, names: string[], options?: IconCSSIconSetOptions): string;
/**
* Get CSS for icons as content
*/
declare function getIconsContentCSS(iconSet: IconifyJSON, names: string[], options: IconContentIconSetOptions): string;
export { getIconsCSS, getIconsCSSData, getIconsContentCSS };
@@ -0,0 +1,168 @@
import { getIconData } from '../icon-set/get-icon.mjs';
import { defaultIconProps } from '../icon/defaults.mjs';
import { getCommonCSSRules, generateItemCSSRules, generateItemContent } from './common.mjs';
import { formatCSS } from './format.mjs';
import '../icon/merge.mjs';
import '../icon/transformations.mjs';
import '../icon-set/tree.mjs';
import '../svg/html.mjs';
import '../svg/size.mjs';
import '../svg/url.mjs';
import '../icon/square.mjs';
import '../svg/build.mjs';
import '../customisations/defaults.mjs';
import '../svg/defs.mjs';
const commonSelector = ".icon--{prefix}";
const iconSelector = ".icon--{prefix}--{name}";
const contentSelector = ".icon--{prefix}--{name}::after";
const defaultSelectors = {
commonSelector,
iconSelector,
overrideSelector: commonSelector + iconSelector
};
function getIconsCSSData(iconSet, names, options = {}) {
const css = [];
const errors = [];
const palette = options.color ? true : void 0;
let mode = options.mode || typeof palette === "boolean" && (palette ? "background" : "mask");
if (!mode) {
for (let i = 0; i < names.length; i++) {
const name = names[i];
const icon = getIconData(iconSet, name);
if (icon) {
const body = options.customise ? options.customise(icon.body, name) : icon.body;
mode = body.includes("currentColor") ? "mask" : "background";
break;
}
}
if (!mode) {
mode = "mask";
errors.push(
"/* cannot detect icon mode: not set in options and icon set is missing info, rendering as " + mode + " */"
);
}
}
let varName = options.varName;
if (varName === void 0 && mode === "mask") {
varName = "svg";
}
const newOptions = {
...options,
// Override mode and varName
mode,
varName
};
const { commonSelector: commonSelector2, iconSelector: iconSelector2, overrideSelector } = newOptions.iconSelector ? newOptions : defaultSelectors;
const iconSelectorWithPrefix = iconSelector2.replace(
/{prefix}/g,
iconSet.prefix
);
const commonRules = {
...options.rules,
...getCommonCSSRules(newOptions)
};
const hasCommonRules = commonSelector2 && commonSelector2 !== iconSelector2;
const commonSelectors = /* @__PURE__ */ new Set();
if (hasCommonRules) {
css.push({
selector: commonSelector2.replace(/{prefix}/g, iconSet.prefix),
rules: commonRules
});
}
for (let i = 0; i < names.length; i++) {
const name = names[i];
const iconData = getIconData(iconSet, name);
if (!iconData) {
errors.push("/* Could not find icon: " + name + " */");
continue;
}
const body = options.customise ? options.customise(iconData.body, name) : iconData.body;
const rules = generateItemCSSRules(
{
...defaultIconProps,
...iconData,
body
},
newOptions
);
let requiresOverride = false;
if (hasCommonRules && overrideSelector) {
for (const key in rules) {
if (key in commonRules) {
requiresOverride = true;
}
}
}
const selector = (requiresOverride && overrideSelector ? overrideSelector.replace(/{prefix}/g, iconSet.prefix) : iconSelectorWithPrefix).replace(/{name}/g, name);
css.push({
selector,
rules
});
if (!hasCommonRules) {
commonSelectors.add(selector);
}
}
const result = {
css,
errors
};
if (!hasCommonRules && commonSelectors.size) {
const selector = Array.from(commonSelectors).join(
newOptions.format === "compressed" ? "," : ", "
);
result.common = {
selector,
rules: commonRules
};
}
return result;
}
function getIconsCSS(iconSet, names, options = {}) {
const { css, errors, common } = getIconsCSSData(iconSet, names, options);
if (common) {
if (css.length === 1 && css[0].selector === common.selector) {
css[0].rules = {
// Common first, override later
...common.rules,
...css[0].rules
};
} else {
css.unshift(common);
}
}
return formatCSS(css, options.format) + (errors.length ? "\n" + errors.join("\n") + "\n" : "");
}
function getIconsContentCSS(iconSet, names, options) {
const errors = [];
const css = [];
const iconSelectorWithPrefix = (options.iconSelector ?? contentSelector).replace(/{prefix}/g, iconSet.prefix);
for (let i = 0; i < names.length; i++) {
const name = names[i];
const iconData = getIconData(iconSet, name);
if (!iconData) {
errors.push("/* Could not find icon: " + name + " */");
continue;
}
const body = options.customise ? options.customise(iconData.body, name) : iconData.body;
const content = generateItemContent(
{
...defaultIconProps,
...iconData,
body
},
options
);
const selector = iconSelectorWithPrefix.replace(/{name}/g, name);
css.push({
selector,
rules: {
...options.rules,
content
}
});
}
return formatCSS(css, options.format) + (errors.length ? "\n" + errors.join("\n") + "\n" : "");
}
export { getIconsCSS, getIconsCSSData, getIconsContentCSS };
@@ -0,0 +1,2 @@
'use strict';
@@ -0,0 +1,107 @@
/**
* Icon mode
*/
type IconCSSMode = 'mask' | 'background';
/**
* Selector for icon
*/
interface IconCSSIconSelectorOptions {
pseudoSelector?: boolean;
iconSelector?: string;
}
/**
* Selector for icon when generating data from icon set
*/
interface IconCSSSelectorOptions extends IconCSSIconSelectorOptions {
commonSelector?: string;
overrideSelector?: string;
}
/**
* Options common for both multiple icons and single icon
*/
interface IconCSSSharedOptions {
varName?: string | null;
forceSquare?: boolean;
color?: string;
rules?: Record<string, string>;
}
/**
* Mode
*/
interface IconCSSModeOptions {
mode?: IconCSSMode;
}
/**
* Options for generating common code
*
* Requires mode
*/
interface IconCSSCommonCodeOptions extends IconCSSSharedOptions, IconCSSIconSelectorOptions, Required<IconCSSModeOptions> {
}
/**
* Options for generating data for one icon
*/
interface IconCSSItemOptions extends IconCSSSharedOptions, Required<IconCSSModeOptions> {
}
/**
* Selector for icon
*/
interface IconContentIconSelectorOptions {
iconSelector?: string;
}
/**
* Options common for both multiple icons and single icon
*/
interface IconContentSharedOptions {
height: number;
width?: number;
color?: string;
rules?: Record<string, string>;
}
/**
* Options for generating data for one icon
*/
type IconContentItemOptions = IconContentSharedOptions;
/**
* Formatting modes. Same as in SASS
*/
type CSSFormatMode = 'expanded' | 'compact' | 'compressed';
/**
* Item to format
*/
interface CSSUnformattedItem {
selector: string | string[];
rules: Record<string, string>;
}
/**
* Formatting options
*/
interface IconCSSFormatOptions {
format?: CSSFormatMode;
}
/**
* Options for generating data for one icon as background/mask
*/
interface IconCSSIconOptions extends IconCSSSharedOptions, IconCSSIconSelectorOptions, IconCSSModeOptions, IconCSSFormatOptions {
customise?: (content: string) => string;
}
/**
* Options for generating data for one icon as content
*/
interface IconContentIconOptions extends IconContentSharedOptions, IconContentIconSelectorOptions, IconCSSFormatOptions {
customise?: (content: string) => string;
}
/**
* Options for generating multiple icons as background/mask
*/
interface IconCSSIconSetOptions extends IconCSSSharedOptions, IconCSSSelectorOptions, IconCSSModeOptions, IconCSSFormatOptions {
customise?: (content: string, name: string) => string;
}
/**
* Options for generating multiple icons as content
*/
interface IconContentIconSetOptions extends IconContentSharedOptions, IconContentIconSelectorOptions, IconCSSFormatOptions {
customise?: (content: string, name: string) => string;
}
export type { CSSFormatMode, CSSUnformattedItem, IconCSSCommonCodeOptions, IconCSSFormatOptions, IconCSSIconOptions, IconCSSIconSelectorOptions, IconCSSIconSetOptions, IconCSSItemOptions, IconCSSMode, IconCSSModeOptions, IconCSSSelectorOptions, IconCSSSharedOptions, IconContentIconOptions, IconContentIconSelectorOptions, IconContentIconSetOptions, IconContentItemOptions, IconContentSharedOptions };
@@ -0,0 +1,107 @@
/**
* Icon mode
*/
type IconCSSMode = 'mask' | 'background';
/**
* Selector for icon
*/
interface IconCSSIconSelectorOptions {
pseudoSelector?: boolean;
iconSelector?: string;
}
/**
* Selector for icon when generating data from icon set
*/
interface IconCSSSelectorOptions extends IconCSSIconSelectorOptions {
commonSelector?: string;
overrideSelector?: string;
}
/**
* Options common for both multiple icons and single icon
*/
interface IconCSSSharedOptions {
varName?: string | null;
forceSquare?: boolean;
color?: string;
rules?: Record<string, string>;
}
/**
* Mode
*/
interface IconCSSModeOptions {
mode?: IconCSSMode;
}
/**
* Options for generating common code
*
* Requires mode
*/
interface IconCSSCommonCodeOptions extends IconCSSSharedOptions, IconCSSIconSelectorOptions, Required<IconCSSModeOptions> {
}
/**
* Options for generating data for one icon
*/
interface IconCSSItemOptions extends IconCSSSharedOptions, Required<IconCSSModeOptions> {
}
/**
* Selector for icon
*/
interface IconContentIconSelectorOptions {
iconSelector?: string;
}
/**
* Options common for both multiple icons and single icon
*/
interface IconContentSharedOptions {
height: number;
width?: number;
color?: string;
rules?: Record<string, string>;
}
/**
* Options for generating data for one icon
*/
type IconContentItemOptions = IconContentSharedOptions;
/**
* Formatting modes. Same as in SASS
*/
type CSSFormatMode = 'expanded' | 'compact' | 'compressed';
/**
* Item to format
*/
interface CSSUnformattedItem {
selector: string | string[];
rules: Record<string, string>;
}
/**
* Formatting options
*/
interface IconCSSFormatOptions {
format?: CSSFormatMode;
}
/**
* Options for generating data for one icon as background/mask
*/
interface IconCSSIconOptions extends IconCSSSharedOptions, IconCSSIconSelectorOptions, IconCSSModeOptions, IconCSSFormatOptions {
customise?: (content: string) => string;
}
/**
* Options for generating data for one icon as content
*/
interface IconContentIconOptions extends IconContentSharedOptions, IconContentIconSelectorOptions, IconCSSFormatOptions {
customise?: (content: string) => string;
}
/**
* Options for generating multiple icons as background/mask
*/
interface IconCSSIconSetOptions extends IconCSSSharedOptions, IconCSSSelectorOptions, IconCSSModeOptions, IconCSSFormatOptions {
customise?: (content: string, name: string) => string;
}
/**
* Options for generating multiple icons as content
*/
interface IconContentIconSetOptions extends IconContentSharedOptions, IconContentIconSelectorOptions, IconCSSFormatOptions {
customise?: (content: string, name: string) => string;
}
export type { CSSFormatMode, CSSUnformattedItem, IconCSSCommonCodeOptions, IconCSSFormatOptions, IconCSSIconOptions, IconCSSIconSelectorOptions, IconCSSIconSetOptions, IconCSSItemOptions, IconCSSMode, IconCSSModeOptions, IconCSSSelectorOptions, IconCSSSharedOptions, IconContentIconOptions, IconContentIconSelectorOptions, IconContentIconSetOptions, IconContentItemOptions, IconContentSharedOptions };
@@ -0,0 +1,107 @@
/**
* Icon mode
*/
type IconCSSMode = 'mask' | 'background';
/**
* Selector for icon
*/
interface IconCSSIconSelectorOptions {
pseudoSelector?: boolean;
iconSelector?: string;
}
/**
* Selector for icon when generating data from icon set
*/
interface IconCSSSelectorOptions extends IconCSSIconSelectorOptions {
commonSelector?: string;
overrideSelector?: string;
}
/**
* Options common for both multiple icons and single icon
*/
interface IconCSSSharedOptions {
varName?: string | null;
forceSquare?: boolean;
color?: string;
rules?: Record<string, string>;
}
/**
* Mode
*/
interface IconCSSModeOptions {
mode?: IconCSSMode;
}
/**
* Options for generating common code
*
* Requires mode
*/
interface IconCSSCommonCodeOptions extends IconCSSSharedOptions, IconCSSIconSelectorOptions, Required<IconCSSModeOptions> {
}
/**
* Options for generating data for one icon
*/
interface IconCSSItemOptions extends IconCSSSharedOptions, Required<IconCSSModeOptions> {
}
/**
* Selector for icon
*/
interface IconContentIconSelectorOptions {
iconSelector?: string;
}
/**
* Options common for both multiple icons and single icon
*/
interface IconContentSharedOptions {
height: number;
width?: number;
color?: string;
rules?: Record<string, string>;
}
/**
* Options for generating data for one icon
*/
type IconContentItemOptions = IconContentSharedOptions;
/**
* Formatting modes. Same as in SASS
*/
type CSSFormatMode = 'expanded' | 'compact' | 'compressed';
/**
* Item to format
*/
interface CSSUnformattedItem {
selector: string | string[];
rules: Record<string, string>;
}
/**
* Formatting options
*/
interface IconCSSFormatOptions {
format?: CSSFormatMode;
}
/**
* Options for generating data for one icon as background/mask
*/
interface IconCSSIconOptions extends IconCSSSharedOptions, IconCSSIconSelectorOptions, IconCSSModeOptions, IconCSSFormatOptions {
customise?: (content: string) => string;
}
/**
* Options for generating data for one icon as content
*/
interface IconContentIconOptions extends IconContentSharedOptions, IconContentIconSelectorOptions, IconCSSFormatOptions {
customise?: (content: string) => string;
}
/**
* Options for generating multiple icons as background/mask
*/
interface IconCSSIconSetOptions extends IconCSSSharedOptions, IconCSSSelectorOptions, IconCSSModeOptions, IconCSSFormatOptions {
customise?: (content: string, name: string) => string;
}
/**
* Options for generating multiple icons as content
*/
interface IconContentIconSetOptions extends IconContentSharedOptions, IconContentIconSelectorOptions, IconCSSFormatOptions {
customise?: (content: string, name: string) => string;
}
export type { CSSFormatMode, CSSUnformattedItem, IconCSSCommonCodeOptions, IconCSSFormatOptions, IconCSSIconOptions, IconCSSIconSelectorOptions, IconCSSIconSetOptions, IconCSSItemOptions, IconCSSMode, IconCSSModeOptions, IconCSSSelectorOptions, IconCSSSharedOptions, IconContentIconOptions, IconContentIconSelectorOptions, IconContentIconSetOptions, IconContentItemOptions, IconContentSharedOptions };
@@ -0,0 +1 @@
@@ -0,0 +1,24 @@
'use strict';
function toBoolean(name, value, defaultValue) {
switch (typeof value) {
case "boolean":
return value;
case "number":
return !!value;
case "string":
switch (value.toLowerCase()) {
case "1":
case "true":
case name.toLowerCase():
return true;
case "0":
case "false":
case "":
return false;
}
}
return defaultValue;
}
exports.toBoolean = toBoolean;
@@ -0,0 +1,6 @@
/**
* Get boolean customisation value from attribute
*/
declare function toBoolean(name: string, value: unknown, defaultValue: boolean): boolean;
export { toBoolean };
@@ -0,0 +1,6 @@
/**
* Get boolean customisation value from attribute
*/
declare function toBoolean(name: string, value: unknown, defaultValue: boolean): boolean;
export { toBoolean };
@@ -0,0 +1,6 @@
/**
* Get boolean customisation value from attribute
*/
declare function toBoolean(name: string, value: unknown, defaultValue: boolean): boolean;
export { toBoolean };
@@ -0,0 +1,22 @@
function toBoolean(name, value, defaultValue) {
switch (typeof value) {
case "boolean":
return value;
case "number":
return !!value;
case "string":
switch (value.toLowerCase()) {
case "1":
case "true":
case name.toLowerCase():
return true;
case "0":
case "false":
case "":
return false;
}
}
return defaultValue;
}
export { toBoolean };

Some files were not shown because too many files have changed in this diff Show More