Skip to content

Docs code transformation callables - #68

Closed
evnchn wants to merge 14 commits into
DONOTMERGEfrom
docs-code-transformation-callables
Closed

evnchn wants to merge 14 commits into
DONOTMERGEfrom
docs-code-transformation-callables

Conversation

@evnchn

@evnchn evnchn commented Feb 8, 2026

Copy link
Copy Markdown
Owner

This pull request introduces a modular system for transforming demo code before it is displayed in documentation. The changes enable demos to use "fake" objects and patterns for execution, while displaying standardized code to users. The main improvements include the addition of code transformers, integration of these transformers into demo decorators and rendering, and the creation of a pipeline for sub_pages-related demos. The PR also adds comprehensive tests for the new code transformation logic.

Modular code transformation for demo display:

  • Added a suite of code transformers (replace_fake_links, replace_fake_sub_pages, remove_fake_init, remove_fake_imports, replace_fake_arguments, wrap_in_root, make_replacer) in code_extraction.py, along with the new get_display_code function to apply them. This allows demos to use internal/fake objects for execution while displaying standardized code to users.
  • Introduced _SUB_PAGES_TRANSFORMS pipeline in sub_pages_documentation.py for sub_pages demos, ensuring display code uses ui.sub_pages, ui.link, and wraps top-level statements in a root() function.

Integration with demo system and rendering:

  • Added code_transformers parameter to demo decorators and the Demo dataclass, enabling demos to specify custom transformation pipelines for their display code. [1] [2] [3] [4]
  • Updated demo rendering logic in demo.py and rendering.py to use get_display_code with the specified code transformers, ensuring transformed code is shown in documentation. [1] [2]

Documentation and test enhancements:

  • Refactored sub_pages documentation demos to use the new transformer pipeline, removing manual code hiding and display logic. [1] [2] [3] [4]
  • Added extensive unit tests for each transformer and the full pipeline in test_code_extraction.py, ensuring correctness and robustness of the new transformation system.

API improvements and refactoring:

  • Modified get_full_code to support disabling line uncommenting when transformers are used, improving compatibility with the new transformation pipeline. [1] [2]
  • Updated imports and refactored demo signatures across files to use the new transformer-based system. [1] [2]

These changes make demo code display more flexible, maintainable, and consistent across documentation.

evnchn and others added 3 commits February 8, 2026 09:21
Introduce a system of composable Callable[[str], str] transformers for
documentation demos.  Each transformer handles one concern (e.g. replacing
FakeSubPages with ui.sub_pages, replacing fake links, wrapping code in a
root function).  Demos can specify code_transformers to convert execution
code into clean display code without the previous comment-duplication
pattern.

- Add code_transformers field to Demo dataclass
- Thread code_transformers through doc.demo() API, rendering, and demo.py
- Add get_full_code(uncomment=) parameter for transformer-based demos
- Implement replace_fake_links, replace_fake_sub_pages, remove_fake_init,
  remove_fake_imports, replace_fake_arguments, wrap_in_root transformers

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Convert 4 sub_pages demos (main_demo, parameters_demo,
path_changed_event_demo, async_demo) from the comment-duplication
pattern to the new code_transformers approach. Each demo is now
written once as clean execution code, and transformers convert it
to display code automatically.

- Add get_display_code() helper and make_replacer() factory
- Use get_display_code in demo.py and search.py
- Define _SUB_PAGES_TRANSFORMS pipeline for standard sub_pages demos
- Keep complex demos (url_parameters, page_arguments, wildcard,
  nested, error_handling, adding_sub_pages) in old style where
  display code differs structurally from execution code

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Test each transformer individually and the full pipeline:
- replace_fake_links, replace_fake_sub_pages, remove_fake_init
- remove_fake_imports, replace_fake_arguments
- make_replacer factory, wrap_in_root structural transformer
- get_display_code with and without transformers
- Full pipeline integration test

Co-Authored-By: Claude Opus 4.6 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a transformer-based pipeline for turning “execution” demo code into standardized “display” code in the documentation, and wires that into both rendering and search indexing.

Changes:

  • Introduces get_display_code plus a set of modular code transformers in website/documentation/code_extraction.py.
  • Extends the documentation demo metadata/decorators to carry code_transformers, and updates rendering/search indexing to use transformed display code.
  • Refactors sub_pages documentation demos to use a shared transformer pipeline and adds unit tests for the transformation behavior.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
