cncjs-conversational 0.1.0 → 0.2.1

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Pedro Paulo Vezza Campos
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pedro Paulo Vezza Campos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -20,9 +20,13 @@ In CNCjs, turn on **Custom Widget** under **Manage Widgets** and set its URL to
20
20
  `/conversational/`. [cncjs-whb04b6-el400-integration](https://github.com/pedropaulovc/cncjs-whb04b6-el400-integration)
21
21
  mounts it for you.
22
22
 
23
- The widget does not send programs to CNCjs yet: use **Download .nc** and load
24
- the file with CNCjs's **Upload G-code**. The page also works on its own; open
25
- `web/index.html` in a browser.
23
+ Open a port in CNCjs, then click **Load in CNCjs**: the program replaces the one
24
+ loaded in CNCjs's workspace, ready for the Visualizer and **Run**. Loading is
25
+ refused while a program is running or paused, since it would stop the job.
26
+ Inside CNCjs the widget uses CNCjs's session token and `/api/gcode`, so it must
27
+ be served by CNCjs (`--mount`) rather than from another address. CNCjs's widget
28
+ sandbox blocks file downloads, so **Download .nc** only appears when the page is
29
+ opened on its own (for example `web/index.html` in a browser).
26
30
 
27
31
  ## Checks
28
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cncjs-conversational",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Conversational programming CNCjs custom widget: face, side face, square up, pockets and bolt circles laid out as a dimensioned sketch.",
5
5
  "keywords": [
6
6
  "cncjs",
package/web/index.html CHANGED
@@ -188,8 +188,10 @@ pre .arc { color: var(--path); }
188
188
  <h2>G-code</h2>
189
189
  <button class="btn" id="copy">Copy</button>
190
190
  <button class="btn primary" id="dl">Download .nc</button>
191
+ <button class="btn primary" id="load" hidden>Load in CNCjs</button>
191
192
  </div>
192
193
  <p class="stats" id="stats"></p>
194
+ <p class="stats" id="cnc-note" aria-live="polite" hidden></p>
193
195
  <pre id="gcode" aria-label="Generated G-code"></pre>
194
196
  </section>
195
197
  </aside>
@@ -1015,6 +1017,7 @@ function render() {
1015
1017
  current = [];
1016
1018
  pre.innerHTML = '<span class="c">(fix the errors on the left to generate code)</span>';
1017
1019
  stats.textContent = '';
1020
+ updateLoad();
1018
1021
  return;
1019
1022
  }
1020
1023
  current = [];
@@ -1025,6 +1028,7 @@ function render() {
1025
1028
  const e = estimate(current);
1026
1029
  const m = Math.floor(e.min), s = Math.round((e.min - m) * 60);
1027
1030
  stats.innerHTML = `<b>${current.length}</b> lines, <b>${Math.round(e.cut)}</b> mm of feed moves, about <b>${m} min ${s} s</b> at the programmed feeds`;
1031
+ updateLoad();
1028
1032
  }
1029
1033
 
1030
1034
  // ---------- wiring ----------
@@ -1058,10 +1062,92 @@ document.getElementById('copy').addEventListener('click', async e => {
1058
1062
  document.getElementById('dl').addEventListener('click', () => {
1059
1063
  const a = document.createElement('a');
1060
1064
  a.href = URL.createObjectURL(new Blob([current.join('\n') + '\n'], { type: 'text/plain' }));
1061
- a.download = `${st.op}.nc`;
1065
+ a.download = programName();
1062
1066
  a.click();
1063
1067
  URL.revokeObjectURL(a.href);
1064
1068
  });
1069
+
1070
+ // ---------- CNCjs custom widget ----------
1071
+ // CNCjs puts its session token on the iframe URL, answers a `connect` message with
1072
+ // { action: { type: 'change', payload: { port, controller } } }, and sizes the
1073
+ // iframe from its body itself. Its sandbox has no allow-downloads, so inside
1074
+ // CNCjs the program goes through /api/gcode instead of a file.
1075
+ const token = new URLSearchParams(location.search).get('token');
1076
+ const sameOriginParent = () => { try { return window.parent.location.origin === location.origin; } catch { return false; } };
1077
+ // standalone: own tab or file; cncjs: served and framed by CNCjs; foreign: framed by CNCjs from another origin
1078
+ const embedding = window.parent === window || !token ? 'standalone' : sameOriginParent() ? 'cncjs' : 'foreign';
1079
+ // load.state: idle | loading | loaded | refused | failed; `program` is the text the message is about
1080
+ const cnc = { token, port: null, load: { state: 'idle', message: '', program: '' } };
1081
+ const programName = () => `${st.op}${st.op === 'square' ? `-setup${st.sq.setup}` : st.op === 'side' ? `-${st.side.side}` : ''}.nc`;
1082
+ const programText = () => current.length ? current.join('\n') + '\n' : '';
1083
+ const setLoad = (state, message = '', program = '') => {
1084
+ // An outcome that arrives after the operator edited the program is still shown once,
1085
+ // marked as describing the earlier version; the next edit clears it.
1086
+ const edited = state !== 'loading' && program !== programText();
1087
+ cnc.load = edited
1088
+ ? { state, message: `${message} (This was the program before your last edit.)`, program: programText() }
1089
+ : { state, message, program };
1090
+ updateLoad();
1091
+ };
1092
+
1093
+ function updateLoad() {
1094
+ const load = document.getElementById('load'), note = document.getElementById('cnc-note');
1095
+ load.hidden = note.hidden = embedding === 'standalone';
1096
+ document.getElementById('dl').hidden = embedding !== 'standalone';
1097
+ if (embedding === 'standalone') return;
1098
+ if (embedding === 'foreign') {
1099
+ load.disabled = true;
1100
+ note.textContent = 'Loading into CNCjs needs the widget served by CNCjs itself (same address and port).';
1101
+ return;
1102
+ }
1103
+ const { load: L } = cnc;
1104
+ // A result describes one program; editing it makes the result stale.
1105
+ if (L.state !== 'idle' && L.state !== 'loading' && L.program !== programText()) cnc.load = { state: 'idle', message: '', program: '' };
1106
+ load.disabled = !current.length || !cnc.port || cnc.load.state === 'loading';
1107
+ note.textContent = cnc.load.state !== 'idle' ? cnc.load.message
1108
+ : cnc.port ? `Port ${cnc.port}: loading replaces the program loaded in CNCjs.` : 'Open a port in CNCjs to load this program.';
1109
+ }
1110
+
1111
+ async function cncjsApi(path, init = {}) {
1112
+ const res = await fetch(path, { ...init, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${cnc.token}` } });
1113
+ const body = await res.json().catch(() => ({}));
1114
+ if (!res.ok) throw new Error(body.msg || `HTTP ${res.status}`);
1115
+ return body;
1116
+ }
1117
+
1118
+ async function loadIntoCncjs() {
1119
+ // Snapshot what is being sent; the port and the editor may change while waiting.
1120
+ const port = cnc.port, name = programName(), program = programText();
1121
+ setLoad('loading', `Loading ${name}…`, program);
1122
+ try {
1123
+ // gcode:load stops CNCjs's workflow, so only load when nothing is running or paused,
1124
+ // the same rule CNCjs's own Upload button follows.
1125
+ const controllers = await cncjsApi('/api/controllers');
1126
+ if (!Array.isArray(controllers)) return setLoad('failed', 'Not loaded: CNCjs did not report its controllers.', program);
1127
+ const workflow = controllers.find(c => c.port === port)?.workflow?.state;
1128
+ if (!workflow) return setLoad('failed', `Not loaded: ${port} is not open in CNCjs.`, program);
1129
+ if (workflow !== 'idle') return setLoad('refused', `Not loaded: a program is ${workflow} on ${port}. Stop it in CNCjs first.`, program);
1130
+ await cncjsApi('/api/gcode', { method: 'POST', body: JSON.stringify({ port, name, gcode: program }) });
1131
+ setLoad('loaded', `Loaded ${name} into CNCjs on ${port}.`, program);
1132
+ } catch (error) {
1133
+ setLoad('failed', `Not loaded: ${error.message}`, program);
1134
+ }
1135
+ }
1136
+
1137
+ if (embedding === 'cncjs') {
1138
+ window.addEventListener('message', e => {
1139
+ if (e.source !== window.parent || e.origin !== location.origin) return;
1140
+ const msg = e.data || {};
1141
+ if (typeof msg.token === 'string' && msg.token) cnc.token = msg.token;
1142
+ const a = msg.action || {};
1143
+ if (a.type !== 'change' || !a.payload || !Object.hasOwn(a.payload, 'port')) return;
1144
+ cnc.port = a.payload.port || null;
1145
+ if (cnc.load.state !== 'loading') cnc.load = { state: 'idle', message: '', program: '' };
1146
+ updateLoad();
1147
+ });
1148
+ document.getElementById('load').addEventListener('click', loadIntoCncjs);
1149
+ window.parent.postMessage({ token: cnc.token, action: { type: 'connect' } }, location.origin);
1150
+ }
1065
1151
  selectOp(st.op);
1066
1152
  </script>
1067
1153
  </body>