suada 0.1.0 → 0.2.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.
@@ -1,11 +1,14 @@
1
+ import {settle, transition} from "./motion.js";
2
+
1
3
  export async function readJSON(path) {
2
4
  const response = await fetch(path);
3
5
  if (!response.ok) throw new Error(`Cannot load ${path} (${response.status})`);
4
6
  return response.json();
5
7
  }
6
8
 
7
- export function keyFromHash() {
8
- try { return decodeURIComponent(location.hash.slice(1)); } catch { return ""; }
9
+ function positionFromHash() {
10
+ const [key, step = "1"] = location.hash.slice(1).split("/");
11
+ try { return {key: decodeURIComponent(key), step: Number(step)}; } catch { return {}; }
9
12
  }
10
13
 
11
14
  export function installLanguage(manifest) {
@@ -13,6 +16,22 @@ export function installLanguage(manifest) {
13
16
  if (manifest.title) document.title = manifest.title;
14
17
  }
15
18
 
19
+ const fragments = new WeakMap();
20
+
21
+ function loadSteps(manifest, slide) {
22
+ if (!fragments.has(manifest)) fragments.set(manifest, new Map());
23
+ const cache = fragments.get(manifest);
24
+ if (!cache.has(slide.src)) {
25
+ cache.set(slide.src, fetch(slide.src).then(async response => {
26
+ if (!response.ok) throw new Error(`Cannot load ${slide.src} (${response.status})`);
27
+ const template = document.createElement("template");
28
+ template.innerHTML = await response.text();
29
+ return template.content.children;
30
+ }).catch(error => { cache.delete(slide.src); throw error; }));
31
+ }
32
+ return cache.get(slide.src);
33
+ }
34
+
16
35
  export function viewport(stage, manifest) {
17
36
  const width = manifest.canvasWidth, height = manifest.canvasHeight;
18
37
  const host = document.createElement("div");
@@ -21,75 +40,113 @@ export function viewport(stage, manifest) {
21
40
  position: "absolute", width: `${width}px`, height: `${height}px`,
22
41
  left: "50%", top: "50%", transformOrigin: "center"
23
42
  });
24
- const root = host.attachShadow({ mode: "open" });
43
+ const root = host.attachShadow({mode: "open"});
25
44
  const sheet = document.createElement("link");
26
45
  sheet.rel = "stylesheet";
27
46
  sheet.href = "suada.css";
28
- root.append(sheet);
47
+ const frame = document.createElement("div");
48
+ frame.className = "suada-frame";
49
+ Object.assign(frame.style, {position: "absolute", inset: "0"});
50
+ const styled = new Promise(resolve => { sheet.onload = sheet.onerror = resolve; });
51
+ root.append(sheet, frame);
52
+ let scale = 1;
29
53
  const resize = () => {
30
- host.style.transform = `translate(-50%, -50%) scale(${Math.min(stage.clientWidth / width, stage.clientHeight / height)})`;
54
+ scale = Math.min(stage.clientWidth / width, stage.clientHeight / height) || 1;
55
+ host.style.transform = `translate(-50%, -50%) scale(${scale})`;
31
56
  };
32
- const observer = new ResizeObserver(resize);
33
- observer.observe(stage);
57
+ new ResizeObserver(resize).observe(stage);
34
58
  stage.replaceChildren(host);
35
59
  let serial = 0;
36
- return async function show(index) {
60
+ return async function show(index, step = 1, direction = 0) {
37
61
  const request = ++serial;
62
+ settle(frame);
38
63
  const slide = manifest.slides[index];
39
64
  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();
65
+ const [sections] = await Promise.all([loadSteps(manifest, slide), styled]);
44
66
  if (request !== serial) return false;
67
+ const section = sections[step - 1];
68
+ if (!section) throw new Error(`Missing step ${step} in slide '${slide.key}'`);
45
69
  host.hidden = false;
46
70
  host.dataset.slideKey = slide.key;
47
- root.replaceChildren(sheet, template.content);
48
71
  resize();
72
+ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
73
+ transition(frame, frame.lastElementChild, section.cloneNode(true), {scale, direction, reducedMotion, sections}).catch(showError);
49
74
  const roots = window.__suadaShadowRoots ||= [];
50
75
  if (!roots.includes(root)) roots.push(root);
51
- window.dispatchEvent(new CustomEvent("suada:shadow-mounted", {detail: {root, key: slide.key, index}}));
76
+ window.dispatchEvent(new CustomEvent("suada:shadow-mounted", {detail: {root, key: slide.key, index, step, steps: slide.steps}}));
52
77
  return true;
53
78
  };
54
79
  }
55
80
 
56
- export async function viewer(manifest, {skip = false} = {}) {
81
+ export function adjacent(slides, position, direction, skip) {
82
+ let {index, step} = position;
83
+ step += direction;
84
+ if (step > 0 && step <= slides[index]?.steps) return {index, step};
85
+ for (index += direction; slides[index]; index += direction) {
86
+ if (!skip || !slides[index].skip) return {index, step: direction > 0 ? 1 : slides[index].steps};
87
+ }
88
+ }
89
+
90
+ export async function viewer(manifest, {skip = false, auto = true} = {}) {
57
91
  installLanguage(manifest);
58
92
  const draw = viewport(document.querySelector("#stage"), manifest);
59
93
  const slides = manifest.slides;
60
94
  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) {
95
+ const visible = slides.flatMap((slide, index) => !skip || !slide.skip ? [index] : []);
96
+ if (!visible.length) throw new Error("Every slide is skipped. Clear skip on a slide to present it.");
97
+ let current = {index: -1, step: 0}, requested = current;
98
+ let timer, serial = 0;
99
+ async function navigate(to, syncDirection) {
100
+ clearTimeout(timer);
101
+ const direction = to === "next" ? 1 : to === "prev" ? -1 : syncDirection || 0;
71
102
  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;
103
+ if (to === "first") target = {index: visible[0], step: 1};
104
+ else if (to === "last") target = {index: visible.at(-1), step: slides[visible.at(-1)].steps};
105
+ else if (to === "next" || to === "prev") target = adjacent(slides, requested, to === "next" ? 1 : -1, skip);
106
+ else {
107
+ const index = typeof to?.key === "string" ? slides.findIndex(s => s.key === to.key) : to?.index;
108
+ if (Number.isInteger(index) && slides[index]) {
109
+ const step = Number.isInteger(to.step) ? Math.max(1, Math.min(to.step, slides[index].steps)) : 1;
110
+ target = {index, step};
111
+ }
112
+ }
113
+ if (!target || (target.index === requested.index && target.step === requested.step)) return;
114
+ const request = ++serial;
79
115
  requested = target;
80
- if (!await draw(target)) return;
81
- const previousIndex = index;
82
- index = target;
83
- const key = slides[target].key;
116
+ const {index} = target;
117
+ if (direction < 0 && to === "prev") {
118
+ const sections = await loadSteps(manifest, slides[index]);
119
+ if (request !== serial) return;
120
+ while (target.step > 1 && sections[target.step - 1].hasAttribute("data-auto")) target.step--;
121
+ }
122
+ const neighbor = direction ? adjacent(slides, current, direction, skip) : null;
123
+ const motion = direction && neighbor?.index === index && neighbor.step === target.step ? direction : 0;
124
+ try {
125
+ if (!await draw(index, target.step, motion) || request !== serial) return;
126
+ } catch (error) {
127
+ if (requested === target) requested = current;
128
+ throw error;
129
+ }
130
+ const previousIndex = current.index, previousStep = current.step;
131
+ current = target;
132
+ const {step} = current;
133
+ const {key, steps} = slides[index];
84
134
  const url = new URL(location.href);
85
- url.hash = encodeURIComponent(key);
135
+ url.hash = encodeURIComponent(key) + (step === 1 ? "" : `/${step}`);
86
136
  history.replaceState(null, "", url);
87
137
  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}}));
138
+ if (count) count.textContent = `${index + 1} / ${slides.length}` + (steps > 1 ? ` · Step ${step} / ${steps}` : "");
139
+ const detail = {key, index, total: slides.length, previousIndex, step, steps, previousStep, direction};
140
+ if (index !== previousIndex) window.dispatchEvent(new CustomEvent("suada:slidechange", {detail}));
141
+ window.dispatchEvent(new CustomEvent("suada:stepchange", {detail}));
142
+ if (auto && direction >= 0 && step < steps) {
143
+ const sections = await loadSteps(manifest, slides[index]);
144
+ const delay = sections[step]?.dataset.auto;
145
+ if (request === serial && delay !== undefined) timer = setTimeout(() => issue("next"), Number(delay));
146
+ }
90
147
  }
