story_player 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Story Player</title>
7
+ <style>
8
+ :root { color-scheme: light dark; }
9
+ * { box-sizing: border-box; }
10
+ body {
11
+ margin: 0; min-height: 100vh; background: Canvas; color: CanvasText;
12
+ font-family: ui-sans-serif, system-ui, sans-serif;
13
+ display: flex; flex-direction: column;
14
+ }
15
+ .stage {
16
+ flex: 1; display: flex; align-items: center; justify-content: center;
17
+ padding: 16px 16px 88px;
18
+ }
19
+ .stage img {
20
+ max-width: 100%; max-height: calc(100vh - 120px);
21
+ border-radius: 8px; box-shadow: 0 12px 40px rgba(0,0,0,0.45);
22
+ background: #000;
23
+ }
24
+ .pane {
25
+ position: fixed; left: 12px; right: 12px; bottom: 12px;
26
+ display: flex; flex-direction: column; gap: 6px;
27
+ padding: 8px 10px; border-radius: 10px;
28
+ background: light-dark(#e2e8f0, #14181c);
29
+ box-shadow: 0 8px 24px rgba(0,0,0,0.35);
30
+ }
31
+ [hidden] { display: none !important; }
32
+ .progress {
33
+ height: 6px; border-radius: 999px; background: rgba(255,255,255,0.18); overflow: hidden;
34
+ }
35
+ .progress > i { display: block; height: 100%; width: 0%; background: #7dd3fc; }
36
+ .row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
37
+ .meta { flex: 1 1 150px; overflow-wrap: anywhere; font-size: 12px; line-height: 1.3; }
38
+ button, select {
39
+ border: 0; border-radius: 6px; background: rgba(255,255,255,0.12); color: inherit;
40
+ min-width: 32px; height: 32px; padding: 0 8px; cursor: pointer;
41
+ }
42
+ button:hover, select:hover { background: rgba(255,255,255,0.2); }
43
+ button:focus-visible, select:focus-visible { outline: 2px solid Highlight; }
44
+ .fab {
45
+ position: fixed; left: 50%; bottom: 12px; transform: translateX(-50%);
46
+ border: 0; border-radius: 999px; background: light-dark(#e2e8f0, #14181c); color: #f4f6f8;
47
+ height: 36px; padding: 0 14px; cursor: pointer;
48
+ }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <div class="stage"><img id="frame" alt="Demo frame"></div>
53
+ <div class="pane" id="pane">
54
+ <div class="progress" role="progressbar" aria-label="Demo progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><i id="fill"></i></div>
55
+ <div class="row">
56
+ <strong id="outcome" hidden></strong>
57
+ <button type="button" data-act="back" aria-label="Backward">⏮</button>
58
+ <button type="button" data-act="play" aria-label="Play">▶</button>
59
+ <button type="button" data-act="pause" aria-label="Pause">⏸</button>
60
+ <button type="button" data-act="stop" aria-label="Stop">⏹</button>
61
+ <button type="button" data-act="forward" aria-label="Forward">⏭</button>
62
+ <select id="seek" aria-label="Go to a frame"></select>
63
+ <select id="speed" aria-label="Speed">
64
+ <option value="0.25">0.25×</option>
65
+ <option value="0.5">0.5×</option>
66
+ <option value="1" selected>1×</option>
67
+ <option value="1.5">1.5×</option>
68
+ <option value="2">2×</option>
69
+ </select>
70
+ <div class="meta" id="meta"></div>
71
+ <button type="button" data-act="hide" aria-label="Hide controls">Hide</button>
72
+ </div>
73
+ </div>
74
+ <button type="button" class="fab" id="fab" aria-label="Show controls" hidden>Demo</button>
75
+ <script>
76
+ const manifest = __DEMO_MANIFEST__;
77
+ const frames = manifest.frames || [];
78
+ const outcome = document.getElementById("outcome");
79
+ if (manifest.outcome) {
80
+ outcome.textContent = manifest.outcome[0].toUpperCase() + manifest.outcome.slice(1);
81
+ outcome.hidden = false;
82
+ }
83
+ const img = document.getElementById("frame");
84
+ const fill = document.getElementById("fill");
85
+ const bar = document.querySelector(".progress");
86
+ const meta = document.getElementById("meta");
87
+ const pane = document.getElementById("pane");
88
+ const fab = document.getElementById("fab");
89
+ const seekSelect = document.getElementById("seek");
90
+ frames.forEach((_, frameIndex) => seekSelect.add(new Option(`Frame ${frameIndex + 1}`, frameIndex)));
91
+ const speedSelect = document.getElementById("speed");
92
+ const DELAY_MS = 700;
93
+ let index = 0;
94
+ let mode = "paused";
95
+ let speed = manifest.defaultSpeed || 1;
96
+ let controlsHidden = false;
97
+ let timer = null;
98
+
99
+ function render() {
100
+ if (frames.length === 0) {
101
+ img.hidden = true;
102
+ pane.querySelector(".progress").hidden = true;
103
+ for (const control of pane.querySelectorAll("button, select")) control.hidden = true;
104
+ meta.textContent = `${manifest.chapter || "Story"} · No frames were captured.`;
105
+ return;
106
+ }
107
+
108
+ const frame = frames[index] || { file: "", label: "empty" };
109
+ img.src = frame.file;
110
+ img.alt = frame.label || "Demo frame";
111
+ const pct = frames.length ? ((index + 1) / frames.length) * 100 : 0;
112
+ fill.style.width = pct.toFixed(2) + "%";
113
+ bar.setAttribute("aria-valuenow", String(Math.round(pct)));
114
+ meta.textContent = `${manifest.chapter || "Demo"} · Frame ${Math.min(index + 1, frames.length)} / ${frames.length} — ${frame.label || ""}`;
115
+ speedSelect.value = String(speed);
116
+ seekSelect.value = String(index);
117
+ const hidden = controlsHidden;
118
+ pane.hidden = hidden;
119
+ fab.hidden = !hidden;
120
+ }
121
+
122
+ function setHidden(hidden) {
123
+ controlsHidden = hidden;
124
+ render();
125
+ (hidden ? fab : pane.querySelector('[data-act="hide"]')).focus();
126
+ }
127
+
128
+ function show(i, pause) {
129
+ index = Math.max(0, Math.min(frames.length - 1, i));
130
+ if (pause) mode = "paused";
131
+ render();
132
+ schedule();
133
+ }
134
+
135
+ function schedule() {
136
+ clearTimeout(timer);
137
+ if (mode !== "playing" || frames.length === 0) return;
138
+ timer = setTimeout(() => {
139
+ if (index >= frames.length - 1) {
140
+ mode = "paused";
141
+ render();
142
+ return;
143
+ }
144
+ index += 1;
145
+ render();
146
+ schedule();
147
+ }, DELAY_MS / Math.max(speed, 0.25));
148
+ }
149
+
150
+ document.getElementById("pane").addEventListener("click", (event) => {
151
+ const btn = event.target.closest("[data-act]");
152
+ if (!btn) return;
153
+ const act = btn.getAttribute("data-act");
154
+ if (act === "play") { if (index === frames.length - 1) index = 0; mode = "playing"; schedule(); }
155
+ if (act === "pause") { mode = "paused"; schedule(); }
156
+ if (act === "stop") { mode = "paused"; show(0, true); }
157
+ if (act === "back") show(index - 1, true);
158
+ if (act === "forward") show(index + 1, true);
159
+ if (act === "hide") setHidden(true);
160
+ render();
161
+ });
162
+
163
+ speedSelect.addEventListener("change", () => {
164
+ speed = Number(speedSelect.value) || 1;
165
+ schedule();
166
+ });
167
+ seekSelect.addEventListener("change", () => show(Number(seekSelect.value), true));
168
+ fab.addEventListener("click", () => setHidden(false));
169
+
170
+ window.addEventListener("keydown", (event) => {
171
+ if (event.target.closest("select, input")) return;
172
+ if (event.code === "Space" && !event.target.closest("button")) {
173
+ event.preventDefault();
174
+ mode = mode === "playing" ? "paused" : "playing";
175
+ schedule();
176
+ render();
177
+ } else if (event.key === "ArrowLeft") show(index - 1, true);
178
+ else if (event.key === "ArrowRight") show(index + 1, true);
179
+ else if (event.key === "Escape") setHidden(true);
180
+ else if (["1","2","3","4","5"].includes(event.key)) {
181
+ speed = [0.25, 0.5, 1, 1.5, 2][Number(event.key) - 1];
182
+ schedule();
183
+ render();
184
+ }
185
+ });
186
+
187
+ if (manifest.startPaused !== false) mode = "paused";
188
+ render();
189
+ </script>
190
+ </body>
191
+ </html>
@@ -0,0 +1,65 @@
1
+ :host {
2
+ all: initial;
3
+ position: fixed;
4
+ inset: 0;
5
+ z-index: 2147483645;
6
+ pointer-events: none;
7
+ color-scheme: light dark;
8
+ font: 13px/1.35 system-ui, sans-serif;
9
+ --paper: light-dark(#f8fafc, #181c24);
10
+ --ink: light-dark(#161b23, #f1f5f9);
11
+ --line: light-dark(#64748b, #94a3b8);
12
+ --control: light-dark(#e2e8f0, #323a46);
13
+ --active: light-dark(#c6d4e4, #455366);
14
+ --focus: light-dark(#0059ae, #8ad1ff);
15
+ }
16
+ *, *::before, *::after { box-sizing: border-box; }
17
+ [hidden] { display: none !important; }
18
+ .pane, .reopen {
19
+ position: fixed;
20
+ inset-inline: 8px;
21
+ bottom: 8px;
22
+ max-width: 42rem;
23
+ margin-inline: auto;
24
+ background: var(--paper);
25
+ color: var(--ink);
26
+ border: 1px solid var(--line);
27
+ border-radius: 9px;
28
+ box-shadow: 0 4px 20px #0003;
29
+ pointer-events: auto;
30
+ }
31
+ .pane { padding: 6px 8px; max-height: 48vh; overflow: auto; }
32
+ .pane.reviewing { max-height: min(85vh, calc(100vh - 16px)); }
33
+ .heading, .controls { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; }
34
+ .caption { flex: 1; min-width: 0; overflow-wrap: anywhere; }
35
+ .position { display: block; }
36
+ progress { display: block; width: 100%; height: 7px; margin: 5px 0; accent-color: var(--focus); }
37
+ [role="status"] { margin: 4px 0 6px; }
38
+ button, select {
39
+ border: 0;
40
+ border-radius: 5px;
41
+ min-width: 32px;
42
+ min-height: 32px;
43
+ padding: 3px 8px;
44
+ background: var(--control);
45
+ color: var(--ink);
46
+ font: inherit;
47
+ cursor: pointer;
48
+ }
49
+ button:hover:not(:disabled), select:hover:not(:disabled), button:active:not(:disabled) { background: var(--active); }
50
+ button:disabled, select:disabled { opacity: .54; cursor: default; }
51
+ :focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
52
+ .reopen { width: max-content; padding-inline: 16px; }
53
+
54
+ .review { display: grid; gap: 6px; }
55
+ .outcome {
56
+ width: fit-content;
57
+ border: 1px solid var(--line);
58
+ border-radius: 5px;
59
+ padding: 2px 7px;
60
+ }
61
+ .outcome[data-outcome="passed"] { color: light-dark(#126237, #8de4ab); }
62
+ .outcome[data-outcome="failed"] { color: light-dark(#a91e2d, #ffb0b8); }
63
+ .playlist { margin: 0; min-width: 0; padding: 4px 6px 6px; border: 1px solid var(--line); border-radius: 6px; }
64
+ .playlist legend { padding: 0 4px; }
65
+ .playlist select { max-width: 100%; }
@@ -0,0 +1,195 @@
1
+ async (call, css) => {
2
+ const key = Symbol.for("demoStage.player");
3
+ try {
4
+ if (await call("state") === false || window[key]) return;
5
+ } catch { return; }
6
+ const events = new AbortController();
7
+ const host = document.createElement("div");
8
+ host.id = "demo-stage-player";
9
+ const shadow = host.attachShadow({mode: "open"});
10
+ const style = new CSSStyleSheet();
11
+ style.replaceSync(css);
12
+ shadow.adoptedStyleSheets = [style];
13
+ shadow.innerHTML = `
14
+ <section class="pane" aria-label="Story Player" hidden>
15
+ <div class="heading">
16
+ <div class="caption"><strong></strong><span class="position"></span></div>
17
+ <strong class="outcome" aria-live="polite" hidden></strong>
18
+ <button type="button" data-action="hide" aria-label="Hide controls" title="Hide controls">Hide</button>
19
+ </div>
20
+ <progress aria-label="Demo progress"></progress>
21
+ <p role="status"></p>
22
+ <div class="controls">
23
+ <button type="button" data-action="back" aria-label="Backward" title="Previous visited step">⏮</button>
24
+ <button type="button" disabled data-action="play" aria-label="Play" title="Restore the current test step and resume">▶</button>
25
+ <button type="button" data-action="pause" aria-label="Pause" title="Pause">⏸</button>
26
+ <button type="button" data-action="stop" aria-label="Stop" title="Pause and return to the first step">⏹</button>
27
+ <button type="button" disabled data-action="forward" aria-label="Forward" title="Next step">⏭</button>
28
+ <button type="button" data-action="restore" aria-label="Restore" title="Restore this step">↺</button>
29
+ <button type="button" data-action="finish" hidden>Check result</button>
30
+ <select aria-label="Go to a visited step" title="Go to a visited step"></select>
31
+ <select aria-label="Speed" title="Playback speed">
32
+ <option value="0.25">0.25×</option><option value="0.5">0.5×</option>
33
+ <option value="1" selected>1×</option><option value="1.5">1.5×</option><option value="2">2×</option>
34
+ </select>
35
+ </div>
36
+ <div class="review" hidden>
37
+ <div class="controls">
38
+ <button type="button" data-action="history" hidden>Run history</button>
39
+ <button type="button" data-action="close-story">Close story</button>
40
+ </div>
41
+ <fieldset class="playlist" hidden>
42
+ <legend>Playlist</legend>
43
+ <div class="controls">
44
+ <button type="button" data-action="previous-story" aria-label="Previous story" title="Previous story">Previous</button>
45
+ <button type="button" data-action="replay-story" aria-label="Replay story" title="Replay story">Replay</button>
46
+ <button type="button" data-action="next-story" aria-label="Next story" title="Next story">Next</button>
47
+ <select aria-label="Choose a story"></select>
48
+ <button type="button" data-action="open-story">Open story</button>
49
+ </div>
50
+ </fieldset>
51
+ </div>
52
+ </section>
53
+ <button type="button" class="reopen" aria-label="Show controls" hidden>Story Player</button>
54
+ `;
55
+
56
+ const find = selector => shadow.querySelector(selector);
57
+ const pane = find(".pane");
58
+ const reopen = find(".reopen");
59
+ const seek = find('[aria-label="Go to a visited step"]');
60
+ const speed = find('[aria-label="Speed"]');
61
+ const signal = events.signal;
62
+ const storySelect = find('[aria-label="Choose a story"]');
63
+ const playlistPanel = find(".playlist");
64
+ let playlistRendered = false;
65
+ let state;
66
+ let hidden = false;
67
+ try { hidden = sessionStorage.getItem("demoStage.controlsHidden") === "1"; } catch {}
68
+
69
+ function show() {
70
+ pane.hidden = !state || hidden;
71
+ reopen.hidden = !state || !hidden;
72
+ }
73
+
74
+ function renderReview(view) {
75
+ const review = view.mode === "review";
76
+ pane.classList.toggle("reviewing", review);
77
+ find(".review").hidden = !review;
78
+ find(".pane > .controls").hidden = review;
79
+ find("progress").hidden = review;
80
+ const result = find(".outcome");
81
+ result.hidden = !review;
82
+ if (!review) return;
83
+
84
+ result.textContent = view.outcome[0].toUpperCase() + view.outcome.slice(1);
85
+ result.dataset.outcome = view.outcome;
86
+ find('[data-action="history"]').hidden = !view.history;
87
+ const close = find('[data-action="close-story"]');
88
+ close.textContent = view.playlist ? "Exit playlist" : "Close story";
89
+ playlistPanel.hidden = !view.playlist;
90
+ if (!view.playlist || playlistRendered) return;
91
+
92
+ const {titles, current, outcomes} = view.playlist;
93
+ titles.forEach((title, index) => {
94
+ const outcome = index === current ? view.outcome : outcomes[index];
95
+ storySelect.add(new Option(`${index + 1}. ${title} · ${outcome || "queued"}`, index));
96
+ });
97
+ storySelect.value = current;
98
+ find('[data-action="previous-story"]').disabled = current === 0;
99
+ find('[data-action="next-story"]').disabled = current === titles.length - 1;
100
+ playlistRendered = true;
101
+ }
102
+
103
+ function render(view) {
104
+ if (!view || (state && state.revision >= view.revision)) return;
105
+ state = view;
106
+ const recovering = view.mode === "recovering";
107
+ const playing = view.mode === "playing";
108
+ const progress = find("progress");
109
+ progress.max = view.total;
110
+ progress.value = view.cursor + 1;
111
+ find("strong").textContent = view.title;
112
+ const position = find(".position");
113
+ position.hidden = !view.label;
114
+ position.textContent = view.mode === "review"
115
+ ? `Last step · ${view.label}`
116
+ : `Step ${view.cursor + 1} / ${view.total}${view.final ? "" : "+"} · ${view.label}`;
117
+ find("[role=status]").textContent = view.status;
118
+ find('[data-action="play"]').disabled = playing || recovering || view.final;
119
+ find('[data-action="pause"]').disabled = !playing;
120
+ find('[data-action="back"]').disabled = recovering || view.cursor === 0;
121
+ find('[data-action="forward"]').disabled = recovering || (view.final && view.cursor === view.count - 1);
122
+ find('[data-action="finish"]').hidden = !view.final;
123
+ find('[data-action="finish"]').disabled = recovering;
124
+ find('[data-action="stop"]').disabled = recovering;
125
+ find('[data-action="restore"]').disabled = recovering;
126
+ while (seek.options.length < view.count) {
127
+ const index = seek.options.length;
128
+ seek.add(new Option(`Step ${index + 1}`, index));
129
+ }
130
+ seek.value = view.cursor;
131
+ seek.disabled = recovering || view.count < 2;
132
+ speed.value = view.speed;
133
+ speed.disabled = recovering;
134
+ renderReview(view);
135
+ show();
136
+ }
137
+
138
+ function setHidden(value) {
139
+ hidden = value;
140
+ try { sessionStorage.setItem("demoStage.controlsHidden", value ? "1" : "0"); } catch {}
141
+ show();
142
+ (value ? reopen : find('[data-action="hide"]')).focus();
143
+ }
144
+
145
+ async function send(action, value) {
146
+ try {
147
+ if (await call(action, {gate: state.gate, value})) return;
148
+ } catch {
149
+ // A navigation can replace the page before a command is acknowledged.
150
+ }
151
+ find("[role=status]").textContent = "That control is unavailable. Try again.";
152
+ }
153
+
154
+ pane.addEventListener("click", event => {
155
+ const action = event.target.closest("button")?.dataset.action;
156
+ if (action === "hide") setHidden(true);
157
+ else if (action && state.mode === "review" && state.playlist && action.endsWith("-story") && action !== "close-story") {
158
+ const current = state.playlist.current;
159
+ const index = ({
160
+ "previous-story": current - 1,
161
+ "next-story": current + 1,
162
+ "replay-story": current,
163
+ "open-story": Number(storySelect.value)
164
+ })[action];
165
+ void send("select-story", index);
166
+ } else if (action) void send(action);
167
+ }, {signal});
168
+ pane.addEventListener("keydown", event => {
169
+ if (event.key === "Escape") setHidden(true);
170
+ if (event.target.tagName !== "BUTTON" || state.mode === "review") return;
171
+ const action = ({ArrowLeft: "back", ArrowRight: "forward"})[event.key];
172
+ if (action && !find(`[data-action="${action}"]`).disabled) {
173
+ event.preventDefault();
174
+ void send(action);
175
+ }
176
+ }, {signal});
177
+ reopen.addEventListener("click", () => setHidden(false), {signal});
178
+ seek.addEventListener("change", () => void send("seek", Number(seek.value)), {signal});
179
+ speed.addEventListener("change", () => void send("speed", Number(speed.value)), {signal});
180
+
181
+ const mount = () => {
182
+ if (!host.isConnected && document.documentElement) document.documentElement.append(host);
183
+ };
184
+ window[key] = {
185
+ render,
186
+ close() {
187
+ events.abort();
188
+ host.remove();
189
+ delete window[key];
190
+ }
191
+ };
192
+ if (document.documentElement) mount();
193
+ else document.addEventListener("DOMContentLoaded", mount, {once: true, signal});
194
+ try { render(await call("state")); } catch { /* The run has already closed. */ }
195
+ }
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+ require "uri"
6
+
7
+ module StoryPlayer
8
+ class Bridge
9
+ attr_reader :primary_origin
10
+
11
+ def self.location(url)
12
+ uri = URI.parse(url)
13
+ uri if uri.is_a?(URI::HTTP) && uri.host
14
+ rescue URI::InvalidURIError
15
+ nil
16
+ end
17
+
18
+ def self.playwright_error?(error)
19
+ defined?(::Playwright::Error) && error.is_a?(::Playwright::Error)
20
+ end
21
+
22
+ def initialize(page, allowed_origins: [])
23
+ @page = page
24
+ @primary_origin = self.class.location(page.url)&.origin
25
+ raise Error, "Open an HTTP or HTTPS page before starting the stage" unless @primary_origin
26
+
27
+ @origins = [@primary_origin, *allowed_origins.map { |address| self.class.location(address)&.normalize&.origin }]
28
+ raise ArgumentError, "Expected HTTP or HTTPS origins" if @origins.include?(nil)
29
+
30
+ @origins.uniq!
31
+ @name = "demoStage_#{SecureRandom.hex(12)}"
32
+ end
33
+
34
+ def start(bootstrap, cleanup:, &handler)
35
+ @active = true
36
+ @cleanup = cleanup
37
+ @binding = @page.expose_binding(@name, ->(source, operation, argument = nil) do
38
+ frame = source.fetch(:frame)
39
+ location = self.class.location(frame.url)
40
+ next false unless @active && frame.parent_frame.nil? && @origins.include?(location&.origin)
41
+
42
+ handler.call(location, operation, argument)
43
+ end)
44
+ source = <<~JS
45
+ (() => {
46
+ if (window !== window.top || !#{@origins.to_json}.includes(location.origin)) return;
47
+ const call = (...args) => window[#{@name.to_json}](...args);
48
+ #{bootstrap}
49
+ })();
50
+ JS
51
+ @script = @page.add_init_script(script: source)
52
+ evaluate(source)
53
+ end
54
+
55
+ def trusted_page?
56
+ allows?(@page.url)
57
+ end
58
+
59
+ def allows?(url)
60
+ @origins.include?(self.class.location(url)&.origin)
61
+ end
62
+
63
+ def evaluate(source, **options)
64
+ @page.evaluate(source, **options) if trusted_page? && !@page.closed?
65
+ rescue => error
66
+ return if recoverable_playwright_error?(error)
67
+
68
+ raise
69
+ end
70
+
71
+ def close
72
+ @active = false
73
+ return if @page.closed?
74
+
75
+ dispose(@script)
76
+ dispose(@binding)
77
+ evaluate(@cleanup) if @cleanup
78
+ rescue => error
79
+ return if self.class.playwright_error?(error) && @page.closed?
80
+
81
+ raise
82
+ end
83
+
84
+ private
85
+
86
+ def recoverable_playwright_error?(error)
87
+ self.class.playwright_error?(error) &&
88
+ (@page.closed? || error.message.match?(/Execution context was destroyed|Cannot find context with specified id/i))
89
+ end
90
+
91
+ # Playwright Ruby 1.65+ returns Disposable handles from expose_binding and
92
+ # add_init_script. Older clients return a Proc or nil with no dispose API.
93
+ def dispose(handle)
94
+ handle.dispose if handle.respond_to?(:dispose)
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "capybara"
4
+ require "story_player"
5
+
6
+ module StoryPlayer
7
+ module Capybara
8
+ module Actions
9
+ %i[visit click_button click_link click_on fill_in].each do |action|
10
+ define_method(action) do |*arguments, **keywords, &block|
11
+ result = super(*arguments, **keywords, &block)
12
+ run = Thread.current[:story_player_run]
13
+ run&.capybara_action(self, action, arguments.first || keywords[:id])
14
+ result
15
+ end
16
+ end
17
+ end
18
+
19
+ def self.install!
20
+ ::Capybara::Session.prepend(Actions)
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi"
4
+ require "tempfile"
5
+ require "uri"
6
+
7
+ module StoryPlayer
8
+ class History
9
+ def self.write(root, title: nil)
10
+ entries = Recording.history(root, title:)
11
+ raise Error, "No story recordings are available" if entries.empty?
12
+
13
+ filename = title ? "history-#{Recording.key(title)}.html" : "history.html"
14
+ path = File.expand_path(filename, root)
15
+ rows = entries.map do |entry|
16
+ <<~HTML
17
+ <li><a href="#{CGI.escapeURIComponent(entry.fetch("id"))}/index.html">#{CGI.escapeHTML(entry.fetch("chapter"))}</a>
18
+ <span>#{CGI.escapeHTML(entry.fetch("outcome").capitalize)}</span>
19
+ <time>#{CGI.escapeHTML(entry.fetch("recordedAt"))}</time></li>
20
+ HTML
21
+ end.join
22
+ Tempfile.create(".history-", root) do |file|
23
+ file.write(<<~HTML)
24
+ <!doctype html><html lang="en"><meta charset="utf-8">
25
+ <meta name="viewport" content="width=device-width, initial-scale=1">
26
+ <title>Story Player · Run history</title>
27
+ <style>
28
+ :root{color-scheme:light dark}
29
+ body{max-width:48rem;margin:2rem auto;padding:0 1rem;font:1rem/1.45 system-ui}
30
+ ul{list-style:none;padding:0}
31
+ li{display:flex;gap:.5rem 1rem;flex-wrap:wrap;padding:.75rem 0;border-bottom:1px solid GrayText}
32
+ a{flex:1 1 12rem;overflow-wrap:anywhere}
33
+ time{font-variant-numeric:tabular-nums}
34
+ :focus-visible{outline:2px solid Highlight;outline-offset:3px}
35
+ </style><h1>Run history</h1><ul>#{rows}</ul>
36
+ HTML
37
+ file.close
38
+ File.rename(file.path, path)
39
+ end
40
+ path
41
+ end
42
+
43
+ def self.open(page, root, title:)
44
+ path = write(root, title:)
45
+ browser = page.context.browser
46
+ tab = browser ? browser.new_page : page.context.new_page
47
+ path = "/#{path}" unless path.start_with?("/")
48
+ tab.goto("file://#{URI::DEFAULT_PARSER.escape(path, /[^A-Za-z0-9._~\/:-]/)}")
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "story_player"
4
+
5
+ module StoryPlayer
6
+ module Integration
7
+ def demo_checkpoint!(label, **options)
8
+ Thread.current[:story_player_run]&.checkpoint(label, **options)
9
+ end
10
+
11
+ def story_player_complete!(outcome)
12
+ Thread.current[:story_player_run]&.complete(outcome)
13
+ end
14
+
15
+ def with_demo_stage(title:, page: -> { self.page }, automatic: false, mode: StoryPlayer.mode, **options)
16
+ return yield unless mode
17
+
18
+ if automatic
19
+ require "story_player/capybara"
20
+ Capybara.install!
21
+ end
22
+ previous = Thread.current[:story_player_run]
23
+ stage = Run.new(page:, title:, mode:, automatic:, **options)
24
+ begin
25
+ Thread.current[:story_player_run] = stage
26
+ yielded = begin
27
+ yield stage
28
+ rescue
29
+ stage.complete(:failed)
30
+ raise
31
+ end
32
+ stage.complete((yielded == false) ? :failed : :passed)
33
+ yielded
34
+ ensure
35
+ Thread.current[:story_player_run] = previous
36
+ stage.close
37
+ end
38
+ end
39
+ end
40
+ end