dechatter 0.1.1 → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,103 @@
1
+ # Changelog
2
+
3
+ What changed for people who use the dechatter widget and command line. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.0] - 2026-11-12
10
+
11
+ ### Changed
12
+
13
+ - **Breaking:** the spindle motor power is given in horsepower. `spindle_power_w` in
14
+ `[machine]` is now `spindle_power_hp` (1 hp = 745.7 W), and the wizard asks for hp.
15
+ - **Breaking:** sessions from 0.1.x do not load in 0.2.0, in the widget or the command line:
16
+ their setup, plans and results are in the older format. Start a new session for each
17
+ tool. dechatter refuses them with a message that says so: a 0.1.x setup (it has
18
+ `spindle_power_w`) is named as one, and a round in the older format says it was written
19
+ by an older dechatter. A round damaged otherwise is named with its file and the problem.
20
+ - **Breaking:** once a round has been cut (recorded or analysed), the setup can no longer
21
+ change in anything that shapes the cut or its sound: the machine's weight and spindle
22
+ control, the tool, the work material, depth, direction and chip load, the stock length,
23
+ the dwell and the coolant. The wizard and `dechatter plan` refuse such a change and say
24
+ which fields differ. Start a new session for the new setup.
25
+ - Programs are written in the machine's units: on a machine in G20 the program is in
26
+ inches, so a job never switches the machine's units, even one stopped part-way. Comments,
27
+ plans and results stay in millimetres. "Load into cncjs" waits until cncjs reports G20 or
28
+ G21; until it does, you can say which the machine is in.
29
+ - A round planned but not yet run is discarded when the setup changes its program, and the
30
+ widget says so. Plan it again. Program names now carry a short code, so a program loaded
31
+ into cncjs before such a change, or before a widget reload, is not taken for the new one:
32
+ load it again before running it.
33
+ - The machine's speed range and power, the cut's speed and width limits and shallower
34
+ depths, the machine's name, the safe height, clearance, plunge feed, truing width, stock
35
+ width and the planner's settings may change at any time. Cuts outside narrowed limits stay
36
+ in their round but are not recommended, nor are cuts over a lowered power cap, and the
37
+ chip-load sweep is offered only for a cut the power cap leaves room to sweep. A sweep's
38
+ result stays within the power cap as it is now. On the map, a stable cut wider than a narrowed
39
+ width limit counts as stable at the widest width searched; chatter that wide, and cuts at
40
+ speeds outside the limits, are left out. Cuts at the edges of the search, such as a width
41
+ the grid rounds just above the limit, or speeds a coarser speed step no longer reaches,
42
+ keep counting.
43
+ - The setup wizard shows on each step only what has to be answered about the machine, tool
44
+ and stock. Settings with a default or a computed value sit in a collapsed Advanced section,
45
+ showing what an empty entry becomes; a section holding a changed setting opens by itself.
46
+ - The setup cannot be saved while a job runs in cncjs or while a round is being recorded.
47
+
48
+ ### Added
49
+
50
+ - A chip-load sweep after convergence: the widget offers it, and `dechatter plan --sweep`
51
+ plans it. The best stable cut runs again at five chip loads, by default 0.6 to 1.7 times
52
+ the session's, lightest first and inside the power cap. The result, the highest chip load
53
+ that stayed stable with its feed, shows beside the best cuts, in `dechatter report` and in
54
+ the printed report. Its cuts do not change the stability map. The bounds are two new
55
+ planner settings, `chip_load_sweep_low` and `chip_load_sweep_high`.
56
+ - A printable report: one HTML page for Letter or A4 with the recommended cuts per depth
57
+ (feed, removal rate, spindle power), the stability map, every round's passes with
58
+ verdicts set by hand marked, and the setup. The widget offers it on convergence and beside
59
+ the best cuts, exports include it as `report.html`, and `dechatter report <session>
60
+ --html <file> [--units in]` writes it. An export still succeeds, without the report, if
61
+ the report cannot be made.
62
+ - An (i) button on every wizard field with a longer explanation: what it changes, its
63
+ default, and whether it may change after a cut.
64
+
65
+ ### Removed
66
+
67
+ - The "Use mm instead" button and the `G20` line at the end of programs: programs no longer
68
+ change the machine's units, so neither is needed.
69
+
70
+ ### Fixed
71
+
72
+ - A new session could plan round 1 from the example setup when the wizard was cancelled.
73
+ Planning now waits until the setup is filled in, and the widget points to the wizard.
74
+ - Saving a new setup after rounds existed kept rounds planned for the old one.
75
+
76
+ ## [0.1.1] - 2026-11-10
77
+
78
+ ### Changed
79
+
80
+ - No changes to the widget or the command line. The first release published by the release
81
+ workflow, with npm provenance.
82
+
83
+ ## [0.1.0] - 2026-11-10
84
+
85
+ ### Added
86
+
87
+ - Command line: `dechatter init`, `plan`, `analyze`, `report`, `materials` and `widget`.
88
+ Each round of test cuts is a G-code program; a recording of the run is split into passes
89
+ and each is classified as stable or chatter from its sound.
90
+ - A Bayesian stability map over spindle speed and radial width that chooses the next cuts,
91
+ and stops when no cut promises enough extra removal rate.
92
+ - Shallower depths to compare once the deepest one is settled.
93
+ - Manual spindle control: the program stops before each speed for you to set it.
94
+ - The cncjs widget: runs a whole session in the browser (Pyodide), records with the
95
+ browser's microphone while the job runs, loads programs into cncjs, and shows verdicts,
96
+ the stability map and the best cuts. A setup wizard follows the machine's G20/G21 units.
97
+ Sessions export to a zip the command line reads, and import in another browser.
98
+ - Published on npm as `dechatter`, with third-party notices for the bundled Pyodide.
99
+
100
+ [Unreleased]: https://github.com/pedropaulovc/dechatter/compare/v0.2.0...HEAD
101
+ [0.2.0]: https://github.com/pedropaulovc/dechatter/compare/v0.1.1...v0.2.0
102
+ [0.1.1]: https://github.com/pedropaulovc/dechatter/compare/v0.1.0...v0.1.1
103
+ [0.1.0]: https://github.com/pedropaulovc/dechatter/releases/tag/v0.1.0
package/README.md CHANGED
@@ -60,10 +60,31 @@ a page the microphone on those. Then, in the widget:
60
60
  1. Create a session. A short wizard asks for the machine, the tool, the cut and the stock. It
61
61
  shows lengths in inches when the machine is in G20 and in millimetres when it is in G21,
62
62
  or with no machine connected. Its last step holds the planner's settings, which rarely
63
- need changing. Saving from the wizard rewrites the session's setup file without comments.
64
- Programs are always in millimetres (G21); one run on an inch machine switches it back to
65
- G20 before it ends. A job you stop part-way leaves the machine in G21: the wizard keeps
66
- showing inches and tells you to send G20, or you can choose to carry on in mm.
63
+ need changing. Settings with a sensible default or a computed value (the machine's name,
64
+ the holder, the cut's limits and chip load, the program's dwell, clearance, plunge feed,
65
+ truing width and coolant, and the planner) sit in a collapsed Advanced section of their
66
+ step, showing what an empty entry becomes. A section holding a changed setting opens by
67
+ itself. Every field has an (i) button with a longer explanation: what it changes, its
68
+ default, and whether it may change after a cut. Saving from the wizard rewrites the
69
+ session's setup file without comments.
70
+ Programs are written in the machine's units too (G20 or G21, as cncjs reports it), so a
71
+ job never changes them, even one stopped part-way. Their comments, like the plan and the
72
+ results, stay in millimetres.
73
+ Nothing is planned until the wizard has been saved: a new session holds only an example
74
+ setup. Each round keeps a copy of the setup it was planned from. Once a round has been
75
+ cut, the setup can no longer change in anything that shapes the cut or its sound (the
76
+ machine's weight and spindle control, the tool, the work material, depth, direction and
77
+ chip load, the stock length, the dwell and the coolant), since the stability map belongs
78
+ to the setup it was measured with: start a new session instead. What only bounds the
79
+ search may still change (the machine's speed range and power, the cut's speed and width
80
+ limits and shallower depths), as may the machine's name, the safe height, clearance,
81
+ plunge feed, truing width, stock width and the planner's settings. Cuts outside narrowed
82
+ bounds stay in their round but are not recommended, nor are cuts over a lowered power
83
+ cap. On the map, a stable cut wider than a narrowed width limit counts as stable at the
84
+ widest width searched; chatter that wide, and cuts at speeds outside the limits, are left
85
+ out. A round
86
+ planned but not yet run is discarded when the setup changes its program, so the next
87
+ plan uses the new setup. `dechatter plan` refuses the same changes made by hand.
67
88
  2. Plan a round. Round 1 is a coarse grid of speeds and widths.
68
89
  3. Set the work zero at the left end of the stock, on its front face, at the top.
69
90
  4. Load the program into cncjs and press play in cncjs. The widget never starts the machine.
@@ -71,6 +92,15 @@ a page the microphone on those. Then, in the widget:
71
92
  pass as stable or chatter, the stability map and the best cuts so far.
72
93
  6. If your ears disagree with a verdict, change it in the table. Plan the next round and
73
94
  repeat until the widget reports convergence.
95
+ 7. Optionally, plan the chip-load sweep it then offers: the best cut once more at five
96
+ chip loads, from 0.6 to 1.7 times the session's (both Advanced planner settings), lightest
97
+ first and inside the power cap. The result is the highest chip load that stayed stable,
98
+ with its feed. Its cuts do not change the map, which stays at the session's chip load.
99
+ 8. Download the report: one HTML page to print (Letter or A4, black and white) and keep with
100
+ the tool. It holds the recommended cuts per depth with feed, removal rate and spindle
101
+ power, the stability map, every round's passes (marking verdicts set by hand) and the
102
+ setup. Lengths follow the machine's G20/G21, with mm beside. It is offered on convergence
103
+ and any time beside the best cuts.
74
104
 
75
105
  Everything runs in the browser tab. The same Python that the command line uses runs there
76
106
  under [Pyodide](https://pyodide.org), which `dechatter widget` downloads once and copies into
@@ -81,7 +111,7 @@ browser kept any of that processing on.
81
111
 
82
112
  Sessions are stored in that browser (IndexedDB), per cncjs address. Export saves one as a zip
83
113
  holding `setup.toml` and each round's plan, program, `recording.wav`, results and the job
84
- timeline cncjs reported. Import loads it in another browser, and unzipped it is a session
114
+ timeline cncjs reported, plus `report.html`. Import loads it in another browser, and unzipped it is a session
85
115
  folder the command line reads. Keep the tab open while a round runs: the recording lives in
86
116
  the page until the job ends.
87
117
 
@@ -113,7 +143,9 @@ continuous recording, run the program, stop recording after `M30`. Then:
113
143
  ```sh
114
144
  dechatter analyze al-10mm recording.wav # classifies each pass
115
145
  dechatter plan al-10mm # next round, or "converged"
146
+ dechatter plan al-10mm --sweep # once converged: chip-load sweep of the best cut
116
147
  dechatter report al-10mm # stability map and best cuts so far
148
+ dechatter report al-10mm --html al-10mm.html --units in # printable report
117
149
  ```
118
150
 
119
151
  Repeat until `plan` reports convergence. WAV, FLAC, OGG and MP3 load directly. Phone formats
@@ -223,9 +255,17 @@ uv run validation/purdue.py ~/purdue-cache # downloads about 370 MB once
223
255
  `e2e/` runs real cncjs against a simulated Grbl inside WSL, for driving the widget without a
224
256
  machine. See `e2e/README.md`.
225
257
 
226
- To release, set the same version in `pyproject.toml` and `package.json`, merge to `main`, and
227
- push a tag `vX.Y.Z` on that commit. The `release` workflow tests on Linux and Windows, builds
228
- the widget once and publishes that build to npm. npm trusts the workflow itself, so no token
258
+ Every change users can notice adds a line under `## [Unreleased]` in
259
+ [`CHANGELOG.md`](CHANGELOG.md), in the same pull request: what they will notice and, for a
260
+ breaking change, what to do about it.
261
+
262
+ To release, set the same version in `src/dechatter/__init__.py` (`__version__`, which
263
+ `pyproject.toml` reads) and `package.json`, rename `## [Unreleased]` in `CHANGELOG.md` to
264
+ `## [X.Y.Z] - YYYY-MM-DD` above a fresh empty Unreleased section (and update the links at
265
+ its end), merge to `main`, and push a tag `vX.Y.Z` on that commit. The `release` workflow
266
+ refuses a tag without that dated section, tests on Linux and Windows, builds the widget
267
+ once, publishes that build to npm, and creates the GitHub release with the section as its
268
+ notes. npm trusts the workflow itself, so no token
229
269
  is stored; version 0.1.0 was published by hand, because that trust can only be registered
230
270
  for a package that exists.
231
271
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dechatter",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "CNCjs custom widget that finds chatter-free milling speeds, widths and depths from test cuts heard through the microphone.",
5
5
  "keywords": [
6
6
  "cncjs",
@@ -27,6 +27,7 @@
27
27
  },
28
28
  "files": [
29
29
  "web",
30
+ "CHANGELOG.md",
30
31
  "THIRD_PARTY_NOTICES.md"
31
32
  ],
32
33
  "publishConfig": {
package/web/dechatter.zip CHANGED
Binary file
package/web/engine.js CHANGED
@@ -5,7 +5,7 @@ import { loadPyodide } from './pyodide/pyodide.js';
5
5
 
6
6
  const ROOT = '/sessions';
7
7
  // Calls that change files; the filesystem is flushed to IndexedDB after each of them.
8
- const WRITES = new Set(['create', 'save_setup', 'plan', 'record_stop', 'analyze', 'set_verdict', 'import_zip']);
8
+ const WRITES = new Set(['create', 'save_setup', 'plan', 'plan_sweep', 'record_stop', 'analyze', 'set_verdict', 'import_zip']);
9
9
 
10
10
  let pyodide;
11
11
  let call;
package/web/index.html CHANGED
@@ -43,7 +43,6 @@
43
43
  <button id="setup-next" class="primary" type="submit" form="setup-form">Next</button>
44
44
  <button id="cancel-setup" type="button">Cancel</button>
45
45
  <span id="units" class="muted"></span>
46
- <button id="follow-machine" type="button" hidden>Use mm instead</button>
47
46
  </p>
48
47
  </section>
49
48
 
@@ -68,11 +67,12 @@
68
67
  </section>
69
68
 
70
69
  <section id="best-section" hidden>
71
- <h2>Best stable cuts</h2>
70
+ <h2>Best stable cuts <button id="download-report" type="button">Download report</button></h2>
72
71
  <table>
73
72
  <thead><tr><th>rpm</th><th>width</th><th>depth</th><th>feed</th><th>cm³/min</th></tr></thead>
74
73
  <tbody id="best"></tbody>
75
74
  </table>
75
+ <p id="sweep-result" class="muted legend" hidden></p>
76
76
  </section>
77
77
  </div>
78
78
 
package/web/widget.css CHANGED
@@ -14,7 +14,7 @@ header select { flex: 1 1 110px; min-width: 0; }
14
14
  header button { padding: 4px 6px; }
15
15
  #summary { flex-basis: 100%; }
16
16
  #device { max-width: 150px; }
17
- #setup-form label {
17
+ #setup-form .field {
18
18
  display: grid;
19
19
  grid-template-columns: 1fr 96px 44px;
20
20
  gap: 2px 6px;
@@ -25,6 +25,16 @@ header button { padding: 4px 6px; }
25
25
  #setup-form small { color: #777; }
26
26
  #setup-form em { grid-column: 1 / -1; color: #777; font-size: 12px; font-style: normal; }
27
27
  #setup-form input:invalid { border: 1px solid #c9302c; }
28
+ #setup-form details.advanced { margin-top: 4px; }
29
+ #setup-form button.info {
30
+ width: 16px; height: 16px; padding: 0; margin-left: 2px; vertical-align: 1px;
31
+ font: italic bold 11px/14px Georgia, serif; color: #337ab7; border-radius: 50%;
32
+ }
33
+ #setup-form .bubble {
34
+ grid-column: 1 / -1; margin: 2px 0 0; padding: 6px 8px; font-size: 12px; line-height: 1.4;
35
+ background: #f7f7f7; border: 1px solid #ccc; border-radius: 3px;
36
+ }
37
+ #setup-form details.advanced summary { margin-bottom: 6px; color: #555; cursor: pointer; }
28
38
  .wizard-buttons { display: flex; gap: 4px; align-items: center; }
