@mathwiz/ui-components 0.1.22 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/data/GeometryProblemAdapterV4/GeometryAdapterCore.d.ts.map +1 -1
- package/dist/data/GeometryProblemAdapterV4/geometry-types.d.ts +1012 -0
- package/dist/data/GeometryProblemAdapterV4/geometry-types.d.ts.map +1 -0
- package/dist/data/GeometryProblemAdapterV4/types.d.ts +16 -103
- package/dist/data/GeometryProblemAdapterV4/types.d.ts.map +1 -1
- package/dist/data/dataSchema/OpenAPI/openapi.json +8564 -0
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +14 -17
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -16,9 +16,9 @@ import 'katex/dist/katex.min.css';
|
|
|
16
16
|
2. point1 + point2 IDs
|
|
17
17
|
3. p1 + p2 coordinates
|
|
18
18
|
Received: ${JSON.stringify(n)}`)}case"shear":{const n=r.params,s=ve(n.shearX,e),o=ve(n.shearY,e);return[s,o]}case"generic":{const n=r.params;return[ve(n.a,e),ve(n.b,e),ve(n.c,e),ve(n.d,e),ve(n.e,e),ve(n.f,e),ve(n.g,e),ve(n.h,e),ve(n.i,e)]}case"matrix":{const n=r.params;if(!Array.isArray(n.matrix)||n.matrix.length!==3||!n.matrix.every(s=>Array.isArray(s)&&s.length===3))throw new Error("Matrix transform requires a 3x3 matrix array");return[n.matrix]}default:throw new Error(`Unsupported transform type: ${r.params.type}`)}}function Gl(r){const e={};return Object.entries(r).forEach(([t,n])=>{if(typeof n=="string"&&Ul(n))try{e[t]=Pl(n)}catch(s){console.warn(`Failed to parse function string for ${t}: ${n}`,s),e[t]=()=>0}else e[t]=n}),e}function zl(r){if(!r||typeof r!="object")return{valid:!1,errors:["Config must be an object"]};const e=[];return(!r.id||typeof r.id!="string"||r.id.trim()==="")&&e.push("Config must have a valid id (string)"),Array.isArray(r.transforms)?r.transforms.forEach((t,n)=>{(!t.id||typeof t.id!="string")&&e.push(`Transform at index ${n} must have a valid id`),(!t.type||typeof t.type!="string")&&e.push(`Transform at index ${n} must have a valid type`),(!t.params||typeof t.params!="object")&&e.push(`Transform at index ${n} must have valid params`),Array.isArray(t.targetShapes)?t.targetShapes.length===0&&e.push("targetShapes must not be empty"):e.push(`Transform at index ${n} must have targetShapes array`)}):e.push("Config must have a transforms array"),{valid:e.length===0,errors:e.length>0?e:void 0}}const Jn=ps.JSXGraph,io=r=>{console.warn("🔍 GraphContainer props:",{hasAnimation:!!r.animation,animationId:r.animation?.id,hasControl:!!r.animation?.control,controlConfig:r.animation?.control,animationProgress:r.animationProgress});const e=b.useRef(null),[t,n]=b.useState(null),[,s]=b.useState({}),[o,i]=b.useState(!1),a=b.useRef({}),c=b.useRef({}),l=b.useRef(null),d=b.useRef({}),u=b.useCallback((m,h)=>{r.onShapeChange},[r.onShapeChange]),y=b.useCallback(m=>{r.onSelectionChange&&r.onSelectionChange(m?[m]:[])},[r.onSelectionChange]);return b.useEffect(()=>{if(e.current){try{const m=r.boundingBox||[-10,10,10,-10];console.warn("🔍 JSXGraph Board Initialization:"),console.warn(" - Received boundingBox:",m),console.warn(" - Container dimensions:",e.current.clientWidth,"x",e.current.clientHeight);const h=Jn.initBoard(e.current,{boundingbox:m,axis:r.showAxis??!0,grid:r.showGrid??!0,showNavigation:!1,pan:{enabled:r.mode==="edit"},keepaspectratio:!0,showCopyright:!1});console.warn(" - Board actual boundingbox:",h.getBoundingBox()),setTimeout(()=>{console.warn(" - 验证坐标转换:"),console.warn(" * 理论边界框:",m),console.warn(" * 实际边界框:",h.getBoundingBox()),console.warn(" * 实际显示范围:",{left:h.getBoundingBox()[0],top:h.getBoundingBox()[1],right:h.getBoundingBox()[2],bottom:h.getBoundingBox()[3]})},100),n(h)}catch(m){console.error("JSXGraph initialization failed:",m)}return()=>{t&&Jn.freeBoard(t)}}},[]),b.useEffect(()=>{if(console.warn("🔍 Control useEffect triggered:",{hasBoard:!!t,hasAnimation:!!r.animation,hasControl:!!r.animation?.control,animationId:r.animation?.id,controlType:r.animation?.control?.type,controlPosition:r.animation?.control?.position,controlRange:r.animation?.control?.range}),!t||!r.animation?.control){if(console.warn("❌ Control creation skipped: board="+!!t+", control="+!!r.animation?.control),l.current){try{l.current.remove&&l.current.remove()}catch(h){console.warn("Failed to remove control:",h)}l.current=null}return}const m=r.animation.control;console.warn("✨ Creating Control Component:",{type:m.type,config:m,position:m.position,range:m.range});try{if(m.type==="slider"){const h=m.position[0]+(m.length||5);console.warn("📐 Slider creation parameters:",{startPoint:m.position,endPoint:[h,m.position[1]],values:[m.range[0],m.initial||0,m.range[1]],label:m.label,snapWidth:m.snapWidth||.01});const g=t.create("slider",[m.position,[h,m.position[1]],[m.range[0],m.initial||0,m.range[1]]],{name:m.label||"control",snapWidth:m.snapWidth||.01,withLabel:m.showLabel!==void 0?m.showLabel:!0,visible:!0,strokeColor:"#4CAF50",fillColor:"#4CAF50",highlightFillColor:"#66BB6A"});l.current=g,console.warn("✅ Slider created:",{id:g.id,name:g.name,initialValue:g.Value(),startPoint:m.position,endPoint:[h,m.position[1]],boundingBox:t.getBoundingBox(),visProp:g.visProp});const p=t.objectsList.map(C=>({id:C.id,type:C.elType,name:C.name,visible:C.visProp?.visible})),x=p.find(C=>C.id===g.id);if(console.warn("📊 Slider in board.objectsList:",!!x,x),console.warn("📊 All board objects count:",p.length),r.onAnimationChange){let C=!1;g.on("drag",()=>{if(C)return;C=!0;const E=(g.Value()-m.range[0])/(m.range[1]-m.range[0]);r.onAnimationChange?.(E),C=!1})}}else if(m.type==="glider"){const h=t.select(m.line,!0);if(h){const g=t.create("glider",[m.initial||0,0,h],{name:m.label||"control",snapWidth:m.snapWidth||.01});if(l.current=g,console.warn("✅ Glider created:",{id:g.id,name:g.name}),r.onAnimationChange){let p=!1;g.on("drag",()=>{if(p)return;p=!0;const x=g.Value();r.onAnimationChange?.(x),p=!1})}}else console.warn(`Reference line not found for glider: ${m.line}`)}}catch(h){console.error("Failed to create control component:",h)}return()=>{if(l.current){try{l.current.remove()}catch(h){console.warn("Failed to remove control on cleanup:",h)}l.current=null}}},[t,r.animation?.control]),b.useEffect(()=>{if(!t||!r.animation){Object.keys(a.current).length>0&&(a.current={});return}try{console.warn("✨ Creating Transforms:",{animationId:r.animation.id,transformCount:r.animation.transforms.length}),Object.values(a.current).forEach(g=>{try{g&&g.remove&&g.remove()}catch(p){console.warn("Failed to remove transform:",p)}}),a.current={};const m={},h=r.animationProgress??0;r.animation.transforms.forEach(g=>{try{let p,x;const C=g.usesControl||!1;if(l.current&&C){p=jr(g,h,l.current),console.warn(`🔧 Creating transform ${g.id} (with dynamic params):`,{type:g.type,paramsTypes:p.map(E=>typeof E),targetShapes:g.targetShapes,controlValue:l.current.Value()}),x=t.create("transform",p,{type:g.type,id:`transform_${g.id}`});const S=()=>{if(!l.current)return;t.update();const E=l.current.Value();if(console.warn(`🎯 Slider drag - transform ${g.id} auto-updated (controlValue: ${E})`),r.onAnimationChange){const _=r.animation?.control?.range||[0,1],j=(E-_[0])/(_[1]-_[0]);r.onAnimationChange(j)}};l.current.on("drag",S),d.current[g.id]=S,console.warn(`🔗 Slider listener attached for transform ${g.id} (auto-update mode)`)}else p=jr(g,h),console.warn(`🔧 Creating transform ${g.id} (with progress ${h}):`,{type:g.type,params:p,targetShapes:g.targetShapes}),x=t.create("transform",p,{type:g.type,id:`transform_${g.id}`});m[g.id]=x,console.warn(`📝 Transform ${g.id} created:`,{type:g.type,paramsTypes:p.map(S=>typeof S),transformMethods:Object.keys(x).filter(S=>typeof x[S]=="function")})}catch(p){console.error(`Failed to create transform ${g.id}:`,p)}}),a.current=m}catch(m){console.error("Transform setup failed:",m)}},[t,r.animation]),b.useEffect(()=>{if(!o||!t||!r.animation){console.warn(`⏳ Transform binding waiting: shapesReady=${o}, board=${!!t}, animation=${!!r.animation}`);return}if(console.warn("✅ Attempting to bind transforms to shapes..."),console.warn(` Available shapes: ${Object.keys(c.current).length}`),console.warn(` Available transforms: ${Object.keys(a.current).length}`),Object.keys(c.current).length===0){console.warn("❌ No shapes available, skipping transform binding");return}if(Object.keys(a.current).length===0){console.warn("❌ No transforms available, skipping binding");return}Object.entries(a.current).forEach(([m,h])=>{const g=r.animation?.transforms.find(x=>x.id===m);if(!g)return;console.warn(`🔍 Binding transform ${m} (type: ${g.type}) to shapes:`,g.targetShapes),console.warn("🔍 Available shapes in shapeElementsRef:",Object.keys(c.current));const p=g.targetShapes.map(x=>{const C=c.current[x];return C?console.warn(`✅ Found shape ${x}:`,C):(console.warn(`❌ Shape not found for transform binding: ${x}`),console.warn(" Available IDs:",Object.keys(c.current))),C}).filter(Boolean);if(console.warn("🔍 Target elements after filtering:",p.length),p.length>0)try{console.warn(`🔗 Attempting to bind transform ${m} to ${p.length} shapes`),h.bindTo(p),console.warn(`✅ Successfully bound transform ${m} to ${p.length} shapes`),console.warn(" Transform object:",h),console.warn(" Target elements:",p.map(x=>({id:x.id,name:x.name,type:x.elementClass})))}catch(x){console.error(`❌ Failed to bind transform ${m}:`,x),console.error(" Transform:",h),console.error(" TargetElements:",p)}else console.warn(`⚠️ No valid target elements for transform ${m}`)}),t.update(),console.warn("✅ All transforms bound and board updated")},[o,t,r.animation]),b.useEffect(()=>{if(!t||Object.keys(a.current).length===0)return;const m=r.animationProgress??0;console.warn(`🔄 Updating transforms for progress: ${m}`);try{Object.entries(a.current).forEach(([h,g])=>{const p=r.animation?.transforms.find(C=>C.id===h);if(!p)return;const x=jr(p,m);console.warn(`🔄 Attempting to update transform ${h} with params:`,x),g.update?(console.warn(" Using transform.update(params)"),g.update(x)):g.setMatrix?(console.warn(" Using transform.setMatrix(board, config.type, params)"),g.setMatrix(t,p.type,x)):(console.warn(" Transform has no update or setMatrix method"),console.warn(" Available methods:",Object.keys(g).filter(C=>typeof g[C]=="function")))}),t.update()}catch(h){console.error("Transform update failed:",h)}},[t,r.animationProgress]),b.useEffect(()=>{if(t)try{console.warn("🎯 GraphContainer rendering shapes:",{totalShapes:r.shapes.length,shapes:r.shapes.map(g=>({id:g.id,type:g.type,hasVertices:"vertices"in g,verticesCount:"vertices"in g&&g.vertices?g.vertices.length:"undefined",hasPosition:"position"in g,hasGeometryRef:"geometryRef"in g,geometryRef:"geometryRef"in g?g.geometryRef:void 0}))}),t.suspendUpdate(),[...t.objectsList].forEach(g=>{t.removeObject(g)});const h={};c.current={},r.shapes.forEach(g=>{if(g.type==="point")try{const p=Ir(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create point shape ${g.id}:`,p)}}),console.warn("📐 Starting phase 2: creating lines, circles and polygons"),console.warn("📊 Current board.objectsList:",t.objectsList.map(g=>({id:g.id,name:g.name,type:g.elementClass}))),r.shapes.forEach(g=>{if(g.type==="line"||g.type==="circle"||g.type==="polygon")try{const p=Ir(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create shape ${g.id}:`,p)}}),console.warn("📝 Starting phase 3: creating text labels"),r.shapes.forEach(g=>{if(g.type==="text")try{const p=Ir(t,g,r.mode,u,y);p&&(h[g.id]=p)}catch(p){console.warn(`Failed to create text ${g.id}:`,p)}}),s(h),c.current=h,i(!0),console.warn(`✅ Shapes rendering completed: ${Object.keys(h).length} shapes created`),t.unsuspendUpdate()}catch(m){console.error("Shape rendering failed:",m)}},[t,r.shapes,r.mode,u,y]),b.useEffect(()=>()=>{console.warn("🧹 Component unmounting, cleaning up..."),l.current&&Object.entries(d.current).forEach(([m,h])=>{try{l.current.off("drag",h),console.warn(` Removed drag listener for transform ${m}`)}catch(g){console.warn(`Failed to remove drag listener for ${m}:`,g)}}),d.current={},Object.values(a.current).forEach(m=>{try{m&&m.remove&&m.remove()}catch(h){console.warn("Failed to remove transform during cleanup:",h)}}),a.current={},c.current={},i(!1),console.warn("✅ Cleanup complete")},[]),f.jsx("div",{ref:e,className:"w-full h-full"})};function Ir(r,e,t,n,s){const o=t==="edit";switch(e.type){case"point":try{if(console.warn(`🔍 Creating point ${e.id}:`,{id:e.id,type:e.type,position:e.position,hasPosition:"position"in e,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),positionX:e.position?.x,positionY:e.position?.y,position0:Array.isArray(e.position)?e.position[0]:void 0,position1:Array.isArray(e.position)?e.position[1]:void 0}),!e.position)return console.error(`❌ Point ${e.id} has no position field`),null;let l,d;if(e.position.x!==void 0&&e.position.y!==void 0)l=e.position.x,d=e.position.y;else if(Array.isArray(e.position)&&e.position.length>=2)l=e.position[0],d=e.position[1];else return console.error(`❌ Point ${e.id} has invalid position format:`,e.position),null;const u=r.create("point",[l,d],{id:e.id,name:e.name||"",withLabel:e.withLabel??!!e.name,fixed:!o,size:e.size??3,strokeColor:e.strokeColor||e.color||"black",visible:e.visible??!0,label:e.label?{offset:e.label.offset||[10,10],fontSize:e.label.fontSize||14,color:e.label.color,anchorX:e.label.anchorX||"middle",anchorY:e.label.anchorY||"bottom",cssClass:e.label.cssClass,position:e.label.position||"urt",autoPosition:e.label.autoPosition||!1,distance:e.label.distance||1.5}:void 0});return console.warn("🔵 Created point:",{shapeId:e.id,pointId:u.id,pointName:u.name,hasIdProperty:"id"in u}),o&&(r.on("drag",()=>{n(e.id,{x:u.X(),y:u.Y()})}),r.on("down",()=>{s(e.id)})),u}catch(l){return console.error(`Failed to create point ${e.id}:`,l),null}case"line":const i=Jt(e.start,r),a=Jt(e.end,r);if(i&&a)try{const l=r.create("line",[i,a],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",dash:e.dash??0,fixed:!o,visible:e.visible??!0,straightFirst:!1,straightLast:!1});return o&&r.on("down",()=>{s(e.id)}),l}catch(l){return console.error(`Failed to create line ${e.id}:`,l),null}else console.warn(`Cannot create line ${e.id}: missing start or end point`,{startPoint:!!i,endPoint:!!a,startRef:e.start,endRef:e.end});break;case"circle":const c=Jt(e.center,r);if(c){let l;if(e.through){const d=Jt(e.through,r);d&&(l=r.create("circle",[c,d],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0}))}else e.radius!==void 0&&(l=r.create("circle",[c,e.radius],{strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"none",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0}));return l&&o&&r.on("down",()=>{s(e.id)}),l}break;case"polygon":try{if(console.error(`🔍 Creating polygon ${e.id}:`,{id:e.id,type:e.type,hasVertices:"vertices"in e,vertices:e.vertices,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e),geometryRef:"geometryRef"in e?e.geometryRef:void 0,styleRef:"styleRef"in e?e.styleRef:void 0,fullShapeData:JSON.stringify(e,null,2)}),!e.vertices)return console.error(`❌ FATAL: Polygon ${e.id} has no vertices! Full shape data:`,JSON.stringify(e,null,2)),null;if(!Array.isArray(e.vertices))return console.error(`❌ FATAL: Polygon ${e.id} vertices is not an array:`,e.vertices),null;const l=e.vertices.map((d,u)=>{const y=e.verticesConfig?e.verticesConfig[u]:null;return Bl(d,r,y)});if(console.warn(`🔧 Polygon ${e.id} resolved vertices:`,l),console.warn(`🔧 Polygon ${e.id} vertices types:`,l.map(d=>({type:typeof d,isArray:Array.isArray(d),value:d}))),l.every(d=>d!==null)){const d={strokeWidth:e.strokeWidth??2,strokeColor:e.strokeColor||e.color||"black",fillColor:e.fillColor||"lightblue",fillOpacity:e.fillOpacity??.3,dash:e.dash??0,fixed:!o,visible:e.visible??!0};if(e.verticesConfig){console.warn(`🔧 GraphContainer processing verticesConfig for polygon ${e.id}:`,{verticesConfig:e.verticesConfig,verticesConfigKeys:Object.keys(e.verticesConfig),verticesConfigType:typeof e.verticesConfig});const y={};e.verticesConfig.withLabel!==void 0?y.withLabel=e.verticesConfig.withLabel:y.withLabel=!0;const m={};let h=!1;e.verticesConfig.offset&&(m.offset=e.verticesConfig.offset,h=!0),e.verticesConfig.fontSize&&(m.fontSize=e.verticesConfig.fontSize,h=!0),e.verticesConfig.color&&(m.color=e.verticesConfig.color,h=!0),e.verticesConfig.anchorX&&(m.anchorX=e.verticesConfig.anchorX,h=!0),e.verticesConfig.anchorY&&(m.anchorY=e.verticesConfig.anchorY,h=!0),h&&(y.label=m),d.vertices=y,console.warn("🔧 Using JSXGraph vertices config:",y)}else d.vertices={withLabel:!0};console.warn("🔧 Creating polygon with config:",d);const u=r.create("polygon",l,d);return console.warn("🔧 Polygon created:",u),console.warn("🔧 Polygon vertices:",u.vertices),console.warn("🔧 Polygon vertices names:",u.vertices?u.vertices.map(y=>y.name):"no vertices"),console.warn("🔧 Polygon vertices labels:",u.vertices?u.vertices.map(y=>y.hasLabel?y.label:"no label"):"no vertices"),o&&r.on("down",()=>{s(e.id)}),u}else console.warn(`Cannot create polygon ${e.id}: some vertices are missing`,{vertices:e.vertices,resolvedVertices:l})}catch(l){console.error(`Failed to create polygon ${e.id}:`,l)}break;case"text":try{return console.warn(`🔍 Creating text ${e.id}:`,{id:e.id,type:e.type,hasPosition:"position"in e,position:e.position,positionX:e.position?.x,positionY:e.position?.y,hasContent:"content"in e,content:e.content,shapeKeys:Object.keys(e)}),r.create("text",[e.position.x,e.position.y,e.content],{color:e.color||"black",fontSize:e.fontSize??14,fixed:!0,visible:e.visible??!0})}catch(l){console.error(`Failed to create text ${e.id}:`,l)}break}return null}function Jt(r,e){if(Array.isArray(r)&&r.length>=2)return r;if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r)return[r.x,r.y];if("$ref"in r)try{if(e.objects&&e.objects[r.$ref]){const n=e.objects[r.$ref];if(n)return n}const t=e.objectsList.find(n=>n.id===r.$ref);if(t)return console.warn(`✅ Found referenced point ${r.$ref}:`,t),t;console.warn(`⚠️ Point reference ${r.$ref} not found in board.objectsList`)}catch(t){console.warn(`Failed to resolve point reference ${r.$ref}:`,t)}}return null}function Bl(r,e,t){if(Array.isArray(r)&&r.length>=2){if(t&&t.name){const n=e.create("point",r,{name:t.name});return console.warn(`🔧 Created point with name ${t.name} at`,r),n}return r}if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r){const n=[r.x,r.y];if(t&&t.name){const s=e.create("point",n,{name:t.name});return console.warn(`🔧 Created point with name ${t.name} at`,n),s}return n}if("$ref"in r)try{if(e.objects&&e.objects[r.$ref]){const s=e.objects[r.$ref];if(s)return t&&t.name&&s.setName&&(s.setName(t.name),console.warn(`🔧 Updated point ${r.$ref} name to ${t.name}`)),s}const n=e.objectsList.find(s=>s.id===r.$ref);if(n)return console.warn(`✅ Found referenced point ${r.$ref}:`,n),t&&t.name&&n.setName&&(n.setName(t.name),console.warn(`🔧 Updated point ${r.$ref} name to ${t.name}`)),n;console.warn(`⚠️ Point reference ${r.$ref} not found in board.objectsList`)}catch(n){console.warn(`Failed to resolve point reference ${r.$ref}:`,n)}}return null}function ln(r,e={}){const{padding:t=.2,margin:n=1,minSize:s=4}=e,o=[];if(r.forEach(w=>{switch(w.type){case"point":o.push(w.position);break;case"line":const P=ut(w.start,r),$=ut(w.end,r);P&&o.push(P),$&&o.push($);break;case"circle":const O=ut(w.center,r);if(O&&(o.push(O),w.radius!==void 0&&o.push({x:O.x+w.radius,y:O.y},{x:O.x-w.radius,y:O.y},{x:O.x,y:O.y+w.radius},{x:O.x,y:O.y-w.radius})),w.through){const M=ut(w.through,r);M&&o.push(M)}break;case"polygon":w.vertices.forEach(M=>{const G=ut(M,r);G&&o.push(G)});break;case"text":o.push(w.position);const Y=w.content.length*(w.fontSize||14)/20,q=(w.fontSize||14)/10;o.push({x:w.position.x+Y,y:w.position.y},{x:w.position.x-Y,y:w.position.y},{x:w.position.x,y:w.position.y+q},{x:w.position.x,y:w.position.y-q});break}}),o.length===0)return{boundingBox:[-s,s,s,-s],center:{x:0,y:0},width:s*2,height:s*2};const i=Math.min(...o.map(w=>w.x)),a=Math.max(...o.map(w=>w.x)),c=Math.min(...o.map(w=>w.y)),l=Math.max(...o.map(w=>w.y)),d=(i+a)/2,u=(c+l)/2;let y=Math.max(a-i,s),m=Math.max(l-c,s);const h=800/500,g=y/m;Math.abs(g-h)>.1&&(g>h?m=y/h:y=m*h);const p=y*(1+t)+n*2,x=m*(1+t)+n*2,C=d-p/2,S=u+x/2,E=d+p/2,_=u-x/2,j=[C,S,E,_];if(process.env.NODE_ENV==="development"){const P=o.map($=>({x:$.x,y:$.y,insideX:$.x>=C&&$.x<=E,insideY:$.y<=S&&$.y>=_,inside:$.x>=C&&$.x<=E&&$.y<=S&&$.y>=_})).filter($=>!$.inside);P.length>0&&console.warn("⚠️ 边界框验证警告: 有图形元素超出边界框",{boundingBox:j,outsidePoints:P.slice(0,5),totalOutside:P.length})}return{boundingBox:j,center:{x:d,y:u},width:p,height:x}}function ut(r,e=[]){if(typeof r=="object"&&r!==null){if("x"in r&&"y"in r)return{x:r.x,y:r.y};if("$ref"in r){const t=e.find(n=>n.id===r.$ref&&n.type==="point");if(t)return t.position}}return null}function Vl(r,e="Debug"){console.group(`🔍 ${e} - 边界框计算调试`);const t=[];if(r.forEach(s=>{switch(s.type){case"point":t.push({x:s.position.x,y:s.position.y,source:`point:${s.id}`});break;case"text":t.push({x:s.position.x,y:s.position.y,source:`text:${s.id}`});const o=s.content.length*(s.fontSize||14)/20,i=(s.fontSize||14)/10;t.push({x:s.position.x+o,y:s.position.y,source:`text:${s.id}:right`},{x:s.position.x-o,y:s.position.y,source:`text:${s.id}:left`},{x:s.position.x,y:s.position.y+i,source:`text:${s.id}:top`},{x:s.position.x,y:s.position.y-i,source:`text:${s.id}:bottom`});break;case"polygon":s.vertices.forEach((a,c)=>{const l=ut(a,r);l&&t.push({x:l.x,y:l.y,source:`polygon:${s.id}:vertex${c}`})});break}}),console.log("📊 收集到的坐标点:",t),t.length>0){const s=Math.min(...t.map(c=>c.x)),o=Math.max(...t.map(c=>c.x)),i=Math.min(...t.map(c=>c.y)),a=Math.max(...t.map(c=>c.y));console.log("📐 原始包围盒:",{minX:s,maxX:o,minY:i,maxY:a,width:o-s,height:a-i})}const n=ln(r,{padding:.3,margin:1,minSize:4});return console.log("🎯 自动边界框计算结果:",n),console.groupEnd(),n}const Sr=r=>{const{shapes:e,mode:t,onShapeChange:n,onSelectionChange:s,width:o=600,height:i=400,showGrid:a=!0,showAxis:c=!0,className:l="",boundingBox:d,autoBoundingBox:u=!0,boundingBoxOptions:y,animation:m,animationProgress:h,onAnimationChange:g,showAnimationControls:p}=r,x=b.useMemo(()=>{if(d)return d;if(u&&e.length>0)try{process.env.NODE_ENV==="development"&&Vl(e,"MathGraph Auto BoundingBox");const S=ln(e,y);return console.log("📐 Auto-calculated bounding box:"),console.log(" - BoundingBox:",S.boundingBox),console.log(" - Center:",S.center),console.log(" - Width:",S.width),console.log(" - Height:",S.height),console.log(" - Options used:",y),S.boundingBox}catch(S){return console.warn("Failed to calculate auto bounding box, using default:",S),[-10,10,10,-10]}return[-10,10,10,-10]},[d,u,e,y]),C=b.useMemo(()=>({width:typeof o=="number"?`${o}px`:o,height:typeof i=="number"?`${i}px`:i}),[o,i]);return f.jsx(Fl,{children:f.jsx("div",{className:`border border-gray-200 rounded-lg bg-white shadow-sm overflow-hidden ${l}`,style:C,"data-testid":"mathgraph",role:"application","aria-label":"数学绘图区域",children:f.jsx(io,{shapes:e,mode:t,onShapeChange:n,onSelectionChange:s,boundingBox:x,showGrid:a,showAxis:c,animation:m,animationProgress:h,onAnimationChange:g})})})},ao=({shapes:r,width:e,height:t,showGrid:n=!0,showAxis:s=!0,boundingBox:o,autoBoundingBox:i,onShapeChange:a,className:c="",animation:l,animationProgress:d,showAnimationControls:u,onAnimationChange:y})=>{const m=b.useRef(null),[h,g]=b.useState({width:600,height:400});b.useEffect(()=>{const x=()=>{if(m.current){const{clientWidth:S,clientHeight:E}=m.current;S>0&&E>0&&g({width:S,height:E})}};x(),window.addEventListener("resize",x);const C=new ResizeObserver(x);return m.current&&C.observe(m.current),()=>{window.removeEventListener("resize",x),C.disconnect()}},[]);const p={width:e?typeof e=="string"?e:`${e}px`:"100%",height:t?typeof t=="string"?t:`${t}px`:"100%"};return f.jsx("div",{ref:m,className:`mathcard-v2-graph ${c}`,style:p,children:f.jsx(Sr,{shapes:r,width:h.width,height:h.height,showGrid:n,showAxis:s,boundingBox:o,autoBoundingBox:i,onShapeChange:a,mode:"view","data-testid":"mathgraph",animation:l,animationProgress:d,showAnimationControls:u,onAnimationChange:y})})},cn=({config:r,onTransformChange:e,onTransformComplete:t,onError:n,layoutDensity:s,boardHeight:o,boardWidth:i,className:a=""})=>{const c=s??r.ui?.layoutDensity??"default",l=o??r.ui?.boardHeight??300,d=i??r.ui?.boardWidth??400,u=h=>{e?.(h)},y=()=>{t?.()},m=h=>{n?.(h)};return console.error("🔍 GeometryTransformContent: config =",{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,shapesAnimatedLength:r.shapes?.animated?.length,shapesStaticLength:r.shapes?.static?.length,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig,boardConfigKeys:r.boardConfig?Object.keys(r.boardConfig):[],boardConfigBoundingBox:r.boardConfig?.boundingBox,boardConfigOriginX:r.boardConfig?.originX,boardConfigOriginY:r.boardConfig?.originY,configKeys:Object.keys(r)}),f.jsx("div",{className:`mathcard-v2-geometry-transform ${a}`,style:{width:"100%",display:"flex",justifyContent:"center",alignItems:"center"},"data-testid":"geometry-transform",children:f.jsx(qs,{base:r.base,height:r.height,unit:r.unit,shapes:r.shapes,transform:r.transform,animation:r.animation,boardConfig:r.boardConfig,onTransformChange:u,onTransformComplete:y,onError:m,layoutDensity:c,boardHeight:l,boardWidth:d,enableKeyboardNavigation:!0,enableRigidityVerification:!0,autoCompleteThreshold:.95,theme:"light"})})},Wl=({headers:r,values:e,colors:t={}})=>{const{headerBg:n="#f1f5f9",valueBg:s="#ffffff",borderColor:o="#e2e8f0"}=t;return r.length!==e.length?(console.warn("PlaceValueChart: headers and values length mismatch"),null):f.jsxs("div",{className:"place-value-chart",style:{display:"inline-block",border:`1px solid ${o}`,borderRadius:"8px",overflow:"hidden",fontFamily:"system-ui, sans-serif",fontSize:"14px",lineHeight:"1.4"},children:[f.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${o}`},children:r.map((i,a)=>f.jsx("div",{style:{flex:1,padding:"8px 12px",backgroundColor:n,fontWeight:"600",textAlign:"center",borderRight:a<r.length-1?`1px solid ${o}`:"none",color:"#1e293b"},children:i},a))}),f.jsx("div",{style:{display:"flex"},children:e.map((i,a)=>f.jsx("div",{style:{flex:1,padding:"12px",backgroundColor:s,textAlign:"center",borderRight:a<e.length-1?`1px solid ${o}`:"none",color:"#0f172a",fontSize:"16px",fontWeight:"500"},children:i},a))})]})},lo=({content:r,onInteraction:e})=>{const t=(n,s)=>{if(n.enabled===!1)return null;const o=`${n.type}-${s}`,i=a=>{e?.(o,a)};switch(n.type){case"text":return f.jsx(so,{content:n.content,style:n.style,onInteraction:i},o);case"formula":const a=n;return f.jsx(oo,{parts:a.parts||[],displayMode:a.displayMode,style:n.style},o);case"graph":const c=n;return f.jsx(ao,{shapes:c.shapes||[],width:c.width,height:c.height,showGrid:c.showGrid,showAxis:c.showAxis,boundingBox:c.boardConfig?.boundingBox,autoBoundingBox:!c.boardConfig?.boundingBox,animation:c.animation,animationProgress:c.animationProgress,showAnimationControls:c.showAnimationControls,onAnimationChange:c.onAnimationChange},o);case"hundredGrid":const l=n;return f.jsx(Qs,{...l.props},o);case"placeValueChart":const d=n;return f.jsx(Wl,{...d.props},o);case"geometryTransform":const u=n;return console.log("🔍 ContentRenderer: geometryTransformBlock =",{metadata:u.metadata,config:u.metadata?.config,hasConfig:!!u.metadata?.config,configKeys:u.metadata?.config?Object.keys(u.metadata.config):[],configShapes:u.metadata?.config?.shapes,configShapesAnimatedLength:u.metadata?.config?.shapes?.animated?.length,configShapesStaticLength:u.metadata?.config?.shapes?.static?.length,configBase:u.metadata?.config?.base,configHeight:u.metadata?.config?.height,configUnit:u.metadata?.config?.unit,configTransform:u.metadata?.config?.transform}),f.jsx(cn,{config:u.metadata.config,onTransformChange:y=>i({type:"transformChange",progress:y}),onTransformComplete:()=>i({type:"transformComplete"}),onError:y=>i({type:"error",error:y})},o);default:return f.jsx("div",{onClick:()=>i({type:"click"}),children:n.content},o)}};return f.jsx(f.Fragment,{children:r.map(t)})},Re=({data:r,scene:e="question",layout:t={type:"card"},renderer:n={mode:"default"},theme:s="light",onContentInteraction:o,className:i="",children:a})=>{const c=eo(r,e),l={data:c,scene:e,layout:c.layout||t,renderer:c.renderer||n,theme:s,onContentInteraction:o},d=c.layout||t,u=(()=>{switch(d.type){case"grid":return ro;case"flow":return no;default:return to}})(),y=(()=>{const m={className:i,theme:s,"data-testid":"mathcard-v2-container"};switch(d.type){case"grid":return{...m,columns:d.columns||2,gap:d.gap||"16px",responsive:d.responsive!==!1};case"flow":return{...m,direction:d.direction||"vertical",gap:d.gap||"16px",wrap:d.wrap!==!1};default:return{...m,padding:d.padding||"24px",shadow:d.shadow!==!1,border:d.border!==!1}}})();return f.jsx(Ml.Provider,{value:l,children:f.jsx(u,{...y,children:a||f.jsx(lo,{content:c.content,layout:c.layout||t,onInteraction:o})})})};Re.CardLayout=to;Re.GridLayout=ro;Re.FlowLayout=no;Re.TextContent=so;Re.FormulaContent=oo;Re.GraphContent=ao;Re.GeometryTransformContent=cn;Re.ContentRenderer=lo;const co=r=>{const{ixlConfig:e,enableIXLStyle:t,isMobile:n}=r,s=b.useMemo(()=>e.label?e.label:{remember:"速记",review:"回顾",solve:"解答"}[e.type]||e.type,[e.label,e.type]),o=b.useMemo(()=>{if(e.tagColor)return e.tagColor;const d={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"};return d[e.type]||d.remember},[e.tagColor,e.type]),i=b.useMemo(()=>e.tagTextColor?e.tagTextColor:"var(--ixl-tag-text-color, #ffffff)",[e.tagTextColor]),a=b.useMemo(()=>{if(!t)return{};const d={backgroundColor:o,color:i,fontSize:"var(--ixl-tag-font-size, 14px)",fontWeight:"var(--ixl-tag-font-weight, 600)"};return n?Object.assign(d,{height:"var(--ixl-mobile-tag-height, 32px)",borderRadius:"var(--ixl-mobile-tag-border-radius, 8px 8px 0 0)",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",zIndex:1}):Object.assign(d,{width:"var(--ixl-tag-width, 40px)",borderRadius:"var(--ixl-tag-border-radius, 8px 0 0 8px)",height:"100%",position:"absolute",left:0,top:0,display:"flex",alignItems:"center",justifyContent:"center",writingMode:"vertical-rl",textOrientation:"mixed",transform:"rotate(0deg)"}),d},[t,o,i,n]),c=b.useMemo(()=>!t||n?{}:{paddingLeft:"calc(var(--ixl-tag-width, 40px) + var(--ixl-card-gap, 16px))"},[t,n]);return{ixlClassName:b.useMemo(()=>{if(!t)return"";const d=["ixl-styled"];return d.push(`ixl-type-${e.type}`),n?d.push("ixl-mobile-layout"):d.push("ixl-desktop-layout"),d.join(" ")},[t,e.type,n]),tagStyle:a,contentStyle:c,tagText:s,tagColor:o,tagTextColor:i}},ql=(r,e)=>{let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>{r(...n)},e)}},fo=(r={})=>{const e=typeof r=="number"?r:r.breakpoint||768,t=typeof r=="number"?!0:r.enabled!==!1,[n,s]=b.useState(()=>typeof window<"u"?window.innerWidth:1024),[o,i]=b.useState(()=>typeof window<"u"?window.innerWidth<e:!1),a=b.useRef(new Set),c=b.useCallback(()=>{if(typeof window>"u")return;const y=window.innerWidth,m=y<e;s(y),i(m),a.current.forEach(h=>{try{h()}catch(g){console.error("Error in resize listener:",g)}})},[e]),l=b.useCallback(ql(c,150),[c]);b.useEffect(()=>{if(!(!t||typeof window>"u"))return c(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l)}},[t,l,c]);const d=b.useCallback(y=>(a.current.add(y),()=>{a.current.delete(y)}),[]),u=b.useCallback(y=>{a.current.delete(y)},[]);return{isMobile:o,viewportWidth:n,addResizeListener:d,removeResizeListener:u}},xt=({cardProps:r,ixlConfig:e,enableIXLStyle:t=!0,wrapperMode:n="mathcard",mobileBreakpoint:s=768,className:o="",style:i,children:a,onResponsiveChange:c})=>{const l=fo(s),d=co({ixlConfig:e,enableIXLStyle:t,isMobile:l.isMobile});b.useEffect(()=>{c?.(l.isMobile)},[l.isMobile,c]);const u=b.useMemo(()=>{const h=["ixl-style-card-container"];return t&&h.push(d.ixlClassName),o&&h.push(o),l.isMobile?h.push("ixl-mobile"):h.push("ixl-desktop"),h.join(" ")},[t,d.ixlClassName,o,l.isMobile]),y=b.useMemo(()=>{const h={...i};return t&&!l.isMobile?{...h,paddingLeft:d.contentStyle.paddingLeft}:h},[t,l.isMobile,d.contentStyle,i]),m=b.useMemo(()=>{if(n!=="mathcard"||!r)return"";const h=[r.className||""];return t&&h.push("ixl-adjusted"),h.filter(Boolean).join(" ")},[n,r?.className,t]);return f.jsxs("div",{className:u,style:y,"data-testid":"ixl-style-card-container","data-ixl-type":e.type,"data-ixl-enabled":t,"data-responsive-mode":l.isMobile?"mobile":"desktop",children:[t&&e.showTag!==!1&&f.jsx("div",{className:"ixl-tag",style:d.tagStyle,"data-testid":"ixl-tag",children:f.jsx("span",{className:"ixl-tag-text",children:d.tagText})}),n==="mathcard"&&r?f.jsx(Re,{...r,className:m}):a]})};xt.displayName="IXLStyleCard";const Yl={remember:{type:"remember",label:"速记",showTag:!0},review:{type:"review",label:"回顾",showTag:!0},solve:{type:"solve",label:"解答",showTag:!0}},Hl={remember:"var(--ixl-color-remember, #5bc0de)",review:"var(--ixl-color-review, #a5c63b)",solve:"var(--ixl-color-solve, #f0ad4e)"},Kl={remember:"速记",review:"回顾",solve:"解答"},Xl=({grades:r,onGradeSelect:e,selectedGrade:t})=>f.jsxs("div",{className:"grade-navigation",children:[f.jsx("h2",{className:"grade-navigation__title",children:"选择年级"}),f.jsx("div",{className:"grade-navigation__grid",children:r.map(n=>f.jsxs("div",{className:`grade-card ${t===n.id?"grade-card--selected":""}`,style:{borderLeftColor:n.color},onClick:()=>e?.(n.id),children:[f.jsx("div",{className:"grade-card__level",children:n.level}),f.jsx("div",{className:"grade-card__name",children:n.name}),f.jsx("div",{className:"grade-card__description",children:n.description})]},n.id))})]}),uo=({abilities:r,width:e=400,height:t=400})=>{const n=()=>r.length===0?"":r.map(i=>{if(i.svgPoint)return`${i.svgPoint.x},${i.svgPoint.y}`;const a=Math.PI*2*r.indexOf(i)/r.length,c=i.score/i.maxScore*40+10,l=50+c*Math.sin(a),d=50-c*Math.cos(a);return`${l},${d}`}).join(" "),s=i=>{const a=Math.PI*2*i/Math.max(r.length,1),c=50+40*Math.sin(a),l=50-40*Math.cos(a);return{x2:c,y2:l}},o=i=>{const a=Math.PI*2*i/Math.max(r.length,1),c=50+45*Math.sin(a),l=50-45*Math.cos(a);let d="middle";return a>Math.PI*.25&&a<Math.PI*.75&&(d="start"),a>Math.PI*1.25&&a<Math.PI*1.75&&(d="end"),{x:c,y:l,textAnchor:d}};return f.jsxs("svg",{"data-testid":"radar-chart",width:e,height:t,viewBox:"0 0 100 100",className:"w-full h-full",preserveAspectRatio:"xMidYMid meet",children:[f.jsx("circle",{"data-testid":"center-point",cx:"50",cy:"50",r:"1",fill:"#4A90E2"}),r.map((i,a)=>{const{x2:c,y2:l}=s(a);return f.jsx("line",{"data-testid":"axis-line",x1:"50",y1:"50",x2:c,y2:l,stroke:"#E2E8F0",strokeWidth:"0.5"},`axis-${a}`)}),r.length>2&&f.jsx("polygon",{"data-testid":"radar-polygon",points:n(),fill:"rgba(74, 144, 226, 0.2)",stroke:"rgb(74, 144, 226)",strokeWidth:"1",fillRule:"evenodd"}),r.map((i,a)=>{let c,l;if(i.svgPoint)c=i.svgPoint.x,l=i.svgPoint.y;else{const d=Math.PI*2*a/r.length,u=i.score/i.maxScore*40+10;c=50+u*Math.sin(d),l=50-u*Math.cos(d)}return f.jsx("circle",{"data-testid":"data-point",cx:c,cy:l,r:"2",fill:i.progressBarColor==="bg-orange-400"?"#FBBF24":"#4A90E2"},`point-${i.name}`)}),r.map((i,a)=>{const{x:c,y:l,textAnchor:d}=o(a);return f.jsx("text",{x:c,y:l,textAnchor:d,fontSize:"5",fill:"#334155",className:"text-xs",children:i.name},`label-${i.name}`)})]})},Zn={overallRating:"优秀",generalRecommendation:"你的空间想象力和逻辑推理能力非常出色!若能进一步提升在复杂图形下的专注力,你将所向披靡。建议尝试我们‘专注力挑战’系列游戏。",abilities:[{name:"空间想象力",score:7.5,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:50,y:17.5},recommendation:"通过观察三维物体在不同角度的投影,或尝试构建复杂结构的游戏,能有效提升空间想象力。",recommendationLink:"#spatial-challenges"},{name:"逻辑推理",score:8,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:82,y:35},recommendation:"解决数独、迷宫或逻辑谜题,能够持续锻炼你的逻辑思维,尝试挑战更高难度的推理游戏。",recommendationLink:"#logic-puzzles"},{name:"图形辨识",score:9,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:85,y:65},recommendation:"你在这方面表现出色!可以尝试在更复杂、干扰因素更多的图形中进行辨识训练,保持敏锐。",recommendationLink:"#graphic-training"},{name:"专注力",score:7,maxScore:10,progressBarColor:"bg-orange-400",svgPoint:{x:50,y:80},recommendation:"在长时间的游戏中保持专注对你来说是一个挑战,建议尝试我们‘专注力挑战’系列游戏,逐渐延长专注时间。",recommendationLink:"#focus-challenges"},{name:"观察力",score:8.5,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:15,y:65},recommendation:"你的观察力非常敏锐,在细节发现上尤为突出。尝试在限时模式下进行观察力训练,提高反应速度。",recommendationLink:"#observation-drills"},{name:"抗压性",score:7.8,maxScore:10,progressBarColor:"bg-blue-500",svgPoint:{x:18,y:35},recommendation:"面对高压挑战时,保持冷静是关键。通过模拟竞赛或限时任务来提升抗压能力,逐步适应压力。",recommendationLink:"#stress-games"}]};class Jl{static API_BASE_URL="/api/radar-ability";static async fetchRadarAbilityData(){try{return process.env.NODE_ENV==="test"?(await new Promise(e=>setTimeout(e,100)),Zn):(await le.get(`${this.API_BASE_URL}/assessment`)).data}catch(e){if(console.error("Failed to fetch radar ability data:",e),process.env.NODE_ENV==="test")throw new Error("获取能力评估数据失败");return Zn}}static async submitFeedback(e){try{await le.post(`${this.API_BASE_URL}/feedback`,e)}catch(t){throw console.error("Failed to submit feedback:",t),new Error("提交反馈失败")}}}const Zl=Pt.create((r,e)=>({data:null,loading:!1,error:null,fetchData:async()=>{if(!e().loading){r({loading:!0,error:null});try{const t=await Jl.fetchRadarAbilityData();r({data:t,loading:!1})}catch(t){const n=t instanceof Error?t.message:"获取数据失败";r({error:n,loading:!1})}}},setData:t=>{r({data:t,error:null,loading:!1})},setError:t=>{r({error:t,loading:!1})},reset:()=>{r({data:null,loading:!1,error:null})}})),mo=({ability:r})=>{const e=r.score/r.maxScore*100;return f.jsxs("div",{className:"ability-progress-bar-item","data-ability":r.name,"data-testid":"progress-bar-container",children:[f.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[f.jsx("span",{className:"text-gray-700 font-medium",children:r.name}),f.jsxs("span",{className:"text-gray-600",children:[r.score,"/",r.maxScore]})]}),f.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5","data-testid":"progress-bar-outer",children:f.jsx("div",{className:`${r.progressBarColor} h-2.5 rounded-full transition-all duration-300`,style:{width:`${e}%`},"data-testid":"progress-bar-inner",role:"progressbar","aria-valuenow":r.score,"aria-valuemin":0,"aria-valuemax":r.maxScore,"aria-label":`${r.name} progress: ${r.score} out of ${r.maxScore}`})})]})},ho=({generalRecommendation:r})=>f.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4","data-testid":"advice-panel",role:"region","aria-label":"个性化建议",children:f.jsxs("div",{className:"flex items-start",children:[f.jsx("div",{className:"flex-shrink-0",children:f.jsx("i",{className:"material-icons text-blue-500","data-testid":"lightbulb-icon","aria-hidden":"true",children:"lightbulb"})}),f.jsxs("div",{className:"ml-3",children:[f.jsx("h3",{className:"text-md font-semibold text-blue-800","aria-level":3,children:"个性化建议"}),f.jsx("p",{className:"text-sm text-blue-700 mt-1","data-testid":"recommendation-text",children:r})]})]})}),go=({ability:r,customLinkTexts:e={}})=>{const t=n=>{const s={空间想象力:"探索空间挑战",逻辑推理:"深入逻辑谜题",图形辨识:"精进图形训练",专注力:"挑战专注极限",观察力:"提升观察速度",抗压性:"磨砺抗压意志"};return e[n]||s[n]||"开始挑战"};return f.jsx(ke.Card,{className:"recommendation-card w-full max-w-sm hover:shadow-lg transition-all duration-300","data-ability":r.name,"data-testid":"recommendation-card",isHoverable:!0,isPressable:!0,children:f.jsx(ke.CardBody,{className:"p-5",children:f.jsxs("div",{className:"flex flex-col gap-3",children:[f.jsxs("h4",{className:"text-lg font-semibold text-foreground","aria-level":4,children:[r.name,": 专项提高"]}),f.jsx("p",{className:"text-sm text-default-600 leading-relaxed","data-testid":"recommendation-description",children:r.recommendation}),f.jsx(ke.Button,{as:"a",href:r.recommendationLink,className:"mt-2 w-fit",size:"sm",variant:"flat",color:"primary",endContent:f.jsx(Gr.ArrowRight,{className:"w-4 h-4"}),"data-testid":"recommendation-link","aria-label":`前往${r.name}专项提高页面`,children:t(r.name)})]})})})},Ql="_dashboardLayout_10wqn_5",ec="_upperSection_10wqn_19",tc="_lowerSection_10wqn_33",rc="_radarChartArea_10wqn_51",Zt={dashboardLayout:Ql,upperSection:ec,lowerSection:tc,radarChartArea:rc},nc=()=>{const{data:r,loading:e,error:t,fetchData:n}=Zl();return b.useEffect(()=>{n()},[n]),e?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 flex items-center justify-center","data-testid":"loading-spinner",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"}),f.jsx("span",{className:"ml-3 text-gray-600",children:"加载中..."})]}):t?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"alert","aria-live":"assertive",children:[f.jsx("div",{className:"text-red-500 mb-4",children:f.jsx("i",{className:"material-icons text-4xl","aria-hidden":"true",children:"error_outline"})}),f.jsx("h3",{className:"text-lg font-semibold text-gray-800 mb-2",children:"加载失败"}),f.jsx("p",{className:"text-gray-600 mb-4",children:t}),f.jsx("button",{onClick:n,className:"bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2","aria-label":"重试加载数据",children:"重试"})]}):r?f.jsxs("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 animate-fade-in","data-component":"AbilityAssessmentDashboard",role:"main","aria-label":"能力评估雷达图展示",children:[f.jsxs("div",{className:"flex justify-between items-center mb-6",children:[f.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"能力评估雷达图"}),f.jsxs("span",{className:"bg-blue-100 text-blue-800 text-sm font-semibold px-2.5 py-0.5 rounded-full","aria-label":`综合评级: ${r.overallRating}`,children:["综合评级: ",r.overallRating]})]}),f.jsxs("div",{className:Zt.dashboardLayout,children:[f.jsxs("div",{className:Zt.upperSection,children:[f.jsx("div",{className:Zt.radarChartArea,children:f.jsx(uo,{abilities:r.abilities})}),f.jsx("div",{className:"space-y-4 flex flex-col justify-around py-2",children:r.abilities.map(s=>f.jsx(mo,{ability:s},s.name))})]}),f.jsxs("div",{className:Zt.lowerSection,children:[f.jsx(ho,{generalRecommendation:r.generalRecommendation}),f.jsx("h3",{className:"text-lg font-bold text-gray-800 mb-4 mt-6",children:"专项提升建议"}),f.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:r.abilities.map(s=>f.jsx(go,{ability:s},s.name))})]})]})]}):f.jsx("div",{className:"card max-w-4xl mx-auto p-6 md:p-8 text-center",role:"status","aria-live":"polite",children:f.jsx("p",{className:"text-gray-600",children:"暂无数据"})})},jt={"Arithmetic and Algebra":"🔢","Graphics and Geometry":"📐","Probability and Statistics":"📊",Default:"📚"},sc={mastered:"已掌握",proficient:"熟练",familiar:"熟悉",attempted:"已尝试","not-started":"未开始"},oc={mastered:"#10b981",proficient:"#3b82f6",familiar:"#f59e0b",attempted:"#8b5cf6","not-started":"#6b7280"},Vt={id:"user-001",name:"小明",level:5,avatar:"https://i.pravatar.cc/40?u=student1",logIn:!0,badges:["🏆","🏅","🌟"]},ic=[{id:"g3",label:"三年级",status:"new",onClick:()=>console.log("三年级 clicked")},{id:"g4",label:"四年级",status:"2%",onClick:()=>console.log("四年级 clicked")},{id:"g5",label:"五年级",status:"进行中",onClick:()=>console.log("五年级 clicked")},{id:"g6",label:"六年级",status:"new",onClick:()=>console.log("六年级 clicked")},{id:"g7",label:"七年级",status:"new",onClick:()=>console.log("七年级 clicked")},{id:"g8",label:"八年级",status:"new",onClick:()=>console.log("八年级 clicked")},{id:"alg_topic",label:"代数专题",status:"new",onClick:()=>console.log("代数专题 clicked")},{id:"calc_topic",label:"计算专题",status:"new",onClick:()=>console.log("计算专题 clicked")},{id:"geo_topic",label:"几何专题",status:"new",onClick:()=>console.log("几何专题 clicked")},{id:"olym_topic",label:"奥数专题",status:"new",onClick:()=>console.log("奥数专题 clicked")}],ac="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTAwMSIsIm5hbWUiOiLlsI_mmI4iLCJsZXZlbCI6NSwiYXZhdGFyIjoiaHR0cHM6Ly9pLnByYXZhdGFyLmNjLzQwP3U9c3R1ZGVudDEiLCJiYWRnZXMiOlsi8J-SoiIsIvCfjZUiLCLwn5KbIl0sImlhdCI6MTY5MTYwMDAwMCwiZXhwIjoxNzIzMTM2MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",de={id:"g5",title:"小学数学五年级",level:5,subject:"数学",units:[{id:"unit_1",title:"小数乘法",description:"学习小数乘法的计算方法及应用",estimatedDuration:"3周",totalLessons:10,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit1_lesson1",title:"小数乘整数",duration:40,knowledgeItems:[{id:"unit1_lesson1_k1",title:"小数乘整数的意义",description:"理解小数乘整数的意义与整数乘法相同",progress:0,contentUrl:""},{id:"unit1_lesson1_k2",title:"小数乘整数的计算方法",description:"掌握小数乘整数的计算方法:先按整数乘法计算,再看因数中有几位小数,就从积的右边起数出几位点上小数点",progress:0,contentUrl:""}]},{id:"unit1_lesson2",title:"小数乘小数",duration:40,knowledgeItems:[{id:"unit1_lesson2_k1",title:"小数乘小数的计算方法",description:"掌握小数乘小数的计算方法:先按整数乘法算出积,再给积点上小数点",progress:0,contentUrl:""},{id:"unit1_lesson2_k2",title:"积的小数位数确定",description:"理解积的小数位数等于两个因数的小数位数之和",progress:0,contentUrl:""}]},{id:"unit1_lesson3",title:"积的近似数",duration:40,knowledgeItems:[{id:"unit1_lesson3_k1",title:'用"四舍五入"法求积的近似数',description:'掌握用"四舍五入"法求积的近似数的方法',progress:0,contentUrl:""}]},{id:"unit1_lesson4",title:"整数乘法运算定律推广到小数",duration:40,knowledgeItems:[{id:"unit1_lesson4_k1",title:"乘法运算定律在小数中的适用性",description:"理解整数乘法运算定律对于小数乘法同样适用",progress:0,contentUrl:""},{id:"unit1_lesson4_k2",title:"运用运算定律进行简便计算",description:"能运用乘法运算定律进行小数乘法的简便计算",progress:0,contentUrl:""}]},{id:"unit1_lesson5",title:"解决问题",duration:40,knowledgeItems:[{id:"unit1_lesson5_k1",title:"用小数乘法解决实际问题",description:"能运用小数乘法解决购物、面积计算等实际问题",progress:0,contentUrl:""}]}]},{id:"unit_2",title:"小数除法",description:"学习小数除法的计算方法及应用",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit2_lesson1",title:"小数除以整数",duration:40,knowledgeItems:[{id:"unit2_lesson1_k1",title:"小数除以整数的计算方法",description:"掌握小数除以整数的计算方法:按照整数除法的方法计算,商的小数点要与被除数的小数点对齐",progress:0,contentUrl:""}]},{id:"unit2_lesson2",title:"一个数除以小数",duration:40,knowledgeItems:[{id:"unit2_lesson2_k1",title:"除数是小数的除法计算方法",description:"掌握除数是小数的除法计算方法:利用商不变的性质,将除数转化为整数",progress:0,contentUrl:""}]},{id:"unit2_lesson3",title:"商的近似数",duration:40,knowledgeItems:[{id:"unit2_lesson3_k1",title:'用"四舍五入"法求商的近似数',description:'掌握用"四舍五入"法求商的近似数的方法',progress:0,contentUrl:""}]},{id:"unit2_lesson4",title:"循环小数",duration:40,knowledgeItems:[{id:"unit2_lesson4_k1",title:"循环小数的概念",description:"理解循环小数的概念,认识循环节",progress:0,contentUrl:""},{id:"unit2_lesson4_k2",title:"循环小数的表示方法",description:"掌握循环小数的简便表示方法",progress:0,contentUrl:""}]},{id:"unit2_lesson5",title:"用计算器探索规律",duration:40,knowledgeItems:[{id:"unit2_lesson5_k1",title:"用计算器计算小数除法",description:"会用计算器计算较复杂的小数除法",progress:0,contentUrl:""},{id:"unit2_lesson5_k2",title:"发现商的变化规律",description:"能借助计算器发现商的变化规律",progress:0,contentUrl:""}]},{id:"unit2_lesson6",title:"解决问题",duration:40,knowledgeItems:[{id:"unit2_lesson6_k1",title:"用小数除法解决实际问题",description:"能运用小数除法解决购物、分配等实际问题",progress:0,contentUrl:""}]}]},{id:"unit_3",title:"简易方程",description:"学习用字母表示数和解简易方程",estimatedDuration:"4周",totalLessons:14,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit3_lesson1",title:"用字母表示数",duration:40,knowledgeItems:[{id:"unit3_lesson1_k1",title:"用字母表示数",description:"初步理解用字母表示数的意义和作用",progress:0,contentUrl:""},{id:"unit3_lesson1_k2",title:"用字母表示运算定律和计算公式",description:"会用字母表示运算定律和计算公式",progress:0,contentUrl:""}]},{id:"unit3_lesson2",title:"方程的意义",duration:40,knowledgeItems:[{id:"unit3_lesson2_k1",title:"方程的概念",description:"理解方程的意义,知道方程与等式的区别和联系",progress:0,contentUrl:""}]},{id:"unit3_lesson3",title:"等式的性质",duration:40,knowledgeItems:[{id:"unit3_lesson3_k1",title:"等式的性质1",description:"理解等式的性质1:等式两边加上或减去同一个数,左右两边仍然相等",progress:0,contentUrl:""},{id:"unit3_lesson3_k2",title:"等式的性质2",description:"理解等式的性质2:等式两边乘同一个数,或除以同一个不为0的数,左右两边仍然相等",progress:0,contentUrl:""}]},{id:"unit3_lesson4",title:"解简易方程",duration:40,knowledgeItems:[{id:"unit3_lesson4_k1",title:"利用等式的性质解方程",description:"会利用等式的性质解形如x±a=b、ax=b、x÷a=b、a-x=b、a÷x=b的方程",progress:0,contentUrl:""}]},{id:"unit3_lesson5",title:"实际问题与方程",duration:40,knowledgeItems:[{id:"unit3_lesson5_k1",title:"列方程解决实际问题",description:"初步学会列方程解决一些简单的实际问题",progress:0,contentUrl:""}]}]},{id:"unit_4",title:"多边形的面积",description:"学习平行四边形、三角形、梯形和组合图形的面积计算",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Graphics and Geometry",lessons:[{id:"unit4_lesson1",title:"平行四边形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson1_k1",title:"平行四边形面积公式的推导",description:"通过割补法理解平行四边形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson1_k2",title:"平行四边形面积的计算",description:"掌握平行四边形面积计算公式:S=ah,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson2",title:"三角形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson2_k1",title:"三角形面积公式的推导",description:"通过拼摆法理解三角形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson2_k2",title:"三角形面积的计算",description:"掌握三角形面积计算公式:S=ah÷2,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson3",title:"梯形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson3_k1",title:"梯形面积公式的推导",description:"通过拼摆法理解梯形面积公式的推导过程",progress:0,contentUrl:""},{id:"unit4_lesson3_k2",title:"梯形面积的计算",description:"掌握梯形面积计算公式:S=(a+b)h÷2,并能正确运用",progress:0,contentUrl:""}]},{id:"unit4_lesson4",title:"组合图形的面积",duration:40,knowledgeItems:[{id:"unit4_lesson4_k1",title:"认识组合图形",description:"认识组合图形,会把组合图形分解成已学过的平面图形",progress:0,contentUrl:""},{id:"unit4_lesson4_k2",title:"计算组合图形的面积",description:"掌握计算组合图形面积的多种方法",progress:0,contentUrl:""}]}]},{id:"unit_5",title:"因数与倍数",description:"学习因数、倍数、质数、合数等概念",estimatedDuration:"3周",totalLessons:10,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit5_lesson1",title:"因数和倍数",duration:40,knowledgeItems:[{id:"unit5_lesson1_k1",title:"因数和倍数的意义",description:"理解因数和倍数的意义,掌握找一个数的因数和倍数的方法",progress:0,contentUrl:""},{id:"unit5_lesson1_k2",title:"因数和倍数的特征",description:"了解一个数的因数的个数是有限的,倍数的个数是无限的",progress:0,contentUrl:""}]},{id:"unit5_lesson2",title:"2、5、3的倍数的特征",duration:40,knowledgeItems:[{id:"unit5_lesson2_k1",title:"2、5的倍数的特征",description:"掌握2、5的倍数的特征,理解奇数和偶数的意义",progress:0,contentUrl:""},{id:"unit5_lesson2_k2",title:"3的倍数的特征",description:"掌握3的倍数的特征,能判断一个数是不是3的倍数",progress:0,contentUrl:""}]},{id:"unit5_lesson3",title:"质数和合数",duration:40,knowledgeItems:[{id:"unit5_lesson3_k1",title:"质数和合数的意义",description:"理解质数和合数的意义,能判断一个数是质数还是合数",progress:0,contentUrl:""},{id:"unit5_lesson3_k2",title:"制作100以内的质数表",description:"会制作100以内的质数表,熟记20以内的质数",progress:0,contentUrl:""}]}]},{id:"unit_6",title:"长方体和正方体",description:"学习长方体和正方体的特征、表面积和体积计算",estimatedDuration:"4周",totalLessons:14,moduleCategory:"Graphics and Geometry",lessons:[{id:"unit6_lesson1",title:"长方体和正方体的认识",duration:40,knowledgeItems:[{id:"unit6_lesson1_k1",title:"长方体的特征",description:"认识长方体的特征,了解长方体的长、宽、高",progress:0,contentUrl:""},{id:"unit6_lesson1_k2",title:"正方体的特征",description:"认识正方体的特征,理解正方体是特殊的长方体",progress:0,contentUrl:""}]},{id:"unit6_lesson2",title:"长方体和正方体的表面积",duration:40,knowledgeItems:[{id:"unit6_lesson2_k1",title:"表面积的意义",description:"理解表面积的意义,掌握长方体和正方体表面积的计算方法",progress:0,contentUrl:""},{id:"unit6_lesson2_k2",title:"表面积的实际应用",description:"能运用表面积知识解决一些实际问题",progress:0,contentUrl:""}]},{id:"unit6_lesson3",title:"长方体和正方体的体积",duration:40,knowledgeItems:[{id:"unit6_lesson3_k1",title:"体积和体积单位",description:"理解体积的意义,认识常用的体积单位",progress:0,contentUrl:""},{id:"unit6_lesson3_k2",title:"长方体和正方体体积的计算",description:"掌握长方体和正方体体积的计算公式",progress:0,contentUrl:""},{id:"unit6_lesson3_k3",title:"体积单位间的进率",description:"掌握体积单位之间的进率和换算",progress:0,contentUrl:""}]},{id:"unit6_lesson4",title:"容积和容积单位",duration:40,knowledgeItems:[{id:"unit6_lesson4_k1",title:"容积和容积单位",description:"理解容积的意义,认识常用的容积单位",progress:0,contentUrl:""},{id:"unit6_lesson4_k2",title:"容积和体积的关系",description:"掌握容积和体积之间的关系",progress:0,contentUrl:""}]}]},{id:"unit_7",title:"分数的意义和性质",description:"学习分数的意义、性质和约分、通分等方法",estimatedDuration:"4周",totalLessons:16,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit7_lesson1",title:"分数的意义",duration:40,knowledgeItems:[{id:"unit7_lesson1_k1",title:"分数的产生和意义",description:"理解分数的产生和意义,明确分数与除法的关系",progress:0,contentUrl:""},{id:"unit7_lesson1_k2",title:"分数单位",description:"认识分数单位,能说出一个分数中有几个这样的分数单位",progress:0,contentUrl:""}]},{id:"unit7_lesson2",title:"分数与除法",duration:40,knowledgeItems:[{id:"unit7_lesson2_k1",title:"分数与除法的关系",description:"理解分数与除法的关系,会用分数表示两个数相除的商",progress:0,contentUrl:""}]},{id:"unit7_lesson3",title:"真分数和假分数",duration:40,knowledgeItems:[{id:"unit7_lesson3_k1",title:"真分数和假分数的意义",description:"理解真分数和假分数的意义和特征",progress:0,contentUrl:""},{id:"unit7_lesson3_k2",title:"带分数",description:"认识带分数,会进行假分数与整数、带分数的互化",progress:0,contentUrl:""}]},{id:"unit7_lesson4",title:"分数的基本性质",duration:40,knowledgeItems:[{id:"unit7_lesson4_k1",title:"分数的基本性质",description:"理解分数的基本性质,能运用分数的基本性质进行分数的变形",progress:0,contentUrl:""}]},{id:"unit7_lesson5",title:"约分",duration:40,knowledgeItems:[{id:"unit7_lesson5_k1",title:"最大公因数",description:"理解公因数和最大公因数的意义,掌握求两个数的最大公因数的方法",progress:0,contentUrl:""},{id:"unit7_lesson5_k2",title:"约分的方法",description:"掌握约分的方法,能正确地进行约分",progress:0,contentUrl:""}]},{id:"unit7_lesson6",title:"通分",duration:40,knowledgeItems:[{id:"unit7_lesson6_k1",title:"最小公倍数",description:"理解公倍数和最小公倍数的意义,掌握求两个数的最小公倍数的方法",progress:0,contentUrl:""},{id:"unit7_lesson6_k2",title:"通分的方法",description:"掌握通分的方法,能正确地进行通分",progress:0,contentUrl:""}]},{id:"unit7_lesson7",title:"分数和小数的互化",duration:40,knowledgeItems:[{id:"unit7_lesson7_k1",title:"分数化成小数",description:"掌握分数化成小数的方法",progress:0,contentUrl:""},{id:"unit7_lesson7_k2",title:"小数化成分数",description:"掌握小数化成分数的方法",progress:0,contentUrl:""}]}]},{id:"unit_8",title:"分数的加法和减法",description:"学习同分母分数、异分母分数的加法和减法",estimatedDuration:"3周",totalLessons:12,moduleCategory:"Arithmetic and Algebra",lessons:[{id:"unit8_lesson1",title:"同分母分数加、减法",duration:40,knowledgeItems:[{id:"unit8_lesson1_k1",title:"同分母分数加法的计算方法",description:"掌握同分母分数加法的计算方法",progress:0,contentUrl:""},{id:"unit8_lesson1_k2",title:"同分母分数减法的计算方法",description:"掌握同分母分数减法的计算方法",progress:0,contentUrl:""}]},{id:"unit8_lesson2",title:"异分母分数加、减法",duration:40,knowledgeItems:[{id:"unit8_lesson2_k1",title:"异分母分数加法的计算方法",description:"掌握异分母分数加法的计算方法:先通分,然后按照同分母分数加法进行计算",progress:0,contentUrl:""},{id:"unit8_lesson2_k2",title:"异分母分数减法的计算方法",description:"掌握异分母分数减法的计算方法:先通分,然后按照同分母分数减法进行计算",progress:0,contentUrl:""}]},{id:"unit8_lesson3",title:"分数加减混合运算",duration:40,knowledgeItems:[{id:"unit8_lesson3_k1",title:"分数加减混合运算的顺序",description:"掌握分数加减混合运算的运算顺序",progress:0,contentUrl:""},{id:"unit8_lesson3_k2",title:"整数加法运算定律推广到分数加法",description:"理解整数加法运算定律对于分数加法同样适用,能运用运算定律进行简便计算",progress:0,contentUrl:""}]}]},{id:"unit_9",title:"折线统计图",description:"学习单式折线统计图和复式折线统计图的认识和制作",estimatedDuration:"2周",totalLessons:6,moduleCategory:"Probability and Statistics",lessons:[{id:"unit9_lesson1",title:"单式折线统计图",duration:40,knowledgeItems:[{id:"unit9_lesson1_k1",title:"单式折线统计图的特点",description:"认识单式折线统计图,了解其特点和作用",progress:0,contentUrl:""},{id:"unit9_lesson1_k2",title:"绘制单式折线统计图",description:"能根据数据绘制单式折线统计图",progress:0,contentUrl:""}]},{id:"unit9_lesson2",title:"复式折线统计图",duration:40,knowledgeItems:[{id:"unit9_lesson2_k1",title:"复式折线统计图的特点",description:"认识复式折线统计图,了解其特点和作用",progress:0,contentUrl:""},{id:"unit9_lesson2_k2",title:"绘制复式折线统计图",description:"能根据数据绘制复式折线统计图",progress:0,contentUrl:""}]},{id:"unit9_lesson3",title:"数据分析",duration:40,knowledgeItems:[{id:"unit9_lesson3_k1",title:"根据统计图进行数据分析",description:"能根据折线统计图进行简单的数据分析,作出合理的判断和预测",progress:0,contentUrl:""}]}]}]},lc=ic,cc=Vt;class dc{baseURL;token;constructor(e="/api/v1",t=ac){this.baseURL=e,this.token=t}getAuthHeaders(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async fetchWithAuth(e,t={}){const n=await fetch(e,{...t,headers:{...this.getAuthHeaders(),...t.headers}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return n}async getCourseData(e){return(await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}`)).json()}async getUserGradeUnitsNav(e){const t=e?`${this.baseURL}/content/grades/${encodeURIComponent(e)}/units/nav`:`${this.baseURL}/content/grades/current/units/nav`;return(await this.fetchWithAuth(t)).json()}async getUnitProgress(e,t){const n=t?`${this.baseURL}/content/courses/${e}/units/${t}/progress`:`${this.baseURL}/content/courses/${e}/progress`;return(await this.fetchWithAuth(n)).json()}async batchUpdateLessonProgress(e,t){return(await this.fetchWithAuth(`${this.baseURL}/content/units/${e}/progress/batch`,{method:"POST",body:JSON.stringify(t)})).json()}async updateLessonProgress(e,t,n,s){await this.fetchWithAuth(`${this.baseURL}/content/courses/${e}/units/${t}/lessons/${n}/progress`,{method:"POST",body:JSON.stringify({status:s})})}setToken(e){this.token=e}getToken(){return this.token}}const Qt=new dc;class Ye extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="DataSourceError"}}class fc{config;constructor(e){this.config={enableCaching:!1,cacheTTL:3e5,timeout:15e3,retryCount:3,retryDelay:1e3,...e},Qt.setToken(this.config.token)}async getUserGradeUnitsNav(e,t){try{return console.log(`[ApiDataSource] 获取年级单元导航数据: gradeId=${e}, userId=${t}`),await this.withRetry(()=>Qt.getUserGradeUnitsNav(e))}catch(n){throw console.error("[ApiDataSource] 获取年级单元导航数据失败:",n),new Ye(`获取年级单元导航数据失败: ${n instanceof Error?n.message:"未知错误"}`,"GET_USER_GRADE_UNITS_NAV_FAILED",n instanceof Error?n:void 0)}}async getUserProfile(e){try{return console.log(`[ApiDataSource] 获取用户个人信息: userId=${e}`),{id:e,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}}catch(t){throw console.error("[ApiDataSource] 获取用户个人信息失败:",t),new Ye(`获取用户个人信息失败: ${t instanceof Error?t.message:"未知错误"}`,"GET_USER_PROFILE_FAILED",t instanceof Error?t:void 0)}}async getExploreMenu(){try{return console.log("[ApiDataSource] 获取探索菜单数据"),[{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}]}catch(e){throw console.error("[ApiDataSource] 获取探索菜单数据失败:",e),new Ye(`获取探索菜单数据失败: ${e instanceof Error?e.message:"未知错误"}`,"GET_EXPLORE_MENU_FAILED",e instanceof Error?e:void 0)}}async updateLessonProgress(e){try{console.log("[ApiDataSource] 更新课时进度:",e),await this.withRetry(()=>Qt.updateLessonProgress(e.courseId,e.unitId,e.lessonId,e.status))}catch(t){throw console.error("[ApiDataSource] 更新课时进度失败:",t),new Ye(`更新课时进度失败: ${t instanceof Error?t.message:"未知错误"}`,"UPDATE_LESSON_PROGRESS_FAILED",t instanceof Error?t:void 0)}}async batchUpdateLessonProgress(e,t){try{return console.log(`[ApiDataSource] 批量更新课时进度: unitId=${e}`,t),await this.withRetry(()=>Qt.batchUpdateLessonProgress(e,t))}catch(n){throw console.error("[ApiDataSource] 批量更新课时进度失败:",n),new Ye(`批量更新课时进度失败: ${n instanceof Error?n.message:"未知错误"}`,"BATCH_UPDATE_LESSON_PROGRESS_FAILED",n instanceof Error?n:void 0)}}async withRetry(e){let t;for(let n=1;n<=this.config.retryCount;n++)try{return await e()}catch(s){t=s instanceof Error?s:new Error(String(s)),n<this.config.retryCount&&(console.warn(`[ApiDataSource] 请求失败,第${n}次重试...`,t.message),await this.delay(this.config.retryDelay))}throw t}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}}class uc{config;constructor(e){this.config={delay:500,simulateError:!1,errorProbability:.1,...e}}async getUserGradeUnitsNav(e,t){if(console.log(`[MockDataSource] 开始获取年级单元导航数据: gradeId=${e}, userId=${t}`),await this.simulateDelay(),this.shouldSimulateError())throw console.log(`[MockDataSource] 模拟错误: gradeId=${e}, userId=${t}`),new Ye("模拟数据源:获取年级单元导航数据失败","MOCK_GET_USER_GRADE_UNITS_NAV_FAILED");return console.log(`[MockDataSource] 成功获取年级单元导航数据: gradeId=${e}, userId=${t}`),{userId:t,courseId:e,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:de.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:de.units.map((s,o)=>({unitId:s.id,title:s.title,description:s.description,moduleCategory:s.moduleCategory,estimatedDuration:s.estimatedDuration,totalLessons:s.lessons.length,completedLessons:o<2?Math.floor(s.lessons.length*.5):0,progressPercentage:o<2?50:0,status:o<2?"in-progress":"not-started",lastAccessed:o<2?new Date().toISOString():void 0,isActive:o===0,route:`/math/grade-5/unit/${s.id}`,icon:jt[s.moduleCategory]||jt.Default}))}}async getUserProfile(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new Ye("模拟数据源:获取用户个人信息失败","MOCK_GET_USER_PROFILE_FAILED");return console.log(`[MockDataSource] 获取用户个人信息: userId=${e}`),{id:e,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}}async getExploreMenu(){if(await this.simulateDelay(),this.shouldSimulateError())throw new Ye("模拟数据源:获取探索菜单数据失败","MOCK_GET_EXPLORE_MENU_FAILED");return console.log("[MockDataSource] 获取探索菜单数据"),[{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}]}async updateLessonProgress(e){if(await this.simulateDelay(),this.shouldSimulateError())throw new Ye("模拟数据源:更新课时进度失败","MOCK_UPDATE_LESSON_PROGRESS_FAILED");console.log("[MockDataSource] 更新课时进度:",e),console.log(`课时 ${e.lessonId} 状态更新为: ${e.status}`)}async batchUpdateLessonProgress(e,t){if(await this.simulateDelay(),this.shouldSimulateError())throw new Ye("模拟数据源:批量更新课时进度失败","MOCK_BATCH_UPDATE_LESSON_PROGRESS_FAILED");return console.log(`[MockDataSource] 批量更新课时进度: unitId=${e}`,t),{success:!0,results:t.map(s=>({lessonId:s.lessonId,success:!0,status:s.status}))}}async simulateDelay(){this.config.delay&&this.config.delay>0&&await new Promise(e=>setTimeout(e,this.config.delay))}shouldSimulateError(){return this.config.simulateError?Math.random()<(this.config.errorProbability||.1):!1}getConfig(){return{...this.config}}getCourseData(){return de}getLessonsData(){const e={};return de.units.forEach(t=>{e[t.id]=t.lessons.map(n=>({id:n.id,title:n.title,duration:n.duration,knowledgeItems:n.knowledgeItems.map(s=>({...s,progress:0}))}))}),e}}class mc{static instances=new Map;static createDataSource(e){const{type:t,config:n,customDataSourceClass:s}=e,o=this.getInstanceKey(t,n);if(this.instances.has(o))return this.instances.get(o);let i;switch(t){case"api":i=new fc(n);break;case"mock":i=new uc(n);break;case"custom":if(!s)throw new Error("自定义数据源类型需要提供 customDataSourceClass 参数");i=new s(n);break;default:throw new Error(`不支持的数据源类型: ${t}`)}return this.instances.set(o,i),console.log(`[DataSourceFactory] 创建数据源: type=${t}, name=${n.name}`),i}static createApiDataSource(e){return this.createDataSource({type:"api",config:e})}static createMockDataSource(e={}){return this.createDataSource({type:"mock",config:{name:"MockDataSource",...e}})}static createDefaultDataSource(){const e=typeof window<"u";let t=!1,n=!1,s=!1;try{typeof process<"u"&&process.env?(t=process.env.NODE_ENV==="development",n=process.env.NODE_ENV==="test",s=process.env.REACT_APP_USE_MOCK==="true"):(t=!0,s=!0)}catch(o){console.warn("无法检测环境变量,使用默认配置:",o),t=!0,s=!0}return t||n||s?this.createMockDataSource({name:"DefaultMockDataSource",delay:300}):this.createApiDataSource({name:"DefaultApiDataSource",baseURL:"/api/v1",token:e&&localStorage.getItem("authToken")||""})}static clearCache(){this.instances.clear(),console.log("[DataSourceFactory] 已清除所有数据源实例缓存")}static getCachedInstanceCount(){return this.instances.size}static getInstanceKey(e,t){return`${e}:${t.name}:${JSON.stringify(t)}`}}function hc(){return mc.createDefaultDataSource()}function gc(r={}){const{dataSource:e=hc(),fallbackStrategy:t="mock",errorHandling:n={},performance:s={},theme:o={},debug:i=!1,enableDevTools:a=!1}=r;return{dataSource:e,fallbackStrategy:t,errorHandling:{showUserFriendlyErrors:!0,logErrors:!0,autoRetry:!0,maxRetries:3,retryDelay:1e3,...n},performance:{enableVirtualization:!0,lazyLoadImages:!0,debounceSearch:300,enableCaching:!0,cacheTTL:3e5,...s},theme:{primaryColor:"#1865f2",borderRadius:"8px",spacing:"16px",fontSize:"14px",enableDarkMode:!1,...o},debug:i,enableDevTools:a}}function pc(r,e){return{...r,...e,errorHandling:{...r.errorHandling,...e.errorHandling},performance:{...r.performance,...e.performance},theme:{...r.theme,...e.theme}}}const po=b.createContext(null),yo=()=>{const r=b.useContext(po);if(!r)throw new Error("useGradeUnitBrowser must be used within GradeUnitBrowserProvider");return r},bo=({children:r,config:e})=>{const[t,n]=b.useState(()=>gc(e)),[s,o]=b.useState(null),[i,a]=b.useState([]),[c,l]=b.useState(null),[d,u]=b.useState({}),[y,m]=b.useState(!1),[h,g]=b.useState(null),[p,x]=b.useState(null),[C,S]=b.useState([]),E=b.useCallback(async($,O)=>{m(!0),g(null);try{process.env.NODE_ENV!=="test"&&await new Promise(M=>setTimeout(M,100));const Y=await t.dataSource.getUserGradeUnitsNav($,O);l(Y);const q={};de.units.forEach(M=>{q[M.id]=M.lessons.map(G=>({id:G.id,title:G.title,duration:G.duration,knowledgeItems:G.knowledgeItems.map(H=>({...H,progress:0}))}))}),console.log("Lessons data loaded:",q),u(q);try{const M=await t.dataSource.getUserProfile(O);o(M)}catch(M){console.warn("获取用户信息失败,使用默认数据:",M),o({id:O,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]})}try{const M=await t.dataSource.getExploreMenu();a(M)}catch(M){console.warn("获取探索菜单失败,使用默认数据:",M),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}}catch(Y){if(console.error("数据加载错误:",Y),t.fallbackStrategy==="mock"){console.log("使用mock数据作为fallback");const q={userId:O,courseId:$,courseTitle:"小学数学五年级",courseLevel:5,totalUnits:de.units.length,completedUnits:2,overallProgress:22,status:"in-progress",lastAccessed:new Date().toISOString(),units:de.units.map((G,H)=>({unitId:G.id,title:G.title,description:G.description,moduleCategory:G.moduleCategory,estimatedDuration:G.estimatedDuration,totalLessons:G.lessons.length,completedLessons:H<2?Math.floor(G.lessons.length*.5):0,progressPercentage:H<2?50:0,status:H<2?"in-progress":"not-started",lastAccessed:H<2?new Date().toISOString():void 0,isActive:H===0,route:`/math/grade-5/unit/${G.id}`,icon:jt[G.moduleCategory]||jt.Default}))};l(q);const M={};de.units.forEach(G=>{M[G.id]=G.lessons.map(H=>({id:H.id,title:H.title,duration:H.duration,knowledgeItems:H.knowledgeItems.map(I=>({...I,progress:0}))}))}),u(M),o({id:O,name:"学生用户",level:5,avatar:"https://i.pravatar.cc/40",badges:["🏆"]}),a([{id:"g5",label:"五年级",status:"进行中"},{id:"g6",label:"六年级",status:"new"}])}else g(Y instanceof Error?Y.message:"数据加载失败"),l(null)}finally{m(!1)}},[t]),_=b.useCallback($=>{S(O=>O.includes($)?O.filter(Y=>Y!==$):[...O,$])},[]),j=b.useCallback($=>{x($)},[]),w=b.useCallback($=>{n(O=>pc(O,$))},[]);b.useEffect(()=>{if(console.log("unitsData state updated:",c),console.log("unitsData?.units:",c?.units),console.log("unitsData?.units?.length:",c?.units?.length),c&&c.units.length>0){console.log("Looking for active unit...");const $=c.units.find(Y=>Y.isActive);console.log("Found active unit:",$);const O=$?.unitId||c.units[0].unitId;console.log("Setting default active unit:",O),x(O),console.log("Default active unit set after state update:",O)}else console.log("No units data available for setting default active unit")},[c]);const P={userInfo:s,exploreMenu:i,unitsData:c,lessons:d,loading:y,error:h,activeUnitId:p,activeLessonIds:C,config:t,theme:t.theme,enableVirtualization:t.performance?.enableVirtualization,setLoading:m,setError:g,setActiveUnit:j,toggleLesson:_,loadPageData:E,updateConfig:w};return f.jsx(po.Provider,{value:P,children:r})},yc=({gradeId:r,userId:e,onLearnAction:t,className:n,userInfo:s,exploreMenu:o})=>{const{userInfo:i,exploreMenu:a,unitsData:c,lessons:l,loading:d,error:u,activeUnitId:y,activeLessonIds:m,setActiveUnit:h,toggleLesson:g,loadPageData:p}=yo(),x=s??i,C=o??a;b.useEffect(()=>{console.log("GradeUnitBrowserPageContent: useEffect triggered, calling loadPageData"),console.log("gradeId:",r,"userId:",e),p(r,e)},[r,e,p]),b.useEffect(()=>{console.log("activeUnitId from context:",y),console.log("lessons from context:",l);const _=c?.units?.find(w=>w.unitId===y)||null,j=_&&y&&l[y]?{id:_.unitId,title:_.title,description:_.description,estimatedDuration:_.estimatedDuration,totalLessons:_.totalLessons,moduleCategory:_.moduleCategory,lessons:l[y]}:null;console.log("activeUnit computed:",j)},[y,l,c]);const S=c?.units?.find(_=>_.unitId===y)||null,E=S&&y&&l[y]?{id:S.unitId,title:S.title,description:S.description,estimatedDuration:S.estimatedDuration,totalLessons:S.totalLessons,moduleCategory:S.moduleCategory,lessons:l[y]}:null;return d?f.jsx("div",{className:`grade-unit-browser-page loading ${n||""}`,"data-testid":"grade-unit-browser-page",children:f.jsx("div",{className:"loading-spinner","data-testid":"loading-spinner",children:"加载中..."})}):u?f.jsxs("div",{className:`grade-unit-browser-page error ${n||""}`,"data-testid":"grade-unit-browser-page",children:[f.jsx("div",{className:"error-message","data-testid":"error-message",children:u}),f.jsx("button",{onClick:()=>p(r,e),className:"retry-button",children:"重试"})]}):f.jsxs("div",{className:`grade-unit-browser-page ${n||""}`,"data-testid":"grade-unit-browser-page",children:[f.jsx("div",{className:"header-area",children:f.jsx(Bs,{userData:x||void 0,exploreItems:C})}),f.jsx("div",{className:"sidebar-area",children:f.jsx(xs,{data:c,activeUnitId:y,onUnitSelect:h,loading:d})}),f.jsx("div",{className:"content-area",children:f.jsx(bs,{unit:E,activeLessonIds:m,onToggleLesson:g,onLearnAction:t||(()=>{}),loading:d})})]})},bc=r=>f.jsx(bo,{config:r.config,children:f.jsx(yc,{...r})}),xc=(r,e,t=.1)=>{if(!r.trim())return{isValid:!1,isCorrect:!1,errorMessage:"请输入答案"};const n=parseFloat(r);if(isNaN(n))return{isValid:!1,isCorrect:!1,errorMessage:"请输入有效的数字"};if(n<0)return{isValid:!1,isCorrect:!1,errorMessage:"答案不能为负数"};const o=Math.abs(n-e)<=t;return{isValid:!0,isCorrect:o,errorMessage:o?void 0:"答案不正确,请再试一次"}},vc=()=>Pt.create((r,e)=>({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,problemData:null,validationError:null,setProblemData:t=>{r({problemData:t,currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},updateUserAnswer:t=>{r({userAnswer:t,validationError:null})},submitAnswer:t=>{const n=e();if(!n.problemData){r({validationError:"问题数据未加载,请刷新页面重试"});return}const s=n.problemData.answer_info?.value??n.problemData.answer.value,o=Number(s),i=n.problemData.answer_info?.tolerance??.1,a=xc(t,o,i);if(!a.isValid){r({userAnswer:t,validationError:a.errorMessage||"答案格式错误"});return}r({userAnswer:t,isCorrect:a.isCorrect,showAnswerForm:!1,validationError:null,currentScene:a.isCorrect?"success":"explanation"})},nextQuestion:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})},resetSession:()=>{r({currentScene:"question",userAnswer:"",isCorrect:null,showAnswerForm:!0,validationError:null})}})),Qe=vc(),dn=()=>Qe(r=>r.currentScene),fn=()=>Qe(r=>r.userAnswer),_c=()=>Qe(r=>r.isCorrect),un=()=>Qe(r=>r.showAnswerForm),xo=()=>Qe(r=>r.validationError),wc=()=>Qe(r=>r.problemData),mn=()=>Qe(Qr.useShallow(r=>({updateUserAnswer:r.updateUserAnswer,submitAnswer:r.submitAnswer,nextQuestion:r.nextQuestion,resetSession:r.resetSession,setProblemData:r.setProblemData}))),Ac=b.createContext(null),Wt=()=>{const r=b.useContext(Ac);if(!r)throw new Error("useMathPracticeStore 必须在 MathPracticeStoreProvider 内部使用");return r},Rc=()=>{const r=Wt(),e=b.useCallback(t=>t.currentScene,[]);return r(e)},Sc=()=>{const r=Wt(),e=b.useCallback(t=>t.userAnswer,[]);return r(e)},Cc=()=>{const r=Wt(),e=b.useCallback(t=>t.showAnswerForm,[]);return r(e)},Ec=()=>{const r=Wt(),e=b.useCallback(t=>t.validationError,[]);return r(e)},Tc=()=>Wt()(Qr.useShallow(e=>({updateUserAnswer:e.updateUserAnswer,submitAnswer:e.submitAnswer,nextQuestion:e.nextQuestion,resetSession:e.resetSession,setProblemData:e.setProblemData}))),hn=()=>{try{return Rc()}catch{return dn()}},gn=()=>{try{return Sc()}catch{return fn()}},pn=()=>{try{return Cc()}catch{return un()}},yn=()=>{try{return Ec()}catch{return xo()}},bn=()=>{try{return Tc()}catch{return mn()}},wt=({problemData:r,userAnswer:e,showAnswerForm:t,onAnswerSubmit:n,onAnswerChange:s,validationError:o})=>{const i=c=>{c.preventDefault(),n(e)},a=c=>{s(c)};return f.jsx("div",{className:"question-scene-container",children:f.jsxs("div",{className:"question-scene-card",children:[f.jsx("div",{className:"question-display-area",children:f.jsx(Re,{data:{id:r.id,grade:r.grade,unit:r.unit,content:r.scenes?.question?.items||r.scenes?.question?.content||[]},scene:"question",layout:{type:"card",padding:"0px",shadow:!1,border:!1}})}),t&&f.jsxs("div",{className:"answer-form-container",children:[f.jsxs("form",{onSubmit:i,className:"answer-form",children:[f.jsx("label",{className:"answer-label",children:"答案"}),f.jsx("input",{type:"number",value:e,onChange:c=>a(c.target.value),className:`answer-input ${o?"error":"normal"}`,placeholder:"?",required:!0}),f.jsx("span",{className:"answer-unit",children:r.basicInfo.answerUnit||r.basicInfo.areaUnit}),f.jsx(pt,{type:"submit",size:"lg",className:"submit-button",children:"提交答案"})]}),o&&f.jsxs("div",{className:"validation-error",children:[f.jsx("span",{children:"⚠️"}),f.jsx("span",{children:o})]})]})]})})},vo=({problemData:r,enableIXLStyle:e=!0})=>{console.log("🔍 RememberModule problemData:",r),console.log("🔍 RememberModule scenes.remember:",r?.scenes?.remember),console.log("🔍 RememberModule scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 RememberModule scenes.remember.content:",r?.scenes?.remember?.content);const n=(()=>{const o=r.scenes?.review?.items;if(o&&Array.isArray(o)&&o.length>0)return console.log("🔍 RememberModule 使用 review.items"),o;const i=r.scenes?.review?.content;if(i&&Array.isArray(i)&&i.length>0)return console.log("🔍 RememberModule 使用 review.content"),i;const a=r.scenes?.remember?.items;if(a&&Array.isArray(a)&&a.length>0)return console.log("🔍 RememberModule 使用 remember.items"),a;const c=r.scenes?.remember?.content;return c&&Array.isArray(c)&&c.length>0?(console.log("🔍 RememberModule 使用 remember.content"),c):(console.log("🔍 RememberModule 未找到任何内容"),[])})();if(n.length===0){const o=f.jsx("div",{className:"remember-module-content",children:f.jsx("p",{className:"remember-module-empty",children:"暂无记忆内容"})});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:o}):f.jsxs("div",{className:"remember-module-container",children:[f.jsx("h4",{className:"remember-module-title",children:"记忆"}),o]})}const s=f.jsx("div",{className:"remember-module-content",children:n.map((o,i)=>{const{type:a,content:c,style:l,parts:d}=o;switch(a){case"text":return f.jsx("p",{className:"remember-module-text-block",style:l,children:c},i);case"formula":return f.jsx("div",{className:"remember-module-formula-block",children:f.jsx(Re,{data:{id:`formula-${i}`,grade:r.grade,unit:r.unit,content:[{type:"formula",content:c,parts:d||[c]}]},layout:{type:"card"},className:e?"ixl-adjusted":""})},i);default:return f.jsxs("p",{className:"remember-module-unsupported",children:["不支持的内容类型: ",a]},i)}})});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"remember",label:"速记",showTag:!0},enableIXLStyle:!0,children:s}):f.jsxs("div",{className:"remember-module-container",children:[f.jsx("h4",{className:"remember-module-title",children:"记忆"}),s]})},xn=({problemData:r,userAnswer:e,enableIXLStyle:t=!0})=>{const n=f.jsxs("div",{className:"review-module-content",children:[f.jsx("p",{className:"review-module-question",children:r.basicInfo.question}),f.jsx("div",{className:"review-module-graph",children:f.jsx(Re,{data:{id:"review-problem",grade:r.grade,unit:r.unit,content:r.scenes?.question?.items||r.scenes?.question?.content||[]},scene:"question",layout:{type:"card"},className:t?"ixl-adjusted":""})}),f.jsxs("p",{className:"review-module-user-answer",children:["你的答案: ",f.jsx("span",{className:"review-module-user-answer-value",children:e})]})]});return t?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"review",label:"回顾",showTag:!0},enableIXLStyle:!0,children:n}):f.jsxs("div",{className:"review-module-container",children:[f.jsx("h4",{className:"review-module-title",children:"复习"}),n]})},Nc=r=>[{color:"var(--mc-step-color-ident)",bg:"var(--mc-step-bg-ident)"},{color:"var(--mc-step-color-calc)",bg:"var(--mc-step-bg-calc)"},{color:"var(--mc-step-color-res)",bg:"var(--mc-step-bg-res)"}][r%3],$c=({step:r,problemData:e,stepNumber:t})=>{const{title:n,description:s,chartConfig:o}=r.content,i=!!o,a=Nc(t-1),c=[{type:"text",content:s.replace(/<br>/g,`
|
|
19
|
-
`).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return f.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[f.jsxs("h3",{className:"explanation-step-title",children:[f.jsx("span",{className:"explanation-step-number",children:t}),f.jsx("span",{children:n})]}),f.jsxs("div",{className:"explanation-step-content",children:[f.jsx(Re,{data:{id:`${r.id}-description`,grade:e.grade,unit:e.unit,content:c},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&f.jsx("div",{className:"explanation-step-chart-container",children:o.type==="geometryTransform"&&(o.config||o.metadata?.config)?f.jsx(cn,{config:o.config||o.metadata?.config,onTransformChange:l=>console.log("Transform progress:",l),onTransformComplete:()=>console.log("Transform complete"),onError:l=>console.error("Geometry transform error:",l)}):f.jsx(Sr,{shapes:o.shapes||[],width:400,height:300,boundingBox:o.boundingBox||[-10,10,10,-10],showGrid:o.showGrid||!1,showAxis:o.showAxis||!1,mode:"view",className:"mx-auto"})})]})]})};function kc(r){return r.steps!==void 0}function Oc(r){if(kc(r))return r;if(Array.isArray(r)){if(r.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=r[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const n=r.map(s=>({id:s.id,type:s.type,title:s.content.title||"",description:s.content.description||"",chartConfig:s.content.chartConfig,videoUrl:s.content.videoUrl,commonErrors:s.content.commonErrors,difficulty:s.content.difficulty}));return{steps:n,total_steps:n.length,strategy:"step_by_step",estimated_time:n.length*30}}else return{steps:r,total_steps:r.length,strategy:"step_by_step",estimated_time:r.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}const vn=({problemData:r,enableIXLStyle:e=!0})=>{const[t,n]=b.useState(!1),s=r?.scenes?.solve?.items||r?.scenes?.solve?.content,o=Array.isArray(s)&&s.length>0,i=b.useMemo(()=>Oc(r.explanation),[r.explanation]),a=i.steps.length>0,c=b.useMemo(()=>a?i.steps.map(d=>({...d,content:{title:d.title,description:d.description,chartConfig:d.chartConfig?{...d.chartConfig,boundingBox:d.chartConfig.type==="graph"&&Array.isArray(d.chartConfig.boundingBox)&&d.chartConfig.boundingBox.length===4?[d.chartConfig.boundingBox[0],d.chartConfig.boundingBox[1],d.chartConfig.boundingBox[2],d.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[a,i.steps]),l=f.jsxs("div",{className:"solve-module-content",children:[o?f.jsxs(f.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",s),s?.forEach?.((d,u)=>{d.type==="geometryTransform"&&console.log(`🔍 SolveModule: geometryTransform block [${u}] =`,{type:d.type,hasMetadata:!!d.metadata,metadata:d.metadata,hasConfig:!!d.config,config:d.config,hasShapes:!!d.shapes,shapes:d.shapes,hasTransform:!!d.transform,transform:d.transform})}),f.jsx(Re,{data:{id:"solve-steps",grade:r.grade,unit:r.unit,content:s},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):f.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),f.jsx("div",{className:"solve-module-button-container",children:f.jsx("button",{type:"button",onClick:()=>n(d=>!d),className:"solve-module-button",children:t?"收起详细解题步骤":"查看详细解题步骤"})}),t&&f.jsxs("div",{className:"solve-module-detailed-container",children:[f.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),a?f.jsx("div",{className:"solve-module-detailed-list",children:c.map((d,u)=>f.jsx($c,{step:d,problemData:r,stepNumber:u+1},d.id))}):f.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:l}):f.jsxs("div",{className:"solve-module-container",children:[f.jsx("h4",{className:"solve-module-title",children:"解题"}),l]})},qt=({problemData:r,userAnswer:e,onNextQuestion:t})=>(console.log("🔍 ExplanationScene problemData:",r),console.log("🔍 ExplanationScene scenes.remember:",r?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",r?.scenes?.remember?.content),f.jsxs("div",{children:[f.jsx("div",{className:"explanation-error-banner",children:f.jsxs("div",{className:"explanation-inner-container",children:[f.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),f.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[f.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),f.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[f.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),f.jsx("div",{className:"correct-answer-value-container",children:f.jsx("span",{className:"correct-answer-value",children:f.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:r.answer?.value??"--"})})})]})]}),f.jsx("div",{className:"explanation-button-container",children:f.jsx(pt,{onClick:t,size:"lg",className:"explanation-next-button",children:"明白了"})})]})}),f.jsxs("div",{className:"explanation-content-area",children:[f.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),f.jsx(xn,{problemData:r,userAnswer:e}),f.jsx(vo,{problemData:r}),f.jsx(vn,{problemData:r})]}),f.jsx("div",{className:"explanation-bottom-area",children:f.jsx(pt,{onClick:t,size:"md",children:"明白了"})})]})),At=({problemData:r,onNextQuestion:e})=>f.jsxs("div",{className:"success-scene-container",children:[f.jsx("h3",{className:"success-message-title",children:"正确!"}),f.jsx("p",{className:"success-message-description",children:"你做得很好!"}),f.jsx("div",{className:"concept-review-container",children:f.jsx(Re,{data:{id:"review-concepts",grade:r.grade,unit:r.unit,content:r.scenes?.review?.items||r.scenes?.review?.content||r.scenes?.remember?.items||r.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),f.jsx(pt,{onClick:e,size:"lg",className:"next-button",children:"下一题"})]}),jc={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},Mr={MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"},Ic={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},ee={DESIGN_TOKEN:"design_token",STYLE_REF:"style_ref",GEOMETRY_REF:"geometry_ref",TRANSFORM_REF:"transform_ref",LAYOUT_REF:"layout_ref",ANIMATION_REF:"animation_ref",BOARD_REF:"board_ref",GEOMETRY_TRANSFORM_REF:"geometry_transform_ref",SLIDER_REF:"slider_ref"},B={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};class me extends Error{code;details;constructor(e,t,n){super(t),this.name="AdapterError",this.code=e,this.details=n}}const lr={id:"fallback-triangle-problem",title:"三角形面积计算",grade:5,unit:"三角形面积计算",lesson:"锐角三角形的面积",skill:"已知锐角三角形的底和高,求三角形面积",objective:"掌握锐角三角形面积公式 A=½bh",knowledgePoints:["三角形面积公式 A=½bh"],difficulty:1,metadata:{topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","三角形面积公式"]},basicInfo:{question:"以下三角形面积是多少?",base:6,height:4,baseUnit:"cm",heightUnit:"cm",answerUnit:"cm²"},scenes:{question:{content:[],layout:{type:"card"}},solve:{content:[],layout:{type:"card"}},review:{content:[],layout:{type:"card"}}},explanation:{steps:[]},answer:{value:12,unit:"cm²",explanation:"三角形面积公式为 A = ½ × 底 × 高 = ½ × 6 × 4 = 12"}},Qn={[B.INVALID_INPUT]:"输入数据无效",[B.MISSING_REQUIRED_FIELD]:"缺少必需字段",[B.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[B.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[B.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[B.STYLE_REF_NOT_FOUND]:"样式引用未找到",[B.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[B.BOARD_REF_NOT_FOUND]:"画板引用未找到",[B.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[B.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[B.TRANSFORMATION_FAILED]:"数据转换失败",[B.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},nt={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Fr={RAW_DATA:["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective","knowledge_points","difficulty","basic_info","scenes","explanation","answer_info"],BASIC_INFO:["question"],ANSWER_INFO:["value","unit","explanation_text"]},_o=["question","solve","review","remember"],ie={DESIGN_TOKEN:/^\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)$/,STYLE_REF:/^styleRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_REF:/^geometryRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,TRANSFORM_REF:/^transformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,LAYOUT_REF:/^layoutRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,ANIMATION_REF:/^animationRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_TRANSFORM_REF:/^geometryTransformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,SLIDER_REF:/^sliderRef:([a-zA-Z_][a-zA-Z0-9_]*)$/},ye={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},wo={design_tokens:{colors:{primary:"#4a90e2",primary_light:"#8ec5fc",error:"#FF5252",success:"#7ED321",success_dark:"#67b510",highlight_left:"#6a5acd",highlight_right:"#FF6B6B",highlight_yellow:"#FFFFE0",text_primary:"#333",text_secondary:"#666",background_light:"#F8FAFC",background_lighter:"#F0F9FF",background_gray:"#f9f9f9",border_light:"#E3F2FD",border_lighter:"#BAE6FD"},fonts:{heading_large:"1.8rem",heading_normal:"1.2rem",body:"1rem",label:"16px",formula:"1.1rem"},spacing:{large:"20px",medium:"15px",small:"10px",tiny:"5px"},geometry:{stroke_width_normal:2,stroke_width_thick:3,stroke_width_thin:1.5,opacity_normal:.8,opacity_light:.3,opacity_medium:.7,dash_normal:2,dash_long:4}}},Ao={style_presets:{primary:{id:"primary",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},secondary:{id:"secondary",fillColor:"$colors.background_light",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},transparent:{id:"transparent",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_light",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},highlight:{id:"highlight",fillColor:"$colors.highlight_yellow",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_thick"},error:{id:"error",fillColor:"transparent",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick"},success:{id:"success",fillColor:"$colors.success",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.success_dark",strokeWidth:"$geometry.stroke_width_normal"},dashed:{id:"dashed",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal",dash:"$geometry.dash_normal"},text_primary:{id:"text_primary",color:"$colors.text_primary",fontSize:"$fonts.body"},text_heading_large:{id:"text_heading_large",color:"$colors.text_primary",fontSize:"$fonts.heading_large",fontWeight:"bold"},base_highlight:{id:"base_highlight",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick",fillColor:"transparent"},label_position:{id:"label_position",color:"$colors.text_primary",fontSize:"$fonts.label",fontWeight:"bold",textAlign:"center"},highlight_left:{id:"highlight_left",fillColor:"$colors.highlight_left",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},highlight_right:{id:"highlight_right",fillColor:"$colors.highlight_right",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},label_error:{id:"label_error",color:"$colors.error",fontSize:"$fonts.label",fontWeight:"bold"}}},Ro={geometry_presets:{acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[[100,300],[300,100],[500,300]],styleRef:"primary",description:"锐角三角形"},right_triangle:{id:"right_triangle",type:"triangle",vertices:[[100,100],[100,300],[300,300]],styleRef:"secondary",description:"直角三角形"},equilateral_triangle:{id:"equilateral_triangle",type:"triangle",vertices:[[200,100],[100,273],[300,273]],styleRef:"highlight",description:"等边三角形"},rectangle:{id:"rectangle",type:"rectangle",dimensions:{width:200,height:100},styleRef:"primary",description:"矩形"},parallelogram:{id:"parallelogram",type:"parallelogram",vertices:[[100,100],[300,100],[250,200],[50,200]],styleRef:"secondary",description:"平行四边形"},horizontal_line:{id:"horizontal_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"primary",description:"水平线段模板"},vertical_line:{id:"vertical_line",type:"segment",endpoints:[[0,0],[0,100]],styleRef:"primary",description:"垂直线段模板"},arrow_line:{id:"arrow_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"error",description:"箭头线段模板"},label_point:{id:"label_point",type:"point",position:[50,20],styleRef:"text_primary",description:"标签位置点模板"},center_point:{id:"center_point",type:"point",position:[50,50],styleRef:"primary",description:"中心点模板"},vertex_point:{id:"vertex_point",type:"point",position:[0,0],styleRef:"primary",description:"顶点点模板"},marker_point:{id:"marker_point",type:"point",position:[0,0],styleRef:"highlight",description:"标记点模板"},left_triangle:{id:"left_triangle",type:"polygon",vertices:[[100,100],[100,300],[250,300]],styleRef:"highlight_left",description:"左三角形模板"}}},So={layout_presets:{card:{id:"card",type:"card",padding:"$spacing.large",theme:"light"},vertical_centered:{id:"vertical_centered",type:"vertical",spacing:"$spacing.large",alignment:"center"},vertical_spaced:{id:"vertical_spaced",type:"vertical",spacing:"$spacing.medium",alignment:"start"},grid_2col:{id:"grid_2col",type:"grid",columns:2,spacing:"$spacing.medium"}}},Co={transform_definitions:{left_rotation:{id:"left_rotation",type:"rotation",angle:-90,origin:[0,0],description:"向左旋转90度"},right_rotation:{id:"right_rotation",type:"rotation",angle:90,origin:[0,0],description:"向右旋转90度"},translation:{id:"translation",type:"translation",dx:0,dy:0,description:"平移变换"},scale:{id:"scale",type:"scale",factor:1,origin:[0,0],description:"缩放变换"}}},ht={slider_definitions:{slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}}},Eo={board_definitions:{default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}}},it={designTokens:wo.design_tokens,stylePresets:Ao.style_presets,geometryPresets:Ro.geometry_presets,layoutPresets:So.layout_presets,transformDefinitions:Co.transform_definitions,animationDefinitions:ht.slider_definitions,animationConfigs:ht.slider_definitions,boardDefinitions:Eo.board_definitions};function To(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!ht,sliderDefinitionsKeys:ht.slider_definitions?Object.keys(ht.slider_definitions):[]});const r=ht.slider_definitions;return{designTokens:wo.design_tokens,stylePresets:Ao.style_presets,geometryPresets:Ro.geometry_presets,layoutPresets:So.layout_presets,transformDefinitions:Co.transform_definitions,animationDefinitions:r,animationConfigs:r,boardDefinitions:Eo.board_definitions}}class Pe{static canResolve(e){return ie.DESIGN_TOKEN.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const n=e.substring(1);return this.resolvePath(n,t.designTokens)}static resolvePath(e,t){const n=e.split(".");let s=t;for(const o of n){if(s==null)throw new Error(`设计令牌路径不存在: ${e} (在 ${o} 处中断)`);if(typeof s!="object")throw new Error(`设计令牌路径无效: ${e} (${o} 不是对象)`);s=s[o]}if(s===void 0)throw new Error(`设计令牌未找到: ${e}`);return s}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`设计令牌解析失败: ${s}`,o)}return n}static extractDesignTokenRefs(e){const t=[],n=s=>{typeof s=="string"?this.canResolve(s)&&t.push(s):Array.isArray(s)?s.forEach(n):typeof s=="object"&&s!==null&&Object.values(s).forEach(n)};return n(e),t}static replaceDesignTokenRefs(e,t,n){const s=o=>{if(typeof o=="string"){if(this.canResolve(o))try{return this.resolve(o,t)}catch(d){if(n)return n(o);throw d}const i=/\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;let a,c=0;const l=[];for(;(a=i.exec(o))!==null;){a.index>c&&l.push(o.substring(c,a.index));const d=a[0];try{const u=this.resolve(d,t);l.push(String(u))}catch{n?l.push(String(n(d))):l.push(d)}c=a.index+d.length}return c<o.length&&l.push(o.substring(c)),l.length>1?l.join(""):o}else{if(Array.isArray(o))return o.map(s);if(typeof o=="object"&&o!==null){const i={};for(const[a,c]of Object.entries(o))i[a]=s(c);return i}}return o};return s(e)}}function Mc(){return{type:ee.DESIGN_TOKEN,canResolve:Pe.canResolve.bind(Pe),resolve:Pe.resolve.bind(Pe)}}class Be{static canResolve(e,t){if(typeof e!="string"||e.length===0)return!1;if(ie.GEOMETRY_REF.test(e)||[/^point_[a-zA-Z0-9_]+$/,/^segment_[a-zA-Z0-9_]+$/,/^line_[a-zA-Z0-9_]+$/,/^triangle_[a-zA-Z0-9_]+$/,/^polygon_[a-zA-Z0-9_]+$/,/^circle_[a-zA-Z0-9_]+$/,/^angle_[a-zA-Z0-9_]+$/,/^vector_[a-zA-Z0-9_]+$/,/^arc_[a-zA-Z0-9_]+$/,/^ray_[a-zA-Z0-9_]+$/].some(o=>o.test(e)))return!0;if(t&&t.geometryPresets){let o;const i=e.match(ie.GEOMETRY_REF);return i?o=i[1]:o=e,o in t.geometryPresets}return["acute_triangle","right_triangle","equilateral_triangle","rectangle","parallelogram","horizontal_line","vertical_line","arrow_line","label_point","center_point","vertex_point","marker_point","left_triangle","right_triangle","base_segment","height_segment","base_arrow","height_arrow","full_rectangle"].includes(e)}static resolveVertexReference(e,t){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!t.geometryPresets,pointFound:!!t.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const n=e.$ref;if(t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return console.error(`✅ 解析顶点引用 ${n}: 使用 position`,s.position),[s.position.x,s.position.y];if("x"in s&&"y"in s)return console.error(`✅ 解析顶点引用 ${n}: 使用 x/y`,{x:s.x,y:s.y}),[s.x,s.y]}return console.warn(`无法解析顶点引用: ${n}`),e}return Array.isArray(e)&&e.length===2?e:e&&typeof e=="object"&&"x"in e&&"y"in e?[e.x,e.y]:e}static resolve(e,t){if(!this.canResolve(e,t))throw new Error(`无法解析的几何引用: ${e}`);let n;const s=e.match(ie.GEOMETRY_REF);s?n=s[1]:n=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${n}"`),console.error(" Available geometryPresets:",Object.keys(t.geometryPresets||{}));const o=t.geometryPresets[n];if(!o)throw console.error(`❌ Geometry preset not found: ${n} in`,t.geometryPresets),new Error(`几何预设未找到: ${n}`);console.error("✅ Geometry resolved:",{name:n,type:o.type,hasVertices:"vertices"in o,verticesCount:o.vertices?o.vertices.length:0,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,geometryKeys:Object.keys(o)});const i={...o};return i.vertices&&Array.isArray(i.vertices)&&(i.vertices=i.vertices.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(c){return console.warn("顶点引用解析失败:",c),a}}),console.error(`🔍 GeometryRefResolver: 转换顶点格式,数量=${i.vertices.length}`,{sampleVertices:i.vertices.slice(0,3).map((a,c)=>({index:c,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})),i.endpoints&&Array.isArray(i.endpoints)&&(i.endpoints=i.endpoints.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(c){return console.warn("端点引用解析失败:",c),a}})),i}static validate(e,t){if(!this.canResolve(e,t))return!1;let n;const s=e.match(ie.GEOMETRY_REF);return s?n=s[1]:n=e,n in t.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,t){const n=this.resolve(e,t);if(n.styleRef&&t.stylePresets[n.styleRef]){const s=t.stylePresets[n.styleRef];return{...n,style:{...s}}}return n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`几何引用解析失败: ${s}`,o)}return n}static extractGeometryRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.geometryRef&&typeof s.geometryRef=="string"&&t.push(s.geometryRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.geometryRef&&typeof o.geometryRef=="string"&&t.push(o.geometryRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Fc(){return{type:ee.GEOMETRY_REF,canResolve:Be.canResolve.bind(Be),resolve:Be.resolve.bind(Be),validate:Be.validate.bind(Be)}}class Se{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.TRANSFORM_REF.test(e)?!0:["left_rotation","right_rotation","translation"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let n;const s=e.match(ie.TRANSFORM_REF);if(s?n=s[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n])return{...t.transformDefinitions[n]};const o={left_rotation:{type:"rotation",angle:-90,origin:[0,0]},right_rotation:{type:"rotation",angle:90,origin:[0,0]},translation:{type:"translation",dx:0,dy:0}};if(o[n])return{...o[n]};throw new Error(`变换定义未找到: ${n}`)}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.TRANSFORM_REF);return s?n=s[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n]?!0:["left_rotation","right_rotation","translation"].includes(n)}static applyTransform(e,t){if(!t||!e)return e;const n={...e};switch(t.type){case"rotation":n.vertices=this.applyRotation(e.vertices,t.angle,t.origin);break;case"translation":n.vertices=this.applyTranslation(e.vertices,t.dx,t.dy);break;case"scale":n.vertices=this.applyScale(e.vertices,t.factor,t.origin);break;default:console.warn(`未知的变换类型: ${t.type}`)}return n}static applyRotation(e,t,n){if(!e||!Array.isArray(e))return e;const[s,o]=n,i=t*Math.PI/180,a=Math.cos(i),c=Math.sin(i);return e.map(([l,d])=>{const u=l-s,y=d-o;return[s+u*a-y*c,o+u*c+y*a]})}static applyTranslation(e,t,n){return!e||!Array.isArray(e)?e:e.map(([s,o])=>[s+t,o+n])}static applyScale(e,t,n){if(!e||!Array.isArray(e))return e;const[s,o]=n;return e.map(([i,a])=>{const c=i-s,l=a-o;return[s+c*t,o+l*t]})}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`变换引用解析失败: ${s}`,o)}return n}static extractTransformRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.transformRef&&typeof s.transformRef=="string"&&t.push(s.transformRef),Array.isArray(s.transformations)&&s.transformations.forEach(o=>{o.transformRef&&typeof o.transformRef=="string"&&t.push(o.transformRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Pc(){return{type:ee.TRANSFORM_REF,canResolve:Se.canResolve.bind(Se),resolve:Se.resolve.bind(Se),validate:Se.validate.bind(Se)}}class we{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.STYLE_REF.test(e)?!0:["primary","secondary","transparent","highlight","error","success","dashed","text_primary","text_heading_large","base_highlight","label_position","highlight_left","highlight_right","label_error"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let n;const s=e.match(ie.STYLE_REF);s?n=s[1]:n=e;const o=t.stylePresets[n];if(!o)throw new Error(`样式预设未找到: ${n}`);return this.resolveStylePreset(o,t)}static resolveStylePreset(e,t){const n={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(Pe.canResolve(o))try{n[s]=Pe.resolve(o,t)}catch(i){console.warn(`样式中的设计令牌解析失败: ${s}=${o}`,i),n[s]=o}}else o&&typeof o=="object"&&(n[s]=this.resolveStylePreset(o,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.STYLE_REF);return s?n=s[1]:n=e,n in t.stylePresets}static applyStyle(e,t){if(!e||!t)return e;const n={...e};return n.style=n.style?{...n.style,...t}:{...t},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(o=>{t[o]!==void 0&&(n[o]=t[o])}),n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`样式引用解析失败: ${s}`,o)}return n}static extractStyleRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.styleRef&&typeof s.styleRef=="string"&&t.push(s.styleRef),s.style&&typeof s.style=="object"&&s.style.styleRef&&typeof s.style.styleRef=="string"&&t.push(s.style.styleRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.styleRef&&typeof o.styleRef=="string"&&t.push(o.styleRef),o.style&&o.style.styleRef&&typeof o.style.styleRef=="string"&&t.push(o.style.styleRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function Dc(){return{type:ee.STYLE_REF,canResolve:we.canResolve.bind(we),resolve:we.resolve.bind(we),validate:we.validate.bind(we)}}class Ve{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let n;const s=e.match(ie.LAYOUT_REF);if(s?n=s[1]:n=e,t.layoutPresets&&t.layoutPresets[n]){const i=t.layoutPresets[n];return this.resolveLayoutPreset(i,t)}const o={card:{type:"card",padding:"20px",theme:"light"},vertical:{type:"vertical",spacing:"15px",alignment:"start"},horizontal:{type:"horizontal",spacing:"15px",alignment:"center"}};if(o[n])return{...o[n]};throw new Error(`布局预设未找到: ${n}`)}static resolveLayoutPreset(e,t){const n={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(Pe.canResolve(o))try{n[s]=Pe.resolve(o,t)}catch(i){console.warn(`布局中的设计令牌解析失败: ${s}=${o}`,i),n[s]=o}}else o&&typeof o=="object"&&(n[s]=this.resolveLayoutPreset(o,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.LAYOUT_REF);return s?n=s[1]:n=e,t.layoutPresets&&t.layoutPresets[n]?!0:["card","vertical","horizontal"].includes(n)}static applyLayout(e,t){if(!e||!t)return e;const n={...e};return n.layout?n.layout={...n.layout,...t}:n.layout={...t},n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`布局引用解析失败: ${s}`,o)}return n}static extractLayoutRefs(e){const t=[];for(const n of Object.values(e))if(n.layout&&n.layout.type&&typeof n.layout.type=="string"&&this.isLayoutRef(n.layout.type)&&t.push(n.layout.type),n.layout&&typeof n.layout=="object")for(const s of Object.values(n.layout))typeof s=="string"&&this.isLayoutRef(s)&&t.push(s);return[...new Set(t)]}static isLayoutRef(e){return ie.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function Lc(){return{type:ee.LAYOUT_REF,canResolve:Ve.canResolve.bind(Ve),resolve:Ve.resolve.bind(Ve),validate:Ve.validate.bind(Ve)}}class st{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.ANIMATION_REF.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new me(B.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const n=e.match(ie.ANIMATION_REF);if(!n)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const s=n[1],o=t.animationConfigs?.[s];if(!o)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${s}`);return this.resolveAnimationConfig(s,o,t)}static resolveAnimationConfig(e,t,n){if(!t.transforms||!Array.isArray(t.transforms))throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const s=t.transforms.map((a,c)=>{if(!a.id)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 id 字段`);if(!a.type)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] targetShapes 不能为空`);a.targetShapes.forEach((u,y)=>{if(typeof u!="string"||u.trim()==="")throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}].targetShapes[${y}] 必须是有效的字符串 ID`)});const l=Gl(a.params),d=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:l,targetShapes:a.targetShapes,usesControl:d}}),o={id:e,control:t.control,transforms:s,visualEffects:t.visualEffects||[],progressControl:t.progressControl},i=zl(o);if(!i.valid)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
|
|
19
|
+
`).replace(/<[^>]*>/g,""),style:{fontSize:"var(--mc-text-base)",color:"var(--mc-text-secondary)",lineHeight:"var(--mc-leading-relaxed)"}}];return f.jsxs("div",{className:"explanation-step-container",style:{"--current-step-color":a.color,"--current-step-bg":a.bg},children:[f.jsxs("h3",{className:"explanation-step-title",children:[f.jsx("span",{className:"explanation-step-number",children:t}),f.jsx("span",{children:n})]}),f.jsxs("div",{className:"explanation-step-content",children:[f.jsx(Re,{data:{id:`${r.id}-description`,grade:e.grade,unit:e.unit,content:c},layout:{type:"card",padding:"16px",border:!1,shadow:!1},className:"explanation-step-mathcard"}),i&&f.jsx("div",{className:"explanation-step-chart-container",children:o.type==="geometryTransform"&&(o.config||o.metadata?.config)?f.jsx(cn,{config:o.config||o.metadata?.config,onTransformChange:l=>console.log("Transform progress:",l),onTransformComplete:()=>console.log("Transform complete"),onError:l=>console.error("Geometry transform error:",l)}):f.jsx(Sr,{shapes:o.shapes||[],width:400,height:300,boundingBox:o.boundingBox||[-10,10,10,-10],showGrid:o.showGrid||!1,showAxis:o.showAxis||!1,mode:"view",className:"mx-auto"})})]})]})};function kc(r){return r.steps!==void 0}function Oc(r){if(kc(r))return r;if(Array.isArray(r)){if(r.length===0)return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0};const e=r[0];if(e&&e.content&&(e.content.title!==void 0||e.content.description!==void 0)){const n=r.map(s=>({id:s.id,type:s.type,title:s.content.title||"",description:s.content.description||"",chartConfig:s.content.chartConfig,videoUrl:s.content.videoUrl,commonErrors:s.content.commonErrors,difficulty:s.content.difficulty}));return{steps:n,total_steps:n.length,strategy:"step_by_step",estimated_time:n.length*30}}else return{steps:r,total_steps:r.length,strategy:"step_by_step",estimated_time:r.length*30}}return{steps:[],total_steps:0,strategy:"step_by_step",estimated_time:0}}const vn=({problemData:r,enableIXLStyle:e=!0})=>{const[t,n]=b.useState(!1),s=r?.scenes?.solve?.items||r?.scenes?.solve?.content,o=Array.isArray(s)&&s.length>0,i=b.useMemo(()=>Oc(r.explanation),[r.explanation]),a=i.steps.length>0,c=b.useMemo(()=>a?i.steps.map(d=>({...d,content:{title:d.title,description:d.description,chartConfig:d.chartConfig?{...d.chartConfig,boundingBox:d.chartConfig.type==="graph"&&Array.isArray(d.chartConfig.boundingBox)&&d.chartConfig.boundingBox.length===4?[d.chartConfig.boundingBox[0],d.chartConfig.boundingBox[1],d.chartConfig.boundingBox[2],d.chartConfig.boundingBox[3]]:[-10,10,10,-10]}:void 0}})):[],[a,i.steps]),l=f.jsxs("div",{className:"solve-module-content",children:[o?f.jsxs(f.Fragment,{children:[console.log("🔍 SolveModule: solveContent =",s),s?.forEach?.((d,u)=>{d.type==="geometryTransform"&&console.log(`🔍 SolveModule: geometryTransform block [${u}] =`,{type:d.type,hasMetadata:!!d.metadata,metadata:d.metadata,hasConfig:!!d.config,config:d.config,hasShapes:!!d.shapes,shapes:d.shapes,hasTransform:!!d.transform,transform:d.transform})}),f.jsx(Re,{data:{id:"solve-steps",grade:r.grade,unit:r.unit,content:s},scene:"solve",layout:{type:"flow",direction:"vertical",gap:"12px"},className:e?"ixl-adjusted":""})]}):f.jsx("div",{className:"solve-module-empty",children:"空白(暂无简化解题步骤)"}),f.jsx("div",{className:"solve-module-button-container",children:f.jsx("button",{type:"button",onClick:()=>n(d=>!d),className:"solve-module-button",children:t?"收起详细解题步骤":"查看详细解题步骤"})}),t&&f.jsxs("div",{className:"solve-module-detailed-container",children:[f.jsx("h5",{className:"solve-module-detailed-title",children:"详细解题步骤"}),a?f.jsx("div",{className:"solve-module-detailed-list",children:c.map((d,u)=>f.jsx($c,{step:d,problemData:r,stepNumber:u+1},d.id))}):f.jsx("div",{className:"solve-module-empty",children:"暂无详细解题步骤"})]})]});return e?f.jsx(xt,{wrapperMode:"generic",ixlConfig:{type:"solve",label:"解答",showTag:!0},enableIXLStyle:!0,children:l}):f.jsxs("div",{className:"solve-module-container",children:[f.jsx("h4",{className:"solve-module-title",children:"解题"}),l]})},qt=({problemData:r,userAnswer:e,onNextQuestion:t})=>(console.log("🔍 ExplanationScene problemData:",r),console.log("🔍 ExplanationScene scenes.remember:",r?.scenes?.remember),console.log("🔍 ExplanationScene scenes.remember.items:",r?.scenes?.remember?.items),console.log("🔍 ExplanationScene scenes.remember.content:",r?.scenes?.remember?.content),f.jsxs("div",{children:[f.jsx("div",{className:"explanation-error-banner",children:f.jsxs("div",{className:"explanation-inner-container",children:[f.jsx("div",{className:"explanation-icon","aria-hidden":!0,children:"💡"}),f.jsxs("div",{className:"explanation-content explanation-content-spacing",children:[f.jsx("h3",{className:"explanation-title",children:"让我们再看一遍..."}),f.jsxs("div",{className:"explanation-description explanation-description-spacing",children:[f.jsx("div",{className:"correct-answer-label",children:"正确答案是:"}),f.jsx("div",{className:"correct-answer-value-container",children:f.jsx("span",{className:"correct-answer-value",children:f.jsx("span",{style:{fontFamily:"var(--mc-font-serif)"},children:r.answer?.value??"--"})})})]})]}),f.jsx("div",{className:"explanation-button-container",children:f.jsx(pt,{onClick:t,size:"lg",className:"explanation-next-button",children:"明白了"})})]})}),f.jsxs("div",{className:"explanation-content-area",children:[f.jsx("h4",{className:"explanation-subtitle",children:"详细解释"}),f.jsx(xn,{problemData:r,userAnswer:e}),f.jsx(vo,{problemData:r}),f.jsx(vn,{problemData:r})]}),f.jsx("div",{className:"explanation-bottom-area",children:f.jsx(pt,{onClick:t,size:"md",children:"明白了"})})]})),At=({problemData:r,onNextQuestion:e})=>f.jsxs("div",{className:"success-scene-container",children:[f.jsx("h3",{className:"success-message-title",children:"正确!"}),f.jsx("p",{className:"success-message-description",children:"你做得很好!"}),f.jsx("div",{className:"concept-review-container",children:f.jsx(Re,{data:{id:"review-concepts",grade:r.grade,unit:r.unit,content:r.scenes?.review?.items||r.scenes?.review?.content||r.scenes?.remember?.items||r.scenes?.remember?.content||[{type:"text",content:"核心概念回顾:本次练习中你掌握了重要的数学概念!"}]},scene:"review",layout:{type:"card"}})}),f.jsx(pt,{onClick:e,size:"lg",className:"next-button",children:"下一题"})]}),Mr={MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"},jc={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},Ic={strictMode:!1,enableLogging:!1,validationLevel:"basic",fallbackOnError:!0,enableReferenceResolution:!0,enableComponentContractValidation:!1,maxReferenceDepth:10,enablePerformanceMonitoring:!1},ee={DESIGN_TOKEN:"design_token",STYLE_REF:"style_ref",GEOMETRY_REF:"geometry_ref",TRANSFORM_REF:"transform_ref",LAYOUT_REF:"layout_ref",ANIMATION_REF:"animation_ref",BOARD_REF:"board_ref",GEOMETRY_TRANSFORM_REF:"geometry_transform_ref",SLIDER_REF:"slider_ref"},B={INVALID_INPUT:"INVALID_INPUT",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",DESIGN_TOKEN_NOT_FOUND:"DESIGN_TOKEN_NOT_FOUND",GEOMETRY_REF_NOT_FOUND:"GEOMETRY_REF_NOT_FOUND",TRANSFORM_REF_NOT_FOUND:"TRANSFORM_REF_NOT_FOUND",GEOMETRY_TRANSFORM_REF_NOT_FOUND:"GEOMETRY_TRANSFORM_REF_NOT_FOUND",STYLE_REF_NOT_FOUND:"STYLE_REF_NOT_FOUND",ANIMATION_REF_NOT_FOUND:"ANIMATION_REF_NOT_FOUND",BOARD_REF_NOT_FOUND:"BOARD_REF_NOT_FOUND",SLIDER_REF_NOT_FOUND:"SLIDER_REF_NOT_FOUND",TRANSFORMATION_FAILED:"TRANSFORMATION_FAILED",OUTPUT_VALIDATION_FAILED:"OUTPUT_VALIDATION_FAILED"};class me extends Error{code;details;constructor(e,t,n){super(t),this.name="AdapterError",this.code=e,this.details=n}}const lr={id:"fallback-triangle-problem",title:"三角形面积计算",grade:5,unit:"三角形面积计算",lesson:"锐角三角形的面积",skill:"已知锐角三角形的底和高,求三角形面积",objective:"掌握锐角三角形面积公式 A=½bh",knowledgePoints:["三角形面积公式 A=½bh"],difficulty:1,metadata:{topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","三角形面积公式"]},basicInfo:{question:"以下三角形面积是多少?",base:6,height:4,baseUnit:"cm",heightUnit:"cm",answerUnit:"cm²"},scenes:{question:{content:[],layout:{type:"card"}},solve:{content:[],layout:{type:"card"}},review:{content:[],layout:{type:"card"}}},explanation:{steps:[]},answer:{value:12,unit:"cm²",explanation:"三角形面积公式为 A = ½ × 底 × 高 = ½ × 6 × 4 = 12"}},Qn={[B.INVALID_INPUT]:"输入数据无效",[B.MISSING_REQUIRED_FIELD]:"缺少必需字段",[B.DESIGN_TOKEN_NOT_FOUND]:"设计令牌未找到",[B.GEOMETRY_REF_NOT_FOUND]:"几何引用未找到",[B.TRANSFORM_REF_NOT_FOUND]:"变换引用未找到",[B.STYLE_REF_NOT_FOUND]:"样式引用未找到",[B.ANIMATION_REF_NOT_FOUND]:"动画引用未找到",[B.BOARD_REF_NOT_FOUND]:"画板引用未找到",[B.GEOMETRY_TRANSFORM_REF_NOT_FOUND]:"几何变换引用未找到",[B.SLIDER_REF_NOT_FOUND]:"滑块引用未找到",[B.TRANSFORMATION_FAILED]:"数据转换失败",[B.OUTPUT_VALIDATION_FAILED]:"输出验证失败"},nt={MAX_TRANSFORMATION_TIME:5,MAX_MEMORY_INCREASE:50*1024,MAX_REFERENCE_DEPTH:10,WARNING_TRANSFORMATION_TIME:10},Fr={RAW_DATA:["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective","knowledge_points","difficulty","basic_info","scenes","explanation","answer_info"],BASIC_INFO:["question"],ANSWER_INFO:["value","unit","explanation_text"]},_o=["question","solve","review","remember"],ie={DESIGN_TOKEN:/^\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)$/,STYLE_REF:/^styleRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_REF:/^geometryRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,TRANSFORM_REF:/^transformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,LAYOUT_REF:/^layoutRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,ANIMATION_REF:/^animationRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,GEOMETRY_TRANSFORM_REF:/^geometryTransformRef:([a-zA-Z_][a-zA-Z0-9_]*)$/,SLIDER_REF:/^sliderRef:([a-zA-Z_][a-zA-Z0-9_]*)$/},ye={TEXT:"text",FORMULA:"formula",GRAPH:"graph",GEOMETRY_TRANSFORM:"geometryTransform",HUNDRED_GRID:"hundredGrid",PLACE_VALUE_CHART:"placeValueChart"},wo={design_tokens:{colors:{primary:"#4a90e2",primary_light:"#8ec5fc",error:"#FF5252",success:"#7ED321",success_dark:"#67b510",highlight_left:"#6a5acd",highlight_right:"#FF6B6B",highlight_yellow:"#FFFFE0",text_primary:"#333",text_secondary:"#666",background_light:"#F8FAFC",background_lighter:"#F0F9FF",background_gray:"#f9f9f9",border_light:"#E3F2FD",border_lighter:"#BAE6FD"},fonts:{heading_large:"1.8rem",heading_normal:"1.2rem",body:"1rem",label:"16px",formula:"1.1rem"},spacing:{large:"20px",medium:"15px",small:"10px",tiny:"5px"},geometry:{stroke_width_normal:2,stroke_width_thick:3,stroke_width_thin:1.5,opacity_normal:.8,opacity_light:.3,opacity_medium:.7,dash_normal:2,dash_long:4}}},Ao={style_presets:{primary:{id:"primary",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},secondary:{id:"secondary",fillColor:"$colors.background_light",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},transparent:{id:"transparent",fillColor:"$colors.primary_light",fillOpacity:"$geometry.opacity_light",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal"},highlight:{id:"highlight",fillColor:"$colors.highlight_yellow",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_thick"},error:{id:"error",fillColor:"transparent",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick"},success:{id:"success",fillColor:"$colors.success",fillOpacity:"$geometry.opacity_normal",strokeColor:"$colors.success_dark",strokeWidth:"$geometry.stroke_width_normal"},dashed:{id:"dashed",strokeColor:"$colors.text_secondary",strokeWidth:"$geometry.stroke_width_normal",dash:"$geometry.dash_normal"},text_primary:{id:"text_primary",color:"$colors.text_primary",fontSize:"$fonts.body"},text_heading_large:{id:"text_heading_large",color:"$colors.text_primary",fontSize:"$fonts.heading_large",fontWeight:"bold"},base_highlight:{id:"base_highlight",strokeColor:"$colors.error",strokeWidth:"$geometry.stroke_width_thick",fillColor:"transparent"},label_position:{id:"label_position",color:"$colors.text_primary",fontSize:"$fonts.label",fontWeight:"bold",textAlign:"center"},highlight_left:{id:"highlight_left",fillColor:"$colors.highlight_left",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},highlight_right:{id:"highlight_right",fillColor:"$colors.highlight_right",fillOpacity:"$geometry.opacity_medium",strokeColor:"$colors.primary",strokeWidth:"$geometry.stroke_width_normal"},label_error:{id:"label_error",color:"$colors.error",fontSize:"$fonts.label",fontWeight:"bold"}}},Ro={geometry_presets:{acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[[100,300],[300,100],[500,300]],styleRef:"primary",description:"锐角三角形"},right_triangle:{id:"right_triangle",type:"triangle",vertices:[[100,100],[100,300],[300,300]],styleRef:"secondary",description:"直角三角形"},equilateral_triangle:{id:"equilateral_triangle",type:"triangle",vertices:[[200,100],[100,273],[300,273]],styleRef:"highlight",description:"等边三角形"},rectangle:{id:"rectangle",type:"rectangle",dimensions:{width:200,height:100},styleRef:"primary",description:"矩形"},parallelogram:{id:"parallelogram",type:"parallelogram",vertices:[[100,100],[300,100],[250,200],[50,200]],styleRef:"secondary",description:"平行四边形"},horizontal_line:{id:"horizontal_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"primary",description:"水平线段模板"},vertical_line:{id:"vertical_line",type:"segment",endpoints:[[0,0],[0,100]],styleRef:"primary",description:"垂直线段模板"},arrow_line:{id:"arrow_line",type:"segment",endpoints:[[0,0],[100,0]],styleRef:"error",description:"箭头线段模板"},label_point:{id:"label_point",type:"point",position:[50,20],styleRef:"text_primary",description:"标签位置点模板"},center_point:{id:"center_point",type:"point",position:[50,50],styleRef:"primary",description:"中心点模板"},vertex_point:{id:"vertex_point",type:"point",position:[0,0],styleRef:"primary",description:"顶点点模板"},marker_point:{id:"marker_point",type:"point",position:[0,0],styleRef:"highlight",description:"标记点模板"},left_triangle:{id:"left_triangle",type:"polygon",vertices:[[100,100],[100,300],[250,300]],styleRef:"highlight_left",description:"左三角形模板"}}},So={layout_presets:{card:{id:"card",type:"card",padding:"$spacing.large",theme:"light"},vertical_centered:{id:"vertical_centered",type:"vertical",spacing:"$spacing.large",alignment:"center"},vertical_spaced:{id:"vertical_spaced",type:"vertical",spacing:"$spacing.medium",alignment:"start"},grid_2col:{id:"grid_2col",type:"grid",columns:2,spacing:"$spacing.medium"}}},Co={transform_definitions:{left_rotation:{id:"left_rotation",type:"rotation",angle:-90,origin:[0,0],description:"向左旋转90度"},right_rotation:{id:"right_rotation",type:"rotation",angle:90,origin:[0,0],description:"向右旋转90度"},translation:{id:"translation",type:"translation",dx:0,dy:0,description:"平移变换"},scale:{id:"scale",type:"scale",factor:1,origin:[0,0],description:"缩放变换"}}},ht={slider_definitions:{slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}}},Eo={board_definitions:{default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}}},it={designTokens:wo.design_tokens,stylePresets:Ao.style_presets,geometryPresets:Ro.geometry_presets,layoutPresets:So.layout_presets,transformDefinitions:Co.transform_definitions,animationDefinitions:ht.slider_definitions,animationConfigs:ht.slider_definitions,boardDefinitions:Eo.board_definitions};function To(){console.error("🔍 getDefaultReferenceContext called:",{hasEmbeddedAnimationDefinitions:!!ht,sliderDefinitionsKeys:ht.slider_definitions?Object.keys(ht.slider_definitions):[]});const r=ht.slider_definitions;return{designTokens:wo.design_tokens,stylePresets:Ao.style_presets,geometryPresets:Ro.geometry_presets,layoutPresets:So.layout_presets,transformDefinitions:Co.transform_definitions,animationDefinitions:r,animationConfigs:r,boardDefinitions:Eo.board_definitions}}class Pe{static canResolve(e){return ie.DESIGN_TOKEN.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的设计令牌引用: ${e}`);const n=e.substring(1);return this.resolvePath(n,t.designTokens)}static resolvePath(e,t){const n=e.split(".");let s=t;for(const o of n){if(s==null)throw new Error(`设计令牌路径不存在: ${e} (在 ${o} 处中断)`);if(typeof s!="object")throw new Error(`设计令牌路径无效: ${e} (${o} 不是对象)`);s=s[o]}if(s===void 0)throw new Error(`设计令牌未找到: ${e}`);return s}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`设计令牌解析失败: ${s}`,o)}return n}static extractDesignTokenRefs(e){const t=[],n=s=>{typeof s=="string"?this.canResolve(s)&&t.push(s):Array.isArray(s)?s.forEach(n):typeof s=="object"&&s!==null&&Object.values(s).forEach(n)};return n(e),t}static replaceDesignTokenRefs(e,t,n){const s=o=>{if(typeof o=="string"){if(this.canResolve(o))try{return this.resolve(o,t)}catch(d){if(n)return n(o);throw d}const i=/\$([a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;let a,c=0;const l=[];for(;(a=i.exec(o))!==null;){a.index>c&&l.push(o.substring(c,a.index));const d=a[0];try{const u=this.resolve(d,t);l.push(String(u))}catch{n?l.push(String(n(d))):l.push(d)}c=a.index+d.length}return c<o.length&&l.push(o.substring(c)),l.length>1?l.join(""):o}else{if(Array.isArray(o))return o.map(s);if(typeof o=="object"&&o!==null){const i={};for(const[a,c]of Object.entries(o))i[a]=s(c);return i}}return o};return s(e)}}function Mc(){return{type:ee.DESIGN_TOKEN,canResolve:Pe.canResolve.bind(Pe),resolve:Pe.resolve.bind(Pe)}}class Be{static canResolve(e,t){if(typeof e!="string"||e.length===0)return!1;if(ie.GEOMETRY_REF.test(e)||[/^point_[a-zA-Z0-9_]+$/,/^segment_[a-zA-Z0-9_]+$/,/^line_[a-zA-Z0-9_]+$/,/^triangle_[a-zA-Z0-9_]+$/,/^polygon_[a-zA-Z0-9_]+$/,/^circle_[a-zA-Z0-9_]+$/,/^angle_[a-zA-Z0-9_]+$/,/^vector_[a-zA-Z0-9_]+$/,/^arc_[a-zA-Z0-9_]+$/,/^ray_[a-zA-Z0-9_]+$/].some(o=>o.test(e)))return!0;if(t&&t.geometryPresets){let o;const i=e.match(ie.GEOMETRY_REF);return i?o=i[1]:o=e,o in t.geometryPresets}return["acute_triangle","right_triangle","equilateral_triangle","rectangle","parallelogram","horizontal_line","vertical_line","arrow_line","label_point","center_point","vertex_point","marker_point","left_triangle","right_triangle","base_segment","height_segment","base_arrow","height_arrow","full_rectangle"].includes(e)}static resolveVertexReference(e,t){if(console.error("🔍 GeometryRefResolver.resolveVertexReference:",{input:e,isRef:e&&typeof e=="object"&&"$ref"in e,refName:e?.$ref,hasContext:!!t.geometryPresets,pointFound:!!t.geometryPresets?.[e?.$ref]}),e&&typeof e=="object"&&"$ref"in e){const n=e.$ref;if(t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return console.error(`✅ 解析顶点引用 ${n}: 使用 position`,s.position),[s.position.x,s.position.y];if("x"in s&&"y"in s)return console.error(`✅ 解析顶点引用 ${n}: 使用 x/y`,{x:s.x,y:s.y}),[s.x,s.y]}return console.warn(`无法解析顶点引用: ${n}`),e}return Array.isArray(e)&&e.length===2?e:e&&typeof e=="object"&&"x"in e&&"y"in e?[e.x,e.y]:e}static resolve(e,t){if(!this.canResolve(e,t))throw new Error(`无法解析的几何引用: ${e}`);let n;const s=e.match(ie.GEOMETRY_REF);s?n=s[1]:n=e,console.error(`🔍 GeometryRefResolver.resolve: ref="${e}", geometryName="${n}"`),console.error(" Available geometryPresets:",Object.keys(t.geometryPresets||{}));const o=t.geometryPresets[n];if(!o)throw console.error(`❌ Geometry preset not found: ${n} in`,t.geometryPresets),new Error(`几何预设未找到: ${n}`);console.error("✅ Geometry resolved:",{name:n,type:o.type,hasVertices:"vertices"in o,verticesCount:o.vertices?o.vertices.length:0,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,geometryKeys:Object.keys(o)});const i={...o};return i.vertices&&Array.isArray(i.vertices)&&(i.vertices=i.vertices.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(c){return console.warn("顶点引用解析失败:",c),a}}),console.error(`🔍 GeometryRefResolver: 转换顶点格式,数量=${i.vertices.length}`,{sampleVertices:i.vertices.slice(0,3).map((a,c)=>({index:c,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})),i.endpoints&&Array.isArray(i.endpoints)&&(i.endpoints=i.endpoints.map(a=>{try{return a&&typeof a=="object"&&"$ref"in a?this.resolveVertexReference(a,t):Array.isArray(a)&&a.length===2?a:a&&typeof a=="object"&&"x"in a&&"y"in a?[a.x,a.y]:a}catch(c){return console.warn("端点引用解析失败:",c),a}})),i}static validate(e,t){if(!this.canResolve(e,t))return!1;let n;const s=e.match(ie.GEOMETRY_REF);return s?n=s[1]:n=e,n in t.geometryPresets}static getAvailableGeometryNames(e){return Object.keys(e.geometryPresets)}static resolveWithStyle(e,t){const n=this.resolve(e,t);if(n.styleRef&&t.stylePresets[n.styleRef]){const s=t.stylePresets[n.styleRef];return{...n,style:{...s}}}return n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`几何引用解析失败: ${s}`,o)}return n}static extractGeometryRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.geometryRef&&typeof s.geometryRef=="string"&&t.push(s.geometryRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.geometryRef&&typeof o.geometryRef=="string"&&t.push(o.geometryRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Fc(){return{type:ee.GEOMETRY_REF,canResolve:Be.canResolve.bind(Be),resolve:Be.resolve.bind(Be),validate:Be.validate.bind(Be)}}class Se{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.TRANSFORM_REF.test(e)?!0:["left_rotation","right_rotation","translation"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的变换引用: ${e}`);let n;const s=e.match(ie.TRANSFORM_REF);if(s?n=s[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n])return{...t.transformDefinitions[n]};const o={left_rotation:{type:"rotation",angle:-90,origin:[0,0]},right_rotation:{type:"rotation",angle:90,origin:[0,0]},translation:{type:"translation",dx:0,dy:0}};if(o[n])return{...o[n]};throw new Error(`变换定义未找到: ${n}`)}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.TRANSFORM_REF);return s?n=s[1]:n=e,t.transformDefinitions&&t.transformDefinitions[n]?!0:["left_rotation","right_rotation","translation"].includes(n)}static applyTransform(e,t){if(!t||!e)return e;const n={...e};switch(t.type){case"rotation":n.vertices=this.applyRotation(e.vertices,t.angle,t.origin);break;case"translation":n.vertices=this.applyTranslation(e.vertices,t.dx,t.dy);break;case"scale":n.vertices=this.applyScale(e.vertices,t.factor,t.origin);break;default:console.warn(`未知的变换类型: ${t.type}`)}return n}static applyRotation(e,t,n){if(!e||!Array.isArray(e))return e;const[s,o]=n,i=t*Math.PI/180,a=Math.cos(i),c=Math.sin(i);return e.map(([l,d])=>{const u=l-s,y=d-o;return[s+u*a-y*c,o+u*c+y*a]})}static applyTranslation(e,t,n){return!e||!Array.isArray(e)?e:e.map(([s,o])=>[s+t,o+n])}static applyScale(e,t,n){if(!e||!Array.isArray(e))return e;const[s,o]=n;return e.map(([i,a])=>{const c=i-s,l=a-o;return[s+c*t,o+l*t]})}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`变换引用解析失败: ${s}`,o)}return n}static extractTransformRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.transformRef&&typeof s.transformRef=="string"&&t.push(s.transformRef),Array.isArray(s.transformations)&&s.transformations.forEach(o=>{o.transformRef&&typeof o.transformRef=="string"&&t.push(o.transformRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Pc(){return{type:ee.TRANSFORM_REF,canResolve:Se.canResolve.bind(Se),resolve:Se.resolve.bind(Se),validate:Se.validate.bind(Se)}}class we{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.STYLE_REF.test(e)?!0:["primary","secondary","transparent","highlight","error","success","dashed","text_primary","text_heading_large","base_highlight","label_position","highlight_left","highlight_right","label_error"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的样式引用: ${e}`);let n;const s=e.match(ie.STYLE_REF);s?n=s[1]:n=e;const o=t.stylePresets[n];if(!o)throw new Error(`样式预设未找到: ${n}`);return this.resolveStylePreset(o,t)}static resolveStylePreset(e,t){const n={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(Pe.canResolve(o))try{n[s]=Pe.resolve(o,t)}catch(i){console.warn(`样式中的设计令牌解析失败: ${s}=${o}`,i),n[s]=o}}else o&&typeof o=="object"&&(n[s]=this.resolveStylePreset(o,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.STYLE_REF);return s?n=s[1]:n=e,n in t.stylePresets}static applyStyle(e,t){if(!e||!t)return e;const n={...e};return n.style=n.style?{...n.style,...t}:{...t},["strokeWidth","fillOpacity","strokeOpacity","dash"].forEach(o=>{t[o]!==void 0&&(n[o]=t[o])}),n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`样式引用解析失败: ${s}`,o)}return n}static extractStyleRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.styleRef&&typeof s.styleRef=="string"&&t.push(s.styleRef),s.style&&typeof s.style=="object"&&s.style.styleRef&&typeof s.style.styleRef=="string"&&t.push(s.style.styleRef),Array.isArray(s.shapes)&&s.shapes.forEach(o=>{o.styleRef&&typeof o.styleRef=="string"&&t.push(o.styleRef),o.style&&o.style.styleRef&&typeof o.style.styleRef=="string"&&t.push(o.style.styleRef)});for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}static createDefaultStyle(){return{fillColor:"#8ec5fc",fillOpacity:.3,strokeColor:"#4a90e2",strokeWidth:2}}}function Dc(){return{type:ee.STYLE_REF,canResolve:we.canResolve.bind(we),resolve:we.resolve.bind(we),validate:we.validate.bind(we)}}class Ve{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.LAYOUT_REF.test(e)?!0:["card","vertical","horizontal","grid","panel","vertical_centered","horizontal_centered","centered"].includes(e)}static resolve(e,t){if(!this.canResolve(e))throw new Error(`无法解析的布局引用: ${e}`);let n;const s=e.match(ie.LAYOUT_REF);if(s?n=s[1]:n=e,t.layoutPresets&&t.layoutPresets[n]){const i=t.layoutPresets[n];return this.resolveLayoutPreset(i,t)}const o={card:{type:"card",padding:"20px",theme:"light"},vertical:{type:"vertical",spacing:"15px",alignment:"start"},horizontal:{type:"horizontal",spacing:"15px",alignment:"center"}};if(o[n])return{...o[n]};throw new Error(`布局预设未找到: ${n}`)}static resolveLayoutPreset(e,t){const n={...e};for(const[s,o]of Object.entries(e))if(typeof o=="string"){if(Pe.canResolve(o))try{n[s]=Pe.resolve(o,t)}catch(i){console.warn(`布局中的设计令牌解析失败: ${s}=${o}`,i),n[s]=o}}else o&&typeof o=="object"&&(n[s]=this.resolveLayoutPreset(o,t));return n}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.LAYOUT_REF);return s?n=s[1]:n=e,t.layoutPresets&&t.layoutPresets[n]?!0:["card","vertical","horizontal"].includes(n)}static applyLayout(e,t){if(!e||!t)return e;const n={...e};return n.layout?n.layout={...n.layout,...t}:n.layout={...t},n}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`布局引用解析失败: ${s}`,o)}return n}static extractLayoutRefs(e){const t=[];for(const n of Object.values(e))if(n.layout&&n.layout.type&&typeof n.layout.type=="string"&&this.isLayoutRef(n.layout.type)&&t.push(n.layout.type),n.layout&&typeof n.layout=="object")for(const s of Object.values(n.layout))typeof s=="string"&&this.isLayoutRef(s)&&t.push(s);return[...new Set(t)]}static isLayoutRef(e){return ie.LAYOUT_REF.test(e)}static createDefaultLayout(){return{type:"card",padding:"20px",theme:"light"}}}function Lc(){return{type:ee.LAYOUT_REF,canResolve:Ve.canResolve.bind(Ve),resolve:Ve.resolve.bind(Ve),validate:Ve.validate.bind(Ve)}}class st{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.ANIMATION_REF.test(e)}static resolve(e,t){if(!this.canResolve(e))throw new me(B.ANIMATION_REF_NOT_FOUND,`无法解析的动画引用: ${e}`);const n=e.match(ie.ANIMATION_REF);if(!n)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画引用格式无效: ${e}`);const s=n[1],o=t.animationConfigs?.[s];if(!o)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置未找到: ${s}`);return this.resolveAnimationConfig(s,o,t)}static resolveAnimationConfig(e,t,n){if(!t.transforms||!Array.isArray(t.transforms))throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置格式错误: ${e} 缺少 transforms 数组`);const s=t.transforms.map((a,c)=>{if(!a.id)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 id 字段`);if(!a.type)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 type 字段`);if(!a.targetShapes||!Array.isArray(a.targetShapes))throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] 缺少 targetShapes 数组`);if(a.targetShapes.length===0)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}] targetShapes 不能为空`);a.targetShapes.forEach((u,y)=>{if(typeof u!="string"||u.trim()==="")throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置 ${e} 中 transform[${c}].targetShapes[${y}] 必须是有效的字符串 ID`)});const l=Gl(a.params),d=JSON.stringify(a.params).includes("control.value");return{id:a.id,type:a.type,params:l,targetShapes:a.targetShapes,usesControl:d}}),o={id:e,control:t.control,transforms:s,visualEffects:t.visualEffects||[],progressControl:t.progressControl},i=zl(o);if(!i.valid)throw new me(B.ANIMATION_REF_NOT_FOUND,`动画配置验证失败: ${e}
|
|
20
20
|
${i.errors?.join(`
|
|
21
|
-
`)}`);return o}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.ANIMATION_REF);return s?n=s[1]:n=e,n in(t.animationConfigs||{})}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`动画引用解析失败: ${s}`,o)}return n}static extractAnimationRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.animationRef&&typeof s.animationRef=="string"&&t.push(s.animationRef),s.chartConfig?.animationRef&&typeof s.chartConfig.animationRef=="string"&&t.push(s.chartConfig.animationRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Uc(){return{type:ee.ANIMATION_REF,canResolve:st.canResolve.bind(st),resolve:st.resolve.bind(st),validate:st.validate.bind(st)}}class Je{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!t,contextKeys:Object.keys(t||{}),animationDefinitionsKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[],animationConfigsKeys:t.animationConfigs?Object.keys(t.animationConfigs):[]}),!this.canResolve(e))throw new me(B.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const n=e.match(ie.SLIDER_REF),s=n?n[1]:e;let o=t.animationDefinitions?.[s];return!o&&t.animationConfigs&&(o=t.animationConfigs[s]),!o&&it?.animationDefinitions&&(o=it.animationDefinitions[s]),!o&&it?.animationConfigs&&(o=it.animationConfigs[s]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:s,hasRawConfig:!!o,rawConfig:o,animationDefinitions:t.animationDefinitions,animationConfigs:t.animationConfigs,hasGlobalContext:!!it}),o?this.validateAndTransformConfig(s,o):(console.warn(`⚠️ 滑块配置未找到: ${s},使用默认配置`),{...Gc,id:s})}static validateAndTransformConfig(e,t){if(!t.slider)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:n}=t,s=["position","length","orientation","min","max","step"];for(const o of s)if(!(o in n))throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${o} 字段`);if(!Array.isArray(n.position)||n.position.length!==2)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(n.orientation!=="horizontal"&&n.orientation!=="vertical")throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(n.min>=n.max)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(n.step<=0)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.step 必须大于 0`);return{id:e,slider:{position:n.position,length:n.length,orientation:n.orientation,min:n.min,max:n.max,step:n.step},progressIndicator:t.progressIndicator,duration:t.duration,easing:t.easing,description:t.description}}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ie.SLIDER_REF),s=n?n[1]:e;return s in(t.animationDefinitions||{})||s in(t.animationConfigs||{}),!0}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`滑块引用解析失败: ${s}`,o)}return n}static extractSliderRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.sliderRef&&typeof s.sliderRef=="string"&&t.push(s.sliderRef),s.chartConfig?.sliderRef&&typeof s.chartConfig.sliderRef=="string"&&t.push(s.chartConfig.sliderRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}const Gc={id:"default_slider",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"默认滑块配置(引用未找到时使用)"};function zc(){return{type:ee.SLIDER_REF,canResolve:Je.canResolve.bind(Je),resolve:Je.resolve.bind(Je),validate:Je.validate.bind(Je)}}class ot{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t,n){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const s=e.match(ie.GEOMETRY_TRANSFORM_REF),o=s?s[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${o}`,{hasGeometryTransformConfigs:!!t.geometryTransformConfigs,configKeys:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});const i=t.geometryTransformConfigs?.[o];if(!i)throw new me(B.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${o}`,{reference:e,configId:o,availableConfigs:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=n?this.applyOverride(i,n):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,t){const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&(n[s]=o);return t.shapes&&(n.shapes={static:[...n.shapes?.static||[]],animated:[...n.shapes?.animated||[]]},t.shapes.static&&(n.shapes.static=t.shapes.static),t.shapes.animated&&(n.shapes.animated=t.shapes.animated)),t.transform&&(n.transform={...n.transform,...t.transform}),n}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ie.GEOMETRY_TRANSFORM_REF),s=n?n[1]:e;return!!t.geometryTransformConfigs?.[s]}static batchResolve(e,t,n){const s={};for(const o of e)if(this.canResolve(o)&&this.validate(o,t))try{const i=n?.[o];s[o]=this.resolve(o,t,i)}catch(i){console.warn(`几何变换引用解析失败: ${o}`,i)}return s}static extractFromContentBlock(e){return!e||typeof e!="object"?null:e.geometryTransformRef&&typeof e.geometryTransformRef=="string"?e.geometryTransformRef:null}static extractFromContentBlocks(e){const t=[];for(const n of e){const s=this.extractFromContentBlock(n);s&&t.push(s)}return[...new Set(t)]}}function Bc(){return{type:ee.GEOMETRY_TRANSFORM_REF,canResolve:ot.canResolve.bind(ot),resolve:ot.resolve.bind(ot),validate:ot.validate.bind(ot)}}const Pr={geometryRef:ee.GEOMETRY_REF,styleRef:ee.STYLE_REF,layoutRef:ee.LAYOUT_REF,boardRef:ee.BOARD_REF,animationRef:ee.ANIMATION_REF,transformRef:ee.TRANSFORM_REF,appearanceRef:ee.STYLE_REF,geometryTransformRef:ee.GEOMETRY_TRANSFORM_REF,sliderRef:ee.SLIDER_REF,$ref:ee.GEOMETRY_REF};class Vc{static extractRefs(e){const t=[],n=new Set,s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o)){if(i in Pr){if(typeof a=="string"){const c=Pr[i],l=`${i}:${a}`;n.has(l)||(n.add(l),t.push({ref:a,type:c,path:i,value:a,fieldName:i,combined:l}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(l=>{const d=`$ref:${l}`;n.has(d)||(n.add(d),t.push({ref:l,type:ee.GEOMETRY_REF,path:"$ref",value:l,fieldName:"$ref",combined:d}))});continue}if(Array.isArray(a)){a.forEach(c=>s(c));continue}typeof a=="object"&&s(a)}};return s(e),t}static extractDesignTokens(e){const t=[],n=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let s;for(;(s=n.exec(e))!==null;)t.push(s[0]);return t}static calculateStats(e){const t=this.extractRefs(e).map(o=>o.ref),n={},s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o))i in Pr?n[i]=(n[i]||0)+1:typeof a=="object"&&s(a)};return s(e),{totalRefs:t.length,uniqueRefs:new Set(t).size,fieldCounts:n}}}class mt{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(Mc()),this.register(Fc()),this.register(Pc()),this.register(Dc()),this.register(Lc()),this.register(Uc()),this.register(zc()),this.register(Bc())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(t=>t.type===e)}getResolverForRef(e){return this.resolvers.find(t=>t.canResolve(e))}resolve(e,t){if(typeof e!="string"){const s=this.getResolverByType(e.type);if(!s)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return s.resolve(e.value,t)}catch(o){throw new Error(`解析器 ${e.type} 解析 ${e.combined} 失败: ${o}`)}}const n=this.resolvers.filter(s=>s.canResolve(e));if(n.length===0)throw new Error(`没有找到适合的解析器: ${e}`);for(const s of n)try{return s.resolve(e,t)}catch(o){console.debug(`解析器 ${s.type} 解析 ${e} 失败:`,o);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,t){const n={};for(const s of e)try{const o=this.resolve(s,t),i=typeof s=="string"?s:s.combined;n[i]=o}catch(o){const i=typeof s=="string"?s:s.combined;console.warn(`引用解析失败: ${i}`,o)}return n}extractAllRefsEnhanced(e){try{return Vc.extractRefs(e)}catch(t){return console.warn("ReferenceExtractor 提取失败:",t),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(n=>n.combined)}extractAllRefsLegacy(e){const t=[],n=s=>{if(!(!s||typeof s!="object"))for(const[o,i]of Object.entries(s))if(o.endsWith("Ref")&&typeof i=="string")t.push(i);else if(typeof i=="string"&&i.includes("$")){const a=i.match(/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g);a&&t.push(...a)}else Array.isArray(i)?i.forEach(a=>n(a)):typeof i=="object"&&n(i)};return n(e),[...new Set(t)]}validate(e,t){const n=this.getResolverForRef(e);if(!n)return!1;if(n.validate)return n.validate(e,t);try{return n.resolve(e,t),!0}catch{return!1}}}function No(){return new mt}class er{static transform(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;console.error("🔄 GraphTransformer.transform START for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o,contextGeometryKeys:Object.keys(t.geometryPresets||{})}),console.error("🎯 GraphTransformer.transform called for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o}),e.shapes&&Array.isArray(e.shapes)&&console.warn(`📊 GraphTransformer contentBlock shapes (${e.shapes.length}):`,e.shapes.map(a=>({id:a.id,type:a.type,geometryRef:a.geometryRef,styleRef:a.styleRef})));const i={...e,type:ye.GRAPH};if(!s)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,t),delete i.boardRef),Array.isArray(i.shapes)&&(console.error(`🎯 GraphTransformer处理shapes数组,数量: ${i.shapes.length}`),i.shapes=i.shapes.map((a,c)=>(console.error(` 🎯 处理shape[${c}]:`,{id:a.id,geometryRef:a.geometryRef,styleRef:a.styleRef,keys:Object.keys(a)}),this.transformShape(a,t,{strictMode:o})))),i.styleRef){try{const a=we.resolve(i.styleRef,t);i.style=a}catch(a){if(o)throw a;console.warn(`图形样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}if(i.animationRef){console.warn(`🎬 GraphTransformer处理animationRef: ${i.animationRef}`);try{const a=i.animationRef.startsWith("animationRef:")?i.animationRef:`animationRef:${i.animationRef}`,c=st.resolve(a,t);console.warn(" 动画配置解析结果:",{animationId:c.id,transformCount:c.transforms.length,hasControl:!!c.control,controlConfig:c.control,hasVisualEffects:!!c.visualEffects,visualEffectsCount:c.visualEffects?.length||0}),i.animation=c,i.transformDefinitions&&(console.warn(" 清理旧的 transformDefinitions(被 animation 替代)"),delete i.transformDefinitions)}catch(a){if(o)throw a;console.warn(`❌ 动画配置解析失败: ${i.animationRef}`,a)}delete i.animationRef}else i.animation&&(console.warn("🎬 GraphTransformer检测到内联动画配置:",{animationId:i.animation.id,transformCount:i.animation.transforms?.length||0}),i.animation.transforms&&Array.isArray(i.animation.transforms)?console.warn(` 内联动画配置有效,transforms 数量: ${i.animation.transforms.length}`):(console.warn(" ⚠️ 内联动画配置格式无效,缺少 transforms 数组"),delete i.animation));return i}catch(a){if(o)throw a;return console.warn("图形转换失败:",a),i}}static transformShape(e,t,n={}){const{strictMode:s=!1}=n;console.error("🔄 GraphTransformer.transformShape START for shape:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:"geometryRef"in e,geometryRef:e.geometryRef,hasStyleRef:"styleRef"in e,styleRef:e.styleRef,allShapeKeys:Object.keys(e),contextGeometryKeys:Object.keys(t.geometryPresets||{})}),(e.id==="base_line"||e.id==="height_line")&&console.error(`🔍 特别处理 ${e.id}:`,{id:e.id,type:e.type,geometryRef:e.geometryRef,styleRef:e.styleRef,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints)});let o={...e};e.type==="point"&&console.warn(`📌 GraphTransformer processing point ${e.id}:`,{id:e.id,type:e.type,position:e.position,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),shapeKeys:Object.keys(e)});try{if(o.geometryRef){console.warn(`🔄 GraphTransformer processing geometryRef: ${o.geometryRef} for shape ${o.id}`,{shapeId:o.id,shapeType:o.type,geometryRef:o.geometryRef,contextHasGeometryPresets:!!t.geometryPresets,geometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});try{const i=Be.resolve(o.geometryRef,t);console.warn(` Geometry resolved for ${o.geometryRef}:`,{type:i.type,hasVertices:"vertices"in i,vertices:i.vertices,hasPosition:"position"in i,position:i.position,hasEndpoints:"endpoints"in i,endpoints:i.endpoints,endpointsIsArray:Array.isArray(i.endpoints),geometryKeys:Object.keys(i)});const a=o.type,c=o.content,l={...o};Object.assign(o,i),o.id=e.id,a!==void 0&&(o.type=a),c!==void 0&&(o.content=c),console.warn(` After merge for ${o.id}:`,{type:o.type,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:"undefined",position:o.position,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),transformedShapeKeys:Object.keys(o)});const d=o.type;let u=!1;const y=t.geometryPresets[o.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:o.geometryRef,originalGeometryExists:!!y,originalGeometryType:y?.type,originalGeometryKeys:y?Object.keys(y):[],hasVertices:y&&"vertices"in y,verticesIsArray:y&&Array.isArray(y.vertices),verticesLength:y?.vertices?.length,contextGeometryPresetsKeys:Object.keys(t.geometryPresets||{})}),y&&y.vertices&&Array.isArray(y.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:y.vertices,hasWithLabel:"withLabel"in y,withLabel:y.withLabel,hasLabel:"label"in y,label:y.label}),o.verticesConfig||(o.verticesConfig={}),y.vertices.forEach((m,h)=>{if(console.warn(`🔍 DEBUG: 检查顶点${h}:`,{vertex:m,isObject:m&&typeof m=="object",hasDollarRef:m&&typeof m=="object"&&"$ref"in m,refName:m?.$ref}),m&&typeof m=="object"&&"$ref"in m){const g=m.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${g},检查context.geometryPresets`),t.geometryPresets&&t.geometryPresets[g]){const p=t.geometryPresets[g];console.warn(`🔍 DEBUG: 找到点定义 ${g}:`,p),p.name?(o.verticesConfig[h]||(o.verticesConfig[h]={}),o.verticesConfig[h].name=p.name,console.warn(`✅ 从原始几何定义提取顶点${h}名字: ${p.name}`)):console.warn(`⚠️ 点定义 ${g} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${g}`)}else console.warn(`⚠️ 顶点${h}不是$ref对象`)}),y.withLabel!==void 0&&(o.verticesConfig.withLabel=y.withLabel),y.label&&typeof y.label=="object"){const m=y.label;m.offset&&Array.isArray(m.offset)&&m.offset.length>=2&&(o.verticesConfig.offset=m.offset),m.fontSize!==void 0&&(o.verticesConfig.fontSize=m.fontSize),m.color&&(o.verticesConfig.color=m.color),m.anchorX&&(o.verticesConfig.anchorX=m.anchorX),m.anchorY&&(o.verticesConfig.anchorY=m.anchorY)}console.warn("✅ 构建的verticesConfig:",o.verticesConfig)}if(d==="segment"||d==="line"?u="endpoints"in o&&Array.isArray(o.endpoints):d==="point"?u="position"in o&&o.position!==void 0:d==="polygon"||d==="triangle"||d==="rectangle"||d==="parallelogram"?u="vertices"in o&&Array.isArray(o.vertices):u="vertices"in o&&Array.isArray(o.vertices)||"endpoints"in o&&Array.isArray(o.endpoints)||"position"in o&&o.position!==void 0,u||(console.error(`❌ ERROR: After geometryRef merge, shape ${o.id} (type: ${d}) has no valid geometry properties!`),console.error(" geometry keys:",Object.keys(i)),console.error(" geometry.type:",i.type),console.error(" transformedShape keys:",Object.keys(o))),i.styleRef){console.error(`🎨 GraphTransformer处理几何styleRef: ${i.styleRef}`);const m=we.resolve(i.styleRef,t);console.error(" 几何样式解析结果:",m),o.style=m}}catch(i){if(s)throw i;console.error(`❌ 图形几何解析失败: ${o.geometryRef}`,i),console.error(` shape id: ${o.id}, type: ${o.type}`),console.error(" context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):"undefined")}delete o.geometryRef}if(o.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${o.styleRef}, shape id: ${o.id}`);try{const i=we.resolve(o.styleRef,t);console.error(" 形状样式解析成功:",i);const{id:a,...c}=i;o={...o,...c,style:{...o.style,...i}}}catch(i){if(s)throw i;console.warn(`图形元素样式解析失败: ${o.styleRef}`,i),delete o.style}delete o.styleRef}if(Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(i=>this.transformTransform(i,t,{strictMode:s}))),o.label&&typeof o.label=="object"&&(o.label=this.transformLabel(o.label,t)),console.warn(`🔍 Checking segment conversion for ${o.id}:`,{type:o.type,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,shapeKeys:Object.keys(o)}),o=this.convertShapeCoordinates(o,t),o.type==="segment"&&Array.isArray(o.endpoints)&&o.endpoints.length>=2){console.warn(`🔄 Converting segment to line for ${o.id}:`,{originalType:o.type,endpoints:o.endpoints}),o.type="line";const i=this.resolvePointReference(o.endpoints[0],t),a=this.resolvePointReference(o.endpoints[1],t);Array.isArray(i)&&i.length>=2?o.start={x:i[0],y:i[1]}:i&&typeof i=="object"&&"x"in i&&"y"in i?o.start=i:o.start=o.endpoints[0],Array.isArray(a)&&a.length>=2?o.end={x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?o.end=a:o.end=o.endpoints[1],delete o.endpoints}return console.warn(`✅ GraphTransformer finished transforming shape ${o.id} (${o.type}):`,{id:o.id,type:o.type,hasVertices:"vertices"in o,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:0,hasVerticesConfig:"verticesConfig"in o,verticesConfig:o.verticesConfig,verticesConfigKeys:o.verticesConfig?Object.keys(o.verticesConfig):[],hasPosition:"position"in o,position:o.position,hasStart:"start"in o,start:o.start,hasEnd:"end"in o,end:o.end,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,hasGeometryRef:"geometryRef"in o,geometryRef:o.geometryRef,keys:Object.keys(o)}),o}catch(i){if(s)throw i;return console.warn("图形元素转换失败:",i),o}}static resolvePointReference(e,t){if(!e||typeof e!="object")return e;if("$ref"in e){const n=e.$ref;if(t&&t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}if("geometryRef"in e){const n=e.geometryRef;if(t&&t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}return e}static convertShapeCoordinates(e,t){if(!e||typeof e!="object")return e;console.warn("🔄 GraphTransformer.convertShapeCoordinates START for shape:",{id:e.id,type:e.type,hasVertices:"vertices"in e,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e)});const n={...e};if(n.position){if(Array.isArray(n.position)&&n.position.length>=2)console.warn(`🔄 Converting position array to object for ${n.id}:`,{shapeId:n.id,positionArray:n.position,convertedTo:{x:n.position[0],y:n.position[1]}}),n.position={x:n.position[0],y:n.position[1]};else if(typeof n.position=="object"){const s=this.resolvePointReference(n.position,t);s&&typeof s=="object"&&(n.position=s)}}if(Array.isArray(n.vertices)){const s=n.verticesConfig?{...n.verticesConfig}:{};if(console.warn("🔍 convertShapeCoordinates: 初始化 verticesConfig",{hasExisting:!!n.verticesConfig,existingKeys:n.verticesConfig?Object.keys(n.verticesConfig):[],verticesConfigKeys:Object.keys(s)}),n.vertices=n.vertices.map((o,i)=>{const a=this.resolvePointReference(o,t);let c=null;if(o&&typeof o=="object"&&"$ref"in o){const l=o.$ref;t&&t.geometryPresets&&t.geometryPresets[l]&&(c=t.geometryPresets[l],console.warn(`📌 Found point definition for ${l} at vertex ${i}:`,{hasWithLabel:"withLabel"in c,withLabel:c.withLabel,hasLabel:"label"in c,labelKeys:c.label?Object.keys(c.label):"none"}),c.name&&(s[i]||(s[i]={}),s[i].name=c.name))}return Array.isArray(a)&&a.length>=2?{x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?a:(o&&typeof o=="object"&&("$ref"in o||"geometryRef"in o),o)}),n.withLabel!==void 0||n.label){const o={withLabel:n.withLabel!==void 0?n.withLabel:!0};if(n.label&&typeof n.label=="object"){const a=n.label;a.offset&&Array.isArray(a.offset)&&a.offset.length>=2&&(o.offset=a.offset),a.fontSize!==void 0&&(o.fontSize=a.fontSize),a.color&&(o.color=a.color),a.anchorX&&(o.anchorX=a.anchorX),a.anchorY&&(o.anchorY=a.anchorY)}const i={...o};for(const a in s)isNaN(Number(a))||(i[a]||(i[a]={}),Object.assign(i[a],s[a]));n.verticesConfig=i,console.warn(`✅ Added merged verticesConfig for polygon ${n.id}:`,i)}else Object.keys(s).length>0&&(n.verticesConfig=s,console.warn(`✅ Added verticesConfig for polygon ${n.id}:`,s))}if(Array.isArray(n.endpoints)&&(n.endpoints=n.endpoints.map(s=>{const o=this.resolvePointReference(s,t);return Array.isArray(o)&&o.length>=2?{x:o[0],y:o[1]}:o&&typeof o=="object"&&"x"in o&&"y"in o?o:(s&&typeof s=="object"&&("$ref"in s||"geometryRef"in s),s)})),Array.isArray(n.center)&&n.center.length>=2)n.center={x:n.center[0],y:n.center[1]};else if(n.center&&typeof n.center=="object"){const s=this.resolvePointReference(n.center,t);s&&typeof s=="object"&&(n.center=s)}if(n.start){if(Array.isArray(n.start)&&n.start.length>=2)n.start={x:n.start[0],y:n.start[1]};else if(typeof n.start=="object"){const s=this.resolvePointReference(n.start,t);s&&typeof s=="object"&&(n.start=s)}}if(n.end){if(Array.isArray(n.end)&&n.end.length>=2)n.end={x:n.end[0],y:n.end[1]};else if(typeof n.end=="object"){const s=this.resolvePointReference(n.end,t);s&&typeof s=="object"&&(n.end=s)}}for(const[s,o]of Object.entries(n))Array.isArray(o)?n[s]=o.map(i=>typeof i=="object"?this.convertShapeCoordinates(i,t):i):o&&typeof o=="object"&&(n[s]=this.convertShapeCoordinates(o,t));return n}static transformTransform(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.transformRef){try{const i=Se.resolve(o.transformRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformLabel(e,t){const n={...e};if(n.styleRef){try{const s=we.resolve(n.styleRef,t);n.style=s}catch(s){console.warn(`标签样式解析失败: ${n.styleRef}`,s)}delete n.styleRef}return n}static resolveBoardConfig(e,t){if(t.boardDefinitions&&t.boardDefinitions[e])return t.boardDefinitions[e];const n={default:{originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1},extended:{originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1}};return n[e]||n.default}static validate(e){const t=[];return e?(e.type!==ye.GRAPH&&t.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&t.push("图形内容块 shapes 数组不能为空"):t.push("图形内容块缺少 shapes 数组"),t):(t.push("图形内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(s=>s.type===ye.GRAPH).map(s=>this.transform(s,t,n))}}function Wc(){return{type:ye.GRAPH,transform:er.transform.bind(er),validate:er.validate.bind(er)}}class tr{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const t={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:t,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:t.static.length,animatedLength:t.animated.length}),t}static transform(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;if(e.geometryTransformRef){console.error("🔍 GeometryTransformTransformer.transform: 检测到几何变换引用",{geometryTransformRef:e.geometryTransformRef,hasOverride:!!e.override});try{if(s){console.error("🔍 GeometryTransformTransformer: 解析 geometryTransformRef:",e.geometryTransformRef);const d=ot.resolve(e.geometryTransformRef,t,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",d),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(d||{}));const u={type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:d}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",u.metadata.config),u.metadata.config&&typeof u.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),u.metadata.config=this.transformConfig(u.metadata.config,t,{strictMode:o})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",u),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",u.metadata.config),u}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:6,height:4,unit:"cm",strategy:"default",shapes:{static:[],animated:[]},transform:{type:"composite",transforms:[]}}}}}catch(d){if(o)throw d;console.error("❌ 几何变换引用解析失败:",d),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",t.geometryTransformConfigs)}}const i=e.base||e.config?.base||t.basicInfo?.base||0,a=e.height||e.config?.height||t.basicInfo?.height||0,c=e.unit||e.config?.unit||t.basicInfo?.baseUnit||"cm",l={...e,type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:i,height:a,unit:c,...e.config||{},shapes:this.normalizeShapes(e.shapes||e.config?.shapes),transform:e.transform||e.config?.transform||{},animation:e.animation||e.config?.animation||{},boardConfig:e.boardConfig||e.config?.boardConfig||{}}}};if(console.error("🔍 GeometryTransformTransformer.transform: 转换后配置 =",{metadataConfig:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasTransformRef:!!e.transformRef,transformRef:e.transformRef,originalContentBlock:e}),delete l.config,delete l.base,delete l.height,delete l.unit,delete l.shapes,delete l.transform,delete l.animation,delete l.boardConfig,!s)return l;try{if(l.geometryRef){try{const d=Be.resolve(l.geometryRef,t);if(l.metadata.config||(l.metadata.config={}),Object.assign(l.metadata.config,d),d.styleRef){const u=we.resolve(d.styleRef,t);l.metadata.config.style=u}}catch(d){if(o)throw d;console.warn(`几何变换几何解析失败: ${l.geometryRef}`,d)}delete l.geometryRef}if(l.transformRef){try{const d=Se.resolve(l.transformRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.transform||(l.metadata.config.transform={}),Object.assign(l.metadata.config.transform,d)}catch(d){if(o)throw d;console.warn(`几何变换变换解析失败: ${l.transformRef}`,d)}delete l.transformRef}if(console.error("🔍 GeometryTransformTransformer.transform: 检查 metadata.config",{hasMetadata:!!l.metadata,hasConfig:!!l.metadata?.config,configType:l.metadata?.config?typeof l.metadata.config:"undefined",configIsObject:l.metadata?.config?typeof l.metadata.config=="object":!1,configKeys:l.metadata?.config?Object.keys(l.metadata.config):[]}),l.metadata?.config&&typeof l.metadata.config=="object"?(console.error("🔍 GeometryTransformTransformer.transform: 调用 transformConfig"),l.metadata.config=this.transformConfig(l.metadata.config,t,{strictMode:o}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),l.styleRef){try{const d=we.resolve(l.styleRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.style=d}catch(d){if(o)throw d;console.warn(`几何变换样式解析失败: ${l.styleRef}`,d)}delete l.styleRef}if(l.animationRef){try{const d=this.resolveAnimationConfig(l.animationRef,t,{strictMode:o});l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层动画引用解析失败: ${l.animationRef}`,d)}delete l.animationRef}if(l.sliderRef){try{const d=Je.resolve(l.sliderRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层滑块引用解析失败: ${l.sliderRef}`,d)}delete l.sliderRef}if(l.boardRef){console.error("🔍 GeometryTransformTransformer.transform: 处理顶层 boardRef",{boardRef:l.boardRef,hasMetadataConfig:!!l.metadata?.config,currentBoardConfig:l.metadata?.config?.boardConfig});try{const d=this.resolveBoardConfig(l.boardRef,t,{strictMode:o});console.error("🔍 解析后的 boardConfig:",d),l.metadata.config||(l.metadata.config={}),l.metadata.config.boardConfig={...d,...l.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",l.metadata.config.boardConfig)}catch(d){if(o)throw d;console.warn(`顶层画板引用解析失败: ${l.boardRef}`,d)}delete l.boardRef}if(l.metadata?.config?.boardConfig&&typeof l.metadata.config.boardConfig=="object"){const d=l.metadata.config.boardConfig;(!d.boundingBox||!Array.isArray(d.boundingBox)||d.boundingBox.length!==4)&&(console.error("🔍 GeometryTransformTransformer: boardConfig 缺少 boundingBox,使用默认值"),d.boundingBox=[0,7,10,0],d.originX=d.originX??2,d.originY=d.originY??2,d.keepAspectRatio=d.keepAspectRatio??!0,d.showGrid=d.showGrid??!1,d.showAxis=d.showAxis??!1,d.description=d.description||"默认画板配置")}return console.error("🔍 GeometryTransformTransformer.transform: 最终转换结果 =",{type:l.type,metadataConfig:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasTransform:!!l.metadata?.config?.transform,transform:l.metadata?.config?.transform,hasAnimation:!!l.metadata?.config?.animation,animation:l.metadata?.config?.animation,hasBoardConfig:!!l.metadata?.config?.boardConfig,boardConfig:l.metadata?.config?.boardConfig}),l}catch(d){if(o)throw d;return console.warn("几何变换转换失败:",d),l}}static transformConfig(e,t,n={}){const{strictMode:s=!1}=n,o={...e},i={};if(o.shapes&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 shapes"),console.error(" transformedConfig.shapes:",o.shapes),o.shapes.static&&(console.error(` 处理 static shapes (${o.shapes.static.length}):`),o.shapes.static=o.shapes.static.map((a,c)=>{console.error(` 处理 static shape[${c}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:s});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 static shape[${c}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l})),o.shapes.animated&&(console.error(` 处理 animated shapes (${o.shapes.animated.length}):`),o.shapes.animated=o.shapes.animated.map((a,c)=>{console.error(` 处理 animated shape[${c}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:s});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 animated shape[${c}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l}))),o.transform){if(o.transform.transformRef)try{const a=Se.resolve(o.transform.transformRef,t);o.transform={...a,...o.transform,transformRef:void 0},console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transform 对象中的 transformRef",{originalTransformRef:o.transform.transformRef,resolvedTransform:a,mergedTransform:o.transform})}catch(a){if(s)throw a;console.warn(`Transform ref解析失败: ${o.transform.transformRef}`,a)}o.transform=this.normalizeTransformConfig(o.transform,i),Array.isArray(o.transform.transforms)&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transforms 数组",{transformsLength:o.transform.transforms.length,transforms:o.transform.transforms}),o.transform.transforms=o.transform.transforms.map((a,c)=>{if(console.error(`🔍 处理 transform[${c}]:`,{type:typeof a,isString:typeof a=="string",isObject:typeof a=="object"&&a!==null,transformItem:a,hasTransformRef:a&&typeof a=="object"&&"transformRef"in a,transformRef:a&&typeof a=="object"?a.transformRef:void 0}),typeof a=="string"){if(console.error(`🔍 transform[${c}] 是字符串格式`),a.startsWith("transformRef:")){const l=a.replace("transformRef:","");console.error(`🔍 解析 transformRef 字符串: ${l}`);try{const d=Se.resolve(l,t);console.error(`🔍 transform[${c}] 解析成功:`,d);const u=this.normalizeTransformConfig(d,i);return console.error(`🔍 transform[${c}] 标准化后:`,u),u}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}try{const l=Se.resolve(a,t);return this.normalizeTransformConfig(l,i)}catch(l){if(s)throw l;return console.warn(`Transform ref解析失败: ${a}`,l),a}}else if(a&&typeof a=="object"&&a.transformRef){const l=a.transformRef;console.error(`🔍 transform[${c}] 是对象格式,refName=${l}`);try{const d=Se.resolve(l,t);console.error(`🔍 transform[${c}] 解析成功:`,d);const u={...d,...a,transformRef:void 0};console.error(`🔍 transform[${c}] 合并后:`,u);const y=this.normalizeTransformConfig(u,i);return console.error(`🔍 transform[${c}] 标准化后:`,y),y}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${c}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${c}] 未处理,返回原始值:`,a),a}))}if(o.geometry&&typeof o.geometry=="object"&&(o.geometry=this.transformGeometry(o.geometry,t,{strictMode:s})),Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(a=>{if(a.transformRef)try{const c=Se.resolve(a.transformRef,t);return{...a,...c,transformRef:void 0}}catch(c){if(s)throw c;return console.warn(`Transformations解析失败: ${a.transformRef}`,c),a}return a})),o.style&&typeof o.style=="object"&&(o.style=this.transformStyle(o.style,t,{strictMode:s})),o.animationRef){try{const a=this.resolveAnimationConfig(o.animationRef,t,{strictMode:s});o.animation={...a,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`动画引用解析失败: ${o.animationRef}`,a)}delete o.animationRef}if(o.sliderRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 sliderRef",{sliderRef:o.sliderRef,hasAnimationDefinitions:!!t.animationDefinitions,animationDefinitionKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[]});try{const a={...it,...t,animationDefinitions:t.animationDefinitions||it.animationDefinitions},c=Je.resolve(o.sliderRef,a);o.animation={...c,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`滑块引用解析失败: ${o.sliderRef}`,a)}delete o.sliderRef}if(o.boardRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 config 中的 boardRef",{boardRef:o.boardRef,currentBoardConfig:o.boardConfig});try{const a=this.resolveBoardConfig(o.boardRef,t,{strictMode:s});console.error("🔍 解析后的 boardConfig (config):",a),o.boardConfig={...a,...o.boardConfig||{}},console.error("🔍 设置后的 transformedConfig.boardConfig:",o.boardConfig)}catch(a){if(s)throw a;console.warn(`画板引用解析失败: ${o.boardRef}`,a)}delete o.boardRef}return o}static normalizeTransformConfig(e,t){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:t?Object.keys(t):[],geometryRefToShapeId:t});const n={...e};switch(!n.type&&n.config&&n.config.type&&(n.type=n.config.type),n.type){case"rotation":if(n.config){if(n.rotation={...n.config},n.rotation.center&&typeof n.rotation.center=="object"){const s=n.rotation.center;"x"in s&&"y"in s&&(n.rotation.center=[s.x,s.y])}delete n.config}break;case"translation":n.config&&(n.translation={...n.config},delete n.config);break;case"scale":if(n.config){if(n.scale={...n.config},n.scale.center&&typeof n.scale.center=="object"){const s=n.scale.center;"x"in s&&"y"in s&&(n.scale.center=[s.x,s.y])}delete n.config}break;case"composite":n.config&&Array.isArray(n.config.transforms)&&(n.composite=n.config.transforms.map(s=>this.normalizeTransformConfig(s,t)),delete n.config);break;default:if(n.config){const{type:s,...o}=n.config;Object.assign(n,o),delete n.config}}if(n.targetGroup&&t){const s=n.targetGroup;let o;if(t[s])o=t[s],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:s,mapped:o,type:"exact"});else{const i=Object.keys(t).find(a=>{if(a.startsWith(s+"_")||a===s||a.includes(s))return!0;const c=a.split("_"),l=s.split("_");return c.some(d=>l.includes(d))});i&&(o=t[i],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 启发式匹配 targetGroup",{original:s,geometryRef:i,mapped:o,type:"heuristic"}))}o?n.targetGroup=o:console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 无法映射 targetGroup",{original:s,geometryRefToShapeId:t,warning:"targetGroup 无法映射到任何 shapeId,可能导致旋转失败"})}return e.targetGroup&&!n.targetGroup&&(n.targetGroup=e.targetGroup),console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig:",{input:e,output:n,hasRotation:!!n.rotation,hasTranslation:!!n.translation,hasScale:!!n.scale,hasComposite:!!n.composite}),n}static transformShape(e,t,n={}){console.error("🔍 transformShape 被调用:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasStyleRef:!!e.styleRef,styleRef:e.styleRef,shapeKeys:Object.keys(e),contextHasGeometryPresets:!!t.geometryPresets,contextGeometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});const{strictMode:s=!1}=n,o={...e};if(o.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",o.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",t.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=Be.resolve(o.geometryRef,t);console.error("🔍 transformShape: geometry 解析结果:",i),Object.assign(o,i),console.error("🔍 transformShape: 合并后的 shape:",o),o.vertices&&Array.isArray(o.vertices)&&console.error("🔍 transformShape: 顶点数据:",{count:o.vertices.length,sample:o.vertices.slice(0,3).map((a,c)=>({index:c,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})}catch(i){if(console.error("🔍 transformShape: geometryRef 解析错误:",i),s)throw i;console.warn(`Shape geometryRef解析失败: ${o.geometryRef}`,i)}delete o.geometryRef,console.error("🔍 transformShape: 删除 geometryRef 后的 shape:",o)}if(o.styleRef){try{const i=we.resolve(o.styleRef,t);o.style=i}catch(i){if(s)throw i;console.warn(`Shape styleRef解析失败: ${o.styleRef}`,i)}delete o.styleRef}if(o.metadata||(o.metadata={}),!o.metadata.id&&o.id&&(o.metadata.id=o.id),o.withLabel!==void 0&&(o.metadata.showLabel=o.withLabel,delete o.withLabel),o.label&&(typeof o.label=="object"?o.metadata.label=o.label.text||o.metadata.id||"":typeof o.label=="string"&&(o.metadata.label=o.label),delete o.label),o.metadata.showLabel&&!o.metadata.label&&o.metadata.id&&(o.metadata.label=o.metadata.id),o.metadata.id){const i=o.metadata.id.toLowerCase();i.includes("left")?o.metadata.rotationGroup="left":i.includes("right")?o.metadata.rotationGroup="right":o.metadata.rotationGroup=o.metadata.id}if(o.type==="point"&&o.position){console.error("🔍 transformShape: 转换point为circle:",{shapeId:o.metadata?.id,position:o.position,originalType:o.type});const i=o.position.x,a=o.position.y,c=.1;o.type="circle",o.vertices=[[i,a],[i+c,a]],delete o.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:o.type,vertices:o.vertices})}return o}static transformGeometry(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.geometryRef){try{const i=Be.resolve(o.geometryRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`几何对象解析失败: ${o.geometryRef}`,i)}delete o.geometryRef}return o}static transformTransform(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.transformRef){try{const i=Se.resolve(o.transformRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换对象解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformStyle(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.styleRef){try{const i=we.resolve(o.styleRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`样式对象解析失败: ${o.styleRef}`,i)}delete o.styleRef}return o}static resolveAnimationConfig(e,t,n={}){const{strictMode:s=!1}=n;if(!e||typeof e!="string"){if(s)throw new Error(`无效的动画引用: ${e}`);return console.warn(`无效的动画引用: ${e}`),{}}try{const o=e.replace("animationRef:","");if(t.animationDefinitions&&t.animationDefinitions[o])return{...t.animationDefinitions[o]};if(s)throw new Error(`动画引用未找到: ${o}`);const i=this.getFallbackAnimationConfig(o);return console.warn(`动画引用未在上下文中找到,使用回退配置: ${o}`),i}catch(o){if(s)throw o;return console.warn(`动画配置解析失败: ${e}`,o),{}}}static resolveBoardConfig(e,t,n={}){const{strictMode:s=!1}=n;if(!e||typeof e!="string"){if(s)throw new Error(`无效的画板引用: ${e}`);return console.warn(`无效的画板引用: ${e}`),{}}try{const o=e.replace("boardRef:","");if(console.error("🔍 GeometryTransformTransformer.resolveBoardConfig:",{boardRef:e,refName:o,hasContextBoardDefinitions:!!t.boardDefinitions,contextBoardDefinitionKeys:t.boardDefinitions?Object.keys(t.boardDefinitions):[],hasRefInContext:t.boardDefinitions&&!!t.boardDefinitions[o]}),t.boardDefinitions&&t.boardDefinitions[o]){const a={...t.boardDefinitions[o]};return console.error("🔍 从上下文获取画板配置:",a),a}if(s)throw new Error(`画板引用未找到: ${o}`);const i=this.getFallbackBoardConfig(o);return console.warn(`画板引用未在上下文中找到,使用回退配置: ${o}`),console.error("🔍 使用回退画板配置:",i),i}catch(o){if(s)throw o;return console.warn(`画板配置解析失败: ${e}`,o),{}}}static getFallbackAnimationConfig(e){const t={slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}};return t[e]||t.slider_horizontal}static getFallbackBoardConfig(e){const t={default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}};return t[e]||t.default}static validate(e){const t=[];return e?(e.type!==ye.GEOMETRY_TRANSFORM&&t.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||t.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&t.push("几何变换内容块缺少 geometry 或 geometryRef"),t):(t.push("几何变换内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(s=>s.type===ye.GEOMETRY_TRANSFORM).map(s=>this.transform(s,t,n))}}function qc(){return{type:ye.GEOMETRY_TRANSFORM,transform:tr.transform.bind(tr),validate:tr.validate.bind(tr)}}class Ze{static transformText(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;console.error(`📄 TextTransformer.transformText: type=${e.type}, content=${e.content?.substring(0,50)}..., styleRef=${e.styleRef}, enableReferenceResolution=${s}`);const i={...e,type:ye.TEXT};if(!s)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,t,{strictMode:o})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:o})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=we.resolve(i.styleRef,t);console.error(" StyleRefResolver解析结果:",a),i.style={...i.style,...a},console.error(" 合并后style:",i.style)}catch(a){if(o)throw a;console.warn(`文本样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("文本转换失败:",a),i}}static transformFormula(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n,i={...e,type:ye.FORMULA};if(!s)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:o})),i.styleRef){try{const a=we.resolve(i.styleRef,t);i.style={...i.style,...a}}catch(a){if(o)throw a;console.warn(`公式样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("公式转换失败:",a),i}}static resolveTextContent(e,t,n={}){const{strictMode:s=!1}=n;if(console.error(`📝 TextTransformer.resolveTextContent START: text="${e}", hasDesignTokens=${e.includes("$")}`),!e.includes("$"))return console.error(` resolveTextContent END (no design tokens): "${e}"`),e;let o=e,i;const a=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;for(;(i=a.exec(e))!==null;){const c=i[0],l=i[1];console.error(` 发现设计令牌: ${c}, path=${l}`);try{const d=Pe.resolve(c,t);console.error(` 解析结果: ${c} -> ${d}`),o=o.replace(c,String(d))}catch(d){if(s)throw d;console.warn(`文本中的设计令牌解析失败: ${c}`,d)}}return console.error(` resolveTextContent END: original="${e}", resolved="${o}"`),o}static resolveStyle(e,t,n={}){const{strictMode:s=!1}=n;try{return Pe.replaceDesignTokenRefs(e,t,o=>{if(s)throw new Error(`设计令牌未找到: ${o}`);return console.warn(`设计令牌未找到: ${o}`),o})}catch(o){if(s)throw o;return console.warn("样式解析失败:",o),e}}static validateText(e){const t=[];return e?(e.type!==ye.TEXT&&t.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("文本内容块缺少 content 字段"),t):(t.push("文本内容块不能为空"),t)}static validateFormula(e){const t=[];return e?(e.type!==ye.FORMULA&&t.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("公式内容块缺少 content 字段"),t):(t.push("公式内容块不能为空"),t)}static batchTransformText(e,t,n={}){return e.filter(s=>s.type===ye.TEXT).map(s=>this.transformText(s,t,n))}static batchTransformFormula(e,t,n={}){return e.filter(s=>s.type===ye.FORMULA).map(s=>this.transformFormula(s,t,n))}}function Yc(){return{type:ye.TEXT,transform:Ze.transformText.bind(Ze),validate:Ze.validateText.bind(Ze)}}function Hc(){return{type:ye.FORMULA,transform:Ze.transformFormula.bind(Ze),validate:Ze.validateFormula.bind(Ze)}}class Kc{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(Wc()),this.register(qc()),this.register(Yc()),this.register(Hc())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,t,n={}){if(!e||!e.type)throw new Error("内容块缺少 type 字段");const s=this.getTransformer(e.type);return s?(console.error(`🔄 TransformerRegistry.transform: type="${e.type}", transformer.type="${s.type}", enableReferenceResolution=${n.enableReferenceResolution}`),s.transform(e,t,n)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,t,n={}){return e.map(s=>this.transform(s,t,n))}transformScene(e,t,n={}){const s=e.items||e.content;if(!e||!Array.isArray(s))return{items:[],layout:e?.layout};const o=this.batchTransform(s,t,n);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,t,n);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=Ve.resolve(e.layout,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:o,layout:i}}resolveLayoutReferences(e,t,n){if(!e||!n.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return Ve.resolve(e,t)}catch(s){if(n.strictMode)throw s;return console.warn(`布局引用解析失败: ${e}`,s),e}if(typeof e=="object"){if(e.layoutRef&&typeof e.layoutRef=="string")try{const o=`layoutRef:${e.layoutRef}`,i=Ve.resolve(o,t),{layoutRef:a,...c}=e;return{...i,...c}}catch(o){if(n.strictMode)throw o;console.warn(`布局引用解析失败: ${e.layoutRef}`,o)}const s=Array.isArray(e)?[]:{};for(const[o,i]of Object.entries(e))if(typeof i=="string"&&i.startsWith("layoutRef:"))try{s[o]=Ve.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),s[o]=i}else if(typeof i=="string"&&i.startsWith("$"))try{s[o]=Pe.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局中的设计令牌解析失败: ${o}=${i}`,a),s[o]=i}else i&&typeof i=="object"?s[o]=this.resolveLayoutReferences(i,t,n):s[o]=i;return s}return e}transformScenes(e,t,n={}){const s={};for(const[o,i]of Object.entries(e))s[o]=this.transformScene(i,t,n);return s}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const t=this.getTransformer(e.type);return!t||!t.validate?[]:t.validate(e)}batchValidate(e){return e.map(t=>({block:t,errors:this.validate(t)}))}}function $o(){return new Kc}class es{static validate(e,t={}){const{strictMode:n=!1,skipOptionalFields:s=!1}=t,o=[],i=[];return!e||typeof e!="object"?(o.push("输入数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i,{skipOptionalFields:s}),this.validateFieldTypes(e,o,i),this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswerInfo(e,o,i),n&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,t,n,s){const{skipOptionalFields:o}=s;for(const i of Fr.RAW_DATA)e[i]===void 0&&t.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Fr.BASIC_INFO)e.basic_info[i]===void 0&&t.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Fr.ANSWER_INFO)e.answer_info[i]===void 0&&t.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,t,n){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&t.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&t.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&t.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&t.push(`${a} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||t.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${o} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||t.push(`场景 ${o} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${o} 的 layout 应为对象类型`),_o.includes(o)||n.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,t,n){if(!e.basic_info||typeof e.basic_info!="object")return;const s=e.basic_info;["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&t.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&t.push(`basic_info.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&t.push("basic_info.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&t.push("basic_info.context 应为对象类型"),s.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(s.shape)&&n.push(`未知的形状类型: ${s.shape}`)}static validateAnswerInfo(e,t,n){if(!e.answer_info||typeof e.answer_info!="object")return;const s=e.answer_info;typeof s.value!="number"&&t.push("answer_info.value 应为数字类型"),typeof s.unit!="string"&&t.push("answer_info.unit 应为字符串类型"),typeof s.explanation_text!="string"&&t.push("answer_info.explanation_text 应为字符串类型"),s.value!==void 0&&(s.value<0&&n.push("answer_info.value 为负数,可能不正确"),s.value>1e4&&n.push("answer_info.value 过大,可能不正确"))}static validateStrictMode(e,t,n){if(e.schema_version||n.push("建议添加 schema_version 字段"),e.config_version||n.push("建议添加 config_version 字段"),e.knowledge_points&&e.knowledge_points.length===0&&n.push("knowledge_points 数组为空"),e.scenes)for(const[s,o]of Object.entries(e.scenes)){const i=o;i.content&&i.content.length===0&&n.push(`场景 ${s} 的 content 数组为空`)}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["math_prob_id","title","basic_info","scenes","answer_info"];for(const n of t)if(e[n]===void 0)return!1;return!0}static validateAndClean(e,t={}){const{strictMode:n=!1,removeInvalidFields:s=!1}=t,o=this.validate(e,{strictMode:n});let i=e;return s&&!o.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(c=>{c in i&&delete i[c]})),{data:i,errors:o.errors,warnings:o.warnings}}}class ts{static validate(e,t={}){const{strictMode:n=!1,checkSceneContent:s=!0}=t,o=[],i=[];return!e||typeof e!="object"?(o.push("输出数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i),this.validateFieldTypes(e,o,i),s&&this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswer(e,o,i),this.validateExplanation(e,o,i),n&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,t,n){const s=["id","title","grade","unit","lesson","skill","objective","knowledgePoints","difficulty","metadata","basicInfo","scenes","answer"];for(const o of s)e[o]===void 0&&t.push(`缺少必需字段: ${o}`)}static validateFieldTypes(e,t,n){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&t.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&t.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&t.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&t.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&t.push(`${i} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||t.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${o} 应为对象类型`);continue}const a=i,c=a.items||a.content;Array.isArray(c)?c.length===0&&n.push(`场景 ${o} 的内容数组为空`):t.push(`场景 ${o} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${o} 的 layout 应为对象类型`),_o.includes(o)||n.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,t,n){if(!e.basicInfo||typeof e.basicInfo!="object"){t.push("basicInfo 应为对象类型");return}const s=e.basicInfo;(s.question===void 0||typeof s.question!="string")&&t.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&t.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&t.push(`basicInfo.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&t.push("basicInfo.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&t.push("basicInfo.context 应为对象类型")}static validateAnswer(e,t,n){if(!e.answer||typeof e.answer!="object"){t.push("answer 应为对象类型");return}const s=e.answer;typeof s.value!="number"&&t.push("answer.value 应为数字类型"),typeof s.unit!="string"&&t.push("answer.unit 应为字符串类型"),typeof s.explanation!="string"&&t.push("answer.explanation 应为字符串类型"),s.value!==void 0&&(s.value<0&&n.push("answer.value 为负数,可能不正确"),s.value>1e4&&n.push("answer.value 过大,可能不正确"))}static validateExplanation(e,t,n){if(e.explanation===void 0){t.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){t.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&n.push("explanation 数组为空"),e.explanation.forEach((s,o)=>{(!s||typeof s!="object")&&t.push(`explanation[${o}] 应为对象类型`)})):e.explanation.steps===void 0?t.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||t.push("explanation.steps 应为数组类型")}static validateStrictMode(e,t,n){if(e.id&&typeof e.id=="string"&&(e.id.includes("-")||n.push("id 格式可能不符合规范,建议使用连字符分隔")),e.grade!==void 0&&(e.grade<1||e.grade>12)&&n.push(`grade 值 ${e.grade} 超出常见范围 (1-12)`),e.difficulty!==void 0&&(e.difficulty<1||e.difficulty>5)&&n.push(`difficulty 值 ${e.difficulty} 超出范围 (1-5)`),e.knowledgePoints&&e.knowledgePoints.length===0&&n.push("knowledgePoints 数组为空"),e.metadata&&typeof e.metadata=="object"){const s=e.metadata;(!s.topic||typeof s.topic!="string")&&n.push("metadata.topic 应为字符串类型"),(!s.skill||typeof s.skill!="string")&&n.push("metadata.skill 应为字符串类型"),(!s.tags||!Array.isArray(s.tags))&&n.push("metadata.tags 应为数组类型")}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["id","title","basicInfo","scenes","answer"];for(const n of t)if(e[n]===void 0)return!1;return!(typeof e.title!="string"||e.basicInfo&&typeof e.basicInfo!="object"||e.scenes&&typeof e.scenes!="object"||e.answer&&typeof e.answer!="object")}static isValidMathPracticeProblemData(e){return this.validate(e,{strictMode:!1,checkSceneContent:!1}).isValid}}class gr{static validateInput(e,t={}){const{isValid:n,errors:s,warnings:o}=es.validate(e,t);return{isValid:n,errors:s,warnings:o,timestamp:Date.now()}}static validateOutput(e,t={}){const{isValid:n,errors:s,warnings:o}=ts.validate(e,t);return{isValid:n,errors:s,warnings:o,timestamp:Date.now()}}static validateComplete(e,t,n={}){const{inputStrictMode:s=!1,outputStrictMode:o=!1}=n,i=this.validateInput(e,{strictMode:s}),a=this.validateOutput(t,{strictMode:o}),c=[...i.errors,...a.errors],l=[...i.warnings,...a.warnings],d={isValid:i.isValid&&a.isValid,errors:c,warnings:l};return{input:i,output:a,overall:d}}static quickValidateInput(e){return es.quickValidate(e)}static quickValidateOutput(e){return ts.quickValidate(e)}static validateAndReport(e,t,n={}){const s=t==="input"?this.validateInput(e,n):this.validateOutput(e,n);console.group(`${t.toUpperCase()} 验证结果`),console.log(`有效性: ${s.isValid?"✅ 通过":"❌ 失败"}`),s.errors.length>0&&(console.group("❌ 错误:"),s.errors.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),s.warnings.length>0&&(console.group("⚠️ 警告:"),s.warnings.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),console.groupEnd()}}class Kr{static extractAllReferences(e){const t=[],n=s=>{typeof s=="string"?t.push(s):Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&Object.values(s).forEach(n)};return n(e),[...new Set(t)]}static categorizeReferences(e,t){const n={[ee.DESIGN_TOKEN]:[],[ee.STYLE_REF]:[],[ee.GEOMETRY_REF]:[],[ee.TRANSFORM_REF]:[],[ee.LAYOUT_REF]:[]},s=new mt;for(const o of e){const i=s.getResolverForRef(o);i&&n[i.type].push(o)}return n}static batchResolveReferences(e,t,n={}){const{strictMode:s=!1,onMissing:o}=n,i=new mt,a={};for(const c of e){const l=i.getResolverForRef(c);if(l)try{a[c]=l.resolve(c,t)}catch(d){if(s)throw d;console.warn(`引用解析失败: ${c}`,d),o&&(a[c]=o(c))}}return a}static replaceReferences(e,t,n={}){const{strictMode:s=!1,onMissing:o,maxDepth:i=10}=n,a=new mt,c=new Set(["geometryRef","styleRef","transformRef","layoutRef","boardRef","animationRef","appearanceRef","position","vertices","endpoints","center","start","end","type","theme","strategy","content","description","title","question","answer","unit","id","name","label","config","metadata","layout","renderer","padding","component","inputType","placeholder","submitButton","targetGroup","direction","executionMode","transformSource","rotationGroup","isMovable","isStatic","shapes","animated","static","transform","chartConfig","steps","value","tolerance","validation","explanation_text","solution_steps","variables","originX","originY","areaUnit","baseUnit","heightUnit","answerUnit","base","height","displayMode","parts","fontSize","fontWeight","anchorX"]),l=(d,u=0,y)=>{if(u>i)return console.warn(`引用替换达到最大深度: ${i}`),d;if(typeof d=="string"){if(y&&c.has(y))return console.warn(`🛡️ 跳过保留字段 "${y}" 的通用解析: "${d}"`),d;if(!(d.startsWith("$")||d.includes("Ref:")))return d;const h=a.getResolverForRef(d);if(h)try{return h.resolve(d,t)}catch(g){if(s)throw g;return console.warn(`引用解析失败: ${d}`,g),o?o(d):d}return d}else{if(Array.isArray(d))return d.map(m=>l(m,u+1,void 0));if(d&&typeof d=="object"){const m={};for(const[h,g]of Object.entries(d))m[h]=l(g,u+1,h);return m}}return d};return l(e)}static calculateReferenceStats(e,t){const n=new mt,s={total:e.length,resolved:0,failed:0,byType:{}};Object.values(ee).forEach(o=>{s.byType[o]={total:0,resolved:0,failed:0}}),console.log("🔍 calculateReferenceStats: 开始处理引用,总数=",e.length);for(const o of e){console.log("🔍 处理引用:",o);const i=n.getResolverForRef(o);if(i){const a=i.type;s.byType[a].total++,console.log(`🔍 找到解析器: type=${a}`);try{const c=i.resolve(o,t);console.log(`🔍 引用解析成功: ${o} =>`,c),s.resolved++,s.byType[a].resolved++}catch(c){console.error(`🔍 引用解析失败: ${o}`,c),s.failed++,s.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${o}`)}return s}static checkReferenceExists(e,t){const s=new mt().getResolverForRef(e);if(!s)return!1;if(s.validate)return s.validate(e,t);try{return s.resolve(e,t),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const t=e.match(/^(\w+):(\w+)$/);return t?[t[1],t[2]]:[e]}static createReference(e,t){switch(e){case ee.DESIGN_TOKEN:return`$${t.join(".")}`;case ee.STYLE_REF:return`styleRef:${t[0]}`;case ee.GEOMETRY_REF:return`geometryRef:${t[0]}`;case ee.TRANSFORM_REF:return`transformRef:${t[0]}`;case ee.LAYOUT_REF:return`layoutRef:${t[0]}`;default:return t.join(":")}}static flattenNestedReferences(e){const t=[],n=(s,o=[])=>{if(typeof s=="string")t.push(`${o.join(".")}=${s}`);else if(Array.isArray(s))s.forEach((i,a)=>{n(i,[...o,`[${a}]`])});else if(s&&typeof s=="object")for(const[i,a]of Object.entries(s))n(a,[...o,i])};return n(e),t}}class ko{marks=new Map;stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0};memoryStart=0;constructor(){this.startMemoryTracking()}markStart(e){this.marks.set(e,{name:e,startTime:performance.now()})}markEnd(e){const t=this.marks.get(e);if(!t){console.warn(`性能标记未找到: ${e}`);return}const n=performance.now(),s=n-t.startTime;t.endTime=n,t.duration=s,this.updateStats(e,s)}updateStats(e,t){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=t;break;case"transformation":this.stats.transformationTime=t;break;case"validation":this.stats.validationTime=t;break;case"total":this.stats.totalTime=t;break}}startMemoryTracking(){typeof performance<"u"&&performance.memory&&(this.memoryStart=performance.memory.usedJSHeapSize)}endMemoryTracking(){if(typeof performance<"u"&&performance.memory){const e=performance.memory.usedJSHeapSize;this.stats.memoryUsage=e-this.memoryStart}}setReferenceCount(e){this.stats.referenceCount=e}getStats(){return this.endMemoryTracking(),{...this.stats}}getMarks(){return Array.from(this.marks.values())}checkPerformance(){const e=[];return this.stats.transformationTime>nt.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${nt.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>nt.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${nt.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>nt.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${nt.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>nt.MAX_REFERENCE_DEPTH*10&&e.push(`引用数量较多: ${this.stats.referenceCount} (可能影响性能)`),{passed:e.length===0,warnings:e}}reset(){this.marks.clear(),this.stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0},this.startMemoryTracking()}}class Xc{static deepMerge(e,t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return Array.isArray(e)?e.map((s,o)=>o<t.length?this.deepMerge(s,t[o]):s):[...t];const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&(s in n&&typeof n[s]=="object"&&typeof o=="object"?n[s]=this.deepMerge(n[s],o):n[s]=o);return n}static deepEqual(e,t){if(e===t)return!0;if(typeof e!=typeof t||typeof e!="object"||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e))return e.length!==t.length?!1:e.every((o,i)=>this.deepEqual(o,t[i]));const n=Object.keys(e),s=Object.keys(t);return n.length!==s.length?!1:n.every(o=>o in t?this.deepEqual(e[o],t[o]):!1)}static safeGet(e,t,n=void 0){const s=Array.isArray(t)?t:t.split(".");let o=e;for(const i of s){if(o==null||typeof o!="object")return n;const a=i.match(/^\[(\d+)\]$/);if(a&&Array.isArray(o)){const c=parseInt(a[1],10);o=o[c]}else o=o[i]}return o!==void 0?o:n}static safeSet(e,t,n){const s=Array.isArray(t)?t:t.split("."),o=Array.isArray(e)?[...e]:{...e};let i=o;for(let l=0;l<s.length-1;l++){const d=s[l],u=d.match(/^\[(\d+)\]$/);if(u&&Array.isArray(i)){const y=parseInt(u[1],10);i[y]===void 0&&(i[y]={}),i=i[y]}else{if(i[d]===void 0){const m=s[l+1].match(/^\[(\d+)\]$/);i[d]=m?[]:{}}i=i[d]}}const a=s[s.length-1],c=a.match(/^\[(\d+)\]$/);if(c&&Array.isArray(i)){const l=parseInt(c[1],10);i[l]=n}else i[a]=n;return o}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,t){let n=0;return(...s)=>{const o=Date.now();o-n>=t&&(n=o,e(...s))}}static debounce(e,t){let n;return(...s)=>{clearTimeout(n),n=setTimeout(()=>e(...s),t)}}static formatBytes(e,t=2){if(e===0)return"0 Bytes";const n=1024,s=t<0?0:t,o=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/Math.pow(n,i)).toFixed(s))+" "+o[i]}static estimateObjectSize(e){const t=new WeakSet,n=s=>t.has(s)?0:typeof s=="string"?(t.add(s),s.length*2):typeof s=="number"?8:typeof s=="boolean"?4:s==null?0:Array.isArray(s)?(t.add(s),s.reduce((o,i)=>o+n(i),0)):typeof s=="object"?(t.add(s),Object.values(s).reduce((o,i)=>o+n(i),0)):0;return n(e)}}class Jc{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...Ic,...e},this.referenceContext=To(),this.resolverRegistry=No(),this.transformerRegistry=$o(),this.performanceMonitor=new ko}adapt(e){console.error("🔧 SyncAdapter.adapt called with inputData:",{math_prob_id:e?.math_prob_id,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{this.performanceMonitor.markStart("validation");const t=this.validateInput(e);if(!t.isValid&&this.config.strictMode)throw new me(B.INVALID_INPUT,Qn[B.INVALID_INPUT],{errors:t.errors});this.performanceMonitor.markEnd("validation"),this.performanceMonitor.markStart("base-transformation");const n=this.transformBaseData(e);this.performanceMonitor.markEnd("base-transformation");let s=n;this.config.enableReferenceResolution&&(this.performanceMonitor.markStart("reference-resolution"),s=this.resolveReferences(n),this.performanceMonitor.markEnd("reference-resolution")),this.performanceMonitor.markStart("scene-transformation"),!this.referenceContext.basicInfo&&s.basicInfo&&(this.referenceContext.basicInfo=s.basicInfo);const o=this.transformScenes(s);this.performanceMonitor.markEnd("scene-transformation"),this.performanceMonitor.markStart("output-validation");const i=this.validateOutput(o);if(!i.isValid&&this.config.strictMode)throw new me(B.OUTPUT_VALIDATION_FAILED,Qn[B.OUTPUT_VALIDATION_FAILED],{errors:i.errors});this.performanceMonitor.markEnd("output-validation"),this.performanceMonitor.markEnd("total"),console.error("🔧 adapt: transformedData before buildResult:",o),console.error("🔧 adapt: transformedData.basicInfo:",o.basicInfo),console.error("🔧 adapt: transformedData.basicInfo?.answerUnit:",o.basicInfo?.answerUnit);const a=this.buildResult(o,{inputValidation:t,outputValidation:i,inputWarnings:t.warnings,outputWarnings:i.warnings},e);return console.error("🔧 adapt: result.data.basicInfo:",a.data.basicInfo),console.error("🔧 adapt: result.data.basicInfo?.answerUnit:",a.data.basicInfo?.answerUnit),a}catch(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}validateInput(e){return gr.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(console.error("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([t,n])=>{if(n&&typeof n=="object"){console.error(` 🔍 Processing geometry shape ${t}:`,{id:n.id,type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),shapeKeys:Object.keys(n)});const s=this.convertGeometryShapeCoordinates(n);console.error(` 📍 ${t}:`,{type:n.type,position:n.position,vertices:n.vertices}),this.referenceContext.geometryPresets[t]=s}}),console.error("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):console.error("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&Object.entries(e.transform_definitions).forEach(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=s}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(t=>{t&&t.content&&Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="graph"&&n.shapes&&this.extractPointCoordinatesFromShapes(n.shapes)})})}extractGeometryTransformConfigsFromInput(e){if(!e){console.error("⚠️ extractGeometryTransformConfigsFromInput: inputData is null or undefined");return}this.referenceContext.geometryTransformConfigs||(this.referenceContext.geometryTransformConfigs={}),e.geometry_transform_configs&&typeof e.geometry_transform_configs=="object"?(console.error("📦 Extracting geometry_transform_configs:",Object.keys(e.geometry_transform_configs)),Object.entries(e.geometry_transform_configs).forEach(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing geometry transform config ${t}:`,{id:n.id,strategy:n.strategy,hasBase:"base"in n,hasHeight:"height"in n,hasShapes:"shapes"in n,hasTransform:"transform"in n}),this.referenceContext.geometryTransformConfigs[t]=n)}),console.error("✅ geometryTransformConfigs after extraction:",Object.keys(this.referenceContext.geometryTransformConfigs))):console.error("⚠️ No geometry_transform_configs found in input data")}extractAnimationConfigsFromInput(e){if(!e){console.error("⚠️ extractAnimationConfigsFromInput: inputData is null or undefined");return}this.referenceContext.animationConfigs||(this.referenceContext.animationConfigs={}),e.animation_configs&&typeof e.animation_configs=="object"?(console.error("📦 Extracting animation_configs:",Object.keys(e.animation_configs)),Object.entries(e.animation_configs).forEach(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing animation config ${t}:`,{id:n.id,description:n.description,hasTransforms:"transforms"in n,hasVisualEffects:"visualEffects"in n}),this.referenceContext.animationConfigs[t]=n)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;console.error("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0});const t={...e};t.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(console.error(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,s)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(console.error(` Endpoint ${s} is not array:`,n),n)),t.type==="segment"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&console.error(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?t[n]=s:t[n]=this.convertGeometryShapeCoordinates(s));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>typeof o=="object"?this.convertTransformDefinitionCoordinates(o):o):s&&typeof s=="object"&&(t[n]=this.convertTransformDefinitionCoordinates(s));return t}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(t=>{if(t&&t.type==="point"&&t.position&&Array.isArray(t.position)&&t.position.length>=2){const n=t.id||`point_${t.position[0]}_${t.position[1]}`;this.referenceContext.geometryPresets[n]={type:"point",position:{x:t.position[0],y:t.position[1]}}}})}transformBaseData(e){if(!e)return console.error("⚠️ transformBaseData: inputData is null or undefined"),{id:"fallback-empty-input",title:"回退数据",grade:5,unit:"未知单元",lesson:"未知课程",skill:"未知技能",objective:"未知目标",knowledgePoints:[],difficulty:1,metadata:{},basicInfo:{question:""},scenes:{question:{items:[]},solve:{items:[]},review:{items:[]}},explanation:{steps:[]},answer:{value:0,unit:"",explanation:""}};this.extractGeometryDefinitionsFromInput(e),this.extractGeometryTransformConfigsFromInput(e),this.extractAnimationConfigsFromInput(e);const t={id:e.math_prob_id||Xc.generateId("triangle"),title:e.title,grade:this.parseGrade(e.grade_id),unit:e.unit_name,lesson:e.lesson_name,skill:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points||[],difficulty:e.difficulty||1,metadata:this.transformMetadata(e),description:e.description,scenes:this.transformScenesStructure(e.scenes),answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info)};["unit_id","lesson_id","module_id","skill_item_id","skill_id","created_at","updated_at","layout"].forEach(o=>{e[o]!==void 0&&(t[o]=e[o])}),console.error("🔧 transformBaseData: inputData.basic_info =",e.basic_info);const s=this.transformBasicInfo(e.basic_info);return console.error("🔧 transformBaseData: basicInfo after transform =",s),console.error("🔧 transformBaseData: basicInfo.answerUnit =",s?.answerUnit),this.referenceContext.basicInfo=s,t.basicInfo=s,console.error("🔧 transformBaseData: transformed.basicInfo set =",t.basicInfo),t.explanation=this.transformExplanation(e.explanation),t}parseGrade(e){const t=e.match(/g(\d+)/);return t?parseInt(t[1],10):5}transformMetadata(e){return e.metadata&&typeof e.metadata=="object"?e.metadata:{topic:e.unit_name||"三角形面积计算",skill:e.skill_description||"三角形面积求解技能",tags:e.knowledge_points||["三角形面积公式"]}}transformBasicInfo(e){if(console.error("🔄 transformBasicInfo called with:",e),!e||typeof e!="object")return console.error("⚠️ transformBasicInfo: basicInfo is empty, returning default"),{question:""};const t={...e};return console.error("🔄 transformBasicInfo: transformed copy:",t),t.question===void 0&&t.content!==void 0&&(t.question=t.content),t.question===void 0&&(t.question=""),console.error("🔄 transformBasicInfo: returning:",t),t}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const t={};return["question","solve","review"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];t[o]={...i,items:a},i.content!==void 0&&delete t[o].content}else t[o]={items:[]}}),["remember"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];t[o]={...i,items:a},i.content!==void 0&&delete t[o].content}}),t}transformExplanation(e){if(console.error("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&e.steps&&Array.isArray(e.steps),stepsCount:e&&e.steps?e.steps.length:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){console.error(`🔄 transformExplanation: processing ${e.steps.length} steps`);const t=e.steps.map((n,s)=>(console.error(` Step ${s}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.error(" chartConfig keys:",Object.keys(t)),n!=="graph"&&n!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const s={type:n,...t};console.error(" contentBlock keys:",Object.keys(s)),n==="graph"&&s.shapes&&(console.error(" shapes count:",s.shapes.length),s.shapes.length>0&&console.error(" first shape:",s.shapes[0])),console.error("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.error("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]);const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});console.error(" transformedBlock keys:",Object.keys(o)),n==="graph"&&o.shapes&&console.error(" transformed shapes count:",o.shapes.length);let i;if(n==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,console.error(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.error(` geometryTransform preserved: step.title=${e.title}`),console.error(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.error(" geometryTransform preserved: config=",i.metadata?.config);else if(n==="graph"&&o.boardConfig){const{boardConfig:a,...c}=o;i={...c,...a},console.error(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}resolveReferences(e){const t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),Kr.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(console.warn(`引用未找到: ${n}`),n)})}transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),t}validateOutput(e){return gr.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const s=this.performanceMonitor.getStats(),o=this.performanceMonitor.checkPerformance(),i=[...t.inputValidation.warnings.map(d=>({code:B.INVALID_INPUT,message:`输入验证警告: ${d}`,suggestion:"检查输入数据格式"})),...t.outputValidation.warnings.map(d=>({code:B.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${d}`,suggestion:"检查数据转换逻辑"})),...o.warnings.map(d=>({code:B.TRANSFORMATION_FAILED,message:`性能警告: ${d}`,suggestion:"优化数据转换性能"}))],a=n||e,c=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],l=Kr.calculateReferenceStats(c,this.referenceContext);return{data:e,warnings:i,performance:s,referenceStats:{total:l.total,resolved:l.resolved,failed:l.failed,byType:l.byType}}}createFallbackResult(e,t){const n={...lr,id:e?.math_prob_id||lr.id,title:e?.title||lr.title},s={code:B.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t.message}`,suggestion:"检查输入数据格式和适配器配置"};return{data:n,warnings:[s],performance:this.performanceMonitor.getStats(),referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}getPerformanceStats(){return this.performanceMonitor.getStats()}reset(){this.performanceMonitor.reset()}}class Yt{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...jc,...e},this.referenceContext=To(),this.resolverRegistry=No(),this.transformerRegistry=$o(),this.performanceMonitor=new ko,this.syncAdapter=new Jc(e)}adapt(e){this.config.enableLogging&&console.log("🔧 GeometryAdapter.adapt called with inputData (delegating to SyncAdapterCore):",{math_prob_id:e?.math_prob_id,schema_version:e?.schema_version,shape:e?.basic_info?.shape,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{const t=e,n=this.syncAdapter.adapt(t);return this.performanceMonitor.markEnd("total"),this.config.enableLogging&&console.log("✅ GeometryAdapter.adapt completed successfully:",{id:n.data.id,hasBasicInfo:!!n.data.basicInfo,warningCount:n.warnings.length,referenceStats:n.referenceStats}),n}catch(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}_validateInput(e){return gr.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){this.config.enableLogging&&console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(this.config.enableLogging&&console.log("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertGeometryShapeCoordinates(n);this.referenceContext.geometryPresets[t]=s}}),this.config.enableLogging&&console.log("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):this.config.enableLogging&&console.log("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&Object.entries(e.transform_definitions).forEach(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=s}})}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}transformExplanation(e){if(this.config.enableLogging&&console.log("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&e.steps&&Array.isArray(e.steps),stepsCount:e&&e.steps?e.steps.length:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){this.config.enableLogging&&console.log(`🔄 transformExplanation: processing ${e.steps.length} steps`);const t=e.steps.map((n,s)=>(this.config.enableLogging&&console.log(` Step ${s}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.log(" chartConfig keys:",Object.keys(t))),n!=="graph"&&n!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const s={type:n,...t};this.config.enableLogging&&(console.log(" contentBlock keys:",Object.keys(s)),n==="graph"&&s.shapes&&(console.log(" shapes count:",s.shapes.length),s.shapes.length>0&&console.log(" first shape:",s.shapes[0]))),this.config.enableLogging&&(console.log("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.log("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]));const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});this.config.enableLogging&&(console.log(" transformedBlock keys:",Object.keys(o)),n==="graph"&&o.shapes&&console.log(" transformed shapes count:",o.shapes.length));let i;if(n==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,this.config.enableLogging&&(console.log(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.log(` geometryTransform preserved: step.title=${e.title}`),console.log(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.log(" geometryTransform preserved: config=",i.metadata?.config));else if(n==="graph"&&o.boardConfig){const{boardConfig:a,...c}=o;i={...c,...a},this.config.enableLogging&&console.log(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(this.config.enableLogging&&console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;this.config.enableLogging&&console.log("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0});const t={...e};t.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,s)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(this.config.enableLogging&&console.log(` Endpoint ${s} is not array:`,n),n)),t.type==="segment"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&this.config.enableLogging&&console.log(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?t[n]=s:t[n]=this.convertGeometryShapeCoordinates(s));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>typeof o=="object"?this.convertTransformDefinitionCoordinates(o):o):s&&typeof s=="object"&&(t[n]=this.convertTransformDefinitionCoordinates(s));return t}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.deepClone(n));const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const t={id:e.math_prob_id,title:e.title,grade:parseInt(e.grade_id.replace("g",""))||5,unit:e.unit_name,lesson:e.lesson_name,skillDescription:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points,difficulty:e.difficulty,description:e.description,metadata:e.metadata,basicInfo:{question:e.basic_info.question,answerUnit:e.basic_info.answerUnit||e.basic_info.areaUnit,shape:e.basic_info.shape,base:e.basic_info.base,height:e.basic_info.height,baseUnit:e.basic_info.baseUnit,heightUnit:e.basic_info.heightUnit,topBase:e.basic_info.topBase,topBaseUnit:e.basic_info.topBaseUnit,length:e.basic_info.length,width:e.basic_info.width,lengthUnit:e.basic_info.lengthUnit,widthUnit:e.basic_info.widthUnit,side:e.basic_info.side,sideUnit:e.basic_info.sideUnit,variables:e.basic_info.variables,score:e.basic_info.score,context:e.basic_info.context},rawGeometryShapes:e.geometry_shapes,rawTransformDefinitions:e.transform_definitions,rawGeometryTransformConfigs:e.geometry_transform_configs,rawAnimationConfigs:e.animation_configs,rawScenes:e.scenes,rawExplanation:e.explanation,rawAnswerInfo:e.answer_info,answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info),explanation:this.transformExplanation(e.explanation),unitId:e.unit_id,lessonId:e.lesson_id,moduleId:e.module_id,skillItemId:e.skill_item_id,skillId:e.skill_id,createdAt:e.created_at,updatedAt:e.updated_at,layout:e.layout};return this.referenceContext.basicInfo=t.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),t}_resolveReferences(e){const t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),Kr.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(this.config.enableLogging&&console.warn(`引用未找到: ${n}`),n)})}_transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),t}_validateOutput(e){return gr.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const s=this.performanceMonitor.getStats(),o=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(t.inputWarnings||[]).map(a=>({code:Mr.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(t.outputWarnings||[]).map(a=>({code:Mr.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?s:void 0,referenceStats:o}}createFallbackResult(e,t){return{data:{...lr,id:e?.math_prob_id||"geometry-fallback",title:e?.title||"几何问题(回退)",basicInfo:{question:e?.basic_info?.question||"计算下面几何图形的面积:",answerUnit:e?.basic_info?.answerUnit||"cm²",shape:e?.basic_info?.shape||"triangle",base:e?.basic_info?.base||6,height:e?.basic_info?.height||4,baseUnit:e?.basic_info?.baseUnit||"cm",heightUnit:e?.basic_info?.heightUnit||"cm"}},warnings:[{code:Mr.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t instanceof Error?t.message:t}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new Yt(e)}}function dt(r,e){return new Yt(e).adapt(r)}async function _n(r,e){return Promise.resolve(dt(r,e))}function Oo(r,e){const t=typeof r=="function"?r():r;return dt(t,e)}async function jo(r,e){const t=typeof r=="function"?await r():r instanceof Promise?await r:r;return dt(t,e)}function Io(r){return new Yt(r)}function Mo(r){const e=new Yt(r);return{adapt:t=>Promise.resolve(e.adapt(t))}}function Zc(r,e="input"){const{ValidationManager:t}=require("../TriangleAdapterV3/validators");return t.validate(r,e)}function Qc(r,e,t=100){const n=[];for(let c=0;c<t;c++){const l=performance.now();r.adapt(e);const d=performance.now();n.push(d-l)}const s=n.reduce((c,l)=>c+l,0)/t,o=Math.min(...n),i=Math.max(...n),a=process.memoryUsage?.().heapUsed||0;return{averageTime:s,minTime:o,maxTime:i,memoryUsage:a}}const ed={adapt:(r,e)=>dt(r,e),adaptAsync:(r,e)=>_n(r,e),create:r=>Io(r)},td="4.0.0",Fo="4.0.0";function rd(r="4.0.0"){return Fo>=r}function Po(r){return r?.schema_version==="4.0.0"||r?.schema_version?.startsWith("4.")}function nd(r){return Po(r)&&(r.geometry_shapes||r.transform_definitions||r.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(r.basic_info.shape))}class Dr extends Error{constructor(e,t,n,s){super(`Failed to generate config for ${t}: ${e}`),this.shapeType=t,this.options=n,this.innerError=s,this.name="ConfigGenerationError"}}function sd(r){const e=[],t=[];if(r.shapes||e.push(U("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),r.transform||e.push(U("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),r.strategy||e.push(U("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:ns(e),timestamp:new Date().toISOString()};r.shapes&&e.push(...od(r.shapes));let n=!1;if(r.shapes?.animated){for(const s of r.shapes.animated)if(s.transform){n=!0;break}}return r.transform?e.push(...id(r.transform)):n||e.push(U("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...ad(r)),e.push(...ld(r)),e.push(...cd(r)),e.length>0&&t.push(...ns(e)),{isValid:e.length===0,errors:e,fixes:t,timestamp:new Date().toISOString()}}function Do(r){if(!r||typeof r!="object"||!r.type||typeof r.type!="string"||!["rotation","translation","scale","composite"].includes(r.type))return!1;switch(r.type){case"rotation":if(!r.config||typeof r.config!="object")return!1;const t=r.config.center;if(t!=="auto"&&(!Array.isArray(t)||t.length!==2)||typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number"||r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical")return!1;break;case"translation":if(!r.config||typeof r.config!="object")return!1;const n=r.config.direction;if(Array.isArray(n)){if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="number")return!1}else if(typeof n=="string"){if(n!=="horizontal"&&n!=="vertical")return!1}else return!1;if(typeof r.config.distance!="number"||r.config.distance<=0)return!1;break;case"scale":if(!r.config||typeof r.config!="object")return!1;const s=r.config.center;if(s!=="centroid"&&(!Array.isArray(s)||s.length!==2)||typeof r.config.startScale!="number"||typeof r.config.endScale!="number"||typeof r.config.uniform!="boolean")return!1;break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))return!1;for(const o of r.transforms)if(!Do(o))return!1;if(r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel")return!1;break}return!0}function Lo(r,e){const t=[];if(!r||typeof r!="object")return t.push(U("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,r,{type:"rotation"})),t;(!r.type||typeof r.type!="string")&&t.push(U("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,r.type,"rotation"));const n=["rotation","translation","scale","composite"];switch(r.type&&!n.includes(r.type)&&t.push(U("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${r.type}`,`${e}.type`,r.type,"rotation")),r.type){case"rotation":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,r.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const s=r.config.center;s!=="auto"&&(!Array.isArray(s)||s.length!==2)&&t.push(U("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,r.config.center,[0,0])),(typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,r.config,{startAngle:0,endAngle:Math.PI})),r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical"&&t.push(U("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,r.config.direction,"clockwise"))}break;case"translation":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,r.config,{direction:"horizontal",distance:1}));else{const s=r.config.direction;Array.isArray(s)?s.length!==2?t.push(U("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,s,[1,0])):(typeof s[0]!="number"||typeof s[1]!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,s,[1,0])):typeof s=="string"?s!=="horizontal"&&s!=="vertical"&&t.push(U("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,s,"horizontal")):t.push(U("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,s,"horizontal")),(typeof r.config.distance!="number"||r.config.distance<=0)&&t.push(U("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,r.config.distance,1))}break;case"scale":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,r.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const s=r.config.center;s!=="centroid"&&(!Array.isArray(s)||s.length!==2)&&t.push(U("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,r.config.center,"centroid")),(typeof r.config.startScale!="number"||typeof r.config.endScale!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,r.config,{startScale:1,endScale:2})),typeof r.config.uniform!="boolean"&&t.push(U("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,r.config.uniform,!0))}break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))t.push(U("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,r.transforms,[]));else for(let s=0;s<r.transforms.length;s++){const o=Lo(r.transforms[s],`${e}.transforms[${s}]`);t.push(...o)}r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel"&&t.push(U("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,r.executionMode,"sequential"));break}return t}function U(r,e,t,n,s){let o=s;if(s===void 0)switch(r){case"INVALID_TRIANGLE_TYPE":o="right_triangle";break;case"INVALID_BASE_VALUE":case"INVALID_HEIGHT_VALUE":o=1;break;case"INVALID_ORIGIN":o=0;break;case"MISSING_SHAPES":o={static:[],animated:[]};break;case"MISSING_TRANSFORM":o={type:"rotation"};break;case"STRATEGY_MISMATCH":o="single_rotation";break;case"UNIT_MISMATCH":o="in";break;default:o=void 0}return{code:r,message:e,path:t,value:n,suggestedValue:o}}function od(r){const e=[];if(!r||typeof r!="object")return e.push(U("MISSING_SHAPES","形状定义无效或缺失","$.shapes",r)),e;if(!Array.isArray(r.static))e.push(U("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",r.static));else for(let t=0;t<r.static.length;t++){const n=r.static[t],s=rs(n,`$.shapes.static[${t}]`);e.push(...s)}if(!Array.isArray(r.animated))e.push(U("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",r.animated));else for(let t=0;t<r.animated.length;t++){const n=r.animated[t],s=rs(n,`$.shapes.animated[${t}]`);e.push(...s)}return e}function rs(r,e){const t=[];if(!r||typeof r!="object")return t.push(U("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,r)),t;if((!r.type||typeof r.type!="string")&&t.push(U("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,r.type)),!Array.isArray(r.vertices))t.push(U("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,r.vertices));else if(r.vertices.length===0)t.push(U("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,r.vertices));else for(let n=0;n<r.vertices.length;n++){const s=r.vertices[n];!Array.isArray(s)||s.length!==2?t.push(U("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须是包含两个数字的数组`,`${e}.vertices[${n}]`,s)):(typeof s[0]!="number"||typeof s[1]!="number")&&t.push(U("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须包含数字`,`${e}.vertices[${n}]`,s))}if(r.transform!==void 0){const n=Lo(r.transform,`${e}.transform`);t.push(...n)}return t}function id(r){const e=[];if(!r)return e.push(U("MISSING_TRANSFORM","变换配置缺失","$.transform",r)),e;const t=Array.isArray(r),n=t?r:[r],s="$.transform";for(let o=0;o<n.length;o++){const i=n[o],a=t?`${s}[${o}]`:s;Do(i)||e.push(U("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function ad(r){const e=[];if(!r.strategy)return e;const{strategy:t}=r;let n=0;if(r.transform&&(Array.isArray(r.transform)?n+=r.transform.length:typeof r.transform=="object"&&(r.transform.type==="composite"&&Array.isArray(r.transform.transforms)?n+=r.transform.transforms.length:n+=1)),r.shapes?.animated)for(const o of r.shapes.animated)o.transform&&(n+=1);return t.includes("single")&&n!==1&&e.push(U("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${n} 个`,"$.strategy",t,n===0?"single_rotation":"double_rotation")),t.includes("double")&&n!==2&&e.push(U("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${n} 个`,"$.strategy",t,n===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(t)||e.push(U("STRATEGY_MISMATCH",`无效的策略名称: ${t}`,"$.strategy",t,"single_rotation")),e}function ld(r){const e=[];if(r.unit&&typeof r.unit!="string"&&e.push(U("UNIT_MISMATCH","单位必须是字符串","$.unit",r.unit,"in")),r.baseUnit&&typeof r.baseUnit!="string"&&e.push(U("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",r.baseUnit,r.unit||"in")),r.heightUnit&&typeof r.heightUnit!="string"&&e.push(U("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",r.heightUnit,r.unit||"in")),r.unit&&r.baseUnit&&r.baseUnit!==r.unit&&e.push(U("UNIT_MISMATCH",`底边单位 (${r.baseUnit}) 与主单位 (${r.unit}) 不一致`,"$.baseUnit",r.baseUnit,r.unit)),r.unit&&r.heightUnit&&r.heightUnit!==r.unit&&e.push(U("UNIT_MISMATCH",`高度单位 (${r.heightUnit}) 与主单位 (${r.unit}) 不一致`,"$.heightUnit",r.heightUnit,r.unit)),r.unit&&r.boardConfig&&r.boardConfig.boundingBox){const[t,n,s,o]=r.boardConfig.boundingBox,i=s-t,a=n-o,c=r.unit==="cm"?50:20;(i>c*5||a>c*5)&&e.push(U("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${r.unit})不匹配`,"$.boardConfig.boundingBox",r.boardConfig.boundingBox,void 0))}return e}function cd(r){const e=[];if(r.shapes&&r.boardConfig&&r.boardConfig.boundingBox){const t=r.boardConfig.boundingBox,[n,s,o,i]=t,a=[...r.shapes.static||[],...r.shapes.animated||[]];for(let c=0;c<a.length;c++){const l=a[c];if(l&&l.vertices)for(let d=0;d<l.vertices.length;d++){const u=l.vertices[d];if(Array.isArray(u)&&u.length===2){const[y,m]=u;(y<n||y>o||m<i||m>s)&&e.push(U("GEOMETRY_INCONSISTENCY",`形状 ${c} 的顶点 ${d} (${y}, ${m}) 超出画板边界`,`$.shapes.${c<(r.shapes.static?.length||0)?"static":"animated"}[${c}].vertices[${d}]`,u,[Math.max(n,Math.min(y,o)),Math.max(i,Math.min(m,s))]))}}}}if(r.metadata&&r.metadata.base&&r.metadata.height){const t=.5*r.metadata.base*r.metadata.height;if(r.shapes?.static?.[0]?.vertices){const n=r.shapes.static[0].vertices;if(n.length===3){const[s,o]=n[0],[i,a]=n[1],[c,l]=n[2],d=.5*Math.abs((i-s)*(l-o)-(c-s)*(a-o));Math.abs(d-t)>.01&&e.push(U("GEOMETRY_INCONSISTENCY",`计算面积 (${d.toFixed(2)}) 与预期面积 (${t.toFixed(2)}) 不一致`,"$.metadata",{base:r.metadata.base,height:r.metadata.height,calculatedArea:d,expectedArea:t}))}}}return e}function ns(r){const e=[];for(const t of r)switch(t.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:t.path,value:t.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${t.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将底边长度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将高度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:t.path,value:t.suggestedValue||0,description:`将原点坐标修复为: ${t.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:t.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:t.suggestedValue!==void 0&&e.push({action:"replace",path:t.path,value:t.suggestedValue,description:`修复 ${t.code} 错误`,isSafe:!1})}return e}function ss(r){if(!dd(r))throw new Dr("Invalid parallelogram config options","parallelogram",r);const{base:e,height:t,unit:n="in",layoutDensity:s="compact",theme:o="light"}=r,i=r.originX??0,a=r.originY??0,c=r.skew??e/3;try{const l=fd(e,t,c,i,a,o),d=ud(e),u=md(s),y=hd(e,t,c,i,a);return{ui:{layoutDensity:s},base:e,height:t,unit:n,shapes:l,transform:d,animation:u,boardConfig:y,strategy:"cut_and_paste",theme:o,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{shapeType:"parallelogram",base:e,height:t,skew:c,unit:n,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(l){throw l instanceof Dr?l:new Dr(l.message,"parallelogram",r,l)}}function dd(r){if(!r||typeof r!="object")return!1;const e=["base","height"];for(const t of e)if(!(t in r))return!1;return!(typeof r.base!="number"||r.base<=0||typeof r.height!="number"||r.height<=0||r.skew!==void 0&&(typeof r.skew!="number"||r.skew<0)||r.originX!==void 0&&(typeof r.originX!="number"||!isFinite(r.originX))||r.originY!==void 0&&(typeof r.originY!="number"||!isFinite(r.originY)))}function fd(r,e,t,n,s,o){const a=o==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},c=[[n+t,s],[n+r,s],[n+r+t,s+e],[n+t,s+e]],l=[[n,s],[n+t,s],[n+t,s+e]];return{static:[{type:"trapezoid",vertices:c,style:{fillColor:a.staticFill,fillOpacity:.6,strokeColor:a.staticStroke,strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:l,style:{fillColor:a.animatedFill,fillOpacity:.7,strokeColor:a.animatedStroke,strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]}}function ud(r){return{type:"translation",translation:{direction:[1,0],distance:r}}}function md(r){return{slider:{position:r==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function hd(r,e,t,n,s){const o=Math.min(n,n+t,n+r,n+r+t),i=Math.max(n,n+t,n+r,n+r+t),a=Math.min(s,s+e),c=Math.max(s,s+e),l=3;return{boundingBox:[o-l,c+l,i+l,a-l],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function gd(r){return{id:r.id||r.math_prob_id,title:r.title||"",grade:r.grade||5,unit:r.unit||r.unit_name||"",lesson:r.lesson||r.lesson_name||"",skill:r.skill||r.skill_description||"",objective:r.objective||"",knowledgePoints:Array.isArray(r.knowledge_points)?r.knowledge_points:Array.isArray(r.knowledgePoints)?r.knowledgePoints:[],difficulty:r.difficulty||1,description:r.description||"",metadata:r.metadata||{topic:"",skill:"",tags:[]},math_prob_id:r.math_prob_id,grade_id:r.grade_id,unit_id:r.unit_id,lesson_id:r.lesson_id,module_id:r.module_id,skill_item_id:r.skill_item_id,skill_id:r.skill_id,created_at:r.created_at,updated_at:r.updated_at,layout:r.layout||{type:"card",padding:"20px",theme:"light"}}}function pd(r){const e=r||{};return{question:e.question||"",answerUnit:e.answerUnit||"",areaUnit:e.areaUnit||"",shape:e.shape||"",base:e.base||e.length||0,height:e.height||e.width||0,baseUnit:e.baseUnit||e.lengthUnit||"",heightUnit:e.heightUnit||e.widthUnit||"",length:e.base||e.length||0,width:e.height||e.width||0,lengthUnit:e.baseUnit||e.lengthUnit||"",widthUnit:e.heightUnit||e.widthUnit||"",variables:e.variables||{},context:e.context||{}}}function yd(r,e,t){return{value:r,unit:e,type:"numeric",tolerance:.01,format:{decimal_places:2,allow_fraction:!0,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!1},explanation_text:t}}function bd(r){return r?{value:r.value,unit:r.unit,explanation:r.explanation_text||r.explanation||"正确答案"}:null}function xd(r){return r.answer?r.answer:r.answer_info?bd(r.answer_info):null}function vd(){return{question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}},review:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}}]}}}function _d(){return{steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。"},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。"},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。"}],strategy:"visual_transformation",total_steps:3,estimated_time:120}}function wd(r){return Array.isArray(r)||r&&r.steps?r:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function Uo(r){const e=gd(r),t=pd(r.basic_info||r.basicInfo),n=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"];return{id:r.id||r.math_prob_id||"parallelogram-area-001",title:r.title||"平行四边形面积公式推导",grade:r.grade||5,unit:r.unit||r.unit_name||"多边形的面积",lesson:r.lesson||r.lesson_name||"平行四边形的面积",skill:r.skill||r.skill_description||"已知平行四边形的底和高,求平行四边形面积",objective:r.objective||"理解平行四边形面积公式 A=bh",knowledgePoints:Array.isArray(r.knowledge_points||r.knowledgePoints)?r.knowledge_points||r.knowledgePoints:n,difficulty:r.difficulty||1,description:r.description||"通过割补变换演示理解平行四边形面积公式 A=bh",metadata:r.metadata||{topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换"]},basicInfo:{...t,question:t.question||"计算下面平行四边形的面积:",answerUnit:t.answerUnit||"平方英寸",shape:t.shape||"parallelogram",base:t.base||9,height:t.height||6,baseUnit:t.baseUnit||"in",heightUnit:t.heightUnit||"in",variables:t.variables||{b:9,h:6,unit:"in"},context:t.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:Sd(r.scenes||vd(),"parallelogram",t),explanation:wd(r.explanation||_d()),answer:xd(r)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:r.answer_info||yd(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),...e,layout:r.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function Ad(r){return r?.config&&typeof r.config=="object"}function Rd(r){if(r.shapes?.static&&r.shapes?.animated)return console.log("🔍 JSON config already in system format"),r;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!r.transform,type:r.transform?.type,distance:r.transform?.translation?.distance,direction:r.transform?.translation?.direction});try{const e={...r};if(r.shapes&&typeof r.shapes=="object"){const t=[],n=[];if(r.shapes.trapezoid){const s=r.shapes.trapezoid;Array.isArray(s)?t.push(...s.map(o=>({...o,metadata:{...o.metadata,isStatic:!0}}))):typeof s=="object"&&t.push({...s,metadata:{...s.metadata,isStatic:!0}})}if(r.shapes.triangle){const s=r.shapes.triangle;Array.isArray(s)?n.push(...s.map(o=>({...o,metadata:{...o.metadata,isMovable:!0}}))):typeof s=="object"&&n.push({...s,metadata:{...s.metadata,isMovable:!0}})}(t.length===0||n.length===0)&&Object.entries(r.shapes).forEach(([s,o])=>{const i=s.toLowerCase();i.includes("static")||i.includes("original")||i.includes("trapezoid")?Array.isArray(o)?t.push(...o):o&&typeof o=="object"&&t.push(o):(i.includes("animated")||i.includes("movable")||i.includes("triangle"))&&(Array.isArray(o)?n.push(...o):o&&typeof o=="object"&&n.push(o))}),e.shapes={static:t,animated:n}}return!e.base&&r.base&&(e.base=r.base),!e.height&&r.height&&(e.height=r.height),!e.unit&&r.unit&&(e.unit=r.unit),r.transform&&r.transform.type==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:r.transform.type,translation:r.transform.translation,distance:r.transform.translation?.distance,direction:r.transform.translation?.direction}),r.transform.translation&&(e.transform={type:"translation",translation:r.transform.translation},console.log("✅ Set converted.transform with distance:",r.transform.translation.distance))):r.transform?console.log("⚠️ JSON has transform but not translation type:",r.transform.type):console.log("ℹ️ No transform found in JSON config"),e.animation?(e.animation.slider||(e.animation.slider={position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01}),e.animation.progressIndicator||(e.animation.progressIndicator={enabled:!1})):e.animation={slider:{position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}},!e.boardConfig&&r.boardConfig&&(e.boardConfig=r.boardConfig),e.strategy||(e.strategy="cut_and_paste"),e.theme||(e.theme="light"),e.layoutDensity||(e.layoutDensity="compact"),e.ui||(e.ui={layoutDensity:e.layoutDensity}),!e.baseUnit&&e.unit&&(e.baseUnit=e.unit),!e.heightUnit&&e.unit&&(e.heightUnit=e.unit),e.metadata||(e.metadata={shapeType:"parallelogram",base:e.base,height:e.height,unit:e.unit,strategy:e.strategy,generatedAt:new Date().toISOString()}),console.log("🎉 Conversion complete. Final converted config:"),console.log("📊 Final transform:",{type:e.transform?.type,distance:e.transform?.translation?.distance,direction:e.transform?.translation?.direction}),console.log("📐 Final base:",e.base,"height:",e.height),console.log("🏷️ Final strategy:",e.strategy,"theme:",e.theme),e}catch(e){return console.warn("Failed to convert parallelogram JSON config format:",e),r}}function Sd(r,e,t){if(r?.solve?.content){const n=r.solve.content.map(s=>{if(s.type==="geometryTransform"){if(Ad(s))try{const i=Rd(s.config),a=sd(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",i.transform?.translation?.distance||i.transform?.translation?.distance||"N/A"),console.log("📐 JSON base:",i.base,"height:",i.height),{...s,metadata:{...s.metadata,config:i,source:"json",validationResult:a}};console.warn("❌ JSON-provided parallelogram config validation failed:",a.errors),console.log("📊 JSON config structure:",{hasShapes:!!i.shapes,hasTransform:!!i.transform,transformType:i.transform?.type,distance:i.transform?.translation?.distance,strategy:i.strategy,theme:i.theme})}catch(i){console.warn("Failed to process JSON-provided parallelogram config:",i)}let o;try{const i=t?.base||9,a=t?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),o=ss({base:i,height:a,unit:t?.baseUnit||t?.unit||"in",originX:t?.originX,originY:t?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",o.transform?.translation?.distance||"N/A")}catch(i){console.warn("Failed to generate dynamic parallelogram config:",i),console.log("🔄 Using fallback dynamic config with base: 9, height: 6"),o=ss({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",o.transform?.translation?.distance||"N/A")}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:o.transform?.type,direction:o.transform?.translation?.direction,distance:o.transform?.translation?.distance}),{...s,metadata:{...s.metadata,config:o,source:"generated"}}}return s});return{...r,solve:{...r.solve,content:n}}}return r}const Cd="4.0.0",Ed="1.0.0",Td="mp-10506-0002-0002-G01-0001",Nd="锐角三角形面积练习",$d="通过双旋转策略练习锐角三角形面积公式 A=½bh",kd="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",Od=1,jd="g5",Id="三角形面积计算",Md=1050602,Fd="锐角三角形的面积",Pd=105060201,Dd=1002,Ld="已知锐角三角形的底和高,求三角形面积",Ud="s-105-06-0002",Gd=1002,zd=2,Bd=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],Vd={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},Wd={question:"以下三角形面积是多少?",answerUnit:"cm²",shape:"acute_triangle",base:6,height:4,baseUnit:"cm",heightUnit:"cm",originX:2,originY:2,unit:"cm²",variables:{b:6,h:4,answer:12}},qd={acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_b"},{$ref:"point_c"}],withLabel:!0,label:{offset:[-15,-15],fontSize:16,color:"#000000",anchorX:"middle",anchorY:"bottom"}},left_triangle:{id:"left_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_d"},{$ref:"point_c"}]},right_triangle:{id:"right_triangle",type:"polygon",vertices:[{$ref:"point_b"},{$ref:"point_d"},{$ref:"point_c"}]},base_segment:{id:"base_segment",type:"segment",endpoints:[{$ref:"point_a"},{$ref:"point_b"}]},height_segment:{id:"height_segment",type:"segment",endpoints:[{$ref:"point_d"},{$ref:"point_c"}]},left_rotation_center:{id:"left_rotation_center",type:"point",position:{x:3.5,y:4}},right_rotation_center:{id:"right_rotation_center",type:"point",position:{x:6.5,y:4}},full_rectangle:{id:"full_rectangle",type:"polygon",vertices:[{x:2,y:2},{x:8,y:2},{x:8,y:6},{x:2,y:6}]},base_arrow:{id:"base_arrow",type:"segment",endpoints:[{x:2,y:1.5},{x:8,y:1.5}]},height_arrow:{id:"height_arrow",type:"segment",endpoints:[{x:5,y:2},{x:5,y:6}]},base_label_position:{id:"base_label_position",type:"point",position:{x:5,y:1.2}},height_label_position:{id:"height_label_position",type:"point",position:{x:5.5,y:4}},point_a:{id:"point_a",type:"point",position:{x:2,y:2},name:"A"},point_b:{id:"point_b",type:"point",position:{x:8,y:2},name:"B"},point_c:{id:"point_c",type:"point",position:{x:5,y:6},name:"C"},point_d:{id:"point_d",type:"point",position:{x:5,y:2},name:"D"}},Yd={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},Hd={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"What is the area of the triangle?",styleRef:"text_heading_large"},{type:"graph",boardRef:"default",shapes:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{id:"base_line",type:"segment",geometryRef:"base_segment",styleRef:"base_highlight"},{id:"height_line",type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base_label",type:"text",geometryRef:"base_label_position",content:"6 cm",styleRef:"label_error"},{id:"height_label",type:"text",geometryRef:"height_label_position",content:"4 cm",styleRef:"text_primary"}]},{type:"interactive",component:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"cm²",submitButton:{label:"Submit",color:"$colors.success"}}}]},remember:{layout:{layoutRef:"vertical_spaced"},items:[{type:"text",content:"锐角三角形面积公式",styleRef:"text_heading_large"},{type:"formula",content:"A = \\frac{1}{2} \\times b \\times h",parts:["A = \\frac{1}{2} \\times b \\times h","= \\frac{1}{2} \\times 6 \\times 4","= \\frac{1}{2} \\times 24","= 12"],displayMode:!0,style:{fontSize:"$fonts.formula",color:"$colors.text_primary"}}]},solve:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"解题步骤演示",styleRef:"text_heading_large"},{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}]}},Kd={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别锐角三角形的底和高",description:"确定锐角三角形的底边长度 b = 6 cm 和对应的高度 h = 4 cm。垂足将底边平分为两段。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base-label",type:"text",position:{x:5,y:1.4},content:"6 cm",styleRef:"label_error"},{id:"height-label",type:"text",position:{x:5.3,y:4},content:"4 cm",styleRef:"label_success"}]}},{id:"exp-step-2",type:"instructionalStep",title:"双旋转策略:分割为两个直角三角形",description:"沿高线将锐角三角形分割为两个直角三角形:左直角三角形和右直角三角形。每个直角三角形将独立旋转。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"point",geometryRef:"left_rotation_center",styleRef:"primary",size:4},{type:"point",geometryRef:"right_rotation_center",styleRef:"primary",size:4}]}},{id:"exp-step-3",type:"instructionalStep",title:"刚体旋转形成矩形",description:"每个直角三角形围绕其斜边中点旋转180度,形成对应的矩形。左直角三角形形成左矩形,右直角三角形形成右矩形。",chartConfig:{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}},{id:"exp-step-4",type:"instructionalStep",title:"组合形成完整矩形并推导面积公式",description:"两个小矩形组合形成完整的大矩形,其面积为 b × h = 6 × 4 = 24 cm²。锐角三角形面积是大矩形面积的一半,即 A = ½ × b × h = 12 cm²。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"full_rectangle",styleRef:"primary"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{type:"text",position:{x:5,y:1.2},content:"Base = 6 cm",style:{fontSize:"$fonts.label",color:"$colors.error",fontWeight:"bold",anchorX:"middle"}},{type:"text",position:{x:5.5,y:4},content:"Height = 4 cm",style:{fontSize:"$fonts.label",color:"$colors.success",fontWeight:"bold"}}]}}]},Xd={value:12,unit:"cm²",type:"number",tolerance:.1,validation:{type:"exact",allowPartial:!1},explanation_text:"三角形面积 = ½ × 底 × 高 = ½ × 6cm × 4cm = 12cm²",solution_steps:["识别三角形的底和高","应用面积公式 A = ½ × b × h","代入数值:A = ½ × 6 × 4","计算:A = ½ × 24 = 12","添加单位:12 cm²"]},Jd="2026-01-20T20:34:00Z",Zd="2026-01-20T20:34:00Z",Qd={double_rotation_proof:{id:"double_rotation_proof",description:"双旋转几何证明策略",base:6,height:4,unit:"cm",strategy:"double_rotation",shapes:{static:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary",appearanceRef:"always_visible"}],animated:[{id:"left_triangle",type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left",appearanceRef:"appear_at_90"},{id:"right_triangle",type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right",appearanceRef:"appear_at_90"}]},transform:{type:"composite",transforms:[{transformRef:"left_rotation"},{transformRef:"right_rotation"}],executionMode:"parallel"},boardRef:"default",sliderRef:"slider_horizontal"}},ef={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right"}},tf={schema_version:Cd,config_version:Ed,math_prob_id:Td,title:Nd,description:$d,objective:kd,difficulty:Od,grade_id:jd,unit_name:Id,unit_id:Md,lesson_name:Fd,lesson_id:Pd,module_id:Dd,skill_description:Ld,skill_item_id:Ud,skill_id:Gd,score:zd,knowledge_points:Bd,metadata:Vd,basic_info:Wd,geometry_shapes:qd,layout:Yd,scenes:Hd,explanation:Kd,answer_info:Xd,created_at:Jd,updated_at:Zd,geometry_transform_configs:Qd,transform_definitions:ef},rf="mp-10506-0001-0001-G01-0001",nf="平行四边形面积公式推导",sf="通过割补变换演示理解平行四边形面积公式 A=bh",of="理解平行四边形面积公式 A=bh",af=1,lf="g5",cf="多边形的面积",df=1050601,ff="平行四边形的面积",uf=105060101,mf=1002,hf="已知平行四边形的底和高,求平行四边形面积",gf="s-105-06-0001",pf=1001,yf=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],bf={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},xf={question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",shape:"parallelogram",base:9,height:6,baseUnit:"in",heightUnit:"in",score:2,variables:{b:9,h:6,unit:"in"},context:{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},vf={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},_f={question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}},{type:"graph",content:"parallelogram_static",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.8,strokeColor:"#2980b9",strokeWidth:2},{id:"height-dash",type:"line",start:{x:4,y:1},end:{x:4,y:7},strokeColor:"#64748b",strokeWidth:2,dash:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16},{id:"side-label",type:"text",position:{x:2.5,y:4},content:"9 in",color:"#475569",fontSize:16}],width:400,height:300,boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1},{type:"interactive",content:"answer_input",metadata:{componentType:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"square inches",submitButton:{label:"Submit",color:"#67b510"}}}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},remember:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}},{type:"text",content:"Area = base × height",style:{color:"#64748b",marginTop:"8px"}},{type:"formula",content:"A = bh",parts:["A = bh"],displayMode:!0,style:{color:"#64748b",marginTop:"4px"}}],layout:{type:"vertical",spacing:"15px",alignment:"center",cardStyle:{backgroundColor:"#F8FAFC",borderColor:"#E3F2FD",borderWidth:"2px"}}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"text",content:"This parallelogram has base b = 9 inches and height h = 6 inches.",style:{color:"#555",marginBottom:"15px"}},{type:"text",content:"Interactive Demo: Drag the slider to transform the parallelogram into a rectangle.",style:{color:"#555",fontStyle:"italic",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{type:"text",content:"Through dissection, the parallelogram transforms into a rectangle with the same area.",style:{color:"#555",marginTop:"15px",marginBottom:"15px"}},{type:"formula",content:"A = b \\times h",parts:["A = b \\times h","= 9 \\times 6","= 54"],displayMode:!0,style:{fontSize:"1.2rem",textAlign:"center",margin:"15px 0"}},{type:"text",content:"The area of the parallelogram is 54 square inches.",style:{fontWeight:"bold",color:"#4a90e2",marginTop:"10px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}}},wf={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。",chartConfig:{type:"graph",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。",chartConfig:{type:"geometryTransform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。",chartConfig:{type:"graph",shapes:[{id:"rectangle",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:10,y:7},{x:1,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:10.5,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}}],strategy:"visual_transformation",total_steps:3,estimated_time:120,hints:[{step:1,text:"注意平行四边形的高是从底边垂直向上的距离,不是斜边的长度"},{step:2,text:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},Af={value:54,unit:"square inches",type:"numeric",tolerance:0,format:{decimal_places:0,allow_fraction:!1,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!0},explanation_text:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。",solution_steps:[{step:1,action:"identify_dimensions",description:"底边 b = 9 英寸,高 h = 6 英寸"},{step:2,action:"apply_formula",description:"面积公式 A = b × h"},{step:3,action:"calculate",description:"A = 9 × 6 = 54"},{step:4,action:"add_unit",description:"54 平方英寸"}]},Rf="2024-01-15T10:30:00Z",Sf="2024-01-15T10:30:00Z",Cf={math_prob_id:rf,title:nf,description:sf,objective:of,difficulty:af,grade_id:lf,unit_name:cf,unit_id:df,lesson_name:ff,lesson_id:uf,module_id:mf,skill_description:hf,skill_item_id:gf,skill_id:pf,knowledge_points:yf,metadata:bf,basic_info:xf,layout:vf,scenes:_f,explanation:wf,answer_info:Af,created_at:Rf,updated_at:Sf},Ef={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function Tf(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
|
|
21
|
+
`)}`);return o}static validate(e,t){if(!this.canResolve(e))return!1;let n;const s=e.match(ie.ANIMATION_REF);return s?n=s[1]:n=e,n in(t.animationConfigs||{})}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`动画引用解析失败: ${s}`,o)}return n}static extractAnimationRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.animationRef&&typeof s.animationRef=="string"&&t.push(s.animationRef),s.chartConfig?.animationRef&&typeof s.chartConfig.animationRef=="string"&&t.push(s.chartConfig.animationRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}function Uc(){return{type:ee.ANIMATION_REF,canResolve:st.canResolve.bind(st),resolve:st.resolve.bind(st),validate:st.validate.bind(st)}}class Je{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.SLIDER_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t){if(console.error("🔍 SliderRefResolver.resolve called:",{ref:e,hasContext:!!t,contextKeys:Object.keys(t||{}),animationDefinitionsKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[],animationConfigsKeys:t.animationConfigs?Object.keys(t.animationConfigs):[]}),!this.canResolve(e))throw new me(B.SLIDER_REF_NOT_FOUND,`无法解析的滑块引用: ${e}`);const n=e.match(ie.SLIDER_REF),s=n?n[1]:e;let o=t.animationDefinitions?.[s];return!o&&t.animationConfigs&&(o=t.animationConfigs[s]),!o&&it?.animationDefinitions&&(o=it.animationDefinitions[s]),!o&&it?.animationConfigs&&(o=it.animationConfigs[s]),console.error("🔍 SliderRefResolver.resolve lookup:",{sliderConfigId:s,hasRawConfig:!!o,rawConfig:o,animationDefinitions:t.animationDefinitions,animationConfigs:t.animationConfigs,hasGlobalContext:!!it}),o?this.validateAndTransformConfig(s,o):(console.warn(`⚠️ 滑块配置未找到: ${s},使用默认配置`),{...Gc,id:s})}static validateAndTransformConfig(e,t){if(!t.slider)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置格式错误: ${e} 缺少 slider 对象`);const{slider:n}=t,s=["position","length","orientation","min","max","step"];for(const o of s)if(!(o in n))throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider 缺少 ${o} 字段`);if(!Array.isArray(n.position)||n.position.length!==2)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.position 必须是长度为 2 的数组`);if(n.orientation!=="horizontal"&&n.orientation!=="vertical")throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.orientation 必须是 "horizontal" 或 "vertical"`);if(n.min>=n.max)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.min 必须小于 slider.max`);if(n.step<=0)throw new me(B.SLIDER_REF_NOT_FOUND,`滑块配置 ${e} 中 slider.step 必须大于 0`);return{id:e,slider:{position:n.position,length:n.length,orientation:n.orientation,min:n.min,max:n.max,step:n.step},progressIndicator:t.progressIndicator,duration:t.duration,easing:t.easing,description:t.description}}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ie.SLIDER_REF),s=n?n[1]:e;return s in(t.animationDefinitions||{})||s in(t.animationConfigs||{}),!0}static batchResolve(e,t){const n={};for(const s of e)if(this.canResolve(s))try{n[s]=this.resolve(s,t)}catch(o){console.warn(`滑块引用解析失败: ${s}`,o)}return n}static extractSliderRefs(e){const t=[],n=s=>{if(!(!s||typeof s!="object")){s.sliderRef&&typeof s.sliderRef=="string"&&t.push(s.sliderRef),s.chartConfig?.sliderRef&&typeof s.chartConfig.sliderRef=="string"&&t.push(s.chartConfig.sliderRef);for(const o of Object.values(s))Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return n(e),[...new Set(t)]}}const Gc={id:"default_slider",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"默认滑块配置(引用未找到时使用)"};function zc(){return{type:ee.SLIDER_REF,canResolve:Je.canResolve.bind(Je),resolve:Je.resolve.bind(Je),validate:Je.validate.bind(Je)}}class ot{static canResolve(e){return typeof e!="string"||e.length===0?!1:ie.GEOMETRY_TRANSFORM_REF.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}static resolve(e,t,n){if(!this.canResolve(e))throw new Error(`无法解析的几何变换引用: ${e}`);const s=e.match(ie.GEOMETRY_TRANSFORM_REF),o=s?s[1]:e;console.error(`🔍 GeometryTransformRefResolver.resolve: 解析引用 ${e} -> ${o}`,{hasGeometryTransformConfigs:!!t.geometryTransformConfigs,configKeys:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});const i=t.geometryTransformConfigs?.[o];if(!i)throw new me(B.GEOMETRY_TRANSFORM_REF_NOT_FOUND,`几何变换配置未找到: ${o}`,{reference:e,configId:o,availableConfigs:t.geometryTransformConfigs?Object.keys(t.geometryTransformConfigs):[]});console.error("✅ 找到几何变换配置:",i);const a=n?this.applyOverride(i,n):{...i};return console.error("📋 应用覆盖后的配置:",a),a}static applyOverride(e,t){const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&(n[s]=o);return t.shapes&&(n.shapes={static:[...n.shapes?.static||[]],animated:[...n.shapes?.animated||[]]},t.shapes.static&&(n.shapes.static=t.shapes.static),t.shapes.animated&&(n.shapes.animated=t.shapes.animated)),t.transform&&(n.transform={...n.transform,...t.transform}),n}static validate(e,t){if(!this.canResolve(e))return!1;const n=e.match(ie.GEOMETRY_TRANSFORM_REF),s=n?n[1]:e;return!!t.geometryTransformConfigs?.[s]}static batchResolve(e,t,n){const s={};for(const o of e)if(this.canResolve(o)&&this.validate(o,t))try{const i=n?.[o];s[o]=this.resolve(o,t,i)}catch(i){console.warn(`几何变换引用解析失败: ${o}`,i)}return s}static extractFromContentBlock(e){return!e||typeof e!="object"?null:e.geometryTransformRef&&typeof e.geometryTransformRef=="string"?e.geometryTransformRef:null}static extractFromContentBlocks(e){const t=[];for(const n of e){const s=this.extractFromContentBlock(n);s&&t.push(s)}return[...new Set(t)]}}function Bc(){return{type:ee.GEOMETRY_TRANSFORM_REF,canResolve:ot.canResolve.bind(ot),resolve:ot.resolve.bind(ot),validate:ot.validate.bind(ot)}}const Pr={geometryRef:ee.GEOMETRY_REF,styleRef:ee.STYLE_REF,layoutRef:ee.LAYOUT_REF,boardRef:ee.BOARD_REF,animationRef:ee.ANIMATION_REF,transformRef:ee.TRANSFORM_REF,appearanceRef:ee.STYLE_REF,geometryTransformRef:ee.GEOMETRY_TRANSFORM_REF,sliderRef:ee.SLIDER_REF,$ref:ee.GEOMETRY_REF};class Vc{static extractRefs(e){const t=[],n=new Set,s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o)){if(i in Pr){if(typeof a=="string"){const c=Pr[i],l=`${i}:${a}`;n.has(l)||(n.add(l),t.push({ref:a,type:c,path:i,value:a,fieldName:i,combined:l}))}continue}if(typeof a=="string"){this.extractDesignTokens(a).forEach(l=>{const d=`$ref:${l}`;n.has(d)||(n.add(d),t.push({ref:l,type:ee.GEOMETRY_REF,path:"$ref",value:l,fieldName:"$ref",combined:d}))});continue}if(Array.isArray(a)){a.forEach(c=>s(c));continue}typeof a=="object"&&s(a)}};return s(e),t}static extractDesignTokens(e){const t=[],n=/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g;let s;for(;(s=n.exec(e))!==null;)t.push(s[0]);return t}static calculateStats(e){const t=this.extractRefs(e).map(o=>o.ref),n={},s=o=>{if(!(!o||typeof o!="object"))for(const[i,a]of Object.entries(o))i in Pr?n[i]=(n[i]||0)+1:typeof a=="object"&&s(a)};return s(e),{totalRefs:t.length,uniqueRefs:new Set(t).size,fieldCounts:n}}}class mt{resolvers=[];constructor(){this.registerDefaultResolvers()}registerDefaultResolvers(){this.register(Mc()),this.register(Fc()),this.register(Pc()),this.register(Dc()),this.register(Lc()),this.register(Uc()),this.register(zc()),this.register(Bc())}register(e){this.resolvers.push(e)}getAllResolvers(){return[...this.resolvers]}getResolverByType(e){return this.resolvers.find(t=>t.type===e)}getResolverForRef(e){return this.resolvers.find(t=>t.canResolve(e))}resolve(e,t){if(typeof e!="string"){const s=this.getResolverByType(e.type);if(!s)throw new Error(`找不到类型为 ${e.type} 的解析器`);try{return s.resolve(e.value,t)}catch(o){throw new Error(`解析器 ${e.type} 解析 ${e.combined} 失败: ${o}`)}}const n=this.resolvers.filter(s=>s.canResolve(e));if(n.length===0)throw new Error(`没有找到适合的解析器: ${e}`);for(const s of n)try{return s.resolve(e,t)}catch(o){console.debug(`解析器 ${s.type} 解析 ${e} 失败:`,o);continue}throw new Error(`所有解析器都无法解析引用: ${e}`)}batchResolve(e,t){const n={};for(const s of e)try{const o=this.resolve(s,t),i=typeof s=="string"?s:s.combined;n[i]=o}catch(o){const i=typeof s=="string"?s:s.combined;console.warn(`引用解析失败: ${i}`,o)}return n}extractAllRefsEnhanced(e){try{return Vc.extractRefs(e)}catch(t){return console.warn("ReferenceExtractor 提取失败:",t),[]}}extractAllRefs(e){return this.extractAllRefsEnhanced(e).map(n=>n.combined)}extractAllRefsLegacy(e){const t=[],n=s=>{if(!(!s||typeof s!="object"))for(const[o,i]of Object.entries(s))if(o.endsWith("Ref")&&typeof i=="string")t.push(i);else if(typeof i=="string"&&i.includes("$")){const a=i.match(/\$[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*/g);a&&t.push(...a)}else Array.isArray(i)?i.forEach(a=>n(a)):typeof i=="object"&&n(i)};return n(e),[...new Set(t)]}validate(e,t){const n=this.getResolverForRef(e);if(!n)return!1;if(n.validate)return n.validate(e,t);try{return n.resolve(e,t),!0}catch{return!1}}}function No(){return new mt}class er{static transform(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;console.error("🔄 GraphTransformer.transform START for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o,contextGeometryKeys:Object.keys(t.geometryPresets||{})}),console.error("🎯 GraphTransformer.transform called for content block:",{blockType:e.type,hasShapes:Array.isArray(e.shapes),shapesCount:e.shapes?e.shapes.length:0,enableReferenceResolution:s,strictMode:o}),e.shapes&&Array.isArray(e.shapes)&&console.warn(`📊 GraphTransformer contentBlock shapes (${e.shapes.length}):`,e.shapes.map(a=>({id:a.id,type:a.type,geometryRef:a.geometryRef,styleRef:a.styleRef})));const i={...e,type:ye.GRAPH};if(!s)return i;try{if(i.boardRef&&(i.boardConfig=this.resolveBoardConfig(i.boardRef,t),delete i.boardRef),Array.isArray(i.shapes)&&(console.error(`🎯 GraphTransformer处理shapes数组,数量: ${i.shapes.length}`),i.shapes=i.shapes.map((a,c)=>(console.error(` 🎯 处理shape[${c}]:`,{id:a.id,geometryRef:a.geometryRef,styleRef:a.styleRef,keys:Object.keys(a)}),this.transformShape(a,t,{strictMode:o})))),i.styleRef){try{const a=we.resolve(i.styleRef,t);i.style=a}catch(a){if(o)throw a;console.warn(`图形样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}if(i.animationRef){console.warn(`🎬 GraphTransformer处理animationRef: ${i.animationRef}`);try{const a=i.animationRef.startsWith("animationRef:")?i.animationRef:`animationRef:${i.animationRef}`,c=st.resolve(a,t);console.warn(" 动画配置解析结果:",{animationId:c.id,transformCount:c.transforms.length,hasControl:!!c.control,controlConfig:c.control,hasVisualEffects:!!c.visualEffects,visualEffectsCount:c.visualEffects?.length||0}),i.animation=c,i.transformDefinitions&&(console.warn(" 清理旧的 transformDefinitions(被 animation 替代)"),delete i.transformDefinitions)}catch(a){if(o)throw a;console.warn(`❌ 动画配置解析失败: ${i.animationRef}`,a)}delete i.animationRef}else i.animation&&(console.warn("🎬 GraphTransformer检测到内联动画配置:",{animationId:i.animation.id,transformCount:i.animation.transforms?.length||0}),i.animation.transforms&&Array.isArray(i.animation.transforms)?console.warn(` 内联动画配置有效,transforms 数量: ${i.animation.transforms.length}`):(console.warn(" ⚠️ 内联动画配置格式无效,缺少 transforms 数组"),delete i.animation));return i}catch(a){if(o)throw a;return console.warn("图形转换失败:",a),i}}static transformShape(e,t,n={}){const{strictMode:s=!1}=n;console.error("🔄 GraphTransformer.transformShape START for shape:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:"geometryRef"in e,geometryRef:e.geometryRef,hasStyleRef:"styleRef"in e,styleRef:e.styleRef,allShapeKeys:Object.keys(e),contextGeometryKeys:Object.keys(t.geometryPresets||{})}),(e.id==="base_line"||e.id==="height_line")&&console.error(`🔍 特别处理 ${e.id}:`,{id:e.id,type:e.type,geometryRef:e.geometryRef,styleRef:e.styleRef,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints)});let o={...e};e.type==="point"&&console.warn(`📌 GraphTransformer processing point ${e.id}:`,{id:e.id,type:e.type,position:e.position,positionType:typeof e.position,positionIsArray:Array.isArray(e.position),shapeKeys:Object.keys(e)});try{if(o.geometryRef){console.warn(`🔄 GraphTransformer processing geometryRef: ${o.geometryRef} for shape ${o.id}`,{shapeId:o.id,shapeType:o.type,geometryRef:o.geometryRef,contextHasGeometryPresets:!!t.geometryPresets,geometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});try{const i=Be.resolve(o.geometryRef,t);console.warn(` Geometry resolved for ${o.geometryRef}:`,{type:i.type,hasVertices:"vertices"in i,vertices:i.vertices,hasPosition:"position"in i,position:i.position,hasEndpoints:"endpoints"in i,endpoints:i.endpoints,endpointsIsArray:Array.isArray(i.endpoints),geometryKeys:Object.keys(i)});const a=o.type,c=o.content,l={...o};Object.assign(o,i),o.id=e.id,a!==void 0&&(o.type=a),c!==void 0&&(o.content=c),console.warn(` After merge for ${o.id}:`,{type:o.type,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:"undefined",position:o.position,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),transformedShapeKeys:Object.keys(o)});const d=o.type;let u=!1;const y=t.geometryPresets[o.geometryRef];if(console.warn("🔍 DEBUG: 检查原始几何定义",{geometryRef:o.geometryRef,originalGeometryExists:!!y,originalGeometryType:y?.type,originalGeometryKeys:y?Object.keys(y):[],hasVertices:y&&"vertices"in y,verticesIsArray:y&&Array.isArray(y.vertices),verticesLength:y?.vertices?.length,contextGeometryPresetsKeys:Object.keys(t.geometryPresets||{})}),y&&y.vertices&&Array.isArray(y.vertices)){if(console.warn("📌 原始几何定义有vertices,检查$ref引用",{originalVertices:y.vertices,hasWithLabel:"withLabel"in y,withLabel:y.withLabel,hasLabel:"label"in y,label:y.label}),o.verticesConfig||(o.verticesConfig={}),y.vertices.forEach((m,h)=>{if(console.warn(`🔍 DEBUG: 检查顶点${h}:`,{vertex:m,isObject:m&&typeof m=="object",hasDollarRef:m&&typeof m=="object"&&"$ref"in m,refName:m?.$ref}),m&&typeof m=="object"&&"$ref"in m){const g=m.$ref;if(console.warn(`🔍 DEBUG: 找到$ref引用 ${g},检查context.geometryPresets`),t.geometryPresets&&t.geometryPresets[g]){const p=t.geometryPresets[g];console.warn(`🔍 DEBUG: 找到点定义 ${g}:`,p),p.name?(o.verticesConfig[h]||(o.verticesConfig[h]={}),o.verticesConfig[h].name=p.name,console.warn(`✅ 从原始几何定义提取顶点${h}名字: ${p.name}`)):console.warn(`⚠️ 点定义 ${g} 没有name属性`)}else console.warn(`⚠️ context.geometryPresets 中未找到 ${g}`)}else console.warn(`⚠️ 顶点${h}不是$ref对象`)}),y.withLabel!==void 0&&(o.verticesConfig.withLabel=y.withLabel),y.label&&typeof y.label=="object"){const m=y.label;m.offset&&Array.isArray(m.offset)&&m.offset.length>=2&&(o.verticesConfig.offset=m.offset),m.fontSize!==void 0&&(o.verticesConfig.fontSize=m.fontSize),m.color&&(o.verticesConfig.color=m.color),m.anchorX&&(o.verticesConfig.anchorX=m.anchorX),m.anchorY&&(o.verticesConfig.anchorY=m.anchorY)}console.warn("✅ 构建的verticesConfig:",o.verticesConfig)}if(d==="segment"||d==="line"?u="endpoints"in o&&Array.isArray(o.endpoints):d==="point"?u="position"in o&&o.position!==void 0:d==="polygon"||d==="triangle"||d==="rectangle"||d==="parallelogram"?u="vertices"in o&&Array.isArray(o.vertices):u="vertices"in o&&Array.isArray(o.vertices)||"endpoints"in o&&Array.isArray(o.endpoints)||"position"in o&&o.position!==void 0,u||(console.error(`❌ ERROR: After geometryRef merge, shape ${o.id} (type: ${d}) has no valid geometry properties!`),console.error(" geometry keys:",Object.keys(i)),console.error(" geometry.type:",i.type),console.error(" transformedShape keys:",Object.keys(o))),i.styleRef){console.error(`🎨 GraphTransformer处理几何styleRef: ${i.styleRef}`);const m=we.resolve(i.styleRef,t);console.error(" 几何样式解析结果:",m),o.style=m}}catch(i){if(s)throw i;console.error(`❌ 图形几何解析失败: ${o.geometryRef}`,i),console.error(` shape id: ${o.id}, type: ${o.type}`),console.error(" context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):"undefined")}delete o.geometryRef}if(o.styleRef){console.error(`🎨 GraphTransformer处理形状styleRef: ${o.styleRef}, shape id: ${o.id}`);try{const i=we.resolve(o.styleRef,t);console.error(" 形状样式解析成功:",i);const{id:a,...c}=i;o={...o,...c,style:{...o.style,...i}}}catch(i){if(s)throw i;console.warn(`图形元素样式解析失败: ${o.styleRef}`,i),delete o.style}delete o.styleRef}if(Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(i=>this.transformTransform(i,t,{strictMode:s}))),o.label&&typeof o.label=="object"&&(o.label=this.transformLabel(o.label,t)),console.warn(`🔍 Checking segment conversion for ${o.id}:`,{type:o.type,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,endpointsIsArray:Array.isArray(o.endpoints),endpointsLength:o.endpoints?o.endpoints.length:0,shapeKeys:Object.keys(o)}),o=this.convertShapeCoordinates(o,t),o.type==="segment"&&Array.isArray(o.endpoints)&&o.endpoints.length>=2){console.warn(`🔄 Converting segment to line for ${o.id}:`,{originalType:o.type,endpoints:o.endpoints}),o.type="line";const i=this.resolvePointReference(o.endpoints[0],t),a=this.resolvePointReference(o.endpoints[1],t);Array.isArray(i)&&i.length>=2?o.start={x:i[0],y:i[1]}:i&&typeof i=="object"&&"x"in i&&"y"in i?o.start=i:o.start=o.endpoints[0],Array.isArray(a)&&a.length>=2?o.end={x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?o.end=a:o.end=o.endpoints[1],delete o.endpoints}return console.warn(`✅ GraphTransformer finished transforming shape ${o.id} (${o.type}):`,{id:o.id,type:o.type,hasVertices:"vertices"in o,vertices:o.vertices,verticesIsArray:Array.isArray(o.vertices),verticesLength:o.vertices?o.vertices.length:0,hasVerticesConfig:"verticesConfig"in o,verticesConfig:o.verticesConfig,verticesConfigKeys:o.verticesConfig?Object.keys(o.verticesConfig):[],hasPosition:"position"in o,position:o.position,hasStart:"start"in o,start:o.start,hasEnd:"end"in o,end:o.end,hasEndpoints:"endpoints"in o,endpoints:o.endpoints,hasGeometryRef:"geometryRef"in o,geometryRef:o.geometryRef,keys:Object.keys(o)}),o}catch(i){if(s)throw i;return console.warn("图形元素转换失败:",i),o}}static resolvePointReference(e,t){if(!e||typeof e!="object")return e;if("$ref"in e){const n=e.$ref;if(t&&t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}if("geometryRef"in e){const n=e.geometryRef;if(t&&t.geometryPresets&&t.geometryPresets[n]){const s=t.geometryPresets[n];if(s.position)return s.position;if("x"in s&&"y"in s)return s}return e}return e}static convertShapeCoordinates(e,t){if(!e||typeof e!="object")return e;console.warn("🔄 GraphTransformer.convertShapeCoordinates START for shape:",{id:e.id,type:e.type,hasVertices:"vertices"in e,verticesIsArray:Array.isArray(e.vertices),verticesLength:e.vertices?e.vertices.length:"undefined",shapeKeys:Object.keys(e)});const n={...e};if(n.position){if(Array.isArray(n.position)&&n.position.length>=2)console.warn(`🔄 Converting position array to object for ${n.id}:`,{shapeId:n.id,positionArray:n.position,convertedTo:{x:n.position[0],y:n.position[1]}}),n.position={x:n.position[0],y:n.position[1]};else if(typeof n.position=="object"){const s=this.resolvePointReference(n.position,t);s&&typeof s=="object"&&(n.position=s)}}if(Array.isArray(n.vertices)){const s=n.verticesConfig?{...n.verticesConfig}:{};if(console.warn("🔍 convertShapeCoordinates: 初始化 verticesConfig",{hasExisting:!!n.verticesConfig,existingKeys:n.verticesConfig?Object.keys(n.verticesConfig):[],verticesConfigKeys:Object.keys(s)}),n.vertices=n.vertices.map((o,i)=>{const a=this.resolvePointReference(o,t);let c=null;if(o&&typeof o=="object"&&"$ref"in o){const l=o.$ref;t&&t.geometryPresets&&t.geometryPresets[l]&&(c=t.geometryPresets[l],console.warn(`📌 Found point definition for ${l} at vertex ${i}:`,{hasWithLabel:"withLabel"in c,withLabel:c.withLabel,hasLabel:"label"in c,labelKeys:c.label?Object.keys(c.label):"none"}),c.name&&(s[i]||(s[i]={}),s[i].name=c.name))}return Array.isArray(a)&&a.length>=2?{x:a[0],y:a[1]}:a&&typeof a=="object"&&"x"in a&&"y"in a?a:(o&&typeof o=="object"&&("$ref"in o||"geometryRef"in o),o)}),n.withLabel!==void 0||n.label){const o={withLabel:n.withLabel!==void 0?n.withLabel:!0};if(n.label&&typeof n.label=="object"){const a=n.label;a.offset&&Array.isArray(a.offset)&&a.offset.length>=2&&(o.offset=a.offset),a.fontSize!==void 0&&(o.fontSize=a.fontSize),a.color&&(o.color=a.color),a.anchorX&&(o.anchorX=a.anchorX),a.anchorY&&(o.anchorY=a.anchorY)}const i={...o};for(const a in s)isNaN(Number(a))||(i[a]||(i[a]={}),Object.assign(i[a],s[a]));n.verticesConfig=i,console.warn(`✅ Added merged verticesConfig for polygon ${n.id}:`,i)}else Object.keys(s).length>0&&(n.verticesConfig=s,console.warn(`✅ Added verticesConfig for polygon ${n.id}:`,s))}if(Array.isArray(n.endpoints)&&(n.endpoints=n.endpoints.map(s=>{const o=this.resolvePointReference(s,t);return Array.isArray(o)&&o.length>=2?{x:o[0],y:o[1]}:o&&typeof o=="object"&&"x"in o&&"y"in o?o:(s&&typeof s=="object"&&("$ref"in s||"geometryRef"in s),s)})),Array.isArray(n.center)&&n.center.length>=2)n.center={x:n.center[0],y:n.center[1]};else if(n.center&&typeof n.center=="object"){const s=this.resolvePointReference(n.center,t);s&&typeof s=="object"&&(n.center=s)}if(n.start){if(Array.isArray(n.start)&&n.start.length>=2)n.start={x:n.start[0],y:n.start[1]};else if(typeof n.start=="object"){const s=this.resolvePointReference(n.start,t);s&&typeof s=="object"&&(n.start=s)}}if(n.end){if(Array.isArray(n.end)&&n.end.length>=2)n.end={x:n.end[0],y:n.end[1]};else if(typeof n.end=="object"){const s=this.resolvePointReference(n.end,t);s&&typeof s=="object"&&(n.end=s)}}for(const[s,o]of Object.entries(n))Array.isArray(o)?n[s]=o.map(i=>typeof i=="object"?this.convertShapeCoordinates(i,t):i):o&&typeof o=="object"&&(n[s]=this.convertShapeCoordinates(o,t));return n}static transformTransform(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.transformRef){try{const i=Se.resolve(o.transformRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformLabel(e,t){const n={...e};if(n.styleRef){try{const s=we.resolve(n.styleRef,t);n.style=s}catch(s){console.warn(`标签样式解析失败: ${n.styleRef}`,s)}delete n.styleRef}return n}static resolveBoardConfig(e,t){if(t.boardDefinitions&&t.boardDefinitions[e])return t.boardDefinitions[e];const n={default:{originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1},extended:{originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1}};return n[e]||n.default}static validate(e){const t=[];return e?(e.type!==ye.GRAPH&&t.push(`图形内容块类型应为 'graph',实际为 '${e.type}'`),Array.isArray(e.shapes)?e.shapes.length===0&&t.push("图形内容块 shapes 数组不能为空"):t.push("图形内容块缺少 shapes 数组"),t):(t.push("图形内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(s=>s.type===ye.GRAPH).map(s=>this.transform(s,t,n))}}function Wc(){return{type:ye.GRAPH,transform:er.transform.bind(er),validate:er.validate.bind(er)}}class tr{static normalizeShapes(e){if(!e||typeof e!="object")return{static:[],animated:[]};const t={static:Array.isArray(e.static)?e.static:[],animated:Array.isArray(e.animated)?e.animated:[]};return console.error("🔍 GeometryTransformTransformer.normalizeShapes:",{inputShapes:e,normalized:t,hasStatic:Array.isArray(e.static),hasAnimated:Array.isArray(e.animated),staticLength:t.static.length,animatedLength:t.animated.length}),t}static transform(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;if(e.geometryTransformRef){console.error("🔍 GeometryTransformTransformer.transform: 检测到几何变换引用",{geometryTransformRef:e.geometryTransformRef,hasOverride:!!e.override});try{if(s){console.error("🔍 GeometryTransformTransformer: 解析 geometryTransformRef:",e.geometryTransformRef);const d=ot.resolve(e.geometryTransformRef,t,e.override);console.error("🔍 GeometryTransformTransformer: resolvedConfig:",d),console.error("🔍 GeometryTransformTransformer: resolvedConfig keys:",Object.keys(d||{}));const u={type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:d}};return console.error("🔍 几何变换引用解析完成,继续处理几何引用:",u.metadata.config),u.metadata.config&&typeof u.metadata.config=="object"&&(console.error("🔍 处理引用配置中的 geometryRef"),u.metadata.config=this.transformConfig(u.metadata.config,t,{strictMode:o})),console.error("🔍 GeometryTransformTransformer: 返回解析后的 transformed:",u),console.error("🔍 GeometryTransformTransformer: transformed.metadata.config:",u.metadata.config),u}else return console.warn("⚠️ 几何变换引用解析被禁用,使用默认配置"),{type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:6,height:4,unit:"cm",strategy:"default",shapes:{static:[],animated:[]},transform:{type:"composite",transforms:[]}}}}}catch(d){if(o)throw d;console.error("❌ 几何变换引用解析失败:",d),console.error("❌ contentBlock:",e),console.error("❌ context.geometryTransformConfigs:",t.geometryTransformConfigs)}}const i=e.base||e.config?.base||t.basicInfo?.base||0,a=e.height||e.config?.height||t.basicInfo?.height||0,c=e.unit||e.config?.unit||t.basicInfo?.baseUnit||"cm",l={...e,type:ye.GEOMETRY_TRANSFORM,metadata:{componentType:"geometry-transform",config:{base:i,height:a,unit:c,...e.config||{},shapes:this.normalizeShapes(e.shapes||e.config?.shapes),transform:e.transform||e.config?.transform||{},animation:e.animation||e.config?.animation||{},boardConfig:e.boardConfig||e.config?.boardConfig||{}}}};if(console.error("🔍 GeometryTransformTransformer.transform: 转换后配置 =",{metadataConfig:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasTransformRef:!!e.transformRef,transformRef:e.transformRef,originalContentBlock:e}),delete l.config,delete l.base,delete l.height,delete l.unit,delete l.shapes,delete l.transform,delete l.animation,delete l.boardConfig,!s)return l;try{if(l.geometryRef){try{const d=Be.resolve(l.geometryRef,t);if(l.metadata.config||(l.metadata.config={}),Object.assign(l.metadata.config,d),d.styleRef){const u=we.resolve(d.styleRef,t);l.metadata.config.style=u}}catch(d){if(o)throw d;console.warn(`几何变换几何解析失败: ${l.geometryRef}`,d)}delete l.geometryRef}if(l.transformRef){try{const d=Se.resolve(l.transformRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.transform||(l.metadata.config.transform={}),Object.assign(l.metadata.config.transform,d)}catch(d){if(o)throw d;console.warn(`几何变换变换解析失败: ${l.transformRef}`,d)}delete l.transformRef}if(console.error("🔍 GeometryTransformTransformer.transform: 检查 metadata.config",{hasMetadata:!!l.metadata,hasConfig:!!l.metadata?.config,configType:l.metadata?.config?typeof l.metadata.config:"undefined",configIsObject:l.metadata?.config?typeof l.metadata.config=="object":!1,configKeys:l.metadata?.config?Object.keys(l.metadata.config):[]}),l.metadata?.config&&typeof l.metadata.config=="object"?(console.error("🔍 GeometryTransformTransformer.transform: 调用 transformConfig"),l.metadata.config=this.transformConfig(l.metadata.config,t,{strictMode:o}),console.error("🔍 GeometryTransformTransformer.transform: transformConfig 调用完成")):console.error("🔍 GeometryTransformTransformer.transform: 不满足调用条件,跳过 transformConfig"),l.styleRef){try{const d=we.resolve(l.styleRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.style=d}catch(d){if(o)throw d;console.warn(`几何变换样式解析失败: ${l.styleRef}`,d)}delete l.styleRef}if(l.animationRef){try{const d=this.resolveAnimationConfig(l.animationRef,t,{strictMode:o});l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层动画引用解析失败: ${l.animationRef}`,d)}delete l.animationRef}if(l.sliderRef){try{const d=Je.resolve(l.sliderRef,t);l.metadata.config||(l.metadata.config={}),l.metadata.config.animation={...d,...l.metadata.config.animation||{}}}catch(d){if(o)throw d;console.warn(`顶层滑块引用解析失败: ${l.sliderRef}`,d)}delete l.sliderRef}if(l.boardRef){console.error("🔍 GeometryTransformTransformer.transform: 处理顶层 boardRef",{boardRef:l.boardRef,hasMetadataConfig:!!l.metadata?.config,currentBoardConfig:l.metadata?.config?.boardConfig});try{const d=this.resolveBoardConfig(l.boardRef,t,{strictMode:o});console.error("🔍 解析后的 boardConfig:",d),l.metadata.config||(l.metadata.config={}),l.metadata.config.boardConfig={...d,...l.metadata.config.boardConfig||{}},console.error("🔍 设置后的 metadata.config.boardConfig:",l.metadata.config.boardConfig)}catch(d){if(o)throw d;console.warn(`顶层画板引用解析失败: ${l.boardRef}`,d)}delete l.boardRef}if(l.metadata?.config?.boardConfig&&typeof l.metadata.config.boardConfig=="object"){const d=l.metadata.config.boardConfig;(!d.boundingBox||!Array.isArray(d.boundingBox)||d.boundingBox.length!==4)&&(console.error("🔍 GeometryTransformTransformer: boardConfig 缺少 boundingBox,使用默认值"),d.boundingBox=[0,7,10,0],d.originX=d.originX??2,d.originY=d.originY??2,d.keepAspectRatio=d.keepAspectRatio??!0,d.showGrid=d.showGrid??!1,d.showAxis=d.showAxis??!1,d.description=d.description||"默认画板配置")}return console.error("🔍 GeometryTransformTransformer.transform: 最终转换结果 =",{type:l.type,metadataConfig:l.metadata?.config,shapesAnimatedLength:l.metadata?.config?.shapes?.animated?.length,shapesStaticLength:l.metadata?.config?.shapes?.static?.length,base:l.metadata?.config?.base,height:l.metadata?.config?.height,unit:l.metadata?.config?.unit,hasTransform:!!l.metadata?.config?.transform,transform:l.metadata?.config?.transform,hasAnimation:!!l.metadata?.config?.animation,animation:l.metadata?.config?.animation,hasBoardConfig:!!l.metadata?.config?.boardConfig,boardConfig:l.metadata?.config?.boardConfig}),l}catch(d){if(o)throw d;return console.warn("几何变换转换失败:",d),l}}static transformConfig(e,t,n={}){const{strictMode:s=!1}=n,o={...e},i={};if(o.shapes&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 shapes"),console.error(" transformedConfig.shapes:",o.shapes),o.shapes.static&&(console.error(` 处理 static shapes (${o.shapes.static.length}):`),o.shapes.static=o.shapes.static.map((a,c)=>{console.error(` 处理 static shape[${c}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:s});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 static shape[${c}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l})),o.shapes.animated&&(console.error(` 处理 animated shapes (${o.shapes.animated.length}):`),o.shapes.animated=o.shapes.animated.map((a,c)=>{console.error(` 处理 animated shape[${c}]:`,{id:a.id,type:a.type,hasGeometryRef:!!a.geometryRef,geometryRef:a.geometryRef,shapeKeys:Object.keys(a)});const l=this.transformShape(a,t,{strictMode:s});return a.geometryRef&&l.id&&(i[a.geometryRef]=l.id,console.error(` 记录映射: geometryRef "${a.geometryRef}" -> shapeId "${l.id}" (转换后)`)),console.error(` 转换后的 animated shape[${c}]:`,{id:l.id,type:l.type,hasGeometryRef:!!l.geometryRef,geometryRef:l.geometryRef,hasVertices:!!l.vertices,vertices:l.vertices}),l}))),o.transform){if(o.transform.transformRef)try{const a=Se.resolve(o.transform.transformRef,t);o.transform={...a,...o.transform,transformRef:void 0},console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transform 对象中的 transformRef",{originalTransformRef:o.transform.transformRef,resolvedTransform:a,mergedTransform:o.transform})}catch(a){if(s)throw a;console.warn(`Transform ref解析失败: ${o.transform.transformRef}`,a)}o.transform=this.normalizeTransformConfig(o.transform,i),Array.isArray(o.transform.transforms)&&(console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 transforms 数组",{transformsLength:o.transform.transforms.length,transforms:o.transform.transforms}),o.transform.transforms=o.transform.transforms.map((a,c)=>{if(console.error(`🔍 处理 transform[${c}]:`,{type:typeof a,isString:typeof a=="string",isObject:typeof a=="object"&&a!==null,transformItem:a,hasTransformRef:a&&typeof a=="object"&&"transformRef"in a,transformRef:a&&typeof a=="object"?a.transformRef:void 0}),typeof a=="string"){if(console.error(`🔍 transform[${c}] 是字符串格式`),a.startsWith("transformRef:")){const l=a.replace("transformRef:","");console.error(`🔍 解析 transformRef 字符串: ${l}`);try{const d=Se.resolve(l,t);console.error(`🔍 transform[${c}] 解析成功:`,d);const u=this.normalizeTransformConfig(d,i);return console.error(`🔍 transform[${c}] 标准化后:`,u),u}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}try{const l=Se.resolve(a,t);return this.normalizeTransformConfig(l,i)}catch(l){if(s)throw l;return console.warn(`Transform ref解析失败: ${a}`,l),a}}else if(a&&typeof a=="object"&&a.transformRef){const l=a.transformRef;console.error(`🔍 transform[${c}] 是对象格式,refName=${l}`);try{const d=Se.resolve(l,t);console.error(`🔍 transform[${c}] 解析成功:`,d);const u={...d,...a,transformRef:void 0};console.error(`🔍 transform[${c}] 合并后:`,u);const y=this.normalizeTransformConfig(u,i);return console.error(`🔍 transform[${c}] 标准化后:`,y),y}catch(d){if(s)throw d;return console.warn(`Transform ref解析失败: ${l}`,d),a}}else if(a&&typeof a=="object")return console.error(`🔍 transform[${c}] 已是对象格式,标准化`),this.normalizeTransformConfig(a,i);return console.error(`🔍 transform[${c}] 未处理,返回原始值:`,a),a}))}if(o.geometry&&typeof o.geometry=="object"&&(o.geometry=this.transformGeometry(o.geometry,t,{strictMode:s})),Array.isArray(o.transformations)&&(o.transformations=o.transformations.map(a=>{if(a.transformRef)try{const c=Se.resolve(a.transformRef,t);return{...a,...c,transformRef:void 0}}catch(c){if(s)throw c;return console.warn(`Transformations解析失败: ${a.transformRef}`,c),a}return a})),o.style&&typeof o.style=="object"&&(o.style=this.transformStyle(o.style,t,{strictMode:s})),o.animationRef){try{const a=this.resolveAnimationConfig(o.animationRef,t,{strictMode:s});o.animation={...a,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`动画引用解析失败: ${o.animationRef}`,a)}delete o.animationRef}if(o.sliderRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 sliderRef",{sliderRef:o.sliderRef,hasAnimationDefinitions:!!t.animationDefinitions,animationDefinitionKeys:t.animationDefinitions?Object.keys(t.animationDefinitions):[]});try{const a={...it,...t,animationDefinitions:t.animationDefinitions||it.animationDefinitions},c=Je.resolve(o.sliderRef,a);o.animation={...c,...o.animation||{}}}catch(a){if(s)throw a;console.warn(`滑块引用解析失败: ${o.sliderRef}`,a)}delete o.sliderRef}if(o.boardRef){console.error("🔍 GeometryTransformTransformer.transformConfig: 处理 config 中的 boardRef",{boardRef:o.boardRef,currentBoardConfig:o.boardConfig});try{const a=this.resolveBoardConfig(o.boardRef,t,{strictMode:s});console.error("🔍 解析后的 boardConfig (config):",a),o.boardConfig={...a,...o.boardConfig||{}},console.error("🔍 设置后的 transformedConfig.boardConfig:",o.boardConfig)}catch(a){if(s)throw a;console.warn(`画板引用解析失败: ${o.boardRef}`,a)}delete o.boardRef}return o}static normalizeTransformConfig(e,t){if(!e||typeof e!="object")return e;console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 输入",{transformId:e.id,transformType:e.type,hasTargetGroup:!!e.targetGroup,targetGroup:e.targetGroup,geometryRefToShapeIdKeys:t?Object.keys(t):[],geometryRefToShapeId:t});const n={...e};switch(!n.type&&n.config&&n.config.type&&(n.type=n.config.type),n.type){case"rotation":if(n.config){if(n.rotation={...n.config},n.rotation.center&&typeof n.rotation.center=="object"){const s=n.rotation.center;"x"in s&&"y"in s&&(n.rotation.center=[s.x,s.y])}delete n.config}break;case"translation":n.config&&(n.translation={...n.config},delete n.config);break;case"scale":if(n.config){if(n.scale={...n.config},n.scale.center&&typeof n.scale.center=="object"){const s=n.scale.center;"x"in s&&"y"in s&&(n.scale.center=[s.x,s.y])}delete n.config}break;case"composite":n.config&&Array.isArray(n.config.transforms)&&(n.composite=n.config.transforms.map(s=>this.normalizeTransformConfig(s,t)),delete n.config);break;default:if(n.config){const{type:s,...o}=n.config;Object.assign(n,o),delete n.config}}if(n.targetGroup&&t){const s=n.targetGroup;let o;if(t[s])o=t[s],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 精确匹配 targetGroup",{original:s,mapped:o,type:"exact"});else{const i=Object.keys(t).find(a=>{if(a.startsWith(s+"_")||a===s||a.includes(s))return!0;const c=a.split("_"),l=s.split("_");return c.some(d=>l.includes(d))});i&&(o=t[i],console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 启发式匹配 targetGroup",{original:s,geometryRef:i,mapped:o,type:"heuristic"}))}o?n.targetGroup=o:console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig: 无法映射 targetGroup",{original:s,geometryRefToShapeId:t,warning:"targetGroup 无法映射到任何 shapeId,可能导致旋转失败"})}return e.targetGroup&&!n.targetGroup&&(n.targetGroup=e.targetGroup),console.error("🔍 GeometryTransformTransformer.normalizeTransformConfig:",{input:e,output:n,hasRotation:!!n.rotation,hasTranslation:!!n.translation,hasScale:!!n.scale,hasComposite:!!n.composite}),n}static transformShape(e,t,n={}){console.error("🔍 transformShape 被调用:",{shapeId:e.id,shapeType:e.type,hasGeometryRef:!!e.geometryRef,geometryRef:e.geometryRef,hasStyleRef:!!e.styleRef,styleRef:e.styleRef,shapeKeys:Object.keys(e),contextHasGeometryPresets:!!t.geometryPresets,contextGeometryPresetKeys:t.geometryPresets?Object.keys(t.geometryPresets):[]});const{strictMode:s=!1}=n,o={...e};if(o.geometryRef){console.error("🔍 transformShape: 处理 geometryRef:",o.geometryRef),console.error("🔍 transformShape: context.geometryPresets:",t.geometryPresets),console.error("🔍 transformShape: context.geometryPresets keys:",t.geometryPresets?Object.keys(t.geometryPresets):[]);try{console.error("🔍 transformShape: 调用 GeometryRefResolver.resolve");const i=Be.resolve(o.geometryRef,t);console.error("🔍 transformShape: geometry 解析结果:",i),Object.assign(o,i),console.error("🔍 transformShape: 合并后的 shape:",o),o.vertices&&Array.isArray(o.vertices)&&console.error("🔍 transformShape: 顶点数据:",{count:o.vertices.length,sample:o.vertices.slice(0,3).map((a,c)=>({index:c,value:a,isArray:Array.isArray(a),length:Array.isArray(a)?a.length:"N/A"}))})}catch(i){if(console.error("🔍 transformShape: geometryRef 解析错误:",i),s)throw i;console.warn(`Shape geometryRef解析失败: ${o.geometryRef}`,i)}delete o.geometryRef,console.error("🔍 transformShape: 删除 geometryRef 后的 shape:",o)}if(o.styleRef){try{const i=we.resolve(o.styleRef,t);o.style=i}catch(i){if(s)throw i;console.warn(`Shape styleRef解析失败: ${o.styleRef}`,i)}delete o.styleRef}if(o.metadata||(o.metadata={}),!o.metadata.id&&o.id&&(o.metadata.id=o.id),o.withLabel!==void 0&&(o.metadata.showLabel=o.withLabel,delete o.withLabel),o.label&&(typeof o.label=="object"?o.metadata.label=o.label.text||o.metadata.id||"":typeof o.label=="string"&&(o.metadata.label=o.label),delete o.label),o.metadata.showLabel&&!o.metadata.label&&o.metadata.id&&(o.metadata.label=o.metadata.id),o.metadata.id){const i=o.metadata.id.toLowerCase();i.includes("left")?o.metadata.rotationGroup="left":i.includes("right")?o.metadata.rotationGroup="right":o.metadata.rotationGroup=o.metadata.id}if(o.type==="point"&&o.position){console.error("🔍 transformShape: 转换point为circle:",{shapeId:o.metadata?.id,position:o.position,originalType:o.type});const i=o.position.x,a=o.position.y,c=.1;o.type="circle",o.vertices=[[i,a],[i+c,a]],delete o.position,console.error("🔍 transformShape: point转换为circle完成:",{newType:o.type,vertices:o.vertices})}return o}static transformGeometry(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.geometryRef){try{const i=Be.resolve(o.geometryRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`几何对象解析失败: ${o.geometryRef}`,i)}delete o.geometryRef}return o}static transformTransform(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.transformRef){try{const i=Se.resolve(o.transformRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`变换对象解析失败: ${o.transformRef}`,i)}delete o.transformRef}return o}static transformStyle(e,t,n={}){const{strictMode:s=!1}=n,o={...e};if(o.styleRef){try{const i=we.resolve(o.styleRef,t);Object.assign(o,i)}catch(i){if(s)throw i;console.warn(`样式对象解析失败: ${o.styleRef}`,i)}delete o.styleRef}return o}static resolveAnimationConfig(e,t,n={}){const{strictMode:s=!1}=n;if(!e||typeof e!="string"){if(s)throw new Error(`无效的动画引用: ${e}`);return console.warn(`无效的动画引用: ${e}`),{}}try{const o=e.replace("animationRef:","");if(t.animationDefinitions&&t.animationDefinitions[o])return{...t.animationDefinitions[o]};if(s)throw new Error(`动画引用未找到: ${o}`);const i=this.getFallbackAnimationConfig(o);return console.warn(`动画引用未在上下文中找到,使用回退配置: ${o}`),i}catch(o){if(s)throw o;return console.warn(`动画配置解析失败: ${e}`,o),{}}}static resolveBoardConfig(e,t,n={}){const{strictMode:s=!1}=n;if(!e||typeof e!="string"){if(s)throw new Error(`无效的画板引用: ${e}`);return console.warn(`无效的画板引用: ${e}`),{}}try{const o=e.replace("boardRef:","");if(console.error("🔍 GeometryTransformTransformer.resolveBoardConfig:",{boardRef:e,refName:o,hasContextBoardDefinitions:!!t.boardDefinitions,contextBoardDefinitionKeys:t.boardDefinitions?Object.keys(t.boardDefinitions):[],hasRefInContext:t.boardDefinitions&&!!t.boardDefinitions[o]}),t.boardDefinitions&&t.boardDefinitions[o]){const a={...t.boardDefinitions[o]};return console.error("🔍 从上下文获取画板配置:",a),a}if(s)throw new Error(`画板引用未找到: ${o}`);const i=this.getFallbackBoardConfig(o);return console.warn(`画板引用未在上下文中找到,使用回退配置: ${o}`),console.error("🔍 使用回退画板配置:",i),i}catch(o){if(s)throw o;return console.warn(`画板配置解析失败: ${e}`,o),{}}}static getFallbackAnimationConfig(e){const t={slider_horizontal:{id:"slider_horizontal",slider:{position:[0,-6],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"水平滑块动画"},slider_vertical:{id:"slider_vertical",slider:{position:[-6,0],length:10,orientation:"vertical",min:0,max:1,step:.01},progressIndicator:{enabled:!0,stages:4,labels:["开始","25%","50%","75%","完成"],showPercentage:!0},duration:2e3,easing:"ease-in-out",description:"垂直滑块动画"}};return t[e]||t.slider_horizontal}static getFallbackBoardConfig(e){const t={default:{id:"default",originX:2,originY:2,boundingBox:[0,7,10,0],keepAspectRatio:!0,showGrid:!1,showAxis:!1,description:"默认画板配置"},extended:{id:"extended",originX:0,originY:0,boundingBox:[-5,12,15,-5],keepAspectRatio:!0,showGrid:!0,showAxis:!0,gridSize:1,description:"扩展画板配置(带网格和坐标轴)"}};return t[e]||t.default}static validate(e){const t=[];return e?(e.type!==ye.GEOMETRY_TRANSFORM&&t.push(`几何变换内容块类型应为 'geometryTransform',实际为 '${e.type}'`),!e.config||typeof e.config!="object"?e.geometryRef||t.push("几何变换内容块缺少 config 对象或 geometryRef"):!e.config.geometry&&!e.geometryRef&&t.push("几何变换内容块缺少 geometry 或 geometryRef"),t):(t.push("几何变换内容块不能为空"),t)}static batchTransform(e,t,n={}){return e.filter(s=>s.type===ye.GEOMETRY_TRANSFORM).map(s=>this.transform(s,t,n))}}function qc(){return{type:ye.GEOMETRY_TRANSFORM,transform:tr.transform.bind(tr),validate:tr.validate.bind(tr)}}class Ze{static transformText(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n;console.error(`📄 TextTransformer.transformText: type=${e.type}, content=${e.content?.substring(0,50)}..., styleRef=${e.styleRef}, enableReferenceResolution=${s}`);const i={...e,type:ye.TEXT};if(!s)return i;try{if(typeof i.content=="string"&&(i.content=this.resolveTextContent(i.content,t,{strictMode:o})),i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:o})),i.styleRef){console.error(`🎨 TextTransformer处理styleRef: ${i.styleRef}`);try{const a=we.resolve(i.styleRef,t);console.error(" StyleRefResolver解析结果:",a),i.style={...i.style,...a},console.error(" 合并后style:",i.style)}catch(a){if(o)throw a;console.warn(`文本样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("文本转换失败:",a),i}}static transformFormula(e,t,n={}){const{enableReferenceResolution:s=!0,strictMode:o=!1}=n,i={...e,type:ye.FORMULA};if(!s)return i;try{if(i.style&&typeof i.style=="object"&&(i.style=this.resolveStyle(i.style,t,{strictMode:o})),i.styleRef){try{const a=we.resolve(i.styleRef,t);i.style={...i.style,...a}}catch(a){if(o)throw a;console.warn(`公式样式解析失败: ${i.styleRef}`,a)}delete i.styleRef}return i}catch(a){if(o)throw a;return console.warn("公式转换失败:",a),i}}static resolveTextContent(e,t,n={}){const{strictMode:s=!1}=n;if(console.error(`📝 TextTransformer.resolveTextContent START: text="${e}", hasDesignTokens=${e.includes("$")}`),!e.includes("$"))return console.error(` resolveTextContent END (no design tokens): "${e}"`),e;let o=e,i;const a=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;for(;(i=a.exec(e))!==null;){const c=i[0],l=i[1];console.error(` 发现设计令牌: ${c}, path=${l}`);try{const d=Pe.resolve(c,t);console.error(` 解析结果: ${c} -> ${d}`),o=o.replace(c,String(d))}catch(d){if(s)throw d;console.warn(`文本中的设计令牌解析失败: ${c}`,d)}}return console.error(` resolveTextContent END: original="${e}", resolved="${o}"`),o}static resolveStyle(e,t,n={}){const{strictMode:s=!1}=n;try{return Pe.replaceDesignTokenRefs(e,t,o=>{if(s)throw new Error(`设计令牌未找到: ${o}`);return console.warn(`设计令牌未找到: ${o}`),o})}catch(o){if(s)throw o;return console.warn("样式解析失败:",o),e}}static validateText(e){const t=[];return e?(e.type!==ye.TEXT&&t.push(`文本内容块类型应为 'text',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("文本内容块缺少 content 字段"),t):(t.push("文本内容块不能为空"),t)}static validateFormula(e){const t=[];return e?(e.type!==ye.FORMULA&&t.push(`公式内容块类型应为 'formula',实际为 '${e.type}'`),(e.content===void 0||e.content===null)&&t.push("公式内容块缺少 content 字段"),t):(t.push("公式内容块不能为空"),t)}static batchTransformText(e,t,n={}){return e.filter(s=>s.type===ye.TEXT).map(s=>this.transformText(s,t,n))}static batchTransformFormula(e,t,n={}){return e.filter(s=>s.type===ye.FORMULA).map(s=>this.transformFormula(s,t,n))}}function Yc(){return{type:ye.TEXT,transform:Ze.transformText.bind(Ze),validate:Ze.validateText.bind(Ze)}}function Hc(){return{type:ye.FORMULA,transform:Ze.transformFormula.bind(Ze),validate:Ze.validateFormula.bind(Ze)}}class Kc{transformers=new Map;constructor(){this.registerDefaultTransformers()}registerDefaultTransformers(){this.register(Wc()),this.register(qc()),this.register(Yc()),this.register(Hc())}register(e){this.transformers.set(e.type,e)}getAllTransformers(){return Array.from(this.transformers.values())}getTransformer(e){return this.transformers.get(e)}transform(e,t,n={}){if(!e||!e.type)throw new Error("内容块缺少 type 字段");const s=this.getTransformer(e.type);return s?(console.error(`🔄 TransformerRegistry.transform: type="${e.type}", transformer.type="${s.type}", enableReferenceResolution=${n.enableReferenceResolution}`),s.transform(e,t,n)):(console.error(`没有找到适合的转换器: ${e.type}`),e)}batchTransform(e,t,n={}){return e.map(s=>this.transform(s,t,n))}transformScene(e,t,n={}){const s=e.items||e.content;if(!e||!Array.isArray(s))return{items:[],layout:e?.layout};const o=this.batchTransform(s,t,n);let i=e.layout;if(e.layout&&typeof e.layout=="object")i=this.resolveLayoutReferences(e.layout,t,n);else if(typeof e.layout=="string"&&e.layout.startsWith("layoutRef:"))try{i=Ve.resolve(e.layout,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${e.layout}`,a),i=e.layout}return{items:o,layout:i}}resolveLayoutReferences(e,t,n){if(!e||!n.enableReferenceResolution)return e;if(typeof e=="string"&&e.startsWith("layoutRef:"))try{return Ve.resolve(e,t)}catch(s){if(n.strictMode)throw s;return console.warn(`布局引用解析失败: ${e}`,s),e}if(typeof e=="object"){if(e.layoutRef&&typeof e.layoutRef=="string")try{const o=`layoutRef:${e.layoutRef}`,i=Ve.resolve(o,t),{layoutRef:a,...c}=e;return{...i,...c}}catch(o){if(n.strictMode)throw o;console.warn(`布局引用解析失败: ${e.layoutRef}`,o)}const s=Array.isArray(e)?[]:{};for(const[o,i]of Object.entries(e))if(typeof i=="string"&&i.startsWith("layoutRef:"))try{s[o]=Ve.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局引用解析失败: ${i}`,a),s[o]=i}else if(typeof i=="string"&&i.startsWith("$"))try{s[o]=Pe.resolve(i,t)}catch(a){if(n.strictMode)throw a;console.warn(`布局中的设计令牌解析失败: ${o}=${i}`,a),s[o]=i}else i&&typeof i=="object"?s[o]=this.resolveLayoutReferences(i,t,n):s[o]=i;return s}return e}transformScenes(e,t,n={}){const s={};for(const[o,i]of Object.entries(e))s[o]=this.transformScene(i,t,n);return s}validate(e){if(!e||!e.type)return["内容块缺少 type 字段"];const t=this.getTransformer(e.type);return!t||!t.validate?[]:t.validate(e)}batchValidate(e){return e.map(t=>({block:t,errors:this.validate(t)}))}}function $o(){return new Kc}class es{static validate(e,t={}){const{strictMode:n=!1,skipOptionalFields:s=!1}=t,o=[],i=[];return!e||typeof e!="object"?(o.push("输入数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i,{skipOptionalFields:s}),this.validateFieldTypes(e,o,i),this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswerInfo(e,o,i),n&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,t,n,s){const{skipOptionalFields:o}=s;for(const i of Fr.RAW_DATA)e[i]===void 0&&t.push(`缺少必需字段: ${i}`);if(e.basic_info)for(const i of Fr.BASIC_INFO)e.basic_info[i]===void 0&&t.push(`basic_info 缺少必需字段: ${i}`);if(e.answer_info)for(const i of Fr.ANSWER_INFO)e.answer_info[i]===void 0&&t.push(`answer_info 缺少必需字段: ${i}`)}static validateFieldTypes(e,t,n){["math_prob_id","title","grade_id","unit_name","lesson_name","skill_description","objective"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="string"&&t.push(`${a} 应为字符串类型`)}),["difficulty","unit_id","lesson_id","module_id","skill_id"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="number"&&t.push(`${a} 应为数字类型`)}),e.knowledge_points!==void 0&&!Array.isArray(e.knowledge_points)&&t.push("knowledge_points 应为数组类型"),["metadata","basic_info","answer_info","scenes"].forEach(a=>{e[a]!==void 0&&(typeof e[a]!="object"||Array.isArray(e[a]))&&t.push(`${a} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||t.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${o} 应为对象类型`);continue}const a=i;Array.isArray(a.content)||t.push(`场景 ${o} 的 content 应为数组类型`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${o} 的 layout 应为对象类型`),_o.includes(o)||n.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,t,n){if(!e.basic_info||typeof e.basic_info!="object")return;const s=e.basic_info;["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&t.push(`basic_info.${a} 应为数字类型`)}),["question","answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&t.push(`basic_info.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&t.push("basic_info.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&t.push("basic_info.context 应为对象类型"),s.shape&&!["acute_triangle","right_triangle","rectangle","circle"].includes(s.shape)&&n.push(`未知的形状类型: ${s.shape}`)}static validateAnswerInfo(e,t,n){if(!e.answer_info||typeof e.answer_info!="object")return;const s=e.answer_info;typeof s.value!="number"&&t.push("answer_info.value 应为数字类型"),typeof s.unit!="string"&&t.push("answer_info.unit 应为字符串类型"),typeof s.explanation_text!="string"&&t.push("answer_info.explanation_text 应为字符串类型"),s.value!==void 0&&(s.value<0&&n.push("answer_info.value 为负数,可能不正确"),s.value>1e4&&n.push("answer_info.value 过大,可能不正确"))}static validateStrictMode(e,t,n){if(e.schema_version||n.push("建议添加 schema_version 字段"),e.config_version||n.push("建议添加 config_version 字段"),e.knowledge_points&&e.knowledge_points.length===0&&n.push("knowledge_points 数组为空"),e.scenes)for(const[s,o]of Object.entries(e.scenes)){const i=o;i.content&&i.content.length===0&&n.push(`场景 ${s} 的 content 数组为空`)}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["math_prob_id","title","basic_info","scenes","answer_info"];for(const n of t)if(e[n]===void 0)return!1;return!0}static validateAndClean(e,t={}){const{strictMode:n=!1,removeInvalidFields:s=!1}=t,o=this.validate(e,{strictMode:n});let i=e;return s&&!o.isValid&&(i={...e},["__proto__","constructor","prototype"].forEach(c=>{c in i&&delete i[c]})),{data:i,errors:o.errors,warnings:o.warnings}}}class ts{static validate(e,t={}){const{strictMode:n=!1,checkSceneContent:s=!0}=t,o=[],i=[];return!e||typeof e!="object"?(o.push("输出数据必须是对象"),{isValid:!1,errors:o,warnings:i}):(this.validateRequiredFields(e,o,i),this.validateFieldTypes(e,o,i),s&&this.validateScenes(e,o,i),this.validateBasicInfo(e,o,i),this.validateAnswer(e,o,i),this.validateExplanation(e,o,i),n&&this.validateStrictMode(e,o,i),{isValid:o.length===0,errors:o,warnings:i})}static validateRequiredFields(e,t,n){const s=["id","title","grade","unit","lesson","skill","objective","knowledgePoints","difficulty","metadata","basicInfo","scenes","answer"];for(const o of s)e[o]===void 0&&t.push(`缺少必需字段: ${o}`)}static validateFieldTypes(e,t,n){["id","title","unit","lesson","skill","objective"].forEach(i=>{e[i]!==void 0&&typeof e[i]!="string"&&t.push(`${i} 应为字符串类型`)}),e.grade!==void 0&&typeof e.grade!="number"&&t.push("grade 应为数字类型"),e.difficulty!==void 0&&typeof e.difficulty!="number"&&t.push("difficulty 应为数字类型"),e.knowledgePoints!==void 0&&!Array.isArray(e.knowledgePoints)&&t.push("knowledgePoints 应为数组类型"),["metadata","basicInfo","scenes","answer"].forEach(i=>{e[i]!==void 0&&(typeof e[i]!="object"||Array.isArray(e[i]))&&t.push(`${i} 应为对象类型`)})}static validateScenes(e,t,n){if(!e.scenes||typeof e.scenes!="object"){t.push("scenes 应为对象类型");return}const s=["question","solve","review"];for(const o of s)e.scenes[o]||t.push(`缺少必需场景: ${o}`);for(const[o,i]of Object.entries(e.scenes)){if(!i||typeof i!="object"){t.push(`场景 ${o} 应为对象类型`);continue}const a=i,c=a.items||a.content;Array.isArray(c)?c.length===0&&n.push(`场景 ${o} 的内容数组为空`):t.push(`场景 ${o} 缺少有效的内容数组(应为 items 或 content 字段)`),a.layout!==void 0&&typeof a.layout!="object"&&t.push(`场景 ${o} 的 layout 应为对象类型`),_o.includes(o)||n.push(`未知的场景名称: ${o}`)}}static validateBasicInfo(e,t,n){if(!e.basicInfo||typeof e.basicInfo!="object"){t.push("basicInfo 应为对象类型");return}const s=e.basicInfo;(s.question===void 0||typeof s.question!="string")&&t.push("basicInfo.question 应为字符串类型"),["base","height","length","width","score"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="number"&&t.push(`basicInfo.${a} 应为数字类型`)}),["answerUnit","areaUnit","shape","baseUnit","heightUnit","lengthUnit","widthUnit"].forEach(a=>{s[a]!==void 0&&typeof s[a]!="string"&&t.push(`basicInfo.${a} 应为字符串类型`)}),s.variables!==void 0&&typeof s.variables!="object"&&t.push("basicInfo.variables 应为对象类型"),s.context!==void 0&&typeof s.context!="object"&&t.push("basicInfo.context 应为对象类型")}static validateAnswer(e,t,n){if(!e.answer||typeof e.answer!="object"){t.push("answer 应为对象类型");return}const s=e.answer;typeof s.value!="number"&&t.push("answer.value 应为数字类型"),typeof s.unit!="string"&&t.push("answer.unit 应为字符串类型"),typeof s.explanation!="string"&&t.push("answer.explanation 应为字符串类型"),s.value!==void 0&&(s.value<0&&n.push("answer.value 为负数,可能不正确"),s.value>1e4&&n.push("answer.value 过大,可能不正确"))}static validateExplanation(e,t,n){if(e.explanation===void 0){t.push("缺少 explanation 字段");return}if(typeof e.explanation!="object"){t.push("explanation 应为对象或数组类型");return}Array.isArray(e.explanation)?(e.explanation.length===0&&n.push("explanation 数组为空"),e.explanation.forEach((s,o)=>{(!s||typeof s!="object")&&t.push(`explanation[${o}] 应为对象类型`)})):e.explanation.steps===void 0?t.push("explanation 对象缺少 steps 字段"):Array.isArray(e.explanation.steps)||t.push("explanation.steps 应为数组类型")}static validateStrictMode(e,t,n){if(e.id&&typeof e.id=="string"&&(e.id.includes("-")||n.push("id 格式可能不符合规范,建议使用连字符分隔")),e.grade!==void 0&&(e.grade<1||e.grade>12)&&n.push(`grade 值 ${e.grade} 超出常见范围 (1-12)`),e.difficulty!==void 0&&(e.difficulty<1||e.difficulty>5)&&n.push(`difficulty 值 ${e.difficulty} 超出范围 (1-5)`),e.knowledgePoints&&e.knowledgePoints.length===0&&n.push("knowledgePoints 数组为空"),e.metadata&&typeof e.metadata=="object"){const s=e.metadata;(!s.topic||typeof s.topic!="string")&&n.push("metadata.topic 应为字符串类型"),(!s.skill||typeof s.skill!="string")&&n.push("metadata.skill 应为字符串类型"),(!s.tags||!Array.isArray(s.tags))&&n.push("metadata.tags 应为数组类型")}}static quickValidate(e){if(!e||typeof e!="object")return!1;const t=["id","title","basicInfo","scenes","answer"];for(const n of t)if(e[n]===void 0)return!1;return!(typeof e.title!="string"||e.basicInfo&&typeof e.basicInfo!="object"||e.scenes&&typeof e.scenes!="object"||e.answer&&typeof e.answer!="object")}static isValidMathPracticeProblemData(e){return this.validate(e,{strictMode:!1,checkSceneContent:!1}).isValid}}class gr{static validateInput(e,t={}){const{isValid:n,errors:s,warnings:o}=es.validate(e,t);return{isValid:n,errors:s,warnings:o,timestamp:Date.now()}}static validateOutput(e,t={}){const{isValid:n,errors:s,warnings:o}=ts.validate(e,t);return{isValid:n,errors:s,warnings:o,timestamp:Date.now()}}static validateComplete(e,t,n={}){const{inputStrictMode:s=!1,outputStrictMode:o=!1}=n,i=this.validateInput(e,{strictMode:s}),a=this.validateOutput(t,{strictMode:o}),c=[...i.errors,...a.errors],l=[...i.warnings,...a.warnings],d={isValid:i.isValid&&a.isValid,errors:c,warnings:l};return{input:i,output:a,overall:d}}static quickValidateInput(e){return es.quickValidate(e)}static quickValidateOutput(e){return ts.quickValidate(e)}static validateAndReport(e,t,n={}){const s=t==="input"?this.validateInput(e,n):this.validateOutput(e,n);console.group(`${t.toUpperCase()} 验证结果`),console.log(`有效性: ${s.isValid?"✅ 通过":"❌ 失败"}`),s.errors.length>0&&(console.group("❌ 错误:"),s.errors.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),s.warnings.length>0&&(console.group("⚠️ 警告:"),s.warnings.forEach(o=>console.log(` - ${o}`)),console.groupEnd()),console.groupEnd()}}class Kr{static extractAllReferences(e){const t=[],n=s=>{typeof s=="string"?t.push(s):Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&Object.values(s).forEach(n)};return n(e),[...new Set(t)]}static categorizeReferences(e,t){const n={[ee.DESIGN_TOKEN]:[],[ee.STYLE_REF]:[],[ee.GEOMETRY_REF]:[],[ee.TRANSFORM_REF]:[],[ee.LAYOUT_REF]:[]},s=new mt;for(const o of e){const i=s.getResolverForRef(o);i&&n[i.type].push(o)}return n}static batchResolveReferences(e,t,n={}){const{strictMode:s=!1,onMissing:o}=n,i=new mt,a={};for(const c of e){const l=i.getResolverForRef(c);if(l)try{a[c]=l.resolve(c,t)}catch(d){if(s)throw d;console.warn(`引用解析失败: ${c}`,d),o&&(a[c]=o(c))}}return a}static replaceReferences(e,t,n={}){const{strictMode:s=!1,onMissing:o,maxDepth:i=10}=n,a=new mt,c=new Set(["geometryRef","styleRef","transformRef","layoutRef","boardRef","animationRef","appearanceRef","position","vertices","endpoints","center","start","end","type","theme","strategy","content","description","title","question","answer","unit","id","name","label","config","metadata","layout","renderer","padding","component","inputType","placeholder","submitButton","targetGroup","direction","executionMode","transformSource","rotationGroup","isMovable","isStatic","shapes","animated","static","transform","chartConfig","steps","value","tolerance","validation","explanation_text","solution_steps","variables","originX","originY","areaUnit","baseUnit","heightUnit","answerUnit","base","height","displayMode","parts","fontSize","fontWeight","anchorX"]),l=(d,u=0,y)=>{if(u>i)return console.warn(`引用替换达到最大深度: ${i}`),d;if(typeof d=="string"){if(y&&c.has(y))return console.warn(`🛡️ 跳过保留字段 "${y}" 的通用解析: "${d}"`),d;if(!(d.startsWith("$")||d.includes("Ref:")))return d;const h=a.getResolverForRef(d);if(h)try{return h.resolve(d,t)}catch(g){if(s)throw g;return console.warn(`引用解析失败: ${d}`,g),o?o(d):d}return d}else{if(Array.isArray(d))return d.map(m=>l(m,u+1,void 0));if(d&&typeof d=="object"){const m={};for(const[h,g]of Object.entries(d))m[h]=l(g,u+1,h);return m}}return d};return l(e)}static calculateReferenceStats(e,t){const n=new mt,s={total:e.length,resolved:0,failed:0,byType:{}};Object.values(ee).forEach(o=>{s.byType[o]={total:0,resolved:0,failed:0}}),console.log("🔍 calculateReferenceStats: 开始处理引用,总数=",e.length);for(const o of e){console.log("🔍 处理引用:",o);const i=n.getResolverForRef(o);if(i){const a=i.type;s.byType[a].total++,console.log(`🔍 找到解析器: type=${a}`);try{const c=i.resolve(o,t);console.log(`🔍 引用解析成功: ${o} =>`,c),s.resolved++,s.byType[a].resolved++}catch(c){console.error(`🔍 引用解析失败: ${o}`,c),s.failed++,s.byType[a].failed++}}else console.log(`🔍 未找到解析器: ${o}`)}return s}static checkReferenceExists(e,t){const s=new mt().getResolverForRef(e);if(!s)return!1;if(s.validate)return s.validate(e,t);try{return s.resolve(e,t),!0}catch{return!1}}static getReferencePath(e){if(e.startsWith("$"))return e.substring(1).split(".");const t=e.match(/^(\w+):(\w+)$/);return t?[t[1],t[2]]:[e]}static createReference(e,t){switch(e){case ee.DESIGN_TOKEN:return`$${t.join(".")}`;case ee.STYLE_REF:return`styleRef:${t[0]}`;case ee.GEOMETRY_REF:return`geometryRef:${t[0]}`;case ee.TRANSFORM_REF:return`transformRef:${t[0]}`;case ee.LAYOUT_REF:return`layoutRef:${t[0]}`;default:return t.join(":")}}static flattenNestedReferences(e){const t=[],n=(s,o=[])=>{if(typeof s=="string")t.push(`${o.join(".")}=${s}`);else if(Array.isArray(s))s.forEach((i,a)=>{n(i,[...o,`[${a}]`])});else if(s&&typeof s=="object")for(const[i,a]of Object.entries(s))n(a,[...o,i])};return n(e),t}}class ko{marks=new Map;stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0};memoryStart=0;constructor(){this.startMemoryTracking()}markStart(e){this.marks.set(e,{name:e,startTime:performance.now()})}markEnd(e){const t=this.marks.get(e);if(!t){console.warn(`性能标记未找到: ${e}`);return}const n=performance.now(),s=n-t.startTime;t.endTime=n,t.duration=s,this.updateStats(e,s)}updateStats(e,t){switch(e){case"reference-resolution":this.stats.referenceResolutionTime=t;break;case"transformation":this.stats.transformationTime=t;break;case"validation":this.stats.validationTime=t;break;case"total":this.stats.totalTime=t;break}}startMemoryTracking(){typeof performance<"u"&&performance.memory&&(this.memoryStart=performance.memory.usedJSHeapSize)}endMemoryTracking(){if(typeof performance<"u"&&performance.memory){const e=performance.memory.usedJSHeapSize;this.stats.memoryUsage=e-this.memoryStart}}setReferenceCount(e){this.stats.referenceCount=e}getStats(){return this.endMemoryTracking(),{...this.stats}}getMarks(){return Array.from(this.marks.values())}checkPerformance(){const e=[];return this.stats.transformationTime>nt.WARNING_TRANSFORMATION_TIME&&e.push(`转换时间较长: ${this.stats.transformationTime.toFixed(2)}ms (警告阈值: ${nt.WARNING_TRANSFORMATION_TIME}ms)`),this.stats.transformationTime>nt.MAX_TRANSFORMATION_TIME&&e.push(`转换时间过长: ${this.stats.transformationTime.toFixed(2)}ms (最大阈值: ${nt.MAX_TRANSFORMATION_TIME}ms)`),this.stats.memoryUsage>nt.MAX_MEMORY_INCREASE&&e.push(`内存增加过多: ${(this.stats.memoryUsage/1024).toFixed(2)}KB (最大阈值: ${nt.MAX_MEMORY_INCREASE/1024}KB)`),this.stats.referenceCount>nt.MAX_REFERENCE_DEPTH*10&&e.push(`引用数量较多: ${this.stats.referenceCount} (可能影响性能)`),{passed:e.length===0,warnings:e}}reset(){this.marks.clear(),this.stats={totalTime:0,referenceResolutionTime:0,transformationTime:0,validationTime:0,memoryUsage:0,referenceCount:0},this.startMemoryTracking()}}class Xc{static deepMerge(e,t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return Array.isArray(e)?e.map((s,o)=>o<t.length?this.deepMerge(s,t[o]):s):[...t];const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&(s in n&&typeof n[s]=="object"&&typeof o=="object"?n[s]=this.deepMerge(n[s],o):n[s]=o);return n}static deepEqual(e,t){if(e===t)return!0;if(typeof e!=typeof t||typeof e!="object"||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e))return e.length!==t.length?!1:e.every((o,i)=>this.deepEqual(o,t[i]));const n=Object.keys(e),s=Object.keys(t);return n.length!==s.length?!1:n.every(o=>o in t?this.deepEqual(e[o],t[o]):!1)}static safeGet(e,t,n=void 0){const s=Array.isArray(t)?t:t.split(".");let o=e;for(const i of s){if(o==null||typeof o!="object")return n;const a=i.match(/^\[(\d+)\]$/);if(a&&Array.isArray(o)){const c=parseInt(a[1],10);o=o[c]}else o=o[i]}return o!==void 0?o:n}static safeSet(e,t,n){const s=Array.isArray(t)?t:t.split("."),o=Array.isArray(e)?[...e]:{...e};let i=o;for(let l=0;l<s.length-1;l++){const d=s[l],u=d.match(/^\[(\d+)\]$/);if(u&&Array.isArray(i)){const y=parseInt(u[1],10);i[y]===void 0&&(i[y]={}),i=i[y]}else{if(i[d]===void 0){const m=s[l+1].match(/^\[(\d+)\]$/);i[d]=m?[]:{}}i=i[d]}}const a=s[s.length-1],c=a.match(/^\[(\d+)\]$/);if(c&&Array.isArray(i)){const l=parseInt(c[1],10);i[l]=n}else i[a]=n;return o}static generateId(e="id"){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static throttle(e,t){let n=0;return(...s)=>{const o=Date.now();o-n>=t&&(n=o,e(...s))}}static debounce(e,t){let n;return(...s)=>{clearTimeout(n),n=setTimeout(()=>e(...s),t)}}static formatBytes(e,t=2){if(e===0)return"0 Bytes";const n=1024,s=t<0?0:t,o=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/Math.pow(n,i)).toFixed(s))+" "+o[i]}static estimateObjectSize(e){const t=new WeakSet,n=s=>t.has(s)?0:typeof s=="string"?(t.add(s),s.length*2):typeof s=="number"?8:typeof s=="boolean"?4:s==null?0:Array.isArray(s)?(t.add(s),s.reduce((o,i)=>o+n(i),0)):typeof s=="object"?(t.add(s),Object.values(s).reduce((o,i)=>o+n(i),0)):0;return n(e)}}class Jc{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;constructor(e={}){this.config={...Ic,...e},this.referenceContext=To(),this.resolverRegistry=No(),this.transformerRegistry=$o(),this.performanceMonitor=new ko}adapt(e){console.error("🔧 SyncAdapter.adapt called with inputData:",{math_prob_id:e?.math_prob_id,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{this.performanceMonitor.markStart("validation");const t=this.validateInput(e);if(!t.isValid&&this.config.strictMode)throw new me(B.INVALID_INPUT,Qn[B.INVALID_INPUT],{errors:t.errors});this.performanceMonitor.markEnd("validation"),this.performanceMonitor.markStart("base-transformation");const n=this.transformBaseData(e);this.performanceMonitor.markEnd("base-transformation");let s=n;this.config.enableReferenceResolution&&(this.performanceMonitor.markStart("reference-resolution"),s=this.resolveReferences(n),this.performanceMonitor.markEnd("reference-resolution")),this.performanceMonitor.markStart("scene-transformation"),!this.referenceContext.basicInfo&&s.basicInfo&&(this.referenceContext.basicInfo=s.basicInfo);const o=this.transformScenes(s);this.performanceMonitor.markEnd("scene-transformation"),this.performanceMonitor.markStart("output-validation");const i=this.validateOutput(o);if(!i.isValid&&this.config.strictMode)throw new me(B.OUTPUT_VALIDATION_FAILED,Qn[B.OUTPUT_VALIDATION_FAILED],{errors:i.errors});this.performanceMonitor.markEnd("output-validation"),this.performanceMonitor.markEnd("total"),console.error("🔧 adapt: transformedData before buildResult:",o),console.error("🔧 adapt: transformedData.basicInfo:",o.basicInfo),console.error("🔧 adapt: transformedData.basicInfo?.answerUnit:",o.basicInfo?.answerUnit);const a=this.buildResult(o,{inputValidation:t,outputValidation:i,inputWarnings:t.warnings,outputWarnings:i.warnings},e);return console.error("🔧 adapt: result.data.basicInfo:",a.data.basicInfo),console.error("🔧 adapt: result.data.basicInfo?.answerUnit:",a.data.basicInfo?.answerUnit),a}catch(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}validateInput(e){return gr.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(console.error("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([t,n])=>{if(n&&typeof n=="object"){console.error(` 🔍 Processing geometry shape ${t}:`,{id:n.id,type:n.type,hasEndpoints:"endpoints"in n,endpoints:n.endpoints,endpointsIsArray:Array.isArray(n.endpoints),shapeKeys:Object.keys(n)});const s=this.convertGeometryShapeCoordinates(n);console.error(` 📍 ${t}:`,{type:n.type,position:n.position,vertices:n.vertices}),this.referenceContext.geometryPresets[t]=s}}),console.error("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):console.error("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&Object.entries(e.transform_definitions).forEach(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=s}}),e.scenes&&typeof e.scenes=="object"&&Object.values(e.scenes).forEach(t=>{t&&t.content&&Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="graph"&&n.shapes&&this.extractPointCoordinatesFromShapes(n.shapes)})})}extractGeometryTransformConfigsFromInput(e){if(!e){console.error("⚠️ extractGeometryTransformConfigsFromInput: inputData is null or undefined");return}this.referenceContext.geometryTransformConfigs||(this.referenceContext.geometryTransformConfigs={}),e.geometry_transform_configs&&typeof e.geometry_transform_configs=="object"?(console.error("📦 Extracting geometry_transform_configs:",Object.keys(e.geometry_transform_configs)),Object.entries(e.geometry_transform_configs).forEach(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing geometry transform config ${t}:`,{id:n.id,strategy:n.strategy,hasBase:"base"in n,hasHeight:"height"in n,hasShapes:"shapes"in n,hasTransform:"transform"in n}),this.referenceContext.geometryTransformConfigs[t]=n)}),console.error("✅ geometryTransformConfigs after extraction:",Object.keys(this.referenceContext.geometryTransformConfigs))):console.error("⚠️ No geometry_transform_configs found in input data")}extractAnimationConfigsFromInput(e){if(!e){console.error("⚠️ extractAnimationConfigsFromInput: inputData is null or undefined");return}this.referenceContext.animationConfigs||(this.referenceContext.animationConfigs={}),e.animation_configs&&typeof e.animation_configs=="object"?(console.error("📦 Extracting animation_configs:",Object.keys(e.animation_configs)),Object.entries(e.animation_configs).forEach(([t,n])=>{n&&typeof n=="object"&&(console.error(` 🔍 Processing animation config ${t}:`,{id:n.id,description:n.description,hasTransforms:"transforms"in n,hasVisualEffects:"visualEffects"in n}),this.referenceContext.animationConfigs[t]=n)}),console.error("✅ animationConfigs after extraction:",Object.keys(this.referenceContext.animationConfigs))):console.error("⚠️ No animation_configs found in input data")}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;console.error("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0});const t={...e};t.type==="segment"&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(console.error(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,s)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(console.error(` Endpoint ${s} is not array:`,n),n)),t.type==="segment"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(console.error(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&console.error(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?t[n]=s:t[n]=this.convertGeometryShapeCoordinates(s));return console.error(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>typeof o=="object"?this.convertTransformDefinitionCoordinates(o):o):s&&typeof s=="object"&&(t[n]=this.convertTransformDefinitionCoordinates(s));return t}extractPointCoordinatesFromShapes(e){Array.isArray(e)&&e.forEach(t=>{if(t&&t.type==="point"&&t.position&&Array.isArray(t.position)&&t.position.length>=2){const n=t.id||`point_${t.position[0]}_${t.position[1]}`;this.referenceContext.geometryPresets[n]={type:"point",position:{x:t.position[0],y:t.position[1]}}}})}transformBaseData(e){if(!e)return console.error("⚠️ transformBaseData: inputData is null or undefined"),{id:"fallback-empty-input",title:"回退数据",grade:5,unit:"未知单元",lesson:"未知课程",skill:"未知技能",objective:"未知目标",knowledgePoints:[],difficulty:1,metadata:{},basicInfo:{question:""},scenes:{question:{items:[]},solve:{items:[]},review:{items:[]}},explanation:{steps:[]},answer:{value:0,unit:"",explanation:""}};this.extractGeometryDefinitionsFromInput(e),this.extractGeometryTransformConfigsFromInput(e),this.extractAnimationConfigsFromInput(e);const t={id:e.math_prob_id||Xc.generateId("triangle"),title:e.title,grade:this.parseGrade(e.grade_id),unit:e.unit_name,lesson:e.lesson_name,skill:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points||[],difficulty:e.difficulty||1,metadata:this.transformMetadata(e),description:e.description,scenes:this.transformScenesStructure(e.scenes),answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info)};["unit_id","lesson_id","module_id","skill_item_id","skill_id","created_at","updated_at","layout"].forEach(o=>{e[o]!==void 0&&(t[o]=e[o])}),console.error("🔧 transformBaseData: inputData.basic_info =",e.basic_info);const s=this.transformBasicInfo(e.basic_info);return console.error("🔧 transformBaseData: basicInfo after transform =",s),console.error("🔧 transformBaseData: basicInfo.answerUnit =",s?.answerUnit),this.referenceContext.basicInfo=s,t.basicInfo=s,console.error("🔧 transformBaseData: transformed.basicInfo set =",t.basicInfo),t.explanation=this.transformExplanation(e.explanation),t}parseGrade(e){const t=e.match(/g(\d+)/);return t?parseInt(t[1],10):5}transformMetadata(e){return e.metadata&&typeof e.metadata=="object"?e.metadata:{topic:e.unit_name||"三角形面积计算",skill:e.skill_description||"三角形面积求解技能",tags:e.knowledge_points||["三角形面积公式"]}}transformBasicInfo(e){if(console.error("🔄 transformBasicInfo called with:",e),!e||typeof e!="object")return console.error("⚠️ transformBasicInfo: basicInfo is empty, returning default"),{question:""};const t={...e};return console.error("🔄 transformBasicInfo: transformed copy:",t),t.question===void 0&&t.content!==void 0&&(t.question=t.content),t.question===void 0&&(t.question=""),console.error("🔄 transformBasicInfo: returning:",t),t}transformScenesStructure(e){if(!e||typeof e!="object")return{question:{items:[]},solve:{items:[]},review:{items:[]}};const t={};return["question","solve","review"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];t[o]={...i,items:a},i.content!==void 0&&delete t[o].content}else t[o]={items:[]}}),["remember"].forEach(o=>{if(e[o]){const i=e[o],a=i.items||i.content||[];t[o]={...i,items:a},i.content!==void 0&&delete t[o].content}}),t}transformExplanation(e){if(console.error("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&e.steps&&Array.isArray(e.steps),stepsCount:e&&e.steps?e.steps.length:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){console.error(`🔄 transformExplanation: processing ${e.steps.length} steps`);const t=e.steps.map((n,s)=>(console.error(` Step ${s}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(console.error(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.error(" chartConfig keys:",Object.keys(t)),n!=="graph"&&n!=="geometryTransform")return console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const s={type:n,...t};console.error(" contentBlock keys:",Object.keys(s)),n==="graph"&&s.shapes&&(console.error(" shapes count:",s.shapes.length),s.shapes.length>0&&console.error(" first shape:",s.shapes[0])),console.error("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.error("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]);const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});console.error(" transformedBlock keys:",Object.keys(o)),n==="graph"&&o.shapes&&console.error(" transformed shapes count:",o.shapes.length);let i;if(n==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,console.error(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.error(` geometryTransform preserved: step.title=${e.title}`),console.error(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.error(" geometryTransform preserved: config=",i.metadata?.config);else if(n==="graph"&&o.boardConfig){const{boardConfig:a,...c}=o;i={...c,...a},console.error(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}resolveReferences(e){const t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),Kr.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(console.warn(`引用未找到: ${n}`),n)})}transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(console.error("🔄 transformScenes: starting scene transformation"),console.error(" - referenceContext.geometryPresets keys:",Object.keys(this.referenceContext.geometryPresets||{})),console.error(" - enableReferenceResolution:",this.config.enableReferenceResolution),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),console.error("✅ transformScenes: completed scene transformation")),t}validateOutput(e){return gr.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const s=this.performanceMonitor.getStats(),o=this.performanceMonitor.checkPerformance(),i=[...t.inputValidation.warnings.map(d=>({code:B.INVALID_INPUT,message:`输入验证警告: ${d}`,suggestion:"检查输入数据格式"})),...t.outputValidation.warnings.map(d=>({code:B.OUTPUT_VALIDATION_FAILED,message:`输出验证警告: ${d}`,suggestion:"检查数据转换逻辑"})),...o.warnings.map(d=>({code:B.TRANSFORMATION_FAILED,message:`性能警告: ${d}`,suggestion:"优化数据转换性能"}))],a=n||e,c=this.config.enableReferenceResolution?this.resolverRegistry.extractAllRefs(a):[],l=Kr.calculateReferenceStats(c,this.referenceContext);return{data:e,warnings:i,performance:s,referenceStats:{total:l.total,resolved:l.resolved,failed:l.failed,byType:l.byType}}}createFallbackResult(e,t){const n={...lr,id:e?.math_prob_id||lr.id,title:e?.title||lr.title},s={code:B.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t.message}`,suggestion:"检查输入数据格式和适配器配置"};return{data:n,warnings:[s],performance:this.performanceMonitor.getStats(),referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}getPerformanceStats(){return this.performanceMonitor.getStats()}reset(){this.performanceMonitor.reset()}}class Yt{config;referenceContext;resolverRegistry;transformerRegistry;performanceMonitor;syncAdapter;constructor(e={}){this.config={...jc,...e},this.referenceContext=To(),this.resolverRegistry=No(),this.transformerRegistry=$o(),this.performanceMonitor=new ko,this.syncAdapter=new Jc(e)}adapt(e){this.config.enableLogging&&console.log("🔧 GeometryAdapter.adapt called with inputData (delegating to SyncAdapterCore):",{math_prob_id:e?.math_prob_id,schema_version:e?.schema_version,shape:e?.basic_info?.shape,hasGeometryShapes:!!e?.geometry_shapes,geometryShapeKeys:e?.geometry_shapes?Object.keys(e.geometry_shapes):[],hasScenes:!!e?.scenes,sceneKeys:e?.scenes?Object.keys(e.scenes):[]}),this.performanceMonitor.markStart("total");try{const t=e,n=this.syncAdapter.adapt(t);return this.performanceMonitor.markEnd("total"),this.config.enableLogging&&console.log("✅ GeometryAdapter.adapt completed successfully:",{id:n.data.id,hasBasicInfo:!!n.data.basicInfo,warningCount:n.warnings.length,referenceStats:n.referenceStats}),n}catch(t){if(this.performanceMonitor.markEnd("total"),this.config.strictMode)throw t;if(this.config.fallbackOnError)return console.warn("适配失败,使用回退数据:",t),this.createFallbackResult(e,t);throw t}}_validateInput(e){return gr.validateInput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}extractGeometryDefinitionsFromInput(e){if(!e){this.config.enableLogging&&console.error("⚠️ extractGeometryDefinitionsFromInput: inputData is null or undefined");return}this.referenceContext.geometryPresets||(this.referenceContext.geometryPresets={}),this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),e.geometry_shapes&&typeof e.geometry_shapes=="object"?(this.config.enableLogging&&console.log("📦 Extracting geometry_shapes:",Object.keys(e.geometry_shapes)),Object.entries(e.geometry_shapes).forEach(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertGeometryShapeCoordinates(n);this.referenceContext.geometryPresets[t]=s}}),this.config.enableLogging&&console.log("✅ geometryPresets after extraction:",Object.keys(this.referenceContext.geometryPresets))):this.config.enableLogging&&console.log("⚠️ No geometry_shapes found in input data"),e.transform_definitions&&typeof e.transform_definitions=="object"&&(this.referenceContext.transformDefinitions||(this.referenceContext.transformDefinitions={}),Object.entries(e.transform_definitions).forEach(([t,n])=>{if(n&&typeof n=="object"){const s=this.convertTransformDefinitionCoordinates(n);this.referenceContext.transformDefinitions[t]=s}}))}transformAnswer(e){return!e||typeof e!="object"?{value:0,unit:"",explanation:""}:{value:e.value||0,unit:e.unit||"",explanation:e.explanation_text||""}}transformAnswerInfo(e){if(!(!e||typeof e!="object"))return{...e,explanation_text:e.explanation_text||""}}transformExplanation(e){if(this.config.enableLogging&&console.log("🔄 transformExplanation called:",{hasExplanation:!!e,isArray:Array.isArray(e),hasSteps:e&&!Array.isArray(e)&&e.steps&&Array.isArray(e.steps),stepsCount:e?Array.isArray(e)?e.length:e.steps?e.steps.length:0:0}),!e)return{steps:[]};if(Array.isArray(e))return{steps:e};if(e.steps&&Array.isArray(e.steps)){this.config.enableLogging&&console.log(`🔄 transformExplanation: processing ${e.steps.length} steps`);const t=e.steps.map((n,s)=>(this.config.enableLogging&&console.log(` Step ${s}: hasChartConfig=${!!n.chartConfig}`),this.transformExplanationStep(n)));return{...e,steps:t}}return{steps:[]}}transformExplanationStep(e){if(!e||!e.chartConfig)return e;const t=e.chartConfig,n=t.type;if(this.config.enableLogging&&(console.log(`🔄 transformExplanationStep: step.title=${e.title}, chartConfigType=${n}`),console.log(" chartConfig keys:",Object.keys(t))),n!=="graph"&&n!=="geometryTransform")return this.config.enableLogging&&console.warn(`⚠️ 不支持的 chartConfig 类型: ${n},跳过转换`),e;try{const s={...t,type:n};this.config.enableLogging&&(console.log(" contentBlock keys:",Object.keys(s)),n==="graph"&&s.shapes&&(console.log(" shapes count:",s.shapes.length),s.shapes.length>0&&console.log(" first shape:",s.shapes[0]))),this.config.enableLogging&&(console.log("🔍 transformExplanationStep: referenceContext.transformDefinitions =",this.referenceContext.transformDefinitions),console.log("🔍 transformExplanationStep: transformDefinitions keys =",this.referenceContext.transformDefinitions?Object.keys(this.referenceContext.transformDefinitions):[]));const o=this.transformerRegistry.transform(s,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode});this.config.enableLogging&&(console.log(" transformedBlock keys:",Object.keys(o)),n==="graph"&&o.shapes&&console.log(" transformed shapes count:",o.shapes.length));let i;if(n==="geometryTransform"&&o.metadata&&o.metadata.config)i=o,this.config.enableLogging&&(console.log(` geometryTransform preserved: metadata.config exists=${!!i.metadata?.config}`),console.log(` geometryTransform preserved: step.title=${e.title}`),console.log(" geometryTransform preserved: config keys=",Object.keys(i.metadata?.config||{})),console.log(" geometryTransform preserved: config=",i.metadata?.config));else if(n==="graph"&&o.boardConfig){const{boardConfig:a,...c}=o;i={...c,...a},this.config.enableLogging&&console.log(` graph flattened: boundingBox=${i.boundingBox}`)}else i={...o};return{...e,chartConfig:i}}catch(s){if(this.config.enableLogging&&console.error("❌ 转换解释步骤中的 chartConfig 失败:",s),this.config.strictMode)throw s;return e}}convertGeometryShapeCoordinates(e){if(!e||typeof e!="object")return e;this.config.enableLogging&&console.log("🔄 convertGeometryShapeCoordinates called for shape:",{id:e.id,type:e.type,hasEndpoints:"endpoints"in e,endpoints:e.endpoints,endpointsIsArray:Array.isArray(e.endpoints),endpointsLength:e.endpoints?e.endpoints.length:0});const t={...e};t.type==="segment"&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line"),Array.isArray(t.position)&&t.position.length>=2&&(t.position={x:t.position[0],y:t.position[1]}),Array.isArray(t.vertices)&&(t.vertices=t.vertices.map(n=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:n)),Array.isArray(t.endpoints)?(this.config.enableLogging&&console.log(`🔄 Processing endpoints for shape ${t.id||"unknown"}:`,{endpointsLength:t.endpoints.length,firstEndpoint:t.endpoints[0],firstEndpointType:typeof t.endpoints[0],firstEndpointIsArray:Array.isArray(t.endpoints[0])}),t.endpoints=t.endpoints.map((n,s)=>Array.isArray(n)&&n.length>=2?{x:n[0],y:n[1]}:(this.config.enableLogging&&console.log(` Endpoint ${s} is not array:`,n),n)),t.type==="line"&&Array.isArray(t.endpoints)&&t.endpoints.length===2&&(this.config.enableLogging&&console.log(`🔄 Converting segment to line for shape ${t.id||"unknown"}`),t.type="line",t.start=t.endpoints[0],t.end=t.endpoints[1],delete t.endpoints)):"endpoints"in t&&this.config.enableLogging&&console.log(`⚠️ Shape ${t.id||"unknown"} has endpoints but not array:`,{endpoints:t.endpoints,endpointsType:typeof t.endpoints});for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>o&&typeof o=="object"&&"$ref"in o?o:typeof o=="object"?this.convertGeometryShapeCoordinates(o):o):s&&typeof s=="object"&&("$ref"in s?t[n]=s:t[n]=this.convertGeometryShapeCoordinates(s));return this.config.enableLogging&&console.log(`✅ convertGeometryShapeCoordinates result for ${e.id}:`,{type:t.type,hasEndpoints:"endpoints"in t,endpoints:t.endpoints,endpointsIsArray:Array.isArray(t.endpoints),endpointsLength:t.endpoints?t.endpoints.length:0,keys:Object.keys(t)}),t}convertTransformDefinitionCoordinates(e){if(!e||typeof e!="object")return e;const t={...e};if(t.config&&t.config.center){const n=t.config.center;n&&typeof n=="object"&&"x"in n&&"y"in n&&(t.config.center=[n.x,n.y])}for(const[n,s]of Object.entries(t))Array.isArray(s)?t[n]=s.map(o=>typeof o=="object"&&o!==null?"id"in o&&"type"in o&&"config"in o?this.convertTransformDefinitionCoordinates(o):this.deepClone(o):o):s&&typeof s=="object"&&("id"in s&&"type"in s&&"config"in s?t[n]=this.convertTransformDefinitionCoordinates(s):t[n]=this.deepClone(s));return t}deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.deepClone(n));const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=this.deepClone(e[n]));return t}_transformBaseData(e){this.extractGeometryDefinitionsFromInput(e);const t={id:e.math_prob_id,title:e.title,grade:parseInt(e.grade_id.replace("g",""))||5,unit:e.unit_name,lesson:e.lesson_name,skillDescription:e.skill_description,objective:e.objective,knowledgePoints:e.knowledge_points,difficulty:e.difficulty,description:e.description,metadata:e.metadata,basicInfo:{question:e.basic_info.question,answerUnit:e.basic_info.answerUnit||e.basic_info.areaUnit,shape:e.basic_info.shape,base:e.basic_info.base,height:e.basic_info.height,baseUnit:e.basic_info.baseUnit,heightUnit:e.basic_info.heightUnit,topBase:e.basic_info.topBase,topBaseUnit:e.basic_info.topBaseUnit,length:e.basic_info.length,width:e.basic_info.width,lengthUnit:e.basic_info.lengthUnit,widthUnit:e.basic_info.widthUnit,side:e.basic_info.side,sideUnit:e.basic_info.sideUnit,variables:e.basic_info.variables,score:e.basic_info.score,context:e.basic_info.context},rawGeometryShapes:e.geometry_shapes,rawTransformDefinitions:e.transform_definitions,rawGeometryTransformConfigs:e.geometry_transform_configs,rawAnimationConfigs:e.animation_configs,rawScenes:e.scenes,rawExplanation:e.explanation,rawAnswerInfo:e.answer_info,answer:this.transformAnswer(e.answer_info),answer_info:this.transformAnswerInfo(e.answer_info),explanation:this.transformExplanation(e.explanation),unitId:e.unit_id,lessonId:e.lesson_id,moduleId:e.module_id,skillItemId:e.skill_item_id,skillId:e.skill_id,createdAt:e.created_at,updatedAt:e.updated_at,layout:e.layout};return this.referenceContext.basicInfo=t.basicInfo,e.geometry_transform_configs&&(this.referenceContext.geometryTransformConfigs=e.geometry_transform_configs),e.animation_configs&&(this.referenceContext.animationConfigs=e.animation_configs),t}_resolveReferences(e){const t=this.resolverRegistry.extractAllRefs(e);return this.performanceMonitor.setReferenceCount(t.length),this.resolverRegistry.batchResolve(t,this.referenceContext),Kr.replaceReferences(e,this.referenceContext,{strictMode:this.config.strictMode,onMissing:n=>(this.config.enableLogging&&console.warn(`引用未找到: ${n}`),n)})}_transformScenes(e){const t={...e};return t.scenes&&typeof t.scenes=="object"&&(this.config.enableLogging&&console.log("🔄 transformScenes: starting scene transformation"),t.scenes=this.transformerRegistry.transformScenes(t.scenes,this.referenceContext,{enableReferenceResolution:this.config.enableReferenceResolution,strictMode:this.config.strictMode}),this.config.enableLogging&&console.log("✅ transformScenes: completed scene transformation")),t}_validateOutput(e){return gr.validateOutput(e,{strictMode:this.config.strictMode||this.config.validationLevel==="strict"})}buildResult(e,t,n){const s=this.performanceMonitor.getStats(),o=this.resolverRegistry.getStats?.()||{total:0,resolved:0,failed:0,byType:{}},i=[...(t.inputWarnings||[]).map(a=>({code:Mr.MISSING_REQUIRED_FIELD,message:a,path:"input"})),...(t.outputWarnings||[]).map(a=>({code:Mr.OUTPUT_VALIDATION_FAILED,message:a,path:"output"}))];return{data:e,warnings:i,performance:this.config.enablePerformanceMonitoring?s:void 0,referenceStats:o}}createFallbackResult(e,t){return{data:{...lr,id:e?.math_prob_id||"geometry-fallback",title:e?.title||"几何问题(回退)",basicInfo:{question:e?.basic_info?.question||"计算下面几何图形的面积:",answerUnit:e?.basic_info?.answerUnit||"cm²",shape:e?.basic_info?.shape||"triangle",base:e?.basic_info?.base||6,height:e?.basic_info?.height||4,baseUnit:e?.basic_info?.baseUnit||"cm",heightUnit:e?.basic_info?.heightUnit||"cm"}},warnings:[{code:Mr.TRANSFORMATION_FAILED,message:`适配失败,使用回退数据: ${t instanceof Error?t.message:t}`,suggestion:"检查输入数据格式是否符合V4规范"}],referenceStats:{total:0,resolved:0,failed:0,byType:{}}}}static create(e){return new Yt(e)}}function dt(r,e){return new Yt(e).adapt(r)}async function _n(r,e){return Promise.resolve(dt(r,e))}function Oo(r,e){const t=typeof r=="function"?r():r;return dt(t,e)}async function jo(r,e){const t=typeof r=="function"?await r():r instanceof Promise?await r:r;return dt(t,e)}function Io(r){return new Yt(r)}function Mo(r){const e=new Yt(r);return{adapt:t=>Promise.resolve(e.adapt(t))}}function Zc(r,e="input"){const{ValidationManager:t}=require("../TriangleAdapterV3/validators");return t.validate(r,e)}function Qc(r,e,t=100){const n=[];for(let c=0;c<t;c++){const l=performance.now();r.adapt(e);const d=performance.now();n.push(d-l)}const s=n.reduce((c,l)=>c+l,0)/t,o=Math.min(...n),i=Math.max(...n),a=process.memoryUsage?.().heapUsed||0;return{averageTime:s,minTime:o,maxTime:i,memoryUsage:a}}const ed={adapt:(r,e)=>dt(r,e),adaptAsync:(r,e)=>_n(r,e),create:r=>Io(r)},td="4.0.0",Fo="4.0.0";function rd(r="4.0.0"){return Fo>=r}function Po(r){return r?.schema_version==="4.0.0"||r?.schema_version?.startsWith("4.")}function nd(r){return Po(r)&&(r.geometry_shapes||r.transform_definitions||r.basic_info?.shape&&["triangle","acute_triangle","right_triangle","obtuse_triangle","trapezoid","parallelogram","rectangle","square","rhombus"].includes(r.basic_info.shape))}class Dr extends Error{constructor(e,t,n,s){super(`Failed to generate config for ${t}: ${e}`),this.shapeType=t,this.options=n,this.innerError=s,this.name="ConfigGenerationError"}}function sd(r){const e=[],t=[];if(r.shapes||e.push(U("MISSING_SHAPES","缺少形状定义","$.shapes",void 0)),r.transform||e.push(U("MISSING_TRANSFORM","缺少变换配置","$.transform",void 0)),r.strategy||e.push(U("STRATEGY_MISMATCH","缺少变换策略","$.strategy",void 0)),e.length>0)return{isValid:!1,errors:e,fixes:ns(e),timestamp:new Date().toISOString()};r.shapes&&e.push(...od(r.shapes));let n=!1;if(r.shapes?.animated){for(const s of r.shapes.animated)if(s.transform){n=!0;break}}return r.transform?e.push(...id(r.transform)):n||e.push(U("MISSING_TRANSFORM","缺少变换配置:需要全局transform或形状专属transform","$.transform",void 0,{type:"rotation"})),e.push(...ad(r)),e.push(...ld(r)),e.push(...cd(r)),e.length>0&&t.push(...ns(e)),{isValid:e.length===0,errors:e,fixes:t,timestamp:new Date().toISOString()}}function Do(r){if(!r||typeof r!="object"||!r.type||typeof r.type!="string"||!["rotation","translation","scale","composite"].includes(r.type))return!1;switch(r.type){case"rotation":if(!r.config||typeof r.config!="object")return!1;const t=r.config.center;if(t!=="auto"&&(!Array.isArray(t)||t.length!==2)||typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number"||r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical")return!1;break;case"translation":if(!r.config||typeof r.config!="object")return!1;const n=r.config.direction;if(Array.isArray(n)){if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="number")return!1}else if(typeof n=="string"){if(n!=="horizontal"&&n!=="vertical")return!1}else return!1;if(typeof r.config.distance!="number"||r.config.distance<=0)return!1;break;case"scale":if(!r.config||typeof r.config!="object")return!1;const s=r.config.center;if(s!=="centroid"&&(!Array.isArray(s)||s.length!==2)||typeof r.config.startScale!="number"||typeof r.config.endScale!="number"||typeof r.config.uniform!="boolean")return!1;break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))return!1;for(const o of r.transforms)if(!Do(o))return!1;if(r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel")return!1;break}return!0}function Lo(r,e){const t=[];if(!r||typeof r!="object")return t.push(U("INVALID_TRANSFORM_CONFIG","变换配置必须是对象",e,r,{type:"rotation"})),t;(!r.type||typeof r.type!="string")&&t.push(U("INVALID_TRANSFORM_CONFIG","变换类型缺失或无效",`${e}.type`,r.type,"rotation"));const n=["rotation","translation","scale","composite"];switch(r.type&&!n.includes(r.type)&&t.push(U("INVALID_TRANSFORM_CONFIG",`无效的变换类型: ${r.type}`,`${e}.type`,r.type,"rotation")),r.type){case"rotation":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","旋转变换缺少配置",`${e}.config`,r.config,{center:[0,0],startAngle:0,endAngle:Math.PI,direction:"clockwise"}));else{const s=r.config.center;s!=="auto"&&(!Array.isArray(s)||s.length!==2)&&t.push(U("INVALID_TRANSFORM_CONFIG",'旋转中心必须是包含两个数字的数组或字符串 "auto"',`${e}.config.center`,r.config.center,[0,0])),(typeof r.config.startAngle!="number"||typeof r.config.endAngle!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","旋转起始角度和结束角度必须是数字",`${e}.config.startAngle`,r.config,{startAngle:0,endAngle:Math.PI})),r.config.direction!=="clockwise"&&r.config.direction!=="counterclockwise"&&r.config.direction!=="horizontal"&&r.config.direction!=="vertical"&&t.push(U("INVALID_TRANSFORM_CONFIG","旋转方向必须是 clockwise、counterclockwise、horizontal 或 vertical",`${e}.config.direction`,r.config.direction,"clockwise"))}break;case"translation":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","平移变换缺少配置",`${e}.config`,r.config,{direction:"horizontal",distance:1}));else{const s=r.config.direction;Array.isArray(s)?s.length!==2?t.push(U("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含两个数字",`${e}.config.direction`,s,[1,0])):(typeof s[0]!="number"||typeof s[1]!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","平移方向数组必须包含数字",`${e}.config.direction`,s,[1,0])):typeof s=="string"?s!=="horizontal"&&s!=="vertical"&&t.push(U("INVALID_TRANSFORM_CONFIG","平移方向必须是 horizontal 或 vertical",`${e}.config.direction`,s,"horizontal")):t.push(U("INVALID_TRANSFORM_CONFIG","平移方向必须是数组 [number, number] 或字符串 horizontal/vertical",`${e}.config.direction`,s,"horizontal")),(typeof r.config.distance!="number"||r.config.distance<=0)&&t.push(U("INVALID_TRANSFORM_CONFIG","平移距离必须是大于0的数字",`${e}.config.distance`,r.config.distance,1))}break;case"scale":if(!r.config||typeof r.config!="object")t.push(U("INVALID_TRANSFORM_CONFIG","缩放变换缺少配置",`${e}.config`,r.config,{center:"centroid",startScale:1,endScale:2,uniform:!0}));else{const s=r.config.center;s!=="centroid"&&(!Array.isArray(s)||s.length!==2)&&t.push(U("INVALID_TRANSFORM_CONFIG",'缩放中心必须是包含两个数字的数组或字符串 "centroid"',`${e}.config.center`,r.config.center,"centroid")),(typeof r.config.startScale!="number"||typeof r.config.endScale!="number")&&t.push(U("INVALID_TRANSFORM_CONFIG","缩放起始比例和结束比例必须是数字",`${e}.config.startScale`,r.config,{startScale:1,endScale:2})),typeof r.config.uniform!="boolean"&&t.push(U("INVALID_TRANSFORM_CONFIG","缩放uniform字段必须是布尔值",`${e}.config.uniform`,r.config.uniform,!0))}break;case"composite":if(!r.transforms||!Array.isArray(r.transforms))t.push(U("INVALID_TRANSFORM_CONFIG","复合变换transforms字段必须是数组",`${e}.transforms`,r.transforms,[]));else for(let s=0;s<r.transforms.length;s++){const o=Lo(r.transforms[s],`${e}.transforms[${s}]`);t.push(...o)}r.executionMode!==void 0&&r.executionMode!=="sequential"&&r.executionMode!=="parallel"&&t.push(U("INVALID_TRANSFORM_CONFIG","复合变换执行模式必须是 sequential 或 parallel",`${e}.executionMode`,r.executionMode,"sequential"));break}return t}function U(r,e,t,n,s){let o=s;if(s===void 0)switch(r){case"INVALID_TRIANGLE_TYPE":o="right_triangle";break;case"INVALID_BASE_VALUE":case"INVALID_HEIGHT_VALUE":o=1;break;case"INVALID_ORIGIN":o=0;break;case"MISSING_SHAPES":o={static:[],animated:[]};break;case"MISSING_TRANSFORM":o={type:"rotation"};break;case"STRATEGY_MISMATCH":o="single_rotation";break;case"UNIT_MISMATCH":o="in";break;default:o=void 0}return{code:r,message:e,path:t,value:n,suggestedValue:o}}function od(r){const e=[];if(!r||typeof r!="object")return e.push(U("MISSING_SHAPES","形状定义无效或缺失","$.shapes",r)),e;if(!Array.isArray(r.static))e.push(U("INVALID_SHAPE_VERTICES","静态形状必须是数组","$.shapes.static",r.static));else for(let t=0;t<r.static.length;t++){const n=r.static[t],s=rs(n,`$.shapes.static[${t}]`);e.push(...s)}if(!Array.isArray(r.animated))e.push(U("INVALID_SHAPE_VERTICES","动画形状必须是数组","$.shapes.animated",r.animated));else for(let t=0;t<r.animated.length;t++){const n=r.animated[t],s=rs(n,`$.shapes.animated[${t}]`);e.push(...s)}return e}function rs(r,e){const t=[];if(!r||typeof r!="object")return t.push(U("INVALID_SHAPE_VERTICES","形状定义必须是对象",e,r)),t;if((!r.type||typeof r.type!="string")&&t.push(U("INVALID_SHAPE_VERTICES","形状类型缺失或无效",`${e}.type`,r.type)),!Array.isArray(r.vertices))t.push(U("INVALID_SHAPE_VERTICES","形状顶点必须是数组",`${e}.vertices`,r.vertices));else if(r.vertices.length===0)t.push(U("INVALID_SHAPE_VERTICES","形状顶点数组不能为空",`${e}.vertices`,r.vertices));else for(let n=0;n<r.vertices.length;n++){const s=r.vertices[n];!Array.isArray(s)||s.length!==2?t.push(U("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须是包含两个数字的数组`,`${e}.vertices[${n}]`,s)):(typeof s[0]!="number"||typeof s[1]!="number")&&t.push(U("INVALID_SHAPE_VERTICES",`顶点 ${n} 必须包含数字`,`${e}.vertices[${n}]`,s))}if(r.transform!==void 0){const n=Lo(r.transform,`${e}.transform`);t.push(...n)}return t}function id(r){const e=[];if(!r)return e.push(U("MISSING_TRANSFORM","变换配置缺失","$.transform",r)),e;const t=Array.isArray(r),n=t?r:[r],s="$.transform";for(let o=0;o<n.length;o++){const i=n[o],a=t?`${s}[${o}]`:s;Do(i)||e.push(U("INVALID_TRANSFORM_CONFIG","变换配置无效",a,i))}return e}function ad(r){const e=[];if(!r.strategy)return e;const{strategy:t}=r;let n=0;if(r.transform&&(Array.isArray(r.transform)?n+=r.transform.length:typeof r.transform=="object"&&(r.transform.type==="composite"&&Array.isArray(r.transform.transforms)?n+=r.transform.transforms.length:n+=1)),r.shapes?.animated)for(const o of r.shapes.animated)o.transform&&(n+=1);return t.includes("single")&&n!==1&&e.push(U("STRATEGY_MISMATCH",`单旋转策略需要一个变换,但找到 ${n} 个`,"$.strategy",t,n===0?"single_rotation":"double_rotation")),t.includes("double")&&n!==2&&e.push(U("STRATEGY_MISMATCH",`双旋转策略需要两个变换,但找到 ${n} 个`,"$.strategy",t,n===1?"single_rotation":"double_rotation")),["single_rotation","double_rotation","cut_and_paste","rigid_rotation","double_rotation_visual_proof","fillcolor_swap"].includes(t)||e.push(U("STRATEGY_MISMATCH",`无效的策略名称: ${t}`,"$.strategy",t,"single_rotation")),e}function ld(r){const e=[];if(r.unit&&typeof r.unit!="string"&&e.push(U("UNIT_MISMATCH","单位必须是字符串","$.unit",r.unit,"in")),r.baseUnit&&typeof r.baseUnit!="string"&&e.push(U("UNIT_MISMATCH","底边单位必须是字符串","$.baseUnit",r.baseUnit,r.unit||"in")),r.heightUnit&&typeof r.heightUnit!="string"&&e.push(U("UNIT_MISMATCH","高度单位必须是字符串","$.heightUnit",r.heightUnit,r.unit||"in")),r.unit&&r.baseUnit&&r.baseUnit!==r.unit&&e.push(U("UNIT_MISMATCH",`底边单位 (${r.baseUnit}) 与主单位 (${r.unit}) 不一致`,"$.baseUnit",r.baseUnit,r.unit)),r.unit&&r.heightUnit&&r.heightUnit!==r.unit&&e.push(U("UNIT_MISMATCH",`高度单位 (${r.heightUnit}) 与主单位 (${r.unit}) 不一致`,"$.heightUnit",r.heightUnit,r.unit)),r.unit&&r.boardConfig&&r.boardConfig.boundingBox){const[t,n,s,o]=r.boardConfig.boundingBox,i=s-t,a=n-o,c=r.unit==="cm"?50:20;(i>c*5||a>c*5)&&e.push(U("UNIT_MISMATCH",`边界框尺寸(${i.toFixed(1)}×${a.toFixed(1)})与单位(${r.unit})不匹配`,"$.boardConfig.boundingBox",r.boardConfig.boundingBox,void 0))}return e}function cd(r){const e=[];if(r.shapes&&r.boardConfig&&r.boardConfig.boundingBox){const t=r.boardConfig.boundingBox,[n,s,o,i]=t,a=[...r.shapes.static||[],...r.shapes.animated||[]];for(let c=0;c<a.length;c++){const l=a[c];if(l&&l.vertices)for(let d=0;d<l.vertices.length;d++){const u=l.vertices[d];if(Array.isArray(u)&&u.length===2){const[y,m]=u;(y<n||y>o||m<i||m>s)&&e.push(U("GEOMETRY_INCONSISTENCY",`形状 ${c} 的顶点 ${d} (${y}, ${m}) 超出画板边界`,`$.shapes.${c<(r.shapes.static?.length||0)?"static":"animated"}[${c}].vertices[${d}]`,u,[Math.max(n,Math.min(y,o)),Math.max(i,Math.min(m,s))]))}}}}if(r.metadata&&r.metadata.base&&r.metadata.height){const t=.5*r.metadata.base*r.metadata.height;if(r.shapes?.static?.[0]?.vertices){const n=r.shapes.static[0].vertices;if(n.length===3){const[s,o]=n[0],[i,a]=n[1],[c,l]=n[2],d=.5*Math.abs((i-s)*(l-o)-(c-s)*(a-o));Math.abs(d-t)>.01&&e.push(U("GEOMETRY_INCONSISTENCY",`计算面积 (${d.toFixed(2)}) 与预期面积 (${t.toFixed(2)}) 不一致`,"$.metadata",{base:r.metadata.base,height:r.metadata.height,calculatedArea:d,expectedArea:t}))}}}return e}function ns(r){const e=[];for(const t of r)switch(t.code){case"INVALID_TRIANGLE_TYPE":e.push({action:"replace",path:t.path,value:t.suggestedValue||"right_triangle",description:`将三角形类型修复为: ${t.suggestedValue||"right_triangle"}`,isSafe:!0});break;case"INVALID_BASE_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将底边长度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_HEIGHT_VALUE":e.push({action:"replace",path:t.path,value:t.suggestedValue||1,description:`将高度修复为: ${t.suggestedValue||1}`,isSafe:!0});break;case"INVALID_ORIGIN":e.push({action:"replace",path:t.path,value:t.suggestedValue||0,description:`将原点坐标修复为: ${t.suggestedValue||0}`,isSafe:!0});break;case"MISSING_TRANSFORM":e.push({action:"add",path:t.path,value:{type:"rotation"},description:"添加默认旋转变换配置",isSafe:!1});break;default:t.suggestedValue!==void 0&&e.push({action:"replace",path:t.path,value:t.suggestedValue,description:`修复 ${t.code} 错误`,isSafe:!1})}return e}function ss(r){if(!dd(r))throw new Dr("Invalid parallelogram config options","parallelogram",r);const{base:e,height:t,unit:n="in",layoutDensity:s="compact",theme:o="light"}=r,i=r.originX??0,a=r.originY??0,c=r.skew??e/3;try{const l=fd(e,t,c,i,a,o),d=ud(e),u=md(s),y=hd(e,t,c,i,a);return{ui:{layoutDensity:s},base:e,height:t,unit:n,shapes:l,transform:d,animation:u,boardConfig:y,strategy:"cut_and_paste",theme:o,enableRigidityVerification:!0,enableKeyboardNavigation:!0,autoCompleteThreshold:.95,metadata:{shapeType:"parallelogram",base:e,height:t,skew:c,unit:n,originX:i,originY:a,strategy:"cut_and_paste",generatedAt:new Date().toISOString()}}}catch(l){throw l instanceof Dr?l:new Dr(l.message,"parallelogram",r,l)}}function dd(r){if(!r||typeof r!="object")return!1;const e=["base","height"];for(const t of e)if(!(t in r))return!1;return!(typeof r.base!="number"||r.base<=0||typeof r.height!="number"||r.height<=0||r.skew!==void 0&&(typeof r.skew!="number"||r.skew<0)||r.originX!==void 0&&(typeof r.originX!="number"||!isFinite(r.originX))||r.originY!==void 0&&(typeof r.originY!="number"||!isFinite(r.originY)))}function fd(r,e,t,n,s,o){const a=o==="dark"?{staticFill:"#2a4365",staticStroke:"#1a365d",animatedFill:"#4c51bf",animatedStroke:"#434190"}:{staticFill:"#8ec5fc",staticStroke:"#4a90e2",animatedFill:"#6a5acd",animatedStroke:"#483d8b"},c=[[n+t,s],[n+r,s],[n+r+t,s+e],[n+t,s+e]],l=[[n,s],[n+t,s],[n+t,s+e]];return{static:[{type:"trapezoid",vertices:c,style:{fillColor:a.staticFill,fillOpacity:.6,strokeColor:a.staticStroke,strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:l,style:{fillColor:a.animatedFill,fillOpacity:.7,strokeColor:a.animatedStroke,strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]}}function ud(r){return{type:"translation",translation:{direction:[1,0],distance:r}}}function md(r){return{slider:{position:r==="compact"?[0,-5]:[0,-8],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}}}function hd(r,e,t,n,s){const o=Math.min(n,n+t,n+r,n+r+t),i=Math.max(n,n+t,n+r,n+r+t),a=Math.min(s,s+e),c=Math.max(s,s+e),l=3;return{boundingBox:[o-l,c+l,i+l,a-l],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}function gd(r){return{id:r.id||r.math_prob_id,title:r.title||"",grade:r.grade||5,unit:r.unit||r.unit_name||"",lesson:r.lesson||r.lesson_name||"",skill:r.skill||r.skill_description||"",objective:r.objective||"",knowledgePoints:Array.isArray(r.knowledge_points)?r.knowledge_points:Array.isArray(r.knowledgePoints)?r.knowledgePoints:[],difficulty:r.difficulty||1,description:r.description||"",metadata:r.metadata||{topic:"",skill:"",tags:[]},math_prob_id:r.math_prob_id,grade_id:r.grade_id,unit_id:r.unit_id,lesson_id:r.lesson_id,module_id:r.module_id,skill_item_id:r.skill_item_id,skill_id:r.skill_id,created_at:r.created_at,updated_at:r.updated_at,layout:r.layout||{type:"card",padding:"20px",theme:"light"}}}function pd(r){const e=r||{};return{question:e.question||"",answerUnit:e.answerUnit||"",areaUnit:e.areaUnit||"",shape:e.shape||"",base:e.base||e.length||0,height:e.height||e.width||0,baseUnit:e.baseUnit||e.lengthUnit||"",heightUnit:e.heightUnit||e.widthUnit||"",length:e.base||e.length||0,width:e.height||e.width||0,lengthUnit:e.baseUnit||e.lengthUnit||"",widthUnit:e.heightUnit||e.widthUnit||"",variables:e.variables||{},context:e.context||{}}}function yd(r,e,t){return{value:r,unit:e,type:"numeric",tolerance:.01,format:{decimal_places:2,allow_fraction:!0,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!1},explanation_text:t}}function bd(r){return r?{value:r.value,unit:r.unit,explanation:r.explanation_text||r.explanation||"正确答案"}:null}function xd(r){return r.answer?r.answer:r.answer_info?bd(r.answer_info):null}function vd(){return{question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}},review:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}}]}}}function _d(){return{steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。"},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。"},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。"}],strategy:"visual_transformation",total_steps:3,estimated_time:120}}function wd(r){return Array.isArray(r)||r&&r.steps?r:{steps:[],strategy:"visual_transformation",total_steps:0,estimated_time:0}}function Uo(r){const e=gd(r),t=pd(r.basic_info||r.basicInfo),n=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"];return{id:r.id||r.math_prob_id||"parallelogram-area-001",title:r.title||"平行四边形面积公式推导",grade:r.grade||5,unit:r.unit||r.unit_name||"多边形的面积",lesson:r.lesson||r.lesson_name||"平行四边形的面积",skill:r.skill||r.skill_description||"已知平行四边形的底和高,求平行四边形面积",objective:r.objective||"理解平行四边形面积公式 A=bh",knowledgePoints:Array.isArray(r.knowledge_points||r.knowledgePoints)?r.knowledge_points||r.knowledgePoints:n,difficulty:r.difficulty||1,description:r.description||"通过割补变换演示理解平行四边形面积公式 A=bh",metadata:r.metadata||{topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换"]},basicInfo:{...t,question:t.question||"计算下面平行四边形的面积:",answerUnit:t.answerUnit||"平方英寸",shape:t.shape||"parallelogram",base:t.base||9,height:t.height||6,baseUnit:t.baseUnit||"in",heightUnit:t.heightUnit||"in",variables:t.variables||{b:9,h:6,unit:"in"},context:t.context||{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},scenes:Sd(r.scenes||vd(),"parallelogram",t),explanation:wd(r.explanation||_d()),answer:xd(r)||{value:54,unit:"square inches",explanation:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"},answer_info:r.answer_info||yd(54,"square inches","正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。"),...e,layout:r.layout||{type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}}}}function Ad(r){return r?.config&&typeof r.config=="object"}function Rd(r){if(r.shapes?.static&&r.shapes?.animated)return console.log("🔍 JSON config already in system format"),r;console.log("🔍 Converting parallelogram JSON config to system format"),console.log("📦 Input JSON config transform:",{hasTransform:!!r.transform,type:r.transform?.type,distance:r.transform?.translation?.distance,direction:r.transform?.translation?.direction});try{const e={...r};if(r.shapes&&typeof r.shapes=="object"){const t=[],n=[];if(r.shapes.trapezoid){const s=r.shapes.trapezoid;Array.isArray(s)?t.push(...s.map(o=>({...o,metadata:{...o.metadata,isStatic:!0}}))):typeof s=="object"&&t.push({...s,metadata:{...s.metadata,isStatic:!0}})}if(r.shapes.triangle){const s=r.shapes.triangle;Array.isArray(s)?n.push(...s.map(o=>({...o,metadata:{...o.metadata,isMovable:!0}}))):typeof s=="object"&&n.push({...s,metadata:{...s.metadata,isMovable:!0}})}(t.length===0||n.length===0)&&Object.entries(r.shapes).forEach(([s,o])=>{const i=s.toLowerCase();i.includes("static")||i.includes("original")||i.includes("trapezoid")?Array.isArray(o)?t.push(...o):o&&typeof o=="object"&&t.push(o):(i.includes("animated")||i.includes("movable")||i.includes("triangle"))&&(Array.isArray(o)?n.push(...o):o&&typeof o=="object"&&n.push(o))}),e.shapes={static:t,animated:n}}return!e.base&&r.base&&(e.base=r.base),!e.height&&r.height&&(e.height=r.height),!e.unit&&r.unit&&(e.unit=r.unit),r.transform&&r.transform.type==="translation"?(console.log("🔧 Processing translation transform from JSON"),console.log("📐 JSON transform details:",{type:r.transform.type,translation:r.transform.translation,distance:r.transform.translation?.distance,direction:r.transform.translation?.direction}),r.transform.translation&&(e.transform={type:"translation",translation:r.transform.translation},console.log("✅ Set converted.transform with distance:",r.transform.translation.distance))):r.transform?console.log("⚠️ JSON has transform but not translation type:",r.transform.type):console.log("ℹ️ No transform found in JSON config"),e.animation?(e.animation.slider||(e.animation.slider={position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01}),e.animation.progressIndicator||(e.animation.progressIndicator={enabled:!1})):e.animation={slider:{position:[0,-5],length:10,orientation:"horizontal",min:0,max:1,step:.01},progressIndicator:{enabled:!1}},!e.boardConfig&&r.boardConfig&&(e.boardConfig=r.boardConfig),e.strategy||(e.strategy="cut_and_paste"),e.theme||(e.theme="light"),e.layoutDensity||(e.layoutDensity="compact"),e.ui||(e.ui={layoutDensity:e.layoutDensity}),!e.baseUnit&&e.unit&&(e.baseUnit=e.unit),!e.heightUnit&&e.unit&&(e.heightUnit=e.unit),e.metadata||(e.metadata={shapeType:"parallelogram",base:e.base,height:e.height,unit:e.unit,strategy:e.strategy,generatedAt:new Date().toISOString()}),console.log("🎉 Conversion complete. Final converted config:"),console.log("📊 Final transform:",{type:e.transform?.type,distance:e.transform?.translation?.distance,direction:e.transform?.translation?.direction}),console.log("📐 Final base:",e.base,"height:",e.height),console.log("🏷️ Final strategy:",e.strategy,"theme:",e.theme),e}catch(e){return console.warn("Failed to convert parallelogram JSON config format:",e),r}}function Sd(r,e,t){if(r?.solve?.content){const n=r.solve.content.map(s=>{if(s.type==="geometryTransform"){if(Ad(s))try{const i=Rd(s.config),a=sd(i);if(a.isValid)return console.log("✅ Using JSON-provided parallelogram geometry transform configuration"),console.log("📏 JSON transform distance:",i.transform?.translation?.distance||i.transform?.translation?.distance||"N/A"),console.log("📐 JSON base:",i.base,"height:",i.height),{...s,metadata:{...s.metadata,config:i,source:"json",validationResult:a}};console.warn("❌ JSON-provided parallelogram config validation failed:",a.errors),console.log("📊 JSON config structure:",{hasShapes:!!i.shapes,hasTransform:!!i.transform,transformType:i.transform?.type,distance:i.transform?.translation?.distance,strategy:i.strategy,theme:i.theme})}catch(i){console.warn("Failed to process JSON-provided parallelogram config:",i)}let o;try{const i=t?.base||9,a=t?.height||6;console.log("🔄 Generating dynamic parallelogram config with base:",i,"height:",a),o=ss({base:i,height:a,unit:t?.baseUnit||t?.unit||"in",originX:t?.originX,originY:t?.originY,layoutDensity:"compact"}),console.log("📏 Dynamic transform distance:",o.transform?.translation?.distance||"N/A")}catch(i){console.warn("Failed to generate dynamic parallelogram config:",i),console.log("🔄 Using fallback dynamic config with base: 9, height: 6"),o=ss({base:9,height:6,unit:"in",layoutDensity:"compact"}),console.log("📏 Fallback transform distance:",o.transform?.translation?.distance||"N/A")}return console.log("🔧 Final config source: generated"),console.log("📊 Final transform details:",{type:o.transform?.type,direction:o.transform?.translation?.direction,distance:o.transform?.translation?.distance}),{...s,metadata:{...s.metadata,config:o,source:"generated"}}}return s});return{...r,solve:{...r.solve,content:n}}}return r}const Cd="4.0.0",Ed="1.0.0",Td="mp-10506-0002-0002-G01-0001",Nd="锐角三角形面积练习",$d="通过双旋转策略练习锐角三角形面积公式 A=½bh",kd="掌握锐角三角形面积公式 A=½bh,掌握双旋转证明方法",Od=1,jd="g5",Id="三角形面积计算",Md=1050602,Fd="锐角三角形的面积",Pd=105060201,Dd=1002,Ld="已知锐角三角形的底和高,求三角形面积",Ud="s-105-06-0002",Gd=1002,zd=2,Bd=["三角形面积公式 A=½bh","锐角三角形双旋转证明","直角三角形组合变换"],Vd={topic:"三角形面积计算",skill:"三角形面积求解技能",tags:["锐角三角形","双旋转策略","三角形面积公式"],version:"1.1.0",author:"chen-hui",strategy:"double_rotation_visual_proof"},Wd={question:"以下三角形面积是多少?",answerUnit:"cm²",shape:"acute_triangle",base:6,height:4,baseUnit:"cm",heightUnit:"cm",originX:2,originY:2,unit:"cm²",variables:{b:6,h:4,answer:12}},qd={acute_triangle:{id:"acute_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_b"},{$ref:"point_c"}],withLabel:!0,label:{offset:[-15,-15],fontSize:16,color:"#000000",anchorX:"middle",anchorY:"bottom"}},left_triangle:{id:"left_triangle",type:"polygon",vertices:[{$ref:"point_a"},{$ref:"point_d"},{$ref:"point_c"}]},right_triangle:{id:"right_triangle",type:"polygon",vertices:[{$ref:"point_b"},{$ref:"point_d"},{$ref:"point_c"}]},base_segment:{id:"base_segment",type:"segment",endpoints:[{$ref:"point_a"},{$ref:"point_b"}]},height_segment:{id:"height_segment",type:"segment",endpoints:[{$ref:"point_d"},{$ref:"point_c"}]},left_rotation_center:{id:"left_rotation_center",type:"point",position:{x:3.5,y:4}},right_rotation_center:{id:"right_rotation_center",type:"point",position:{x:6.5,y:4}},full_rectangle:{id:"full_rectangle",type:"polygon",vertices:[{x:2,y:2},{x:8,y:2},{x:8,y:6},{x:2,y:6}]},base_arrow:{id:"base_arrow",type:"segment",endpoints:[{x:2,y:1.5},{x:8,y:1.5}]},height_arrow:{id:"height_arrow",type:"segment",endpoints:[{x:5,y:2},{x:5,y:6}]},base_label_position:{id:"base_label_position",type:"point",position:{x:5,y:1.2}},height_label_position:{id:"height_label_position",type:"point",position:{x:5.5,y:4}},point_a:{id:"point_a",type:"point",position:{x:2,y:2},name:"A"},point_b:{id:"point_b",type:"point",position:{x:8,y:2},name:"B"},point_c:{id:"point_c",type:"point",position:{x:5,y:6},name:"C"},point_d:{id:"point_d",type:"point",position:{x:5,y:2},name:"D"}},Yd={type:"card",padding:"$spacing.large",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,keepAspectRatio:!0}},Hd={question:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"What is the area of the triangle?",styleRef:"text_heading_large"},{type:"graph",boardRef:"default",shapes:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{id:"base_line",type:"segment",geometryRef:"base_segment",styleRef:"base_highlight"},{id:"height_line",type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base_label",type:"text",geometryRef:"base_label_position",content:"6 cm",styleRef:"label_error"},{id:"height_label",type:"text",geometryRef:"height_label_position",content:"4 cm",styleRef:"text_primary"}]},{type:"interactive",component:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"cm²",submitButton:{label:"Submit",color:"$colors.success"}}}]},remember:{layout:{layoutRef:"vertical_spaced"},items:[{type:"text",content:"锐角三角形面积公式",styleRef:"text_heading_large"},{type:"formula",content:"A = \\frac{1}{2} \\times b \\times h",parts:["A = \\frac{1}{2} \\times b \\times h","= \\frac{1}{2} \\times 6 \\times 4","= \\frac{1}{2} \\times 24","= 12"],displayMode:!0,style:{fontSize:"$fonts.formula",color:"$colors.text_primary"}}]},solve:{layout:{layoutRef:"vertical_centered"},items:[{type:"text",content:"解题步骤演示",styleRef:"text_heading_large"},{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}]}},Kd={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别锐角三角形的底和高",description:"确定锐角三角形的底边长度 b = 6 cm 和对应的高度 h = 4 cm。垂足将底边平分为两段。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"acute_triangle",styleRef:"primary"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{id:"base-label",type:"text",position:{x:5,y:1.4},content:"6 cm",styleRef:"label_error"},{id:"height-label",type:"text",position:{x:5.3,y:4},content:"4 cm",styleRef:"label_success"}]}},{id:"exp-step-2",type:"instructionalStep",title:"双旋转策略:分割为两个直角三角形",description:"沿高线将锐角三角形分割为两个直角三角形:左直角三角形和右直角三角形。每个直角三角形将独立旋转。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"point",geometryRef:"left_rotation_center",styleRef:"primary",size:4},{type:"point",geometryRef:"right_rotation_center",styleRef:"primary",size:4}]}},{id:"exp-step-3",type:"instructionalStep",title:"刚体旋转形成矩形",description:"每个直角三角形围绕其斜边中点旋转180度,形成对应的矩形。左直角三角形形成左矩形,右直角三角形形成右矩形。",chartConfig:{type:"geometryTransform",geometryTransformRef:"double_rotation_proof"}},{id:"exp-step-4",type:"instructionalStep",title:"组合形成完整矩形并推导面积公式",description:"两个小矩形组合形成完整的大矩形,其面积为 b × h = 6 × 4 = 24 cm²。锐角三角形面积是大矩形面积的一半,即 A = ½ × b × h = 12 cm²。",chartConfig:{type:"graph",boardRef:"default",shapes:[{type:"polygon",geometryRef:"full_rectangle",styleRef:"primary"},{type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right"},{type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left"},{type:"segment",geometryRef:"base_segment",styleRef:"error"},{type:"segment",geometryRef:"height_segment",styleRef:"dashed"},{type:"text",position:{x:5,y:1.2},content:"Base = 6 cm",style:{fontSize:"$fonts.label",color:"$colors.error",fontWeight:"bold",anchorX:"middle"}},{type:"text",position:{x:5.5,y:4},content:"Height = 4 cm",style:{fontSize:"$fonts.label",color:"$colors.success",fontWeight:"bold"}}]}}]},Xd={value:12,unit:"cm²",type:"number",tolerance:.1,validation:{type:"exact",allowPartial:!1},explanation_text:"三角形面积 = ½ × 底 × 高 = ½ × 6cm × 4cm = 12cm²",solution_steps:["识别三角形的底和高","应用面积公式 A = ½ × b × h","代入数值:A = ½ × 6 × 4","计算:A = ½ × 24 = 12","添加单位:12 cm²"]},Jd="2026-01-20T20:34:00Z",Zd="2026-01-20T20:34:00Z",Qd={double_rotation_proof:{id:"double_rotation_proof",description:"双旋转几何证明策略",base:6,height:4,unit:"cm",strategy:"double_rotation",shapes:{static:[{id:"main_triangle",type:"polygon",geometryRef:"acute_triangle",styleRef:"primary",appearanceRef:"always_visible"}],animated:[{id:"left_triangle",type:"polygon",geometryRef:"left_triangle",styleRef:"highlight_left",appearanceRef:"appear_at_90"},{id:"right_triangle",type:"polygon",geometryRef:"right_triangle",styleRef:"highlight_right",appearanceRef:"appear_at_90"}]},transform:{type:"composite",transforms:[{transformRef:"left_rotation"},{transformRef:"right_rotation"}],executionMode:"parallel"},boardRef:"default",sliderRef:"slider_horizontal"}},ef={left_rotation:{id:"left_rotation",type:"rotation",config:{center:{x:3.5,y:4},startAngle:0,endAngle:3.14159,direction:"clockwise"},targetGroup:"left"},right_rotation:{id:"right_rotation",type:"rotation",config:{center:{x:6.5,y:4},startAngle:0,endAngle:3.14159,direction:"counterclockwise"},targetGroup:"right"}},tf={schema_version:Cd,config_version:Ed,math_prob_id:Td,title:Nd,description:$d,objective:kd,difficulty:Od,grade_id:jd,unit_name:Id,unit_id:Md,lesson_name:Fd,lesson_id:Pd,module_id:Dd,skill_description:Ld,skill_item_id:Ud,skill_id:Gd,score:zd,knowledge_points:Bd,metadata:Vd,basic_info:Wd,geometry_shapes:qd,layout:Yd,scenes:Hd,explanation:Kd,answer_info:Xd,created_at:Jd,updated_at:Zd,geometry_transform_configs:Qd,transform_definitions:ef},rf="mp-10506-0001-0001-G01-0001",nf="平行四边形面积公式推导",sf="通过割补变换演示理解平行四边形面积公式 A=bh",of="理解平行四边形面积公式 A=bh",af=1,lf="g5",cf="多边形的面积",df=1050601,ff="平行四边形的面积",uf=105060101,mf=1002,hf="已知平行四边形的底和高,求平行四边形面积",gf="s-105-06-0001",pf=1001,yf=["平行四边形面积公式 A=bh","平行四边形面积与矩形面积关系"],bf={topic:"面积计算",skill:"平行四边形面积公式的推导",tags:["平行四边形","割补变换","面积","公式推导","几何变换","平行四边形面积与矩形面积关系"],version:"1.0.0",author:"math-editor-system",created_date:"2024-01-15",last_modified:"2024-01-15",status:"published"},xf={question:"计算下面平行四边形的面积:",answerUnit:"平方英寸",shape:"parallelogram",base:9,height:6,baseUnit:"in",heightUnit:"in",score:2,variables:{b:9,h:6,unit:"in"},context:{learning_objective:"parallelogram_area_derivation",prerequisite_skills:["rectangle_area","unit_conversion"],time_estimate:300}},vf={type:"card",padding:"20px",theme:"light",renderer:{showFormulaSteps:!0,interactiveAnimations:!0,validateAnswers:!0,auto_progress:!0,hints_enabled:!0}},_f={question:{content:[{type:"text",content:"What is the area of the parallelogram?",style:{fontSize:"1.5rem",color:"#1e293b",fontWeight:"bold",textAlign:"center",marginBottom:"20px"}},{type:"graph",content:"parallelogram_static",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.8,strokeColor:"#2980b9",strokeWidth:2},{id:"height-dash",type:"line",start:{x:4,y:1},end:{x:4,y:7},strokeColor:"#64748b",strokeWidth:2,dash:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16},{id:"side-label",type:"text",position:{x:2.5,y:4},content:"9 in",color:"#475569",fontSize:16}],width:400,height:300,boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1},{type:"interactive",content:"answer_input",metadata:{componentType:"answer_input",config:{inputType:"number",placeholder:"输入面积",unit:"square inches",submitButton:{label:"Submit",color:"#67b510"}}}}],layout:{type:"vertical",spacing:"20px",alignment:"center"}},remember:{content:[{type:"text",content:"Core Concept Review:",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b"}},{type:"text",content:"The area of a parallelogram is found by multiplying its base by its height.",style:{marginTop:"8px"}},{type:"text",content:"Area = base × height",style:{color:"#64748b",marginTop:"8px"}},{type:"formula",content:"A = bh",parts:["A = bh"],displayMode:!0,style:{color:"#64748b",marginTop:"4px"}}],layout:{type:"vertical",spacing:"15px",alignment:"center",cardStyle:{backgroundColor:"#F8FAFC",borderColor:"#E3F2FD",borderWidth:"2px"}}},solve:{content:[{type:"text",content:"SOLVE",style:{fontSize:"1.25rem",fontWeight:"bold",color:"#1e293b",marginBottom:"10px"}},{type:"text",content:"This parallelogram has base b = 9 inches and height h = 6 inches.",style:{color:"#555",marginBottom:"15px"}},{type:"text",content:"Interactive Demo: Drag the slider to transform the parallelogram into a rectangle.",style:{color:"#555",fontStyle:"italic",marginBottom:"10px"}},{type:"geometryTransform",content:"平行四边形割补演示",enabled:!0,metadata:{componentType:"geometry-transform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{type:"text",content:"Through dissection, the parallelogram transforms into a rectangle with the same area.",style:{color:"#555",marginTop:"15px",marginBottom:"15px"}},{type:"formula",content:"A = b \\times h",parts:["A = b \\times h","= 9 \\times 6","= 54"],displayMode:!0,style:{fontSize:"1.2rem",textAlign:"center",margin:"15px 0"}},{type:"text",content:"The area of the parallelogram is 54 square inches.",style:{fontWeight:"bold",color:"#4a90e2",marginTop:"10px"}}],layout:{type:"vertical",spacing:"20px",alignment:"center",cardStyle:{backgroundColor:"#F0F9FF",borderColor:"#BAE6FD",borderWidth:"2px"}}}},wf={steps:[{id:"exp-step-1",type:"instructionalStep",title:"识别底和高",description:"确定平行四边形的底边长度 b = 9 inches 和对应的高度 h = 6 inches。",chartConfig:{type:"graph",shapes:[{id:"parallelogram",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:13,y:7},{x:4,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:4.3,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}},{id:"exp-step-2",type:"instructionalStep",title:"割补法演示",description:"将平行四边形切割成三角形和梯形,然后将三角形移动到另一侧形成长方形。",chartConfig:{type:"geometryTransform",config:{base:9,height:6,unit:"in",shapes:{static:[{type:"trapezoid",vertices:[[4,1],[10,1],[13,7],[4,7]],style:{fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},metadata:{id:"static-trapezoid",label:"梯形部分",isStatic:!0}}],animated:[{type:"triangle",vertices:[[1,1],[4,1],[4,7]],style:{fillColor:"#6a5acd",fillOpacity:.7,strokeColor:"#4b0082",strokeWidth:2},metadata:{id:"animated-triangle",label:"移动三角形",isMovable:!0}}]},transform:{type:"translation",translation:{direction:"horizontal",distance:9}},animation:{progressIndicator:{enabled:!1}},boardConfig:{boundingBox:[0,10,14,-1],keepAspectRatio:!0,showGrid:!0,showAxis:!1}}}},{id:"exp-step-3",type:"instructionalStep",title:"面积公式推导",description:"转换后的长方形面积 = b × h = 54 平方英寸,因此平行四边形面积 = b × h = 54 平方英寸。",chartConfig:{type:"graph",shapes:[{id:"rectangle",type:"polygon",vertices:[{x:1,y:1},{x:10,y:1},{x:10,y:7},{x:1,y:7}],fillColor:"#8ec5fc",fillOpacity:.6,strokeColor:"#2980b9",strokeWidth:2},{id:"base-label",type:"text",position:{x:5.5,y:.4},content:"9 in",color:"#475569",fontSize:16},{id:"height-label",type:"text",position:{x:10.5,y:4},content:"6 in",color:"#475569",fontSize:16}],boundingBox:[0,8,14,0],showGrid:!1,showAxis:!1}}],strategy:"visual_transformation",total_steps:3,estimated_time:120,hints:[{step:1,text:"注意平行四边形的高是从底边垂直向上的距离,不是斜边的长度"},{step:2,text:"尝试将左侧的三角形移动到右侧,观察图形如何变成矩形"}]},Af={value:54,unit:"square inches",type:"numeric",tolerance:0,format:{decimal_places:0,allow_fraction:!1,allow_negative:!1},validation_rules:{required:!0,min_value:0,max_value:1e3,exact_match:!0},explanation_text:"正确答案是54平方英寸。通过割补法,平行四边形可以转换为等面积的长方形,因此面积公式为:A = b × h = 9 × 6 = 54。",solution_steps:[{step:1,action:"identify_dimensions",description:"底边 b = 9 英寸,高 h = 6 英寸"},{step:2,action:"apply_formula",description:"面积公式 A = b × h"},{step:3,action:"calculate",description:"A = 9 × 6 = 54"},{step:4,action:"add_unit",description:"54 平方英寸"}]},Rf="2024-01-15T10:30:00Z",Sf="2024-01-15T10:30:00Z",Cf={math_prob_id:rf,title:nf,description:sf,objective:of,difficulty:af,grade_id:lf,unit_name:cf,unit_id:df,lesson_name:ff,lesson_id:uf,module_id:mf,skill_description:hf,skill_item_id:gf,skill_id:pf,knowledge_points:yf,metadata:bf,basic_info:xf,layout:vf,scenes:_f,explanation:wf,answer_info:Af,created_at:Rf,updated_at:Sf},Ef={enableReferenceResolution:!0,strictMode:!1,fallbackOnError:!0,validationLevel:"basic",enableLogging:!1};async function Tf(){console.warn(`⚠️ DEPRECATION WARNING ⚠️
|
|
22
22
|
函数 loadAcuteTriangleV2Data() 已弃用。
|
|
23
23
|
组件库不再包含数据加载逻辑。
|
|
24
24
|
|