website/documentation/search.py Search index now includes transformed demo display code via get_display_code.
website/documentation/rendering.py Demo rendering passes code_transformers through to the demo renderer.
website/documentation/demo.py Demo renderer uses get_display_code instead of raw extraction.
website/documentation/content/sub_pages_documentation.py Adds a shared transformer pipeline for sub_pages demos and applies it to selected demos.
website/documentation/content/doc/part.py Extends Demo metadata with code_transformers.
website/documentation/content/doc/api.py Updates doc.demo(...) API/overloads to accept code_transformers and stores it in Demo.
website/documentation/code_extraction.py Adds transformer utilities and get_display_code; updates get_full_code to support non-uncommented extraction.
tests/test_code_extraction.py Adds unit tests for each transformer and basic pipeline behavior.

Comment thread tests/test_code_extraction.py Resolved
- Fix mutable default argument in FakeSubPages.__init__: change
  data={} to data=None with data or {} in body
- Fix remove_fake_imports to preserve co-located imports on the same
  line (e.g. "from x import FakeSubPages, RealThing" keeps RealThing)
- Remove noqa suppression in test by using print() instead of unused
  variable assignment
- Add test_remove_fake_imports_preserves_colocated test

Co-Authored-By: Claude Opus 4.6 <[email protected]>
evnchn and others added 10 commits February 8, 2026 19:02
…d Chrome (zauberzeug#5740)

### Motivation

The `ubuntu-latest` runner image already ships with matched Chrome and
ChromeDriver versions ([runner-images
manifest](https://github.com/actions/runner-images/blob/ubuntu24/20260201.15/images/ubuntu/Ubuntu2404-Readme.md)).
The third-party `nanasess/[email protected]` action is redundant
and introduces a point of fragility: when Chrome auto-updates on the
runner image, the action may install a mismatched or conflicting
ChromeDriver version, causing test failures unrelated to any code
change.

This issue materialized on Feb 8, 2026, when Chrome auto-updated from
`144.0.7559.96` to `144.0.7559.109` on the runner image. The update
caused 4 test failures and 1 error across multiple unrelated PRs:

| Test | Error |
|------|-------|
| `test_page::test_exception` | `AssertionError: Could not find "500"` |
| `test_select::test_add_new_values[add-False-True]` | `IndexError: pop
from empty list` |
| `test_select::test_add_new_values[add-True-True]` | `IndexError: pop
from empty list` |
| `test_storage::test_missing_storage_secret` | `IndexError: pop from
empty list` |
| `test_page::test_exception_after_connected` | JS `RangeError: Maximum
call stack size exceeded` |

These failures appeared identically on two completely unrelated PRs
([#68](#68),
[#71](#71)), confirming they
are environment-caused, not code-caused. Upstream last ran CI on Feb 5
with Chrome `.96` (passing); the next CI run will encounter the same
failures.

### Implementation

Remove the `nanasess/[email protected]` step from
`.github/workflows/_test.yml`. The runner image's preinstalled Chrome
and ChromeDriver are used instead.

This is the most maintainable approach because:
- The runner image always ships a matched Chrome + ChromeDriver pair
- If the preinstalled Chrome breaks, it affects the entire GitHub
Actions ecosystem, guaranteeing rapid upstream fixes from
GitHub/Microsoft
- No third-party action to maintain, audit, or pin versions for
- One fewer network fetch during CI (the action downloads ChromeDriver
on every run)

### Alternatives explored

Five approaches were tested on
[evnchn/nicegui](https://github.com/evnchn/nicegui) to triangulate the
root cause and find the best fix:

| PR | Approach | Result | Trade-off |
|----|----------|--------|-----------|
| [#72](#72) | Pin
Chrome+ChromeDriver to `.96` via `browser-actions/setup-chrome@v2` |
**All 769 tests pass** | Requires manual version bumps; masks Chrome
regressions |
| [#73](#73) | Pin ChromeDriver
only to `.96` via `nanasess` with `chromedriver-version` | **All 769
tests pass** | Same pinning burden; still depends on third-party action
|
| [#74](#74) | ARM64 runner
(`ubuntu-24.04-arm`) + Chromium via apt | **3 failures**, 769 passed |
8% slower pytest (24m06s vs 22m18s), +93s Chromium install overhead, new
platform-specific test failures (`test_upload` file path bug,
`test_xterm` terminal size mismatch) |
| [#75](#75) | Remove `nanasess`,
use preinstalled Chrome | **All 769 tests pass** | **This approach** —
zero maintenance, zero overhead |

### Timing comparison (PR #75 vs PR #74)

| | PR #75 x86_64 (this approach) | PR #74 ARM64 |
|---|---|---|
| Chrome install | 0s (preinstalled) | 93s (apt-get) |
| pytest duration | 22m 18s | 24m 06s |
| Total job wall-clock | 22m 30s | 25m 56s |
| Test result | **769 passed** | 3 failed, 769 passed |

### Root cause analysis

- Chrome auto-updated from `144.0.7559.96` to `144.0.7559.109` between
Feb 6 and Feb 8 on the `ubuntu-latest` runner image
- All Python dependencies are identical across passing and failing runs
(`selenium==4.40.0`, `cpython-3.10.19`)
- Chromium commit log between `.97` and `.110` contains only
Chrome-internal changes (contextual tasks UI, i18n, Android GPU, sandbox
policy, translation, PDF, PKI metadata) — no V8, CSS, WebDriver, or
networking changes
- The behavioral regression in `.109` is likely in a rolled dependency
(via DEPS) rather than a direct Chromium commit
- Removing `nanasess` resolves the issue because the runner image's
preinstalled Chrome `.109` and its matched ChromeDriver work correctly
together — the problem was the version mismatch introduced by the action

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] If this PR addresses a security issue, it has been coordinated via
the [security
advisory](https://github.com/zauberzeug/nicegui/security/advisories/new)
process.
- [x] Pytests have been added (or are not necessary).
- [x] Documentation has been added (or is not necessary).

Co-authored-by: Claude Opus 4.6 <[email protected]>
Tests that import from the `website/` package trigger the
documentation module chain, which auto-executes a demo that
registers a custom @app.on_page_exception handler. Since
App.reset() did not clear _page_exception_handler, this handler
leaked across the entire test session, causing 4 failures + 1 error
in test_page, test_select, and test_storage.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
### Motivation

The `sqlite_database` example breaks with Tortoise ORM 1.0:

```
RuntimeError: No TortoiseContext is currently active.
Use 'async with TortoiseContext() as ctx:' to create one, or call Tortoise.init() for global state.
```

Tortoise ORM 1.0 replaced global state with a `ContextVar`-based
architecture. Since NiceGUI runs async `on_startup` handlers as
background tasks (via `safe_invoke` / `background_tasks.create`), the
`ContextVar` set by `Tortoise.init()` in the startup task never
propagates to request handler tasks.

Additionally, `aiosqlite` was pinned to 0.21.0 to work around
[tortoise/tortoise-orm#2037](tortoise/tortoise-orm#2037),
and the example was skipped in CI for Python 3.11/3.12 due to
[omnilib/aiosqlite#241](omnilib/aiosqlite#241).
Both issues are resolved in Tortoise ORM 1.0.

### Implementation

Replace the manual `Tortoise.init()` / `close_connections()` /
`on_startup` / `on_shutdown` boilerplate with `register_tortoise()` from
`tortoise.contrib.fastapi`. Since NiceGUI's `app` is a FastAPI subclass,
this hooks directly into the app's lifespan and uses
`_enable_global_fallback=True` internally, making the Tortoise context
available across all async tasks.

This also removes the `aiosqlite` pin and the CI skip for Python
3.11/3.12.

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] This is not a security issue.
- [x] Pytests have been added (or are not necessary).
- [x] Documentation has been added (or is not necessary).
)

### Motivation

Sponsor images on the main page were passed as local file `Path` objects
to `ui.interactive_image()`, causing
NiceGUI to serve them via auto-generated paths like
`/_nicegui/auto/static/<hash>/lechler-gmbh.webp`. This had two
  problems:

1. **Broken images across server instances:** The hash in the auto path
is instance-specific. Since nicegui.io
runs multiple server instances, a client could receive HTML from one
instance but have the image request routed to
another instance where that hash doesn't exist, causing the image to
fail to load.

2. **Poor caching / Lighthouse score:** The auto path bypasses the
`DocsSetCacheControlMiddleware` that sets cache
headers for `/static/` paths. Using the static URL ensures sponsor
images are strongly cached.

### Implementation

Use the URL path `/static/sponsors/...` (served by
`app.add_static_files`) instead of local file `Path` objects.
The local path is still used for the `exists()` check to decide between
single vs light/dark image variants.

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] If this PR addresses a security issue, it has been coordinated via
the [security

advisory](https://github.com/zauberzeug/nicegui/security/advisories/new)
process.
- [x] Pytests have been added (or are not necessary).
- [x] Documentation has been added (or is not necessary).

Co-authored-by: Claude Opus 4.6 <[email protected]>
…eug#5729)

### Motivation

Starting a new Chrome browser for each test using the `Screen` fixture
is slow. By reusing the same browser session across all tests, we can
significantly reduce test execution time.

### Implementation

- Made `nicegui_driver` and `nicegui_chrome_options` fixtures
session-scoped so the browser is started once and reused
- Added `_reset_browser_state()` helper to clean up browser state
between tests (closes extra tabs, navigates to about:blank, clears
browser logs)
- Updated `Screen.close()` to navigate to about:blank instead of closing
the last tab, which would invalidate the session-scoped driver
- Consolidated `capabilities` fixture into `nicegui_chrome_options`
(moved logging prefs to `set_capability()`)

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] If this PR addresses a security issue, it has been coordinated via
the [security
advisory](https://github.com/zauberzeug/nicegui/security/advisories/new)
process.
- [x] Pytests are not necessary.
- [x] Documentation is not necessary.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Falko Schindler <[email protected]>
### Motivation

The bundled Mermaid 11.12.0 includes `dagre-d3-es` 7.0.9, which is
affected by a prototype pollution vulnerability (CVE-2025-57347). This
was reported privately by @henriknoren via GHSA-mp6h-mc3x-8v69. But
since it is in an upstream dependency, not in NiceGUI itself, and is
already public knowledge, we decided to fix it in a public PR rather
than a GHSA.

### Implementation

Bump `mermaid` from 11.12.0 to 11.12.2 and rebuild the bundle.

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] Since this PR addresses a security issue, it has been coordinated
via the [security
advisory](https://github.com/zauberzeug/nicegui/security/advisories/new)
process.
- [x] Pytests have been added (or are not necessary).
- [x] Documentation has been added (or is not necessary).
### Motivation

Claude Code doesn't read `AGENTS.md` natively — it only loads
`CLAUDE.md` on startup. Two earlier PRs explored ways to bridge this
gap:

- **zauberzeug#5720** — symlink (`ln -s AGENTS.md CLAUDE.md`) — closed because
symlinks [break on
Windows](zauberzeug#5720 (comment))
- **zauberzeug#5722** — full copy with pre-commit sync hook — works but duplicates
the entire file and adds a Python hook

Inspired by [this
recommendation](anthropics/claude-code#6235 (comment)).

### Implementation

A minimal `CLAUDE.md` containing just `@AGENTS.md`. Claude Code's native
`@file` directive inlines the referenced file into the system prompt at
session start. This keeps `AGENTS.md` as the single source of truth — no
duplication, no sync hooks, no symlinks. Works cross-platform.

Supersedes zauberzeug#5720 and zauberzeug#5722.

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] If this PR addresses a security issue, it has been coordinated via
the [security
advisory](https://github.com/zauberzeug/nicegui/security/advisories/new)
process.
- [x] Pytests have been added (or are not necessary).
- [x] Documentation has been added (or is not necessary).

Co-authored-by: Claude Opus 4.6 <[email protected]>
@evnchn
evnchn deleted the branch DONOTMERGE February 11, 2026 15:39
@evnchn evnchn closed this Feb 11, 2026
@evnchn evnchn added the question Further information is requested label Feb 11, 2026
falkoschindler added a commit that referenced this pull request Mar 12, 2026
### Motivation

This PR addresses multiple Dependabot security alerts by bumping
vulnerable dependencies to their patched versions:

- [#67](https://github.com/zauberzeug/nicegui/security/dependabot/67) -
`lodash-es` for vanilla-jsoneditor (json_editor element)
- [#68](https://github.com/zauberzeug/nicegui/security/dependabot/68) -
`fonttools` for matplotlib
- [#72](https://github.com/zauberzeug/nicegui/security/dependabot/72) -
`aiohttp` ≥3.13.3
- [#80](https://github.com/zauberzeug/nicegui/security/dependabot/80) -
`urllib3` ≥2.6.3
- [#83](https://github.com/zauberzeug/nicegui/security/dependabot/83) -
`orjson` ≥3.11.5

### Implementation

- Updated pyproject.toml with new minimum versions for `aiohttp`,
`orjson`, `urllib3`, and added `fonttools` to the matplotlib extra
- Pinned `lodash-es` ^4.17.23 in package.json for two elements to
override vulnerable transitive dependencies
- Regenerated package-lock.json files and uv.lock (`npm run build`
didn't change anything in the generated bundles)

### Progress

- [x] I chose a meaningful title that completes the sentence: "If
applied, this PR will..."
- [x] The implementation is complete.
- [x] This is not a security issue in NiceGUI itself, but updating
dependencies with already-public CVEs.
- [x] Pytests are not necessary.
- [x] Documentation is not necessary.
@evnchn
evnchn deleted the docs-code-transformation-callables branch May 14, 2026 17:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

question Further information is requested

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants