@patrick91/stickers 0.0.0-stage → 0.2.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1
4
+
5
+ - Die-cut outlines follow the artwork smoothly. Before, the white border bumped out and in along its edge, most visibly on large stickers and long, thin ones.
6
+ - Long, thin stickers get as fine an outline as other stickers, rather than a few rows of large steps.
7
+
8
+ ## 0.2.0
9
+
10
+ The first release on npm.
11
+
12
+ - One WebGL2 engine with adapters for plain JavaScript (`@patrick91/stickers`), Web Components (`@patrick91/stickers/web-components`), React (`@patrick91/stickers/react`) and Svelte (`@patrick91/stickers/svelte`).
13
+ - 14 finishes, contour, circle, rectangle and rounded cuts, filled holes, remembered positions, an exploded view, and a `mirror` finish that can reflect a frame you supply.
14
+ - Stickers cut the same way from the same image file share one outline and one set of textures.
15
+ - `mountSticker()` and every adapter build outlines a few at a time between frames, artwork on screen first, so a page full of stickers doesn't freeze while it loads.
16
+ - `<peel-sticker>` accepts its `img` inside a `picture`, to serve AVIF or WebP with a fallback.
17
+
18
+ **Coming from 0.1**, a version that was only shared as a packed file: import the React components from `@patrick91/stickers/react`. The package root now exports the framework-free API and the shared types.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Arminio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,280 @@
1
- # Temporary Holding Version
1
+ # @patrick91/stickers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Peelable, draggable stickers for the web. One WebGL2 engine, with adapters for Web Components, React, and Svelte. Each adapter keeps ordinary image markup in the layout, including when JavaScript or WebGL2 is unavailable.
4
+
5
+ Try it at [stickers.patrick.wtf](https://stickers.patrick.wtf), and tune a sticker and copy its code in the [sticker lab](https://stickers.patrick.wtf/lab/).
6
+
7
+ ```sh
8
+ npm install @patrick91/stickers
9
+ ```
10
+
11
+ The package is ESM only and ships TypeScript declarations. Use TypeScript's `bundler`, `node16`, or `nodenext` module resolution. Bare package imports in the HTML examples need a bundler or an import map. The demo artwork isn't included in the package.
12
+
13
+ Stickers need WebGL2: Chrome and Edge 56, Firefox 51, or Safari 15 and later. Without it, and until the script runs, the artwork stays an ordinary image in the page.
14
+
15
+ ## Choose an integration
16
+
17
+ | Import | Use it for | Needs |
18
+ |---|---|---|
19
+ | `@patrick91/stickers` | Adding stickers to existing images, or controlling the renderer directly | No framework |
20
+ | `@patrick91/stickers/web-components` | Reusable HTML elements, with plain image fallback before registration | No framework |
21
+ | `@patrick91/stickers/react` | React components and a context hook | React 18.3 or 19 |
22
+ | `@patrick91/stickers/svelte` | Native Svelte components and a context store | Svelte 5 |
23
+
24
+ Framework peers are optional; only install the one you use.
25
+
26
+ ### Plain JavaScript
27
+
28
+ ```html
29
+ <img id="planet" src="/art/planet.png" width="150" alt="Ringed planet">
30
+
31
+ <script type="module">
32
+ import { createStickerEngine, mountSticker } from '@patrick91/stickers';
33
+
34
+ const engine = createStickerEngine({ persist: 'page-stickers' });
35
+ const dispose = mountSticker(engine, document.querySelector('#planet'), {
36
+ id: 'planet',
37
+ finish: 'holo',
38
+ });
39
+
40
+ // On unmount in a single-page app:
41
+ // dispose();
42
+ // engine?.destroy();
43
+ </script>
44
+ ```
45
+
46
+ `createStickerEngine()` returns `null` outside the browser or when WebGL2 cannot initialize. `mountSticker()` waits for the image to load, uses it as the layout anchor by default, and returns a cleanup function. It builds outlines a few at a time between frames, artwork on screen first, so a page full of stickers doesn't freeze while it loads; each image stays visible until its sticker takes over. Set an explicit `anchor` or `width` in its options when you need to control layout or texture size. For loaded images, canvases, or bitmaps without an existing image element, use the lower-level `StickerEngine.add()` API.
47
+
48
+ ### Web Components
49
+
50
+ ```html
51
+ <script type="module">
52
+ import { defineStickerElements } from '@patrick91/stickers/web-components';
53
+ defineStickerElements();
54
+ </script>
55
+
56
+ <peel-sticker-provider persist="page-stickers">
57
+ <peel-sticker sticker-id="planet" rotate="-6" finish="holo">
58
+ <img src="/art/planet.png" width="150" height="120" alt="Ringed planet">
59
+ </peel-sticker>
60
+ </peel-sticker-provider>
61
+ ```
62
+
63
+ Registration is explicit, safe to import in SSR, and idempotent. Put an ordinary `img` directly in each `peel-sticker` and use its `width`, `height`, `alt`, and `crossorigin` attributes as usual. To offer the artwork in more than one format, such as AVIF with a PNG fallback, wrap the `img` in a `picture`; the sticker uses whichever source the browser picks. The element's own styles only reach an `img` that is its direct child, so give an `img` inside a `picture` `display: block; width: 100%; height: auto` yourself, and `transform: rotate(var(--peel-rotation))` to match `rotate` before the sticker loads. The wrapper accepts `sticker-id`, `rotate`, `finish` (named finishes), `cut`, `border`, and the boolean `fill-holes` attribute. The provider accepts `persist` and reads its optional JavaScript `options` property when connected. Call `provider.reset()` or `provider.setExploded(true)` to control the sheet.
64
+
65
+ ### React
66
+
67
+ ```tsx
68
+ import { Sticker, StickerProvider } from '@patrick91/stickers/react';
69
+
70
+ export function Page() {
71
+ return (
72
+ <StickerProvider persist="page-stickers">
73
+ <Sticker id="planet" src="/art/planet.png" width={150} height={120}
74
+ alt="Ringed planet" rotate={-6} finish="holo" />
75
+ </StickerProvider>
76
+ );
77
+ }
78
+ ```
79
+
80
+ `useStickers()` returns the nearest provider's engine, or `null` until it is mounted. The components accept `className` and `style` for layout.
81
+
82
+ ### Svelte
83
+
84
+ ```svelte
85
+ <script>
86
+ import { Sticker, StickerProvider } from '@patrick91/stickers/svelte';
87
+ </script>
88
+
89
+ <StickerProvider persist="page-stickers">
90
+ <Sticker id="planet" src="/art/planet.png" width={150} height={120}
91
+ alt="Ringed planet" rotate={-6} finish="holo" />
92
+ </StickerProvider>
93
+ ```
94
+
95
+ Inside a component beneath a provider, `const engine = useStickers()` gives you a readable store. Call `$engine?.reset()` or `$engine?.setExploded(true)`. Stickers accept `class` and `style` for layout.
96
+
97
+ ## Supply a mirror reflection
98
+
99
+ The `mirror` finish reflects a built-in room by default. Supply a ready image, canvas, bitmap, or video frame to replace it for every mirror sticker on that engine:
100
+
101
+ ```js
102
+ engine.setMirrorSource(canvas); // After drawing into a canvas
103
+ engine.setMirrorSource(video, { flipX: true }); // For each ready camera frame
104
+ engine.setMirrorSource(null); // Clear the frame and restore the built-in room
105
+ ```
106
+
107
+ Use a same-origin or CORS-readable source. A return value of `false` means the frame was not uploaded. Call again as new frames arrive. The library never requests camera access, starts playback, or stops media tracks. Your app owns those steps. Get the engine from `useStickers()` in React, the `useStickers()` store in Svelte, or the provider element’s `engine` property in Web Components.
108
+
109
+ The [webcam mirror lab](https://stickers.patrick.wtf/lab/#webcam-mirror) shows a live example.
110
+
111
+ ## Common options
112
+
113
+ Use one engine or provider per document. Give it a stable `persist` key and give each sticker a unique `id` if you want to remember positions. Provide artwork from the same origin or from a server that sends CORS headers (use `crossOrigin="anonymous"` on React/Svelte or `crossorigin="anonymous"` on a regular image).
114
+
115
+ | Sticker option | Default | What it does |
116
+ |---|---|---|
117
+ | `width`, `height` | Required width in React/Svelte, optional height | Reserve layout space. Use CSS to make the box fluid. |
118
+ | `alt` | Empty | Accessible name. Omit it for decorative stickers. |
119
+ | `rotate` | `0` | Initial rotation in degrees. Use `rotation` with `mountSticker()`. |
120
+ | `finish` | `'gloss'` | Surface material. |
121
+ | `cut` | `'contour'` | Follow the artwork, or use `'circle'`, `'rect'`, or `'rounded'`. |
122
+ | `border` | `7` | White die-cut border in pixels. Use `0` for no border. |
123
+ | `fillHoles` | `false` | For contour cuts, leave stock behind enclosed gaps without changing the printed artwork. |
124
+
125
+ **Finishes:** `gloss` (alias `vinyl`), `matte`, `holo`, `transparent`, `glitter`, `mirror`, `pixie`, `brushed`, `prismatic`, `reflective`, `kraft`, `glow`, `low-tack`, and `hi-tack`. Outside Web Components you can also pass a finish object that adjusts one of them, e.g. `{ base: 'mirror', gloss: 0.6, tack: 0.8 }`:
126
+
127
+ | Finish field | What it does |
128
+ |---|---|
129
+ | `base` | The named finish to start from. Default `'gloss'`. |
130
+ | `gloss` | Strength of the laminate's reflections. `1` is gloss vinyl, `0.16` is matte. |
131
+ | `grain` | Strength of the surface texture. |
132
+ | `tack` | `0` lifts easily and leaves no mark, `0.5` is ordinary vinyl, `1` clings and leaves more behind. |
133
+
134
+ | Engine/provider option | Default | What it does |
135
+ |---|---|---|
136
+ | `persist` | Off | Local storage key for sticker positions. Use a different key for independent layouts. |
137
+ | `residue` | `1` | Strength of the ghost a sticker leaves where it was first stuck. `0` turns it off. |
138
+ | `shadow` | `0.55` | Shadow opacity, 0 to 1. Raise it on dark pages. |
139
+ | `touchHold` | `170` | Milliseconds a finger must rest on a sticker before it grabs, so swipes still scroll the page. `0` grabs at once but stops the page scrolling from a sticker. |
140
+ | `hoverPeel` | `true` | Slightly lift a sticker edge under the mouse. |
141
+ | `gyroscope` | `false` | Slide the highlights as a phone or tablet tilts. iOS asks for motion permission on the first tap. |
142
+ | `detachAt` | `0.74` | How much of a sticker must be peeled, as a fraction of its length in the pull direction, before it comes off and follows the pointer. |
143
+ | `liftHeight` | `15` | How high a held sticker floats, in pixels. It moves the shadow further out. |
144
+ | `light` | `[-0.38, -0.56, 0.74]` | Direction to the light: x to the right, y down, z towards the viewer. |
145
+ | `shadowSlope` | `[0.3, 0.52]` | Shadow offset in pixels per pixel of height. |
146
+ | `maxDpr` | `2` | Highest device pixel ratio the canvas renders at. Lower it to save GPU time on dense screens. |
147
+ | `overscan` | `240` | Pixels the canvas extends above and below the viewport, so scrolling doesn't show undrawn stickers. |
148
+ | `zIndex` | `30` | Stacking order of the canvas. |
149
+
150
+ To change an option on a live engine, assign it on `engine.opts` and call `engine.invalidate()`, e.g. `engine.opts.shadow = 0.8; engine.invalidate()`. `persist`, `zIndex`, and `maxDpr` are read when the engine starts or measures the page, so create a new engine to change those. The React and Svelte providers and the `peel-sticker-provider` element read their options once, when they mount.
151
+
152
+ ## API reference
153
+
154
+ ### `createStickerEngine(options?)`
155
+
156
+ ```ts
157
+ function createStickerEngine(options?: EngineOptions): StickerEngine | null;
158
+ ```
159
+
160
+ Creates the engine and the one canvas it draws every sticker on. Returns `null` during server rendering, before `document.body` exists, and when WebGL2 can't start. Prefer it to `new StickerEngine()`, which throws outside the browser and, without WebGL2, returns an engine whose `ok` is `false`. The providers call it for you.
161
+
162
+ ### `mountSticker(engine, image, options?)`
163
+
164
+ ```ts
165
+ function mountSticker(engine: StickerEngine | null, image: HTMLImageElement, options?: StickerMountOptions): () => void;
166
+ ```
167
+
168
+ Makes an `img` a sticker once it loads, and rebuilds it whenever the image loads new artwork. The image stays in the layout and the accessibility tree, and turns transparent while the canvas draws it. Returns a cleanup function that removes the sticker and shows the image again; call it before you remove the image. It does nothing when `engine` is `null`.
169
+
170
+ `options` are the [`add()` options](#add-options) without `image`. `width` defaults to the image's rendered width, and `anchor` to the image itself; pass `anchor: null` to place it with `x` and `y` instead. If the image fails to load, the sticker is removed and the `img` shown again. A cross-origin image served without CORS stays a plain image, and a warning is logged.
171
+
172
+ ### `StickerEngine`
173
+
174
+ Get it from `createStickerEngine()`, from `useStickers()` in React or Svelte, or from a provider element's `engine` property.
175
+
176
+ | Member | What it does |
177
+ |---|---|
178
+ | `ok` | `false` when WebGL2 is unavailable. Nothing is drawn, and `add()` must not be called. |
179
+ | `stickers` | Every sticker, in drawing order: the last is on top. |
180
+ | `opts` | The engine options, with defaults filled in. See [Common options](#common-options) for changing them. |
181
+ | `onChange` | `(sticker) => void`, called after a visitor drops a sticker they moved. `reset()` doesn't call it. |
182
+ | `onHover` | `(sticker \| null) => void`, called with the sticker under the pointer whenever that changes, or with `null`. |
183
+ | `add(options)` | Adds a sticker for artwork that has already loaded, builds its outline at once, and returns it. Throws if the image is cross-origin and wasn't served with CORS. |
184
+ | `remove(sticker)` | Removes a sticker. |
185
+ | `reset(sticker?)` | Flies one sticker, or all of them, back home, and forgets where the visitor left them. |
186
+ | `setExploded(on)` | Tips every sticker back and pulls its layers apart, or puts them back. |
187
+ | `setMirrorSource(source, options?)` | See [Supply a mirror reflection](#supply-a-mirror-reflection). |
188
+ | `invalidate()` | Asks for a redraw on the next frame. |
189
+ | `destroy()` | Removes the canvas and its listeners and frees GPU memory. Images mounted with `mountSticker()` stay transparent until you call their cleanup functions. |
190
+
191
+ `onChange` and `onHover` each hold one function; assigning one replaces the last.
192
+
193
+ #### `add()` options
194
+
195
+ | Option | What it does |
196
+ |---|---|
197
+ | `image` | Required. A loaded image, canvas, or bitmap with a transparent background. |
198
+ | `width` | Required. Width of the artwork in CSS pixels. It also sets the texture resolution. |
199
+ | `anchor` | Element whose centre is the sticker's home. Its rendered width scales the sticker, so the sticker moves and resizes with the layout. |
200
+ | `x`, `y` | Home in document pixels, for a sticker without an anchor. |
201
+ | `rotation` | Degrees. |
202
+ | `finish`, `cut`, `border`, `fillHoles` | As in [Common options](#common-options). |
203
+ | `id` | Lets `persist` remember where the visitor left the sticker. Unique per engine. |
204
+ | `offset` | `[dx, dy, degrees]` from home to start at. A position remembered under `id` takes its place. |
205
+ | `paper`, `back` | RGB colours, 0 to 1, of the sticker's stock and of its adhesive side. |
206
+
207
+ #### `Sticker`
208
+
209
+ What `add()` returns and `engine.stickers` holds. Its type is exported as `EngineSticker`.
210
+
211
+ | Member | What it does |
212
+ |---|---|
213
+ | `id` | The `id` it was added with, or `null`. |
214
+ | `state` | `'idle'`, `'peel'` while being peeled, `'held'` once off the page and following the pointer, or `'fly'` while returning home. |
215
+ | `x`, `y` | Centre in document pixels. |
216
+ | `offset` | `[dx, dy, degrees]` from home, which is what `persist` saves. |
217
+ | `setImage(image)` | Replaces the artwork with another loaded image, keeping the sticker's place and settings. |
218
+
219
+ ### Web Components
220
+
221
+ `defineStickerElements()` registers both elements. It's safe to import during server rendering and to call more than once.
222
+
223
+ `<peel-sticker-provider>` owns the engine for the stickers inside it, and lays out as if it weren't there (`display: contents`). Removing it from the document destroys the engine. In TypeScript, `document.querySelector('peel-sticker-provider')` returns a `StickerProviderElement`.
224
+
225
+ | Member | What it does |
226
+ |---|---|
227
+ | `persist` attribute | As the engine option. It overrides `options.persist`. |
228
+ | `options` property | Other engine options. Set it before the element joins the document. |
229
+ | `engine` property | The `StickerEngine`, or `null` before it connects and without WebGL2. |
230
+ | `reset()`, `setExploded(on)` | As on the engine. |
231
+
232
+ `<peel-sticker>` must be inside a provider, and holds one `img`, directly or in a `picture`. The `img`'s `width` attribute sets both the element's width and the texture size. Changing any of these attributes, or the image's `width`, rebuilds the sticker.
233
+
234
+ | Attribute | What it does |
235
+ |---|---|
236
+ | `sticker-id` | The sticker's `id`. |
237
+ | `rotate` | Rotation in degrees. |
238
+ | `finish` | A named finish. |
239
+ | `cut`, `border` | As in [Common options](#common-options). |
240
+ | `fill-holes` | Present to fill enclosed holes. |
241
+
242
+ ### React
243
+
244
+ `<StickerProvider>` takes the engine options as props. It creates the engine after it mounts and destroys it when it unmounts.
245
+
246
+ `<Sticker>` takes `src`, `width` (required), `height`, `alt`, `rotate`, `finish`, `cut`, `border`, `fillHoles`, `id`, `crossOrigin`, `className`, and `style`. It renders a `span` around an `img`, which server rendering outputs as plain markup. Changing `src`, `width`, `rotate`, `finish`, `cut`, `border`, `fillHoles`, `id`, or `crossOrigin` rebuilds the sticker.
247
+
248
+ `useStickers()` returns the nearest provider's engine, or `null` during server rendering, before the provider mounts, and without WebGL2.
249
+
250
+ The entry point is marked `'use client'`, so React Server Components can render these components.
251
+
252
+ ### Svelte
253
+
254
+ The same components and props as React, with `class` and `style` strings in place of `className` and `style`. `useStickers()` returns a readable store of the engine.
255
+
256
+ ### Types
257
+
258
+ | Entry point | Types |
259
+ |---|---|
260
+ | `@patrick91/stickers` | `EngineOptions`, `StickerOptions`, `StickerMountOptions`, `StickerImageProps`, `StickerFinish`, `StickerFinishName`, `StickerCut`, `MirrorSource`, `MirrorSourceOptions`, `EngineSticker` |
261
+ | `@patrick91/stickers/react`, `@patrick91/stickers/svelte` | `StickerProps`, `StickerProviderProps` |
262
+ | `@patrick91/stickers/web-components` | `StickerProviderElement` |
263
+
264
+ ## Accessibility and motion
265
+
266
+ - Each sticker stays an `img` in the page, so assistive technology reads the artwork as usual, and the canvas is hidden from it. Give meaningful stickers an `alt`, and leave decorative ones without.
267
+ - Peeling and dragging work with a mouse, pen, or finger. There's no keyboard equivalent, so don't make anything reachable only by moving a sticker.
268
+ - With `prefers-reduced-motion: reduce`, stickers don't drop in or lift an edge under the pointer, and `reset()` and `setExploded()` jump to the end instead of animating. Dragging still follows the pointer.
269
+ - While a sticker is held, text selection is turned off for the page.
270
+
271
+ ## Performance
272
+
273
+ - One canvas draws every sticker, and only when something on it changes.
274
+ - Stickers cut the same way from the same image file share one outline and one set of textures.
275
+ - Building an outline takes a few milliseconds per sticker, more on a phone. `mountSticker()` and the adapters spread those builds across frames, artwork on screen first. `add()` builds at once.
276
+ - With the default `maxDpr`, a sticker's texture is at most 2.6 times its `width` and 2048 pixels across, so artwork files wider than that only cost download time. With `<peel-sticker>`, you can serve AVIF or WebP in a `picture`.
277
+
278
+ ## Licence
279
+
280
+ MIT. The full text is in the package's `LICENSE` file.
@@ -0,0 +1,14 @@
1
+ import type { CSSProperties, ReactNode } from 'react';
2
+ import type { EngineOptions, StickerEngine, StickerImageProps } from './index.js';
3
+ export interface StickerProviderProps extends EngineOptions {
4
+ children: ReactNode;
5
+ }
6
+ /** Owns the one canvas all stickers are drawn on. Options are read once, on mount. */
7
+ export declare function StickerProvider({ children, ...options }: StickerProviderProps): import("react").JSX.Element;
8
+ /** The engine, or null before mount and when WebGL2 is unavailable. */
9
+ export declare function useStickers(): StickerEngine | null;
10
+ export interface StickerProps extends StickerImageProps {
11
+ className?: string;
12
+ style?: CSSProperties;
13
+ }
14
+ export declare function Sticker({ src, width, height, alt, rotate, finish, cut, border, fillHoles, id, crossOrigin, className, style }: StickerProps): import("react").JSX.Element;
@@ -0,0 +1,40 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useContext, useEffect, useRef, useState } from 'react';
4
+ import { createStickerEngine, mountSticker } from './index.js';
5
+ const EngineContext = createContext(null);
6
+ /** Owns the one canvas all stickers are drawn on. Options are read once, on mount. */
7
+ export function StickerProvider({ children, ...options }) {
8
+ const [engine, setEngine] = useState(null);
9
+ const initial = useRef(options);
10
+ useEffect(() => {
11
+ const created = createStickerEngine(initial.current);
12
+ setEngine(created);
13
+ return () => created?.destroy();
14
+ }, []);
15
+ return _jsx(EngineContext.Provider, { value: engine, children: children });
16
+ }
17
+ /** The engine, or null before mount and when WebGL2 is unavailable. */
18
+ export function useStickers() {
19
+ return useContext(EngineContext);
20
+ }
21
+ export function Sticker({ src, width, height, alt = '', rotate = 0, finish, cut, border, fillHoles, id, crossOrigin, className, style }) {
22
+ const engine = useStickers();
23
+ const anchor = useRef(null);
24
+ const image = useRef(null);
25
+ const finishKey = typeof finish === 'string' ? finish : JSON.stringify(finish);
26
+ useEffect(() => {
27
+ if (!image.current)
28
+ return;
29
+ return mountSticker(engine, image.current, { anchor: anchor.current, width, rotation: rotate, finish, cut, border, fillHoles, id });
30
+ // `finish` is compared by value through finishKey.
31
+ // eslint-disable-next-line react-hooks/exhaustive-deps
32
+ }, [engine, src, crossOrigin, width, rotate, finishKey, cut, border, fillHoles, id]);
33
+ return (_jsx("span", { ref: anchor, className: className, role: alt ? 'img' : undefined, "aria-label": alt || undefined, "aria-hidden": alt ? undefined : true, style: { display: 'inline-block', width, maxWidth: '100%', lineHeight: 0, userSelect: 'none', WebkitUserSelect: 'none', ...style }, children: _jsx("img", { ref: image, crossOrigin: crossOrigin, src: src, alt: "", width: width, height: height, draggable: false, style: {
34
+ display: 'block',
35
+ width: '100%',
36
+ height: 'auto',
37
+ transform: rotate ? `rotate(${rotate}deg)` : undefined,
38
+ pointerEvents: 'none',
39
+ } }) }));
40
+ }
@@ -0,0 +1,4 @@
1
+ export { StickerEngine } from './sticker-engine.js';
2
+ export { createStickerEngine, mountSticker } from './mount-sticker.js';
3
+ export type { StickerImageProps, StickerMountOptions } from './mount-sticker.js';
4
+ export type { EngineOptions, MirrorSource, MirrorSourceOptions, Sticker as EngineSticker, StickerCut, StickerFinish, StickerFinishName, StickerOptions, } from './sticker-engine.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { StickerEngine } from './sticker-engine.js';
2
+ export { createStickerEngine, mountSticker } from './mount-sticker.js';
@@ -0,0 +1,24 @@
1
+ import { StickerEngine } from './sticker-engine.js';
2
+ import type { EngineOptions, StickerOptions } from './sticker-engine.js';
3
+ /** Shared artwork props for the framework adapters. */
4
+ export interface StickerImageProps extends Pick<StickerOptions, 'width' | 'id' | 'finish' | 'cut' | 'border' | 'fillHoles'> {
5
+ /** Transparent artwork, served from the same origin or with CORS. */
6
+ src: string;
7
+ /** Reserve layout space before the image loads. */
8
+ height?: number;
9
+ alt?: string;
10
+ /** Initial rotation, in degrees. */
11
+ rotate?: number;
12
+ crossOrigin?: 'anonymous' | 'use-credentials';
13
+ }
14
+ export interface StickerMountOptions extends Omit<StickerOptions, 'image' | 'width'> {
15
+ /** Texture width in CSS pixels. Defaults to the image's rendered or intrinsic width. */
16
+ width?: number;
17
+ }
18
+ /** Create an engine in the browser, or return null if the canvas cannot be initialized. */
19
+ export declare function createStickerEngine(options?: EngineOptions): StickerEngine | null;
20
+ /**
21
+ * Register an ordinary image after it loads. It stays in the layout and accessibility tree,
22
+ * but becomes transparent while the canvas draws it. Dispose before removing the artwork.
23
+ */
24
+ export declare function mountSticker(engine: StickerEngine | null, image: HTMLImageElement, options?: StickerMountOptions): () => void;
@@ -0,0 +1,132 @@
1
+ import { StickerEngine } from './sticker-engine.js';
2
+ /** Create an engine in the browser, or return null if the canvas cannot be initialized. */
3
+ export function createStickerEngine(options) {
4
+ if (typeof window === 'undefined' || typeof document === 'undefined' || !document.body)
5
+ return null;
6
+ try {
7
+ const engine = new StickerEngine(options);
8
+ if (engine.ok)
9
+ return engine;
10
+ engine.destroy();
11
+ }
12
+ catch (error) {
13
+ console.warn('[stickers] could not initialize the WebGL renderer', error);
14
+ }
15
+ return null;
16
+ }
17
+ // Building a sticker's outline holds the main thread for a few milliseconds, more on a phone, so a
18
+ // page of artwork that loads at once would freeze it for hundreds. Once a task has spent BUILD_BUDGET
19
+ // on builds, the rest wait for the next task, and the page paints and answers input in between.
20
+ // Each image stays visible until its sticker replaces it.
21
+ const BUILD_BUDGET = 8;
22
+ const builds = [];
23
+ let spent = 0;
24
+ let channel;
25
+ function schedule(build) {
26
+ if (builds.length || spent >= BUILD_BUDGET)
27
+ builds.push(build);
28
+ else
29
+ run(build);
30
+ nextTask();
31
+ }
32
+ function run(build) {
33
+ const start = performance.now();
34
+ build.run();
35
+ spent += performance.now() - start;
36
+ }
37
+ // Artwork arrives in whatever order the network sends it. Build what is on screen first, then the
38
+ // rest in the order it arrived.
39
+ function next() {
40
+ const i = builds.findIndex(({ image }) => {
41
+ const r = image.getBoundingClientRect();
42
+ return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth;
43
+ });
44
+ return builds.splice(Math.max(0, i), 1)[0];
45
+ }
46
+ function nextTask() {
47
+ if (channel)
48
+ return;
49
+ // A message comes back in a task of its own, without the 4ms a chain of timeouts waits.
50
+ channel = new MessageChannel();
51
+ channel.port1.onmessage = () => {
52
+ channel.port1.close();
53
+ channel = undefined;
54
+ spent = 0;
55
+ while (builds.length && spent < BUILD_BUDGET)
56
+ run(next());
57
+ if (builds.length)
58
+ nextTask();
59
+ };
60
+ channel.port2.postMessage(null);
61
+ }
62
+ /**
63
+ * Register an ordinary image after it loads. It stays in the layout and accessibility tree,
64
+ * but becomes transparent while the canvas draws it. Dispose before removing the artwork.
65
+ */
66
+ export function mountSticker(engine, image, options = {}) {
67
+ if (!engine?.ok)
68
+ return () => { };
69
+ let sticker;
70
+ let queued;
71
+ const opacity = image.style.opacity;
72
+ const cancel = () => {
73
+ if (!queued)
74
+ return;
75
+ const i = builds.indexOf(queued);
76
+ if (i >= 0)
77
+ builds.splice(i, 1);
78
+ queued = undefined;
79
+ };
80
+ const remove = () => {
81
+ cancel();
82
+ if (!sticker)
83
+ return;
84
+ engine.remove(sticker);
85
+ sticker = undefined;
86
+ if (image.style.opacity === '0')
87
+ image.style.opacity = opacity;
88
+ };
89
+ const load = () => {
90
+ if (queued || !engine.ok || !image.complete || !image.naturalWidth)
91
+ return;
92
+ queued = {
93
+ image,
94
+ run: () => {
95
+ queued = undefined;
96
+ build();
97
+ },
98
+ };
99
+ schedule(queued);
100
+ };
101
+ const build = () => {
102
+ if (!engine.ok || !image.complete || !image.naturalWidth)
103
+ return;
104
+ try {
105
+ if (sticker) {
106
+ sticker.setImage(image);
107
+ }
108
+ else {
109
+ sticker = engine.add({
110
+ ...options,
111
+ image,
112
+ width: options.width ?? (image.width || image.naturalWidth),
113
+ anchor: options.anchor === undefined ? image : options.anchor,
114
+ });
115
+ }
116
+ image.style.opacity = '0';
117
+ }
118
+ catch (error) {
119
+ remove();
120
+ // For example, a cross-origin image loaded without CORS.
121
+ console.warn('[stickers] could not mount artwork', image.currentSrc || image.src, error);
122
+ }
123
+ };
124
+ image.addEventListener('load', load);
125
+ image.addEventListener('error', remove);
126
+ load();
127
+ return () => {
128
+ image.removeEventListener('load', load);
129
+ image.removeEventListener('error', remove);
130
+ remove();
131
+ };
132
+ }
@@ -0,0 +1,2 @@
1
+ export { Sticker, StickerProvider, useStickers } from './Stickers.js';
2
+ export type { StickerProps, StickerProviderProps } from './Stickers.js';
package/dist/react.js ADDED
@@ -0,0 +1,2 @@
1
+ 'use client';
2
+ export { Sticker, StickerProvider, useStickers } from './Stickers.js';