@kriya-ai/harness 2.1.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- var fn=n=>n.path.split(/[\\/]/).at(-1),jt=n=>n.label??fn(n),Pt=n=>String(n??"").toLocaleLowerCase();function Js(n,o,a){let r=Pt(a).split(/\s+/).filter(Boolean);if(!r.length)return n;let l=new Map;for(let u of o??[])l.set(u.asset,`${l.get(u.asset)??""} ${Pt(u.text)} ${Pt(u.heard)}`);return n.filter(u=>{let i=`${Pt(u.label)} ${Pt(fn(u))} ${l.get(u.id)??""}`;return r.every(p=>i.includes(p))})}var Qs={added:"Order added",recorded:"Date recorded",length:"Length",name:"Name"};function Ys(n,o){let a=[...n];return o==="recorded"?a.sort((r,l)=>(r.recorded??"\uFFFF").localeCompare(l.recorded??"\uFFFF")):o==="length"?a.sort((r,l)=>(l.facts?.duration??0)-(r.facts?.duration??0)):o==="name"?a.sort((r,l)=>jt(r).localeCompare(jt(l),void 0,{numeric:!0,sensitivity:"base"})):a}var Xs={none:"No groups",folder:"By folder",day:"By day recorded"},Fa=n=>n.path.split(/[\\/]/).slice(0,-1).join("/")||"Project folder",Ga=n=>n.recorded?n.recorded.slice(0,10):"No date";function Zs(n,o){if(o!=="folder"&&o!=="day")return[{name:null,assets:n}];let a=new Map;for(let r of n){let l=o==="folder"?Fa(r):Ga(r);a.set(l,[...a.get(l)??[],r])}return[...a].map(([r,l])=>({name:r,assets:l}))}var eo=60;function to(n,o,a,r=4){let l=0,u=n.length,i=n.length;for(let[h,c]of n.entries()){if(u===n.length&&l+c>o&&(u=h),l>=o+a){i=h;break}l+=c}let p=Math.max(0,u-r),g=Math.min(n.length,i+r),w=h=>h.reduce((c,v)=>c+v,0);return{start:p,end:g,before:w(n.slice(0,p)),after:w(n.slice(g))}}function t(n,o={},...a){let r=document.createElement(n);for(let[l,u]of Object.entries(o??{}))u==null||u===!1||(l.startsWith("on")?r.addEventListener(l.slice(2),u):l==="class"?r.className=u:l==="dataset"?Object.assign(r.dataset,u):u===!0?r.setAttribute(l,""):r.setAttribute(l,String(u)));for(let l of a.flat())l!=null&&l!==!1&&r.append(l instanceof Node?l:String(l));return r}var J=n=>(n.replaceChildren(),n);async function Y(n,o,a){let r=await fetch(o,{method:n,headers:a===void 0?{}:{"content-type":"application/json"},body:a===void 0?void 0:JSON.stringify(a),credentials:"same-origin"}),l=await r.json().catch(()=>({}));if(!r.ok){let u=new Error(l.message??`The Edit Host answered ${r.status}.`);throw u.status=r.status,u.value=l,u}return l}var Ne=n=>7056e5*n.d/n.n,no=(n,o)=>Math.floor(n/Ne(o)+1e-9),wt=(n,o)=>Math.round(no(n,o)*Ne(o));function _e(n,o){let a=Math.max(0,n)/7056e5,r=Math.floor(a/60),l=Math.floor(a%60),u=no(Math.max(0,n)-Math.floor(a)*7056e5,o);return`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}.${String(u).padStart(2,"0")}`}function so(n,{shift:o=!1,mod:a=!1}={}){if(a)return n==="z"||n==="Z"?{type:o?"redo":"undo"}:null;switch(n){case" ":return{type:"toggle"};case"k":case"K":return{type:"rate",rate:0};case"l":case"L":return{type:"faster"};case"j":case"J":return{type:"reverse"};case"ArrowRight":return{type:"step",frames:o?null:1,seconds:o?1:null};case"ArrowLeft":return{type:"step",frames:o?null:-1,seconds:o?-1:null};case"Home":return{type:"seek",t:0};case"1":return{type:"mode",mode:"direct"};case"2":return{type:"mode",mode:"edit"};case"3":return{type:"mode",mode:"finish"};case"/":return{type:"prompt"};case"s":case"S":return{type:"split"};case"Backspace":case"Delete":return{type:"delete"};case"i":case"I":return{type:"mark",edge:"in"};case"o":case"O":return{type:"mark",edge:"out"};default:return null}}function oo(n,o,{fps:a,duration:r}){let l=Math.max(0,r-Ne(a)),u=i=>Math.min(Math.max(0,Math.round(i)),l);switch(o.type){case"toggle":return{...n,rate:n.rate===0?1:0};case"rate":return{...n,rate:o.rate};case"faster":return{...n,rate:n.rate<=0?1:2};case"reverse":return{...n,rate:n.rate>=0?-1:-2};case"step":{let i=o.frames!==null?o.frames*Ne(a):o.seconds*7056e5;return{rate:0,t:u(wt(n.t,a)+i)}}case"seek":return{...n,t:u(o.t)};case"tick":{let i=u(o.t);return{t:i,rate:i===0&&n.rate<0||i===l&&n.rate>0?0:n.rate}}default:return n}}var Ka=(n,o,a)=>.2126*n+.7152*o+.0722*a;function Wa(n,o=128){let a=new Uint32Array(256),r=Array.from({length:o},()=>new Uint32Array(64)),{data:l,width:u,height:i}=n,p=Math.max(1,Math.floor(u*i/6e4));for(let g=0,w=0;w<u*i;w+=p,g=w*4){let h=Math.min(255,Math.round(Ka(l[g],l[g+1],l[g+2])));a[h]++,r[Math.min(o-1,Math.floor(w%u/u*o))][h>>2]++}return{histogram:a,waveform:r}}var _a={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you: a check failed",not_checked:"Not checked"},Ua={"QG-01":"Playable and to spec","QG-02":"Length","QG-03":"Sync","QG-04":"Round-trip speech","QG-05":"Cut hygiene","QG-06":"Loudness","QG-07":"Picture health","QG-08":"Layout","QG-09":"Legibility","QG-10":"Copy","QG-11":"Motion","QG-12":"Brief","QG-13":"Rights","QG-14":"Blind reviewer","QG-15":"Assembly","QG-16":"Reference fit"},Ha={passed:"Passed",failed:"Failed",not_checked:"Not checked",not_applicable:"Not applicable"};function qa(n){if(!n||!Array.isArray(n.gates)||!n.gates.length)return null;let o=n.gates.map(i=>({id:String(i.id),name:Ua[i.id]??String(i.id),status:i.status==="failed"&&i.severity==="note"?"note":String(i.status),said:i.status==="failed"&&i.severity==="note"?"Note":Ha[i.status]??String(i.status),message:typeof i.message=="string"?i.message:"",...Number.isFinite(i.at)&&i.at>=0&&i.status==="failed"?{at:i.at}:{}})),a=o.filter(i=>i.status==="passed").length,r=o.filter(i=>i.status==="failed").length,l=[...(n.repairs??[]).map(i=>`Repair round ${i.round}: ${(i.fixes??[]).map(p=>p.why??p.kind).join("; ")||"no fix"}${i.accepted?", kept":`, not kept${i.reason?` (${i.reason})`:""}`}.`),...(n.watch?.rounds??[]).map(i=>`Watch round ${i.round}: ${(i.fixes??[]).join(", ")||"no fix"}${i.kept?", kept":`, not kept${i.reason?` (${i.reason})`:""}`}.`)],u=o.length-a-r;return{summary:`${a} passed, ${r} failed${u?`, ${u} not checked or not applicable`:""}`,gates:o,repairs:l}}function ao({root:n,finalRoot:o,pixels:a,project:r,onAdjust:l=()=>{},scorecard:u=!1,head:i=()=>null,onShow:p=()=>{}}){let g=t("video",{class:"final-film",controls:!0,preload:"metadata",playsinline:!0,"aria-label":"The final cut"}),w=t("p",{class:"note",role:"status"}),h=t("select",{id:"final-pick",class:"field select","aria-label":"Which film",onchange:()=>x()}),c=t("a",{class:"btn primary",href:"#",download:"",hidden:!0},"Download"),v=[],y=z=>`/projects/${r().id}/renders/${z.job}`,E=z=>z?new Date(z).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";function x(){let z=v.find(ne=>String(ne.job)===h.value)??v[0];if(!z){g.removeAttribute("src"),g.hidden=!0,c.hidden=!0,h.hidden=!0,w.textContent="No film yet. Render a draft and the finished cut plays here, captions, look, music and sound included.";return}g.hidden=!1,h.hidden=v.length<2;let Q=y(z);g.getAttribute("src")!==Q&&(g.src=Q),c.hidden=!1,c.href=`${Q}?download=1`,c.setAttribute("download",z.name);let re=z.current?"This is your edit as it is now.":"Made before your latest changes: render a draft to see them.";w.textContent=`${re}${z.verdict?` ${_a[z.verdict]??z.verdict}.`:""}`,w.classList.toggle("stale",!z.current)}let f=0,P=0;async function L(){let z=++f,Q=(await Y("GET",`/projects/${r().id}/renders`)).renders;if(z!==f)return;let re=h.value;v=Q;let ne=v[0]?.job??0;J(h).append(...v.map(pe=>t("option",{value:String(pe.job)},`${pe.quality==="draft"?"Draft":"Master"} \xB7 ${E(pe.at)}${pe.current?" \xB7 current":""} \xB7 ${pe.name}`))),h.value=String(ne>P||!v.some(pe=>String(pe.job)===re)?ne:re),P=Math.max(P,ne),x()}o.append(t("section",{class:"panel final","aria-label":"Final cut"},t("h2",{},"Final cut"),g,w,t("div",{class:"row"},h,c,t("button",{type:"button",class:"btn",onclick:()=>B("draft")},"Render again"),t("button",{type:"button",class:"btn",onclick:l},"Adjust in Edit"))));let H=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),q=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),te=t("ul",{class:"jobs","aria-live":"polite"}),V=t("p",{class:"note",role:"status"}),B=async z=>{V.textContent="";try{await Y("POST","/jobs",{project:r().id,quality:z}),ve()}catch(Q){V.textContent=Q.message}},D=t("p",{class:"note",role:"status"}),ce=t("ul",{class:"jobs","aria-label":"Handoff files"}),de=async()=>{D.textContent="",J(ce);try{let z=await Y("POST",`/projects/${r().id}/export/handoff`),Q=z.chapters.length,re=Q?`, ${Q} chapter${Q===1?"":"s"}`:"";D.textContent=`Written to ${z.folder}, with ${z.media} media file${z.media===1?"":"s"} linked${re}.`;for(let ne of z.files)ce.append(t("li",{},t("span",{class:"file"},ne)));for(let ne of z.omitted)ce.append(t("li",{},t("span",{class:"label-mono"},ne.format),` ${ne.reason}`))}catch(z){D.textContent=z.message}},oe=u?t("details",{class:"panel scorecard"},t("summary",{},t("span",{class:"score-title"},"Quality checks"),t("span",{class:"score-sum"},"No make yet"))):null,X=u?t("div",{class:"score-body"}):null;oe?.append(X);function K(z){if(!oe)return;let Q=z.filter(Z=>Z.project===r().id&&Z.kind==="make"&&Z.status==="done").at(-1),re=null;try{re=Q?JSON.parse(Q.output):null}catch{}let ne=qa(re),pe=re?.head!=null&&re.head===i();if(oe.querySelector(".score-sum").textContent=ne?ne.summary:"No make yet",J(X),!ne)return X.append(t("p",{class:"note"},"Make it in Brief and each check the film went through is listed here."));X.append(t("ul",{class:"score-gates"},ne.gates.map(Z=>t("li",{class:`score-row ${Z.status}`},t("span",{class:"score-id label-mono"},Z.id),t("span",{class:"score-name"},Z.name),t("span",{class:"score-status"},Z.said),Z.message?t("span",{class:"score-msg"},Z.message):null,pe&&Z.at!==void 0?t("button",{type:"button",class:"btn small score-show",onclick:()=>p(Z.at)},`Show ${Z.id} at ${_e(Z.at,r().canvas.fps)}`):null))),...ne.repairs.length?[t("p",{class:"score-head"},"Repairs"),t("ul",{class:"score-repairs"},ne.repairs.map(Z=>t("li",{},Z)))]:[],t("p",{class:"note small"},"Measured on the rendered master by code, never by a model's say-so."))}n.append(...oe?[oe]:[],t("section",{class:"panel scopes","aria-label":"Scopes"},t("h2",{},"Scopes"),t("div",{class:"scope-row"},t("figure",{},H,t("figcaption",{},"Histogram")),t("figure",{},q,t("figcaption",{},"Waveform"))),t("p",{class:"note"},"Measured on the preview: 8-bit, from the proxy.")),t("section",{class:"panel export","aria-label":"Export"},t("h2",{},"Export"),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:()=>B("draft")},"Render a draft"),t("button",{type:"button",class:"btn primary",onclick:()=>B("master")},"Render the master")),t("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),V,te),t("section",{class:"panel handoff","aria-label":"Handoff"},t("h2",{},"Handoff"),t("p",{class:"note"},"For Premiere, Resolve or Final Cut: the cut as OTIO, FCPXML, EDL and SRT, with chapters, and the media linked beside them."),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:de},"Export for another editor")),D,ce));function le(z,Q){let re=z.getContext("2d");re.clearRect(0,0,z.width,z.height),re.fillStyle=getComputedStyle(n).getPropertyValue("--scope").trim()||"#6cc0b8",Q(re)}function me(){let z=a();if(!z)return;let{histogram:Q,waveform:re}=Wa(z),ne=Math.max(1,...Q);le(H,pe=>Q.forEach((Z,Be)=>pe.fillRect(Be,100-Z/ne*100,1,Z/ne*100))),le(q,pe=>re.forEach((Z,Be)=>Z.forEach((fe,Me)=>{fe&&(pe.globalAlpha=Math.min(1,.15+fe/200),pe.fillRect(Be*2,100-Me/64*100-2,2,2))})))}async function ve(){L().catch(Q=>w.textContent=Q.message);let{jobs:z}=await Y("GET","/jobs");K(z),J(te);for(let Q of z.filter(re=>re.project===r().id&&re.kind==="render").reverse().slice(0,8)){let re=Q.output?Q.output.split(/[\\/]/).at(-1):null;te.append(t("li",{},t("span",{class:"label-mono"},Q.status),` ${Q.progress}%`,re?t("span",{class:"file"},` ${re}`):null,Q.error?t("span",{class:"error"},` ${Q.error}`):null))}}return{scopes:me,refresh:ve}}var De="application/x-kriya-clip",lo=/(?<![\p{L}\p{N}])@(\d{1,3})(?: (\d+:\d{2}(?:\.\d)?)–(\d+:\d{2}(?:\.\d)?))?/gu;function kt(n){let o=Math.round(Math.max(0,n)*10/7056e5),a=Math.floor(o/10);return`${Math.floor(a/60)}:${String(a%60).padStart(2,"0")}${o%10?`.${o%10}`:""}`}var ro=n=>{let[o,a]=n.split(":");return Math.round((Number(o)*60+Number(a))*7056e5)},io=(n,o)=>`@${n}${o?` ${kt(o.from)}\u2013${kt(o.to)}`:""}`;function za(n,o){let a=/(?:^|[^\p{L}\p{N}@])@([\p{L}\p{N}]*)$/u.exec(n.slice(0,o));return a?{start:o-a[1].length-1,query:a[1]}:null}function Va(n,o){let a=o.toLocaleLowerCase();if(!a)return n.slice(0,8);let r=n.filter(u=>String(u.number).startsWith(a)),l=n.filter(u=>!r.includes(u)&&u.name.toLocaleLowerCase().includes(a));return[...r,...l].slice(0,8)}function Rt(n){let o=t("span",{class:`thumb${n?.thumb?.sheet?" sheet":""}`,"aria-hidden":"true"},n?.thumb?null:"\u266A");return n?.thumb&&(o.style.backgroundImage=`url("${n.thumb.url}")`),o}function co(n){let o=[],a=0;for(let r of n.matchAll(lo))r.index>a&&o.push({text:n.slice(a,r.index)}),o.push({text:r[0],number:Number(r[1])}),a=r.index+r[0].length;return a<n.length&&o.push({text:n.slice(a)}),o}function Ja(n,o,a=new Map){let r=[];return{text:n.replace(lo,(u,i,p,g)=>{let w=o.find(c=>c.number===Number(i));if(!w)return u;let h=a.get(u)??(p?{from:ro(p),to:ro(g)}:null);return r.push({asset:w.asset,...h?{from:h.from,to:h.to}:{}}),`\u27E6${r.length}\u27E7`}),mentions:r}}function uo({input:n,clips:o}){let a=t("ul",{class:"mention-list",id:"mention-list",role:"listbox","aria-label":"Clips to mention",hidden:!0}),r=new Map,l=[],u=0,i=null;n.setAttribute("aria-controls","mention-list"),n.setAttribute("aria-autocomplete","list"),n.setAttribute("aria-expanded","false");let p=()=>{i=null,a.hidden=!0,a.replaceChildren(),n.setAttribute("aria-expanded","false"),n.removeAttribute("aria-activedescendant")},g=(y,E,x)=>{n.setRangeText(y,E,x,"end"),n.focus()},w=y=>{y&&i&&g(`${io(y.number)} `,i.start,n.selectionStart),p()};function h(){a.replaceChildren(...l.map((y,E)=>t("li",{class:"mention-option",role:"option",id:`mention-${E}`,"aria-selected":String(E===u),onmousedown:x=>(x.preventDefault(),w(y))},Rt(y),t("span",{class:"badge"},String(y.number)),t("span",{class:"name"},y.name)))),a.hidden=!1,n.setAttribute("aria-expanded","true"),n.setAttribute("aria-activedescendant",`mention-${u}`)}function c(){if(i=za(n.value,n.selectionStart),l=i?Va(o(),i.query):[],!l.length)return p();u=Math.min(u,l.length-1),h()}n.addEventListener("input",c),n.addEventListener("blur",p),n.addEventListener("keydown",y=>{if(a.hidden)return;let E={ArrowDown:1,ArrowUp:-1}[y.key];if(E)u=(u+E+l.length)%l.length;else if(y.key==="Enter"||y.key==="Tab")w(l[u]);else if(y.key==="Escape")p();else return;y.preventDefault(),y.stopImmediatePropagation(),E&&h()},!0);function v({asset:y,from:E,to:x}){let f=o().find(q=>q.asset===y);if(!f)return;let P=Number.isSafeInteger(E)&&Number.isSafeInteger(x)&&x>E?{from:E,to:x}:null,L=io(f.number,P);P&&r.set(L,P);let H=n.selectionStart;g(`${H>0&&!/\s$/.test(n.value.slice(0,H))?" ":""}${L} `,H,n.selectionEnd)}return n.addEventListener("dragover",y=>y.dataTransfer?.types.includes(De)&&y.preventDefault()),n.addEventListener("drop",y=>{let E=y.dataTransfer?.getData(De);if(E){y.preventDefault();try{v(JSON.parse(E))}catch{}}}),{el:a,get open(){return!a.hidden},insert:v,take:y=>Ja(y,o(),r)}}var fo="#101014",Qa={music:12,sfx:6,ambience:0,dialogue:0},po=.015*7056e5,hn=(n,o,a)=>{let r=Math.min(1,Math.max(0,(a-n)/(o-n)));return r*r*(3-2*r)},ho=(n,o)=>n?.find(a=>o>=a.at&&o<a.end)??null;function mo(n,o){for(let a of n??[]){if(!a.enter||o<a.at||o>=a.at+a.enter.duration)continue;let r=n.find(l=>l.end===a.at&&l!==a)??null;return{...a.enter,progress:(o-a.at)/a.enter.duration,item:a,before:r}}return null}function go(n,o,a,r,l,u=1,i={width:r,height:l}){let p=x=>({x:(r-o*x)/2,y:(l-a*x)/2,w:o*x,h:a*x}),g=p(Math.max(r/o,l/a)*u);if(n!=="fit"&&n!=="blur")return{picture:g};let w=Math.min(i.width/o,i.height/a),h=x=>Math.max(2,Math.round(x/2)*2),[c,v]=[h(o*w),h(a*w)],y=r/i.width,E={x:Math.floor((i.width-c)/4)*2*y,y:Math.floor((i.height-v)/4)*2*y,w:c*y,h:v*y};return n==="fit"?{picture:E,plate:!0}:{picture:E,behind:p(Math.max(r/o,l/a))}}function bo(n,o,a=1){return`blur(${(.82*(Math.max(2,Math.round(Math.min(n,o)/24))*a)).toFixed(2)}px) brightness(0.88) saturate(0.9)`}function Ye(n){if(!n)return"none";let o=[],a=1+(n.lift??0)+(n.ev??0)/8;a!==1&&o.push(`brightness(${a.toFixed(3)})`),n.gain!==void 0&&n.gain!==1&&o.push(`contrast(${n.gain})`);let r=(n.saturation??1)*(1+(n.vibrance??0)*.5);return r!==1&&o.push(`saturate(${r.toFixed(3)})`),o.length?o.join(" "):"none"}function yo(n,o){let a=1-Math.min(1,Math.max(0,o));switch(n){case"fade":return{a,b:1-a,bg:0};case"dip":case"flash":{let r=hn(.8,1,a),l=hn(.2,1,a);return{a:r*a,b:(1-l)*(1-a),bg:(1-r)*a+l*(1-a),backdrop:n==="dip"?"#000":"#fff"}}case"wipe":return{a:1,b:1,bg:0,edge:a};case"slide":return{a:1,b:1,bg:0,shift:1-a};case"zoom":{let r=hn(0,.5,a);return{a:r,b:1-r,bg:0,magnify:hn(.5,1,a)}}default:return{a:0,b:1,bg:0}}}var Zn=n=>10**(n/20);function Ya(n,o){if(!n?.curve?.length)return 1;let a=Math.min(n.curve.length-1,Math.max(0,Math.floor(o/7056e5*n.rate)));return n.curve[a]}function es(n,o,a){if(o<n.at||o>=n.end)return 0;let r=Zn(n.db??-Qa[n.bus??"dialogue"]),l=o-n.at,u=n.end-o,i=Math.min(1,l/po,u/po);return n.fadeIn&&(i=Math.min(i,l/n.fadeIn)),n.fadeOut&&(i=Math.min(i,u/n.fadeOut)),r*Math.max(0,i)*(n.bus==="music"?Ya(a,o):1)}function ts(n,o){if(o<n.at||o>=n.end)return null;let a=n.speed?n.speed.n/n.speed.d:1,r=(o-n.at)*a;if(n.fit?.segments?.length){let l=n.at,{segments:u,crossfade:i=0}=n.fit;for(let[p,g]of u.entries()){let w=(g.out-g.in)/a-(p<u.length-1?i/2:0)-(p>0?i/2:0),h=p>0?i/2:0;if(o<l+w||p===u.length-1)return{source:g.in+(h+o-l)*a,until:Math.min(n.end,l+w)};l+=w}}if(n.loop){let l=n.out-n.in;return r%=l,{source:n.in+r,until:Math.min(n.end,o+(l-r)/a)}}return{source:n.in+r,until:n.end}}var Xa=null,mn=()=>Xa??=new AudioContext,wo=n=>Number.isFinite(n)?Math.min(1,Math.max(0,(n+60)/60)):0;function Za(n){let o=0;for(let r of n)o+=r*r;let a=Math.sqrt(o/Math.max(1,n.length));return a>0?20*Math.log10(a):-1/0}function ko(){let n=null,o=null,a=new WeakSet,r=()=>{if(!n){let l=mn();n=l.createAnalyser(),n.fftSize=1024,n.connect(l.destination),o=new Float32Array(n.fftSize)}return n};return{input:()=>r(),join(l){if(!a.has(l)){try{mn().createMediaElementSource(l).connect(r()),a.add(l)}catch{}mn().resume().catch(()=>{})}},level(){return n?(n.getFloatTimeDomainData(o),Za(o)):-1/0}}}function vo({canvas:n,urlOf:o}){let a=document.createElement("div");a.className="tile-layer",a.setAttribute("aria-hidden","true");let r=new Map;function l(u){a.style.left=`${n.offsetLeft}px`,a.style.top=`${n.offsetTop}px`,a.style.width=`${n.clientWidth}px`,a.style.height=`${n.clientHeight}px`;let i=n.clientWidth/u.width;for(let{frame:p}of r.values())p.style.transform=`scale(${i})`}return{sync(u,i,p){!a.isConnected&&n.isConnected&&n.after(a);let g=(u??[]).filter(h=>i>=h.at&&i<h.end),w=new Set(g.map(h=>h.key));for(let[h,{frame:c}]of r)w.has(h)||(c.remove(),r.delete(h));for(let h of g){let c=r.get(h.key);if(!c){let v=document.createElement("iframe");v.setAttribute("sandbox","allow-scripts"),v.setAttribute("tabindex","-1"),v.title=h.kind==="caption"?"Caption":"Graphic",v.className="tile",v.style.width=`${p.width}px`,v.style.height=`${p.height}px`,v.style.zIndex=String(h.depth??1),v.dataset.key=h.key,c={frame:v,tile:h,loaded:!1,at:0},v.addEventListener("load",()=>{c.loaded=!0,v.contentWindow?.postMessage({t:c.at},"*")}),v.src=o(h.key),r.set(h.key,c),a.append(v)}c.at=(i-h.at)*1e3/7056e5,c.loaded&&c.frame.contentWindow?.postMessage({t:c.at},"*")}r.size&&l(p)},clipLeft(u){a.style.clipPath=u===null?"":`inset(0 0 0 ${(u*100).toFixed(2)}%)`},get frames(){return new Map([...r].map(([u,{frame:i}])=>[u,i]))},clear(){for(let{frame:u}of r.values())u.remove();r.clear()}}}function xo({urlOf:n,meter:o=null}){let a=null,r=[],l={items:[],duck:null},u=()=>{for(let p of r){for(let g of p.timers)clearTimeout(g);p.element.pause(),p.node.disconnect(),p.gain.disconnect()}r=[]};function i(p,g,w){let{item:h,element:c,gain:v}=p;if(!ts(h,Math.max(g,h.at)))return;let E=Math.max(0,(h.at-g)/7056e5),x=()=>{let q=ts(h,Math.max(g+(performance.now()-w)*(7056e5/1e3),h.at));q&&(c.currentTime=q.source/7056e5,c.play().catch(()=>{}),q.until<h.end&&p.timers.push(setTimeout(x,(q.until-g)*1e3/7056e5-(performance.now()-w))))};p.timers.push(setTimeout(x,E*1e3));let f=.02*7056e5,P=Math.max(g,h.at),L=[];for(let q=P;q<h.end;q+=f)L.push(es(h,q,l.duck));L.push(0);let H=a.currentTime+(P-g)/7056e5;v.gain.setValueAtTime(L[0],H),L.length>1&&v.gain.setValueCurveAtTime(Float32Array.from(L),H,Math.max(.01,(h.end-P)/7056e5))}return{load(p){u(),l=p??{items:[],duck:null}},start(p,g){if(u(),g!==1)return;let w=l.items.filter(c=>c.bus!=="dialogue"&&c.end>p);if(!w.length)return;a??=mn(),a.resume();let h=performance.now();for(let c of w){let v=new Audio;v.preload="auto",v.src=n(c.asset);let y=a.createMediaElementSource(v),E=a.createGain();y.connect(E).connect(o?o.input():a.destination);let x={item:c,element:v,node:y,gain:E,timers:[]};r.push(x),i(x,p,h)}},stop:u,state(p){return r.map(({item:g,gain:w})=>({asset:g.asset,bus:g.bus,planned:es(g,p,l.duck),node:w.gain.value}))}}}var $o=n=>typeof n=="number"?{n,d:1}:n??{n:1,d:1},gn=n=>[...n?.picture??[]].sort((o,a)=>o.at-a.at),ns=n=>[{clip:null,asset:n.id,in:0,out:n.facts.duration,at:0,end:n.facts.duration,speed:{n:1,d:1}}],vt=(n,o)=>n.find(a=>o>=a.at&&o<a.end)??(n.length&&o>=n.at(-1).end?n.at(-1):null);function lt(n,o){if(n.hold)return n.in;let{n:a,d:r}=$o(n.speed);return Math.min(n.out,n.in+Math.round((o-n.at)*a/r))}function It(n,o,a){for(let r of n){if(r.asset!==o||r.hold||a<r.in||a>=r.out)continue;let{n:l,d:u}=$o(r.speed);return r.at+Math.round((a-r.in)*u/l)}return null}var Ue=n=>n.length?Math.max(...n.map(o=>o.end)):0;function So(n,o){let a=[];for(let r of o){let l=It(n,r.asset,r.start);l!==null&&l>0&&a.push({id:r.id,at:l})}return a}var er=1280;function Mo({canvas:n,urlOf:o,assetOf:a,onTime:r,onRate:l,tileUrl:u}){let i=n.getContext("2d",{willReadFrequently:!0}),p=new Map,g=[],w={n:30,d:1},h=0,c=0,v=0,y={width:1920,height:1080},E=1,x=!1,f=0,P=null,L=null,H=u?vo({canvas:n,urlOf:u}):null,q=u?ko():null,te=u?xo({urlOf:o,meter:q}):null,V=null,B=u?[document.createElement("canvas"),document.createElement("canvas")]:null,D=new Map;function ce(m){let S=g[m],N=`${S.asset}:${m%2}`;if(!p.has(N)){let F=document.createElement("video");Object.assign(F,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:o(S.asset)}),p.set(N,F)}return p.get(N)}function de(m,S){let N=a(m.asset)?.facts?.fps??w;return(S+Ne(N)/2)/7056e5}function oe(){let m=Math.min(1,er/Math.max(y.width,y.height)),S=Math.round(y.width*m),N=Math.round(y.height*m);(n.width!==S||n.height!==N)&&Object.assign(n,{width:S,height:N})}function X(m,S,N,F,T){let{width:j,height:R}=n;(m.width!==j||m.height!==R)&&Object.assign(m,{width:j,height:R});let G=m.getContext("2d");G.imageSmoothingQuality="high",G.fillStyle="#000",G.fillRect(0,0,j,R);let W=go(T?.frame,N,F,j,R,E,L.output);return W.plate&&(G.fillStyle=fo,G.fillRect(0,0,j,R)),W.behind&&(G.filter=bo(L.output.width,L.output.height,j/L.output.width),G.drawImage(S,W.behind.x,W.behind.y,W.behind.w,W.behind.h),G.filter="none"),G.drawImage(S,W.picture.x,W.picture.y,W.picture.w,W.picture.h),m}function K(m,S){let{width:N,height:F}=n,T=ho(L.picture,S),j=mo(L.picture,S),R=j&&D.get(`${j.asset}@${j.source}`),G=[...T?.fx??[],...(L.adjust??[]).filter(he=>S>=he.at&&S<he.end).flatMap(he=>he.fx)],W=(he,Le)=>{let Ze=Ye(Le);i.filter=G.length?`${Ze==="none"?"":`${Ze} `}${G.join(" ")}`:Ze,i.drawImage(he,0,0),i.filter="none"};if(!R)return W(X(B[1],m,m.videoWidth,m.videoHeight,T),T?.grade);let ae=X(B[0],R,R.width,R.height,j.before),ue=X(B[1],m,m.videoWidth,m.videoHeight,T),se=yo(j.kind,j.progress);if(i.fillStyle="#000",i.fillRect(0,0,N,F),j.kind==="wipe")return W(ae,j.before?.grade),i.save(),i.beginPath(),i.rect(N*se.edge,0,N-N*se.edge,F),i.clip(),W(ue,T?.grade),i.restore();if(j.kind==="slide"){i.filter=Ye(j.before?.grade),i.drawImage(ae,-N*se.shift,0),i.filter=Ye(T?.grade),i.drawImage(ue,N*(1-se.shift),0),i.filter="none";return}if(se.bg>0&&(i.fillStyle=se.backdrop,i.fillRect(0,0,N,F)),se.b>0&&(i.globalAlpha=se.b/(se.b+se.bg),i.filter=Ye(T?.grade),i.drawImage(ue,0,0)),se.a>0){i.globalAlpha=se.a,i.filter=Ye(j.before?.grade);let he=se.magnify===void 0?1:Math.max(.01,se.magnify);i.drawImage(ae,(N-N*he)/2,(F-F*he)/2,N*he,F*he,0,0,N,F)}i.filter="none",i.globalAlpha=1}async function le(m){for(let S of m.picture){if(!S.enter||L!==m)continue;let N=`${S.enter.asset}@${S.enter.source}`;if(D.has(N))continue;let F=document.createElement("video");Object.assign(F,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:o(S.enter.asset)});let T=a(S.enter.asset)?.facts?.fps??w;if(await new Promise(R=>{F.addEventListener("seeked",R,{once:!0}),F.addEventListener("error",R,{once:!0}),F.currentTime=(S.enter.source+Ne(T)/2)/7056e5}),!F.videoWidth)continue;let j=document.createElement("canvas");Object.assign(j,{width:F.videoWidth,height:F.videoHeight}),j.getContext("2d").drawImage(F,0,0),D.set(N,j),F.removeAttribute("src")}}let me=()=>L&&Math.abs(y.width*L.output.height-y.height*L.output.width)<y.width;function ve(m,S,N,F){oe();let{width:T,height:j}=n;if(i.fillStyle="#000",i.fillRect(0,0,T,j),L&&m?.videoWidth&&me()){if(K(m,F),V!==null){let R=Math.max(T/m.videoWidth,j/m.videoHeight)*E;i.save(),i.beginPath(),i.rect(0,0,T*V,j),i.clip(),i.drawImage(m,(T-m.videoWidth*R)/2,(j-m.videoHeight*R)/2,m.videoWidth*R,m.videoHeight*R),i.restore()}P={asset:S.asset,source:N}}else if(m?.videoWidth){let R=Math.max(T/m.videoWidth,j/m.videoHeight)*E,G=m.videoWidth*R,W=m.videoHeight*R;i.drawImage(m,(T-G)/2,(j-W)/2,G,W),P={asset:S.asset,source:N}}if(x){i.strokeStyle="rgb(255 255 255 / 0.55)",i.setLineDash([6,6]),i.lineWidth=1;for(let R of[.05,.1])i.strokeRect(T*R,j*R,T*(1-2*R),j*(1-2*R));i.setLineDash([])}H&&(H.sync(me()?L.tiles:[],F,L?.output),H.clipLeft(V!==null&&me()?V:null))}let z=()=>{oe(),i.fillStyle="#000",i.fillRect(0,0,n.width,n.height),P=null,H?.clear()},Q=0,re=Promise.resolve();function ne(m){let S=g.indexOf(vt(g,m));if(S<0)return Promise.resolve(z());let N=g[S],F=lt(N,m),T=ce(S),j=de(N,F),R=++Q,G=new Promise(W=>{let ae=()=>{Q===R&&ve(T,N,F,m),W()};if(T.readyState>=2&&Math.abs(T.currentTime-j)<1e-4)return ae();T.addEventListener("seeked",ae,{once:!0}),T.currentTime=j});if(re=G,g[S+1]){let W=ce(S+1);W!==T&&(W.currentTime=de(g[S+1],g[S+1].in))}return G}function pe(){for(let m of p.values())m.pause(),m.muted=!0}function Z(m,S=!0){c=Math.min(Math.max(0,m),Math.max(0,h-Ne(w))),S&&r(c)}function Be(m){let S=g.indexOf(vt(g,c));if(S<0)return Me(0);let N=(F,T)=>{let j=g[F],R=ce(F);R.currentTime=de(j,lt(j,T)),R.playbackRate=v,R.muted=!1,q?.join(R);let G=L?.audio.items.find(se=>se.bus==="dialogue"&&se.asset===j.asset&&se.at<j.end&&j.at<se.end);L&&(R.volume=G?.db===void 0?1:Math.min(1,Zn(G.db)));let{n:W,d:ae}=typeof j.speed=="object"?j.speed:{n:1,d:1},ue=(se,he)=>{if(m!==f)return;let Le=j.at+Math.round((Math.round(he.mediaTime*7056e5)-j.in)*ae/W);if(Le>=j.end-Ne(w)/2||R.ended)return R.pause(),R.muted=!0,g[F+1]?(S=F+1,Z(g[S].at),N(S,g[S].at)):Me(0);ve(R,j,lt(j,Le),Le),Z(Le),R.requestVideoFrameCallback(ue)};R.requestVideoFrameCallback(ue),R.play().catch(()=>m===f&&Me(0))};N(S,c)}function fe(m){let S=performance.now(),N=async F=>{if(m===f){if(Z(c-(F-S)/1e3*7056e5*Math.abs(v)),S=F,await ne(c),c===0)return Me(0);requestAnimationFrame(N)}};requestAnimationFrame(N)}function Me(m){if(m===v&&m!==0)return;v=m;let S=++f;pe(),l(v),te&&(me()&&v>0?te.start(c,v):te.stop()),v>0?Be(S):v<0?fe(S):(Z(wt(c,w)),ne(c))}return{load(m,{fps:S,duration:N,shape:F,preview:T}){return g=m,H&&(L=T??null,te.load(L?.audio),H.clear(),L&&le(L).then(()=>v===0&&L===T&&ne(c))),w=S,h=N,F&&(y=F),++f,pe(),v=0,l(0),Z(Math.min(c,Math.max(0,h-Ne(w)))),ne(c)},seek(m){return v!==0&&Me(0),Z(wt(m,w)),ne(c)},setRate:Me,get time(){return c},get rate(){return v},get shown(){return P},get settled(){return re},setShape(m){return y=m,ne(c)},setZoom(m){return E=m,ne(c)},setGuides(m){return x=m,ne(c)},setWipe(m){return H?(V=m===null?null:Math.min(1,Math.max(0,m)),v===0?ne(c):Promise.resolve()):Promise.resolve()},get wipe(){return V},level:()=>q&&v!==0?q.level():-1/0,get live(){return H?{on:!!(L&&me()),tiles:[...H.frames.keys()],sound:te.state(c),held:D.size}:null},pixels:()=>n.width?i.getImageData(0,0,n.width,n.height):null}}var Co="http://www.w3.org/2000/svg",ss={box:"Box",ring:"Ring",arrow:"Arrow"},Lo=10,os=n=>Math.min(1,Math.max(0,n)),bn=(n,o)=>os(.5+(n-.5)/o),Eo=(n,o)=>.5+(n-.5)*o;function Ao(n,o,a,{zoom:r=1,at:l}){let[u,i]=[bn(o.u,r),bn(a.u,r)].sort((y,E)=>y-E),[p,g]=[bn(o.v,r),bn(a.v,r)].sort((y,E)=>y-E),w=Math.round(u*1e3),h=Math.round(p*1e3),c=Math.min(1e3-w,Math.round(i*1e3)-w),v=Math.min(1e3-h,Math.round(g*1e3)-h);return c<Lo||v<Lo||!Number.isSafeInteger(l)||l<0?null:{kind:n,x:w,y:h,w:c,h:v,at:Math.round(l)}}function To({frame:n,canvas:o,timeNow:a,zoomNow:r,usable:l,onChange:u,pause:i}){let p=null,g=null,w=null,h=document.createElementNS(Co,"svg");h.setAttribute("class","draw-layer"),h.setAttribute("viewBox","0 0 1000 1000"),h.setAttribute("preserveAspectRatio","none"),h.setAttribute("aria-hidden","true"),n.classList.add("drawable"),n.append(h);let c=t("span",{class:"note small draw-note",role:"status","aria-live":"polite"});function v(){Object.assign(h.style,{left:`${o.offsetLeft}px`,top:`${o.offsetTop}px`,width:`${o.offsetWidth}px`,height:`${o.offsetHeight}px`})}new ResizeObserver(()=>(v(),x())).observe(o),window.addEventListener("resize",()=>(v(),x()));let y=(B,D)=>{let ce=document.createElementNS(Co,B);for(let[de,oe]of Object.entries(D))ce.setAttribute(de,String(oe));return ce.setAttribute("vector-effect","non-scaling-stroke"),ce};function E(B,D,ce=!1){let de=r(),oe=Eo(D.x/1e3,de)*1e3,X=Eo(D.y/1e3,de)*1e3,K=D.w/1e3*de*1e3,le=D.h/1e3*de*1e3,me=`draw-mark${ce?" draft":""}`;if(B==="ring")return[y("ellipse",{cx:oe+K/2,cy:X+le/2,rx:K/2,ry:le/2,class:me})];if(B==="box")return[y("rect",{x:oe,y:X,width:K,height:le,rx:6,class:me})];let ve=X>120?X:X+le,z=X>120?Math.max(0,X-110):Math.min(1e3,X+le+110);return[y("rect",{x:oe,y:X,width:K,height:le,class:`${me} faint`}),y("line",{x1:oe+K/2,y1:z,x2:oe+K/2,y2:ve,class:me}),y("polyline",{points:`${oe+K/2-22},${ve+(X>120?-26:26)} ${oe+K/2},${ve} ${oe+K/2+22},${ve+(X>120?-26:26)}`,class:me})]}function x(){h.replaceChildren(...g?E(g.kind,g):[],...w?.box?E(p,w.box,!0):[])}function f(B){let D=B?l():null;if(D){c.textContent=D;return}p=p===B?null:B;for(let[ce,de]of Object.entries(H))de.setAttribute("aria-pressed",String(ce===p));h.classList.toggle("active",!!p),c.textContent=p?`Drag on the picture to draw a ${ss[p].toLowerCase()}.`:"",p&&i()}let P=B=>{let D=h.getBoundingClientRect();return{u:os((B.clientX-D.left)/D.width),v:os((B.clientY-D.top)/D.height)}};h.addEventListener("pointerdown",B=>{p&&(B.preventDefault(),h.setPointerCapture(B.pointerId),w={start:P(B),box:null})}),h.addEventListener("pointermove",B=>{w&&(w.box=Ao(p,w.start,P(B),{zoom:r(),at:0}),x())});let L=B=>{if(!w)return;let D=Ao(p,w.start,P(B),{zoom:r(),at:a()});if(w=null,!D)return c.textContent="Too small: drag a bigger shape.",x();g=D,f(null),c.textContent=`Drawn: ${ss[D.kind].toLowerCase()}. Say what to do with it, like "callout this", "blur this", "zoom here" or "mask this".`,x(),u(g)};h.addEventListener("pointerup",L),h.addEventListener("pointercancel",()=>(w=null,x())),window.addEventListener("keydown",B=>B.key==="Escape"&&p&&f(null));let H=Object.fromEntries(Object.entries(ss).map(([B,D])=>[B,t("button",{type:"button",class:"btn","aria-pressed":"false",title:`Draw a ${D.toLowerCase()} on the frame`,onclick:()=>f(B)},D)])),q=t("button",{type:"button",class:"btn",title:"Remove the drawing",onclick:()=>te()},"Clear");function te(){g=null,w=null,c.textContent="",p&&f(null),x(),u(null)}let V=t("div",{class:"row draw-tools",role:"group","aria-label":"Draw on the frame"},...Object.values(H),q,c);return v(),{tools:V,mark:()=>g,clear:te,redraw:()=>(v(),x())}}var as=[["story","Story"],["cuts","Cuts"],["broll","B-roll"],["look","Look"],["captions","Captions"],["audio","Audio"],["render","Render"],["check","Checks"],["repair","Repairs"],["watch","Watch"]],tr=new Set(as.map(([n])=>n));function Oo(n,o){return Object.fromEntries(as.map(([a])=>[a,a===o?"active":n.has(a)?"done":"waiting"]))}var nr={passed:"passed",failed:"failed",not_checked:"not checked",not_applicable:"not applicable"};function Po({onFollow:n=()=>{}}={}){let o=new Set,a=null,r=!0,l=as.map(([y,E])=>t("li",{class:"stage",dataset:{stage:y,state:"waiting"}},t("span",{class:"dot","aria-hidden":"true"}),E)),u=t("ol",{class:"stages","aria-label":"What the Director has done so far"},l),i=t("p",{class:"stage-line",role:"status","aria-live":"polite"},"Starting: reading the footage."),p=t("ul",{class:"stage-changes","aria-label":"Changes in this stage"}),g=t("ul",{class:"stage-gates","aria-label":"Checks so far"}),w=t("button",{type:"button",class:"btn small follow","aria-pressed":"true",title:"Show the Director's working cut on the monitor as it builds",onclick:()=>v(!r)},"Follow on the monitor"),h=t("div",{class:"director-strip"},u,i,p,g,w);function c(){let y=Oo(o,a);for(let E of l)E.dataset.state=y[E.dataset.stage],y[E.dataset.stage]==="active"?E.setAttribute("aria-current","step"):E.removeAttribute("aria-current")}function v(y){r=y,w.setAttribute("aria-pressed",String(r)),n(r)}return{el:h,reset(){o=new Set,a=null,i.textContent="Starting: reading the footage.",w.hidden=!1,J(p),J(g),c()},push(y){return!y||!tr.has(y.stage)?!1:(o.add(y.stage),a=y.stage,i.textContent=typeof y.text=="string"?y.text:"",y.skipped&&(i.textContent+=` This layer couldn't be drawn on its own (${y.skipped}), so the monitor shows the one before.`),Array.isArray(y.changes)?J(p).append(...y.changes.slice(0,4).map(E=>t("li",{},String(E)))):["check","repair","watch"].includes(y.stage)||J(p),Array.isArray(y.gates)&&J(g).append(...y.gates.map(E=>t("li",{class:`gate ${E.status==="failed"&&E.severity==="note"?"note":E.status}`,title:`${E.id}: ${nr[E.status]??E.status}${E.message?`. ${E.message}`:""}`},String(E.id)))),c(),!0)},finish(){a=null,w.hidden=!0,c()},get follow(){return r},get states(){return Oo(o,a)}}}var jo=({reduced:n=!1,automated:o=!1}={})=>!n&&!o,sr=1800;function Ro({load:n,show:o,restore:a,animate:r,stepMs:l=sr}){let u=[],i=0,p=null,g=!1,w=!1,h=t("p",{class:"replay-title"},"How it was edited"),c=t("div",{class:"replay-steps",role:"group","aria-label":"Layers of the edit"}),v=t("p",{class:"replay-detail",role:"status","aria-live":"polite"}),y=t("button",{type:"button",class:"btn small",hidden:!0,onclick:()=>g?f():P()},"Pause replay"),E=t("button",{type:"button",class:"btn small",onclick:()=>q()},"Skip replay"),x=t("div",{class:"replay",hidden:!0,"aria-label":"Replay of how the cut was edited",role:"region"},t("div",{class:"replay-head"},h,t("div",{class:"replay-actions"},y,E)),c,v),f=()=>{clearTimeout(p),p=null,g=!1,y.textContent="Play replay"},P=()=>{g=!0,y.textContent="Pause replay",L()};function L(){clearTimeout(p),g&&(p=setTimeout(()=>i<u.length-1?H(i+1).then(L):q(),l))}async function H(te){i=te;let V=u[te];for(let[D,ce]of[...c.children].entries())ce.setAttribute("aria-pressed",String(D===te));let B=V.id==="raw"?"The cut before the Director touched it.":V.ops?`${V.ops} change${V.ops===1?"":"s"}${V.changes?.length?`: ${V.changes.join("; ")}`:""}.`:"Nothing changed in this layer.";v.textContent=`${te+1} of ${u.length} \xB7 ${V.label}. ${B}${V.skipped?` It couldn't be drawn on its own (${V.skipped}), so this shows the layer before.`:""}`,E.textContent=te===u.length-1?"Back to my cut":"Skip replay",await o(V)}async function q(){f(),w&&(w=!1,x.hidden=!0,await a())}return{el:x,get open(){return w},get at(){return i},async start(){f();let te;try{te=await n()}catch(V){return x.hidden=!1,w=!1,J(c),v.textContent=V.message,E.textContent="Close",!1}return u=te.layers.filter((V,B)=>B===0||V.ops>0),J(c).append(...u.map((V,B)=>t("button",{type:"button",class:"btn small step","aria-pressed":"false",onclick:()=>(f(),H(B))},V.label))),w=!0,x.hidden=!1,y.hidden=!r,await H(0),r&&P(),!0},stop:q}}var or={vivid:{saturation:1.15,gain:1.06,vibrance:.35},cinematic:{saturation:.9,gain:1.12,gamma:.95,temperature:7200,vignette:.45},warm:{temperature:5200,saturation:1.05,vibrance:.2,vignette:.2},bright:{lift:.04,gamma:1.1,vibrance:.2},mono:{saturation:0,gain:1.1,vignette:.3}};function ar(n){if(!n)return{filter:"none",tint:null,vignette:0};let o=n.temperature??6500,a=Math.min(1,Math.abs(o-6500)/2500),r=o===6500?null:{colour:o<6500?"255 150 60":"70 140 255",alpha:Math.round(a*.22*1e3)/1e3};return{filter:Ye(n),tint:r,vignette:n.vignette??0}}function Io(n){let o=Math.max(1,Math.ceil(n/100));return Math.min(99,Math.max(0,Math.floor(n/o/2)))}function No({select:n,source:o}){let a=[...n.options].map(w=>{let h=t("canvas",{class:"look-sketch",width:96,height:54,"aria-hidden":"true"}),c=w.textContent.replace(/^Look:\s*/,"").replace(/\s*\(.*\)$/,""),v=t("button",{type:"button",class:"look-card","aria-pressed":String(n.value===w.value),title:`${w.textContent}. A sketch on your footage: the render is exact.`,onclick:()=>{n.value=w.value,n.dispatchEvent(new Event("change",{bubbles:!0})),p()}},h,t("span",{class:"look-name"},c.charAt(0).toUpperCase()+c.slice(1)));return{value:w.value,button:v,canvas:h}}),r=t("div",{class:"look-cards",role:"group","aria-label":"Colour looks, drawn on your footage"},a.map(w=>w.button)),l=null,u=null,i=0;function p(){for(let w of a)w.button.setAttribute("aria-pressed",String(w.value===n.value))}function g(){for(let w of a){let h=w.canvas.getContext("2d"),{width:c,height:v}=w.canvas,y=ar(or[w.value]??null);if(h.filter="none",h.fillStyle="#22302f",h.fillRect(0,0,c,v),l?.naturalWidth){let E=l.naturalWidth/10,x=l.naturalHeight/10,f=Math.max(c/E,v/x);h.filter=y.filter,h.drawImage(l,i%10*E,Math.floor(i/10)*x,E,x,(c-E*f)/2,(v-x*f)/2,E*f,x*f),h.filter="none"}else{let E=h.createLinearGradient(0,0,c,v);E.addColorStop(0,"#c98f6b"),E.addColorStop(.5,"#6f9c98"),E.addColorStop(1,"#33486b"),h.filter=y.filter,h.fillStyle=E,h.fillRect(0,0,c,v),h.filter="none"}if(y.tint&&(h.fillStyle=`rgb(${y.tint.colour} / ${y.tint.alpha})`,h.fillRect(0,0,c,v)),y.vignette>0){let E=h.createRadialGradient(c/2,v/2,Math.min(c,v)*.3,c/2,v/2,Math.max(c,v)*.7);E.addColorStop(0,"rgb(0 0 0 / 0)"),E.addColorStop(1,`rgb(0 0 0 / ${Math.min(.8,y.vignette*1.2)})`),h.fillStyle=E,h.fillRect(0,0,c,v)}}}return n.addEventListener("change",p),{el:r,refresh(){p();let w=o();if(w?.url===u&&w?.cell===i)return g();if(u=w?.url??null,i=w?.cell??0,!u)return l=null,g();let h=new Image;h.addEventListener("load",()=>u===w.url&&(l=h,g())),h.addEventListener("error",()=>u===w.url&&(l=null,g())),h.src=u,g()},mark:p}}var Do=[{group:"Play",keys:["Space"],press:[" "],action:"toggle",does:"Play or pause"},{group:"Play",keys:["J","K","L"],press:["j","k","l"],action:["reverse","rate","faster"],does:"Play backwards, stop, play forwards (press again to go faster)"},{group:"Play",keys:["\u2190","\u2192"],press:["ArrowLeft","ArrowRight"],action:"step",does:"One frame back or forward"},{group:"Play",keys:["Shift","\u2190/\u2192"],press:["ArrowLeft"],shift:!0,action:"step",does:"One second back or forward"},{group:"Play",keys:["Home"],press:["Home"],action:"seek",does:"To the start"},{group:"Cut",keys:["I","O"],press:["i","o"],action:"mark",does:'Mark in and out: the marked stretch is "this" to Kriya'},{group:"Cut",keys:["S"],press:["s"],action:"split",does:"Split the clip at the playhead"},{group:"Cut",keys:["Delete"],press:["Delete","Backspace"],action:"delete",does:"Remove the selected clip and close the gap"},{group:"Cut",keys:["\u2318/Ctrl","Z"],press:["z"],mod:!0,action:"undo",does:"Undo (add Shift to redo)"},{group:"Studio",keys:["1","2","3"],press:["1","2","3"],action:"mode",does:"Direct, Edit, Finish"},{group:"Studio",keys:["/"],press:["/"],action:"prompt",does:"Write to Kriya"},{group:"Studio",keys:["Esc"],press:[],action:null,does:"Let go of the field, the selection and the marks"},{group:"Studio",keys:["?"],press:[],action:null,does:"This list"}];function Bo(){let n=[...new Set(Do.map(r=>r.group))],o=t("button",{type:"button",class:"btn",onclick:()=>a.close()},"Close"),a=t("dialog",{class:"picker shortcuts","aria-label":"Keyboard shortcuts"},t("h2",{},"Keyboard shortcuts"),...n.map(r=>t("section",{class:"keys-group","aria-label":r},t("p",{class:"keys-head"},r),t("dl",{class:"keys"},Do.filter(l=>l.group===r).flatMap(l=>[t("dt",{},...l.keys.flatMap((u,i)=>[i?" ":null,t("kbd",{},u)])),t("dd",{},l.does)])))),t("p",{class:"note small"},"Keys work when no field has the focus."),t("div",{class:"row end"},o));return a.addEventListener("keydown",r=>{r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),a.close())}),{dialog:a,open(){a.isConnected||document.body.append(a),a.open||a.showModal(),o.focus()}}}var rr=["story","whole"],ir={auto:"Automatic",fill:"Fill the frame",fit:"Fit, with bars",blur:"Fit, blur behind"},wn=n=>n.sequences.find(o=>o.id===n.active)?.assembly?.parts??[],kn=n=>n.filter(o=>rr.includes(o.use)),Go=n=>({op:"set_assembly",assembly:{version:1,parts:n}});function xt(n,o,a){let r=kn(n),l=r.findIndex(w=>w.id===o),u=r[l+a];if(l<0||!u)return null;let i=[...n],p=i.indexOf(r[l]),g=i.indexOf(u);return[i[p],i[g]]=[i[g],i[p]],i}function Ko(n,o,a){let r=n.find(p=>p.id===o);if(!r||o===a)return null;let l=n.filter(p=>p!==r),u=a===null?l.length:l.findIndex(p=>p.id===a);if(u<0)return null;let i=[...l.slice(0,u),r,...l.slice(u)];return i.every((p,g)=>p===n[g])?null:i}var rs=(n,o)=>n.filter(a=>a.id!==o&&a.at?.part!==o);function Fo(n,{asset:o,from:a,to:r},l=null){let u=n.length+1;for(;n.some(g=>g.id===`p${u}`);)u++;let i=Number.isSafeInteger(a)&&Number.isSafeInteger(r)&&r>a,p={id:`p${u}`,asset:o,...i?{from:a,to:r}:{},use:"whole",why:"storyboard"};return Ko([...n,p],p.id,l)??[...n,p]}function lr(n,o,a){return n.map(r=>{if(r.id!==o)return r;let{fit:l,...u}=r;return a==="auto"?u:{...u,fit:a}})}var yn=(n,o,a)=>typeof n=="number"?n:o.find(r=>r.id===n?.word)?.[n?.edge??a]??null;function cr(n,o=[]){if(n.from===void 0&&n.to===void 0)return"whole";let a=n.from===void 0?0:yn(n.from,o,"start"),r=n.to===void 0?null:yn(n.to,o,"end");return`${a===null?"?":kt(a)}\u2013${r===null?"end":kt(r)}`}function dr(n,o,a,r,l=[]){let u=n.from===void 0?0:yn(n.from,l,"start"),i=n.to===void 0?r?.duration??null:yn(n.to,l,"end"),p=u===null||i===null?null:kt(i-u);return[`Part ${o+1} of ${a}: clip ${r?.number??"?"}`,r?.name,n.use,p].filter(Boolean).join(", ")}function Wo({root:n,clips:o,words:a,onChange:r}){let l=[],u=null,i=t("ol",{class:"sb-cards","aria-label":"The film's order"}),p=t("ul",{class:"sb-unused","aria-label":"Clips not used"}),g=t("p",{class:"note small"},"Nothing in the storyboard yet. Add clips in the order the film should play."),w=t("p",{class:"sr-only",role:"status","aria-live":"polite"}),h=(x,f=null,P="")=>{x&&(u=f,w.textContent=P,r(x))},c=x=>{try{return JSON.parse(x.dataTransfer.getData(De))}catch{return null}},v=x=>x.dataTransfer?.types.includes(De)&&x.preventDefault(),y=x=>f=>{let P=c(f);P&&(f.preventDefault(),f.stopPropagation(),P.part?h(Ko(l,P.part,x),P.part,"Moved."):o().some(L=>L.asset===P.asset)&&h(Fo(l,P,x),null,"Added to the film."))};function E(){let x=new Map(o().map(L=>[L.asset,L])),f=kn(l);J(i),f.forEach((L,H)=>{let q=x.get(L.asset),te=t("select",{class:"field select","aria-label":`How clip ${q?.number??"?"} fits the frame`,onchange:()=>h(lr(l,L.id,te.value),L.id)},Object.entries(ir).map(([B,D])=>t("option",{value:B},D)));te.value=L.fit??"auto";let V=t("div",{class:"sb-card",role:"group",tabindex:"0",draggable:"true","aria-label":dr(L,H,f.length,q,a()),"aria-keyshortcuts":"Alt+ArrowLeft Alt+ArrowRight Delete",dataset:{part:L.id},ondragstart:B=>B.dataTransfer.setData(De,JSON.stringify({part:L.id,asset:L.asset,...typeof L.from=="number"&&typeof L.to=="number"?{from:L.from,to:L.to}:{}})),onkeydown:B=>{if(B.target!==V)return;let D=B.altKey?{ArrowLeft:-1,ArrowRight:1,ArrowUp:-1,ArrowDown:1}[B.key]:null;if(D)h(xt(l,L.id,D),L.id,`Part ${H+1+D} of ${f.length}.`);else if(B.key==="Delete"||B.key==="Backspace")h(rs(l,L.id),f[H+1]?.id??f[H-1]?.id??null,"Left out of the film.");else return;B.preventDefault(),B.stopPropagation()}},Rt(q),t("span",{class:"badge"},String(q?.number??"?")),t("span",{class:"name"},q?.name??"A missing clip"),t("span",{class:"stretch label-mono"},cr(L,a())),te,t("span",{class:"sb-moves"},t("button",{type:"button",class:"btn move",disabled:H===0,"aria-label":`Move clip ${q?.number??"?"} up`,onclick:()=>h(xt(l,L.id,-1),L.id,`Part ${H} of ${f.length}.`)},"Move up"),t("button",{type:"button",class:"btn move",disabled:H===f.length-1,"aria-label":`Move clip ${q?.number??"?"} down`,onclick:()=>h(xt(l,L.id,1),L.id,`Part ${H+2} of ${f.length}.`)},"Move down"),t("button",{type:"button",class:"btn","aria-label":`Leave clip ${q?.number??"?"} out of the film`,onclick:()=>h(rs(l,L.id),f[H+1]?.id??f[H-1]?.id??null,"Left out of the film.")},"Remove")));i.append(t("li",{ondragover:v,ondrop:y(L.id)},V))}),g.hidden=f.length>0;let P=new Set(l.map(L=>L.asset));J(p);for(let L of o().filter(H=>!P.has(H.asset)))p.append(t("li",{},t("button",{type:"button",class:"btn sb-add",draggable:"true","aria-label":`Add clip ${L.number}, ${L.name}, to the film`,ondragstart:H=>H.dataTransfer.setData(De,JSON.stringify({asset:L.asset})),onclick:()=>h(Fo(l,{asset:L.asset}),null,`Added clip ${L.number} to the film.`)},t("span",{class:"badge"},String(L.number)),t("span",{class:"name"},L.name),t("span",{"aria-hidden":"true"}," +"))));p.children.length||p.append(t("li",{class:"note small"},o().length?"Every clip is in the film.":"Add files to the project first.")),u&&i.querySelector(`[data-part="${CSS.escape(u)}"]`)?.focus(),u=null}return n.append(t("h2",{},"Storyboard"),i,g,t("h3",{class:"sb-head"},"Not used"),p,w),i.addEventListener("dragover",v),i.addEventListener("drop",y(null)),n.addEventListener("dragover",v),p.addEventListener("drop",x=>{let f=c(x);f?.part&&(x.preventDefault(),h(rs(l,f.part),null,"Left out of the film."))}),{load(x){l=wn(x),E()}}}var _o={matched:["\u2713","matched"],nearest:["\u2248","nearest"],cannot:["\u2717","can't"]};function Uo({id:n,where:o,state:a,off:r,onRead:l,onCancel:u,onToggle:i}){let p=`${o}-${n}`;if(a.status==="measuring"){let c=a.progress??0;return t("div",{class:"style-brief","aria-live":"polite"},t("p",{class:"note small"},`Reading its style\u2026 ${c}%`),t("progress",{max:100,value:c,"aria-label":"Reading the reference's style"}),t("button",{type:"button",class:"btn",id:`style-cancel-${p}`,onclick:u},"Cancel"))}if(a.status!=="ready")return t("div",{class:"style-brief"},t("button",{type:"button",class:"btn",id:`style-read-${p}`,onclick:l},"Read its style"),t("p",{class:"note small"},a.status==="failed"?`Couldn't read it: ${a.error??"the measure stopped"}`:"Measured on this computer, as numbers only: its cuts, transitions, captions, colour and sound. No picture, sound or words from it are kept."));let{lines:g,unread:w}=a.brief,h=g.map(c=>{let[v,y]=_o[c.state]??_o.cannot,E=`style-${p}-${c.id}`,x=c.set&&!c.locked?t("input",{type:"checkbox",id:E,checked:!r.has(c.id),onchange:L=>i(c.id,L.target.checked)}):t("span",{class:"style-fixed","aria-hidden":"true"}),f=t("span",{class:"style-text"},t("span",{class:`style-mark ${c.state}`,"aria-hidden":"true"},v),t("span",{class:"sr-only"},`${y}: `),c.text,c.gate?t("span",{class:"chip style-gate",title:"A quality gate outranks the reference here"},`gate: ${c.gate}`):null),P=c.why?t("span",{class:"style-why"},c.why):null;return t("li",{class:`style-row ${c.state}`},c.set&&!c.locked?t("label",{class:"style-label",for:E},x,t("span",{class:"style-body"},f,P)):t("div",{class:"style-label"},x,t("span",{class:"style-body"},f,P)))});return t("div",{class:"style-brief"},t("h3",{class:"style-head"},"From this reference"),t("ul",{class:"style-rows",id:`style-rows-${p}`},h),w.length?t("p",{class:"note small style-unread"},`Couldn't read: ${w.join(", ")}.`):null,t("button",{type:"button",class:"btn",id:`style-read-${p}`,onclick:l},"Read it again"))}function Ho({project:n,state:o,chosen:a,onAsk:r,onChoose:l}){let u=t("button",{type:"button",class:"btn wide",id:"openings-ask",disabled:o.status==="making",onclick:r},o.status==="ready"?"Three more openings":"Give me three openings");if(o.status==="making")return t("div",{class:"openings","aria-live":"polite"},u,t("p",{class:"note small"},`Drafting three openings\u2026 ${o.progress??0}%`),t("progress",{max:100,value:o.progress??0,"aria-label":"Drafting three openings"}));if(o.status!=="ready")return t("div",{class:"openings"},u,t("p",{class:"note small"},o.status==="failed"?`Couldn't draft them: ${o.error??"the drafts stopped"}`:"Three quick eight-second drafts, each starting on a different line. Pick one and the next make opens on it."));let i=String(o.job??"").split(".").at(-1),p=o.openings.map(g=>{let w=a===g.hook;return t("li",{class:`opening${w?" chosen":""}`},t("video",{class:"opening-film",src:`/projects/${encodeURIComponent(n)}/openings/${encodeURIComponent(i)}/${g.n}`,controls:!0,preload:"metadata",playsinline:!0,"aria-label":`Opening ${g.n+1}`}),t("p",{class:"opening-words"},t("span",{class:"opening-tag"},`${g.n+1} \xB7 ${g.seconds} s`)," ",`\u201C${g.words}\u201D`),t("button",{type:"button",class:`btn${w?" primary":""}`,id:`opening-use-${g.n}`,"aria-pressed":w?"true":"false",onclick:()=>l(w?null:g.hook)},w?"Chosen \u2713":"Open on this"))});return t("div",{class:"openings"},t("h3",{class:"openings-head"},"Openings"),t("ul",{class:"openings-wall",id:"openings-wall"},p),t("p",{class:"note small"},a?"The next make opens on the line you picked.":"Pick one, or keep the Director's choice."),u)}var ur=0;function is(n,{label:o,selected:a=n[0]?.key,onSelect:r=()=>{},className:l=""}={}){let u=`tabs-${++ur}`,i=null,p=new Map,g=new Map,w=new Map;for(let x of n){let f=t("span",{class:"tab-count"}),P=t("span",{class:"tab-badge",hidden:!0});w.set(x.key,f),g.set(x.key,P);let L=t("button",{type:"button",role:"tab",id:`${u}-${x.key}`,class:"tab","aria-controls":`${u}-${x.key}-panel`,"aria-selected":"false",tabindex:"-1",onclick:()=>E(x.key,{focus:!0})},t("span",{class:"tab-label"},x.label),f,P);p.set(x.key,L),Object.assign(x.panel,{id:`${u}-${x.key}-panel`}),x.panel.setAttribute("role","tabpanel"),x.panel.setAttribute("aria-labelledby",L.id),x.panel.classList.add("tab-panel")}let h=n.map(x=>x.key),c=t("div",{class:`tabs ${l}`.trim(),role:"tablist","aria-label":o,onkeydown:x=>{let f=h.indexOf(i),P={ArrowRight:f+1,ArrowDown:f+1,ArrowLeft:f-1,ArrowUp:f-1,Home:0,End:h.length-1}[x.key];P!==void 0&&(x.preventDefault(),x.stopPropagation(),E(h[(P+h.length)%h.length],{focus:!0}))}},...p.values());function v(){for(let x of n){let f=x.count?.();w.get(x.key).textContent=f==null?"":String(f)}}function y(x,f){let P=g.get(x);P&&(P.hidden=f===null||f===0||f===""||x===i,P.textContent=P.hidden?"":String(f),P.setAttribute("aria-label",P.hidden?"":`${f} new`))}function E(x,{focus:f=!1}={}){if(p.has(x)){i=x;for(let P of n){let L=P.key===x,H=p.get(P.key);H.setAttribute("aria-selected",String(L)),H.tabIndex=L?0:-1,P.panel.hidden=!L}y(x,null),f&&p.get(x).focus(),r(x)}}return v(),E(a),{strip:c,select:E,selected:()=>i,mark:y,refresh:v}}var qo=[{key:"picture",label:"Picture",colour:"--clip-picture"},{key:"overlays",label:"B-roll",colour:"--clip-broll"},{key:"audio",label:"Audio",colour:"--clip-audio"},{key:"captions",label:"Captions",colour:"--clip-caption"}],ke=44,zo=6,ls={mouse:6,touch:22},pr=8;function fr(n,o,{width:a,duration:r,pointer:l="mouse"}){if(!r)return null;let u=l==="touch"?ls.touch:ls.mouse,i=g=>g/r*a,p=new Map;for(let g of n){let w=p.get(g.clip)??{clip:g.clip,at:g.at,end:g.end};p.set(g.clip,{...w,at:Math.min(w.at,g.at),end:Math.max(w.end,g.end)})}for(let g of p.values()){let[w,h]=[i(g.at),i(g.end)];if(!(h-w<u*3)){if(o>=w&&o<w+u)return{clip:g.clip,edge:"in",at:g.at};if(o>=h-u&&o<h)return{clip:g.clip,edge:"out",at:g.end}}}return null}function hr(n,o,{width:a,duration:r}){let l=n,u=pr/a*r;for(let i of o)Math.abs(i-n)<=u&&([l,u]=[i,Math.abs(i-n)]);return l}var Jo=7056e5,Vo=(n,o)=>Math.min(99,Math.max(0,Math.floor(n/Jo/o))),mr=n=>(n?.picture??[]).filter(o=>o.enter).map(o=>({at:o.at,kind:o.enter.kind}));function cs({root:n,compact:o=!1,onSeek:a,onSelect:r=()=>{},onTrim:l,rich:u=null}){let i=o?qo.slice(0,1):qo,p=t("canvas",{class:"lanes","aria-hidden":"true"}),g=o?null:t("div",{class:"lane-labels","aria-hidden":"true"},i.map(m=>t("div",{class:"lane-label"},m.label))),w=t("ul",{class:"clip-list","aria-label":o?"Story":"Clips on the timeline"}),h=!!u&&!o,c=null,v=new Map,y=h?t("canvas",{class:"tl-frame",width:96,height:54}):null,E=h?t("span",{class:"tl-time"}):null,x=h?t("div",{class:"tl-tip","aria-hidden":"true",hidden:!0},y,E):null;x&&n.classList.add("rich"),n.append(...[g,t("div",{class:"lanes-wrap"},p,x),w].filter(Boolean));let f=p.getContext("2d"),P={picture:[],overlays:[],audio:[],captions:[]},L=0,H={n:30,d:1},q=0,te=[],V=[],B=new Map,D=null,ce=null,de=!!l&&!o,oe=[],X=null,K=m=>getComputedStyle(n).getPropertyValue(m).trim()||"#888";function le(){let m=Math.max(1,p.clientWidth),S=i.length*(ke+zo),N=window.devicePixelRatio||1;(p.width!==Math.round(m*N)||p.height!==Math.round(S*N))&&(p.width=Math.round(m*N),p.height=Math.round(S*N),p.style.height=`${S}px`),f.setTransform(N,0,0,N,0,0),f.clearRect(0,0,m,S);let F=T=>L?T/L*m:0;i.forEach((T,j)=>{let R=j*(ke+zo);f.fillStyle=K("--lane"),f.fillRect(0,R,m,ke);for(let G of P[T.key]??[]){let W=F(G.at),ae=Math.max(2,F(G.end)-W);f.fillStyle=K(T.colour),f.fillRect(W,R+2,ae-1,ke-4),h&&(T.key==="picture"||T.key==="overlays")&&me(G,W,ae,R),h&&T.key==="picture"&&Q(G,W,ae,R),G.clip&&G.clip===D&&(f.strokeStyle=K("--focus"),f.lineWidth=2,f.strokeRect(W+1,R+3,ae-3,ke-6));let ue=T.key==="audio"||o&&T.key==="picture"?B.get(G.asset):null;if(ue&&G.in!==void 0){f.fillStyle=K("--wave");let se=G.out-G.in;for(let he=0;he<ae;he++){let Le=(G.in+se*he/ae)/7056e5,Dt=(ue.peaks[Math.floor(Le*ue.perSecond)]??0)*(ke-8);f.fillRect(W+he,R+ke/2-Dt/2,1,Math.max(1,Dt))}}}if(T.key==="picture"&&ce){f.strokeStyle=K("--ghost"),f.setLineDash([5,4]),f.lineWidth=2;let G=Math.max(L,ce.duration)||1;for(let W of ce.picture)f.strokeRect(W.at/G*m+1,R+6,Math.max(2,(W.end-W.at)/G*m-2),ke-12);f.setLineDash([])}if(T.key==="picture"){f.fillStyle=K("--shot");for(let G of te)f.fillRect(F(G.at)-.5,R,1,8)}if(h&&T.key==="picture")for(let G of mr(c))re(F(G.at),R,G.kind);if(h&&T.key==="audio"&&c?.audio?.duck?.curve?.length&&ne(c.audio.duck,R,m),T.key==="picture"&&de){f.fillStyle=K("--ink-2");for(let G of P.picture){let[W,ae]=[F(G.at),F(G.end)];ae-W<ls.mouse*3||(P.picture.some(ue=>ue.clip===G.clip&&ue.end===G.at)||f.fillRect(W+1,R+ke/2-8,2,16),P.picture.some(ue=>ue.clip===G.clip&&ue.at===G.end)||f.fillRect(ae-3,R+ke/2-8,2,16))}X&&(f.fillStyle=K("--focus"),f.fillRect(F(X.at)-1,R,3,ke))}}),f.fillStyle=K("--playhead");for(let T of V)f.fillRect(F(T.at)-1,0,3,8);f.fillStyle=K("--playhead"),f.fillRect(F(q)-1,0,2,S)}function me(m,S,N,F){if(!m.asset||m.in===void 0||N<24)return;let T=u.thumbs(m.asset),j=T&&v.get(T.url);if(!T)return;if(!j)return z(T.url);if(!j.naturalWidth)return;let[R,G]=[j.naturalWidth/10,j.naturalHeight/10],W=Math.max(24,Math.round((ke-4)*R/G)),ae=(m.out??m.end-m.at+m.in)-m.in;f.save(),f.beginPath(),f.rect(S,F+2,N-1,ke-4),f.clip(),f.globalAlpha=.85;for(let ue=0;ue<N;ue+=W){let se=Vo(m.in+ae*Math.min(N,ue+W/2)/N,T.every);f.drawImage(j,se%10*R,Math.floor(se/10)*G,R,G,S+ue,F+2,W,ke-4)}f.restore()}function ve(m){let S=P.picture.find(se=>m>=se.at&&m<se.end),N=S?.asset&&S.in!==void 0?u.thumbs(S.asset):null,F=N&&v.get(N.url);if(!N)return!1;if(!F)return z(N.url),!1;if(!F.naturalWidth)return!1;let{n:T,d:j}=typeof S.speed=="object"?S.speed:{n:1,d:1},R=Vo(S.in+(m-S.at)*T/j,N.every),[G,W]=[F.naturalWidth/10,F.naturalHeight/10],ae=y.getContext("2d"),ue=Math.max(y.width/G,y.height/W);return ae.drawImage(F,R%10*G,Math.floor(R/10)*W,G,W,(y.width-G*ue)/2,(y.height-W*ue)/2,G*ue,W*ue),!0}function z(m){if(v.has(m))return;let S=new Image;v.set(m,S),S.addEventListener("load",le,{once:!0}),S.src=m}function Q(m,S,N,F){c?.picture?.find(j=>j.asset===m.asset&&j.at<m.end&&m.at<j.end&&(j.grade||j.fx||j.lut))&&(f.fillStyle=K("--saffron"),f.fillRect(S,F+ke-5,N-1,3))}function re(m,S,N){let T=S+ke/2;f.fillStyle=K("--sheet"),f.strokeStyle=K("--ink"),f.lineWidth=1.5,f.beginPath(),f.arc(m,T,8,0,Math.PI*2),f.fill(),f.stroke(),f.fillStyle=K("--ink"),f.beginPath(),N==="wipe"?f.rect(m-4,T-4,4,8):N==="slide"?(f.moveTo(m-3,T-4),f.lineTo(m+4,T),f.lineTo(m-3,T+4)):N==="zoom"?(f.arc(m,T,4,0,Math.PI*2),f.arc(m,T,2,0,Math.PI*2,!0)):(f.moveTo(m-4,T-4),f.lineTo(m,T),f.lineTo(m-4,T+4),f.moveTo(m+4,T-4),f.lineTo(m,T),f.lineTo(m+4,T+4)),f.fill("evenodd")}function ne(m,S,N){f.strokeStyle=K("--ghost"),f.lineWidth=1.5,f.beginPath();let F=Math.max(1,Math.floor(m.curve.length/N));for(let T=0;T<m.curve.length;T+=F){let j=L?T/m.rate*Jo/L*N:0,R=S+4+(1-m.curve[T])*(ke-8);T===0?f.moveTo(j,R):f.lineTo(j,R)}f.stroke()}let pe=!1,Z=m=>{let S=p.getBoundingClientRect();a(Math.round(Math.min(1,Math.max(0,(m.clientX-S.left)/S.width))*L))},Be=m=>{if(!de)return null;let S=p.getBoundingClientRect();return m.clientY-S.top>ke?null:fr(P.picture,m.clientX-S.left,{width:S.width,duration:L,pointer:m.pointerType==="touch"?"touch":"mouse"})},fe=m=>{let S=p.getBoundingClientRect(),N=Math.round(Math.min(1,Math.max(0,(m.clientX-S.left)/S.width))*L);X={...X,at:hr(N,oe,{width:S.width,duration:L})},le()};p.addEventListener("pointerdown",m=>{p.setPointerCapture(m.pointerId);let S=Be(m);if(S)return X={...S,from:S.at},le();pe=!0,Z(m)}),p.addEventListener("pointermove",m=>{if(x&&m.pointerType!=="touch"){let S=p.getBoundingClientRect(),N=Math.round(Math.min(1,Math.max(0,(m.clientX-S.left)/S.width))*L);E.textContent=_e(N,H),y.hidden=!ve(N),x.hidden=!1;let F=x.offsetWidth/2;x.style.left=`${Math.min(S.width-2*F,Math.max(0,m.clientX-S.left-F))}px`}if(X)return fe(m);if(pe)return Z(m);de&&(p.style.cursor=Be(m)?"ew-resize":"")}),p.addEventListener("pointerup",()=>{if(pe=!1,!X)return;let m=X;X=null,le(),m.at!==m.from&&l({clip:m.clip,edge:m.edge,at:m.at})}),de&&p.addEventListener("pointercancel",()=>{pe=!1,X=null,le()}),x&&p.addEventListener("pointerleave",()=>x.hidden=!0),new ResizeObserver(le).observe(p);function Me(m){D=m;for(let S of w.querySelectorAll("button"))S.setAttribute("aria-pressed",String(S.dataset.clip===m));r(m),le()}return{load(m,{duration:S,fps:N,marks:F=[],pins:T=[]}){V=T,P=m,L=S,H=N,te=F,D&&!P.picture.some(j=>j.clip===D)&&(D=null),J(w);for(let j of P.picture.filter((R,G,W)=>W.findIndex(ae=>ae.clip===R.clip)===G)){let R=t("button",{type:"button","aria-pressed":String(j.clip===D),dataset:{clip:j.clip},onclick:()=>(Me(j.clip),a(j.at))},`Clip ${j.clip}, ${_e(j.at,H)} to ${_e(j.end,H)}`);w.append(t("li",{},R))}le()},setPeaks(m,S){B.set(m,S),le()},setGhost(m){ce=m,le()},setPreview(m){c=m,le()},setSnaps(m){oe=m},setTime(m){q=m,le()},select:Me,get selected(){return D},draw:le}}var Qo=new Set(["filler","stutter","restart"]);function Yo({root:n,onSeek:o,onCut:a,onFix:r=async()=>{}}){let l=[],u=new Map,i=null,p=[],g=null,w=()=>{for(let c of n.querySelectorAll(".word[aria-pressed='true']"))c.setAttribute("aria-pressed","false");for(let c of p)n.querySelector(`[data-word="${CSS.escape(c)}"]`)?.setAttribute("aria-pressed","true")};n.addEventListener("click",c=>{let v=c.target.closest(".word");if(!v)return;let y=u.get(v.dataset.word);if(c.shiftKey&&i){let[E,x]=[l.indexOf(i),l.indexOf(y)].sort((f,P)=>f-P);p=l.slice(E,x+1).filter(f=>f.asset===y.asset).map(f=>f.id)}else i=y,p=[y.id],o(y);w()});function h(c){let v=u.get(c.dataset.word);if(!v)return;let y=t("input",{class:"word-edit",value:v.text,size:String(Math.max(4,v.text.length+2)),maxlength:"60","aria-label":`Fix the word "${v.text}"`});c.replaceWith(y),y.focus(),y.select();let E=!1,x=async f=>{if(E)return;E=!0;let P=y.value.trim();y.replaceWith(c),f&&P&&P!==v.text?await r(v,P):c.focus()};y.addEventListener("keydown",f=>{f.stopPropagation(),f.key==="Enter"?(f.preventDefault(),x(!0)):f.key==="Escape"&&(f.preventDefault(),x(!1))}),y.addEventListener("blur",()=>x(!0))}return n.addEventListener("dblclick",c=>{let v=c.target.closest(".word");v&&h(v)}),n.addEventListener("keydown",c=>{if(c.key==="F2"&&c.target.closest(".word"))return c.preventDefault(),c.stopPropagation(),h(c.target.closest(".word"));(c.key==="Backspace"||c.key==="Delete")&&p.length&&(c.preventDefault(),c.stopPropagation(),a(u.get(p[0]),u.get(p.at(-1))))}),{load({words:c=[],sentences:v=[],takes:y=[]}){l=c,u=new Map(c.map(f=>[f.id,f])),p=p.filter(f=>u.has(f));let E=new Map(y.map(f=>[f.sentence,f]));if(J(n),!c.length){n.append(t("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let x=v.length?v:[...new Set(c.map(f=>f.asset))].map(f=>{let P=c.filter(L=>L.asset===f);return{id:null,asset:f,firstWord:P[0].id,lastWord:P.at(-1).id,score:1}});for(let f of x){let P=E.get(f.id),L=P&&P.rank>1||f.score===0,H=Number(f.firstWord.split(":w")[1]),q=Number(f.lastWord.split(":w")[1]),te=t("p",{class:`sentence${L?" lost":""}`,dataset:f.id?{sentence:f.id}:{}});P&&te.append(t("span",{class:"tag"},P.rank===1?"best take":`take ${P.rank}`));for(let V=H;V<=q;V++){let B=u.get(`${f.asset}:w${V}`);if(!B)continue;let D=L||B.flags.some(X=>Qo.has(X)),ce=D?`${B.text} (${L?"retake":B.flags.filter(X=>Qo.has(X)).join(", ")})`:null,de=typeof B.heard=="string",oe=t("button",{type:"button",class:`word${D?" struck":""}${!de&&B.flags.includes("low_confidence")?" unsure":""}${de?" fixed":""}`,"aria-pressed":"false","aria-label":ce??(de?`${B.text} (fixed; heard as ${B.heard})`:null),title:de?`Heard as "${B.heard}". Double-click to change.`:"Double-click to fix this word",dataset:{word:B.id}});oe.textContent=B.text,te.append(oe," ")}n.append(te)}w()},playing(c){c!==g&&(n.querySelector(".word.now")?.classList.remove("now"),g=c,c&&n.querySelector(`[data-word="${CSS.escape(c)}"]`)?.classList.add("now"))},words:()=>l,selection:()=>p.length?[p[0],p.at(-1)]:null,clear(){p=[],i=null,w()}}}var ds={format:"Format",seconds:"Length",captions:"Captions",grade:"Look",music:"Music",cleanVoice:"Clean the voice",cutSound:"Sound on each cut",introSound:"Sound into the story",punches:"Punch-ins",angles:"Two angles from one camera",broll:"B-roll from your clips",titles:"Title cards",ramps:"Speed ramps",transition:"Transitions"};function Nt(n,o){return typeof o=="boolean"?o?"yes":"no":n==="seconds"?`${o} seconds`:n==="punches"?`${o}`:o==="none"?"none":String(o)}function Xo(n){let o=`${ds[n.field]??n.field}: ${Nt(n.field,n.value)}`,a=n.evidence?` (you said "${n.evidence}")`:"",r=n.by==="code"&&n.model!==void 0?`; read by Kriya's code, not as ${Nt(n.field,n.model)}`:"";return`${o}${a}${r}`}function Zo(n,o,a){return o==="music"?a==="none"||a==="reference"?delete n.music:n.music=`generated:${a}`:o==="transition"?a==="none"?(delete n.transition,delete n.transitionAll):n.transition=a:typeof a=="boolean"?a?n[o]=!0:delete n[o]:o==="broll"?a==="own"?n.broll="own":delete n.broll:{captions:"none",grade:"natural",cutSound:"none",introSound:"none"}[o]===a?delete n[o]:n[o]=a,n}var us=document.getElementById("app"),ea=["direct","edit","finish"],Se=(n,o)=>{try{if(o===void 0)return localStorage.getItem(n);localStorage.setItem(n,o)}catch{return null}},gr=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function ta(...n){let o=gr();return t("header",{class:"bar"},o?t("a",{class:"btn ghost",href:o},"\u2190 Kriya Harness"):t("span",{class:"brand"},"Kriya"),t("span",{class:"title"},"Editing Studio"),...n)}function vn(n){J(us).append(t("main",{class:"center"},t("h1",{},"Open the Studio from Kriya"),t("p",{},n??"Click Editing Studio in Kriya Harness, or run kriya edit and open its link.")))}function br(n){return new Promise(o=>{let a=t("ul",{class:"folders","aria-label":"Folders"}),r=t("p",{class:"label-mono where"}),l=t("p",{class:"note",role:"status"}),u=t("input",{class:"field",placeholder:"New folder name","aria-label":"New folder name",maxlength:"80"}),i=null,p=h=>{w.close(),w.remove(),o(h)};async function g(h){try{let c=await Y("GET",`/browse${h?`?root=${encodeURIComponent(h)}`:""}`);i=c.root,r.textContent=c.root,J(a),c.parent&&a.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>g(c.parent)},"\u2191 Up")));let v=c.entries.filter(y=>y.kind==="folder");for(let y of v)a.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>g(`${c.root}/${y.name}`)},`\u{1F4C1} ${y.name}`)));v.length||a.append(t("li",{class:"note"},"No folders here.")),l.textContent=""}catch(c){l.textContent=c.message}}let w=t("dialog",{class:"picker","aria-label":"Choose a folder"},t("h2",{},"Choose a folder"),r,a,t("form",{class:"row tight",onsubmit:async h=>{h.preventDefault();try{let{folder:c}=await Y("POST","/browse/folder",{parent:i,name:u.value});u.value="",await g(c)}catch(c){l.textContent=c.message}}},u,t("button",{type:"submit",class:"btn"},"New folder")),l,t("div",{class:"row end"},t("button",{type:"button",class:"btn",onclick:()=>p(null)},"Cancel"),t("button",{type:"button",class:"btn primary",onclick:()=>p(i)},"Use this folder")));w.addEventListener("cancel",h=>(h.preventDefault(),p(null))),document.body.append(w),w.showModal(),g(n)})}async function na(){let n;try{({projects:n}=await Y("GET","/projects"))}catch(g){return g.status===401?vn():vn(g.message)}let o=t("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),a=t("input",{id:"new-folder",class:"field",required:!0,readonly:!0,placeholder:"Choose a folder\u2026"}),r=t("button",{type:"button",class:"btn",onclick:()=>br(a.value||null).then(g=>g&&(a.value=g,l.textContent=""))},"Choose\u2026"),l=t("p",{class:"note",role:"status"}),u=t("form",{class:"panel new",onsubmit:async g=>{if(g.preventDefault(),!a.value)return l.textContent="Choose a folder for the project first.";try{let{id:w}=await Y("POST","/projects",{name:o.value.trim(),folder:a.value.trim()});location.hash=`#/p/${w}`}catch(w){l.textContent=w.message}}},t("h2",{},"New project"),t("label",{for:"new-name"},"Name"),o,t("label",{for:"new-folder"},"Folder for the project (its footage stays where it is)"),t("div",{class:"row tight"},a,r),t("button",{class:"btn primary",type:"submit"},"Create"),l),i=t("section",{class:"panel taste","aria-label":"Your taste"}),p=async g=>{let{proposed:w,confirmed:h}=g??await Y("GET","/taste"),c=(v,y)=>async()=>p(await Y("POST",`/taste/${encodeURIComponent(v)}/${y}`));J(i).append(t("h2",{},"Your taste"),...w.length||h.length?[]:[t("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...w.map(v=>t("div",{class:"taste-row"},t("p",{},v.sentence),t("button",{type:"button",class:"btn primary",onclick:c(v.key,"confirm")},"Use it"),t("button",{type:"button",class:"btn",onclick:c(v.key,"dismiss")},"No"))),...h.map(v=>t("div",{class:"taste-row"},t("p",{},v.shown),t("button",{type:"button",class:"btn","aria-label":`Remove the rule ${v.shown}`,onclick:c(v.key,"remove")},"Remove"))))};p().catch(()=>{}),J(us).append(ta(),t("main",{class:"home"},t("h1",{},"What are we making?"),t("section",{class:"panel"},t("h2",{},"Projects"),n.length?t("ul",{class:"projects"},n.map(g=>t("li",{class:"project-row"},t("a",{class:"btn open",href:`#/p/${g.id}`},g.name),t("button",{type:"button",class:"btn ghost danger","aria-label":`Delete the project ${g.name}`,onclick:async()=>{if(confirm(`Delete "${g.name}" from the Studio?
1
+ var fn=n=>n.path.split(/[\\/]/).at(-1),jt=n=>n.label??fn(n),Pt=n=>String(n??"").toLocaleLowerCase();function Ys(n,o,a){let r=Pt(a).split(/\s+/).filter(Boolean);if(!r.length)return n;let l=new Map;for(let u of o??[])l.set(u.asset,`${l.get(u.asset)??""} ${Pt(u.text)} ${Pt(u.heard)}`);return n.filter(u=>{let i=`${Pt(u.label)} ${Pt(fn(u))} ${l.get(u.id)??""}`;return r.every(p=>i.includes(p))})}var Xs={added:"Order added",recorded:"Date recorded",length:"Length",name:"Name"};function Zs(n,o){let a=[...n];return o==="recorded"?a.sort((r,l)=>(r.recorded??"\uFFFF").localeCompare(l.recorded??"\uFFFF")):o==="length"?a.sort((r,l)=>(l.facts?.duration??0)-(r.facts?.duration??0)):o==="name"?a.sort((r,l)=>jt(r).localeCompare(jt(l),void 0,{numeric:!0,sensitivity:"base"})):a}var eo={none:"No groups",folder:"By folder",day:"By day recorded"},Wa=n=>n.path.split(/[\\/]/).slice(0,-1).join("/")||"Project folder",_a=n=>n.recorded?n.recorded.slice(0,10):"No date";function to(n,o){if(o!=="folder"&&o!=="day")return[{name:null,assets:n}];let a=new Map;for(let r of n){let l=o==="folder"?Wa(r):_a(r);a.set(l,[...a.get(l)??[],r])}return[...a].map(([r,l])=>({name:r,assets:l}))}var no=60;function so(n,o,a,r=4){let l=0,u=n.length,i=n.length;for(let[h,c]of n.entries()){if(u===n.length&&l+c>o&&(u=h),l>=o+a){i=h;break}l+=c}let p=Math.max(0,u-r),g=Math.min(n.length,i+r),w=h=>h.reduce((c,v)=>c+v,0);return{start:p,end:g,before:w(n.slice(0,p)),after:w(n.slice(g))}}function t(n,o={},...a){let r=document.createElement(n);for(let[l,u]of Object.entries(o??{}))u==null||u===!1||(l.startsWith("on")?r.addEventListener(l.slice(2),u):l==="class"?r.className=u:l==="dataset"?Object.assign(r.dataset,u):u===!0?r.setAttribute(l,""):r.setAttribute(l,String(u)));for(let l of a.flat())l!=null&&l!==!1&&r.append(l instanceof Node?l:String(l));return r}var J=n=>(n.replaceChildren(),n);async function Y(n,o,a){let r=await fetch(o,{method:n,headers:a===void 0?{}:{"content-type":"application/json"},body:a===void 0?void 0:JSON.stringify(a),credentials:"same-origin"}),l=await r.json().catch(()=>({}));if(!r.ok){let u=new Error(l.message??`The Edit Host answered ${r.status}.`);throw u.status=r.status,u.value=l,u}return l}var Ne=n=>7056e5*n.d/n.n,oo=(n,o)=>Math.floor(n/Ne(o)+1e-9),wt=(n,o)=>Math.round(oo(n,o)*Ne(o));function _e(n,o){let a=Math.max(0,n)/7056e5,r=Math.floor(a/60),l=Math.floor(a%60),u=oo(Math.max(0,n)-Math.floor(a)*7056e5,o);return`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}.${String(u).padStart(2,"0")}`}function ao(n,{shift:o=!1,mod:a=!1}={}){if(a)return n==="z"||n==="Z"?{type:o?"redo":"undo"}:null;switch(n){case" ":return{type:"toggle"};case"k":case"K":return{type:"rate",rate:0};case"l":case"L":return{type:"faster"};case"j":case"J":return{type:"reverse"};case"ArrowRight":return{type:"step",frames:o?null:1,seconds:o?1:null};case"ArrowLeft":return{type:"step",frames:o?null:-1,seconds:o?-1:null};case"Home":return{type:"seek",t:0};case"1":return{type:"mode",mode:"direct"};case"2":return{type:"mode",mode:"edit"};case"3":return{type:"mode",mode:"finish"};case"/":return{type:"prompt"};case"s":case"S":return{type:"split"};case"Backspace":case"Delete":return{type:"delete"};case"i":case"I":return{type:"mark",edge:"in"};case"o":case"O":return{type:"mark",edge:"out"};default:return null}}function ro(n,o,{fps:a,duration:r}){let l=Math.max(0,r-Ne(a)),u=i=>Math.min(Math.max(0,Math.round(i)),l);switch(o.type){case"toggle":return{...n,rate:n.rate===0?1:0};case"rate":return{...n,rate:o.rate};case"faster":return{...n,rate:n.rate<=0?1:2};case"reverse":return{...n,rate:n.rate>=0?-1:-2};case"step":{let i=o.frames!==null?o.frames*Ne(a):o.seconds*7056e5;return{rate:0,t:u(wt(n.t,a)+i)}}case"seek":return{...n,t:u(o.t)};case"tick":{let i=u(o.t);return{t:i,rate:i===0&&n.rate<0||i===l&&n.rate>0?0:n.rate}}default:return n}}var Ha=(n,o,a)=>.2126*n+.7152*o+.0722*a;function Ua(n,o=128){let a=new Uint32Array(256),r=Array.from({length:o},()=>new Uint32Array(64)),{data:l,width:u,height:i}=n,p=Math.max(1,Math.floor(u*i/6e4));for(let g=0,w=0;w<u*i;w+=p,g=w*4){let h=Math.min(255,Math.round(Ha(l[g],l[g+1],l[g+2])));a[h]++,r[Math.min(o-1,Math.floor(w%u/u*o))][h>>2]++}return{histogram:a,waveform:r}}var qa={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you: a check failed",not_checked:"Not checked"},za={"QG-01":"Playable and to spec","QG-02":"Length","QG-03":"Sync","QG-04":"Round-trip speech","QG-05":"Cut hygiene","QG-06":"Loudness","QG-07":"Picture health","QG-08":"Layout","QG-09":"Legibility","QG-10":"Copy","QG-11":"Motion","QG-12":"Brief","QG-13":"Rights","QG-14":"Blind reviewer","QG-15":"Assembly","QG-16":"Reference fit"},Va={passed:"Passed",failed:"Failed",not_checked:"Not checked",not_applicable:"Not applicable"};function Ja(n){if(!n||!Array.isArray(n.gates)||!n.gates.length)return null;let o=n.gates.map(i=>({id:String(i.id),name:za[i.id]??String(i.id),status:i.status==="failed"&&i.severity==="note"?"note":String(i.status),said:i.status==="failed"&&i.severity==="note"?"Note":Va[i.status]??String(i.status),message:typeof i.message=="string"?i.message:"",...Number.isFinite(i.at)&&i.at>=0&&i.status==="failed"?{at:i.at}:{}})),a=o.filter(i=>i.status==="passed").length,r=o.filter(i=>i.status==="failed").length,l=[...(n.repairs??[]).map(i=>`Repair round ${i.round}: ${(i.fixes??[]).map(p=>p.why??p.kind).join("; ")||"no fix"}${i.accepted?", kept":`, not kept${i.reason?` (${i.reason})`:""}`}.`),...(n.watch?.rounds??[]).map(i=>`Watch round ${i.round}: ${(i.fixes??[]).join(", ")||"no fix"}${i.kept?", kept":`, not kept${i.reason?` (${i.reason})`:""}`}.`)],u=o.length-a-r;return{summary:`${a} passed, ${r} failed${u?`, ${u} not checked or not applicable`:""}`,gates:o,repairs:l}}function io({root:n,finalRoot:o,pixels:a,project:r,onAdjust:l=()=>{},scorecard:u=!1,head:i=()=>null,onShow:p=()=>{}}){let g=t("video",{class:"final-film",controls:!0,preload:"metadata",playsinline:!0,"aria-label":"The final cut"}),w=t("p",{class:"note",role:"status"}),h=t("select",{id:"final-pick",class:"field select","aria-label":"Which film",onchange:()=>x()}),c=t("a",{class:"btn primary",href:"#",download:"",hidden:!0},"Download"),v=[],y=z=>`/projects/${r().id}/renders/${z.job}`,E=z=>z?new Date(z).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";function x(){let z=v.find(ne=>String(ne.job)===h.value)??v[0];if(!z){g.removeAttribute("src"),g.hidden=!0,c.hidden=!0,h.hidden=!0,w.textContent="No film yet. Render a draft and the finished cut plays here, captions, look, music and sound included.";return}g.hidden=!1,h.hidden=v.length<2;let Q=y(z);g.getAttribute("src")!==Q&&(g.src=Q),c.hidden=!1,c.href=`${Q}?download=1`,c.setAttribute("download",z.name);let re=z.current?"This is your edit as it is now.":"Made before your latest changes: render a draft to see them.";w.textContent=`${re}${z.verdict?` ${qa[z.verdict]??z.verdict}.`:""}`,w.classList.toggle("stale",!z.current)}let f=0,P=0;async function L(){let z=++f,Q=(await Y("GET",`/projects/${r().id}/renders`)).renders;if(z!==f)return;let re=h.value;v=Q;let ne=v[0]?.job??0;J(h).append(...v.map(pe=>t("option",{value:String(pe.job)},`${pe.quality==="draft"?"Draft":"Master"} \xB7 ${E(pe.at)}${pe.current?" \xB7 current":""} \xB7 ${pe.name}`))),h.value=String(ne>P||!v.some(pe=>String(pe.job)===re)?ne:re),P=Math.max(P,ne),x()}o.append(t("section",{class:"panel final","aria-label":"Final cut"},t("h2",{},"Final cut"),g,w,t("div",{class:"row"},h,c,t("button",{type:"button",class:"btn",onclick:()=>B("draft")},"Render again"),t("button",{type:"button",class:"btn",onclick:l},"Adjust in Edit"))));let U=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),q=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),te=t("ul",{class:"jobs","aria-live":"polite"}),V=t("p",{class:"note",role:"status"}),B=async z=>{V.textContent="";try{await Y("POST","/jobs",{project:r().id,quality:z}),ve()}catch(Q){V.textContent=Q.message}},D=t("p",{class:"note",role:"status"}),ce=t("ul",{class:"jobs","aria-label":"Handoff files"}),de=async()=>{D.textContent="",J(ce);try{let z=await Y("POST",`/projects/${r().id}/export/handoff`),Q=z.chapters.length,re=Q?`, ${Q} chapter${Q===1?"":"s"}`:"";D.textContent=`Written to ${z.folder}, with ${z.media} media file${z.media===1?"":"s"} linked${re}.`;for(let ne of z.files)ce.append(t("li",{},t("span",{class:"file"},ne)));for(let ne of z.omitted)ce.append(t("li",{},t("span",{class:"label-mono"},ne.format),` ${ne.reason}`))}catch(z){D.textContent=z.message}},oe=u?t("details",{class:"panel scorecard"},t("summary",{},t("span",{class:"score-title"},"Quality checks"),t("span",{class:"score-sum"},"No make yet"))):null,X=u?t("div",{class:"score-body"}):null;oe?.append(X);function G(z){if(!oe)return;let Q=z.filter(Z=>Z.project===r().id&&Z.kind==="make"&&Z.status==="done").at(-1),re=null;try{re=Q?JSON.parse(Q.output):null}catch{}let ne=Ja(re),pe=re?.head!=null&&re.head===i();if(oe.querySelector(".score-sum").textContent=ne?ne.summary:"No make yet",J(X),!ne)return X.append(t("p",{class:"note"},"Make it in Brief and each check the film went through is listed here."));X.append(t("ul",{class:"score-gates"},ne.gates.map(Z=>t("li",{class:`score-row ${Z.status}`},t("span",{class:"score-id label-mono"},Z.id),t("span",{class:"score-name"},Z.name),t("span",{class:"score-status"},Z.said),Z.message?t("span",{class:"score-msg"},Z.message):null,pe&&Z.at!==void 0?t("button",{type:"button",class:"btn small score-show",onclick:()=>p(Z.at)},`Show ${Z.id} at ${_e(Z.at,r().canvas.fps)}`):null))),...ne.repairs.length?[t("p",{class:"score-head"},"Repairs"),t("ul",{class:"score-repairs"},ne.repairs.map(Z=>t("li",{},Z)))]:[],t("p",{class:"note small"},"Measured on the rendered master by code, never by a model's say-so."))}n.append(...oe?[oe]:[],t("section",{class:"panel scopes","aria-label":"Scopes"},t("h2",{},"Scopes"),t("div",{class:"scope-row"},t("figure",{},U,t("figcaption",{},"Histogram")),t("figure",{},q,t("figcaption",{},"Waveform"))),t("p",{class:"note"},"Measured on the preview: 8-bit, from the proxy.")),t("section",{class:"panel export","aria-label":"Export"},t("h2",{},"Export"),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:()=>B("draft")},"Render a draft"),t("button",{type:"button",class:"btn primary",onclick:()=>B("master")},"Render the master")),t("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),V,te),t("section",{class:"panel handoff","aria-label":"Handoff"},t("h2",{},"Handoff"),t("p",{class:"note"},"For Premiere, Resolve or Final Cut: the cut as OTIO, FCPXML, EDL and SRT, with chapters, and the media linked beside them."),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:de},"Export for another editor")),D,ce));function le(z,Q){let re=z.getContext("2d");re.clearRect(0,0,z.width,z.height),re.fillStyle=getComputedStyle(n).getPropertyValue("--scope").trim()||"#6cc0b8",Q(re)}function me(){let z=a();if(!z)return;let{histogram:Q,waveform:re}=Ua(z),ne=Math.max(1,...Q);le(U,pe=>Q.forEach((Z,Be)=>pe.fillRect(Be,100-Z/ne*100,1,Z/ne*100))),le(q,pe=>re.forEach((Z,Be)=>Z.forEach((fe,Me)=>{fe&&(pe.globalAlpha=Math.min(1,.15+fe/200),pe.fillRect(Be*2,100-Me/64*100-2,2,2))})))}async function ve(){L().catch(Q=>w.textContent=Q.message);let{jobs:z}=await Y("GET","/jobs");G(z),J(te);for(let Q of z.filter(re=>re.project===r().id&&re.kind==="render").reverse().slice(0,8)){let re=Q.output?Q.output.split(/[\\/]/).at(-1):null;te.append(t("li",{},t("span",{class:"label-mono"},Q.status),` ${Q.progress}%`,re?t("span",{class:"file"},` ${re}`):null,Q.error?t("span",{class:"error"},` ${Q.error}`):null))}}return{scopes:me,refresh:ve}}var De="application/x-kriya-clip",uo=/(?<![\p{L}\p{N}])@(\d{1,3})(?: (\d+:\d{2}(?:\.\d)?)–(\d+:\d{2}(?:\.\d)?))?/gu;function kt(n){let o=Math.round(Math.max(0,n)*10/7056e5),a=Math.floor(o/10);return`${Math.floor(a/60)}:${String(a%60).padStart(2,"0")}${o%10?`.${o%10}`:""}`}var lo=n=>{let[o,a]=n.split(":");return Math.round((Number(o)*60+Number(a))*7056e5)},co=(n,o)=>`@${n}${o?` ${kt(o.from)}\u2013${kt(o.to)}`:""}`;function Qa(n,o){let a=/(?:^|[^\p{L}\p{N}@])@([\p{L}\p{N}]*)$/u.exec(n.slice(0,o));return a?{start:o-a[1].length-1,query:a[1]}:null}function Ya(n,o){let a=o.toLocaleLowerCase();if(!a)return n.slice(0,8);let r=n.filter(u=>String(u.number).startsWith(a)),l=n.filter(u=>!r.includes(u)&&u.name.toLocaleLowerCase().includes(a));return[...r,...l].slice(0,8)}function Rt(n){let o=t("span",{class:`thumb${n?.thumb?.sheet?" sheet":""}`,"aria-hidden":"true"},n?.thumb?null:"\u266A");return n?.thumb&&(o.style.backgroundImage=`url("${n.thumb.url}")`),o}function po(n){let o=[],a=0;for(let r of n.matchAll(uo))r.index>a&&o.push({text:n.slice(a,r.index)}),o.push({text:r[0],number:Number(r[1])}),a=r.index+r[0].length;return a<n.length&&o.push({text:n.slice(a)}),o}function Xa(n,o,a=new Map){let r=[];return{text:n.replace(uo,(u,i,p,g)=>{let w=o.find(c=>c.number===Number(i));if(!w)return u;let h=a.get(u)??(p?{from:lo(p),to:lo(g)}:null);return r.push({asset:w.asset,...h?{from:h.from,to:h.to}:{}}),`\u27E6${r.length}\u27E7`}),mentions:r}}function fo({input:n,clips:o}){let a=t("ul",{class:"mention-list",id:"mention-list",role:"listbox","aria-label":"Clips to mention",hidden:!0}),r=new Map,l=[],u=0,i=null;n.setAttribute("aria-controls","mention-list"),n.setAttribute("aria-autocomplete","list"),n.setAttribute("aria-expanded","false");let p=()=>{i=null,a.hidden=!0,a.replaceChildren(),n.setAttribute("aria-expanded","false"),n.removeAttribute("aria-activedescendant")},g=(y,E,x)=>{n.setRangeText(y,E,x,"end"),n.focus()},w=y=>{y&&i&&g(`${co(y.number)} `,i.start,n.selectionStart),p()};function h(){a.replaceChildren(...l.map((y,E)=>t("li",{class:"mention-option",role:"option",id:`mention-${E}`,"aria-selected":String(E===u),onmousedown:x=>(x.preventDefault(),w(y))},Rt(y),t("span",{class:"badge"},String(y.number)),t("span",{class:"name"},y.name)))),a.hidden=!1,n.setAttribute("aria-expanded","true"),n.setAttribute("aria-activedescendant",`mention-${u}`)}function c(){if(i=Qa(n.value,n.selectionStart),l=i?Ya(o(),i.query):[],!l.length)return p();u=Math.min(u,l.length-1),h()}n.addEventListener("input",c),n.addEventListener("blur",p),n.addEventListener("keydown",y=>{if(a.hidden)return;let E={ArrowDown:1,ArrowUp:-1}[y.key];if(E)u=(u+E+l.length)%l.length;else if(y.key==="Enter"||y.key==="Tab")w(l[u]);else if(y.key==="Escape")p();else return;y.preventDefault(),y.stopImmediatePropagation(),E&&h()},!0);function v({asset:y,from:E,to:x}){let f=o().find(q=>q.asset===y);if(!f)return;let P=Number.isSafeInteger(E)&&Number.isSafeInteger(x)&&x>E?{from:E,to:x}:null,L=co(f.number,P);P&&r.set(L,P);let U=n.selectionStart;g(`${U>0&&!/\s$/.test(n.value.slice(0,U))?" ":""}${L} `,U,n.selectionEnd)}return n.addEventListener("dragover",y=>y.dataTransfer?.types.includes(De)&&y.preventDefault()),n.addEventListener("drop",y=>{let E=y.dataTransfer?.getData(De);if(E){y.preventDefault();try{v(JSON.parse(E))}catch{}}}),{el:a,get open(){return!a.hidden},insert:v,take:y=>Xa(y,o(),r)}}var mo="#101014",Za={music:12,sfx:6,ambience:0,dialogue:0},ho=.015*7056e5,hn=(n,o,a)=>{let r=Math.min(1,Math.max(0,(a-n)/(o-n)));return r*r*(3-2*r)},go=(n,o)=>n?.find(a=>o>=a.at&&o<a.end)??null;function bo(n,o){for(let a of n??[]){if(!a.enter||o<a.at||o>=a.at+a.enter.duration)continue;let r=n.find(l=>l.end===a.at&&l!==a)??null;return{...a.enter,progress:(o-a.at)/a.enter.duration,item:a,before:r}}return null}function yo(n,o,a,r,l,u=1,i={width:r,height:l}){let p=x=>({x:(r-o*x)/2,y:(l-a*x)/2,w:o*x,h:a*x}),g=p(Math.max(r/o,l/a)*u);if(n!=="fit"&&n!=="blur")return{picture:g};let w=Math.min(i.width/o,i.height/a),h=x=>Math.max(2,Math.round(x/2)*2),[c,v]=[h(o*w),h(a*w)],y=r/i.width,E={x:Math.floor((i.width-c)/4)*2*y,y:Math.floor((i.height-v)/4)*2*y,w:c*y,h:v*y};return n==="fit"?{picture:E,plate:!0}:{picture:E,behind:p(Math.max(r/o,l/a))}}function wo(n,o,a=1){return`blur(${(.82*(Math.max(2,Math.round(Math.min(n,o)/24))*a)).toFixed(2)}px) brightness(0.88) saturate(0.9)`}function Ye(n){if(!n)return"none";let o=[],a=1+(n.lift??0)+(n.ev??0)/8;a!==1&&o.push(`brightness(${a.toFixed(3)})`),n.gain!==void 0&&n.gain!==1&&o.push(`contrast(${n.gain})`);let r=(n.saturation??1)*(1+(n.vibrance??0)*.5);return r!==1&&o.push(`saturate(${r.toFixed(3)})`),o.length?o.join(" "):"none"}function ko(n,o){let a=1-Math.min(1,Math.max(0,o));switch(n){case"fade":return{a,b:1-a,bg:0};case"dip":case"flash":{let r=hn(.8,1,a),l=hn(.2,1,a);return{a:r*a,b:(1-l)*(1-a),bg:(1-r)*a+l*(1-a),backdrop:n==="dip"?"#000":"#fff"}}case"wipe":return{a:1,b:1,bg:0,edge:a};case"slide":return{a:1,b:1,bg:0,shift:1-a};case"zoom":{let r=hn(0,.5,a);return{a:r,b:1-r,bg:0,magnify:hn(.5,1,a)}}default:return{a:0,b:1,bg:0}}}var es=n=>10**(n/20);function er(n,o){if(!n?.curve?.length)return 1;let a=Math.min(n.curve.length-1,Math.max(0,Math.floor(o/7056e5*n.rate)));return n.curve[a]}function ts(n,o,a){if(o<n.at||o>=n.end)return 0;let r=es(n.db??-Za[n.bus??"dialogue"]),l=o-n.at,u=n.end-o,i=Math.min(1,l/ho,u/ho);return n.fadeIn&&(i=Math.min(i,l/n.fadeIn)),n.fadeOut&&(i=Math.min(i,u/n.fadeOut)),r*Math.max(0,i)*(n.bus==="music"?er(a,o):1)}function ns(n,o){if(o<n.at||o>=n.end)return null;let a=n.speed?n.speed.n/n.speed.d:1,r=(o-n.at)*a;if(n.fit?.segments?.length){let l=n.at,{segments:u,crossfade:i=0}=n.fit;for(let[p,g]of u.entries()){let w=(g.out-g.in)/a-(p<u.length-1?i/2:0)-(p>0?i/2:0),h=p>0?i/2:0;if(o<l+w||p===u.length-1)return{source:g.in+(h+o-l)*a,until:Math.min(n.end,l+w)};l+=w}}if(n.loop){let l=n.out-n.in;return r%=l,{source:n.in+r,until:Math.min(n.end,o+(l-r)/a)}}return{source:n.in+r,until:n.end}}var tr=null,mn=()=>tr??=new AudioContext,vo=n=>Number.isFinite(n)?Math.min(1,Math.max(0,(n+60)/60)):0;function nr(n){let o=0;for(let r of n)o+=r*r;let a=Math.sqrt(o/Math.max(1,n.length));return a>0?20*Math.log10(a):-1/0}function xo(){let n=null,o=null,a=new WeakSet,r=()=>{if(!n){let l=mn();n=l.createAnalyser(),n.fftSize=1024,n.connect(l.destination),o=new Float32Array(n.fftSize)}return n};return{input:()=>r(),join(l){if(!a.has(l)){try{mn().createMediaElementSource(l).connect(r()),a.add(l)}catch{}mn().resume().catch(()=>{})}},level(){return n?(n.getFloatTimeDomainData(o),nr(o)):-1/0}}}function $o({canvas:n,urlOf:o}){let a=document.createElement("div");a.className="tile-layer",a.setAttribute("aria-hidden","true");let r=new Map;function l(u){a.style.left=`${n.offsetLeft}px`,a.style.top=`${n.offsetTop}px`,a.style.width=`${n.clientWidth}px`,a.style.height=`${n.clientHeight}px`;let i=n.clientWidth/u.width;for(let{frame:p}of r.values())p.style.transform=`scale(${i})`}return{sync(u,i,p){!a.isConnected&&n.isConnected&&n.after(a);let g=(u??[]).filter(h=>i>=h.at&&i<h.end),w=new Set(g.map(h=>h.key));for(let[h,{frame:c}]of r)w.has(h)||(c.remove(),r.delete(h));for(let h of g){let c=r.get(h.key);if(!c){let v=document.createElement("iframe");v.setAttribute("sandbox","allow-scripts"),v.setAttribute("tabindex","-1"),v.title=h.kind==="caption"?"Caption":"Graphic",v.className="tile",v.style.width=`${p.width}px`,v.style.height=`${p.height}px`,v.style.zIndex=String(h.depth??1),v.dataset.key=h.key,c={frame:v,tile:h,loaded:!1,at:0},v.addEventListener("load",()=>{c.loaded=!0,v.contentWindow?.postMessage({t:c.at},"*")}),v.src=o(h.key),r.set(h.key,c),a.append(v)}c.at=(i-h.at)*1e3/7056e5,c.loaded&&c.frame.contentWindow?.postMessage({t:c.at},"*")}r.size&&l(p)},clipLeft(u){a.style.clipPath=u===null?"":`inset(0 0 0 ${(u*100).toFixed(2)}%)`},get frames(){return new Map([...r].map(([u,{frame:i}])=>[u,i]))},clear(){for(let{frame:u}of r.values())u.remove();r.clear()}}}function So({urlOf:n,meter:o=null}){let a=null,r=[],l={items:[],duck:null},u=()=>{for(let p of r){for(let g of p.timers)clearTimeout(g);p.element.pause(),p.node.disconnect(),p.gain.disconnect()}r=[]};function i(p,g,w){let{item:h,element:c,gain:v}=p;if(!ns(h,Math.max(g,h.at)))return;let E=Math.max(0,(h.at-g)/7056e5),x=()=>{let q=ns(h,Math.max(g+(performance.now()-w)*(7056e5/1e3),h.at));q&&(c.currentTime=q.source/7056e5,c.play().catch(()=>{}),q.until<h.end&&p.timers.push(setTimeout(x,(q.until-g)*1e3/7056e5-(performance.now()-w))))};p.timers.push(setTimeout(x,E*1e3));let f=.02*7056e5,P=Math.max(g,h.at),L=[];for(let q=P;q<h.end;q+=f)L.push(ts(h,q,l.duck));L.push(0);let U=a.currentTime+(P-g)/7056e5;v.gain.setValueAtTime(L[0],U),L.length>1&&v.gain.setValueCurveAtTime(Float32Array.from(L),U,Math.max(.01,(h.end-P)/7056e5))}return{load(p){u(),l=p??{items:[],duck:null}},start(p,g){if(u(),g!==1)return;let w=l.items.filter(c=>c.bus!=="dialogue"&&c.end>p);if(!w.length)return;a??=mn(),a.resume();let h=performance.now();for(let c of w){let v=new Audio;v.preload="auto",v.src=n(c.asset);let y=a.createMediaElementSource(v),E=a.createGain();y.connect(E).connect(o?o.input():a.destination);let x={item:c,element:v,node:y,gain:E,timers:[]};r.push(x),i(x,p,h)}},stop:u,state(p){return r.map(({item:g,gain:w})=>({asset:g.asset,bus:g.bus,planned:ts(g,p,l.duck),node:w.gain.value}))}}}var Mo=n=>typeof n=="number"?{n,d:1}:n??{n:1,d:1},gn=n=>[...n?.picture??[]].sort((o,a)=>o.at-a.at),ss=n=>[{clip:null,asset:n.id,in:0,out:n.facts.duration,at:0,end:n.facts.duration,speed:{n:1,d:1}}],vt=(n,o)=>n.find(a=>o>=a.at&&o<a.end)??(n.length&&o>=n.at(-1).end?n.at(-1):null);function lt(n,o){if(n.hold)return n.in;let{n:a,d:r}=Mo(n.speed);return Math.min(n.out,n.in+Math.round((o-n.at)*a/r))}function It(n,o,a){for(let r of n){if(r.asset!==o||r.hold||a<r.in||a>=r.out)continue;let{n:l,d:u}=Mo(r.speed);return r.at+Math.round((a-r.in)*u/l)}return null}var He=n=>n.length?Math.max(...n.map(o=>o.end)):0;function Co(n,o){let a=[];for(let r of o){let l=It(n,r.asset,r.start);l!==null&&l>0&&a.push({id:r.id,at:l})}return a}var sr=1280;function Lo({canvas:n,urlOf:o,assetOf:a,onTime:r,onRate:l,tileUrl:u}){let i=n.getContext("2d",{willReadFrequently:!0}),p=new Map,g=[],w={n:30,d:1},h=0,c=0,v=0,y={width:1920,height:1080},E=1,x=!1,f=0,P=null,L=null,U=u?$o({canvas:n,urlOf:u}):null,q=u?xo():null,te=u?So({urlOf:o,meter:q}):null,V=null,B=u?[document.createElement("canvas"),document.createElement("canvas")]:null,D=new Map;function ce(m){let S=g[m],N=`${S.asset}:${m%2}`;if(!p.has(N)){let F=document.createElement("video");Object.assign(F,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:o(S.asset)}),p.set(N,F)}return p.get(N)}function de(m,S){let N=a(m.asset)?.facts?.fps??w;return(S+Ne(N)/2)/7056e5}function oe(){let m=Math.min(1,sr/Math.max(y.width,y.height)),S=Math.round(y.width*m),N=Math.round(y.height*m);(n.width!==S||n.height!==N)&&Object.assign(n,{width:S,height:N})}function X(m,S,N,F,T){let{width:j,height:R}=n;(m.width!==j||m.height!==R)&&Object.assign(m,{width:j,height:R});let K=m.getContext("2d");K.imageSmoothingQuality="high",K.fillStyle="#000",K.fillRect(0,0,j,R);let W=yo(T?.frame,N,F,j,R,E,L.output);return W.plate&&(K.fillStyle=mo,K.fillRect(0,0,j,R)),W.behind&&(K.filter=wo(L.output.width,L.output.height,j/L.output.width),K.drawImage(S,W.behind.x,W.behind.y,W.behind.w,W.behind.h),K.filter="none"),K.drawImage(S,W.picture.x,W.picture.y,W.picture.w,W.picture.h),m}function G(m,S){let{width:N,height:F}=n,T=go(L.picture,S),j=bo(L.picture,S),R=j&&D.get(`${j.asset}@${j.source}`),K=[...T?.fx??[],...(L.adjust??[]).filter(he=>S>=he.at&&S<he.end).flatMap(he=>he.fx)],W=(he,Le)=>{let Ze=Ye(Le);i.filter=K.length?`${Ze==="none"?"":`${Ze} `}${K.join(" ")}`:Ze,i.drawImage(he,0,0),i.filter="none"};if(!R)return W(X(B[1],m,m.videoWidth,m.videoHeight,T),T?.grade);let ae=X(B[0],R,R.width,R.height,j.before),ue=X(B[1],m,m.videoWidth,m.videoHeight,T),se=ko(j.kind,j.progress);if(i.fillStyle="#000",i.fillRect(0,0,N,F),j.kind==="wipe")return W(ae,j.before?.grade),i.save(),i.beginPath(),i.rect(N*se.edge,0,N-N*se.edge,F),i.clip(),W(ue,T?.grade),i.restore();if(j.kind==="slide"){i.filter=Ye(j.before?.grade),i.drawImage(ae,-N*se.shift,0),i.filter=Ye(T?.grade),i.drawImage(ue,N*(1-se.shift),0),i.filter="none";return}if(se.bg>0&&(i.fillStyle=se.backdrop,i.fillRect(0,0,N,F)),se.b>0&&(i.globalAlpha=se.b/(se.b+se.bg),i.filter=Ye(T?.grade),i.drawImage(ue,0,0)),se.a>0){i.globalAlpha=se.a,i.filter=Ye(j.before?.grade);let he=se.magnify===void 0?1:Math.max(.01,se.magnify);i.drawImage(ae,(N-N*he)/2,(F-F*he)/2,N*he,F*he,0,0,N,F)}i.filter="none",i.globalAlpha=1}async function le(m){for(let S of m.picture){if(!S.enter||L!==m)continue;let N=`${S.enter.asset}@${S.enter.source}`;if(D.has(N))continue;let F=document.createElement("video");Object.assign(F,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:o(S.enter.asset)});let T=a(S.enter.asset)?.facts?.fps??w;if(await new Promise(R=>{F.addEventListener("seeked",R,{once:!0}),F.addEventListener("error",R,{once:!0}),F.currentTime=(S.enter.source+Ne(T)/2)/7056e5}),!F.videoWidth)continue;let j=document.createElement("canvas");Object.assign(j,{width:F.videoWidth,height:F.videoHeight}),j.getContext("2d").drawImage(F,0,0),D.set(N,j),F.removeAttribute("src")}}let me=()=>L&&Math.abs(y.width*L.output.height-y.height*L.output.width)<y.width;function ve(m,S,N,F){oe();let{width:T,height:j}=n;if(i.fillStyle="#000",i.fillRect(0,0,T,j),L&&m?.videoWidth&&me()){if(G(m,F),V!==null){let R=Math.max(T/m.videoWidth,j/m.videoHeight)*E;i.save(),i.beginPath(),i.rect(0,0,T*V,j),i.clip(),i.drawImage(m,(T-m.videoWidth*R)/2,(j-m.videoHeight*R)/2,m.videoWidth*R,m.videoHeight*R),i.restore()}P={asset:S.asset,source:N}}else if(m?.videoWidth){let R=Math.max(T/m.videoWidth,j/m.videoHeight)*E,K=m.videoWidth*R,W=m.videoHeight*R;i.drawImage(m,(T-K)/2,(j-W)/2,K,W),P={asset:S.asset,source:N}}if(x){i.strokeStyle="rgb(255 255 255 / 0.55)",i.setLineDash([6,6]),i.lineWidth=1;for(let R of[.05,.1])i.strokeRect(T*R,j*R,T*(1-2*R),j*(1-2*R));i.setLineDash([])}U&&(U.sync(me()?L.tiles:[],F,L?.output),U.clipLeft(V!==null&&me()?V:null))}let z=()=>{oe(),i.fillStyle="#000",i.fillRect(0,0,n.width,n.height),P=null,U?.clear()},Q=0,re=Promise.resolve();function ne(m){let S=g.indexOf(vt(g,m));if(S<0)return Promise.resolve(z());let N=g[S],F=lt(N,m),T=ce(S),j=de(N,F),R=++Q,K=new Promise(W=>{let ae=()=>{Q===R&&ve(T,N,F,m),W()};if(T.readyState>=2&&Math.abs(T.currentTime-j)<1e-4)return ae();T.addEventListener("seeked",ae,{once:!0}),T.currentTime=j});if(re=K,g[S+1]){let W=ce(S+1);W!==T&&(W.currentTime=de(g[S+1],g[S+1].in))}return K}function pe(){for(let m of p.values())m.pause(),m.muted=!0}function Z(m,S=!0){c=Math.min(Math.max(0,m),Math.max(0,h-Ne(w))),S&&r(c)}function Be(m){let S=g.indexOf(vt(g,c));if(S<0)return Me(0);let N=(F,T)=>{let j=g[F],R=ce(F);R.currentTime=de(j,lt(j,T)),R.playbackRate=v,R.muted=!1,q?.join(R);let K=L?.audio.items.find(se=>se.bus==="dialogue"&&se.asset===j.asset&&se.at<j.end&&j.at<se.end);L&&(R.volume=K?.db===void 0?1:Math.min(1,es(K.db)));let{n:W,d:ae}=typeof j.speed=="object"?j.speed:{n:1,d:1},ue=(se,he)=>{if(m!==f)return;let Le=j.at+Math.round((Math.round(he.mediaTime*7056e5)-j.in)*ae/W);if(Le>=j.end-Ne(w)/2||R.ended)return R.pause(),R.muted=!0,g[F+1]?(S=F+1,Z(g[S].at),N(S,g[S].at)):Me(0);ve(R,j,lt(j,Le),Le),Z(Le),R.requestVideoFrameCallback(ue)};R.requestVideoFrameCallback(ue),R.play().catch(()=>m===f&&Me(0))};N(S,c)}function fe(m){let S=performance.now(),N=async F=>{if(m===f){if(Z(c-(F-S)/1e3*7056e5*Math.abs(v)),S=F,await ne(c),c===0)return Me(0);requestAnimationFrame(N)}};requestAnimationFrame(N)}function Me(m){if(m===v&&m!==0)return;v=m;let S=++f;pe(),l(v),te&&(me()&&v>0?te.start(c,v):te.stop()),v>0?Be(S):v<0?fe(S):(Z(wt(c,w)),ne(c))}return{load(m,{fps:S,duration:N,shape:F,preview:T}){return g=m,U&&(L=T??null,te.load(L?.audio),U.clear(),L&&le(L).then(()=>v===0&&L===T&&ne(c))),w=S,h=N,F&&(y=F),++f,pe(),v=0,l(0),Z(Math.min(c,Math.max(0,h-Ne(w)))),ne(c)},seek(m){return v!==0&&Me(0),Z(wt(m,w)),ne(c)},setRate:Me,get time(){return c},get rate(){return v},get shown(){return P},get settled(){return re},setShape(m){return y=m,ne(c)},setZoom(m){return E=m,ne(c)},setGuides(m){return x=m,ne(c)},setWipe(m){return U?(V=m===null?null:Math.min(1,Math.max(0,m)),v===0?ne(c):Promise.resolve()):Promise.resolve()},get wipe(){return V},level:()=>q&&v!==0?q.level():-1/0,get live(){return U?{on:!!(L&&me()),tiles:[...U.frames.keys()],sound:te.state(c),held:D.size}:null},pixels:()=>n.width?i.getImageData(0,0,n.width,n.height):null}}var Eo="http://www.w3.org/2000/svg",os={box:"Box",ring:"Ring",arrow:"Arrow"},Ao=10,as=n=>Math.min(1,Math.max(0,n)),bn=(n,o)=>as(.5+(n-.5)/o),To=(n,o)=>.5+(n-.5)*o;function Oo(n,o,a,{zoom:r=1,at:l}){let[u,i]=[bn(o.u,r),bn(a.u,r)].sort((y,E)=>y-E),[p,g]=[bn(o.v,r),bn(a.v,r)].sort((y,E)=>y-E),w=Math.round(u*1e3),h=Math.round(p*1e3),c=Math.min(1e3-w,Math.round(i*1e3)-w),v=Math.min(1e3-h,Math.round(g*1e3)-h);return c<Ao||v<Ao||!Number.isSafeInteger(l)||l<0?null:{kind:n,x:w,y:h,w:c,h:v,at:Math.round(l)}}function Po({frame:n,canvas:o,timeNow:a,zoomNow:r,usable:l,onChange:u,pause:i}){let p=null,g=null,w=null,h=document.createElementNS(Eo,"svg");h.setAttribute("class","draw-layer"),h.setAttribute("viewBox","0 0 1000 1000"),h.setAttribute("preserveAspectRatio","none"),h.setAttribute("aria-hidden","true"),n.classList.add("drawable"),n.append(h);let c=t("span",{class:"note small draw-note",role:"status","aria-live":"polite"});function v(){Object.assign(h.style,{left:`${o.offsetLeft}px`,top:`${o.offsetTop}px`,width:`${o.offsetWidth}px`,height:`${o.offsetHeight}px`})}new ResizeObserver(()=>(v(),x())).observe(o),window.addEventListener("resize",()=>(v(),x()));let y=(B,D)=>{let ce=document.createElementNS(Eo,B);for(let[de,oe]of Object.entries(D))ce.setAttribute(de,String(oe));return ce.setAttribute("vector-effect","non-scaling-stroke"),ce};function E(B,D,ce=!1){let de=r(),oe=To(D.x/1e3,de)*1e3,X=To(D.y/1e3,de)*1e3,G=D.w/1e3*de*1e3,le=D.h/1e3*de*1e3,me=`draw-mark${ce?" draft":""}`;if(B==="ring")return[y("ellipse",{cx:oe+G/2,cy:X+le/2,rx:G/2,ry:le/2,class:me})];if(B==="box")return[y("rect",{x:oe,y:X,width:G,height:le,rx:6,class:me})];let ve=X>120?X:X+le,z=X>120?Math.max(0,X-110):Math.min(1e3,X+le+110);return[y("rect",{x:oe,y:X,width:G,height:le,class:`${me} faint`}),y("line",{x1:oe+G/2,y1:z,x2:oe+G/2,y2:ve,class:me}),y("polyline",{points:`${oe+G/2-22},${ve+(X>120?-26:26)} ${oe+G/2},${ve} ${oe+G/2+22},${ve+(X>120?-26:26)}`,class:me})]}function x(){h.replaceChildren(...g?E(g.kind,g):[],...w?.box?E(p,w.box,!0):[])}function f(B){let D=B?l():null;if(D){c.textContent=D;return}p=p===B?null:B;for(let[ce,de]of Object.entries(U))de.setAttribute("aria-pressed",String(ce===p));h.classList.toggle("active",!!p),c.textContent=p?`Drag on the picture to draw a ${os[p].toLowerCase()}.`:"",p&&i()}let P=B=>{let D=h.getBoundingClientRect();return{u:as((B.clientX-D.left)/D.width),v:as((B.clientY-D.top)/D.height)}};h.addEventListener("pointerdown",B=>{p&&(B.preventDefault(),h.setPointerCapture(B.pointerId),w={start:P(B),box:null})}),h.addEventListener("pointermove",B=>{w&&(w.box=Oo(p,w.start,P(B),{zoom:r(),at:0}),x())});let L=B=>{if(!w)return;let D=Oo(p,w.start,P(B),{zoom:r(),at:a()});if(w=null,!D)return c.textContent="Too small: drag a bigger shape.",x();g=D,f(null),c.textContent=`Drawn: ${os[D.kind].toLowerCase()}. Say what to do with it, like "callout this", "blur this", "zoom here" or "mask this".`,x(),u(g)};h.addEventListener("pointerup",L),h.addEventListener("pointercancel",()=>(w=null,x())),window.addEventListener("keydown",B=>B.key==="Escape"&&p&&f(null));let U=Object.fromEntries(Object.entries(os).map(([B,D])=>[B,t("button",{type:"button",class:"btn","aria-pressed":"false",title:`Draw a ${D.toLowerCase()} on the frame`,onclick:()=>f(B)},D)])),q=t("button",{type:"button",class:"btn",title:"Remove the drawing",onclick:()=>te()},"Clear");function te(){g=null,w=null,c.textContent="",p&&f(null),x(),u(null)}let V=t("div",{class:"row draw-tools",role:"group","aria-label":"Draw on the frame"},...Object.values(U),q,c);return v(),{tools:V,mark:()=>g,clear:te,redraw:()=>(v(),x())}}var rs=[["story","Story"],["cuts","Cuts"],["broll","B-roll"],["look","Look"],["captions","Captions"],["audio","Audio"],["render","Render"],["check","Checks"],["repair","Repairs"],["watch","Watch"]],or=new Set(rs.map(([n])=>n));function jo(n,o){return Object.fromEntries(rs.map(([a])=>[a,a===o?"active":n.has(a)?"done":"waiting"]))}var ar={passed:"passed",failed:"failed",not_checked:"not checked",not_applicable:"not applicable"};function Ro({onFollow:n=()=>{}}={}){let o=new Set,a=null,r=!0,l=rs.map(([y,E])=>t("li",{class:"stage",dataset:{stage:y,state:"waiting"}},t("span",{class:"dot","aria-hidden":"true"}),E)),u=t("ol",{class:"stages","aria-label":"What the Director has done so far"},l),i=t("p",{class:"stage-line",role:"status","aria-live":"polite"},"Starting: reading the footage."),p=t("ul",{class:"stage-changes","aria-label":"Changes in this stage"}),g=t("ul",{class:"stage-gates","aria-label":"Checks so far"}),w=t("button",{type:"button",class:"btn small follow","aria-pressed":"true",title:"Show the Director's working cut on the monitor as it builds",onclick:()=>v(!r)},"Follow on the monitor"),h=t("div",{class:"director-strip"},u,i,p,g,w);function c(){let y=jo(o,a);for(let E of l)E.dataset.state=y[E.dataset.stage],y[E.dataset.stage]==="active"?E.setAttribute("aria-current","step"):E.removeAttribute("aria-current")}function v(y){r=y,w.setAttribute("aria-pressed",String(r)),n(r)}return{el:h,reset(){o=new Set,a=null,i.textContent="Starting: reading the footage.",w.hidden=!1,J(p),J(g),c()},push(y){return!y||!or.has(y.stage)?!1:(o.add(y.stage),a=y.stage,i.textContent=typeof y.text=="string"?y.text:"",y.skipped&&(i.textContent+=` This layer couldn't be drawn on its own (${y.skipped}), so the monitor shows the one before.`),Array.isArray(y.changes)?J(p).append(...y.changes.slice(0,4).map(E=>t("li",{},String(E)))):["check","repair","watch"].includes(y.stage)||J(p),Array.isArray(y.gates)&&J(g).append(...y.gates.map(E=>t("li",{class:`gate ${E.status==="failed"&&E.severity==="note"?"note":E.status}`,title:`${E.id}: ${ar[E.status]??E.status}${E.message?`. ${E.message}`:""}`},String(E.id)))),c(),!0)},finish(){a=null,w.hidden=!0,c()},get follow(){return r},get states(){return jo(o,a)}}}var Io=({reduced:n=!1,automated:o=!1}={})=>!n&&!o,rr=1800;function No({load:n,show:o,restore:a,animate:r,stepMs:l=rr}){let u=[],i=0,p=null,g=!1,w=!1,h=t("p",{class:"replay-title"},"How it was edited"),c=t("div",{class:"replay-steps",role:"group","aria-label":"Layers of the edit"}),v=t("p",{class:"replay-detail",role:"status","aria-live":"polite"}),y=t("button",{type:"button",class:"btn small",hidden:!0,onclick:()=>g?f():P()},"Pause replay"),E=t("button",{type:"button",class:"btn small",onclick:()=>q()},"Skip replay"),x=t("div",{class:"replay",hidden:!0,"aria-label":"Replay of how the cut was edited",role:"region"},t("div",{class:"replay-head"},h,t("div",{class:"replay-actions"},y,E)),c,v),f=()=>{clearTimeout(p),p=null,g=!1,y.textContent="Play replay"},P=()=>{g=!0,y.textContent="Pause replay",L()};function L(){clearTimeout(p),g&&(p=setTimeout(()=>i<u.length-1?U(i+1).then(L):q(),l))}async function U(te){i=te;let V=u[te];for(let[D,ce]of[...c.children].entries())ce.setAttribute("aria-pressed",String(D===te));let B=V.id==="raw"?"The cut before the Director touched it.":V.ops?`${V.ops} change${V.ops===1?"":"s"}${V.changes?.length?`: ${V.changes.join("; ")}`:""}.`:"Nothing changed in this layer.";v.textContent=`${te+1} of ${u.length} \xB7 ${V.label}. ${B}${V.skipped?` It couldn't be drawn on its own (${V.skipped}), so this shows the layer before.`:""}`,E.textContent=te===u.length-1?"Back to my cut":"Skip replay",await o(V)}async function q(){f(),w&&(w=!1,x.hidden=!0,await a())}return{el:x,get open(){return w},get at(){return i},async start(){f();let te;try{te=await n()}catch(V){return x.hidden=!1,w=!1,J(c),v.textContent=V.message,E.textContent="Close",!1}return u=te.layers.filter((V,B)=>B===0||V.ops>0),J(c).append(...u.map((V,B)=>t("button",{type:"button",class:"btn small step","aria-pressed":"false",onclick:()=>(f(),U(B))},V.label))),w=!0,x.hidden=!1,y.hidden=!r,await U(0),r&&P(),!0},stop:q}}var ir={vivid:{saturation:1.15,gain:1.06,vibrance:.35},cinematic:{saturation:.9,gain:1.12,gamma:.95,temperature:7200,vignette:.45},warm:{temperature:5200,saturation:1.05,vibrance:.2,vignette:.2},bright:{lift:.04,gamma:1.1,vibrance:.2},mono:{saturation:0,gain:1.1,vignette:.3}};function lr(n){if(!n)return{filter:"none",tint:null,vignette:0};let o=n.temperature??6500,a=Math.min(1,Math.abs(o-6500)/2500),r=o===6500?null:{colour:o<6500?"255 150 60":"70 140 255",alpha:Math.round(a*.22*1e3)/1e3};return{filter:Ye(n),tint:r,vignette:n.vignette??0}}function Do(n){let o=Math.max(1,Math.ceil(n/100));return Math.min(99,Math.max(0,Math.floor(n/o/2)))}function Bo({select:n,source:o}){let a=[...n.options].map(w=>{let h=t("canvas",{class:"look-sketch",width:96,height:54,"aria-hidden":"true"}),c=w.textContent.replace(/^Look:\s*/,"").replace(/\s*\(.*\)$/,""),v=t("button",{type:"button",class:"look-card","aria-pressed":String(n.value===w.value),title:`${w.textContent}. A sketch on your footage: the render is exact.`,onclick:()=>{n.value=w.value,n.dispatchEvent(new Event("change",{bubbles:!0})),p()}},h,t("span",{class:"look-name"},c.charAt(0).toUpperCase()+c.slice(1)));return{value:w.value,button:v,canvas:h}}),r=t("div",{class:"look-cards",role:"group","aria-label":"Colour looks, drawn on your footage"},a.map(w=>w.button)),l=null,u=null,i=0;function p(){for(let w of a)w.button.setAttribute("aria-pressed",String(w.value===n.value))}function g(){for(let w of a){let h=w.canvas.getContext("2d"),{width:c,height:v}=w.canvas,y=lr(ir[w.value]??null);if(h.filter="none",h.fillStyle="#22302f",h.fillRect(0,0,c,v),l?.naturalWidth){let E=l.naturalWidth/10,x=l.naturalHeight/10,f=Math.max(c/E,v/x);h.filter=y.filter,h.drawImage(l,i%10*E,Math.floor(i/10)*x,E,x,(c-E*f)/2,(v-x*f)/2,E*f,x*f),h.filter="none"}else{let E=h.createLinearGradient(0,0,c,v);E.addColorStop(0,"#c98f6b"),E.addColorStop(.5,"#6f9c98"),E.addColorStop(1,"#33486b"),h.filter=y.filter,h.fillStyle=E,h.fillRect(0,0,c,v),h.filter="none"}if(y.tint&&(h.fillStyle=`rgb(${y.tint.colour} / ${y.tint.alpha})`,h.fillRect(0,0,c,v)),y.vignette>0){let E=h.createRadialGradient(c/2,v/2,Math.min(c,v)*.3,c/2,v/2,Math.max(c,v)*.7);E.addColorStop(0,"rgb(0 0 0 / 0)"),E.addColorStop(1,`rgb(0 0 0 / ${Math.min(.8,y.vignette*1.2)})`),h.fillStyle=E,h.fillRect(0,0,c,v)}}}return n.addEventListener("change",p),{el:r,refresh(){p();let w=o();if(w?.url===u&&w?.cell===i)return g();if(u=w?.url??null,i=w?.cell??0,!u)return l=null,g();let h=new Image;h.addEventListener("load",()=>u===w.url&&(l=h,g())),h.addEventListener("error",()=>u===w.url&&(l=null,g())),h.src=u,g()},mark:p}}var Fo=[{group:"Play",keys:["Space"],press:[" "],action:"toggle",does:"Play or pause"},{group:"Play",keys:["J","K","L"],press:["j","k","l"],action:["reverse","rate","faster"],does:"Play backwards, stop, play forwards (press again to go faster)"},{group:"Play",keys:["\u2190","\u2192"],press:["ArrowLeft","ArrowRight"],action:"step",does:"One frame back or forward"},{group:"Play",keys:["Shift","\u2190/\u2192"],press:["ArrowLeft"],shift:!0,action:"step",does:"One second back or forward"},{group:"Play",keys:["Home"],press:["Home"],action:"seek",does:"To the start"},{group:"Cut",keys:["I","O"],press:["i","o"],action:"mark",does:'Mark in and out: the marked stretch is "this" to Kriya'},{group:"Cut",keys:["S"],press:["s"],action:"split",does:"Split the clip at the playhead"},{group:"Cut",keys:["Delete"],press:["Delete","Backspace"],action:"delete",does:"Remove the selected clip and close the gap"},{group:"Cut",keys:["\u2318/Ctrl","Z"],press:["z"],mod:!0,action:"undo",does:"Undo (add Shift to redo)"},{group:"Studio",keys:["1","2","3"],press:["1","2","3"],action:"mode",does:"Direct, Edit, Finish"},{group:"Studio",keys:["/"],press:["/"],action:"prompt",does:"Write to Kriya"},{group:"Studio",keys:["Esc"],press:[],action:null,does:"Let go of the field, the selection and the marks"},{group:"Studio",keys:["?"],press:[],action:null,does:"This list"}];function Ko(){let n=[...new Set(Fo.map(r=>r.group))],o=t("button",{type:"button",class:"btn",onclick:()=>a.close()},"Close"),a=t("dialog",{class:"picker shortcuts","aria-label":"Keyboard shortcuts"},t("h2",{},"Keyboard shortcuts"),...n.map(r=>t("section",{class:"keys-group","aria-label":r},t("p",{class:"keys-head"},r),t("dl",{class:"keys"},Fo.filter(l=>l.group===r).flatMap(l=>[t("dt",{},...l.keys.flatMap((u,i)=>[i?" ":null,t("kbd",{},u)])),t("dd",{},l.does)])))),t("p",{class:"note small"},"Keys work when no field has the focus."),t("div",{class:"row end"},o));return a.addEventListener("keydown",r=>{r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),a.close())}),{dialog:a,open(){a.isConnected||document.body.append(a),a.open||a.showModal(),o.focus()}}}var cr=["story","whole"],dr={auto:"Automatic",fill:"Fill the frame",fit:"Fit, with bars",blur:"Fit, blur behind"},wn=n=>n.sequences.find(o=>o.id===n.active)?.assembly?.parts??[],kn=n=>n.filter(o=>cr.includes(o.use)),Wo=n=>({op:"set_assembly",assembly:{version:1,parts:n}});function xt(n,o,a){let r=kn(n),l=r.findIndex(w=>w.id===o),u=r[l+a];if(l<0||!u)return null;let i=[...n],p=i.indexOf(r[l]),g=i.indexOf(u);return[i[p],i[g]]=[i[g],i[p]],i}function _o(n,o,a){let r=n.find(p=>p.id===o);if(!r||o===a)return null;let l=n.filter(p=>p!==r),u=a===null?l.length:l.findIndex(p=>p.id===a);if(u<0)return null;let i=[...l.slice(0,u),r,...l.slice(u)];return i.every((p,g)=>p===n[g])?null:i}var is=(n,o)=>n.filter(a=>a.id!==o&&a.at?.part!==o);function Go(n,{asset:o,from:a,to:r},l=null){let u=n.length+1;for(;n.some(g=>g.id===`p${u}`);)u++;let i=Number.isSafeInteger(a)&&Number.isSafeInteger(r)&&r>a,p={id:`p${u}`,asset:o,...i?{from:a,to:r}:{},use:"whole",why:"storyboard"};return _o([...n,p],p.id,l)??[...n,p]}function ur(n,o,a){return n.map(r=>{if(r.id!==o)return r;let{fit:l,...u}=r;return a==="auto"?u:{...u,fit:a}})}var yn=(n,o,a)=>typeof n=="number"?n:o.find(r=>r.id===n?.word)?.[n?.edge??a]??null;function pr(n,o=[]){if(n.from===void 0&&n.to===void 0)return"whole";let a=n.from===void 0?0:yn(n.from,o,"start"),r=n.to===void 0?null:yn(n.to,o,"end");return`${a===null?"?":kt(a)}\u2013${r===null?"end":kt(r)}`}function fr(n,o,a,r,l=[]){let u=n.from===void 0?0:yn(n.from,l,"start"),i=n.to===void 0?r?.duration??null:yn(n.to,l,"end"),p=u===null||i===null?null:kt(i-u);return[`Part ${o+1} of ${a}: clip ${r?.number??"?"}`,r?.name,n.use,p].filter(Boolean).join(", ")}function Ho({root:n,clips:o,words:a,onChange:r}){let l=[],u=null,i=t("ol",{class:"sb-cards","aria-label":"The film's order"}),p=t("ul",{class:"sb-unused","aria-label":"Clips not used"}),g=t("p",{class:"note small"},"Nothing in the storyboard yet. Add clips in the order the film should play."),w=t("p",{class:"sr-only",role:"status","aria-live":"polite"}),h=(x,f=null,P="")=>{x&&(u=f,w.textContent=P,r(x))},c=x=>{try{return JSON.parse(x.dataTransfer.getData(De))}catch{return null}},v=x=>x.dataTransfer?.types.includes(De)&&x.preventDefault(),y=x=>f=>{let P=c(f);P&&(f.preventDefault(),f.stopPropagation(),P.part?h(_o(l,P.part,x),P.part,"Moved."):o().some(L=>L.asset===P.asset)&&h(Go(l,P,x),null,"Added to the film."))};function E(){let x=new Map(o().map(L=>[L.asset,L])),f=kn(l);J(i),f.forEach((L,U)=>{let q=x.get(L.asset),te=t("select",{class:"field select","aria-label":`How clip ${q?.number??"?"} fits the frame`,onchange:()=>h(ur(l,L.id,te.value),L.id)},Object.entries(dr).map(([B,D])=>t("option",{value:B},D)));te.value=L.fit??"auto";let V=t("div",{class:"sb-card",role:"group",tabindex:"0",draggable:"true","aria-label":fr(L,U,f.length,q,a()),"aria-keyshortcuts":"Alt+ArrowLeft Alt+ArrowRight Delete",dataset:{part:L.id},ondragstart:B=>B.dataTransfer.setData(De,JSON.stringify({part:L.id,asset:L.asset,...typeof L.from=="number"&&typeof L.to=="number"?{from:L.from,to:L.to}:{}})),onkeydown:B=>{if(B.target!==V)return;let D=B.altKey?{ArrowLeft:-1,ArrowRight:1,ArrowUp:-1,ArrowDown:1}[B.key]:null;if(D)h(xt(l,L.id,D),L.id,`Part ${U+1+D} of ${f.length}.`);else if(B.key==="Delete"||B.key==="Backspace")h(is(l,L.id),f[U+1]?.id??f[U-1]?.id??null,"Left out of the film.");else return;B.preventDefault(),B.stopPropagation()}},Rt(q),t("span",{class:"badge"},String(q?.number??"?")),t("span",{class:"name"},q?.name??"A missing clip"),t("span",{class:"stretch label-mono"},pr(L,a())),te,t("span",{class:"sb-moves"},t("button",{type:"button",class:"btn move",disabled:U===0,"aria-label":`Move clip ${q?.number??"?"} up`,onclick:()=>h(xt(l,L.id,-1),L.id,`Part ${U} of ${f.length}.`)},"Move up"),t("button",{type:"button",class:"btn move",disabled:U===f.length-1,"aria-label":`Move clip ${q?.number??"?"} down`,onclick:()=>h(xt(l,L.id,1),L.id,`Part ${U+2} of ${f.length}.`)},"Move down"),t("button",{type:"button",class:"btn","aria-label":`Leave clip ${q?.number??"?"} out of the film`,onclick:()=>h(is(l,L.id),f[U+1]?.id??f[U-1]?.id??null,"Left out of the film.")},"Remove")));i.append(t("li",{ondragover:v,ondrop:y(L.id)},V))}),g.hidden=f.length>0;let P=new Set(l.map(L=>L.asset));J(p);for(let L of o().filter(U=>!P.has(U.asset)))p.append(t("li",{},t("button",{type:"button",class:"btn sb-add",draggable:"true","aria-label":`Add clip ${L.number}, ${L.name}, to the film`,ondragstart:U=>U.dataTransfer.setData(De,JSON.stringify({asset:L.asset})),onclick:()=>h(Go(l,{asset:L.asset}),null,`Added clip ${L.number} to the film.`)},t("span",{class:"badge"},String(L.number)),t("span",{class:"name"},L.name),t("span",{"aria-hidden":"true"}," +"))));p.children.length||p.append(t("li",{class:"note small"},o().length?"Every clip is in the film.":"Add files to the project first.")),u&&i.querySelector(`[data-part="${CSS.escape(u)}"]`)?.focus(),u=null}return n.append(t("h2",{},"Storyboard"),i,g,t("h3",{class:"sb-head"},"Not used"),p,w),i.addEventListener("dragover",v),i.addEventListener("drop",y(null)),n.addEventListener("dragover",v),p.addEventListener("drop",x=>{let f=c(x);f?.part&&(x.preventDefault(),h(is(l,f.part),null,"Left out of the film."))}),{load(x){l=wn(x),E()}}}var Uo={matched:["\u2713","matched"],nearest:["\u2248","nearest"],cannot:["\u2717","can't"]};function qo({id:n,where:o,state:a,off:r,onRead:l,onCancel:u,onToggle:i}){let p=`${o}-${n}`;if(a.status==="measuring"){let c=a.progress??0;return t("div",{class:"style-brief","aria-live":"polite"},t("p",{class:"note small"},`Reading its style\u2026 ${c}%`),t("progress",{max:100,value:c,"aria-label":"Reading the reference's style"}),t("button",{type:"button",class:"btn",id:`style-cancel-${p}`,onclick:u},"Cancel"))}if(a.status!=="ready")return t("div",{class:"style-brief"},t("button",{type:"button",class:"btn",id:`style-read-${p}`,onclick:l},"Read its style"),t("p",{class:"note small"},a.status==="failed"?`Couldn't read it: ${a.error??"the measure stopped"}`:"Measured on this computer, as numbers only: its cuts, transitions, captions, colour and sound. No picture, sound or words from it are kept."));let{lines:g,unread:w}=a.brief,h=g.map(c=>{let[v,y]=Uo[c.state]??Uo.cannot,E=`style-${p}-${c.id}`,x=c.set&&!c.locked?t("input",{type:"checkbox",id:E,checked:!r.has(c.id),onchange:L=>i(c.id,L.target.checked)}):t("span",{class:"style-fixed","aria-hidden":"true"}),f=t("span",{class:"style-text"},t("span",{class:`style-mark ${c.state}`,"aria-hidden":"true"},v),t("span",{class:"sr-only"},`${y}: `),c.text,c.gate?t("span",{class:"chip style-gate",title:"A quality gate outranks the reference here"},`gate: ${c.gate}`):null),P=c.why?t("span",{class:"style-why"},c.why):null;return t("li",{class:`style-row ${c.state}`},c.set&&!c.locked?t("label",{class:"style-label",for:E},x,t("span",{class:"style-body"},f,P)):t("div",{class:"style-label"},x,t("span",{class:"style-body"},f,P)))});return t("div",{class:"style-brief"},t("h3",{class:"style-head"},"From this reference"),t("ul",{class:"style-rows",id:`style-rows-${p}`},h),w.length?t("p",{class:"note small style-unread"},`Couldn't read: ${w.join(", ")}.`):null,t("button",{type:"button",class:"btn",id:`style-read-${p}`,onclick:l},"Read it again"))}function zo({project:n,state:o,chosen:a,onAsk:r,onChoose:l}){let u=t("button",{type:"button",class:"btn wide",id:"openings-ask",disabled:o.status==="making",onclick:r},o.status==="ready"?"Three more openings":"Give me three openings");if(o.status==="making")return t("div",{class:"openings","aria-live":"polite"},u,t("p",{class:"note small"},`Drafting three openings\u2026 ${o.progress??0}%`),t("progress",{max:100,value:o.progress??0,"aria-label":"Drafting three openings"}));if(o.status!=="ready")return t("div",{class:"openings"},u,t("p",{class:"note small"},o.status==="failed"?`Couldn't draft them: ${o.error??"the drafts stopped"}`:"Three quick eight-second drafts, each starting on a different line. Pick one and the next make opens on it."));let i=String(o.job??"").split(".").at(-1),p=o.openings.map(g=>{let w=a===g.hook;return t("li",{class:`opening${w?" chosen":""}`},t("video",{class:"opening-film",src:`/projects/${encodeURIComponent(n)}/openings/${encodeURIComponent(i)}/${g.n}`,controls:!0,preload:"metadata",playsinline:!0,"aria-label":`Opening ${g.n+1}`}),t("p",{class:"opening-words"},t("span",{class:"opening-tag"},`${g.n+1} \xB7 ${g.seconds} s`)," ",`\u201C${g.words}\u201D`),t("button",{type:"button",class:`btn${w?" primary":""}`,id:`opening-use-${g.n}`,"aria-pressed":w?"true":"false",onclick:()=>l(w?null:g.hook)},w?"Chosen \u2713":"Open on this"))});return t("div",{class:"openings"},t("h3",{class:"openings-head"},"Openings"),t("ul",{class:"openings-wall",id:"openings-wall"},p),t("p",{class:"note small"},a?"The next make opens on the line you picked.":"Pick one, or keep the Director's choice."),u)}var hr=0;function ls(n,{label:o,selected:a=n[0]?.key,onSelect:r=()=>{},className:l=""}={}){let u=`tabs-${++hr}`,i=null,p=new Map,g=new Map,w=new Map;for(let x of n){let f=t("span",{class:"tab-count"}),P=t("span",{class:"tab-badge",hidden:!0});w.set(x.key,f),g.set(x.key,P);let L=t("button",{type:"button",role:"tab",id:`${u}-${x.key}`,class:"tab","aria-controls":`${u}-${x.key}-panel`,"aria-selected":"false",tabindex:"-1",onclick:()=>E(x.key,{focus:!0})},t("span",{class:"tab-label"},x.label),f,P);p.set(x.key,L),Object.assign(x.panel,{id:`${u}-${x.key}-panel`}),x.panel.setAttribute("role","tabpanel"),x.panel.setAttribute("aria-labelledby",L.id),x.panel.classList.add("tab-panel")}let h=n.map(x=>x.key),c=t("div",{class:`tabs ${l}`.trim(),role:"tablist","aria-label":o,onkeydown:x=>{let f=h.indexOf(i),P={ArrowRight:f+1,ArrowDown:f+1,ArrowLeft:f-1,ArrowUp:f-1,Home:0,End:h.length-1}[x.key];P!==void 0&&(x.preventDefault(),x.stopPropagation(),E(h[(P+h.length)%h.length],{focus:!0}))}},...p.values());function v(){for(let x of n){let f=x.count?.();w.get(x.key).textContent=f==null?"":String(f)}}function y(x,f){let P=g.get(x);P&&(P.hidden=f===null||f===0||f===""||x===i,P.textContent=P.hidden?"":String(f),P.setAttribute("aria-label",P.hidden?"":`${f} new`))}function E(x,{focus:f=!1}={}){if(p.has(x)){i=x;for(let P of n){let L=P.key===x,U=p.get(P.key);U.setAttribute("aria-selected",String(L)),U.tabIndex=L?0:-1,P.panel.hidden=!L}y(x,null),f&&p.get(x).focus(),r(x)}}return v(),E(a),{strip:c,select:E,selected:()=>i,mark:y,refresh:v}}var Vo=[{key:"picture",label:"Picture",colour:"--clip-picture"},{key:"overlays",label:"B-roll",colour:"--clip-broll"},{key:"audio",label:"Audio",colour:"--clip-audio"},{key:"captions",label:"Captions",colour:"--clip-caption"}],ke=44,Jo=6,cs={mouse:6,touch:22},mr=8;function gr(n,o,{width:a,duration:r,pointer:l="mouse"}){if(!r)return null;let u=l==="touch"?cs.touch:cs.mouse,i=g=>g/r*a,p=new Map;for(let g of n){let w=p.get(g.clip)??{clip:g.clip,at:g.at,end:g.end};p.set(g.clip,{...w,at:Math.min(w.at,g.at),end:Math.max(w.end,g.end)})}for(let g of p.values()){let[w,h]=[i(g.at),i(g.end)];if(!(h-w<u*3)){if(o>=w&&o<w+u)return{clip:g.clip,edge:"in",at:g.at};if(o>=h-u&&o<h)return{clip:g.clip,edge:"out",at:g.end}}}return null}function br(n,o,{width:a,duration:r}){let l=n,u=mr/a*r;for(let i of o)Math.abs(i-n)<=u&&([l,u]=[i,Math.abs(i-n)]);return l}var Yo=7056e5,Qo=(n,o)=>Math.min(99,Math.max(0,Math.floor(n/Yo/o))),yr=n=>(n?.picture??[]).filter(o=>o.enter).map(o=>({at:o.at,kind:o.enter.kind}));function ds({root:n,compact:o=!1,onSeek:a,onSelect:r=()=>{},onTrim:l,rich:u=null}){let i=o?Vo.slice(0,1):Vo,p=t("canvas",{class:"lanes","aria-hidden":"true"}),g=o?null:t("div",{class:"lane-labels","aria-hidden":"true"},i.map(m=>t("div",{class:"lane-label"},m.label))),w=t("ul",{class:"clip-list","aria-label":o?"Story":"Clips on the timeline"}),h=!!u&&!o,c=null,v=new Map,y=h?t("canvas",{class:"tl-frame",width:96,height:54}):null,E=h?t("span",{class:"tl-time"}):null,x=h?t("div",{class:"tl-tip","aria-hidden":"true",hidden:!0},y,E):null;x&&n.classList.add("rich"),n.append(...[g,t("div",{class:"lanes-wrap"},p,x),w].filter(Boolean));let f=p.getContext("2d"),P={picture:[],overlays:[],audio:[],captions:[]},L=0,U={n:30,d:1},q=0,te=[],V=[],B=new Map,D=null,ce=null,de=!!l&&!o,oe=[],X=null,G=m=>getComputedStyle(n).getPropertyValue(m).trim()||"#888";function le(){let m=Math.max(1,p.clientWidth),S=i.length*(ke+Jo),N=window.devicePixelRatio||1;(p.width!==Math.round(m*N)||p.height!==Math.round(S*N))&&(p.width=Math.round(m*N),p.height=Math.round(S*N),p.style.height=`${S}px`),f.setTransform(N,0,0,N,0,0),f.clearRect(0,0,m,S);let F=T=>L?T/L*m:0;i.forEach((T,j)=>{let R=j*(ke+Jo);f.fillStyle=G("--lane"),f.fillRect(0,R,m,ke);for(let K of P[T.key]??[]){let W=F(K.at),ae=Math.max(2,F(K.end)-W);f.fillStyle=G(T.colour),f.fillRect(W,R+2,ae-1,ke-4),h&&(T.key==="picture"||T.key==="overlays")&&me(K,W,ae,R),h&&T.key==="picture"&&Q(K,W,ae,R),K.clip&&K.clip===D&&(f.strokeStyle=G("--focus"),f.lineWidth=2,f.strokeRect(W+1,R+3,ae-3,ke-6));let ue=T.key==="audio"||o&&T.key==="picture"?B.get(K.asset):null;if(ue&&K.in!==void 0){f.fillStyle=G("--wave");let se=K.out-K.in;for(let he=0;he<ae;he++){let Le=(K.in+se*he/ae)/7056e5,Dt=(ue.peaks[Math.floor(Le*ue.perSecond)]??0)*(ke-8);f.fillRect(W+he,R+ke/2-Dt/2,1,Math.max(1,Dt))}}}if(T.key==="picture"&&ce){f.strokeStyle=G("--ghost"),f.setLineDash([5,4]),f.lineWidth=2;let K=Math.max(L,ce.duration)||1;for(let W of ce.picture)f.strokeRect(W.at/K*m+1,R+6,Math.max(2,(W.end-W.at)/K*m-2),ke-12);f.setLineDash([])}if(T.key==="picture"){f.fillStyle=G("--shot");for(let K of te)f.fillRect(F(K.at)-.5,R,1,8)}if(h&&T.key==="picture")for(let K of yr(c))re(F(K.at),R,K.kind);if(h&&T.key==="audio"&&c?.audio?.duck?.curve?.length&&ne(c.audio.duck,R,m),T.key==="picture"&&de){f.fillStyle=G("--ink-2");for(let K of P.picture){let[W,ae]=[F(K.at),F(K.end)];ae-W<cs.mouse*3||(P.picture.some(ue=>ue.clip===K.clip&&ue.end===K.at)||f.fillRect(W+1,R+ke/2-8,2,16),P.picture.some(ue=>ue.clip===K.clip&&ue.at===K.end)||f.fillRect(ae-3,R+ke/2-8,2,16))}X&&(f.fillStyle=G("--focus"),f.fillRect(F(X.at)-1,R,3,ke))}}),f.fillStyle=G("--playhead");for(let T of V)f.fillRect(F(T.at)-1,0,3,8);f.fillStyle=G("--playhead"),f.fillRect(F(q)-1,0,2,S)}function me(m,S,N,F){if(!m.asset||m.in===void 0||N<24)return;let T=u.thumbs(m.asset),j=T&&v.get(T.url);if(!T)return;if(!j)return z(T.url);if(!j.naturalWidth)return;let[R,K]=[j.naturalWidth/10,j.naturalHeight/10],W=Math.max(24,Math.round((ke-4)*R/K)),ae=(m.out??m.end-m.at+m.in)-m.in;f.save(),f.beginPath(),f.rect(S,F+2,N-1,ke-4),f.clip(),f.globalAlpha=.85;for(let ue=0;ue<N;ue+=W){let se=Qo(m.in+ae*Math.min(N,ue+W/2)/N,T.every);f.drawImage(j,se%10*R,Math.floor(se/10)*K,R,K,S+ue,F+2,W,ke-4)}f.restore()}function ve(m){let S=P.picture.find(se=>m>=se.at&&m<se.end),N=S?.asset&&S.in!==void 0?u.thumbs(S.asset):null,F=N&&v.get(N.url);if(!N)return!1;if(!F)return z(N.url),!1;if(!F.naturalWidth)return!1;let{n:T,d:j}=typeof S.speed=="object"?S.speed:{n:1,d:1},R=Qo(S.in+(m-S.at)*T/j,N.every),[K,W]=[F.naturalWidth/10,F.naturalHeight/10],ae=y.getContext("2d"),ue=Math.max(y.width/K,y.height/W);return ae.drawImage(F,R%10*K,Math.floor(R/10)*W,K,W,(y.width-K*ue)/2,(y.height-W*ue)/2,K*ue,W*ue),!0}function z(m){if(v.has(m))return;let S=new Image;v.set(m,S),S.addEventListener("load",le,{once:!0}),S.src=m}function Q(m,S,N,F){c?.picture?.find(j=>j.asset===m.asset&&j.at<m.end&&m.at<j.end&&(j.grade||j.fx||j.lut))&&(f.fillStyle=G("--saffron"),f.fillRect(S,F+ke-5,N-1,3))}function re(m,S,N){let T=S+ke/2;f.fillStyle=G("--sheet"),f.strokeStyle=G("--ink"),f.lineWidth=1.5,f.beginPath(),f.arc(m,T,8,0,Math.PI*2),f.fill(),f.stroke(),f.fillStyle=G("--ink"),f.beginPath(),N==="wipe"?f.rect(m-4,T-4,4,8):N==="slide"?(f.moveTo(m-3,T-4),f.lineTo(m+4,T),f.lineTo(m-3,T+4)):N==="zoom"?(f.arc(m,T,4,0,Math.PI*2),f.arc(m,T,2,0,Math.PI*2,!0)):(f.moveTo(m-4,T-4),f.lineTo(m,T),f.lineTo(m-4,T+4),f.moveTo(m+4,T-4),f.lineTo(m,T),f.lineTo(m+4,T+4)),f.fill("evenodd")}function ne(m,S,N){f.strokeStyle=G("--ghost"),f.lineWidth=1.5,f.beginPath();let F=Math.max(1,Math.floor(m.curve.length/N));for(let T=0;T<m.curve.length;T+=F){let j=L?T/m.rate*Yo/L*N:0,R=S+4+(1-m.curve[T])*(ke-8);T===0?f.moveTo(j,R):f.lineTo(j,R)}f.stroke()}let pe=!1,Z=m=>{let S=p.getBoundingClientRect();a(Math.round(Math.min(1,Math.max(0,(m.clientX-S.left)/S.width))*L))},Be=m=>{if(!de)return null;let S=p.getBoundingClientRect();return m.clientY-S.top>ke?null:gr(P.picture,m.clientX-S.left,{width:S.width,duration:L,pointer:m.pointerType==="touch"?"touch":"mouse"})},fe=m=>{let S=p.getBoundingClientRect(),N=Math.round(Math.min(1,Math.max(0,(m.clientX-S.left)/S.width))*L);X={...X,at:br(N,oe,{width:S.width,duration:L})},le()};p.addEventListener("pointerdown",m=>{p.setPointerCapture(m.pointerId);let S=Be(m);if(S)return X={...S,from:S.at},le();pe=!0,Z(m)}),p.addEventListener("pointermove",m=>{if(x&&m.pointerType!=="touch"){let S=p.getBoundingClientRect(),N=Math.round(Math.min(1,Math.max(0,(m.clientX-S.left)/S.width))*L);E.textContent=_e(N,U),y.hidden=!ve(N),x.hidden=!1;let F=x.offsetWidth/2;x.style.left=`${Math.min(S.width-2*F,Math.max(0,m.clientX-S.left-F))}px`}if(X)return fe(m);if(pe)return Z(m);de&&(p.style.cursor=Be(m)?"ew-resize":"")}),p.addEventListener("pointerup",()=>{if(pe=!1,!X)return;let m=X;X=null,le(),m.at!==m.from&&l({clip:m.clip,edge:m.edge,at:m.at})}),de&&p.addEventListener("pointercancel",()=>{pe=!1,X=null,le()}),x&&p.addEventListener("pointerleave",()=>x.hidden=!0),new ResizeObserver(le).observe(p);function Me(m){D=m;for(let S of w.querySelectorAll("button"))S.setAttribute("aria-pressed",String(S.dataset.clip===m));r(m),le()}return{load(m,{duration:S,fps:N,marks:F=[],pins:T=[]}){V=T,P=m,L=S,U=N,te=F,D&&!P.picture.some(j=>j.clip===D)&&(D=null),J(w);for(let j of P.picture.filter((R,K,W)=>W.findIndex(ae=>ae.clip===R.clip)===K)){let R=t("button",{type:"button","aria-pressed":String(j.clip===D),dataset:{clip:j.clip},onclick:()=>(Me(j.clip),a(j.at))},`Clip ${j.clip}, ${_e(j.at,U)} to ${_e(j.end,U)}`);w.append(t("li",{},R))}le()},setPeaks(m,S){B.set(m,S),le()},setGhost(m){ce=m,le()},setPreview(m){c=m,le()},setSnaps(m){oe=m},setTime(m){q=m,le()},select:Me,get selected(){return D},draw:le}}var Xo=new Set(["filler","stutter","restart"]);function Zo({root:n,onSeek:o,onCut:a,onFix:r=async()=>{}}){let l=[],u=new Map,i=null,p=[],g=null,w=()=>{for(let c of n.querySelectorAll(".word[aria-pressed='true']"))c.setAttribute("aria-pressed","false");for(let c of p)n.querySelector(`[data-word="${CSS.escape(c)}"]`)?.setAttribute("aria-pressed","true")};n.addEventListener("click",c=>{let v=c.target.closest(".word");if(!v)return;let y=u.get(v.dataset.word);if(c.shiftKey&&i){let[E,x]=[l.indexOf(i),l.indexOf(y)].sort((f,P)=>f-P);p=l.slice(E,x+1).filter(f=>f.asset===y.asset).map(f=>f.id)}else i=y,p=[y.id],o(y);w()});function h(c){let v=u.get(c.dataset.word);if(!v)return;let y=t("input",{class:"word-edit",value:v.text,size:String(Math.max(4,v.text.length+2)),maxlength:"60","aria-label":`Fix the word "${v.text}"`});c.replaceWith(y),y.focus(),y.select();let E=!1,x=async f=>{if(E)return;E=!0;let P=y.value.trim();y.replaceWith(c),f&&P&&P!==v.text?await r(v,P):c.focus()};y.addEventListener("keydown",f=>{f.stopPropagation(),f.key==="Enter"?(f.preventDefault(),x(!0)):f.key==="Escape"&&(f.preventDefault(),x(!1))}),y.addEventListener("blur",()=>x(!0))}return n.addEventListener("dblclick",c=>{let v=c.target.closest(".word");v&&h(v)}),n.addEventListener("keydown",c=>{if(c.key==="F2"&&c.target.closest(".word"))return c.preventDefault(),c.stopPropagation(),h(c.target.closest(".word"));(c.key==="Backspace"||c.key==="Delete")&&p.length&&(c.preventDefault(),c.stopPropagation(),a(u.get(p[0]),u.get(p.at(-1))))}),{load({words:c=[],sentences:v=[],takes:y=[]}){l=c,u=new Map(c.map(f=>[f.id,f])),p=p.filter(f=>u.has(f));let E=new Map(y.map(f=>[f.sentence,f]));if(J(n),!c.length){n.append(t("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let x=v.length?v:[...new Set(c.map(f=>f.asset))].map(f=>{let P=c.filter(L=>L.asset===f);return{id:null,asset:f,firstWord:P[0].id,lastWord:P.at(-1).id,score:1}});for(let f of x){let P=E.get(f.id),L=P&&P.rank>1||f.score===0,U=Number(f.firstWord.split(":w")[1]),q=Number(f.lastWord.split(":w")[1]),te=t("p",{class:`sentence${L?" lost":""}`,dataset:f.id?{sentence:f.id}:{}});P&&te.append(t("span",{class:"tag"},P.rank===1?"best take":`take ${P.rank}`));for(let V=U;V<=q;V++){let B=u.get(`${f.asset}:w${V}`);if(!B)continue;let D=L||B.flags.some(X=>Xo.has(X)),ce=D?`${B.text} (${L?"retake":B.flags.filter(X=>Xo.has(X)).join(", ")})`:null,de=typeof B.heard=="string",oe=t("button",{type:"button",class:`word${D?" struck":""}${!de&&B.flags.includes("low_confidence")?" unsure":""}${de?" fixed":""}`,"aria-pressed":"false","aria-label":ce??(de?`${B.text} (fixed; heard as ${B.heard})`:null),title:de?`Heard as "${B.heard}". Double-click to change.`:"Double-click to fix this word",dataset:{word:B.id}});oe.textContent=B.text,te.append(oe," ")}n.append(te)}w()},playing(c){c!==g&&(n.querySelector(".word.now")?.classList.remove("now"),g=c,c&&n.querySelector(`[data-word="${CSS.escape(c)}"]`)?.classList.add("now"))},words:()=>l,selection:()=>p.length?[p[0],p.at(-1)]:null,clear(){p=[],i=null,w()}}}var us={format:"Format",seconds:"Length",captions:"Captions",grade:"Look",music:"Music",cleanVoice:"Clean the voice",cutSound:"Sound on each cut",introSound:"Sound into the story",punches:"Punch-ins",angles:"Two angles from one camera",broll:"B-roll from your clips",titles:"Title cards",ramps:"Speed ramps",transition:"Transitions"};function Nt(n,o){return typeof o=="boolean"?o?"yes":"no":n==="seconds"?`${o} seconds`:n==="punches"?`${o}`:o==="none"?"none":String(o)}function ea(n){let o=`${us[n.field]??n.field}: ${Nt(n.field,n.value)}`,a=n.evidence?` (you said "${n.evidence}")`:"",r=n.by==="code"&&n.model!==void 0?`; read by Kriya's code, not as ${Nt(n.field,n.model)}`:"";return`${o}${a}${r}`}function ta(n,o,a){return o==="music"?a==="none"||a==="reference"?delete n.music:n.music=`generated:${a}`:o==="transition"?a==="none"?(delete n.transition,delete n.transitionAll):n.transition=a:typeof a=="boolean"?a?n[o]=!0:delete n[o]:o==="broll"?a==="own"?n.broll="own":delete n.broll:{captions:"none",grade:"natural",cutSound:"none",introSound:"none"}[o]===a?delete n[o]:n[o]=a,n}var ps=document.getElementById("app"),na=["direct","edit","finish"],Se=(n,o)=>{try{if(o===void 0)return localStorage.getItem(n);localStorage.setItem(n,o)}catch{return null}},wr=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function sa(...n){let o=wr();return t("header",{class:"bar"},o?t("a",{class:"btn ghost",href:o},"\u2190 Kriya Harness"):t("span",{class:"brand"},"Kriya"),t("span",{class:"title"},"Editing Studio"),...n)}function vn(n){J(ps).append(t("main",{class:"center"},t("h1",{},"Open the Studio from Kriya"),t("p",{},n??"Click Editing Studio in Kriya Harness, or run kriya edit and open its link.")))}function kr(n){return new Promise(o=>{let a=t("ul",{class:"folders","aria-label":"Folders"}),r=t("p",{class:"label-mono where"}),l=t("p",{class:"note",role:"status"}),u=t("input",{class:"field",placeholder:"New folder name","aria-label":"New folder name",maxlength:"80"}),i=null,p=h=>{w.close(),w.remove(),o(h)};async function g(h){try{let c=await Y("GET",`/browse${h?`?root=${encodeURIComponent(h)}`:""}`);i=c.root,r.textContent=c.root,J(a),c.parent&&a.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>g(c.parent)},"\u2191 Up")));let v=c.entries.filter(y=>y.kind==="folder");for(let y of v)a.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>g(`${c.root}/${y.name}`)},`\u{1F4C1} ${y.name}`)));v.length||a.append(t("li",{class:"note"},"No folders here.")),l.textContent=""}catch(c){l.textContent=c.message}}let w=t("dialog",{class:"picker","aria-label":"Choose a folder"},t("h2",{},"Choose a folder"),r,a,t("form",{class:"row tight",onsubmit:async h=>{h.preventDefault();try{let{folder:c}=await Y("POST","/browse/folder",{parent:i,name:u.value});u.value="",await g(c)}catch(c){l.textContent=c.message}}},u,t("button",{type:"submit",class:"btn"},"New folder")),l,t("div",{class:"row end"},t("button",{type:"button",class:"btn",onclick:()=>p(null)},"Cancel"),t("button",{type:"button",class:"btn primary",onclick:()=>p(i)},"Use this folder")));w.addEventListener("cancel",h=>(h.preventDefault(),p(null))),document.body.append(w),w.showModal(),g(n)})}async function oa(){let n;try{({projects:n}=await Y("GET","/projects"))}catch(g){return g.status===401?vn():vn(g.message)}let o=t("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),a=t("input",{id:"new-folder",class:"field",required:!0,readonly:!0,placeholder:"Choose a folder\u2026"}),r=t("button",{type:"button",class:"btn",onclick:()=>kr(a.value||null).then(g=>g&&(a.value=g,l.textContent=""))},"Choose\u2026"),l=t("p",{class:"note",role:"status"}),u=t("form",{class:"panel new",onsubmit:async g=>{if(g.preventDefault(),!a.value)return l.textContent="Choose a folder for the project first.";try{let{id:w}=await Y("POST","/projects",{name:o.value.trim(),folder:a.value.trim()});location.hash=`#/p/${w}`}catch(w){l.textContent=w.message}}},t("h2",{},"New project"),t("label",{for:"new-name"},"Name"),o,t("label",{for:"new-folder"},"Folder for the project (its footage stays where it is)"),t("div",{class:"row tight"},a,r),t("button",{class:"btn primary",type:"submit"},"Create"),l),i=t("section",{class:"panel taste","aria-label":"Your taste"}),p=async g=>{let{proposed:w,confirmed:h}=g??await Y("GET","/taste"),c=(v,y)=>async()=>p(await Y("POST",`/taste/${encodeURIComponent(v)}/${y}`));J(i).append(t("h2",{},"Your taste"),...w.length||h.length?[]:[t("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...w.map(v=>t("div",{class:"taste-row"},t("p",{},v.sentence),t("button",{type:"button",class:"btn primary",onclick:c(v.key,"confirm")},"Use it"),t("button",{type:"button",class:"btn",onclick:c(v.key,"dismiss")},"No"))),...h.map(v=>t("div",{class:"taste-row"},t("p",{},v.shown),t("button",{type:"button",class:"btn","aria-label":`Remove the rule ${v.shown}`,onclick:c(v.key,"remove")},"Remove"))))};p().catch(()=>{}),J(ps).append(sa(),t("main",{class:"home"},t("h1",{},"What are we making?"),t("section",{class:"panel"},t("h2",{},"Projects"),n.length?t("ul",{class:"projects"},n.map(g=>t("li",{class:"project-row"},t("a",{class:"btn open",href:`#/p/${g.id}`},g.name),t("button",{type:"button",class:"btn ghost danger","aria-label":`Delete the project ${g.name}`,onclick:async()=>{if(confirm(`Delete "${g.name}" from the Studio?
2
2
 
3
- Its edit history, cache and index on this computer are removed. Your folder, footage, exports and the project file stay where they are.`))try{await Y("DELETE",`/projects/${g.id}`),na()}catch(w){alert(w.message)}}},"Delete")))):t("p",{class:"note"},"No projects yet.")),u,i))}async function yr(n){let o;try{o=await Y("GET",`/projects/${n}`)}catch(e){return e.status===401?vn():vn(e.message)}let a=o.project,r=o.assets,l={assets:[],words:[],sentences:[],takes:[],shots:[]},u=[],i={picture:[],overlays:[],audio:[],captions:[]},p=null,g=ea.includes(Se("kriya-edit-mode"))?Se("kriya-edit-mode"):"direct",w=!1,h=o.assembly===!0,c=o.livePreview===!0,v=o.customMotion===!0,y=o.typeKit??null,E={single:"One word",duo:"Two words",marker:"Marker",underline:"Underline",grow:"Grow",typewriter:"Typewriter",headline:"Headline",subtle:"Subtle"},x=null,f=o.head??null,P=e=>e.offline?null:e.kind==="video"?{url:`/tiles/${e.media}?kind=thumbs`,sheet:!0}:e.kind==="image"?{url:`/media/${e.media}`,sheet:!1}:null,L=e=>({asset:e.id,number:e.number,name:jt(e),duration:e.facts.duration,thumb:P(e)}),H=()=>r.filter(e=>e.number).map(L),q=()=>a.canvas.fps,te=t("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),V=t("span",{class:"chip"},"Preview"),B=t("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),D=t("p",{class:"note",role:"status","aria-live":"polite"}),ce=c?t("span",{class:"level-fill"}):null,de=c?t("span",{class:"level","aria-hidden":"true",title:"Sound level of the preview"},ce):null,oe=c?t("span",{class:"director-badge",hidden:!0},"Director working preview"):null,X=()=>{if(!ce)return;let e=K.level();ce.style.width=`${(wo(e)*100).toFixed(1)}%`,de.classList.toggle("hot",e>-6)},K=Mo({canvas:B,urlOf:e=>`/media/${r.find(s=>s.id===e).media}`,assetOf:e=>r.find(s=>s.id===e),onTime:e=>{te.textContent=`${_e(e,q())} / ${_e(z(),q())}`,X(),fe.setTime(e),S.setTime(e);let s=vt(ve(),e),d=s?lt(s,e):null,k=d===null?null:l.words.find(b=>b.asset===s.asset&&d>=b.start&&d<b.end);Z.playing(k?.id??null)},onRate:e=>{e===0&&(X(),Ns()),rn.textContent=e===0?"Play":"Pause",rn.setAttribute("aria-label",e===0?"Play (Space)":`Pause (Space), playing at ${e}\xD7`)},...c?{tileUrl:e=>`/projects/${n}/tile-preview?key=${e}`}:{}}),le=e=>c&&x?{...e,preview:x}:e,me=()=>({"16:9":{width:1920,height:1080},"9:16":{width:1080,height:1920}})[Un.value]??a.canvas,ve=()=>p?ns(r.find(e=>e.id===p)):u,z=()=>Ue(ve()),Q=t("div",{class:"transcript",tabindex:"-1"}),re=t("div",{class:"strip"}),ne=t("div",{class:"timeline"}),pe=t("div",{class:"finish"}),Z=Yo({root:Q,onSeek:e=>{let s=It(u,e.asset,e.start);s!==null?(T(),K.seek(s)):j(e.asset,e.start)},onCut:(e,s)=>G([{op:"remove_range",asset:e.asset,from:{word:e.id,edge:"start"},to:{word:s.id,edge:"end"}}]),onFix:async(e,s)=>{try{await Y("POST",`/projects/${n}/words/${encodeURIComponent(e.id)}`,{text:s}),D.textContent=`Fixed "${e.text}" to "${s}". Captions and Kriya use it from now on.`}catch(d){D.textContent=d.message}await R()}}),fe=cs({root:ne,onSeek:e=>(T(),K.seek(e)),...c?{onTrim:Me,rich:{thumbs:e=>{let s=r.find(d=>d.id===e);return!s||s.offline||s.kind!=="video"||!s.facts?.duration?null:{url:`/tiles/${s.media}?kind=thumbs`,every:Math.max(1,Math.ceil(s.facts.duration/7056e5/100))}}}}:{}});function Me({clip:e,edge:s,at:d}){let k=i.picture.filter(A=>A.clip===e).sort((A,_)=>A.at-_.at),b=s==="in"?k[0]:k.at(-1);if(!b||b.hold)return;let{n:$,d:C}=typeof b.speed=="object"?b.speed:{n:1,d:1},M=r.find(A=>A.id===b.asset)?.facts.duration??b.out,I=Math.min(M,Math.max(0,b.in+Math.round((wt(d,q())-b.at)*$/C))),O=s==="in"?k.at(-1).out:k[0].in;return(s==="in"?I>=O:I<=O)?D.textContent="That would leave nothing of the clip.":G([{op:"trim",clip:e,[s]:I}])}function m(){let e=[...x?.beats??[]],s=new Map;for(let d of[...i.picture].sort((k,b)=>k.at-b.at))s.set(d.clip,[...s.get(d.clip)??[],d]);for(let d of s.values()){let[k,b]=[d[0],d.at(-1)];if(k.hold)continue;let{n:$,d:C}=typeof k.speed=="object"?k.speed:{n:1,d:1};for(let M of l.words??[])if(M.asset===k.asset)for(let I of[M.start,M.end]){let A=It(d,M.asset,I)??(I<k.in?k.at+Math.round((I-k.in)*C/$):I>=b.out?b.at+Math.round((I-b.in)*C/$):null);A!==null&&e.push(A)}}return e}let S=cs({root:re,compact:!0,onSeek:e=>(T(),K.seek(e))}),N=t("div",{class:"area-final"}),F=ao({root:pe,finalRoot:N,pixels:()=>K.pixels(),project:()=>a,onAdjust:()=>rt("edit"),scorecard:c,...c?{head:()=>f,onShow:e=>(rt("edit"),T(),K.seek(e))}:{}});function T(){if(p){if(p=null,V.textContent="Preview",nt&&Ve)return void sn(Ve);K.load(u,le({fps:q(),duration:Ue(u),shape:me()}))}}function j(e,s){p=e;let d=r.find(k=>k.id===e).facts;V.textContent="Source",K.load(ns(r.find(k=>k.id===e)),{fps:d.fps??q(),duration:d.duration,shape:{width:d.width??1920,height:d.height??1080}}).then(()=>K.seek(s))}async function R(){let[e,s,d,k]=await Promise.all([Y("GET",`/projects/${n}`),Y("GET",`/projects/${n}/plan`),Y("GET",`/projects/${n}/index`),c?Y("GET",`/projects/${n}/preview`).catch(()=>null):null]);x=k,a=e.project,f=e.head,r=e.assets,l=d,i=s.timeline,u=gn(s.timeline);let b=Ue(u),$=So(u,l.shots),C=new Map((l.words??[]).map(O=>[O.id,O])),I=(a.sequences.find(O=>O.id===a.active)?.markers??[]).flatMap(O=>{let A=O.name.startsWith("Note: ")&&O.at?.word?C.get(O.at.word):null,_=A?It(u,A.asset,A.start):null;return _==null?[]:[{at:_,name:O.name}]});if(fe.load(i,{duration:b,fps:q(),marks:$,pins:I}),c&&fe.setSnaps(m()),c&&(fe.setPreview(x),ft?.refresh()),S.load({picture:i.picture},{duration:b,fps:q(),marks:$}),Z.load(l),zt(),xn(),da?.load(a),!w){w=!0;let O=[...Ee.options].map(A=>A.value).find(A=>{let[_,ee]=A.split(":").map(Number);return _*a.canvas.height===ee*a.canvas.width});O&&a.sequences.some(A=>A.clips.length)&&(Ee.value=O)}p||(V.textContent="Preview"),!p&&nt&&Ve?await sn(Ve):!p&&!ot?.open&&await K.load(u,le({fps:q(),duration:b,shape:me()}));for(let O of new Set([...i.audio,...i.picture].map(A=>A.asset))){let A=r.find(_=>_.id===O)?.media;A&&r.find(_=>_.id===O).facts.hasAudio&&fetch(`/tiles/${A}?kind=peaks`).then(_=>_.ok?_.json():null).then(_=>_&&(fe.setPeaks(O,_.levels[0]),S.setPeaks(O,_.levels[0]))).catch(()=>{})}}async function G(e){try{let s=await Y("PATCH",`/projects/${n}`,{ops:e});D.textContent=s.diagnostics?.length?s.diagnostics[0].message:""}catch(s){D.textContent=s.value?.diagnostics?.[0]?.message??s.message}await R()}let W=t("ul",{class:"bin","aria-label":"Footage"}),ae=new Map,ue=e=>[...ae.values()].find(s=>s.kind==="index"&&s.asset===e&&["pending","running"].includes(s.status)),se=(e,s)=>{let d=t("span",{class:e===null?"busy":""});return e!==null&&(d.style.width=`${e}%`),t("div",{class:"progress",role:"progressbar","aria-label":s,"aria-valuemin":"0","aria-valuemax":"100",...e===null?{}:{"aria-valuenow":String(e)}},d)},he=t("input",{type:"search",id:"bin-search",class:"field",placeholder:"Label, file name or words said",autocomplete:"off",oninput:()=>$t()}),Le=t("select",{id:"bin-sort",class:"field select","aria-label":"Sort the bin",onchange:()=>$t()},Object.entries(Qs).map(([e,s])=>t("option",{value:e},`Sort: ${s.toLowerCase()}`))),Ze=t("select",{id:"bin-group",class:"field select","aria-label":"Group the bin",onchange:()=>$t()},Object.entries(Xs).map(([e,s])=>t("option",{value:e},s))),Dt=h?t("div",{class:"bin-tools"},t("label",{for:"bin-search",class:"sr-only"},"Search the bin"),he,Le,Ze):null,oa={aroll:"Talking",broll:"B-roll",screen:"Screen recording",music:"Music",sfx:"Sound effect",logo:"Logo"},ps={asset:236,head:36};function fs(e,s){let d=t("input",{class:"field",value:e.label??"",maxlength:"40","aria-label":`Label for clip ${e.number}`,placeholder:"A label, such as intro"});s.replaceWith(d),d.focus(),d.select();let k=!1,b=$=>{if(k)return;k=!0;let C=d.value.trim();d.replaceWith(s),$&&C!==(e.label??"")?G([{op:"describe_asset",asset:e.id,label:C}]):s.focus()};d.addEventListener("keydown",$=>{$.stopPropagation(),$.key==="Enter"?($.preventDefault(),b(!0)):$.key==="Escape"&&($.preventDefault(),b(!1))}),d.addEventListener("blur",()=>b(!0))}function hs(e){let s=l.assets.find(A=>A.asset===e.id),d=s?.layers.find(A=>A.layer==="L2"),k=ue(e.id),b=Ge?.speech?"Indexed, no words yet: set up speech-to-text above":d?.notice??"Indexed, no words",$=k?`Reading this file\u2026 ${k.progress??0}%`:s?d?.status==="ok"?"Indexed":b:"Not indexed",C=["video","audio"].includes(e.kind),M=h&&e.number,I=t("button",{type:"button",class:"btn",onclick:()=>j(e.id,0)},`${M?jt(e):e.path.split(/[\\/]/).at(-1)} \xB7 ${e.kind}`);M&&(I.title=`${fn(e)}. Double-click or F2 to label it.`,I.addEventListener("dblclick",()=>fs(e,I)),I.addEventListener("keydown",A=>A.key==="F2"&&(A.preventDefault(),A.stopPropagation(),fs(e,I))));let O=M?t("select",{class:"field select","aria-label":`What clip ${e.number} is`,onchange:()=>G([{op:"describe_asset",asset:e.id,role:O.value}])},[e.role?null:t("option",{value:"",disabled:!0},"What it is\u2026"),...Object.entries(oa).map(([A,_])=>t("option",{value:A},_))]):null;return O&&(O.value=e.role??""),t("li",{class:`asset${M?" handle":""}`,...M?{draggable:"true",ondragstart:A=>A.dataTransfer.setData(De,JSON.stringify({asset:e.id}))}:{}},M?t("div",{class:"asset-head"},Rt(L(e)),t("span",{class:"badge","aria-label":`Clip ${e.number}`},String(e.number)),I):I,t("span",{class:"note"},e.offline?"Offline: the file has moved":$),k?se(k.progress??0,`Indexing ${e.path.split(/[\\/]/).at(-1)}`):null,O,C?t("button",{type:"button",class:"btn",disabled:!!k,onclick:()=>aa(e)},s?"Index again":"Index"):null,C?t("button",{type:"button",class:"btn",onclick:()=>G([{op:"keep_range",asset:e.id,from:0,to:e.facts.duration}])},"Add to cut"):null)}function $t(){let e=r.filter(C=>C.kind!=="reference"),s=document.activeElement===he,d=W.scrollTop;if(J(W),W.classList.remove("virtual"),!h)return W.append(...e.map(hs));let k=Ys(Js(e,l.words,he.value),Le.value),b=Zs(k,Ze.value).flatMap(C=>[...C.name===null?[]:[{head:`${C.name} \xB7 ${C.assets.length}`}],...C.assets]),$=C=>C.head?t("li",{class:"bin-group label-mono"},C.head):hs(C);if(he.value.trim()&&!k.length)W.append(t("li",{class:"note"},"Nothing in the bin matches that."));else if(b.length<=eo)W.append(...b.map($));else{W.classList.add("virtual");let{start:C,end:M,before:I,after:O}=to(b.map(_=>_.head?ps.head:ps.asset),d,W.clientHeight||600),A=_=>{let ee=t("li",{class:"bin-space","aria-hidden":"true"});return ee.style.height=`${_}px`,ee};W.append(A(I),...b.slice(C,M).map($),A(O)),W.scrollTop=d}s&&he.focus()}let ms=0;W.addEventListener("scroll",()=>W.classList.contains("virtual")&&(cancelAnimationFrame(ms),ms=requestAnimationFrame($t)));function xn(){$t(),Oe()}async function aa(e){Ge?.speech&&!Ge.setup?.error&&(D.textContent="Your file is indexed without words until speech-to-text is set up (above).",Tn.hidden=!1);try{let s=await Y("POST",`/projects/${n}/index`,{asset:e.id});ae.set(s.id,{...s,asset:e.id}),D.textContent="Reading your footage. You can keep working.",xn()}catch(s){D.textContent=s.message}}function gs(e,{reference:s=!1,aspect:d="all"}={}){let k=b=>new Promise(($,C)=>{let M=t("li",{class:"asset"},t("span",{class:"note"},`Copying ${b.name}\u2026`),se(0,`Copying ${b.name}`));bs.append(M);let I=new XMLHttpRequest;I.open("POST",`/projects/${n}/upload?name=${encodeURIComponent(b.name)}${s?"&as=reference":""}`),I.upload.onprogress=O=>{if(!O.lengthComputable)return;let A=Math.round(O.loaded*100/O.total);M.querySelector(".progress span").style.width=`${A}%`,M.querySelector(".progress").setAttribute("aria-valuenow",String(A)),M.querySelector(".note").textContent=`Copying ${b.name}\u2026 ${A}%`},I.onload=()=>{M.remove();let O={};try{O=JSON.parse(I.responseText)}catch{}I.status<300?$(O):C(new Error(O.message??`The Edit Host answered ${I.status}.`))},I.onerror=()=>(M.remove(),C(new Error(`${b.name} couldn't be copied.`))),I.send(b)});return(async()=>{for(let b of e)try{let $=await k(b);D.textContent=s?`Added ${b.name} as a reference for ${et[d].toLowerCase()}.`:`Added ${b.name}. Index it to read its words.`,s&&(Fe.add($.id),Se(Ft($.id),d))}catch($){D.textContent=$.message}await R()})()}let bs=t("ul",{class:"bin","aria-label":"Copying"}),Bt=t("input",{type:"file",multiple:!0,accept:"video/*,audio/*,.mov,.mp4,.m4v,.mkv,.wav,.mp3,.m4a,.aac,.flac,.cube",hidden:!0,id:"pick-files",onchange:()=>(gs([...Bt.files]),Bt.value="")}),$n=t("input",{id:"add-path",class:"field",placeholder:"/Users/you/Movies/take.mov",autocomplete:"off"}),ra=t("section",{class:"panel bin-panel","aria-label":"Bin"},t("h2",{},"Bin"),Dt,W,bs,Bt,t("button",{type:"button",class:"btn primary wide",onclick:()=>Bt.click()},"Add files\u2026"),t("p",{class:"note small"},"Copied into the project's media folder; your originals aren't touched."),t("details",{class:"by-path"},t("summary",{},"Link a file by its path instead (no copy)"),t("form",{class:"row",onsubmit:async e=>{e.preventDefault();try{await Y("POST",`/projects/${n}/assets`,{path:$n.value.trim()}),$n.value="",await R()}catch(s){D.textContent=s.message}}},t("label",{for:"add-path",class:"sr-only"},"Link a file by its path"),$n,t("button",{class:"btn",type:"submit"},"Link")))),Fe=new Set,ys=new Set,et={all:"Everything it shows",editing:"Editing: cuts and pace",sound:"Sound: music and feel",colour:"Colour grade",graphics:"Graphics: captions and text"},Ft=e=>`kriya-ref-aspect:${n}:${e}`,Gt=e=>Object.hasOwn(et,Se(Ft(e))??"")?Se(Ft(e)):"all",Sn=(e,s,d)=>t("select",{class:"field select",...e,onchange:d},Object.entries(et).map(([k,b])=>t("option",{value:k,selected:k===s},b))),Kt=Sn({id:"ref-aspect","aria-label":"The next reference is for"},"all",()=>Mn.value=Kt.value),Mn=Sn({id:"ref-aspect-bin","aria-label":"The next reference is for"},"all",()=>Kt.value=Mn.value),ia=(e,s)=>e.parts?s!=="all"?e.parts[s]?[e.parts[s]]:[`Nothing to take for ${et[s].toLowerCase()} from this one.`]:e.lines.filter(d=>!(e.kind==="video"&&e.pace&&d===e.parts.sound)):e.lines,St=new Map,Wt=o.referenceIntent===!0,Ce=new Map,ws=e=>`kriya-ref-style-off:${n}:${e}`,Cn=e=>new Set((Se(ws(e))??"").split(",").filter(Boolean)),ks=e=>Y("GET",`/projects/${n}/references/${encodeURIComponent(e)}/brief?format=${encodeURIComponent(Ee.value)}`).then(s=>(Ce.set(e,s.status==="ready"?{status:"ready",brief:s.brief}:{status:"none"}),Oe())).catch(()=>(Ce.set(e,{status:"none"}),Oe()));async function la(e){try{let s=await Y("POST",`/projects/${n}/references/${encodeURIComponent(e)}/measure`);ae.set(s.id,s),Ce.set(e,{status:"measuring",progress:0,job:s.id})}catch(s){Ce.set(e,{status:"failed",error:s.message})}Oe(`style-cancel-direct-${e}`)}function ca(e){if(!(e?.kind!=="reference"||!e.asset)){if(e.status==="pending"||e.status==="running")Ce.set(e.asset,{status:"measuring",progress:e.progress??0,job:e.id});else{if(e.status==="done")return void ks(e.asset);Ce.set(e.asset,e.status==="canceled"?{status:"none"}:{status:"failed",error:e.error??"the measure stopped"})}Oe()}}let vs=()=>{if(!Wt)return{};let e=[...Fe].find(s=>Ce.get(s)?.status==="ready"&&Gt(s)==="all"&&r.some(d=>d.id===s&&d.kind==="reference"));return e?{styleBrief:{ref:e,off:[...Cn(e)]}}:{}},_t=t("ul",{class:"bin","aria-label":"References"}),Ln=t("ul",{class:"bin refs-direct","aria-label":"References for this cut"}),xs=t("p",{class:"note small"}),Mt=t("input",{type:"file",accept:"video/*,image/*,audio/*,.mov,.mp4,.m4v,.mkv,.webm,.jpg,.jpeg,.png,.webp,.wav,.mp3,.m4a,.aac,.flac",hidden:!0,id:"pick-reference",onchange:()=>{let e=[...Mt.files];Mt.value="";let s=Kt.value,d=s==="all"?"a video's pace, captions, colour and music; an image's colour grade; music's tempo and energy":`only its ${et[s].toLowerCase()}`;e.length&&confirm(`Use this only as a reference for ${et[s].toLowerCase()}?
3
+ Its edit history, cache and index on this computer are removed. Your folder, footage, exports and the project file stay where they are.`))try{await Y("DELETE",`/projects/${g.id}`),oa()}catch(w){alert(w.message)}}},"Delete")))):t("p",{class:"note"},"No projects yet.")),u,i))}async function vr(n){let o;try{o=await Y("GET",`/projects/${n}`)}catch(e){return e.status===401?vn():vn(e.message)}let a=o.project,r=o.assets,l={assets:[],words:[],sentences:[],takes:[],shots:[]},u=[],i={picture:[],overlays:[],audio:[],captions:[]},p=null,g=na.includes(Se("kriya-edit-mode"))?Se("kriya-edit-mode"):"direct",w=!1,h=o.assembly===!0,c=o.livePreview===!0,v=o.customMotion===!0,y=o.typeKit??null,E={single:"One word",duo:"Two words",marker:"Marker",underline:"Underline",grow:"Grow",typewriter:"Typewriter",headline:"Headline",subtle:"Subtle"},x=null,f=o.head??null,P=e=>e.offline?null:e.kind==="video"?{url:`/tiles/${e.media}?kind=thumbs`,sheet:!0}:e.kind==="image"?{url:`/media/${e.media}`,sheet:!1}:null,L=e=>({asset:e.id,number:e.number,name:jt(e),duration:e.facts.duration,thumb:P(e)}),U=()=>r.filter(e=>e.number).map(L),q=()=>a.canvas.fps,te=t("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),V=t("span",{class:"chip"},"Preview"),B=t("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),D=t("p",{class:"note",role:"status","aria-live":"polite"}),ce=c?t("span",{class:"level-fill"}):null,de=c?t("span",{class:"level","aria-hidden":"true",title:"Sound level of the preview"},ce):null,oe=c?t("span",{class:"director-badge",hidden:!0},"Director working preview"):null,X=()=>{if(!ce)return;let e=G.level();ce.style.width=`${(vo(e)*100).toFixed(1)}%`,de.classList.toggle("hot",e>-6)},G=Lo({canvas:B,urlOf:e=>`/media/${r.find(s=>s.id===e).media}`,assetOf:e=>r.find(s=>s.id===e),onTime:e=>{te.textContent=`${_e(e,q())} / ${_e(z(),q())}`,X(),fe.setTime(e),S.setTime(e);let s=vt(ve(),e),d=s?lt(s,e):null,k=d===null?null:l.words.find(b=>b.asset===s.asset&&d>=b.start&&d<b.end);Z.playing(k?.id??null)},onRate:e=>{e===0&&(X(),Bs()),rn.textContent=e===0?"Play":"Pause",rn.setAttribute("aria-label",e===0?"Play (Space)":`Pause (Space), playing at ${e}\xD7`)},...c?{tileUrl:e=>`/projects/${n}/tile-preview?key=${e}`}:{}}),le=e=>c&&x?{...e,preview:x}:e,me=()=>({"16:9":{width:1920,height:1080},"9:16":{width:1080,height:1920}})[Un.value]??a.canvas,ve=()=>p?ss(r.find(e=>e.id===p)):u,z=()=>He(ve()),Q=t("div",{class:"transcript",tabindex:"-1"}),re=t("div",{class:"strip"}),ne=t("div",{class:"timeline"}),pe=t("div",{class:"finish"}),Z=Zo({root:Q,onSeek:e=>{let s=It(u,e.asset,e.start);s!==null?(T(),G.seek(s)):j(e.asset,e.start)},onCut:(e,s)=>K([{op:"remove_range",asset:e.asset,from:{word:e.id,edge:"start"},to:{word:s.id,edge:"end"}}]),onFix:async(e,s)=>{try{await Y("POST",`/projects/${n}/words/${encodeURIComponent(e.id)}`,{text:s}),D.textContent=`Fixed "${e.text}" to "${s}". Captions and Kriya use it from now on.`}catch(d){D.textContent=d.message}await R()}}),fe=ds({root:ne,onSeek:e=>(T(),G.seek(e)),...c?{onTrim:Me,rich:{thumbs:e=>{let s=r.find(d=>d.id===e);return!s||s.offline||s.kind!=="video"||!s.facts?.duration?null:{url:`/tiles/${s.media}?kind=thumbs`,every:Math.max(1,Math.ceil(s.facts.duration/7056e5/100))}}}}:{}});function Me({clip:e,edge:s,at:d}){let k=i.picture.filter(A=>A.clip===e).sort((A,_)=>A.at-_.at),b=s==="in"?k[0]:k.at(-1);if(!b||b.hold)return;let{n:$,d:C}=typeof b.speed=="object"?b.speed:{n:1,d:1},M=r.find(A=>A.id===b.asset)?.facts.duration??b.out,I=Math.min(M,Math.max(0,b.in+Math.round((wt(d,q())-b.at)*$/C))),O=s==="in"?k.at(-1).out:k[0].in;return(s==="in"?I>=O:I<=O)?D.textContent="That would leave nothing of the clip.":K([{op:"trim",clip:e,[s]:I}])}function m(){let e=[...x?.beats??[]],s=new Map;for(let d of[...i.picture].sort((k,b)=>k.at-b.at))s.set(d.clip,[...s.get(d.clip)??[],d]);for(let d of s.values()){let[k,b]=[d[0],d.at(-1)];if(k.hold)continue;let{n:$,d:C}=typeof k.speed=="object"?k.speed:{n:1,d:1};for(let M of l.words??[])if(M.asset===k.asset)for(let I of[M.start,M.end]){let A=It(d,M.asset,I)??(I<k.in?k.at+Math.round((I-k.in)*C/$):I>=b.out?b.at+Math.round((I-b.in)*C/$):null);A!==null&&e.push(A)}}return e}let S=ds({root:re,compact:!0,onSeek:e=>(T(),G.seek(e))}),N=t("div",{class:"area-final"}),F=io({root:pe,finalRoot:N,pixels:()=>G.pixels(),project:()=>a,onAdjust:()=>rt("edit"),scorecard:c,...c?{head:()=>f,onShow:e=>(rt("edit"),T(),G.seek(e))}:{}});function T(){if(p){if(p=null,V.textContent="Preview",nt&&Ve)return void sn(Ve);G.load(u,le({fps:q(),duration:He(u),shape:me()}))}}function j(e,s){p=e;let d=r.find(k=>k.id===e).facts;V.textContent="Source",G.load(ss(r.find(k=>k.id===e)),{fps:d.fps??q(),duration:d.duration,shape:{width:d.width??1920,height:d.height??1080}}).then(()=>G.seek(s))}async function R(){let[e,s,d,k]=await Promise.all([Y("GET",`/projects/${n}`),Y("GET",`/projects/${n}/plan`),Y("GET",`/projects/${n}/index`),c?Y("GET",`/projects/${n}/preview`).catch(()=>null):null]);x=k,a=e.project,f=e.head,r=e.assets,l=d,i=s.timeline,u=gn(s.timeline);let b=He(u),$=Co(u,l.shots),C=new Map((l.words??[]).map(O=>[O.id,O])),I=(a.sequences.find(O=>O.id===a.active)?.markers??[]).flatMap(O=>{let A=O.name.startsWith("Note: ")&&O.at?.word?C.get(O.at.word):null,_=A?It(u,A.asset,A.start):null;return _==null?[]:[{at:_,name:O.name}]});if(fe.load(i,{duration:b,fps:q(),marks:$,pins:I}),c&&fe.setSnaps(m()),c&&(fe.setPreview(x),ft?.refresh()),S.load({picture:i.picture},{duration:b,fps:q(),marks:$}),Z.load(l),zt(),xn(),fa?.load(a),!w){w=!0;let O=[...Ee.options].map(A=>A.value).find(A=>{let[_,ee]=A.split(":").map(Number);return _*a.canvas.height===ee*a.canvas.width});O&&a.sequences.some(A=>A.clips.length)&&(Ee.value=O)}p||(V.textContent="Preview"),!p&&nt&&Ve?await sn(Ve):!p&&!ot?.open&&await G.load(u,le({fps:q(),duration:b,shape:me()}));for(let O of new Set([...i.audio,...i.picture].map(A=>A.asset))){let A=r.find(_=>_.id===O)?.media;A&&r.find(_=>_.id===O).facts.hasAudio&&fetch(`/tiles/${A}?kind=peaks`).then(_=>_.ok?_.json():null).then(_=>_&&(fe.setPeaks(O,_.levels[0]),S.setPeaks(O,_.levels[0]))).catch(()=>{})}}async function K(e){try{let s=await Y("PATCH",`/projects/${n}`,{ops:e});D.textContent=s.diagnostics?.length?s.diagnostics[0].message:""}catch(s){D.textContent=s.value?.diagnostics?.[0]?.message??s.message}await R()}let W=t("ul",{class:"bin","aria-label":"Footage"}),ae=new Map,ue=e=>[...ae.values()].find(s=>s.kind==="index"&&s.asset===e&&["pending","running"].includes(s.status)),se=(e,s)=>{let d=t("span",{class:e===null?"busy":""});return e!==null&&(d.style.width=`${e}%`),t("div",{class:"progress",role:"progressbar","aria-label":s,"aria-valuemin":"0","aria-valuemax":"100",...e===null?{}:{"aria-valuenow":String(e)}},d)},he=t("input",{type:"search",id:"bin-search",class:"field",placeholder:"Label, file name or words said",autocomplete:"off",oninput:()=>$t()}),Le=t("select",{id:"bin-sort",class:"field select","aria-label":"Sort the bin",onchange:()=>$t()},Object.entries(Xs).map(([e,s])=>t("option",{value:e},`Sort: ${s.toLowerCase()}`))),Ze=t("select",{id:"bin-group",class:"field select","aria-label":"Group the bin",onchange:()=>$t()},Object.entries(eo).map(([e,s])=>t("option",{value:e},s))),Dt=h?t("div",{class:"bin-tools"},t("label",{for:"bin-search",class:"sr-only"},"Search the bin"),he,Le,Ze):null,ra={aroll:"Talking",broll:"B-roll",screen:"Screen recording",music:"Music",sfx:"Sound effect",logo:"Logo"},fs={asset:236,head:36};function hs(e,s){let d=t("input",{class:"field",value:e.label??"",maxlength:"40","aria-label":`Label for clip ${e.number}`,placeholder:"A label, such as intro"});s.replaceWith(d),d.focus(),d.select();let k=!1,b=$=>{if(k)return;k=!0;let C=d.value.trim();d.replaceWith(s),$&&C!==(e.label??"")?K([{op:"describe_asset",asset:e.id,label:C}]):s.focus()};d.addEventListener("keydown",$=>{$.stopPropagation(),$.key==="Enter"?($.preventDefault(),b(!0)):$.key==="Escape"&&($.preventDefault(),b(!1))}),d.addEventListener("blur",()=>b(!0))}function ms(e){let s=l.assets.find(A=>A.asset===e.id),d=s?.layers.find(A=>A.layer==="L2"),k=ue(e.id),b=Ke?.speech?"Indexed, no words yet: set up speech-to-text above":d?.notice??"Indexed, no words",$=k?`Reading this file\u2026 ${k.progress??0}%`:s?d?.status==="ok"?"Indexed":b:"Not indexed",C=["video","audio"].includes(e.kind),M=h&&e.number,I=t("button",{type:"button",class:"btn",onclick:()=>j(e.id,0)},`${M?jt(e):e.path.split(/[\\/]/).at(-1)} \xB7 ${e.kind}`);M&&(I.title=`${fn(e)}. Double-click or F2 to label it.`,I.addEventListener("dblclick",()=>hs(e,I)),I.addEventListener("keydown",A=>A.key==="F2"&&(A.preventDefault(),A.stopPropagation(),hs(e,I))));let O=M?t("select",{class:"field select","aria-label":`What clip ${e.number} is`,onchange:()=>K([{op:"describe_asset",asset:e.id,role:O.value}])},[e.role?null:t("option",{value:"",disabled:!0},"What it is\u2026"),...Object.entries(ra).map(([A,_])=>t("option",{value:A},_))]):null;return O&&(O.value=e.role??""),t("li",{class:`asset${M?" handle":""}`,...M?{draggable:"true",ondragstart:A=>A.dataTransfer.setData(De,JSON.stringify({asset:e.id}))}:{}},M?t("div",{class:"asset-head"},Rt(L(e)),t("span",{class:"badge","aria-label":`Clip ${e.number}`},String(e.number)),I):I,t("span",{class:"note"},e.offline?"Offline: the file has moved":$),k?se(k.progress??0,`Indexing ${e.path.split(/[\\/]/).at(-1)}`):null,O,C?t("button",{type:"button",class:"btn",disabled:!!k,onclick:()=>ia(e)},s?"Index again":"Index"):null,C?t("button",{type:"button",class:"btn",onclick:()=>K([{op:"keep_range",asset:e.id,from:0,to:e.facts.duration}])},"Add to cut"):null)}function $t(){let e=r.filter(C=>C.kind!=="reference"),s=document.activeElement===he,d=W.scrollTop;if(J(W),W.classList.remove("virtual"),!h)return W.append(...e.map(ms));let k=Zs(Ys(e,l.words,he.value),Le.value),b=to(k,Ze.value).flatMap(C=>[...C.name===null?[]:[{head:`${C.name} \xB7 ${C.assets.length}`}],...C.assets]),$=C=>C.head?t("li",{class:"bin-group label-mono"},C.head):ms(C);if(he.value.trim()&&!k.length)W.append(t("li",{class:"note"},"Nothing in the bin matches that."));else if(b.length<=no)W.append(...b.map($));else{W.classList.add("virtual");let{start:C,end:M,before:I,after:O}=so(b.map(_=>_.head?fs.head:fs.asset),d,W.clientHeight||600),A=_=>{let ee=t("li",{class:"bin-space","aria-hidden":"true"});return ee.style.height=`${_}px`,ee};W.append(A(I),...b.slice(C,M).map($),A(O)),W.scrollTop=d}s&&he.focus()}let gs=0;W.addEventListener("scroll",()=>W.classList.contains("virtual")&&(cancelAnimationFrame(gs),gs=requestAnimationFrame($t)));function xn(){$t(),Oe()}async function ia(e){Ke?.speech&&!Ke.setup?.error&&(D.textContent="Your file is indexed without words until speech-to-text is set up (above).",Tn.hidden=!1);try{let s=await Y("POST",`/projects/${n}/index`,{asset:e.id});ae.set(s.id,{...s,asset:e.id}),D.textContent="Reading your footage. You can keep working.",xn()}catch(s){D.textContent=s.message}}function bs(e,{reference:s=!1,aspect:d="all"}={}){let k=b=>new Promise(($,C)=>{let M=t("li",{class:"asset"},t("span",{class:"note"},`Copying ${b.name}\u2026`),se(0,`Copying ${b.name}`));ys.append(M);let I=new XMLHttpRequest;I.open("POST",`/projects/${n}/upload?name=${encodeURIComponent(b.name)}${s?"&as=reference":""}`),I.upload.onprogress=O=>{if(!O.lengthComputable)return;let A=Math.round(O.loaded*100/O.total);M.querySelector(".progress span").style.width=`${A}%`,M.querySelector(".progress").setAttribute("aria-valuenow",String(A)),M.querySelector(".note").textContent=`Copying ${b.name}\u2026 ${A}%`},I.onload=()=>{M.remove();let O={};try{O=JSON.parse(I.responseText)}catch{}I.status<300?$(O):C(new Error(O.message??`The Edit Host answered ${I.status}.`))},I.onerror=()=>(M.remove(),C(new Error(`${b.name} couldn't be copied.`))),I.send(b)});return(async()=>{for(let b of e)try{let $=await k(b);D.textContent=s?`Added ${b.name} as a reference for ${et[d].toLowerCase()}.`:`Added ${b.name}. Index it to read its words.`,s&&(Fe.add($.id),Se(Ft($.id),d))}catch($){D.textContent=$.message}await R()})()}let ys=t("ul",{class:"bin","aria-label":"Copying"}),Bt=t("input",{type:"file",multiple:!0,accept:"video/*,audio/*,.mov,.mp4,.m4v,.mkv,.wav,.mp3,.m4a,.aac,.flac,.cube",hidden:!0,id:"pick-files",onchange:()=>(bs([...Bt.files]),Bt.value="")}),$n=t("input",{id:"add-path",class:"field",placeholder:"/Users/you/Movies/take.mov",autocomplete:"off"}),la=t("section",{class:"panel bin-panel","aria-label":"Bin"},t("h2",{},"Bin"),Dt,W,ys,Bt,t("button",{type:"button",class:"btn primary wide",onclick:()=>Bt.click()},"Add files\u2026"),t("p",{class:"note small"},"Copied into the project's media folder; your originals aren't touched."),t("details",{class:"by-path"},t("summary",{},"Link a file by its path instead (no copy)"),t("form",{class:"row",onsubmit:async e=>{e.preventDefault();try{await Y("POST",`/projects/${n}/assets`,{path:$n.value.trim()}),$n.value="",await R()}catch(s){D.textContent=s.message}}},t("label",{for:"add-path",class:"sr-only"},"Link a file by its path"),$n,t("button",{class:"btn",type:"submit"},"Link")))),Fe=new Set,ws=new Set,et={all:"Everything it shows",editing:"Editing: cuts and pace",sound:"Sound: music and feel",colour:"Colour grade",graphics:"Graphics: captions and text"},Ft=e=>`kriya-ref-aspect:${n}:${e}`,Kt=e=>Object.hasOwn(et,Se(Ft(e))??"")?Se(Ft(e)):"all",Sn=(e,s,d)=>t("select",{class:"field select",...e,onchange:d},Object.entries(et).map(([k,b])=>t("option",{value:k,selected:k===s},b))),Gt=Sn({id:"ref-aspect","aria-label":"The next reference is for"},"all",()=>Mn.value=Gt.value),Mn=Sn({id:"ref-aspect-bin","aria-label":"The next reference is for"},"all",()=>Gt.value=Mn.value),ca=(e,s)=>e.parts?s!=="all"?e.parts[s]?[e.parts[s]]:[`Nothing to take for ${et[s].toLowerCase()} from this one.`]:e.lines.filter(d=>!(e.kind==="video"&&e.pace&&d===e.parts.sound)):e.lines,St=new Map,Wt=o.referenceIntent===!0,Ce=new Map,ks=e=>`kriya-ref-style-off:${n}:${e}`,Cn=e=>new Set((Se(ks(e))??"").split(",").filter(Boolean)),vs=e=>Y("GET",`/projects/${n}/references/${encodeURIComponent(e)}/brief?format=${encodeURIComponent(Ee.value)}`).then(s=>(Ce.set(e,s.status==="ready"?{status:"ready",brief:s.brief}:{status:"none"}),Oe())).catch(()=>(Ce.set(e,{status:"none"}),Oe()));async function da(e){try{let s=await Y("POST",`/projects/${n}/references/${encodeURIComponent(e)}/measure`);ae.set(s.id,s),Ce.set(e,{status:"measuring",progress:0,job:s.id})}catch(s){Ce.set(e,{status:"failed",error:s.message})}Oe(`style-cancel-direct-${e}`)}function ua(e){if(!(e?.kind!=="reference"||!e.asset)){if(e.status==="pending"||e.status==="running")Ce.set(e.asset,{status:"measuring",progress:e.progress??0,job:e.id});else{if(e.status==="done")return void vs(e.asset);Ce.set(e.asset,e.status==="canceled"?{status:"none"}:{status:"failed",error:e.error??"the measure stopped"})}Oe()}}let xs=()=>{if(!Wt)return{};let e=[...Fe].find(s=>Ce.get(s)?.status==="ready"&&Kt(s)==="all"&&r.some(d=>d.id===s&&d.kind==="reference"));return e?{styleBrief:{ref:e,off:[...Cn(e)]}}:{}},_t=t("ul",{class:"bin","aria-label":"References"}),Ln=t("ul",{class:"bin refs-direct","aria-label":"References for this cut"}),$s=t("p",{class:"note small"}),Mt=t("input",{type:"file",accept:"video/*,image/*,audio/*,.mov,.mp4,.m4v,.mkv,.webm,.jpg,.jpeg,.png,.webp,.wav,.mp3,.m4a,.aac,.flac",hidden:!0,id:"pick-reference",onchange:()=>{let e=[...Mt.files];Mt.value="";let s=Gt.value,d=s==="all"?"a video's pace, captions, colour and music; an image's colour grade; music's tempo and energy":`only its ${et[s].toLowerCase()}`;e.length&&confirm(`Use this only as a reference for ${et[s].toLowerCase()}?
4
4
 
5
- Kriya measures it as numbers: ${d}. No picture, sound or words from it go into your video. Add only what you're allowed to use this way.`)&&gs(e,{reference:!0,aspect:s})}});function $s(e,s){let d=e.path.split(/[\\/]/).at(-1),k=e.facts.width?e.facts.duration?"video":"image":"music",b=t("input",{type:"checkbox",id:`use-${s}-${e.id}`,checked:Fe.has(e.id),onchange:()=>(b.checked?Fe.add(e.id):Fe.delete(e.id),Oe(b.id))}),$=St.get(e.id),C=Gt(e.id),M=t("ul",{class:"ref-lines"},...$?ia($,C).map(A=>t("li",{},A)):[t("li",{class:"note"},"Measuring\u2026")]),I=Sn({id:`aspect-${s}-${e.id}`,"aria-label":`Take from ${d}`},C,A=>(Se(Ft(e.id),A.target.value),Oe(A.target.id))),O=Wt&&k==="video"?Uo({id:e.id,where:s,state:Ce.get(e.id)??{status:"none"},off:Cn(e.id),onRead:()=>la(e.id),onCancel:()=>Ce.get(e.id)?.job&&Y("DELETE",`/jobs/${encodeURIComponent(Ce.get(e.id).job)}`).catch(()=>{}),onToggle:(A,_)=>{let ee=Cn(e.id);_?ee.delete(A):ee.add(A),Se(ws(e.id),[...ee].join(",")),Oe(`style-${s}-${e.id}-${A}`)}}):null;return t("li",{class:"asset ref"},t("button",{type:"button",class:"btn",onclick:()=>e.facts.duration&&j(e.id,0)},`${d} \xB7 ${k}`),t("label",{class:"note small",for:`aspect-${s}-${e.id}`},"Take from it"),I,Wt&&Ce.get(e.id)?.status==="ready"&&C==="all"?null:M,O,t("label",{class:"inline",for:`use-${s}-${e.id}`},b," Use in the cut"))}function Oe(e=null){J(_t),J(Ln);let s=r.filter(b=>b.kind==="reference");s.length||_t.append(t("li",{class:"note"},"None yet. Pick what a reference is for, then add a video whose cuts you like, music whose feel you like, or an image whose colour you like."));for(let b of s)ys.has(b.id)||(ys.add(b.id),Fe.add(b.id)),_t.append($s(b,"bin")),Ln.append($s(b,"direct")),St.has(b.id)||(St.set(b.id,null),Y("GET",`/projects/${n}/references/${encodeURIComponent(b.id)}`).then($=>(St.set(b.id,$),Oe())).catch($=>(St.set(b.id,{lines:[`Couldn't measure it: ${$.message}`]}),Oe()))),Wt&&b.facts.width&&b.facts.duration&&!Ce.has(b.id)&&(Ce.set(b.id,{status:"none"}),ks(b.id));Aa(),e&&document.getElementById(e)?.focus();let d=(b,$,C)=>{let M=b.value;J(b).append(t("option",{value:""},C),...$.map(I=>t("option",{value:I.id},I.path.split(/[\\/]/).at(-1)))),b.value=$.some(I=>I.id===M)?M:""};d($e,r.filter(b=>b.kind==="audio"&&!/kriya-music-/.test(b.path)),"No music"),Et&&d(Et,r.filter(b=>b.kind==="image"||b.role==="logo"||b.kind==="video"&&/\.(?:png|jpe?g|webp)$/i.test(b.path)).sort((b,$)=>($.role==="logo")-(b.role==="logo")),"Logo: none");let k=$e.value;$e.insertBefore(t("optgroup",{label:"Made by Kriya"},t("option",{value:"generated:calm"},"Music: calm bed (made by Kriya)"),t("option",{value:"generated:upbeat"},"Music: upbeat bed (made by Kriya)"),t("option",{value:"generated:warm"},"Music: warm bed (made by Kriya)")),$e.options[1]??null),/^generated:/.test(tn)?$e.value=tn:k&&($e.value=k)}let Ge=null,ct=t("p",{class:"note"}),En=t("div"),An=t("button",{type:"button",class:"btn primary",onclick:()=>Y("POST","/runtime/setup").then(Ut).catch(e=>ct.textContent=e.message)},"Set up speech-to-text"),Tn=t("section",{class:"panel setup","aria-label":"Speech-to-text setup",hidden:!0},t("h2",{},"Speech-to-text"),ct,En,An),Ss=e=>(e/1e6).toLocaleString(void 0,{maximumFractionDigits:0});function Ut(e){Ge=e;let s=Ge.setup,d=s&&!s.finished;if(Tn.hidden=!Ge.speech&&!d&&!s?.error,An.hidden=!!d,An.textContent=s?.error?"Try again":"Set up speech-to-text",J(En),d){let k=s.total?Math.round(s.done*100/s.total):null;ct.textContent=s.total?`Downloading ${s.step}: ${Ss(s.done)} of ${Ss(s.total)} MB (${k}%)`:s.line??"Setting up\u2026",En.append(se(k,"Media Runtime setup"))}else s?.error?ct.textContent=`Setup stopped: ${s.error}`:Ge.speech?ct.textContent="Words in the transcript need the speech model on this computer. Setting it up downloads it once; after that it works offline.":s?.finished&&(ct.textContent="Ready. Index a file to read its words.")}let we=t("textarea",{id:"prompt",class:"field chat-input",rows:"2",placeholder:'Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',autocomplete:"off"}),On=t("span",{class:"chip selection",hidden:!0}),Ms=h?t("section",{class:"area-story panel storyboard","aria-label":"Storyboard"}):null,da=h?Wo({root:Ms,clips:H,words:()=>l.words??[],onChange:e=>G([Go(e)])}):null,Ct=h?uo({input:we,clips:H}):null,Ht=()=>{let[e,s]=(Z.selection()??[]).map(d=>l.words.find(k=>k.id===d));return e&&s?{asset:e.asset,from:e.start,to:s.end}:null},Cs=h?t("button",{type:"button",class:"btn",hidden:!0,title:"Point at the selected words in your message",onclick:()=>Ht()&&Ct.insert(Ht())},"Mention this"):null;h&&(we.placeholder="Tell Kriya what to change. Type @ to point at a clip.",Q.addEventListener("dragstart",e=>Ht()&&e.dataTransfer.setData(De,JSON.stringify(Ht()))));let qt=t("ol",{class:"chat","aria-label":"Chat with Kriya","aria-live":"polite"}),Pe=t("ul",{class:"did","aria-label":"What I did"}),dt=[],xe=null,je=null,Re=e=>{let s=Math.max(0,e)/7056e5,d=Math.floor(s/60);return`${d}:${(s-d*60).toFixed(1).padStart(4,"0")}`},Ls=()=>{if(xe!==null&&je!==null&&je>xe)return{selection:{from:xe,to:je},label:`Marked ${Re(xe)}\u2013${Re(je)}`};let e=Z.selection();return e?{selection:{words:e},label:`Selected: ${l.words.find(s=>s.id===e[0])?.text??""}${e[0]===e[1]?"":" \u2026"}`}:fe.selected?{selection:{clip:fe.selected},label:`Selected: clip ${fe.selected}`}:xe!==null?{selection:{at:xe},label:`Marked in at ${Re(xe)} (press O for the end)`}:{selection:{at:K.time},label:null}},zt=()=>{let{label:e}=Ls();if(On.hidden=!e,On.textContent=e??"",!!h){Cs.hidden=!Z.selection();for(let s of Q.querySelectorAll(".word"))s.draggable=s.getAttribute("aria-pressed")==="true"}};Q.addEventListener("click",()=>setTimeout(zt));function Vt(e){let s=[],d=0;for(let k of String(e).matchAll(/\b(\d{1,2}):(\d{2}(?:\.\d+)?)\b/g)){s.push(e.slice(d,k.index));let b=Math.round((Number(k[1])*60+Number(k[2]))*7056e5);s.push(t("button",{type:"button",class:"time-link",title:"Play from here",onclick:()=>(T(),K.seek(Math.min(b,Math.max(0,Ue(u)-1))))},k[0])),d=k.index+k[0].length}return s.push(e.slice(d)),s}function He(e,s,...d){let k=e==="you"&&Ct?co(s).flatMap($=>$.number?[t("span",{class:"chip mention"},$.text)]:Vt($.text)):Vt(s),b=t("li",{class:`msg ${e}`},t("span",{class:"who"},e==="you"?"You":"Kriya"),t("p",{},...k),...d);return qt.append(b),b.scrollIntoView({block:"nearest"}),b}function ua(e){st=e.timeline??null,fe.setGhost(e.timeline),S.setGhost(e.timeline);let s=t("div",{class:"proposal"}),d=async($,C)=>{try{let M=await Y("POST",`/projects/${n}/proposals/${e.id}`,{accept:$,...C?{only:C}:{}});if(D.textContent=M.dropped.length?`Not applied, because you changed that part: ${M.dropped.map(I=>I.change).join("; ")}.`:$?"Done. Undo with Cmd+Z.":"Left as it was.",$)for(let I of C?C.map(O=>e.changes[O]):e.changes)Pe.prepend(t("li",{},I));J(s).append(t("p",{class:"note"},$?M.dropped.length?"Partly applied.":"Applied.":"Not applied."))}catch(M){D.textContent=M.message}st=null,fe.setGhost(null),S.setGhost(null),await R()},k=c&&e.timeline?(()=>{let $={},C=async M=>{try{if(M){let I=await Y("GET",`/projects/${n}/preview?proposal=${encodeURIComponent(e.id)}`),O=gn(e.timeline);await K.load(O,{fps:q(),duration:Ue(O),shape:me(),preview:I})}else await K.load(u,le({fps:q(),duration:Ue(u),shape:me()}));V.textContent=M?"Preview: after":"Preview",$.before.setAttribute("aria-pressed",String(!M)),$.after.setAttribute("aria-pressed",String(M))}catch(I){D.textContent=I.message}};return $.before=t("button",{type:"button",class:"btn","aria-pressed":"true",onclick:()=>C(!1)},"Before"),$.after=t("button",{type:"button",class:"btn","aria-pressed":"false",onclick:()=>C(!0)},"After"),t("div",{class:"row compare",role:"group","aria-label":"Show on the monitor"},$.before,$.after)})():null,b=v&&e.motion?(()=>{let $=a.canvas.width,C=a.canvas.height,M=Math.min(220,Math.round(220*$/Math.max($,C))),I=`/projects/${n}/custom-preview?proposal=${encodeURIComponent(e.id)}&op=${e.motion.op}`,O=t("iframe",{title:"Preview of the custom animation",sandbox:"allow-scripts",loading:"lazy",src:I});Object.assign(O.style,{width:`${$}px`,height:`${C}px`,transform:`scale(${M/$})`});let A=t("div",{class:"scene-picture custom-picture"},O);Object.assign(A.style,{width:`${M}px`,height:`${Math.round(M*C/$)}px`});let _=(e.motion.gates??[]).map(U=>`${U.id} ${U.status.replaceAll("_"," ")}`).join(" \xB7 "),ee=()=>{we.value=`${e.ask??"That animation"}, in a different style`,d(!1).then(()=>Yt())};return t("div",{class:"scene-row custom-motion"},A,t("div",{class:"scene-info"},t("p",{class:"small"},"Custom animation, written by a model and checked by code"),_?t("p",{class:"note small"},`Checked on its own tile: ${_}`):null,t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>d(!0)},"Approve"),t("button",{type:"button",class:"btn",onclick:()=>O.src=I},"Play again"),t("button",{type:"button",class:"btn",onclick:ee},"Restyle"),t("button",{type:"button",class:"btn",onclick:()=>d(!1)},"Remove"))))})():null;return s.append(t("p",{class:"lead"},"Proposed, not applied yet"),...b?[b]:[],...k?[k]:[],t("ul",{},e.changes.map(($,C)=>t("li",{},t("span",{},...Vt($)),e.changes.length>1?t("button",{type:"button",class:"btn",onclick:()=>d(!0,[C])},"Only this"):null))),...b&&e.changes.length===1?[]:[t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>d(!0)},e.changes.length>1?"Accept all":"Accept"),t("button",{type:"button",class:"btn",onclick:()=>d(!1)},"Reject"))]),s}let Lt=null,Jt=()=>{},pa=()=>({...Bn(),...At.value==="clean"?{cleanVoice:!0}:{}}),Es=e=>l.words.find(s=>s.id===e)?.text??e,Qt=e=>`${Math.floor(e/60)}:${(e%60).toFixed(1).padStart(4,"0")}`,As=null;function Ts(e={}){return[As,e.format,e.seconds?`about ${e.seconds} s`:null,e.captions&&e.captions!=="none"?`${e.captions} captions`:"no captions",e.grade&&e.grade!=="natural"?`${e.grade} look`:"natural colour",e.music&&e.music!=="none"?`${e.music} music`:"no music",e.cleanVoice?"background noise out of the voice":null,e.coldOpen?`cold open on "${Es(e.coldOpen.from)} \u2026 ${Es(e.coldOpen.to)}"${e.coldOpen.mono===!1?"":" in black and white"}`:null,e.hook?"a hook line first":null,e.cutSound&&e.cutSound!=="none"?`a ${e.cutSound} on each cut`:null,e.introSound&&e.introSound!=="none"?`a ${e.introSound} into the story`:null,Number.isInteger(e.punches)?`${e.punches} punch-ins`:null,e.angles?"wide and tight angles":null,e.arrange?"an accent in the music's key on every join":null,e.ambience?"a room tone from your own quiet":null,e.splits?"the voice leading and trailing its picture at the joins":null,e.beatJoins?"B-roll on the beat":null,e.broll==="own"?"B-roll from your clips":null,e.titles?"title cards":null,e.scenes?.length?`${e.scenes.length} animated scene${e.scenes.length===1?"":"s"}`:null,e.graphics?.length?`${e.graphics.length} motion graphic${e.graphics.length===1?"":"s"}`:null,e.transition&&e.transition!=="none"?`${e.transition} transitions ${e.transitionAll?"on every cut":"where the story changes moment"}`:null,e.pictures?.length?`${e.pictures.length} licensed picture${e.pictures.length===1?"":"s"}`:null,e.terms?.length?`${e.terms.length} cited definition${e.terms.length===1?"":"s"}`:null,e.song?"your song":null,e.montage?"cut on its beats":null,e.multicam?`${e.multicam.angles.length} cameras, following who speaks`:null,e.ramps?"a speed ramp into the story":null,e.cuts?.length?`trims ${e.cuts.map(d=>`${Qt(d.from)}\u2013${Qt(d.to)}`).join(", ")} of the take`:null].filter(Boolean).join(" \xB7 ")}function fa(e,s){let d=e.sceneChoices??{kinds:{},themes:{},swaps:[]},k=e.settings.format??Ee.value,$=k==="16:9"?{w:1920,h:1080,show:200}:k==="1:1"?{w:1080,h:1080,show:150}:k==="4:5"?{w:1080,h:1350,show:136}:{w:1080,h:1920,show:120},C=e.settings.scenes.map((U,ie)=>({scene:U,swaps:d.swaps[ie]??[U.kind]})),M=t("ul",{class:"scene-list"}),I=()=>{e.settings.scenes=C.map(U=>U.scene),C.length?e.brief.scenes=e.settings.scenes:delete e.brief.scenes,s()},O=U=>`/projects/${n}/scene-preview?format=${encodeURIComponent(k)}&scene=${encodeURIComponent(JSON.stringify(U))}`,A=U=>{let ie=ge=>Qt(ge/7056e5),be=l.words?.find(ge=>ge.id===U.from),ye=l.words?.find(ge=>ge.id===U.to);return be&&ye?`${ie(be.start)}\u2013${ie(ye.end)}`:""},_=()=>{J(M),C.length||M.append(t("li",{class:"note small"},"No animated scenes: the speaker stays on screen."));for(let U of C){let ie=t("iframe",{title:`Preview of the scene "${U.scene.title||U.scene.items[0].text}"`,sandbox:"allow-scripts",loading:"lazy",src:O(U.scene)});ie.style.width=`${$.w}px`,ie.style.height=`${$.h}px`,ie.style.transform=`scale(${$.show/$.w})`;let be=t("div",{class:"scene-picture"},ie);be.style.width=`${$.show}px`,be.style.height=`${Math.round($.show*$.h/$.w)}px`;let ye=t("select",{class:"field select","aria-label":"Draw this scene as",onchange:()=>(U.scene={...U.scene,kind:ye.value},I(),ie.src=O(U.scene))},U.swaps.map(ge=>t("option",{value:ge},d.kinds[ge]??ge)));ye.value=U.scene.kind,M.append(t("li",{class:"scene-row"},be,t("div",{class:"scene-info"},t("p",{class:"small"},t("span",{class:"scene-time"},A(U.scene)),` ${U.scene.title||U.scene.items[0].text}`),t("p",{class:"note small"},U.scene.items.map(ge=>`${ge.text}${ge.value!==void 0?` ${ge.value}${ge.unit??""}`:""}`).join(" \xB7 ")),t("div",{class:"row"},ye,t("button",{type:"button",class:"btn",onclick:()=>ie.src=O(U.scene)},"Play again"),t("button",{type:"button",class:"btn",onclick:()=>(C.splice(C.indexOf(U),1),I(),_())},"Keep the speaker")))))}},ee=t("select",{class:"field select","aria-label":"Look of the scenes",onchange:()=>{for(let U of C)U.scene={...U.scene,theme:ee.value};I(),_()}},Object.entries(d.themes).map(([U,ie])=>t("option",{value:U},ie)));return ee.value=C[0].scene.theme,_(),t("div",{class:"scenes"},t("div",{class:"row scene-head"},t("p",{class:"lead"},"Animated scenes"),ee),M)}function ha(e,s){let d=e.graphicChoices??{kinds:{},styles:{},accents:[],tones:[],fonts:[]},k=e.settings.format??Ee.value,b=k==="16:9"?{w:1920,h:1080,show:200}:k==="1:1"?{w:1080,h:1080,show:150}:k==="4:5"?{w:1080,h:1350,show:136}:{w:1080,h:1920,show:120},$=[...e.settings.graphics],C=t("ul",{class:"scene-list"}),M=()=>{e.settings.graphics=$,$.length?e.brief.graphics=$:delete e.brief.graphics,s()},I=U=>`/projects/${n}/graphic-preview?format=${encodeURIComponent(k)}&graphic=${encodeURIComponent(JSON.stringify(U))}`,O=U=>{let ie=U.at&&l.words?.find(be=>be.id===U.at);return U.kind==="intro"?"start":U.kind==="end"?"end":ie?Qt(ie.start/7056e5):""},A=()=>{J(C),$.length||C.append(t("li",{class:"note small"},"No motion graphics.")),$.forEach((U,ie)=>{let be=d.kinds[U.kind]??{label:U.kind,styles:[U.style]},ye=t("iframe",{title:`Preview of the ${be.label.toLowerCase()} "${U.text}"`,sandbox:"allow-scripts",loading:"lazy",src:I(U)});ye.style.width=`${b.w}px`,ye.style.height=`${b.h}px`,ye.style.transform=`scale(${b.show/b.w})`;let ge=t("div",{class:"scene-picture graphic-picture"},ye);ge.style.width=`${b.show}px`,ge.style.height=`${Math.round(b.show*b.h/b.w)}px`;let un=be.styles.length>1?t("select",{class:"field select","aria-label":`Style of the ${be.label.toLowerCase()}`,onchange:()=>($[ie]={...$[ie],style:un.value},M(),ye.src=I($[ie]))},be.styles.map(pn=>t("option",{value:pn},d.styles[pn]??pn))):null;un&&(un.value=U.style),C.append(t("li",{class:"scene-row"},ge,t("div",{class:"scene-info"},t("p",{class:"small"},t("span",{class:"scene-time"},O(U)),` ${be.label}`),t("p",{class:"note small"},[U.text,U.subtitle].filter(Boolean).join(" \xB7 ")),t("div",{class:"row"},un,t("button",{type:"button",class:"btn",onclick:()=>ye.src=I($[ie])},"Play again"),t("button",{type:"button",class:"btn",onclick:()=>($=$.filter((pn,Ba)=>Ba!==ie),M(),A())},"Remove")))))})},_=(U,ie,be)=>{let ye=t("select",{class:"field select","aria-label":be,onchange:()=>($=$.map(ge=>({...ge,[U]:ye.value})),M(),A())},ie.map(ge=>t("option",{value:ge},`${be}: ${ge}`)));return ye.value=$[0][U],ye},ee=t("div",{class:"row"},_("accent",d.accents,"Colour"),_("tone",d.tones,"Plate"),_("font",d.fonts,"Font"));return A(),t("div",{class:"scenes"},t("p",{class:"lead"},"Motion graphics"),ee,C)}function ma(e,s){let d=t("ul",{class:"scene-list"}),k=()=>{e.brief.pictures=e.settings.pictures.map(({from:$,to:C,id:M})=>({from:$,to:C,id:M})),e.brief.pictures.length||delete e.brief.pictures,s()},b=()=>{J(d),e.settings.pictures.length||d.append(t("li",{class:"note small"},"No pictures: the speaker stays on screen."));for(let $ of e.settings.pictures){let C=()=>$.options.find(A=>A.id===$.id)??$.options[0],M=t("img",{class:"found-thumb",alt:C().title,loading:"lazy",src:`/projects/${n}/found-thumb?id=${encodeURIComponent($.id)}`}),I=t("p",{class:"note small"},`${C().licence} \xB7 ${C().creator}`),O=t("select",{class:"field select","aria-label":"Use this picture",onchange:()=>{$.id=O.value,M.src=`/projects/${n}/found-thumb?id=${encodeURIComponent($.id)}`,M.alt=C().title,I.textContent=`${C().licence} \xB7 ${C().creator}`,k()}},$.options.map(A=>t("option",{value:A.id},A.title.slice(0,60))));O.value=$.id,d.append(t("li",{class:"scene-row"},M,t("div",{class:"scene-info"},t("p",{class:"small"},$.query),I,t("div",{class:"row"},O,t("button",{type:"button",class:"btn",onclick:()=>{e.settings.pictures.splice(e.settings.pictures.indexOf($),1),k(),b()}},"Keep the speaker")))))}};return b(),t("div",{class:"scenes"},t("p",{class:"lead"},"Real pictures"),d)}function ga(e,s){let d=t("ul",{class:"scene-list"}),k=()=>{J(d);for(let b of e.settings.terms)d.append(t("li",{class:"scene-row"},t("div",{class:"scene-info"},t("p",{class:"small"},t("b",{},b.term),` \u201C${b.quote}\u201D ${b.source}`),t("button",{type:"button",class:"btn",onclick:()=>{e.settings.terms.splice(e.settings.terms.indexOf(b),1),e.brief.terms=e.settings.terms.map(({at:$,id:C,term:M})=>({at:$,id:C,term:M})),e.brief.terms.length||delete e.brief.terms,s(),k()}},"Don't show this"))))};return k(),t("div",{class:"scenes"},t("p",{class:"lead"},"Definitions"),d)}function ba(e){let s=t("select",{class:"field select","aria-label":"Style pack",onchange:()=>{s.value?e.brief.stylePack=e.settings.stylePack=s.value:(delete e.brief.stylePack,delete e.settings.stylePack)}},[t("option",{value:""},"No style pack"),...Object.entries(y.packs).map(([d,k])=>t("option",{value:d,title:k.does},k.label))]);return s.value=e.brief.stylePack??"",t("div",{class:"scenes"},t("p",{class:"lead"},"Style"),s)}function ya(e,s){let d={clean:"Clean",karaoke:"Karaoke",boxed:"Boxed",pop:"Pop",story:"Story",minimal:"Minimal",...y?Object.fromEntries(y.looks.map(C=>[C,E[C]??C])):{}},k={"#ffd23f":"Yellow","#ffb347":"Amber","#4fd1c5":"Teal","#ff7ab6":"Pink","#ffffff":"White"},b=t("select",{class:"field select","aria-label":"Caption look",onchange:()=>{e.brief.captions=b.value,e.settings.captions=b.value,s()}},Object.entries(d).map(([C,M])=>t("option",{value:C},M)));b.value=e.brief.captions;let $=t("select",{class:"field select","aria-label":"Highlight colour",onchange:()=>{$.value?e.brief.captionStyle={accent:$.value}:delete e.brief.captionStyle,e.settings.captionStyle=e.brief.captionStyle,s()}},[t("option",{value:""},"Look's own colour"),...Object.entries(k).map(([C,M])=>t("option",{value:C},M))]);return $.value=e.brief.captionStyle?.accent??"",t("div",{class:"scenes"},t("p",{class:"lead"},"Captions"),t("div",{class:"row"},b,$))}function wa(e){let s=t("ol",{class:"order-strip","aria-label":"The film's order"}),d=t("p",{class:"sr-only",role:"status","aria-live":"polite"}),k={director:"the Director's choice",default:"the order added",storyboard:"your storyboard",person:"as you said"},b={story:"story",whole:"whole",over:"over the voice",sound:"sound only"},$=M=>M.from===null&&M.to===null?M.duration?Re(M.duration):"":`${M.from===null?"0:00":Re(M.from)}\u2013${M.to===null?"end":Re(M.to)}`,C=(M=null)=>{J(s);let I=e.order.parts,O=kn(I);I.forEach(A=>{let _=O.indexOf(A),ee=`clip ${A.number??"?"}${A.label?`, ${A.label}`:""}`,U=(ie,be)=>t("button",{type:"button",class:"btn order-move","aria-label":`Move ${ee} ${be}`,disabled:_<0||!O[_+ie],"data-move":`${A.id}:${ie}`,onclick:()=>{let ye=xt(e.settings.assembly.parts,A.id,ie);ye&&(e.settings.assembly={version:1,parts:ye},e.brief.assembly=e.settings.assembly,e.order.parts=xt(e.order.parts,A.id,ie),d.textContent=`${ee} moved ${be}.`,C(`${A.id}:${ie}`))}},ie<0?"\u2191":"\u2193");s.append(t("li",{class:"order-part","data-part":A.id},t("span",{class:"order-n"},_>=0?String(_+1):"+"),t("span",{class:"order-what"},t("b",{},`Clip ${A.number??"?"}`),A.label?` ${A.label}`:"",t("span",{class:"note small"},` ${[b[A.use]??A.use,$(A),k[A.why]].filter(Boolean).join(" \xB7 ")}`)),_>=0?t("span",{class:"order-moves"},U(-1,"earlier"),U(1,"later")):null))}),M&&(s.querySelector(`[data-move="${M}"]:not([disabled])`)??s.querySelector(`[data-part="${M.split(":")[0]}"] button:not([disabled])`))?.focus()};return C(),t("div",{class:"scenes order"},t("p",{class:"lead"},"Order"),e.order.parts.length?s:null,...e.order.lines.map(M=>t("p",{class:"note small"},M)),d)}function ka(e,s){let{understood:d=[],cannot:k=[],questions:b=[],defaulted:$=[]}=e.intent;e.intent.answers??={};let C=(M,I)=>{let O=`q-${e.intent.id??(e.intent.id=Math.random().toString(36).slice(2,8))}-${I}`;return t("fieldset",{class:"question"},t("legend",{},M.question),...M.options.map(A=>t("label",{class:"inline choice"},t("input",{type:"radio",name:O,value:String(A),checked:A===(e.intent.answers[M.field]??M.default),onchange:()=>{e.intent.answers[M.field]=A,e.settings[M.field]=A,Zo(e.brief,M.field,A),s()}}),` ${Nt(M.field,A)}${A===M.default?" (default)":""}`)))};return t("div",{class:"intent"},d.length?t("div",{},t("p",{class:"lead"},"What I understood"),t("ul",{},d.map(M=>t("li",{},Xo(M))))):null,k.length?t("div",{},t("p",{class:"lead"},"Not in this cut"),t("ul",{},k.map(M=>t("li",{},`"${M.said}"${M.nearest?`. Nearest I can do: ${M.nearest}`:""}`)))):null,...b.map(C),$.length?t("p",{class:"note small"},`Also decided by default: ${$.map(M=>`${ds[M.field]??M.field} ${Nt(M.field,M.value)}`).join(", ")}.`):null)}function va(e){As=e.genreLabel?`reads as: ${e.genreLabel}`:null;let s=t("p",{class:"note small plan-summary"},Ts(e.settings)),d=null,k=()=>{s.textContent=Ts(e.settings),d?.refresh()},b=[e.steps.length?t("ol",{class:"steps"},e.steps.map(ee=>t("li",{},...Vt(ee)))):null,e.intent?ka(e,k):null,e.order?wa(e):null].filter(Boolean),$=[e.brief.captions?ya(e,k):null,y?ba(e):null].filter(Boolean),C=[b.length?{key:"plan",label:"Plan",panel:t("div",{class:"plan-section"},...b)}:null,e.settings.scenes?.length?{key:"scenes",label:"Scenes",panel:t("div",{class:"plan-section"},fa(e,k)),count:()=>e.settings.scenes?.length??0}:null,e.settings.graphics?.length?{key:"graphics",label:"Graphics",panel:t("div",{class:"plan-section"},ha(e,k)),count:()=>e.settings.graphics?.length??0}:null,e.settings.pictures?.length?{key:"pictures",label:"Pictures",panel:t("div",{class:"plan-section"},ma(e,k)),count:()=>e.settings.pictures?.length??0}:null,e.settings.terms?.length?{key:"terms",label:"Definitions",panel:t("div",{class:"plan-section"},ga(e,k)),count:()=>e.settings.terms?.length??0}:null,$.length?{key:"look",label:"Look",panel:t("div",{class:"plan-section"},...$)}:null].filter(Boolean);C.length>1&&(d=is(C,{label:"Parts of the plan",className:"plan-tabs"}));let M=t("div",{class:"plan-backdrop",hidden:!0,onclick:()=>A(!1)}),I=t("button",{type:"button",class:"btn ghost plan-expand","aria-expanded":"false",onclick:()=>A(!_.classList.contains("expanded"))},"Expand"),O=ee=>ee.key==="Escape"&&(ee.stopPropagation(),A(!1));function A(ee){_.classList.toggle("expanded",ee),M.hidden=!ee,I.textContent=ee?"Close":"Expand",I.setAttribute("aria-expanded",String(ee)),ee?(document.body.append(M),_.setAttribute("role","dialog"),_.setAttribute("aria-modal","true"),_.setAttribute("aria-label","The Director's plan"),window.addEventListener("keydown",O,!0),I.focus()):(_.removeAttribute("role"),_.removeAttribute("aria-modal"),_.removeAttribute("aria-label"),M.remove(),window.removeEventListener("keydown",O,!0))}let _=t("div",{class:"proposal plan"},t("div",{class:"plan-head"},t("div",{class:"plan-title"},t("p",{class:"lead"},e.revises?"A change to your current cut, not made yet":"The Director's plan, not made yet"),I),s),e.revises?t("p",{class:"note small"},`${e.differs?.length?`What changes: ${e.differs.join(" \xB7 ")}. `:""}${e.keepsStory?"The story and your own edits stay.":"The length or the trims change, so the lines are chosen again; your own edits are kept where they still fit."} Say "start over" for a new cut from the footage.`):null,...d?[d.strip]:[],...C.map(ee=>ee.panel),t("div",{class:"row plan-actions"},t("button",{type:"button",class:"btn primary",onclick:()=>(A(!1),Lt=null,xa(e.brief),J(_).append(t("p",{class:"note"},`Approved. Making it now in ${e.brief.format??Ee.value}; the progress is in Brief.`)),Rs(e.brief,{exact:!0,plan:e}),Jt("brief"))},"Approve and make it"),t("button",{type:"button",class:"btn",onclick:()=>(A(!1),Lt=e,we.focus(),we.placeholder="Say what to change in the plan\u2026")},"Change\u2026")));return _}function xa(e={}){e.format&&(Ee.value=e.format);let s=e.seconds?String(e.seconds):"";s&&![...tt.options].some(d=>d.value===s)&&tt.append(t("option",{value:s},`${s} seconds`)),tt.value=s,qe.value=e.captions??"",ze.value=e.grade??"",ft?.mark(),/^generated:/.test(e.music??"")&&[...$e.options].some(d=>d.value===e.music)?$e.value=e.music:e.music||($e.value=""),At.value=e.cleanVoice?"clean":"",Zt.box.checked=!!e.angles,Dn.box.checked=e.broll==="own",en.box.checked=!!e.titles,nn.value=""}async function Os(e,s=null,d={}){Jt("chat");let k=He("kriya",s?"Revising the plan\u2026":"Planning the cut\u2026");try{let b=await Y("POST",`/projects/${n}/plan`,{text:e,history:dt.slice(-6),previous:s,choices:pa(),...d});k.remove(),Lt=b,He("kriya",b.say||"Here's my plan.",va(b)),dt.push({who:"kriya",text:(b.say||"").slice(0,400)})}catch(b){k.remove(),He("kriya",b.message)}}async function Yt({planning:e=!1}={}){let s=we.value.trim();if(!s)return;Jt("chat");let d=Ct?Ct.take(s):{text:s,mentions:[]},k=d.text,b=mt?.mark(),$={...d.mentions.length?{mentions:d.mentions}:{},...b?{mark:b}:{}};if(b&&mt.clear(),we.placeholder=h?"Tell Kriya what to change. Type @ to point at a clip.":'Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',Lt||e)return He("you",s),dt.push({who:"you",text:s.slice(0,400)}),we.value="",Os(k,Lt,$);let{selection:C,label:M}=Ls();He("you",b?`${s} (on the ${b.kind} you drew at ${Re(b.at)})`:M?`${s} (${M.replace(/^Selected: /,"on ")})`:s),we.value="";let I=He("kriya","Thinking about that\u2026");try{let O=await Y("POST",`/projects/${n}/ask`,{text:k,selection:C,history:dt.slice(-6),...$});I.remove();let A=O.say||(O.proposal?"Here's what I'd change.":O.direct?"That's about the whole video.":O.reason??"I couldn't turn that into an edit. Try saying it another way.");if(dt.push({who:"you",text:s.slice(0,400)}),O.proposal?.motion&&(O.proposal.ask=k),O.direct&&!O.proposal)return Os(k,null,$);let _=O.cannot?.length?t("div",{class:"intent"},t("p",{class:"lead"},"Not in this change"),t("ul",{},O.cannot.map(ee=>t("li",{},`"${ee.said}"${ee.nearest?`. Nearest I can do: ${ee.nearest}`:""}`)))):null;He("kriya",A,O.proposal?ua(O.proposal):null,_),dt.push({who:"kriya",text:A.slice(0,400)})}catch(O){I.remove(),He("kriya",O.status===0||O.status>=500?"I can't reach Kriya right now, so I can't make changes by asking. You can still edit by hand.":O.message)}}we.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),Yt())});let $a=t("form",{class:"prompt",onsubmit:e=>(e.preventDefault(),Yt())},t("label",{for:"prompt",class:"sr-only"},"Message Kriya"),we,t("div",{class:"send"},t("button",{class:"btn primary",type:"submit"},"Send"),t("button",{type:"button",class:"btn",title:"Ask the Director for a plan of the whole cut",onclick:()=>Yt({planning:!0})},"Plan"),...o.dictation?[Sa()]:[]));function Sa(){let e=t("button",{type:"button",class:"btn talk","aria-pressed":"false",title:"Hold to talk (or hold Space on this button); the text appears in the box"},"Hold to talk"),s=null,d=null,k=0,b=async()=>{if(s)return;try{d=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{D.textContent="The microphone isn't available to the Studio.";return}let C=[];s=new MediaRecorder(d),s.ondataavailable=M=>M.data.size&&C.push(M.data),s.onstop=async()=>{for(let I of d.getTracks())I.stop();let M=(s.mimeType||"audio/webm").split(";")[0];if(s=null,e.setAttribute("aria-pressed","false"),e.textContent="Hold to talk",Date.now()-k<300||!C.length)return D.textContent="Hold the button while you speak.";D.textContent="Turning your words into text on this computer\u2026";try{let I=await fetch(`/projects/${n}/dictate`,{method:"POST",headers:{"content-type":M},body:new Blob(C,{type:M})}),O=await I.json();if(!I.ok)throw new Error(O.message??"That couldn't be heard.");we.value=`${we.value?`${we.value} `:""}${O.text}`.trim(),D.textContent=O.text?"Read it over, then send.":"Nothing was heard.",we.focus()}catch(I){D.textContent=I.message}},k=Date.now(),s.start(),e.setAttribute("aria-pressed","true"),e.textContent="Listening\u2026 let go to stop",setTimeout(()=>s?.state==="recording"&&s.stop(),6e4)},$=()=>s?.state==="recording"&&s.stop();e.addEventListener("pointerdown",C=>(C.preventDefault(),b()));for(let C of["pointerup","pointerleave","pointercancel"])e.addEventListener(C,$);return e.addEventListener("keydown",C=>(C.key===" "||C.key==="Enter")&&!C.repeat&&(C.preventDefault(),b())),e.addEventListener("keyup",C=>(C.key===" "||C.key==="Enter")&&$()),e}let Ma=t("div",{class:"marks",role:"group","aria-label":"Mark a range of the cut"},t("button",{type:"button",class:"btn","aria-keyshortcuts":"I",title:"Mark in (I)",onclick:()=>gt({type:"mark",edge:"in"})},"Mark in"),t("button",{type:"button",class:"btn","aria-keyshortcuts":"O",title:"Mark out (O)",onclick:()=>gt({type:"mark",edge:"out"})},"Mark out")),Ca={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",needs_you:"Needs you",not_checked:"Not checked"},tt=t("select",{id:"make-length",class:"field select"},[["","Length: auto (30\u201360 s)"],["30","30 seconds"],["45","45 seconds"],["60","60 seconds"],["90","90 seconds"]].map(([e,s])=>t("option",{value:e},s))),qe=t("select",{id:"make-captions",class:"field select"},[["","No captions"],["clean","Captions: clean"],["karaoke","Captions: karaoke"],["boxed","Captions: boxed"],["pop","Captions: pop"],["story","Captions: story"],["minimal","Captions: minimal"]].map(([e,s])=>t("option",{value:e},s)));y&&qe.append(...y.looks.map(e=>t("option",{value:e},`Captions: ${(E[e]??e).toLowerCase()}`)));let $e=t("select",{id:"make-music",class:"field select"}),Xt=y?t("select",{id:"make-style",class:"field select"},[t("option",{value:""},"Style: none"),...Object.entries(y.packs).map(([e,s])=>t("option",{value:e,title:s.does},`Style: ${s.label}`))]):null,Pn=y?t("select",{id:"make-type",class:"field select"},[t("option",{value:""},"Type: the film's own"),...Object.entries(y.pairs).map(([e,s])=>t("option",{value:e},`Type: ${s}`))]):null,jn=y?t("select",{id:"make-bar",class:"field select"},[["","Bar: none"],["progress","Bar: progress"],["chapters","Bar: chapters"]].map(([e,s])=>t("option",{value:e},s))):null,Et=y?t("select",{id:"make-logo",class:"field select"}):null,Ps=(e,s)=>{let d=t("input",{type:"checkbox",id:`${e}-on`}),k=t("input",{type:"color",id:e,class:"swatch",value:e==="make-ink"?"#ffffff":"#ffd23f","aria-label":s});return{on:d,pick:k,el:t("label",{class:"inline",for:`${e}-on`},d,` ${s} `,k)}},Rn=y?Ps("make-ink","My text colour"):null,In=y?Ps("make-accent","My accent"):null,js=y&&!y.shipped?t("p",{class:"note"},"The Fonts pack isn't installed on this computer, so a type kit draws in the system fonts until it is (kriya edit setup --pack fonts)."):null,La=()=>{if(!y)return{};let e=Pn.value||(Xt.value?null:y.chosen?.pair??"clean"),s={...Rn.on.checked?{text:Rn.pick.value}:{},...In.on.checked?{accent:In.pick.value}:{}},d={...Object.keys(s).length?{colors:s}:{},...Et.value?{logo:Et.value}:{},...jn.value?{bar:jn.value}:{}};return{...Xt.value?{stylePack:Xt.value}:{},...Pn.value||Object.keys(d).length?{typeKit:{...e?{pair:e}:{},...d}}:{}}},Ee=t("select",{id:"make-format",class:"field select"},[["9:16","Format: 9:16 (Reels, Shorts)"],["16:9","Format: 16:9 (YouTube)"],["1:1","Format: 1:1 (square post)"],["4:5","Format: 4:5 (feed post)"]].map(([e,s])=>t("option",{value:e},s))),ze=t("select",{id:"make-grade",class:"field select"},[["","Look: natural"],["vivid","Look: vivid"],["cinematic","Look: cinematic (cool, vignette)"],["warm","Look: warm"],["bright","Look: bright"],["mono","Look: black and white"]].map(([e,s])=>t("option",{value:e},s))),At=t("select",{id:"make-voice",class:"field select"},[["","Voice: as recorded"],["clean","Voice: remove background noise"]].map(([e,s])=>t("option",{value:e},s))),Nn=(e,s)=>{let d=t("input",{type:"checkbox",id:e});return{box:d,el:t("label",{class:"inline",for:e},d,` ${s}`)}},Zt=Nn("make-angles","Angles (wide and tight)"),Dn=Nn("make-broll","B-roll from my clips"),en=Nn("make-titles","Title cards"),tn="";$e.addEventListener("change",()=>tn=$e.value);let Ea={"":null,reel:{format:"9:16",captions:"karaoke",grade:"vivid",length:"45",music:"generated:upbeat",voice:"clean",angles:!0},clean:{format:"9:16",captions:"clean",grade:"",length:"30",music:"",voice:"clean"},youtube:{format:"16:9",captions:"clean",grade:"warm",length:"60",music:"generated:calm",voice:"clean"},square:{format:"1:1",captions:"boxed",grade:"vivid",length:"30",music:"generated:upbeat",voice:"clean"},cinematic:{format:"16:9",captions:"",grade:"cinematic",length:"60",music:"generated:warm",voice:"clean",angles:!0,titles:!0}},nn=t("select",{id:"make-template",class:"field select",onchange:()=>{let e=Ea[nn.value];e&&(Ee.value=e.format,qe.value=e.captions,ze.value=e.grade,tt.value=e.length,At.value=e.voice,Zt.box.checked=!!e.angles,en.box.checked=!!e.titles,$e.value=tn=e.music)}},[["","Template: choose\u2026"],["reel","Talking-head reel: karaoke captions, upbeat music"],["clean","Clean reel: simple captions, no music"],["youtube","YouTube talk: 16:9, warm, calm music"],["square","Square post: boxed captions, vivid"],["cinematic","Cinematic: 16:9, cool look, no captions"]].map(([e,s])=>t("option",{value:e},s))),Aa=()=>{let e=r.filter(d=>d.kind==="reference"&&Fe.has(d.id)),s=[...new Set(e.map(d=>Gt(d.id)))].map(d=>d==="all"?"everything":et[d].split(":")[0].toLowerCase());xs.textContent=e.length?`${e.length} reference${e.length===1?"":"s"} in use, for ${s.join(", ")}.`:"No references in use."},Bn=(e={})=>({...tt.value?{seconds:Number(tt.value)}:{},...qe.value?{captions:qe.value}:{},...$e.value?{music:$e.value}:{},...Fe.size?{references:[...Fe].filter(s=>r.some(d=>d.id===s&&d.kind==="reference")).map(s=>({id:s,aspect:Gt(s)}))}:{},format:Ee.value,...ze.value?{grade:ze.value}:{},...At.value==="clean"?{cleanVoice:!0}:{},...Zt.box.checked?{angles:!0}:{},...Dn.box.checked?{broll:"own"}:{},...en.box.checked?{titles:!0}:{},...La(),...vs(),..._n&&pt?{hook:pt,mustKeep:[pt]}:{},...e});async function Rs(e,{exact:s=!1,plan:d=null}={}){try{let k=Bn().references,b=await Y("POST",`/projects/${n}/make`,{brief:s?{...e,...k?{references:k}:{},...vs()}:{...Bn(e),...h&&wn(a).length?{assembly:{version:1,parts:wn(a)}}:{}},...d?{plan:{say:d.say,steps:d.steps,settings:d.settings}}:{}});We=b.id,ae.set(b.id,b),c&&(Je.reset(),Kn=!0,Oa()),D.textContent="Directing your reel: reading the footage, choosing the story, cutting and checking it. You can keep working.",Gn()}catch(k){D.textContent=k.message}}let Fn=t("button",{type:"button",class:"btn primary wide",onclick:()=>Rs()},"Make it"),Tt=t("div",{class:"make-status","aria-live":"polite"});function Gn(){let e=We?ae.get(We):null;J(Tt),Fn.disabled=!!e,Wn&&(Wn.disabled=!!e),e&&c?Tt.append(Je.el,se(e.progress??0,"Making the reel")):e?Tt.append(t("p",{class:"note"},`Making the reel\u2026 ${e.progress??0}%`),se(e.progress??0,"Making the reel")):c&&Kn&&Tt.append(Je.el)}let nt=!1,Ve=null,ut=null,Kn=!1,st=null,Je=c?Po({onFollow:e=>e?Ve&&sn(Ve):Ds()}):null,ot=c?Ro({load:()=>Y("GET",`/projects/${n}/layers`),show:e=>Is(e,`Replay: ${e.label}`),restore:()=>Ds(),animate:jo({reduced:matchMedia("(prefers-reduced-motion: reduce)").matches,automated:navigator.webdriver===!0})}):null,Wn=c?t("button",{type:"button",class:"btn replay-open",title:"Watch the latest make build up layer by layer, from the raw footage to the mix. Nothing renders.",onclick:()=>nt?null:ot.start()},"Replay how it was edited"):null;async function Is(e,s){if(!e?.preview||!e?.timeline||(oe.textContent=s,oe.hidden=!1,st||(fe.setGhost(e.timeline),S.setGhost(e.timeline)),p))return;let d=gn(e.timeline);await K.load(d,{fps:q(),duration:Ue(d),shape:me(),preview:e.preview})}function sn(e){return nt=!0,Is(e,"Director working preview")}function Ns(){if(!ut||K.rate!==0||ot?.open||!Je?.follow)return;let e=ut;ut=null,sn(e)}async function Ds(){nt=!1,ut=null,oe&&(oe.hidden=!0),fe.setGhost(st),S.setGhost(st),p||await K.load(u,le({fps:q(),duration:Ue(u),shape:me()}))}let on=[];function Ta(e){let s=null;try{s=JSON.parse(e.data)}catch{}if(!(!s||s.project!==n)){if(We===null)return void(on=[...on,s].slice(-40));Bs(s)}}function Oa(){let e=on;on=[];for(let s of e)Bs(s)}function Bs(e){e.job===We&&(Kn=!0,Je.push(e),e.preview&&e.timeline&&(Ve=e,ut=e,Je.follow&&Ns()))}function Pa(){Je.finish(),nt=!1,Ve=ut=null,oe&&(oe.hidden=!0),fe.setGhost(st),S.setGhost(st)}let _n=o.directorLoop===!0,pt=null,Ke={status:"none"},Fs=t("div",{class:"openings-host"});function an(){_n&&J(Fs).append(Ho({project:n,state:Ke,chosen:pt,onAsk:ja,onChoose:e=>(pt=e,an())}))}async function ja(){try{Ke={status:"making",job:(await Y("POST",`/projects/${n}/openings`,{brief:{format:Ee.value,...qe.value?{captions:qe.value}:{},...ze.value?{grade:ze.value}:{}}})).id,progress:0},pt=null}catch(e){Ke={status:"failed",error:e.message}}an()}async function Ra(){if(Ke.status!=="making")return;let e=(await Y("GET","/jobs")).jobs.find(s=>s.id===Ke.job);e&&(e.status==="done"?Ke={status:"ready",job:e.id,openings:JSON.parse(e.output).openings}:["failed","canceled"].includes(e.status)?Ke={status:"failed",error:e.error??"the drafts stopped"}:Ke={...Ke,progress:e.progress??0},an())}an();let ft=c?No({select:ze,source:()=>{let e=r.find(s=>s.kind==="video"&&!s.offline&&s.facts?.duration);return e?{url:`/tiles/${e.media}?kind=thumbs`,cell:Io(e.facts.duration/7056e5)}:null}}):null;ft&&nn.addEventListener("change",()=>ft.mark());let at=(e,...s)=>t("section",{class:"brief-group","aria-label":e},t("h3",{class:"group-title"},e),...s),Ot=(...e)=>t("div",{class:"brief-pair"},...e),Ia=t("div",{class:"make"},at("Start from",t("label",{for:"make-template",class:"sr-only"},"Template"),nn),at("Shape",Ot(t("div",{},t("label",{for:"make-format",class:"sr-only"},"Format"),Ee),t("div",{},t("label",{for:"make-length",class:"sr-only"},"Length"),tt))),at("Look and sound",...ft?[ft.el]:[],Ot(t("div",{},t("label",{for:"make-captions",class:"sr-only"},"Captions"),qe),t("div",{},t("label",{for:"make-grade",class:"sr-only"},"Colour look"),ze)),Ot(t("div",{},t("label",{for:"make-music",class:"sr-only"},"Music"),$e),t("div",{},t("label",{for:"make-voice",class:"sr-only"},"Voice"),At))),at("Extras",t("div",{class:"extras toggles",role:"group","aria-label":"Extras"},Zt.el,Dn.el,en.el)),...y?[at("Brand",Ot(t("div",{},t("label",{for:"make-style",class:"sr-only"},"Style pack"),Xt),t("div",{},t("label",{for:"make-type",class:"sr-only"},"Type kit"),Pn)),t("div",{class:"extras toggles",role:"group","aria-label":"Brand colours"},Rn.el,In.el),Ot(t("div",{},t("label",{for:"make-logo",class:"sr-only"},"Logo"),Et),t("div",{},t("label",{for:"make-bar",class:"sr-only"},"Bar across the film"),jn)),...js?[js]:[])]:[],at("References",xs,Ln,t("div",{class:"row tight"},Mt,Kt,t("button",{type:"button",class:"btn","aria-label":"Add a reference",title:"Add a reference for what's chosen: a video, an image or music",onclick:()=>Mt.click()},"+ Reference"))),..._n?[at("Openings",Fs)]:[],t("div",{class:"make-footer"},...c?[t("div",{class:"make-row"},Fn,Wn)]:[Fn],Tt)),We=null;async function Na(){if(!We)return;let e=(await Y("GET","/jobs")).jobs.find(d=>d.id===We);if(e&&ae.set(e.id,e),Gn(),!e||!["done","failed","canceled"].includes(e.status))return;if(We=null,Gn(),e.status!=="done")return D.textContent=e.error??"The reel stopped.";let s=JSON.parse(e.output);D.textContent=`${Ca[s.verdict]??s.verdict}. ${s.notes.join(" ")}`,s.file&&Pe.prepend(t("li",{class:"watch"},t("button",{type:"button",class:"btn primary",onclick:()=>rt("finish")},"Watch the final cut")));for(let d of[...s.changes].reverse())Pe.prepend(t("li",{},d))}let rn=t("button",{type:"button",class:"btn primary",onclick:()=>gt({type:"toggle"})},"Play"),Un=t("select",{class:"field small select","aria-label":"Preview shape",onchange:()=>K.setShape(me())},["project","16:9","9:16"].map(e=>t("option",{value:e},e==="project"?"Project shape":e))),ln=t("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>K.setZoom(Number(ln.value))}),Gs=t("input",{type:"checkbox",id:"guides",onchange:()=>K.setGuides(Gs.checked)}),cn=c?Bo():null,Hn=t("div",{class:`monitor-frame${c?" live":""}`},B,oe),ht=.5,Ae=c?t("span",{class:"wipe-grip",role:"slider",tabindex:"0","aria-label":"Compare: raw footage on the left, your cut on the right","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":"50"}):null,Qe=c?t("div",{class:"wipe",hidden:!0},t("span",{class:"wipe-tag raw"},"Raw"),t("span",{class:"wipe-tag cut"},"Cut"),t("span",{class:"wipe-line"},Ae)):null,qn=c?t("button",{type:"button",class:"btn small compare","aria-pressed":"false",title:"Drag the handle across the picture: raw footage on one side, your cut on the other",onclick:()=>zn(Qe.hidden)},"Compare raw"):null;function Ks(){!Qe||Qe.hidden||(Object.assign(Qe.style,{left:`${B.offsetLeft}px`,top:`${B.offsetTop}px`,width:`${B.clientWidth}px`,height:`${B.clientHeight}px`}),Qe.querySelector(".wipe-line").style.left=`${(ht*100).toFixed(2)}%`,Ae.setAttribute("aria-valuenow",String(Math.round(ht*100))))}function zn(e,s=ht){return ht=Math.min(1,Math.max(0,s)),Qe.hidden=!e,qn.setAttribute("aria-pressed",String(e)),Ks(),K.setWipe(e?ht:null)}if(Qe){Hn.append(Qe),new ResizeObserver(Ks).observe(B);let e=s=>{let d=B.getBoundingClientRect();return zn(!0,(s.clientX-d.left)/d.width)};Ae.addEventListener("pointerdown",s=>{s.preventDefault(),s.stopPropagation(),Ae.setPointerCapture(s.pointerId);let d=b=>e(b),k=()=>(Ae.removeEventListener("pointermove",d),Ae.removeEventListener("pointerup",k),Ae.removeEventListener("pointercancel",k));Ae.addEventListener("pointermove",d),Ae.addEventListener("pointerup",k),Ae.addEventListener("pointercancel",k)}),Ae.addEventListener("keydown",s=>{let d={ArrowLeft:-.05,ArrowRight:.05}[s.key],k=s.key==="Home"?0:s.key==="End"?1:d===void 0?null:ht+d;k!==null&&(s.preventDefault(),s.stopPropagation(),zn(!0,k))})}let mt=v?To({frame:Hn,canvas:B,timeNow:()=>K.time,zoomNow:()=>Number(ln.value),usable:()=>p?"Drawing marks the cut: show the cut on the monitor first.":Un.value!=="project"?"Drawing marks the project's own frame: set the preview shape back to Project shape.":null,pause:()=>K.rate!==0&&gt({type:"toggle"}),onChange:()=>{}}):null;mt&&ln.addEventListener("input",()=>mt.redraw());function gt(e){if(!e)return;if(e.type==="mode")return rt(e.mode);if(e.type==="prompt")return we.focus();if(e.type==="mark")return T(),e.edge==="in"||xe===null?(xe=K.time,je=null):K.time>xe?je=K.time:(je=xe,xe=K.time),D.textContent=je===null?`Marked in at ${Re(xe)}. Play to the end of the stretch and press O.`:`Marked ${Re(xe)} to ${Re(je)}. Tell Kriya what to do with it.`,zt();if(e.type==="undo")return Y("PATCH",`/projects/${n}`,{undo:!0}).then(R);if(e.type==="redo")return D.textContent="Redo isn't here yet.";if(e.type==="split"){let b=vt(u,K.time);return b&&G([{op:"split",clip:b.clip,at:lt(b,K.time)}])}if(e.type==="delete")return fe.selected&&G([{op:"ripple_delete",clip:fe.selected}]);let s={fps:p?r.find(b=>b.id===p).facts.fps??q():q(),duration:z()},d={t:K.time,rate:K.rate},k=oo(d,e,s);k.rate!==d.rate&&K.setRate(k.rate),(k.t!==d.t||e.type==="seek")&&K.seek(k.t)}function rt(e){g=e,Se("kriya-edit-mode",g),yt.dataset.mode=g;for(let s of Ws.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.mode===g));fe.draw(),S.draw(),g==="finish"&&F.refresh().catch(()=>{})}let Ws=t("div",{class:"modes",role:"group","aria-label":"Mode"},ea.map((e,s)=>t("button",{type:"button",class:"btn",dataset:{mode:e},"aria-pressed":"false","aria-keyshortcuts":String(s+1),onclick:()=>rt(e)},e[0].toUpperCase()+e.slice(1)))),bt={min:300,step:32},Vn=()=>Math.max(bt.min,Math.min(960,Math.round(window.innerWidth*.62))),Jn=()=>document.querySelector(".area-kriya")?.getBoundingClientRect().width??0;function dn(e){if(e===null)yt.style.removeProperty("--side"),Se("kriya-side-width","");else{let s=Math.round(Math.min(Vn(),Math.max(bt.min,e)));yt.style.setProperty("--side",`${s}px`),Se("kriya-side-width",String(s))}Te.setAttribute("aria-valuenow",String(Math.round(Jn()))),fe.draw(),S.draw()}let Te=t("div",{class:"side-handle",role:"separator",tabindex:"0","aria-orientation":"vertical","aria-label":"Resize the Kriya panel","aria-valuemin":String(bt.min),title:"Drag to resize. Double-click to fit the window.",onpointerdown:e=>{e.preventDefault(),Te.setPointerCapture(e.pointerId);let s=document.querySelector(".area-kriya").getBoundingClientRect().right,d=b=>dn(s-b.clientX),k=()=>(Te.removeEventListener("pointermove",d),Te.removeEventListener("pointerup",k),Te.removeEventListener("pointercancel",k));Te.addEventListener("pointermove",d),Te.addEventListener("pointerup",k),Te.addEventListener("pointercancel",k)},ondblclick:()=>dn(null),onkeydown:e=>{let s={ArrowLeft:bt.step,ArrowRight:-bt.step}[e.key];s?(e.preventDefault(),e.stopPropagation(),dn(Jn()+s)):e.key==="Home"&&(e.preventDefault(),dn(null))}}),_s=t("div",{class:"brief-panel"},Ia),Da=["A 30 second reel from this","Cut the false starts","A punchier start","A name strap with my name and role"],Us=t("div",{class:"chat-empty"},t("p",{class:"empty-title"},"Tell Kriya what you want"),t("p",{class:"note small"},'A change to this cut, or a plan for the whole film. Times like 0:05, a marked stretch or selected words are "this".'),t("div",{class:"suggestions",role:"group","aria-label":"Ideas to start from"},Da.map(e=>t("button",{type:"button",class:"btn suggestion",onclick:()=>(we.value=e,we.focus())},e)))),Hs=t("div",{class:"chat-panel"},t("div",{class:"chat-scroll"},Us,qt),t("div",{class:"composer"},On,Cs,Ct?.el,$a,t("p",{class:"note small hint"},"Enter sends. Shift+Enter is a new line. Mark a stretch with I and O."))),qs=t("div",{class:"activity-panel"},t("p",{class:"note small activity-empty"},"Nothing yet. Changes you accept and the cuts Kriya makes are listed here, newest first."),Pe),Ie=is([{key:"brief",label:"Brief",panel:_s},{key:"chat",label:"Chat",panel:Hs},{key:"activity",label:"Activity",panel:qs,count:()=>Pe.children.length||null}],{label:"Kriya",selected:["brief","chat","activity"].includes(Se("kriya-tab"))?Se("kriya-tab"):"chat",className:"inspector-tabs",onSelect:e=>Se("kriya-tab",e)});Jt=e=>Ie.select(e);let Qn=0,zs=()=>Us.hidden=qt.children.length>0;new MutationObserver(e=>{zs();let s=e.flatMap(d=>[...d.addedNodes]).filter(d=>d.classList?.contains("kriya")).length;Ie.selected()==="chat"?Qn=0:s&&Ie.mark("chat",Qn+=s)}).observe(qt,{childList:!0}),zs();let Yn=Pe.children.length;new MutationObserver(()=>{Ie.refresh();let e=Pe.children.length-Yn;Ie.selected()==="activity"?Yn=Pe.children.length:e>0&&Ie.mark("activity",e)}).observe(Pe,{childList:!0}),Ie.strip.addEventListener("click",()=>{Ie.selected()==="chat"&&(Qn=0),Ie.selected()==="activity"&&(Yn=Pe.children.length)});let yt=t("div",{class:"workspace"},ta(t("span",{class:"project-name"},a.name),Ws),t("div",{class:"banner"},D,Tn),t("div",{class:"grid"},t("div",{class:"area-bin"},ra,t("section",{class:"panel refs","aria-label":"Style references"},t("h2",{},"References"),_t,Mn,t("button",{type:"button",class:"btn wide",onclick:()=>Mt.click()},"Add a reference\u2026"))),t("section",{class:"area-monitor panel","aria-label":"Monitor"},Hn,...ot?[ot.el]:[],t("div",{class:"transport"},t("div",{class:"tgroup tplay"},rn,te,...de?[de]:[],V,...cn?[t("button",{type:"button",class:"btn keys-open","aria-label":"Keyboard shortcuts","aria-keyshortcuts":"?",title:"Keyboard shortcuts (?)",onclick:()=>cn.open()},"?")]:[]),t("div",{class:"tgroup"},Ma),t("div",{class:"tgroup tview"},Un,...qn?[qn]:[],t("label",{class:"inline"},Gs," Safe zones"),t("label",{class:"inline"},"Zoom ",ln))),...mt?[mt.tools]:[]),t("aside",{class:"area-kriya panel inspector","aria-label":"Kriya"},Te,Ie.strip,_s,Hs,qs),t("section",{class:"area-transcript panel","aria-label":"Transcript"},t("h2",{},"Transcript"),t("p",{class:"note small hint"},"Click a word to jump there. Double-click (or F2) to fix a misheard word."),Q),Ms,t("div",{class:"area-strip"},re),t("section",{class:"area-timeline panel","aria-label":"Timeline"},ne),t("div",{class:"area-finish"},pe),N));h&&yt.classList.add("has-story"),J(us).append(yt);let Vs=Number(Se("kriya-side-width"));Vs>=bt.min&&yt.style.setProperty("--side",`${Math.min(Vn(),Vs)}px`),rt(g),Te.setAttribute("aria-valuemax",String(Vn())),Te.setAttribute("aria-valuenow",String(Math.round(Jn()))),window.onkeydown=e=>{let s=e.target.closest?.("input, select, textarea");if(s&&e.key!=="Escape")return;if(e.key==="Escape")return s?document.activeElement?.blur():(Z.clear(),fe.select(null),xe=je=null,zt());if(cn&&e.key==="?"&&!e.metaKey&&!e.ctrlKey)return e.preventDefault(),cn.open();let d=so(e.key,{shift:e.shiftKey,mod:e.metaKey||e.ctrlKey});d&&(d.type==="toggle"&&e.target.closest?.("button")&&e.target!==rn||(e.preventDefault(),gt(d)))},setInterval(()=>g==="finish"&&F.scopes(),250);let Xn=new EventSource("/events");Xn.addEventListener("job",e=>{let s=null;try{s=JSON.parse(e.data)}catch{}s?.id&&ae.set(s.id,s),c&&s?.id&&s.id===We&&!["pending","running"].includes(s.status)&&Pa(),ca(s),g==="finish"&&F.refresh().catch(()=>{}),Na().catch(()=>{}),Ra().catch(()=>{}),s&&["pending","running"].includes(s.status)?xn():R().catch(()=>{})}),c&&Xn.addEventListener("live",Ta),Xn.addEventListener("setup",e=>{try{Ut({...Ge??{},setup:JSON.parse(e.data)})}catch{}Ge?.setup?.finished&&Y("GET","/runtime").then(Ut).catch(()=>{})}),Y("GET","/runtime").then(Ut).catch(()=>{}),await R(),window.__studio={monitor:K,act:gt,reload:R,setMode:rt,get pieces(){return u},...c?{director:{get states(){return Je.states},get showing(){return nt},get replay(){return{open:ot.open,at:ot.at}}}}:{}}}function sa(){let n=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);n?yr(n[1]):na()}window.addEventListener("hashchange",sa);sa();
5
+ Kriya measures it as numbers: ${d}. No picture, sound or words from it go into your video. Add only what you're allowed to use this way.`)&&bs(e,{reference:!0,aspect:s})}});function Ss(e,s){let d=e.path.split(/[\\/]/).at(-1),k=e.facts.width?e.facts.duration?"video":"image":"music",b=t("input",{type:"checkbox",id:`use-${s}-${e.id}`,checked:Fe.has(e.id),onchange:()=>(b.checked?Fe.add(e.id):Fe.delete(e.id),Oe(b.id))}),$=St.get(e.id),C=Kt(e.id),M=t("ul",{class:"ref-lines"},...$?ca($,C).map(A=>t("li",{},A)):[t("li",{class:"note"},"Measuring\u2026")]),I=Sn({id:`aspect-${s}-${e.id}`,"aria-label":`Take from ${d}`},C,A=>(Se(Ft(e.id),A.target.value),Oe(A.target.id))),O=Wt&&k==="video"?qo({id:e.id,where:s,state:Ce.get(e.id)??{status:"none"},off:Cn(e.id),onRead:()=>da(e.id),onCancel:()=>Ce.get(e.id)?.job&&Y("DELETE",`/jobs/${encodeURIComponent(Ce.get(e.id).job)}`).catch(()=>{}),onToggle:(A,_)=>{let ee=Cn(e.id);_?ee.delete(A):ee.add(A),Se(ks(e.id),[...ee].join(",")),Oe(`style-${s}-${e.id}-${A}`)}}):null;return t("li",{class:"asset ref"},t("button",{type:"button",class:"btn",onclick:()=>e.facts.duration&&j(e.id,0)},`${d} \xB7 ${k}`),t("label",{class:"note small",for:`aspect-${s}-${e.id}`},"Take from it"),I,Wt&&Ce.get(e.id)?.status==="ready"&&C==="all"?null:M,O,t("label",{class:"inline",for:`use-${s}-${e.id}`},b," Use in the cut"))}function Oe(e=null){J(_t),J(Ln);let s=r.filter(b=>b.kind==="reference");s.length||_t.append(t("li",{class:"note"},"None yet. Pick what a reference is for, then add a video whose cuts you like, music whose feel you like, or an image whose colour you like."));for(let b of s)ws.has(b.id)||(ws.add(b.id),Fe.add(b.id)),_t.append(Ss(b,"bin")),Ln.append(Ss(b,"direct")),St.has(b.id)||(St.set(b.id,null),Y("GET",`/projects/${n}/references/${encodeURIComponent(b.id)}`).then($=>(St.set(b.id,$),Oe())).catch($=>(St.set(b.id,{lines:[`Couldn't measure it: ${$.message}`]}),Oe()))),Wt&&b.facts.width&&b.facts.duration&&!Ce.has(b.id)&&(Ce.set(b.id,{status:"none"}),vs(b.id));Pa(),e&&document.getElementById(e)?.focus();let d=(b,$,C)=>{let M=b.value;J(b).append(t("option",{value:""},C),...$.map(I=>t("option",{value:I.id},I.path.split(/[\\/]/).at(-1)))),b.value=$.some(I=>I.id===M)?M:""};d($e,r.filter(b=>b.kind==="audio"&&!/kriya-music-/.test(b.path)),"No music"),Et&&d(Et,r.filter(b=>b.kind==="image"||b.role==="logo"||b.kind==="video"&&/\.(?:png|jpe?g|webp)$/i.test(b.path)).sort((b,$)=>($.role==="logo")-(b.role==="logo")),"Logo: none");let k=$e.value;$e.insertBefore(t("optgroup",{label:"Made by Kriya"},t("option",{value:"generated:calm"},"Music: calm bed (made by Kriya)"),t("option",{value:"generated:upbeat"},"Music: upbeat bed (made by Kriya)"),t("option",{value:"generated:warm"},"Music: warm bed (made by Kriya)")),$e.options[1]??null),/^generated:/.test(tn)?$e.value=tn:k&&($e.value=k)}let Ke=null,ct=t("p",{class:"note"}),En=t("div"),An=t("button",{type:"button",class:"btn primary",onclick:()=>Y("POST","/runtime/setup").then(Ht).catch(e=>ct.textContent=e.message)},"Set up speech-to-text"),Tn=t("section",{class:"panel setup","aria-label":"Speech-to-text setup",hidden:!0},t("h2",{},"Speech-to-text"),ct,En,An),On=t("p",{class:"note",role:"status"}),Ms={signed_out:"You're not signed in to Kriya",server_unreachable:"Kriya isn't reachable right now"};function pa(e){if(!e||e.mode==="kriya")return On.textContent="";On.textContent=e.mode==="none"?e.message:`${Ms[e.reason]??Ms.signed_out}, so the Director runs on ${e.label}. ${e.cloudOnly??""}`.trim()}let Cs=e=>(e/1e6).toLocaleString(void 0,{maximumFractionDigits:0});function Ht(e){Ke=e,"director"in e&&pa(e.director);let s=Ke.setup,d=s&&!s.finished;if(Tn.hidden=!Ke.speech&&!d&&!s?.error,An.hidden=!!d,An.textContent=s?.error?"Try again":"Set up speech-to-text",J(En),d){let k=s.total?Math.round(s.done*100/s.total):null;ct.textContent=s.total?`Downloading ${s.step}: ${Cs(s.done)} of ${Cs(s.total)} MB (${k}%)`:s.line??"Setting up\u2026",En.append(se(k,"Media Runtime setup"))}else s?.error?ct.textContent=`Setup stopped: ${s.error}`:Ke.speech?ct.textContent="Words in the transcript need the speech model on this computer. Setting it up downloads it once; after that it works offline.":s?.finished&&(ct.textContent="Ready. Index a file to read its words.")}let we=t("textarea",{id:"prompt",class:"field chat-input",rows:"2",placeholder:'Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',autocomplete:"off"}),Pn=t("span",{class:"chip selection",hidden:!0}),Ls=h?t("section",{class:"area-story panel storyboard","aria-label":"Storyboard"}):null,fa=h?Ho({root:Ls,clips:U,words:()=>l.words??[],onChange:e=>K([Wo(e)])}):null,Ct=h?fo({input:we,clips:U}):null,Ut=()=>{let[e,s]=(Z.selection()??[]).map(d=>l.words.find(k=>k.id===d));return e&&s?{asset:e.asset,from:e.start,to:s.end}:null},Es=h?t("button",{type:"button",class:"btn",hidden:!0,title:"Point at the selected words in your message",onclick:()=>Ut()&&Ct.insert(Ut())},"Mention this"):null;h&&(we.placeholder="Tell Kriya what to change. Type @ to point at a clip.",Q.addEventListener("dragstart",e=>Ut()&&e.dataTransfer.setData(De,JSON.stringify(Ut()))));let qt=t("ol",{class:"chat","aria-label":"Chat with Kriya","aria-live":"polite"}),Pe=t("ul",{class:"did","aria-label":"What I did"}),dt=[],xe=null,je=null,Re=e=>{let s=Math.max(0,e)/7056e5,d=Math.floor(s/60);return`${d}:${(s-d*60).toFixed(1).padStart(4,"0")}`},As=()=>{if(xe!==null&&je!==null&&je>xe)return{selection:{from:xe,to:je},label:`Marked ${Re(xe)}\u2013${Re(je)}`};let e=Z.selection();return e?{selection:{words:e},label:`Selected: ${l.words.find(s=>s.id===e[0])?.text??""}${e[0]===e[1]?"":" \u2026"}`}:fe.selected?{selection:{clip:fe.selected},label:`Selected: clip ${fe.selected}`}:xe!==null?{selection:{at:xe},label:`Marked in at ${Re(xe)} (press O for the end)`}:{selection:{at:G.time},label:null}},zt=()=>{let{label:e}=As();if(Pn.hidden=!e,Pn.textContent=e??"",!!h){Es.hidden=!Z.selection();for(let s of Q.querySelectorAll(".word"))s.draggable=s.getAttribute("aria-pressed")==="true"}};Q.addEventListener("click",()=>setTimeout(zt));function Vt(e){let s=[],d=0;for(let k of String(e).matchAll(/\b(\d{1,2}):(\d{2}(?:\.\d+)?)\b/g)){s.push(e.slice(d,k.index));let b=Math.round((Number(k[1])*60+Number(k[2]))*7056e5);s.push(t("button",{type:"button",class:"time-link",title:"Play from here",onclick:()=>(T(),G.seek(Math.min(b,Math.max(0,He(u)-1))))},k[0])),d=k.index+k[0].length}return s.push(e.slice(d)),s}function Ue(e,s,...d){let k=e==="you"&&Ct?po(s).flatMap($=>$.number?[t("span",{class:"chip mention"},$.text)]:Vt($.text)):Vt(s),b=t("li",{class:`msg ${e}`},t("span",{class:"who"},e==="you"?"You":"Kriya"),t("p",{},...k),...d);return qt.append(b),b.scrollIntoView({block:"nearest"}),b}function ha(e){st=e.timeline??null,fe.setGhost(e.timeline),S.setGhost(e.timeline);let s=t("div",{class:"proposal"}),d=async($,C)=>{try{let M=await Y("POST",`/projects/${n}/proposals/${e.id}`,{accept:$,...C?{only:C}:{}});if(D.textContent=M.dropped.length?`Not applied, because you changed that part: ${M.dropped.map(I=>I.change).join("; ")}.`:$?"Done. Undo with Cmd+Z.":"Left as it was.",$)for(let I of C?C.map(O=>e.changes[O]):e.changes)Pe.prepend(t("li",{},I));J(s).append(t("p",{class:"note"},$?M.dropped.length?"Partly applied.":"Applied.":"Not applied."))}catch(M){D.textContent=M.message}st=null,fe.setGhost(null),S.setGhost(null),await R()},k=c&&e.timeline?(()=>{let $={},C=async M=>{try{if(M){let I=await Y("GET",`/projects/${n}/preview?proposal=${encodeURIComponent(e.id)}`),O=gn(e.timeline);await G.load(O,{fps:q(),duration:He(O),shape:me(),preview:I})}else await G.load(u,le({fps:q(),duration:He(u),shape:me()}));V.textContent=M?"Preview: after":"Preview",$.before.setAttribute("aria-pressed",String(!M)),$.after.setAttribute("aria-pressed",String(M))}catch(I){D.textContent=I.message}};return $.before=t("button",{type:"button",class:"btn","aria-pressed":"true",onclick:()=>C(!1)},"Before"),$.after=t("button",{type:"button",class:"btn","aria-pressed":"false",onclick:()=>C(!0)},"After"),t("div",{class:"row compare",role:"group","aria-label":"Show on the monitor"},$.before,$.after)})():null,b=v&&e.motion?(()=>{let $=a.canvas.width,C=a.canvas.height,M=Math.min(220,Math.round(220*$/Math.max($,C))),I=`/projects/${n}/custom-preview?proposal=${encodeURIComponent(e.id)}&op=${e.motion.op}`,O=t("iframe",{title:"Preview of the custom animation",sandbox:"allow-scripts",loading:"lazy",src:I});Object.assign(O.style,{width:`${$}px`,height:`${C}px`,transform:`scale(${M/$})`});let A=t("div",{class:"scene-picture custom-picture"},O);Object.assign(A.style,{width:`${M}px`,height:`${Math.round(M*C/$)}px`});let _=(e.motion.gates??[]).map(H=>`${H.id} ${H.status.replaceAll("_"," ")}`).join(" \xB7 "),ee=()=>{we.value=`${e.ask??"That animation"}, in a different style`,d(!1).then(()=>Yt())};return t("div",{class:"scene-row custom-motion"},A,t("div",{class:"scene-info"},t("p",{class:"small"},"Custom animation, written by a model and checked by code"),_?t("p",{class:"note small"},`Checked on its own tile: ${_}`):null,t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>d(!0)},"Approve"),t("button",{type:"button",class:"btn",onclick:()=>O.src=I},"Play again"),t("button",{type:"button",class:"btn",onclick:ee},"Restyle"),t("button",{type:"button",class:"btn",onclick:()=>d(!1)},"Remove"))))})():null;return s.append(t("p",{class:"lead"},"Proposed, not applied yet"),...b?[b]:[],...k?[k]:[],t("ul",{},e.changes.map(($,C)=>t("li",{},t("span",{},...Vt($)),e.changes.length>1?t("button",{type:"button",class:"btn",onclick:()=>d(!0,[C])},"Only this"):null))),...b&&e.changes.length===1?[]:[t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>d(!0)},e.changes.length>1?"Accept all":"Accept"),t("button",{type:"button",class:"btn",onclick:()=>d(!1)},"Reject"))]),s}let Lt=null,Jt=()=>{},ma=()=>({...Fn(),...At.value==="clean"?{cleanVoice:!0}:{}}),Ts=e=>l.words.find(s=>s.id===e)?.text??e,Qt=e=>`${Math.floor(e/60)}:${(e%60).toFixed(1).padStart(4,"0")}`,Os=null;function Ps(e={}){return[Os,e.format,e.seconds?`about ${e.seconds} s`:null,e.captions&&e.captions!=="none"?`${e.captions} captions`:"no captions",e.grade&&e.grade!=="natural"?`${e.grade} look`:"natural colour",e.music&&e.music!=="none"?`${e.music} music`:"no music",e.cleanVoice?"background noise out of the voice":null,e.coldOpen?`cold open on "${Ts(e.coldOpen.from)} \u2026 ${Ts(e.coldOpen.to)}"${e.coldOpen.mono===!1?"":" in black and white"}`:null,e.hook?"a hook line first":null,e.cutSound&&e.cutSound!=="none"?`a ${e.cutSound} on each cut`:null,e.introSound&&e.introSound!=="none"?`a ${e.introSound} into the story`:null,Number.isInteger(e.punches)?`${e.punches} punch-ins`:null,e.angles?"wide and tight angles":null,e.arrange?"an accent in the music's key on every join":null,e.ambience?"a room tone from your own quiet":null,e.splits?"the voice leading and trailing its picture at the joins":null,e.beatJoins?"B-roll on the beat":null,e.broll==="own"?"B-roll from your clips":null,e.titles?"title cards":null,e.scenes?.length?`${e.scenes.length} animated scene${e.scenes.length===1?"":"s"}`:null,e.graphics?.length?`${e.graphics.length} motion graphic${e.graphics.length===1?"":"s"}`:null,e.transition&&e.transition!=="none"?`${e.transition} transitions ${e.transitionAll?"on every cut":"where the story changes moment"}`:null,e.pictures?.length?`${e.pictures.length} licensed picture${e.pictures.length===1?"":"s"}`:null,e.terms?.length?`${e.terms.length} cited definition${e.terms.length===1?"":"s"}`:null,e.song?"your song":null,e.montage?"cut on its beats":null,e.multicam?`${e.multicam.angles.length} cameras, following who speaks`:null,e.ramps?"a speed ramp into the story":null,e.cuts?.length?`trims ${e.cuts.map(d=>`${Qt(d.from)}\u2013${Qt(d.to)}`).join(", ")} of the take`:null].filter(Boolean).join(" \xB7 ")}function ga(e,s){let d=e.sceneChoices??{kinds:{},themes:{},swaps:[]},k=e.settings.format??Ee.value,$=k==="16:9"?{w:1920,h:1080,show:200}:k==="1:1"?{w:1080,h:1080,show:150}:k==="4:5"?{w:1080,h:1350,show:136}:{w:1080,h:1920,show:120},C=e.settings.scenes.map((H,ie)=>({scene:H,swaps:d.swaps[ie]??[H.kind]})),M=t("ul",{class:"scene-list"}),I=()=>{e.settings.scenes=C.map(H=>H.scene),C.length?e.brief.scenes=e.settings.scenes:delete e.brief.scenes,s()},O=H=>`/projects/${n}/scene-preview?format=${encodeURIComponent(k)}&scene=${encodeURIComponent(JSON.stringify(H))}`,A=H=>{let ie=ge=>Qt(ge/7056e5),be=l.words?.find(ge=>ge.id===H.from),ye=l.words?.find(ge=>ge.id===H.to);return be&&ye?`${ie(be.start)}\u2013${ie(ye.end)}`:""},_=()=>{J(M),C.length||M.append(t("li",{class:"note small"},"No animated scenes: the speaker stays on screen."));for(let H of C){let ie=t("iframe",{title:`Preview of the scene "${H.scene.title||H.scene.items[0].text}"`,sandbox:"allow-scripts",loading:"lazy",src:O(H.scene)});ie.style.width=`${$.w}px`,ie.style.height=`${$.h}px`,ie.style.transform=`scale(${$.show/$.w})`;let be=t("div",{class:"scene-picture"},ie);be.style.width=`${$.show}px`,be.style.height=`${Math.round($.show*$.h/$.w)}px`;let ye=t("select",{class:"field select","aria-label":"Draw this scene as",onchange:()=>(H.scene={...H.scene,kind:ye.value},I(),ie.src=O(H.scene))},H.swaps.map(ge=>t("option",{value:ge},d.kinds[ge]??ge)));ye.value=H.scene.kind,M.append(t("li",{class:"scene-row"},be,t("div",{class:"scene-info"},t("p",{class:"small"},t("span",{class:"scene-time"},A(H.scene)),` ${H.scene.title||H.scene.items[0].text}`),t("p",{class:"note small"},H.scene.items.map(ge=>`${ge.text}${ge.value!==void 0?` ${ge.value}${ge.unit??""}`:""}`).join(" \xB7 ")),t("div",{class:"row"},ye,t("button",{type:"button",class:"btn",onclick:()=>ie.src=O(H.scene)},"Play again"),t("button",{type:"button",class:"btn",onclick:()=>(C.splice(C.indexOf(H),1),I(),_())},"Keep the speaker")))))}},ee=t("select",{class:"field select","aria-label":"Look of the scenes",onchange:()=>{for(let H of C)H.scene={...H.scene,theme:ee.value};I(),_()}},Object.entries(d.themes).map(([H,ie])=>t("option",{value:H},ie)));return ee.value=C[0].scene.theme,_(),t("div",{class:"scenes"},t("div",{class:"row scene-head"},t("p",{class:"lead"},"Animated scenes"),ee),M)}function ba(e,s){let d=e.graphicChoices??{kinds:{},styles:{},accents:[],tones:[],fonts:[]},k=e.settings.format??Ee.value,b=k==="16:9"?{w:1920,h:1080,show:200}:k==="1:1"?{w:1080,h:1080,show:150}:k==="4:5"?{w:1080,h:1350,show:136}:{w:1080,h:1920,show:120},$=[...e.settings.graphics],C=t("ul",{class:"scene-list"}),M=()=>{e.settings.graphics=$,$.length?e.brief.graphics=$:delete e.brief.graphics,s()},I=H=>`/projects/${n}/graphic-preview?format=${encodeURIComponent(k)}&graphic=${encodeURIComponent(JSON.stringify(H))}`,O=H=>{let ie=H.at&&l.words?.find(be=>be.id===H.at);return H.kind==="intro"?"start":H.kind==="end"?"end":ie?Qt(ie.start/7056e5):""},A=()=>{J(C),$.length||C.append(t("li",{class:"note small"},"No motion graphics.")),$.forEach((H,ie)=>{let be=d.kinds[H.kind]??{label:H.kind,styles:[H.style]},ye=t("iframe",{title:`Preview of the ${be.label.toLowerCase()} "${H.text}"`,sandbox:"allow-scripts",loading:"lazy",src:I(H)});ye.style.width=`${b.w}px`,ye.style.height=`${b.h}px`,ye.style.transform=`scale(${b.show/b.w})`;let ge=t("div",{class:"scene-picture graphic-picture"},ye);ge.style.width=`${b.show}px`,ge.style.height=`${Math.round(b.show*b.h/b.w)}px`;let un=be.styles.length>1?t("select",{class:"field select","aria-label":`Style of the ${be.label.toLowerCase()}`,onchange:()=>($[ie]={...$[ie],style:un.value},M(),ye.src=I($[ie]))},be.styles.map(pn=>t("option",{value:pn},d.styles[pn]??pn))):null;un&&(un.value=H.style),C.append(t("li",{class:"scene-row"},ge,t("div",{class:"scene-info"},t("p",{class:"small"},t("span",{class:"scene-time"},O(H)),` ${be.label}`),t("p",{class:"note small"},[H.text,H.subtitle].filter(Boolean).join(" \xB7 ")),t("div",{class:"row"},un,t("button",{type:"button",class:"btn",onclick:()=>ye.src=I($[ie])},"Play again"),t("button",{type:"button",class:"btn",onclick:()=>($=$.filter((pn,Ga)=>Ga!==ie),M(),A())},"Remove")))))})},_=(H,ie,be)=>{let ye=t("select",{class:"field select","aria-label":be,onchange:()=>($=$.map(ge=>({...ge,[H]:ye.value})),M(),A())},ie.map(ge=>t("option",{value:ge},`${be}: ${ge}`)));return ye.value=$[0][H],ye},ee=t("div",{class:"row"},_("accent",d.accents,"Colour"),_("tone",d.tones,"Plate"),_("font",d.fonts,"Font"));return A(),t("div",{class:"scenes"},t("p",{class:"lead"},"Motion graphics"),ee,C)}function ya(e,s){let d=t("ul",{class:"scene-list"}),k=()=>{e.brief.pictures=e.settings.pictures.map(({from:$,to:C,id:M})=>({from:$,to:C,id:M})),e.brief.pictures.length||delete e.brief.pictures,s()},b=()=>{J(d),e.settings.pictures.length||d.append(t("li",{class:"note small"},"No pictures: the speaker stays on screen."));for(let $ of e.settings.pictures){let C=()=>$.options.find(A=>A.id===$.id)??$.options[0],M=t("img",{class:"found-thumb",alt:C().title,loading:"lazy",src:`/projects/${n}/found-thumb?id=${encodeURIComponent($.id)}`}),I=t("p",{class:"note small"},`${C().licence} \xB7 ${C().creator}`),O=t("select",{class:"field select","aria-label":"Use this picture",onchange:()=>{$.id=O.value,M.src=`/projects/${n}/found-thumb?id=${encodeURIComponent($.id)}`,M.alt=C().title,I.textContent=`${C().licence} \xB7 ${C().creator}`,k()}},$.options.map(A=>t("option",{value:A.id},A.title.slice(0,60))));O.value=$.id,d.append(t("li",{class:"scene-row"},M,t("div",{class:"scene-info"},t("p",{class:"small"},$.query),I,t("div",{class:"row"},O,t("button",{type:"button",class:"btn",onclick:()=>{e.settings.pictures.splice(e.settings.pictures.indexOf($),1),k(),b()}},"Keep the speaker")))))}};return b(),t("div",{class:"scenes"},t("p",{class:"lead"},"Real pictures"),d)}function wa(e,s){let d=t("ul",{class:"scene-list"}),k=()=>{J(d);for(let b of e.settings.terms)d.append(t("li",{class:"scene-row"},t("div",{class:"scene-info"},t("p",{class:"small"},t("b",{},b.term),` \u201C${b.quote}\u201D ${b.source}`),t("button",{type:"button",class:"btn",onclick:()=>{e.settings.terms.splice(e.settings.terms.indexOf(b),1),e.brief.terms=e.settings.terms.map(({at:$,id:C,term:M})=>({at:$,id:C,term:M})),e.brief.terms.length||delete e.brief.terms,s(),k()}},"Don't show this"))))};return k(),t("div",{class:"scenes"},t("p",{class:"lead"},"Definitions"),d)}function ka(e){let s=t("select",{class:"field select","aria-label":"Style pack",onchange:()=>{s.value?e.brief.stylePack=e.settings.stylePack=s.value:(delete e.brief.stylePack,delete e.settings.stylePack)}},[t("option",{value:""},"No style pack"),...Object.entries(y.packs).map(([d,k])=>t("option",{value:d,title:k.does},k.label))]);return s.value=e.brief.stylePack??"",t("div",{class:"scenes"},t("p",{class:"lead"},"Style"),s)}function va(e,s){let d={clean:"Clean",karaoke:"Karaoke",boxed:"Boxed",pop:"Pop",story:"Story",minimal:"Minimal",...y?Object.fromEntries(y.looks.map(C=>[C,E[C]??C])):{}},k={"#ffd23f":"Yellow","#ffb347":"Amber","#4fd1c5":"Teal","#ff7ab6":"Pink","#ffffff":"White"},b=t("select",{class:"field select","aria-label":"Caption look",onchange:()=>{e.brief.captions=b.value,e.settings.captions=b.value,s()}},Object.entries(d).map(([C,M])=>t("option",{value:C},M)));b.value=e.brief.captions;let $=t("select",{class:"field select","aria-label":"Highlight colour",onchange:()=>{$.value?e.brief.captionStyle={accent:$.value}:delete e.brief.captionStyle,e.settings.captionStyle=e.brief.captionStyle,s()}},[t("option",{value:""},"Look's own colour"),...Object.entries(k).map(([C,M])=>t("option",{value:C},M))]);return $.value=e.brief.captionStyle?.accent??"",t("div",{class:"scenes"},t("p",{class:"lead"},"Captions"),t("div",{class:"row"},b,$))}function xa(e){let s=t("ol",{class:"order-strip","aria-label":"The film's order"}),d=t("p",{class:"sr-only",role:"status","aria-live":"polite"}),k={director:"the Director's choice",default:"the order added",storyboard:"your storyboard",person:"as you said"},b={story:"story",whole:"whole",over:"over the voice",sound:"sound only"},$=M=>M.from===null&&M.to===null?M.duration?Re(M.duration):"":`${M.from===null?"0:00":Re(M.from)}\u2013${M.to===null?"end":Re(M.to)}`,C=(M=null)=>{J(s);let I=e.order.parts,O=kn(I);I.forEach(A=>{let _=O.indexOf(A),ee=`clip ${A.number??"?"}${A.label?`, ${A.label}`:""}`,H=(ie,be)=>t("button",{type:"button",class:"btn order-move","aria-label":`Move ${ee} ${be}`,disabled:_<0||!O[_+ie],"data-move":`${A.id}:${ie}`,onclick:()=>{let ye=xt(e.settings.assembly.parts,A.id,ie);ye&&(e.settings.assembly={version:1,parts:ye},e.brief.assembly=e.settings.assembly,e.order.parts=xt(e.order.parts,A.id,ie),d.textContent=`${ee} moved ${be}.`,C(`${A.id}:${ie}`))}},ie<0?"\u2191":"\u2193");s.append(t("li",{class:"order-part","data-part":A.id},t("span",{class:"order-n"},_>=0?String(_+1):"+"),t("span",{class:"order-what"},t("b",{},`Clip ${A.number??"?"}`),A.label?` ${A.label}`:"",t("span",{class:"note small"},` ${[b[A.use]??A.use,$(A),k[A.why]].filter(Boolean).join(" \xB7 ")}`)),_>=0?t("span",{class:"order-moves"},H(-1,"earlier"),H(1,"later")):null))}),M&&(s.querySelector(`[data-move="${M}"]:not([disabled])`)??s.querySelector(`[data-part="${M.split(":")[0]}"] button:not([disabled])`))?.focus()};return C(),t("div",{class:"scenes order"},t("p",{class:"lead"},"Order"),e.order.parts.length?s:null,...e.order.lines.map(M=>t("p",{class:"note small"},M)),d)}function $a(e,s){let{understood:d=[],cannot:k=[],questions:b=[],defaulted:$=[]}=e.intent;e.intent.answers??={};let C=(M,I)=>{let O=`q-${e.intent.id??(e.intent.id=Math.random().toString(36).slice(2,8))}-${I}`;return t("fieldset",{class:"question"},t("legend",{},M.question),...M.options.map(A=>t("label",{class:"inline choice"},t("input",{type:"radio",name:O,value:String(A),checked:A===(e.intent.answers[M.field]??M.default),onchange:()=>{e.intent.answers[M.field]=A,e.settings[M.field]=A,ta(e.brief,M.field,A),s()}}),` ${Nt(M.field,A)}${A===M.default?" (default)":""}`)))};return t("div",{class:"intent"},d.length?t("div",{},t("p",{class:"lead"},"What I understood"),t("ul",{},d.map(M=>t("li",{},ea(M))))):null,k.length?t("div",{},t("p",{class:"lead"},"Not in this cut"),t("ul",{},k.map(M=>t("li",{},`"${M.said}"${M.nearest?`. Nearest I can do: ${M.nearest}`:""}`)))):null,...b.map(C),$.length?t("p",{class:"note small"},`Also decided by default: ${$.map(M=>`${us[M.field]??M.field} ${Nt(M.field,M.value)}`).join(", ")}.`):null)}function Sa(e){Os=e.genreLabel?`reads as: ${e.genreLabel}`:null;let s=t("p",{class:"note small plan-summary"},Ps(e.settings)),d=null,k=()=>{s.textContent=Ps(e.settings),d?.refresh()},b=[e.steps.length?t("ol",{class:"steps"},e.steps.map(ee=>t("li",{},...Vt(ee)))):null,e.intent?$a(e,k):null,e.order?xa(e):null].filter(Boolean),$=[e.brief.captions?va(e,k):null,y?ka(e):null].filter(Boolean),C=[b.length?{key:"plan",label:"Plan",panel:t("div",{class:"plan-section"},...b)}:null,e.settings.scenes?.length?{key:"scenes",label:"Scenes",panel:t("div",{class:"plan-section"},ga(e,k)),count:()=>e.settings.scenes?.length??0}:null,e.settings.graphics?.length?{key:"graphics",label:"Graphics",panel:t("div",{class:"plan-section"},ba(e,k)),count:()=>e.settings.graphics?.length??0}:null,e.settings.pictures?.length?{key:"pictures",label:"Pictures",panel:t("div",{class:"plan-section"},ya(e,k)),count:()=>e.settings.pictures?.length??0}:null,e.settings.terms?.length?{key:"terms",label:"Definitions",panel:t("div",{class:"plan-section"},wa(e,k)),count:()=>e.settings.terms?.length??0}:null,$.length?{key:"look",label:"Look",panel:t("div",{class:"plan-section"},...$)}:null].filter(Boolean);C.length>1&&(d=ls(C,{label:"Parts of the plan",className:"plan-tabs"}));let M=t("div",{class:"plan-backdrop",hidden:!0,onclick:()=>A(!1)}),I=t("button",{type:"button",class:"btn ghost plan-expand","aria-expanded":"false",onclick:()=>A(!_.classList.contains("expanded"))},"Expand"),O=ee=>ee.key==="Escape"&&(ee.stopPropagation(),A(!1));function A(ee){_.classList.toggle("expanded",ee),M.hidden=!ee,I.textContent=ee?"Close":"Expand",I.setAttribute("aria-expanded",String(ee)),ee?(document.body.append(M),_.setAttribute("role","dialog"),_.setAttribute("aria-modal","true"),_.setAttribute("aria-label","The Director's plan"),window.addEventListener("keydown",O,!0),I.focus()):(_.removeAttribute("role"),_.removeAttribute("aria-modal"),_.removeAttribute("aria-label"),M.remove(),window.removeEventListener("keydown",O,!0))}let _=t("div",{class:"proposal plan"},t("div",{class:"plan-head"},t("div",{class:"plan-title"},t("p",{class:"lead"},e.revises?"A change to your current cut, not made yet":"The Director's plan, not made yet"),I),s),e.revises?t("p",{class:"note small"},`${e.differs?.length?`What changes: ${e.differs.join(" \xB7 ")}. `:""}${e.keepsStory?"The story and your own edits stay.":"The length or the trims change, so the lines are chosen again; your own edits are kept where they still fit."} Say "start over" for a new cut from the footage.`):null,...d?[d.strip]:[],...C.map(ee=>ee.panel),t("div",{class:"row plan-actions"},t("button",{type:"button",class:"btn primary",onclick:()=>(A(!1),Lt=null,Ma(e.brief),J(_).append(t("p",{class:"note"},`Approved. Making it now in ${e.brief.format??Ee.value}; the progress is in Brief.`)),Ns(e.brief,{exact:!0,plan:e}),Jt("brief"))},"Approve and make it"),t("button",{type:"button",class:"btn",onclick:()=>(A(!1),Lt=e,we.focus(),we.placeholder="Say what to change in the plan\u2026")},"Change\u2026")));return _}function Ma(e={}){e.format&&(Ee.value=e.format);let s=e.seconds?String(e.seconds):"";s&&![...tt.options].some(d=>d.value===s)&&tt.append(t("option",{value:s},`${s} seconds`)),tt.value=s,qe.value=e.captions??"",ze.value=e.grade??"",ft?.mark(),/^generated:/.test(e.music??"")&&[...$e.options].some(d=>d.value===e.music)?$e.value=e.music:e.music||($e.value=""),At.value=e.cleanVoice?"clean":"",Zt.box.checked=!!e.angles,Bn.box.checked=e.broll==="own",en.box.checked=!!e.titles,nn.value=""}async function js(e,s=null,d={}){Jt("chat");let k=Ue("kriya",s?"Revising the plan\u2026":"Planning the cut\u2026");try{let b=await Y("POST",`/projects/${n}/plan`,{text:e,history:dt.slice(-6),previous:s,choices:ma(),...d});k.remove(),Lt=b,Ue("kriya",b.say||"Here's my plan.",Sa(b)),dt.push({who:"kriya",text:(b.say||"").slice(0,400)})}catch(b){k.remove(),Ue("kriya",b.message)}}async function Yt({planning:e=!1}={}){let s=we.value.trim();if(!s)return;Jt("chat");let d=Ct?Ct.take(s):{text:s,mentions:[]},k=d.text,b=mt?.mark(),$={...d.mentions.length?{mentions:d.mentions}:{},...b?{mark:b}:{}};if(b&&mt.clear(),we.placeholder=h?"Tell Kriya what to change. Type @ to point at a clip.":'Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',Lt||e)return Ue("you",s),dt.push({who:"you",text:s.slice(0,400)}),we.value="",js(k,Lt,$);let{selection:C,label:M}=As();Ue("you",b?`${s} (on the ${b.kind} you drew at ${Re(b.at)})`:M?`${s} (${M.replace(/^Selected: /,"on ")})`:s),we.value="";let I=Ue("kriya","Thinking about that\u2026");try{let O=await Y("POST",`/projects/${n}/ask`,{text:k,selection:C,history:dt.slice(-6),...$});I.remove();let A=O.say||(O.proposal?"Here's what I'd change.":O.direct?"That's about the whole video.":O.reason??"I couldn't turn that into an edit. Try saying it another way.");if(dt.push({who:"you",text:s.slice(0,400)}),O.proposal?.motion&&(O.proposal.ask=k),O.direct&&!O.proposal)return js(k,null,$);let _=O.cannot?.length?t("div",{class:"intent"},t("p",{class:"lead"},"Not in this change"),t("ul",{},O.cannot.map(ee=>t("li",{},`"${ee.said}"${ee.nearest?`. Nearest I can do: ${ee.nearest}`:""}`)))):null;Ue("kriya",A,O.proposal?ha(O.proposal):null,_),dt.push({who:"kriya",text:A.slice(0,400)})}catch(O){I.remove(),Ue("kriya",O.status===0||O.status>=500?"I can't reach Kriya right now, so I can't make changes by asking. You can still edit by hand.":O.message)}}we.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),Yt())});let Ca=t("form",{class:"prompt",onsubmit:e=>(e.preventDefault(),Yt())},t("label",{for:"prompt",class:"sr-only"},"Message Kriya"),we,t("div",{class:"send"},t("button",{class:"btn primary",type:"submit"},"Send"),t("button",{type:"button",class:"btn",title:"Ask the Director for a plan of the whole cut",onclick:()=>Yt({planning:!0})},"Plan"),...o.dictation?[La()]:[]));function La(){let e=t("button",{type:"button",class:"btn talk","aria-pressed":"false",title:"Hold to talk (or hold Space on this button); the text appears in the box"},"Hold to talk"),s=null,d=null,k=0,b=async()=>{if(s)return;try{d=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{D.textContent="The microphone isn't available to the Studio.";return}let C=[];s=new MediaRecorder(d),s.ondataavailable=M=>M.data.size&&C.push(M.data),s.onstop=async()=>{for(let I of d.getTracks())I.stop();let M=(s.mimeType||"audio/webm").split(";")[0];if(s=null,e.setAttribute("aria-pressed","false"),e.textContent="Hold to talk",Date.now()-k<300||!C.length)return D.textContent="Hold the button while you speak.";D.textContent="Turning your words into text on this computer\u2026";try{let I=await fetch(`/projects/${n}/dictate`,{method:"POST",headers:{"content-type":M},body:new Blob(C,{type:M})}),O=await I.json();if(!I.ok)throw new Error(O.message??"That couldn't be heard.");we.value=`${we.value?`${we.value} `:""}${O.text}`.trim(),D.textContent=O.text?"Read it over, then send.":"Nothing was heard.",we.focus()}catch(I){D.textContent=I.message}},k=Date.now(),s.start(),e.setAttribute("aria-pressed","true"),e.textContent="Listening\u2026 let go to stop",setTimeout(()=>s?.state==="recording"&&s.stop(),6e4)},$=()=>s?.state==="recording"&&s.stop();e.addEventListener("pointerdown",C=>(C.preventDefault(),b()));for(let C of["pointerup","pointerleave","pointercancel"])e.addEventListener(C,$);return e.addEventListener("keydown",C=>(C.key===" "||C.key==="Enter")&&!C.repeat&&(C.preventDefault(),b())),e.addEventListener("keyup",C=>(C.key===" "||C.key==="Enter")&&$()),e}let Ea=t("div",{class:"marks",role:"group","aria-label":"Mark a range of the cut"},t("button",{type:"button",class:"btn","aria-keyshortcuts":"I",title:"Mark in (I)",onclick:()=>gt({type:"mark",edge:"in"})},"Mark in"),t("button",{type:"button",class:"btn","aria-keyshortcuts":"O",title:"Mark out (O)",onclick:()=>gt({type:"mark",edge:"out"})},"Mark out")),Aa={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",needs_you:"Needs you",not_checked:"Not checked"},tt=t("select",{id:"make-length",class:"field select"},[["","Length: auto (30\u201360 s)"],["30","30 seconds"],["45","45 seconds"],["60","60 seconds"],["90","90 seconds"]].map(([e,s])=>t("option",{value:e},s))),qe=t("select",{id:"make-captions",class:"field select"},[["","No captions"],["clean","Captions: clean"],["karaoke","Captions: karaoke"],["boxed","Captions: boxed"],["pop","Captions: pop"],["story","Captions: story"],["minimal","Captions: minimal"]].map(([e,s])=>t("option",{value:e},s)));y&&qe.append(...y.looks.map(e=>t("option",{value:e},`Captions: ${(E[e]??e).toLowerCase()}`)));let $e=t("select",{id:"make-music",class:"field select"}),Xt=y?t("select",{id:"make-style",class:"field select"},[t("option",{value:""},"Style: none"),...Object.entries(y.packs).map(([e,s])=>t("option",{value:e,title:s.does},`Style: ${s.label}`))]):null,jn=y?t("select",{id:"make-type",class:"field select"},[t("option",{value:""},"Type: the film's own"),...Object.entries(y.pairs).map(([e,s])=>t("option",{value:e},`Type: ${s}`))]):null,Rn=y?t("select",{id:"make-bar",class:"field select"},[["","Bar: none"],["progress","Bar: progress"],["chapters","Bar: chapters"]].map(([e,s])=>t("option",{value:e},s))):null,Et=y?t("select",{id:"make-logo",class:"field select"}):null,Rs=(e,s)=>{let d=t("input",{type:"checkbox",id:`${e}-on`}),k=t("input",{type:"color",id:e,class:"swatch",value:e==="make-ink"?"#ffffff":"#ffd23f","aria-label":s});return{on:d,pick:k,el:t("label",{class:"inline",for:`${e}-on`},d,` ${s} `,k)}},In=y?Rs("make-ink","My text colour"):null,Nn=y?Rs("make-accent","My accent"):null,Is=y&&!y.shipped?t("p",{class:"note"},"The Fonts pack isn't installed on this computer, so a type kit draws in the system fonts until it is (kriya edit setup --pack fonts)."):null,Ta=()=>{if(!y)return{};let e=jn.value||(Xt.value?null:y.chosen?.pair??"clean"),s={...In.on.checked?{text:In.pick.value}:{},...Nn.on.checked?{accent:Nn.pick.value}:{}},d={...Object.keys(s).length?{colors:s}:{},...Et.value?{logo:Et.value}:{},...Rn.value?{bar:Rn.value}:{}};return{...Xt.value?{stylePack:Xt.value}:{},...jn.value||Object.keys(d).length?{typeKit:{...e?{pair:e}:{},...d}}:{}}},Ee=t("select",{id:"make-format",class:"field select"},[["9:16","Format: 9:16 (Reels, Shorts)"],["16:9","Format: 16:9 (YouTube)"],["1:1","Format: 1:1 (square post)"],["4:5","Format: 4:5 (feed post)"]].map(([e,s])=>t("option",{value:e},s))),ze=t("select",{id:"make-grade",class:"field select"},[["","Look: natural"],["vivid","Look: vivid"],["cinematic","Look: cinematic (cool, vignette)"],["warm","Look: warm"],["bright","Look: bright"],["mono","Look: black and white"]].map(([e,s])=>t("option",{value:e},s))),At=t("select",{id:"make-voice",class:"field select"},[["","Voice: as recorded"],["clean","Voice: remove background noise"]].map(([e,s])=>t("option",{value:e},s))),Dn=(e,s)=>{let d=t("input",{type:"checkbox",id:e});return{box:d,el:t("label",{class:"inline",for:e},d,` ${s}`)}},Zt=Dn("make-angles","Angles (wide and tight)"),Bn=Dn("make-broll","B-roll from my clips"),en=Dn("make-titles","Title cards"),tn="";$e.addEventListener("change",()=>tn=$e.value);let Oa={"":null,reel:{format:"9:16",captions:"karaoke",grade:"vivid",length:"45",music:"generated:upbeat",voice:"clean",angles:!0},clean:{format:"9:16",captions:"clean",grade:"",length:"30",music:"",voice:"clean"},youtube:{format:"16:9",captions:"clean",grade:"warm",length:"60",music:"generated:calm",voice:"clean"},square:{format:"1:1",captions:"boxed",grade:"vivid",length:"30",music:"generated:upbeat",voice:"clean"},cinematic:{format:"16:9",captions:"",grade:"cinematic",length:"60",music:"generated:warm",voice:"clean",angles:!0,titles:!0}},nn=t("select",{id:"make-template",class:"field select",onchange:()=>{let e=Oa[nn.value];e&&(Ee.value=e.format,qe.value=e.captions,ze.value=e.grade,tt.value=e.length,At.value=e.voice,Zt.box.checked=!!e.angles,en.box.checked=!!e.titles,$e.value=tn=e.music)}},[["","Template: choose\u2026"],["reel","Talking-head reel: karaoke captions, upbeat music"],["clean","Clean reel: simple captions, no music"],["youtube","YouTube talk: 16:9, warm, calm music"],["square","Square post: boxed captions, vivid"],["cinematic","Cinematic: 16:9, cool look, no captions"]].map(([e,s])=>t("option",{value:e},s))),Pa=()=>{let e=r.filter(d=>d.kind==="reference"&&Fe.has(d.id)),s=[...new Set(e.map(d=>Kt(d.id)))].map(d=>d==="all"?"everything":et[d].split(":")[0].toLowerCase());$s.textContent=e.length?`${e.length} reference${e.length===1?"":"s"} in use, for ${s.join(", ")}.`:"No references in use."},Fn=(e={})=>({...tt.value?{seconds:Number(tt.value)}:{},...qe.value?{captions:qe.value}:{},...$e.value?{music:$e.value}:{},...Fe.size?{references:[...Fe].filter(s=>r.some(d=>d.id===s&&d.kind==="reference")).map(s=>({id:s,aspect:Kt(s)}))}:{},format:Ee.value,...ze.value?{grade:ze.value}:{},...At.value==="clean"?{cleanVoice:!0}:{},...Zt.box.checked?{angles:!0}:{},...Bn.box.checked?{broll:"own"}:{},...en.box.checked?{titles:!0}:{},...Ta(),...xs(),...Hn&&pt?{hook:pt,mustKeep:[pt]}:{},...e});async function Ns(e,{exact:s=!1,plan:d=null}={}){try{let k=Fn().references,b=await Y("POST",`/projects/${n}/make`,{brief:s?{...e,...k?{references:k}:{},...xs()}:{...Fn(e),...h&&wn(a).length?{assembly:{version:1,parts:wn(a)}}:{}},...d?{plan:{say:d.say,steps:d.steps,settings:d.settings}}:{}});We=b.id,ae.set(b.id,b),c&&(Je.reset(),Wn=!0,Ra()),D.textContent="Directing your reel: reading the footage, choosing the story, cutting and checking it. You can keep working.",Gn()}catch(k){D.textContent=k.message}}let Kn=t("button",{type:"button",class:"btn primary wide",onclick:()=>Ns()},"Make it"),Tt=t("div",{class:"make-status","aria-live":"polite"});function Gn(){let e=We?ae.get(We):null;J(Tt),Kn.disabled=!!e,_n&&(_n.disabled=!!e),e&&c?Tt.append(Je.el,se(e.progress??0,"Making the reel")):e?Tt.append(t("p",{class:"note"},`Making the reel\u2026 ${e.progress??0}%`),se(e.progress??0,"Making the reel")):c&&Wn&&Tt.append(Je.el)}let nt=!1,Ve=null,ut=null,Wn=!1,st=null,Je=c?Ro({onFollow:e=>e?Ve&&sn(Ve):Fs()}):null,ot=c?No({load:()=>Y("GET",`/projects/${n}/layers`),show:e=>Ds(e,`Replay: ${e.label}`),restore:()=>Fs(),animate:Io({reduced:matchMedia("(prefers-reduced-motion: reduce)").matches,automated:navigator.webdriver===!0})}):null,_n=c?t("button",{type:"button",class:"btn replay-open",title:"Watch the latest make build up layer by layer, from the raw footage to the mix. Nothing renders.",onclick:()=>nt?null:ot.start()},"Replay how it was edited"):null;async function Ds(e,s){if(!e?.preview||!e?.timeline||(oe.textContent=s,oe.hidden=!1,st||(fe.setGhost(e.timeline),S.setGhost(e.timeline)),p))return;let d=gn(e.timeline);await G.load(d,{fps:q(),duration:He(d),shape:me(),preview:e.preview})}function sn(e){return nt=!0,Ds(e,"Director working preview")}function Bs(){if(!ut||G.rate!==0||ot?.open||!Je?.follow)return;let e=ut;ut=null,sn(e)}async function Fs(){nt=!1,ut=null,oe&&(oe.hidden=!0),fe.setGhost(st),S.setGhost(st),p||await G.load(u,le({fps:q(),duration:He(u),shape:me()}))}let on=[];function ja(e){let s=null;try{s=JSON.parse(e.data)}catch{}if(!(!s||s.project!==n)){if(We===null)return void(on=[...on,s].slice(-40));Ks(s)}}function Ra(){let e=on;on=[];for(let s of e)Ks(s)}function Ks(e){e.job===We&&(Wn=!0,Je.push(e),e.preview&&e.timeline&&(Ve=e,ut=e,Je.follow&&Bs()))}function Ia(){Je.finish(),nt=!1,Ve=ut=null,oe&&(oe.hidden=!0),fe.setGhost(st),S.setGhost(st)}let Hn=o.directorLoop===!0,pt=null,Ge={status:"none"},Gs=t("div",{class:"openings-host"});function an(){Hn&&J(Gs).append(zo({project:n,state:Ge,chosen:pt,onAsk:Na,onChoose:e=>(pt=e,an())}))}async function Na(){try{Ge={status:"making",job:(await Y("POST",`/projects/${n}/openings`,{brief:{format:Ee.value,...qe.value?{captions:qe.value}:{},...ze.value?{grade:ze.value}:{}}})).id,progress:0},pt=null}catch(e){Ge={status:"failed",error:e.message}}an()}async function Da(){if(Ge.status!=="making")return;let e=(await Y("GET","/jobs")).jobs.find(s=>s.id===Ge.job);e&&(e.status==="done"?Ge={status:"ready",job:e.id,openings:JSON.parse(e.output).openings}:["failed","canceled"].includes(e.status)?Ge={status:"failed",error:e.error??"the drafts stopped"}:Ge={...Ge,progress:e.progress??0},an())}an();let ft=c?Bo({select:ze,source:()=>{let e=r.find(s=>s.kind==="video"&&!s.offline&&s.facts?.duration);return e?{url:`/tiles/${e.media}?kind=thumbs`,cell:Do(e.facts.duration/7056e5)}:null}}):null;ft&&nn.addEventListener("change",()=>ft.mark());let at=(e,...s)=>t("section",{class:"brief-group","aria-label":e},t("h3",{class:"group-title"},e),...s),Ot=(...e)=>t("div",{class:"brief-pair"},...e),Ba=t("div",{class:"make"},at("Start from",t("label",{for:"make-template",class:"sr-only"},"Template"),nn),at("Shape",Ot(t("div",{},t("label",{for:"make-format",class:"sr-only"},"Format"),Ee),t("div",{},t("label",{for:"make-length",class:"sr-only"},"Length"),tt))),at("Look and sound",...ft?[ft.el]:[],Ot(t("div",{},t("label",{for:"make-captions",class:"sr-only"},"Captions"),qe),t("div",{},t("label",{for:"make-grade",class:"sr-only"},"Colour look"),ze)),Ot(t("div",{},t("label",{for:"make-music",class:"sr-only"},"Music"),$e),t("div",{},t("label",{for:"make-voice",class:"sr-only"},"Voice"),At))),at("Extras",t("div",{class:"extras toggles",role:"group","aria-label":"Extras"},Zt.el,Bn.el,en.el)),...y?[at("Brand",Ot(t("div",{},t("label",{for:"make-style",class:"sr-only"},"Style pack"),Xt),t("div",{},t("label",{for:"make-type",class:"sr-only"},"Type kit"),jn)),t("div",{class:"extras toggles",role:"group","aria-label":"Brand colours"},In.el,Nn.el),Ot(t("div",{},t("label",{for:"make-logo",class:"sr-only"},"Logo"),Et),t("div",{},t("label",{for:"make-bar",class:"sr-only"},"Bar across the film"),Rn)),...Is?[Is]:[])]:[],at("References",$s,Ln,t("div",{class:"row tight"},Mt,Gt,t("button",{type:"button",class:"btn","aria-label":"Add a reference",title:"Add a reference for what's chosen: a video, an image or music",onclick:()=>Mt.click()},"+ Reference"))),...Hn?[at("Openings",Gs)]:[],t("div",{class:"make-footer"},...c?[t("div",{class:"make-row"},Kn,_n)]:[Kn],Tt)),We=null;async function Fa(){if(!We)return;let e=(await Y("GET","/jobs")).jobs.find(d=>d.id===We);if(e&&ae.set(e.id,e),Gn(),!e||!["done","failed","canceled"].includes(e.status))return;if(We=null,Gn(),e.status!=="done")return D.textContent=e.error??"The reel stopped.";let s=JSON.parse(e.output);D.textContent=`${Aa[s.verdict]??s.verdict}. ${s.notes.join(" ")}`,s.file&&Pe.prepend(t("li",{class:"watch"},t("button",{type:"button",class:"btn primary",onclick:()=>rt("finish")},"Watch the final cut")));for(let d of[...s.changes].reverse())Pe.prepend(t("li",{},d))}let rn=t("button",{type:"button",class:"btn primary",onclick:()=>gt({type:"toggle"})},"Play"),Un=t("select",{class:"field small select","aria-label":"Preview shape",onchange:()=>G.setShape(me())},["project","16:9","9:16"].map(e=>t("option",{value:e},e==="project"?"Project shape":e))),ln=t("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>G.setZoom(Number(ln.value))}),Ws=t("input",{type:"checkbox",id:"guides",onchange:()=>G.setGuides(Ws.checked)}),cn=c?Ko():null,qn=t("div",{class:`monitor-frame${c?" live":""}`},B,oe),ht=.5,Ae=c?t("span",{class:"wipe-grip",role:"slider",tabindex:"0","aria-label":"Compare: raw footage on the left, your cut on the right","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":"50"}):null,Qe=c?t("div",{class:"wipe",hidden:!0},t("span",{class:"wipe-tag raw"},"Raw"),t("span",{class:"wipe-tag cut"},"Cut"),t("span",{class:"wipe-line"},Ae)):null,zn=c?t("button",{type:"button",class:"btn small compare","aria-pressed":"false",title:"Drag the handle across the picture: raw footage on one side, your cut on the other",onclick:()=>Vn(Qe.hidden)},"Compare raw"):null;function _s(){!Qe||Qe.hidden||(Object.assign(Qe.style,{left:`${B.offsetLeft}px`,top:`${B.offsetTop}px`,width:`${B.clientWidth}px`,height:`${B.clientHeight}px`}),Qe.querySelector(".wipe-line").style.left=`${(ht*100).toFixed(2)}%`,Ae.setAttribute("aria-valuenow",String(Math.round(ht*100))))}function Vn(e,s=ht){return ht=Math.min(1,Math.max(0,s)),Qe.hidden=!e,zn.setAttribute("aria-pressed",String(e)),_s(),G.setWipe(e?ht:null)}if(Qe){qn.append(Qe),new ResizeObserver(_s).observe(B);let e=s=>{let d=B.getBoundingClientRect();return Vn(!0,(s.clientX-d.left)/d.width)};Ae.addEventListener("pointerdown",s=>{s.preventDefault(),s.stopPropagation(),Ae.setPointerCapture(s.pointerId);let d=b=>e(b),k=()=>(Ae.removeEventListener("pointermove",d),Ae.removeEventListener("pointerup",k),Ae.removeEventListener("pointercancel",k));Ae.addEventListener("pointermove",d),Ae.addEventListener("pointerup",k),Ae.addEventListener("pointercancel",k)}),Ae.addEventListener("keydown",s=>{let d={ArrowLeft:-.05,ArrowRight:.05}[s.key],k=s.key==="Home"?0:s.key==="End"?1:d===void 0?null:ht+d;k!==null&&(s.preventDefault(),s.stopPropagation(),Vn(!0,k))})}let mt=v?Po({frame:qn,canvas:B,timeNow:()=>G.time,zoomNow:()=>Number(ln.value),usable:()=>p?"Drawing marks the cut: show the cut on the monitor first.":Un.value!=="project"?"Drawing marks the project's own frame: set the preview shape back to Project shape.":null,pause:()=>G.rate!==0&&gt({type:"toggle"}),onChange:()=>{}}):null;mt&&ln.addEventListener("input",()=>mt.redraw());function gt(e){if(!e)return;if(e.type==="mode")return rt(e.mode);if(e.type==="prompt")return we.focus();if(e.type==="mark")return T(),e.edge==="in"||xe===null?(xe=G.time,je=null):G.time>xe?je=G.time:(je=xe,xe=G.time),D.textContent=je===null?`Marked in at ${Re(xe)}. Play to the end of the stretch and press O.`:`Marked ${Re(xe)} to ${Re(je)}. Tell Kriya what to do with it.`,zt();if(e.type==="undo")return Y("PATCH",`/projects/${n}`,{undo:!0}).then(R);if(e.type==="redo")return D.textContent="Redo isn't here yet.";if(e.type==="split"){let b=vt(u,G.time);return b&&K([{op:"split",clip:b.clip,at:lt(b,G.time)}])}if(e.type==="delete")return fe.selected&&K([{op:"ripple_delete",clip:fe.selected}]);let s={fps:p?r.find(b=>b.id===p).facts.fps??q():q(),duration:z()},d={t:G.time,rate:G.rate},k=ro(d,e,s);k.rate!==d.rate&&G.setRate(k.rate),(k.t!==d.t||e.type==="seek")&&G.seek(k.t)}function rt(e){g=e,Se("kriya-edit-mode",g),yt.dataset.mode=g;for(let s of Hs.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.mode===g));fe.draw(),S.draw(),g==="finish"&&F.refresh().catch(()=>{})}let Hs=t("div",{class:"modes",role:"group","aria-label":"Mode"},na.map((e,s)=>t("button",{type:"button",class:"btn",dataset:{mode:e},"aria-pressed":"false","aria-keyshortcuts":String(s+1),onclick:()=>rt(e)},e[0].toUpperCase()+e.slice(1)))),bt={min:300,step:32},Jn=()=>Math.max(bt.min,Math.min(960,Math.round(window.innerWidth*.62))),Qn=()=>document.querySelector(".area-kriya")?.getBoundingClientRect().width??0;function dn(e){if(e===null)yt.style.removeProperty("--side"),Se("kriya-side-width","");else{let s=Math.round(Math.min(Jn(),Math.max(bt.min,e)));yt.style.setProperty("--side",`${s}px`),Se("kriya-side-width",String(s))}Te.setAttribute("aria-valuenow",String(Math.round(Qn()))),fe.draw(),S.draw()}let Te=t("div",{class:"side-handle",role:"separator",tabindex:"0","aria-orientation":"vertical","aria-label":"Resize the Kriya panel","aria-valuemin":String(bt.min),title:"Drag to resize. Double-click to fit the window.",onpointerdown:e=>{e.preventDefault(),Te.setPointerCapture(e.pointerId);let s=document.querySelector(".area-kriya").getBoundingClientRect().right,d=b=>dn(s-b.clientX),k=()=>(Te.removeEventListener("pointermove",d),Te.removeEventListener("pointerup",k),Te.removeEventListener("pointercancel",k));Te.addEventListener("pointermove",d),Te.addEventListener("pointerup",k),Te.addEventListener("pointercancel",k)},ondblclick:()=>dn(null),onkeydown:e=>{let s={ArrowLeft:bt.step,ArrowRight:-bt.step}[e.key];s?(e.preventDefault(),e.stopPropagation(),dn(Qn()+s)):e.key==="Home"&&(e.preventDefault(),dn(null))}}),Us=t("div",{class:"brief-panel"},Ba),Ka=["A 30 second reel from this","Cut the false starts","A punchier start","A name strap with my name and role"],qs=t("div",{class:"chat-empty"},t("p",{class:"empty-title"},"Tell Kriya what you want"),t("p",{class:"note small"},'A change to this cut, or a plan for the whole film. Times like 0:05, a marked stretch or selected words are "this".'),t("div",{class:"suggestions",role:"group","aria-label":"Ideas to start from"},Ka.map(e=>t("button",{type:"button",class:"btn suggestion",onclick:()=>(we.value=e,we.focus())},e)))),zs=t("div",{class:"chat-panel"},t("div",{class:"chat-scroll"},qs,qt),t("div",{class:"composer"},Pn,Es,Ct?.el,Ca,t("p",{class:"note small hint"},"Enter sends. Shift+Enter is a new line. Mark a stretch with I and O."))),Vs=t("div",{class:"activity-panel"},t("p",{class:"note small activity-empty"},"Nothing yet. Changes you accept and the cuts Kriya makes are listed here, newest first."),Pe),Ie=ls([{key:"brief",label:"Brief",panel:Us},{key:"chat",label:"Chat",panel:zs},{key:"activity",label:"Activity",panel:Vs,count:()=>Pe.children.length||null}],{label:"Kriya",selected:["brief","chat","activity"].includes(Se("kriya-tab"))?Se("kriya-tab"):"chat",className:"inspector-tabs",onSelect:e=>Se("kriya-tab",e)});Jt=e=>Ie.select(e);let Yn=0,Js=()=>qs.hidden=qt.children.length>0;new MutationObserver(e=>{Js();let s=e.flatMap(d=>[...d.addedNodes]).filter(d=>d.classList?.contains("kriya")).length;Ie.selected()==="chat"?Yn=0:s&&Ie.mark("chat",Yn+=s)}).observe(qt,{childList:!0}),Js();let Xn=Pe.children.length;new MutationObserver(()=>{Ie.refresh();let e=Pe.children.length-Xn;Ie.selected()==="activity"?Xn=Pe.children.length:e>0&&Ie.mark("activity",e)}).observe(Pe,{childList:!0}),Ie.strip.addEventListener("click",()=>{Ie.selected()==="chat"&&(Yn=0),Ie.selected()==="activity"&&(Xn=Pe.children.length)});let yt=t("div",{class:"workspace"},sa(t("span",{class:"project-name"},a.name),Hs),t("div",{class:"banner"},D,On,Tn),t("div",{class:"grid"},t("div",{class:"area-bin"},la,t("section",{class:"panel refs","aria-label":"Style references"},t("h2",{},"References"),_t,Mn,t("button",{type:"button",class:"btn wide",onclick:()=>Mt.click()},"Add a reference\u2026"))),t("section",{class:"area-monitor panel","aria-label":"Monitor"},qn,...ot?[ot.el]:[],t("div",{class:"transport"},t("div",{class:"tgroup tplay"},rn,te,...de?[de]:[],V,...cn?[t("button",{type:"button",class:"btn keys-open","aria-label":"Keyboard shortcuts","aria-keyshortcuts":"?",title:"Keyboard shortcuts (?)",onclick:()=>cn.open()},"?")]:[]),t("div",{class:"tgroup"},Ea),t("div",{class:"tgroup tview"},Un,...zn?[zn]:[],t("label",{class:"inline"},Ws," Safe zones"),t("label",{class:"inline"},"Zoom ",ln))),...mt?[mt.tools]:[]),t("aside",{class:"area-kriya panel inspector","aria-label":"Kriya"},Te,Ie.strip,Us,zs,Vs),t("section",{class:"area-transcript panel","aria-label":"Transcript"},t("h2",{},"Transcript"),t("p",{class:"note small hint"},"Click a word to jump there. Double-click (or F2) to fix a misheard word."),Q),Ls,t("div",{class:"area-strip"},re),t("section",{class:"area-timeline panel","aria-label":"Timeline"},ne),t("div",{class:"area-finish"},pe),N));h&&yt.classList.add("has-story"),J(ps).append(yt);let Qs=Number(Se("kriya-side-width"));Qs>=bt.min&&yt.style.setProperty("--side",`${Math.min(Jn(),Qs)}px`),rt(g),Te.setAttribute("aria-valuemax",String(Jn())),Te.setAttribute("aria-valuenow",String(Math.round(Qn()))),window.onkeydown=e=>{let s=e.target.closest?.("input, select, textarea");if(s&&e.key!=="Escape")return;if(e.key==="Escape")return s?document.activeElement?.blur():(Z.clear(),fe.select(null),xe=je=null,zt());if(cn&&e.key==="?"&&!e.metaKey&&!e.ctrlKey)return e.preventDefault(),cn.open();let d=ao(e.key,{shift:e.shiftKey,mod:e.metaKey||e.ctrlKey});d&&(d.type==="toggle"&&e.target.closest?.("button")&&e.target!==rn||(e.preventDefault(),gt(d)))},setInterval(()=>g==="finish"&&F.scopes(),250);let Zn=new EventSource("/events");Zn.addEventListener("job",e=>{let s=null;try{s=JSON.parse(e.data)}catch{}s?.id&&ae.set(s.id,s),c&&s?.id&&s.id===We&&!["pending","running"].includes(s.status)&&Ia(),ua(s),g==="finish"&&F.refresh().catch(()=>{}),Fa().catch(()=>{}),Da().catch(()=>{}),s&&["pending","running"].includes(s.status)?xn():R().catch(()=>{})}),c&&Zn.addEventListener("live",ja),Zn.addEventListener("setup",e=>{try{Ht({...Ke??{},setup:JSON.parse(e.data)})}catch{}Ke?.setup?.finished&&Y("GET","/runtime").then(Ht).catch(()=>{})}),Y("GET","/runtime").then(Ht).catch(()=>{}),await R(),window.__studio={monitor:G,act:gt,reload:R,setMode:rt,get pieces(){return u},...c?{director:{get states(){return Je.states},get showing(){return nt},get replay(){return{open:ot.open,at:ot.at}}}}:{}}}function aa(){let n=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);n?vr(n[1]):oa()}window.addEventListener("hashchange",aa);aa();