Switch UI to HTML based tools
Some checks failed
Mirror to Gitea / mirror (push) Has been cancelled

This commit is contained in:
2026-08-12 04:56:02 +03:30
parent 7c50480324
commit f1d9693966
19 changed files with 1523 additions and 489 deletions

View File

@@ -1,298 +1,139 @@
"""Cross-platform Dear PyGui desktop GUI for New QC Sheet."""
"""PyWebView desktop GUI for New QC Sheet."""
from __future__ import annotations
import argparse
import sys
from importlib.metadata import PackageNotFoundError, version as package_version
import dearpygui.dearpygui as dpg
import webview
from xlsx_clean.core import (
create_datasheet,
list_ink_colors,
list_sets,
load_config,
)
from xlsx_clean.paths import default_backend, package_file
from xlsx_clean.core import create_datasheet, list_ink_colors, list_sets, load_config
from xlsx_clean.app_logging import get_logger
from xlsx_clean.paths import package_file
try:
_VERSION = package_version('xlsx-clean')
_VERSION = package_version("xlsx-clean")
except PackageNotFoundError:
_VERSION = 'dev'
# Module-level variables
rows = []
addin_paths = []
config = {}
_VERSION = "dev"
# Tags
SET_COMBO = "set_combo"
INK_COMBO = "ink_combo"
SERIAL_INPUT = "serial_input"
STATUS_TEXT = "status_text"
HEADING_FONT = "heading_font"
class Api:
"""Python functions exposed to JavaScript via ``window.pywebview.api``."""
def on_set_change(sender, app_data):
"""Callback when the set combo changes."""
new_inks = list_ink_colors(rows, app_data)
dpg.configure_item(INK_COMBO, items=new_inks)
dpg.set_value(INK_COMBO, new_inks[0] if new_inks else '')
def __init__(self) -> None:
self.rows: list[dict] = []
self.addin_paths: list[str] = []
self.config: dict = {}
self._initial_data: dict | None = None
self._initialization_error: Exception | None = None
def on_create(sender, app_data):
"""Callback for the Create datasheet button."""
selected_set = dpg.get_value(SET_COMBO)
selected_dir = dpg.get_value(INK_COMBO)
batch_serial = dpg.get_value(SERIAL_INPUT)
try:
result = create_datasheet(
selected_set=selected_set,
selected_dir=selected_dir,
batch_serial=batch_serial,
backend=None,
rows=rows,
addin_paths=addin_paths,
config=config
)
msg = result.message
if result.template:
msg += f"\nTemplate: {result.template}"
if result.destination:
msg += f"\nDestination: {result.destination}"
if result.backend:
msg += f"\nBackend: {result.backend}"
dpg.set_value(STATUS_TEXT, msg)
if result.skipped:
dpg.configure_item(STATUS_TEXT, color=(230, 180, 30)) # Yellow
elif result.ok:
dpg.configure_item(STATUS_TEXT, color=(0, 200, 80)) # Green
else:
dpg.configure_item(STATUS_TEXT, color=(220, 60, 60)) # Red
except Exception as e:
dpg.set_value(STATUS_TEXT, f"Error: {e}")
dpg.configure_item(STATUS_TEXT, color=(220, 60, 60))
def initialize(self) -> None:
"""Load configuration before the local frontend is opened."""
if self._initial_data is not None or self._initialization_error is not None:
return
try:
content, self.rows, self.config = load_config()
sets = list_sets(self.rows)
self.addin_paths = content[3:5] if len(content) >= 5 else []
self._initial_data = {
"sets": sets,
"inks": list_ink_colors(self.rows, sets[0]) if sets else [],
"labels": {
"set": content[0] if len(content) > 0 else "Select Set",
"ink": content[1] if len(content) > 1 else "Select Ink Color",
"serial": content[2] if len(content) > 2 else "Serial:",
},
"version": _VERSION,
}
except Exception as exc: # noqa: BLE001 - serialize bridge failures to JS
self._initialization_error = exc
def _create_modern_theme() -> int:
"""Build a global theme that gives DPG widgets a modern, web-like feel, matching the HTML demo."""
with dpg.theme() as theme:
with dpg.theme_component(dpg.mvAll):
# Rounded corners (like CSS border-radius)
dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 4)
dpg.add_theme_style(dpg.mvStyleVar_PopupRounding, 4)
dpg.add_theme_style(dpg.mvStyleVar_WindowRounding, 8)
dpg.add_theme_style(dpg.mvStyleVar_GrabRounding, 4)
dpg.add_theme_style(dpg.mvStyleVar_TabRounding, 4)
dpg.add_theme_style(dpg.mvStyleVar_ChildRounding, 4)
dpg.add_theme_style(dpg.mvStyleVar_ScrollbarRounding, 4)
def get_initial_data(self) -> dict:
"""Return configuration-derived values for the initial page render."""
self.initialize()
if self._initialization_error is not None:
raise self._initialization_error
assert self._initial_data is not None
return self._initial_data
# Generous padding (like CSS padding)
dpg.add_theme_style(dpg.mvStyleVar_FramePadding, 12, 10)
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 10, 10)
dpg.add_theme_style(dpg.mvStyleVar_ItemInnerSpacing, 8, 6)
dpg.add_theme_style(dpg.mvStyleVar_WindowPadding, 48, 48)
def get_inks(self, selected_set: str) -> list[str]:
"""Return ink colors for a selected set."""
return list_ink_colors(self.rows, selected_set)
# Scrollbar
dpg.add_theme_style(dpg.mvStyleVar_ScrollbarSize, 12)
def create(
self, selected_set: str, selected_dir: str, batch_serial: str
) -> dict:
"""Create a datasheet and return a JSON-safe result.
# Colors from demo.html
bg = (248, 250, 252, 255) # Slate 50 (#f8fafc)
surface = (255, 255, 255, 255) # White (#ffffff)
frame = (255, 255, 255, 255) # White (inputs)
frame_hover = (240, 253, 250, 255) # Teal 50 (#f0fdfa)
frame_active = (204, 251, 241, 255) # Teal 100 (#ccfbf1)
accent = (15, 118, 110, 255) # Teal 700 (#0f766e) - Primary
accent_hover = (17, 94, 89, 255) # Teal 800 (#115e59) - Secondary
accent_active = (19, 78, 74, 255) # Teal 900 (#134e4a)
text = (15, 23, 42, 255) # Slate 900 (#0f172a)
text_dim = (100, 116, 139, 255) # Slate 500 (#64748b)
border = (203, 213, 225, 255) # Slate 300 (#cbd5e1)
popup_bg = (255, 255, 255, 255) # White dropdowns
# Window
dpg.add_theme_color(dpg.mvThemeCol_WindowBg, bg)
dpg.add_theme_color(dpg.mvThemeCol_PopupBg, popup_bg)
dpg.add_theme_color(dpg.mvThemeCol_TitleBg, bg)
dpg.add_theme_color(dpg.mvThemeCol_TitleBgActive, bg)
# Frame (combos, inputs)
dpg.add_theme_color(dpg.mvThemeCol_FrameBg, frame)
dpg.add_theme_color(dpg.mvThemeCol_FrameBgHovered, frame_hover)
dpg.add_theme_color(dpg.mvThemeCol_FrameBgActive, frame_active)
# Border
dpg.add_theme_color(dpg.mvThemeCol_Border, border)
dpg.add_theme_color(dpg.mvThemeCol_BorderShadow, (0, 0, 0, 0))
dpg.add_theme_style(dpg.mvStyleVar_FrameBorderSize, 1)
# Button (Combo box drop arrows) - blend into frame
dpg.add_theme_color(dpg.mvThemeCol_Button, frame)
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, frame_hover)
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, frame_active)
# Header (combo dropdown items on hover)
dpg.add_theme_color(dpg.mvThemeCol_Header, frame_hover)
dpg.add_theme_color(dpg.mvThemeCol_HeaderHovered, frame_active)
dpg.add_theme_color(dpg.mvThemeCol_HeaderActive, accent)
# Text
dpg.add_theme_color(dpg.mvThemeCol_Text, text)
dpg.add_theme_color(dpg.mvThemeCol_TextDisabled, text_dim)
# Separator
dpg.add_theme_color(dpg.mvThemeCol_Separator, border)
# Scrollbar
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarBg, bg)
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrab, border)
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrabHovered, text_dim)
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrabActive, text)
# Check mark / selection
dpg.add_theme_color(dpg.mvThemeCol_CheckMark, accent)
return theme
Unexpected exceptions are serialized into the result contract so the
frontend always sees the same shape, regardless of platform-specific
bridge behavior.
"""
log = get_logger()
try:
result = create_datasheet(
selected_set=selected_set,
selected_dir=selected_dir,
batch_serial=batch_serial,
backend=None,
rows=self.rows,
addin_paths=self.addin_paths,
config=self.config,
)
except Exception as exc: # noqa: BLE001 - serialize bridge failures to JS
log.exception(
"Unexpected error in Api.create(set=%r, dir=%r, serial=%r)",
selected_set,
selected_dir,
batch_serial,
)
return {
"ok": False,
"skipped": False,
"message": f"Unexpected error: {exc}",
"template": None,
"destination": None,
"backend": None,
}
return {
"ok": result.ok,
"skipped": result.skipped,
"message": result.message,
"template": str(result.template) if result.template is not None else None,
"destination": (
str(result.destination) if result.destination is not None else None
),
"backend": result.backend,
}
def parse_args() -> argparse.Namespace:
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse GUI dimensions without changing process-global arguments."""
parser = argparse.ArgumentParser(
description="New QC Sheet — Dear PyGui desktop application.",
description="Start the New QC Sheet PyWebView interface."
)
parser.add_argument('--width', type=int, default=650, help='Window width')
parser.add_argument('--height', type=int, default=700, help='Window height')
return parser.parse_args()
parser.add_argument("--width", type=int, default=800, help="Window width")
parser.add_argument("--height", type=int, default=600, help="Window height")
return parser.parse_args(argv)
def main() -> None:
global rows, addin_paths, config
args = parse_args()
dpg.create_context()
# --- Modern theme ---------------------------------------------------
modern_theme = _create_modern_theme()
dpg.bind_theme(modern_theme)
# --- Load Inter font ------------------------------------------------
font_regular = package_file("fonts/Inter-Regular.ttf")
font_bold = package_file("fonts/Inter-Bold.ttf")
default_font = None
heading_font = None
label_font = None
if font_regular.is_file():
with dpg.font_registry():
default_font = dpg.add_font(str(font_regular), 18)
label_font = dpg.add_font(str(font_regular), 14)
if font_bold.is_file():
heading_font = dpg.add_font(str(font_bold), 28, tag=HEADING_FONT)
# Load config and initialize variables
sets = []
initial_inks = []
error_msg = ""
label_set = 'Select Set'
label_ink = 'Select Ink Color'
label_serial = 'Serial:'
try:
content, loaded_rows, loaded_config = load_config()
rows = loaded_rows
config = loaded_config
if len(content) >= 5:
label_set = content[0]
label_ink = content[1]
label_serial = content[2]
addin_paths = content[3:5]
sets = list_sets(rows)
if sets:
initial_inks = list_ink_colors(rows, sets[0])
except Exception as e:
error_msg = f"Failed to load config: {e}"
with dpg.theme() as tight_theme:
with dpg.theme_component(dpg.mvAll):
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 10, -8)
with dpg.theme() as normal_spacing_theme:
with dpg.theme_component(dpg.mvAll):
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 10, 10)
with dpg.theme() as btn_theme:
with dpg.theme_component(dpg.mvButton):
dpg.add_theme_color(dpg.mvThemeCol_Text, (255, 255, 255, 255))
dpg.add_theme_color(dpg.mvThemeCol_Button, (15, 118, 110, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (17, 94, 89, 255))
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (19, 78, 74, 255))
with dpg.window(tag="primary_window"):
if default_font:
dpg.bind_font(default_font)
title = dpg.add_text('New QC Sheet', color=(17, 94, 89, 255))
if heading_font:
dpg.bind_item_font(title, heading_font)
dpg.add_text(f"v{_VERSION}", color=(100, 106, 120))
dpg.add_spacer(height=4)
dpg.add_separator()
dpg.add_spacer(height=10)
def add_floating_label(text):
lbl = dpg.add_text(text, color=(15, 118, 110, 255))
if label_font:
dpg.bind_item_font(lbl, label_font)
with dpg.group() as g1:
add_floating_label(label_set)
c1 = dpg.add_combo(items=sets, default_value=sets[0] if sets else '',
tag=SET_COMBO, callback=on_set_change, width=-1)
dpg.bind_item_theme(c1, normal_spacing_theme)
dpg.bind_item_theme(g1, tight_theme)
dpg.add_spacer(height=8)
with dpg.group() as g2:
add_floating_label(label_ink)
c2 = dpg.add_combo(items=initial_inks,
default_value=initial_inks[0] if initial_inks else '',
tag=INK_COMBO, width=-1)
dpg.bind_item_theme(c2, normal_spacing_theme)
dpg.bind_item_theme(g2, tight_theme)
dpg.add_spacer(height=8)
with dpg.group() as g3:
add_floating_label(label_serial)
c3 = dpg.add_input_text(tag=SERIAL_INPUT, width=-1, hint="e.g. 1234/A")
dpg.bind_item_theme(c3, normal_spacing_theme)
dpg.bind_item_theme(g3, tight_theme)
dpg.add_spacer(height=10)
dpg.add_separator()
dpg.add_spacer(height=10)
btn = dpg.add_button(label='Create datasheet', width=-1, height=38,
callback=on_create)
dpg.bind_item_theme(btn, btn_theme)
dpg.add_spacer(height=14)
dpg.add_text(error_msg, tag=STATUS_TEXT, wrap=args.width - 40)
if error_msg:
dpg.configure_item(STATUS_TEXT, color=(220, 60, 60))
dpg.create_viewport(title=f'New QC Sheet · v{_VERSION}',
width=args.width, height=args.height)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.set_primary_window("primary_window", True)
dpg.start_dearpygui()
dpg.destroy_context()
def main(argv: list[str] | None = None) -> None:
"""Open the native PyWebView window."""
args = parse_args(argv)
api = Api()
api.initialize()
index_html = package_file("ui/index.html")
webview.create_window(
title=f"New QC Sheet · v{_VERSION}",
url=index_html.as_uri(),
js_api=api,
width=args.width,
height=args.height,
min_size=(450, 400),
background_color="#f8fafc",
)
webview.start()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,590 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>New QC Sheet</title>
<style>
@font-face {
font-family: "Inter";
src: url("../fonts/Inter-Regular.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Inter";
src: url("../fonts/Inter-Bold.ttf") format("truetype");
font-weight: 700;
font-style: normal;
font-display: swap;
}
:root {
--primary: #0f766e;
--secondary: #115e59;
--accent: #14b8a6;
--slate-50: #f8fafc;
--slate-300: #cbd5e1;
--slate-500: #64748b;
--slate-700: #334155;
--status-ready: #f8fafc;
--status-success: #f0fdfa;
--status-skipped: #fffbeb;
--status-error: #fef2f2;
}
* { box-sizing: border-box; }
body {
min-height: 100vh;
margin: 0;
background: var(--slate-50);
color: var(--slate-700);
font-family: "Inter", sans-serif;
font-size: 15px;
}
.page {
display: flex;
min-height: 100vh;
padding: 24px;
}
.panel {
display: flex;
flex: 1;
flex-direction: column;
width: min(100%, 36rem);
margin: auto;
}
h1 {
margin: 0;
color: var(--secondary);
font-size: 1.875rem;
font-weight: 700;
line-height: 2.25rem;
}
.subtitle {
margin: 8px 0 24px;
color: #475569;
line-height: 1.5;
}
.fields { display: grid; gap: 18px; }
.field {
position: relative;
display: block;
padding-top: 8px;
}
.field-label {
position: absolute;
z-index: 1;
top: 0;
left: 11px;
padding: 0 4px;
background: var(--slate-50);
color: var(--primary);
font-size: 0.75rem;
line-height: 1rem;
pointer-events: none;
}
select, input {
width: 100%;
min-height: 54px;
padding: 16px 12px 6px;
border: 1px solid var(--slate-300);
border-radius: 4px;
outline: none;
background: #fff;
color: #0f172a;
font: inherit;
transition: border-color 150ms ease, box-shadow 150ms ease;
}
.combobox-input {
padding-right: 36px;
cursor: text;
}
.combobox { position: relative; }
.combobox > select {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
background: transparent;
}
.combobox-caret {
position: absolute;
top: 0;
right: 12px;
bottom: 0;
display: flex;
align-items: center;
color: var(--slate-500);
pointer-events: none;
font-size: 0.75rem;
}
.combobox-panel {
position: absolute;
top: calc(100% + 4px);
left: 0;
right: 0;
z-index: 5;
max-height: 220px;
overflow-y: auto;
padding: 4px 0;
background: #fff;
border: 1px solid var(--slate-300);
border-radius: 4px;
box-shadow: 0 4px 12px rgb(15 23 42 / 12%);
}
.combobox-panel[hidden] { display: none; }
.combobox-option {
padding: 8px 12px;
cursor: pointer;
color: var(--slate-700);
line-height: 1.25;
}
.combobox-option[aria-selected="true"],
.combobox-option:hover {
background: var(--status-success);
color: var(--secondary);
}
.combobox-option[hidden] { display: none; }
.combobox-empty {
padding: 8px 12px;
color: var(--slate-500);
font-style: italic;
}
select:focus, input:focus,
.combobox-input:focus {
border-color: var(--primary);
box-shadow: 0 0 0 2px rgb(20 184 166 / 25%);
}
select:disabled, input:disabled,
.combobox-input:disabled {
cursor: not-allowed;
background: #f1f5f9;
color: var(--slate-500);
}
.divider {
height: 1px;
margin: 24px 0;
background: var(--slate-300);
}
button {
width: 100%;
min-height: 42px;
border: 0;
border-radius: 4px;
background: var(--primary);
color: #fff;
cursor: pointer;
font: inherit;
font-size: 0.875rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
transition: background-color 150ms ease, box-shadow 150ms ease;
}
button:hover:not(:disabled) {
background: var(--secondary);
box-shadow: 0 2px 5px rgb(15 118 110 / 25%);
}
button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
button:disabled { cursor: not-allowed; opacity: 0.65; }
.status {
min-height: 48px;
margin-top: 16px;
padding: 12px;
border-radius: 4px;
color: var(--slate-700);
line-height: 1.45;
white-space: pre-wrap;
}
.status-ready { background: var(--status-ready); }
.status-success { background: var(--status-success); color: #115e59; }
.status-skipped { background: var(--status-skipped); color: #92400e; }
.status-error { background: var(--status-error); color: #b91c1c; }
.version {
margin: auto 0 0;
padding-top: 24px;
color: #94a3b8;
font-size: 0.75rem;
text-align: right;
}
@media (max-width: 480px) {
.page { padding: 18px; }
h1 { font-size: 1.5rem; }
}
</style>
</head>
<body>
<main class="page">
<section class="panel" aria-labelledby="heading">
<h1 id="heading">New QC Sheet</h1>
<p class="subtitle">Create a new QC datasheet from the latest matching workbook.</p>
<div class="fields">
<label class="field combobox" for="set-dropdown-input">
<span id="set-label" class="field-label">Select Set</span>
<input
id="set-dropdown-input"
class="combobox-input"
type="text"
autocomplete="off"
spellcheck="false"
role="combobox"
aria-expanded="false"
aria-controls="set-dropdown-panel"
aria-autocomplete="list"
aria-labelledby="set-label"
placeholder=" ">
<select id="set-dropdown" aria-labelledby="set-label" tabindex="-1"></select>
<span class="combobox-caret" aria-hidden="true">&#9662;</span>
<div id="set-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="set-label" hidden></div>
</label>
<label class="field combobox" for="ink-dropdown-input">
<span id="ink-label" class="field-label">Select Ink Color</span>
<input
id="ink-dropdown-input"
class="combobox-input"
type="text"
autocomplete="off"
spellcheck="false"
role="combobox"
aria-expanded="false"
aria-controls="ink-dropdown-panel"
aria-autocomplete="list"
aria-labelledby="ink-label"
placeholder=" ">
<select id="ink-dropdown" aria-labelledby="ink-label" tabindex="-1"></select>
<span class="combobox-caret" aria-hidden="true">&#9662;</span>
<div id="ink-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="ink-label" hidden></div>
</label>
<label class="field" for="serial-input">
<span id="serial-label" class="field-label">Serial:</span>
<input id="serial-input" type="text" placeholder="e.g. 1234/A" aria-labelledby="serial-label">
</label>
</div>
<div class="divider"></div>
<button id="create-button" type="button">Create datasheet</button>
<div id="status" class="status status-ready" role="status">Loading configuration...</div>
<p id="version" class="version"></p>
</section>
</main>
<script>
const setDropdown = document.getElementById("set-dropdown");
const inkDropdown = document.getElementById("ink-dropdown");
const setInput = document.getElementById("set-dropdown-input");
const inkInput = document.getElementById("ink-dropdown-input");
const setPanel = document.getElementById("set-dropdown-panel");
const inkPanel = document.getElementById("ink-dropdown-panel");
const serialInput = document.getElementById("serial-input");
const createBtn = document.getElementById("create-button");
const status = document.getElementById("status");
// Builds a searchable combobox. The underlying <select> stays as the
// semantic source of truth; the visible widget is a text <input> plus a
// listbox panel that filters options as the user types.
function createCombobox(selectEl, inputEl, panelEl) {
let openState = false;
let inputDirty = false;
const visibleOptions = () =>
Array.from(panelEl.querySelectorAll(".combobox-option")).filter(
(node) => !node.hidden
);
const open = () => {
if (openState || inputEl.disabled) return;
openState = true;
panelEl.hidden = false;
inputEl.setAttribute("aria-expanded", "true");
filter();
};
const close = () => {
if (!openState) return;
openState = false;
panelEl.hidden = true;
inputEl.setAttribute("aria-expanded", "false");
inputEl.removeAttribute("aria-activedescendant");
for (const node of panelEl.querySelectorAll(".combobox-option")) {
node.setAttribute("aria-selected", "false");
}
};
const setActive = (idx) => {
const options = visibleOptions();
for (const node of panelEl.querySelectorAll(".combobox-option")) {
node.setAttribute("aria-selected", "false");
}
if (idx < 0 || idx >= options.length) {
inputEl.removeAttribute("aria-activedescendant");
return;
}
const node = options[idx];
node.setAttribute("aria-selected", "true");
node.scrollIntoView({ block: "nearest" });
inputEl.setAttribute("aria-activedescendant", node.id);
};
const filter = () => {
const needle = inputDirty ? inputEl.value.trim().toLowerCase() : "";
let firstVisible = -1;
let count = 0;
for (const node of panelEl.querySelectorAll(".combobox-option")) {
const value = (node.dataset.value || "").toLowerCase();
const match = !needle || value.includes(needle);
node.hidden = !match;
if (match) {
if (firstVisible === -1) firstVisible = count;
count += 1;
}
}
const empty = panelEl.querySelector(".combobox-empty");
if (empty) empty.hidden = count > 0;
setActive(firstVisible === -1 ? -1 : 0);
};
const selectValue = (value) => {
if (selectEl.value !== value) {
selectEl.value = value;
selectEl.dispatchEvent(new Event("change", { bubbles: true }));
}
inputEl.value = value;
inputDirty = false;
close();
inputEl.focus();
};
const syncDisabled = () => {
inputEl.disabled = selectEl.disabled;
if (selectEl.disabled) close();
};
const rebuild = () => {
panelEl.replaceChildren();
const values = Array.from(selectEl.options).map((o) => o.value);
for (const value of values) {
const node = document.createElement("div");
node.className = "combobox-option";
node.id = `${selectEl.id}-opt-${CSS.escape(value)}`;
node.setAttribute("role", "option");
node.setAttribute("aria-selected", "false");
node.dataset.value = value;
node.textContent = value;
node.addEventListener("mousedown", (event) => {
// mousedown (not click) so we beat the input's blur handler.
event.preventDefault();
selectValue(value);
});
panelEl.append(node);
}
const empty = document.createElement("div");
empty.className = "combobox-empty";
empty.textContent = "No matches";
empty.hidden = true;
panelEl.append(empty);
if (selectEl.value && !inputEl.value) {
inputEl.value = selectEl.value;
}
inputDirty = false;
syncDisabled();
};
inputEl.addEventListener("focus", open);
inputEl.addEventListener("input", () => {
inputDirty = true;
if (!openState) open();
filter();
});
inputEl.addEventListener("blur", () => {
// Defer close so a mousedown on a panel option can fire first.
setTimeout(() => {
if (inputEl.value !== selectEl.value) {
inputEl.value = selectEl.value || "";
inputDirty = false;
}
close();
}, 0);
});
inputEl.addEventListener("keydown", (event) => {
const options = visibleOptions();
if (event.key === "ArrowDown") {
event.preventDefault();
if (!openState) open();
const idx = options.findIndex(
(n) => n.getAttribute("aria-selected") === "true"
);
setActive(Math.min(idx + 1, options.length - 1));
} else if (event.key === "ArrowUp") {
event.preventDefault();
if (!openState) open();
const idx = options.findIndex(
(n) => n.getAttribute("aria-selected") === "true"
);
setActive(Math.max(idx - 1, 0));
} else if (event.key === "Home") {
if (openState) {
event.preventDefault();
setActive(0);
}
} else if (event.key === "End") {
if (openState) {
event.preventDefault();
setActive(options.length - 1);
}
} else if (event.key === "Enter") {
if (openState) {
event.preventDefault();
const node = panelEl.querySelector(
'.combobox-option[aria-selected="true"]'
);
if (node) selectValue(node.dataset.value);
}
} else if (event.key === "Escape") {
if (openState) {
event.preventDefault();
close();
}
}
});
// Click outside closes the panel.
document.addEventListener("mousedown", (event) => {
if (!openState) return;
if (!inputEl.parentElement.contains(event.target)) close();
});
return { rebuild, syncDisabled };
}
const setCombobox = createCombobox(setDropdown, setInput, setPanel);
const inkCombobox = createCombobox(inkDropdown, inkInput, inkPanel);
function populateDropdown(dropdown, combobox, values) {
dropdown.replaceChildren();
for (const value of values) {
const option = document.createElement("option");
option.value = value;
option.textContent = value;
dropdown.append(option);
}
dropdown.disabled = values.length === 0;
combobox.rebuild();
}
function populateDropdowns(sets, inks) {
populateDropdown(setDropdown, setCombobox, sets);
populateDropdown(inkDropdown, inkCombobox, inks);
}
function populateInkDropdown(inks) {
populateDropdown(inkDropdown, inkCombobox, inks);
}
function setLabels(labels) {
document.getElementById("set-label").textContent = labels.set;
document.getElementById("ink-label").textContent = labels.ink;
document.getElementById("serial-label").textContent = labels.serial;
}
function setVersion(version) {
document.getElementById("version").textContent = `v${version}`;
}
function showStatus(result) {
const details = [result.message];
if (result.template) details.push(`Template: ${result.template}`);
if (result.destination) details.push(`Output: ${result.destination}`);
if (result.backend) details.push(`Backend: ${result.backend}`);
status.textContent = details.join("\n");
status.className = "status";
if (result.skipped) {
status.classList.add("status-skipped");
} else if (result.ok) {
status.classList.add("status-success");
} else {
status.classList.add("status-error");
}
}
async function initialize() {
try {
const data = await window.pywebview.api.get_initial_data();
populateDropdowns(data.sets, data.inks);
setLabels(data.labels);
setVersion(data.version);
showStatus({ message: "Ready.", ok: true, skipped: false });
} catch (error) {
showStatus({ message: `Failed to load configuration: ${error}`, ok: false, skipped: false });
createBtn.disabled = true;
}
}
setDropdown.addEventListener("change", async () => {
try {
const inks = await window.pywebview.api.get_inks(setDropdown.value);
populateInkDropdown(inks);
} catch (error) {
showStatus({ message: `Failed to load ink colors: ${error}`, ok: false, skipped: false });
}
});
createBtn.addEventListener("click", async () => {
createBtn.disabled = true;
try {
const result = await window.pywebview.api.create(
setDropdown.value, inkDropdown.value, serialInput.value
);
showStatus(result);
} catch (error) {
showStatus({ message: `Failed to create datasheet: ${error}`, ok: false, skipped: false });
} finally {
createBtn.disabled = false;
}
});
window.addEventListener("pywebviewready", initialize);
</script>
</body>
</html>