seewo-kit: 新增审计/改样式/删页排序/备份列表
- inspect_courseware:按页序审计文字、字号、颜色、位置、动画与点击顺序,支持全课件搜索 - set_text_style:批量改字号/加粗/颜色/对齐/框宽,只改 TextRun,保护默认属性与项目符号 - replace_text:支持 pages/allPages、matchAll、dryRun 预览 - delete_slides / move_slides:重写 Board 页序与索引映射,删页默认进回收目录 - list_backups:列出快照,供 restore_courseware 取 backupId - README 更新到 17 个工具
This commit is contained in:
+619
-56
@@ -264,6 +264,235 @@ const elementText = body => {
|
||||
return cands[0] ?? '';
|
||||
};
|
||||
|
||||
/** 把 #RGB / #RRGGBB / #AARRGGBB 统一成希沃用的 #AARRGGBB */
|
||||
function normalizeColor(value) {
|
||||
if (value == null || value === '') return null;
|
||||
let s = String(value).trim();
|
||||
if (!s.startsWith('#')) s = '#' + s;
|
||||
s = s.toUpperCase();
|
||||
if (/^#[0-9A-F]{3}$/.test(s)) s = '#' + [...s.slice(1)].map(ch => ch + ch).join('');
|
||||
if (/^#[0-9A-F]{6}$/.test(s)) return '#FF' + s.slice(1);
|
||||
if (/^#[0-9A-F]{8}$/.test(s)) return s;
|
||||
throw new Error(`颜色格式不支持:${value}(用 #RRGGBB 或 #AARRGGBB)`);
|
||||
}
|
||||
|
||||
/** 粗略估算一行文字的像素宽度:中文按 1em,英文/数字按 0.55em */
|
||||
function estimateTextWidth(text, fontSize) {
|
||||
let units = 0;
|
||||
for (const ch of String(text)) {
|
||||
const code = ch.codePointAt(0);
|
||||
if (ch === ' ') units += 0.5;
|
||||
else if (code >= 0x2E80) units += 1;
|
||||
else if (/[A-Za-z0-9]/.test(ch)) units += 0.55;
|
||||
else units += 0.6;
|
||||
}
|
||||
return units * (Number(fontSize) || 28);
|
||||
}
|
||||
|
||||
const textStyleOf = el => ({
|
||||
fontSize: el?.fontSizes?.[0] ?? null,
|
||||
bold: !!el?.bold,
|
||||
color: el?.color ?? null,
|
||||
align: el?.body?.match(/<TextAlignment>([^<]*)<\/TextAlignment>/)?.[1] ?? null,
|
||||
width: el?.w ?? null,
|
||||
});
|
||||
|
||||
/** page / pages / allPages 三种写法统一成页码数组 */
|
||||
function selectedPagesFor(cw, { page, pages, allPages = false } = {}) {
|
||||
const all = slidesInBoardOrder(cw);
|
||||
if (allPages) return all.map(s => s.page);
|
||||
if (Array.isArray(pages) && pages.length) {
|
||||
const out = [...new Set(pages.map(Number))];
|
||||
for (const n of out) {
|
||||
if (!Number.isInteger(n) || n < 1 || n > all.length) {
|
||||
throw new Error(`页码 ${n} 超出范围(1-${all.length})`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (page == null) throw new Error('需要 page,或传 pages / allPages=true');
|
||||
const n = Number(page);
|
||||
if (!Number.isInteger(n) || n < 1 || n > all.length) {
|
||||
throw new Error(`页码 ${n} 超出范围(1-${all.length})`);
|
||||
}
|
||||
return [n];
|
||||
}
|
||||
|
||||
/** 按新页序重写索引里的 Slides\Slide_N.xml 映射;被删页的记录直接丢弃 */
|
||||
function reindexSlides(cw, ordered) {
|
||||
const nonSlides = cw.json.CoursewareFiles.filter(f => !isSlidePath(f.RelativePath));
|
||||
ordered.forEach((s, i) => {
|
||||
s.rec.RelativePath = `Slides\\Slide_${i}.xml`;
|
||||
s.rec.FilePath = `${cw.localId}\\${s.rec.FileName}`;
|
||||
});
|
||||
cw.json.CoursewareFiles = [...nonSlides, ...ordered.map(s => s.rec)];
|
||||
}
|
||||
|
||||
/** 按新页序重写 Board.xml 的 <Slides> 列表 */
|
||||
function writeBoardOrder(cw, ordered) {
|
||||
const board = readBoard(cw);
|
||||
const xml = board.xml.replace(/<Slides>[\s\S]*?<\/Slides>/,
|
||||
'<Slides>\n' + ordered.map(s => ` <Item>${s.id}</Item>`).join('\n') + '\n </Slides>');
|
||||
writeFileSync(board.file, xml, 'utf8');
|
||||
saveSlideRecord(cw, board.rec, board.file);
|
||||
}
|
||||
|
||||
function inspectSlide(slide, { includeAnimations = true } = {}) {
|
||||
const { lines } = readLines(slide.file);
|
||||
const orders = parseOrders(lines);
|
||||
const orderIndex = new Map(orders.map((id, i) => [id.toLowerCase(), i + 1]));
|
||||
const elements = listElements(lines).map(el => {
|
||||
const anims = includeAnimations
|
||||
? parseAnimations(el.body).map(a => ({ ...a, order: orderIndex.get(String(a.id).toLowerCase()) ?? null }))
|
||||
: [];
|
||||
const fontSize = el.fontSizes[0] ?? null;
|
||||
const overflow = !!(fontSize && el.text && el.w > 0
|
||||
&& estimateTextWidth(el.text, fontSize) > el.w * 1.05);
|
||||
return {
|
||||
id: el.id, type: el.type, text: el.text,
|
||||
fontSize, fontSizes: el.fontSizes, bold: el.bold, color: el.color,
|
||||
x: el.x, y: el.y, w: el.w, h: el.h,
|
||||
blank: /_{3,}/.test(el.text),
|
||||
animated: el.animated,
|
||||
animations: anims,
|
||||
overflow,
|
||||
};
|
||||
});
|
||||
const textElements = elements.filter(e => e.type === 'Text' && e.text);
|
||||
return {
|
||||
page: slide.page, slideId: slide.id, file: path.basename(slide.file),
|
||||
elementCount: elements.length,
|
||||
textCount: textElements.length,
|
||||
animationCount: elements.reduce((a, e) => a + e.animations.length, 0),
|
||||
fontSizes: [...new Set(textElements.map(e => e.fontSize).filter(Boolean))].sort((a, b) => a - b),
|
||||
clickOrder: orders,
|
||||
warnings: elements.filter(e => e.overflow).map(e => `${e.id} 可能超宽:${e.text.slice(0, 40)}`),
|
||||
elements,
|
||||
};
|
||||
}
|
||||
|
||||
function renderInspectText(result) {
|
||||
const out = [];
|
||||
if (result.matches?.length) {
|
||||
out.push(`匹配「${result.query}」共 ${result.matches.length} 处:`);
|
||||
for (const m of result.matches) {
|
||||
out.push(` 第 ${m.page} 页 ${m.fontSize ?? '-'}px ${m.elementId} ${m.text.slice(0, 80)}`);
|
||||
}
|
||||
out.push('');
|
||||
}
|
||||
for (const p of result.items) {
|
||||
out.push(`第 ${p.page} 页 ${p.file} 元素 ${p.elementCount} 文本 ${p.textCount} 动画 ${p.animationCount} 字号 ${p.fontSizes.join('/') || '-'}`);
|
||||
for (const e of p.elements) {
|
||||
if (!e.text && !e.animated) continue;
|
||||
const flag = e.animated ? '[动画]' : '[ ]';
|
||||
const size = e.fontSize == null ? ' - ' : String(e.fontSize).padStart(3) + 'px';
|
||||
const body = e.text
|
||||
? ` ${e.text.replace(/\s+/g, ' ').slice(0, 90)}`
|
||||
: ` <${e.type}> x=${e.x} y=${e.y} w=${e.w} h=${e.h}`;
|
||||
out.push(` ${flag} ${size} ${body}${e.overflow ? ' ⚠可能超宽' : ''}`);
|
||||
}
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
/** 重新导出给 inspect_courseware 使用 */
|
||||
export function inspectCourseware({
|
||||
courseware, page, pages, query, includeElements, includeAnimations = true, format = 'json',
|
||||
} = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
const all = slidesInBoardOrder(cw);
|
||||
let selected;
|
||||
if (Array.isArray(pages) && pages.length) {
|
||||
const nums = [...new Set(pages.map(Number))];
|
||||
for (const n of nums) {
|
||||
if (!Number.isInteger(n) || n < 1 || n > all.length) throw new Error(`页码 ${n} 超出范围(1-${all.length})`);
|
||||
}
|
||||
selected = nums.map(n => all[n - 1]);
|
||||
} else if (page != null) {
|
||||
const n = Number(page);
|
||||
if (!Number.isInteger(n) || n < 1 || n > all.length) throw new Error(`页码 ${page} 超出范围(1-${all.length})`);
|
||||
selected = [all[n - 1]];
|
||||
} else {
|
||||
selected = all;
|
||||
}
|
||||
const showElements = includeElements ?? selected.length <= 2;
|
||||
const items = selected.map(s => {
|
||||
const item = inspectSlide(s, { includeAnimations });
|
||||
if (!showElements) {
|
||||
item.elements = item.elements.map(e => ({
|
||||
id: e.id, type: e.type, text: e.text.slice(0, 120),
|
||||
fontSize: e.fontSize, animated: e.animated, overflow: e.overflow,
|
||||
}));
|
||||
}
|
||||
return item;
|
||||
});
|
||||
const hasQuery = query != null && String(query) !== '';
|
||||
const matches = [];
|
||||
if (hasQuery) {
|
||||
const needle = String(query);
|
||||
for (const s of all) {
|
||||
const { lines } = readLines(s.file);
|
||||
for (const el of listElements(lines)) {
|
||||
if (el.text && el.text.includes(needle)) {
|
||||
matches.push({
|
||||
page: s.page, elementId: el.id, type: el.type, text: el.text,
|
||||
fontSize: el.fontSizes[0] ?? null, x: el.x, y: el.y,
|
||||
animated: el.animated,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const result = {
|
||||
courseware: cw.name, localId: cw.localId, pages: all.length,
|
||||
revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision,
|
||||
inspectedPages: selected.map(s => s.page), items,
|
||||
};
|
||||
if (hasQuery) { result.query = String(query); result.matches = matches; }
|
||||
if (format === 'text') {
|
||||
return {
|
||||
courseware: result.courseware, localId: result.localId, pages: result.pages,
|
||||
revision: result.revision, syncedRevision: result.syncedRevision,
|
||||
inspectedPages: result.inspectedPages, query: result.query,
|
||||
matchCount: matches.length, text: renderInspectText(result),
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 去掉默认文本属性 / 项目符号属性,只留真正渲染文本的 TextRun 属性 */
|
||||
function textRunsBody(body) {
|
||||
return String(body)
|
||||
.replace(/<DefaultRunProperty>[\s\S]*?<\/DefaultRunProperty>/g, '')
|
||||
.replace(/<TextMarkerStyle>[\s\S]*?<\/TextMarkerStyle>/g, '');
|
||||
}
|
||||
|
||||
/** 在元素 XML 上改样式;DefaultRunProperty / TextMarkerStyle 原样保留 */
|
||||
function applyStyleToXml(xml, opts) {
|
||||
const keep = [];
|
||||
const masked = xml.replace(/<(DefaultRunProperty|TextMarkerStyle)>[\s\S]*?<\/\1>/g, m => {
|
||||
keep.push(m);
|
||||
return `\u0000KEEP${keep.length - 1}\u0000`;
|
||||
});
|
||||
let out = masked;
|
||||
if (opts.fontSize != null) {
|
||||
out = out.replace(/<FontSize>[^<]*<\/FontSize>/g, `<FontSize>${opts.fontSize}</FontSize>`);
|
||||
}
|
||||
if (opts.bold != null) {
|
||||
out = out.replace(/<FontWeight>[^<]*<\/FontWeight>/g, `<FontWeight>${opts.bold ? 'Bold' : 'Normal'}</FontWeight>`);
|
||||
}
|
||||
if (opts.color) {
|
||||
out = out.replace(/(<Foreground>\s*<ColorBrush>)[^<]*(<\/ColorBrush>)/g, `$1${opts.color}$2`);
|
||||
}
|
||||
if (opts.align) {
|
||||
out = out.replace(/<TextAlignment>[^<]*<\/TextAlignment>/g, `<TextAlignment>${opts.align}</TextAlignment>`);
|
||||
}
|
||||
if (opts.width != null) {
|
||||
out = out.replace(/<Width>[^<]*<\/Width>/, `<Width>${opts.width}</Width>`);
|
||||
}
|
||||
return out.replace(/\u0000KEEP(\d+)\u0000/g, (m, i) => keep[Number(i)]);
|
||||
}
|
||||
|
||||
export function listElements(lines) {
|
||||
const out = [];
|
||||
lines.forEach((l, i) => {
|
||||
@@ -274,11 +503,19 @@ export function listElements(lines) {
|
||||
const body = lines.slice(i + 1, k).join('\n');
|
||||
const id = body.match(/<Id>([0-9a-fA-F]{32})<\/Id>/)?.[1];
|
||||
if (!id) return;
|
||||
const styleBody = textRunsBody(body);
|
||||
out.push({
|
||||
id, type: tag, body,
|
||||
x: Number(body.match(/<X>([^<]*)<\/X>/)?.[1]),
|
||||
y: Number(body.match(/<Y>([^<]*)<\/Y>/)?.[1]),
|
||||
w: Number(body.match(/<Width>([^<]*)<\/Width>/)?.[1]),
|
||||
h: Number(body.match(/<Height>([^<]*)<\/Height>/)?.[1]),
|
||||
fontSizes: [...new Set(
|
||||
[...styleBody.matchAll(/<FontSize>([\d.]+)<\/FontSize>/g)]
|
||||
.map(m => Number(m[1])).filter(n => Number.isFinite(n) && n > 0),
|
||||
)],
|
||||
bold: /<FontWeight>Bold<\/FontWeight>/.test(styleBody),
|
||||
color: styleBody.match(/<Foreground>\s*<ColorBrush>(#[0-9A-Fa-f]{6,8})<\/ColorBrush>/)?.[1] ?? null,
|
||||
text: elementText(body),
|
||||
animated: body.includes('<Animations>'),
|
||||
});
|
||||
@@ -576,6 +813,36 @@ function resolveBackup(backupId) {
|
||||
return { dir, manifest: readJson(mf) };
|
||||
}
|
||||
|
||||
/** 列出备份快照,可按课件过滤;restore_courseware 的 backupId 就从这里取 */
|
||||
export function listBackups({ courseware, limit = 50 } = {}) {
|
||||
const localId = courseware ? resolveCourseware(courseware).localId : null;
|
||||
let names = [];
|
||||
try { names = readdirSync(BACKUP_ROOT); } catch { names = []; }
|
||||
const items = [];
|
||||
for (const name of names) {
|
||||
if (localId && !name.startsWith(localId + '-')) continue;
|
||||
const dir = path.join(BACKUP_ROOT, name);
|
||||
const mf = backupManifestPath(dir);
|
||||
if (!existsSync(mf)) continue;
|
||||
try {
|
||||
const m = readJson(mf);
|
||||
items.push({
|
||||
backupId: name, dir,
|
||||
createdAt: m.createdAt, note: m.note,
|
||||
name: m.name, localId: m.localId, remoteId: m.remoteId,
|
||||
revision: m.revision, syncedRevision: m.syncedRevision, size: m.size,
|
||||
files: Array.isArray(m.files) ? m.files.length : null,
|
||||
pages: Array.isArray(m.files) ? m.files.filter(f => isSlidePath(f.RelativePath)).length : null,
|
||||
warnings: m.warnings ?? [],
|
||||
});
|
||||
} catch { /* 跳过坏 manifest */ }
|
||||
}
|
||||
items.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))
|
||||
|| String(b.backupId).localeCompare(String(a.backupId)));
|
||||
const n = Math.max(1, Number(limit) || 50);
|
||||
return { count: items.length, backups: items.slice(0, n) };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 关/开/同步
|
||||
function sameCourseware(shell, cw) {
|
||||
const n = String(shell.coursewareName || '').trim();
|
||||
@@ -911,77 +1178,262 @@ export async function clearAnimations({
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:改文字
|
||||
function replaceOneElement(lines, el, spec) {
|
||||
if (spec.text == null && spec.find == null) {
|
||||
return { missing: { elementId: el.id, reason: '需要 text 或 find' } };
|
||||
}
|
||||
const r = blockRange(lines, el.id);
|
||||
if (!r) return { missing: { elementId: el.id, reason: '元素块定位失败' } };
|
||||
const block = lines.slice(r.start, r.end + 1);
|
||||
const before = elementText(block.join('\n'));
|
||||
let after;
|
||||
|
||||
if (spec.text != null) {
|
||||
after = String(spec.text);
|
||||
const nonEmpty = new Set([...block.join('\n').matchAll(/<Text>([^<]*)<\/Text>/g)]
|
||||
.map(m => unesc(m[1])).filter(Boolean));
|
||||
if (nonEmpty.size > 1) {
|
||||
throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`);
|
||||
}
|
||||
const oldTag = `<Text>${esc(before)}</Text>`;
|
||||
for (let i = 0; i < block.length; i++) {
|
||||
if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`<Text>${esc(after)}</Text>`);
|
||||
}
|
||||
} else {
|
||||
const find = String(spec.find);
|
||||
const rep = String(spec.replace ?? '');
|
||||
if (!before.includes(find)) return { missing: { elementId: el.id, reason: `文本里没有「${find}」` } };
|
||||
after = before.split(find).join(rep);
|
||||
for (let i = 0; i < block.length; i++) {
|
||||
block[i] = block[i].replace(/<Text>([^<]*)<\/Text>/g, (m, t) => {
|
||||
const plain = unesc(t);
|
||||
return plain.includes(find) ? `<Text>${esc(plain.split(find).join(rep))}</Text>` : m;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (spec.width != null) collapseLines(block, after, Number(spec.width));
|
||||
else collapseLines(block, after);
|
||||
lines.splice(r.start, r.end - r.start + 1, ...block);
|
||||
return { change: { elementId: el.id, before, after, find: spec.find ?? null } };
|
||||
}
|
||||
|
||||
function applyReplacements(lines, replacements, { matchAll = false } = {}) {
|
||||
const changes = [];
|
||||
const missing = [];
|
||||
for (const spec of replacements) {
|
||||
if (spec.elementId) {
|
||||
const el = listElements(lines).find(e => e.id === spec.elementId);
|
||||
if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; }
|
||||
const r = replaceOneElement(lines, el, spec);
|
||||
if (r.change) changes.push(r.change); else missing.push(r.missing);
|
||||
continue;
|
||||
}
|
||||
if (spec.find) {
|
||||
const hits = listElements(lines).filter(e => e.type === 'Text' && e.text.includes(spec.find));
|
||||
if (!hits.length) { missing.push({ find: spec.find, reason: '没有文本含这段文字' }); continue; }
|
||||
if (hits.length > 1 && !matchAll) {
|
||||
throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId 或 matchAll=true:`
|
||||
+ hits.map(h => h.id).join(', '));
|
||||
}
|
||||
for (const el of (matchAll ? hits : [hits[0]])) {
|
||||
const r = replaceOneElement(lines, el, spec);
|
||||
if (r.change) changes.push(r.change); else missing.push(r.missing);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
missing.push({ reason: '需要 elementId 或 find' });
|
||||
}
|
||||
return { changes, missing };
|
||||
}
|
||||
|
||||
/** 多页时把「这一页没找到」的噪音去掉;真正一次都没命中的才保留 */
|
||||
function pruneMissing(missing, changes) {
|
||||
const foundIds = new Set(changes.map(c => c.elementId));
|
||||
const foundFinds = new Set(changes.map(c => c.find).filter(Boolean));
|
||||
const seen = new Set();
|
||||
return missing.filter(m => {
|
||||
if (m.elementId && foundIds.has(m.elementId)) return false;
|
||||
if (m.find && foundFinds.has(m.find)) return false;
|
||||
const key = m.elementId ? `id:${m.elementId}` : m.find ? `find:${m.find}` : `reason:${m.reason}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export async function replaceText({
|
||||
courseware, page, replacements = [],
|
||||
courseware, page, pages, allPages = false, replacements = [], matchAll = false, dryRun = false,
|
||||
reopen = true, sync = false, force = false, backup = true,
|
||||
} = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
if (!Array.isArray(replacements) || !replacements.length) throw new Error('replacements 不能为空');
|
||||
const pageNumbers = selectedPagesFor(cw, { page, pages, allPages });
|
||||
|
||||
if (dryRun) {
|
||||
const allChanges = [];
|
||||
const allMissing = [];
|
||||
const reports = [];
|
||||
for (const n of pageNumbers) {
|
||||
const { lines } = readLines(slideAt(cw, n).file);
|
||||
const { changes, missing } = applyReplacements(lines, replacements, { matchAll });
|
||||
reports.push({ page: n, changes, missing });
|
||||
allChanges.push(...changes.map(c => ({ page: n, ...c })));
|
||||
allMissing.push(...missing.map(m => ({ page: n, ...m })));
|
||||
}
|
||||
return {
|
||||
courseware: cw.name, dryRun: true,
|
||||
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
|
||||
changes: allChanges,
|
||||
missing: pruneMissing(allMissing, allChanges),
|
||||
...(pageNumbers.length === 1 ? {} : { reports }),
|
||||
};
|
||||
}
|
||||
|
||||
return runEdit(cw, { reopen, sync, force, backup }, async c => {
|
||||
const { file, rec } = slideAt(c, page);
|
||||
const { lines, eol } = readLines(file);
|
||||
const changes = [];
|
||||
const allChanges = [];
|
||||
const allMissing = [];
|
||||
const reports = [];
|
||||
for (const n of pageNumbers) {
|
||||
const { file, rec } = slideAt(c, n);
|
||||
const { lines, eol } = readLines(file);
|
||||
const { changes, missing } = applyReplacements(lines, replacements, { matchAll });
|
||||
if (changes.length) {
|
||||
writeLines(file, lines, eol);
|
||||
saveSlideRecord(c, rec, file);
|
||||
}
|
||||
reports.push({ page: n, changes, missing });
|
||||
allChanges.push(...changes.map(x => ({ page: n, ...x })));
|
||||
allMissing.push(...missing.map(x => ({ page: n, ...x })));
|
||||
}
|
||||
return {
|
||||
courseware: c.name,
|
||||
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
|
||||
changes: allChanges,
|
||||
missing: pruneMissing(allMissing, allChanges),
|
||||
...(pageNumbers.length === 1 ? {} : { reports }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:改样式
|
||||
export async function setTextStyle({
|
||||
courseware, page, pages, allPages = false,
|
||||
elementIds = [], textMatches = [], matchAll = false,
|
||||
fontSize, bold, color, align, width, dryRun = false,
|
||||
reopen = true, sync = false, force = false, backup = true,
|
||||
} = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
const pageNumbers = selectedPagesFor(cw, { page, pages, allPages });
|
||||
const opts = {
|
||||
elementIds, textMatches, matchAll,
|
||||
fontSize: fontSize == null ? null : Number(fontSize),
|
||||
bold: bold == null ? null : !!bold,
|
||||
color: color == null || color === '' ? null : normalizeColor(color),
|
||||
align: align == null || align === '' ? null : String(align),
|
||||
width: width == null ? null : Number(width),
|
||||
};
|
||||
if (opts.fontSize != null && (!Number.isFinite(opts.fontSize) || opts.fontSize <= 0)) {
|
||||
throw new Error('fontSize 必须是正数');
|
||||
}
|
||||
if (opts.width != null && (!Number.isFinite(opts.width) || opts.width <= 0)) {
|
||||
throw new Error('width 必须是正数');
|
||||
}
|
||||
if (opts.align && !['Left', 'Center', 'Right'].includes(opts.align)) {
|
||||
throw new Error('align 只能是:Left / Center / Right');
|
||||
}
|
||||
if (opts.fontSize == null && opts.bold == null && opts.color == null && opts.align == null && opts.width == null) {
|
||||
throw new Error('至少要传一个样式参数:fontSize / bold / color / align / width');
|
||||
}
|
||||
|
||||
const applyPage = lines => {
|
||||
const els = listElements(lines).filter(e => e.type === 'Text');
|
||||
const picked = [];
|
||||
const missing = [];
|
||||
|
||||
for (const spec of replacements) {
|
||||
let el = null;
|
||||
if (spec.elementId) {
|
||||
el = listElements(lines).find(e => e.id === spec.elementId);
|
||||
if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; }
|
||||
} else if (spec.find) {
|
||||
const hits = listElements(lines).filter(e => e.type === 'Text' && e.text.includes(spec.find));
|
||||
if (!hits.length) { missing.push({ find: spec.find, reason: '没有文本含这段文字' }); continue; }
|
||||
if (hits.length > 1) {
|
||||
throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId:`
|
||||
if (elementIds.length) {
|
||||
const byId = new Map(els.map(e => [e.id, e]));
|
||||
for (const id of elementIds) {
|
||||
const el = byId.get(id);
|
||||
if (el) picked.push(el); else missing.push({ elementId: id, reason: '元素不存在' });
|
||||
}
|
||||
}
|
||||
if (textMatches.length) {
|
||||
for (const needle of textMatches) {
|
||||
const hits = els.filter(e => e.text.includes(needle));
|
||||
if (!hits.length) missing.push({ text: needle, reason: '没有文本含这段文字' });
|
||||
else if (hits.length > 1 && !matchAll) {
|
||||
throw new Error(`「${needle}」匹配到 ${hits.length} 个元素,请加 elementId 或 matchAll=true:`
|
||||
+ hits.map(h => h.id).join(', '));
|
||||
}
|
||||
el = hits[0];
|
||||
} else {
|
||||
missing.push({ reason: '需要 elementId 或 find' });
|
||||
continue;
|
||||
} else picked.push(...(matchAll ? hits : [hits[0]]));
|
||||
}
|
||||
if (spec.text == null && spec.find == null) { missing.push({ elementId: el.id, reason: '需要 text 或 find' }); continue; }
|
||||
}
|
||||
if (!elementIds.length && !textMatches.length) picked.push(...els);
|
||||
|
||||
const targets = [...new Map(picked.map(e => [e.id, e])).values()];
|
||||
const changes = [];
|
||||
for (const el of targets) {
|
||||
const r = blockRange(lines, el.id);
|
||||
if (!r) { missing.push({ elementId: el.id, reason: '元素块定位失败' }); continue; }
|
||||
const block = lines.slice(r.start, r.end + 1);
|
||||
const before = elementText(block.join('\n'));
|
||||
let after;
|
||||
const before = textStyleOf(el);
|
||||
const nextBlock = applyStyleToXml(block.join('\n'), opts).split('\n');
|
||||
collapseLines(nextBlock, el.text, opts.width ?? undefined);
|
||||
lines.splice(r.start, r.end - r.start + 1, ...nextBlock);
|
||||
const updated = listElements(lines).find(e => e.id === el.id) ?? el;
|
||||
const after = textStyleOf(updated);
|
||||
const textWidth = estimateTextWidth(el.text, after.fontSize ?? before.fontSize ?? 28);
|
||||
changes.push({
|
||||
elementId: el.id, text: el.text.slice(0, 60), before, after,
|
||||
estimatedWidth: Math.round(textWidth),
|
||||
overflow: after.width != null && textWidth > after.width * 1.05,
|
||||
});
|
||||
}
|
||||
return { changes, missing };
|
||||
};
|
||||
|
||||
if (spec.text != null) {
|
||||
after = String(spec.text);
|
||||
const nonEmpty = new Set([...block.join('\n').matchAll(/<Text>([^<]*)<\/Text>/g)]
|
||||
.map(m => unesc(m[1])).filter(Boolean));
|
||||
if (nonEmpty.size > 1) {
|
||||
throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`);
|
||||
}
|
||||
const oldTag = `<Text>${esc(before)}</Text>`;
|
||||
for (let i = 0; i < block.length; i++) {
|
||||
if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`<Text>${esc(after)}</Text>`);
|
||||
}
|
||||
} else {
|
||||
const find = String(spec.find);
|
||||
const rep = String(spec.replace ?? '');
|
||||
if (!before.includes(find)) { missing.push({ elementId: el.id, reason: `文本里没有「${find}」` }); continue; }
|
||||
after = before.split(find).join(rep);
|
||||
for (let i = 0; i < block.length; i++) {
|
||||
block[i] = block[i].replace(/<Text>([^<]*)<\/Text>/g, (m, t) => {
|
||||
const plain = unesc(t);
|
||||
return plain.includes(find) ? `<Text>${esc(plain.split(find).join(rep))}</Text>` : m;
|
||||
});
|
||||
}
|
||||
if (dryRun) {
|
||||
const allChanges = [];
|
||||
const allMissing = [];
|
||||
const reports = [];
|
||||
for (const n of pageNumbers) {
|
||||
const { lines } = readLines(slideAt(cw, n).file);
|
||||
const { changes, missing } = applyPage(lines);
|
||||
reports.push({ page: n, changes, missing });
|
||||
allChanges.push(...changes.map(c => ({ page: n, ...c })));
|
||||
allMissing.push(...missing.map(m => ({ page: n, ...m })));
|
||||
}
|
||||
return {
|
||||
courseware: cw.name, dryRun: true,
|
||||
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
|
||||
changes: allChanges,
|
||||
missing: pruneMissing(allMissing, allChanges),
|
||||
...(pageNumbers.length === 1 ? {} : { reports }),
|
||||
};
|
||||
}
|
||||
|
||||
return runEdit(cw, { reopen, sync, force, backup }, async c => {
|
||||
const allChanges = [];
|
||||
const allMissing = [];
|
||||
const reports = [];
|
||||
for (const n of pageNumbers) {
|
||||
const { file, rec } = slideAt(c, n);
|
||||
const { lines, eol } = readLines(file);
|
||||
const { changes, missing } = applyPage(lines);
|
||||
if (changes.length) {
|
||||
writeLines(file, lines, eol);
|
||||
saveSlideRecord(c, rec, file);
|
||||
}
|
||||
|
||||
if (spec.width != null) collapseLines(block, after, Number(spec.width));
|
||||
else collapseLines(block, after);
|
||||
lines.splice(r.start, r.end - r.start + 1, ...block);
|
||||
changes.push({ elementId: el.id, before, after });
|
||||
reports.push({ page: n, changes, missing });
|
||||
allChanges.push(...changes.map(x => ({ page: n, ...x })));
|
||||
allMissing.push(...missing.map(x => ({ page: n, ...x })));
|
||||
}
|
||||
|
||||
if (changes.length) {
|
||||
writeLines(file, lines, eol);
|
||||
saveSlideRecord(c, rec, file);
|
||||
}
|
||||
return { courseware: c.name, page, changes, missing };
|
||||
return {
|
||||
courseware: c.name,
|
||||
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
|
||||
changes: allChanges,
|
||||
missing: pruneMissing(allMissing, allChanges),
|
||||
...(pageNumbers.length === 1 ? {} : { reports }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1376,6 +1828,117 @@ export async function copySlides({
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:删页 / 排序
|
||||
export async function deleteSlides({
|
||||
courseware, pages = [], trash = true,
|
||||
reopen = true, sync = false, force = false, backup = true,
|
||||
} = {}) {
|
||||
if (!Array.isArray(pages) || !pages.length) throw new Error('pages 不能为空');
|
||||
const cw = resolveCourseware(courseware);
|
||||
const initial = slidesInBoardOrder(cw);
|
||||
const nums = [...new Set(pages.map(Number))];
|
||||
for (const n of nums) {
|
||||
if (!Number.isInteger(n) || n < 1 || n > initial.length) {
|
||||
throw new Error(`页码 ${n} 超出范围(1-${initial.length})`);
|
||||
}
|
||||
}
|
||||
if (nums.length >= initial.length) throw new Error('不能删除全部页面,至少保留 1 页');
|
||||
|
||||
return runEdit(cw, { reopen, sync, force, backup }, async c => {
|
||||
const all = slidesInBoardOrder(c);
|
||||
const del = new Set(nums);
|
||||
const kept = all.filter(s => !del.has(s.page));
|
||||
const removed = all.filter(s => del.has(s.page));
|
||||
if (!kept.length) throw new Error('不能删除全部页面,至少保留 1 页');
|
||||
|
||||
let trashDir = null;
|
||||
if (trash) {
|
||||
trashDir = path.join(TMP, 'seewo-kit-trash', `${c.localId}-${stamp()}`);
|
||||
mkdirSync(trashDir, { recursive: true });
|
||||
}
|
||||
const deleted = [];
|
||||
for (const s of removed) {
|
||||
const name = path.basename(s.file);
|
||||
if (trash) {
|
||||
const dst = path.join(trashDir, name);
|
||||
try { renameSync(s.file, dst); } catch {
|
||||
copyFileSync(s.file, dst);
|
||||
rmSync(s.file, { force: true });
|
||||
}
|
||||
} else {
|
||||
rmSync(s.file, { force: true });
|
||||
}
|
||||
deleted.push({ page: s.page, slideId: s.id, file: name });
|
||||
}
|
||||
|
||||
reindexSlides(c, kept);
|
||||
writeBoardOrder(c, kept);
|
||||
return {
|
||||
courseware: c.name,
|
||||
deleted, remaining: kept.length, trashDir,
|
||||
pages: kept.map((s, i) => ({ page: i + 1, slideId: s.id })),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function moveSlides({
|
||||
courseware, from, to, order,
|
||||
reopen = true, sync = false, force = false, backup = true,
|
||||
} = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
const initial = slidesInBoardOrder(cw);
|
||||
if (!(Array.isArray(order) && order.length) && (from == null || to == null)) {
|
||||
throw new Error('需要 order(完整页序),或 from + to(把 from 页移到 to 位置)');
|
||||
}
|
||||
|
||||
const resolveOrder = (all, list) => {
|
||||
if (list.length !== all.length) throw new Error(`order 必须包含全部 ${all.length} 页`);
|
||||
const seen = new Set();
|
||||
return list.map(value => {
|
||||
const p = Number(value);
|
||||
if (!Number.isInteger(p) || p < 1 || p > all.length) {
|
||||
throw new Error(`order 里的页码 ${value} 超出范围(1-${all.length})`);
|
||||
}
|
||||
if (seen.has(p)) throw new Error(`order 里的页码 ${p} 重复`);
|
||||
seen.add(p);
|
||||
return all[p - 1];
|
||||
});
|
||||
};
|
||||
const resolveMove = (all, f, t) => {
|
||||
if (!Number.isInteger(f) || f < 1 || f > all.length) throw new Error(`from 页码 ${f} 超出范围(1-${all.length})`);
|
||||
if (!Number.isInteger(t) || t < 1 || t > all.length) throw new Error(`to 页码 ${t} 超出范围(1-${all.length})`);
|
||||
const next = [...all];
|
||||
const [moved] = next.splice(f - 1, 1);
|
||||
next.splice(t - 1, 0, moved);
|
||||
return next;
|
||||
};
|
||||
|
||||
const preview = Array.isArray(order) && order.length
|
||||
? resolveOrder(initial, order)
|
||||
: resolveMove(initial, Number(from), Number(to));
|
||||
const oldOrder = initial.map(s => s.page).join(',');
|
||||
const newOrder = preview.map(s => s.page).join(',');
|
||||
if (oldOrder === newOrder) {
|
||||
return { courseware: cw.name, changed: false, order: preview.map(s => s.page) };
|
||||
}
|
||||
|
||||
return runEdit(cw, { reopen, sync, force, backup }, async c => {
|
||||
const all = slidesInBoardOrder(c);
|
||||
const next = Array.isArray(order) && order.length
|
||||
? resolveOrder(all, order)
|
||||
: resolveMove(all, Number(from), Number(to));
|
||||
reindexSlides(c, next);
|
||||
writeBoardOrder(c, next);
|
||||
return {
|
||||
courseware: c.name, changed: true,
|
||||
from: from == null ? null : Number(from),
|
||||
to: to == null ? null : Number(to),
|
||||
order: next.map(s => s.page),
|
||||
pages: next.map((s, i) => ({ page: i + 1, slideId: s.id, oldPage: s.page })),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 工具:单独同步
|
||||
export async function syncCourseware({ courseware } = {}) {
|
||||
const cw = resolveCourseware(courseware);
|
||||
|
||||
Reference in New Issue
Block a user