@reekon-tools/boldr-utils 1.6.39 → 1.7.0
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/annotation/canvas/elements/BackgroundImageElement.js +2 -7
- package/dist/annotation/canvas/tools/measurementLineTool.d.ts +12 -0
- package/dist/annotation/canvas/tools/measurementLineTool.js +95 -0
- package/dist/annotation/canvas/useAnnotationCanvasState.js +31 -17
- package/dist/annotation/data/AnnotationDataProvider.d.ts +6 -1
- package/dist/annotation/data/AnnotationDataProvider.js +4 -1
- package/dist/calculator/evaluate.d.ts +49 -0
- package/dist/calculator/evaluate.js +207 -0
- package/dist/calculator/index.d.ts +5 -0
- package/dist/calculator/index.js +9 -0
- package/dist/calculator/schema.d.ts +163 -0
- package/dist/calculator/schema.js +129 -0
- package/dist/calculator/solve.d.ts +46 -0
- package/dist/calculator/solve.js +227 -0
- package/dist/calculator/units.d.ts +50 -0
- package/dist/calculator/units.js +137 -0
- package/dist/calculator/validate.d.ts +192 -0
- package/dist/calculator/validate.js +370 -0
- package/dist/exports.d.ts +2 -1
- package/dist/exports.js +4 -1
- package/package.json +3 -2
- package/dist/canvas/AnnotationCanvas.d.ts +0 -11
- package/dist/canvas/AnnotationCanvas.js +0 -10
- package/dist/canvas/AnnotationCanvas.native.d.ts +0 -8
- package/dist/canvas/AnnotationCanvas.native.js +0 -6
- package/dist/canvas/AnnotationCanvasInner.d.ts +0 -39
- package/dist/canvas/AnnotationCanvasInner.js +0 -219
- package/dist/canvas/AnnotationCanvasInner.native.d.ts +0 -35
- package/dist/canvas/AnnotationCanvasInner.native.js +0 -138
- package/dist/canvas/AnnotationCanvasSkia.d.ts +0 -27
- package/dist/canvas/AnnotationCanvasSkia.js +0 -20
- package/dist/canvas/Tool.d.ts +0 -38
- package/dist/canvas/Tool.js +0 -1
- package/dist/canvas/elements/BackgroundImageElement.d.ts +0 -9
- package/dist/canvas/elements/BackgroundImageElement.js +0 -37
- package/dist/canvas/elements/MeasurementStampElement.d.ts +0 -13
- package/dist/canvas/elements/MeasurementStampElement.js +0 -30
- package/dist/canvas/elements/ShapeElement.d.ts +0 -7
- package/dist/canvas/elements/ShapeElement.js +0 -62
- package/dist/canvas/elements/StrokeElement.d.ts +0 -7
- package/dist/canvas/elements/StrokeElement.js +0 -18
- package/dist/canvas/measurementPicker.d.ts +0 -10
- package/dist/canvas/measurementPicker.js +0 -1
- package/dist/canvas/measurementStampOverlay.d.ts +0 -11
- package/dist/canvas/measurementStampOverlay.js +0 -1
- package/dist/canvas/pointerAdapter.d.ts +0 -3
- package/dist/canvas/pointerAdapter.js +0 -19
- package/dist/canvas/stampLayout.d.ts +0 -5
- package/dist/canvas/stampLayout.js +0 -14
- package/dist/canvas/tools/measurementStampTool.d.ts +0 -9
- package/dist/canvas/tools/measurementStampTool.js +0 -37
- package/dist/canvas/tools/panTool.d.ts +0 -5
- package/dist/canvas/tools/panTool.js +0 -25
- package/dist/canvas/tools/penTool.d.ts +0 -13
- package/dist/canvas/tools/penTool.js +0 -68
- package/dist/canvas/tools/selectTool.d.ts +0 -2
- package/dist/canvas/tools/selectTool.js +0 -182
- package/dist/canvas/useAnnotationCanvasState.d.ts +0 -54
- package/dist/canvas/useAnnotationCanvasState.js +0 -210
- package/dist/canvas/viewport.d.ts +0 -16
- package/dist/canvas/viewport.js +0 -54
- package/dist/data/AnnotationDataContext.d.ts +0 -8
- package/dist/data/AnnotationDataContext.js +0 -11
- package/dist/data/AnnotationDataProvider.d.ts +0 -65
- package/dist/data/AnnotationDataProvider.js +0 -4
- package/dist/data/InMemoryAnnotationProvider.d.ts +0 -30
- package/dist/data/InMemoryAnnotationProvider.js +0 -197
- package/dist/data/canvasPersistence.d.ts +0 -3
- package/dist/data/canvasPersistence.js +0 -26
- package/dist/data/hooks/useAnnotationCanvasDoc.d.ts +0 -33
- package/dist/data/hooks/useAnnotationCanvasDoc.js +0 -314
- package/dist/data/hooks/useAnnotationDoc.d.ts +0 -7
- package/dist/data/hooks/useAnnotationDoc.js +0 -33
- package/dist/data/hooks/useAnnotationList.d.ts +0 -7
- package/dist/data/hooks/useAnnotationList.js +0 -26
- package/dist/data/hooks/useAnnotationMutations.d.ts +0 -9
- package/dist/data/hooks/useAnnotationMutations.js +0 -11
- package/dist/hooks/useParseMeasurement.d.ts +0 -4
- package/dist/hooks/useParseMeasurement.js +0 -14
- package/dist/utils/evaluateFormula.d.ts +0 -20
- package/dist/utils/evaluateFormula.js +0 -31
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { ColumnType, type ColumnConfig, type ConversionTableColumnData, type InstructionsColumnData, type SelectColumnData, type DecimalTolerance, type FractionalTolerance } from '../types/firestore.js';
|
|
2
|
+
import type { AngleUnit, CalculatorUnit, FieldDimension, MeasurementDimension } from './units.js';
|
|
3
|
+
/**
|
|
4
|
+
* Version of the definition format itself. Bumped only on breaking schema
|
|
5
|
+
* changes; independent of the npm package version and of each calculator's
|
|
6
|
+
* own content `version`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const CALCULATOR_SCHEMA_VERSION = 1;
|
|
9
|
+
/**
|
|
10
|
+
* Which table a field appears in (the Figma mockup's Input Fields / Output
|
|
11
|
+
* Fields split). Mostly cosmetic: an input with solve hints can be computed
|
|
12
|
+
* from outputs at runtime, and outputs are just fields targeted by equations.
|
|
13
|
+
*/
|
|
14
|
+
export type FieldRole = 'input' | 'output';
|
|
15
|
+
/** Field kinds reuse the app-wide ColumnType enum (calculator subset). */
|
|
16
|
+
export type CalculatorFieldKind = ColumnType.Number | ColumnType.Measurement | ColumnType.Angle | ColumnType.SingleSelect | ColumnType.MultiSelect | ColumnType.ConversionTable | ColumnType.Instructions;
|
|
17
|
+
export declare const CALCULATOR_FIELD_KINDS: CalculatorFieldKind[];
|
|
18
|
+
/**
|
|
19
|
+
* Per-field unit configuration (templates have only a global user unit).
|
|
20
|
+
* `dimension` covers the volume-calculator case: inputs in inches, output in
|
|
21
|
+
* cubic feet — each field picks its own dimension and display units.
|
|
22
|
+
*/
|
|
23
|
+
export interface FieldUnitConfig {
|
|
24
|
+
dimension: MeasurementDimension;
|
|
25
|
+
/** Default display unit; must belong to `dimension`. */
|
|
26
|
+
defaultUnit: CalculatorUnit;
|
|
27
|
+
/** Units the runtime lets the user toggle between; must match `dimension`. */
|
|
28
|
+
allowedUnits: CalculatorUnit[];
|
|
29
|
+
fractionalTolerance?: FractionalTolerance;
|
|
30
|
+
decimalTolerance?: DecimalTolerance;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The schema half of two-way solving. A solvable field can be computed by
|
|
34
|
+
* numerically inverting its governing equation when the user supplies that
|
|
35
|
+
* equation's output value instead (see solve.ts). `min`/`max` bracket the
|
|
36
|
+
* root search in CANONICAL units; when absent the solver falls back to
|
|
37
|
+
* generous per-dimension defaults, so brackets are only needed to isolate a
|
|
38
|
+
* specific root (e.g. the positive branch of a quadratic) or to speed search.
|
|
39
|
+
*/
|
|
40
|
+
export interface SolveHints {
|
|
41
|
+
solvable: boolean;
|
|
42
|
+
/** The ONE equation numerically inverted for this field. */
|
|
43
|
+
governingEquationId?: string;
|
|
44
|
+
min?: number;
|
|
45
|
+
max?: number;
|
|
46
|
+
/** Optional Newton seed (canonical units). */
|
|
47
|
+
guess?: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Binds a field to a diagram hotspot. `hotspotId` is the id of the placed
|
|
51
|
+
* canvas tile — the tile itself carries the reverse link by storing the field
|
|
52
|
+
* id in `PlacedMeasurementRef.columnId` (the existing template-canvas
|
|
53
|
+
* column-anchor channel, reused with field-id semantics).
|
|
54
|
+
*/
|
|
55
|
+
export interface DiagramBinding {
|
|
56
|
+
hotspotId: string;
|
|
57
|
+
}
|
|
58
|
+
interface CalculatorFieldBase {
|
|
59
|
+
id: string;
|
|
60
|
+
name: string;
|
|
61
|
+
role: FieldRole;
|
|
62
|
+
description?: string;
|
|
63
|
+
binding?: DiagramBinding;
|
|
64
|
+
}
|
|
65
|
+
export type CalculatorField = CalculatorFieldBase & ({
|
|
66
|
+
kind: ColumnType.Number;
|
|
67
|
+
defaultValue?: number;
|
|
68
|
+
solve?: SolveHints;
|
|
69
|
+
} | {
|
|
70
|
+
kind: ColumnType.Measurement;
|
|
71
|
+
unit: FieldUnitConfig;
|
|
72
|
+
/** Canonical (µm / µm² / µm³ per unit.dimension). */
|
|
73
|
+
defaultValue?: number;
|
|
74
|
+
solve?: SolveHints;
|
|
75
|
+
} | {
|
|
76
|
+
kind: ColumnType.Angle;
|
|
77
|
+
/** Display unit; canonical storage is always degrees. */
|
|
78
|
+
angleUnit?: AngleUnit;
|
|
79
|
+
defaultValue?: number;
|
|
80
|
+
solve?: SolveHints;
|
|
81
|
+
} | {
|
|
82
|
+
kind: ColumnType.SingleSelect;
|
|
83
|
+
columnData: SelectColumnData;
|
|
84
|
+
defaultValue?: string;
|
|
85
|
+
} | {
|
|
86
|
+
kind: ColumnType.MultiSelect;
|
|
87
|
+
columnData: SelectColumnData;
|
|
88
|
+
defaultValue?: string[];
|
|
89
|
+
} | {
|
|
90
|
+
kind: ColumnType.ConversionTable;
|
|
91
|
+
columnData: ConversionTableColumnData;
|
|
92
|
+
/** The selected conversion's label. */
|
|
93
|
+
defaultValue?: string;
|
|
94
|
+
} | {
|
|
95
|
+
kind: ColumnType.Instructions;
|
|
96
|
+
columnData: InstructionsColumnData;
|
|
97
|
+
});
|
|
98
|
+
/**
|
|
99
|
+
* A forward equation computing one output field. Mirrors the existing
|
|
100
|
+
* `Formula` shape (`expression` + variable map), but variables bind to field
|
|
101
|
+
* ids and the equation lives inside the definition rather than in the org
|
|
102
|
+
* `formulas` collection. Variables may reference other OUTPUT fields — their
|
|
103
|
+
* equations are evaluated recursively (cycles are rejected by validation).
|
|
104
|
+
*/
|
|
105
|
+
export interface CalculatorEquation {
|
|
106
|
+
id: string;
|
|
107
|
+
/** The output field this equation computes. */
|
|
108
|
+
targetFieldId: string;
|
|
109
|
+
/** math.js forward expression, e.g. 'A * B * C'. */
|
|
110
|
+
expression: string;
|
|
111
|
+
/** Variable letter -> field id. */
|
|
112
|
+
variableToFieldId: Record<string, string>;
|
|
113
|
+
}
|
|
114
|
+
/** A runtime/preview value for one field, in canonical units. */
|
|
115
|
+
export type CalculatorFieldValue = number | string | string[] | null;
|
|
116
|
+
export type CalculatorValues = Record<string, CalculatorFieldValue>;
|
|
117
|
+
export interface CalculatorDefinition {
|
|
118
|
+
id: string;
|
|
119
|
+
/** CALCULATOR_SCHEMA_VERSION captured at author time. */
|
|
120
|
+
schemaVersion: number;
|
|
121
|
+
/** Monotonic content revision; bumped on publish. Offline-cache key with updatedAt. */
|
|
122
|
+
version: number;
|
|
123
|
+
name: string;
|
|
124
|
+
description: string;
|
|
125
|
+
folderId: string | null;
|
|
126
|
+
/** Inputs + outputs in one list, discriminated by `role`. */
|
|
127
|
+
fields: CalculatorField[];
|
|
128
|
+
equations: CalculatorEquation[];
|
|
129
|
+
/** Diagram file (files subcollection doc carrying the Skia canvas). */
|
|
130
|
+
diagramFileId?: string | null;
|
|
131
|
+
/** Public calculators are readable by everyone; rules/query key. */
|
|
132
|
+
isPublic: boolean;
|
|
133
|
+
sharedUserIds?: string[];
|
|
134
|
+
sharedOrgIds?: string[];
|
|
135
|
+
createdBy?: {
|
|
136
|
+
userId: string;
|
|
137
|
+
firstName?: string;
|
|
138
|
+
lastName?: string;
|
|
139
|
+
};
|
|
140
|
+
createdAt?: Date;
|
|
141
|
+
updatedAt?: Date;
|
|
142
|
+
}
|
|
143
|
+
export declare const fieldsByRole: (definition: Pick<CalculatorDefinition, "fields">, role: FieldRole) => CalculatorField[];
|
|
144
|
+
export declare const findField: (definition: Pick<CalculatorDefinition, "fields">, fieldId: string) => CalculatorField | undefined;
|
|
145
|
+
export declare const findEquation: (definition: Pick<CalculatorDefinition, "equations">, equationId: string) => CalculatorEquation | undefined;
|
|
146
|
+
/** The equation targeting an output field, if any. */
|
|
147
|
+
export declare const equationForField: (definition: Pick<CalculatorDefinition, "equations">, fieldId: string) => CalculatorEquation | undefined;
|
|
148
|
+
/** The dimension a field's numeric value carries. */
|
|
149
|
+
export declare const fieldDimension: (field: CalculatorField) => FieldDimension;
|
|
150
|
+
/** Fields whose value participates in equations as a number. */
|
|
151
|
+
export declare const isNumericFieldKind: (kind: CalculatorFieldKind) => kind is ColumnType.Number | ColumnType.Measurement | ColumnType.Angle | ColumnType.ConversionTable;
|
|
152
|
+
/** Field kinds an equation may target (compute into). */
|
|
153
|
+
export declare const isEquationTargetKind: (kind: CalculatorFieldKind) => kind is ColumnType.Number | ColumnType.Measurement | ColumnType.Angle;
|
|
154
|
+
/**
|
|
155
|
+
* Synthesize a ColumnConfig for a field so the existing table/tile components
|
|
156
|
+
* (built around ColumnConfig) can render calculator fields unchanged.
|
|
157
|
+
*/
|
|
158
|
+
export declare const fieldToColumnConfig: (field: CalculatorField) => ColumnConfig;
|
|
159
|
+
/** Default per-field unit config for a fresh measurement field. */
|
|
160
|
+
export declare const defaultFieldUnitConfig: (dimension?: MeasurementDimension) => FieldUnitConfig;
|
|
161
|
+
/** Seed for the create-new-calculator stub doc (mirrors the template flow). */
|
|
162
|
+
export declare const createEmptyCalculatorDefinition: (id: string) => Omit<CalculatorDefinition, "createdAt" | "updatedAt" | "createdBy">;
|
|
163
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { ColumnType, Units, } from '../types/firestore.js';
|
|
2
|
+
import { unitsForDimension } from './units.js';
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// The Construction Calculator definition — the shared artifact the web
|
|
5
|
+
// authoring tool produces, the mobile runtime interprets, and sync ships.
|
|
6
|
+
//
|
|
7
|
+
// Distinct from the loosely-typed Template/ColumnConfig model, but reuses its
|
|
8
|
+
// vocabulary where it fits: field kinds ARE ColumnType values (subset) and the
|
|
9
|
+
// per-kind payloads reuse the existing column-data shapes, so the table UI
|
|
10
|
+
// and the runtime tiles can share components with templates.
|
|
11
|
+
//
|
|
12
|
+
// CANONICAL VALUES: every numeric value in a definition (defaultValue, solve
|
|
13
|
+
// brackets) and every runtime field value is canonical — µm for length, µm²
|
|
14
|
+
// area, µm³ volume, degrees for angle, raw for dimensionless (see units.ts).
|
|
15
|
+
//
|
|
16
|
+
// EXPRESSION SEMANTICS: equations are math.js expressions evaluated over a
|
|
17
|
+
// canonical scope. Numeric literals inside an expression are therefore
|
|
18
|
+
// canonical too (a bare `2` multiplying a length is a plain scalar; a bare
|
|
19
|
+
// additive length constant would be micrometers). Authors should express
|
|
20
|
+
// length constants as input fields with a defaultValue instead of literals.
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
/**
|
|
23
|
+
* Version of the definition format itself. Bumped only on breaking schema
|
|
24
|
+
* changes; independent of the npm package version and of each calculator's
|
|
25
|
+
* own content `version`.
|
|
26
|
+
*/
|
|
27
|
+
export const CALCULATOR_SCHEMA_VERSION = 1;
|
|
28
|
+
export const CALCULATOR_FIELD_KINDS = [
|
|
29
|
+
ColumnType.Number,
|
|
30
|
+
ColumnType.Measurement,
|
|
31
|
+
ColumnType.Angle,
|
|
32
|
+
ColumnType.SingleSelect,
|
|
33
|
+
ColumnType.MultiSelect,
|
|
34
|
+
ColumnType.ConversionTable,
|
|
35
|
+
ColumnType.Instructions,
|
|
36
|
+
];
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Helpers
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
export const fieldsByRole = (definition, role) => definition.fields.filter((f) => f.role === role);
|
|
41
|
+
export const findField = (definition, fieldId) => definition.fields.find((f) => f.id === fieldId);
|
|
42
|
+
export const findEquation = (definition, equationId) => definition.equations.find((e) => e.id === equationId);
|
|
43
|
+
/** The equation targeting an output field, if any. */
|
|
44
|
+
export const equationForField = (definition, fieldId) => definition.equations.find((e) => e.targetFieldId === fieldId);
|
|
45
|
+
/** The dimension a field's numeric value carries. */
|
|
46
|
+
export const fieldDimension = (field) => {
|
|
47
|
+
switch (field.kind) {
|
|
48
|
+
case ColumnType.Measurement:
|
|
49
|
+
return field.unit.dimension;
|
|
50
|
+
case ColumnType.Angle:
|
|
51
|
+
return 'angle';
|
|
52
|
+
default:
|
|
53
|
+
return 'none';
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
/** Fields whose value participates in equations as a number. */
|
|
57
|
+
export const isNumericFieldKind = (kind) => kind === ColumnType.Number ||
|
|
58
|
+
kind === ColumnType.Measurement ||
|
|
59
|
+
kind === ColumnType.Angle ||
|
|
60
|
+
kind === ColumnType.ConversionTable;
|
|
61
|
+
/** Field kinds an equation may target (compute into). */
|
|
62
|
+
export const isEquationTargetKind = (kind) => kind === ColumnType.Number ||
|
|
63
|
+
kind === ColumnType.Measurement ||
|
|
64
|
+
kind === ColumnType.Angle;
|
|
65
|
+
/**
|
|
66
|
+
* Synthesize a ColumnConfig for a field so the existing table/tile components
|
|
67
|
+
* (built around ColumnConfig) can render calculator fields unchanged.
|
|
68
|
+
*/
|
|
69
|
+
export const fieldToColumnConfig = (field) => {
|
|
70
|
+
switch (field.kind) {
|
|
71
|
+
case ColumnType.SingleSelect:
|
|
72
|
+
return {
|
|
73
|
+
id: field.id,
|
|
74
|
+
name: field.name,
|
|
75
|
+
type: ColumnType.SingleSelect,
|
|
76
|
+
columnData: field.columnData,
|
|
77
|
+
};
|
|
78
|
+
case ColumnType.MultiSelect:
|
|
79
|
+
return {
|
|
80
|
+
id: field.id,
|
|
81
|
+
name: field.name,
|
|
82
|
+
type: ColumnType.MultiSelect,
|
|
83
|
+
columnData: field.columnData,
|
|
84
|
+
};
|
|
85
|
+
case ColumnType.ConversionTable:
|
|
86
|
+
return {
|
|
87
|
+
id: field.id,
|
|
88
|
+
name: field.name,
|
|
89
|
+
type: ColumnType.ConversionTable,
|
|
90
|
+
columnData: field.columnData,
|
|
91
|
+
};
|
|
92
|
+
case ColumnType.Instructions:
|
|
93
|
+
return {
|
|
94
|
+
id: field.id,
|
|
95
|
+
name: field.name,
|
|
96
|
+
type: ColumnType.Instructions,
|
|
97
|
+
columnData: field.columnData,
|
|
98
|
+
};
|
|
99
|
+
case ColumnType.Number:
|
|
100
|
+
return { id: field.id, name: field.name, type: ColumnType.Number };
|
|
101
|
+
case ColumnType.Angle:
|
|
102
|
+
return { id: field.id, name: field.name, type: ColumnType.Angle };
|
|
103
|
+
case ColumnType.Measurement:
|
|
104
|
+
return { id: field.id, name: field.name, type: ColumnType.Measurement };
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
/** Default per-field unit config for a fresh measurement field. */
|
|
108
|
+
export const defaultFieldUnitConfig = (dimension = 'length') => ({
|
|
109
|
+
dimension,
|
|
110
|
+
defaultUnit: dimension === 'length'
|
|
111
|
+
? Units.FractionalInches
|
|
112
|
+
: dimension === 'area'
|
|
113
|
+
? 'sq_ft'
|
|
114
|
+
: 'cu_ft',
|
|
115
|
+
allowedUnits: unitsForDimension(dimension),
|
|
116
|
+
});
|
|
117
|
+
/** Seed for the create-new-calculator stub doc (mirrors the template flow). */
|
|
118
|
+
export const createEmptyCalculatorDefinition = (id) => ({
|
|
119
|
+
id,
|
|
120
|
+
schemaVersion: CALCULATOR_SCHEMA_VERSION,
|
|
121
|
+
version: 0,
|
|
122
|
+
name: '',
|
|
123
|
+
description: '',
|
|
124
|
+
folderId: null,
|
|
125
|
+
fields: [],
|
|
126
|
+
equations: [],
|
|
127
|
+
diagramFileId: null,
|
|
128
|
+
isPublic: false,
|
|
129
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { CalculatorDefinition, CalculatorValues } from './schema.js';
|
|
2
|
+
export type SolveFailure = {
|
|
3
|
+
kind: 'unknown-field';
|
|
4
|
+
} | {
|
|
5
|
+
kind: 'not-solvable';
|
|
6
|
+
} | {
|
|
7
|
+
kind: 'no-governing-equation';
|
|
8
|
+
} | {
|
|
9
|
+
kind: 'missing-target';
|
|
10
|
+
targetFieldId: string;
|
|
11
|
+
} | {
|
|
12
|
+
kind: 'missing-inputs';
|
|
13
|
+
missingFieldIds: string[];
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'invalid-bracket';
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'no-sign-change';
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'eval-error';
|
|
20
|
+
error: string;
|
|
21
|
+
} | {
|
|
22
|
+
kind: 'non-convergent';
|
|
23
|
+
};
|
|
24
|
+
export type SolveResult = {
|
|
25
|
+
ok: true;
|
|
26
|
+
value: number;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
failure: SolveFailure;
|
|
30
|
+
};
|
|
31
|
+
export interface SolveOptions {
|
|
32
|
+
maxIter?: number;
|
|
33
|
+
/** Points probed when the bracket endpoints don't straddle a root. */
|
|
34
|
+
scanSamples?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Numerically solve a solvable field from its governing equation, given the
|
|
38
|
+
* equation's output value (and every other referenced value) in `values`.
|
|
39
|
+
*/
|
|
40
|
+
export declare const solveForField: ({ definition, fieldId, values, options, }: {
|
|
41
|
+
definition: Pick<CalculatorDefinition, "fields" | "equations">;
|
|
42
|
+
fieldId: string;
|
|
43
|
+
/** Canonical values; must include the governing equation's target value. */
|
|
44
|
+
values: CalculatorValues;
|
|
45
|
+
options?: SolveOptions;
|
|
46
|
+
}) => SolveResult;
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { ColumnType } from '../types/firestore.js';
|
|
2
|
+
import { fieldDimension, findEquation, findField } from './schema.js';
|
|
3
|
+
import { evaluateEquation, numericFieldValue } from './evaluate.js';
|
|
4
|
+
// Generous: the alternating secant/bisection worst case over the widest
|
|
5
|
+
// default bracket (volume, [0, 1e30]) needs ~170 halvings-equivalent.
|
|
6
|
+
const DEFAULT_MAX_ITER = 256;
|
|
7
|
+
const DEFAULT_SCAN_SAMPLES = 128;
|
|
8
|
+
// Generous per-dimension fallback brackets so common monotonic equations
|
|
9
|
+
// solve with zero authoring effort; author hints exist to isolate a specific
|
|
10
|
+
// root, not as a prerequisite. Lengths/areas/volumes are non-negative (which
|
|
11
|
+
// also picks the physical branch of even-power equations).
|
|
12
|
+
const DEFAULT_BRACKETS = {
|
|
13
|
+
length: [0, 1e10], // 10 km in µm
|
|
14
|
+
area: [0, 1e20],
|
|
15
|
+
volume: [0, 1e30],
|
|
16
|
+
angle: [-360, 360],
|
|
17
|
+
none: [-1e12, 1e12],
|
|
18
|
+
};
|
|
19
|
+
// Convergence: bracket width below the dimension's absolute floor or a
|
|
20
|
+
// relative epsilon of the estimate, whichever is larger.
|
|
21
|
+
const ABS_TOL = {
|
|
22
|
+
length: 1e-3, // 1 nm — far below any display tolerance
|
|
23
|
+
area: 1e-3,
|
|
24
|
+
volume: 1e-3,
|
|
25
|
+
angle: 1e-9,
|
|
26
|
+
none: 1e-12,
|
|
27
|
+
};
|
|
28
|
+
const REL_TOL = 1e-12;
|
|
29
|
+
/**
|
|
30
|
+
* Numerically solve a solvable field from its governing equation, given the
|
|
31
|
+
* equation's output value (and every other referenced value) in `values`.
|
|
32
|
+
*/
|
|
33
|
+
export const solveForField = ({ definition, fieldId, values, options, }) => {
|
|
34
|
+
const field = findField(definition, fieldId);
|
|
35
|
+
if (!field)
|
|
36
|
+
return { ok: false, failure: { kind: 'unknown-field' } };
|
|
37
|
+
if (field.kind !== ColumnType.Number &&
|
|
38
|
+
field.kind !== ColumnType.Measurement &&
|
|
39
|
+
field.kind !== ColumnType.Angle) {
|
|
40
|
+
return { ok: false, failure: { kind: 'not-solvable' } };
|
|
41
|
+
}
|
|
42
|
+
const hints = field.solve;
|
|
43
|
+
if (!hints?.solvable) {
|
|
44
|
+
return { ok: false, failure: { kind: 'not-solvable' } };
|
|
45
|
+
}
|
|
46
|
+
const equation = hints.governingEquationId
|
|
47
|
+
? findEquation(definition, hints.governingEquationId)
|
|
48
|
+
: undefined;
|
|
49
|
+
if (!equation) {
|
|
50
|
+
return { ok: false, failure: { kind: 'no-governing-equation' } };
|
|
51
|
+
}
|
|
52
|
+
const targetField = findField(definition, equation.targetFieldId);
|
|
53
|
+
const targetValue = targetField
|
|
54
|
+
? numericFieldValue(targetField, values[equation.targetFieldId])
|
|
55
|
+
: null;
|
|
56
|
+
if (targetValue == null) {
|
|
57
|
+
return {
|
|
58
|
+
ok: false,
|
|
59
|
+
failure: {
|
|
60
|
+
kind: 'missing-target',
|
|
61
|
+
targetFieldId: equation.targetFieldId,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
// g(x) — forward value with the unknown pinned to x, minus the target.
|
|
66
|
+
// Returns null at points where the expression is undefined (e.g. a
|
|
67
|
+
// division by zero at x = 0); the search skips such points.
|
|
68
|
+
let lastError = null;
|
|
69
|
+
const g = (x) => {
|
|
70
|
+
const result = evaluateEquation({
|
|
71
|
+
definition,
|
|
72
|
+
equation,
|
|
73
|
+
values: { ...values, [fieldId]: x },
|
|
74
|
+
});
|
|
75
|
+
if (result.ok)
|
|
76
|
+
return result.value - targetValue;
|
|
77
|
+
if (result.reason === 'missing-inputs') {
|
|
78
|
+
// Missing something other than the unknown — not point-dependent, bail.
|
|
79
|
+
throw {
|
|
80
|
+
solveFailure: {
|
|
81
|
+
kind: 'missing-inputs',
|
|
82
|
+
missingFieldIds: result.missingFieldIds.filter((id) => id !== fieldId),
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
lastError = result.error;
|
|
87
|
+
return null;
|
|
88
|
+
};
|
|
89
|
+
const dimension = fieldDimension(field);
|
|
90
|
+
const [defaultLo, defaultHi] = DEFAULT_BRACKETS[dimension];
|
|
91
|
+
const lo0 = hints.min ?? defaultLo;
|
|
92
|
+
const hi0 = hints.max ?? defaultHi;
|
|
93
|
+
if (!Number.isFinite(lo0) || !Number.isFinite(hi0) || lo0 >= hi0) {
|
|
94
|
+
return { ok: false, failure: { kind: 'invalid-bracket' } };
|
|
95
|
+
}
|
|
96
|
+
const residualTol = Math.max(1e-9, Math.abs(targetValue) * 1e-9);
|
|
97
|
+
const absTol = ABS_TOL[dimension];
|
|
98
|
+
const converged = (lo, hi) => hi - lo <= Math.max(absTol, REL_TOL * Math.max(Math.abs(lo), Math.abs(hi)));
|
|
99
|
+
try {
|
|
100
|
+
// --- Find a sign-change bracket -------------------------------------
|
|
101
|
+
let lo = lo0;
|
|
102
|
+
let hi = hi0;
|
|
103
|
+
let gLo = g(lo);
|
|
104
|
+
let gHi = g(hi);
|
|
105
|
+
if (gLo != null && Math.abs(gLo) <= residualTol) {
|
|
106
|
+
return { ok: true, value: lo };
|
|
107
|
+
}
|
|
108
|
+
if (gHi != null && Math.abs(gHi) <= residualTol) {
|
|
109
|
+
return { ok: true, value: hi };
|
|
110
|
+
}
|
|
111
|
+
const straddles = (a, b) => a != null && b != null && Math.sign(a) !== Math.sign(b);
|
|
112
|
+
if (!straddles(gLo, gHi)) {
|
|
113
|
+
// Probe interior points (also around the Newton seed, if given) for an
|
|
114
|
+
// adjacent evaluable pair with opposite signs.
|
|
115
|
+
const samples = options?.scanSamples ?? DEFAULT_SCAN_SAMPLES;
|
|
116
|
+
let found = false;
|
|
117
|
+
let prevX = lo;
|
|
118
|
+
let prevG = gLo;
|
|
119
|
+
for (let i = 1; i <= samples; i++) {
|
|
120
|
+
const x = i === samples ? hi : lo0 + ((hi0 - lo0) * i) / samples;
|
|
121
|
+
const gx = g(x);
|
|
122
|
+
if (gx != null && Math.abs(gx) <= residualTol) {
|
|
123
|
+
return { ok: true, value: x };
|
|
124
|
+
}
|
|
125
|
+
if (straddles(prevG, gx)) {
|
|
126
|
+
lo = prevX;
|
|
127
|
+
hi = x;
|
|
128
|
+
gLo = prevG;
|
|
129
|
+
gHi = gx;
|
|
130
|
+
found = true;
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
if (gx != null) {
|
|
134
|
+
prevX = x;
|
|
135
|
+
prevG = gx;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (!found) {
|
|
139
|
+
return lastError != null && gLo == null && gHi == null
|
|
140
|
+
? { ok: false, failure: { kind: 'eval-error', error: lastError } }
|
|
141
|
+
: { ok: false, failure: { kind: 'no-sign-change' } };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// --- Root refinement: secant (regula falsi) fast-path guarded by ------
|
|
145
|
+
// bisection, so invertible/monotonic equations converge fast and
|
|
146
|
+
// anything pathological still halves the bracket every step.
|
|
147
|
+
const maxIter = options?.maxIter ?? DEFAULT_MAX_ITER;
|
|
148
|
+
for (let iter = 0; iter < maxIter; iter++) {
|
|
149
|
+
if (gLo == null || gHi == null)
|
|
150
|
+
break; // defensive; shouldn't happen
|
|
151
|
+
let x;
|
|
152
|
+
const denom = gHi - gLo;
|
|
153
|
+
if (denom !== 0) {
|
|
154
|
+
// Secant estimate, clamped to the interior of the bracket.
|
|
155
|
+
const secant = hi - (gHi * (hi - lo)) / denom;
|
|
156
|
+
const mid = (lo + hi) / 2;
|
|
157
|
+
x =
|
|
158
|
+
secant > lo && secant < hi
|
|
159
|
+
? // Blend toward bisection to avoid regula-falsi stagnation on
|
|
160
|
+
// one stuck endpoint.
|
|
161
|
+
iter % 2 === 0
|
|
162
|
+
? secant
|
|
163
|
+
: mid
|
|
164
|
+
: mid;
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
x = (lo + hi) / 2;
|
|
168
|
+
}
|
|
169
|
+
const gx = g(x);
|
|
170
|
+
if (gx == null) {
|
|
171
|
+
// Undefined interior point — fall back to plain midpoint stepping
|
|
172
|
+
// toward the evaluable side.
|
|
173
|
+
const mid = (lo + hi) / 2;
|
|
174
|
+
const gMid = x === mid ? gx : g(mid);
|
|
175
|
+
if (gMid == null) {
|
|
176
|
+
return {
|
|
177
|
+
ok: false,
|
|
178
|
+
failure: {
|
|
179
|
+
kind: 'eval-error',
|
|
180
|
+
error: lastError ?? 'Expression undefined inside bracket',
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
x = mid;
|
|
185
|
+
if (Math.sign(gMid) === Math.sign(gLo)) {
|
|
186
|
+
lo = x;
|
|
187
|
+
gLo = gMid;
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
hi = x;
|
|
191
|
+
gHi = gMid;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
if (Math.abs(gx) <= residualTol)
|
|
196
|
+
return { ok: true, value: x };
|
|
197
|
+
if (Math.sign(gx) === Math.sign(gLo)) {
|
|
198
|
+
lo = x;
|
|
199
|
+
gLo = gx;
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
hi = x;
|
|
203
|
+
gHi = gx;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (converged(lo, hi)) {
|
|
207
|
+
return { ok: true, value: (lo + hi) / 2 };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { ok: false, failure: { kind: 'non-convergent' } };
|
|
211
|
+
}
|
|
212
|
+
catch (err) {
|
|
213
|
+
if (err && typeof err === 'object' && 'solveFailure' in err) {
|
|
214
|
+
return {
|
|
215
|
+
ok: false,
|
|
216
|
+
failure: err.solveFailure,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
ok: false,
|
|
221
|
+
failure: {
|
|
222
|
+
kind: 'eval-error',
|
|
223
|
+
error: err instanceof Error ? err.message : String(err),
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { DecimalTolerance, FractionalTolerance, Units } from '../types/firestore.js';
|
|
2
|
+
export type MeasurementDimension = 'length' | 'area' | 'volume';
|
|
3
|
+
export type FieldDimension = MeasurementDimension | 'angle' | 'none';
|
|
4
|
+
export type AreaUnit = 'sq_mm' | 'sq_cm' | 'sq_m' | 'sq_in' | 'sq_ft' | 'sq_yd';
|
|
5
|
+
export type VolumeUnit = 'cu_mm' | 'cu_cm' | 'cu_m' | 'cu_in' | 'cu_ft' | 'cu_yd' | 'liter' | 'gallon';
|
|
6
|
+
export type AngleUnit = 'deg' | 'rad';
|
|
7
|
+
/** Every unit a calculator field may display in. Length reuses `Units`. */
|
|
8
|
+
export type CalculatorUnit = Units | AreaUnit | VolumeUnit | AngleUnit;
|
|
9
|
+
export interface CalculatorUnitInfo {
|
|
10
|
+
dimension: FieldDimension;
|
|
11
|
+
/**
|
|
12
|
+
* Real math.js unit token used for conversion. The fractional/composite
|
|
13
|
+
* length units (`in_frac`, `ft_in_*`) are display-only and collapse to
|
|
14
|
+
* their real unit here (mirrors normalizeUnitForMathJS in evaluateFormula).
|
|
15
|
+
*/
|
|
16
|
+
mathUnit: string;
|
|
17
|
+
/** Short display label, e.g. 'ft³'. */
|
|
18
|
+
label: string;
|
|
19
|
+
}
|
|
20
|
+
export declare const CALCULATOR_UNIT_INFO: Record<CalculatorUnit, CalculatorUnitInfo>;
|
|
21
|
+
/** The math.js token for a dimension's canonical unit. '' for dimensionless. */
|
|
22
|
+
export declare const canonicalMathUnit: (dimension: FieldDimension) => string;
|
|
23
|
+
export declare const unitDimension: (unit: CalculatorUnit) => FieldDimension;
|
|
24
|
+
export declare const unitsForDimension: (dimension: FieldDimension) => CalculatorUnit[];
|
|
25
|
+
/** Short label for a unit ('ft³', 'in', '°'). */
|
|
26
|
+
export declare const calculatorUnitLabel: (unit: CalculatorUnit) => string;
|
|
27
|
+
/** Convert a display-unit numeric value to the dimension's canonical unit. */
|
|
28
|
+
export declare const toCanonical: (value: number, unit: CalculatorUnit) => number;
|
|
29
|
+
/** Convert a canonical value to a display-unit numeric value. */
|
|
30
|
+
export declare const fromCanonical: (value: number, unit: CalculatorUnit) => number;
|
|
31
|
+
/**
|
|
32
|
+
* Parse user input in a display unit into a canonical value. Accepts plain
|
|
33
|
+
* numbers, fractions and mixed numbers ("12 1/2"). Length units additionally
|
|
34
|
+
* accept a trailing unit token (delegated to parseMeasurement). Returns null
|
|
35
|
+
* on unparseable input.
|
|
36
|
+
*/
|
|
37
|
+
export declare const parseToCanonical: (input: string, unit: CalculatorUnit) => number | null;
|
|
38
|
+
export interface FormatTolerances {
|
|
39
|
+
fractionalTolerance?: FractionalTolerance;
|
|
40
|
+
decimalTolerance?: DecimalTolerance;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Format a canonical value for display in the given unit. Lengths delegate to
|
|
44
|
+
* convertMicrometers (the one place that renders fractional-inch / feet-inch
|
|
45
|
+
* strings); other dimensions format decimally per the decimal tolerance.
|
|
46
|
+
*/
|
|
47
|
+
export declare const formatCanonical: (value: number | null | undefined, unit: CalculatorUnit, tolerances?: FormatTolerances) => {
|
|
48
|
+
value: string;
|
|
49
|
+
unit: string;
|
|
50
|
+
};
|