lepus-saga 0.3.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 (84) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +28 -0
  3. data/Gemfile +5 -0
  4. data/Gemfile.lock +237 -0
  5. data/LICENSE.txt +21 -0
  6. data/README.md +337 -0
  7. data/Rakefile +8 -0
  8. data/docs/brand/BRAND.md +67 -0
  9. data/docs/brand/apple-touch-icon.png +0 -0
  10. data/docs/brand/favicon-16.png +0 -0
  11. data/docs/brand/favicon-32.png +0 -0
  12. data/docs/brand/favicon.ico +0 -0
  13. data/docs/brand/favicon.svg +1 -0
  14. data/docs/brand/icon-512.png +0 -0
  15. data/docs/brand/lockup-lepus-mono.svg +1 -0
  16. data/docs/brand/lockup-lepus-on-dark.svg +1 -0
  17. data/docs/brand/lockup-lepus-on-light.svg +1 -0
  18. data/docs/brand/lockup-lepus-saga-mono.svg +1 -0
  19. data/docs/brand/lockup-lepus-saga-on-dark.svg +1 -0
  20. data/docs/brand/lockup-lepus-saga-on-light.svg +1 -0
  21. data/docs/brand/lockup-lepus-saga.svg +1 -0
  22. data/docs/brand/lockup-lepus.svg +1 -0
  23. data/docs/brand/mark-mono.svg +1 -0
  24. data/docs/brand/mark-on-dark.svg +1 -0
  25. data/docs/brand/mark-on-light.svg +1 -0
  26. data/docs/brand/mark-small-mono.svg +1 -0
  27. data/docs/brand/mark-small-on-dark.svg +1 -0
  28. data/docs/brand/mark-small-on-light.svg +1 -0
  29. data/docs/brand/mark-small.svg +1 -0
  30. data/docs/brand/mark.svg +1 -0
  31. data/lib/lepus/saga/configuration.rb +48 -0
  32. data/lib/lepus/saga/control.rb +27 -0
  33. data/lib/lepus/saga/definition.rb +123 -0
  34. data/lib/lepus/saga/execution_behaviour.rb +58 -0
  35. data/lib/lepus/saga/executor.rb +282 -0
  36. data/lib/lepus/saga/executor_consumer.rb +38 -0
  37. data/lib/lepus/saga/instrumentation.rb +41 -0
  38. data/lib/lepus/saga/log_subscriber.rb +42 -0
  39. data/lib/lepus/saga/queue_depth.rb +28 -0
  40. data/lib/lepus/saga/resume_stuck_job.rb +19 -0
  41. data/lib/lepus/saga/retry_policy.rb +19 -0
  42. data/lib/lepus/saga/rspec/engine_examples.rb +635 -0
  43. data/lib/lepus/saga/rspec/helpers.rb +22 -0
  44. data/lib/lepus/saga/rspec/query_examples.rb +378 -0
  45. data/lib/lepus/saga/rspec/store_examples.rb +514 -0
  46. data/lib/lepus/saga/rspec.rb +6 -0
  47. data/lib/lepus/saga/step.rb +9 -0
  48. data/lib/lepus/saga/step_attempt_behaviour.rb +35 -0
  49. data/lib/lepus/saga/step_producer.rb +37 -0
  50. data/lib/lepus/saga/stores/base.rb +305 -0
  51. data/lib/lepus/saga/stores/memory.rb +375 -0
  52. data/lib/lepus/saga/stores.rb +40 -0
  53. data/lib/lepus/saga/testing.rb +35 -0
  54. data/lib/lepus/saga/version.rb +7 -0
  55. data/lib/lepus/saga/web/api.rb +326 -0
  56. data/lib/lepus/saga/web/configuration.rb +49 -0
  57. data/lib/lepus/saga/web/guard.rb +38 -0
  58. data/lib/lepus/saga/web/serializer.rb +59 -0
  59. data/lib/lepus/saga/web/static.rb +108 -0
  60. data/lib/lepus/saga/web.rb +61 -0
  61. data/lib/lepus/saga.rb +212 -0
  62. data/lib/lepus-saga.rb +3 -0
  63. data/mise.toml +2 -0
  64. data/web/assets/app.css +913 -0
  65. data/web/assets/apple-touch-icon.png +0 -0
  66. data/web/assets/favicon-32.png +0 -0
  67. data/web/assets/favicon.svg +1 -0
  68. data/web/assets/fonts/overpass/OFL.txt +93 -0
  69. data/web/assets/fonts/overpass/overpass-latin-wght.woff2 +0 -0
  70. data/web/assets/js/api.js +50 -0
  71. data/web/assets/js/dom.js +84 -0
  72. data/web/assets/js/format.js +79 -0
  73. data/web/assets/js/live.js +74 -0
  74. data/web/assets/js/main.js +143 -0
  75. data/web/assets/js/map.js +639 -0
  76. data/web/assets/js/range.js +19 -0
  77. data/web/assets/js/sagas.js +18 -0
  78. data/web/assets/js/theme.js +8 -0
  79. data/web/assets/js/throughput.js +262 -0
  80. data/web/assets/js/views/execution.js +426 -0
  81. data/web/assets/js/views/executions.js +165 -0
  82. data/web/assets/js/views/overview.js +465 -0
  83. data/web/index.html +63 -0
  84. metadata +323 -0
