yonge 1 month ago
parent
commit
6e63f85172

+ 1 - 1
dist/assets/index-0d8QvEtu.js → dist/assets/index-BuoWoiic.js

@@ -1 +1 @@
-import{_ as a}from"./404-R0y5dkvZ.js";import{a5 as o,eo as t,ae as r,af as c,bO as _,bP as d,ak as s,bH as p}from"./index-DsJhEHFn.js";const i=e=>(_("data-v-dda25179"),e=e(),d(),e),n={class:"errorPage"},m=i(()=>s("div",{class:"error"},[s("img",{src:a,class:"img",alt:""}),s("div",{class:"tit"},"页面找不到了~")],-1)),l=[m],f=o({__name:"errorPage",setup(e){return t(),(u,h)=>(r(),c("div",n,l))}}),I=p(f,[["__scopeId","data-v-dda25179"]]);export{I as default};
+import{_ as a}from"./404-R0y5dkvZ.js";import{a5 as o,eo as t,ae as r,af as c,bO as _,bP as d,ak as s,bH as p}from"./index-DFtuSmYr.js";const i=e=>(_("data-v-dda25179"),e=e(),d(),e),n={class:"errorPage"},m=i(()=>s("div",{class:"error"},[s("img",{src:a,class:"img",alt:""}),s("div",{class:"tit"},"页面找不到了~")],-1)),l=[m],f=o({__name:"errorPage",setup(e){return t(),(u,h)=>(r(),c("div",n,l))}}),I=p(f,[["__scopeId","data-v-dda25179"]]);export{I as default};

File diff suppressed because it is too large
+ 0 - 0
dist/assets/index-CPUAq0_P.css


+ 1 - 1
dist/assets/index-CvtVGL--.js → dist/assets/index-DC_-oGFJ.js

@@ -1 +1 @@
-import{u as c,ag as l}from"./index-CDpGg4JB.js";import{w as p,bA as d,a5 as g,cD as m,R as t,ae as r,af as u,al as f,ag as w,bH as k}from"./index-DsJhEHFn.js";import"./shapes-DnCVbkCB.js";const S=()=>{function o(a){if(window.parent===window)return;const{api:e,playState:n}=a.data||{};e==="headerTogge"?window.parent.postMessage({api:"headerTogge",playState:n},"*"):e==="changeTogge"?window.parent.postMessage({api:"changeTogge"},"*"):["clickTempo","clickViewFigner"].includes(e)&&window.parent.postMessage({api:e},"*")}p(()=>{window.addEventListener("message",o)}),d(()=>{window.removeEventListener("message",o)})},_=g({__name:"mobileScreen",setup(o){S();const a=m(),e=t(!0),n=t(!1),i=c();return a.setScreenMode("mobileScreen"),i.initPPTData().then(()=>{e.value=!1}),(v,s)=>(r(),u("div",{class:"mobileScreen",onClick:s[0]||(s[0]=b=>n.value=!1)},[e.value?w("",!0):(r(),f(l,{key:0}))]))}}),P=k(_,[["__scopeId","data-v-90b2692a"]]);export{P as default};
+import{u as c,ag as l}from"./index-DSieeq3F.js";import{w as p,bA as d,a5 as g,cD as m,R as t,ae as r,af as u,al as f,ag as w,bH as k}from"./index-DFtuSmYr.js";import"./shapes-DQLOV3Qn.js";const S=()=>{function o(a){if(window.parent===window)return;const{api:e,playState:n}=a.data||{};e==="headerTogge"?window.parent.postMessage({api:"headerTogge",playState:n},"*"):e==="changeTogge"?window.parent.postMessage({api:"changeTogge"},"*"):["clickTempo","clickViewFigner"].includes(e)&&window.parent.postMessage({api:e},"*")}p(()=>{window.addEventListener("message",o)}),d(()=>{window.removeEventListener("message",o)})},_=g({__name:"mobileScreen",setup(o){S();const a=m(),e=t(!0),n=t(!1),i=c();return a.setScreenMode("mobileScreen"),i.initPPTData().then(()=>{e.value=!1}),(v,s)=>(r(),u("div",{class:"mobileScreen",onClick:s[0]||(s[0]=b=>n.value=!1)},[e.value?w("",!0):(r(),f(l,{key:0}))]))}}),P=k(_,[["__scopeId","data-v-90b2692a"]]);export{P as default};

File diff suppressed because it is too large
+ 1 - 1
dist/assets/index-DFtuSmYr.js


+ 1 - 1
dist/assets/index-CDpGg4JB.js → dist/assets/index-DSieeq3F.js

@@ -1,4 +1,4 @@
-import{cH as pw,cI as gw,aG as mw,cJ as yw,cK as Sw,cL as bw,cM as xw,ah as Wt,cN as Cw,cO as ww,cP as Tw,cQ as Iw,aM as _w,aF as Aw,cR as Ew,aB as d1,bg as Pw,cS as Mw,cT as Rw,cU as Dw,cV as Lw,cW as kw,cX as Ow,cY as Bw,aE as Nw,cZ as Fw,s as Te,bl as $w,al as je,ag as Fe,af as he,ak as Z,c_ as zw,c$ as Uw,d0 as Hw,d1 as Vw,bk as Gw,cy as cl,aS as wv,aq as Ye,d2 as Ww,d3 as jw,a5 as ze,d4 as Kw,d5 as Xw,d6 as Yw,d7 as Zw,d8 as Qw,d9 as Jw,da as qw,db as eT,dc as tT,dd as rT,de as nT,v as iT,df as aT,dg as oT,dh as sT,aW as lT,di as uT,dj as cT,dk as fT,dl as dT,dm as hT,ay as ur,dn as vT,dp as pT,dq as gT,dr as mT,A as yT,ds as ST,dt as bT,bq as xT,du as CT,dv as wT,dw as TT,ap as IT,ac as Tv,ai as ct,dx as _T,au as xe,dy as AT,X as h1,y as ET,dz as PT,aP as MT,dA as RT,w as Er,dB as DT,dC as LT,H as kT,dD as OT,bA as hn,aD as BT,ae as ne,bP as ea,$ as Tc,dE as NT,bO as ta,dF as FT,aC as $T,aO as zT,R as fe,dG as UT,br as ih,b3 as _r,aj as Hs,b1 as lt,b2 as Ua,an as Iv,dH as HT,dI as VT,dJ as GT,dK as WT,dL as jT,dM as KT,dN as XT,Q as YT,dO as ZT,dP as QT,dQ as JT,at as Mt,dR as qT,aR as eI,aY as tI,ad as fl,aZ as rI,dS as nI,dT as iI,dU as aI,P as le,a6 as oI,dV as sI,dW as lI,dX as uI,dY as cI,a7 as fI,dZ as dI,bM as hI,d_ as vI,d$ as pI,bL as gI,b4 as v1,aA as _v,e0 as mI,e1 as yI,E as Jt,x as SI,e2 as bI,e3 as xI,e4 as CI,am as _n,e5 as wI,az as sr,aU as Vs,e6 as TI,as as pr,e7 as II,e8 as Av,cG as yr,by as ah,cw as oh,bI as _I,bH as Ve,bu as sh,bv as Ev,bx as jt,bB as Ic,bQ as di,e9 as Tu,bE as hi,ea as AI,bJ as ra,bC as EI,bw as Lt,eb as PI,ec as ui,bN as MI,ed as RI,ee as DI,ef as LI,eg as kI,eh as Jp,ei as OI,bF as qp,cD as _c,cC as BI,ej as Vu,ek as _l}from"./index-DsJhEHFn.js";/**
+import{cH as pw,cI as gw,aG as mw,cJ as yw,cK as Sw,cL as bw,cM as xw,ah as Wt,cN as Cw,cO as ww,cP as Tw,cQ as Iw,aM as _w,aF as Aw,cR as Ew,aB as d1,bg as Pw,cS as Mw,cT as Rw,cU as Dw,cV as Lw,cW as kw,cX as Ow,cY as Bw,aE as Nw,cZ as Fw,s as Te,bl as $w,al as je,ag as Fe,af as he,ak as Z,c_ as zw,c$ as Uw,d0 as Hw,d1 as Vw,bk as Gw,cy as cl,aS as wv,aq as Ye,d2 as Ww,d3 as jw,a5 as ze,d4 as Kw,d5 as Xw,d6 as Yw,d7 as Zw,d8 as Qw,d9 as Jw,da as qw,db as eT,dc as tT,dd as rT,de as nT,v as iT,df as aT,dg as oT,dh as sT,aW as lT,di as uT,dj as cT,dk as fT,dl as dT,dm as hT,ay as ur,dn as vT,dp as pT,dq as gT,dr as mT,A as yT,ds as ST,dt as bT,bq as xT,du as CT,dv as wT,dw as TT,ap as IT,ac as Tv,ai as ct,dx as _T,au as xe,dy as AT,X as h1,y as ET,dz as PT,aP as MT,dA as RT,w as Er,dB as DT,dC as LT,H as kT,dD as OT,bA as hn,aD as BT,ae as ne,bP as ea,$ as Tc,dE as NT,bO as ta,dF as FT,aC as $T,aO as zT,R as fe,dG as UT,br as ih,b3 as _r,aj as Hs,b1 as lt,b2 as Ua,an as Iv,dH as HT,dI as VT,dJ as GT,dK as WT,dL as jT,dM as KT,dN as XT,Q as YT,dO as ZT,dP as QT,dQ as JT,at as Mt,dR as qT,aR as eI,aY as tI,ad as fl,aZ as rI,dS as nI,dT as iI,dU as aI,P as le,a6 as oI,dV as sI,dW as lI,dX as uI,dY as cI,a7 as fI,dZ as dI,bM as hI,d_ as vI,d$ as pI,bL as gI,b4 as v1,aA as _v,e0 as mI,e1 as yI,E as Jt,x as SI,e2 as bI,e3 as xI,e4 as CI,am as _n,e5 as wI,az as sr,aU as Vs,e6 as TI,as as pr,e7 as II,e8 as Av,cG as yr,by as ah,cw as oh,bI as _I,bH as Ve,bu as sh,bv as Ev,bx as jt,bB as Ic,bQ as di,e9 as Tu,bE as hi,ea as AI,bJ as ra,bC as EI,bw as Lt,eb as PI,ec as ui,bN as MI,ed as RI,ee as DI,ef as LI,eg as kI,eh as Jp,ei as OI,bF as qp,cD as _c,cC as BI,ej as Vu,ek as _l}from"./index-DFtuSmYr.js";/**
 * vue v3.4.34
 * (c) 2018-present Yuxi (Evan) You and Vue contributors
 * @license MIT

File diff suppressed because it is too large
+ 0 - 0
dist/assets/index-D_52pD1d.js


+ 1 - 1
dist/assets/index-BVB_xaq6.js → dist/assets/index-tMsysvx2.js

@@ -1 +1 @@
-import{u as s,ag as r}from"./index-CDpGg4JB.js";import{a5 as c,cD as n,R as p,ae as t,af as _,al as u,ag as i,bH as l}from"./index-DsJhEHFn.js";const m={class:"pptScreen"},d=c({__name:"pptScreen",setup(f){const a=n(),e=p(!0),o=s();return a.setScreenMode("pptScreen"),o.initPPTData().then(()=>{e.value=!1}),(S,k)=>(t(),_("div",m,[e.value?i("",!0):(t(),u(r,{key:0}))]))}}),g=l(d,[["__scopeId","data-v-678905e9"]]);export{g as default};
+import{u as s,ag as r}from"./index-DSieeq3F.js";import{a5 as c,cD as n,R as p,ae as t,af as _,al as u,ag as i,bH as l}from"./index-DFtuSmYr.js";const m={class:"pptScreen"},d=c({__name:"pptScreen",setup(f){const a=n(),e=p(!0),o=s();return a.setScreenMode("pptScreen"),o.initPPTData().then(()=>{e.value=!1}),(S,k)=>(t(),_("div",m,[e.value?i("",!0):(t(),u(r,{key:0}))]))}}),g=l(d,[["__scopeId","data-v-678905e9"]]);export{g as default};

+ 1 - 1
dist/assets/index-CigFQ5bh.js → dist/assets/index-ykApa_GF.js

@@ -1 +1 @@
-import{_ as t}from"./404-R0y5dkvZ.js";import{E as c}from"./index-DOqnoaec.js";import{a5 as n,ae as i,af as r,ak as o,aq as _,am as d,P as l,aS as p,bO as m,bP as f,bH as u}from"./index-DsJhEHFn.js";const s=a=>(m("data-v-340bbdaa"),a=a(),f(),a),h={class:"login"},b={class:"error"},g=s(()=>o("img",{src:t,class:"img",alt:""},null,-1)),k=s(()=>o("div",{class:"tit"},"登录已过期或服务器错误!",-1)),v=n({__name:"login",setup(a){function e(){window.close()}return(x,B)=>(i(),r("div",h,[o("div",b,[g,k,_(l(c),{class:"backBtn",type:"primary",plain:"",onClick:e},{default:d(()=>[p("关闭页面")]),_:1})])]))}}),C=u(v,[["__scopeId","data-v-340bbdaa"]]);export{C as default};
+import{_ as t}from"./404-R0y5dkvZ.js";import{E as c}from"./index-D_52pD1d.js";import{a5 as n,ae as i,af as r,ak as o,aq as _,am as d,P as l,aS as p,bO as m,bP as f,bH as u}from"./index-DFtuSmYr.js";const s=a=>(m("data-v-340bbdaa"),a=a(),f(),a),h={class:"login"},b={class:"error"},g=s(()=>o("img",{src:t,class:"img",alt:""},null,-1)),k=s(()=>o("div",{class:"tit"},"登录已过期或服务器错误!",-1)),v=n({__name:"login",setup(a){function e(){window.close()}return(x,B)=>(i(),r("div",h,[o("div",b,[g,k,_(l(c),{class:"backBtn",type:"primary",plain:"",onClick:e},{default:d(()=>[p("关闭页面")]),_:1})])]))}}),C=u(v,[["__scopeId","data-v-340bbdaa"]]);export{C as default};

File diff suppressed because it is too large
+ 0 - 0
dist/assets/index-yoY4S8AP.js


+ 1 - 1
dist/assets/shapes-DnCVbkCB.js → dist/assets/shapes-DQLOV3Qn.js

@@ -1,4 +1,4 @@
-import{cG as k,bB as $1}from"./index-DsJhEHFn.js";import{ah as Z,ai as H1,aj as U,ak as n0,al as c0,am as i0,an as j1,ao as K1,ap as Y1,aq as R}from"./index-CDpGg4JB.js";var z1={exports:{}};/*!
+import{cG as k,bB as $1}from"./index-DFtuSmYr.js";import{ah as Z,ai as H1,aj as U,ak as n0,al as c0,am as i0,an as j1,ao as K1,ap as Y1,aq as R}from"./index-DSieeq3F.js";var z1={exports:{}};/*!
  * clipboard.js v2.0.11
  * https://clipboardjs.com/
  *

+ 1 - 1
dist/index.html

@@ -10,7 +10,7 @@
     <meta name="description" content="ppt编辑器" />
     <meta name="keywords" content="ppt,powerpoint,office powerpoint,在线ppt,幻灯片,演示文稿,ppt在线制作,Vue3,TypeScript" />
     <title>PPT</title>
-    <script type="module" crossorigin src="./assets/index-DsJhEHFn.js"></script>
+    <script type="module" crossorigin src="./assets/index-DFtuSmYr.js"></script>
     <link rel="stylesheet" crossorigin href="./assets/index-AavUEaYy.css">
   </head>
   <body>

+ 21 - 9
scripts/aiPptSelfTest.mjs

@@ -3,7 +3,7 @@ import { existsSync } from "node:fs"
 import { resolve } from "node:path"
 import assert from "node:assert/strict"
 import { classroomFixture } from "./fixtures/aiPptClassroom.mjs"
-import { semanticDesignFixture } from "./fixtures/aiPptSemanticDesign.mjs"
+import { semanticDesignFixture, densityRegressionFixture } from "./fixtures/aiPptSemanticDesign.mjs"
 import { modelDesignFixture } from "./fixtures/aiPptModelDesign.mjs"
 
 const vite = await createServer({ server: { middlewareMode: true }, appType: "custom", logLevel: "error" })
@@ -295,7 +295,7 @@ try {
   assert(classroomSlides[6].elements.some(element => element.type === "text" && element.width > 1200), "无图听唱页应使用宽版正文")
   assert(classroomSlides[9].elements.some(element => element.type === "text" && element.width > 1200), "无图检测页不得保留半页空白")
   const classroomReport = inspectAiPptQuality(classroom, classroomSlides)
-  assert(!classroomReport.errors.some(issue => ["out_of_bounds", "text_overlap", "text_overflow", "missing_content", "small_font"].includes(issue.code)), JSON.stringify(classroomReport.errors))
+  assert(!classroomReport.errors.some(issue => ["out_of_bounds", "text_overlap", "text_overflow", "rendered_text_geometry", "missing_content", "small_font"].includes(issue.code)), JSON.stringify(classroomReport.errors))
   assert.equal(classroomReport.issues.filter(issue => issue.code === "missing_required_visual").length, 6)
   assert(classroomReport.issues.filter(issue => issue.code === "missing_required_visual").every(issue => issue.message.includes("未返回图片")))
   // 配图不能迫使对比、活动、总结、目标页统一分栏,也不能在保留版式后丢图。
@@ -310,7 +310,7 @@ try {
       const sampleSlides = render(sample)
       assert.equal(resolveAiPptLayout(sample.pages[1], 1), layout)
       assert(sampleSlides[1].elements.some(element => element.type === "image"), `${template.id}/${layout} 丢失配图`)
-      assert(!inspectAiPptQuality(sample, sampleSlides).errors.some(issue => issue.pageNo === 2 && ["out_of_bounds", "text_overlap", "text_overflow", "missing_content"].includes(issue.code)))
+      assert(!inspectAiPptQuality(sample, sampleSlides).errors.some(issue => issue.pageNo === 2 && ["out_of_bounds", "text_overlap", "text_overflow", "rendered_text_geometry", "missing_content"].includes(issue.code)))
     }
   }
   const { PAGE_COMPOSITIONS, compilePageDesign } = await vite.ssrLoadModule('/src/utils/aiPptPageDesign.ts')
@@ -319,7 +319,7 @@ try {
   const modelFixture = modelDesignFixture(scoreImage)
   const modelSlides = render(modelFixture)
   const modelReport = inspectAiPptQuality(modelFixture, modelSlides)
-  assert(!modelReport.errors.some(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'missing_content', 'small_font'].includes(issue.code)), JSON.stringify(modelReport.errors))
+  assert(!modelReport.errors.some(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'rendered_text_geometry', 'missing_content', 'small_font'].includes(issue.code)), JSON.stringify(modelReport.errors))
   assert(!modelReport.issues.some(issue => ['missing_required_visual', 'generated_focal_visual', 'rendered_layout_repeat'].includes(issue.code)), JSON.stringify(modelReport.issues))
   assert(new Set(modelSlides.map(slide => JSON.stringify(geometry(slide)))).size >= 8, '模型设计应实际产生不同坐标与内容组织')
   for (const template of AI_COURSEWARE_TEMPLATES) {
@@ -335,7 +335,7 @@ try {
               requiredVisual: false, visualPlan: { composition, visualShare, textPresentation, visualMode: illustrated ? 'generated_image' : 'native_diagram', imagePurpose: illustrated ? 'observation' : 'none' }
             })
             const slides = render(sample)
-            const errors = inspectAiPptQuality(sample, slides).errors.filter(issue => issue.pageNo === 2 && ['out_of_bounds', 'text_overlap', 'text_overflow', 'missing_content', 'small_font'].includes(issue.code))
+            const errors = inspectAiPptQuality(sample, slides).errors.filter(issue => issue.pageNo === 2 && ['out_of_bounds', 'text_overlap', 'text_overflow', 'rendered_text_geometry', 'missing_content', 'small_font'].includes(issue.code))
             assert.equal(errors.length, 0, `${template.id}/${composition}/${visualShare}/${textPresentation}/${illustrated}: ${JSON.stringify(errors)}`)
             assert.equal(slides[1].elements.some(el => el.type === 'image'), illustrated)
             const text = slides[1].elements.map(elementText).join(' ')
@@ -366,12 +366,12 @@ try {
   assert(inspectAiPptQuality(modelFixture, repeatedSlides).issues.some(issue => issue.code === 'rendered_layout_repeat'), '版式名不同但坐标相同也应被检测到')
   const semantic = semanticDesignFixture(scoreImage)
   const semanticSlides = render(semantic)
-  const semanticErrors = inspectAiPptQuality(semantic, semanticSlides).errors.filter(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'missing_content', 'small_font'].includes(issue.code))
+  const semanticErrors = inspectAiPptQuality(semantic, semanticSlides).errors.filter(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'rendered_text_geometry', 'missing_content', 'small_font'].includes(issue.code))
   assert.deepEqual(semanticErrors, [], JSON.stringify(semanticErrors))
   for (const template of AI_COURSEWARE_TEMPLATES) {
     const check = structuredClone(semantic)
     check.templateId = template.id
-    const errors = inspectAiPptQuality(check, render(check)).errors.filter(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'missing_content', 'small_font'].includes(issue.code))
+    const errors = inspectAiPptQuality(check, render(check)).errors.filter(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'rendered_text_geometry', 'missing_content', 'small_font'].includes(issue.code))
     assert.deepEqual(errors, [], `${template.id}: ${JSON.stringify(errors)}`)
   }
   const illustratedGroups = structuredClone(semantic)
@@ -379,7 +379,7 @@ try {
   illustratedGroups.pages[4].visualPlan.visualMode = 'generated_image'
   illustratedGroups.pages[4].studentContent.comparisonGroups[0].points.push('用手势表现变化')
   illustratedGroups.pages[4].studentContent.comparisonGroups[1].points.push('试着模仿它的声音')
-  const illustratedErrors = inspectAiPptQuality(illustratedGroups, render(illustratedGroups)).errors.filter(issue => issue.pageNo === 5 && ['out_of_bounds', 'text_overlap', 'text_overflow', 'missing_content', 'small_font'].includes(issue.code))
+  const illustratedErrors = inspectAiPptQuality(illustratedGroups, render(illustratedGroups)).errors.filter(issue => issue.pageNo === 5 && ['out_of_bounds', 'text_overlap', 'text_overflow', 'rendered_text_geometry', 'missing_content', 'small_font'].includes(issue.code))
   assert.deepEqual(illustratedErrors, [], '图文对比必须为组名、正文和公共提示预留高度')
   const textElement = (i, text) => semanticSlides[i].elements.find(el => elementText(el).includes(text))
   assert(textElement(3, '风的声音').left < textElement(3, '老虎的声音').left, '两种对比对象必须各在一侧')
@@ -393,7 +393,19 @@ try {
   const invalidGroups = structuredClone(semantic.pages[4])
   invalidGroups.studentContent.comparisonGroups.push({ label: '第三组', points: ['第三组的完整内容'] })
   assert(modelPageContent(invalidGroups).points.includes('第三组的完整内容'), '异常分组不能丢失正文')
-  console.log(JSON.stringify({ passed: failures.length === 0, scenarioCount: results.length, contractChecks: 13, imageTemplateChecks: AI_COURSEWARE_TEMPLATES.length, modelDesignChecks, semanticDesignChecks: 10,
+  const density = densityRegressionFixture(scoreImage)
+  const densitySlides = render(density)
+  assert.deepEqual(inspectAiPptQuality(density, densitySlides).errors.filter(issue => ['out_of_bounds', 'text_overlap', 'text_overflow', 'rendered_text_geometry', 'missing_content', 'small_font'].includes(issue.code)), [])
+  assert.equal(densitySlides[8].elements.filter(el => /^[1-9]$/.test(elementText(el))).length, 3, '新语义字段不得丢失为单个引导标题')
+  const brokenDensity = structuredClone(densitySlides)
+  brokenDensity[4].elements.filter(el => el.type === 'text' && density.pages[4].studentContent.points.some(point => elementText(el).includes(point))).forEach((el, i) => { el.top = 783.915 + i * 55.6875; el.height = 41.1075 })
+  assert(inspectAiPptQuality(density, brokenDensity).errors.some(issue => issue.pageNo === 5 && issue.code === 'rendered_text_geometry'), '必须拦截之前坐标检查漏掉的真实高度溢出')
+  const { aiPptEntryChanged } = await vite.ssrLoadModule('/src/utils/aiPptClientVersion.ts')
+  const html = '<script type="module" crossorigin src="./assets/index-new.js"></script>'
+  assert(aiPptEntryChanged(html, 'https://example.com/classroom-ppt/', './assets/index-old.js'))
+  assert(!aiPptEntryChanged(html, 'https://example.com/classroom-ppt/', 'https://example.com/classroom-ppt/assets/index-new.js'))
+  assert(!aiPptEntryChanged('<html>login</html>', 'https://example.com/', './assets/index-old.js'))
+  console.log(JSON.stringify({ passed: failures.length === 0, scenarioCount: results.length, contractChecks: 13, imageTemplateChecks: AI_COURSEWARE_TEMPLATES.length, modelDesignChecks, semanticDesignChecks: 10, regressionChecks: 6,
     scenarios: courseVariants.map(item => item.id), ...(process.argv.includes("--verbose") ? { results } : {}), failures }, null, 2))
   if (failures.length) process.exitCode = 1
 } finally {

+ 27 - 3
scripts/aiPptVisualTest.html

@@ -14,7 +14,7 @@
   <body>
     <div id="app"></div>
     <script type="module">
-      import { createApp, h, ref } from "vue"
+      import { createApp, h, ref, nextTick, watch } from "vue"
       import { createPinia, setActivePinia } from "pinia"
       import ThumbnailSlide from "/src/views/components/ThumbnailSlide/index.vue"
       import { aiCoursewareToSlides } from "/src/utils/aiCoursewareToSlides.ts"
@@ -23,7 +23,7 @@
       import "/src/assets/styles/prosemirror.scss"
       import { hydrateSlideBackgroundImages } from "/src/libs/jsonTool.ts"
       import { classroomFixture } from "./fixtures/aiPptClassroom.mjs"
-      import { semanticDesignFixture } from "./fixtures/aiPptSemanticDesign.mjs"
+      import { semanticDesignFixture, densityRegressionFixture } from "./fixtures/aiPptSemanticDesign.mjs"
       import { modelDesignFixture } from "./fixtures/aiPptModelDesign.mjs"
 
       const id = new URLSearchParams(location.search).get("template") || "ethnic-flower"
@@ -45,14 +45,16 @@
       }
       const scenario = new URLSearchParams(location.search).get("scenario")
       const fixtureImage = '/ai-courseware-templates/extracted/bird-garden/background-01.jpg'
-      const fixture = scenario === 'semantic' ? semanticDesignFixture(fixtureImage) : scenario === 'model-design' ? modelDesignFixture(fixtureImage)
+      const fixture = scenario === 'density' ? densityRegressionFixture(fixtureImage) : scenario === 'semantic' ? semanticDesignFixture(fixtureImage) : scenario === 'model-design' ? modelDesignFixture(fixtureImage)
         : scenario === 'classroom' ? classroomFixture(fixtureImage) : outline
       const result = aiCoursewareToSlides(fixture, { templateId: id })
       const group = ref(0)
+      const geometryStatus = ref("正在检查实际文字边界")
       const previewWidth = Math.floor(Math.min(720, (window.innerHeight - 96) * 8 / 9))
       const app = createApp({
         render: () => h("main", [
           h("h1", `${getAiCoursewareTemplate(id).name} · 通用版式视觉回归`),
+          h("div", { id: "geometry-status" }, geometryStatus.value),
           ...[0, 1, 2].map(index => h('button', { onClick: () => { group.value = index } }, `查看第${index * 4 + 1}—${Math.min(index * 4 + 4, result.slides.length)}页`)),
           h("section", { class: "grid", style: { gridTemplateColumns: `repeat(2, ${previewWidth}px)` } }, result.slides.slice(group.value * 4, group.value * 4 + 4).map(slide => h("div", { class: "slide" }, [h(ThumbnailSlide, { slide, size: previewWidth })])))
         ])
@@ -61,6 +63,28 @@
       setActivePinia(pinia)
       app.use(pinia)
       app.mount("#app")
+      async function checkRenderedGeometry() {
+        await nextTick()
+        await document.fonts.ready
+        await new Promise(resolve => requestAnimationFrame(resolve))
+        const errors = []
+        document.querySelectorAll('.grid .slide').forEach((slide, index) => {
+          const pageNo = group.value * 4 + index + 1
+          const texts = [...slide.querySelectorAll('.base-element-text')]
+          const rects = texts.map(el => el.querySelector('.element-content').getBoundingClientRect())
+          texts.forEach((el, i) => {
+            const actual = el.querySelector('.element-content').offsetHeight
+            if (actual > parseFloat(el.style.height) + 2) errors.push(`${pageNo}:文字高度 ${actual} > ${el.style.height}`)
+            for (let j = i + 1; j < texts.length; j++) {
+              const a = rects[i], b = rects[j]
+              if (Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1 && Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 1) errors.push(`${pageNo}:文字重叠`)
+            }
+          })
+        })
+        geometryStatus.value = JSON.stringify({ pages: `${group.value * 4 + 1}-${Math.min(group.value * 4 + 4, result.slides.length)}`, errors })
+      }
+      watch(group, checkRenderedGeometry)
+      checkRenderedGeometry()
 
       if (new URLSearchParams(location.search).get("export") === "1") {
         const status = document.createElement("p")

+ 20 - 0
scripts/fixtures/aiPptSemanticDesign.mjs

@@ -23,3 +23,23 @@ export function semanticDesignFixture(imageUrl) {
   steps.bullets = ['旧正文不应再次混入步骤']
   return outline
 }
+
+// 测试环境退化用例:大图下四条正文、仅 steps 有内容的排练页。
+export function densityRegressionFixture(imageUrl) {
+  const outline = semanticDesignFixture(imageUrl)
+  outline.textbookName = '人教版(2024版)一年级上册(新)'
+  Object.assign(outline.pages[4], {
+    title: '学一学:模仿动物叫', type: 'performance_activity', bullets: [],
+    studentContent: { headline: '一起学动物叫', points: ['蛐蛐:细细的,yi-yi-yi', '蝈蝈:咯-咯-咯', '蜜蜂:嗡嗡嗡', '老虎:嗷~'] },
+    classroomAction: { studentTask: '一起学动物叫' },
+    image: { url: imageUrl, width: 1584, height: 560 }, resourceBindings: [],
+    visualPlan: { composition: 'image_top', visualMode: 'generated_image', textPresentation: 'cards', visualShare: .65 }
+  })
+  Object.assign(outline.pages[8], {
+    title: '分组排练:山谷音乐会', type: 'performance_activity', bullets: [], image: undefined, resourceBindings: [], requiredVisual: false,
+    studentContent: { headline: '排练开始', points: [], steps: ['分好角色', '轮流练习', '一起合奏'] },
+    classroomAction: { studentTask: '听老师指令,和组员一起练习' },
+    visualPlan: { composition: 'steps', visualMode: 'native_diagram', textPresentation: 'steps', imagePurpose: 'none' }
+  })
+  return outline
+}

+ 5 - 0
src/hooks/useAiCoursewarePageRepair.ts

@@ -5,6 +5,7 @@ import usePptWork from "@/store/pptWork"
 import queryParams from "@/queryParams"
 import { httpAjax } from "@/plugins/httpAjax"
 import { aiCoursewareGenerateApi, aiCoursewareTaskApi, aiCoursewareResultApi, type AiCoursewareOutline, type AiCoursewarePreferences } from "@/api/aiCourseware"
+import { assertAiPptClientCurrent } from "@/utils/aiPptClientVersion"
 import { aiCoursewareToSlides } from "@/utils/aiCoursewareToSlides"
 import { getAiPptImageAspectRatios } from "@/utils/aiPptTemplateEngine"
 import { DEFAULT_AI_COURSEWARE_TEMPLATE_ID } from "@/config/aiCoursewareTemplates"
@@ -48,6 +49,8 @@ export default function useAiCoursewarePageRepair() {
     repairingPage.value = pageNo
     error.value = ""
     try {
+      await assertAiPptClientCurrent()
+      if (!active()) return
       const response = await httpAjax(aiCoursewareGenerateApi, {
         id: materialId, fromType: queryParams.pptResourcesType || queryParams.fromType || "TEACHER",
         outline: sourceOutline, templateId, preferences: prefs, regeneratePageNo: pageNo,
@@ -73,6 +76,8 @@ export default function useAiCoursewarePageRepair() {
       // 忽略后端返回的其他页面,保留本地原始教学安排。
       const nextOutline = clone(sourceOutline)
       nextOutline.pages[pageNo - 1] = result.data.outline.pages[pageNo - 1]
+      await assertAiPptClientCurrent()
+      if (!active()) return
       const converted = aiCoursewareToSlides(nextOutline, { templateId, enableAnimations: prefs.enableAnimations })
       const target = converted.slides[pageNo - 1]
       const report = inspectAiPptQuality(nextOutline, converted.slides, { ...prefs, minPages: nextOutline.pages.length, maxPages: nextOutline.pages.length })

+ 25 - 0
src/utils/aiPptClientVersion.ts

@@ -0,0 +1,25 @@
+const ENTRY_PATTERN = /<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>/i
+
+export function aiPptEntryChanged(html: string, baseUrl: string, currentEntry: string) {
+  const next = html.match(ENTRY_PATTERN)?.[1]
+  if (!next) return false // 登录页或网关响应不能被误判为新版。
+  return new URL(next, baseUrl).href !== new URL(currentEntry, baseUrl).href
+}
+
+export async function assertAiPptClientCurrent() {
+  if (import.meta.env.DEV || typeof document === 'undefined') return
+  const currentEntry = document.querySelector<HTMLScriptElement>('script[type="module"][src]')?.src
+  if (!currentEntry) return
+  const base = new URL(import.meta.env.BASE_URL, document.baseURI)
+  base.hash = ''
+  base.search = ''
+  const controller = new AbortController()
+  const timeout = setTimeout(() => controller.abort(), 4000)
+  let changed = false
+  try {
+    const response = await fetch(base.href, { cache: 'no-store', signal: controller.signal })
+    if (response.ok) changed = aiPptEntryChanged(await response.text(), base.href, currentEntry)
+  } catch { /* 版本探测失败不影响正常生成,后端仍提供旧协议兼容。 */ }
+  finally { clearTimeout(timeout) }
+  if (changed) throw new Error('课件排版已更新,请先保存当前编辑并刷新页面,再继续使用新版排版。')
+}

