iconify.mjs 67 KB

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