1/** 2 * <image-slot> â user-fillable image placeholder. 3 * 4 * Drop this into a deck, mockup, or page wherever you want the user to 5 * supply an image. You control the slot's shape and size; the user fills it 6 * by dragging an image file onto it (or clicking to browse). The dropped 7 * image persists across reloads via a .image-slots.state.json sidecar â 8 * same read-via-fetch / write-via-window.omelette pattern as 9 * design_canvas.jsx, so the filled slot shows on share links, downloaded 10 * zips, and PPTX export. Outside the omelette runtime the slot is read-only. 11 * 12 * The host bridge only allows sidecar writes at the project root, so the 13 * HTML that uses this component is assumed to live at the project root too 14 * (same constraint as design_canvas.jsx). 15 * 16 * Attributes: 17 * id Persistence key. REQUIRED for the drop to survive reload â 18 * every slot on the page needs a distinct id. 19 * shape 'rect' | 'rounded' | 'circle' | 'pill' (default 'rounded') 20 * 'circle' applies 50% border-radius; on a non-square slot 21 * that's an ellipse â set equal width and height for a true 22 * circle. 23 * radius Corner radius in px for 'rounded'. (default 12) 24 * mask Any CSS clip-path value. Overrides `shape` â use this for 25 * hexagons, blobs, arbitrary polygons. 26 * fit object-fit: cover | contain | fill. (default 'cover') 27 * With cover (the default) double-clicking the filled slot 28 * enters a reframe mode: the whole image spills past the mask 29 * (translucent outside, opaque inside), drag to reposition, 30 * corner-drag to scale. The crop persists alongside the image 31 * in the sidecar. contain/fill stay static. 32 * position object-position for fit=contain|fill. (default '50% 50%') 33 * placeholder Empty-state caption. (default 'Drop an image') 34 * src Optional initial/fallback image URL. A user drop overrides 35 * it; clearing the drop reveals src again. 36 * 37 * Size and layout come from ordinary CSS on the element â width/height 38 * inline or from a parent grid â so it composes with any layout. 39 * 40 * Usage: 41 * <script src="image-slot.js"></script> 42 * <image-slot id="hero" style="width:800px;height:450px" shape="rounded" radius="20" 43 * placeholder="Drop a hero image"></image-slot> 44 * <image-slot id="avatar" style="width:120px;height:120px" shape="circle"></image-slot> 45 * <image-slot id="kite" style="width:300px;height:300px" 46 * mask="polygon(50% 0, 100% 50%, 50% 100%, 0 50%)"></image-slot> 47 */ 48 49(() => { 50 const STATE_FILE = '.image-slots.state.json'; 51 // 2Ã a ~600px slot in a 1920-wide deck â retina-sharp without making the 52 // sidecar enormous. A 1200px WebP at q=0.85 is ~150-300KB. 53 const MAX_DIM = 1200; 54 // Raster formats only. SVG is excluded (can carry script; createImageBitmap 55 // on SVG blobs is inconsistent). GIF is excluded because the canvas 56 // re-encode keeps only the first frame, so an animated GIF would silently 57 // go still â better to reject than surprise. 58 const ACCEPT = ['image/png', 'image/jpeg', 'image/webp', 'image/avif']; 59 60 // ââ Shared sidecar store ââââââââââââââââââââââââââââââââââââââââââââââââ 61 // One fetch + immediate write-on-change for every <image-slot> on the 62 // page. Reads via fetch() so viewing works anywhere the HTML and sidecar 63 // are served together; writes go through window.omelette.writeFile, which 64 // the host allowlists to *.state.json basenames only. 65 const subs = new Set(); 66 let slots = {}; 67 // ids explicitly cleared before the sidecar fetch resolved â otherwise 68 // the merge below can't tell "never set" from "just deleted" and would 69 // resurrect the sidecar's stale value. 70 const tombstones = new Set(); 71 let loaded = false; 72 let loadP = null; 73 74 function load() { 75 if (loadP) return loadP; 76 loadP = fetch(STATE_FILE) 77 .then((r) => (r.ok ? r.json() : null)) 78 .then((j) => { 79 // Merge: sidecar loses to any in-memory change that raced ahead of 80 // the fetch (drop or clear) so neither is clobbered by hydration. 81 if (j && typeof j === 'object') { 82 const merged = Object.assign({}, j, slots); 83 // A framing-only write that raced ahead of hydration must not 84 // drop a user image that's only on disk â inherit u from the 85 // sidecar for any in-memory entry that lacks one. 86 for (const k in slots) { 87 if (merged[k] && !merged[k].u && j[k]) { 88 merged[k].u = typeof j[k] === 'string' ? j[k] : j[k].u; 89 } 90 } 91 for (const id of tombstones) delete merged[id]; 92 slots = merged; 93 } 94 tombstones.clear(); 95 }) 96 .catch(() => {}) 97 .then(() => { loaded = true;
97 subs.forEach((fn) => fn()); }); 98 return loadP; 99 } 100 101 // Serialize writes so two near-simultaneous drops on different slots 102 // can't reorder at the backend and leave the sidecar with only the 103 // first. A save requested mid-flight just marks dirty and re-fires on 104 // completion with the then-current slots. 105 let saving = false; 106 let saveDirty = false; 107 function save() { 108 if (saving) { saveDirty = true; return; } 109 const w = window.omelette && window.omelette.writeFile; 110 if (!w) return; 111 saving = true; 112 Promise.resolve(w(STATE_FILE, JSON.stringify(slots))) 113 .catch(() => {}) 114 .then(() => { saving = false; if (saveDirty) { saveDirty = false; save(); } }); 115 } 116 117 const S_MAX = 5; 118 const clampS = (s) => Math.max(1, Math.min(S_MAX, s)); 119 120 // Normalize a stored slot value. Pre-reframe sidecars stored a bare 121 // data-URL string; newer ones store {u, s, x, y}. Either shape is valid. 122 function getSlot(id) { 123 const v = slots[id]; 124 if (!v) return null; 125 return typeof v === 'string' ? { u: v, s: 1, x: 0, y: 0 } : v; 126 } 127 128 function setSlot(id, val) { 129 if (!id) return; 130 if (val) { slots[id] = val; tombstones.delete(id); } 131 else { delete slots[id]; if (!loaded) tombstones.add(id); } 132 subs.forEach((fn) => fn()); 133 // A drop is rare + high-value â write immediately so nav-away can't lose 134 // it. Gate on the initial read so we don't overwrite a sidecar we haven't 135 // merged yet; the merge in load() keeps this change once the read lands. 136 if (loaded) save(); else load().then(save); 137 } 138 139 // ââ Image downscale âââââââââââââââââââââââââââââââââââââââââââââââââââââ 140 // Encode through a canvas so the sidecar carries resized bytes, not the 141 // raw upload. Longest side is capped at 2Ã the slot's rendered width 142 // (retina) and at MAX_DIM. WebP keeps alpha and is ~10Ã smaller than PNG 143 // for photos, so there's no need for per-image format picking. 144 async function toDataUrl(file, targetW) { 145 const bitmap = await createImageBitmap(file); 146 try { 147 const cap = Math.min(MAX_DIM, Math.max(1, Math.round(targetW * 2)) || MAX_DIM); 148 const scale = Math.min(1, cap / Math.max(bitmap.width, bitmap.height)); 149 const w = Math.max(1, Math.round(bitmap.width * scale)); 150 const h = Math.max(1, Math.round(bitmap.height * scale)); 151 const canvas = document.createElement('canvas'); 152 canvas.width = w; canvas.height = h; 153 canvas.getContext('2d').drawImage(bitmap, 0, 0, w, h); 154 return canvas.toDataURL('image/webp', 0.85); 155 } finally { 156 bitmap.close && bitmap.close(); 157 } 158 } 159 160 // ââ Custom element ââââââââââââââââââââââââââââââââââââââââââââââââââââââ 161 const stylesheet = 162 ':host{display:inline-block;position:relative;vertical-align:top;' + 163 ' font:13px/1.3 system-ui,-apple-system,sans-serif;color:rgba(0,0,0,.55);width:240px;height:160px}' + 164 '.frame{position:absolute;inset:0;overflow:hidden;background:rgba(0,0,0,.04)}' + 165 // .frame img (clipped) and .spill (unclipped ghost + handles) share the 166 // same left/top/width/height in frame-%, computed by _applyView(), so the 167 // inside-mask crop and the outside-mask spill stay pixel-aligned. 168 '.frame img{position:absolute;max-width:none;transform:translate(-50%,-50%);' + 169 ' -webkit-user-drag:none;user-select:none;touch-action:none}' + 170 // Reframe mode (double-click): the full image spills past the mask. The 171 // spill layer is sized to the IMAGE bounds so its corners are where the 172 // resize handles belong. The ghost <img> inside is translucent; the real 173 // clipped <img> underneath shows the opaque in-mask crop. 174 '.spill{position:absolute;transform:translate(-50%,-50%);display:none;z-index:1;' + 175 ' cursor:grab;touch-action:none}' + 176 ':host([data-panning]) .spill{cursor:grabbing}' + 177 '.spill .ghost{position:absolute;inset:0;width:100%;height:100%;opacity:.35;' + 178 ' pointer-events:none;-webkit-user-drag:none;user-select:none;' + 179 ' box-shadow:0 0 0 1px rgba(0,0,0,.2),0 12px 32px rgba(0,0,0,.2)}' + 180 '.spill .handle{position:absolute;width:12px;height:12px;border-radius:50%;' + 181 ' background:#fff;box-shadow:0 0 0 1.5px #c96442,0 1px 3px rgba(0,0,0,.3);' + 182 ' transform:translate(-50%,-50%)}' + 183 '.spill .handle[data-c=nw]{left:0;top:0;cursor:nwse-resize}' + 184 '.spill .handle[data-c=ne]{left:100%;top:0;cursor:nesw-resize}' + 185 '.spill .handle[data-c=sw]{left:0;top:100%;cursor:nesw-resize}' + 186 '.spill .handle[data-c=se]{left:100%;top:100%;cursor:nwse-resize}' + 187 ':host([data-reframe]){z-index:10}' + 188 ':host([data-reframe]) .spill{display:block}' + 189 ':host([data-reframe]) .frame{box-shadow:0 0 0 2px #c96442}' + 190 '.empty{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;' + 191 ' justify-content:center;gap:6px;text-align:center;padding:12px;box-sizing:border-box;' + 192 ' cursor:pointer;user-select:none}' + 193 '.empty svg{opacity:.45}' + 194 '.empty .cap{max-width:90%;font-weight:500;letter-spacing:.01em}' + 195 '.empty .sub{font-size:11px}' + 196 '.empty .sub u{text-underline-offset:2px;text-decoration-color:rgba(0,0,0,.25)}' + 197 '.empty:hover .sub u{color:rgba(0,0,0,.75);text-decoration-color:currentColor}' + 198 ':host([data-over]) .frame{outline:2px solid #c96442;outline-offset:-2px;' + 199 ' background:rgba(201,100,66,.10)}' + 200 '.ring{position:absolute;inset:0;pointer-events:none;border:1.5px dashed rgba(0,0,0,.25);' + 201 ' transition:border-color .12s}' + 202 ':host([data-over]) .ring{border-color:#c96442}' + 203 ':host([data-filled]) .ring{display:none}' + 204 // Controls sit BELOW the mask (top:100%), absolutely positioned
204so the 205 // author-declared slot height is unaffected. The gap is padding, not a 206 // top offset, so the hover target stays contiguous with the frame. 207 '.ctl{position:absolute;top:100%;left:50%;transform:translateX(-50%);padding-top:8px;' + 208 ' display:flex;gap:6px;opacity:0;pointer-events:none;transition:opacity .12s;z-index:2;' + 209 ' white-space:nowrap}' + 210 ':host([data-filled][data-editable]:hover) .ctl,:host([data-reframe]) .ctl' + 211 ' {opacity:1;pointer-events:auto}' + 212 '.ctl button{appearance:none;border:0;border-radius:6px;padding:5px 10px;cursor:pointer;' + 213 ' background:rgba(0,0,0,.65);color:#fff;font:11px/1 system-ui,-apple-system,sans-serif;' + 214 ' backdrop-filter:blur(6px)}' + 215 '.ctl button:hover{background:rgba(0,0,0,.8)}' + 216 '.err{position:absolute;left:8px;bottom:8px;right:8px;color:#b3261e;font-size:11px;' + 217 ' background:rgba(255,255,255,.85);padding:4px 6px;border-radius:5px;pointer-events:none}'; 218 219 const icon = 220 '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' + 221 'stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">' + 222 '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/>' + 223 '<path d="m21 15-5-5L5 21"/></svg>'; 224 225 class ImageSlot extends HTMLElement { 226 static get observedAttributes() { 227 return ['shape', 'radius', 'mask', 'fit', 'position', 'placeholder', 'src', 'id']; 228 } 229 230 constructor() { 231 super(); 232 const root = this.attachShadow({ mode: 'open' }); 233 // .spill and .ctl sit OUTSIDE .frame so overflow:hidden + border-radius 234 // on the frame (circle, pill, rounded) can't clip them. 235 root.innerHTML = 236 '<style>' + stylesheet + '</style>' + 237 '<div class="frame" part="frame">' + 238 ' <img part="image" alt="" draggable="false" style="display:none">' + 239 ' <div class="empty" part="empty">' + icon + 240 ' <div class="cap"></div>' + 241 ' <div class="sub">or <u>browse files</u></div></div>' + 242 ' <div class="ring" part="ring"></div>' + 243 '</div>' + 244 '<div class="spill">' + 245 ' <img class="ghost" alt="" draggable="false">' + 246 ' <div class="handle" data-c="nw"></div><div class="handle" data-c="ne"></div>' + 247 ' <div class="handle" data-c="sw"></div><div class="handle" data-c="se"></div>' + 248 '</div>' + 249 '<div class="ctl"><button data-act="replace" title="Replace image">Replace</button>' + 250 ' <button data-act="clear" title="Remove image">Remove</button></div>' + 251 '<input type="file" accept="' + ACCEPT.join(',') + '" hidden>'; 252 this._frame = root.querySelector('.frame'); 253 this._ring = root.querySelector('.ring'); 254 this._img = root.querySelector('.frame img'); 255 this._empty = root.querySelector('.empty'); 256 this._cap = root.querySelector('.cap'); 257 this._sub = root.querySelector('.sub'); 258 this._spill = root.querySelector('.spill'); 259 this._ghost = root.querySelector('.ghost'); 260 this._err = null; 261 this._input = root.querySelector('input'); 262 this._depth = 0; 263 this._gen = 0; 264 this._view = { s: 1, x: 0, y: 0 }; 265 this._subFn = () => this._render(); 266 // Shadow-DOM listeners live with the shadow DOM â bound once here so 267 // disconnect/reconnect (e.g. React remount) doesn't stack handlers. 268 this._empty.addEventListener('click', () => this._input.click()); 269 root.addEventListener('click', (e) => { 270 const act = e.target && e.target.getAttribute && e.target.getAttribute('data-act'); 271 if (act === 'replace') { this._exitReframe(true); this._input.click(); } 272 if (act === 'clear') { 273 this._exitReframe(false); 274 this._gen++; 275 this._local = null; 276 if (this.id) setSlot(this.id, null); else this._render(); 277 } 278 }); 279 this._input.addEventListener('change', () => { 280 const f = this._input.files && this._input.files[0]; 281 if (f) this._ingest(f); 282 this._input.value = ''; 283 });
284 // naturalWidth/Height aren't known until load â re-apply so the cover 285 // baseline is computed from real dimensions, not the 100%Ã100% fallback. 286 this._img.addEventListener('load', () => this._applyView()); 287 // Gated on editable + fit=cover so share links and contain/fill slots 288 // stay static. 289 this.addEventListener('dblclick', (e) => { 290 if (!this.hasAttribute('data-editable') || !this._reframes()) return; 291 e.preventDefault(); 292 if (this.hasAttribute('data-reframe')) this._exitReframe(true); 293 else this._enterReframe(); 294 }); 295 // Pan + resize both originate on the spill layer. A handle pointerdown 296 // drives an aspect-locked resize anchored at the opposite corner; any 297 // other pointerdown on the spill pans. Offsets are frame-% so a 298 // reframed slot survives responsive resize / PPTX export. 299 this._spill.addEventListener('pointerdown', (e) => { 300 if (e.button !== 0 || !this.hasAttribute('data-reframe')) return; 301 e.preventDefault(); 302 e.stopPropagation(); 303 this._spill.setPointerCapture(e.pointerId); 304 const rect = this.getBoundingClientRect(); 305 const fw = rect.width || 1, fh = rect.height || 1; 306 const corner = e.target.getAttribute && e.target.getAttribute('data-c'); 307 let move; 308 if (corner) { 309 // Resize about the OPPOSITE corner. Viewport-px throughout (rect 310 // fw/fh, not clientWidth) so the math survives a transform:scale() 311 // ancestor â deck_stage renders slides scaled-to-fit. 312 const iw = this._img.naturalWidth || 1, ih = this._img.naturalHeight || 1; 313 const base = Math.max(fw / iw, fh / ih); 314 const sx = corner.includes('e') ? 1 : -1; 315 const sy = corner.includes('s') ? 1 : -1; 316 const s0 = this._view.s; 317 const w0 = iw * base * s0, h0 = ih * base * s0; 318 const cx0 = (50 + this._view.x) / 100 * fw; 319 const cy0 = (50 + this._view.y) / 100 * fh; 320 const ox = cx0 - sx * w0 / 2, oy = cy0 - sy * h0 / 2; 321 const diag0 = Math.hypot(w0, h0); 322 const ux = sx * w0 / diag0, uy = sy * h0 / diag0; 323 move = (ev) => { 324 const proj = (ev.clientX - rect.left - ox) * ux + 325 (ev.clientY - rect.top - oy) * uy; 326 const s = clampS(s0 * proj / diag0); 327 const d = diag0 * s / s0; 328 this._view.s = s; 329 this._view.x = (ox + ux * d / 2) / fw * 100 - 50; 330 this._view.y = (oy + uy * d / 2) / fh * 100 - 50; 331 this._clampView(); 332 this._applyView(); 333 }; 334 } else { 335 this.setAttribute('data-panning', ''); 336 const start = { px: e.clientX, py: e.clientY, x: this._view.x, y: this._view.y }; 337 move = (ev) => { 338 this._view.x = start.x + (ev.clientX - start.px) / fw * 100; 339 this._view.y = start.y + (ev.clientY - start.py) / fh * 100; 340 this._clampView(); 341 this._applyView(); 342 }; 343 } 344 const up = () => { 345 try { this._spill.releasePointerCapture(e.pointerId); } catch {} 346 this._spill.removeEventListener('pointermove', move); 347 this._spill.removeEventListener('pointerup', up); 348 this._spill.removeEventListener('pointercancel', up); 349 this.removeAttribute('data-panning'); 350 this._dragUp = null; 351 }; 352 // Stashed so _exitReframe (Escape / outside-click mid-drag) can 353 // tear the capture + listeners down synchronously. 354 this._dragUp = up; 355 this._spill.addEventListener('pointermove', move); 356 this._spill.addEventListener('pointerup', up); 357 this._spill.addEventListener('pointercancel', up); 358 }); 359 // Wheel zoom stays available inside reframe mode as a trackpad nicety â 360 // zooms toward the cursor (offset' = cursor·(1-k) + offset·k). 361 this.addEventListener('wheel', (e) => { 362 if (!this.hasAttribute('data-reframe')) return; 363 e.preventDefault(); 364 const r = this.getBoundingClientRect(); 365 const cx = (e.clientX - r.left) / r.width * 100 - 50; 366 const cy = (e.clientY - r.top) / r.height * 100 - 50; 367 const prev = this._view.s; 368 const next = clampS(prev * Math.pow(1.0015, -e.deltaY)); 369 if (next === prev) return;
370 const k = next / prev; 371 this._view.s = next; 372 this._view.x = cx * (1 - k) + this._view.x * k; 373 this._view.y = cy * (1 - k) + this._view.y * k; 374 this._clampView(); 375 this._applyView(); 376 }, { passive: false }); 377 } 378 379 connectedCallback() { 380 // Warn once per page â an id-less slot works for the session but 381 // cannot persist, and two id-less slots would share nothing. 382 if (!this.id && !ImageSlot._warned) { 383 ImageSlot._warned = true; 384 console.warn('<image-slot> without an id will not persist its dropped image.'); 385 } 386 this.addEventListener('dragenter', this); 387 this.addEventListener('dragover', this); 388 this.addEventListener('dragleave', this); 389 this.addEventListener('drop', this); 390 subs.add(this._subFn); 391 // width%/height% in _applyView encode the frame aspect at call time â 392 // a host resize (responsive grid, pane divider) would stretch the 393 // image until the next _render. Re-render on size change: _render() 394 // re-seeds _view from stored before clamp/apply, so a shrinkâgrow 395 // cycle round-trips instead of ratcheting x/y toward the narrower 396 // frame's clamp range. 397 this._ro = new ResizeObserver(() => this._render()); 398 this._ro.observe(this); 399 load(); 400 this._render(); 401 } 402 403 disconnectedCallback() { 404 subs.delete(this._subFn); 405 this.removeEventListener('dragenter', this); 406 this.removeEventListener('dragover', this); 407 this.removeEventListener('dragleave', this); 408 this.removeEventListener('drop', this); 409 if (this._ro) { this._ro.disconnect(); this._ro = null; } 410 this._exitReframe(false); 411 } 412 413 _enterReframe() { 414 if (this.hasAttribute('data-reframe')) return; 415 this.setAttribute('data-reframe', ''); 416 this._applyView(); 417 // Close on click outside (the spill handler stopPropagation()s so 418 // in-image drags don't reach this) and on Escape. Listeners are held 419 // on the instance so _exitReframe / disconnectedCallback can detach 420 // exactly what was attached. 421 this._outside = (e) => { 422 if (e.composedPath && e.composedPath().includes(this)) return; 423 this._exitReframe(true); 424 }; 425 this._esc = (e) => { if (e.key === 'Escape') this._exitReframe(true); }; 426 document.addEventListener('pointerdown', this._outside, true); 427 document.addEventListener('keydown', this._esc, true); 428 } 429 430 _exitReframe(commit) { 431 if (!this.hasAttribute('data-reframe')) return; 432 if (this._dragUp) this._dragUp(); 433 this.removeAttribute('data-reframe'); 434 this.removeAttribute('data-panning'); 435 if (this._outside) document.removeEventListener('pointerdown', this._outside, true); 436 if (this._esc) document.removeEventListener('keydown', this._esc, true); 437 this._outside = this._esc = null; 438 if (commit) this._commitView(); 439 } 440 441 attributeChangedCallback() { if (this.shadowRoot) this._render(); } 442 443 // handleEvent â one listener object for all four drag events keeps the 444 // add/remove symmetric and the depth counter correct. 445 handleEvent(e) { 446 if (e.type === 'dragenter' || e.type === 'dragover') { 447 // Without preventDefault the browser never fires 'drop'. 448 e.preventDefault(); 449 e.stopPropagation(); 450 if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; 451 if (e.type === 'dragenter') this._depth++; 452 this.setAttribute('data-over', ''); 453 } else if (e.type === 'dragleave') { 454 // dragenter/leave fire for every descendant crossing â count depth 455 // so hovering the icon inside the empty state doesn't flicker. 456 if (--this._depth <= 0) { this._depth = 0; this.removeAttribute('data-over'); } 457 } else if (e.type === 'drop') { 458 e.preventDefault(); 459 e.stopPropagation(); 460 this._depth = 0; 461 this.removeAttribute('data-over'); 462 const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]; 463 if (f) this._ingest(f); 464 } 465 } 466 467 async _ingest(file) { 468 this._setError(null); 469 if (!file || ACCEPT.indexOf(file.type) < 0) { 470 this._setError('Drop a PNG, JPEG, WebP, or AVIF image.'); 471 return; 472 } 473 // toDataUrl can take hundreds of ms on a large photo. A Clear or a 474 // newer drop during that window would be clobbered when this await 475 // resumes â bump + capture a generation so stale encodes bail. 476 const gen = ++this._gen;
477 try { 478 const w = this.clientWidth || this.offsetWidth || MAX_DIM; 479 const url = await toDataUrl(file, w); 480 if (gen !== this._gen) return; 481 // Only exit reframe once the new image is in hand â a rejected type 482 // or decode failure leaves the in-progress crop untouched. 483 this._exitReframe(false); 484 const val = { u: url, s: 1, x: 0, y: 0 }; 485 setSlot(this.id || '', val); 486 // Keep a session-local copy for id-less slots so the drop still 487 // shows, even though it cannot persist. 488 if (!this.id) { this._local = val; this._render(); } 489 } catch (err) { 490 if (gen !== this._gen) return; 491 this._setError('Could not read that image.'); 492 console.warn('<image-slot> ingest failed:', err); 493 } 494 } 495 496 _setError(msg) { 497 if (this._err) { this._err.remove(); this._err = null; } 498 if (!msg) return; 499 const d = document.createElement('div'); 500 d.className = 'err'; d.textContent = msg; 501 this.shadowRoot.appendChild(d); 502 this._err = d; 503 setTimeout(() => { if (this._err === d) { d.remove(); this._err = null; } }, 3000); 504 } 505 506 // Reframing (pan/resize) is only meaningful for fit=cover â contain/fill 507 // keep the old object-fit path and double-click is a no-op. 508 _reframes() { 509 return this.hasAttribute('data-filled') && 510 (this.getAttribute('fit') || 'cover') === 'cover'; 511 } 512 513 // Cover-baseline geometry, shared by clamp/apply/resize. Null until the 514 // img has loaded (naturalWidth is 0 before that) or when the slot has no 515 // layout box â ResizeObserver fires with a 0Ã0 rect under display:none, 516 // and clamping against a degenerate 1Ã1 frame would silently pull the 517 // stored pan toward zero. 518 _geom() { 519 const iw = this._img.naturalWidth, ih = this._img.naturalHeight; 520 const fw = this.clientWidth, fh = this.clientHeight; 521 if (!iw || !ih || !fw || !fh) return null; 522 return { iw, ih, fw, fh, base: Math.max(fw / iw, fh / ih) }; 523 } 524 525 _clampView() { 526 // Pan range on each axis is half the overflow past the frame edge. 527 const g = this._geom(); 528 if (!g) return; 529 const mx = Math.max(0, (g.iw * g.base * this._view.s / g.fw - 1) * 50); 530 const my = Math.max(0, (g.ih * g.base * this._view.s / g.fh - 1) * 50); 531 this._view.x = Math.max(-mx, Math.min(mx, this._view.x)); 532 this._view.y = Math.max(-my, Math.min(my, this._view.y)); 533 } 534 535 _applyView() { 536 const g = this._geom(); 537 const fit = this.getAttribute('fit') || 'cover'; 538 if (fit !== 'cover' || !g) { 539 // Non-cover, or dimensions not known yet (before img load). 540 this._img.style.width = '100%'; 541 this._img.style.height = '100%'; 542 this._img.style.left = '50%'; 543 this._img.style.top = '50%'; 544 this._img.style.objectFit = fit; 545 this._img.style.objectPosition = this.getAttribute('position') || '50% 50%'; 546 return; 547 } 548 // Cover baseline: img fills the frame on its tighter axis at s=1, so 549 // pan works immediately on the overflowing axis without zooming first. 550 // Width/height and left/top are all frame-% â depends only on the 551 // frame aspect ratio, so a responsive resize keeps the same crop. The 552 // spill layer mirrors the same box so its corners = image corners. 553 const k = g.base * this._view.s; 554 const w = (g.iw * k / g.fw * 100) + '%'; 555 const h = (g.ih * k / g.fh * 100) + '%'; 556 const l = (50 + this._view.x) + '%'; 557 const t = (50 + this._view.y) + '%'; 558 this._img.style.width = w; this._img.style.height = h; 559 this._img.style.left = l; this._img.style.top = t; 560 this._img.style.objectFit = ''; 561 this._spill.style.width = w; this._spill.style.height = h; 562 this._spill.style.left = l; this._spill.style.top = t; 563 } 564 565 _commitView() { 566 const v = { s: this._view.s, x: this._view.x, y: this._view.y }; 567 if (this._userUrl) v.u = this._userUrl; 568 // Framing-only (no u) persists too so an author-src slot remembers its 569 // crop; clearing the sidecar still falls through to src=.
570 if (this.id) setSlot(this.id, v); 571 else { this._local = v; } 572 } 573 574 _render() { 575 // Shape / mask. Presets use border-radius so the dashed ring can 576 // follow the rounded outline; clip-path is only applied for an 577 // explicit `mask` (the ring is hidden there since a rectangle 578 // dashed border chopped by an arbitrary polygon looks broken). 579 const mask = this.getAttribute('mask'); 580 const shape = (this.getAttribute('shape') || 'rounded').toLowerCase(); 581 let radius = ''; 582 if (shape === 'circle') radius = '50%'; 583 else if (shape === 'pill') radius = '9999px'; 584 else if (shape === 'rounded') { 585 const n = parseFloat(this.getAttribute('radius')); 586 radius = (Number.isFinite(n) ? n : 12) + 'px'; 587 } 588 this._frame.style.borderRadius = mask ? '' : radius; 589 this._frame.style.clipPath = mask || ''; 590 this._ring.style.borderRadius = mask ? '' : radius; 591 this._ring.style.display = mask ? 'none' : ''; 592 593 // Controls and reframe entry gate on this so share links stay read-only. 594 const editable = !!(window.omelette && window.omelette.writeFile); 595 this.toggleAttribute('data-editable', editable); 596 this._sub.style.display = editable ? '' : 'none'; 597 598 // Content. The sidecar is also writable by the agent's write_file 599 // tool, so its value isn't guaranteed canvas-originated â only accept 600 // data:image/ URLs from it. The `src` attribute is author-controlled 601 // (Claude wrote it into the HTML) so it passes through unchanged. 602 let stored = this.id ? getSlot(this.id) : this._local; 603 if (stored && stored.u && !/^data:image\//i.test(stored.u)) stored = null; 604 const srcAttr = this.getAttribute('src') || ''; 605 this._userUrl = (stored && stored.u) || null; 606 const url = this._userUrl || srcAttr; 607 // Don't clobber an in-flight reframe with a store-triggered re-render. 608 if (!this.hasAttribute('data-reframe')) { 609 this._view = { 610 s: stored && Number.isFinite(stored.s) ? clampS(stored.s) : 1, 611 x: stored && Number.isFinite(stored.x) ? stored.x : 0, 612 y: stored && Number.isFinite(stored.y) ? stored.y : 0, 613 }; 614 } 615 this._cap.textContent = this.getAttribute('placeholder') || 'Drop an image'; 616 // Toggle via style.display â the [hidden] attribute alone loses to 617 // the display:flex / display:block rules in the stylesheet above. 618 if (url) { 619 if (this._img.getAttribute('src') !== url) { 620 this._img.src = url; 621 this._ghost.src = url; 622 } 623 this._img.style.display = 'block'; 624 this._empty.style.display = 'none'; 625 this.setAttribute('data-filled', ''); 626 this._clampView(); 627 this._applyView(); 628 } else { 629 this._img.style.display = 'none'; 630 this._img.removeAttribute('src'); 631 this._ghost.removeAttribute('src'); 632 this._empty.style.display = 'flex'; 633 this.removeAttribute('data-filled'); 634 } 635 } 636 } 637 638 if (!customElements.get('image-slot')) { 639 customElements.define('image-slot', ImageSlot); 640 } 641})();
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.