iconify.without-api.cjs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353
  1. /**
  2. * (c) Iconify
  3. *
  4. * For the full copyright and license information, please view the license.txt or license.gpl.txt
  5. * files at https://github.com/iconify/iconify
  6. *
  7. * Licensed under MIT.
  8. *
  9. * @license MIT
  10. * @version 3.1.0
  11. */
  12. 'use strict';
  13. Object.defineProperty(exports, '__esModule', { value: true });
  14. const defaultIconDimensions = Object.freeze(
  15. {
  16. left: 0,
  17. top: 0,
  18. width: 16,
  19. height: 16
  20. }
  21. );
  22. const defaultIconTransformations = Object.freeze({
  23. rotate: 0,
  24. vFlip: false,
  25. hFlip: false
  26. });
  27. const defaultIconProps = Object.freeze({
  28. ...defaultIconDimensions,
  29. ...defaultIconTransformations
  30. });
  31. const defaultExtendedIconProps = Object.freeze({
  32. ...defaultIconProps,
  33. body: "",
  34. hidden: false
  35. });
  36. function mergeIconTransformations(obj1, obj2) {
  37. const result = {};
  38. if (!obj1.hFlip !== !obj2.hFlip) {
  39. result.hFlip = true;
  40. }
  41. if (!obj1.vFlip !== !obj2.vFlip) {
  42. result.vFlip = true;
  43. }
  44. const rotate = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;
  45. if (rotate) {
  46. result.rotate = rotate;
  47. }
  48. return result;
  49. }
  50. function mergeIconData(parent, child) {
  51. const result = mergeIconTransformations(parent, child);
  52. for (const key in defaultExtendedIconProps) {
  53. if (key in defaultIconTransformations) {
  54. if (key in parent && !(key in result)) {
  55. result[key] = defaultIconTransformations[key];
  56. }
  57. } else if (key in child) {
  58. result[key] = child[key];
  59. } else if (key in parent) {
  60. result[key] = parent[key];
  61. }
  62. }
  63. return result;
  64. }
  65. function getIconsTree(data, names) {
  66. const icons = data.icons;
  67. const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  68. const resolved = /* @__PURE__ */ Object.create(null);
  69. function resolve(name) {
  70. if (icons[name]) {
  71. return resolved[name] = [];
  72. }
  73. if (!(name in resolved)) {
  74. resolved[name] = null;
  75. const parent = aliases[name] && aliases[name].parent;
  76. const value = parent && resolve(parent);
  77. if (value) {
  78. resolved[name] = [parent].concat(value);
  79. }
  80. }
  81. return resolved[name];
  82. }
  83. (names || Object.keys(icons).concat(Object.keys(aliases))).forEach(resolve);
  84. return resolved;
  85. }
  86. function internalGetIconData(data, name, tree) {
  87. const icons = data.icons;
  88. const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  89. let currentProps = {};
  90. function parse(name2) {
  91. currentProps = mergeIconData(
  92. icons[name2] || aliases[name2],
  93. currentProps
  94. );
  95. }
  96. parse(name);
  97. tree.forEach(parse);
  98. return mergeIconData(data, currentProps);
  99. }
  100. function parseIconSet(data, callback) {
  101. const names = [];
  102. if (typeof data !== "object" || typeof data.icons !== "object") {
  103. return names;
  104. }
  105. if (data.not_found instanceof Array) {
  106. data.not_found.forEach((name) => {
  107. callback(name, null);
  108. names.push(name);
  109. });
  110. }
  111. const tree = getIconsTree(data);
  112. for (const name in tree) {
  113. const item = tree[name];
  114. if (item) {
  115. callback(name, internalGetIconData(data, name, item));
  116. names.push(name);
  117. }
  118. }
  119. return names;
  120. }
  121. const matchIconName = /^[a-z0-9]+(-[a-z0-9]+)*$/;
  122. const stringToIcon = (value, validate, allowSimpleName, provider = "") => {
  123. const colonSeparated = value.split(":");
  124. if (value.slice(0, 1) === "@") {
  125. if (colonSeparated.length < 2 || colonSeparated.length > 3) {
  126. return null;
  127. }
  128. provider = colonSeparated.shift().slice(1);
  129. }
  130. if (colonSeparated.length > 3 || !colonSeparated.length) {
  131. return null;
  132. }
  133. if (colonSeparated.length > 1) {
  134. const name2 = colonSeparated.pop();
  135. const prefix = colonSeparated.pop();
  136. const result = {
  137. provider: colonSeparated.length > 0 ? colonSeparated[0] : provider,
  138. prefix,
  139. name: name2
  140. };
  141. return validate && !validateIconName(result) ? null : result;
  142. }
  143. const name = colonSeparated[0];
  144. const dashSeparated = name.split("-");
  145. if (dashSeparated.length > 1) {
  146. const result = {
  147. provider,
  148. prefix: dashSeparated.shift(),
  149. name: dashSeparated.join("-")
  150. };
  151. return validate && !validateIconName(result) ? null : result;
  152. }
  153. if (allowSimpleName && provider === "") {
  154. const result = {
  155. provider,
  156. prefix: "",
  157. name
  158. };
  159. return validate && !validateIconName(result, allowSimpleName) ? null : result;
  160. }
  161. return null;
  162. };
  163. const validateIconName = (icon, allowSimpleName) => {
  164. if (!icon) {
  165. return false;
  166. }
  167. return !!((icon.provider === "" || icon.provider.match(matchIconName)) && (allowSimpleName && icon.prefix === "" || icon.prefix.match(matchIconName)) && icon.name.match(matchIconName));
  168. };
  169. const optionalPropertyDefaults = {
  170. provider: "",
  171. aliases: {},
  172. not_found: {},
  173. ...defaultIconDimensions
  174. };
  175. function checkOptionalProps(item, defaults) {
  176. for (const prop in defaults) {
  177. if (prop in item && typeof item[prop] !== typeof defaults[prop]) {
  178. return false;
  179. }
  180. }
  181. return true;
  182. }
  183. function quicklyValidateIconSet(obj) {
  184. if (typeof obj !== "object" || obj === null) {
  185. return null;
  186. }
  187. const data = obj;
  188. if (typeof data.prefix !== "string" || !obj.icons || typeof obj.icons !== "object") {
  189. return null;
  190. }
  191. if (!checkOptionalProps(obj, optionalPropertyDefaults)) {
  192. return null;
  193. }
  194. const icons = data.icons;
  195. for (const name in icons) {
  196. const icon = icons[name];
  197. if (!name.match(matchIconName) || typeof icon.body !== "string" || !checkOptionalProps(
  198. icon,
  199. defaultExtendedIconProps
  200. )) {
  201. return null;
  202. }
  203. }
  204. const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
  205. for (const name in aliases) {
  206. const icon = aliases[name];
  207. const parent = icon.parent;
  208. if (!name.match(matchIconName) || typeof parent !== "string" || !icons[parent] && !aliases[parent] || !checkOptionalProps(
  209. icon,
  210. defaultExtendedIconProps
  211. )) {
  212. return null;
  213. }
  214. }
  215. return data;
  216. }
  217. const dataStorage = /* @__PURE__ */ Object.create(null);
  218. function newStorage(provider, prefix) {
  219. return {
  220. provider,
  221. prefix,
  222. icons: /* @__PURE__ */ Object.create(null),
  223. missing: /* @__PURE__ */ new Set()
  224. };
  225. }
  226. function getStorage(provider, prefix) {
  227. const providerStorage = dataStorage[provider] || (dataStorage[provider] = /* @__PURE__ */ Object.create(null));
  228. return providerStorage[prefix] || (providerStorage[prefix] = newStorage(provider, prefix));
  229. }
  230. function addIconSet(storage, data) {
  231. if (!quicklyValidateIconSet(data)) {
  232. return [];
  233. }
  234. return parseIconSet(data, (name, icon) => {
  235. if (icon) {
  236. storage.icons[name] = icon;
  237. } else {
  238. storage.missing.add(name);
  239. }
  240. });
  241. }
  242. function addIconToStorage(storage, name, icon) {
  243. try {
  244. if (typeof icon.body === "string") {
  245. storage.icons[name] = { ...icon };
  246. return true;
  247. }
  248. } catch (err) {
  249. }
  250. return false;
  251. }
  252. function listIcons(provider, prefix) {
  253. let allIcons = [];
  254. const providers = typeof provider === "string" ? [provider] : Object.keys(dataStorage);
  255. providers.forEach((provider2) => {
  256. const prefixes = typeof provider2 === "string" && typeof prefix === "string" ? [prefix] : Object.keys(dataStorage[provider2] || {});
  257. prefixes.forEach((prefix2) => {
  258. const storage = getStorage(provider2, prefix2);
  259. allIcons = allIcons.concat(
  260. Object.keys(storage.icons).map(
  261. (name) => (provider2 !== "" ? "@" + provider2 + ":" : "") + prefix2 + ":" + name
  262. )
  263. );
  264. });
  265. });
  266. return allIcons;
  267. }
  268. let simpleNames = false;
  269. function allowSimpleNames(allow) {
  270. if (typeof allow === "boolean") {
  271. simpleNames = allow;
  272. }
  273. return simpleNames;
  274. }
  275. function getIconData(name) {
  276. const icon = typeof name === "string" ? stringToIcon(name, true, simpleNames) : name;
  277. if (icon) {
  278. const storage = getStorage(icon.provider, icon.prefix);
  279. const iconName = icon.name;
  280. return storage.icons[iconName] || (storage.missing.has(iconName) ? null : void 0);
  281. }
  282. }
  283. function addIcon(name, data) {
  284. const icon = stringToIcon(name, true, simpleNames);
  285. if (!icon) {
  286. return false;
  287. }
  288. const storage = getStorage(icon.provider, icon.prefix);
  289. return addIconToStorage(storage, icon.name, data);
  290. }
  291. function addCollection(data, provider) {
  292. if (typeof data !== "object") {
  293. return false;
  294. }
  295. if (typeof provider !== "string") {
  296. provider = data.provider || "";
  297. }
  298. if (simpleNames && !provider && !data.prefix) {
  299. let added = false;
  300. if (quicklyValidateIconSet(data)) {
  301. data.prefix = "";
  302. parseIconSet(data, (name, icon) => {
  303. if (icon && addIcon(name, icon)) {
  304. added = true;
  305. }
  306. });
  307. }
  308. return added;
  309. }
  310. const prefix = data.prefix;
  311. if (!validateIconName({
  312. provider,
  313. prefix,
  314. name: "a"
  315. })) {
  316. return false;
  317. }
  318. const storage = getStorage(provider, prefix);
  319. return !!addIconSet(storage, data);
  320. }
  321. function iconExists(name) {
  322. return !!getIconData(name);
  323. }
  324. function getIcon(name) {
  325. const result = getIconData(name);
  326. return result ? {
  327. ...defaultIconProps,
  328. ...result
  329. } : null;
  330. }
  331. const defaultIconSizeCustomisations = Object.freeze({
  332. width: null,
  333. height: null
  334. });
  335. const defaultIconCustomisations = Object.freeze({
  336. ...defaultIconSizeCustomisations,
  337. ...defaultIconTransformations
  338. });
  339. const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
  340. const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
  341. function calculateSize(size, ratio, precision) {
  342. if (ratio === 1) {
  343. return size;
  344. }
  345. precision = precision || 100;
  346. if (typeof size === "number") {
  347. return Math.ceil(size * ratio * precision) / precision;
  348. }
  349. if (typeof size !== "string") {
  350. return size;
  351. }
  352. const oldParts = size.split(unitsSplit);
  353. if (oldParts === null || !oldParts.length) {
  354. return size;
  355. }
  356. const newParts = [];
  357. let code = oldParts.shift();
  358. let isNumber = unitsTest.test(code);
  359. while (true) {
  360. if (isNumber) {
  361. const num = parseFloat(code);
  362. if (isNaN(num)) {
  363. newParts.push(code);
  364. } else {
  365. newParts.push(Math.ceil(num * ratio * precision) / precision);
  366. }
  367. } else {
  368. newParts.push(code);
  369. }
  370. code = oldParts.shift();
  371. if (code === void 0) {
  372. return newParts.join("");
  373. }
  374. isNumber = !isNumber;
  375. }
  376. }
  377. const isUnsetKeyword = (value) => value === "unset" || value === "undefined" || value === "none";
  378. function iconToSVG(icon, customisations) {
  379. const fullIcon = {
  380. ...defaultIconProps,
  381. ...icon
  382. };
  383. const fullCustomisations = {
  384. ...defaultIconCustomisations,
  385. ...customisations
  386. };
  387. const box = {
  388. left: fullIcon.left,
  389. top: fullIcon.top,
  390. width: fullIcon.width,
  391. height: fullIcon.height
  392. };
  393. let body = fullIcon.body;
  394. [fullIcon, fullCustomisations].forEach((props) => {
  395. const transformations = [];
  396. const hFlip = props.hFlip;
  397. const vFlip = props.vFlip;
  398. let rotation = props.rotate;
  399. if (hFlip) {
  400. if (vFlip) {
  401. rotation += 2;
  402. } else {
  403. transformations.push(
  404. "translate(" + (box.width + box.left).toString() + " " + (0 - box.top).toString() + ")"
  405. );
  406. transformations.push("scale(-1 1)");
  407. box.top = box.left = 0;
  408. }
  409. } else if (vFlip) {
  410. transformations.push(
  411. "translate(" + (0 - box.left).toString() + " " + (box.height + box.top).toString() + ")"
  412. );
  413. transformations.push("scale(1 -1)");
  414. box.top = box.left = 0;
  415. }
  416. let tempValue;
  417. if (rotation < 0) {
  418. rotation -= Math.floor(rotation / 4) * 4;
  419. }
  420. rotation = rotation % 4;
  421. switch (rotation) {
  422. case 1:
  423. tempValue = box.height / 2 + box.top;
  424. transformations.unshift(
  425. "rotate(90 " + tempValue.toString() + " " + tempValue.toString() + ")"
  426. );
  427. break;
  428. case 2:
  429. transformations.unshift(
  430. "rotate(180 " + (box.width / 2 + box.left).toString() + " " + (box.height / 2 + box.top).toString() + ")"
  431. );
  432. break;
  433. case 3:
  434. tempValue = box.width / 2 + box.left;
  435. transformations.unshift(
  436. "rotate(-90 " + tempValue.toString() + " " + tempValue.toString() + ")"
  437. );
  438. break;
  439. }
  440. if (rotation % 2 === 1) {
  441. if (box.left !== box.top) {
  442. tempValue = box.left;
  443. box.left = box.top;
  444. box.top = tempValue;
  445. }
  446. if (box.width !== box.height) {
  447. tempValue = box.width;
  448. box.width = box.height;
  449. box.height = tempValue;
  450. }
  451. }
  452. if (transformations.length) {
  453. body = '<g transform="' + transformations.join(" ") + '">' + body + "</g>";
  454. }
  455. });
  456. const customisationsWidth = fullCustomisations.width;
  457. const customisationsHeight = fullCustomisations.height;
  458. const boxWidth = box.width;
  459. const boxHeight = box.height;
  460. let width;
  461. let height;
  462. if (customisationsWidth === null) {
  463. height = customisationsHeight === null ? "1em" : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
  464. width = calculateSize(height, boxWidth / boxHeight);
  465. } else {
  466. width = customisationsWidth === "auto" ? boxWidth : customisationsWidth;
  467. height = customisationsHeight === null ? calculateSize(width, boxHeight / boxWidth) : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
  468. }
  469. const attributes = {};
  470. const setAttr = (prop, value) => {
  471. if (!isUnsetKeyword(value)) {
  472. attributes[prop] = value.toString();
  473. }
  474. };
  475. setAttr("width", width);
  476. setAttr("height", height);
  477. attributes.viewBox = box.left.toString() + " " + box.top.toString() + " " + boxWidth.toString() + " " + boxHeight.toString();
  478. return {
  479. attributes,
  480. body
  481. };
  482. }
  483. const regex = /\sid="(\S+)"/g;
  484. const randomPrefix = "IconifyId" + Date.now().toString(16) + (Math.random() * 16777216 | 0).toString(16);
  485. let counter = 0;
  486. function replaceIDs(body, prefix = randomPrefix) {
  487. const ids = [];
  488. let match;
  489. while (match = regex.exec(body)) {
  490. ids.push(match[1]);
  491. }
  492. if (!ids.length) {
  493. return body;
  494. }
  495. const suffix = "suffix" + (Math.random() * 16777216 | Date.now()).toString(16);
  496. ids.forEach((id) => {
  497. const newID = typeof prefix === "function" ? prefix(id) : prefix + (counter++).toString();
  498. const escapedID = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  499. body = body.replace(
  500. new RegExp('([#;"])(' + escapedID + ')([")]|\\.[a-z])', "g"),
  501. "$1" + newID + suffix + "$3"
  502. );
  503. });
  504. body = body.replace(new RegExp(suffix, "g"), "");
  505. return body;
  506. }
  507. function mergeCustomisations(defaults, item) {
  508. const result = {
  509. ...defaults
  510. };
  511. for (const key in item) {
  512. const value = item[key];
  513. const valueType = typeof value;
  514. if (key in defaultIconSizeCustomisations) {
  515. if (value === null || value && (valueType === "string" || valueType === "number")) {
  516. result[key] = value;
  517. }
  518. } else if (valueType === typeof result[key]) {
  519. result[key] = key === "rotate" ? value % 4 : value;
  520. }
  521. }
  522. return result;
  523. }
  524. const defaultExtendedIconCustomisations = {
  525. ...defaultIconCustomisations,
  526. inline: false,
  527. };
  528. /**
  529. * Class names
  530. */
  531. const blockClass = 'iconify';
  532. const inlineClass = 'iconify-inline';
  533. /**
  534. * Names of properties to add to nodes
  535. */
  536. const elementDataProperty = ('iconifyData' + Date.now());
  537. /**
  538. * List of root nodes
  539. */
  540. let nodes = [];
  541. /**
  542. * Find node
  543. */
  544. function findRootNode(node) {
  545. for (let i = 0; i < nodes.length; i++) {
  546. const item = nodes[i];
  547. const root = typeof item.node === 'function' ? item.node() : item.node;
  548. if (root === node) {
  549. return item;
  550. }
  551. }
  552. }
  553. /**
  554. * Add extra root node
  555. */
  556. function addRootNode(root, autoRemove = false) {
  557. let node = findRootNode(root);
  558. if (node) {
  559. // Node already exist: switch type if needed
  560. if (node.temporary) {
  561. node.temporary = autoRemove;
  562. }
  563. return node;
  564. }
  565. // Create item, add it to list
  566. node = {
  567. node: root,
  568. temporary: autoRemove,
  569. };
  570. nodes.push(node);
  571. return node;
  572. }
  573. /**
  574. * Add document.body node
  575. */
  576. function addBodyNode() {
  577. if (document.documentElement) {
  578. return addRootNode(document.documentElement);
  579. }
  580. nodes.push({
  581. node: () => {
  582. return document.documentElement;
  583. },
  584. });
  585. }
  586. /**
  587. * Remove root node
  588. */
  589. function removeRootNode(root) {
  590. nodes = nodes.filter((node) => root !== node &&
  591. root !== (typeof node.node === 'function' ? node.node() : node.node));
  592. }
  593. /**
  594. * Get list of root nodes
  595. */
  596. function listRootNodes() {
  597. return nodes;
  598. }
  599. /**
  600. * Execute function when DOM is ready
  601. */
  602. function onReady(callback) {
  603. const doc = document;
  604. if (doc.readyState && doc.readyState !== 'loading') {
  605. callback();
  606. }
  607. else {
  608. doc.addEventListener('DOMContentLoaded', callback);
  609. }
  610. }
  611. /**
  612. * Callback
  613. */
  614. let callback = null;
  615. /**
  616. * Parameters for mutation observer
  617. */
  618. const observerParams = {
  619. childList: true,
  620. subtree: true,
  621. attributes: true,
  622. };
  623. /**
  624. * Queue DOM scan
  625. */
  626. function queueScan(node) {
  627. if (!node.observer) {
  628. return;
  629. }
  630. const observer = node.observer;
  631. if (!observer.pendingScan) {
  632. observer.pendingScan = setTimeout(() => {
  633. delete observer.pendingScan;
  634. if (callback) {
  635. callback(node);
  636. }
  637. });
  638. }
  639. }
  640. /**
  641. * Check mutations for added nodes
  642. */
  643. function checkMutations(node, mutations) {
  644. if (!node.observer) {
  645. return;
  646. }
  647. const observer = node.observer;
  648. if (!observer.pendingScan) {
  649. for (let i = 0; i < mutations.length; i++) {
  650. const item = mutations[i];
  651. if (
  652. // Check for added nodes
  653. (item.addedNodes && item.addedNodes.length > 0) ||
  654. // Check for icon or placeholder with modified attributes
  655. (item.type === 'attributes' &&
  656. item.target[elementDataProperty] !==
  657. void 0)) {
  658. if (!observer.paused) {
  659. queueScan(node);
  660. }
  661. return;
  662. }
  663. }
  664. }
  665. }
  666. /**
  667. * Start/resume observer
  668. */
  669. function continueObserving(node, root) {
  670. node.observer.instance.observe(root, observerParams);
  671. }
  672. /**
  673. * Start mutation observer
  674. */
  675. function startObserver(node) {
  676. let observer = node.observer;
  677. if (observer && observer.instance) {
  678. // Already started
  679. return;
  680. }
  681. const root = typeof node.node === 'function' ? node.node() : node.node;
  682. if (!root || !window) {
  683. // document.body is not available yet or window is missing
  684. return;
  685. }
  686. if (!observer) {
  687. observer = {
  688. paused: 0,
  689. };
  690. node.observer = observer;
  691. }
  692. // Create new instance, observe
  693. observer.instance = new window.MutationObserver(checkMutations.bind(null, node));
  694. continueObserving(node, root);
  695. // Scan immediately
  696. if (!observer.paused) {
  697. queueScan(node);
  698. }
  699. }
  700. /**
  701. * Start all observers
  702. */
  703. function startObservers() {
  704. listRootNodes().forEach(startObserver);
  705. }
  706. /**
  707. * Stop observer
  708. */
  709. function stopObserver(node) {
  710. if (!node.observer) {
  711. return;
  712. }
  713. const observer = node.observer;
  714. // Stop scan
  715. if (observer.pendingScan) {
  716. clearTimeout(observer.pendingScan);
  717. delete observer.pendingScan;
  718. }
  719. // Disconnect observer
  720. if (observer.instance) {
  721. observer.instance.disconnect();
  722. delete observer.instance;
  723. }
  724. }
  725. /**
  726. * Start observer when DOM is ready
  727. */
  728. function initObserver(cb) {
  729. const isRestart = callback !== null;
  730. if (callback !== cb) {
  731. // Change callback and stop all pending observers
  732. callback = cb;
  733. if (isRestart) {
  734. listRootNodes().forEach(stopObserver);
  735. }
  736. }
  737. if (isRestart) {
  738. // Restart instances
  739. startObservers();
  740. return;
  741. }
  742. // Start observers when document is ready
  743. onReady(startObservers);
  744. }
  745. /**
  746. * Pause observing node
  747. */
  748. function pauseObservingNode(node) {
  749. (node ? [node] : listRootNodes()).forEach((node) => {
  750. if (!node.observer) {
  751. node.observer = {
  752. paused: 1,
  753. };
  754. return;
  755. }
  756. const observer = node.observer;
  757. observer.paused++;
  758. if (observer.paused > 1 || !observer.instance) {
  759. return;
  760. }
  761. // Disconnect observer
  762. const instance = observer.instance;
  763. // checkMutations(node, instance.takeRecords());
  764. instance.disconnect();
  765. });
  766. }
  767. /**
  768. * Pause observer
  769. */
  770. function pauseObserver(root) {
  771. if (root) {
  772. const node = findRootNode(root);
  773. if (node) {
  774. pauseObservingNode(node);
  775. }
  776. }
  777. else {
  778. pauseObservingNode();
  779. }
  780. }
  781. /**
  782. * Resume observer
  783. */
  784. function resumeObservingNode(observer) {
  785. (observer ? [observer] : listRootNodes()).forEach((node) => {
  786. if (!node.observer) {
  787. // Start observer
  788. startObserver(node);
  789. return;
  790. }
  791. const observer = node.observer;
  792. if (observer.paused) {
  793. observer.paused--;
  794. if (!observer.paused) {
  795. // Start / resume
  796. const root = typeof node.node === 'function' ? node.node() : node.node;
  797. if (!root) {
  798. return;
  799. }
  800. else if (observer.instance) {
  801. continueObserving(node, root);
  802. }
  803. else {
  804. startObserver(node);
  805. }
  806. }
  807. }
  808. });
  809. }
  810. /**
  811. * Resume observer
  812. */
  813. function resumeObserver(root) {
  814. if (root) {
  815. const node = findRootNode(root);
  816. if (node) {
  817. resumeObservingNode(node);
  818. }
  819. }
  820. else {
  821. resumeObservingNode();
  822. }
  823. }
  824. /**
  825. * Observe node
  826. */
  827. function observe(root, autoRemove = false) {
  828. const node = addRootNode(root, autoRemove);
  829. startObserver(node);
  830. return node;
  831. }
  832. /**
  833. * Remove observed node
  834. */
  835. function stopObserving(root) {
  836. const node = findRootNode(root);
  837. if (node) {
  838. stopObserver(node);
  839. removeRootNode(root);
  840. }
  841. }
  842. function sortIcons(icons) {
  843. const result = {
  844. loaded: [],
  845. missing: [],
  846. pending: []
  847. };
  848. const storage = /* @__PURE__ */ Object.create(null);
  849. icons.sort((a, b) => {
  850. if (a.provider !== b.provider) {
  851. return a.provider.localeCompare(b.provider);
  852. }
  853. if (a.prefix !== b.prefix) {
  854. return a.prefix.localeCompare(b.prefix);
  855. }
  856. return a.name.localeCompare(b.name);
  857. });
  858. let lastIcon = {
  859. provider: "",
  860. prefix: "",
  861. name: ""
  862. };
  863. icons.forEach((icon) => {
  864. if (lastIcon.name === icon.name && lastIcon.prefix === icon.prefix && lastIcon.provider === icon.provider) {
  865. return;
  866. }
  867. lastIcon = icon;
  868. const provider = icon.provider;
  869. const prefix = icon.prefix;
  870. const name = icon.name;
  871. const providerStorage = storage[provider] || (storage[provider] = /* @__PURE__ */ Object.create(null));
  872. const localStorage = providerStorage[prefix] || (providerStorage[prefix] = getStorage(provider, prefix));
  873. let list;
  874. if (name in localStorage.icons) {
  875. list = result.loaded;
  876. } else if (prefix === "" || localStorage.missing.has(name)) {
  877. list = result.missing;
  878. } else {
  879. list = result.pending;
  880. }
  881. const item = {
  882. provider,
  883. prefix,
  884. name
  885. };
  886. list.push(item);
  887. });
  888. return result;
  889. }
  890. function removeCallback(storages, id) {
  891. storages.forEach((storage) => {
  892. const items = storage.loaderCallbacks;
  893. if (items) {
  894. storage.loaderCallbacks = items.filter((row) => row.id !== id);
  895. }
  896. });
  897. }
  898. function updateCallbacks(storage) {
  899. if (!storage.pendingCallbacksFlag) {
  900. storage.pendingCallbacksFlag = true;
  901. setTimeout(() => {
  902. storage.pendingCallbacksFlag = false;
  903. const items = storage.loaderCallbacks ? storage.loaderCallbacks.slice(0) : [];
  904. if (!items.length) {
  905. return;
  906. }
  907. let hasPending = false;
  908. const provider = storage.provider;
  909. const prefix = storage.prefix;
  910. items.forEach((item) => {
  911. const icons = item.icons;
  912. const oldLength = icons.pending.length;
  913. icons.pending = icons.pending.filter((icon) => {
  914. if (icon.prefix !== prefix) {
  915. return true;
  916. }
  917. const name = icon.name;
  918. if (storage.icons[name]) {
  919. icons.loaded.push({
  920. provider,
  921. prefix,
  922. name
  923. });
  924. } else if (storage.missing.has(name)) {
  925. icons.missing.push({
  926. provider,
  927. prefix,
  928. name
  929. });
  930. } else {
  931. hasPending = true;
  932. return true;
  933. }
  934. return false;
  935. });
  936. if (icons.pending.length !== oldLength) {
  937. if (!hasPending) {
  938. removeCallback([storage], item.id);
  939. }
  940. item.callback(
  941. icons.loaded.slice(0),
  942. icons.missing.slice(0),
  943. icons.pending.slice(0),
  944. item.abort
  945. );
  946. }
  947. });
  948. });
  949. }
  950. }
  951. let idCounter = 0;
  952. function storeCallback(callback, icons, pendingSources) {
  953. const id = idCounter++;
  954. const abort = removeCallback.bind(null, pendingSources, id);
  955. if (!icons.pending.length) {
  956. return abort;
  957. }
  958. const item = {
  959. id,
  960. icons,
  961. callback,
  962. abort
  963. };
  964. pendingSources.forEach((storage) => {
  965. (storage.loaderCallbacks || (storage.loaderCallbacks = [])).push(item);
  966. });
  967. return abort;
  968. }
  969. const storage = /* @__PURE__ */ Object.create(null);
  970. function getAPIModule(provider) {
  971. return storage[provider] || storage[""];
  972. }
  973. function listToIcons(list, validate = true, simpleNames = false) {
  974. const result = [];
  975. list.forEach((item) => {
  976. const icon = typeof item === "string" ? stringToIcon(item, validate, simpleNames) : item;
  977. if (icon) {
  978. result.push(icon);
  979. }
  980. });
  981. return result;
  982. }
  983. // src/config.ts
  984. var defaultConfig = {
  985. resources: [],
  986. index: 0,
  987. timeout: 2e3,
  988. rotate: 750,
  989. random: false,
  990. dataAfterTimeout: false
  991. };
  992. // src/query.ts
  993. function sendQuery(config, payload, query, done) {
  994. const resourcesCount = config.resources.length;
  995. const startIndex = config.random ? Math.floor(Math.random() * resourcesCount) : config.index;
  996. let resources;
  997. if (config.random) {
  998. let list = config.resources.slice(0);
  999. resources = [];
  1000. while (list.length > 1) {
  1001. const nextIndex = Math.floor(Math.random() * list.length);
  1002. resources.push(list[nextIndex]);
  1003. list = list.slice(0, nextIndex).concat(list.slice(nextIndex + 1));
  1004. }
  1005. resources = resources.concat(list);
  1006. } else {
  1007. resources = config.resources.slice(startIndex).concat(config.resources.slice(0, startIndex));
  1008. }
  1009. const startTime = Date.now();
  1010. let status = "pending";
  1011. let queriesSent = 0;
  1012. let lastError;
  1013. let timer = null;
  1014. let queue = [];
  1015. let doneCallbacks = [];
  1016. if (typeof done === "function") {
  1017. doneCallbacks.push(done);
  1018. }
  1019. function resetTimer() {
  1020. if (timer) {
  1021. clearTimeout(timer);
  1022. timer = null;
  1023. }
  1024. }
  1025. function abort() {
  1026. if (status === "pending") {
  1027. status = "aborted";
  1028. }
  1029. resetTimer();
  1030. queue.forEach((item) => {
  1031. if (item.status === "pending") {
  1032. item.status = "aborted";
  1033. }
  1034. });
  1035. queue = [];
  1036. }
  1037. function subscribe(callback, overwrite) {
  1038. if (overwrite) {
  1039. doneCallbacks = [];
  1040. }
  1041. if (typeof callback === "function") {
  1042. doneCallbacks.push(callback);
  1043. }
  1044. }
  1045. function getQueryStatus() {
  1046. return {
  1047. startTime,
  1048. payload,
  1049. status,
  1050. queriesSent,
  1051. queriesPending: queue.length,
  1052. subscribe,
  1053. abort
  1054. };
  1055. }
  1056. function failQuery() {
  1057. status = "failed";
  1058. doneCallbacks.forEach((callback) => {
  1059. callback(void 0, lastError);
  1060. });
  1061. }
  1062. function clearQueue() {
  1063. queue.forEach((item) => {
  1064. if (item.status === "pending") {
  1065. item.status = "aborted";
  1066. }
  1067. });
  1068. queue = [];
  1069. }
  1070. function moduleResponse(item, response, data) {
  1071. const isError = response !== "success";
  1072. queue = queue.filter((queued) => queued !== item);
  1073. switch (status) {
  1074. case "pending":
  1075. break;
  1076. case "failed":
  1077. if (isError || !config.dataAfterTimeout) {
  1078. return;
  1079. }
  1080. break;
  1081. default:
  1082. return;
  1083. }
  1084. if (response === "abort") {
  1085. lastError = data;
  1086. failQuery();
  1087. return;
  1088. }
  1089. if (isError) {
  1090. lastError = data;
  1091. if (!queue.length) {
  1092. if (!resources.length) {
  1093. failQuery();
  1094. } else {
  1095. execNext();
  1096. }
  1097. }
  1098. return;
  1099. }
  1100. resetTimer();
  1101. clearQueue();
  1102. if (!config.random) {
  1103. const index = config.resources.indexOf(item.resource);
  1104. if (index !== -1 && index !== config.index) {
  1105. config.index = index;
  1106. }
  1107. }
  1108. status = "completed";
  1109. doneCallbacks.forEach((callback) => {
  1110. callback(data);
  1111. });
  1112. }
  1113. function execNext() {
  1114. if (status !== "pending") {
  1115. return;
  1116. }
  1117. resetTimer();
  1118. const resource = resources.shift();
  1119. if (resource === void 0) {
  1120. if (queue.length) {
  1121. timer = setTimeout(() => {
  1122. resetTimer();
  1123. if (status === "pending") {
  1124. clearQueue();
  1125. failQuery();
  1126. }
  1127. }, config.timeout);
  1128. return;
  1129. }
  1130. failQuery();
  1131. return;
  1132. }
  1133. const item = {
  1134. status: "pending",
  1135. resource,
  1136. callback: (status2, data) => {
  1137. moduleResponse(item, status2, data);
  1138. }
  1139. };
  1140. queue.push(item);
  1141. queriesSent++;
  1142. timer = setTimeout(execNext, config.rotate);
  1143. query(resource, payload, item.callback);
  1144. }
  1145. setTimeout(execNext);
  1146. return getQueryStatus;
  1147. }
  1148. // src/index.ts
  1149. function initRedundancy(cfg) {
  1150. const config = {
  1151. ...defaultConfig,
  1152. ...cfg
  1153. };
  1154. let queries = [];
  1155. function cleanup() {
  1156. queries = queries.filter((item) => item().status === "pending");
  1157. }
  1158. function query(payload, queryCallback, doneCallback) {
  1159. const query2 = sendQuery(
  1160. config,
  1161. payload,
  1162. queryCallback,
  1163. (data, error) => {
  1164. cleanup();
  1165. if (doneCallback) {
  1166. doneCallback(data, error);
  1167. }
  1168. }
  1169. );
  1170. queries.push(query2);
  1171. return query2;
  1172. }
  1173. function find(callback) {
  1174. return queries.find((value) => {
  1175. return callback(value);
  1176. }) || null;
  1177. }
  1178. const instance = {
  1179. query,
  1180. find,
  1181. setIndex: (index) => {
  1182. config.index = index;
  1183. },
  1184. getIndex: () => config.index,
  1185. cleanup
  1186. };
  1187. return instance;
  1188. }
  1189. function createAPIConfig(source) {
  1190. let resources;
  1191. if (typeof source.resources === "string") {
  1192. resources = [source.resources];
  1193. } else {
  1194. resources = source.resources;
  1195. if (!(resources instanceof Array) || !resources.length) {
  1196. return null;
  1197. }
  1198. }
  1199. const result = {
  1200. resources,
  1201. path: source.path || "/",
  1202. maxURL: source.maxURL || 500,
  1203. rotate: source.rotate || 750,
  1204. timeout: source.timeout || 5e3,
  1205. random: source.random === true,
  1206. index: source.index || 0,
  1207. dataAfterTimeout: source.dataAfterTimeout !== false
  1208. };
  1209. return result;
  1210. }
  1211. const configStorage = /* @__PURE__ */ Object.create(null);
  1212. const fallBackAPISources = [
  1213. "https://api.simplesvg.com",
  1214. "https://api.unisvg.com"
  1215. ];
  1216. const fallBackAPI = [];
  1217. while (fallBackAPISources.length > 0) {
  1218. if (fallBackAPISources.length === 1) {
  1219. fallBackAPI.push(fallBackAPISources.shift());
  1220. } else {
  1221. if (Math.random() > 0.5) {
  1222. fallBackAPI.push(fallBackAPISources.shift());
  1223. } else {
  1224. fallBackAPI.push(fallBackAPISources.pop());
  1225. }
  1226. }
  1227. }
  1228. configStorage[""] = createAPIConfig({
  1229. resources: ["https://api.iconify.design"].concat(fallBackAPI)
  1230. });
  1231. function getAPIConfig(provider) {
  1232. return configStorage[provider];
  1233. }
  1234. function emptyCallback$1() {
  1235. }
  1236. const redundancyCache = /* @__PURE__ */ Object.create(null);
  1237. function getRedundancyCache(provider) {
  1238. if (!redundancyCache[provider]) {
  1239. const config = getAPIConfig(provider);
  1240. if (!config) {
  1241. return;
  1242. }
  1243. const redundancy = initRedundancy(config);
  1244. const cachedReundancy = {
  1245. config,
  1246. redundancy
  1247. };
  1248. redundancyCache[provider] = cachedReundancy;
  1249. }
  1250. return redundancyCache[provider];
  1251. }
  1252. function sendAPIQuery(target, query, callback) {
  1253. let redundancy;
  1254. let send;
  1255. if (typeof target === "string") {
  1256. const api = getAPIModule(target);
  1257. if (!api) {
  1258. callback(void 0, 424);
  1259. return emptyCallback$1;
  1260. }
  1261. send = api.send;
  1262. const cached = getRedundancyCache(target);
  1263. if (cached) {
  1264. redundancy = cached.redundancy;
  1265. }
  1266. } else {
  1267. const config = createAPIConfig(target);
  1268. if (config) {
  1269. redundancy = initRedundancy(config);
  1270. const moduleKey = target.resources ? target.resources[0] : "";
  1271. const api = getAPIModule(moduleKey);
  1272. if (api) {
  1273. send = api.send;
  1274. }
  1275. }
  1276. }
  1277. if (!redundancy || !send) {
  1278. callback(void 0, 424);
  1279. return emptyCallback$1;
  1280. }
  1281. return redundancy.query(query, send, callback)().abort;
  1282. }
  1283. const browserCacheVersion = "iconify2";
  1284. const browserCachePrefix = "iconify";
  1285. const browserCacheCountKey = browserCachePrefix + "-count";
  1286. const browserCacheVersionKey = browserCachePrefix + "-version";
  1287. const browserStorageHour = 36e5;
  1288. const browserStorageCacheExpiration = 168;
  1289. function getStoredItem(func, key) {
  1290. try {
  1291. return func.getItem(key);
  1292. } catch (err) {
  1293. }
  1294. }
  1295. function setStoredItem(func, key, value) {
  1296. try {
  1297. func.setItem(key, value);
  1298. return true;
  1299. } catch (err) {
  1300. }
  1301. }
  1302. function removeStoredItem(func, key) {
  1303. try {
  1304. func.removeItem(key);
  1305. } catch (err) {
  1306. }
  1307. }
  1308. function setBrowserStorageItemsCount(storage, value) {
  1309. return setStoredItem(storage, browserCacheCountKey, value.toString());
  1310. }
  1311. function getBrowserStorageItemsCount(storage) {
  1312. return parseInt(getStoredItem(storage, browserCacheCountKey)) || 0;
  1313. }
  1314. const browserStorageConfig = {
  1315. local: true,
  1316. session: true
  1317. };
  1318. const browserStorageEmptyItems = {
  1319. local: /* @__PURE__ */ new Set(),
  1320. session: /* @__PURE__ */ new Set()
  1321. };
  1322. let browserStorageStatus = false;
  1323. function setBrowserStorageStatus(status) {
  1324. browserStorageStatus = status;
  1325. }
  1326. let _window = typeof window === "undefined" ? {} : window;
  1327. function getBrowserStorage(key) {
  1328. const attr = key + "Storage";
  1329. try {
  1330. if (_window && _window[attr] && typeof _window[attr].length === "number") {
  1331. return _window[attr];
  1332. }
  1333. } catch (err) {
  1334. }
  1335. browserStorageConfig[key] = false;
  1336. }
  1337. function iterateBrowserStorage(key, callback) {
  1338. const func = getBrowserStorage(key);
  1339. if (!func) {
  1340. return;
  1341. }
  1342. const version = getStoredItem(func, browserCacheVersionKey);
  1343. if (version !== browserCacheVersion) {
  1344. if (version) {
  1345. const total2 = getBrowserStorageItemsCount(func);
  1346. for (let i = 0; i < total2; i++) {
  1347. removeStoredItem(func, browserCachePrefix + i.toString());
  1348. }
  1349. }
  1350. setStoredItem(func, browserCacheVersionKey, browserCacheVersion);
  1351. setBrowserStorageItemsCount(func, 0);
  1352. return;
  1353. }
  1354. const minTime = Math.floor(Date.now() / browserStorageHour) - browserStorageCacheExpiration;
  1355. const parseItem = (index) => {
  1356. const name = browserCachePrefix + index.toString();
  1357. const item = getStoredItem(func, name);
  1358. if (typeof item !== "string") {
  1359. return;
  1360. }
  1361. try {
  1362. const data = JSON.parse(item);
  1363. if (typeof data === "object" && typeof data.cached === "number" && data.cached > minTime && typeof data.provider === "string" && typeof data.data === "object" && typeof data.data.prefix === "string" && callback(data, index)) {
  1364. return true;
  1365. }
  1366. } catch (err) {
  1367. }
  1368. removeStoredItem(func, name);
  1369. };
  1370. let total = getBrowserStorageItemsCount(func);
  1371. for (let i = total - 1; i >= 0; i--) {
  1372. if (!parseItem(i)) {
  1373. if (i === total - 1) {
  1374. total--;
  1375. setBrowserStorageItemsCount(func, total);
  1376. } else {
  1377. browserStorageEmptyItems[key].add(i);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. function initBrowserStorage() {
  1383. if (browserStorageStatus) {
  1384. return;
  1385. }
  1386. setBrowserStorageStatus(true);
  1387. for (const key in browserStorageConfig) {
  1388. iterateBrowserStorage(key, (item) => {
  1389. const iconSet = item.data;
  1390. const provider = item.provider;
  1391. const prefix = iconSet.prefix;
  1392. const storage = getStorage(
  1393. provider,
  1394. prefix
  1395. );
  1396. if (!addIconSet(storage, iconSet).length) {
  1397. return false;
  1398. }
  1399. const lastModified = iconSet.lastModified || -1;
  1400. storage.lastModifiedCached = storage.lastModifiedCached ? Math.min(storage.lastModifiedCached, lastModified) : lastModified;
  1401. return true;
  1402. });
  1403. }
  1404. }
  1405. function updateLastModified(storage, lastModified) {
  1406. const lastValue = storage.lastModifiedCached;
  1407. if (lastValue && lastValue >= lastModified) {
  1408. return lastValue === lastModified;
  1409. }
  1410. storage.lastModifiedCached = lastModified;
  1411. if (lastValue) {
  1412. for (const key in browserStorageConfig) {
  1413. iterateBrowserStorage(key, (item) => {
  1414. const iconSet = item.data;
  1415. return item.provider !== storage.provider || iconSet.prefix !== storage.prefix || iconSet.lastModified === lastModified;
  1416. });
  1417. }
  1418. }
  1419. return true;
  1420. }
  1421. function storeInBrowserStorage(storage, data) {
  1422. if (!browserStorageStatus) {
  1423. initBrowserStorage();
  1424. }
  1425. function store(key) {
  1426. let func;
  1427. if (!browserStorageConfig[key] || !(func = getBrowserStorage(key))) {
  1428. return;
  1429. }
  1430. const set = browserStorageEmptyItems[key];
  1431. let index;
  1432. if (set.size) {
  1433. set.delete(index = Array.from(set).shift());
  1434. } else {
  1435. index = getBrowserStorageItemsCount(func);
  1436. if (!setBrowserStorageItemsCount(func, index + 1)) {
  1437. return;
  1438. }
  1439. }
  1440. const item = {
  1441. cached: Math.floor(Date.now() / browserStorageHour),
  1442. provider: storage.provider,
  1443. data
  1444. };
  1445. return setStoredItem(
  1446. func,
  1447. browserCachePrefix + index.toString(),
  1448. JSON.stringify(item)
  1449. );
  1450. }
  1451. if (data.lastModified && !updateLastModified(storage, data.lastModified)) {
  1452. return;
  1453. }
  1454. if (!Object.keys(data.icons).length) {
  1455. return;
  1456. }
  1457. if (data.not_found) {
  1458. data = Object.assign({}, data);
  1459. delete data.not_found;
  1460. }
  1461. if (!store("local")) {
  1462. store("session");
  1463. }
  1464. }
  1465. function emptyCallback() {
  1466. }
  1467. function loadedNewIcons(storage) {
  1468. if (!storage.iconsLoaderFlag) {
  1469. storage.iconsLoaderFlag = true;
  1470. setTimeout(() => {
  1471. storage.iconsLoaderFlag = false;
  1472. updateCallbacks(storage);
  1473. });
  1474. }
  1475. }
  1476. function loadNewIcons(storage, icons) {
  1477. if (!storage.iconsToLoad) {
  1478. storage.iconsToLoad = icons;
  1479. } else {
  1480. storage.iconsToLoad = storage.iconsToLoad.concat(icons).sort();
  1481. }
  1482. if (!storage.iconsQueueFlag) {
  1483. storage.iconsQueueFlag = true;
  1484. setTimeout(() => {
  1485. storage.iconsQueueFlag = false;
  1486. const { provider, prefix } = storage;
  1487. const icons2 = storage.iconsToLoad;
  1488. delete storage.iconsToLoad;
  1489. let api;
  1490. if (!icons2 || !(api = getAPIModule(provider))) {
  1491. return;
  1492. }
  1493. const params = api.prepare(provider, prefix, icons2);
  1494. params.forEach((item) => {
  1495. sendAPIQuery(provider, item, (data) => {
  1496. if (typeof data !== "object") {
  1497. item.icons.forEach((name) => {
  1498. storage.missing.add(name);
  1499. });
  1500. } else {
  1501. try {
  1502. const parsed = addIconSet(
  1503. storage,
  1504. data
  1505. );
  1506. if (!parsed.length) {
  1507. return;
  1508. }
  1509. const pending = storage.pendingIcons;
  1510. if (pending) {
  1511. parsed.forEach((name) => {
  1512. pending.delete(name);
  1513. });
  1514. }
  1515. storeInBrowserStorage(storage, data);
  1516. } catch (err) {
  1517. console.error(err);
  1518. }
  1519. }
  1520. loadedNewIcons(storage);
  1521. });
  1522. });
  1523. });
  1524. }
  1525. }
  1526. const isPending = (icon) => {
  1527. const storage = getStorage(
  1528. icon.provider,
  1529. icon.prefix
  1530. );
  1531. const pending = storage.pendingIcons;
  1532. return !!(pending && pending.has(icon.name));
  1533. };
  1534. const loadIcons = (icons, callback) => {
  1535. const cleanedIcons = listToIcons(icons, true, allowSimpleNames());
  1536. const sortedIcons = sortIcons(cleanedIcons);
  1537. if (!sortedIcons.pending.length) {
  1538. let callCallback = true;
  1539. if (callback) {
  1540. setTimeout(() => {
  1541. if (callCallback) {
  1542. callback(
  1543. sortedIcons.loaded,
  1544. sortedIcons.missing,
  1545. sortedIcons.pending,
  1546. emptyCallback
  1547. );
  1548. }
  1549. });
  1550. }
  1551. return () => {
  1552. callCallback = false;
  1553. };
  1554. }
  1555. const newIcons = /* @__PURE__ */ Object.create(null);
  1556. const sources = [];
  1557. let lastProvider, lastPrefix;
  1558. sortedIcons.pending.forEach((icon) => {
  1559. const { provider, prefix } = icon;
  1560. if (prefix === lastPrefix && provider === lastProvider) {
  1561. return;
  1562. }
  1563. lastProvider = provider;
  1564. lastPrefix = prefix;
  1565. sources.push(getStorage(provider, prefix));
  1566. const providerNewIcons = newIcons[provider] || (newIcons[provider] = /* @__PURE__ */ Object.create(null));
  1567. if (!providerNewIcons[prefix]) {
  1568. providerNewIcons[prefix] = [];
  1569. }
  1570. });
  1571. sortedIcons.pending.forEach((icon) => {
  1572. const { provider, prefix, name } = icon;
  1573. const storage = getStorage(provider, prefix);
  1574. const pendingQueue = storage.pendingIcons || (storage.pendingIcons = /* @__PURE__ */ new Set());
  1575. if (!pendingQueue.has(name)) {
  1576. pendingQueue.add(name);
  1577. newIcons[provider][prefix].push(name);
  1578. }
  1579. });
  1580. sources.forEach((storage) => {
  1581. const { provider, prefix } = storage;
  1582. if (newIcons[provider][prefix].length) {
  1583. loadNewIcons(storage, newIcons[provider][prefix]);
  1584. }
  1585. });
  1586. return callback ? storeCallback(callback, sortedIcons, sources) : emptyCallback;
  1587. };
  1588. /**
  1589. * Compare props
  1590. */
  1591. function propsChanged(props1, props2) {
  1592. if (props1.name !== props2.name || props1.mode !== props2.mode) {
  1593. return true;
  1594. }
  1595. const customisations1 = props1.customisations;
  1596. const customisations2 = props2.customisations;
  1597. for (const key in defaultExtendedIconCustomisations) {
  1598. if (customisations1[key] !== customisations2[key]) {
  1599. return true;
  1600. }
  1601. }
  1602. return false;
  1603. }
  1604. function rotateFromString(value, defaultValue = 0) {
  1605. const units = value.replace(/^-?[0-9.]*/, "");
  1606. function cleanup(value2) {
  1607. while (value2 < 0) {
  1608. value2 += 4;
  1609. }
  1610. return value2 % 4;
  1611. }
  1612. if (units === "") {
  1613. const num = parseInt(value);
  1614. return isNaN(num) ? 0 : cleanup(num);
  1615. } else if (units !== value) {
  1616. let split = 0;
  1617. switch (units) {
  1618. case "%":
  1619. split = 25;
  1620. break;
  1621. case "deg":
  1622. split = 90;
  1623. }
  1624. if (split) {
  1625. let num = parseFloat(value.slice(0, value.length - units.length));
  1626. if (isNaN(num)) {
  1627. return 0;
  1628. }
  1629. num = num / split;
  1630. return num % 1 === 0 ? cleanup(num) : 0;
  1631. }
  1632. }
  1633. return defaultValue;
  1634. }
  1635. const separator = /[\s,]+/;
  1636. function flipFromString(custom, flip) {
  1637. flip.split(separator).forEach((str) => {
  1638. const value = str.trim();
  1639. switch (value) {
  1640. case "horizontal":
  1641. custom.hFlip = true;
  1642. break;
  1643. case "vertical":
  1644. custom.vFlip = true;
  1645. break;
  1646. }
  1647. });
  1648. }
  1649. /**
  1650. * Size attributes
  1651. */
  1652. const sizeAttributes = ['width', 'height'];
  1653. /**
  1654. * Boolean attributes
  1655. */
  1656. const booleanAttributes = [
  1657. 'inline',
  1658. 'hFlip',
  1659. 'vFlip',
  1660. ];
  1661. /**
  1662. * Get attribute value
  1663. */
  1664. function getBooleanAttribute(value, key) {
  1665. if (value === key || value === 'true') {
  1666. return true;
  1667. }
  1668. if (value === '' || value === 'false') {
  1669. return false;
  1670. }
  1671. return null;
  1672. }
  1673. /**
  1674. * Get element properties from HTML element
  1675. */
  1676. function getElementProps(element) {
  1677. // Get icon name
  1678. const name = element.getAttribute('data-icon');
  1679. const icon = typeof name === 'string' && stringToIcon(name, true);
  1680. if (!icon) {
  1681. return null;
  1682. }
  1683. // Get defaults and inline
  1684. const customisations = {
  1685. ...defaultExtendedIconCustomisations,
  1686. inline: element.classList && element.classList.contains(inlineClass),
  1687. };
  1688. // Get dimensions
  1689. sizeAttributes.forEach((attr) => {
  1690. const value = element.getAttribute('data-' + attr);
  1691. if (value) {
  1692. customisations[attr] = value;
  1693. }
  1694. });
  1695. // Get rotation
  1696. const rotation = element.getAttribute('data-rotate');
  1697. if (typeof rotation === 'string') {
  1698. customisations.rotate = rotateFromString(rotation);
  1699. }
  1700. // Get flip shorthand
  1701. const flip = element.getAttribute('data-flip');
  1702. if (typeof flip === 'string') {
  1703. flipFromString(customisations, flip);
  1704. }
  1705. // Boolean attributes
  1706. booleanAttributes.forEach((attr) => {
  1707. const key = 'data-' + attr;
  1708. const value = getBooleanAttribute(element.getAttribute(key), key);
  1709. if (typeof value === 'boolean') {
  1710. customisations[attr] = value;
  1711. }
  1712. });
  1713. // Get render mode. Not checking actual value because incorrect values are treated as inline
  1714. const mode = element.getAttribute('data-mode');
  1715. return {
  1716. name,
  1717. icon,
  1718. customisations,
  1719. mode,
  1720. };
  1721. }
  1722. /**
  1723. * Selector combining class names and tags
  1724. */
  1725. const selector = 'svg.' +
  1726. blockClass +
  1727. ', i.' +
  1728. blockClass +
  1729. ', span.' +
  1730. blockClass +
  1731. ', i.' +
  1732. inlineClass +
  1733. ', span.' +
  1734. inlineClass;
  1735. /**
  1736. * Find all parent nodes in DOM
  1737. */
  1738. function scanRootNode(root) {
  1739. const nodes = [];
  1740. root.querySelectorAll(selector).forEach((node) => {
  1741. // Get props, ignore SVG rendered outside of SVG framework
  1742. const props = node[elementDataProperty] || node.tagName.toLowerCase() !== 'svg'
  1743. ? getElementProps(node)
  1744. : null;
  1745. if (props) {
  1746. nodes.push({
  1747. node,
  1748. props,
  1749. });
  1750. }
  1751. });
  1752. return nodes;
  1753. }
  1754. function iconToHTML(body, attributes) {
  1755. let renderAttribsHTML = body.indexOf("xlink:") === -1 ? "" : ' xmlns:xlink="http://www.w3.org/1999/xlink"';
  1756. for (const attr in attributes) {
  1757. renderAttribsHTML += " " + attr + '="' + attributes[attr] + '"';
  1758. }
  1759. return '<svg xmlns="http://www.w3.org/2000/svg"' + renderAttribsHTML + ">" + body + "</svg>";
  1760. }
  1761. /**
  1762. * Get classes to add from icon name
  1763. */
  1764. function iconClasses(iconName) {
  1765. const classesToAdd = new Set(['iconify']);
  1766. ['provider', 'prefix'].forEach((attr) => {
  1767. if (iconName[attr]) {
  1768. classesToAdd.add('iconify--' + iconName[attr]);
  1769. }
  1770. });
  1771. return classesToAdd;
  1772. }
  1773. /**
  1774. * Add classes to SVG, removing previously added classes, keeping custom classes
  1775. */
  1776. function applyClasses(svg, classes, previouslyAddedClasses, placeholder) {
  1777. const svgClasses = svg.classList;
  1778. // Copy classes from placeholder
  1779. if (placeholder) {
  1780. const placeholderClasses = placeholder.classList;
  1781. Array.from(placeholderClasses).forEach((item) => {
  1782. svgClasses.add(item);
  1783. });
  1784. }
  1785. // Add new classes
  1786. const addedClasses = [];
  1787. classes.forEach((item) => {
  1788. if (!svgClasses.contains(item)) {
  1789. // Add new class
  1790. svgClasses.add(item);
  1791. addedClasses.push(item);
  1792. }
  1793. else if (previouslyAddedClasses.has(item)) {
  1794. // Was added before: keep it
  1795. addedClasses.push(item);
  1796. }
  1797. });
  1798. // Remove previously added classes
  1799. previouslyAddedClasses.forEach((item) => {
  1800. if (!classes.has(item)) {
  1801. // Class that was added before, but no longer needed
  1802. svgClasses.remove(item);
  1803. }
  1804. });
  1805. return addedClasses;
  1806. }
  1807. /**
  1808. * Copy old styles, apply new styles
  1809. */
  1810. function applyStyle(svg, styles, previouslyAddedStyles) {
  1811. const svgStyle = svg.style;
  1812. // Remove previously added styles
  1813. (previouslyAddedStyles || []).forEach((prop) => {
  1814. svgStyle.removeProperty(prop);
  1815. });
  1816. // Apply new styles, ignoring styles that already exist
  1817. const appliedStyles = [];
  1818. for (const prop in styles) {
  1819. if (!svgStyle.getPropertyValue(prop)) {
  1820. appliedStyles.push(prop);
  1821. svgStyle.setProperty(prop, styles[prop]);
  1822. }
  1823. }
  1824. return appliedStyles;
  1825. }
  1826. /**
  1827. * Render icon as inline SVG
  1828. */
  1829. function renderInlineSVG(element, props, iconData) {
  1830. // Create placeholder. Why placeholder? innerHTML setter on SVG does not work in some environments.
  1831. let span;
  1832. try {
  1833. span = document.createElement('span');
  1834. }
  1835. catch (err) {
  1836. return element;
  1837. }
  1838. // Generate data to render
  1839. const customisations = props.customisations;
  1840. const renderData = iconToSVG(iconData, customisations);
  1841. // Get old data
  1842. const oldData = element[elementDataProperty];
  1843. // Generate SVG
  1844. const html = iconToHTML(replaceIDs(renderData.body), {
  1845. 'aria-hidden': 'true',
  1846. 'role': 'img',
  1847. ...renderData.attributes,
  1848. });
  1849. span.innerHTML = html;
  1850. // Get SVG element
  1851. const svg = span.childNodes[0];
  1852. // Add attributes
  1853. const placeholderAttributes = element.attributes;
  1854. for (let i = 0; i < placeholderAttributes.length; i++) {
  1855. const item = placeholderAttributes.item(i);
  1856. const name = item.name;
  1857. if (name !== 'class' && !svg.hasAttribute(name)) {
  1858. svg.setAttribute(name, item.value);
  1859. }
  1860. }
  1861. // Add classes
  1862. const classesToAdd = iconClasses(props.icon);
  1863. const addedClasses = applyClasses(svg, classesToAdd, new Set(oldData && oldData.addedClasses), element);
  1864. // Update style
  1865. const addedStyles = applyStyle(svg, customisations.inline
  1866. ? {
  1867. 'vertical-align': '-0.125em',
  1868. }
  1869. : {}, oldData && oldData.addedStyles);
  1870. // Add data to element
  1871. const newData = {
  1872. ...props,
  1873. status: 'loaded',
  1874. addedClasses,
  1875. addedStyles,
  1876. };
  1877. svg[elementDataProperty] = newData;
  1878. // Replace old element
  1879. if (element.parentNode) {
  1880. element.parentNode.replaceChild(svg, element);
  1881. }
  1882. return svg;
  1883. }
  1884. function encodeSVGforURL(svg) {
  1885. return svg.replace(/"/g, "'").replace(/%/g, "%25").replace(/#/g, "%23").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\s+/g, " ");
  1886. }
  1887. function svgToURL(svg) {
  1888. return 'url("data:image/svg+xml,' + encodeSVGforURL(svg) + '")';
  1889. }
  1890. const commonProps = {
  1891. display: 'inline-block',
  1892. };
  1893. const monotoneProps = {
  1894. 'background-color': 'currentColor',
  1895. };
  1896. const coloredProps = {
  1897. 'background-color': 'transparent',
  1898. };
  1899. // Dynamically add common props to variables above
  1900. const propsToAdd = {
  1901. image: 'var(--svg)',
  1902. repeat: 'no-repeat',
  1903. size: '100% 100%',
  1904. };
  1905. const propsToAddTo = {
  1906. '-webkit-mask': monotoneProps,
  1907. 'mask': monotoneProps,
  1908. 'background': coloredProps,
  1909. };
  1910. for (const prefix in propsToAddTo) {
  1911. const list = propsToAddTo[prefix];
  1912. for (const prop in propsToAdd) {
  1913. list[prefix + '-' + prop] = propsToAdd[prop];
  1914. }
  1915. }
  1916. /**
  1917. * Fix size: add 'px' to numbers
  1918. */
  1919. function fixSize(value) {
  1920. return value + (value.match(/^[-0-9.]+$/) ? 'px' : '');
  1921. }
  1922. /**
  1923. * Render icon as inline SVG
  1924. */
  1925. function renderBackground(element, props, iconData, useMask) {
  1926. // Generate data to render
  1927. const customisations = props.customisations;
  1928. const renderData = iconToSVG(iconData, customisations);
  1929. const renderAttribs = renderData.attributes;
  1930. // Get old data
  1931. const oldData = element[elementDataProperty];
  1932. // Generate SVG
  1933. const html = iconToHTML(renderData.body, {
  1934. ...renderAttribs,
  1935. width: iconData.width + '',
  1936. height: iconData.height + '',
  1937. });
  1938. // Add classes
  1939. const classesToAdd = iconClasses(props.icon);
  1940. const addedClasses = applyClasses(element, classesToAdd, new Set(oldData && oldData.addedClasses));
  1941. // Update style
  1942. const url = svgToURL(html);
  1943. const newStyles = {
  1944. '--svg': url,
  1945. 'width': fixSize(renderAttribs.width),
  1946. 'height': fixSize(renderAttribs.height),
  1947. ...commonProps,
  1948. ...(useMask ? monotoneProps : coloredProps),
  1949. };
  1950. if (customisations.inline) {
  1951. newStyles['vertical-align'] = '-0.125em';
  1952. }
  1953. const addedStyles = applyStyle(element, newStyles, oldData && oldData.addedStyles);
  1954. // Add data to element
  1955. const newData = {
  1956. ...props,
  1957. status: 'loaded',
  1958. addedClasses,
  1959. addedStyles,
  1960. };
  1961. element[elementDataProperty] = newData;
  1962. return element;
  1963. }
  1964. /**
  1965. * Flag to avoid scanning DOM too often
  1966. */
  1967. let scanQueued = false;
  1968. /**
  1969. * Icons have been loaded
  1970. */
  1971. function checkPendingIcons() {
  1972. if (!scanQueued) {
  1973. scanQueued = true;
  1974. setTimeout(() => {
  1975. if (scanQueued) {
  1976. scanQueued = false;
  1977. scanDOM();
  1978. }
  1979. });
  1980. }
  1981. }
  1982. /**
  1983. * Scan node for placeholders
  1984. */
  1985. function scanDOM(rootNode, addTempNode = false) {
  1986. // List of icons to load: [provider][prefix] = Set<name>
  1987. const iconsToLoad = Object.create(null);
  1988. function getIcon(icon, load) {
  1989. const { provider, prefix, name } = icon;
  1990. const storage = getStorage(provider, prefix);
  1991. const storedIcon = storage.icons[name];
  1992. if (storedIcon) {
  1993. return {
  1994. status: 'loaded',
  1995. icon: storedIcon,
  1996. };
  1997. }
  1998. if (storage.missing.has(name)) {
  1999. return {
  2000. status: 'missing',
  2001. };
  2002. }
  2003. if (load && !isPending(icon)) {
  2004. const providerIconsToLoad = iconsToLoad[provider] ||
  2005. (iconsToLoad[provider] = Object.create(null));
  2006. const set = providerIconsToLoad[prefix] ||
  2007. (providerIconsToLoad[prefix] = new Set());
  2008. set.add(name);
  2009. }
  2010. return {
  2011. status: 'loading',
  2012. };
  2013. }
  2014. // Parse all root nodes
  2015. (rootNode ? [rootNode] : listRootNodes()).forEach((observedNode) => {
  2016. const root = typeof observedNode.node === 'function'
  2017. ? observedNode.node()
  2018. : observedNode.node;
  2019. if (!root || !root.querySelectorAll) {
  2020. return;
  2021. }
  2022. // Track placeholders
  2023. let hasPlaceholders = false;
  2024. // Observer
  2025. let paused = false;
  2026. /**
  2027. * Render icon
  2028. */
  2029. function render(element, props, iconData) {
  2030. if (!paused) {
  2031. paused = true;
  2032. pauseObservingNode(observedNode);
  2033. }
  2034. if (element.tagName.toUpperCase() !== 'SVG') {
  2035. // Check for one of style modes
  2036. const mode = props.mode;
  2037. const isMask = mode === 'mask' ||
  2038. (mode === 'bg'
  2039. ? false
  2040. : mode === 'style'
  2041. ? iconData.body.indexOf('currentColor') !== -1
  2042. : null);
  2043. if (typeof isMask === 'boolean') {
  2044. renderBackground(element, props, {
  2045. ...defaultIconProps,
  2046. ...iconData,
  2047. }, isMask);
  2048. return;
  2049. }
  2050. }
  2051. renderInlineSVG(element, props, iconData);
  2052. }
  2053. // Find all elements
  2054. scanRootNode(root).forEach(({ node, props }) => {
  2055. // Check if item already has props
  2056. const oldData = node[elementDataProperty];
  2057. if (!oldData) {
  2058. // New icon without data
  2059. const { status, icon } = getIcon(props.icon, true);
  2060. if (icon) {
  2061. // Ready to render!
  2062. render(node, props, icon);
  2063. return;
  2064. }
  2065. // Loading or missing
  2066. hasPlaceholders = hasPlaceholders || status === 'loading';
  2067. node[elementDataProperty] = {
  2068. ...props,
  2069. status,
  2070. };
  2071. return;
  2072. }
  2073. // Previously found icon
  2074. let item;
  2075. if (!propsChanged(oldData, props)) {
  2076. // Props have not changed. Check status
  2077. const oldStatus = oldData.status;
  2078. if (oldStatus !== 'loading') {
  2079. return;
  2080. }
  2081. item = getIcon(props.icon, false);
  2082. if (!item.icon) {
  2083. // Nothing to render
  2084. oldData.status = item.status;
  2085. return;
  2086. }
  2087. }
  2088. else {
  2089. // Properties have changed: load icon if name has changed
  2090. item = getIcon(props.icon, oldData.name !== props.name);
  2091. if (!item.icon) {
  2092. // Cannot render icon: update status and props
  2093. hasPlaceholders =
  2094. hasPlaceholders || item.status === 'loading';
  2095. Object.assign(oldData, {
  2096. ...props,
  2097. status: item.status,
  2098. });
  2099. return;
  2100. }
  2101. }
  2102. // Re-render icon
  2103. render(node, props, item.icon);
  2104. });
  2105. // Observed node stuff
  2106. if (observedNode.temporary && !hasPlaceholders) {
  2107. // Remove temporary node
  2108. stopObserving(root);
  2109. }
  2110. else if (addTempNode && hasPlaceholders) {
  2111. // Add new temporary node
  2112. observe(root, true);
  2113. }
  2114. else if (paused && observedNode.observer) {
  2115. // Resume observer
  2116. resumeObservingNode(observedNode);
  2117. }
  2118. });
  2119. // Load icons
  2120. for (const provider in iconsToLoad) {
  2121. const providerIconsToLoad = iconsToLoad[provider];
  2122. for (const prefix in providerIconsToLoad) {
  2123. const set = providerIconsToLoad[prefix];
  2124. loadIcons(Array.from(set).map((name) => ({
  2125. provider,
  2126. prefix,
  2127. name,
  2128. })), checkPendingIcons);
  2129. }
  2130. }
  2131. }
  2132. /**
  2133. * Scan node for placeholders
  2134. */
  2135. function scanElement(root) {
  2136. // Add temporary node
  2137. const node = findRootNode(root);
  2138. if (!node) {
  2139. scanDOM({
  2140. node: root,
  2141. temporary: true,
  2142. }, true);
  2143. }
  2144. else {
  2145. scanDOM(node);
  2146. }
  2147. }
  2148. function generateIcon(name, customisations, returnString = false) {
  2149. // Get icon data
  2150. const iconData = getIconData(name);
  2151. if (!iconData) {
  2152. return null;
  2153. }
  2154. // Split name
  2155. const iconName = stringToIcon(name);
  2156. // Clean up customisations
  2157. const changes = mergeCustomisations(defaultExtendedIconCustomisations, customisations || {});
  2158. // Get data
  2159. const result = renderInlineSVG(document.createElement('span'), {
  2160. name,
  2161. icon: iconName,
  2162. customisations: changes,
  2163. }, iconData);
  2164. return returnString
  2165. ? result.outerHTML
  2166. : result;
  2167. }
  2168. /**
  2169. * Get version
  2170. */
  2171. function getVersion() {
  2172. return '3.1.0';
  2173. }
  2174. /**
  2175. * Generate SVG element
  2176. */
  2177. function renderSVG(name, customisations) {
  2178. return generateIcon(name, customisations, false);
  2179. }
  2180. /**
  2181. * Generate SVG as string
  2182. */
  2183. function renderHTML(name, customisations) {
  2184. return generateIcon(name, customisations, true);
  2185. }
  2186. /**
  2187. * Get rendered icon as object that can be used to create SVG (use replaceIDs on body)
  2188. */
  2189. function renderIcon(name, customisations) {
  2190. // Get icon data
  2191. const iconData = getIconData(name);
  2192. if (!iconData) {
  2193. return null;
  2194. }
  2195. // Clean up customisations
  2196. const changes = mergeCustomisations(defaultExtendedIconCustomisations, customisations || {});
  2197. // Get data
  2198. return iconToSVG(iconData, changes);
  2199. }
  2200. /**
  2201. * Scan DOM
  2202. */
  2203. function scan(root) {
  2204. if (root) {
  2205. scanElement(root);
  2206. }
  2207. else {
  2208. scanDOM();
  2209. }
  2210. }
  2211. /**
  2212. * Initialise stuff
  2213. */
  2214. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  2215. // Add document.body node
  2216. addBodyNode();
  2217. const _window = window;
  2218. // Load icons from global "IconifyPreload"
  2219. if (_window.IconifyPreload !== void 0) {
  2220. const preload = _window.IconifyPreload;
  2221. const err = 'Invalid IconifyPreload syntax.';
  2222. if (typeof preload === 'object' && preload !== null) {
  2223. (preload instanceof Array ? preload : [preload]).forEach((item) => {
  2224. try {
  2225. if (
  2226. // Check if item is an object and not null/array
  2227. typeof item !== 'object' ||
  2228. item === null ||
  2229. item instanceof Array ||
  2230. // Check for 'icons' and 'prefix'
  2231. typeof item.icons !== 'object' ||
  2232. typeof item.prefix !== 'string' ||
  2233. // Add icon set
  2234. !addCollection(item)) {
  2235. console.error(err);
  2236. }
  2237. }
  2238. catch (e) {
  2239. console.error(err);
  2240. }
  2241. });
  2242. }
  2243. }
  2244. // Load observer and scan DOM on next tick
  2245. setTimeout(() => {
  2246. initObserver(scanDOM);
  2247. scanDOM();
  2248. });
  2249. }
  2250. /**
  2251. * Global variable
  2252. */
  2253. const Iconify = {
  2254. // IconifyStorageFunctions
  2255. iconExists,
  2256. getIcon,
  2257. listIcons,
  2258. addIcon,
  2259. addCollection,
  2260. // IconifyBuilderFunctions
  2261. replaceIDs,
  2262. calculateSize,
  2263. buildIcon: iconToSVG,
  2264. // IconifyCommonFunctions
  2265. getVersion,
  2266. renderSVG,
  2267. renderHTML,
  2268. renderIcon,
  2269. scan,
  2270. observe,
  2271. stopObserving,
  2272. pauseObserver,
  2273. resumeObserver,
  2274. };
  2275. exports.addCollection = addCollection;
  2276. exports.addIcon = addIcon;
  2277. exports.buildIcon = iconToSVG;
  2278. exports.calculateSize = calculateSize;
  2279. exports.default = Iconify;
  2280. exports.getIcon = getIcon;
  2281. exports.getVersion = getVersion;
  2282. exports.iconExists = iconExists;
  2283. exports.listIcons = listIcons;
  2284. exports.observe = observe;
  2285. exports.pauseObserver = pauseObserver;
  2286. exports.renderHTML = renderHTML;
  2287. exports.renderIcon = renderIcon;
  2288. exports.renderSVG = renderSVG;
  2289. exports.replaceIDs = replaceIDs;
  2290. exports.resumeObserver = resumeObserver;
  2291. exports.scan = scan;
  2292. exports.stopObserving = stopObserving;
  2293. // Export to window or web worker
  2294. try {
  2295. if (self.Iconify === void 0) {
  2296. self.Iconify = Iconify;
  2297. }
  2298. } catch (err) {
  2299. }