From c8b985ff237f8a012fc2a92a46c9adff3779b8d6 Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 7 Nov 2026 17:03:50 +0800 Subject: [PATCH] fix(i18n): preserve unsaved editor input --- .../cloud/admin-user-copy-page-editor.js | 81 +++++++++- web/public/cloud/admin-user-copy.js | 144 +++++++++++++++--- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/CloudAssetVersionContractTest.php | 2 +- web/tests/UserCopyAdminUiContractTest.php | 33 +++- web/tests/UserCopyPageEditorContractTest.php | 29 ++++ 6 files changed, 262 insertions(+), 29 deletions(-) diff --git a/web/public/cloud/admin-user-copy-page-editor.js b/web/public/cloud/admin-user-copy-page-editor.js index 323cd767..5f6d2aab 100644 --- a/web/public/cloud/admin-user-copy-page-editor.js +++ b/web/public/cloud/admin-user-copy-page-editor.js @@ -21,6 +21,8 @@ page: null, shared: null, }, + draftBuffer: new Map(), + dirtyKeys: new Set(), locale: bootstrap.runtime_locale === 'zh-CN' ? '' : String(bootstrap.runtime_locale || ''), query: '', @@ -178,6 +180,54 @@ return ''; } + function bufferKey(locale, copyKey) { + return String(locale || '') + '\u0000' + String(copyKey || ''); + } + + function draftFor(entry, locale) { + var key = bufferKey(locale, entry.key); + if (state.draftBuffer.has(key)) return state.draftBuffer.get(key); + return { text: textFor(entry) }; + } + + function rememberDraft(entry, locale, text) { + var key = bufferKey(locale, entry.key); + if (text === textFor(entry)) { + state.draftBuffer.delete(key); + state.dirtyKeys.delete(key); + return; + } + state.draftBuffer.set(key, { text: text }); + state.dirtyKeys.add(key); + } + + function clearBufferedDraft(locale, copyKey) { + var key = bufferKey(locale, copyKey); + state.draftBuffer.delete(key); + state.dirtyKeys.delete(key); + } + + function hasDirtyLocale(locale) { + var prefix = String(locale || '') + '\u0000'; + return Array.from(state.dirtyKeys).some(function (key) { + return key.indexOf(prefix) === 0; + }); + } + + function discardLocaleDrafts(locale) { + var prefix = String(locale || '') + '\u0000'; + Array.from(state.dirtyKeys).forEach(function (key) { + if (key.indexOf(prefix) !== 0) return; + state.dirtyKeys.delete(key); + state.draftBuffer.delete(key); + }); + } + + function discardAllDrafts() { + state.dirtyKeys.clear(); + state.draftBuffer.clear(); + } + function visibleEntries() { var workspace = activeWorkspace(); var entries = workspace && Array.isArray(workspace.entries) @@ -213,6 +263,7 @@ function renderEntry(entry) { var workspace = activeWorkspace(); + var buffered = draftFor(entry, state.locale); var card = element('article', 'user-copy-page-editor-entry'); card.dataset.copyKey = entry.key; var meta = element('div', 'user-copy-page-editor-entry-meta'); @@ -232,10 +283,13 @@ var textarea = element('textarea'); textarea.rows = 4; textarea.maxLength = Number(entry.max_length) || 4000; - textarea.value = textFor(entry); + textarea.value = buffered.text; textarea.id = 'user-copy-page-editor-' + String(entry.key).replace(/[^a-z0-9_-]/g, '-'); draftLabel.htmlFor = textarea.id; textarea.readOnly = state.writeLocked || !workspace || workspace.write_ready !== true; + textarea.addEventListener('input', function () { + rememberDraft(entry, state.locale, textarea.value); + }); card.append(meta, sourceLabel, source, publishedLabel, published, draftLabel, textarea); if (Array.isArray(entry.parameters) && entry.parameters.length) { @@ -327,6 +381,7 @@ async function saveDraft(entry, textarea, button) { var workspace = activeWorkspace(); if (state.writeLocked || !workspace || workspace.write_ready !== true) return; + var locale = state.locale; var text = textarea.value; if (!text.trim()) { inform('目标语言草稿不能为空。', 'error'); @@ -341,13 +396,14 @@ + encodeURIComponent(entry.key) + '/draft', { method: 'PUT', body: { - locale: state.locale, + locale: locale, text: text, hidden: false, draft_version: Number(entry.draft_version) || 0, }, }); saved = result && result.entry ? result.entry : null; + clearBufferedDraft(locale, entry.key); } catch (error) { if (error && error.mutationMayHaveApplied === true) { lockWrites('保存结果无法确认,请刷新页面核对;请勿重复提交。'); @@ -404,6 +460,11 @@ } function closeEditor() { + if (state.dirtyKeys.size > 0 + && !window.confirm('存在未保存输入,关闭编辑器后将丢弃这些输入。确认继续?')) { + return false; + } + discardAllDrafts(); drawer.hidden = true; backdrop.hidden = true; document.body.classList.remove('user-copy-page-editor-open'); @@ -411,6 +472,7 @@ if (state.previousFocus && typeof state.previousFocus.focus === 'function') { state.previousFocus.focus(); } + return true; } launch.addEventListener('click', openEditor); @@ -429,7 +491,15 @@ (tab === 'shared' ? sharedTab : pageTab).focus(); }); localeSelect.addEventListener('change', function () { - state.locale = localeSelect.value; + var previousLocale = state.locale; + var nextLocale = localeSelect.value; + if (hasDirtyLocale(previousLocale) + && !window.confirm('当前语言存在未保存输入,切换后将丢弃这些输入。确认继续?')) { + localeSelect.value = previousLocale; + return; + } + discardLocaleDrafts(previousLocale); + state.locale = nextLocale; state.workspaces.page = null; state.workspaces.shared = null; loadWorkspace(state.activeTab, state.locale).catch(function (error) { @@ -460,5 +530,10 @@ event.preventDefault(); first.focus(); } }); + window.addEventListener('beforeunload', function (event) { + if (state.dirtyKeys.size === 0) return; + event.preventDefault(); + event.returnValue = ''; + }); updateTabUi(); }()); diff --git a/web/public/cloud/admin-user-copy.js b/web/public/cloud/admin-user-copy.js index 2061eef2..f11c3c95 100644 --- a/web/public/cloud/admin-user-copy.js +++ b/web/public/cloud/admin-user-copy.js @@ -30,6 +30,8 @@ var synchronizeButton = document.getElementById('user-copy-synchronize'); var historyOpenButton = document.getElementById('user-copy-history-open'); var uncertain = false; + var draftBuffer = new Map(); + var dirtyKeys = new Set(); function element(tag, className, text) { var node = document.createElement(tag); @@ -43,16 +45,16 @@ feedback.className = 'admin-config-status' + (state ? ' is-' + state : ''); } - function stateLabel(entry) { - if (entry.hidden) return '已隐藏'; + function stateLabel(entry, buffered) { + if (buffered ? buffered.hidden : entry.hidden) return '已隐藏'; if (entry.draft && entry.draft.validation_state !== 'valid') return '无效草稿'; if (entry.state === 'published') return '已发布'; if (entry.state === 'draft') return '仅有草稿'; return '待翻译'; } - function stateClass(entry) { - if (entry.hidden) return 'is-hidden'; + function stateClass(entry, buffered) { + if (buffered ? buffered.hidden : entry.hidden) return 'is-hidden'; if (entry.draft && entry.draft.validation_state !== 'valid') return 'is-invalid'; return entry.state === 'published' ? 'is-published' : entry.state === 'draft' ? 'is-draft' : 'is-missing'; @@ -64,6 +66,59 @@ return ''; } + function bufferKey(locale, copyKey) { + return String(locale || '') + '\u0000' + String(copyKey || ''); + } + + function draftFor(entry, locale) { + var key = bufferKey(locale, entry.key); + if (draftBuffer.has(key)) return draftBuffer.get(key); + return { + text: textFor(entry), + hidden: entry.hidden === true, + }; + } + + function rememberDraft(entry, locale, text, hidden) { + var key = bufferKey(locale, entry.key); + var baseline = { + text: textFor(entry), + hidden: entry.hidden === true, + }; + if (text === baseline.text && hidden === baseline.hidden) { + draftBuffer.delete(key); + dirtyKeys.delete(key); + } else { + draftBuffer.set(key, { text: text, hidden: hidden }); + dirtyKeys.add(key); + } + updatePublishButton(); + } + + function clearBufferedDraft(locale, copyKey) { + var key = bufferKey(locale, copyKey); + draftBuffer.delete(key); + dirtyKeys.delete(key); + updatePublishButton(); + } + + function hasDirtyLocale(locale) { + var prefix = String(locale || '') + '\u0000'; + return Array.from(dirtyKeys).some(function (key) { + return key.indexOf(prefix) === 0; + }); + } + + function discardLocaleDrafts(locale) { + var prefix = String(locale || '') + '\u0000'; + Array.from(dirtyKeys).forEach(function (key) { + if (key.indexOf(prefix) !== 0) return; + dirtyKeys.delete(key); + draftBuffer.delete(key); + }); + updatePublishButton(); + } + function isToast(entry) { return entry.kind === 'toast_title' || entry.kind === 'toast_body'; } @@ -102,16 +157,17 @@ var term = search.value.trim().toLowerCase(); var state = stateFilter.value; return (workspace.entries || []).filter(function (entry) { + var buffered = draftFor(entry, localeSelect.value); if (surfaceFilter.value && entry.editor_surface !== surfaceFilter.value) return false; - if (state && (entry.hidden ? 'hidden' : entry.state) !== state) return false; + if (state && (buffered.hidden ? 'hidden' : entry.state) !== state) return false; if (!term) return true; return String(entry.key).toLowerCase().indexOf(term) !== -1 || String(entry.source).toLowerCase().indexOf(term) !== -1; }); } - function meta(entry) { + function meta(entry, buffered) { var row = element('div', 'user-copy-entry-meta'); row.append(element('code', '', entry.key)); row.append(element('span', 'user-copy-surface', surfaceLabel(entry.editor_surface))); @@ -119,7 +175,8 @@ row.append(element('span', 'user-copy-group', entry.editor_group)); } row.append(element('span', 'user-copy-kind', entry.kind)); - var status = element('span', 'user-copy-state ' + stateClass(entry), stateLabel(entry)); + var status = element('span', 'user-copy-state ' + stateClass(entry, buffered), + stateLabel(entry, buffered)); row.append(status); if (entry.criticality !== 'normal') { row.append(element('span', 'user-copy-critical', entry.criticality === 'critical' ? '关键文案' : '必需文案')); @@ -128,9 +185,10 @@ } function renderEntry(entry) { + var buffered = draftFor(entry, localeSelect.value); var card = element('article', 'user-copy-entry'); card.dataset.copyKey = entry.key; - card.append(meta(entry)); + card.append(meta(entry, buffered)); var columns = element('div', 'user-copy-entry-columns'); var source = element('section', 'user-copy-source'); @@ -140,11 +198,12 @@ var target = element('section', 'user-copy-target'); var targetHead = element('div', 'user-copy-target-head'); targetHead.append(element('label', 'user-copy-field-label', '目标语言草稿')); + var hide = null; if (entry.allow_hide) { var hideLabel = element('label', 'user-copy-hide'); - var hide = element('input'); + hide = element('input'); hide.type = 'checkbox'; - hide.checked = entry.hidden === true; + hide.checked = buffered.hidden; hide.disabled = !canManage || !workspace.write_ready || uncertain; hideLabel.append(hide, element('span', '', '发布时隐藏')); targetHead.append(hideLabel); @@ -152,11 +211,21 @@ var textarea = element('textarea', 'form-control'); textarea.rows = 3; textarea.maxLength = Number(entry.max_length) || 4000; - textarea.value = textFor(entry); + textarea.value = buffered.text; var localeOption = localeSelect.options[localeSelect.selectedIndex]; textarea.placeholder = '输入 ' + (localeOption ? localeOption.text : '目标语言') + '译文'; textarea.readOnly = !canManage || !workspace.write_ready || uncertain; textarea.setAttribute('aria-label', entry.key + ' 的目标语言草稿'); + var bufferCurrentDraft = function () { + rememberDraft( + entry, + localeSelect.value, + textarea.value, + Boolean(hide && hide.checked) + ); + }; + textarea.addEventListener('input', bufferCurrentDraft); + if (hide) hide.addEventListener('change', bufferCurrentDraft); target.append(targetHead, textarea); if ((entry.parameters || []).length) { target.append(element('p', 'user-copy-parameters', '必须保留参数:' + entry.parameters.join('、'))); @@ -183,7 +252,7 @@ save.type = 'button'; save.disabled = !canManage || !workspace.write_ready || uncertain; save.addEventListener('click', function () { - writeEntry(entry, textarea.value, card.querySelector('.user-copy-hide input')); + writeEntry(entry, textarea.value, hide); }); actions.append(previewButton, save); card.append(actions); @@ -195,18 +264,23 @@ list.replaceChildren(); entries.forEach(function (entry) { list.append(renderEntry(entry)); }); empty.hidden = entries.length !== 0; - if (publishLocaleButton) { - var invalidDraft = (workspace.entries || []).some(function (entry) { - return entry.draft && entry.draft.validation_state !== 'valid'; - }); - publishLocaleButton.disabled = !canManage || !workspace.write_ready - || uncertain || invalidDraft; - publishLocaleButton.title = invalidDraft - ? '当前页面存在无效或过期草稿,请先修正。' : ''; - } + updatePublishButton(); if (historyOpenButton) historyOpenButton.disabled = !localeSelect.value; } + function updatePublishButton() { + if (!publishLocaleButton || !workspace) return; + var invalidDraft = (workspace.entries || []).some(function (entry) { + return entry.draft && entry.draft.validation_state !== 'valid'; + }); + var unsaved = dirtyKeys.size > 0; + publishLocaleButton.disabled = !canManage || !workspace.write_ready + || uncertain || invalidDraft || unsaved; + publishLocaleButton.title = unsaved + ? '存在未保存输入,请先逐条保存草稿。' + : invalidDraft ? '当前目录存在无效或过期草稿,请先修正。' : ''; + } + function escapeHtml(value) { return String(value).replace(/[&<>"']/g, function (character) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character]; @@ -295,6 +369,7 @@ inform('目标语言草稿不能为空。', 'error'); return; } + var locale = localeSelect.value; var endpoint = '/admin/user-copy/entries/' + encodeURIComponent(entry.key) + '/draft'; try { @@ -302,12 +377,13 @@ var result = await transport.mutate(endpoint, { method: 'PUT', body: { - locale: localeSelect.value, + locale: locale, text: text, hidden: Boolean(hideInput && hideInput.checked), draft_version: Number(entry.draft_version) || 0, }, }); + clearBufferedDraft(locale, entry.key); await loadWorkspace(); var saved = result && result.entry ? result.entry : null; if (saved && saved.validation_state !== 'valid') { @@ -324,6 +400,10 @@ } async function publishLocale() { + if (dirtyKeys.size > 0) { + inform('存在未保存输入,请先逐条保存草稿后再发布。', 'error'); + return; + } if (!transport || !canManage || !workspace.write_ready || uncertain) return; if (!window.confirm('确认发布当前目标语言的全部有效草稿?用户页面会切换到新的不可变目录版本。')) return; try { @@ -410,6 +490,19 @@ } } + function changeLocale() { + var previousLocale = String(workspace.selected.locale || ''); + var nextLocale = localeSelect.value; + if (nextLocale === previousLocale) return; + if (hasDirtyLocale(previousLocale) + && !window.confirm('当前语言存在未保存输入,切换后将丢弃这些输入。确认继续?')) { + localeSelect.value = previousLocale; + return; + } + discardLocaleDrafts(previousLocale); + loadWorkspace(); + } + function updateUrl() { if (!window.history || !window.history.replaceState) return; var query = new URLSearchParams(window.location.search); @@ -430,7 +523,7 @@ control.addEventListener(control === search ? 'input' : 'change', renderEntries); }); groupSelect.addEventListener('change', loadWorkspace); - localeSelect.addEventListener('change', loadWorkspace); + localeSelect.addEventListener('change', changeLocale); document.getElementById('user-copy-preview-close').addEventListener('click', closeDrawers); document.getElementById('user-copy-history-close').addEventListener('click', closeDrawers); if (historyOpenButton) historyOpenButton.addEventListener('click', openHistory); @@ -440,4 +533,9 @@ document.addEventListener('keydown', function (event) { if (event.key === 'Escape') closeDrawers(); }); + window.addEventListener('beforeunload', function (event) { + if (dirtyKeys.size === 0) return; + event.preventDefault(); + event.returnValue = ''; + }); }()); diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index e3df1777..667cff04 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110707' scope='global'} +{assign var=venix_asset_version value='2026110708' scope='global'} diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index 580a07b1..69fca52e 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110707'") + && str_contains($assets, "venix_asset_version value='2026110708'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.'); diff --git a/web/tests/UserCopyAdminUiContractTest.php b/web/tests/UserCopyAdminUiContractTest.php index d7fa417b..48819e0b 100644 --- a/web/tests/UserCopyAdminUiContractTest.php +++ b/web/tests/UserCopyAdminUiContractTest.php @@ -115,9 +115,40 @@ $writeStart = strpos($javascript, 'async function writeEntry('); $writeEnd = strpos($javascript, 'async function publishLocale(', $writeStart); $writeBody = substr($javascript, $writeStart, $writeEnd - $writeStart); $assert(!str_contains($writeBody, 'page:') - && str_contains($writeBody, 'locale: localeSelect.value') + && str_contains($writeBody, 'var locale = localeSelect.value') + && str_contains($writeBody, 'locale: locale') && str_contains($writeBody, 'draft_version:'), 'Draft writes still depend on the retired page selector or lost version locking.'); +$assert(str_contains($javascript, 'var draftBuffer = new Map()') + && str_contains($javascript, 'var dirtyKeys = new Set()') + && str_contains($javascript, 'function bufferKey(locale, copyKey)') + && str_contains($javascript, "textarea.addEventListener('input'") + && str_contains($javascript, "hide.addEventListener('change'") + && str_contains($javascript, 'textarea.value = buffered.text') + && str_contains($javascript, 'hide.checked = buffered.hidden'), + 'Administrator draft inputs are not buffered across catalog redraws.'); +$assert(str_contains($writeBody, 'var locale = localeSelect.value') + && str_contains($writeBody, 'clearBufferedDraft(locale, entry.key)') + && substr_count($writeBody, + 'clearBufferedDraft(locale, entry.key)') === 1 + && strpos($writeBody, 'clearBufferedDraft(locale, entry.key)') + > strpos($writeBody, 'await transport.mutate(') + && strpos($writeBody, 'clearBufferedDraft(locale, entry.key)') + < strpos($writeBody, '} catch (error)'), + 'The administrator clears buffered input before confirmation or on failure.'); +$assert(str_contains($javascript, 'function changeLocale()') + && str_contains($javascript, 'hasDirtyLocale(previousLocale)') + && str_contains($javascript, 'discardLocaleDrafts(previousLocale)') + && str_contains($javascript, + "localeSelect.addEventListener('change', changeLocale)") + && str_contains($javascript, "window.addEventListener('beforeunload'") + && str_contains($javascript, 'event.returnValue ='), + 'Dirty administrator inputs are not protected during locale or page exit.'); +$assert(str_contains($javascript, 'if (dirtyKeys.size > 0)') + && str_contains($javascript, + '存在未保存输入,请先逐条保存草稿后再发布。') + && str_contains($javascript, '|| uncertain || invalidDraft || unsaved'), + 'Locale publication is not blocked while browser-only inputs remain unsaved.'); $assert(str_contains($javascript, 'validation_state') && str_contains($javascript, 'user-copy-validation-error') && str_contains($javascript, '存在无效或过期草稿'), diff --git a/web/tests/UserCopyPageEditorContractTest.php b/web/tests/UserCopyPageEditorContractTest.php index b3bb5484..6f6d5584 100644 --- a/web/tests/UserCopyPageEditorContractTest.php +++ b/web/tests/UserCopyPageEditorContractTest.php @@ -92,6 +92,35 @@ $assert(str_contains($javascript, 'function applyWorkspace(channel, workspace)') 'loadWorkspace(state.activeTab, state.locale)' ) >= 3, 'Inactive-tab responses can render directly or active-tab refresh was lost.'); +$assert(str_contains($javascript, 'draftBuffer: new Map()') + && str_contains($javascript, 'dirtyKeys: new Set()') + && str_contains($javascript, 'function bufferKey(locale, copyKey)') + && str_contains($javascript, 'var buffered = draftFor(entry, state.locale)') + && str_contains($javascript, 'textarea.value = buffered.text') + && str_contains($javascript, "textarea.addEventListener('input'") + && str_contains($javascript, + 'rememberDraft(entry, state.locale, textarea.value)'), + 'Page-editor inputs are not buffered across tab or search redraws.'); +$saveStart = strpos($javascript, 'async function saveDraft('); +$saveEnd = strpos($javascript, 'function openEditor(', $saveStart); +$saveBody = substr($javascript, $saveStart, $saveEnd - $saveStart); +$assert(str_contains($saveBody, 'var locale = state.locale') + && substr_count($saveBody, 'clearBufferedDraft(locale, entry.key)') === 1 + && strpos($saveBody, 'clearBufferedDraft(locale, entry.key)') + > strpos($saveBody, 'await transport.mutate(') + && strpos($saveBody, 'clearBufferedDraft(locale, entry.key)') + < strpos($saveBody, '} catch (error)'), + 'The page editor clears buffered input before confirmation or on failure.'); +$assert(str_contains($javascript, 'state.dirtyKeys.size > 0') + && str_contains($javascript, 'discardAllDrafts()') + && str_contains($javascript, 'hasDirtyLocale(previousLocale)') + && str_contains($javascript, 'discardLocaleDrafts(previousLocale)') + && str_contains($javascript, 'localeSelect.value = previousLocale') + && str_contains($javascript, "window.addEventListener('beforeunload'") + && str_contains($javascript, 'event.returnValue =') + && str_contains($javascript, '存在未保存输入,关闭编辑器后将丢弃这些输入。') + && str_contains($javascript, '当前语言存在未保存输入,切换后将丢弃这些输入。'), + 'Page-editor dirty input is not guarded before close or locale changes.'); $assert(str_contains($javascript, "locale: bootstrap.runtime_locale === 'zh-CN'") && str_contains($javascript,