Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: revert to simple icons decoration and extract the spriting logic #253

Closed
wants to merge 7 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 19 additions & 68 deletions scripts/lib-franklin.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,79 +157,30 @@ export function toCamelCase(name) {
return toClassName(name).replace(/-([a-z])/g, (g) => g[1].toUpperCase());
}

const ICONS_CACHE = {};
/**
* Replace icons with inline SVG and prefix with codeBasePath.
* @param {Element} [element] Element containing icons
* Add <img> for icon, prefixed with codeBasePath and optional prefix.
* @param {span} [element] span element with icon classes
* @param {string} [prefix] prefix to be added to icon the src
*/
export async function decorateIcons(element) {
// Prepare the inline sprite
let svgSprite = document.getElementById('franklin-svg-sprite');
if (!svgSprite) {
const div = document.createElement('div');
div.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" id="franklin-svg-sprite" style="display: none"></svg>';
svgSprite = div.firstElementChild;
document.body.append(div.firstElementChild);
}
export function decorateIcon(span, prefix = '') {
const iconName = Array.from(span.classList).find((c) => c.startsWith('icon-')).substring(5);
const img = document.createElement('img');
img.dataset.iconName = iconName;
img.src = `${prefix}/icons/${iconName}.svg`;
img.loading = 'lazy';

span.append(img);
}

// Download all new icons
/**
* Add <img> for icons, prefixed with codeBasePath and optional prefix.
* @param {Element} [element] Element containing icons
* @param {string} [prefix] prefix to be added to icon the src
*/
export function decorateIcons(element, prefix = '') {
const icons = [...element.querySelectorAll('span.icon')];
await Promise.all(icons.map(async (span) => {
const iconName = Array.from(span.classList).find((c) => c.startsWith('icon-')).substring(5);
if (!ICONS_CACHE[iconName]) {
ICONS_CACHE[iconName] = true;
try {
const response = await fetch(`${window.hlx.codeBasePath}/icons/${iconName}.svg`);
if (!response.ok) {
ICONS_CACHE[iconName] = false;
return;
}
// Styled icons don't play nice with the sprite approach because of shadow dom isolation
// and same for internal references
const svg = await response.text();
if (svg.match(/(<style | class=|url\(#| xlink:href="#)/)) {
ICONS_CACHE[iconName] = {
styled: true,
html: svg
// rescope ids and references to avoid clashes across icons;
.replaceAll(/ id="([^"]+)"/g, (_, id) => ` id="${iconName}-${id}"`)
.replaceAll(/="url\(#([^)]+)\)"/g, (_, id) => `="url(#${iconName}-${id})"`)
.replaceAll(/ xlink:href="#([^"]+)"/g, (_, id) => ` xlink:href="#${iconName}-${id}"`),
};
} else {
ICONS_CACHE[iconName] = {
html: svg
.replace('<svg', `<symbol id="icons-sprite-${iconName}"`)
.replace(/ width=".*?"/, '')
.replace(/ height=".*?"/, '')
.replace('</svg>', '</symbol>'),
};
}
} catch (error) {
ICONS_CACHE[iconName] = false;
// eslint-disable-next-line no-console
console.error(error);
}
}
}));

const symbols = Object
.keys(ICONS_CACHE).filter((k) => !svgSprite.querySelector(`#icons-sprite-${k}`))
.map((k) => ICONS_CACHE[k])
.filter((v) => !v.styled)
.map((v) => v.html)
.join('\n');
svgSprite.innerHTML += symbols;

icons.forEach((span) => {
const iconName = Array.from(span.classList).find((c) => c.startsWith('icon-')).substring(5);
const parent = span.firstElementChild?.tagName === 'A' ? span.firstElementChild : span;
// Styled icons need to be inlined as-is, while unstyled ones can leverage the sprite
if (ICONS_CACHE[iconName].styled) {
parent.innerHTML = ICONS_CACHE[iconName].html;
} else {
parent.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg"><use href="#icons-sprite-${iconName}"/></svg>`;
}
decorateIcon(span, prefix);
});
}

Expand Down