iconify.cjs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613
  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. const browserStorageConfig = {
  508. local: true,
  509. session: true
  510. };
  511. const browserStorageEmptyItems = {
  512. local: /* @__PURE__ */ new Set(),
  513. session: /* @__PURE__ */ new Set()
  514. };
  515. let browserStorageStatus = false;
  516. function setBrowserStorageStatus(status) {
  517. browserStorageStatus = status;
  518. }
  519. const browserCacheVersion = "iconify2";
  520. const browserCachePrefix = "iconify";
  521. const browserCacheCountKey = browserCachePrefix + "-count";
  522. const browserCacheVersionKey = browserCachePrefix + "-version";
  523. const browserStorageHour = 36e5;
  524. const browserStorageCacheExpiration = 168;
  525. function getStoredItem(func, key) {
  526. try {
  527. return func.getItem(key);
  528. } catch (err) {
  529. }
  530. }
  531. function setStoredItem(func, key, value) {
  532. try {
  533. func.setItem(key, value);
  534. return true;
  535. } catch (err) {
  536. }
  537. }
  538. function removeStoredItem(func, key) {
  539. try {
  540. func.removeItem(key);
  541. } catch (err) {
  542. }
  543. }
  544. function setBrowserStorageItemsCount(storage, value) {
  545. return setStoredItem(storage, browserCacheCountKey, value.toString());
  546. }
  547. function getBrowserStorageItemsCount(storage) {
  548. return parseInt(getStoredItem(storage, browserCacheCountKey)) || 0;
  549. }
  550. let _window = typeof window === "undefined" ? {} : window;
  551. function getBrowserStorage(key) {
  552. const attr = key + "Storage";
  553. try {
  554. if (_window && _window[attr] && typeof _window[attr].length === "number") {
  555. return _window[attr];
  556. }
  557. } catch (err) {
  558. }
  559. browserStorageConfig[key] = false;
  560. }
  561. function iterateBrowserStorage(key, callback) {
  562. const func = getBrowserStorage(key);
  563. if (!func) {
  564. return;
  565. }
  566. const version = getStoredItem(func, browserCacheVersionKey);
  567. if (version !== browserCacheVersion) {
  568. if (version) {
  569. const total2 = getBrowserStorageItemsCount(func);
  570. for (let i = 0; i < total2; i++) {
  571. removeStoredItem(func, browserCachePrefix + i.toString());
  572. }
  573. }
  574. setStoredItem(func, browserCacheVersionKey, browserCacheVersion);
  575. setBrowserStorageItemsCount(func, 0);
  576. return;
  577. }
  578. const minTime = Math.floor(Date.now() / browserStorageHour) - browserStorageCacheExpiration;
  579. const parseItem = (index) => {
  580. const name = browserCachePrefix + index.toString();
  581. const item = getStoredItem(func, name);
  582. if (typeof item !== "string") {
  583. return;
  584. }
  585. try {
  586. const data = JSON.parse(item);
  587. 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)) {
  588. return true;
  589. }
  590. } catch (err) {
  591. }
  592. removeStoredItem(func, name);
  593. };
  594. let total = getBrowserStorageItemsCount(func);
  595. for (let i = total - 1; i >= 0; i--) {
  596. if (!parseItem(i)) {
  597. if (i === total - 1) {
  598. total--;
  599. setBrowserStorageItemsCount(func, total);
  600. } else {
  601. browserStorageEmptyItems[key].add(i);
  602. }
  603. }
  604. }
  605. }
  606. function initBrowserStorage() {
  607. if (browserStorageStatus) {
  608. return;
  609. }
  610. setBrowserStorageStatus(true);
  611. for (const key in browserStorageConfig) {
  612. iterateBrowserStorage(key, (item) => {
  613. const iconSet = item.data;
  614. const provider = item.provider;
  615. const prefix = iconSet.prefix;
  616. const storage = getStorage(
  617. provider,
  618. prefix
  619. );
  620. if (!addIconSet(storage, iconSet).length) {
  621. return false;
  622. }
  623. const lastModified = iconSet.lastModified || -1;
  624. storage.lastModifiedCached = storage.lastModifiedCached ? Math.min(storage.lastModifiedCached, lastModified) : lastModified;
  625. return true;
  626. });
  627. }
  628. }
  629. function toggleBrowserCache(storage, value) {
  630. switch (storage) {
  631. case "local":
  632. case "session":
  633. browserStorageConfig[storage] = value;
  634. break;
  635. case "all":
  636. for (const key in browserStorageConfig) {
  637. browserStorageConfig[key] = value;
  638. }
  639. break;
  640. }
  641. }
  642. const storage = /* @__PURE__ */ Object.create(null);
  643. function setAPIModule(provider, item) {
  644. storage[provider] = item;
  645. }
  646. function getAPIModule(provider) {
  647. return storage[provider] || storage[""];
  648. }
  649. function createAPIConfig(source) {
  650. let resources;
  651. if (typeof source.resources === "string") {
  652. resources = [source.resources];
  653. } else {
  654. resources = source.resources;
  655. if (!(resources instanceof Array) || !resources.length) {
  656. return null;
  657. }
  658. }
  659. const result = {
  660. resources,
  661. path: source.path || "/",
  662. maxURL: source.maxURL || 500,
  663. rotate: source.rotate || 750,
  664. timeout: source.timeout || 5e3,
  665. random: source.random === true,
  666. index: source.index || 0,
  667. dataAfterTimeout: source.dataAfterTimeout !== false
  668. };
  669. return result;
  670. }
  671. const configStorage = /* @__PURE__ */ Object.create(null);
  672. const fallBackAPISources = [
  673. "https://api.simplesvg.com",
  674. "https://api.unisvg.com"
  675. ];
  676. const fallBackAPI = [];
  677. while (fallBackAPISources.length > 0) {
  678. if (fallBackAPISources.length === 1) {
  679. fallBackAPI.push(fallBackAPISources.shift());
  680. } else {
  681. if (Math.random() > 0.5) {
  682. fallBackAPI.push(fallBackAPISources.shift());
  683. } else {
  684. fallBackAPI.push(fallBackAPISources.pop());
  685. }
  686. }
  687. }
  688. configStorage[""] = createAPIConfig({
  689. resources: ["https://api.iconify.design"].concat(fallBackAPI)
  690. });
  691. function addAPIProvider(provider, customConfig) {
  692. const config = createAPIConfig(customConfig);
  693. if (config === null) {
  694. return false;
  695. }
  696. configStorage[provider] = config;
  697. return true;
  698. }
  699. function getAPIConfig(provider) {
  700. return configStorage[provider];
  701. }
  702. function listAPIProviders() {
  703. return Object.keys(configStorage);
  704. }
  705. const detectFetch = () => {
  706. let callback;
  707. try {
  708. callback = fetch;
  709. if (typeof callback === "function") {
  710. return callback;
  711. }
  712. } catch (err) {
  713. }
  714. };
  715. let fetchModule = detectFetch();
  716. function setFetch(fetch2) {
  717. fetchModule = fetch2;
  718. }
  719. function getFetch() {
  720. return fetchModule;
  721. }
  722. function calculateMaxLength(provider, prefix) {
  723. const config = getAPIConfig(provider);
  724. if (!config) {
  725. return 0;
  726. }
  727. let result;
  728. if (!config.maxURL) {
  729. result = 0;
  730. } else {
  731. let maxHostLength = 0;
  732. config.resources.forEach((item) => {
  733. const host = item;
  734. maxHostLength = Math.max(maxHostLength, host.length);
  735. });
  736. const url = prefix + ".json?icons=";
  737. result = config.maxURL - maxHostLength - config.path.length - url.length;
  738. }
  739. return result;
  740. }
  741. function shouldAbort(status) {
  742. return status === 404;
  743. }
  744. const prepare = (provider, prefix, icons) => {
  745. const results = [];
  746. const maxLength = calculateMaxLength(provider, prefix);
  747. const type = "icons";
  748. let item = {
  749. type,
  750. provider,
  751. prefix,
  752. icons: []
  753. };
  754. let length = 0;
  755. icons.forEach((name, index) => {
  756. length += name.length + 1;
  757. if (length >= maxLength && index > 0) {
  758. results.push(item);
  759. item = {
  760. type,
  761. provider,
  762. prefix,
  763. icons: []
  764. };
  765. length = name.length;
  766. }
  767. item.icons.push(name);
  768. });
  769. results.push(item);
  770. return results;
  771. };
  772. function getPath(provider) {
  773. if (typeof provider === "string") {
  774. const config = getAPIConfig(provider);
  775. if (config) {
  776. return config.path;
  777. }
  778. }
  779. return "/";
  780. }
  781. const send = (host, params, callback) => {
  782. if (!fetchModule) {
  783. callback("abort", 424);
  784. return;
  785. }
  786. let path = getPath(params.provider);
  787. switch (params.type) {
  788. case "icons": {
  789. const prefix = params.prefix;
  790. const icons = params.icons;
  791. const iconsList = icons.join(",");
  792. const urlParams = new URLSearchParams({
  793. icons: iconsList
  794. });
  795. path += prefix + ".json?" + urlParams.toString();
  796. break;
  797. }
  798. case "custom": {
  799. const uri = params.uri;
  800. path += uri.slice(0, 1) === "/" ? uri.slice(1) : uri;
  801. break;
  802. }
  803. default:
  804. callback("abort", 400);
  805. return;
  806. }
  807. let defaultError = 503;
  808. fetchModule(host + path).then((response) => {
  809. const status = response.status;
  810. if (status !== 200) {
  811. setTimeout(() => {
  812. callback(shouldAbort(status) ? "abort" : "next", status);
  813. });
  814. return;
  815. }
  816. defaultError = 501;
  817. return response.json();
  818. }).then((data) => {
  819. if (typeof data !== "object" || data === null) {
  820. setTimeout(() => {
  821. if (data === 404) {
  822. callback("abort", data);
  823. } else {
  824. callback("next", defaultError);
  825. }
  826. });
  827. return;
  828. }
  829. setTimeout(() => {
  830. callback("success", data);
  831. });
  832. }).catch(() => {
  833. callback("next", defaultError);
  834. });
  835. };
  836. const fetchAPIModule = {
  837. prepare,
  838. send
  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. function listToIcons(list, validate = true, simpleNames = false) {
  968. const result = [];
  969. list.forEach((item) => {
  970. const icon = typeof item === "string" ? stringToIcon(item, validate, simpleNames) : item;
  971. if (icon) {
  972. result.push(icon);
  973. }
  974. });
  975. return result;
  976. }
  977. // src/config.ts
  978. var defaultConfig = {
  979. resources: [],
  980. index: 0,
  981. timeout: 2e3,
  982. rotate: 750,
  983. random: false,
  984. dataAfterTimeout: false
  985. };
  986. // src/query.ts
  987. function sendQuery(config, payload, query, done) {
  988. const resourcesCount = config.resources.length;
  989. const startIndex = config.random ? Math.floor(Math.random() * resourcesCount) : config.index;
  990. let resources;
  991. if (config.random) {
  992. let list = config.resources.slice(0);
  993. resources = [];
  994. while (list.length > 1) {
  995. const nextIndex = Math.floor(Math.random() * list.length);
  996. resources.push(list[nextIndex]);
  997. list = list.slice(0, nextIndex).concat(list.slice(nextIndex + 1));
  998. }
  999. resources = resources.concat(list);
  1000. } else {
  1001. resources = config.resources.slice(startIndex).concat(config.resources.slice(0, startIndex));
  1002. }
  1003. const startTime = Date.now();
  1004. let status = "pending";
  1005. let queriesSent = 0;
  1006. let lastError;
  1007. let timer = null;
  1008. let queue = [];
  1009. let doneCallbacks = [];
  1010. if (typeof done === "function") {
  1011. doneCallbacks.push(done);
  1012. }
  1013. function resetTimer() {
  1014. if (timer) {
  1015. clearTimeout(timer);
  1016. timer = null;
  1017. }
  1018. }
  1019. function abort() {
  1020. if (status === "pending") {
  1021. status = "aborted";
  1022. }
  1023. resetTimer();
  1024. queue.forEach((item) => {
  1025. if (item.status === "pending") {
  1026. item.status = "aborted";
  1027. }
  1028. });
  1029. queue = [];
  1030. }
  1031. function subscribe(callback, overwrite) {
  1032. if (overwrite) {
  1033. doneCallbacks = [];
  1034. }
  1035. if (typeof callback === "function") {
  1036. doneCallbacks.push(callback);
  1037. }
  1038. }
  1039. function getQueryStatus() {
  1040. return {
  1041. startTime,
  1042. payload,
  1043. status,
  1044. queriesSent,
  1045. queriesPending: queue.length,
  1046. subscribe,
  1047. abort
  1048. };
  1049. }
  1050. function failQuery() {
  1051. status = "failed";
  1052. doneCallbacks.forEach((callback) => {
  1053. callback(void 0, lastError);
  1054. });
  1055. }
  1056. function clearQueue() {
  1057. queue.forEach((item) => {
  1058. if (item.status === "pending") {
  1059. item.status = "aborted";
  1060. }
  1061. });
  1062. queue = [];
  1063. }
  1064. function moduleResponse(item, response, data) {
  1065. const isError = response !== "success";
  1066. queue = queue.filter((queued) => queued !== item);
  1067. switch (status) {
  1068. case "pending":
  1069. break;
  1070. case "failed":
  1071. if (isError || !config.dataAfterTimeout) {
  1072. return;
  1073. }
  1074. break;
  1075. default:
  1076. return;
  1077. }
  1078. if (response === "abort") {
  1079. lastError = data;
  1080. failQuery();
  1081. return;
  1082. }
  1083. if (isError) {
  1084. lastError = data;
  1085. if (!queue.length) {
  1086. if (!resources.length) {
  1087. failQuery();
  1088. } else {
  1089. execNext();
  1090. }
  1091. }
  1092. return;
  1093. }
  1094. resetTimer();
  1095. clearQueue();
  1096. if (!config.random) {
  1097. const index = config.resources.indexOf(item.resource);
  1098. if (index !== -1 && index !== config.index) {
  1099. config.index = index;
  1100. }
  1101. }
  1102. status = "completed";
  1103. doneCallbacks.forEach((callback) => {
  1104. callback(data);
  1105. });
  1106. }
  1107. function execNext() {
  1108. if (status !== "pending") {
  1109. return;
  1110. }
  1111. resetTimer();
  1112. const resource = resources.shift();
  1113. if (resource === void 0) {
  1114. if (queue.length) {
  1115. timer = setTimeout(() => {
  1116. resetTimer();
  1117. if (status === "pending") {
  1118. clearQueue();
  1119. failQuery();
  1120. }
  1121. }, config.timeout);
  1122. return;
  1123. }
  1124. failQuery();
  1125. return;
  1126. }
  1127. const item = {
  1128. status: "pending",
  1129. resource,
  1130. callback: (status2, data) => {
  1131. moduleResponse(item, status2, data);
  1132. }
  1133. };
  1134. queue.push(item);
  1135. queriesSent++;
  1136. timer = setTimeout(execNext, config.rotate);
  1137. query(resource, payload, item.callback);
  1138. }
  1139. setTimeout(execNext);
  1140. return getQueryStatus;
  1141. }
  1142. // src/index.ts
  1143. function initRedundancy(cfg) {
  1144. const config = {
  1145. ...defaultConfig,
  1146. ...cfg
  1147. };
  1148. let queries = [];
  1149. function cleanup() {
  1150. queries = queries.filter((item) => item().status === "pending");
  1151. }
  1152. function query(payload, queryCallback, doneCallback) {
  1153. const query2 = sendQuery(
  1154. config,
  1155. payload,
  1156. queryCallback,
  1157. (data, error) => {
  1158. cleanup();
  1159. if (doneCallback) {
  1160. doneCallback(data, error);
  1161. }
  1162. }
  1163. );
  1164. queries.push(query2);
  1165. return query2;
  1166. }
  1167. function find(callback) {
  1168. return queries.find((value) => {
  1169. return callback(value);
  1170. }) || null;
  1171. }
  1172. const instance = {
  1173. query,
  1174. find,
  1175. setIndex: (index) => {
  1176. config.index = index;
  1177. },
  1178. getIndex: () => config.index,
  1179. cleanup
  1180. };
  1181. return instance;
  1182. }
  1183. function emptyCallback$1() {
  1184. }
  1185. const redundancyCache = /* @__PURE__ */ Object.create(null);
  1186. function getRedundancyCache(provider) {
  1187. if (!redundancyCache[provider]) {
  1188. const config = getAPIConfig(provider);
  1189. if (!config) {
  1190. return;
  1191. }
  1192. const redundancy = initRedundancy(config);
  1193. const cachedReundancy = {
  1194. config,
  1195. redundancy
  1196. };
  1197. redundancyCache[provider] = cachedReundancy;
  1198. }
  1199. return redundancyCache[provider];
  1200. }
  1201. function sendAPIQuery(target, query, callback) {
  1202. let redundancy;
  1203. let send;
  1204. if (typeof target === "string") {
  1205. const api = getAPIModule(target);
  1206. if (!api) {
  1207. callback(void 0, 424);
  1208. return emptyCallback$1;
  1209. }
  1210. send = api.send;
  1211. const cached = getRedundancyCache(target);
  1212. if (cached) {
  1213. redundancy = cached.redundancy;
  1214. }
  1215. } else {
  1216. const config = createAPIConfig(target);
  1217. if (config) {
  1218. redundancy = initRedundancy(config);
  1219. const moduleKey = target.resources ? target.resources[0] : "";
  1220. const api = getAPIModule(moduleKey);
  1221. if (api) {
  1222. send = api.send;
  1223. }
  1224. }
  1225. }
  1226. if (!redundancy || !send) {
  1227. callback(void 0, 424);
  1228. return emptyCallback$1;
  1229. }
  1230. return redundancy.query(query, send, callback)().abort;
  1231. }
  1232. function updateLastModified(storage, lastModified) {
  1233. const lastValue = storage.lastModifiedCached;
  1234. if (lastValue && lastValue >= lastModified) {
  1235. return lastValue === lastModified;
  1236. }
  1237. storage.lastModifiedCached = lastModified;
  1238. if (lastValue) {
  1239. for (const key in browserStorageConfig) {
  1240. iterateBrowserStorage(key, (item) => {
  1241. const iconSet = item.data;
  1242. return item.provider !== storage.provider || iconSet.prefix !== storage.prefix || iconSet.lastModified === lastModified;
  1243. });
  1244. }
  1245. }
  1246. return true;
  1247. }
  1248. function storeInBrowserStorage(storage, data) {
  1249. if (!browserStorageStatus) {
  1250. initBrowserStorage();
  1251. }
  1252. function store(key) {
  1253. let func;
  1254. if (!browserStorageConfig[key] || !(func = getBrowserStorage(key))) {
  1255. return;
  1256. }
  1257. const set = browserStorageEmptyItems[key];
  1258. let index;
  1259. if (set.size) {
  1260. set.delete(index = Array.from(set).shift());
  1261. } else {
  1262. index = getBrowserStorageItemsCount(func);
  1263. if (!setBrowserStorageItemsCount(func, index + 1)) {
  1264. return;
  1265. }
  1266. }
  1267. const item = {
  1268. cached: Math.floor(Date.now() / browserStorageHour),
  1269. provider: storage.provider,
  1270. data
  1271. };
  1272. return setStoredItem(
  1273. func,
  1274. browserCachePrefix + index.toString(),
  1275. JSON.stringify(item)
  1276. );
  1277. }
  1278. if (data.lastModified && !updateLastModified(storage, data.lastModified)) {
  1279. return;
  1280. }
  1281. if (!Object.keys(data.icons).length) {
  1282. return;
  1283. }
  1284. if (data.not_found) {
  1285. data = Object.assign({}, data);
  1286. delete data.not_found;
  1287. }
  1288. if (!store("local")) {
  1289. store("session");
  1290. }
  1291. }
  1292. function emptyCallback() {
  1293. }
  1294. function loadedNewIcons(storage) {
  1295. if (!storage.iconsLoaderFlag) {
  1296. storage.iconsLoaderFlag = true;
  1297. setTimeout(() => {
  1298. storage.iconsLoaderFlag = false;
  1299. updateCallbacks(storage);
  1300. });
  1301. }
  1302. }
  1303. function loadNewIcons(storage, icons) {
  1304. if (!storage.iconsToLoad) {
  1305. storage.iconsToLoad = icons;
  1306. } else {
  1307. storage.iconsToLoad = storage.iconsToLoad.concat(icons).sort();
  1308. }
  1309. if (!storage.iconsQueueFlag) {
  1310. storage.iconsQueueFlag = true;
  1311. setTimeout(() => {
  1312. storage.iconsQueueFlag = false;
  1313. const { provider, prefix } = storage;
  1314. const icons2 = storage.iconsToLoad;
  1315. delete storage.iconsToLoad;
  1316. let api;
  1317. if (!icons2 || !(api = getAPIModule(provider))) {
  1318. return;
  1319. }
  1320. const params = api.prepare(provider, prefix, icons2);
  1321. params.forEach((item) => {
  1322. sendAPIQuery(provider, item, (data) => {
  1323. if (typeof data !== "object") {
  1324. item.icons.forEach((name) => {
  1325. storage.missing.add(name);
  1326. });
  1327. } else {
  1328. try {
  1329. const parsed = addIconSet(
  1330. storage,
  1331. data
  1332. );
  1333. if (!parsed.length) {
  1334. return;
  1335. }
  1336. const pending = storage.pendingIcons;
  1337. if (pending) {
  1338. parsed.forEach((name) => {
  1339. pending.delete(name);
  1340. });
  1341. }
  1342. storeInBrowserStorage(storage, data);
  1343. } catch (err) {
  1344. console.error(err);
  1345. }
  1346. }
  1347. loadedNewIcons(storage);
  1348. });
  1349. });
  1350. });
  1351. }
  1352. }
  1353. const isPending = (icon) => {
  1354. const storage = getStorage(
  1355. icon.provider,
  1356. icon.prefix
  1357. );
  1358. const pending = storage.pendingIcons;
  1359. return !!(pending && pending.has(icon.name));
  1360. };
  1361. const loadIcons = (icons, callback) => {
  1362. const cleanedIcons = listToIcons(icons, true, allowSimpleNames());
  1363. const sortedIcons = sortIcons(cleanedIcons);
  1364. if (!sortedIcons.pending.length) {
  1365. let callCallback = true;
  1366. if (callback) {
  1367. setTimeout(() => {
  1368. if (callCallback) {
  1369. callback(
  1370. sortedIcons.loaded,
  1371. sortedIcons.missing,
  1372. sortedIcons.pending,
  1373. emptyCallback
  1374. );
  1375. }
  1376. });
  1377. }
  1378. return () => {
  1379. callCallback = false;
  1380. };
  1381. }
  1382. const newIcons = /* @__PURE__ */ Object.create(null);
  1383. const sources = [];
  1384. let lastProvider, lastPrefix;
  1385. sortedIcons.pending.forEach((icon) => {
  1386. const { provider, prefix } = icon;
  1387. if (prefix === lastPrefix && provider === lastProvider) {
  1388. return;
  1389. }
  1390. lastProvider = provider;
  1391. lastPrefix = prefix;
  1392. sources.push(getStorage(provider, prefix));
  1393. const providerNewIcons = newIcons[provider] || (newIcons[provider] = /* @__PURE__ */ Object.create(null));
  1394. if (!providerNewIcons[prefix]) {
  1395. providerNewIcons[prefix] = [];
  1396. }
  1397. });
  1398. sortedIcons.pending.forEach((icon) => {
  1399. const { provider, prefix, name } = icon;
  1400. const storage = getStorage(provider, prefix);
  1401. const pendingQueue = storage.pendingIcons || (storage.pendingIcons = /* @__PURE__ */ new Set());
  1402. if (!pendingQueue.has(name)) {
  1403. pendingQueue.add(name);
  1404. newIcons[provider][prefix].push(name);
  1405. }
  1406. });
  1407. sources.forEach((storage) => {
  1408. const { provider, prefix } = storage;
  1409. if (newIcons[provider][prefix].length) {
  1410. loadNewIcons(storage, newIcons[provider][prefix]);
  1411. }
  1412. });
  1413. return callback ? storeCallback(callback, sortedIcons, sources) : emptyCallback;
  1414. };
  1415. const loadIcon = (icon) => {
  1416. return new Promise((fulfill, reject) => {
  1417. const iconObj = typeof icon === "string" ? stringToIcon(icon, true) : icon;
  1418. if (!iconObj) {
  1419. reject(icon);
  1420. return;
  1421. }
  1422. loadIcons([iconObj || icon], (loaded) => {
  1423. if (loaded.length && iconObj) {
  1424. const data = getIconData(iconObj);
  1425. if (data) {
  1426. fulfill({
  1427. ...defaultIconProps,
  1428. ...data
  1429. });
  1430. return;
  1431. }
  1432. }
  1433. reject(icon);
  1434. });
  1435. });
  1436. };
  1437. function mergeCustomisations(defaults, item) {
  1438. const result = {
  1439. ...defaults
  1440. };
  1441. for (const key in item) {
  1442. const value = item[key];
  1443. const valueType = typeof value;
  1444. if (key in defaultIconSizeCustomisations) {
  1445. if (value === null || value && (valueType === "string" || valueType === "number")) {
  1446. result[key] = value;
  1447. }
  1448. } else if (valueType === typeof result[key]) {
  1449. result[key] = key === "rotate" ? value % 4 : value;
  1450. }
  1451. }
  1452. return result;
  1453. }
  1454. const defaultExtendedIconCustomisations = {
  1455. ...defaultIconCustomisations,
  1456. inline: false,
  1457. };
  1458. /**
  1459. * Class names
  1460. */
  1461. const blockClass = 'iconify';
  1462. const inlineClass = 'iconify-inline';
  1463. /**
  1464. * Names of properties to add to nodes
  1465. */
  1466. const elementDataProperty = ('iconifyData' + Date.now());
  1467. /**
  1468. * List of root nodes
  1469. */
  1470. let nodes = [];
  1471. /**
  1472. * Find node
  1473. */
  1474. function findRootNode(node) {
  1475. for (let i = 0; i < nodes.length; i++) {
  1476. const item = nodes[i];
  1477. const root = typeof item.node === 'function' ? item.node() : item.node;
  1478. if (root === node) {
  1479. return item;
  1480. }
  1481. }
  1482. }
  1483. /**
  1484. * Add extra root node
  1485. */
  1486. function addRootNode(root, autoRemove = false) {
  1487. let node = findRootNode(root);
  1488. if (node) {
  1489. // Node already exist: switch type if needed
  1490. if (node.temporary) {
  1491. node.temporary = autoRemove;
  1492. }
  1493. return node;
  1494. }
  1495. // Create item, add it to list
  1496. node = {
  1497. node: root,
  1498. temporary: autoRemove,
  1499. };
  1500. nodes.push(node);
  1501. return node;
  1502. }
  1503. /**
  1504. * Add document.body node
  1505. */
  1506. function addBodyNode() {
  1507. if (document.documentElement) {
  1508. return addRootNode(document.documentElement);
  1509. }
  1510. nodes.push({
  1511. node: () => {
  1512. return document.documentElement;
  1513. },
  1514. });
  1515. }
  1516. /**
  1517. * Remove root node
  1518. */
  1519. function removeRootNode(root) {
  1520. nodes = nodes.filter((node) => root !== node &&
  1521. root !== (typeof node.node === 'function' ? node.node() : node.node));
  1522. }
  1523. /**
  1524. * Get list of root nodes
  1525. */
  1526. function listRootNodes() {
  1527. return nodes;
  1528. }
  1529. /**
  1530. * Execute function when DOM is ready
  1531. */
  1532. function onReady(callback) {
  1533. const doc = document;
  1534. if (doc.readyState && doc.readyState !== 'loading') {
  1535. callback();
  1536. }
  1537. else {
  1538. doc.addEventListener('DOMContentLoaded', callback);
  1539. }
  1540. }
  1541. /**
  1542. * Callback
  1543. */
  1544. let callback = null;
  1545. /**
  1546. * Parameters for mutation observer
  1547. */
  1548. const observerParams = {
  1549. childList: true,
  1550. subtree: true,
  1551. attributes: true,
  1552. };
  1553. /**
  1554. * Queue DOM scan
  1555. */
  1556. function queueScan(node) {
  1557. if (!node.observer) {
  1558. return;
  1559. }
  1560. const observer = node.observer;
  1561. if (!observer.pendingScan) {
  1562. observer.pendingScan = setTimeout(() => {
  1563. delete observer.pendingScan;
  1564. if (callback) {
  1565. callback(node);
  1566. }
  1567. });
  1568. }
  1569. }
  1570. /**
  1571. * Check mutations for added nodes
  1572. */
  1573. function checkMutations(node, mutations) {
  1574. if (!node.observer) {
  1575. return;
  1576. }
  1577. const observer = node.observer;
  1578. if (!observer.pendingScan) {
  1579. for (let i = 0; i < mutations.length; i++) {
  1580. const item = mutations[i];
  1581. if (
  1582. // Check for added nodes
  1583. (item.addedNodes && item.addedNodes.length > 0) ||
  1584. // Check for icon or placeholder with modified attributes
  1585. (item.type === 'attributes' &&
  1586. item.target[elementDataProperty] !==
  1587. void 0)) {
  1588. if (!observer.paused) {
  1589. queueScan(node);
  1590. }
  1591. return;
  1592. }
  1593. }
  1594. }
  1595. }
  1596. /**
  1597. * Start/resume observer
  1598. */
  1599. function continueObserving(node, root) {
  1600. node.observer.instance.observe(root, observerParams);
  1601. }
  1602. /**
  1603. * Start mutation observer
  1604. */
  1605. function startObserver(node) {
  1606. let observer = node.observer;
  1607. if (observer && observer.instance) {
  1608. // Already started
  1609. return;
  1610. }
  1611. const root = typeof node.node === 'function' ? node.node() : node.node;
  1612. if (!root || !window) {
  1613. // document.body is not available yet or window is missing
  1614. return;
  1615. }
  1616. if (!observer) {
  1617. observer = {
  1618. paused: 0,
  1619. };
  1620. node.observer = observer;
  1621. }
  1622. // Create new instance, observe
  1623. observer.instance = new window.MutationObserver(checkMutations.bind(null, node));
  1624. continueObserving(node, root);
  1625. // Scan immediately
  1626. if (!observer.paused) {
  1627. queueScan(node);
  1628. }
  1629. }
  1630. /**
  1631. * Start all observers
  1632. */
  1633. function startObservers() {
  1634. listRootNodes().forEach(startObserver);
  1635. }
  1636. /**
  1637. * Stop observer
  1638. */
  1639. function stopObserver(node) {
  1640. if (!node.observer) {
  1641. return;
  1642. }
  1643. const observer = node.observer;
  1644. // Stop scan
  1645. if (observer.pendingScan) {
  1646. clearTimeout(observer.pendingScan);
  1647. delete observer.pendingScan;
  1648. }
  1649. // Disconnect observer
  1650. if (observer.instance) {
  1651. observer.instance.disconnect();
  1652. delete observer.instance;
  1653. }
  1654. }
  1655. /**
  1656. * Start observer when DOM is ready
  1657. */
  1658. function initObserver(cb) {
  1659. const isRestart = callback !== null;
  1660. if (callback !== cb) {
  1661. // Change callback and stop all pending observers
  1662. callback = cb;
  1663. if (isRestart) {
  1664. listRootNodes().forEach(stopObserver);
  1665. }
  1666. }
  1667. if (isRestart) {
  1668. // Restart instances
  1669. startObservers();
  1670. return;
  1671. }
  1672. // Start observers when document is ready
  1673. onReady(startObservers);
  1674. }
  1675. /**
  1676. * Pause observing node
  1677. */
  1678. function pauseObservingNode(node) {
  1679. (node ? [node] : listRootNodes()).forEach((node) => {
  1680. if (!node.observer) {
  1681. node.observer = {
  1682. paused: 1,
  1683. };
  1684. return;
  1685. }
  1686. const observer = node.observer;
  1687. observer.paused++;
  1688. if (observer.paused > 1 || !observer.instance) {
  1689. return;
  1690. }
  1691. // Disconnect observer
  1692. const instance = observer.instance;
  1693. // checkMutations(node, instance.takeRecords());
  1694. instance.disconnect();
  1695. });
  1696. }
  1697. /**
  1698. * Pause observer
  1699. */
  1700. function pauseObserver(root) {
  1701. if (root) {
  1702. const node = findRootNode(root);
  1703. if (node) {
  1704. pauseObservingNode(node);
  1705. }
  1706. }
  1707. else {
  1708. pauseObservingNode();
  1709. }
  1710. }
  1711. /**
  1712. * Resume observer
  1713. */
  1714. function resumeObservingNode(observer) {
  1715. (observer ? [observer] : listRootNodes()).forEach((node) => {
  1716. if (!node.observer) {
  1717. // Start observer
  1718. startObserver(node);
  1719. return;
  1720. }
  1721. const observer = node.observer;
  1722. if (observer.paused) {
  1723. observer.paused--;
  1724. if (!observer.paused) {
  1725. // Start / resume
  1726. const root = typeof node.node === 'function' ? node.node() : node.node;
  1727. if (!root) {
  1728. return;
  1729. }
  1730. else if (observer.instance) {
  1731. continueObserving(node, root);
  1732. }
  1733. else {
  1734. startObserver(node);
  1735. }
  1736. }
  1737. }
  1738. });
  1739. }
  1740. /**
  1741. * Resume observer
  1742. */
  1743. function resumeObserver(root) {
  1744. if (root) {
  1745. const node = findRootNode(root);
  1746. if (node) {
  1747. resumeObservingNode(node);
  1748. }
  1749. }
  1750. else {
  1751. resumeObservingNode();
  1752. }
  1753. }
  1754. /**
  1755. * Observe node
  1756. */
  1757. function observe(root, autoRemove = false) {
  1758. const node = addRootNode(root, autoRemove);
  1759. startObserver(node);
  1760. return node;
  1761. }
  1762. /**
  1763. * Remove observed node
  1764. */
  1765. function stopObserving(root) {
  1766. const node = findRootNode(root);
  1767. if (node) {
  1768. stopObserver(node);
  1769. removeRootNode(root);
  1770. }
  1771. }
  1772. /**
  1773. * Compare props
  1774. */
  1775. function propsChanged(props1, props2) {
  1776. if (props1.name !== props2.name || props1.mode !== props2.mode) {
  1777. return true;
  1778. }
  1779. const customisations1 = props1.customisations;
  1780. const customisations2 = props2.customisations;
  1781. for (const key in defaultExtendedIconCustomisations) {
  1782. if (customisations1[key] !== customisations2[key]) {
  1783. return true;
  1784. }
  1785. }
  1786. return false;
  1787. }
  1788. function rotateFromString(value, defaultValue = 0) {
  1789. const units = value.replace(/^-?[0-9.]*/, "");
  1790. function cleanup(value2) {
  1791. while (value2 < 0) {
  1792. value2 += 4;
  1793. }
  1794. return value2 % 4;
  1795. }
  1796. if (units === "") {
  1797. const num = parseInt(value);
  1798. return isNaN(num) ? 0 : cleanup(num);
  1799. } else if (units !== value) {
  1800. let split = 0;
  1801. switch (units) {
  1802. case "%":
  1803. split = 25;
  1804. break;
  1805. case "deg":
  1806. split = 90;
  1807. }
  1808. if (split) {
  1809. let num = parseFloat(value.slice(0, value.length - units.length));
  1810. if (isNaN(num)) {
  1811. return 0;
  1812. }
  1813. num = num / split;
  1814. return num % 1 === 0 ? cleanup(num) : 0;
  1815. }
  1816. }
  1817. return defaultValue;
  1818. }
  1819. const separator = /[\s,]+/;
  1820. function flipFromString(custom, flip) {
  1821. flip.split(separator).forEach((str) => {
  1822. const value = str.trim();
  1823. switch (value) {
  1824. case "horizontal":
  1825. custom.hFlip = true;
  1826. break;
  1827. case "vertical":
  1828. custom.vFlip = true;
  1829. break;
  1830. }
  1831. });
  1832. }
  1833. /**
  1834. * Size attributes
  1835. */
  1836. const sizeAttributes = ['width', 'height'];
  1837. /**
  1838. * Boolean attributes
  1839. */
  1840. const booleanAttributes = [
  1841. 'inline',
  1842. 'hFlip',
  1843. 'vFlip',
  1844. ];
  1845. /**
  1846. * Get attribute value
  1847. */
  1848. function getBooleanAttribute(value, key) {
  1849. if (value === key || value === 'true') {
  1850. return true;
  1851. }
  1852. if (value === '' || value === 'false') {
  1853. return false;
  1854. }
  1855. return null;
  1856. }
  1857. /**
  1858. * Get element properties from HTML element
  1859. */
  1860. function getElementProps(element) {
  1861. // Get icon name
  1862. const name = element.getAttribute('data-icon');
  1863. const icon = typeof name === 'string' && stringToIcon(name, true);
  1864. if (!icon) {
  1865. return null;
  1866. }
  1867. // Get defaults and inline
  1868. const customisations = {
  1869. ...defaultExtendedIconCustomisations,
  1870. inline: element.classList && element.classList.contains(inlineClass),
  1871. };
  1872. // Get dimensions
  1873. sizeAttributes.forEach((attr) => {
  1874. const value = element.getAttribute('data-' + attr);
  1875. if (value) {
  1876. customisations[attr] = value;
  1877. }
  1878. });
  1879. // Get rotation
  1880. const rotation = element.getAttribute('data-rotate');
  1881. if (typeof rotation === 'string') {
  1882. customisations.rotate = rotateFromString(rotation);
  1883. }
  1884. // Get flip shorthand
  1885. const flip = element.getAttribute('data-flip');
  1886. if (typeof flip === 'string') {
  1887. flipFromString(customisations, flip);
  1888. }
  1889. // Boolean attributes
  1890. booleanAttributes.forEach((attr) => {
  1891. const key = 'data-' + attr;
  1892. const value = getBooleanAttribute(element.getAttribute(key), key);
  1893. if (typeof value === 'boolean') {
  1894. customisations[attr] = value;
  1895. }
  1896. });
  1897. // Get render mode. Not checking actual value because incorrect values are treated as inline
  1898. const mode = element.getAttribute('data-mode');
  1899. return {
  1900. name,
  1901. icon,
  1902. customisations,
  1903. mode,
  1904. };
  1905. }
  1906. /**
  1907. * Selector combining class names and tags
  1908. */
  1909. const selector = 'svg.' +
  1910. blockClass +
  1911. ', i.' +
  1912. blockClass +
  1913. ', span.' +
  1914. blockClass +
  1915. ', i.' +
  1916. inlineClass +
  1917. ', span.' +
  1918. inlineClass;
  1919. /**
  1920. * Find all parent nodes in DOM
  1921. */
  1922. function scanRootNode(root) {
  1923. const nodes = [];
  1924. root.querySelectorAll(selector).forEach((node) => {
  1925. // Get props, ignore SVG rendered outside of SVG framework
  1926. const props = node[elementDataProperty] || node.tagName.toLowerCase() !== 'svg'
  1927. ? getElementProps(node)
  1928. : null;
  1929. if (props) {
  1930. nodes.push({
  1931. node,
  1932. props,
  1933. });
  1934. }
  1935. });
  1936. return nodes;
  1937. }
  1938. function iconToHTML(body, attributes) {
  1939. let renderAttribsHTML = body.indexOf("xlink:") === -1 ? "" : ' xmlns:xlink="http://www.w3.org/1999/xlink"';
  1940. for (const attr in attributes) {
  1941. renderAttribsHTML += " " + attr + '="' + attributes[attr] + '"';
  1942. }
  1943. return '<svg xmlns="http://www.w3.org/2000/svg"' + renderAttribsHTML + ">" + body + "</svg>";
  1944. }
  1945. /**
  1946. * Get classes to add from icon name
  1947. */
  1948. function iconClasses(iconName) {
  1949. const classesToAdd = new Set(['iconify']);
  1950. ['provider', 'prefix'].forEach((attr) => {
  1951. if (iconName[attr]) {
  1952. classesToAdd.add('iconify--' + iconName[attr]);
  1953. }
  1954. });
  1955. return classesToAdd;
  1956. }
  1957. /**
  1958. * Add classes to SVG, removing previously added classes, keeping custom classes
  1959. */
  1960. function applyClasses(svg, classes, previouslyAddedClasses, placeholder) {
  1961. const svgClasses = svg.classList;
  1962. // Copy classes from placeholder
  1963. if (placeholder) {
  1964. const placeholderClasses = placeholder.classList;
  1965. Array.from(placeholderClasses).forEach((item) => {
  1966. svgClasses.add(item);
  1967. });
  1968. }
  1969. // Add new classes
  1970. const addedClasses = [];
  1971. classes.forEach((item) => {
  1972. if (!svgClasses.contains(item)) {
  1973. // Add new class
  1974. svgClasses.add(item);
  1975. addedClasses.push(item);
  1976. }
  1977. else if (previouslyAddedClasses.has(item)) {
  1978. // Was added before: keep it
  1979. addedClasses.push(item);
  1980. }
  1981. });
  1982. // Remove previously added classes
  1983. previouslyAddedClasses.forEach((item) => {
  1984. if (!classes.has(item)) {
  1985. // Class that was added before, but no longer needed
  1986. svgClasses.remove(item);
  1987. }
  1988. });
  1989. return addedClasses;
  1990. }
  1991. /**
  1992. * Copy old styles, apply new styles
  1993. */
  1994. function applyStyle(svg, styles, previouslyAddedStyles) {
  1995. const svgStyle = svg.style;
  1996. // Remove previously added styles
  1997. (previouslyAddedStyles || []).forEach((prop) => {
  1998. svgStyle.removeProperty(prop);
  1999. });
  2000. // Apply new styles, ignoring styles that already exist
  2001. const appliedStyles = [];
  2002. for (const prop in styles) {
  2003. if (!svgStyle.getPropertyValue(prop)) {
  2004. appliedStyles.push(prop);
  2005. svgStyle.setProperty(prop, styles[prop]);
  2006. }
  2007. }
  2008. return appliedStyles;
  2009. }
  2010. /**
  2011. * Render icon as inline SVG
  2012. */
  2013. function renderInlineSVG(element, props, iconData) {
  2014. // Create placeholder. Why placeholder? innerHTML setter on SVG does not work in some environments.
  2015. let span;
  2016. try {
  2017. span = document.createElement('span');
  2018. }
  2019. catch (err) {
  2020. return element;
  2021. }
  2022. // Generate data to render
  2023. const customisations = props.customisations;
  2024. const renderData = iconToSVG(iconData, customisations);
  2025. // Get old data
  2026. const oldData = element[elementDataProperty];
  2027. // Generate SVG
  2028. const html = iconToHTML(replaceIDs(renderData.body), {
  2029. 'aria-hidden': 'true',
  2030. 'role': 'img',
  2031. ...renderData.attributes,
  2032. });
  2033. span.innerHTML = html;
  2034. // Get SVG element
  2035. const svg = span.childNodes[0];
  2036. // Add attributes
  2037. const placeholderAttributes = element.attributes;
  2038. for (let i = 0; i < placeholderAttributes.length; i++) {
  2039. const item = placeholderAttributes.item(i);
  2040. const name = item.name;
  2041. if (name !== 'class' && !svg.hasAttribute(name)) {
  2042. svg.setAttribute(name, item.value);
  2043. }
  2044. }
  2045. // Add classes
  2046. const classesToAdd = iconClasses(props.icon);
  2047. const addedClasses = applyClasses(svg, classesToAdd, new Set(oldData && oldData.addedClasses), element);
  2048. // Update style
  2049. const addedStyles = applyStyle(svg, customisations.inline
  2050. ? {
  2051. 'vertical-align': '-0.125em',
  2052. }
  2053. : {}, oldData && oldData.addedStyles);
  2054. // Add data to element
  2055. const newData = {
  2056. ...props,
  2057. status: 'loaded',
  2058. addedClasses,
  2059. addedStyles,
  2060. };
  2061. svg[elementDataProperty] = newData;
  2062. // Replace old element
  2063. if (element.parentNode) {
  2064. element.parentNode.replaceChild(svg, element);
  2065. }
  2066. return svg;
  2067. }
  2068. function encodeSVGforURL(svg) {
  2069. return svg.replace(/"/g, "'").replace(/%/g, "%25").replace(/#/g, "%23").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\s+/g, " ");
  2070. }
  2071. function svgToURL(svg) {
  2072. return 'url("data:image/svg+xml,' + encodeSVGforURL(svg) + '")';
  2073. }
  2074. const commonProps = {
  2075. display: 'inline-block',
  2076. };
  2077. const monotoneProps = {
  2078. 'background-color': 'currentColor',
  2079. };
  2080. const coloredProps = {
  2081. 'background-color': 'transparent',
  2082. };
  2083. // Dynamically add common props to variables above
  2084. const propsToAdd = {
  2085. image: 'var(--svg)',
  2086. repeat: 'no-repeat',
  2087. size: '100% 100%',
  2088. };
  2089. const propsToAddTo = {
  2090. '-webkit-mask': monotoneProps,
  2091. 'mask': monotoneProps,
  2092. 'background': coloredProps,
  2093. };
  2094. for (const prefix in propsToAddTo) {
  2095. const list = propsToAddTo[prefix];
  2096. for (const prop in propsToAdd) {
  2097. list[prefix + '-' + prop] = propsToAdd[prop];
  2098. }
  2099. }
  2100. /**
  2101. * Fix size: add 'px' to numbers
  2102. */
  2103. function fixSize(value) {
  2104. return value + (value.match(/^[-0-9.]+$/) ? 'px' : '');
  2105. }
  2106. /**
  2107. * Render icon as inline SVG
  2108. */
  2109. function renderBackground(element, props, iconData, useMask) {
  2110. // Generate data to render
  2111. const customisations = props.customisations;
  2112. const renderData = iconToSVG(iconData, customisations);
  2113. const renderAttribs = renderData.attributes;
  2114. // Get old data
  2115. const oldData = element[elementDataProperty];
  2116. // Generate SVG
  2117. const html = iconToHTML(renderData.body, {
  2118. ...renderAttribs,
  2119. width: iconData.width + '',
  2120. height: iconData.height + '',
  2121. });
  2122. // Add classes
  2123. const classesToAdd = iconClasses(props.icon);
  2124. const addedClasses = applyClasses(element, classesToAdd, new Set(oldData && oldData.addedClasses));
  2125. // Update style
  2126. const url = svgToURL(html);
  2127. const newStyles = {
  2128. '--svg': url,
  2129. 'width': fixSize(renderAttribs.width),
  2130. 'height': fixSize(renderAttribs.height),
  2131. ...commonProps,
  2132. ...(useMask ? monotoneProps : coloredProps),
  2133. };
  2134. if (customisations.inline) {
  2135. newStyles['vertical-align'] = '-0.125em';
  2136. }
  2137. const addedStyles = applyStyle(element, newStyles, oldData && oldData.addedStyles);
  2138. // Add data to element
  2139. const newData = {
  2140. ...props,
  2141. status: 'loaded',
  2142. addedClasses,
  2143. addedStyles,
  2144. };
  2145. element[elementDataProperty] = newData;
  2146. return element;
  2147. }
  2148. /**
  2149. * Flag to avoid scanning DOM too often
  2150. */
  2151. let scanQueued = false;
  2152. /**
  2153. * Icons have been loaded
  2154. */
  2155. function checkPendingIcons() {
  2156. if (!scanQueued) {
  2157. scanQueued = true;
  2158. setTimeout(() => {
  2159. if (scanQueued) {
  2160. scanQueued = false;
  2161. scanDOM();
  2162. }
  2163. });
  2164. }
  2165. }
  2166. /**
  2167. * Scan node for placeholders
  2168. */
  2169. function scanDOM(rootNode, addTempNode = false) {
  2170. // List of icons to load: [provider][prefix] = Set<name>
  2171. const iconsToLoad = Object.create(null);
  2172. function getIcon(icon, load) {
  2173. const { provider, prefix, name } = icon;
  2174. const storage = getStorage(provider, prefix);
  2175. const storedIcon = storage.icons[name];
  2176. if (storedIcon) {
  2177. return {
  2178. status: 'loaded',
  2179. icon: storedIcon,
  2180. };
  2181. }
  2182. if (storage.missing.has(name)) {
  2183. return {
  2184. status: 'missing',
  2185. };
  2186. }
  2187. if (load && !isPending(icon)) {
  2188. const providerIconsToLoad = iconsToLoad[provider] ||
  2189. (iconsToLoad[provider] = Object.create(null));
  2190. const set = providerIconsToLoad[prefix] ||
  2191. (providerIconsToLoad[prefix] = new Set());
  2192. set.add(name);
  2193. }
  2194. return {
  2195. status: 'loading',
  2196. };
  2197. }
  2198. // Parse all root nodes
  2199. (rootNode ? [rootNode] : listRootNodes()).forEach((observedNode) => {
  2200. const root = typeof observedNode.node === 'function'
  2201. ? observedNode.node()
  2202. : observedNode.node;
  2203. if (!root || !root.querySelectorAll) {
  2204. return;
  2205. }
  2206. // Track placeholders
  2207. let hasPlaceholders = false;
  2208. // Observer
  2209. let paused = false;
  2210. /**
  2211. * Render icon
  2212. */
  2213. function render(element, props, iconData) {
  2214. if (!paused) {
  2215. paused = true;
  2216. pauseObservingNode(observedNode);
  2217. }
  2218. if (element.tagName.toUpperCase() !== 'SVG') {
  2219. // Check for one of style modes
  2220. const mode = props.mode;
  2221. const isMask = mode === 'mask' ||
  2222. (mode === 'bg'
  2223. ? false
  2224. : mode === 'style'
  2225. ? iconData.body.indexOf('currentColor') !== -1
  2226. : null);
  2227. if (typeof isMask === 'boolean') {
  2228. renderBackground(element, props, {
  2229. ...defaultIconProps,
  2230. ...iconData,
  2231. }, isMask);
  2232. return;
  2233. }
  2234. }
  2235. renderInlineSVG(element, props, iconData);
  2236. }
  2237. // Find all elements
  2238. scanRootNode(root).forEach(({ node, props }) => {
  2239. // Check if item already has props
  2240. const oldData = node[elementDataProperty];
  2241. if (!oldData) {
  2242. // New icon without data
  2243. const { status, icon } = getIcon(props.icon, true);
  2244. if (icon) {
  2245. // Ready to render!
  2246. render(node, props, icon);
  2247. return;
  2248. }
  2249. // Loading or missing
  2250. hasPlaceholders = hasPlaceholders || status === 'loading';
  2251. node[elementDataProperty] = {
  2252. ...props,
  2253. status,
  2254. };
  2255. return;
  2256. }
  2257. // Previously found icon
  2258. let item;
  2259. if (!propsChanged(oldData, props)) {
  2260. // Props have not changed. Check status
  2261. const oldStatus = oldData.status;
  2262. if (oldStatus !== 'loading') {
  2263. return;
  2264. }
  2265. item = getIcon(props.icon, false);
  2266. if (!item.icon) {
  2267. // Nothing to render
  2268. oldData.status = item.status;
  2269. return;
  2270. }
  2271. }
  2272. else {
  2273. // Properties have changed: load icon if name has changed
  2274. item = getIcon(props.icon, oldData.name !== props.name);
  2275. if (!item.icon) {
  2276. // Cannot render icon: update status and props
  2277. hasPlaceholders =
  2278. hasPlaceholders || item.status === 'loading';
  2279. Object.assign(oldData, {
  2280. ...props,
  2281. status: item.status,
  2282. });
  2283. return;
  2284. }
  2285. }
  2286. // Re-render icon
  2287. render(node, props, item.icon);
  2288. });
  2289. // Observed node stuff
  2290. if (observedNode.temporary && !hasPlaceholders) {
  2291. // Remove temporary node
  2292. stopObserving(root);
  2293. }
  2294. else if (addTempNode && hasPlaceholders) {
  2295. // Add new temporary node
  2296. observe(root, true);
  2297. }
  2298. else if (paused && observedNode.observer) {
  2299. // Resume observer
  2300. resumeObservingNode(observedNode);
  2301. }
  2302. });
  2303. // Load icons
  2304. for (const provider in iconsToLoad) {
  2305. const providerIconsToLoad = iconsToLoad[provider];
  2306. for (const prefix in providerIconsToLoad) {
  2307. const set = providerIconsToLoad[prefix];
  2308. loadIcons(Array.from(set).map((name) => ({
  2309. provider,
  2310. prefix,
  2311. name,
  2312. })), checkPendingIcons);
  2313. }
  2314. }
  2315. }
  2316. /**
  2317. * Scan node for placeholders
  2318. */
  2319. function scanElement(root) {
  2320. // Add temporary node
  2321. const node = findRootNode(root);
  2322. if (!node) {
  2323. scanDOM({
  2324. node: root,
  2325. temporary: true,
  2326. }, true);
  2327. }
  2328. else {
  2329. scanDOM(node);
  2330. }
  2331. }
  2332. function generateIcon(name, customisations, returnString = false) {
  2333. // Get icon data
  2334. const iconData = getIconData(name);
  2335. if (!iconData) {
  2336. return null;
  2337. }
  2338. // Split name
  2339. const iconName = stringToIcon(name);
  2340. // Clean up customisations
  2341. const changes = mergeCustomisations(defaultExtendedIconCustomisations, customisations || {});
  2342. // Get data
  2343. const result = renderInlineSVG(document.createElement('span'), {
  2344. name,
  2345. icon: iconName,
  2346. customisations: changes,
  2347. }, iconData);
  2348. return returnString
  2349. ? result.outerHTML
  2350. : result;
  2351. }
  2352. /**
  2353. * Get version
  2354. */
  2355. function getVersion() {
  2356. return '3.1.0';
  2357. }
  2358. /**
  2359. * Generate SVG element
  2360. */
  2361. function renderSVG(name, customisations) {
  2362. return generateIcon(name, customisations, false);
  2363. }
  2364. /**
  2365. * Generate SVG as string
  2366. */
  2367. function renderHTML(name, customisations) {
  2368. return generateIcon(name, customisations, true);
  2369. }
  2370. /**
  2371. * Get rendered icon as object that can be used to create SVG (use replaceIDs on body)
  2372. */
  2373. function renderIcon(name, customisations) {
  2374. // Get icon data
  2375. const iconData = getIconData(name);
  2376. if (!iconData) {
  2377. return null;
  2378. }
  2379. // Clean up customisations
  2380. const changes = mergeCustomisations(defaultExtendedIconCustomisations, customisations || {});
  2381. // Get data
  2382. return iconToSVG(iconData, changes);
  2383. }
  2384. /**
  2385. * Scan DOM
  2386. */
  2387. function scan(root) {
  2388. if (root) {
  2389. scanElement(root);
  2390. }
  2391. else {
  2392. scanDOM();
  2393. }
  2394. }
  2395. /**
  2396. * Initialise stuff
  2397. */
  2398. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  2399. // Add document.body node
  2400. addBodyNode();
  2401. const _window = window;
  2402. // Load icons from global "IconifyPreload"
  2403. if (_window.IconifyPreload !== void 0) {
  2404. const preload = _window.IconifyPreload;
  2405. const err = 'Invalid IconifyPreload syntax.';
  2406. if (typeof preload === 'object' && preload !== null) {
  2407. (preload instanceof Array ? preload : [preload]).forEach((item) => {
  2408. try {
  2409. if (
  2410. // Check if item is an object and not null/array
  2411. typeof item !== 'object' ||
  2412. item === null ||
  2413. item instanceof Array ||
  2414. // Check for 'icons' and 'prefix'
  2415. typeof item.icons !== 'object' ||
  2416. typeof item.prefix !== 'string' ||
  2417. // Add icon set
  2418. !addCollection(item)) {
  2419. console.error(err);
  2420. }
  2421. }
  2422. catch (e) {
  2423. console.error(err);
  2424. }
  2425. });
  2426. }
  2427. }
  2428. // Load observer and scan DOM on next tick
  2429. setTimeout(() => {
  2430. initObserver(scanDOM);
  2431. scanDOM();
  2432. });
  2433. }
  2434. /**
  2435. * Enable cache
  2436. */
  2437. function enableCache(storage, enable) {
  2438. toggleBrowserCache(storage, enable !== false);
  2439. }
  2440. /**
  2441. * Disable cache
  2442. */
  2443. function disableCache(storage) {
  2444. toggleBrowserCache(storage, true);
  2445. }
  2446. /**
  2447. * Initialise stuff
  2448. */
  2449. // Set API module
  2450. setAPIModule('', fetchAPIModule);
  2451. /**
  2452. * Browser stuff
  2453. */
  2454. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  2455. // Set cache and load existing cache
  2456. initBrowserStorage();
  2457. const _window = window;
  2458. // Set API from global "IconifyProviders"
  2459. if (_window.IconifyProviders !== void 0) {
  2460. const providers = _window.IconifyProviders;
  2461. if (typeof providers === 'object' && providers !== null) {
  2462. for (const key in providers) {
  2463. const err = 'IconifyProviders[' + key + '] is invalid.';
  2464. try {
  2465. const value = providers[key];
  2466. if (typeof value !== 'object' ||
  2467. !value ||
  2468. value.resources === void 0) {
  2469. continue;
  2470. }
  2471. if (!addAPIProvider(key, value)) {
  2472. console.error(err);
  2473. }
  2474. }
  2475. catch (e) {
  2476. console.error(err);
  2477. }
  2478. }
  2479. }
  2480. }
  2481. }
  2482. /**
  2483. * Internal API
  2484. */
  2485. const _api = {
  2486. getAPIConfig,
  2487. setAPIModule,
  2488. sendAPIQuery,
  2489. setFetch,
  2490. getFetch,
  2491. listAPIProviders,
  2492. };
  2493. /**
  2494. * Global variable
  2495. */
  2496. const Iconify = {
  2497. // IconifyAPIInternalFunctions
  2498. _api,
  2499. // IconifyAPIFunctions
  2500. addAPIProvider,
  2501. loadIcons,
  2502. loadIcon,
  2503. // IconifyStorageFunctions
  2504. iconExists,
  2505. getIcon,
  2506. listIcons,
  2507. addIcon,
  2508. addCollection,
  2509. // IconifyBuilderFunctions
  2510. replaceIDs,
  2511. calculateSize,
  2512. buildIcon: iconToSVG,
  2513. // IconifyCommonFunctions
  2514. getVersion,
  2515. renderSVG,
  2516. renderHTML,
  2517. renderIcon,
  2518. scan,
  2519. observe,
  2520. stopObserving,
  2521. pauseObserver,
  2522. resumeObserver,
  2523. // IconifyBrowserCacheFunctions
  2524. enableCache,
  2525. disableCache,
  2526. };
  2527. exports._api = _api;
  2528. exports.addAPIProvider = addAPIProvider;
  2529. exports.addCollection = addCollection;
  2530. exports.addIcon = addIcon;
  2531. exports.buildIcon = iconToSVG;
  2532. exports.calculateSize = calculateSize;
  2533. exports.default = Iconify;
  2534. exports.disableCache = disableCache;
  2535. exports.enableCache = enableCache;
  2536. exports.getIcon = getIcon;
  2537. exports.getVersion = getVersion;
  2538. exports.iconExists = iconExists;
  2539. exports.listIcons = listIcons;
  2540. exports.loadIcon = loadIcon;
  2541. exports.loadIcons = loadIcons;
  2542. exports.observe = observe;
  2543. exports.pauseObserver = pauseObserver;
  2544. exports.renderHTML = renderHTML;
  2545. exports.renderIcon = renderIcon;
  2546. exports.renderSVG = renderSVG;
  2547. exports.replaceIDs = replaceIDs;
  2548. exports.resumeObserver = resumeObserver;
  2549. exports.scan = scan;
  2550. exports.stopObserving = stopObserving;
  2551. // Export to window or web worker
  2552. try {
  2553. if (self.Iconify === void 0) {
  2554. self.Iconify = Iconify;
  2555. }
  2556. } catch (err) {
  2557. }