Component to handle printers notice that we only use browserprint for USB-printers and have a separate handling for networkprinters. window.printerComponent = function () { return { printEnabled: false, status: 'searching', printrar: [], selectedDevice: null, selectedPrinterUid: Alpine.$persist('').as(window.location.href.substring(window.location.href.lastIndexOf('/') + 1) + 'selectedPrinter'), printing: false, get hasSelectedPrinter() { return this.activePrinter.uid !== "0"; }, get activePrinter() { return this.printrar.find(p => p.uid === this.selectedPrinterUid) || { name: "Ingen skrivare vald", uid: "0", status: "Redo" }; }, get usbPrinters() { return this.printrar.filter(p => p.type === 'usb'); }, async init() { this.printers = await this.updatePrinters(); var printer = this.printrar.find((p) => p.uid == this.selectedPrinterUid); if (printer) { this.selectPrinter(printer); } else if (this.printrar.length > 0) { this.selectPrinter(this.printrar[0]); } }, async selectPrinter(printer) { this.selectedPrinterUid = printer.uid; this.selectedDevice = printer; }, async updatePrinters() { var getLocalDevices = this.getLocalDevices(); var getNetworkDevices = this.getNetworkDevices(); getLocalDevices.then(localDevices => { if (localDevices !== null) { var p = localDevices.map(p => { return { name: p.name, uid: p.uid, type: 'usb', status: 'Redo', device: p.device } }); this.printrar.push(...p); } }); }, async print() { if ($("form").valid()) { try { const zplResponse = await this.getZpl(); for (const r of zplResponse) { if (r.success) { this.printing = true; if (this.activePrinter.type === 'usb') { this.printToUsb(r.zpl) site.toast.info("Skickad för utskrift", "Utskrift skickad till skrivaren"); } else if (this.activePrinter.type === 'network') { await this.printToNetwork(r) } } } window.dispatchEvent(new CustomEvent('printCompleted')); } catch (error) { console.error('Error during printing:', error); } finally { this.printing = false; site.sessionTimeout.reset(); } } }, printToUsb(zpl) { this.selectedDevice.device.send(zpl, undefined, this.errorCallback); }, errorCallback (errorMessage) { site.toast.error("Problem vid utskrift", errorMessage); console.log(errorMessage); }, getLocalDevices() { return new Promise(resolve => { BrowserPrint.getLocalDevices( response => { if (!response.printer) { this.localDevices = []; resolve([]); } else { var printers = response.printer.filter(p => // Ett försök att ta bort skrivare som är upplagda med datorns namn. Då kommer uid och name att skilja. // Ta endast med USB-skrivare samt de med zebrabp och driver (p.connection === 'usb' && p.uid === p.name) ); this.localDevices = printers; var result = printers.map(p => { return { uid: p.uid, name: p.name, manufacturer: p.manufacturer, device: p } }); resolve(result); } }, error => { console.log(error); resolve(null); }); }); } }; };