Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Language packs: add one to the FILE, not just to this browser
nyblneta7814b4e03a2
diff --git a/kernel/src/save.ts b/kernel/src/save.tsindex 042b558e..4bc8a063 100644--- a/kernel/src/save.ts+++ b/kernel/src/save.ts@@ -28,10 +28,60 @@ export function readEmbeddedDoc(): string | null {return text || null}+/**+ * Extra plaintext blocks the app wants written into every saved shell —+ * language packs today (docs/i18n-packs.md), whatever else later. The kernel+ * stays ignorant of what they mean: it is told an id, a type and a JSON body,+ * and guarantees only that they survive a save the same way #bento-doc does.+ *+ * The full set is re-declared on every serialize, so dropping one from the+ * list removes it from the next saved file — that is how "remove from this+ * file" works without a second API.+ */+export interface ShellBlock {+ id: string+ type: string+ /** JSON text; `<` is escaped on write exactly as the doc block's is */+ body: string+ attrs?: Record<string, string>+}+let shellBlocks: () => ShellBlock[] = () => []++/** Register the provider consulted on every serialize. Call once, at boot. */+export function registerShellBlocks(fn: () => ShellBlock[]): void {+ shellBlocks = fn+}++/** Every extra block currently in THIS document (as loaded from disk). */+export function readShellBlocks(type: string): Array<{ id: string; body: string; el: Element }> {+ return Array.from(document.querySelectorAll(`script[type="${type}"]`)).map((el) => ({+ id: el.id,+ body: (el.textContent ?? '').trim(),+ el,+ }))+}+/** Serialize a raw data-block body into an app shell. */function serializeBody(shell: Document, body: string, title: string): string {const clone = shell.cloneNode(true) as Document+ // Re-declare the app's extra blocks: drop every one of a managed type, then+ // write the current set back. Removing a language from the file is therefore+ // just "stop listing it" — no deletion path to get wrong.+ const wanted = shellBlocks()+ for (const type of new Set(wanted.map((b) => b.type))) {+ for (const stale of Array.from(clone.querySelectorAll(`script[type="${type}"]`))) stale.remove()+ }+ for (const b of wanted) {+ const el = clone.createElement('script')+ el.setAttribute('type', b.type)+ el.id = b.id+ for (const [k, v] of Object.entries(b.attrs ?? {})) el.setAttribute(k, v)+ // same <-escape as the doc block: these can never contain "</script>"+ el.textContent = '\n' + b.body.replace(/</g, '\\u003c') + '\n'+ clone.head.appendChild(el)+ }+let block = clone.getElementById(DATA_BLOCK_ID)if (!block) {block = clone.createElement('script')diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 890c644a..f527610c 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -24,7 +24,7 @@ import { openSpeakerWindow, speakerIdleBody } from '../screens'import { borderPoint, boxCenter, lineEndpoints, setLineEndpoints, sideMidpoint } from './lineedit'import { ICONS } from '../icons'import { t, setLocale, locale, localeChoices, LOCALE_CHOICES } from '../i18n'-import { availablePacks, installPack, installedPacks, uninstallPack } from '../packs'+import { availablePacks, fetchPack, installPack, installedPacks, packsInFile, stageForFile, uninstallPack, unstageFromFile } from '../packs'import { appConfig } from '../../../kernel/src/app.ts'import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'@@ -1023,7 +1023,7 @@ export class Editor {b.textContent = blurblistHost.appendChild(b)}- const row = (label: string, sub: string, action?: HTMLElement, host: HTMLElement = listHost) => {+ const row = (label: string, sub: string, actions: HTMLElement[] = [], host: HTMLElement = listHost) => {const r = div('ed-lang-row')const txt = div('ed-lang-txt')const n = document.createElement('b')@@ -1032,12 +1032,33 @@ export class Editor {s.textContent = subtxt.append(n, s)r.appendChild(txt)- if (action) r.appendChild(action)+ if (actions.length) {+ const acts = div('ed-lang-acts')+ for (const a of actions) acts.appendChild(a)+ r.appendChild(acts)+ }host.appendChild(r)}section(t('In this file'), t('Travels with the deck — anyone you send it to gets these too.'))row('English, ' + bundled.map((c) => c.label).join(', '), t('Included in every Bento'))+ for (const p of packsInFile()) {+ const rm = document.createElement('button')+ rm.className = 'ed-btn'+ rm.textContent = t('Remove')+ rm.title = t('Take out of the file — applies when you next save')+ rm.addEventListener('click', () => {+ unstageFromFile(p.lang)+ this.build()+ this.rebuildSidebar()+ void paint()+ })+ row(+ p.label || p.lang,+ p.pending ? t('Added when you next save') : t('Saved in this file'),+ [rm],+ )+ }section(t('On this computer'),@@ -1060,11 +1081,11 @@ export class Editor {this.rebuildSidebar()void paint()})- row(p.label || p.lang, p.version ? t('Language pack · built for v{v}', { v: p.version }) : t('Language pack'), rm)+ row(p.label || p.lang, p.version ? t('Language pack · built for v{v}', { v: p.version }) : t('Language pack'), [rm])}const all = await availablePacks()- section(t('Available to add'), t('Adding one puts it on this computer. New languages arrive with each release.'))+ section(t('Available to add'), t('Choose where it goes: just for you, or into the deck so it travels.'))if (!all.length) {const none = div('ed-hint')none.textContent = t('Nothing new right now.')@@ -1087,6 +1108,9 @@ export class Editor {const renderAvail = (q = '') => {scroller.textContent = ''+ // Nothing on offer at all is already stated above — saying it twice,+ // once as 'No language matches ""', is worse than saying it once.+ if (!all.length) returnconst needle = q.trim().toLowerCase()const hits = needle? all.filter((p) => p.label.toLowerCase().includes(needle) || p.lang.toLowerCase().includes(needle))@@ -1100,27 +1124,55 @@ export class Editor {for (const p of hits) addRow(p, scroller)}+ // Two destinations, labelled with the SAME words as the sections above,+ // so the button says where the language will end up. Nobody should have+ // to install a language locally just to put it in a file they are+ // sending to someone else.const addRow = (p: import('../packs').PackListing, host: HTMLElement) => {- const add = document.createElement('button')- add.className = 'ed-btn'- add.textContent = t('Add')- add.title = t('Download and use on this computer — the deck itself is not changed')- add.addEventListener('click', async () => {- add.disabled = true- add.textContent = t('Adding…')- const err = await installPack(p)- if (err) {- this.toast(languageInstallError(err))- add.disabled = false- add.textContent = t('Add')- return- }- this.toast(t('{lang} is ready to use', { lang: p.label }))- this.build()- this.rebuildSidebar()- void paint()- })- row(p.label, p.lang, add, host)+ const mk = (label: string, title: string, run: () => Promise<string | null>) => {+ const b = document.createElement('button')+ b.className = 'ed-btn'+ b.textContent = label+ b.title = title+ b.addEventListener('click', async () => {+ const siblings = [...(b.parentElement?.children ?? [])] as HTMLButtonElement[]+ siblings.forEach((s) => (s.disabled = true))+ b.textContent = t('Adding…')+ const err = await run()+ if (err) {+ this.toast(languageInstallError(err as 'offline'))+ siblings.forEach((s) => (s.disabled = false))+ b.textContent = label+ return+ }+ this.build()+ this.rebuildSidebar()+ void paint()+ })+ return b+ }++ const toComputer = mk(+ t('This computer'),+ t('Download and use here. The deck itself is not changed.'),+ async () => {+ const err = await installPack(p)+ if (!err) this.toast(t('{lang} is ready to use', { lang: p.label }))+ return err+ },+ )+ const toFile = mk(+ t('This file'),+ t('Put it in the deck so it travels — written when you next save.'),+ async () => {+ const err = await fetchPack(p)+ if (typeof err === 'string') return err+ stageForFile(err)+ this.toast(t('{lang} will be saved with this deck', { lang: p.label }))+ return null+ },+ )+ row(p.label, p.lang, [toComputer, toFile], host)}renderAvail()diff --git a/slides/src/i18n.ts b/slides/src/i18n.tsindex 28fdf58f..90d2de79 100644--- a/slides/src/i18n.ts+++ b/slides/src/i18n.ts@@ -18,7 +18,8 @@// node scripts/build-i18n.mjs//import { PACKED, PACKED_LOCALES } from './i18n/packed'-import { restoreInstalledPacks } from './packs'+import { readPacksFromShell, restoreInstalledPacks, shellBlocksForPacks } from './packs'+import { registerShellBlocks } from '../../kernel/src/save.ts'import { registerI18n } from '../../kernel/src/i18n.ts'import type { LocaleChoice } from '../../kernel/src/i18n.ts'@@ -56,10 +57,19 @@ registerI18n({choices: CHOICES,})-// Packs installed on THIS browser, re-registered before the first t() — same-// module-evaluation-order guarantee that makes the facade own registration.+// Packs, re-registered before the first t() — same module-evaluation-order+// guarantee that makes the facade own registration.+//+// FILE FIRST, then browser. A pack embedded in the deck is what its author+// chose to send; a locally installed one is the reader's own preference, and+// the reader should win when both carry the same language.+readPacksFromShell()restoreInstalledPacks()+// Every save re-declares the file's packs, so staging one is enough to make+// it travel and dropping it is enough to remove it.+registerShellBlocks(shellBlocksForPacks)+/*** The BUNDLED locales only. Call sites that need the live list — including any* language an installed pack added — must use `localeChoices()` instead: thisdiff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.tsindex 1af3c47c..863601ac 100644--- a/slides/src/i18n/de.ts+++ b/slides/src/i18n/de.ts@@ -694,4 +694,13 @@ export const de: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "Es funktioniert jetzt, aber hier ist kein Platz zum Speichern — nach dem Neuladen ist es weg.","Search languages": "Sprachen suchen","No language matches “{q}”.": "Keine Sprache passt zu „{q}“.",+ "This computer": "Dieser Computer",+ "This file": "Diese Datei",+ "Download and use here. The deck itself is not changed.": "Herunterladen und hier verwenden. Die Präsentation wird nicht verändert.",+ "Put it in the deck so it travels — written when you next save.": "In die Präsentation legen, damit sie mitreist — wird beim nächsten Speichern geschrieben.",+ "{lang} will be saved with this deck": "{lang} wird mit dieser Präsentation gespeichert",+ "Added when you next save": "Wird beim nächsten Speichern hinzugefügt",+ "Saved in this file": "In dieser Datei gespeichert",+ "Take out of the file — applies when you next save": "Aus der Datei entfernen — gilt ab dem nächsten Speichern",+ "Choose where it goes: just for you, or into the deck so it travels.": "Wähle das Ziel: nur für dich, oder in der Präsentation, damit sie mitreist.",}diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.tsindex 270d502d..e4a7a6a6 100644--- a/slides/src/i18n/es.ts+++ b/slides/src/i18n/es.ts@@ -694,4 +694,13 @@ export const es: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "Funciona ahora, pero no hay espacio para guardarlo aquí: desaparecerá al recargar.","Search languages": "Buscar idiomas","No language matches “{q}”.": "Ningún idioma coincide con «{q}».",+ "This computer": "Este equipo",+ "This file": "Este archivo",+ "Download and use here. The deck itself is not changed.": "Descargar y usar aquí. La presentación no se modifica.",+ "Put it in the deck so it travels — written when you next save.": "Ponerlo en la presentación para que viaje: se escribe al guardar.",+ "{lang} will be saved with this deck": "{lang} se guardará con esta presentación",+ "Added when you next save": "Se añadirá al guardar",+ "Saved in this file": "Guardado en este archivo",+ "Take out of the file — applies when you next save": "Quitar del archivo: se aplica al guardar",+ "Choose where it goes: just for you, or into the deck so it travels.": "Elige dónde va: solo para ti, o dentro de la presentación para que viaje.",}diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.tsindex 6b1ebb98..31c6a76c 100644--- a/slides/src/i18n/fr.ts+++ b/slides/src/i18n/fr.ts@@ -694,4 +694,13 @@ export const fr: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "Cela fonctionne pour l’instant, mais il n’y a pas de place pour l’enregistrer ici — ce sera perdu au rechargement.","Search languages": "Rechercher des langues","No language matches “{q}”.": "Aucune langue ne correspond à « {q} ».",+ "This computer": "Cet ordinateur",+ "This file": "Ce fichier",+ "Download and use here. The deck itself is not changed.": "Télécharger et utiliser ici. La présentation n’est pas modifiée.",+ "Put it in the deck so it travels — written when you next save.": "La placer dans la présentation pour qu’elle voyage — écrite au prochain enregistrement.",+ "{lang} will be saved with this deck": "{lang} sera enregistré avec cette présentation",+ "Added when you next save": "Ajouté au prochain enregistrement",+ "Saved in this file": "Enregistré dans ce fichier",+ "Take out of the file — applies when you next save": "Retirer du fichier — appliqué au prochain enregistrement",+ "Choose where it goes: just for you, or into the deck so it travels.": "Choisissez la destination : pour vous seul, ou dans la présentation pour qu’elle voyage.",}diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.tsindex 241a7d90..7af787e5 100644--- a/slides/src/i18n/it.ts+++ b/slides/src/i18n/it.ts@@ -694,4 +694,13 @@ export const it: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "Funziona adesso, ma non c’è spazio per salvarla qui — sparirà al ricaricamento.","Search languages": "Cerca lingue","No language matches “{q}”.": "Nessuna lingua corrisponde a «{q}».",+ "This computer": "Questo computer",+ "This file": "Questo file",+ "Download and use here. The deck itself is not changed.": "Scarica e usa qui. La presentazione non viene modificata.",+ "Put it in the deck so it travels — written when you next save.": "Mettila nella presentazione perché viaggi — scritta al prossimo salvataggio.",+ "{lang} will be saved with this deck": "{lang} sarà salvata con questa presentazione",+ "Added when you next save": "Aggiunta al prossimo salvataggio",+ "Saved in this file": "Salvata in questo file",+ "Take out of the file — applies when you next save": "Togli dal file — vale dal prossimo salvataggio",+ "Choose where it goes: just for you, or into the deck so it travels.": "Scegli dove va: solo per te, o dentro la presentazione perché viaggi.",}diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.tsindex 991f03a7..5de2766d 100644--- a/slides/src/i18n/ja.ts+++ b/slides/src/i18n/ja.ts@@ -694,4 +694,13 @@ export const ja: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "今は使えますが、ここに保存する空き容量がありません — 再読み込みすると消えます。","Search languages": "言語を検索","No language matches “{q}”.": "「{q}」に一致する言語はありません。",+ "This computer": "このコンピューター",+ "This file": "このファイル",+ "Download and use here. The deck itself is not changed.": "ダウンロードしてここで使用します。デッキ自体は変更されません。",+ "Put it in the deck so it travels — written when you next save.": "デッキに入れて一緒に配布します — 次回の保存時に書き込まれます。",+ "{lang} will be saved with this deck": "{lang} はこのデッキと一緒に保存されます",+ "Added when you next save": "次回の保存時に追加",+ "Saved in this file": "このファイルに保存済み",+ "Take out of the file — applies when you next save": "ファイルから削除 — 次回の保存時に反映",+ "Choose where it goes: just for you, or into the deck so it travels.": "保存先を選んでください: 自分用か、デッキに入れて一緒に配布するか。",}diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.tsindex f3351988..6899b2a1 100644--- a/slides/src/i18n/packed.ts+++ b/slides/src/i18n/packed.ts@@ -700,4 +700,13 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"It works now, but there’s no room to save it here — it will be gone after a reload.": ["今は使えますが、ここに保存する空き容量がありません — 再読み込みすると消えます。","现在可以使用,但这里没有空间保存 — 重新加载后将会消失。","現在可以使用,但這裡沒有空間保存 — 重新載入後將會消失。","Funciona ahora, pero no hay espacio para guardarlo aquí: desaparecerá al recargar.","Cela fonctionne pour l’instant, mais il n’y a pas de place pour l’enregistrer ici — ce sera perdu au rechargement.","Es funktioniert jetzt, aber hier ist kein Platz zum Speichern — nach dem Neuladen ist es weg.","Funziona adesso, ma non c’è spazio per salvarla qui — sparirà al ricaricamento.","Funciona agora, mas não há espaço para salvar aqui — sumirá após recarregar."],"Search languages": ["言語を検索","搜索语言","搜尋語言","Buscar idiomas","Rechercher des langues","Sprachen suchen","Cerca lingue","Pesquisar idiomas"],"No language matches “{q}”.": ["「{q}」に一致する言語はありません。","没有与“{q}”匹配的语言。","沒有與「{q}」相符的語言。","Ningún idioma coincide con «{q}».","Aucune langue ne correspond à « {q} ».","Keine Sprache passt zu „{q}“.","Nessuna lingua corrisponde a «{q}».","Nenhum idioma corresponde a “{q}”."],+ "This computer": ["このコンピューター","此计算机","此電腦","Este equipo","Cet ordinateur","Dieser Computer","Questo computer","Este computador"],+ "This file": ["このファイル","此文件","此檔案","Este archivo","Ce fichier","Diese Datei","Questo file","Este arquivo"],+ "Download and use here. The deck itself is not changed.": ["ダウンロードしてここで使用します。デッキ自体は変更されません。","下载并在此使用。不会改动演示文稿本身。","下載並在此使用。不會變更簡報本身。","Descargar y usar aquí. La presentación no se modifica.","Télécharger et utiliser ici. La présentation n’est pas modifiée.","Herunterladen und hier verwenden. Die Präsentation wird nicht verändert.","Scarica e usa qui. La presentazione non viene modificata.","Baixar e usar aqui. A apresentação em si não é alterada."],+ "Put it in the deck so it travels — written when you next save.": ["デッキに入れて一緒に配布します — 次回の保存時に書き込まれます。","放入演示文稿一起传递 — 下次保存时写入。","放入簡報一起傳遞 — 下次儲存時寫入。","Ponerlo en la presentación para que viaje: se escribe al guardar.","La placer dans la présentation pour qu’elle voyage — écrite au prochain enregistrement.","In die Präsentation legen, damit sie mitreist — wird beim nächsten Speichern geschrieben.","Mettila nella presentazione perché viaggi — scritta al prossimo salvataggio.","Colocar na apresentação para viajar junto — gravado no próximo salvamento."],+ "{lang} will be saved with this deck": ["{lang} はこのデッキと一緒に保存されます","{lang} 将随此演示文稿一起保存","{lang} 將隨此簡報一起儲存","{lang} se guardará con esta presentación","{lang} sera enregistré avec cette présentation","{lang} wird mit dieser Präsentation gespeichert","{lang} sarà salvata con questa presentazione","{lang} será salvo com esta apresentação"],+ "Added when you next save": ["次回の保存時に追加","下次保存时添加","下次儲存時新增","Se añadirá al guardar","Ajouté au prochain enregistrement","Wird beim nächsten Speichern hinzugefügt","Aggiunta al prossimo salvataggio","Adicionado no próximo salvamento"],+ "Saved in this file": ["このファイルに保存済み","已保存在此文件中","已儲存在此檔案中","Guardado en este archivo","Enregistré dans ce fichier","In dieser Datei gespeichert","Salvata in questo file","Salvo neste arquivo"],+ "Take out of the file — applies when you next save": ["ファイルから削除 — 次回の保存時に反映","从文件中移除 — 下次保存时生效","從檔案中移除 — 下次儲存時生效","Quitar del archivo: se aplica al guardar","Retirer du fichier — appliqué au prochain enregistrement","Aus der Datei entfernen — gilt ab dem nächsten Speichern","Togli dal file — vale dal prossimo salvataggio","Tirar do arquivo — vale a partir do próximo salvamento"],+ "Choose where it goes: just for you, or into the deck so it travels.": ["保存先を選んでください: 自分用か、デッキに入れて一緒に配布するか。","选择位置:仅供你使用,或放入演示文稿一起传递。","選擇位置:僅供你使用,或放入簡報一起傳遞。","Elige dónde va: solo para ti, o dentro de la presentación para que viaje.","Choisissez la destination : pour vous seul, ou dans la présentation pour qu’elle voyage.","Wähle das Ziel: nur für dich, oder in der Präsentation, damit sie mitreist.","Scegli dove va: solo per te, o dentro la presentazione perché viaggi.","Escolha o destino: só para você, ou dentro da apresentação para viajar junto."],}diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.tsindex cbdb4d96..659afb01 100644--- a/slides/src/i18n/pt.ts+++ b/slides/src/i18n/pt.ts@@ -692,4 +692,13 @@ export const pt: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "Funciona agora, mas não há espaço para salvar aqui — sumirá após recarregar.","Search languages": "Pesquisar idiomas","No language matches “{q}”.": "Nenhum idioma corresponde a “{q}”.",+ "This computer": "Este computador",+ "This file": "Este arquivo",+ "Download and use here. The deck itself is not changed.": "Baixar e usar aqui. A apresentação em si não é alterada.",+ "Put it in the deck so it travels — written when you next save.": "Colocar na apresentação para viajar junto — gravado no próximo salvamento.",+ "{lang} will be saved with this deck": "{lang} será salvo com esta apresentação",+ "Added when you next save": "Adicionado no próximo salvamento",+ "Saved in this file": "Salvo neste arquivo",+ "Take out of the file — applies when you next save": "Tirar do arquivo — vale a partir do próximo salvamento",+ "Choose where it goes: just for you, or into the deck so it travels.": "Escolha o destino: só para você, ou dentro da apresentação para viajar junto.",}diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.tsindex 359b01c6..dffff934 100644--- a/slides/src/i18n/zh-Hans.ts+++ b/slides/src/i18n/zh-Hans.ts@@ -694,4 +694,13 @@ export const zhHans: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "现在可以使用,但这里没有空间保存 — 重新加载后将会消失。","Search languages": "搜索语言","No language matches “{q}”.": "没有与“{q}”匹配的语言。",+ "This computer": "此计算机",+ "This file": "此文件",+ "Download and use here. The deck itself is not changed.": "下载并在此使用。不会改动演示文稿本身。",+ "Put it in the deck so it travels — written when you next save.": "放入演示文稿一起传递 — 下次保存时写入。",+ "{lang} will be saved with this deck": "{lang} 将随此演示文稿一起保存",+ "Added when you next save": "下次保存时添加",+ "Saved in this file": "已保存在此文件中",+ "Take out of the file — applies when you next save": "从文件中移除 — 下次保存时生效",+ "Choose where it goes: just for you, or into the deck so it travels.": "选择位置:仅供你使用,或放入演示文稿一起传递。",}diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.tsindex 6aa2bb61..1bf5a886 100644--- a/slides/src/i18n/zh-Hant.ts+++ b/slides/src/i18n/zh-Hant.ts@@ -694,4 +694,13 @@ export const zhHant: Catalog = {"It works now, but there’s no room to save it here — it will be gone after a reload.": "現在可以使用,但這裡沒有空間保存 — 重新載入後將會消失。","Search languages": "搜尋語言","No language matches “{q}”.": "沒有與「{q}」相符的語言。",+ "This computer": "此電腦",+ "This file": "此檔案",+ "Download and use here. The deck itself is not changed.": "下載並在此使用。不會變更簡報本身。",+ "Put it in the deck so it travels — written when you next save.": "放入簡報一起傳遞 — 下次儲存時寫入。",+ "{lang} will be saved with this deck": "{lang} 將隨此簡報一起儲存",+ "Added when you next save": "下次儲存時新增",+ "Saved in this file": "已儲存在此檔案中",+ "Take out of the file — applies when you next save": "從檔案中移除 — 下次儲存時生效",+ "Choose where it goes: just for you, or into the deck so it travels.": "選擇位置:僅供你使用,或放入簡報一起傳遞。",}diff --git a/slides/src/packs.ts b/slides/src/packs.tsindex 34c40742..e871cc0f 100644--- a/slides/src/packs.ts+++ b/slides/src/packs.ts@@ -17,6 +17,7 @@// fine; a quota failure is caught and surfaced rather than left to throw.import { addPack, removePack, type LanguagePack } from '../../kernel/src/i18n.ts'+import { readShellBlocks, type ShellBlock } from '../../kernel/src/save.ts'/** Installed packs, keyed by language. */const KEY = 'bento-packs'@@ -82,7 +83,14 @@ export function installedPacks(): LanguagePack[] {* can turn into a sentence (t() must run at display time, so no text crosses* this boundary — same contract as SyncNotice).*/-export async function installPack(listing: PackListing): Promise<null | 'offline' | 'bad-pack' | 'wrong-app' | 'no-space'> {+export type PackError = 'offline' | 'bad-pack' | 'wrong-app' | 'no-space'++/**+ * Download and validate a pack WITHOUT deciding where it goes. Both+ * destinations — this computer, or into the file — start here, which is what+ * lets a language be put in a file without first installing it locally.+ */+export async function fetchPack(listing: PackListing): Promise<LanguagePack | PackError> {const url = /^https?:/.test(listing.url) ? listing.url : `${channel()}/${listing.url}`let pack: LanguagePacktry {@@ -94,6 +102,13 @@ export async function installPack(listing: PackListing): Promise<null | 'offline}if (!pack?.lang || !pack.strings || typeof pack.strings !== 'object') return 'bad-pack'if (pack.app && pack.app !== 'slides') return 'wrong-app'+ return pack+}++export async function installPack(listing: PackListing): Promise<null | PackError> {+ const got = await fetchPack(listing)+ if (typeof got === 'string') return got+ const pack = gotif (!addPack(pack, 'slides')) return 'wrong-app'const s = read()@@ -107,6 +122,95 @@ export async function installPack(listing: PackListing): Promise<null | 'offlinereturn null}+// --- packs that live IN THE FILE --------------------------------------------+//+// The other half of the story. A pack installed above belongs to the reader;+// a pack in the file belongs to the DECK and travels to whoever opens it.+//+// Staging is deliberate rather than immediate: adding one marks it for the+// file and it is written on the next save, exactly like any other edit. The+// alternative — writing the user's file the instant they click Add — is worse+// on every browser without File System Access, where "write" means silently+// downloading a second copy of their deck.++/** The block type carrying a pack inside a saved shell. */+const BLOCK_TYPE = 'application/bento+lang'+const blockId = (lang: string) => `bento-lang-${lang}`++/** Packs destined for the file: those already in it, plus any staged since. */+const inFile = new Map<string, LanguagePack>()+/** Which of those were NOT in the file as loaded — i.e. need a save. */+const pending = new Set<string>()++/**+ * Read packs already embedded in this file and register them. Runs at boot+ * from the i18n facade: a deck that arrives carrying Japanese must show+ * Japanese immediately, offline, with nothing fetched.+ */+export function readPacksFromShell(): number {+ let n = 0+ for (const { body } of readShellBlocks(BLOCK_TYPE)) {+ try {+ const pack = JSON.parse(body) as LanguagePack+ if (pack?.lang && pack.strings && addPack(pack, 'slides')) {+ inFile.set(pack.lang, pack)+ n+++ }+ } catch {+ // a corrupt block must not stop the app booting — skip it+ }+ }+ return n+}++/** Packs that will be written into the file on the next save. */+export function packsInFile(): Array<LanguagePack & { pending: boolean }> {+ return [...inFile.values()].map((p) => ({ ...p, pending: pending.has(p.lang) }))+}++/** Is this language waiting for a save to reach the file? */+export const isPendingInFile = (lang: string): boolean => pending.has(lang)++/**+ * Mark a pack for inclusion in the file. Registers it immediately so the+ * editor can use it right away; the FILE only gains it on the next save.+ */+export function stageForFile(pack: LanguagePack): boolean {+ if (!pack?.lang || !pack.strings) return false+ if (!addPack(pack, 'slides')) return false+ inFile.set(pack.lang, pack)+ pending.add(pack.lang)+ return true+}++/**+ * Drop a pack from the file. Also a staged change: the file keeps it until+ * the next save, which is why this marks pending too.+ */+export function unstageFromFile(lang: string): boolean {+ if (!inFile.has(lang)) return false+ inFile.delete(lang)+ pending.add(lang)+ // only unregister if no local install is also providing it+ if (!read()[lang]) removePack(lang)+ return true+}++/** Everything staged has now been written — called after a successful save. */+export function markFileSaved(): void {+ pending.clear()+}++/** The blocks the kernel writes into every saved shell. */+export function shellBlocksForPacks(): ShellBlock[] {+ return [...inFile.values()].map((p) => ({+ id: blockId(p.lang),+ type: BLOCK_TYPE,+ body: JSON.stringify(p),+ attrs: { 'data-lang': p.lang },+ }))+}+/** Remove an installed pack and forget it. */export function uninstallPack(lang: string): boolean {const s = read()@@ -128,7 +232,9 @@ export async function availablePacks(): Promise<PackListing[]> {if (!res.ok) return []const list = (await res.json()) as PackListing[]if (!Array.isArray(list)) return []- const have = new Set(Object.keys(read()))+ // A language already present by EITHER route is not on offer: showing it+ // again invites adding the same pack twice to two different places.+ const have = new Set([...Object.keys(read()), ...inFile.keys()])return list.filter((p) => p?.lang && p?.url && !have.has(p.lang))} catch {return []diff --git a/slides/src/styles.css b/slides/src/styles.cssindex a94e3744..0dbd26c7 100644--- a/slides/src/styles.css+++ b/slides/src/styles.css@@ -1969,4 +1969,12 @@ input.ed-toggle { width: 16px; height: 16px; accent-color: #5E7699; cursor: poinwidth: 100%; margin: 4px 0 6px; padding: 7px 10px; font-size: 13px;border: 1px solid var(--line); border-radius: 8px; background: var(--bg);}-.ed-lang-scroll { max-height: 240px; overflow-y: auto; scrollbar-gutter: stable; }+.ed-lang-scroll {+ max-height: 240px; overflow-y: auto;+ /* Keep the row's action button clear of the scrollbar — without this the+ Add button sits flush against it. The stable gutter stops the list+ shifting sideways when the bar appears or goes. */+ padding-right: 12px; scrollbar-gutter: stable;+}+.ed-lang-acts { display: flex; gap: 6px; flex: 0 0 auto; }+.ed-lang-acts .ed-btn { white-space: nowrap; }