tortoise-orm-studio 1.0.0__py3-none-any.whl

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 (68) hide show
  1. tortoise_orm_studio/__init__.py +11 -0
  2. tortoise_orm_studio/adapters/__init__.py +1 -0
  3. tortoise_orm_studio/adapters/aiohttp_adapter.py +31 -0
  4. tortoise_orm_studio/adapters/asgi.py +89 -0
  5. tortoise_orm_studio/adapters/base.py +25 -0
  6. tortoise_orm_studio/adapters/django_adapter.py +84 -0
  7. tortoise_orm_studio/adapters/quart_adapter.py +32 -0
  8. tortoise_orm_studio/adapters/registry.py +39 -0
  9. tortoise_orm_studio/adapters/sanic_adapter.py +39 -0
  10. tortoise_orm_studio/auth.py +34 -0
  11. tortoise_orm_studio/cli.py +41 -0
  12. tortoise_orm_studio/core/__init__.py +1 -0
  13. tortoise_orm_studio/core/aerich.py +86 -0
  14. tortoise_orm_studio/core/ai.py +87 -0
  15. tortoise_orm_studio/core/audit.py +69 -0
  16. tortoise_orm_studio/core/config.py +58 -0
  17. tortoise_orm_studio/core/filters.py +94 -0
  18. tortoise_orm_studio/core/handler.py +249 -0
  19. tortoise_orm_studio/core/http.py +55 -0
  20. tortoise_orm_studio/core/i18n.py +18 -0
  21. tortoise_orm_studio/core/introspect.py +197 -0
  22. tortoise_orm_studio/core/manifest.py +128 -0
  23. tortoise_orm_studio/core/pagination.py +59 -0
  24. tortoise_orm_studio/core/permissions.py +46 -0
  25. tortoise_orm_studio/core/plugins.py +214 -0
  26. tortoise_orm_studio/core/ratelimit.py +32 -0
  27. tortoise_orm_studio/core/scoping.py +23 -0
  28. tortoise_orm_studio/core/serializers.py +61 -0
  29. tortoise_orm_studio/core/service.py +594 -0
  30. tortoise_orm_studio/plugins.py +8 -0
  31. tortoise_orm_studio/static/ALPINE_LICENSE.txt +11 -0
  32. tortoise_orm_studio/static/_types.d.ts +706 -0
  33. tortoise_orm_studio/static/a11y.js +115 -0
  34. tortoise_orm_studio/static/ai.js +66 -0
  35. tortoise_orm_studio/static/alpine.min.js +23 -0
  36. tortoise_orm_studio/static/app.css +514 -0
  37. tortoise_orm_studio/static/app.js +1443 -0
  38. tortoise_orm_studio/static/audit.js +171 -0
  39. tortoise_orm_studio/static/copy-as.js +118 -0
  40. tortoise_orm_studio/static/er-layout.js +227 -0
  41. tortoise_orm_studio/static/er.js +296 -0
  42. tortoise_orm_studio/static/filters.js +114 -0
  43. tortoise_orm_studio/static/i18n.en.js +190 -0
  44. tortoise_orm_studio/static/i18n.js +140 -0
  45. tortoise_orm_studio/static/i18n.zh-CN.js +189 -0
  46. tortoise_orm_studio/static/index.html +515 -0
  47. tortoise_orm_studio/static/inline-edit.js +107 -0
  48. tortoise_orm_studio/static/json-view.js +161 -0
  49. tortoise_orm_studio/static/migrations.js +139 -0
  50. tortoise_orm_studio/static/palette.js +141 -0
  51. tortoise_orm_studio/static/pending.js +240 -0
  52. tortoise_orm_studio/static/pickers.js +230 -0
  53. tortoise_orm_studio/static/playground.js +105 -0
  54. tortoise_orm_studio/static/query-history.js +84 -0
  55. tortoise_orm_studio/static/shortcuts.js +145 -0
  56. tortoise_orm_studio/static/state-hash.js +112 -0
  57. tortoise_orm_studio/static/tabs.js +368 -0
  58. tortoise_orm_studio/static/theme-init.js +33 -0
  59. tortoise_orm_studio/static/theme.js +106 -0
  60. tortoise_orm_studio/static/toasts.js +76 -0
  61. tortoise_orm_studio/static/views.js +70 -0
  62. tortoise_orm_studio/static/widgets.js +345 -0
  63. tortoise_orm_studio/studio.py +51 -0
  64. tortoise_orm_studio-1.0.0.dist-info/METADATA +177 -0
  65. tortoise_orm_studio-1.0.0.dist-info/RECORD +68 -0
  66. tortoise_orm_studio-1.0.0.dist-info/WHEEL +4 -0
  67. tortoise_orm_studio-1.0.0.dist-info/entry_points.txt +2 -0
  68. tortoise_orm_studio-1.0.0.dist-info/licenses/LICENSE +13 -0
