@kriya-ai/harness 0.2.2 → 0.2.3

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.
@@ -5,6 +5,7 @@
5
5
  // the lines to drop; the emphasis words), each with a default that needs no model.
6
6
 
7
7
  import { apply } from "../core/ops.js"
8
+ import { solve } from "../core/solver.js"
8
9
  import { LOOKS, pages } from "../engine/captions.js"
9
10
  import { paperEdit } from "../index/views.js"
10
11
 
@@ -22,11 +23,50 @@ export const REEL_TALKING_HEAD = {
22
23
  notes: "Recipe: a talking-head reel for phones. The first sentence must work on its own as a hook. Keep the speaker's meaning; drop only lines that repeat or wander.",
23
24
  }
24
25
 
25
- const STRUCK = new Set(["filler", "stutter", "restart"])
26
+ const STRUCK = new Set(["filler", "stutter", "restart", "trimmed"])
27
+
28
+ const clock = (t) => { const s = Math.round(t / (FLICKS / 10)) / 10; return `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}` }
29
+
30
+ /**
31
+ * The person's trims ("remove everything after 0:25"): each word whose middle falls inside a
32
+ * stretch is marked `trimmed`, so the cut lands between words, never inside one (QG-05).
33
+ * @param {{ from: number, to: number }[]} cuts source flicks of `asset`
34
+ */
35
+ export function trimIndex(index, asset, cuts = []) {
36
+ if (!cuts.length) return { index, trimmed: 0 }
37
+ let trimmed = 0
38
+ const inside = (w) => cuts.some((c) => (w.start + w.end) / 2 >= c.from && (w.start + w.end) / 2 < c.to)
39
+ const words = index.words.map((w) => (w.asset === asset && inside(w) ? (trimmed++, { ...w, flags: [...w.flags, "trimmed"] }) : w))
40
+ return { index: { ...index, words }, trimmed }
41
+ }
42
+
43
+ /** Templates' frames: the reel's 9:16 by default; the same cut also makes a landscape, square or 4:5 film. */
44
+ export const FORMATS = {
45
+ "9:16": { width: 1080, height: 1920, preset: "reel-9x16" },
46
+ "16:9": { width: 1920, height: 1080, preset: "landscape-16x9" },
47
+ "1:1": { width: 1080, height: 1080, preset: "square-1x1" },
48
+ "4:5": { width: 1080, height: 1350, preset: "portrait-4x5" },
49
+ }
50
+
51
+ /** Colour looks as FFmpeg renders them: eq, colortemperature, vibrance and vignette. Data, applied by code. */
52
+ export const GRADES = {
53
+ vivid: { saturation: 1.15, gain: 1.06, vibrance: 0.35 },
54
+ cinematic: { saturation: 0.9, gain: 1.12, gamma: 0.95, temperature: 7200, vignette: 0.45 },
55
+ warm: { temperature: 5200, saturation: 1.05, vibrance: 0.2, vignette: 0.2 },
56
+ bright: { lift: 0.04, gamma: 1.1, vibrance: 0.2 },
57
+ mono: { saturation: 0, gain: 1.1, vignette: 0.3 },
58
+ }
59
+
60
+ /** The recipe in the brief's frame: canvas and export follow `brief.format`. */
61
+ export function recipeFor(brief = {}) {
62
+ const format = FORMATS[brief.format] ?? FORMATS["9:16"]
63
+ const base = REEL_TALKING_HEAD
64
+ return { ...base, canvas: { width: format.width, height: format.height }, deliverable: { ...base.deliverable, preset: format.preset, size: { width: format.width, height: format.height } } }
65
+ }
26
66
 
27
67
  /** The recipe's deliverable; with captions asked for, they burn in and the text gates run (ED8). */
28
68
  export function deliverableFor(brief = {}) {
29
- const base = REEL_TALKING_HEAD.deliverable
69
+ const base = recipeFor(brief).deliverable
30
70
  return LOOKS[brief.captions] ? { ...base, burnCaptions: true, gates: [...base.gates, "QG-08", "QG-09", "QG-10"].sort() } : base
31
71
  }
32
72
 