91
- window.addEventListener("suada:navigate", e => navigate(e.detail?.to).catch(showError));
92
- window.addEventListener("hashchange", () => issue({key: keyFromHash()}));
148
+ window.addEventListener("suada:navigate", e => navigate(e.detail?.to, e.detail?.direction).catch(showError));
149
+ window.addEventListener("hashchange", () => issue(positionFromHash()));
93
150
  const keys = {ArrowRight: "next", PageDown: "next", ArrowLeft: "prev", PageUp: "prev", Home: "first", End: "last"};
94
151
  window.addEventListener("keydown", e => {
95
152
  if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !keys[e.key]) return;
@@ -97,12 +154,13 @@ export async function viewer(manifest, {skip = false} = {}) {
97
154
  issue(keys[e.key]);
98
155
  });
99
156
  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; }};
157
+ const initial = positionFromHash();
158
+ await navigate(slides.some(s => s.key === initial.key) ? initial : "first");
159
+ return {get index() { return current.index; }, get step() { return current.step; }};
102
160
  }
103
161
 
104
- export function issue(to) {
105
- window.dispatchEvent(new CustomEvent("suada:navigate", {detail: {to}}));
162
+ export function issue(to, direction = 0) {
163
+ window.dispatchEvent(new CustomEvent("suada:navigate", {detail: {to, direction}}));
106
164
  }
107
165
 
108
166
  export function showError(error) {
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+ require_relative "errors"
5
+
6
+ module Suada
7
+ module Attributes
8
+ TRANSITIONS = %w[cut fade morph].freeze
9
+ KEY = /\A[a-z0-9-]+\z/
10
+ NAME = /[a-z][a-z0-9-]*/
11
+ DOUBLE = /"((?:\\.|[^"\\])*)"/
12
+ SINGLE = /'([^']*)'/
13
+ BARE = /[^\s"'{}]+/
14
+
15
+ def self.parse(text, allowed:, file:, line:)
16
+ scanner = StringScanner.new(text.strip)
17
+ attrs = {}
18
+ fail_at(file, line, "empty attributes") if scanner.eos?
19
+ until scanner.eos?
20
+ name = scanner.scan(NAME)&.to_sym
21
+ fail_at(file, line, "expected an attribute name") unless name
22
+ fail_at(file, line, "duplicate attribute '#{name}'") if attrs.key?(name)
23
+ type = allowed[name]
24
+ fail_at(file, line, "unsupported attribute '#{name}'") unless type
25
+ value = if !scanner.scan(/=/) then true
26
+ elsif scanner.scan(DOUBLE) then scanner[1].gsub(/\\(["\\])/, '\1')
27
+ elsif scanner.scan(SINGLE) then scanner[1]
28
+ elsif scanner.scan(BARE) then scanner.matched
29
+ else fail_at(file, line, "expected a value for '#{name}'")
30
+ end
31
+ attrs[name] = coerce(name, value, type, file, line)
32
+ fail_at(file, line, "expected a space after '#{name}'") unless scanner.eos? || scanner.skip(/\s+/)
33
+ end
34
+ attrs
35
+ end
36
+
37
+ def self.coerce(name, value, type, file, line)
38
+ case type
39
+ when :flag then return true if value == true
40
+ when :string then return value if value.is_a?(String) && !value.strip.empty?
41
+ when :key then return value if value.is_a?(String) && KEY.match?(value)
42
+ when Array then return value if type.include?(value)
43
+ when Range
44
+ if value.is_a?(String) && /\A\d+\z/.match?(value)
45
+ integer = value.to_i
46
+ return integer if type.cover?(integer)
47
+ end
48
+ end
49
+ fail_at(file, line, "invalid value for '#{name}'")
50
+ end
51
+
52
+ def self.fail_at(file, line, message)
53
+ raise BuildError.new(kind: :parse, file:, line:, message:, help: "use supported space-separated attributes inside braces")
54
+ end
55
+ private_class_method :coerce, :fail_at
56
+ end
57
+ end
@@ -4,8 +4,8 @@ require "webrick"
4
4
 
5
5
  module Suada
6
6
  module BrowserOutput
7
- def self.pdf(deck, path, target)
8
- with_page(deck, path) do |page, width, height|
7
+ def self.pdf(deck, path, target, steps: "last")
8
+ with_page(deck, path, steps, print: true) do |page, width, height|
9
9
  page.pdf(path: target, paper_width: width / 96.0, paper_height: height / 96.0,
10
10
  margin_top: 0, margin_right: 0, margin_bottom: 0, margin_left: 0,
11
11
  prefer_css_page_size: true, print_background: true)
@@ -13,19 +13,19 @@ module Suada
13
13
  end
14
14
 
15
15
  def self.lint(deck, path)
16
- with_page(deck, path) do |page, _, _|
16
+ with_page(deck, path, "all") do |page, _, _|
17
17
  page.evaluate(<<~JS)
18
- Array.from(document.querySelectorAll('.suada-slide')).flatMap((slide, index) => {
18
+ Array.from(document.querySelectorAll('.suada-slide')).flatMap(slide => {
19
19
  const frame = slide.getBoundingClientRect();
20
20
  const issues = [];
21
21
  for (const slot of slide.querySelectorAll('[class]')) {
22
- const name = Array.from(slot.classList).find(c => c.startsWith('slot-'));
22
+ const name = Array.from(slot.classList).find(c => c.startsWith('slot-') || c === 'suada-mark' || c === 'suada-call');
23
23
  if (!name || !slot.getClientRects().length) continue;
24
24
  const box = slot.getBoundingClientRect();
25
25
  const excess = Math.max(frame.left - box.left, frame.top - box.top,
26
26
  box.right - frame.right, box.bottom - frame.bottom);
27
27
  if (excess > 1) {
28
- issues.push(`slide ${index + 1} ('${slide.dataset.slideKey}'): ${name} overflows by ${Math.ceil(excess)}px`);
28
+ issues.push(`slide ${Number(slide.dataset.slideIndex) + 1} ('${slide.dataset.slideKey}'), step ${slide.dataset.step}: ${name} overflows by ${Math.ceil(excess)}px`);
29
29
  }
30
30
  }
31
31
  return issues;
@@ -34,10 +34,15 @@ module Suada
34
34
  end
35
35
  end
36
36
 
37
- def self.with_page(deck, path)
37
+ def self.with_page(deck, path, mode, print: false)
38
38
  manifest = Manifest.for(deck)
39
39
  width = manifest.fetch(:canvasWidth)
40
40
  height = manifest.fetch(:canvasHeight)
41
+ steps = case mode
42
+ when "last" then deck.slides.map { |slide| slide.steps.last }
43
+ when "all" then deck.slides.flat_map(&:steps)
44
+ else raise UsageError, "steps must be last or all"
45
+ end
41
46
  parent = File.join(File.dirname(File.expand_path(path)), ".suada", "pdf-work")
42
47
  FileUtils.mkdir_p(parent)
43
48
  Dir.mktmpdir("print-", parent) do |dir|
@@ -51,9 +56,9 @@ module Suada
51
56
  html, body { margin: 0; padding: 0 }
52
57
  .suada-page { width: #{width}px; height: #{height}px; overflow: hidden; break-after: page; }
53
58
  .suada-page:last-child { break-after: auto }
54
- .suada-page > .suada-slide { box-sizing: border-box; width: 100%; height: 100%; }
59
+ .suada-page > .suada-slide { position: relative; box-sizing: border-box; width: 100%; height: 100%; }
55
60
  </style>
56
- <body>#{deck.slides.map { |slide| %(<div class="suada-page">#{slide.html}</div>) }.join}</body>
61
+ <body>#{steps.map { |step| %(<div class="suada-page">#{step.html}</div>) }.join}</body>
57
62
  HTML
58
63
  File.write(File.join(dir, "pdf.html"), html)
59
64
  server = WEBrick::HTTPServer.new(BindAddress: "127.0.0.1", Port: 0, DocumentRoot: dir,
@@ -63,7 +68,15 @@ module Suada
63
68
  browser = launch_browser(width, height)
64
69
  page = browser.create_page
65
70
  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)")
71
+ page.command("Emulation.setEmulatedMedia", media: "print") if print
72
+ page.evaluate(<<~JS)
73
+ (async () => {
74
+ await Promise.all([document.fonts.ready, ...Array.from(document.images, img => img.decode())]);
75
+ const {decorate} = await import('./motion.js');
76
+ await Promise.all(Array.from(document.querySelectorAll('.suada-slide'), slide => decorate(slide)));
77
+ return true;
78
+ })()
79
+ JS
67
80
  yield page, width, height
68
81
  ensure
69
82
  browser&.quit
data/lib/suada/checker.rb CHANGED
@@ -26,7 +26,7 @@ module Suada
26
26
  else
27
27
  "adjust the #{slot.name} slot arity or move excess content to another slot"
28
28
  end
29
- fail_slide!(slide, path, :arity, excess ? excess.line : slide.source.line,
29
+ fail_slide!(slide, path, :arity, excess ? excess.line : slide.step.line,
30
30
  "slot '#{slot.name}' got #{items.size} item(s), but layout '#{slide.layout.name}' allows #{slot.arity}", help)
31
31
  end
32
32
  leftover = slide.unassigned.first
@@ -45,7 +45,7 @@ module Suada
45
45
 
46
46
  def fail_slide!(slide, path, kind, line, message, help)
47
47
  raise BuildError.new(kind:, file: path, line:, message:, help:, slide_key: slide.source.key,
48
- slide_number: slide.source.number)
48
+ slide_number: slide.source.number, step_number: slide.step.number)
49
49
  end
50
50
  end
51
51
  end
data/lib/suada/cli.rb CHANGED
@@ -9,9 +9,9 @@ require_relative "server"
9
9
  module Suada
10
10
  module CLI
11
11
  COMMANDS = {
12
- "build" => "[DECK] [-o DIR] [--watch]", "layouts" => "[DECK] [--explain KEY]",
12
+ "build" => "[DECK] [-o DIR] [--watch]", "layouts" => "[DECK] [--explain KEY[/STEP]]",
13
13
  "new" => "NAME [--theme light|dark]", "preview" => "[DECK] [--port N] [--no-open]",
14
- "present" => "[DECK] [--port N] [--no-open]", "export" => "pdf [DECK] -o FILE",
14
+ "present" => "[DECK] [--port N] [--no-open]", "export" => "pdf [DECK] -o FILE [--steps last|all]",
15
15
  "lint" => "[DECK]", "publish" => "[DECK] [--dir DIR] -- COMMAND [ARG...]",
16
16
  "version" => "", "help" => "[COMMAND]"
17
17
  }.freeze
@@ -69,6 +69,7 @@ module Suada
69
69
  def self.parser(cmd, opts)
70
70
  OptionParser.new do |p|
71
71
  p.on("-o PATH", "--out PATH") { |v| opts[:out] = v } if %w[build export].include?(cmd)
72
+ p.on("--steps MODE", %w[last all]) { |v| opts[:steps] = v } if cmd == "export"
72
73
  p.on("--watch") { opts[:watch] = true } if cmd == "build"
73
74
  p.on("--theme THEME") { |v| opts[:theme] = v } if cmd == "new"
74
75
  p.on("--explain KEY") { |v| opts[:explain] = v } if cmd == "layouts"
@@ -98,7 +99,10 @@ module Suada
98
99
  when "layouts"
99
100
  deck = Suada.compile(path)
100
101
  if (key = opts[:explain])
101
- puts deck.traces.fetch(key) { raise UsageError, "unknown slide key: #{key}" }
102
+ matches = deck.traces.select { |position, _| position == key || position.start_with?("#{key}/") }
103
+ raise UsageError, "unknown slide or step: #{key}" if matches.empty?
104
+
105
+ matches.each { |position, trace| puts "#{position}\n#{trace}" }
102
106
  else
103
107
  deck.layouts.each do |layout|
104
108
  puts layout.name
@@ -112,7 +116,7 @@ module Suada
112
116
  return Publisher.run(Suada.compile(path), opts.fetch(:dir), delegated)
113
117
  when "export"
114
118
  out = opts.fetch(:out) { raise UsageError, "export pdf requires -o FILE" }
115
- BrowserOutput.pdf(Suada.compile(path), path, out)
119
+ BrowserOutput.pdf(Suada.compile(path), path, out, steps: opts.fetch(:steps, "last"))
116
120
  when "lint"
117
121
  warnings = BrowserOutput.lint(Suada.compile(path), path)
118
122
  warnings.each { |warning| warn warning }
@@ -1,4 +1,9 @@
1
1
  .suada-slide {
2
+ --suada-morph-duration: 420ms;
3
+ --suada-morph-easing: cubic-bezier(.22,1,.36,1);
4
+ --suada-exit-duration: 150ms;
5
+ --suada-enter-duration: 220ms;
6
+ --suada-enter-lag: 110ms;
2
7
  box-sizing: border-box;
3
8
  width: 100%;
4
9
  height: 100%;
@@ -17,3 +22,20 @@
17
22
  .highlight .s, .highlight .s1, .highlight .s2 { color: #14705a; }
18
23
  .highlight .mi, .highlight .mf { color: #735817; }
19
24
  .highlight .c, .highlight .c1 { color: #637067; font-style: italic; }
25
+
26
+ .suada-slide { --suada-call-wait: .45; --suada-mark-padding: .14; }
27
+ .suada-g { display: inline-block; white-space: pre; }
28
+ .suada-plate { background: #ebeef0; border: 1px solid #cdd3d7; border-radius: .25em; }
29
+ .suada-mark { background: #ffdb71; border-radius: .12em; }
30
+ .suada-mark.suada-tone-b { background: #94d9cc; }
31
+ .suada-call {
32
+ --call-color: #ffdb71;
33
+ width: max-content; padding: .25em .65em; border-radius: .3em;
34
+ background: var(--call-color); color: #20241f; font-size: .75em;
35
+ }
36
+ .suada-call.suada-tone-b { --call-color: #94d9cc; }
37
+ .suada-call::after {
38
+ content: ""; position: absolute; left: var(--suada-call-tail); top: 100%;
39
+ border: .3em solid transparent; border-top-color: var(--call-color); transform: translateX(-50%);
40
+ }
41
+ .suada-call[data-below]::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: var(--call-color); }
@@ -14,7 +14,7 @@ module Suada
14
14
  slide = "slide #{error.slide_number}"
15
15
  slide += " ('#{error.slide_key}')" if error.slide_key
16
16
  end
17
- prefix = [location, slide].compact.join(", ")
17
+ prefix = [location, slide, ("step #{error.step_number}" if error.step_number)].compact.join(", ")
18
18
  message = [prefix, error.message].reject(&:empty?).join(": ")
19
19
  label = color ? "\e[31merror:\e[0m" : "error:"
20
20
  hint = color ? "\e[36mhelp:\e[0m" : "help:"
@@ -32,7 +32,7 @@ module Suada
32
32
  end
33
33
  File.write(File.join(stage, "manifest.json"), JSON.pretty_generate(manifest) + "\n")
34
34
  File.write(File.join(stage, "suada.css"), rendered.css)
35
- FileUtils.cp(%w[index.html viewer.js].map { |f| File.join(ASSETS, f) }, stage)
35
+ FileUtils.cp(%w[index.html viewer.js motion.js].map { |f| File.join(ASSETS, f) }, stage)
36
36
  install(stage, path)
37
37
  end
38
38
  Result.new(path, rendered.slides.size)
@@ -55,11 +55,16 @@ module Suada
55
55
  previous = path.join("manifest.json")
56
56
  prior = JSON.parse(previous.read) if previous.file? && !previous.symlink?
57
57
  owned = prior.is_a?(Hash) && prior["generator"] == "suada"
58
- generated = %w[slides assets manifest.json viewer.js index.html suada.css]
58
+ generated = %w[slides assets manifest.json viewer.js motion.js index.html suada.css]
59
59
  collisions = generated.select { |name| path.join(name).exist? || path.join(name).symlink? }
60
- if !owned && !collisions.empty?
61
- raise UsageError, "output contains existing files: #{collisions.join(', ')}"
62
- end
60
+ unowned = if !owned
61
+ collisions
62
+ elsif prior["version"] != 2
63
+ collisions & ["motion.js"]
64
+ else
65
+ []
66
+ end
67
+ raise UsageError, "output contains existing files: #{unowned.join(', ')}" unless unowned.empty?
63
68
  if owned
64
69
  old_slides = Array(prior["slides"]).filter_map { |entry| entry["src"] if entry.is_a?(Hash) }
65
70
  { "slides" => ->(f) { old_slides.include?("slides/#{f}") },
data/lib/suada/errors.rb CHANGED
@@ -5,9 +5,9 @@ module Suada
5
5
  class UsageError < Error; end
6
6
 
7
7
  class BuildError < Error
8
- attr_reader :kind, :help, :file, :line, :slide_number, :slide_key
8
+ attr_reader :kind, :help, :file, :line, :slide_number, :slide_key, :step_number
9
9
 
10
- def initialize(kind:, message:, help:, file: nil, line: nil, slide_number: nil, slide_key: nil)
10
+ def initialize(kind:, message:, help:, file: nil, line: nil, slide_number: nil, slide_key: nil, step_number: nil)
11
11
  super(message)
12
12
  @kind = kind
13
13
  @help = help
@@ -15,10 +15,11 @@ module Suada
15
15
  @line = line
16
16
  @slide_number = slide_number
17
17
  @slide_key = slide_key
18
+ @step_number = step_number
18
19
  end
19
20
 
20
- def with_slide(number, key)
21
- self.class.new(kind:, message:, help:, file:, line:, slide_number: number, slide_key: key)
21
+ def with_slide(number, key, step = step_number)
22
+ self.class.new(kind:, message:, help:, file:, line:, slide_number: number, slide_key: key, step_number: step)
22
23
  end
23
24
  end
24
25
  end
@@ -2,6 +2,21 @@
2
2
 
3
3
  module Suada
4
4
  module Fragment
5
+ def self.title(parts)
6
+ parts.select { |part| part.kind == :heading }.min_by(&:level)
7
+ end
8
+
9
+ def self.destination(part, title)
10
+ return "title" if part.equal?(title)
11
+
12
+ case part.kind
13
+ in :slot_group then part.slot
14
+ in :code then "code"
15
+ in :image then :image
16
+ in :paragraph | :heading | :list | :blockquote | :table then "body"
17
+ end
18
+ end
19
+
5
20
  Heading = Data.define(:line, :level, :inline_html, :text) do
6
21
  def kind = :heading
7
22
  def html = "<h#{level}>#{inline_html}</h#{level}>\n"
@@ -12,7 +27,7 @@ module Suada
12
27
  Blockquote = Data.define(:line, :html) { def kind = :blockquote }
13
28
  Table = Data.define(:line, :html) { def kind = :table }
14
29
 
15
- Code = Data.define(:line, :lang, :source) do
30
+ Code = Data.define(:line, :lang, :source, :attrs) do
16
31
  def kind = :code
17
32
  def html = nil
18
33
  end
@@ -22,6 +37,8 @@ module Suada
22
37
  def html = nil
23
38
  end
24
39
 
40
+ Callout = Data.define(:line, :targets, :tone, :below, :inline_html)
41
+
25
42
  SlotGroup = Data.define(:line, :slot, :children) do
26
43
  def kind = :slot_group
27
44
  def html = nil
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "psych"
4
4
  require_relative "source"
5
+ require_relative "attributes"
5
6
 
6
7
  module Suada
7
8
  module PlannedTime
@@ -19,8 +20,8 @@ module Suada
19
20
  end
20
21
 
21
22
  module Frontmatter
22
- DEFAULTS = { aspect_ratio: "16:9", breaks: false, lang: "en" }.freeze
23
- KEYS = %w[layouts css time aspect_ratio breaks lang].freeze
23
+ DEFAULTS = { aspect_ratio: "16:9", breaks: false, lang: "en", transition: "cut" }.freeze
24
+ KEYS = %w[layouts css time aspect_ratio breaks lang transition].freeze
24
25
  LANGUAGE_TAG = /\A(?:
25
26
  (?:[a-z]{2,3}(?:-[a-z]{3}){0,3}|[a-z]{4,8})(?:-[a-z]{4})?(?:-(?:[a-z]{2}|\d{3}))?
26
27
  (?:-(?:[a-z\d]{5,8}|\d[a-z\d]{3}))*(?:-[0-9a-wy-z](?:-[a-z\d]{2,8})+)*
@@ -62,6 +63,8 @@ module Suada
62
63
  case name
63
64
  when :time
64
65
  return PlannedTime.parse(raw) || fail_at(source, line, "invalid time '#{raw}'", "use minutes or a duration such as 1h30m")
66
+ when :transition
67
+ return raw if Attributes::TRANSITIONS.include?(raw)
65
68
  when :aspect_ratio
66
69
  return raw if %w[16:9 4:3].include?(raw)
67
70
  when :lang
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "nokogiri"
4
4
  require_relative "slot_contract"
5
+ require_relative "attributes"
5
6
 
6
7
  module Suada
7
8
  module LayoutParser
@@ -25,7 +26,17 @@ module Suada
25
26
  end
26
27
  slots[slot.name] = slot
27
28
  end
28
- Layout.new(name:, html: html.freeze, slots: slots.freeze, file:)
29
+ keys = []
30
+ doc.css("[data-k]").each do |node|
31
+ key = node["data-k"]
32
+ unless Attributes::KEY.match?(key) && !keys.include?(key) && node.name != "slot" &&
33
+ node.ancestors.none? { |parent| parent.name == "slot" }
34
+ raise BuildError.new(kind: :layout, file:, line: node.line, message: "invalid or duplicate layout key '#{key}'",
35
+ help: "use unique lowercase keys on elements outside slots")
36
+ end
37
+ keys << key
38
+ end
39
+ Layout.new(name:, html: html.freeze, slots: slots.freeze, file:, keys: keys.freeze)
29
40
  end
30
41
 
31
42
  def contract(node, file)
@@ -9,9 +9,10 @@ module Suada
9
9
  ratio = settings.fetch(:aspect_ratio, "16:9")
10
10
  slides = deck.slides.each_with_index.map do |slide, index|
11
11
  { index: index, key: slide.key, src: format("slides/%03d-%s.html", index, slide.key),
12
+ steps: slide.steps.length, transition: slide.steps.first.transition,
12
13
  hasNotes: !slide.notes.empty?, skip: slide.settings.fetch(:skip, false) }
13
14
  end
14
- { version: 1, generator: "suada", generatorVersion: VERSION, title: deck.slides.first&.title.to_s,
15
+ { version: 2, generator: "suada", generatorVersion: VERSION, title: deck.slides.first&.title.to_s,
15
16
  lang: settings.fetch(:lang, "en"), slideCount: slides.size, aspectRatio: ratio,
16
17
  canvasWidth: ratio == "4:3" ? 960 : 1280, canvasHeight: 720, plannedDurationMs: settings[:time],
17
18
  sections: settings.fetch(:sections, []), slides: slides }.compact