iconify.without-api.mjs 61 KB

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