@printhive/react 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,901 @@
1
+ import {
2
+ FilamentManagementError,
3
+ requirePrinterLayout
4
+ } from "./chunk-RY4P4TFQ.js";
5
+
6
+ // src/FilamentManagement.tsx
7
+ import { useState as useState4 } from "react";
8
+ import {
9
+ QueryClientProvider,
10
+ useIsMutating as useIsMutating2,
11
+ useQuery as useQuery2
12
+ } from "@tanstack/react-query";
13
+ import { Button as Button3 } from "@ui-sdk/react/button";
14
+ import {
15
+ Dialog,
16
+ DialogBackdrop,
17
+ DialogClose as DialogClose2,
18
+ DialogContent,
19
+ DialogDescription as DialogDescription2,
20
+ DialogTitle as DialogTitle2,
21
+ DialogTrigger
22
+ } from "@ui-sdk/react/dialog";
23
+
24
+ // src/presentation.ts
25
+ function layoutSlots(layout) {
26
+ return [
27
+ ...layout.nozzles.flatMap(
28
+ (nozzle) => nozzle.sources.flatMap((source) => source.slots)
29
+ ),
30
+ ...layout.unboundSources.flatMap((source) => source.slots),
31
+ ...layout.unmappedAssignments
32
+ ];
33
+ }
34
+ function slotContext(layout, slotId) {
35
+ for (const nozzle of layout.nozzles) {
36
+ for (const source of nozzle.sources) {
37
+ if (source.slots.some((slot) => slot.id === slotId)) {
38
+ return layout.nozzles.length > 1 ? `${nozzle.label} \xB7 ${source.label}` : source.label;
39
+ }
40
+ }
41
+ }
42
+ return layout.unboundSources.find(
43
+ (source) => source.slots.some((slot) => slot.id === slotId)
44
+ )?.label ?? "Saved assignments";
45
+ }
46
+ function slotStatus(slot) {
47
+ if (slot.reading) return "Reading RFID";
48
+ if (slot.feeding) return "Feeding nozzle";
49
+ switch (slot.presentation) {
50
+ case "synced":
51
+ return "Matches printer";
52
+ case "mismatch":
53
+ return "Different from printer";
54
+ case "assigned-empty":
55
+ return "Assigned, no filament detected";
56
+ case "assigned-unknown":
57
+ return "Assignment saved, presence unknown";
58
+ case "presence-unknown":
59
+ return "Filament presence unknown";
60
+ case "printer-only":
61
+ return "Reported by printer, not assigned";
62
+ case "empty":
63
+ return "No filament detected";
64
+ }
65
+ }
66
+ function fillStyle(colors, kind) {
67
+ if (colors.length === 0) return {};
68
+ if (colors.length === 1) return { backgroundColor: colors[0] };
69
+ const stops = kind && kind !== "gradient" ? colors.map(
70
+ (color, index) => `${color} ${index / colors.length * 100}% ${(index + 1) / colors.length * 100}%`
71
+ ) : colors;
72
+ return { backgroundImage: `linear-gradient(135deg, ${stops.join(", ")})` };
73
+ }
74
+ function assignmentNotice(result) {
75
+ const slot = result.slots[0];
76
+ if (!slot || slot.record !== "saved") {
77
+ return {
78
+ tone: "error",
79
+ message: "The assignment was not saved. Refresh this printer before trying again; its metadata may have changed."
80
+ };
81
+ }
82
+ if (slot.printerSync.status === "failed") {
83
+ return {
84
+ tone: "warning",
85
+ message: "Assignment saved in PrintHive. The printer metadata request could not be confirmed."
86
+ };
87
+ }
88
+ if (slot.printerSync.status === "skipped") {
89
+ return {
90
+ tone: "success",
91
+ message: "Assignment saved in PrintHive. Printer metadata was not changed."
92
+ };
93
+ }
94
+ if (slot.observation?.status === "observed") {
95
+ return {
96
+ tone: "success",
97
+ message: "Assignment saved and confirmed by the printer."
98
+ };
99
+ }
100
+ if (slot.observation?.status === "mismatch") {
101
+ return {
102
+ tone: "warning",
103
+ message: "Assignment saved. The printer still reports different filament."
104
+ };
105
+ }
106
+ return {
107
+ tone: "success",
108
+ message: "Assignment saved. Metadata request sent; printer confirmation is still pending."
109
+ };
110
+ }
111
+ function clearNotice(result) {
112
+ return result.slots.some((slot) => slot.record === "cleared") ? {
113
+ tone: "success",
114
+ message: "Assignment cleared. Printer metadata was not changed."
115
+ } : {
116
+ tone: "success",
117
+ message: "No saved assignment remained. Printer metadata was not changed."
118
+ };
119
+ }
120
+ function rfidNotice(result) {
121
+ switch (result.printerSync.status) {
122
+ case "failed":
123
+ return {
124
+ tone: "warning",
125
+ message: "The RFID request could not be confirmed. Refresh this printer before trying again."
126
+ };
127
+ case "skipped":
128
+ return {
129
+ tone: "warning",
130
+ message: "The RFID reread was not requested. Refresh this printer to check which actions are available."
131
+ };
132
+ case "sent":
133
+ return {
134
+ tone: "success",
135
+ message: "RFID reread requested. A completed tag read has not yet been confirmed."
136
+ };
137
+ }
138
+ }
139
+
140
+ // src/provider.tsx
141
+ import { createContext, useContext, useState } from "react";
142
+ import { QueryClient } from "@tanstack/react-query";
143
+ import { jsx } from "react/jsx-runtime";
144
+ var DataSourceContext = createContext(null);
145
+ function PrintHiveProvider({
146
+ dataSource,
147
+ children
148
+ }) {
149
+ const [scope, setScope] = useState(() => ({
150
+ dataSource,
151
+ queryClient: createQueryClient()
152
+ }));
153
+ if (scope.dataSource !== dataSource) {
154
+ setScope({ dataSource, queryClient: createQueryClient() });
155
+ }
156
+ return /* @__PURE__ */ jsx(DataSourceContext, { value: scope, children });
157
+ }
158
+ function createQueryClient() {
159
+ return new QueryClient({
160
+ defaultOptions: {
161
+ queries: { retry: false, refetchOnWindowFocus: false, gcTime: 0 },
162
+ mutations: { retry: false }
163
+ }
164
+ });
165
+ }
166
+ function useFilamentRuntime() {
167
+ const source = useContext(DataSourceContext);
168
+ if (source === null) {
169
+ throw new Error("FilamentManagement must be inside a PrintHiveProvider.");
170
+ }
171
+ return source;
172
+ }
173
+
174
+ // src/queries.ts
175
+ function layoutQueryKey(printerId) {
176
+ return ["printhive-filaments", printerId];
177
+ }
178
+ function operationQueryKey(printerId) {
179
+ return ["printhive-filament-operation", printerId];
180
+ }
181
+ async function catalogDebounce(signal, delayMs) {
182
+ if (signal.aborted)
183
+ throw new DOMException("Catalog search aborted", "AbortError");
184
+ await new Promise((resolve, reject) => {
185
+ const finish = () => {
186
+ signal.removeEventListener("abort", cancel);
187
+ resolve();
188
+ };
189
+ const timer = setTimeout(finish, delayMs);
190
+ const cancel = () => {
191
+ clearTimeout(timer);
192
+ reject(new DOMException("Catalog search aborted", "AbortError"));
193
+ };
194
+ signal.addEventListener("abort", cancel, { once: true });
195
+ });
196
+ }
197
+
198
+ // src/SlotEditor.tsx
199
+ import { useState as useState3 } from "react";
200
+ import { useIsMutating } from "@tanstack/react-query";
201
+ import { Button as Button2 } from "@ui-sdk/react/button";
202
+ import {
203
+ DialogClose,
204
+ DialogDescription,
205
+ DialogTitle
206
+ } from "@ui-sdk/react/dialog";
207
+
208
+ // src/CatalogPicker.tsx
209
+ import { useState as useState2 } from "react";
210
+ import { useQuery } from "@tanstack/react-query";
211
+ import { Button } from "@ui-sdk/react/button";
212
+ import {
213
+ Combobox,
214
+ ComboboxContent,
215
+ ComboboxEmpty,
216
+ ComboboxInput,
217
+ ComboboxItem,
218
+ ComboboxLabel,
219
+ ComboboxList,
220
+ ComboboxTrigger
221
+ } from "@ui-sdk/react/combobox";
222
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
223
+ function CatalogPicker({
224
+ printerId,
225
+ selected,
226
+ onSelect,
227
+ disabled
228
+ }) {
229
+ const { dataSource, queryClient } = useFilamentRuntime();
230
+ const [query, setQuery] = useState2("");
231
+ const search = useQuery(
232
+ {
233
+ queryKey: ["printhive-filament-catalog", printerId, query],
234
+ queryFn: async ({ signal }) => {
235
+ await catalogDebounce(signal, query.length === 0 ? 0 : 180);
236
+ return dataSource.search(printerId, query, { signal });
237
+ },
238
+ enabled: !disabled
239
+ },
240
+ queryClient
241
+ );
242
+ const state = disabled ? { kind: "ready", options: [] } : search.isError ? { kind: "failed" } : search.data !== void 0 ? { kind: "ready", options: search.data } : { kind: "loading" };
243
+ const results = state.kind === "ready" ? state.options : [];
244
+ const options = selected && !results.some((option) => option.id === selected.id) ? [selected, ...results] : results;
245
+ return /* @__PURE__ */ jsxs("div", { className: "ph-filament-catalog", children: [
246
+ /* @__PURE__ */ jsxs(
247
+ Combobox,
248
+ {
249
+ items: options.map((option) => ({
250
+ value: option.id,
251
+ label: option.label
252
+ })),
253
+ value: selected?.id ?? null,
254
+ query,
255
+ onQueryChange: (next, details) => {
256
+ setQuery(next);
257
+ if (details.reason === "input-change") onSelect(null);
258
+ },
259
+ onValueChange: (next) => onSelect(options.find((option) => option.id === next) ?? null),
260
+ filter: false,
261
+ disabled,
262
+ children: [
263
+ /* @__PURE__ */ jsx2(ComboboxLabel, { children: "Assign filament" }),
264
+ /* @__PURE__ */ jsxs("div", { className: "ph-filament-combobox-control", children: [
265
+ /* @__PURE__ */ jsx2(
266
+ ComboboxInput,
267
+ {
268
+ placeholder: "Search your filament catalog",
269
+ autoComplete: "off"
270
+ }
271
+ ),
272
+ /* @__PURE__ */ jsx2(ComboboxTrigger, { "aria-label": "Show filament catalog", children: /* @__PURE__ */ jsx2("svg", { width: "16", height: "16", viewBox: "0 0 16 16", "aria-hidden": "true", children: /* @__PURE__ */ jsx2(
273
+ "path",
274
+ {
275
+ d: "m4 6 4 4 4-4",
276
+ fill: "none",
277
+ stroke: "currentColor",
278
+ strokeWidth: "1.5"
279
+ }
280
+ ) }) })
281
+ ] }),
282
+ /* @__PURE__ */ jsxs(ComboboxContent, { className: "ph-filament-catalog-popup", sideOffset: 4, children: [
283
+ /* @__PURE__ */ jsx2(ComboboxEmpty, { children: state.kind === "loading" ? "Searching catalog\u2026" : "No matching filaments" }),
284
+ /* @__PURE__ */ jsx2(ComboboxList, { "aria-busy": state.kind === "loading", children: options.map((option) => /* @__PURE__ */ jsxs(
285
+ ComboboxItem,
286
+ {
287
+ value: option.id,
288
+ label: option.label,
289
+ "aria-label": option.label,
290
+ children: [
291
+ /* @__PURE__ */ jsx2(
292
+ "span",
293
+ {
294
+ className: "ph-filament-swatch ph-filament-swatch-small",
295
+ style: fillStyle(
296
+ option.colors.length ? option.colors : option.color ? [option.color] : []
297
+ ),
298
+ "aria-hidden": "true"
299
+ }
300
+ ),
301
+ /* @__PURE__ */ jsxs("span", { children: [
302
+ /* @__PURE__ */ jsx2("span", { className: "ph-filament-option-label", children: option.label }),
303
+ /* @__PURE__ */ jsxs("span", { className: "ph-filament-muted", children: [
304
+ option.materialType,
305
+ option.description ? ` \xB7 ${option.description}` : ""
306
+ ] })
307
+ ] })
308
+ ]
309
+ },
310
+ option.id
311
+ )) })
312
+ ] })
313
+ ]
314
+ }
315
+ ),
316
+ state.kind === "failed" && /* @__PURE__ */ jsxs("div", { className: "ph-filament-inline-error", role: "alert", children: [
317
+ /* @__PURE__ */ jsx2("p", { children: "The filament catalog could not be loaded." }),
318
+ /* @__PURE__ */ jsx2(Button, { onClick: () => search.refetch(), children: "Retry catalog search" })
319
+ ] })
320
+ ] });
321
+ }
322
+
323
+ // src/mutations.ts
324
+ import { useMutation } from "@tanstack/react-query";
325
+ function useFilamentOperation(printerId) {
326
+ const { dataSource, queryClient } = useFilamentRuntime();
327
+ return useMutation(
328
+ {
329
+ mutationKey: operationQueryKey(printerId),
330
+ retry: false,
331
+ mutationFn: async (operation) => {
332
+ switch (operation.kind) {
333
+ case "assign":
334
+ return assignmentNotice(
335
+ await dataSource.assign(printerId, operation.input)
336
+ );
337
+ case "clear":
338
+ return clearNotice(
339
+ await dataSource.clear(printerId, operation.input)
340
+ );
341
+ case "rfid":
342
+ return rfidNotice(
343
+ await dataSource.refreshRfid(printerId, operation.input)
344
+ );
345
+ }
346
+ },
347
+ onSettled: () => {
348
+ void queryClient.invalidateQueries({
349
+ queryKey: layoutQueryKey(printerId)
350
+ });
351
+ }
352
+ },
353
+ queryClient
354
+ );
355
+ }
356
+
357
+ // src/SlotEditor.tsx
358
+ import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
359
+ function SlotComparison({ slot }) {
360
+ const assignment = slot.assignment;
361
+ const reported = "reported" in slot.observation ? slot.observation.reported : null;
362
+ const unavailable = slot.observation.status === "stale" ? "Last report is stale" : "Observation unavailable";
363
+ return /* @__PURE__ */ jsxs2("div", { className: "ph-filament-comparison", children: [
364
+ /* @__PURE__ */ jsxs2("section", { children: [
365
+ /* @__PURE__ */ jsx3("h3", { children: "Saved assignment" }),
366
+ /* @__PURE__ */ jsxs2("div", { className: "ph-filament-material", children: [
367
+ /* @__PURE__ */ jsx3(
368
+ "span",
369
+ {
370
+ className: "ph-filament-swatch",
371
+ style: fillStyle(assignment?.color ? [assignment.color] : []),
372
+ "aria-hidden": "true"
373
+ }
374
+ ),
375
+ /* @__PURE__ */ jsxs2("div", { children: [
376
+ /* @__PURE__ */ jsx3("strong", { children: assignment ? slot.displayName ?? assignment.materialType ?? "Assigned filament" : "No assignment" }),
377
+ /* @__PURE__ */ jsx3("p", { children: assignment?.color ?? "No saved color" })
378
+ ] })
379
+ ] })
380
+ ] }),
381
+ /* @__PURE__ */ jsxs2("section", { children: [
382
+ /* @__PURE__ */ jsx3("h3", { children: "Printer reports" }),
383
+ /* @__PURE__ */ jsxs2("div", { className: "ph-filament-material", children: [
384
+ /* @__PURE__ */ jsx3(
385
+ "span",
386
+ {
387
+ className: "ph-filament-swatch",
388
+ style: fillStyle(reported?.color ? [reported.color] : []),
389
+ "aria-hidden": "true"
390
+ }
391
+ ),
392
+ /* @__PURE__ */ jsxs2("div", { children: [
393
+ /* @__PURE__ */ jsx3("strong", { children: reported?.materialType ?? "No current report" }),
394
+ /* @__PURE__ */ jsx3("p", { children: reported?.color ?? unavailable })
395
+ ] })
396
+ ] })
397
+ ] })
398
+ ] });
399
+ }
400
+ function ActionReason({
401
+ capability
402
+ }) {
403
+ return capability.kind === "unavailable" ? /* @__PURE__ */ jsx3("p", { className: "ph-filament-muted", children: capability.message }) : null;
404
+ }
405
+ function OperationFeedback({
406
+ operation
407
+ }) {
408
+ if (operation.isPending) {
409
+ const message = operation.variables.kind === "assign" ? "Saving assignment\u2026" : operation.variables.kind === "clear" ? "Clearing assignment\u2026" : "Requesting RFID reread\u2026";
410
+ return /* @__PURE__ */ jsx3("p", { className: "ph-filament-muted", role: "status", children: message });
411
+ }
412
+ if (operation.isError) {
413
+ const message = operation.error instanceof FilamentManagementError ? operation.error.message : "The request could not be confirmed. Your draft is still here. Refresh this printer before trying again.";
414
+ return /* @__PURE__ */ jsx3("p", { className: "ph-filament-notice", "data-tone": "error", role: "alert", children: message });
415
+ }
416
+ if (!operation.data) return null;
417
+ return /* @__PURE__ */ jsx3(
418
+ "p",
419
+ {
420
+ className: "ph-filament-notice",
421
+ "data-tone": operation.data.tone,
422
+ role: operation.data.tone === "error" ? "alert" : "status",
423
+ children: operation.data.message
424
+ }
425
+ );
426
+ }
427
+ function SlotEditor({
428
+ printerId,
429
+ slot,
430
+ context
431
+ }) {
432
+ const { queryClient } = useFilamentRuntime();
433
+ const operation = useFilamentOperation(printerId);
434
+ const busy = useIsMutating({ mutationKey: operationQueryKey(printerId) }, queryClient) > 0;
435
+ const [selected, setSelected] = useState3(null);
436
+ const [clearTarget, setClearTarget] = useState3(
437
+ null
438
+ );
439
+ const assignAvailability = slot.capabilities.assign;
440
+ const clearAvailability = slot.capabilities.clearAssignment;
441
+ const rfidAvailability = slot.capabilities.refreshRfid;
442
+ const clearVersion = slot.assignment?.version ?? null;
443
+ const run = (intent) => {
444
+ if (queryClient.isMutating({ mutationKey: operationQueryKey(printerId) }) > 0)
445
+ return;
446
+ return operation.mutateAsync(intent, {
447
+ onSuccess: (notice, completed) => {
448
+ if (completed.kind === "assign" && notice.tone !== "error")
449
+ setSelected(null);
450
+ setClearTarget(null);
451
+ }
452
+ }).catch(() => void 0);
453
+ };
454
+ const requestClear = () => {
455
+ if (clearVersion === null) return;
456
+ setClearTarget({ slotId: slot.id, expectedVersion: clearVersion });
457
+ };
458
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
459
+ /* @__PURE__ */ jsxs2("div", { className: "ph-filament-editor-heading", children: [
460
+ /* @__PURE__ */ jsxs2("div", { children: [
461
+ /* @__PURE__ */ jsxs2(DialogTitle, { children: [
462
+ context,
463
+ " \xB7 ",
464
+ slot.label
465
+ ] }),
466
+ /* @__PURE__ */ jsx3(DialogDescription, { children: "Manage the saved assignment and compare it with the printer report." })
467
+ ] }),
468
+ /* @__PURE__ */ jsx3(DialogClose, { className: "ph-filament-close", disabled: busy, children: "Close" })
469
+ ] }),
470
+ /* @__PURE__ */ jsx3(SlotComparison, { slot }),
471
+ /* @__PURE__ */ jsx3(
472
+ CatalogPicker,
473
+ {
474
+ printerId,
475
+ selected,
476
+ onSelect: setSelected,
477
+ disabled: busy || assignAvailability.kind !== "available"
478
+ }
479
+ ),
480
+ /* @__PURE__ */ jsx3(ActionReason, { capability: assignAvailability }),
481
+ slot.capabilities.writePrinterMetadata.kind === "unavailable" && assignAvailability.kind === "available" && /* @__PURE__ */ jsxs2("p", { className: "ph-filament-muted", children: [
482
+ slot.capabilities.writePrinterMetadata.message,
483
+ " Saving an assignment still records it in PrintHive."
484
+ ] }),
485
+ /* @__PURE__ */ jsx3(OperationFeedback, { operation }),
486
+ /* @__PURE__ */ jsx3("div", { className: "ph-filament-editor-primary", children: /* @__PURE__ */ jsx3(
487
+ Button2,
488
+ {
489
+ className: "ph-filament-primary",
490
+ disabled: busy || selected === null || assignAvailability.kind !== "available",
491
+ onClick: () => selected ? run({
492
+ kind: "assign",
493
+ input: { slotId: slot.id, materialId: selected.id }
494
+ }) : void 0,
495
+ pendingAnnouncement: "Saving assignment",
496
+ children: "Save assignment"
497
+ }
498
+ ) }),
499
+ /* @__PURE__ */ jsxs2("div", { className: "ph-filament-editor-secondary", children: [
500
+ /* @__PURE__ */ jsxs2("div", { children: [
501
+ /* @__PURE__ */ jsx3(
502
+ Button2,
503
+ {
504
+ disabled: busy || rfidAvailability.kind !== "available",
505
+ onClick: () => run({ kind: "rfid", input: { slotId: slot.id } }),
506
+ pendingAnnouncement: "Requesting RFID reread",
507
+ children: "Read RFID"
508
+ }
509
+ ),
510
+ /* @__PURE__ */ jsx3(ActionReason, { capability: rfidAvailability })
511
+ ] }),
512
+ /* @__PURE__ */ jsxs2("div", { children: [
513
+ /* @__PURE__ */ jsx3(
514
+ Button2,
515
+ {
516
+ disabled: busy || clearVersion === null || clearAvailability.kind !== "available",
517
+ onClick: requestClear,
518
+ children: "Clear assignment"
519
+ }
520
+ ),
521
+ /* @__PURE__ */ jsx3(ActionReason, { capability: clearAvailability }),
522
+ slot.assignment && clearVersion === null && /* @__PURE__ */ jsx3("p", { className: "ph-filament-muted", children: "Refresh this printer before clearing its assignment; the saved version is unavailable." })
523
+ ] })
524
+ ] }),
525
+ clearTarget && /* @__PURE__ */ jsxs2(
526
+ "section",
527
+ {
528
+ className: "ph-filament-clear-confirmation",
529
+ "aria-label": "Confirm clearing assignment",
530
+ children: [
531
+ /* @__PURE__ */ jsxs2("p", { children: [
532
+ "Clear the saved assignment for ",
533
+ slot.label,
534
+ "? This does not unload filament or change printer metadata."
535
+ ] }),
536
+ /* @__PURE__ */ jsxs2("div", { className: "ph-filament-actions", children: [
537
+ /* @__PURE__ */ jsx3(
538
+ Button2,
539
+ {
540
+ className: "ph-filament-danger",
541
+ "data-agent-confirm": `Clears the saved filament assignment for ${context} \xB7 ${slot.label}. Printer metadata is unchanged.`,
542
+ disabled: busy,
543
+ onClick: () => run({ kind: "clear", input: clearTarget }),
544
+ children: "Confirm clear assignment"
545
+ }
546
+ ),
547
+ /* @__PURE__ */ jsx3(Button2, { disabled: busy, onClick: () => setClearTarget(null), children: "Keep assignment" })
548
+ ] })
549
+ ]
550
+ }
551
+ )
552
+ ] });
553
+ }
554
+
555
+ // src/FilamentManagement.tsx
556
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
557
+ function layoutState(query) {
558
+ if (query.data === void 0)
559
+ return query.isPending ? { kind: "loading" } : { kind: "failed" };
560
+ let refresh = { kind: "idle" };
561
+ if (query.isFetching) refresh = { kind: "pending" };
562
+ else if (query.isRefetchError) refresh = { kind: "failed" };
563
+ return { kind: "ready", layout: query.data, refresh };
564
+ }
565
+ function SlotCard({
566
+ slot,
567
+ context
568
+ }) {
569
+ return /* @__PURE__ */ jsxs3(
570
+ DialogTrigger,
571
+ {
572
+ render: /* @__PURE__ */ jsx4(Button3, {}),
573
+ payload: slot.id,
574
+ className: "ph-filament-slot",
575
+ "aria-label": `Manage ${context} \xB7 ${slot.label}`,
576
+ children: [
577
+ /* @__PURE__ */ jsxs3("span", { className: "ph-filament-slot-top", children: [
578
+ /* @__PURE__ */ jsx4("span", { className: "ph-filament-slot-label", children: slot.label }),
579
+ slot.feeding && /* @__PURE__ */ jsx4("span", { className: "ph-filament-feeding", children: "Feeding" })
580
+ ] }),
581
+ /* @__PURE__ */ jsx4(
582
+ "span",
583
+ {
584
+ className: "ph-filament-swatch",
585
+ style: fillStyle(slot.fill?.colors ?? [], slot.fill?.kind),
586
+ "aria-hidden": "true"
587
+ }
588
+ ),
589
+ /* @__PURE__ */ jsx4("strong", { children: slot.displayName ?? slot.materialType ?? (slot.assignment ? "Assigned filament" : "No assignment") }),
590
+ /* @__PURE__ */ jsx4("span", { className: "ph-filament-slot-status", "data-state": slot.presentation, children: slotStatus(slot) }),
591
+ slot.remainingPct !== null && /* @__PURE__ */ jsxs3("span", { className: "ph-filament-muted", children: [
592
+ Math.round(slot.remainingPct),
593
+ "% remaining"
594
+ ] })
595
+ ]
596
+ }
597
+ );
598
+ }
599
+ function SourceUnit({
600
+ source,
601
+ context
602
+ }) {
603
+ return /* @__PURE__ */ jsxs3("section", { className: "ph-filament-source", "aria-label": source.label, children: [
604
+ /* @__PURE__ */ jsxs3("header", { children: [
605
+ /* @__PURE__ */ jsx4("h3", { children: source.label }),
606
+ source.humidityPct !== null && /* @__PURE__ */ jsxs3("span", { className: "ph-filament-muted", children: [
607
+ source.humidityPct,
608
+ "% humidity"
609
+ ] })
610
+ ] }),
611
+ /* @__PURE__ */ jsx4("div", { className: "ph-filament-slots", "data-layout": source.layout, children: source.slots.map((slot) => /* @__PURE__ */ jsx4(SlotCard, { slot, context }, slot.id)) })
612
+ ] });
613
+ }
614
+ function HotendRack({ rack }) {
615
+ if (rack.kind === "no-rack-reported") return null;
616
+ if (rack.kind === "invalid-report")
617
+ return /* @__PURE__ */ jsx4("p", { className: "ph-filament-muted", children: "Hotend rack information is unavailable." });
618
+ return /* @__PURE__ */ jsxs3("section", { className: "ph-filament-rack", "aria-label": "Hotend rack", children: [
619
+ /* @__PURE__ */ jsx4("h3", { children: "Hotend rack" }),
620
+ rack.kind === "reported" && rack.tools === null && /* @__PURE__ */ jsx4("p", { className: "ph-filament-muted", children: "Hotend details unavailable." }),
621
+ /* @__PURE__ */ jsx4("div", { className: "ph-filament-rack-tools", children: rack.kind === "legacy" ? rack.slots.map((slot) => /* @__PURE__ */ jsxs3("span", { children: [
622
+ "Holder ",
623
+ slot.id + 1,
624
+ /* @__PURE__ */ jsx4("strong", { children: slot.occupied ? slot.diameterMm !== null ? `${slot.diameterMm} mm` : "Hotend" : "Empty" }),
625
+ slot.active && /* @__PURE__ */ jsx4("small", { children: "Active" })
626
+ ] }, slot.id)) : (rack.tools ?? []).map((tool) => /* @__PURE__ */ jsxs3("span", { children: [
627
+ tool.location === "toolhead" ? "Toolhead" : tool.holderAddress !== null ? `Holder ${tool.holderAddress + 1}` : "Rack",
628
+ /* @__PURE__ */ jsx4("strong", { children: tool.diameterMm !== null ? `${tool.diameterMm} mm` : tool.kind }),
629
+ tool.serialNumber && /* @__PURE__ */ jsx4("small", { children: tool.serialNumber })
630
+ ] }, tool.id)) }),
631
+ /* @__PURE__ */ jsx4("p", { className: "ph-filament-muted", children: "Hardware information only. Filament assignments belong to the sources below." })
632
+ ] });
633
+ }
634
+ function FilamentManagement({
635
+ printerId,
636
+ className
637
+ }) {
638
+ const { dataSource, queryClient } = useFilamentRuntime();
639
+ const [scope, setScope] = useState4({ dataSource, revision: 0 });
640
+ if (scope.dataSource !== dataSource) {
641
+ setScope({ dataSource, revision: scope.revision + 1 });
642
+ }
643
+ return /* @__PURE__ */ jsx4(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsx4(
644
+ PrinterFilamentManagement,
645
+ {
646
+ printerId,
647
+ className,
648
+ source: dataSource
649
+ },
650
+ `${printerId}:${scope.revision}`
651
+ ) });
652
+ }
653
+ function PrinterFilamentManagement({
654
+ printerId,
655
+ className,
656
+ source
657
+ }) {
658
+ const { queryClient } = useFilamentRuntime();
659
+ const query = useQuery2(
660
+ {
661
+ queryKey: layoutQueryKey(printerId),
662
+ queryFn: async ({ signal }) => requirePrinterLayout(
663
+ await source.read(printerId, { signal }),
664
+ printerId
665
+ )
666
+ },
667
+ queryClient
668
+ );
669
+ const busy = useIsMutating2({ mutationKey: operationQueryKey(printerId) }, queryClient) > 0;
670
+ const refresh = () => {
671
+ void query.refetch();
672
+ };
673
+ const state = layoutState(query);
674
+ const rootClass = `ph-filament-management${className ? ` ${className}` : ""}`;
675
+ if (state.kind === "loading")
676
+ return /* @__PURE__ */ jsx4(
677
+ "section",
678
+ {
679
+ className: rootClass,
680
+ "aria-label": "Filament management",
681
+ "aria-busy": "true",
682
+ children: /* @__PURE__ */ jsx4("p", { role: "status", children: "Loading printer filaments\u2026" })
683
+ }
684
+ );
685
+ if (state.kind === "failed")
686
+ return /* @__PURE__ */ jsxs3("section", { className: rootClass, "aria-label": "Filament management", children: [
687
+ /* @__PURE__ */ jsx4("h2", { children: "Filaments unavailable" }),
688
+ /* @__PURE__ */ jsx4("p", { role: "alert", children: "The printer filaments could not be loaded. Check your connection and access to this printer." }),
689
+ /* @__PURE__ */ jsx4(Button3, { onClick: refresh, children: "Retry loading filaments" })
690
+ ] });
691
+ const { layout } = state;
692
+ const slots = layoutSlots(layout);
693
+ const sources = layout.nozzles.flatMap((nozzle) => nozzle.sources).concat(layout.unboundSources);
694
+ const observedAt = "observedAt" in layout.freshness ? layout.freshness.observedAt : null;
695
+ return /* @__PURE__ */ jsx4(Dialog, { dismissible: !busy, children: /* @__PURE__ */ jsxs3(
696
+ "section",
697
+ {
698
+ className: rootClass,
699
+ "aria-label": `Filaments for ${layout.printer.name}`,
700
+ children: [
701
+ /* @__PURE__ */ jsxs3("header", { className: "ph-filament-header", children: [
702
+ /* @__PURE__ */ jsxs3("div", { children: [
703
+ /* @__PURE__ */ jsx4("p", { className: "ph-filament-eyebrow", children: "Printer filaments" }),
704
+ /* @__PURE__ */ jsx4("h2", { children: layout.printer.name }),
705
+ /* @__PURE__ */ jsxs3("p", { className: "ph-filament-muted", children: [
706
+ layout.printer.make,
707
+ " ",
708
+ layout.printer.model
709
+ ] })
710
+ ] }),
711
+ /* @__PURE__ */ jsxs3("div", { className: "ph-filament-header-actions", children: [
712
+ /* @__PURE__ */ jsx4("span", { className: "ph-filament-connection", children: layout.printer.connected === true ? "Online" : layout.printer.connected === false ? "Offline" : "Connection unknown" }),
713
+ /* @__PURE__ */ jsx4(
714
+ Button3,
715
+ {
716
+ disabled: state.refresh.kind === "pending" || busy,
717
+ onClick: refresh,
718
+ children: "Refresh"
719
+ }
720
+ )
721
+ ] })
722
+ ] }),
723
+ /* @__PURE__ */ jsxs3("div", { className: "ph-filament-freshness", children: [
724
+ /* @__PURE__ */ jsx4("span", { children: layout.freshness.status === "fresh" ? "Current printer report" : layout.freshness.status === "stale" ? "Last known printer report" : "Live printer report unavailable" }),
725
+ observedAt && /* @__PURE__ */ jsx4("time", { dateTime: observedAt, children: new Date(observedAt).toLocaleString() })
726
+ ] }),
727
+ state.refresh.kind === "pending" && /* @__PURE__ */ jsx4("p", { className: "ph-filament-muted", role: "status", children: "Refreshing printer filaments\u2026" }),
728
+ state.refresh.kind === "failed" && /* @__PURE__ */ jsx4("p", { className: "ph-filament-inline-error", role: "alert", children: "The latest state could not be loaded. Showing the previous snapshot." }),
729
+ layout.topology.kind === "unavailable" && /* @__PURE__ */ jsx4("p", { className: "ph-filament-inline-error", children: "The printer has not reported its hardware layout. Saved assignments are shown without guessing their nozzle or AMS unit." }),
730
+ /* @__PURE__ */ jsx4(HotendRack, { rack: layout.hotendRack }),
731
+ /* @__PURE__ */ jsx4("div", { className: "ph-filament-nozzles", children: layout.nozzles.map((nozzle) => /* @__PURE__ */ jsxs3(
732
+ "section",
733
+ {
734
+ className: "ph-filament-nozzle",
735
+ "aria-label": nozzle.label,
736
+ children: [
737
+ /* @__PURE__ */ jsxs3("header", { children: [
738
+ /* @__PURE__ */ jsx4("h3", { children: nozzle.label }),
739
+ nozzle.hotend?.diameterMm !== null && nozzle.hotend?.diameterMm !== void 0 && /* @__PURE__ */ jsxs3("span", { className: "ph-filament-muted", children: [
740
+ nozzle.hotend.diameterMm,
741
+ " mm",
742
+ nozzle.hotend.mount === "vortek" ? " \xB7 Vortek" : ""
743
+ ] })
744
+ ] }),
745
+ nozzle.sources.map((unit) => /* @__PURE__ */ jsx4(
746
+ SourceUnit,
747
+ {
748
+ source: unit,
749
+ context: layout.nozzles.length > 1 ? `${nozzle.label} \xB7 ${unit.label}` : unit.label
750
+ },
751
+ unit.id
752
+ ))
753
+ ]
754
+ },
755
+ nozzle.id
756
+ )) }),
757
+ layout.unboundSources.length > 0 && /* @__PURE__ */ jsxs3("section", { className: "ph-filament-unbound", children: [
758
+ /* @__PURE__ */ jsx4("h3", { children: "Not assigned to a nozzle" }),
759
+ layout.unboundSources.map((unit) => /* @__PURE__ */ jsx4(SourceUnit, { source: unit, context: unit.label }, unit.id))
760
+ ] }),
761
+ layout.unmappedAssignments.length > 0 && /* @__PURE__ */ jsxs3("section", { className: "ph-filament-unbound", children: [
762
+ /* @__PURE__ */ jsx4("h3", { children: "Saved assignments" }),
763
+ /* @__PURE__ */ jsx4("div", { className: "ph-filament-slots", "data-layout": "row4", children: layout.unmappedAssignments.map((slot) => /* @__PURE__ */ jsx4(
764
+ SlotCard,
765
+ {
766
+ slot,
767
+ context: "Saved assignments"
768
+ },
769
+ slot.id
770
+ )) })
771
+ ] }),
772
+ sources.length === 0 && slots.length === 0 && /* @__PURE__ */ jsx4("p", { className: "ph-filament-muted", children: "No filament sources have been reported for this printer." }),
773
+ /* @__PURE__ */ jsx4(DialogBackdrop, { className: "ph-filament-backdrop" }),
774
+ /* @__PURE__ */ jsx4(
775
+ DialogContent,
776
+ {
777
+ className: "ph-filament-editor",
778
+ "aria-label": `Manage ${layout.printer.name} filaments`,
779
+ keepMounted: true,
780
+ children: (dialog) => {
781
+ const slot = slots.find(
782
+ (candidate) => candidate.id === dialog.payload
783
+ );
784
+ return dialog.open && slot ? /* @__PURE__ */ jsx4(
785
+ SlotEditor,
786
+ {
787
+ printerId,
788
+ slot,
789
+ context: slotContext(layout, slot.id)
790
+ },
791
+ slot.id
792
+ ) : /* @__PURE__ */ jsxs3(Fragment2, { children: [
793
+ /* @__PURE__ */ jsx4(DialogTitle2, { children: !dialog.open || dialog.payload === void 0 ? `Manage ${layout.printer.name} filaments` : "Slot unavailable" }),
794
+ /* @__PURE__ */ jsx4(DialogDescription2, { children: "This slot is no longer part of the reported printer layout. Refresh the printer before making changes." }),
795
+ /* @__PURE__ */ jsx4(DialogClose2, { children: "Close" })
796
+ ] });
797
+ }
798
+ }
799
+ )
800
+ ]
801
+ }
802
+ ) });
803
+ }
804
+
805
+ // src/http-data-source.ts
806
+ import {
807
+ isAssignFilamentsResult,
808
+ isClearFilamentAssignmentsResult,
809
+ isFilamentSearchPage,
810
+ isPrinterMaterialLayout,
811
+ isRefreshMaterialSlotRfidResult
812
+ } from "@printhive/api/validation";
813
+ import { z } from "zod";
814
+ var failureSchema = z.object({ error: z.string(), message: z.string() });
815
+ var layoutSchema = z.custom(isPrinterMaterialLayout);
816
+ var catalogSchema = z.custom(isFilamentSearchPage);
817
+ var assignmentSchema = z.custom(
818
+ isAssignFilamentsResult
819
+ );
820
+ var clearSchema = z.custom(
821
+ isClearFilamentAssignmentsResult
822
+ );
823
+ var rfidSchema = z.custom(
824
+ isRefreshMaterialSlotRfidResult
825
+ );
826
+ function invalidResponse(response) {
827
+ return new FilamentManagementError(
828
+ "The filament service returned an invalid response.",
829
+ {
830
+ code: "invalid_response",
831
+ status: response.status
832
+ }
833
+ );
834
+ }
835
+ function createFilamentManagementDataSource(options) {
836
+ const baseUrl = options.baseUrl.trim().replace(/\/+$/, "");
837
+ if (!options.baseUrl.trim()) throw new TypeError("baseUrl is required");
838
+ const fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
839
+ async function request(printerId, suffix, schema, signal, body) {
840
+ if (!printerId.trim()) throw new TypeError("printerId is required");
841
+ const response = await fetcher(
842
+ `${baseUrl}/printers/${encodeURIComponent(printerId)}/filaments${suffix}`,
843
+ {
844
+ method: body === void 0 ? "GET" : "POST",
845
+ credentials: "same-origin",
846
+ signal,
847
+ headers: body === void 0 ? void 0 : { "content-type": "application/json" },
848
+ body: body === void 0 ? void 0 : JSON.stringify(body)
849
+ }
850
+ );
851
+ const value = await response.json().catch(() => {
852
+ throw invalidResponse(response);
853
+ });
854
+ if (!response.ok) {
855
+ const failure = failureSchema.safeParse(value);
856
+ throw new FilamentManagementError(
857
+ failure.success ? failure.data.message : "The filament request could not be completed.",
858
+ {
859
+ code: failure.success ? failure.data.error : "request_failed",
860
+ status: response.status
861
+ }
862
+ );
863
+ }
864
+ const parsed = schema.safeParse(value);
865
+ if (!parsed.success) throw invalidResponse(response);
866
+ return parsed.data;
867
+ }
868
+ return {
869
+ read: async (id, options2) => requirePrinterLayout(
870
+ await request(id, "", layoutSchema, options2?.signal),
871
+ id
872
+ ),
873
+ async search(id, query, options2) {
874
+ const params = new URLSearchParams({ q: query });
875
+ const page = await request(
876
+ id,
877
+ `/catalog?${params}`,
878
+ catalogSchema,
879
+ options2?.signal
880
+ );
881
+ return page.filaments.map((filament) => ({
882
+ id: filament.id,
883
+ label: filament.name,
884
+ materialType: filament.material_type,
885
+ color: filament.color,
886
+ colors: filament.colors,
887
+ description: [filament.brand, filament.colorName].filter(Boolean).join(" \xB7 ")
888
+ }));
889
+ },
890
+ assign: (id, input, options2) => request(id, "/assign", assignmentSchema, options2?.signal, input),
891
+ clear: (id, input, options2) => request(id, "/clear", clearSchema, options2?.signal, input),
892
+ refreshRfid: (id, input, options2) => request(id, "/refresh-rfid", rfidSchema, options2?.signal, input)
893
+ };
894
+ }
895
+ export {
896
+ FilamentManagement,
897
+ FilamentManagementError,
898
+ PrintHiveProvider,
899
+ createFilamentManagementDataSource
900
+ };
901
+ //# sourceMappingURL=index.js.map