@patrick91/stickers 0.2.2 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - Buttons and dialogs above a sticker receive pointer input instead of peeling the sticker behind them.
6
+ - Replacing the `img` inside a `peel-sticker`'s `picture` now replaces its sticker too.
7
+ - Stickers can use an inline `svg` as their artwork: pass the element to `mountSticker()`, put it in `<peel-sticker>`, or give it to React's or Svelte's `<Sticker>` as its child in place of `src`. The sticker redraws when the svg's markup changes.
8
+ - On an HDR screen, a `glow` sticker in the dark shines brighter than the page's white. The new `hdr` option sets how much brighter; `1` turns it off. It needs WebGL `drawingBufferToneMapping`, which Chrome plans to ship in version 160.
9
+ - A sticker no longer jumps to the pointer as it comes off the page. It glides there over a moment, as its folded flap lays flat.
10
+ - New `swing`, `swingStrength`, `swingSpring`, `swingDamping`, `swingSmoothing`, `catchUp`, `liftSpring` and `dropSpring` options set how a dragged sticker turns, reaches the pointer, rises and settles.
11
+ - A sticker you drag stays exactly under the pointer, and swings with the pointer's speed, up to about 50°, settling back as the pointer stops. Before, it trailed the pointer on a spring, swung by up to about 23°, and stayed tilted where you dropped it.
12
+ - A sticker that starts away from home, such as one `persist` puts back where it was left after a reload, no longer leaves a mark at its home. It leaves one again once `reset()` returns it there.
13
+ - `persist` no longer forgets where stickers were left when they aren't on the page as another is moved, such as ones whose artwork is still loading. Before, moving or resetting any sticker saved only the stickers mounted at that moment.
14
+ - An svg file without a `width` and `height`, which some browsers, such as Firefox, give no natural size, becomes a sticker at the size the page lays it out. Before, it stayed a flat image.
15
+
3
16
  ## 0.2.2
4
17
 
5
18
  - A peeled sticker keeps the point you grabbed under the pointer. Before, grabbing anywhere but the very edge, or dragging diagonally, peeled a far edge or a corner first and the flap trailed behind the pointer.
package/README.md CHANGED
@@ -2,15 +2,15 @@
2
2
 
