@kriya-ai/harness 0.2.3 → 0.2.5

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.
Files changed (41) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +194 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +19 -1
  5. package/src/edit/core/layout.js +24 -1
  6. package/src/edit/core/ops.js +9 -3
  7. package/src/edit/core/plan.js +36 -5
  8. package/src/edit/core/solver.js +39 -3
  9. package/src/edit/core/transitions.js +17 -0
  10. package/src/edit/director/beats.js +335 -0
  11. package/src/edit/director/continuity.js +129 -0
  12. package/src/edit/director/graphics.js +152 -0
  13. package/src/edit/director/lookups.js +133 -0
  14. package/src/edit/director/plan.js +118 -6
  15. package/src/edit/director/playbooks.js +131 -0
  16. package/src/edit/director/revise.js +49 -5
  17. package/src/edit/engine/captions.js +32 -0
  18. package/src/edit/engine/found-media.js +64 -0
  19. package/src/edit/engine/graphics.js +178 -0
  20. package/src/edit/engine/motion.js +24 -3
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/gates/copy.js +25 -5
  23. package/src/edit/gates/index.js +16 -5
  24. package/src/edit/gates/picture.js +11 -3
  25. package/src/edit/gates/text.js +20 -4
  26. package/src/edit/graph/scheduler.js +1 -1
  27. package/src/edit/host/deliver.js +8 -1
  28. package/src/edit/host/main.js +8 -5
  29. package/src/edit/host/paths.js +15 -2
  30. package/src/edit/host/projects.js +229 -12
  31. package/src/edit/host/server.js +72 -3
  32. package/src/edit/index/views.js +9 -0
  33. package/src/edit/loop/make.js +25 -6
  34. package/src/edit/recipes/graphic-clips.js +57 -0
  35. package/src/edit/recipes/montage.js +74 -0
  36. package/src/edit/recipes/programme.js +24 -0
  37. package/src/edit/recipes/reel.js +65 -14
  38. package/src/edit/recipes/scene-clips.js +127 -0
  39. package/src/edit/runtime/fetch.js +33 -0
  40. package/studio/dist/studio.css +15 -0
  41. package/studio/dist/studio.js +3 -3
@@ -1,5 +1,5 @@
1
- function t(a,d={},...u){let f=document.createElement(a);for(let[p,o]of Object.entries(d??{}))o==null||o===!1||(p.startsWith("on")?f.addEventListener(p.slice(2),o):p==="class"?f.className=o:p==="dataset"?Object.assign(f.dataset,o):o===!0?f.setAttribute(p,""):f.setAttribute(p,String(o)));for(let p of u.flat())p!=null&&p!==!1&&f.append(p instanceof Node?p:String(p));return f}var W=a=>(a.replaceChildren(),a);async function I(a,d,u){let f=await fetch(d,{method:a,headers:u===void 0?{}:{"content-type":"application/json"},body:u===void 0?void 0:JSON.stringify(u),credentials:"same-origin"}),p=await f.json().catch(()=>({}));if(!f.ok){let o=new Error(p.message??`The Edit Host answered ${f.status}.`);throw o.status=f.status,o.value=p,o}return p}var pn=(a,d,u)=>.2126*a+.7152*d+.0722*u;function fn(a,d=128){let u=new Uint32Array(256),f=Array.from({length:d},()=>new Uint32Array(64)),{data:p,width:o,height:M}=a,g=Math.max(1,Math.floor(o*M/6e4));for(let i=0,$=0;$<o*M;$+=g,i=$*4){let k=Math.min(255,Math.round(pn(p[i],p[i+1],p[i+2])));u[k]++,f[Math.min(d-1,Math.floor($%o/o*d))][k>>2]++}return{histogram:u,waveform:f}}var hn={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you: a check failed",not_checked:"Not checked"};function It({root:a,finalRoot:d,pixels:u,project:f,onAdjust:p=()=>{}}){let o=t("video",{class:"final-film",controls:!0,preload:"metadata",playsinline:!0,"aria-label":"The final cut"}),M=t("p",{class:"note",role:"status"}),g=t("select",{id:"final-pick",class:"field select","aria-label":"Which film",onchange:()=>x()}),i=t("a",{class:"btn primary",href:"#",download:"",hidden:!0},"Download"),$=[],k=y=>`/projects/${f().id}/renders/${y.job}`,l=y=>y?new Date(y).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";function x(){let y=$.find(r=>String(r.job)===g.value)??$[0];if(!y){o.removeAttribute("src"),o.hidden=!0,i.hidden=!0,g.hidden=!0,M.textContent="No film yet. Render a draft and the finished cut plays here, captions, look, music and sound included.";return}o.hidden=!1,g.hidden=$.length<2;let v=k(y);o.getAttribute("src")!==v&&(o.src=v),i.hidden=!1,i.href=`${v}?download=1`,i.setAttribute("download",y.name);let T=y.current?"This is your edit as it is now.":"Made before your latest changes: render a draft to see them.";M.textContent=`${T}${y.verdict?` ${hn[y.verdict]??y.verdict}.`:""}`,M.classList.toggle("stale",!y.current)}let A=0,L=0;async function S(){let y=++A,v=(await I("GET",`/projects/${f().id}/renders`)).renders;if(y!==A)return;let T=g.value;$=v;let r=$[0]?.job??0;W(g).append(...$.map(m=>t("option",{value:String(m.job)},`${m.quality==="draft"?"Draft":"Master"} \xB7 ${l(m.at)}${m.current?" \xB7 current":""} \xB7 ${m.name}`))),g.value=String(r>L||!$.some(m=>String(m.job)===T)?r:T),L=Math.max(L,r),x()}d.append(t("section",{class:"panel final","aria-label":"Final cut"},t("h2",{},"Final cut"),o,M,t("div",{class:"row"},g,i,t("button",{type:"button",class:"btn",onclick:()=>J("draft")},"Render again"),t("button",{type:"button",class:"btn",onclick:p},"Adjust in Edit"))));let b=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),N=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),D=t("ul",{class:"jobs","aria-live":"polite"}),_=t("p",{class:"note",role:"status"}),J=async y=>{_.textContent="";try{await I("POST","/jobs",{project:f().id,quality:y}),K()}catch(v){_.textContent=v.message}},Y=t("p",{class:"note",role:"status"}),z=t("ul",{class:"jobs","aria-label":"Handoff files"}),w=async()=>{Y.textContent="",W(z);try{let y=await I("POST",`/projects/${f().id}/export/handoff`),v=y.chapters.length,T=v?`, ${v} chapter${v===1?"":"s"}`:"";Y.textContent=`Written to ${y.folder}, with ${y.media} media file${y.media===1?"":"s"} linked${T}.`;for(let r of y.files)z.append(t("li",{},t("span",{class:"file"},r)));for(let r of y.omitted)z.append(t("li",{},t("span",{class:"label-mono"},r.format),` ${r.reason}`))}catch(y){Y.textContent=y.message}};a.append(t("section",{class:"panel scopes","aria-label":"Scopes"},t("h2",{},"Scopes"),t("div",{class:"scope-row"},t("figure",{},b,t("figcaption",{},"Histogram")),t("figure",{},N,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:()=>J("draft")},"Render a draft"),t("button",{type:"button",class:"btn primary",onclick:()=>J("master")},"Render the master")),t("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),_,D),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:w},"Export for another editor")),Y,z));function C(y,v){let T=y.getContext("2d");T.clearRect(0,0,y.width,y.height),T.fillStyle=getComputedStyle(a).getPropertyValue("--scope").trim()||"#6cc0b8",v(T)}function B(){let y=u();if(!y)return;let{histogram:v,waveform:T}=fn(y),r=Math.max(1,...v);C(b,m=>v.forEach((j,P)=>m.fillRect(P,100-j/r*100,1,j/r*100))),C(N,m=>T.forEach((j,P)=>j.forEach((q,R)=>{q&&(m.globalAlpha=Math.min(1,.15+q/200),m.fillRect(P*2,100-R/64*100-2,2,2))})))}async function K(){S().catch(v=>M.textContent=v.message);let{jobs:y}=await I("GET","/jobs");W(D);for(let v of y.filter(T=>T.project===f().id&&T.kind==="render").reverse().slice(0,8)){let T=v.output?v.output.split(/[\\/]/).at(-1):null;D.append(t("li",{},t("span",{class:"label-mono"},v.status),` ${v.progress}%`,T?t("span",{class:"file"},` ${T}`):null,v.error?t("span",{class:"error"},` ${v.error}`):null))}}return{scopes:B,refresh:K}}var Nt=a=>typeof a=="number"?{n:a,d:1}:a??{n:1,d:1},Ft=a=>[...a?.picture??[]].sort((d,u)=>d.at-u.at),ht=a=>[{clip:null,asset:a.id,in:0,out:a.facts.duration,at:0,end:a.facts.duration,speed:{n:1,d:1}}],ve=(a,d)=>a.find(u=>d>=u.at&&d<u.end)??(a.length&&d>=a.at(-1).end?a.at(-1):null);function he(a,d){if(a.hold)return a.in;let{n:u,d:f}=Nt(a.speed);return Math.min(a.out,a.in+Math.round((d-a.at)*u/f))}function Ve(a,d,u){for(let f of a){if(f.asset!==d||f.hold||u<f.in||u>=f.out)continue;let{n:p,d:o}=Nt(f.speed);return f.at+Math.round((u-f.in)*o/p)}return null}var Ie=a=>a.length?Math.max(...a.map(d=>d.end)):0;function Dt(a,d){let u=[];for(let f of d){let p=Ve(a,f.asset,f.start);p!==null&&p>0&&u.push({id:f.id,at:p})}return u}var re=a=>7056e5*a.d/a.n,Kt=(a,d)=>Math.floor(a/re(d)+1e-9),ze=(a,d)=>Math.round(Kt(a,d)*re(d));function xe(a,d){let u=Math.max(0,a)/7056e5,f=Math.floor(u/60),p=Math.floor(u%60),o=Kt(Math.max(0,a)-Math.floor(u)*7056e5,d);return`${String(f).padStart(2,"0")}:${String(p).padStart(2,"0")}.${String(o).padStart(2,"0")}`}function Bt(a,{shift:d=!1,mod:u=!1}={}){if(u)return a==="z"||a==="Z"?{type:d?"redo":"undo"}:null;switch(a){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:d?null:1,seconds:d?1:null};case"ArrowLeft":return{type:"step",frames:d?null:-1,seconds:d?-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 Wt(a,d,{fps:u,duration:f}){let p=Math.max(0,f-re(u)),o=M=>Math.min(Math.max(0,Math.round(M)),p);switch(d.type){case"toggle":return{...a,rate:a.rate===0?1:0};case"rate":return{...a,rate:d.rate};case"faster":return{...a,rate:a.rate<=0?1:2};case"reverse":return{...a,rate:a.rate>=0?-1:-2};case"step":{let M=d.frames!==null?d.frames*re(u):d.seconds*7056e5;return{rate:0,t:o(ze(a.t,u)+M)}}case"seek":return{...a,t:o(d.t)};case"tick":{let M=o(d.t);return{t:M,rate:M===0&&a.rate<0||M===p&&a.rate>0?0:a.rate}}default:return a}}var mn=1280;function qt({canvas:a,urlOf:d,assetOf:u,onTime:f,onRate:p}){let o=a.getContext("2d",{willReadFrequently:!0}),M=new Map,g=[],i={n:30,d:1},$=0,k=0,l=0,x={width:1920,height:1080},A=1,L=!1,S=0,b=null;function N(r){let m=g[r],j=`${m.asset}:${r%2}`;if(!M.has(j)){let P=document.createElement("video");Object.assign(P,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:d(m.asset)}),M.set(j,P)}return M.get(j)}function D(r,m){let j=u(r.asset)?.facts?.fps??i;return(m+re(j)/2)/7056e5}function _(){let r=Math.min(1,mn/Math.max(x.width,x.height)),m=Math.round(x.width*r),j=Math.round(x.height*r);(a.width!==m||a.height!==j)&&Object.assign(a,{width:m,height:j})}function J(r,m,j){_();let{width:P,height:q}=a;if(o.fillStyle="#000",o.fillRect(0,0,P,q),r?.videoWidth){let R=Math.max(P/r.videoWidth,q/r.videoHeight)*A,G=r.videoWidth*R,te=r.videoHeight*R;o.drawImage(r,(P-G)/2,(q-te)/2,G,te),b={asset:m.asset,source:j}}if(L){o.strokeStyle="rgb(255 255 255 / 0.55)",o.setLineDash([6,6]),o.lineWidth=1;for(let R of[.05,.1])o.strokeRect(P*R,q*R,P*(1-2*R),q*(1-2*R));o.setLineDash([])}}let Y=()=>{_(),o.fillStyle="#000",o.fillRect(0,0,a.width,a.height),b=null},z=0,w=Promise.resolve();function C(r){let m=g.indexOf(ve(g,r));if(m<0)return Promise.resolve(Y());let j=g[m],P=he(j,r),q=N(m),R=D(j,P),G=++z,te=new Promise(Q=>{let ie=()=>{z===G&&J(q,j,P),Q()};if(q.readyState>=2&&Math.abs(q.currentTime-R)<1e-4)return ie();q.addEventListener("seeked",ie,{once:!0}),q.currentTime=R});if(w=te,g[m+1]){let Q=N(m+1);Q!==q&&(Q.currentTime=D(g[m+1],g[m+1].in))}return te}function B(){for(let r of M.values())r.pause(),r.muted=!0}function K(r,m=!0){k=Math.min(Math.max(0,r),Math.max(0,$-re(i))),m&&f(k)}function y(r){let m=g.indexOf(ve(g,k));if(m<0)return T(0);let j=(P,q)=>{let R=g[P],G=N(P);G.currentTime=D(R,he(R,q)),G.playbackRate=l,G.muted=!1;let{n:te,d:Q}=typeof R.speed=="object"?R.speed:{n:1,d:1},ie=($e,Se)=>{if(r!==S)return;let Ce=R.at+Math.round((Math.round(Se.mediaTime*7056e5)-R.in)*Q/te);if(Ce>=R.end-re(i)/2||G.ended)return G.pause(),G.muted=!0,g[P+1]?(m=P+1,K(g[m].at),j(m,g[m].at)):T(0);J(G,R,he(R,Ce)),K(Ce),G.requestVideoFrameCallback(ie)};G.requestVideoFrameCallback(ie),G.play().catch(()=>r===S&&T(0))};j(m,k)}function v(r){let m=performance.now(),j=async P=>{if(r===S){if(K(k-(P-m)/1e3*7056e5*Math.abs(l)),m=P,await C(k),k===0)return T(0);requestAnimationFrame(j)}};requestAnimationFrame(j)}function T(r){if(r===l&&r!==0)return;l=r;let m=++S;B(),p(l),l>0?y(m):l<0?v(m):(K(ze(k,i)),C(k))}return{load(r,{fps:m,duration:j,shape:P}){return g=r,i=m,$=j,P&&(x=P),++S,B(),l=0,p(0),K(Math.min(k,Math.max(0,$-re(i)))),C(k)},seek(r){return l!==0&&T(0),K(ze(r,i)),C(k)},setRate:T,get time(){return k},get rate(){return l},get shown(){return b},get settled(){return w},setShape(r){return x=r,C(k)},setZoom(r){return A=r,C(k)},setGuides(r){return L=r,C(k)},pixels:()=>a.width?o.getImageData(0,0,a.width,a.height):null}}var Gt=[{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"}],de=44,_t=6;function gt({root:a,compact:d=!1,onSeek:u,onSelect:f=()=>{}}){let p=d?Gt.slice(0,1):Gt,o=t("canvas",{class:"lanes","aria-hidden":"true"}),M=d?null:t("div",{class:"lane-labels","aria-hidden":"true"},p.map(w=>t("div",{class:"lane-label"},w.label))),g=t("ul",{class:"clip-list","aria-label":d?"Story":"Clips on the timeline"});a.append(...[M,t("div",{class:"lanes-wrap"},o),g].filter(Boolean));let i=o.getContext("2d"),$={picture:[],overlays:[],audio:[],captions:[]},k=0,l={n:30,d:1},x=0,A=[],L=[],S=new Map,b=null,N=null,D=w=>getComputedStyle(a).getPropertyValue(w).trim()||"#888";function _(){let w=Math.max(1,o.clientWidth),C=p.length*(de+_t),B=window.devicePixelRatio||1;(o.width!==Math.round(w*B)||o.height!==Math.round(C*B))&&(o.width=Math.round(w*B),o.height=Math.round(C*B),o.style.height=`${C}px`),i.setTransform(B,0,0,B,0,0),i.clearRect(0,0,w,C);let K=y=>k?y/k*w:0;p.forEach((y,v)=>{let T=v*(de+_t);i.fillStyle=D("--lane"),i.fillRect(0,T,w,de);for(let r of $[y.key]??[]){let m=K(r.at),j=Math.max(2,K(r.end)-m);i.fillStyle=D(y.colour),i.fillRect(m,T+2,j-1,de-4),r.clip&&r.clip===b&&(i.strokeStyle=D("--focus"),i.lineWidth=2,i.strokeRect(m+1,T+3,j-3,de-6));let P=y.key==="audio"||d&&y.key==="picture"?S.get(r.asset):null;if(P&&r.in!==void 0){i.fillStyle=D("--wave");let q=r.out-r.in;for(let R=0;R<j;R++){let G=(r.in+q*R/j)/7056e5,Q=(P.peaks[Math.floor(G*P.perSecond)]??0)*(de-8);i.fillRect(m+R,T+de/2-Q/2,1,Math.max(1,Q))}}}if(y.key==="picture"&&N){i.strokeStyle=D("--ghost"),i.setLineDash([5,4]),i.lineWidth=2;let r=Math.max(k,N.duration)||1;for(let m of N.picture)i.strokeRect(m.at/r*w+1,T+6,Math.max(2,(m.end-m.at)/r*w-2),de-12);i.setLineDash([])}if(y.key==="picture"){i.fillStyle=D("--shot");for(let r of A)i.fillRect(K(r.at)-.5,T,1,8)}}),i.fillStyle=D("--playhead");for(let y of L)i.fillRect(K(y.at)-1,0,3,8);i.fillStyle=D("--playhead"),i.fillRect(K(x)-1,0,2,C)}let J=!1,Y=w=>{let C=o.getBoundingClientRect();u(Math.round(Math.min(1,Math.max(0,(w.clientX-C.left)/C.width))*k))};o.addEventListener("pointerdown",w=>{J=!0,o.setPointerCapture(w.pointerId),Y(w)}),o.addEventListener("pointermove",w=>J&&Y(w)),o.addEventListener("pointerup",()=>J=!1),new ResizeObserver(_).observe(o);function z(w){b=w;for(let C of g.querySelectorAll("button"))C.setAttribute("aria-pressed",String(C.dataset.clip===w));f(w),_()}return{load(w,{duration:C,fps:B,marks:K=[],pins:y=[]}){L=y,$=w,k=C,l=B,A=K,b&&!$.picture.some(v=>v.clip===b)&&(b=null),W(g);for(let v of $.picture.filter((T,r,m)=>m.findIndex(j=>j.clip===T.clip)===r)){let T=t("button",{type:"button","aria-pressed":String(v.clip===b),dataset:{clip:v.clip},onclick:()=>(z(v.clip),u(v.at))},`Clip ${v.clip}, ${xe(v.at,l)} to ${xe(v.end,l)}`);g.append(t("li",{},T))}_()},setPeaks(w,C){S.set(w,C),_()},setGhost(w){N=w,_()},setTime(w){x=w,_()},select:z,get selected(){return b},draw:_}}var Ht=new Set(["filler","stutter","restart"]);function Ut({root:a,onSeek:d,onCut:u,onFix:f=async()=>{}}){let p=[],o=new Map,M=null,g=[],i=null,$=()=>{for(let l of a.querySelectorAll(".word[aria-pressed='true']"))l.setAttribute("aria-pressed","false");for(let l of g)a.querySelector(`[data-word="${CSS.escape(l)}"]`)?.setAttribute("aria-pressed","true")};a.addEventListener("click",l=>{let x=l.target.closest(".word");if(!x)return;let A=o.get(x.dataset.word);if(l.shiftKey&&M){let[L,S]=[p.indexOf(M),p.indexOf(A)].sort((b,N)=>b-N);g=p.slice(L,S+1).filter(b=>b.asset===A.asset).map(b=>b.id)}else M=A,g=[A.id],d(A);$()});function k(l){let x=o.get(l.dataset.word);if(!x)return;let A=t("input",{class:"word-edit",value:x.text,size:String(Math.max(4,x.text.length+2)),maxlength:"60","aria-label":`Fix the word "${x.text}"`});l.replaceWith(A),A.focus(),A.select();let L=!1,S=async b=>{if(L)return;L=!0;let N=A.value.trim();A.replaceWith(l),b&&N&&N!==x.text?await f(x,N):l.focus()};A.addEventListener("keydown",b=>{b.stopPropagation(),b.key==="Enter"?(b.preventDefault(),S(!0)):b.key==="Escape"&&(b.preventDefault(),S(!1))}),A.addEventListener("blur",()=>S(!0))}return a.addEventListener("dblclick",l=>{let x=l.target.closest(".word");x&&k(x)}),a.addEventListener("keydown",l=>{if(l.key==="F2"&&l.target.closest(".word"))return l.preventDefault(),l.stopPropagation(),k(l.target.closest(".word"));(l.key==="Backspace"||l.key==="Delete")&&g.length&&(l.preventDefault(),l.stopPropagation(),u(o.get(g[0]),o.get(g.at(-1))))}),{load({words:l=[],sentences:x=[],takes:A=[]}){p=l,o=new Map(l.map(b=>[b.id,b])),g=g.filter(b=>o.has(b));let L=new Map(A.map(b=>[b.sentence,b]));if(W(a),!l.length){a.append(t("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let S=x.length?x:[...new Set(l.map(b=>b.asset))].map(b=>{let N=l.filter(D=>D.asset===b);return{id:null,asset:b,firstWord:N[0].id,lastWord:N.at(-1).id,score:1}});for(let b of S){let N=L.get(b.id),D=N&&N.rank>1||b.score===0,_=Number(b.firstWord.split(":w")[1]),J=Number(b.lastWord.split(":w")[1]),Y=t("p",{class:`sentence${D?" lost":""}`,dataset:b.id?{sentence:b.id}:{}});N&&Y.append(t("span",{class:"tag"},N.rank===1?"best take":`take ${N.rank}`));for(let z=_;z<=J;z++){let w=o.get(`${b.asset}:w${z}`);if(!w)continue;let C=D||w.flags.some(v=>Ht.has(v)),B=C?`${w.text} (${D?"retake":w.flags.filter(v=>Ht.has(v)).join(", ")})`:null,K=typeof w.heard=="string",y=t("button",{type:"button",class:`word${C?" struck":""}${!K&&w.flags.includes("low_confidence")?" unsure":""}${K?" fixed":""}`,"aria-pressed":"false","aria-label":B??(K?`${w.text} (fixed; heard as ${w.heard})`:null),title:K?`Heard as "${w.heard}". Double-click to change.`:"Double-click to fix this word",dataset:{word:w.id}});y.textContent=w.text,Y.append(y," ")}a.append(Y)}$()},playing(l){l!==i&&(a.querySelector(".word.now")?.classList.remove("now"),i=l,l&&a.querySelector(`[data-word="${CSS.escape(l)}"]`)?.classList.add("now"))},words:()=>p,selection:()=>g.length?[g[0],g.at(-1)]:null,clear(){g=[],M=null,$()}}}var yt=document.getElementById("app"),Vt=["direct","edit","finish"],ae=(a,d)=>{try{if(d===void 0)return localStorage.getItem(a);localStorage.setItem(a,d)}catch{return null}},gn=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function zt(...a){let d=gn();return t("header",{class:"bar"},d?t("a",{class:"btn ghost",href:d},"\u2190 Kriya Harness"):t("span",{class:"brand"},"Kriya"),t("span",{class:"title"},"Editing Studio"),...a)}function Ye(a){W(yt).append(t("main",{class:"center"},t("h1",{},"Open the Studio from Kriya"),t("p",{},a??"Click Editing Studio in Kriya Harness, or run kriya edit and open its link.")))}function yn(a){return new Promise(d=>{let u=t("ul",{class:"folders","aria-label":"Folders"}),f=t("p",{class:"label-mono where"}),p=t("p",{class:"note",role:"status"}),o=t("input",{class:"field",placeholder:"New folder name","aria-label":"New folder name",maxlength:"80"}),M=null,g=k=>{$.close(),$.remove(),d(k)};async function i(k){try{let l=await I("GET",`/browse${k?`?root=${encodeURIComponent(k)}`:""}`);M=l.root,f.textContent=l.root,W(u),l.parent&&u.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>i(l.parent)},"\u2191 Up")));let x=l.entries.filter(A=>A.kind==="folder");for(let A of x)u.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>i(`${l.root}/${A.name}`)},`\u{1F4C1} ${A.name}`)));x.length||u.append(t("li",{class:"note"},"No folders here.")),p.textContent=""}catch(l){p.textContent=l.message}}let $=t("dialog",{class:"picker","aria-label":"Choose a folder"},t("h2",{},"Choose a folder"),f,u,t("form",{class:"row tight",onsubmit:async k=>{k.preventDefault();try{let{folder:l}=await I("POST","/browse/folder",{parent:M,name:o.value});o.value="",await i(l)}catch(l){p.textContent=l.message}}},o,t("button",{type:"submit",class:"btn"},"New folder")),p,t("div",{class:"row end"},t("button",{type:"button",class:"btn",onclick:()=>g(null)},"Cancel"),t("button",{type:"button",class:"btn primary",onclick:()=>g(M)},"Use this folder")));$.addEventListener("cancel",k=>(k.preventDefault(),g(null))),document.body.append($),$.showModal(),i(a)})}async function Yt(){let a;try{({projects:a}=await I("GET","/projects"))}catch(i){return i.status===401?Ye():Ye(i.message)}let d=t("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),u=t("input",{id:"new-folder",class:"field",required:!0,readonly:!0,placeholder:"Choose a folder\u2026"}),f=t("button",{type:"button",class:"btn",onclick:()=>yn(u.value||null).then(i=>i&&(u.value=i,p.textContent=""))},"Choose\u2026"),p=t("p",{class:"note",role:"status"}),o=t("form",{class:"panel new",onsubmit:async i=>{if(i.preventDefault(),!u.value)return p.textContent="Choose a folder for the project first.";try{let{id:$}=await I("POST","/projects",{name:d.value.trim(),folder:u.value.trim()});location.hash=`#/p/${$}`}catch($){p.textContent=$.message}}},t("h2",{},"New project"),t("label",{for:"new-name"},"Name"),d,t("label",{for:"new-folder"},"Folder for the project (its footage stays where it is)"),t("div",{class:"row tight"},u,f),t("button",{class:"btn primary",type:"submit"},"Create"),p),M=t("section",{class:"panel taste","aria-label":"Your taste"}),g=async i=>{let{proposed:$,confirmed:k}=i??await I("GET","/taste"),l=(x,A)=>async()=>g(await I("POST",`/taste/${encodeURIComponent(x)}/${A}`));W(M).append(t("h2",{},"Your taste"),...$.length||k.length?[]:[t("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...$.map(x=>t("div",{class:"taste-row"},t("p",{},x.sentence),t("button",{type:"button",class:"btn primary",onclick:l(x.key,"confirm")},"Use it"),t("button",{type:"button",class:"btn",onclick:l(x.key,"dismiss")},"No"))),...k.map(x=>t("div",{class:"taste-row"},t("p",{},x.shown),t("button",{type:"button",class:"btn","aria-label":`Remove the rule ${x.shown}`,onclick:l(x.key,"remove")},"Remove"))))};g().catch(()=>{}),W(yt).append(zt(),t("main",{class:"home"},t("h1",{},"What are we making?"),t("section",{class:"panel"},t("h2",{},"Projects"),a.length?t("ul",{class:"projects"},a.map(i=>t("li",{class:"project-row"},t("a",{class:"btn open",href:`#/p/${i.id}`},i.name),t("button",{type:"button",class:"btn ghost danger","aria-label":`Delete the project ${i.name}`,onclick:async()=>{if(confirm(`Delete "${i.name}" from the Studio?
1
+ function t(n,p={},...h){let m=document.createElement(n);for(let[f,r]of Object.entries(p??{}))r==null||r===!1||(f.startsWith("on")?m.addEventListener(f.slice(2),r):f==="class"?m.className=r:f==="dataset"?Object.assign(m.dataset,r):r===!0?m.setAttribute(f,""):m.setAttribute(f,String(r)));for(let f of h.flat())f!=null&&f!==!1&&m.append(f instanceof Node?f:String(f));return m}var q=n=>(n.replaceChildren(),n);async function B(n,p,h){let m=await fetch(p,{method:n,headers:h===void 0?{}:{"content-type":"application/json"},body:h===void 0?void 0:JSON.stringify(h),credentials:"same-origin"}),f=await m.json().catch(()=>({}));if(!m.ok){let r=new Error(f.message??`The Edit Host answered ${m.status}.`);throw r.status=m.status,r.value=f,r}return f}var Ms=(n,p,h)=>.2126*n+.7152*p+.0722*h;function js(n,p=128){let h=new Uint32Array(256),m=Array.from({length:p},()=>new Uint32Array(64)),{data:f,width:r,height:P}=n,b=Math.max(1,Math.floor(r*P/6e4));for(let d=0,j=0;j<r*P;j+=b,d=j*4){let k=Math.min(255,Math.round(Ms(f[d],f[d+1],f[d+2])));h[k]++,m[Math.min(p-1,Math.floor(j%r/r*p))][k>>2]++}return{histogram:h,waveform:m}}var Ts={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you: a check failed",not_checked:"Not checked"};function Ht({root:n,finalRoot:p,pixels:h,project:m,onAdjust:f=()=>{}}){let r=t("video",{class:"final-film",controls:!0,preload:"metadata",playsinline:!0,"aria-label":"The final cut"}),P=t("p",{class:"note",role:"status"}),b=t("select",{id:"final-pick",class:"field select","aria-label":"Which film",onchange:()=>C()}),d=t("a",{class:"btn primary",href:"#",download:"",hidden:!0},"Download"),j=[],k=y=>`/projects/${m().id}/renders/${y.job}`,u=y=>y?new Date(y).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";function C(){let y=j.find(c=>String(c.job)===b.value)??j[0];if(!y){r.removeAttribute("src"),r.hidden=!0,d.hidden=!0,b.hidden=!0,P.textContent="No film yet. Render a draft and the finished cut plays here, captions, look, music and sound included.";return}r.hidden=!1,b.hidden=j.length<2;let x=k(y);r.getAttribute("src")!==x&&(r.src=x),d.hidden=!1,d.href=`${x}?download=1`,d.setAttribute("download",y.name);let L=y.current?"This is your edit as it is now.":"Made before your latest changes: render a draft to see them.";P.textContent=`${L}${y.verdict?` ${Ts[y.verdict]??y.verdict}.`:""}`,P.classList.toggle("stale",!y.current)}let D=0,N=0;async function T(){let y=++D,x=(await B("GET",`/projects/${m().id}/renders`)).renders;if(y!==D)return;let L=b.value;j=x;let c=j[0]?.job??0;q(b).append(...j.map(g=>t("option",{value:String(g.job)},`${g.quality==="draft"?"Draft":"Master"} \xB7 ${u(g.at)}${g.current?" \xB7 current":""} \xB7 ${g.name}`))),b.value=String(c>N||!j.some(g=>String(g.job)===L)?c:L),N=Math.max(N,c),C()}p.append(t("section",{class:"panel final","aria-label":"Final cut"},t("h2",{},"Final cut"),r,P,t("div",{class:"row"},b,d,t("button",{type:"button",class:"btn",onclick:()=>te("draft")},"Render again"),t("button",{type:"button",class:"btn",onclick:f},"Adjust in Edit"))));let w=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),W=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),_=t("ul",{class:"jobs","aria-live":"polite"}),J=t("p",{class:"note",role:"status"}),te=async y=>{J.textContent="";try{await B("POST","/jobs",{project:m().id,quality:y}),G()}catch(x){J.textContent=x.message}},ee=t("p",{class:"note",role:"status"}),Z=t("ul",{class:"jobs","aria-label":"Handoff files"}),v=async()=>{ee.textContent="",q(Z);try{let y=await B("POST",`/projects/${m().id}/export/handoff`),x=y.chapters.length,L=x?`, ${x} chapter${x===1?"":"s"}`:"";ee.textContent=`Written to ${y.folder}, with ${y.media} media file${y.media===1?"":"s"} linked${L}.`;for(let c of y.files)Z.append(t("li",{},t("span",{class:"file"},c)));for(let c of y.omitted)Z.append(t("li",{},t("span",{class:"label-mono"},c.format),` ${c.reason}`))}catch(y){ee.textContent=y.message}};n.append(t("section",{class:"panel scopes","aria-label":"Scopes"},t("h2",{},"Scopes"),t("div",{class:"scope-row"},t("figure",{},w,t("figcaption",{},"Histogram")),t("figure",{},W,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:()=>te("draft")},"Render a draft"),t("button",{type:"button",class:"btn primary",onclick:()=>te("master")},"Render the master")),t("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),J,_),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:v},"Export for another editor")),ee,Z));function E(y,x){let L=y.getContext("2d");L.clearRect(0,0,y.width,y.height),L.fillStyle=getComputedStyle(n).getPropertyValue("--scope").trim()||"#6cc0b8",x(L)}function H(){let y=h();if(!y)return;let{histogram:x,waveform:L}=js(y),c=Math.max(1,...x);E(w,g=>x.forEach((A,R)=>g.fillRect(R,100-A/c*100,1,A/c*100))),E(W,g=>L.forEach((A,R)=>A.forEach((V,F)=>{V&&(g.globalAlpha=Math.min(1,.15+V/200),g.fillRect(R*2,100-F/64*100-2,2,2))})))}async function G(){T().catch(x=>P.textContent=x.message);let{jobs:y}=await B("GET","/jobs");q(_);for(let x of y.filter(L=>L.project===m().id&&L.kind==="render").reverse().slice(0,8)){let L=x.output?x.output.split(/[\\/]/).at(-1):null;_.append(t("li",{},t("span",{class:"label-mono"},x.status),` ${x.progress}%`,L?t("span",{class:"file"},` ${L}`):null,x.error?t("span",{class:"error"},` ${x.error}`):null))}}return{scopes:H,refresh:G}}var zt=n=>typeof n=="number"?{n,d:1}:n??{n:1,d:1},Vt=n=>[...n?.picture??[]].sort((p,h)=>p.at-h.at),Ct=n=>[{clip:null,asset:n.id,in:0,out:n.facts.duration,at:0,end:n.facts.duration,speed:{n:1,d:1}}],Te=(n,p)=>n.find(h=>p>=h.at&&p<h.end)??(n.length&&p>=n.at(-1).end?n.at(-1):null);function ke(n,p){if(n.hold)return n.in;let{n:h,d:m}=zt(n.speed);return Math.min(n.out,n.in+Math.round((p-n.at)*h/m))}function ot(n,p,h){for(let m of n){if(m.asset!==p||m.hold||h<m.in||h>=m.out)continue;let{n:f,d:r}=zt(m.speed);return m.at+Math.round((h-m.in)*r/f)}return null}var _e=n=>n.length?Math.max(...n.map(p=>p.end)):0;function Yt(n,p){let h=[];for(let m of p){let f=ot(n,m.asset,m.start);f!==null&&f>0&&h.push({id:m.id,at:f})}return h}var fe=n=>7056e5*n.d/n.n,Jt=(n,p)=>Math.floor(n/fe(p)+1e-9),at=(n,p)=>Math.round(Jt(n,p)*fe(p));function Ee(n,p){let h=Math.max(0,n)/7056e5,m=Math.floor(h/60),f=Math.floor(h%60),r=Jt(Math.max(0,n)-Math.floor(h)*7056e5,p);return`${String(m).padStart(2,"0")}:${String(f).padStart(2,"0")}.${String(r).padStart(2,"0")}`}function Zt(n,{shift:p=!1,mod:h=!1}={}){if(h)return n==="z"||n==="Z"?{type:p?"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:p?null:1,seconds:p?1:null};case"ArrowLeft":return{type:"step",frames:p?null:-1,seconds:p?-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 Xt(n,p,{fps:h,duration:m}){let f=Math.max(0,m-fe(h)),r=P=>Math.min(Math.max(0,Math.round(P)),f);switch(p.type){case"toggle":return{...n,rate:n.rate===0?1:0};case"rate":return{...n,rate:p.rate};case"faster":return{...n,rate:n.rate<=0?1:2};case"reverse":return{...n,rate:n.rate>=0?-1:-2};case"step":{let P=p.frames!==null?p.frames*fe(h):p.seconds*7056e5;return{rate:0,t:r(at(n.t,h)+P)}}case"seek":return{...n,t:r(p.t)};case"tick":{let P=r(p.t);return{t:P,rate:P===0&&n.rate<0||P===f&&n.rate>0?0:n.rate}}default:return n}}var Es=1280;function Qt({canvas:n,urlOf:p,assetOf:h,onTime:m,onRate:f}){let r=n.getContext("2d",{willReadFrequently:!0}),P=new Map,b=[],d={n:30,d:1},j=0,k=0,u=0,C={width:1920,height:1080},D=1,N=!1,T=0,w=null;function W(c){let g=b[c],A=`${g.asset}:${c%2}`;if(!P.has(A)){let R=document.createElement("video");Object.assign(R,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:p(g.asset)}),P.set(A,R)}return P.get(A)}function _(c,g){let A=h(c.asset)?.facts?.fps??d;return(g+fe(A)/2)/7056e5}function J(){let c=Math.min(1,Es/Math.max(C.width,C.height)),g=Math.round(C.width*c),A=Math.round(C.height*c);(n.width!==g||n.height!==A)&&Object.assign(n,{width:g,height:A})}function te(c,g,A){J();let{width:R,height:V}=n;if(r.fillStyle="#000",r.fillRect(0,0,R,V),c?.videoWidth){let F=Math.max(R/c.videoWidth,V/c.videoHeight)*D,Y=c.videoWidth*F,ie=c.videoHeight*F;r.drawImage(c,(R-Y)/2,(V-ie)/2,Y,ie),w={asset:g.asset,source:A}}if(N){r.strokeStyle="rgb(255 255 255 / 0.55)",r.setLineDash([6,6]),r.lineWidth=1;for(let F of[.05,.1])r.strokeRect(R*F,V*F,R*(1-2*F),V*(1-2*F));r.setLineDash([])}}let ee=()=>{J(),r.fillStyle="#000",r.fillRect(0,0,n.width,n.height),w=null},Z=0,v=Promise.resolve();function E(c){let g=b.indexOf(Te(b,c));if(g<0)return Promise.resolve(ee());let A=b[g],R=ke(A,c),V=W(g),F=_(A,R),Y=++Z,ie=new Promise(oe=>{let he=()=>{Z===Y&&te(V,A,R),oe()};if(V.readyState>=2&&Math.abs(V.currentTime-F)<1e-4)return he();V.addEventListener("seeked",he,{once:!0}),V.currentTime=F});if(v=ie,b[g+1]){let oe=W(g+1);oe!==V&&(oe.currentTime=_(b[g+1],b[g+1].in))}return ie}function H(){for(let c of P.values())c.pause(),c.muted=!0}function G(c,g=!0){k=Math.min(Math.max(0,c),Math.max(0,j-fe(d))),g&&m(k)}function y(c){let g=b.indexOf(Te(b,k));if(g<0)return L(0);let A=(R,V)=>{let F=b[R],Y=W(R);Y.currentTime=_(F,ke(F,V)),Y.playbackRate=u,Y.muted=!1;let{n:ie,d:oe}=typeof F.speed=="object"?F.speed:{n:1,d:1},he=(Pe,Le)=>{if(c!==T)return;let Oe=F.at+Math.round((Math.round(Le.mediaTime*7056e5)-F.in)*oe/ie);if(Oe>=F.end-fe(d)/2||Y.ended)return Y.pause(),Y.muted=!0,b[R+1]?(g=R+1,G(b[g].at),A(g,b[g].at)):L(0);te(Y,F,ke(F,Oe)),G(Oe),Y.requestVideoFrameCallback(he)};Y.requestVideoFrameCallback(he),Y.play().catch(()=>c===T&&L(0))};A(g,k)}function x(c){let g=performance.now(),A=async R=>{if(c===T){if(G(k-(R-g)/1e3*7056e5*Math.abs(u)),g=R,await E(k),k===0)return L(0);requestAnimationFrame(A)}};requestAnimationFrame(A)}function L(c){if(c===u&&c!==0)return;u=c;let g=++T;H(),f(u),u>0?y(g):u<0?x(g):(G(at(k,d)),E(k))}return{load(c,{fps:g,duration:A,shape:R}){return b=c,d=g,j=A,R&&(C=R),++T,H(),u=0,f(0),G(Math.min(k,Math.max(0,j-fe(d)))),E(k)},seek(c){return u!==0&&L(0),G(at(c,d)),E(k)},setRate:L,get time(){return k},get rate(){return u},get shown(){return w},get settled(){return v},setShape(c){return C=c,E(k)},setZoom(c){return D=c,E(k)},setGuides(c){return N=c,E(k)},pixels:()=>n.width?r.getImageData(0,0,n.width,n.height):null}}var es=[{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"}],be=44,ts=6;function jt({root:n,compact:p=!1,onSeek:h,onSelect:m=()=>{}}){let f=p?es.slice(0,1):es,r=t("canvas",{class:"lanes","aria-hidden":"true"}),P=p?null:t("div",{class:"lane-labels","aria-hidden":"true"},f.map(v=>t("div",{class:"lane-label"},v.label))),b=t("ul",{class:"clip-list","aria-label":p?"Story":"Clips on the timeline"});n.append(...[P,t("div",{class:"lanes-wrap"},r),b].filter(Boolean));let d=r.getContext("2d"),j={picture:[],overlays:[],audio:[],captions:[]},k=0,u={n:30,d:1},C=0,D=[],N=[],T=new Map,w=null,W=null,_=v=>getComputedStyle(n).getPropertyValue(v).trim()||"#888";function J(){let v=Math.max(1,r.clientWidth),E=f.length*(be+ts),H=window.devicePixelRatio||1;(r.width!==Math.round(v*H)||r.height!==Math.round(E*H))&&(r.width=Math.round(v*H),r.height=Math.round(E*H),r.style.height=`${E}px`),d.setTransform(H,0,0,H,0,0),d.clearRect(0,0,v,E);let G=y=>k?y/k*v:0;f.forEach((y,x)=>{let L=x*(be+ts);d.fillStyle=_("--lane"),d.fillRect(0,L,v,be);for(let c of j[y.key]??[]){let g=G(c.at),A=Math.max(2,G(c.end)-g);d.fillStyle=_(y.colour),d.fillRect(g,L+2,A-1,be-4),c.clip&&c.clip===w&&(d.strokeStyle=_("--focus"),d.lineWidth=2,d.strokeRect(g+1,L+3,A-3,be-6));let R=y.key==="audio"||p&&y.key==="picture"?T.get(c.asset):null;if(R&&c.in!==void 0){d.fillStyle=_("--wave");let V=c.out-c.in;for(let F=0;F<A;F++){let Y=(c.in+V*F/A)/7056e5,oe=(R.peaks[Math.floor(Y*R.perSecond)]??0)*(be-8);d.fillRect(g+F,L+be/2-oe/2,1,Math.max(1,oe))}}}if(y.key==="picture"&&W){d.strokeStyle=_("--ghost"),d.setLineDash([5,4]),d.lineWidth=2;let c=Math.max(k,W.duration)||1;for(let g of W.picture)d.strokeRect(g.at/c*v+1,L+6,Math.max(2,(g.end-g.at)/c*v-2),be-12);d.setLineDash([])}if(y.key==="picture"){d.fillStyle=_("--shot");for(let c of D)d.fillRect(G(c.at)-.5,L,1,8)}}),d.fillStyle=_("--playhead");for(let y of N)d.fillRect(G(y.at)-1,0,3,8);d.fillStyle=_("--playhead"),d.fillRect(G(C)-1,0,2,E)}let te=!1,ee=v=>{let E=r.getBoundingClientRect();h(Math.round(Math.min(1,Math.max(0,(v.clientX-E.left)/E.width))*k))};r.addEventListener("pointerdown",v=>{te=!0,r.setPointerCapture(v.pointerId),ee(v)}),r.addEventListener("pointermove",v=>te&&ee(v)),r.addEventListener("pointerup",()=>te=!1),new ResizeObserver(J).observe(r);function Z(v){w=v;for(let E of b.querySelectorAll("button"))E.setAttribute("aria-pressed",String(E.dataset.clip===v));m(v),J()}return{load(v,{duration:E,fps:H,marks:G=[],pins:y=[]}){N=y,j=v,k=E,u=H,D=G,w&&!j.picture.some(x=>x.clip===w)&&(w=null),q(b);for(let x of j.picture.filter((L,c,g)=>g.findIndex(A=>A.clip===L.clip)===c)){let L=t("button",{type:"button","aria-pressed":String(x.clip===w),dataset:{clip:x.clip},onclick:()=>(Z(x.clip),h(x.at))},`Clip ${x.clip}, ${Ee(x.at,u)} to ${Ee(x.end,u)}`);b.append(t("li",{},L))}J()},setPeaks(v,E){T.set(v,E),J()},setGhost(v){W=v,J()},setTime(v){C=v,J()},select:Z,get selected(){return w},draw:J}}var ss=new Set(["filler","stutter","restart"]);function ns({root:n,onSeek:p,onCut:h,onFix:m=async()=>{}}){let f=[],r=new Map,P=null,b=[],d=null,j=()=>{for(let u of n.querySelectorAll(".word[aria-pressed='true']"))u.setAttribute("aria-pressed","false");for(let u of b)n.querySelector(`[data-word="${CSS.escape(u)}"]`)?.setAttribute("aria-pressed","true")};n.addEventListener("click",u=>{let C=u.target.closest(".word");if(!C)return;let D=r.get(C.dataset.word);if(u.shiftKey&&P){let[N,T]=[f.indexOf(P),f.indexOf(D)].sort((w,W)=>w-W);b=f.slice(N,T+1).filter(w=>w.asset===D.asset).map(w=>w.id)}else P=D,b=[D.id],p(D);j()});function k(u){let C=r.get(u.dataset.word);if(!C)return;let D=t("input",{class:"word-edit",value:C.text,size:String(Math.max(4,C.text.length+2)),maxlength:"60","aria-label":`Fix the word "${C.text}"`});u.replaceWith(D),D.focus(),D.select();let N=!1,T=async w=>{if(N)return;N=!0;let W=D.value.trim();D.replaceWith(u),w&&W&&W!==C.text?await m(C,W):u.focus()};D.addEventListener("keydown",w=>{w.stopPropagation(),w.key==="Enter"?(w.preventDefault(),T(!0)):w.key==="Escape"&&(w.preventDefault(),T(!1))}),D.addEventListener("blur",()=>T(!0))}return n.addEventListener("dblclick",u=>{let C=u.target.closest(".word");C&&k(C)}),n.addEventListener("keydown",u=>{if(u.key==="F2"&&u.target.closest(".word"))return u.preventDefault(),u.stopPropagation(),k(u.target.closest(".word"));(u.key==="Backspace"||u.key==="Delete")&&b.length&&(u.preventDefault(),u.stopPropagation(),h(r.get(b[0]),r.get(b.at(-1))))}),{load({words:u=[],sentences:C=[],takes:D=[]}){f=u,r=new Map(u.map(w=>[w.id,w])),b=b.filter(w=>r.has(w));let N=new Map(D.map(w=>[w.sentence,w]));if(q(n),!u.length){n.append(t("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let T=C.length?C:[...new Set(u.map(w=>w.asset))].map(w=>{let W=u.filter(_=>_.asset===w);return{id:null,asset:w,firstWord:W[0].id,lastWord:W.at(-1).id,score:1}});for(let w of T){let W=N.get(w.id),_=W&&W.rank>1||w.score===0,J=Number(w.firstWord.split(":w")[1]),te=Number(w.lastWord.split(":w")[1]),ee=t("p",{class:`sentence${_?" lost":""}`,dataset:w.id?{sentence:w.id}:{}});W&&ee.append(t("span",{class:"tag"},W.rank===1?"best take":`take ${W.rank}`));for(let Z=J;Z<=te;Z++){let v=r.get(`${w.asset}:w${Z}`);if(!v)continue;let E=_||v.flags.some(x=>ss.has(x)),H=E?`${v.text} (${_?"retake":v.flags.filter(x=>ss.has(x)).join(", ")})`:null,G=typeof v.heard=="string",y=t("button",{type:"button",class:`word${E?" struck":""}${!G&&v.flags.includes("low_confidence")?" unsure":""}${G?" fixed":""}`,"aria-pressed":"false","aria-label":H??(G?`${v.text} (fixed; heard as ${v.heard})`:null),title:G?`Heard as "${v.heard}". Double-click to change.`:"Double-click to fix this word",dataset:{word:v.id}});y.textContent=v.text,ee.append(y," ")}n.append(ee)}j()},playing(u){u!==d&&(n.querySelector(".word.now")?.classList.remove("now"),d=u,u&&n.querySelector(`[data-word="${CSS.escape(u)}"]`)?.classList.add("now"))},words:()=>f,selection:()=>b.length?[b[0],b.at(-1)]:null,clear(){b=[],P=null,j()}}}var Tt=document.getElementById("app"),os=["direct","edit","finish"],le=(n,p)=>{try{if(p===void 0)return localStorage.getItem(n);localStorage.setItem(n,p)}catch{return null}},Ps=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function as(...n){let p=Ps();return t("header",{class:"bar"},p?t("a",{class:"btn ghost",href:p},"\u2190 Kriya Harness"):t("span",{class:"brand"},"Kriya"),t("span",{class:"title"},"Editing Studio"),...n)}function it(n){q(Tt).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 Ls(n){return new Promise(p=>{let h=t("ul",{class:"folders","aria-label":"Folders"}),m=t("p",{class:"label-mono where"}),f=t("p",{class:"note",role:"status"}),r=t("input",{class:"field",placeholder:"New folder name","aria-label":"New folder name",maxlength:"80"}),P=null,b=k=>{j.close(),j.remove(),p(k)};async function d(k){try{let u=await B("GET",`/browse${k?`?root=${encodeURIComponent(k)}`:""}`);P=u.root,m.textContent=u.root,q(h),u.parent&&h.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>d(u.parent)},"\u2191 Up")));let C=u.entries.filter(D=>D.kind==="folder");for(let D of C)h.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>d(`${u.root}/${D.name}`)},`\u{1F4C1} ${D.name}`)));C.length||h.append(t("li",{class:"note"},"No folders here.")),f.textContent=""}catch(u){f.textContent=u.message}}let j=t("dialog",{class:"picker","aria-label":"Choose a folder"},t("h2",{},"Choose a folder"),m,h,t("form",{class:"row tight",onsubmit:async k=>{k.preventDefault();try{let{folder:u}=await B("POST","/browse/folder",{parent:P,name:r.value});r.value="",await d(u)}catch(u){f.textContent=u.message}}},r,t("button",{type:"submit",class:"btn"},"New folder")),f,t("div",{class:"row end"},t("button",{type:"button",class:"btn",onclick:()=>b(null)},"Cancel"),t("button",{type:"button",class:"btn primary",onclick:()=>b(P)},"Use this folder")));j.addEventListener("cancel",k=>(k.preventDefault(),b(null))),document.body.append(j),j.showModal(),d(n)})}async function is(){let n;try{({projects:n}=await B("GET","/projects"))}catch(d){return d.status===401?it():it(d.message)}let p=t("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),h=t("input",{id:"new-folder",class:"field",required:!0,readonly:!0,placeholder:"Choose a folder\u2026"}),m=t("button",{type:"button",class:"btn",onclick:()=>Ls(h.value||null).then(d=>d&&(h.value=d,f.textContent=""))},"Choose\u2026"),f=t("p",{class:"note",role:"status"}),r=t("form",{class:"panel new",onsubmit:async d=>{if(d.preventDefault(),!h.value)return f.textContent="Choose a folder for the project first.";try{let{id:j}=await B("POST","/projects",{name:p.value.trim(),folder:h.value.trim()});location.hash=`#/p/${j}`}catch(j){f.textContent=j.message}}},t("h2",{},"New project"),t("label",{for:"new-name"},"Name"),p,t("label",{for:"new-folder"},"Folder for the project (its footage stays where it is)"),t("div",{class:"row tight"},h,m),t("button",{class:"btn primary",type:"submit"},"Create"),f),P=t("section",{class:"panel taste","aria-label":"Your taste"}),b=async d=>{let{proposed:j,confirmed:k}=d??await B("GET","/taste"),u=(C,D)=>async()=>b(await B("POST",`/taste/${encodeURIComponent(C)}/${D}`));q(P).append(t("h2",{},"Your taste"),...j.length||k.length?[]:[t("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...j.map(C=>t("div",{class:"taste-row"},t("p",{},C.sentence),t("button",{type:"button",class:"btn primary",onclick:u(C.key,"confirm")},"Use it"),t("button",{type:"button",class:"btn",onclick:u(C.key,"dismiss")},"No"))),...k.map(C=>t("div",{class:"taste-row"},t("p",{},C.shown),t("button",{type:"button",class:"btn","aria-label":`Remove the rule ${C.shown}`,onclick:u(C.key,"remove")},"Remove"))))};b().catch(()=>{}),q(Tt).append(as(),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(d=>t("li",{class:"project-row"},t("a",{class:"btn open",href:`#/p/${d.id}`},d.name),t("button",{type:"button",class:"btn ghost danger","aria-label":`Delete the project ${d.name}`,onclick:async()=>{if(confirm(`Delete "${d.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 I("DELETE",`/projects/${i.id}`),Yt()}catch($){alert($.message)}}},"Delete")))):t("p",{class:"note"},"No projects yet.")),o,M))}async function bn(a){let d;try{d=await I("GET",`/projects/${a}`)}catch(e){return e.status===401?Ye():Ye(e.message)}let u=d.project,f=d.assets,p={assets:[],words:[],sentences:[],takes:[],shots:[]},o=[],M={picture:[],overlays:[],audio:[],captions:[]},g=null,i=Vt.includes(ae("kriya-edit-mode"))?ae("kriya-edit-mode"):"direct",$=!1,k=()=>u.canvas.fps,l=t("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),x=t("span",{class:"chip"},"Preview"),A=t("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),L=t("p",{class:"note",role:"status","aria-live":"polite"}),S=qt({canvas:A,urlOf:e=>`/media/${f.find(n=>n.id===e).media}`,assetOf:e=>f.find(n=>n.id===e),onTime:e=>{l.textContent=`${xe(e,k())} / ${xe(D(),k())}`,C.setTime(e),B.setTime(e);let n=ve(N(),e),s=n?he(n,e):null,c=s===null?null:p.words.find(h=>h.asset===n.asset&&s>=h.start&&s<h.end);w.playing(c?.id??null)},onRate:e=>{He.textContent=e===0?"Play":"Pause",He.setAttribute("aria-label",e===0?"Play (Space)":`Pause (Space), playing at ${e}\xD7`)}}),b=()=>({"16:9":{width:1920,height:1080},"9:16":{width:1080,height:1920}})[jt.value]??u.canvas,N=()=>g?ht(f.find(e=>e.id===g)):o,D=()=>Ie(N()),_=t("div",{class:"transcript",tabindex:"-1"}),J=t("div",{class:"strip"}),Y=t("div",{class:"timeline"}),z=t("div",{class:"finish"}),w=Ut({root:_,onSeek:e=>{let n=Ve(o,e.asset,e.start);n!==null?(v(),S.seek(n)):T(e.asset,e.start)},onCut:(e,n)=>m([{op:"remove_range",asset:e.asset,from:{word:e.id,edge:"start"},to:{word:n.id,edge:"end"}}]),onFix:async(e,n)=>{try{await I("POST",`/projects/${a}/words/${encodeURIComponent(e.id)}`,{text:n}),L.textContent=`Fixed "${e.text}" to "${n}". Captions and Kriya use it from now on.`}catch(s){L.textContent=s.message}await r()}}),C=gt({root:Y,onSeek:e=>(v(),S.seek(e))}),B=gt({root:J,compact:!0,onSeek:e=>(v(),S.seek(e))}),K=t("div",{class:"area-final"}),y=It({root:z,finalRoot:K,pixels:()=>S.pixels(),project:()=>u,onAdjust:()=>ke("edit")});function v(){g&&(g=null,x.textContent="Preview",S.load(o,{fps:k(),duration:Ie(o),shape:b()}))}function T(e,n){g=e;let s=f.find(c=>c.id===e).facts;x.textContent="Source",S.load(ht(f.find(c=>c.id===e)),{fps:s.fps??k(),duration:s.duration,shape:{width:s.width??1920,height:s.height??1080}}).then(()=>S.seek(n))}async function r(){let[e,n,s]=await Promise.all([I("GET",`/projects/${a}`),I("GET",`/projects/${a}/plan`),I("GET",`/projects/${a}/index`)]);u=e.project,f=e.assets,p=s,M=n.timeline,o=Ft(n.timeline);let c=Ie(o),h=Dt(o,p.shots),E=new Map((p.words??[]).map(O=>[O.id,O])),U=(u.sequences.find(O=>O.id===u.active)?.markers??[]).flatMap(O=>{let F=O.name.startsWith("Note: ")&&O.at?.word?E.get(O.at.word):null,H=F?Ve(o,F.asset,F.start):null;return H==null?[]:[{at:H,name:O.name}]});if(C.load(M,{duration:c,fps:k(),marks:h,pins:U}),B.load({picture:M.picture},{duration:c,fps:k(),marks:h}),w.load(p),We(),G(),!$){$=!0;let O=[...fe.options].map(F=>F.value).find(F=>{let[H,un]=F.split(":").map(Number);return H*u.canvas.height===un*u.canvas.width});O&&u.sequences.some(F=>F.clips.length)&&(fe.value=O)}g||await S.load(o,{fps:k(),duration:c,shape:b()});for(let O of new Set([...M.audio,...M.picture].map(F=>F.asset))){let F=f.find(H=>H.id===O)?.media;F&&f.find(H=>H.id===O).facts.hasAudio&&fetch(`/tiles/${F}?kind=peaks`).then(H=>H.ok?H.json():null).then(H=>H&&(C.setPeaks(O,H.levels[0]),B.setPeaks(O,H.levels[0]))).catch(()=>{})}}async function m(e){try{let n=await I("PATCH",`/projects/${a}`,{ops:e});L.textContent=n.diagnostics?.length?n.diagnostics[0].message:""}catch(n){L.textContent=n.value?.diagnostics?.[0]?.message??n.message}await r()}let j=t("ul",{class:"bin","aria-label":"Footage"}),P=new Map,q=e=>[...P.values()].find(n=>n.kind==="index"&&n.asset===e&&["pending","running"].includes(n.status)),R=(e,n)=>{let s=t("span",{class:e===null?"busy":""});return e!==null&&(s.style.width=`${e}%`),t("div",{class:"progress",role:"progressbar","aria-label":n,"aria-valuemin":"0","aria-valuemax":"100",...e===null?{}:{"aria-valuenow":String(e)}},s)};function G(){W(j);for(let e of f.filter(n=>n.kind!=="reference")){let n=p.assets.find(U=>U.asset===e.id),s=n?.layers.find(U=>U.layer==="L2"),c=q(e.id),h=se?.speech?"Indexed, no words yet: set up speech-to-text above":s?.notice??"Indexed, no words",E=c?`Reading this file\u2026 ${c.progress??0}%`:n?s?.status==="ok"?"Indexed":h:"Not indexed",V=["video","audio"].includes(e.kind);j.append(t("li",{class:"asset"},t("button",{type:"button",class:"btn",onclick:()=>T(e.id,0)},`${e.path.split(/[\\/]/).at(-1)} \xB7 ${e.kind}`),t("span",{class:"note"},e.offline?"Offline: the file has moved":E),c?R(c.progress??0,`Indexing ${e.path.split(/[\\/]/).at(-1)}`):null,V?t("button",{type:"button",class:"btn",disabled:!!c,onclick:()=>te(e)},n?"Index again":"Index"):null,V?t("button",{type:"button",class:"btn",onclick:()=>m([{op:"keep_range",asset:e.id,from:0,to:e.facts.duration}])},"Add to cut"):null))}Ee()}async function te(e){se?.speech&&!se.setup?.error&&(L.textContent="Your file is indexed without words until speech-to-text is set up (above).",nt.hidden=!1);try{let n=await I("POST",`/projects/${a}/index`,{asset:e.id});P.set(n.id,{...n,asset:e.id}),L.textContent="Reading your footage. You can keep working.",G()}catch(n){L.textContent=n.message}}function Q(e,{reference:n=!1,aspect:s="all"}={}){let c=h=>new Promise((E,V)=>{let U=t("li",{class:"asset"},t("span",{class:"note"},`Copying ${h.name}\u2026`),R(0,`Copying ${h.name}`));ie.append(U);let O=new XMLHttpRequest;O.open("POST",`/projects/${a}/upload?name=${encodeURIComponent(h.name)}${n?"&as=reference":""}`),O.upload.onprogress=F=>{if(!F.lengthComputable)return;let H=Math.round(F.loaded*100/F.total);U.querySelector(".progress span").style.width=`${H}%`,U.querySelector(".progress").setAttribute("aria-valuenow",String(H)),U.querySelector(".note").textContent=`Copying ${h.name}\u2026 ${H}%`},O.onload=()=>{U.remove();let F={};try{F=JSON.parse(O.responseText)}catch{}O.status<300?E(F):V(new Error(F.message??`The Edit Host answered ${O.status}.`))},O.onerror=()=>(U.remove(),V(new Error(`${h.name} couldn't be copied.`))),O.send(h)});return(async()=>{for(let h of e)try{let E=await c(h);L.textContent=n?`Added ${h.name} as a reference for ${ue[s].toLowerCase()}.`:`Added ${h.name}. Index it to read its words.`,n&&(le.add(E.id),ae(Ne(E.id),s))}catch(E){L.textContent=E.message}await r()})()}let ie=t("ul",{class:"bin","aria-label":"Copying"}),$e=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:()=>(Q([...$e.files]),$e.value="")}),Se=t("input",{id:"add-path",class:"field",placeholder:"/Users/you/Movies/take.mov",autocomplete:"off"}),Ce=t("section",{class:"panel bin-panel","aria-label":"Bin"},t("h2",{},"Bin"),j,ie,$e,t("button",{type:"button",class:"btn primary wide",onclick:()=>$e.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 I("POST",`/projects/${a}/assets`,{path:Se.value.trim()}),Se.value="",await r()}catch(n){L.textContent=n.message}}},t("label",{for:"add-path",class:"sr-only"},"Link a file by its path"),Se,t("button",{class:"btn",type:"submit"},"Link")))),le=new Set,bt=new Set,ue={all:"Everything it shows",editing:"Editing: cuts and pace",sound:"Sound: music and feel",colour:"Colour grade",graphics:"Graphics: captions and text"},Ne=e=>`kriya-ref-aspect:${a}:${e}`,Je=e=>Object.hasOwn(ue,ae(Ne(e))??"")?ae(Ne(e)):"all",Ze=(e,n,s)=>t("select",{class:"field select",...e,onchange:s},Object.entries(ue).map(([c,h])=>t("option",{value:c,selected:c===n},h))),Fe=Ze({id:"ref-aspect","aria-label":"The next reference is for"},"all",()=>Xe.value=Fe.value),Xe=Ze({id:"ref-aspect-bin","aria-label":"The next reference is for"},"all",()=>Fe.value=Xe.value),Zt=(e,n)=>e.parts?n!=="all"?e.parts[n]?[e.parts[n]]:[`Nothing to take for ${ue[n].toLowerCase()} from this one.`]:e.lines.filter(s=>!(e.kind==="video"&&e.pace&&s===e.parts.sound)):e.lines,Me=new Map,De=t("ul",{class:"bin","aria-label":"References"}),Qe=t("ul",{class:"bin refs-direct","aria-label":"References for this cut"}),kt=t("p",{class:"note small"}),Te=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=[...Te.files];Te.value="";let n=Fe.value,s=n==="all"?"a video's pace, captions, colour and music; an image's colour grade; music's tempo and energy":`only its ${ue[n].toLowerCase()}`;e.length&&confirm(`Use this only as a reference for ${ue[n].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 B("DELETE",`/projects/${d.id}`),is()}catch(j){alert(j.message)}}},"Delete")))):t("p",{class:"note"},"No projects yet.")),r,P))}async function Os(n){let p;try{p=await B("GET",`/projects/${n}`)}catch(e){return e.status===401?it():it(e.message)}let h=p.project,m=p.assets,f={assets:[],words:[],sentences:[],takes:[],shots:[]},r=[],P={picture:[],overlays:[],audio:[],captions:[]},b=null,d=os.includes(le("kriya-edit-mode"))?le("kriya-edit-mode"):"direct",j=!1,k=()=>h.canvas.fps,u=t("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),C=t("span",{class:"chip"},"Preview"),D=t("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),N=t("p",{class:"note",role:"status","aria-live":"polite"}),T=Qt({canvas:D,urlOf:e=>`/media/${m.find(s=>s.id===e).media}`,assetOf:e=>m.find(s=>s.id===e),onTime:e=>{u.textContent=`${Ee(e,k())} / ${Ee(_(),k())}`,E.setTime(e),H.setTime(e);let s=Te(W(),e),o=s?ke(s,e):null,a=o===null?null:f.words.find(i=>i.asset===s.asset&&o>=i.start&&o<i.end);v.playing(a?.id??null)},onRate:e=>{et.textContent=e===0?"Play":"Pause",et.setAttribute("aria-label",e===0?"Play (Space)":`Pause (Space), playing at ${e}\xD7`)}}),w=()=>({"16:9":{width:1920,height:1080},"9:16":{width:1080,height:1920}})[Bt.value]??h.canvas,W=()=>b?Ct(m.find(e=>e.id===b)):r,_=()=>_e(W()),J=t("div",{class:"transcript",tabindex:"-1"}),te=t("div",{class:"strip"}),ee=t("div",{class:"timeline"}),Z=t("div",{class:"finish"}),v=ns({root:J,onSeek:e=>{let s=ot(r,e.asset,e.start);s!==null?(x(),T.seek(s)):L(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 B("POST",`/projects/${n}/words/${encodeURIComponent(e.id)}`,{text:s}),N.textContent=`Fixed "${e.text}" to "${s}". Captions and Kriya use it from now on.`}catch(o){N.textContent=o.message}await c()}}),E=jt({root:ee,onSeek:e=>(x(),T.seek(e))}),H=jt({root:te,compact:!0,onSeek:e=>(x(),T.seek(e))}),G=t("div",{class:"area-final"}),y=Ht({root:Z,finalRoot:G,pixels:()=>T.pixels(),project:()=>h,onAdjust:()=>Me("edit")});function x(){b&&(b=null,C.textContent="Preview",T.load(r,{fps:k(),duration:_e(r),shape:w()}))}function L(e,s){b=e;let o=m.find(a=>a.id===e).facts;C.textContent="Source",T.load(Ct(m.find(a=>a.id===e)),{fps:o.fps??k(),duration:o.duration,shape:{width:o.width??1920,height:o.height??1080}}).then(()=>T.seek(s))}async function c(){let[e,s,o]=await Promise.all([B("GET",`/projects/${n}`),B("GET",`/projects/${n}/plan`),B("GET",`/projects/${n}/index`)]);h=e.project,m=e.assets,f=o,P=s.timeline,r=Vt(s.timeline);let a=_e(r),i=Yt(r,f.shots),l=new Map((f.words??[]).map(M=>[M.id,M])),O=(h.sequences.find(M=>M.id===h.active)?.markers??[]).flatMap(M=>{let I=M.name.startsWith("Note: ")&&M.at?.word?l.get(M.at.word):null,K=I?ot(r,I.asset,I.start):null;return K==null?[]:[{at:K,name:M.name}]});if(E.load(P,{duration:a,fps:k(),marks:i,pins:O}),H.load({picture:P.picture},{duration:a,fps:k(),marks:i}),v.load(f),Ye(),Y(),!j){j=!0;let M=[...ue.options].map(I=>I.value).find(I=>{let[K,pe]=I.split(":").map(Number);return K*h.canvas.height===pe*h.canvas.width});M&&h.sequences.some(I=>I.clips.length)&&(ue.value=M)}b||await T.load(r,{fps:k(),duration:a,shape:w()});for(let M of new Set([...P.audio,...P.picture].map(I=>I.asset))){let I=m.find(K=>K.id===M)?.media;I&&m.find(K=>K.id===M).facts.hasAudio&&fetch(`/tiles/${I}?kind=peaks`).then(K=>K.ok?K.json():null).then(K=>K&&(E.setPeaks(M,K.levels[0]),H.setPeaks(M,K.levels[0]))).catch(()=>{})}}async function g(e){try{let s=await B("PATCH",`/projects/${n}`,{ops:e});N.textContent=s.diagnostics?.length?s.diagnostics[0].message:""}catch(s){N.textContent=s.value?.diagnostics?.[0]?.message??s.message}await c()}let A=t("ul",{class:"bin","aria-label":"Footage"}),R=new Map,V=e=>[...R.values()].find(s=>s.kind==="index"&&s.asset===e&&["pending","running"].includes(s.status)),F=(e,s)=>{let o=t("span",{class:e===null?"busy":""});return e!==null&&(o.style.width=`${e}%`),t("div",{class:"progress",role:"progressbar","aria-label":s,"aria-valuemin":"0","aria-valuemax":"100",...e===null?{}:{"aria-valuenow":String(e)}},o)};function Y(){q(A);for(let e of m.filter(s=>s.kind!=="reference")){let s=f.assets.find(O=>O.asset===e.id),o=s?.layers.find(O=>O.layer==="L2"),a=V(e.id),i=ce?.speech?"Indexed, no words yet: set up speech-to-text above":o?.notice??"Indexed, no words",l=a?`Reading this file\u2026 ${a.progress??0}%`:s?o?.status==="ok"?"Indexed":i:"Not indexed",S=["video","audio"].includes(e.kind);A.append(t("li",{class:"asset"},t("button",{type:"button",class:"btn",onclick:()=>L(e.id,0)},`${e.path.split(/[\\/]/).at(-1)} \xB7 ${e.kind}`),t("span",{class:"note"},e.offline?"Offline: the file has moved":l),a?F(a.progress??0,`Indexing ${e.path.split(/[\\/]/).at(-1)}`):null,S?t("button",{type:"button",class:"btn",disabled:!!a,onclick:()=>ie(e)},s?"Index again":"Index"):null,S?t("button",{type:"button",class:"btn",onclick:()=>g([{op:"keep_range",asset:e.id,from:0,to:e.facts.duration}])},"Add to cut"):null))}Ie()}async function ie(e){ce?.speech&&!ce.setup?.error&&(N.textContent="Your file is indexed without words until speech-to-text is set up (above).",ft.hidden=!1);try{let s=await B("POST",`/projects/${n}/index`,{asset:e.id});R.set(s.id,{...s,asset:e.id}),N.textContent="Reading your footage. You can keep working.",Y()}catch(s){N.textContent=s.message}}function oe(e,{reference:s=!1,aspect:o="all"}={}){let a=i=>new Promise((l,S)=>{let O=t("li",{class:"asset"},t("span",{class:"note"},`Copying ${i.name}\u2026`),F(0,`Copying ${i.name}`));he.append(O);let M=new XMLHttpRequest;M.open("POST",`/projects/${n}/upload?name=${encodeURIComponent(i.name)}${s?"&as=reference":""}`),M.upload.onprogress=I=>{if(!I.lengthComputable)return;let K=Math.round(I.loaded*100/I.total);O.querySelector(".progress span").style.width=`${K}%`,O.querySelector(".progress").setAttribute("aria-valuenow",String(K)),O.querySelector(".note").textContent=`Copying ${i.name}\u2026 ${K}%`},M.onload=()=>{O.remove();let I={};try{I=JSON.parse(M.responseText)}catch{}M.status<300?l(I):S(new Error(I.message??`The Edit Host answered ${M.status}.`))},M.onerror=()=>(O.remove(),S(new Error(`${i.name} couldn't be copied.`))),M.send(i)});return(async()=>{for(let i of e)try{let l=await a(i);N.textContent=s?`Added ${i.name} as a reference for ${ye[o].toLowerCase()}.`:`Added ${i.name}. Index it to read its words.`,s&&(me.add(l.id),le(Ge(l.id),o))}catch(l){N.textContent=l.message}await c()})()}let he=t("ul",{class:"bin","aria-label":"Copying"}),Pe=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:()=>(oe([...Pe.files]),Pe.value="")}),Le=t("input",{id:"add-path",class:"field",placeholder:"/Users/you/Movies/take.mov",autocomplete:"off"}),Oe=t("section",{class:"panel bin-panel","aria-label":"Bin"},t("h2",{},"Bin"),A,he,Pe,t("button",{type:"button",class:"btn primary wide",onclick:()=>Pe.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 B("POST",`/projects/${n}/assets`,{path:Le.value.trim()}),Le.value="",await c()}catch(s){N.textContent=s.message}}},t("label",{for:"add-path",class:"sr-only"},"Link a file by its path"),Le,t("button",{class:"btn",type:"submit"},"Link")))),me=new Set,Et=new Set,ye={all:"Everything it shows",editing:"Editing: cuts and pace",sound:"Sound: music and feel",colour:"Colour grade",graphics:"Graphics: captions and text"},Ge=e=>`kriya-ref-aspect:${n}:${e}`,rt=e=>Object.hasOwn(ye,le(Ge(e))??"")?le(Ge(e)):"all",lt=(e,s,o)=>t("select",{class:"field select",...e,onchange:o},Object.entries(ye).map(([a,i])=>t("option",{value:a,selected:a===s},i))),Ue=lt({id:"ref-aspect","aria-label":"The next reference is for"},"all",()=>ct.value=Ue.value),ct=lt({id:"ref-aspect-bin","aria-label":"The next reference is for"},"all",()=>Ue.value=ct.value),ls=(e,s)=>e.parts?s!=="all"?e.parts[s]?[e.parts[s]]:[`Nothing to take for ${ye[s].toLowerCase()} from this one.`]:e.lines.filter(o=>!(e.kind==="video"&&e.pace&&o===e.parts.sound)):e.lines,Ae=new Map,He=t("ul",{class:"bin","aria-label":"References"}),dt=t("ul",{class:"bin refs-direct","aria-label":"References for this cut"}),Pt=t("p",{class:"note small"}),Re=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=[...Re.files];Re.value="";let s=Ue.value,o=s==="all"?"a video's pace, captions, colour and music; an image's colour grade; music's tempo and energy":`only its ${ye[s].toLowerCase()}`;e.length&&confirm(`Use this only as a reference for ${ye[s].toLowerCase()}?
4
4
 
5
- Kriya measures it as numbers: ${s}. No picture, sound or words from it go into your video. Add only what you're allowed to use this way.`)&&Q(e,{reference:!0,aspect:n})}});function wt(e,n){let s=e.path.split(/[\\/]/).at(-1),c=e.facts.width?e.facts.duration?"video":"image":"music",h=t("input",{type:"checkbox",id:`use-${n}-${e.id}`,checked:le.has(e.id),onchange:()=>(h.checked?le.add(e.id):le.delete(e.id),Ee(h.id))}),E=Me.get(e.id),V=Je(e.id),U=t("ul",{class:"ref-lines"},...E?Zt(E,V).map(F=>t("li",{},F)):[t("li",{class:"note"},"Measuring\u2026")]),O=Ze({id:`aspect-${n}-${e.id}`,"aria-label":`Take from ${s}`},V,F=>(ae(Ne(e.id),F.target.value),Ee(F.target.id)));return t("li",{class:"asset ref"},t("button",{type:"button",class:"btn",onclick:()=>e.facts.duration&&T(e.id,0)},`${s} \xB7 ${c}`),t("label",{class:"note small",for:`aspect-${n}-${e.id}`},"Take from it"),O,U,t("label",{class:"inline",for:`use-${n}-${e.id}`},h," Use in the cut"))}function Ee(e=null){W(De),W(Qe);let n=f.filter(h=>h.kind==="reference");n.length||De.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 h of n)bt.has(h.id)||(bt.add(h.id),le.add(h.id)),De.append(wt(h,"bin")),Qe.append(wt(h,"direct")),Me.has(h.id)||(Me.set(h.id,null),I("GET",`/projects/${a}/references/${encodeURIComponent(h.id)}`).then(E=>(Me.set(h.id,E),Ee())).catch(E=>(Me.set(h.id,{lines:[`Couldn't measure it: ${E.message}`]}),Ee())));ln(),e&&document.getElementById(e)?.focus(),((h,E,V)=>{let U=h.value;W(h).append(t("option",{value:""},V),...E.map(O=>t("option",{value:O.id},O.path.split(/[\\/]/).at(-1)))),h.value=E.some(O=>O.id===U)?U:""})(X,f.filter(h=>h.kind==="audio"&&!/kriya-music-/.test(h.path)),"No music");let c=X.value;X.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)")),X.options[1]??null),/^generated:/.test(_e)?X.value=_e:c&&(X.value=c)}let se=null,me=t("p",{class:"note"}),et=t("div"),tt=t("button",{type:"button",class:"btn primary",onclick:()=>I("POST","/runtime/setup").then(Ke).catch(e=>me.textContent=e.message)},"Set up speech-to-text"),nt=t("section",{class:"panel setup","aria-label":"Speech-to-text setup",hidden:!0},t("h2",{},"Speech-to-text"),me,et,tt),vt=e=>(e/1e6).toLocaleString(void 0,{maximumFractionDigits:0});function Ke(e){se=e;let n=se.setup,s=n&&!n.finished;if(nt.hidden=!se.speech&&!s&&!n?.error,tt.hidden=!!s,tt.textContent=n?.error?"Try again":"Set up speech-to-text",W(et),s){let c=n.total?Math.round(n.done*100/n.total):null;me.textContent=n.total?`Downloading ${n.step}: ${vt(n.done)} of ${vt(n.total)} MB (${c}%)`:n.line??"Setting up\u2026",et.append(R(c,"Media Runtime setup"))}else n?.error?me.textContent=`Setup stopped: ${n.error}`:se.speech?me.textContent="Words in the transcript need the speech model on this computer. Setting it up downloads it once; after that it works offline.":n?.finished&&(me.textContent="Ready. Index a file to read its words.")}let oe=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"}),at=t("span",{class:"chip selection",hidden:!0}),xt=t("ol",{class:"chat","aria-label":"Chat with Kriya","aria-live":"polite"}),Be=t("ul",{class:"did","aria-label":"What I did"}),ge=[],Z=null,ne=null,ye=e=>{let n=Math.max(0,e)/7056e5,s=Math.floor(n/60);return`${s}:${(n-s*60).toFixed(1).padStart(4,"0")}`},$t=()=>{if(Z!==null&&ne!==null&&ne>Z)return{selection:{from:Z,to:ne},label:`Marked ${ye(Z)}\u2013${ye(ne)}`};let e=w.selection();return e?{selection:{words:e},label:`Selected: ${p.words.find(n=>n.id===e[0])?.text??""}${e[0]===e[1]?"":" \u2026"}`}:C.selected?{selection:{clip:C.selected},label:`Selected: clip ${C.selected}`}:Z!==null?{selection:{at:Z},label:`Marked in at ${ye(Z)} (press O for the end)`}:{selection:{at:S.time},label:null}},We=()=>{let{label:e}=$t();at.hidden=!e,at.textContent=e??""};_.addEventListener("click",()=>setTimeout(We));function st(e){let n=[],s=0;for(let c of String(e).matchAll(/\b(\d{1,2}):(\d{2}(?:\.\d+)?)\b/g)){n.push(e.slice(s,c.index));let h=Math.round((Number(c[1])*60+Number(c[2]))*7056e5);n.push(t("button",{type:"button",class:"time-link",title:"Play from here",onclick:()=>(v(),S.seek(Math.min(h,Math.max(0,Ie(o)-1))))},c[0])),s=c.index+c[0].length}return n.push(e.slice(s)),n}function ce(e,n,...s){let c=t("li",{class:`msg ${e}`},t("span",{class:"who"},e==="you"?"You":"Kriya"),t("p",{},...st(n)),...s);return xt.append(c),c.scrollIntoView({block:"nearest"}),c}function Xt(e){C.setGhost(e.timeline),B.setGhost(e.timeline);let n=t("div",{class:"proposal"}),s=async(c,h)=>{try{let E=await I("POST",`/projects/${a}/proposals/${e.id}`,{accept:c,...h?{only:h}:{}});if(L.textContent=E.dropped.length?`Not applied, because you changed that part: ${E.dropped.map(V=>V.change).join("; ")}.`:c?"Done. Undo with Cmd+Z.":"Left as it was.",c)for(let V of h?h.map(U=>e.changes[U]):e.changes)Be.prepend(t("li",{},V));W(n).append(t("p",{class:"note"},c?E.dropped.length?"Partly applied.":"Applied.":"Not applied."))}catch(E){L.textContent=E.message}C.setGhost(null),B.setGhost(null),await r()};return n.append(t("p",{class:"lead"},"Proposed, not applied yet"),t("ul",{},e.changes.map((c,h)=>t("li",{},t("span",{},...st(c)),e.changes.length>1?t("button",{type:"button",class:"btn",onclick:()=>s(!0,[h])},"Only this"):null))),t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>s(!0)},e.changes.length>1?"Accept all":"Accept"),t("button",{type:"button",class:"btn",onclick:()=>s(!1)},"Reject"))),n}let je=null,Qt=()=>({...ct(),...Ae.value==="clean"?{cleanVoice:!0}:{}}),St=e=>p.words.find(n=>n.id===e)?.text??e,Ct=e=>`${Math.floor(e/60)}:${(e%60).toFixed(1).padStart(4,"0")}`;function en(e={}){return[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 "${St(e.coldOpen.from)} \u2026 ${St(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.broll==="own"?"B-roll from your clips":null,e.titles?"title cards":null,e.ramps?"a speed ramp into the story":null,e.cuts?.length?`trims ${e.cuts.map(s=>`${Ct(s.from)}\u2013${Ct(s.to)}`).join(", ")} of the take`:null].filter(Boolean).join(" \xB7 ")}function tn(e){let n=t("div",{class:"proposal plan"},t("p",{class:"lead"},"The Director's plan, not made yet"),e.steps.length?t("ol",{class:"steps"},e.steps.map(s=>t("li",{},...st(s)))):null,t("p",{class:"note small"},en(e.settings)),t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>(je=null,nn(e.brief),W(n).append(t("p",{class:"note"},`Approved. Making it now in ${e.brief.format??fe.value}; the progress is in Direct.`)),Tt(e.brief,{exact:!0}))},"Approve and make it"),t("button",{type:"button",class:"btn",onclick:()=>(je=e,oe.focus(),oe.placeholder="Say what to change in the plan\u2026")},"Change\u2026")));return n}function nn(e={}){e.format&&(fe.value=e.format);let n=e.seconds?String(e.seconds):"";n&&![...pe.options].some(s=>s.value===n)&&pe.append(t("option",{value:n},`${n} seconds`)),pe.value=n,Pe.value=e.captions??"",Le.value=e.grade??"",/^generated:/.test(e.music??"")&&[...X.options].some(s=>s.value===e.music)?X.value=e.music:e.music||(X.value=""),Ae.value=e.cleanVoice?"clean":"",qe.box.checked=!!e.angles,it.box.checked=e.broll==="own",Ge.box.checked=!!e.titles,lt.value=""}async function Mt(e,n=null){let s=ce("kriya",n?"Revising the plan\u2026":"Planning the cut\u2026");try{let c=await I("POST",`/projects/${a}/plan`,{text:e,history:ge.slice(-6),previous:n,choices:Qt()});s.remove(),je=c,ce("kriya",c.say||"Here's my plan.",tn(c)),ge.push({who:"kriya",text:(c.say||"").slice(0,400)})}catch(c){s.remove(),ce("kriya",c.message)}}async function ot({planning:e=!1}={}){let n=oe.value.trim();if(!n)return;if(oe.placeholder='Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',je||e)return ce("you",n),ge.push({who:"you",text:n.slice(0,400)}),oe.value="",Mt(n,je);let{selection:s,label:c}=$t();ce("you",c?`${n} (${c.replace(/^Selected: /,"on ")})`:n),oe.value="";let h=ce("kriya","Thinking about that\u2026");try{let E=await I("POST",`/projects/${a}/ask`,{text:n,selection:s,history:ge.slice(-6)});h.remove();let V=E.say||(E.proposal?"Here's what I'd change.":E.direct?"That's about the whole video.":E.reason??"I couldn't turn that into an edit. Try saying it another way.");if(ge.push({who:"you",text:n.slice(0,400)}),E.direct&&!E.proposal)return Mt(n);ce("kriya",V,E.proposal?Xt(E.proposal):null),ge.push({who:"kriya",text:V.slice(0,400)})}catch(E){h.remove(),ce("kriya",E.status===0||E.status>=500?"I can't reach Kriya right now, so I can't make changes by asking. You can still edit by hand.":E.message)}}oe.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),ot())});let an=t("form",{class:"prompt",onsubmit:e=>(e.preventDefault(),ot())},t("label",{for:"prompt",class:"sr-only"},"Message Kriya"),oe,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:()=>ot({planning:!0})},"Plan"))),sn=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:()=>Oe({type:"mark",edge:"in"})},"Mark in"),t("button",{type:"button",class:"btn","aria-keyshortcuts":"O",title:"Mark out (O)",onclick:()=>Oe({type:"mark",edge:"out"})},"Mark out")),on={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",not_checked:"Not checked"},pe=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,n])=>t("option",{value:e},n))),Pe=t("select",{id:"make-captions",class:"field select"},[["","No captions"],["clean","Captions: clean"],["karaoke","Captions: karaoke"],["boxed","Captions: boxed"]].map(([e,n])=>t("option",{value:e},n))),X=t("select",{id:"make-music",class:"field select"}),fe=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,n])=>t("option",{value:e},n))),Le=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,n])=>t("option",{value:e},n))),Ae=t("select",{id:"make-voice",class:"field select"},[["","Voice: as recorded"],["clean","Voice: remove background noise"]].map(([e,n])=>t("option",{value:e},n))),rt=(e,n)=>{let s=t("input",{type:"checkbox",id:e});return{box:s,el:t("label",{class:"inline",for:e},s,` ${n}`)}},qe=rt("make-angles","Angles (wide and tight)"),it=rt("make-broll","B-roll from my clips"),Ge=rt("make-titles","Title cards"),_e="";X.addEventListener("change",()=>_e=X.value);let rn={"":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}},lt=t("select",{id:"make-template",class:"field select",onchange:()=>{let e=rn[lt.value];e&&(fe.value=e.format,Pe.value=e.captions,Le.value=e.grade,pe.value=e.length,Ae.value=e.voice,qe.box.checked=!!e.angles,Ge.box.checked=!!e.titles,X.value=_e=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,n])=>t("option",{value:e},n))),ln=()=>{let e=f.filter(s=>s.kind==="reference"&&le.has(s.id)),n=[...new Set(e.map(s=>Je(s.id)))].map(s=>s==="all"?"everything":ue[s].split(":")[0].toLowerCase());kt.textContent=e.length?`${e.length} reference${e.length===1?"":"s"} in use, for ${n.join(", ")}.`:"No references in use."},ct=(e={})=>({...pe.value?{seconds:Number(pe.value)}:{},...Pe.value?{captions:Pe.value}:{},...X.value?{music:X.value}:{},...le.size?{references:[...le].filter(n=>f.some(s=>s.id===n&&s.kind==="reference")).map(n=>({id:n,aspect:Je(n)}))}:{},format:fe.value,...Le.value?{grade:Le.value}:{},...Ae.value==="clean"?{cleanVoice:!0}:{},...qe.box.checked?{angles:!0}:{},...it.box.checked?{broll:"own"}:{},...Ge.box.checked?{titles:!0}:{},...e});async function Tt(e,{exact:n=!1}={}){try{let s=ct().references,c=await I("POST",`/projects/${a}/make`,{brief:n?{...e,...s?{references:s}:{}}:ct(e)});be=c.id,P.set(c.id,c),L.textContent="Directing your reel: reading the footage, choosing the story, cutting and checking it. You can keep working.",ut()}catch(s){L.textContent=s.message}}let Et=t("button",{type:"button",class:"btn primary wide",onclick:()=>Tt()},"Make it"),dt=t("div",{class:"make-status","aria-live":"polite"});function ut(){let e=be?P.get(be):null;W(dt),Et.disabled=!!e,e&&dt.append(t("p",{class:"note"},`Making the reel\u2026 ${e.progress??0}%`),R(e.progress??0,"Making the reel"))}let cn=t("div",{class:"make"},t("label",{for:"make-template",class:"sr-only"},"Template"),lt,t("label",{for:"make-format",class:"sr-only"},"Format"),fe,t("label",{for:"make-length",class:"sr-only"},"Length"),pe,t("label",{for:"make-captions",class:"sr-only"},"Captions"),Pe,t("label",{for:"make-grade",class:"sr-only"},"Colour look"),Le,t("label",{for:"make-music",class:"sr-only"},"Music"),X,t("label",{for:"make-voice",class:"sr-only"},"Voice"),Ae,t("div",{class:"extras",role:"group","aria-label":"Extras"},qe.el,it.el,Ge.el),kt,Qe,t("div",{class:"row tight"},Te,Fe,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:()=>Te.click()},"+ Reference")),Et,dt),be=null;async function dn(){if(!be)return;let e=(await I("GET","/jobs")).jobs.find(s=>s.id===be);if(e&&P.set(e.id,e),ut(),!e||!["done","failed","canceled"].includes(e.status))return;if(be=null,ut(),e.status!=="done")return L.textContent=e.error??"The reel stopped.";let n=JSON.parse(e.output);L.textContent=`${on[n.verdict]??n.verdict}. ${n.notes.join(" ")}`,n.file&&Be.prepend(t("li",{class:"watch"},t("button",{type:"button",class:"btn primary",onclick:()=>ke("finish")},"Watch the final cut")));for(let s of[...n.changes].reverse())Be.prepend(t("li",{},s))}let He=t("button",{type:"button",class:"btn primary",onclick:()=>Oe({type:"toggle"})},"Play"),jt=t("select",{class:"field small select","aria-label":"Preview shape",onchange:()=>S.setShape(b())},["project","16:9","9:16"].map(e=>t("option",{value:e},e==="project"?"Project shape":e))),Pt=t("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>S.setZoom(Number(Pt.value))}),Lt=t("input",{type:"checkbox",id:"guides",onchange:()=>S.setGuides(Lt.checked)});function Oe(e){if(!e)return;if(e.type==="mode")return ke(e.mode);if(e.type==="prompt")return oe.focus();if(e.type==="mark")return v(),e.edge==="in"||Z===null?(Z=S.time,ne=null):S.time>Z?ne=S.time:(ne=Z,Z=S.time),L.textContent=ne===null?`Marked in at ${ye(Z)}. Play to the end of the stretch and press O.`:`Marked ${ye(Z)} to ${ye(ne)}. Tell Kriya what to do with it.`,We();if(e.type==="undo")return I("PATCH",`/projects/${a}`,{undo:!0}).then(r);if(e.type==="redo")return L.textContent="Redo isn't here yet.";if(e.type==="split"){let h=ve(o,S.time);return h&&m([{op:"split",clip:h.clip,at:he(h,S.time)}])}if(e.type==="delete")return C.selected&&m([{op:"ripple_delete",clip:C.selected}]);let n={fps:g?f.find(h=>h.id===g).facts.fps??k():k(),duration:D()},s={t:S.time,rate:S.rate},c=Wt(s,e,n);c.rate!==s.rate&&S.setRate(c.rate),(c.t!==s.t||e.type==="seek")&&S.seek(c.t)}function ke(e){i=e,ae("kriya-edit-mode",i),Re.dataset.mode=i;for(let n of At.querySelectorAll("button"))n.setAttribute("aria-pressed",String(n.dataset.mode===i));C.draw(),B.draw(),i==="finish"&&y.refresh().catch(()=>{})}let At=t("div",{class:"modes",role:"group","aria-label":"Mode"},Vt.map((e,n)=>t("button",{type:"button",class:"btn",dataset:{mode:e},"aria-pressed":"false","aria-keyshortcuts":String(n+1),onclick:()=>ke(e)},e[0].toUpperCase()+e.slice(1)))),we={min:300,step:32},pt=()=>Math.max(we.min,Math.min(960,Math.round(window.innerWidth*.62))),ft=()=>document.querySelector(".area-kriya")?.getBoundingClientRect().width??0;function Ue(e){if(e===null)Re.style.removeProperty("--side"),ae("kriya-side-width","");else{let n=Math.round(Math.min(pt(),Math.max(we.min,e)));Re.style.setProperty("--side",`${n}px`),ae("kriya-side-width",String(n))}ee.setAttribute("aria-valuenow",String(Math.round(ft()))),C.draw(),B.draw()}let ee=t("div",{class:"side-handle",role:"separator",tabindex:"0","aria-orientation":"vertical","aria-label":"Resize the Kriya panel","aria-valuemin":String(we.min),title:"Drag to resize. Double-click to fit the window.",onpointerdown:e=>{e.preventDefault(),ee.setPointerCapture(e.pointerId);let n=document.querySelector(".area-kriya").getBoundingClientRect().right,s=h=>Ue(n-h.clientX),c=()=>(ee.removeEventListener("pointermove",s),ee.removeEventListener("pointerup",c),ee.removeEventListener("pointercancel",c));ee.addEventListener("pointermove",s),ee.addEventListener("pointerup",c),ee.addEventListener("pointercancel",c)},ondblclick:()=>Ue(null),onkeydown:e=>{let n={ArrowLeft:we.step,ArrowRight:-we.step}[e.key];n?(e.preventDefault(),e.stopPropagation(),Ue(ft()+n)):e.key==="Home"&&(e.preventDefault(),Ue(null))}}),Re=t("div",{class:"workspace"},zt(t("span",{class:"project-name"},u.name),At),t("div",{class:"banner"},L,nt),t("div",{class:"grid"},t("div",{class:"area-bin"},Ce,t("section",{class:"panel refs","aria-label":"Style references"},t("h2",{},"References"),De,Xe,t("button",{type:"button",class:"btn wide",onclick:()=>Te.click()},"Add a reference\u2026"))),t("section",{class:"area-monitor panel","aria-label":"Monitor"},t("div",{class:"monitor-frame"},A),t("div",{class:"transport"},He,l,x,jt,sn,t("label",{class:"inline"},Lt," Safe zones"),t("label",{class:"inline"},"Zoom ",Pt))),t("aside",{class:"area-kriya panel","aria-label":"Kriya"},ee,t("h2",{},"Direct"),cn,t("h2",{},"Chat with Kriya"),xt,at,an,t("p",{class:"note small"},"Say times like 0:05 or mark a stretch with I and O. Enter sends."),t("h2",{},"What I did"),Be),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."),_),t("div",{class:"area-strip"},J),t("section",{class:"area-timeline panel","aria-label":"Timeline"},Y),t("div",{class:"area-finish"},z),K));W(yt).append(Re);let Ot=Number(ae("kriya-side-width"));Ot>=we.min&&Re.style.setProperty("--side",`${Math.min(pt(),Ot)}px`),ke(i),ee.setAttribute("aria-valuemax",String(pt())),ee.setAttribute("aria-valuenow",String(Math.round(ft()))),window.onkeydown=e=>{let n=e.target.closest?.("input, select, textarea");if(n&&e.key!=="Escape")return;if(e.key==="Escape")return n?document.activeElement?.blur():(w.clear(),C.select(null),Z=ne=null,We());let s=Bt(e.key,{shift:e.shiftKey,mod:e.metaKey||e.ctrlKey});s&&(s.type==="toggle"&&e.target.closest?.("button")&&e.target!==He||(e.preventDefault(),Oe(s)))},setInterval(()=>i==="finish"&&y.scopes(),250);let Rt=new EventSource("/events");Rt.addEventListener("job",e=>{let n=null;try{n=JSON.parse(e.data)}catch{}n?.id&&P.set(n.id,n),i==="finish"&&y.refresh().catch(()=>{}),dn().catch(()=>{}),n&&["pending","running"].includes(n.status)?G():r().catch(()=>{})}),Rt.addEventListener("setup",e=>{try{Ke({...se??{},setup:JSON.parse(e.data)})}catch{}se?.setup?.finished&&I("GET","/runtime").then(Ke).catch(()=>{})}),I("GET","/runtime").then(Ke).catch(()=>{}),await r(),window.__studio={monitor:S,act:Oe,reload:r,setMode:ke,get pieces(){return o}}}function Jt(){let a=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);a?bn(a[1]):Yt()}window.addEventListener("hashchange",Jt);Jt();
5
+ Kriya measures it as numbers: ${o}. No picture, sound or words from it go into your video. Add only what you're allowed to use this way.`)&&oe(e,{reference:!0,aspect:s})}});function Lt(e,s){let o=e.path.split(/[\\/]/).at(-1),a=e.facts.width?e.facts.duration?"video":"image":"music",i=t("input",{type:"checkbox",id:`use-${s}-${e.id}`,checked:me.has(e.id),onchange:()=>(i.checked?me.add(e.id):me.delete(e.id),Ie(i.id))}),l=Ae.get(e.id),S=rt(e.id),O=t("ul",{class:"ref-lines"},...l?ls(l,S).map(I=>t("li",{},I)):[t("li",{class:"note"},"Measuring\u2026")]),M=lt({id:`aspect-${s}-${e.id}`,"aria-label":`Take from ${o}`},S,I=>(le(Ge(e.id),I.target.value),Ie(I.target.id)));return t("li",{class:"asset ref"},t("button",{type:"button",class:"btn",onclick:()=>e.facts.duration&&L(e.id,0)},`${o} \xB7 ${a}`),t("label",{class:"note small",for:`aspect-${s}-${e.id}`},"Take from it"),M,O,t("label",{class:"inline",for:`use-${s}-${e.id}`},i," Use in the cut"))}function Ie(e=null){q(He),q(dt);let s=m.filter(i=>i.kind==="reference");s.length||He.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 i of s)Et.has(i.id)||(Et.add(i.id),me.add(i.id)),He.append(Lt(i,"bin")),dt.append(Lt(i,"direct")),Ae.has(i.id)||(Ae.set(i.id,null),B("GET",`/projects/${n}/references/${encodeURIComponent(i.id)}`).then(l=>(Ae.set(i.id,l),Ie())).catch(l=>(Ae.set(i.id,{lines:[`Couldn't measure it: ${l.message}`]}),Ie())));xs(),e&&document.getElementById(e)?.focus(),((i,l,S)=>{let O=i.value;q(i).append(t("option",{value:""},S),...l.map(M=>t("option",{value:M.id},M.path.split(/[\\/]/).at(-1)))),i.value=l.some(M=>M.id===O)?O:""})(ne,m.filter(i=>i.kind==="audio"&&!/kriya-music-/.test(i.path)),"No music");let a=ne.value;ne.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)")),ne.options[1]??null),/^generated:/.test(Qe)?ne.value=Qe:a&&(ne.value=a)}let ce=null,ve=t("p",{class:"note"}),ut=t("div"),pt=t("button",{type:"button",class:"btn primary",onclick:()=>B("POST","/runtime/setup").then(ze).catch(e=>ve.textContent=e.message)},"Set up speech-to-text"),ft=t("section",{class:"panel setup","aria-label":"Speech-to-text setup",hidden:!0},t("h2",{},"Speech-to-text"),ve,ut,pt),Ot=e=>(e/1e6).toLocaleString(void 0,{maximumFractionDigits:0});function ze(e){ce=e;let s=ce.setup,o=s&&!s.finished;if(ft.hidden=!ce.speech&&!o&&!s?.error,pt.hidden=!!o,pt.textContent=s?.error?"Try again":"Set up speech-to-text",q(ut),o){let a=s.total?Math.round(s.done*100/s.total):null;ve.textContent=s.total?`Downloading ${s.step}: ${Ot(s.done)} of ${Ot(s.total)} MB (${a}%)`:s.line??"Setting up\u2026",ut.append(F(a,"Media Runtime setup"))}else s?.error?ve.textContent=`Setup stopped: ${s.error}`:ce.speech?ve.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&&(ve.textContent="Ready. Index a file to read its words.")}let de=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"}),ht=t("span",{class:"chip selection",hidden:!0}),At=t("ol",{class:"chat","aria-label":"Chat with Kriya","aria-live":"polite"}),Ve=t("ul",{class:"did","aria-label":"What I did"}),xe=[],se=null,re=null,$e=e=>{let s=Math.max(0,e)/7056e5,o=Math.floor(s/60);return`${o}:${(s-o*60).toFixed(1).padStart(4,"0")}`},Rt=()=>{if(se!==null&&re!==null&&re>se)return{selection:{from:se,to:re},label:`Marked ${$e(se)}\u2013${$e(re)}`};let e=v.selection();return e?{selection:{words:e},label:`Selected: ${f.words.find(s=>s.id===e[0])?.text??""}${e[0]===e[1]?"":" \u2026"}`}:E.selected?{selection:{clip:E.selected},label:`Selected: clip ${E.selected}`}:se!==null?{selection:{at:se},label:`Marked in at ${$e(se)} (press O for the end)`}:{selection:{at:T.time},label:null}},Ye=()=>{let{label:e}=Rt();ht.hidden=!e,ht.textContent=e??""};J.addEventListener("click",()=>setTimeout(Ye));function mt(e){let s=[],o=0;for(let a of String(e).matchAll(/\b(\d{1,2}):(\d{2}(?:\.\d+)?)\b/g)){s.push(e.slice(o,a.index));let i=Math.round((Number(a[1])*60+Number(a[2]))*7056e5);s.push(t("button",{type:"button",class:"time-link",title:"Play from here",onclick:()=>(x(),T.seek(Math.min(i,Math.max(0,_e(r)-1))))},a[0])),o=a.index+a[0].length}return s.push(e.slice(o)),s}function ge(e,s,...o){let a=t("li",{class:`msg ${e}`},t("span",{class:"who"},e==="you"?"You":"Kriya"),t("p",{},...mt(s)),...o);return At.append(a),a.scrollIntoView({block:"nearest"}),a}function cs(e){E.setGhost(e.timeline),H.setGhost(e.timeline);let s=t("div",{class:"proposal"}),o=async(a,i)=>{try{let l=await B("POST",`/projects/${n}/proposals/${e.id}`,{accept:a,...i?{only:i}:{}});if(N.textContent=l.dropped.length?`Not applied, because you changed that part: ${l.dropped.map(S=>S.change).join("; ")}.`:a?"Done. Undo with Cmd+Z.":"Left as it was.",a)for(let S of i?i.map(O=>e.changes[O]):e.changes)Ve.prepend(t("li",{},S));q(s).append(t("p",{class:"note"},a?l.dropped.length?"Partly applied.":"Applied.":"Not applied."))}catch(l){N.textContent=l.message}E.setGhost(null),H.setGhost(null),await c()};return s.append(t("p",{class:"lead"},"Proposed, not applied yet"),t("ul",{},e.changes.map((a,i)=>t("li",{},t("span",{},...mt(a)),e.changes.length>1?t("button",{type:"button",class:"btn",onclick:()=>o(!0,[i])},"Only this"):null))),t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>o(!0)},e.changes.length>1?"Accept all":"Accept"),t("button",{type:"button",class:"btn",onclick:()=>o(!1)},"Reject"))),s}let Ne=null,ds=()=>({...kt(),...Ke.value==="clean"?{cleanVoice:!0}:{}}),It=e=>f.words.find(s=>s.id===e)?.text??e,Je=e=>`${Math.floor(e/60)}:${(e%60).toFixed(1).padStart(4,"0")}`,Nt=null;function Se(e={}){return[Nt,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 "${It(e.coldOpen.from)} \u2026 ${It(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.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(o=>`${Je(o.from)}\u2013${Je(o.to)}`).join(", ")} of the take`:null].filter(Boolean).join(" \xB7 ")}function us(e,s){let o=e.sceneChoices??{kinds:{},themes:{},swaps:[]},a=e.settings.format??ue.value,l=a==="16:9"?{w:1920,h:1080,show:200}:a==="1:1"?{w:1080,h:1080,show:150}:a==="4:5"?{w:1080,h:1350,show:136}:{w:1080,h:1920,show:120},S=e.settings.scenes.map(($,U)=>({scene:$,swaps:o.swaps[U]??[$.kind]})),O=t("ul",{class:"scene-list"}),M=()=>{e.settings.scenes=S.map($=>$.scene),S.length?e.brief.scenes=e.settings.scenes:delete e.brief.scenes,s()},I=$=>`/projects/${n}/scene-preview?format=${encodeURIComponent(a)}&scene=${encodeURIComponent(JSON.stringify($))}`,K=$=>{let U=z=>Je(z/7056e5),X=f.words?.find(z=>z.id===$.from),Q=f.words?.find(z=>z.id===$.to);return X&&Q?`${U(X.start)}\u2013${U(Q.end)}`:""},pe=()=>{q(O),S.length||O.append(t("li",{class:"note small"},"No animated scenes: the speaker stays on screen."));for(let $ of S){let U=t("iframe",{title:`Preview of the scene "${$.scene.title||$.scene.items[0].text}"`,sandbox:"allow-scripts",loading:"lazy",src:I($.scene)});U.style.width=`${l.w}px`,U.style.height=`${l.h}px`,U.style.transform=`scale(${l.show/l.w})`;let X=t("div",{class:"scene-picture"},U);X.style.width=`${l.show}px`,X.style.height=`${Math.round(l.show*l.h/l.w)}px`;let Q=t("select",{class:"field select","aria-label":"Draw this scene as",onchange:()=>($.scene={...$.scene,kind:Q.value},M(),U.src=I($.scene))},$.swaps.map(z=>t("option",{value:z},o.kinds[z]??z)));Q.value=$.scene.kind,O.append(t("li",{class:"scene-row"},X,t("div",{class:"scene-info"},t("p",{class:"small"},t("span",{class:"scene-time"},K($.scene)),` ${$.scene.title||$.scene.items[0].text}`),t("p",{class:"note small"},$.scene.items.map(z=>`${z.text}${z.value!==void 0?` ${z.value}${z.unit??""}`:""}`).join(" \xB7 ")),t("div",{class:"row"},Q,t("button",{type:"button",class:"btn",onclick:()=>U.src=I($.scene)},"Play again"),t("button",{type:"button",class:"btn",onclick:()=>(S.splice(S.indexOf($),1),M(),pe())},"Keep the speaker")))))}},qe=t("select",{class:"field select","aria-label":"Look of the scenes",onchange:()=>{for(let $ of S)$.scene={...$.scene,theme:qe.value};M(),pe()}},Object.entries(o.themes).map(([$,U])=>t("option",{value:$},U)));return qe.value=S[0].scene.theme,pe(),t("div",{class:"scenes"},t("div",{class:"row scene-head"},t("p",{class:"lead"},"Animated scenes"),qe),O)}function ps(e,s){let o=e.graphicChoices??{kinds:{},styles:{},accents:[],tones:[],fonts:[]},a=e.settings.format??ue.value,i=a==="16:9"?{w:1920,h:1080,show:200}:a==="1:1"?{w:1080,h:1080,show:150}:a==="4:5"?{w:1080,h:1350,show:136}:{w:1080,h:1920,show:120},l=[...e.settings.graphics],S=t("ul",{class:"scene-list"}),O=()=>{e.settings.graphics=l,l.length?e.brief.graphics=l:delete e.brief.graphics,s()},M=$=>`/projects/${n}/graphic-preview?format=${encodeURIComponent(a)}&graphic=${encodeURIComponent(JSON.stringify($))}`,I=$=>{let U=$.at&&f.words?.find(X=>X.id===$.at);return $.kind==="intro"?"start":$.kind==="end"?"end":U?Je(U.start/7056e5):""},K=()=>{q(S),l.length||S.append(t("li",{class:"note small"},"No motion graphics.")),l.forEach(($,U)=>{let X=o.kinds[$.kind]??{label:$.kind,styles:[$.style]},Q=t("iframe",{title:`Preview of the ${X.label.toLowerCase()} "${$.text}"`,sandbox:"allow-scripts",loading:"lazy",src:M($)});Q.style.width=`${i.w}px`,Q.style.height=`${i.h}px`,Q.style.transform=`scale(${i.show/i.w})`;let z=t("div",{class:"scene-picture graphic-picture"},Q);z.style.width=`${i.show}px`,z.style.height=`${Math.round(i.show*i.h/i.w)}px`;let st=X.styles.length>1?t("select",{class:"field select","aria-label":`Style of the ${X.label.toLowerCase()}`,onchange:()=>(l[U]={...l[U],style:st.value},O(),Q.src=M(l[U]))},X.styles.map(nt=>t("option",{value:nt},o.styles[nt]??nt))):null;st&&(st.value=$.style),S.append(t("li",{class:"scene-row"},z,t("div",{class:"scene-info"},t("p",{class:"small"},t("span",{class:"scene-time"},I($)),` ${X.label}`),t("p",{class:"note small"},[$.text,$.subtitle].filter(Boolean).join(" \xB7 ")),t("div",{class:"row"},st,t("button",{type:"button",class:"btn",onclick:()=>Q.src=M(l[U])},"Play again"),t("button",{type:"button",class:"btn",onclick:()=>(l=l.filter((nt,Cs)=>Cs!==U),O(),K())},"Remove")))))})},pe=($,U,X)=>{let Q=t("select",{class:"field select","aria-label":X,onchange:()=>(l=l.map(z=>({...z,[$]:Q.value})),O(),K())},U.map(z=>t("option",{value:z},`${X}: ${z}`)));return Q.value=l[0][$],Q},qe=t("div",{class:"row"},pe("accent",o.accents,"Colour"),pe("tone",o.tones,"Plate"),pe("font",o.fonts,"Font"));return K(),t("div",{class:"scenes"},t("p",{class:"lead"},"Motion graphics"),qe,S)}function fs(e,s){let o=t("ul",{class:"scene-list"}),a=()=>{e.brief.pictures=e.settings.pictures.map(({from:l,to:S,id:O})=>({from:l,to:S,id:O})),e.brief.pictures.length||delete e.brief.pictures,s()},i=()=>{q(o),e.settings.pictures.length||o.append(t("li",{class:"note small"},"No pictures: the speaker stays on screen."));for(let l of e.settings.pictures){let S=()=>l.options.find(K=>K.id===l.id)??l.options[0],O=t("img",{class:"found-thumb",alt:S().title,loading:"lazy",src:`/projects/${n}/found-thumb?id=${encodeURIComponent(l.id)}`}),M=t("p",{class:"note small"},`${S().licence} \xB7 ${S().creator}`),I=t("select",{class:"field select","aria-label":"Use this picture",onchange:()=>{l.id=I.value,O.src=`/projects/${n}/found-thumb?id=${encodeURIComponent(l.id)}`,O.alt=S().title,M.textContent=`${S().licence} \xB7 ${S().creator}`,a()}},l.options.map(K=>t("option",{value:K.id},K.title.slice(0,60))));I.value=l.id,o.append(t("li",{class:"scene-row"},O,t("div",{class:"scene-info"},t("p",{class:"small"},l.query),M,t("div",{class:"row"},I,t("button",{type:"button",class:"btn",onclick:()=>{e.settings.pictures.splice(e.settings.pictures.indexOf(l),1),a(),i()}},"Keep the speaker")))))}};return i(),t("div",{class:"scenes"},t("p",{class:"lead"},"Real pictures"),o)}function hs(e,s){let o=t("ul",{class:"scene-list"}),a=()=>{q(o);for(let i of e.settings.terms)o.append(t("li",{class:"scene-row"},t("div",{class:"scene-info"},t("p",{class:"small"},t("b",{},i.term),` \u201C${i.quote}\u201D ${i.source}`),t("button",{type:"button",class:"btn",onclick:()=>{e.settings.terms.splice(e.settings.terms.indexOf(i),1),e.brief.terms=e.settings.terms.map(({at:l,id:S,term:O})=>({at:l,id:S,term:O})),e.brief.terms.length||delete e.brief.terms,s(),a()}},"Don't show this"))))};return a(),t("div",{class:"scenes"},t("p",{class:"lead"},"Definitions"),o)}function ms(e,s){let o={clean:"Clean",karaoke:"Karaoke",boxed:"Boxed",pop:"Pop",story:"Story",minimal:"Minimal"},a={"#ffd23f":"Yellow","#ffb347":"Amber","#4fd1c5":"Teal","#ff7ab6":"Pink","#ffffff":"White"},i=t("select",{class:"field select","aria-label":"Caption look",onchange:()=>{e.brief.captions=i.value,e.settings.captions=i.value,s()}},Object.entries(o).map(([S,O])=>t("option",{value:S},O)));i.value=e.brief.captions;let l=t("select",{class:"field select","aria-label":"Highlight colour",onchange:()=>{l.value?e.brief.captionStyle={accent:l.value}:delete e.brief.captionStyle,e.settings.captionStyle=e.brief.captionStyle,s()}},[t("option",{value:""},"Look's own colour"),...Object.entries(a).map(([S,O])=>t("option",{value:S},O))]);return l.value=e.brief.captionStyle?.accent??"",t("div",{class:"scenes"},t("p",{class:"lead"},"Captions"),t("div",{class:"row"},i,l))}function gs(e){Nt=e.genreLabel?`reads as: ${e.genreLabel}`:null;let s=t("p",{class:"note small"},Se(e.settings)),o=t("div",{class:"proposal plan"},t("p",{class:"lead"},e.revises?"A change to your current cut, not made yet":"The Director's plan, not made yet"),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,e.steps.length?t("ol",{class:"steps"},e.steps.map(a=>t("li",{},...mt(a)))):null,s,e.settings.scenes?.length?us(e,()=>s.textContent=Se(e.settings)):null,e.settings.graphics?.length?ps(e,()=>s.textContent=Se(e.settings)):null,e.settings.pictures?.length?fs(e,()=>s.textContent=Se(e.settings)):null,e.settings.terms?.length?hs(e,()=>s.textContent=Se(e.settings)):null,e.brief.captions?ms(e,()=>s.textContent=Se(e.settings)):null,t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>(Ne=null,bs(e.brief),q(o).append(t("p",{class:"note"},`Approved. Making it now in ${e.brief.format??ue.value}; the progress is in Direct.`)),Ft(e.brief,{exact:!0,plan:e}))},"Approve and make it"),t("button",{type:"button",class:"btn",onclick:()=>(Ne=e,de.focus(),de.placeholder="Say what to change in the plan\u2026")},"Change\u2026")));return o}function bs(e={}){e.format&&(ue.value=e.format);let s=e.seconds?String(e.seconds):"";s&&![...we.options].some(o=>o.value===s)&&we.append(t("option",{value:s},`${s} seconds`)),we.value=s,De.value=e.captions??"",Fe.value=e.grade??"",/^generated:/.test(e.music??"")&&[...ne.options].some(o=>o.value===e.music)?ne.value=e.music:e.music||(ne.value=""),Ke.value=e.cleanVoice?"clean":"",Ze.box.checked=!!e.angles,yt.box.checked=e.broll==="own",Xe.box.checked=!!e.titles,wt.value=""}async function Dt(e,s=null){let o=ge("kriya",s?"Revising the plan\u2026":"Planning the cut\u2026");try{let a=await B("POST",`/projects/${n}/plan`,{text:e,history:xe.slice(-6),previous:s,choices:ds()});o.remove(),Ne=a,ge("kriya",a.say||"Here's my plan.",gs(a)),xe.push({who:"kriya",text:(a.say||"").slice(0,400)})}catch(a){o.remove(),ge("kriya",a.message)}}async function gt({planning:e=!1}={}){let s=de.value.trim();if(!s)return;if(de.placeholder='Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',Ne||e)return ge("you",s),xe.push({who:"you",text:s.slice(0,400)}),de.value="",Dt(s,Ne);let{selection:o,label:a}=Rt();ge("you",a?`${s} (${a.replace(/^Selected: /,"on ")})`:s),de.value="";let i=ge("kriya","Thinking about that\u2026");try{let l=await B("POST",`/projects/${n}/ask`,{text:s,selection:o,history:xe.slice(-6)});i.remove();let S=l.say||(l.proposal?"Here's what I'd change.":l.direct?"That's about the whole video.":l.reason??"I couldn't turn that into an edit. Try saying it another way.");if(xe.push({who:"you",text:s.slice(0,400)}),l.direct&&!l.proposal)return Dt(s);ge("kriya",S,l.proposal?cs(l.proposal):null),xe.push({who:"kriya",text:S.slice(0,400)})}catch(l){i.remove(),ge("kriya",l.status===0||l.status>=500?"I can't reach Kriya right now, so I can't make changes by asking. You can still edit by hand.":l.message)}}de.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),gt())});let ys=t("form",{class:"prompt",onsubmit:e=>(e.preventDefault(),gt())},t("label",{for:"prompt",class:"sr-only"},"Message Kriya"),de,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:()=>gt({planning:!0})},"Plan"))),ws=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:()=>Be({type:"mark",edge:"in"})},"Mark in"),t("button",{type:"button",class:"btn","aria-keyshortcuts":"O",title:"Mark out (O)",onclick:()=>Be({type:"mark",edge:"out"})},"Mark out")),ks={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",not_checked:"Not checked"},we=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))),De=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))),ne=t("select",{id:"make-music",class:"field select"}),ue=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))),Fe=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))),Ke=t("select",{id:"make-voice",class:"field select"},[["","Voice: as recorded"],["clean","Voice: remove background noise"]].map(([e,s])=>t("option",{value:e},s))),bt=(e,s)=>{let o=t("input",{type:"checkbox",id:e});return{box:o,el:t("label",{class:"inline",for:e},o,` ${s}`)}},Ze=bt("make-angles","Angles (wide and tight)"),yt=bt("make-broll","B-roll from my clips"),Xe=bt("make-titles","Title cards"),Qe="";ne.addEventListener("change",()=>Qe=ne.value);let vs={"":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}},wt=t("select",{id:"make-template",class:"field select",onchange:()=>{let e=vs[wt.value];e&&(ue.value=e.format,De.value=e.captions,Fe.value=e.grade,we.value=e.length,Ke.value=e.voice,Ze.box.checked=!!e.angles,Xe.box.checked=!!e.titles,ne.value=Qe=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))),xs=()=>{let e=m.filter(o=>o.kind==="reference"&&me.has(o.id)),s=[...new Set(e.map(o=>rt(o.id)))].map(o=>o==="all"?"everything":ye[o].split(":")[0].toLowerCase());Pt.textContent=e.length?`${e.length} reference${e.length===1?"":"s"} in use, for ${s.join(", ")}.`:"No references in use."},kt=(e={})=>({...we.value?{seconds:Number(we.value)}:{},...De.value?{captions:De.value}:{},...ne.value?{music:ne.value}:{},...me.size?{references:[...me].filter(s=>m.some(o=>o.id===s&&o.kind==="reference")).map(s=>({id:s,aspect:rt(s)}))}:{},format:ue.value,...Fe.value?{grade:Fe.value}:{},...Ke.value==="clean"?{cleanVoice:!0}:{},...Ze.box.checked?{angles:!0}:{},...yt.box.checked?{broll:"own"}:{},...Xe.box.checked?{titles:!0}:{},...e});async function Ft(e,{exact:s=!1,plan:o=null}={}){try{let a=kt().references,i=await B("POST",`/projects/${n}/make`,{brief:s?{...e,...a?{references:a}:{}}:kt(e),...o?{plan:{say:o.say,steps:o.steps,settings:o.settings}}:{}});Ce=i.id,R.set(i.id,i),N.textContent="Directing your reel: reading the footage, choosing the story, cutting and checking it. You can keep working.",xt()}catch(a){N.textContent=a.message}}let Kt=t("button",{type:"button",class:"btn primary wide",onclick:()=>Ft()},"Make it"),vt=t("div",{class:"make-status","aria-live":"polite"});function xt(){let e=Ce?R.get(Ce):null;q(vt),Kt.disabled=!!e,e&&vt.append(t("p",{class:"note"},`Making the reel\u2026 ${e.progress??0}%`),F(e.progress??0,"Making the reel"))}let $s=t("div",{class:"make"},t("label",{for:"make-template",class:"sr-only"},"Template"),wt,t("label",{for:"make-format",class:"sr-only"},"Format"),ue,t("label",{for:"make-length",class:"sr-only"},"Length"),we,t("label",{for:"make-captions",class:"sr-only"},"Captions"),De,t("label",{for:"make-grade",class:"sr-only"},"Colour look"),Fe,t("label",{for:"make-music",class:"sr-only"},"Music"),ne,t("label",{for:"make-voice",class:"sr-only"},"Voice"),Ke,t("div",{class:"extras",role:"group","aria-label":"Extras"},Ze.el,yt.el,Xe.el),Pt,dt,t("div",{class:"row tight"},Re,Ue,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:()=>Re.click()},"+ Reference")),Kt,vt),Ce=null;async function Ss(){if(!Ce)return;let e=(await B("GET","/jobs")).jobs.find(o=>o.id===Ce);if(e&&R.set(e.id,e),xt(),!e||!["done","failed","canceled"].includes(e.status))return;if(Ce=null,xt(),e.status!=="done")return N.textContent=e.error??"The reel stopped.";let s=JSON.parse(e.output);N.textContent=`${ks[s.verdict]??s.verdict}. ${s.notes.join(" ")}`,s.file&&Ve.prepend(t("li",{class:"watch"},t("button",{type:"button",class:"btn primary",onclick:()=>Me("finish")},"Watch the final cut")));for(let o of[...s.changes].reverse())Ve.prepend(t("li",{},o))}let et=t("button",{type:"button",class:"btn primary",onclick:()=>Be({type:"toggle"})},"Play"),Bt=t("select",{class:"field small select","aria-label":"Preview shape",onchange:()=>T.setShape(w())},["project","16:9","9:16"].map(e=>t("option",{value:e},e==="project"?"Project shape":e))),Wt=t("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>T.setZoom(Number(Wt.value))}),qt=t("input",{type:"checkbox",id:"guides",onchange:()=>T.setGuides(qt.checked)});function Be(e){if(!e)return;if(e.type==="mode")return Me(e.mode);if(e.type==="prompt")return de.focus();if(e.type==="mark")return x(),e.edge==="in"||se===null?(se=T.time,re=null):T.time>se?re=T.time:(re=se,se=T.time),N.textContent=re===null?`Marked in at ${$e(se)}. Play to the end of the stretch and press O.`:`Marked ${$e(se)} to ${$e(re)}. Tell Kriya what to do with it.`,Ye();if(e.type==="undo")return B("PATCH",`/projects/${n}`,{undo:!0}).then(c);if(e.type==="redo")return N.textContent="Redo isn't here yet.";if(e.type==="split"){let i=Te(r,T.time);return i&&g([{op:"split",clip:i.clip,at:ke(i,T.time)}])}if(e.type==="delete")return E.selected&&g([{op:"ripple_delete",clip:E.selected}]);let s={fps:b?m.find(i=>i.id===b).facts.fps??k():k(),duration:_()},o={t:T.time,rate:T.rate},a=Xt(o,e,s);a.rate!==o.rate&&T.setRate(a.rate),(a.t!==o.t||e.type==="seek")&&T.seek(a.t)}function Me(e){d=e,le("kriya-edit-mode",d),We.dataset.mode=d;for(let s of _t.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.mode===d));E.draw(),H.draw(),d==="finish"&&y.refresh().catch(()=>{})}let _t=t("div",{class:"modes",role:"group","aria-label":"Mode"},os.map((e,s)=>t("button",{type:"button",class:"btn",dataset:{mode:e},"aria-pressed":"false","aria-keyshortcuts":String(s+1),onclick:()=>Me(e)},e[0].toUpperCase()+e.slice(1)))),je={min:300,step:32},$t=()=>Math.max(je.min,Math.min(960,Math.round(window.innerWidth*.62))),St=()=>document.querySelector(".area-kriya")?.getBoundingClientRect().width??0;function tt(e){if(e===null)We.style.removeProperty("--side"),le("kriya-side-width","");else{let s=Math.round(Math.min($t(),Math.max(je.min,e)));We.style.setProperty("--side",`${s}px`),le("kriya-side-width",String(s))}ae.setAttribute("aria-valuenow",String(Math.round(St()))),E.draw(),H.draw()}let ae=t("div",{class:"side-handle",role:"separator",tabindex:"0","aria-orientation":"vertical","aria-label":"Resize the Kriya panel","aria-valuemin":String(je.min),title:"Drag to resize. Double-click to fit the window.",onpointerdown:e=>{e.preventDefault(),ae.setPointerCapture(e.pointerId);let s=document.querySelector(".area-kriya").getBoundingClientRect().right,o=i=>tt(s-i.clientX),a=()=>(ae.removeEventListener("pointermove",o),ae.removeEventListener("pointerup",a),ae.removeEventListener("pointercancel",a));ae.addEventListener("pointermove",o),ae.addEventListener("pointerup",a),ae.addEventListener("pointercancel",a)},ondblclick:()=>tt(null),onkeydown:e=>{let s={ArrowLeft:je.step,ArrowRight:-je.step}[e.key];s?(e.preventDefault(),e.stopPropagation(),tt(St()+s)):e.key==="Home"&&(e.preventDefault(),tt(null))}}),We=t("div",{class:"workspace"},as(t("span",{class:"project-name"},h.name),_t),t("div",{class:"banner"},N,ft),t("div",{class:"grid"},t("div",{class:"area-bin"},Oe,t("section",{class:"panel refs","aria-label":"Style references"},t("h2",{},"References"),He,ct,t("button",{type:"button",class:"btn wide",onclick:()=>Re.click()},"Add a reference\u2026"))),t("section",{class:"area-monitor panel","aria-label":"Monitor"},t("div",{class:"monitor-frame"},D),t("div",{class:"transport"},et,u,C,Bt,ws,t("label",{class:"inline"},qt," Safe zones"),t("label",{class:"inline"},"Zoom ",Wt))),t("aside",{class:"area-kriya panel","aria-label":"Kriya"},ae,t("h2",{},"Direct"),$s,t("h2",{},"Chat with Kriya"),At,ht,ys,t("p",{class:"note small"},"Say times like 0:05 or mark a stretch with I and O. Enter sends."),t("h2",{},"What I did"),Ve),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."),J),t("div",{class:"area-strip"},te),t("section",{class:"area-timeline panel","aria-label":"Timeline"},ee),t("div",{class:"area-finish"},Z),G));q(Tt).append(We);let Gt=Number(le("kriya-side-width"));Gt>=je.min&&We.style.setProperty("--side",`${Math.min($t(),Gt)}px`),Me(d),ae.setAttribute("aria-valuemax",String($t())),ae.setAttribute("aria-valuenow",String(Math.round(St()))),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():(v.clear(),E.select(null),se=re=null,Ye());let o=Zt(e.key,{shift:e.shiftKey,mod:e.metaKey||e.ctrlKey});o&&(o.type==="toggle"&&e.target.closest?.("button")&&e.target!==et||(e.preventDefault(),Be(o)))},setInterval(()=>d==="finish"&&y.scopes(),250);let Ut=new EventSource("/events");Ut.addEventListener("job",e=>{let s=null;try{s=JSON.parse(e.data)}catch{}s?.id&&R.set(s.id,s),d==="finish"&&y.refresh().catch(()=>{}),Ss().catch(()=>{}),s&&["pending","running"].includes(s.status)?Y():c().catch(()=>{})}),Ut.addEventListener("setup",e=>{try{ze({...ce??{},setup:JSON.parse(e.data)})}catch{}ce?.setup?.finished&&B("GET","/runtime").then(ze).catch(()=>{})}),B("GET","/runtime").then(ze).catch(()=>{}),await c(),window.__studio={monitor:T,act:Be,reload:c,setMode:Me,get pieces(){return r}}}function rs(){let n=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);n?Os(n[1]):is()}window.addEventListener("hashchange",rs);rs();