Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
26 lines (26 loc) · 14.2 KB
/
Copy pathapp.js
File metadata and controls
26 lines (26 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import {defaults,themes,localDay,scenePrompt,shareText,escapeHTML as esc} from './core.js';
const $=s=>document.querySelector(s), main=$('#main');
let db, prefs={...defaults}, pieces=[],current,draft={}, ready=false,busy=false;
const sample=()=>({id:'example',day:localDay(),theme:'Change',...themes.Change,image:'assets/before-you-are-ready.png',kind:'example',note:'',response:'',look:'',fit:'',why:'A pre-made illustration of the concept, not a personalized reading. Your own pieces start in Ask, then see.'});
function notify(text){$('#notice').textContent=text;clearTimeout(notify.timer);notify.timer=setTimeout(()=>$('#notice').textContent='',6500);}
function transaction(mode,action){return new Promise((resolve,reject)=>{if(!db)return reject(new Error('Storage unavailable'));const tx=db.transaction('records',mode);const req=action(tx.objectStore('records'));tx.oncomplete=()=>resolve(req.result);tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);});}
async function put(key,value){await transaction('readwrite',s=>s.put(value,key));}
async function get(key){return transaction('readonly',s=>s.get(key));}
async function initialize(){try{db=await new Promise((resolve,reject)=>{const req=indexedDB.open('innerworld-v1',1);req.onupgradeneeded=()=>req.result.createObjectStore('records');req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);});prefs={...defaults,...await get('preferences')};pieces=await get('pieces')||[];current=await get('current');ready=!!await get('onboarded');}catch{notify('Device storage is unavailable. You can explore, but saving will not work.');}if(!current||current.day!==localDay())current=pieces.find(p=>p.day===localDay())||sample();render();if(!ready)openSetup();}
function openSetup(){const f=$('#setup-form');for(const name of ['medium','palette'])for(const input of f.elements[name])input.checked=input.value===prefs[name];f.elements.motifs.value=prefs.motifs;f.elements.symbolic.checked=prefs.symbolic;$('#setup').showModal();}
$('#preferences').onclick=openSetup;$('#privacy').onclick=()=>$('#about').showModal();document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>document.getElementById(b.dataset.close).close());
$('#setup-form').onsubmit=async e=>{e.preventDefault();const f=new FormData(e.target);const next={medium:f.get('medium'),palette:f.get('palette'),motifs:f.get('motifs').trim(),symbolic:f.has('symbolic')};try{await put('preferences',next);await put('onboarded',true);prefs=next;ready=true;$('#setup').close();notify('Your visual language is saved. It will shape your next prompt.');}catch{notify('Preferences could not be saved. Check browser storage permissions.');}};
function render(){const route=location.hash||'#today';document.querySelectorAll('nav a').forEach(a=>{a.removeAttribute('aria-current');if(a.getAttribute('href')===route)a.setAttribute('aria-current','page');});$('#count').textContent=pieces.length;if(route==='#studio')studio();else if(route==='#folio')folio();else today();}
window.addEventListener('hashchange',()=>{render();main.focus();});
function group(key,values){return `<div class="chips" role="group" aria-label="${key==='look'?'Visual preference':'Emotional fit'}">${values.map(v=>`<button class="chip" data-feedback="${key}" data-value="${esc(v)}" aria-pressed="${current[key]===v}">${v}</button>`).join('')}</div>`;}
function today(){main.innerHTML=`<div class="topline"><p class="eyebrow">YOUR INNER WEATHER</p><p class="eyebrow">${new Date().toLocaleDateString(undefined,{month:'long',day:'numeric',year:'numeric'})}</p></div><section class="daily"><figure class="art"><img src="${esc(current.image)}" alt="${esc(current.kind==='example'?themes.Change.scene:current.prompt)}"><figcaption><span>${current.kind==='example'?'01 / CONCEPT ARTWORK':'YOUR VISUAL SELF-PORTRAIT'}</span><span>${current.kind==='example'?'Pre-made example · AI-created':'AI-created · Your direction'}</span></figcaption></figure><div class="copy"><p class="eyebrow">${esc(current.theme)} / ${current.kind==='example'?'AN INVITATION':'YOUR CHOSEN THEME'}</p><h1>${esc(current.title)}</h1><p class="quote">“${esc(current.line)}”</p><p>${current.kind==='example'?'An unfinished room. A door left open. This example explores the space between preparing and beginning.':`You chose ${esc(current.theme.toLowerCase())}. The scene is a creative starting point, not a conclusion about you.`}</p><details><summary>Why this?</summary><p class="small">${esc(current.why)}</p></details><div class="section-rule"><p class="eyebrow">ONE SMALL INVITATION</p><p class="prompt">${esc(current.invitation)}</p><label>Your response — kept on this device<textarea id="response" maxlength="3000" placeholder="One word, one line, or nothing at all.">${esc(current.response)}</textarea></label><p class="feedback-label">Do you like how this looks?</p>${group('look',['Yes','Not my taste'])}<p class="feedback-label">Does this reflect your experience?</p>${group('fit',['Yes','Not really','I see something different'])}<div class="actions"><button id="save" class="primary">${pieces.some(p=>p.id===current.id)?'Update in Folio':'Save to Folio'}</button><button id="revise" class="secondary">Reshape this</button></div><p class="small">${current.kind==='example'?'Ready for your own piece? Start with “Reshape this.”':'No need to agree. You can keep your own interpretation.'}</p></div></div></section>`;
$('#response').oninput=e=>{current.response=e.target.value;};document.querySelectorAll('[data-feedback]').forEach(b=>b.onclick=()=>{current[b.dataset.feedback]=b.dataset.value;document.querySelectorAll(`[data-feedback="${b.dataset.feedback}"]`).forEach(x=>x.setAttribute('aria-pressed',x===b));notify('Noted for this piece. Save to Folio to keep it.');});$('#save').onclick=saveCurrent;$('#revise').onclick=()=>{draft={theme:current.theme,note:current.note||'',prompt:current.prompt||scenePrompt(current.theme,prefs),title:current.title,line:current.line};location.hash='studio';};}
async function saveCurrent(){const saved={...current,id:current.id==='example'?crypto.randomUUID():current.id};const next=[saved,...pieces.filter(p=>p.id!==saved.id)];try{await put('pieces',next);await put('current',saved);pieces=next;current=saved;$('#count').textContent=pieces.length;$('#save').textContent='Update in Folio';notify('Saved to your device’s Folio.');}catch{notify('Could not save. Your piece is still open; export or free browser storage.');}}
function studio(){const theme=draft.theme||'Change',t=themes[theme];main.innerHTML=`<section class="studio"><div><p class="eyebrow">ASK, THEN SEE</p><h1>Make room for<br>your version.</h1><p>Start with a feeling. Turn it into a scene. You decide what it means.</p><form id="studio-form"><p class="steps">01 / YOUR EXPERIENCE</p><label>What does your life feel like lately?<textarea id="note" maxlength="3000" placeholder="I want to start something new, but I keep waiting…">${esc(draft.note||'')}</textarea></label><p class="small">This note stays here. It isn’t automatically sent to the image provider or analyzed.</p><label>A theme to explore<select id="theme">${Object.keys(themes).map(v=>`<option ${v===theme?'selected':''}>${esc(v)}</option>`).join('')}</select></label><p class="steps">02 / YOUR VISUAL CONCEPT</p><label>Scene prompt — review what will be sent<textarea id="scene" maxlength="2500" rows="7" required>${esc(draft.prompt||scenePrompt(theme,prefs))}</textarea></label><p class="small">The starting scene comes from your selected theme and visual preferences, not an analysis of your note. Change it until it fits. For revisions, describe the complete new scene.</p><label>Title<input id="title" maxlength="100" required value="${esc(draft.title||t.title)}"></label><label>Your accompanying line<input id="line" maxlength="250" value="${esc(draft.line||t.line)}"></label>${prefs.symbolic?'<p class="banner">Symbolic lens: a doorway might suggest possibility or distance. Which meaning, if either, is yours? This is an optional metaphor, not a chart reading.</p>':''}<label class="check"><input id="consent" type="checkbox" required> Send only this scene prompt to OpenAI to create an image.</label><button class="primary" id="generate" type="submit">Create my piece</button><p id="generation-status" role="status" class="small">Checking the image connection…</p><button class="plain" id="export-prompt" type="button">Download this prompt instead</button></form></div><aside class="sample"><img src="assets/before-you-are-ready.png" alt="A red chair in an unfinished room facing an ocean doorway"><p class="eyebrow">A SCENE, NOT A VERDICT</p><h3>Before You Are Ready</h3><p>The room could be a beginning. Or a place you’re ready to leave. The artwork doesn’t get the last word.</p><p class="small">Pre-made concept artwork. Your generated scene appears in Today when the image service is configured.</p></aside></section>`;
const capture=()=>draft={theme:$('#theme').value,note:$('#note').value,prompt:$('#scene').value,title:$('#title').value,line:$('#line').value};$('#studio-form').oninput=capture;$('#theme').onchange=()=>{const v=$('#theme').value;$('#scene').value=scenePrompt(v,prefs);$('#title').value=themes[v].title;$('#line').value=themes[v].line;capture();};$('#export-prompt').onclick=()=>{capture();download('innerworld-scene.txt',draft.prompt,'text/plain');};
fetch('/api/status').then(r=>r.ok?r.json():Promise.reject()).then(s=>{if(!$('#generation-status'))return;$('#generation-status').textContent=s.configured?'Image service connected. Generation may take a few minutes.':'Image service is not configured. Prompt editing and export work now; generation needs a server-side API key.';$('#generate').disabled=!s.configured;}).catch(()=>{if($('#generation-status')){$('#generation-status').textContent='Static preview: image generation needs the included local server and a server-side API key.';$('#generate').disabled=true;}});
$('#studio-form').onsubmit=async e=>{e.preventDefault();if(busy)return;capture();const request={...draft};busy=true;$('#generate').disabled=true;$('#generation-status').textContent='Creating your piece. Keep this tab open; this can take a few minutes.';try{const r=await fetch('/api/generate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:request.prompt}),signal:AbortSignal.timeout(240000)});const result=await r.json();if(!r.ok)throw new Error(result.error||'Generation failed');current={id:crypto.randomUUID(),day:localDay(),theme:request.theme,title:request.title,line:request.line,prompt:request.prompt,note:request.note,image:result.image,kind:'generated',response:'',look:'',fit:'',invitation:themes[request.theme].invitation,why:`Created from the scene prompt you approved for ${request.theme.toLowerCase()}. Your private note was not sent. The reflection is a theme-based invitation you can reinterpret.`};try{await put('current',current);}catch{notify('Image created, but not saved. Keep this tab open.');}draft={};location.hash='today';}catch(error){if($('#generation-status'))$('#generation-status').textContent=error.name==='TimeoutError'?'The request timed out. Your prompt is preserved; check the service before retrying.':error.message;}finally{busy=false;if($('#generate'))$('#generate').disabled=false;}};}
function download(name,content,type){const blob=content instanceof Blob?content:new Blob([content],{type});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),30000);}
function folio(){main.innerHTML=`<div class="folio-header"><div><p class="eyebrow">YOUR PRIVATE COLLECTION / ON THIS DEVICE</p><h1>Your Folio.</h1><p>Small pieces of a life. Yours to arrange and return to.</p></div><div class="actions"><button id="backup" class="secondary">Export backup</button><button id="print" class="secondary">Print chapter</button></div></div><label>Chapter title<input id="chapter" maxlength="100" placeholder="A season of beginnings"></label><p class="small">Printing includes artwork, titles and accompanying lines. Private notes and responses are excluded. Backups include private notes — store them securely.</p><div class="folio-grid">${pieces.map(p=>`<article class="folio-card"><img src="${esc(p.image)}" alt="${esc(p.title)}" loading="lazy"><p class="small">${esc(p.day)} / ${p.kind==='example'?'Example artwork':'AI-created'}</p><h3>${esc(p.title)}</h3><p>${esc(p.line)}</p><div class="actions"><button class="secondary" data-open="${p.id}">Revisit</button><button class="plain" data-share="${p.id}">Share</button><button class="plain" data-remove="${p.id}">Remove</button></div></article>`).join('')}</div>${pieces.length?'':'<div class="empty"><h2>Nothing to collect yet.</h2><p>Save a piece from Today. There’s no streak to keep.</p><a href="#today">Return to today’s piece</a></div>'}`;
get('chapter').then(v=>{if($('#chapter'))$('#chapter').value=v||'';}).catch(()=>{});$('#chapter').onchange=async e=>{try{await put('chapter',e.target.value);}catch{notify('Chapter title could not be saved.');}};$('#print').onclick=()=>window.print();$('#backup').onclick=()=>{if(!confirm('This backup includes private notes and reflections. Download it to this device?'))return;download('innerworld-private-backup.json',JSON.stringify({version:1,preferences:prefs,pieces,chapter:$('#chapter').value},null,2),'application/json');};document.querySelectorAll('[data-open]').forEach(b=>b.onclick=()=>{current=pieces.find(p=>p.id===b.dataset.open);location.hash='today';});document.querySelectorAll('[data-share]').forEach(b=>b.onclick=async()=>{const p=pieces.find(p=>p.id===b.dataset.share);if(!confirm('Share only this title and accompanying line? Your private note and response will not be included.'))return;try{if(navigator.share)await navigator.share({title:p.title,text:shareText(p)});else download('innerworld-share.txt',shareText(p),'text/plain');}catch(e){if(e.name!=='AbortError')notify('Sharing did not finish. Your piece is still saved.');}});document.querySelectorAll('[data-remove]').forEach(b=>b.onclick=async()=>{if(!confirm('Remove this piece from this device’s Folio? Export a backup first if you want to keep it.'))return;const next=pieces.filter(p=>p.id!==b.dataset.remove);try{await put('pieces',next);if(current.id===b.dataset.remove){current=sample();await put('current',current);}pieces=next;render();notify('Piece removed from this device’s Folio.');}catch{notify('Could not remove the piece.');}});}
initialize();