3
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
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/).
5
+ Try the [demo](https://stickers.patrick.wtf), explore the [interactive docs](https://stickers.patrick.wtf/docs/), or tune a sticker and copy its code in the [sticker lab](https://stickers.patrick.wtf/lab/).
6
6
 
7
7
  ```sh
8
8
  npm install @patrick91/stickers
9
9
  ```
10
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.
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. Replace `/art/planet.png` with your own artwork; demo images aren't included in the package.
12
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.
13
+ The renderer needs WebGL2. If it cannot start, or JavaScript is unavailable, the artwork stays an ordinary image in the page.
14
14
 
15
15
  ## Choose an integration
16
16
 
@@ -18,7 +18,7 @@ Stickers need WebGL2: Chrome and Edge 56, Firefox 51, or Safari 15 and later. Wi
18
18
  |---|---|---|
19
19
  | `@patrick91/stickers` | Adding stickers to existing images, or controlling the renderer directly | No framework |
20
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 |
21
+ | `@patrick91/stickers/react` | React components and a context hook | React 18.3.1 or 19 |
22
22
  | `@patrick91/stickers/svelte` | Native Svelte components and a context store | Svelte 5 |
23
23
 
24
24
  Framework peers are optional; only install the one you use.
@@ -26,7 +26,7 @@ Framework peers are optional; only install the one you use.
26
26
  ### Plain JavaScript
27
27
 
28
28
  ```html
29
- <img id="planet" src="/art/planet.png" width="150" alt="Ringed planet">
29
+ <img id="planet" src="/art/planet.png" width="150" height="120" alt="Ringed planet">
30
30
 
31
31
  <script type="module">
32
32
  import { createStickerEngine, mountSticker } from '@patrick91/stickers';
@@ -43,7 +43,9 @@ Framework peers are optional; only install the one you use.
43
43
  </script>
44
44
  ```
45
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.
46
+ `createStickerEngine()` returns `null` outside the browser, before `document.body` exists, or when WebGL2 cannot initialize. `mountSticker()` safely accepts `null`; otherwise, it waits for the image to load, uses it as the layout anchor by default, and returns a cleanup function. Call that function before removing the image, then destroy the engine when the page unmounts.
47
+
48
+ Outline builds run in batches, prioritising visible artwork so the page can respond between them. Each image stays visible until its sticker takes over. Set an explicit `anchor` or `width` 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
49
 
48
50
  ### Web Components
49
51
 
@@ -60,7 +62,13 @@ Framework peers are optional; only install the one you use.
60
62
  </peel-sticker-provider>
61
63
  ```
62
64
 
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.
65
+ Registration is explicit, safe during server rendering, and safe to call more than once. Put an ordinary `img` directly in each `peel-sticker` and use its `width`, `height`, `alt`, and `crossorigin` attributes as usual.
66
+
67
+ To offer multiple image formats, wrap the `img` in a `picture`; the sticker uses whichever source the browser picks. The element's styles only reach direct children, so style a nested `img` with `display: block; width: 100%; height: auto` and `transform: rotate(var(--peel-rotation, 0deg))` to match `rotate` while the image is visible.
68
+
69
+ In place of the `img`, a `peel-sticker` can hold an inline `svg`; see [Inline SVG](#inline-svg).
70
+
71
+ 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. Set `options` before calling `defineStickerElements()` for existing markup, or before inserting a new provider into the document. Call `provider.reset()` or `provider.setExploded(true)` to control the sheet.
64
72
 
65
73
  ### React
66
74
 
@@ -77,7 +85,7 @@ export function Page() {
77
85
  }
78
86
  ```
79
87
 
80
- `useStickers()` returns the nearest provider's engine, or `null` until it is mounted. The components accept `className` and `style` for layout.
88
+ In a component beneath the provider, `useStickers()` returns its engine, or `null` before mount and when WebGL2 is unavailable. `Sticker` accepts `className` and `style` for layout; the provider adds no wrapper element.
81
89
 
82
90
  ### Svelte
83
91
 
@@ -92,16 +100,30 @@ export function Page() {
92
100
  </StickerProvider>
93
101
  ```
94
102
 
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.
103
+ Import `useStickers` from `@patrick91/stickers/svelte` inside a component beneath the provider. `const engine = useStickers()` gives you a readable store whose value is the engine or `null`. Call `$engine?.reset()` or `$engine?.setExploded(true)`. Stickers accept `class` and `style` for layout.
104
+
105
+ ## Inline SVG
106
+
107
+ Every adapter, and `mountSticker()`, also takes an inline `svg` as the artwork in place of an image. The sticker redraws whenever the svg's markup changes.
108
+
109
+ ```tsx
110
+ <Sticker id="badge" width={150} alt="Badge" rotate={-6}>
111
+ <svg viewBox="0 0 100 80">…</svg>
112
+ </Sticker>
113
+ ```
114
+
115
+ In Svelte, put the `svg` inside `<Sticker>` the same way. In Web Components, put it directly in `<peel-sticker>`, with a `width` attribute to set the sticker's width, as on an `img`. With `mountSticker()`, pass the `svg` element itself.
116
+
117
+ The sticker is drawn from a copy of the svg loaded as an image, so it sees none of the page's CSS and can't load anything else. `currentColor` and the svg's size are taken from the page. Classes styled by the page's stylesheets, `<use>` references to elements outside the svg, and web fonts don't reach the sticker; put styles inside the svg, or as attributes, instead.
96
118
 
97
119
  ## Supply a mirror reflection
98
120
 
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:
121
+ The `mirror` finish reflects a built-in room by default. Supply a loaded image, canvas, bitmap, or ready video element to replace it for every mirror sticker on that engine:
100
122
 
101
123
  ```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
124
+ engine?.setMirrorSource(canvas); // After drawing into a canvas
125
+ engine?.setMirrorSource(video, { flipX: true }); // For each ready camera frame
126
+ engine?.setMirrorSource(null); // Restore the built-in room
105
127
  ```
106
128
 
107
129
  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.
@@ -114,8 +136,9 @@ Use one engine or provider per document. Give it a stable `persist` key and give
114
136
 
115
137
  | Sticker option | Default | What it does |
116
138
  |---|---|---|
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. |
139
+ | `width` | CSS or intrinsic image width | Artwork width in CSS pixels; also sets the texture resolution. In Web Components, set it on the inner `img` or `svg`. |
140
+ | `height` | From the image's aspect ratio | Set together with `width`, in the artwork's aspect ratio, to reserve space before the image loads. Width alone does not reserve its height. |
141
+ | `alt` | `''` in React and Svelte | Accessible name. Use `alt=""` for decorative images, including ordinary HTML `img` elements. |
119
142
  | `rotate` | `0` | Initial rotation in degrees. Use `rotation` with `mountSticker()`. |
120
143
  | `finish` | `'gloss'` | Surface material. |
121
144
  | `cut` | `'contour'` | Follow the artwork, or use `'circle'`, `'rect'`, or `'rounded'`. |
@@ -134,20 +157,38 @@ Use one engine or provider per document. Give it a stable `persist` key and give
134
157
  | Engine/provider option | Default | What it does |
135
158
  |---|---|---|
136
159
  | `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. |
160
+ | `residue` | `1` | Strength of the ghost a sticker leaves where it was first stuck. A sticker that starts away from home, such as one `persist` puts back where it was left, leaves none until `reset()` returns it. `0` turns it off. |
138
161
  | `shadow` | `0.55` | Shadow opacity, 0 to 1. Raise it on dark pages. |
139
162
  | `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
163
  | `hoverPeel` | `true` | Slightly lift a sticker edge under the mouse. |
141
164
  | `gyroscope` | `false` | Slide the highlights as a phone or tablet tilts. iOS asks for motion permission on the first tap. |
142
165
  | `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
166
  | `liftHeight` | `15` | How high a held sticker floats, in pixels. It moves the shadow further out. |
167
+ | `swing` | `50` | Most a held sticker turns, in degrees, as the pointer moves it. `0` keeps it straight. |
168
+ | `swingStrength` | `3.95` | How far a given pointer speed turns a held sticker, up to `swing`. |
169
+ | `swingSpring` | `17.5` | How quickly a held sticker turns back once the pointer slows, per second. |
170
+ | `swingDamping` | `0.45` | How much it overshoots on the way back. `1` doesn't; lower values wobble. |
171
+ | `swingSmoothing` | `35.5` | How quickly the swing follows the pointer's speed, per second. Lower values make it lazier. |
172
+ | `catchUp` | `14` | How quickly a sticker reaches the pointer after it comes off the page, per second. |
173
+ | `liftSpring` | `17` | How quickly a grabbed sticker rises to `liftHeight`, per second. |
174
+ | `dropSpring` | `25` | How quickly a dropped sticker settles back onto the page, per second. |
144
175
  | `light` | `[-0.38, -0.56, 0.74]` | Direction to the light: x to the right, y down, z towards the viewer. |
145
176
  | `shadowSlope` | `[0.3, 0.52]` | Shadow offset in pixels per pixel of height. |
177
+ | `hdr` | `2.5` | On an HDR screen, how many times brighter than white a `glow` sticker shines in the dark. `1` turns it off. Requires WebGL `drawingBufferToneMapping` and floating-point colour buffers; the engine detects support at startup and uses standard rendering elsewhere. |
146
178
  | `maxDpr` | `2` | Highest device pixel ratio the canvas renders at. Lower it to save GPU time on dense screens. |
147
179
  | `overscan` | `240` | Pixels the canvas extends above and below the viewport, so scrolling doesn't show undrawn stickers. |
148
180
  | `zIndex` | `30` | Stacking order of the canvas. |
149
181
 
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.
182
+ The React and Svelte providers and the `peel-sticker-provider` element read their options once, when they mount. For most live changes, assign the option on `engine.opts` and call `engine.invalidate()`:
183
+
184
+ ```js
185
+ if (engine) {
186
+ engine.opts.shadow = 0.8;
187
+ engine.invalidate();
188
+ }
189
+ ```
190
+
191
+ Recreate the engine to change `persist`, `zIndex` or whether HDR is enabled. A live `maxDpr` change affects the canvas after the next resize, but does not rebuild existing textures; set it at setup for consistent canvas and texture resolution. `overscan` can change on a live engine.
151
192
 
152
193
  ## API reference
153
194
 
@@ -162,10 +203,10 @@ Creates the engine and the one canvas it draws every sticker on. Returns `null`
162
203
  ### `mountSticker(engine, image, options?)`
163
204
 
164
205
  ```ts
165
- function mountSticker(engine: StickerEngine | null, image: HTMLImageElement, options?: StickerMountOptions): () => void;
206
+ function mountSticker(engine: StickerEngine | null, image: HTMLImageElement | SVGSVGElement, options?: StickerMountOptions): () => void;
166
207
  ```
167
208
 
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`.
209
+ Makes an `img` a sticker once it loads, and rebuilds it whenever the image loads new artwork. It also takes an inline `svg`, which it rebuilds whenever the svg's markup changes; see [Inline SVG](#inline-svg). 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
210
 
170
211
  `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
212
 
@@ -229,7 +270,7 @@ What `add()` returns and `engine.stickers` holds. Its type is exported as `Engin
229
270
  | `engine` property | The `StickerEngine`, or `null` before it connects and without WebGL2. |
230
271
  | `reset()`, `setExploded(on)` | As on the engine. |
231
272
 
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.
273
+ `<peel-sticker>` must be inside a provider, and holds one `img`, directly or in a `picture`, or one inline `svg`. The `img`'s or `svg`'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
274
 
234
275
  | Attribute | What it does |
235
276
  |---|---|
@@ -243,7 +284,7 @@ What `add()` returns and `engine.stickers` holds. Its type is exported as `Engin
243
284
 
244
285
  `<StickerProvider>` takes the engine options as props. It creates the engine after it mounts and destroys it when it unmounts.
245
286
 
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.
287
+ `<Sticker>` takes `src`, `width`, `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. In place of `src`, pass one inline `svg` as its child; `height` and `crossOrigin` don't apply to it. Changing `src`, `width`, `rotate`, `finish`, `cut`, `border`, `fillHoles`, `id`, or `crossOrigin` rebuilds the sticker.
247
288
 
248
289
  `useStickers()` returns the nearest provider's engine, or `null` during server rendering, before the provider mounts, and without WebGL2.
249
290
 
@@ -263,7 +304,7 @@ The same components and props as React, with `class` and `style` strings in plac
263
304
 
264
305
  ## Accessibility and motion
265
306
 
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.
307
+ - The canvas is hidden from assistive technology; the original markup supplies the accessible name. Give meaningful stickers descriptive `alt` text. Use `alt=""` for decorative images; React and Svelte stickers default to it.
267
308
  - 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
309
  - 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
310
  - While a sticker is held, text selection is turned off for the page.
@@ -272,7 +313,7 @@ The same components and props as React, with `class` and `style` strings in plac
272
313
 
273
314
  - One canvas draws every sticker, and only when something on it changes.
274
315
  - 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.
316
+ - Building an outline takes a few milliseconds per sticker, more on a phone. `mountSticker()` and the adapters spread those builds across tasks, prioritising visible artwork so the page can respond between batches. `add()` builds at once.
276
317
  - 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
318
 
278
319
  ## Licence
@@ -7,8 +7,16 @@ export interface StickerProviderProps extends EngineOptions {
7
7
  export declare function StickerProvider({ children, ...options }: StickerProviderProps): import("react").JSX.Element;
8
8
  /** The engine, or null before mount and when WebGL2 is unavailable. */
9
9
  export declare function useStickers(): StickerEngine | null;
10
- export interface StickerProps extends StickerImageProps {
10
+ export type StickerProps = Omit<StickerImageProps, 'src'> & {
11
11
  className?: string;
12
12
  style?: CSSProperties;
13
+ } & ({
14
+ src: string;
15
+ children?: never;
13
16
  }
14
- export declare function Sticker({ src, width, height, alt, rotate, finish, cut, border, fillHoles, id, crossOrigin, className, style }: StickerProps): import("react").JSX.Element;
17
+ /** In place of src, one inline svg element, or a component that renders one, as the artwork. */
18
+ | {
19
+ src?: never;
20
+ children: ReactNode;
21
+ });
22
+ export declare function Sticker({ src, children, width, height, alt, rotate, finish, cut, border, fillHoles, id, crossOrigin, className, style }: StickerProps): import("react").JSX.Element;
package/dist/Stickers.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { createContext, useContext, useEffect, useRef, useState } from 'react';
3
+ import { cloneElement, createContext, isValidElement, useContext, useEffect, useRef, useState } from 'react';
4
4
  import { createStickerEngine, mountSticker } from './index.js';
5
5
  const EngineContext = createContext(null);
6
6
  /** Owns the one canvas all stickers are drawn on. Options are read once, on mount. */
@@ -18,23 +18,34 @@ export function StickerProvider({ children, ...options }) {
18
18
  export function useStickers() {
19
19
  return useContext(EngineContext);
20
20
  }
21
- export function Sticker({ src, width, height, alt = '', rotate = 0, finish, cut, border, fillHoles, id, crossOrigin, className, style }) {
21
+ export function Sticker({ src, children, width, height, alt = '', rotate = 0, finish, cut, border, fillHoles, id, crossOrigin, className, style }) {
22
22
  const engine = useStickers();
23
23
  const anchor = useRef(null);
24
24
  const image = useRef(null);
25
+ // An inline svg child, found after each render in case a new one replaced it.
26
+ const [svg, setSvg] = useState(null);
25
27
  const finishKey = typeof finish === 'string' ? finish : JSON.stringify(finish);
28
+ const transform = rotate ? `rotate(${rotate}deg)` : undefined;
29
+ const artStyle = { display: 'block', width: '100%', height: 'auto', transform, pointerEvents: 'none' };
26
30
  useEffect(() => {
27
- if (!image.current)
31
+ setSvg(src === undefined ? anchor.current?.querySelector(':scope > svg') ?? null : null);
32
+ });
33
+ useEffect(() => {
34
+ const artwork = image.current ?? svg;
35
+ if (!artwork)
28
36
  return;
29
- return mountSticker(engine, image.current, { anchor: anchor.current, width, rotation: rotate, finish, cut, border, fillHoles, id });
37
+ return mountSticker(engine, artwork, { anchor: anchor.current, width, rotation: rotate, finish, cut, border, fillHoles, id });
30
38
  // `finish` is compared by value through finishKey.
31
39
  // 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
+ }, [engine, src, svg, crossOrigin, width, rotate, finishKey, cut, border, fillHoles, id]);
41
+ let art;
42
+ if (src !== undefined) {
43
+ art = (_jsx("img", { ref: image, crossOrigin: crossOrigin, src: src, alt: "", width: width, height: height, draggable: false, style: artStyle }));
44
+ }
45
+ else {
46
+ art = isValidElement(children)
47
+ ? cloneElement(children, { style: { ...artStyle, ...children.props.style } })
48
+ : children;
49
+ }
50
+ 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: art }));
40
51
  }
@@ -1,10 +1,15 @@
1
1
  import { StickerEngine } from './sticker-engine.js';
2
2
  import type { EngineOptions, StickerOptions } from './sticker-engine.js';
3
3
  /** Shared artwork props for the framework adapters. */
4
- export interface StickerImageProps extends Pick<StickerOptions, 'width' | 'id' | 'finish' | 'cut' | 'border' | 'fillHoles'> {
4
+ export interface StickerImageProps extends Pick<StickerOptions, 'id' | 'finish' | 'cut' | 'border' | 'fillHoles'> {
5
5
  /** Transparent artwork, served from the same origin or with CORS. */
6
6
  src: string;
7
- /** Reserve layout space before the image loads. */
7
+ /**
8
+ * Width in CSS px, which also sets the texture resolution. Without it, the sticker takes the width
9
+ * CSS gives it, or the image's own width, and its space is unknown until the image loads.
10
+ */
11
+ width?: number;
12
+ /** With width, reserves the sticker's space before the image loads. */
8
13
  height?: number;
9
14
  alt?: string;
10
15
  /** Initial rotation, in degrees. */
@@ -18,7 +23,7 @@ export interface StickerMountOptions extends Omit<StickerOptions, 'image' | 'wid
18
23
  /** Create an engine in the browser, or return null if the canvas cannot be initialized. */
19
24
  export declare function createStickerEngine(options?: EngineOptions): StickerEngine | null;
20
25
  /**
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.
26
+ * Register an ordinary image, or an inline svg, after it loads. It stays in the layout and
27
+ * accessibility tree, but becomes transparent while the canvas draws it. Dispose before removing the artwork.
23
28
  */
24
- export declare function mountSticker(engine: StickerEngine | null, image: HTMLImageElement, options?: StickerMountOptions): () => void;
29
+ export declare function mountSticker(engine: StickerEngine | null, artwork: HTMLImageElement | SVGSVGElement, options?: StickerMountOptions): () => void;
@@ -37,8 +37,8 @@ function run(build) {
37
37
  // Artwork arrives in whatever order the network sends it. Build what is on screen first, then the
38
38
  // rest in the order it arrived.
39
39
  function next() {
40
- const i = builds.findIndex(({ image }) => {
41
- const r = image.getBoundingClientRect();
40
+ const i = builds.findIndex(({ element }) => {
41
+ const r = element.getBoundingClientRect();
42
42
  return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth;
43
43
  });
44
44
  return builds.splice(Math.max(0, i), 1)[0];
@@ -60,15 +60,59 @@ function nextTask() {
60
60
  channel.port2.postMessage(null);
61
61
  }
62
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.
63
+ * Register an ordinary image, or an inline svg, after it loads. It stays in the layout and
64
+ * accessibility tree, but becomes transparent while the canvas draws it. Dispose before removing the artwork.
65
65
  */
66
- export function mountSticker(engine, image, options = {}) {
66
+ export function mountSticker(engine, artwork, options = {}) {
67
67
  if (!engine?.ok)
68
68
  return () => { };
69
+ if (artwork.namespaceURI !== SVG_NS)
70
+ return mountImage(engine, artwork, artwork, options);
71
+ // The engine draws images, so an inline svg is drawn from a copy of itself in an image of its own,
72
+ // which a change to the svg's markup reloads.
73
+ const svg = artwork;
74
+ const image = new Image();
75
+ const dispose = mountImage(engine, image, svg, options);
76
+ let src = '';
77
+ const update = () => {
78
+ const next = svgSource(svg);
79
+ if (next !== src)
80
+ image.src = src = next;
81
+ };
82
+ // Mounting changes the svg's own opacity, which the copy leaves out, so that doesn't reload it.
83
+ const observer = new MutationObserver(update);
84
+ observer.observe(svg, { subtree: true, childList: true, attributes: true, characterData: true });
85
+ update();
86
+ return () => {
87
+ observer.disconnect();
88
+ dispose();
89
+ };
90
+ }
91
+ const SVG_NS = 'http://www.w3.org/2000/svg';
92
+ // An svg in an image sees none of the page's CSS, so the copy takes the size and text colour
93
+ // (for currentColor) the svg has on the page, and none of the styles that place it there.
94
+ function svgSource(svg) {
95
+ const copy = svg.cloneNode(true);
96
+ const style = getComputedStyle(svg);
97
+ const box = svg.viewBox.baseVal;
98
+ let width = parseFloat(style.width), height = parseFloat(style.height);
99
+ if (!(width > 0 && height > 0) && box?.width > 0 && box.height > 0)
100
+ ({ width, height } = box);
101
+ if (width > 0 && height > 0) {
102
+ copy.setAttribute('width', String(width));
103
+ copy.setAttribute('height', String(height));
104
+ }
105
+ for (const name of ['width', 'height', 'transform', 'rotate', 'scale', 'translate', 'opacity'])
106
+ copy.style.removeProperty(name);
107
+ copy.style.color = style.color;
108
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(copy))}`;
109
+ }
110
+ // Draws image as a sticker each time it loads, in place of shown, which is the image itself or the
111
+ // inline svg it was made from.
112
+ function mountImage(engine, image, shown, options) {
69
113
  let sticker;
70
114
  let queued;
71
- const opacity = image.style.opacity;
115
+ const opacity = shown.style.opacity;
72
116
  const cancel = () => {
73
117
  if (!queued)
74
118
  return;
@@ -83,14 +127,17 @@ export function mountSticker(engine, image, options = {}) {
83
127
  return;
84
128
  engine.remove(sticker);
85
129
  sticker = undefined;
86
- if (image.style.opacity === '0')
87
- image.style.opacity = opacity;
130
+ if (shown.style.opacity === '0')
131
+ shown.style.opacity = opacity;
88
132
  };
133
+ // An svg file without a width and height has no natural size in some browsers, such as Firefox; the
134
+ // engine then draws it at the size the page lays it out.
135
+ const ready = () => engine.ok && image.complete && !!(image.naturalWidth || image.width);
89
136
  const load = () => {
90
- if (queued || !engine.ok || !image.complete || !image.naturalWidth)
137
+ if (queued || !ready())
91
138
  return;
92
139
  queued = {
93
- image,
140
+ element: shown,
94
141
  run: () => {
95
142
  queued = undefined;
96
143
  build();
@@ -99,7 +146,7 @@ export function mountSticker(engine, image, options = {}) {
99
146
  schedule(queued);
100
147
  };
101
148
  const build = () => {
102
- if (!engine.ok || !image.complete || !image.naturalWidth)
149
+ if (!ready())
103
150
  return;
104
151
  try {
105
152
  if (sticker) {
@@ -110,15 +157,15 @@ export function mountSticker(engine, image, options = {}) {
110
157
  ...options,
111
158
  image,
112
159
  width: options.width ?? (image.width || image.naturalWidth),
113
- anchor: options.anchor === undefined ? image : options.anchor,
160
+ anchor: options.anchor === undefined ? shown : options.anchor,
114
161
  });
115
162
  }
116
- image.style.opacity = '0';
163
+ shown.style.opacity = '0';
117
164
  }
118
165
  catch (error) {
119
166
  remove();
120
167
  // For example, a cross-origin image loaded without CORS.
121
- console.warn('[stickers] could not mount artwork', image.currentSrc || image.src, error);
168
+ console.warn('[stickers] could not mount artwork', shown === image ? image.currentSrc || image.src : shown, error);
122
169
  }
123
170
  };
124
171
  image.addEventListener('load', load);
@@ -32,7 +32,7 @@ export interface StickerOptions {
32
32
  /** Width of the artwork in CSS px. Also decides the texture resolution. */
33
33
  width: number;
34
34
  /** Element whose centre is the sticker's home. Its rendered width sets the sticker's scale. */
35
- anchor?: HTMLElement | null;
35
+ anchor?: Element | null;
36
36
  /** Home position in document px, when there is no anchor. */
37
37
  x?: number;
38
38
  y?: number;
@@ -64,6 +64,22 @@ export interface EngineOptions {
64
64
  /** Fraction of a sticker that must be peeled before it comes off. Default 0.74. */
65
65
  detachAt?: number;
66
66
  liftHeight?: number;
67
+ /** Most a held sticker turns as the pointer moves, in degrees; 0 keeps it straight. Default 50. */
68
+ swing?: number;
69
+ /** How far a given pointer speed turns a held sticker. Default 3.95. */
70
+ swingStrength?: number;
71
+ /** How quickly a held sticker turns back, per second. Default 17.5. */
72
+ swingSpring?: number;
73
+ /** How much it overshoots turning back: 1 doesn't, lower wobbles. Default 0.45. */
74
+ swingDamping?: number;
75
+ /** How quickly the swing follows the pointer's speed, per second; lower is lazier. Default 35.5. */
76
+ swingSmoothing?: number;
77
+ /** How quickly a sticker reaches the pointer after it comes off, per second. Default 14. */
78
+ catchUp?: number;
79
+ /** How quickly a grabbed sticker rises to liftHeight, per second. Default 17. */
80
+ liftSpring?: number;
81
+ /** How quickly a dropped sticker settles back down, per second. Default 25. */
82
+ dropSpring?: number;
67
83
  /** An edge lifts towards a hovering mouse. Default true. */
68
84
  hoverPeel?: boolean;
69
85
  /** ms a finger must rest on a sticker before it grabs, so swipes still scroll. Default 170. */
@@ -77,6 +93,11 @@ export interface EngineOptions {
77
93
  residue?: number;
78
94
  /** Highlights slide as a phone or tablet tilts. iOS asks for permission on the first tap. Default false. */
79
95
  gyroscope?: boolean;
96
+ /**
97
+ * On an HDR screen, how many times brighter than white a glowing sticker shines in the dark. Default 2.5; 1 turns it off.
98
+ * Needs a browser with WebGL `drawingBufferToneMapping`; elsewhere stickers render as on any other screen.
99
+ */
100
+ hdr?: number;
80
101
  }
81
102
 
82
103
  export class Sticker {
@@ -60,6 +60,7 @@ uniform vec2 uEnv; // environment shift (pointer parallax)
60
60
  uniform vec4 uFin; // gloss, material kind, grain, show-through
61
61
  uniform vec3 uPtr; // pointer in viewport px, and whether there is one
62
62
  uniform float uGlow; // how dark the surroundings are, 0..1
63
+ uniform float uHdr; // how much brighter than white a glowing sticker shines, 1 on SDR screens
63
64
  uniform float uTrim; // 1: no border, so the sticker ends exactly where the artwork does
64
65
  uniform vec3 uPaper;
65
66
  uniform vec3 uBack;
@@ -265,6 +266,8 @@ vec4 shadeFront(vec2 m, vec3 N, vec3 s, vec4 raw, float flapSh) {
265
266
  float clear = kind == 2 ? 1.0 : 0.0;
266
267
  float a = c.a + film * clamp(mix(0.1, 0.03, clear) + g * 2.0 + 0.16 * edge, 0.0, 1.0);
267
268
  rgb += g * (c.a - rgb) + film * (vec3(0.07, 0.09, 0.11) * mix(1.0, 0.35, clear) + g * 2.0 + edge * (0.1 + 0.08 * facing));
269
+ // on an HDR screen the phosphor shines brighter than the page's white
270
+ if (kind == 10) rgb += (uHdr - 1.0) * glint * c.a;
268
271
  return vec4(rgb, a);
269
272
  }
270
273
 
@@ -524,6 +527,9 @@ export class Sticker {
524
527
  this.x = this.hx + this.ox; this.y = this.hy + this.oy;
525
528
  this.scale = 1;
526
529
  this.hidden = false;
530
+ // It leaves a mark at home only once it has been stuck there: not when it starts somewhere else,
531
+ // such as where persist remembered it, until reset() sends it home.
532
+ this.marked = !(this.ox || this.oy || off[2]);
527
533
  this.age = engine.reduced ? 1 : 0;
528
534
  this.seed = Math.random() * 50;
529
535
 
@@ -534,9 +540,10 @@ export class Sticker {
534
540
  this.gx = 0; this.gy = 0; // grabbed point (local)
535
541
  this.p0x = 0; this.p0y = 0;
536
542
  this.floor = 0; this.floorNx = 0; this.floorNy = 0;
537
- this.pvx = 0; this.pvy = 0; this.pvvx = 0; this.pvvy = 0;
538
- this.rotV = 0; this.rot0 = this.rot; this.heldT = 0;
543
+ this.pvx = 0; this.pvy = 0; this.pvvx = 0; this.pvvy = 0; this.lagX = 0; this.lagY = 0;
544
+ this.rotV = 0; this.rot0 = this.rot;
539
545
  this.hint = null;
546
+ this.pose = null; // see _step
540
547
  this.ground = 1; // brightness of the page under its home, for the residue mark
541
548
  this.fly = null;
542
549
 
@@ -555,7 +562,9 @@ export class Sticker {
555
562
  let shape = key && engine._shapes.get(key);
556
563
  if (!shape) {
557
564
  const w = this.width, h = w * ih / iw;
558
- const pad = this.border + 10;
565
+ // _buildShape grows the outline by up to 1.7 × border before rounding it back to border, so leave
566
+ // room for all of it: an outline that reaches the texture's edge is cut flat there.
567
+ const pad = Math.ceil(this.border * 1.7) + 10;
559
568
  const W = w + pad * 2, H = h + pad * 2;
560
569
  const ts = Math.min(engine.texScale, 2048 / Math.max(W, H));
561
570
  const cv = document.createElement('canvas');
@@ -703,6 +712,14 @@ const DEFAULTS = {
703
712
  maxDpr: 2,
704
713
  detachAt: 0.74, // fraction of the sticker that must be peeled before it lets go
705
714
  liftHeight: 15,
715
+ swing: 50, // most a held sticker turns as the pointer moves, in degrees; 0 keeps it straight
716
+ swingStrength: 3.95, // how far a given pointer speed turns it
717
+ swingSpring: 17.5, // how quickly it turns back, per second
718
+ swingDamping: 0.45, // how much it overshoots on the way back: 1 doesn't, lower wobbles
719
+ swingSmoothing: 35.5, // how quickly the swing follows the pointer's speed, per second; lower is lazier
720
+ catchUp: 14, // how quickly a sticker reaches the pointer after it comes off, per second
721
+ liftSpring: 17, // how quickly a grabbed sticker rises to liftHeight, per second
722
+ dropSpring: 25, // how quickly a dropped sticker settles back down, per second
706
723
  hoverPeel: true, // an edge lifts towards a hovering mouse
707
724
  touchHold: 170, // ms a finger must rest on a sticker before it grabs (0 = at once, but then it blocks scrolling)
708
725
  zIndex: 30,
@@ -710,6 +727,7 @@ const DEFAULTS = {
710
727
  persist: null, // localStorage key; stickers with an id remember where they were left
711
728
  residue: 1, // strength of the mark a sticker leaves where it was first stuck; 0 turns it off
712
729
  gyroscope: false, // highlights slide as a phone or tablet tilts; iOS asks for permission on the first tap
730
+ hdr: 2.5, // on an HDR screen, how many times brighter than white a glowing sticker shines; 1 turns it off
713
731
  };
714
732
 
715
733
  export class StickerEngine {
@@ -747,6 +765,13 @@ export class StickerEngine {
747
765
  this.ok = !!gl;
748
766
  this._tick = this._tick.bind(this);
749
767
  if (!gl) return;
768
+ // HDR screens: a half-float buffer the browser doesn't clip at white. Without tone mapping it would only cost memory.
769
+ this._hdr = this.opts.hdr > 1 && !!gl.drawingBufferToneMapping && !!window.matchMedia
770
+ && window.matchMedia('(dynamic-range: high)').matches && !!gl.getExtension('EXT_color_buffer_float');
771
+ if (this._hdr) {
772
+ gl.drawingBufferStorage(gl.RGBA16F, cv.width, cv.height); // kept when the canvas is resized
773
+ gl.drawingBufferToneMapping({ mode: 'extended' });
774
+ }
750
775
  document.body.append(cv, ct);
751
776
  try {
752
777
  this._initGL();
@@ -875,12 +900,16 @@ export class StickerEngine {
875
900
  /** Send every sticker (or one) back to where the layout put it. */
876
901
  reset(sticker) {
877
902
  const list = sticker ? [sticker] : this.stickers;
878
- list.forEach((s, i) => {
903
+ let i = 0;
904
+ for (const s of list) {
879
905
  if (this.active === s) this._release();
880
- if (this.reduced) { s.ox = 0; s.oy = 0; s.rot = s.baseRot; s.state = 'idle'; return; }
906
+ s.marked = true;
907
+ if (this.reduced) { s.ox = 0; s.oy = 0; s.rot = s.baseRot; s.state = 'idle'; continue; }
908
+ // Only stickers away from home take a turn, so one moved sticker on a full page leaves at once.
909
+ if (!s.ox && !s.oy && s.rot === s.baseRot && s.state === 'idle') continue;
881
910
  s.state = 'fly';
882
- s.fly = { ox: s.ox, oy: s.oy, r: s.rot, t: -i * 0.035, d: 0.5 };
883
- });
911
+ s.fly = { ox: s.ox, oy: s.oy, r: s.rot, t: -i++ * 0.035, d: 0.5 };
912
+ }
884
913
  this._save();
885
914
  this.invalidate();
886
915
  }
@@ -942,7 +971,17 @@ export class StickerEngine {
942
971
  _wake() { if (!this._raf && this.ok) this._raf = requestAnimationFrame(this._tick); }
943
972
 
944
973
  hitTest(x, y, slop) {
945
- for (let i = this.stickers.length - 1; i >= 0; i--) if (this.stickers[i].contains(x, y, slop)) return this.stickers[i];
974
+ for (let i = this.stickers.length - 1; i >= 0; i--) {
975
+ const s = this.stickers[i];
976
+ if (!s.contains(x, y, slop)) continue;
977
+ // All stickers share one layer. Ask the browser whether a control or dialog is above it,
978
+ // including on the first touch, when hover hasn't enabled the catcher yet.
979
+ const { style } = this.catcher, previous = style.pointerEvents;
980
+ if (previous !== 'auto') style.pointerEvents = 'auto';
981
+ const top = document.elementFromPoint(x - window.scrollX, y - window.scrollY);
982
+ if (previous !== 'auto') style.pointerEvents = previous;
983
+ return top === this.catcher ? s : null;
984
+ }
946
985
  return null;
947
986
  }
948
987
 
@@ -1157,17 +1196,26 @@ export class StickerEngine {
1157
1196
 
1158
1197
  _save() {
1159
1198
  if (!this.opts.persist) return;
1160
- const out = {};
1161
- for (const s of this.stickers) if (s.id) { const o = s.state === 'fly' ? [0, 0, 0] : s.offset; if (o[0] || o[1] || o[2]) out[s.id] = o; }
1199
+ // Keep what is saved for stickers not on the page right now, such as ones still loading.
1200
+ const out = Object.assign({}, this.saved);
1201
+ for (const s of this.stickers) {
1202
+ if (!s.id) continue;
1203
+ const o = s.state === 'fly' ? [0, 0, 0] : s.offset;
1204
+ if (o[0] || o[1] || o[2]) out[s.id] = o; else delete out[s.id];
1205
+ }
1162
1206
  this.saved = out;
1163
1207
  try { localStorage.setItem(this.opts.persist, JSON.stringify(out)); } catch (_) {}
1164
1208
  }
1165
1209
 
1166
1210
  _detach(s) {
1167
1211
  const c = Math.cos(s.rot), n = Math.sin(s.rot), k = s.renderSize;
1168
- s.state = 'held'; s.heldT = 0; s.rot0 = s.rot; s.rotV = 0;
1212
+ s.state = 'held'; s.rot0 = s.rot; s.rotV = 0;
1169
1213
  s.pvx = s.x + (c * s.gx - n * s.gy) * k; s.pvy = s.y + (n * s.gx + c * s.gy) * k;
1170
1214
  s.pvvx = 0; s.pvvy = 0;
1215
+ // The flap was folded short of the pointer: the grabbed point starts where it was, and closes
1216
+ // the gap as the sticker flattens out, rather than jumping to the pointer.
1217
+ const P = this.pointer;
1218
+ s.lagX = s.pvx - (clamp(P.cx, 6, this._vw - 6) + window.scrollX); s.lagY = s.pvy - (clamp(P.cy, 6, window.innerHeight - 6) + window.scrollY);
1171
1219
  }
1172
1220
 
1173
1221
  // ------------------------------------------------------------ simulation
@@ -1212,6 +1260,16 @@ export class StickerEngine {
1212
1260
  tx = nx * tau; ty = ny * tau;
1213
1261
  if (tau > s.byTack(0.48, this.opts.detachAt, 0.93) * (far + near)) this._detach(s);
1214
1262
  } else { tx = s.floorNx * s.floor; ty = s.floorNy * s.floor; }
1263
+ } else if (s.state === 'idle' && s.pose && !this.explodeTarget) {
1264
+ // Undocumented: a pose the page holds the sticker in while nobody touches it, so the docs can
1265
+ // show options that only matter mid-peel. { peel: 0.9, nx, ny } folds the edge towards local
1266
+ // (nx, ny) back to 90% of the way to coming off; { lift: true } holds it up like a held sticker.
1267
+ const { peel, nx = 0.6, ny = 0.8 } = s.pose;
1268
+ if (peel) {
1269
+ const far = s.support(nx, ny), near = s.support(-nx, -ny);
1270
+ const tau = peel * s.byTack(0.48, this.opts.detachAt, 0.93) * (far + near);
1271
+ tx = nx * tau; ty = ny * tau;
1272
+ }
1215
1273
  } else if (s.state === 'idle' && !this.explodeTarget && !this.reduced) {
1216
1274
  // an edge lifts towards a hovering mouse, or for a moment after a tap
1217
1275
  let at = null, amount = 0;
@@ -1241,7 +1299,8 @@ export class StickerEngine {
1241
1299
  const tau = s.tau;
1242
1300
  if (tau > 0.02) { s.nx = s.fx / tau; s.ny = s.fy / tau; }
1243
1301
 
1244
- let liftTarget = s.state === 'held' ? this.opts.liftHeight : 0;
1302
+ const posed = s.state === 'idle' && s.pose && s.pose.lift && !this.explodeTarget;
1303
+ let liftTarget = s.state === 'held' || posed ? this.opts.liftHeight : 0;
1245
1304
  if (s.state === 'fly') {
1246
1305
  const f = s.fly;
1247
1306
  f.t += dt;
@@ -1252,7 +1311,7 @@ export class StickerEngine {
1252
1311
  if (t >= 1) { s.state = 'idle'; s.fly = null; }
1253
1312
  }
1254
1313
  {
1255
- const w = liftTarget > 0 ? 17 : 25, z = liftTarget > 0 ? 0.8 : 0.5;
1314
+ const w = liftTarget > 0 ? this.opts.liftSpring : this.opts.dropSpring, z = liftTarget > 0 ? 0.8 : 0.5;
1256
1315
  for (let i = 0; i < 2; i++) {
1257
1316
  const h = dt / 2;
1258
1317
  s.liftV += (w * w * (liftTarget - s.lift) - 2 * z * w * s.liftV) * h;
@@ -1261,20 +1320,22 @@ export class StickerEngine {
1261
1320
  }
1262
1321
 
1263
1322
  if (s.state === 'held') {
1264
- // the grabbed point is pulled to the pointer; the rest swings behind it
1265
- s.heldT += dt;
1266
- const w = 20 + 30 * clamp(s.heldT / 0.35, 0, 1), z = 0.82;
1267
- const px = clamp(P.cx, 6, this._vw - 6) + window.scrollX, py = clamp(P.cy, 6, window.innerHeight - 6) + window.scrollY;
1268
- const k = s.size;
1323
+ // the grabbed point stays under the pointer, once it has caught up with it after coming off;
1324
+ // the rest swings a little behind it, by up to opts.swing degrees, and settles back when it stops
1325
+ const kl = Math.exp(-dt * this.opts.catchUp);
1326
+ s.lagX *= kl; s.lagY *= kl;
1327
+ const px = clamp(P.cx, 6, this._vw - 6) + window.scrollX + s.lagX, py = clamp(P.cy, 6, window.innerHeight - 6) + window.scrollY + s.lagY;
1328
+ const kv = 1 - Math.exp(-dt * this.opts.swingSmoothing); // the pointer's velocity, smoothed so the swing doesn't jitter
1329
+ s.pvvx += ((px - s.pvx) / dt - s.pvvx) * kv; s.pvvy += ((py - s.pvy) / dt - s.pvvy) * kv;
1330
+ s.pvx = px; s.pvy = py;
1331
+ const k = s.size, { swingStrength, swingSpring: w, swingDamping: z } = this.opts, most = this.opts.swing * Math.PI / 180;
1269
1332
  for (let i = 0; i < 2; i++) {
1270
1333
  const h = dt / 2;
1271
- s.pvvx += (w * w * (px - s.pvx) - 2 * z * w * s.pvvx) * h; s.pvvy += (w * w * (py - s.pvy) - 2 * z * w * s.pvvy) * h;
1272
- s.pvx += s.pvvx * h; s.pvy += s.pvvy * h;
1273
1334
  const c = Math.cos(s.rot), n = Math.sin(s.rot);
1274
1335
  const rx = -(c * s.gx - n * s.gy), ry = -(n * s.gx + c * s.gy);
1275
1336
  const torque = (ry * s.pvvx - rx * s.pvvy) / k;
1276
- s.rotV += (torque * 4.2e-4 - 2 * 0.5 * 12 * s.rotV - 144 * (s.rot - s.rot0)) * h;
1277
- s.rot = clamp(s.rot + s.rotV * h, s.rot0 - 0.4, s.rot0 + 0.4);
1337
+ s.rotV += (torque * 1.2e-4 * swingStrength - 2 * z * w * s.rotV - w * w * (s.rot - s.rot0)) * h;
1338
+ s.rot = clamp(s.rot + s.rotV * h, s.rot0 - most, s.rot0 + most);
1278
1339
  }
1279
1340
  const c = Math.cos(s.rot), n = Math.sin(s.rot), kr = s.renderSize;
1280
1341
  s.x = s.pvx - (c * s.gx - n * s.gy) * kr; s.y = s.pvy - (n * s.gx + c * s.gy) * kr;
@@ -1337,9 +1398,10 @@ export class StickerEngine {
1337
1398
  gl.uniform2f(this.u.uEnv, this.env.x, this.env.y);
1338
1399
  gl.uniform3f(this.u.uPtr, this.pointer.cx, this.pointer.cy, this.pointer.seen ? 1 : 0);
1339
1400
  gl.uniform1f(this.u.uShadow, this.opts.shadow);
1401
+ gl.uniform1f(this.u.uHdr, this._hdr ? this.opts.hdr : 1);
1340
1402
  // marks first, so every sticker sits on top of them
1341
1403
  if (this.opts.residue > 0) for (const s of this.stickers) {
1342
- if (s.hidden) continue;
1404
+ if (s.hidden || !s.marked) continue;
1343
1405
  const home = s.state === 'idle' && s.tau < 0.02 && s.lift < 0.5 && Math.abs(s.ox) + Math.abs(s.oy) < 0.5 && Math.abs(s.rot - s.baseRot) < 0.002 && e < 0.002;
1344
1406
  if ((home && s.age >= 1) || s.tack < 0.02) continue; // hidden under its own sticker, or a low-tack one that leaves nothing
1345
1407
  const reach = (s.shape.reach + 4) * s.scale;
@@ -3,34 +3,49 @@
3
3
  import { useStickers } from './context.js';
4
4
  import type { StickerProps } from './types.js';
5
5
 
6
- let { src, width, height, alt = '', rotate = 0, finish, cut, border, fillHoles, id, crossOrigin, class: className, style }: StickerProps = $props();
6
+ let { src, children, width, height, alt = '', rotate = 0, finish, cut, border, fillHoles, id, crossOrigin, class: className, style }: StickerProps = $props();
7
7
  let image = $state<HTMLImageElement>();
8
8
  let anchor = $state<HTMLSpanElement>();
9
9
  const engine = useStickers();
10
10
 
11
11
  $effect(() => {
12
- if (!image) return;
13
- return mountSticker($engine, image, { anchor, width, rotation: rotate, finish, cut, border, fillHoles, id });
12
+ // Without src, the artwork is the inline svg that children renders.
13
+ children;
14
+ const artwork = image ?? anchor?.querySelector<SVGSVGElement>(':scope > svg');
15
+ if (!artwork) return;
16
+ return mountSticker($engine, artwork, { anchor, width, rotation: rotate, finish, cut, border, fillHoles, id });
14
17
  });
15
18
  </script>
16
19
 
17
- <span bind:this={anchor} class={className} {style} style:--sticker-width={`${width}px`}>
18
- <img bind:this={image} crossorigin={crossOrigin} {src} {alt} {width} {height} draggable="false" style:transform={`rotate(${rotate}deg)`} />
19
- </span>
20
+ {#if src !== undefined}
21
+ <span bind:this={anchor} class={className} {style} style:--sticker-width={width ? `${width}px` : undefined}>
22
+ <img bind:this={image} crossorigin={crossOrigin} {src} {alt} {width} {height} draggable="false" style:transform={`rotate(${rotate}deg)`} />
23
+ </span>
24
+ {:else}
25
+ <!-- The span names the svg, as the img's alt would. -->
26
+ <span bind:this={anchor} class={className} {style} style:--sticker-width={width ? `${width}px` : undefined}
27
+ style:--sticker-rotation={`${rotate}deg`} role={alt ? 'img' : undefined} aria-label={alt || undefined} aria-hidden={alt ? undefined : true}>
28
+ {@render children?.()}
29
+ </span>
30
+ {/if}
20
31
 
21
32
  <style>
22
33
  span {
23
34
  display: inline-block;
24
- width: var(--sticker-width);
35
+ width: var(--sticker-width, auto);
25
36
  max-width: 100%;
26
37
  line-height: 0;
27
38
  user-select: none;
28
39
  }
29
40
 
30
- img {
41
+ img, span > :global(svg) {
31
42
  display: block;
32
43
  width: 100%;
33
44
  height: auto;
34
45
  pointer-events: none;
35
46
  }
47
+
48
+ span > :global(svg) {
49
+ transform: rotate(var(--sticker-rotation));
50
+ }
36
51
  </style>
@@ -3,7 +3,15 @@ import type { EngineOptions, StickerImageProps } from '../index.js';
3
3
  export interface StickerProviderProps extends EngineOptions {
4
4
  children?: Snippet;
5
5
  }
6
- export interface StickerProps extends StickerImageProps {
6
+ export type StickerProps = Omit<StickerImageProps, 'src'> & {
7
7
  class?: string;
8
8
  style?: string;
9
+ } & ({
10
+ src: string;
11
+ children?: never;
9
12
  }
13
+ /** In place of src, an inline svg element as the artwork. */
14
+ | {
15
+ src?: never;
16
+ children: Snippet;
17
+ });
@@ -1,6 +1,8 @@
1
1
  import { createStickerEngine, mountSticker } from './index.js';
2
2
  const PROVIDER_TAG = 'peel-sticker-provider';
3
3
  const STICKER_TAG = 'peel-sticker';
4
+ // The artwork is an img, on its own or in a picture that offers it in other formats, or an inline svg.
5
+ const ARTWORK = ':scope > img, :scope > picture > img, :scope > svg';
4
6
  function numberAttribute(element, name) {
5
7
  const value = element.getAttribute(name);
6
8
  if (value === null || value.trim() === '')
@@ -14,7 +16,6 @@ function mountSlot(host, css) {
14
16
  style.textContent = css;
15
17
  const slot = document.createElement('slot');
16
18
  host.attachShadow({ mode: 'open' }).append(style, slot);
17
- return slot;
18
19
  }
19
20
  /** Register the two custom elements explicitly. Safe to import on the server and to call twice. */
20
21
  export function defineStickerElements() {
@@ -45,10 +46,17 @@ export function defineStickerElements() {
45
46
  static observedAttributes = ['rotate', 'finish', 'cut', 'border', 'fill-holes', 'sticker-id'];
46
47
  #dispose;
47
48
  #queued = false;
48
- #observer = new MutationObserver(() => this.#schedule());
49
+ #artwork = null;
50
+ #observer = new MutationObserver(records => {
51
+ const artwork = this.querySelector(ARTWORK);
52
+ // Changing img inside the same picture doesn't fire slotchange. Edits *inside* the
53
+ // same svg, on the other hand, are handled by mountSticker without replacing the sticker.
54
+ if (artwork !== this.#artwork || records.some(r => r.type === 'attributes' && r.target === artwork))
55
+ this.#schedule();
56
+ });
49
57
  constructor() {
50
58
  super();
51
- const slot = mountSlot(this, `
59
+ mountSlot(this, `
52
60
  :host {
53
61
  display: inline-block;
54
62
  width: var(--peel-width, auto);
@@ -56,7 +64,7 @@ export function defineStickerElements() {
56
64
  line-height: 0;
57
65
  user-select: none;
58
66
  }
59
- ::slotted(img) {
67
+ ::slotted(img), ::slotted(svg) {
60
68
  display: block;
61
69
  width: 100%;
62
70
  height: auto;
@@ -65,16 +73,16 @@ export function defineStickerElements() {
65
73
  }
66
74
  ::slotted(picture) { display: block; }
67
75
  `);
68
- slot.addEventListener('slotchange', () => this.#schedule());
69
76
  }
70
77
  connectedCallback() {
71
- this.#observer.observe(this, { subtree: true, attributes: true, attributeFilter: ['width'] });
78
+ this.#observer.observe(this, { subtree: true, childList: true, attributeFilter: ['width'] });
72
79
  this.#schedule();
73
80
  }
74
81
  disconnectedCallback() {
75
82
  this.#observer.disconnect();
76
83
  this.#dispose?.();
77
84
  this.#dispose = undefined;
85
+ this.#artwork = null;
78
86
  }
79
87
  attributeChangedCallback() {
80
88
  this.#schedule();
@@ -92,9 +100,8 @@ export function defineStickerElements() {
92
100
  #mount() {
93
101
  this.#dispose?.();
94
102
  this.#dispose = undefined;
95
- // The artwork is the img, on its own or in a picture that offers it in other formats.
96
- const image = this.querySelector(':scope > img, :scope > picture > img');
97
- const widthAttr = image ? numberAttribute(image, 'width') : undefined;
103
+ const artwork = this.#artwork = this.querySelector(ARTWORK);
104
+ const widthAttr = artwork ? numberAttribute(artwork, 'width') : undefined;
98
105
  const width = widthAttr !== undefined && widthAttr > 0 ? widthAttr : undefined;
99
106
  if (width === undefined)
100
107
  this.style.removeProperty('--peel-width');
@@ -103,11 +110,11 @@ export function defineStickerElements() {
103
110
  const rotation = numberAttribute(this, 'rotate') ?? 0;
104
111
  this.style.setProperty('--peel-rotation', `${rotation}deg`);
105
112
  const engine = this.closest(PROVIDER_TAG)?.engine ?? null;
106
- if (!image || !engine)
113
+ if (!artwork || !engine)
107
114
  return;
108
115
  const cut = this.getAttribute('cut');
109
116
  const border = numberAttribute(this, 'border');
110
- this.#dispose = mountSticker(engine, image, {
117
+ this.#dispose = mountSticker(engine, artwork, {
111
118
  anchor: this,
112
119
  width,
113
120
  rotation,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@patrick91/stickers",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Peelable WebGL stickers for plain JavaScript, Web Components, React, and Svelte.",
5
5
  "keywords": ["stickers", "peel", "drag", "webgl", "webgl2", "web-components", "custom-elements", "react", "svelte"],
6
6
  "license": "MIT",