@nice2dev/ui-math 1.1.9 → 1.1.10

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/dist/index.cjs CHANGED
@@ -1 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-BYbn7eM9.cjs");exports.CalculatorService=e.CalculatorService;exports.CalculusOps=e.CalculusOps;exports.EQUATION_TEMPLATES=e.EQUATION_TEMPLATES;exports.ExpressionParser=e.ExpressionParser;exports.FUNCTION_PRESETS=e.FUNCTION_PRESETS;exports.GeoMath=e.GeoMath;exports.GeometryService=e.GeometryService;exports.GraphService=e.GraphService;exports.MATH_SYMBOLS=e.MATH_SYMBOLS;exports.MathEditorService=e.MathEditorService;exports.MatrixOps=e.MatrixOps;exports.NiceCalculator=e.NiceCalculator;exports.NiceGeometry=e.NiceGeometry;exports.NiceGraphPlotter=e.NiceGraphPlotter;exports.NiceI18nProvider=e.NiceI18nProvider;exports.NiceMathEditor=e.NiceMathEditor;exports.createCalculatorService=e.createCalculatorService;exports.createGeometryService=e.createGeometryService;exports.createGraphService=e.createGraphService;exports.createMathEditorService=e.createMathEditorService;exports.getSymbolsByCategory=e.getSymbolsByCategory;exports.recognizeHandwriting=e.recognizeHandwriting;exports.useCalculator=e.useCalculator;exports.useGeometry=e.useGeometry;exports.useGraph=e.useGraph;exports.useMathEditor=e.useMathEditor;exports.useNiceTranslation=e.useNiceTranslation;
1
+ "use strict";var B=Object.defineProperty;var T=(e,t,r)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var C=(e,t,r)=>T(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const jsxRuntime=require("react/jsx-runtime"),ui=require("@nice2dev/ui"),uiCore=require("@nice2dev/ui-core"),React=require("react"),translations={en:{"calculator.matrixA":"Matrix A","calculator.matrixB":"Matrix B","calculator.exprPlaceholder":"Enter expression (e.g., x^2, sin(x))","calculator.differentiate":"Differentiate","calculator.integrate":"Integrate","calculator.convert":"Convert","plotter.quickAdd":"Quick add preset...","plotter.noPlots":"No plots added yet","plotter.grid":"Grid","plotter.axes":"Axes","editor.latexPlaceholder":"Enter LaTeX equation...","editor.clear":"Clear","editor.recognize":"Recognize","editor.recognizing":"Recognizing...","editor.handwritingNote":"Draw your equation above. Handwriting recognition requires external API integration."},pl:{"calculator.matrixA":"Macierz A","calculator.matrixB":"Macierz B","calculator.exprPlaceholder":"Wprowadź wyrażenie (np. x^2, sin(x))","calculator.differentiate":"Różniczkuj","calculator.integrate":"Całkuj","calculator.convert":"Przelicz","plotter.quickAdd":"Szybko dodaj ustawienie...","plotter.noPlots":"Nie dodano jeszcze żadnych wykresów","plotter.grid":"Siatka","plotter.axes":"Osie","editor.latexPlaceholder":"Wprowadź równanie LaTeX...","editor.clear":"Wyczyść","editor.recognize":"Rozpoznaj","editor.recognizing":"Rozpoznawanie...","editor.handwritingNote":"Narysuj równanie powyżej. Rozpoznawanie pisma wymaga zewnętrznej integracji API."},de:{"calculator.matrixA":"Matrix A","calculator.matrixB":"Matrix B","calculator.exprPlaceholder":"Ausdruck eingeben (z. B. x^2, sin(x))","calculator.differentiate":"Ableiten","calculator.integrate":"Integrieren","calculator.convert":"Umrechnen","plotter.quickAdd":"Voreinstellung schnell hinzufügen...","plotter.noPlots":"Noch keine Diagramme hinzugefügt","plotter.grid":"Raster","plotter.axes":"Achsen","editor.latexPlaceholder":"LaTeX-Gleichung eingeben...","editor.clear":"Löschen","editor.recognize":"Erkennen","editor.recognizing":"Erkennung läuft...","editor.handwritingNote":"Zeichnen Sie Ihre Gleichung oben. Die Handschrifterkennung erfordert eine externe API-Integration."},fr:{"calculator.matrixA":"Matrice A","calculator.matrixB":"Matrice B","calculator.exprPlaceholder":"Saisir une expression (ex. x^2, sin(x))","calculator.differentiate":"Dériver","calculator.integrate":"Intégrer","calculator.convert":"Convertir","plotter.quickAdd":"Ajouter un préréglage rapide...","plotter.noPlots":"Aucun tracé ajouté pour le moment","plotter.grid":"Grille","plotter.axes":"Axes","editor.latexPlaceholder":"Saisir une équation LaTeX...","editor.clear":"Effacer","editor.recognize":"Reconnaître","editor.recognizing":"Reconnaissance...","editor.handwritingNote":"Dessinez votre équation ci-dessus. La reconnaissance d'écriture nécessite une intégration API externe."},es:{"calculator.matrixA":"Matriz A","calculator.matrixB":"Matriz B","calculator.exprPlaceholder":"Introduce una expresión (p. ej. x^2, sin(x))","calculator.differentiate":"Derivar","calculator.integrate":"Integrar","calculator.convert":"Convertir","plotter.quickAdd":"Añadir preajuste rápido...","plotter.noPlots":"Aún no se ha añadido ningún gráfico","plotter.grid":"Cuadrícula","plotter.axes":"Ejes","editor.latexPlaceholder":"Introduce una ecuación LaTeX...","editor.clear":"Borrar","editor.recognize":"Reconocer","editor.recognizing":"Reconociendo...","editor.handwritingNote":"Dibuja tu ecuación arriba. El reconocimiento de escritura requiere integración con una API externa."},it:{"calculator.matrixA":"Matrice A","calculator.matrixB":"Matrice B","calculator.exprPlaceholder":"Inserisci un’espressione (es. x^2, sin(x))","calculator.differentiate":"Derivare","calculator.integrate":"Integrare","calculator.convert":"Converti","plotter.quickAdd":"Aggiungi un preset rapido...","plotter.noPlots":"Nessun grafico aggiunto","plotter.grid":"Griglia","plotter.axes":"Assi","editor.latexPlaceholder":"Inserisci un’equazione LaTeX...","editor.clear":"Cancella","editor.recognize":"Riconosci","editor.recognizing":"Riconoscimento...","editor.handwritingNote":"Disegna la tua equazione qui sopra. Il riconoscimento della scrittura richiede un’integrazione API esterna."},pt:{"calculator.matrixA":"Matriz A","calculator.matrixB":"Matriz B","calculator.exprPlaceholder":"Introduza uma expressão (p. ex. x^2, sin(x))","calculator.differentiate":"Derivar","calculator.integrate":"Integrar","calculator.convert":"Converter","plotter.quickAdd":"Adicionar predefinição rápida...","plotter.noPlots":"Ainda não foram adicionados gráficos","plotter.grid":"Grelha","plotter.axes":"Eixos","editor.latexPlaceholder":"Introduza uma equação LaTeX...","editor.clear":"Limpar","editor.recognize":"Reconhecer","editor.recognizing":"A reconhecer...","editor.handwritingNote":"Desenhe a sua equação acima. O reconhecimento de escrita requer integração com uma API externa."},cs:{"calculator.matrixA":"Matice A","calculator.matrixB":"Matice B","calculator.exprPlaceholder":"Zadejte výraz (např. x^2, sin(x))","calculator.differentiate":"Derivovat","calculator.integrate":"Integrovat","calculator.convert":"Převést","plotter.quickAdd":"Rychle přidat předvolbu...","plotter.noPlots":"Zatím nebyl přidán žádný graf","plotter.grid":"Mřížka","plotter.axes":"Osy","editor.latexPlaceholder":"Zadejte rovnici v LaTeXu...","editor.clear":"Vymazat","editor.recognize":"Rozpoznat","editor.recognizing":"Rozpoznávání...","editor.handwritingNote":"Nakreslete svou rovnici výše. Rozpoznávání rukopisu vyžaduje externí integraci API."},uk:{"calculator.matrixA":"Матриця A","calculator.matrixB":"Матриця B","calculator.exprPlaceholder":"Введіть вираз (напр. x^2, sin(x))","calculator.differentiate":"Диференціювати","calculator.integrate":"Інтегрувати","calculator.convert":"Перетворити","plotter.quickAdd":"Швидко додати пресет...","plotter.noPlots":"Поки що не додано жодного графіка","plotter.grid":"Сітка","plotter.axes":"Осі","editor.latexPlaceholder":"Введіть рівняння в LaTeX...","editor.clear":"Очистити","editor.recognize":"Розпізнати","editor.recognizing":"Розпізнавання...","editor.handwritingNote":"Намалюйте своє рівняння вище. Розпізнавання рукопису потребує зовнішньої інтеграції з API."}},I18nContext=React.createContext({locale:"en",t:(e,t)=>t??e});function NiceI18nProvider({locale:e="en",overrides:t,children:r}){const a=React.useMemo(()=>{const n={...translations.en,...translations[e],...t};return{locale:e,t:(i,c)=>n[i]??c??i}},[e,t]);return React.createElement(I18nContext.Provider,{value:a},r)}function useNiceTranslation(){return React.useContext(I18nContext)}const MATH_EDITOR_TOUR=[{target:".nice-math-editor",titleKey:"tutorial.mathEditor.intro.title",title:"Math editor",contentKey:"tutorial.mathEditor.intro.content",content:"Write equations as LaTeX or insert symbols from the palette; switch to handwriting input, and preview the rendered formula live.",placement:"auto"}],MATH_SYMBOLS=[{name:"alpha",latex:"\\alpha",category:"greek",preview:"α"},{name:"beta",latex:"\\beta",category:"greek",preview:"β"},{name:"gamma",latex:"\\gamma",category:"greek",preview:"γ"},{name:"delta",latex:"\\delta",category:"greek",preview:"δ"},{name:"epsilon",latex:"\\epsilon",category:"greek",preview:"ε"},{name:"zeta",latex:"\\zeta",category:"greek",preview:"ζ"},{name:"eta",latex:"\\eta",category:"greek",preview:"η"},{name:"theta",latex:"\\theta",category:"greek",preview:"θ"},{name:"iota",latex:"\\iota",category:"greek",preview:"ι"},{name:"kappa",latex:"\\kappa",category:"greek",preview:"κ"},{name:"lambda",latex:"\\lambda",category:"greek",preview:"λ"},{name:"mu",latex:"\\mu",category:"greek",preview:"μ"},{name:"nu",latex:"\\nu",category:"greek",preview:"ν"},{name:"xi",latex:"\\xi",category:"greek",preview:"ξ"},{name:"pi",latex:"\\pi",category:"greek",preview:"π"},{name:"rho",latex:"\\rho",category:"greek",preview:"ρ"},{name:"sigma",latex:"\\sigma",category:"greek",preview:"σ"},{name:"tau",latex:"\\tau",category:"greek",preview:"τ"},{name:"upsilon",latex:"\\upsilon",category:"greek",preview:"υ"},{name:"phi",latex:"\\phi",category:"greek",preview:"φ"},{name:"chi",latex:"\\chi",category:"greek",preview:"χ"},{name:"psi",latex:"\\psi",category:"greek",preview:"ψ"},{name:"omega",latex:"\\omega",category:"greek",preview:"ω"},{name:"Gamma",latex:"\\Gamma",category:"greek",preview:"Γ"},{name:"Delta",latex:"\\Delta",category:"greek",preview:"Δ"},{name:"Theta",latex:"\\Theta",category:"greek",preview:"Θ"},{name:"Lambda",latex:"\\Lambda",category:"greek",preview:"Λ"},{name:"Xi",latex:"\\Xi",category:"greek",preview:"Ξ"},{name:"Pi",latex:"\\Pi",category:"greek",preview:"Π"},{name:"Sigma",latex:"\\Sigma",category:"greek",preview:"Σ"},{name:"Phi",latex:"\\Phi",category:"greek",preview:"Φ"},{name:"Psi",latex:"\\Psi",category:"greek",preview:"Ψ"},{name:"Omega",latex:"\\Omega",category:"greek",preview:"Ω"},{name:"plus/minus",latex:"\\pm",category:"operators",preview:"±"},{name:"minus/plus",latex:"\\mp",category:"operators",preview:"∓"},{name:"times",latex:"\\times",category:"operators",preview:"×"},{name:"divide",latex:"\\div",category:"operators",preview:"÷"},{name:"cdot",latex:"\\cdot",category:"operators",preview:"·"},{name:"star",latex:"\\star",category:"operators",preview:"⋆"},{name:"circle",latex:"\\circ",category:"operators",preview:"∘"},{name:"bullet",latex:"\\bullet",category:"operators",preview:"•"},{name:"oplus",latex:"\\oplus",category:"operators",preview:"⊕"},{name:"otimes",latex:"\\otimes",category:"operators",preview:"⊗"},{name:"odot",latex:"\\odot",category:"operators",preview:"⊙"},{name:"less than",latex:"<",category:"relations",preview:"<"},{name:"greater than",latex:">",category:"relations",preview:">"},{name:"less or equal",latex:"\\leq",category:"relations",preview:"≤"},{name:"greater or equal",latex:"\\geq",category:"relations",preview:"≥"},{name:"not equal",latex:"\\neq",category:"relations",preview:"≠"},{name:"approximately",latex:"\\approx",category:"relations",preview:"≈"},{name:"equivalent",latex:"\\equiv",category:"relations",preview:"≡"},{name:"similar",latex:"\\sim",category:"relations",preview:"∼"},{name:"proportional",latex:"\\propto",category:"relations",preview:"∝"},{name:"perpendicular",latex:"\\perp",category:"relations",preview:"⊥"},{name:"parallel",latex:"\\parallel",category:"relations",preview:"∥"},{name:"right arrow",latex:"\\rightarrow",category:"arrows",preview:"→"},{name:"left arrow",latex:"\\leftarrow",category:"arrows",preview:"←"},{name:"double right",latex:"\\Rightarrow",category:"arrows",preview:"⇒"},{name:"double left",latex:"\\Leftarrow",category:"arrows",preview:"⇐"},{name:"iff",latex:"\\Leftrightarrow",category:"arrows",preview:"⇔"},{name:"up arrow",latex:"\\uparrow",category:"arrows",preview:"↑"},{name:"down arrow",latex:"\\downarrow",category:"arrows",preview:"↓"},{name:"maps to",latex:"\\mapsto",category:"arrows",preview:"↦"},{name:"sine",latex:"\\sin",category:"functions",preview:"sin"},{name:"cosine",latex:"\\cos",category:"functions",preview:"cos"},{name:"tangent",latex:"\\tan",category:"functions",preview:"tan"},{name:"cotangent",latex:"\\cot",category:"functions",preview:"cot"},{name:"arcsine",latex:"\\arcsin",category:"functions",preview:"arcsin"},{name:"arccosine",latex:"\\arccos",category:"functions",preview:"arccos"},{name:"arctangent",latex:"\\arctan",category:"functions",preview:"arctan"},{name:"logarithm",latex:"\\log",category:"functions",preview:"log"},{name:"natural log",latex:"\\ln",category:"functions",preview:"ln"},{name:"exponential",latex:"\\exp",category:"functions",preview:"exp"},{name:"limit",latex:"\\lim",category:"functions",preview:"lim"},{name:"supremum",latex:"\\sup",category:"functions",preview:"sup"},{name:"infimum",latex:"\\inf",category:"functions",preview:"inf"},{name:"maximum",latex:"\\max",category:"functions",preview:"max"},{name:"minimum",latex:"\\min",category:"functions",preview:"min"},{name:"hat",latex:"\\hat{x}",category:"accents",preview:"x̂"},{name:"bar",latex:"\\bar{x}",category:"accents",preview:"x̄"},{name:"vector",latex:"\\vec{x}",category:"accents",preview:"x⃗"},{name:"dot",latex:"\\dot{x}",category:"accents",preview:"ẋ"},{name:"double dot",latex:"\\ddot{x}",category:"accents",preview:"ẍ"},{name:"tilde",latex:"\\tilde{x}",category:"accents",preview:"x̃"},{name:"parentheses",latex:"\\left( \\right)",category:"delimiters",preview:"( )"},{name:"brackets",latex:"\\left[ \\right]",category:"delimiters",preview:"[ ]"},{name:"braces",latex:"\\left\\{ \\right\\}",category:"delimiters",preview:"{ }"},{name:"angle brackets",latex:"\\left\\langle \\right\\rangle",category:"delimiters",preview:"⟨ ⟩"},{name:"ceiling",latex:"\\left\\lceil \\right\\rceil",category:"delimiters",preview:"⌈ ⌉"},{name:"floor",latex:"\\left\\lfloor \\right\\rfloor",category:"delimiters",preview:"⌊ ⌋"},{name:"absolute",latex:"\\left| \\right|",category:"delimiters",preview:"| |"},{name:"norm",latex:"\\left\\| \\right\\|",category:"delimiters",preview:"‖ ‖"},{name:"element of",latex:"\\in",category:"sets",preview:"∈"},{name:"not element",latex:"\\notin",category:"sets",preview:"∉"},{name:"contains",latex:"\\ni",category:"sets",preview:"∋"},{name:"subset",latex:"\\subset",category:"sets",preview:"⊂"},{name:"superset",latex:"\\supset",category:"sets",preview:"⊃"},{name:"subset or equal",latex:"\\subseteq",category:"sets",preview:"⊆"},{name:"union",latex:"\\cup",category:"sets",preview:"∪"},{name:"intersection",latex:"\\cap",category:"sets",preview:"∩"},{name:"set minus",latex:"\\setminus",category:"sets",preview:"∖"},{name:"empty set",latex:"\\emptyset",category:"sets",preview:"∅"},{name:"naturals",latex:"\\mathbb{N}",category:"sets",preview:"ℕ"},{name:"integers",latex:"\\mathbb{Z}",category:"sets",preview:"ℤ"},{name:"rationals",latex:"\\mathbb{Q}",category:"sets",preview:"ℚ"},{name:"reals",latex:"\\mathbb{R}",category:"sets",preview:"ℝ"},{name:"complex",latex:"\\mathbb{C}",category:"sets",preview:"ℂ"},{name:"for all",latex:"\\forall",category:"logic",preview:"∀"},{name:"exists",latex:"\\exists",category:"logic",preview:"∃"},{name:"not exists",latex:"\\nexists",category:"logic",preview:"∄"},{name:"and",latex:"\\land",category:"logic",preview:"∧"},{name:"or",latex:"\\lor",category:"logic",preview:"∨"},{name:"not",latex:"\\neg",category:"logic",preview:"¬"},{name:"therefore",latex:"\\therefore",category:"logic",preview:"∴"},{name:"because",latex:"\\because",category:"logic",preview:"∵"},{name:"integral",latex:"\\int",category:"calculus",preview:"∫"},{name:"double integral",latex:"\\iint",category:"calculus",preview:"∬"},{name:"triple integral",latex:"\\iiint",category:"calculus",preview:"∭"},{name:"contour integral",latex:"\\oint",category:"calculus",preview:"∮"},{name:"partial",latex:"\\partial",category:"calculus",preview:"∂"},{name:"nabla/gradient",latex:"\\nabla",category:"calculus",preview:"∇"},{name:"summation",latex:"\\sum",category:"calculus",preview:"Σ"},{name:"product",latex:"\\prod",category:"calculus",preview:"Π"},{name:"infinity",latex:"\\infty",category:"calculus",preview:"∞"},{name:"matrix",latex:"\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}",category:"matrices",preview:"[ ]"},{name:"determinant",latex:"\\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix}",category:"matrices",preview:"| |"},{name:"bracket matrix",latex:"\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}",category:"matrices",preview:"[[ ]]"},{name:"cases",latex:"\\begin{cases} a & \\text{if } x > 0 \\\\ b & \\text{otherwise} \\end{cases}",category:"matrices",preview:"{ }"}];function getSymbolsByCategory(e){return MATH_SYMBOLS.filter(t=>t.category===e)}const EQUATION_TEMPLATES=[{name:"Fraction",latex:"\\frac{a}{b}",category:"basic"},{name:"Square root",latex:"\\sqrt{x}",category:"basic"},{name:"Nth root",latex:"\\sqrt[n]{x}",category:"basic"},{name:"Power",latex:"x^{n}",category:"basic"},{name:"Subscript",latex:"x_{n}",category:"basic"},{name:"Both",latex:"x_{i}^{n}",category:"basic"},{name:"Derivative",latex:"\\frac{d}{dx}f(x)",category:"calculus"},{name:"Partial derivative",latex:"\\frac{\\partial f}{\\partial x}",category:"calculus"},{name:"Definite integral",latex:"\\int_{a}^{b} f(x)\\,dx",category:"calculus"},{name:"Indefinite integral",latex:"\\int f(x)\\,dx",category:"calculus"},{name:"Limit",latex:"\\lim_{x \\to a} f(x)",category:"calculus"},{name:"Summation",latex:"\\sum_{i=1}^{n} a_i",category:"calculus"},{name:"Product",latex:"\\prod_{i=1}^{n} a_i",category:"calculus"},{name:"Quadratic formula",latex:"x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}",category:"algebra"},{name:"Binomial",latex:"\\binom{n}{k} = \\frac{n!}{k!(n-k)!}",category:"algebra"},{name:"System of equations",latex:"\\begin{cases} ax + by = c \\\\ dx + ey = f \\end{cases}",category:"algebra"},{name:"Pythagorean",latex:"a^2 + b^2 = c^2",category:"geometry"},{name:"Circle area",latex:"A = \\pi r^2",category:"geometry"},{name:"Sphere volume",latex:"V = \\frac{4}{3}\\pi r^3",category:"geometry"},{name:"Euler's identity",latex:"e^{i\\pi} + 1 = 0",category:"geometry"},{name:"Mean",latex:"\\bar{x} = \\frac{1}{n}\\sum_{i=1}^{n} x_i",category:"statistics"},{name:"Variance",latex:"\\sigma^2 = \\frac{1}{n}\\sum_{i=1}^{n}(x_i - \\bar{x})^2",category:"statistics"},{name:"Normal distribution",latex:"f(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}}e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}",category:"statistics"},{name:"Einstein mass-energy",latex:"E = mc^2",category:"physics"},{name:"Newton's second law",latex:"F = ma",category:"physics"},{name:"Schrödinger equation",latex:"i\\hbar\\frac{\\partial}{\\partial t}\\Psi = \\hat{H}\\Psi",category:"physics"},{name:"Maxwell's equations",latex:"\\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\epsilon_0}",category:"physics"}];class MathEditorService{constructor(t={}){C(this,"equations",new Map);C(this,"config");C(this,"nextNumber");this.config={enableNumbering:t.enableNumbering??!0,startNumber:t.startNumber??1,renderDelay:t.renderDelay??100},this.nextNumber=this.config.startNumber}createEquation(t,r){const a={id:this.generateId(),latex:t,label:r,number:this.config.enableNumbering?this.nextNumber++:void 0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.equations.set(a.id,a),a}updateEquation(t,r,a){const n=this.equations.get(t);if(!n)throw new Error(`Equation not found: ${t}`);const o={...n,latex:r,label:a??n.label,updatedAt:new Date().toISOString()};return this.equations.set(t,o),o}deleteEquation(t){this.equations.delete(t)}getEquation(t){return this.equations.get(t)}listEquations(){return Array.from(this.equations.values()).sort((t,r)=>new Date(t.createdAt).getTime()-new Date(r.createdAt).getTime())}exportToLatex(){const t=["\\documentclass{article}","\\usepackage{amsmath}","\\usepackage{amssymb}","","\\begin{document}",""];for(const r of this.listEquations())r.number!==void 0?(t.push("\\begin{equation}"),r.label&&t.push(`\\label{${r.label}}`),t.push(r.latex),t.push("\\end{equation}")):(t.push("\\["),t.push(r.latex),t.push("\\]")),t.push("");return t.push("\\end{document}"),t.join(`
2
+ `)}parseLatex(t){const r=[],a=/\\\[([\s\S]*?)\\\]/g;let n;for(;(n=a.exec(t))!==null;)r.push(this.createEquation(n[1].trim()));const o=/\\begin\{equation\}([\s\S]*?)\\end\{equation\}/g;for(;(n=o.exec(t))!==null;){const i=n[1].match(/\\label\{([^}]+)\}/),c=n[1].replace(/\\label\{[^}]+\}/,"").trim();r.push(this.createEquation(c,i==null?void 0:i[1]))}return r}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function createMathEditorService(e){return new MathEditorService(e)}async function recognizeHandwriting(e){return await new Promise(r=>setTimeout(r,500)),{latex:e.reduce((r,a)=>r+a.points.length,0)>50?"\\sqrt{x^2 + y^2}":"x",confidence:.85,alternatives:["x","X","\\times"]}}const MathEditorContext=React.createContext(null);function useMathEditor(){const e=React.useContext(MathEditorContext);if(!e)throw new Error("useMathEditor must be used within MathEditorProvider");return e}const styles$3={toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid var(--nice-border, #e0e0e0)",backgroundColor:"var(--nice-bg-secondary, #fafafa)",flexWrap:"wrap",alignItems:"center"},sidebar:{width:"200px",borderRight:"1px solid var(--nice-border, #e0e0e0)",overflow:"auto",backgroundColor:"var(--nice-bg-secondary, #f5f5f5)"},editor:{flex:1,display:"flex",flexDirection:"column",padding:"16px",overflow:"auto"},input:{width:"100%",minHeight:"100px",padding:"12px",fontFamily:"'JetBrains Mono', monospace",fontSize:"14px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",resize:"vertical"},preview:{marginTop:"16px",padding:"20px",backgroundColor:"var(--nice-bg, #fff)",border:"1px solid var(--nice-border, #e0e0e0)",borderRadius:"4px",minHeight:"60px",fontSize:"20px",textAlign:"center"},button:{padding:"6px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"13px"},symbolGrid:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:"4px",padding:"8px"},symbolButton:{padding:"8px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:"var(--nice-bg, #fff)",cursor:"pointer",fontSize:"16px",textAlign:"center"},categoryHeader:{padding:"8px 12px",backgroundColor:"var(--nice-border, #e0e0e0)",fontWeight:600,fontSize:"12px",textTransform:"uppercase"},canvas:{width:"100%",height:"200px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:"var(--nice-bg, #fff)",cursor:"crosshair"}};function NiceMathEditor({service:e,initialLatex:t="",onChange:r,className:a,style:n,tutorial:o}){const{t:i}=useNiceTranslation(),[c,x]=React.useState(t),[s,u]=React.useState("input"),m=React.useRef(null),g=React.useCallback(f=>{x(f),r==null||r(f)},[r]),h=React.useCallback(f=>{const l=m.current;if(!l){g(c+f);return}const p=l.selectionStart,b=l.selectionEnd,R=c.slice(0,p)+f+c.slice(b);g(R),setTimeout(()=>{l.focus(),l.selectionStart=l.selectionEnd=p+f.length},0)},[c,g]),w=React.useCallback(f=>{h(f.latex)},[h]),d={service:e,latex:c,setLatex:g,insertSymbol:h,insertTemplate:w,mode:s,setMode:u};return jsxRuntime.jsx(MathEditorContext.Provider,{value:d,children:jsxRuntime.jsxs(ui.NiceAppShell,{flush:!0,className:`nice-math-editor ${a??""}`,style:{position:"relative",...n},toolbar:jsxRuntime.jsx(Toolbar$1,{}),sidebar:jsxRuntime.jsx(SymbolPalette,{}),children:[jsxRuntime.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:jsxRuntime.jsx(uiCore.NiceTutorialButton,{steps:uiCore.resolveTutorial(o,MATH_EDITOR_TOUR)})}),jsxRuntime.jsx("div",{style:styles$3.editor,children:s==="input"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("textarea",{ref:m,value:c,onChange:f=>g(f.target.value),placeholder:i("editor.latexPlaceholder","Enter LaTeX equation..."),style:styles$3.input}),jsxRuntime.jsx(LatexPreview,{latex:c})]}):jsxRuntime.jsx(HandwritingCanvas,{})})]})})}function Toolbar$1(){const{mode:e,setMode:t,latex:r,insertTemplate:a}=useMathEditor(),[n,o]=React.useState(!1);return jsxRuntime.jsxs("div",{style:styles$3.toolbar,children:[jsxRuntime.jsxs("button",{onClick:()=>t("input"),style:{...styles$3.button,backgroundColor:e==="input"?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg-tertiary, #9e9e9e)",color:e==="input"?"var(--nice-text-on-primary, #fff)":"var(--nice-text-primary, #fff)"},children:[jsxRuntime.jsx(ui.NiceIcon,{name:"keyboard",size:14})," LaTeX Input"]}),jsxRuntime.jsxs("button",{onClick:()=>t("handwriting"),style:{...styles$3.button,backgroundColor:e==="handwriting"?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg-tertiary, #9e9e9e)",color:e==="handwriting"?"var(--nice-text-on-primary, #fff)":"var(--nice-text-primary, #fff)"},children:[jsxRuntime.jsx(ui.NiceIcon,{name:"pen",size:14})," Handwriting"]}),jsxRuntime.jsx("div",{style:{borderLeft:"1px solid var(--nice-border, #ccc)",height:"24px",margin:"0 8px"}}),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsxs("button",{onClick:()=>o(!n),style:styles$3.button,children:[jsxRuntime.jsx(ui.NiceIcon,{name:"ruler",size:14})," Templates ",jsxRuntime.jsx(ui.NiceIcon,{name:"chevron-down",size:12})]}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"100%",left:0,backgroundColor:"var(--nice-bg, #fff)",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",boxShadow:"0 2px 8px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",zIndex:100,width:"300px",maxHeight:"400px",overflow:"auto"},children:["basic","calculus","algebra","geometry","statistics","physics"].map(i=>jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:styles$3.categoryHeader,children:i}),EQUATION_TEMPLATES.filter(c=>c.category===i).map(c=>jsxRuntime.jsxs("div",{onClick:()=>{a(c),o(!1)},style:{padding:"8px 12px",cursor:"pointer",borderBottom:"1px solid var(--nice-border, #eee)"},onMouseOver:x=>x.target.style.backgroundColor="var(--nice-bg-secondary, #f5f5f5)",onMouseOut:x=>x.target.style.backgroundColor="transparent",children:[jsxRuntime.jsx("div",{style:{fontWeight:500},children:c.name}),jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:[c.latex.substring(0,40),c.latex.length>40?"...":""]})]},c.name))]},i))})]}),jsxRuntime.jsx("div",{style:{flex:1}}),jsxRuntime.jsxs("button",{onClick:()=>navigator.clipboard.writeText(r),style:{...styles$3.button,backgroundColor:"var(--nice-success, #4caf50)"},children:[jsxRuntime.jsx(ui.NiceIcon,{name:"copy",size:14})," Copy LaTeX"]})]})}function SymbolPalette(){const{insertSymbol:e}=useMathEditor(),[t,r]=React.useState("greek"),a=["greek","operators","relations","arrows","functions","accents","delimiters","sets","logic","calculus","matrices"],n=getSymbolsByCategory(t);return jsxRuntime.jsxs("div",{style:styles$3.sidebar,children:[jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",padding:"8px",gap:"4px"},children:a.map(o=>jsxRuntime.jsx("button",{onClick:()=>r(o),style:{padding:"4px 8px",fontSize:"11px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:t===o?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg, #fff)",color:t===o?"var(--nice-text-on-primary, #fff)":"var(--nice-text, #333)",cursor:"pointer"},children:o},o))}),jsxRuntime.jsx("div",{style:styles$3.symbolGrid,children:n.map(o=>jsxRuntime.jsx("button",{onClick:()=>e(o.latex),style:styles$3.symbolButton,title:`${o.name}: ${o.latex}`,children:o.preview||o.latex},o.name))})]})}function LatexPreview({latex:e}){return jsxRuntime.jsxs("div",{style:styles$3.preview,children:[jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginBottom:"8px"},children:"Preview (requires KaTeX/MathJax integration):"}),jsxRuntime.jsx("code",{style:{fontSize:"16px"},children:e||"(empty)"})]})}function HandwritingCanvas(){const{t:e}=useNiceTranslation(),{setLatex:t,setMode:r}=useMathEditor(),a=React.useRef(null),[n,o]=React.useState([]),[i,c]=React.useState([]),[x,s]=React.useState(!1),[u,m]=React.useState(!1),g=l=>{const p=a.current;if(!p)return;s(!0);const b=p.getBoundingClientRect();c([{x:l.clientX-b.left,y:l.clientY-b.top,pressure:l.pressure,timestamp:Date.now()}])},h=l=>{if(!x)return;const p=a.current,b=p==null?void 0:p.getContext("2d");if(!p||!b)return;const R=p.getBoundingClientRect(),y={x:l.clientX-R.left,y:l.clientY-R.top,pressure:l.pressure,timestamp:Date.now()};if(c(v=>[...v,y]),i.length>0){const v=i[i.length-1];b.beginPath(),b.moveTo(v.x,v.y),b.lineTo(y.x,y.y),b.strokeStyle=uiCore.resolveCssColor("var(--nice-text, #000)",b.canvas),b.lineWidth=2,b.lineCap="round",b.stroke()}},w=()=>{if(x){if(s(!1),i.length>1){const l={id:Date.now().toString(),points:[...i]};o(p=>[...p,l])}c([])}},d=()=>{const l=a.current,p=l==null?void 0:l.getContext("2d");p&&l&&p.clearRect(0,0,l.width,l.height),o([])},f=async()=>{if(n.length!==0){m(!0);try{const l=await recognizeHandwriting(n);t(l.latex),r("input")}finally{m(!1)}}};return React.useEffect(()=>{const l=a.current;l&&(l.width=l.offsetWidth,l.height=200)},[]),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("canvas",{ref:a,style:styles$3.canvas,onPointerDown:g,onPointerMove:h,onPointerUp:w,onPointerLeave:w}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",marginTop:"12px"},children:[jsxRuntime.jsx("button",{onClick:d,style:{...styles$3.button,backgroundColor:"var(--nice-danger, #f44336)"},children:e("editor.clear","Clear")}),jsxRuntime.jsx("button",{onClick:f,disabled:n.length===0||u,style:styles$3.button,children:u?e("editor.recognizing","Recognizing..."):e("editor.recognize","Recognize")})]}),jsxRuntime.jsx("p",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginTop:"8px"},children:e("editor.handwritingNote","Draw your equation above. Handwriting recognition requires external API integration.")})]})}const mathConstants={pi:Math.PI,PI:Math.PI,e:Math.E,E:Math.E,phi:(1+Math.sqrt(5))/2,tau:Math.PI*2},mathFunctions={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,sqrt:Math.sqrt,cbrt:Math.cbrt,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,exp:Math.exp,log:Math.log,log10:Math.log10,log2:Math.log2,pow:Math.pow,min:Math.min,max:Math.max,sign:Math.sign,hypot:Math.hypot,sec:e=>1/Math.cos(e),csc:e=>1/Math.sin(e),cot:e=>1/Math.tan(e),ln:Math.log};class ExpressionParser{constructor(){C(this,"pos",0);C(this,"expr","")}parse(t){this.expr=t.replace(/\s+/g,""),this.pos=0;const r=this.parseAddSub();return a=>this.evaluate(r,{...mathConstants,...a})}parseAddSub(){let t=this.parseMulDiv();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="+"&&r!=="-")break;this.pos++;const a=this.parseMulDiv();t={type:"binary",op:r,left:t,right:a}}return t}parseMulDiv(){let t=this.parsePower();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="*"&&r!=="/")break;this.pos++;const a=this.parsePower();t={type:"binary",op:r,left:t,right:a}}return t}parsePower(){let t=this.parseUnary();for(;this.pos<this.expr.length&&this.expr[this.pos]==="^";){this.pos++;const r=this.parseUnary();t={type:"binary",op:"^",left:t,right:r}}return t}parseUnary(){return this.expr[this.pos]==="-"?(this.pos++,{type:"unary",op:"-",arg:this.parseUnary()}):(this.expr[this.pos]==="+"&&this.pos++,this.parsePrimary())}parsePrimary(){if(this.expr[this.pos]==="("){this.pos++;const a=this.parseAddSub();return this.expr[this.pos]===")"&&this.pos++,a}const t=this.expr.slice(this.pos).match(/^(\d+\.?\d*)/);if(t)return this.pos+=t[1].length,{type:"number",value:parseFloat(t[1])};const r=this.expr.slice(this.pos).match(/^([a-zA-Z_][a-zA-Z0-9_]*)/);if(r){const a=r[1];if(this.pos+=a.length,this.expr[this.pos]==="("){this.pos++;const n=[];for(;this.expr[this.pos]!==")"&&this.pos<this.expr.length;)n.push(this.parseAddSub()),this.expr[this.pos]===","&&this.pos++;return this.expr[this.pos]===")"&&this.pos++,{type:"call",name:a,args:n}}return{type:"variable",name:a}}return{type:"number",value:0}}evaluate(t,r){switch(t.type){case"number":return t.value;case"variable":if(t.name in r)return r[t.name];throw new Error(`Unknown variable: ${t.name}`);case"unary":return t.op==="-"?-this.evaluate(t.arg,r):this.evaluate(t.arg,r);case"binary":{const a=this.evaluate(t.left,r),n=this.evaluate(t.right,r);switch(t.op){case"+":return a+n;case"-":return a-n;case"*":return a*n;case"/":return a/n;case"^":return Math.pow(a,n);default:return 0}}case"call":{const a=mathFunctions[t.name];if(!a)throw new Error(`Unknown function: ${t.name}`);const n=t.args.map(o=>this.evaluate(o,r));return a(...n)}default:return 0}}}class GraphService{constructor(t={}){C(this,"plots",new Map);C(this,"parser",new ExpressionParser);C(this,"config");this.config={defaultResolution:t.defaultResolution??200,maxResolution:t.maxResolution??1e3}}addPlot(t){const r={id:this.generateId(),type:t.type,expression:t.expression,expressionY:t.expressionY,expressionZ:t.expressionZ,label:t.label,color:t.color??{r:66,g:133,b:244},lineWidth:t.lineWidth??2,visible:t.visible??!0,parameterRange:t.parameterRange??{min:-Math.PI,max:Math.PI},parameterRange2:t.parameterRange2??{min:-Math.PI,max:Math.PI},resolution:t.resolution??this.config.defaultResolution};return this.plots.set(r.id,r),r}updatePlot(t,r){const a=this.plots.get(t);if(!a)throw new Error(`Plot not found: ${t}`);const n={...a,...r,id:a.id};return this.plots.set(t,n),n}removePlot(t){this.plots.delete(t)}getPlots(){return Array.from(this.plots.values())}getPlot(t){return this.plots.get(t)}compute2DFunction(t,r,a,n){const o=this.parser.parse(t),i=[],c=(r.max-r.min)/a;for(let x=0;x<=a;x++){const s=r.min+x*c;try{const u=o({x:s,...n});Number.isFinite(u)&&i.push({x:s,y:u})}catch{}}return i}compute2DParametric(t,r,a,n,o){const i=this.parser.parse(t),c=this.parser.parse(r),x=[],s=(a.max-a.min)/n;for(let u=0;u<=n;u++){const m=a.min+u*s;try{const g=i({t:m,...o}),h=c({t:m,...o});Number.isFinite(g)&&Number.isFinite(h)&&x.push({x:g,y:h})}catch{}}return x}compute2DPolar(t,r,a,n){const o=this.parser.parse(t),i=[],c=(r.max-r.min)/a;for(let x=0;x<=a;x++){const s=r.min+x*c;try{const u=o({theta:s,t:s,...n});if(Number.isFinite(u)){const m=u*Math.cos(s),g=u*Math.sin(s);i.push({x:m,y:g})}}catch{}}return i}compute3DSurface(t,r,a,n,o){const i=this.parser.parse(t),c=[],x=(r.max-r.min)/n,s=(a.max-a.min)/n;for(let u=0;u<=n;u++){const m=[],g=r.min+u*x;for(let h=0;h<=n;h++){const w=a.min+h*s;try{const d=i({x:g,y:w,...o});Number.isFinite(d)?m.push({x:g,y:w,z:d}):m.push({x:g,y:w,z:0})}catch{m.push({x:g,y:w,z:0})}}c.push(m)}return c}exportSVG(t,r,a,n){const i=a-80,c=n-80,x=m=>40+(m-r.xRange.min)/(r.xRange.max-r.xRange.min)*i,s=m=>n-40-(m-r.yRange.min)/(r.yRange.max-r.yRange.min)*c,u=[`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${n}">`,`<rect width="100%" height="100%" fill="rgb(${r.backgroundColor.r},${r.backgroundColor.g},${r.backgroundColor.b})"/>`];if(r.showGrid){u.push('<g stroke="var(--nice-border, #ddd)" stroke-width="0.5">');for(let m=Math.ceil(r.xRange.min);m<=r.xRange.max;m++){const g=x(m);u.push(`<line x1="${g}" y1="40" x2="${g}" y2="${n-40}"/>`)}for(let m=Math.ceil(r.yRange.min);m<=r.yRange.max;m++){const g=s(m);u.push(`<line x1="40" y1="${g}" x2="${a-40}" y2="${g}"/>`)}u.push("</g>")}if(r.showAxes){u.push('<g stroke="var(--nice-text, #333)" stroke-width="1">');const m=s(0),g=x(0);u.push(`<line x1="40" y1="${m}" x2="${a-40}" y2="${m}"/>`),u.push(`<line x1="${g}" y1="40" x2="${g}" y2="${n-40}"/>`),u.push("</g>")}for(const m of t.filter(g=>g.visible))if(m.type==="2d-function"){const g=this.compute2DFunction(m.expression,r.xRange,m.resolution||200);if(g.length>0){const h=g.map((w,d)=>`${d===0?"M":"L"}${x(w.x)},${s(w.y)}`).join(" ");u.push(`<path d="${h}" fill="none" stroke="rgb(${m.color.r},${m.color.g},${m.color.b})" stroke-width="${m.lineWidth}"/>`)}}return r.showLabels&&(u.push(`<text x="${a/2}" y="${n-10}" text-anchor="middle" font-size="12">x</text>`),u.push(`<text x="10" y="${n/2}" text-anchor="middle" font-size="12" transform="rotate(-90,10,${n/2})">y</text>`)),u.push("</svg>"),u.join(`
3
+ `)}async exportPNG(t,r,a,n){const o=this.exportSVG(t,r,a,n);return new Promise((i,c)=>{const x=new Image;x.onload=()=>{const s=document.createElement("canvas");s.width=a,s.height=n;const u=s.getContext("2d");if(!u){c(new Error("Could not get canvas context"));return}u.drawImage(x,0,0),i(s.toDataURL("image/png"))},x.onerror=c,x.src="data:image/svg+xml;base64,"+btoa(o)})}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function createGraphService(e){return new GraphService(e)}const FUNCTION_PRESETS=[{name:"Linear",expression:"x",type:"2d-function",category:"basic"},{name:"Quadratic",expression:"x^2",type:"2d-function",category:"basic"},{name:"Cubic",expression:"x^3",type:"2d-function",category:"basic"},{name:"Square root",expression:"sqrt(x)",type:"2d-function",category:"basic"},{name:"Absolute",expression:"abs(x)",type:"2d-function",category:"basic"},{name:"Reciprocal",expression:"1/x",type:"2d-function",category:"basic"},{name:"Sine",expression:"sin(x)",type:"2d-function",category:"trigonometric"},{name:"Cosine",expression:"cos(x)",type:"2d-function",category:"trigonometric"},{name:"Tangent",expression:"tan(x)",type:"2d-function",category:"trigonometric"},{name:"Sine wave",expression:"sin(2*x)",type:"2d-function",category:"trigonometric"},{name:"Damped oscillation",expression:"exp(-x/5)*sin(x*3)",type:"2d-function",category:"trigonometric"},{name:"Exponential",expression:"exp(x)",type:"2d-function",category:"exponential"},{name:"Natural log",expression:"ln(x)",type:"2d-function",category:"exponential"},{name:"Gaussian",expression:"exp(-x^2)",type:"2d-function",category:"exponential"},{name:"Sigmoid",expression:"1/(1+exp(-x))",type:"2d-function",category:"exponential"},{name:"Circle",expression:"cos(t)",expressionY:"sin(t)",type:"2d-parametric",category:"parametric"},{name:"Ellipse",expression:"2*cos(t)",expressionY:"sin(t)",type:"2d-parametric",category:"parametric"},{name:"Lissajous",expression:"sin(3*t)",expressionY:"sin(2*t)",type:"2d-parametric",category:"parametric"},{name:"Spiral",expression:"t*cos(t)",expressionY:"t*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Cardioid",expression:"(1-cos(t))*cos(t)",expressionY:"(1-cos(t))*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Rose curve",expression:"cos(3*t)*cos(t)",expressionY:"cos(3*t)*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Polar rose 3",expression:"cos(3*theta)",type:"2d-polar",category:"polar"},{name:"Polar rose 5",expression:"cos(5*theta)",type:"2d-polar",category:"polar"},{name:"Archimedean spiral",expression:"theta",type:"2d-polar",category:"polar"},{name:"Logarithmic spiral",expression:"exp(theta/10)",type:"2d-polar",category:"polar"},{name:"Paraboloid",expression:"x^2 + y^2",type:"3d-surface",category:"3d"},{name:"Saddle",expression:"x^2 - y^2",type:"3d-surface",category:"3d"},{name:"Ripple",expression:"sin(sqrt(x^2 + y^2))",type:"3d-surface",category:"3d"},{name:"Torus slice",expression:"cos(x)*sin(y)",type:"3d-surface",category:"3d"},{name:"Peaks",expression:"3*(1-x)^2*exp(-x^2-(y+1)^2) - 10*(x/5-x^3-y^5)*exp(-x^2-y^2) - 1/3*exp(-(x+1)^2-y^2)",type:"3d-surface",category:"3d"}],GraphContext=React.createContext(null);function useGraph(){const e=React.useContext(GraphContext);if(!e)throw new Error("useGraph must be used within GraphProvider");return e}const styles$2={container:{display:"flex",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},sidebar:{width:"280px",borderRight:"1px solid var(--nice-border, #e0e0e0)",display:"flex",flexDirection:"column",overflow:"hidden"},plotList:{flex:1,overflow:"auto",padding:"8px"},main:{flex:1,display:"flex",flexDirection:"column",backgroundColor:"var(--nice-bg, #fff)"},canvas:{flex:1,backgroundColor:"var(--nice-bg, #fff)"},toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid var(--nice-border, #e0e0e0)",alignItems:"center"},button:{padding:"6px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"13px"},input:{padding:"6px 8px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",fontSize:"13px"},plotItem:{padding:"8px",marginBottom:"8px",border:"1px solid var(--nice-border, #e0e0e0)",borderRadius:"4px",backgroundColor:"var(--nice-bg-secondary, #fafafa)"}};function NiceGraphPlotter({service:e,width:t=800,height:r=600,className:a,style:n}){const[o,i]=React.useState([]),[c,x]=React.useState({xRange:{min:-10,max:10},yRange:{min:-10,max:10},zRange:{min:-5,max:5},showGrid:!0,showAxes:!0,showLabels:!0,backgroundColor:{r:255,g:255,b:255},cameraRotationX:30,cameraRotationY:45,cameraDistance:5}),[s,u]=React.useState({isPlaying:!1,parameter:"a",currentValue:0,minValue:-5,maxValue:5,speed:1}),m=React.useCallback(()=>{i(e.getPlots())},[e]),g=React.useCallback(p=>{x(b=>({...b,...p}))},[]),h=React.useCallback(p=>{u(b=>({...b,...p}))},[]),w=React.useCallback(p=>{e.addPlot(p),m()},[e,m]),d=React.useCallback(p=>{e.removePlot(p),m()},[e,m]),f=React.useCallback((p,b)=>{e.updatePlot(p,b),m()},[e,m]),l={service:e,plots:o,view:c,setView:g,addPlot:w,removePlot:d,updatePlot:f,animation:s,setAnimation:h,refresh:m};return jsxRuntime.jsx(GraphContext.Provider,{value:l,children:jsxRuntime.jsxs("div",{className:a,style:{...styles$2.container,...n},children:[jsxRuntime.jsxs("div",{style:styles$2.sidebar,children:[jsxRuntime.jsx(PlotControls,{}),jsxRuntime.jsx(PlotList,{})]}),jsxRuntime.jsxs("div",{style:styles$2.main,children:[jsxRuntime.jsx(GraphToolbar,{width:t,height:r}),jsxRuntime.jsx(Canvas2D,{width:t,height:r})]})]})})}function PlotControls(){const{t:e}=useNiceTranslation(),{addPlot:t}=useGraph(),[r,a]=React.useState("sin(x)"),[n,o]=React.useState("2d-function"),[i,c]=React.useState("cos(x)"),x=()=>{t({type:n,expression:r,expressionY:n==="2d-parametric"?i:void 0,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})};return jsxRuntime.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid var(--nice-border, #e0e0e0)"},children:[jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsxs("select",{value:n,onChange:s=>o(s.target.value),style:{...styles$2.input,width:"100%"},children:[jsxRuntime.jsx("option",{value:"2d-function",children:"y = f(x)"}),jsxRuntime.jsx("option",{value:"2d-parametric",children:"Parametric (x(t), y(t))"}),jsxRuntime.jsx("option",{value:"2d-polar",children:"Polar r = f(θ)"}),jsxRuntime.jsx("option",{value:"3d-surface",children:"3D Surface z = f(x,y)"})]})}),jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsx("input",{type:"text",value:r,onChange:s=>a(s.target.value),placeholder:n==="2d-parametric"?"x(t) = ...":"Expression...",style:{...styles$2.input,width:"100%"}})}),n==="2d-parametric"&&jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsx("input",{type:"text",value:i,onChange:s=>c(s.target.value),placeholder:"y(t) = ...",style:{...styles$2.input,width:"100%"}})}),jsxRuntime.jsx("button",{onClick:x,style:{...styles$2.button,width:"100%"},children:"+ Add Plot"}),jsxRuntime.jsxs("select",{onChange:s=>{const u=FUNCTION_PRESETS.find(m=>m.name===s.target.value);u&&t({type:u.type,expression:u.expression,expressionY:u.expressionY,label:u.name,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})},style:{...styles$2.input,width:"100%",marginTop:"8px"},value:"",children:[jsxRuntime.jsx("option",{value:"",disabled:!0,children:e("plotter.quickAdd","Quick add preset...")}),["basic","trigonometric","exponential","parametric","polar","3d"].map(s=>jsxRuntime.jsx("optgroup",{label:s.charAt(0).toUpperCase()+s.slice(1),children:FUNCTION_PRESETS.filter(u=>u.category===s).map(u=>jsxRuntime.jsxs("option",{value:u.name,children:[u.name,": ",u.expression]},u.name))},s))]})]})}function PlotList(){const{t:e}=useNiceTranslation(),{plots:t,removePlot:r,updatePlot:a}=useGraph();return jsxRuntime.jsxs("div",{style:styles$2.plotList,children:[t.length===0&&jsxRuntime.jsx("div",{style:{color:"var(--nice-text-secondary, #666)",textAlign:"center",padding:"16px"},children:e("plotter.noPlots","No plots added yet")}),t.map(n=>jsxRuntime.jsxs("div",{style:styles$2.plotItem,children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:n.visible,onChange:o=>a(n.id,{visible:o.target.checked})}),jsxRuntime.jsx("div",{style:{width:"16px",height:"16px",borderRadius:"3px",backgroundColor:`rgb(${n.color.r},${n.color.g},${n.color.b})`}}),jsxRuntime.jsx("span",{style:{flex:1,fontWeight:500},children:n.label||n.expression}),jsxRuntime.jsx("button",{onClick:()=>r(n.id),style:{padding:"2px 6px",backgroundColor:"var(--nice-danger, #f44336)",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"12px"},children:"×"})]}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:n.type==="2d-parametric"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["x(t) = ",n.expression,jsxRuntime.jsx("br",{}),"y(t) = ",n.expressionY]}):n.expression})]},n.id))]})}function GraphToolbar({width:e,height:t}){const{t:r}=useNiceTranslation(),{service:a,plots:n,view:o,setView:i}=useGraph(),c=()=>{const s=a.exportSVG(n,o,e,t),u=new Blob([s],{type:"image/svg+xml"}),m=URL.createObjectURL(u),g=document.createElement("a");g.href=m,g.download="graph.svg",g.click(),URL.revokeObjectURL(m)},x=async()=>{const s=await a.exportPNG(n,o,e,t),u=document.createElement("a");u.href=s,u.download="graph.png",u.click()};return jsxRuntime.jsxs("div",{style:styles$2.toolbar,children:[jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:["X: ["," ",jsxRuntime.jsx("input",{type:"number",value:o.xRange.min,onChange:s=>i({xRange:{...o.xRange,min:Number(s.target.value)}}),style:{...styles$2.input,width:"50px"}}),","," ",jsxRuntime.jsx("input",{type:"number",value:o.xRange.max,onChange:s=>i({xRange:{...o.xRange,max:Number(s.target.value)}}),style:{...styles$2.input,width:"50px"}}),"]"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:["Y: ["," ",jsxRuntime.jsx("input",{type:"number",value:o.yRange.min,onChange:s=>i({yRange:{...o.yRange,min:Number(s.target.value)}}),style:{...styles$2.input,width:"50px"}}),","," ",jsxRuntime.jsx("input",{type:"number",value:o.yRange.max,onChange:s=>i({yRange:{...o.yRange,max:Number(s.target.value)}}),style:{...styles$2.input,width:"50px"}}),"]"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:o.showGrid,onChange:s=>i({showGrid:s.target.checked})}),r("plotter.grid","Grid")]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:o.showAxes,onChange:s=>i({showAxes:s.target.checked})}),r("plotter.axes","Axes")]}),jsxRuntime.jsx("div",{style:{flex:1}}),jsxRuntime.jsxs("button",{onClick:c,style:{...styles$2.button,backgroundColor:"var(--nice-success, #4caf50)"},children:[jsxRuntime.jsx(uiCore.NiceIcon,{name:"download",size:14})," SVG"]}),jsxRuntime.jsxs("button",{onClick:x,style:{...styles$2.button,backgroundColor:"var(--nice-warning, #ff9800)"},children:[jsxRuntime.jsx(uiCore.NiceIcon,{name:"download",size:14})," PNG"]})]})}function Canvas2D({width:e,height:t}){const r=React.useRef(null),{service:a,plots:n,view:o,animation:i}=useGraph(),c=40;return React.useEffect(()=>{const x=r.current,s=x==null?void 0:x.getContext("2d");if(!x||!s)return;s.fillStyle=`rgb(${o.backgroundColor.r},${o.backgroundColor.g},${o.backgroundColor.b})`,s.fillRect(0,0,e,t);const u=e-c*2,m=t-c*2,g=d=>c+(d-o.xRange.min)/(o.xRange.max-o.xRange.min)*u,h=d=>t-c-(d-o.yRange.min)/(o.yRange.max-o.yRange.min)*m;if(o.showGrid){s.strokeStyle=uiCore.resolveCssColor("var(--nice-border, #e0e0e0)",s.canvas),s.lineWidth=.5;for(let d=Math.ceil(o.xRange.min);d<=o.xRange.max;d++){const f=g(d);s.beginPath(),s.moveTo(f,c),s.lineTo(f,t-c),s.stroke()}for(let d=Math.ceil(o.yRange.min);d<=o.yRange.max;d++){const f=h(d);s.beginPath(),s.moveTo(c,f),s.lineTo(e-c,f),s.stroke()}}if(o.showAxes){s.strokeStyle=uiCore.resolveCssColor("var(--nice-text, #333)",s.canvas),s.lineWidth=1;const d=h(0);s.beginPath(),s.moveTo(c,d),s.lineTo(e-c,d),s.stroke();const f=g(0);if(s.beginPath(),s.moveTo(f,c),s.lineTo(f,t-c),s.stroke(),o.showLabels){s.fillStyle=uiCore.resolveCssColor("var(--nice-text, #333)",s.canvas),s.font="12px sans-serif",s.textAlign="center",s.fillText("x",e-c+15,d+4),s.fillText("y",f,c-10),s.font="10px sans-serif";for(let l=Math.ceil(o.xRange.min);l<=o.xRange.max;l++)l!==0&&s.fillText(String(l),g(l),d+15);for(let l=Math.ceil(o.yRange.min);l<=o.yRange.max;l++)l!==0&&(s.textAlign="right",s.fillText(String(l),f-5,h(l)+4))}}const w=i.isPlaying?{[i.parameter]:i.currentValue}:{};for(const d of n.filter(f=>f.visible)){const f=`rgb(${d.color.r},${d.color.g},${d.color.b})`;s.strokeStyle=f,s.lineWidth=d.lineWidth||2;let l=[];switch(d.type){case"2d-function":l=a.compute2DFunction(d.expression,o.xRange,d.resolution||200,w);break;case"2d-parametric":l=a.compute2DParametric(d.expression,d.expressionY||"sin(t)",d.parameterRange||{min:0,max:2*Math.PI},d.resolution||200,w);break;case"2d-polar":l=a.compute2DPolar(d.expression,d.parameterRange||{min:0,max:2*Math.PI},d.resolution||200,w);break}if(l.length>0){s.beginPath();let p=!1;for(const b of l){const R=g(b.x),y=h(b.y);if(y<0||y>t){p=!1;continue}p?s.lineTo(R,y):(s.moveTo(R,y),p=!0)}s.stroke()}}},[n,o,i,a,e,t]),jsxRuntime.jsx("canvas",{ref:r,width:e,height:t,style:styles$2.canvas})}const UNITS=[{name:"Meter",symbol:"m",category:"Length",toBase:e=>e,fromBase:e=>e},{name:"Kilometer",symbol:"km",category:"Length",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Centimeter",symbol:"cm",category:"Length",toBase:e=>e/100,fromBase:e=>e*100},{name:"Millimeter",symbol:"mm",category:"Length",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Mile",symbol:"mi",category:"Length",toBase:e=>e*1609.344,fromBase:e=>e/1609.344},{name:"Yard",symbol:"yd",category:"Length",toBase:e=>e*.9144,fromBase:e=>e/.9144},{name:"Foot",symbol:"ft",category:"Length",toBase:e=>e*.3048,fromBase:e=>e/.3048},{name:"Inch",symbol:"in",category:"Length",toBase:e=>e*.0254,fromBase:e=>e/.0254},{name:"Kilogram",symbol:"kg",category:"Mass",toBase:e=>e,fromBase:e=>e},{name:"Gram",symbol:"g",category:"Mass",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Milligram",symbol:"mg",category:"Mass",toBase:e=>e/1e6,fromBase:e=>e*1e6},{name:"Pound",symbol:"lb",category:"Mass",toBase:e=>e*.453592,fromBase:e=>e/.453592},{name:"Ounce",symbol:"oz",category:"Mass",toBase:e=>e*.0283495,fromBase:e=>e/.0283495},{name:"Ton",symbol:"t",category:"Mass",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Celsius",symbol:"°C",category:"Temperature",toBase:e=>e,fromBase:e=>e},{name:"Fahrenheit",symbol:"°F",category:"Temperature",toBase:e=>(e-32)*5/9,fromBase:e=>e*9/5+32},{name:"Kelvin",symbol:"K",category:"Temperature",toBase:e=>e-273.15,fromBase:e=>e+273.15},{name:"Second",symbol:"s",category:"Time",toBase:e=>e,fromBase:e=>e},{name:"Millisecond",symbol:"ms",category:"Time",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Minute",symbol:"min",category:"Time",toBase:e=>e*60,fromBase:e=>e/60},{name:"Hour",symbol:"hr",category:"Time",toBase:e=>e*3600,fromBase:e=>e/3600},{name:"Day",symbol:"d",category:"Time",toBase:e=>e*86400,fromBase:e=>e/86400},{name:"Week",symbol:"wk",category:"Time",toBase:e=>e*604800,fromBase:e=>e/604800},{name:"Square meter",symbol:"m²",category:"Area",toBase:e=>e,fromBase:e=>e},{name:"Square kilometer",symbol:"km²",category:"Area",toBase:e=>e*1e6,fromBase:e=>e/1e6},{name:"Hectare",symbol:"ha",category:"Area",toBase:e=>e*1e4,fromBase:e=>e/1e4},{name:"Acre",symbol:"ac",category:"Area",toBase:e=>e*4046.86,fromBase:e=>e/4046.86},{name:"Square foot",symbol:"ft²",category:"Area",toBase:e=>e*.092903,fromBase:e=>e/.092903},{name:"Liter",symbol:"L",category:"Volume",toBase:e=>e,fromBase:e=>e},{name:"Milliliter",symbol:"mL",category:"Volume",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Cubic meter",symbol:"m³",category:"Volume",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Gallon (US)",symbol:"gal",category:"Volume",toBase:e=>e*3.78541,fromBase:e=>e/3.78541},{name:"Quart",symbol:"qt",category:"Volume",toBase:e=>e*.946353,fromBase:e=>e/.946353},{name:"Pint",symbol:"pt",category:"Volume",toBase:e=>e*.473176,fromBase:e=>e/.473176},{name:"Cup",symbol:"cup",category:"Volume",toBase:e=>e*.236588,fromBase:e=>e/.236588},{name:"Meters/second",symbol:"m/s",category:"Speed",toBase:e=>e,fromBase:e=>e},{name:"Kilometers/hour",symbol:"km/h",category:"Speed",toBase:e=>e/3.6,fromBase:e=>e*3.6},{name:"Miles/hour",symbol:"mph",category:"Speed",toBase:e=>e*.44704,fromBase:e=>e/.44704},{name:"Knots",symbol:"kn",category:"Speed",toBase:e=>e*.514444,fromBase:e=>e/.514444},{name:"Byte",symbol:"B",category:"Data",toBase:e=>e,fromBase:e=>e},{name:"Kilobyte",symbol:"KB",category:"Data",toBase:e=>e*1024,fromBase:e=>e/1024},{name:"Megabyte",symbol:"MB",category:"Data",toBase:e=>e*1048576,fromBase:e=>e/1048576},{name:"Gigabyte",symbol:"GB",category:"Data",toBase:e=>e*1073741824,fromBase:e=>e/1073741824},{name:"Terabyte",symbol:"TB",category:"Data",toBase:e=>e*1099511627776,fromBase:e=>e/1099511627776},{name:"Bit",symbol:"bit",category:"Data",toBase:e=>e/8,fromBase:e=>e*8}],MatrixOps={create(e,t,r=0){const a=[];for(let n=0;n<e;n++)a.push(new Array(t).fill(r));return{rows:e,cols:t,data:a}},identity(e){const t=this.create(e,e);for(let r=0;r<e;r++)t.data[r][r]=1;return t},add(e,t){if(e.rows!==t.rows||e.cols!==t.cols)throw new Error("Matrix dimensions must match for addition");const r=this.create(e.rows,e.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<e.cols;n++)r.data[a][n]=e.data[a][n]+t.data[a][n];return r},subtract(e,t){if(e.rows!==t.rows||e.cols!==t.cols)throw new Error("Matrix dimensions must match for subtraction");const r=this.create(e.rows,e.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<e.cols;n++)r.data[a][n]=e.data[a][n]-t.data[a][n];return r},multiply(e,t){if(e.cols!==t.rows)throw new Error("Matrix A columns must equal Matrix B rows for multiplication");const r=this.create(e.rows,t.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<t.cols;n++){let o=0;for(let i=0;i<e.cols;i++)o+=e.data[a][i]*t.data[i][n];r.data[a][n]=o}return r},scalar(e,t){const r=this.create(e.rows,e.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<e.cols;n++)r.data[a][n]=e.data[a][n]*t;return r},transpose(e){const t=this.create(e.cols,e.rows);for(let r=0;r<e.rows;r++)for(let a=0;a<e.cols;a++)t.data[a][r]=e.data[r][a];return t},determinant(e){if(e.rows!==e.cols)throw new Error("Determinant requires square matrix");if(e.rows===1)return e.data[0][0];if(e.rows===2)return e.data[0][0]*e.data[1][1]-e.data[0][1]*e.data[1][0];let t=0;for(let r=0;r<e.cols;r++)t+=Math.pow(-1,r)*e.data[0][r]*this.determinant(this.minor(e,0,r));return t},minor(e,t,r){const a=this.create(e.rows-1,e.cols-1);let n=0;for(let o=0;o<e.rows;o++){if(o===t)continue;let i=0;for(let c=0;c<e.cols;c++)c!==r&&(a.data[n][i]=e.data[o][c],i++);n++}return a},inverse(e){const t=this.determinant(e);if(t===0)throw new Error("Matrix is singular, cannot compute inverse");const r=e.rows,a=this.create(r,r);for(let n=0;n<r;n++)for(let o=0;o<r;o++){const i=Math.pow(-1,n+o),c=this.determinant(this.minor(e,n,o));a.data[o][n]=i*c}return this.scalar(a,1/t)},trace(e){if(e.rows!==e.cols)throw new Error("Trace requires square matrix");let t=0;for(let r=0;r<e.rows;r++)t+=e.data[r][r];return t},eigenvalues2x2(e){if(e.rows!==2||e.cols!==2)throw new Error("Only 2x2 matrices supported for eigenvalues");const t=e.data[0][0],r=e.data[0][1],a=e.data[1][0],n=e.data[1][1],o=t+n,i=t*n-r*a,c=o*o-4*i;if(c<0)throw new Error("Complex eigenvalues not supported");const x=Math.sqrt(c);return[(o+x)/2,(o-x)/2]},toString(e,t=4){return e.data.map(r=>"[ "+r.map(a=>a.toFixed(t).padStart(10)).join(" ")+" ]").join(`
4
+ `)}},CalculusOps={derivative(e,t,r=1e-7){return(e(t+r)-e(t-r))/(2*r)},secondDerivative(e,t,r=1e-5){return(e(t+r)-2*e(t)+e(t-r))/(r*r)},integrate(e,t,r,a=1e3){a%2!==0&&a++;const n=(r-t)/a;let o=e(t)+e(r);for(let i=1;i<a;i++){const c=t+i*n;o+=i%2===0?2*e(c):4*e(c)}return n/3*o},findRoot(e,t,r=1e-10,a=100){let n=t;for(let o=0;o<a;o++){const i=e(n);if(Math.abs(i)<r)return n;const c=this.derivative(e,n);if(c===0)throw new Error("Derivative is zero, Newton-Raphson failed");n=n-i/c}throw new Error("Newton-Raphson did not converge")},symbolicDerivative(e){if(e=e.trim(),/^-?\d+\.?\d*$/.test(e))return"0";if(e==="x")return"1";const t=e.match(/^x\^(\d+)$/);if(t){const a=parseInt(t[1],10);return a===1?"1":a===2?"2*x":`${a}*x^${a-1}`}const r=e.match(/^(-?\d+\.?\d*)\*x\^(\d+)$/);if(r){const a=parseFloat(r[1]),n=parseInt(r[2],10),o=a*n;return n===1?String(o):n===2?`${o}*x`:`${o}*x^${n-1}`}return e==="sin(x)"?"cos(x)":e==="cos(x)"?"-sin(x)":e==="e^x"||e==="exp(x)"?"e^x":e==="ln(x)"?"1/x":`d/dx(${e})`},symbolicIntegral(e){if(e=e.trim(),/^-?\d+\.?\d*$/.test(e))return`${e}*x + C`;if(e==="x")return"x^2/2 + C";const t=e.match(/^x\^(\d+)$/);if(t){const r=parseInt(t[1],10);return`x^${r+1}/${r+1} + C`}return e==="sin(x)"?"-cos(x) + C":e==="cos(x)"?"sin(x) + C":e==="e^x"||e==="exp(x)"?"e^x + C":e==="1/x"?"ln|x| + C":`∫(${e})dx + C`},solveQuadratic(e,t,r){const a=t*t-4*e*r;if(a<0)throw new Error("No real solutions (complex roots)");if(a===0)return[-t/(2*e)];const n=Math.sqrt(a);return[(-t+n)/(2*e),(-t-n)/(2*e)]}};class CalculatorService{constructor(e={}){C(this,"history",[]);C(this,"memory",0);C(this,"variables",new Map);C(this,"config");this.config={precision:e.precision??12,angleUnit:e.angleUnit??"rad"}}evaluate(expression){let expr=expression.replace(/π|pi/gi,String(Math.PI)).replace(/e(?![xp])/gi,String(Math.E)).replace(/\^/g,"**").replace(/√/g,"Math.sqrt").replace(/sin/gi,"Math.sin").replace(/cos/gi,"Math.cos").replace(/tan/gi,"Math.tan").replace(/asin/gi,"Math.asin").replace(/acos/gi,"Math.acos").replace(/atan/gi,"Math.atan").replace(/sinh/gi,"Math.sinh").replace(/cosh/gi,"Math.cosh").replace(/tanh/gi,"Math.tanh").replace(/log10/gi,"Math.log10").replace(/log2/gi,"Math.log2").replace(/ln/gi,"Math.log").replace(/log\b/gi,"Math.log10").replace(/exp/gi,"Math.exp").replace(/sqrt/gi,"Math.sqrt").replace(/cbrt/gi,"Math.cbrt").replace(/abs/gi,"Math.abs").replace(/floor/gi,"Math.floor").replace(/ceil/gi,"Math.ceil").replace(/round/gi,"Math.round").replace(/pow/gi,"Math.pow").replace(/min/gi,"Math.min").replace(/max/gi,"Math.max");for(const[e,t]of this.variables)expr=expr.replace(new RegExp(`\\b${e}\\b`,"g"),String(t));try{const result=eval(expr);if(typeof result!="number"||!Number.isFinite(result))throw new Error("Invalid result");return result}catch(e){throw new Error(`Invalid expression: ${e.message}`)}}addHistory(e,t,r){this.history.unshift({id:Date.now().toString(36),expression:e,result:t,timestamp:new Date().toISOString(),mode:r}),this.history.length>100&&this.history.pop()}getHistory(){return this.history}clearHistory(){this.history=[]}memoryStore(e){this.memory=e}memoryRecall(){return this.memory}memoryAdd(e){this.memory+=e}memoryClear(){this.memory=0}setVariable(e,t){this.variables.set(e,t)}getVariable(e){return this.variables.get(e)}convertBase(e,t,r){const a={BIN:2,OCT:8,DEC:10,HEX:16},n=parseInt(e,a[t]);if(isNaN(n))throw new Error("Invalid number for base conversion");return n.toString(a[r]).toUpperCase()}convertUnits(e,t,r){const a=UNITS.find(i=>i.symbol===t),n=UNITS.find(i=>i.symbol===r);if(!a||!n)throw new Error("Unknown unit");if(a.category!==n.category)throw new Error("Cannot convert between different unit categories");const o=a.toBase(e);return n.fromBase(o)}getUnitsByCategory(e){return UNITS.filter(t=>t.category===e)}getUnitCategories(){return[...new Set(UNITS.map(e=>e.category))]}format(e){const t=this.config.precision;return Math.abs(e)<1e-10?"0":Math.abs(e)>1e10||Math.abs(e)<1e-6?e.toExponential(t):parseFloat(e.toPrecision(t)).toString()}}function createCalculatorService(e){return new CalculatorService(e)}const CalculatorContext=React.createContext(null);function useCalculator(){const e=React.useContext(CalculatorContext);if(!e)throw new Error("useCalculator must be used within CalculatorProvider");return e}const styles$1={container:{width:"400px",fontFamily:"'Inter', sans-serif",backgroundColor:"var(--nice-bg, #1e1e1e)",borderRadius:"12px",overflow:"hidden",boxShadow:"0 4px 20px var(--nice-overlay-30, rgba(0, 0, 0, 0.3))"},modeSelector:{display:"flex",backgroundColor:"var(--nice-bg-secondary, #2d2d2d)"},modeButton:{flex:1,padding:"8px",border:"none",backgroundColor:"transparent",color:"var(--nice-text-secondary, #888)",fontSize:"11px",cursor:"pointer"},display:{padding:"20px",backgroundColor:"var(--nice-bg-secondary, #252525)",minHeight:"80px"},displayText:{color:"var(--nice-text-primary, #fff)",fontSize:"32px",fontFamily:"'JetBrains Mono', monospace",textAlign:"right",wordBreak:"break-all"},keypad:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1px",backgroundColor:"var(--nice-bg-tertiary, #333)",padding:"1px"},key:{padding:"20px",border:"none",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",fontSize:"18px",cursor:"pointer",transition:"background-color 0.1s"},keyOperator:{backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)"},keyFunction:{backgroundColor:"#505050"}};function NiceCalculator({service:e,className:t,style:r}){const[a,n]=React.useState("0"),[o,i]=React.useState("standard"),[c,x]=React.useState([]),[s,u]=React.useState(!1),m=React.useCallback(d=>{s&&/[0-9.]/.test(d)?(n(d),u(!1)):(n(f=>f==="0"&&d!=="."?d:f+d),u(!1))},[s]),g=React.useCallback(()=>{n("0"),u(!1)},[]),h=React.useCallback(()=>{try{const d=e.evaluate(a),f=e.format(d);e.addHistory(a,f,o),x(e.getHistory()),n(f),u(!0)}catch{n("Error"),u(!0)}},[a,o,e]),w={service:e,display:a,setDisplay:n,mode:o,setMode:i,history:c,calculate:h,appendDigit:m,clear:g};return jsxRuntime.jsx(CalculatorContext.Provider,{value:w,children:jsxRuntime.jsxs("div",{className:t,style:{...styles$1.container,...r},children:[jsxRuntime.jsx(ModeSelector,{}),jsxRuntime.jsx(Display,{}),o==="standard"&&jsxRuntime.jsx(StandardKeypad,{}),o==="scientific"&&jsxRuntime.jsx(ScientificKeypad,{}),o==="programmer"&&jsxRuntime.jsx(ProgrammerKeypad,{}),o==="matrix"&&jsxRuntime.jsx(MatrixMode,{}),o==="calculus"&&jsxRuntime.jsx(CalculusMode,{}),o==="units"&&jsxRuntime.jsx(UnitsMode,{})]})})}function ModeSelector(){const{mode:e,setMode:t}=useCalculator(),r=[{id:"standard",label:"Standard"},{id:"scientific",label:"Scientific"},{id:"programmer",label:"Programmer"},{id:"matrix",label:"Matrix"},{id:"calculus",label:"Calculus"},{id:"units",label:"Units"}];return jsxRuntime.jsx("div",{style:styles$1.modeSelector,children:r.map(a=>jsxRuntime.jsx("button",{onClick:()=>t(a.id),style:{...styles$1.modeButton,backgroundColor:e===a.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:e===a.id?"var(--nice-text-on-primary, #fff)":"var(--nice-text-secondary, #888)"},children:a.label},a.id))})}function Display(){const{display:e}=useCalculator();return jsxRuntime.jsx("div",{style:styles$1.display,children:jsxRuntime.jsx("div",{style:styles$1.displayText,children:e})})}function StandardKeypad(){const{appendDigit:e,clear:t,calculate:r,setDisplay:a,display:n}=useCalculator(),o=[{label:"AC",action:t,style:styles$1.keyFunction},{label:"±",action:()=>a(n.startsWith("-")?n.slice(1):"-"+n),style:styles$1.keyFunction},{label:"%",action:()=>e("/100"),style:styles$1.keyFunction},{label:"÷",action:()=>e("/"),style:styles$1.keyOperator},{label:"7",action:()=>e("7")},{label:"8",action:()=>e("8")},{label:"9",action:()=>e("9")},{label:"×",action:()=>e("*"),style:styles$1.keyOperator},{label:"4",action:()=>e("4")},{label:"5",action:()=>e("5")},{label:"6",action:()=>e("6")},{label:"−",action:()=>e("-"),style:styles$1.keyOperator},{label:"1",action:()=>e("1")},{label:"2",action:()=>e("2")},{label:"3",action:()=>e("3")},{label:"+",action:()=>e("+"),style:styles$1.keyOperator},{label:"0",action:()=>e("0")},{label:".",action:()=>e(".")},{label:"⌫",action:()=>a(n.length>1?n.slice(0,-1):"0")},{label:"=",action:r,style:styles$1.keyOperator}];return jsxRuntime.jsx("div",{style:styles$1.keypad,children:o.map((i,c)=>jsxRuntime.jsx("button",{onClick:i.action,style:{...styles$1.key,...i.style||{}},children:i.label},c))})}function ScientificKeypad(){const{appendDigit:e,clear:t,calculate:r,setDisplay:a,display:n}=useCalculator(),o=[{label:"sin",action:()=>e("sin(")},{label:"cos",action:()=>e("cos(")},{label:"tan",action:()=>e("tan(")},{label:"ln",action:()=>e("ln(")},{label:"log",action:()=>e("log10(")}],i=[{label:"x²",action:()=>e("^2")},{label:"x³",action:()=>e("^3")},{label:"xʸ",action:()=>e("^")},{label:"√",action:()=>e("sqrt(")},{label:"eˣ",action:()=>e("exp(")}],c=[{label:"(",action:()=>e("(")},{label:")",action:()=>e(")")},{label:"π",action:()=>e("π")},{label:"e",action:()=>e("e")},{label:"AC",action:t}];return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(5, 1fr)"},children:[...o,...i,...c].map((x,s)=>jsxRuntime.jsx("button",{onClick:x.action,style:{...styles$1.key,...styles$1.keyFunction,padding:"12px"},children:x.label},s))}),jsxRuntime.jsx(StandardKeypad,{})]})}function ProgrammerKeypad(){const{display:e,setDisplay:t,service:r}=useCalculator(),[a,n]=React.useState("DEC"),o=c=>{try{const x=r.convertBase(e,a,c);t(x),n(c)}catch{t("Error")}},i=a==="HEX"?["A","B","C","D","E","F"]:[];return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",padding:"8px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:["BIN","OCT","DEC","HEX"].map(c=>jsxRuntime.jsx("button",{onClick:()=>o(c),style:{flex:1,padding:"8px",border:"none",borderRadius:"4px",backgroundColor:a===c?"var(--nice-primary-hover, #1976d2)":"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer"},children:c},c))}),i.length>0&&jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(6, 1fr)"},children:i.map(c=>jsxRuntime.jsx("button",{onClick:()=>t(e==="0"?c:e+c),style:styles$1.key,children:c},c))}),jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(4, 1fr)"},children:["7","8","9","AND","4","5","6","OR","1","2","3","XOR","0","NOT","<<",">>"].map(c=>{const x=["AND","OR","XOR","NOT","<<",">>"].includes(c);return jsxRuntime.jsx("button",{onClick:()=>t(e==="0"?c:e+c),style:{...styles$1.key,...x?styles$1.keyFunction:{}},children:c},c)})})]})}function MatrixMode(){const{t:e}=useNiceTranslation(),[t,r]=React.useState(MatrixOps.create(2,2)),[a,n]=React.useState(MatrixOps.create(2,2)),[o,i]=React.useState(""),c=(s,u,m,g,h)=>{const w={...s,data:s.data.map(d=>[...d])};w.data[m][g]=parseFloat(h)||0,u(w)},x=[{label:"A + B",fn:()=>MatrixOps.toString(MatrixOps.add(t,a))},{label:"A - B",fn:()=>MatrixOps.toString(MatrixOps.subtract(t,a))},{label:"A × B",fn:()=>MatrixOps.toString(MatrixOps.multiply(t,a))},{label:"det(A)",fn:()=>MatrixOps.determinant(t).toFixed(4)},{label:"Aᵀ",fn:()=>MatrixOps.toString(MatrixOps.transpose(t))},{label:"A⁻¹",fn:()=>MatrixOps.toString(MatrixOps.inverse(t))}];return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",marginBottom:"12px"},children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:e("calculator.matrixA","Matrix A")}),jsxRuntime.jsx(MatrixInput,{matrix:t,onChange:(s,u,m)=>c(t,r,s,u,m)})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:e("calculator.matrixB","Matrix B")}),jsxRuntime.jsx(MatrixInput,{matrix:a,onChange:(s,u,m)=>c(a,n,s,u,m)})]})]}),jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:x.map(s=>jsxRuntime.jsx("button",{onClick:()=>{try{i(s.fn())}catch(u){i(u.message)}},style:{padding:"8px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:s.label},s.label))}),o&&jsxRuntime.jsx("pre",{style:{color:"var(--nice-text-primary, #fff)",fontFamily:"monospace",whiteSpace:"pre-wrap"},children:o})]})}function MatrixInput({matrix:e,onChange:t}){return jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.cols}, 50px)`,gap:"4px"},children:e.data.map((r,a)=>r.map((n,o)=>jsxRuntime.jsx("input",{type:"number",value:n,onChange:i=>t(a,o,i.target.value),style:{width:"100%",padding:"4px",textAlign:"center",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}},`${a}-${o}`)))})}function CalculusMode(){const{t:e}=useNiceTranslation(),[t,r]=React.useState("x^2"),[a,n]=React.useState("");return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[jsxRuntime.jsx("input",{type:"text",value:t,onChange:o=>r(o.target.value),placeholder:e("calculator.exprPlaceholder","Enter expression (e.g., x^2, sin(x))"),style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:[jsxRuntime.jsx("button",{onClick:()=>n(`d/dx(${t}) = ${CalculusOps.symbolicDerivative(t)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-success, #4caf50)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:e("calculator.differentiate","Differentiate")}),jsxRuntime.jsx("button",{onClick:()=>n(`∫(${t})dx = ${CalculusOps.symbolicIntegral(t)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-primary, #2196f3)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:e("calculator.integrate","Integrate")})]}),a&&jsxRuntime.jsx("div",{style:{color:"var(--nice-text-primary, #fff)",fontFamily:"monospace",padding:"8px",backgroundColor:"var(--nice-bg, #1e1e1e)",borderRadius:"4px"},children:a})]})}function UnitsMode(){const{t:e}=useNiceTranslation(),{service:t}=useCalculator(),[r,a]=React.useState("1"),[n,o]=React.useState("m"),[i,c]=React.useState("ft"),[x,s]=React.useState("Length"),[u,m]=React.useState(""),g=t.getUnitCategories(),h=t.getUnitsByCategory(x),w=()=>{try{const d=t.convertUnits(parseFloat(r),n,i);m(`${r} ${n} = ${t.format(d)} ${i}`)}catch(d){m(d.message)}};return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[jsxRuntime.jsx("select",{value:x,onChange:d=>{s(d.target.value);const f=t.getUnitsByCategory(d.target.value);f.length>=2&&(o(f[0].symbol),c(f[1].symbol))},style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:g.map(d=>jsxRuntime.jsx("option",{value:d,children:d},d))}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("input",{type:"number",value:r,onChange:d=>a(d.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}}),jsxRuntime.jsx("select",{value:n,onChange:d=>o(d.target.value),style:{padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:h.map(d=>jsxRuntime.jsxs("option",{value:d.symbol,children:[d.name," (",d.symbol,")"]},d.symbol))})]}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("span",{style:{color:"var(--nice-text-secondary, #888)"},children:"→"}),jsxRuntime.jsx("select",{value:i,onChange:d=>c(d.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-text-on-primary, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:h.map(d=>jsxRuntime.jsxs("option",{value:d.symbol,children:[d.name," (",d.symbol,")"]},d.symbol))})]}),jsxRuntime.jsx("button",{onClick:w,style:{width:"100%",padding:"12px",backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)",border:"none",borderRadius:"4px",fontSize:"16px",cursor:"pointer"},children:e("calculator.convert","Convert")}),u&&jsxRuntime.jsx("div",{style:{marginTop:"12px",color:"var(--nice-text-primary, #fff)",fontSize:"18px",textAlign:"center"},children:u})]})}const GeoMath={distance(e,t){return Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2)},midpoint(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}},angle(e,t,r){const a=Math.atan2(e.y-t.y,e.x-t.x);let o=Math.atan2(r.y-t.y,r.x-t.x)-a;return o<0&&(o+=2*Math.PI),o},angleDegrees(e,t,r){return this.angle(e,t,r)*180/Math.PI},closestPointOnLine(e,t,r){const a=t.x-e.x,n=t.y-e.y,o=((r.x-e.x)*a+(r.y-e.y)*n)/(a*a+n*n);return{x:e.x+o*a,y:e.y+o*n}},lineIntersection(e,t,r,a){const n=(e.x-t.x)*(r.y-a.y)-(e.y-t.y)*(r.x-a.x);if(Math.abs(n)<1e-10)return null;const o=((e.x-r.x)*(r.y-a.y)-(e.y-r.y)*(r.x-a.x))/n;return{x:e.x+o*(t.x-e.x),y:e.y+o*(t.y-e.y)}},circleLineIntersection(e,t,r,a){const n=a.x-r.x,o=a.y-r.y,i=r.x-e.x,c=r.y-e.y,x=n*n+o*o,s=2*(i*n+c*o),u=i*i+c*c-t*t,m=s*s-4*x*u;if(m<0)return[];const g=Math.sqrt(m),h=(-s-g)/(2*x),w=(-s+g)/(2*x),d=[];return h>=0&&h<=1&&d.push({x:r.x+h*n,y:r.y+h*o}),w>=0&&w<=1&&Math.abs(w-h)>1e-10&&d.push({x:r.x+w*n,y:r.y+w*o}),d},circleCircleIntersection(e,t,r,a){const n=this.distance(e,r);if(n>t+a||n<Math.abs(t-a)||n===0)return[];const o=(t*t-a*a+n*n)/(2*n),i=Math.sqrt(t*t-o*o),c=e.x+o*(r.x-e.x)/n,x=e.y+o*(r.y-e.y)/n;return[{x:c+i*(r.y-e.y)/n,y:x-i*(r.x-e.x)/n},{x:c-i*(r.y-e.y)/n,y:x+i*(r.x-e.x)/n}]},perpendicularThrough(e,t,r){this.closestPointOnLine(e,t,r);const a=t.x-e.x,n=t.y-e.y;return{p1:r,p2:{x:r.x-n,y:r.y+a}}},parallelThrough(e,t,r){const a=t.x-e.x,n=t.y-e.y;return{p1:r,p2:{x:r.x+a,y:r.y+n}}},angleBisector(e,t,r){const a=Math.atan2(e.y-t.y,e.x-t.x),n=Math.atan2(r.y-t.y,r.x-t.x);let o=(a+n)/2;return Math.abs(n-a)>Math.PI&&(o+=Math.PI),{x:t.x+Math.cos(o),y:t.y+Math.sin(o)}},reflect(e,t,r){const a=this.closestPointOnLine(t,r,e);return{x:2*a.x-e.x,y:2*a.y-e.y}},rotate(e,t,r){const a=Math.cos(r),n=Math.sin(r),o=e.x-t.x,i=e.y-t.y;return{x:t.x+o*a-i*n,y:t.y+o*n+i*a}},translate(e,t,r){return{x:e.x+t,y:e.y+r}},dilate(e,t,r){return{x:t.x+r*(e.x-t.x),y:t.y+r*(e.y-t.y)}},polygonArea(e){let t=0;const r=e.length;for(let a=0;a<r;a++){const n=(a+1)%r;t+=e[a].x*e[n].y,t-=e[n].x*e[a].y}return Math.abs(t)/2},polygonPerimeter(e){let t=0;const r=e.length;for(let a=0;a<r;a++){const n=(a+1)%r;t+=this.distance(e[a],e[n])}return t},circumcenter(e,t,r){const a=2*(e.x*(t.y-r.y)+t.x*(r.y-e.y)+r.x*(e.y-t.y)),n=((e.x**2+e.y**2)*(t.y-r.y)+(t.x**2+t.y**2)*(r.y-e.y)+(r.x**2+r.y**2)*(e.y-t.y))/a,o=((e.x**2+e.y**2)*(r.x-t.x)+(t.x**2+t.y**2)*(e.x-r.x)+(r.x**2+r.y**2)*(t.x-e.x))/a;return{x:n,y:o}},incenter(e,t,r){const a=this.distance(e,t),n=this.distance(t,r),o=this.distance(r,e),i=a+n+o;return{x:(n*e.x+o*t.x+a*r.x)/i,y:(n*e.y+o*t.y+a*r.y)/i}},centroid(e,t,r){return{x:(e.x+t.x+r.x)/3,y:(e.y+t.y+r.y)/3}}};class GeometryService{constructor(){C(this,"elements",new Map);C(this,"nextLabel",1)}addElement(t){const r=this.generateId(),a={...t,id:r};return this.elements.set(r,a),a}getElement(t){return this.elements.get(t)}getPoint(t){const r=this.elements.get(t);return(r==null?void 0:r.type)==="point"?r:void 0}updateElement(t,r){const a=this.elements.get(t);a&&this.elements.set(t,{...a,...r,id:t,type:a.type})}deleteElement(t){var r;this.elements.delete(t);for(const[a,n]of this.elements)(r=n.dependencies)!=null&&r.includes(t)&&this.deleteElement(a)}getAllElements(){return Array.from(this.elements.values())}getElementsByType(t){return Array.from(this.elements.values()).filter(r=>r.type===t)}clear(){this.elements.clear(),this.nextLabel=1}createPoint(t,r,a){return this.addElement({type:"point",x:t,y:r,label:a??this.getNextLabel(),color:{r:0,g:0,b:0},visible:!0,selected:!1,locked:!1,size:6})}createSegment(t,r){return this.addElement({type:"segment",point1Id:t,point2Id:r,label:void 0,color:{r:50,g:50,b:50},visible:!0,selected:!1,locked:!1,width:2,dependencies:[t,r]})}createLine(t,r){return this.addElement({type:"line",point1Id:t,point2Id:r,label:void 0,color:{r:50,g:50,b:200},visible:!0,selected:!1,locked:!1,width:1,dependencies:[t,r]})}createRay(t,r){return this.addElement({type:"ray",originId:t,throughId:r,label:void 0,color:{r:50,g:150,b:50},visible:!0,selected:!1,locked:!1,width:1,dependencies:[t,r]})}createCircle(t,r){return this.addElement({type:"circle",centerId:t,radius:r,label:void 0,color:{r:200,g:50,b:50},visible:!0,selected:!1,locked:!1,width:2,dependencies:[t]})}createPolygon(t){return this.addElement({type:"polygon",pointIds:t,label:void 0,color:{r:100,g:100,b:200},visible:!0,selected:!1,locked:!1,width:2,fill:{r:100,g:100,b:200,a:.2},dependencies:t})}createMidpoint(t,r){const a=this.getPoint(t),n=this.getPoint(r);if(!a||!n)return null;const o=GeoMath.midpoint(a,n),i=this.createPoint(o.x,o.y);return i.dependencies=[t,r],i.color={r:0,g:150,b:0},i}createPerpendicular(t,r,a){const n=this.getPoint(t),o=this.getPoint(r),i=this.getPoint(a);if(!n||!o||!i)return null;const c=GeoMath.perpendicularThrough(n,o,i),x=this.createPoint(c.p2.x,c.p2.y),s=this.createLine(a,x.id);return s.dependencies=[t,r,a],s}createParallel(t,r,a){const n=this.getPoint(t),o=this.getPoint(r),i=this.getPoint(a);if(!n||!o||!i)return null;const c=GeoMath.parallelThrough(n,o,i),x=this.createPoint(c.p2.x,c.p2.y),s=this.createLine(a,x.id);return s.dependencies=[t,r,a],s}createIntersection(t,r){const a=this.elements.get(t),n=this.elements.get(r);if(!a||!n)return[];const o=[],i=s=>{if(s.type==="line"||s.type==="segment"||s.type==="ray"){const u=s,m=this.getPoint(u.point1Id??u.originId),g=this.getPoint(u.point2Id??u.throughId);if(m&&g)return[m,g]}return null},c=i(a),x=i(n);if(c&&x){const s=GeoMath.lineIntersection(c[0],c[1],x[0],x[1]);if(s){const u=this.createPoint(s.x,s.y);u.dependencies=[t,r],u.color={r:255,g:0,b:0},o.push(u)}}if(a.type==="circle"&&x){const s=a,u=this.getPoint(s.centerId);if(u){const m=GeoMath.circleLineIntersection(u,s.radius,x[0],x[1]);for(const g of m){const h=this.createPoint(g.x,g.y);h.dependencies=[t,r],h.color={r:255,g:0,b:0},o.push(h)}}}if(a.type==="circle"&&n.type==="circle"){const s=a,u=n,m=this.getPoint(s.centerId),g=this.getPoint(u.centerId);if(m&&g){const h=GeoMath.circleCircleIntersection(m,s.radius,g,u.radius);for(const w of h){const d=this.createPoint(w.x,w.y);d.dependencies=[t,r],d.color={r:255,g:0,b:0},o.push(d)}}}return o}calculateMeasurement(t,r){switch(t){case"distance":{const a=this.getPoint(r[0]),n=this.getPoint(r[1]);if(a&&n)return GeoMath.distance(a,n);break}case"angle":{const a=this.getPoint(r[0]),n=this.getPoint(r[1]),o=this.getPoint(r[2]);if(a&&n&&o)return GeoMath.angleDegrees(a,n,o);break}case"area":case"perimeter":{const a=this.elements.get(r[0]);if((a==null?void 0:a.type)==="polygon"){const n=a.pointIds.map(o=>this.getPoint(o)).filter(Boolean);return t==="area"?GeoMath.polygonArea(n):GeoMath.polygonPerimeter(n)}break}}return 0}exportSVG(t,r,a){const n=[`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${r}" viewBox="0 0 ${t} ${r}">`];n.push(`<rect width="100%" height="100%" fill="rgb(${a.backgroundColor.r},${a.backgroundColor.g},${a.backgroundColor.b})"/>`);const o=(i,c)=>({x:t/2+(i-a.centerX)*a.scale,y:r/2-(c-a.centerY)*a.scale});if(a.showGrid){n.push('<g stroke="var(--nice-border, #ddd)" stroke-width="0.5">');for(let i=Math.floor(-t/2/a.scale+a.centerX);i<=t/2/a.scale+a.centerX;i+=a.gridSpacing){const c=o(i,0);n.push(`<line x1="${c.x}" y1="0" x2="${c.x}" y2="${r}"/>`)}for(let i=Math.floor(-r/2/a.scale+a.centerY);i<=r/2/a.scale+a.centerY;i+=a.gridSpacing){const c=o(0,i);n.push(`<line x1="0" y1="${c.y}" x2="${t}" y2="${c.y}"/>`)}n.push("</g>")}if(a.showAxes){const i=o(0,0);n.push('<g stroke="var(--nice-text, #333)" stroke-width="1">'),n.push(`<line x1="0" y1="${i.y}" x2="${t}" y2="${i.y}"/>`),n.push(`<line x1="${i.x}" y1="0" x2="${i.x}" y2="${r}"/>`),n.push("</g>")}for(const i of this.getAllElements()){if(!i.visible)continue;const c=`rgb(${i.color.r},${i.color.g},${i.color.b})`;switch(i.type){case"point":{const x=o(i.x,i.y);n.push(`<circle cx="${x.x}" cy="${x.y}" r="${i.size}" fill="${c}"/>`),i.label&&n.push(`<text x="${x.x+8}" y="${x.y-8}" font-size="12">${i.label}</text>`);break}case"segment":{const x=this.getPoint(i.point1Id),s=this.getPoint(i.point2Id);if(x&&s){const u=o(x.x,x.y),m=o(s.x,s.y);n.push(`<line x1="${u.x}" y1="${u.y}" x2="${m.x}" y2="${m.y}" stroke="${c}" stroke-width="${i.width}"/>`)}break}case"circle":{const x=this.getPoint(i.centerId);if(x){const s=o(x.x,x.y),u=i.radius*a.scale,m=i.fill?`rgba(${i.fill.r},${i.fill.g},${i.fill.b},${i.fill.a??.2})`:"none";n.push(`<circle cx="${s.x}" cy="${s.y}" r="${u}" fill="${m}" stroke="${c}" stroke-width="${i.width}"/>`)}break}case"polygon":{const x=i.pointIds.map(s=>this.getPoint(s)).filter(Boolean);if(x.length>0){const u=x.map(g=>o(g.x,g.y)).map((g,h)=>`${h===0?"M":"L"}${g.x},${g.y}`).join(" ")+" Z",m=i.fill?`rgba(${i.fill.r},${i.fill.g},${i.fill.b},${i.fill.a??.2})`:"none";n.push(`<path d="${u}" fill="${m}" stroke="${c}" stroke-width="${i.width}"/>`)}break}}}return n.push("</svg>"),n.join(`
5
+ `)}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}getNextLabel(){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r=this.nextLabel-1;return this.nextLabel++,r<26?t[r]:t[r%26]+Math.floor(r/26)}}function createGeometryService(){return new GeometryService}const GeometryContext=React.createContext(null);function useGeometry(){const e=React.useContext(GeometryContext);if(!e)throw new Error("useGeometry must be used within GeometryProvider");return e}const styles={container:{display:"flex",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},toolbar:{width:"50px",backgroundColor:"var(--nice-bg-secondary, #f5f5f5)",borderRight:"1px solid var(--nice-border, #e0e0e0)",display:"flex",flexDirection:"column",padding:"8px 4px",gap:"4px"},toolButton:{width:"40px",height:"40px",border:"none",borderRadius:"4px",backgroundColor:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"18px"},main:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},canvas:{flex:1,cursor:"crosshair"},statusBar:{height:"30px",backgroundColor:"var(--nice-bg-secondary, #f5f5f5)",borderTop:"1px solid var(--nice-border, #e0e0e0)",padding:"0 12px",display:"flex",alignItems:"center",fontSize:"12px",color:"var(--nice-text-secondary, #666)"}};function NiceGeometry({service:e,width:t=800,height:r=600,className:a,style:n}){const[o,i]=React.useState([]),[c,x]=React.useState("point"),[s,u]=React.useState([]),[m,g]=React.useState({centerX:0,centerY:0,scale:40,showGrid:!0,showAxes:!0,gridSpacing:1,snapToGrid:!0,snapToPoints:!0,backgroundColor:{r:255,g:255,b:255}}),h=React.useCallback(()=>{i(e.getAllElements())},[e]),w=React.useCallback(f=>{g(l=>({...l,...f}))},[]);React.useEffect(()=>{h()},[h]);const d={service:e,elements:o,tool:c,setTool:x,view:m,setView:w,selectedIds:s,setSelectedIds:u,refresh:h};return jsxRuntime.jsx(GeometryContext.Provider,{value:d,children:jsxRuntime.jsxs("div",{className:a,style:{...styles.container,...n},children:[jsxRuntime.jsx(Toolbar,{}),jsxRuntime.jsxs("div",{style:styles.main,children:[jsxRuntime.jsx(Canvas,{width:t,height:r}),jsxRuntime.jsx(StatusBar,{width:t,height:r})]})]})})}function Toolbar(){const{tool:e,setTool:t}=useGeometry(),r=[{id:"select",icon:"cursor",title:"Select"},{id:"point",icon:"•",title:"Point"},{id:"segment",icon:"—",title:"Segment"},{id:"line",icon:"line",title:"Line"},{id:"ray",icon:"arrow-right",title:"Ray"},{id:"circle",icon:"circle",title:"Circle"},{id:"polygon",icon:"triangle",title:"Polygon"},{id:"perpendicular",icon:"⊥",title:"Perpendicular"},{id:"parallel",icon:"∥",title:"Parallel"},{id:"midpoint",icon:"⊙",title:"Midpoint"},{id:"bisector",icon:"∠",title:"Angle Bisector"},{id:"intersection",icon:"close",title:"Intersection"},{id:"reflect",icon:"shuffle",title:"Reflect"},{id:"rotate",icon:"refresh",title:"Rotate"},{id:"measure",icon:"ruler",title:"Measure"}];return jsxRuntime.jsx("div",{style:styles.toolbar,children:r.map(a=>jsxRuntime.jsx("button",{onClick:()=>t(a.id),title:a.title,style:{...styles.toolButton,backgroundColor:e===a.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:e===a.id?"var(--nice-text-on-primary, #fff)":"var(--nice-text, #333)"},children:/^[a-z][a-z0-9-]*$/.test(a.icon)?jsxRuntime.jsx(uiCore.NiceIcon,{name:a.icon,size:16}):a.icon},a.id))})}function Canvas({width:e,height:t}){const r=React.useRef(null),{service:a,elements:n,tool:o,view:i,selectedIds:c,setSelectedIds:x,refresh:s}=useGeometry(),[u,m]=React.useState([]),g=React.useCallback((f,l)=>{const p=(f-e/2)/i.scale+i.centerX,b=-(l-t/2)/i.scale+i.centerY;return i.snapToGrid?{x:Math.round(p/i.gridSpacing)*i.gridSpacing,y:Math.round(b/i.gridSpacing)*i.gridSpacing}:{x:p,y:b}},[e,t,i]),h=React.useCallback((f,l)=>({x:e/2+(f-i.centerX)*i.scale,y:t/2-(l-i.centerY)*i.scale}),[e,t,i]),w=React.useCallback(f=>{var b;const l=(b=r.current)==null?void 0:b.getBoundingClientRect();if(!l)return;const p=g(f.clientX-l.left,f.clientY-l.top);switch(o){case"point":{a.createPoint(p.x,p.y),s();break}case"segment":case"line":case"ray":{const R=d(p);if(R)m(y=>{const v=[...y,R.id];return v.length===2?(o==="segment"?a.createSegment(v[0],v[1]):o==="line"?a.createLine(v[0],v[1]):o==="ray"&&a.createRay(v[0],v[1]),s(),[]):v});else{const y=a.createPoint(p.x,p.y);m(v=>{const j=[...v,y.id];return j.length===2?(o==="segment"?a.createSegment(j[0],j[1]):o==="line"?a.createLine(j[0],j[1]):o==="ray"&&a.createRay(j[0],j[1]),s(),[]):j}),s()}break}case"circle":{const R=d(p);if(R)m(y=>{if(y.length===0)return[R.id];const v=a.getPoint(y[0]);if(v){const j=GeoMath.distance(v,p);a.createCircle(y[0],j),s()}return[]});else if(u.length===1){const y=a.getPoint(u[0]);if(y){const v=GeoMath.distance(y,p);a.createCircle(u[0],v),s(),m([])}}else{const y=a.createPoint(p.x,p.y);m([y.id]),s()}break}case"midpoint":{const R=d(p);R&&m(y=>{const v=[...y,R.id];return v.length===2?(a.createMidpoint(v[0],v[1]),s(),[]):v});break}case"select":{const R=d(p);x(R?[R.id]:[]);break}}},[o,a,s,g,u,x]),d=f=>{for(const p of n)if(p.type==="point"&&GeoMath.distance(p,f)<.5)return p};return React.useEffect(()=>{const f=r.current,l=f==null?void 0:f.getContext("2d");if(!(!f||!l)){if(l.fillStyle=`rgb(${i.backgroundColor.r},${i.backgroundColor.g},${i.backgroundColor.b})`,l.fillRect(0,0,e,t),i.showGrid){l.strokeStyle=uiCore.resolveCssColor("var(--nice-border, #e0e0e0)",l.canvas),l.lineWidth=.5;const p=i.gridSpacing*i.scale,b=(e/2-i.centerX*i.scale)%p,R=(t/2+i.centerY*i.scale)%p;for(let y=b;y<e;y+=p)l.beginPath(),l.moveTo(y,0),l.lineTo(y,t),l.stroke();for(let y=R;y<t;y+=p)l.beginPath(),l.moveTo(0,y),l.lineTo(e,y),l.stroke()}if(i.showAxes){const p=h(0,0);l.strokeStyle=uiCore.resolveCssColor("var(--nice-text, #333)",l.canvas),l.lineWidth=1,l.beginPath(),l.moveTo(0,p.y),l.lineTo(e,p.y),l.stroke(),l.beginPath(),l.moveTo(p.x,0),l.lineTo(p.x,t),l.stroke()}for(const p of n){if(!p.visible)continue;const b=`rgb(${p.color.r},${p.color.g},${p.color.b})`,R=c.includes(p.id);switch(p.type){case"point":{const y=h(p.x,p.y);l.beginPath(),l.arc(y.x,y.y,R?p.size+2:p.size,0,2*Math.PI),l.fillStyle=R?uiCore.resolveCssColor("var(--nice-primary-hover, #1976d2)",l.canvas):b,l.fill(),p.label&&(l.fillStyle=uiCore.resolveCssColor("var(--nice-text, #333)",l.canvas),l.font="12px sans-serif",l.fillText(p.label,y.x+8,y.y-8));break}case"segment":{const y=a.getPoint(p.point1Id),v=a.getPoint(p.point2Id);if(y&&v){const j=h(y.x,y.y),k=h(v.x,v.y);l.strokeStyle=b,l.lineWidth=p.width,l.beginPath(),l.moveTo(j.x,j.y),l.lineTo(k.x,k.y),l.stroke()}break}case"line":{const y=a.getPoint(p.point1Id),v=a.getPoint(p.point2Id);if(y&&v){const j=v.x-y.x,k=v.y-y.y,M=-1e3,S=1e3,P=h(y.x+M*j,y.y+M*k),$=h(y.x+S*j,y.y+S*k);l.strokeStyle=b,l.lineWidth=p.width,l.beginPath(),l.moveTo(P.x,P.y),l.lineTo($.x,$.y),l.stroke()}break}case"circle":{const y=a.getPoint(p.centerId);if(y){const v=h(y.x,y.y),j=p.radius*i.scale;l.beginPath(),l.arc(v.x,v.y,j,0,2*Math.PI),p.fill&&(l.fillStyle=`rgba(${p.fill.r},${p.fill.g},${p.fill.b},${p.fill.a??.2})`,l.fill()),l.strokeStyle=b,l.lineWidth=p.width,l.stroke()}break}case"polygon":{const y=p.pointIds.map(v=>a.getPoint(v)).filter(Boolean);if(y.length>0){l.beginPath();const v=h(y[0].x,y[0].y);l.moveTo(v.x,v.y);for(let j=1;j<y.length;j++){const k=h(y[j].x,y[j].y);l.lineTo(k.x,k.y)}l.closePath(),p.fill&&(l.fillStyle=`rgba(${p.fill.r},${p.fill.g},${p.fill.b},${p.fill.a??.2})`,l.fill()),l.strokeStyle=b,l.lineWidth=p.width,l.stroke()}break}}}if(u.length>0){l.fillStyle="rgba(25, 118, 210, 0.3)";for(const p of u){const b=a.getPoint(p);if(b){const R=h(b.x,b.y);l.beginPath(),l.arc(R.x,R.y,12,0,2*Math.PI),l.fill()}}}}},[n,i,e,t,c,u,a,h]),jsxRuntime.jsx("canvas",{ref:r,width:e,height:t,style:styles.canvas,onClick:w})}function StatusBar({width:e,height:t}){const{tool:r,elements:a,view:n,service:o}=useGeometry(),[i,c]=React.useState(null),x={select:"Select",point:"Point",line:"Line",ray:"Ray",segment:"Segment",circle:"Circle",arc:"Arc",polygon:"Polygon",angle:"Angle",perpendicular:"Perpendicular",parallel:"Parallel",bisector:"Angle Bisector",midpoint:"Midpoint",tangent:"Tangent",intersection:"Intersection",reflect:"Reflect",rotate:"Rotate",translate:"Translate",dilate:"Dilate",measure:"Measure",text:"Text"},s=a.filter(u=>u.type==="point").length;return jsxRuntime.jsxs("div",{style:styles.statusBar,children:[jsxRuntime.jsxs("span",{children:["Tool: ",x[r]]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Objects: ",a.length]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Points: ",s]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Scale: ",n.scale.toFixed(1),"x"]})]})}exports.CalculatorService=CalculatorService;exports.CalculusOps=CalculusOps;exports.EQUATION_TEMPLATES=EQUATION_TEMPLATES;exports.ExpressionParser=ExpressionParser;exports.FUNCTION_PRESETS=FUNCTION_PRESETS;exports.GeoMath=GeoMath;exports.GeometryService=GeometryService;exports.GraphService=GraphService;exports.MATH_SYMBOLS=MATH_SYMBOLS;exports.MathEditorService=MathEditorService;exports.MatrixOps=MatrixOps;exports.NiceCalculator=NiceCalculator;exports.NiceGeometry=NiceGeometry;exports.NiceGraphPlotter=NiceGraphPlotter;exports.NiceI18nProvider=NiceI18nProvider;exports.NiceMathEditor=NiceMathEditor;exports.createCalculatorService=createCalculatorService;exports.createGeometryService=createGeometryService;exports.createGraphService=createGraphService;exports.createMathEditorService=createMathEditorService;exports.getSymbolsByCategory=getSymbolsByCategory;exports.recognizeHandwriting=recognizeHandwriting;exports.useCalculator=useCalculator;exports.useGeometry=useGeometry;exports.useGraph=useGraph;exports.useMathEditor=useMathEditor;exports.useNiceTranslation=useNiceTranslation;