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

chore(icons): Using svg image tag when rendering an icon from an external domain #3708

Draft
wants to merge 14 commits into
base: v4-dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
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

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
path: icon.path|default(''),
name: icon.name|default(''),
size: icon.size|default('s'),
cors: icon.cors|default(false),
},
extra_classes: 'ecl-accordion__toggle-icon' ~ icon.extra_classes|default(''),
extra_attributes: icon.extra_attributes|default([{}])|merge([{ name: "data-ecl-accordion-icon" }]),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { withNotes } from '@ecl/storybook-addon-notes';
import withCode from '@ecl/storybook-addon-code';
import { correctPaths } from '@ecl/story-utils';

import demoData from '@ecl/specs-component-accordion/demo/data';
import accordion from './accordion.html.twig';
Expand Down Expand Up @@ -51,7 +50,6 @@ const getArgTypes = (data) => {
};

const prepareData = (data, args) => {
correctPaths(data);
data.items.forEach((item, i) => {
item.toggle.label = args[`toggle${i + 1}`];
item.content = args[`content${i + 1}`];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@ exports[`Fact and figures 1 col renders correctly 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -78,10 +81,13 @@ exports[`Fact and figures 1 col renders correctly when centerd 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -142,10 +148,13 @@ exports[`Fact and figures 1 col renders correctly whit large icons 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--2xl ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -208,10 +217,13 @@ exports[`Fact and figures 1 col renders correctly with extra attributes 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -272,10 +284,13 @@ exports[`Fact and figures 1 col renders correctly with extra class names 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -336,10 +351,13 @@ exports[`Fact and figures 2 cols renders correctly 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -428,10 +446,13 @@ exports[`Fact and figures 3 cols renders correctly 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -632,10 +653,13 @@ exports[`Fact and figures 4 cols renders correctly 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#infographic"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#infographic"
/>
</svg>
<div
Expand Down Expand Up @@ -828,10 +852,13 @@ exports[`Fact and figures 4 cols renders correctly 1`] = `
<svg
aria-hidden="true"
class="ecl-icon ecl-icon--l ecl-fact-figures__icon"
data-ecl-auto-init="Icon"
data-ecl-icon=""
focusable="false"
>
<use
xlink:href="/icons.svg#presentation"
<image
crossorigin="anonymous"
href="https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg#presentation"
/>
</svg>
<div
Expand Down
17 changes: 17 additions & 0 deletions src/implementations/twig/components/icon/icon.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,16 @@

{# Internal properties #}

{% set extra_attributes = extra_attributes|default([{}]) %}

{% set _icon = {
path: '',
name: '',
size: 'm',
transform: '',
color: '',
title: '',
cors: false,
}|merge(icon|default({})) %}

{% set _extra_accessibility = {
Expand All @@ -48,6 +51,13 @@
role: '',
}|merge(extra_accessibility|default({})) %}

{% if _icon.cors %}
{% set extra_attributes = extra_attributes|merge([
{ name: 'data-ecl-auto-init', value: 'Icon' },
{ name: 'data-ecl-icon' },
]) %}
{% endif %}

{% set _as_image = as_image|default(false) %}
{% set _aria_hidden = 'true' %}

Expand Down Expand Up @@ -120,7 +130,14 @@
{{- _extra_accessibility.description -}}
</desc>
{% endif %}
{% if _icon.cors %}
<image
crossorigin="anonymous"
href="{{ _icon.path }}#{{ _icon.name }}"
>
{% else %}
<use xlink:href="{{ _icon.path }}#{{ _icon.name }}"></use>
{% endif %}
</svg>

{% endapply %}
7 changes: 7 additions & 0 deletions src/implementations/twig/components/icon/icon.story.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const getArgs = (data) => ({
color: 'default',
transform: 'none',
title: '',
path: 'local',
});

const getArgTypes = (data, icons) => getIconControls(data, icons, iconMapping);
Expand All @@ -30,13 +31,19 @@ const prepareData = (data, args) => {
if (args.transformation === 'none') {
args.transformation = '';
}
data.icon.path = args.path;

correctPaths(data);
data.icon.title = args.title;
data.icon.name = args.name;
data.icon.size = args.size;
data.icon.color = args.color;
data.extra_classes = data.icon.color === 'inverted' ? 'ecl-u-bg-dark' : '';
data.icon.transform = args.transform;
if (args.path !== 'local') {
data.icon.cors = true;
}

return data;
};

Expand Down
104 changes: 104 additions & 0 deletions src/implementations/vanilla/components/icon/icon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/**
* @param {HTMLElement} element DOM element for component instantiation and scope
*/
export class Icon {
/**
* @static
* Shorthand for instance creation and initialisation.
*
* @param {HTMLElement} root DOM element for component instantiation and scope
*
* @return {Icon} An instance of Icon.
*/
static autoInit(root, { ICON: defaultOptions = {} } = {}) {
const icon = new Icon(root, defaultOptions);
icon.init();
root.ECLIcon = icon;
return icon;
}

constructor(element, { iconSelector = '[data-ecl-icon]' } = {}) {
// Check element
if (!element || element.nodeType !== Node.ELEMENT_NODE) {
throw new TypeError(
'DOM element should be given to initialize this widget.',
);
}

this.element = element;
this.iconSelector = iconSelector;
this.cache = new Map();
}

/**
* Initialise component.
*/
init() {
if (!ECL) {
throw new TypeError('Called init but ECL is not present');
}

ECL.components = ECL.components || new Map();

this.inlineSVG();

this.element.setAttribute('data-ecl-auto-initialized', 'true');
ECL.components.set(this.element, this);
}

/**
* Method used to inline the svg.
*/
inlineSVG = async () => {
const imageElement = this.element.querySelector('image');
if (!imageElement) return;

const iconUrl = imageElement.getAttribute('href');
const [url, symbolId] = iconUrl.split('#');

if (this.cache.has(url)) {
this.renderSymbol(this.cache.get(url), symbolId);
return;
}

try {
const response = await fetch(url, { mode: 'cors' });
const svgText = await response.text();
this.cache.set(url, svgText);

const parser = new DOMParser();
const svgDocument = parser.parseFromString(svgText, 'image/svg+xml');
const symbolElement = svgDocument.getElementById(symbolId);

if (symbolElement) {
const viewBox = symbolElement.getAttribute('viewBox');
const parentSVG = imageElement.parentElement;

const fragment = document.createDocumentFragment();
Array.from(symbolElement.childNodes).forEach((node) =>
fragment.appendChild(node.cloneNode(true)),
);

parentSVG.replaceChild(fragment, imageElement);

if (viewBox) {
parentSVG.setAttribute('viewBox', viewBox);
}
}
} catch (error) {
console.error('Error inlining SVG:', error);
}
};

/**
* Destroy component.
*/
destroy() {
if (this.element) {
this.element.removeAttribute('data-ecl-auto-initialized');
ECL.components.delete(this.element);
}
}
}

export default Icon;
5 changes: 2 additions & 3 deletions src/implementations/vanilla/components/icon/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
"description": "ECL Icons",
"style": "icon.scss",
"sass": "icon.scss",
"peerDependencies": {
"svg4everybody": "^2.1.9"
},
"main": "icon.js",
"module": "icon.js",
"publishConfig": {
"access": "public"
},
Expand Down
25 changes: 25 additions & 0 deletions src/playground/addons/story-utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import iconFlagPath from '@ecl/resources-flag-icons/dist/sprites/icons-flag.svg'
export const correctPaths = (data) => {
Object.keys(data).forEach((prop) => {
if (typeof data[prop] === 'string' && data[prop].includes('.svg')) {
if (data[prop].startsWith('https://cdn')) {
return;
}
if (data[prop].includes('social-media')) {
data[prop] = iconMediaSocialPath;
} else if (data[prop].includes('social')) {
Expand Down Expand Up @@ -149,6 +152,28 @@ export const getIconControls = (data, icons, mapping) => {
},
if: { arg: 'name', neq: 'none' },
};
argTypes.path = {
name: 'icon path',
type: 'select',
description: 'When selecting remote, the svg will be inlined',
options: ['local', 'remote'],
labels: {
local: '/icons.svg',
remote:
'https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg',
},
mapping: {
local: '/icons.svg',
remote:
'https://cdn1.fpfis.tech.ec.europa.eu/ecl/unversioned/icons-current.svg',
},
table: {
type: { summary: 'string' },
defaultValue: { summary: '' },
category: 'Icon',
},
if: { arg: 'name', neq: 'none' },
};

return argTypes;
};
Expand Down
Loading
Loading