PageSourceSearch

https://rankimpact.com/image-slot.js

js rankimpact.com collected 2026-10-10 02:20:15 UTC 65,350 bytes, 1,225 lines download raw bytes

1// @ds-adherence-ignore -- omelette starter scaffold (raw elements/hex/px by design)
2// Copied omelette starter. Re-running copy_starter_component with this kind overwrites this file with the latest version (page content is unaffected).
3/* BEGIN USAGE */
4/**
5 * <image-slot> — user-fillable image placeholder.
6 *
7 * Drop this into a deck, mockup, or page wherever a design needs an image.
8 * You control the slot's shape; it sizes to its container by default. When the search_stock_photos tool
9 * is available, prefill the slot by default — write the photo's URL into
10 * src (with credit/credit-href); the user can still fill or replace it
11 * by dragging an image file onto it (or clicking to browse). The dropped
12 * image persists across reloads via a .image-slots.state.json sidecar —
13 * same read-via-fetch / write-via-window.omelette pattern as
14 * design_canvas.jsx, so the filled slot shows on share links, downloaded
15 * zips, and PPTX export. Outside the omelette runtime the slot is read-only.
16 *
17 * The sidecar is a SIBLING of the HTML file that uses this component: the
18 * read is a document-relative fetch, and the host resolves the bridge's
19 * sidecar writes into the previewed file's directory to match (same
20 * contract as design_canvas.jsx). Pages in the same directory share one
21 * sidecar; keep slot ids distinct across them.
22 *
23 * Attributes:
24 *   id           Persistence key. REQUIRED for the drop to survive reload —
25 *                every slot on the page needs a distinct id.
26 *   shape        'rect' | 'rounded' | 'circle' | 'pill'   (default 'rounded')
27 *                'circle' applies 50% border-radius; on a non-square slot
28 *                that's an ellipse — set equal width and height for a true
29 *                circle.
30 *   radius       Corner radius in px for 'rounded'.       (default 12)
31 *   mask         Any CSS clip-path value. Overrides `shape` — use this for
32 *                hexagons, blobs, arbitrary polygons.
33 *   fit          Initial framing baseline: cover | contain.   (default 'cover')
34 *                cover starts the image filling the frame (overflow cropped);
35 *                contain starts it fully visible (letterboxed). Either way the
36 *                user can always pan/scale from there — double-click, or the
37 *                Edit control, enters reframe mode (drag to move, scroll or
38 *                corner-handles to scale; Escape / click-out commits). The
39 *                crop persists alongside the image in the sidecar.
40 *   placeholder  Empty-state caption.                      (default 'Drop an image')
41 *   src          Optional initial/fallback image URL. Prefill it with a real
42 *                photo via search_stock_photos when that tool is available
43 *                (set credit/credit-href from the result). A user drop
44 *                overrides it; clearing the drop reveals src again.
45 *   credit       Attribution text shown as a small overlay at the
46 *                bottom-left of the filled slot. REQUIRED whenever src
47 *                points at any Unsplash host (images.unsplash.com,
48 *                plus.unsplash.com, …): an Unsplash src with no credit
49 *                renders an error tile INSTEAD of the photo (Unsplash
50 *                terms forbid showing their photos unattributed). Use the
51 *                exact form 'Photo by {photographer name} on Unsplash' —
52 *                the overlay then links the name to credit-href and
53 *                'Unsplash' to the Unsplash homepage, and links back to
54 *                unsplash.com automatically get the required utm referral
55 *                params appended at render time. The credit belongs to
56 *                the src image, so it only shows while src is what's
57 *                displayed — a user-dropped image hides it.
58 *   credit-href  Link for the photographer's name in the credit overlay
59 *                (their Unsplash profile URL from the stock-photo search
60 *                results). http(s) URLs only — anything else renders the
61 *                name as plain text.
62 *
63 * Sizing: the slot fills its container by default (width/height 100%).
64 * Put it in a sized wrapper — absolutely positioned, a grid cell, a fixed
65 * frame — and it takes exactly that box. When the parent's height is
66 * indefinite (ordinary flow), it falls back to full width at a 3:2 aspect
67 * ratio instead of collapsing. In a shrink-to-fit parent (a float,
68 * width:max-content, an unsized absolute wrapper), percentages have
69 * nothing to resolve against — size the slot or its wrapper explicitly
70 * there. For a fixed-size slot, set
71 * width/height on the element itself (inline style), which overrides the
72 * default. When
73 * layering content above a slot (full-bleed layouts), make the overlay
74 * click-through — pointer-events: none on scrims/text plates, re-enabled
75 * on interactive children — so the slot's hover controls stay reachable.
76 * Keep the slot's bottom-left corner visually clear as well: the credit
77 * overlay renders there, and a dark fade or text plate covering it hides
78 * the attribution Unsplash's terms require — end the fade above that
79 * corner, or keep it nearly transparent where the credit sits.
80 *
81 * Usage:
82 *   <div style="position:relative;width:100%;height:100%">      <!-- full-bleed: -->
83 *     <image-slot id="bg" shape="rect"></image-slot>            <!-- fills the wrapper -->
84 *   </div>
85 *   <image-slot id="hero"   style="width:800px;height:450px" shape="rounded" radius="20"
86 *               placeholder="Drop a hero image"></image-slot>
87 *   <image-slot id="avatar" style="width:120px;height:120px" shape="circle"></image-slot>
88 *   <image-slot id="kite"   style="width:300px;height:300px"
89 *               mask="polygon(50% 0, 100% 50%, 50% 100%, 0 50%)"></image-slot>
90 */
91/* END USAGE */
92
93(() => {
94  const STATE_FILE = '.image-slots.state.json';
95
96  // Unsplash terms require visible attribution wherever their photos
97  // display, and every link back to unsplash.com must carry utm referral
98  // params. Two render-time rules enforce that here:
99  //  - an Unsplash-src slot with NO credit attribute renders an error
100  //    tile INSTEAD of the photo (an uncredited Unsplash photo on screen
101  //    is itself the terms violation, so it never renders bare);
102  //  - rendered credit links pointing at unsplash.com get the referral
103  //    params appended when absent (credit-href values live in page
104  //    content that can't be edited after the fact).
105  // Keep the utm_source value in sync with UTM_SOURCE in
106  // platform/web-agent/unsplash.ts — this file is a project-local
107  // artifact and cannot import it (equality is pinned by tests).
108  const UNSPLASH_HOMEPAGE_HREF =
109    'https://unsplash.com/?utm_source=claude_design&utm_medium=referral';
110  // Host rule mirrors the hotlink validator that admits Unsplash srcs into
111  // pages in the first place (cdn$ in unsplash.ts: apex or any subdomain)
112  // — Unsplash+ results serve from plus.unsplash.com, not just images.*,
113  // and an admitted-but-uncredited photo must error whatever unsplash
114  // host it rides on.
115  // Trailing-dot FQDNs (images.unsplash.com.) are the same host to the
116  // browser but would miss the regex — strip one dot so the check fails
117  // CLOSED (unrecognized-but-real Unsplash srcs must error, not render).
118  const isUnsplashHost = (u) => {
119    try {
120      return /(^|\.)unsplash\.com$/.test(
121        new URL(u, document.baseURI).hostname.replace(/\.$/, '')
122      );
123    } catch {
124      return false;
125    }
126  };
127  // Render-time referral normalization for links back to Unsplash:
128  // appends utm_source/utm_medium when absent, preserves every existing
129  // query param, never overwrites an existing utm_source, and passes
130  // non-Unsplash URLs through untouched. Input is an ABSOLUTE validated
131  // http(s) URL (the credit render funnel resolves + validates first).
132  const withReferral = (href) => {
133    try {
134      const u = new URL(href);
135      if (!/(^|\.)unsplash\.com$/.test(u.hostname.replace(/\.$/, ''))) {
136        return href;
137      }
138      if (!u.searchParams.has('utm_source')) {
139        u.searchParams.set('utm_source', 'claude_design');
140      }
141      if (!u.searchParams.has('utm_medium')) {
142        u.searchParams.set('utm_medium', 'referral');
143      }
144      return u.toString();
145    } catch (e) {
146      return href;
147    }
148  };
149  // 2× a ~600px slot in a 1920-wide deck — retina-sharp without making the
150  // sidecar enormous. A 1200px WebP at q=0.85 is ~150-300KB.
151  const MAX_DIM = 1200;
152  // Raster formats only. SVG is excluded (can carry script; createImageBitmap
153  // on SVG blobs is inconsistent). GIF is excluded because the canvas
154  // re-encode keeps only the first frame, so an animated GIF would silently
155  // go still — better to reject than surprise.
156  const ACCEPT = ['image/png', 'image/jpeg', 'image/webp', 'image/avif'];
157
158  // ── Shared sidecar store ────────────────────────────────────────────────
159  // One fetch + immediate write-on-change for every <image-slot> on the
160  // page. Reads via fetch() so viewing works anywhere the HTML and sidecar
161  // are served together; writes go through window.omelette.writeFile, which
162  // the host allowlists to *.state.json basenames only.
163  const subs = new Set();
164  let slots = {};
165  // ids explicitly cleared before the sidecar fetch resolved — otherwise
166  // the merge below can't tell "never set" from "just deleted" and would
167  // resurrect the sidecar's stale value.
168  const tombstones = new Set();
169  let loaded = false;
170  let loadP = null;
171
172  function load() {
173    if (loadP) return loadP;
174    loadP = fetch(STATE_FILE)
175      .then((r) => (r.ok ? r.json() : null))
176      .then((j) => {
177        // Merge: sidecar loses to any in-memory change that raced ahead of
178        // the fetch (drop or clear) so neither is clobbered by hydration.
179        if (j && typeof j === 'object') {
180          const merged = Object.assign({}, j, slots);
181          // A framing-only write that raced ahead of hydration must not
182          // drop a user image that's only on disk — inherit u from the
183          // sidecar for any in-memory entry that lacks one.
184          for (const k in slots) {
185            if (merged[k] && !merged[k].u && j[k]) {
186              merged[k].u = typeof j[k] === 'string' ? j[k] : j[k].u;
187            }
188          }
189          for (const id of tombstones) delete merged[id];
190          slots = merged;
191        }
192        tombstones.clear();
193      })
194      .catch(() => {})
195      .then(() => { loaded = true; subs.forEach((fn) => fn()); });
196    return loadP;
197  }
198
199  // Serialize writes so two near-simultaneous drops on different slots
200  // can't reorder at the backend and leave the sidecar with only the
201  // first. A save requested mid-flight just marks dirty and re-fires on
202  // completion with the then-current slots.
203  let saving = false;
204  let saveDirty = false;
205  // Unload-time flush: save()'s serialization defers a mid-RTT re-fire to a
206  // .then that never runs in an unloading document, silently dropping a
207  // pagehide commit. Post the current slots immediately instead — content
208  // is a superset snapshot of any in-flight save's, the write is a
209  // whole-file last-writer-wins replace, and postMessage FIFO delivers it
210  // to the host after the in-flight one, so a backend-side reorder at
211  // worst reproduces the dropped-commit outcome this flush improves on.
212  // Guarded on the initial sidecar read: pre-hydration slots can miss
213  // other slots' persisted entries, and flushing it would clobber them —
214  // that narrow case stays best-effort (the in-memory merge in load()
215  // cannot happen in an unloading document anyway).
216  function flushNow() {
217    if (!loaded) return;
218    const w = window.omelette && window.omelette.writeFile;
219    if (!w) return;
220    try { Promise.resolve(w(STATE_FILE, JSON.stringify(slots))).catch(() => {}); } catch (e) {}
221  }
222  function save() {
223    if (saving) { saveDirty = true; return; }
224    const w = window.omelette && window.omelette.writeFile;
225    if (!w) return;
226    saving = true;
227    Promise.resolve(w(STATE_FILE, JSON.stringify(slots)))
228      .catch(() => {})
229      .then(() => { saving = false; if (saveDirty) { saveDirty = false; save(); } });
230  }
231
232  const S_MAX = 5;
233  const clampS = (s) => Math.max(1, Math.min(S_MAX, s));
234
235  // Normalize a stored slot value. Pre-reframe sidecars stored a bare
236  // data-URL string; newer ones store {u, s, x, y}. Either shape is valid.
237  function getSlot(id) {
238    const v = slots[id];
239    if (!v) return null;
240    return typeof v === 'string' ? { u: v, s: 1, x: 0, y: 0 } : v;
241  }
242
243  function setSlot(id, val) {
244    if (!id) return;
245    if (val) { slots[id] = val; tombstones.delete(id); }
246    else { delete slots[id]; if (!loaded) tombstones.add(id); }
247    subs.forEach((fn) => fn());
248    // A drop is rare + high-value — write immediately so nav-away can't lose
249    // it. Gate on the initial read so we don't overwrite a sidecar we haven't
250    // merged yet; the merge in load() keeps this change once the read lands.
251    if (loaded) save(); else load().then(save);
252  }
253
254  // ── Image downscale ─────────────────────────────────────────────────────
255  // Encode through a canvas so the sidecar carries resized bytes, not the
256  // raw upload. Longest side is capped at 2× the slot's rendered width
257  // (retina) and at MAX_DIM. WebP keeps alpha and is ~10× smaller than PNG
258  // for photos, so there's no need for per-image format picking.
259  async function toDataUrl(file, targetW) {
260    const bitmap = await createImageBitmap(file);
261    try {
262      const cap = Math.min(MAX_DIM, Math.max(1, Math.round(targetW * 2)) || MAX_DIM);
263      const scale = Math.min(1, cap / Math.max(bitmap.width, bitmap.height));
264      const w = Math.max(1, Math.round(bitmap.width * scale));
265      const h = Math.max(1, Math.round(bitmap.height * scale));
266      const canvas = document.createElement('canvas');
267      canvas.width = w; canvas.height = h;
268      canvas.getContext('2d').drawImage(bitmap, 0, 0, w, h);
269      return canvas.toDataURL('image/webp', 0.85);
270    } finally {
271      bitmap.close && bitmap.close();
272    }
273  }
274
275  // ── Custom element ──────────────────────────────────────────────────────
276  const stylesheet =
277    // Fill the container by default: slots are usually placed inside a
278    // sized wrapper (a hero frame, a grid cell, an inset:0 layer) and are
279    // expected to take that box — a fixed intrinsic size would render as
280    // a small tile in the corner of a full-bleed wrapper instead.
281    // aspect-ratio is the companion fallback that keeps a bare slot
282    // visible when the parent's height is indefinite: height:100%
283    // resolves to auto there, and the ratio then derives height from
284    // width instead of letting the slot collapse to zero height.
285    // Explicit width/height on the element override all of this.
286    // color:inherit (not a fixed near-black): the placeholder chrome —
287    // empty-state icon/caption (currentColor) and the dashed ring — must
288    // read on dark decks too, and the slide's own text color is the one
289    // color guaranteed to contrast with the slide background. The soft
290    // look comes from opacity on those parts, not from a baked-in alpha.
291    ':host{display:block;position:relative;' +
292    '  font:13px/1.3 system-ui,-apple-system,sans-serif;' +
293    '  width:100%;height:100%;aspect-ratio:3/2}' +
294    '.empty .cap,.empty .sub{opacity:.75}' +
295    '.frame{position:absolute;inset:0;overflow:hidden;background:rgba(127,127,127,.08)}' +
296    // .frame img (clipped) and .spill (unclipped ghost + handles) share the
297    // same left/top/width/height in frame-%, computed by _applyView(), so the
298    // inside-mask crop and the outside-mask spill stay pixel-aligned.
299    '.frame img{position:absolute;max-width:none;transform:translate(-50%,-50%);' +
300    '  -webkit-user-drag:none;user-select:none;touch-action:none}' +
301    // Reframe mode (double-click): the full image spills past the mask. The
302    // spill layer is sized to the IMAGE bounds so its corners are where the
303    // resize handles belong. The ghost <img> inside is translucent; the real
304    // clipped <img> underneath shows the opaque in-mask crop.
305    // popover=manual promotes the spill to the top layer on reframe, so it is
306    // not clipped by any overflow:hidden / clip-path / scroll-container
307    // ancestor (a plain z-index can't escape overflow clipping). UA popover
308    // defaults (inset:0;margin:auto) are reset; _applyView sets viewport px.
309    '.spill{position:fixed;margin:0;inset:auto;border:0;padding:0;background:transparent;' +
310    '  overflow:visible;transform:translate(-50%,-50%);z-index:1;cursor:grab;touch-action:none}' +
311    ':host([data-panning]) .spill{cursor:grabbing}' +
312    '.spill .ghost{position:absolute;inset:0;width:100%;height:100%;opacity:.35;' +
313    '  pointer-events:none;-webkit-user-drag:none;user-select:none;' +
314    '  box-shadow:0 0 0 1px rgba(0,0,0,.2),0 12px 32px rgba(0,0,0,.2)}' +
315    '.spill .handle{position:absolute;width:12px;height:12px;border-radius:50%;' +
316    '  background:#fff;box-shadow:0 0 0 1.5px #c96442,0 1px 3px rgba(0,0,0,.3);' +
317    '  transform:translate(-50%,-50%)}' +
318    '.spill .handle[data-c=nw]{left:0;top:0;cursor:nwse-resize}' +
319    '.spill .handle[data-c=ne]{left:100%;top:0;cursor:nesw-resize}' +
320    '.spill .handle[data-c=sw]{left:0;top:100%;cursor:nesw-resize}' +
321    '.spill .handle[data-c=se]{left:100%;top:100%;cursor:nwse-resize}' +
322    ':host([data-reframe]){z-index:10}' +
323    ':host([data-reframe]) .frame{box-shadow:0 0 0 2px #c96442}' +
324    '.empty{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;' +
325    '  justify-content:center;gap:6px;text-align:center;padding:12px;box-sizing:border-box;' +
326    '  cursor:pointer;user-select:none}' +
327    '.empty svg{opacity:.45}' +
328    '.empty .cap{max-width:90%;font-weight:500;letter-spacing:.01em}' +
329    '.empty .sub{font-size:11px}' +
330    '.empty .sub u{text-underline-offset:2px}' +
331    '.empty:hover .sub{opacity:1}' +
332    ':host([data-over]) .frame{outline:2px solid #c96442;outline-offset:-2px;' +
333    '  background:rgba(201,100,66,.10)}' +
334    '.ring{position:absolute;inset:0;pointer-events:none;border:1.5px dashed currentColor;' +
335    '  opacity:.35;transition:border-color .12s,opacity .12s}' +
336    ':host([data-over]) .ring{border-color:#c96442;opacity:1}' +
337    ':host([data-filled]) .ring{display:none}' +
338    // Controls overlay INSIDE the frame, pinned to the top-right corner, so
339    // a full-bleed slot in an overflow:hidden container still shows them
340    // (the old below-mask placement got clipped). Credit sits bottom-left,
341    // so top-right avoids collision. The blurred pill background keeps them
342    // legible over the image.
343    // The UA [popover] base rule styles the element in EVERY state (only
344    // display:none is gated on :not(:popover-open), and the display:flex
345    // below overrides that) — so the UA resets live HERE, like .spill's,
346    // or the ordinary hover-state strip renders as a bordered Canvas box
347    // centered by margin:auto. inset:auto precedes top/right (shorthand).
348    '.ctl{position:absolute;inset:auto;top:8px;right:8px;margin:0;border:0;padding:0;' +
349    '  background:transparent;overflow:visible;' +
350    '  display:flex;gap:6px;opacity:0;pointer-events:none;transition:opacity .12s;z-index:2;' +
351    '  white-space:nowrap}' +
352    // While reframing, the spill owns the top layer and would swallow every
353    // click on the in-frame controls. Promoting .ctl into the top layer
354    // ABOVE the spill (shown after it — later popovers stack higher) keeps
355    // Edit-as-toggle and Replace clickable mid-reframe. _applyView pins it
356    // to the frame's top-right in viewport px (translateX(-100%)
357    // right-aligns against the computed left edge); inset:auto clears the
358    // base rule's top/right so the inline left/top position it alone.
359    '.ctl:popover-open{position:fixed;inset:auto;transform:translateX(-100%)}' +
360    ':host([data-filled][data-editable]:hover) .ctl,:host([data-reframe]) .ctl' +
361    '  {opacity:1;pointer-events:auto}' +
362    '.ctl button{appearance:none;border:0;border-radius:6px;padding:5px 10px;cursor:pointer;' +
363    '  background:rgba(0,0,0,.65);color:#fff;font:11px/1 system-ui,-apple-system,sans-serif;' +
364    '  backdrop-filter:blur(6px)}' +
365    '.ctl button:hover{background:rgba(0,0,0,.8)}' +
366    '.err{position:absolute;left:8px;bottom:8px;right:8px;color:#b3261e;font-size:11px;' +
367    '  background:rgba(255,255,255,.85);padding:4px 6px;border-radius:5px;pointer-events:none}' +
368    // Replacement in flight: after a src swap the browser keeps painting
369    // the PREVIOUS image until the new one decodes, so a Replace would
370    // flash the old photo and then pop. Hide the stale frame (visibility,
371    // not display — _applyView geometry still applies) and spin until the
372    // new image reports in (load/error clears data-swapping).
373    ':host([data-swapping]) .frame img{visibility:hidden}' +
374    '.loading{position:absolute;inset:0;display:none;align-items:center;' +
375    '  justify-content:center;pointer-events:none}' +
376    ':host([data-swapping]) .loading{display:flex}' +
377    '.loading::after{content:"";width:22px;height:22px;border-radius:50%;' +
378    '  border:2px solid rgba(127,127,127,.25);border-top-color:currentColor;' +
379    '  animation:om-slot-spin .7s linear infinite}' +
380    '@keyframes om-slot-spin{to{transform:rotate(360deg)}}' +
381    // Reduced motion: the static two-tone ring still reads as "working".
382    '@media (prefers-reduced-motion:reduce){.loading::after{animation:none}}' +
383    '.credit{position:absolute;left:6px;bottom:6px;max-width:calc(100% - 12px);display:none;' +
384    '  padding:3px 7px;border-radius:5px;background:rgba(0,0,0,.55);color:#fff;' +
385    '  font:10px/1.2 system-ui,-apple-system,sans-serif;text-decoration:none;' +
386    '  white-space:nowrap;overflow:hidden;text-overflow:ellipsis;backdrop-filter:blur(6px)}' +
387    // The credit is a SPAN holding one or two <a>s (Unsplash's prescribed
388    // form links the photographer AND Unsplash) — anchors style inline so
389    // the overlay reads as one line of text.
390    '.credit a{color:inherit;text-decoration:none}' +
391    '.credit a:hover,.credit a:focus-visible{text-decoration:underline}' +
392    ':host([data-filled][data-credit]) .credit{display:block}' +
393    // Exports must ship JUST the image — no hover controls, no credit chip
394    // (the host marks <html data-om-exporting> for the capture window; the
395    // page-level hide script can't reach shadow DOM, this rule can).
396    ':host-context([data-om-exporting]) .ctl,' +
397    ':host-context([data-om-exporting]) .credit{display:none !important}' +
398    // Print must ship just the image too: the hover-gated controls can be
399    // mid-hover when print() fires, and the credit chip is screen chrome —
400    // the same rule the capture window gets, keyed on print media instead
401    // of the host's data-om-exporting mark (the print path sets no mark).
402    '@media print{.ctl,.credit{display:none !important}}' +
403    // No export-window mask rules here on purpose: the export capture
404    // releases the replacement mask by REMOVING data-swapping (the
405    // shadow-root pass in pages/export/shared.ts HIDE_EXPORT_CHROME_SCRIPT)
406    // — attribute removal works in every engine (:host-context is
407    // Chromium-only), is scoped by construction to slots actually
408    // mid-swap, and hides the spinner through the same gate. A masked img
409    // would otherwise be silently dropped from PPTX decks (the capture
410    // walk skips visibility:hidden imgs).
411    // Attribution error tile: REPLACES the photo when an Unsplash src has
412    // no credit attribute — rendering the photo uncredited is the terms
413    // violation, so the photo must not appear at all.
414    // Calm and neutral on purpose (review feedback): the tile informs the
415    // user; the fix instructions are machine-facing (usage docblock, tool
416    // description, and the turn-end scan's bounce copy name the attributes
417    // for the agent).
418    '.attr-error{position:absolute;inset:0;display:none;flex-direction:column;align-items:center;' +
419    '  justify-content:center;gap:6px;text-align:center;padding:12px;box-sizing:border-box;' +
420    '  background:#f2f1ef;color:#6e6c66;user-select:none;' +
421    '  font:13px/1.45 system-ui,-apple-system,sans-serif}' +
422    '.attr-error svg{opacity:.55}' +
423    '.attr-error .cap{max-width:92%;font-weight:500;letter-spacing:.01em}' +
424    ':host([data-attribution-error]) .attr-error{display:flex}' +
425    ':host([data-attribution-error]) .ring{display:none}';
426
427  const icon =
428    '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
429    'stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' +
430    '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/>' +
431    '<path d="m21 15-5-5L5 21"/></svg>';
432
433  const warnIcon =
434    '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
435    'stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' +
436    '<path d="m21.73 18-8-14a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/>' +
437    '<path d="M12 9v4"/><path d="M12 17h.01"/></svg>';
438
439  class ImageSlot extends HTMLElement {
440    static get observedAttributes() {
441      return ['shape', 'radius', 'mask', 'fit', 'placeholder', 'src', 'id', 'credit', 'credit-href'];
442    }
443
444    /** Duplicate-slide hook (called by deck-stage, see its
445     *  _remintDuplicateIds): copy this id's stored image, if any, under a
446     *  freshly minted key and return that key — so a duplicated slide's
447     *  slot keeps its dropped photo instead of reverting to the
448     *  placeholder. 'isFree' is the caller's uniqueness check (document
449     *  ids); candidates must ALSO be unused in the sidecar, which can
450     *  hold keys from other pages sharing the project root. (An EMPTY
451     *  slot on another page leaves no sidecar entry, so its id is not
452     *  detectable here — a minted key can collide with it and that slot
453     *  would show this photo. Same blast radius as two pages reusing an
454     *  id by hand, which the shared sidecar already permits.) Returns null
455     *  when no id could be minted (caller strips the id, today's
456     *  behavior). */
457    static cloneSlot(fromId, isFree) {
458      if (typeof fromId !== 'string' || !fromId) return null;
459      // Pre-hydration the store can't veto candidates or source the copy
460      // — degrade to the strip (today's behavior) rather than mint
461      // against keys we can't see yet. Any rendered (= droppable) slot
462      // means load() has already settled.
463      if (!loaded) return null;
464      const stem = fromId.replace(/-\d+$/, '') || fromId;
465      for (let n = 2; n < 100; n++) {
466        const toId = stem + '-' + n;
467        if (toId === fromId) continue;
468        if (slots[toId] !== undefined) {
469          // Reuse a key holding this exact value (bytes AND crop) if no
470          // live element here owns it — a duplicate op the host refused
471          // after minting leaves such a key behind, and reusing keeps
472          // refused retries from accumulating one orphaned copy per
473          // attempt. Full equality (not just bytes) so a byte-identical
474          // key another PAGE owns with its own crop is stepped past, not
475          // adopted or rewritten. (Entries without .u never match.)
476          const prev = getSlot(toId);
477          const cur = getSlot(fromId);
478          if (!(prev && cur && prev.u && prev.u === cur.u &&
479                prev.s === cur.s && prev.x === cur.x && prev.y === cur.y &&
480                (typeof isFree !== 'function' || isFree(toId)))) continue;
481          return toId;
482        }
483        if (typeof isFree === 'function' && !isFree(toId)) continue;
484        const v = getSlot(fromId);
485        if (v) setSlot(toId, Object.assign({}, v));
486        return toId;
487      }
488      return null;
489    }
490
491    constructor() {
492      super();
493      // clonable: rail thumbnails deep-clone slides and carry this shadow
494      // along; reuse an already-cloned root so upgrade-after-clone works.
495      // (Deliberately NOT serializable — a getHTML consumer would embed
496      // multi-MB sidecar data-URLs into serialized page HTML.)
497      const root = this.shadowRoot ||
498        this.attachShadow({ mode: 'open', clonable: true });
499      // .spill and .ctl sit OUTSIDE .frame so overflow:hidden + border-radius
500      // on the frame (circle, pill, rounded) can't clip them.
501      root.innerHTML =
502        '<style>' + stylesheet + '</style>' +
503        '<div class="frame" part="frame">' +
504        '  <img part="image" alt="" draggable="false" style="display:none">' +
505        '  <div class="empty" part="empty">' + icon +
506        '    <div class="cap"></div>' +
507        '    <div class="sub">or <u>browse files</u></div></div>' +
508        '  <div class="attr-error" part="attribution-error">' + warnIcon +
509        '    <div class="cap">This photo needs attribution</div></div>' +
510        '  <div class="loading" part="loading"></div>' +
511        '  <div class="ring" part="ring"></div>' +
512        '</div>' +
513        // Outside .frame, like .spill/.ctl — the frame's overflow:hidden +
514        // border-radius/clip-path would cut the credit off on circle/pill/mask.
515        // A SPAN, not an <a>: the prescribed Unsplash credit holds two links
516        // (photographer + Unsplash), built per-render in _render().
517        '<span class="credit" part="credit"></span>' +
518        '<div class="spill" popover="manual" data-dc-edit-transparent>' +
519        '  <img class="ghost" alt="" draggable="false">' +
520        '  <div class="handle" data-c="nw"></div><div class="handle" data-c="ne"></div>' +
521        '  <div class="handle" data-c="sw"></div><div class="handle" data-c="se"></div>' +
522        '</div>' +
523        // data-dc-edit-transparent: the DC editor's edit-mode picker lets
524        // clicks through for chrome marked with it (EDIT_TRANSPARENT_SEL)
525        // — without it, Replace/Edit clicks in Edit mode are swallowed by
526        // element selection and the controls look dead.
527        '<div class="ctl" popover="manual" data-dc-edit-transparent><button data-act="replace" title="Replace image">Replace</button>' +
528        '  <button data-act="edit" title="Reframe image">Edit</button></div>' +
529        '<input type="file" accept="' + ACCEPT.join(',') + '" hidden>';
530      this._frame = root.querySelector('.frame');
531      this._ring = root.querySelector('.ring');
532      this._img = root.querySelector('.frame img');
533      this._empty = root.querySelector('.empty');
534      this._cap = root.querySelector('.cap');
535      this._sub = root.querySelector('.sub');
536      this._spill = root.querySelector('.spill');
537      this._ctl = root.querySelector('.ctl');
538      this._credit = root.querySelector('.credit');
539      this._attrError = root.querySelector('.attr-error');
540      // Credit clicks open the link, not browse/reframe.
541      this._credit.addEventListener('click', (e) => e.stopPropagation());
542      this._credit.addEventListener('dblclick', (e) => e.stopPropagation());
543      this._ghost = root.querySelector('.ghost');
544      this._err = null;
545      this._input = root.querySelector('input');
546      this._depth = 0;
547      this._gen = 0;
548      // Encode-in-flight marker (the owning _ingest generation): while set,
549      // the same-src "nothing in flight" clear in _render must not fire —
550      // the stored value still points at the OLD image until the encode
551      // lands, so that clear would unmask the stale image mid-replace.
552      this._swapGen = 0;
553      // Render-owned swap in flight: set when _render assigns a new src,
554      // cleared only by the img's own load/error (or the empty branch).
555      // img.complete CANNOT stand in for this — setting src only QUEUES
556      // the current-request swap (a microtask), so synchronously after an
557      // assignment, complete still reports the OLD settled request. The
558      // pick path does exactly that: the host sets src, credit, and
559      // credit-href back-to-back in one task, and renders #2/#3 would
560      // read the stale complete === true and drop the mask one render
561      // after it was set.
562      this._loadPending = false;
563      // See _render's empty branch: a transient attribution-error wipe of a
564      // showing image must make the follow-up render a replacement (spinner),
565      // not a first fill (blank frame).
566      this._hidShowing = false;
567      this._view = { s: 1, x: 0, y: 0 };
568      this._subFn = () => this._render();
569      // Shadow-DOM listeners live with the shadow DOM — bound once here so
570      // disconnect/reconnect (e.g. React remount) doesn't stack handlers.
571      this._empty.addEventListener('click', () => this._input.click());
572      root.addEventListener('click', (e) => {
573        const act = e.target && e.target.getAttribute && e.target.getAttribute('data-act');
574        if (!act) return;
575        // The hidden controls are opacity-0 but still tabbable — without
576        // this gate a keyboard user could drive them on a read-only share
577        // link (mirrors the dblclick handler's editable gate).
578        if (!this.hasAttribute('data-editable')) return;
579        if (act === 'replace') {
580          this._exitReframe(true);
581          // Host-owned picker (Unsplash modal; it also offers local import).
582          this.dispatchEvent(new CustomEvent('image-slot:pick', {
583            bubbles: true, composed: true, detail: { id: this.id || null }
584          }));
585        }
586        if (act === 'edit') {
587          if (!this._reframes()) return;
588          if (this.hasAttribute('data-reframe')) this._exitReframe(true);
589          else this._enterReframe();
590        }
591      });
592      this._input.addEventListener('change', () => {
593        const f = this._input.files && this._input.files[0];
594        if (f) this._ingest(f);
595        this._input.value = '';
596      });
597      // naturalWidth/Height aren't known until load — re-apply so the cover
598      // baseline is computed from real dimensions, not the 100%×100% fallback.
599      // load/error also release the replacement-in-flight mask (via the
600      // single discipline in _releaseMask): the swap is only revealed once
601      // the new image can actually paint (on error the frame shows its
602      // background, same as a fresh slot with a broken src).
603      this._img.addEventListener('load', () => {
604        this._loadPending = false;
605        this._releaseMask(true);
606        this._applyView();
607      });
608      this._img.addEventListener('error', () => {
609        this._loadPending = false;
610        this._releaseMask(true);
611      });
612      // Gated only on editable — any filled slot can be repositioned/scaled,
613      // regardless of fit. Share links (no writeFile) stay static.
614      this.addEventListener('dblclick', (e) => {
615        if (!this.hasAttribute('data-editable') || !this._reframes()) return;
616        e.preventDefault();
617        if (this.hasAttribute('data-reframe')) this._exitReframe(true);
618        else this._enterReframe();
619      });
620      // Pan + resize both originate on the spill layer. A handle pointerdown
621      // drives an aspect-locked resize anchored at the opposite corner; any
622      // other pointerdown on the spill pans. Offsets are frame-% so a
623      // reframed slot survives responsive resize / PPTX export.
624      this._spill.addEventListener('pointerdown', (e) => {
625        if (e.button !== 0 || !this.hasAttribute('data-reframe')) return;
626        e.preventDefault();
627        e.stopPropagation();
628        this._spill.setPointerCapture(e.pointerId);
629        const rect = this.getBoundingClientRect();
630        const fw = rect.width || 1, fh = rect.height || 1;
631        const corner = e.target.getAttribute && e.target.getAttribute('data-c');
632        let move;
633        if (corner) {
634          // Resize about the OPPOSITE corner. Viewport-px throughout (rect
635          // fw/fh, not clientWidth) so the math survives a transform:scale()
636          // ancestor — deck_stage renders slides scaled-to-fit.
637          const iw = this._img.naturalWidth || 1, ih = this._img.naturalHeight || 1;
638          const contain = (this.getAttribute('fit') || 'cover').toLowerCase() === 'contain';
639          const base = contain ? Math.min(fw / iw, fh / ih) : Math.max(fw / iw, fh / ih);
640          const sx = corner.includes('e') ? 1 : -1;
641          const sy = corner.includes('s') ? 1 : -1;
642          const s0 = this._view.s;
643          const w0 = iw * base * s0, h0 = ih * base * s0;
644          const cx0 = (50 + this._view.x) / 100 * fw;
645          const cy0 = (50 + this._view.y) / 100 * fh;
646          const ox = cx0 - sx * w0 / 2, oy = cy0 - sy * h0 / 2;
647          const diag0 = Math.hypot(w0, h0);
648          const ux = sx * w0 / diag0, uy = sy * h0 / diag0;
649          move = (ev) => {
650            const proj = (ev.clientX - rect.left - ox) * ux +
651                         (ev.clientY - rect.top - oy) * uy;
652            const s = clampS(s0 * proj / diag0);
653            const d = diag0 * s / s0;
654            this._view.s = s;
655            this._view.x = (ox + ux * d / 2) / fw * 100 - 50;
656            this._view.y = (oy + uy * d / 2) / fh * 100 - 50;
657            this._clampView();
658            this._applyView();
659          };
660        } else {
661          this.setAttribute('data-panning', '');
662          const start = { px: e.clientX, py: e.clientY, x: this._view.x, y: this._view.y };
663          move = (ev) => {
664            this._view.x = start.x + (ev.clientX - start.px) / fw * 100;
665            this._view.y = start.y + (ev.clientY - start.py) / fh * 100;
666            this._clampView();
667            this._applyView();
668          };
669        }
670        const up = () => {
671          try { this._spill.releasePointerCapture(e.pointerId); } catch {}
672          this._spill.removeEventListener('pointermove', move);
673          this._spill.removeEventListener('pointerup', up);
674          this._spill.removeEventListener('pointercancel', up);
675          this.removeAttribute('data-panning');
676          this._dragUp = null;
677        };
678        // Stashed so _exitReframe (Escape / outside-click mid-drag) can
679        // tear the capture + listeners down synchronously.
680        this._dragUp = up;
681        this._spill.addEventListener('pointermove', move);
682        this._spill.addEventListener('pointerup', up);
683        this._spill.addEventListener('pointercancel', up);
684      });
685      // Wheel zoom stays available inside reframe mode as a trackpad nicety —
686      // zooms toward the cursor (offset' = cursor·(1-k) + offset·k).
687      this.addEventListener('wheel', (e) => {
688        if (!this.hasAttribute('data-reframe')) return;
689        e.preventDefault();
690        const r = this.getBoundingClientRect();
691        const cx = (e.clientX - r.left) / r.width * 100 - 50;
692        const cy = (e.clientY - r.top) / r.height * 100 - 50;
693        const prev = this._view.s;
694        const next = clampS(prev * Math.pow(1.0015, -e.deltaY));
695        if (next === prev) return;
696        const k = next / prev;
697        this._view.s = next;
698        this._view.x = cx * (1 - k) + this._view.x * k;
699        this._view.y = cy * (1 - k) + this._view.y * k;
700        this._clampView();
701        this._applyView();
702      }, { passive: false });
703    }
704
705    connectedCallback() {
706      // Warn once per page — an id-less slot works for the session but
707      // cannot persist, and two id-less slots would share nothing.
708      if (!this.id && !ImageSlot._warned) {
709        ImageSlot._warned = true;
710        console.warn('<image-slot> without an id will not persist its dropped image.');
711      }
712      this.addEventListener('dragenter', this);
713      this.addEventListener('dragover', this);
714      this.addEventListener('dragleave', this);
715      this.addEventListener('drop', this);
716      subs.add(this._subFn);
717      // The host may inject window.omelette.writeFile AFTER the first render;
718      // re-render on hover so the editable-gated controls reliably appear.
719      this.addEventListener('pointerenter', this._subFn);
720      // width%/height% in _applyView encode the frame aspect at call time —
721      // a host resize (responsive grid, pane divider) would stretch the
722      // image until the next _render. Re-render on size change: _render()
723      // re-seeds _view from stored before clamp/apply, so a shrink→grow
724      // cycle round-trips instead of ratcheting x/y toward the narrower
725      // frame's clamp range.
726      this._ro = new ResizeObserver(() => this._render());
727      this._ro.observe(this);
728      load();
729      this._render();
730    }
731
732    disconnectedCallback() {
733      subs.delete(this._subFn);
734      this.removeEventListener('pointerenter', this._subFn);
735      this.removeEventListener('dragenter', this);
736      this.removeEventListener('dragover', this);
737      this.removeEventListener('dragleave', this);
738      this.removeEventListener('drop', this);
739      if (this._ro) { this._ro.disconnect(); this._ro = null; }
740      // commit=false: a disconnect is not a user intent — committing here
741      // would persist whatever half-finished drag a React remount or DOM
742      // splice happened to interrupt. Deliberate exits commit on their own
743      // paths (Escape/click-out/toggle), and unloads commit via pagehide.
744      this._exitReframe(false);
745    }
746
747    _enterReframe() {
748      if (this.hasAttribute('data-reframe')) return;
749      this.setAttribute('data-reframe', '');
750      this._signalReframe(true);
751      // Best-effort commit when the document unloads mid-reframe (a host
752      // navigation racing the enter signal, a manual reload, tab close):
753      // the sidecar write rides the host bridge, which outlives this
754      // document, so the crop survives even though the mode dies with the
755      // DOM. Held on the instance so _exitReframe detaches exactly what
756      // was attached.
757      this._pagehide = () => { this._exitReframe(true); flushNow(); };
758      window.addEventListener('pagehide', this._pagehide);
759      // Promote spill to the top layer, then keep it pinned over the frame:
760      // scroll/resize cover the common cases, and a per-frame rect check
761      // catches layout shifts that fire neither (an image above finishing
762      // load, streamed DOM pushing the slot down, an ancestor transform
763      // change) so the overlay can't detach from the frame.
764      try { this._spill.showPopover(); } catch {}
765      // After the spill, so the controls stack above it in the top layer.
766      try { this._ctl.showPopover(); } catch {}
767      this._reposition = () => { if (this.hasAttribute('data-reframe')) this._applyView(); };
768      window.addEventListener('scroll', this._reposition, true);
769      window.addEventListener('resize', this._reposition);
770      this._lastRect = '';
771      this._watch = () => {
772        if (!this.hasAttribute('data-reframe')) return;
773        const r = this.getBoundingClientRect();
774        const key = r.left + ',' + r.top + ',' + r.width + ',' + r.height;
775        if (key !== this._lastRect) { this._lastRect = key; this._applyView(); }
776        this._watchId = requestAnimationFrame(this._watch);
777      };
778      this._watchId = requestAnimationFrame(this._watch);
779      this._applyView();
780      // Close on click outside (the spill handler stopPropagation()s so
781      // in-image drags don't reach this) and on Escape. Listeners are held
782      // on the instance so _exitReframe / disconnectedCallback can detach
783      // exactly what was attached.
784      this._outside = (e) => {
785        if (e.composedPath && e.composedPath().includes(this)) return;
786        this._exitReframe(true);
787      };
788      this._esc = (e) => { if (e.key === 'Escape') this._exitReframe(true); };
789      document.addEventListener('pointerdown', this._outside, true);
790      document.addEventListener('keydown', this._esc, true);
791    }
792
793    _exitReframe(commit) {
794      if (!this.hasAttribute('data-reframe')) return;
795      if (this._dragUp) this._dragUp();
796      this.removeAttribute('data-reframe');
797      this.removeAttribute('data-panning');
798      if (this._outside) document.removeEventListener('pointerdown', this._outside, true);
799      if (this._esc) document.removeEventListener('keydown', this._esc, true);
800      this._outside = this._esc = null;
801      if (this._reposition) {
802        window.removeEventListener('scroll', this._reposition, true);
803        window.removeEventListener('resize', this._reposition);
804        this._reposition = null;
805      }
806      if (this._watchId) { cancelAnimationFrame(this._watchId); this._watchId = 0; }
807      if (this._pagehide) {
808        window.removeEventListener('pagehide', this._pagehide);
809        this._pagehide = null;
810      }
811      try { this._spill.hidePopover(); } catch {}
812      try { this._ctl.hidePopover(); } catch {}
813      this._ctl.style.left = ''; this._ctl.style.top = '';
814      if (commit) this._commitView();
815      this._signalReframe(false);
816    }
817
818    // Reframe state lives only in this DOM until commit, invisible to the
819    // host's dirty signals — announce enter/exit so the host can hold
820    // auto-reloads for exactly the gesture (the guest bundle forwards
821    // image-slot:reframe to the host as imageSlotReframe). Dispatched on
822    // the element (composed, so it escapes shadow roots) while connected;
823    // a disconnected exit (disconnectedCallback) falls back to document so
824    // the host still hears it.
825    _signalReframe(active) {
826      const target = this.isConnected ? this : document;
827      target.dispatchEvent(new CustomEvent('image-slot:reframe', {
828        bubbles: true, composed: true,
829        detail: { active: active, id: this.id || null }
830      }));
831    }
832
833    // Public: host's "Import from computer" calls this to run local browse.
834    openFilePicker() { this._exitReframe(true); this._input.click(); }
835
836    // A src write is a newer intent for this slot's content — the host
837    // pick path (setImageSlotImage) or an agent edit — so it must win
838    // over any encode still in flight from an earlier drop: left live,
839    // that encode lands later, passes _ingest's gen guard, and its
840    // setSlot silently overwrites the pick (the stored value shadows
841    // src in _render). Bumping _gen kills the encode before its own
842    // _swapGen clear runs, so clear the dead claim here too — otherwise
843    // _releaseMask (gated on !_swapGen) never fires and the pick's
844    // spinner is stranded. src ONLY: the pick sets credit/credit-href
845    // in the same task, and clearing _swapGen on those would let the
846    // same-src branch unmask the old image mid-encode.
847    attributeChangedCallback(name, oldVal, newVal) {
848      if (name === 'src' && oldVal !== newVal) {
849        this._gen++;
850        this._swapGen = 0;
851      }
852      if (this.shadowRoot) this._render();
853    }
854
855    // handleEvent — one listener object for all four drag events keeps the
856    // add/remove symmetric and the depth counter correct.
857    handleEvent(e) {
858      if (e.type === 'dragenter' || e.type === 'dragover') {
859        // Without preventDefault the browser never fires 'drop'.
860        e.preventDefault();
861        e.stopPropagation();
862        if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
863        if (e.type === 'dragenter') this._depth++;
864        this.setAttribute('data-over', '');
865      } else if (e.type === 'dragleave') {
866        // dragenter/leave fire for every descendant crossing — count depth
867        // so hovering the icon inside the empty state doesn't flicker.
868        if (--this._depth <= 0) { this._depth = 0; this.removeAttribute('data-over'); }
869      } else if (e.type === 'drop') {
870        e.preventDefault();
871        e.stopPropagation();
872        this._depth = 0;
873        this.removeAttribute('data-over');
874        const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
875        if (f) this._ingest(f);
876      }
877    }
878
879    async _ingest(file) {
880      this._setError(null);
881      if (!file || ACCEPT.indexOf(file.type) < 0) {
882        this._setError('Drop a PNG, JPEG, WebP, or AVIF image.');
883        return;
884      }
885      // toDataUrl can take hundreds of ms on a large photo. A Clear or a
886      // newer drop during that window would be clobbered when this await
887      // resumes — bump + capture a generation so stale encodes bail.
888      const gen = ++this._gen;
889      // Replacing a shown image: surface the swap through the encode too,
890      // not just the decode — otherwise the old photo sits there with no
891      // feedback while the canvas re-encode runs. An empty slot keeps its
892      // placeholder (no spinner) until the encode lands, as before.
893      // _swapGen guards the mask against re-renders DURING the encode
894      // (pointerenter, ResizeObserver, another slot's store write): the
895      // stored value still resolves to the old image there, so _render's
896      // same-src clear would otherwise unmask it mid-replace.
897      if (this.hasAttribute('data-filled')) {
898        this.setAttribute('data-swapping', '');
899        this._swapGen = gen;
900      }
901      try {
902        const w = this.clientWidth || this.offsetWidth || MAX_DIM;
903        const url = await toDataUrl(file, w);
904        if (gen !== this._gen) return;
905        // Only exit reframe once the new image is in hand — a rejected type
906        // or decode failure leaves the in-progress crop untouched.
907        this._exitReframe(false);
908        // Clear BEFORE setSlot: its synchronous re-render must see no
909        // pending encode, so a byte-identical re-upload (same data URL, no
910        // load event coming) still clears the mask via the complete branch.
911        this._swapGen = 0;
912        const val = { u: url, s: 1, x: 0, y: 0 };
913        setSlot(this.id || '', val);
914        // Keep a session-local copy for id-less slots so the drop still
915        // shows, even though it cannot persist.
916        if (!this.id) { this._local = val; this._render(); }
917      } catch (err) {
918        if (gen !== this._gen) return;
919        this._swapGen = 0;
920        // Reveal the kept old image — unless another replacement (a
921        // remote pick's src swap) is still in flight, in which case the
922        // mask stays until THAT image settles (its load/error releases).
923        this._releaseMask();
924        this._setError('Could not read that image.');
925        console.warn('<image-slot> ingest failed:', err);
926      }
927    }
928
929    _setError(msg) {
930      if (this._err) { this._err.remove(); this._err = null; }
931      if (!msg) return;
932      const d = document.createElement('div');
933      d.className = 'err'; d.textContent = msg;
934      this.shadowRoot.appendChild(d);
935      this._err = d;
936      setTimeout(() => { if (this._err === d) { d.remove(); this._err = null; } }, 3000);
937    }
938
939    // Reframing (pan/resize) is available on any filled slot — the user can
940    // always reposition/scale. `fit` only sets the initial baseline (see
941    // _geom): contain starts fully-visible, cover starts frame-filling.
942    _reframes() {
943      return this.hasAttribute('data-filled');
944    }
945
946    // The single release discipline for the replacement-in-flight mask
947    // (data-swapping). The mask comes off only when BOTH hold:
948    //  - no encode is pending (_swapGen) — mid-encode the stored value
949    //    still resolves to the old image, so any reveal paints it;
950    //  - the frame img has settled on its current src — an unsettled src
951    //    means some replacement is still in flight (e.g. a remote pick),
952    //    whoever started it, and revealing would paint the previous
953    //    frame. The load/error listeners pass settled=true (the event IS
954    //    the settlement signal, per spec complete is true by then);
955    //    other callers rely on the complete flag (covers loaded AND
956    //    failed).
957    // Every release path funnels through here EXCEPT _render's empty
958    // branch (the img is being cleared — nothing will ever settle).
959    _releaseMask(settled) {
960      if (
961        !this._swapGen &&
962        !this._loadPending &&
963        (settled || this._img.complete)
964      ) {
965        this.removeAttribute('data-swapping');
966      }
967    }
968
969    // Baseline geometry, shared by clamp/apply/resize. `base` is the scale at
970    // view-scale s=1: cover = fill the frame (overflow on the looser axis),
971    // contain = fit fully inside (letterboxed). Zooming a contain image past
972    // s where it overflows naturally becomes a crop. Null until the img has
973    // loaded (naturalWidth is 0 before that) or when the slot has no layout
974    // box — ResizeObserver fires with a 0×0 rect under display:none, and
975    // clamping against a degenerate 1×1 frame would silently pull the stored
976    // pan toward zero.
977    _geom() {
978      const iw = this._img.naturalWidth, ih = this._img.naturalHeight;
979      const fw = this.clientWidth, fh = this.clientHeight;
980      if (!iw || !ih || !fw || !fh) return null;
981      const contain = (this.getAttribute('fit') || 'cover').toLowerCase() === 'contain';
982      const base = contain
983        ? Math.min(fw / iw, fh / ih)
984        : Math.max(fw / iw, fh / ih);
985      return { iw, ih, fw, fh, base };
986    }
987
988    _clampView() {
989      // Pan range on each axis is half the overflow past the frame edge.
990      const g = this._geom();
991      if (!g) return;
992      const mx = Math.max(0, (g.iw * g.base * this._view.s / g.fw - 1) * 50);
993      const my = Math.max(0, (g.ih * g.base * this._view.s / g.fh - 1) * 50);
994      this._view.x = Math.max(-mx, Math.min(mx, this._view.x));
995      this._view.y = Math.max(-my, Math.min(my, this._view.y));
996    }
997
998    _applyView() {
999      const g = this._geom();
1000      // Top-layer controls: pin to the frame's top-right in viewport px
1001      // (the same 8px inset as the in-frame layout; unscaled — top-layer UI
1002      // reads as chrome, not page content). BEFORE the geometry branch:
1003      // placement needs only the frame rect, and a not-yet-loaded or broken
1004      // src must not leave the promoted strip floating unpositioned. Gated
1005      // on the popover actually being open: without the Popover API,
1006      // showPopover() threw (swallowed in _enterReframe), .ctl stays in
1007      // its in-frame absolute layout, and viewport-px coordinates would
1008      // shove it off-frame — and matches(':popover-open') itself throws
1009      // there (unknown pseudo-class), hence the try/catch.
1010      if (this.hasAttribute('data-reframe')) {
1011        let onTop = false;
1012        try { onTop = this._ctl.matches(':popover-open'); } catch {}
1013        if (onTop) {
1014          const r = this.getBoundingClientRect();
1015          this._ctl.style.left = (r.right - 8) + 'px';
1016          this._ctl.style.top = (r.top + 8) + 'px';
1017        }
1018      }
1019      if (!g) {
1020        // Dimensions not known yet (before img load) — centered fit so there
1021        // is no flash of an unpositioned image before the geometry lands.
1022        const contain = (this.getAttribute('fit') || 'cover').toLowerCase() === 'contain';
1023        this._img.style.width = '100%';
1024        this._img.style.height = '100%';
1025        this._img.style.left = '50%';
1026        this._img.style.top = '50%';
1027        this._img.style.objectFit = contain ? 'contain' : 'cover';
1028        return;
1029      }
1030      // Baseline (cover-fill or contain-fit) × view scale. Width/height and
1031      // left/top are all frame-% — depends only on the frame aspect ratio, so
1032      // a responsive resize keeps the same crop. The spill layer mirrors the
1033      // same box so its corners = image corners.
1034      const k = g.base * this._view.s;
1035      const w = (g.iw * k / g.fw * 100) + '%';
1036      const h = (g.ih * k / g.fh * 100) + '%';
1037      const l = (50 + this._view.x) + '%';
1038      const t = (50 + this._view.y) + '%';
1039      this._img.style.width = w; this._img.style.height = h;
1040      this._img.style.left = l; this._img.style.top = t;
1041      this._img.style.objectFit = '';
1042      if (this.hasAttribute('data-reframe')) {
1043        // Top-layer spill: position in viewport px over the frame. The top
1044        // layer escapes ancestor transforms entirely, so EVERY term must be
1045        // in viewport units: getBoundingClientRect gives the frame's scaled
1046        // origin AND size, and the rect/layout ratio rescales the ghost —
1047        // sizing from layout px alone renders it 1/scale too large under a
1048        // scaled deck slide. Inner ghost + handles stay box-relative.
1049        const r = this.getBoundingClientRect();
1050        const sx = g.fw ? r.width / g.fw : 1;
1051        const sy = g.fh ? r.height / g.fh : 1;
1052        this._spill.style.width = (g.iw * k * sx) + 'px';
1053        this._spill.style.height = (g.ih * k * sy) + 'px';
1054        this._spill.style.left = (r.left + (50 + this._view.x) / 100 * r.width) + 'px';
1055        this._spill.style.top = (r.top + (50 + this._view.y) / 100 * r.height) + 'px';
1056      }
1057    }
1058
1059    _commitView() {
1060      const v = { s: this._view.s, x: this._view.x, y: this._view.y };
1061      if (this._userUrl) v.u = this._userUrl;
1062      // Framing-only (no u) persists too so an author-src slot remembers its
1063      // crop; clearing the sidecar still falls through to src=.
1064      if (this.id) setSlot(this.id, v);
1065      else { this._local = v; }
1066    }
1067
1068    _render() {
1069      // Shape / mask. Presets use border-radius so the dashed ring can
1070      // follow the rounded outline; clip-path is only applied for an
1071      // explicit `mask` (the ring is hidden there since a rectangle
1072      // dashed border chopped by an arbitrary polygon looks broken).
1073      const mask = this.getAttribute('mask');
1074      const shape = (this.getAttribute('shape') || 'rounded').toLowerCase();
1075      let radius = '';
1076      if (shape === 'circle') radius = '50%';
1077      else if (shape === 'pill') radius = '9999px';
1078      else if (shape === 'rounded') {
1079        const n = parseFloat(this.getAttribute('radius'));
1080        radius = (Number.isFinite(n) ? n : 12) + 'px';
1081      }
1082      this._frame.style.borderRadius = mask ? '' : radius;
1083      this._frame.style.clipPath = mask || '';
1084      this._ring.style.borderRadius = mask ? '' : radius;
1085      this._ring.style.display = mask ? 'none' : '';
1086
1087      // Controls and reframe entry gate on this so share links stay read-only.
1088      const editable = !!(window.omelette && window.omelette.writeFile);
1089      this.toggleAttribute('data-editable', editable);
1090      this._sub.style.display = editable ? '' : 'none';
1091
1092      // Content. The sidecar is also writable by the agent's write_file
1093      // tool, so its value isn't guaranteed canvas-originated — only accept
1094      // data:image/ URLs from it. The `src` attribute is author-controlled
1095      // (Claude wrote it into the HTML) so it passes through unchanged.
1096      let stored = this.id ? getSlot(this.id) : this._local;
1097      if (stored && stored.u && !/^data:image\//i.test(stored.u)) stored = null;
1098      const srcAttr = this.getAttribute('src') || '';
1099      this._userUrl = (stored && stored.u) || null;
1100      const url = this._userUrl || srcAttr;
1101      // Don't clobber an in-flight reframe with a store-triggered re-render.
1102      if (!this.hasAttribute('data-reframe')) {
1103        this._view = {
1104          s: stored && Number.isFinite(stored.s) ? clampS(stored.s) : 1,
1105          x: stored && Number.isFinite(stored.x) ? stored.x : 0,
1106          y: stored && Number.isFinite(stored.y) ? stored.y : 0,
1107        };
1108      }
1109      this._cap.textContent = this.getAttribute('placeholder') || 'Drop an image';
1110      // Toggle via style.display — the [hidden] attribute alone loses to
1111      // the display:flex / display:block rules in the stylesheet above.
1112      // An Unsplash src with no credit attribute must NOT render — showing
1113      // the photo uncredited is the Unsplash-terms violation itself. The
1114      // error tile replaces the photo until the credit is written. A
1115      // user-dropped image is the user's own content and always renders.
1116      // Trimmed: credit is agent/user-editable content, and a whitespace-
1117      // only value must count as missing — otherwise it would suppress the
1118      // error tile AND render an empty credit box (no text, no links),
1119      // exactly the unattributed state this gate exists to prevent.
1120      const credit = (this.getAttribute('credit') || '').trim();
1121      const attrError = !!(
1122        !credit && !this._userUrl && srcAttr && isUnsplashHost(srcAttr)
1123      );
1124      this.toggleAttribute('data-attribution-error', attrError);
1125      if (url && !attrError) {
1126        const prev = this._img.getAttribute('src');
1127        if (prev !== url) {
1128          // Replacing an already-shown image: mark the swap BEFORE setting
1129          // src so the stale frame is never revealed (see the data-swapping
1130          // stylesheet rules). First fill (prev empty) keeps the existing
1131          // placeholder-until-load behavior — no spinner. _hidShowing
1132          // covers the pick path's transient attribution-error wipe: prev
1133          // is gone, but an image WAS showing, so this is a replacement.
1134          if (prev || this._hidShowing) this.setAttribute('data-swapping', '');
1135          // Mark the swap BEFORE assigning src: complete keeps reporting
1136          // the old settled request until the browser's
1137          // update-the-image-data microtask runs, so same-task re-renders
1138          // (the pick path's credit/credit-href setAttributes) need this
1139          // flag, not complete, to know a load is in flight.
1140          this._loadPending = true;
1141          this._img.src = url;
1142          this._ghost.src = url;
1143        } else {
1144          // Same-src re-render — release if settled, so an ingest-set
1145          // spinner can't stick after a byte-identical re-upload (same
1146          // data URL, no further load event ever fires).
1147          this._releaseMask();
1148        }
1149        this._hidShowing = false;
1150        this._img.style.display = 'block';
1151        this._empty.style.display = 'none';
1152        this.setAttribute('data-filled', '');
1153        this._clampView();
1154        this._applyView();
1155      } else {
1156        this.removeAttribute('data-swapping');
1157        // The src is being removed — no load/error will ever fire for it.
1158        this._loadPending = false;
1159        // A transient attribution-error wipe of a showing image happens on
1160        // the pick path: the host sets src one setAttribute before credit,
1161        // so render N hides the old image (attrError) and render N+1
1162        // restores a URL. Remember the wipe so that restore renders as a
1163        // replacement (spinner), not a first fill (blank frame).
1164        this._hidShowing = attrError && !!this._img.getAttribute('src');
1165        this._img.style.display = 'none';
1166        this._img.removeAttribute('src');
1167        this._ghost.removeAttribute('src');
1168        // The error tile owns the blocked-photo state; .empty stays for
1169        // the genuinely-empty slot.
1170        this._empty.style.display = attrError ? 'none' : 'flex';
1171        this.removeAttribute('data-filled');
1172      }
1173
1174      // Credit belongs to the author src, so a user drop hides it.
1175      // textContent + the http(s)-only funnel keep external strings inert.
1176      const showCredit = !!(url && credit && !this._userUrl && !attrError);
1177      this._credit.textContent = '';
1178      if (showCredit) {
1179        // Validate once (resolved against the document, http(s) only),
1180        // then append the terms-required utm referral params to links
1181        // that point back at unsplash.com.
1182        let href = '';
1183        const rawHref = this.getAttribute('credit-href') || '';
1184        if (rawHref) {
1185          try {
1186            const u = new URL(rawHref, document.baseURI);
1187            if (u.protocol === 'http:' || u.protocol === 'https:') {
1188              href = withReferral(u.href);
1189            }
1190          } catch {}
1191        }
1192        const mkLink = (text, linkHref) => {
1193          const a = document.createElement('a');
1194          a.setAttribute('target', '_blank');
1195          a.setAttribute('rel', 'noopener noreferrer');
1196          a.setAttribute('href', linkHref);
1197          a.textContent = text;
1198          return a;
1199        };
1200        // Unsplash's prescribed credit is TWO links — the photographer's
1201        // name to their profile (credit-href) and 'Unsplash' to the
1202        // homepage. Render that split whenever the text has the canonical
1203        // shape; other text keeps the legacy single-link rendering.
1204        const m = /^Photo by (.+) on Unsplash$/.exec(credit);
1205        if (m) {
1206          this._credit.appendChild(document.createTextNode('Photo by '));
1207          this._credit.appendChild(
1208            href ? mkLink(m[1], href) : document.createTextNode(m[1])
1209          );
1210          this._credit.appendChild(document.createTextNode(' on '));
1211          this._credit.appendChild(mkLink('Unsplash', UNSPLASH_HOMEPAGE_HREF));
1212        } else if (href) {
1213          this._credit.appendChild(mkLink(credit, href));
1214        } else {
1215          this._credit.textContent = credit;
1216        }
1217      }
1218      this.toggleAttribute('data-credit', showCredit);
1219    }
1220  }
1221
1222  if (!customElements.get('image-slot')) {
1223    customElements.define('image-slot', ImageSlot);
1224  }
1225})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.