Spaces:
Running
Running
Upload 10 files
Browse filesKugguk LAbs card
Files changed (11)
- .gitattributes+2
- .thumbnailAdded
- Kugguk Labs Readme.dc.htmlAdded+39
- RCV Local.dc.htmlAdded+333
- README.md+50-10
- animations-v3.jsxAdded+1347
- assets/zebra-k2.pngAdded
- kugguk-piece.jsxAdded+314
- support.jsAdded+1911
- tweaks-panel.jsxAdded+553
- uploads/Gemini_Generated_Image_3ltthj3ltthj3ltt.pngAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/zebra-k2.png filter=lfs diff=lfs merge=lfs -textuploads/Gemini_Generated_Image_3ltthj3ltthj3ltt.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><script src="./support.js"></script></head><body><x-dc><helmet> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" /> <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" /> <style> body { margin: 0; background: #070807; } a { color: #E9A23B; } a:hover { color: #F3F1EB; } </style> <script>window.OM_SCENES = '[{"name":"Boot","dur":3.5,"desc":"Instrument grid and timecode come up; the KUGGUK LABS logotype wipes in at hero scale"},{"name":"Thesis","dur":4,"desc":"The logotype shrinks into the top-left chrome slot while the headline Machines under observation rises and an amber rule draws across"},{"name":"Body","dur":6,"desc":"The premise paragraph reveals line by line as the camera creeps in"},{"name":"Domains","dur":7,"desc":"A signal travels a horizontal track, lighting the five work domains one by one while the camera pans right"},{"name":"Trace","dur":5.5,"desc":"Leave a trace headline, then four evidence cards stamp in"},{"name":"Local","dur":7.5,"desc":"RCV: three seconds stored offline, and the signal drops down the WebGPU to WASM to CPU fallback chain, ending on no upload no trace no proof of work"},{"name":"Close","dur":6.5,"desc":"Ideas enter then transformations can make a brand lands word by word, the framed field-unit specimen plate is revealed beside it, then everything fades back to the empty grid for the loop"}]';</script> <script>window.OM_PLAYBACK = '{"mode":"loop"}';</script> <script>window.TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{ "accent": "#E9A23B", "grid": true, "motionEditor": true }/*EDITMODE-END*/;</script></helmet><x-import component-from-global-scope="CompositionStage" from="./animations-v3.jsx ./tweaks-panel.jsx ./kugguk-piece.jsx" width="1920" height="1080" bg="#0A0B0B" scenes="{{ scenes }}" playback="{{ playback }}" hint-size="100%,100%"> <x-import component-from-global-scope="KuggukStage" hint-size="100%,100%"></x-import></x-import></x-dc><script type="text/x-dc" data-dc-script>class Component extends DCLogic { renderVals() { return { scenes: window.OM_SCENES, playback: window.OM_PLAYBACK }; }}</script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><script src="./support.js"></script></head><body><x-dc><helmet> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" /> <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" /> <style> body { margin: 0; background: #0A0B0B; } a { color: #E9A23B; text-decoration: none; border-bottom: 1px solid #3a2f16; } a:hover { color: #F3F1EB; } </style></helmet><div style="min-height: 100vh; background: #0A0B0B; color: #F3F1EB; font-family: 'Space Grotesk', system-ui, sans-serif; padding: 72px 0 120px; background-image: linear-gradient(to right, #17191800 0, #171918 1px, transparent 1px), linear-gradient(to bottom, #171918 1px, transparent 1px); background-size: 80px 80px;"> <div style="max-width: 1040px; margin: 0 auto; padding: 0 40px; display: flex; flex-direction: column; gap: 64px;">
<header style="display: flex; flex-direction: column; gap: 28px;"> <div style="display: flex; justify-content: space-between; align-items: baseline; font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.28em; color: #83857E;"> <span>KUGGUK LABS · OBSERVATION LOG</span> <span style="color: #E9A23B;">RCV · LOCAL ONLY</span> </div> <h1 style="margin: 0; font: 600 76px/1.02 'Space Grotesk', sans-serif; letter-spacing: -0.035em;">Three seconds,<br /><span style="color: #E9A23B;">stored offline.</span></h1> <div style="display: grid; grid-template-columns: 1fr 320px; gap: 40px; align-items: start;"> <p style="margin: 0; font: 400 24px/1.5 'Space Grotesk', sans-serif; color: #C7C6BF;">RCV takes a 3 second voice recording, keeps it on the device, and applies it to zyntalic text locally, so playback adapts and improves with use. No upload, no round trip, no server-side copy of a voice.</p> <figure style="margin: 0; display: flex; flex-direction: column; gap: 12px;"> <div style="display: flex; justify-content: space-between; font: 500 11px 'JetBrains Mono', monospace; letter-spacing: 0.22em; color: #83857E;"><span>SPECIMEN 001</span><span style="color: #E9A23B;">K2 · 8,611M</span></div> <div style="border: 1px solid #232624; background: #0E100F; padding: 8px;"> <div style="overflow: hidden; height: 168px;"> <img src="./assets/zebra-k2.png" alt="Field unit on K2" style="width: 168%; margin-left: -34%; display: block; filter: saturate(0.5) contrast(1.06) brightness(0.86) sepia(0.12);" /> </div> </div> <figcaption style="font: 400 12px/1.5 'JetBrains Mono', monospace; letter-spacing: 0.04em; color: #5f615c;">field unit · observed, unbothered</figcaption> </figure> </div> </header>
<section style="display: flex; flex-direction: column; gap: 24px;"> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.28em; color: #83857E;">01 — PIPELINE</div> <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px;"> <div style="border: 1px solid #232624; background: #0E100F; padding: 24px;"> <div style="font: 500 11px 'JetBrains Mono', monospace; letter-spacing: 0.24em; color: #E9A23B;">CAPTURE</div> <div style="margin-top: 14px; font: 400 22px/1.3 'Space Grotesk', sans-serif;">3s from the mic</div> </div> <div style="border: 1px solid #232624; background: #0E100F; padding: 24px;"> <div style="font: 500 11px 'JetBrains Mono', monospace; letter-spacing: 0.24em; color: #E9A23B;">STORE</div> <div style="margin-top: 14px; font: 400 22px/1.3 'Space Grotesk', sans-serif;">IndexedDB, this origin</div> </div> <div style="border: 1px solid #232624; background: #0E100F; padding: 24px;"> <div style="font: 500 11px 'JetBrains Mono', monospace; letter-spacing: 0.24em; color: #E9A23B;">COMPUTE</div> <div style="margin-top: 14px; font: 400 22px/1.3 'Space Grotesk', sans-serif;">WebGPU → WASM → CPU</div> </div> <div style="border: 1px solid #232624; background: #0E100F; padding: 24px;"> <div style="font: 500 11px 'JetBrains Mono', monospace; letter-spacing: 0.24em; color: #E9A23B;">PLAYBACK</div> <div style="margin-top: 14px; font: 400 22px/1.3 'Space Grotesk', sans-serif;">adapts each replay</div> </div> </div> </section>
<section style="display: flex; flex-direction: column; gap: 24px;"> <div style="display: flex; justify-content: space-between; align-items: baseline;"> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.28em; color: #83857E;">02 — TIERS ON THIS DEVICE</div> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.2em; color: #E9A23B;">SELECTED: {{ tierLabel }}</div> </div> <div style="display: flex; flex-direction: column; gap: 12px;"> <sc-for list="{{ tiers }}" as="t" hint-placeholder-count="3"> <div style="display: grid; grid-template-columns: 132px 1fr 200px; gap: 24px; align-items: center; border: 1px solid #232624; background: #0E100F; padding: 22px 26px;"> <div style="font: 500 18px 'JetBrains Mono', monospace; letter-spacing: 0.1em;">{{ t.name }}</div> <div style="font: 400 19px/1.4 'Space Grotesk', sans-serif; color: #C7C6BF;">{{ t.detail }}</div> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.22em; text-align: right;">{{ t.status }}</div> </div> </sc-for> </div> <div style="font: 400 16px/1.6 'Space Grotesk', sans-serif; color: #83857E;">The tiers are a fallback chain, not a feature ladder: the same transform runs on all three, only the throughput differs. Hardware concurrency reported: {{ cores }}.</div> </section>
<section style="display: flex; flex-direction: column; gap: 24px;"> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.28em; color: #83857E;">03 — LIVE PROBE</div> <div style="border: 1px solid #232624; background: #0E100F; padding: 40px; display: flex; flex-direction: column; gap: 30px;"> <div style="display: flex; gap: 20px; align-items: center; flex-wrap: wrap;"> <button onClick="{{ record }}" style="font: 500 14px 'JetBrains Mono', monospace; letter-spacing: 0.18em; padding: 18px 30px; min-height: 44px; background: #E9A23B; color: #0A0B0B; border: none; cursor: pointer;" style-hover="background: #F3B54F;">RECORD 3s</button> <button onClick="{{ play }}" style="font: 500 14px 'JetBrains Mono', monospace; letter-spacing: 0.18em; padding: 18px 30px; min-height: 44px; background: transparent; color: #F3F1EB; border: 1px solid #3a3d3a; cursor: pointer;" style-hover="border-color: #E9A23B; color: #E9A23B;">REPLAY LOCALLY</button> <button onClick="{{ wipe }}" style="font: 500 14px 'JetBrains Mono', monospace; letter-spacing: 0.18em; padding: 18px 30px; min-height: 44px; background: transparent; color: #83857E; border: 1px solid #232624; cursor: pointer;" style-hover="color: #F3F1EB;">WIPE</button> <div style="font: 500 13px 'JetBrains Mono', monospace; letter-spacing: 0.16em; color: #E9A23B;">{{ status }}</div> </div> <div style="height: 96px; border-bottom: 1px solid #232624; display: flex; align-items: flex-end; gap: 2px;"> <sc-for list="{{ wave }}" as="bar" hint-placeholder-count="64"> <div style="flex: 1; background: #E9A23B; opacity: 0.85; min-height: 1px; height: {{ bar.h }}"></div> </sc-for> </div> <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; font: 400 15px/1.5 'Space Grotesk', sans-serif; color: #83857E;"> <div>Replays: <span style="color: #F3F1EB;">{{ plays }}</span></div> <div>Adapted rate: <span style="color: #F3F1EB;">{{ rate }}</span></div> <div>Bytes held locally: <span style="color: #F3F1EB;">{{ bytes }}</span></div> </div> </div> </section>
<section style="display: flex; flex-direction: column; gap: 20px;"> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.28em; color: #83857E;">04 — THE IMPOSSIBLE PART</div> <p style="margin: 0; max-width: 860px; font: 400 32px/1.4 'Space Grotesk', sans-serif; letter-spacing: -0.02em;">Believing this works for most users locally, with <span style="color: #E9A23B;">no legal trace and no proof of work</span>.</p> <p style="margin: 0; max-width: 780px; font: 400 19px/1.65 'Space Grotesk', sans-serif; color: #C7C6BF;">There is no receipt to point at: no server log, no signed job, no verifiable state transition to inspect. Everything that makes the design defensible in private is the same thing that makes it unprovable in public. The work is not illegal today, but a transmitted clone is evidence, and evidence outlives intent. Keeping capture, storage and inference on one machine removes the transmission step entirely.</p> </section>
<section style="display: flex; flex-direction: column; gap: 18px;"> <div style="font: 500 12px 'JetBrains Mono', monospace; letter-spacing: 0.28em; color: #83857E;">05 — LIMITATIONS</div> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;"> <div style="border-left: 1px solid #E9A23B; padding: 4px 0 4px 22px; font: 400 18px/1.5 'Space Grotesk', sans-serif; color: #C7C6BF;">3 seconds is a thin sample. Quality varies by voice, microphone and room.</div> <div style="border-left: 1px solid #E9A23B; padding: 4px 0 4px 22px; font: 400 18px/1.5 'Space Grotesk', sans-serif; color: #C7C6BF;">WebGPU availability is uneven; most devices land on the WASM or CPU tier.</div> <div style="border-left: 1px solid #E9A23B; padding: 4px 0 4px 22px; font: 400 18px/1.5 'Space Grotesk', sans-serif; color: #C7C6BF;">Storage is per-browser, per-origin. Clearing site data destroys the recording, by design.</div> <div style="border-left: 1px solid #E9A23B; padding: 4px 0 4px 22px; font: 400 18px/1.5 'Space Grotesk', sans-serif; color: #C7C6BF;">The absence of a trace is a deliberate property, not an oversight.</div> </div> <div style="margin-top: 20px; font: 400 15px/1.6 'JetBrains Mono', monospace; color: #5f615c;">This page probes real capabilities and records real audio into local storage. The transform is a sample-level pitch and gain kernel, not a voice model.</div> </section> </div></div></x-dc><script type="text/x-dc" data-dc-script>class Component extends DCLogic { state = { gpu: 'probing', gpuName: '', simd: 'probing', cores: '—', tier: '—', status: 'IDLE', plays: 0, rate: 1, bytes: 0, wave: [] };
componentDidMount() { const cores = navigator.hardwareConcurrency || '—'; let simd = false; try { simd = WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])); } catch (e) { simd = false; } this.setState({ cores, simd: simd ? 'available' : 'unavailable' }); if (navigator.gpu && navigator.gpu.requestAdapter) { navigator.gpu.requestAdapter().then((a) => { if (!a) return this.setState({ gpu: 'unavailable' }, this.pickTier); const info = (a.info && (a.info.vendor || a.info.description)) || ''; this.setState({ gpu: 'available', gpuName: String(info).slice(0, 28) }, this.pickTier); }).catch(() => this.setState({ gpu: 'unavailable' }, this.pickTier)); } else { this.setState({ gpu: 'unavailable' }, this.pickTier); } this.openDb().then((db) => this.load(db)).catch(() => {}); }
pickTier = () => { const s = this.state; this.setState({ tier: s.gpu === 'available' ? 'WEBGPU' : s.simd === 'available' ? 'WASM' : 'CPU' }); };
openDb() { return new Promise((res, rej) => { const r = indexedDB.open('kugguk-rcv', 1); r.onupgradeneeded = () => r.result.createObjectStore('clips'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); }); }
store(blob) { return this.openDb().then((db) => new Promise((res) => { const tx = db.transaction('clips', 'readwrite'); tx.objectStore('clips').put(blob, 'sample'); tx.oncomplete = () => res(); })); }
load(db) { return new Promise((res) => { const tx = db.transaction('clips', 'readonly'); const q = tx.objectStore('clips').get('sample'); q.onsuccess = () => { if (!q.result) return res(); this.decode(q.result).then(() => this.setState({ status: 'HELD LOCALLY' })); res(); }; q.onerror = () => res(); }); }
decode(blob) { this.setState({ bytes: blob.size }); return blob.arrayBuffer() .then((ab) => { this.ctx = this.ctx || new (window.AudioContext || window.webkitAudioContext)(); return this.ctx.decodeAudioData(ab); }) .then((buf) => { this.buf = buf; this.drawWave(buf); }) .catch(() => {}); }
drawWave(buf) { const d = buf.getChannelData(0), N = 72, step = Math.floor(d.length / N); const wave = []; for (let i = 0; i < N; i++) { let peak = 0; for (let j = 0; j < step; j += 8) peak = Math.max(peak, Math.abs(d[i * step + j] || 0)); wave.push({ h: Math.max(2, Math.round(peak * 96)) + 'px' }); } this.setState({ wave }); }
record = () => { this.setState({ status: 'REQUESTING MIC' }); navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { const rec = new MediaRecorder(stream); const parts = []; rec.ondataavailable = (e) => parts.push(e.data); rec.onstop = () => { stream.getTracks().forEach((t) => t.stop()); const blob = new Blob(parts, { type: rec.mimeType || 'audio/webm' }); this.store(blob).then(() => this.decode(blob)).then(() => this.setState({ status: 'STORED OFFLINE', plays: 0, rate: 1 })); }; rec.start(); this.setState({ status: 'RECORDING 3s' }); setTimeout(() => rec.state !== 'inactive' && rec.stop(), 3000); }).catch(() => this.setState({ status: 'MIC DENIED' })); };
// Same kernel on every tier: resample + gain. WebGPU runs it as a compute // shader; the CPU path is the plain-JS floor. gpuKernel(input, rate, gain) { const dev = this.dev; const n = Math.floor(input.length / rate); const inBuf = dev.createBuffer({ size: input.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); dev.queue.writeBuffer(inBuf, 0, input); const outBuf = dev.createBuffer({ size: n * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC }); const readBuf = dev.createBuffer({ size: n * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); const par = dev.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); dev.queue.writeBuffer(par, 0, new Float32Array([rate, gain, input.length, n])); const mod = dev.createShaderModule({ code: ` struct P { rate: f32, gain: f32, inLen: f32, outLen: f32 }; @group(0) @binding(0) var<storage, read> src: array<f32>; @group(0) @binding(1) var<storage, read_write> dst: array<f32>; @group(0) @binding(2) var<uniform> p: P; @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3<u32>) { let i = gid.x; if (f32(i) >= p.outLen) { return; } let pos = f32(i) * p.rate; let i0 = u32(floor(pos)); let f = pos - floor(pos); let a = src[i0]; let b = src[min(i0 + 1u, u32(p.inLen) - 1u)]; dst[i] = (a + (b - a) * f) * p.gain; }` }); const pipe = dev.createComputePipeline({ layout: 'auto', compute: { module: mod, entryPoint: 'main' } }); const bind = dev.createBindGroup({ layout: pipe.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: inBuf } }, { binding: 1, resource: { buffer: outBuf } }, { binding: 2, resource: { buffer: par } } ] }); const enc = dev.createCommandEncoder(); const pass = enc.beginComputePass(); pass.setPipeline(pipe); pass.setBindGroup(0, bind); pass.dispatchWorkgroups(Math.ceil(n / 64)); pass.end(); enc.copyBufferToBuffer(outBuf, 0, readBuf, 0, n * 4); dev.queue.submit([enc.finish()]); return readBuf.mapAsync(GPUMapMode.READ).then(() => { const out = new Float32Array(readBuf.getMappedRange().slice(0)); readBuf.unmap(); return out; }); }
cpuKernel(input, rate, gain) { const n = Math.floor(input.length / rate), out = new Float32Array(n); for (let i = 0; i < n; i++) { const pos = i * rate, i0 = Math.floor(pos), f = pos - i0; const a = input[i0] || 0, b = input[Math.min(i0 + 1, input.length - 1)] || 0; out[i] = (a + (b - a) * f) * gain; } return Promise.resolve(out); }
play = () => { if (!this.buf) return this.setState({ status: 'NOTHING HELD' }); this.ctx = this.ctx || new (window.AudioContext || window.webkitAudioContext)(); const plays = this.state.plays + 1; // "adapt": each replay converges toward the target rate const rate = +(1 + (0.94 - 1) * (1 - Math.pow(0.6, plays))).toFixed(3); const src = this.buf.getChannelData(0); const useGpu = this.state.tier === 'WEBGPU'; const run = () => (useGpu ? this.gpuKernel(src, rate, 1.08) : this.cpuKernel(src, rate, 1.08)); const start = performance.now(); const ensure = useGpu && !this.dev ? navigator.gpu.requestAdapter().then((a) => a.requestDevice()).then((d) => { this.dev = d; }) : Promise.resolve(); ensure.then(run).catch(() => this.cpuKernel(src, rate, 1.08)).then((out) => { const ab = this.ctx.createBuffer(1, out.length, this.buf.sampleRate); ab.copyToChannel(out, 0); const node = this.ctx.createBufferSource(); node.buffer = ab; node.connect(this.ctx.destination); node.start(); this.drawWave(ab); const ms = Math.round(performance.now() - start); this.setState({ plays, rate, status: `${useGpu ? 'WEBGPU' : 'CPU'} KERNEL ${ms}ms` }); }); };
wipe = () => { this.openDb().then((db) => { const tx = db.transaction('clips', 'readwrite'); tx.objectStore('clips').delete('sample'); tx.oncomplete = () => { this.buf = null; this.setState({ status: 'WIPED', wave: [], bytes: 0, plays: 0, rate: 1 }); }; }); };
renderVals() { const s = this.state; const mark = (v) => v === 'available' ? 'READY' : v === 'probing' ? 'PROBING' : 'UNAVAILABLE'; return { tiers: [ { name: 'WEBGPU', detail: 'compute shader over the sample buffer' + (s.gpuName ? ' · ' + s.gpuName : ''), status: mark(s.gpu) }, { name: 'WASM', detail: 'SIMD kernel, worker threads if available', status: mark(s.simd) }, { name: 'CPU', detail: 'plain JS over Float32Array — the floor', status: 'READY' } ], tierLabel: s.tier, cores: String(s.cores), status: s.status, plays: s.plays, rate: s.rate.toFixed(3) + '×', bytes: s.bytes ? (s.bytes / 1024).toFixed(1) + ' KB' : '0 KB', wave: s.wave, record: this.record, play: this.play, wipe: this.wipe }; }}</script></body></html>1234567891011---title: Kugguk Labs RCVemoji: 🦓colorFrom: graycolorTo: yellowsdk: staticapp_file: RCV Local.dc.htmlfullWidth: trueheader: minishort_description: Three seconds, stored offline. WebGPU → WASM → CPU.---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Kugguk Labs## Bring AI out-of-its-box.We build experimental interfaces that expose how ideas are transformed, challenged, transmitted and preserved by machines.Our work moves between synthetic language, adversarial validation, forward-only inference, verifiable state transitions and private communication. Every public experiment is designed to leave a trace: stable inputs, visible transformations, explicit limitations and artifacts that others can inspect or reproduce.**Ideas enter then transformations can make a brand.**---## RCV — recorded, cloned, localRCV takes a **3 second voice recording**, keeps it **offline on the device**, and applies it to zyntalic text locally, so playback adapts and improves with use. Nothing is uploaded. There is no round trip, no account, and no server-side copy of a voice.**Pipeline**```3s capture → local store → compute tier → local playback(mic) (IndexedDB) WebGPUWASM (SIMD)CPU (JS)```**Compute tiers**, in order of preference. The device picks the first one it can prove it has:| Tier | Path | Selected when || --- | --- | --- || WebGPU | compute shader over the sample buffer | `navigator.gpu` returns an adapter || WASM | SIMD kernel, worker threads if available | WebAssembly SIMD validates || CPU | plain JS over `Float32Array` | always available, the floor |The tiers are a fallback chain, not a feature ladder: the same transform runs on all three, only the throughput differs. A device that can do none of them cannot run RCV at all — that is the honest failure mode.**Why local only**Direction of travel matters more than capability here. The work is not illegal today, but shared voice artifacts can become a liability the moment they leave the device: a transmitted clone is evidence, and evidence outlives intent. Keeping capture, storage and inference on one machine removes the transmission step entirely.**The impossible part**Believing this works for most users locally, with no legal trace and no proof of work. There is no receipt to point at — no server log, no signed job, no verifiable state transition to inspect. Everything that makes the design defensible in private is the same thing that makes it unprovable in public.**Limitations, stated plainly**- 3 seconds is a thin sample. Quality varies by voice, microphone and room.- WebGPU availability is uneven across browsers and drivers; most devices land on the WASM or CPU tier.- Offline storage is per-browser and per-origin. Clearing site data destroys the recording, by design.- No proof of work: the absence of a trace is a deliberate property, not an oversight.A live capability probe and a 3 second record/replay run in `RCV Local.dc.html`.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347// @ds-adherence-ignore -- omelette starter scaffold (raw elements/hex/px by design)// Copied omelette starter. Re-running copy_starter_component with this kind overwrites this file with the latest version (page content is unaffected).
/* BEGIN USAGE */// animations-v3.jsx — continuous-composition animation engine.//// THE MODEL: the animation is ONE element tree rendered as a pure function// of one authored-time axis. Nothing mounts or unmounts at section// boundaries, so any element can move, morph, or persist across them by// ordinary interpolation. The scene list (OM_SCENES) is the user-control// view — names, order, playback durations — and the engine derives the cue// table from it, so structure has exactly one source and cannot drift.//// API INDEX (every export is a window global):// <CompositionStage width height scenes={window.OM_SCENES}// playback={window.OM_PLAYBACK} bg>// <Piece /> — ONE component, the whole animation// </CompositionStage>// useComposition() -> {T, CUES, time, duration, authoredTotal, playing}// T: authored seconds (warped per-section by user trims/speeds) —// key ALL choreography to T, never to wall-clock time// CUES: {SectionName: authoredStart} derived from OM_SCENES; an unknown// name returns NaN and raises a preview-only badge (never exports);// duplicate section names bind to the first occurrence// <Shot from={CUES.Build} to={CUES.Close}> — children visible between two// authored times (an authored hard cut in one line); children stay// mounted (media keeps its readiness) and are hidden outside the window// <Captions items={[{at, until?, text}, ...]} /> — ONE caption element,// at most one visible at a time, keyed to T; 'until' defaults to the// next item's 'at'; a last item with no 'until' stays to the end// WATERCOLOR (only when the Watercolor illustration skill is active —// otherwise ignore these entries). A painting is a function(p) written// against the paint kit, on a width x height sheet; it needs// watercolor_kit.js loaded by a <script> tag before this engine, must// be a stable function defined once (module scope, never an inline// arrow), and every component below renders <img> elements, so it all// exports by construction.// <WatercolorPainting painting={fn} from={CUES.X} to={CUES.Y} width height// seed scale quality style /> — the painting assembled from its own// STROKES: each wash / ink line / splatter is a separate layer// stacked over the paper, appearing in painting order between two// authored times (washes bloom in, ink draws tip to tail). This is the// default way to show a watercolor being painted. It keeps the sheet's// aspect ratio (size it with style, e.g. {position:'absolute', left,// top, width}). scale is the layers' render resolution over width x// height (default 1, a deliberate weight-over-dpi trade — raise it// toward the zoom factor if the composition zooms into the painting,// or toward the devicePixelRatio for a hero-sized sheet); quality is// 0..1 layer image quality (default 0.92; 1 is the encoder's maximum).// useWatercolorLayers(fn, {width, height, seed, scale, quality}) -> L// (null if the kit isn't loaded — load watercolor_kit.js before the// engine — or if the painting fails to build) — the painting taken apart into strokes, for// choreography beyond in-order painting: L.count strokes, L.kind(i)// ('wash' | 'gradedWash' | 'glaze' | 'ink' | 'hatch' | 'splatter' |// 'dryStroke' | 'reserve' | 'caption'), L.span(i) = the stroke's// {from, to} share of the painting's 0..1 timeline; call L.warm()// once after load so finished strokes pre-render off the critical// path (WatercolorPainting does this itself). Compose with:// <WatercolorSheet layers={L} style>children</WatercolorSheet> — the// paper the strokes sit on (keeps the sheet's aspect ratio), and// <WatercolorStroke index={i} at={0..1} style /> — stroke i as its own// element, placed where it was painted; at is its painting progress// (0 hidden, 1 finished — drive it from T with animate()); style lets// you move, scale, rotate, or fade the stroke (transform / opacity).// Strokes are paint, so they multiply: overlapping strokes darken// where they cross, as in the still image, within a few 8-bit levels// (tighter still at quality 1). The sheet clips to its// box — for strokes that fly in from outside it, set// style={{overflow: 'visible'}} on the WatercolorSheet. 'reserve' strokes// are erasures (lifted paper) — keep them where they were painted and// reveal them in order after the strokes they erase; moving an erase// around has no sensible meaning.// <WatercolorReveal painting={fn} from={CUES.X} to={CUES.Y} width height// seed steps scale format quality style />, or <WatercolorReveal// frames={[src, ...]} from to /> — the whole painting as ONE flat// image that paints on (frames pre-baked in the background, so it is// the lightest option and the one to zoom or pan over as a single// picture). Prefer WatercolorPainting when the strokes themselves// should appear one by one or be individually animated. format is// the image MIME type (default image/jpeg), quality 0..1 (default// 0.88). Frames bake at width x height times scale (default: the// device pixel ratio, capped at 2) — if the composition zooms INTO// the painting, raise scale toward the maximum zoom so frames stay// crisp. The kit caps a sheet at ~12M pixels and the components clamp// scale to stay under it; exported video sharpness also depends on// the export dialog's own resolution choice.// Motion: Easing.{linear, easeIn|Out|InOutQuad/Cubic/Quart/Expo/Sine,// easeIn|Out|InOutBack, easeOutElastic}, interpolate(input, output, ease),// animate({from, to, start, end, ease}) -> fn(T), clamp(v, min, max)// Plumbing (rarely needed): Stage, PlaybackBar, TimelineContext,// useTime, useTimeline// Seek event (host/export transport): 'data-om-seek-to-time-frame',// detail {time, sync, playing} — the stage owns it; never implement it// yourself//// THE AUTHORING CONTRACT — this is what makes the host timeline's trim and// speed gestures write back into YOUR file, so follow it exactly:// 1. Declare the scene list as a JSON string literal in a plain inline// <script> of the main document (NOT type="text/babel", NOT a sibling// .jsx — only vanilla inline scripts are addressable for write-back):// <script>window.OM_SCENES = '[{"name":"Opening","dur":3,"desc":"The logo fades in and the title settles"},{"name":"Build","dur":5,"desc":"Bars grow to their final values"}]';</script>// Give every entry a "desc": one short plain-words sentence saying// what happens in that section. The user reads it in the timeline's// section popover — keep it true whenever you edit the section.// 2. Pass the string through untouched:// <CompositionStage scenes={window.OM_SCENES} ...>// 3. ALSO declare the playback setting the same way:// <script>window.OM_PLAYBACK = '{"mode":"loop"}';</script>// and pass it through untouched (values: '{"mode":"loop"}' or// '{"mode":"times","count":N}'; omitting keeps loop behavior but// leaves the host Repeat control read-only for this document).// IMPORTANT — the exportable-video contract: CompositionStage/Stage OWNS// it (the data-om-exportable-video-with-duration-secs attribute, the// data-om-seek-to-time-frame listener, the svg/foreignObject wrapper,// and font inlining). NEVER put the exportable attribute on any other// element — a second "exportable root" makes the host timeline and the// video exporter bind to the wrong element, and playback control /// export silently break.//// HOW TIME WORKS: each OM_SCENES entry is a named slice of the authored// timeline. CUES.Name is that section's authored start (the running sum of// authored lengths, in literal order). useComposition().T is the authored// clock: when the user trims or speeds a section on the host timeline, the// engine replays that section's SAME authored slice over the new playback// length — your choreography retimes, never cuts off. The optional "nat"// field on an entry is the engine's authored-length anchor — the host// timeline stamps it on the first retime; don't set it by hand.//// CUE-FIRST DISCIPLINE (what makes a piece read as one continuous video):// 1. Write the OM_SCENES literal FIRST — it is the piece's outline.// 2. One helper component per section for readability, but ALL of them// render ALL the time inside the one tree, keyed to CUES — never// conditionally mounted per section.// 3. Define exactly three motion helpers up front (e.g.// MOTION = {enter, draw, pop} wrapping Easing curves) and use no// easing or transform outside them; one caption element, one visible// at a time (<Captions> has this built in).// A shared element that crosses a boundary is just motion whose start// and end straddle a cue: animate({from, to, start: CUES.Build - 0.4,// end: CUES.Build + 0.6})(T) glides through the boundary, and a user// slowing either section slows the glide without breaking it.//// RENDER FROM T ONLY: the exporter seeks each frame with a synchronous// commit and may serialize the stage the moment the seek event returns —// anything painted from useEffect or your own requestAnimationFrame lags// that commit and exports stale. Render everything visible from T and this// is automatic. A seeked frame is a deterministic render at that time.//// HARD CUTS are content now, not structure: wrap a shot's elements in// <Shot from to> (visibility toggles at the cues; children stay mounted so// images and videos hold their readiness). Shot also doubles as the// perf gate for heavy far-away beats.//// LOOP SEAMS are the one surviving boundary rule: a looping piece shows// its last authored frame immediately before its first — make them match// (settle your choreography by authoredTotal, open it at 0).//// DIAGNOSTICS: choreography that references an unknown section name (a// rename or deletion in OM_SCENES) shows a badge below the stage in the// preview, outside the exportable svg — visible in preview screenshots,// never in the exported video. An OM_SCENES section with no choreography// keyed to it is a valid empty beat, not an error./* END USAGE */
// ─────────────────────────────────────────────────────────────────────────────
// ── Easing functions (hand-rolled, Popmotion-style) ─────────────────────────// All easings take t ∈ [0,1] and return eased t ∈ [0,1] (may overshoot for back/elastic).const Easing = { linear: (t) => t,
// Quad easeInQuad: (t) => t * t, easeOutQuad: (t) => t * (2 - t), easeInOutQuad: (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
// Cubic easeInCubic: (t) => t * t * t, easeOutCubic: (t) => (--t) * t * t + 1, easeInOutCubic: (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1),
// Quart easeInQuart: (t) => t * t * t * t, easeOutQuart: (t) => 1 - (--t) * t * t * t, easeInOutQuart: (t) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t),
// Expo easeInExpo: (t) => (t === 0 ? 0 : Math.pow(2, 10 * (t - 1))), easeOutExpo: (t) => (t === 1 ? 1 : 1 - Math.pow(2, -10 * t)), easeInOutExpo: (t) => { if (t === 0) return 0; if (t === 1) return 1; if (t < 0.5) return 0.5 * Math.pow(2, 20 * t - 10); return 1 - 0.5 * Math.pow(2, -20 * t + 10); },
// Sine easeInSine: (t) => 1 - Math.cos((t * Math.PI) / 2), easeOutSine: (t) => Math.sin((t * Math.PI) / 2), easeInOutSine: (t) => -(Math.cos(Math.PI * t) - 1) / 2,
// Back (overshoot) easeOutBack: (t) => { const c1 = 1.70158, c3 = c1 + 1; return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2); }, easeInBack: (t) => { const c1 = 1.70158, c3 = c1 + 1; return c3 * t * t * t - c1 * t * t; }, easeInOutBack: (t) => { const c1 = 1.70158, c2 = c1 * 1.525; return t < 0.5 ? (Math.pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2 : (Math.pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2; },
// Elastic easeOutElastic: (t) => { const c4 = (2 * Math.PI) / 3; if (t === 0) return 0; if (t === 1) return 1; return Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1; },};
// ── Core interpolation helpers ──────────────────────────────────────────────
// Clamp a value to [min, max]const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
// interpolate([0, 0.5, 1], [0, 100, 50], ease?) -> fn(t)// Popmotion-style: linearly maps t across input keyframes to output values,// with optional easing per segment (single fn or array of fns).function interpolate(input, output, ease = Easing.linear) { return (t) => { if (t <= input[0]) return output[0]; if (t >= input[input.length - 1]) return output[output.length - 1]; for (let i = 0; i < input.length - 1; i++) { if (t >= input[i] && t <= input[i + 1]) { const span = input[i + 1] - input[i]; const local = span === 0 ? 0 : (t - input[i]) / span; const easeFn = Array.isArray(ease) ? (ease[i] || Easing.linear) : ease; const eased = easeFn(local); return output[i] + (output[i + 1] - output[i]) * eased; } } return output[output.length - 1]; };}
// animate({from, to, start, end, ease})(t) — simpler single-segment tween.// Returns `from` before `start`, `to` after `end`.function animate({ from = 0, to = 1, start = 0, end = 1, ease = Easing.easeInOutCubic }) { return (t) => { if (t <= start) return from; if (t >= end) return to; const local = (t - start) / (end - start); return from + (to - from) * ease(local); };}
// ── Timeline context ────────────────────────────────────────────────────────
const TimelineContext = React.createContext({ time: 0, duration: 10, playing: false });
const useTime = () => React.useContext(TimelineContext).time;const useTimeline = () => React.useContext(TimelineContext);
// How long a marked (detail.playing === true) host seek keeps the// external-playback latch alive with no successor. The host play bar's// seek pump is one-in-flight/latest-wins, so its inter-seek gap is tens// of milliseconds in the worst case — 400ms is far above that, so a// marked stream that dies mid-play decays the latch promptly.var SS_EXT_PLAY_MS = 400;
// ── Font inlining ───────────────────────────────────────────────────────────// Copy every @font-face rule from the page into a <style> inside the svg's// foreignObject, with font URLs rewritten to data: URLs. Makes the svg// self-describing so serializing it alone (video export fast path) still// renders with the right fonts. Sets data-om-fonts-inlined on the svg when// done so the exporter can wait for it.
function useInlineFontsInto(svgRef) { React.useEffect(() => { const svg = svgRef.current; const host = svg && svg.querySelector('foreignObject > div'); if (!svg || !host) return; let cancelled = false; (async () => { const rules = []; for (const ss of document.styleSheets) { let cssRules; try { cssRules = ss.cssRules; } catch { // Cross-origin sheet without crossorigin attr (e.g. the standard // fonts.googleapis.com <link>) — fetch the CSS text directly and // regex-extract the @font-face blocks. if (ss.href) { try { const txt = await fetch(ss.href).then(r => { if (!r.ok) throw 0; return r.text(); }); for (const ff of (txt.match(/@font-face\s*{[^}]*}/g) || [])) rules.push({ css: ff, base: ss.href }); } catch {} } continue; } if (!cssRules) continue; for (const r of cssRules) { if (r.type === CSSRule.FONT_FACE_RULE) { rules.push({ css: r.cssText, base: ss.href || location.href }); } } } const toDataURL = (url) => fetch(url) .then(r => { if (!r.ok) throw 0; return r.blob(); }) .then(b => new Promise(res => { const fr = new FileReader(); fr.onload = () => res(fr.result); fr.onerror = () => res(url); fr.readAsDataURL(b); })) .catch(() => url); const parts = await Promise.all(rules.map(async ({ css, base }) => { const re = /url\((['"]?)([^'")]+)\1\)/g; let out = css, m; while ((m = re.exec(css))) { const u = m[2]; if (u.startsWith('data:')) continue; let abs; try { abs = new URL(u, base).href; } catch { continue; } out = out.split(m[0]).join(`url("${await toDataURL(abs)}")`); } return out; })); if (cancelled || !parts.length) { svg.setAttribute('data-om-fonts-inlined', 'true'); return; } const style = document.createElement('style'); style.textContent = parts.join('\n'); host.insertBefore(style, host.firstChild); svg.setAttribute('data-om-fonts-inlined', 'true'); })(); return () => { cancelled = true; }; }, []);}
function Stage({ width = 1280, height = 720, duration = 10, background = '#f6f4ef', fps = 60, loop = true, autoplay = true, // Parsed playback object ({mode:'loop'} | {mode:'times',count:N}) or // null. When present it overrides the legacy loop prop — CompositionStage // passes the validated value from the OM_PLAYBACK authoring contract. playback = null, persistKey = 'animstage-v3', children,}) { // Props arrive as strings when Stage is mounted via <x-import> (DC // projects) — coerce so style={{width}} gets a number React can px-ify. width = +width || 1280; height = +height || 720; duration = +duration || 10; fps = +fps || 60; if (typeof loop === 'string') loop = loop !== 'false'; if (typeof autoplay === 'string') autoplay = autoplay !== 'false'; const playTimes = playback && playback.mode === 'times' ? playback.count : null; const loopEff = playback ? playback.mode === 'loop' : loop;
const [time, setTime] = React.useState(() => { try { const v = parseFloat(localStorage.getItem(persistKey + ':t') || '0'); return isFinite(v) ? clamp(v, 0, duration) : 0; } catch { return 0; } }); const [playing, setPlaying] = React.useState(autoplay); // The external-playback latch: true while the HOST play bar is driving // time forward as genuine continuous playback (its play-loop seeks // carry detail.playing === true). The engine's own clock stays paused // the whole time — exactly one clock ever drives — so this is a // separate bit, not a second meaning for `playing`. Set and cleared // in the seek handler below; decays via SS_EXT_PLAY_MS when the // marked stream stops without a parting unmarked seek. const [extPlay, setExtPlay] = React.useState(false); const extPlayTimerRef = React.useRef(null); const [hoverTime, setHoverTime] = React.useState(null); const [scale, setScale] = React.useState(1);
const stageRef = React.useRef(null); const canvasRef = React.useRef(null); const rafRef = React.useRef(null); const lastTsRef = React.useRef(null);
// Persist playhead React.useEffect(() => { try { localStorage.setItem(persistKey + ':t', String(time)); } catch {} }, [time, persistKey]);
// Auto-scale to fit viewport React.useEffect(() => { if (!stageRef.current) return; const el = stageRef.current; const measure = () => { const barH = 44; // playback bar height const s = Math.min( el.clientWidth / width, (el.clientHeight - barH) / height ); setScale(Math.max(0.05, s)); }; measure(); const ro = new ResizeObserver(measure); ro.observe(el); window.addEventListener('resize', measure); return () => { ro.disconnect(); window.removeEventListener('resize', measure); }; }, [width, height]);
// Passes completed since playback last started. Lives in a ref so the // per-frame wrap can count without re-running this effect; reset on // every (re)start so a fresh play (or a host restart) gets the full // run count again. const passesRef = React.useRef(0);
// Animation loop React.useEffect(() => { if (!playing) { lastTsRef.current = null; return; } passesRef.current = 0; const step = (ts) => { if (lastTsRef.current == null) lastTsRef.current = ts; const dt = (ts - lastTsRef.current) / 1000; lastTsRef.current = ts; setTime((t) => { let next = t + dt; if (next >= duration) { if (playTimes !== null) { // Play N times then hold the last frame — the partial pass a // mid-timeline start produces counts as a pass, so the piece // never runs longer than N full durations. passesRef.current += 1; if (passesRef.current >= playTimes) { next = duration; setPlaying(false); } else { next = next % duration; } } else if (loopEff) { next = next % duration; } else { next = duration; setPlaying(false); } } return next; }); rafRef.current = requestAnimationFrame(step); }; rafRef.current = requestAnimationFrame(step); return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); lastTsRef.current = null; }; }, [playing, duration, loopEff, playTimes]);
// Keyboard: space = play/pause, ← → = seek React.useEffect(() => { const onKey = (e) => { if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return; if (e.code === 'Space') { e.preventDefault(); setPlaying(p => !p); } else if (e.code === 'ArrowLeft') { setTime(t => clamp(t - (e.shiftKey ? 1 : 0.1), 0, duration)); } else if (e.code === 'ArrowRight') { setTime(t => clamp(t + (e.shiftKey ? 1 : 0.1), 0, duration)); } else if (e.key === '0' || e.code === 'Home') { setTime(0); } }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [duration]);
// Video-export protocol + the editor's play bar: hosts dispatch this // event per frame; pause + sync the playhead so the frame shows exactly // that timestamp. The host play bar marks its play-loop seeks with // detail.playing === true — the mark latches extPlay (playback is // playback even when a host clock drives it), while ANY unmarked seek // (scrub, step, export frame, the transport's pause park) clears the // latch in the same commit it retimes, so a seeked frame still renders // exactly one scene's state. The engine's own clock pauses either way. React.useEffect(() => { const el = canvasRef.current; if (!el) return; // Sync-seek capability: a dispatcher that marks its seek with // detail.sync === true gets the commit applied via ReactDOM.flushSync, // so the stage DOM reflects the seeked frame the moment dispatchEvent // returns. The video exporter keys off the data-om-sync-seek // advertisement to drop its two-display-refresh settle (that wait only // exists to let React's async commit land — serialization needs the // committed DOM, not the paint). Feature-detected: a runtime without // ReactDOM.flushSync never advertises and every seek takes the async // path. Unmarked seeks (scrubs, the host play bar) stay async — a // forced sync render per pointermove would tax the editor for no one. const canSyncSeek = typeof ReactDOM !== 'undefined' && typeof ReactDOM.flushSync === 'function'; const onSeek = (e) => { const apply = () => { setPlaying(false); const hostPlay = !!(e.detail && e.detail.playing === true); if (extPlayTimerRef.current) { clearTimeout(extPlayTimerRef.current); extPlayTimerRef.current = null; } if (hostPlay) { // Watchdog: the latch is only as alive as its seek stream. If the // host stops without a parting seek (tab jank, bar unmount), the // latch decays on its own rather than stranding extPlaying true. extPlayTimerRef.current = setTimeout(() => { extPlayTimerRef.current = null; setExtPlay(false); }, SS_EXT_PLAY_MS); } setExtPlay(hostPlay); setTime(clamp(e.detail.time, 0, duration)); }; // flushSync is safe here: a native DOM listener runs outside React's // lifecycle, and the exporter's dispatchEvent is synchronous, so the // commit lands in the same JS task — the engine's own rAF loop can // never interleave between seek and serialize. if (canSyncSeek && e.detail && e.detail.sync === true) { ReactDOM.flushSync(apply); } else { apply(); } }; el.addEventListener('data-om-seek-to-time-frame', onSeek); if (canSyncSeek) el.setAttribute('data-om-sync-seek', 'true'); return () => { el.removeEventListener('data-om-seek-to-time-frame', onSeek); el.removeAttribute('data-om-sync-seek'); if (extPlayTimerRef.current) { clearTimeout(extPlayTimerRef.current); extPlayTimerRef.current = null; } // Drop the latch too: this cleanup runs on every duration change // (an agent edit can retime mid-host-play, no gesture involved) and // the new effect instance arms no watchdog — clearing only the // timer could strand extPlay true forever if the marked stream died // in the gap. Fail toward cut: the next marked seek re-latches. setExtPlay(false); }; }, [duration]);
// Inline @font-face rules into the svg's foreignObject so the svg is // self-describing — serializing it alone (for video export) then renders // with the right fonts. Sets data-om-fonts-inlined once done. useInlineFontsInto(canvasRef);
const displayTime = hoverTime != null ? hoverTime : time;
const ctxValue = React.useMemo( // extPlaying is ADDITIVE: "time is advancing under an external // driver's continuous playback". `playing` keeps meaning the // engine's OWN clock — the hidden PlaybackBar glyph (and through it // the host's clock-reporter/adoption channel) reads that — and // CompositionClock is the one consumer that widens to either. () => ({ time: displayTime, duration, playing, extPlaying: extPlay, setTime, setPlaying, }), [displayTime, duration, playing, extPlay] );
return ( // data-om-starter: inert presence marker — Claude Design's starter-usage // probe reads it; it renders nothing. Keep it on this root element. <div ref={stageRef} data-om-starter="animations-v3" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', background: '#0a0a0a', fontFamily: 'Inter, system-ui, sans-serif', }} > {/* Canvas area — vertically centered in remaining space */} <div style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', minHeight: 0, }}> <svg ref={canvasRef} width={width} height={height} data-om-exportable-video-with-duration-secs={duration} style={{ transform: `scale(${scale})`, transformOrigin: 'center', flexShrink: 0, boxShadow: '0 20px 60px rgba(0,0,0,0.4)', display: 'block', }} > <foreignObject x="0" y="0" width="100%" height="100%"> <div xmlns="http://www.w3.org/1999/xhtml" style={{ width, height, background, position: 'relative', overflow: 'hidden', }} > <TimelineContext.Provider value={ctxValue}> {children} </TimelineContext.Provider> </div> </foreignObject> </svg> </div>
{/* Playback bar — stacked below canvas, never overlapping */} <PlaybackBar time={displayTime} actualTime={time} duration={duration} playing={playing} onPlayPause={() => setPlaying(p => !p)} onReset={() => { setTime(0); }} onSeek={(t) => setTime(t)} onHover={(t) => setHoverTime(t)} /> </div> );}
// ── Playback bar ────────────────────────────────────────────────────────────// Play/pause, return-to-begin, scrub track, time display.// Uses fixed-width time fields so layout doesn't thrash.
function PlaybackBar({ time, duration, playing, onPlayPause, onReset, onSeek, onHover }) { const trackRef = React.useRef(null); const [dragging, setDragging] = React.useState(false);
const timeFromEvent = React.useCallback((e) => { const rect = trackRef.current.getBoundingClientRect(); const x = clamp((e.clientX - rect.left) / rect.width, 0, 1); return x * duration; }, [duration]);
const onTrackMove = (e) => { if (!trackRef.current) return; const t = timeFromEvent(e); if (dragging) { onSeek(t); } else { onHover(t); } };
const onTrackLeave = () => { if (!dragging) onHover(null); };
const onTrackDown = (e) => { setDragging(true); const t = timeFromEvent(e); onSeek(t); onHover(null); };
React.useEffect(() => { if (!dragging) return; const onUp = () => setDragging(false); const onMove = (e) => { if (!trackRef.current) return; const t = timeFromEvent(e); onSeek(t); }; window.addEventListener('mouseup', onUp); window.addEventListener('mousemove', onMove); return () => { window.removeEventListener('mouseup', onUp); window.removeEventListener('mousemove', onMove); }; }, [dragging, timeFromEvent, onSeek]);
const pct = duration > 0 ? (time / duration) * 100 : 0; const fmt = (t) => { const total = Math.max(0, t); const m = Math.floor(total / 60); const s = Math.floor(total % 60); const cs = Math.floor((total * 100) % 100); return `${String(m).padStart(1, '0')}:${String(s).padStart(2, '0')}.${String(cs).padStart(2, '0')}`; };
const mono = 'JetBrains Mono, ui-monospace, SFMono-Regular, monospace';
return ( <div data-omelette-chrome style={{ // Slimmed to visually match the host editor bar's basic row (the // single-scrubber look): transport first, tighter metrics, quieter // chrome. Shown only outside the app — the host bar suppresses this // whenever it is present. display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px', background: 'rgba(20,20,20,0.92)', borderTop: '1px solid rgba(255,255,255,0.08)', width: '100%', maxWidth: 680, alignSelf: 'center',
borderRadius: 6, color: '#f6f4ef', fontFamily: 'Inter, system-ui, sans-serif', userSelect: 'none', flexShrink: 0, }}> <IconButton onClick={onPlayPause} title="Play/pause (space)"> {playing ? ( <svg width="14" height="14" viewBox="0 0 14 14" fill="none"> <rect x="3" y="2" width="3" height="10" fill="currentColor"/> <rect x="8" y="2" width="3" height="10" fill="currentColor"/> </svg> ) : ( <svg width="14" height="14" viewBox="0 0 14 14" fill="none"> <path d="M3 2l9 5-9 5V2z" fill="currentColor"/> </svg> )} </IconButton> <IconButton onClick={onReset} title="Return to start (0)"> <svg width="14" height="14" viewBox="0 0 14 14" fill="none"> <path d="M3 2v10M12 2L5 7l7 5V2z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/> </svg> </IconButton>
{/* Current time: fixed width so it doesn't thrash */} <div style={{ fontFamily: mono, fontSize: 12, fontVariantNumeric: 'tabular-nums', width: 64, textAlign: 'right', color: '#f6f4ef', }}> {fmt(time)} </div>
{/* Scrub track */} <div ref={trackRef} onMouseMove={onTrackMove} onMouseLeave={onTrackLeave} onMouseDown={onTrackDown} style={{ flex: 1, height: 22, position: 'relative', cursor: 'pointer', display: 'flex', alignItems: 'center', }} > <div style={{ position: 'absolute', left: 0, right: 0, height: 4, background: 'rgba(255,255,255,0.12)', borderRadius: 2, }}/> <div style={{ position: 'absolute', left: 0, width: `${pct}%`, height: 4, background: 'oklch(72% 0.12 250)', borderRadius: 2, }}/> <div style={{ position: 'absolute', left: `${pct}%`, top: '50%', width: 12, height: 12, marginLeft: -6, marginTop: -6, background: '#fff', borderRadius: 6, boxShadow: '0 2px 4px rgba(0,0,0,0.4)', }}/> </div>
{/* Duration: fixed width */} <div style={{ fontFamily: mono, fontSize: 12, fontVariantNumeric: 'tabular-nums', width: 64, textAlign: 'left', color: 'rgba(246,244,239,0.55)', }}> {fmt(duration)} </div>
{typeof VideoEncoder !== 'undefined' && ( <IconButton title="Export video" onClick={() => window.parent.postMessage({ type: 'omelette:request-video-export' }, '*')} > <svg width="14" height="14" viewBox="0 0 14 14" fill="none"> <path d="M7 2v7m0 0L4 6m3 3l3-3M2 12h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/> </svg> </IconButton> )} </div> );}
function IconButton({ children, onClick, title }) { const [hover, setHover] = React.useState(false); return ( <button onClick={onClick} title={title} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', background: hover ? 'rgba(255,255,255,0.12)' : 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 5, color: '#f6f4ef', cursor: 'pointer', padding: 0, transition: 'background 120ms', }} > {children} </button> );}
// ── Scene-list plumbing ──────────────────────────────────────────────────// Guest-side validation of a scene list (the engine's own inputs: the// authored prop, and host-dispatched updates). Mirrors the host parser's// shape rules and constants — keep in sync with parseTimelineScenes in// apps/web/src/shared/timeline.ts (16KB raw cap, 50 entries, dur finite in// (0, 300]); returns null on any violation.function ssParse(raw) { if (typeof raw !== 'string' || !raw || raw.length > 16 * 1024) return null; var parsed; try { parsed = JSON.parse(raw); } catch (e) { return null; } if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > 50) return null; for (var i = 0; i < parsed.length; i++) { var s = parsed[i]; if (typeof s !== 'object' || s === null) return null; if (typeof s.name !== 'string' || typeof s.dur !== 'number') return null; if (!isFinite(s.dur) || s.dur <= 0 || s.dur > 300) return null; } return parsed;}
// Guest-side validation of the playback value — mirrors the host parser// (shared/timeline.ts parseTimelinePlayback): {"mode":"loop"} or// {"mode":"times","count":1..99}, strict all-or-nothing, null otherwise.// Callers treat null as the loop default.function ppParse(raw) { if (typeof raw !== 'string' || !raw || raw.length > 256) return null; var parsed; try { parsed = JSON.parse(raw); } catch (e) { return null; } if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null; var keys = Object.keys(parsed); if (parsed.mode === 'loop') return keys.length === 1 ? { mode: 'loop' } : null; if (parsed.mode === 'times') { if (keys.length !== 2) return null; var c = parsed.count; if (typeof c !== 'number' || c !== Math.floor(c) || c < 1 || c > 99) return null; return { mode: 'times', count: c }; } return null;}
// Stamps the playback attribute VERBATIM from the authored raw string (the// host's write-back anchors on that exact value) and listens for the// host's post-write update event. Same shape as SceneSync; only rendered// when the document authors a playback literal — an absent contract means// the attribute stays absent and the document plays its default.function PlaybackSync(props) { var ref = React.useRef(null); var raw = props.raw; var onUpdate = props.onUpdate; React.useEffect(function () { var el = ref.current; if (!el) return; var root = el.closest('[data-om-exportable-video-with-duration-secs]'); if (!root) return; root.setAttribute('data-om-timeline-playback', raw); var onEvent = function (e) { var next = e && e.detail; if (ppParse(next)) onUpdate(next); }; root.addEventListener('data-om-timeline-playback-update', onEvent); return function () { root.removeEventListener('data-om-timeline-playback-update', onEvent); root.removeAttribute('data-om-timeline-playback'); }; }, [raw, onUpdate]); return <div ref={ref} style={{ display: 'none' }} />;}
// Renders inside the Stage (so it can reach the exportable root via// closest()): stamps the scenes attribute VERBATIM from the current raw// string — the host's write-back anchors on that exact value — and listens// for the host's post-write update event.function SceneSync(props) { var ref = React.useRef(null); var raw = props.raw; var onUpdate = props.onUpdate; React.useEffect(function () { var el = ref.current; if (!el) return; var root = el.closest('[data-om-exportable-video-with-duration-secs]'); if (!root) return; root.setAttribute('data-om-timeline-scenes', raw); var onEvent = function (e) { var next = e && e.detail; // Ignore anything that doesn't validate — a bad update must not tear // down a working composition. if (ssParse(next)) onUpdate(next); }; root.addEventListener('data-om-timeline-scenes-update', onEvent); return function () { root.removeEventListener('data-om-timeline-scenes-update', onEvent); root.removeAttribute('data-om-timeline-scenes'); }; }, [raw, onUpdate]); return <div ref={ref} style={{ display: 'none' }} />;}
// ── Continuous composition ──────────────────────────────────────────────
var CompositionContext = React.createContext(null);function useComposition() { var ctx = React.useContext(CompositionContext); if (!ctx) throw new Error('useComposition() must be called inside <CompositionStage>'); return ctx;}
function ccDerive(scenes) { var playStart = 0; var authStart = 0; var sections = []; var table = Object.create(null); for (var i = 0; i < scenes.length; i++) { var s = scenes[i]; var nat = typeof s.nat === 'number' && isFinite(s.nat) && s.nat > 0 ? s.nat : s.dur; sections.push({ name: s.name, playStart: playStart, dur: s.dur, authStart: authStart, nat: nat }); if (!Object.prototype.hasOwnProperty.call(table, s.name)) { table[s.name] = Math.round(authStart * 1000) / 1000; } playStart += s.dur; authStart += nat; } return { sections: sections, table: table, total: Math.round(playStart * 1000) / 1000, authoredTotal: Math.round(authStart * 1000) / 1000, };}
function ccWarp(d, t) { var ss = d.sections; if (ss.length === 0) return 0; var idx = ss.length - 1; for (var i = 0; i < ss.length; i++) { if (t < ss[i].playStart + ss[i].dur) { idx = i; break; } } var s = ss[idx]; var local = Math.min(Math.max(t - s.playStart, 0), s.dur); var T = s.authStart + (s.dur > 0 ? local * (s.nat / s.dur) : 0); return Math.min(T, d.authoredTotal);}
var CC_META = Object.assign(Object.create(null), { toString: 1, toLocaleString: 1, valueOf: 1, toJSON: 1, then: 1, constructor: 1, hasOwnProperty: 1, isPrototypeOf: 1, propertyIsEnumerable: 1, default: 1,});function ccCueProxy(table, unknownRef) { if (typeof Proxy !== 'function') return table; return new Proxy(table, { get: function (target, prop) { if (typeof prop !== 'string' || prop in target) return target[prop]; if (CC_META[prop] || prop.indexOf('@@') === 0) return Object.prototype[prop]; unknownRef.current[prop] = true; return NaN; }, });}
function CcUnknownWatch(props) { var tl = useTimeline(); React.useEffect(function () { var next = Object.keys(props.unknownRef.current).sort().join(', '); if (next !== props.badge) props.setBadge(next); }, [tl.time]); return null;}
function CompositionClock(props) { var tl = useTimeline(); var d = props.derived; var T = ccWarp(d, tl.time); var value = React.useMemo(function () { return { T: T, CUES: props.cues, time: tl.time, duration: tl.duration, authoredTotal: d.authoredTotal, playing: tl.playing || tl.extPlaying === true, }; }, [T, props.cues, tl.time, tl.duration, d, tl.playing, tl.extPlaying]); return ( <CompositionContext.Provider value={value}> {props.children} </CompositionContext.Provider> );}
function Shot(props) { var c = useComposition(); var from = +props.from; var to = props.to == null ? Infinity : +props.to; var on = isFinite(from) && c.T >= from && c.T < to; return ( <div style={{ position: 'absolute', inset: 0, visibility: on ? 'visible' : 'hidden' }}> {props.children} </div> );}
var CAPTION_FADE = 0.18;function Captions(props) { var c = useComposition(); var t = c.T; var items = (props.items || []) .filter(function (it) { return it && isFinite(+it.at); }) .sort(function (a, b) { return a.at - b.at; }); var active = null; var end = Infinity; for (var i = 0; i < items.length; i++) { if (t < items[i].at) break; active = items[i]; end = typeof active.until === 'number' && isFinite(active.until) ? active.until : (i + 1 < items.length ? items[i + 1].at : Infinity); } if (!active || t >= end) return null; var o = Math.min(1, (t - active.at) / CAPTION_FADE); if (isFinite(end)) o = Math.min(o, (end - t) / CAPTION_FADE); o = Math.max(0, Math.min(1, o)); return ( <div data-om-caption style={Object.assign({ position: 'absolute', left: '8%', right: '8%', bottom: '7%', textAlign: 'center', opacity: o, pointerEvents: 'none', font: '500 30px Inter, system-ui, sans-serif', color: '#f6f4ef', textShadow: '0 1px 14px rgba(0,0,0,0.45)', }, props.style)} >{active.text}</div> );}
function CompositionStage(props) { var width = +props.width || 1280; var height = +props.height || 720; var bg = props.bg || '#0b0b0e'; var autoplay = props.autoplay == null ? true : String(props.autoplay) !== 'false'; var loop = props.loop == null ? true : String(props.loop) !== 'false'; var state = React.useState(props.scenes); var raw = state[0]; var setRaw = state[1]; var scenes = React.useMemo(function () { return ssParse(raw); }, [raw]); var pstate = React.useState(props.playback); var praw = pstate[0]; var setPraw = pstate[1]; var pb = React.useMemo(function () { return ppParse(praw); }, [praw]); var unknownRef = React.useRef({}); var badgeState = React.useState(''); var badge = badgeState[0]; var setBadge = badgeState[1]; var derived = React.useMemo(function () { unknownRef.current = {}; return scenes ? ccDerive(scenes) : null; }, [scenes]); var cues = React.useMemo(function () { return derived ? ccCueProxy(derived.table, unknownRef) : null; }, [derived]); React.useEffect(function () { var next = Object.keys(unknownRef.current).sort().join(', '); if (next !== badge) setBadge(next); }); if (!scenes) { return ( <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#0b0b0e', color: '#c96442', font: '500 16px Inter, system-ui, sans-serif', textAlign: 'center', }}> animations-v3: the scenes prop isn't a valid JSON scene list <br />(expected '[{'{'}"name":"…","dur":N{'}'}, …]') </div> ); } return ( <React.Fragment> <Stage width={width} height={height} duration={derived.total} background={bg} autoplay={autoplay} loop={loop} playback={pb}> <SceneSync raw={raw} onUpdate={setRaw} /> {typeof praw === 'string' && praw !== '' && ( <PlaybackSync raw={praw} onUpdate={setPraw} /> )} <CompositionClock derived={derived} cues={cues}> {props.children} </CompositionClock> <CcUnknownWatch unknownRef={unknownRef} badge={badge} setBadge={setBadge} /> </Stage> {badge !== '' && ( // Sibling of Stage, outside the exportable <svg>: visible in the // preview (and its screenshots), never in the exported video. <div data-om-unknown-cues style={{ position: 'absolute', left: 12, bottom: 56, zIndex: 10, padding: '6px 10px', borderRadius: 6, background: 'rgba(0,0,0,0.72)', color: '#e8906a', font: '500 12px Inter, system-ui, sans-serif', pointerEvents: 'none', }} > choreography references unknown section{badge.indexOf(',') >= 0 ? 's' : ''}: {badge} </div> )} </React.Fragment> );}
// Strokes as layers: paint multiplies, so stroke images stacked with// mix-blend-mode:multiply over the paper reproduce the flat render.
var WC_PIXEL_CAP = 11000000;
function wcLayerOpts(props) { var w = +props.width || 900, h = +props.height || 1200; var askScale = +props.scale || 1; return { width: w, height: h, scale: Math.min(askScale, Math.sqrt(WC_PIXEL_CAP / (w * h))), seed: props.seed == null ? undefined : +props.seed, quality: props.quality == null ? undefined : +props.quality };}
var wcWarned = {};function wcWarnOnce(key, message, err) { if (wcWarned[key]) return; wcWarned[key] = true; console.warn(message, err);}
function useWatercolorLayers(painting, opts) { var kit = window.WatercolorKit; if (typeof painting !== 'function' || !kit || typeof kit.layers !== 'function') return null; try { return kit.layers(painting, wcLayerOpts(opts || {})); } catch (e) { wcWarnOnce('layers:' + e, 'watercolor painting failed to build; rendering the fallback sheet', e); return null; }}
var WatercolorSheetContext = React.createContext(null);
function WatercolorSheet(props) { var L = props.layers || null; var style = Object.assign({ position: 'relative', display: 'block', width: '100%', aspectRatio: L ? L.width + ' / ' + L.height : '3 / 4', isolation: 'isolate', overflow: 'hidden', }, props.style); if (!L) { return ( <div style={Object.assign(style, { background: '#f4f1e8', color: '#8a8270', font: '12px system-ui, sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center' })}> watercolor-kit.js not loaded (or the painting failed to build) </div> ); } return ( <WatercolorSheetContext.Provider value={L}> <div style={style} data-om-watercolor-sheet> <img src={L.paper} alt={props.alt || ''} style={{ position: 'absolute', left: 0, top: 0, width: '100%', height: '100%', display: 'block' }} /> {props.children} </div> </WatercolorSheetContext.Provider> );}
function WatercolorStroke(props) { var fromSheet = React.useContext(WatercolorSheetContext); var L = props.layers || fromSheet; if (!L) return null; var i = +props.index; if (!(i >= 0) || i >= L.count) return null; var at = props.at == null ? 1 : clamp(+props.at, 0, 1); if (!(at > 0)) return null; var box, src; try { box = L.box(i); src = box ? L.src(i, at) : null; } catch (e) { wcWarnOnce('stroke:' + i + ':' + e, 'watercolor stroke ' + i + ' failed to render; skipping it', e); return null; } if (!box || !src) return null; var style = Object.assign({ position: 'absolute', display: 'block', left: box.x * 100 + '%', top: box.y * 100 + '%', width: box.w * 100 + '%', height: box.h * 100 + '%', mixBlendMode: L.kind(i) === 'reserve' ? 'normal' : 'multiply', pointerEvents: 'none', }, props.style); return <img src={src} alt="" data-om-watercolor-stroke={i} data-om-stroke-kind={L.kind(i)} style={style} />;}
// The default watercolor moment: the painting assembled from its strokes,// each appearing in painting order (a pure function of T).function WatercolorPainting(props) { var c = useComposition(); var from = +props.from || 0; var to = props.to == null ? from + 6 : +props.to; var u = clamp((c.T - from) / Math.max(to - from, 0.001), 0, 1); var eased = Easing.easeInOutQuad(u); var L = useWatercolorLayers(props.painting, props); var tick = React.useState(0)[1]; var warmed = React.useRef(null); React.useEffect(function () { if (!L || typeof L.warm !== 'function') return; var p = L.warm(); if (warmed.current === p) return; var live = true; p.then(function () { warmed.current = p; if (live) tick(function (x) { return x + 1; }); }); return function () { live = false; }; }, [L && L.paper, props.painting]); var strokes = []; if (L) { for (var i = 0; i < L.count; i++) { var sp = L.span(i); var at = clamp((eased - sp.from) / Math.max(sp.to - sp.from, 1e-6), 0, 1); if (at <= 0) break; strokes.push(<WatercolorStroke key={i} layers={L} index={i} at={at} />); } } return <WatercolorSheet layers={L} style={props.style} alt={props.alt}>{strokes}</WatercolorSheet>;}
// Paint-on watercolor reveal as a pure function of T — an <img> with a data:// URL (the exporter serializes those as-is; a live canvas would export blank).function WatercolorReveal(props) { var c = useComposition(); var from = +props.from || 0; var to = props.to == null ? from + 6 : +props.to; var u = clamp((c.T - from) / Math.max(to - from, 0.001), 0, 1); var style = Object.assign({ display: 'block', width: '100%', height: '100%', objectFit: 'contain' }, props.style); var frames = Array.isArray(props.frames) && props.frames.length ? props.frames : null; var steps = frames ? frames.length - 1 : Math.max(1, Math.round(+props.steps || 36)); var i = Math.min(steps, Math.round(Easing.easeInOutQuad(u) * steps)); var painting = typeof props.painting === 'function' ? props.painting : null; var kit = window.WatercolorKit; var w = +props.width || 900, h = +props.height || 1200; var askScale = +props.scale || Math.min(2, window.devicePixelRatio || 1); var opts = { width: w, height: h, scale: Math.min(askScale, Math.sqrt(11000000 / (w * h))), seed: props.seed == null ? undefined : +props.seed, steps: steps, type: props.format || 'image/jpeg', quality: props.quality == null ? 0.88 : +props.quality, }; var key = opts.width + 'x' + opts.height + '#' + opts.seed + '@' + opts.scale + '/' + steps + ':' + opts.type + '/' + opts.quality; var cache = React.useRef({ fn: null, key: '', frames: {}, baking: false }).current; var tick = React.useState(0)[1]; if ((cache.fn !== painting && String(cache.fn) !== String(painting)) || cache.key !== key) { cache.key = key; cache.frames = {}; cache.baking = false; } cache.fn = painting; React.useEffect(function () { if (frames || cache.baking || !painting || !kit || typeof kit.bake !== 'function') return; cache.baking = true; var target = cache.frames; try { kit.bake(painting, opts, function (n, _t, url) { target[n] = url; }).then(function (all) { if (cache.frames !== target) return; for (var n = 0; n < all.length; n++) target[n] = all[n]; tick(function (x) { return x + 1; }); }).catch(function () { /* failed bake: the guarded lazy path below still renders */ }); } catch (e) { /* oversized painting: the guarded lazy path below still renders */ } }); if (frames) return <img src={frames[i]} alt={props.alt || ''} style={style} />; if (!kit || !painting) { return ( <div style={Object.assign({ width: '100%', height: '100%', background: '#f4f1e8', color: '#8a8270', font: '12px system-ui, sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center' }, props.style)}> watercolor-kit.js not loaded (or no painting function) </div> ); } if (!cache.frames[i]) { try { cache.frames[i] = kit.frame(painting, Object.assign({}, opts, { at: i / steps })); } catch (e) { return ( <div style={Object.assign({ width: '100%', height: '100%', background: '#f4f1e8', color: '#8a8270', font: '12px system-ui, sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center' }, props.style)}> painting too large to render ({String(e && e.message).slice(0, 80)}) </div> ); } } return <img src={cache.frames[i]} alt={props.alt || ''} style={style} />;}
Object.assign(window, { Easing, interpolate, animate, clamp, TimelineContext, useTime, useTimeline, Stage, PlaybackBar, CompositionStage, useComposition, Shot, Captions, WatercolorReveal, WatercolorPainting, WatercolorSheet, WatercolorStroke, useWatercolorLayers,});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314/* Kugguk Labs — README motion piece. Rendered from authored time T only. */const { useComposition, animate, interpolate, Easing, clamp, Shot, useTweaks, TweaksPanel, TweakSection, TweakToggle, TweakColor, TweakRadio } = window;
const MONO = "'JetBrains Mono', ui-monospace, monospace";const DISP = "'Space Grotesk', system-ui, sans-serif";
const MOTION = { enter: (T, start, dur = 0.7, dy = 26) => { const p = animate({ from: 0, to: 1, start, end: start + dur, ease: Easing.easeOutCubic })(T); return { opacity: p, transform: `translateY(${(1 - p) * dy}px)` }; }, draw: (T, start, end) => animate({ from: 0, to: 1, start, end, ease: Easing.easeInOutCubic })(T), pop: (T, start) => { const p = animate({ from: 0, to: 1, start, end: start + 0.5, ease: Easing.easeOutBack })(T); return { opacity: clamp(p * 1.8, 0, 1), transform: `scale(${0.9 + 0.1 * p})` }; }};
const lerp = (T, a, b, from, to, ease) => animate({ from, to, start: a, end: b, ease: ease || Easing.easeInOutCubic })(T);const win = (T, a, b, fi = 0.6, fo = 0.5) => clamp(MOTION.draw(T, a, a + fi) * (1 - MOTION.draw(T, b - fo, b)), 0, 1);
const tc = (t) => { const s = Math.max(0, t); const m = Math.floor(s / 60); const r = s - m * 60; return `T+${String(m).padStart(2, '0')}:${r.toFixed(1).padStart(4, '0')}`;};
const DOMAINS = [ ['01', 'synthetic language'], ['02', 'adversarial validation'], ['03', 'forward-only inference'], ['04', 'verifiable state transitions'], ['05', 'private communication']];
const TRACE = ['stable inputs', 'visible transformations', 'explicit limitations', 'artifacts that others can inspect or reproduce'];
function KuggukPiece(props) { const { T, CUES, authoredTotal } = useComposition(); const C = { bg: '#0A0B0B', ink: '#F3F1EB', mute: '#83857E', amber: props.accent || '#E9A23B', line: '#232624' }; const showGrid = props.grid !== false;
/* ---------- camera ---------- */ const panX = lerp(T, CUES.Domains + 1.1, CUES.Domains + 5.6, 0, -1180, Easing.easeInOutQuad) + lerp(T, CUES.Trace - 0.9, CUES.Trace + 0.15, 0, 1180); const zoom = lerp(T, 0, CUES.Thesis, 1.06, 1.0) * lerp(T, CUES.Body, CUES.Body + 6, 1.0, 1.04) * lerp(T, CUES.Close, authoredTotal, 1.0, 1.05); const camY = lerp(T, CUES.Trace - 0.4, CUES.Trace + 0.8, 0, 0);
/* ---------- persistent logotype ---------- */ const lp = lerp(T, CUES.Thesis - 0.5, CUES.Thesis + 0.8, 0, 1); const logoReveal = MOTION.draw(T, 0.5, 2.1); const closePulse = 1 + 0.02 * Math.sin(Math.max(0, T - CUES.Close) * 2.2);
/* ---------- text reveals ---------- */ const bodyLines = [ 'We build experimental interfaces that expose how ideas', 'are transformed, challenged, transmitted and preserved', 'by machines.' ]; const closeWords = [ { w: 'Ideas', hot: false }, { w: 'enter', hot: false }, { w: 'then', hot: false }, { w: 'transformations', hot: true }, { w: 'can', hot: false }, { w: 'make', hot: false }, { w: 'a', hot: false }, { w: 'brand.', hot: true } ];
const scanY = ((T * 0.34) % 1) * 1080; const tick = Math.floor(T * 6);
return ( <div style={{ position: 'absolute', inset: 0, background: C.bg, overflow: 'hidden', color: C.ink }}> {/* grid + scan */} {showGrid && ( <div style={{ position: 'absolute', inset: -200, opacity: 0.55, backgroundImage: `linear-gradient(to right, ${C.line} 1px, transparent 1px), linear-gradient(to bottom, ${C.line} 1px, transparent 1px)`, backgroundSize: '80px 80px', transform: `translateY(${lerp(T, 0, authoredTotal, 0, -40, Easing.linear)}px)` }} /> )} <div style={{ position: 'absolute', left: 0, right: 0, top: scanY, height: 240, background: `linear-gradient(to bottom, transparent, ${C.amber}0F, transparent)`, pointerEvents: 'none' }} />
{/* stage */} <div style={{ position: 'absolute', inset: 0, transform: `scale(${zoom}) translate(${panX}px, ${camY}px)`, transformOrigin: '50% 50%' }}>
{/* THESIS */} <div style={{ position: 'absolute', left: 120, top: 470, width: 1680, font: `500 132px/1.02 ${DISP}`, letterSpacing: '-0.03em', textWrap: 'balance', opacity: win(T, CUES.Thesis + 0.35, CUES.Body + 0.6, 0.8, 0.7), transform: `translateY(${lerp(T, CUES.Thesis + 0.35, CUES.Thesis + 1.6, 34, 0)}px)` }}> Bring AI <span style={{ color: C.amber }}> out-of-its-box.</span> <div style={{ height: 2, marginTop: 40, background: C.amber, width: `${MOTION.draw(T, CUES.Thesis + 1.1, CUES.Thesis + 2.6) * 100}%` }} /> </div>
{/* BODY */} <div style={{ position: 'absolute', left: 120, top: 372, width: 1720, opacity: win(T, CUES.Body - 0.2, CUES.Domains + 0.6, 0.7, 0.7) }}> <div style={{ font: `500 13px ${MONO}`, letterSpacing: '0.28em', color: C.mute, marginBottom: 44 }}>01 — PREMISE</div> {bodyLines.map((l, i) => ( <div key={i} style={{ font: `400 56px/1.32 ${DISP}`, letterSpacing: '-0.02em', ...MOTION.enter(T, CUES.Body + 0.15 + i * 0.55, 0.9, 18) }}>{l}</div> ))} </div>
{/* DOMAINS */} <div style={{ position: 'absolute', inset: 0, opacity: win(T, CUES.Domains - 0.2, CUES.Trace + 0.6, 0.7, 0.7) }}> <div style={{ position: 'absolute', left: 120, top: 300, width: 1500, font: `400 34px/1.5 ${DISP}`, color: C.mute, letterSpacing: '-0.01em', ...MOTION.enter(T, CUES.Domains + 0.05, 0.8, 14) }}> Our work moves between </div> <div style={{ position: 'absolute', left: 120, top: 470, height: 2, width: 3060, background: C.line }} /> <div style={{ position: 'absolute', left: 120, top: 470, height: 2, background: C.amber, width: `${MOTION.draw(T, CUES.Domains + 0.8, CUES.Domains + 5.9) * 3060}px` }} /> <div style={{ position: 'absolute', top: 462, left: 120 + MOTION.draw(T, CUES.Domains + 0.8, CUES.Domains + 5.9) * 3060, width: 18, height: 18, marginLeft: -9, borderRadius: 9, background: C.amber, boxShadow: `0 0 34px ${C.amber}`, opacity: win(T, CUES.Domains + 0.7, CUES.Domains + 6.3, 0.3, 0.4) }} /> {DOMAINS.map(([n, label], i) => { const at = CUES.Domains + 1.0 + i * 1.0; const lit = MOTION.draw(T, at, at + 0.45); return ( <div key={n} style={{ position: 'absolute', left: 120 + i * 610, top: 530, width: 520, ...MOTION.pop(T, at) }}> <div style={{ width: 2, height: 46, background: lit > 0.5 ? C.amber : C.line }} /> <div style={{ font: `500 13px ${MONO}`, letterSpacing: '0.28em', color: C.amber, margin: '26px 0 14px' }}>{n}</div> <div style={{ font: `400 46px/1.16 ${DISP}`, letterSpacing: '-0.02em', color: interpolate(lit, [0, 1], [0, 1]) > 0.5 ? C.ink : C.mute }}>{label}</div> </div> ); })} </div>
{/* TRACE */} <div style={{ position: 'absolute', inset: 0, opacity: win(T, CUES.Trace - 0.1, CUES.Local + 0.5, 0.7, 0.6) }}> <div style={{ position: 'absolute', left: 120, top: 268, width: 1600, font: `500 74px/1.16 ${DISP}`, letterSpacing: '-0.025em', ...MOTION.enter(T, CUES.Trace + 0.2, 0.9, 22) }}> Every public experiment is designed to <span style={{ color: C.amber }}>leave a trace</span>. </div> <div style={{ position: 'absolute', left: 120, top: 520, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '28px 40px', width: 1680 }}> {TRACE.map((t, i) => ( <div key={t} style={{ border: `1px solid ${C.line}`, padding: '34px 36px', display: 'flex', gap: 24, alignItems: 'baseline', background: '#0E100F', ...MOTION.pop(T, CUES.Trace + 1.2 + i * 0.5) }}> <span style={{ font: `500 13px ${MONO}`, letterSpacing: '0.24em', color: C.amber }}>{String(i + 1).padStart(2, '0')}</span> <span style={{ font: `400 38px/1.25 ${DISP}`, letterSpacing: '-0.015em' }}>{t}</span> </div> ))} </div> </div>
{/* LOCAL — RCV fallback chain */} <div style={{ position: 'absolute', inset: 0, opacity: win(T, CUES.Local - 0.1, CUES.Close + 0.5, 0.7, 0.6) }}> <div style={{ font: `500 13px ${MONO}`, letterSpacing: '0.28em', color: C.mute, position: 'absolute', left: 120, top: 250, ...MOTION.enter(T, CUES.Local + 0.1, 0.7, 12) }}>05 — RCV</div> <div style={{ position: 'absolute', left: 120, top: 300, width: 1000, font: `500 82px/1.08 ${DISP}`, letterSpacing: '-0.03em', ...MOTION.enter(T, CUES.Local + 0.25, 0.9, 24) }}> Three seconds,<br /><span style={{ color: C.amber }}>stored offline.</span> </div> {[['WEBGPU', 'compute shader over the sample buffer'], ['WASM', 'SIMD kernel, worker threads if available'], ['CPU', 'plain JS over Float32Array — the floor']].map(([n, d], i) => { const at = CUES.Local + 1.4 + i * 0.85; const lit = MOTION.draw(T, at + 0.15, at + 0.5); return ( <div key={n} style={{ position: 'absolute', left: 1180, top: 300 + i * 150, width: 620, borderLeft: `2px solid ${lit > 0.5 ? C.amber : C.line}`, paddingLeft: 28, ...MOTION.enter(T, at, 0.7, 16) }}> <div style={{ font: `500 30px ${MONO}`, letterSpacing: '0.08em', color: lit > 0.5 ? C.ink : C.mute }}>{n}</div> <div style={{ marginTop: 10, font: `400 21px/1.4 ${DISP}`, color: C.mute }}>{d}</div> </div> ); })} <div style={{ position: 'absolute', left: 1140, top: 318, width: 14, height: 14, borderRadius: 7, background: C.amber, boxShadow: `0 0 30px ${C.amber}`, transform: `translateY(${lerp(T, CUES.Local + 1.6, CUES.Local + 3.4, 0, 300)}px)`, opacity: win(T, CUES.Local + 1.5, CUES.Local + 4.4, 0.3, 0.5) }} /> <div style={{ position: 'absolute', left: 120, top: 700, width: 1680, font: `400 46px/1.35 ${DISP}`, letterSpacing: '-0.02em', color: C.ink, ...MOTION.enter(T, CUES.Local + 4.5, 0.9, 20) }}> No upload. <span style={{ color: C.mute }}>No trace.</span> <span style={{ color: C.amber }}>No proof of work.</span> </div> </div>
{/* SPECIMEN PLATE — framed field unit, revealed under the closing line */} <div style={{ position: 'absolute', right: 120, top: 300, width: 760, opacity: win(T, CUES.Close + 1.4, authoredTotal - 0.05, 0.9, 0.9) }}> <div style={{ display: 'flex', justifyContent: 'space-between', font: `500 12px ${MONO}`, letterSpacing: '0.26em', color: C.mute, marginBottom: 14 }}> <span>SPECIMEN 001 · FIELD UNIT</span> <span style={{ color: C.amber }}>K2 · 8,611M</span> </div> <div style={{ border: `1px solid ${C.line}`, padding: 10, background: '#0E100F', overflow: 'hidden' }}> <div style={{ overflow: 'hidden', height: 400 }}> <img src="./assets/zebra-k2.png" alt="Field unit on K2" style={{ width: '100%', display: 'block', filter: 'saturate(0.5) contrast(1.06) brightness(0.86) sepia(0.12)', transform: `scale(${lerp(T, CUES.Close + 1.2, authoredTotal, 1.14, 1.02)}) translateY(-6%)`, transformOrigin: '50% 42%' }} /> </div> </div> <div style={{ marginTop: 14, font: `400 15px ${MONO}`, letterSpacing: '0.06em', color: C.mute }}> observed, unbothered · no upload </div> </div>
{/* CLOSE */} <div style={{ position: 'absolute', left: 120, top: 420, width: 900, opacity: win(T, CUES.Close - 0.2, authoredTotal - 0.05, 0.5, 0.9) }}> <div style={{ font: `600 96px/1.08 ${DISP}`, letterSpacing: '-0.035em', display: 'flex', flexWrap: 'wrap', gap: '0 26px' }}> {closeWords.map((c, i) => ( <span key={i} style={{ color: c.hot ? C.amber : C.ink, ...MOTION.enter(T, CUES.Close + 0.3 + i * 0.14, 0.6, 26) }}>{c.w}</span> ))} </div> </div> </div>
{/* persistent logotype: hero -> chrome slot */} <div style={{ position: 'absolute', left: 0, right: 0, top: lerp(T, CUES.Thesis - 0.5, CUES.Thesis + 0.8, 438, 54), display: 'flex', justifyContent: 'center' }}> <div style={{ font: `500 ${lerp(T, CUES.Thesis - 0.5, CUES.Thesis + 0.8, 96, 15)}px ${MONO}`, letterSpacing: `${lerp(T, CUES.Thesis - 0.5, CUES.Thesis + 0.8, 0.34, 0.3)}em`, transform: `translateX(${lerp(T, CUES.Thesis - 0.5, CUES.Thesis + 0.8, 0, -820)}px) scale(${lp > 0.99 ? closePulse : 1})`, clipPath: `inset(0 ${(1 - logoReveal) * 100}% 0 0)`, whiteSpace: 'nowrap' }}>KUGGUK LABS</div> </div>
{/* chrome */} <div style={{ position: 'absolute', left: 120, top: 100, font: `400 13px ${MONO}`, letterSpacing: '0.24em', color: C.mute, opacity: interpolate(lp, [0, 1], [0, 1]) }}> OBSERVATION LOG · REV 01 </div> <div style={{ position: 'absolute', right: 120, top: 54, font: `400 15px ${MONO}`, letterSpacing: '0.16em', color: C.amber, opacity: 0.9 }}> {tc(T)} </div> <div style={{ position: 'absolute', right: 120, top: 100, font: `400 13px ${MONO}`, letterSpacing: '0.24em', color: C.mute }}> {`SIG ${String(tick % 997).padStart(3, '0')}`} </div> <div style={{ position: 'absolute', left: 120, right: 120, bottom: 76, height: 1, background: C.line }}> <div style={{ height: 1, background: C.amber, width: `${clamp(T / authoredTotal, 0, 1) * 100}%` }} /> </div> {[[120, 54], [120, 1026], [1800, 54], [1800, 1026]].map(([x, y], i) => ( <div key={i} style={{ position: 'absolute', left: x - 6, top: y - 6, width: 12, height: 12, borderLeft: `1px solid ${C.mute}`, borderTop: `1px solid ${C.mute}`, opacity: 0.5, transform: `rotate(${i * 90}deg)` }} /> ))} </div> );}
function KuggukStage(props) { const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS || {}); return ( <> <KuggukPiece accent={t.accent} grid={t.grid} /> {ReactDOM.createPortal( <TweaksPanel> <TweakSection label="Look" /> <TweakColor label="Accent" value={t.accent} options={['#E9A23B', '#D97757', '#7FD4C1', '#F3F1EB']} onChange={(v) => setTweak('accent', v)} /> <TweakToggle label="Measurement grid" value={t.grid} onChange={(v) => setTweak('grid', v)} /> <TweakSection label="Editing" /> <TweakToggle label="Motion editor" value={t.motionEditor} onChange={(v) => setTweak('motionEditor', v)} /> </TweaksPanel>, document.body)} </> );}
window.KuggukStage = KuggukStage;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911// GENERATED from dc-runtime/src/*.ts — do not edit. Rebuild with `cd dc-runtime && bun run build`."use strict";(() => { var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/react.ts function getReact() { const R = window.React; if (!R) throw new Error("dc-runtime: window.React is not available yet"); return R; } function getReactDOM() { const RD = window.ReactDOM; if (!RD) throw new Error("dc-runtime: window.ReactDOM is not available yet"); return RD; } var h = ((...args) => getReact().createElement( ...args ));
// src/parse.ts function parseDcDocument(doc) { const dc = doc.querySelector("x-dc"); if (!dc) return null; const scriptEl = doc.querySelector("script[data-dc-script]"); const { props, preview } = parseDataProps( scriptEl?.getAttribute("data-props") ?? null ); return { template: dc.innerHTML, js: scriptEl ? scriptEl.textContent || "" : "", props, preview }; } function parseDcText(src) { const openMatch = /<x-dc(?:\s[^>]*)?>/.exec(src); if (!openMatch) return null; const close = src.lastIndexOf("</x-dc>"); if (close === -1 || close < openMatch.index) return null; const template = src.slice(openMatch.index + openMatch[0].length, close); const doc = new DOMParser().parseFromString(src, "text/html"); const scriptEl = doc.querySelector("script[data-dc-script]"); const { props, preview } = parseDataProps( scriptEl?.getAttribute("data-props") ?? null ); return { template, js: scriptEl ? scriptEl.textContent || "" : "", props, preview }; } function parseDataProps(raw) { if (!raw) return { props: null, preview: null }; let parsed; try { parsed = JSON.parse(raw); } catch { return { props: null, preview: null }; } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { return { props: null, preview: null }; } const obj = parsed; const preview = obj.$preview && typeof obj.$preview === "object" ? obj.$preview : null; const rest = {}; for (const k of Object.keys(obj)) { if (k[0] !== "$") rest[k] = obj[k]; } return { props: Object.keys(rest).length ? rest : null, preview }; } function dcNameFromPath(pathname) { let p = pathname || ""; try { p = decodeURIComponent(p); } catch { } const base = p.split("/").pop() || "Root"; return base.replace(/\.dc\.html$/, "").replace(/\.html?$/, "") || "Root"; }
// src/boot.ts var BASE_CSS = ` .sc-placeholder{background:color-mix(in srgb,currentColor 8%,transparent); border:1px solid color-mix(in srgb,currentColor 50%,transparent); border-radius:2px;box-sizing:border-box;overflow:hidden} @keyframes sc-shine{0%{background-position:100% 50%}100%{background-position:0% 50%}} html.sc-dc-streaming .sc-placeholder, html.sc-dc-streaming .sc-interp.sc-missing{position:relative; background:color-mix(in srgb,currentColor 5%,transparent); border-color:transparent} html.sc-dc-streaming .sc-placeholder::before, html.sc-dc-streaming .sc-interp.sc-missing::before{content:''; position:absolute;inset:0;pointer-events:none; background:linear-gradient(90deg,rgba(217,119,87,0) 25%,rgba(247,225,211,.95) 37%,rgba(217,119,87,0) 63%); background-size:400% 100%;animation:sc-shine 1.4s ease infinite} html.sc-dc-streaming .sc-placeholder:nth-child(n+9 of .sc-placeholder)::before, html.sc-dc-streaming .sc-interp.sc-missing:nth-child(n+9 of .sc-interp.sc-missing)::before{animation:none; background:color-mix(in srgb,currentColor 8%,transparent)} .sc-placeholder-error{padding:4px 8px;font:11px/1.4 ui-monospace,monospace; color:color-mix(in srgb,currentColor 70%,transparent);word-break:break-word} .sc-interp.sc-missing{display:inline-block;width:2em;height:1em;overflow:hidden; vertical-align:text-bottom;background:rgba(255,255,255,.3);border:1px solid rgba(0,0,0,.5); border-radius:2px;box-sizing:border-box;color:transparent; user-select:none} .sc-interp.sc-unresolved{font-family:ui-monospace,monospace;font-size:.85em; color:color-mix(in srgb,currentColor 50%,transparent); background:color-mix(in srgb,currentColor 10%,transparent);border-radius:3px; padding:0 3px} .sc-host.sc-has-error{position:relative} .sc-logic-error{position:absolute;top:8px;left:8px;z-index:2147483647;max-width:60ch; padding:6px 10px;background:#b00020;color:#fff;font:12px/1.4 ui-monospace,monospace; border-radius:4px;white-space:pre-wrap;pointer-events:none} /* Mirrors PRINT_BASELINE_CSS in apps/web deck-stage-export.ts \u2014 keep both in sync until dc-runtime regains a build step. */ @media print { @page { margin: 0.5cm; } figure, table { break-inside: avoid; } #dc-root, #dc-root > .sc-host { height: auto; } *, *::before, *::after { print-color-adjust: exact; -webkit-print-color-adjust: exact; backdrop-filter: none !important; -webkit-backdrop-filter: none !important; animation-delay: -99s !important; animation-duration: .001s !important; animation-iteration-count: 1 !important; animation-fill-mode: both !important; animation-play-state: running !important; transition-duration: 0s !important; } } `; var FULL_PAGE_CSS = "html,body{height:100%;margin:0}#dc-root,#dc-root>.sc-host{height:100%}"; function rootNameForDocument(doc, loc) { let bootPath = loc.pathname || ""; if (!/\.dc\.html?$/i.test(safeDecode(bootPath))) { try { bootPath = new URL(doc.baseURI || "/").pathname; } catch { } } return dcNameFromPath(bootPath); } function safeDecode(s) { try { return decodeURIComponent(s); } catch { return s; } } function boot(runtime, doc = document) { const parsed = parseDcDocument(doc); if (!parsed) return null; const React = getReact(); const rootName = rootNameForDocument(doc, location); runtime.markFetched(rootName); runtime.setRootName(rootName); runtime.adoptParsed(rootName, parsed); if (!window.__resources) { fetch(location.href).then((res) => res.ok ? res.text() : "").then((t) => { const raw = t ? parseDcText(t) : null; if (raw?.template) runtime.updateHtml(rootName, raw.template); }).catch(() => { }); } const dc = doc.querySelector("x-dc"); const hostEl = doc.createElement("div"); hostEl.id = "dc-root"; dc.replaceWith(hostEl); if (!parsed.preview) { const s = doc.createElement("style"); s.textContent = FULL_PAGE_CSS; doc.head.appendChild(s); } const Root = runtime.getDC(rootName); const entry = runtime.registry.get(rootName); function StandaloneRoot() { const [, setTick] = React.useState(0); React.useEffect(() => { const sub = () => setTick((n) => n + 1); entry.subs.add(sub); return () => { entry.subs.delete(sub); }; }, []); const defaults = React.useMemo(() => { const d = {}; for (const k in entry.propsMeta || {}) { const v = entry.propsMeta?.[k]?.default; if (v !== void 0) d[k] = v; } return d; }, [entry.propsMeta]); return h(Root, { ...defaults, ...entry.propOverrides || {} }); } const ReactDOM = getReactDOM(); if (ReactDOM.createRoot) ReactDOM.createRoot(hostEl).render(h(StandaloneRoot)); else ReactDOM.render(h(StandaloneRoot), hostEl); return rootName; }
// src/expr.ts var IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*/; var NUMBER_RE = /^-?\d+(\.\d+)?$/; function resolve(vals, src) { const expr = String(src).trim(); if (!expr) return void 0; if (expr[0] === "(" && expr[expr.length - 1] === ")" && parensWrapWhole(expr)) { return resolve(vals, expr.slice(1, -1)); } const eq = findTopLevelEquality(expr); if (eq) { const lv = resolve(vals, expr.slice(0, eq.index)); const rv = resolve(vals, expr.slice(eq.index + eq.op.length)); switch (eq.op) { case "===": return lv === rv; case "!==": return lv !== rv; case "==": return lv == rv; default: return lv != rv; } } if (expr[0] === "!") return !resolve(vals, expr.slice(1)); if (expr === "true") return true; if (expr === "false") return false; if (expr === "null") return null; if (expr === "undefined") return void 0; if (NUMBER_RE.test(expr)) return Number(expr); if (expr.length >= 2 && (expr[0] === '"' || expr[0] === "'") && expr[expr.length - 1] === expr[0]) { return expr.slice(1, -1); } return resolvePath(vals, expr); } function parensWrapWhole(expr) { let depth = 0; for (let i = 0; i < expr.length - 1; i++) { if (expr[i] === "(") depth++; else if (expr[i] === ")") { depth--; if (depth === 0) return false; } } return true; } function findTopLevelEquality(expr) { let depth = 0; for (let i = 0; i < expr.length; i++) { const c = expr[i]; if (c === "[" || c === "(") depth++; else if (c === "]" || c === ")") depth--; else if (depth === 0 && (c === "=" || c === "!") && expr[i + 1] === "=") { if (i > 0 && (expr[i - 1] === "=" || expr[i - 1] === "!")) continue; if (!expr.slice(0, i).trim()) continue; const op = expr[i + 2] === "=" ? c + "==" : c + "="; return { index: i, op }; } } return null; } function resolvePath(vals, expr) { const head = expr.match(IDENT_RE); if (!head) return void 0; let cur = vals == null ? void 0 : vals[head[0]]; let i = head[0].length; while (i < expr.length) { if (expr[i] === ".") { const m = expr.slice(i + 1).match(IDENT_RE) || expr.slice(i + 1).match(/^\d+/); if (!m) return void 0; cur = cur == null ? void 0 : cur[m[0]]; i += 1 + m[0].length; } else if (expr[i] === "[") { let depth = 1; let j = i + 1; while (j < expr.length && depth > 0) { if (expr[j] === "[") depth++; else if (expr[j] === "]") { depth--; if (depth === 0) break; } j++; } if (depth !== 0) return void 0; const key = resolve(vals, expr.slice(i + 1, j)); cur = cur == null ? void 0 : cur[key]; i = j + 1; } else { return void 0; } } return cur; }
// src/encode.ts var CAMEL_ATTR = "sc-camel-"; var INLINE_TEXT_TAGS = new Set( "a abbr b bdi bdo br cite code del dfn em i ins kbd mark q s samp small span strike strong sub sup u var wbr".split( " " ) ); var RAW_WRAP = { select: "sc-raw-select", table: "sc-raw-table", tbody: "sc-raw-tbody", thead: "sc-raw-thead", tfoot: "sc-raw-tfoot", tr: "sc-raw-tr", td: "sc-raw-td", th: "sc-raw-th", caption: "sc-raw-caption" }; var RAW_UNWRAP = Object.fromEntries( Object.entries(RAW_WRAP).map(([k, v]) => [v, k]) ); var EVENT_MAP = { onclick: "onClick", onchange: "onChange", oninput: "onInput", onsubmit: "onSubmit", onkeydown: "onKeyDown", onkeyup: "onKeyUp", onkeypress: "onKeyPress", onmousedown: "onMouseDown", onmouseup: "onMouseUp", onmouseenter: "onMouseEnter", onmouseleave: "onMouseLeave", onfocus: "onFocus", onblur: "onBlur", ondoubleclick: "onDoubleClick", oncontextmenu: "onContextMenu", onmousemove: "onMouseMove", onmouseover: "onMouseOver", onmouseout: "onMouseOut", onpointerdown: "onPointerDown", onpointerup: "onPointerUp", onpointermove: "onPointerMove", onpointerenter: "onPointerEnter", onpointerleave: "onPointerLeave", onpointercancel: "onPointerCancel", onpointerover: "onPointerOver", onpointerout: "onPointerOut", ongotpointercapture: "onGotPointerCapture", onlostpointercapture: "onLostPointerCapture", ontouchstart: "onTouchStart", ontouchend: "onTouchEnd", ontouchmove: "onTouchMove", ontouchcancel: "onTouchCancel", ondragstart: "onDragStart", ondragend: "onDragEnd", ondragenter: "onDragEnter", ondragleave: "onDragLeave", ondragover: "onDragOver", onanimationstart: "onAnimationStart", onanimationend: "onAnimationEnd", onanimationiteration: "onAnimationIteration", ontransitionend: "onTransitionEnd" }; var ATTRS = `(?:[^>"']|"[^"]*"|'[^']*')*`; var IMPORT_SELF_CLOSE_RE = new RegExp( "<(x-import|dc-import)(" + ATTRS + ")/>", "gi" ); var CAMEL_ATTR_RE = /(\s)([a-z]+[A-Z][A-Za-z0-9]*)(\s*=)/g; function encodeCamelAttrs(html) { return html.replace( CAMEL_ATTR_RE, (_, sp, name, eq) => sp + CAMEL_ATTR + name.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()) + eq ); } function encodeCase(html) { html = html.replace( IMPORT_SELF_CLOSE_RE, (_, t, a) => "<" + t + a + "></" + t + ">" ); html = html.replace(/<helmet(\s|>)/gi, "<sc-helmet$1"); html = html.replace(/<\/helmet\s*>/gi, "</sc-helmet>"); html = encodeCamelAttrs(html); for (const [real, alias] of Object.entries(RAW_WRAP)) { html = html.replace( new RegExp("(</?)" + real + "(?=[\\s>])", "gi"), "$1" + alias ); } return html; } function kebabToCamel(s) { return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); } function cssToObj(css) { const o = {}; for (const decl of css.split(";")) { const i = decl.indexOf(":"); if (i < 0) continue; const prop = decl.slice(0, i).trim(); o[prop.startsWith("--") ? prop : kebabToCamel(prop)] = decl.slice(i + 1).trim(); } return o; } function compileAttr(raw) { const whole = raw.match(/^\s*\{\{([\s\S]+?)\}\}\s*$/); if (whole) { const path = whole[1]; return (vals) => resolve(vals, path); } if (raw.includes("{{")) { const parts = raw.split(/\{\{([\s\S]+?)\}\}/g); return (vals) => parts.map((s, i) => i & 1 ? resolve(vals, s) ?? "" : s).join(""); } return () => raw; }
// src/compile.ts function collectProps(node, kind, host) { const propGetters = []; const pseudoClasses = []; let hintSize = null; for (const { name, value } of [...node.attributes]) { if (name === "sc-name" || name === "data-dc-tpl") continue; let key = name; if (key.startsWith(CAMEL_ATTR)) key = kebabToCamel(key.slice(CAMEL_ATTR.length)); if (key === "hint-size") { hintSize = value; continue; } if (key.startsWith("style-")) { pseudoClasses.push(host.pseudoClass(key.slice(6), value)); continue; } if (kind !== "dom") { if (key.includes("-") && !(kind === "x-import" && (key.startsWith("aria-") || key.startsWith("data-")))) key = kebabToCamel(key); } else { if (key === "class") key = "className"; else if (key === "for") key = "htmlFor"; else if (key.startsWith("on")) key = EVENT_MAP[key] || "on" + key[2].toUpperCase() + key.slice(3); } propGetters.push([key, compileAttr(value)]); } return { propGetters, pseudoClasses, hintSize }; } var HOST_STYLE_PROPS = /* @__PURE__ */ new Set([ "position", "left", "right", "top", "bottom", "inset", "width", "height", "z-index", "transform" ]); function hostPositionStyle(style) { const all = typeof style === "string" ? cssToObj(style) : style != null && typeof style === "object" ? style : null; if (!all) return void 0; const out = {}; for (const [k, v] of Object.entries(all)) { const kebab = k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()); if (HOST_STYLE_PROPS.has(kebab)) out[k] = v; } return Object.keys(out).length ? out : void 0; } function compileTemplate(html, host) { const tpl = document.createElement("template"); //! nosemgrep: direct-inner-html-assignment tpl.innerHTML = encodeCase(html); let tplN = 0; (function stamp(node) { if (node.nodeType === Node.ELEMENT_NODE) { node.setAttribute("data-dc-tpl", String(tplN++)); } for (const c of node.childNodes) stamp(c); })(tpl.content); const builders = walkChildren(tpl.content, host); const render = ((vals, ctx) => builders.map((b, i) => b(vals || {}, ctx, i))); render.__annotated = tpl.innerHTML; return render; } function walkChildren(node, host) { return [...node.childNodes].map((c) => walk(c, host)).filter((b) => b != null); } var SLIDE_ID_VALUE_RE = /^[0-9a-f]{8}$/; var DECK_CONTROL_FLOW_RE = /^(sc-if|sc-for|sc-else|dc-import|x-import)$/; var DECK_AUX_RE = /^(template|script|style|sc-helmet|helmet)$/; function isDeckMountTag(el) { if (el.localName === "deck-stage") return true; return el.localName === "x-import" && (el.getAttribute("component-from-global-scope") || "") === "deck-stage"; } function walkDeckChildren(el, host) { const pairs = [...el.childNodes].map((c) => ({ c, b: walk(c, host) })).filter((p) => p.b !== null); const kids = pairs.map((p) => p.b); const seen = /* @__PURE__ */ new Set(); const wsSeen = /* @__PURE__ */ new Map(); const keys = []; const nextSlideId = new Array(pairs.length); { let upcoming = null; for (let j = pairs.length - 1; j >= 0; j--) { const n = pairs[j].c; if (n.nodeType === Node.ELEMENT_NODE) { const t = n.localName; upcoming = !DECK_AUX_RE.test(t) && !DECK_CONTROL_FLOW_RE.test(t) ? n.getAttribute("data-om-slide-id") : null; } nextSlideId[j] = upcoming; } } for (let j = 0; j < pairs.length; j++) { const { c } = pairs[j]; if (c.nodeType === Node.TEXT_NODE) { if ((c.nodeValue ?? "").trim() === "") { const base = nextSlideId[j] ? "omid-ws:" + nextSlideId[j] : "omid-ws:aux"; const n = wsSeen.get(base) ?? 0; wsSeen.set(base, n + 1); keys.push(n === 0 ? base : base + ":" + n); continue; } return { kids, keys: null }; } if (c.nodeType !== Node.ELEMENT_NODE) { keys.push(j); continue; } const child = c; const tag = child.localName; if (DECK_AUX_RE.test(tag)) { keys.push(j); continue; } if (DECK_CONTROL_FLOW_RE.test(tag)) return { kids, keys: null }; const v = child.getAttribute("data-om-slide-id"); if (!v || !SLIDE_ID_VALUE_RE.test(v) || seen.has(v)) { return { kids, keys: null }; } seen.add(v); keys.push("omid:" + v); } return { kids, keys }; } function renderDeckKids(kids, kidKeys, vals, ctx) { return kids.map((b, j) => { const k = kidKeys ? kidKeys[j] : j; const out = b(vals, ctx, k); return kidKeys != null && typeof out === "string" ? h(getReact().Fragment, { key: k }, out) : out; }); } function walk(node, host) { if (node.nodeType === Node.TEXT_NODE) return walkText(node); if (node.nodeType !== Node.ELEMENT_NODE) return null; const el = node; const tag = el.tagName.toLowerCase(); if (tag === "sc-for") return walkFor(el, host); if (tag === "sc-if") return walkIf(el, host); if (tag === "x-import") return walkXImport(el, host); if (tag === "sc-helmet") return host.helmet(el); if (tag === "dc-import") return walkComponent(el, host); return walkElement(el, host); } var warnedHoles = /* @__PURE__ */ new Set(); function warnUnresolved(ctx, what) { const key = (ctx?.__name || "?") + "\0" + what; if (warnedHoles.has(key)) return; warnedHoles.add(key); console.warn("[dc-runtime] " + (ctx?.__name || "template") + ": " + what); } function walkText(node) { const txt = node.nodeValue ?? ""; if (!txt.includes("{{")) { if (!txt.trim() && !txt.includes(" ")) return null; return () => txt; } const parts = txt.split(/\{\{([\s\S]+?)\}\}/g); return (vals, ctx, key) => h( getReact().Fragment, { key }, ...parts.map((p, i) => { if (!(i & 1)) return p; const v = resolve(vals, p); if (v === void 0) { if (!ctx?.__streamingNow) { if (document.body?.hasAttribute("data-dc-editor-on")) { return h( "span", { key: i, className: "sc-interp sc-unresolved" }, "{{ " + p.trim() + " }}" ); } warnUnresolved( ctx, "{{ " + p.trim() + " }} never resolved \u2014 rendered as empty" ); return null; } return h( "span", { key: i, className: "sc-interp sc-missing" }, p.trim() ); } if (getReact().isValidElement(v) || Array.isArray(v)) { return h(getReact().Fragment, { key: i }, v); } if (v === null || typeof v === "boolean") return null; return h("span", { key: i, className: "sc-interp" }, String(v)); }) ); } function walkFor(el, host) { const listGet = compileAttr(el.getAttribute("list") || ""); const asName = el.getAttribute("as") || "item"; const hintN = parseInt(el.getAttribute("hint-placeholder-count") || "0", 10); const kids = walkChildren(el, host); const listSrc = el.getAttribute("list") || ""; return (vals, ctx, key) => { let list = listGet(vals); if (!Array.isArray(list)) { if (!ctx?.__streamingNow) { if (list !== void 0 && list !== null) { warnUnresolved( ctx, 'sc-for list="' + listSrc + '" is not an array (' + typeof list + ")" ); } list = []; } else { list = hintN > 0 ? Array(hintN).fill(void 0) : []; } } return h( getReact().Fragment, { key }, list.map((item, i) => { const sub = { ...vals, [asName]: item, $index: i }; return h( getReact().Fragment, { key: i }, kids.map((b, j) => b(sub, ctx, j)) ); }) ); }; } function walkIf(el, host) { const valGet = compileAttr(el.getAttribute("value") || ""); const hintRaw = el.getAttribute("hint-placeholder-val"); const hintGet = hintRaw != null ? compileAttr(hintRaw) : null; const kids = walkChildren(el, host); return (vals, ctx, key) => { let v = valGet(vals); if (v === void 0 && hintGet && ctx?.__streamingNow) v = hintGet(vals); return v ? h( getReact().Fragment, { key }, kids.map((b, j) => b(vals, ctx, j)) ) : null; }; } function walkComponent(el, host) { const name = el.getAttribute("name") || el.getAttribute("component") || ""; el.removeAttribute("name"); el.removeAttribute("component"); const tplId = el.getAttribute("data-dc-tpl"); const styleRaw = el.getAttribute("style"); el.removeAttribute("style"); const styleGet = styleRaw != null ? compileAttr(styleRaw) : null; const { propGetters, hintSize } = collectProps(el, "dc-import", host); const kids = walkChildren(el, host); return (vals, ctx, key) => { const props = { key, __hintSize: hintSize, __tplId: tplId, __hostStyle: styleGet ? hostPositionStyle(styleGet(vals)) : void 0 }; for (const [k, g] of propGetters) { const v = g(vals); if (k === "dcProps") { if (v && typeof v === "object") Object.assign(props, v); continue; } props[k] = v; } if (kids.length) props.children = kids.map((b, j) => b(vals, ctx, j)); return h(host.component(name), props); }; } function walkXImport(el, host) { const globalNameGet = compileAttr( el.getAttribute("component-from-global-scope") || "" ); const exportNameGet = compileAttr( el.getAttribute("component") || el.getAttribute("name") || "" ); const fromRaw = el.getAttribute("from") || (el.getAttribute("component-from-global-scope") ? "" : el.getAttribute("src") || el.getAttribute("import") || ""); const urls = fromRaw.trim() ? fromRaw.trim().split(/\s+/) : []; const url = urls.length ? urls[urls.length - 1] : ""; const kindOf = (u) => /\.(jsx|tsx)(\?|#|$)/i.test(u) ? "jsx" : "js"; const tplId = el.getAttribute("data-dc-tpl"); const styleRaw = el.getAttribute("style"); el.removeAttribute("style"); const styleGet = styleRaw != null ? compileAttr(styleRaw) : null; const wrap = tplId != null || styleGet != null; const { propGetters, hintSize } = collectProps(el, "x-import", host); const hasContent = el.children.length > 0 || !!(el.textContent || "").trim(); const deckKeyed = hasContent && isDeckMountTag(el) ? walkDeckChildren(el, host) : null; const kids = deckKeyed ? deckKeyed.kids : hasContent ? walkChildren(el, host) : []; const kidKeys = deckKeyed?.keys ?? null; const urlBindable = fromRaw.includes("{{"); if (urls.length && !urlBindable) { let prev; for (const u of urls) prev = host.loadExternal(kindOf(u), u, prev); } const evalName = (g, vals) => { const v = g(vals); const s = v == null ? "" : String(v); return s.includes("{{") ? "" : s; }; return (vals, ctx, key) => { const globalName = evalName(globalNameGet, vals); const name = globalName || evalName(exportNameGet, vals); const C = !name || urlBindable ? null : globalName ? host.resolveExternalGlobal(url, globalName) : host.resolveExternal(url, name); const hostStyle = styleGet ? hostPositionStyle(styleGet(vals)) : void 0; const wrapper = wrap ? { key, className: "sc-host-x", "data-dc-tpl": tplId, style: hostStyle || { display: "contents" } } : null; if (!C) { const error = urlBindable ? "x-import `from` cannot contain {{ \u2026 }} \u2014 module URLs are resolved at parse time; use a literal URL" : host.resolveExternalError(url, name); const ph = host.placeholder({ key: wrapper ? void 0 : key, name, hintSize, error }); return wrapper ? h("div", wrapper, ph) : ph; } const props = wrapper ? {} : { key }; let unresolvedHole = false; for (const [k, g] of propGetters) { if (k === "component" || k === "componentFromGlobalScope" || k === "from") { continue; } const v = g(vals); if (v === void 0) unresolvedHole = true; if (k === "dcProps") { if (v && typeof v === "object") Object.assign(props, v); continue; } props[k] = v; } if (unresolvedHole && ctx?.__htmlStreamingNow) { const ph = host.placeholder({ key: wrapper ? void 0 : key, name, hintSize, error: null }); return wrapper ? h("div", wrapper, ph) : ph; } if (kids.length) { props.children = renderDeckKids(kids, kidKeys, vals, ctx); } return wrapper ? h("div", wrapper, h(C, props)) : h(C, props); }; } function contentKey(el) { const clone = el.cloneNode(true); for (const d of clone.querySelectorAll("*")) { while (d.attributes.length) d.removeAttribute(d.attributes[0].name); } const s = clone.innerHTML; let h2 = 5381; for (let i = 0; i < s.length; i++) h2 = (h2 << 5) + h2 + s.charCodeAt(i) | 0; return s.length + "." + (h2 >>> 0).toString(36); } var NEVER_CONTENT_KEYED = new Set( "script style textarea option title select canvas iframe video audio".split( " " ) ); var NOT_INLINE_SELECTOR = ":not(" + [...INLINE_TEXT_TAGS].join(",") + ")"; function walkElement(el, host) { const realTag = RAW_UNWRAP[el.localName] || el.localName; const tplId = el.getAttribute("data-dc-tpl"); const inlineOnly = el.childNodes.length > 0 && !NEVER_CONTENT_KEYED.has(realTag) && el.querySelector(NOT_INLINE_SELECTOR) === null; const keySuffix = inlineOnly ? "|" + contentKey(el) : ""; const { propGetters, pseudoClasses } = collectProps(el, "dom", host); const deckKeyed = isDeckMountTag(el) ? walkDeckChildren(el, host) : null; const kids = deckKeyed ? deckKeyed.kids : walkChildren(el, host); const kidKeys = deckKeyed?.keys ?? null; return (vals, ctx, key) => { const props = { key: key + keySuffix, "data-dc-tpl": tplId }; for (const [k, g] of propGetters) { let v = g(vals); if (k === "style" && typeof v === "string") v = cssToObj(v); if ((k === "value" || k === "checked") && v === void 0) { v = k === "checked" ? false : ""; } props[k] = v; } if (pseudoClasses.length) { props.className = [props.className, ...pseudoClasses].filter(Boolean).join(" "); } return h(realTag, props, ...renderDeckKids(kids, kidKeys, vals, ctx)); }; }
// src/logic.ts var StreamableLogic = class { constructor(props) { __publicField(this, "props"); __publicField(this, "state", {}); /** Back-pointer to the wrapper component, installed after construction. */ __publicField(this, "__host"); this.props = props || {}; } setState(update, cb) { this.__host && this.__host.__setLogicState(update, cb); } forceUpdate() { this.__host && this.__host.forceUpdate(); } componentDidMount() { } componentDidUpdate(_prevProps) { } componentWillUnmount() { } /** The flat object the template renders against (merged over props). */ renderVals() { return {}; } }; function evalDcLogic(src) { //! nosemgrep: eval-and-function-constructor const fn = new Function( "DCLogic", "StreamableLogic", "React", src + '\n;return (typeof Component!=="undefined"&&Component)||undefined;' ); return fn(StreamableLogic, StreamableLogic, getReact()); }
// src/component.ts function shallowEqual(a, b) { if (!b) return false; const ak = Object.keys(a).filter((k) => k !== "children"); const bk = Object.keys(b).filter((k) => k !== "children"); if (ak.length !== bk.length) return false; for (const k of ak) if (a[k] !== b[k]) return false; return true; } function Placeholder({ name, hintSize, streaming, error }) { const [w, hgt] = (hintSize || "100%,60px").split(","); return h( "div", { className: "sc-placeholder" + (streaming ? " sc-streaming" : ""), style: { width: w.trim(), height: hgt && hgt.trim() }, title: name }, error ? h( "div", { className: "sc-placeholder-error" }, (name ? name + ": " : "") + error ) : null ); } function hintToMin(hint) { if (!hint) return void 0; const [w, hgt] = hint.split(","); return { minWidth: w.trim(), minHeight: hgt && hgt.trim() }; } function createComponentFactory(registry, ensureFetched) { const React = getReact(); const AncestorContext = React.createContext([]); class StreamableComponent extends React.Component { constructor(props) { super(props); __publicField(this, "__name"); __publicField(this, "__sub"); __publicField(this, "__needsDidMount", false); /** Snapshot of the registry's streaming flags taken at render time — * builders read it off the RenderCtx (this) to pick placeholder vs * render-nothing for unresolved values. */ __publicField(this, "__streamingNow", false); __publicField(this, "__htmlStreamingNow", false); /** When a construct throws, remember the (class, registry.ver, props) * triple so render-time reconcile doesn't re-attempt it on every parent * re-render. A registry bump (new class, template, external module * resolving via bumpAll) changes `ver` and breaks the memo so an * env-dependent constructor can self-heal. */ __publicField(this, "__failedLogic", null); __publicField(this, "__failedUserProps", null); __publicField(this, "__failedVer", -1); /** Per-instance constructor error — kept here (not on the registry entry) * so one instance's successful construct can't hide a sibling's failure, * and a construct can never wipe an eval error `updateJs` recorded on * `r.logicError`. */ __publicField(this, "__ctorError", null); __publicField(this, "logic"); this.__name = props.__name; this.state = { __v: 0, __err: null }; this.__sub = () => { if (this.state.__err) this.setState({ __err: null }); this.forceUpdate(); }; this.__makeLogic(registry.get(this.__name).Logic, null); ensureFetched(this.__name); } /** Error-boundary hook: a render crash anywhere in this DC's subtree * (its own template, an x-import'd component, a child DC without its * own deeper boundary) lands here instead of unmounting the page. */ static getDerivedStateFromError(e) { return { __err: e instanceof Error && e.message ? e.message : String(e) }; } componentDidCatch(e, info) { console.error( "[dc-runtime] render error in <" + this.__name + ">:", e, info?.componentStack || "" ); } /** Instantiate the logic class (or the no-op base) and adopt `prevState` * over its initial state — used both at mount and on hot-swap. */ __makeLogic(Logic, prevState) { const L = Logic || StreamableLogic; try { this.logic = new L(this.__userProps()); this.__failedLogic = null; this.__failedUserProps = null; this.__ctorError = null; } catch (e) { console.error(e); this.__failedLogic = Logic; this.__failedUserProps = this.__userProps(); this.__failedVer = registry.get(this.__name).ver; this.__ctorError = this.__name + ": " + (e instanceof Error && e.message ? e.message : String(e)); this.logic = new StreamableLogic( this.__userProps() ); } this.logic.__host = this; if (prevState) this.logic.state = { ...this.logic.state || {}, ...prevState }; } /** The props the author's logic + template see — internal __-prefixed * wiring stripped. */ __userProps() { const { __name, __hintSize, __tplId, __hostStyle, ...rest } = this.props; return rest; } __setLogicState(update, cb) { const prev = this.logic.state; const patch = typeof update === "function" ? update(prev) : update; this.logic.state = { ...prev, ...patch }; this.setState((s) => ({ __v: s.__v + 1 }), cb); } /** Swap the logic instance when the registry's Logic class changed * (streaming completion, hot reload). State carries over; didMount * re-fires after the swap commits so refs exist. */ __reconcileLogic() { const r = registry.get(this.__name); const Next = r.Logic; const Cur = this.logic.constructor; if (Next === Cur || !Next && Cur === StreamableLogic || Next === this.__failedLogic && r.ver === this.__failedVer && shallowEqual(this.__userProps(), this.__failedUserProps)) { return; } if (!this.__needsDidMount) { try { this.logic.componentWillUnmount(); } catch (e) { console.error(e); } } this.__makeLogic(Next, this.logic.state); this.__needsDidMount = true; } componentDidMount() { registry.get(this.__name).subs.add(this.__sub); try { this.logic.componentDidMount(); } catch (e) { console.error(e); } } componentDidUpdate(prevProps) { this.logic.props = this.__userProps(); if (this.__needsDidMount) { if (this.state.__err || !registry.get(this.__name).tpl) return; this.__needsDidMount = false; try { this.logic.componentDidMount(); } catch (e) { console.error(e); } } else { try { this.logic.componentDidUpdate(prevProps); } catch (e) { console.error(e); } } } componentWillUnmount() { registry.get(this.__name).subs.delete(this.__sub); if (!this.__needsDidMount) { try { this.logic.componentWillUnmount(); } catch (e) { console.error(e); } } } render() { const r = registry.get(this.__name); const cls = "sc-host" + (r.htmlStreaming ? " sc-streaming-html" : "") + (r.jsStreaming ? " sc-streaming-js" : ""); const hintStyle = r.htmlStreaming ? hintToMin(this.props.__hintSize) : void 0; const hostStyle = this.props.__hostStyle || hintStyle ? { ...hintStyle || {}, ...this.props.__hostStyle || {} } : void 0; const hostBase = { className: cls, style: hostStyle, "data-sc-name": this.__name, "data-dc-tpl": this.props.__tplId }; const chain = Array.isArray(this.context) ? this.context : []; if (chain.includes(this.__name)) { const cycle = [ ...chain.slice(chain.indexOf(this.__name)), this.__name ].join(" \u2192 "); return h( "div", { ...hostBase, className: cls + " sc-has-error" }, h(Placeholder, { name: this.__name, hintSize: this.props.__hintSize, error: "circular import: " + cycle }) ); } if (this.state.__err) { return h( "div", { ...hostBase, className: cls + " sc-has-error" }, h( "div", { className: "sc-logic-error", "data-omelette-chrome": "" }, this.__name + ": " + this.state.__err ), h(Placeholder, { name: this.__name, hintSize: this.props.__hintSize, error: this.state.__err }) ); } this.__reconcileLogic(); if (!r.tpl) { return h( "div", hostBase, h(Placeholder, { name: this.__name, hintSize: this.props.__hintSize }) ); } const userProps = this.__userProps(); this.logic.props = userProps; let vals = userProps; let renderErr = r.logicError || this.__ctorError; try { vals = { ...userProps, ...this.logic.renderVals() || {} }; } catch (e) { console.error(e); renderErr = this.__name + ".renderVals(): " + (e instanceof Error && e.message ? e.message : String(e)); } this.__streamingNow = !!(r.htmlStreaming || r.jsStreaming); this.__htmlStreamingNow = !!r.htmlStreaming; return h( "div", { ...hostBase, className: cls + (renderErr ? " sc-has-error" : "") }, renderErr && h( "div", { className: "sc-logic-error", "data-omelette-chrome": "" }, renderErr ), h( AncestorContext.Provider, { value: [...chain, this.__name] }, r.tpl(vals, this) ) ); } } __publicField(StreamableComponent, "contextType", AncestorContext); const named = /* @__PURE__ */ new Map(); function getDC(name) { const hit = named.get(name); if (hit) return hit; function Dispatcher(p) { const [, setTick] = React.useState(0); React.useEffect(() => { const sub = () => setTick((n) => n + 1); registry.get(name).subs.add(sub); return () => { registry.get(name).subs.delete(sub); }; }, []); ensureFetched(name); return h(StreamableComponent, { ...p, __name: name }); } Dispatcher.displayName = name; named.set(name, Dispatcher); return Dispatcher; } return { getDC, StreamableComponent }; }
// src/bundled.ts function bundledBlob(url) { const blobs = window.__resourceBlobs; const b = blobs ? blobs[url.split("#")[0]] : void 0; return b instanceof Blob ? b : null; }
// src/cdn.ts var REACT_URL = "https://unpkg.com/react@18.3.1/umd/react.production.min.js"; var REACT_SRI = "sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z"; var REACT_DOM_URL = "https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js"; var REACT_DOM_SRI = "sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1"; var BABEL_URL = "https://unpkg.com/@babel/standalone@7.29.0/babel.min.js"; var BABEL_SRI = "sha384-m08KidiNqLdpJqLq95G/LEi8Qvjl/xUYll3QILypMoQ65QorJ9Lvtp2RXYGBFj1y"; function cdnScriptFor(url, sri) { const res = window.__resources; const v = res ? res[url] : void 0; return typeof v === "string" && v ? { src: v } : { src: url, integrity: sri }; }
// src/external.ts var isCustomElementName = (n) => !n.includes(".") && n.includes("-"); function isRenderableType(g) { if (typeof g === "function") return !isElementClass(g); return typeof g === "object" && g !== null && typeof g.$$typeof === "symbol"; } function resolveDottedPath(root, name) { let cur = root; for (const seg of name.split(".")) { if (cur == null) return void 0; cur = cur[seg]; } return cur; } var GLOBAL_POLL_INTERVAL_MS = 50; var GLOBAL_POLL_TIMEOUT_MS = 3e4; function createExternalModules(onResolved) { const cache = /* @__PURE__ */ new Map(); let babelLoading = null; const reportedMissing = /* @__PURE__ */ new Map(); const polling = /* @__PURE__ */ new Set(); function ensureBabel() { if (window.Babel) return Promise.resolve(); if (babelLoading) return babelLoading; const babel = cdnScriptFor(BABEL_URL, BABEL_SRI); babelLoading = new Promise((res, rej) => { const s = document.createElement("script"); s.src = babel.src; if (babel.integrity) { s.integrity = babel.integrity; s.crossOrigin = "anonymous"; } s.onload = () => res(); s.onerror = rej; document.head.appendChild(s); }); return babelLoading; } const pending = /* @__PURE__ */ new Map(); function load(kind, url, after) { const existing = pending.get(url); if (existing) return existing; cache.set(url, null); console.info("[dc-runtime] x-import: loading", url, "(" + kind + ")"); const ready = Promise.all([ kind === "jsx" ? ensureBabel() : Promise.resolve(), after ?? Promise.resolve() ]); const p = ready.then(() => { const pre = bundledBlob(url); if (pre) return pre.text(); return fetch(url).then((r) => { if (!r.ok) throw new Error("HTTP " + r.status); return r.text(); }); }).then((src) => { const code = kind === "jsx" ? window.Babel.transform(src, { filename: url, presets: ["react", "typescript"] }).code : src; const module = { exports: {} }; const before = new Set(Object.keys(window)); //! nosemgrep: eval-and-function-constructor new Function("React", "module", "exports", "require", code)( getReact(), module, module.exports, () => ({}) ); const globals = {}; for (const k of Object.keys(window)) { if (!before.has(k) && typeof window[k] === "function") { globals[k] = window[k]; } } cache.set(url, { mod: module.exports, globals }); console.info( "[dc-runtime] x-import: loaded", url, "\u2014 exports:", Object.keys(module.exports), "window globals:", Object.keys(globals) ); onResolved(); }).catch((e) => { cache.set(url, { mod: {}, globals: {}, error: "failed to load: " + (e instanceof Error && e.message ? e.message : String(e)) }); console.error( "[dc-runtime] x-import: FAILED to load", url, "(" + kind + ")", e ); onResolved(); }); pending.set(url, p); return p; } function resolve2(url, name) { const entry = cache.get(url); if (!entry) return null; const { mod, globals } = entry; const C = mod && mod[name] || globals && globals[name] || typeof window !== "undefined" && window[name] || mod && mod.default; if (typeof C === "function") return C; const key = url + "\0" + name; if (!reportedMissing.has(key)) { reportedMissing.set( key, entry.error || 'no export named "' + name + '" (has: ' + Object.keys(mod).join(", ") + ")" ); console.error( "[dc-runtime] x-import: module", url, "loaded but has no component named", JSON.stringify(name), "\u2014 available exports:", Object.keys(mod), "window globals:", Object.keys(globals), ". The module must `module.exports = {" + name + "}` or set `window." + name + "`." ); } return null; } function waitForGlobal(name) { if (polling.has(name)) return; polling.add(name); const started = Date.now(); const isCE = isCustomElementName(name); const tick = () => { const found = isCE ? customElements.get(name) : isRenderableType(resolveDottedPath(window, name)); if (found) { polling.delete(name); onResolved(); return; } if (Date.now() - started >= GLOBAL_POLL_TIMEOUT_MS) { console.warn( "[dc-runtime] x-import: global", JSON.stringify(name), "never appeared on window after " + GLOBAL_POLL_TIMEOUT_MS + "ms" ); return; } setTimeout(tick, GLOBAL_POLL_INTERVAL_MS); }; setTimeout(tick, GLOBAL_POLL_INTERVAL_MS); } function resolveGlobal(url, name) { const isCE = isCustomElementName(name); if (!url) { if (isCE) { if (customElements.get(name)) return name; waitForGlobal(name); return null; } const g2 = resolveDottedPath(window, name); if (isRenderableType(g2)) return g2; waitForGlobal(name); return null; } const entry = cache.get(url); if (!entry) return null; if (isCE && customElements.get(name)) return name; const g = entry.globals[name] ?? resolveDottedPath(window, name); if (isRenderableType(g)) return g; if (name.includes(".")) return null; const key = url + "\0global\0" + name; if (!reportedMissing.has(key)) { reportedMissing.set(key, null); if (isCE && !customElements.get(name)) { console.warn( "[dc-runtime] x-import:", url, "loaded but no custom element", JSON.stringify(name), "is registered and window." + name + " is not a function \u2014 rendering <" + name + "> as an unknown element." ); } } return name; } function getError(url, name) { const entry = cache.get(url); if (entry?.error) return entry.error; return reportedMissing.get(url + "\0" + name) || null; } return { load, resolve: resolve2, resolveGlobal, getError }; } function isElementClass(g) { try { return typeof g === "function" && typeof HTMLElement !== "undefined" && g.prototype instanceof HTMLElement; } catch { return false; } }
// src/atomics.ts var ATOMIC_CSS = ( // layout ".fx{display:flex}.col{display:flex;flex-direction:column}.grid{display:grid}.ac{align-items:center}.jc{justify-content:center}.jb{justify-content:space-between}.f1{flex:1}.noshrink{flex-shrink:0}.wrap{flex-wrap:wrap}.fw5{font-weight:500}.fw6{font-weight:600}.fw7{font-weight:700}.fw8{font-weight:800}.fs11{font-size:11px}.fs12{font-size:12px}.fs13{font-size:13px}.fs14{font-size:14px}.fs15{font-size:15px}.fs16{font-size:16px}.fs20{font-size:20px}.fs22{font-size:22px}.upper{text-transform:uppercase}.tc{text-align:center}.nowrap{white-space:nowrap}.gap8{gap:8px}.gap10{gap:10px}.gap12{gap:12px}.gap16{gap:16px}.gap24{gap:24px}.m0{margin:0}.mt8{margin-top:8px}.mt12{margin-top:12px}.mt16{margin-top:16px}.mb8{margin-bottom:8px}.mb12{margin-bottom:12px}.mb16{margin-bottom:16px}.posrel{position:relative}.posabs{position:absolute}.round{border-radius:50%}.ohide{overflow:hidden}.bbox{box-sizing:border-box}.pointer{cursor:pointer}.w100{width:100%}.b0{border:none}" );
// src/helmet.ts var DESIGN_DOC_MODE_RE = /<meta\b[^>]*\bname\s*=\s*["']design_doc_mode["'][^>]*\b(?:content|value)\s*=\s*["'](\w+)["']/i; var CANVAS_BG_LIGHT = "#f0eee6"; var CANVAS_BG_DARK = "#2e2c26"; function createHelmetManager(doc, isStreaming) { const mounted = /* @__PURE__ */ new Set(); const live = /* @__PURE__ */ new Map(); let designDocMode = null; let canvasStyleEl = null; let appTheme = "light"; try { const ds = doc.documentElement.dataset.theme; appTheme = ds === "dark" || ds === "light" ? ds : new URLSearchParams(doc.defaultView?.location.search ?? "").get( "theme" ) === "dark" ? "dark" : "light"; } catch { } function applyCanvasBg() { if (!canvasStyleEl) return; const bg = appTheme === "dark" ? CANVAS_BG_DARK : CANVAS_BG_LIGHT; canvasStyleEl.textContent = `html,body{background:${bg}}#dc-root>.sc-host{position:relative}`; } function postDesignMode(mode) { if (window.parent === window) return; try { window.parent.postMessage({ type: "__dc_design_mode", mode }, "*"); } catch { } } function setDesignDocMode(mode) { if (mode === designDocMode) return; designDocMode = mode; postDesignMode(mode); if (mode === "canvas") { doc.documentElement.setAttribute("data-dc-canvas", ""); canvasStyleEl = doc.createElement("style"); canvasStyleEl.setAttribute("data-dc-canvas", ""); applyCanvasBg(); doc.head.appendChild(canvasStyleEl); } else { doc.documentElement.removeAttribute("data-dc-canvas"); canvasStyleEl?.remove(); canvasStyleEl = null; } } window.addEventListener("message", (e) => { const type = e.data && e.data.type; if (type === "__dc_theme") { const t = e.data.theme; if (t === "light" || t === "dark") { appTheme = t; applyCanvasBg(); } return; } if (!designDocMode || type !== "__dc_probe") return; postDesignMode(designDocMode); }); function compile(node) { const raw = [...node.children]; const helmetClosed = node.nextSibling != null || node.parentNode?.nextSibling != null; if (node.hasAttribute("data-dc-atomics") && !mounted.has("__dc-atomics")) { mounted.add("__dc-atomics"); const el = doc.createElement("style"); el.id = "__dc-atomics"; el.textContent = ATOMIC_CSS; doc.head.appendChild(el); } return (_vals, ctx) => { const name = ctx && ctx.__name || ""; const streaming = !!(name && isStreaming(name)); for (let i = 0; i < raw.length; i++) { const child = raw[i]; const tag = child.tagName; const mayBePartial = streaming && !helmetClosed && i === raw.length - 1; if (tag === "SCRIPT") { if (mayBePartial) continue; const key = "SCRIPT|" + (child.getAttribute("src") || child.textContent || ""); if (mounted.has(key)) continue; mounted.add(key); const el = doc.createElement("script"); for (const { name: an, value } of [...child.attributes]) el.setAttribute(an, value); if (child.textContent) el.textContent = child.textContent; doc.head.appendChild(el); } else if (tag === "LINK" || tag === "META") { if (mayBePartial) continue; const key = tag + "|" + (child.getAttribute("href") || child.getAttribute("src") || child.outerHTML); if (mounted.has(key)) continue; mounted.add(key); if (tag === "LINK") { const rel = (child.getAttribute("rel") || "").toLowerCase().split(/\s+/); const href = (child.getAttribute("href") || "").trim(); const res = window.__resources; const pre = res && rel.includes("stylesheet") && !rel.includes("alternate") ? res[href] : void 0; const blob = typeof pre === "string" && pre ? bundledBlob(pre) : null; if (blob) { const el = doc.createElement("style"); if (child.hasAttribute("disabled")) { el.setAttribute("media", "not all"); } else if (child.getAttribute("media")) { el.setAttribute("media", child.getAttribute("media")); } if (child.getAttribute("title")) el.setAttribute("title", child.getAttribute("title")); void blob.text().then((css) => { el.textContent = css; }); doc.head.appendChild(el); continue; } } doc.head.appendChild(child.cloneNode(true)); } else { const key = name + "|" + i; let el = live.get(key); if (!el || el.tagName !== tag) { if (el) el.remove(); el = doc.createElement(tag.toLowerCase()); live.set(key, el); doc.head.appendChild(el); } for (const { name: an, value } of [...child.attributes]) { if (el.getAttribute(an) !== value) el.setAttribute(an, value); } if (el.textContent !== child.textContent) el.textContent = child.textContent; } } return null; }; } return { compile, setDesignDocMode }; }
// src/pseudo.ts function scanUnquotedUrl(css, i) { if (css[i] !== "u" && css[i] !== "U" || css.slice(i, i + 4).toLowerCase() !== "url(" || /[a-z0-9_-]/i.test(css[i - 1] ?? "")) { return -1; } let j = i + 4; while (j < css.length && /\s/.test(css[j])) j++; if (css[j] === '"' || css[j] === "'") return -1; while (j < css.length && css[j] !== ")") { if (css[j] === "\\") j++; j++; } return j < css.length ? j + 1 : css.length; } function stripComments(css) { let out = ""; let quote = ""; for (let i = 0; i < css.length; i++) { const c = css[i]; if (quote) { if (c === "\\") { out += c + (css[i + 1] ?? ""); i++; continue; } if (c === quote) quote = ""; out += c; } else if (c === "'" || c === '"') { quote = c; out += c; } else if (c === "/" && css[i + 1] === "*") { const end = css.indexOf("*/", i + 2); i = end === -1 ? css.length : end + 1; out += " "; } else { const end = scanUnquotedUrl(css, i); if (end === -1) out += c; else { out += css.slice(i, end); i = end - 1; } } } return out; } function importantify(css) { css = stripComments(css); const decls = []; let start = 0; let depth = 0; let quote = ""; for (let i = 0; i < css.length; i++) { const c = css[i]; if (quote) { if (c === "\\") i++; else if (c === quote) quote = ""; } else if (c === "'" || c === '"') quote = c; else if (c === "(") depth++; else if (c === ")") depth = Math.max(0, depth - 1); else if (c === ";" && depth === 0) { decls.push(css.slice(start, i)); start = i + 1; } else { const end = scanUnquotedUrl(css, i); if (end !== -1) i = end - 1; } } decls.push(css.slice(start)); return decls.map((d) => d.trim()).filter(Boolean).map((d) => /!\s*important$/i.test(d) ? d : d + " !important").join(";"); } function createPseudoSheet(doc) { let el = null; const cache = /* @__PURE__ */ new Map(); let n = 0; return (pseudo, css) => { const k = pseudo + "|" + css; const hit = cache.get(k); if (hit) return hit; if (!el) { el = doc.createElement("style"); doc.head.appendChild(el); } const cls = "scp" + (n++).toString(36); const isPseudoElement = pseudo === "before" || pseudo === "after"; const sel = isPseudoElement ? "." + cls + "::" + pseudo : "." + cls + ":" + pseudo; el.sheet.insertRule( sel + "{" + (isPseudoElement ? css : importantify(css)) + "}", el.sheet.cssRules.length ); cache.set(k, cls); return cls; }; }
// src/registry.ts function createRegistry() { const entries = /* @__PURE__ */ Object.create(null); function get(name) { return entries[name] || (entries[name] = { html: "", tpl: null, Logic: null, jsStreaming: false, htmlStreaming: false, ver: 0, subs: /* @__PURE__ */ new Set(), fetched: false }); } function bump(name) { const r = get(name); r.ver++; for (const fn of r.subs) fn(); } return { entries, get, bump, bumpAll() { for (const n in entries) bump(n); } }; }
// src/runtime.ts var COMPONENT_DIR = "."; function createRuntime(doc = document) { const registry = createRegistry(); const pseudoClass = createPseudoSheet(doc); const helmet = createHelmetManager( doc, (name) => registry.get(name).htmlStreaming ); const external = createExternalModules(() => registry.bumpAll()); const factory = createComponentFactory(registry, ensureFetched); const host = { component: (name) => factory.getDC(name), placeholder: (props) => h(Placeholder, props), helmet: (node) => helmet.compile(node), loadExternal: (kind, url, after) => external.load(kind, url, after), resolveExternal: (url, name) => external.resolve(url, name), resolveExternalGlobal: (url, name) => external.resolveGlobal(url, name), resolveExternalError: (url, name) => external.getError(url, name), pseudoClass }; function ensureFetched(name) { const r = registry.get(name); if (r.fetched) return; r.fetched = true; const url = COMPONENT_DIR + "/" + encodeURIComponent(name) + ".dc.html"; const res = window.__resources; const pre = res ? res[url] : void 0; const target = typeof pre === "string" && pre ? pre : url; const blob = bundledBlob(target); (blob ? blob.text() : fetch(target).then((res2) => { if (!res2.ok) { console.error( '[dc-runtime] sibling fetch for "' + name + '" failed:', url, "returned", res2.status, "\u2014 the reference renders as an empty placeholder." ); return ""; } return res2.text(); })).then((t) => { if (!t) return; const parsed = parseDcText(t); if (!parsed) { console.error( '[dc-runtime] sibling fetch for "' + name + '":', url, "has no <x-dc> block \u2014 not a Design Component." ); return; } if (parsed.props) r.propsMeta = parsed.props; if (parsed.preview) r.preview = parsed.preview; if (parsed.template && !r.html) updateHtml(name, parsed.template); if (parsed.js && !r.Logic) updateJs(name, parsed.js); }).catch( (e) => console.error( '[dc-runtime] sibling fetch for "' + name + '" threw:', url, e ) ); } let rootName = null; function updateHtml(name, html) { const r = registry.get(name); r.html = html; if (name === rootName) { const mode = DESIGN_DOC_MODE_RE.exec(html)?.[1] ?? null; if (mode || !r.htmlStreaming) helmet.setDesignDocMode(mode); } try { r.tpl = compileTemplate(html, host); } catch (e) { console.error("[dc-runtime] template compile FAILED for", name, e); } registry.bump(name); } function updateJs(name, src) { const r = registry.get(name); const seq = r.jsSeq = (r.jsSeq || 0) + 1; try { const Cls = evalDcLogic(src); if (r.jsSeq !== seq) return; if (typeof Cls !== "function") { r.logicError = name + ".dc.html: <script data-dc-script> must define `class Component extends DCLogic`"; } else { r.logicError = null; r.Logic = Cls; } } catch (e) { if (r.jsSeq !== seq) return; console.error( "[dc-runtime] logic class eval FAILED for", name, "\u2014 the template renders with props only.", e ); r.logicError = name + ": " + (e instanceof Error && e.message ? e.message : String(e)); } registry.bump(name); } function setStreaming(name, kind, on) { const r = registry.get(name); if (kind === "html") r.htmlStreaming = !!on; else r.jsStreaming = !!on; let any = false; for (const n in registry.entries) { const e = registry.entries[n]; if (e && (e.htmlStreaming || e.jsStreaming)) { any = true; break; } } doc.documentElement.classList.toggle("sc-dc-streaming", any); registry.bump(name); } function dcUpdate(name, kind, content, streaming) { if (streaming) registry.get(name).fetched = true; if (kind === "html") { setStreaming(name, "html", !!streaming); updateHtml(name, content); } else if (kind === "js") { setStreaming(name, "js", !!streaming); if (!streaming) updateJs(name, content); } else if (kind === "props") { const { props, preview } = parseDataProps(content); const r = registry.get(name); r.propsMeta = props ?? void 0; r.preview = preview; registry.bump(name); } } function setProps(name, overrides) { registry.get(name).propOverrides = overrides && typeof overrides === "object" ? { ...overrides } : null; registry.bump(name); } function adoptParsed(name, parsed) { if (!parsed) return; const r = registry.get(name); if (parsed.props) r.propsMeta = parsed.props; if (parsed.preview) r.preview = parsed.preview; if (parsed.template) updateHtml(name, parsed.template); if (parsed.js) updateJs(name, parsed.js); } return { registry, getDC: factory.getDC, updateHtml, updateJs, dcUpdate, setProps, adoptParsed, setRootName: (name) => { rootName = name; }, markFetched: (name) => { registry.get(name).fetched = true; }, annotatedTemplate: (name) => { const r = registry.get(name); return r.tpl && r.tpl.__annotated || null; }, templateSource: (name) => registry.get(name).html || null, StreamableLogic }; }
// src/stream-state.ts function createStreamTracker(staleMs = 6e4, now = Date.now) { const since = /* @__PURE__ */ new Map(); const liveOne = (n) => { const t = since.get(n); if (t === void 0) return false; if (now() - t > staleMs) { since.delete(n); return false; } return true; }; return { push(name, streaming, viewportKey) { if (viewportKey === "dc-model") return; if (streaming) since.set(name, now()); else since.delete(name); }, live(name) { if (name !== void 0) return liveOne(name); for (const n of [...since.keys()]) if (liveOne(n)) return true; return false; } }; }
// src/index.ts function hideRawTemplate() { const s = document.createElement("style"); s.textContent = "x-dc{display:none!important}"; document.head.appendChild(s); } function loadScript(src, integrity) { return new Promise((resolve2, reject) => { //! nosemgrep: create-script-element const s = document.createElement("script"); s.src = src; if (integrity) { s.integrity = integrity; s.crossOrigin = "anonymous"; } s.async = false; s.onload = () => resolve2(); s.onerror = () => reject(new Error(`failed to load ${src}`)); document.head.appendChild(s); }); } function loadReactUmd() { const w = window; if (w.React && w.ReactDOM) return Promise.resolve(); const react = cdnScriptFor(REACT_URL, REACT_SRI); const reactDom = cdnScriptFor(REACT_DOM_URL, REACT_DOM_SRI); return Promise.all([ loadScript(react.src, react.integrity), loadScript(reactDom.src, reactDom.integrity) ]).then(() => void 0); } function init() { const runtime = createRuntime(document); let rootName = "Root"; const baseCss = document.createElement("style"); baseCss.textContent = BASE_CSS; document.head.prepend(baseCss); const notifyHost = () => { if (window.parent === window) return; const r = runtime.registry.entries[rootName]; try { window.parent.postMessage( { type: "__dc_booted", rootName, propsMeta: r && r.propsMeta || null, preview: r && r.preview || null }, "*" ); } catch { } }; const streams = createStreamTracker(); const api = { __dcUpdate: (name, kind, content, streaming, viewportKey) => { streams.push(name, streaming, viewportKey); runtime.dcUpdate(name, kind, content, streaming); if (name === rootName && !streaming && kind === "props") notifyHost(); }, __dcStreaming: (name) => streams.live(name), __dcSetProps: (name, overrides) => runtime.setProps(name, overrides), /** Name of the component currently mounted as the page root — DC tools * push their template-stream here when targeting "the open page". */ __dcRootName: () => rootName, /** Editor bridge — the encoded, `data-dc-tpl`-annotated template source. * The host editor parses this into its own template DOM so it can map a * rendered node (carrying the same `data-dc-tpl`) back to the source * node that emitted it. Returns the encoded form (`sc-camel-*` attrs, * `<sc-raw-*>`/`<sc-helmet>` tags); the editor decodes on serialize. */ __dcAnnotatedTemplate: (name) => runtime.annotatedTemplate(name), /** Editor bridge — the *original* (decoded) template source. */ __dcTemplateSource: (name) => runtime.templateSource(name), __dcBoot: () => { rootName = boot(runtime, document) ?? rootName; notifyHost(); }, __dcRegistry: runtime.registry.entries, getDC: (name) => runtime.getDC(name), // `DCLogic` is the documented base class name; `StreamableLogic` is the // implementation alias kept for any project that already references it. DCLogic: runtime.StreamableLogic, StreamableLogic: runtime.StreamableLogic }; Object.assign(window, api); window.__dcContentKeyed = true; if (document.readyState !== "loading") api.__dcBoot(); else document.addEventListener("DOMContentLoaded", () => api.__dcBoot()); } hideRawTemplate(); loadReactUmd().then(init).catch((err) => { console.error("[dc] failed to load React or boot:", err); throw err; });})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553// @ds-adherence-ignore -- omelette starter scaffold (raw elements/hex/px by design)// Copied omelette starter. Re-running copy_starter_component with this kind overwrites this file with the latest version (page content is unaffected).
/* BEGIN USAGE */// tweaks-panel.jsx// Reusable Tweaks shell + form-control helpers.// Exports (to window): useTweaks, TweaksPanel, TweakSection, TweakRow, TweakSlider,// TweakToggle, TweakRadio, TweakSelect, TweakText, TweakNumber, TweakColor, TweakButton.//// Owns the host protocol (listens for __activate_edit_mode / __deactivate_edit_mode,// posts __edit_mode_available / __edit_mode_set_keys / __edit_mode_dismissed) so// individual prototypes don't re-roll it. Ships a consistent set of controls so you// don't hand-draw <input type="range">, segmented radios, steppers, etc.//// Usage (in an HTML file that loads React + Babel)://// const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{// "primaryColor": "#D97757",// "palette": ["#D97757", "#29261b", "#f6f4ef"],// "fontSize": 16,// "density": "regular",// "dark": false// }/*EDITMODE-END*/;//// function App() {// const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);// return (// <div style={{ fontSize: t.fontSize, color: t.primaryColor }}>// Hello// <TweaksPanel>// <TweakSection label="Typography" />// <TweakSlider label="Font size" value={t.fontSize} min={10} max={32} unit="px"// onChange={(v) => setTweak('fontSize', v)} />// <TweakRadio label="Density" value={t.density}// options={['compact', 'regular', 'comfy']}// onChange={(v) => setTweak('density', v)} />// <TweakSection label="Theme" />// <TweakColor label="Primary" value={t.primaryColor}// options={['#D97757', '#2A6FDB', '#1F8A5B', '#7A5AE0']}// onChange={(v) => setTweak('primaryColor', v)} />// <TweakColor label="Palette" value={t.palette}// options={[['#D97757', '#29261b', '#f6f4ef'],// ['#475569', '#0f172a', '#f1f5f9']]}// onChange={(v) => setTweak('palette', v)} />// <TweakToggle label="Dark mode" value={t.dark}// onChange={(v) => setTweak('dark', v)} />// </TweaksPanel>// </div>// );// }//// TweakRadio is the segmented control for 2–3 short options (auto-falls-back to// TweakSelect past ~16/~10 chars per label); reach for TweakSelect directly when// options are many or long. For color tweaks always curate 3-4 options rather than// a free picker; an option can also be a whole 2–5 color palette (the stored value// is the array). The Tweak* controls are a floor, not a ceiling — build custom// controls inside the panel if a tweak calls for UI they don't cover./* END USAGE */// ─────────────────────────────────────────────────────────────────────────────
const __TWEAKS_STYLE = ` .twk-panel{position:fixed;right:16px;bottom:16px;z-index:2147483646;width:280px; max-height:calc(100vh - 32px);display:flex;flex-direction:column; transform:scale(var(--dc-inv-zoom,1));transform-origin:bottom right; background:rgba(250,249,247,.78);color:#29261b; -webkit-backdrop-filter:blur(24px) saturate(160%);backdrop-filter:blur(24px) saturate(160%); border:.5px solid rgba(255,255,255,.6);border-radius:14px; box-shadow:0 1px 0 rgba(255,255,255,.5) inset,0 12px 40px rgba(0,0,0,.18); font:11.5px/1.4 ui-sans-serif,system-ui,-apple-system,sans-serif;overflow:hidden} .twk-hd{display:flex;align-items:center;justify-content:space-between; padding:10px 8px 10px 14px;cursor:move;user-select:none} .twk-hd b{font-size:12px;font-weight:600;letter-spacing:.01em} .twk-x{appearance:none;border:0;background:transparent;color:rgba(41,38,27,.55); width:22px;height:22px;border-radius:6px;cursor:default;font-size:13px;line-height:1} .twk-x:hover{background:rgba(0,0,0,.06);color:#29261b} .twk-body{padding:2px 14px 14px;display:flex;flex-direction:column;gap:10px; overflow-y:auto;overflow-x:hidden;min-height:0; scrollbar-width:thin;scrollbar-color:rgba(0,0,0,.15) transparent} .twk-body::-webkit-scrollbar{width:8px} .twk-body::-webkit-scrollbar-track{background:transparent;margin:2px} .twk-body::-webkit-scrollbar-thumb{background:rgba(0,0,0,.15);border-radius:4px; border:2px solid transparent;background-clip:content-box} .twk-body::-webkit-scrollbar-thumb:hover{background:rgba(0,0,0,.25); border:2px solid transparent;background-clip:content-box} .twk-row{display:flex;flex-direction:column;gap:5px} .twk-row-h{flex-direction:row;align-items:center;justify-content:space-between;gap:10px} .twk-lbl{display:flex;justify-content:space-between;align-items:baseline; color:rgba(41,38,27,.72)} .twk-lbl>span:first-child{font-weight:500} .twk-val{color:rgba(41,38,27,.5);font-variant-numeric:tabular-nums}
.twk-sect{font-size:10px;font-weight:600;letter-spacing:.06em;text-transform:uppercase; color:rgba(41,38,27,.45);padding:10px 0 0} .twk-sect:first-child{padding-top:0}
.twk-field{appearance:none;box-sizing:border-box;width:100%;min-width:0;height:26px;padding:0 8px; border:.5px solid rgba(0,0,0,.1);border-radius:7px; background:rgba(255,255,255,.6);color:inherit;font:inherit;outline:none} .twk-field:focus{border-color:rgba(0,0,0,.25);background:rgba(255,255,255,.85)} select.twk-field{padding-right:22px; background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path fill='rgba(0,0,0,.5)' d='M0 0h10L5 6z'/></svg>"); background-repeat:no-repeat;background-position:right 8px center}
.twk-slider{appearance:none;-webkit-appearance:none;width:100%;height:4px;margin:6px 0; border-radius:999px;background:rgba(0,0,0,.12);outline:none} .twk-slider::-webkit-slider-thumb{-webkit-appearance:none;appearance:none; width:14px;height:14px;border-radius:50%;background:#fff; border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default} .twk-slider::-moz-range-thumb{width:14px;height:14px;border-radius:50%; background:#fff;border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default}
.twk-seg{position:relative;display:flex;padding:2px;border-radius:8px; background:rgba(0,0,0,.06);user-select:none} .twk-seg-thumb{position:absolute;top:2px;bottom:2px;border-radius:6px; background:rgba(255,255,255,.9);box-shadow:0 1px 2px rgba(0,0,0,.12); transition:left .15s cubic-bezier(.3,.7,.4,1),width .15s} .twk-seg.dragging .twk-seg-thumb{transition:none} .twk-seg button{appearance:none;position:relative;z-index:1;flex:1;border:0; background:transparent;color:inherit;font:inherit;font-weight:500;min-height:22px; border-radius:6px;cursor:default;padding:4px 6px;line-height:1.2; overflow-wrap:anywhere}
.twk-toggle{position:relative;width:32px;height:18px;border:0;border-radius:999px; background:rgba(0,0,0,.15);transition:background .15s;cursor:default;padding:0} .twk-toggle[data-on="1"]{background:#34c759} .twk-toggle i{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%; background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .15s} .twk-toggle[data-on="1"] i{transform:translateX(14px)}
.twk-num{display:flex;align-items:center;box-sizing:border-box;min-width:0;height:26px;padding:0 0 0 8px; border:.5px solid rgba(0,0,0,.1);border-radius:7px;background:rgba(255,255,255,.6)} .twk-num-lbl{font-weight:500;color:rgba(41,38,27,.6);cursor:ew-resize; user-select:none;padding-right:8px} .twk-num input{flex:1;min-width:0;height:100%;border:0;background:transparent; font:inherit;font-variant-numeric:tabular-nums;text-align:right;padding:0 8px 0 0; outline:none;color:inherit;-moz-appearance:textfield} .twk-num input::-webkit-inner-spin-button,.twk-num input::-webkit-outer-spin-button{ -webkit-appearance:none;margin:0} .twk-num-unit{padding-right:8px;color:rgba(41,38,27,.45)}
.twk-btn{appearance:none;height:26px;padding:0 12px;border:0;border-radius:7px; background:rgba(0,0,0,.78);color:#fff;font:inherit;font-weight:500;cursor:default} .twk-btn:hover{background:rgba(0,0,0,.88)} .twk-btn.secondary{background:rgba(0,0,0,.06);color:inherit} .twk-btn.secondary:hover{background:rgba(0,0,0,.1)}
.twk-swatch{appearance:none;-webkit-appearance:none;width:56px;height:22px; border:.5px solid rgba(0,0,0,.1);border-radius:6px;padding:0;cursor:default; background:transparent;flex-shrink:0} .twk-swatch::-webkit-color-swatch-wrapper{padding:0} .twk-swatch::-webkit-color-swatch{border:0;border-radius:5.5px} .twk-swatch::-moz-color-swatch{border:0;border-radius:5.5px}
.twk-chips{display:flex;gap:6px} .twk-chip{position:relative;appearance:none;flex:1;min-width:0;height:46px; padding:0;border:0;border-radius:6px;overflow:hidden;cursor:default; box-shadow:0 0 0 .5px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.06); transition:transform .12s cubic-bezier(.3,.7,.4,1),box-shadow .12s} .twk-chip:hover{transform:translateY(-1px); box-shadow:0 0 0 .5px rgba(0,0,0,.18),0 4px 10px rgba(0,0,0,.12)} .twk-chip[data-on="1"]{box-shadow:0 0 0 1.5px rgba(0,0,0,.85), 0 2px 6px rgba(0,0,0,.15)} .twk-chip>span{position:absolute;top:0;bottom:0;right:0;width:34%; display:flex;flex-direction:column;box-shadow:-1px 0 0 rgba(0,0,0,.1)} .twk-chip>span>i{flex:1;box-shadow:0 -1px 0 rgba(0,0,0,.1)} .twk-chip>span>i:first-child{box-shadow:none} .twk-chip svg{position:absolute;top:6px;left:6px;width:13px;height:13px; filter:drop-shadow(0 1px 1px rgba(0,0,0,.3))}`;
// ── useTweaks ───────────────────────────────────────────────────────────────// Single source of truth for tweak values. setTweak persists via the host// (__edit_mode_set_keys → host rewrites the EDITMODE block on disk).function useTweaks(defaults) { const [values, setValues] = React.useState(defaults); // Accepts either setTweak('key', value) or setTweak({ key: value, ... }) so a // useState-style call doesn't write a "[object Object]" key into the persisted // JSON block. const setTweak = React.useCallback((keyOrEdits, val) => { const edits = typeof keyOrEdits === 'object' && keyOrEdits !== null ? keyOrEdits : { [keyOrEdits]: val }; setValues((prev) => ({ ...prev, ...edits })); window.parent.postMessage({ type: '__edit_mode_set_keys', edits }, '*'); // Same-window signal so in-page listeners (deck-stage rail thumbnails) // can react — the parent message only reaches the host, not peers. window.dispatchEvent(new CustomEvent('tweakchange', { detail: edits })); }, []); return [values, setTweak];}
// ── TweaksPanel ─────────────────────────────────────────────────────────────// Floating shell. Registers the protocol listener BEFORE announcing// availability — if the announce ran first, the host's activate could land// before our handler exists and the toolbar toggle would silently no-op.// The close button posts __edit_mode_dismissed so the host's toolbar toggle// flips off in lockstep; the host echoes __deactivate_edit_mode back which// is what actually hides the panel.function TweaksPanel({ title = 'Tweaks', children }) { const [open, setOpen] = React.useState(false); const dragRef = React.useRef(null); const offsetRef = React.useRef({ x: 16, y: 16 }); const PAD = 16;
const clampToViewport = React.useCallback(() => { const panel = dragRef.current; if (!panel) return; const w = panel.offsetWidth, h = panel.offsetHeight; const maxRight = Math.max(PAD, window.innerWidth - w - PAD); const maxBottom = Math.max(PAD, window.innerHeight - h - PAD); offsetRef.current = { x: Math.min(maxRight, Math.max(PAD, offsetRef.current.x)), y: Math.min(maxBottom, Math.max(PAD, offsetRef.current.y)), }; panel.style.right = offsetRef.current.x + 'px'; panel.style.bottom = offsetRef.current.y + 'px'; }, []);
React.useEffect(() => { if (!open) return; clampToViewport(); if (typeof ResizeObserver === 'undefined') { window.addEventListener('resize', clampToViewport); return () => window.removeEventListener('resize', clampToViewport); } const ro = new ResizeObserver(clampToViewport); ro.observe(document.documentElement); return () => ro.disconnect(); }, [open, clampToViewport]);
React.useEffect(() => { const onMsg = (e) => { const t = e?.data?.type; if (t === '__activate_edit_mode') setOpen(true); else if (t === '__deactivate_edit_mode') setOpen(false); }; window.addEventListener('message', onMsg); window.parent.postMessage({ type: '__edit_mode_available' }, '*'); return () => window.removeEventListener('message', onMsg); }, []);
const dismiss = () => { setOpen(false); window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*'); };
const onDragStart = (e) => { const panel = dragRef.current; if (!panel) return; const r = panel.getBoundingClientRect(); const sx = e.clientX, sy = e.clientY; const startRight = window.innerWidth - r.right; const startBottom = window.innerHeight - r.bottom; const move = (ev) => { offsetRef.current = { x: startRight - (ev.clientX - sx), y: startBottom - (ev.clientY - sy), }; clampToViewport(); }; const up = () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); }; window.addEventListener('mousemove', move); window.addEventListener('mouseup', up); };
// data-om-starter: inert presence marker — Claude Design's starter-usage // probe reads it. The closed panel renders nothing, so the marker rides // the <html> element as an attribute instead of a rendered node — zero // elements added, so page CSS (even structural selectors like // :nth-child) can never observe it. It records that the page WIRES a // tweaks panel, whether or not the panel is open. Keep this effect. React.useEffect(() => { document.documentElement.setAttribute('data-om-starter', 'tweaks-panel'); return () => document.documentElement.removeAttribute('data-om-starter'); }, []);
if (!open) return null; return ( <> <style>{__TWEAKS_STYLE}</style> <div ref={dragRef} className="twk-panel" data-omelette-chrome="" style={{ right: offsetRef.current.x, bottom: offsetRef.current.y }}> <div className="twk-hd" onMouseDown={onDragStart}> <b>{title}</b> <button className="twk-x" aria-label="Close tweaks" onMouseDown={(e) => e.stopPropagation()} onClick={dismiss}>✕</button> </div> <div className="twk-body"> {children} </div> </div> </> );}
// ── Layout helpers ──────────────────────────────────────────────────────────
function TweakSection({ label, children }) { return ( <> <div className="twk-sect">{label}</div> {children} </> );}
function TweakRow({ label, value, children, inline = false }) { return ( <div className={inline ? 'twk-row twk-row-h' : 'twk-row'}> <div className="twk-lbl"> <span>{label}</span> {value != null && <span className="twk-val">{value}</span>} </div> {children} </div> );}
// ── Controls ────────────────────────────────────────────────────────────────
function TweakSlider({ label, value, min = 0, max = 100, step = 1, unit = '', onChange }) { return ( <TweakRow label={label} value={`${value}${unit}`}> <input type="range" className="twk-slider" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} /> </TweakRow> );}
function TweakToggle({ label, value, onChange }) { return ( <div className="twk-row twk-row-h"> <div className="twk-lbl"><span>{label}</span></div> <button type="button" className="twk-toggle" data-on={value ? '1' : '0'} role="switch" aria-checked={!!value} onClick={() => onChange(!value)}><i /></button> </div> );}
function TweakRadio({ label, value, options, onChange }) { const trackRef = React.useRef(null); const [dragging, setDragging] = React.useState(false); // The active value is read by pointer-move handlers attached for the lifetime // of a drag — ref it so a stale closure doesn't fire onChange for every move. const valueRef = React.useRef(value); valueRef.current = value;
// Segments wrap mid-word once per-segment width runs out. The track is // ~248px (280 panel − 28 body pad − 4 seg pad), each button loses 12px // to its own padding, and 11.5px system-ui averages ~6.3px/char — so 2 // options fit ~16 chars each, 3 fit ~10. Past that (or >3 options), fall // back to a dropdown rather than wrap. const labelLen = (o) => String(typeof o === 'object' ? o.label : o).length; const maxLen = options.reduce((m, o) => Math.max(m, labelLen(o)), 0); const fitsAsSegments = maxLen <= ({ 2: 16, 3: 10 }[options.length] ?? 0); if (!fitsAsSegments) { // <select> emits strings — map back to the original option value so the // fallback stays type-preserving (numbers, booleans) like the segment path. const resolve = (s) => { const m = options.find((o) => String(typeof o === 'object' ? o.value : o) === s); return m === undefined ? s : typeof m === 'object' ? m.value : m; }; return <TweakSelect label={label} value={value} options={options} onChange={(s) => onChange(resolve(s))} />; } const opts = options.map((o) => (typeof o === 'object' ? o : { value: o, label: o })); const idx = Math.max(0, opts.findIndex((o) => o.value === value)); const n = opts.length;
const segAt = (clientX) => { const r = trackRef.current.getBoundingClientRect(); const inner = r.width - 4; const i = Math.floor(((clientX - r.left - 2) / inner) * n); return opts[Math.max(0, Math.min(n - 1, i))].value; };
const onPointerDown = (e) => { setDragging(true); const v0 = segAt(e.clientX); if (v0 !== valueRef.current) onChange(v0); const move = (ev) => { if (!trackRef.current) return; const v = segAt(ev.clientX); if (v !== valueRef.current) onChange(v); }; const up = () => { setDragging(false); window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); }; window.addEventListener('pointermove', move); window.addEventListener('pointerup', up); };
return ( <TweakRow label={label}> <div ref={trackRef} role="radiogroup" onPointerDown={onPointerDown} className={dragging ? 'twk-seg dragging' : 'twk-seg'}> <div className="twk-seg-thumb" style={{ left: `calc(2px + ${idx} * (100% - 4px) / ${n})`, width: `calc((100% - 4px) / ${n})` }} /> {opts.map((o) => ( <button key={o.value} type="button" role="radio" aria-checked={o.value === value}> {o.label} </button> ))} </div> </TweakRow> );}
function TweakSelect({ label, value, options, onChange }) { return ( <TweakRow label={label}> <select className="twk-field" value={value} onChange={(e) => onChange(e.target.value)}> {options.map((o) => { const v = typeof o === 'object' ? o.value : o; const l = typeof o === 'object' ? o.label : o; return <option key={v} value={v}>{l}</option>; })} </select> </TweakRow> );}
function TweakText({ label, value, placeholder, onChange }) { return ( <TweakRow label={label}> <input className="twk-field" type="text" value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} /> </TweakRow> );}
function TweakNumber({ label, value, min, max, step = 1, unit = '', onChange }) { const clamp = (n) => { if (min != null && n < min) return min; if (max != null && n > max) return max; return n; }; const startRef = React.useRef({ x: 0, val: 0 }); const onScrubStart = (e) => { e.preventDefault(); startRef.current = { x: e.clientX, val: value }; const decimals = (String(step).split('.')[1] || '').length; const move = (ev) => { const dx = ev.clientX - startRef.current.x; const raw = startRef.current.val + dx * step; const snapped = Math.round(raw / step) * step; onChange(clamp(Number(snapped.toFixed(decimals)))); }; const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); }; window.addEventListener('pointermove', move); window.addEventListener('pointerup', up); }; return ( <div className="twk-num"> <span className="twk-num-lbl" onPointerDown={onScrubStart}>{label}</span> <input type="number" value={value} min={min} max={max} step={step} onChange={(e) => onChange(clamp(Number(e.target.value)))} /> {unit && <span className="twk-num-unit">{unit}</span>} </div> );}
// Relative-luminance contrast pick — checkmarks drawn over a swatch need to// read on both #111 and #fafafa without per-option configuration. Hex input// only (#rgb / #rrggbb); named or rgb()/hsl() colors fall through to "light".function __twkIsLight(hex) { const h = String(hex).replace('#', ''); const x = h.length === 3 ? h.replace(/./g, (c) => c + c) : h.padEnd(6, '0'); const n = parseInt(x.slice(0, 6), 16); if (Number.isNaN(n)) return true; const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255; return r * 299 + g * 587 + b * 114 > 148000;}
const __TwkCheck = ({ light }) => ( <svg viewBox="0 0 14 14" aria-hidden="true"> <path d="M3 7.2 5.8 10 11 4.2" fill="none" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" stroke={light ? 'rgba(0,0,0,.78)' : '#fff'} /> </svg>);
// TweakColor — curated color/palette picker. Each option is either a single// hex string or an array of 1-5 hex strings; the card adapts — a lone color// renders solid, a palette renders colors[0] as the hero (left ~2/3) with the// rest stacked in a sharp column on the right. onChange emits the// option in the shape it was passed (string stays string, array stays array).// Without options it falls back to the native color input for back-compat.function TweakColor({ label, value, options, onChange }) { if (!options || !options.length) { return ( <div className="twk-row twk-row-h"> <div className="twk-lbl"><span>{label}</span></div> <input type="color" className="twk-swatch" value={value} onChange={(e) => onChange(e.target.value)} /> </div> ); } // Native <input type=color> emits lowercase hex per the HTML spec, so // compare case-insensitively. String() guards JSON.stringify(undefined), // which returns the primitive undefined (no .toLowerCase). const key = (o) => String(JSON.stringify(o)).toLowerCase(); const cur = key(value); return ( <TweakRow label={label}> <div className="twk-chips" role="radiogroup"> {options.map((o, i) => { const colors = Array.isArray(o) ? o : [o]; const [hero, ...rest] = colors; const sup = rest.slice(0, 4); const on = key(o) === cur; return ( <button key={i} type="button" className="twk-chip" role="radio" aria-checked={on} data-on={on ? '1' : '0'} aria-label={colors.join(', ')} title={colors.join(' · ')} style={{ background: hero }} onClick={() => onChange(o)}> {sup.length > 0 && ( <span> {sup.map((c, j) => <i key={j} style={{ background: c }} />)} </span> )} {on && <__TwkCheck light={__twkIsLight(hero)} />} </button> ); })} </div> </TweakRow> );}
function TweakButton({ label, onClick, secondary = false }) { return ( <button type="button" className={secondary ? 'twk-btn secondary' : 'twk-btn'} onClick={onClick}>{label}</button> );}
Object.assign(window, { useTweaks, TweaksPanel, TweakSection, TweakRow, TweakSlider, TweakToggle, TweakRadio, TweakSelect, TweakText, TweakNumber, TweakColor, TweakButton,});.gitattributes+2
.thumbnailAdded
Kugguk Labs Readme.dc.htmlAdded+39
RCV Local.dc.htmlAdded+333
README.md+50-10
animations-v3.jsxAdded+1347
assets/zebra-k2.pngAdded

Large File Pointer Details
- SHA256: c6aa71a0100d1c31417b548a7f8e4790ff7a462cb4b695e9e78f45e97f1b1d40
- Pointer size: 132 Bytes
- Size of remote file: 8.02 MB
kugguk-piece.jsxAdded+314
support.jsAdded+1911
tweaks-panel.jsxAdded+553
uploads/Gemini_Generated_Image_3ltthj3ltthj3ltt.pngAdded

Large File Pointer Details
- SHA256: c6aa71a0100d1c31417b548a7f8e4790ff7a462cb4b695e9e78f45e97f1b1d40
- Pointer size: 132 Bytes
- Size of remote file: 8.02 MB