aiPptTemplateEngine.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. import { nanoid } from "nanoid"
  2. import { measureAiPptText, aiPptBlockHeight, aiPptTextGeometry } from "@/utils/aiPptTextMetrics"
  3. import type {
  4. Gradient,
  5. PPTElement,
  6. PPTElementShadow,
  7. PPTImageElement,
  8. PPTVideoElement,
  9. PPTAudioElement,
  10. PPTCloudCoachElement,
  11. PPTLineElement,
  12. PPTAnimation,
  13. PPTShapeElement,
  14. PPTTextElement,
  15. Slide,
  16. SlideBackground,
  17. SlideTheme
  18. } from "@/types/slides"
  19. import type { AiCoursewareOutline, AiCoursewarePage } from "@/api/aiCourseware"
  20. import { audioBindings, scoreBinding, isScorePage, usableResourceUrl, isTeacherFacingText, teacherFacingTexts, modelPageContent, rhythmRows } from "@/utils/aiPptContent"
  21. import { compilePageDesign, hasModelPageDesign, externalVisual } from "@/utils/aiPptPageDesign"
  22. import {
  23. AI_COURSEWARE_TEMPLATES,
  24. getAiCoursewarePalette,
  25. getAiCoursewareTemplate,
  26. DEFAULT_AI_COURSEWARE_TEMPLATE_ID,
  27. type AiCoursewareTemplateId,
  28. type AiCoursewareThemePalette
  29. } from "@/config/aiCoursewareTemplates"
  30. import {
  31. getAiCoursewareTemplateMaster,
  32. getTemplateMasterPage,
  33. selectTemplateMasterPageVariant,
  34. resolveTemplatePageLayout,
  35. validateTemplateMasterRegistry,
  36. type TemplateMaster,
  37. type TemplateMasterElement,
  38. type TemplateMasterPage,
  39. type TemplatePageRole,
  40. type TemplateSlot
  41. } from "@/config/aiCoursewareTemplateMasters"
  42. interface AiPptOptions {
  43. backgroundImage?: string
  44. enableAnimations?: boolean
  45. paletteVariant?: number
  46. templateId?: AiCoursewareTemplateId
  47. }
  48. type PageRole = TemplatePageRole
  49. type Palette = AiCoursewareThemePalette
  50. interface ImageRect {
  51. left: number
  52. top: number
  53. width: number
  54. height: number
  55. radius?: number
  56. }
  57. interface PageRenderIntent {
  58. role: PageRole
  59. density: "low" | "medium" | "high"
  60. visualKind: "image" | "notation" | "rhythm" | "compare" | "activity" | "text"
  61. showMedia: boolean
  62. }
  63. const SLIDE_WIDTH = 1600
  64. const SLIDE_HEIGHT = 900
  65. const VIEWPORT_WIDTH = 1920
  66. const VIEWPORT_HEIGHT = 1080
  67. const VIEWPORT_SCALE = VIEWPORT_WIDTH / SLIDE_WIDTH
  68. const FONT_NAME = "Microsoft Yahei"
  69. const GENERIC_PAGE_TITLES = new Set(["封面", "课程导入", "故事导入", "导入", "首页", "cover"])
  70. export function buildAiPptSlides(
  71. outline: AiCoursewareOutline,
  72. options: AiPptOptions = {}
  73. ): { title: string; theme: Partial<SlideTheme>; slides: Slide[] } {
  74. const normalized = normalizeOutline(outline)
  75. validateTemplateMasterRegistry(AI_COURSEWARE_TEMPLATES.map(template => template.id))
  76. const requestedTemplateId = options.templateId || normalized.templateId
  77. const templateId = requestedTemplateId
  78. ? getAiCoursewareTemplate(requestedTemplateId).id
  79. : DEFAULT_AI_COURSEWARE_TEMPLATE_ID
  80. const palette = buildPalette(normalized, options.paletteVariant || 0, templateId)
  81. const resolvedOptions = { ...options, templateId }
  82. const layoutOccurrences = new Map<string, number>()
  83. const slides = normalized.pages.map((page, index) => buildSlide(page, normalized, palette, resolvedOptions, index, layoutOccurrences))
  84. runPreflight(slides)
  85. return {
  86. title: normalized.title || normalized.chapterName || "音乐课件",
  87. theme: {
  88. themeColor: palette.primary,
  89. backgroundColor: palette.background,
  90. fontColor: palette.text,
  91. fontName: FONT_NAME,
  92. fontSize: "36px"
  93. },
  94. slides
  95. }
  96. }
  97. function buildSlide(page: AiCoursewarePage, outline: AiCoursewareOutline, palette: Palette, options: AiPptOptions, index: number, layoutOccurrences: Map<string, number>): Slide {
  98. const role = pageRole(page, index)
  99. const intent = pageRenderIntent(page, role)
  100. const master = getAiCoursewareTemplateMaster(options.templateId!)
  101. const baseMasterPage = getTemplateMasterPage(master, role, resolveAiPptLayout(page, index))
  102. const occurrence = layoutOccurrences.get(baseMasterPage.id) || 0
  103. layoutOccurrences.set(baseMasterPage.id, occurrence + 1)
  104. const adapted = adaptMasterPage(selectTemplateMasterPageVariant(baseMasterPage, occurrence), intent)
  105. const nativeVisual = isScorePage(page) || (role === "rhythm" && adapted.layout === "diagram")
  106. const designed = hasModelPageDesign(page) && !isScorePage(page)
  107. const headline = designed ? modelPageContent(page).heading : cleanText(page.interaction?.question) || activityTask(page) || studentHeadline(page)
  108. let masterPage = designed
  109. ? compilePageDesign(page, index, master, intent.showMedia, (externalVisual(page) && hasImage(page)) || Boolean(videoBinding(page)), Boolean(headline))
  110. : fitVisualSlots(adapted, hasImage(page) || Boolean(videoBinding(page)), nativeVisual)
  111. let contentElements = designed
  112. ? fillDesignedPage(master, masterPage, page, outline, palette, index, headline, intent)
  113. : fillTemplatePage(master, masterPage, page, outline, palette, role, intent)
  114. if (designed && aiPptTextGeometry(scaleElementsToViewport(contentElements)).length) {
  115. // 实际文字放不下时只重排一次:让图文并列,为正文让出宽度,保持分组和步骤语义。
  116. const retryPage = { ...page, visualPlan: { ...page.visualPlan!, visualShare: .35 } }
  117. const retryLayout = compilePageDesign(retryPage, index, master, intent.showMedia,
  118. (externalVisual(page) && hasImage(page)) || Boolean(videoBinding(page)), Boolean(headline), true)
  119. const retryElements = fillDesignedPage(master, retryLayout, retryPage, outline, palette, index, headline, intent)
  120. if (aiPptTextGeometry(scaleElementsToViewport(retryElements)).length < aiPptTextGeometry(scaleElementsToViewport(contentElements)).length) {
  121. masterPage = retryLayout
  122. contentElements = retryElements
  123. }
  124. }
  125. assertContentContract(master, masterPage, contentElements)
  126. const elements = [
  127. ...renderTemplateMasterElements(masterPage.base),
  128. ...contentElements,
  129. ...renderTemplateMasterElements(masterPage.chrome)
  130. ]
  131. return {
  132. id: nanoid(10),
  133. elements: scaleElementsToViewport(keepInCanvas(elements)),
  134. background: backgroundConfig(masterPage, options),
  135. remark: slideRemark(page),
  136. animations: options.enableAnimations ? entranceAnimations(contentElements) : undefined,
  137. turningMode: options.enableAnimations ? "fade" : "no"
  138. }
  139. }
  140. /** 传给图片生成器的真实模板槽位比例;媒体行存在时使用独立尺寸。 */
  141. export function getAiPptImageAspectRatios(templateId: AiCoursewareTemplateId): Record<string, number> {
  142. const master = getAiCoursewareTemplateMaster(templateId)
  143. const layouts: Record<string, string> = { cover: "cover_scene", hero: "hero_focus", media: "media_focus", split: "split_content", text: "text_focus", diagram: "diagram_focus", compare: "compare", activity: "activity", summary: "summary", objectives: "objectives" }
  144. const ratios: Record<string, number> = {}
  145. for (const page of master.pages) {
  146. for (const showMedia of [true, false]) {
  147. const adapted = fitVisualSlots(adaptMasterPage(page, { role: page.roles[0], density: "medium", visualKind: "image", showMedia }), true, false)
  148. const slot = adapted.slots.find(slot => slot.kind === "image" && slot.enabled !== false)
  149. if (slot) ratios[layouts[page.layout] + (showMedia ? ":media" : "")] = slot.width / slot.height
  150. }
  151. }
  152. ratios.model_design_v1 = 1 // 服务端依据本版编译器的安全区域和模型比例计算图片尺寸。
  153. ratios.model_design_v2 = 1
  154. return ratios
  155. }
  156. function fillDesignedPage(master: TemplateMaster, layout: TemplateMasterPage, page: AiCoursewarePage, outline: AiCoursewareOutline, palette: Palette, index: number, headline: string, intent: PageRenderIntent): PPTElement[] {
  157. const elements: PPTElement[] = []
  158. const content = modelPageContent(page)
  159. const points = content.points
  160. addSlotText(elements, slotOf(layout, 'title'), page.title, master.titleColor, true)
  161. if (index === 0) addSlotText(elements, slotOf(layout, 'meta'), [outline.gradeName, conciseTextbook(outline.textbookName), outline.unitName].filter(Boolean).join(' · '), master.mutedColor)
  162. addSlotText(elements, slotOf(layout, 'headline'), headline, master.textColor, true)
  163. addSlotText(elements, layout.slots.find(slot => slot.id === 'instruction'), content.task, master.mutedColor)
  164. addVisualOrResource(elements, slotOf(layout, 'image'), page, master, palette)
  165. const composition = page.visualPlan!.composition
  166. const presentation = page.visualPlan!.textPresentation || 'plain'
  167. const paintText = (slot: TemplateSlot | undefined, values: string[]) => {
  168. if (slot) slot = compactTextSlot(slot, values, presentation)
  169. if (presentation === 'steps') addStepGrid(elements, slot, values, master, palette)
  170. else if (presentation === 'grid') addCardGrid(elements, slot, values, master, palette)
  171. else if (presentation === 'cards' && values.length === 4 && slot && slot.width >= 1000) addCardGrid(elements, slot, values, master, palette, 2)
  172. else addSlotList(elements, slot, values, master, palette, presentation === 'cards')
  173. }
  174. if (composition === 'comparison' && content.groups.length === 2) {
  175. content.groups.forEach((group, i) => {
  176. const slot = slotOf(layout, i === 0 ? 'left' : 'right')!
  177. if (group.label) addSlotText(elements, { ...slot, height: 52 }, group.label, master.titleColor, true)
  178. paintText(group.label ? { ...slot, top: slot.top + 66, height: slot.height - 66 } : slot, group.points)
  179. })
  180. paintText(slotOf(layout, 'body'), points)
  181. } else {
  182. const body = slotOf(layout, 'body')!
  183. const rows = page.visualPlan?.visualMode === 'native_diagram' ? rhythmRows(points) : []
  184. const pattern = page.visualPlan?.visualMode === 'native_diagram' && pageRole(page, index) === 'rhythm'
  185. ? [headline, ...points].join(' ').match(/[短长](?:\s*[-—·、]\s*[短长]){1,7}/)?.[0].match(/[短长]/g) : undefined
  186. if (!content.steps.length && rows.length && rows.length === points.length && body.height >= rows.length * 160) {
  187. addRhythmRows(elements, body, rows, master, palette)
  188. } else if (pattern && !content.steps.length) {
  189. addDurationDiagram(elements, { ...body, height: body.height * .55 }, pattern, master, palette)
  190. paintText({ ...body, top: body.top + body.height * .60, height: body.height * .40 }, points)
  191. } else paintText(body, [...content.steps, ...points])
  192. }
  193. addInlineMedia(elements, slotOf(layout, 'media'), page, master, palette, intent.showMedia)
  194. return elements
  195. }
  196. function compactTextSlot(slot: TemplateSlot, values: string[], presentation: string): TemplateSlot {
  197. const grid = presentation === 'grid' || presentation === 'steps'
  198. const height = Math.min(slot.height, aiPptBlockHeight(values, slot.width, presentation))
  199. return { ...slot, top: slot.top + (grid ? Math.min(100, (slot.height - height) / 2) : 0), height, preferredFontSize: Math.max(slot.preferredFontSize || 34, 38) }
  200. }
  201. function addRhythmRows(elements: PPTElement[], slot: TemplateSlot, rows: ReturnType<typeof rhythmRows>, master: TemplateMaster, palette: Palette) {
  202. const rowHeight = Math.min(220, (slot.height - 24 * (rows.length - 1)) / rows.length)
  203. rows.forEach((row, i) => {
  204. const top = slot.top + i * (rowHeight + 24)
  205. addSlotText(elements, { ...slot, top, height: 58, preferredFontSize: 38 }, row.source, master.textColor, true)
  206. const width = Math.min(160, (slot.width - 12 * (row.tokens.length - 1)) / row.tokens.length)
  207. row.tokens.forEach((token, j) => {
  208. const cell = { left: slot.left + j * (width + 12), top: top + 76, width, height: Math.max(48, rowHeight - 82) }
  209. if (!/[||]/.test(token)) elements.push(shapeElement({ ...cell, fill: palette.soft, radius: 10 }))
  210. addSlotText(elements, { ...slot, ...cell, preferredFontSize: 44 }, token, master.textColor, true)
  211. })
  212. })
  213. }
  214. function fillTemplatePage(master: TemplateMaster, masterPage: TemplateMasterPage, page: AiCoursewarePage, outline: AiCoursewareOutline, palette: Palette, role: PageRole = masterPage.roles[0], intent = pageRenderIntent(page, role)): PPTElement[] {
  215. master = {
  216. ...master,
  217. titleColor: masterPage.titleColor || master.titleColor,
  218. coverTitleColor: masterPage.coverTitleColor || master.coverTitleColor,
  219. textColor: masterPage.textColor || master.textColor,
  220. mutedColor: masterPage.mutedColor || master.mutedColor
  221. }
  222. const elements: PPTElement[] = []
  223. const title = masterPage.layout === "cover" ? chapterTitle(outline, page) : displayPageTitle(page, outline)
  224. // 学生可见内容必须与编辑区保持一致,不能因模板容量静默丢弃条目。
  225. const headline = cleanText(page.interaction?.question) || activityTask(page) || studentHeadline(page)
  226. const points = uniqueVisibleTexts([activityTask(page), ...studentPoints(page), ...(page.interaction?.options || [])])
  227. .filter(point => !sameVisibleText(point, headline))
  228. addSlotText(elements, slotOf(masterPage, "title"), title, masterPage.layout === "cover" ? master.coverTitleColor : master.titleColor, true)
  229. if (role !== "cover" && isScorePage(page)) {
  230. addNotationVisual(elements, slotOf(masterPage, "image"), page, master, palette)
  231. addSlotList(elements, slotOf(masterPage, "body"), uniqueVisibleTexts([headline, ...points, page.interaction?.question || "", ...(page.interaction?.options || [])]), master, palette, false)
  232. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  233. return elements
  234. }
  235. if (masterPage.layout === "cover") {
  236. const meta = [outline.gradeName, conciseTextbook(outline.textbookName), outline.unitName].filter(Boolean).join(" · ")
  237. const coverSecondaryColor = master.coverTitleColor.toUpperCase() === "#FFFFFF" ? "#DDE6F4" : master.mutedColor
  238. addSlotText(elements, slotOf(masterPage, "meta"), meta, coverSecondaryColor)
  239. addSlotList(elements, slotOf(masterPage, "headline"), uniqueVisibleTexts([headline, ...points]), master, palette, false, master.coverTitleColor)
  240. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette, !masterPage.backgroundVisual)
  241. return elements
  242. }
  243. if (masterPage.layout === "hero") {
  244. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette, !masterPage.backgroundVisual)
  245. const body = uniqueVisibleTexts([page.interaction?.question || "", headline, ...points])
  246. addSlotList(elements, slotOf(masterPage, "body"), body, master, palette)
  247. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  248. return elements
  249. }
  250. if (masterPage.layout === "objectives") {
  251. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette)
  252. addCardGrid(elements, slotOf(masterPage, "body"), uniqueVisibleTexts([headline, ...points]), master, palette)
  253. return elements
  254. }
  255. if (masterPage.layout === "media") {
  256. addSlotText(elements, slotOf(masterPage, "headline"), headline || page.interaction?.question || "带着问题听音乐", palette.primary, true)
  257. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette, !masterPage.backgroundVisual)
  258. addSlotList(elements, slotOf(masterPage, "body"), points, master, palette)
  259. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  260. return elements
  261. }
  262. if (masterPage.layout === "split") {
  263. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette, !masterPage.backgroundVisual)
  264. addSlotList(elements, slotOf(masterPage, "body"), uniqueVisibleTexts([headline, ...points]), master, palette)
  265. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  266. return elements
  267. }
  268. if (masterPage.layout === "text") {
  269. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette)
  270. addSlotText(elements, slotOf(masterPage, "headline"), headline || (role === "lyric" ? "读一读,再唱一唱" : "抓住这一页的关键信息"), page.interaction?.question ? master.textColor : palette.primary, true)
  271. if (role === "lyric") addLyricLines(elements, slotOf(masterPage, "body"), points, master, palette)
  272. else addSlotList(elements, slotOf(masterPage, "body"), points, master, palette, false)
  273. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  274. return elements
  275. }
  276. if (masterPage.layout === "diagram") {
  277. const rhythmPattern = role === "rhythm" ? [headline, ...points].join(" ").match(/[短长](?:\s*[-—·、]\s*[短长]){1,7}/)?.[0].match(/[短长]/g) : undefined
  278. if (role === "notation") addNotationVisual(elements, slotOf(masterPage, "image"), page, master, palette, false)
  279. else if (rhythmPattern) addDurationDiagram(elements, slotOf(masterPage, "image"), rhythmPattern, master, palette)
  280. else if (role === "rhythm") addStepGrid(elements, slotOf(masterPage, "image"), points, master, palette)
  281. else addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette, true)
  282. if (role !== "rhythm" || rhythmPattern) addSlotList(elements, slotOf(masterPage, "body"), uniqueVisibleTexts([headline, ...points]), master, palette)
  283. else addSlotText(elements, slotOf(masterPage, "body"), headline, master.textColor)
  284. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  285. return elements
  286. }
  287. if (masterPage.layout === "compare") {
  288. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette)
  289. const values = uniqueVisibleTexts([...(page.interaction?.options || []), ...points])
  290. const midpoint = Math.max(1, Math.ceil(values.length / 2))
  291. addSlotText(elements, slotOf(masterPage, "headline"), headline || page.interaction?.question || "听一听,它们有什么不同?", palette.primary, true)
  292. addSlotList(elements, slotOf(masterPage, "left"), values.slice(0, midpoint), master, palette)
  293. addSlotList(elements, slotOf(masterPage, "right"), values.slice(midpoint), master, palette)
  294. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  295. return elements
  296. }
  297. if (masterPage.layout === "activity") {
  298. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette)
  299. addSlotText(elements, slotOf(masterPage, "headline"), headline || "一起完成音乐任务", palette.primary, true)
  300. addStepGrid(elements, slotOf(masterPage, "steps"), points, master, palette)
  301. addInlineMedia(elements, slotOf(masterPage, "media"), page, master, palette, intent.showMedia)
  302. return elements
  303. }
  304. addVisualOrResource(elements, slotOf(masterPage, "image"), page, master, palette)
  305. addChecklist(elements, slotOf(masterPage, "body"), points, master, palette)
  306. addSlotText(elements, slotOf(masterPage, "headline"), headline, palette.primary, true)
  307. return elements
  308. }
  309. function slotOf(page: TemplateMasterPage, id: string) {
  310. return page.slots.find(item => item.id === id && item.enabled !== false)
  311. }
  312. function pageRenderIntent(page: AiCoursewarePage, role: PageRole): PageRenderIntent {
  313. const densityValue = String(page.visualPlan?.visualDensity || "").toLowerCase()
  314. const pointCount = Math.max(page.studentContent?.points?.length || 0, page.bullets?.length || 0, page.activity?.steps?.length || 0)
  315. const density: PageRenderIntent["density"] = densityValue === "low" || densityValue === "high"
  316. ? densityValue
  317. : pointCount <= 2 ? "low" : pointCount >= 5 ? "high" : "medium"
  318. const hasBoundMedia = (page.resourceBindings || []).some(binding =>
  319. binding.verified !== false && ["SONG", "VIDEO"].includes(binding.resourceType) && Boolean(binding.contentUrl)
  320. )
  321. const expectsMedia = role === "listen" || (page.resourceBindings || []).some(binding =>
  322. ["SONG", "VIDEO"].includes(binding.resourceType) && binding.required === true
  323. )
  324. const visualKind: PageRenderIntent["visualKind"] = role === "notation"
  325. ? "notation"
  326. : role === "rhythm"
  327. ? "rhythm"
  328. : role === "compare"
  329. ? "compare"
  330. : ["activity", "performance"].includes(role)
  331. ? "activity"
  332. : ["goal", "summary", "homework", "practice", "lyric"].includes(role)
  333. ? "text"
  334. : "image"
  335. return { role, density, visualKind, showMedia: hasBoundMedia || expectsMedia }
  336. }
  337. export function resolveAiPptLayout(page: AiCoursewarePage, index: number): string {
  338. const role = pageRole(page, index)
  339. if (role === "cover") return "cover_scene"
  340. if (isScorePage(page)) return "diagram_focus"
  341. if (role === "practice") return "text_focus"
  342. const requested = resolveTemplatePageLayout(page.visualPlan?.layout || page.visual?.layout)
  343. // 历史大纲可能已被服务端统一改为 split,优先恢复教学页型;配图由槽位适配处理。
  344. if (role === "rhythm") return hasImage(page) ? "activity" : "diagram_focus"
  345. if (requested && requested !== "split" && requested !== "cover") return requested
  346. const layouts: Partial<Record<PageRole, string>> = {
  347. intro: "hero_focus", story: "hero_focus", goal: "objectives", knowledge: "objectives",
  348. listen: "media_focus", compare: "compare", activity: "activity", performance: "activity",
  349. summary: "summary", homework: "activity", practice: "text_focus", interaction: "text_focus", lyric: "text_focus"
  350. }
  351. return layouts[role] || "split_content"
  352. }
  353. function fitVisualSlots(page: TemplateMasterPage, hasVisual: boolean, nativeVisual: boolean): TemplateMasterPage {
  354. if (nativeVisual) return page
  355. const image = slotOf(page, "image")
  356. const body = slotOf(page, "body")
  357. if (!hasVisual) {
  358. if (!image || !body) return page
  359. // 只合并并排区域,不能跨过标题或侵入模板保留区域。
  360. if (Math.abs(image.top - body.top) > 40) return page
  361. const left = Math.min(image.left, body.left)
  362. const right = Math.max(image.left + image.width, body.left + body.width)
  363. return { ...page, slots: page.slots.filter(s => s.kind !== "image").map(s => s.id === body.id ? { ...s, left, width: right - left } : s) }
  364. }
  365. if (image) return page
  366. // 在既有安全内容区内给教学图片分配位置,保留对比、步骤、总结的语义结构。
  367. const content = page.slots.filter(s => s.enabled !== false && ["body", "steps", "left", "right"].includes(s.kind))
  368. if (!content.length) return page // 自带封面主视觉的母版保持原有背景契约。
  369. const left = Math.min(...content.map(s => s.left)), top = Math.min(...content.map(s => s.top))
  370. const width = Math.max(...content.map(s => s.left + s.width)) - left
  371. const height = Math.max(...content.map(s => s.top + s.height)) - top
  372. // 对比图片置于两栏上方,左右内容保持同等面积,避免暗示一侧更重要。
  373. if (content.length > 1) {
  374. const imageHeight = Math.min(...content.map(s => s.height)) * 0.42
  375. const imageWidth = Math.min(width, imageHeight * 2)
  376. return { ...page, slots: [...page.slots.map(s => content.some(c => c.id === s.id)
  377. ? { ...s, top: s.top + imageHeight + 20, height: s.height - imageHeight - 20 } : s),
  378. { id: "image", kind: "image", left: left + (width - imageWidth) / 2, top, width: imageWidth, height: imageHeight }] }
  379. }
  380. const imageWidth = width * 0.4
  381. return { ...page, slots: [...page.slots.map(s => s.id === content[0].id ? { ...s, left: left + imageWidth + 28, width: width - imageWidth - 28 } : s),
  382. { id: "image", kind: "image", left, top, width: imageWidth, height }] }
  383. }
  384. function adaptMasterPage(page: TemplateMasterPage, intent: PageRenderIntent): TemplateMasterPage {
  385. if (intent.showMedia) return page
  386. const media = page.slots.find(slot => slot.kind === "media" && slot.enabled !== false)
  387. if (!media) return page
  388. const availableBottom = media.top + media.height
  389. const expandable = new Set(["body", "image", "steps", "left", "right"])
  390. return {
  391. ...page,
  392. slots: page.slots
  393. .filter(slot => slot.kind !== "media")
  394. .map(slot => {
  395. if (!expandable.has(slot.kind) || slot.top + slot.height > media.top + 24) return { ...slot }
  396. return { ...slot, height: Math.max(slot.height, availableBottom - slot.top) }
  397. })
  398. }
  399. }
  400. function assertContentContract(master: TemplateMaster, page: TemplateMasterPage, elements: PPTElement[]) {
  401. if (!page.safeArea || !page.reservedZones) return
  402. type ElementBounds = { left: number; top: number; width: number; height: number }
  403. const boundedElements = elements.filter((element): element is PPTElement & ElementBounds =>
  404. "height" in element && typeof element.height === "number"
  405. )
  406. const overlaps = (left: ElementBounds, right: ElementBounds) =>
  407. left.left < right.left + right.width && left.left + left.width > right.left && left.top < right.top + right.height && left.top + left.height > right.top
  408. const outsideSafeArea = boundedElements.find(element =>
  409. element.left < page.safeArea!.left ||
  410. element.top < page.safeArea!.top ||
  411. element.left + element.width > page.safeArea!.left + page.safeArea!.width ||
  412. element.top + element.height > page.safeArea!.top + page.safeArea!.height
  413. )
  414. if (outsideSafeArea) throw new Error(`模板 ${master.id}/${page.id} 生成内容超出投屏安全区,请调整该页面内容槽。`)
  415. const collision = page.reservedZones.find(zone => boundedElements.some(element => overlaps(element, zone)))
  416. if (collision) throw new Error(`模板 ${master.id}/${page.id} 生成内容侵入“${collision.purpose}”保留区,请更换版式或缩减内容。`)
  417. }
  418. function addSlotText(elements: PPTElement[], slot: TemplateSlot | undefined, content: string, color: string, bold = false) {
  419. if (!slot || !cleanText(content)) return
  420. elements.push(textElement({
  421. left: slot.left,
  422. top: slot.top,
  423. width: slot.width,
  424. height: slot.height,
  425. content,
  426. fontSize: fitFont(content, slot.width, slot.height, slot.preferredFontSize || 30, slot.minimumFontSize || 22),
  427. minimumFontSize: slot.minimumFontSize,
  428. color,
  429. bold
  430. }))
  431. }
  432. function addSlotList(
  433. elements: PPTElement[],
  434. slot: TemplateSlot | undefined,
  435. sourceItems: string[],
  436. master: TemplateMaster,
  437. palette: Palette,
  438. cards = true,
  439. textColor = master.textColor
  440. ) {
  441. if (!slot) return
  442. const items = uniqueVisibleTexts(sourceItems.map(cleanText).filter(Boolean))
  443. if (!items.length) return
  444. const gap = collectionGap(slot.height, items.length, 16)
  445. const rowHeight = (slot.height - gap * (items.length - 1)) / items.length
  446. items.forEach((item, index) => {
  447. const top = slot.top + index * (rowHeight + gap)
  448. const inset = cards ? Math.min(34, Math.max(12, rowHeight * 0.22)) : 0
  449. const textTopInset = Math.min(6, Math.max(1, rowHeight * 0.08))
  450. const textHeight = Math.max(12, rowHeight - textTopInset * 2)
  451. const textWidth = Math.max(40, slot.width - (cards ? inset + 24 : 0))
  452. const minimumFontSize = adaptiveMinimumFont(slot, textHeight)
  453. if (cards) {
  454. addCardFrame(elements, slot.left, top, slot.width, rowHeight, index, master, palette)
  455. }
  456. elements.push(
  457. textElement({
  458. left: slot.left + inset,
  459. top: top + textTopInset,
  460. width: textWidth,
  461. height: textHeight,
  462. content: item,
  463. fontSize: fitFont(item, textWidth, textHeight, slot.preferredFontSize || 30, minimumFontSize),
  464. minimumFontSize,
  465. color: textColor,
  466. bold: index === 0 && items.length === 1
  467. })
  468. )
  469. })
  470. }
  471. function collectionGap(height: number, count: number, preferred: number) {
  472. if (count <= 1) return 0
  473. return Math.max(1, Math.min(preferred, height / Math.max(8, count * 8)))
  474. }
  475. function adaptiveMinimumFont(slot: TemplateSlot, availableHeight: number) {
  476. // 内容过多时交给质量门禁提示拆页,不能靠无限缩小正文隐藏问题。
  477. return Math.max(24, slot.minimumFontSize || 24)
  478. }
  479. function addCardFrame(elements: PPTElement[], left: number, top: number, width: number, height: number, index: number, master: TemplateMaster, palette: Palette) {
  480. const accent = index % 2 ? palette.secondary : palette.primary
  481. if (master.cardStyle === "ink") {
  482. elements.push(shapeElement({ left, top: top + height - 3, width, height: 3, fill: master.borderColor, opacity: 0.52 }))
  483. elements.push(shapeElement({ left, top: top + 12, width: 14, height: 14, fill: accent, radius: 7 }))
  484. return
  485. }
  486. if (master.cardStyle === "sticker") {
  487. const fills = [palette.warm, palette.soft, master.surfaceColor]
  488. elements.push(shapeElement({ left, top, width, height, fill: fills[index % fills.length], radius: 22, shadow: lightShadow() }))
  489. elements.push(shapeElement({ left: left + 12, top: top + 12, width: 38, height: 38, fill: accent, radius: 19 }))
  490. return
  491. }
  492. if (master.cardStyle === "bubble") {
  493. elements.push(shapeElement({ left, top, width, height, fill: index % 2 ? palette.soft : master.surfaceColor, radius: Math.min(28, height / 2), shadow: lightShadow() }))
  494. elements.push(shapeElement({ left: left + 14, top: top + height / 2 - 8, width: 16, height: 16, fill: accent, radius: 8 }))
  495. return
  496. }
  497. if (master.cardStyle === "grid") {
  498. elements.push(shapeElement({ left, top, width, height, fill: master.surfaceColor, radius: 4 }))
  499. elements.push(shapeElement({ left, top, width: 14, height: 14, fill: accent, radius: 0 }))
  500. elements.push(shapeElement({ left: left + width - 26, top: top + height - 10, width: 26, height: 10, fill: accent, opacity: 0.5 }))
  501. return
  502. }
  503. if (master.cardStyle === "cinematic") {
  504. elements.push(shapeElement({ left, top, width, height, fill: master.surfaceColor, radius: 6, shadow: lightShadow() }))
  505. elements.push(shapeElement({ left, top, width: 8, height, fill: accent }))
  506. return
  507. }
  508. elements.push(shapeElement({ left, top, width, height, fill: master.surfaceColor, radius: 14, shadow: lightShadow() }))
  509. elements.push(shapeElement({ left, top, width: 10, height, fill: accent }))
  510. }
  511. function addCardGrid(elements: PPTElement[], slot: TemplateSlot | undefined, sourceItems: string[], master: TemplateMaster, palette: Palette, preferredColumns?: number) {
  512. if (!slot) return
  513. const items = uniqueVisibleTexts(sourceItems.map(cleanText).filter(Boolean))
  514. if (!items.length) return
  515. 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))
  516. const rows = Math.ceil(items.length / columns)
  517. const gap = collectionGap(slot.height, rows, 22)
  518. const width = (slot.width - gap * (columns - 1)) / columns
  519. const height = (slot.height - gap * (rows - 1)) / rows
  520. items.forEach((item, index) => {
  521. const left = slot.left + (index % columns) * (width + gap)
  522. const top = slot.top + Math.floor(index / columns) * (height + gap)
  523. const inset = Math.min(34, Math.max(10, Math.min(width, height) * 0.1))
  524. const textWidth = Math.max(36, width - inset * 2)
  525. const textHeight = Math.max(12, height - inset * 2)
  526. const minimumFontSize = adaptiveMinimumFont(slot, textHeight)
  527. addCardFrame(elements, left, top, width, height, index, master, palette)
  528. elements.push(
  529. textElement({
  530. left: left + inset,
  531. top: top + inset,
  532. width: textWidth,
  533. height: textHeight,
  534. content: item,
  535. fontSize: fitFont(item, textWidth, textHeight, slot.preferredFontSize || 32, minimumFontSize),
  536. minimumFontSize,
  537. color: master.textColor,
  538. bold: true
  539. })
  540. )
  541. })
  542. }
  543. function addLyricLines(elements: PPTElement[], slot: TemplateSlot | undefined, sourceItems: string[], master: TemplateMaster, palette: Palette) {
  544. if (!slot) return
  545. const items = uniqueVisibleTexts(sourceItems.map(cleanText).filter(Boolean))
  546. const gap = collectionGap(slot.height, items.length, 12)
  547. const height = (slot.height - gap * Math.max(0, items.length - 1)) / Math.max(1, items.length)
  548. items.forEach((item, index) => {
  549. const top = slot.top + index * (height + gap)
  550. const inset = Math.min(8, Math.max(1, height * 0.08))
  551. const textHeight = Math.max(12, height - inset * 2)
  552. const minimumFontSize = adaptiveMinimumFont(slot, textHeight)
  553. if (index % 2 === 0)
  554. elements.push(shapeElement({ left: slot.left, top, width: slot.width, height, fill: palette.soft, opacity: 0.55, radius: 18 }))
  555. elements.push(
  556. textElement({
  557. left: slot.left + 45,
  558. top: top + inset,
  559. width: slot.width - 90,
  560. height: textHeight,
  561. content: `♪ ${item}`,
  562. fontSize: fitFont(item, slot.width - 90, textHeight, slot.preferredFontSize || 38, minimumFontSize),
  563. minimumFontSize,
  564. color: master.textColor,
  565. bold: index === 0
  566. })
  567. )
  568. })
  569. }
  570. function addNotationVisual(elements: PPTElement[], slot: TemplateSlot | undefined, page: AiCoursewarePage, master: TemplateMaster, palette: Palette, backgroundVisual = false) {
  571. if (!slot) return
  572. const binding = scoreBinding(page)
  573. if (!binding) return // 缺谱在教师质量面板中提示,绝不绘制虚构谱例。
  574. if (usableResourceUrl(binding.scoreImageUrl)) {
  575. // 保持整张曲谱,不使用 cover 裁切,防止丢失谱号、小节或歌词。
  576. elements.push({ id: nanoid(10), type: "image", src: binding.scoreImageUrl!, left: slot.left, top: slot.top,
  577. width: slot.width, height: slot.height, fixedRatio: true, rotate: 0 } as PPTImageElement)
  578. } else {
  579. elements.push({ id: nanoid(10), type: "elf", subtype: "elf-sing-play", sid: binding.resourceId,
  580. title: binding.name || page.title, left: slot.left, top: slot.top, width: slot.width, height: slot.height, rotate: 0 } as PPTCloudCoachElement)
  581. }
  582. }
  583. function addDurationDiagram(elements: PPTElement[], slot: TemplateSlot | undefined, pattern: string[], master: TemplateMaster, palette: Palette) {
  584. if (!slot) return
  585. // 只可视化正文明确给出的长短顺序,不猜拍号、音符时值或教材谱例。
  586. const gap = 24, unit = (slot.width - gap * (pattern.length - 1)) / pattern.reduce((sum, item) => sum + (item === "长" ? 2 : 1), 0)
  587. let left = slot.left
  588. const barHeight = Math.min(80, slot.height * 0.22), top = slot.top + slot.height * 0.36
  589. pattern.forEach(item => {
  590. const width = unit * (item === "长" ? 2 : 1)
  591. elements.push(shapeElement({ left, top, width, height: barHeight, fill: item === "长" ? palette.secondary : palette.primary, radius: 12 }))
  592. addSlotText(elements, { id: "duration-label", kind: "body", left, top: top + barHeight + 22, width, height: 70, preferredFontSize: 40, minimumFontSize: 24 }, item, master.textColor, true)
  593. left += width + gap
  594. })
  595. }
  596. function addStepGrid(elements: PPTElement[], slot: TemplateSlot | undefined, sourceItems: string[], master: TemplateMaster, palette: Palette) {
  597. if (!slot) return
  598. const items = uniqueVisibleTexts(sourceItems.map(cleanText).filter(Boolean))
  599. if (!items.length) return
  600. const columns = Math.max(1, Math.min(4, items.length, (slot.minimumFontSize || 0) >= 28 ? Math.floor(slot.width / 300) : 4))
  601. const rows = Math.ceil(items.length / columns)
  602. const gap = collectionGap(slot.height, rows, 22)
  603. const width = (slot.width - gap * (columns - 1)) / columns
  604. const height = (slot.height - gap * (rows - 1)) / rows
  605. items.forEach((item, index) => {
  606. const left = slot.left + (index % columns) * (width + gap)
  607. const top = slot.top + Math.floor(index / columns) * (height + gap)
  608. const badgeSize = Math.min(72, Math.max((slot.minimumFontSize || 0) >= 28 ? 52 : 24, height * 0.2))
  609. const cardTop = top + badgeSize * 0.55
  610. const cardHeight = Math.max(12, height - badgeSize * 0.55)
  611. const textInset = Math.min(30, Math.max(8, width * 0.08))
  612. const textTop = cardTop + Math.min(70, Math.max(18, cardHeight * 0.22))
  613. const textHeight = Math.max(12, top + height - textTop - 8)
  614. const minimumFontSize = adaptiveMinimumFont(slot, textHeight)
  615. addCardFrame(elements, left, cardTop, width, cardHeight, index, master, palette)
  616. elements.push(
  617. shapeElement({
  618. left: left + textInset,
  619. top,
  620. width: badgeSize,
  621. height: badgeSize,
  622. fill: index % 2 ? palette.secondary : palette.primary,
  623. radius: badgeSize / 2
  624. })
  625. )
  626. elements.push(
  627. textElement({
  628. left: left + textInset,
  629. top,
  630. width: badgeSize,
  631. height: badgeSize,
  632. content: String(index + 1),
  633. fontSize: Math.min(28, Math.max(14, badgeSize * 0.4)),
  634. minimumFontSize: 12,
  635. color: "#FFFFFF",
  636. bold: true
  637. })
  638. )
  639. elements.push(
  640. textElement({
  641. left: left + textInset,
  642. top: textTop,
  643. width: Math.max(36, width - textInset * 2),
  644. height: textHeight,
  645. content: item,
  646. fontSize: fitFont(item, width - textInset * 2, textHeight, (slot.minimumFontSize || 0) >= 28 ? 40 : 29, minimumFontSize),
  647. minimumFontSize,
  648. color: master.textColor,
  649. bold: true
  650. })
  651. )
  652. })
  653. }
  654. function addChecklist(elements: PPTElement[], slot: TemplateSlot | undefined, sourceItems: string[], master: TemplateMaster, palette: Palette) {
  655. if (!slot) return
  656. const items = uniqueVisibleTexts(sourceItems.map(cleanText).filter(Boolean))
  657. const gap = collectionGap(slot.height, items.length, 16)
  658. const height = (slot.height - gap * Math.max(0, items.length - 1)) / Math.max(1, items.length)
  659. items.forEach((item, index) => {
  660. const top = slot.top + index * (height + gap)
  661. const iconSize = Math.min(42, Math.max(16, height * 0.58))
  662. const iconTop = top + Math.max(0, (height - iconSize) / 2)
  663. const textLeft = slot.left + iconSize + Math.min(30, Math.max(8, iconSize * 0.7))
  664. const textWidth = Math.max(40, slot.left + slot.width - textLeft)
  665. const minimumFontSize = adaptiveMinimumFont(slot, height)
  666. elements.push(
  667. shapeElement({
  668. left: slot.left,
  669. top: iconTop,
  670. width: iconSize,
  671. height: iconSize,
  672. fill: index % 2 ? palette.secondary : palette.primary,
  673. radius: iconSize / 2
  674. })
  675. )
  676. elements.push(
  677. textElement({
  678. left: slot.left + iconSize * 0.2,
  679. top: iconTop + iconSize * 0.12,
  680. width: iconSize * 0.6,
  681. height: iconSize * 0.7,
  682. content: "✓",
  683. fontSize: Math.min(24, Math.max(10, iconSize * 0.55)),
  684. minimumFontSize: 10,
  685. color: "#FFFFFF",
  686. bold: true
  687. })
  688. )
  689. elements.push(
  690. textElement({
  691. left: textLeft,
  692. top,
  693. width: textWidth,
  694. height,
  695. content: item,
  696. fontSize: fitFont(item, textWidth, height, slot.preferredFontSize || 32, minimumFontSize),
  697. minimumFontSize,
  698. color: master.textColor,
  699. bold: index === 0
  700. })
  701. )
  702. })
  703. }
  704. function addVisualOrResource(elements: PPTElement[], slot: TemplateSlot | undefined, page: AiCoursewarePage, master: TemplateMaster, palette: Palette, allowPlaceholder = true) {
  705. if (!slot) return
  706. const dedicated = (page.resourceBindings || []).find(item => item.verified !== false && item.dedicatedPage)
  707. if (dedicated?.resourceType === "MUSIC") {
  708. elements.push({ id: nanoid(10), type: "elf", subtype: "elf-sing-play", sid: dedicated.resourceId, title: dedicated.name || page.title, left: slot.left, top: slot.top, width: slot.width, height: slot.height, rotate: 0 } as PPTCloudCoachElement)
  709. return
  710. }
  711. const video = videoBinding(page)
  712. if (video) {
  713. elements.push({ id: nanoid(10), type: "elf", subtype: "elf-video", left: slot.left, top: slot.top, width: slot.width, height: slot.height, rotate: 0, src: video.contentUrl || "", poster: video.coverUrl, autoplay: false } as PPTVideoElement)
  714. return
  715. }
  716. if (hasImage(page)) {
  717. elements.push(imageElement(page, { left: slot.left, top: slot.top, width: slot.width, height: slot.height, radius: 18 }))
  718. return
  719. }
  720. // 无教学图片时留给文字排版;通用装饰不能充当观察对象。
  721. }
  722. function addSemanticVisual(elements: PPTElement[], slot: TemplateSlot, page: AiCoursewarePage, master: TemplateMaster, palette: Palette) {
  723. elements.push(shapeElement({ left: slot.left, top: slot.top, width: slot.width, height: slot.height, fill: master.surfaceColor, opacity: 0.86, radius: 18, shadow: lightShadow() }))
  724. const landscapeTop = slot.top + slot.height * 0.48
  725. elements.push(shapeElement({ left: slot.left + slot.width * 0.08, top: landscapeTop, width: slot.width * 0.84, height: slot.height * 0.35, fill: palette.soft, opacity: 0.9, radius: 28 }))
  726. elements.push(shapeElement({ left: slot.left + slot.width * 0.68, top: slot.top + slot.height * 0.12, width: Math.min(84, slot.width * 0.16), height: Math.min(84, slot.width * 0.16), fill: palette.warm, opacity: 0.85, radius: 42 }))
  727. elements.push(shapeElement({ left: slot.left + slot.width * 0.12, top: landscapeTop + slot.height * 0.12, width: slot.width * 0.46, height: slot.height * 0.2, fill: palette.secondary, opacity: 0.55, radius: 40 }))
  728. elements.push(shapeElement({ left: slot.left + slot.width * 0.42, top: landscapeTop + slot.height * 0.08, width: slot.width * 0.42, height: slot.height * 0.24, fill: palette.primary, opacity: 0.45, radius: 44 }))
  729. const requestedCue = cleanText(page.visualPlan?.focalContent || page.visualPlan?.mainVisual || page.visual?.mainVisual || page.imageKeywords?.[0])
  730. const cue = !requestedCue || sameVisibleText(requestedCue, page.title)
  731. ? `画面线索:${cleanText(page.title) || "观察音乐变化"}`
  732. : requestedCue
  733. elements.push(textElement({
  734. left: slot.left + slot.width * 0.1,
  735. top: slot.top + slot.height * 0.13,
  736. width: slot.width * 0.54,
  737. height: slot.height * 0.25,
  738. content: cue,
  739. fontSize: fitFont(cue, slot.width * 0.54, slot.height * 0.25, 30, 22),
  740. minimumFontSize: 22,
  741. color: master.titleColor,
  742. bold: true
  743. }))
  744. }
  745. function addInlineMedia(elements: PPTElement[], slot: TemplateSlot | undefined, page: AiCoursewarePage, master: TemplateMaster, palette: Palette, showMedia: boolean) {
  746. if (!slot || !showMedia) return
  747. const bindings = audioBindings(page)
  748. const width = slot.width / Math.max(1, bindings.length)
  749. bindings.forEach((binding, index) => {
  750. elements.push({ id: nanoid(10), type: "elf", subtype: "elf-audio", left: slot.left + index * width,
  751. top: slot.top + (slot.height - 60) / 2, width: 60, height: 60, rotate: 0, fixedRatio: true,
  752. color: palette.primary, autoplay: false, loop: false, src: binding.contentUrl! } as PPTAudioElement)
  753. addSlotText(elements, { ...slot, left: slot.left + index * width + 76, width: width - 92 },
  754. `${bindings.length > 1 ? String.fromCharCode(65 + index) + " · " : ""}${binding.name || "课堂音频"}`, master.textColor)
  755. })
  756. }
  757. function renderTemplateMasterElements(elements: TemplateMasterElement[]): PPTElement[] {
  758. return elements.map(element =>
  759. element.type === "text"
  760. ? textElement({
  761. left: element.left,
  762. top: element.top,
  763. width: element.width,
  764. height: element.height,
  765. content: element.content || "",
  766. fontSize: element.fontSize || 14,
  767. color: element.color || "#20313A",
  768. bold: element.bold
  769. })
  770. : shapeElement({
  771. left: element.left,
  772. top: element.top,
  773. width: element.width,
  774. height: element.height,
  775. fill: element.fill || "#FFFFFF",
  776. opacity: element.opacity,
  777. radius: element.radius
  778. })
  779. )
  780. }
  781. function entranceAnimations(elements: PPTElement[]): PPTAnimation[] {
  782. return elements
  783. .filter(
  784. element => element.type === "text" && element.width >= 120 && element.height >= 45
  785. )
  786. .slice(0, 6)
  787. .map((element, index) => ({
  788. id: nanoid(10),
  789. elId: element.id,
  790. effect: index === 0 ? "fadeIn" : "fadeInUp",
  791. type: "in",
  792. duration: 500,
  793. trigger: index === 0 ? "auto" : "click"
  794. }))
  795. }
  796. function videoBinding(page: AiCoursewarePage) {
  797. return (page.resourceBindings || []).find(item => item.verified === true && item.resourceType === "VIDEO" && usableResourceUrl(item.contentUrl))
  798. }
  799. function normalizeOutline(outline: AiCoursewareOutline): AiCoursewareOutline {
  800. const chapter = cleanText(outline.chapterName || outline.title || "音乐课件")
  801. return {
  802. ...outline,
  803. title: GENERIC_PAGE_TITLES.has(cleanText(outline.title).toLowerCase()) ? chapter : cleanText(outline.title || chapter),
  804. pages: (outline.pages || []).map((page, index) => ({
  805. ...page,
  806. pageNo: index + 1,
  807. title: index === 0 && GENERIC_PAGE_TITLES.has(cleanText(page.title).toLowerCase()) ? chapter : cleanText(page.title || chapter),
  808. bullets: (page.bullets || []).map(cleanText).filter(Boolean),
  809. imageKeywords: (page.imageKeywords || []).map(cleanText).filter(Boolean)
  810. }))
  811. }
  812. }
  813. function pageRole(page: AiCoursewarePage, index: number): PageRole {
  814. if (index === 0) return "cover"
  815. const kind = `${page.type || ""} ${page.visualPlan?.layout || ""} ${page.visual?.layout || ""}`.toLowerCase()
  816. if (kind.includes("objective") || kind.includes("goal")) return "goal"
  817. if (kind.includes("practice_check") || kind.includes("assessment")) return "practice"
  818. if (kind.includes("compare")) return "compare"
  819. if (kind.includes("instrument")) return "instrument"
  820. if (kind.includes("melody") || kind.includes("score") || kind.includes("notation")) return "notation"
  821. if (kind.includes("performance") || kind.includes("expressive") || kind.includes("creative")) return "performance"
  822. if (kind.includes("listen")) return "listen"
  823. if (kind.includes("lyric") || kind.includes("phrase_sing") || kind.includes("sing_focus")) return "lyric"
  824. if (kind.includes("rhythm") || kind.includes("skill")) return "rhythm"
  825. if (kind.includes("knowledge")) return "knowledge"
  826. if (kind.includes("interaction")) return "interaction"
  827. if (kind.includes("activity")) return "activity"
  828. if (kind.includes("summary")) return "summary"
  829. if (kind.includes("homework") || kind.includes("extension")) return "homework"
  830. if (kind.includes("intro") || kind.includes("scene")) return "intro"
  831. if (kind.includes("context") || kind.includes("background") || kind.includes("story")) return "story"
  832. return "content"
  833. }
  834. function displayPageTitle(page: AiCoursewarePage, outline: AiCoursewareOutline) {
  835. const title = cleanText(page.title)
  836. return !title || GENERIC_PAGE_TITLES.has(title.toLowerCase()) ? chapterTitle(outline, page) : title
  837. }
  838. function chapterTitle(outline: AiCoursewareOutline, page: AiCoursewarePage) {
  839. return cleanText(page.title || outline.title || outline.chapterName || "音乐课件")
  840. }
  841. function conciseTextbook(value?: string) {
  842. return cleanText(value).replace(/^.*?·/, "")
  843. }
  844. function hasImage(page: AiCoursewarePage) {
  845. return Boolean(page.image?.url)
  846. }
  847. function studentHeadline(page: AiCoursewarePage) {
  848. const headline = cleanText(page.studentContent?.headline || page.subtitle || "")
  849. return sameVisibleText(headline, page.title) || isTeacherFacingText(headline) ? "" : headline
  850. }
  851. function studentPoints(page: AiCoursewarePage) {
  852. const structured = (page.studentContent?.points || []).map(cleanText).filter(Boolean)
  853. const legacy = (page.bullets || []).map(cleanText).filter(Boolean)
  854. const points = [...(structured.length ? structured : legacy), studentHeadline(page)].filter(Boolean)
  855. const excluded = [page.title].map(normalizeVisibleText).filter(Boolean)
  856. return uniqueVisibleTexts(points).filter(item => !excluded.includes(normalizeVisibleText(item)) && !isTeacherFacingText(item))
  857. }
  858. function activityTask(page: AiCoursewarePage) {
  859. // activity 属于教师组织信息,不能回退到学生投屏画面。
  860. const task = cleanText(page.classroomAction?.studentTask || studentHeadline(page) || "")
  861. return sameVisibleText(task, page.title) || isTeacherFacingText(task) ? "" : task
  862. }
  863. function slideRemark(page: AiCoursewarePage) {
  864. const lessonMeta = page.teachingStage || ""
  865. const evidence = page.learningEvidence ? `学习表现:${page.learningEvidence}` : ""
  866. const activity = [page.activity?.task, ...(page.activity?.steps || [])].map(cleanText).filter(Boolean).join("\n")
  867. const fallbackInstruction = cleanText(page.classroomAction?.teacherInstruction || page.teacherTips || page.speakerNotes)
  868. || `引导学生完成“${activityTask(page) || page.title}”,观察学生是否能用语言、动作或声音表达本页学习结果。`
  869. const answer = page.interaction?.answer ? `参考答案:${page.interaction.answer}` : ""
  870. const explanation = page.interaction?.explanation ? `解析:${page.interaction.explanation}` : ""
  871. const resources = (page.resourceBindings || []).map(item => `${item.name || item.resourceType}:${item.purpose || "课堂资源"}`).join("\n")
  872. const mediaReminder = /listen|sing/.test(page.type) && audioBindings(page).length === 0 ? "资源准备:请为本页听唱任务补充对应音频。" : ""
  873. return [lessonMeta, page.teachingPurpose, ...teacherFacingTexts(page), activity, fallbackInstruction, page.speakerNotes, page.teacherTips, evidence, answer, explanation, resources, mediaReminder, page.imageReview]
  874. .map(cleanText)
  875. .filter(Boolean)
  876. .filter((item, index, all) => all.indexOf(item) === index)
  877. .join("\n")
  878. }
  879. function buildPalette(outline: AiCoursewareOutline, variant: number, templateId?: AiCoursewareTemplateId): Palette {
  880. const resolvedTemplateId = templateId || DEFAULT_AI_COURSEWARE_TEMPLATE_ID
  881. return { ...getAiCoursewarePalette(resolvedTemplateId, variant), ...(resolvedTemplateId === "dark-lute" ? { soft: "#16485C" } : {}) }
  882. }
  883. function backgroundConfig(masterPage: TemplateMasterPage, options: AiPptOptions): SlideBackground {
  884. if (options.backgroundImage) return { type: "image", image: options.backgroundImage, imageSize: "cover" }
  885. if (masterPage.backgroundImage) return { type: "image", image: masterPage.backgroundImage, imageSize: "cover" }
  886. return { type: "solid", color: masterPage.background }
  887. }
  888. function fitFont(content: string, width: number, height: number, preferred: number, minimum: number) {
  889. const text = cleanText(content)
  890. if (!text) return preferred
  891. let size = preferred
  892. while (size > minimum) {
  893. const estimated = minimum >= 28 ? measureAiPptText(text, width, size)
  894. : Math.ceil(text.length / Math.max(1, Math.floor(width / size))) * size * 1.35
  895. if (estimated <= height) break
  896. size = Math.max(minimum, size - 2)
  897. }
  898. return size
  899. }
  900. function textElement(params: {
  901. left: number
  902. top: number
  903. width: number
  904. height: number
  905. content: string
  906. fontSize: number
  907. minimumFontSize?: number
  908. color: string
  909. bold?: boolean
  910. lineHeight?: number
  911. }): PPTTextElement {
  912. const lineHeight = params.lineHeight || 1.25
  913. const minimum = Math.min(params.fontSize, params.minimumFontSize ?? (params.fontSize >= 30 ? 22 : 18))
  914. const resolvedFontSize = fitFont(params.content, params.width, params.height, params.fontSize, minimum)
  915. return {
  916. id: nanoid(10),
  917. type: "text",
  918. left: params.left,
  919. top: params.top,
  920. width: params.width,
  921. height: params.height,
  922. rotate: 0,
  923. // 永远保留完整文本。若最小字号仍放不下,由质量门禁阻止应用,而不是静默截断。
  924. content: `<div style="box-sizing:border-box;width:calc(100% - 20px);font-family:${FONT_NAME};font-size:${resolvedFontSize}px;${params.bold ? "font-weight:700;" : ""}">${escapeHtml(cleanText(params.content))}</div>`,
  925. defaultFontName: FONT_NAME,
  926. defaultColor: params.color,
  927. lineHeight,
  928. paragraphSpace: 0,
  929. wordSpace: 0,
  930. opacity: 1
  931. }
  932. }
  933. function imageElement(page: AiCoursewarePage, rect: ImageRect): PPTImageElement {
  934. const width = page.image?.width || 0
  935. const height = page.image?.height || 0
  936. const contain = page.requiredVisual || page.visualPlan?.imagePurpose !== "decoration" || page.visualPlan?.imageFit !== "cover"
  937. const scale = width > 0 && height > 0 ? Math.min(rect.width / width, rect.height / height) : 0
  938. const fittedWidth = contain && scale ? width * scale : rect.width
  939. const fittedHeight = contain && scale ? height * scale : rect.height
  940. return {
  941. id: nanoid(10),
  942. type: "image",
  943. left: rect.left + (rect.width - fittedWidth) / 2,
  944. top: rect.top + (rect.height - fittedHeight) / 2,
  945. width: fittedWidth,
  946. height: fittedHeight,
  947. rotate: 0,
  948. src: page.image?.url || "",
  949. fixedRatio: Boolean(contain),
  950. radius: rect.radius || 0,
  951. shadow: rect.radius ? softShadow() : undefined,
  952. clip: !contain && width > 0 && height > 0 ? { shape: "rect", range: coverRange(width, height, rect.width, rect.height) } : undefined
  953. }
  954. }
  955. function coverRange(sourceWidth: number, sourceHeight: number, targetWidth: number, targetHeight: number): [[number, number], [number, number]] {
  956. const sourceRatio = sourceWidth / sourceHeight
  957. const targetRatio = targetWidth / targetHeight
  958. if (sourceRatio > targetRatio) {
  959. const visible = (targetRatio / sourceRatio) * 100
  960. const start = (100 - visible) / 2
  961. return [
  962. [start, 0],
  963. [100 - start, 100]
  964. ]
  965. }
  966. const visible = (sourceRatio / targetRatio) * 100
  967. const start = (100 - visible) / 2
  968. return [
  969. [0, start],
  970. [100, 100 - start]
  971. ]
  972. }
  973. function shapeElement(params: {
  974. left: number
  975. top: number
  976. width: number
  977. height: number
  978. fill: string
  979. opacity?: number
  980. radius?: number
  981. shadow?: PPTElementShadow
  982. gradient?: Gradient
  983. text?: PPTShapeElement["text"]
  984. }): PPTShapeElement {
  985. return {
  986. id: nanoid(10),
  987. type: "shape",
  988. left: params.left,
  989. top: params.top,
  990. width: params.width,
  991. height: params.height,
  992. rotate: 0,
  993. viewBox: [200, 200],
  994. path: roundedRectPath(params.radius || 0),
  995. fixedRatio: false,
  996. fill: params.fill,
  997. opacity: params.opacity ?? 1,
  998. shadow: params.shadow,
  999. gradient: params.gradient,
  1000. text: params.text
  1001. }
  1002. }
  1003. function lineElement(x1: number, y1: number, x2: number, y2: number, color: string, width = 2): PPTLineElement {
  1004. const left = Math.min(x1, x2)
  1005. const top = Math.min(y1, y2)
  1006. const lineWidth = Math.abs(x2 - x1)
  1007. const lineHeight = Math.abs(y2 - y1)
  1008. return {
  1009. id: nanoid(10),
  1010. type: "line",
  1011. left,
  1012. top,
  1013. width,
  1014. start: [x1 === left ? 0 : lineWidth, y1 === top ? 0 : lineHeight],
  1015. end: [x2 === left ? 0 : lineWidth, y2 === top ? 0 : lineHeight],
  1016. style: "solid",
  1017. color,
  1018. points: ["", ""]
  1019. }
  1020. }
  1021. function keepInCanvas(elements: PPTElement[]) {
  1022. return elements.map(element => {
  1023. const left = Math.max(0, Math.min(element.left, SLIDE_WIDTH - 1))
  1024. const top = Math.max(0, Math.min(element.top, SLIDE_HEIGHT - 1))
  1025. if (element.type === "line") return { ...element, left, top, width: Math.max(1, Math.min(element.width, 20)) }
  1026. return {
  1027. ...element,
  1028. left,
  1029. top,
  1030. width: Math.max(1, Math.min(element.width, SLIDE_WIDTH - left)),
  1031. height: Math.max(1, Math.min(element.height, SLIDE_HEIGHT - top))
  1032. }
  1033. }) as PPTElement[]
  1034. }
  1035. function scaleElementsToViewport(elements: PPTElement[]): PPTElement[] {
  1036. return elements.map(element => {
  1037. if (element.type === "line") {
  1038. return {
  1039. ...element,
  1040. left: element.left * VIEWPORT_SCALE,
  1041. top: element.top * VIEWPORT_SCALE,
  1042. width: element.width * VIEWPORT_SCALE,
  1043. start: [element.start[0] * VIEWPORT_SCALE, element.start[1] * VIEWPORT_SCALE],
  1044. end: [element.end[0] * VIEWPORT_SCALE, element.end[1] * VIEWPORT_SCALE]
  1045. }
  1046. }
  1047. const scaled = {
  1048. ...element,
  1049. left: element.left * VIEWPORT_SCALE,
  1050. top: element.top * VIEWPORT_SCALE,
  1051. width: element.width * VIEWPORT_SCALE,
  1052. height: element.height * VIEWPORT_SCALE
  1053. } as PPTElement
  1054. if (scaled.type === "text") {
  1055. scaled.content = scaleInlineFontSizes(scaled.content)
  1056. }
  1057. if (scaled.type === "shape" && scaled.text) {
  1058. scaled.text = { ...scaled.text, content: scaleInlineFontSizes(scaled.text.content) }
  1059. }
  1060. if ("radius" in scaled && typeof scaled.radius === "number") {
  1061. scaled.radius *= VIEWPORT_SCALE
  1062. }
  1063. if ("shadow" in scaled && scaled.shadow) {
  1064. scaled.shadow = {
  1065. ...scaled.shadow,
  1066. h: scaled.shadow.h * VIEWPORT_SCALE,
  1067. v: scaled.shadow.v * VIEWPORT_SCALE,
  1068. blur: scaled.shadow.blur * VIEWPORT_SCALE
  1069. }
  1070. }
  1071. return scaled
  1072. })
  1073. }
  1074. function scaleInlineFontSizes(content: string) {
  1075. return content.replace(/font-size:\s*([\d.]+)px/g, (_match, size) => `font-size:${Number(size) * VIEWPORT_SCALE}px`)
  1076. }
  1077. function runPreflight(slides: Slide[]) {
  1078. slides.forEach((slide, index) => {
  1079. const invalid = slide.elements.filter(
  1080. element =>
  1081. element.left < 0 ||
  1082. element.top < 0 ||
  1083. element.left + element.width > VIEWPORT_WIDTH + 1 ||
  1084. (element.type !== "line" && element.top + element.height > VIEWPORT_HEIGHT + 1)
  1085. )
  1086. const emptyText = slide.elements.filter(element => element.type === "text" && !stripHtml(element.content))
  1087. if (invalid.length || emptyText.length)
  1088. console.warn("AI PPT preflight issue", { pageNo: index + 1, invalid: invalid.length, emptyText: emptyText.length })
  1089. })
  1090. }
  1091. function roundedRectPath(radius: number) {
  1092. const r = Math.max(0, Math.min(radius, 100))
  1093. return `M ${r} 0 L ${200 - r} 0 Q 200 0 200 ${r} L 200 ${200 - r} Q 200 200 ${200 - r} 200 L ${r} 200 Q 0 200 0 ${200 - r} L 0 ${r} Q 0 0 ${r} 0 Z`
  1094. }
  1095. function softShadow(): PPTElementShadow {
  1096. return { h: 0, v: 8, blur: 22, color: "rgba(23, 34, 46, 0.14)" }
  1097. }
  1098. function lightShadow(): PPTElementShadow {
  1099. return { h: 0, v: 4, blur: 14, color: "rgba(23, 34, 46, 0.1)" }
  1100. }
  1101. function cleanText(value?: string) {
  1102. return String(value || "")
  1103. .replace(/\s+/g, " ")
  1104. .trim()
  1105. }
  1106. function escapeHtml(value: string) {
  1107. return cleanText(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
  1108. }
  1109. function stripHtml(value: string) {
  1110. return value.replace(/<[^>]+>/g, "").trim()
  1111. }
  1112. function normalizeVisibleText(value?: string) {
  1113. return cleanText(value)
  1114. .replace(/[,。!?、;:,.!?;:\s]+/g, "")
  1115. .toLowerCase()
  1116. }
  1117. function sameVisibleText(left?: string, right?: string) {
  1118. const normalizedLeft = normalizeVisibleText(left)
  1119. return Boolean(normalizedLeft) && normalizedLeft === normalizeVisibleText(right)
  1120. }
  1121. function uniqueVisibleTexts(values: string[]) {
  1122. const seen = new Set<string>()
  1123. return values.filter(value => {
  1124. const key = normalizeVisibleText(value)
  1125. if (!key || seen.has(key)) return false
  1126. seen.add(key)
  1127. return true
  1128. })
  1129. }