Binary file
Binary file
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Lepus"><title>Lepus</title><style>.i{stroke:#1a2233}.f{fill:#1a2233}@media (prefers-color-scheme:dark){.i{stroke:#e3e9f3}.f{fill:#e3e9f3}}</style><path class="i" d="M12 6 V40 A16 16 0 0 0 28 56 H42 A10 10 0 0 0 42 36 H28 V18" fill="none" stroke-width="8" stroke-linecap="round" stroke-linejoin="round"/><circle cx="40" cy="46" r="5" fill="#f2a30f"/></svg>
@@ -0,0 +1,93 @@
1
+ Copyright 2021 The Overpass Project Authors (https://github.com/RedHatOfficial/Overpass) Overpass-Italic[wght].ttf: Copyright 2021 The Overpass Project Authors (https://github.com/RedHatOfficial/Overpass)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,50 @@
1
+ export class ApiError extends Error {
2
+ constructor(status, message) {
3
+ super(message);
4
+ this.status = status;
5
+ }
6
+ }
7
+
8
+ function url(path, params = {}) {
9
+ const query = new URLSearchParams();
10
+ for (const [key, value] of Object.entries(params)) {
11
+ if (value === null || value === undefined || value === "") continue;
12
+ query.set(key, Array.isArray(value) ? value.join(",") : value);
13
+ }
14
+ const search = query.toString();
15
+ return `api/${path}${search ? `?${search}` : ""}`;
16
+ }
17
+
18
+ async function request(path, options = {}) {
19
+ let response;
20
+ try {
21
+ response = await fetch(path, { credentials: "same-origin", headers: { Accept: "application/json" }, ...options });
22
+ } catch {
23
+ throw new ApiError(0, "The console could not reach the server");
24
+ }
25
+ const data = await response.json().catch(() => ({}));
26
+ if (!response.ok) throw new ApiError(response.status, data.error || `Request failed (${response.status})`);
27
+ return data;
28
+ }
29
+
30
+ function post(path, body = {}) {
31
+ return request(url(path), {
32
+ method: "POST",
33
+ headers: { Accept: "application/json", "Content-Type": "application/json", "X-Lepus-Saga": "1" },
34
+ body: JSON.stringify(body)
35
+ });
36
+ }
37
+
38
+ export const api = {
39
+ me: () => request(url("me")),
40
+ sagas: (params) => request(url("sagas", params)),
41
+ executions: (params) => request(url("executions", params)),
42
+ execution: (id) => request(url(`executions/${encodeURIComponent(id)}`)),
43
+ moving: (params) => request(url("moving", params)),
44
+ series: (params) => request(url("series", params)),
45
+ failures: (params) => request(url("insights/failures", params)),
46
+ latency: (params) => request(url("insights/latency", params)),
47
+ stalled: (params) => request(url("stalled", params)),
48
+ retry: (id) => post(`executions/${encodeURIComponent(id)}/retry`),
49
+ compensate: (id, reason) => post(`executions/${encodeURIComponent(id)}/compensate`, { reason })
50
+ };
@@ -0,0 +1,84 @@
1
+ const SVG_NS = "http://www.w3.org/2000/svg";
2
+
3
+ function apply(el, attrs) {
4
+ for (const [key, value] of Object.entries(attrs || {})) {
5
+ if (value === null || value === undefined || value === false) continue;
6
+ if (key === "text") el.textContent = value;
7
+ else if (key.startsWith("on") && typeof value === "function") el.addEventListener(key.slice(2), value);
8
+ else el.setAttribute(key, value === true ? "" : String(value));
9
+ }
10
+ }
11
+
12
+ function append(el, children) {
13
+ for (const child of children.flat(Infinity)) {
14
+ if (child === null || child === undefined || child === false) continue;
15
+ el.append(child instanceof Node ? child : document.createTextNode(String(child)));
16
+ }
17
+ return el;
18
+ }
19
+
20
+ export function h(tag, attrs, ...children) {
21
+ const el = document.createElement(tag);
22
+ apply(el, attrs);
23
+ return append(el, children);
24
+ }
25
+
26
+ export function s(tag, attrs, ...children) {
27
+ const el = document.createElementNS(SVG_NS, tag);
28
+ apply(el, attrs);
29
+ return append(el, children);
30
+ }
31
+
32
+ export function clear(el) {
33
+ while (el.firstChild) el.firstChild.remove();
34
+ return el;
35
+ }
36
+
37
+ const FOCUSABLE = "a[href], button, input, select, summary, [tabindex]";
38
+ const focusKey = (el) => el.getAttribute("href") || `${el.tagName}|${el.textContent}`;
39
+
40
+ // Replaces el's children for a poll without disturbing assistive technology:
41
+ // unchanged content is left alone, and focus inside el moves to the matching
42
+ // control of the new content (the same link target, or tag and text).
43
+ export function refill(el, ...children) {
44
+ const next = append(document.createDocumentFragment(), children);
45
+ const same = next.childNodes.length === el.childNodes.length &&
46
+ [...next.childNodes].every((node, index) => node.isEqualNode(el.childNodes[index]));
47
+ if (same) return el;
48
+ const active = document.activeElement;
49
+ const key = active && active !== el && el.contains(active) ? focusKey(active) : null;
50
+ clear(el).append(next);
51
+ if (key) [...el.querySelectorAll(FOCUSABLE)].find((node) => focusKey(node) === key)?.focus({ preventScroll: true });
52
+ return el;
53
+ }
54
+
55
+ let toastTimer;
56
+ export function toast(message, { error = false } = {}) {
57
+ const el = document.getElementById("toast");
58
+ el.textContent = message;
59
+ el.classList.toggle("is-error", error);
60
+ el.classList.add("is-shown");
61
+ clearTimeout(toastTimer);
62
+ toastTimer = setTimeout(() => el.classList.remove("is-shown"), 3600);
63
+ }
64
+
65
+ export const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
66
+
67
+ export function copyButton(value, label) {
68
+ return h("button", {
69
+ type: "button",
70
+ class: "copy",
71
+ "aria-label": `Copy ${label}`,
72
+ title: `Copy ${label}`,
73
+ onclick: async () => {
74
+ try {
75
+ await navigator.clipboard.writeText(value);
76
+ toast(`Copied ${label}`);
77
+ } catch {
78
+ toast("The browser blocked the clipboard", { error: true });
79
+ }
80
+ }
81
+ }, s("svg", { viewBox: "0 0 16 16", width: 14, height: 14, "aria-hidden": "true" },
82
+ s("rect", { x: 5.5, y: 5.5, width: 8, height: 8, rx: 1.5 }),
83
+ s("path", { d: "M10.5 3.5v-.5a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h.5" })));
84
+ }
@@ -0,0 +1,79 @@
1
+ const numbers = new Intl.NumberFormat();
2
+ const timeOfDay = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit" });
3
+ const dayTime = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
4
+
5
+ const STATUS = {
6
+ running: "Running",
7
+ compensating: "Compensating",
8
+ completed: "Completed",
9
+ compensated: "Compensated",
10
+ failed: "Failed",
11
+ compensation_failed: "Compensation failed"
12
+ };
13
+
14
+ export const statusLabel = (status) => STATUS[status] || status;
15
+ export const count = (value) => numbers.format(value || 0);
16
+ export const plural = (n, one, many = `${one}s`) => `${count(n)} ${n === 1 ? one : many}`;
17
+ export const toTime = (value) => (value ? Date.parse(value) : null);
18
+ export const hourMinute = (value) => timeOfDay.format(new Date(value));
19
+ export const stamp = (value) => (value ? dayTime.format(new Date(value)) : "");
20
+
21
+ export function duration(ms) {
22
+ if (ms === null || ms === undefined || Number.isNaN(ms)) return "";
23
+ if (ms < 1000) return `${Math.round(ms)} ms`;
24
+ const seconds = ms / 1000;
25
+ if (seconds < 10) return `${seconds.toFixed(1)} s`;
26
+ if (seconds < 60) return `${Math.round(seconds)} s`;
27
+ const minutes = Math.floor(seconds / 60);
28
+ if (minutes < 60) {
29
+ const rest = Math.round(seconds - minutes * 60);
30
+ return rest ? `${minutes} min ${rest} s` : `${minutes} min`;
31
+ }
32
+ const hours = Math.floor(minutes / 60);
33
+ if (hours < 48) {
34
+ const rest = minutes - hours * 60;
35
+ return rest ? `${hours} h ${rest} min` : `${hours} h`;
36
+ }
37
+ return `${Math.round(hours / 24)} days`;
38
+ }
39
+
40
+ export function ago(value, now = Date.now()) {
41
+ const time = typeof value === "number" ? value : toTime(value);
42
+ if (!time) return "";
43
+ const ms = Math.max(0, now - time);
44
+ if (ms < 45_000) return "just now";
45
+ if (ms >= 86_400_000) return `${waited(ms)} ago`;
46
+ return `${duration(Math.round(ms / 60_000) * 60_000)} ago`;
47
+ }
48
+
49
+ export function offset(ms) {
50
+ if (ms < 1000) return "+0 s";
51
+ const seconds = Math.round(ms / 1000);
52
+ if (seconds < 60) return `+${seconds} s`;
53
+ const minutes = Math.floor(seconds / 60);
54
+ if (minutes < 60) return `+${minutes}:${String(seconds % 60).padStart(2, "0")}`;
55
+ const hours = Math.floor(minutes / 60);
56
+ return `+${hours} h ${minutes % 60}m`;
57
+ }
58
+
59
+ export function waited(ms) {
60
+ const minutes = Math.floor(ms / 60_000);
61
+ if (minutes < 60) return `${minutes} min`;
62
+ const hours = Math.floor(minutes / 60);
63
+ if (hours < 24) return `${hours} h ${minutes % 60} min`;
64
+ return `${Math.floor(hours / 24)} d ${hours % 24} h`;
65
+ }
66
+
67
+ const dayOfMonth = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" });
68
+
69
+ export const dayMonth = (value) => dayOfMonth.format(new Date(value));
70
+
71
+ export function compact(value) {
72
+ const n = value || 0;
73
+ if (n < 1000) return String(n);
74
+ const [scaled, unit] = n < 1_000_000 ? [n / 1000, "k"] : [n / 1_000_000, "M"];
75
+ const digits = scaled < 10 ? 1 : 0;
76
+ const rounded = Number(scaled.toFixed(digits));
77
+ if (rounded >= 1000 && unit === "k") return compact(1_000_000);
78
+ return `${rounded}${unit}`;
79
+ }
@@ -0,0 +1,74 @@
1
+ const KEY = "lepus-saga:poll";
2
+ const listeners = new Set();
3
+
4
+ // Polling state shared by every view: `seconds` is 0 when paused. The map
5
+ // reads `now()` so tokens freeze while paused instead of creeping on.
6
+ export const live = { seconds: 5, choices: [0, 2, 5, 15, 60], fallback: 5, frozenAt: null };
7
+
8
+ export const isLive = () => live.seconds > 0;
9
+ export const pollMs = () => (live.seconds || live.fallback) * 1000;
10
+ export const now = () => (isLive() ? Date.now() : live.frozenAt ?? Date.now());
11
+
12
+ export function setupPolling(me) {
13
+ const choices = (me.poll_intervals || []).filter((n) => Number.isFinite(n) && n >= 0);
14
+ if (choices.length) live.choices = [...new Set(choices)].sort((a, b) => a - b);
15
+ if (!live.choices.includes(0)) live.choices.unshift(0);
16
+ live.fallback = live.choices.includes(me.poll_interval) && me.poll_interval > 0 ? me.poll_interval : live.choices.find((n) => n > 0) || 5;
17
+ let stored = null;
18
+ try { stored = localStorage.getItem(KEY); } catch {}
19
+ const wanted = stored === null ? live.fallback : Number(stored);
20
+ setPoll(live.choices.includes(wanted) ? wanted : live.fallback, { store: false });
21
+ }
22
+
23
+ export function setPoll(seconds, { store = true } = {}) {
24
+ const was = live.seconds;
25
+ live.seconds = seconds;
26
+ if (seconds === 0 && was !== 0) live.frozenAt = Date.now();
27
+ if (seconds > 0) live.frozenAt = null;
28
+ if (store) {
29
+ try { localStorage.setItem(KEY, String(seconds)); } catch {}
30
+ }
31
+ for (const listener of listeners) listener(live);
32
+ }
33
+
34
+ export function onLive(listener) {
35
+ listeners.add(listener);
36
+ return () => listeners.delete(listener);
37
+ }
38
+
39
+ // Runs fn now (even while paused, so a view always has data) and then every
40
+ // `interval()` ms, measured from the start of each run, while polling is on
41
+ // and the tab is visible. Turning polling back on or changing the interval
42
+ // runs it again right away, or as soon as a run in progress finishes.
43
+ export function every(interval, fn) {
44
+ const ms = typeof interval === "function" ? interval : () => interval;
45
+ let timer = null;
46
+ let stopped = false;
47
+ let busy = false;
48
+ let again = false;
49
+ const tick = async (force = false) => {
50
+ clearTimeout(timer);
51
+ timer = null;
52
+ if (stopped) return;
53
+ if (busy) { again = true; return; }
54
+ busy = true;
55
+ again = false;
56
+ const started = Date.now();
57
+ if (force || (isLive() && !document.hidden)) {
58
+ try { await fn(); } catch (error) { console.warn(error); }
59
+ }
60
+ busy = false;
61
+ if (stopped || !isLive()) return;
62
+ timer = setTimeout(tick, again ? 0 : Math.max(0, ms() - (Date.now() - started)));
63
+ };
64
+ const resume = () => { if (!stopped && isLive() && !document.hidden) tick(); };
65
+ const offLive = onLive(resume);
66
+ document.addEventListener("visibilitychange", resume);
67
+ tick(true);
68
+ return () => {
69
+ stopped = true;
70
+ clearTimeout(timer);
71
+ offLive();
72
+ document.removeEventListener("visibilitychange", resume);
73
+ };
74
+ }
@@ -0,0 +1,143 @@
1
+ import { api } from "./api.js";
2
+ import { clear, h } from "./dom.js";
3
+ import { live, onLive, setPoll, setupPolling } from "./live.js";
4
+ import { overview } from "./views/overview.js";
5
+ import { executions } from "./views/executions.js";
6
+ import { execution } from "./views/execution.js";
7
+
8
+ const THEME_KEY = "lepus-saga:theme";
9
+ const view = document.getElementById("view");
10
+ let current = null;
11
+ let me = { actions: {}, read_only: true, poll_interval: 5 };
12
+
13
+ function route() {
14
+ const hash = location.hash.replace(/^#/, "") || "/";
15
+ const [path, search = ""] = hash.split("?");
16
+ const params = new URLSearchParams(search);
17
+ const detail = path.match(/^\/executions\/([^/]+)$/);
18
+ if (detail) return { name: "executions", render: execution, args: { id: decodeURIComponent(detail[1]) } };
19
+ if (path === "/executions") return { name: "executions", render: executions, args: { params } };
20
+ return { name: "map", render: overview, args: { params } };
21
+ }
22
+
23
+ function navigate() {
24
+ if (current && current.destroy) current.destroy();
25
+ const { name, render, args } = route();
26
+ for (const link of document.querySelectorAll("[data-nav]")) {
27
+ if (link.dataset.nav === name) link.setAttribute("aria-current", "page");
28
+ else link.removeAttribute("aria-current");
29
+ }
30
+ clear(view);
31
+ current = render(view, { ...args, me });
32
+ window.scrollTo(0, 0);
33
+ }
34
+
35
+ function applyTheme(choice) {
36
+ if (choice === "light" || choice === "dark") document.documentElement.setAttribute("data-theme", choice);
37
+ else document.documentElement.removeAttribute("data-theme");
38
+ for (const button of document.querySelectorAll("[data-theme-choice]")) {
39
+ button.setAttribute("aria-pressed", String(button.dataset.themeChoice === choice));
40
+ }
41
+ }
42
+
43
+ function setupTheme() {
44
+ let choice = "auto";
45
+ try { choice = localStorage.getItem(THEME_KEY) || "auto"; } catch {}
46
+ applyTheme(choice);
47
+ for (const button of document.querySelectorAll("[data-theme-choice]")) {
48
+ button.addEventListener("click", () => {
49
+ const next = button.dataset.themeChoice;
50
+ try {
51
+ if (next === "auto") localStorage.removeItem(THEME_KEY);
52
+ else localStorage.setItem(THEME_KEY, next);
53
+ } catch {}
54
+ applyTheme(next);
55
+ });
56
+ }
57
+ }
58
+
59
+ const rateText = (seconds) => (seconds ? `${seconds} s` : "Paused");
60
+
61
+ function setupLive() {
62
+ const wrap = document.getElementById("poll");
63
+ const button = document.getElementById("live");
64
+ const menu = document.getElementById("poll-menu");
65
+ const options = document.getElementById("poll-options");
66
+ const text = button.querySelector(".live-text");
67
+ const rate = button.querySelector(".live-rate");
68
+
69
+ // Arrow keys move through the radios one by one; only the rate the
70
+ // keyboard settles on (or the menu closes on) is applied.
71
+ let pending = null;
72
+ let commitTimer = null;
73
+ const commit = () => {
74
+ clearTimeout(commitTimer);
75
+ if (pending !== null && pending !== live.seconds) setPoll(pending);
76
+ pending = null;
77
+ };
78
+
79
+ clear(options);
80
+ const order = [0, ...live.choices.filter((n) => n > 0)];
81
+ const radios = order.map((seconds) => {
82
+ const input = h("input", { type: "radio", name: "poll", value: String(seconds) });
83
+ input.addEventListener("change", () => {
84
+ pending = seconds;
85
+ clearTimeout(commitTimer);
86
+ commitTimer = setTimeout(commit, 700);
87
+ });
88
+ options.append(h("label", { class: "poll-option" }, input,
89
+ h("span", {}, seconds ? `Every ${seconds} s` : "Paused"),
90
+ seconds === live.fallback ? h("span", { class: "poll-default" }, "default") : null));
91
+ return input;
92
+ });
93
+
94
+ const show = () => {
95
+ const on = live.seconds > 0;
96
+ wrap.classList.toggle("is-paused", !on);
97
+ text.textContent = on ? "Live" : "Paused";
98
+ rate.textContent = on ? rateText(live.seconds) : "";
99
+ button.setAttribute("aria-label", on ? `Live ${rateText(live.seconds)}, refresh interval` : "Paused, refresh interval");
100
+ button.title = on ? `Updating every ${live.seconds} seconds` : "Updates paused";
101
+ radios.forEach((input, index) => { input.checked = order[index] === live.seconds; });
102
+ };
103
+
104
+ const open = (state) => {
105
+ menu.hidden = !state;
106
+ button.setAttribute("aria-expanded", String(state));
107
+ if (state) (radios.find((input) => input.checked) || radios[0]).focus();
108
+ };
109
+ const close = (refocus) => {
110
+ commit();
111
+ if (menu.hidden) return;
112
+ open(false);
113
+ if (refocus) button.focus();
114
+ };
115
+
116
+ button.addEventListener("click", () => open(menu.hidden));
117
+ menu.addEventListener("keydown", (event) => {
118
+ if (event.key === "Escape" || event.key === "Enter") { event.preventDefault(); close(true); }
119
+ });
120
+ menu.addEventListener("click", (event) => { if (event.target.matches("input") && event.detail > 0) close(true); });
121
+ document.addEventListener("keydown", (event) => { if (event.key === "Escape") close(wrap.contains(document.activeElement)); });
122
+ document.addEventListener("pointerdown", (event) => { if (!wrap.contains(event.target)) close(false); });
123
+ wrap.addEventListener("focusout", (event) => { if (event.relatedTarget && !wrap.contains(event.relatedTarget)) close(false); });
124
+ onLive(show);
125
+ show();
126
+ }
127
+
128
+ async function start() {
129
+ setupTheme();
130
+ try {
131
+ me = await api.me();
132
+ document.getElementById("brand-title").textContent = me.title;
133
+ setupPolling(me);
134
+ setupLive();
135
+ } catch (error) {
136
+ clear(view).append(h("p", { class: "error" }, error.message));
137
+ return;
138
+ }
139
+ window.addEventListener("hashchange", navigate);
140
+ navigate();
141
+ }
142
+
143
+ start();