From e7b440602b362a7a4c14982681899389d8227b13 Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期二, 03 十一月 2026 14:30:35 +0800
Subject: [PATCH] feat(report-word-editor) 1.报告审核添加上下标文字格式 2.优化复核模式下设备选择框标签完整展开显示样式

---
 src/views/business/inspectionTask/components/InspectionWord.vue |   17 +++
 src/views/business/inspectionView/index.vue                     |   17 +++
 tests/superdoc-script.smoke.mjs                                 |  153 ++++++++++++++++++++++++++++++
 src/views/business/inspectionTask/inspection.vue                |   17 +++
 src/components/ReportWordEditor/index.vue                       |   59 +++++++++++
 5 files changed, 261 insertions(+), 2 deletions(-)

diff --git a/src/components/ReportWordEditor/index.vue b/src/components/ReportWordEditor/index.vue
index c84b0ef..8bcf348 100644
--- a/src/components/ReportWordEditor/index.vue
+++ b/src/components/ReportWordEditor/index.vue
@@ -6,7 +6,15 @@
         {{ label }} <input v-model.number="margins[side]" type="number" min="0" max="80" step="0.1"
                            :aria-label="`${label}椤佃竟璺濓紙姣背锛塦" :disabled="readonly || !ready || applyingMargins" />
       </label>
-      <el-button size="small" :loading="applyingMargins" :disabled="readonly || !ready" @click="applyMargins">搴旂敤椤佃竟璺�</el-button>
+      <el-button size="small" :loading="applyingMargins" :disabled="readonly || !ready || applyingScript" @click="applyMargins">搴旂敤椤佃竟璺�</el-button>
+      <div class="script-settings" role="group" aria-label="涓婁笅鏍囪缃�">
+        <span>閫変腑鏂囧瓧鍚庤缃細</span>
+        <el-button v-for="option in scriptOptions" :key="option.value" size="small"
+                   :disabled="readonly || !ready || applyingMargins || applyingScript"
+                   :aria-label="option.label" :title="option.tip"
+                   @pointerdown.prevent="rememberScriptSelection" @mousedown.prevent
+                   @click="applyScript(option.value)">{{ option.label }}</el-button>
+      </div>
     </div>
     <div ref="toolbar" class="word-toolbar" :inert="readonly || undefined"></div>
     <div class="word-canvas" :inert="readonly || undefined">
@@ -36,6 +44,12 @@
 const editor = shallowRef(null)
 const ready = ref(false)
 const applyingMargins = ref(false)
+const applyingScript = ref(false)
+const scriptOptions = [
+  { value: 'superscript', label: '涓婃爣 x虏', tip: '灏嗛�変腑鏂囧瓧璁句负涓婃爣锛屼緥濡� 10鈦宦� 涓殑 -3' },
+  { value: 'subscript', label: '涓嬫爣 x鈧�', tip: '灏嗛�変腑鏂囧瓧璁句负涓嬫爣锛屼緥濡� H鈧侽 涓殑 2' },
+  { value: 'baseline', label: '鎭㈠姝e父', tip: '鍙栨秷閫変腑鏂囧瓧鐨勪笂鏍囨垨涓嬫爣' }
+]
 const error = ref('')
 const margins = ref({ top: 25.4, bottom: 25.4, left: 25.4, right: 25.4 })
 const marginLabels = { top: '涓�', bottom: '涓�', left: '宸�', right: '鍙�' }
@@ -44,6 +58,12 @@
 let toolbarObserver
 let fontSelectionTarget = false
 let fontSelectionKnown = false
+let scriptSelection = null
+
+function rememberScriptSelection() {
+  // 鍦ㄦ寜閽鐢ㄦ垨鐒︾偣鍙樺寲涔嬪墠鍚� Worker 璇诲彇閫夊尯锛岄伩鍏嶇偣鍑诲悗閫夊尯琚竻绌恒��
+  scriptSelection = editor.value?.activeEditor.doc.selection.current().catch(() => null)
+}
 
 function rememberFontSelection(event) {
   if (!event.target?.closest?.('[data-item="btn-fontFamily"]')) return
@@ -94,6 +114,7 @@
 
 async function openDocument() {
   const current = ++generation
+  scriptSelection = null
   clearTimeout(readyTimer)
   editor.value?.destroy()
   editor.value = null
@@ -150,7 +171,7 @@
 }
 
 async function applyMargins() {
-  if (!ready.value || props.readonly || applyingMargins.value) return
+  if (!ready.value || props.readonly || applyingMargins.value || applyingScript.value) return
   applyingMargins.value = true
   try {
     const sections = editor.value.activeEditor.doc.sections
@@ -176,9 +197,41 @@
   finally { applyingMargins.value = false }
 }
 
+async function applyScript(vertAlign) {
+  if (!ready.value || props.readonly || applyingMargins.value || applyingScript.value) return
+  const current = generation
+  const superdoc = editor.value
+  const selectionPromise = scriptSelection || superdoc.activeEditor.doc.selection.current()
+  scriptSelection = null
+  applyingScript.value = true
+  try {
+    // 璇诲彇瀹為檯閫夊尯锛岄伩鍏� UI 蹇収灏氭湭鏇存柊鏃朵慨鏀瑰埌涔嬪墠閫変腑鐨勬枃瀛椼��
+    const selection = await selectionPromise
+    if (current !== generation || props.readonly) return
+    if (!selection || selection.empty || !selection.selectionTarget) {
+      ElMessage.info('璇峰厛閫変腑闇�瑕佽缃笂涓嬫爣鐨勬枃瀛楋紝渚嬪 10-3 涓殑 -3')
+      return
+    }
+    const receipt = await superdoc.activeEditor.doc.format.apply({
+      target: selection.selectionTarget,
+      // 娓呴櫎鍘熸湁鎵嬪姩鍗囬檷浣嶇疆锛岃 Word 鎸変笂涓嬫爣瑙勫垯鎺掔増銆�
+      inline: { vertAlign, position: null }
+    })
+    if (current !== generation) return
+    if (!receipt.success && receipt.failure?.code !== 'NO_OP') {
+      throw new Error(receipt.failure?.message || '璁剧疆涓婁笅鏍囧け璐�')
+    }
+    emit('change')
+    ElMessage.success('鏂囧瓧鏍煎紡宸茶缃紝鐐瑰嚮淇濆瓨鍚庣敓鏁�')
+  } catch (cause) {
+    if (current === generation) ElMessage.error(cause.message || '璁剧疆涓婁笅鏍囧け璐�')
+  } finally { applyingScript.value = false }
+}
+
 async function exportDocx() {
   if (!ready.value || error.value || !editor.value) throw new Error('Word 灏氭湭鍔犺浇瀹屾垚锛屼笉鑳戒繚瀛�')
   if (applyingMargins.value) throw new Error('椤佃竟璺濇鍦ㄥ簲鐢紝璇风◢鍊欏啀淇濆瓨')
+  if (applyingScript.value) throw new Error('涓婁笅鏍囨鍦ㄨ缃紝璇风◢鍊欏啀淇濆瓨')
   const blob = await editor.value.export({ exportType: ['docx'], triggerDownload: false })
   if (!(blob instanceof Blob) || !blob.size) throw new Error('Word 瀵煎嚭澶辫触')
   return blob
@@ -213,6 +266,8 @@
 .page-settings { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 8px; background: #fff; }
 .page-settings label { display: flex; align-items: center; gap: 4px; }
 .page-settings input { width: 70px; padding: 5px; border: 1px solid #dcdfe6; border-radius: 4px; }
+.script-settings { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+.script-settings :deep(.el-button + .el-button) { margin-left: 0; }
 .word-toolbar { flex-shrink: 0; }
 .word-canvas { flex: 1; min-height: 0; overflow: auto; background: #f3f4f6; }
 /* SuperDoc 婊氬姩鏃朵細鎶婃枃妗e鍣ㄧ缉鍒扮焊寮犲搴︼紝瀵艰嚧鏁撮〉閲嶆柊璐村埌宸﹁竟銆� */
diff --git a/src/views/business/inspectionTask/components/InspectionWord.vue b/src/views/business/inspectionTask/components/InspectionWord.vue
index 9c05062..8028cd0 100644
--- a/src/views/business/inspectionTask/components/InspectionWord.vue
+++ b/src/views/business/inspectionTask/components/InspectionWord.vue
@@ -1810,6 +1810,23 @@
   flex: 0 0 360px;
 }
 
+/* 澶嶆牳鏃堕�夋嫨妗嗙鐢紝鐩存帴灞曞紑瀹屾暣璁惧鍚嶇О鍜岀紪鍙枫�� */
+.template-panel:deep(.device-select .el-tag) {
+  height: auto;
+  min-height: 24px;
+  padding-top: 2px;
+  padding-bottom: 2px;
+  max-width: 100%;
+}
+
+.template-panel:deep(.device-select .el-select__tags-text) {
+  white-space: normal;
+  overflow-wrap: anywhere;
+  overflow: visible;
+  text-overflow: clip;
+  line-height: 1.5;
+}
+
 .template-panel__unit {
   margin-left: 4px;
   color: var(--lims-text-2);
diff --git a/src/views/business/inspectionTask/inspection.vue b/src/views/business/inspectionTask/inspection.vue
index 0a6299a..edbdefe 100644
--- a/src/views/business/inspectionTask/inspection.vue
+++ b/src/views/business/inspectionTask/inspection.vue
@@ -2335,6 +2335,23 @@
   flex: 0 0 360px;
 }
 
+/* 澶嶆牳鏃堕�夋嫨妗嗙鐢紝鐩存帴灞曞紑瀹屾暣璁惧鍚嶇О鍜岀紪鍙枫�� */
+.template-panel:deep(.device-select .el-tag) {
+  height: auto;
+  min-height: 24px;
+  padding-top: 2px;
+  padding-bottom: 2px;
+  max-width: 100%;
+}
+
+.template-panel:deep(.device-select .el-select__tags-text) {
+  white-space: normal;
+  overflow-wrap: anywhere;
+  overflow: visible;
+  text-overflow: clip;
+  line-height: 1.5;
+}
+
 .template-panel__unit {
   margin-left: 4px;
   color: var(--lims-text-2);
diff --git a/src/views/business/inspectionView/index.vue b/src/views/business/inspectionView/index.vue
index 7396b58..342e7e1 100644
--- a/src/views/business/inspectionView/index.vue
+++ b/src/views/business/inspectionView/index.vue
@@ -2552,6 +2552,23 @@
   flex: 0 0 360px;
 }
 
+/* 澶嶆牳鏃堕�夋嫨妗嗙鐢紝鐩存帴灞曞紑瀹屾暣璁惧鍚嶇О鍜岀紪鍙枫�� */
+.template-panel:deep(.device-select .el-tag) {
+  height: auto;
+  min-height: 24px;
+  padding-top: 2px;
+  padding-bottom: 2px;
+  max-width: 100%;
+}
+
+.template-panel:deep(.device-select .el-select__tags-text) {
+  white-space: normal;
+  overflow-wrap: anywhere;
+  overflow: visible;
+  text-overflow: clip;
+  line-height: 1.5;
+}
+
 .template-panel__unit {
   margin-left: 4px;
   color: var(--lims-text-2);
diff --git a/tests/superdoc-script.smoke.mjs b/tests/superdoc-script.smoke.mjs
new file mode 100644
index 0000000..e4eb135
--- /dev/null
+++ b/tests/superdoc-script.smoke.mjs
@@ -0,0 +1,153 @@
+// node tests/superdoc-script.smoke.mjs (requires Playwright and Chrome)
+import assert from 'node:assert/strict'
+import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { createServer } from 'node:http'
+import { fileURLToPath } from 'node:url'
+import { createServer as createViteServer } from 'vite'
+import vue from '@vitejs/plugin-vue'
+import JSZip from 'jszip'
+import superdocHttpWorker from '../vite/plugins/superdoc-http-worker.js'
+
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+const project = fileURLToPath(new URL('../', import.meta.url))
+const temporary = await mkdtemp(path.join(tmpdir(), 'lims-superdoc-script-'))
+const fixture = path.join(project, 'tests/.superdoc-script-smoke.html')
+let browser, server, vite
+try {
+  await writeFile(fixture, `<!doctype html><html><body><div id="app"></div><script type="module">
+    import { createApp, ref, h } from 'vue';
+    import ElementPlus from 'element-plus';
+    import 'element-plus/dist/index.css';
+    import ReportWordEditor from '../src/components/ReportWordEditor/index.vue';
+    window.documentState = ref(null);
+    window.readonlyState = ref(false);
+    window.changes = 0;
+    const component = ref();
+    window.openDocument = async (blob) => {
+      window.result = null;
+      documentState.value = { blob, title: 'script-test.docx' };
+    };
+    window.exportDocument = async () => Array.from(new Uint8Array(await (await component.value.exportDocx()).arrayBuffer()));
+    createApp({ setup: () => () => documentState.value && h(ReportWordEditor, {
+      ref: component, document: documentState.value, readonly: readonlyState.value,
+      onReady: () => window.result = 'ready', onError: error => window.result = error,
+      onChange: () => window.changes++
+    }) }).use(ElementPlus).mount('#app');
+    fetch('/fixture.docx').then(response => response.blob()).then(openDocument);
+  </script></body></html>`)
+  vite = await createViteServer({ configFile: false, root: project, logLevel: 'warn',
+    cacheDir: path.join(temporary, 'cache'), server: { middlewareMode: true }, appType: 'custom',
+    optimizeDeps: { entries: [fixture] },
+    resolve: { alias: { '@': path.join(project, 'src') } },
+    plugins: [vue(), superdocHttpWorker(), {
+      name: 'capture-test-editor', enforce: 'pre',
+      resolveId(id, importer) {
+        if (importer === '\0test-editor-loader') return
+        if (id === '@/utils/loadSuperDoc' || id.replaceAll('\\', '/').replace(/\.js$/, '') === path.join(project, 'src/utils/loadSuperDoc').replaceAll('\\', '/')) {
+          return '\0test-editor-loader'
+        }
+      },
+      load(id) {
+        if (id !== '\0test-editor-loader') return
+        return `import { loadSuperDoc as load } from ${JSON.stringify(path.join(project, 'src/utils/loadSuperDoc.js').replaceAll('\\', '/'))};
+          export async function loadSuperDoc() {
+            const module = await load();
+            return { SuperDoc: class extends module.SuperDoc {
+              constructor(options) { super(options); window.superdoc = this; }
+            } };
+          }`
+      }
+    }] })
+  const zip = new JSZip()
+  zip.file('[Content_Types].xml', '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')
+  zip.file('_rels/.rels', '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')
+  // Real report values live inside table cells; include existing bold to check preservation.
+  zip.file('word/document.xml', '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl><w:tblPr><w:tblW w:w="9000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="9000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="9000" w:type="dxa"/></w:tcPr><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>10-3 H2O</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/><w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>')
+  const docx = await zip.generateAsync({ type: 'nodebuffer' })
+  server = createServer(async (req, res) => {
+    try {
+      const url = new URL(req.url, 'http://localhost')
+      if (url.pathname === '/fixture.docx') { res.end(docx); return }
+      if (url.pathname === '/') {
+        res.setHeader('Content-Type', 'text/html')
+        res.end(await vite.transformIndexHtml('/tests/.superdoc-script-smoke.html', await readFile(fixture, 'utf8')))
+        return
+      }
+      vite.middlewares(req, res, () => res.writeHead(404).end())
+    } catch { res.writeHead(404).end() }
+  })
+  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
+  browser = await chromium.launch({ executablePath: process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true })
+  const page = await browser.newPage({ viewport: { width: 1500, height: 1000 } })
+  const errors = []
+  page.on('pageerror', error => errors.push(error.message))
+  await page.goto(`http://127.0.0.1:${server.address().port}/`)
+  async function ready() {
+    await page.waitForFunction(() => window.result, null, { timeout: 120000 })
+    assert.equal(await page.evaluate(() => window.result), 'ready')
+  }
+  await ready()
+  async function select(start, end) {
+    await page.locator('.superdoc-page').first().click({ position: { x: 120, y: 110 } })
+    await page.keyboard.press('Control+Home')
+    for (let i = 0; i < start; i++) await page.keyboard.press('ArrowRight')
+    for (let i = start; i < end; i++) await page.keyboard.press('Shift+ArrowRight')
+    if (start !== end) await page.waitForFunction(async () => !(await superdoc.activeEditor.doc.selection.current()).empty)
+  }
+  async function xml() {
+    const bytes = await page.evaluate(() => exportDocument())
+    return (await JSZip.loadAsync(Buffer.from(bytes))).file('word/document.xml').async('string')
+  }
+  function runs(xml) {
+    return [...xml.matchAll(/<w:r\b[^>]*>([\s\S]*?)<\/w:r>/g)].map(match => ({
+      text: [...match[1].matchAll(/<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g)].map(m => m[1]).join(''),
+      align: match[1].match(/<w:vertAlign\b[^>]*w:val="([^"]+)"/)?.[1],
+      bold: /<w:b(?:\s|\/|>)/.test(match[1])
+    }))
+  }
+  async function apply(label) {
+    const before = await page.evaluate(() => changes)
+    await page.getByRole('button', { name: label, exact: true }).click()
+    await page.locator('.el-message').last().waitFor()
+    const message = await page.locator('.el-message').last().textContent()
+    try { await page.waitForFunction(before => changes > before, before, { timeout: 5000 }) }
+    catch (error) { throw new Error(`${error.message}: ${message}`) }
+  }
+  await select(2, 4)
+  await apply('涓婃爣 x虏')
+  let formatted = runs(await xml())
+  assert.ok(formatted.some(run => run.text === '-3' && run.align === 'superscript' && run.bold))
+  assert.ok(formatted.filter(run => run.text && run.text !== '-3').every(run => run.align !== 'superscript'))
+  await select(6, 7)
+  await apply('涓嬫爣 x鈧�')
+  formatted = runs(await xml())
+  assert.ok(formatted.some(run => run.text === '2' && run.align === 'subscript'))
+  const saved = await page.evaluate(() => exportDocument())
+  await page.evaluate(bytes => openDocument(new Blob([new Uint8Array(bytes)])), saved)
+  await ready()
+  formatted = runs(await xml())
+  assert.ok(formatted.some(run => run.text === '-3' && run.align === 'superscript'))
+  assert.ok(formatted.some(run => run.text === '2' && run.align === 'subscript'))
+  await select(2, 4)
+  await apply('鎭㈠姝e父')
+  assert.ok(runs(await xml()).filter(run => run.text.includes('-3')).every(run => !run.align || run.align === 'baseline'))
+  await select(0, 0)
+  const before = await xml()
+  await page.getByRole('button', { name: '涓婃爣 x虏', exact: true }).click()
+  await page.getByText('璇峰厛閫変腑闇�瑕佽缃笂涓嬫爣鐨勬枃瀛楋紝渚嬪 10-3 涓殑 -3', { exact: true }).waitFor()
+  assert.equal(await xml(), before)
+  await page.evaluate(() => readonlyState.value = true)
+  assert.equal(await page.getByRole('button', { name: '涓婃爣 x虏', exact: true }).isDisabled(), true)
+  assert.deepEqual(errors, [])
+  console.log(JSON.stringify({ result: 'PASS', superscript: true, subscript: true, preservedBold: true,
+    restoredBaseline: true, reopened: true, emptySelectionUnchanged: true, readonlyDisabled: true, browserErrors: errors }, null, 2))
+} finally {
+  await browser?.close()
+  await vite?.close()
+  if (server) await new Promise(resolve => server.close(resolve))
+  await rm(fixture, { force: true })
+  assert.ok(path.resolve(temporary).startsWith(path.resolve(tmpdir()) + path.sep + 'lims-superdoc-script-'))
+  await rm(temporary, { recursive: true, force: true })
+}

--
Gitblit v1.9.3