Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"ai": "^6.0.168",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.6",
"gaussformula": "0.1.7",
"gaussformula": "file:../gaussformula/gaussformula-0.1.7.tgz",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"zod": "^4.3.6"
Expand Down
11 changes: 6 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

90 changes: 52 additions & 38 deletions src/components/spreadsheet/CellRenderer.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import React, {
useCallback,
useMemo,
useRef,
useState,
} from "react";
import React, { useCallback, useMemo, useRef, useState } from "react";
import {
getSamplesFromDistribution,
isDistributionValue,
Expand All @@ -23,6 +18,40 @@ import type { DistributionParams } from "../charts/distributionChartOptions";
import { SpreadsheetContext } from "../../context/SpreadsheetContext";
import styles from "./CellRenderer.module.css";

interface CellEditInputProps {
initialValue: string;
onCommit: (value: string) => void;
onCancel: () => void;
ariaLabel: string;
}

// Keeps the in-progress edit value in local state so typing does not
// re-render the parent Spreadsheet (and therefore every other cell) on
// every keystroke. This component mounts when editing begins and unmounts
// when it ends, so `initialValue` is captured fresh each edit session.
const CellEditInput: React.FC<CellEditInputProps> = ({
initialValue,
onCommit,
onCancel,
ariaLabel,
}) => {
const [value, setValue] = useState(initialValue);
return (
<input
autoFocus
value={value}
onChange={(e) => setValue(e.target.value)}
onBlur={() => onCommit(value)}
onKeyDown={(e) => {
if (e.key === "Enter") onCommit(value);
if (e.key === "Escape") onCancel();
}}
className={styles.editInput}
aria-label={ariaLabel}
/>
);
};

interface CellRendererProps {
row: number;
col: number;
Expand All @@ -38,7 +67,7 @@ interface CellRendererProps {
onStopEdit?: () => void;
}

export const CellRenderer: React.FC<CellRendererProps> = ({
const CellRendererComponent: React.FC<CellRendererProps> = ({
row,
col,
value,
Expand All @@ -48,7 +77,6 @@ export const CellRenderer: React.FC<CellRendererProps> = ({
isSelected = false,
isEditing = false,
editValue = "",
onEditValueChange,
onRequestEdit,
onStopEdit,
}) => {
Expand Down Expand Up @@ -114,11 +142,6 @@ export const CellRenderer: React.FC<CellRendererProps> = ({
onClick?.();
};

const handleBlur = () => {
onEdit(row, col, editValue);
onStopEdit?.();
};

const handleChartHintClick = (e: React.MouseEvent) => {
e.stopPropagation();
if (!cellRef.current) return;
Expand Down Expand Up @@ -187,27 +210,20 @@ export const CellRenderer: React.FC<CellRendererProps> = ({
left,
});

if (
isDistributionValue(value) ||
isSampledDistributionValue(value)
) {
if (isDistributionValue(value) || isSampledDistributionValue(value)) {
setShowPlot(true);
}
}
};

const isDistribution =
isDistributionValue(value) ||
isSampledDistributionValue(value);
isDistributionValue(value) || isSampledDistributionValue(value);

const leadingIcon = useMemo(() => {
if (
isDistributionValue(value) ||
isSampledDistributionValue(value)
) {
if (isDistributionValue(value) || isSampledDistributionValue(value)) {
const sparkType = isSampledDistributionValue(value)
? ("sampled" as const)
: explicitDistribution?.kind ?? "normal";
: (explicitDistribution?.kind ?? "normal");
const sparkColor = distColors?.accent ?? "var(--text-muted)";
return <MicroSparkline type={sparkType} color={sparkColor} />;
}
Expand All @@ -219,10 +235,7 @@ export const CellRenderer: React.FC<CellRendererProps> = ({
return null;
}, [value, explicitDistribution, distColors]);

const displayValue = useMemo(
() => formatCellValue(value),
[value],
);
const displayValue = useMemo(() => formatCellValue(value), [value]);

const cellClassName = [
styles.cell,
Expand Down Expand Up @@ -254,17 +267,14 @@ export const CellRenderer: React.FC<CellRendererProps> = ({
}}
>
{isEditing ? (
<input
autoFocus
value={editValue}
onChange={(e) => onEditValueChange?.(e.target.value)}
onBlur={handleBlur}
onKeyDown={(e) => {
if (e.key === "Enter") handleBlur();
if (e.key === "Escape") onStopEdit?.();
<CellEditInput
initialValue={editValue}
onCommit={(committed) => {
onEdit(row, col, committed);
onStopEdit?.();
}}
className={styles.editInput}
aria-label={`Cell ${String.fromCharCode(65 + col)}${row + 1}`}
onCancel={() => onStopEdit?.()}
ariaLabel={`Cell ${String.fromCharCode(65 + col)}${row + 1}`}
/>
) : (
<>
Expand Down Expand Up @@ -381,3 +391,7 @@ export const CellRenderer: React.FC<CellRendererProps> = ({
</>
);
};

// Memoized so cells whose props didn't change skip re-rendering when
// unrelated cells update (e.g. selection changes elsewhere in the grid).
export const CellRenderer = React.memo(CellRendererComponent);
11 changes: 2 additions & 9 deletions src/components/spreadsheet/Spreadsheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,6 @@ export const Spreadsheet: React.FC<SpreadsheetProps> = ({
? editingCell.value
: ""
}
onEditValueChange={(value) => {
setEditingCell((current) =>
current?.row === rowIndex && current?.col === colIndex
? { ...current, value }
: current,
);
}}
onRequestEdit={(row, col, value) =>
setEditingCell({ row, col, value })
}
Expand Down Expand Up @@ -274,8 +267,8 @@ export const Spreadsheet: React.FC<SpreadsheetProps> = ({
</svg>
<p className={styles.welcomeTitle}>Start building your model</p>
<p className={styles.welcomeSubtitle}>
Type values, formulas, or uncertainty like <code>N.CI(10, 20, 0.95)</code> to
add uncertainty
Type values, formulas, or uncertainty like{" "}
<code>N.CI(10, 20, 0.95)</code> to add uncertainty
</p>
</div>
</div>
Expand Down
40 changes: 32 additions & 8 deletions src/components/spreadsheet/cellFormatting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import React from "react";

import {
confidenceLevelToFormulaArgument,
formatDistributionFormulaNumber,
isDistributionValue,
isSampledDistributionValue,
parseDistributionValue,
Expand Down Expand Up @@ -145,28 +146,51 @@ export const formatCellEditValue = (val: CellValue): string => {
const distribution = parseDistributionValue(val);
if (distribution) {
switch (distribution.kind) {
case "normal":
case "normal": {
if (
distribution.source === "ci" &&
distribution.lower !== undefined &&
distribution.upper !== undefined &&
distribution.confidenceLevel !== undefined
) {
return `N.CI(${distribution.lower.toFixed(2)}, ${distribution.upper.toFixed(2)}, ${confidenceLevelToFormulaArgument(distribution.confidenceLevel).toFixed(2)})`;
const lower = formatDistributionFormulaNumber(distribution.lower);
const upper = formatDistributionFormulaNumber(distribution.upper);
const confidence = formatDistributionFormulaNumber(
confidenceLevelToFormulaArgument(distribution.confidenceLevel),
);
return `N.CI(${lower}, ${upper}, ${confidence})`;
}
return `N(${(distribution.mean ?? 0).toFixed(2)}, ${(distribution.variance ?? 0).toFixed(2)})`;
case "lognormal":
const mean = formatDistributionFormulaNumber(distribution.mean ?? 0);
const variance = formatDistributionFormulaNumber(
distribution.variance ?? 0,
);
return `N(${mean}, ${variance})`;
}
case "lognormal": {
if (
distribution.source === "ci" &&
distribution.lower !== undefined &&
distribution.upper !== undefined &&
distribution.confidenceLevel !== undefined
) {
return `LN.CI(${distribution.lower.toFixed(2)}, ${distribution.upper.toFixed(2)}, ${confidenceLevelToFormulaArgument(distribution.confidenceLevel).toFixed(2)})`;
const lower = formatDistributionFormulaNumber(distribution.lower);
const upper = formatDistributionFormulaNumber(distribution.upper);
const confidence = formatDistributionFormulaNumber(
confidenceLevelToFormulaArgument(distribution.confidenceLevel),
);
return `LN.CI(${lower}, ${upper}, ${confidence})`;
}
return `LN(${(distribution.mu ?? 0).toFixed(2)}, ${(distribution.sigma ?? 0).toFixed(2)})`;
case "uniform":
return `U(${(distribution.min ?? 0).toFixed(2)}, ${(distribution.max ?? 0).toFixed(2)})`;
const mu = formatDistributionFormulaNumber(distribution.mu ?? 0);
const sigma = formatDistributionFormulaNumber(
distribution.sigma ?? 0,
);
return `LN(${mu}, ${sigma})`;
}
case "uniform": {
const min = formatDistributionFormulaNumber(distribution.min ?? 0);
const max = formatDistributionFormulaNumber(distribution.max ?? 0);
return `U(${min}, ${max})`;
}
}
}
}
Expand Down
40 changes: 32 additions & 8 deletions src/hooks/useFormulaBar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useCallback, useContext, useEffect, useState } from "react";
import { SpreadsheetContext } from "../context/SpreadsheetContext";
import {
confidenceLevelToFormulaArgument,
formatDistributionFormulaNumber,
parseDistributionValue,
parseSampledDistributionValue,
} from "../utils/distribution/distributionUtils";
Expand All @@ -19,28 +20,51 @@ export const formatFormulaBarCellValue = (value: unknown): string => {
const distribution = parseDistributionValue(value);
if (distribution) {
switch (distribution.kind) {
case "normal":
case "normal": {
if (
distribution.source === "ci" &&
distribution.lower !== undefined &&
distribution.upper !== undefined &&
distribution.confidenceLevel !== undefined
) {
return `N.CI(${distribution.lower.toFixed(2)}, ${distribution.upper.toFixed(2)}, ${confidenceLevelToFormulaArgument(distribution.confidenceLevel).toFixed(2)})`;
const lower = formatDistributionFormulaNumber(distribution.lower);
const upper = formatDistributionFormulaNumber(distribution.upper);
const confidence = formatDistributionFormulaNumber(
confidenceLevelToFormulaArgument(distribution.confidenceLevel),
);
return `N.CI(${lower}, ${upper}, ${confidence})`;
}
return `N(${(distribution.mean ?? 0).toFixed(2)}, ${(distribution.variance ?? 0).toFixed(2)})`;
case "lognormal":
const mean = formatDistributionFormulaNumber(distribution.mean ?? 0);
const variance = formatDistributionFormulaNumber(
distribution.variance ?? 0,
);
return `N(${mean}, ${variance})`;
}
case "lognormal": {
if (
distribution.source === "ci" &&
distribution.lower !== undefined &&
distribution.upper !== undefined &&
distribution.confidenceLevel !== undefined
) {
return `LN.CI(${distribution.lower.toFixed(2)}, ${distribution.upper.toFixed(2)}, ${confidenceLevelToFormulaArgument(distribution.confidenceLevel).toFixed(2)})`;
const lower = formatDistributionFormulaNumber(distribution.lower);
const upper = formatDistributionFormulaNumber(distribution.upper);
const confidence = formatDistributionFormulaNumber(
confidenceLevelToFormulaArgument(distribution.confidenceLevel),
);
return `LN.CI(${lower}, ${upper}, ${confidence})`;
}
return `LN(${(distribution.mu ?? 0).toFixed(2)}, ${(distribution.sigma ?? 0).toFixed(2)})`;
case "uniform":
return `U(${(distribution.min ?? 0).toFixed(2)}, ${(distribution.max ?? 0).toFixed(2)})`;
const mu = formatDistributionFormulaNumber(distribution.mu ?? 0);
const sigma = formatDistributionFormulaNumber(
distribution.sigma ?? 0,
);
return `LN(${mu}, ${sigma})`;
}
case "uniform": {
const min = formatDistributionFormulaNumber(distribution.min ?? 0);
const max = formatDistributionFormulaNumber(distribution.max ?? 0);
return `U(${min}, ${max})`;
}
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/utils/distribution/distributionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,18 @@ export const confidenceLevelToFormulaArgument = (
confidenceLevel: number,
): number => confidenceLevel > 1 ? confidenceLevel / 100 : confidenceLevel

export const formatDistributionFormulaNumber = (value: number): string => {
if (!Number.isFinite(value)) {
return String(value)
}

if (Number.isInteger(value) || Math.abs(value) >= 1) {
return value.toFixed(2)
}

return Number(value.toPrecision(12)).toString()
}

type SampledDistributionLike = {
samples?: unknown
getSamples?: () => number[]
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/components/spreadsheet/cellFormatting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ describe('formatCellValue', () => {
).toBe('LN.CI(1.00, 2.00, 0.95)')
})

it('preserves small CI bounds in editable formulas', () => {
expect(
formatCellEditValue(
{
kind: 'normal',
source: 'ci',
lower: 0.009,
upper: 0.011,
confidenceLevel: 95,
},
),
).toBe('N.CI(0.009, 0.011, 0.95)')
})

it('formats sampled distributions', () => {
expect(
formatCellValue(sampledValue),
Expand Down
Loading
Loading