suada 0.1.0

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 (47) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +90 -0
  4. data/exe/suada +7 -0
  5. data/lib/suada/asset_resolver.rb +48 -0
  6. data/lib/suada/assets/index.html +8 -0
  7. data/lib/suada/assets/present.html +6 -0
  8. data/lib/suada/assets/presenter.html +10 -0
  9. data/lib/suada/assets/presenter.js +40 -0
  10. data/lib/suada/assets/preview.html +8 -0
  11. data/lib/suada/assets/preview.js +56 -0
  12. data/lib/suada/assets/shell.js +84 -0
  13. data/lib/suada/assets/viewer.js +111 -0
  14. data/lib/suada/browser_output.rb +92 -0
  15. data/lib/suada/checker.rb +51 -0
  16. data/lib/suada/cli.rb +125 -0
  17. data/lib/suada/defaults/css/base.css +19 -0
  18. data/lib/suada/defaults/layouts/default.html +9 -0
  19. data/lib/suada/defaults/scaffold/deck.md +22 -0
  20. data/lib/suada/diagnostics.rb +24 -0
  21. data/lib/suada/emitter/distribution.rb +98 -0
  22. data/lib/suada/errors.rb +24 -0
  23. data/lib/suada/fragment.rb +30 -0
  24. data/lib/suada/frontmatter.rb +84 -0
  25. data/lib/suada/image_resolver.rb +66 -0
  26. data/lib/suada/layout_parser.rb +41 -0
  27. data/lib/suada/manifest.rb +25 -0
  28. data/lib/suada/mapper.rb +85 -0
  29. data/lib/suada/parser/block_classifier.rb +86 -0
  30. data/lib/suada/parser/page_settings.rb +42 -0
  31. data/lib/suada/parser/slot_fence.rb +45 -0
  32. data/lib/suada/parser.rb +142 -0
  33. data/lib/suada/pipeline.rb +90 -0
  34. data/lib/suada/publisher.rb +38 -0
  35. data/lib/suada/renderer.rb +73 -0
  36. data/lib/suada/scaffold.rb +25 -0
  37. data/lib/suada/server.rb +191 -0
  38. data/lib/suada/slot_contract.rb +19 -0
  39. data/lib/suada/source.rb +21 -0
  40. data/lib/suada/theme.rb +66 -0
  41. data/lib/suada/version.rb +5 -0
  42. data/lib/suada/watcher.rb +61 -0
  43. data/lib/suada.rb +18 -0
  44. data/sig/compiler.rbs +128 -0
  45. data/sig/parser.rbs +123 -0
  46. data/sig/suada.rbs +15 -0
  47. metadata +154 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fbc0157aaef16a7c4e3238b4b3894537d2ee511753216e5566bbe02a864c2fa6
