iconplease 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # iconplease
2
2
 
3
- Icons you can draw yourself. The catalogue loads once from the iconplease CDN, is cached in the
4
- browser, and new icons show up without updating this package.
3
+ Icons you can draw yourself. Each page loads only the icons it shows from the iconplease CDN, keeps
4
+ them in the browser, and new icons show up without updating this package.
5
5
 
6
6
  ## React
7
7
 
8
8
  ```bash
9
- npm i iconplease
9
+ npm i iconplease@0.3.0
10
10
  ```
11
11
 
12
12
  ```tsx
@@ -35,15 +35,16 @@ never throws.
35
35
  ## Plain HTML
36
36
 
37
37
  ```html
38
- <script src="https://cdn.jsdelivr.net/npm/iconplease@0.1/dist/iconplease.min.js" defer></script>
39
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/iconplease@0.1/dist/styles.css">
38
+ <script src="https://cdn.jsdelivr.net/npm/iconplease@0.3.0/dist/iconplease.min.js" defer></script>
39
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/iconplease@0.3.0/dist/styles.css">
40
40
 
41
41
  <i data-icon="heart"></i>
42
42
  <i data-icon="rocket" data-size="32" data-color="#e11d48" data-stroke="1.5" data-motion="pop"></i>
43
43
  <i data-icon="bell" data-label="Notifications"></i>
44
44
  ```
45
45
 
46
- Elements added later are picked up automatically. `<i class="ip ip-heart">` works too.
46
+ Elements added later are picked up automatically. `<i class="ip ip-heart">` works too. A `class` on the
47
+ `<i>` stays on the `<i>`; style that element. An unknown name leaves the `<i>` empty and logs one warning.
47
48
 
48
49
  ## Functions
49
50
 
@@ -57,17 +58,69 @@ const names = iconNames();
57
58
 
58
59
  ## Your own set
59
60
 
60
- Create a publishable key for a set in your iconplease account (Account → API keys), then:
61
+ Create a set in your iconplease account, publish it, and pick one of three ways to use it. Sites only
62
+ ever see the version you published, never work in progress.
63
+
64
+ ### Build time (recommended for public sites)
65
+
66
+ No key on the page and no network for your icons. With React, server rendering outputs the real icon
67
+ (call `init({ set })` on the server as well).
68
+
69
+ ```sh
70
+ ICONPLEASE_SECRET_KEY=ip_sk_… npx iconplease pull
71
+ ```
72
+
73
+ This writes `src/iconplease.generated.ts`: your published set, plus the public icons your code uses
74
+ (`icon="…"` and `data-icon="…"` literals), plus an `IconName` type listing every name in it. `pull` warns
75
+ about names it cannot find; type your own props or constants as `IconName` and a typo fails to compile.
76
+ Commit it, and run `npx iconplease pull --check` in CI to catch a stale file. The secret key is only
77
+ read from the environment and never written to the file.
61
78
 
62
79
  ```ts
63
80
  import { init } from "iconplease";
81
+ import set from "./iconplease.generated";
82
+ init({ set });
83
+ ```
84
+
85
+ Names not in the file (built dynamically at runtime) still load from the public CDN.
86
+
87
+ ### Live, with a publishable key
88
+
89
+ ```ts
64
90
  init({ apiKey: "ip_pk_…" });
