eleventy-plugin-tabler-icons/tablericons.js

58 lines
1.8 KiB
JavaScript

import ICONS from './icons.js';
const tablericons = (eleventyConfig, config = {}) => {
const { className = '', errorOnMissing = false } = config;
const renderIcon = (context = {}, name, alt = '', attrs = {}) => {
const contents = ICONS[name];
if (!contents) {
handleMissingIcon(name, context.page?.inputPath);
return '';
}
return `${buildHead(alt, className, name, attrs)}${contents}${ICONS.TAIL}`;
};
const handleMissingIcon = (name, inputPath) => {
const message = `No tablericon found for name '${name}'`;
if (errorOnMissing) {
throw new Error(message);
} else {
console.warn(`${message}${inputPath ? ` in ${inputPath}` : ''}`);
}
};
eleventyConfig.addShortcode('tablericon', function (name, alt, attrs) {
return renderIcon(this, name, alt, attrs);
});
};
const buildHead = (alt = '', className = '', iconName, attrs = {}) => {
let output = `${ICONS.HEAD.slice(0, -1)} aria-hidden="true"`;
if (className) output += ` class="${className}"`;
output += ` data-tablericon-name="${iconName}"`;
if (typeof attrs === 'string') {
output += ` ${attrs}`;
} else if (attrs && typeof attrs === 'object') {
output += Object.entries(attrs)
.map(([key, val]) => (key && val ? ` ${key}="${val}"` : ''))
.join('');
}
return `${output}>`;
};
export function renderTablerIcon(name, alt = '', attrs = {}, options = {}) {
const context = { page: { inputPath: options.inputPath || '' } };
const contents = ICONS[name];
if (!contents) {
console.warn(`No tablericon found for name '${name}'${options.inputPath ? ` in ${options.inputPath}` : ''}`);
return '';
}
return `${buildHead(alt, options.className || '', name, attrs)}${contents}${ICONS.TAIL}`;
}
export default tablericons;