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,1443 @@
1
+ // @ts-check
2
+ /**
3
+ * Alpine component for tortoise-orm-studio.
4
+ * CSP-safe: no eval, no inline handlers, all logic lives here.
5
+ *
6
+ * Runtime globals (loaded before this file):
7
+ * window.StudioWidgets, window.StudioFilters, window.StudioPicker, window.StudioToasts
8
+ * Types from _types.d.ts.
9
+ */
10
+
11
+ document.addEventListener("alpine:init", () => {
12
+ const base = location.pathname.replace(/\/?$/, "/");
13
+ const enc = encodeURIComponent;
14
+ /** @type {any} */
15
+ const Alpine = /** @type {any} */ (window).Alpine;
16
+
17
+ /**
18
+ * The whole UI state machine. Typed by `StudioComponent` in _types.d.ts so
19
+ * every template property name is checked in exactly one place.
20
+ * @returns {StudioComponent}
21
+ */
22
+ Alpine.data("studio", () => ({
23
+ /** @type {Schema|null} */ schema: null,
24
+ /** @type {ModelDesc[]} */ models: [],
25
+ current: "", view: "list",
26
+ /** @type {any[]} */ rows: [],
27
+ total: 0, page: 1, limit: 25, sort: "", search: "",
28
+ /** @type {string[]} */ cols: [],
29
+ /** @type {string[]} */ allCols: [],
30
+ /** @type {Record<string,boolean>} */ hiddenCols: {},
31
+ pk: /** @type {string|number|null} */ (null),
32
+ json: "",
33
+ /** @type {Relation[]} */ relations: [],
34
+ /** @type {any[]} */ relRows: [],
35
+ /** @type {string[]} */ relCols: [],
36
+ relModel: "", relName: "", relType: "", hasRel: false,
37
+
38
+ formMode: "widgets",
39
+ /** @type {Record<string,any>} */ formValues: {},
40
+ /** @type {Field[]} */ formFields: [],
41
+
42
+ /** @type {FilterPredicate[]} */ filters: [],
43
+ draftField: "", draftOp: "eq", draftValue: "", draftError: "",
44
+ showAddFilter: false,
45
+
46
+ // v0.2.3
47
+ connection: "",
48
+ /** @type {string[]} */ connections: [],
49
+ /** @type {Record<string,true>} */ selectedPks: {},
50
+
51
+ // v0.3.0 panels
52
+ playgroundModel: "",
53
+ playgroundFilters: "[]",
54
+ playgroundSearch: "",
55
+ playgroundSort: "",
56
+ playgroundLimit: 50,
57
+ playgroundError: "",
58
+ playgroundMs: 0,
59
+ /** @type {any[]} recent playground queries (shape only) */
60
+ playgroundHistory: [],
61
+ queryHistoryOpen: false,
62
+
63
+ // v0.3.1 — audit panel
64
+ auditPage: 1,
65
+ auditLimit: 50,
66
+ auditFilters: /** @type {{action:string,model:string,actor:string}} */ ({ action: "", model: "", actor: "" }),
67
+
68
+ // v0.3.1 — theme (light | dark | system); painted by theme-init.js pre-paint
69
+ /** @type {ThemeChoice} */
70
+ themeChoice: "system",
71
+ /** @type {ThemeChoice[]} */
72
+ themeChoices: ["light", "dark", "system"],
73
+
74
+ // v0.3.1 — saved views
75
+ viewsOpen: false,
76
+ savedViews: /** @type {SavedViews} */ ({}),
77
+
78
+ // v0.3.3 — navigation: sidebar, tabs, palette, shortcuts, shareable state
79
+ sideFilter: "",
80
+ sidebarCollapsed: false,
81
+ /** @type {string[]} */
82
+ pinnedModels: [],
83
+ /** @type {TabStore} */
84
+ tabStore: { tabs: [], activeId: null, split: false, cap: 12, error: null },
85
+ paletteOpen: false,
86
+ /** @type {HTMLElement|null} element focused before the palette opened */
87
+ paletteReturnFocus: null,
88
+ helpOpen: false,
89
+ // v0.5.0 — staged saves (nothing is written until "Save all")
90
+ /** @type {PendingStore} */
91
+ pendingStore: { changes: [], seq: 0 },
92
+ pendingOpen: false,
93
+ // v0.5.0 — optional AI filter (hidden entirely when the hook is unset)
94
+ /** @type {any[]} */
95
+ aiFilters: [],
96
+ aiText: "",
97
+ aiError: "",
98
+ aiOpen: false,
99
+ // v0.5.0 — detail drawer + inline cell edit (program D)
100
+ /** @type {Record<string,any>} snapshot of the row when the drawer opened */
101
+ drawerSnapshot: {},
102
+ /** @type {HTMLElement|null} element focused before the drawer opened */
103
+ drawerReturnFocus: null,
104
+ /** @type {{active:any,last:any}} inline edit session */
105
+ inline: { active: null, last: null },
106
+ /** @type {string|null} pk whose Copy-as menu is open */
107
+ copyMenuPk: null,
108
+ /** JSON tree visible in the detail drawer */
109
+ jsonTreeOpen: false,
110
+ /** @type {Array<{label:string,key:string}>} */
111
+ breadcrumbs: [],
112
+ lastRequestMs: 0,
113
+ pendingShortcut: /** @type {string | null} */ (null),
114
+ dense: false,
115
+ // v0.9.0 — declarative plugin actions (no plugin-owned JS in the page)
116
+ pluginTitle: "Plugins",
117
+ pluginText: "",
118
+ pluginError: "",
119
+ // v0.9.0 — locale, switchable at runtime without a reload
120
+ locale: "en",
121
+
122
+ // ---- derived
123
+ get isList() { return this.view === "list"; },
124
+ get isDetail() { return this.view === "detail"; },
125
+ get readOnly() { return !this.schema || this.schema.read_only; },
126
+ get canWrite() { return !this.readOnly; },
127
+ get canDelete() { return !this.readOnly && this.pk !== null; },
128
+ get canM2m() { return !this.readOnly && this.relType === "m2m"; },
129
+ get isPlayground() { return this.view === "playground"; },
130
+ get isEr() { return this.view === "er"; },
131
+ get isMigrations() { return this.view === "migrations"; },
132
+ get isAudit() { return this.view === "audit"; },
133
+ get isPlugin() { return this.view === "plugin"; },
134
+ /** Flatten ``schema.plugins[*].actions`` into safe, labelled GET buttons. */
135
+ get pluginActions() {
136
+ /** @type {Array<{key:string,plugin:string,id:string,label:string,path:string,description:string}>} */
137
+ const out = [];
138
+ const all = (this.schema && this.schema.plugins) || {};
139
+ Object.keys(all).forEach((name) => {
140
+ const info = all[name];
141
+ (info.actions || []).forEach((/** @type {PluginAction} */ a) => {
142
+ out.push({ key: name + ":" + a.id, plugin: name, id: a.id,
143
+ label: a.label, path: a.path, description: a.description || "" });
144
+ });
145
+ });
146
+ return out;
147
+ },
148
+ get hasSavedViews() { return Object.keys(this.savedViews).length > 0; },
149
+ get savedViewNames() { return Object.keys(this.savedViews).sort(); },
150
+ get localeChoices() {
151
+ const I = /** @type {I18nAPI|undefined} */ (/** @type {any} */ (window).StudioI18n);
152
+ return I ? I.available() : ["en"];
153
+ },
154
+ get atFirst() { return this.page <= 1; },
155
+ get atLast() { return this.page >= this.pages; },
156
+ get pages() { return Math.max(1, Math.ceil(this.total / this.limit)); },
157
+ get pageLabel() { return this.page + " / " + this.pages; },
158
+ get countLabel() { return this.tr("list.rows", { count: this.total }); },
159
+ get showWidgets() { return this.formMode === "widgets"; },
160
+ get showJson() { return this.formMode === "json"; },
161
+ get formModeLabel() { return this.tr(this.formMode === "widgets" ? "detail.formMode.json" : "detail.formMode.form"); },
162
+ get hasFilters() { return this.filters.length > 0; },
163
+ get draftNeedsValue() { return this.draftOp !== "isnull"; },
164
+ get showConnection() { return this.connections.length > 1; },
165
+ get selectedCount() { return Object.keys(this.selectedPks).length; },
166
+ get hasSelection() { return this.selectedCount > 0; },
167
+ get allVisibleSelected() {
168
+ return this.rows.length > 0 && this.rows.every((r) => !!this.selectedPks[String(r._pk)]);
169
+ },
170
+ get maxBulk() {
171
+ return (this.schema && this.schema.limits && this.schema.limits.max_bulk) || 500;
172
+ },
173
+
174
+ // ---- v0.3.3 derived
175
+ get tabList() { return this.tabStore.tabs; },
176
+ get activeTabId() { return this.tabStore.activeId; },
177
+ get tabSplit() { return this.tabStore.split; },
178
+ get tabError() { return this.tabStore.error || ""; },
179
+ get pendingDirty() {
180
+ const P = /** @type {PendingAPI|undefined} */ (/** @type {any} */ (window).StudioPending);
181
+ return P ? P.isDirty(this.pendingStore) : this.pendingStore.changes.length > 0;
182
+ },
183
+ get pendingCount() { return this.pendingStore.changes.length; },
184
+ get aiEnabled() {
185
+ const A = /** @type {any} */ (window).StudioAI;
186
+ return A ? A.isEnabled(this.schema) : false;
187
+ },
188
+ /** True when the drawer form differs from the snapshot taken on open. */
189
+ get drawerDirty() {
190
+ return JSON.stringify(this.formValues) !== JSON.stringify(this.drawerSnapshot);
191
+ },
192
+ /** Field-level diff of the drawer form against its snapshot. */
193
+ get drawerDiff() {
194
+ const P = this.pending();
195
+ if (!P) return [];
196
+ return P.diff(/** @type {any} */ ({ op: "update", data: this.formValues, before: this.drawerSnapshot }));
197
+ },
198
+ get inlineEditing() {
199
+ const IE = this.ie();
200
+ return IE ? IE.isEditing(this.inline) : !!this.inline.active;
201
+ },
202
+ get groupedApps() {
203
+ /** @type {string[]} */
204
+ const apps = [];
205
+ for (const m of this.models) if (!apps.includes(m.app)) apps.push(m.app);
206
+ return apps;
207
+ },
208
+ get filterSummary() {
209
+ if (!this.filters.length) return this.search ? this.tr("search: {q}", { q: this.search }) : this.tr("no filters");
210
+ return this.filters.map((f) => f.field + " " + f.op).join(", ");
211
+ },
212
+ get lastRequestLabel() { return this.lastRequestMs ? this.lastRequestMs + " ms" : "—"; },
213
+ get playgroundLabel() { return this.playgroundMs ? this.playgroundMs + " ms" : "—"; },
214
+
215
+ get filterableFields() {
216
+ const m = this.model(this.current);
217
+ if (!m) return [];
218
+ const direct = m.fields.slice();
219
+ /** @type {Field[]} */
220
+ const traversals = [];
221
+ const paths = m.filter_paths || {};
222
+ for (const path of Object.keys(paths)) {
223
+ const info = paths[path];
224
+ if (info.traversal) {
225
+ traversals.push({
226
+ name: path, kind: info.kind, pk: false, null: true, readonly: false,
227
+ });
228
+ }
229
+ }
230
+ return direct.concat(traversals);
231
+ },
232
+ get draftFieldObj() {
233
+ return this.filterableFields.find((f) => f.name === this.draftField) || null;
234
+ },
235
+ get draftOps() {
236
+ const f = this.draftFieldObj;
237
+ if (!f) return [];
238
+ const SF = /** @type {FiltersAPI} */ (/** @type {any} */ (window).StudioFilters);
239
+ return SF ? SF.opsForField(f) : [];
240
+ },
241
+
242
+ // ---- api helper (this.connection aware)
243
+ /** @type {StudioComponent["api"]} */
244
+ /** @type {StudioComponent["api"]} */
245
+ async api(path, method, body) {
246
+ let fullPath = path;
247
+ if (this.connection) {
248
+ const sep = path.indexOf("?") >= 0 ? "&" : "?";
249
+ fullPath = path + sep + "connection=" + enc(this.connection);
250
+ }
251
+ /** @type {Record<string,string>} */
252
+ const headers = { "x-requested-with": "studio" };
253
+ if (body !== undefined) headers["content-type"] = "application/json";
254
+ // v0.4.0: /api/v1 is the stable public prefix; /api remains a
255
+ // deprecated server-side alias for older clients.
256
+ const res = await fetch(base + "api/v1/" + fullPath, {
257
+ method: method || "GET", headers,
258
+ body: body === undefined ? undefined : JSON.stringify(body),
259
+ });
260
+ const data = await res.json().catch(() => ({}));
261
+ if (!res.ok) throw new Error((data.error && data.error.message) || res.statusText);
262
+ return data;
263
+ },
264
+
265
+ // ---- guards / toasts
266
+ /** @param {() => Promise<void>|void} fn */
267
+ async guard(fn) {
268
+ try { await fn(); }
269
+ catch (e) {
270
+ const msg = e instanceof Error ? e.message : String(e);
271
+ /** @type {ToastsAPI} */ (/** @type {any} */ (window).StudioToasts).error(msg);
272
+ }
273
+ },
274
+ /** @param {string} m */
275
+ toastError(m) { /** @type {ToastsAPI} */ (/** @type {any} */ (window).StudioToasts).error(m); },
276
+ /** @param {string} m */
277
+ toastSuccess(m) { /** @type {ToastsAPI} */ (/** @type {any} */ (window).StudioToasts).success(m); },
278
+
279
+ // ---- v0.3.3 navigation
280
+ /** @param {string} key */
281
+ openModelTab(key) {
282
+ this.newTabWith({ view: "list", model: key });
283
+ },
284
+ /** @param {any} state */
285
+ newTabWith(state) {
286
+ const T = /** @type {any} */ (window).StudioTabs;
287
+ if (!T) return;
288
+ const r = T.add(this.tabStore, state);
289
+ this.tabStore = r.store;
290
+ if (r.error) this.toastError(r.error);
291
+ },
292
+ newTab() {
293
+ this.newTabWith({ view: "list", model: this.current || (this.models[0] || {}).key || "" });
294
+ },
295
+ /** @param {string} id */
296
+ activateTab(id) {
297
+ const T = /** @type {any} */ (window).StudioTabs;
298
+ if (!T) return;
299
+ this.tabStore = T.activate(this.tabStore, id);
300
+ const tab = this.tabStore.tabs.find((/** @type {Tab} */ t) => t.id === id);
301
+ if (tab && tab.state && tab.state.model) void this.pick(tab.state.model);
302
+ },
303
+ /** @param {string} id */
304
+ closeTab(id) {
305
+ const T = /** @type {any} */ (window).StudioTabs;
306
+ if (!T) return;
307
+ const tab = this.tabStore.tabs.find((/** @type {Tab} */ t) => t.id === id);
308
+ if (tab && tab.dirty && !this.confirm(this.tr("This tab has unsaved changes. Close it anyway?"))) return;
309
+ const r = T.close(this.tabStore, id);
310
+ this.tabStore = r.store;
311
+ if (r.error) this.toastError(r.error);
312
+ },
313
+ toggleSplit() {
314
+ const T = /** @type {any} */ (window).StudioTabs;
315
+ if (T) this.tabStore = T.setSplit(this.tabStore, !this.tabStore.split);
316
+ },
317
+ /** @param {string} app @returns {ModelDesc[]} */
318
+ modelsForApp(app) {
319
+ const q = this.sideFilter.toLowerCase().trim();
320
+ return this.models.filter((m) => m.app === app && (!q || m.key.toLowerCase().includes(q)));
321
+ },
322
+ toggleSidebar() { this.sidebarCollapsed = !this.sidebarCollapsed; },
323
+ /** @param {string} key */
324
+ isPinned(key) { return this.pinnedModels.includes(key); },
325
+ /** @param {string} key */
326
+ togglePinModel(key) {
327
+ this.pinnedModels = this.isPinned(key)
328
+ ? this.pinnedModels.filter((k) => k !== key)
329
+ : this.pinnedModels.concat([key]);
330
+ try {
331
+ const S = /** @type {any} */ (window).sessionStorage;
332
+ if (S) S.setItem("studio.pins.v1", JSON.stringify(this.pinnedModels));
333
+ } catch (e) { /* storage disabled: pins are session-only */ }
334
+ },
335
+ togglePalette() {
336
+ const A = this.a11y();
337
+ if (!this.paletteOpen && A) this.paletteReturnFocus = A.saveFocus();
338
+ this.paletteOpen = !this.paletteOpen;
339
+ this.helpOpen = false;
340
+ if (this.paletteOpen) this.renderPalette();
341
+ else if (A && this.paletteReturnFocus) {
342
+ A.restoreFocus(this.paletteReturnFocus);
343
+ this.paletteReturnFocus = null;
344
+ }
345
+ },
346
+ renderPalette() {
347
+ const P = /** @type {any} */ (window).StudioPalette;
348
+ const body = /** @type {any} */ (this).$refs && /** @type {any} */ (this).$refs.paletteBody;
349
+ if (!P || !body) return;
350
+ body.replaceChildren();
351
+ const el = P.render(P.commands(this.schema, { hasSavedViews: this.hasSavedViews }), {
352
+ onRun: (/** @type {PaletteCommand} */ c) => {
353
+ this.closePalette();
354
+ switch (c.action) {
355
+ case "open_model": void this.pick(c.arg || ""); break;
356
+ case "new_row": this.newRow(); break;
357
+ case "open_playground": void this.openPlayground(); break;
358
+ case "open_er": void this.openEr(); break;
359
+ case "open_migrations": void this.openMigrations(); break;
360
+ case "open_audit": void this.openAudit(); break;
361
+ case "toggle_theme": this.setTheme(this.themeChoice === "dark" ? "light" : "dark"); break;
362
+ case "saved_views": this.viewsOpen = true; break;
363
+ }
364
+ },
365
+ onClose: () => this.closePalette(),
366
+ });
367
+ body.appendChild(el);
368
+ // x-show flips display on Alpine's next tick; focus only sticks once
369
+ // the container is actually visible.
370
+ /** @type {any} */ (this).$nextTick(() => {
371
+ const input = el.querySelector(".palette-input");
372
+ if (input) input.focus();
373
+ });
374
+ },
375
+ closePalette() {
376
+ this.paletteOpen = false;
377
+ const A = this.a11y();
378
+ if (A && this.paletteReturnFocus) {
379
+ A.restoreFocus(this.paletteReturnFocus);
380
+ this.paletteReturnFocus = null;
381
+ }
382
+ },
383
+ /** @param {KeyboardEvent} ev Tab trap inside the palette dialog. */
384
+ onPaletteKeydown(ev) {
385
+ if (ev.key !== "Tab") return;
386
+ const A = this.a11y();
387
+ const root = /** @type {any} */ (this).$refs && /** @type {any} */ (this).$refs.paletteBody;
388
+ if (A && root && A.trapFocus(root, ev)) ev.preventDefault();
389
+ },
390
+ toggleHelp() { this.helpOpen = !this.helpOpen; this.paletteOpen = false; },
391
+ /** @param {number} i */
392
+ goCrumb(i) {
393
+ const b = this.breadcrumbs[i];
394
+ if (!b) return;
395
+ this.breadcrumbs = this.breadcrumbs.slice(0, i + 1);
396
+ if (b.key) void this.pick(b.key); else void this.viewList();
397
+ },
398
+ /** Global keydown handler (wired in init). @param {KeyboardEvent} ev */
399
+ onKeydown(ev) {
400
+ const Sh = /** @type {any} */ (window).StudioShortcuts;
401
+ if (!Sh) return;
402
+ if (Sh.ignoreTyping(ev.target)) {
403
+ if (ev.key === "Escape" && ev.target && /** @type {any} */ (ev.target).blur) {
404
+ /** @type {any} */ (ev.target).blur();
405
+ }
406
+ return;
407
+ }
408
+ const r = Sh.match(ev, Sh.defaults(), this.pendingShortcut);
409
+ this.pendingShortcut = r.pending;
410
+ if (!r.action) return;
411
+ switch (r.action) {
412
+ case "palette": this.togglePalette(); break;
413
+ case "search": { const el = /** @type {HTMLElement | null} */ (document.querySelector(".bar input")); if (el) el.focus(); break; }
414
+ case "down": this.moveSelection(1); break;
415
+ case "up": this.moveSelection(-1); break;
416
+ case "open": {
417
+ const pk = Object.keys(this.selectedPks)[0];
418
+ const row = this.rows.find((x) => String(x._pk) === pk);
419
+ if (row) void this.openRow(row);
420
+ break;
421
+ }
422
+ case "close": if (this.paletteOpen) this.closePalette(); else if (this.helpOpen) this.helpOpen = false; else void this.back(); break;
423
+ case "models": this.sideFilter = ""; this.sidebarCollapsed = false; break;
424
+ case "help": this.toggleHelp(); break;
425
+ }
426
+ },
427
+ /** @param {number} delta */
428
+ moveSelection(delta) {
429
+ if (!this.rows.length) return;
430
+ const keys = this.rows.map((r) => String(r._pk));
431
+ const current = keys.findIndex((k) => !!this.selectedPks[k]);
432
+ const next = Math.max(0, Math.min(keys.length - 1, (current < 0 ? (delta > 0 ? 0 : keys.length - 1) : current + delta)));
433
+ this.selectedPks = { [keys[next]]: true };
434
+ },
435
+
436
+ // ---- browser dialogs (overridable in tests, never blocked by CSP)
437
+ /** @param {string} message @returns {boolean} */
438
+ confirm(message) {
439
+ return typeof window.confirm === "function" ? window.confirm(message) : true;
440
+ },
441
+ /** @param {string} message @returns {string | null} */
442
+ prompt(message) {
443
+ return typeof window.prompt === "function" ? window.prompt(message) : null;
444
+ },
445
+
446
+ // ---- theme
447
+ get prefersDark() {
448
+ try {
449
+ return !!(window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches);
450
+ } catch (e) {
451
+ return false;
452
+ }
453
+ },
454
+ /** @param {string} choice */
455
+ setTheme(choice) {
456
+ const T = /** @type {ThemeAPI} */ (/** @type {any} */ (window).StudioTheme);
457
+ const next = T ? T.normalize(choice) : "system";
458
+ this.themeChoice = next;
459
+ if (T) {
460
+ T.save(next);
461
+ T.apply(document, next);
462
+ }
463
+ },
464
+
465
+ // ---- i18n (v0.9.0)
466
+ /** @param {string} key @param {Record<string,any>} [vars] */
467
+ tr(key, vars) {
468
+ const I = /** @type {I18nAPI|undefined} */ (/** @type {any} */ (window).StudioI18n);
469
+ return I ? I.t(key, vars) : key;
470
+ },
471
+ /** @param {string} value */
472
+ setLocale(value) {
473
+ const I = /** @type {I18nAPI|undefined} */ (/** @type {any} */ (window).StudioI18n);
474
+ if (!I || !I.save(value)) return;
475
+ this.locale = I.locale();
476
+ I.apply(document);
477
+ this.pluginTitle = this.tr("nav.plugins");
478
+ },
479
+
480
+ // ---- helpers
481
+ /** @param {string} key */
482
+ sideClass(key) { return key === this.current ? "on" : ""; },
483
+ /** @param {string} name */
484
+ viewClass(name) { return this.view === name ? "on" : ""; },
485
+ /** @param {string} c */
486
+ ariaSort(c) {
487
+ if (this.sort === c) return "ascending";
488
+ if (this.sort === "-" + c) return "descending";
489
+ return "none";
490
+ },
491
+ /** @param {string} c */
492
+ head(c) {
493
+ if (this.sort === c) return this.tr("list.sortAsc", { col: c });
494
+ if (this.sort === "-" + c) return this.tr("list.sortDesc", { col: c });
495
+ return c;
496
+ },
497
+ /**
498
+ * @param {Row} row
499
+ * @param {string} c
500
+ */
501
+ cell(row, c) {
502
+ const v = row[c];
503
+ return v === null ? this.tr("list.null") : typeof v === "object" ? JSON.stringify(v) : String(v);
504
+ },
505
+ /**
506
+ * CSP-safe template helpers: Alpine's expression scope has no `String`
507
+ * or `JSON` globals, so templates call these component methods instead.
508
+ * @param {any} pk
509
+ */
510
+ pkKey(pk) { return String(pk); },
511
+ /** @param {any} v */
512
+ show(v) { return JSON.stringify(v); },
513
+ /** @param {Relation} r */
514
+ relLabel(r) { return this.tr("detail.relation", { name: r.name, type: r.type }); },
515
+ /** @param {string} key */
516
+ model(key) { return this.models.find((m) => m.key === key); },
517
+
518
+ // ---- bulk select
519
+ /** @param {string|number} pk */
520
+ toggleSelect(pk) {
521
+ const s = String(pk);
522
+ if (this.selectedPks[s]) delete this.selectedPks[s];
523
+ else this.selectedPks[s] = true;
524
+ },
525
+ toggleSelectAll() {
526
+ if (this.allVisibleSelected) {
527
+ this.selectedPks = {};
528
+ } else {
529
+ /** @type {Record<string,true>} */
530
+ const next = {};
531
+ for (const r of this.rows) next[String(r._pk)] = true;
532
+ this.selectedPks = next;
533
+ }
534
+ },
535
+ clearSelection() { this.selectedPks = {}; },
536
+ bulkDelete() {
537
+ const ids = Object.keys(this.selectedPks);
538
+ if (!ids.length) { this.toastError(this.tr("No rows selected")); return Promise.resolve(); }
539
+ if (ids.length > this.maxBulk) {
540
+ this.toastError(this.tr("Cannot delete {n} rows (max {max})", { n: ids.length, max: this.maxBulk }));
541
+ return Promise.resolve();
542
+ }
543
+ if (!this.confirm(`Delete ${ids.length} row(s)?`)) return Promise.resolve();
544
+ return this.guard(async () => {
545
+ const res = await this.api("models/" + this.current + "/bulk-delete", "POST", { ids });
546
+ this.toastSuccess(this.tr("Deleted {n} row(s)", { n: res.deleted }));
547
+ this.selectedPks = {};
548
+ await this.load();
549
+ });
550
+ },
551
+
552
+ // ---- connection
553
+ connectionChanged() { this.page = 1; this.selectedPks = {}; return this.load(); },
554
+
555
+ // ---- widgets
556
+ renderWidgets() {
557
+ const root = /** @type {any} */ (this).$refs.form;
558
+ if (!root) return;
559
+ root.innerHTML = "";
560
+ const SW = /** @type {WidgetsAPI} */ (/** @type {any} */ (window).StudioWidgets);
561
+ if (!SW) return;
562
+ for (const f of this.formFields) {
563
+ /** @type {Field} */
564
+ const field = Object.assign({}, f, {
565
+ readonly: f.readonly || this.readOnly,
566
+ display_value: this.formValues[f.name + "_display"] != null
567
+ ? this.formValues[f.name + "_display"]
568
+ : null,
569
+ });
570
+ const widget = SW.renderField(
571
+ field, this.formValues[f.name],
572
+ (name, val) => this.updateField(name, val),
573
+ );
574
+ root.appendChild(widget);
575
+ }
576
+ },
577
+ /**
578
+ * @param {string} name
579
+ * @param {unknown} value
580
+ */
581
+ updateField(name, value) {
582
+ this.formValues[name] = value;
583
+ this.json = JSON.stringify(this.formValues, null, 2);
584
+ },
585
+ setFormFields() {
586
+ const m = this.model(this.current);
587
+ if (!m) return;
588
+ this.formFields = this.pk === null ? m.fields.filter((f) => !f.readonly) : m.fields;
589
+ },
590
+ toggleFormMode() {
591
+ if (this.formMode === "widgets") {
592
+ this.json = JSON.stringify(this.formValues, null, 2);
593
+ this.formMode = "json";
594
+ } else if (this.applyJson()) {
595
+ this.formMode = "widgets";
596
+ this.renderWidgets();
597
+ }
598
+ },
599
+ /**
600
+ * Parse the JSON textarea into `formValues`.
601
+ * Returns false (and toasts) when the text is not an object, so callers
602
+ * can abort before writing anything to the server.
603
+ * @returns {boolean}
604
+ */
605
+ applyJson() {
606
+ let parsed;
607
+ try {
608
+ parsed = JSON.parse(this.json);
609
+ } catch (e) {
610
+ this.toastError(this.tr("Invalid JSON: {msg}", { msg: e instanceof Error ? e.message : String(e) }));
611
+ return false;
612
+ }
613
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
614
+ this.toastError(this.tr("Invalid JSON: expected an object"));
615
+ return false;
616
+ }
617
+ this.formValues = parsed;
618
+ return true;
619
+ },
620
+
621
+ // ---- column chooser
622
+ /** @param {string} c */
623
+ isHidden(c) { return !!this.hiddenCols[c]; },
624
+ /** @param {string} c */
625
+ toggleCol(c) {
626
+ if (this.hiddenCols[c]) delete this.hiddenCols[c];
627
+ else this.hiddenCols[c] = true;
628
+ this.cols = this.allCols.filter((x) => !this.hiddenCols[x]);
629
+ },
630
+ resetCols() {
631
+ const m = this.model(this.current);
632
+ if (!m) return;
633
+ this.allCols = m.list_display.slice();
634
+ this.hiddenCols = {};
635
+ this.cols = m.list_display.slice();
636
+ },
637
+
638
+ // ---- filter builder
639
+ toggleAddFilter() {
640
+ this.showAddFilter = !this.showAddFilter;
641
+ if (this.showAddFilter) {
642
+ this.draftError = "";
643
+ if (!this.draftField && this.filterableFields.length) {
644
+ this.draftField = this.filterableFields[0].name;
645
+ const ops = this.draftOps;
646
+ this.draftOp = ops.length ? ops[0] : "eq";
647
+ this.draftValue = "";
648
+ }
649
+ }
650
+ },
651
+ onDraftFieldChange() {
652
+ const ops = this.draftOps;
653
+ if (ops.indexOf(this.draftOp) === -1) this.draftOp = ops[0] || "eq";
654
+ this.draftValue = ""; this.draftError = "";
655
+ },
656
+ addFilter() {
657
+ const f = this.draftFieldObj;
658
+ if (!f) { this.draftError = "Pick a field"; return; }
659
+ const SF = /** @type {FiltersAPI} */ (/** @type {any} */ (window).StudioFilters);
660
+ if (!SF) { this.draftError = "filters.js not loaded"; return; }
661
+ const err = SF.validate(f, this.draftOp, this.draftValue);
662
+ if (err) { this.draftError = err; return; }
663
+ /** @type {FilterPredicate} */
664
+ const pred = { field: f.name, op: this.draftOp, value: SF.normalizeValue(f, this.draftOp, this.draftValue) };
665
+ this.filters.push(pred);
666
+ this.showAddFilter = false;
667
+ this.draftValue = ""; this.draftError = "";
668
+ this.page = 1;
669
+ return this.load();
670
+ },
671
+ /** @param {number} i */
672
+ removeFilter(i) { this.filters.splice(i, 1); this.page = 1; return this.load(); },
673
+ clearFilters() { this.filters = []; this.page = 1; return this.load(); },
674
+ /** @param {FilterPredicate} f */
675
+ chipLabel(f) {
676
+ const SF = /** @type {FiltersAPI} */ (/** @type {any} */ (window).StudioFilters);
677
+ return SF ? SF.label(f) : f.field + " " + f.op;
678
+ },
679
+
680
+ // ---- actions
681
+ /** Apply the current location.hash to the view state. */
682
+ applyHash() {
683
+ const H = /** @type {any} */ (window).StudioStateHash;
684
+ if (!H) return;
685
+ const parts = H.decode(window.location.hash);
686
+ if (parts.m) this.current = parts.m;
687
+ if (parts.v) this.view = parts.v;
688
+ if (parts.q) this.search = parts.q;
689
+ if (parts.s) this.sort = parts.s;
690
+ if (parts.p) this.page = Number(parts.p) || 1;
691
+ },
692
+ /** Write the current view state into the URL hash (no row data). */
693
+ syncHash() {
694
+ const H = /** @type {any} */ (window).StudioStateHash;
695
+ if (!H) return;
696
+ const hash = H.encode(H.fromState({
697
+ model: this.current, view: this.view, search: this.search,
698
+ sort: this.sort, page: this.page, cols: this.cols, filters: this.filters,
699
+ connection: this.connection,
700
+ }));
701
+ try {
702
+ if (window.location.hash.slice(1) !== hash) window.location.hash = hash;
703
+ } catch (e) { /* non-browser or locked location */ }
704
+ },
705
+
706
+ async init() {
707
+ try {
708
+ const s = await this.api("schema");
709
+ this.schema = s;
710
+ this.models = s ? s.models : [];
711
+ this.connections = (s && s.connections) || [];
712
+ const I = /** @type {I18nAPI|undefined} */ (/** @type {any} */ (window).StudioI18n);
713
+ if (I) {
714
+ // An explicit browser choice wins; otherwise the host's schema
715
+ // default decides the first language shown.
716
+ var saved = null;
717
+ try { saved = window.localStorage && window.localStorage.getItem(I.STORAGE_KEY); }
718
+ catch (e) { saved = null; }
719
+ if (saved) I.load(); else I.setLocale((s && s.locale) || "en");
720
+ this.locale = I.locale();
721
+ I.apply(document);
722
+ this.pluginTitle = this.tr("nav.plugins");
723
+ }
724
+ const V = /** @type {ViewsAPI} */ (/** @type {any} */ (window).StudioViews);
725
+ this.savedViews = V ? V.load() : {};
726
+ this.initQueryHistory();
727
+ const T = /** @type {ThemeAPI} */ (/** @type {any} */ (window).StudioTheme);
728
+ this.themeChoice = T ? T.load() : "system";
729
+ try {
730
+ const S = /** @type {any} */ (window).sessionStorage;
731
+ if (S) this.pinnedModels = JSON.parse(S.getItem("studio.pins.v1") || "[]");
732
+ } catch (e) { this.pinnedModels = []; }
733
+ const TB = /** @type {any} */ (window).StudioTabs;
734
+ if (TB) this.tabStore = TB.load(/** @type {any} */ (window).sessionStorage);
735
+ document.addEventListener("keydown", (ev) => this.onKeydown(ev));
736
+ window.addEventListener("hashchange", () => this.applyHash());
737
+ this.applyHash();
738
+ if (this.models.length && !this.current) await this.pick(this.models[0].key);
739
+ if (TB && !this.tabStore.tabs.length) this.newTabWith({ view: "list", model: this.current });
740
+ } catch (e) {
741
+ this.toastError(e instanceof Error ? e.message : String(e));
742
+ }
743
+ },
744
+ /** @param {string} key */
745
+ async pick(key) {
746
+ this.current = key; this.page = 1; this.search = ""; this.sort = "";
747
+ this.filters = []; this.selectedPks = {}; this.view = "list";
748
+ this.resetCols();
749
+ await this.load();
750
+ },
751
+ async load() {
752
+ const started = Date.now();
753
+ await this.guard(async () => {
754
+ const m = this.model(this.current);
755
+ if (!m) return;
756
+ this.selectedPks = {};
757
+ const qs = new URLSearchParams({ page: String(this.page), limit: String(this.limit) });
758
+ if (this.sort) qs.set("sort", this.sort);
759
+ if (this.search) qs.set("search", this.search);
760
+ if (this.filters.length) qs.set("filter", JSON.stringify(this.filters));
761
+ const d = await this.api("models/" + this.current + "?" + qs.toString());
762
+ this.rows = d.items; this.total = d.total; this.limit = d.limit;
763
+ this.lastRequestMs = Date.now() - started;
764
+ this.syncHash();
765
+ });
766
+ },
767
+ doSearch() { this.page = 1; return this.load(); },
768
+ /** @param {string} c */
769
+ sortBy(c) { this.sort = this.sort === c ? "-" + c : c; return this.load(); },
770
+ prev() { this.page -= 1; return this.load(); },
771
+ next() { this.page += 1; return this.load(); },
772
+ back() { this.closeDrawer(); return this.load(); },
773
+
774
+ newRow() {
775
+ const m = this.model(this.current);
776
+ if (!m) return;
777
+ this.rememberDrawerFocus();
778
+ /** @type {Record<string,any>} */
779
+ const blank = {};
780
+ for (const f of m.fields) if (!f.readonly) blank[f.name] = null;
781
+ this.pk = null; this.formValues = blank;
782
+ this.drawerSnapshot = JSON.parse(JSON.stringify(blank));
783
+ this.json = JSON.stringify(blank, null, 2);
784
+ this.formMode = "widgets"; this.resetRel(m); this.view = "detail";
785
+ this.setFormFields();
786
+ /** @type {any} */ (this).$nextTick(() => { this.renderWidgets(); this.focusDrawer(); });
787
+ },
788
+ /** @param {Row} row */
789
+ async openRow(row) {
790
+ this.rememberDrawerFocus();
791
+ await this.guard(async () => {
792
+ const rec = await this.api("models/" + this.current + "/" + enc(row._pk));
793
+ this.pk = row._pk; this.formValues = rec;
794
+ this.drawerSnapshot = JSON.parse(JSON.stringify(rec));
795
+ this.json = JSON.stringify(rec, null, 2);
796
+ this.formMode = "widgets";
797
+ const m = this.model(this.current);
798
+ if (m) this.resetRel(m);
799
+ this.view = "detail"; this.setFormFields();
800
+ this.breadcrumbs = [
801
+ { label: this.current, key: this.current },
802
+ { label: String(row._pk), key: this.current },
803
+ ];
804
+ this.syncHash();
805
+ /** @type {any} */ (this).$nextTick(() => { this.renderWidgets(); this.focusDrawer(); });
806
+ });
807
+ },
808
+ /** @param {ModelDesc} m */
809
+ resetRel(m) {
810
+ this.relations = m.relations; this.hasRel = false;
811
+ this.relRows = []; this.relType = "";
812
+ },
813
+ payload() {
814
+ const m = this.model(this.current);
815
+ if (!m) return {};
816
+ /** @type {Record<string,any>} */
817
+ const out = {};
818
+ for (const f of m.fields) {
819
+ if (f.readonly) continue;
820
+ if (this.pk !== null && f.pk) continue;
821
+ if (f.name in this.formValues) out[f.name] = this.formValues[f.name];
822
+ }
823
+ return out;
824
+ },
825
+ save() {
826
+ return this.guard(async () => {
827
+ if (this.formMode === "json" && !this.applyJson()) return;
828
+ if (this.pk === null) {
829
+ await this.api("models/" + this.current, "POST", this.payload());
830
+ this.toastSuccess(this.tr("Created"));
831
+ } else {
832
+ await this.api("models/" + this.current + "/" + enc(this.pk), "PATCH", this.payload());
833
+ this.toastSuccess(this.tr("Saved"));
834
+ }
835
+ this.restoreDrawerFocus();
836
+ this.view = "list"; await this.load();
837
+ });
838
+ },
839
+ remove() {
840
+ return this.guard(async () => {
841
+ if (!this.confirm(this.tr("Delete this row?"))) return;
842
+ await this.api("models/" + this.current + "/" + enc(this.pk), "DELETE");
843
+ this.toastSuccess(this.tr("Deleted"));
844
+ this.restoreDrawerFocus();
845
+ this.view = "list"; await this.load();
846
+ });
847
+ },
848
+ /** @param {{ name: string, type: string, model: string }} r */
849
+ showRel(r) {
850
+ return this.guard(async () => {
851
+ const d = await this.api("models/" + this.current + "/" + enc(this.pk) + "/" + r.name);
852
+ this.relName = r.name; this.relType = r.type; this.relModel = r.model;
853
+ const rm = this.model(r.model);
854
+ this.relCols = rm ? rm.list_display : [];
855
+ this.relRows = d.items; this.hasRel = true;
856
+ });
857
+ },
858
+ /** @param {Row} it */
859
+ openRelated(it) { this.current = this.relModel; return this.openRow(it); },
860
+
861
+ /** @param {"add"|"remove"} mode */
862
+ openM2mPicker(mode) {
863
+ const P = /** @type {PickerAPI} */ (/** @type {any} */ (window).StudioPicker);
864
+ if (!P) { this.toastError(this.tr("pickers.js not loaded")); return; }
865
+ P.request({
866
+ model: this.relModel, multiSelect: true, label: this.relName,
867
+ preselect: mode === "remove" ? this.relRows.map((r) => r._pk) : [],
868
+ onConfirm: (pks) => { this.m2mApply(mode, pks); },
869
+ });
870
+ },
871
+ /** @param {"add"|"remove"} mode @param {string[]} pks */
872
+ async m2mApply(mode, pks) {
873
+ if (!pks.length) return;
874
+ const verb = mode === "add" ? "POST" : "DELETE";
875
+ await this.guard(async () => {
876
+ await this.api("models/" + this.current + "/" + enc(this.pk) + "/" + this.relName, verb, { ids: pks });
877
+ this.toastSuccess(this.tr(mode === "add" ? "Added {n}" : "Removed {n}", { n: pks.length }));
878
+ await this.showRel({ name: this.relName, type: /** @type {any} */ (this.relType), model: this.relModel });
879
+ });
880
+ },
881
+
882
+ // ---- v0.5.0 staged saves (program G2)
883
+ /** @returns {PendingAPI|undefined} */
884
+ pending() {
885
+ return /** @type {PendingAPI|undefined} */ (/** @type {any} */ (window).StudioPending);
886
+ },
887
+ /** @returns {InlineEditAPI|undefined} */
888
+ ie() {
889
+ return /** @type {InlineEditAPI|undefined} */ (/** @type {any} */ (window).StudioInlineEdit);
890
+ },
891
+ /** @returns {A11yAPI|undefined} */
892
+ a11y() {
893
+ return /** @type {A11yAPI|undefined} */ (/** @type {any} */ (window).StudioA11y);
894
+ },
895
+
896
+ // ---- v0.5.0 detail drawer (program D)
897
+ /** Remember the element to return focus to when the drawer closes. */
898
+ rememberDrawerFocus() {
899
+ const A = this.a11y();
900
+ this.drawerReturnFocus = A ? A.saveFocus() : (/** @type {any} */ (document).activeElement || null);
901
+ },
902
+ restoreDrawerFocus() {
903
+ const A = this.a11y();
904
+ if (A && A.restoreFocus(this.drawerReturnFocus)) {
905
+ this.drawerReturnFocus = null;
906
+ } else if (this.drawerReturnFocus) {
907
+ this.drawerReturnFocus = null;
908
+ }
909
+ },
910
+ /** Focus the first control in the drawer once its form is rendered. */
911
+ focusDrawer() {
912
+ const A = this.a11y();
913
+ const root = /** @type {any} */ (this).$refs && /** @type {any} */ (this).$refs.drawer;
914
+ if (!A || !root) return;
915
+ const items = A.focusable(root);
916
+ if (items.length) items[0].focus();
917
+ },
918
+ /** @param {KeyboardEvent} ev */
919
+ onDrawerKeydown(ev) {
920
+ if (!this.isDetail) return;
921
+ if (ev.key === "Escape") {
922
+ ev.preventDefault();
923
+ this.closeDrawer();
924
+ return;
925
+ }
926
+ const A = this.a11y();
927
+ const root = /** @type {any} */ (this).$refs && /** @type {any} */ (this).$refs.drawer;
928
+ if (A && root && A.trapFocus(root, ev)) ev.preventDefault();
929
+ },
930
+ closeDrawer() {
931
+ if (this.drawerDirty && !this.confirm(this.tr("This row has unsaved changes. Leave it anyway?"))) return;
932
+ this.restoreDrawerFocus();
933
+ this.view = "list";
934
+ this.hasRel = false;
935
+ this.breadcrumbs = [];
936
+ this.inline = { active: null, last: null };
937
+ this.syncHash();
938
+ },
939
+
940
+ // ---- v0.5.0 inline cell editing (program D)
941
+ /** @param {Row} row @param {string} col @param {any} ev */
942
+ beginInline(row, col, ev) {
943
+ if (!this.canWrite || !ev) return;
944
+ const m = this.model(this.current);
945
+ if (!m) return;
946
+ const field = m.fields.find((/** @type {Field} */ f) => f.name === col);
947
+ if (!field || field.readonly || field.pk) return;
948
+ const IE = this.ie();
949
+ if (!IE) return;
950
+ const td = ev.currentTarget || ev.target;
951
+ if (!td || typeof td.querySelector !== "function") return;
952
+ // One active editor at a time: close any prior one without committing.
953
+ this.finishInlineDom(/** @type {HTMLElement} */ (td));
954
+ this.inline = IE.begin(this.inline, { model: this.current, pk: row._pk, col, value: row[col] });
955
+ const SW = /** @type {WidgetsAPI|undefined} */ (/** @type {any} */ (window).StudioWidgets);
956
+ if (!SW) return;
957
+ /** @type {any} */
958
+ const fieldCfg = Object.assign({}, field, { readonly: false });
959
+ const wrap = document.createElement("div");
960
+ wrap.className = "inline-edit";
961
+ wrap.appendChild(SW.renderField(fieldCfg, row[col], (/** @type {string} */ _n, /** @type {any} */ v) => {
962
+ this.inline = IE.change(this.inline, v);
963
+ }));
964
+ td.appendChild(wrap);
965
+ const span = td.querySelector(":scope > span");
966
+ if (span) span.classList.add("inline-hidden");
967
+ const first = /** @type {HTMLElement|null} */ (wrap.querySelector("input,select,textarea,button"));
968
+ if (first) {
969
+ first.focus();
970
+ first.addEventListener("keydown", (/** @type {KeyboardEvent} */ e) => {
971
+ if (e.key === "Enter") { e.preventDefault(); this.commitInline(td); }
972
+ else if (e.key === "Escape") { e.preventDefault(); this.cancelInline(td); }
973
+ });
974
+ }
975
+ },
976
+ /** @param {HTMLElement} td */
977
+ finishInlineDom(td) {
978
+ const wrap = td.querySelector && td.querySelector(".inline-edit");
979
+ if (wrap && wrap.parentNode) wrap.parentNode.removeChild(wrap);
980
+ const span = td.querySelector && td.querySelector(":scope > span");
981
+ if (span) span.classList.remove("inline-hidden");
982
+ },
983
+ /** @param {HTMLElement} td */
984
+ commitInline(td) {
985
+ const IE = this.ie();
986
+ if (!IE) return;
987
+ const r = IE.commit(this.inline);
988
+ this.inline = r.state;
989
+ this.finishInlineDom(td);
990
+ if (!r.changed) { this.toastSuccess(this.tr("No change")); return; }
991
+ const P = this.pending();
992
+ if (P) {
993
+ this.pendingStore = P.stage(this.pendingStore, r.spec).store;
994
+ this.syncPendingDirty();
995
+ }
996
+ this.toastSuccess(this.tr("Cell change staged"));
997
+ },
998
+ /** @param {HTMLElement} td */
999
+ cancelInline(td) {
1000
+ const IE = this.ie();
1001
+ if (!IE) return;
1002
+ this.inline = IE.cancel(this.inline);
1003
+ this.finishInlineDom(td);
1004
+ this.restoreDrawerFocus();
1005
+ },
1006
+ undoInline() {
1007
+ const IE = this.ie();
1008
+ if (!IE) return;
1009
+ const u = IE.undo(this.inline);
1010
+ this.inline = u.state;
1011
+ if (!u.spec) return;
1012
+ const P = this.pending();
1013
+ if (P) {
1014
+ this.pendingStore = P.stage(this.pendingStore, u.spec).store;
1015
+ this.syncPendingDirty();
1016
+ }
1017
+ this.toastSuccess(this.tr("Undid last cell edit"));
1018
+ },
1019
+
1020
+ // ---- v0.5.0 Copy-as menu + JSON tree (program D)
1021
+ /** @param {string|number} pk */
1022
+ toggleCopyMenu(pk) {
1023
+ this.copyMenuPk = String(pk) === String(this.copyMenuPk) ? null : String(pk);
1024
+ },
1025
+ closeCopyMenu() { this.copyMenuPk = null; },
1026
+ /** @returns {CopyAsAPI|undefined} */
1027
+ copyAs() {
1028
+ return /** @type {CopyAsAPI|undefined} */ (/** @type {any} */ (window).StudioCopyAs);
1029
+ },
1030
+ /**
1031
+ * @param {"json"|"create"|"csv"} kind
1032
+ * @param {Row} row
1033
+ */
1034
+ copyRow(kind, row) {
1035
+ const C = this.copyAs();
1036
+ if (!C) return;
1037
+ let text;
1038
+ if (kind === "json") text = C.json(row);
1039
+ else if (kind === "create") text = C.createSnippet(this.model(this.current), row);
1040
+ else text = C.csvLine(row, this.cols.length ? this.cols : this.allCols);
1041
+ const label = kind === "json" ? "JSON" : kind === "create" ? "create() snippet" : "CSV line";
1042
+ C.write(text).then((/** @type {boolean} */ ok) => {
1043
+ this.toastSuccess(this.tr(ok ? "Copied {label}" : "Copy failed", { label: label }));
1044
+ });
1045
+ this.closeCopyMenu();
1046
+ },
1047
+ toggleJsonTree() {
1048
+ this.jsonTreeOpen = !this.jsonTreeOpen;
1049
+ if (this.jsonTreeOpen) /** @type {any} */ (this).$nextTick(() => this.renderJsonTree());
1050
+ },
1051
+ /** @param {string} text */
1052
+ applyJsonTree(text) {
1053
+ const J = /** @type {JsonViewAPI|undefined} */ (/** @type {any} */ (window).StudioJsonView);
1054
+ if (!J) return;
1055
+ const r = J.validate(text);
1056
+ if (!r.ok) { this.toastError(this.tr("Invalid JSON: {msg}", { msg: r.error || "" })); return; }
1057
+ this.formValues = r.value || {};
1058
+ this.json = JSON.stringify(this.formValues, null, 2);
1059
+ this.toastSuccess(this.tr("JSON applied"));
1060
+ },
1061
+ renderJsonTree() {
1062
+ const J = /** @type {JsonViewAPI|undefined} */ (/** @type {any} */ (window).StudioJsonView);
1063
+ const root = /** @type {any} */ (this).$refs && /** @type {any} */ (this).$refs.jsonTreeBody;
1064
+ if (!J || !root) return;
1065
+ root.replaceChildren();
1066
+ root.appendChild(J.render(this.formValues, { rootLabel: this.current || "row" }));
1067
+ },
1068
+ stageSave() {
1069
+ const P = this.pending();
1070
+ if (!P || this.readOnly) return;
1071
+ if (this.formMode === "json" && !this.applyJson()) return;
1072
+ if (!this.model(this.current)) return;
1073
+ /** @type {any} */
1074
+ const spec = this.pk === null
1075
+ ? { op: "create", model: this.current, data: this.payload() }
1076
+ : { op: "update", model: this.current, pk: this.pk, data: this.payload(), before: this.formValues };
1077
+ this.pendingStore = P.stage(this.pendingStore, spec).store;
1078
+ this.pendingOpen = true;
1079
+ this.syncPendingDirty();
1080
+ this.toastSuccess(this.tr("Change staged"));
1081
+ },
1082
+ stageDelete() {
1083
+ const P = this.pending();
1084
+ if (!P || !this.canDelete) return;
1085
+ if (!this.confirm(this.tr("Stage deletion of this row?"))) return;
1086
+ this.pendingStore = P.stage(this.pendingStore, {
1087
+ op: "delete", model: this.current, pk: this.pk, before: this.formValues,
1088
+ }).store;
1089
+ this.pendingOpen = true;
1090
+ this.syncPendingDirty();
1091
+ this.toastSuccess(this.tr("Deletion staged"));
1092
+ },
1093
+ /** @param {"add"|"remove"} mode @param {string[]} pks */
1094
+ stageM2m(mode, pks) {
1095
+ const P = this.pending();
1096
+ if (!P || !pks.length) return;
1097
+ this.pendingStore = P.stage(this.pendingStore, {
1098
+ op: mode === "add" ? "m2m_add" : "m2m_remove",
1099
+ model: this.current, pk: this.pk, rel: this.relName, ids: pks,
1100
+ }).store;
1101
+ this.pendingOpen = true;
1102
+ this.syncPendingDirty();
1103
+ this.toastSuccess(this.tr("{n} relation change(s) staged", { n: pks.length }));
1104
+ },
1105
+ async saveAll() {
1106
+ const P = this.pending();
1107
+ if (!P || !this.pendingDirty) return;
1108
+ await this.guard(async () => {
1109
+ const body = P.requestBody(this.pendingStore, this.connection);
1110
+ await this.api("batch", "POST", body);
1111
+ this.pendingStore = P.discardAll(this.pendingStore);
1112
+ this.syncPendingDirty();
1113
+ this.pendingOpen = false;
1114
+ this.toastSuccess(this.tr("Saved all staged changes"));
1115
+ await this.load();
1116
+ });
1117
+ },
1118
+ discardAllPending() {
1119
+ const P = this.pending();
1120
+ if (!P) return;
1121
+ this.pendingStore = P.discardAll(this.pendingStore);
1122
+ this.syncPendingDirty();
1123
+ this.toastSuccess(this.tr("Discarded all staged changes"));
1124
+ },
1125
+ /** @param {string} id */
1126
+ removePending(id) {
1127
+ const P = this.pending();
1128
+ if (!P) return;
1129
+ this.pendingStore = P.discard(this.pendingStore, id);
1130
+ this.syncPendingDirty();
1131
+ },
1132
+ undoPending() {
1133
+ const P = this.pending();
1134
+ if (!P) return;
1135
+ this.pendingStore = P.undo(this.pendingStore);
1136
+ this.syncPendingDirty();
1137
+ },
1138
+ /** @param {PendingChange} change @returns {DiffEntry[]} */
1139
+ pendingDiff(change) {
1140
+ const P = this.pending();
1141
+ return P ? P.diff(change) : [];
1142
+ },
1143
+ togglePending() { this.pendingOpen = !this.pendingOpen; },
1144
+ // ---- v0.5.0 optional AI filter (program G3)
1145
+ toggleAi() { this.aiOpen = !this.aiOpen; },
1146
+ /** @param {any} f @returns {string} */
1147
+ aiChipLabel(f) {
1148
+ const A = /** @type {any} */ (window).StudioAI;
1149
+ return A ? A.label(f) : String(f.field || "");
1150
+ },
1151
+ /** @param {number} i */
1152
+ removeAiChip(i) { this.aiFilters.splice(i, 1); },
1153
+ runAi() {
1154
+ return this.guard(async () => {
1155
+ this.aiError = "";
1156
+ const data = await this.api("ai/filter", "POST", { model: this.current, text: this.aiText });
1157
+ // Results are staged for review only — never applied here.
1158
+ this.aiFilters = Array.isArray(data.filters) ? data.filters : [];
1159
+ });
1160
+ },
1161
+ applyAi() {
1162
+ if (!this.aiFilters.length) return;
1163
+ this.filters = this.aiFilters.slice();
1164
+ this.aiFilters = [];
1165
+ this.page = 1;
1166
+ return this.load();
1167
+ },
1168
+ syncPendingDirty() {
1169
+ const T = /** @type {any} */ (window).StudioTabs;
1170
+ if (!T || !this.tabStore.activeId) return;
1171
+ this.tabStore = T.setDirty(this.tabStore, this.tabStore.activeId, this.pendingDirty);
1172
+ },
1173
+
1174
+ // ---- v0.3.0 panels
1175
+ async viewList() {
1176
+ if (!this.current && this.models.length) this.current = this.models[0].key;
1177
+ this.view = "list";
1178
+ await this.load();
1179
+ },
1180
+
1181
+ /** v0.9.0 — open the declarative plugin panel. */
1182
+ viewPlugin() {
1183
+ this.view = "plugin";
1184
+ this.pluginText = "";
1185
+ this.pluginError = "";
1186
+ this.syncHash();
1187
+ },
1188
+
1189
+ /**
1190
+ * Invoke one plugin action. The response is inserted with `x-text`, never
1191
+ * as HTML, so a plugin cannot inject markup into the shell.
1192
+ * @param {{plugin:string,id:string,label:string,path:string}} a
1193
+ */
1194
+ async runPluginAction(a) {
1195
+ this.pluginTitle = a.label;
1196
+ this.pluginText = "";
1197
+ this.pluginError = "";
1198
+ try {
1199
+ const url = base + "api/v1/plugins/" + enc(a.plugin) + a.path;
1200
+ const res = await fetch(url, { method: "GET", headers: { "x-requested-with": "studio" } });
1201
+ let text = "";
1202
+ if (typeof res.text === "function") text = await res.text();
1203
+ else text = JSON.stringify(await res.json().catch(() => ({})));
1204
+ if (!res.ok) {
1205
+ let message = res.statusText || "Plugin request failed";
1206
+ try {
1207
+ const parsed = JSON.parse(text);
1208
+ if (parsed && parsed.error && parsed.error.message) message = parsed.error.message;
1209
+ } catch (e) { /* plain-text error body */ }
1210
+ throw new Error(message);
1211
+ }
1212
+ this.pluginText = text;
1213
+ } catch (e) {
1214
+ const msg = e instanceof Error ? e.message : String(e);
1215
+ this.pluginError = msg;
1216
+ this.toastError(msg);
1217
+ }
1218
+ },
1219
+
1220
+ async openPlayground() {
1221
+ if (!this.current && this.models.length) this.current = this.models[0].key;
1222
+ this.view = "playground";
1223
+ if (!this.playgroundModel) {
1224
+ this.playgroundModel = this.current || (this.models[0] ? this.models[0].key : "");
1225
+ this.playgroundFilters = "[]";
1226
+ this.playgroundSearch = "";
1227
+ this.playgroundSort = "";
1228
+ this.playgroundLimit = 50;
1229
+ }
1230
+ await this.runPlayground();
1231
+ },
1232
+
1233
+ async runPlayground() {
1234
+ this.playgroundError = "";
1235
+ let filters;
1236
+ try {
1237
+ filters = JSON.parse(this.playgroundFilters || "[]");
1238
+ } catch (e) {
1239
+ this.playgroundError = "Invalid filter JSON: " + (e instanceof Error ? e.message : String(e));
1240
+ return;
1241
+ }
1242
+ const started = Date.now();
1243
+ try {
1244
+ const result = await this.api("query/preview", "POST", {
1245
+ model: this.playgroundModel || this.current,
1246
+ filters: filters,
1247
+ search: this.playgroundSearch || null,
1248
+ sort: this.playgroundSort || null,
1249
+ limit: parseInt(String(this.playgroundLimit || "50"), 10),
1250
+ });
1251
+ this.playgroundMs = Date.now() - started;
1252
+ const container = /** @type {any} */ (this).$refs.playgroundBody;
1253
+ if (container) {
1254
+ container.innerHTML = "";
1255
+ const P = /** @type {PlaygroundAPI} */ (/** @type {any} */ (window).StudioPlayground);
1256
+ if (P) container.appendChild(P.render(result));
1257
+ }
1258
+ const H = this.queryHistory();
1259
+ if (H) {
1260
+ this.playgroundHistory = H.create(/** @type {any} */ (window).localStorage).add({
1261
+ model: this.playgroundModel || this.current, filters: filters,
1262
+ search: this.playgroundSearch, sort: this.playgroundSort, limit: this.playgroundLimit,
1263
+ });
1264
+ }
1265
+ } catch (e) {
1266
+ this.playgroundError = e instanceof Error ? e.message : String(e);
1267
+ }
1268
+ },
1269
+
1270
+ // ---- v0.5.0 playground polish (program D)
1271
+ /** @returns {QueryHistoryFactory|undefined} */
1272
+ queryHistory() {
1273
+ return /** @type {QueryHistoryFactory|undefined} */ (/** @type {any} */ (window).StudioQueryHistory);
1274
+ },
1275
+ initQueryHistory() {
1276
+ const H = this.queryHistory();
1277
+ if (H) this.playgroundHistory = H.create(/** @type {any} */ (window).localStorage).list();
1278
+ },
1279
+ toggleQueryHistory() {
1280
+ this.queryHistoryOpen = !this.queryHistoryOpen;
1281
+ if (this.queryHistoryOpen) this.initQueryHistory();
1282
+ },
1283
+ /** @param {number} i */
1284
+ loadHistoryQuery(i) {
1285
+ const h = this.playgroundHistory[i];
1286
+ if (!h) return;
1287
+ this.playgroundModel = h.model;
1288
+ this.playgroundFilters = JSON.stringify(h.filters || []);
1289
+ this.playgroundSearch = h.search || "";
1290
+ this.playgroundSort = h.sort || "";
1291
+ this.playgroundLimit = h.limit || 50;
1292
+ this.queryHistoryOpen = false;
1293
+ return this.runPlayground();
1294
+ },
1295
+ clearQueryHistory() {
1296
+ const H = this.queryHistory();
1297
+ if (!H) return;
1298
+ this.playgroundHistory = H.create(/** @type {any} */ (window).localStorage).clear();
1299
+ this.toastSuccess(this.tr("Query history cleared"));
1300
+ },
1301
+ /** Apply the current playground query to the list view. */
1302
+ openInList() {
1303
+ let filters;
1304
+ try { filters = JSON.parse(this.playgroundFilters || "[]"); }
1305
+ catch (e) { this.toastError(this.tr("Invalid filter JSON")); return; }
1306
+ this.current = this.playgroundModel || this.current;
1307
+ this.filters = Array.isArray(filters) ? filters.slice() : [];
1308
+ this.search = this.playgroundSearch || "";
1309
+ this.sort = this.playgroundSort || "";
1310
+ this.limit = parseInt(String(this.playgroundLimit || "50"), 10) || 25;
1311
+ this.page = 1;
1312
+ this.selectedPks = {};
1313
+ this.queryHistoryOpen = false;
1314
+ return this.viewList();
1315
+ },
1316
+ async openEr() {
1317
+ this.view = "er";
1318
+ await this.guard(async () => {
1319
+ const [schema, result] = await Promise.all([
1320
+ this.api("schema"),
1321
+ this.api("er"),
1322
+ ]);
1323
+ const container = /** @type {any} */ (this).$refs.erBody;
1324
+ if (container) {
1325
+ container.replaceChildren();
1326
+ const E = /** @type {ErAPI} */ (/** @type {any} */ (window).StudioEr);
1327
+ if (E) {
1328
+ container.appendChild(E.render(schema, {
1329
+ mermaid: result.mermaid || null,
1330
+ onOpen: (key) => { this.current = key; void this.pick(key); },
1331
+ }));
1332
+ }
1333
+ }
1334
+ });
1335
+ },
1336
+
1337
+ async openMigrations() {
1338
+ this.view = "migrations";
1339
+ await this.guard(async () => {
1340
+ const [info, pending] = await Promise.all([
1341
+ this.api("migrations"),
1342
+ this.api("migrations/pending"),
1343
+ ]);
1344
+ const container = /** @type {any} */ (this).$refs.migrationsBody;
1345
+ if (container) {
1346
+ container.replaceChildren();
1347
+ const M = /** @type {MigrationsAPI} */ (/** @type {any} */ (window).StudioMigrations);
1348
+ if (M) container.appendChild(M.render(info, pending));
1349
+ }
1350
+ });
1351
+ },
1352
+
1353
+ // ---- v0.3.1 audit panel
1354
+ async openAudit() {
1355
+ this.view = "audit";
1356
+ this.auditPage = 1;
1357
+ await this.loadAudit();
1358
+ },
1359
+ async loadAudit() {
1360
+ await this.guard(async () => {
1361
+ const qs = new URLSearchParams({
1362
+ page: String(this.auditPage),
1363
+ limit: String(this.auditLimit),
1364
+ });
1365
+ const f = this.auditFilters;
1366
+ if (f.action) qs.set("action", f.action);
1367
+ if (f.model) qs.set("model", f.model);
1368
+ if (f.actor) qs.set("actor", f.actor);
1369
+ const info = await this.api("audit?" + qs.toString());
1370
+ const container = /** @type {any} */ (this).$refs.auditBody;
1371
+ if (container) {
1372
+ container.innerHTML = "";
1373
+ const A = /** @type {AuditAPI} */ (/** @type {any} */ (window).StudioAudit);
1374
+ if (A) {
1375
+ container.appendChild(A.render(info, {
1376
+ onPageChange: (p) => { this.auditPage = p; this.loadAudit(); },
1377
+ }));
1378
+ }
1379
+ }
1380
+ });
1381
+ },
1382
+ async applyAuditFilters() {
1383
+ this.auditPage = 1;
1384
+ await this.loadAudit();
1385
+ },
1386
+ async clearAuditFilters() {
1387
+ this.auditFilters = { action: "", model: "", actor: "" };
1388
+ this.auditPage = 1;
1389
+ await this.loadAudit();
1390
+ },
1391
+
1392
+ // ---- v0.3.1 saved views
1393
+ viewsToggle() { this.viewsOpen = !this.viewsOpen; },
1394
+ saveCurrentView() {
1395
+ if (!this.current) { this.toastError(this.tr("No model selected")); return; }
1396
+ const name = (this.prompt(this.tr("Save view as (existing names overwrite):")) || "").trim();
1397
+ if (!name) return;
1398
+ const V = /** @type {ViewsAPI} */ (/** @type {any} */ (window).StudioViews);
1399
+ if (!V) { this.toastError(this.tr("views.js not loaded")); return; }
1400
+ const view = V.serialize({
1401
+ name: name,
1402
+ current: this.current,
1403
+ filters: this.filters,
1404
+ sort: this.sort,
1405
+ search: this.search,
1406
+ cols: this.cols,
1407
+ allCols: this.allCols,
1408
+ hiddenCols: this.hiddenCols,
1409
+ });
1410
+ const all = V.load();
1411
+ all[name] = view;
1412
+ V.save(all);
1413
+ this.savedViews = all;
1414
+ this.viewsOpen = false;
1415
+ this.toastSuccess(this.tr("Saved view: {name}", { name: name }));
1416
+ },
1417
+ /** @param {string} name */
1418
+ async loadView(name) {
1419
+ const view = this.savedViews[name];
1420
+ if (!view) return;
1421
+ this.viewsOpen = false;
1422
+ this.current = view.model;
1423
+ this.filters = view.filters.slice();
1424
+ this.sort = view.sort;
1425
+ this.search = view.search;
1426
+ this.allCols = view.allCols.slice();
1427
+ this.hiddenCols = { ...(view.hiddenCols || {}) };
1428
+ this.cols = view.cols.slice();
1429
+ this.page = 1;
1430
+ this.selectedPks = {};
1431
+ this.view = "list";
1432
+ await this.load();
1433
+ },
1434
+ /** @param {string} name */
1435
+ deleteView(name) {
1436
+ const V = /** @type {ViewsAPI} */ (/** @type {any} */ (window).StudioViews);
1437
+ if (!V) return;
1438
+ V.remove(name);
1439
+ this.savedViews = V.load();
1440
+ this.toastSuccess(this.tr("Deleted view: {name}", { name: name }));
1441
+ },
1442
+ }));
1443
+ });