65
91
  ```
66
92
 
67
- `<Iconplease icon="heart" />` now uses your set's version of `heart` if it has one, and the public
68
- catalogue otherwise. The set loads in one request, is cached in the browser and re-checked at most
69
- once an hour. Limit a key to your own sites when you create it; a page on any other site gets a
70
- console warning and the public icons instead. Publishable keys are safe to ship in front-end code.
93
+ Your set's version of an icon wins over the public one. The set loads in one request, is cached in the
94
+ browser and re-checked at most once an hour. Limit the key to your own sites when you create it; any
95
+ other site gets a console warning and the public icons. Publishable keys are visible in your page by
96
+ design.
97
+
98
+ Combine both with `init({ set, apiKey })`: bundled icons render immediately, and are replaced only
99
+ when a newer version has been published.
100
+
101
+ ### Signed-in apps, with short-lived tokens
102
+
103
+ Keep a secret key on your server and hand the page a token that lasts 10 minutes:
104
+
105
+ ```ts
106
+ // your server, behind your own sign-in
107
+ const res = await fetch("https://api.iconplease.com/sdk/token", {
108
+ method: "POST",
109
+ headers: { Authorization: `Bearer ${process.env.ICONPLEASE_SECRET_KEY}` },
110
+ });
111
+ return res.json(); // { token, expiresAt }
112
+
113
+ // your page
114
+ init({ token: () => fetch("/api/iconplease-token").then((r) => r.json()) });
115
+ ```
116
+
117
+ The snippet above is your `/api/iconplease-token` route. Your function may return the token text or
118
+ `{ token, expiresAt }`. The package calls it when it needs to load the set and its last token is within a
119
+ minute of expiring, and once more if a token is refused. In token mode the set is kept in memory only, never
120
+ in `localStorage`. This protects pages behind your sign-in only; on a
121
+ public page, use build time instead.
122
+
123
+ **Never put a secret key (`ip_sk_…`) in front-end code.** `init` refuses one.
71
124
 
72
125
  ## How loading works
73
126
 
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, mkdirSync } from "node:fs";
3
+ import { dirname, extname, join, relative, resolve } from "node:path";
4
+
5
+ const HELP = `iconplease pull — write your published set into your project
6
+
7
+ Usage
8
+ npx iconplease pull [options]
9
+
10
+ Reads ICONPLEASE_SECRET_KEY (a secret key, ip_sk_…) from the environment.
11
+
12
+ Options
13
+ --out <file> generated file (default src/iconplease.generated.ts; .js writes plain JavaScript)
14
+ --src <dir> folder scanned for public icon names (default src)
15
+ --check do not write; exit 1 if the file is missing or out of date (for CI)
16
+ --api <url> API address (default https://api.iconplease.com)
17
+ --cdn <url> CDN address (default https://cdn.iconplease.com)
18
+ -h, --help show this help
19
+
20
+ Then, in your app:
21
+ import { init } from "iconplease";
22
+ import set from "./iconplease.generated";
23
+ init({ set });
24
+ `;
25
+
26
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
27
+ const NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
28
+ const USAGE = /\b(?:data-icon|icon)\s*=\s*\{?\s*["'`]([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)["'`]/g;
29
+ const SCANNED = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro", ".html", ".mdx", ".md"]);
30
+ const SKIPPED = new Set(["node_modules", "dist", "build", ".git", ".next", ".svelte-kit", ".astro", "coverage", "out"]);
31
+ const SECRET = /ip_sk_[A-Za-z0-9]{32}/;
32
+
33
+ const fail = (message) => {
34
+ console.error(`iconplease: ${message}`);
35
+ process.exit(1);
36
+ };
37
+
38
+ const parseArgs = (argv) => {
39
+ const [command, ...rest] = argv;
40
+ const options = { out: "src/iconplease.generated.ts", src: "src", api: "https://api.iconplease.com", cdn: "https://cdn.iconplease.com", check: false };
41
+ if (!command || command === "-h" || command === "--help" || command === "help") return { help: true };
42
+ if (command !== "pull") fail(`unknown command "${command}". Run npx iconplease --help.`);
43
+ for (let index = 0; index < rest.length; index++) {
44
+ const flag = rest[index];
45
+ if (flag === "-h" || flag === "--help") return { help: true };
46
+ if (flag === "--check") options.check = true;
47
+ else if (["--out", "--src", "--api", "--cdn"].includes(flag)) {
48
+ const value = rest[++index];
49
+ if (!value) fail(`${flag} needs a value.`);
50
+ options[flag.slice(2)] = value;
51
+ } else fail(`unknown option "${flag}". Run npx iconplease --help.`);
52
+ }
53
+ return options;
54
+ };
55
+
56
+ const walk = (dir, outFile, found) => {
57
+ if (!existsSync(dir)) return;
58
+ for (const entry of readdirSync(dir)) {
59
+ if (SKIPPED.has(entry)) continue;
60
+ const path = join(dir, entry);
61
+ const info = statSync(path);
62
+ if (info.isDirectory()) walk(path, outFile, found);
63
+ else if (SCANNED.has(extname(entry)) && resolve(path) !== outFile && info.size < 2_000_000) {
64
+ for (const match of readFileSync(path, "utf8").matchAll(USAGE)) found.add(match[1]);
65
+ }
66
+ }
67
+ };
68
+
69
+ const getJSON = async (url, init) => {
70
+ let response;
71
+ try {
72
+ response = await fetch(url, init);
73
+ } catch (error) {
74
+ fail(`could not reach ${new URL(url).origin} (${error.message}).`);
75
+ }
76
+ const body = await response.json().catch(() => ({}));
77
+ return { status: response.status, ok: response.ok, body };
78
+ };
79
+
80
+ const fetchSet = async (api, key) => {
81
+ const { status, ok, body } = await getJSON(`${api.replace(/\/+$/, "")}/sdk/set`, { headers: { Authorization: `Bearer ${key}` } });
82
+ if (status === 401) fail(`ICONPLEASE_SECRET_KEY was refused: ${body.error ?? "not valid"}`);
83
+ if (!ok) fail(`could not read your set (${status}): ${body.error ?? "unknown error"}`);
84
+ return body;
85
+ };
86
+
87
+ const fetchPublic = async (cdn, names) => {
88
+ if (!names.length) return { icons: {}, missing: [] };
89
+ const base = cdn.replace(/\/+$/, "");
90
+ const pointer = await getJSON(`${base}/catalogue/latest.json`);
91
+ if (!pointer.ok || !/^catalogue\/index-[a-z0-9]+\.json$/.test(String(pointer.body.index ?? "").replace(/^\/+/, ""))) {
92
+ fail("could not read the public catalogue.");
93
+ }
94
+ const index = await getJSON(`${base}/${String(pointer.body.index).replace(/^\/+/, "")}`);
95
+ if (!index.ok || typeof index.body !== "object") fail("could not read the public catalogue index.");
96
+ const versions = index.body.icons ?? index.body;
97
+ const icons = {};
98
+ const missing = [];
99
+ for (const name of names) {
100
+ const version = versions[name];
101
+ if (!Number.isInteger(version) || version < 1) {
102
+ missing.push(name);
103
+ continue;
104
+ }
105
+ let response;
106
+ try {
107
+ response = await fetch(`${base}/v${version}/${name}.svg`);
108
+ } catch (error) {
109
+ fail(`could not download the public icon "${name}" (${error.message}).`);
110
+ }
111
+ if (!response.ok) fail(`could not download the public icon "${name}" (${response.status}).`);
112
+ icons[name] = { version, svg: (await response.text()).trim(), source: "public" };
113
+ }
114
+ return { icons, missing };
115
+ };
116
+
117
+ const render = (outFile, payload, names) => {
118
+ const typed = /\.(ts|tsx|mts|cts)$/.test(outFile);
119
+ const json = JSON.stringify(payload, null, 2);
120
+ const summary = `${plural(Object.values(payload.icons).filter((icon) => icon.source === "set").length, "set icon")}, ${plural(Object.values(payload.icons).filter((icon) => icon.source === "public").length, "public icon")}`;
121
+ const lines = [
122
+ "// Generated by `npx iconplease pull`. Do not edit; run it again to update.",
123
+ `// ${payload.workspace ? `Set: ${payload.workspace.name}` : "No set"} · published version ${payload.version ?? "none"} · ${summary}.`,
124
+ ];
125
+ if (typed) {
126
+ lines.push('import type { BundledSet } from "iconplease";', "", `export const set: BundledSet = ${json};`, "");
127
+ lines.push(`export type IconName = ${names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never"};`, "");
128
+ } else {
129
+ lines.push("", `export const set = ${json};`, "");
130
+ }
131
+ lines.push("export default set;", "");
132
+ return lines.join("\n");
133
+ };
134
+
135
+ const main = async () => {
136
+ const options = parseArgs(process.argv.slice(2));
137
+ if (options.help) {
138
+ console.log(HELP);
139
+ return;
140
+ }
141
+
142
+ const key = (process.env.ICONPLEASE_SECRET_KEY ?? "").trim();
143
+ if (!key) fail("set ICONPLEASE_SECRET_KEY to a secret key (ip_sk_…) from your set's API keys tab.");
144
+ if (key.startsWith("ip_pk_")) fail("ICONPLEASE_SECRET_KEY holds a publishable key. pull needs a secret key (ip_sk_…).");
145
+ if (!SECRET.test(key)) fail("ICONPLEASE_SECRET_KEY does not look like a secret key (ip_sk_ followed by 32 characters).");
146
+
147
+ const outFile = resolve(options.out);
148
+ const remote = await fetchSet(options.api, key);
149
+ const setIcons = {};
150
+ for (const [name, entry] of Object.entries(remote.icons ?? {})) {
151
+ if (NAME.test(name) && typeof entry?.svg === "string") setIcons[name] = { version: Number(entry.version) || 1, svg: entry.svg, source: "set" };
152
+ }
153
+
154
+ const used = new Set();
155
+ walk(resolve(options.src), outFile, used);
156
+ const wanted = [...used].filter((name) => !setIcons[name]).sort();
157
+ const { icons: publicIcons, missing } = await fetchPublic(options.cdn, wanted);
158
+
159
+ const all = { ...publicIcons, ...setIcons };
160
+ const names = Object.keys(all).sort();
161
+ const payload = {
162
+ format: 1,
163
+ version: typeof remote.version === "number" ? remote.version : null,
164
+ workspace: remote.workspace ? { id: remote.workspace.id, name: remote.workspace.name } : null,
165
+ icons: Object.fromEntries(names.map((name) => [name, all[name]])),
166
+ };
167
+ const output = render(outFile, payload, names);
168
+
169
+ if (output.includes(key) || SECRET.test(output)) fail("refusing to write: the output would contain a secret key.");
170
+
171
+ const where = relative(process.cwd(), outFile) || outFile;
172
+ if (remote.version === null || remote.version === undefined) console.warn("iconplease: this set has not been published yet, so it adds no icons. Publish it in your account.");
173
+ if (missing.length) console.warn(`iconplease: not in your set or the public library: ${missing.join(", ")}. Check the spelling.`);
174
+
175
+ if (options.check) {
176
+ const current = existsSync(outFile) ? readFileSync(outFile, "utf8") : null;
177
+ if (current !== output) fail(`${where} is ${current === null ? "missing" : "out of date"}. Run npx iconplease pull and commit the result.`);
178
+ console.log(`iconplease: ${where} is up to date (${plural(names.length, "icon")}, set version ${payload.version ?? "none"}).`);
179
+ return;
180
+ }
181
+
182
+ mkdirSync(dirname(outFile), { recursive: true });
183
+ writeFileSync(outFile, output);
184
+ console.log(`iconplease: wrote ${where} — ${plural(Object.keys(setIcons).length, "set icon")}, ${plural(Object.keys(publicIcons).length, "public icon")}, set version ${payload.version ?? "none"}.`);
185
+ };
186
+
187
+ main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
@@ -0,0 +1,64 @@
1
+ export type AnimationPreset = "draw" | "fade" | "pop" | "spin" | "slide-up" | "slide-down" | "slide-left" | "slide-right" | "bounce" | "pulse" | "shake" | "follow";
2
+ export type AnimationEasing = "linear" | "ease-in" | "ease-out" | "ease-in-out" | "spring";
3
+ export type AnimationTrigger = "load" | "hover" | "click" | "visible";
4
+ export type AnimationClip = {
5
+ id: string;
6
+ target: string;
7
+ preset: AnimationPreset;
8
+ start: number;
9
+ duration: number;
10
+ easing: AnimationEasing;
11
+ path?: string;
12
+ orient?: boolean;
13
+ };
14
+ export type IconAnimation = {
15
+ version: 1;
16
+ trigger: AnimationTrigger;
17
+ loop: boolean;
18
+ loopGap: number;
19
+ clips: AnimationClip[];
20
+ };
21
+ type Frame = {
22
+ offset: number;
23
+ transform?: string;
24
+ opacity?: number;
25
+ };
26
+ type PresetSpec = {
27
+ label: string;
28
+ hint: string;
29
+ duration: number;
30
+ easing: AnimationEasing;
31
+ frames?: Frame[];
32
+ draw?: boolean;
33
+ route?: boolean;
34
+ };
35
+ export declare const PRESETS: Record<AnimationPreset, PresetSpec>;
36
+ export declare const PRESET_ORDER: AnimationPreset[];
37
+ export declare const ROUTE_PATH: RegExp;
38
+ export declare const EASINGS: Record<AnimationEasing, {
39
+ label: string;
40
+ css: string;
41
+ }>;
42
+ export declare const TRIGGERS: Record<AnimationTrigger, string>;
43
+ export declare const MAX_CLIPS = 64;
44
+ export declare const MAX_TIME = 10000;
45
+ export declare const MIN_DURATION = 50;
46
+ export declare const cleanAnimation: (value: unknown) => IconAnimation | undefined;
47
+ export declare const ANIMATION_ATTRIBUTE = "data-ip-animation";
48
+ export declare const MARKER_ATTRIBUTE = "data-ip";
49
+ export declare const encodeAnimation: (animation: IconAnimation) => string;
50
+ export declare const decodeAnimation: (value: string | undefined | null) => IconAnimation | undefined;
51
+ export declare const totalDuration: (animation: Pick<IconAnimation, "clips">) => number;
52
+ export type Playback = {
53
+ play: () => void;
54
+ pause: () => void;
55
+ seek: (time: number) => void;
56
+ cancel: () => void;
57
+ readonly period: number;
58
+ readonly animations: Animation[];
59
+ };
60
+ export declare const animate: (animation: IconAnimation, targetsOf: (target: string) => Element[], options?: {
61
+ paused?: boolean;
62
+ loop?: boolean;
63
+ }) => Playback;
64
+ export {};
@@ -0,0 +1,243 @@
1
+ export const PRESETS = {
2
+ draw: { label: "Draw on", hint: "Strokes draw themselves", duration: 700, easing: "ease-in-out", draw: true },
3
+ fade: { label: "Fade in", hint: "From invisible to visible", duration: 400, easing: "ease-out", frames: [{ offset: 0, opacity: 0 }, { offset: 1, opacity: 1 }] },
4
+ pop: { label: "Pop in", hint: "Grows from nothing with a little overshoot", duration: 450, easing: "spring", frames: [{ offset: 0, transform: "scale(0)" }, { offset: 1, transform: "scale(1)" }] },
5
+ spin: { label: "Spin", hint: "One full turn", duration: 800, easing: "ease-in-out", frames: [{ offset: 0, transform: "rotate(0deg)" }, { offset: 1, transform: "rotate(360deg)" }] },
6
+ "slide-up": { label: "Slide up", hint: "Rises into place", duration: 450, easing: "ease-out", frames: [{ offset: 0, transform: "translateY(4px)", opacity: 0 }, { offset: 1, transform: "translateY(0px)", opacity: 1 }] },
7
+ "slide-down": { label: "Slide down", hint: "Drops into place", duration: 450, easing: "ease-out", frames: [{ offset: 0, transform: "translateY(-4px)", opacity: 0 }, { offset: 1, transform: "translateY(0px)", opacity: 1 }] },
8
+ "slide-left": { label: "Slide left", hint: "Comes in from the right", duration: 450, easing: "ease-out", frames: [{ offset: 0, transform: "translateX(4px)", opacity: 0 }, { offset: 1, transform: "translateX(0px)", opacity: 1 }] },
9
+ "slide-right": { label: "Slide right", hint: "Comes in from the left", duration: 450, easing: "ease-out", frames: [{ offset: 0, transform: "translateX(-4px)", opacity: 0 }, { offset: 1, transform: "translateX(0px)", opacity: 1 }] },
10
+ bounce: {
11
+ label: "Bounce",
12
+ hint: "Hops up and lands",
13
+ duration: 700,
14
+ easing: "ease-out",
15
+ frames: [
16
+ { offset: 0, transform: "translateY(0px)" },
17
+ { offset: 0.35, transform: "translateY(-4px)" },
18
+ { offset: 0.65, transform: "translateY(0px)" },
19
+ { offset: 0.82, transform: "translateY(-1.5px)" },
20
+ { offset: 1, transform: "translateY(0px)" },
21
+ ],
22
+ },
23
+ pulse: {
24
+ label: "Pulse",
25
+ hint: "Swells and settles",
26
+ duration: 600,
27
+ easing: "ease-in-out",
28
+ frames: [
29
+ { offset: 0, transform: "scale(1)" },
30
+ { offset: 0.5, transform: "scale(1.18)" },
31
+ { offset: 1, transform: "scale(1)" },
32
+ ],
33
+ },
34
+ follow: { label: "Move along path", hint: "The shape's centre travels along a route you drew", duration: 1200, easing: "ease-in-out", route: true },
35
+ shake: {
36
+ label: "Shake",
37
+ hint: "A quick wobble",
38
+ duration: 600,
39
+ easing: "ease-in-out",
40
+ frames: [
41
+ { offset: 0, transform: "rotate(0deg)" },
42
+ { offset: 0.2, transform: "rotate(-14deg)" },
43
+ { offset: 0.4, transform: "rotate(12deg)" },
44
+ { offset: 0.6, transform: "rotate(-8deg)" },
45
+ { offset: 0.8, transform: "rotate(4deg)" },
46
+ { offset: 1, transform: "rotate(0deg)" },
47
+ ],
48
+ },
49
+ };
50
+ export const PRESET_ORDER = Object.keys(PRESETS).filter((preset) => !PRESETS[preset].route);
51
+ export const ROUTE_PATH = /^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]{1,8000}$/;
52
+ export const EASINGS = {
53
+ linear: { label: "Linear", css: "linear" },
54
+ "ease-in": { label: "Ease in", css: "cubic-bezier(0.4, 0, 1, 1)" },
55
+ "ease-out": { label: "Ease out", css: "cubic-bezier(0, 0, 0.2, 1)" },
56
+ "ease-in-out": { label: "Ease in-out", css: "cubic-bezier(0.4, 0, 0.2, 1)" },
57
+ spring: { label: "Spring", css: "cubic-bezier(0.34, 1.56, 0.64, 1)" },
58
+ };
59
+ export const TRIGGERS = {
60
+ load: "When it appears",
61
+ hover: "On hover",
62
+ click: "On click",
63
+ visible: "When scrolled into view",
64
+ };
65
+ export const MAX_CLIPS = 64;
66
+ export const MAX_TIME = 10000;
67
+ export const MIN_DURATION = 50;
68
+ const PRESET_SET = new Set(PRESET_ORDER);
69
+ const ID = /^[A-Za-z0-9_-]{1,64}$/;
70
+ const ms = (value, low, high) => typeof value === "number" && Number.isFinite(value) ? Math.round(Math.min(Math.max(value, low), high)) : undefined;
71
+ export const cleanAnimation = (value) => {
72
+ if (!value || typeof value !== "object")
73
+ return undefined;
74
+ const raw = value;
75
+ const clips = [];
76
+ for (const clip of Array.isArray(raw.clips) ? raw.clips.slice(0, MAX_CLIPS) : []) {
77
+ if (!clip || typeof clip !== "object")
78
+ continue;
79
+ const start = ms(clip.start, 0, MAX_TIME);
80
+ const duration = ms(clip.duration, MIN_DURATION, MAX_TIME);
81
+ if (typeof clip.id !== "string" || !ID.test(clip.id))
82
+ continue;
83
+ if (typeof clip.target !== "string" || !ID.test(clip.target))
84
+ continue;
85
+ if (!PRESET_SET.has(clip.preset) || start === undefined || duration === undefined)
86
+ continue;
87
+ const route = PRESETS[clip.preset].route;
88
+ if (route && (typeof clip.path !== "string" || !ROUTE_PATH.test(clip.path) || !/^\s*[Mm]/.test(clip.path)))
89
+ continue;
90
+ clips.push({
91
+ id: clip.id,
92
+ target: clip.target,
93
+ preset: clip.preset,
94
+ start,
95
+ duration,
96
+ easing: clip.easing && clip.easing in EASINGS ? clip.easing : PRESETS[clip.preset].easing,
97
+ ...(route ? { path: clip.path, orient: clip.orient === true } : {}),
98
+ });
99
+ }
100
+ if (!clips.length)
101
+ return undefined;
102
+ return {
103
+ version: 1,
104
+ trigger: raw.trigger && raw.trigger in TRIGGERS ? raw.trigger : "load",
105
+ loop: raw.loop === true,
106
+ loopGap: ms(raw.loopGap, 0, MAX_TIME) ?? 0,
107
+ clips,
108
+ };
109
+ };
110
+ export const ANIMATION_ATTRIBUTE = "data-ip-animation";
111
+ export const MARKER_ATTRIBUTE = "data-ip";
112
+ const toBase64Url = (text) => btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
113
+ const fromBase64Url = (value) => atob(value.replace(/-/g, "+").replace(/_/g, "/"));
114
+ export const encodeAnimation = (animation) => toBase64Url(JSON.stringify(animation));
115
+ export const decodeAnimation = (value) => {
116
+ if (!value || value.length > 60000 || !/^[A-Za-z0-9_-]+$/.test(value))
117
+ return undefined;
118
+ try {
119
+ return cleanAnimation(JSON.parse(fromBase64Url(value)));
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ };
125
+ export const totalDuration = (animation) => animation.clips.reduce((end, clip) => Math.max(end, clip.start + clip.duration), 0);
126
+ const GEOMETRY = "path, line, rect, ellipse, circle, polyline, polygon";
127
+ const strokesOf = (root) => [...root.querySelectorAll(GEOMETRY)].filter((node) => {
128
+ if (node.closest("defs, clipPath, mask"))
129
+ return false;
130
+ const stroke = node.getAttribute("stroke") ?? getComputedStyle(node).stroke;
131
+ return Boolean(stroke) && stroke !== "none" && stroke !== "transparent" && typeof node.getTotalLength === "function";
132
+ });
133
+ const SVG_NS = "http://www.w3.org/2000/svg";
134
+ const ROUTE_SAMPLES = 48;
135
+ const routeFrames = (root, d, orient) => {
136
+ const host = root.ownerSVGElement ?? root.closest("svg");
137
+ if (!host || typeof root.getBBox !== "function")
138
+ return [];
139
+ const guide = document.createElementNS(SVG_NS, "path");
140
+ guide.setAttribute("d", d);
141
+ guide.setAttribute("visibility", "hidden");
142
+ host.appendChild(guide);
143
+ try {
144
+ const length = guide.getTotalLength();
145
+ const box = root.getBBox();
146
+ const cx = box.x + box.width / 2;
147
+ const cy = box.y + box.height / 2;
148
+ const at = (distance) => guide.getPointAtLength(Math.min(Math.max(distance, 0), length));
149
+ const angle = (distance) => {
150
+ const step = Math.max(length / 400, 0.01);
151
+ const a = at(distance - step);
152
+ const b = at(distance + step);
153
+ return (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
154
+ };
155
+ const first = angle(0);
156
+ let previous = 0;
157
+ return Array.from({ length: ROUTE_SAMPLES + 1 }, (_, index) => {
158
+ const distance = (index / ROUTE_SAMPLES) * length;
159
+ const point = at(distance);
160
+ let turn = angle(distance) - first;
161
+ while (turn - previous > 180)
162
+ turn -= 360;
163
+ while (turn - previous < -180)
164
+ turn += 360;
165
+ previous = turn;
166
+ const move = `translate(${(point.x - cx).toFixed(3)}px, ${(point.y - cy).toFixed(3)}px)`;
167
+ return { offset: index / ROUTE_SAMPLES, transform: orient ? `${move} rotate(${turn.toFixed(2)}deg)` : move };
168
+ });
169
+ }
170
+ finally {
171
+ guide.remove();
172
+ }
173
+ };
174
+ const onTimeline = (frames, clip, period, neutral) => {
175
+ const begin = clip.start / period;
176
+ const end = (clip.start + clip.duration) / period;
177
+ const easing = EASINGS[clip.easing].css;
178
+ const placed = frames.map((frame, index) => ({
179
+ ...frame,
180
+ offset: begin + frame.offset * (end - begin),
181
+ easing: index < frames.length - 1 ? easing : "linear",
182
+ }));
183
+ const first = { ...(neutral ?? frames[0]), offset: 0, easing: "linear" };
184
+ const last = { ...frames[frames.length - 1], offset: 1, easing: "linear" };
185
+ const out = [];
186
+ if (placed[0].offset > 0) {
187
+ out.push(first);
188
+ if (neutral)
189
+ out.push({ ...neutral, offset: placed[0].offset, easing: "linear" });
190
+ }
191
+ out.push(...placed);
192
+ if (placed[placed.length - 1].offset < 1)
193
+ out.push(last);
194
+ return out;
195
+ };
196
+ export const animate = (animation, targetsOf, options = {}) => {
197
+ const total = Math.max(totalDuration(animation), MIN_DURATION);
198
+ const loop = options.loop ?? animation.loop;
199
+ const period = loop ? total + animation.loopGap : total;
200
+ const animations = [];
201
+ const timing = { duration: period, iterations: loop ? Infinity : 1, fill: "both" };
202
+ for (const clip of animation.clips) {
203
+ const spec = PRESETS[clip.preset];
204
+ const follows = animation.clips.some((other) => other.target === clip.target && other.start < clip.start);
205
+ for (const root of targetsOf(clip.target)) {
206
+ if (spec.draw) {
207
+ for (const stroke of strokesOf(root)) {
208
+ const length = Math.max(stroke.getTotalLength(), 0.01);
209
+ const frames = [
210
+ { offset: 0, strokeDasharray: `${length} ${length}`, strokeDashoffset: length },
211
+ { offset: 1, strokeDasharray: `${length} ${length}`, strokeDashoffset: 0 },
212
+ ];
213
+ const shown = follows ? { offset: 0, strokeDasharray: `${length} ${length}`, strokeDashoffset: 0 } : undefined;
214
+ animations.push(stroke.animate(onTimeline(frames, clip, period, shown), timing));
215
+ }
216
+ continue;
217
+ }
218
+ const element = root;
219
+ element.style.transformBox = "fill-box";
220
+ element.style.transformOrigin = "center";
221
+ const frames = spec.route ? routeFrames(root, clip.path ?? "", clip.orient === true) : (spec.frames ?? []).map((frame) => ({ ...frame }));
222
+ if (!frames.length)
223
+ continue;
224
+ const moves = frames.some((frame) => frame.transform !== undefined);
225
+ const fades = frames.some((frame) => frame.opacity !== undefined);
226
+ const shown = follows
227
+ ? { offset: 0, ...(moves ? { transform: "translate(0px, 0px)" } : {}), ...(fades ? { opacity: 1 } : {}) }
228
+ : undefined;
229
+ animations.push(element.animate(onTimeline(frames, clip, period, shown), { ...timing, composite: moves ? "add" : "replace" }));
230
+ }
231
+ }
232
+ const each = (fn) => animations.forEach(fn);
233
+ if (options.paused)
234
+ each((item) => item.pause());
235
+ return {
236
+ play: () => each((item) => item.play()),
237
+ pause: () => each((item) => item.pause()),
238
+ seek: (time) => each((item) => (item.currentTime = Math.max(0, time))),
239
+ cancel: () => each((item) => item.cancel()),
240
+ period,
241
+ animations,
242
+ };
243
+ };
package/dist/config.d.ts CHANGED
@@ -5,3 +5,5 @@ export declare const cdnBase: () => string;
5
5
  export declare const revalidateMs: () => number;
6
6
  export declare const apiBase: () => string;
7
7
  export declare const apiKey: () => string | undefined;
8
+ export declare const tokenSource: () => import("./types.js").TokenSource | undefined;
9
+ export declare const bundledSet: () => import("./types.js").BundledSet | undefined;
package/dist/config.js CHANGED
@@ -11,6 +11,9 @@ export const init = (next = {}) => {
11
11
  if (next.apiKey && !/^ip_pk_[A-Za-z0-9]{32}$/.test(next.apiKey)) {
12
12
  console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load.");
13
13
  }
14
+ if (next.token !== undefined && typeof next.token !== "function") {
15
+ throw new Error("iconplease: token must be a function that asks your server for a fresh token, e.g. () => fetch(\"/api/iconplease-token\").then((r) => r.json()).");
16
+ }
14
17
  config = { ...DEFAULTS, ...next };
15
18
  return config;
16
19
  };
@@ -19,3 +22,5 @@ export const cdnBase = () => (config.cdnUrl ?? DEFAULTS.cdnUrl).replace(/\/+$/,
19
22
  export const revalidateMs = () => Math.max(0, config.revalidate ?? DEFAULTS.revalidate) * 1000;
20
23
  export const apiBase = () => (config.apiUrl ?? DEFAULTS.apiUrl).replace(/\/+$/, "");
21
24
  export const apiKey = () => config.apiKey || undefined;
25
+ export const tokenSource = () => config.token;
26
+ export const bundledSet = () => config.set;
@@ -1 +1 @@
1
- "use strict";(()=>{var w={cdnUrl:"https://cdn.iconplease.com",apiUrl:"https://api.iconplease.com",revalidate:3600},g={...w},C=(e={})=>{if(e.apiKey&&e.apiKey.startsWith("ip_sk_"))throw new Error("iconplease: that is a secret key. init() runs in the browser, where the key is readable by anyone \u2014 use the publishable key (ip_pk_\u2026).");return e.apiKey&&!/^ip_pk_[A-Za-z0-9]{32}$/.test(e.apiKey)&&console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load."),g={...w,...e},g};var P=()=>{var e;return((e=g.cdnUrl)!=null?e:w.cdnUrl).replace(/\/+$/,"")},j=()=>{var e;return Math.max(0,(e=g.revalidate)!=null?e:w.revalidate)*1e3},X=()=>{var e;return((e=g.apiUrl)!=null?e:w.apiUrl).replace(/\/+$/,"")},x=()=>g.apiKey||void 0;var me=/<\s*(script|foreignObject|iframe|object|embed|style)\b[\s\S]*?(<\s*\/\s*\1\s*>|\/>)/gi,he=/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,ye=/\s+(?:xlink:)?href\s*=\s*("\s*javascript:[^"]*"|'\s*javascript:[^']*')/gi,be=/^[a-z][a-z0-9-]*$/,we=/^[^"<>]*$/,xe=e=>e.replace(me,"").replace(he,"").replace(ye,""),D=e=>{var o;if(!e||typeof e!="object")return;let t=e;if(typeof t.body!="string"||typeof t.viewBox!="string"||!/^[0-9.\s-]+$/.test(t.viewBox))return;let n={};for(let[s,r]of Object.entries((o=t.attrs)!=null?o:{}))be.test(s)&&!s.startsWith("on")&&typeof r=="string"&&we.test(r)&&(n[s]=r);return{viewBox:t.viewBox,attrs:n,body:xe(t.body)}};var te="iconplease:index:v2",ne="iconplease:icons:v2",oe="iconplease:set:v1",ve=1e3,A=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,c={status:"idle",revision:0},O=0,I,Y=!1,Z=!1,M,m=new Map,u=new Map,T,k=0,h=!1,v,_=!1,R=new Map,z=new Set,S=()=>{try{return typeof localStorage=="undefined"?void 0:localStorage}catch{return}},p=(e={})=>{c={...c,...e,revision:c.revision+1};for(let t of z)t()},E=(e,t)=>`${e}@${t}`,se=e=>{if(!e||typeof e!="object")return;let t=e;if(t.format!==2||typeof t.hash!="string"||!t.icons||typeof t.icons!="object")return;let n=Object.entries(t.icons).filter(([o,s])=>A.test(o)&&Number.isInteger(s)&&s>0);return{format:2,hash:t.hash,icons:Object.fromEntries(n)}},L=e=>e.slice(0,14),ke=()=>{var n,o,s;let e=x(),t=e?L(e):void 0;if(t!==T&&(T=t,u.clear(),k=0,h=!1,v=void 0,_=!1,!!t))try{let r=JSON.parse((o=(n=S())==null?void 0:n.getItem(oe))!=null?o:"null");if(!r||r.tag!==t)return;for(let[i,f]of Object.entries((s=r.icons)!=null?s:{})){let a=A.test(i)&&typeof(f==null?void 0:f.svg)=="string"?K(f.svg):void 0;a&&u.set(i,a)}k=typeof r.checkedAt=="number"?r.checkedAt:0,h=!0}catch{return}},y=()=>{var t,n;if(ke(),Y)return;Y=!0;let e=S();if(e){try{let o=JSON.parse((t=e.getItem(te))!=null?t:"null"),s=se(o==null?void 0:o.index);s&&(c={status:"ready",index:s,revision:c.revision},O=typeof(o==null?void 0:o.checkedAt)=="number"?o.checkedAt:0)}catch{return}try{let o=JSON.parse((n=e.getItem(ne))!=null?n:"{}");for(let[s,r]of Object.entries(o)){let i=D(r);i&&m.set(s,i)}}catch{return}}},Q=()=>{var e;try{(e=S())==null||e.setItem(te,JSON.stringify({index:c.index,checkedAt:O}))}catch{return}},re=()=>{M||(M=setTimeout(()=>{var n,o,s;M=void 0;let e=(o=(n=c.index)==null?void 0:n.icons)!=null?o:{},t=[...m.entries()].filter(([r])=>{let i=r.lastIndexOf("@");return e[r.slice(0,i)]===Number(r.slice(i+1))});try{(s=S())==null||s.setItem(ne,JSON.stringify(Object.fromEntries(t.slice(-ve))))}catch{return}},0))},ee=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} for ${e}`);return t.json()},ie=e=>{Z||(Z=!0,console.warn("iconplease: could not reach the icon CDN.",e))},Se=async()=>{var s;let e=P(),t=await ee(`${e}/catalogue/latest.json`);if((t==null?void 0:t.format)!==2||typeof t.hash!="string"||typeof t.index!="string")throw new Error("iconplease: the catalogue pointer is malformed");if(O=Date.now(),((s=c.index)==null?void 0:s.hash)===t.hash){Q();return}let n=t.index.replace(/^\/+/,"");if(!/^catalogue\/index-[a-z0-9]+\.json$/.test(n))throw new Error("iconplease: unexpected index location");let o=se(await ee(`${e}/${n}`));if(!o)throw new Error("iconplease: the icon index is malformed");p({status:"ready",index:o}),Q(),re()},B=(e={})=>{if(y(),c.index&&Date.now()-O<j()&&!e.force)return Promise.resolve();if(I)return I;let n=Se().catch(o=>{c.index||p({status:"error"}),ie(o)}).finally(()=>{I=void 0});return I=n,!c.index&&c.status!=="loading"&&p({status:"loading"}),n},K=e=>{let t=/<svg\b([^>]*)>([\s\S]*)<\/svg>\s*$/.exec(e.trim());if(!t)return;let n={},o="0 0 24 24";for(let[,s,r]of t[1].matchAll(/([a-zA-Z:-]+)="([^"]*)"/g))s==="viewBox"?o=r:["xmlns","width","height","aria-hidden","role","class","style"].includes(s)||(n[s]=r);return D({viewBox:o,attrs:n,body:t[2]})},Ie=(e,t)=>{let n=E(e,t),o=R.get(n);if(o)return o;let s=fetch(`${P()}/v${t}/${e}.svg`).then(async r=>{if(!r.ok)throw new Error(`${r.status} for ${e}`);let i=K(await r.text());if(!i)throw new Error(`iconplease: "${e}" is not a valid SVG`);m.set(n,i),re(),p()}).catch(ie).finally(()=>{R.delete(n)});return R.set(n,s),s},Ee=async e=>{var r,i;let t=await fetch(`${X()}/sdk/set?key=${encodeURIComponent(e)}`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);let o=new Map,s={};for(let[f,a]of Object.entries((r=n.icons)!=null?r:{})){if(!A.test(f)||typeof(a==null?void 0:a.svg)!="string")continue;let l=K(a.svg);l&&(o.set(f,l),s[f]={version:Number(a.version)||1,svg:a.svg})}if(L(e)===T){u.clear();for(let[f,a]of o)u.set(f,a);k=Date.now(),h=!0;try{(i=S())==null||i.setItem(oe,JSON.stringify({tag:L(e),checkedAt:k,icons:s}))}catch{p();return}p()}},U=(e={})=>{y();let t=x();if(!t||h&&Date.now()-k<j()&&!e.force)return Promise.resolve();if(v)return v;let o=Ee(t).catch(s=>{h=!0,_||(_=!0,console.warn(`iconplease: could not load your icon set \u2014 ${s instanceof Error?s.message:String(s)} Falling back to public icons.`)),p()}).finally(()=>{v=void 0});return v=o,o},F=async e=>{var o,s;if(!A.test(e))return;if(y(),x()){if(u.has(e)){U();return}if(await U(),u.has(e))return}let t=(o=c.index)==null?void 0:o.icons[e];if(t&&m.has(E(e,t))){B();return}await B();let n=(s=c.index)==null?void 0:s.icons[e];n&&!m.has(E(e,n))&&await Ie(e,n)},J=async(e={})=>{let{icons:t=[],force:n=!1}=Array.isArray(e)?{icons:e}:e;await Promise.all([B({force:n}),U({force:n})]),await Promise.all(t.map(F))},ae=e=>(y(),z.add(e),()=>z.delete(e));var $=e=>{var o;y();let t=u.get(e);if(t)return t;let n=(o=c.index)==null?void 0:o.icons[e];return n?m.get(E(e,n)):void 0},ce=e=>(y(),u.has(e)||x()&&!h?!1:c.status==="ready"&&!!c.index&&!(e in c.index.icons));var Ae=/^[#a-zA-Z0-9(),.%\s-]{1,64}$/,Oe=/[<>"&]/g,$e={"<":"&lt;",">":"&gt;",'"':"&quot;","&":"&amp;"},Ne=e=>e.replace(Oe,t=>$e[t]),de=e=>String(Number(e.toFixed(3))),Ce=(e,t)=>e.replace(/\b(fill|stroke)="currentColor"/g,`$1="${t}"`),Pe=(e,t)=>e.replace(/\bstroke-width="([0-9]*\.?[0-9]+)"/g,(n,o)=>`stroke-width="${de(Number(o)*t)}"`),q=(e,t={})=>{var G;let{size:n=24,color:o,strokeScale:s,motion:r,label:i,className:f}=t,a=o&&Ae.test(o)?o:void 0,l=typeof s=="number"&&Number.isFinite(s)&&s>0&&s!==1?s:void 0,d={...(G=e.attrs)!=null?G:{}};if(a)for(let W of["fill","stroke"])d[W]==="currentColor"&&(d[W]=a);l&&d["stroke-width"]&&(d["stroke-width"]=de(Number(d["stroke-width"])*l));let b=e.body;return a&&(b=Ce(b,a)),l&&(b=Pe(b,l)),d.width=String(n),d.height=String(n),d.viewBox=e.viewBox,r&&r!=="none"&&(d["data-motion"]=r),i?(d.role="img",d["aria-label"]=i):d["aria-hidden"]="true",f&&(d.class=f),{attrs:d,body:b}},H=({attrs:e,body:t})=>`<svg xmlns="http://www.w3.org/2000/svg" ${Object.entries(e).map(([o,s])=>`${o}="${Ne(s)}"`).join(" ")}>${t}</svg>`,fe=(e,t={})=>{let n=typeof e=="string"?$(e):e;return n?H(q(n,t)):void 0};var le="[data-icon], i.ip[class*='ip-']",je=new Set(["none","wiggle","pop","bounce","draw"]),ue=new Set,De=e=>{let t=e.getAttribute("data-icon");if(t)return t;for(let n of Array.from(e.classList))if(n.startsWith("ip-")&&n.length>3)return n.slice(3)},pe=e=>{if(e===null)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},V=e=>{var f,a,l,d;let t=De(e);if(!t)return;let n=$(t),o=e.getAttribute("data-motion"),s=o&&je.has(o)?o:void 0,r={size:(f=pe(e.getAttribute("data-size")))!=null?f:24,color:(a=e.getAttribute("data-color"))!=null?a:void 0,strokeScale:pe(e.getAttribute("data-stroke")),motion:s,label:(l=e.getAttribute("data-label"))!=null?l:void 0},i=JSON.stringify([t,r,n?"1":"0"]);if(e.getAttribute("data-ip-rendered")!==i){if(!n){ce(t)?ue.has(t)||(ue.add(t),console.warn(`iconplease: no icon named "${t}".`)):F(t);return}e.innerHTML=H(q(n,r)),e.setAttribute("data-ip-rendered",i),e.tagName==="I"&&((d=e.style).display||(d.display="inline-flex"))}},N=(e=document)=>{e instanceof Element&&e.matches(le)&&V(e),e.querySelectorAll(le).forEach(V)},ge=()=>{let e=window.iconpleaseConfig;e&&C(e),ae(()=>N()),N(),J(),new MutationObserver(t=>{for(let n of t)n.type==="attributes"&&n.target instanceof Element&&V(n.target),n.addedNodes.forEach(o=>{o instanceof Element&&N(o)})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-icon","data-size","data-color","data-stroke","data-motion","data-label","class"]})};window.iconplease={init:C,load:J,renderSVG:fe,refresh:()=>N()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ge,{once:!0}):ge();})();
1
+ "use strict";(()=>{var M={cdnUrl:"https://cdn.iconplease.com",apiUrl:"https://api.iconplease.com",revalidate:3600},k={...M},Z=(e={})=>{if(e.apiKey&&e.apiKey.startsWith("ip_sk_"))throw new Error("iconplease: that is a secret key. init() runs in the browser, where the key is readable by anyone \u2014 use the publishable key (ip_pk_\u2026).");if(e.apiKey&&!/^ip_pk_[A-Za-z0-9]{32}$/.test(e.apiKey)&&console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load."),e.token!==void 0&&typeof e.token!="function")throw new Error('iconplease: token must be a function that asks your server for a fresh token, e.g. () => fetch("/api/iconplease-token").then((r) => r.json()).');return k={...M,...e},k};var Q=()=>{var e;return((e=k.cdnUrl)!=null?e:M.cdnUrl).replace(/\/+$/,"")},ee=()=>{var e;return Math.max(0,(e=k.revalidate)!=null?e:M.revalidate)*1e3},te=()=>{var e;return((e=k.apiUrl)!=null?e:M.apiUrl).replace(/\/+$/,"")},ne=()=>k.apiKey||void 0,$=()=>k.token,ve=()=>k.set;var et=/<\s*(script|foreignObject|iframe|object|embed|style)\b[\s\S]*?(<\s*\/\s*\1\s*>|\/>)/gi,tt=/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,nt=/\s+(?:xlink:)?href\s*=\s*("\s*javascript:[^"]*"|'\s*javascript:[^']*')/gi,ot=/^[a-z][a-z0-9-]*$/,rt=/^[^"<>]*$/,st=e=>e.replace(et,"").replace(tt,"").replace(nt,""),oe=e=>{var r;if(!e||typeof e!="object")return;let t=e;if(typeof t.body!="string"||typeof t.viewBox!="string"||!/^[0-9.\s-]+$/.test(t.viewBox))return;let n={};for(let[o,s]of Object.entries((r=t.attrs)!=null?r:{}))ot.test(o)&&!o.startsWith("on")&&typeof s=="string"&&rt.test(s)&&(n[o]=s);return{viewBox:t.viewBox,attrs:n,body:st(t.body)}};var Oe="iconplease:index:v2",Pe="iconplease:icons:v2",Me="iconplease:set:v1",it=1e3,C=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,g={status:"idle",revision:0},Y=0,z,Ae=!1,Se=!1,re,I=new Map,T=new Map,ie,_=0,O=!1,R,ae=!1,se=new Map,P=null,ce=0,at=6e4,D,U=null,le=new Map,F=new Map,ct=()=>{let e=ve();if(e!==D&&(D=e,le.clear(),F.clear(),U=null,!(!e||e.format!==1||typeof e.icons!="object"))){U=typeof e.version=="number"?e.version:null;for(let[t,n]of Object.entries(e.icons)){if(!C.test(t)||typeof(n==null?void 0:n.svg)!="string")continue;let r=q(n.svg);r&&(n.source==="public"?F:le).set(t,r)}}},lt=()=>P!==null&&(U===null||P>U),E=e=>{var t,n;return D?lt()?(t=T.get(e))!=null?t:F.get(e):(n=le.get(e))!=null?n:F.get(e):T.get(e)};var fe=new Set,L=()=>{try{return typeof localStorage=="undefined"?void 0:localStorage}catch{return}},A=(e={})=>{g={...g,...e,revision:g.revision+1};for(let t of fe)t()},V=(e,t)=>`${e}@${t}`,$e=e=>{if(!e||typeof e!="object")return;let t=e;if(t.format!==2||typeof t.hash!="string"||!t.icons||typeof t.icons!="object")return;let n=Object.entries(t.icons).filter(([r,o])=>C.test(r)&&Number.isInteger(o)&&o>0);return{format:2,hash:t.hash,icons:Object.fromEntries(n)}},ft=e=>e.slice(0,14),j=()=>{if($())return"token";let e=ne();return e?ft(e):void 0},dt=6e4,ut=9*6e4,K,N,pt=(e=!1)=>{let t=$();return t?!e&&K&&K.expiresAt-dt>Date.now()?Promise.resolve(K.token):N||(N=t().then(n=>{let r=typeof n=="string"?n:n==null?void 0:n.token;if(typeof r!="string"||!r.startsWith("ipt_"))throw new Error("your token function did not return an iconplease token (ipt_\u2026).");let o=typeof n=="string"?void 0:n.expiresAt,s=typeof o=="number"?o:o?Date.parse(o):NaN;return K={token:r,expiresAt:Number.isFinite(s)?s:Date.now()+ut},r}).finally(()=>{N=void 0}),N):Promise.reject(new Error("no token source"))},gt=()=>{var t,n,r;let e=j();if(e!==ie&&(ie=e,T.clear(),_=0,O=!1,R=void 0,ae=!1,P=null,ce=0,!!e))try{if(e==="token")return;let o=JSON.parse((n=(t=L())==null?void 0:t.getItem(Me))!=null?n:"null");if(!o||o.tag!==e)return;for(let[s,i]of Object.entries((r=o.icons)!=null?r:{})){let a=C.test(s)&&typeof(i==null?void 0:i.svg)=="string"?q(i.svg):void 0;a&&T.set(s,a)}_=typeof o.checkedAt=="number"?o.checkedAt:0,P=typeof o.version=="number"?o.version:null,O=!0}catch{return}},S=()=>{var t,n;if(ct(),gt(),Ae)return;Ae=!0;let e=L();if(e){try{let r=JSON.parse((t=e.getItem(Oe))!=null?t:"null"),o=$e(r==null?void 0:r.index);o&&(g={status:"ready",index:o,revision:g.revision},Y=typeof(r==null?void 0:r.checkedAt)=="number"?r.checkedAt:0)}catch{return}try{let r=JSON.parse((n=e.getItem(Pe))!=null?n:"{}");for(let[o,s]of Object.entries(r)){let i=oe(s);i&&I.set(o,i)}}catch{return}}},Ee=()=>{var e;try{(e=L())==null||e.setItem(Oe,JSON.stringify({index:g.index,checkedAt:Y}))}catch{return}},Ne=()=>{re||(re=setTimeout(()=>{var n,r,o;re=void 0;let e=(r=(n=g.index)==null?void 0:n.icons)!=null?r:{},t=[...I.entries()].filter(([s])=>{let i=s.lastIndexOf("@");return e[s.slice(0,i)]===Number(s.slice(i+1))});try{(o=L())==null||o.setItem(Pe,JSON.stringify(Object.fromEntries(t.slice(-it))))}catch{return}},0))},Ie=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} for ${e}`);return t.json()},Re=e=>{Se||(Se=!0,console.warn("iconplease: could not reach the icon CDN.",e))},mt=async()=>{var o;let e=Q(),t=await Ie(`${e}/catalogue/latest.json`);if((t==null?void 0:t.format)!==2||typeof t.hash!="string"||typeof t.index!="string")throw new Error("iconplease: the catalogue pointer is malformed");if(Y=Date.now(),((o=g.index)==null?void 0:o.hash)===t.hash){Ee();return}let n=t.index.replace(/^\/+/,"");if(!/^catalogue\/index-[a-z0-9]+\.json$/.test(n))throw new Error("iconplease: unexpected index location");let r=$e(await Ie(`${e}/${n}`));if(!r)throw new Error("iconplease: the icon index is malformed");A({status:"ready",index:r}),Ee(),Ne()},de=(e={})=>{if(S(),g.index&&Date.now()-Y<ee()&&!e.force)return Promise.resolve();if(z)return z;let n=mt().catch(r=>{g.index||A({status:"error"}),Re(r)}).finally(()=>{z=void 0});return z=n,!g.index&&g.status!=="loading"&&A({status:"loading"}),n},q=e=>{let t=/<svg\b([^>]*)>([\s\S]*)<\/svg>\s*$/.exec(e.trim());if(!t)return;let n={},r="0 0 24 24";for(let[,o,s]of t[1].matchAll(/([a-zA-Z:-]+)="([^"]*)"/g))o==="viewBox"?r=s:["xmlns","width","height","aria-hidden","role","class","style"].includes(o)||(n[o]=s);return oe({viewBox:r,attrs:n,body:t[2]})},ht=(e,t)=>{let n=V(e,t),r=se.get(n);if(r)return r;let o=fetch(`${Q()}/v${t}/${e}.svg`).then(async s=>{if(!s.ok)throw new Error(`${s.status} for ${e}`);let i=q(await s.text());if(!i)throw new Error(`iconplease: "${e}" is not a valid SVG`);I.set(n,i),Ne(),A()}).catch(Re).finally(()=>{se.delete(n)});return se.set(n,o),o},Te=async(e=!1)=>{var n;if(!$()){let r=(n=ne())!=null?n:"";return fetch(`${te()}/sdk/set?key=${encodeURIComponent(r)}`)}let t=await pt(e);return fetch(`${te()}/sdk/set`,{headers:{Authorization:`Bearer ${t}`}})},yt=async e=>{var s,i;let t=await Te();t.status===401&&$()&&(t=await Te(!0));let n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);let r=new Map,o={};for(let[a,c]of Object.entries((s=n.icons)!=null?s:{})){if(!C.test(a)||typeof(c==null?void 0:c.svg)!="string")continue;let u=q(c.svg);u&&(r.set(a,u),o[a]={version:Number(c.version)||1,svg:c.svg})}if(e===ie){T.clear();for(let[a,c]of r)T.set(a,c);_=Date.now(),O=!0,P=typeof n.version=="number"?n.version:null;try{e!=="token"&&((i=L())==null||i.setItem(Me,JSON.stringify({tag:e,checkedAt:_,version:P,icons:o})))}catch{A();return}A()}},ue=(e={})=>{S();let t=j();if(!t||O&&Date.now()-_<ee()&&!e.force||!e.force&&Date.now()<ce)return Promise.resolve();if(R)return R;let r=yt(t).catch(o=>{O=!0,ce=Date.now()+at,ae||(ae=!0,console.warn(`iconplease: could not load your icon set \u2014 ${o instanceof Error?o.message:String(o)} Falling back to public icons.`)),A()}).finally(()=>{R=void 0});return R=r,r},pe=async e=>{var r,o;if(!C.test(e))return;if(S(),j()){if(E(e)){ue();return}if(await ue(),E(e))return}else if(E(e))return;let t=(r=g.index)==null?void 0:r.icons[e];if(t&&I.has(V(e,t))){de();return}await de();let n=(o=g.index)==null?void 0:o.icons[e];n&&!I.has(V(e,n))&&await ht(e,n)},ge=async(e={})=>{let{icons:t=[],force:n=!1}=Array.isArray(e)?{icons:e}:e;S(),!(D&&!j()&&t.every(o=>E(o)))&&(await Promise.all([D?Promise.resolve():de({force:n}),ue({force:n})]),await Promise.all(t.map(pe)))},_e=e=>(S(),fe.add(e),()=>fe.delete(e));var J=e=>{var r;S();let t=E(e);if(t)return t;let n=(r=g.index)==null?void 0:r.icons[e];return n?I.get(V(e,n)):void 0},De=e=>(S(),E(e)||j()&&!O?!1:g.status==="ready"&&!!g.index&&!(e in g.index.icons));var bt=/^[#a-zA-Z0-9(),.%\s-]{1,64}$/,xt=/[<>"&]/g,wt={"<":"&lt;",">":"&gt;",'"':"&quot;","&":"&amp;"},kt=e=>e.replace(xt,t=>wt[t]),Ce=e=>String(Number(e.toFixed(3))),vt=(e,t)=>e.replace(/\b(fill|stroke)="currentColor"/g,`$1="${t}"`),At=(e,t)=>e.replace(/\bstroke-width="([0-9]*\.?[0-9]+)"/g,(n,r)=>`stroke-width="${Ce(Number(r)*t)}"`),me=(e,t={})=>{var d;let{size:n=24,color:r,strokeScale:o,motion:s,label:i,className:a}=t,c=r&&bt.test(r)?r:void 0,u=typeof o=="number"&&Number.isFinite(o)&&o>0&&o!==1?o:void 0,l={...(d=e.attrs)!=null?d:{}};if(c)for(let f of["fill","stroke"])l[f]==="currentColor"&&(l[f]=c);u&&l["stroke-width"]&&(l["stroke-width"]=Ce(Number(l["stroke-width"])*u));let p=e.body;return c&&(p=vt(p,c)),u&&(p=At(p,u)),l.width=String(n),l.height=String(n),l.viewBox=e.viewBox,s&&s!=="none"&&(l["data-motion"]=s),i?(l.role="img",l["aria-label"]=i):l["aria-hidden"]="true",a&&(l.class=a),{attrs:l,body:p}},he=({attrs:e,body:t})=>`<svg xmlns="http://www.w3.org/2000/svg" ${Object.entries(e).map(([r,o])=>`${r}="${kt(o)}"`).join(" ")}>${t}</svg>`,Le=(e,t={})=>{let n=typeof e=="string"?J(e):e;return n?he(me(n,t)):void 0};var B={draw:{label:"Draw on",hint:"Strokes draw themselves",duration:700,easing:"ease-in-out",draw:!0},fade:{label:"Fade in",hint:"From invisible to visible",duration:400,easing:"ease-out",frames:[{offset:0,opacity:0},{offset:1,opacity:1}]},pop:{label:"Pop in",hint:"Grows from nothing with a little overshoot",duration:450,easing:"spring",frames:[{offset:0,transform:"scale(0)"},{offset:1,transform:"scale(1)"}]},spin:{label:"Spin",hint:"One full turn",duration:800,easing:"ease-in-out",frames:[{offset:0,transform:"rotate(0deg)"},{offset:1,transform:"rotate(360deg)"}]},"slide-up":{label:"Slide up",hint:"Rises into place",duration:450,easing:"ease-out",frames:[{offset:0,transform:"translateY(4px)",opacity:0},{offset:1,transform:"translateY(0px)",opacity:1}]},"slide-down":{label:"Slide down",hint:"Drops into place",duration:450,easing:"ease-out",frames:[{offset:0,transform:"translateY(-4px)",opacity:0},{offset:1,transform:"translateY(0px)",opacity:1}]},"slide-left":{label:"Slide left",hint:"Comes in from the right",duration:450,easing:"ease-out",frames:[{offset:0,transform:"translateX(4px)",opacity:0},{offset:1,transform:"translateX(0px)",opacity:1}]},"slide-right":{label:"Slide right",hint:"Comes in from the left",duration:450,easing:"ease-out",frames:[{offset:0,transform:"translateX(-4px)",opacity:0},{offset:1,transform:"translateX(0px)",opacity:1}]},bounce:{label:"Bounce",hint:"Hops up and lands",duration:700,easing:"ease-out",frames:[{offset:0,transform:"translateY(0px)"},{offset:.35,transform:"translateY(-4px)"},{offset:.65,transform:"translateY(0px)"},{offset:.82,transform:"translateY(-1.5px)"},{offset:1,transform:"translateY(0px)"}]},pulse:{label:"Pulse",hint:"Swells and settles",duration:600,easing:"ease-in-out",frames:[{offset:0,transform:"scale(1)"},{offset:.5,transform:"scale(1.18)"},{offset:1,transform:"scale(1)"}]},follow:{label:"Move along path",hint:"The shape's centre travels along a route you drew",duration:1200,easing:"ease-in-out",route:!0},shake:{label:"Shake",hint:"A quick wobble",duration:600,easing:"ease-in-out",frames:[{offset:0,transform:"rotate(0deg)"},{offset:.2,transform:"rotate(-14deg)"},{offset:.4,transform:"rotate(12deg)"},{offset:.6,transform:"rotate(-8deg)"},{offset:.8,transform:"rotate(4deg)"},{offset:1,transform:"rotate(0deg)"}]}},St=Object.keys(B).filter(e=>!B[e].route),Et=/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]{1,8000}$/,Ge={linear:{label:"Linear",css:"linear"},"ease-in":{label:"Ease in",css:"cubic-bezier(0.4, 0, 1, 1)"},"ease-out":{label:"Ease out",css:"cubic-bezier(0, 0, 0.2, 1)"},"ease-in-out":{label:"Ease in-out",css:"cubic-bezier(0.4, 0, 0.2, 1)"},spring:{label:"Spring",css:"cubic-bezier(0.34, 1.56, 0.64, 1)"}},It={load:"When it appears",hover:"On hover",click:"On click",visible:"When scrolled into view"},Tt=64,ye=1e4,ze=50,Ot=new Set(St),je=/^[A-Za-z0-9_-]{1,64}$/,be=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)?Math.round(Math.min(Math.max(e,t),n)):void 0,Pt=e=>{var r;if(!e||typeof e!="object")return;let t=e,n=[];for(let o of Array.isArray(t.clips)?t.clips.slice(0,Tt):[]){if(!o||typeof o!="object")continue;let s=be(o.start,0,ye),i=be(o.duration,ze,ye);if(typeof o.id!="string"||!je.test(o.id)||typeof o.target!="string"||!je.test(o.target)||!Ot.has(o.preset)||s===void 0||i===void 0)continue;let a=B[o.preset].route;a&&(typeof o.path!="string"||!Et.test(o.path)||!/^\s*[Mm]/.test(o.path))||n.push({id:o.id,target:o.target,preset:o.preset,start:s,duration:i,easing:o.easing&&o.easing in Ge?o.easing:B[o.preset].easing,...a?{path:o.path,orient:o.orient===!0}:{}})}if(n.length)return{version:1,trigger:t.trigger&&t.trigger in It?t.trigger:"load",loop:t.loop===!0,loopGap:(r=be(t.loopGap,0,ye))!=null?r:0,clips:n}},we="data-ip-animation",Ke="data-ip";var Mt=e=>atob(e.replace(/-/g,"+").replace(/_/g,"/"));var Ue=e=>{if(!(!e||e.length>6e4||!/^[A-Za-z0-9_-]+$/.test(e)))try{return Pt(JSON.parse(Mt(e)))}catch{return}},$t=e=>e.clips.reduce((t,n)=>Math.max(t,n.start+n.duration),0),Nt="path, line, rect, ellipse, circle, polyline, polygon",Rt=e=>[...e.querySelectorAll(Nt)].filter(t=>{var r;if(t.closest("defs, clipPath, mask"))return!1;let n=(r=t.getAttribute("stroke"))!=null?r:getComputedStyle(t).stroke;return!!n&&n!=="none"&&n!=="transparent"&&typeof t.getTotalLength=="function"}),_t="http://www.w3.org/2000/svg",xe=48,Dt=(e,t,n)=>{var s;let r=(s=e.ownerSVGElement)!=null?s:e.closest("svg");if(!r||typeof e.getBBox!="function")return[];let o=document.createElementNS(_t,"path");o.setAttribute("d",t),o.setAttribute("visibility","hidden"),r.appendChild(o);try{let i=o.getTotalLength(),a=e.getBBox(),c=a.x+a.width/2,u=a.y+a.height/2,l=h=>o.getPointAtLength(Math.min(Math.max(h,0),i)),p=h=>{let m=Math.max(i/400,.01),b=l(h-m),y=l(h+m);return Math.atan2(y.y-b.y,y.x-b.x)*180/Math.PI},d=p(0),f=0;return Array.from({length:xe+1},(h,m)=>{let b=m/xe*i,y=l(b),x=p(b)-d;for(;x-f>180;)x-=360;for(;x-f<-180;)x+=360;f=x;let G=`translate(${(y.x-c).toFixed(3)}px, ${(y.y-u).toFixed(3)}px)`;return{offset:m/xe,transform:n?`${G} rotate(${x.toFixed(2)}deg)`:G}})}finally{o.remove()}},Be=(e,t,n,r)=>{let o=t.start/n,s=(t.start+t.duration)/n,i=Ge[t.easing].css,a=e.map((p,d)=>({...p,offset:o+p.offset*(s-o),easing:d<e.length-1?i:"linear"})),c={...r!=null?r:e[0],offset:0,easing:"linear"},u={...e[e.length-1],offset:1,easing:"linear"},l=[];return a[0].offset>0&&(l.push(c),r&&l.push({...r,offset:a[0].offset,easing:"linear"})),l.push(...a),a[a.length-1].offset<1&&l.push(u),l},Fe=(e,t,n={})=>{var u,l,p;let r=Math.max($t(e),ze),o=(u=n.loop)!=null?u:e.loop,s=o?r+e.loopGap:r,i=[],a={duration:s,iterations:o?1/0:1,fill:"both"};for(let d of e.clips){let f=B[d.preset],h=e.clips.some(m=>m.target===d.target&&m.start<d.start);for(let m of t(d.target)){if(f.draw){for(let w of Rt(m)){let v=Math.max(w.getTotalLength(),.01),Ze=[{offset:0,strokeDasharray:`${v} ${v}`,strokeDashoffset:v},{offset:1,strokeDasharray:`${v} ${v}`,strokeDashoffset:0}],Qe=h?{offset:0,strokeDasharray:`${v} ${v}`,strokeDashoffset:0}:void 0;i.push(w.animate(Be(Ze,d,s,Qe),a))}continue}let b=m;b.style.transformBox="fill-box",b.style.transformOrigin="center";let y=f.route?Dt(m,(l=d.path)!=null?l:"",d.orient===!0):((p=f.frames)!=null?p:[]).map(w=>({...w}));if(!y.length)continue;let x=y.some(w=>w.transform!==void 0),G=y.some(w=>w.opacity!==void 0),We=h?{offset:0,...x?{transform:"translate(0px, 0px)"}:{},...G?{opacity:1}:{}}:void 0;i.push(b.animate(Be(y,d,s,We),{...a,composite:x?"add":"replace"}))}}let c=d=>i.forEach(d);return n.paused&&c(d=>d.pause()),{play:()=>c(d=>d.play()),pause:()=>c(d=>d.pause()),seek:d=>c(f=>f.currentTime=Math.max(0,d)),cancel:()=>c(d=>d.cancel()),period:s,animations:i}};var H=new WeakMap,Ct=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,Ve=e=>{var t,n;return(n=(t=e.closest("a, button, [role=button], label, summary"))!=null?t:e.parentElement)!=null?n:e},X=(e,t={})=>{var l,p,d;(l=H.get(e))==null||l();let n=Ue(e.getAttribute(we));if(!n||typeof e.animate!="function")return()=>{};if((p=t.reducedMotion)!=null?p:Ct())return()=>{};let r=(d=t.trigger)!=null?d:n.trigger,o=f=>[...e.querySelectorAll(`[${Ke}="${f}"]`)],s,i=[],a=()=>{s==null||s.cancel(),s=void 0},c=()=>{a(),s=Fe(n,o)};if(r==="load"&&c(),r==="hover"){let f=Ve(e);f.addEventListener("pointerenter",c),f.addEventListener("pointerleave",a),f.addEventListener("focusin",c),f.addEventListener("focusout",a),i.push(()=>{f.removeEventListener("pointerenter",c),f.removeEventListener("pointerleave",a),f.removeEventListener("focusin",c),f.removeEventListener("focusout",a)})}if(r==="click"){let f=Ve(e);f.addEventListener("click",c),i.push(()=>f.removeEventListener("click",c))}if(r==="visible")if(typeof IntersectionObserver=="function"){let f=new IntersectionObserver(h=>{h.some(m=>m.isIntersecting)&&(f.disconnect(),c())},{threshold:.5});f.observe(e),i.push(()=>f.disconnect())}else c();let u=()=>{a(),i.forEach(f=>f()),H.delete(e)};return H.set(e,u),u},Ye=(e=document)=>{e.querySelectorAll(`svg[${we}]`).forEach(t=>{H.has(t)||X(t)})};var qe="[data-icon], i.ip[class*='ip-']",Lt=new Set(["none","wiggle","pop","bounce","draw"]),Je=new Set,jt=e=>{let t=e.getAttribute("data-icon");if(t)return t;for(let n of Array.from(e.classList))if(n.startsWith("ip-")&&n.length>3)return n.slice(3)},He=e=>{if(e===null)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},ke=e=>{var c,u,l,p;let t=jt(e);if(!t)return;let n=J(t),r=e.getAttribute("data-motion"),o=r&&Lt.has(r)?r:void 0,s={size:(c=He(e.getAttribute("data-size")))!=null?c:24,color:(u=e.getAttribute("data-color"))!=null?u:void 0,strokeScale:He(e.getAttribute("data-stroke")),motion:o,label:(l=e.getAttribute("data-label"))!=null?l:void 0},i=JSON.stringify([t,s,n?"1":"0"]);if(e.getAttribute("data-ip-rendered")===i)return;if(!n){De(t)?Je.has(t)||(Je.add(t),console.warn(`iconplease: no icon named "${t}".`)):pe(t);return}e.innerHTML=he(me(n,s)),e.setAttribute("data-ip-rendered",i);let a=e.querySelector("svg");a&&X(a),e.tagName==="I"&&((p=e.style).display||(p.display="inline-flex"))},W=(e=document)=>{e instanceof Element&&e.matches(qe)&&ke(e),e.querySelectorAll(qe).forEach(ke)},Xe=()=>{let e=window.iconpleaseConfig;e&&Z(e),_e(()=>W()),W(),ge(),new MutationObserver(t=>{for(let n of t)n.type==="attributes"&&n.target instanceof Element&&ke(n.target),n.addedNodes.forEach(r=>{r instanceof Element&&W(r)})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-icon","data-size","data-color","data-stroke","data-motion","data-label","class"]})};window.iconplease={init:Z,load:ge,renderSVG:Le,attachAnimation:X,attachAll:Ye,refresh:()=>W()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Xe,{once:!0}):Xe();})();
package/dist/index.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export { init, getConfig } from "./config.js";
2
- export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown } from "./store.js";
2
+ export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown, bundledIcon } from "./store.js";
3
3
  export { renderSVG, prepare } from "./render.js";
4
+ export { attachAnimation, attachAll } from "./player.js";
5
+ export { decodeAnimation, encodeAnimation, cleanAnimation, PRESETS } from "./animation.js";
6
+ export type { IconAnimation, AnimationClip, AnimationPreset, AnimationTrigger } from "./animation.js";
4
7
  export type { RenderOptions, Prepared } from "./render.js";
5
8
  export type { LoadOptions } from "./store.js";
6
- export type { Config, IconData, IconIndex, IconMotion, Status } from "./types.js";
9
+ export type { Config, IconData, IconIndex, IconMotion, Status, BundledSet, BundledIcon, TokenSource } from "./types.js";
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  export { init, getConfig } from "./config.js";
2
- export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown } from "./store.js";
2
+ export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown, bundledIcon } from "./store.js";
3
3
  export { renderSVG, prepare } from "./render.js";
4
+ export { attachAnimation, attachAll } from "./player.js";
5
+ export { decodeAnimation, encodeAnimation, cleanAnimation, PRESETS } from "./animation.js";
@@ -0,0 +1,7 @@
1
+ import { type IconAnimation } from "./animation.js";
2
+ export type AttachOptions = {
3
+ trigger?: IconAnimation["trigger"];
4
+ reducedMotion?: boolean;
5
+ };
6
+ export declare const attachAnimation: (svg: Element, options?: AttachOptions) => (() => void);
7
+ export declare const attachAll: (root?: ParentNode) => void;
package/dist/player.js ADDED
@@ -0,0 +1,72 @@
1
+ import { ANIMATION_ATTRIBUTE, MARKER_ATTRIBUTE, animate, decodeAnimation } from "./animation.js";
2
+ const attached = new WeakMap();
3
+ const prefersReduced = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
4
+ const hoverHost = (svg) => svg.closest("a, button, [role=button], label, summary") ?? svg.parentElement ?? svg;
5
+ export const attachAnimation = (svg, options = {}) => {
6
+ attached.get(svg)?.();
7
+ const animation = decodeAnimation(svg.getAttribute(ANIMATION_ATTRIBUTE));
8
+ if (!animation || typeof svg.animate !== "function")
9
+ return () => { };
10
+ if (options.reducedMotion ?? prefersReduced())
11
+ return () => { };
12
+ const trigger = options.trigger ?? animation.trigger;
13
+ const targets = (marker) => [...svg.querySelectorAll(`[${MARKER_ATTRIBUTE}="${marker}"]`)];
14
+ let playback;
15
+ const cleanups = [];
16
+ const stop = () => {
17
+ playback?.cancel();
18
+ playback = undefined;
19
+ };
20
+ const start = () => {
21
+ stop();
22
+ playback = animate(animation, targets);
23
+ };
24
+ if (trigger === "load")
25
+ start();
26
+ if (trigger === "hover") {
27
+ const host = hoverHost(svg);
28
+ host.addEventListener("pointerenter", start);
29
+ host.addEventListener("pointerleave", stop);
30
+ host.addEventListener("focusin", start);
31
+ host.addEventListener("focusout", stop);
32
+ cleanups.push(() => {
33
+ host.removeEventListener("pointerenter", start);
34
+ host.removeEventListener("pointerleave", stop);
35
+ host.removeEventListener("focusin", start);
36
+ host.removeEventListener("focusout", stop);
37
+ });
38
+ }
39
+ if (trigger === "click") {
40
+ const host = hoverHost(svg);
41
+ host.addEventListener("click", start);
42
+ cleanups.push(() => host.removeEventListener("click", start));
43
+ }
44
+ if (trigger === "visible") {
45
+ if (typeof IntersectionObserver === "function") {
46
+ const observer = new IntersectionObserver((entries) => {
47
+ if (!entries.some((entry) => entry.isIntersecting))
48
+ return;
49
+ observer.disconnect();
50
+ start();
51
+ }, { threshold: 0.5 });
52
+ observer.observe(svg);
53
+ cleanups.push(() => observer.disconnect());
54
+ }
55
+ else {
56
+ start();
57
+ }
58
+ }
59
+ const detach = () => {
60
+ stop();
61
+ cleanups.forEach((cleanup) => cleanup());
62
+ attached.delete(svg);
63
+ };
64
+ attached.set(svg, detach);
65
+ return detach;
66
+ };
67
+ export const attachAll = (root = document) => {
68
+ root.querySelectorAll(`svg[${ANIMATION_ATTRIBUTE}]`).forEach((svg) => {
69
+ if (!attached.has(svg))
70
+ attachAnimation(svg);
71
+ });
72
+ };
package/dist/react.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useEffect, useSyncExternalStore } from "react";
2
+ import { useEffect, useRef, useSyncExternalStore } from "react";
3
+ import { attachAnimation } from "./player.js";
3
4
  import { prepare } from "./render.js";
4
- import { getIcon, getSnapshot, isUnknown, requestIcon, subscribe } from "./store.js";
5
+ import { bundledIcon, getIcon, getSnapshot, isUnknown, requestIcon, subscribe } from "./store.js";
5
6
  const serverSnapshot = { status: "idle", revision: 0 };
6
7
  const getServerSnapshot = () => serverSnapshot;
7
8
  const REACT_NAMES = {
@@ -20,10 +21,11 @@ const toProps = (attrs) => Object.fromEntries(Object.entries(attrs).map(([name,
20
21
  const warned = new Set();
21
22
  export const Iconplease = ({ icon, size = 24, className, label, ...options }) => {
22
23
  const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
24
+ const ref = useRef(null);
23
25
  useEffect(() => {
24
26
  void requestIcon(icon);
25
27
  }, [icon]);
26
- const data = state === serverSnapshot ? undefined : getIcon(icon);
28
+ const data = state === serverSnapshot ? bundledIcon(icon) : getIcon(icon);
27
29
  if (!data) {
28
30
  if (state !== serverSnapshot && isUnknown(icon) && !warned.has(icon)) {
29
31
  warned.add(icon);
@@ -32,6 +34,13 @@ export const Iconplease = ({ icon, size = 24, className, label, ...options }) =>
32
34
  return (_jsx("svg", { width: size, height: size, viewBox: "0 0 24 24", "aria-hidden": label ? undefined : true, role: label ? "img" : undefined, "aria-label": label, className: className, "data-iconplease-pending": "" }));
33
35
  }
34
36
  const { attrs, body } = prepare(data, { size, className, label, ...options });
35
- return _jsx("svg", { xmlns: "http://www.w3.org/2000/svg", ...toProps(attrs), dangerouslySetInnerHTML: { __html: body } });
37
+ return _jsx(Animated, { attrs: attrs, body: body, svgRef: ref });
38
+ };
39
+ const Animated = ({ attrs, body, svgRef }) => {
40
+ useEffect(() => {
41
+ const svg = svgRef.current;
42
+ return svg ? attachAnimation(svg) : undefined;
43
+ }, [body, attrs["data-ip-animation"], svgRef]);
44
+ return _jsx("svg", { ref: svgRef, xmlns: "http://www.w3.org/2000/svg", ...toProps(attrs), dangerouslySetInnerHTML: { __html: body } });
36
45
  };
37
46
  export default Iconplease;
package/dist/script.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { init } from "./config.js";
2
2
  import { load, requestIcon, subscribe, getIcon, isUnknown } from "./store.js";
3
3
  import { prepare, renderSVG, toMarkup } from "./render.js";
4
+ import { attachAll, attachAnimation } from "./player.js";
4
5
  const SELECTOR = "[data-icon], i.ip[class*='ip-']";
5
6
  const MOTIONS = new Set(["none", "wiggle", "pop", "bounce", "draw"]);
6
7
  const warned = new Set();
@@ -51,6 +52,9 @@ const paint = (element) => {
51
52
  }
52
53
  element.innerHTML = toMarkup(prepare(icon, options));
53
54
  element.setAttribute("data-ip-rendered", key);
55
+ const svg = element.querySelector("svg");
56
+ if (svg)
57
+ attachAnimation(svg);
54
58
  if (element.tagName === "I")
55
59
  (_a = element.style).display || (_a.display = "inline-flex");
56
60
  };
@@ -82,7 +86,7 @@ const start = () => {
82
86
  attributeFilter: ["data-icon", "data-size", "data-color", "data-stroke", "data-motion", "data-label", "class"],
83
87
  });
84
88
  };
85
- window.iconplease = { init, load, renderSVG, refresh: () => paintAll() };
89
+ window.iconplease = { init, load, renderSVG, attachAnimation, attachAll, refresh: () => paintAll() };
86
90
  if (document.readyState === "loading")
87
91
  document.addEventListener("DOMContentLoaded", start, { once: true });
88
92
  else
package/dist/store.d.ts CHANGED
@@ -4,6 +4,7 @@ export type State = {
4
4
  index?: IconIndex;
5
5
  revision: number;
6
6
  };
7
+ export declare const bundledIcon: (name: string) => IconData | undefined;
7
8
  export declare const loadIndex: (options?: {
8
9
  force?: boolean;
9
10
  }) => Promise<void>;
package/dist/store.js CHANGED
@@ -1,4 +1,4 @@
1
- import { apiBase, apiKey, cdnBase, revalidateMs } from "./config.js";
1
+ import { apiBase, apiKey, bundledSet, cdnBase, revalidateMs, tokenSource } from "./config.js";
2
2
  import { cleanIcon } from "./sanitize.js";
3
3
  const INDEX_KEY = "iconplease:index:v2";
4
4
  const ICONS_KEY = "iconplease:icons:v2";
@@ -19,6 +19,45 @@ let setLoaded = false;
19
19
  let setInflight;
20
20
  let warnedSet = false;
21
21
  const iconInflight = new Map();
22
+ let liveVersion = null;
23
+ let setRetryAt = 0;
24
+ const SET_RETRY_MS = 60000;
25
+ let appliedBundle;
26
+ let bundleVersion = null;
27
+ const bundleOwn = new Map();
28
+ const bundlePublic = new Map();
29
+ const syncBundle = () => {
30
+ const bundle = bundledSet();
31
+ if (bundle === appliedBundle)
32
+ return;
33
+ appliedBundle = bundle;
34
+ bundleOwn.clear();
35
+ bundlePublic.clear();
36
+ bundleVersion = null;
37
+ if (!bundle || bundle.format !== 1 || typeof bundle.icons !== "object")
38
+ return;
39
+ bundleVersion = typeof bundle.version === "number" ? bundle.version : null;
40
+ for (const [name, entry] of Object.entries(bundle.icons)) {
41
+ if (!NAME.test(name) || typeof entry?.svg !== "string")
42
+ continue;
43
+ const icon = parseSVG(entry.svg);
44
+ if (!icon)
45
+ continue;
46
+ (entry.source === "public" ? bundlePublic : bundleOwn).set(name, icon);
47
+ }
48
+ };
49
+ const liveWins = () => liveVersion !== null && (bundleVersion === null || liveVersion > bundleVersion);
50
+ const ownIcon = (name) => {
51
+ if (!appliedBundle)
52
+ return setIcons.get(name);
53
+ if (liveWins())
54
+ return setIcons.get(name) ?? bundlePublic.get(name);
55
+ return bundleOwn.get(name) ?? bundlePublic.get(name);
56
+ };
57
+ export const bundledIcon = (name) => {
58
+ syncBundle();
59
+ return bundleOwn.get(name) ?? bundlePublic.get(name);
60
+ };
22
61
  const listeners = new Set();
23
62
  const storage = () => {
24
63
  try {
@@ -45,9 +84,41 @@ const cleanIndex = (raw) => {
45
84
  return { format: 2, hash: data.hash, icons: Object.fromEntries(entries) };
46
85
  };
47
86
  const keyTag = (key) => key.slice(0, 14);
48
- const syncSetKey = () => {
87
+ const sourceTag = () => {
88
+ if (tokenSource())
89
+ return "token";
49
90
  const key = apiKey();
50
- const tag = key ? keyTag(key) : undefined;
91
+ return key ? keyTag(key) : undefined;
92
+ };
93
+ const TOKEN_MARGIN_MS = 60000;
94
+ const DEFAULT_TOKEN_MS = 9 * 60000;
95
+ let cachedToken;
96
+ let tokenInflight;
97
+ const freshToken = (force = false) => {
98
+ const source = tokenSource();
99
+ if (!source)
100
+ return Promise.reject(new Error("no token source"));
101
+ if (!force && cachedToken && cachedToken.expiresAt - TOKEN_MARGIN_MS > Date.now())
102
+ return Promise.resolve(cachedToken.token);
103
+ if (tokenInflight)
104
+ return tokenInflight;
105
+ tokenInflight = source()
106
+ .then((answer) => {
107
+ const token = typeof answer === "string" ? answer : answer?.token;
108
+ if (typeof token !== "string" || !token.startsWith("ipt_"))
109
+ throw new Error("your token function did not return an iconplease token (ipt_…).");
110
+ const raw = typeof answer === "string" ? undefined : answer.expiresAt;
111
+ const at = typeof raw === "number" ? raw : raw ? Date.parse(raw) : NaN;
112
+ cachedToken = { token, expiresAt: Number.isFinite(at) ? at : Date.now() + DEFAULT_TOKEN_MS };
113
+ return token;
114
+ })
115
+ .finally(() => {
116
+ tokenInflight = undefined;
117
+ });
118
+ return tokenInflight;
119
+ };
120
+ const syncSetKey = () => {
121
+ const tag = sourceTag();
51
122
  if (tag === setFor)
52
123
  return;
53
124
  setFor = tag;
@@ -56,9 +127,13 @@ const syncSetKey = () => {
56
127
  setLoaded = false;
57
128
  setInflight = undefined;
58
129
  warnedSet = false;
130
+ liveVersion = null;
131
+ setRetryAt = 0;
59
132
  if (!tag)
60
133
  return;
61
134
  try {
135
+ if (tag === "token")
136
+ return;
62
137
  const cached = JSON.parse(storage()?.getItem(SET_KEY) ?? "null");
63
138
  if (!cached || cached.tag !== tag)
64
139
  return;
@@ -68,6 +143,7 @@ const syncSetKey = () => {
68
143
  setIcons.set(name, icon);
69
144
  }
70
145
  setCheckedAt = typeof cached.checkedAt === "number" ? cached.checkedAt : 0;
146
+ liveVersion = typeof cached.version === "number" ? cached.version : null;
71
147
  setLoaded = true;
72
148
  }
73
149
  catch {
@@ -75,6 +151,7 @@ const syncSetKey = () => {
75
151
  }
76
152
  };
77
153
  const hydrate = () => {
154
+ syncBundle();
78
155
  syncSetKey();
79
156
  if (hydrated)
80
157
  return;
@@ -222,8 +299,18 @@ const fetchIcon = (name, version) => {
222
299
  iconInflight.set(key, request);
223
300
  return request;
224
301
  };
225
- const fetchSet = async (key) => {
226
- const response = await fetch(`${apiBase()}/sdk/set?key=${encodeURIComponent(key)}`);
302
+ const requestSet = async (force = false) => {
303
+ if (!tokenSource()) {
304
+ const key = apiKey() ?? "";
305
+ return fetch(`${apiBase()}/sdk/set?key=${encodeURIComponent(key)}`);
306
+ }
307
+ const token = await freshToken(force);
308
+ return fetch(`${apiBase()}/sdk/set`, { headers: { Authorization: `Bearer ${token}` } });
309
+ };
310
+ const fetchSet = async (tag) => {
311
+ let response = await requestSet();
312
+ if (response.status === 401 && tokenSource())
313
+ response = await requestSet(true);
227
314
  const body = (await response.json().catch(() => ({})));
228
315
  if (!response.ok)
229
316
  throw new Error(body.error || `HTTP ${response.status}`);
@@ -238,15 +325,17 @@ const fetchSet = async (key) => {
238
325
  next.set(name, icon);
239
326
  raw[name] = { version: Number(entry.version) || 1, svg: entry.svg };
240
327
  }
241
- if (keyTag(key) !== setFor)
328
+ if (tag !== setFor)
242
329
  return;
243
330
  setIcons.clear();
244
331
  for (const [name, icon] of next)
245
332
  setIcons.set(name, icon);
246
333
  setCheckedAt = Date.now();
247
334
  setLoaded = true;
335
+ liveVersion = typeof body.version === "number" ? body.version : null;
248
336
  try {
249
- storage()?.setItem(SET_KEY, JSON.stringify({ tag: keyTag(key), checkedAt: setCheckedAt, icons: raw }));
337
+ if (tag !== "token")
338
+ storage()?.setItem(SET_KEY, JSON.stringify({ tag, checkedAt: setCheckedAt, version: liveVersion, icons: raw }));
250
339
  }
251
340
  catch {
252
341
  notify();
@@ -256,17 +345,20 @@ const fetchSet = async (key) => {
256
345
  };
257
346
  export const loadSet = (options = {}) => {
258
347
  hydrate();
259
- const key = apiKey();
260
- if (!key)
348
+ const tag = sourceTag();
349
+ if (!tag)
261
350
  return Promise.resolve();
262
351
  const fresh = setLoaded && Date.now() - setCheckedAt < revalidateMs();
263
352
  if (fresh && !options.force)
264
353
  return Promise.resolve();
354
+ if (!options.force && Date.now() < setRetryAt)
355
+ return Promise.resolve();
265
356
  if (setInflight)
266
357
  return setInflight;
267
- const pending = fetchSet(key)
358
+ const pending = fetchSet(tag)
268
359
  .catch((error) => {
269
360
  setLoaded = true;
361
+ setRetryAt = Date.now() + SET_RETRY_MS;
270
362
  if (!warnedSet) {
271
363
  warnedSet = true;
272
364
  console.warn(`iconplease: could not load your icon set — ${error instanceof Error ? error.message : String(error)} Falling back to public icons.`);
@@ -283,15 +375,18 @@ export const requestIcon = async (name) => {
283
375
  if (!NAME.test(name))
284
376
  return;
285
377
  hydrate();
286
- if (apiKey()) {
287
- if (setIcons.has(name)) {
378
+ if (sourceTag()) {
379
+ if (ownIcon(name)) {
288
380
  void loadSet();
289
381
  return;
290
382
  }
291
383
  await loadSet();
292
- if (setIcons.has(name))
384
+ if (ownIcon(name))
293
385
  return;
294
386
  }
387
+ else if (ownIcon(name)) {
388
+ return;
389
+ }
295
390
  const known = state.index?.icons[name];
296
391
  if (known && icons.has(keyOf(name, known))) {
297
392
  void loadIndex();
@@ -304,7 +399,11 @@ export const requestIcon = async (name) => {
304
399
  };
305
400
  export const load = async (options = {}) => {
306
401
  const { icons: names = [], force = false } = Array.isArray(options) ? { icons: options } : options;
307
- await Promise.all([loadIndex({ force }), loadSet({ force })]);
402
+ hydrate();
403
+ const bundledOnly = appliedBundle && !sourceTag() && names.every((name) => ownIcon(name));
404
+ if (bundledOnly)
405
+ return;
406
+ await Promise.all([appliedBundle ? Promise.resolve() : loadIndex({ force }), loadSet({ force })]);
308
407
  await Promise.all(names.map(requestIcon));
309
408
  };
310
409
  export const subscribe = (listener) => {
@@ -319,7 +418,7 @@ export const getSnapshot = () => {
319
418
  export const getStatus = () => getSnapshot().status;
320
419
  export const getIcon = (name) => {
321
420
  hydrate();
322
- const own = setIcons.get(name);
421
+ const own = ownIcon(name);
323
422
  if (own)
324
423
  return own;
325
424
  const version = state.index?.icons[name];
@@ -327,17 +426,19 @@ export const getIcon = (name) => {
327
426
  };
328
427
  export const isUnknown = (name) => {
329
428
  hydrate();
330
- if (setIcons.has(name))
429
+ if (ownIcon(name))
331
430
  return false;
332
- if (apiKey() && !setLoaded)
431
+ if (sourceTag() && !setLoaded)
333
432
  return false;
334
433
  return state.status === "ready" && !!state.index && !(name in state.index.icons);
335
434
  };
336
435
  export const setIconNames = () => {
337
436
  hydrate();
338
- return [...setIcons.keys()];
437
+ if (!appliedBundle)
438
+ return [...setIcons.keys()];
439
+ return liveWins() ? [...setIcons.keys()] : [...bundleOwn.keys()];
339
440
  };
340
- export const iconNames = () => [...new Set([...setIconNames(), ...Object.keys(getSnapshot().index?.icons ?? {})])];
441
+ export const iconNames = () => [...new Set([...setIconNames(), ...bundlePublic.keys(), ...Object.keys(getSnapshot().index?.icons ?? {})])];
341
442
  export const resetForTests = () => {
342
443
  state = { status: "idle", revision: 0 };
343
444
  checkedAt = 0;
@@ -352,6 +453,14 @@ export const resetForTests = () => {
352
453
  setLoaded = false;
353
454
  setInflight = undefined;
354
455
  warnedSet = false;
456
+ cachedToken = undefined;
457
+ tokenInflight = undefined;
458
+ liveVersion = null;
459
+ setRetryAt = 0;
460
+ appliedBundle = undefined;
461
+ bundleVersion = null;
462
+ bundleOwn.clear();
463
+ bundlePublic.clear();
355
464
  if (persistTimer)
356
465
  clearTimeout(persistTimer);
357
466
  persistTimer = undefined;
package/dist/types.d.ts CHANGED
@@ -20,5 +20,25 @@ export type Config = {
20
20
  apiUrl?: string;
21
21
  revalidate?: number;
22
22
  apiKey?: string;
23
+ token?: TokenSource;
24
+ set?: BundledSet;
23
25
  };
26
+ export type BundledIcon = {
27
+ version: number;
28
+ svg: string;
29
+ source: "set" | "public";
30
+ };
31
+ export type BundledSet = {
32
+ format: 1;
33
+ version: number | null;
34
+ workspace?: {
35
+ id: string;
36
+ name: string;
37
+ } | null;
38
+ icons: Record<string, BundledIcon>;
39
+ };
40
+ export type TokenSource = () => Promise<string | {
41
+ token: string;
42
+ expiresAt?: string | number;
43
+ }>;
24
44
  export type Status = "idle" | "loading" | "ready" | "error";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "iconplease",
3
- "version": "0.2.0",
4
- "description": "Icons you can draw yourself. The catalogue loads once from the iconplease CDN and is cached in the browser.",
3
+ "version": "0.4.0",
4
+ "description": "Icons you can draw yourself. Pages load only the icons they show from the iconplease CDN; private sets via a key, a token or a build-time file.",
5
5
  "keywords": [
6
6
  "icons",
7
7
  "icon",
@@ -34,6 +34,7 @@
34
34
  },
35
35
  "files": [
36
36
  "dist",
37
+ "bin",
37
38
  "README.md"
38
39
  ],
39
40
  "engines": {
@@ -61,5 +62,8 @@
61
62
  "react": "^19.3.0",
62
63
  "react-dom": "^19.3.0",
63
64
  "typescript": "^5.8.3"
65
+ },
66
+ "bin": {
67
+ "iconplease": "./bin/iconplease.mjs"
64
68
  }
65
69
  }