diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 920e4b3..8b23955 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -39,7 +39,7 @@ QuantUI/ │ ├── app_launcher.py ← `quantui run app` / `quantui view` Voilà launch │ ├── app_viewer.py ← read-only viewer mode (History + Analysis only) │ ├── app_workspace.py ← two-pane workspace: persistent viewer pane, view toolbar, atom list, status footer -│ ├── app_pane_views.py ← Populations / Vibrational / Isosurface panels show their 3D view in the pane (one viewer) +│ ├── app_pane_views.py ← Populations / Vibrational / Isosurface / Trajectory / Geometries panels (and PES-plot clicks) show their 3D view in the pane (one viewer; stepper controls stay in the panel) │ ├── app_a11y.py ← page script for menu ARIA roles + arrow keys, dialog focus, live status region, skip link │ ├── app_menubar.py ← menu bar (File / Calculate / View / Results / Help); items call existing handlers │ ├── app_setup_dialog.py ← modal dialog that moves calc_setup_panel in and back out diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a87c79..eca5a51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,83 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +## [0.15.0] - 2026-12-06 + +### Changed + +- **Trajectory, Geometries and PES Scan use the workspace pane's viewer.** + With the two-pane workspace on, the optimization trajectory (also the + frequency pre-optimization, IRC path and scan points), the reorganization + energy Geometries viewer and the PES Scan geometries play in the viewer + pane, with the same "Showing … — Back to structure" banner as the + Populations, Vibrational and Isosurface views. The play / step buttons, + slider, frame label and the energy plots stay in their panels and drive + the pane's viewer; the panel shows a one-line note where its viewer was. + Clicking a point on a 1-D PES profile or a 2-D PES map shows that point's + geometry in the pane, even before the Trajectory panel was opened. + Collapsing the panel, a new result or a Calculate-tab pick mode brings the + structure back. With the workspace turned off, each panel keeps its own + viewer as before. + +- **Menus say why an item is unavailable.** A greyed-out menu item now has a + short muted line under it with the reason ("Load a molecule first", + "Available after: Single Point, Geometry Opt"), so you no longer have to + hover to find out. Screen readers read the reason with the item; the + tooltip stays. +- **No more emoji as status icons.** Error and warning texts use Font + Awesome icons in the app (XYZ errors, the Slurm error panel, the step + progress box, help notes, the "RI" badge) and plain words in plain text + (XYZ and charge/multiplicity errors, structure search messages, run + summaries such as "Warning: SCF did not converge"). Compare's Converged + column says Yes / **No**; the basis-set help table drops its emoji. +- **Run boxes and the run log follow the theme.** The "Calculation failed", + "Calculation cancelled", "Result NOT saved" and dependency boxes, the + Slurm error panel and the cluster banner used light-only pinks and + yellows (a pale box on a dark page); they now use the palette's surfaces + with text that meets WCAG AA. A new `surface_error_bg` theme token backs + the error boxes. The coloured lines of the run log use theme colours too. +- **Plot colours read on every theme.** Spectrum, energy-level, Compare, + charge and PES traces use one set of mid-tone data colours that keep at + least 3:1 contrast on light and dark backgrounds, also in exported files + (the blue occupied levels were 2.8:1 on Dark, the grey virtual levels + 1.7:1 on Bright). Grid and axis colours of the plot modules come from the + theme. The Bright theme's teal is a little darker so teal log lines meet + 4.5:1. +- **Scrollbars and selected text follow the theme.** Scrollbars use the + palette's border and panel colours instead of the browser's light + default, and selected text is highlighted in the theme's accent. +- **Fewer boxes inside boxes.** A tab set inside another tab's panel (the + Library / XYZ Input / Online Search / Upload File tabs under Molecule + Input) no longer draws its own frame and background; a single line under + its tab bar keeps the tabs grouped with their content. +- **Run answers the click at once.** The moment you click Run (or Run in + the menu or the setup dialog), the button turns into a spinner reading + "Starting…", the run status, the header chip and the footer say + "Starting…", and screen readers hear "Starting the calculation…" — before + any checks or program output. Then the usual "Running …" states take + over, and the button reads "Running…" until the run ends. If the run + does not start (a setting to fix, say), Run comes straight back with the + reason. +- **Screen readers can name icon buttons and unlabelled fields.** Buttons + that show only an icon or a glyph (the "?" help buttons, refresh, trash, + previous / next, the viewer frame steppers) take their tooltip as their + accessible name, so a screen reader says "RHF vs UHF — opens Help tab" + instead of "question mark". Fields without a visible label (the engine + and execution menus, the atom table's symbol and x / y / z boxes, the + orbital gallery span, the Compare export format, the Files list) have a + name too, and the hidden helper fields used for PNG capture and atom + picking are no longer in the Tab order. + +### Fixed + +- Slider tracks show again in Chromium-based browsers (the Trajectory, + Geometries and vibration steppers drew only the handle): the slider style + mixed rules for two browser engines in one selector list, which browsers + discard as a whole. +- Clicking the gold "minimum" star on a 1-D PES profile opens that scan + point's geometry (it opened the first point); clicking a failed point no + longer opens an unrelated geometry. + ## [0.14.0] - 2026-12-05 ### Added @@ -1917,7 +1994,8 @@ Initial public scaffolding of the QuantUI package: `quantui` package with `calculator.py`, basic notebook launcher, Apptainer container definition, MIT license, and project metadata. -[Unreleased]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.14.0...HEAD +[Unreleased]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.15.0...HEAD +[0.15.0]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.14.0...v0.15.0 [0.14.0]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.2...v0.14.0 [0.13.2]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.1...v0.13.2 [0.13.1]: https://github.com/The-Schultz-Lab/QuantUI/compare/v0.13.0...v0.13.1 diff --git a/CLAUDE.md b/CLAUDE.md index db4c1a3..381c05f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,7 +63,7 @@ pytest tests/test_foo.py -n0 # one test, serial (breakpoints work; -n=auto is o pre-commit run --all-files # file hygiene + nbstripout + black (26.5.1) + ruff (v0.16.0); mypy runs on pre-push and in CI ``` -Test baseline (see STATUS): **~5410 passed / 11 skipped** for +Test baseline (see STATUS): **~6219 passed / 11 skipped** for `pytest -m "not network and not weekly"` (what PR CI runs; cloud, Python 3.11, 2026-12). `weekly`-marked tests (full backend cross-check, PyFock cases) run in `.github/workflows/xcheck-weekly.yml`. `network`-marked tests diff --git a/pyproject.toml b/pyproject.toml index 6649468..dd9f197 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ build-backend = "setuptools.build_meta" [project] name = "quantui" -version = "0.14.0" +version = "0.15.0" description = "An open-source frontend for DFT and post-HF quantum chemistry with PySCF" readme = "README.md" requires-python = ">=3.9" diff --git a/quantui/__init__.py b/quantui/__init__.py index 24b238e..da70853 100644 --- a/quantui/__init__.py +++ b/quantui/__init__.py @@ -7,7 +7,7 @@ PySCF requires Linux/macOS/WSL. Windows users should use the Apptainer container. """ -__version__ = "0.14.0" +__version__ = "0.15.0" import logging from typing import Any diff --git a/quantui/app.py b/quantui/app.py index 957147f..a70e492 100644 --- a/quantui/app.py +++ b/quantui/app.py @@ -302,6 +302,9 @@ from quantui.app_runflow import ( frozen_atom_indices as _run_frozen_atoms, ) +from quantui.app_runflow import ( + mark_run_running as _run_mark_running, +) from quantui.app_runflow import ( on_accumulate as _run_on_accumulate, ) @@ -407,6 +410,9 @@ from quantui.app_runflow import ( on_reset_click as _run_on_reset_click, ) +from quantui.app_runflow import ( + on_run_button_disabled_changed as _run_on_run_button_disabled_changed, +) from quantui.app_runflow import ( on_run_clicked as _run_on_run_clicked, ) @@ -1048,6 +1054,13 @@ class carries a per-app uid suffix. LiveLog also sets the stack inline — this height: auto !important; } .quantui-history-recent:hover { text-decoration: underline !important; } +/* Run clicked / running (UX-34): busy, not "unavailable". Outranks the + dashed disabled look of theme.disabled_button_css. */ +button.jupyter-button.mod-success.quantui-run-busy:disabled { + border-style: solid !important; + color: var(--q-text-body) !important; + cursor: progress !important; +} /* Job status: a chip, not a button (UX-4). Hover still shows its tooltip. */ .quantui-status-chip { cursor: default !important; @@ -3349,6 +3362,11 @@ def _wire_callbacks(self) -> None: self.calc_type_help_btn.on_click(self._on_calc_type_help) # Run self.run_btn.on_click(self._on_run_clicked) + # Run re-enabled however the run ended: back to its idle label (UX-34). + self.run_btn.observe( + self._safe_cb(lambda ch: _run_on_run_button_disabled_changed(self, ch)), + names="disabled", + ) self._slurm_reconnect_btn.on_click( self._safe_cb(lambda _btn: _slurm_on_reconnect_clicked(self, _btn)) ) @@ -4151,7 +4169,7 @@ def _preview_file_path(self, path: Path) -> None: "" + "".join( f'{_html.escape(str(c))}' for c in r ) @@ -5366,11 +5384,8 @@ def _on_calc_type_help(self, btn) -> None: # ── Run ─────────────────────────────────────────────────────────────── def _on_run_clicked(self, btn) -> None: - self._activity_pulse( - "Queueing calculation...", - hold_s=0.18, - kind="compute", - ) + # The click is acknowledged by a "Starting…" state (UX-34), which + # replaces the old 0.18 s "Computing…" pulse. _run_on_run_clicked(self, btn) def _on_cancel(self, btn=None) -> None: @@ -7000,8 +7015,9 @@ def _do_run(self) -> None: "Running compute operations...", kind="compute", ) - self.run_btn.disabled = True - self.run_status.value = "Starting..." + # The click already showed "Starting…" (UX-34); the run is under way. + _run_mark_running(self) + self.run_status.value = "Starting…" # Run-in-flight state: arm Cancel, lock out Clear (so it can't wipe the # live output mid-run), reset the cancel flag for this fresh run. self._calc_running = True @@ -7215,10 +7231,10 @@ def _run_required_final_single_point(target_mol, reason: str): if _preopt_warning: result_html = ( - '
' - f"⚠ {_html.escape(_preopt_warning)}
" + result_html + f'
' + f'⚠ ' + f"{_html.escape(_preopt_warning)}
" + result_html ) self.result_output.append_display_data(HTML(result_html)) self.run_status.value = "Finalizing results..." @@ -7349,11 +7365,10 @@ def _run_required_final_single_point(target_mol, reason: str): pass self.result_output.append_display_data( HTML( - '
' + f'
' f'' "⚠ Result NOT saved
" - 'The calculation finished, ' + f'The calculation finished, ' "but writing it to the results folder failed: " f"{_html.escape(_save_error)}. It is not in " "History, and the export buttons have no results folder " @@ -7525,11 +7540,10 @@ def _run_required_final_single_point(target_mol, reason: str): ) log.write(_msg) _err_html = ( - '
' + f'
' f'⚠ Dependency Not Available
' - f'{_html.escape(_err_detail)}

' - '' + f'{_html.escape(_err_detail)}

' + f'' f"{_html.escape(_dependency_hint())} " "Full details are in the Output tab." "
" @@ -7555,10 +7569,9 @@ def _run_required_final_single_point(target_mol, reason: str): log.write("\n── Calculation cancelled by user ──\n") self.result_output.append_display_data( HTML( - '
' - '■ Calculation cancelled
' - 'Stopped at your request — no ' + f'
' + f'■ Calculation cancelled
' + f'Stopped at your request — no ' "results were saved. Adjust the settings and run again." "
" ) @@ -7636,11 +7649,10 @@ def _run_required_final_single_point(target_mol, reason: str): pass # Clean summary → result panel (student-facing) _err_html = ( - '
' + f'
' f'⚠ Calculation Failed
' - f'{_html.escape(str(exc))}

' - '' + f'{_html.escape(str(exc))}

' + f'' "Tips: try a smaller basis set (STO-3G), use a geometry-optimized " "structure first, or check for unusually long/short bonds in your " "XYZ input. Full error details are in the Output tab." @@ -8472,9 +8484,9 @@ def _run_calc_single_point(self, rc: _RunContext) -> None: if _n_heavy > 20: self.result_output.append_display_data( HTML( - f'
' - f"⚠️ MP2 scales as O(N⁵) — this molecule has {_n_heavy} heavy atoms " + f'
' + f" MP2 scales as O(N⁵) — this molecule has {_n_heavy} heavy atoms " "and may be slow. Consider using DFT instead.
" ) ) @@ -8809,7 +8821,7 @@ def _resume_hint_html(self, ckpt: Optional[Any]) -> str: if not points: done = "the steps completed so far" return ( - '

' + f'

' f"♻ This run can be resumed. {done} " "were saved. Leave the settings as they are and press " "Run again — the Resume from checkpoint box " @@ -8939,15 +8951,15 @@ def _render_log(self, text: str, source_label: str = "") -> None: esc = _html_mod.escape(line) # ── Log header / footer structure ───────────────────────────────── if len(line) >= 40 and line == "=" * len(line): - style = "color:#1e3a5f;font-weight:700" + style = f"color:{_theme.css.TEXT_HEADING};font-weight:700" elif "QuantUI — Quantum Chemistry Interface" in line: - style = "color:#6d28d9;font-weight:700" + style = f"color:{_theme.css.ACCENT_PURPLE};font-weight:700" elif line.startswith(" ── "): style = f"color:{_theme.css.TEXT_BODY};font-weight:700" elif line.startswith(" ✓"): style = f"color:{_theme.css.ACCENT_SUCCESS};font-weight:700" elif line.startswith(" ✗"): - style = "color:#dc2626;font-weight:700" + style = f"color:{_theme.css.ACCENT_ERROR};font-weight:700" elif ( line.startswith(" Machine:") or line.startswith(" GPU:") @@ -8960,17 +8972,17 @@ def _render_log(self, text: str, source_label: str = "") -> None: or line.startswith(" Calc type:") or line.startswith(" Started:") ): - style = "color:#1d4ed8" + style = f"color:{_theme.css.ACCENT_INFO}" elif ( line.startswith(" Energy:") or line.startswith(" HOMO-LUMO gap:") or line.startswith(" ZPVE:") ): - style = "color:#0f766e;font-weight:600" + style = f"color:{_theme.css.TEXT_HEADING};font-weight:600" elif line.startswith(" Wall time:"): style = f"color:{_theme.css.TEXT_SLATE}" elif line.startswith(" ✔") or line.startswith(" ⚠"): - style = "color:#d97706" + style = f"color:{_theme.css.ACCENT_WARNING}" # ── Geometry optimisation (ASE BFGS) ────────────────────────────── elif line.startswith("BFGS:"): m = _bfgs_re.match(line) @@ -8988,9 +9000,9 @@ def _render_log(self, text: str, source_label: str = "") -> None: style = f"color:{_theme.css.TEXT_BODY};font-weight:700" # ── Post-optimisation summary ────────────────────────────────────── elif line.startswith("── Final SCF"): - style = "color:#6d28d9;font-weight:600" + style = f"color:{_theme.css.ACCENT_PURPLE};font-weight:600" elif "HOMO-LUMO gap:" in line: - style = "color:#6d28d9;font-weight:600" + style = f"color:{_theme.css.ACCENT_PURPLE};font-weight:600" # ── SCF convergence ──────────────────────────────────────────────── elif "converged SCF energy" in line or "SCF converged" in line: style = f"color:{_theme.css.ACCENT_SUCCESS};font-weight:600" @@ -8998,13 +9010,13 @@ def _render_log(self, text: str, source_label: str = "") -> None: style = f"color:{_theme.css.TEXT_SLATE}" # ── MO / orbital info (verbose=4) ────────────────────────────────── elif "MO energies" in line or "** MO" in line: - style = "color:#1d4ed8;font-weight:600" + style = f"color:{_theme.css.ACCENT_INFO};font-weight:600" elif "HOMO" in line or "LUMO" in line or "All MO energies" in line: style = f"color:{_theme.css.ACCENT_INFO}" elif line.lstrip().startswith("occupied:") or line.lstrip().startswith( "virtual:" ): - style = "color:#3b82f6" + style = f"color:{_theme.css.ACCENT_INFO}" # ── Thermo / properties ──────────────────────────────────────────── elif "Mulliken" in line or "mulliken" in line: style = f"color:{_theme.css.ACCENT_PURPLE}" @@ -9013,12 +9025,12 @@ def _render_log(self, text: str, source_label: str = "") -> None: elif "nuclear repulsion" in line.lower() or "Nuclear repulsion" in line: style = f"color:{_theme.css.TEXT_SUBTLE}" elif "E(MP2)" in line or "MP2 correlation" in line: - style = "color:#0891b2" + style = f"color:{_theme.css.ACCENT_TEAL}" # ── Warnings / errors ────────────────────────────────────────────── elif "Warning" in line or "warning" in line: - style = "color:#d97706" + style = f"color:{_theme.css.ACCENT_WARNING}" elif "Error" in line or "error" in line or "failed" in line: - style = "color:#dc2626" + style = f"color:{_theme.css.ACCENT_ERROR}" else: style = f"color:{_theme.css.TEXT_STRONG}" rows.append(f'
{esc}
') diff --git a/quantui/app_a11y.py b/quantui/app_a11y.py index d8f3a08..be342d4 100644 --- a/quantui/app_a11y.py +++ b/quantui/app_a11y.py @@ -11,7 +11,8 @@ - **Menu bar semantics:** ``role="menubar"`` / ``"menu"`` / ``"menuitem"``, ``aria-haspopup`` and ``aria-expanded`` on the titles, ``aria-disabled`` on - unavailable items. + unavailable items, and ``aria-describedby`` pointing at the muted line + under an unavailable item that says why. - **Menu keyboard navigation:** ArrowDown / ArrowUp open a menu and move through its enabled items, ArrowLeft / ArrowRight move between menus, Home / End jump to the first / last item, Esc closes the menu (the existing @@ -20,8 +21,12 @@ the dialog when it opens, Tab stays inside it, and focus returns to the control that opened it when it closes. - **Run status announcements:** a visually hidden ``role="status"`` live - region (:func:`build_live_region`) that :func:`announce` fills when a run - starts, finishes or fails. + region (:func:`build_live_region`) that :func:`announce` fills when Run is + clicked, and when a run starts, finishes or fails. +- **Names for icon-only buttons:** a button whose text is empty or only a + glyph ("?", an arrow, a trash or refresh icon) gets its tooltip as its + ``aria-label``. :func:`unnamed_controls` lists any icon-only button or + description-less field that has no tooltip to take a name from. - **Shorter tab path:** the header status chip (a display, not a control) is taken out of the Tab order, and a "Skip to molecule input" link becomes visible on the first Tab press (:func:`skip_link_html`). @@ -36,6 +41,7 @@ import html as _html import logging +import re from typing import Any import ipywidgets as widgets @@ -87,7 +93,8 @@ window.__quantuiA11y = true; var BAR=".__BAR__", MENU=".__MENU__", TITLE=".__TITLE__", LIST=".__LIST__", ITEM=".__ITEM__", OPEN="__OPEN__", PANEL=".__PANEL__", BODY=".__BODY__", - BACKDROP=".__BACKDROP__", LIVE=".__LIVE__", CHIP=".__CHIP__"; + BACKDROP=".__BACKDROP__", LIVE=".__LIVE__", CHIP=".__CHIP__", + REASON=".__REASON__"; var FOCUSABLE="button:not(:disabled), select:not(:disabled), "+ "input:not(:disabled):not([type=hidden]), textarea:not(:disabled), "+ "a[href], [tabindex]:not([tabindex='-1'])"; @@ -109,13 +116,20 @@ var m=l.closest(MENU), t=m && m.querySelector(TITLE); if (t) { set(l,"aria-label", t.textContent.trim()); } Array.prototype.forEach.call(l.children, function(c){ - if (!c.matches(ITEM)) { set(c,"role","presentation"); } + // The reason line is read as the item's description instead. + if (c.matches(REASON)) { set(c,"aria-hidden","true"); } + else if (!c.matches(ITEM)) { set(c,"role","presentation"); } }); }); all(ITEM).forEach(function(i){ set(i,"role","menuitem"); set(i,"tabindex","-1"); set(i,"aria-disabled", i.disabled ? "true" : "false"); + // Unavailable item: its muted reason line (the next sibling) becomes + // its accessible description (UX-22). + var r=i.nextElementSibling, s=r && r.matches(REASON) && r.querySelector("[id]"); + if (i.disabled && s && shown(r)) { set(i,"aria-describedby", s.id); } + else if (i.hasAttribute("aria-describedby")) { i.removeAttribute("aria-describedby"); } }); all(PANEL).forEach(function(p){ set(p,"role","dialog"); set(p,"aria-modal","true"); @@ -125,8 +139,29 @@ set(r,"role","status"); set(r,"aria-live","polite"); set(r,"aria-atomic","true"); }); all(CHIP).forEach(function(c){ set(c,"tabindex","-1"); set(c,"aria-hidden","true"); }); + iconNames(); + // Hidden JS-bridge fields (PNG captures, atom picks): not for people. + all('[class$="__INBOX__"] textarea, [class*="__INBOX__ "] textarea').forEach(function(t){ + set(t,"tabindex","-1"); set(t,"aria-hidden","true"); + }); dialogFocus(); } + // Icon-only and glyph buttons ("?", arrows, the trash and refresh icons, + // viewer steppers): their text says nothing, so their tooltip becomes + // their accessible name. Buttons with real text keep it. + var GLYPH=/^[^A-Za-z0-9]{0,3}$/; + function iconNames(){ + all("button").forEach(function(b){ + var tip=b.getAttribute("title"), auto=b.getAttribute("data-quantui-aria") === "1"; + if (tip && GLYPH.test((b.textContent || "").trim())) { + if (b.getAttribute("aria-label") !== tip) { + b.setAttribute("aria-label", tip); b.setAttribute("data-quantui-aria","1"); + } + } else if (auto) { + b.removeAttribute("aria-label"); b.removeAttribute("data-quantui-aria"); + } + }); + } function later(){ [60, 250, 700].forEach(function(ms){ setTimeout(roles, ms); }); } // Voila renders widgets progressively: keep applying for a while after load. var boot=0, bootTimer=setInterval(function(){ roles(); if (++boot > 40) { clearInterval(bootTimer); } }, 500); @@ -250,6 +285,7 @@ def a11y_js() -> str: MENU_ITEM_CLASS, MENU_LIST_CLASS, MENU_OPEN_CLASS, + MENU_REASON_CLASS, MENU_TITLE_CLASS, MENUBAR_CLASS, ) @@ -267,6 +303,8 @@ def a11y_js() -> str: "__BACKDROP__": BACKDROP_CLASS, "__LIVE__": LIVE_REGION_CLASS, "__CHIP__": STATUS_CHIP_CLASS, + "__REASON__": MENU_REASON_CLASS, + "__INBOX__": BRIDGE_CLASS_SUFFIX, } js = _A11Y_JS # Longest first, so __BAR__ cannot eat part of __BACKDROP__. @@ -275,6 +313,92 @@ def a11y_js() -> str: return js +# --------------------------------------------------------------------------- +# Accessible names +# --------------------------------------------------------------------------- + +# Hidden textareas the page writes into (PNG captures, atom picks) carry a +# class ending in this; the page script takes them out of the Tab order and +# hides them from screen readers. +BRIDGE_CLASS_SUFFIX = "-inbox" + +# Same test as GLYPH in the page script: no letters or digits to read out. +_GLYPH_ONLY = re.compile(r"^[^A-Za-z0-9]{0,3}$") + +# Fields that take their accessible name from a description, else from the +# tooltip (ipywidgets 8 sets ``title`` on a description-less field). +_NAMED_FIELDS = ( + widgets.Dropdown, + widgets.Select, + widgets.SelectMultiple, + widgets.Text, + widgets.Textarea, + widgets.FloatText, + widgets.IntText, + widgets.BoundedFloatText, + widgets.BoundedIntText, + widgets.IntSlider, + widgets.FloatSlider, + widgets.Checkbox, + widgets.ToggleButton, +) + + +def _walk_widgets(roots: Any) -> list: + seen: set = set() + out: list = [] + stack = list(roots) + while stack: + w = stack.pop() + if not isinstance(w, widgets.Widget) or id(w) in seen: + continue + seen.add(id(w)) + out.append(w) + stack.extend(getattr(w, "children", ()) or ()) + return out + + +def unnamed_controls(roots: Any) -> list: + """Controls under *roots* that a screen reader could not name. + + An icon-only or glyph button ("?", an arrow, a trash icon) or a + ToggleButtons option without a tooltip, and a field with neither a + description nor a tooltip. Returns ``(widget, why)`` pairs. + """ + found = [] + for w in _walk_widgets(roots): + if isinstance(w, widgets.Button): + if ( + _GLYPH_ONLY.match((w.description or "").strip()) + and not (w.tooltip or "").strip() + ): + found.append((w, f"icon-only button {w.icon!r} has no tooltip")) + elif isinstance(w, widgets.ToggleButtons): + labels = [str(lbl) for lbl in getattr(w, "_options_labels", ())] + tips = list(w.tooltips or ()) + for i, lbl in enumerate(labels): + tip = tips[i] if i < len(tips) else "" + if _GLYPH_ONLY.match(lbl.strip()) and not str(tip).strip(): + found.append((w, f"option {i} ({lbl!r}) has no tooltip")) + elif isinstance(w, _NAMED_FIELDS): + if any(c.endswith(BRIDGE_CLASS_SUFFIX) for c in w._dom_classes): + continue # hidden JS bridge, hidden from screen readers + names = ( + w.description, + getattr(w, "tooltip", None), + getattr(w, "placeholder", None), + ) + # ipywidgets' default placeholder is a zero-width space. + if not any(str(n or "").replace("\u200b", "").strip() for n in names): + found.append( + ( + w, + f"{type(w).__name__} has no description, tooltip or placeholder", + ) + ) + return found + + # --------------------------------------------------------------------------- # Skip link # --------------------------------------------------------------------------- @@ -334,6 +458,7 @@ def announce(app: Any, text: str) -> None: _JOB_ANNOUNCEMENTS = { + "starting": "Starting the calculation…", "running": "{label}", "done": "Calculation finished. Results are ready.", "failed": "Calculation failed. See the Calculate tab for the reason.", @@ -364,4 +489,5 @@ def announce_job_state(app: Any, key: str, label: str) -> None: "announce_job_state", "build_live_region", "skip_link_html", + "unnamed_controls", ] diff --git a/quantui/app_analysis.py b/quantui/app_analysis.py index 9be1992..6a8adef 100644 --- a/quantui/app_analysis.py +++ b/quantui/app_analysis.py @@ -362,6 +362,9 @@ def _apply_analysis_context(app: Any, ctx: Any) -> None: # traj_output is a VBox (see app_builders.py traj_output construction); # clear children instead of clear_output. app.traj_output.children = () + from quantui.app_pane_views import clear_viewer + + clear_viewer(app, "Trajectory") app._orb_iso_output.clear_output() first_auto_selected = False @@ -543,12 +546,14 @@ def render_reorg_geometries(app: Any) -> None: geoms = getattr(app, "_reorg_geometries", None) if not geoms: return + from quantui.app_pane_views import set_viewer_html from quantui.app_visualization import ( - build_reorg_geometry_viewer_html, + build_reorg_geometry_viewer_parts, build_reorg_overlay_html, ) bg = app._plotly_theme_colors()["scene_bgcolor"] + html: Any try: if app._reorg_view_toggle.value == "overlay": idx = int(app._reorg_overlay_pair.value or 1) @@ -566,13 +571,16 @@ def render_reorg_geometries(app: Any) -> None: if getattr(app, "_reorg_png_inbox", None) is not None else "" ) - html = build_reorg_geometry_viewer_html( + html = build_reorg_geometry_viewer_parts( geoms, bgcolor=bg, capture_class=capture_class ) - app._set_html_output(app._reorg_geom_output, html) + # One fragment in the panel, or the viewer in the workspace pane and + # the stepper controls here (app_pane_views). + set_viewer_html(app, "Geometries", html) except Exception as exc: # noqa: BLE001 - app._set_html_output( - app._reorg_geom_output, + set_viewer_html( + app, + "Geometries", f'

Geometry view failed: {exc}

', ) diff --git a/quantui/app_builders.py b/quantui/app_builders.py index c64ea9a..08b48f0 100644 --- a/quantui/app_builders.py +++ b/quantui/app_builders.py @@ -409,6 +409,8 @@ def _render_status(gpu_state: Any) -> str: options=engine_options, value=quantum_engine, description="", + # No visible description: the tooltip is its accessible name. + tooltip="Quantum engine", layout=layout_fn(width="360px"), ) app.quantum_engine_note = widgets.HTML(value="") @@ -508,6 +510,7 @@ def _render_status(gpu_state: Any) -> str: options=exec_options, value=execution_backend if execution_backend in ("local", "slurm") else "local", description="", + tooltip="Where calculations run", layout=layout_fn(width="320px"), ) if not slurm_available: @@ -746,7 +749,7 @@ def build_history_section( ], layout=layout_fn( display="none", - border="1px solid #fca5a5", + border=f"1px solid {_theme.css.ACCENT_ERROR}", padding="8px 10px", margin="6px 0 0", ), @@ -2638,6 +2641,17 @@ def _plot_export_row(prefix: str) -> widgets.HBox: # `with output: display(widget)` to be deferred/asynchronous, leaving the # accordion visibly empty even after _show_opt_trajectory logged success. app.traj_output = widgets.VBox(layout=layout_fn(margin="0")) + # The trajectory viewer and its stepper controls live for the app's + # lifetime (each render refills them) so the workspace can move the + # viewer into the pane while the controls stay in the panel + # (app_pane_views). min_height, not height: the framed fragment would + # lose its bottom border. + app._traj_viewer_output = widgets.Output( + layout=layout_fn( + min_height="420px", width="100%", max_width="500px", overflow="hidden" + ) + ) + app._traj_controls_output = widgets.Output(layout=layout_fn(margin="0")) app.traj_accordion = widgets.Accordion( children=[app.traj_output], layout=layout_fn(display="none", margin="8px 0"), @@ -3013,7 +3027,9 @@ def _plot_export_row(prefix: str) -> widgets.HBox: max=200, step=2, # Labelled by the "Levels shown:" text before it; its own "Show N:" - # description was truncated to "Show …". + # description was truncated to "Show …". The tooltip names it for + # screen readers. + tooltip="Levels shown", layout=layout_fn(width="70px"), ) # D2: core levels (hundreds of eV down) squeezed the valence orbitals into @@ -3154,6 +3170,7 @@ def _plot_export_row(prefix: str) -> widgets.HBox: ("HOMO−3 … LUMO+3 (8)", 4), ], value=3, + tooltip="Orbitals in the gallery", layout=layout_fn(width="220px"), ) app._orb_gallery_box = widgets.HBox( @@ -3450,6 +3467,9 @@ def _plot_export_row(prefix: str) -> widgets.HBox: app._reorg_geom_output = widgets.Output( layout=layout_fn(min_height="470px", overflow="hidden") ) + # The stepper's controls when the viewer is in the workspace pane + # (app_pane_views); empty in the single-column layout. + app._reorg_controls_output = widgets.Output(layout=layout_fn(margin="0")) app._reorg_view_toggle = widgets.ToggleButtons( options=[("Step through", "step"), ("Overlay", "overlay")], value="step", @@ -3503,6 +3523,7 @@ def _plot_export_row(prefix: str) -> widgets.HBox: app._reorg_overlay_pair, app._reorg_exaggerate, app._reorg_geom_output, + app._reorg_controls_output, widgets.HBox( [app._reorg_export_btn, app._reorg_export_status], layout=layout_fn(align_items="center"), @@ -4539,6 +4560,7 @@ def build_files_tab(app: Any, *, layout_fn: Any) -> None: options=[("(no files)", "")], rows=12, description="", + tooltip="Files in this folder", layout=layout_fn(width="100%"), ) app._files_up_btn = widgets.Button( diff --git a/quantui/app_compare_tools.py b/quantui/app_compare_tools.py index 5ffee1d..749550c 100644 --- a/quantui/app_compare_tools.py +++ b/quantui/app_compare_tools.py @@ -131,6 +131,7 @@ def build_compare_tools(app: Any, *, layout_fn: Any) -> widgets.Widget: app._cmpx_spec_fmt_dd = widgets.Dropdown( options=[("HTML", "html"), ("PNG", "png")], value="html", + tooltip="Export format", layout=layout_fn(width="90px"), ) app._cmpx_spec_export_btn = widgets.Button( diff --git a/quantui/app_formatters.py b/quantui/app_formatters.py index 6ae879b..56875ed 100644 --- a/quantui/app_formatters.py +++ b/quantui/app_formatters.py @@ -336,7 +336,7 @@ def _num(label: str, value: str) -> str: if bool(get("density_fit", False)): rows += ( f'Density fitting' - f'⚡ RI ' + f' RI ' f'' "(approximate 2-electron integrals)" ) diff --git a/quantui/app_menubar.py b/quantui/app_menubar.py index 81a6db3..cb2e889 100644 --- a/quantui/app_menubar.py +++ b/quantui/app_menubar.py @@ -15,7 +15,8 @@ Item state is read from those same widgets when a menu opens (and, for Run / Cancel, again whenever the real buttons change): an item whose button is -disabled is disabled too, with a tooltip saying why. +disabled is disabled too, with a muted line under it (and a tooltip) saying +why. The bar can be switched off (System Settings → Menu bar, ``ui.menu_bar``). """ @@ -24,6 +25,7 @@ import html as _html import logging +import re from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union @@ -38,6 +40,12 @@ MENU_LIST_CLASS = "quantui-menu-list" MENU_ITEM_CLASS = "quantui-menu-item" MENU_HEAD_CLASS = "quantui-menu-head" +# The muted second line under an unavailable item, saying why (UX-22). +MENU_REASON_CLASS = "quantui-menu-reason" +MENU_REASON_TEXT_CLASS = "quantui-menu-reason-text" +# Text token of that line; tests/test_theme_contrast.py checks it clears +# 4.5:1 on the menu's background (bg_panel) in every palette. +MENU_REASON_TOKEN = "text_subtle" RUN_PANEL_CLASS = "quantui-run-panel" EXPORT_ACC_CLASS = "quantui-export-acc" ANA_PANEL_CLASS_PREFIX = "quantui-ana-panel-" @@ -104,6 +112,15 @@ .{MENU_LIST_CLASS} > * {{ flex-shrink: 0; }} +/* Long menus scroll inside the list. The bar's "overflow: visible" rule + above (.{MENUBAR_CLASS} .widget-box) outranked the list's own overflow, + so a list taller than 70vh (Results, with a reason under each + unavailable panel) spilled past its frame. */ +.{MENUBAR_CLASS} .widget-box.{MENU_LIST_CLASS} {{ + overflow-y: auto !important; + overflow-x: hidden !important; + max-width: min(440px, 90vw); +}} button.jupyter-button.{MENU_ITEM_CLASS}{_NEUTRAL} {{ background: transparent !important; border: none !important; @@ -136,6 +153,25 @@ opacity: 0.6 !important; cursor: not-allowed !important; }} +/* Why an item is unavailable: a muted line under it, readable without + hovering (UX-22). Not faded with the disabled item: it is real text, so + it keeps 4.5:1 (theme token MENU_REASON_TOKEN). */ +.{MENU_REASON_CLASS} {{ + margin: -3px 0 3px !important; + padding: 0 16px 0 36px !important; + height: auto !important; + min-height: 0 !important; +}} +.{MENU_REASON_CLASS} > .widget-html-content {{ + height: auto !important; + line-height: 1.3 !important; + white-space: normal !important; + background: transparent !important; +}} +.{MENU_REASON_CLASS} .{MENU_REASON_TEXT_CLASS} {{ + font-size: 11.5px; + color: var(--q-{MENU_REASON_TOKEN.replace("_", "-")}) !important; +}} .{MENU_HEAD_CLASS} {{ padding: 6px 12px 2px; border-top: 1px solid var(--q-border); @@ -242,8 +278,9 @@ def menubar_js() -> str: class MenuItem: """One action in a drop-down. - ``reason`` returns why the item is unavailable right now (shown as its - tooltip), or None when it can be used. ``checked`` makes it a check item + ``reason`` returns why the item is unavailable right now (shown as a + muted line under the item and in its tooltip), or None when it can be + used. ``checked`` makes it a check item (or a radio item with ``radio=True``); ``visible`` hides it entirely when it does not apply to this app (e.g. Cluster jobs without SLURM). """ @@ -872,6 +909,7 @@ def build_menubar(app: Any, *, layout_fn: Any, enabled: bool = True) -> None: app._mb_lists = {} app._mb_items = {} app._mb_entries = {} + app._mb_reasons = {} viewer_mode = bool(getattr(app, "_viewer_mode", False)) # Scroll targets for the jump actions (classes only; nothing moves). @@ -941,6 +979,10 @@ def _build_menu( btn.on_click(lambda _b, it=entry: choose_item(app, it)) app._mb_items[entry.key] = (entry, btn) children.append(btn) + reason = widgets.HTML(value="", layout=layout_fn(display="none")) + reason.add_class(MENU_REASON_CLASS) + app._mb_reasons[entry.key] = reason + children.append(reason) if title == "Help": children.append(widgets.HTML(value=about_html())) menu_list = widgets.VBox(children, layout=layout_fn(display="none")) @@ -959,8 +1001,22 @@ def _build_menu( # --------------------------------------------------------------------------- +def reason_id(key: str) -> str: + """DOM id of an item's reason text (the item's ``aria-describedby``).""" + return "quantui-mr-" + re.sub(r"[^A-Za-z0-9_-]", "-", key) + + +def reason_html(key: str, why: str) -> str: + """The muted "why unavailable" line under a disabled item (UX-22).""" + return ( + f'' + f"{_html.escape(why)}" + ) + + def refresh_menu(app: Any, title: str) -> None: - """Re-read every item's state (enabled, tooltip, check mark, shown).""" + """Re-read every item's state (enabled, reason, tooltip, check mark, shown).""" + reasons = getattr(app, "_mb_reasons", {}) for item in app._mb_entries.get(title, []): _entry, btn = app._mb_items[item.key] shown = item.visible(app) if item.visible is not None else True @@ -970,6 +1026,12 @@ def refresh_menu(app: Any, title: str) -> None: btn.tooltip = f"Unavailable: {why}" if why else item.tip checked = item.checked(app) if item.checked is not None else None btn.icon = item_icon(item, checked) + line = reasons.get(item.key) + if line is not None: + # The page script (app_a11y) points the item's aria-describedby + # at this text, so screen readers read the reason with the item. + line.value = reason_html(item.key, why) if why else "" + line.layout.display = "" if (why and shown) else "none" def refresh_open_menu(app: Any) -> None: @@ -1054,6 +1116,8 @@ def on_menu_bar_setting_changed(app: Any, change: Dict[str, Any]) -> None: __all__ = [ "MENUBAR_CLASS", "MENUBAR_CSS", + "MENU_REASON_CLASS", + "MENU_REASON_TOKEN", "MenuItem", "about_html", "apply_menu_bar_visible", @@ -1070,6 +1134,8 @@ def on_menu_bar_setting_changed(app: Any, change: Dict[str, Any]) -> None: "open_menu", "open_molecule_input", "push_js", + "reason_html", + "reason_id", "refresh_menu", "run_from_menu", "run_reason", diff --git a/quantui/app_pane_views.py b/quantui/app_pane_views.py index 3fc79f7..b8addb9 100644 --- a/quantui/app_pane_views.py +++ b/quantui/app_pane_views.py @@ -1,17 +1,30 @@ """Analysis panels drive the workspace pane's viewer (one viewer, DEC-035). With the two-pane workspace on (``app_workspace``), the Populations, -Vibrational and Isosurface panels no longer draw a 3D viewer of their own -next to the pane's copy of the same molecule (UI/UX review 2026-12-05, -UX-7). Their viewer is *moved* into the pane while it is in use, the way the -workspace moves the Analysis viewer and the setup dialog moves Calculation -Setup: one widget, one state, no copy. +Vibrational, Isosurface, Trajectory and Geometries panels no longer draw a +3D viewer of their own next to the pane's copy of the same molecule (UI/UX +review 2026-12-05, UX-7; DEC-036 "pane viewer, controls in panel"). Their +viewer is *moved* into the pane while it is in use, the way the workspace +moves the Analysis viewer and the setup dialog moves Calculation Setup: one +widget, one state, no copy. - **Claiming the pane.** Opening one of these panels (its header, the Results menu, or the panel's "Show in viewer" button), choosing another - vibrational mode, or generating a surface puts that panel's viewer in the - pane in place of the structure viewer. A banner at the top of the pane - names what it shows and has a **Back to structure** button. + vibrational mode, generating a surface, switching the Geometries view, or + clicking a point on a PES plot puts that panel's viewer in the pane in + place of the structure viewer. A banner at the top of the pane names what + it shows and has a **Back to structure** button. +- **Steppers: viewer in the pane, controls in the panel.** The Trajectory and + Geometries viewers are one py3Dmol viewer each, stepped client-side. With + the workspace on they are built in two halves (``ViewerParts``): the viewer + goes to the pane, the prev/play/next buttons, slider and frame label stay + in the panel (shown while their viewer is in the pane) and drive it + through page globals keyed by the viewer id, so playing needs no kernel + round trip. The energy plots stay in their panels. +- **PES Scan** has no viewer of its own: a click on the profile (1-D) or the + map (2-D) shows that scan point's geometry with the Trajectory panel's + viewer (``LINKED_VIEWS``). The click reaches the kernel through a hidden + inbox so the pane can be claimed (and the viewer built) on the first click. - **In the panel** the viewer's place holds a one-line note (DEC-009: the panel stays visible; only its content changes): what is shown in the pane, or a "Show in viewer" button when the pane shows something else. @@ -26,7 +39,8 @@ Moving a viewer re-creates it in the browser, which drops client-side state (the mode the single vibration viewer switched to, live isosurface appearance tweaks, the charge overlay). Each claim therefore refreshes the -moved viewer from the panel's controls (:func:`_refresh`). +moved viewer from the panel's controls (:func:`_refresh`). A stepper's +viewer half re-applies the frame its panel's stepper is on by itself. With the workspace off nothing here applies: every panel keeps its own viewer, as before (the fallback). @@ -64,9 +78,42 @@ "Surface", "Generated surfaces show in the viewer pane.", ), + "Trajectory": ( + "_traj_viewer_output", + "Trajectory", + "The steps play in the viewer pane; the controls appear here.", + ), + "Geometries": ( + "_reorg_geom_output", + "Relaxation geometries", + "The geometries show in the viewer pane; the controls appear here.", + ), +} + +# Stepper panels: the Output holding the controls half (stays in the panel). +STEPPER_CONTROLS: Dict[str, str] = { + "Trajectory": "_traj_controls_output", + "Geometries": "_reorg_controls_output", +} + +# A panel that shows another panel's viewer: name → (viewer owner, the panel +# widget its note replaces, banner label, note in the panel). +LINKED_VIEWS: Dict[str, Tuple[str, str, str, str]] = { + "PES Scan": ( + "Trajectory", + "_pes_plot_hint", + "Scan geometry", + "Click a point on the plot to show its geometry in the viewer pane.", + ), } ISOSURFACE = "Isosurface" +TRAJECTORY = "Trajectory" +GEOMETRIES = "Geometries" +PES_SCAN = "PES Scan" + +# Hidden Textarea a PES-plot click writes the point index into. +PES_PICK_INBOX_CLASS = "quantui-pv-pes-inbox" # --------------------------------------------------------------------------- @@ -86,7 +133,21 @@ def side_by_side(app: Any) -> bool: def _ws_on(app: Any) -> bool: - return bool(getattr(app, "_ws_enabled", False)) + return getattr(app, "_ws_enabled", False) is True + + +def _active(app: Any) -> bool: + """Pane views are built (a real app, not a bare stub).""" + return isinstance(getattr(app, "_pv_notes", None), dict) + + +def _views() -> Tuple[str, ...]: + return tuple(PANE_VIEWS) + tuple(LINKED_VIEWS) + + +def _owner(name: str) -> str: + """The panel whose viewer *name* shows.""" + return LINKED_VIEWS[name][0] if name in LINKED_VIEWS else name def _accordion(app: Any, name: str) -> Any: @@ -96,12 +157,20 @@ def _accordion(app: Any, name: str) -> Any: def _viewer(app: Any, name: str) -> Any: - attr = PANE_VIEWS[name][0] + attr = PANE_VIEWS[_owner(name)][0] return getattr(app, attr, None) +def _slot_widget(app: Any, name: str) -> Any: + """The panel widget *name*'s note replaces (its viewer, or a hint).""" + if name in LINKED_VIEWS: + return getattr(app, LINKED_VIEWS[name][1], None) + return _viewer(app, name) + + def _pane_hosts(app: Any, name: str) -> bool: """Whether *name*'s viewer belongs in the pane rather than its panel.""" + name = _owner(name) return _ws_on(app) and not (name == ISOSURFACE and side_by_side(app)) @@ -144,7 +213,15 @@ def build_pane_views(app: Any, *, layout_fn: Any) -> None: app._pv_notes = {} app._pv_note_btns = {} - for name in PANE_VIEWS: + app._pv_html = {} + app._pv_pes_linked = False + app._pv_pes_inbox = widgets.Textarea( + value="", + layout=layout_fn(width="1px", height="1px", visibility="hidden"), + ) + app._pv_pes_inbox.add_class(PES_PICK_INBOX_CLASS) + app._pv_pes_inbox.observe(safe(lambda ch: _on_pes_inbox(app, ch)), names="value") + for name in _views(): text = widgets.HTML(value="") btn = widgets.Button( description="Show in viewer", @@ -153,8 +230,9 @@ def build_pane_views(app: Any, *, layout_fn: Any) -> None: layout=layout_fn(width="150px", height="28px"), ) btn.on_click(lambda _b, n=name: claim(app, n)) + extra = [app._pv_pes_inbox] if name == PES_SCAN else [] note = widgets.VBox( - [text, btn], + [text, btn, *extra], layout=layout_fn( gap="6px", padding="10px 12px", @@ -191,6 +269,15 @@ def build_pane_views(app: Any, *, layout_fn: Any) -> None: # Choosing a mode means "show me this mode": into the pane. dd.observe(safe(lambda _ch: _on_vib_mode(app)), names="value") + # Switching the Geometries view (step / overlay, pair, arrow scale) is + # likewise "show me this". + for attr in ("_reorg_view_toggle", "_reorg_overlay_pair", "_reorg_exaggerate"): + w = getattr(app, attr, None) + if isinstance(w, widgets.Widget): + w.observe( + safe(lambda _ch: _on_panel_control(app, GEOMETRIES)), names="value" + ) + # --------------------------------------------------------------------------- # Moving viewers @@ -205,32 +292,41 @@ def _find_parent(root: Any, child: Any) -> Optional[Tuple[Any, int]]: def _park(app: Any, name: str) -> None: """Take *name*'s viewer out of its panel; its note takes the place.""" + note = app._pv_notes[name][0] if name in app._pv_slots: - return - acc, out = _accordion(app, name), _viewer(app, name) + old_box, old_idx = app._pv_slots[name] + current = tuple(old_box.children) + if old_idx < len(current) and current[old_idx] is note: + return + # The panel rebuilt its content (e.g. the Trajectory panel per result). + app._pv_slots.pop(name) + acc, out = _accordion(app, name), _slot_widget(app, name) hit = _find_parent(acc, out) if hit is None: return box, idx = hit kids = list(box.children) - kids[idx] = app._pv_notes[name][0] + kids[idx] = note box.children = tuple(kids) app._pv_slots[name] = (box, idx) def _unpark(app: Any, name: str) -> None: """Put *name*'s viewer back in its panel (workspace off / side by side).""" - if holder(app) == name: + cur = holder(app) + if cur == name or (cur and name in PANE_VIEWS and _owner(cur) == name): _leave_pane(app) if name not in app._pv_slots: return - note, out = app._pv_notes[name][0], _viewer(app, name) + note, out = app._pv_notes[name][0], _slot_widget(app, name) box, idx = app._pv_slots.pop(name) kids = list(box.children) if not (idx < len(kids) and kids[idx] is note): hit = _find_parent(_accordion(app, name), note) if hit is None: - logger.warning("pane views: note for %s not found", name) + # The panel was emptied since (a new result): its next render + # places the viewer itself (panel_slot). + logger.debug("pane views: note for %s not found", name) return box, idx = hit kids = list(box.children) @@ -263,17 +359,31 @@ def _leave_pane(app: Any) -> None: def claim(app: Any, name: str, *, refresh: bool = True) -> bool: """Show *name*'s viewer in the pane. False when it stays where it is.""" - if name not in PANE_VIEWS or not _pane_hosts(app, name): + if name not in _views() or not _active(app) or not _pane_hosts(app, name): return False from quantui.app_pick_mode import pick_mode_active if pick_mode_active(app): return False # a Calculate tool is picking on the structure - if name not in getattr(app, "_ana_available", set()): + available: Any = getattr(app, "_ana_available", set()) + owner = _owner(name) + if name not in available or owner not in available: return False - if holder(app) == name: + cur = holder(app) + if cur == name: return True - _park(app, name) + if owner == TRAJECTORY: + _ensure_trajectory(app) + if cur and _owner(cur) == owner: + # The same viewer is already in the pane (a PES click, then the + # Trajectory panel): only the banner changes, nothing is re-created. + app._pv_holder = name + _sync(app) + _log("pane_view_claimed", name) + return True + _park(app, owner) + if name != owner: + _park(app, name) out = _viewer(app, name) if isinstance(out, widgets.Widget): out.layout.max_width = "100%" @@ -304,25 +414,29 @@ def show_structure(app: Any, *, rerender: bool = True) -> None: def apply_pane_views_layout(app: Any, enabled: bool) -> None: """Workspace on: panel viewers live in the pane; off: back home.""" - if not hasattr(app, "_pv_notes"): + if not _active(app): return if enabled: - for name in PANE_VIEWS: + for name in _views(): if _pane_hosts(app, name): _park(app, name) else: show_structure(app, rerender=False) - for name in PANE_VIEWS: + for name in _views(): _unpark(app, name) + for name in STEPPER_CONTROLS: + _fill(app, name) # one fragment in the panel, or split for the pane _sync(app) def reset_for_new_result(app: Any) -> None: """A new result (live or History): the pane shows its structure.""" - if not hasattr(app, "_pv_notes"): + if not _active(app): return app._pv_iso_has_surface = False + app._pv_pes_linked = False show_structure(app, rerender=False) + _sync(app) # --------------------------------------------------------------------------- @@ -336,16 +450,51 @@ def _on_accordion(app: Any, name: str, change: Dict[str, Any]) -> None: if change.get("new") == 0: if name == ISOSURFACE and not getattr(app, "_pv_iso_has_surface", False): return # nothing but the molecule until Generate + if name == PES_SCAN: + return # the plot; a click on a point shows its geometry claim(app, name) elif holder(app) == name: show_structure(app) def _on_vib_mode(app: Any) -> None: - if getattr(app, "_pv_suppress", False): + _on_panel_control(app, "Vibrational") + + +def _on_panel_control(app: Any, name: str) -> None: + """A panel control changed what the panel shows: into the pane.""" + if getattr(app, "_pv_suppress", False) or not _ws_on(app): + return + if holder(app) == name: + _sync(app) # the banner names the new mode / view + else: + claim(app, name) + + +def _on_pes_inbox(app: Any, change: Dict[str, Any]) -> None: + """A PES-plot click posted ``" "``.""" + raw = str(change.get("new") or "").split() + if not raw: + return + try: + index = int(raw[0]) + except ValueError: return - if holder(app) != "Vibrational": - claim(app, "Vibrational") + show_pes_point(app, index) + + +def show_pes_point(app: Any, index: int) -> bool: + """Scan point *index*'s geometry in the pane (a PES-plot click). + + The browser has already moved a built stepper to the point; when the + trajectory viewer is not built yet it opens on that point. + """ + if not _active(app) or not _ws_on(app): + return False + out = _viewer(app, PES_SCAN) + if not getattr(out, "outputs", None): + app._traj_start_index = max(0, int(index)) + return claim(app, PES_SCAN) def claim_for_surface(app: Any, label: str = "") -> None: @@ -353,7 +502,7 @@ def claim_for_surface(app: Any, label: str = "") -> None: Claimed before the surface lands, so nothing needs re-applying. """ - if not hasattr(app, "_pv_notes"): + if not _active(app): return app._pv_iso_has_surface = True app._pv_iso_label = str(label or "") @@ -452,13 +601,139 @@ def _push_iso_appearance(app: Any) -> None: logger.debug("iso appearance push failed: %s", exc) +# --------------------------------------------------------------------------- +# Stepper viewers: one fragment, or split between pane and panel +# --------------------------------------------------------------------------- + + +def _ensure_trajectory(app: Any) -> None: + """Build the Trajectory viewer if it was never drawn (it renders lazily + when its panel opens; a PES click can come first).""" + out = _viewer(app, TRAJECTORY) + if out is None or bool(getattr(out, "outputs", None)): + return + if getattr(app, "_pending_traj_result", None) is None and ( + getattr(app, "_last_traj_result", None) is None + ): + return + try: + app._on_traj_expand({"new": 0}) + except Exception as exc: # noqa: BLE001 — a click must never raise + logger.debug("trajectory build for the pane failed: %s", exc) + + +def set_viewer_html(app: Any, name: str, parts: Any) -> None: + """Show a stepper panel's viewer (``ViewerParts`` or plain HTML). + + The single-column layout gets the combined fragment in the panel; with + the workspace on, the viewer half goes in the (moving) viewer Output and + the controls half in the panel's controls Output. + """ + if isinstance(parts, str): + parts = (parts, parts, "") + if not isinstance(getattr(app, "_pv_html", None), dict): + app._pv_html = {} + app._pv_html[name] = tuple(parts) + _fill(app, name) + + +def clear_viewer(app: Any, name: str) -> None: + """Forget a stepper panel's viewer (a new result).""" + if isinstance(getattr(app, "_pv_html", None), dict): + app._pv_html.pop(name, None) + for out in (_viewer(app, name), getattr(app, STEPPER_CONTROLS[name], None)): + if isinstance(out, widgets.Output): + out.outputs = () + + +def _fill(app: Any, name: str) -> None: + parts = (getattr(app, "_pv_html", None) or {}).get(name) + out = _viewer(app, name) + ctl = getattr(app, STEPPER_CONTROLS[name], None) + if parts is None or out is None: + return + combined, viewer, controls = parts + split = _active(app) and _pane_hosts(app, name) + _set_html(app, out, viewer if split else combined) + if isinstance(ctl, widgets.Output): + if split and controls: + _set_html(app, ctl, controls) + else: + ctl.outputs = () + + +def _set_html(app: Any, out: Any, html: str) -> None: + setter = getattr(app, "_set_html_output", None) + if callable(setter): + setter(out, html) + else: + out.outputs = ( + { + "output_type": "display_data", + "data": {"text/html": html}, + "metadata": {}, + }, + ) + + +def panel_slot(app: Any, name: str) -> Any: + """What a panel's own re-render puts where its viewer goes. + + The viewer itself, or its note while the viewer belongs in the pane: a + widget in both places would draw two viewers. + """ + if _active(app) and _pane_hosts(app, name): + return app._pv_notes[name][0] + return _viewer(app, name) + + +def panel_rendered(app: Any, name: str) -> None: + """A panel rebuilt its content around :func:`panel_slot`: note where the + note now sits, so the workspace toggle can swap it back.""" + if not _active(app): + return + app._pv_slots.pop(name, None) + if _pane_hosts(app, name): + hit = _find_parent(_accordion(app, name), app._pv_notes[name][0]) + if hit is not None: + app._pv_slots[name] = hit + _sync(app) + + +def set_pes_linked(app: Any, linked: bool) -> None: + """The PES plot shown can (or cannot) show its points' geometries.""" + if not _active(app): + return + app._pv_pes_linked = bool(linked) + _sync(app) + + +def pes_pick_js(index_var: str = "i") -> str: + """JS for a PES-plot click handler: tell the kernel which point. + + A nonce makes a second click on the same point a change too. Without the + inbox on the page (workspace off) it does nothing. + """ + return ( + f'var _qb=document.querySelector(".{PES_PICK_INBOX_CLASS} textarea");' + f'if(_qb){{_qb.value=String({index_var})+" "+Date.now();' + '_qb.dispatchEvent(new Event("input",{bubbles:true}));}' + ) + + # --------------------------------------------------------------------------- # Banner and notes # --------------------------------------------------------------------------- def _banner_label(app: Any, name: str) -> str: + if name in LINKED_VIEWS: + return LINKED_VIEWS[name][2] label = PANE_VIEWS[name][1] + if name == GEOMETRIES: + toggle = getattr(app, "_reorg_view_toggle", None) + if getattr(toggle, "value", "step") == "overlay": + return "Relaxation overlay" iso_label = getattr(app, "_pv_iso_label", None) if name == ISOSURFACE and iso_label: return f"{label}: {iso_label}" @@ -483,15 +758,36 @@ def _sync(app: Any) -> None: f"{_html.escape(name)} panel" ) has_surface = bool(getattr(app, "_pv_iso_has_surface", False)) - for panel, (_note, text, btn) in app._pv_notes.items(): + pes_linked = bool(getattr(app, "_pv_pes_linked", False)) + for panel, (note, text, btn) in app._pv_notes.items(): here = panel == name - no_surface = panel == ISOSURFACE and not has_surface - msg = "Shown in the viewer pane now." if here else PANE_VIEWS[panel][2] + nothing = (panel == ISOSURFACE and not has_surface) or ( + panel == PES_SCAN and not pes_linked + ) + if here: + msg = "Shown in the viewer pane now." + if panel in STEPPER_CONTROLS: + msg += " Step or play it with the controls below." + elif panel in LINKED_VIEWS: + msg += " Click another point to show its geometry." + elif panel in LINKED_VIEWS: + msg = LINKED_VIEWS[panel][3] + else: + msg = PANE_VIEWS[panel][2] text.value = ( f'' f"{_html.escape(msg)}" ) - btn.layout.display = "none" if (here or no_surface) else "" + btn.layout.display = "none" if (here or nothing) else "" + if panel == PES_SCAN: + # Nothing to click through to (an interpolated TS-guess profile). + note.layout.display = "" if pes_linked else "none" + # A stepper's controls show while they drive something on screen. + for panel, attr in STEPPER_CONTROLS.items(): + ctl = getattr(app, attr, None) + if isinstance(ctl, widgets.Widget): + shown = not _ws_on(app) or (bool(name) and _owner(name) == panel) + ctl.layout.display = "" if shown else "none" def _log(event: str, detail: str = "") -> None: @@ -504,15 +800,28 @@ def _log(event: str, detail: str = "") -> None: __all__ = [ + "GEOMETRIES", "ISOSURFACE", + "LINKED_VIEWS", "PANE_VIEWS", + "PES_PICK_INBOX_CLASS", + "PES_SCAN", + "STEPPER_CONTROLS", + "TRAJECTORY", "apply_pane_views_layout", "build_pane_views", "claim", "claim_for_surface", + "clear_viewer", "holder", "on_side_by_side", + "panel_rendered", + "panel_slot", + "pes_pick_js", "reset_for_new_result", + "set_pes_linked", + "set_viewer_html", + "show_pes_point", "show_structure", "side_by_side", ] diff --git a/quantui/app_pes2d.py b/quantui/app_pes2d.py index fef2b89..78e071f 100644 --- a/quantui/app_pes2d.py +++ b/quantui/app_pes2d.py @@ -367,6 +367,9 @@ def show_pes_scan_2d_result(app: Any, result: Any) -> bool: if link: plot_html += click_link_js(div_id, len(result.values2)) app._set_html_output(app._pes_plot_html, plot_html) + from .app_pane_views import set_pes_linked + + set_pes_linked(app, link) except Exception as exc: # noqa: BLE001 — shown in the panel app._last_pes_fig = None _show_plot_error(app, getattr(app, "_pes_plot_html", None), "2-D PES map", exc) diff --git a/quantui/app_runflow.py b/quantui/app_runflow.py index 5de0434..58eb91c 100644 --- a/quantui/app_runflow.py +++ b/quantui/app_runflow.py @@ -298,8 +298,101 @@ def _set_run_output(app: Any, outputs: tuple) -> None: pass +# --------------------------------------------------------------------------- +# Instant Run feedback (UI/UX review 2026-12-05, UX-34) +# --------------------------------------------------------------------------- + +RUN_STARTING_LABEL = "Starting…" +RUN_RUNNING_LABEL = "Running…" +RUN_BUSY_ICON = "spinner spin" # fa-spinner fa-spin +RUN_BUSY_CLASS = "quantui-run-busy" + + +def _set_run_button_busy(app: Any, label: str) -> None: + """Run button: disabled, spinner, *label*; remembers its idle look.""" + btn = getattr(app, "run_btn", None) + if btn is None: + return + if getattr(app, "_run_btn_idle", None) is None: + app._run_btn_idle = (btn.description, btn.icon) + btn.disabled = True + btn.description = label + btn.icon = RUN_BUSY_ICON + btn.add_class(RUN_BUSY_CLASS) + + +def clear_run_busy(app: Any) -> None: + """Give the Run button back its idle label and icon.""" + btn = getattr(app, "run_btn", None) + idle = getattr(app, "_run_btn_idle", None) + was_starting = bool(getattr(app, "_run_starting", False)) + app._run_starting = False + app._run_btn_idle = None + if btn is not None: + if idle is not None: + btn.description, btn.icon = idle + btn.remove_class(RUN_BUSY_CLASS) + if was_starting: + _refresh_job_status(app) + + +def _refresh_job_status(app: Any) -> None: + from quantui.app_workspace import refresh_status + + try: + refresh_status(app) + except (AttributeError, TypeError, ValueError) as exc: + logger.debug("job status refresh failed: %s", exc) + + +def mark_run_starting(app: Any) -> None: + """The moment Run is clicked: busy button, "Starting…" everywhere. + + Before any validation, clearing or PySCF output, so the click is + acknowledged at once: the button turns into a disabled spinner, the run + status, the header chip and the footer say "Starting…", and the live + region announces it. :func:`mark_run_running` (worker) or + :func:`cancel_run_starting` (the run did not start) take over. + """ + btn = getattr(app, "run_btn", None) + app._run_btn_prior_disabled = bool(getattr(btn, "disabled", False)) + app._run_starting = True + _set_run_button_busy(app, RUN_STARTING_LABEL) + try: + app.run_status.value = RUN_STARTING_LABEL + except AttributeError: + pass + _refresh_job_status(app) + + +def mark_run_running(app: Any) -> None: + """The run is under way: the normal running states take over.""" + was_starting = bool(getattr(app, "_run_starting", False)) + app._run_starting = False + _set_run_button_busy(app, RUN_RUNNING_LABEL) + if was_starting: + _refresh_job_status(app) + + +def cancel_run_starting(app: Any) -> None: + """The run did not start (a validation message, say): Run comes back.""" + if not getattr(app, "_run_starting", False): + return + prior = bool(getattr(app, "_run_btn_prior_disabled", False)) + clear_run_busy(app) + btn = getattr(app, "run_btn", None) + if btn is not None and not getattr(app, "_calc_running", False): + btn.disabled = prior + + +def on_run_button_disabled_changed(app: Any, change: Dict[str, Any]) -> None: + """Run re-enabled (the run ended, however it ended): drop the busy look.""" + if not (change or {}).get("new"): + clear_run_busy(app) + + def on_run_clicked(app: Any, btn: Any) -> None: - """Reset result panes and start the background run thread.""" + """Acknowledge the click at once, then validate and start the run.""" # One run at a time. The button is disabled while a run is in flight, # but a double-click (or a click queued before the disable reached the # browser) still lands here; two runs would share the cancel flag, the @@ -318,6 +411,17 @@ def on_run_clicked(app: Any, btn: Any) -> None: except Exception: # noqa: BLE001 — status label is best-effort pass return + mark_run_starting(app) + started = False + try: + started = _start_run(app) + finally: + if not started: + cancel_run_starting(app) + + +def _start_run(app: Any) -> bool: + """Validate, reset the result panes and start the run; True if started.""" # Pre-run guard: catch a basis with no parameters for an # element (e.g. 6-31G on Pt) or a charge/multiplicity inconsistent with the # electron count, and explain it here — on the main thread, before anything @@ -359,7 +463,7 @@ def on_run_clicked(app: Any, btn: Any) -> None: # offer a one-click switch rather than making the student hunt the # dropdown. Only reveal it when def2-SVP actually resolves coverage. _update_basis_fix_button(app, mol) - return + return False _hide_basis_fix_button(app) if mol is not None and app.calc_type_dd.value == "PES Scan": @@ -385,7 +489,7 @@ def on_run_clicked(app: Any, btn: Any) -> None: ) except Exception: # noqa: BLE001 — status label is best-effort pass - return + return False if mol is not None and app.calc_type_dd.value == "NMR Shielding": # Open-shell references and meta-GGA functionals cannot run the GIAO @@ -418,7 +522,7 @@ def on_run_clicked(app: Any, btn: Any) -> None: ) except Exception: # noqa: BLE001 — status label is best-effort pass - return + return False # Write the header FIRST (atomic, main thread) — this also clears the # previous run's log via the single ``outputs`` assignment. @@ -447,7 +551,10 @@ def on_run_clicked(app: Any, btn: Any) -> None: if use_slurm_execution(app): submit_slurm_run(app) - return + if not getattr(app, "_calc_running", False): + return False # refused before submitting; the reason is shown + mark_run_running(app) + return True # Claim the run on this (main) thread, before the worker starts: the # worker used to set the flag itself, leaving a window for a second run. @@ -457,6 +564,7 @@ def on_run_clicked(app: Any, btn: Any) -> None: # The card was just cleared: "A calculation is running…" until it lands. refresh_results_empty_state(app, has_card=False) threading.Thread(target=app._run_in_thread, daemon=True).start() + return True _FREQ_PREOPT_DESC_DEFAULT = "Geometry optimization before calculation (QM, slower)" @@ -584,7 +692,7 @@ def on_spin_apply(app: Any, index: int) -> None: app.spin_helper_output.value = _spin_small( f"Multiplicity set to {mult}. Remember to set the charge from your " "complex — it isn't inferred.", - "#166534", + _theme.css.ACCENT_SUCCESS, ) @@ -667,7 +775,7 @@ def on_charge_mult_apply(app: Any, btn: Any = None) -> None: app.charge_mult_suggest_output.value = _spin_small( f"Applied charge {suggestion.charge} and multiplicity " f"{suggestion.multiplicity}. Re-check before running.", - "#166534", + _theme.css.ACCENT_SUCCESS, ) app.charge_mult_apply_btn.layout.display = "none" app._charge_mult_suggestion = None @@ -2844,7 +2952,7 @@ def _cal_status_text(status: str) -> str: return { "ok": "✓", "timed_out": "⏱ timed out", - "stopped": "⛔ stopped", + "stopped": "■ stopped", "skipped": "⏭ skipped", "error": "✗ error", "running": "▶ running", @@ -2917,7 +3025,7 @@ def _err_detail(s) -> str: summary = f"Completed {n_done} / {total} steps." return ( '
' - f'

{summary}

' + f'

{summary}

' '' "" '' @@ -2995,7 +3103,7 @@ def _progress( icon = { "ok": "✓", "timed_out": "⏱", - "stopped": "⛔", + "stopped": "■", "error": "✗", "running": "▶", }.get(status, "?") @@ -3052,14 +3160,14 @@ def _progress( '
.' if result.n_completed > 0 else ( - 'No steps completed.' + f'No steps completed.' '
.' ) ) except Exception as exc: # noqa: BLE001 — shown in the panel logger.exception("Calibration failed") app._cal_step_label.value = ( - 'Calibration failed: ' + f'Calibration failed: ' f"{html.escape(f'{type(exc).__name__}: {exc}')}" '
.' ) diff --git a/quantui/app_slurm.py b/quantui/app_slurm.py index 328218f..fa762bb 100644 --- a/quantui/app_slurm.py +++ b/quantui/app_slurm.py @@ -1058,9 +1058,9 @@ def _show_slurm_banner(app: Any, message: str, *, request_id: str) -> None: if banner is None: return banner.value = ( - f'
' - f"ℹ️ {message}
" + f'
' + f' {message}
' ) banner.layout.display = "" btn = getattr(app, "_slurm_reconnect_btn", None) diff --git a/quantui/app_visualization.py b/quantui/app_visualization.py index b58e765..a722366 100644 --- a/quantui/app_visualization.py +++ b/quantui/app_visualization.py @@ -9,7 +9,7 @@ from contextlib import contextmanager from html import escape as _escape # for scopes where `html` is a local str from pathlib import Path -from typing import Any, List, Optional, cast +from typing import Any, List, NamedTuple, Optional, cast import ipywidgets as widgets @@ -309,6 +309,16 @@ def on_traj_expand(app: Any, change: dict[str, Any]) -> None: ) +def _new_traj_viewer_output(layout_fn: Any) -> Any: + """A trajectory viewer host (min_height: a fixed height clips the frame).""" + viewer_output = widgets.Output( + layout=layout_fn( + min_height="420px", width="100%", max_width="500px", overflow="hidden" + ) + ) + return viewer_output + + def show_opt_trajectory( app: Any, opt_result: Any, @@ -366,7 +376,7 @@ def _is_stale() -> bool: y=rel_e, mode="lines+markers", name="ΔE", - line=dict(color="#2563eb", width=2), + line=dict(color=_theme.PLOT_DATA_COLORS["blue"], width=2), marker=dict(size=6), ) ) @@ -399,11 +409,17 @@ def _is_stale() -> bool: # --- Single-viewer trajectory stepper (all frames preloaded) --- # min_height, not height: build_trajectory_viewer_html returns a framed # fragment, and a fixed height would clip its bottom border off. - viewer_output = widgets.Output( - layout=layout_fn( - min_height="420px", width="100%", max_width="500px", overflow="hidden" - ) - ) + # One app-lifetime Output (app_builders), so the workspace can move it + # into the viewer pane (app_pane_views); a bare stub gets a fresh one. + from quantui import app_pane_views as _pv + + viewer_output = getattr(app, "_traj_viewer_output", None) + if not isinstance(viewer_output, widgets.Output): + viewer_output = _new_traj_viewer_output(layout_fn) + controls_output = getattr(app, "_traj_controls_output", None) + # A PES-plot click that came before the viewer existed: open on its point. + start_index = getattr(app, "_traj_start_index", None) + app._traj_start_index = None # Hidden inbox for the viewer's Save-PNG button — same # write-into-DOM-node-then-sync-to-kernel bridge as the isosurface/reorg # viewers. Rebuilt every render like the export button/status below it, @@ -424,28 +440,34 @@ def _on_traj_png_captured(change: dict) -> None: try: with _viz_render_event(app, task="trajectory", backend="py3dmol", n_frames=n): - html = build_trajectory_viewer_html( + parts = build_trajectory_viewer_parts( xyzblocks, formula=formula, energies=list(energies) if energies else None, rel_e=rel_e or None, bgcolor=bgcolor, capture_class=_TRAJ_PNG_INBOX_CLASS, + start_index=start_index if isinstance(start_index, int) else None, ) - app._set_html_output(viewer_output, html) + if viewer_output is getattr(app, "_traj_viewer_output", None): + _pv.set_viewer_html(app, "Trajectory", parts) + else: + app._set_html_output(viewer_output, parts.combined) except Exception as exc: # noqa: BLE001 — surface inline, never crash the tab - viewer_output.outputs = ( - { - "output_type": "display_data", - "data": { - "text/html": ( - '

' - f"Trajectory viewer failed: {_escape(str(exc))}

" - ) - }, - "metadata": {}, - }, + err = ( + '

' + f"Trajectory viewer failed: {_escape(str(exc))}

" ) + if viewer_output is getattr(app, "_traj_viewer_output", None): + _pv.set_viewer_html(app, "Trajectory", err) + else: + viewer_output.outputs = ( + { + "output_type": "display_data", + "data": {"text/html": err}, + "metadata": {}, + }, + ) # --- Export button (standalone HTML animation; plotlymol3d) --- export_btn = widgets.Button( @@ -537,7 +559,14 @@ def _do_export() -> None: }, ) new_children.append(energy_holder) - new_children.append(viewer_output) + if viewer_output is getattr(app, "_traj_viewer_output", None): + # The viewer, or its note while the viewer lives in the pane; the + # stepper controls stay here either way (empty in one-fragment mode). + new_children.append(_pv.panel_slot(app, "Trajectory")) + if isinstance(controls_output, widgets.Output): + new_children.append(controls_output) + else: + new_children.append(viewer_output) new_children.append( widgets.HBox( [export_btn, export_status, png_status], @@ -546,6 +575,7 @@ def _do_export() -> None: ) new_children.append(png_inbox) app.traj_output.children = tuple(new_children) + _pv.panel_rendered(app, "Trajectory") try: from quantui import calc_log as _clog_sp @@ -1091,7 +1121,7 @@ def _render_uv_energy_axis( x=e_grid.tolist(), y=list(map(float, y)), mode="lines", - line=dict(color="#2563eb", width=2), + line=dict(color=_theme.PLOT_DATA_COLORS["blue"], width=2), name="Broadened (eV)", ) ) @@ -1106,7 +1136,7 @@ def _render_uv_energy_axis( x=stick_x, y=stick_y, mode="lines", - line=dict(color="#2563eb", width=2), + line=dict(color=_theme.PLOT_DATA_COLORS["blue"], width=2), name="Stick", ) ) @@ -1115,7 +1145,7 @@ def _render_uv_energy_axis( x=energies, y=osc, mode="markers", - marker=dict(color="#1d4ed8", size=6), + marker=dict(color=_theme.PLOT_DATA_COLORS["blue"], size=6), showlegend=False, hovertemplate=( "Energy: %{x:.3f} eV
Oscillator strength: %{y:.3f}" @@ -1356,7 +1386,7 @@ def update_uv_vis_figure(app: Any, mode: str, fwhm: float) -> None: x=x_grid.tolist(), y=y_grid.tolist(), mode="lines", - line=dict(color="#2563eb", width=2), + line=dict(color=_theme.PLOT_DATA_COLORS["blue"], width=2), name="Broadened", ) ) @@ -1371,7 +1401,7 @@ def update_uv_vis_figure(app: Any, mode: str, fwhm: float) -> None: x=stick_x, y=stick_y, mode="lines", - line=dict(color="#2563eb", width=2), + line=dict(color=_theme.PLOT_DATA_COLORS["blue"], width=2), name="Stick", ) ) @@ -1380,7 +1410,7 @@ def update_uv_vis_figure(app: Any, mode: str, fwhm: float) -> None: x=wl, y=osc, mode="markers", - marker=dict(color="#1d4ed8", size=6), + marker=dict(color=_theme.PLOT_DATA_COLORS["blue"], size=6), showlegend=False, hovertemplate=( "Wavelength: %{x:.2f} nm" @@ -2501,10 +2531,10 @@ def _show_range_err() -> None: _orb_opts.pop("esp_range", None) html_str = render_orbital_isosurface_py3dmol(cube_path, **_orb_opts) else: - is_dark = _theme.get_palette(app.theme_btn.value).is_dark - axis_color = "#dbeafe" if is_dark else "#1f2937" - bond_color = "#cbd5e1" if is_dark else "#4b5563" - title_color = app._plotly_theme_colors()["font_color"] + _tc = app._plotly_theme_colors() + axis_color = _tc["font_color"] + bond_color = _tc["axis_line_color"] + title_color = _tc["font_color"] fig = plot_cube_isosurface( cube_path, # The second knob. Without this the Plotly fallback would @@ -3708,6 +3738,7 @@ def on_vib_mode_changed(app: Any, change: dict[str, Any]) -> None: var slider=g("st_slider_"), lbl=g("st_lbl_"), prevB=g("st_prev_"), nextB=g("st_next_"), playB=g("st_play_"), abB=g("st_ab_"); var cur=__START__, timer=null; + window["__quantuiStepCur_"+UID]=cur; function vw(){return window["viewer_"+UID];} function label(i){ __LABEL_BODY__ } function draw(i){ @@ -3742,12 +3773,66 @@ def on_vib_mode_changed(app: Any, change: dict[str, Any]) -> None: var t=0, poll=setInterval(function(){ t++; if(vw()){ clearInterval(poll); draw(cur); } else if(t>200){ clearInterval(poll); - if(lbl) lbl.innerHTML="3D viewer failed to load"; } + // With the workspace on, the viewer may be in the pane later (or not + // on the page at all while the pane shows the structure): only a + // viewer that is on the page and never loaded is a failure. + if(lbl && document.getElementById("3dmolviewer_"+UID)) + lbl.innerHTML="3D viewer failed to load"; } + },50); +})(); +""" + +# The viewer half of a stepper split between the pane and its panel +# (``app_pane_views``): the pane's viewer is re-created whenever it moves, so on +# (re)load it shows the frame the panel's stepper is on. +_STEPPER_VIEWER_SYNC_JS = """ +(function(){ + var UID="__UID__", START=__START__; + var t=0, poll=setInterval(function(){ t++; + var v=window["viewer_"+UID]; + if(v){ clearInterval(poll); + var c=window["__quantuiStepCur_"+UID]; if(c==null) c=START; + try{ var p=v.setFrame(c); + if(p&&p.then){ p.then(function(){v.render();}); } else { v.render(); } + }catch(e){} + } else if(t>200){ clearInterval(poll); } },50); })(); """ +class ViewerParts(NamedTuple): + """A stepper viewer as one fragment, or split for the workspace pane. + + ``combined`` is the classic framed viewer with its controls inside (the + single-column layout and exports). With the workspace on, ``viewer`` goes + to the pane and ``controls`` (prev/play/next, slider, frame label) stay + in the panel; the two halves talk through page globals keyed by the + viewer id, so stepping in the panel drives the pane with no kernel round + trip. + """ + + combined: str + viewer: str + controls: str + + +def _split_viewer_parts( + view_html: str, controls: str, *, width: int, uid: Optional[str], start: int +) -> ViewerParts: + combined = _theme.frame_viewer_html(view_html, width=width, controls=controls) + if not controls or uid is None: + return ViewerParts(combined, combined, "") + sync = _STEPPER_VIEWER_SYNC_JS.replace("__UID__", uid).replace( + "__START__", str(int(start)) + ) + viewer = _theme.frame_viewer_html( + view_html + f"", width=width + ) + panel = f'
{controls}
' + return ViewerParts(combined, viewer, panel) + + def _frame_stepper_controls( uid: str, n: int, @@ -3860,13 +3945,56 @@ def build_reorg_geometry_viewer_html( ``capture_class`` wires a "Save PNG" button, mirroring the isosurface viewer's capture bridge but with a uid-scoped capture function — see ``_GENERIC_CAPTURE_JS``. Empty omits the button. + + :func:`build_reorg_geometry_viewer_parts` is the same viewer split into a + pane half and a panel half (the workspace layout). """ - import re + if not geometries: + return '

No geometries available.

' + view_html, controls, _uid = _reorg_geometry_viewer_core( + geometries, + bgcolor=bgcolor, + width=width, + height=height, + capture_class=capture_class, + ) + return _theme.frame_viewer_html(view_html, width=width, controls=controls) - from quantui.viz_assets import make_view +def build_reorg_geometry_viewer_parts( + geometries: list[dict], + *, + bgcolor: str = "white", + width: int = 560, + height: int = 420, + capture_class: str = "", +) -> ViewerParts: + """:func:`build_reorg_geometry_viewer_html`, also split for the pane.""" if not geometries: - return '

No geometries available.

' + empty = build_reorg_geometry_viewer_html(geometries) + return ViewerParts(empty, empty, "") + view_html, controls, uid = _reorg_geometry_viewer_core( + geometries, + bgcolor=bgcolor, + width=width, + height=height, + capture_class=capture_class, + ) + return _split_viewer_parts(view_html, controls, width=width, uid=uid, start=0) + + +def _reorg_geometry_viewer_core( + geometries: list[dict], + *, + bgcolor: str, + width: int, + height: int, + capture_class: str, +) -> tuple[str, str, Optional[str]]: + """(viewer HTML, stepper controls or "", viewer id); *geometries* non-empty.""" + import re + + from quantui.viz_assets import make_view blocks = [] for g in geometries: @@ -3887,7 +4015,7 @@ def build_reorg_geometry_viewer_html( m = re.search(r"3dmolviewer_(\w+)", view_html) if m is None: - return _theme.frame_viewer_html(view_html, width=width) + return view_html, "", None uid = m.group(1) slugs = _script_json( @@ -3922,7 +4050,7 @@ def build_reorg_geometry_viewer_html( ) if len(geometries) < 2: - return _theme.frame_viewer_html(view_html, width=width) + return view_html, "", uid labels = _script_json( [g.get("label", f"Geometry {i + 1}") for i, g in enumerate(geometries)] @@ -3945,7 +4073,7 @@ def build_reorg_geometry_viewer_html( start_index=0, extra_decls=f"var LBL={labels}; var NOTE={notes};", ) - return _theme.frame_viewer_html(view_html, width=width, controls=controls) + return view_html, controls, uid def build_reorg_overlay_html( @@ -4168,7 +4296,71 @@ def build_trajectory_viewer_html( ``window["viewer_"+UID]``, which 3Dmol.js sets regardless of what is displayed in it — nothing trajectory-specific needed). Empty omits the button. + + :func:`build_trajectory_viewer_parts` is the same viewer split into a + pane half and a panel half (the workspace layout). + """ + view_html, controls, _uid, _start = _trajectory_viewer_core( + xyzblocks, + formula=formula, + energies=energies, + rel_e=rel_e, + bgcolor=bgcolor, + width=width, + height=height, + fps=fps, + capture_class=capture_class, + ) + return _theme.frame_viewer_html(view_html, width=width, controls=controls) + + +def build_trajectory_viewer_parts( + xyzblocks: list[str], + *, + formula: str = "", + energies: list[float] | None = None, + rel_e: list[float] | None = None, + bgcolor: str = "white", + width: int = 460, + height: int = 340, + fps: int = 8, + capture_class: str = "", + start_index: int | None = None, +) -> ViewerParts: + """:func:`build_trajectory_viewer_html`, also split for the pane. + + ``start_index`` opens the stepper on that frame (default: the last), e.g. + the scan point a PES-plot click asked for before the viewer existed. """ + view_html, controls, uid, start = _trajectory_viewer_core( + xyzblocks, + formula=formula, + energies=energies, + rel_e=rel_e, + bgcolor=bgcolor, + width=width, + height=height, + fps=fps, + capture_class=capture_class, + start_index=start_index, + ) + return _split_viewer_parts(view_html, controls, width=width, uid=uid, start=start) + + +def _trajectory_viewer_core( + xyzblocks: list[str], + *, + formula: str, + energies: list[float] | None, + rel_e: list[float] | None, + bgcolor: str, + width: int, + height: int, + fps: int, + capture_class: str, + start_index: int | None = None, +) -> tuple[str, str, Optional[str], int]: + """(viewer HTML, stepper controls or "", viewer id, first frame).""" import re from quantui.viz_assets import make_view @@ -4201,10 +4393,13 @@ def build_trajectory_viewer_html( + _png_capture_controls(uid, capture_class, capture_fn=capture_fn) ) + start = n - 1 + if start_index is not None: + start = max(0, min(n - 1, int(start_index))) if n <= 1 or uid is None: # n<=1: static structure, no stepper needed. uid is None: can't wire # controls without the viewer id either way. - return _theme.frame_viewer_html(view_html, width=width) + return view_html, "", uid, start interval_ms = max(1, int(round(1000.0 / max(1, fps)))) eabs = _script_json([float(e) for e in energies]) if energies else "null" @@ -4223,15 +4418,16 @@ def build_trajectory_viewer_html( n, interval_ms, label_js=label_js, - initial_label=f"Step {n - 1} / {n - 1}", + initial_label=f"Step {start} / {n - 1}", loop=True, # optimization animation: loop continuously ab_at_start="⇄ Final geometry", ab_other="⇄ First step (input)", scrub_title="Scrub the optimization steps", + start_index=start, extra_decls=f"var EABS={eabs}; var EREL={erel};", register_goto=True, # the PES plot's click target ) - return _theme.frame_viewer_html(view_html, width=width, controls=controls) + return view_html, controls, uid, start # Single-viewer vibrational animation. ONE py3Dmol viewer holds every mode; the @@ -4268,7 +4464,7 @@ def build_trajectory_viewer_html( arrowShapes.push(v.addArrow({ start:{x:b[0], y:b[1], z:b[2]}, end:{x:b[0]+s*d[a][0], y:b[1]+s*d[a][1], z:b[2]+s*d[a][2]}, - radius:0.06, radiusRatio:2.0, mid:0.72, color:"#16a34a"})); + radius:0.06, radiusRatio:2.0, mid:0.72, color:"#059669"})); } } function frames(m){ @@ -4924,8 +5120,8 @@ def show_pes_scan_result(app: Any, result: Any) -> bool: customdata=valid_idx, mode="lines+markers", name="Profile", - line=dict(color="#2563eb", width=2), - marker=dict(size=8, color="#2563eb"), + line=dict(color=_theme.PLOT_DATA_COLORS["blue"], width=2), + marker=dict(size=8, color=_theme.PLOT_DATA_COLORS["blue"]), hovertext=valid_hover, hoverinfo="text", ) @@ -4943,6 +5139,9 @@ def show_pes_scan_result(app: Any, result: Any) -> bool: go.Scatter( x=[valid_x[star_idx]], y=[valid_y[star_idx]], + # Its scan-point index, so a click on the star opens that + # point (without it the click fell back to frame 0). + customdata=[valid_idx[star_idx]], mode="markers", name=star_name.replace(" energy", ""), # Gold star with a text-coloured outline, so its edge @@ -4967,7 +5166,9 @@ def show_pes_scan_result(app: Any, result: Any) -> bool: y=fail_y, mode="markers", name="Failed", - marker=dict(size=11, color="#dc2626", symbol="x"), + marker=dict( + size=11, color=_theme.PLOT_DATA_COLORS["red"], symbol="x" + ), hovertext=fail_hover, hoverinfo="text", ) @@ -5002,14 +5203,24 @@ def show_pes_scan_result(app: Any, result: Any) -> bool: gd.on("plotly_click", function(ev){ if(!ev.points||!ev.points.length) return; var pt=ev.points[0]; - var i=(pt.customdata!=null)?pt.customdata:pt.pointIndex; + // Only markers that carry a scan-point index open a geometry; a + // failed point has none (its pointIndex is not a scan index). + if(typeof pt.customdata!=="number") return; + var i=pt.customdata; if(window.__quantuiTrajGoTo){ window.__quantuiTrajGoTo(i); } + __PANE_PICK__ }); } attach(); })(); """ + # With the workspace on, the click also tells the kernel, which shows + # the point's geometry in the viewer pane (app_pane_views). + from quantui.app_pane_views import pes_pick_js, set_pes_linked + + link_js = link_js.replace("__PANE_PICK__", pes_pick_js("i")) app._set_html_output(app._pes_plot_html, plot_html + (link_js if _link else "")) + set_pes_linked(app, _link) except Exception as exc: # noqa: BLE001 app._last_pes_fig = None _show_plot_error( diff --git a/quantui/app_workspace.py b/quantui/app_workspace.py index 34d3114..9a75cd6 100644 --- a/quantui/app_workspace.py +++ b/quantui/app_workspace.py @@ -464,6 +464,7 @@ def selection_text(molecule: Any, picks: Sequence[int]) -> str: _JOB_COLORS = { "idle": _theme.css.TEXT_SUBTLE, + "starting": _theme.css.ACCENT_WARNING, "running": _theme.css.ACCENT_WARNING, "done": _theme.css.ACCENT_SUCCESS, "warn": _theme.css.ACCENT_WARNING, @@ -472,14 +473,17 @@ def selection_text(molecule: Any, picks: Sequence[int]) -> str: def job_state(app: Any) -> tuple[str, str]: - """(key, label) for the current job: idle / running / done / warn / failed. + """(key, label) for the current job: idle / starting / running / done / warn / failed. The one status source for both the workspace footer and the header chip (UX-4). Read from the existing run state — ``_calc_running``, the compute-activity counter (calibration, isosurfaces), the step indicator's last two steps (run, results) and the last run's warnings — rather than a - second copy. + second copy. "starting" covers the moment between the Run click and the + run getting under way (UX-34). """ + if bool(getattr(app, "_run_starting", False)): + return "starting", "Starting…" if bool(getattr(app, "_calc_running", False)): calc = getattr(getattr(app, "calc_type_dd", None), "value", "") or "" return "running", f"Running {calc}".strip() + "…" @@ -499,6 +503,7 @@ def job_state(app: Any) -> tuple[str, str]: _CHIP_TOOLTIPS = { "idle": "No calculation running.", + "starting": "The calculation is starting.", "running": "A calculation is running.", "done": "The last calculation finished.", "warn": "The last calculation finished with warnings — see Results.", diff --git a/quantui/app_xyz_input.py b/quantui/app_xyz_input.py index 4fe7ab6..3bc0480 100644 --- a/quantui/app_xyz_input.py +++ b/quantui/app_xyz_input.py @@ -10,6 +10,7 @@ from quantui import theme as _theme from quantui.molecule import ISOTOPE_NOTE, has_isotope_labels, parse_xyz_input +from quantui.utils import status_icon from quantui.xyz_input import ( format_xyz_body, load_molecule_from_xyz_text, @@ -79,6 +80,7 @@ def _head(text: str, width: str) -> widgets.HTML: app.xyz_cleanup_notes = widgets.HTML(value="") app.xyz_cleanup_preview = widgets.Textarea( disabled=True, + tooltip="Cleaned-up coordinates (preview)", layout=layout_fn(width="440px", height="110px"), ) app.xyz_cleanup_accept_btn = widgets.Button( @@ -128,10 +130,18 @@ def _add_xyz_table_row( value=symbol, layout=layout_fn(width=_SYM_W), placeholder="H", + # The column headings are separate text; tooltips name each field. + tooltip="Element symbol", + ) + x_w, y_w, z_w = ( + widgets.FloatText( + value=v, + layout=layout_fn(width=_COORD_W), + step=0.01, + tooltip=f"{axis} coordinate (Å)", + ) + for axis, v in (("x", x), ("y", y), ("z", z)) ) - x_w = widgets.FloatText(value=x, layout=layout_fn(width=_COORD_W), step=0.01) - y_w = widgets.FloatText(value=y, layout=layout_fn(width=_COORD_W), step=0.01) - z_w = widgets.FloatText(value=z, layout=layout_fn(width=_COORD_W), step=0.01) remove_btn = widgets.Button( icon="trash", layout=layout_fn(width="36px", height="28px"), @@ -176,7 +186,7 @@ def set_xyz_msg(app: Any, text: str, kind: str = "info") -> None: app.xyz_msg.value = "" return color = _theme.css.ACCENT_ERROR if kind == "error" else _theme.css.TEXT_BODY - icon = "⚠ " if kind == "error" else "" + icon = status_icon("error") + " " if kind == "error" else "" app.xyz_msg.value = ( f'
{icon}{html.escape(text)}
' @@ -196,8 +206,8 @@ def xyz_error_html(text: str, exc: BaseException) -> str: if not problems: return ( f'
⚠ ' - f"{html.escape(str(exc).replace('❌ ', ''))}
" + f'word-break:break-word;margin:4px 0">{status_icon("error")} ' + f"{html.escape(str(exc))}" ) shown = problems[:_MAX_LISTED_PROBLEMS] more = len(problems) - len(shown) @@ -211,7 +221,7 @@ def xyz_error_html(text: str, exc: BaseException) -> str: n = len(problems) return ( f'
⚠ The coordinates could not be read ' + f'word-break:break-word">{status_icon("error")} The coordinates could not be read ' f"({n} problem{'s' if n != 1 else ''}):" f'
    {items}
' f'' diff --git a/quantui/backends/slurm_errors.py b/quantui/backends/slurm_errors.py index 794dd04..5fa0ce8 100644 --- a/quantui/backends/slurm_errors.py +++ b/quantui/backends/slurm_errors.py @@ -11,6 +11,9 @@ from dataclasses import dataclass from typing import List, Optional, Tuple +from quantui.theme import alert_box_style, css +from quantui.utils import status_icon + @dataclass(frozen=True) class ErrorTranslation: @@ -164,16 +167,22 @@ def format_error_for_student(stderr: str) -> str: translation = translate_slurm_error(stderr) if translation is not None: lines = [ - f"❌ {translation.category}: {translation.summary}", + f"{translation.category}: {translation.summary}", "", - f"💡 What to do: {translation.advice}", + f"What to do: {translation.advice}", "", f"Technical details: {translation.raw_excerpt}", ] return "\n".join(lines) truncated = stderr.strip()[:500] - return f"❌ Error encountered:\n\n{truncated}" + return f"Error encountered:\n\n{truncated}" + + +# Theme tokens, not a light-only pink box (UX-32). +_BOX = alert_box_style("error", padding="10px 14px") + ";max-width:620px" +_ERR = css.ACCENT_ERROR +_MUTED = css.TEXT_MUTED def format_error_html(stderr: str) -> str: @@ -186,13 +195,12 @@ def format_error_html(stderr: str) -> str: translation = translate_slurm_error(stderr) if translation is not None: return ( - '
' - f'
' - f"❌ {esc(translation.category)}: {esc(translation.summary)}
" + f'
' + f'
' + f"{status_icon('error')} {esc(translation.category)}: {esc(translation.summary)}
" f'
' - f"💡 What to do: {esc(translation.advice)}
" - f'
' + f"{status_icon('tip')} What to do: {esc(translation.advice)}
" + f'
' f"Technical details" f"
"
             f"{esc(translation.raw_excerpt)}
" @@ -201,10 +209,9 @@ def format_error_html(stderr: str) -> str: truncated = stderr.strip()[:500] return ( - '
' - '
' - "❌ Error encountered
" + f'
' + f'
' + f"{status_icon('error')} Error encountered
" f'
'
         f"{esc(truncated)}
" ) diff --git a/quantui/comparison.py b/quantui/comparison.py index e1138c6..e60f771 100644 --- a/quantui/comparison.py +++ b/quantui/comparison.py @@ -22,6 +22,8 @@ import numpy as np +from quantui.theme import PLOT_DATA_COLORS + from .config import HARTREE_TO_EV, HARTREE_TO_KJ_MOL logger = logging.getLogger(__name__) @@ -307,7 +309,10 @@ def comparison_table_html( ) e_str = f"{s.energy_hartree:.8f}" if s.energy_hartree is not None else "—" g_str = f"{s.homo_lumo_gap_ev:.4f}" if s.homo_lumo_gap_ev is not None else "—" - c_str = "✅" if s.converged else ("❌" if s.converged is not None else "—") + # Words, not emoji (UX-31); "No" in bold so it is not missed. + c_str = ( + "Yes" if s.converged else ("No" if s.converged is not None else "—") + ) i_str = str(s.n_iterations) if s.n_iterations is not None else "—" rows.append( # Explicit, theme-aware row colours: JupyterLab's rendered-HTML @@ -405,7 +410,10 @@ def plot_comparison( if has_energies: ax = axes[idx] vals = [e if e is not None else 0.0 for e in energies] - colours = ["#2171b5" if e is not None else "#bdbdbd" for e in energies] + colours = [ + PLOT_DATA_COLORS["blue"] if e is not None else PLOT_DATA_COLORS["grey"] + for e in energies + ] ax.bar(x, vals, color=colours, edgecolor="white") ax.set_xticks(x) ax.set_xticklabels(labels, rotation=30, ha="right", fontsize=9) @@ -419,7 +427,10 @@ def plot_comparison( if has_gaps: ax = axes[idx] vals = [g if g is not None else 0.0 for g in gaps] - colours = ["#e6550d" if g is not None else "#bdbdbd" for g in gaps] + colours = [ + PLOT_DATA_COLORS["orange"] if g is not None else PLOT_DATA_COLORS["grey"] + for g in gaps + ] ax.bar(x, vals, color=colours, edgecolor="white") ax.set_xticks(x) ax.set_xticklabels(labels, rotation=30, ha="right", fontsize=9) @@ -443,8 +454,8 @@ def plot_comparison_plotly( summaries: Sequence[CalcSummary], *, reference_index: int = 0, - bar_color: str = "#2563eb", - gap_color: str = "#7c3aed", + bar_color: str = PLOT_DATA_COLORS["blue"], + gap_color: str = PLOT_DATA_COLORS["purple"], font_color: Optional[str] = None, grid_color: Optional[str] = None, axis_color: Optional[str] = None, diff --git a/quantui/downloads.py b/quantui/downloads.py index 9e1d144..e588e56 100644 --- a/quantui/downloads.py +++ b/quantui/downloads.py @@ -52,11 +52,11 @@ def download_link_html(path: Union[str, Path], label: Optional[str] = None) -> s try: size = p.stat().st_size except OSError: - return f'{name} not found.' + return f'{name} not found.' if size > MAX_DOWNLOAD_BYTES: mb = size / (1024 * 1024) return ( - f'{name} is {mb:.0f} MB — too large ' + f'{name} is {mb:.0f} MB — too large ' f"for a browser download link (limit " f"{MAX_DOWNLOAD_BYTES // (1024 * 1024)} MB). Copy it from the " "result folder instead." @@ -84,7 +84,7 @@ def text_download_link_html( name = html.escape(Path(filename).name) if len(data) > MAX_DOWNLOAD_BYTES: return ( - f'{name} is too large for a browser ' + f'{name} is too large for a browser ' "download link." ) mime = _MIME.get(Path(filename).suffix.lower(), "text/plain") @@ -137,4 +137,4 @@ def offer_download(app: object, path: Union[str, Path]) -> None: try: slot.value = download_link_html(path) except Exception as exc: # noqa: BLE001 — a link must never break an export - slot.value = f'Download link failed: {html.escape(str(exc))}' + slot.value = f'Download link failed: {html.escape(str(exc))}' diff --git a/quantui/ecd_plot.py b/quantui/ecd_plot.py index 1c6ba1b..b7a6b06 100644 --- a/quantui/ecd_plot.py +++ b/quantui/ecd_plot.py @@ -36,6 +36,8 @@ import numpy as np +from quantui.theme import PLOT_DATA_COLORS, plot_chrome + # h·c in eV·nm — λ(nm) = 1239.84 / E(eV) EV_NM: float = 1239.84193 @@ -138,7 +140,7 @@ def plot_ecd_spectrum( x=lam.tolist(), y=deps.tolist(), mode="lines", - line=dict(color="#2563eb", width=2), + line=dict(color=PLOT_DATA_COLORS["blue"], width=2), name="Δε (broadened)", hovertemplate=( "λ: %{x:.1f} nm
Δε: %{y:.3g} L mol⁻¹ cm⁻¹" @@ -158,7 +160,7 @@ def plot_ecd_spectrum( x=xs, y=ys, mode="lines", - line=dict(color="#6b7280", width=2), + line=dict(color=PLOT_DATA_COLORS["grey"], width=2), name="Rotatory strength", hoverinfo="skip", ) @@ -169,7 +171,10 @@ def plot_ecd_spectrum( y=rot, mode="markers", marker=dict( - color=["#dc2626" if r >= 0 else "#2563eb" for r in rot], + color=[ + PLOT_DATA_COLORS["red"] if r >= 0 else PLOT_DATA_COLORS["blue"] + for r in rot + ], size=8, ), name="R (velocity gauge)", @@ -185,7 +190,7 @@ def plot_ecd_spectrum( # Symmetric about zero; a flat (achiral) spectrum still gets a visible # axis instead of Plotly's degenerate [-1e-12, 1e-12] autorange. y_lim = 1.15 * y_abs if y_abs > 1e-6 else 1.0 - fig.add_hline(y=0.0, line=dict(color="#9ca3af", width=1)) + fig.add_hline(y=0.0, line=dict(color=plot_chrome()["axis_line_color"], width=1)) fig.update_layout( xaxis_title="Wavelength (nm)", yaxis_title=y_title, diff --git a/quantui/freq_calc.py b/quantui/freq_calc.py index 3a3295c..88a79d5 100644 --- a/quantui/freq_calc.py +++ b/quantui/freq_calc.py @@ -759,7 +759,7 @@ def _status(msg: str) -> None: mf, gpu_used, gpu_name = _try_to_gpu(mf, method_upper) if gpu_used: try: - stream.write(f"\n🚀 GPU offload active — running on {gpu_name}\n") + stream.write(f"\nGPU offload active — running on {gpu_name}\n") except Exception: # noqa: BLE001 — cleanup (stream may be closed) pass diff --git a/quantui/help_content.py b/quantui/help_content.py index a0a0d96..09074e4 100644 --- a/quantui/help_content.py +++ b/quantui/help_content.py @@ -215,11 +215,11 @@ "
" " " "" - " " + " " " " " " "" - " " + " " " " " " "" @@ -240,7 +240,7 @@ " " " " "" - " " + " " " " " " "
CalculationAccuracyBest for
STO-3G⚡ Very fastVery fastLowLearning, quick tests
3-21G⚡ FastFastLow–MediumQuick estimates
6-31GHighCorrelation-consistent studies
cc-pVTZ🐢 SlowSlowVery highBenchmark / publication
" @@ -335,7 +335,7 @@ " Effect of DF" "TD-DFT (UV-Vis) and larger " "molecules" - " ⚡ Noticeably faster — this is the " + " Noticeably faster — this is the " "case it is built for" "Small single points" " Roughly neutral, sometimes slightly " @@ -1602,8 +1602,8 @@ def help_panel(topic: str) -> widgets.HTML: entry = HELP_TOPICS[topic] html = ( f'
' - f'' - f'ℹ️ {entry["title"]}' + f'' + f' {entry["title"]}' f'
{entry["body"]}
' f"
" ) diff --git a/quantui/ir_plot.py b/quantui/ir_plot.py index 8452a31..f24bf26 100644 --- a/quantui/ir_plot.py +++ b/quantui/ir_plot.py @@ -57,6 +57,8 @@ import numpy as np import plotly.graph_objects as go +from quantui.theme import PLOT_DATA_COLORS, plot_chrome + # x-axis range is low → high wavenumber; ``plot_ir_spectrum(descending=True)`` # flips it to the FTIR convention (high → low), which the app uses by default. # This used to be the FIXED plot range/grid @@ -195,7 +197,7 @@ def plot_ir_spectrum( scale_factor: float = 1.0, lineshape: str = "lorentzian", yaxis_mode: str = "intensity", - color: str = "#2563eb", + color: str = PLOT_DATA_COLORS["blue"], ) -> go.Figure: """Return a Plotly figure for the IR absorption spectrum. @@ -222,7 +224,8 @@ def plot_ir_spectrum( ``"transmittance"`` (%T, bands pointing down). color: Line, stick and marker colour. The app passes the theme's info accent so the spectrum reads on every palette (UX-20); the - default suits a white page. + default is a mid-tone blue that keeps 3:1 on light and dark + backgrounds (UX-32). Returns: :class:`plotly.graph_objects.Figure` ready for display or wrapping @@ -245,21 +248,21 @@ def plot_ir_spectrum( title="Transmittance (%)", range=[0, 105], showgrid=True, - gridcolor="#e5e7eb", + gridcolor=plot_chrome()["grid_color"], ) else: yaxis = dict( title=yaxis_title, rangemode="tozero", showgrid=True, - gridcolor="#e5e7eb", + gridcolor=plot_chrome()["grid_color"], ) _base_layout = dict( xaxis=dict( title=x_title, range=xrange[::-1] if descending else xrange, showgrid=True, - gridcolor="#e5e7eb", + gridcolor=plot_chrome()["grid_color"], ), yaxis=yaxis, template="plotly_white", diff --git a/quantui/molecule.py b/quantui/molecule.py index a68444e..0795b53 100644 --- a/quantui/molecule.py +++ b/quantui/molecule.py @@ -141,7 +141,7 @@ def _validate(self): num_electrons = self.get_electron_count() if num_electrons < 1: raise ValueError( - f"❌ Charge Error: charge {self.charge:+d} leaves " + f"Charge Error: charge {self.charge:+d} leaves " f"{num_electrons} electrons — the atoms only have " f"{num_electrons + self.charge}. Lower the charge." ) @@ -150,7 +150,7 @@ def _validate(self): # (H2 has 2 electrons, so multiplicity 5 is impossible). if self.multiplicity - 1 > num_electrons: raise ValueError( - f"❌ Multiplicity Error: Multiplicity {self.multiplicity} needs " + f"Multiplicity Error: Multiplicity {self.multiplicity} needs " f"{self.multiplicity - 1} unpaired electrons, but this molecule " f"has only {num_electrons}. Lower the multiplicity." ) @@ -170,11 +170,11 @@ def _validate(self): valid_str = ", ".join(str(m) for m in valid_mults) raise ValueError( - f"❌ Multiplicity Error: Multiplicity {self.multiplicity} is incompatible with " + f"Multiplicity Error: Multiplicity {self.multiplicity} is incompatible with " f"{num_electrons} electrons.\n\n" - f"💡 Explanation: This molecule has {num_electrons} electrons (an " + f"Explanation: This molecule has {num_electrons} electrons (an " f"{'even' if num_electrons % 2 == 0 else 'odd'} number), so the {explanation}.\n\n" - f"✅ Valid multiplicities for this molecule: {valid_str}\n\n" + f"Valid multiplicities for this molecule: {valid_str}\n\n" f"Common values:\n" f" • Multiplicity 1 (singlet) = all electrons paired\n" f" • Multiplicity 2 (doublet) = 1 unpaired electron (radical)\n" @@ -448,7 +448,7 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: xyz_text = normalize_xyz_text(xyz_text) if not xyz_text or not xyz_text.strip(): raise ValueError( - "❌ Empty Input: Please provide XYZ coordinates.\n\n" + "Empty Input: Please provide XYZ coordinates.\n\n" "Expected format:\n" " ATOM X Y Z\n\n" "Example:\n" @@ -498,10 +498,10 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: # The second frame's count line used to fail as # "Line N: not enough values", which says nothing useful. raise ValueError( - f"❌ This looks like a multi-frame XYZ file ({n_frames} " + f"This looks like a multi-frame XYZ file ({n_frames} " f"structures of {expected_atoms} atoms each, e.g. an " "optimization trajectory).\n\n" - "💡 Paste only one structure (one count line, one title line, " + "Tip: paste only one structure (one count line, one title line, " "then the atom lines), or load the whole file with the " "Upload File tab, which takes the last structure." ) @@ -536,7 +536,7 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: if not processed_lines: raise ValueError( - "❌ No Data: All lines are empty or comments.\n\n" + "No Data: All lines are empty or comments.\n\n" "Please provide at least 1 atom with coordinates." ) @@ -552,11 +552,11 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: # Check minimum parts (atom symbol + 3 coordinates) if len(parts) < 4: raise ValueError( - f"❌ Line {orig_line_num}: Invalid format - not enough values.\n\n" + f"Line {orig_line_num}: Invalid format - not enough values.\n\n" f"Got: {line}\n" f"Expected format: ATOM X Y Z\n\n" f"Example: H 0.0 0.0 0.74\n\n" - f"💡 Make sure each line has:\n" + f"Make sure each line has:\n" f" 1. Atom symbol (H, C, N, O, etc.)\n" f" 2. Three coordinate values (X, Y, Z)" ) @@ -607,17 +607,17 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: # Build error message error_msg = ( - f"❌ Line {orig_line_num}: Invalid atom symbol '{atom_symbol}'.\n\n" + f"Line {orig_line_num}: Invalid atom symbol '{atom_symbol}'.\n\n" f"Got: {line}\n" ) if suggestions: - error_msg += "\n💡 Suggestions:\n" + error_msg += "\nSuggestions:\n" for suggestion in suggestions: error_msg += f" • {suggestion}\n" else: error_msg += ( - "\n💡 Valid atom symbols include:\n" + "\nValid atom symbols include:\n" " • H, C, N, O, F, P, S, Cl, Br, I\n" " • Li, Be, B, Na, Mg, Al, Si\n" " • K, Ca, Fe, Cu, Zn, etc.\n" @@ -631,19 +631,19 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: x, y, z = _xyz_float(parts[1]), _xyz_float(parts[2]), _xyz_float(parts[3]) except ValueError as e: raise ValueError( - f"❌ Line {orig_line_num}: Could not parse coordinates as numbers.\n\n" + f"Line {orig_line_num}: Could not parse coordinates as numbers.\n\n" f"Got: {line}\n" f"Values: X={parts[1]}, Y={parts[2]}, Z={parts[3]}\n\n" - f"💡 Coordinates must be numbers (integers or decimals).\n" + f"Coordinates must be numbers (integers or decimals).\n" f"Examples: 0.0, 1.5, -2.3, 0.757\n\n" f"Error details: {e}" ) from e if not all(math.isfinite(v) for v in (x, y, z)): raise ValueError( - f"❌ Line {orig_line_num}: Coordinates must be finite numbers.\n\n" + f"Line {orig_line_num}: Coordinates must be finite numbers.\n\n" f"Got: {line}\n\n" - f"💡 'nan' and 'inf' are not positions — re-export the " + f"Tip: 'nan' and 'inf' are not positions — re-export the " f"structure or fix this line." ) @@ -653,7 +653,7 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: # Validate we got atoms if not atoms: raise ValueError( - "❌ No atoms found in input after parsing.\n\n" + "No atoms found in input after parsing.\n\n" "Please check your coordinate format." ) @@ -662,9 +662,9 @@ def parse_xyz_input(xyz_text: str) -> Tuple[List[str], List[List[float]]]: # calculation on the wrong molecule. if expected_atoms is not None and len(atoms) != expected_atoms: raise ValueError( - f"❌ Atom count mismatch: the XYZ header says {expected_atoms} " + f"Atom count mismatch: the XYZ header says {expected_atoms} " f"atoms, but {len(atoms)} atom line(s) were found.\n\n" - "💡 The paste may be truncated. Paste the complete structure, or " + "Tip: the paste may be truncated. Paste the complete structure, or " "fix (or delete) the count line at the top." ) diff --git a/quantui/mulliken_plot.py b/quantui/mulliken_plot.py index ca34215..1ab085a 100644 --- a/quantui/mulliken_plot.py +++ b/quantui/mulliken_plot.py @@ -11,6 +11,8 @@ import plotly.graph_objects as go +from quantui.theme import PLOT_DATA_COLORS, plot_chrome + def plot_mulliken_charges( atom_symbols: Sequence[str], @@ -30,7 +32,10 @@ def plot_mulliken_charges( """ labels: List[str] = [f"{sym}{i + 1}" for i, sym in enumerate(atom_symbols)] values = [float(c) for c in charges] - colors = ["#2563eb" if c >= 0 else "#dc2626" for c in values] + colors = [ + PLOT_DATA_COLORS["blue"] if c >= 0 else PLOT_DATA_COLORS["red"] for c in values + ] + chrome = plot_chrome() fig = go.Figure( data=[ @@ -47,15 +52,15 @@ def plot_mulliken_charges( title=f"{scheme} charge (e)", zeroline=True, zerolinewidth=1.5, - zerolinecolor="#9ca3af", + zerolinecolor=chrome["axis_line_color"], showgrid=True, - gridcolor="#e5e7eb", + gridcolor=chrome["grid_color"], ), template="plotly_white", showlegend=False, margin=dict(l=60, r=20, t=20, b=55), height=height, - plot_bgcolor="#fafafa", + plot_bgcolor=chrome["plot_bgcolor"], ), ) return fig diff --git a/quantui/nmr_plot.py b/quantui/nmr_plot.py index bd20c87..92e49ac 100644 --- a/quantui/nmr_plot.py +++ b/quantui/nmr_plot.py @@ -11,6 +11,8 @@ import plotly.graph_objects as go +from quantui.theme import PLOT_DATA_COLORS, plot_chrome + # Typical display windows (ppm) when peaks are sparse. _DEFAULT_XRANGE = { "¹H": (0.0, 12.0), @@ -179,7 +181,7 @@ def plot_nmr_spectrum( title="Chemical shift δ (ppm)", range=[xmax, xmin] if descending else [xmin, xmax], showgrid=True, - gridcolor="#e5e7eb", + gridcolor=plot_chrome()["grid_color"], ), yaxis=dict( title="", @@ -192,7 +194,7 @@ def plot_nmr_spectrum( showlegend=False, margin=dict(l=60, r=20, t=20, b=55), height=300, - plot_bgcolor="#fafafa", + plot_bgcolor=plot_chrome()["plot_bgcolor"], ) ) @@ -231,7 +233,7 @@ def plot_nmr_spectrum( x=stick_x, y=stick_y, mode="lines", - line=dict(color="#0d9488", width=2), + line=dict(color=PLOT_DATA_COLORS["teal"], width=2), name=f"{nucleus_label} (stick)", hoverinfo="skip", ) @@ -243,7 +245,7 @@ def plot_nmr_spectrum( mode="markers+text", text=hover_labels, textposition="top center", - marker=dict(color="#0f766e", size=7), + marker=dict(color=PLOT_DATA_COLORS["teal"], size=7), showlegend=False, customdata=[len(g) for g in groups], hovertemplate=( diff --git a/quantui/optimizer.py b/quantui/optimizer.py index 8e97320..350777f 100644 --- a/quantui/optimizer.py +++ b/quantui/optimizer.py @@ -283,7 +283,7 @@ def calculate( if not self.gpu_used: try: self.progress_stream.write( - f"\n🚀 GPU offload active — running on {_gpu_name}\n" + f"\nGPU offload active — running on {_gpu_name}\n" ) except Exception: # noqa: BLE001 — stream is user-owned pass @@ -467,7 +467,7 @@ def summary(self) -> str: "=" * 60, f" Molecule : {self.formula}", f" Method/Basis : {self.method}/{self.basis}", - f" Converged : {'Yes' if self.converged else '❌ NO — max steps reached'}", + f" Converged : {'Yes' if self.converged else 'NO — max steps reached'}", f" Steps taken : {self.n_steps}", f" Final energy : {self.energy_hartree:.8f} Ha", f" Energy change : {self.energy_change_hartree:+.6f} Ha", @@ -475,10 +475,10 @@ def summary(self) -> str: "=" * 60, ] if self.converged: - lines.append("✅ Optimization converged successfully!") + lines.append("Optimization converged successfully.") else: lines.append( - "⚠️ Optimization did not converge.\n" + "Warning: Optimization did not converge.\n" " Try increasing Max Steps, loosening Force Threshold,\n" " or using LJ pre-optimization to improve the starting geometry." ) @@ -842,7 +842,7 @@ def optimize_geometry( if _pyfock_use_gpu: _write_stream( _stream, - f"\n🚀 PyFock GPU acceleration active — running on " + f"\nPyFock GPU acceleration active — running on " f"{_pyfock_gpu_name}. GPU force evaluation uses numerical " "gradients because PyFock analytical GPU gradients are not " "available in the installed release.\n", diff --git a/quantui/orbital_visualization.py b/quantui/orbital_visualization.py index a5f3456..87fea13 100644 --- a/quantui/orbital_visualization.py +++ b/quantui/orbital_visualization.py @@ -30,6 +30,15 @@ logger = logging.getLogger(__name__) +# Energy-level diagram colours: mid-tones that keep 3:1 on light and dark +# plot backgrounds (UX-32; the old #2171b5 was 2.85:1 on Dark and the grey +# virtual levels 1.7:1 on Bright). +_C_OCC = _theme.PLOT_DATA_COLORS["blue"] +_C_LUMO = _theme.PLOT_DATA_COLORS["orange"] +_C_VIRT = _theme.PLOT_DATA_COLORS["grey"] +# Chrome defaults for figures built outside the app (the app re-themes). +_CHROME = _theme.plot_chrome() + # Conversion factor — PySCF stores MO energies in Hartree HARTREE_TO_EV: float = 27.211386245988 BOHR_PER_ANGSTROM: float = 1.8897261254578281 @@ -280,7 +289,7 @@ def plot_orbital_diagram( # Draw energy levels line_half_width = 0.3 for i, (e, occ) in enumerate(zip(subset, subset_occ)): - color = "#2171b5" if occ else "#bdbdbd" + color = _C_OCC if occ else _C_VIRT lw = 2.5 if (start + i == n_occ - 1 or start + i == n_occ) else 1.5 ax.plot( [-line_half_width, line_half_width], @@ -304,7 +313,7 @@ def plot_orbital_diagram( ax.plot( [beta_dx - line_half_width, beta_dx + line_half_width], [e_b[j], e_b[j]], - color="#2171b5" if j < n_occ_b else "#bdbdbd", + color=_C_OCC if j < n_occ_b else _C_VIRT, linewidth=2.5 if j in (n_occ_b - 1, n_occ_b) else 1.5, solid_capstyle="round", ) @@ -321,7 +330,7 @@ def plot_orbital_diagram( xy=(beta_dx + line_half_width + 0.05, info.homo_energy_ev), fontsize=10, fontweight="bold", - color="#2171b5", + color=_C_OCC, va="center", ) @@ -331,7 +340,7 @@ def plot_orbital_diagram( xy=(beta_dx + line_half_width + 0.05, info.lumo_energy_ev), fontsize=10, fontweight="bold", - color="#e6550d", + color=_C_LUMO, va="center", ) @@ -342,7 +351,7 @@ def plot_orbital_diagram( "", xy=(mid_x, info.lumo_energy_ev), xytext=(mid_x, info.homo_energy_ev), - arrowprops=dict(arrowstyle="<->", color="#e6550d", lw=1.5), + arrowprops=dict(arrowstyle="<->", color=_C_LUMO, lw=1.5), ) gap_mid = (info.homo_energy_ev + info.lumo_energy_ev) / 2.0 ax.text( @@ -350,7 +359,7 @@ def plot_orbital_diagram( gap_mid, f"{info.homo_lumo_gap_ev:.2f} eV", fontsize=9, - color="#e6550d", + color=_C_LUMO, ha="right", va="center", fontweight="bold", @@ -372,8 +381,8 @@ def plot_orbital_diagram( ) # Legend - occ_patch = mpatches.Patch(color="#2171b5", label="Occupied") - virt_patch = mpatches.Patch(color="#bdbdbd", label="Virtual") + occ_patch = mpatches.Patch(color=_C_OCC, label="Occupied") + virt_patch = mpatches.Patch(color=_C_VIRT, label="Virtual") ax.legend(handles=[occ_patch, virt_patch], loc="lower right", fontsize=9) fig.tight_layout() @@ -524,16 +533,16 @@ def _sym(idx: int) -> str: name = f"MO #{idx + 1}{tag}{ch_sym(idx)}" if is_homo: - color, lw = "#2171b5", 3.0 + color, lw = _C_OCC, 3.0 hover = f"{name} — HOMO
{e:+.4f} eV" elif is_lumo: - color, lw = "#e6550d", 3.0 + color, lw = _C_LUMO, 3.0 hover = f"{name} — LUMO
{e:+.4f} eV" elif is_occ: - color, lw = "#2171b5", 1.5 + color, lw = _C_OCC, 1.5 hover = f"{name} (occupied)
{e:+.4f} eV" else: - color, lw = "#9e9e9e", 1.5 + color, lw = _C_VIRT, 1.5 hover = f"{name} (virtual)
{e:+.4f} eV" traces.append( @@ -579,7 +588,7 @@ def _sym(idx: int) -> str: yref="y", text=f"HOMO{homo_lbl}", showarrow=False, - font=dict(size=fs_label, color="#2171b5"), + font=dict(size=fs_label, color=_C_OCC), xanchor="left", yanchor="middle", ), @@ -593,7 +602,7 @@ def _sym(idx: int) -> str: yref="y", text=f"LUMO{lumo_lbl}", showarrow=False, - font=dict(size=fs_label, color="#e6550d"), + font=dict(size=fs_label, color=_C_LUMO), xanchor="left", yanchor="middle", ), @@ -607,10 +616,10 @@ def _sym(idx: int) -> str: axref="x", ayref="y", text=f"{gap:.2f} eV", - font=dict(size=fs_gap, color="#e6550d"), + font=dict(size=fs_gap, color=_C_LUMO), arrowhead=2, arrowwidth=1.5, - arrowcolor="#e6550d", + arrowcolor=_C_LUMO, xanchor="right", ), ] @@ -692,7 +701,7 @@ def _sym(idx: int) -> str: title=dict(text="Energy (eV)", font=dict(size=fs_axis)), range=[y_min, y_max], showgrid=True, - gridcolor="#e5e7eb", + gridcolor=_CHROME["grid_color"], tickformat=".1f", tickfont=dict(size=fs_axis), ), @@ -717,8 +726,8 @@ def orbital_summary_html(info: OrbitalInfo) -> str: """ a = " (α)" if _is_unrestricted(info) else "" # counts below are alpha-only return ( - '
' + '
' f"Orbital Summary — {_html_escape(info.formula)}
" f"Occupied MOs{a}: {info.n_occupied}  |  " f"Virtual MOs{a}: {info.n_virtual}  |  " @@ -1605,7 +1614,7 @@ def orbital_colors(scheme: str) -> tuple[str, str]: range:__RANGE__}; function v(){ return window["viewer_"+UID]; } - // ⚠️ Isosurfaces are SHAPES, not surfaces. viewer.addVolumetricData() routes + // NOTE: Isosurfaces are SHAPES, not surfaces. viewer.addVolumetricData() routes // to addIsosurface(), which does this.shapes.push(...) — so // removeAllSurfaces() iterates this.surfaces, finds nothing, and removes // nothing. Using it meant every update stacked another layer on the old one: @@ -2162,10 +2171,10 @@ def plot_cube_isosurface( show_molecule: bool = False, show_grid: bool = True, scene_bgcolor: str = "white", - axis_color: str = "#111827", + axis_color: str = _CHROME["font_color"], max_points: Optional[int] = None, title_color: Optional[str] = None, - bond_color: str = "#6b7280", + bond_color: str = _CHROME["axis_line_color"], ): """ Render an orbital isosurface from a cube file using Plotly. diff --git a/quantui/pes_scan_2d_plot.py b/quantui/pes_scan_2d_plot.py index 1b9464b..909e0fc 100644 --- a/quantui/pes_scan_2d_plot.py +++ b/quantui/pes_scan_2d_plot.py @@ -14,6 +14,8 @@ import plotly.graph_objects as go +from quantui.theme import PLOT_DATA_COLORS + def _none_if_nan(v: float) -> Optional[float]: return float(v) if math.isfinite(v) else None @@ -123,7 +125,7 @@ def build_pes_2d_figure(result: Any, *, link_hint: bool = True) -> go.Figure: y=bad_y, mode="markers", name="Failed", - marker=dict(size=11, color="#dc2626", symbol="x"), + marker=dict(size=11, color=PLOT_DATA_COLORS["red"], symbol="x"), hovertext=bad_hover, hoverinfo="text", ) @@ -144,11 +146,17 @@ def build_pes_2d_figure(result: Any, *, link_hint: bool = True) -> go.Figure: def click_link_js(div_id: str, n2: int) -> str: """Script sending a clicked grid point to the Trajectory panel. + With the workspace on, the click also reaches the kernel (a hidden inbox, + ``app_pane_views.pes_pick_js``), which shows the point in the viewer pane. + A marker carries its point index in ``customdata``; a click on the map itself reports ``pointIndex = [row (coordinate 2), column (coordinate 1)]``, which is turned into the same index. """ - return """ + from quantui.app_pane_views import pes_pick_js + + return ( + """ """.replace("__N2__", str(int(n2))).replace("__DIV__", div_id) +""".replace("__N2__", str(int(n2))) + .replace("__DIV__", div_id) + .replace("__PANE_PICK__", pes_pick_js("i")) + ) diff --git a/quantui/populations_overlay.py b/quantui/populations_overlay.py index 1d6b6d5..3baabc8 100644 --- a/quantui/populations_overlay.py +++ b/quantui/populations_overlay.py @@ -344,7 +344,7 @@ def _mulliken_vividness(app: Any) -> float: def _mulliken_viewer_unavailable_html() -> str: - style = "padding:12px 16px;color:#6b7280;font-size:13px;font-style:italic" + style = "padding:12px 16px;color:var(--q-text-muted, #666);font-size:13px;font-style:italic" return ( f'
' "3D structure unavailable: this result has no saved coordinates. " diff --git a/quantui/progress.py b/quantui/progress.py index eb3f039..2aae213 100644 --- a/quantui/progress.py +++ b/quantui/progress.py @@ -30,6 +30,7 @@ import ipywidgets as widgets from quantui import theme as _theme +from quantui.utils import fa_icon class StepProgress: @@ -38,20 +39,22 @@ class StepProgress: Each step shows an icon reflecting its state: - - ⬜ not started - - ⏳ in progress - - ✅ completed - - ❌ failed + - an empty square: not started + - an hourglass: in progress + - a check mark: completed + - a cross: failed + + The icons are Font Awesome, not emoji (UI/UX review 2026-12-05, UX-31). Args: step_labels: Human-readable labels for each step. """ _ICONS = { - "pending": "⬜", - "active": "⏳", - "done": "✅", - "fail": "❌", + "pending": fa_icon("square-o"), + "active": fa_icon("hourglass-half"), + "done": fa_icon("check-circle"), + "fail": fa_icon("times-circle"), } def __init__(self, step_labels: List[str], *, horizontal: bool = False) -> None: diff --git a/quantui/pubchem.py b/quantui/pubchem.py index 7ccbc88..0c9fa51 100644 --- a/quantui/pubchem.py +++ b/quantui/pubchem.py @@ -556,7 +556,7 @@ def student_friendly_fetch(name: str) -> Tuple[Optional[str], str]: except MoleculeNotFoundError: message = ( - f"❌ Could not find '{name}' in PubChem.\n" + f"Could not find '{name}' in PubChem.\n" f" Try:\n" f" • Check spelling (e.g., 'ethanol' not 'ethonal')\n" f" • Use IUPAC name (e.g., 'ethanol' not 'alcohol')\n" @@ -567,7 +567,7 @@ def student_friendly_fetch(name: str) -> Tuple[Optional[str], str]: except PubChemAPIError: message = ( - "❌ Connection to PubChem failed.\n" + "Connection to PubChem failed.\n" " • Check your internet connection\n" " • Try again in a moment\n" " • Use preset molecules if problem persists" @@ -576,7 +576,7 @@ def student_friendly_fetch(name: str) -> Tuple[Optional[str], str]: except Exception as e: message = ( - f"❌ Error fetching molecule: {str(e)}\n" + f"Error fetching molecule: {str(e)}\n" f" Please try a different molecule or contact your instructor." ) logger.error(f"Unexpected error in student_friendly_fetch: {e}", exc_info=True) @@ -803,7 +803,7 @@ def student_friendly_smiles_to_xyz(smiles: str) -> Tuple[Optional[str], str]: except ValueError as e: message = ( - f"❌ Invalid SMILES string: {smiles}\n" + f"Invalid SMILES string: {smiles}\n" f" Error: {str(e)}\n\n" f" SMILES Tips:\n" f" • Check syntax (use RDKit/OpenBabel style)\n" @@ -819,14 +819,14 @@ def student_friendly_smiles_to_xyz(smiles: str) -> Tuple[Optional[str], str]: except ImportError: message = ( - "❌ RDKit is required for SMILES conversion.\n" + "RDKit is required for SMILES conversion.\n" " Install with: conda install -c conda-forge rdkit" ) return None, message except Exception as e: message = ( - f"❌ Error converting SMILES: {str(e)}\n" + f"Error converting SMILES: {str(e)}\n" f" Please try a different molecule or contact your instructor." ) logger.error( @@ -972,16 +972,16 @@ def display_2d_structure( ipython_display(SVG(svg)) return True else: - print("⚠️ Could not generate 2D structure") + print("Warning: Could not generate 2D structure") return False except ImportError as e: logger.warning(f"Could not display 2D structure: {e}") - print("⚠️ IPython display not available") + print("Warning: IPython display not available") return False except Exception as e: logger.error(f"2D structure display failed: {e}") - print(f"⚠️ 2D structure display failed: {e}") + print(f"Warning: 2D structure display failed: {e}") return False @@ -1176,28 +1176,28 @@ def student_friendly_resolve(query: str) -> Tuple[Optional[str], str]: xyz_string, metadata = fetch_structure(query, conformer_3d=True) except (MoleculeNotFoundError, ValueError) as exc: return None, ( - f"❌ Could not resolve '{query}'.\n" + f"Could not resolve '{query}'.\n" f" {exc}\n" f" Try a different name, a SMILES (e.g. CCO), or check spelling.\n" f" Search manually at: https://pubchem.ncbi.nlm.nih.gov/" ) except PubChemAPIError: return None, ( - "❌ Connection to PubChem failed.\n" + "Connection to PubChem failed.\n" " • Check your internet connection\n" " • Try again in a moment\n" " • Use a preset molecule if the problem persists" ) except ImportError: return None, ( - "❌ RDKit is required for SMILES / InChI input.\n" + "RDKit is required for SMILES / InChI input.\n" " Install with: conda install -c conda-forge rdkit" ) except Exception as exc: # pragma: no cover - unexpected logger.error( f"Unexpected error in student_friendly_resolve: {exc}", exc_info=True ) - return None, f"❌ Error resolving '{query}': {exc}" + return None, f"Error resolving '{query}': {exc}" source = { "rdkit-smiles": "generated locally from SMILES", diff --git a/quantui/raman_plot.py b/quantui/raman_plot.py index 712d5ca..f2db1f7 100644 --- a/quantui/raman_plot.py +++ b/quantui/raman_plot.py @@ -23,6 +23,7 @@ import plotly.graph_objects as go from quantui.ir_plot import _default_xrange, _grid_for_range, _peak_labels +from quantui.theme import PLOT_DATA_COLORS, plot_chrome def plot_raman_spectrum( @@ -54,13 +55,13 @@ def plot_raman_spectrum( title="Wavenumber (cm⁻¹)", range=xrange[::-1] if descending else xrange, showgrid=True, - gridcolor="#e5e7eb", + gridcolor=plot_chrome()["grid_color"], ), yaxis=dict( title=yaxis_title, rangemode="tozero", showgrid=True, - gridcolor="#e5e7eb", + gridcolor=plot_chrome()["grid_color"], ), template="plotly_white", showlegend=False, @@ -89,7 +90,7 @@ def plot_raman_spectrum( x=_xgrid, y=y_broad, mode="lines", - line=dict(color="#059669", width=1.5), + line=dict(color=PLOT_DATA_COLORS["green"], width=1.5), name="Raman (broadened)", hovertemplate="%{x:.0f} cm⁻¹ | %{y:.2f} Å⁴/amu", ) @@ -106,7 +107,7 @@ def plot_raman_spectrum( x=x_stick, y=y_stick, mode="lines", - line=dict(color="#059669", width=2), + line=dict(color=PLOT_DATA_COLORS["green"], width=2), name="Raman (stick)", hoverinfo="skip", ) @@ -116,7 +117,7 @@ def plot_raman_spectrum( x=list(freqs_real), y=list(acts_real), mode="markers", - marker=dict(color="#047857", size=6), + marker=dict(color=PLOT_DATA_COLORS["green"], size=6), name="Raman (peaks)", showlegend=False, customdata=sym, diff --git a/quantui/session_calc.py b/quantui/session_calc.py index b0ec9fb..21a385d 100644 --- a/quantui/session_calc.py +++ b/quantui/session_calc.py @@ -220,7 +220,7 @@ def summary(self) -> str: f" Molecule : {self.formula}", f" Engine : {self.engine_id}", f" Method/Basis : {self.method}/{self.basis}", - f" SCF converged : {'Yes' if self.converged else '❌ NO — treat results with caution'}", + f" SCF converged : {'Yes' if self.converged else 'NO — treat results with caution'}", f" Iterations : {self.n_iterations}", f" Total energy : {self.energy_hartree:.8f} Ha", ] @@ -228,21 +228,21 @@ def summary(self) -> str: lines.append(f" HOMO-LUMO gap : {self.homo_lumo_gap_ev:.4f} eV") if self.dispersion_applied is False: lines.append( - f" ⚠️ {self.method} requires D3 dispersion, but no D3 backend " + f" Warning: {self.method} requires D3 dispersion, but no D3 backend " "(pyscf-dispersion) was installed — this result has NO " "dispersion correction." ) if self.cc_converged is False: lines.append( - " ⚠️ CCSD amplitude iterations did NOT converge — the " + " Warning: CCSD amplitude iterations did NOT converge — the " "correlation energy above is unreliable." ) lines += [ "=" * 60, ( - "✅ Calculation completed successfully!" + "Calculation completed successfully." if self.converged - else "⚠️ SCF did not converge — try a different starting geometry, basis, or method." + else "Warning: SCF did not converge — try a different starting geometry, basis, or method." ), "=" * 60, ] @@ -922,7 +922,7 @@ def _run_session_calc_body( if density_fit_used and progress_stream is not None: try: progress_stream.write( - "\n⚡ Density fitting (RI) active — approximate integrals\n" + "\nDensity fitting (RI) active — approximate integrals\n" ) except Exception: # noqa: BLE001 — cleanup (stream may be closed) pass @@ -941,7 +941,7 @@ def _run_session_calc_body( mf, gpu_used, gpu_name = _try_to_gpu(mf, method_upper) if gpu_used and progress_stream is not None: try: - progress_stream.write(f"\n🚀 GPU offload active — running on {gpu_name}\n") + progress_stream.write(f"\nGPU offload active — running on {gpu_name}\n") except Exception: # noqa: BLE001 — cleanup (progress stream may be closed) pass diff --git a/quantui/structure_providers.py b/quantui/structure_providers.py index c942bd6..16ae588 100644 --- a/quantui/structure_providers.py +++ b/quantui/structure_providers.py @@ -288,7 +288,7 @@ def resolve_structure_with_details( return ( None, ( - f"❌ Could not resolve '{query}'.\n" + f"Could not resolve '{query}'.\n" f" {exc}\n" f" Try a different name, a SMILES (e.g. CC(=O)O), a CAS " f"number, or check spelling.\n" @@ -297,7 +297,7 @@ def resolve_structure_with_details( ) except Exception as exc: # pragma: no cover - unexpected logger.error(f"Unexpected error resolving '{query}': {exc}", exc_info=True) - return None, f"❌ Error resolving '{query}': {exc}" + return None, f"Error resolving '{query}': {exc}" return result, _resolved_message(query, result) diff --git a/quantui/theme.py b/quantui/theme.py index 2a000cf..cef86b8 100644 --- a/quantui/theme.py +++ b/quantui/theme.py @@ -52,7 +52,8 @@ ACCENT_WARNING_LIGHT = "#f59e0b" ACCENT_INFO = "#2563eb" ACCENT_PURPLE = "#7c3aed" -ACCENT_TEAL = "#0d9488" +# #0d9488 was 3.58:1 on BG_PANEL; the run log uses teal as text (UX-32). +ACCENT_TEAL = "#0f766e" SURFACE_INFO_BG = "#eff6ff" SURFACE_PURPLE_BG = "#f5f3ff" @@ -61,6 +62,9 @@ SURFACE_GREEN_BG = "#f0fdf4" SURFACE_ORANGE_BG = "#fff7ed" SURFACE_MUTED_BG = "#e0e7ef" +# Error boxes (run failed, result not saved); was a light-only #fef2f2 in +# app.py (UX-32). +SURFACE_ERROR_BG = "#fef2f2" _TOKEN_FIELDS: Tuple[str, ...] = ( "page_bg", @@ -96,6 +100,7 @@ "surface_green_bg", "surface_orange_bg", "surface_muted_bg", + "surface_error_bg", ) @@ -139,6 +144,7 @@ class ThemePalette: surface_green_bg: str surface_orange_bg: str surface_muted_bg: str + surface_error_bg: str def css_variables(self) -> Dict[str, str]: """Map ``--q-*`` custom-property names to hex values.""" @@ -293,6 +299,64 @@ def focus_ring_css() -> str: ) +def scrollbar_css() -> str: + """Scrollbars in the palette's colours, not the browser's light default. + + ``scrollbar-color`` (Firefox, Chrome 121+) plus ``::-webkit-scrollbar`` + for older WebKit/Blink. Thumb ``border_strong`` on a ``bg_panel`` track: + >= 3:1 in every palette (tests/test_theme_contrast.py), so the thumb is + findable (UI/UX review 2026-12-05, §4: scrollbars left unthemed). + """ + return ( + "html, body, * " + "{ scrollbar-color: var(--q-border-strong) var(--q-bg-panel) !important; }\n" + "::-webkit-scrollbar { width: 12px; height: 12px; " + "background: var(--q-bg-panel); }\n" + "::-webkit-scrollbar-track, ::-webkit-scrollbar-corner " + "{ background: var(--q-bg-panel); }\n" + "::-webkit-scrollbar-thumb { background: var(--q-border-strong); " + "border-radius: 6px; border: 3px solid var(--q-bg-panel); }\n" + "::-webkit-scrollbar-thumb:hover { background: var(--q-text-subtle); }\n" + ) + + +def selection_css() -> str: + """Selected text in the palette's accent (was the browser default). + + ``page_bg`` text on ``accent_info``: the accent-button pair, >= 4.5:1 in + every palette. + """ + return ( + "::selection { background: var(--q-accent-info) !important; " + "color: var(--q-page-bg) !important; }\n" + ) + + +# Tab sets inside another tab's panel (Calculate → Molecule Input → Library +# was three borders deep; review §4). ipywidgets 8 class first, then the +# deprecated one. +NESTED_TAB_SELECTORS: Tuple[str, ...] = ( + ".widget-tab-contents .jupyter-widget-tab > .widget-tab-contents", + ".widget-tab-contents .widget-tab > .widget-tab-contents", +) + + +def nested_box_css() -> str: + """Flatten a box that sits directly inside another box. + + The inner tab panel loses its frame and its own background; one line + under its tab bar still groups the tabs with their content. + """ + sel = ", ".join(NESTED_TAB_SELECTORS) + return ( + f"{sel} " + "{ border: none !important; " + "border-top: 1px solid var(--q-border) !important; " + "background: transparent !important; " + "padding: 12px 0 4px !important; }\n" + ) + + def _neutral_button_css() -> str: """Default/neutral buttons blend with unified chrome surfaces.""" return ( @@ -326,39 +390,31 @@ def slider_chrome_css() -> str: styling ``input[type=range]`` alone is often ignored. Thumb uses the accent colour with a page-bg ring so it stays visible on every palette. """ - selectors = ( - ".jupyter-widgets input[type=range], " - ".widget-slider input[type=range], " - ".widget-hslider input[type=range], " - "input.quantui-range[type=range]" - ) - thumb = ( - f"{selectors}::-webkit-slider-thumb, " - ".jupyter-widgets input[type=range]::-moz-range-thumb, " - ".widget-slider input[type=range]::-moz-range-thumb, " - ".widget-hslider input[type=range]::-moz-range-thumb, " - "input.quantui-range[type=range]::-moz-range-thumb" + bases = ( + ".jupyter-widgets input[type=range]", + ".widget-slider input[type=range]", + ".widget-hslider input[type=range]", + "input.quantui-range[type=range]", ) - track = ( - f"{selectors}::-webkit-slider-runnable-track, " - ".jupyter-widgets input[type=range]::-moz-range-track, " - ".widget-slider input[type=range]::-moz-range-track, " - ".widget-hslider input[type=range]::-moz-range-track, " - "input.quantui-range[type=range]::-moz-range-track" - ) - return ( - f"{selectors} " - "{ -webkit-appearance: none !important; appearance: none !important; " - "width: 100% !important; height: 20px !important; " - "background: transparent !important; " - "accent-color: var(--q-accent-info) !important; " - "cursor: pointer !important; }\n" - f"{track} " + selectors = ", ".join(bases) + + def pseudo(name: str) -> str: + return ", ".join(f"{b}::{name}" for b in bases) + + # One rule per engine: a selector list that mixes ::-webkit-* and + # ::-moz-* pseudo-elements is invalid as a whole, so the combined rule was + # dropped and Chromium drew no track at all. + webkit_track = pseudo("-webkit-slider-runnable-track") + webkit_thumb = pseudo("-webkit-slider-thumb") + moz_track = pseudo("-moz-range-track") + moz_thumb = pseudo("-moz-range-thumb") + track_body = ( "{ height: 10px !important; border-radius: 5px !important; " "background: var(--q-border-strong) !important; " "border: 1px solid var(--q-border) !important; " "box-shadow: inset 0 0 0 1px var(--q-page-bg) !important; }\n" - f"{thumb} " + ) + thumb_body = ( "{ -webkit-appearance: none !important; appearance: none !important; " "width: 20px !important; height: 20px !important; " "border-radius: 50% !important; " @@ -367,6 +423,18 @@ def slider_chrome_css() -> str: "box-shadow: 0 0 0 1px var(--q-accent-info), " "0 1px 4px rgba(0,0,0,0.45) !important; " "cursor: pointer !important; margin-top: -6px !important; }\n" + ) + return ( + f"{selectors} " + "{ -webkit-appearance: none !important; appearance: none !important; " + "width: 100% !important; height: 20px !important; " + "background: transparent !important; " + "accent-color: var(--q-accent-info) !important; " + "cursor: pointer !important; }\n" + f"{webkit_track} {track_body}" + f"{moz_track} {track_body}" + f"{webkit_thumb} {thumb_body}" + f"{moz_thumb} {thumb_body.replace(' margin-top: -6px !important;', '')}" ".widget-hslider .widget-readout, " ".widget-slider .widget-readout, " ".widget-float-slider .widget-readout " @@ -453,6 +521,9 @@ def _widget_chrome_css() -> str: f"{_accent_button_css()}" f"{focus_ring_css()}" f"{slider_chrome_css()}" + f"{scrollbar_css()}" + f"{selection_css()}" + f"{nested_box_css()}" ".quantui-info-box " f"{{ background: {surface} !important; " "color: var(--q-text-body) !important; " @@ -503,6 +574,7 @@ def _light_palette() -> ThemePalette: surface_green_bg=SURFACE_GREEN_BG, surface_orange_bg=SURFACE_ORANGE_BG, surface_muted_bg=SURFACE_MUTED_BG, + surface_error_bg=SURFACE_ERROR_BG, ) @@ -545,6 +617,7 @@ def _dark_palette() -> ThemePalette: surface_green_bg="#14532d", surface_orange_bg="#431407", surface_muted_bg="#334155", + surface_error_bg="#450a0a", ) @@ -587,6 +660,7 @@ def _midnight_palette() -> ThemePalette: surface_green_bg="#000000", surface_orange_bg="#000000", surface_muted_bg="#111111", + surface_error_bg="#1a0000", ) @@ -629,6 +703,7 @@ def _dark_blue_palette() -> ThemePalette: surface_green_bg="#0d3320", surface_orange_bg="#3d1a0a", surface_muted_bg="#1a3352", + surface_error_bg="#2a1530", ) @@ -671,6 +746,7 @@ def _hot_pink_palette() -> ThemePalette: surface_green_bg="#1a3320", surface_orange_bg="#3d2010", surface_muted_bg="#4a1548", + surface_error_bg="#4a0d2a", ) @@ -713,6 +789,7 @@ def _dark_maroon_palette() -> ThemePalette: surface_green_bg="#1a3320", surface_orange_bg="#3d2010", surface_muted_bg="#3d2430", + surface_error_bg="#3d1015", ) @@ -760,6 +837,7 @@ def _warm_palette() -> ThemePalette: surface_green_bg="#e9f3e2", surface_orange_bg="#fcecdc", surface_muted_bg="#efe6d6", + surface_error_bg="#f9e3dc", ) @@ -885,6 +963,55 @@ def plotly_colors(palette_id: str) -> dict: } +# Data colours for plot traces (UI/UX review 2026-12-05, UX-32). Plots sit +# on the palette's surfaces (a cream page to pure black), and the same +# figure goes into standalone exports, so these are mid-tones: each keeps +# >= 3:1 against bg_panel, page_bg and the 3D scene colour of every palette +# (tests/test_theme_contrast.py). The old #2563eb / #2171b5 blues were 2.8:1 +# on Dark, the grey "virtual" levels 1.7:1 on Bright. +PLOT_DATA_COLORS: Dict[str, str] = { + "blue": "#3b82f6", + "red": "#ef4444", + "orange": "#e6550d", + "green": "#059669", + "teal": "#0d9488", + "purple": "#8b5cf6", + "grey": "#808080", +} + + +def plot_chrome(palette_id: str = DEFAULT_PALETTE_ID) -> dict: + """Grid, axis-line and font colours for a plot module's own defaults. + + The app re-themes every in-app figure (``QuantUIApp._apply_plotly_theme``); + this gives the plot modules the same palette-derived chrome when they are + used on their own, instead of fixed light-theme greys. + """ + return plotly_colors(palette_id) + + +_ALERT_TOKENS: Dict[str, Tuple[str, str]] = { + "error": ("surface-error-bg", "accent-error"), + "warning": ("surface-warning-bg", "accent-warning"), + "info": ("surface-info-bg", "accent-info"), +} + + +def alert_box_style(kind: str = "error", *, padding: str = "14px") -> str: + """Inline style for a run error / warning / info box, from theme tokens. + + Replaces light-only boxes (#fef2f2 on a dark page, UX-32). Text inside + uses ``text_body`` and the accent; both clear 4.5:1 on the box surface in + every palette (tests/test_theme_contrast.py). + """ + bg, edge = _ALERT_TOKENS[kind] + return ( + f"background:var(--q-{bg});border:1px solid var(--q-{edge});" + f"border-radius:8px;padding:{padding};margin:8px 0;" + "color:var(--q-text-body)" + ) + + class _CssVarRefs: """CSS ``var(--q-*)`` references for inline HTML — theme-switchable.""" @@ -921,6 +1048,7 @@ class _CssVarRefs: SURFACE_GREEN_BG = "var(--q-surface-green-bg)" SURFACE_ORANGE_BG = "var(--q-surface-orange-bg)" SURFACE_MUTED_BG = "var(--q-surface-muted-bg)" + SURFACE_ERROR_BG = "var(--q-surface-error-bg)" css = _CssVarRefs() @@ -938,6 +1066,9 @@ def frame_viewer_html(view_html: str, *, width: int, controls: str = "") -> str: __all__ = [ + "PLOT_DATA_COLORS", + "alert_box_style", + "plot_chrome", "ACCENT_ERROR", "ACCENT_ERROR_ALT", "ACCENT_INFO", @@ -972,6 +1103,9 @@ def frame_viewer_html(view_html: str, *, width: int, controls: str = "") -> str: "css", "disabled_button_css", "focus_ring_css", + "nested_box_css", + "scrollbar_css", + "selection_css", "frame_viewer_html", "LOGO_CLASS", "logo_css", diff --git a/quantui/utils.py b/quantui/utils.py index ae486cd..4c885fe 100644 --- a/quantui/utils.py +++ b/quantui/utils.py @@ -260,6 +260,29 @@ def path_html(path: "os.PathLike[str] | str") -> str: ) +# Font Awesome 4 icons for status in HTML messages, instead of emoji (UI/UX +# review 2026-12-05, UX-31). Plain-text messages use words instead. +STATUS_ICONS = { + "error": "times-circle", + "warning": "exclamation-triangle", + "info": "info-circle", + "ok": "check", + "tip": "lightbulb-o", + "resume": "refresh", + "stop": "stop", +} + + +def fa_icon(name: str) -> str: + """Inline Font Awesome 4 icon (decorative: hidden from screen readers).""" + return f'' + + +def status_icon(kind: str) -> str: + """:func:`fa_icon` for a status kind in :data:`STATUS_ICONS`.""" + return fa_icon(STATUS_ICONS[kind]) + + def get_timestamp() -> str: """ Get current timestamp in ISO format. diff --git a/quantui/visualization_py3dmol.py b/quantui/visualization_py3dmol.py index 083d94e..70946f8 100644 --- a/quantui/visualization_py3dmol.py +++ b/quantui/visualization_py3dmol.py @@ -570,7 +570,7 @@ def _unavailable_html(molecule) -> str: """HTML fallback when no 3D visualization backend is installed.""" return ( '
' - "

⚠️ 3D visualization not available.

" + '

3D visualization not available.

' "

To enable visualization, install one of:

" "
  • pip install py3dmol (recommended)
  • " "
  • pip install plotlymol
" @@ -724,7 +724,7 @@ def display_molecule( if not is_visualization_available(): # Fallback: show text representation - print("⚠️ 3D visualization not available") + print("Warning: 3D visualization not available") print("\nTo enable visualization, install one of:") print(" pip install py3dmol (recommended)") print(" pip install plotlymol") diff --git a/tests/test_app_pane_views.py b/tests/test_app_pane_views.py index f5864a0..1d3952e 100644 --- a/tests/test_app_pane_views.py +++ b/tests/test_app_pane_views.py @@ -71,6 +71,21 @@ def _available(app, name): app._activate_ana_panel(name, auto_select=False) +def _prepare(app, name): + """The Trajectory panel draws its viewer (or its note) per result.""" + if name == "Trajectory": + from types import SimpleNamespace + + frames = [ + Molecule(["H", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, z]]) for z in (0.70, 0.74) + ] + app._show_opt_trajectory( + SimpleNamespace( + trajectory=frames, energies_hartree=[-1.0, -1.1], formula="H2" + ) + ) + + # --------------------------------------------------------------------------- # Panel viewers live in the pane, not in their panels # --------------------------------------------------------------------------- @@ -79,6 +94,7 @@ def _available(app, name): class TestPlacement: @pytest.mark.parametrize("name", list(PANE_VIEWS)) def test_panel_viewer_is_not_in_its_panel(self, app, name): + _prepare(app, name) acc = _acc(app, name) assert not _in(acc, _viewer(app, name)) # DEC-009: the panel stays; a note takes the viewer's place. @@ -87,11 +103,13 @@ def test_panel_viewer_is_not_in_its_panel(self, app, name): @pytest.mark.parametrize("name", list(PANE_VIEWS)) def test_fallback_keeps_each_panel_viewer(self, app_off, name): + _prepare(app_off, name) acc = _acc(app_off, name) assert _in(acc, _viewer(app_off, name)) assert not _in(acc, app_off._pv_notes[name][0]) def test_turning_the_workspace_off_puts_viewers_back(self, app): + _prepare(app, "Trajectory") _available(app, "Vibrational") assert claim(app, "Vibrational") app.workspace_layout_cb.value = False diff --git a/tests/test_app_pane_views_steppers.py b/tests/test_app_pane_views_steppers.py new file mode 100644 index 0000000..f5c2bb5 --- /dev/null +++ b/tests/test_app_pane_views_steppers.py @@ -0,0 +1,530 @@ +"""Trajectory, Geometries and PES Scan drive the workspace pane's viewer +(DEC-036: pane viewer, controls in the panel). + +Mirrors ``test_app_pane_views.py``: the viewer moves into the pane with the +"Showing … — Back to structure" banner, the panel keeps a note, and the same +lifecycle (collapse / new result / pick mode → the structure). New here: the +stepper is built in two halves, the viewer for the pane and the controls for +the panel, and a PES-plot click reaches the kernel through a hidden inbox. + +Widget-level checks; the browser side (the pane viewer following the +panel's stepper, a click on a plotted point) needs a Voila look. +""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from quantui.app_pane_views import ( + GEOMETRIES, + PES_PICK_INBOX_CLASS, + PES_SCAN, + TRAJECTORY, + claim, + holder, + show_pes_point, +) +from quantui.molecule import Molecule + +pytest.importorskip("py3Dmol") + +WATER = [[0.0, 0.0, 0.117], [0.0, 0.757, -0.469], [0.0, -0.757, -0.469]] + + +def _water() -> Molecule: + return Molecule(["O", "H", "H"], WATER) + + +def _make_app(tmp_path, monkeypatch, *, workspace: bool = True): + path = tmp_path / "settings.json" + path.write_text( + json.dumps({"_schema_version": 1, "ui": {"workspace_layout": workspace}}) + ) + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(path)) + from quantui.app import QuantUIApp + + return QuantUIApp() + + +@pytest.fixture +def app(tmp_path, monkeypatch): + return _make_app(tmp_path, monkeypatch) + + +@pytest.fixture +def app_off(tmp_path, monkeypatch): + return _make_app(tmp_path, monkeypatch, workspace=False) + + +def _walk(w): + yield w + for c in getattr(w, "children", ()): + yield from _walk(c) + + +def _in(root, widget) -> bool: + return any(w is widget for w in _walk(root)) + + +def _count(root, widget) -> int: + return sum(1 for w in _walk(root) if w is widget) + + +def _html(out) -> str: + return "".join(o["data"]["text/html"] for o in out.outputs) + + +def _acc(app, name): + return app._ana_accordions[app._ana_panel_names.index(name)] + + +def _available(app, *names): + for name in names: + app._activate_ana_panel(name, auto_select=False) + + +def _traj_result(n: int = 3): + frames = [ + Molecule(["H", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.70 + 0.02 * k]]) + for k in range(n) + ] + return SimpleNamespace( + trajectory=frames, + energies_hartree=[-1.0 - 0.01 * k for k in range(n)], + formula="H2", + ) + + +def _pending_trajectory(app, n: int = 3): + """Like a populate step: data waiting for the panel to open.""" + _available(app, TRAJECTORY) + res = _traj_result(n) + app._pending_traj_result = res + app._last_traj_result = res + return res + + +def _geoms(): + return [ + { + "label": "R_neutral — neutral optimized", + "atoms": ["H", "H"], + "coordinates": [[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]], + "note": "E_neutral(R_neutral)", + }, + { + "label": "R_cation — cation optimized", + "atoms": ["H", "H"], + "coordinates": [[0.0, 0.0, 0.0], [0.0, 0.0, 0.80]], + "note": "E_cation(R_cation)", + }, + ] + + +def _with_geometries(app): + from quantui.app_analysis import render_reorg_geometries + + _available(app, GEOMETRIES) + app._reorg_geometries = _geoms() + render_reorg_geometries(app) + + +# --------------------------------------------------------------------------- +# The split builders +# --------------------------------------------------------------------------- + + +class TestViewerParts: + def test_trajectory_halves(self): + from quantui.app_visualization import build_trajectory_viewer_parts + + xyz = ["2\nH2\nH 0 0 0\nH 0 0 0.74", "2\nH2\nH 0 0 0\nH 0 0 0.70"] + parts = build_trajectory_viewer_parts(xyz, formula="H2") + # One fragment for the single-column layout: viewer + stepper. + assert "3dmolviewer_" in parts.combined and "st_play_" in parts.combined + # The pane half has no buttons, and follows the panel's stepper. + assert "3dmolviewer_" in parts.viewer + assert "st_play_" not in parts.viewer + assert "__quantuiStepCur_" in parts.viewer + # The panel half: buttons, slider, label; no viewer of its own. + for el in ("st_prev_", "st_play_", "st_next_", "st_slider_", "st_lbl_"): + assert el in parts.controls + assert '
200)", 1)[1] + assert 'document.getElementById("3dmolviewer_"+UID)' in tail + assert 'window["__quantuiStepCur_"+UID]=cur;' in _STEPPER_JS + + +# --------------------------------------------------------------------------- +# Trajectory +# --------------------------------------------------------------------------- + + +class TestTrajectory: + def test_opening_the_panel_plays_in_the_pane(self, app): + _pending_trajectory(app) + acc = _acc(app, TRAJECTORY) + acc.selected_index = 0 + assert holder(app) == TRAJECTORY + assert app._ws_body.children[0] is app._traj_viewer_output + assert "Trajectory" in app._pv_banner_text.value + # The panel: energy chart and controls stay, the viewer is a note. + assert not _in(acc, app._traj_viewer_output) + assert _in(acc, app._pv_notes[TRAJECTORY][0]) + assert _in(acc, app._traj_controls_output) + assert app._traj_controls_output.layout.display == "" + assert "st_play_" in _html(app._traj_controls_output) + assert "st_play_" not in _html(app._traj_viewer_output) + assert "Step or play it" in app._pv_notes[TRAJECTORY][1].value + # One viewer: the pane's copy is the only one. + assert _count(app._ws_shell, app._traj_viewer_output) == 1 + + def test_controls_hide_while_the_pane_shows_the_structure(self, app): + _pending_trajectory(app) + _acc(app, TRAJECTORY).selected_index = 0 + app._pv_back_btn.click() + assert holder(app) == "" + assert app._ws_body.children[0] is app._ana_viewer_row + assert app._traj_controls_output.layout.display == "none" + # "Show in viewer" brings it (and the controls) back. + note_btn = app._pv_notes[TRAJECTORY][2] + assert note_btn.layout.display == "" + note_btn.click() + assert holder(app) == TRAJECTORY + assert app._traj_controls_output.layout.display == "" + + def test_collapsing_the_panel_releases(self, app): + _pending_trajectory(app) + acc = _acc(app, TRAJECTORY) + acc.selected_index = 0 + acc.selected_index = None + assert holder(app) == "" + assert not _in(app._ws_pane, app._traj_viewer_output) + + def test_rerender_while_in_the_pane_keeps_one_viewer(self, app): + res = _pending_trajectory(app) + acc = _acc(app, TRAJECTORY) + acc.selected_index = 0 + app._show_opt_trajectory(res) # e.g. a theme switch + assert holder(app) == TRAJECTORY + assert app._ws_body.children[0] is app._traj_viewer_output + assert not _in(acc, app._traj_viewer_output) + assert _count(app._ws_shell, app._traj_viewer_output) == 1 + assert _count(acc, app._pv_notes[TRAJECTORY][0]) == 1 + + def test_new_result_gives_the_pane_back_and_drops_the_viewer(self, app): + from quantui.app import _AnalysisContext + + _pending_trajectory(app) + _acc(app, TRAJECTORY).selected_index = 0 + ctx = _AnalysisContext( + calc_type="nmr", formula="H2O", method="RHF", basis="STO-3G" + ) + app._apply_analysis_context(ctx) + assert holder(app) == "" + assert app._ws_body.children[0] is app._ana_viewer_row + assert app._traj_viewer_output.outputs == () + assert app._traj_controls_output.outputs == () + + def test_pick_mode_takes_the_structure_back(self, app): + app._set_molecule(_water()) + _pending_trajectory(app) + _acc(app, TRAJECTORY).selected_index = 0 + app.root_tab.selected_index = app._tab_index("calculate") + app.calc_type_dd.value = "PES Scan" + assert holder(app) == "" + assert claim(app, TRAJECTORY) is False + + def test_another_panel_replaces_it(self, app): + _pending_trajectory(app) + _available(app, "Vibrational") + _acc(app, TRAJECTORY).selected_index = 0 + claim(app, "Vibrational") + assert holder(app) == "Vibrational" + assert not _in(app._ws_pane, app._traj_viewer_output) + assert app._traj_controls_output.layout.display == "none" + + def test_fallback_keeps_the_viewer_with_its_stepper(self, app_off): + _pending_trajectory(app_off) + acc = _acc(app_off, TRAJECTORY) + acc.selected_index = 0 + assert holder(app_off) == "" + assert _in(acc, app_off._traj_viewer_output) + assert "st_play_" in _html(app_off._traj_viewer_output) + assert app_off._traj_controls_output.outputs == () + assert not _in(acc, app_off._pv_notes[TRAJECTORY][0]) + + def test_workspace_toggle_rebuilds_the_halves(self, app): + _pending_trajectory(app) + acc = _acc(app, TRAJECTORY) + acc.selected_index = 0 + app.workspace_layout_cb.value = False + assert holder(app) == "" + assert _in(acc, app._traj_viewer_output) + assert "st_play_" in _html(app._traj_viewer_output) + assert app._traj_controls_output.outputs == () + assert app._traj_controls_output.layout.display == "" + app.workspace_layout_cb.value = True + assert not _in(acc, app._traj_viewer_output) + assert _in(acc, app._pv_notes[TRAJECTORY][0]) + assert "st_play_" not in _html(app._traj_viewer_output) + assert "st_play_" in _html(app._traj_controls_output) + + +# --------------------------------------------------------------------------- +# Geometries (reorganization energy) +# --------------------------------------------------------------------------- + + +class TestGeometries: + def test_opening_the_panel_claims(self, app): + _with_geometries(app) + acc = _acc(app, GEOMETRIES) + acc.selected_index = 0 + assert holder(app) == GEOMETRIES + assert app._ws_body.children[0] is app._reorg_geom_output + assert "Relaxation geometries" in app._pv_banner_text.value + assert "st_ab_" in _html(app._reorg_controls_output) + assert "st_ab_" not in _html(app._reorg_geom_output) + assert app._reorg_controls_output.layout.display == "" + acc.selected_index = None + assert holder(app) == "" + + def test_switching_the_view_claims_and_relabels(self, app): + _with_geometries(app) + app._reorg_view_toggle.value = "overlay" + assert holder(app) == GEOMETRIES + assert "Relaxation overlay" in app._pv_banner_text.value + # The overlay has no stepper. + assert app._reorg_controls_output.outputs == () + app._reorg_view_toggle.value = "step" + assert "Relaxation geometries" in app._pv_banner_text.value + assert "st_ab_" in _html(app._reorg_controls_output) + + def test_populating_does_not_claim(self, app): + app._pv_suppress = True # as while a result is applied + try: + _with_geometries(app) + app._reorg_view_toggle.value = "overlay" + finally: + app._pv_suppress = False + assert holder(app) == "" + + def test_fallback(self, app_off): + _with_geometries(app_off) + acc = _acc(app_off, GEOMETRIES) + app_off._reorg_view_toggle.value = "overlay" + app_off._reorg_view_toggle.value = "step" + assert _in(acc, app_off._reorg_geom_output) + assert "st_ab_" in _html(app_off._reorg_geom_output) + assert app_off._reorg_controls_output.outputs == () + + +# --------------------------------------------------------------------------- +# PES Scan: a click on a point shows its geometry in the pane +# --------------------------------------------------------------------------- + + +def _pes_ready(app, n: int = 4): + _pending_trajectory(app, n) + _available(app, PES_SCAN) + from quantui.app_pane_views import set_pes_linked + + set_pes_linked(app, True) + + +class TestPesScan: + def test_the_note_takes_the_hint_place(self, app, app_off): + acc = _acc(app, PES_SCAN) + assert _in(acc, app._pv_notes[PES_SCAN][0]) + assert not _in(acc, app._pes_plot_hint) + acc_off = _acc(app_off, PES_SCAN) + assert _in(acc_off, app_off._pes_plot_hint) + assert not _in(acc_off, app_off._pv_notes[PES_SCAN][0]) + + def test_opening_the_panel_keeps_the_structure(self, app): + _pes_ready(app) + _acc(app, PES_SCAN).selected_index = 0 + assert holder(app) == "" + + def test_a_click_builds_and_shows_the_point(self, app): + _pes_ready(app) + assert app._traj_viewer_output.outputs == () + app._pv_pes_inbox.value = "2 1700000000000" + assert holder(app) == PES_SCAN + assert app._ws_body.children[0] is app._traj_viewer_output + # Built on the clicked point, though the Trajectory panel never opened. + assert "START=2" in _html(app._traj_viewer_output) + assert "Scan geometry" in app._pv_banner_text.value + assert "PES Scan panel" in app._pv_banner_text.value + assert "Click another point" in app._pv_notes[PES_SCAN][1].value + assert app._traj_controls_output.layout.display == "" + + def test_further_clicks_do_not_rebuild(self, app): + _pes_ready(app) + show_pes_point(app, 1) + first = app._traj_viewer_output.outputs + app._pv_pes_inbox.value = "3 1700000000001" + assert holder(app) == PES_SCAN + assert app._traj_viewer_output.outputs is first + + def test_then_opening_trajectory_keeps_the_same_viewer(self, app): + _pes_ready(app) + show_pes_point(app, 1) + first = app._traj_viewer_output.outputs + _acc(app, TRAJECTORY).selected_index = 0 + assert holder(app) == TRAJECTORY + assert app._ws_body.children[0] is app._traj_viewer_output + assert app._traj_viewer_output.outputs is first + assert _count(app._ws_shell, app._traj_viewer_output) == 1 + + def test_collapsing_the_pes_panel_releases(self, app): + _pes_ready(app) + acc = _acc(app, PES_SCAN) + acc.selected_index = 0 + show_pes_point(app, 0) + acc.selected_index = None + assert holder(app) == "" + + def test_unlinked_profile_hides_the_note(self, app): + from quantui.app_pane_views import set_pes_linked + + _pes_ready(app) + set_pes_linked(app, False) + assert app._pv_notes[PES_SCAN][0].layout.display == "none" + set_pes_linked(app, True) + assert app._pv_notes[PES_SCAN][0].layout.display == "" + + def test_the_inbox_sits_in_the_note(self, app): + assert app._pv_pes_inbox in app._pv_notes[PES_SCAN][0].children + assert PES_PICK_INBOX_CLASS in app._pv_pes_inbox._dom_classes + + def test_garbage_in_the_inbox_is_ignored(self, app): + _pes_ready(app) + app._pv_pes_inbox.value = "not-a-number" + assert holder(app) == "" + + def test_no_pane_without_the_workspace(self, app_off): + _pes_ready(app_off) + assert show_pes_point(app_off, 1) is False + assert holder(app_off) == "" + + def test_new_result_forgets_the_link(self, app): + from quantui.app import _AnalysisContext + + _pes_ready(app) + show_pes_point(app, 1) + ctx = _AnalysisContext( + calc_type="nmr", formula="H2O", method="RHF", basis="STO-3G" + ) + app._apply_analysis_context(ctx) + assert holder(app) == "" + assert app._pv_pes_linked is False + + +class TestPesClickScripts: + def test_1d_profile_posts_the_click(self, app): + from quantui.pes_scan import PESScanResult + + res = PESScanResult( + scan_type="bond", + atom_indices=[0, 1], + scan_parameter_values=[0.7, 0.8, 0.9], + energies_hartree=[-1.0, -1.1, -1.05], + coordinates_list=[], + formula="H2", + method="RHF", + basis="STO-3G", + converged_all=True, + ) + app._show_pes_scan_result(res) + html = _html(app._pes_plot_html) + assert "__quantuiTrajGoTo" in html + assert PES_PICK_INBOX_CLASS in html + assert app._pv_pes_linked is True + + def test_1d_star_carries_its_point_index(self, app): + from quantui.pes_scan import PESScanResult + + res = PESScanResult( + scan_type="bond", + atom_indices=[0, 1], + scan_parameter_values=[0.7, 0.8, 0.9], + energies_hartree=[-1.0, -1.1, -1.05], + coordinates_list=[], + formula="H2", + method="RHF", + basis="STO-3G", + converged_all=True, + ) + app._show_pes_scan_result(res) + star = next(t for t in app._last_pes_fig.data if t.marker.symbol == "star") + # The minimum is scan point 1; a click on the star opens that point. + assert list(star.customdata) == [1] + # Markers without an index (failed points) open nothing. + assert 'typeof pt.customdata!=="number"' in _html(app._pes_plot_html) + + def test_2d_map_posts_the_click(self): + from quantui.pes_scan_2d_plot import click_link_js + + js = click_link_js("quantui-pes-plot", 3) + assert "__quantuiTrajGoTo" in js + assert PES_PICK_INBOX_CLASS in js + assert "Date.now()" in js # a repeat click is a change too diff --git a/tests/test_comparison.py b/tests/test_comparison.py index c14f148..906b95f 100644 --- a/tests/test_comparison.py +++ b/tests/test_comparison.py @@ -197,16 +197,19 @@ def test_contains_gap(self, two_summaries): assert "12.5000" in html assert "13.1000" in html - def test_converged_icon(self, two_summaries): + def test_converged_says_yes(self, two_summaries): + # Words, not emoji (UX-31). html = comparison_table_html(two_summaries) - assert "✅" in html + assert ">Yes" in html + assert "✅" not in html def test_not_converged_icon(self): s = CalcSummary( label="x", formula="H2", method="RHF", basis="STO-3G", converged=False ) html = comparison_table_html([s]) - assert "❌" in html + assert "No" in html + assert "❌" not in html def test_none_converged_dash(self): s = CalcSummary(label="x", formula="H2", method="RHF", basis="STO-3G") diff --git a/tests/test_progress.py b/tests/test_progress.py index dd65456..5d722fe 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -18,7 +18,7 @@ def test_all_steps_start_pending(self): sp = StepProgress(["A", "B"]) html = sp.widget.value # Both should show the pending icon (⬜) - assert html.count("⬜") == 2 + assert html.count("fa-square-o") == 2 def test_widget_is_html(self): import ipywidgets as widgets @@ -47,23 +47,23 @@ def test_start_shows_active_icon(self): sp = StepProgress(["A", "B"]) sp.start(0) html = sp.widget.value - assert "⏳" in html + assert "fa-hourglass-half" in html # Step B still pending - assert "⬜" in html + assert "fa-square-o" in html def test_complete_shows_done_icon(self): sp = StepProgress(["A", "B"]) sp.start(0) sp.complete(0) html = sp.widget.value - assert "✅" in html + assert "fa-check-circle" in html def test_fail_shows_fail_icon(self): sp = StepProgress(["A", "B"]) sp.start(0) sp.fail(0) html = sp.widget.value - assert "❌" in html + assert "fa-times-circle" in html def test_complete_with_message(self): sp = StepProgress(["A"]) @@ -92,8 +92,8 @@ def test_multi_step_workflow(self): sp.complete(1, "OK") sp.start(2) html = sp.widget.value - assert html.count("✅") == 2 - assert html.count("⏳") == 1 + assert html.count("fa-check-circle") == 2 + assert html.count("fa-hourglass-half") == 1 def test_reset_returns_all_to_pending(self): sp = StepProgress(["A", "B"]) @@ -102,9 +102,9 @@ def test_reset_returns_all_to_pending(self): sp.start(1) sp.reset() html = sp.widget.value - assert html.count("⬜") == 2 - assert "✅" not in html - assert "⏳" not in html + assert html.count("fa-square-o") == 2 + assert "fa-check-circle" not in html + assert "fa-hourglass-half" not in html class TestStepProgressEdgeCases: @@ -114,13 +114,13 @@ def test_single_step(self): sp = StepProgress(["Only step"]) sp.start(0) sp.complete(0) - assert "✅" in sp.widget.value + assert "fa-check-circle" in sp.widget.value def test_empty_message_ok(self): sp = StepProgress(["A"]) sp.complete(0, "") # Empty message should not crash - assert "✅" in sp.widget.value + assert "fa-check-circle" in sp.widget.value def test_html_special_chars_in_message(self): sp = StepProgress(["A"]) diff --git a/tests/test_theme_contrast.py b/tests/test_theme_contrast.py index a62d51e..930eeee 100644 --- a/tests/test_theme_contrast.py +++ b/tests/test_theme_contrast.py @@ -304,6 +304,7 @@ def test_the_standalone_export_is_left_unframed(self): ("app_builders.py", "app.viz_output"), ("app_builders.py", "app.preopt_preview_output"), ("app_builders.py", "app.vib_output"), + ("app_builders.py", "app._traj_viewer_output"), ("app_visualization.py", "viewer_output"), ], ) @@ -559,3 +560,14 @@ def test_no_migrated_value_appears_as_a_raw_literal(self): assert offenders == [], ( "raw hex reintroduced where a theme.py token exists: " f"{offenders}" ) + + +def test_slider_rules_do_not_mix_engine_pseudo_elements(): + """A selector list with both ::-webkit-* and ::-moz-* is invalid as a + whole, so the browser drops the rule (the scrubber track vanished).""" + css = theme.slider_chrome_css() + for rule in css.split("}"): + selector = rule.split("{")[0] + assert not ("::-webkit-" in selector and "::-moz-" in selector), selector + assert "input.quantui-range[type=range]::-webkit-slider-runnable-track" in css + assert ".widget-slider input[type=range]::-webkit-slider-thumb" in css diff --git a/tests/test_ux_backlog_polish.py b/tests/test_ux_backlog_polish.py new file mode 100644 index 0000000..b4f2c62 --- /dev/null +++ b/tests/test_ux_backlog_polish.py @@ -0,0 +1,621 @@ +"""UX backlog polish for 0.15.0 (UI/UX review 2026-12-05, DEC-036). + +Menu reasons shown inline (UX-22), icons instead of emoji (UX-31), theme +colours in plots and run boxes (UX-32), themed scrollbars and selection, +flatter nested boxes, instant run feedback (UX-34) and accessible names for +icon-only controls. + +The browser side (how the lines look, what a screen reader says) needs a +human check; these tests pin the widget state, the CSS and the page script. +""" + +from __future__ import annotations + +import pathlib +import re + +import pytest + +from quantui import app_menubar as mb +from quantui import theme + +PKG = pathlib.Path(theme.__file__).parent + + +@pytest.fixture +def app(tmp_path, monkeypatch): + monkeypatch.setenv("QUANTUI_SETTINGS_PATH", str(tmp_path / "settings.json")) + from quantui.app import QuantUIApp + + return QuantUIApp() + + +def _hex_rgb(h: str) -> tuple: + h = h.lstrip("#") + if len(h) == 3: + h = "".join(c * 2 for c in h) + return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4)) + + +def _lum(c: tuple) -> float: + def ch(v: int) -> float: + s = v / 255 + return s / 12.92 if s <= 0.03928 else ((s + 0.055) / 1.055) ** 2.4 + + r, g, b = (ch(x) for x in c) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + +def _ratio(fg: str, bg: str) -> float: + a, b = _lum(_hex_rgb(fg)), _lum(_hex_rgb(bg)) + return (max(a, b) + 0.05) / (min(a, b) + 0.05) + + +# --------------------------------------------------------------------------- +# UX-22: the reason under an unavailable menu item +# --------------------------------------------------------------------------- + + +class TestMenuReasons: + def test_disabled_item_shows_its_reason_line(self, app): + mb.open_menu(app, "Calculate") + _item, btn = app._mb_items["run"] + line = app._mb_reasons["run"] + assert btn.disabled + assert line.layout.display == "" + assert "Load a molecule first" in line.value + assert f'id="{mb.reason_id("run")}"' in line.value + assert mb.MENU_REASON_TEXT_CLASS in line.value + # The tooltip stays too. + assert btn.tooltip.startswith("Unavailable: ") + + def test_enabled_item_has_no_reason_line(self, app): + mb.open_menu(app, "Calculate") + btn = app._mb_items["setup_dialog"][1] + line = app._mb_reasons["setup_dialog"] + assert not btn.disabled + assert line.layout.display == "none" + assert line.value == "" + + def test_reason_line_follows_its_item(self, app): + lst = app._mb_lists["Calculate"] + kids = list(lst.children) + btn = app._mb_items["run"][1] + assert kids[kids.index(btn) + 1] is app._mb_reasons["run"] + + def test_reason_clears_when_item_becomes_available(self, app): + mb.open_menu(app, "Calculate") + assert app._mb_reasons["run"].layout.display == "" + app.run_btn.disabled = False # observer refreshes the open menu + assert app._mb_reasons["run"].layout.display == "none" + assert not app._mb_items["run"][1].disabled + + def test_reason_text_is_escaped(self): + html = mb.reason_html("x", "&") + assert "<b>&" in html + + def test_reason_id_is_a_valid_dom_id(self): + assert mb.reason_id("ana panel/1") == "quantui-mr-ana-panel-1" + + def test_css_styles_the_line_with_a_text_token(self): + assert f".{mb.MENU_REASON_CLASS}" in mb.MENUBAR_CSS + token = mb.MENU_REASON_TOKEN.replace("_", "-") + assert f"color: var(--q-{token}) !important" in mb.MENUBAR_CSS + # Not faded like the disabled item itself. + rule = mb.MENUBAR_CSS[mb.MENUBAR_CSS.index(f".{mb.MENU_REASON_CLASS} {{") :] + rule = rule[: rule.index("}")] + assert "opacity" not in rule + + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + def test_reason_line_contrast_on_menu_background(self, palette_id): + p = theme.get_palette(palette_id) + fg = getattr(p, mb.MENU_REASON_TOKEN) + # The drop-down list sits on bg_panel. + assert _ratio(fg, p.bg_panel) >= 4.5, palette_id + + def test_page_script_links_reason_as_description(self): + from quantui import app_a11y + + js = app_a11y.a11y_js() + assert f".{mb.MENU_REASON_CLASS}" in js + assert '"aria-describedby"' in js + assert "__REASON__" not in js + + +# --------------------------------------------------------------------------- +# UX-32: theme colours in run boxes, the live log and plot traces +# --------------------------------------------------------------------------- + +# (box surface, text tokens drawn on it) +ALERT_PAIRS = { + "error": ("surface_error_bg", ("accent_error", "text_body", "text_strong")), + "warning": ("surface_warning_bg", ("accent_warning", "text_body")), + "info": ("surface_info_bg", ("accent_info", "text_body", "text_strong")), +} +# Colours the run log (QuantUIApp._render_log) draws text in, on bg_panel. +LOG_TEXT_TOKENS = ( + "text_heading", + "text_body", + "text_strong", + "text_slate", + "text_slate_dark", + "text_subtle", + "accent_info", + "accent_purple", + "accent_teal", + "accent_success", + "accent_warning", + "accent_error", +) + + +class TestAlertBoxes: + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + @pytest.mark.parametrize("kind", sorted(ALERT_PAIRS)) + def test_box_text_clears_aa(self, palette_id, kind): + p = theme.get_palette(palette_id) + bg, fgs = ALERT_PAIRS[kind] + for fg in fgs: + ratio = _ratio(getattr(p, fg), getattr(p, bg)) + assert ratio >= 4.5, f"{palette_id}: {fg} on {bg} {ratio:.2f}:1" + + def test_error_surface_is_a_css_variable(self): + block = theme.theme_css_block("Dark") + assert "--q-surface-error-bg: #450a0a" in block + assert theme.css.SURFACE_ERROR_BG == "var(--q-surface-error-bg)" + + @pytest.mark.parametrize("kind", sorted(ALERT_PAIRS)) + def test_style_uses_tokens_only(self, kind): + style = theme.alert_box_style(kind) + assert "#" not in style + assert "var(--q-surface-" in style + assert "var(--q-text-body)" in style + + LIGHT_ONLY = re.compile( + r"#(fef2f2|fca5a5|7f1d1d|991b1b|fffbeb|fcd34d|92400e|fffbe6|fff5f5" + r"|d32f2f|eff6ff|93c5fd|0366d6|1e3a5f|6d28d9|1d4ed8|0f766e|d97706" + r"|0891b2|166534|374151)(?![0-9a-fA-F])", + re.IGNORECASE, + ) + + @pytest.mark.parametrize( + "name", + [ + "app.py", + "app_slurm.py", + "app_runflow.py", + "help_content.py", + "backends/slurm_errors.py", + ], + ) + def test_no_light_only_box_or_log_colours(self, name): + text = (PKG / name).read_text(encoding="utf-8") + assert self.LIGHT_ONLY.findall(text) == [], name + + def test_failed_and_cancelled_boxes_use_tokens(self): + src = (PKG / "app.py").read_text(encoding="utf-8") + for title in ( + "⚠ Calculation Failed", + "■ Calculation cancelled", + "⚠ Result NOT saved", + "⚠ Dependency Not Available", + ): + i = src.index(title) + window = src[max(0, i - 400) : i] + assert "alert_box_style(" in window, title + + def test_slurm_error_panel_is_themed(self): + from quantui.backends.slurm_errors import format_error_html + + html = format_error_html("SCF not converged") + assert "var(--q-surface-error-bg)" in html + assert "fa-times-circle" in html + + +class TestLogColours: + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + @pytest.mark.parametrize("token", LOG_TEXT_TOKENS) + def test_log_text_on_panel(self, palette_id, token): + p = theme.get_palette(palette_id) + ratio = _ratio(getattr(p, token), p.bg_panel) + assert ratio >= 4.5, f"{palette_id}: {token} {ratio:.2f}:1" + + def test_render_log_uses_only_tokens(self, app): + app._render_log( + "=" * 50 + + "\n ✗ failed\n Molecule: H2O\n Energy: -76\n" + + "Warning: x\nError here\nMO energies\n occupied: 1\n" + + "E(MP2) = 1\n── Final SCF\n" + ) + html = app._log_output_html.value + colours = re.findall(r"color:([^;\"]+)", html) + assert colours and all(c.startswith("var(--q-") for c in colours), colours + + +class TestPlotDataColours: + @pytest.mark.parametrize("name", sorted(theme.PLOT_DATA_COLORS)) + @pytest.mark.parametrize("palette_id", theme.PALETTE_IDS) + def test_trace_colour_keeps_3_to_1(self, name, palette_id): + colour = theme.PLOT_DATA_COLORS[name] + p = theme.get_palette(palette_id) + tc = theme.plotly_colors(palette_id) + for bg in (p.bg_panel, p.page_bg, tc["scene_bgcolor"]): + ratio = _ratio(colour, bg) + assert ratio >= 3.0, f"{name} on {palette_id} {bg}: {ratio:.2f}:1" + + # Literal colours still allowed in the plot modules: the PES minimum star + # (gold, outlined) and the white grid-point markers on the 2-D heatmap. + ALLOWED = {"ca8a04", "1c1915", "1f2937"} + PLOT_MODULES = ( + "ecd_plot.py", + "ir_plot.py", + "mulliken_plot.py", + "nmr_plot.py", + "pes_scan_2d_plot.py", + "raman_plot.py", + "comparison.py", + ) + + @pytest.mark.parametrize("name", PLOT_MODULES) + def test_plot_modules_take_colours_from_the_theme(self, name): + text = (PKG / name).read_text(encoding="utf-8") + found = { + m.group(1).lower() + for m in re.finditer(r"(?= 3.0 + assert _ratio(p.page_bg, p.accent_info) >= 4.5 + + +class TestNestedBoxes: + def test_inner_tab_panel_loses_its_frame(self): + css = theme.nested_box_css() + assert css in theme._widget_chrome_css() + for sel in theme.NESTED_TAB_SELECTORS: + assert sel in css + # Only a tab panel inside another tab's panel. + assert sel.startswith(".widget-tab-contents ") + assert "border: none" in css + assert "background: transparent" in css + # The tabs still read as a group: one line under the tab bar. + assert "border-top: 1px solid var(--q-border)" in css + + def test_overrides_the_general_panel_rule(self): + chrome = theme._widget_chrome_css() + assert chrome.index(theme.nested_box_css()) > chrome.index( + ".widget-tab-contents " + ) + + def test_molecule_input_is_a_tab_inside_the_root_tab(self, app): + import ipywidgets as widgets + + def walk(w): + yield w + for c in getattr(w, "children", ()): + yield from walk(c) + + inner = [ + w + for w in walk(app.root_tab) + if isinstance(w, widgets.Tab) and w is not app.root_tab + ] + assert inner, "expected a nested tab set (Molecule Input)" + + +# --------------------------------------------------------------------------- +# UX-34: instant feedback on Run +# --------------------------------------------------------------------------- + + +def _water(): + from quantui.molecule import Molecule + + return Molecule( + ["O", "H", "H"], + [[0.0, 0.0, 0.117], [0.0, 0.757, -0.469], [0.0, -0.757, -0.469]], + ) + + +@pytest.fixture +def water_app(app): + app._set_molecule(_water()) + app.method_dd.value = "RHF" + app.basis_dd.value = "STO-3G" + return app + + +class TestInstantRunFeedback: + def test_click_shows_starting_before_the_worker_runs(self, water_app): + from unittest.mock import patch + + from quantui import app_runflow as rf + from quantui.app_workspace import job_state + + app = water_app + seen = {} + + def worker(): + # What the page shows the moment the worker thread starts. + seen["button"] = (app.run_btn.disabled, app.run_btn.description) + seen["icon"] = app.run_btn.icon + seen["status"] = app.run_status.value + seen["job"] = job_state(app) + seen["chip"] = app._activity_btn.value + + with patch.object(app, "_run_in_thread", side_effect=worker): + app._on_run_clicked(None) + import time + + time.sleep(0.2) + assert seen["button"] == (True, rf.RUN_STARTING_LABEL) + assert seen["icon"] == rf.RUN_BUSY_ICON + assert seen["status"] == "Starting…" + assert seen["job"] == ("starting", "Starting…") + assert "Starting…" in seen["chip"] + assert rf.RUN_BUSY_CLASS in app.run_btn._dom_classes + + def test_click_is_announced_politely(self, water_app): + from unittest.mock import patch + + from quantui import app_a11y + + app = water_app + region = app_a11y.build_live_region(app) # built in display() + with patch.object(app, "_run_in_thread"): + app._on_run_clicked(None) + assert "Starting the calculation" in region.value + + def test_worker_hands_over_to_the_running_state(self, water_app): + from quantui import app_runflow as rf + from quantui.app_workspace import job_state + + app = water_app + rf.mark_run_starting(app) + app._begin_run_lock() + rf.mark_run_running(app) + assert app.run_btn.description == rf.RUN_RUNNING_LABEL + assert job_state(app)[0] == "running" + assert "Running" in app._ws_footer.value + + def test_end_of_run_restores_the_button(self, water_app): + from quantui import app_runflow as rf + + app = water_app + idle = (app.run_btn.description, app.run_btn.icon) + rf.mark_run_starting(app) + app._begin_run_lock() + rf.mark_run_running(app) + app._end_run_lock() + assert not app.run_btn.disabled + assert (app.run_btn.description, app.run_btn.icon) == idle + assert rf.RUN_BUSY_CLASS not in app.run_btn._dom_classes + + def test_validation_failure_restores_the_button(self, water_app): + from unittest.mock import patch + + from quantui.app_workspace import job_state + + app = water_app + idle = (app.run_btn.description, app.run_btn.icon) + with ( + patch( + "quantui.inorganic_guards.preflight_messages", + return_value=["No basis for Xx"], + ), + patch.object(app, "_run_in_thread") as worker, + ): + app._on_run_clicked(None) + assert worker.call_count == 0 + assert not app.run_btn.disabled + assert (app.run_btn.description, app.run_btn.icon) == idle + assert job_state(app)[0] == "idle" + assert "Adjust the settings" in app.run_status.value + + def test_error_in_validation_still_restores_the_button(self, water_app): + from unittest.mock import patch + + app = water_app + with ( + patch("quantui.app_runflow._start_run", side_effect=RuntimeError("boom")), + pytest.raises(RuntimeError), + ): + from quantui.app_runflow import on_run_clicked + + on_run_clicked(app, None) + assert not app.run_btn.disabled + assert not app._run_starting + + def test_worker_that_fails_early_restores_the_button(self, water_app): + from unittest.mock import patch + + from quantui import app_runflow as rf + + app = water_app + idle = app.run_btn.description + rf.mark_run_starting(app) + app._begin_run_lock() + with patch.object(app, "_do_run", side_effect=OSError(28, "disk full")): + app._run_in_thread() + assert not app.run_btn.disabled + assert app.run_btn.description == idle + assert not app._run_starting + + def test_busy_style_outranks_the_disabled_style(self): + from quantui.app import _APP_CSS + + assert "button.jupyter-button.mod-success.quantui-run-busy:disabled" in _APP_CSS + assert "cursor: progress" in _APP_CSS + + +# --------------------------------------------------------------------------- +# Accessible names for icon-only buttons and unlabelled fields +# --------------------------------------------------------------------------- + + +def _app_roots(app): + import ipywidgets as widgets + + roots = [] + for v in vars(app).values(): + if isinstance(v, widgets.Widget): + roots.append(v) + elif isinstance(v, (list, tuple)): + roots += [x for x in v if isinstance(x, widgets.Widget)] + elif isinstance(v, dict): + roots += [x for x in v.values() if isinstance(x, widgets.Widget)] + return roots + + +class TestAccessibleNames: + def test_every_built_control_can_be_named(self, app): + from quantui.app_a11y import unnamed_controls + + names = {id(v): k for k, v in vars(app).items()} + bad = [ + f"{names.get(id(w), type(w).__name__)}: {why}" + for w, why in unnamed_controls(_app_roots(app)) + ] + assert bad == [] + + def test_after_a_molecule_loads_too(self, app): + from quantui.app_a11y import unnamed_controls + + app._set_molecule(_water()) + assert unnamed_controls(_app_roots(app)) == [] + + def test_the_scan_catches_unnamed_controls(self): + import ipywidgets as widgets + + from quantui.app_a11y import unnamed_controls + + box = widgets.VBox( + [ + widgets.Button(icon="refresh"), + widgets.Button(description="?"), + widgets.Button(description="?", tooltip="Help on methods"), + widgets.Button(description="Run"), + widgets.Dropdown(options=["a"]), + widgets.Dropdown(options=["a"], tooltip="Format"), + widgets.ToggleButtons(options=["▶", "Stop"]), + widgets.Text(placeholder="search name or formula"), + widgets.Textarea(), + ] + ) + bridge = widgets.Textarea() + bridge.add_class("quantui-orb-png-inbox") + box.children = (*box.children, bridge) + found = unnamed_controls([box]) + # refresh icon, "?", bare Dropdown, "▶" option, bare Textarea. + assert len(found) == 5, found + + def test_bridge_fields_leave_the_tab_order(self): + from quantui import app_a11y + + js = app_a11y.a11y_js() + assert '[class$="-inbox"] textarea' in js + assert '"tabindex","-1"' in js + + def test_help_buttons_have_a_tooltip_for_their_name(self, app): + helps = [ + w + for k, w in vars(app).items() + if k.endswith("_help_btn") and hasattr(w, "description") + ] + assert helps + for w in helps: + assert w.tooltip.strip(), w + + def test_page_script_names_icon_buttons_from_tooltips(self): + from quantui import app_a11y + + js = app_a11y.a11y_js() + assert "iconNames()" in js + assert 'setAttribute("aria-label", tip)' in js + assert "GLYPH" in js + + def test_atom_table_fields_are_named(self, app): + import ipywidgets as widgets + + from quantui.app_a11y import _walk_widgets + + tips = { + w.tooltip + for w in _walk_widgets(_app_roots(app)) + if isinstance(w, (widgets.FloatText, widgets.Text)) and w.tooltip + } + assert {"Element symbol", "x coordinate (Å)", "z coordinate (Å)"} <= tips + + +def test_long_menus_scroll_inside_their_frame(): + # The bar's overflow:visible rule (0,2,0) used to outrank the list's own + # overflow, so a long Results menu spilled past its frame (headless + # Voilà check, 2026-12-06). + css = mb.MENUBAR_CSS + rule = f".{mb.MENUBAR_CLASS} .widget-box.{mb.MENU_LIST_CLASS} {{" + assert rule in css + body = css[css.index(rule) :] + body = body[: body.index("}")] + assert "overflow-y: auto !important" in body + assert css.index(rule) > css.index(f".{mb.MENUBAR_CLASS} .widget-box {{") diff --git a/tests/test_uxrev_polish.py b/tests/test_uxrev_polish.py index 86fad31..5c8a37d 100644 --- a/tests/test_uxrev_polish.py +++ b/tests/test_uxrev_polish.py @@ -133,21 +133,30 @@ def test_labels_do_not_wrap_and_no_side_stripe(self, app): class TestIconsNotEmoji: - # Colour emoji used as status icons in the app's own UI modules (UX-31). - # (molecule.py / pubchem.py error texts are left to the XYZ-error work.) - FILES = ( - "app_formatters.py", - "app_builders.py", - "app_runflow.py", - "app_visualization.py", - "app_slurm.py", - "visualization_py3dmol.py", - "orbital_visualization.py", - "app.py", + # Colour emoji used as status icons (UX-31). 0.14 covered the app's own + # UI modules; 0.15 extends this to every module in the package + # (molecule.py XYZ errors, pubchem.py, comparison.py, the Slurm error + # panel, run summaries). Text-style glyphs (check marks, the warning + # triangle without VS16) are not colour emoji and stay. + FILES = tuple( + sorted( + p.relative_to(PKG).as_posix() + for p in PKG.rglob("*.py") + if "__pycache__" not in p.parts + ) ) # (The plain arrow glyph on the viewers' Save PNG buttons stays: those # buttons also live in standalone exports, which have no icon font.) - EMOJI = re.compile("[\U0001f300-\U0001faff\u23f3\u2705\u274c]") + # Characters that render as colour emoji by default (Emoji_Presentation), + # plus the VS16 selector that turns a text glyph (ℹ, ⚠) into emoji. + EMOJI = re.compile( + "[\U0001f300-\U0001faff\u231a\u231b\u23e9-\u23ec\u23f0\u23f3" + "\u25fd\u25fe\u2614\u2615\u2648-\u2653\u267f\u2693\u26a1" + "\u26aa\u26ab\u26bd\u26be\u26c4\u26c5\u26ce\u26d4\u26ea" + "\u26f2\u26f3\u26f5\u26fa\u26fd\u2705\u270a\u270b\u2728" + "\u274c\u274e\u2753-\u2755\u2757\u2795-\u2797\u27b0\u27bf" + "\u2b1b\u2b1c\u2b50\u2b55\ufe0f]" + ) @pytest.mark.parametrize("name", FILES) def test_no_status_emoji_in_string_literals(self, name): diff --git a/tests/test_viz_low_audit.py b/tests/test_viz_low_audit.py index b9571ea..45ab7a7 100644 --- a/tests/test_viz_low_audit.py +++ b/tests/test_viz_low_audit.py @@ -400,6 +400,8 @@ def boom(*a, **k): raise RuntimeError(_EVIL) monkeypatch.setattr(av, "build_trajectory_viewer_html", boom) + # The on-screen viewer is built in parts (pane + panel halves). + monkeypatch.setattr(av, "build_trajectory_viewer_parts", boom) app = Mock() app._traj_render_token = 0 app._plotly_theme_colors.return_value = {"scene_bgcolor": "white"}