@kriya-ai/harness 0.2.2 → 0.2.4

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