29
39
  .wizard-buttons select { margin-left: auto; }
30
40
  h2 { margin: 14px 0 6px; font-size: 13px; }
package/web/widget.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // and analysis are dechatter's Python running in a worker (engine.js).
4
4
 
5
5
  import { Mic } from './mic.js';
6
- import { STEPS, draw, read } from './wizard.js';
6
+ import { STEPS, draw, placehold, read, reveal } from './wizard.js';
7
7
 
8
8
  const params = new URLSearchParams(location.search);
9
9
  const token = params.get('token') ?? '';
@@ -20,10 +20,7 @@ const UNITS_TEXT = {
20
20
  mm: 'Lengths in mm: the machine is in G21.',
21
21
  in: 'Lengths in inches: the machine is in G20.',
22
22
  unknown: 'Lengths in mm. With the machine connected they follow its G20/G21 mode.',
23
- kept: 'Lengths in inches, as before the stopped job. The machine is now in G21: send G20 to put it back in inches.',
24
23
  };
25
- const KEEP_UNITS_KEY = 'dechatter.keep-units';
26
- const OWN_PROGRAM = /^dechatter-.*\.nc$/; // the names the engine gives its programs
27
24
  const cnc = {
28
25
  socket: null,
29
26
  link: 'connecting', // connecting | no-port | ready | offline
@@ -31,13 +28,10 @@ const cnc = {
31
28
  workflow: null, // idle | running | paused; null until cncjs reports it
32
29
  program: '', // name of the G-code file cncjs has loaded
33
30
  pause: null, // { text, settled } while the program waits at an M0, else null
34
- units: null, // mm | in: how the wizard shows lengths; null until the machine's mode is known
35
- reported: null, // mm | in: the machine's G21/G20 mode as cncjs last reported it
36
- settled: null, // mm | in: the last report taken while no job ran; null until there is one
37
- // in from the start of one of this widget's jobs on an inch machine until the machine is
38
- // back in G20. Stored per machine, so a reload after a stopped job does not forget it.
39
- keep: null,
40
- lines: { received: 0, total: 0 }, // how far cncjs got through the loaded program
31
+ // mm | in: the machine's G21/G20 mode as cncjs last reported it; null until it has. The
32
+ // wizard shows lengths in it and programs are written in it, so a job never changes it.
33
+ units: null,
34
+ loadedUnits: null, // mm | in: the units of the program this widget last loaded into cncjs
41
35
  };
42
36
  const mic = new Mic();
43
37
  let boot = 'Starting'; // what the engine is loading; null once it is ready
@@ -45,7 +39,7 @@ let fatal = ''; // why the engine could not start; nothing works without it
45
39
  let names = []; // sessions stored in this browser
46
40
  let current = localStorage.getItem(SESSION_KEY) ?? '';
47
41
  let state = null; // the current session, as the engine last reported it
48
- let editing = null; // { values, materials, step } while the setup wizard is open, else null
42
+ let editing = null; // { values, defaults, materials, computed, step } while the setup wizard is open, else null
49
43
  let timeline = []; // what cncjs reported since the job last started; saved with the recording
50
44
  let busy = false; // an engine request is in flight
51
45
  let stockChoice = 'same'; // survives redraws: planning on the wrong face position cuts air or too deep
@@ -139,10 +133,36 @@ async function newSession() {
139
133
  // Start the wizard on the session's stored setup. The form is redrawn even when it last
140
134
  // showed this same step, so nothing typed into an earlier wizard is left on screen.
141
135
  async function openWizard() {
142
- editing = { ...(await engine('setup_form', current)), step: 0 };
136
+ editing = { ...(await engine('setup_form', current)), computed: null, step: 0 };
143
137
  $('setup-form').dataset.key = '';
144
138
  }
145
139
 
140
+ // What the planner makes of the entries left empty, from what the wizard holds so far.
141
+ // Only shown as placeholders, filled in when the answer comes: the step is already drawn
142
+ // and may hold typing. Values the wizard cannot make sense of yet show none, and an answer
143
+ // overtaken by a later request is dropped.
144
+ async function preview(wizard) {
145
+ wizard.asked = (wizard.asked ?? 0) + 1;
146
+ const asked = wizard.asked;
147
+ let computed = null;
148
+ try {
149
+ computed = await engine('setup_preview', JSON.stringify(wizard.values));
150
+ } catch {
151
+ computed = null;
152
+ }
153
+ if (editing !== wizard || wizard.asked !== asked) {
154
+ return;
155
+ }
156
+ wizard.computed = computed;
157
+ placehold($('setup-form'), STEPS[wizard.step], units(), wizard);
158
+ }
159
+
160
+ function goToStep(step) {
161
+ editing.step = Math.min(Math.max(step, 0), STEPS.length - 1);
162
+ render();
163
+ preview(editing);
164
+ }
165
+
146
166
  async function editSetup() {
147
167
  try {
148
168
  await openWizard();
@@ -162,12 +182,21 @@ function keepStep() {
162
182
  }
163
183
 
164
184
  async function nextStep() {
185
+ reveal($('setup-form'));
165
186
  if (!$('setup-form').reportValidity()) {
166
187
  return;
167
188
  }
168
189
  keepStep();
169
190
  if (editing.step < STEPS.length - 1) {
170
- editing.step += 1;
191
+ goToStep(editing.step + 1);
192
+ return;
193
+ }
194
+ if (busy) {
195
+ return; // already saving
196
+ }
197
+ // A job may be running one of this session's programs; a new setup could discard it.
198
+ if (cnc.workflow === 'running' || cnc.workflow === 'paused') {
199
+ showError('A job is running in cncjs. Save the setup once it has ended.');
171
200
  render();
172
201
  return;
173
202
  }
@@ -183,24 +212,37 @@ async function nextStep() {
183
212
 
184
213
  function previousStep() {
185
214
  keepStep();
186
- editing.step -= 1;
187
- render();
215
+ goToStep(editing.step - 1);
216
+ }
217
+
218
+ function download(blob, filename) {
219
+ const url = URL.createObjectURL(blob);
220
+ // cncjs sandboxes widget frames without allow-downloads, so the cncjs page itself
221
+ // (same origin) starts the download.
222
+ const host = window.parent.document;
223
+ const link = host.createElement('a');
224
+ link.href = url;
225
+ link.download = filename;
226
+ host.body.append(link);
227
+ link.click();
228
+ link.remove();
229
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
188
230
  }
189
231
 
232
+ // Both carry the report, whose lengths follow the machine's units (mm until known).
190
233
  async function exportSession() {
191
234
  try {
192
- const bytes = await engine('export_zip', current);
193
- const url = URL.createObjectURL(new Blob([bytes], { type: 'application/zip' }));
194
- // cncjs sandboxes widget frames without allow-downloads, so the cncjs page itself
195
- // (same origin) starts the download.
196
- const host = window.parent.document;
197
- const link = host.createElement('a');
198
- link.href = url;
199
- link.download = `${current}.zip`;
200
- host.body.append(link);
201
- link.click();
202
- link.remove();
203
- setTimeout(() => URL.revokeObjectURL(url), 60000);
235
+ const bytes = await engine('export_zip', current, units());
236
+ download(new Blob([bytes], { type: 'application/zip' }), `${current}.zip`);
237
+ } catch (err) {
238
+ showError(err.message);
239
+ }
240
+ }
241
+
242
+ async function downloadReport() {
243
+ try {
244
+ const page = await engine('report_html', current, units());
245
+ download(new Blob([page], { type: 'text/html' }), `${current}-report.html`);
204
246
  } catch (err) {
205
247
  showError(err.message);
206
248
  }
@@ -267,30 +309,16 @@ function note(event, detail) {
267
309
  }
268
310
 
269
311
  function setPort(port) {
270
- cnc.port = port;
271
- cnc.link = port ? 'ready' : 'no-port';
272
- cnc.keep = port ? localStorage.getItem(keepKey()) : null;
273
- if (!port) {
274
- cnc.reported = null;
275
- cnc.settled = null;
312
+ // Another port may be another machine: its units are unknown until cncjs reports them.
313
+ if (port !== cnc.port) {
276
314
  showIn(null);
315
+ cnc.loadedUnits = null;
277
316
  }
317
+ cnc.port = port;
318
+ cnc.link = port ? 'ready' : 'no-port';
278
319
  render();
279
320
  }
280
321
 
281
- function keepKey() {
282
- return `${KEEP_UNITS_KEY}|${cncjsOrigin}|${cnc.port}`;
283
- }
284
-
285
- function hold(units) {
286
- cnc.keep = units;
287
- if (units) {
288
- localStorage.setItem(keepKey(), units);
289
- return;
290
- }
291
- localStorage.removeItem(keepKey());
292
- }
293
-
294
322
  function showIn(next) {
295
323
  if (next === cnc.units) {
296
324
  return;
@@ -301,36 +329,6 @@ function showIn(next) {
301
329
  cnc.units = next;
302
330
  }
303
331
 
304
- // The stopped job left G21 behind and the machine has not gone back to G20 since.
305
- function keptFromStoppedJob() {
306
- return cnc.keep !== null && cnc.workflow === 'idle' && cnc.reported !== null && cnc.reported !== cnc.keep;
307
- }
308
-
309
- // The machine's G20/G21 mode decides how the wizard shows lengths. Programs run in G21 and
310
- // put an inch machine back in G20 as their last step, so a job that ran to its end changes
311
- // nothing. A job stopped part-way leaves G21 behind, which is not the operator's choice: an
312
- // inch machine then stays in inches here until it goes back to G20 or the operator says
313
- // to follow the machine.
314
- function followMachine() {
315
- if (!cnc.reported || cnc.workflow === null) {
316
- return;
317
- }
318
- if (cnc.workflow !== 'idle') {
319
- // cncjs does not refresh the mode during a job; what it repeats right after one is
320
- // still this value, and must not pass for the machine going back to G20.
321
- cnc.settled = cnc.reported;
322
- return;
323
- }
324
- // Only one of this widget's programs ends by restoring G20.
325
- const finished = OWN_PROGRAM.test(cnc.program) && cnc.lines.total > 0 && cnc.lines.received >= cnc.lines.total;
326
- const wentBack = cnc.reported === cnc.keep && cnc.settled !== cnc.reported;
327
- if (cnc.keep && (finished || wentBack)) {
328
- hold(null);
329
- }
330
- cnc.settled = cnc.reported;
331
- showIn(cnc.keep ?? cnc.reported);
332
- }
333
-
334
332
  async function connectCncjs() {
335
333
  try {
336
334
  await loadScript(`${cncjsOrigin}/socket.io/socket.io.js`);
@@ -366,12 +364,11 @@ async function connectCncjs() {
366
364
  });
367
365
  socket.on('gcode:unload', () => {
368
366
  cnc.program = '';
367
+ cnc.loadedUnits = null;
369
368
  render();
370
369
  });
371
370
  socket.on('sender:status', (status) => {
372
371
  cnc.program = status.name ?? cnc.program;
373
- cnc.lines = { received: status.received, total: status.total };
374
- followMachine();
375
372
  note('sender', { sent: status.sent, received: status.received, total: status.total });
376
373
  // A manual-spindle program stops at "M0 (set the spindle to N rpm, then resume)". cncjs
377
374
  // reports the pause as soon as it sends the line; the machine has only stopped once
@@ -389,20 +386,13 @@ async function connectCncjs() {
389
386
  if (workflow === 'running' && cnc.workflow !== 'paused') {
390
387
  timeline = [];
391
388
  }
392
- // Only this widget's programs switch the machine to G21. Another job starting changes
393
- // nothing: the machine is still in the G21 a stopped job left.
394
- if (workflow === 'running' && cnc.workflow === 'idle' && cnc.units === 'in' && OWN_PROGRAM.test(cnc.program)) {
395
- hold('in');
396
- }
397
389
  cnc.workflow = workflow;
398
- followMachine();
399
390
  note('workflow', { state: workflow });
400
391
  syncRecording();
401
392
  render();
402
393
  });
403
394
  socket.on('controller:state', (_type, controller) => {
404
- cnc.reported = MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.reported;
405
- followMachine();
395
+ showIn(MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.units);
406
396
  render();
407
397
  });
408
398
  }
@@ -422,6 +412,12 @@ window.addEventListener('message', (event) => {
422
412
 
423
413
  // ---- recording follows the job ---------------------------------------------------------
424
414
 
415
+ // cncjs holds this round's program as this widget loaded it, in the units the machine
416
+ // reports now. After a reload of the widget the units it was loaded in are unknown.
417
+ function loadedHere(round) {
418
+ return cnc.program === round.program && cnc.loadedUnits !== null && cnc.loadedUnits === cnc.units;
419
+ }
420
+
425
421
  function plannedRound() {
426
422
  const last = state?.rounds.at(-1);
427
423
  return last && !last.analysed ? last : null;
@@ -433,7 +429,11 @@ function syncRecording() {
433
429
  return;
434
430
  }
435
431
  const round = plannedRound();
436
- if (!mic.recording && round && cnc.workflow === 'running' && cnc.program === round.program) {
432
+ if (!mic.recording && round && cnc.workflow === 'running' && cnc.program === round.program && !loadedHere(round)) {
433
+ showError('This run is not recorded: the program in cncjs may be in other units than the machine is in now. Stop the job, load the program again from here, then run it.');
434
+ return;
435
+ }
436
+ if (!mic.recording && round && cnc.workflow === 'running' && loadedHere(round)) {
437
437
  if (!mic.open) {
438
438
  showError('The job is running but the microphone is not open, so this run cannot be analysed. Enable the microphone and run the round again.');
439
439
  return;
@@ -454,13 +454,15 @@ async function loadProgram(round) {
454
454
  try {
455
455
  // Capture has to be running before the job can start; the listener below does not wait.
456
456
  await mic.resume();
457
- const gcode = await engine('program', current, round.round, units());
457
+ const programUnits = cnc.units;
458
+ const gcode = await engine('program', current, round.round, programUnits);
458
459
  await new Promise((resolve, reject) => {
459
460
  cnc.socket.emit('command', cnc.port, 'gcode:load', round.program, gcode, {}, (err) =>
460
461
  err ? reject(new Error(`cncjs could not load the program: ${err.message ?? err}`)) : resolve(),
461
462
  );
462
463
  });
463
464
  cnc.program = round.program;
465
+ cnc.loadedUnits = programUnits;
464
466
  showError('');
465
467
  } catch (err) {
466
468
  showError(err.message);
@@ -528,18 +530,26 @@ function renderSetup() {
528
530
  $('setup-back').hidden = editing.step === 0;
529
531
  $('setup-next').textContent = editing.step === STEPS.length - 1 ? 'Save' : 'Next';
530
532
  $('setup-next').disabled = busy;
531
- const kept = keptFromStoppedJob();
532
- $('units').textContent = UNITS_TEXT[kept ? 'kept' : (cnc.units ?? 'unknown')];
533
- $('follow-machine').hidden = !kept;
533
+ $('units').textContent = UNITS_TEXT[cnc.units ?? 'unknown'];
534
534
  // Redraw the fields only when the step or the machine's units change, so typing is not
535
535
  // interrupted otherwise. A change of units drops an entry that is only half typed.
536
536
  const key = `${current}|${editing.step}|${units()}`;
537
537
  if ($('setup-form').dataset.key !== key) {
538
- draw($('setup-form'), step, editing.values, units(), editing.materials);
538
+ draw($('setup-form'), step, editing.values, units(), editing);
539
539
  $('setup-form').dataset.key = key;
540
540
  }
541
541
  }
542
542
 
543
+ // Planning on the wrong face position cuts air or too deep: the choice survives redraws.
544
+ function stockSelect() {
545
+ const stock = el('select', {}, el('option', { value: 'same' }, 'same block'), el('option', { value: 'fresh' }, 'fresh block, face at Y0'));
546
+ stock.value = stockChoice;
547
+ stock.onchange = () => {
548
+ stockChoice = stock.value;
549
+ };
550
+ return stock;
551
+ }
552
+
543
553
  function renderStep() {
544
554
  const step = $('step');
545
555
  step.replaceChildren();
@@ -563,18 +573,44 @@ function renderStep() {
563
573
  return;
564
574
  }
565
575
 
576
+ if (state.discarded_round !== null) {
577
+ step.append(el('p', {}, `Round ${state.discarded_round} had not been run and was planned from the old setup, so it was discarded.`));
578
+ }
579
+
566
580
  if (state.next === 'converged') {
567
- step.append(el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'));
581
+ step.append(
582
+ el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'),
583
+ el('p', {}, button('Download the report', downloadReport, { className: 'primary' }), ' to print and keep with the tool.'),
584
+ );
585
+ return;
586
+ }
587
+
588
+ if (state.next === 'sweep') {
589
+ const best = state.best[0];
590
+ const stock = stockSelect();
591
+ step.append(
592
+ el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'),
593
+ el('p', {}, `One more round can find how hard the best cut (${best.rpm} rpm, ${best.width_mm.toFixed(2)} mm wide, ${best.depth_mm} mm deep) can be pushed: the same cut at rising chip loads, lightest first. Its cuts do not change the map.`),
594
+ el('p', {}, button('Plan the chip-load sweep', async () => {
595
+ await act('plan_sweep', stockChoice);
596
+ stockChoice = 'same';
597
+ }, { className: 'primary' }), ' on the ', stock),
598
+ el('p', {}, button('Download the report', downloadReport), ' as it stands.'),
599
+ );
600
+ return;
601
+ }
602
+
603
+ if (state.next === 'setup') {
604
+ step.append(
605
+ el('p', {}, 'This session still holds the example setup, not your machine. Fill it in before planning.'),
606
+ el('p', {}, button('Open the setup wizard', editSetup, { className: 'primary' })),
607
+ );
568
608
  return;
569
609
  }
570
610
 
571
611
  if (state.next === 'plan') {
572
612
  const first = state.rounds.length === 0;
573
- const stock = el('select', {}, el('option', { value: 'same' }, 'same block'), el('option', { value: 'fresh' }, 'fresh block, face at Y0'));
574
- stock.value = stockChoice;
575
- stock.onchange = () => {
576
- stockChoice = stock.value;
577
- };
613
+ const stock = stockSelect();
578
614
  const shallower = !first && state.next_depth_mm !== state.depth_mm;
579
615
  const label = `Plan round ${state.rounds.length + 1}${shallower ? ` at ${state.next_depth_mm} mm depth` : ''}`;
580
616
  const plan = button(label, async () => {
@@ -591,18 +627,33 @@ function renderStep() {
591
627
 
592
628
  const tests = round.passes.filter((p) => p.kind === 'test').length;
593
629
  const speedChanges = (r) => r.passes.filter((p, i) => i === 0 || p.rpm !== r.passes[i - 1].rpm).length;
594
- const loaded = cnc.program === round.program;
595
- const ready = cnc.link === 'ready' && cnc.workflow === 'idle' && mic.open;
630
+ const loaded = loadedHere(round);
631
+ // The name matches, but the units it was loaded in differ or are not known: load it again.
632
+ const unsure = cnc.program === round.program && !loaded;
633
+ // The program is written in the machine's units, so they have to be known first.
634
+ const ready = cnc.link === 'ready' && cnc.workflow === 'idle' && cnc.units !== null && mic.open;
596
635
  const load = button(loaded ? 'Reload program' : 'Load into cncjs', () => loadProgram(round), { className: loaded ? '' : 'primary', disabled: !ready });
636
+ // cncjs reports the mode from the controller's parser state. Until it does, the operator
637
+ // can say which it is: the program sets that mode itself, so a wrong choice cannot
638
+ // misplace a cut, only leave the machine in the other mode afterwards.
639
+ const declare = el('select', {}, el('option', { value: '' }, 'machine units?'), el('option', { value: 'mm' }, 'mm (G21)'), el('option', { value: 'in' }, 'inches (G20)'));
640
+ declare.onchange = () => {
641
+ showIn(declare.value || null);
642
+ render();
643
+ };
644
+ const unknownUnits = mic.open && cnc.link === 'ready' && cnc.units === null;
597
645
  step.append(
598
646
  el('p', {}, `Round ${round.round}: ${tests} test cuts ${round.depth_mm} mm deep, about ${minutes(round.run_time_s)} plus rapids. The front face ends at Y${round.face_y_end_mm}.`),
599
647
  el('ol', {},
600
648
  el('li', {}, 'Zero X at the left end of the stock, Y on its front face, Z on top.'),
601
- el('li', {}, load, mic.open ? '' : ' (enable the microphone first)'),
649
+ el('li', {}, load, ...(unknownUnits ? [' cncjs has not reported G20 or G21 yet; the machine is in ', declare] : []), mic.open ? '' : ' (enable the microphone first)'),
602
650
  el('li', {}, loaded ? 'Press play in cncjs. Recording starts and stops with the job. Keep this tab open.' : 'Press play in cncjs.'),
603
651
  ...(state.spindle === 'manual' ? [el('li', {}, `The program pauses before each of its ${speedChanges(round)} spindle speeds. Set the speed shown here, then resume in cncjs.`)] : []),
604
652
  ),
605
653
  );
654
+ if (unsure) {
655
+ step.append(el('p', { className: 'instruction' }, 'cncjs holds this round\'s program, but it was loaded in other units than the machine is in now, or before this widget was reloaded. Load it again before pressing play; a run of it as it is will not be recorded.'));
656
+ }
606
657
  if (round.has_recording) {
607
658
  step.append(el('p', {}, 'The last run could not be analysed. Run the round again, or ', button('Analyse the last recording again', () => act('analyze', round.round))));
608
659
  }
@@ -632,7 +683,8 @@ function renderRound() {
632
683
  if (!round) {
633
684
  return;
634
685
  }
635
- $('round-title').textContent = `Round ${round.round}${round.analysed ? ' results' : ''}, ${round.depth_mm} mm deep`;
686
+ const kind = round.planner === 'sweep' ? ' (chip-load sweep)' : '';
687
+ $('round-title').textContent = `Round ${round.round}${kind}${round.analysed ? ' results' : ''}, ${round.depth_mm} mm deep`;
636
688
  $('passes').replaceChildren(
637
689
  ...round.passes.map((p) =>
638
690
  el('tr', { className: p.kind === 'test' ? '' : 'prep' },
@@ -717,6 +769,15 @@ function renderBest() {
717
769
  ),
718
770
  ),
719
771
  );
772
+ const sweep = state?.sweep;
773
+ $('sweep-result').hidden = !sweep || best.length === 0;
774
+ if (!sweep) {
775
+ return;
776
+ }
777
+ const where = `At ${sweep.rpm} rpm, ${sweep.width_mm.toFixed(2)} mm wide and ${sweep.depth_mm} mm deep`;
778
+ $('sweep-result').textContent = sweep.chip_load_mm === null
779
+ ? `Chip-load sweep: ${where.toLowerCase()}, even its lightest pass chattered. Keep the session's ${sweep.session_chip_load_mm} mm per tooth.`
780
+ : `Chip-load sweep: ${where.toLowerCase()}, the cut stayed stable up to ${sweep.chip_load_mm} mm per tooth (the session used ${sweep.session_chip_load_mm}): feed ${sweep.feed_mm_min} mm/min, ${sweep.mrr_cm3_min.toFixed(2)} cm³/min.`;
720
781
  }
721
782
 
722
783
  function render() {
@@ -746,17 +807,13 @@ $('setup-form').onsubmit = (event) => {
746
807
  event.preventDefault();
747
808
  nextStep();
748
809
  };
749
- $('follow-machine').onclick = () => {
750
- hold(null);
751
- followMachine();
752
- render();
753
- };
754
810
  $('cancel-setup').onclick = () => {
755
811
  editing = null;
756
812
  showError('');
757
813
  render();
758
814
  };
759
815
  $('export').onclick = exportSession;
816
+ $('download-report').onclick = downloadReport;
760
817
  $('import').onclick = () => $('import-file').click();
761
818
  $('import-file').onchange = () => {
762
819
  const [file] = $('import-file').files;
package/web/wizard.js CHANGED
@@ -1,5 +1,8 @@
1
1
  // Setup wizard: the session's setup as five short forms. Values are kept in millimetres, as
2
2
  // the setup file has them; on a machine in inches they are only shown and typed in inches.
3
+ // Each step shows what has to be answered about this machine, tool and stock. Fields in the
4
+ // 'advanced' section (the default is 'basic') have a sensible default or computed value and
5
+ // sit in a collapsed section.
3
6
 
4
7
  const MM_PER_INCH = 25.4;
5
8
  const LENGTH_UNITS = {
@@ -8,15 +11,63 @@ const LENGTH_UNITS = {
8
11
  feed: { mm: 'mm/min', in: 'in/min' },
9
12
  };
10
13
 
14
+ // The longer explanation behind each field's (i) button. An entry is text, or a function of
15
+ // the units lengths are shown in. Every field has one.
16
+ const SPEED_RANGE = 'The speeds this machine really runs at. Test speeds stay inside them. They only bound the search, so they may change after cuts.';
17
+ const FIXED = 'Fixed once a cut is made.';
18
+ const FREE = 'Safe to change after cuts.';
19
+ const INFO = {
20
+ 'machine.name': 'A label for your own records. It changes nothing else.',
21
+ 'machine.max_rpm': SPEED_RANGE,
22
+ 'machine.min_rpm': SPEED_RANGE,
23
+ 'machine.spindle_power_hp': `From the motor plate. It only sets the power cap, which leaves out cuts that would remove metal faster than the spindle can drive. ${FREE}`,
24
+ 'machine.weight_kg': `A lighter machine starts with a lighter chip load: under 150 kg ×0.5, under 400 kg ×0.7, under 1500 kg ×0.85. ${FIXED} It sets the default chip load.`,
25
+ 'machine.spindle': `"By hand": the program stops (M0) before each new speed and the widget shows the rpm to set. The detector allows for the spindle being up to 5% off. Cuts are grouped by speed, so there is one stop per speed. ${FIXED}`,
26
+ 'tool.diameter_mm': `Sets the default chip load and the widest cut tried (half the diameter), and with the cutter material the top speed. ${FIXED}`,
27
+ 'tool.flutes': `Feed = chip load × flutes × rpm, and the detector listens for the tooth-passing frequency. ${FIXED}`,
28
+ 'tool.stickout_mm': 'From the holder face to the cutter tip. Chatter depends strongly on it, so the results apply only at this stickout. Change it and start a new session.',
29
+ 'tool.holder': `Part of the tool assembly: it changes how the tool vibrates. ${FIXED}`,
30
+ 'tool.material': `Sets the top speed: high-speed steel gets 0.3× the carbide surface speed for the work material. ${FIXED}`,
31
+ 'cut.material': `Sets the default chip load, the top surface speed and the power each cut needs. ${FIXED}`,
32
+ 'cut.axial_depth_mm': `The deepest cut to test, from the top of the stock. The face must be clear of jaws and parallels down past this depth, along its whole length and about one cutter radius plus the clearance beyond each end, where the cutter plunges. ${FIXED}`,
33
+ 'cut.other_depths_mm': 'Tested after the deepest depth settles, deepest first. A shallower round leaves the face flat only down to its own depth, so a deeper one after it needs fresh stock.',
34
+ 'cut.direction': `Conventional or climb. The results apply to the direction tested. ${FIXED}`,
35
+ 'cut.width_max_mm': `The widest radial cut tried. Default: half the cutter diameter. ${FREE}`,
36
+ 'cut.chip_load_mm': `Feed per tooth, held constant for the whole session: feed = chip load × flutes × rpm. The default comes from the work material, the cutter diameter and the machine weight. Chatter barely depends on it, so the default is fine for mapping; the chip-load sweep offered once the map converges finds how far the best cut can be pushed. Very light chip loads make narrow cuts rub and squeal, which can pass for chatter. ${FIXED}`,
37
+ 'cut.speed_min_rpm': `The slowest test speed. Default: a quarter of the fastest, and no lower than the machine allows. ${FREE}`,
38
+ 'cut.speed_max_rpm': `The fastest test speed. Default: the machine's top speed or the material's surface-speed limit for this cutter, whichever is lower. ${FREE}`,
39
+ 'stock.length_mm': `Along X. Every pass cuts the full length. Work zero X is the left end. ${FIXED}`,
40
+ 'stock.width_mm': `Along Y: how much the test may cut back from the front face. Work zero Y is the front face as first mounted. ${FREE}`,
41
+ 'program.coolant': `Coolant noise makes chatter harder to hear: none is best for detection. ${FIXED}`,
42
+ 'program.dwell_s': `Before each cut the spindle runs in the air beside the stock, already at depth. That lets it reach speed and records the quiet sound each cut is compared with. Do not shorten it much. With a manual spindle, the time at each M0 stop comes on top. ${FIXED}`,
43
+ 'program.clearance_mm': `The cutter plunges in the air this far beyond the end of the stock, and backs off this far from the face after each cut. The plunge must never touch the stock. ${FREE}`,
44
+ 'program.safe_z_mm': (units) => `Height above the top of the stock (Z0) for every rapid move. Set it above the tallest clamp, jaw, parallel or stop the tool passes over, plus ${units === 'in' ? 'about 0.1 in' : 'a few mm'}, and within the Z travel left above your work zero. ${FREE}`,
45
+ 'program.plunge_feed_mm_min': `The feed of the plunge from the clearance height down to depth, in the air beside the stock. ${FREE}`,
46
+ 'program.truing_width_mm': `A light first pass that leaves the face flat, at a known position, before the test cuts. ${FREE}`,
47
+ 'planner.round1_speeds': 'More speeds in round 1 find the stable pockets sooner, but take more cuts and more stock.',
48
+ 'planner.round1_width_fractions': 'Round 1 cuts each speed at these widths, as fractions of the widest cut. Wider fractions learn more per cut but chatter more often.',
49
+ 'planner.batch_size': 'More cuts per round means fewer rounds, but each round leans on guesses the earlier cuts of the same round have not confirmed.',
50
+ 'planner.min_probability': 'Higher is more cautious: smaller steps, fewer cuts that chatter, more rounds. The defaults suit most sessions.',
51
+ 'planner.probability_floor': 'The same, judged on measured cuts only, ignoring the round\'s own earlier cuts. Higher is more cautious.',
52
+ 'planner.stop_improvement': 'Lower keeps searching for smaller gains, at the cost of more rounds.',
53
+ 'planner.chip_load_sweep_low': 'Once the map converges, the best cut can be run again at 5 chip loads, lightest first, from this many times the session\'s chip load up to the next setting. The power cap trims the heaviest. The result is the highest chip load that stayed stable. Its cuts do not change the map.',
54
+ 'planner.chip_load_sweep_high': 'The heaviest chip load of the sweep, as a multiple of the session\'s. Higher finds the limit of a stout tool, but the last passes may chatter hard: watch them, and feed-hold if a cut gets violent.',
55
+ };
56
+
57
+ export const infoFor = (field, units) => {
58
+ const text = INFO[field.at];
59
+ return typeof text === 'function' ? text(units) : text;
60
+ };
61
+
11
62
  export const STEPS = [
12
63
  {
13
64
  title: 'Machine',
14
65
  hint: 'The mill this tool runs in.',
15
66
  fields: [
16
- { at: 'machine.name', label: 'Name', type: 'text', optional: true },
67
+ { at: 'machine.name', section: 'advanced', label: 'Name', type: 'text', optional: true },
17
68
  { at: 'machine.max_rpm', label: 'Highest spindle speed', type: 'int', unit: 'rpm' },
18
69
  { at: 'machine.min_rpm', label: 'Lowest usable spindle speed', type: 'int', unit: 'rpm' },
19
- { at: 'machine.spindle_power_w', label: 'Spindle motor power', type: 'number', unit: 'W' },
70
+ { at: 'machine.spindle_power_hp', label: 'Spindle motor power', type: 'number', unit: 'hp' },
20
71
  { at: 'machine.weight_kg', label: 'Machine weight', type: 'number', unit: 'kg', note: 'Light machines start with a lighter chip load.' },
21
72
  {
22
73
  at: 'machine.spindle',
@@ -34,7 +85,7 @@ export const STEPS = [
34
85
  { at: 'tool.diameter_mm', label: 'Cutter diameter', type: 'length' },
35
86
  { at: 'tool.flutes', label: 'Flutes', type: 'int' },
36
87
  { at: 'tool.stickout_mm', label: 'Stickout from the holder', type: 'length' },
37
- { at: 'tool.holder', label: 'Holder', type: 'text', optional: true },
88
+ { at: 'tool.holder', section: 'advanced', label: 'Holder', type: 'text', optional: true },
38
89
  { at: 'tool.material', label: 'Cutter material', type: 'choice', options: [['carbide', 'carbide'], ['hss', 'high-speed steel']] },
39
90
  ],
40
91
  },
@@ -46,10 +97,10 @@ export const STEPS = [
46
97
  { at: 'cut.axial_depth_mm', label: 'Axial depth of cut', type: 'length', note: 'The deepest cut you want. It is tested first.' },
47
98
  { at: 'cut.other_depths_mm', label: 'Shallower depths to compare', type: 'lengths', optional: true, placeholder: 'none', note: 'Separated by commas. Tested afterwards, starting from the widths that were stable.' },
48
99
  { at: 'cut.direction', label: 'Direction', type: 'choice', options: [['conventional', 'conventional'], ['climb', 'climb']] },
49
- { at: 'cut.width_max_mm', label: 'Widest radial cut to try', type: 'length', optional: true, placeholder: 'half the diameter' },
50
- { at: 'cut.chip_load_mm', label: 'Chip load per tooth', type: 'length', optional: true, placeholder: 'from the material' },
51
- { at: 'cut.speed_min_rpm', label: 'Slowest speed to try', type: 'int', unit: 'rpm', optional: true, placeholder: 'a quarter of the fastest' },
52
- { at: 'cut.speed_max_rpm', label: 'Fastest speed to try', type: 'int', unit: 'rpm', optional: true, placeholder: 'machine or material limit' },
100
+ { at: 'cut.width_max_mm', section: 'advanced', label: 'Widest radial cut to try', type: 'length', optional: true, placeholder: 'half the diameter' },
101
+ { at: 'cut.chip_load_mm', section: 'advanced', label: 'Chip load per tooth', type: 'length', optional: true, placeholder: 'from the material' },
102
+ { at: 'cut.speed_min_rpm', section: 'advanced', label: 'Slowest speed to try', type: 'int', unit: 'rpm', optional: true, placeholder: 'a quarter of the fastest' },
103
+ { at: 'cut.speed_max_rpm', section: 'advanced', label: 'Fastest speed to try', type: 'int', unit: 'rpm', optional: true, placeholder: 'machine or material limit' },
53
104
  ],
54
105
  },
55
106
  {
@@ -58,24 +109,26 @@ export const STEPS = [
58
109
  fields: [
59
110
  { at: 'stock.length_mm', label: 'Stock length (X)', type: 'length', note: 'Every pass cuts the full length.' },
60
111
  { at: 'stock.width_mm', label: 'Stock width to use (Y)', type: 'length', note: 'Material the test may consume from the front face.' },
61
- { at: 'program.coolant', label: 'Coolant', type: 'choice', options: [['none', 'none'], ['flood', 'flood'], ['mist', 'mist']], note: 'Coolant noise makes chatter harder to hear.' },
62
- { at: 'program.dwell_s', label: 'Pause at speed before each pass', type: 'number', unit: 's' },
63
- { at: 'program.clearance_mm', label: 'Clearance around the stock', type: 'length' },
112
+ { at: 'program.coolant', section: 'advanced', label: 'Coolant', type: 'choice', options: [['none', 'none'], ['flood', 'flood'], ['mist', 'mist']], note: 'Coolant noise makes chatter harder to hear.' },
113
+ { at: 'program.dwell_s', section: 'advanced', label: 'Pause at speed before each pass', type: 'number', unit: 's' },
114
+ { at: 'program.clearance_mm', section: 'advanced', label: 'Clearance around the stock', type: 'length' },
64
115
  { at: 'program.safe_z_mm', label: 'Safe height (Z)', type: 'length' },
65
- { at: 'program.plunge_feed_mm_min', label: 'Plunge feed', type: 'feed' },
66
- { at: 'program.truing_width_mm', label: 'Truing pass width', type: 'length' },
116
+ { at: 'program.plunge_feed_mm_min', section: 'advanced', label: 'Plunge feed', type: 'feed' },
117
+ { at: 'program.truing_width_mm', section: 'advanced', label: 'Truing pass width', type: 'length' },
67
118
  ],
68
119
  },
69
120
  {
70
121
  title: 'Planner',
71
122
  hint: 'How boldly the next cuts are chosen. The defaults suit most sessions.',
72
123
  fields: [
73
- { at: 'planner.round1_speeds', label: 'Speeds in round 1', type: 'int' },
74
- { at: 'planner.round1_width_fractions', label: 'Round 1 widths', type: 'list', note: 'Fractions of the widest radial cut, separated by commas.' },
75
- { at: 'planner.batch_size', label: 'Most cuts in a later round', type: 'int' },
76
- { at: 'planner.min_probability', label: 'Chance of being stable a cut needs', type: 'number', note: 'Assuming the cut before it passes. Between 0 and 1.' },
77
- { at: 'planner.probability_floor', label: 'The same, on measured cuts alone', type: 'number' },
78
- { at: 'planner.stop_improvement', label: 'Stop when a cut would add less than', type: 'number', note: 'As a fraction of the best removal rate so far.' },
124
+ { at: 'planner.round1_speeds', section: 'advanced', label: 'Speeds in round 1', type: 'int' },
125
+ { at: 'planner.round1_width_fractions', section: 'advanced', label: 'Round 1 widths', type: 'list', note: 'Fractions of the widest radial cut, separated by commas.' },
126
+ { at: 'planner.batch_size', section: 'advanced', label: 'Most cuts in a later round', type: 'int' },
127
+ { at: 'planner.min_probability', section: 'advanced', label: 'Chance of being stable a cut needs', type: 'number', note: 'Assuming the cut before it passes. Between 0 and 1.' },
128
+ { at: 'planner.probability_floor', section: 'advanced', label: 'The same, on measured cuts alone', type: 'number' },
129
+ { at: 'planner.stop_improvement', section: 'advanced', label: 'Stop when a cut would add less than', type: 'number', note: 'As a fraction of the best removal rate so far.' },
130
+ { at: 'planner.chip_load_sweep_low', section: 'advanced', label: 'Chip-load sweep from', type: 'number', unit: '×', note: 'Times the session\'s chip load.' },
131
+ { at: 'planner.chip_load_sweep_high', section: 'advanced', label: 'Chip-load sweep up to', type: 'number', unit: '×' },
79
132
  ],
80
133
  },
81
134
  ];
@@ -104,7 +157,8 @@ function typed(field, text, units) {
104
157
  return text.trim();
105
158
  }
106
159
  if (field.type === 'list') {
107
- return text.split(',').map((part) => Number(part.trim()));
160
+ // Empty: the default applies.
161
+ return text.trim() === '' ? null : text.split(',').map((part) => Number(part.trim()));
108
162
  }
109
163
  if (field.type === 'lengths') {
110
164
  const lengths = text.trim() === '' ? [] : text.split(',').map((part) => Number(part.trim()));
@@ -123,7 +177,7 @@ function typed(field, text, units) {
123
177
  return number;
124
178
  }
125
179
 
126
- function control(field, value, units, materials) {
180
+ function control(field, value, units, materials, placeholder, optional) {
127
181
  if (field.type === 'choice') {
128
182
  const options = field.options === 'materials' ? materials.map((name) => [name, name]) : field.options;
129
183
  const select = document.createElement('select');
@@ -133,8 +187,8 @@ function control(field, value, units, materials) {
133
187
  }
134
188
  const input = document.createElement('input');
135
189
  input.value = shown(field, value, units);
136
- input.required = !field.optional;
137
- input.placeholder = field.placeholder ?? '';
190
+ input.required = !optional;
191
+ input.placeholder = placeholder;
138
192
  if (field.type === 'list' || field.type === 'lengths') {
139
193
  input.pattern = String.raw`\s*\d*\.?\d+(\s*,\s*\d*\.?\d+)*\s*`;
140
194
  input.title = 'Numbers separated by commas';
@@ -149,29 +203,139 @@ function control(field, value, units, materials) {
149
203
  return input;
150
204
  }
151
205
 
152
- // Fill `form` with the fields of one step.
153
- export function draw(form, step, values, units, materials) {
154
- form.replaceChildren(
155
- ...step.fields.map((field) => {
156
- const [section, key] = field.at.split('.');
157
- const input = control(field, values[section][key], units, materials);
158
- input.name = field.at;
159
- // What the user was shown. Only a field they change is written back: a length
160
- // shown rounded in inches must not come back as a slightly different length.
161
- input.dataset.shown = input.value;
162
- const row = document.createElement('label');
163
- const unit = LENGTH_UNITS[field.type]?.[units] ?? field.unit ?? '';
164
- row.append(
165
- Object.assign(document.createElement('span'), { textContent: field.label }),
166
- input,
167
- Object.assign(document.createElement('small'), { textContent: unit }),
168
- );
169
- if (field.note) {
170
- row.append(Object.assign(document.createElement('em'), { textContent: field.note }));
171
- }
172
- return row;
173
- }),
206
+ const has = (object, key) => Object.prototype.hasOwnProperty.call(object ?? {}, key);
207
+
208
+ // `setup` holds the form's choices besides the values: `materials`, the setup's `defaults`
209
+ // and, where known, the `computed` values the planner uses for entries left empty.
210
+ const advanced = (field) => (field.section ?? 'basic') === 'advanced';
211
+
212
+ // What an entry left empty becomes: the planner's computed value, or the default.
213
+ function placeholderFor(field, units, setup) {
214
+ const [section, key] = field.at.split('.');
215
+ const computed = setup.computed?.[section]?.[key];
216
+ const fallback = computed ?? (has(setup.defaults[section], key) ? setup.defaults[section][key] : null);
217
+ return fallback === null || fallback === '' ? (field.placeholder ?? '') : shown(field, fallback, units);
218
+ }
219
+
220
+ function row(field, values, units, setup) {
221
+ const [section, key] = field.at.split('.');
222
+ const placeholder = placeholderFor(field, units, setup);
223
+ const optional = field.optional || (advanced(field) && has(setup.defaults[section], key));
224
+ const input = control(field, values[section][key], units, setup.materials, placeholder, optional);
225
+ input.name = field.at;
226
+ // What the user was shown. Only a field they change is written back: a length
227
+ // shown rounded in inches must not come back as a slightly different length.
228
+ input.dataset.shown = input.value;
229
+ const id = field.at.replace('.', '-');
230
+ input.id = `field-${id}`;
231
+ const unit = LENGTH_UNITS[field.type]?.[units] ?? field.unit ?? '';
232
+ const bubble = Object.assign(document.createElement('p'), {
233
+ className: 'bubble',
234
+ id: `info-${id}`,
235
+ hidden: true,
236
+ textContent: infoFor(field, units),
237
+ });
238
+ bubble.setAttribute('role', 'note');
239
+ const about = Object.assign(document.createElement('button'), { type: 'button', className: 'info', textContent: 'i' });
240
+ about.setAttribute('aria-label', `About ${field.label}`);
241
+ about.setAttribute('aria-expanded', 'false');
242
+ about.setAttribute('aria-controls', bubble.id);
243
+ about.onclick = () => toggle(about, bubble);
244
+ // The label names only the input; the (i) button and its bubble sit beside it.
245
+ const label = Object.assign(document.createElement('label'), { htmlFor: input.id, textContent: field.label });
246
+ const name = document.createElement('span');
247
+ name.append(label, ' ', about);
248
+ const row = Object.assign(document.createElement('div'), { className: 'field' });
249
+ row.append(name, input, Object.assign(document.createElement('small'), { textContent: unit }));
250
+ if (field.note) {
251
+ row.append(Object.assign(document.createElement('em'), { textContent: field.note }));
252
+ }
253
+ row.append(bubble);
254
+ return row;
255
+ }
256
+
257
+ // One info bubble open at a time. It closes on its button, Escape, or a click elsewhere.
258
+ let openInfo = null; // { about, bubble } while a bubble is open
259
+
260
+ function closeInfo() {
261
+ if (openInfo === null) {
262
+ return;
263
+ }
264
+ openInfo.bubble.hidden = true;
265
+ openInfo.about.setAttribute('aria-expanded', 'false');
266
+ openInfo = null;
267
+ }
268
+
269
+ function toggle(about, bubble) {
270
+ const wasOpen = openInfo?.bubble === bubble;
271
+ closeInfo();
272
+ if (wasOpen) {
273
+ return;
274
+ }
275
+ bubble.hidden = false;
276
+ about.setAttribute('aria-expanded', 'true');
277
+ openInfo = { about, bubble };
278
+ }
279
+
280
+ document.addEventListener('keydown', (event) => {
281
+ if (event.key !== 'Escape' || openInfo === null) {
282
+ return;
283
+ }
284
+ const { about } = openInfo;
285
+ closeInfo();
286
+ about.focus();
287
+ });
288
+ document.addEventListener('click', (event) => {
289
+ if (openInfo !== null && !openInfo.bubble.contains(event.target) && !openInfo.about.contains(event.target)) {
290
+ closeInfo();
291
+ }
292
+ });
293
+
294
+ // Whether a field holds something other than its default, so it must not stay hidden.
295
+ function changed(field, values, defaults) {
296
+ const [section, key] = field.at.split('.');
297
+ const fallback = has(defaults[section], key) ? defaults[section][key] : null;
298
+ return JSON.stringify(values[section][key] ?? null) !== JSON.stringify(fallback);
299
+ }
300
+
301
+ // Fill `form` with the fields of one step: the ones to answer, then the advanced ones in a
302
+ // section that starts open when any of them differs from its default.
303
+ export function draw(form, step, values, units, setup) {
304
+ closeInfo();
305
+ const basic = step.fields.filter((field) => !advanced(field));
306
+ const more = step.fields.filter(advanced);
307
+ form.replaceChildren(...basic.map((field) => row(field, values, units, setup)));
308
+ if (more.length === 0) {
309
+ return;
310
+ }
311
+ const details = document.createElement('details');
312
+ details.className = 'advanced';
313
+ details.open = more.some((field) => changed(field, values, setup.defaults));
314
+ details.append(
315
+ Object.assign(document.createElement('summary'), { textContent: 'Advanced' }),
316
+ ...more.map((field) => row(field, values, units, setup)),
174
317
  );
318
+ form.append(details);
319
+ }
320
+
321
+ // Refresh the placeholders of a step already drawn, keeping whatever was typed.
322
+ export function placehold(form, step, units, setup) {
323
+ for (const field of step.fields) {
324
+ const input = form.elements[field.at];
325
+ if (input?.tagName === 'INPUT') {
326
+ input.placeholder = placeholderFor(field, units, setup);
327
+ }
328
+ }
329
+ }
330
+
331
+ // Open the advanced section when it holds an entry the browser would refuse, so the
332
+ // browser can point at it.
333
+ export function reveal(form) {
334
+ for (const details of form.querySelectorAll('details')) {
335
+ if (details.querySelector(':invalid')) {
336
+ details.open = true;
337
+ }
338
+ }
175
339
  }
176
340
 
177
341
  // Copy what the form shows back into `values`.