paces 0.0.25__tar.gz → 0.0.27__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {paces-0.0.25 → paces-0.0.27}/PKG-INFO +1 -1
  2. {paces-0.0.25 → paces-0.0.27}/paces/ask.py +16 -0
  3. {paces-0.0.25 → paces-0.0.27}/paces/ask_contract.py +12 -1
  4. {paces-0.0.25 → paces-0.0.27}/paces/data/ask/ask.js +211 -145
  5. {paces-0.0.25 → paces-0.0.27}/pyproject.toml +1 -1
  6. {paces-0.0.25 → paces-0.0.27}/tests/test_ask.py +66 -0
  7. {paces-0.0.25 → paces-0.0.27}/.gitignore +0 -0
  8. {paces-0.0.25 → paces-0.0.27}/LICENSE +0 -0
  9. {paces-0.0.25 → paces-0.0.27}/README.md +0 -0
  10. {paces-0.0.25 → paces-0.0.27}/docs/README.md +0 -0
  11. {paces-0.0.25 → paces-0.0.27}/docs/alignment/README.md +0 -0
  12. {paces-0.0.25 → paces-0.0.27}/docs/poc-reference/README.md +0 -0
  13. {paces-0.0.25 → paces-0.0.27}/docs/poc-reference/artifacts/clips.json +0 -0
  14. {paces-0.0.25 → paces-0.0.27}/paces/__init__.py +0 -0
  15. {paces-0.0.25 → paces-0.0.27}/paces/__main__.py +0 -0
  16. {paces-0.0.25 → paces-0.0.27}/paces/bodies/__init__.py +0 -0
  17. {paces-0.0.25 → paces-0.0.27}/paces/bodies/_base.py +0 -0
  18. {paces-0.0.25 → paces-0.0.27}/paces/bodies/derivation.py +0 -0
  19. {paces-0.0.25 → paces-0.0.27}/paces/bodies/document.py +0 -0
  20. {paces-0.0.25 → paces-0.0.27}/paces/bodies/signal.py +0 -0
  21. {paces-0.0.25 → paces-0.0.27}/paces/bodies/step.py +0 -0
  22. {paces-0.0.25 → paces-0.0.27}/paces/corrections.py +0 -0
  23. {paces-0.0.25 → paces-0.0.27}/paces/cues.py +0 -0
  24. {paces-0.0.25 → paces-0.0.27}/paces/data/ask/ask.css +0 -0
  25. {paces-0.0.25 → paces-0.0.27}/paces/data/ask/ask.html +0 -0
  26. {paces-0.0.25 → paces-0.0.27}/paces/derivation.py +0 -0
  27. {paces-0.0.25 → paces-0.0.27}/paces/edits.py +0 -0
  28. {paces-0.0.25 → paces-0.0.27}/paces/evidence.py +0 -0
  29. {paces-0.0.25 → paces-0.0.27}/paces/excerpts.py +0 -0
  30. {paces-0.0.25 → paces-0.0.27}/paces/measure.py +0 -0
  31. {paces-0.0.25 → paces-0.0.27}/paces/model.py +0 -0
  32. {paces-0.0.25 → paces-0.0.27}/paces/pose.py +0 -0
  33. {paces-0.0.25 → paces-0.0.27}/paces/projection.py +0 -0
  34. {paces-0.0.25 → paces-0.0.27}/paces/render.py +0 -0
  35. {paces-0.0.25 → paces-0.0.27}/paces/segmentation.py +0 -0
  36. {paces-0.0.25 → paces-0.0.27}/paces/segmenters.py +0 -0
  37. {paces-0.0.25 → paces-0.0.27}/paces/timed_text.py +0 -0
  38. {paces-0.0.25 → paces-0.0.27}/paces/tools.py +0 -0
  39. {paces-0.0.25 → paces-0.0.27}/tests/audio_synth.py +0 -0
  40. {paces-0.0.25 → paces-0.0.27}/tests/data/body_schemas.json +0 -0
  41. {paces-0.0.25 → paces-0.0.27}/tests/data/routine.json +0 -0
  42. {paces-0.0.25 → paces-0.0.27}/tests/poc_fixture.py +0 -0
  43. {paces-0.0.25 → paces-0.0.27}/tests/test_chapters.py +0 -0
  44. {paces-0.0.25 → paces-0.0.27}/tests/test_cli_surface.py +0 -0
  45. {paces-0.0.25 → paces-0.0.27}/tests/test_corrections.py +0 -0
  46. {paces-0.0.25 → paces-0.0.27}/tests/test_cues.py +0 -0
  47. {paces-0.0.25 → paces-0.0.27}/tests/test_derivation.py +0 -0
  48. {paces-0.0.25 → paces-0.0.27}/tests/test_edit_protection_residuals.py +0 -0
  49. {paces-0.0.25 → paces-0.0.27}/tests/test_edits.py +0 -0
  50. {paces-0.0.25 → paces-0.0.27}/tests/test_evidence.py +0 -0
  51. {paces-0.0.25 → paces-0.0.27}/tests/test_evidence_schemas.py +0 -0
  52. {paces-0.0.25 → paces-0.0.27}/tests/test_excerpts.py +0 -0
  53. {paces-0.0.25 → paces-0.0.27}/tests/test_measure.py +0 -0
  54. {paces-0.0.25 → paces-0.0.27}/tests/test_pose.py +0 -0
  55. {paces-0.0.25 → paces-0.0.27}/tests/test_render_media.py +0 -0
  56. {paces-0.0.25 → paces-0.0.27}/tests/test_roundtrip_poc.py +0 -0
  57. {paces-0.0.25 → paces-0.0.27}/tests/test_segment.py +0 -0
  58. {paces-0.0.25 → paces-0.0.27}/tests/test_smoke.py +0 -0
  59. {paces-0.0.25 → paces-0.0.27}/tests/test_vertical_slice.py +0 -0
  60. {paces-0.0.25 → paces-0.0.27}/tests/video_synth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: paces