4
+ data.tar.gz: 2b8f37afda0da68f11114197ad17a4ea5edb992765c04016fd6d055874ed02de
5
+ SHA512:
6
+ metadata.gz: 87f68dcd47c80e80cc2ba7a84a9bb67e3bec7043411cb5257532148ae65a7c3b84d811c26694cddb05aa2290699d95d436e75ffc3fed07f7d5162852694c5b35
7
+ data.tar.gz: 9a2d1e962e90f98e7dcb0f732394ef57878c37a93e700ef5f8b8d979ab5c08ed97821497a02f138e9d78c8a0ef74a688efb7bc19d3eb9fa972584c18202e0d66
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 ydah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # Suada
2
+
3
+ Write a presentation in Markdown, give it an HTML layout, and use CSS to style it. Suada checks that each slide fits the slots in its layout and reports the line and a suggested fix when it doesn't.
4
+
5
+ ## Start a talk
6
+
7
+ Install Ruby 3.4 or later, then run:
8
+
9
+ ```sh
10
+ gem install suada
11
+ suada new talk --theme light
12
+ cd talk
13
+ suada preview
14
+ ```
15
+
16
+ Edit `deck.md` while the preview is open. Use the arrow keys to move. Build a static copy with `suada build` and serve the resulting `dist/` directory over HTTP.
17
+
18
+ ## Write slides
19
+
20
+ Separate slides with a horizontal rule surrounded by blank lines. Give a slide an explicit key to keep its URL and CSS selectors stable as you edit. An independent HTML comment holds private speaker notes.
21
+
22
+ ````markdown
23
+ <!-- {"key":"welcome","section":"Introduction","time":"2m"} -->
24
+ # Welcome
25
+
26
+ - Write content in Markdown.
27
+ - Review layout changes in HTML and CSS.
28
+
29
+ <!-- Explain the example before moving on. -->
30
+
31
+ ---
32
+
33
+ # Example
34
+
35
+ ```ruby
36
+ puts "Hello"
37
+ ```
38
+ ````
39
+
40
+ Set deck-wide options in YAML frontmatter. Supported keys are `layouts`, `css`, `aspect_ratio`, `time`, `breaks` and `lang`. A slide can specify `layout`, `skip` (jump over it during presentation) or `draft` (omit it from the output). Pair each section name with a duration. Sections start on the first slide and their durations must add up to the deck's planned time when supplied.
41
+
42
+ ## Check a layout
43
+
44
+ Place layouts in `layouts/*.html` next to the deck. Each layout contains one section. Each slot declares a name, the kind of content it accepts and the number of items allowed.
45
+
46
+ ```html
47
+ <section class="suada-slide">
48
+ <h1><slot name="title" accepts="inline" arity="1"></slot></h1>
49
+ <slot name="body" accepts="blocks" arity="0..*"></slot>
50
+ </section>
51
+ ```
52
+
53
+ Suada sends the shallowest heading to `title`, code blocks to `code`, and other blocks to `body`. A standalone Markdown image needs a slot with `accepts="image"`. Use a local PNG, JPEG, GIF, WebP or SVG file. Give an SVG explicit dimensions. For a custom slot such as `left`, wrap the Markdown in `::: {slot=left}` and close it with `:::` on its own line.
54
+
55
+ Slot types are `inline`, `blocks`, `list`, `code`, `image`, and the reserved `text`. Cardinalities are `1`, `0..1`, `1..*` and `0..*`. With multiple layouts, exactly one must fit, or the slide must select one explicitly. Run `suada layouts --explain welcome` to see the match.
56
+
57
+ CSS files in `css/` are combined in filename order. Use selectors such as `[data-slide-key="welcome"] .slot-title` to adjust one slide. Suada checks slide and slot references. Syntax highlighting uses Rouge for fenced code with a language name.
58
+
59
+ ## Present and distribute
60
+
61
+ | Command | Result |
62
+ | --- | --- |
63
+ | `suada build [-o DIR]` | Write HTML slides, viewer, CSS, images and a manifest. |
64
+ | `suada build --watch` | Rebuild on edits to the deck or its resources. |
65
+ | `suada preview [--no-open]` | Open a live preview on localhost. |
66
+ | `suada present` | Open the presenter view with notes, agenda and timer. Open the audience window from there. |
67
+ | `suada export pdf -o talk.pdf` | Print one page per slide using Chrome. |
68
+ | `suada lint` | Identify layout slots that overflow the slide. |
69
+ | `suada publish -- COMMAND [ARG...]` | Check the distribution for speaker notes and presenter files, then run the deployment command. |
70
+
71
+ PDF export and lint require Chrome or Chromium and the optional `ferrum` gem (`gem install ferrum`). Under Bundler, add `ferrum` to your application's Gemfile. Speaker notes stay in local preview and presenter caches. Serve only the distribution directory.
72
+
73
+ Build and usage errors write diagnostics to standard error. Build errors and layout warnings exit with 1, invalid command options with 2, and unexpected errors with 3. A delegated deployment returns its own exit status.
74
+
75
+ ## Ruby API
76
+
77
+ ```ruby
78
+ require "suada"
79
+
80
+ deck = Suada.compile("deck.md")
81
+ puts deck.slides.first.html
82
+ result = Suada.build("deck.md", out: "dist")
83
+ puts result.slide_count
84
+ ```
85
+
86
+ ## Development
87
+
88
+ Run `bundle install` and `bundle exec rake`. Set `SUADA_BROWSER_TEST=1` to include Chrome checks.
89
+
90
+ MIT license.
data/exe/suada ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../lib/suada"
5
+ require_relative "../lib/suada/cli"
6
+
7
+ exit Suada::CLI.start(ARGV)
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Suada
4
+ class AssetResolver
5
+ DEFAULTS = File.expand_path("defaults", __dir__)
6
+ TYPES = { layouts: "html", css: "css" }.freeze
7
+
8
+ attr_reader :inputs
9
+
10
+ def initialize(deck)
11
+ @deck = deck
12
+ @dir = File.dirname(deck.path)
13
+ @inputs = [deck.path]
14
+ end
15
+
16
+ def files(type)
17
+ requested = @deck.settings[type]
18
+ path = File.expand_path(requested || type.to_s, @dir)
19
+ @inputs << path
20
+ path = File.join(DEFAULTS, type.to_s) unless requested || File.exist?(path)
21
+ extension = ".#{TYPES.fetch(type)}"
22
+ entries = File.directory?(path) ? Dir.glob("*#{extension}", base: path).sort.map { |f| File.join(path, f) } : [path]
23
+ unless entries.any? && entries.all? { |entry| File.file?(entry) }
24
+ raise BuildError.new(kind: :asset, file: @deck.path, line: @deck.settings[:lines]&.[](type),
25
+ message: "no #{type} files found at '#{requested || path}'",
26
+ help: "specify an existing #{TYPES.fetch(type)} file or a directory containing one")
27
+ end
28
+ entries.each do |entry|
29
+ next if File.extname(entry).downcase == extension && File.extname(File.realpath(entry)).downcase == extension &&
30
+ !File.identical?(entry, @deck.path)
31
+
32
+ raise BuildError.new(kind: :asset, file: @deck.path, line: @deck.settings[:lines]&.[](type),
33
+ message: "invalid #{type} file '#{entry}'", help: "choose a separate #{extension} file")
34
+ end
35
+ @inputs.concat(entries)
36
+ entries
37
+ end
38
+
39
+ def self.read(path)
40
+ text = File.read(path, encoding: "bom|utf-8")
41
+ return text if text.valid_encoding?
42
+
43
+ raise BuildError.new(kind: :asset, file: path, message: "invalid UTF-8 in asset", help: "save the file as UTF-8")
44
+ rescue SystemCallError => e
45
+ raise BuildError.new(kind: :asset, file: path, message: e.message, help: "make sure the file can be read")
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,8 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
3
+ <title>Slides</title><style>
4
+ *{box-sizing:border-box}body{margin:0;background:#18191b;color:white;font:1rem system-ui}#stage{position:absolute;inset:0;overflow:hidden}nav{position:fixed;bottom:.75rem;right:.75rem;background:#252629;color:white;border-radius:.5rem;padding:.25rem;display:flex;align-items:center;gap:.5rem;font:small system-ui}button{font:inherit;color:inherit;background:none;border:0;cursor:pointer;padding:.5rem}#error{position:fixed;inset:auto 1rem 3.5rem;background:white;color:#851820;padding:1rem;white-space:pre-wrap}
5
+ </style></head><body>
6
+ <main id="stage" aria-label="Slide"></main><nav aria-label="Slide navigation"><button data-to="prev" aria-label="Previous slide">←</button><output id="position" aria-live="polite"></output><button data-to="next" aria-label="Next slide">→</button></nav><pre id="error" role="alert" hidden></pre>
7
+ <script type="module">import {viewer,readJSON,showError} from "./viewer.js";readJSON("manifest.json").then(viewer).catch(showError);</script>
8
+ </body></html>
@@ -0,0 +1,6 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Presentation</title>
3
+ <style>*{box-sizing:border-box}body{margin:0;background:#121316;color:white;font:1rem system-ui}#stage{position:absolute;inset:0;overflow:hidden}#error{position:fixed;left:1rem;bottom:1rem;background:white;color:#84241e;padding:1rem;white-space:pre-wrap}</style></head><body>
4
+ <main id="stage" aria-label="Audience slide"></main><pre id="error" role="alert" hidden></pre>
5
+ <script type="module">import {start} from "./shell.js";import {showError} from "./viewer.js";start().catch(showError);</script>
6
+ </body></html>
@@ -0,0 +1,10 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
3
+ <title>Presenter view</title><style>
4
+ *{box-sizing:border-box}body{margin:0;background:#15171a;color:#f1f2f4;font:1rem/1.45 system-ui}header,main,footer{max-width:110rem;margin:auto;padding:1rem clamp(1rem,3vw,3rem)}header,footer{display:flex;gap:1rem;align-items:center;flex-wrap:wrap}header strong{margin-right:auto}button{font:inherit;border:1px solid #747880;border-radius:.3rem;color:inherit;background:#292d32;padding:.35rem .8rem;cursor:pointer}button:focus-visible{outline:3px solid #aad4ff}main{display:grid;grid-template-columns:minmax(0,2fr) minmax(13rem,1fr);gap:1rem 1.5rem}h2{font-size:1rem;font-weight:500;margin:.4rem 0;color:#bec4cb}.screen{position:relative;background:#222529;overflow:hidden;aspect-ratio:16/9}#notes{white-space:pre-wrap;overflow-wrap:anywhere;font:1.15rem/1.6 system-ui;margin:0}ol{padding-left:1.5rem;margin:0}li[aria-current]{font-weight:700;color:#d7ebff}#clock,#position{font-variant-numeric:tabular-nums}#error{white-space:pre-wrap;color:#ffb8ac;padding:1rem}footer{border-top:1px solid #383c41}button[aria-pressed=true]{background:#404b59}@media(max-width:650px){main{grid-template-columns:1fr}#next{max-height:10rem}}
5
+ </style></head><body>
6
+ <header><strong id="title">Presenter view</strong><output id="clock" aria-label="Elapsed time">0:00</output><button id="timer" aria-pressed="false">Start timer</button><button id="audience">Open audience window</button></header>
7
+ <main><section><h2>Current slide</h2><div class="screen" id="stage"></div></section><section><h2>Next slide</h2><div class="screen" id="next"></div></section>
8
+ <section><h2>Speaker notes</h2><p id="notes" aria-live="polite"></p></section><section id="agenda-panel" hidden><h2>Agenda</h2><ol id="agenda"></ol></section></main>
9
+ <footer><button data-to="prev" aria-label="Previous slide">←</button><output id="position" aria-label="Slide position"></output><button data-to="next" aria-label="Next slide">→</button><button id="end">End presentation</button></footer><pre id="error" role="alert" hidden></pre>
10
+ <script type="module" src="presenter.js"></script></body></html>
@@ -0,0 +1,40 @@
1
+ import {readJSON, viewport, showError} from "./viewer.js";
2
+ import {start} from "./shell.js";
3
+
4
+ function duration(ms) {
5
+ const seconds = Math.floor(ms / 1000);
6
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
7
+ }
8
+ async function present() {
9
+ const [manifest, {notes}] = await Promise.all([readJSON("manifest.json"), readJSON("notes.json")]);
10
+ document.querySelector("#title").textContent = manifest.title || "Presenter view";
11
+ for (const stage of document.querySelectorAll(".screen")) stage.style.aspectRatio = `${manifest.canvasWidth}/${manifest.canvasHeight}`;
12
+ const next = viewport(document.querySelector("#next"), manifest);
13
+ window.addEventListener("suada:slidechange", ({detail}) => {
14
+ document.querySelector("#notes").textContent = notes[detail.key] || "";
15
+ const nextIndex = manifest.slides.findIndex((s, i) => i > detail.index && !s.skip);
16
+ next(nextIndex).catch(showError);
17
+ });
18
+ const rows = (manifest.sections || []).map(s => {
19
+ const row = document.createElement("li");
20
+ document.querySelector("#agenda").append(row);
21
+ return row;
22
+ });
23
+ document.querySelector("#agenda-panel").hidden = !rows.length;
24
+ const session = await start(manifest);
25
+ const clock = document.querySelector("#clock"), button = document.querySelector("#timer");
26
+ function update() {
27
+ const state = session.clock();
28
+ clock.textContent = duration(state.elapsed);
29
+ button.textContent = state.running ? "Pause timer" : "Start timer";
30
+ button.setAttribute("aria-pressed", String(state.running));
31
+ rows.forEach((row, i) => {
32
+ const section = manifest.sections[i];
33
+ row.textContent = `${section.name}: ${duration(state.sections[i] || 0)} / ${duration(section.plannedMs || 0)}`;
34
+ if (state.current === i) row.setAttribute("aria-current", "step"); else row.removeAttribute("aria-current");
35
+ });
36
+ }
37
+ update();
38
+ setInterval(update, 250);
39
+ }
40
+ present().catch(showError);
@@ -0,0 +1,8 @@
1
+ <!doctype html>
2
+ <html lang="en" data-generation="GENERATION"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
3
+ <title>Preview</title><style>
4
+ *{box-sizing:border-box}body{margin:0;background:#191a1c;color:white;font:1rem system-ui}#stage{position:absolute;inset:0 0 3rem;overflow:hidden}nav{position:absolute;bottom:0;left:0;right:0;height:3rem;display:flex;align-items:center;justify-content:center;gap:.8rem}button{cursor:pointer;font:inherit;padding:.3rem .7rem}#overview{position:absolute;inset:0 0 3rem;overflow:auto;background:#24262a;padding:1.5rem}#overview ul{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,14rem),1fr));gap:1rem;list-style:none;margin:0;padding:0}#overview button{width:100%;text-align:left;padding:1rem;overflow-wrap:anywhere}#error{position:fixed;bottom:3rem;left:1rem;right:1rem;max-height:45vh;overflow:auto;background:#fff4f3;color:#7a1e16;border-left:.3rem solid #b63c30;padding:1rem;white-space:pre-wrap}
5
+ </style></head><body>
6
+ <main id="stage" aria-label="Slide preview"></main><section id="overview" aria-label="Slide overview" hidden><ul></ul></section>
7
+ <nav aria-label="Preview navigation"><button id="overview-toggle" aria-expanded="false">Overview</button><button data-to="prev" aria-label="Previous slide">←</button><output id="position"></output><button data-to="next" aria-label="Next slide">→</button></nav><pre id="error" role="alert" hidden></pre>
8
+ <script type="module" src="preview.js"></script></body></html>
@@ -0,0 +1,56 @@
1
+ import {viewer, readJSON, issue, showError} from "./viewer.js";
2
+
3
+ const gen = Number(document.documentElement.dataset.generation);
4
+ const error = document.querySelector("#error");
5
+ async function watch() {
6
+ let state = await readJSON("/__suada/status");
7
+ for (;;) {
8
+ if (state.gen !== gen) { location.reload(); return; }
9
+ error.textContent = state.error || "";
10
+ error.hidden = !state.error;
11
+ const res = await fetch(`/__suada/wait?gen=${gen}&rev=${state.revision}`);
12
+ if (res.status === 204) continue;
13
+ if (!res.ok) throw new Error("Preview connection lost");
14
+ state = await res.json();
15
+ }
16
+ }
17
+ async function connect() {
18
+ for (;;) {
19
+ try { await watch(); return; }
20
+ catch (e) { showError(e); await new Promise(resolve => setTimeout(resolve, 500)); }
21
+ }
22
+ }
23
+ async function start() {
24
+ if (!gen) return;
25
+ const manifest = await readJSON("manifest.json");
26
+ const overview = document.querySelector("#overview"), toggle = document.querySelector("#overview-toggle");
27
+ const buttons = manifest.slides.map((slide, index) => {
28
+ const li = document.createElement("li"), b = document.createElement("button");
29
+ b.textContent = `${index + 1}. ${slide.key}`;
30
+ b.onclick = () => { issue({index}); setOverview(false); };
31
+ li.append(b);
32
+ overview.querySelector("ul").append(li);
33
+ return b;
34
+ });
35
+ let current;
36
+ function setOverview(open) {
37
+ overview.hidden = !open;
38
+ toggle.setAttribute("aria-expanded", String(open));
39
+ if (open) buttons[current?.index || 0]?.focus(); else toggle.focus();
40
+ }
41
+ toggle.onclick = () => setOverview(overview.hidden);
42
+ window.addEventListener("keydown", e => {
43
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
44
+ if (e.key.toLowerCase() === "o" || e.key === "Escape") {
45
+ e.preventDefault();
46
+ setOverview(e.key === "Escape" ? false : overview.hidden);
47
+ } else if (!overview.hidden && ["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(e.key)) {
48
+ e.preventDefault();
49
+ const step = ["ArrowRight","ArrowDown"].includes(e.key) ? 1 : -1;
50
+ buttons[Math.max(0, Math.min(buttons.length-1, buttons.indexOf(document.activeElement)+step))]?.focus();
51
+ }
52
+ });
53
+ current = await viewer(manifest);
54
+ }
55
+ connect();
56
+ start().catch(showError);
@@ -0,0 +1,84 @@
1
+ import {readJSON, viewer, issue, showError} from "./viewer.js";
2
+
3
+ export async function start(manifest) {
4
+ manifest ||= await readJSON("manifest.json");
5
+ const deck = await viewer(manifest, {skip: true});
6
+ const channel = new BroadcastChannel("suada-sync");
7
+ let timer = {elapsed: 0, since: null, sections: {}};
8
+ let remoteKey = null, closed = false;
9
+ function sectionAt(index) {
10
+ return (manifest.sections || []).findIndex(s => index >= s.start && index <= s.end);
11
+ }
12
+ function tick(index) {
13
+ if (timer.since === null) return;
14
+ const now = Date.now();
15
+ const delta = Math.max(0, now - timer.since);
16
+ timer.elapsed += delta;
17
+ const section = sectionAt(index);
18
+ if (section >= 0) timer.sections[section] = (timer.sections[section] || 0) + delta;
19
+ timer.since = now;
20
+ }
21
+ function sync() {
22
+ channel.postMessage({type: "state", key: manifest.slides[deck.index]?.key, timer});
23
+ }
24
+ function finish() {
25
+ if (closed) return;
26
+ closed = true;
27
+ channel.close();
28
+ document.body.replaceChildren(Object.assign(document.createElement("p"), {textContent: "Presentation ended."}));
29
+ window.close();
30
+ }
31
+ function end() {
32
+ if (closed) return;
33
+ channel.postMessage({type: "end"});
34
+ fetch("/__suada/close", {method: "POST", keepalive: true}).catch(showError);
35
+ finish();
36
+ }
37
+ channel.onmessage = ({data}) => {
38
+ if (data.type === "end") { finish(); return; }
39
+ if (data.type === "hello") { sync(); return; }
40
+ if (data.type !== "state") return;
41
+ timer = data.timer;
42
+ if (data.key && data.key !== manifest.slides[deck.index]?.key) {
43
+ remoteKey = data.key;
44
+ issue({key: data.key});
45
+ }
46
+ };
47
+ window.addEventListener("suada:slidechange", ({detail}) => {
48
+ if (detail.key === remoteKey) { remoteKey = null; return; }
49
+ remoteKey = null;
50
+ tick(detail.previousIndex);
51
+ sync();
52
+ });
53
+ function timerControl(action) {
54
+ tick(deck.index);
55
+ if (action === "start") timer.since = Date.now();
56
+ if (action === "pause") timer.since = null;
57
+ if (action === "reset") timer = {elapsed: 0, since: null, sections: {}};
58
+ sync();
59
+ }
60
+ window.addEventListener("suada:timercontrol", e => timerControl(e.detail?.action));
61
+ function toggleTimer() {
62
+ window.dispatchEvent(new CustomEvent("suada:timercontrol", {detail: {action: timer.since === null ? "start" : "pause"}}));
63
+ }
64
+ const audience = document.querySelector("#audience");
65
+ if (audience) audience.onclick = () => window.open("present.html", "suada-audience");
66
+ document.querySelector("#end")?.addEventListener("click", end);
67
+ document.querySelector("#timer")?.addEventListener("click", toggleTimer);
68
+ window.addEventListener("keydown", e => {
69
+ if (e.repeat || e.altKey || e.ctrlKey || e.metaKey) return;
70
+ if (e.code === "Space" && e.target.tagName !== "BUTTON") { e.preventDefault(); toggleTimer(); }
71
+ if (e.key.toLowerCase() === "f") {
72
+ const change = document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen();
73
+ change.catch(showError);
74
+ }
75
+ if (e.key === "Escape") end();
76
+ });
77
+ channel.postMessage({type: "hello"});
78
+ return {deck, manifest, clock() {
79
+ const delta = timer.since === null ? 0 : Math.max(0, Date.now() - timer.since);
80
+ const sections = {...timer.sections}, i = sectionAt(deck.index);
81
+ if (i >= 0) sections[i] = (sections[i] || 0) + delta;
82
+ return {elapsed: timer.elapsed + delta, running: timer.since !== null, sections, current: i};
83
+ }};
84
+ }
@@ -0,0 +1,111 @@
1
+ export async function readJSON(path) {
2
+ const response = await fetch(path);
3
+ if (!response.ok) throw new Error(`Cannot load ${path} (${response.status})`);
4
+ return response.json();
5
+ }
6
+
7
+ export function keyFromHash() {
8
+ try { return decodeURIComponent(location.hash.slice(1)); } catch { return ""; }
9
+ }
10
+
11
+ export function installLanguage(manifest) {
12
+ document.documentElement.lang = manifest.lang || "en";
13
+ if (manifest.title) document.title = manifest.title;
14
+ }
15
+
16
+ export function viewport(stage, manifest) {
17
+ const width = manifest.canvasWidth, height = manifest.canvasHeight;
18
+ const host = document.createElement("div");
19
+ host.className = "suada-host";
20
+ Object.assign(host.style, {
21
+ position: "absolute", width: `${width}px`, height: `${height}px`,
22
+ left: "50%", top: "50%", transformOrigin: "center"
23
+ });
24
+ const root = host.attachShadow({ mode: "open" });
25
+ const sheet = document.createElement("link");
26
+ sheet.rel = "stylesheet";
27
+ sheet.href = "suada.css";
28
+ root.append(sheet);
29
+ const resize = () => {
30
+ host.style.transform = `translate(-50%, -50%) scale(${Math.min(stage.clientWidth / width, stage.clientHeight / height)})`;
31
+ };
32
+ const observer = new ResizeObserver(resize);
33
+ observer.observe(stage);
34
+ stage.replaceChildren(host);
35
+ let serial = 0;
36
+ return async function show(index) {
37
+ const request = ++serial;
38
+ const slide = manifest.slides[index];
39
+ if (!slide) { host.hidden = true; return false; }
40
+ const response = await fetch(slide.src);
41
+ if (!response.ok) throw new Error(`Cannot load ${slide.src} (${response.status})`);
42
+ const template = document.createElement("template");
43
+ template.innerHTML = await response.text();
44
+ if (request !== serial) return false;
45
+ host.hidden = false;
46
+ host.dataset.slideKey = slide.key;
47
+ root.replaceChildren(sheet, template.content);
48
+ resize();
49
+ const roots = window.__suadaShadowRoots ||= [];
50
+ if (!roots.includes(root)) roots.push(root);
51
+ window.dispatchEvent(new CustomEvent("suada:shadow-mounted", {detail: {root, key: slide.key, index}}));
52
+ return true;
53
+ };
54
+ }
55
+
56
+ export async function viewer(manifest, {skip = false} = {}) {
57
+ installLanguage(manifest);
58
+ const draw = viewport(document.querySelector("#stage"), manifest);
59
+ const slides = manifest.slides;
60
+ if (!slides.length) throw new Error("This deck has no slides.");
61
+ if (skip && slides.every(slide => slide.skip)) throw new Error("Every slide is skipped. Clear skip on a slide to present it.");
62
+ let index = -1, requested = -1;
63
+ const byKey = key => slides.findIndex(s => s.key === key);
64
+ const reachable = (start, step) => {
65
+ for (let i = start; i >= 0 && i < slides.length; i += step) {
66
+ if (!skip || !slides[i].skip) return i;
67
+ }
68
+ return requested;
69
+ };
70
+ async function navigate(to) {
71
+ let target;
72
+ if (to === "first") target = reachable(0, 1);
73
+ else if (to === "last") target = reachable(slides.length - 1, -1);
74
+ else if (to === "next") target = reachable(requested + 1, 1);
75
+ else if (to === "prev") target = reachable(requested - 1, -1);
76
+ else if (typeof to?.key === "string") target = byKey(to.key);
77
+ else target = to?.index;
78
+ if (!Number.isInteger(target) || !slides[target] || target === requested) return;
79
+ requested = target;
80
+ if (!await draw(target)) return;
81
+ const previousIndex = index;
82
+ index = target;
83
+ const key = slides[target].key;
84
+ const url = new URL(location.href);
85
+ url.hash = encodeURIComponent(key);
86
+ history.replaceState(null, "", url);
87
+ const count = document.querySelector("#position");
88
+ if (count) count.textContent = `${index + 1} / ${slides.length}`;
89
+ window.dispatchEvent(new CustomEvent("suada:slidechange", {detail: {key, index, total: slides.length, previousIndex}}));
90
+ }
91
+ window.addEventListener("suada:navigate", e => navigate(e.detail?.to).catch(showError));
92
+ window.addEventListener("hashchange", () => issue({key: keyFromHash()}));
93
+ const keys = {ArrowRight: "next", PageDown: "next", ArrowLeft: "prev", PageUp: "prev", Home: "first", End: "last"};
94
+ window.addEventListener("keydown", e => {
95
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !keys[e.key]) return;
96
+ e.preventDefault();
97
+ issue(keys[e.key]);
98
+ });
99
+ document.querySelectorAll("[data-to]").forEach(b => b.addEventListener("click", () => issue(b.dataset.to)));
100
+ await navigate(byKey(keyFromHash()) >= 0 ? {key: keyFromHash()} : "first");
101
+ return {get index() { return index; }};
102
+ }
103
+
104
+ export function issue(to) {
105
+ window.dispatchEvent(new CustomEvent("suada:navigate", {detail: {to}}));
106
+ }
107
+
108
+ export function showError(error) {
109
+ const box = document.querySelector("#error");
110
+ if (box) { box.textContent = error.message || String(error); box.hidden = false; }
111
+ }
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "webrick"
4
+
5
+ module Suada
6
+ module BrowserOutput
7
+ def self.pdf(deck, path, target)
8
+ with_page(deck, path) do |page, width, height|
9
+ page.pdf(path: target, paper_width: width / 96.0, paper_height: height / 96.0,
10
+ margin_top: 0, margin_right: 0, margin_bottom: 0, margin_left: 0,
11
+ prefer_css_page_size: true, print_background: true)
12
+ end
13
+ end
14
+
15
+ def self.lint(deck, path)
16
+ with_page(deck, path) do |page, _, _|
17
+ page.evaluate(<<~JS)
18
+ Array.from(document.querySelectorAll('.suada-slide')).flatMap((slide, index) => {
19
+ const frame = slide.getBoundingClientRect();
20
+ const issues = [];
21
+ for (const slot of slide.querySelectorAll('[class]')) {
22
+ const name = Array.from(slot.classList).find(c => c.startsWith('slot-'));
23
+ if (!name || !slot.getClientRects().length) continue;
24
+ const box = slot.getBoundingClientRect();
25
+ const excess = Math.max(frame.left - box.left, frame.top - box.top,
26
+ box.right - frame.right, box.bottom - frame.bottom);
27
+ if (excess > 1) {
28
+ issues.push(`slide ${index + 1} ('${slide.dataset.slideKey}'): ${name} overflows by ${Math.ceil(excess)}px`);
29
+ }
30
+ }
31
+ return issues;
32
+ })
33
+ JS
34
+ end
35
+ end
36
+
37
+ def self.with_page(deck, path)
38
+ manifest = Manifest.for(deck)
39
+ width = manifest.fetch(:canvasWidth)
40
+ height = manifest.fetch(:canvasHeight)
41
+ parent = File.join(File.dirname(File.expand_path(path)), ".suada", "pdf-work")
42
+ FileUtils.mkdir_p(parent)
43
+ Dir.mktmpdir("print-", parent) do |dir|
44
+ Emitter::Distribution.write(deck, out: dir)
45
+ html = <<~HTML
46
+ <!doctype html>
47
+ <meta charset="utf-8">
48
+ <link rel="stylesheet" href="suada.css">
49
+ <style>
50
+ @page { size: #{width}px #{height}px; margin: 0 }
51
+ html, body { margin: 0; padding: 0 }
52
+ .suada-page { width: #{width}px; height: #{height}px; overflow: hidden; break-after: page; }
53
+ .suada-page:last-child { break-after: auto }
54
+ .suada-page > .suada-slide { box-sizing: border-box; width: 100%; height: 100%; }
55
+ </style>
56
+ <body>#{deck.slides.map { |slide| %(<div class="suada-page">#{slide.html}</div>) }.join}</body>
57
+ HTML
58
+ File.write(File.join(dir, "pdf.html"), html)
59
+ server = WEBrick::HTTPServer.new(BindAddress: "127.0.0.1", Port: 0, DocumentRoot: dir,
60
+ AccessLog: [], Logger: WEBrick::Log.new(File::NULL))
61
+ thread = Thread.new { server.start }
62
+ begin
63
+ browser = launch_browser(width, height)
64
+ page = browser.create_page
65
+ page.go_to("http://127.0.0.1:#{server.config.fetch(:Port)}/pdf.html")
66
+ page.evaluate("Promise.all([document.fonts.ready, ...Array.from(document.images, img => img.decode())]).then(() => true)")
67
+ yield page, width, height
68
+ ensure
69
+ browser&.quit
70
+ server.shutdown
71
+ thread.join
72
+ end
73
+ end
74
+ end
75
+ private_class_method :with_page
76
+
77
+ def self.launch_browser(width, height)
78
+ begin
79
+ require "ferrum"
80
+ rescue LoadError
81
+ raise UsageError, "install the ferrum gem and Chrome to print or lint a deck"
82
+ end
83
+
84
+ begin
85
+ Ferrum::Browser.new(window_size: [width, height])
86
+ rescue Ferrum::BinaryNotFoundError => e
87
+ raise UsageError, "install Chrome for printing and linting: #{e.message}"
88
+ end
89
+ end
90
+ private_class_method :launch_browser
91
+ end
92
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Suada
4
+ module Checker
5
+ module_function
6
+
7
+ def check_slide!(slide, path)
8
+ slide.layout.slots.each_value do |slot|
9
+ wrong = slide.assigned.fetch(slot.name).find { |part| !ACCEPTS.fetch(slot.accepts).include?(part.kind) }
10
+ next unless wrong
11
+
12
+ target = ACCEPTS.find { |_name, kinds| kinds.include?(wrong.kind) }&.first
13
+ fail_slide!(slide, path, :accepts, wrong.line,
14
+ "slot '#{slot.name}' accepts #{slot.accepts}, but got #{wrong.kind}",
15
+ "change the layout accepts to '#{target}' or move this content to a #{target} slot")
16
+ end
17
+ slide.layout.slots.each_value do |slot|
18
+ items = slide.assigned.fetch(slot.name)
19
+ next if slot.arity.allows?(items.size)
20
+
21
+ excess = slot.arity.max && items[slot.arity.max]
22
+ help = if items.empty?
23
+ slot.name == "title" ? "add a heading for the title slot" : "add content for the #{slot.name} slot"
24
+ elsif slot.accepts == :code
25
+ "use a layout with more code capacity or remove one code block"
26
+ else
27
+ "adjust the #{slot.name} slot arity or move excess content to another slot"
28
+ end
29
+ fail_slide!(slide, path, :arity, excess ? excess.line : slide.source.line,
30
+ "slot '#{slot.name}' got #{items.size} item(s), but layout '#{slide.layout.name}' allows #{slot.arity}", help)
31
+ end
32
+ leftover = slide.unassigned.first
33
+ if leftover
34
+ name, part = leftover
35
+ help = if part.kind == :image
36
+ "add an image slot to the layout or remove the image"
37
+ else
38
+ "add a '#{name}' slot to the layout or remove the #{part.kind}"
39
+ end
40
+ fail_slide!(slide, path, :residual, part.line, "no slot in layout '#{slide.layout.name}' accepts this #{part.kind}",
41
+ help)
42
+ end
43
+ slide
44
+ end
45
+
46
+ def fail_slide!(slide, path, kind, line, message, help)
47
+ raise BuildError.new(kind:, file: path, line:, message:, help:, slide_key: slide.source.key,
48
+ slide_number: slide.source.number)
49
+ end
50
+ end
51
+ end