offline.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. import { h, defineComponent } from 'vue';
  2. const defaultIconDimensions = Object.freeze(
  3. {
  4. left: 0,
  5. top: 0,
  6. width: 16,
  7. height: 16
  8. }
  9. );
  10. const defaultIconTransformations = Object.freeze({
  11. rotate: 0,
  12. vFlip: false,
  13. hFlip: false
  14. });
  15. const defaultIconProps = Object.freeze({
  16. ...defaultIconDimensions,
  17. ...defaultIconTransformations
  18. });
  19. const defaultExtendedIconProps = Object.freeze({
  20. ...defaultIconProps,
  21. body: "",
  22. hidden: false
  23. });
  24. function mergeIconTransformations(obj1, obj2) {
  25. const result = {};
  26. if (!obj1.hFlip !== !obj2.hFlip) {
  27. result.hFlip = true;
  28. }
  29. if (!obj1.vFlip !== !obj2.vFlip) {
  30. result.vFlip = true;
  31. }
  32. const rotate = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;
  33. if (rotate) {
  34. result.rotate = rotate;
  35. }
  36. return result;
  37. }
  38. function mergeIconData(parent, child) {
  39. const result = mergeIconTransformations(parent, child);
  40. for (const key in defaultExtendedIconProps) {
  41. if (key in defaultIconTransformations) {
  42. if (key in parent && !(key in result)) {
  43. result[key] = defaultIconTransformations[key];
  44. }
  45. } else if (key in child) {
  46. result[key] = child[key];
  47. } else if (key in parent) {
  48. result[key] = parent[key];
  49. }
  50. }
  51. return result;
  52. }
  53. function getIconsTree(data, names) {
  54. const icons = data.icons;
  55. const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  56. const resolved = /* @__PURE__ */ Object.create(null);
  57. function resolve(name) {
  58. if (icons[name]) {
  59. return resolved[name] = [];
  60. }
  61. if (!(name in resolved)) {
  62. resolved[name] = null;
  63. const parent = aliases[name] && aliases[name].parent;
  64. const value = parent && resolve(parent);
  65. if (value) {
  66. resolved[name] = [parent].concat(value);
  67. }
  68. }
  69. return resolved[name];
  70. }
  71. (names || Object.keys(icons).concat(Object.keys(aliases))).forEach(resolve);
  72. return resolved;
  73. }
  74. function internalGetIconData(data, name, tree) {
  75. const icons = data.icons;
  76. const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  77. let currentProps = {};
  78. function parse(name2) {
  79. currentProps = mergeIconData(
  80. icons[name2] || aliases[name2],
  81. currentProps
  82. );
  83. }
  84. parse(name);
  85. tree.forEach(parse);
  86. return mergeIconData(data, currentProps);
  87. }
  88. function parseIconSet(data, callback) {
  89. const names = [];
  90. if (typeof data !== "object" || typeof data.icons !== "object") {
  91. return names;
  92. }
  93. if (data.not_found instanceof Array) {
  94. data.not_found.forEach((name) => {
  95. callback(name, null);
  96. names.push(name);
  97. });
  98. }
  99. const tree = getIconsTree(data);
  100. for (const name in tree) {
  101. const item = tree[name];
  102. if (item) {
  103. callback(name, internalGetIconData(data, name, item));
  104. names.push(name);
  105. }
  106. }
  107. return names;
  108. }
  109. const matchIconName = /^[a-z0-9]+(-[a-z0-9]+)*$/;
  110. const optionalPropertyDefaults = {
  111. provider: "",
  112. aliases: {},
  113. not_found: {},
  114. ...defaultIconDimensions
  115. };
  116. function checkOptionalProps(item, defaults) {
  117. for (const prop in defaults) {
  118. if (prop in item && typeof item[prop] !== typeof defaults[prop]) {
  119. return false;
  120. }
  121. }
  122. return true;
  123. }
  124. function quicklyValidateIconSet(obj) {
  125. if (typeof obj !== "object" || obj === null) {
  126. return null;
  127. }
  128. const data = obj;
  129. if (typeof data.prefix !== "string" || !obj.icons || typeof obj.icons !== "object") {
  130. return null;
  131. }
  132. if (!checkOptionalProps(obj, optionalPropertyDefaults)) {
  133. return null;
  134. }
  135. const icons = data.icons;
  136. for (const name in icons) {
  137. const icon = icons[name];
  138. if (!name.match(matchIconName) || typeof icon.body !== "string" || !checkOptionalProps(
  139. icon,
  140. defaultExtendedIconProps
  141. )) {
  142. return null;
  143. }
  144. }
  145. const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  146. for (const name in aliases) {
  147. const icon = aliases[name];
  148. const parent = icon.parent;
  149. if (!name.match(matchIconName) || typeof parent !== "string" || !icons[parent] && !aliases[parent] || !checkOptionalProps(
  150. icon,
  151. defaultExtendedIconProps
  152. )) {
  153. return null;
  154. }
  155. }
  156. return data;
  157. }
  158. const defaultIconSizeCustomisations = Object.freeze({
  159. width: null,
  160. height: null
  161. });
  162. const defaultIconCustomisations = Object.freeze({
  163. // Dimensions
  164. ...defaultIconSizeCustomisations,
  165. // Transformations
  166. ...defaultIconTransformations
  167. });
  168. function mergeCustomisations(defaults, item) {
  169. const result = {
  170. ...defaults
  171. };
  172. for (const key in item) {
  173. const value = item[key];
  174. const valueType = typeof value;
  175. if (key in defaultIconSizeCustomisations) {
  176. if (value === null || value && (valueType === "string" || valueType === "number")) {
  177. result[key] = value;
  178. }
  179. } else if (valueType === typeof result[key]) {
  180. result[key] = key === "rotate" ? value % 4 : value;
  181. }
  182. }
  183. return result;
  184. }
  185. const separator = /[\s,]+/;
  186. function flipFromString(custom, flip) {
  187. flip.split(separator).forEach((str) => {
  188. const value = str.trim();
  189. switch (value) {
  190. case "horizontal":
  191. custom.hFlip = true;
  192. break;
  193. case "vertical":
  194. custom.vFlip = true;
  195. break;
  196. }
  197. });
  198. }
  199. function rotateFromString(value, defaultValue = 0) {
  200. const units = value.replace(/^-?[0-9.]*/, "");
  201. function cleanup(value2) {
  202. while (value2 < 0) {
  203. value2 += 4;
  204. }
  205. return value2 % 4;
  206. }
  207. if (units === "") {
  208. const num = parseInt(value);
  209. return isNaN(num) ? 0 : cleanup(num);
  210. } else if (units !== value) {
  211. let split = 0;
  212. switch (units) {
  213. case "%":
  214. split = 25;
  215. break;
  216. case "deg":
  217. split = 90;
  218. }
  219. if (split) {
  220. let num = parseFloat(value.slice(0, value.length - units.length));
  221. if (isNaN(num)) {
  222. return 0;
  223. }
  224. num = num / split;
  225. return num % 1 === 0 ? cleanup(num) : 0;
  226. }
  227. }
  228. return defaultValue;
  229. }
  230. const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
  231. const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
  232. function calculateSize(size, ratio, precision) {
  233. if (ratio === 1) {
  234. return size;
  235. }
  236. precision = precision || 100;
  237. if (typeof size === "number") {
  238. return Math.ceil(size * ratio * precision) / precision;
  239. }
  240. if (typeof size !== "string") {
  241. return size;
  242. }
  243. const oldParts = size.split(unitsSplit);
  244. if (oldParts === null || !oldParts.length) {
  245. return size;
  246. }
  247. const newParts = [];
  248. let code = oldParts.shift();
  249. let isNumber = unitsTest.test(code);
  250. while (true) {
  251. if (isNumber) {
  252. const num = parseFloat(code);
  253. if (isNaN(num)) {
  254. newParts.push(code);
  255. } else {
  256. newParts.push(Math.ceil(num * ratio * precision) / precision);
  257. }
  258. } else {
  259. newParts.push(code);
  260. }
  261. code = oldParts.shift();
  262. if (code === void 0) {
  263. return newParts.join("");
  264. }
  265. isNumber = !isNumber;
  266. }
  267. }
  268. const isUnsetKeyword = (value) => value === "unset" || value === "undefined" || value === "none";
  269. function iconToSVG(icon, customisations) {
  270. const fullIcon = {
  271. ...defaultIconProps,
  272. ...icon
  273. };
  274. const fullCustomisations = {
  275. ...defaultIconCustomisations,
  276. ...customisations
  277. };
  278. const box = {
  279. left: fullIcon.left,
  280. top: fullIcon.top,
  281. width: fullIcon.width,
  282. height: fullIcon.height
  283. };
  284. let body = fullIcon.body;
  285. [fullIcon, fullCustomisations].forEach((props) => {
  286. const transformations = [];
  287. const hFlip = props.hFlip;
  288. const vFlip = props.vFlip;
  289. let rotation = props.rotate;
  290. if (hFlip) {
  291. if (vFlip) {
  292. rotation += 2;
  293. } else {
  294. transformations.push(
  295. "translate(" + (box.width + box.left).toString() + " " + (0 - box.top).toString() + ")"
  296. );
  297. transformations.push("scale(-1 1)");
  298. box.top = box.left = 0;
  299. }
  300. } else if (vFlip) {
  301. transformations.push(
  302. "translate(" + (0 - box.left).toString() + " " + (box.height + box.top).toString() + ")"
  303. );
  304. transformations.push("scale(1 -1)");
  305. box.top = box.left = 0;
  306. }
  307. let tempValue;
  308. if (rotation < 0) {
  309. rotation -= Math.floor(rotation / 4) * 4;
  310. }
  311. rotation = rotation % 4;
  312. switch (rotation) {
  313. case 1:
  314. tempValue = box.height / 2 + box.top;
  315. transformations.unshift(
  316. "rotate(90 " + tempValue.toString() + " " + tempValue.toString() + ")"
  317. );
  318. break;
  319. case 2:
  320. transformations.unshift(
  321. "rotate(180 " + (box.width / 2 + box.left).toString() + " " + (box.height / 2 + box.top).toString() + ")"
  322. );
  323. break;
  324. case 3:
  325. tempValue = box.width / 2 + box.left;
  326. transformations.unshift(
  327. "rotate(-90 " + tempValue.toString() + " " + tempValue.toString() + ")"
  328. );
  329. break;
  330. }
  331. if (rotation % 2 === 1) {
  332. if (box.left !== box.top) {
  333. tempValue = box.left;
  334. box.left = box.top;
  335. box.top = tempValue;
  336. }
  337. if (box.width !== box.height) {
  338. tempValue = box.width;
  339. box.width = box.height;
  340. box.height = tempValue;
  341. }
  342. }
  343. if (transformations.length) {
  344. body = '<g transform="' + transformations.join(" ") + '">' + body + "</g>";
  345. }
  346. });
  347. const customisationsWidth = fullCustomisations.width;
  348. const customisationsHeight = fullCustomisations.height;
  349. const boxWidth = box.width;
  350. const boxHeight = box.height;
  351. let width;
  352. let height;
  353. if (customisationsWidth === null) {
  354. height = customisationsHeight === null ? "1em" : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
  355. width = calculateSize(height, boxWidth / boxHeight);
  356. } else {
  357. width = customisationsWidth === "auto" ? boxWidth : customisationsWidth;
  358. height = customisationsHeight === null ? calculateSize(width, boxHeight / boxWidth) : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
  359. }
  360. const attributes = {};
  361. const setAttr = (prop, value) => {
  362. if (!isUnsetKeyword(value)) {
  363. attributes[prop] = value.toString();
  364. }
  365. };
  366. setAttr("width", width);
  367. setAttr("height", height);
  368. attributes.viewBox = box.left.toString() + " " + box.top.toString() + " " + boxWidth.toString() + " " + boxHeight.toString();
  369. return {
  370. attributes,
  371. body
  372. };
  373. }
  374. const regex = /\sid="(\S+)"/g;
  375. const randomPrefix = "IconifyId" + Date.now().toString(16) + (Math.random() * 16777216 | 0).toString(16);
  376. let counter = 0;
  377. function replaceIDs(body, prefix = randomPrefix) {
  378. const ids = [];
  379. let match;
  380. while (match = regex.exec(body)) {
  381. ids.push(match[1]);
  382. }
  383. if (!ids.length) {
  384. return body;
  385. }
  386. const suffix = "suffix" + (Math.random() * 16777216 | Date.now()).toString(16);
  387. ids.forEach((id) => {
  388. const newID = typeof prefix === "function" ? prefix(id) : prefix + (counter++).toString();
  389. const escapedID = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  390. body = body.replace(
  391. // Allowed characters before id: [#;"]
  392. // Allowed characters after id: [)"], .[a-z]
  393. new RegExp('([#;"])(' + escapedID + ')([")]|\\.[a-z])', "g"),
  394. "$1" + newID + suffix + "$3"
  395. );
  396. });
  397. body = body.replace(new RegExp(suffix, "g"), "");
  398. return body;
  399. }
  400. function iconToHTML(body, attributes) {
  401. let renderAttribsHTML = body.indexOf("xlink:") === -1 ? "" : ' xmlns:xlink="http://www.w3.org/1999/xlink"';
  402. for (const attr in attributes) {
  403. renderAttribsHTML += " " + attr + '="' + attributes[attr] + '"';
  404. }
  405. return '<svg xmlns="http://www.w3.org/2000/svg"' + renderAttribsHTML + ">" + body + "</svg>";
  406. }
  407. function encodeSVGforURL(svg) {
  408. return svg.replace(/"/g, "'").replace(/%/g, "%25").replace(/#/g, "%23").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\s+/g, " ");
  409. }
  410. function svgToData(svg) {
  411. return "data:image/svg+xml," + encodeSVGforURL(svg);
  412. }
  413. function svgToURL(svg) {
  414. return 'url("' + svgToData(svg) + '")';
  415. }
  416. const defaultExtendedIconCustomisations = {
  417. ...defaultIconCustomisations,
  418. inline: false,
  419. };
  420. /**
  421. * Default SVG attributes
  422. */
  423. const svgDefaults = {
  424. 'xmlns': 'http://www.w3.org/2000/svg',
  425. 'xmlns:xlink': 'http://www.w3.org/1999/xlink',
  426. 'aria-hidden': true,
  427. 'role': 'img',
  428. };
  429. /**
  430. * Style modes
  431. */
  432. const commonProps = {
  433. display: 'inline-block',
  434. };
  435. const monotoneProps = {
  436. backgroundColor: 'currentColor',
  437. };
  438. const coloredProps = {
  439. backgroundColor: 'transparent',
  440. };
  441. // Dynamically add common props to variables above
  442. const propsToAdd = {
  443. Image: 'var(--svg)',
  444. Repeat: 'no-repeat',
  445. Size: '100% 100%',
  446. };
  447. const propsToAddTo = {
  448. webkitMask: monotoneProps,
  449. mask: monotoneProps,
  450. background: coloredProps,
  451. };
  452. for (const prefix in propsToAddTo) {
  453. const list = propsToAddTo[prefix];
  454. for (const prop in propsToAdd) {
  455. list[prefix + prop] = propsToAdd[prop];
  456. }
  457. }
  458. /**
  459. * Aliases for customisations.
  460. * In Vue 'v-' properties are reserved, so v-flip must be renamed
  461. */
  462. const customisationAliases = {};
  463. ['horizontal', 'vertical'].forEach((prefix) => {
  464. const attr = prefix.slice(0, 1) + 'Flip';
  465. // vertical-flip
  466. customisationAliases[prefix + '-flip'] = attr;
  467. // v-flip
  468. customisationAliases[prefix.slice(0, 1) + '-flip'] = attr;
  469. // verticalFlip
  470. customisationAliases[prefix + 'Flip'] = attr;
  471. });
  472. /**
  473. * Fix size: add 'px' to numbers
  474. */
  475. function fixSize(value) {
  476. return value + (value.match(/^[-0-9.]+$/) ? 'px' : '');
  477. }
  478. /**
  479. * Render icon
  480. */
  481. const render = (
  482. // Icon must be validated before calling this function
  483. icon,
  484. // Partial properties
  485. props) => {
  486. // Split properties
  487. const customisations = mergeCustomisations(defaultExtendedIconCustomisations, props);
  488. const componentProps = { ...svgDefaults };
  489. // Check mode
  490. const mode = props.mode || 'svg';
  491. // Copy style
  492. const style = {};
  493. const propsStyle = props.style;
  494. const customStyle = typeof propsStyle === 'object' && !(propsStyle instanceof Array)
  495. ? propsStyle
  496. : {};
  497. // Get element properties
  498. for (let key in props) {
  499. const value = props[key];
  500. if (value === void 0) {
  501. continue;
  502. }
  503. switch (key) {
  504. // Properties to ignore
  505. case 'icon':
  506. case 'style':
  507. case 'onLoad':
  508. case 'mode':
  509. break;
  510. // Boolean attributes
  511. case 'inline':
  512. case 'hFlip':
  513. case 'vFlip':
  514. customisations[key] =
  515. value === true || value === 'true' || value === 1;
  516. break;
  517. // Flip as string: 'horizontal,vertical'
  518. case 'flip':
  519. if (typeof value === 'string') {
  520. flipFromString(customisations, value);
  521. }
  522. break;
  523. // Color: override style
  524. case 'color':
  525. style.color = value;
  526. break;
  527. // Rotation as string
  528. case 'rotate':
  529. if (typeof value === 'string') {
  530. customisations[key] = rotateFromString(value);
  531. }
  532. else if (typeof value === 'number') {
  533. customisations[key] = value;
  534. }
  535. break;
  536. // Remove aria-hidden
  537. case 'ariaHidden':
  538. case 'aria-hidden':
  539. // Vue transforms 'aria-hidden' property to 'ariaHidden'
  540. if (value !== true && value !== 'true') {
  541. delete componentProps['aria-hidden'];
  542. }
  543. break;
  544. default: {
  545. const alias = customisationAliases[key];
  546. if (alias) {
  547. // Aliases for boolean customisations
  548. if (value === true || value === 'true' || value === 1) {
  549. customisations[alias] = true;
  550. }
  551. }
  552. else if (defaultExtendedIconCustomisations[key] === void 0) {
  553. // Copy missing property if it does not exist in customisations
  554. componentProps[key] = value;
  555. }
  556. }
  557. }
  558. }
  559. // Generate icon
  560. const item = iconToSVG(icon, customisations);
  561. const renderAttribs = item.attributes;
  562. // Inline display
  563. if (customisations.inline) {
  564. style.verticalAlign = '-0.125em';
  565. }
  566. if (mode === 'svg') {
  567. // Add style
  568. componentProps.style = {
  569. ...style,
  570. ...customStyle,
  571. };
  572. // Add icon stuff
  573. Object.assign(componentProps, renderAttribs);
  574. // Counter for ids based on "id" property to render icons consistently on server and client
  575. let localCounter = 0;
  576. let id = props.id;
  577. if (typeof id === 'string') {
  578. // Convert '-' to '_' to avoid errors in animations
  579. id = id.replace(/-/g, '_');
  580. }
  581. // Add innerHTML and style to props
  582. componentProps['innerHTML'] = replaceIDs(item.body, id ? () => id + 'ID' + localCounter++ : 'iconifyVue');
  583. // Render icon
  584. return h('svg', componentProps);
  585. }
  586. // Render <span> with style
  587. const { body, width, height } = icon;
  588. const useMask = mode === 'mask' ||
  589. (mode === 'bg' ? false : body.indexOf('currentColor') !== -1);
  590. // Generate SVG
  591. const html = iconToHTML(body, {
  592. ...renderAttribs,
  593. width: width + '',
  594. height: height + '',
  595. });
  596. // Generate style
  597. componentProps.style = {
  598. ...style,
  599. '--svg': svgToURL(html),
  600. 'width': fixSize(renderAttribs.width),
  601. 'height': fixSize(renderAttribs.height),
  602. ...commonProps,
  603. ...(useMask ? monotoneProps : coloredProps),
  604. ...customStyle,
  605. };
  606. return h('span', componentProps);
  607. };
  608. /**
  609. * Storage for icons referred by name
  610. */
  611. const storage = Object.create(null);
  612. /**
  613. * Add icon to storage, allowing to call it by name
  614. *
  615. * @param name
  616. * @param data
  617. */
  618. function addIcon(name, data) {
  619. storage[name] = data;
  620. }
  621. /**
  622. * Add collection to storage, allowing to call icons by name
  623. *
  624. * @param data Icon set
  625. * @param prefix Optional prefix to add to icon names, true (default) if prefix from icon set should be used.
  626. */
  627. function addCollection(data, prefix) {
  628. const iconPrefix = typeof prefix === 'string'
  629. ? prefix
  630. : prefix !== false && typeof data.prefix === 'string'
  631. ? data.prefix + ':'
  632. : '';
  633. quicklyValidateIconSet(data) &&
  634. parseIconSet(data, (name, icon) => {
  635. if (icon) {
  636. storage[iconPrefix + name] = icon;
  637. }
  638. });
  639. }
  640. /**
  641. * Component
  642. */
  643. const Icon = defineComponent({
  644. // Do not inherit other attributes: it is handled by render()
  645. inheritAttrs: false,
  646. // Render icon
  647. render() {
  648. const props = this.$attrs;
  649. // Check icon
  650. const propsIcon = props.icon;
  651. const icon = typeof propsIcon === 'string'
  652. ? storage[propsIcon]
  653. : typeof propsIcon === 'object'
  654. ? propsIcon
  655. : null;
  656. // Validate icon object
  657. if (icon === null ||
  658. typeof icon !== 'object' ||
  659. typeof icon.body !== 'string') {
  660. return this.$slots.default ? this.$slots.default() : null;
  661. }
  662. // Valid icon: render it
  663. return render({
  664. ...defaultIconProps,
  665. ...icon,
  666. }, props);
  667. },
  668. });
  669. export { Icon, addCollection, addIcon };