|
2 | 2 | import { defaultChartPadding, LineChart, Raster, Spline, Tooltip } from 'layerchart'; |
3 | 3 | import { Field, MenuField, Switch, TextField } from 'svelte-ux'; |
4 | 4 | import { format } from '@layerstack/utils'; |
5 | | - import { evaluate } from 'mathjs'; |
| 5 | + import { browser } from '$app/environment'; |
6 | 6 | import { scaleSequential } from 'd3-scale'; |
7 | 7 | import { |
8 | 8 | interpolateRainbow, |
|
37 | 37 | let selected = $state('x^2'); |
38 | 38 | let customFormula = $state(''); |
39 | 39 | let showRaster = $state(false); |
| 40 | + let evaluateFn: ((expr: string, scope?: object) => any) | null = $state(null); |
| 41 | +
|
| 42 | + $effect(() => { |
| 43 | + if (browser) { |
| 44 | + import('mathjs').then((m) => { |
| 45 | + evaluateFn = m.evaluate; |
| 46 | + }); |
| 47 | + } |
| 48 | + }); |
40 | 49 |
|
41 | 50 | const interpolators = [ |
42 | 51 | { label: 'Viridis', value: 'viridis', fn: interpolateViridis }, |
|
58 | 67 | let interp = $derived(interpolators.find((i) => i.value === selectedInterp)!); |
59 | 68 |
|
60 | 69 | const formula = $derived(selected === 'custom' ? customFormula : selected); |
61 | | - const { data, error } = $derived(computeGraph(formula)); |
| 70 | + const { data, error } = $derived(computeGraph(formula, evaluateFn)); |
62 | 71 |
|
63 | 72 | const rasterValue = $derived.by(() => { |
64 | 73 | const f = formula; |
65 | | - if (!f?.trim()) return (_x: number, _y: number) => 0; |
| 74 | + const eval_ = evaluateFn; |
| 75 | + if (!f?.trim() || !eval_) return (_x: number, _y: number) => 0; |
66 | 76 | return (x: number, _y: number) => { |
67 | 77 | try { |
68 | | - const y = evaluate(f, { x }); |
| 78 | + const y = eval_(f, { x }); |
69 | 79 | return isFinite(y) ? y : NaN; |
70 | 80 | } catch { |
71 | 81 | return NaN; |
72 | 82 | } |
73 | 83 | }; |
74 | 84 | }); |
75 | 85 |
|
76 | | - function computeGraph(formula: string) { |
77 | | - if (!formula?.trim()) return { data: [], error: null }; |
| 86 | + function computeGraph(formula: string, eval_: typeof evaluateFn) { |
| 87 | + if (!formula?.trim() || !eval_) return { data: [], error: null }; |
78 | 88 |
|
79 | 89 | try { |
80 | 90 | const data = xs.flatMap((x) => { |
81 | 91 | try { |
82 | | - const y = evaluate(formula, { x }); |
| 92 | + const y = eval_(formula, { x }); |
83 | 93 | return isFinite(y) && Math.abs(y) < 1e6 ? [{ x, y }] : []; |
84 | 94 | } catch { |
85 | 95 | return []; |
|
0 commit comments