3
- Version: 0.0.25
3
+ Version: 0.0.27
4
4
  Summary: Turn instructional media into structured, interactive learning material
5
5
  Project-URL: Homepage, https://github.com/thorwhalen/paces
6
6
  Project-URL: Repository, https://github.com/thorwhalen/paces
@@ -85,6 +85,21 @@ def _grid_ticks(seg: Segmentation, lo: float, hi: float, *, limit: int) -> list[
85
85
  return [time_str(origin + n * spu) for n in range(first, last + 1)]
86
86
 
87
87
 
88
+ def _meets(seg: Segmentation, cut: str) -> bool:
89
+ """Whether one step ends at ``cut`` and another begins there (no gap).
90
+
91
+ Unnamed segmentations (no steps) are spans between cuts, so every cut meets.
92
+
93
+ >>> from paces.segmenters import segment
94
+ >>> propose(segment(boundaries=[0, 10, 20]))["cutMeets"]
95
+ [True]
96
+ """
97
+ if not seg.steps:
98
+ return True
99
+ spans = [(time_str(a), time_str(b)) for step in seg.steps for a, b in step.spans]
100
+ return any(b == cut for _, b in spans) and any(a == cut for a, _ in spans)
101
+
102
+
88
103
  def propose(
89
104
  seg: Segmentation,
90
105
  *,
@@ -129,6 +144,7 @@ def propose(
129
144
  k_evidence=why,
130
145
  extent=tuple(time_str(t) for t in extent) if extent else None,
131
146
  cuts=[time_str(t) for t in interior],
147
+ cut_meets=[_meets(seg, time_str(t)) for t in interior],
132
148
  steps=[
133
149
  ProposedStep(
134
150
  id=step.id,
@@ -21,6 +21,8 @@ from typing import Any, Literal
21
21
  from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
22
22
  from pydantic.alias_generators import to_camel
23
23
 
24
+ from paces.segmentation import TIME_PLACES
25
+
24
26
  PROPOSAL_KIND = "PacesAskProposal"
25
27
  ANSWERS_KIND = "PacesAskAnswers"
26
28
  #: The proposal/answers contract version. Both documents carry it; a reader
@@ -50,7 +52,13 @@ class Snap(_Wire):
50
52
 
51
53
 
52
54
  class Proposal(_Wire):
53
- """What the machine pre-computes for a human to confirm (:func:`paces.ask.propose`)."""
55
+ """What the machine pre-computes for a human to confirm (:func:`paces.ask.propose`).
56
+
57
+ ``cut_meets`` is aligned with ``cuts``: ``True`` where one step ends and
58
+ another begins (so striking the cut merges them), ``False`` at the edge of a
59
+ gap between steps, where there is nothing to merge. Empty (an older proposal)
60
+ reads as all ``True``.
61
+ """
54
62
 
55
63
  kind: Literal["PacesAskProposal"] = PROPOSAL_KIND
56
64
  version: Literal[1] = CONTRACT_VERSION
@@ -63,8 +71,11 @@ class Proposal(_Wire):
63
71
  k_evidence: str
64
72
  extent: tuple[str, str] | None
65
73
  cuts: list[str]
74
+ cut_meets: list[bool] = []
66
75
  steps: list[ProposedStep]
67
76
  min_step_s: str
77
+ #: The decimal places every time here keeps (the page writes its own the same way).
78
+ time_places: int = Field(TIME_PLACES, ge=1)
68
79
  snap: Snap
69
80
 
70
81
 
@@ -5,22 +5,28 @@
5
5
 
6
6
  // ── pure core ─────────────────────────────────────────────────────────────
7
7
 
8
- const TIME_PLACES = 3;
8
+ /** The places a time keeps when the proposal does not say (one written before it carried timePlaces). */
9
+ const DFLT_TIME_PLACES = 3;
10
+
11
+ /** The places the proposal's times keep: Python's paces.segmentation.TIME_PLACES when it wrote it. */
12
+ const timePlaces = (proposal) => proposal.timePlaces ?? DFLT_TIME_PLACES;
9
13
 
10
14
  /**
11
15
  * Seconds as paces' wire decimal, exactly as Python's
12
- * decimal_str(t, places=3) writes it for t >= 0: 3 places, trailing zeros
16
+ * decimal_str(t, places=places) writes it for t >= 0: trailing zeros
13
17
  * dropped ("95.8"). toFixed breaks an exact binary tie (10.0625) upward;
14
18
  * Python's format rounds it to even ("10.062"), so a tie is corrected here.
15
19
  * toFixed(20) tells a tie apart: a double >= 0.0005 is never within 5e-21
16
- * of a tie without being on it.
20
+ * of a tie without being on it. `places` is an option, not a second
21
+ * argument, so times.map(timeStr) is not handed the index as places.
17
22
  */
18
- function timeStr(t) {
23
+ function timeStr(t, { places = DFLT_TIME_PLACES } = {}) {
19
24
  const x = Number(t);
20
- let text = x.toFixed(TIME_PLACES);
21
- if (x >= 0 && /\.\d{3}50*$/.test(x.toFixed(20)) && /[13579]$/.test(text)) {
22
- const digits = (BigInt(text.replace(".", "")) - 1n).toString().padStart(TIME_PLACES + 1, "0");
23
- text = `${digits.slice(0, -TIME_PLACES)}.${digits.slice(-TIME_PLACES)}`;
25
+ let text = x.toFixed(places);
26
+ const tie = new RegExp(`\\.\\d{${places}}50*$`);
27
+ if (x >= 0 && tie.test(x.toFixed(20)) && /[13579]$/.test(text)) {
28
+ const digits = (BigInt(text.replace(".", "")) - 1n).toString().padStart(places + 1, "0");
29
+ text = `${digits.slice(0, -places)}.${digits.slice(-places)}`;
24
30
  }
25
31
  text = text.replace(/0+$/, "").replace(/\.$/, "");
26
32
  return text === "-0" || text === "" ? "0" : text;
@@ -84,6 +90,13 @@ function nearest(values, t) {
84
90
 
85
91
  const same = (state, message = "") => ({ state, message });
86
92
 
93
+ /** True unless the proposal says no two steps meet at this cut (the edge of a gap). */
94
+ const meets = (proposal, cut) => !proposal.cutMeets || proposal.cutMeets[proposal.cuts.indexOf(cut)] !== false;
95
+
96
+ /** The steps have gaps, so a time between two steps belongs to none. */
97
+ const inGap = (proposal, t) =>
98
+ proposal.steps.length > 0 && !proposal.steps.some((step) => step.spans.some(([a, b]) => Number(a) <= t && t <= Number(b)));
99
+
87
100
  // One rule per action: (proposal, state, action) -> { state, message, fresh? }.
88
101
  // A refusal returns the same state and says why.
89
102
  const RULES = {
@@ -91,7 +104,7 @@ const RULES = {
91
104
  // M1: a struck cut is not a snap target, so strike + tap = move it.
92
105
  const targets = p.snap.targets.filter((c) => !s.struck.includes(c)).map(Number);
93
106
  const { t: snappedT, snapped } = snap(Number(raw), targets, Number(p.snap.windowS));
94
- const key = timeStr(snappedT);
107
+ const key = timeStr(snappedT, { places: timePlaces(p) });
95
108
  const t = Number(key);
96
109
  const at = mmss(key);
97
110
  if (p.cuts.includes(key)) {
@@ -104,6 +117,7 @@ const RULES = {
104
117
  return same(s, `Not added: ${at} is outside the part being checked (${mmss(lo)}–${mmss(hi)}).`);
105
118
  }
106
119
  }
120
+ if (inGap(p, t)) return same(s, `Not added: ${at} falls in a gap between steps, where no step spans that time.`);
107
121
  const inside = absentSpans(p, s).find(([a, b]) => a < t && t < b);
108
122
  if (inside) {
109
123
  return same(s, `Not added: ${at} is inside a step you marked as not in the video (${mmss(inside[0])}–${mmss(inside[1])}).`);
@@ -118,6 +132,7 @@ const RULES = {
118
132
 
119
133
  strike(p, s, { cut }) {
120
134
  if (!p.cuts.includes(cut) || s.struck.includes(cut)) return same(s);
135
+ if (!meets(p, cut)) return same(s, `No two steps meet at ${mmss(cut)} (it is the edge of a gap), so there is nothing to merge.`);
121
136
  const t = Number(cut);
122
137
  const border = p.steps.find(
123
138
  (step, i) => isAbsent(s, i) && step.spans.some((span) => span.map(Number).includes(t)),
@@ -179,12 +194,12 @@ const RULES = {
179
194
 
180
195
  duration(p, s, { seconds }) {
181
196
  const d = Number(seconds);
182
- if (!Number.isFinite(d) || d <= 0 || timeStr(d) === s.duration) return same(s);
197
+ if (!Number.isFinite(d) || d <= 0 || timeStr(d, { places: timePlaces(p) }) === s.duration) return same(s);
183
198
  const past = s.added.filter((t) => Number(t) >= d);
184
199
  const message = past.length
185
200
  ? `${past.length} of your cuts lie past the end of this media (${mmss(d)}) and will not be sent.`
186
201
  : "";
187
- return { state: { ...s, duration: timeStr(d) }, message };
202
+ return { state: { ...s, duration: timeStr(d, { places: timePlaces(p) }) }, message };
188
203
  },
189
204
  };
190
205
 
@@ -234,7 +249,7 @@ function buildAnswers(proposal, state) {
234
249
  for (const [i, step] of proposal.steps.entries()) {
235
250
  if (!isAbsent(state, i) || !step.spans.length) continue;
236
251
  const [a, b] = step.spans[0].map(Number);
237
- corrections.push({ verb: "absent", anchorT: timeStr((a + b) / 2), stepId: step.id, ...meta });
252
+ corrections.push({ verb: "absent", anchorT: timeStr((a + b) / 2, { places: timePlaces(proposal) }), stepId: step.id, ...meta });
238
253
  }
239
254
  for (const cut of proposal.cuts) {
240
255
  if (state.struck.includes(cut)) corrections.push({ verb: "merge", anchorT: cut, ...meta });
@@ -248,7 +263,7 @@ function buildAnswers(proposal, state) {
248
263
 
249
264
  /** Each cut the page lists: proposed (maybe struck) and added, in time order. */
250
265
  function cutRows(proposal, state) {
251
- const rows = proposal.cuts.map((t) => ({ t, kind: state.struck.includes(t) ? "struck" : "proposed" }));
266
+ const rows = proposal.cuts.map((t) => ({ t, kind: state.struck.includes(t) ? "struck" : "proposed", meets: meets(proposal, t) }));
252
267
  for (const t of new Set(state.added)) if (!proposal.cuts.includes(t)) rows.push({ t, kind: "added" });
253
268
  return rows.sort((a, b) => byTime(a.t, b.t));
254
269
  }
@@ -278,30 +293,42 @@ function draftKey(proposal) {
278
293
  /** How long the status line offers to undo a Start over. */
279
294
  const UNDO_MS = 15000;
280
295
 
281
- function startPage(doc) {
296
+ // ── DOM layer ─────────────────────────────────────────────────────────────
297
+ // startPage builds one page context and hands it to small wiring and render
298
+ // functions, each reading on its own: the header (k, restore, start over),
299
+ // the media, the keyboard, the lists, and the answers. Every state decision
300
+ // stays in reduce(); these only dispatch actions and draw.
301
+
302
+ /** The page's shared context: its elements, proposal, state and the two verbs, dispatch and render. */
303
+ function pageContext(doc) {
282
304
  const $ = (id) => doc.getElementById(id);
283
305
  const proposal = JSON.parse($("proposal").textContent);
284
306
  const store = draftStore(draftKey(proposal));
285
307
  const saved = store.load();
286
- let state = Object.assign(freshState(proposal), saved || {});
287
- let fresh = null; // the cut just added: highlighted on the next render only
288
- let undoOpen = false;
289
- let undoTimer = null;
290
- const video = $("video");
291
- const tapButton = $("tap");
292
-
293
- const say = (text) => { $("status-text").textContent = text; };
294
- const syncK = () => { $("k").value = state.k ?? ""; };
295
- function dispatch(action) {
296
- const out = reduce(proposal, state, { ...action, at: new Date().toISOString() });
297
- if (out.message) say(out.message);
298
- if (out.state !== state) { state = out.state; store.save(state); }
299
- fresh = out.fresh;
300
- render(); // also after a refusal: a checkbox the reducer refused flips back
308
+ const ctx = {
309
+ doc, $, proposal, store, saved,
310
+ state: Object.assign(freshState(proposal), saved || {}),
311
+ fresh: null, // the cut just added: highlighted on the next render only
312
+ undo: { open: false, timer: null },
313
+ video: $("video"),
314
+ tapButton: $("tap"),
315
+ };
316
+ ctx.say = (text) => { $("status-text").textContent = text; };
317
+ ctx.syncK = () => { $("k").value = ctx.state.k ?? ""; };
318
+ ctx.render = () => render(ctx);
319
+ ctx.dispatch = (action) => {
320
+ const out = reduce(proposal, ctx.state, { ...action, at: new Date().toISOString() });
321
+ if (out.message) ctx.say(out.message);
322
+ if (out.state !== ctx.state) { ctx.state = out.state; store.save(ctx.state); }
323
+ ctx.fresh = out.fresh;
324
+ ctx.render(); // also after a refusal: a checkbox the reducer refused flips back
301
325
  return out;
302
- }
326
+ };
327
+ return ctx;
328
+ }
303
329
 
304
- // Pressed feedback in the same frame as the press (the feedback principle).
330
+ /** Pressed feedback in the same frame as the press (the feedback principle). */
331
+ function wirePressedFeedback(doc) {
305
332
  doc.addEventListener("pointerdown", (e) => {
306
333
  const b = e.target.closest && e.target.closest("button");
307
334
  if (b) b.setAttribute("data-pressed", "");
@@ -309,36 +336,44 @@ function startPage(doc) {
309
336
  for (const type of ["pointerup", "pointercancel", "pointerleave"]) {
310
337
  doc.addEventListener(type, () => doc.querySelectorAll("button[data-pressed]").forEach((b) => b.removeAttribute("data-pressed")), true);
311
338
  }
339
+ }
312
340
 
341
+ /** The method line, the step count, a restored draft, Start over and its Undo. */
342
+ function wireHeader(ctx) {
343
+ const { $, proposal } = ctx;
313
344
  const methodBits = [proposal.method && `proposed by ${proposal.method}`, ...proposal.flags.filter((f) => !f.startsWith("try:"))];
314
345
  $("method").textContent = methodBits.filter(Boolean).join(" · ");
315
346
  $("k-evidence").textContent = proposal.kEvidence;
316
- if (saved) {
347
+ if (ctx.saved) {
317
348
  $("restored").hidden = false;
318
- $("restored-text").textContent = `Picked up where you left off${state.at ? ` (${new Date(state.at).toLocaleString()})` : ""}.`;
349
+ $("restored-text").textContent = `Picked up where you left off${ctx.state.at ? ` (${new Date(ctx.state.at).toLocaleString()})` : ""}.`;
319
350
  }
320
351
  $("start-over").addEventListener("click", () => {
321
- dispatch({ type: "startOver" });
352
+ ctx.dispatch({ type: "startOver" });
322
353
  $("restored").hidden = true;
323
- syncK();
324
- undoOpen = true;
325
- clearTimeout(undoTimer);
326
- undoTimer = setTimeout(() => { undoOpen = false; render(); }, UNDO_MS);
327
- render();
354
+ ctx.syncK();
355
+ ctx.undo.open = true;
356
+ clearTimeout(ctx.undo.timer);
357
+ ctx.undo.timer = setTimeout(() => { ctx.undo.open = false; ctx.render(); }, UNDO_MS);
358
+ ctx.render();
328
359
  });
329
360
  $("undo").addEventListener("click", () => {
330
- undoOpen = false;
331
- clearTimeout(undoTimer);
332
- dispatch({ type: "undoStartOver" });
333
- syncK();
361
+ ctx.undo.open = false;
362
+ clearTimeout(ctx.undo.timer);
363
+ ctx.dispatch({ type: "undoStartOver" });
364
+ ctx.syncK();
334
365
  });
366
+ ctx.syncK();
367
+ $("k").addEventListener("input", (e) => ctx.dispatch({ type: "setK", value: e.target.value }));
368
+ }
335
369
 
336
- syncK();
337
- $("k").addEventListener("input", (e) => dispatch({ type: "setK", value: e.target.value }));
338
-
339
- // Media: the proposal's own, or a file from this device. Loading and
340
- // failure each say so (the heavy-media principle); Cut here waits for the
341
- // media's metadata, so a tap always has a real clock under it.
370
+ /**
371
+ * Media: the proposal's own, or a file from this device. Loading and failure
372
+ * each say so (the heavy-media principle); Cut here waits for the media's
373
+ * metadata, so a tap always has a real clock under it.
374
+ */
375
+ function wireMedia(ctx) {
376
+ const { $, proposal, video, tapButton } = ctx;
342
377
  const mediaNote = (text) => { $("no-media-text").textContent = text; };
343
378
  const showMedia = (src, name) => {
344
379
  tapButton.disabled = true;
@@ -351,13 +386,13 @@ function startPage(doc) {
351
386
  video.addEventListener("loadedmetadata", () => {
352
387
  $("media-state").hidden = true;
353
388
  tapButton.disabled = false;
354
- dispatch({ type: "duration", seconds: video.duration });
389
+ ctx.dispatch({ type: "duration", seconds: video.duration });
355
390
  });
356
391
  video.addEventListener("error", () => {
357
392
  $("player").hidden = true;
358
393
  tapButton.disabled = true;
359
394
  mediaNote("This browser could not play that media (moved, missing, or a format it does not read). Open a copy from this device:");
360
- say("Could not play the media here.");
395
+ ctx.say("Could not play the media here.");
361
396
  });
362
397
  if (proposal.media && /youtu\.?be/.test(proposal.media)) {
363
398
  mediaNote("This page plays files, not YouTube links. Open a downloaded copy from this device:");
@@ -366,13 +401,19 @@ function startPage(doc) {
366
401
  }
367
402
  $("file").addEventListener("change", (e) => {
368
403
  const file = e.target.files && e.target.files[0];
369
- if (file) { showMedia(URL.createObjectURL(file), file.name); say(`Opened ${file.name}.`); }
404
+ if (file) { showMedia(URL.createObjectURL(file), file.name); ctx.say(`Opened ${file.name}.`); }
370
405
  });
406
+ }
371
407
 
372
- const tap = () => { if (!tapButton.disabled) dispatch({ type: "tap", t: video.currentTime }); };
408
+ /**
409
+ * Cut here, by button or Space. Space taps only from the page itself, the
410
+ * video or Cut here; every other button, link and summary keeps its native
411
+ * Space. A held key taps once.
412
+ */
413
+ function wireKeyboard(ctx) {
414
+ const { doc, $, video, tapButton } = ctx;
415
+ const tap = () => { if (!tapButton.disabled) ctx.dispatch({ type: "tap", t: video.currentTime }); };
373
416
  tapButton.addEventListener("click", tap);
374
- // Space taps only from the page itself, the video or Cut here; every other
375
- // button, link and summary keeps its native Space. A held key taps once.
376
417
  const spaceTargets = [doc.body, doc.documentElement, video, tapButton];
377
418
  doc.addEventListener("keydown", (e) => {
378
419
  if (e.code !== "Space" || !spaceTargets.includes(e.target) || $("player").hidden) return;
@@ -383,113 +424,138 @@ function startPage(doc) {
383
424
  // Cut here's own Space-click would tap a second time.
384
425
  if (e.code === "Space" && e.target === tapButton) e.preventDefault();
385
426
  });
427
+ }
386
428
 
387
- const button = (label, onClick, extra = {}) => {
388
- const b = doc.createElement("button");
389
- b.type = "button"; b.textContent = label;
390
- Object.assign(b, extra);
391
- b.addEventListener("click", onClick);
392
- return b;
393
- };
394
- const seek = (t) => () => { if (!$("player").hidden) { video.currentTime = Number(t); video.play(); } };
395
-
396
- function renderCuts() {
397
- const list = $("cuts");
398
- list.replaceChildren();
399
- for (const row of cutRows(proposal, state)) {
400
- const li = doc.createElement("li");
401
- li.className = row.kind + (row.t === fresh ? " fresh" : "");
402
- li.append(button(mmss(row.t), seek(row.t), { className: "time link", title: "Play from here"}));
403
- li.lastChild.dataset.focusKey = `time:${row.t}`;
404
- const label = doc.createElement("span");
405
- label.className = "grow muted small";
406
- label.textContent = { proposed: "proposed", struck: "not a cut", added: "added by you" }[row.kind];
407
- li.append(label);
408
- if (row.kind === "added") {
409
- li.append(button("Remove", () => dispatch({ type: "remove", cut: row.t })));
410
- li.lastChild.dataset.focusKey = `act:${row.t}`;
411
- } else {
412
- const struck = row.kind === "struck";
413
- li.append(button(struck ? "Keep it" : "Not a cut", () => dispatch({ type: struck ? "keep" : "strike", cut: row.t })));
414
- li.lastChild.setAttribute("aria-pressed", String(struck));
415
- li.lastChild.dataset.focusKey = `act:${row.t}`;
416
- }
417
- list.append(li);
418
- }
419
- if (!list.children.length) {
420
- const li = doc.createElement("li");
421
- li.className = "muted"; li.textContent = "No cuts yet. Tap along with the video to add them.";
422
- list.append(li);
429
+ function makeButton(doc, label, onClick, extra = {}) {
430
+ const b = doc.createElement("button");
431
+ b.type = "button"; b.textContent = label;
432
+ Object.assign(b, extra);
433
+ b.addEventListener("click", onClick);
434
+ return b;
435
+ }
436
+
437
+ /** Play the media from t, when it is showing. */
438
+ const seekTo = (ctx, t) => () => {
439
+ if (!ctx.$("player").hidden) { ctx.video.currentTime = Number(t); ctx.video.play(); }
440
+ };
441
+
442
+ /** An empty list says why it is empty. */
443
+ function emptyRow(doc, list, text) {
444
+ if (list.children.length) return;
445
+ const li = doc.createElement("li");
446
+ li.className = "muted"; li.textContent = text;
447
+ list.append(li);
448
+ }
449
+
450
+ function renderCuts(ctx) {
451
+ const { doc, $, proposal, state } = ctx;
452
+ const list = $("cuts");
453
+ list.replaceChildren();
454
+ for (const row of cutRows(proposal, state)) {
455
+ const li = doc.createElement("li");
456
+ li.className = row.kind + (row.t === ctx.fresh ? " fresh" : "");
457
+ li.append(makeButton(doc, mmss(row.t), seekTo(ctx, row.t), { className: "time link", title: "Play from here" }));
458
+ li.lastChild.dataset.focusKey = `time:${row.t}`;
459
+ const label = doc.createElement("span");
460
+ label.className = "grow muted small";
461
+ label.textContent = { proposed: "proposed", struck: "not a cut", added: "added by you" }[row.kind];
462
+ li.append(label);
463
+ if (row.kind === "added") {
464
+ li.append(makeButton(doc, "Remove", () => ctx.dispatch({ type: "remove", cut: row.t })));
465
+ li.lastChild.dataset.focusKey = `act:${row.t}`;
466
+ } else if (!row.meets) {
467
+ label.textContent = "edge of a gap";
468
+ } else {
469
+ const struck = row.kind === "struck";
470
+ li.append(makeButton(doc, struck ? "Keep it" : "Not a cut", () => ctx.dispatch({ type: struck ? "keep" : "strike", cut: row.t })));
471
+ li.lastChild.setAttribute("aria-pressed", String(struck));
472
+ li.lastChild.dataset.focusKey = `act:${row.t}`;
423
473
  }
474
+ list.append(li);
424
475
  }
476
+ emptyRow(doc, list, "No cuts yet. Tap along with the video to add them.");
477
+ }
425
478
 
426
- function renderSteps() {
427
- const list = $("steps");
428
- list.replaceChildren();
429
- for (const [i, step] of proposal.steps.entries()) {
430
- const li = doc.createElement("li");
431
- const label = doc.createElement("label");
432
- label.className = "grow";
433
- const box = doc.createElement("input");
434
- box.type = "checkbox";
435
- box.checked = isAbsent(state, i);
436
- box.disabled = !step.spans.length;
437
- box.dataset.focusKey = `step:${i}`;
438
- box.addEventListener("change", () => dispatch({ type: "absent", index: i, on: box.checked }));
439
- const span = step.spans[0];
440
- label.append(box, ` ${step.name || "(unnamed)"} `);
441
- const when = doc.createElement("span");
442
- when.className = "muted small";
443
- when.textContent = span ? `${mmss(span[0])}–${mmss(span[1])} · not in this video` : "has no time in this video to mark";
444
- label.append(when);
445
- li.append(label);
446
- list.append(li);
447
- }
448
- if (!proposal.steps.length) {
449
- const li = doc.createElement("li");
450
- li.className = "muted"; li.textContent = "No steps were proposed.";
451
- list.append(li);
452
- }
479
+ function renderSteps(ctx) {
480
+ const { doc, $, proposal, state } = ctx;
481
+ const list = $("steps");
482
+ list.replaceChildren();
483
+ for (const [i, step] of proposal.steps.entries()) {
484
+ const li = doc.createElement("li");
485
+ const label = doc.createElement("label");
486
+ label.className = "grow";
487
+ const box = doc.createElement("input");
488
+ box.type = "checkbox";
489
+ box.checked = isAbsent(state, i);
490
+ box.disabled = !step.spans.length;
491
+ box.dataset.focusKey = `step:${i}`;
492
+ box.addEventListener("change", () => ctx.dispatch({ type: "absent", index: i, on: box.checked }));
493
+ const span = step.spans[0];
494
+ label.append(box, ` ${step.name || "(unnamed)"} `);
495
+ const when = doc.createElement("span");
496
+ when.className = "muted small";
497
+ when.textContent = span ? `${mmss(span[0])}–${mmss(span[1])} · not in this video` : "has no time in this video to mark";
498
+ label.append(when);
499
+ li.append(label);
500
+ list.append(li);
453
501
  }
502
+ emptyRow(doc, list, "No steps were proposed.");
503
+ }
454
504
 
455
- const answersText = () => JSON.stringify(buildAnswers(proposal, state), null, 2);
456
- // Rows are rebuilt on every change; keep keyboard focus on the same control
457
- // (or on its list, never on <body>, where Space would add a cut).
458
- function render() {
459
- const focused = doc.activeElement;
460
- const focusKey = focused && focused.dataset ? focused.dataset.focusKey : undefined;
461
- const focusList = focused && focused.closest ? focused.closest("#cuts, #steps") : null;
462
- renderCuts();
463
- fresh = null; // the highlight plays once, for the row just added
464
- renderSteps();
465
- if (focusKey) {
466
- const again = doc.querySelector(`[data-focus-key="${focusKey}"]`);
467
- if (again) again.focus();
468
- else if (focusList) focusList.focus();
469
- }
470
- $("k-state").textContent = !state.kTouched
471
- ? "Edit the number to confirm it. Until you do, it is not sent."
472
- : state.k === null
473
- ? "That is not a step count, so none is sent."
474
- : "Saved with your answers for segmenters that use a known step count.";
475
- $("undo").hidden = !(undoOpen && state.previous);
476
- $("answers").value = answersText();
505
+ const answersText = (ctx) => JSON.stringify(buildAnswers(ctx.proposal, ctx.state), null, 2);
506
+
507
+ /**
508
+ * Draw the page from the state. Rows are rebuilt on every change; keyboard
509
+ * focus stays on the same control (or on its list, never on <body>, where
510
+ * Space would add a cut).
511
+ */
512
+ function render(ctx) {
513
+ const { doc, $, state } = ctx;
514
+ const focused = doc.activeElement;
515
+ const focusKey = focused && focused.dataset ? focused.dataset.focusKey : undefined;
516
+ const focusList = focused && focused.closest ? focused.closest("#cuts, #steps") : null;
517
+ renderCuts(ctx);
518
+ ctx.fresh = null; // the highlight plays once, for the row just added
519
+ renderSteps(ctx);
520
+ if (focusKey) {
521
+ const again = doc.querySelector(`[data-focus-key="${focusKey}"]`);
522
+ if (again) again.focus();
523
+ else if (focusList) focusList.focus();
477
524
  }
525
+ $("k-state").textContent = !state.kTouched
526
+ ? "Edit the number to confirm it. Until you do, it is not sent."
527
+ : state.k === null
528
+ ? "That is not a step count, so none is sent."
529
+ : "Saved with your answers for segmenters that use a known step count.";
530
+ $("undo").hidden = !(ctx.undo.open && state.previous);
531
+ $("answers").value = answersText(ctx);
532
+ }
478
533
 
534
+ /** Download or copy the answers; a refused clipboard selects them instead. */
535
+ function wireAnswers(ctx) {
536
+ const { doc, $ } = ctx;
479
537
  $("download").addEventListener("click", () => {
480
- const url = URL.createObjectURL(new Blob([answersText() + "\n"], { type: "application/json" }));
538
+ const url = URL.createObjectURL(new Blob([answersText(ctx) + "\n"], { type: "application/json" }));
481
539
  const a = doc.createElement("a");
482
540
  a.href = url; a.download = "answers.json";
483
541
  doc.body.append(a); a.click(); a.remove();
484
542
  setTimeout(() => URL.revokeObjectURL(url), 1000);
485
- say("Downloaded answers.json.");
543
+ ctx.say("Downloaded answers.json.");
486
544
  });
487
545
  $("copy").addEventListener("click", async () => {
488
- try { await navigator.clipboard.writeText(answersText()); say("Copied the answers."); }
489
- catch { $("answers").closest("details").open = true; $("answers").select(); say("The answers are selected: copy them with your keyboard."); }
546
+ try { await navigator.clipboard.writeText(answersText(ctx)); ctx.say("Copied the answers."); }
547
+ catch { $("answers").closest("details").open = true; $("answers").select(); ctx.say("The answers are selected: copy them with your keyboard."); }
490
548
  });
549
+ }
491
550
 
492
- render();
551
+ function startPage(doc) {
552
+ const ctx = pageContext(doc);
553
+ wirePressedFeedback(doc);
554
+ wireHeader(ctx);
555
+ wireMedia(ctx);
556
+ wireKeyboard(ctx);
557
+ wireAnswers(ctx);
558
+ ctx.render();
493
559
  }
494
560
 
495
561
  if (typeof module !== "undefined" && module.exports) {
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "paces"
9
- version = "0.0.25"
9
+ version = "0.0.27"
10
10
  description = "Turn instructional media into structured, interactive learning material"
11
11
  readme = "README.md"
12
12
  license = "MIT"
@@ -553,3 +553,69 @@ def test_the_contract_is_declared_as_models():
553
553
  assert schemas["proposal"]["properties"]["minStepS"]["type"] == "string"
554
554
  assert schemas["answers"]["additionalProperties"] is False
555
555
  assert AnswersDocument.model_validate(_answers()).k == 4
556
+
557
+
558
+ def test_a_gap_cut_does_not_meet():
559
+ seg = segment(boundaries=[0, 10, 30], steps=["a", "b"])
560
+ assert propose(seg)["cutMeets"] == [True]
561
+ gapped = Segmentation(
562
+ boundaries=(0, 10, 20, 30),
563
+ steps=(
564
+ segment(boundaries=[0, 10, 20, 30], steps=["a", "b", "c"]).steps[0],
565
+ ),
566
+ )
567
+ p = propose(gapped)
568
+ assert p["cuts"] == ["10", "20"] and p["cutMeets"] == [False, False]
569
+
570
+
571
+ @needs_node
572
+ def test_js_refuses_striking_a_gap_edge_and_tapping_a_gap():
573
+ proposal = {
574
+ "k": 2, "extent": ["0", "30"], "cuts": ["10", "20"], "cutMeets": [False, True],
575
+ "steps": [
576
+ {"id": "a", "name": "a", "spans": [["0", "10"]]},
577
+ {"id": "b", "name": "b", "spans": [["20", "30"]]},
578
+ ],
579
+ "minStepS": "0.2", "snap": {"windowS": "0", "targets": ["10", "20"]},
580
+ }
581
+ import json as _j
582
+
583
+ out = _run_js(
584
+ f"(() => {{ const p = {_j.dumps(proposal)}; const s = core.freshState(p);"
585
+ "const a = core.reduce(p, s, {type: 'strike', cut: '10'});"
586
+ "const b = core.reduce(p, s, {type: 'tap', t: 15});"
587
+ "const c = core.reduce(p, s, {type: 'tap', t: 25});"
588
+ "return [a.state.struck, a.message, b.state.added, b.message, c.state.added]; })()"
589
+ )
590
+ assert out[0] == [] and "nothing to merge" in out[1]
591
+ assert out[2] == [] and "gap between steps" in out[3]
592
+ assert out[4] == ["25"]
593
+
594
+
595
+ @needs_node
596
+ def test_the_proposal_says_how_many_places_its_times_keep_and_the_page_keeps_them():
597
+ """paces#41 (3): the places travel in the proposal (``timePlaces``, Python's
598
+ ``TIME_PLACES``) instead of being a second constant in the page, and the
599
+ page writes every time it makes at that many places; a proposal written
600
+ before the field reads as 3."""
601
+ from paces.segmentation import TIME_PLACES
602
+
603
+ proposal = propose(segment("video.mp4"))
604
+ assert proposal["timePlaces"] == TIME_PLACES
605
+ actions = [{"type": "duration", "seconds": 30.0}, {"type": "tap", "t": 10.123456}]
606
+ for places, expected in ((TIME_PLACES, "10.123"), (2, "10.12"), (None, "10.123")):
607
+ p = {**proposal, "timePlaces": places}
608
+ if places is None:
609
+ del p["timePlaces"]
610
+ (_, tapped) = _reduce(p, actions)
611
+ assert tapped["state"]["added"] == [expected], places
612
+
613
+
614
+ @needs_node
615
+ def test_the_page_script_still_loads_as_a_module_with_only_its_pure_core():
616
+ """paces#41 (2): the DOM layer is split into functions (media, keyboard,
617
+ render, header, answers); requiring the script runs none of them and
618
+ exports the same pure core."""
619
+ assert _run_js("Object.keys(core).sort()") == sorted(
620
+ ["timeStr", "mmss", "snap", "freshState", "reduce", "buildAnswers", "cutRows"]
621
+ )
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes