@runic-artifex/vite-plugin-runic 0.19.0 → 0.20.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.
@@ -0,0 +1,273 @@
1
+ // Runic Inspect's translation editor (#957): the state of the "Edit" panel of a message, without the DOM. It reads the
2
+ // message from Runic Translations' in-page editing API (`GET /__runic-translations/message`, vite-plugin-runic-translations
3
+ // 0.12 under `vite dev`), keeps an edited text per locale, and writes one locale with the file hash it read (`POST`). The
4
+ // API answers 422 with diagnostics when the text does not compile, 409 with the current message when the file changed
5
+ // since the read, and 403 when this client is not allowed. The page then updates in place through the Translations
6
+ // text-change channel; the panel reads the message again when that channel changes and the text was not edited.
7
+ //
8
+ // `editReducer` is pure: inspect-editor.ts renders a state and sends what `saveRequest` returns.
9
+ /** The panel's first state, for a message the overview lists; `locale` is the one the page shows. */
10
+ export function startEdit(message) {
11
+ return { status: "loading", catalog: message.catalog, key: message.key, locale: message.locale ?? "", drafts: {}, hashes: {}, diagnostics: [] };
12
+ }
13
+ /** The locale's text as read: its source, or empty for a locale without text of its own. */
14
+ export function readText(state, locale = state.locale) {
15
+ return state.message?.locales.find((entry) => entry.locale === locale)?.text ?? "";
16
+ }
17
+ /** The text being edited in a locale. */
18
+ export function draftText(state, locale = state.locale) {
19
+ return state.drafts[locale] ?? readText(state, locale);
20
+ }
21
+ /** Whether a locale's text differs from what was read. */
22
+ export function isDirty(state, locale = state.locale) {
23
+ return draftText(state, locale) !== readText(state, locale);
24
+ }
25
+ /** Whether any locale has an edited text that was not saved. */
26
+ export function hasEdits(state) {
27
+ return Object.keys(state.drafts).some((locale) => isDirty(state, locale));
28
+ }
29
+ /** The locale entry being edited. */
30
+ export function currentLocale(state) {
31
+ return state.message?.locales.find((entry) => entry.locale === state.locale);
32
+ }
33
+ /** Whether Save does something now. */
34
+ export function canSave(state) {
35
+ const locale = currentLocale(state);
36
+ return locale !== undefined && locale.editable && isDirty(state)
37
+ && (state.status === "ready" || state.status === "saved" || state.status === "invalid");
38
+ }
39
+ /** The POST body for the current locale. */
40
+ export function saveRequest(state) {
41
+ return {
42
+ catalog: state.message?.catalog ?? state.catalog, key: state.message?.key ?? state.key, locale: state.locale,
43
+ text: draftText(state), expectedHash: state.hashes[state.locale] ?? "none",
44
+ };
45
+ }
46
+ export function editReducer(state, event) {
47
+ switch (event.type) {
48
+ case "read": {
49
+ const message = event.reply.status === 200 ? parseEditMessage(event.reply.body?.message) : undefined;
50
+ if (message === undefined)
51
+ return refused(state, event.reply, "loading");
52
+ const locale = message.locales.some((entry) => entry.locale === state.locale) ? state.locale
53
+ : message.locales.find((entry) => entry.locale === message.baseLocale)?.locale ?? message.locales[0]?.locale ?? "";
54
+ return { ...state, status: "ready", message, locale, drafts: {}, hashes: hashesOf(message), diagnostics: [], ...clear };
55
+ }
56
+ case "refreshed": {
57
+ // Busy, or showing a conflict: the next action reads or writes anyway.
58
+ if (state.status === "saving" || state.status === "conflict" || state.status === "loading" || state.message === undefined)
59
+ return state;
60
+ const message = event.reply.status === 200 ? parseEditMessage(event.reply.body?.message) : undefined;
61
+ if (message === undefined)
62
+ return state;
63
+ return withMessage(state, message);
64
+ }
65
+ case "locale":
66
+ if (state.message === undefined || !state.message.locales.some((entry) => entry.locale === event.locale))
67
+ return state;
68
+ return { ...state, locale: event.locale, diagnostics: [], ...(state.status === "invalid" || state.status === "saved" ? { status: "ready" } : {}), ...clear };
69
+ case "input": {
70
+ if (state.message === undefined || state.status === "saving" || state.status === "loading")
71
+ return state;
72
+ const status = state.status === "saved" || state.status === "invalid" ? "ready" : state.status;
73
+ return { ...state, status, drafts: { ...state.drafts, [state.locale]: event.text }, ...(status === state.status ? {} : clear) };
74
+ }
75
+ case "revert": {
76
+ if (state.message === undefined || state.status === "saving")
77
+ return state;
78
+ const { [state.locale]: _removed, ...drafts } = state.drafts;
79
+ return { ...state, status: "ready", drafts, diagnostics: [], ...clear };
80
+ }
81
+ case "save":
82
+ return canSave(state) ? { ...state, status: "saving", diagnostics: [], ...clear } : state;
83
+ case "saved": {
84
+ if (state.status !== "saving")
85
+ return state;
86
+ const { status, body } = event.reply;
87
+ const reply = (body ?? {});
88
+ if (status === 200) {
89
+ const message = parseEditMessage(reply.message);
90
+ const written = Array.isArray(reply.written) ? reply.written.filter((path) => typeof path === "string") : [];
91
+ if (message === undefined)
92
+ return { ...state, status: "saved", written };
93
+ const { [state.locale]: _saved, ...drafts } = state.drafts;
94
+ return { ...withMessage({ ...state, drafts }, message), status: "saved", diagnostics: [], written, ...noConflict };
95
+ }
96
+ if (status === 409) {
97
+ const current = parseEditMessage(reply.message);
98
+ const locale = current?.locales.find((entry) => entry.locale === state.locale);
99
+ if (current === undefined || locale === undefined)
100
+ return { ...state, status: "failed", detail: detailOf(reply, "The file changed since it was read.") };
101
+ return { ...state, status: "conflict", diagnostics: [], conflict: { locale: state.locale, text: locale.text ?? "", hash: locale.file.hash, message: current },
102
+ detail: detailOf(reply, "The file changed since it was read.") };
103
+ }
104
+ if (status === 422) {
105
+ return { ...state, status: "invalid", diagnostics: parseDiagnostics(reply.diagnostics),
106
+ detail: detailOf(reply, reply.error === "unsupported" ? "This locale cannot be written." : "The text does not compile; nothing was written.") };
107
+ }
108
+ return refused(state, event.reply, "saving");
109
+ }
110
+ case "reapply": {
111
+ const conflict = state.conflict;
112
+ if (state.status !== "conflict" || conflict === undefined)
113
+ return state;
114
+ // The edited text stays; the hashes are the file's now, so the next Save writes over it.
115
+ return { ...state, status: "ready", message: conflict.message, hashes: hashesOf(conflict.message),
116
+ drafts: { ...state.drafts, [conflict.locale]: draftText(state, conflict.locale) }, diagnostics: [], ...clear };
117
+ }
118
+ case "discard": {
119
+ const conflict = state.conflict;
120
+ if (state.status !== "conflict" || conflict === undefined)
121
+ return state;
122
+ const { [conflict.locale]: _dropped, ...drafts } = state.drafts;
123
+ return { ...state, status: "ready", message: conflict.message, hashes: hashesOf(conflict.message), drafts, diagnostics: [], ...clear };
124
+ }
125
+ }
126
+ }
127
+ const noConflict = { conflict: undefined };
128
+ const clear = { conflict: undefined, detail: undefined, written: undefined };
129
+ // A message read again: the hashes are the file's now, and a locale whose text was not edited takes the new text.
130
+ function withMessage(state, message) {
131
+ const drafts = {};
132
+ for (const [locale, text] of Object.entries(state.drafts)) {
133
+ if (text !== readText(state, locale))
134
+ drafts[locale] = text;
135
+ }
136
+ const locale = message.locales.some((entry) => entry.locale === state.locale) ? state.locale : message.locales[0]?.locale ?? state.locale;
137
+ return { ...state, message, locale, drafts, hashes: hashesOf(message) };
138
+ }
139
+ function hashesOf(message) {
140
+ return Object.fromEntries(message.locales.map((entry) => [entry.locale, entry.file.hash]));
141
+ }
142
+ // A refused or failed request: 403 says who may edit; anything else keeps the message, if there is one, and says why.
143
+ function refused(state, reply, during) {
144
+ const body = (reply.body ?? {});
145
+ if (reply.status === 403) {
146
+ return { ...state, status: "forbidden", detail: detailOf(body, "The Translations dev server refused this client.") };
147
+ }
148
+ const fallback = reply.status === 0 ? "The request did not reach the development server."
149
+ : reply.status === 404 && during === "loading" ? "The Translations dev server has no editing API here (vite-plugin-runic-translations 0.12 or later in project mode, with inPageEditing on), or does not know this message."
150
+ : reply.status === 501 ? "In-page editing needs project mode (the project option of runicTranslations())."
151
+ : `The Translations dev server answered ${reply.status}.`;
152
+ return { ...state, status: "failed", detail: detailOf(body, fallback) };
153
+ }
154
+ function detailOf(body, fallback) {
155
+ return typeof body.detail === "string" && body.detail.length > 0 ? body.detail : fallback;
156
+ }
157
+ /** The API's `message`, with the members the panel uses checked; undefined for anything else. */
158
+ export function parseEditMessage(value) {
159
+ if (typeof value !== "object" || value === null)
160
+ return undefined;
161
+ const message = value;
162
+ if (typeof message.catalog !== "string" || typeof message.key !== "string" || !Array.isArray(message.locales))
163
+ return undefined;
164
+ const locales = message.locales.flatMap((item) => {
165
+ if (typeof item !== "object" || item === null)
166
+ return [];
167
+ const entry = item;
168
+ if (typeof entry.locale !== "string" || entry.locale.length === 0)
169
+ return [];
170
+ const file = (entry.file ?? {});
171
+ const source = entry.source;
172
+ const structure = parseStructure(entry.structure);
173
+ return [{
174
+ locale: entry.locale,
175
+ ...(typeof entry.fallback === "string" ? { fallback: entry.fallback } : {}),
176
+ origin: typeof entry.origin === "string" ? entry.origin : "catalog",
177
+ text: typeof entry.text === "string" ? entry.text : null,
178
+ ...(typeof source?.path === "string" && Number.isSafeInteger(source.line)
179
+ ? { source: { path: source.path, line: source.line, column: Number.isSafeInteger(source.column) ? source.column : 1 } } : {}),
180
+ file: {
181
+ path: typeof file.path === "string" ? file.path : "", exists: file.exists === true,
182
+ hash: typeof file.hash === "string" ? file.hash : "none",
183
+ },
184
+ editable: entry.editable === true,
185
+ ...(typeof entry.reason === "string" ? { reason: entry.reason } : {}),
186
+ ...(structure === undefined ? {} : { structure }),
187
+ }];
188
+ });
189
+ return {
190
+ catalog: message.catalog,
191
+ kind: typeof message.kind === "string" ? message.kind : "catalog",
192
+ ...(typeof message.package === "string" ? { package: message.package } : {}),
193
+ key: message.key,
194
+ ...(typeof message.logicalKey === "string" ? { logicalKey: message.logicalKey } : {}),
195
+ baseLocale: typeof message.baseLocale === "string" ? message.baseLocale : locales[0]?.locale ?? "",
196
+ ...(typeof message.content === "string" ? { content: message.content } : {}),
197
+ structured: message.structured === true,
198
+ inputs: Array.isArray(message.inputs) ? message.inputs.flatMap((input) => named(input)) : [],
199
+ markup: Array.isArray(message.markup) ? message.markup.flatMap((item) => typeof item === "string" ? [item]
200
+ : typeof item?.name === "string" ? [item.name] : []) : [],
201
+ locales,
202
+ };
203
+ }
204
+ function named(value) {
205
+ if (typeof value !== "object" || value === null || typeof value.name !== "string")
206
+ return [];
207
+ const { name, type, function: fn } = value;
208
+ return [{ name, ...(typeof type === "string" ? { type } : {}), ...(typeof fn === "string" ? { function: fn } : {}) }];
209
+ }
210
+ function strings(value) {
211
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
212
+ }
213
+ function parseStructure(value) {
214
+ if (typeof value !== "object" || value === null)
215
+ return undefined;
216
+ const structure = value;
217
+ return {
218
+ supported: structure.supported !== false,
219
+ inputs: Array.isArray(structure.inputs) ? structure.inputs.flatMap((input) => named(input)) : [],
220
+ selectors: strings(structure.selectors),
221
+ selectorFunctions: strings(structure.selectorFunctions),
222
+ variants: Array.isArray(structure.variants) ? structure.variants.flatMap((item) => {
223
+ const variant = item;
224
+ return variant !== null && typeof variant === "object" && typeof variant.pattern === "string"
225
+ ? [{ id: String(variant.id ?? ""), keys: strings(variant.keys), pattern: variant.pattern }] : [];
226
+ }) : [],
227
+ pluralCategories: strings(structure.pluralCategories),
228
+ };
229
+ }
230
+ function parseDiagnostics(value) {
231
+ if (!Array.isArray(value))
232
+ return [];
233
+ return value.flatMap((item) => {
234
+ const diagnostic = item;
235
+ if (diagnostic === null || typeof diagnostic !== "object" || typeof diagnostic.message !== "string")
236
+ return [];
237
+ return [{
238
+ code: typeof diagnostic.code === "string" ? diagnostic.code : "",
239
+ severity: typeof diagnostic.severity === "string" ? diagnostic.severity : "error",
240
+ message: diagnostic.message,
241
+ ...(typeof diagnostic.path === "string" ? { path: diagnostic.path } : {}),
242
+ ...(Number.isSafeInteger(diagnostic.line) ? { line: diagnostic.line } : {}),
243
+ ...(Number.isSafeInteger(diagnostic.column) ? { column: diagnostic.column } : {}),
244
+ ...(typeof diagnostic.helpUri === "string" ? { helpUri: diagnostic.helpUri } : {}),
245
+ }];
246
+ }).slice(0, 20);
247
+ }
248
+ /**
249
+ * What the structure of a locale's text is, in short lines for the panel: its inputs, how it selects (plural or
250
+ * selector, with the plural categories of the locale), its variants' keys and the markup it uses.
251
+ */
252
+ export function describeStructure(message, locale) {
253
+ const lines = [];
254
+ const structure = locale.structure;
255
+ const inputs = structure?.inputs.length ? structure.inputs : message.inputs;
256
+ if (inputs.length > 0) {
257
+ lines.push(`Inputs: ${inputs.map((input) => `$${input.name}${"function" in input && input.function ? ` :${input.function}` : input.type ? ` (${input.type})` : ""}`).join(", ")}`);
258
+ }
259
+ if (structure !== undefined && structure.selectors.length > 0) {
260
+ const how = structure.selectors.map((selector, index) => `$${selector}${structure.selectorFunctions[index] ? ` (${structure.selectorFunctions[index]})` : ""}`);
261
+ lines.push(`Selects on ${how.join(", ")}: ${structure.variants.map((variant) => variant.keys.join(" ")).join(" · ")}`);
262
+ if (structure.pluralCategories.length > 0) {
263
+ const covered = new Set(structure.variants.flatMap((variant) => variant.keys));
264
+ const missing = covered.has("*") ? [] : structure.pluralCategories.filter((category) => !covered.has(category));
265
+ lines.push(`Plural categories of ${locale.locale}: ${structure.pluralCategories.join(", ")}${missing.length === 0 ? "" : ` (no variant for ${missing.join(", ")})`}`);
266
+ }
267
+ }
268
+ if (message.markup.length > 0)
269
+ lines.push(`Markup: ${message.markup.map((name) => `{#${name}}`).join(" ")}`);
270
+ if (structure !== undefined && !structure.supported)
271
+ lines.push("Edited as MF2 source.");
272
+ return lines;
273
+ }
@@ -0,0 +1,34 @@
1
+ import { type EditState } from "./inspect-edit.js";
2
+ import type { RunicInspectLocation } from "./inspect-data.js";
3
+ export declare const editorStyles = "\n.editor { margin-top: 10px; padding-top: 8px; border-top: 1px solid #4b3f8f; }\n.editor:focus { outline: none; }\n.editor .head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }\n.editor .row { display: flex; gap: 6px; align-items: center; margin: 6px 0; flex-wrap: wrap; }\n.editor label { color: #b9b0ff; font-size: 11px; }\n.editor select, .editor textarea, .editor button.action {\n font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: #f4f2ff; background: #241f3d;\n border: 1px solid #4b3f8f; border-radius: 4px; }\n.editor select { padding: 2px 4px; }\n.editor textarea { width: 100%; min-height: 4.5em; resize: vertical; padding: 4px 6px; tab-size: 2; white-space: pre; }\n.editor textarea[readonly] { opacity: 0.7; }\n.editor button.action { cursor: pointer; padding: 2px 10px; }\n.editor button.action.primary { background: #4b3f8f; color: #fff; }\n.editor button.action:disabled { cursor: default; opacity: 0.5; }\n.editor select:focus-visible, .editor textarea:focus-visible, .editor button:focus-visible { outline: 2px solid #8fd3ff; outline-offset: 1px; }\n.editor .structure { color: #c8c3e6; }\n.editor .status { min-height: 1.4em; margin: 4px 0; }\n.editor .status.error { color: #ff9e9e; }\n.editor .status.ok { color: #9ee6b0; }\n.editor .diagnostics li { color: #ff9e9e; }\n.editor .conflict { border: 1px solid #b38b2e; border-radius: 4px; padding: 6px; margin: 6px 0; }\n.editor .conflict pre { margin: 4px 0; white-space: pre-wrap; overflow-wrap: anywhere;\n font: 11.5px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: #ffd98e; }\n.card button.edit { all: unset; cursor: pointer; color: #8fd3ff; text-decoration: underline; margin-left: 6px; }\n.card button.edit:focus-visible { outline: 2px solid #8fd3ff; outline-offset: 1px; }\n";
4
+ export interface MessageEditorOptions {
5
+ readonly base: string;
6
+ /** A file:line link (or, for a remote client, its text) for the panel's source location. */
7
+ readonly location: (location: RunicInspectLocation) => Node;
8
+ /** Called after a write was accepted, and when the panel closes. */
9
+ readonly onSaved?: () => void;
10
+ readonly onClose?: (returnFocus: boolean) => void;
11
+ }
12
+ export interface MessageEditor {
13
+ /** The panel's element; Runic Inspect keeps it in the card while the overview is rendered again. */
14
+ readonly root: HTMLElement;
15
+ readonly state: EditState | undefined;
16
+ /** Opens the panel on a message and reads it. */
17
+ open(message: {
18
+ readonly catalog: string;
19
+ readonly key: string;
20
+ readonly locale?: string;
21
+ }): Promise<void>;
22
+ close(returnFocus?: boolean): void;
23
+ /** Reads the message again when the page's text changed, unless the text is being edited. */
24
+ refresh(): Promise<void>;
25
+ /** Saves the current locale; resolves when the API answered. */
26
+ save(): Promise<void>;
27
+ readonly isOpen: boolean;
28
+ }
29
+ /** The message API's URL below Vite's base. */
30
+ export declare function messageApiUrl(base: string, query?: {
31
+ readonly catalog: string;
32
+ readonly key: string;
33
+ }): string;
34
+ export declare function createMessageEditor(options: MessageEditorOptions): MessageEditor;
@@ -0,0 +1,282 @@
1
+ // The "Edit" panel of Runic Inspect's overview (#957): plain DOM inside the overlay's shadow root, rendering the state of
2
+ // inspect-edit.ts. It edits a message's raw MF2 source per locale and saves it through Runic Translations' in-page
3
+ // editing API; the page then shows the new text in place, and the overview keeps its selection.
4
+ //
5
+ // Keyboard: Tab moves through the locale list, the text, Save and Revert; Ctrl+Enter (⌘+Enter) saves; Esc closes the
6
+ // panel (Runic Inspect's key handler hands it here) and returns the focus to the message's Edit button.
7
+ import { canSave, currentLocale, describeStructure, draftText, editReducer, isDirty, saveRequest, startEdit, } from "./inspect-edit.js";
8
+ const messagePath = "__runic-translations/message";
9
+ export const editorStyles = `
10
+ .editor { margin-top: 10px; padding-top: 8px; border-top: 1px solid #4b3f8f; }
11
+ .editor:focus { outline: none; }
12
+ .editor .head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
13
+ .editor .row { display: flex; gap: 6px; align-items: center; margin: 6px 0; flex-wrap: wrap; }
14
+ .editor label { color: #b9b0ff; font-size: 11px; }
15
+ .editor select, .editor textarea, .editor button.action {
16
+ font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: #f4f2ff; background: #241f3d;
17
+ border: 1px solid #4b3f8f; border-radius: 4px; }
18
+ .editor select { padding: 2px 4px; }
19
+ .editor textarea { width: 100%; min-height: 4.5em; resize: vertical; padding: 4px 6px; tab-size: 2; white-space: pre; }
20
+ .editor textarea[readonly] { opacity: 0.7; }
21
+ .editor button.action { cursor: pointer; padding: 2px 10px; }
22
+ .editor button.action.primary { background: #4b3f8f; color: #fff; }
23
+ .editor button.action:disabled { cursor: default; opacity: 0.5; }
24
+ .editor select:focus-visible, .editor textarea:focus-visible, .editor button:focus-visible { outline: 2px solid #8fd3ff; outline-offset: 1px; }
25
+ .editor .structure { color: #c8c3e6; }
26
+ .editor .status { min-height: 1.4em; margin: 4px 0; }
27
+ .editor .status.error { color: #ff9e9e; }
28
+ .editor .status.ok { color: #9ee6b0; }
29
+ .editor .diagnostics li { color: #ff9e9e; }
30
+ .editor .conflict { border: 1px solid #b38b2e; border-radius: 4px; padding: 6px; margin: 6px 0; }
31
+ .editor .conflict pre { margin: 4px 0; white-space: pre-wrap; overflow-wrap: anywhere;
32
+ font: 11.5px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: #ffd98e; }
33
+ .card button.edit { all: unset; cursor: pointer; color: #8fd3ff; text-decoration: underline; margin-left: 6px; }
34
+ .card button.edit:focus-visible { outline: 2px solid #8fd3ff; outline-offset: 1px; }
35
+ `;
36
+ /** The message API's URL below Vite's base. */
37
+ export function messageApiUrl(base, query) {
38
+ const prefix = base.endsWith("/") ? base : `${base}/`;
39
+ const path = `${/^https?:/iu.test(prefix) ? new URL(prefix).pathname : prefix}${messagePath}`;
40
+ return query === undefined ? path : `${path}?key=${encodeURIComponent(query.key)}&catalog=${encodeURIComponent(query.catalog)}`;
41
+ }
42
+ async function reply(response) {
43
+ try {
44
+ const answer = await response;
45
+ let body;
46
+ try {
47
+ body = await answer.json();
48
+ }
49
+ catch {
50
+ body = undefined;
51
+ }
52
+ return { status: answer.status, body };
53
+ }
54
+ catch {
55
+ return { status: 0 };
56
+ }
57
+ }
58
+ export function createMessageEditor(options) {
59
+ let state;
60
+ let generation = 0;
61
+ const element = (tag, className, text) => {
62
+ const created = document.createElement(tag);
63
+ if (className !== undefined)
64
+ created.className = className;
65
+ if (text !== undefined)
66
+ created.textContent = text;
67
+ return created;
68
+ };
69
+ const root = element("section", "editor");
70
+ root.tabIndex = -1;
71
+ root.hidden = true;
72
+ const head = element("div", "head");
73
+ const title = element("h3");
74
+ const close = element("button", "close", "×");
75
+ close.type = "button";
76
+ close.setAttribute("aria-label", "Close the editor");
77
+ head.append(title, close);
78
+ const localeRow = element("div", "row");
79
+ const localeLabel = element("label", undefined, "Locale");
80
+ const localeSelect = element("select");
81
+ localeSelect.id = "runic-inspect-edit-locale";
82
+ localeLabel.htmlFor = localeSelect.id;
83
+ const where = element("span", "muted");
84
+ localeRow.append(localeLabel, localeSelect, where);
85
+ const structure = element("ul", "structure");
86
+ const textLabel = element("label", undefined, "MF2 source");
87
+ const textarea = element("textarea");
88
+ textarea.id = "runic-inspect-edit-text";
89
+ textarea.spellcheck = false;
90
+ textarea.setAttribute("autocomplete", "off");
91
+ textarea.setAttribute("autocapitalize", "off");
92
+ textarea.setAttribute("aria-keyshortcuts", "Control+Enter Meta+Enter");
93
+ textLabel.htmlFor = textarea.id;
94
+ const conflict = element("div", "conflict");
95
+ conflict.setAttribute("role", "group");
96
+ conflict.setAttribute("aria-label", "Conflict");
97
+ const conflictText = element("p");
98
+ const conflictCurrent = element("pre");
99
+ const reapply = element("button", "action", "Reapply my text");
100
+ const discard = element("button", "action", "Use the file's text");
101
+ reapply.type = discard.type = "button";
102
+ const conflictRow = element("div", "row");
103
+ conflictRow.append(reapply, discard);
104
+ conflict.append(conflictText, conflictCurrent, conflictRow);
105
+ const diagnostics = element("ul", "diagnostics");
106
+ const status = element("p", "status");
107
+ status.setAttribute("role", "status");
108
+ status.setAttribute("aria-live", "polite");
109
+ const actions = element("div", "row");
110
+ const saveButton = element("button", "action primary", "Save");
111
+ saveButton.type = "button";
112
+ saveButton.title = "Save (Ctrl+Enter)";
113
+ const revert = element("button", "action", "Revert");
114
+ revert.type = "button";
115
+ actions.append(saveButton, revert);
116
+ root.append(head, localeRow, structure, textLabel, textarea, conflict, diagnostics, status, actions);
117
+ function dispatch(event) {
118
+ if (state === undefined)
119
+ return;
120
+ state = editReducer(state, event);
121
+ render();
122
+ }
123
+ function render() {
124
+ if (state === undefined)
125
+ return;
126
+ const current = currentLocale(state);
127
+ const message = state.message;
128
+ title.replaceChildren("Edit ", Object.assign(element("code"), { textContent: `${state.catalog}:${state.key}` }));
129
+ root.setAttribute("aria-label", `Edit ${state.catalog}:${state.key}`);
130
+ // The locale list, base locale first, as the API lists them.
131
+ const locales = message?.locales ?? [];
132
+ if (localeSelect.options.length !== locales.length || locales.some((entry, index) => localeSelect.options[index]?.value !== entry.locale)) {
133
+ localeSelect.replaceChildren(...locales.map((entry) => {
134
+ const option = element("option", undefined, `${entry.locale}${entry.locale === message?.baseLocale ? " (base)" : ""}${entry.origin === "missing" ? " (missing)" : entry.origin === "override" ? " (override)" : entry.origin === "library" ? " (library)" : ""}`);
135
+ option.value = entry.locale;
136
+ return option;
137
+ }));
138
+ }
139
+ for (const option of localeSelect.options) {
140
+ const entry = locales.find((candidate) => candidate.locale === option.value);
141
+ const dirty = entry !== undefined && isDirty(state, entry.locale);
142
+ option.textContent = option.textContent.replace(/ ●$/u, "") + (dirty ? " ●" : "");
143
+ }
144
+ localeSelect.value = state.locale;
145
+ localeSelect.disabled = locales.length === 0 || state.status === "saving";
146
+ where.replaceChildren(...(current?.source === undefined && current?.file.path === undefined ? [] : [
147
+ " ", options.location({
148
+ editor: "translations", file: current.source?.path ?? current.file.path, line: current.source?.line ?? 1, column: current.source?.column ?? 1,
149
+ message: { catalog: state.catalog, key: state.key, locale: current.locale },
150
+ }),
151
+ ...(current.file.path !== "" && current.source !== undefined && current.file.path !== current.source.path
152
+ ? [element("span", "muted", ` · saves to ${current.file.path.split(/[\\/]/u).slice(-3).join("/")}`)] : []),
153
+ ]));
154
+ structure.replaceChildren(...(message === undefined || current === undefined ? [] : describeStructure(message, current))
155
+ .map((line) => element("li", undefined, line)));
156
+ // The text: typing makes the draft what the field shows, so the field is set only when the draft differs (another
157
+ // locale, a read, Revert, a conflict's choice), and the caret stays while typing.
158
+ const text = draftText(state);
159
+ if (textarea.value !== text)
160
+ textarea.value = text;
161
+ textarea.readOnly = current === undefined || !current.editable || state.status === "saving" || state.status === "conflict";
162
+ textarea.rows = Math.min(12, Math.max(3, text.split("\n").length + 1));
163
+ // Conflict: the file's text now, and the two ways on.
164
+ conflict.hidden = state.status !== "conflict";
165
+ if (state.conflict !== undefined) {
166
+ conflictText.textContent = `${state.detail ?? "The file changed since it was read."} In the file now:`;
167
+ conflictCurrent.textContent = state.conflict.text;
168
+ }
169
+ diagnostics.replaceChildren(...state.diagnostics.map((diagnostic) => element("li", undefined, `${diagnostic.code}${diagnostic.line === undefined ? "" : ` line ${diagnostic.line}${diagnostic.column === undefined ? "" : `:${diagnostic.column}`}`}: ${diagnostic.message}`)));
170
+ diagnostics.setAttribute("role", state.diagnostics.length > 0 ? "alert" : "list");
171
+ const [statusText, tone] = statusLine(state);
172
+ status.textContent = statusText;
173
+ status.className = `status${tone === undefined ? "" : ` ${tone}`}`;
174
+ saveButton.disabled = !canSave(state);
175
+ saveButton.textContent = state.status === "saving" ? "Saving…" : "Save";
176
+ revert.disabled = !isDirty(state) || state.status === "saving";
177
+ root.dataset["status"] = state.status;
178
+ }
179
+ function statusLine(current) {
180
+ const locale = currentLocale(current);
181
+ switch (current.status) {
182
+ case "loading": return ["Reading the message…", undefined];
183
+ case "saving": return ["Saving…", undefined];
184
+ case "saved": return [`Saved to ${(current.written ?? []).map((path) => path.split(/[\\/]/u).pop()).join(", ") || "its source"}; the page shows it in place.`, "ok"];
185
+ case "invalid": return [current.detail ?? "The text does not compile; nothing was written.", "error"];
186
+ case "conflict": return ["Reapply your text over the file's, or take the file's text.", "error"];
187
+ case "forbidden": return [`${current.detail ?? "Not allowed."} To edit from another machine, start the dev server with RUNIC_DEV_ALLOW listing this machine or its network (or runicTranslations({ inPageEditing: { allow } })).`, "error"];
188
+ case "failed": return [current.detail ?? "The request failed.", "error"];
189
+ case "ready":
190
+ if (locale !== undefined && !locale.editable)
191
+ return [locale.reason ?? "This locale cannot be written here.", "error"];
192
+ if (locale?.origin === "missing")
193
+ return [`${locale.locale} has no text of its own${locale.fallback ? ` (shows ${locale.fallback})` : ""}; saving adds it beside the base locale's.`, undefined];
194
+ if (locale?.origin === "library")
195
+ return ["The library's own text: saving writes the application's override, not the installed package.", undefined];
196
+ return [isDirty(current) ? "Edited; Save writes it to the source." : "", undefined];
197
+ }
198
+ }
199
+ async function read(event) {
200
+ if (state === undefined)
201
+ return;
202
+ const pending = ++generation;
203
+ const answer = await reply(fetch(messageApiUrl(options.base, state), { credentials: "same-origin", cache: "no-store" }));
204
+ if (pending !== generation || state === undefined)
205
+ return;
206
+ dispatch({ type: event, reply: answer });
207
+ if (event === "read" && state?.status === "ready" && root.isConnected)
208
+ textarea.focus();
209
+ }
210
+ async function save() {
211
+ if (state === undefined || !canSave(state))
212
+ return;
213
+ const body = saveRequest(state);
214
+ dispatch({ type: "save" });
215
+ const pending = ++generation;
216
+ const answer = await reply(fetch(messageApiUrl(options.base), {
217
+ method: "POST", credentials: "same-origin", cache: "no-store",
218
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
219
+ body: JSON.stringify(body),
220
+ }));
221
+ if (pending !== generation)
222
+ return;
223
+ dispatch({ type: "saved", reply: answer });
224
+ if (state?.status === "saved")
225
+ options.onSaved?.();
226
+ else if (state?.status === "conflict")
227
+ reapply.focus();
228
+ }
229
+ close.addEventListener("click", () => editor.close(true));
230
+ localeSelect.addEventListener("change", () => {
231
+ dispatch({ type: "locale", locale: localeSelect.value });
232
+ });
233
+ textarea.addEventListener("input", () => dispatch({ type: "input", text: textarea.value }));
234
+ textarea.addEventListener("keydown", (event) => {
235
+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
236
+ event.preventDefault();
237
+ void save();
238
+ }
239
+ });
240
+ saveButton.addEventListener("click", () => void save());
241
+ revert.addEventListener("click", () => {
242
+ dispatch({ type: "revert" });
243
+ textarea.focus();
244
+ });
245
+ reapply.addEventListener("click", () => {
246
+ dispatch({ type: "reapply" });
247
+ textarea.focus();
248
+ });
249
+ discard.addEventListener("click", () => {
250
+ dispatch({ type: "discard" });
251
+ textarea.focus();
252
+ });
253
+ const editor = {
254
+ root,
255
+ get state() { return state; },
256
+ get isOpen() { return !root.hidden; },
257
+ async open(message) {
258
+ generation++;
259
+ state = startEdit(message);
260
+ textarea.value = "";
261
+ root.hidden = false;
262
+ render();
263
+ root.focus();
264
+ await read("read");
265
+ },
266
+ close(returnFocus = false) {
267
+ if (root.hidden)
268
+ return;
269
+ generation++;
270
+ root.hidden = true;
271
+ state = undefined;
272
+ options.onClose?.(returnFocus);
273
+ },
274
+ async refresh() {
275
+ if (state === undefined || root.hidden || state.status === "loading" || state.status === "saving")
276
+ return;
277
+ await read("refreshed");
278
+ },
279
+ save,
280
+ };
281
+ return editor;
282
+ }