|
|
(function () {
|
|
|
'use strict';
|
|
|
|
|
|
var root = document.querySelector('[data-user-copy-admin]');
|
|
|
var bootstrapNode = document.getElementById('user-copy-bootstrap');
|
|
|
if (!root || !bootstrapNode) return;
|
|
|
|
|
|
var workspace;
|
|
|
try { workspace = JSON.parse(bootstrapNode.textContent || '{}'); }
|
|
|
catch (error) { workspace = null; }
|
|
|
if (!workspace || workspace.schema !== 1) return;
|
|
|
|
|
|
var canManage = root.dataset.canManage === '1';
|
|
|
var transport = window.VenixAdminRequestRuntime
|
|
|
? window.VenixAdminRequestRuntime.create() : null;
|
|
|
var feedback = document.getElementById('user-copy-feedback');
|
|
|
var groupSelect = document.getElementById('user-copy-group');
|
|
|
var localeSelect = document.getElementById('user-copy-locale');
|
|
|
var search = document.getElementById('user-copy-search');
|
|
|
var stateFilter = document.getElementById('user-copy-state');
|
|
|
var surfaceFilter = document.getElementById('user-copy-surface');
|
|
|
var catalog = document.getElementById('user-copy-catalog');
|
|
|
var list = document.getElementById('user-copy-list');
|
|
|
var empty = document.getElementById('user-copy-empty');
|
|
|
var paginationStatus = document.getElementById('user-copy-pagination-status');
|
|
|
var loadMoreButton = document.getElementById('user-copy-load-more');
|
|
|
var preview = document.getElementById('user-copy-preview');
|
|
|
var previewFrame = document.getElementById('user-copy-preview-frame');
|
|
|
var history = document.getElementById('user-copy-history');
|
|
|
var historyList = document.getElementById('user-copy-history-list');
|
|
|
var locales = document.getElementById('user-copy-locales');
|
|
|
var localeList = document.getElementById('user-copy-locale-list');
|
|
|
var localeForm = document.getElementById('user-copy-locale-form');
|
|
|
var localeFormTitle = document.getElementById('user-copy-locale-form-title');
|
|
|
var localeCode = document.getElementById('user-copy-locale-code');
|
|
|
var localeName = document.getElementById('user-copy-locale-name');
|
|
|
var localeEnabled = document.getElementById('user-copy-locale-enabled');
|
|
|
var localeFormFeedback = document.getElementById('user-copy-locale-form-feedback');
|
|
|
var localeSaveButton = document.getElementById('user-copy-locale-save');
|
|
|
var localeNewButton = document.getElementById('user-copy-locale-new');
|
|
|
var backdrop = document.getElementById('user-copy-backdrop');
|
|
|
var publishLocaleButton = document.getElementById('user-copy-publish');
|
|
|
var synchronizeButton = document.getElementById('user-copy-synchronize');
|
|
|
var historyOpenButton = document.getElementById('user-copy-history-open');
|
|
|
var localesOpenButton = document.getElementById('user-copy-locales-open');
|
|
|
var readiness = document.getElementById('user-copy-readiness');
|
|
|
var readinessMessage = document.getElementById('user-copy-readiness-message');
|
|
|
var readinessErrors = document.getElementById('user-copy-readiness-errors');
|
|
|
var uncertain = false;
|
|
|
var draftBuffer = new Map();
|
|
|
var dirtyKeys = new Set();
|
|
|
var catalogPerPage = 25;
|
|
|
var catalogBusy = false;
|
|
|
var activeReadController = null;
|
|
|
var requestSerial = 0;
|
|
|
var appliedFilterSignature = '';
|
|
|
var searchTimer = null;
|
|
|
|
|
|
function element(tag, className, text) {
|
|
|
var node = document.createElement(tag);
|
|
|
if (className) node.className = className;
|
|
|
if (text !== undefined) node.textContent = text;
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function inform(message, state) {
|
|
|
feedback.textContent = String(message || '');
|
|
|
feedback.className = 'admin-config-status' + (state ? ' is-' + state : '');
|
|
|
}
|
|
|
|
|
|
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, 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';
|
|
|
}
|
|
|
|
|
|
function textFor(entry) {
|
|
|
if (entry.draft && typeof entry.draft.text === 'string') return entry.draft.text;
|
|
|
if (entry.published && typeof entry.published.text === 'string') return entry.published.text;
|
|
|
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';
|
|
|
}
|
|
|
|
|
|
function surfaceLabel(surface) {
|
|
|
return {
|
|
|
admin: '后台补充',
|
|
|
dialog: '弹窗与确认',
|
|
|
feedback: '反馈与状态',
|
|
|
task: '任务中心',
|
|
|
accessibility: '无障碍与字段',
|
|
|
}[surface] || String(surface || '动态文案');
|
|
|
}
|
|
|
|
|
|
function fillSelect(select, options, selected) {
|
|
|
select.replaceChildren();
|
|
|
(options || []).forEach(function (option) {
|
|
|
var node = element('option', '', option.label || option.id);
|
|
|
node.value = option.id;
|
|
|
node.selected = option.id === selected;
|
|
|
select.append(node);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function fillLocaleSelect(selected) {
|
|
|
localeSelect.replaceChildren();
|
|
|
(workspace.locales || []).forEach(function (locale) {
|
|
|
var label = String(locale.label || locale.id || '');
|
|
|
if (locale.enabled !== true) label += '(已停用)';
|
|
|
var option = element('option', '', label);
|
|
|
option.value = String(locale.id || '');
|
|
|
option.selected = option.value === selected;
|
|
|
localeSelect.append(option);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function renderCoverage(coverage) {
|
|
|
coverage = coverage || {};
|
|
|
document.getElementById('user-copy-total').textContent = String(coverage.total || 0);
|
|
|
document.getElementById('user-copy-published').textContent = String(coverage.published || 0);
|
|
|
document.getElementById('user-copy-draft').textContent = String(coverage.draft || 0);
|
|
|
document.getElementById('user-copy-missing').textContent = String(coverage.missing || 0);
|
|
|
var percent = Math.max(0, Math.min(100, Number(coverage.percent) || 0));
|
|
|
document.getElementById('user-copy-percent').textContent = percent.toFixed(0) + '%';
|
|
|
document.getElementById('user-copy-progress-bar').style.width = percent + '%';
|
|
|
}
|
|
|
|
|
|
function readinessStateLabel(state) {
|
|
|
return {
|
|
|
invalid: '校验失败',
|
|
|
stale: '源文案已变化',
|
|
|
pending: '等待校验',
|
|
|
}[state] || '无法发布';
|
|
|
}
|
|
|
|
|
|
function readinessErrorLabel(error) {
|
|
|
return {
|
|
|
source_contract_changed: '中文源文案或参数合同已变化',
|
|
|
validation_result_corrupt: '校验结果无法读取',
|
|
|
validation_state_unknown: '校验状态无法识别',
|
|
|
}[error] || String(error || '请检查草稿');
|
|
|
}
|
|
|
|
|
|
function renderPublicationReadiness(publicationReadiness) {
|
|
|
publicationReadiness = publicationReadiness || {};
|
|
|
var invalid = Number(publicationReadiness.invalid_draft_count) || 0;
|
|
|
var stale = Number(publicationReadiness.stale_draft_count) || 0;
|
|
|
var pending = Number(publicationReadiness.pending_draft_count) || 0;
|
|
|
var blocking = Number(publicationReadiness.blocking_draft_count) || 0;
|
|
|
document.getElementById('user-copy-readiness-invalid').textContent = String(invalid);
|
|
|
document.getElementById('user-copy-readiness-stale').textContent = String(stale);
|
|
|
document.getElementById('user-copy-readiness-pending').textContent = String(pending);
|
|
|
readiness.classList.remove('is-ready', 'is-blocked', 'is-unavailable');
|
|
|
if (publicationReadiness.ready === true) {
|
|
|
readiness.classList.add('is-ready');
|
|
|
readinessMessage.textContent = '当前目标语言的全部草稿均通过检查,可以发布新的目录版本。';
|
|
|
} else if (publicationReadiness.projection_ready !== true) {
|
|
|
readiness.classList.add('is-unavailable');
|
|
|
readinessMessage.textContent = '源码 Manifest 尚未同步,完成同步前不能发布。';
|
|
|
} else if (publicationReadiness.locale_enabled !== true) {
|
|
|
readiness.classList.add('is-unavailable');
|
|
|
readinessMessage.textContent = '当前目标语言已停用,不能发布。';
|
|
|
} else {
|
|
|
readiness.classList.add('is-blocked');
|
|
|
readinessMessage.textContent = '整语种共有 ' + String(blocking)
|
|
|
+ ' 项草稿阻断发布;即使当前筛选未显示,也必须先处理。';
|
|
|
}
|
|
|
readinessErrors.replaceChildren();
|
|
|
(publicationReadiness.first_errors || []).forEach(function (item) {
|
|
|
var errors = Array.isArray(item.errors) ? item.errors : [];
|
|
|
readinessErrors.append(element(
|
|
|
'li', '', String(item.key || '') + ' · '
|
|
|
+ readinessStateLabel(item.validation_state)
|
|
|
+ (errors.length ? ':' + errors.map(readinessErrorLabel).join(';') : '')
|
|
|
));
|
|
|
});
|
|
|
readinessErrors.hidden = readinessErrors.children.length === 0;
|
|
|
}
|
|
|
|
|
|
function filterSignature() {
|
|
|
return JSON.stringify({
|
|
|
locale: localeSelect.value,
|
|
|
group: groupSelect.value,
|
|
|
q: search.value.trim(),
|
|
|
surface: surfaceFilter.value,
|
|
|
state: stateFilter.value,
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function catalogPagination() {
|
|
|
var entries = Array.isArray(workspace.entries) ? workspace.entries : [];
|
|
|
var value = workspace.pagination && typeof workspace.pagination === 'object'
|
|
|
? workspace.pagination : {};
|
|
|
var page = Math.max(1, Number(value.page) || 1);
|
|
|
var perPage = Math.max(1, Number(value.per_page) || catalogPerPage);
|
|
|
var total = Math.max(entries.length, Number(value.total) || entries.length);
|
|
|
var totalPages = Math.max(1, Number(value.total_pages)
|
|
|
|| Math.ceil(total / perPage) || 1);
|
|
|
return {
|
|
|
page: page,
|
|
|
perPage: perPage,
|
|
|
total: total,
|
|
|
totalPages: totalPages,
|
|
|
hasMore: value.has_more === true,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function mergeEntriesByCopyKey(currentEntries, nextEntries) {
|
|
|
var merged = [];
|
|
|
var positions = new Map();
|
|
|
(currentEntries || []).concat(nextEntries || []).forEach(function (entry) {
|
|
|
var key = String(entry && entry.key || '');
|
|
|
if (!key) return;
|
|
|
if (positions.has(key)) {
|
|
|
merged[positions.get(key)] = entry;
|
|
|
return;
|
|
|
}
|
|
|
positions.set(key, merged.length);
|
|
|
merged.push(entry);
|
|
|
});
|
|
|
return merged;
|
|
|
}
|
|
|
|
|
|
function setCatalogBusy(busy) {
|
|
|
catalogBusy = busy;
|
|
|
catalog.setAttribute('aria-busy', busy ? 'true' : 'false');
|
|
|
if (loadMoreButton) loadMoreButton.disabled = busy;
|
|
|
}
|
|
|
|
|
|
function renderPagination() {
|
|
|
var pagination = catalogPagination();
|
|
|
var shown = Array.isArray(workspace.entries) ? workspace.entries.length : 0;
|
|
|
paginationStatus.textContent = '已显示 ' + String(shown)
|
|
|
+ ' / 共 ' + String(pagination.total) + ' 条';
|
|
|
var filtersCurrent = filterSignature() === appliedFilterSignature;
|
|
|
loadMoreButton.hidden = !pagination.hasMore
|
|
|
|| pagination.page >= pagination.totalPages || !filtersCurrent;
|
|
|
loadMoreButton.disabled = catalogBusy;
|
|
|
}
|
|
|
|
|
|
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)));
|
|
|
if (!groupSelect.value && entry.editor_group) {
|
|
|
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, buffered),
|
|
|
stateLabel(entry, buffered));
|
|
|
row.append(status);
|
|
|
if (entry.criticality !== 'normal') {
|
|
|
row.append(element('span', 'user-copy-critical', entry.criticality === 'critical' ? '关键文案' : '必需文案'));
|
|
|
}
|
|
|
return row;
|
|
|
}
|
|
|
|
|
|
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, buffered));
|
|
|
|
|
|
var columns = element('div', 'user-copy-entry-columns');
|
|
|
var source = element('section', 'user-copy-source');
|
|
|
source.append(element('span', 'user-copy-field-label', '中文源文案(只读)'));
|
|
|
source.append(element('div', 'user-copy-source-text', entry.source));
|
|
|
|
|
|
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');
|
|
|
hide = element('input');
|
|
|
hide.type = 'checkbox';
|
|
|
hide.checked = buffered.hidden;
|
|
|
hide.disabled = !canManage || !workspace.write_ready || uncertain;
|
|
|
hideLabel.append(hide, element('span', '', '发布时隐藏'));
|
|
|
targetHead.append(hideLabel);
|
|
|
}
|
|
|
var textarea = element('textarea', 'form-control');
|
|
|
textarea.rows = 3;
|
|
|
textarea.maxLength = Number(entry.max_length) || 4000;
|
|
|
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('、')));
|
|
|
}
|
|
|
if (entry.draft && entry.draft.validation_state !== 'valid') {
|
|
|
var errors = Array.isArray(entry.draft.validation_errors)
|
|
|
? entry.draft.validation_errors : [];
|
|
|
target.append(element(
|
|
|
'p',
|
|
|
'user-copy-validation-error',
|
|
|
'草稿校验未通过' + (errors.length ? ':' + errors.join(';') : '。')
|
|
|
));
|
|
|
}
|
|
|
columns.append(source, target);
|
|
|
card.append(columns);
|
|
|
|
|
|
var actions = element('div', 'user-copy-entry-actions');
|
|
|
var previewButton = element('button', 'btn btn-light btn-sm', isToast(entry) ? '预览 Toast' : '安全预览');
|
|
|
previewButton.type = 'button';
|
|
|
previewButton.addEventListener('click', function () {
|
|
|
previewEntry(entry, textarea.value);
|
|
|
});
|
|
|
var save = element('button', 'btn btn-outline-primary btn-sm', '保存草稿');
|
|
|
save.type = 'button';
|
|
|
save.disabled = !canManage || !workspace.write_ready || uncertain;
|
|
|
save.addEventListener('click', function () {
|
|
|
writeEntry(entry, textarea.value, hide);
|
|
|
});
|
|
|
actions.append(previewButton, save);
|
|
|
card.append(actions);
|
|
|
return card;
|
|
|
}
|
|
|
|
|
|
function renderEntries() {
|
|
|
var entries = Array.isArray(workspace.entries) ? workspace.entries : [];
|
|
|
list.replaceChildren();
|
|
|
entries.forEach(function (entry) { list.append(renderEntry(entry)); });
|
|
|
empty.hidden = entries.length !== 0;
|
|
|
renderPagination();
|
|
|
updatePublishButton();
|
|
|
if (historyOpenButton) historyOpenButton.disabled = !localeSelect.value;
|
|
|
}
|
|
|
|
|
|
function updatePublishButton() {
|
|
|
if (!publishLocaleButton || !workspace) return;
|
|
|
var publicationReadiness = workspace.publication_readiness || {};
|
|
|
var unsaved = dirtyKeys.size > 0;
|
|
|
publishLocaleButton.disabled = !canManage || !workspace.write_ready
|
|
|
|| uncertain || publicationReadiness.ready !== true || unsaved;
|
|
|
publishLocaleButton.title = unsaved
|
|
|
? '存在未保存输入,请先逐条保存草稿。'
|
|
|
: publicationReadiness.ready !== true
|
|
|
? '整语种仍有阻断项,请先完成发布检查。' : '';
|
|
|
}
|
|
|
|
|
|
function escapeHtml(value) {
|
|
|
return String(value).replace(/[&<>"']/g, function (character) {
|
|
|
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character];
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function previewDocument(entry, translation) {
|
|
|
var source = escapeHtml(entry.source);
|
|
|
var target = escapeHtml(translation || '尚未填写目标语言草稿');
|
|
|
var tone = ['success', 'warning', 'error'].indexOf(entry.severity) !== -1
|
|
|
? entry.severity : 'info';
|
|
|
var content = isToast(entry)
|
|
|
? '<article class="toast ' + tone + '"><i></i><div><strong>'
|
|
|
+ (entry.kind === 'toast_title' ? target : '标题预览')
|
|
|
+ '</strong><p>' + (entry.kind === 'toast_body' ? target : '正文预览') + '</p></div></article>'
|
|
|
: '<section class="copy"><span>中文源文案</span><p>' + source
|
|
|
+ '</p><span>目标语言预览</span><p lang="' + escapeHtml(localeSelect.value) + '">' + target + '</p></section>';
|
|
|
return '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
|
+ '<style>body{margin:0;padding:24px;background:#f4f7f9;color:#19364a;font:14px/1.65 system-ui,sans-serif}'
|
|
|
+ '.copy,.toast{border:1px solid #d9e4e8;background:#fff;box-shadow:0 14px 36px rgba(24,55,71,.09)}'
|
|
|
+ '.copy{padding:22px}.copy span{display:block;color:#8295a2;font-size:11px;font-weight:700}.copy p{margin:7px 0 20px;white-space:pre-wrap}'
|
|
|
+ '.toast{padding:16px;display:flex;gap:12px}.toast i{width:10px;height:10px;margin-top:7px;border-radius:50%;background:#16a1a8}'
|
|
|
+ '.toast.success i{background:#24a574}.toast.warning i{background:#e2a029}.toast.error i{background:#da5967}.toast strong{font-size:13px}.toast p{margin:4px 0 0;color:#627985}'
|
|
|
+ '</style></head><body>' + content + '</body></html>';
|
|
|
}
|
|
|
|
|
|
function previewEntry(entry, translation) {
|
|
|
closeDrawers();
|
|
|
previewFrame.srcdoc = previewDocument(entry, translation);
|
|
|
preview.hidden = false;
|
|
|
backdrop.hidden = false;
|
|
|
document.body.classList.add('user-copy-drawer-open');
|
|
|
}
|
|
|
|
|
|
function closeDrawers() {
|
|
|
preview.hidden = true;
|
|
|
history.hidden = true;
|
|
|
locales.hidden = true;
|
|
|
backdrop.hidden = true;
|
|
|
document.body.classList.remove('user-copy-drawer-open');
|
|
|
}
|
|
|
|
|
|
function localeRecord(localeId) {
|
|
|
return (workspace.locales || []).find(function (locale) {
|
|
|
return String(locale.id || '') === String(localeId || '');
|
|
|
}) || null;
|
|
|
}
|
|
|
|
|
|
function resetLocaleForm() {
|
|
|
localeForm.reset();
|
|
|
localeCode.readOnly = false;
|
|
|
localeEnabled.checked = true;
|
|
|
localeFormTitle.textContent = '添加目标语言';
|
|
|
localeFormFeedback.textContent = '';
|
|
|
localeFormFeedback.className = 'user-copy-locale-form-feedback';
|
|
|
}
|
|
|
|
|
|
function editLocale(locale) {
|
|
|
if (!locale) return;
|
|
|
localeCode.value = String(locale.id || '');
|
|
|
localeCode.readOnly = true;
|
|
|
localeName.value = String(locale.label || locale.id || '');
|
|
|
localeEnabled.checked = locale.enabled === true;
|
|
|
localeFormTitle.textContent = '编辑 ' + String(locale.label || locale.id || '');
|
|
|
localeFormFeedback.textContent = '';
|
|
|
localeName.focus();
|
|
|
}
|
|
|
|
|
|
function renderLocaleRegistry() {
|
|
|
localeList.replaceChildren();
|
|
|
var registered = Array.isArray(workspace.locales) ? workspace.locales : [];
|
|
|
if (registered.length === 0) {
|
|
|
localeList.append(element('p', 'user-copy-history-empty', '尚未登记目标语言。'));
|
|
|
return;
|
|
|
}
|
|
|
registered.forEach(function (locale) {
|
|
|
var item = element('article', 'user-copy-locale-item');
|
|
|
var details = element('div');
|
|
|
details.append(element('strong', '', String(locale.label || locale.id || '')),
|
|
|
element('code', '', String(locale.id || '')));
|
|
|
var state = element('span', 'user-copy-locale-state '
|
|
|
+ (locale.enabled === true ? 'is-enabled' : 'is-disabled'),
|
|
|
locale.enabled === true ? '已启用' : '已停用');
|
|
|
var edit = element('button', 'btn btn-light btn-sm', '编辑');
|
|
|
edit.type = 'button';
|
|
|
edit.disabled = !canManage || uncertain;
|
|
|
edit.addEventListener('click', function () { editLocale(locale); });
|
|
|
item.append(details, state, edit);
|
|
|
localeList.append(item);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function openLocales() {
|
|
|
closeDrawers();
|
|
|
resetLocaleForm();
|
|
|
renderLocaleRegistry();
|
|
|
locales.hidden = false;
|
|
|
backdrop.hidden = false;
|
|
|
document.body.classList.add('user-copy-drawer-open');
|
|
|
localeCode.focus();
|
|
|
}
|
|
|
|
|
|
function upsertWorkspaceLocale(saved) {
|
|
|
var next = (workspace.locales || []).filter(function (locale) {
|
|
|
return String(locale.id || '') !== String(saved.locale || '');
|
|
|
});
|
|
|
next.push({
|
|
|
id: String(saved.locale || ''),
|
|
|
label: String(saved.display_name || saved.locale || ''),
|
|
|
enabled: saved.enabled === true,
|
|
|
});
|
|
|
next.sort(function (left, right) {
|
|
|
if (left.enabled !== right.enabled) return left.enabled ? -1 : 1;
|
|
|
return String(left.id || '').localeCompare(String(right.id || ''));
|
|
|
});
|
|
|
workspace.locales = next;
|
|
|
}
|
|
|
|
|
|
async function saveLocale(event) {
|
|
|
event.preventDefault();
|
|
|
if (!transport || !canManage || uncertain) return;
|
|
|
var code = String(localeCode.value || '').trim().replace(/_/g, '-');
|
|
|
var displayName = String(localeName.value || '').trim();
|
|
|
if (!/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(code)) {
|
|
|
localeFormFeedback.textContent = '语言代码无效,请使用 ja、de、zh-TW 或 pt-BR 这类格式。';
|
|
|
localeFormFeedback.className = 'user-copy-locale-form-feedback is-error';
|
|
|
localeCode.focus();
|
|
|
return;
|
|
|
}
|
|
|
if (!displayName) {
|
|
|
localeFormFeedback.textContent = '请输入用户能够识别的语言显示名称。';
|
|
|
localeFormFeedback.className = 'user-copy-locale-form-feedback is-error';
|
|
|
localeName.focus();
|
|
|
return;
|
|
|
}
|
|
|
var previousLocale = String(localeSelect.value || '');
|
|
|
if (hasDirtyLocale(previousLocale)
|
|
|
&& !window.confirm('当前语言存在未保存输入。保存语言设置会重新加载目录并丢弃这些输入,确认继续?')) {
|
|
|
return;
|
|
|
}
|
|
|
localeSaveButton.disabled = true;
|
|
|
localeFormFeedback.textContent = '正在保存语言…';
|
|
|
localeFormFeedback.className = 'user-copy-locale-form-feedback';
|
|
|
try {
|
|
|
var result = await transport.mutate('/admin/user-copy/locales', {
|
|
|
method: 'PUT',
|
|
|
body: {
|
|
|
locale: code,
|
|
|
display_name: displayName,
|
|
|
enabled: localeEnabled.checked,
|
|
|
},
|
|
|
});
|
|
|
var saved = result && result.locale ? result.locale : null;
|
|
|
if (!saved || !saved.locale) throw new Error('语言保存响应无效。');
|
|
|
discardLocaleDrafts(previousLocale);
|
|
|
upsertWorkspaceLocale(saved);
|
|
|
fillLocaleSelect(String(saved.locale));
|
|
|
workspace.selected.locale = String(saved.locale);
|
|
|
appliedFilterSignature = filterSignature();
|
|
|
await loadWorkspace({ page: 1, append: false });
|
|
|
renderLocaleRegistry();
|
|
|
editLocale(localeRecord(saved.locale));
|
|
|
localeFormFeedback.textContent = saved.enabled === true
|
|
|
? '语言已保存,可以开始录入译文。'
|
|
|
: '语言已停用,草稿和历史版本仍保留。';
|
|
|
localeFormFeedback.className = 'user-copy-locale-form-feedback is-success';
|
|
|
} catch (error) {
|
|
|
if (error && error.mutationMayHaveApplied) {
|
|
|
uncertain = true;
|
|
|
localeFormFeedback.textContent = '保存结果无法确认,请刷新页面核对,不要重复提交。';
|
|
|
} else {
|
|
|
localeFormFeedback.textContent = error && error.message
|
|
|
? error.message : '语言保存失败。';
|
|
|
}
|
|
|
localeFormFeedback.className = 'user-copy-locale-form-feedback is-error';
|
|
|
} finally {
|
|
|
localeSaveButton.disabled = uncertain || !canManage;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function openHistory() {
|
|
|
closeDrawers();
|
|
|
historyList.replaceChildren(element('p', 'text-muted', '正在读取发布历史…'));
|
|
|
history.hidden = false;
|
|
|
backdrop.hidden = false;
|
|
|
document.body.classList.add('user-copy-drawer-open');
|
|
|
if (!transport) return;
|
|
|
try {
|
|
|
var result = await transport.read('/admin/user-copy/publications?locale='
|
|
|
+ encodeURIComponent(localeSelect.value));
|
|
|
renderHistory(result && result.history ? result.history.revisions : []);
|
|
|
} catch (error) {
|
|
|
historyList.replaceChildren(element('p', 'alert alert-danger', error.message || '发布历史读取失败。'));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function renderHistory(revisions) {
|
|
|
historyList.replaceChildren();
|
|
|
if (!Array.isArray(revisions) || revisions.length === 0) {
|
|
|
historyList.append(element('p', 'user-copy-history-empty', '该语言尚无已发布目录版本。'));
|
|
|
return;
|
|
|
}
|
|
|
revisions.forEach(function (revision) {
|
|
|
var item = element('article', 'user-copy-history-item');
|
|
|
var head = element('div');
|
|
|
head.append(element('strong', '', 'v' + String(revision.version || revision.id)),
|
|
|
element('time', '', String(revision.published_at || '')));
|
|
|
item.append(head, element('p', '', revision.text
|
|
|
? String(revision.text)
|
|
|
: '目录包含 ' + String(revision.entry_count || 0) + ' 个词条'));
|
|
|
var rollback = element('button', 'btn btn-light btn-sm', '设为当前版本');
|
|
|
rollback.type = 'button';
|
|
|
rollback.disabled = !canManage || !workspace.write_ready || uncertain;
|
|
|
rollback.addEventListener('click', function () {
|
|
|
rollbackEntry(revision.publication_key || revision.id);
|
|
|
});
|
|
|
item.append(rollback);
|
|
|
historyList.append(item);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function writeEntry(entry, text, hideInput) {
|
|
|
if (!transport || !canManage || !workspace.write_ready || uncertain) return;
|
|
|
if (!text.trim() && !(hideInput && hideInput.checked)) {
|
|
|
inform('目标语言草稿不能为空。', 'error');
|
|
|
return;
|
|
|
}
|
|
|
var locale = localeSelect.value;
|
|
|
var endpoint = '/admin/user-copy/entries/' + encodeURIComponent(entry.key)
|
|
|
+ '/draft';
|
|
|
try {
|
|
|
inform('正在保存草稿…');
|
|
|
var result = await transport.mutate(endpoint, {
|
|
|
method: 'PUT',
|
|
|
body: {
|
|
|
locale: locale,
|
|
|
text: text,
|
|
|
hidden: Boolean(hideInput && hideInput.checked),
|
|
|
draft_version: Number(entry.draft_version) || 0,
|
|
|
},
|
|
|
});
|
|
|
clearBufferedDraft(locale, entry.key);
|
|
|
await loadWorkspace({ page: 1, append: false });
|
|
|
var saved = result && result.entry ? result.entry : null;
|
|
|
if (saved && saved.validation_state !== 'valid') {
|
|
|
var errors = Array.isArray(saved.validation_errors)
|
|
|
? saved.validation_errors : [];
|
|
|
inform('草稿已保存,但校验未通过'
|
|
|
+ (errors.length ? ':' + errors.join(';') : '。'), 'error');
|
|
|
} else {
|
|
|
inform('草稿已保存。', 'success');
|
|
|
}
|
|
|
} catch (error) {
|
|
|
handleMutationError(error);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function publishLocale() {
|
|
|
if (dirtyKeys.size > 0) {
|
|
|
inform('存在未保存输入,请先逐条保存草稿后再发布。', 'error');
|
|
|
return;
|
|
|
}
|
|
|
if (!transport || !canManage || !workspace.write_ready || uncertain) return;
|
|
|
if (!window.confirm('确认发布当前目标语言的全部有效草稿?用户页面会切换到新的不可变目录版本。')) return;
|
|
|
try {
|
|
|
inform('正在编译并发布目标语言目录…');
|
|
|
await transport.mutate('/admin/user-copy/publications', {
|
|
|
method: 'POST',
|
|
|
body: { locale: localeSelect.value },
|
|
|
});
|
|
|
inform('目标语言目录已发布。', 'success');
|
|
|
await loadWorkspace();
|
|
|
} catch (error) {
|
|
|
handleMutationError(error);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function synchronizeManifest() {
|
|
|
if (!transport || !canManage || uncertain) return;
|
|
|
if (!window.confirm('确认同步当前源码词条?已删除词条会标记为孤立,中文或参数合同变化会使对应草稿失效。')) return;
|
|
|
synchronizeButton.disabled = true;
|
|
|
try {
|
|
|
inform('正在同步源码词条…');
|
|
|
await transport.mutate('/admin/user-copy/synchronize', {
|
|
|
method: 'POST',
|
|
|
body: {},
|
|
|
});
|
|
|
inform('源码词条已同步。', 'success');
|
|
|
await loadWorkspace();
|
|
|
} catch (error) {
|
|
|
handleMutationError(error);
|
|
|
} finally {
|
|
|
synchronizeButton.disabled = uncertain;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function rollbackEntry(publicationKey) {
|
|
|
if (!transport || !canManage || !workspace.write_ready || uncertain) return;
|
|
|
if (!publicationKey || !window.confirm('确认把该历史目录重新设为当前公开版本?')) return;
|
|
|
try {
|
|
|
inform('正在切换到历史公开版本…');
|
|
|
await transport.mutate('/admin/user-copy/publications/'
|
|
|
+ encodeURIComponent(publicationKey) + '/rollback', {
|
|
|
method: 'POST',
|
|
|
body: { locale: localeSelect.value },
|
|
|
});
|
|
|
closeDrawers();
|
|
|
inform('历史目录已设为当前公开版本。', 'success');
|
|
|
await loadWorkspace();
|
|
|
} catch (error) {
|
|
|
handleMutationError(error);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function handleMutationError(error) {
|
|
|
if (error && error.mutationMayHaveApplied) {
|
|
|
uncertain = true;
|
|
|
inform('请求结果无法确认,请刷新页面核对后再操作,不要重复提交。', 'error');
|
|
|
renderEntries();
|
|
|
return;
|
|
|
}
|
|
|
inform(error && error.message ? error.message : '译文操作失败。', 'error');
|
|
|
}
|
|
|
|
|
|
function workspaceQuery(page) {
|
|
|
var query = new URLSearchParams();
|
|
|
query.set('channel', 'advanced');
|
|
|
query.set('locale', localeSelect.value);
|
|
|
query.set('catalog_page', String(page));
|
|
|
query.set('per_page', String(catalogPerPage));
|
|
|
if (groupSelect.value) query.set('group', groupSelect.value);
|
|
|
if (search.value.trim()) query.set('q', search.value.trim());
|
|
|
if (surfaceFilter.value) query.set('surface', surfaceFilter.value);
|
|
|
if (stateFilter.value) query.set('state', stateFilter.value);
|
|
|
return query;
|
|
|
}
|
|
|
|
|
|
async function loadWorkspace(options) {
|
|
|
if (!transport) return;
|
|
|
var request = options && typeof options === 'object' ? options : {};
|
|
|
var page = Math.max(1, Number(request.page) || 1);
|
|
|
var append = request.append === true && page > 1;
|
|
|
var signature = filterSignature();
|
|
|
if (activeReadController) activeReadController.abort('superseded');
|
|
|
var controller = new window.AbortController();
|
|
|
activeReadController = controller;
|
|
|
var serial = ++requestSerial;
|
|
|
setCatalogBusy(true);
|
|
|
inform(append ? '正在加载更多动态文案…' : '正在读取动态文案目录…');
|
|
|
try {
|
|
|
var query = workspaceQuery(page);
|
|
|
var result = await transport.read('/admin/user-copy/entries?'
|
|
|
+ query.toString(), { signal: controller.signal });
|
|
|
if (controller.signal.aborted || serial !== requestSerial
|
|
|
|| signature !== filterSignature()) return;
|
|
|
if (!result || !result.workspace || result.workspace.schema !== 1) {
|
|
|
throw new Error('译文目录响应无效。');
|
|
|
}
|
|
|
var nextWorkspace = result.workspace;
|
|
|
var nextPagination = nextWorkspace.pagination || {};
|
|
|
if (Number(nextPagination.page) && Number(nextPagination.page) !== page) {
|
|
|
throw new Error('译文目录分页响应无效。');
|
|
|
}
|
|
|
var previousEntries = append && Array.isArray(workspace.entries)
|
|
|
? workspace.entries : [];
|
|
|
nextWorkspace.entries = append
|
|
|
? mergeEntriesByCopyKey(previousEntries, nextWorkspace.entries)
|
|
|
: mergeEntriesByCopyKey([], nextWorkspace.entries);
|
|
|
workspace = nextWorkspace;
|
|
|
fillLocaleSelect(workspace.selected.locale);
|
|
|
appliedFilterSignature = signature;
|
|
|
fillSelect(groupSelect, [{ id: '', label: '全部文案分组' }]
|
|
|
.concat(workspace.groups || []), workspace.authoring.group);
|
|
|
updateUrl();
|
|
|
renderCoverage(workspace.coverage);
|
|
|
renderPublicationReadiness(workspace.publication_readiness);
|
|
|
renderEntries();
|
|
|
inform(workspace.write_ready
|
|
|
? (append ? '更多动态文案已加载。' : '动态文案目录已更新。')
|
|
|
: workspace.write_block_reason, workspace.write_ready ? 'success' : '');
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted || serial !== requestSerial
|
|
|
|| signature !== filterSignature()) return;
|
|
|
inform(error.message || '动态文案目录读取失败。', 'error');
|
|
|
} finally {
|
|
|
if (serial !== requestSerial || signature !== filterSignature()) return;
|
|
|
if (activeReadController === controller) activeReadController = null;
|
|
|
setCatalogBusy(false);
|
|
|
renderPagination();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function clearSearchTimer() {
|
|
|
if (searchTimer === null) return;
|
|
|
window.clearTimeout(searchTimer);
|
|
|
searchTimer = null;
|
|
|
}
|
|
|
|
|
|
function reloadFirstPage() {
|
|
|
clearSearchTimer();
|
|
|
return loadWorkspace({ page: 1, append: false });
|
|
|
}
|
|
|
|
|
|
function scheduleSearchReload() {
|
|
|
clearSearchTimer();
|
|
|
if (activeReadController) activeReadController.abort('filter_changed');
|
|
|
renderPagination();
|
|
|
searchTimer = window.setTimeout(function () {
|
|
|
searchTimer = null;
|
|
|
loadWorkspace({ page: 1, append: false });
|
|
|
}, 250);
|
|
|
}
|
|
|
|
|
|
function loadMore() {
|
|
|
if (catalogBusy || filterSignature() !== appliedFilterSignature) return;
|
|
|
var pagination = catalogPagination();
|
|
|
if (!pagination.hasMore || pagination.page >= pagination.totalPages) return;
|
|
|
loadWorkspace({ page: pagination.page + 1, append: true });
|
|
|
}
|
|
|
|
|
|
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);
|
|
|
reloadFirstPage();
|
|
|
}
|
|
|
|
|
|
function updateUrl() {
|
|
|
if (!window.history || !window.history.replaceState) return;
|
|
|
var query = new URLSearchParams(window.location.search);
|
|
|
query.delete('page');
|
|
|
query.delete('channel');
|
|
|
if (groupSelect.value) query.set('group', groupSelect.value);
|
|
|
else query.delete('group');
|
|
|
query.set('locale', localeSelect.value);
|
|
|
window.history.replaceState(window.history.state, '', window.location.pathname + '?' + query.toString());
|
|
|
}
|
|
|
|
|
|
fillSelect(groupSelect, [{ id: '', label: '全部文案分组' }]
|
|
|
.concat(workspace.groups || []), workspace.authoring.group);
|
|
|
fillLocaleSelect(workspace.selected.locale);
|
|
|
appliedFilterSignature = filterSignature();
|
|
|
renderCoverage(workspace.coverage);
|
|
|
renderPublicationReadiness(workspace.publication_readiness);
|
|
|
renderEntries();
|
|
|
search.addEventListener('input', scheduleSearchReload);
|
|
|
[stateFilter, surfaceFilter].forEach(function (control) {
|
|
|
control.addEventListener('change', reloadFirstPage);
|
|
|
});
|
|
|
groupSelect.addEventListener('change', reloadFirstPage);
|
|
|
localeSelect.addEventListener('change', changeLocale);
|
|
|
if (loadMoreButton) loadMoreButton.addEventListener('click', loadMore);
|
|
|
document.getElementById('user-copy-preview-close').addEventListener('click', closeDrawers);
|
|
|
document.getElementById('user-copy-history-close').addEventListener('click', closeDrawers);
|
|
|
document.getElementById('user-copy-locales-close').addEventListener('click', closeDrawers);
|
|
|
if (historyOpenButton) historyOpenButton.addEventListener('click', openHistory);
|
|
|
if (localesOpenButton) localesOpenButton.addEventListener('click', openLocales);
|
|
|
if (synchronizeButton) synchronizeButton.addEventListener('click', synchronizeManifest);
|
|
|
if (publishLocaleButton) publishLocaleButton.addEventListener('click', publishLocale);
|
|
|
if (localeNewButton) localeNewButton.addEventListener('click', resetLocaleForm);
|
|
|
if (localeForm) localeForm.addEventListener('submit', saveLocale);
|
|
|
backdrop.addEventListener('click', closeDrawers);
|
|
|
document.addEventListener('keydown', function (event) {
|
|
|
if (event.key === 'Escape') closeDrawers();
|
|
|
});
|
|
|
window.addEventListener('beforeunload', function (event) {
|
|
|
if (dirtyKeys.size === 0) return;
|
|
|
event.preventDefault();
|
|
|
event.returnValue = '';
|
|
|
});
|
|
|
loadWorkspace({ page: 1, append: false });
|
|
|
}());
|