← Files Wish CabinetARCHIVED FILE

assets/widget.js

15.4 KB · Dec 1, 2026 · 00:18 UTC

↓ Download file

(()=>{
'use strict';
const $=id=>document.getElementById(id),KEY='arkheos-wish-cabinet-v1';
const TITLES=['Clock','Shelf','Stars'],IDS=['clock','shelf','stars'],NAMES={shell:'Shell',acorn:'Acorn',boat:'Paper boat'},SYMBOLS={shell:'shell',acorn:'acorn',boat:'paper-boat'};
const STARTING_DESIGN = {"occasion":"birthday","name":"Avery","message":"A little adventure, made just for you.","target":"4:30"};
const occasions = {
 birthday: ['Happy','Birthday','cake','Illustration of a candlelit cake','Tea, cake & a little celebration','Here’s to all the doors you’ll open.'],
 thanks: ['Thank','You','sprig','Illustration of a flowering sprig','A little tea to say thank you','With gratitude, folded into every corner.'],
 cheers: ['Bravo,','you did it!','compass','Illustration of a compass rose','A toast to your next adventure','May your next adventure be just as sweet.']
};
function isTime(value) { return typeof value === 'string' && /^(?:1[0-2]|[1-9]):(?:00|15|30|45)$/.test(value); }
function validDesign(d) {
 return d && typeof d === 'object' && Object.hasOwn(occasions, d.occasion) && isTime(d.target)
  && typeof d.name === 'string' && d.name.length <= 60 && typeof d.message === 'string' && d.message.length <= 600;
}
function designOf(v) { return {occasion:v.occasion,name:v.name,message:v.message,target:v.target}; }
const freshPuzzles=()=>({hour:12,minute:0,order:['acorn','boat','shell'],rings:[1,2,3],solved:[false,false,false],opened:false});
const defaults=()=>({...designOf(STARTING_DESIGN),receiving:false,open:false,gift:false,cabinet:freshPuzzles()});
const copy=o=>JSON.parse(JSON.stringify(o)),numberIn=(v,a,b)=>Number.isInteger(v)&&v>=a&&v<=b;
function puzzleClean(p,target){
const q=freshPuzzles();if(!p||typeof p!=='object'||Array.isArray(p))return q;
if(numberIn(p.hour,1,12))q.hour=p.hour;
if([0,15,30,45].includes(p.minute))q.minute=p.minute;
if(Array.isArray(p.order)&&p.order.length===3&&new Set(p.order).size===3&&p.order.every(x=>Object.prototype.hasOwnProperty.call(NAMES,x)))q.order=p.order.slice();
if(Array.isArray(p.rings)&&p.rings.length===3&&p.rings.every(x=>numberIn(x,0,3)))q.rings=p.rings.slice();
if(Array.isArray(p.solved))q.solved=[p.solved[0]===true&&(q.hour+':'+String(q.minute).padStart(2,'0'))===target,p.solved[1]===true&&q.order.join(',')==='shell,acorn,boat',p.solved[2]===true&&q.rings.every(x=>x===0)];
q.opened=p.opened===true&&q.solved.every(Boolean);return q;
}
function clean(v){
if(!v||typeof v!=='object'||Array.isArray(v))return null;
const target=isTime(v.target)?v.target:STARTING_DESIGN.target;
const cabinet=puzzleClean(v.cabinet,target);
return {occasion:Object.hasOwn(occasions,v.occasion)?v.occasion:STARTING_DESIGN.occasion,target,receiving:v.receiving===true,name:typeof v.name==='string'?v.name.slice(0,60):defaults().name,message:typeof v.message==='string'?v.message.slice(0,600):defaults().message,open:v.open===true,gift:cabinet.opened,cabinet};
}
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
let s=defaults(),history=[],editGroup=null,generation=0,saveChain=Promise.resolve(),restoreEpoch=0,selected=null;
const feedback=['The little brass door is shut.','The shelf is waiting for its story.','The paper sky has a secret seam.'];
const baseFeedback=feedback.slice();
function time(){return s.cabinet.hour+':'+String(s.cabinet.minute).padStart(2,'0');}
const directionSets=[
['north & southeast','east & southwest','south & northwest','west & northeast'],
['west & south','north & west','east & north','south & east'],
['north & east','east & south','south & west','west & north']
];
function render(syncFields=true){
if ($('gift-code').dataset.generated && $('gift-code').dataset.generated !== JSON.stringify(designOf(s))) {
 $('gift-code').value='';$('copy-code').disabled=true;$('code-status').textContent='Your gift changed. Make a new code to include the edits.';delete $('gift-code').dataset.generated;
}
const p=s.cabinet,all=p.solved.every(Boolean),count=p.solved.filter(Boolean).length;
const o=occasions[s.occasion];
$('greeting-top').textContent=o[0];$('greeting-bottom').textContent=o[1];
$('cover-emblem').setAttribute('href','#'+o[2]);$('cover-art').setAttribute('aria-label',o[3]);
$('invitation-copy').textContent=o[4];$('invitation-time').textContent='At '+s.target+'.';$('signoff').textContent=o[5];
$('personalize').hidden=s.receiving;
if (s.receiving) { $('editor').hidden=true; $('personalize').setAttribute('aria-expanded','false'); }
if(syncFields){$('occasion').value=s.occasion;$('chosen-time').value=s.target;}
$('book').classList.toggle('open',s.open);$('cover').hidden=s.open;$('inside').hidden=!s.open;
$('cover-name').textContent=s.name.trim()||'you';$('dear').textContent='Dear '+(s.name.trim()||'you')+',';
$('letter').textContent=p.opened?s.message:'';
$('fold').textContent=s.open?'Fold card closed':'Unfold the room';$('fold').setAttribute('aria-expanded',String(s.open));
$('hour-hand').setAttribute('transform','rotate('+((p.hour%12)*30+p.minute*.5)+' 90 91)');
$('minute-hand').setAttribute('transform','rotate('+(p.minute*6)+' 90 91)');
$('clock-svg-title').textContent='Clock showing '+time();$('clock-readout').textContent=time();
$('clock-door').toggleAttribute('hidden',p.solved[0]);
for(let i=0;i<3;i++){
$('token-'+i).classList.toggle('found',p.solved[i]);$('token-'+i).setAttribute('aria-label',TITLES[i]+' key '+(p.solved[i]?'found':'missing'));
$(IDS[i]+'-object').classList.toggle('solved',p.solved[i]);$(IDS[i]+'-key').toggleAttribute('hidden',!p.solved[i]);
$(IDS[i]+'-feedback').textContent=p.solved[i]?TITLES[i]+' key released.':feedback[i];
$('ring-'+i).setAttribute('transform','rotate('+(p.rings[i]*90)+')');
$('ring-label-'+i).textContent='Now: '+directionSets[i][p.rings[i]];
$('rotate-'+i).disabled=p.solved[2];$('rotate-'+i).setAttribute('aria-label','Turn '+['outer','middle','inner'][i]+' ring clockwise one quarter turn. Stars now point '+directionSets[i][p.rings[i]]);
const item=p.order[i];$('keepsake-use-'+i).setAttribute('href','#'+SYMBOLS[item]);$('keepsake-label-'+i).textContent=NAMES[item];
$('keepsake-'+i).setAttribute('aria-pressed',String(selected===i));$('keepsake-'+i).setAttribute('aria-label',NAMES[item]+', position '+(i+1)+(selected===i?', selected. Choose another keepsake to swap.':'. Choose to swap.'));$('keepsake-'+i).disabled=p.solved[1];
}
$('key-count').textContent=count+' of 3 keys found';
for(const id of ['hour-minus','hour-plus','minute-minus','minute-plus'])$(id).disabled=p.solved[0];
for(let i=0;i<3;i++){$('check-'+IDS[i]).disabled=p.solved[i];$('check-'+IDS[i]).textContent=p.solved[i]?'Key released':(['Try the time','Check the shelf','Pin the stars'][i]);}
$('drawer-label').hidden=p.solved[1];
$('swap-instruction').textContent=p.solved[1]?'The keepsakes tell their story. The drawer slides open.':selected===null?'Choose two keepsakes to swap their places, from left to right.':NAMES[p.order[selected]]+' selected. Choose another keepsake to swap, or choose it again to cancel.';
$('gift').setAttribute('aria-disabled',String(!all));$('gift').setAttribute('aria-expanded',String(p.opened));$('gift').classList.toggle('locked',!all);$('gift').classList.toggle('ready',all&&!p.opened);
$('gift-label').textContent=p.opened?'The secret was a wish.':all?'All three keys are yours.':'Three keys turn together';
$('present-action').textContent=p.opened?'Your present is open':all?'Open your present':'Find all three keys to open';
$('lock-status').textContent=p.opened?'A little adventure, earned with curiosity.':all?'Three locks turn. A ribbon loosens.':TITLES.filter((_,i)=>!p.solved[i]).join(' · ')+' '+(count===2?'key still needed':'keys still needed');
$('surprise').hidden=!p.opened;$('undo').disabled=history.length===0;
if(syncFields){$('recipient').value=s.name;$('message').value=s.message;}
}
function snapshot(){if(!history.length||!equal(history[history.length-1],s)){history.push(copy(s));if(history.length>40)history.shift();}}
function persist(){
const stamp=++generation,payload={kind:KEY,version:1,card:copy(s),history:history.map(copy)};
$('status').textContent='Saving your little room…';
saveChain=saveChain.catch(()=>{}).then(async()=>{if(stamp!==generation)return;try{
if(!window.WidgetCanvas||typeof WidgetCanvas.setState!=='function')throw Error('No save bridge');
await WidgetCanvas.setState(payload);if(stamp===generation)$('status').textContent='Your room and words are saved.';
}catch(e){if(stamp===generation)$('status').textContent='Saving is unavailable. Keep this room open to retain your progress.';}});
}
function change(fn,options={}){
const next=copy(s);fn(next);next.gift=next.cabinet.opened;
if(equal(next,s))return false;
editGroup=null;snapshot();s=next;if(!options.keepSelection)selected=null;render();persist();return true;
}
function restore(v){
if(!v||v.kind!==KEY||v.version!==1)return false;const next=clean(v.card);if(!next)return false;
++generation;++restoreEpoch;editGroup=null;selected=null;s=next;
history=Array.isArray(v.history)?v.history.slice(-40).map(clean).filter(Boolean):[];
while(history.length&&equal(history[history.length-1],s))history.pop();
feedback.splice(0,3,...baseFeedback);render();$('status').textContent='Welcome back. Your room and note are restored.';return true;
}
$('fold').onclick=()=>change(next=>{next.open=!next.open;});
for(const [id,field,delta,mod,start] of [['hour-minus','hour',-1,12,1],['hour-plus','hour',1,12,1],['minute-minus','minute',-15,60,0],['minute-plus','minute',15,60,0]]){
$(id).onclick=()=>{if(s.cabinet.solved[0])return;feedback[0]=baseFeedback[0];change(next=>{next.cabinet[field]=((next.cabinet[field]-start+delta)%mod+mod)%mod+start;});};
}
for(let i=0;i<3;i++){
$('rotate-'+i).onclick=()=>{if(s.cabinet.solved[2])return;feedback[2]=baseFeedback[2];change(next=>{next.cabinet.rings[i]=(next.cabinet.rings[i]+1)%4;});};
$('keepsake-'+i).onclick=()=>{if(s.cabinet.solved[1])return;if(selected===i){selected=null;render(false);return;}if(selected===null){selected=i;render(false);return;}
const first=selected;feedback[1]=baseFeedback[1];change(next=>{const row=next.cabinet.order;[row[first],row[i]]=[row[i],row[first]];});};
}
function solve(i){
const p=s.cabinet;if(p.solved[i])return;
const correct=[time()===s.target,p.order.join(',')==='shell,acorn,boat',p.rings.every(x=>x===0)][i];
if(!correct){feedback[i]=['Not quite. Read the time written on the invitation.','Not quite. Read the note from left to right.','Not quite. Match every star to a hollow gold circle.'][i];render(false);return;}
change(next=>{next.cabinet.solved[i]=true;});
}
$('check-clock').onclick=()=>solve(0);$('check-shelf').onclick=()=>solve(1);$('check-stars').onclick=()=>solve(2);
$('gift').onclick=()=>{if(!s.cabinet.solved.every(Boolean)){$('status').textContent='The present needs all three keys. '+(3-s.cabinet.solved.filter(Boolean).length)+' still to find.';return;}if(s.cabinet.opened)return;change(next=>{next.cabinet.opened=true;});};
function editor(open){$('editor').hidden=!open;$('personalize').setAttribute('aria-expanded',String(open));editGroup=null;if(open)$('recipient').focus();else $('personalize').focus();}
$('personalize').onclick=()=>editor($('editor').hidden);$('done').onclick=()=>editor(false);
$('editor').addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();editor(false);}});
for(const [id,key] of [['recipient','name'],['message','message']]){
$(id).addEventListener('focus',()=>{editGroup=null;});
$(id).addEventListener('input',e=>{const value=e.target.value.slice(0,key==='name'?60:600);if(value===s[key])return;if(editGroup!==id){snapshot();editGroup=id;}s[key]=value;
if(history.length&&equal(history[history.length-1],s)){history.pop();editGroup=null;}render(false);persist();});
$(id).addEventListener('blur',()=>{editGroup=null;});
}
$('undo').onclick=()=>{while(history.length&&equal(history[history.length-1],s))history.pop();if(!history.length){render(false);return;}editGroup=null;selected=null;s=history.pop();feedback.splice(0,3,...baseFeedback);render();persist();};
$('reset').onclick=()=>{selected=null;feedback.splice(0,3,...baseFeedback);const changed=change(next=>{next.cabinet=freshPuzzles();});if(!changed)render(false);};
for(let hour=1;hour<=12;hour++) for(const minute of ['00','15','30','45']){
 const option=document.createElement('option');option.value=hour+':'+minute;option.textContent=option.value;$('chosen-time').appendChild(option);
}
$('occasion').addEventListener('change', e=>{if(Object.hasOwn(occasions,e.target.value))change(next=>{next.occasion=e.target.value;});});
$('chosen-time').addEventListener('change', e=>{
 const target=e.target.value;
 if(!isTime(target)||target===s.target)return;
 feedback[0]=baseFeedback[0];change(next=>{next.target=target;next.cabinet.solved[0]=false;next.cabinet.opened=false;});
});
$('context-design').onclick=async()=>{
 try{
  if(!window.WidgetCanvas||typeof WidgetCanvas.setContext!=='function')throw Error('bridge');
  await WidgetCanvas.setContext({kind:'wish-cabinet-design',design:designOf(s)});
  $('context-note').textContent='Design attached to this chat. Tell Wish Cabinet what to change.';
 }catch{$('context-note').textContent='Chat sharing is unavailable here. Copy a gift code if you want to keep the design.';}
};
const prefix='WISH1.';
function giftCode(d){
 const json=JSON.stringify(designOf(d)),bytes=new TextEncoder().encode(json);
 return prefix+btoa(String.fromCharCode(...bytes)).replace(/=+$/,'').replace(/\+/g,'-').replace(/\//g,'_');
}
function readCode(value){
 const code=value.trim();
 if(!code.startsWith(prefix)||code.length>8192)throw Error('code');
 const raw=code.slice(prefix.length);
 if(!/^[A-Za-z0-9_-]+$/.test(raw))throw Error('code');
 const bin=atob(raw.replace(/-/g,'+').replace(/_/g,'/'));
 const d=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Uint8Array.from(bin,c=>c.charCodeAt(0))));
 if(!validDesign(d))throw Error('design');
 return designOf(d);
}
$('make-code').onclick=()=>{
 $('gift-code').dataset.generated=JSON.stringify(designOf(s));$('gift-code').value=giftCode(s);$('copy-code').disabled=false;
 $('gift-code').focus();$('gift-code').select();$('code-status').textContent='Code ready. Give it to the recipient to open in Wish Cabinet.';
};
$('gift-code').addEventListener('input',()=>{delete $('gift-code').dataset.generated;$('copy-code').disabled=!$('gift-code').value.trim();$('code-status').textContent='';});
$('copy-code').onclick=async()=>{
 $('gift-code').focus();$('gift-code').select();
 try{await navigator.clipboard.writeText($('gift-code').value);$('code-status').textContent='Gift code copied.';}
 catch{$('code-status').textContent='Code selected. Use your device’s Copy command.';}
};
$('import-code').onclick=()=>{
 let d;try{d=readCode($('gift-code').value);}catch{$('code-status').textContent='This code could not be opened. Paste the full WISH1 code.';return;}
 feedback.splice(0,3,...baseFeedback);change(next=>Object.assign(next,defaults(),d,{receiving:true}));
 $('gift-code').value='';$('copy-code').disabled=true;$('code-status').textContent='Gift ready. Open the room to find your note.';$('gift-tools').open=false;$('fold').focus();
};
render();
window.addEventListener('widgetcanvas:restore',e=>restore(e.detail));
async function loadStartup(){
const startupGeneration=generation;
try{if(!window.WidgetCanvas)return;const saved=await WidgetCanvas.getState();if(generation===startupGeneration)restore(saved);}
catch(e){if(generation===startupGeneration)$('status').textContent='Your room is ready. Saved progress could not be loaded.';}
}
try{if(window.WidgetCanvas){WidgetCanvas.setControlsPosition('top-right');WidgetCanvas.setResetEnabled(false);WidgetCanvas.setSharingEnabled(false);}}
catch(e){$('status').textContent='Your room is ready. Saving is unavailable.';}
loadStartup();
})();

SHA-256: fce27f688cbd4bf72c71f6a0f4182a01125f19b5ab066eae70eb517002459e2d