|
| 1 | +import lscache from "lscache"; |
| 2 | + |
| 3 | +function replaceTag(element, markup) { |
| 4 | + const attributes = [...element.attributes] |
| 5 | + .filter((item) => item.name != "x-data") |
| 6 | + .map((item) => [item.name, item.value]); |
| 7 | + const div = document.createElement("div"); |
| 8 | + div.innerHTML = markup; |
| 9 | + const newElement = div.firstElementChild; |
| 10 | + attributes.forEach(([name, value]) => { |
| 11 | + newElement.setAttribute(name, value); |
| 12 | + }); |
| 13 | + element.replaceWith(newElement); |
| 14 | +} |
| 15 | + |
| 16 | +window.addEventListener("alpine:init", () => { |
| 17 | + window.Alpine.data("icon", (segment) => ({ |
| 18 | + init() { |
| 19 | + lscache.setBucket("icons"); |
| 20 | + const cache = lscache.get(segment); |
| 21 | + if (cache && typeof cache === "string") { |
| 22 | + replaceTag(this.$el, cache); |
| 23 | + return; |
| 24 | + } |
| 25 | + fetch(`/garagist/fontawesome/${segment.replaceAll(":", "/")}.svg`) |
| 26 | + .then((response) => { |
| 27 | + if (!response.ok) { |
| 28 | + throw new Error("Failed to load icon"); |
| 29 | + } |
| 30 | + return response.text(); |
| 31 | + }) |
| 32 | + .then((data) => { |
| 33 | + // Store for 1 week 60 min * 24 hours * 7 days = 10080 |
| 34 | + lscache.set(segment, data, 10080); |
| 35 | + replaceTag(this.$el, data); |
| 36 | + }) |
| 37 | + .catch((error) => { |
| 38 | + console.warn(error); |
| 39 | + this.$el.remove(); |
| 40 | + }); |
| 41 | + }, |
| 42 | + })); |
| 43 | +}); |
0 commit comments