Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions web/i18n-en.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

110 changes: 93 additions & 17 deletions web/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
[/(\d{4})年(\d{1,2})月/g, (_, y, m) => `${MONTHS[m - 1] || m} ${y}`],
[/(^|[^\d])(\d{1,2})月(?![\u3400-\u9fff])/g, (_, pre, m) => pre + (MONTHS[m - 1] || m)],
[/共\s*(\d+)\s*(?=[A-Za-z])/g, '$1 '],
[/共\s*(\d+)\s*(条|个|项)/g, (_, n) => `${n} ${Number(n) === 1 ? 'item' : 'items'}`],
[/(\d{4}-\d{2}-\d{2})\s*至\s*(\d{4}-\d{2}-\d{2})/g, '$1 – $2'],
[/(\d+(?:\.\d+)?)\s*(次|步|个|台|条|篇)(?![\u3400-\u9fff])/g, (_, n, u) => {
const word = UNITS[u][Number(n) === 1 ? 0 : 1];
Expand All @@ -122,14 +123,17 @@
return trimmed && Object.prototype.hasOwnProperty.call(dict, trimmed) ? text.replace(trimmed, dict[trimmed]) : text;
}

function translate(text) {
function translate(text, exactOnly) {
if (!text || !HAN.test(text)) return text;
const hit = cache.get(text);
const cacheKey = exactOnly ? '=' + text : text;
const hit = cache.get(cacheKey);
if (hit !== undefined) return hit;
const trimmed = text.trim();
let out;
if (Object.prototype.hasOwnProperty.call(dict, trimmed)) {
out = text.replace(trimmed, dict[trimmed]);
} else if (exactOnly) {
return text;
} else {
out = fragmentRE ? text.replace(fragmentRE, m => dict[m]) : text;
if (sentenceRE && HAN.test(out)) out = out.replace(sentenceRE, m => dict[m]);
Expand All @@ -142,18 +146,18 @@
if (/\s$/.test(text) === false) out = out.replace(/\s+$/, '');
}
if (cache.size > 20000) cache.clear();
cache.set(text, out);
cache.set(cacheKey, out);
return out;
}
window.lfTranslate = translate;

function skipped(el) {
return !el || SKIP.has(el.tagName) || (el.closest && el.closest(SKIP_SEL));
}
function translateText(node) {
function translateText(node, partial) {
const parent = node.parentElement;
if (skipped(parent)) return;
const next = parent.closest(DATA_SEL) ? translateExact(node.nodeValue) : translate(node.nodeValue);
const next = parent.closest(DATA_SEL) ? translateExact(node.nodeValue) : translate(node.nodeValue, partial);
if (next !== node.nodeValue) node.nodeValue = next;
}
function translateAttrs(el) {
Expand All @@ -167,23 +171,95 @@
}
if (el.tagName === 'INPUT' && /^(button|submit|reset)$/i.test(el.type) && HAN.test(el.value)) el.value = translate(el.value);
}
// Copy such as "<strong>平台所有项目共用执行名额</strong>,默认 10 条…" arrives
// split over several text nodes by inline markup, so a dictionary key for the
// whole sentence can never match a single node. Collect runs of text nodes and
// plain inline wrappers inside one block and match dictionary keys across them,
// replacing the run with the translation only when keys cover all of it.
const INLINE = new Set(['A', 'B', 'BR', 'CITE', 'CODE', 'EM', 'I', 'MARK', 'SMALL', 'SPAN', 'STRONG', 'TIME', 'U']);
const byInitial = new Map();
for (const key of fragments) {
const first = key[0];
if (!byInitial.has(first)) byInitial.set(first, []);
byInitial.get(first).push(key);
}
const KEEP_ATTRS = new Set(['class', 'style', 'title', 'aria-label', 'aria-hidden', 'role', 'lang', 'dir', 'data-i18n-skip']);
function inlineOnly(el) {
if (!INLINE.has(el.tagName) || !el.childNodes.length) return false;
for (const attr of el.attributes) if (!KEEP_ATTRS.has(attr.name) && !attr.name.startsWith('data-i18n')) return false;
for (const child of el.childNodes) {
if (child.nodeType === 3) continue;
if (child.nodeType !== 1 || !INLINE.has(child.tagName) || !inlineOnly(child)) return false;
}
return !el.closest(SKIP_SEL) && !el.closest(DATA_SEL);
}
function flatten(nodes) {
return nodes.map(node => {
if (node.nodeType === 3) return node.nodeValue;
return node.childNodes.length ? flatten([...node.childNodes]) : (node.textContent || '');
}).join('');
}
function matchRun(text) {
const out = [];
let i = 0;
let covered = 0;
let leftover = '';
while (i < text.length) {
const keys = byInitial.get(text[i]);
let best = null;
if (keys) for (const key of keys) if (text.startsWith(key, i)) { best = key; break; }
if (best) {
out.push(dict[best]);
covered += best.length;
i += best.length;
} else {
out.push(text[i]);
leftover += text[i];
i += 1;
}
}
// Only merge when the dictionary covers the whole run; a partial match would
// flatten markup around copy that still needs its own translation.
return covered && !leftover.trim() ? out.join('') : null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 英文模式下需求列表表头的 10 个列单元格被合并成一个文本节点,表头与数据列错位

触发条件:英文模式(localStorage['loopforge.lang']='en')打开「需求」页。app/issues.js:161 渲染的表头是 <div class="issue-table-row issue-table-head"> 下 10 个兄弟 <span>(编号/标题/来源/…/操作),每个 span 是 grid 的一列。

原因:mergeRuns 把这 10 个 span 当成同一句被行内标签切开的文案;matchRun 允许用多个互不相关的词条拼接覆盖整段(编号+标题+来源+…),覆盖率满足后就把 10 个单元格删掉、换成一个文本节点。

预期 / 实际

  • 预期(main fd039e5):表头仍是 10 个 <span>:<span>ID</span><span>Title</span>…,与数据行 10 列对齐。
  • 实际(head 6ea4b3f):表头子元素 0 个,只剩一个文本节点 IDTitleSourceAssigneeRepositoryPriorityLinked LOOPCurrent stageProgressActions,挤在第一列里横向溢出(约 451px 宽),后面 9 列表头空白、与数据列不再对齐。

复现

  1. 最小用例(webtest 自带 jsdom,直接加载 web/i18n-en.js + web/i18n.js,<html data-lang="en">):
    <div class="issue-table-row issue-table-head"><span>编号</span><span>标题</span><span>来源</span><span>责任人</span></div>
    • main:{"cells":4,"html":"<span>ID</span><span>Title</span><span>Source</span><span>Assignee</span>"}
    • head:{"cells":0,"html":"IDTitleSourceAssignee"}
  2. 真实浏览器(Chromium 1440×900,静态托管 web/,API 用 webtest 的 createFetchRouter 默认数据,英文模式打开 /#issues):#issueBoard .issue-table-head 子元素 main 10 个、head 0 个;数据行 10 个单元格在两边位置一致(0,76,337,…,1150px),head 表头文本只有一段。

影响范围:同一根因在其他页面也会把带独立样式的兄弟元素压成一行纯文本(在 head 上用 Element.remove/replaceWith 埋点统计到,main 上没有):平台管理概览卡 .platform-metric-info 的 label/数字/说明三行、个人信息浮层 .upp-name-row 的名字与「已登录」徽标、.upp-info-item 的 label/value、流程设置 .flow-settings-sec-head 的标题与副标题、span.required-badge「必填」等,样式(class)随元素一起丢失。中文模式不受影响。

修复方向:只在单个词条完整覆盖合并后的整段时才合并(即 dict[flatten(nodes).trim()] 命中),不要用多个词条拼接;或者跳过带 class、作为 grid/flex 子项的元素。顺手可以给表头这类结构加个回归用例。

}
function mergeRuns(el) {
// Never rewrite rendered controls or observable subtrees: app code binds to
// their ids and the run replacement would drop those elements. Only text
// nodes and plain inline wrappers are safe to merge.
if (el.closest(SKIP_SEL) || el.closest(DATA_SEL) || el.querySelector('[id],input,select,textarea,button,img,svg,iframe,[onclick],[onchange],[oninput]')) return;
const runs = [];
let run = null;
for (const child of el.childNodes) {
if (child.nodeType === 3 || (child.nodeType === 1 && inlineOnly(child))) {
if (!run) { run = []; runs.push(run); }
run.push(child);
} else {
run = null;
}
}
for (const nodes of runs) {
if (nodes.length < 2) continue;
const text = flatten(nodes);
if (!HAN.test(text)) continue;
const hit = matchRun(text);
if (!hit) continue;
let anchor = nodes[0];
if (anchor.nodeType === 1) {
anchor = document.createTextNode('');
nodes[0].replaceWith(anchor);
nodes[0] = anchor;
}
anchor.nodeValue = translate(hit);
for (const node of nodes.slice(1)) node.remove();
}
}
function walk(node) {
if (node.nodeType === 3) return translateText(node);
if (node.nodeType !== 1) return;
if (skipped(node)) { if (node.tagName === 'TEXTAREA') translateAttrs(node); return; }
translateAttrs(node);
const tw = document.createTreeWalker(node, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
acceptNode: n => {
if (n.nodeType !== 1 || !skipped(n)) return NodeFilter.FILTER_ACCEPT;
if (n.tagName === 'TEXTAREA') translateAttrs(n);
return NodeFilter.FILTER_REJECT;
},
});
let n;
while ((n = tw.nextNode())) {
if (n.nodeType === 3) translateText(n);
else translateAttrs(n);
}
mergeRuns(node);
for (const child of [...node.childNodes]) walk(child);
}
function translateTitle() {
const next = translate(document.title);
Expand Down
Loading
Loading