@@ -112,9 +152,12 @@ const EMPHASIS_SCHEMA = { type: "object", properties: { emphasis: { type: "array
112
152
  * @param {{ project: object, index: object, asset: string, ask: Function, brief?: object, variant?: { tighter?: number, noHook?: boolean }, signal?: AbortSignal }} input
113
153
  * @returns {Promise<{ ops: object[], project: object, notes: string[], calls: number, slots: Record<string, string> }>}
114
154
  */
115
- export async function planReel({ project, index, asset, ask, brief = {}, variant = {}, signal }) {
116
- const recipe = REEL_TALKING_HEAD
155
+ export async function planReel({ project, index: fullIndex, asset, ask, brief = {}, variant = {}, signal }) {
156
+ const recipe = recipeFor(brief)
117
157
  const notes = []
158
+ const cuts = (brief.cuts ?? []).filter((c) => Number.isFinite(c.from) && Number.isFinite(c.to) && c.to > c.from)
159
+ const { index, trimmed } = trimIndex(fullIndex, asset, cuts)
160
+ if (cuts.length) notes.push(`Trimmed ${cuts.map((c) => `${clock(c.from)} to ${clock(c.to)}`).join(", ")} of the take, as you asked (${trimmed} word${trimmed === 1 ? "" : "s"}, cut between words).`)
118
161
  const slots = {}
119
162
  let calls = 0
120
163
  const lines = candidateLines(index, asset, brief.picks)
@@ -137,7 +180,9 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
137
180
  calls += story.calls
138
181
  slots.story = story.source
139
182
  if (story.reason) notes.push(`Story: ${story.reason} Kept every line, in order.`)
140
- const hook = variant.noHook ? null : story.value.hook
183
+ // A hook the person approved in the Director's plan wins over the model's pick
184
+ const planned = typeof brief.hook === "string" && lines.some((l) => l.id === brief.hook) ? brief.hook : null
185
+ const hook = variant.noHook ? null : (planned ?? story.value.hook)
141
186
  let chosen = lines.filter((l) => !story.value.drop.includes(l.id) || mustKeep.includes(l.id))
142
187
 
143
188
  // Length: fit under the maximum, the hook and must-keeps always in
@@ -145,20 +190,37 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
145
190
  const required = new Set([...mustKeep, ...(hook ? [hook] : [])])
146
191
  if (chosen.reduce((sum, l) => sum + lengthOf(l), 0) > max) chosen = fitLines(chosen, max, required)
147
192
  const total = chosen.reduce((sum, l) => sum + lengthOf(l), 0)
148
- if (total < recipe.target.min) notes.push(`The footage gives ${(total / FLICKS).toFixed(1)} s of usable speech, under the ${recipe.target.min / FLICKS} s the recipe aims for.`)
193
+ // Short footage sets the length: a 29 s take makes a 29 s cut, not a cut that "needs you"
194
+ // for missing a 30 s target nobody can meet (found in use)
195
+ const asked = brief.targetDuration ?? recipe.target.default
196
+ const target = total > 0 && total < asked ? total : asked
197
+ if (target < asked) notes.push(`The footage gives ${(total / FLICKS).toFixed(1)} s of usable speech, so the cut is that long (you asked for about ${Math.round(asked / FLICKS)} s).`)
149
198
  if (hook && chosen.some((l) => l.id === hook)) chosen = [chosen.find((l) => l.id === hook), ...chosen.filter((l) => l.id !== hook)]
150
199
  if (hook && chosen[0]?.id === hook && lines[0]?.id !== hook) notes.push(`Moved "${hook}" to the front as the hook.`)
151
200
 
152
201
  // The cut: replace whatever is there with the kept runs
153
202
  const sequence = project.sequences.find((q) => q.id === project.active)
154
203
  const base = new Set(sequence.tracks.filter((t) => t.role === "base").map((t) => t.id))
204
+ // The last cut's captions and music go with it: they hang on its words, and a second
205
+ // make left them all on screen twice (found in use, 2026-11-09)
206
+ const rebuilt = new Set(sequence.tracks.filter((t) => ["base", "caption", "music"].includes(t.role)).map((t) => t.id))
155
207
  const ops = [
156
- ...sequence.clips.filter((c) => base.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
157
- { op: "set_brief", format: recipe.id, targetDuration: brief.targetDuration ?? recipe.target.default, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
208
+ ...sequence.clips.filter((c) => rebuilt.has(c.track)).map((c) => ({ op: "ripple_delete", clip: c.id })),
209
+ { op: "set_brief", format: recipe.id, targetDuration: target, mustKeep: brief.mustKeep ?? [], mustCut: brief.mustCut ?? [], effort: brief.effort ?? "best", ...(brief.language ? { language: brief.language } : {}) },
158
210
  { op: "set_format", width: recipe.canvas.width, height: recipe.canvas.height, fps: recipe.deliverable.fps },
159
211
  ...(project.deliverables.some((d) => d.preset === recipe.deliverable.preset) ? [] : [{ op: "add_deliverable", ...deliverableFor(brief) }]),
160
212
  ]
161
213
  for (const line of chosen) for (const run of runsOf(line)) ops.push({ op: "keep_range", asset, from: { word: run[0].id, edge: "start" }, to: { word: run.at(-1).id, edge: "end" } })
214
+ // A cold open: a later moment first (an echo, so captions stay on the moment), in black and white
215
+ const takeWords = new Set(index.words.filter((w) => w.asset === asset).map((w) => w.id))
216
+ const cutOut = new Set(index.words.filter((w) => w.flags.includes("trimmed")).map((w) => w.id))
217
+ const coldTrimmed = brief.coldOpen && index.words.some((w) => cutOut.has(w.id) && w.asset === asset && w.start >= (index.words.find((x) => x.id === brief.coldOpen.from)?.start ?? Infinity) && w.end <= (index.words.find((x) => x.id === brief.coldOpen.to)?.end ?? -Infinity))
218
+ if (coldTrimmed) notes.push("No cold open: its moment is inside a stretch you asked to trim.")
219
+ const cold = !coldTrimmed && brief.coldOpen && takeWords.has(brief.coldOpen.from) && takeWords.has(brief.coldOpen.to) ? brief.coldOpen : null
220
+ if (cold) {
221
+ ops.push({ op: "cold_open", asset, from: { word: cold.from, edge: "start" }, to: { word: cold.to, edge: "end" }, mono: cold.mono !== false })
222
+ notes.push(`Opened cold on "${index.words.find((w) => w.id === cold.from).text} …"${cold.mono !== false ? " in black and white" : ""}, then the story starts.`)
223
+ }
162
224
  let step = apply(project, ops, { index, author: "agent" })
163
225
  if (!step.applied) throw new Error(`The reel's cut was refused: ${step.diagnostics[0].message}`)
164
226
 
@@ -182,13 +244,60 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
182
244
  if (emphasis.reason) notes.push(`Emphasis: ${emphasis.reason}`)
183
245
  const punches = [...new Set(emphasis.value.emphasis)].slice(0, most).map((id) => ({ op: "punch_in", at: { word: id, edge: "start" }, until: { word: id, edge: "end" }, scale: brief.zoom ?? recipe.punch.scale }))
184
246
 
185
- // Reframe to 9:16: follow the speaker where the index has one, else hold the centre
247
+ // Reframe to the template's frame: follow the speaker where the index has one, else hold
248
+ // the centre. A frame as wide as the take or wider keeps the whole picture
186
249
  const facts = project.assets.find((a) => a.id === asset).facts
187
250
  const cropWidth = Math.round((facts.height * recipe.canvas.width) / recipe.canvas.height)
251
+ const crops = cropWidth < facts.width
188
252
  const subject = (index.subjects?.[asset]?.length ?? 0) > 0
189
- if (!subject) notes.push("No face track for this take, so the frame holds the centre.")
253
+ if (crops && !subject) notes.push("No face track for this take, so the frame holds the centre.")
190
254
  const clips = step.project.sequences.find((q) => q.id === step.project.active).clips.filter((c) => base.has(c.track))
191
- const framing = clips.map((c) => (subject ? { op: "reframe", clip: c.id, mode: "subject" } : { op: "reframe", clip: c.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) }))
255
+ const framing = crops ? clips.map((c) => (subject ? { op: "reframe", clip: c.id, mode: "subject" } : { op: "reframe", clip: c.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) })) : []
256
+ // The template's colour look, on every picture clip
257
+ // The look on every story clip; a cold open keeps its own black and white
258
+ const look = GRADES[brief.grade] ?? (brief.customGrade && typeof brief.customGrade === "object" ? brief.customGrade : null)
259
+ const grading = look ? clips.filter((c) => !c.echo).map((c) => ({ op: "grade", clip: c.id, ...look })) : []
260
+ // Sound design: an effect on every cut of the story, a riser into it after a cold open.
261
+ // Each is placed by its peak, so the loudest moment lands on the cut
262
+ const storyClips = clips.filter((c) => !c.echo)
263
+ const cutSounds = brief.sfx?.cut ? storyClips.slice(1).map((c) => ({ op: "add_sfx", asset: brief.sfx.cut, peak_at: { clip: c.id, edge: "start" } })) : []
264
+ const introSound = brief.sfx?.intro && cold && storyClips[0] ? [{ op: "add_sfx", asset: brief.sfx.intro, peak_at: { clip: storyClips[0].id, edge: "start" } }] : []
265
+ const sounds = [...cutSounds, ...introSound]
266
+
267
+ // Angles: one camera cut like two, wide then tight on alternate story clips (a punch the
268
+ // length of the clip). Emphasis punch-ins come after, so they win on their own clips
269
+ const angles = brief.angles ? storyClips.filter((_, i) => i % 2 === 1).map((c) => ({ op: "punch_in", at: { clip: c.id, edge: "start" }, until: { clip: c.id, edge: "end" }, scale: 1.18 })) : []
270
+ // B-roll from the person's own other clips, over every other story clip after the first,
271
+ // 2.5 s or the clip's length, each from a new part of its source
272
+ const brollSources = brief.broll === "own" ? project.assets.filter((a) => a.kind === "video" && a.id !== asset && (a.facts.duration ?? 0) > FLICKS) : []
273
+ const pieces = solve(step.project, index).picture
274
+ const lengthOfClip = (id) => pieces.filter((p) => p.clip === id).reduce((sum, p) => sum + (p.end - p.at), 0)
275
+ const broll = brollSources.length
276
+ ? storyClips
277
+ .slice(1)
278
+ .filter((_, i) => i % 2 === 0)
279
+ .map((c, i) => {
280
+ const source = brollSources[i % brollSources.length]
281
+ const duration = Math.min(Math.round(2.5 * FLICKS), lengthOfClip(c.id))
282
+ const room = Math.max(0, source.facts.duration - duration)
283
+ const from = room ? Math.round((i * 3 * FLICKS) % room) : 0
284
+ return duration > FLICKS / 2 ? { op: "place_broll", asset: source.id, at: { clip: c.id, edge: "start" }, in: from, duration } : null
285
+ })
286
+ .filter(Boolean)
287
+ : []
288
+ if (brief.broll === "own" && !brollSources.length) notes.push("There's no other video in the bin, so the cut has no B-roll. Add clips to the bin and make it again.")
289
+ // Title cards: each emphasis word pops on screen, unless captions already carry the words
290
+ const titleWords = brief.titles && !LOOKS[brief.captions] ? [...new Set(emphasis.value.emphasis)].slice(0, most).map((wid) => index.words.find((w) => w.id === wid)).filter(Boolean) : []
291
+ if (brief.titles && LOOKS[brief.captions]) notes.push("Captions already put the words on screen, so there are no separate title cards.")
292
+ const titles = titleWords.map((w) => ({ op: "add_title", text: w.text.replace(/[^\p{L}\p{N}%$₹' -]/gu, "").toUpperCase().slice(0, 40) || w.text, at: { word: w.id, edge: "start" }, duration: Math.round(1.2 * FLICKS) }))
293
+ // A speed ramp out of the cold open: its last 1.2 s rushes up to 2× into the story
294
+ const coldClip = clips.find((c) => c.echo)
295
+ const coldEnd = cold && index.words.find((w) => w.id === cold.to)?.end
296
+ const coldStart = cold && index.words.find((w) => w.id === cold.from)?.start
297
+ const rampFrom = coldEnd ? Math.max(coldEnd - Math.round(1.2 * FLICKS), coldStart + Math.round((coldEnd - coldStart) / 3)) : 0
298
+ const ramps = brief.ramps && coldClip && coldEnd ? [{ op: "speed_ramp", clip: coldClip.id, from: rampFrom, to: coldEnd, peak: { n: 2, d: 1 } }] : []
299
+ // Background noise out of the voice: FFmpeg's own denoise, EQ, de-ess and compression (clean_voice)
300
+ const cleaning = brief.cleanVoice ? clips.map((c) => ({ op: "clean_voice", clip: c.id, strength: 0.6 })) : []
192
301
 
193
302
  // Captions, when the brief asks for a look: pages of the kept words, timed to the speech
194
303
  const captions = LOOKS[brief.captions] ? chosen.flatMap((l) => runsOf(l)).flatMap((run) => pages(run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
@@ -196,7 +305,7 @@ export async function planReel({ project, index, asset, ask, brief = {}, variant
196
305
  const song = brief.music ? project.assets.find((a) => a.id === brief.music && a.kind === "audio") : null
197
306
  if (brief.music && !song) notes.push(`There is no sound "${brief.music}" in this project, so the reel has no music.`)
198
307
  const music = song ? [{ op: "set_music", asset: song.id }, { op: "music_shape", fit: true, fadeIn: Math.round(FLICKS * 0.3) }, { op: "duck" }] : []
199
- const all = [...ops, ...punches, ...framing, ...captions, ...music]
308
+ const all = [...ops, ...angles, ...punches, ...framing, ...grading, ...cleaning, ...broll, ...titles, ...captions, ...music, ...sounds, ...ramps]
200
309
  step = apply(project, all, { index, author: "agent" })
201
310
  if (!step.applied) throw new Error(`The reel was refused: ${step.diagnostics[0].message}`)
202
311
  return { ops: all, project: step.project, notes, calls, slots }
@@ -107,10 +107,14 @@ a { color: var(--teal); }
107
107
  .projects { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }
108
108
 
109
109
  .workspace { display: flex; flex-direction: column; min-height: 100%; }
110
- .grid { flex: 1; display: grid; gap: 12px; padding: 12px; min-height: 0; grid-template-columns: minmax(0, 1fr) 320px; grid-template-areas: "monitor kriya" "transcript transcript" "strip strip"; align-content: start; }
110
+ /* --side: the Kriya panel's width; it fits the window unless the person drags it (main.js) */
111
+ .grid { flex: 1; display: grid; gap: 12px; padding: 12px; min-height: 0; grid-template-columns: minmax(0, 1fr) min(var(--side, clamp(340px, 32vw, 560px)), 62vw); grid-template-areas: "monitor kriya" "transcript transcript" "strip strip"; align-content: start; }
111
112
  .area-bin { grid-area: bin; }
112
113
  .area-monitor { grid-area: monitor; background: var(--surround); color: #eee; }
113
- .area-kriya { grid-area: kriya; }
114
+ .area-kriya { grid-area: kriya; position: relative; }
115
+ .side-handle { position: absolute; left: -12px; top: 0; bottom: 0; width: 12px; cursor: col-resize; touch-action: none; border-radius: 6px; }
116
+ .side-handle::after { content: ""; position: absolute; left: 4px; top: 50%; width: 4px; height: 48px; margin-top: -24px; border-radius: 999px; background: var(--edge); }
117
+ .side-handle:hover::after, .side-handle:focus-visible::after { background: var(--teal); }
114
118
  .area-transcript { grid-area: transcript; }
115
119
  .area-strip { grid-area: strip; }
116
120
  .area-timeline { grid-area: timeline; }
@@ -118,7 +122,15 @@ a { color: var(--teal); }
118
122
  .workspace[data-mode="direct"] :is(.area-bin, .area-timeline, .area-finish) { display: none; }
119
123
  .workspace[data-mode="edit"] .grid { grid-template-columns: 280px minmax(0, 1fr) 320px; grid-template-areas: "bin monitor transcript" "timeline timeline timeline"; }
120
124
  .workspace[data-mode="edit"] :is(.area-kriya, .area-strip, .area-finish) { display: none; }
121
- .workspace[data-mode="finish"] .grid { grid-template-columns: minmax(0, 1fr) 360px; grid-template-areas: "monitor finish"; }
125
+ .area-final { grid-area: final; display: none; }
126
+ .workspace[data-mode="finish"] .area-final { display: block; }
127
+ .workspace[data-mode="finish"] .grid { grid-template-columns: minmax(0, 1fr) 360px; grid-template-areas: "final finish" "monitor finish"; }
128
+ .final-film { width: 100%; max-height: 62vh; background: #000; border-radius: 8px; display: block; }
129
+ .final .row { margin-top: 8px; }
130
+ .final .row select { flex: 1 1 220px; width: auto; min-width: 0; max-width: 100%; }
131
+ .final .note.stale { color: var(--saffron); }
132
+ .final [hidden] { display: none; }
133
+ .did li.watch::before { content: none; }
122
134
  .workspace[data-mode="finish"] :is(.area-bin, .area-kriya, .area-transcript, .area-strip, .area-timeline) { display: none; }
123
135
 
124
136
  .monitor-frame { display: flex; justify-content: center; align-items: center; min-height: 200px; }
@@ -181,11 +193,43 @@ a { color: var(--teal); }
181
193
 
182
194
  /* Review mode under 760 px (UX_SPEC §12): preview, Kriya, export. No timeline, no bin */
183
195
  @media (max-width: 760px) {
184
- .grid, .workspace[data-mode] .grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "monitor" "kriya" "transcript" "finish"; padding: 8px; }
196
+ .grid, .workspace[data-mode] .grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "final" "monitor" "kriya" "transcript" "finish"; padding: 8px; }
185
197
  .workspace[data-mode] :is(.area-bin, .area-timeline, .area-strip) { display: none; }
186
198
  .workspace[data-mode="edit"] .area-kriya { display: block; }
187
199
  .modes { margin-left: 0; width: 100%; }
200
+ .side-handle { display: none; }
188
201
  .modes .btn { flex: 1; }
189
202
  .monitor { max-height: 50vh; }
190
203
  }
204
+ /* Home: a project's row with its delete; the folder picker */
205
+ .project-row { display: flex; gap: 8px; align-items: center; }
206
+ .project-row .open { flex: 1; justify-content: flex-start; }
207
+ .btn.danger { color: var(--error); }
208
+ .picker { width: min(560px, 92vw); max-height: 80vh; border: 0; border-radius: 14px; padding: 18px; background: var(--sheet); color: var(--ink); box-shadow: 0 12px 40px rgb(0 0 0 / 0.35); display: grid; gap: 10px; }
209
+ .picker::backdrop { background: rgb(0 0 0 / 0.45); }
210
+ .picker .where { word-break: break-all; color: var(--ink-2); margin: 0; }
211
+ .folders { list-style: none; padding: 0; margin: 0; display: grid; gap: 4px; max-height: 46vh; overflow: auto; }
212
+ .btn.folder { width: 100%; justify-content: flex-start; }
213
+ .row.end { justify-content: flex-end; }
214
+
215
+ /* Chat with Kriya */
216
+ .chat { list-style: none; padding: 0; margin: 0 0 8px; display: grid; gap: 8px; max-height: 58vh; overflow: auto; }
217
+ .chat:empty { display: none; }
218
+ .msg { padding: 8px 10px; border-radius: 10px; background: var(--hover); }
219
+ .msg.you { background: color-mix(in srgb, var(--teal) 14%, transparent); }
220
+ .msg .who { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-2); }
221
+ .msg p { margin: 2px 0 0; white-space: pre-wrap; }
222
+ .msg .proposal { margin-top: 8px; }
223
+ .chat-input { min-height: 64px; padding: 10px 12px; resize: vertical; line-height: 1.4; }
224
+ .prompt { align-items: flex-end; }
225
+ .time-link { font: inherit; font-family: ui-monospace, "JetBrains Mono", monospace; font-size: 0.92em; color: var(--teal); background: none; border: 0; padding: 0 2px; min-height: 24px; text-decoration: underline; cursor: pointer; }
226
+ .marks { display: inline-flex; gap: 6px; }
227
+ .send { display: grid; gap: 6px; }
228
+ .extras { display: flex; flex-wrap: wrap; gap: 0 14px; }
229
+ .plan .steps { margin: 4px 0; padding-left: 20px; display: grid; gap: 4px; }
230
+ .refs-direct { margin: 0; }
231
+ .refs-direct:empty { display: none; }
232
+ .ref .ref-lines { list-style: none; padding: 0; margin: 2px 0; font-size: 13px; color: var(--ink-2); display: grid; gap: 2px; }
233
+ .area-monitor .marks .btn { background: #2a2a2a; color: #eee; }
234
+
191
235
  @media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
@@ -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(a,d={},...u){let f=document.createElement(a);for(let[p,o]of Object.entries(d??{}))o==null||o===!1||(p.startsWith("on")?f.addEventListener(p.slice(2),o):p==="class"?f.className=o:p==="dataset"?Object.assign(f.dataset,o):o===!0?f.setAttribute(p,""):f.setAttribute(p,String(o)));for(let p of u.flat())p!=null&&p!==!1&&f.append(p instanceof Node?p:String(p));return f}var W=a=>(a.replaceChildren(),a);async function I(a,d,u){let f=await fetch(d,{method:a,headers:u===void 0?{}:{"content-type":"application/json"},body:u===void 0?void 0:JSON.stringify(u),credentials:"same-origin"}),p=await f.json().catch(()=>({}));if(!f.ok){let o=new Error(p.message??`The Edit Host answered ${f.status}.`);throw o.status=f.status,o.value=p,o}return p}var pn=(a,d,u)=>.2126*a+.7152*d+.0722*u;function fn(a,d=128){let u=new Uint32Array(256),f=Array.from({length:d},()=>new Uint32Array(64)),{data:p,width:o,height:M}=a,g=Math.max(1,Math.floor(o*M/6e4));for(let i=0,$=0;$<o*M;$+=g,i=$*4){let k=Math.min(255,Math.round(pn(p[i],p[i+1],p[i+2])));u[k]++,f[Math.min(d-1,Math.floor($%o/o*d))][k>>2]++}return{histogram:u,waveform:f}}var hn={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you: a check failed",not_checked:"Not checked"};function It({root:a,finalRoot:d,pixels:u,project:f,onAdjust:p=()=>{}}){let o=t("video",{class:"final-film",controls:!0,preload:"metadata",playsinline:!0,"aria-label":"The final cut"}),M=t("p",{class:"note",role:"status"}),g=t("select",{id:"final-pick",class:"field select","aria-label":"Which film",onchange:()=>x()}),i=t("a",{class:"btn primary",href:"#",download:"",hidden:!0},"Download"),$=[],k=y=>`/projects/${f().id}/renders/${y.job}`,l=y=>y?new Date(y).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";function x(){let y=$.find(r=>String(r.job)===g.value)??$[0];if(!y){o.removeAttribute("src"),o.hidden=!0,i.hidden=!0,g.hidden=!0,M.textContent="No film yet. Render a draft and the finished cut plays here, captions, look, music and sound included.";return}o.hidden=!1,g.hidden=$.length<2;let v=k(y);o.getAttribute("src")!==v&&(o.src=v),i.hidden=!1,i.href=`${v}?download=1`,i.setAttribute("download",y.name);let T=y.current?"This is your edit as it is now.":"Made before your latest changes: render a draft to see them.";M.textContent=`${T}${y.verdict?` ${hn[y.verdict]??y.verdict}.`:""}`,M.classList.toggle("stale",!y.current)}let A=0,L=0;async function S(){let y=++A,v=(await I("GET",`/projects/${f().id}/renders`)).renders;if(y!==A)return;let T=g.value;$=v;let r=$[0]?.job??0;W(g).append(...$.map(m=>t("option",{value:String(m.job)},`${m.quality==="draft"?"Draft":"Master"} \xB7 ${l(m.at)}${m.current?" \xB7 current":""} \xB7 ${m.name}`))),g.value=String(r>L||!$.some(m=>String(m.job)===T)?r:T),L=Math.max(L,r),x()}d.append(t("section",{class:"panel final","aria-label":"Final cut"},t("h2",{},"Final cut"),o,M,t("div",{class:"row"},g,i,t("button",{type:"button",class:"btn",onclick:()=>J("draft")},"Render again"),t("button",{type:"button",class:"btn",onclick:p},"Adjust in Edit"))));let b=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma histogram"}),N=t("canvas",{class:"scope",width:256,height:100,role:"img","aria-label":"Luma waveform"}),D=t("ul",{class:"jobs","aria-live":"polite"}),_=t("p",{class:"note",role:"status"}),J=async y=>{_.textContent="";try{await I("POST","/jobs",{project:f().id,quality:y}),K()}catch(v){_.textContent=v.message}},Y=t("p",{class:"note",role:"status"}),z=t("ul",{class:"jobs","aria-label":"Handoff files"}),w=async()=>{Y.textContent="",W(z);try{let y=await I("POST",`/projects/${f().id}/export/handoff`),v=y.chapters.length,T=v?`, ${v} chapter${v===1?"":"s"}`:"";Y.textContent=`Written to ${y.folder}, with ${y.media} media file${y.media===1?"":"s"} linked${T}.`;for(let r of y.files)z.append(t("li",{},t("span",{class:"file"},r)));for(let r of y.omitted)z.append(t("li",{},t("span",{class:"label-mono"},r.format),` ${r.reason}`))}catch(y){Y.textContent=y.message}};a.append(t("section",{class:"panel scopes","aria-label":"Scopes"},t("h2",{},"Scopes"),t("div",{class:"scope-row"},t("figure",{},b,t("figcaption",{},"Histogram")),t("figure",{},N,t("figcaption",{},"Waveform"))),t("p",{class:"note"},"Measured on the preview: 8-bit, from the proxy.")),t("section",{class:"panel export","aria-label":"Export"},t("h2",{},"Export"),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:()=>J("draft")},"Render a draft"),t("button",{type:"button",class:"btn primary",onclick:()=>J("master")},"Render the master")),t("p",{class:"note"},"Files go to the exports folder beside the project. Sources are never written."),_,D),t("section",{class:"panel handoff","aria-label":"Handoff"},t("h2",{},"Handoff"),t("p",{class:"note"},"For Premiere, Resolve or Final Cut: the cut as OTIO, FCPXML, EDL and SRT, with chapters, and the media linked beside them."),t("div",{class:"row"},t("button",{type:"button",class:"btn",onclick:w},"Export for another editor")),Y,z));function C(y,v){let T=y.getContext("2d");T.clearRect(0,0,y.width,y.height),T.fillStyle=getComputedStyle(a).getPropertyValue("--scope").trim()||"#6cc0b8",v(T)}function B(){let y=u();if(!y)return;let{histogram:v,waveform:T}=fn(y),r=Math.max(1,...v);C(b,m=>v.forEach((j,P)=>m.fillRect(P,100-j/r*100,1,j/r*100))),C(N,m=>T.forEach((j,P)=>j.forEach((q,R)=>{q&&(m.globalAlpha=Math.min(1,.15+q/200),m.fillRect(P*2,100-R/64*100-2,2,2))})))}async function K(){S().catch(v=>M.textContent=v.message);let{jobs:y}=await I("GET","/jobs");W(D);for(let v of y.filter(T=>T.project===f().id&&T.kind==="render").reverse().slice(0,8)){let T=v.output?v.output.split(/[\\/]/).at(-1):null;D.append(t("li",{},t("span",{class:"label-mono"},v.status),` ${v.progress}%`,T?t("span",{class:"file"},` ${T}`):null,v.error?t("span",{class:"error"},` ${v.error}`):null))}}return{scopes:B,refresh:K}}var Nt=a=>typeof a=="number"?{n:a,d:1}:a??{n:1,d:1},Ft=a=>[...a?.picture??[]].sort((d,u)=>d.at-u.at),ht=a=>[{clip:null,asset:a.id,in:0,out:a.facts.duration,at:0,end:a.facts.duration,speed:{n:1,d:1}}],ve=(a,d)=>a.find(u=>d>=u.at&&d<u.end)??(a.length&&d>=a.at(-1).end?a.at(-1):null);function he(a,d){if(a.hold)return a.in;let{n:u,d:f}=Nt(a.speed);return Math.min(a.out,a.in+Math.round((d-a.at)*u/f))}function Ve(a,d,u){for(let f of a){if(f.asset!==d||f.hold||u<f.in||u>=f.out)continue;let{n:p,d:o}=Nt(f.speed);return f.at+Math.round((u-f.in)*o/p)}return null}var Ie=a=>a.length?Math.max(...a.map(d=>d.end)):0;function Dt(a,d){let u=[];for(let f of d){let p=Ve(a,f.asset,f.start);p!==null&&p>0&&u.push({id:f.id,at:p})}return u}var re=a=>7056e5*a.d/a.n,Kt=(a,d)=>Math.floor(a/re(d)+1e-9),ze=(a,d)=>Math.round(Kt(a,d)*re(d));function xe(a,d){let u=Math.max(0,a)/7056e5,f=Math.floor(u/60),p=Math.floor(u%60),o=Kt(Math.max(0,a)-Math.floor(u)*7056e5,d);return`${String(f).padStart(2,"0")}:${String(p).padStart(2,"0")}.${String(o).padStart(2,"0")}`}function Bt(a,{shift:d=!1,mod:u=!1}={}){if(u)return a==="z"||a==="Z"?{type:d?"redo":"undo"}:null;switch(a){case" ":return{type:"toggle"};case"k":case"K":return{type:"rate",rate:0};case"l":case"L":return{type:"faster"};case"j":case"J":return{type:"reverse"};case"ArrowRight":return{type:"step",frames:d?null:1,seconds:d?1:null};case"ArrowLeft":return{type:"step",frames:d?null:-1,seconds:d?-1:null};case"Home":return{type:"seek",t:0};case"1":return{type:"mode",mode:"direct"};case"2":return{type:"mode",mode:"edit"};case"3":return{type:"mode",mode:"finish"};case"/":return{type:"prompt"};case"s":case"S":return{type:"split"};case"Backspace":case"Delete":return{type:"delete"};case"i":case"I":return{type:"mark",edge:"in"};case"o":case"O":return{type:"mark",edge:"out"};default:return null}}function Wt(a,d,{fps:u,duration:f}){let p=Math.max(0,f-re(u)),o=M=>Math.min(Math.max(0,Math.round(M)),p);switch(d.type){case"toggle":return{...a,rate:a.rate===0?1:0};case"rate":return{...a,rate:d.rate};case"faster":return{...a,rate:a.rate<=0?1:2};case"reverse":return{...a,rate:a.rate>=0?-1:-2};case"step":{let M=d.frames!==null?d.frames*re(u):d.seconds*7056e5;return{rate:0,t:o(ze(a.t,u)+M)}}case"seek":return{...a,t:o(d.t)};case"tick":{let M=o(d.t);return{t:M,rate:M===0&&a.rate<0||M===p&&a.rate>0?0:a.rate}}default:return a}}var mn=1280;function qt({canvas:a,urlOf:d,assetOf:u,onTime:f,onRate:p}){let o=a.getContext("2d",{willReadFrequently:!0}),M=new Map,g=[],i={n:30,d:1},$=0,k=0,l=0,x={width:1920,height:1080},A=1,L=!1,S=0,b=null;function N(r){let m=g[r],j=`${m.asset}:${r%2}`;if(!M.has(j)){let P=document.createElement("video");Object.assign(P,{muted:!0,preload:"auto",playsInline:!0,crossOrigin:"anonymous",src:d(m.asset)}),M.set(j,P)}return M.get(j)}function D(r,m){let j=u(r.asset)?.facts?.fps??i;return(m+re(j)/2)/7056e5}function _(){let r=Math.min(1,mn/Math.max(x.width,x.height)),m=Math.round(x.width*r),j=Math.round(x.height*r);(a.width!==m||a.height!==j)&&Object.assign(a,{width:m,height:j})}function J(r,m,j){_();let{width:P,height:q}=a;if(o.fillStyle="#000",o.fillRect(0,0,P,q),r?.videoWidth){let R=Math.max(P/r.videoWidth,q/r.videoHeight)*A,G=r.videoWidth*R,te=r.videoHeight*R;o.drawImage(r,(P-G)/2,(q-te)/2,G,te),b={asset:m.asset,source:j}}if(L){o.strokeStyle="rgb(255 255 255 / 0.55)",o.setLineDash([6,6]),o.lineWidth=1;for(let R of[.05,.1])o.strokeRect(P*R,q*R,P*(1-2*R),q*(1-2*R));o.setLineDash([])}}let Y=()=>{_(),o.fillStyle="#000",o.fillRect(0,0,a.width,a.height),b=null},z=0,w=Promise.resolve();function C(r){let m=g.indexOf(ve(g,r));if(m<0)return Promise.resolve(Y());let j=g[m],P=he(j,r),q=N(m),R=D(j,P),G=++z,te=new Promise(Q=>{let ie=()=>{z===G&&J(q,j,P),Q()};if(q.readyState>=2&&Math.abs(q.currentTime-R)<1e-4)return ie();q.addEventListener("seeked",ie,{once:!0}),q.currentTime=R});if(w=te,g[m+1]){let Q=N(m+1);Q!==q&&(Q.currentTime=D(g[m+1],g[m+1].in))}return te}function B(){for(let r of M.values())r.pause(),r.muted=!0}function K(r,m=!0){k=Math.min(Math.max(0,r),Math.max(0,$-re(i))),m&&f(k)}function y(r){let m=g.indexOf(ve(g,k));if(m<0)return T(0);let j=(P,q)=>{let R=g[P],G=N(P);G.currentTime=D(R,he(R,q)),G.playbackRate=l,G.muted=!1;let{n:te,d:Q}=typeof R.speed=="object"?R.speed:{n:1,d:1},ie=($e,Se)=>{if(r!==S)return;let Ce=R.at+Math.round((Math.round(Se.mediaTime*7056e5)-R.in)*Q/te);if(Ce>=R.end-re(i)/2||G.ended)return G.pause(),G.muted=!0,g[P+1]?(m=P+1,K(g[m].at),j(m,g[m].at)):T(0);J(G,R,he(R,Ce)),K(Ce),G.requestVideoFrameCallback(ie)};G.requestVideoFrameCallback(ie),G.play().catch(()=>r===S&&T(0))};j(m,k)}function v(r){let m=performance.now(),j=async P=>{if(r===S){if(K(k-(P-m)/1e3*7056e5*Math.abs(l)),m=P,await C(k),k===0)return T(0);requestAnimationFrame(j)}};requestAnimationFrame(j)}function T(r){if(r===l&&r!==0)return;l=r;let m=++S;B(),p(l),l>0?y(m):l<0?v(m):(K(ze(k,i)),C(k))}return{load(r,{fps:m,duration:j,shape:P}){return g=r,i=m,$=j,P&&(x=P),++S,B(),l=0,p(0),K(Math.min(k,Math.max(0,$-re(i)))),C(k)},seek(r){return l!==0&&T(0),K(ze(r,i)),C(k)},setRate:T,get time(){return k},get rate(){return l},get shown(){return b},get settled(){return w},setShape(r){return x=r,C(k)},setZoom(r){return A=r,C(k)},setGuides(r){return L=r,C(k)},pixels:()=>a.width?o.getImageData(0,0,a.width,a.height):null}}var Gt=[{key:"picture",label:"Picture",colour:"--clip-picture"},{key:"overlays",label:"B-roll",colour:"--clip-broll"},{key:"audio",label:"Audio",colour:"--clip-audio"},{key:"captions",label:"Captions",colour:"--clip-caption"}],de=44,_t=6;function gt({root:a,compact:d=!1,onSeek:u,onSelect:f=()=>{}}){let p=d?Gt.slice(0,1):Gt,o=t("canvas",{class:"lanes","aria-hidden":"true"}),M=d?null:t("div",{class:"lane-labels","aria-hidden":"true"},p.map(w=>t("div",{class:"lane-label"},w.label))),g=t("ul",{class:"clip-list","aria-label":d?"Story":"Clips on the timeline"});a.append(...[M,t("div",{class:"lanes-wrap"},o),g].filter(Boolean));let i=o.getContext("2d"),$={picture:[],overlays:[],audio:[],captions:[]},k=0,l={n:30,d:1},x=0,A=[],L=[],S=new Map,b=null,N=null,D=w=>getComputedStyle(a).getPropertyValue(w).trim()||"#888";function _(){let w=Math.max(1,o.clientWidth),C=p.length*(de+_t),B=window.devicePixelRatio||1;(o.width!==Math.round(w*B)||o.height!==Math.round(C*B))&&(o.width=Math.round(w*B),o.height=Math.round(C*B),o.style.height=`${C}px`),i.setTransform(B,0,0,B,0,0),i.clearRect(0,0,w,C);let K=y=>k?y/k*w:0;p.forEach((y,v)=>{let T=v*(de+_t);i.fillStyle=D("--lane"),i.fillRect(0,T,w,de);for(let r of $[y.key]??[]){let m=K(r.at),j=Math.max(2,K(r.end)-m);i.fillStyle=D(y.colour),i.fillRect(m,T+2,j-1,de-4),r.clip&&r.clip===b&&(i.strokeStyle=D("--focus"),i.lineWidth=2,i.strokeRect(m+1,T+3,j-3,de-6));let P=y.key==="audio"||d&&y.key==="picture"?S.get(r.asset):null;if(P&&r.in!==void 0){i.fillStyle=D("--wave");let q=r.out-r.in;for(let R=0;R<j;R++){let G=(r.in+q*R/j)/7056e5,Q=(P.peaks[Math.floor(G*P.perSecond)]??0)*(de-8);i.fillRect(m+R,T+de/2-Q/2,1,Math.max(1,Q))}}}if(y.key==="picture"&&N){i.strokeStyle=D("--ghost"),i.setLineDash([5,4]),i.lineWidth=2;let r=Math.max(k,N.duration)||1;for(let m of N.picture)i.strokeRect(m.at/r*w+1,T+6,Math.max(2,(m.end-m.at)/r*w-2),de-12);i.setLineDash([])}if(y.key==="picture"){i.fillStyle=D("--shot");for(let r of A)i.fillRect(K(r.at)-.5,T,1,8)}}),i.fillStyle=D("--playhead");for(let y of L)i.fillRect(K(y.at)-1,0,3,8);i.fillStyle=D("--playhead"),i.fillRect(K(x)-1,0,2,C)}let J=!1,Y=w=>{let C=o.getBoundingClientRect();u(Math.round(Math.min(1,Math.max(0,(w.clientX-C.left)/C.width))*k))};o.addEventListener("pointerdown",w=>{J=!0,o.setPointerCapture(w.pointerId),Y(w)}),o.addEventListener("pointermove",w=>J&&Y(w)),o.addEventListener("pointerup",()=>J=!1),new ResizeObserver(_).observe(o);function z(w){b=w;for(let C of g.querySelectorAll("button"))C.setAttribute("aria-pressed",String(C.dataset.clip===w));f(w),_()}return{load(w,{duration:C,fps:B,marks:K=[],pins:y=[]}){L=y,$=w,k=C,l=B,A=K,b&&!$.picture.some(v=>v.clip===b)&&(b=null),W(g);for(let v of $.picture.filter((T,r,m)=>m.findIndex(j=>j.clip===T.clip)===r)){let T=t("button",{type:"button","aria-pressed":String(v.clip===b),dataset:{clip:v.clip},onclick:()=>(z(v.clip),u(v.at))},`Clip ${v.clip}, ${xe(v.at,l)} to ${xe(v.end,l)}`);g.append(t("li",{},T))}_()},setPeaks(w,C){S.set(w,C),_()},setGhost(w){N=w,_()},setTime(w){x=w,_()},select:z,get selected(){return b},draw:_}}var Ht=new Set(["filler","stutter","restart"]);function Ut({root:a,onSeek:d,onCut:u,onFix:f=async()=>{}}){let p=[],o=new Map,M=null,g=[],i=null,$=()=>{for(let l of a.querySelectorAll(".word[aria-pressed='true']"))l.setAttribute("aria-pressed","false");for(let l of g)a.querySelector(`[data-word="${CSS.escape(l)}"]`)?.setAttribute("aria-pressed","true")};a.addEventListener("click",l=>{let x=l.target.closest(".word");if(!x)return;let A=o.get(x.dataset.word);if(l.shiftKey&&M){let[L,S]=[p.indexOf(M),p.indexOf(A)].sort((b,N)=>b-N);g=p.slice(L,S+1).filter(b=>b.asset===A.asset).map(b=>b.id)}else M=A,g=[A.id],d(A);$()});function k(l){let x=o.get(l.dataset.word);if(!x)return;let A=t("input",{class:"word-edit",value:x.text,size:String(Math.max(4,x.text.length+2)),maxlength:"60","aria-label":`Fix the word "${x.text}"`});l.replaceWith(A),A.focus(),A.select();let L=!1,S=async b=>{if(L)return;L=!0;let N=A.value.trim();A.replaceWith(l),b&&N&&N!==x.text?await f(x,N):l.focus()};A.addEventListener("keydown",b=>{b.stopPropagation(),b.key==="Enter"?(b.preventDefault(),S(!0)):b.key==="Escape"&&(b.preventDefault(),S(!1))}),A.addEventListener("blur",()=>S(!0))}return a.addEventListener("dblclick",l=>{let x=l.target.closest(".word");x&&k(x)}),a.addEventListener("keydown",l=>{if(l.key==="F2"&&l.target.closest(".word"))return l.preventDefault(),l.stopPropagation(),k(l.target.closest(".word"));(l.key==="Backspace"||l.key==="Delete")&&g.length&&(l.preventDefault(),l.stopPropagation(),u(o.get(g[0]),o.get(g.at(-1))))}),{load({words:l=[],sentences:x=[],takes:A=[]}){p=l,o=new Map(l.map(b=>[b.id,b])),g=g.filter(b=>o.has(b));let L=new Map(A.map(b=>[b.sentence,b]));if(W(a),!l.length){a.append(t("p",{class:"note"},"No transcript yet. Index a clip in the bin to read its words."));return}let S=x.length?x:[...new Set(l.map(b=>b.asset))].map(b=>{let N=l.filter(D=>D.asset===b);return{id:null,asset:b,firstWord:N[0].id,lastWord:N.at(-1).id,score:1}});for(let b of S){let N=L.get(b.id),D=N&&N.rank>1||b.score===0,_=Number(b.firstWord.split(":w")[1]),J=Number(b.lastWord.split(":w")[1]),Y=t("p",{class:`sentence${D?" lost":""}`,dataset:b.id?{sentence:b.id}:{}});N&&Y.append(t("span",{class:"tag"},N.rank===1?"best take":`take ${N.rank}`));for(let z=_;z<=J;z++){let w=o.get(`${b.asset}:w${z}`);if(!w)continue;let C=D||w.flags.some(v=>Ht.has(v)),B=C?`${w.text} (${D?"retake":w.flags.filter(v=>Ht.has(v)).join(", ")})`:null,K=typeof w.heard=="string",y=t("button",{type:"button",class:`word${C?" struck":""}${!K&&w.flags.includes("low_confidence")?" unsure":""}${K?" fixed":""}`,"aria-pressed":"false","aria-label":B??(K?`${w.text} (fixed; heard as ${w.heard})`:null),title:K?`Heard as "${w.heard}". Double-click to change.`:"Double-click to fix this word",dataset:{word:w.id}});y.textContent=w.text,Y.append(y," ")}a.append(Y)}$()},playing(l){l!==i&&(a.querySelector(".word.now")?.classList.remove("now"),i=l,l&&a.querySelector(`[data-word="${CSS.escape(l)}"]`)?.classList.add("now"))},words:()=>p,selection:()=>g.length?[g[0],g.at(-1)]:null,clear(){g=[],M=null,$()}}}var yt=document.getElementById("app"),Vt=["direct","edit","finish"],ae=(a,d)=>{try{if(d===void 0)return localStorage.getItem(a);localStorage.setItem(a,d)}catch{return null}},gn=()=>{try{return sessionStorage.getItem("kriya-edit-back")}catch{return null}};function zt(...a){let d=gn();return t("header",{class:"bar"},d?t("a",{class:"btn ghost",href:d},"\u2190 Kriya Harness"):t("span",{class:"brand"},"Kriya"),t("span",{class:"title"},"Editing Studio"),...a)}function Ye(a){W(yt).append(t("main",{class:"center"},t("h1",{},"Open the Studio from Kriya"),t("p",{},a??"Click Editing Studio in Kriya Harness, or run kriya edit and open its link.")))}function yn(a){return new Promise(d=>{let u=t("ul",{class:"folders","aria-label":"Folders"}),f=t("p",{class:"label-mono where"}),p=t("p",{class:"note",role:"status"}),o=t("input",{class:"field",placeholder:"New folder name","aria-label":"New folder name",maxlength:"80"}),M=null,g=k=>{$.close(),$.remove(),d(k)};async function i(k){try{let l=await I("GET",`/browse${k?`?root=${encodeURIComponent(k)}`:""}`);M=l.root,f.textContent=l.root,W(u),l.parent&&u.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>i(l.parent)},"\u2191 Up")));let x=l.entries.filter(A=>A.kind==="folder");for(let A of x)u.append(t("li",{},t("button",{type:"button",class:"btn folder",onclick:()=>i(`${l.root}/${A.name}`)},`\u{1F4C1} ${A.name}`)));x.length||u.append(t("li",{class:"note"},"No folders here.")),p.textContent=""}catch(l){p.textContent=l.message}}let $=t("dialog",{class:"picker","aria-label":"Choose a folder"},t("h2",{},"Choose a folder"),f,u,t("form",{class:"row tight",onsubmit:async k=>{k.preventDefault();try{let{folder:l}=await I("POST","/browse/folder",{parent:M,name:o.value});o.value="",await i(l)}catch(l){p.textContent=l.message}}},o,t("button",{type:"submit",class:"btn"},"New folder")),p,t("div",{class:"row end"},t("button",{type:"button",class:"btn",onclick:()=>g(null)},"Cancel"),t("button",{type:"button",class:"btn primary",onclick:()=>g(M)},"Use this folder")));$.addEventListener("cancel",k=>(k.preventDefault(),g(null))),document.body.append($),$.showModal(),i(a)})}async function Yt(){let a;try{({projects:a}=await I("GET","/projects"))}catch(i){return i.status===401?Ye():Ye(i.message)}let d=t("input",{id:"new-name",class:"field",required:!0,placeholder:"Pricing reel",autocomplete:"off"}),u=t("input",{id:"new-folder",class:"field",required:!0,readonly:!0,placeholder:"Choose a folder\u2026"}),f=t("button",{type:"button",class:"btn",onclick:()=>yn(u.value||null).then(i=>i&&(u.value=i,p.textContent=""))},"Choose\u2026"),p=t("p",{class:"note",role:"status"}),o=t("form",{class:"panel new",onsubmit:async i=>{if(i.preventDefault(),!u.value)return p.textContent="Choose a folder for the project first.";try{let{id:$}=await I("POST","/projects",{name:d.value.trim(),folder:u.value.trim()});location.hash=`#/p/${$}`}catch($){p.textContent=$.message}}},t("h2",{},"New project"),t("label",{for:"new-name"},"Name"),d,t("label",{for:"new-folder"},"Folder for the project (its footage stays where it is)"),t("div",{class:"row tight"},u,f),t("button",{class:"btn primary",type:"submit"},"Create"),p),M=t("section",{class:"panel taste","aria-label":"Your taste"}),g=async i=>{let{proposed:$,confirmed:k}=i??await I("GET","/taste"),l=(x,A)=>async()=>g(await I("POST",`/taste/${encodeURIComponent(x)}/${A}`));W(M).append(t("h2",{},"Your taste"),...$.length||k.length?[]:[t("p",{class:"note"},"Nothing yet. When you make the same choice across projects, Kriya asks here before using it.")],...$.map(x=>t("div",{class:"taste-row"},t("p",{},x.sentence),t("button",{type:"button",class:"btn primary",onclick:l(x.key,"confirm")},"Use it"),t("button",{type:"button",class:"btn",onclick:l(x.key,"dismiss")},"No"))),...k.map(x=>t("div",{class:"taste-row"},t("p",{},x.shown),t("button",{type:"button",class:"btn","aria-label":`Remove the rule ${x.shown}`,onclick:l(x.key,"remove")},"Remove"))))};g().catch(()=>{}),W(yt).append(zt(),t("main",{class:"home"},t("h1",{},"What are we making?"),t("section",{class:"panel"},t("h2",{},"Projects"),a.length?t("ul",{class:"projects"},a.map(i=>t("li",{class:"project-row"},t("a",{class:"btn open",href:`#/p/${i.id}`},i.name),t("button",{type:"button",class:"btn ghost danger","aria-label":`Delete the project ${i.name}`,onclick:async()=>{if(confirm(`Delete "${i.name}" from the Studio?
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 I("DELETE",`/projects/${i.id}`),Yt()}catch($){alert($.message)}}},"Delete")))):t("p",{class:"note"},"No projects yet.")),o,M))}async function bn(a){let d;try{d=await I("GET",`/projects/${a}`)}catch(e){return e.status===401?Ye():Ye(e.message)}let u=d.project,f=d.assets,p={assets:[],words:[],sentences:[],takes:[],shots:[]},o=[],M={picture:[],overlays:[],audio:[],captions:[]},g=null,i=Vt.includes(ae("kriya-edit-mode"))?ae("kriya-edit-mode"):"direct",$=!1,k=()=>u.canvas.fps,l=t("span",{class:"time label-mono","aria-live":"off"},"00:00.00"),x=t("span",{class:"chip"},"Preview"),A=t("canvas",{class:"monitor",role:"img","aria-label":"Program monitor"}),L=t("p",{class:"note",role:"status","aria-live":"polite"}),S=qt({canvas:A,urlOf:e=>`/media/${f.find(n=>n.id===e).media}`,assetOf:e=>f.find(n=>n.id===e),onTime:e=>{l.textContent=`${xe(e,k())} / ${xe(D(),k())}`,C.setTime(e),B.setTime(e);let n=ve(N(),e),s=n?he(n,e):null,c=s===null?null:p.words.find(h=>h.asset===n.asset&&s>=h.start&&s<h.end);w.playing(c?.id??null)},onRate:e=>{He.textContent=e===0?"Play":"Pause",He.setAttribute("aria-label",e===0?"Play (Space)":`Pause (Space), playing at ${e}\xD7`)}}),b=()=>({"16:9":{width:1920,height:1080},"9:16":{width:1080,height:1920}})[jt.value]??u.canvas,N=()=>g?ht(f.find(e=>e.id===g)):o,D=()=>Ie(N()),_=t("div",{class:"transcript",tabindex:"-1"}),J=t("div",{class:"strip"}),Y=t("div",{class:"timeline"}),z=t("div",{class:"finish"}),w=Ut({root:_,onSeek:e=>{let n=Ve(o,e.asset,e.start);n!==null?(v(),S.seek(n)):T(e.asset,e.start)},onCut:(e,n)=>m([{op:"remove_range",asset:e.asset,from:{word:e.id,edge:"start"},to:{word:n.id,edge:"end"}}]),onFix:async(e,n)=>{try{await I("POST",`/projects/${a}/words/${encodeURIComponent(e.id)}`,{text:n}),L.textContent=`Fixed "${e.text}" to "${n}". Captions and Kriya use it from now on.`}catch(s){L.textContent=s.message}await r()}}),C=gt({root:Y,onSeek:e=>(v(),S.seek(e))}),B=gt({root:J,compact:!0,onSeek:e=>(v(),S.seek(e))}),K=t("div",{class:"area-final"}),y=It({root:z,finalRoot:K,pixels:()=>S.pixels(),project:()=>u,onAdjust:()=>ke("edit")});function v(){g&&(g=null,x.textContent="Preview",S.load(o,{fps:k(),duration:Ie(o),shape:b()}))}function T(e,n){g=e;let s=f.find(c=>c.id===e).facts;x.textContent="Source",S.load(ht(f.find(c=>c.id===e)),{fps:s.fps??k(),duration:s.duration,shape:{width:s.width??1920,height:s.height??1080}}).then(()=>S.seek(n))}async function r(){let[e,n,s]=await Promise.all([I("GET",`/projects/${a}`),I("GET",`/projects/${a}/plan`),I("GET",`/projects/${a}/index`)]);u=e.project,f=e.assets,p=s,M=n.timeline,o=Ft(n.timeline);let c=Ie(o),h=Dt(o,p.shots),E=new Map((p.words??[]).map(O=>[O.id,O])),U=(u.sequences.find(O=>O.id===u.active)?.markers??[]).flatMap(O=>{let F=O.name.startsWith("Note: ")&&O.at?.word?E.get(O.at.word):null,H=F?Ve(o,F.asset,F.start):null;return H==null?[]:[{at:H,name:O.name}]});if(C.load(M,{duration:c,fps:k(),marks:h,pins:U}),B.load({picture:M.picture},{duration:c,fps:k(),marks:h}),w.load(p),We(),G(),!$){$=!0;let O=[...fe.options].map(F=>F.value).find(F=>{let[H,un]=F.split(":").map(Number);return H*u.canvas.height===un*u.canvas.width});O&&u.sequences.some(F=>F.clips.length)&&(fe.value=O)}g||await S.load(o,{fps:k(),duration:c,shape:b()});for(let O of new Set([...M.audio,...M.picture].map(F=>F.asset))){let F=f.find(H=>H.id===O)?.media;F&&f.find(H=>H.id===O).facts.hasAudio&&fetch(`/tiles/${F}?kind=peaks`).then(H=>H.ok?H.json():null).then(H=>H&&(C.setPeaks(O,H.levels[0]),B.setPeaks(O,H.levels[0]))).catch(()=>{})}}async function m(e){try{let n=await I("PATCH",`/projects/${a}`,{ops:e});L.textContent=n.diagnostics?.length?n.diagnostics[0].message:""}catch(n){L.textContent=n.value?.diagnostics?.[0]?.message??n.message}await r()}let j=t("ul",{class:"bin","aria-label":"Footage"}),P=new Map,q=e=>[...P.values()].find(n=>n.kind==="index"&&n.asset===e&&["pending","running"].includes(n.status)),R=(e,n)=>{let s=t("span",{class:e===null?"busy":""});return e!==null&&(s.style.width=`${e}%`),t("div",{class:"progress",role:"progressbar","aria-label":n,"aria-valuemin":"0","aria-valuemax":"100",...e===null?{}:{"aria-valuenow":String(e)}},s)};function G(){W(j);for(let e of f.filter(n=>n.kind!=="reference")){let n=p.assets.find(U=>U.asset===e.id),s=n?.layers.find(U=>U.layer==="L2"),c=q(e.id),h=se?.speech?"Indexed, no words yet: set up speech-to-text above":s?.notice??"Indexed, no words",E=c?`Reading this file\u2026 ${c.progress??0}%`:n?s?.status==="ok"?"Indexed":h:"Not indexed",V=["video","audio"].includes(e.kind);j.append(t("li",{class:"asset"},t("button",{type:"button",class:"btn",onclick:()=>T(e.id,0)},`${e.path.split(/[\\/]/).at(-1)} \xB7 ${e.kind}`),t("span",{class:"note"},e.offline?"Offline: the file has moved":E),c?R(c.progress??0,`Indexing ${e.path.split(/[\\/]/).at(-1)}`):null,V?t("button",{type:"button",class:"btn",disabled:!!c,onclick:()=>te(e)},n?"Index again":"Index"):null,V?t("button",{type:"button",class:"btn",onclick:()=>m([{op:"keep_range",asset:e.id,from:0,to:e.facts.duration}])},"Add to cut"):null))}Ee()}async function te(e){se?.speech&&!se.setup?.error&&(L.textContent="Your file is indexed without words until speech-to-text is set up (above).",nt.hidden=!1);try{let n=await I("POST",`/projects/${a}/index`,{asset:e.id});P.set(n.id,{...n,asset:e.id}),L.textContent="Reading your footage. You can keep working.",G()}catch(n){L.textContent=n.message}}function Q(e,{reference:n=!1,aspect:s="all"}={}){let c=h=>new Promise((E,V)=>{let U=t("li",{class:"asset"},t("span",{class:"note"},`Copying ${h.name}\u2026`),R(0,`Copying ${h.name}`));ie.append(U);let O=new XMLHttpRequest;O.open("POST",`/projects/${a}/upload?name=${encodeURIComponent(h.name)}${n?"&as=reference":""}`),O.upload.onprogress=F=>{if(!F.lengthComputable)return;let H=Math.round(F.loaded*100/F.total);U.querySelector(".progress span").style.width=`${H}%`,U.querySelector(".progress").setAttribute("aria-valuenow",String(H)),U.querySelector(".note").textContent=`Copying ${h.name}\u2026 ${H}%`},O.onload=()=>{U.remove();let F={};try{F=JSON.parse(O.responseText)}catch{}O.status<300?E(F):V(new Error(F.message??`The Edit Host answered ${O.status}.`))},O.onerror=()=>(U.remove(),V(new Error(`${h.name} couldn't be copied.`))),O.send(h)});return(async()=>{for(let h of e)try{let E=await c(h);L.textContent=n?`Added ${h.name} as a reference for ${ue[s].toLowerCase()}.`:`Added ${h.name}. Index it to read its words.`,n&&(le.add(E.id),ae(Ne(E.id),s))}catch(E){L.textContent=E.message}await r()})()}let ie=t("ul",{class:"bin","aria-label":"Copying"}),$e=t("input",{type:"file",multiple:!0,accept:"video/*,audio/*,.mov,.mp4,.m4v,.mkv,.wav,.mp3,.m4a,.aac,.flac,.cube",hidden:!0,id:"pick-files",onchange:()=>(Q([...$e.files]),$e.value="")}),Se=t("input",{id:"add-path",class:"field",placeholder:"/Users/you/Movies/take.mov",autocomplete:"off"}),Ce=t("section",{class:"panel bin-panel","aria-label":"Bin"},t("h2",{},"Bin"),j,ie,$e,t("button",{type:"button",class:"btn primary wide",onclick:()=>$e.click()},"Add files\u2026"),t("p",{class:"note small"},"Copied into the project's media folder; your originals aren't touched."),t("details",{class:"by-path"},t("summary",{},"Link a file by its path instead (no copy)"),t("form",{class:"row",onsubmit:async e=>{e.preventDefault();try{await I("POST",`/projects/${a}/assets`,{path:Se.value.trim()}),Se.value="",await r()}catch(n){L.textContent=n.message}}},t("label",{for:"add-path",class:"sr-only"},"Link a file by its path"),Se,t("button",{class:"btn",type:"submit"},"Link")))),le=new Set,bt=new Set,ue={all:"Everything it shows",editing:"Editing: cuts and pace",sound:"Sound: music and feel",colour:"Colour grade",graphics:"Graphics: captions and text"},Ne=e=>`kriya-ref-aspect:${a}:${e}`,Je=e=>Object.hasOwn(ue,ae(Ne(e))??"")?ae(Ne(e)):"all",Ze=(e,n,s)=>t("select",{class:"field select",...e,onchange:s},Object.entries(ue).map(([c,h])=>t("option",{value:c,selected:c===n},h))),Fe=Ze({id:"ref-aspect","aria-label":"The next reference is for"},"all",()=>Xe.value=Fe.value),Xe=Ze({id:"ref-aspect-bin","aria-label":"The next reference is for"},"all",()=>Fe.value=Xe.value),Zt=(e,n)=>e.parts?n!=="all"?e.parts[n]?[e.parts[n]]:[`Nothing to take for ${ue[n].toLowerCase()} from this one.`]:e.lines.filter(s=>!(e.kind==="video"&&e.pace&&s===e.parts.sound)):e.lines,Me=new Map,De=t("ul",{class:"bin","aria-label":"References"}),Qe=t("ul",{class:"bin refs-direct","aria-label":"References for this cut"}),kt=t("p",{class:"note small"}),Te=t("input",{type:"file",accept:"video/*,image/*,audio/*,.mov,.mp4,.m4v,.mkv,.webm,.jpg,.jpeg,.png,.webp,.wav,.mp3,.m4a,.aac,.flac",hidden:!0,id:"pick-reference",onchange:()=>{let e=[...Te.files];Te.value="";let n=Fe.value,s=n==="all"?"a video's pace, captions, colour and music; an image's colour grade; music's tempo and energy":`only its ${ue[n].toLowerCase()}`;e.length&&confirm(`Use this only as a reference for ${ue[n].toLowerCase()}?
4
+
5
+ Kriya measures it as numbers: ${s}. No picture, sound or words from it go into your video. Add only what you're allowed to use this way.`)&&Q(e,{reference:!0,aspect:n})}});function wt(e,n){let s=e.path.split(/[\\/]/).at(-1),c=e.facts.width?e.facts.duration?"video":"image":"music",h=t("input",{type:"checkbox",id:`use-${n}-${e.id}`,checked:le.has(e.id),onchange:()=>(h.checked?le.add(e.id):le.delete(e.id),Ee(h.id))}),E=Me.get(e.id),V=Je(e.id),U=t("ul",{class:"ref-lines"},...E?Zt(E,V).map(F=>t("li",{},F)):[t("li",{class:"note"},"Measuring\u2026")]),O=Ze({id:`aspect-${n}-${e.id}`,"aria-label":`Take from ${s}`},V,F=>(ae(Ne(e.id),F.target.value),Ee(F.target.id)));return t("li",{class:"asset ref"},t("button",{type:"button",class:"btn",onclick:()=>e.facts.duration&&T(e.id,0)},`${s} \xB7 ${c}`),t("label",{class:"note small",for:`aspect-${n}-${e.id}`},"Take from it"),O,U,t("label",{class:"inline",for:`use-${n}-${e.id}`},h," Use in the cut"))}function Ee(e=null){W(De),W(Qe);let n=f.filter(h=>h.kind==="reference");n.length||De.append(t("li",{class:"note"},"None yet. Pick what a reference is for, then add a video whose cuts you like, music whose feel you like, or an image whose colour you like."));for(let h of n)bt.has(h.id)||(bt.add(h.id),le.add(h.id)),De.append(wt(h,"bin")),Qe.append(wt(h,"direct")),Me.has(h.id)||(Me.set(h.id,null),I("GET",`/projects/${a}/references/${encodeURIComponent(h.id)}`).then(E=>(Me.set(h.id,E),Ee())).catch(E=>(Me.set(h.id,{lines:[`Couldn't measure it: ${E.message}`]}),Ee())));ln(),e&&document.getElementById(e)?.focus(),((h,E,V)=>{let U=h.value;W(h).append(t("option",{value:""},V),...E.map(O=>t("option",{value:O.id},O.path.split(/[\\/]/).at(-1)))),h.value=E.some(O=>O.id===U)?U:""})(X,f.filter(h=>h.kind==="audio"&&!/kriya-music-/.test(h.path)),"No music");let c=X.value;X.insertBefore(t("optgroup",{label:"Made by Kriya"},t("option",{value:"generated:calm"},"Music: calm bed (made by Kriya)"),t("option",{value:"generated:upbeat"},"Music: upbeat bed (made by Kriya)"),t("option",{value:"generated:warm"},"Music: warm bed (made by Kriya)")),X.options[1]??null),/^generated:/.test(_e)?X.value=_e:c&&(X.value=c)}let se=null,me=t("p",{class:"note"}),et=t("div"),tt=t("button",{type:"button",class:"btn primary",onclick:()=>I("POST","/runtime/setup").then(Ke).catch(e=>me.textContent=e.message)},"Set up speech-to-text"),nt=t("section",{class:"panel setup","aria-label":"Speech-to-text setup",hidden:!0},t("h2",{},"Speech-to-text"),me,et,tt),vt=e=>(e/1e6).toLocaleString(void 0,{maximumFractionDigits:0});function Ke(e){se=e;let n=se.setup,s=n&&!n.finished;if(nt.hidden=!se.speech&&!s&&!n?.error,tt.hidden=!!s,tt.textContent=n?.error?"Try again":"Set up speech-to-text",W(et),s){let c=n.total?Math.round(n.done*100/n.total):null;me.textContent=n.total?`Downloading ${n.step}: ${vt(n.done)} of ${vt(n.total)} MB (${c}%)`:n.line??"Setting up\u2026",et.append(R(c,"Media Runtime setup"))}else n?.error?me.textContent=`Setup stopped: ${n.error}`:se.speech?me.textContent="Words in the transcript need the speech model on this computer. Setting it up downloads it once; after that it works offline.":n?.finished&&(me.textContent="Ready. Index a file to read its words.")}let oe=t("textarea",{id:"prompt",class:"field chat-input",rows:"2",placeholder:'Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',autocomplete:"off"}),at=t("span",{class:"chip selection",hidden:!0}),xt=t("ol",{class:"chat","aria-label":"Chat with Kriya","aria-live":"polite"}),Be=t("ul",{class:"did","aria-label":"What I did"}),ge=[],Z=null,ne=null,ye=e=>{let n=Math.max(0,e)/7056e5,s=Math.floor(n/60);return`${s}:${(n-s*60).toFixed(1).padStart(4,"0")}`},$t=()=>{if(Z!==null&&ne!==null&&ne>Z)return{selection:{from:Z,to:ne},label:`Marked ${ye(Z)}\u2013${ye(ne)}`};let e=w.selection();return e?{selection:{words:e},label:`Selected: ${p.words.find(n=>n.id===e[0])?.text??""}${e[0]===e[1]?"":" \u2026"}`}:C.selected?{selection:{clip:C.selected},label:`Selected: clip ${C.selected}`}:Z!==null?{selection:{at:Z},label:`Marked in at ${ye(Z)} (press O for the end)`}:{selection:{at:S.time},label:null}},We=()=>{let{label:e}=$t();at.hidden=!e,at.textContent=e??""};_.addEventListener("click",()=>setTimeout(We));function st(e){let n=[],s=0;for(let c of String(e).matchAll(/\b(\d{1,2}):(\d{2}(?:\.\d+)?)\b/g)){n.push(e.slice(s,c.index));let h=Math.round((Number(c[1])*60+Number(c[2]))*7056e5);n.push(t("button",{type:"button",class:"time-link",title:"Play from here",onclick:()=>(v(),S.seek(Math.min(h,Math.max(0,Ie(o)-1))))},c[0])),s=c.index+c[0].length}return n.push(e.slice(s)),n}function ce(e,n,...s){let c=t("li",{class:`msg ${e}`},t("span",{class:"who"},e==="you"?"You":"Kriya"),t("p",{},...st(n)),...s);return xt.append(c),c.scrollIntoView({block:"nearest"}),c}function Xt(e){C.setGhost(e.timeline),B.setGhost(e.timeline);let n=t("div",{class:"proposal"}),s=async(c,h)=>{try{let E=await I("POST",`/projects/${a}/proposals/${e.id}`,{accept:c,...h?{only:h}:{}});if(L.textContent=E.dropped.length?`Not applied, because you changed that part: ${E.dropped.map(V=>V.change).join("; ")}.`:c?"Done. Undo with Cmd+Z.":"Left as it was.",c)for(let V of h?h.map(U=>e.changes[U]):e.changes)Be.prepend(t("li",{},V));W(n).append(t("p",{class:"note"},c?E.dropped.length?"Partly applied.":"Applied.":"Not applied."))}catch(E){L.textContent=E.message}C.setGhost(null),B.setGhost(null),await r()};return n.append(t("p",{class:"lead"},"Proposed, not applied yet"),t("ul",{},e.changes.map((c,h)=>t("li",{},t("span",{},...st(c)),e.changes.length>1?t("button",{type:"button",class:"btn",onclick:()=>s(!0,[h])},"Only this"):null))),t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>s(!0)},e.changes.length>1?"Accept all":"Accept"),t("button",{type:"button",class:"btn",onclick:()=>s(!1)},"Reject"))),n}let je=null,Qt=()=>({...ct(),...Ae.value==="clean"?{cleanVoice:!0}:{}}),St=e=>p.words.find(n=>n.id===e)?.text??e,Ct=e=>`${Math.floor(e/60)}:${(e%60).toFixed(1).padStart(4,"0")}`;function en(e={}){return[e.format,e.seconds?`about ${e.seconds} s`:null,e.captions&&e.captions!=="none"?`${e.captions} captions`:"no captions",e.grade&&e.grade!=="natural"?`${e.grade} look`:"natural colour",e.music&&e.music!=="none"?`${e.music} music`:"no music",e.cleanVoice?"background noise out of the voice":null,e.coldOpen?`cold open on "${St(e.coldOpen.from)} \u2026 ${St(e.coldOpen.to)}"${e.coldOpen.mono===!1?"":" in black and white"}`:null,e.hook?"a hook line first":null,e.cutSound&&e.cutSound!=="none"?`a ${e.cutSound} on each cut`:null,e.introSound&&e.introSound!=="none"?`a ${e.introSound} into the story`:null,Number.isInteger(e.punches)?`${e.punches} punch-ins`:null,e.angles?"wide and tight angles":null,e.broll==="own"?"B-roll from your clips":null,e.titles?"title cards":null,e.ramps?"a speed ramp into the story":null,e.cuts?.length?`trims ${e.cuts.map(s=>`${Ct(s.from)}\u2013${Ct(s.to)}`).join(", ")} of the take`:null].filter(Boolean).join(" \xB7 ")}function tn(e){let n=t("div",{class:"proposal plan"},t("p",{class:"lead"},"The Director's plan, not made yet"),e.steps.length?t("ol",{class:"steps"},e.steps.map(s=>t("li",{},...st(s)))):null,t("p",{class:"note small"},en(e.settings)),t("div",{class:"row"},t("button",{type:"button",class:"btn primary",onclick:()=>(je=null,nn(e.brief),W(n).append(t("p",{class:"note"},`Approved. Making it now in ${e.brief.format??fe.value}; the progress is in Direct.`)),Tt(e.brief,{exact:!0}))},"Approve and make it"),t("button",{type:"button",class:"btn",onclick:()=>(je=e,oe.focus(),oe.placeholder="Say what to change in the plan\u2026")},"Change\u2026")));return n}function nn(e={}){e.format&&(fe.value=e.format);let n=e.seconds?String(e.seconds):"";n&&![...pe.options].some(s=>s.value===n)&&pe.append(t("option",{value:n},`${n} seconds`)),pe.value=n,Pe.value=e.captions??"",Le.value=e.grade??"",/^generated:/.test(e.music??"")&&[...X.options].some(s=>s.value===e.music)?X.value=e.music:e.music||(X.value=""),Ae.value=e.cleanVoice?"clean":"",qe.box.checked=!!e.angles,it.box.checked=e.broll==="own",Ge.box.checked=!!e.titles,lt.value=""}async function Mt(e,n=null){let s=ce("kriya",n?"Revising the plan\u2026":"Planning the cut\u2026");try{let c=await I("POST",`/projects/${a}/plan`,{text:e,history:ge.slice(-6),previous:n,choices:Qt()});s.remove(),je=c,ce("kriya",c.say||"Here's my plan.",tn(c)),ge.push({who:"kriya",text:(c.say||"").slice(0,400)})}catch(c){s.remove(),ce("kriya",c.message)}}async function ot({planning:e=!1}={}){let n=oe.value.trim();if(!n)return;if(oe.placeholder='Tell Kriya: "remove 0:05 to 0:09", "change the caption at 0:12 to \u2026", "make the start punchier"',je||e)return ce("you",n),ge.push({who:"you",text:n.slice(0,400)}),oe.value="",Mt(n,je);let{selection:s,label:c}=$t();ce("you",c?`${n} (${c.replace(/^Selected: /,"on ")})`:n),oe.value="";let h=ce("kriya","Thinking about that\u2026");try{let E=await I("POST",`/projects/${a}/ask`,{text:n,selection:s,history:ge.slice(-6)});h.remove();let V=E.say||(E.proposal?"Here's what I'd change.":E.direct?"That's about the whole video.":E.reason??"I couldn't turn that into an edit. Try saying it another way.");if(ge.push({who:"you",text:n.slice(0,400)}),E.direct&&!E.proposal)return Mt(n);ce("kriya",V,E.proposal?Xt(E.proposal):null),ge.push({who:"kriya",text:V.slice(0,400)})}catch(E){h.remove(),ce("kriya",E.status===0||E.status>=500?"I can't reach Kriya right now, so I can't make changes by asking. You can still edit by hand.":E.message)}}oe.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),ot())});let an=t("form",{class:"prompt",onsubmit:e=>(e.preventDefault(),ot())},t("label",{for:"prompt",class:"sr-only"},"Message Kriya"),oe,t("div",{class:"send"},t("button",{class:"btn primary",type:"submit"},"Send"),t("button",{type:"button",class:"btn",title:"Ask the Director for a plan of the whole cut",onclick:()=>ot({planning:!0})},"Plan"))),sn=t("div",{class:"marks",role:"group","aria-label":"Mark a range of the cut"},t("button",{type:"button",class:"btn","aria-keyshortcuts":"I",title:"Mark in (I)",onclick:()=>Oe({type:"mark",edge:"in"})},"Mark in"),t("button",{type:"button",class:"btn","aria-keyshortcuts":"O",title:"Mark out (O)",onclick:()=>Oe({type:"mark",edge:"out"})},"Mark out")),on={delivered:"Checked",delivered_with_notes:"Checked, with notes",blocked:"Needs you",not_checked:"Not checked"},pe=t("select",{id:"make-length",class:"field select"},[["","Length: auto (30\u201360 s)"],["30","30 seconds"],["45","45 seconds"],["60","60 seconds"],["90","90 seconds"]].map(([e,n])=>t("option",{value:e},n))),Pe=t("select",{id:"make-captions",class:"field select"},[["","No captions"],["clean","Captions: clean"],["karaoke","Captions: karaoke"],["boxed","Captions: boxed"]].map(([e,n])=>t("option",{value:e},n))),X=t("select",{id:"make-music",class:"field select"}),fe=t("select",{id:"make-format",class:"field select"},[["9:16","Format: 9:16 (Reels, Shorts)"],["16:9","Format: 16:9 (YouTube)"],["1:1","Format: 1:1 (square post)"],["4:5","Format: 4:5 (feed post)"]].map(([e,n])=>t("option",{value:e},n))),Le=t("select",{id:"make-grade",class:"field select"},[["","Look: natural"],["vivid","Look: vivid"],["cinematic","Look: cinematic (cool, vignette)"],["warm","Look: warm"],["bright","Look: bright"],["mono","Look: black and white"]].map(([e,n])=>t("option",{value:e},n))),Ae=t("select",{id:"make-voice",class:"field select"},[["","Voice: as recorded"],["clean","Voice: remove background noise"]].map(([e,n])=>t("option",{value:e},n))),rt=(e,n)=>{let s=t("input",{type:"checkbox",id:e});return{box:s,el:t("label",{class:"inline",for:e},s,` ${n}`)}},qe=rt("make-angles","Angles (wide and tight)"),it=rt("make-broll","B-roll from my clips"),Ge=rt("make-titles","Title cards"),_e="";X.addEventListener("change",()=>_e=X.value);let rn={"":null,reel:{format:"9:16",captions:"karaoke",grade:"vivid",length:"45",music:"generated:upbeat",voice:"clean",angles:!0},clean:{format:"9:16",captions:"clean",grade:"",length:"30",music:"",voice:"clean"},youtube:{format:"16:9",captions:"clean",grade:"warm",length:"60",music:"generated:calm",voice:"clean"},square:{format:"1:1",captions:"boxed",grade:"vivid",length:"30",music:"generated:upbeat",voice:"clean"},cinematic:{format:"16:9",captions:"",grade:"cinematic",length:"60",music:"generated:warm",voice:"clean",angles:!0,titles:!0}},lt=t("select",{id:"make-template",class:"field select",onchange:()=>{let e=rn[lt.value];e&&(fe.value=e.format,Pe.value=e.captions,Le.value=e.grade,pe.value=e.length,Ae.value=e.voice,qe.box.checked=!!e.angles,Ge.box.checked=!!e.titles,X.value=_e=e.music)}},[["","Template: choose\u2026"],["reel","Talking-head reel: karaoke captions, upbeat music"],["clean","Clean reel: simple captions, no music"],["youtube","YouTube talk: 16:9, warm, calm music"],["square","Square post: boxed captions, vivid"],["cinematic","Cinematic: 16:9, cool look, no captions"]].map(([e,n])=>t("option",{value:e},n))),ln=()=>{let e=f.filter(s=>s.kind==="reference"&&le.has(s.id)),n=[...new Set(e.map(s=>Je(s.id)))].map(s=>s==="all"?"everything":ue[s].split(":")[0].toLowerCase());kt.textContent=e.length?`${e.length} reference${e.length===1?"":"s"} in use, for ${n.join(", ")}.`:"No references in use."},ct=(e={})=>({...pe.value?{seconds:Number(pe.value)}:{},...Pe.value?{captions:Pe.value}:{},...X.value?{music:X.value}:{},...le.size?{references:[...le].filter(n=>f.some(s=>s.id===n&&s.kind==="reference")).map(n=>({id:n,aspect:Je(n)}))}:{},format:fe.value,...Le.value?{grade:Le.value}:{},...Ae.value==="clean"?{cleanVoice:!0}:{},...qe.box.checked?{angles:!0}:{},...it.box.checked?{broll:"own"}:{},...Ge.box.checked?{titles:!0}:{},...e});async function Tt(e,{exact:n=!1}={}){try{let s=ct().references,c=await I("POST",`/projects/${a}/make`,{brief:n?{...e,...s?{references:s}:{}}:ct(e)});be=c.id,P.set(c.id,c),L.textContent="Directing your reel: reading the footage, choosing the story, cutting and checking it. You can keep working.",ut()}catch(s){L.textContent=s.message}}let Et=t("button",{type:"button",class:"btn primary wide",onclick:()=>Tt()},"Make it"),dt=t("div",{class:"make-status","aria-live":"polite"});function ut(){let e=be?P.get(be):null;W(dt),Et.disabled=!!e,e&&dt.append(t("p",{class:"note"},`Making the reel\u2026 ${e.progress??0}%`),R(e.progress??0,"Making the reel"))}let cn=t("div",{class:"make"},t("label",{for:"make-template",class:"sr-only"},"Template"),lt,t("label",{for:"make-format",class:"sr-only"},"Format"),fe,t("label",{for:"make-length",class:"sr-only"},"Length"),pe,t("label",{for:"make-captions",class:"sr-only"},"Captions"),Pe,t("label",{for:"make-grade",class:"sr-only"},"Colour look"),Le,t("label",{for:"make-music",class:"sr-only"},"Music"),X,t("label",{for:"make-voice",class:"sr-only"},"Voice"),Ae,t("div",{class:"extras",role:"group","aria-label":"Extras"},qe.el,it.el,Ge.el),kt,Qe,t("div",{class:"row tight"},Te,Fe,t("button",{type:"button",class:"btn","aria-label":"Add a reference",title:"Add a reference for what's chosen: a video, an image or music",onclick:()=>Te.click()},"+ Reference")),Et,dt),be=null;async function dn(){if(!be)return;let e=(await I("GET","/jobs")).jobs.find(s=>s.id===be);if(e&&P.set(e.id,e),ut(),!e||!["done","failed","canceled"].includes(e.status))return;if(be=null,ut(),e.status!=="done")return L.textContent=e.error??"The reel stopped.";let n=JSON.parse(e.output);L.textContent=`${on[n.verdict]??n.verdict}. ${n.notes.join(" ")}`,n.file&&Be.prepend(t("li",{class:"watch"},t("button",{type:"button",class:"btn primary",onclick:()=>ke("finish")},"Watch the final cut")));for(let s of[...n.changes].reverse())Be.prepend(t("li",{},s))}let He=t("button",{type:"button",class:"btn primary",onclick:()=>Oe({type:"toggle"})},"Play"),jt=t("select",{class:"field small select","aria-label":"Preview shape",onchange:()=>S.setShape(b())},["project","16:9","9:16"].map(e=>t("option",{value:e},e==="project"?"Project shape":e))),Pt=t("input",{type:"range",min:"1",max:"3",step:"0.05",value:"1",class:"zoom","aria-label":"Zoom",oninput:()=>S.setZoom(Number(Pt.value))}),Lt=t("input",{type:"checkbox",id:"guides",onchange:()=>S.setGuides(Lt.checked)});function Oe(e){if(!e)return;if(e.type==="mode")return ke(e.mode);if(e.type==="prompt")return oe.focus();if(e.type==="mark")return v(),e.edge==="in"||Z===null?(Z=S.time,ne=null):S.time>Z?ne=S.time:(ne=Z,Z=S.time),L.textContent=ne===null?`Marked in at ${ye(Z)}. Play to the end of the stretch and press O.`:`Marked ${ye(Z)} to ${ye(ne)}. Tell Kriya what to do with it.`,We();if(e.type==="undo")return I("PATCH",`/projects/${a}`,{undo:!0}).then(r);if(e.type==="redo")return L.textContent="Redo isn't here yet.";if(e.type==="split"){let h=ve(o,S.time);return h&&m([{op:"split",clip:h.clip,at:he(h,S.time)}])}if(e.type==="delete")return C.selected&&m([{op:"ripple_delete",clip:C.selected}]);let n={fps:g?f.find(h=>h.id===g).facts.fps??k():k(),duration:D()},s={t:S.time,rate:S.rate},c=Wt(s,e,n);c.rate!==s.rate&&S.setRate(c.rate),(c.t!==s.t||e.type==="seek")&&S.seek(c.t)}function ke(e){i=e,ae("kriya-edit-mode",i),Re.dataset.mode=i;for(let n of At.querySelectorAll("button"))n.setAttribute("aria-pressed",String(n.dataset.mode===i));C.draw(),B.draw(),i==="finish"&&y.refresh().catch(()=>{})}let At=t("div",{class:"modes",role:"group","aria-label":"Mode"},Vt.map((e,n)=>t("button",{type:"button",class:"btn",dataset:{mode:e},"aria-pressed":"false","aria-keyshortcuts":String(n+1),onclick:()=>ke(e)},e[0].toUpperCase()+e.slice(1)))),we={min:300,step:32},pt=()=>Math.max(we.min,Math.min(960,Math.round(window.innerWidth*.62))),ft=()=>document.querySelector(".area-kriya")?.getBoundingClientRect().width??0;function Ue(e){if(e===null)Re.style.removeProperty("--side"),ae("kriya-side-width","");else{let n=Math.round(Math.min(pt(),Math.max(we.min,e)));Re.style.setProperty("--side",`${n}px`),ae("kriya-side-width",String(n))}ee.setAttribute("aria-valuenow",String(Math.round(ft()))),C.draw(),B.draw()}let ee=t("div",{class:"side-handle",role:"separator",tabindex:"0","aria-orientation":"vertical","aria-label":"Resize the Kriya panel","aria-valuemin":String(we.min),title:"Drag to resize. Double-click to fit the window.",onpointerdown:e=>{e.preventDefault(),ee.setPointerCapture(e.pointerId);let n=document.querySelector(".area-kriya").getBoundingClientRect().right,s=h=>Ue(n-h.clientX),c=()=>(ee.removeEventListener("pointermove",s),ee.removeEventListener("pointerup",c),ee.removeEventListener("pointercancel",c));ee.addEventListener("pointermove",s),ee.addEventListener("pointerup",c),ee.addEventListener("pointercancel",c)},ondblclick:()=>Ue(null),onkeydown:e=>{let n={ArrowLeft:we.step,ArrowRight:-we.step}[e.key];n?(e.preventDefault(),e.stopPropagation(),Ue(ft()+n)):e.key==="Home"&&(e.preventDefault(),Ue(null))}}),Re=t("div",{class:"workspace"},zt(t("span",{class:"project-name"},u.name),At),t("div",{class:"banner"},L,nt),t("div",{class:"grid"},t("div",{class:"area-bin"},Ce,t("section",{class:"panel refs","aria-label":"Style references"},t("h2",{},"References"),De,Xe,t("button",{type:"button",class:"btn wide",onclick:()=>Te.click()},"Add a reference\u2026"))),t("section",{class:"area-monitor panel","aria-label":"Monitor"},t("div",{class:"monitor-frame"},A),t("div",{class:"transport"},He,l,x,jt,sn,t("label",{class:"inline"},Lt," Safe zones"),t("label",{class:"inline"},"Zoom ",Pt))),t("aside",{class:"area-kriya panel","aria-label":"Kriya"},ee,t("h2",{},"Direct"),cn,t("h2",{},"Chat with Kriya"),xt,at,an,t("p",{class:"note small"},"Say times like 0:05 or mark a stretch with I and O. Enter sends."),t("h2",{},"What I did"),Be),t("section",{class:"area-transcript panel","aria-label":"Transcript"},t("h2",{},"Transcript"),t("p",{class:"note small hint"},"Click a word to jump there. Double-click (or F2) to fix a misheard word."),_),t("div",{class:"area-strip"},J),t("section",{class:"area-timeline panel","aria-label":"Timeline"},Y),t("div",{class:"area-finish"},z),K));W(yt).append(Re);let Ot=Number(ae("kriya-side-width"));Ot>=we.min&&Re.style.setProperty("--side",`${Math.min(pt(),Ot)}px`),ke(i),ee.setAttribute("aria-valuemax",String(pt())),ee.setAttribute("aria-valuenow",String(Math.round(ft()))),window.onkeydown=e=>{let n=e.target.closest?.("input, select, textarea");if(n&&e.key!=="Escape")return;if(e.key==="Escape")return n?document.activeElement?.blur():(w.clear(),C.select(null),Z=ne=null,We());let s=Bt(e.key,{shift:e.shiftKey,mod:e.metaKey||e.ctrlKey});s&&(s.type==="toggle"&&e.target.closest?.("button")&&e.target!==He||(e.preventDefault(),Oe(s)))},setInterval(()=>i==="finish"&&y.scopes(),250);let Rt=new EventSource("/events");Rt.addEventListener("job",e=>{let n=null;try{n=JSON.parse(e.data)}catch{}n?.id&&P.set(n.id,n),i==="finish"&&y.refresh().catch(()=>{}),dn().catch(()=>{}),n&&["pending","running"].includes(n.status)?G():r().catch(()=>{})}),Rt.addEventListener("setup",e=>{try{Ke({...se??{},setup:JSON.parse(e.data)})}catch{}se?.setup?.finished&&I("GET","/runtime").then(Ke).catch(()=>{})}),I("GET","/runtime").then(Ke).catch(()=>{}),await r(),window.__studio={monitor:S,act:Oe,reload:r,setMode:ke,get pieces(){return o}}}function Jt(){let a=/^#\/p\/([0-9a-f]{16})$/.exec(location.hash);a?bn(a[1]):Yt()}window.addEventListener("hashchange",Jt);Jt();