Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | 1x 1x 1x 59x 19x 19x 9x 41x 41x 41x 41x 41x 1x 31x 41x 34x 34x 41x 34x 34x 22x 22x 19x 32x 10x 22x 22x 22x 40x 19x 19x 6x 13x 10x 9x 9x 2x 7x 7x 7x 7x 9x 1x 12x 32x 32x 19x 19x 7x 19x 13x 55x 55x 5x 5x 5x 41x 32x 32x 25x 25x 25x 25x 25x 9x 4x 41x 41x 1x 1x 1x | import { LightningElement, api } from 'lwc';
import { reflectAttribute } from 'sds/utils';
const sdsFigureParser = new DOMParser();
// Names only allow letters, digits, _ and -, so they can't change the path of the resolved URL
const VALID_SET = /^[a-zA-Z]+$/;
const VALID_SYMBOL = /^[a-zA-Z][A-Za-z0-9_-]*$/;
/**
* Validates if the provided set or symbol name matches the allowed pattern.
*
* @param {RegExp} pattern
* @param {string} name
* @returns {boolean}
*/
function isValidName(pattern, name) {
return typeof name === 'string' && pattern.test(name);
}
/**
* Validates if the provided URL is an SVG file.
* The path must end in .svg, optionally followed by a query string, and must not contain ".." or an encoded dot (%2e).
*
* @param {string} url
* @returns {boolean}
*/
function isValidSvgUrl(url) {
const svgUrlPattern = /^[^?#]*\.svg(\?[^#]*)?$/i;
return typeof url === 'string' && !/\.\.|%2e/i.test(url) && svgUrlPattern.test(url);
}
/**
* Validates if the provided content type is an SVG.
* The media type must be exactly image/svg+xml; parameters such as charset are ignored.
*
* @param {string} contentType
* @returns {boolean}
*/
function isValidContentType(contentType) {
return (
typeof contentType === 'string' && contentType.split(';')[0].trim().toLowerCase() === 'image/svg+xml'
);
}
export default class Figure extends LightningElement {
static shadowSupportMode = 'native';
_set;
_symbol;
_figureSets = new Map();
_generatedFigure = false; // set and symbol generated figure
/**
* An array of figure sets to use when resolving the figure.
*
* @type {Array}
*/
@api
get figureSets() {
return this._figureSets;
}
set figureSets(value) {
this._figureSets = new Map(value.map((item) => [item.name, item]));
}
/**
* The name of the figure set to use when resolving the illustration.
*
* @type {string}
*/
@api
get set() {
return this._set;
}
set set(value) {
this._set = value;
reflectAttribute(this, 'set', this._set);
}
/**
* The name of the figure to resolve.
*
* @type {string}
*/
@api
get symbol() {
return this._symbol;
}
set symbol(value) {
this._symbol = value;
reflectAttribute(this, 'symbol', this._symbol);
}
/**
* Retrieve a figure set
*
* @param {string} name
*/
getFigureSet(name) {
return this._figureSets.get(name);
}
/**
* Return the resolver (url) for a figure set
*
* @param {string} set
* @param {string} symbol
*/
getFigureUrl(figureSet, set, symbol) {
if (figureSet && symbol) {
return figureSet.resolver(set, symbol);
}
}
/**
* Return the parameters of a symbol in an object for easier reference.
* Returns an empty object if set or symbol is not a valid name.
*
* @param {string} set
* @param {string} symbol
*/
getSymbolParams(set, symbol) {
if (!isValidName(VALID_SET, set) || !isValidName(VALID_SYMBOL, symbol)) {
return {};
}
const figureSet = this.getFigureSet(set);
const url = this.getFigureUrl(figureSet, set, symbol);
return {
figureSet,
url,
};
}
/**
* Check if the figure set and symbol are set.
*
* @returns {boolean}
*/
hasFigureConfigured() {
return Boolean(this._set && this._symbol);
}
async fetchFigure(url) {
try {
// Validate url
if (!isValidSvgUrl(url)) {
throw new Error(`Invalid URL: ${url}. Only SVG files are allowed.`);
}
const response = await fetch(url);
if (response.ok) {
const contentType = response.headers.get('content-type');
if (!isValidContentType(contentType)) {
throw new Error(`Invalid content type: ${contentType}. Only SVG files are allowed.`);
}
const fetchText = await response.text();
// sanitize fetchText
const parsedFetchDoc = sdsFigureParser.parseFromString(fetchText, 'text/html');
const parsedSvgEl = parsedFetchDoc.body.querySelector('svg');
const result = {
url: url,
svg: parsedSvgEl && parsedSvgEl.tagName.toLowerCase() === 'svg' ? parsedSvgEl : '',
};
return result;
} else {
throw new Error(`There's an error: Fetch response.ok is false.`);
}
} catch (error) {
// eslint-disable-next-line preserve-caught-error
throw new Error(error.message || `Network error: There's an error in the fetch API.`);
}
}
/**
* Create the figure (entry point)
*/
async createFigure() {
const { figureSet, url } = this.getSymbolParams(this._set, this._symbol);
if (figureSet && url) {
const slotContainer = !this._generatedFigure
? this.refs.illustration
: this.template.querySelector(`svg`);
const figure = await this.fetchFigure(url);
// Add the SVG as the fallback content of the slot
!this._generatedFigure ? slotContainer.appendChild(figure.svg) : slotContainer.replaceWith(figure.svg);
this._generatedFigure = true;
} else {
throw new Error(
`Unable to create a figure using set: ${this._set}, symbol: ${this._symbol} and URL: ${url}. Double check your registered figureSet name(s) and path(s)`,
);
}
}
/**
* Check if the slot has slotted content
*
*I @returns {boolean}
*/
hasSlottedChildren() {
const slot = this.template.querySelector('slot');
return slot.assignedNodes({ flatten: true }).length !== 0;
}
I
/**
* Handle slotchange event
*/
async handleSlotChange() {
// Remove figure generated by API to make room for slotted content
if (this._generatedFigure) {
this.template.querySelector('svg').remove();
this._generatedFigure = false;
}
try {
// Recreate figure if slot is emptied and figures are configured
if (!this.hasSlottedChildren() && !this._generatedFigure && this.hasFigureConfigured()) {
await this.createFigure();
}
} catch (error) {
// Using console.error as SDS has no control over slotted content
console.error(
error.message ||
'Error: Unable to create sds-figure. There is no slotted figure. Check all required APIs.',
);
}
}
/**
* RenderedCallback LWC lifecycle
*/
async renderedCallback() {
if (!this.hasSlottedChildren() && this.hasFigureConfigured()) {
try {
await this.createFigure();
} catch (error) {
// Clear previous error messages
this.template.querySelectorAll('.slds-figure_error').forEach((el) => el.remove());
const div = document.createElement('div');
div.classList.add('slds-figure_error');
div.textContent = `Error: ${error.message || 'Could not create figure'}`;
this.template.appendChild(div);
}
} else if (!this.hasSlottedChildren() && !this.hasFigureConfigured()) {
// If figure has not been configured
console.error('Error: Unable to create sds-figure. Check all required APIs.');
}
// set aria-hidden based on aria-label value
this.ariaHidden = this.ariaLabel ? 'false' : 'true';
// set role="img" on host
this.role = 'img';
}
}
|