+ 24 - 13
src/utils/aiPptPageDesign.ts

@@ -1,6 +1,7 @@
 import type { AiCoursewarePage } from "@/api/aiCourseware"
 import type { TemplateMaster, TemplateMasterPage, TemplateSlot } from "@/config/aiCoursewareTemplateMasters"
 import { modelPageContent } from '@/utils/aiPptContent'
+import { measureAiPptText, aiPptBlockHeight } from '@/utils/aiPptTextMetrics'
 
 export const PAGE_COMPOSITIONS = ['full_scene', 'image_left', 'image_right', 'image_top', 'comparison', 'steps', 'focus_question', 'concept_grid'] as const
 export const VISUAL_MODES = ['generated_image', 'reference_image', 'native_diagram', 'text_only'] as const
@@ -13,7 +14,7 @@ export function hasModelPageDesign(page: AiCoursewarePage) {
 export const externalVisual = (page: AiCoursewarePage) => ['generated_image', 'reference_image'].includes(page.visualPlan?.visualMode || '')
 
 // 模型提供构图、比例和阅读顺序,编译器只负责安全坐标。旧大纲继续走原母版。
-export function compilePageDesign(page: AiCoursewarePage, index: number, master: TemplateMaster, showMedia: boolean, hasVisual: boolean, hasHeadline: boolean): TemplateMasterPage {
+export function compilePageDesign(page: AiCoursewarePage, index: number, master: TemplateMaster, showMedia: boolean, hasVisual: boolean, hasHeadline: boolean, preferSide = false): TemplateMasterPage {
   const plan = page.visualPlan!
   const composition = plan.composition!
   const share = Number.isFinite(plan.visualShare) ? Math.round(Math.min(.70, Math.max(.35, plan.visualShare!)) * 20) / 20 : .55
@@ -22,29 +23,39 @@ export function compilePageDesign(page: AiCoursewarePage, index: number, master:
   const slot = (id: string, left: number, top: number, width: number, height: number, font = 34): TemplateSlot => ({
     id, kind: id as TemplateSlot['kind'], left, top, width, height, preferredFontSize: font, minimumFontSize: 28
   })
-  const slots: TemplateSlot[] = [slot('title', 80, 64, 1440, cover ? 100 : 86, cover ? 68 : 50)]
-  if (cover) slots.push(slot('meta', 80, 174, 1440, 48, 28))
+  const slots: TemplateSlot[] = [slot('title', 80, 64, 1440, Math.max(cover ? 110 : 86, measureAiPptText(page.title, 1440, cover ? 68 : 50, 1.2, true)), cover ? 68 : 50)]
+  if (cover) slots.push(slot('meta', 80, Math.max(174, slots[0].top + slots[0].height + 8), 1440, 62, 28))
   if (hasHeadline) slots.push(slot('headline', 80, cover ? 236 : 174, 1440, 82, composition === 'focus_question' ? 44 : 36))
-  const baseTop = cover ? hasHeadline ? 340 : 250 : hasHeadline ? 280 : 190
-  if (content.task) slots.push({ ...slot('instruction', 80, baseTop - 4, 1440, 62, 30), kind: 'headline' })
-  const top = baseTop + (content.task ? 76 : 0)
+  const heading = slots.find(item => item.id === 'headline')
+  if (heading) {
+    heading.top = Math.max(heading.top, ...slots.filter(item => ['title', 'meta'].includes(item.id)).map(item => item.top + item.height + 12))
+    heading.height = Math.max(heading.height, measureAiPptText(content.heading, heading.width, heading.preferredFontSize!, 1.2, true))
+  }
+  const baseTop = Math.max(cover ? hasHeadline ? 340 : 250 : hasHeadline ? 280 : 190, ...slots.map(item => item.top + item.height + 18))
+  const instructionHeight = content.task ? Math.max(62, measureAiPptText(content.task, 1440, 30)) : 0
+  if (content.task) slots.push({ ...slot('instruction', 80, baseTop - 4, 1440, instructionHeight, 30), kind: 'headline' })
+  const top = baseTop + (content.task ? instructionHeight + 14 : 0)
   const bottom = showMedia ? 730 : 830
   const height = bottom - top
   if (showMedia) slots.push(slot('media', 80, 758, 1440, 72, 30))
+  const presentation = plan.textPresentation || 'plain'
+  const bodyHeight = (width: number) => content.groups.length === 2
+    ? Math.max(...content.groups.map(group => (group.label ? 66 : 0) + aiPptBlockHeight(group.points, (width - 40) / 2, presentation)))
+      + (content.points.length ? aiPptBlockHeight(content.points, width, 'plain') + 20 : 0)
+    : aiPptBlockHeight([...content.steps, ...content.points], width, presentation)
   let body = slot('body', 80, top, 1440, height)
   if (hasVisual) {
-    if (['image_left', 'image_right', 'concept_grid', 'focus_question'].includes(composition)) {
-      const imageWidth = (1440 - 36) * share
+    if (preferSide || ['image_left', 'image_right', 'concept_grid', 'focus_question'].includes(composition)) {
+      let imageWidth = (1440 - 36) * share
+      // 文字较多时逐步让出横向空间,不把正文压成狭长小字。
+      while (imageWidth > (1440 - 36) * .35 && bodyHeight(1440 - imageWidth - 36) > height) imageWidth = Math.max((1440 - 36) * .35, imageWidth - 70)
       const bodyWidth = 1440 - imageWidth - 36
       const imageLeft = composition === 'image_right' ? 80 + bodyWidth + 36 : 80
       slots.push(slot('image', imageLeft, top, imageWidth, height))
       body = slot('body', composition === 'image_right' ? 80 : 80 + imageWidth + 36, top, bodyWidth, height)
     } else {
       // 短句必须保留可读空间,不能靠缩小字号挤到图片下面。
-      const groupHeight = content.groups.length === 2 ? Math.max(...content.groups.map(group =>
-        (group.label ? 66 : 0) + group.points.reduce((sum, text) => sum + Math.max(56, Math.ceil(text.length / 17) * 44 + 12), 0)
-          + Math.max(0, group.points.length - 1) * 16)) + (content.points.length ? 120 : 0) : 180
-      const imageHeight = Math.max(80, Math.min(height * share, height - Math.max(180, groupHeight) - 28))
+      const imageHeight = Math.max(80, Math.min(height * share, height - Math.max(180, bodyHeight(1440)) - 28))
       const imageWidth = Math.min(1440, imageHeight * 2.8)
       slots.push(slot('image', 80 + (1440 - imageWidth) / 2, top, imageWidth, imageHeight))
       body = slot('body', 80, top + imageHeight + 28, 1440, height - imageHeight - 28)
@@ -52,7 +63,7 @@ export function compilePageDesign(page: AiCoursewarePage, index: number, master:
   }
   if (composition === 'comparison' && content.groups.length === 2) {
     if (content.points.length) {
-      const sharedHeight = Math.min(100, body.height * .3)
+      const sharedHeight = Math.min(aiPptBlockHeight(content.points, body.width, 'plain'), body.height * .4)
       slots.push({ ...body, top: body.top + body.height - sharedHeight, height: sharedHeight })
       body = { ...body, height: body.height - sharedHeight - 20 }
     }

+ 5 - 0
src/utils/aiPptQuality.ts

@@ -4,6 +4,7 @@ import type { PPTElement, Slide } from "@/types/slides"
 import { audioBindings, scoreBinding, isScorePage, needsAudio, studentTexts, usableResourceUrl } from "@/utils/aiPptContent"
 import { resolveAiPptLayout } from "@/utils/aiPptTemplateEngine"
 import { resolveTemplatePageLayout } from "@/config/aiCoursewareTemplateMasters"
+import { aiPptTextGeometry } from "@/utils/aiPptTextMetrics"
 import { hasModelPageDesign, externalVisual } from "@/utils/aiPptPageDesign"
 
 type BoundedPPTElement = Exclude<PPTElement, { type: "line" }>
@@ -76,6 +77,10 @@ export function inspectAiPptQuality(outline: AiCoursewareOutline, slides: Slide[
   const issues: AiPptQualityIssue[] = []
   inspectOutline(outline, issues, preferences)
   inspectSlides(slides, issues, preferences)
+  slides.forEach((slide, index) => {
+    if (!outline.pages[index] || !hasModelPageDesign(outline.pages[index]) || isScorePage(outline.pages[index])) return
+    for (const message of aiPptTextGeometry(slide.elements)) push(issues, 'rendered_text_geometry', 'error', index + 1, message)
+  })
   inspectTeachingContract(outline, slides, issues, preferences)
   const errors = issues.filter(issue => issue.severity === "error")
   const warnings = issues.filter(issue => issue.severity === "warning")

+ 25 - 17
src/utils/aiPptTemplateEngine.ts

@@ -1,4 +1,5 @@
 import { nanoid } from "nanoid"
+import { measureAiPptText, aiPptBlockHeight, aiPptTextGeometry } from "@/utils/aiPptTextMetrics"
 import type {
   Gradient,
   PPTElement,
@@ -112,12 +113,23 @@ function buildSlide(page: AiCoursewarePage, outline: AiCoursewareOutline, palett
   const nativeVisual = isScorePage(page) || (role === "rhythm" && adapted.layout === "diagram")
   const designed = hasModelPageDesign(page) && !isScorePage(page)
   const headline = designed ? modelPageContent(page).heading : cleanText(page.interaction?.question) || activityTask(page) || studentHeadline(page)
-  const masterPage = designed
+  let masterPage = designed
     ? compilePageDesign(page, index, master, intent.showMedia, (externalVisual(page) && hasImage(page)) || Boolean(videoBinding(page)), Boolean(headline))
     : fitVisualSlots(adapted, hasImage(page) || Boolean(videoBinding(page)), nativeVisual)
-  const contentElements = designed
+  let contentElements = designed
     ? fillDesignedPage(master, masterPage, page, outline, palette, index, headline, intent)
     : fillTemplatePage(master, masterPage, page, outline, palette, role, intent)
+  if (designed && aiPptTextGeometry(scaleElementsToViewport(contentElements)).length) {
+    // 实际文字放不下时只重排一次:让图文并列,为正文让出宽度,保持分组和步骤语义。
+    const retryPage = { ...page, visualPlan: { ...page.visualPlan!, visualShare: .35 } }
+    const retryLayout = compilePageDesign(retryPage, index, master, intent.showMedia,
+      (externalVisual(page) && hasImage(page)) || Boolean(videoBinding(page)), Boolean(headline), true)
+    const retryElements = fillDesignedPage(master, retryLayout, retryPage, outline, palette, index, headline, intent)
+    if (aiPptTextGeometry(scaleElementsToViewport(retryElements)).length < aiPptTextGeometry(scaleElementsToViewport(contentElements)).length) {
+      masterPage = retryLayout
+      contentElements = retryElements
+    }
+  }
   assertContentContract(master, masterPage, contentElements)
   const elements = [
     ...renderTemplateMasterElements(masterPage.base),
@@ -166,6 +178,7 @@ function fillDesignedPage(master: TemplateMaster, layout: TemplateMasterPage, pa
     if (slot) slot = compactTextSlot(slot, values, presentation)
     if (presentation === 'steps') addStepGrid(elements, slot, values, master, palette)
     else if (presentation === 'grid') addCardGrid(elements, slot, values, master, palette)
+    else if (presentation === 'cards' && values.length === 4 && slot && slot.width >= 1000) addCardGrid(elements, slot, values, master, palette, 2)
     else addSlotList(elements, slot, values, master, palette, presentation === 'cards')
   }
   if (composition === 'comparison' && content.groups.length === 2) {
@@ -193,12 +206,7 @@ function fillDesignedPage(master: TemplateMaster, layout: TemplateMasterPage, pa
 
 function compactTextSlot(slot: TemplateSlot, values: string[], presentation: string): TemplateSlot {
   const grid = presentation === 'grid' || presentation === 'steps'
-  const columns = grid ? Math.max(1, Math.min(presentation === 'steps' ? 4 : 3, values.length, Math.floor(slot.width / 300))) : 1
-  const rows = Math.max(1, Math.ceil(values.length / columns))
-  const width = (slot.width - 22 * (columns - 1)) / columns
-  const lines = Math.max(1, ...values.map(text => Math.ceil(text.length / Math.max(4, (width - 68) / 34))))
-  const rowHeight = Math.max(grid ? 190 : 80, lines * 44 + (presentation === 'steps' ? 84 : presentation === 'plain' ? 16 : 48))
-  const height = Math.min(slot.height, rowHeight * rows + 22 * (rows - 1))
+  const height = Math.min(slot.height, aiPptBlockHeight(values, slot.width, presentation))
   return { ...slot, top: slot.top + (grid ? Math.min(100, (slot.height - height) / 2) : 0), height, preferredFontSize: Math.max(slot.preferredFontSize || 34, 38) }
 }
 
@@ -537,11 +545,11 @@ function addCardFrame(elements: PPTElement[], left: number, top: number, width:
   elements.push(shapeElement({ left, top, width: 10, height, fill: accent }))
 }
 
-function addCardGrid(elements: PPTElement[], slot: TemplateSlot | undefined, sourceItems: string[], master: TemplateMaster, palette: Palette) {
+function addCardGrid(elements: PPTElement[], slot: TemplateSlot | undefined, sourceItems: string[], master: TemplateMaster, palette: Palette, preferredColumns?: number) {
   if (!slot) return
   const items = uniqueVisibleTexts(sourceItems.map(cleanText).filter(Boolean))
   if (!items.length) return
-  const columns = items.length === 1 ? 1 : Math.max(1, Math.min(3, items.length, (slot.minimumFontSize || 0) >= 28 ? Math.floor(slot.width / 300) : 3))
+  const columns = items.length === 1 ? 1 : Math.max(1, Math.min(preferredColumns || 3, items.length, (slot.minimumFontSize || 0) >= 28 ? Math.floor(slot.width / 300) : 3))
   const rows = Math.ceil(items.length / columns)
   const gap = collectionGap(slot.height, rows, 22)
   const width = (slot.width - gap * (columns - 1)) / columns
@@ -659,9 +667,9 @@ function addStepGrid(elements: PPTElement[], slot: TemplateSlot | undefined, sou
     elements.push(
       textElement({
         left: left + textInset,
-        top: top + badgeSize * 0.15,
+        top,
         width: badgeSize,
-        height: badgeSize * 0.62,
+        height: badgeSize,
         content: String(index + 1),
         fontSize: Math.min(28, Math.max(14, badgeSize * 0.4)),
         minimumFontSize: 12,
@@ -943,10 +951,10 @@ function fitFont(content: string, width: number, height: number, preferred: numb
   if (!text) return preferred
   let size = preferred
   while (size > minimum) {
-    const charsPerLine = Math.max(1, Math.floor(width / size))
-    const lines = Math.ceil(text.length / charsPerLine)
-    if (lines * size * 1.35 <= height) break
-    size -= 2
+    const estimated = minimum >= 28 ? measureAiPptText(text, width, size)
+      : Math.ceil(text.length / Math.max(1, Math.floor(width / size))) * size * 1.35
+    if (estimated <= height) break
+    size = Math.max(minimum, size - 2)
   }
   return size
 }
@@ -965,7 +973,7 @@ function textElement(params: {
 }): PPTTextElement {
   const lineHeight = params.lineHeight || 1.25
   const minimum = Math.min(params.fontSize, params.minimumFontSize ?? (params.fontSize >= 30 ? 22 : 18))
-  const resolvedFontSize = fitFont(params.content, params.width - 20, params.height, params.fontSize, minimum)
+  const resolvedFontSize = fitFont(params.content, params.width, params.height, params.fontSize, minimum)
   return {
     id: nanoid(10),
     type: "text",

+ 75 - 0
src/utils/aiPptTextMetrics.ts

@@ -0,0 +1,75 @@
+import type { PPTElement, PPTTextElement } from '@/types/slides'
+
+// 编辑器在 1920 画布中固定使用 10px 内边距;生成器内部坐标为 1600。
+export const AI_PPT_SCALE = 1.2
+const LINE_HEIGHT = 1.25
+
+/** 与 BaseTextElement 的 width、padding、换行及 line-height 保持一致。 */
+export function measureAiPptText(text: string, width: number, fontSize: number, scale = AI_PPT_SCALE, bold = false, lineHeight = LINE_HEIGHT): number {
+  const actualWidth = width * scale
+  const actualFont = fontSize * scale
+  if (typeof document !== 'undefined' && document.body) {
+    const outer = document.createElement('div')
+    outer.setAttribute('aria-hidden', 'true')
+    Object.assign(outer.style, { position: 'fixed', left: '-20000px', top: '0', visibility: 'hidden', pointerEvents: 'none',
+      width: `${actualWidth}px`, height: 'auto', padding: '10px', margin: '0', boxSizing: 'border-box',
+      fontFamily: 'Microsoft Yahei', lineHeight: String(lineHeight), wordBreak: 'break-word', letterSpacing: '0px' })
+    const inner = document.createElement('div')
+    Object.assign(inner.style, { width: 'calc(100% - 20px)', margin: '0', padding: '0', boxSizing: 'border-box',
+      fontSize: `${actualFont}px`, fontWeight: bold ? '700' : '400', whiteSpace: 'normal' })
+    inner.textContent = text
+    outer.appendChild(inner)
+    document.body.appendChild(outer)
+    try { return Math.ceil(outer.getBoundingClientRect().height + 1) / scale }
+    finally { outer.remove() }
+  }
+  // SSR 测试使用保守估算,浏览器中始终测量实际字体和换行。
+  const units = Array.from(text).reduce((sum, char) => sum + (char.charCodeAt(0) <= 255 ? .6 : 1), 0)
+  const lines = Math.max(1, Math.ceil(units * actualFont / Math.max(1, actualWidth - 40)))
+  return Math.ceil(lines * actualFont * lineHeight + 21) / scale
+}
+
+export function aiPptTextHeight(content: string, width: number, lineHeight = LINE_HEIGHT) {
+  const size = Number(content.match(/font-size:\s*([\d.]+)px/)?.[1] || 0)
+  if (!size) return 0
+  let text: string
+  if (typeof document !== 'undefined') {
+    const template = document.createElement('template')
+    template.innerHTML = content
+    text = template.content.textContent || ''
+  } else text = content.replace(/<[^>]*>/g, '').replace(/&(?:amp|lt|gt|quot|#39);/g, '字')
+  return measureAiPptText(text, width, size, 1, /font-weight:\s*(700|bold)/.test(content), lineHeight)
+}
+
+export function aiPptBlockHeight(values: string[], width: number, presentation: string, font = 38) {
+  if (!values.length) return 0
+  const pairedCards = presentation === 'cards' && values.length === 4 && width >= 1000
+  const grid = pairedCards || presentation === 'grid' || presentation === 'steps'
+  const columns = pairedCards ? 2 : grid ? Math.max(1, Math.min(presentation === 'steps' ? 4 : 3, values.length, Math.floor(width / 300))) : 1
+  const cellWidth = (width - 22 * (columns - 1)) / columns
+  const textWidth = cellWidth - (grid ? 68 : presentation === 'cards' ? 58 : 0)
+  const textHeight = Math.max(...values.map(value => measureAiPptText(value, textWidth, presentation === 'steps' ? 40 : font, AI_PPT_SCALE, grid)))
+  const rowHeight = grid ? Math.max(pairedCards ? 130 : 190, textHeight + (presentation === 'steps' ? 112 : 68)) : Math.max(80, textHeight + 12)
+  const rows = Math.ceil(values.length / columns)
+  return rowHeight * rows + (rows - 1) * (grid ? 22 : 16)
+}
+
+/** 在最终 1920 坐标下检查真实文字边界,不能只信生成器写入的 height。 */
+export function aiPptTextGeometry(elements: PPTElement[]) {
+  const texts = elements.filter((element): element is PPTTextElement => element.type === 'text').map(element => ({ ...element,
+    height: Math.max(element.height, aiPptTextHeight(element.content, element.width, element.lineHeight)) }))
+  const issues: string[] = []
+  for (let i = 0; i < texts.length; i++) {
+    const first = texts[i]
+    if (first.top + first.height > 1081) issues.push('文字超出画布')
+    const original = elements.find(element => element.id === first.id)!
+    if ('height' in original && first.height > original.height + 2) issues.push('文字实际高度超过预留空间')
+    for (let j = i + 1; j < texts.length; j++) {
+      const second = texts[j]
+      const width = Math.min(first.left + first.width, second.left + second.width) - Math.max(first.left, second.left)
+      const height = Math.min(first.top + first.height, second.top + second.height) - Math.max(first.top, second.top)
+      if (width > 2 && height > 2) issues.push('文字实际区域相互重叠')
+    }
+  }
+  return [...new Set(issues)]
+}

+ 7 - 0
src/views/Editor/EditorHeader/AiCoursewareDialog.vue

@@ -206,6 +206,7 @@ import {
   type AiCoursewareGenerateResult
 } from "@/api/aiCourseware"
 import { AI_COURSEWARE_TEMPLATES, DEFAULT_AI_COURSEWARE_TEMPLATE_ID, getAiCoursewareTemplate } from "@/config/aiCoursewareTemplates"
+import { assertAiPptClientCurrent } from "@/utils/aiPptClientVersion"
 import { aiCoursewareToSlides } from "@/utils/aiCoursewareToSlides"
 import { getAiPptImageAspectRatios } from "@/utils/aiPptTemplateEngine"
 import { inspectAiPptQuality, type AiPptQualityIssue } from "@/utils/aiPptQuality"
@@ -405,6 +406,8 @@ async function generateOutline() {
   outlineLoading.value = true
   setupError.value = ""
   try {
+    await assertAiPptClientCurrent()
+    if (requestVersion !== version) return
     const response = await httpAjax(aiCoursewareOutlineApi, {
       id: pptWork.id,
       fromType: source(),
@@ -474,6 +477,8 @@ async function startGeneration() {
   generationError.value = ""
   transferring.value = true
   try {
+    await assertAiPptClientCurrent()
+    if (requestVersion !== version) return
     const plan = clone(confirmed.value)
     plan.templateId = templateId.value
     plan.style = getAiCoursewareTemplate(templateId.value).baseStyle
@@ -543,6 +548,8 @@ async function pollTask() {
 }
 async function enterEditor(result: AiCoursewareGenerateResult, active: () => boolean) {
   if (!result?.outline?.pages?.length) throw new Error("尚未获得课件内容,请继续查看")
+  await assertAiPptClientCurrent()
+  if (!active()) return
   const converted = aiCoursewareToSlides(result.outline, { templateId: templateId.value, enableAnimations: preferences.enableAnimations })
   const report = inspectAiPptQuality(result.outline, converted.slides, {
       ...preferences,

Some files were not shown because too many files changed in this diff