String packs: translate mode. Strings carry an invisible key marker, a click on a word opens an editor that checks the edit with the pack rules, edits collect in the tab as a draft pack that applies after a reload, and "Copy pack file" gives the pack; the Languages section switches it on (the delivery then carries the whole inventory, packs or not); native code accepts such a delivery without packs
This commit is contained in:
parent
3c60e6a43c
commit
4c25fc0f4f
8 changed files with 359 additions and 6 deletions
|
|
@ -302,12 +302,17 @@ impl StringsStore {
|
||||||
}
|
}
|
||||||
let value: serde_json::Value = serde_json::from_str(text).map_err(|_| "VALIDATION: the delivery is not JSON")?;
|
let value: serde_json::Value = serde_json::from_str(text).map_err(|_| "VALIDATION: the delivery is not JSON")?;
|
||||||
let inventory = value.get("inventory").filter(|v| v.is_object()).cloned();
|
let inventory = value.get("inventory").filter(|v| v.is_object()).cloned();
|
||||||
let packs = value.get("packs").filter(|v| v.as_array().is_some_and(|packs| !packs.is_empty() && packs.len() <= MAX_ENABLED)).cloned();
|
// Translate mode may run without any pack (the author starts from the site's own words).
|
||||||
|
let translate = value.get("translate").and_then(serde_json::Value::as_bool).unwrap_or(false);
|
||||||
|
let packs = value.get("packs").filter(|v| v.as_array().is_some_and(|packs| (translate || !packs.is_empty()) && packs.len() <= MAX_ENABLED)).cloned();
|
||||||
let (Some(inventory), Some(packs)) = (inventory, packs) else {
|
let (Some(inventory), Some(packs)) = (inventory, packs) else {
|
||||||
return Err("VALIDATION: a delivery is { inventory, packs } with 1 to 8 packs".into());
|
return Err("VALIDATION: a delivery is { inventory, packs } with 1 to 8 packs".into());
|
||||||
};
|
};
|
||||||
stored.insert("inventory".into(), inventory);
|
stored.insert("inventory".into(), inventory);
|
||||||
stored.insert("packs".into(), packs);
|
stored.insert("packs".into(), packs);
|
||||||
|
if translate {
|
||||||
|
stored.insert("translate".into(), true.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
stored.insert("rev".into(), rev.into());
|
stored.insert("rev".into(), rev.into());
|
||||||
let text = serde_json::Value::Object(stored).to_string();
|
let text = serde_json::Value::Object(stored).to_string();
|
||||||
|
|
@ -402,6 +407,7 @@ mod tests {
|
||||||
assert_eq!(store.delivery().as_deref(), Some(stored.as_str()));
|
assert_eq!(store.delivery().as_deref(), Some(stored.as_str()));
|
||||||
assert!(store.set_delivery(Some("[]"), 8).is_err());
|
assert!(store.set_delivery(Some("[]"), 8).is_err());
|
||||||
assert!(store.set_delivery(Some(r#"{"inventory":{},"packs":[]}"#), 8).is_err(), "no packs is None, not an empty list");
|
assert!(store.set_delivery(Some(r#"{"inventory":{},"packs":[]}"#), 8).is_err(), "no packs is None, not an empty list");
|
||||||
|
assert_eq!(store.set_delivery(Some(r#"{"inventory":{},"packs":[],"translate":true}"#), 8).unwrap(), r#"{"inventory":{},"packs":[],"rev":8,"translate":true}"#, "translate mode may start without a pack");
|
||||||
assert_eq!(store.list().packs.len(), 2, "the delivery file is not a pack");
|
assert_eq!(store.list().packs.len(), 2, "the delivery file is not a pack");
|
||||||
assert_eq!(store.set_delivery(None, 9).unwrap(), r#"{"rev":9}"#);
|
assert_eq!(store.set_delivery(None, 9).unwrap(), r#"{"rev":9}"#);
|
||||||
store.remove("second").unwrap();
|
store.remove("second").unwrap();
|
||||||
|
|
|
||||||
|
|
@ -74,6 +74,11 @@ export type StringPacksOptions = {
|
||||||
settleMs?: number;
|
settleMs?: number;
|
||||||
/** Called once per catalog when its status is decided (`ok` as soon as it is reached). */
|
/** Called once per catalog when its status is decided (`ok` as soon as it is reached). */
|
||||||
onStatus?: (report: CatalogReport) => void;
|
onStatus?: (report: CatalogReport) => void;
|
||||||
|
/**
|
||||||
|
* Translate mode: every value passes through here after the packs (the marker of
|
||||||
|
* stringPackTranslate.ts), and the catalog is hooked even without a usable pack.
|
||||||
|
*/
|
||||||
|
mark?: (id: string, value: unknown) => unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
type TimerWindow = { setTimeout(handler: () => void, ms: number): unknown; clearTimeout(id: never): void };
|
type TimerWindow = { setTimeout(handler: () => void, ms: number): unknown; clearTimeout(id: never): void };
|
||||||
|
|
@ -97,7 +102,7 @@ export function installStringPacks(win: Window, setups: readonly CatalogSetup[],
|
||||||
const usable = packs.filter(pack => pack.values.size > 0);
|
const usable = packs.filter(pack => pack.values.size > 0);
|
||||||
return {
|
return {
|
||||||
catalog: setup.adapter.catalog, adapter: setup.adapter, packs, refused, usable,
|
catalog: setup.adapter.catalog, adapter: setup.adapter, packs, refused, usable,
|
||||||
engine: usable.length ? createStringEngine(setup.inventory, usable) : null,
|
engine: usable.length || options.mark ? createStringEngine(setup.inventory, usable) : null,
|
||||||
seen: {} as Record<string, number>, languages: new Set<string>(), keys: 0, settled: false, told: false,
|
seen: {} as Record<string, number>, languages: new Set<string>(), keys: 0, settled: false, told: false,
|
||||||
remove: null as null | (() => void),
|
remove: null as null | (() => void),
|
||||||
};
|
};
|
||||||
|
|
@ -133,7 +138,8 @@ export function installStringPacks(win: Window, setups: readonly CatalogSetup[],
|
||||||
resolve(id, original) {
|
resolve(id, original) {
|
||||||
try {
|
try {
|
||||||
state.keys += 1;
|
state.keys += 1;
|
||||||
const value = engine.resolve(id, original);
|
const resolved = engine.resolve(id, original);
|
||||||
|
const value = options.mark ? options.mark(id, resolved) : resolved;
|
||||||
if (state.keys === 1) tell(state);
|
if (state.keys === 1) tell(state);
|
||||||
return value;
|
return value;
|
||||||
} catch {
|
} catch {
|
||||||
|
|
|
||||||
270
packages/runtime/src/stringPackTranslate.ts
Normal file
270
packages/runtime/src/stringPackTranslate.ts
Normal file
|
|
@ -0,0 +1,270 @@
|
||||||
|
// Translate mode for string packs (published as `waybetter/runtime/stringPackTranslate`): the site's
|
||||||
|
// strings carry an invisible marker naming their key, so clicking a word on the page tells which
|
||||||
|
// key it is. The author types a replacement (checked with the pack rules right there), the edits
|
||||||
|
// collect in the tab as a draft pack that applies on the next reload, and Export copies the pack
|
||||||
|
// file. Nothing leaves the page; the draft lives in the tab's session storage.
|
||||||
|
//
|
||||||
|
// The markers change the site's text (invisible characters at the end of each string), so exact
|
||||||
|
// comparisons in the site's own code may notice: translate mode is for authors, never on by default,
|
||||||
|
// and leaving it reloads the page without markers.
|
||||||
|
import { compilePack, inventoryLookup, validateString, type InventoryLookup, type PageInventory, type StringPack } from './stringPacks.ts';
|
||||||
|
|
||||||
|
const START = '';
|
||||||
|
const DIGITS = ['', '', '', ''];
|
||||||
|
const MARKED = /([]+)/g;
|
||||||
|
|
||||||
|
export type Marker = {
|
||||||
|
/** The value with its key's marker (strings, and functions whose result is a string). */
|
||||||
|
mark(id: string, value: unknown): unknown;
|
||||||
|
/** The keys marked in a text, in order. */
|
||||||
|
ids(text: string): string[];
|
||||||
|
/** The text without markers. */
|
||||||
|
strip(text: string): string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createMarker(): Marker {
|
||||||
|
const ids: string[] = [];
|
||||||
|
const index = new Map<string, number>();
|
||||||
|
const code = (id: string) => {
|
||||||
|
let n = index.get(id);
|
||||||
|
if (n === undefined) { n = ids.length; ids.push(id); index.set(id, n); }
|
||||||
|
let digits = '';
|
||||||
|
do { digits = DIGITS[n % 4] + digits; n = Math.floor(n / 4); } while (n);
|
||||||
|
return START + digits + START;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
mark(id, value) {
|
||||||
|
if (typeof value === 'string') return value + code(id);
|
||||||
|
if (typeof value === 'function') {
|
||||||
|
const original = value as (...args: unknown[]) => unknown;
|
||||||
|
return function (this: unknown, ...args: unknown[]) {
|
||||||
|
const out = original.apply(this, args);
|
||||||
|
return typeof out === 'string' ? out + code(id) : out;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
ids(text) {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const match of text.matchAll(MARKED)) {
|
||||||
|
let n = 0;
|
||||||
|
for (const ch of match[1]!) n = n * 4 + DIGITS.indexOf(ch);
|
||||||
|
const id = ids[n];
|
||||||
|
if (id && !out.includes(id)) out.push(id);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
strip: text => text.replace(MARKED, ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The author's edits in this tab. */
|
||||||
|
export type TranslateDraft = { language: string; name: string; strings: Record<string, string> };
|
||||||
|
|
||||||
|
export const DRAFT_KEY = 'wayBetter.translateDraft';
|
||||||
|
|
||||||
|
export function readDraft(storage: Pick<Storage, 'getItem'>): TranslateDraft | null {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(storage.getItem(DRAFT_KEY) ?? 'null') as TranslateDraft | null;
|
||||||
|
return value && typeof value === 'object' && typeof value.strings === 'object' && value.strings !== null ? value : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The draft as a pack document for `site`/`catalog`. */
|
||||||
|
export function draftPack(draft: TranslateDraft, site: string, catalog: string): StringPack {
|
||||||
|
return {
|
||||||
|
format: 1, site, catalog, language: draft.language || 'en-x-draft', name: draft.name || 'My strings', authors: ['Me'],
|
||||||
|
version: '0.1.0', strings: { ...draft.strings },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks one edit against the key's shape; `null` when it can be used. */
|
||||||
|
export function checkEdit(lookup: InventoryLookup, id: string, value: string): string | null {
|
||||||
|
const shape = lookup(id);
|
||||||
|
if (!shape) return 'this key is not in the inventory';
|
||||||
|
const result = validateString(shape, value);
|
||||||
|
return 'reason' in result ? result.reason : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TranslateWords = {
|
||||||
|
bar: string; hint: string; edits(count: number): string; exportPack: string; copied: string; exit: string; reload: string;
|
||||||
|
key: string; original: string; parameters: string; save: string; cancel: string; remove: string; notTranslatable: string; choose: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** English defaults (the app passes its own words). */
|
||||||
|
export const TRANSLATE_WORDS: TranslateWords = {
|
||||||
|
bar: 'Translate mode', hint: 'Click a word to change it.', edits: count => `${count} ${count === 1 ? 'edit' : 'edits'}`,
|
||||||
|
exportPack: 'Copy pack file', copied: 'Pack file copied', exit: 'Leave', reload: 'Reload to see it',
|
||||||
|
key: 'Key', original: 'Now', parameters: 'Parameters', save: 'Save', cancel: 'Cancel', remove: 'Remove edit',
|
||||||
|
notTranslatable: 'This string cannot be changed by a pack yet.', choose: 'Which one?',
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TranslateUiOptions = {
|
||||||
|
inventory: PageInventory;
|
||||||
|
marker: Marker;
|
||||||
|
site: string;
|
||||||
|
catalog: string;
|
||||||
|
words?: Partial<TranslateWords>;
|
||||||
|
/** Leaves translate mode (the app drops the flag and reloads). */
|
||||||
|
exit(): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CSS = `
|
||||||
|
:host { all: initial; }
|
||||||
|
.bar { position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 2147483646; display: flex; gap: 10px; align-items: center;
|
||||||
|
padding: 8px 12px; border-radius: 12px; background: #111827; color: #f9fafb; font: 13px/1.3 system-ui, sans-serif; box-shadow: 0 8px 24px rgba(0,0,0,.35); }
|
||||||
|
.bar b { font-weight: 600; } .bar span { color: #cbd5e1; }
|
||||||
|
button { font: inherit; border: 0; border-radius: 8px; padding: 6px 10px; cursor: pointer; background: #334155; color: #f9fafb; }
|
||||||
|
button.primary { background: #2563eb; }
|
||||||
|
.pop { position: fixed; z-index: 2147483647; width: 360px; max-width: calc(100vw - 24px); padding: 12px; border-radius: 12px; background: #fff; color: #111827;
|
||||||
|
font: 13px/1.4 system-ui, sans-serif; box-shadow: 0 12px 32px rgba(0,0,0,.3); display: grid; gap: 8px; }
|
||||||
|
.pop small { color: #475569; } .pop code { font-size: 12px; color: #334155; }
|
||||||
|
.pop textarea { width: 100%; box-sizing: border-box; min-height: 64px; font: inherit; padding: 6px; border: 1px solid #cbd5e1; border-radius: 8px; }
|
||||||
|
.pop .row { display: flex; gap: 8px; justify-content: flex-end; } .pop .err { color: #b91c1c; }
|
||||||
|
.pop .pick { display: grid; gap: 4px; } .pop .pick button { text-align: left; background: #e2e8f0; color: #111827; }
|
||||||
|
`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The page part of translate mode: a bar (edits, copy the pack file, leave) and an editor for the
|
||||||
|
* string under a click. Clicks on marked text are the editor's while the mode is on.
|
||||||
|
*/
|
||||||
|
export function installTranslateUi(win: Window, options: TranslateUiOptions): { dispose(): void } {
|
||||||
|
const doc = win.document;
|
||||||
|
const words = { ...TRANSLATE_WORDS, ...options.words };
|
||||||
|
const lookup = inventoryLookup(options.inventory);
|
||||||
|
const storage = win.sessionStorage;
|
||||||
|
const draft = (): TranslateDraft => readDraft(storage) ?? { language: '', name: '', strings: {} };
|
||||||
|
const save = (next: TranslateDraft) => { try { storage.setItem(DRAFT_KEY, JSON.stringify(next)); } catch { /* storage full or blocked */ } };
|
||||||
|
|
||||||
|
const host = doc.createElement('wb-translate');
|
||||||
|
const root = host.attachShadow({ mode: 'open' });
|
||||||
|
const style = doc.createElement('style');
|
||||||
|
style.textContent = CSS;
|
||||||
|
root.append(style);
|
||||||
|
const bar = doc.createElement('div');
|
||||||
|
bar.className = 'bar';
|
||||||
|
root.append(bar);
|
||||||
|
let pop: HTMLElement | null = null;
|
||||||
|
let changed = false;
|
||||||
|
|
||||||
|
const button = (label: string, onClick: () => void, primary = false) => {
|
||||||
|
const el = doc.createElement('button');
|
||||||
|
el.textContent = label;
|
||||||
|
if (primary) el.className = 'primary';
|
||||||
|
el.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); onClick(); });
|
||||||
|
return el;
|
||||||
|
};
|
||||||
|
const renderBar = () => {
|
||||||
|
bar.replaceChildren();
|
||||||
|
const title = doc.createElement('b');
|
||||||
|
title.textContent = words.bar;
|
||||||
|
const hint = doc.createElement('span');
|
||||||
|
hint.textContent = `${words.hint} · ${words.edits(Object.keys(draft().strings).length)}`;
|
||||||
|
bar.append(title, hint);
|
||||||
|
if (changed) bar.append(button(words.reload, () => win.location.reload(), true));
|
||||||
|
bar.append(button(words.exportPack, () => {
|
||||||
|
const text = JSON.stringify(draftPack(draft(), options.site, options.catalog), null, 2);
|
||||||
|
void win.navigator.clipboard?.writeText(text).then(() => { hint.textContent = words.copied; }).catch(() => {});
|
||||||
|
}));
|
||||||
|
bar.append(button(words.exit, options.exit));
|
||||||
|
};
|
||||||
|
const closePop = () => { pop?.remove(); pop = null; };
|
||||||
|
|
||||||
|
const edit = (id: string, x: number, y: number, now: string) => {
|
||||||
|
closePop();
|
||||||
|
pop = doc.createElement('div');
|
||||||
|
pop.className = 'pop';
|
||||||
|
pop.style.left = `${Math.max(12, Math.min(x, win.innerWidth - 372))}px`;
|
||||||
|
pop.style.top = `${Math.max(12, Math.min(y + 12, win.innerHeight - 260))}px`;
|
||||||
|
const shape = lookup(id);
|
||||||
|
const head = doc.createElement('small');
|
||||||
|
head.textContent = `${words.key}: `;
|
||||||
|
const code = doc.createElement('code');
|
||||||
|
code.textContent = id;
|
||||||
|
head.append(code);
|
||||||
|
const current = doc.createElement('div');
|
||||||
|
current.textContent = `${words.original}: ${now}`;
|
||||||
|
pop.append(head, current);
|
||||||
|
if (!shape || (shape.kind !== 'text' && shape.kind !== 'message')) {
|
||||||
|
const note = doc.createElement('div');
|
||||||
|
note.textContent = words.notTranslatable;
|
||||||
|
pop.append(note, button(words.cancel, closePop));
|
||||||
|
root.append(pop);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (shape.params?.length) {
|
||||||
|
const params = doc.createElement('small');
|
||||||
|
params.textContent = `${words.parameters}: ${shape.params.map(name => `{${name}}${shape.plural?.includes(name) ? ' (plural)' : ''}`).join(', ')}`;
|
||||||
|
pop.append(params);
|
||||||
|
}
|
||||||
|
const input = doc.createElement('textarea');
|
||||||
|
input.value = draft().strings[id] ?? now;
|
||||||
|
const error = doc.createElement('div');
|
||||||
|
error.className = 'err';
|
||||||
|
const row = doc.createElement('div');
|
||||||
|
row.className = 'row';
|
||||||
|
if (draft().strings[id] !== undefined) {
|
||||||
|
row.append(button(words.remove, () => { const next = draft(); delete next.strings[id]; save(next); changed = true; closePop(); renderBar(); }));
|
||||||
|
}
|
||||||
|
row.append(button(words.cancel, closePop), button(words.save, () => {
|
||||||
|
const value = input.value.trim();
|
||||||
|
const problem = checkEdit(lookup, id, value);
|
||||||
|
if (problem) { error.textContent = problem; return; }
|
||||||
|
const next = draft();
|
||||||
|
next.strings[id] = value;
|
||||||
|
save(next);
|
||||||
|
changed = true;
|
||||||
|
closePop();
|
||||||
|
renderBar();
|
||||||
|
}, true));
|
||||||
|
pop.append(input, error, row);
|
||||||
|
root.append(pop);
|
||||||
|
input.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The marked keys at a click: the element's own text and labels, then up to three parents. */
|
||||||
|
const keysAt = (target: Element | null) => {
|
||||||
|
for (let el = target, depth = 0; el && depth < 4; el = el.parentElement, depth += 1) {
|
||||||
|
const texts = [el.textContent ?? '', el.getAttribute('aria-label') ?? '', el.getAttribute('placeholder') ?? '', el.getAttribute('title') ?? ''];
|
||||||
|
const found = texts.flatMap(text => options.marker.ids(text).map(id => ({ id, text: options.marker.strip(text) })));
|
||||||
|
if (found.length) return found.filter((item, i) => found.findIndex(other => other.id === item.id) === i).slice(0, 8);
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
const onClick = (event: MouseEvent) => {
|
||||||
|
if (event.composedPath().includes(host)) return;
|
||||||
|
const found = keysAt(event.target as Element | null);
|
||||||
|
if (!found.length) return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
if (found.length === 1) { edit(found[0]!.id, event.clientX, event.clientY, found[0]!.text); return; }
|
||||||
|
closePop();
|
||||||
|
pop = doc.createElement('div');
|
||||||
|
pop.className = 'pop';
|
||||||
|
pop.style.left = `${Math.max(12, Math.min(event.clientX, win.innerWidth - 372))}px`;
|
||||||
|
pop.style.top = `${Math.max(12, Math.min(event.clientY + 12, win.innerHeight - 260))}px`;
|
||||||
|
const pick = doc.createElement('div');
|
||||||
|
pick.className = 'pick';
|
||||||
|
const label = doc.createElement('small');
|
||||||
|
label.textContent = words.choose;
|
||||||
|
pick.append(label, ...found.map(item => button(`${item.text.slice(0, 60)} · ${item.id}`, () => edit(item.id, event.clientX, event.clientY, item.text))));
|
||||||
|
pop.append(pick, button(words.cancel, closePop));
|
||||||
|
root.append(pop);
|
||||||
|
};
|
||||||
|
|
||||||
|
const mount = () => { (doc.body ?? doc.documentElement).append(host); renderBar(); };
|
||||||
|
if (doc.body) mount(); else doc.addEventListener('DOMContentLoaded', mount, { once: true });
|
||||||
|
win.addEventListener('click', onClick, true);
|
||||||
|
return { dispose() { win.removeEventListener('click', onClick, true); host.remove(); } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The draft as the last pack of a delivery (it applies over the others), when it has any string. */
|
||||||
|
export function withDraft(packs: readonly unknown[], storage: Pick<Storage, 'getItem'>, site: string, catalog: string, inventory: PageInventory): unknown[] {
|
||||||
|
const draft = readDraft(storage);
|
||||||
|
if (!draft || !Object.keys(draft.strings).length) return [...packs];
|
||||||
|
const pack = draftPack(draft, site, catalog);
|
||||||
|
try { compilePack(pack, inventory); } catch { return [...packs]; }
|
||||||
|
return [...packs, pack];
|
||||||
|
}
|
||||||
53
packages/runtime/tests/stringPackTranslate.test.ts
Normal file
53
packages/runtime/tests/stringPackTranslate.test.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import { checkEdit, createMarker, draftPack, readDraft, withDraft, DRAFT_KEY } from '../src/stringPackTranslate.ts';
|
||||||
|
import { inventoryLookup, type PageInventory } from '../src/stringPacks.ts';
|
||||||
|
import { installStringPacks, type CatalogHookAdapter, type CatalogSink } from '../src/stringPackHook.ts';
|
||||||
|
|
||||||
|
const INVENTORY: PageInventory = { site: 'demo', catalog: 'web', text: 'a0000001 a0000002', message: { b0000001: 'count*' }, closed: 'c0000001' };
|
||||||
|
|
||||||
|
test('marker: strings and string results carry an invisible key marker that reads back', () => {
|
||||||
|
const marker = createMarker();
|
||||||
|
const home = marker.mark('a0000001', 'Home') as string;
|
||||||
|
const posts = (marker.mark('b0000001', (e: { count: number }) => `${e.count} posts`) as (e: unknown) => string)({ count: 3 });
|
||||||
|
assert.notEqual(home, 'Home');
|
||||||
|
assert.equal(marker.strip(home), 'Home');
|
||||||
|
assert.equal(marker.strip(posts), '3 posts');
|
||||||
|
assert.deepEqual(marker.ids(`${home} and ${posts}`), ['a0000001', 'b0000001']);
|
||||||
|
assert.deepEqual(marker.ids('no markers'), []);
|
||||||
|
const element = { element: true };
|
||||||
|
assert.equal((marker.mark('c0000001', () => element) as () => unknown)(), element, 'an element result is left alone');
|
||||||
|
assert.equal(marker.mark('x', 42), 42);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('edits: checked with the pack rules; the draft is a pack applied last', () => {
|
||||||
|
const lookup = inventoryLookup(INVENTORY);
|
||||||
|
assert.equal(checkEdit(lookup, 'a0000001', 'Hejmo'), null);
|
||||||
|
assert.match(checkEdit(lookup, 'a0000001', '<b>x</b>')!, /markup/);
|
||||||
|
assert.match(checkEdit(lookup, 'b0000001', '{total}')!, /not a parameter/);
|
||||||
|
assert.match(checkEdit(lookup, 'c0000001', 'x')!, /not translatable yet/);
|
||||||
|
assert.match(checkEdit(lookup, 'zzzzzzzz', 'x')!, /not in the inventory/);
|
||||||
|
const store = new Map<string, string>();
|
||||||
|
const storage = { getItem: (key: string) => store.get(key) ?? null };
|
||||||
|
assert.equal(readDraft(storage), null);
|
||||||
|
assert.deepEqual(withDraft(['p1'], storage, 'demo', 'web', INVENTORY), ['p1']);
|
||||||
|
store.set(DRAFT_KEY, JSON.stringify({ language: 'eo', name: 'Mine', strings: { a0000001: 'Hejmo' } }));
|
||||||
|
const packs = withDraft(['p1'], storage, 'demo', 'web', INVENTORY);
|
||||||
|
assert.equal(packs.length, 2);
|
||||||
|
assert.deepEqual(packs[1], draftPack(readDraft(storage)!, 'demo', 'web'));
|
||||||
|
assert.equal((packs[1] as { language: string }).language, 'eo');
|
||||||
|
store.set(DRAFT_KEY, '{broken');
|
||||||
|
assert.equal(readDraft(storage), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('translate mode hooks the catalog even without a pack and marks every value', () => {
|
||||||
|
const hooked: { sink: CatalogSink | null } = { sink: null };
|
||||||
|
const adapter: CatalogHookAdapter = { catalog: 'web', install: (_win, s) => { hooked.sink = s; return () => {}; } };
|
||||||
|
const win = { setTimeout: () => 0, clearTimeout() {} } as unknown as Window;
|
||||||
|
const marker = createMarker();
|
||||||
|
installStringPacks(win, [{ adapter, inventory: INVENTORY, packs: [] }], { mark: (id, value) => marker.mark(id, value) });
|
||||||
|
assert.ok(hooked.sink, 'hooked without packs');
|
||||||
|
const value = hooked.sink.resolve('a0000001', 'Home') as string;
|
||||||
|
assert.equal(marker.strip(value), 'Home');
|
||||||
|
assert.deepEqual(marker.ids(value), ['a0000001']);
|
||||||
|
});
|
||||||
|
|
@ -14,6 +14,8 @@ import type { PanelSection, SectionProps } from './site.ts';
|
||||||
import './strings.css';
|
import './strings.css';
|
||||||
|
|
||||||
const MAX_ON = 8;
|
const MAX_ON = 8;
|
||||||
|
const TRANSLATE_KEY = 'wb.strings.translate';
|
||||||
|
const translating = () => { try { return localStorage.getItem(TRANSLATE_KEY) === '1'; } catch { return false; } };
|
||||||
const ICON = 'M2.5 3.5h7M6 2v1.5M8 3.5c-.6 2.9-2.6 5-5.4 6.1M4.6 6.2c.8 1.2 2 2.2 3.4 2.9M9.5 14l3-7 3 7M10.6 11.8h3.8';
|
const ICON = 'M2.5 3.5h7M6 2v1.5M8 3.5c-.6 2.9-2.6 5-5.4 6.1M4.6 6.2c.8 1.2 2 2.2 3.4 2.9M9.5 14l3-7 3 7M10.6 11.8h3.8';
|
||||||
|
|
||||||
type Row = InstalledStrings & { summary: StringsSummary | null };
|
type Row = InstalledStrings & { summary: StringsSummary | null };
|
||||||
|
|
@ -23,7 +25,7 @@ export async function applyStringPacks(inventory: PageInventory, packs?: Install
|
||||||
const list = packs ?? (await invoke<{ packs: InstalledStrings[] }>('strings_list')).packs;
|
const list = packs ?? (await invoke<{ packs: InstalledStrings[] }>('strings_list')).packs;
|
||||||
const texts: string[] = [];
|
const texts: string[] = [];
|
||||||
for (const pack of list) if (pack.enabled) texts.push(await invoke<string>('strings_read', { id: pack.id }));
|
for (const pack of list) if (pack.enabled) texts.push(await invoke<string>('strings_read', { id: pack.id }));
|
||||||
await invoke('strings_apply', { delivery: buildDelivery(texts, inventory) });
|
await invoke('strings_apply', { delivery: buildDelivery(texts, inventory, { translate: translating() }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createStringPacksSection(options: { inventory: PageInventory; id?: string; icon?: string }): PanelSection {
|
export function createStringPacksSection(options: { inventory: PageInventory; id?: string; icon?: string }): PanelSection {
|
||||||
|
|
@ -35,6 +37,7 @@ export function createStringPacksSection(options: { inventory: PageInventory; id
|
||||||
const name = site().name;
|
const name = site().name;
|
||||||
const [rows, setRows] = useState<Row[] | null>(null);
|
const [rows, setRows] = useState<Row[] | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [translate, setTranslate] = useState(translating);
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
const { packs } = await invoke<{ packs: InstalledStrings[] }>('strings_list');
|
const { packs } = await invoke<{ packs: InstalledStrings[] }>('strings_list');
|
||||||
|
|
@ -104,6 +107,15 @@ export function createStringPacksSection(options: { inventory: PageInventory; id
|
||||||
</li>)}
|
</li>)}
|
||||||
</ul>}
|
</ul>}
|
||||||
{on >= MAX_ON && <p className="btp-hint">{t('wb.strings.limit')}</p>}
|
{on >= MAX_ON && <p className="btp-hint">{t('wb.strings.limit')}</p>}
|
||||||
|
<div className="btp-strings-row">
|
||||||
|
<Toggle label={t('wb.strings.translate')} checked={translate} disabled={busy} onChange={checked => {
|
||||||
|
try { localStorage.setItem(TRANSLATE_KEY, checked ? '1' : '0'); } catch { /* it still applies once */ }
|
||||||
|
setTranslate(checked);
|
||||||
|
setBusy(true);
|
||||||
|
void applyStringPacks(inventory).then(() => notify(t('wb.strings.applied', { site: name }))).catch(error => notify(String(error), true)).finally(() => setBusy(false));
|
||||||
|
}}/>
|
||||||
|
<div className="btp-strings-text"><strong>{t('wb.strings.translate')}</strong><small>{t('wb.strings.translateHint', { site: name })}</small></div>
|
||||||
|
</div>
|
||||||
</Section>;
|
</Section>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -137,6 +137,8 @@ export const STORE_MESSAGES = {
|
||||||
'wb.strings.applied': 'Your {site} tabs reload to apply it.',
|
'wb.strings.applied': 'Your {site} tabs reload to apply it.',
|
||||||
'wb.strings.limit': 'At most 8 packs can be on at once.',
|
'wb.strings.limit': 'At most 8 packs can be on at once.',
|
||||||
'wb.strings.dataOnly': 'Data only',
|
'wb.strings.dataOnly': 'Data only',
|
||||||
|
'wb.strings.translate': 'Translate mode',
|
||||||
|
'wb.strings.translateHint': 'Every {site} tab shows a bar: click a word to change it. Your edits apply in that tab after a reload, and “Copy pack file” gives you a pack to share. While it is on, words carry invisible markers.',
|
||||||
'wb.install.doneButton': 'Done',
|
'wb.install.doneButton': 'Done',
|
||||||
'wb.install.drop': 'Drop to install',
|
'wb.install.drop': 'Drop to install',
|
||||||
'wb.install.dropHint': 'A theme (.json), a plugin (.plugin.js) or a string pack (.strings.json). You will see what it is before anything is installed.',
|
'wb.install.dropHint': 'A theme (.json), a plugin (.plugin.js) or a string pack (.strings.json). You will see what it is before anything is installed.',
|
||||||
|
|
|
||||||
|
|
@ -70,7 +70,7 @@ export const coveragePercent = (summary: Pick<StringsSummary, 'translated' | 'tr
|
||||||
* What the site tabs get: the texts of the packs that are on, in application order, with the slice
|
* What the site tabs get: the texts of the packs that are on, in application order, with the slice
|
||||||
* of the inventory their keys need. `null` when no usable pack is on (the tabs then drop theirs).
|
* of the inventory their keys need. `null` when no usable pack is on (the tabs then drop theirs).
|
||||||
*/
|
*/
|
||||||
export function buildDelivery(texts: readonly string[], inventory: PageInventory): string | null {
|
export function buildDelivery(texts: readonly string[], inventory: PageInventory, options: { translate?: boolean } = {}): string | null {
|
||||||
const packs: unknown[] = [];
|
const packs: unknown[] = [];
|
||||||
const ids = new Set<string>();
|
const ids = new Set<string>();
|
||||||
for (const text of texts) {
|
for (const text of texts) {
|
||||||
|
|
@ -83,6 +83,8 @@ export function buildDelivery(texts: readonly string[], inventory: PageInventory
|
||||||
for (const id of compiled.values.keys()) ids.add(id);
|
for (const id of compiled.values.keys()) ids.add(id);
|
||||||
if (packs.length >= 8) break;
|
if (packs.length >= 8) break;
|
||||||
}
|
}
|
||||||
|
// Translate mode: the whole inventory (the author may change any string), packs or not.
|
||||||
|
if (options.translate) return JSON.stringify({ inventory, packs, translate: true });
|
||||||
if (!packs.length) return null;
|
if (!packs.length) return null;
|
||||||
return JSON.stringify({ inventory: sliceInventory(inventory, ids), packs });
|
return JSON.stringify({ inventory: sliceInventory(inventory, ids), packs });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1226,6 +1226,8 @@
|
||||||
"wb.install.eyebrow.strings.update": "Update string pack",
|
"wb.install.eyebrow.strings.update": "Update string pack",
|
||||||
"wb.install.eyebrow.strings.reinstall": "Reinstall string pack",
|
"wb.install.eyebrow.strings.reinstall": "Reinstall string pack",
|
||||||
"wb.install.err.stringsLarge": "String packs are limited to 2 MB.",
|
"wb.install.err.stringsLarge": "String packs are limited to 2 MB.",
|
||||||
"wb.install.err.stringsNotInstalled": "The string pack was not installed"
|
"wb.install.err.stringsNotInstalled": "The string pack was not installed",
|
||||||
|
"wb.strings.translate": "Translate mode",
|
||||||
|
"wb.strings.translateHint": "Every {site} tab shows a bar: click a word to change it. Your edits apply in that tab after a reload, and “Copy pack file” gives you a pack to share. While it is on, words carry invisible markers."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue