PageSourceSearch

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

js goldcare.com collected 2026-09-28 10:16:26 UTC 56,000 bytes, 1,066 lines download raw bytes

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

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.