@@ -0,0 +1,230 @@
1
+ // @ts-check
2
+ /**
3
+ * FK/O2O/M2M picker modal. No Alpine dependency.
4
+ *
5
+ * Widgets call ``StudioPicker.request({model, onSelect})`` — the picker
6
+ * fetches rows from the API, renders a searchable table, and calls back
7
+ * with the selected pk. Close with ×, Escape, or a row click.
8
+ *
9
+ * Types (PickerConfig, PickerAPI) come from _types.d.ts.
10
+ */
11
+
12
+ (function (/** @type {Window & { StudioPicker?: PickerAPI }} */ global) {
13
+ "use strict";
14
+
15
+ const base = (global.location && global.location.pathname || "/").replace(/\/?$/, "/");
16
+
17
+ /** @param {string} path @returns {Promise<any>} */
18
+ async function api(path) {
19
+ const res = await fetch(base + "api/" + path, {
20
+ headers: { "x-requested-with": "studio" },
21
+ });
22
+ const data = await res.json().catch(() => ({}));
23
+ if (!res.ok) throw new Error((data.error && data.error.message) || res.statusText);
24
+ return data;
25
+ }
26
+
27
+ /**
28
+ * @template {keyof HTMLElementTagNameMap} K
29
+ * @param {K} tag
30
+ * @param {Record<string, any>} props
31
+ * @param {Array<Node|string>} [children]
32
+ * @returns {HTMLElementTagNameMap[K]}
33
+ */
34
+ function create(tag, props, children) {
35
+ /** @type {any} */
36
+ const el = document.createElement(tag);
37
+ for (const k of Object.keys(props || {})) {
38
+ const v = props[k];
39
+ if (v === undefined) continue;
40
+ if (k === "class") el.className = v;
41
+ else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
42
+ else if (k in el) el[k] = v;
43
+ else el.setAttribute(k, String(v));
44
+ }
45
+ for (const c of children || []) {
46
+ el.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
47
+ }
48
+ return el;
49
+ }
50
+
51
+ /** @param {unknown} v @returns {string} */
52
+ function cellText(v) {
53
+ return v === null ? "NULL"
54
+ : typeof v === "object" ? JSON.stringify(v)
55
+ : String(v);
56
+ }
57
+
58
+ /** @param {PickerConfig} cfg */
59
+ function request(cfg) {
60
+ const isMulti = !!cfg.multiSelect;
61
+ /** @type {Set<string>} */
62
+ const selected = new Set((cfg.preselect || []).map(String));
63
+ let confirmed = false;
64
+
65
+ const overlay = create("div", { class: "picker-overlay" });
66
+ const modal = create("div", { class: "picker-modal", role: "dialog",
67
+ "aria-modal": "true", "aria-label": "Choose " + (cfg.label || cfg.model) });
68
+ const A = /** @type {A11yAPI|undefined} */ (/** @type {any} */ (global).StudioA11y);
69
+ /** @type {HTMLElement|null} */
70
+ const returnFocus = A ? A.saveFocus() : (/** @type {any} */ (document).activeElement || null);
71
+
72
+ /** Close modal. Calls onCancel if not confirmed. */
73
+ function close() {
74
+ document.removeEventListener("keydown", onKey);
75
+ overlay.remove();
76
+ if (A && returnFocus) A.restoreFocus(returnFocus);
77
+ if (!confirmed && cfg.onCancel) cfg.onCancel();
78
+ }
79
+
80
+ /** @param {KeyboardEvent} e */
81
+ function onKey(e) {
82
+ if (e.key === "Escape") { close(); return; }
83
+ if (e.key === "Tab" && A && A.trapFocus(modal, e)) e.preventDefault();
84
+ }
85
+ document.addEventListener("keydown", onKey);
86
+
87
+ const header = create("div", { class: "picker-header" }, [
88
+ create("h3", {}, [`Pick ${cfg.label || cfg.model}`]),
89
+ create("button", { type: "button", class: "picker-close", "aria-label": "Close picker", onclick: close }, ["×"]),
90
+ ]);
91
+ const search = create("input", {
92
+ type: "search", placeholder: "search (Enter)", class: "picker-search",
93
+ });
94
+ const tableWrap = create("div", { class: "picker-table-wrap" });
95
+ const table = create("table", { class: "picker-table" });
96
+ tableWrap.appendChild(table);
97
+ const footer = create("div", { class: "picker-footer" });
98
+
99
+ modal.appendChild(header);
100
+ modal.appendChild(search);
101
+ modal.appendChild(tableWrap);
102
+ modal.appendChild(footer);
103
+ overlay.appendChild(modal);
104
+ document.body.appendChild(overlay);
105
+
106
+ let page = 1;
107
+ const limit = 20;
108
+ let total = 0;
109
+ let searchTerm = "";
110
+
111
+ async function load() {
112
+ table.innerHTML = "";
113
+ try {
114
+ const qs = new URLSearchParams({
115
+ page: String(page), limit: String(limit),
116
+ });
117
+ if (searchTerm) qs.set("search", searchTerm);
118
+ const d = await api("models/" + cfg.model + "?" + qs.toString());
119
+ total = d.total;
120
+ const rows = d.items;
121
+
122
+ if (!rows.length) {
123
+ table.appendChild(create("tbody", {}, [
124
+ create("tr", {}, [create("td", { class: "picker-empty" }, ["No results"])]),
125
+ ]));
126
+ } else {
127
+ const cols = ["_pk", ...Object.keys(rows[0]).filter(k => k !== "_pk")];
128
+ table.appendChild(create("thead", {}, [
129
+ create("tr", {}, cols.map(c => create("th", {}, [c === "_pk" ? "id" : c]))),
130
+ ]));
131
+ const tbody = create("tbody", {});
132
+ for (const row of rows) {
133
+ const pkStr = String(row._pk);
134
+ const isSel = selected.has(pkStr);
135
+ const tr = create("tr", {
136
+ class: "picker-row" + (isSel ? " selected" : ""),
137
+ "data-pk": pkStr,
138
+ onclick: function (/** @type {Event} */ e) {
139
+ if (isMulti) toggle(row, /** @type {HTMLElement} */ (e.currentTarget));
140
+ else pick(row);
141
+ },
142
+ });
143
+ if (isMulti) {
144
+ tr.appendChild(create("td", {}, [
145
+ create("input", {
146
+ type: "checkbox", checked: isSel,
147
+ onclick: function (/** @type {Event} */ e) {
148
+ e.stopPropagation();
149
+ toggle(row, tr);
150
+ },
151
+ }),
152
+ ]));
153
+ }
154
+ for (const c of cols) {
155
+ tr.appendChild(create("td", {}, [cellText(row[c])]));
156
+ }
157
+ tbody.appendChild(tr);
158
+ }
159
+ table.appendChild(tbody);
160
+ }
161
+ renderFooter();
162
+ } catch (e) {
163
+ table.innerHTML = "";
164
+ table.appendChild(create("tbody", {}, [
165
+ create("tr", {}, [create("td", { class: "picker-error" }, [String(e)])]),
166
+ ]));
167
+ }
168
+ }
169
+
170
+ function renderFooter() {
171
+ footer.innerHTML = "";
172
+ const pages = Math.max(1, Math.ceil(total / limit));
173
+ footer.appendChild(create("button", {
174
+ type: "button", disabled: page <= 1,
175
+ onclick: function () { page -= 1; load(); },
176
+ }, ["Prev"]));
177
+ footer.appendChild(create("span", { class: "picker-page" }, [`${page} / ${pages} (${total})`]));
178
+ footer.appendChild(create("button", {
179
+ type: "button", disabled: page >= pages,
180
+ onclick: function () { page += 1; load(); },
181
+ }, ["Next"]));
182
+ if (isMulti) {
183
+ footer.appendChild(create("span", { class: "picker-count" }, [` · ${selected.size} selected`]));
184
+ footer.appendChild(create("button", {
185
+ type: "button", class: "picker-confirm",
186
+ onclick: function () {
187
+ confirmed = true;
188
+ close();
189
+ if (cfg.onConfirm) cfg.onConfirm(Array.from(selected));
190
+ },
191
+ }, ["Confirm"]));
192
+ }
193
+ }
194
+
195
+ /** @param {any} row @param {HTMLElement} [tr] */
196
+ function toggle(row, tr) {
197
+ const s = String(row._pk);
198
+ if (selected.has(s)) selected.delete(s);
199
+ else selected.add(s);
200
+ if (tr) {
201
+ tr.classList.toggle("selected", selected.has(s));
202
+ const cb = /** @type {HTMLInputElement|null} */ (tr.querySelector("input[type=checkbox]"));
203
+ if (cb) cb.checked = selected.has(s);
204
+ }
205
+ renderFooter();
206
+ }
207
+
208
+ /** @param {any} row */
209
+ function pick(row) {
210
+ confirmed = true;
211
+ close();
212
+ if (cfg.onSelect) cfg.onSelect(row._pk);
213
+ }
214
+
215
+ let t = 0;
216
+ search.addEventListener("input", function () {
217
+ clearTimeout(t);
218
+ t = /** @type {any} */ (setTimeout(function () {
219
+ searchTerm = search.value;
220
+ page = 1;
221
+ load();
222
+ }, 250));
223
+ });
224
+
225
+ load();
226
+ search.focus();
227
+ }
228
+
229
+ global.StudioPicker = { request: request };
230
+ })(window);
@@ -0,0 +1,105 @@
1
+ // @ts-check
2
+ /**
3
+ * Renders the result of POST /api/query/preview.
4
+ *
5
+ * Exposes window.StudioPlayground.render(result).
6
+ * Pure DOM construction — no state, no fetch. app.js orchestrates.
7
+ *
8
+ * Types: PreviewResult, PlaygroundAPI from _types.d.ts.
9
+ */
10
+
11
+ (function (/** @type {Window & { StudioPlayground?: PlaygroundAPI }} */ global) {
12
+ "use strict";
13
+
14
+ /**
15
+ * @template {keyof HTMLElementTagNameMap} K
16
+ * @param {K} tag
17
+ * @param {Record<string, any>} props
18
+ * @param {Array<Node|string>} [children]
19
+ * @returns {HTMLElementTagNameMap[K]}
20
+ */
21
+ function create(tag, props, children) {
22
+ /** @type {any} */
23
+ const el = document.createElement(tag);
24
+ for (const k of Object.keys(props || {})) {
25
+ const v = props[k];
26
+ if (v === undefined) continue;
27
+ if (k === "class") el.className = v;
28
+ else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
29
+ else if (k in el) el[k] = v;
30
+ else el.setAttribute(k, String(v));
31
+ }
32
+ for (const c of children || []) {
33
+ el.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
34
+ }
35
+ return el;
36
+ }
37
+
38
+ /** @param {string} text */
39
+ function copyToClipboard(text) {
40
+ if (!navigator.clipboard) return Promise.reject(new Error("clipboard unavailable"));
41
+ return navigator.clipboard.writeText(text);
42
+ }
43
+
44
+ /** @param {string} msg @param {"success"|"error"} kind */
45
+ function toast(msg, kind) {
46
+ const T = /** @type {any} */ (/** @type {any} */ (global).StudioToasts);
47
+ if (T) T.show(msg, kind);
48
+ }
49
+
50
+ /**
51
+ * @param {PreviewResult | null} result
52
+ * @returns {HTMLElement}
53
+ */
54
+ function render(result) {
55
+ const root = create("div", { class: "playground-result" });
56
+ if (!result) {
57
+ root.appendChild(create("p", { class: "mut" }, ["Run a preview to see results."]));
58
+ return root;
59
+ }
60
+
61
+ // Python code section
62
+ const codeSection = create("section", { class: "playground-section" });
63
+ const codeHeader = create("div", { class: "playground-section-header" });
64
+ codeHeader.appendChild(create("h4", {}, ["Python"]));
65
+ const codeCopy = create("button", {
66
+ type: "button", class: "playground-copy",
67
+ }, ["Copy"]);
68
+ codeCopy.addEventListener("click", function () {
69
+ copyToClipboard(result.code || "").then(
70
+ function () { toast("Copied Python", "success"); },
71
+ function () { toast("Copy failed", "error"); }
72
+ );
73
+ });
74
+ codeHeader.appendChild(codeCopy);
75
+ codeSection.appendChild(codeHeader);
76
+ codeSection.appendChild(create("pre", { class: "playground-code" }, [result.code || ""]));
77
+ root.appendChild(codeSection);
78
+
79
+ // SQL section
80
+ const sqlSection = create("section", { class: "playground-section" });
81
+ const sqlHeader = create("div", { class: "playground-section-header" });
82
+ sqlHeader.appendChild(create("h4", {}, ["SQL"]));
83
+ if (result.sql) {
84
+ const sqlCopy = create("button", {
85
+ type: "button", class: "playground-copy",
86
+ }, ["Copy"]);
87
+ sqlCopy.addEventListener("click", function () {
88
+ copyToClipboard(result.sql || "").then(
89
+ function () { toast("Copied SQL", "success"); },
90
+ function () { toast("Copy failed", "error"); }
91
+ );
92
+ });
93
+ sqlHeader.appendChild(sqlCopy);
94
+ }
95
+ sqlSection.appendChild(sqlHeader);
96
+ sqlSection.appendChild(create("pre", { class: "playground-sql" }, [
97
+ result.sql || "(SQL preview not available for this dialect)",
98
+ ]));
99
+ root.appendChild(sqlSection);
100
+
101
+ return root;
102
+ }
103
+
104
+ global.StudioPlayground = { render: render };
105
+ })(window);
@@ -0,0 +1,84 @@
1
+ // @ts-check
2
+ /**
3
+ * Playground query history for v0.5.0 (UI program D).
4
+ *
5
+ * A small, pure wrapper over a Storage-like object. Only query *shape* is
6
+ * stored (model, filters, search, sort, limit, timestamp) — never row data.
7
+ * Storage failures (disabled/quota) degrade to an in-memory list so the UI
8
+ * never breaks. Testable in `node --test` with a fake storage.
9
+ *
10
+ * Types: QueryHistoryAPI in _types.d.ts.
11
+ */
12
+ (function (/** @type {any} */ global) {
13
+ "use strict";
14
+
15
+ var KEY = "studio.query-history.v1";
16
+ var MAX = 20;
17
+
18
+ /**
19
+ * @param {{ getItem(k: string): string|null, setItem(k: string, v: string): void }|null} [storage]
20
+ * @returns {QueryHistoryAPI}
21
+ */
22
+ function create(storage) {
23
+ var store = storage || null;
24
+ /** @type {any[]} */
25
+ var memory = [];
26
+
27
+ function read() {
28
+ if (!store) return memory.slice();
29
+ try {
30
+ var raw = store.getItem(KEY);
31
+ var parsed = raw ? JSON.parse(raw) : [];
32
+ return Array.isArray(parsed) ? parsed : [];
33
+ } catch (e) { return memory.slice(); }
34
+ }
35
+
36
+ /** @param {any[]} list */
37
+ function write(list) {
38
+ memory = list.slice();
39
+ if (!store) return;
40
+ try { store.setItem(KEY, JSON.stringify(list)); }
41
+ catch (e) { /* storage disabled: keep the in-memory copy */ }
42
+ }
43
+
44
+ /** @returns {any[]} newest first */
45
+ function list() { return read(); }
46
+
47
+ /**
48
+ * @param {{ model: string, filters?: any, search?: string, sort?: string, limit?: any }} spec
49
+ * @returns {any[]}
50
+ */
51
+ function add(spec) {
52
+ var entry = {
53
+ model: String(spec.model || ""),
54
+ filters: spec.filters === undefined ? [] : spec.filters,
55
+ search: spec.search || "",
56
+ sort: spec.sort || "",
57
+ limit: spec.limit,
58
+ at: Date.now(),
59
+ };
60
+ var all = read();
61
+ // Drop an older duplicate with the same query shape.
62
+ all = all.filter(function (/** @type {any} */ e) {
63
+ return !(
64
+ e.model === entry.model &&
65
+ JSON.stringify(e.filters) === JSON.stringify(entry.filters) &&
66
+ (e.search || "") === entry.search &&
67
+ (e.sort || "") === entry.sort &&
68
+ e.limit === entry.limit
69
+ );
70
+ });
71
+ all.unshift(entry);
72
+ if (all.length > MAX) all = all.slice(0, MAX);
73
+ write(all);
74
+ return all;
75
+ }
76
+
77
+ /** @returns {any[]} */
78
+ function clear() { write([]); return []; }
79
+
80
+ return { list: list, add: add, clear: clear, KEY: KEY, MAX: MAX };
81
+ }
82
+
83
+ global.StudioQueryHistory = { create: create };
84
+ })(typeof window !== "undefined" ? window : globalThis);
@@ -0,0 +1,145 @@
1
+ // @ts-check
2
+ /**
3
+ * Pure keyboard-shortcut matching and fuzzy command-palette search (v0.3.3).
4
+ *
5
+ * No DOM: `match()` takes a plain keydown-like object, `ignoreTyping()`
6
+ * implements the "do not steal keys from inputs" rule, and `search()` is a
7
+ * small deterministic fuzzy scorer. The DOM wiring lives in app.js/palette.js.
8
+ */
9
+ (function (/** @type {any} */ global) {
10
+ "use strict";
11
+
12
+ /**
13
+ * Keys that mean "the user is typing". Shortcuts must be ignored there.
14
+ * @param {any} target
15
+ * @returns {boolean}
16
+ */
17
+ function ignoreTyping(target) {
18
+ if (!target) return false;
19
+ var tag = String(target.tagName || "").toLowerCase();
20
+ if (tag === "input" || tag === "textarea" || tag === "select") return true;
21
+ return target.isContentEditable === true;
22
+ }
23
+
24
+ /**
25
+ * Normalise a keydown event into a comparable shortcut string.
26
+ * Modifiers are ordered consistently: ctrl+meta+alt+shift+key.
27
+ * @param {{ key?: string, code?: string, ctrlKey?: boolean, metaKey?: boolean,
28
+ * altKey?: boolean, shiftKey?: boolean }} ev
29
+ * @returns {string}
30
+ */
31
+ function normalise(ev) {
32
+ var parts = [];
33
+ if (ev.ctrlKey) parts.push("ctrl");
34
+ if (ev.metaKey) parts.push("meta");
35
+ if (ev.altKey) parts.push("alt");
36
+ var key = ev.key || ev.code || "";
37
+ // Shift is implied by a printable character: '?' needs Shift on most
38
+ // layouts, and 'J' should still trigger the 'j' shortcut. Keeping Shift
39
+ // here would make both unusable, so only record it for named keys.
40
+ if (!(key.length === 1) && ev.shiftKey) parts.push("shift");
41
+ parts.push(key.toLowerCase());
42
+ return parts.join("+");
43
+ }
44
+
45
+ /**
46
+ * A two-key chord like "g m" is tracked as a pending prefix. This helper
47
+ * returns the prefix a key could start, or null.
48
+ * @param {string} combo
49
+ * @returns {string | null}
50
+ */
51
+ function chordPrefix(combo) {
52
+ var parts = combo.split("+");
53
+ if (parts.length === 1 && parts[0].length === 1 && /[a-z]/.test(parts[0])) return parts[0];
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * Match a keydown against a table of shortcuts. Each entry is
59
+ * `{ keys: string[], action: string }`. Two-key chords are expressed as
60
+ * `"g m"` and tracked by passing `pending` (the previous lone key).
61
+ * @param {{ key?: string, code?: string, ctrlKey?: boolean, metaKey?: boolean,
62
+ * altKey?: boolean, shiftKey?: boolean }} ev
63
+ * @param {Array<{ keys: string[], action: string }>} table
64
+ * @param {string | null} [pending]
65
+ * @returns {{ action: string | null, pending: string | null }}
66
+ */
67
+ function match(ev, table, pending) {
68
+ var combo = normalise(ev);
69
+ // Exact single-chord shortcuts win first.
70
+ for (var entry of table) {
71
+ for (var keys of entry.keys) {
72
+ if (keys !== combo && !(pending && keys === pending + " " + combo)) continue;
73
+ return { action: entry.action, pending: null };
74
+ }
75
+ }
76
+ // Otherwise, remember a lone letter that starts a chord ("g m", "?").
77
+ var prefix = chordPrefix(combo);
78
+ var startsChord = table.some(function (/** @type {any} */ e) {
79
+ return e.keys.some(function (/** @type {string} */ k) { return k.startsWith(prefix + " "); });
80
+ });
81
+ return { action: null, pending: prefix && startsChord ? prefix : null };
82
+ }
83
+
84
+ /**
85
+ * Subsequence fuzzy score. Returns -1 when `query` is not a subsequence of
86
+ * `text`. Higher is better; consecutive and word-start matches score more.
87
+ * @param {string} text
88
+ * @param {string} query
89
+ * @returns {number}
90
+ */
91
+ function score(text, query) {
92
+ var t = text.toLowerCase();
93
+ var q = query.toLowerCase().trim();
94
+ if (!q) return 0;
95
+ var total = 0, pos = 0, streak = 0;
96
+ for (var i = 0; i < q.length; i++) {
97
+ var ch = q[i];
98
+ var found = t.indexOf(ch, pos);
99
+ if (found < 0) return -1;
100
+ if (found === pos && i > 0) { streak += 1; total += 4 + streak * 2; }
101
+ else { streak = 0; total += 1; }
102
+ if (found === 0 || /[\s._/-]/.test(t[found - 1] || "")) total += 6;
103
+ pos = found + 1;
104
+ }
105
+ return total - t.length * 0.01; // prefer shorter targets
106
+ }
107
+
108
+ /**
109
+ * Fuzzy-search a list of commands; returns the best matches in order.
110
+ * @template {{ title: string }} T
111
+ * @param {T[]} items
112
+ * @param {string} query
113
+ * @param {number} [limit]
114
+ * @returns {T[]}
115
+ */
116
+ function search(items, query, limit) {
117
+ var ranked = items.map(function (/** @type {any} */ item) {
118
+ return { item: item, s: score(item.title, query) };
119
+ }).filter(function (/** @type {any} */ r) { return r.s >= 0; });
120
+ ranked.sort(function (/** @type {any} */ a, /** @type {any} */ b) { return b.s - a.s; });
121
+ return ranked.slice(0, limit || 20).map(function (/** @type {any} */ r) { return r.item; });
122
+ }
123
+
124
+ /**
125
+ * The default shortcut table (program B). Each action is handled by app.js.
126
+ * @returns {Array<{ keys: string[], action: string }>}
127
+ */
128
+ function defaults() {
129
+ return [
130
+ { keys: ["ctrl+k", "meta+k"], action: "palette" },
131
+ { keys: ["/"], action: "search" },
132
+ { keys: ["j"], action: "down" },
133
+ { keys: ["k"], action: "up" },
134
+ { keys: ["enter"], action: "open" },
135
+ { keys: ["escape"], action: "close" },
136
+ { keys: ["g m"], action: "models" },
137
+ { keys: ["?"], action: "help" },
138
+ ];
139
+ }
140
+
141
+ global.StudioShortcuts = {
142
+ ignoreTyping: ignoreTyping, normalise: normalise, chordPrefix: chordPrefix,
143
+ match: match, score: score, search: search, defaults: defaults,
144
+ };
145
+ })(typeof window !== "undefined" ? window : globalThis);
@@ -0,0 +1,112 @@
1
+ // @ts-check
2
+ /**
3
+ * Shareable view state in the URL hash (program B, v0.3.3).
4
+ *
5
+ * Plain `#key=value&...` pairs — no JSON, no secrets, no row data. Pure
6
+ * encode/decode functions tested without a DOM; the DOM wiring (reading
7
+ * location.hash and listening to hashchange) lives in app.js.
8
+ */
9
+ (function (/** @type {any} */ global) {
10
+ "use strict";
11
+
12
+ /** Keys that may appear in the hash, in a stable order. */
13
+ var KEYS = ["m", "v", "f", "s", "p", "c", "q", "cn"];
14
+
15
+ /**
16
+ * @param {any} state
17
+ * @returns {string} a hash WITHOUT the leading '#'
18
+ */
19
+ function encode(state) {
20
+ var pairs = [];
21
+ for (var key of KEYS) {
22
+ var value = state && state[key];
23
+ if (value === undefined || value === null || value === "") continue;
24
+ if (Array.isArray(value) && value.length === 0) continue;
25
+ pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(String(value)));
26
+ }
27
+ return pairs.join("&");
28
+ }
29
+
30
+ /**
31
+ * @param {string} hash with or without a leading '#'
32
+ * @returns {Record<string, string>}
33
+ */
34
+ function decode(hash) {
35
+ /** @type {Record<string, string>} */
36
+ var out = {};
37
+ var raw = String(hash || "").replace(/^#/, "");
38
+ if (!raw) return out;
39
+ for (var pair of raw.split("&")) {
40
+ var i = pair.indexOf("=");
41
+ if (i <= 0) continue;
42
+ var key = decodeURIComponent(pair.slice(0, i));
43
+ if (KEYS.indexOf(key) < 0) continue; // unknown keys are dropped
44
+ try {
45
+ out[key] = decodeURIComponent(pair.slice(i + 1));
46
+ } catch (e) {
47
+ // Malformed percent-encoding: ignore just that pair.
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /**
54
+ * Merge a decoded hash into a state object, coercing numeric fields.
55
+ * @param {string} hash
56
+ * @param {any} base
57
+ * @returns {any}
58
+ */
59
+ function apply(hash, base) {
60
+ var parts = decode(hash);
61
+ /** @type {any} */
62
+ var out = {};
63
+ for (var k of Object.keys(base || {})) out[k] = base[k];
64
+ if (parts.m !== undefined) out.model = parts.m;
65
+ if (parts.v !== undefined) out.view = parts.v;
66
+ if (parts.q !== undefined) out.search = parts.q;
67
+ if (parts.cn !== undefined) out.connection = parts.cn;
68
+ if (parts.c !== undefined) out.cols = parts.c.split(",").filter(Boolean);
69
+ if (parts.s !== undefined) out.sort = parts.s;
70
+ if (parts.f !== undefined) {
71
+ // Filters are stored as `field:op:value` triples; values are kept as
72
+ // strings and go through the same whitelist as manual filters.
73
+ out.filters = parts.f.split("~").map(function (/** @type {string} */ triple) {
74
+ var bits = triple.split(":");
75
+ return { field: bits[0] || "", op: bits[1] || "eq", value: bits.slice(2).join(":") };
76
+ }).filter(function (/** @type {any} */ f) { return !!f.field; });
77
+ }
78
+ if (parts.p !== undefined) {
79
+ var n = Number(parts.p);
80
+ out.page = Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /**
86
+ * Build the state that should go into the hash (whitelisted only).
87
+ * @param {any} state
88
+ * @returns {any}
89
+ */
90
+ function fromState(state) {
91
+ /** @type {any} */
92
+ var out = {};
93
+ if (!state) return out;
94
+ if (state.model) out.m = state.model;
95
+ if (state.view) out.v = state.view;
96
+ if (state.search) out.q = state.search;
97
+ if (state.connection) out.cn = state.connection;
98
+ if (Array.isArray(state.cols) && state.cols.length) out.c = state.cols.join(",");
99
+ if (state.sort) out.s = state.sort;
100
+ if (Array.isArray(state.filters) && state.filters.length) {
101
+ out.f = state.filters.map(function (/** @type {any} */ f) {
102
+ return [f.field, f.op, String(f.value === undefined ? "" : f.value)].join(":");
103
+ }).join("~");
104
+ }
105
+ if (state.page && state.page > 1) out.p = state.page;
106
+ return out;
107
+ }
108
+
109
+ global.StudioStateHash = {
110
+ KEYS: KEYS, encode: encode, decode: decode, apply: apply, fromState: fromState,
111
+ };
112
+ })(typeof window !== "undefined" ? window : globalThis);