kuhy_credit: web element, Godot, Flutter, CI, README

Todo: 3a5477b9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-20 15:33:19 +01:00
parent f27d42ff66
commit 50473d2d26
53 changed files with 3988 additions and 23 deletions

22
.github/workflows/kuhy-credit-drift.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: kuhy_credit drift
# Not path-filtered, like palette-drift: the sources live outside kuhy_credit/
# (the M1 art, web_ui's tokens.css), so an edit there must be able to fail it.
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
drift:
runs-on: ubuntu-latest
defaults:
run:
working-directory: kuhy_credit
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- name: Every stack's generated file matches credit.json, the art and the tokens
run: python3 -m generator.generate --check

96
.github/workflows/kuhy-credit-tests.yml vendored Normal file
View File

@ -0,0 +1,96 @@
name: kuhy_credit tests
on:
push:
branches: [main]
paths: ['kuhy_credit/**', 'flutter_web_drive/**', '.github/workflows/kuhy-credit-tests.yml']
pull_request:
branches: [main]
paths: ['kuhy_credit/**', 'flutter_web_drive/**', '.github/workflows/kuhy-credit-tests.yml']
env:
GODOT_VERSION: "4.7.2"
jobs:
python:
runs-on: ubuntu-latest
defaults:
run:
working-directory: kuhy_credit
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- name: Install the package, pytest and a virtual X display
run: |
sudo apt-get update && sudo apt-get install -y xvfb python3-tk
pip install -r requirements-dev.txt && pip install --no-deps -e .
- name: Lint
run: ruff check . && ruff format --check .
- name: Tests, Tk E2E and the drift check, 100% branch coverage
run: xvfb-run -a -s "-screen 0 1600x1200x24" python -m pytest -q
web:
runs-on: ubuntu-latest
defaults:
run:
working-directory: kuhy_credit/web
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with: { version: 12 }
- uses: actions/setup-node@v4
with: { node-version: "26.13.1" }
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- run: pnpm install --frozen-lockfile
- run: pnpm lint
- name: Unit tests, 100% coverage
run: pnpm coverage
- name: E2E in headless Chrome (window.open stubbed)
working-directory: .
env: { CHROMIUM: google-chrome }
run: |
pip install -r flutter_web_drive/requirements.txt
python3 kuhy_credit/e2e/web_e2e.py
flutter:
runs-on: ubuntu-latest
defaults:
run:
working-directory: kuhy_credit/flutter
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with: { channel: stable }
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- run: flutter pub get
- run: flutter analyze
- name: Widget tests, 100% line coverage
run: flutter test --coverage && ../../scripts/check_coverage.sh coverage/lcov.info 100
- name: Example web build + E2E in headless Chrome (window.open stubbed)
env: { CHROMIUM: google-chrome }
run: |
(cd example && flutter pub get && flutter analyze && flutter build web --release)
pip install -r ../../flutter_web_drive/requirements.txt
python3 ../e2e/flutter_web_e2e.py
godot:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.15.2" }
- name: Install Godot
run: |
curl -fsSL -o godot.zip "https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}-stable/Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip"
unzip -q godot.zip
chmod +x "Godot_v${GODOT_VERSION}-stable_linux.x86_64"
sudo mv "Godot_v${GODOT_VERSION}-stable_linux.x86_64" /usr/local/bin/godot
rm godot.zip
- name: Lint (gdlint, gdformat)
run: pip install -r godot_dev_tools/requirements-dev.txt && kuhy_credit/godot/lint.sh
- name: GUT unit tests + demo E2E (GUT fetched at its pinned tag)
env: { KUHY_CREDIT_GODOT_TIMEOUT: "50" }
run: kuhy_credit/godot/test.sh

View File

@ -4,6 +4,9 @@ Monorepo of shared gates and libraries (app_errors, dep_freshness, file_length,
repo_contract, coverage_gaps, crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording,
flutter_web_drive (headless Flutter-web E2E driver + MCP), ...).
`godot_dev_tools/` is a Godot addon (GDScript): `godot_dev_tools/test.sh` runs its GUT tests.
`kuhy_credit/` is the shared "Created by kuhy" credit, one implementation per stack (web, Flutter,
Godot, Tk, terminal) generated from `kuhy_credit/credit.json`; `kuhy_credit/README.md` lists each
stack's test and E2E command, `python -m generator.generate --check` (from `kuhy_credit/`) the drift check.
Python packages with a root-level `<pkg>/tests` run with `PYTHONPATH=.`;
subprojects with their own `pyproject.toml` run via `scripts/run_subproject_tests.sh <dir>`.
`scripts/check_repo_contract.sh` is the REAL shared gate (not a shim): never

6
kuhy_credit/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
# Tool output, never committed.
web/node_modules/
web/coverage/
flutter/.dart_tool/
flutter/coverage/
flutter/example/.dart_tool/

140
kuhy_credit/README.md Normal file
View File

@ -0,0 +1,140 @@
# kuhy_credit
One "Created by kuhy" credit for every kuhy repo. The user sees the M1 logo. A
click or tap opens a small panel with the logo and the words "Created by kuhy".
A click or tap on the panel opens https://kuhy.duckdns.org in the system
browser. Escape, a click outside the panel and a second logo click close it.
Nothing loads over the network and nothing opens without a click.
## Where the data lives
- `credit.json` holds the URL, the text and the paths of the two sources it
reads: the M1 art (`unified-design-system/logo/final/kuhy.svg`) and the
design tokens (`web_ui/src/tokens.css`).
- `generator/generate.py` writes each stack's data file from those sources.
Never edit a generated file by hand:
| Stack | Generated file |
| -------- | ----------------------------------------- |
| python | `kuhy_credit/_data.py` |
| web | `web/src/credit-data.js` |
| flutter | `flutter/lib/src/credit_data.g.dart` |
| godot | `godot/addons/kuhy_credit/credit_data.gd` |
| terminal | `terminal/kuhy-credit.sh` |
- `python -m generator.generate --check` (from `kuhy_credit/`) fails and names
every stack whose file differs from the sources. CI runs it on every push.
## Decisions (change them here if you disagree)
- Placement: web footer, Flutter about screen, Godot main-menu corner. The
panel opens above the logo, aligned to its end edge; each stack has a
"below" and a "start" option.
- Lockers and gate windows get no credit. The Tk widget ships but no locker
uses it.
- Distribution: a git dependency pinned to the tag `kuhy-credit-v<version>`
(version in `pyproject.toml`, `web/package.json` and
`flutter/pubspec.yaml`, kept equal). Never copy the files into a repo by hand.
## Web (plain HTML, Astro, React/Vite)
```jsonc
// package.json
"@kuhyx/kuhy-credit": "github:kuhyx/utils#kuhy-credit-v0.1.0&path:kuhy_credit/web"
```
```html
<script type="module">import "@kuhyx/kuhy-credit";</script>
<footer><kuhy-credit></kuhy-credit></footer>
```
In Astro, put the same `import` in a `<script>` tag of the layout. In React
19, call `import "@kuhyx/kuhy-credit";` once and render `<kuhy-credit />`;
the `.d.ts` adds the JSX type. Attributes: `placement="below"`,
`align="start"`, `theme="light|dark"` (default: follow the page). The size
comes from `--kuhy-credit-size` (default 48px). Colours come from the page's
`tokens.css` variables when they exist, else from the generated token values.
Demo: `python3 -m http.server -d . 8765` from the repo root, then open
http://127.0.0.1:8765/kuhy_credit/web/demo/index.html (`?theme=light` forces
the light theme).
## Flutter (Android and web)
```yaml
dependencies:
kuhy_credit:
git:
url: https://github.com/kuhyx/utils
ref: kuhy-credit-v0.1.0
path: kuhy_credit/flutter
```
```dart
import 'package:kuhy_credit/kuhy_credit.dart';
const KuhyCredit() // e.g. at the bottom of the about screen
```
The widget opens the site with `url_launcher` (a new tab on web, the browser
app on Android). Back closes an open panel. Demo: `flutter/example`.
## Godot 4.7
```bash
cache="$(mktemp -d)"
git clone --depth 1 --branch kuhy-credit-v0.1.0 https://github.com/kuhyx/utils "$cache"
cp -r "$cache/kuhy_credit/godot/addons/kuhy_credit" addons/
```
```gdscript
var credit: Control = preload("res://addons/kuhy_credit/kuhy_credit.tscn").instantiate()
credit.light = false # true on a light menu
$MainMenu.add_child(credit) # then place it in a corner
```
The script opens the site with `OS.shell_open`. Demo:
`godot --path kuhy_credit/godot` (`-- --light` for the light theme).
## Python / Tkinter
```bash
pip install "kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.1.0#subdirectory=kuhy_credit"
```
```python
from kuhy_credit.tk import KuhyCredit
KuhyCredit(root, theme="dark").place(relx=1, rely=1, x=-16, y=-16, anchor="se")
```
The widget opens the site with `webbrowser` (a new tab). Tk has no rounded
corners and no accessibility tree, so those two parts of the design do not
apply there. Demo: `python -m kuhy_credit.demo [--light]`.
## Terminal programs
```bash
kuhy-credit # after the pip install above
bash kuhy_credit/terminal/kuhy-credit.sh # no Python needed
```
```python
from kuhy_credit import credit_line
print(credit_line()) # Created by kuhy https://kuhy.duckdns.org
```
## Tests
| Stack | Command (from `kuhy_credit/`) |
| --------------- | --------------------------------------------------------------- |
| python + drift | `xvfb-run -a python -m pytest` (100% branch coverage) |
| web | `cd web && pnpm install && pnpm coverage` (100%) |
| web E2E | `PYTHONPATH=.. python3 e2e/web_e2e.py` |
| flutter | `cd flutter && flutter test --coverage` (100% lines) |
| flutter web E2E | build `flutter/example` for web, then `python3 e2e/flutter_web_e2e.py` |
| godot + E2E | `godot/test.sh` (GUT; `tests/test_demo_e2e.gd` is the E2E) |
| Tk E2E | part of the pytest run: `tests/test_tk_e2e.py` |
Every E2E clicks the logo, then the panel, and checks the URL the stubbed
browser launch received.

149
kuhy_credit/e2e/browser.py Normal file
View File

@ -0,0 +1,149 @@
"""Headless chromium + a loopback file server, driven over CDP.
Shared by the web and Flutter-web E2Es. The browser never has a window and
never touches kuhy's display; window.open is replaced before any page script
runs, so "opening the website" only records the URL.
"""
from __future__ import annotations
import base64
import contextlib
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from collections.abc import Iterator
from pathlib import Path
from typing import Any
REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO))
from flutter_web_drive import cdp # noqa: E402
CREDIT = json.loads((REPO / "kuhy_credit/credit.json").read_text())
STUB = """
window.__opened = [];
window.open = (url) => { window.__opened.push(String(url)); return null; };
"""
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return int(s.getsockname()[1])
def chromium() -> str:
for cand in (os.environ.get("CHROMIUM", ""), "/usr/bin/chromium", "google-chrome", "chromium"):
if cand and shutil.which(cand):
return cand
raise SystemExit("no chromium found (set CHROMIUM)")
def wait_for(probe, what: str, timeout: float = 20.0) -> Any:
end = time.monotonic() + timeout
while time.monotonic() < end:
with contextlib.suppress(Exception):
got = probe()
if got:
return got
time.sleep(0.1)
raise AssertionError(f"timed out waiting for {what}")
class Page:
"""One CDP page with mouse/keyboard helpers."""
def __init__(self, sess: cdp.Session) -> None:
self.s = sess
def eval(self, expr: str) -> Any:
return self.s.evaluate(expr)
def click(self, x: float, y: float) -> None:
for kind in ("mousePressed", "mouseReleased"):
self.s.call(
"Input.dispatchMouseEvent", type=kind, x=x, y=y, button="left", clickCount=1
)
time.sleep(0.15)
def key(self, key: str, code: str, vk: int, text: str = "") -> None:
"""Press and release one key; ``text`` makes Enter/Space activate."""
extra = {"text": text} if text else {}
self.s.call(
"Input.dispatchKeyEvent",
type="keyDown" if text else "rawKeyDown",
key=key,
code=code,
windowsVirtualKeyCode=vk,
**extra,
)
self.s.call(
"Input.dispatchKeyEvent", type="keyUp", key=key, code=code, windowsVirtualKeyCode=vk
)
time.sleep(0.15)
def opened(self) -> list[str]:
return list(self.eval("window.__opened"))
def shot(self, path: Path) -> None:
data = self.s.call("Page.captureScreenshot", format="png")["data"]
path.write_bytes(base64.b64decode(data))
def foreign_requests(self) -> list[str]:
urls = [
e["params"]["request"]["url"]
for e in self.s.drain(0.3)
if e.get("method") == "Network.requestWillBeSent"
]
return [u for u in urls if not u.startswith(("http://127.0.0.1", "data:", "blob:"))]
@contextlib.contextmanager
def session(serve_dir: Path, size: str = "900,600") -> Iterator[tuple[Page, int]]:
"""Serve ``serve_dir`` on loopback and attach to a fresh headless chromium."""
http_port, cdp_port = free_port(), free_port()
profile = tempfile.mkdtemp(prefix="kc-e2e-")
server = subprocess.Popen(
[
sys.executable,
"-m",
"http.server",
str(http_port),
"-b",
"127.0.0.1",
"-d",
str(serve_dir),
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
browser = subprocess.Popen(
[chromium(), "--headless=new", f"--remote-debugging-port={cdp_port}",
"--remote-debugging-address=127.0.0.1", f"--user-data-dir={profile}",
"--disable-extensions", "--no-first-run", "--no-default-browser-check",
"--password-store=basic", "--mute-audio", "--hide-scrollbars",
"--enable-unsafe-swiftshader", f"--window-size={size}", "about:blank"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
) # fmt: skip
try:
sess = wait_for(lambda: cdp.connect(cdp_port), "chromium CDP")
sess.call("Page.enable")
sess.call("Network.enable")
sess.call("Page.addScriptToEvaluateOnNewDocument", source=STUB)
yield Page(sess), http_port
sess.close()
finally:
browser.terminate()
server.terminate()
browser.wait(10)
server.wait(10)
shutil.rmtree(profile, ignore_errors=True)

View File

@ -0,0 +1,72 @@
"""Flutter-web E2E: the built example app in headless chromium, real clicks.
(cd kuhy_credit/flutter/example && flutter build web --release)
python3 kuhy_credit/e2e/flutter_web_e2e.py [shots_dir]
The logo and the panel are found through Flutter's semantics DOM (both are
named "Created by kuhy": the logo is the button, the panel the link). Passes
when the logo click shows the panel, the panel click "opens" the URL
(window.open stubbed, which url_launcher_web calls) and the panel is gone.
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
from browser import CREDIT, REPO, Page, session, wait_for
BUILD = REPO / "kuhy_credit/flutter/example/build/web"
FIND = """(() => {
const want = %s;
const el = [...document.querySelectorAll('flt-semantics, a, [role]')].find(e =>
(e.getAttribute('aria-label') || e.textContent || '').trim() === %s &&
(want === 'button' ? e.getAttribute('role') === 'button'
: e.tagName === 'A' || e.getAttribute('role') === 'link'));
if (!el) return null;
const r = el.getBoundingClientRect();
return r.width > 0 ? [r.x + r.width / 2, r.y + r.height / 2] : null;
})()"""
def find(page: Page, role: str) -> tuple[float, float] | None:
text = repr(CREDIT["text"]).replace("'", '"')
return page.eval(FIND % (f'"{role}"', text))
def main() -> int:
shots = Path(sys.argv[1]) if len(sys.argv) > 1 else None
if not (BUILD / "index.html").is_file():
raise SystemExit(f"no web build at {BUILD}: run flutter build web first")
with session(BUILD) as (page, port):
page.s.call("Page.navigate", url=f"http://127.0.0.1:{port}/index.html")
logo = wait_for(lambda: find(page, "button"), "the logo in the semantics tree", 40)
assert find(page, "link") is None, "panel visible before any click"
if shots:
page.shot(shots / "flutter-web-closed.png")
page.click(*logo)
panel = wait_for(lambda: find(page, "link"), "the panel after the logo click")
time.sleep(0.3)
if shots:
page.shot(shots / "flutter-web-open.png")
assert page.opened() == [], "the logo click opened the site"
page.click(*panel)
wait_for(page.opened, "window.open after the panel click")
assert page.opened() == [CREDIT["url"]], page.opened()
wait_for(lambda: find(page, "link") is None, "the panel to close")
page.click(*logo)
wait_for(lambda: find(page, "link"), "reopen")
page.click(*logo)
wait_for(lambda: find(page, "link") is None, "second logo click to close")
page.click(*logo)
wait_for(lambda: find(page, "link"), "reopen")
page.click(20, 20)
wait_for(lambda: find(page, "link") is None, "outside click to close")
assert page.opened() == [CREDIT["url"]], "a close path opened the site"
print(f"flutter web e2e: two clicks opened {CREDIT['url']}; close paths pass")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,81 @@
"""Web E2E: the <kuhy-credit> demo page in headless chromium, real input events.
PYTHONPATH=<repo> python3 kuhy_credit/e2e/web_e2e.py [shots_dir]
Passes when: only the logo shows; a logo click opens the panel; a panel click
"opens" CREDIT url (window.open stubbed) and closes it; Escape, an outside
click and a second logo click each close it without opening anything; Tab +
Enter reach and open it; the page made no request off loopback.
"""
from __future__ import annotations
import sys
from pathlib import Path
from browser import CREDIT, REPO, Page, session, wait_for
HOST = "document.querySelector('kuhy-credit')"
def centre(page: Page, part: str) -> tuple[float, float]:
r = page.eval(f"(() => {{ const r = {HOST}.shadowRoot.querySelector('{part}').getBoundingClientRect();"
" return [r.x + r.width / 2, r.y + r.height / 2]; })()") # fmt: skip
return r[0], r[1]
def is_open(page: Page) -> bool:
return bool(page.eval(f"{HOST}.open"))
def run(page: Page, port: int, theme: str, shots: Path | None) -> None:
url = f"http://127.0.0.1:{port}/kuhy_credit/web/demo/index.html?theme={theme}"
page.s.call("Page.navigate", url=url)
wait_for(
lambda: page.eval(
f"!!{HOST} && !!customElements.get('kuhy-credit') && !!{HOST}.shadowRoot"
),
"element",
)
assert not is_open(page), "panel visible before any click"
assert page.eval(f"{HOST}.shadowRoot.querySelector('button').textContent.trim()") == ""
if shots:
page.shot(shots / f"web-{theme}-closed.png")
page.click(*centre(page, "button"))
assert is_open(page), "logo click did not open the panel"
assert page.eval(f"{HOST}.shadowRoot.querySelector('a').textContent.trim()") == CREDIT["text"]
if shots:
page.shot(shots / f"web-{theme}-open.png")
page.click(*centre(page, "a"))
assert page.opened() == [CREDIT["url"]], page.opened()
assert not is_open(page), "panel stayed open after opening the site"
for name, close in (
("escape", lambda: page.key("Escape", "Escape", 27)),
("outside", lambda: page.click(20, 20)),
("second logo click", lambda: page.click(*centre(page, "button"))),
):
page.click(*centre(page, "button"))
assert is_open(page), f"reopen before {name}"
close()
assert not is_open(page), f"{name} did not close the panel"
page.click(20, 20)
page.key("Tab", "Tab", 9)
page.key("Enter", "Enter", 13, "\r")
assert is_open(page), "Tab + Enter did not open the panel"
assert page.opened() == [CREDIT["url"]], "a close path opened the site"
foreign = page.foreign_requests()
assert not foreign, f"network requests off loopback: {foreign}"
def main() -> int:
shots = Path(sys.argv[1]) if len(sys.argv) > 1 else None
with session(REPO) as (page, port):
for theme in ("dark", "light"):
run(page, port, theme, shots)
print(f"web e2e: two clicks opened {CREDIT['url']}; all close paths pass")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,38 @@
include: package:very_good_analysis/analysis_options.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
errors:
# Promote key lints to errors so they fail CI, not just warn.
missing_required_param: error
unnecessary_null_comparison: error
dead_code: error
invalid_annotation_target: error
exclude:
- build/**
- example/**
- "**/*.g.dart"
- "**/*.freezed.dart"
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:
# very_good_analysis enables most rules; add extras it doesn't include.
always_use_package_imports: true
avoid_print: true
avoid_relative_lib_imports: true
cancel_subscriptions: true
close_sinks: true
comment_references: false # conflicts with typical Flutter API docs style
directives_ordering: true
lines_longer_than_80_chars: true
public_member_api_docs: true
unawaited_futures: true

View File

@ -0,0 +1,4 @@
analyzer:
exclude:
- build/**
include: package:very_good_analysis/analysis_options.yaml

View File

@ -0,0 +1,44 @@
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:kuhy_credit/kuhy_credit.dart';
/// Demo: an empty token-coloured screen with the credit in the bottom-right
/// corner, the spot an app's about screen would give it.
void main() {
// Builds the semantics tree on web too, so screen readers and the E2E
// find the logo by its name.
WidgetsFlutterBinding.ensureInitialized();
SemanticsBinding.instance.ensureSemantics();
runApp(const CreditDemo());
}
/// The demo app.
class CreditDemo extends StatelessWidget {
/// Creates the demo.
const CreditDemo({super.key});
@override
Widget build(BuildContext context) {
final dark =
MediaQuery.platformBrightnessOf(context) == Brightness.dark;
return WidgetsApp(
color: Color(dark ? kDarkBg : kLightBg),
pageRouteBuilder: <T>(settings, builder) => PageRouteBuilder<T>(
settings: settings,
pageBuilder: (context, _, _) => builder(context),
),
home: ColoredBox(
color: Color(dark ? kDarkBg : kLightBg),
child: const SafeArea(
child: Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: EdgeInsets.all(16),
child: KuhyCredit(),
),
),
),
),
);
}
}

View File

@ -0,0 +1,297 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
characters:
dependency: transitive
description:
name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
url: "https://pub.dev"
source: hosted
version: "1.4.1"
clock:
dependency: transitive
description:
name: clock
sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e
url: "https://pub.dev"
source: hosted
version: "1.1.3"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev"
source: hosted
version: "1.3.3"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
kuhy_credit:
dependency: "direct main"
description:
path: ".."
relative: true
source: path
version: "0.1.0"
leak_tracker:
dependency: transitive
description:
name: leak_tracker
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
url: "https://pub.dev"
source: hosted
version: "11.0.2"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
url: "https://pub.dev"
source: hosted
version: "3.0.10"
leak_tracker_testing:
dependency: transitive
description:
name: leak_tracker_testing
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
listen:
dependency: transitive
description:
name: listen
sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
matcher:
dependency: transitive
description:
name: matcher
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
url: "https://pub.dev"
source: hosted
version: "0.13.0"
meta:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.19.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
url: "https://pub.dev"
source: hosted
version: "1.12.2"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test_api:
dependency: transitive
description:
name: test_api
sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f"
url: "https://pub.dev"
source: hosted
version: "0.7.14"
url_launcher:
dependency: transitive
description:
name: url_launcher
sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda
url: "https://pub.dev"
source: hosted
version: "6.3.3"
url_launcher_android:
dependency: transitive
description:
name: url_launcher_android
sha256: b8073b1e5173d63afe1a18985a75896d72f759d3bc1817eb1ae8d26e8527cceb
url: "https://pub.dev"
source: hosted
version: "6.3.35"
url_launcher_ios:
dependency: transitive
description:
name: url_launcher_ios
sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a"
url: "https://pub.dev"
source: hosted
version: "6.4.2"
url_launcher_linux:
dependency: transitive
description:
name: url_launcher_linux
sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0"
url: "https://pub.dev"
source: hosted
version: "3.2.3"
url_launcher_macos:
dependency: transitive
description:
name: url_launcher_macos
sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201"
url: "https://pub.dev"
source: hosted
version: "3.2.6"
url_launcher_platform_interface:
dependency: transitive
description:
name: url_launcher_platform_interface
sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
url: "https://pub.dev"
source: hosted
version: "2.3.2"
url_launcher_web:
dependency: transitive
description:
name: url_launcher_web
sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34"
url: "https://pub.dev"
source: hosted
version: "2.4.3"
url_launcher_windows:
dependency: transitive
description:
name: url_launcher_windows
sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429"
url: "https://pub.dev"
source: hosted
version: "3.1.6"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc
url: "https://pub.dev"
source: hosted
version: "2.4.4"
very_good_analysis:
dependency: "direct dev"
description:
name: very_good_analysis
sha256: "0bd5eb8d6be76aa0d71e70cbdae6cac8f784f761170568e3c2214a6948c7f6d3"
url: "https://pub.dev"
source: hosted
version: "11.0.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78"
url: "https://pub.dev"
source: hosted
version: "15.4.0"
web:
dependency: transitive
description:
name: web
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
url: "https://pub.dev"
source: hosted
version: "1.1.2"
sdks:
dart: ">=3.13.0 <4.0.0"
flutter: ">=3.44.0"

View File

@ -0,0 +1,18 @@
name: kuhy_credit_example
description: Click-through demo of the kuhy_credit widget (Android + web).
publish_to: 'none'
version: 0.1.0
environment:
sdk: ^3.12.2
dependencies:
flutter:
sdk: flutter
kuhy_credit:
path: ..
dev_dependencies:
flutter_test:
sdk: flutter
very_good_analysis: ^11.0.0

View File

@ -0,0 +1,5 @@
/// The shared kuhy logo credit.
library;
export 'src/credit_data.g.dart';
export 'src/kuhy_credit.dart';

View File

@ -126,6 +126,8 @@ const List<(int, List<double>)> kLogoShapes = [
],
),
];
const int kDarkBg = 0xFF211D1B;
const int kLightBg = 0xFFF6F4F3;
const int kDarkSurface = 0xFF2B2624;
const int kDarkBorder = 0xFF463E3A;
const int kDarkText = 0xFFECEAE9;

View File

@ -0,0 +1,268 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:kuhy_credit/src/credit_data.g.dart';
import 'package:url_launcher/url_launcher.dart';
/// Opens [uri] in the system browser: a new tab on web, the browser app on
/// Android.
Future<void> openInBrowser(Uri uri) async {
await launchUrl(
uri,
mode: LaunchMode.externalApplication,
webOnlyWindowName: '_blank',
);
}
/// The shared kuhy credit.
///
/// Shows the M1 logo. A tap (or Enter/Space) opens a small panel with the
/// logo and the credit text; a tap on the panel opens the website through
/// [launcher] and closes it. Escape, Back, a tap outside and a second logo
/// tap close the panel. Colours follow the platform brightness.
class KuhyCredit extends StatefulWidget {
/// Creates the credit.
const KuhyCredit({
super.key,
this.size = 48,
this.below = false,
this.alignStart = false,
this.launcher = openInBrowser,
});
/// Finds the logo button in tests.
static const ValueKey<String> logoKey = ValueKey('kuhy_credit.logo');
/// Finds the open panel in tests.
static const ValueKey<String> panelKey = ValueKey('kuhy_credit.panel');
/// Logo edge length in logical pixels.
final double size;
/// Open the panel under the logo instead of above it.
final bool below;
/// Align the panel's start edge with the logo instead of its end edge.
final bool alignStart;
/// Opens the website; replace it to stub the browser in tests.
final Future<void> Function(Uri uri) launcher;
@override
State<KuhyCredit> createState() => _KuhyCreditState();
}
class _KuhyCreditState extends State<KuhyCredit> {
final _portal = OverlayPortalController();
final _link = LayerLink();
final _logoFocus = FocusNode();
final _panelFocus = FocusNode();
@override
void dispose() {
_logoFocus.dispose();
_panelFocus.dispose();
super.dispose();
}
void _toggle() {
if (_portal.isShowing) {
_close();
return;
}
setState(_portal.show);
WidgetsBinding.instance.addPostFrameCallback(
(_) => _panelFocus.requestFocus(),
);
}
void _close() {
if (_portal.isShowing) setState(_portal.hide);
}
Future<void> _activate() async {
_close();
await widget.launcher(Uri.parse(kCreditUrl));
}
KeyEventResult _onPanelKey(FocusNode _, KeyEvent event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
final key = event.logicalKey;
if (key == LogicalKeyboardKey.escape) {
_close();
_logoFocus.requestFocus();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.enter || key == LogicalKeyboardKey.space) {
unawaited(_activate());
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final dark =
MediaQuery.platformBrightnessOf(context) == Brightness.dark;
final above = !widget.below;
final end = !widget.alignStart;
final logo = Semantics(
button: true,
expanded: _portal.isShowing,
label: kCreditText,
excludeSemantics: true,
onTap: _toggle,
child: FocusableActionDetector(
focusNode: _logoFocus,
mouseCursor: SystemMouseCursors.click,
actions: {
ActivateIntent: CallbackAction<ActivateIntent>(
onInvoke: (_) => _toggle(),
),
},
child: GestureDetector(
key: KuhyCredit.logoKey,
onTap: _toggle,
child: _Logo(size: widget.size),
),
),
);
return PopScope(
canPop: !_portal.isShowing,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _close();
},
child: TapRegion(
groupId: this,
onTapOutside: (_) => _close(),
child: CompositedTransformTarget(
link: _link,
child: OverlayPortal(
controller: _portal,
overlayChildBuilder: (context) => CompositedTransformFollower(
link: _link,
targetAnchor: Alignment(end ? 1 : -1, above ? -1 : 1),
followerAnchor: Alignment(end ? 1 : -1, above ? 1 : -1),
offset: Offset(0, above ? -kSpaceSm : kSpaceSm),
child: Align(
alignment: Alignment(end ? 1 : -1, above ? 1 : -1),
child: TapRegion(
groupId: this,
child: _Panel(
dark: dark,
size: widget.size,
focusNode: _panelFocus,
onKey: _onPanelKey,
onTap: _activate,
),
),
),
),
child: logo,
),
),
),
);
}
}
class _Panel extends StatelessWidget {
const _Panel({
required this.dark,
required this.size,
required this.focusNode,
required this.onKey,
required this.onTap,
});
final bool dark;
final double size;
final FocusNode focusNode;
final FocusOnKeyEventCallback onKey;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Semantics(
link: true,
label: kCreditText,
excludeSemantics: true,
onTap: onTap,
child: Focus(
focusNode: focusNode,
onKeyEvent: onKey,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
key: KuhyCredit.panelKey,
onTap: onTap,
child: DecoratedBox(
decoration: BoxDecoration(
color: Color(dark ? kDarkSurface : kLightSurface),
border: Border.all(
color: Color(dark ? kDarkBorder : kLightBorder),
),
borderRadius: BorderRadius.circular(kRadius),
),
child: Padding(
padding: const EdgeInsets.all(kSpaceMd),
child: Row(
mainAxisSize: MainAxisSize.min,
spacing: kSpaceSm,
children: [
_Logo(size: size),
Text(
kCreditText,
textDirection: TextDirection.ltr,
style: TextStyle(
color: Color(dark ? kDarkText : kLightText),
fontSize: kTextBody,
decoration: TextDecoration.none,
),
),
],
),
),
),
),
),
),
);
}
}
class _Logo extends StatelessWidget {
const _Logo({required this.size});
final double size;
@override
Widget build(BuildContext context) {
return CustomPaint(size: Size.square(size), painter: const _LogoPainter());
}
}
class _LogoPainter extends CustomPainter {
const _LogoPainter();
@override
void paint(Canvas canvas, Size size) {
canvas
..scale(size.width / kLogoSize)
..drawRect(
const Rect.fromLTWH(0, 0, kLogoSize, kLogoSize),
Paint()..color = const Color(kLogoField),
);
for (final (fill, points) in kLogoShapes) {
final path = Path()..moveTo(points[0], points[1]);
for (var i = 2; i < points.length; i += 2) {
path.lineTo(points[i], points[i + 1]);
}
canvas.drawPath(path..close(), Paint()..color = Color(fill));
}
}
@override
bool shouldRepaint(_LogoPainter oldDelegate) => false;
}

View File

@ -0,0 +1,290 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
characters:
dependency: transitive
description:
name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
url: "https://pub.dev"
source: hosted
version: "1.4.1"
clock:
dependency: transitive
description:
name: clock
sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e
url: "https://pub.dev"
source: hosted
version: "1.1.3"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev"
source: hosted
version: "1.3.3"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
leak_tracker:
dependency: transitive
description:
name: leak_tracker
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
url: "https://pub.dev"
source: hosted
version: "11.0.2"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
url: "https://pub.dev"
source: hosted
version: "3.0.10"
leak_tracker_testing:
dependency: transitive
description:
name: leak_tracker_testing
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
listen:
dependency: transitive
description:
name: listen
sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
matcher:
dependency: transitive
description:
name: matcher
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
url: "https://pub.dev"
source: hosted
version: "0.13.0"
meta:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.19.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
plugin_platform_interface:
dependency: "direct dev"
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
url: "https://pub.dev"
source: hosted
version: "1.12.2"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test_api:
dependency: transitive
description:
name: test_api
sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f"
url: "https://pub.dev"
source: hosted
version: "0.7.14"
url_launcher:
dependency: "direct main"
description:
name: url_launcher
sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda
url: "https://pub.dev"
source: hosted
version: "6.3.3"
url_launcher_android:
dependency: transitive
description:
name: url_launcher_android
sha256: b8073b1e5173d63afe1a18985a75896d72f759d3bc1817eb1ae8d26e8527cceb
url: "https://pub.dev"
source: hosted
version: "6.3.35"
url_launcher_ios:
dependency: transitive
description:
name: url_launcher_ios
sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a"
url: "https://pub.dev"
source: hosted
version: "6.4.2"
url_launcher_linux:
dependency: transitive
description:
name: url_launcher_linux
sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0"
url: "https://pub.dev"
source: hosted
version: "3.2.3"
url_launcher_macos:
dependency: transitive
description:
name: url_launcher_macos
sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201"
url: "https://pub.dev"
source: hosted
version: "3.2.6"
url_launcher_platform_interface:
dependency: "direct dev"
description:
name: url_launcher_platform_interface
sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
url: "https://pub.dev"
source: hosted
version: "2.3.2"
url_launcher_web:
dependency: transitive
description:
name: url_launcher_web
sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34"
url: "https://pub.dev"
source: hosted
version: "2.4.3"
url_launcher_windows:
dependency: transitive
description:
name: url_launcher_windows
sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429"
url: "https://pub.dev"
source: hosted
version: "3.1.6"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc
url: "https://pub.dev"
source: hosted
version: "2.4.4"
very_good_analysis:
dependency: "direct dev"
description:
name: very_good_analysis
sha256: "0bd5eb8d6be76aa0d71e70cbdae6cac8f784f761170568e3c2214a6948c7f6d3"
url: "https://pub.dev"
source: hosted
version: "11.0.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78"
url: "https://pub.dev"
source: hosted
version: "15.4.0"
web:
dependency: transitive
description:
name: web
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
url: "https://pub.dev"
source: hosted
version: "1.1.2"
sdks:
dart: ">=3.13.0 <4.0.0"
flutter: ">=3.44.0"

View File

@ -0,0 +1,21 @@
name: kuhy_credit
description: >-
The shared "Created by kuhy" credit: an M1 logo button that opens a small
panel, whose tap opens kuhy.duckdns.org. Android and Flutter web.
publish_to: 'none'
version: 0.1.0
environment:
sdk: ^3.12.2
dependencies:
flutter:
sdk: flutter
url_launcher: 6.3.3
dev_dependencies:
flutter_test:
sdk: flutter
plugin_platform_interface: 2.1.8
url_launcher_platform_interface: 2.3.2
very_good_analysis: ^11.0.0

View File

@ -0,0 +1,235 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:kuhy_credit/kuhy_credit.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
final Finder _logo = find.byKey(KuhyCredit.logoKey);
final Finder _panel = find.byKey(KuhyCredit.panelKey);
Future<List<Uri>> _pump(
WidgetTester tester, {
Brightness brightness = Brightness.dark,
bool below = false,
bool alignStart = false,
Alignment at = Alignment.bottomRight,
}) async {
final opened = <Uri>[];
tester.platformDispatcher.platformBrightnessTestValue = brightness;
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
await tester.pumpWidget(
WidgetsApp(
color: const Color(kDarkBg),
pageRouteBuilder: _route,
home: Stack(
children: [
const Positioned(
left: 0,
top: 0,
child: SizedBox(width: 40, height: 40),
),
Align(
alignment: at,
child: Padding(
padding: const EdgeInsets.all(16),
child: KuhyCredit(
below: below,
alignStart: alignStart,
launcher: (uri) async => opened.add(uri),
),
),
),
],
),
),
);
return opened;
}
PageRoute<T> _route<T>(RouteSettings settings, WidgetBuilder builder) =>
PageRouteBuilder<T>(
settings: settings,
pageBuilder: (context, _, _) => builder(context),
);
void main() {
testWidgets('shows only the logo, named for screen readers', (tester) async {
final handle = tester.ensureSemantics();
final opened = await _pump(tester);
expect(_logo, findsOneWidget);
expect(_panel, findsNothing);
expect(find.text(kCreditText), findsNothing);
expect(find.bySemanticsLabel(kCreditText), findsOneWidget);
expect(opened, isEmpty);
handle.dispose();
});
testWidgets('logo tap opens the panel; panel tap opens the site', (
tester,
) async {
final opened = await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
expect(_panel, findsOneWidget);
expect(find.text(kCreditText), findsOneWidget);
expect(opened, isEmpty);
await tester.tap(find.text(kCreditText));
await tester.pumpAndSettle();
expect(opened, [Uri.parse(kCreditUrl)]);
expect(_panel, findsNothing);
});
testWidgets('second logo tap closes and stays closed', (tester) async {
final opened = await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
await tester.tap(_logo);
await tester.pumpAndSettle();
expect(_panel, findsNothing);
expect(opened, isEmpty);
});
testWidgets('tap outside closes', (tester) async {
final opened = await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle();
expect(_panel, findsNothing);
expect(opened, isEmpty);
});
testWidgets('Escape closes and returns focus to the logo', (tester) async {
final opened = await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(_panel, findsNothing);
expect(opened, isEmpty);
expect(
Focus.of(tester.element(find.byKey(KuhyCredit.logoKey))).hasFocus,
isTrue,
);
});
testWidgets('Back closes the panel instead of leaving the screen', (
tester,
) async {
await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
final handled = await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(handled, isTrue);
expect(_panel, findsNothing);
});
testWidgets('keyboard: Tab reaches the logo, Enter opens, Enter on panel '
'opens the site', (tester) async {
final opened = await _pump(tester);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(_panel, findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
expect(opened, [Uri.parse(kCreditUrl)]);
});
testWidgets('other keys leave the panel open', (tester) async {
await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
await tester.pumpAndSettle();
expect(_panel, findsOneWidget);
});
for (final (brightness, surface, text) in [
(Brightness.dark, kDarkSurface, kDarkText),
(Brightness.light, kLightSurface, kLightText),
]) {
testWidgets('panel colours follow $brightness tokens', (tester) async {
await _pump(tester, brightness: brightness);
await tester.tap(_logo);
await tester.pumpAndSettle();
final box = tester.widget<DecoratedBox>(
find.descendant(of: _panel, matching: find.byType(DecoratedBox)),
);
final deco = box.decoration as BoxDecoration;
expect(deco.color, Color(surface));
expect(deco.borderRadius, BorderRadius.circular(kRadius));
final style = tester.widget<Text>(find.text(kCreditText)).style!;
expect(style.color, Color(text));
expect(style.fontSize, kTextBody);
});
}
testWidgets('panel sits above and end-aligned by default', (tester) async {
await _pump(tester);
await tester.tap(_logo);
await tester.pumpAndSettle();
final panel = tester.getRect(_panel);
final logo = tester.getRect(_logo);
expect(panel.bottom, lessThan(logo.top));
expect(panel.right, moreOrLessEquals(logo.right));
});
testWidgets('below + alignStart puts it under, start-aligned', (
tester,
) async {
await _pump(tester, below: true, alignStart: true, at: Alignment.topLeft);
await tester.tap(_logo);
await tester.pumpAndSettle();
final panel = tester.getRect(_panel);
final logo = tester.getRect(_logo);
expect(panel.top, greaterThan(logo.bottom));
expect(panel.left, moreOrLessEquals(logo.left));
});
testWidgets('the default launcher opens a new tab / external app', (
tester,
) async {
final fake = _FakeLauncher();
UrlLauncherPlatform.instance = fake;
await tester.pumpWidget(
const WidgetsApp(
color: Color(kDarkBg),
pageRouteBuilder: _route,
home: Center(child: KuhyCredit()),
),
);
await tester.tap(_logo);
await tester.pumpAndSettle();
await tester.tap(find.text(kCreditText));
await tester.pumpAndSettle();
expect(fake.urls, [kCreditUrl]);
expect(fake.options.single.mode, PreferredLaunchMode.externalApplication);
expect(fake.options.single.webOnlyWindowName, '_blank');
});
testWidgets('the logo painter draws and never repaints', (tester) async {
await _pump(tester);
final paint = tester.widget<CustomPaint>(
find.descendant(of: _logo, matching: find.byType(CustomPaint)).first,
);
expect(paint.painter!.shouldRepaint(paint.painter!), isFalse);
});
}
class _FakeLauncher extends Fake
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {
final urls = <String>[];
final options = <LaunchOptions>[];
@override
Future<bool> launchUrl(String url, LaunchOptions options) async {
urls.add(url);
this.options.add(options);
return true;
}
}

View File

@ -47,6 +47,14 @@ def _chunks(text: str, size: int = 60) -> list[str]:
return [json.dumps(text[i : i + size]) for i in range(0, len(text), size)]
def _gd_str(chunk: str) -> str:
"""GDScript literal the way gdformat writes it: single quotes around '"'."""
text = json.dumps(chunk)
if '"' in chunk and "'" not in chunk:
return "'" + text[1:-1].replace('\\"', '"') + "'"
return text
def _argb(hex_colour: str) -> str:
return f"0xFF{hex_colour.lstrip('#').upper()}"
@ -59,7 +67,10 @@ def python(c: Credit) -> str:
)
def pal(p: Palette) -> str:
return f'{{"surface": "{p.surface}", "border": "{p.border}", "text": "{p.text}"}}'
return (
f'{{"bg": "{p.bg}", "surface": "{p.surface}", "border": "{p.border}", '
f'"text": "{p.text}"}}'
)
t = c.tokens
return (
@ -79,7 +90,7 @@ def web(c: Credit) -> str:
t = c.tokens
def pal(p: Palette) -> str:
return f'{{ surface: "{p.surface}", border: "{p.border}", text: "{p.text}" }}'
return f'{{ bg: "{p.bg}", surface: "{p.surface}", border: "{p.border}", text: "{p.text}" }}'
return (
f"// The shared credit data ({MARK}).\n"
@ -107,6 +118,8 @@ def flutter(c: Credit) -> str:
f"const double kLogoSize = {c.logo.size};\n"
f"const int kLogoField = {_argb(c.logo.field)};\n"
f"const List<(int, List<double>)> kLogoShapes = [\n{shapes}];\n"
f"const int kDarkBg = {_argb(t.dark.bg)};\n"
f"const int kLightBg = {_argb(t.light.bg)};\n"
f"const int kDarkSurface = {_argb(t.dark.surface)};\n"
f"const int kDarkBorder = {_argb(t.dark.border)};\n"
f"const int kDarkText = {_argb(t.dark.text)};\n"
@ -123,13 +136,13 @@ def flutter(c: Credit) -> str:
def godot(c: Credit) -> str:
"""godot/addons/kuhy_credit/credit_data.gd."""
svg = "\n\t+ ".join(_chunks(c.svg))
svg = "\n\t+ ".join(_gd_str(c.svg[i : i + 60]) for i in range(0, len(c.svg), 60))
t = c.tokens
def pal(p: Palette) -> str:
return (
f'{{\n\t"surface": Color("{p.surface}"),\n\t"border": Color("{p.border}"),'
f'\n\t"text": Color("{p.text}"),\n}}'
f'{{\n\t"bg": Color("{p.bg}"),\n\t"surface": Color("{p.surface}"),'
f'\n\t"border": Color("{p.border}"),\n\t"text": Color("{p.text}"),\n}}'
)
return (
@ -137,6 +150,7 @@ def godot(c: Credit) -> str:
"extends RefCounted\n\n"
f"const URL := {json.dumps(c.url)}\n"
f"const TEXT := {json.dumps(c.text)}\n"
f"const LOGO_SIZE := {c.logo.size}\n"
f"const LOGO_SVG := (\n\t{svg}\n)\n"
f"const DARK := {pal(t.dark)}\n"
f"const LIGHT := {pal(t.light)}\n"

View File

@ -18,8 +18,9 @@ _COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
@dataclass(frozen=True)
class Palette:
"""Panel colours for one theme."""
"""Page background and panel colours for one theme."""
bg: str
surface: str
border: str
text: str
@ -50,7 +51,12 @@ def _get(table: dict[str, str], name: str) -> str:
def _palette(table: dict[str, str]) -> Palette:
return Palette(_get(table, "--surface-1"), _get(table, "--border"), _get(table, "--text"))
return Palette(
_get(table, "--bg"),
_get(table, "--surface-1"),
_get(table, "--border"),
_get(table, "--text"),
)
def _px(table: dict[str, str], name: str) -> int:

View File

@ -0,0 +1,4 @@
# gdlint: every check on, no rule disabled. The cap matches the shared 250-line gate.
max-file-lines: 250
max-line-length: 100
disable: []

3
kuhy_credit/godot/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# fetched by test.sh at the pinned tag, never committed
addons/gut/
.godot/

View File

@ -0,0 +1,9 @@
{
"dirs": ["res://tests/"],
"include_subdirs": true,
"prefix": "test_",
"suffix": ".gd",
"should_exit": true,
"should_exit_on_success": true,
"log_level": 1
}

View File

@ -3,11 +3,12 @@ extends RefCounted
const URL := "https://kuhy.duckdns.org"
const TEXT := "Created by kuhy"
const LOGO_SIZE := 512
const LOGO_SVG := (
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512"
+ "\" width=\"512\" height=\"512\">\n<rect id=\"field\" width=\"512\" hei"
+ "ght=\"512\" fill=\"#211D1B\"/>\n<path fill=\"#B8862E\" fill-rule=\"e"
+ "venodd\" d=\"M232.45 126.71L235.40 121.83L236.86 117.46L237.16"
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512'
+ '" width="512" height="512">\n<rect id="field" width="512" hei'
+ 'ght="512" fill="#211D1B"/>\n<path fill="#B8862E" fill-rule="e'
+ 'venodd" d="M232.45 126.71L235.40 121.83L236.86 117.46L237.16'
+ " 113.16L236.11 108.55L233.71 104.34L230.14 100.74L225.62 97."
+ "95L220.41 96.16L214.75 95.51L208.86 96.11L202.89 97.96L196.9"
+ "7 101.02L191.80 104.61L186.14 109.43L168.83 127.05L163.79 13"
@ -53,8 +54,8 @@ const LOGO_SVG := (
+ "42 414.79L394.87 412.17L396.16 408.88L397.04 405.40L397.53 4"
+ "01.79L397.58 394.42L395.86 378.48L395.63 371.63L396.54 364.0"
+ "5L398.85 356.69L402.90 348.74L408.61 340.49L415.36 332.56L43"
+ "1.64 315.37L435.86 309.98Z\"/>\n<path fill=\"#ECEAE9\" fill-rule"
+ "=\"evenodd\" d=\"M272.87 180.50L273.78 191.15L275.43 199.68L277"
+ '1.64 315.37L435.86 309.98Z"/>\n<path fill="#ECEAE9" fill-rule'
+ '="evenodd" d="M272.87 180.50L273.78 191.15L275.43 199.68L277'
+ ".93 207.24L281.46 214.32L286.01 220.83L291.97 227.15L298.81 "
+ "232.68L306.29 237.38L314.83 241.44L323.65 244.37L331.97 245."
+ "96L340.33 246.39L348.69 245.62L356.98 243.70L365.74 240.46L3"
@ -105,14 +106,16 @@ const LOGO_SVG := (
+ " 291.09L139.19 297.22L138.23 304.49L138.34 311.05L139.18 317"
+ ".50L144.55 338.96L145.64 347.04L145.57 351.31L144.91 356.27L"
+ "139.77 376.54L138.77 382.07L138.23 387.76L138.29 393.51L139."
+ "06 399.17L140.59 404.59Z\"/>\n</svg>\n"
+ '06 399.17L140.59 404.59Z"/>\n</svg>\n'
)
const DARK := {
"bg": Color("#211d1b"),
"surface": Color("#2b2624"),
"border": Color("#463e3a"),
"text": Color("#eceae9"),
}
const LIGHT := {
"bg": Color("#f6f4f3"),
"surface": Color("#fcfbfb"),
"border": Color("#e0dad7"),
"text": Color("#211d1b"),

View File

@ -0,0 +1,143 @@
extends Control
## The shared kuhy credit: an M1 logo button that opens a panel.
##
## A click or Enter on the logo opens a panel (logo + credit text); a
## click or Enter on the panel opens the website through [member opener]
## (default OS.shell_open) and closes it. Escape, a click anywhere else and a
## second logo click close it. The logo is rasterised at runtime from the
## inlined M1 SVG, so the addon needs no import step and loads nothing.
const CreditData = preload("credit_data.gd")
@export var logo_size := 48
@export var placement_below := false
@export var align_start := false
@export var light := false:
set = _set_light
## Called with the URL when the panel is activated.
var opener: Callable
var logo: TextureButton
var panel: PanelContainer
var panel_logo: TextureRect
var label: Label
func _init() -> void:
opener = _shell_open
logo = TextureButton.new()
logo.texture_normal = _logo_texture(logo_size)
logo.ignore_texture_size = true
logo.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
logo.custom_minimum_size = Vector2(logo_size, logo_size)
logo.size = logo.custom_minimum_size
logo.focus_mode = Control.FOCUS_ALL
logo.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
logo.accessibility_name = CreditData.TEXT
logo.pressed.connect(_toggle)
add_child(logo)
panel = PanelContainer.new()
panel.visible = false
panel.focus_mode = Control.FOCUS_ALL
panel.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
panel.accessibility_name = CreditData.TEXT
panel.gui_input.connect(_on_panel_input)
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", CreditData.SPACE_SM)
row.mouse_filter = Control.MOUSE_FILTER_IGNORE
panel_logo = TextureRect.new()
panel_logo.texture = logo.texture_normal
panel_logo.mouse_filter = Control.MOUSE_FILTER_IGNORE
label = Label.new()
label.text = CreditData.TEXT
label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
label.mouse_filter = Control.MOUSE_FILTER_IGNORE
row.add_child(panel_logo)
row.add_child(label)
panel.add_child(row)
add_child(panel)
custom_minimum_size = logo.custom_minimum_size
size = custom_minimum_size
_apply_theme()
## True while the panel shows.
func is_open() -> bool:
return panel.visible
## Hide the panel.
func close() -> void:
panel.visible = false
func _input(event: InputEvent) -> void:
if not panel.visible:
return
if event is InputEventKey and event.pressed and event.keycode == KEY_ESCAPE:
close()
logo.grab_focus()
get_viewport().set_input_as_handled()
elif event is InputEventMouseButton and event.pressed:
var at: Vector2 = event.position
if not panel.get_global_rect().has_point(at) and not logo.get_global_rect().has_point(at):
close()
func _toggle() -> void:
if panel.visible:
close()
return
panel.reset_size()
var box := panel.get_combined_minimum_size()
var x := 0.0 if align_start else logo_size - box.x
var y := logo_size + CreditData.SPACE_SM if placement_below else -box.y - CreditData.SPACE_SM
panel.position = Vector2(x, y)
panel.visible = true
panel.grab_focus()
func _on_panel_input(event: InputEvent) -> void:
var clicked := (
event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT
)
if clicked or event.is_action_pressed("ui_accept"):
accept_event()
close()
opener.call(CreditData.URL)
func _set_light(value: bool) -> void:
light = value
_apply_theme()
func _apply_theme() -> void:
var pal: Dictionary = CreditData.LIGHT if light else CreditData.DARK
var box := StyleBoxFlat.new()
box.bg_color = pal["surface"]
box.border_color = pal["border"]
box.set_border_width_all(1)
box.set_corner_radius_all(CreditData.RADIUS)
box.set_content_margin_all(CreditData.SPACE_MD)
panel.add_theme_stylebox_override("panel", box)
var ring := StyleBoxFlat.new()
ring.draw_center = false
ring.border_color = CreditData.FOCUS
ring.set_border_width_all(2)
ring.set_corner_radius_all(CreditData.RADIUS)
ring.set_expand_margin_all(2)
logo.add_theme_stylebox_override("focus", ring)
panel.add_theme_stylebox_override("focus", ring)
label.add_theme_color_override("font_color", pal["text"])
label.add_theme_font_size_override("font_size", CreditData.TEXT_BODY)
func _shell_open(url: String) -> void:
OS.shell_open(url)
static func _logo_texture(px: int) -> ImageTexture:
var img := Image.new()
img.load_svg_from_string(CreditData.LOGO_SVG, float(px) / CreditData.LOGO_SIZE)
return ImageTexture.create_from_image(img)

View File

@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://addons/kuhy_credit/kuhy_credit.gd" id="1"]
[node name="KuhyCredit" type="Control"]
script = ExtResource("1")

View File

@ -0,0 +1,27 @@
extends Control
## Demo: a token-coloured screen with the credit in the bottom-right corner.
## Run with `godot --path kuhy_credit/godot` (add `-- --light` for light).
const CreditData = preload("res://addons/kuhy_credit/credit_data.gd")
const CreditScene = preload("res://addons/kuhy_credit/kuhy_credit.tscn")
var credit: Control
func _ready() -> void:
var is_light := OS.get_cmdline_user_args().has("--light")
var bg := ColorRect.new()
bg.color = (CreditData.LIGHT if is_light else CreditData.DARK)["bg"]
bg.mouse_filter = Control.MOUSE_FILTER_IGNORE
bg.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
add_child(bg)
credit = CreditScene.instantiate()
credit.light = is_light
add_child(credit)
_place()
resized.connect(_place)
func _place() -> void:
var margin := float(CreditData.SPACE_MD)
credit.position = size - credit.size - Vector2(margin, margin)

View File

@ -0,0 +1,10 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://demo/demo.gd" id="1"]
[node name="Demo" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
script = ExtResource("1")

33
kuhy_credit/godot/lint.sh Executable file
View File

@ -0,0 +1,33 @@
#!/bin/bash
# ============================================================================
# Lint of the kuhy_credit addon, demo and tests: gdlint (.gdlintrc, every check on)
# and gdformat --check. gdtoolkit is pinned in godot_dev_tools/requirements-dev.txt.
# ============================================================================
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly HERE
main() {
local tool files=()
for tool in gdlint gdformat; do
command -v "$tool" >/dev/null || {
echo "Error: $tool not found (pip install -r godot_dev_tools/requirements-dev.txt)" >&2
exit 1
}
done
mapfile -t files < <(find "$HERE/addons/kuhy_credit" "$HERE/demo" "$HERE/tests" -name '*.gd' -type f | sort)
# One process per tool, not xargs -P: parallel gdtoolkit processes race to
# create their grammar cache dir (os.makedirs EEXIST) on a cold cache and
# report a file as unopenable.
(cd "$HERE" && gdlint "${files[@]}" >/dev/null)
gdformat --check "${files[@]}" >/dev/null 2>&1 || {
gdformat --check "${files[@]}" 2>&1 | grep -v 'left unchanged' >&2 || true
exit 1
}
echo "kuhy_credit godot lint: ${#files[@]} files ok"
}
main "$@"

View File

@ -0,0 +1,20 @@
; Stub host for the kuhy_credit addon: GUT loads it headless, and
; demo/demo.tscn is the click-through demo. Games mount the addon folder.
config_version=5
[application]
config/name="kuhy_credit_test_host"
config/features=PackedStringArray("4.7", "GL Compatibility")
run/main_scene="res://demo/demo.tscn"
[display]
window/size/viewport_width=640
window/size/viewport_height=360
[rendering]
renderer/rendering_method="gl_compatibility"
renderer/rendering_method.mobile="gl_compatibility"

107
kuhy_credit/godot/test.sh Executable file
View File

@ -0,0 +1,107 @@
#!/bin/bash
# ============================================================================
# GUT tests of the kuhy_credit addon against the stub host project in this
# folder, headless and muted, one run under 60 s.
# kuhy_credit/godot/test.sh the whole suite
# kuhy_credit/godot/test.sh -gselect=test_kuhy_credit one file
# GUT is fetched at the pinned tag into addons/gut (gitignored): no third-party
# code is committed. user:// points at a throwaway folder,
# so no test ever writes where a real game saves.
# Fail closed: green only with exit 0, no SCRIPT ERROR, no failing test, at
# least one test and tests == passing + pending. Prints one summary line.
# ============================================================================
set -euo pipefail
readonly GUT_TAG="v9.7.1"
# Wall-clock cap per godot call, only when set (CI sets 50). Locally godot is a
# build-lock shim, and a cap around it would count the queue wait, not the run.
readonly RUN_TIMEOUT="${KUHY_CREDIT_GODOT_TIMEOUT:-}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly HERE
TMP=""
cleanup() {
[[ -z "$TMP" ]] || rm -rf "$TMP"
}
# Fetches GUT at GUT_TAG into addons/gut unless that version is already there.
ensure_gut() {
local gut_dir="$HERE/addons/gut" tmp
if [[ -f "$gut_dir/plugin.cfg" ]] && grep -q "\"${GUT_TAG#v}\"" "$gut_dir/plugin.cfg"; then
return
fi
tmp="$(mktemp -d)"
git -c advice.detachedHead=false clone -q --depth 1 --branch "$GUT_TAG" \
https://github.com/bitwes/Gut "$tmp/gut"
rm -rf "$gut_dir"
mv "$tmp/gut/addons/gut" "$gut_dir"
rm -rf "$tmp"
}
# Value of a GUT totals row ("Tests 59", "Passing Tests 59"...), 0 when absent.
total_of() {
local row="$1" out="$2"
awk -v row="$row" 'index($0, row) == 1 { v = $NF } END { print v + 0 }' <<<"$out"
}
# Runs godot under the resource cap kuhy's machine has, else plainly.
run_capped() {
local capped="$HOME/.claude/scripts/capped.sh"
if [[ -x "$capped" ]]; then
"$capped" "$@"
else
"$@"
fi
}
# Runs godot "$@" capped, and under RUN_TIMEOUT when one is set.
godot_run() {
local cmd=(godot "$@")
if [[ -n "$RUN_TIMEOUT" ]]; then
cmd=(timeout -k 3 "$RUN_TIMEOUT" "${cmd[@]}")
fi
run_capped "${cmd[@]}"
}
main() {
command -v godot >/dev/null || {
echo "Error: godot 4.7.2 not on PATH" >&2
exit 1
}
ensure_gut
TMP="$(mktemp -d)"
trap cleanup EXIT
export XDG_DATA_HOME="$TMP/xdg"
# GUT's own class_names need a class cache before a script run.
godot_run --headless --path "$HERE" --import >/dev/null 2>&1 || true
local out code=0 start="$SECONDS"
out="$(godot_run --headless --audio-driver Dummy \
--path "$HERE" -s addons/gut/gut_cmdln.gd -gexit "$@" 2>&1)" || code=$?
local tests passing failing pending why=""
tests="$(total_of Tests "$out")"
passing="$(total_of "Passing Tests" "$out")"
failing="$(total_of "Failing Tests" "$out")"
pending="$(total_of "Risky/Pending" "$out")"
if [[ "$code" -eq 124 || "$code" -eq 137 || "$code" -eq 143 ]]; then
why="timed out or killed after ${RUN_TIMEOUT}s (exit $code)"
elif grep -qE 'SCRIPT ERROR|Failing Tests' <<<"$out" || ((failing > 0)); then
why="failing tests or a script error"
elif ((code != 0)); then
why="exit code $code"
elif ((tests == 0)); then
why="no tests ran"
elif ((tests != passing + pending)); then
why="tests $tests != passing $passing + pending $pending"
fi
local line="$tests tests, $passing pass, $failing fail, $pending pending, $((SECONDS - start))s"
if [[ -n "$why" ]]; then
echo "$out" | tail -60 >&2
echo "kuhy_credit godot: FAILED ($why; $line)" >&2
exit 1
fi
echo "kuhy_credit godot: green ($line)"
}
main "$@"

View File

@ -0,0 +1,31 @@
extends GutTest
## E2E: the demo scene, two clicks through the viewport, the URL that would open.
const CreditData = preload("res://addons/kuhy_credit/credit_data.gd")
const Demo = preload("res://demo/demo.tscn")
func _click(at: Vector2) -> void:
for pressed in [true, false]:
var ev := InputEventMouseButton.new()
ev.button_index = MOUSE_BUTTON_LEFT
ev.pressed = pressed
ev.position = at
ev.global_position = at
get_viewport().push_input(ev)
await wait_process_frames(2)
func test_two_clicks_open_the_website() -> void:
var demo: Control = Demo.instantiate()
add_child_autofree(demo)
await wait_process_frames(2)
var opened: Array[String] = []
demo.credit.opener = func(url: String) -> void: opened.append(url)
assert_false(demo.credit.is_open())
await _click(demo.credit.logo.get_global_rect().get_center())
assert_true(demo.credit.is_open())
assert_eq(opened, [] as Array[String])
await _click(demo.credit.panel.get_global_rect().get_center())
assert_eq(opened, [CreditData.URL] as Array[String])
assert_false(demo.credit.is_open())

View File

@ -0,0 +1,143 @@
extends GutTest
## The credit control: logo -> panel -> URL, every close path, theme tokens.
## Input goes through the viewport (push_input), as a real click would.
const CreditData = preload("res://addons/kuhy_credit/credit_data.gd")
const Scene = preload("res://addons/kuhy_credit/kuhy_credit.tscn")
var credit: Control
var opened: Array[String] = []
func before_each() -> void:
opened.clear()
credit = Scene.instantiate()
credit.opener = func(url: String) -> void: opened.append(url)
credit.position = Vector2(500, 260)
add_child_autofree(credit)
await wait_process_frames(2)
func _click_at(pos: Vector2) -> void:
for pressed in [true, false]:
var ev := InputEventMouseButton.new()
ev.button_index = MOUSE_BUTTON_LEFT
ev.pressed = pressed
ev.position = pos
ev.global_position = pos
get_viewport().push_input(ev)
await wait_process_frames(2)
func _click(control: Control) -> void:
await _click_at(control.get_global_rect().get_center())
func _key(code: Key) -> void:
for pressed in [true, false]:
var ev := InputEventKey.new()
ev.keycode = code
ev.physical_keycode = code
ev.pressed = pressed
get_viewport().push_input(ev)
await wait_process_frames(2)
func test_shows_only_the_logo_at_start() -> void:
assert_true(credit.logo.visible)
assert_false(credit.panel.visible)
assert_not_null(credit.logo.texture_normal)
assert_eq(credit.logo.accessibility_name, CreditData.TEXT)
assert_eq(opened, [] as Array[String])
func test_logo_click_opens_panel_with_logo_and_text() -> void:
await _click(credit.logo)
assert_true(credit.is_open())
assert_eq(credit.label.text, CreditData.TEXT)
assert_not_null(credit.panel_logo.texture)
assert_eq(opened, [] as Array[String])
func test_panel_click_opens_the_url_and_closes() -> void:
await _click(credit.logo)
await _click(credit.label)
assert_eq(opened, [CreditData.URL] as Array[String])
assert_false(credit.is_open())
func test_escape_closes_without_opening() -> void:
await _click(credit.logo)
await _key(KEY_ESCAPE)
assert_false(credit.is_open())
assert_true(credit.logo.has_focus())
assert_eq(opened, [] as Array[String])
func test_outside_click_closes() -> void:
await _click(credit.logo)
await _click_at(Vector2(10, 10))
assert_false(credit.is_open())
assert_eq(opened, [] as Array[String])
func test_second_logo_click_closes_and_stays_closed() -> void:
await _click(credit.logo)
await _click(credit.logo)
assert_false(credit.is_open())
assert_eq(opened, [] as Array[String])
func test_keyboard_reaches_and_opens() -> void:
assert_eq(credit.logo.focus_mode, Control.FOCUS_ALL)
credit.logo.grab_focus()
await _key(KEY_ENTER)
assert_true(credit.is_open())
assert_true(credit.panel.has_focus())
await _key(KEY_ENTER)
assert_eq(opened, [CreditData.URL] as Array[String])
func test_other_input_is_ignored() -> void:
await _key(KEY_ESCAPE)
await _click_at(Vector2(10, 10))
assert_false(credit.is_open())
await _click(credit.logo)
await _key(KEY_A)
assert_true(credit.is_open())
func test_panel_sits_above_and_end_aligned_by_default() -> void:
await _click(credit.logo)
var p: Rect2 = credit.panel.get_global_rect()
var l: Rect2 = credit.logo.get_global_rect()
assert_lt(p.end.y, l.position.y)
assert_almost_eq(p.end.x, l.end.x, 0.5)
func test_below_and_start_placement() -> void:
credit.placement_below = true
credit.align_start = true
await _click(credit.logo)
var p: Rect2 = credit.panel.get_global_rect()
var l: Rect2 = credit.logo.get_global_rect()
assert_gt(p.position.y, l.end.y)
assert_almost_eq(p.position.x, l.position.x, 0.5)
func test_theme_colours_come_from_tokens() -> void:
var box: StyleBoxFlat = credit.panel.get_theme_stylebox("panel")
assert_eq(box.bg_color, CreditData.DARK.surface)
assert_eq(box.border_color, CreditData.DARK.border)
assert_eq(box.corner_radius_top_left, CreditData.RADIUS)
credit.light = true
box = credit.panel.get_theme_stylebox("panel")
assert_eq(box.bg_color, CreditData.LIGHT.surface)
assert_eq(credit.label.get_theme_color("font_color"), CreditData.LIGHT.text)
func test_default_opener_is_shell_open() -> void:
var fresh: Control = Scene.instantiate()
assert_true(fresh.opener.is_valid())
assert_eq(fresh.opener.get_method(), &"_shell_open")
fresh.free()

View File

@ -1,4 +1,4 @@
"""The shared "Created by kuhy" credit for Python programs.
"""The shared kuhy credit for Python programs.
``credit_line()`` is the terminal form; :mod:`kuhy_credit.tk` holds the
Tkinter logo widget. The words and the link come from the generated

View File

@ -132,8 +132,8 @@ LOGO_SHAPES: tuple[tuple[str, tuple[float, ...]], ...] = (
),
),
)
DARK = {"surface": "#2b2624", "border": "#463e3a", "text": "#eceae9"}
LIGHT = {"surface": "#fcfbfb", "border": "#e0dad7", "text": "#211d1b"}
DARK = {"bg": "#211d1b", "surface": "#2b2624", "border": "#463e3a", "text": "#eceae9"}
LIGHT = {"bg": "#f6f4f3", "surface": "#fcfbfb", "border": "#e0dad7", "text": "#211d1b"}
FOCUS = "#b8862e"
RADIUS = 12
SPACE_SM = 8

View File

@ -23,7 +23,7 @@ def build(
) -> KuhyCredit:
"""Fill ``root`` with a themed demo window and return its credit."""
root.geometry("640x400")
root.configure(bg=(DARK if theme == "dark" else LIGHT)["surface"])
root.configure(bg=(DARK if theme == "dark" else LIGHT)["bg"])
credit = KuhyCredit(root, theme=theme, opener=opener)
credit.place(relx=1.0, rely=1.0, x=-SPACE_MD, y=-SPACE_MD, anchor="se")
return credit

View File

@ -1,4 +1,4 @@
"""The Tkinter credit: an M1 logo button that opens a "Created by kuhy" panel.
"""The Tkinter credit: an M1 logo button that opens a credit-text panel.
credit = KuhyCredit(parent) # a Canvas: pack/grid/place it
credit.place(relx=1, rely=1, anchor="se")

View File

@ -32,6 +32,8 @@ ignore = ["D203", "D213", "COM812", "ISC001", "S603", "S607", "CPY001"]
[tool.ruff.lint.per-file-ignores]
"tests/*.py" = ["ANN", "ARG", "D", "TC", "PLC0415", "PLR2004", "S101", "SLF001", "E501"]
"kuhy_credit/_data.py" = ["E501"]
# E2E drivers: scripts that assert and print, not library code.
"e2e/*.py" = ["ANN", "D", "TC", "E501", "EM", "INP001", "S101", "S603", "T201", "TRY003", "PLR2004"]
# The generator and the terminal helper are CLIs: printing is their output.
"generator/generate.py" = ["T201"]
"kuhy_credit/terminal.py" = ["T201"]

View File

@ -0,0 +1,4 @@
# Exact pins, newest stable (shared dependency-freshness gate).
pytest==9.2.0
pytest-cov==7.1.0
ruff==0.17.6

View File

@ -1,13 +1,45 @@
"""A real Tk root per test. Run under xvfb-run, never on kuhy's display."""
"""A real Tk root per test, always on a private Xvfb display.
The session starts its own Xvfb and points DISPLAY at it, so a plain
``pytest`` run never opens windows on the desktop it was started from.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import tkinter as tk
from collections.abc import Iterator
import pytest
@pytest.fixture(scope="session", autouse=True)
def private_display() -> Iterator[None]:
xvfb = shutil.which("Xvfb")
if xvfb is None:
pytest.exit("Xvfb is required (the Tk tests never use the real display)", 2)
read, write = os.pipe()
proc = subprocess.Popen(
[xvfb, "-displayfd", str(write), "-screen", "0", "1600x1200x24", "-nolisten", "tcp"],
pass_fds=(write,),
stderr=subprocess.DEVNULL,
)
os.close(write)
with os.fdopen(read) as fd:
number = fd.readline().strip()
old = os.environ.get("DISPLAY")
os.environ["DISPLAY"] = f":{number}"
yield
if old is None:
os.environ.pop("DISPLAY", None)
else:
os.environ["DISPLAY"] = old
proc.terminate()
proc.wait(10)
@pytest.fixture
def root() -> Iterator[tk.Tk]:
win = tk.Tk()

View File

@ -47,6 +47,7 @@ def test_missing_field_is_rejected() -> None:
def test_tokens_read_dark_and_light_from_css() -> None:
tok = tokens.parse_tokens((REPO_ROOT / "web_ui/src/tokens.css").read_text())
assert (tok.dark.bg, tok.light.bg) == ("#211d1b", "#f6f4f3")
assert tok.dark.surface == "#2b2624"
assert tok.light.surface == "#fcfbfb"
assert tok.dark.text == "#eceae9"
@ -118,7 +119,7 @@ def test_main_writes_without_check(copy: Path, capsys: pytest.CaptureFixture[str
def test_css_without_root_is_rejected() -> None:
with pytest.raises(ValueError, match="--surface-1"):
with pytest.raises(ValueError, match="--bg"):
tokens.parse_tokens("")
@ -127,3 +128,33 @@ def test_whole_numbers_keep_a_decimal_point() -> None:
assert emit._num(12.0) == "12.0"
assert emit._num(12.5) == "12.5"
HAND_WRITTEN = [
"kuhy_credit/__init__.py",
"kuhy_credit/tk.py",
"kuhy_credit/demo.py",
"web/src/kuhy-credit.js",
"web/demo/index.html",
"flutter/lib/src/kuhy_credit.dart",
"flutter/example/lib/main.dart",
"godot/addons/kuhy_credit/kuhy_credit.gd",
"godot/demo/demo.gd",
]
@pytest.mark.parametrize("rel", HAND_WRITTEN)
def test_hand_written_code_reads_the_constants(rel: str) -> None:
"""Only generated files may spell out the URL or the words."""
text = (CREDIT_DIR / rel).read_text()
data = json.loads((CREDIT_DIR / "credit.json").read_text())
assert data["url"] not in text
assert data["text"] not in text
def test_gdscript_strings_follow_gdformat_quoting() -> None:
from generator import emit
assert emit._gd_str('a"b') == "'a\"b'"
assert emit._gd_str("a'b\"") == '"a\'b\\""'
assert emit._gd_str("plain") == '"plain"'

View File

@ -51,6 +51,8 @@ def test_panel_click_opens_the_url_and_closes(root, opener, target: str) -> None
def test_escape_closes_without_opening(root, opener) -> None:
credit = _make(root, opener)
_click(credit)
credit.panel.focus_force()
root.update()
credit.panel.event_generate("<Escape>")
root.update()
assert not credit.is_open

View File

@ -0,0 +1,21 @@
<!doctype html>
<!-- Plain-HTML demo. Serve the repo root (python3 -m http.server -d ../../..)
and open /kuhy_credit/web/demo/index.html; add ?theme=light or ?theme=dark
to force a theme, otherwise it follows the system. -->
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>kuhy-credit demo</title>
<link rel="stylesheet" href="/web_ui/src/tokens.css" />
<style>
html, body { height: 100%; margin: 0; background: var(--bg); }
footer { position: fixed; right: var(--space-3); bottom: var(--space-3); }
</style>
<script type="module" src="../src/kuhy-credit.js"></script>
<script type="module" src="./theme.js"></script>
</head>
<body>
<footer><kuhy-credit></kuhy-credit></footer>
</body>
</html>

View File

@ -0,0 +1,8 @@
// ?theme=light|dark forces both the page tokens and the credit's theme.
const theme = new URLSearchParams(location.search).get("theme");
if (theme === "light" || theme === "dark") {
document.documentElement.style.colorScheme = theme;
document.querySelector("kuhy-credit").setAttribute("theme", theme);
const surface = { dark: "#211d1b", light: "#f6f4f3" }[theme];
document.body.style.background = surface;
}

View File

@ -0,0 +1,36 @@
{
"name": "@kuhyx/kuhy-credit",
"version": "0.1.0",
"private": false,
"type": "module",
"description": "<kuhy-credit>: the shared 'Created by kuhy' logo credit as a dependency-free custom element.",
"license": "MIT",
"engines": {
"node": ">=24",
"pnpm": ">=10"
},
"packageManager": "pnpm@12.21.0+sha512.66fd8278ee28935ce951792d34367ff3af5c432a2756445823029533835b8da529bbe0be5130afd56ed0713fb8789e47bad82d93bd5ae2fe54b15562d6276ef0",
"files": [
"src/kuhy-credit.js",
"src/kuhy-credit.d.ts",
"src/credit-data.js"
],
"main": "./src/kuhy-credit.js",
"types": "./src/kuhy-credit.d.ts",
"exports": {
".": {
"types": "./src/kuhy-credit.d.ts",
"default": "./src/kuhy-credit.js"
}
},
"scripts": {
"lint": "node --check src/kuhy-credit.js && node --check src/credit-data.js",
"test": "vitest run",
"coverage": "vitest run --coverage"
},
"devDependencies": {
"@vitest/coverage-v8": "5.1.1",
"jsdom": "31.0.1",
"vitest": "5.1.1"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -105,8 +105,8 @@ export const LOGO_SVG =
+ "139.77 376.54L138.77 382.07L138.23 387.76L138.29 393.51L139."
+ "06 399.17L140.59 404.59Z\"/>\n</svg>\n";
export const TOKENS = {
dark: { surface: "#2b2624", border: "#463e3a", text: "#eceae9" },
light: { surface: "#fcfbfb", border: "#e0dad7", text: "#211d1b" },
dark: { bg: "#211d1b", surface: "#2b2624", border: "#463e3a", text: "#eceae9" },
light: { bg: "#f6f4f3", surface: "#fcfbfb", border: "#e0dad7", text: "#211d1b" },
focus: "#b8862e",
radius: 12,
spaceSm: 8,

26
kuhy_credit/web/src/kuhy-credit.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
/** `<kuhy-credit>`: the shared "Created by kuhy" logo credit. */
export declare class KuhyCredit extends HTMLElement {
/** True while the panel is showing. */
readonly open: boolean;
/** Hide the panel. */
close(): void;
}
/** Attributes the element reads. */
export interface KuhyCreditAttributes {
align?: "end" | "start";
placement?: "above" | "below";
theme?: "dark" | "light";
}
declare global {
interface HTMLElementTagNameMap {
"kuhy-credit": KuhyCredit;
}
// React 19 / Vite: <kuhy-credit /> in JSX.
namespace JSX {
interface IntrinsicElements {
"kuhy-credit": KuhyCreditAttributes & { class?: string; className?: string };
}
}
}

View File

@ -0,0 +1,112 @@
/**
* `<kuhy-credit>`: the shared kuhy credit, dependency-free.
*
* Shows only the M1 logo. Click/Enter/Space on it opens a small panel (logo +
* the credit text); a click on the panel opens the website in a new tab.
* Escape, a click anywhere else and a second logo click close the panel.
* Nothing loads over the network: the logo is inlined from credit-data.js,
* which the generator writes from kuhy_credit/credit.json and the M1 art.
*
* Attributes: `placement="above|below"` (default above), `align="end|start"`
* (default end), `theme="light|dark"` (default: follow the page). Size via the
* `--kuhy-credit-size` custom property (default 48px).
*/
import { CREDIT_TEXT, CREDIT_URL, LOGO_SVG, TOKENS } from "./credit-data.js";
const { dark, light } = TOKENS;
const palette = (p, usePage) =>
["surface", "border", "text"]
.map((k) => {
const page = { surface: "--surface-1", border: "--border", text: "--text" }[k];
return `--kc-${k}: ${usePage ? `var(${page}, ${p[k]})` : p[k]};`;
})
.join(" ");
const STYLE = `
:host { position: relative; display: inline-block; ${palette(dark, true)}
--kc-size: var(--kuhy-credit-size, 48px); }
@media (prefers-color-scheme: light) { :host { ${palette(light, true)} } }
:host([theme="dark"]) { ${palette(dark, false)} }
:host([theme="light"]) { ${palette(light, false)} }
button, a { cursor: pointer; border-radius: var(--radius-sm, 8px); }
button { display: block; padding: 0; border: 0; background: none;
width: var(--kc-size); height: var(--kc-size); }
svg { display: block; width: 100%; height: 100%; border-radius: inherit; }
button:focus-visible, a:focus-visible {
outline: 2px solid var(--focus-ring, ${TOKENS.focus}); outline-offset: 2px; }
a { position: absolute; bottom: calc(100% + ${TOKENS.spaceSm}px); right: 0; z-index: 1000;
display: flex; align-items: center; gap: ${TOKENS.spaceSm}px; padding: ${TOKENS.spaceMd}px;
white-space: nowrap; text-decoration: none; color: var(--kc-text);
background: var(--kc-surface); border: 1px solid var(--kc-border);
border-radius: ${TOKENS.radius}px; box-shadow: var(--shadow-1, none);
font: ${TOKENS.textBody}px/1.5 var(--font-sans, system-ui, sans-serif); }
a[hidden] { display: none; }
a svg { width: var(--kc-size); height: var(--kc-size); flex: none; }
:host([placement="below"]) a { bottom: auto; top: calc(100% + ${TOKENS.spaceSm}px); }
:host([align="start"]) a { right: auto; left: 0; }
`;
export class KuhyCredit extends HTMLElement {
#logo;
#panel;
#onDocClick = (event) => {
if (this.open && !event.composedPath().includes(this)) this.close();
};
#onKey = (event) => {
if (this.open && event.key === "Escape") {
this.close();
this.#logo.focus();
}
};
connectedCallback() {
if (!this.shadowRoot) this.#build();
document.addEventListener("click", this.#onDocClick);
document.addEventListener("keydown", this.#onKey);
}
disconnectedCallback() {
document.removeEventListener("click", this.#onDocClick);
document.removeEventListener("keydown", this.#onKey);
}
/** True while the panel is showing. */
get open() {
return !this.#panel.hidden;
}
/** Hide the panel. */
close() {
this.#panel.hidden = true;
this.#logo.setAttribute("aria-expanded", "false");
}
#show() {
this.#panel.hidden = false;
this.#logo.setAttribute("aria-expanded", "true");
this.#panel.focus();
}
#build() {
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `<style>${STYLE}</style>
<button type="button" aria-expanded="false" aria-controls="panel"></button>
<a id="panel" hidden target="_blank" rel="noopener noreferrer"><span></span></a>`;
this.#logo = root.querySelector("button");
this.#panel = root.querySelector("a");
this.#logo.setAttribute("aria-label", CREDIT_TEXT);
this.#logo.innerHTML = LOGO_SVG;
this.#panel.href = CREDIT_URL;
this.#panel.insertAdjacentHTML("afterbegin", LOGO_SVG);
this.#panel.querySelector("span").textContent = CREDIT_TEXT;
for (const svg of root.querySelectorAll("svg")) svg.setAttribute("aria-hidden", "true");
this.#logo.addEventListener("click", () => (this.open ? this.close() : this.#show()));
this.#panel.addEventListener("click", (event) => {
event.preventDefault();
this.close();
window.open(CREDIT_URL, "_blank", "noopener,noreferrer");
});
}
}
if (!customElements.get("kuhy-credit")) customElements.define("kuhy-credit", KuhyCredit);

View File

@ -0,0 +1,132 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CREDIT_TEXT, CREDIT_URL, TOKENS } from "./credit-data.js";
import { KuhyCredit } from "./kuhy-credit.js";
let host;
let open;
const parts = () => ({
logo: host.shadowRoot.querySelector("button"),
panel: host.shadowRoot.querySelector("a"),
});
const click = (el) => el.dispatchEvent(new MouseEvent("click", { bubbles: true, composed: true, cancelable: true }));
const key = (el, k) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true, composed: true }));
beforeEach(() => {
open = vi.spyOn(window, "open").mockImplementation(() => null);
host = document.createElement("kuhy-credit");
document.body.append(host);
});
afterEach(() => {
document.body.replaceChildren();
vi.restoreAllMocks();
});
describe("<kuhy-credit>", () => {
it("registers once and shows only the logo", () => {
expect(customElements.get("kuhy-credit")).toBe(KuhyCredit);
const { logo, panel } = parts();
expect(logo.querySelector("svg")).not.toBeNull();
expect(logo.textContent.trim()).toBe("");
expect(panel.hidden).toBe(true);
expect(open).not.toHaveBeenCalled();
});
it("names the logo and the panel, and wires aria-expanded", () => {
const { logo, panel } = parts();
expect(logo.getAttribute("aria-label")).toBe(CREDIT_TEXT);
expect(logo.getAttribute("aria-expanded")).toBe("false");
expect(logo.getAttribute("aria-controls")).toBe(panel.id);
expect(panel.textContent.trim()).toBe(CREDIT_TEXT);
expect(panel.getAttribute("href")).toBe(CREDIT_URL);
expect(panel.querySelector("svg").getAttribute("aria-hidden")).toBe("true");
});
it("opens the panel on a logo click and the website on a panel click", () => {
const { logo, panel } = parts();
click(logo);
expect(panel.hidden).toBe(false);
expect(logo.getAttribute("aria-expanded")).toBe("true");
expect(host.open).toBe(true);
expect(open).not.toHaveBeenCalled();
click(panel.querySelector("span"));
expect(open).toHaveBeenCalledExactlyOnceWith(CREDIT_URL, "_blank", "noopener,noreferrer");
expect(panel.hidden).toBe(true);
});
it("closes on Escape and returns focus to the logo", () => {
const { logo, panel } = parts();
click(logo);
key(document, "Escape");
expect(panel.hidden).toBe(true);
expect(host.shadowRoot.activeElement).toBe(logo);
expect(open).not.toHaveBeenCalled();
});
it("ignores other keys and Escape while closed", () => {
const { logo, panel } = parts();
key(document, "Escape");
click(logo);
key(document, "Enter");
expect(panel.hidden).toBe(false);
});
it("closes on a click outside", () => {
const { logo, panel } = parts();
click(logo);
click(document.body);
expect(panel.hidden).toBe(true);
expect(open).not.toHaveBeenCalled();
});
it("ignores outside clicks while closed", () => {
click(document.body);
expect(parts().panel.hidden).toBe(true);
});
it("closes on a second logo click and stays closed", () => {
const { logo, panel } = parts();
click(logo);
click(logo);
expect(panel.hidden).toBe(true);
expect(open).not.toHaveBeenCalled();
});
it("focuses the panel link when it opens", () => {
const { logo, panel } = parts();
click(logo);
expect(host.shadowRoot.activeElement).toBe(panel);
});
it("stops listening once removed from the page", () => {
const { logo, panel } = parts();
click(logo);
host.remove();
click(document.body);
expect(panel.hidden).toBe(false);
});
it("does not redefine the element when loaded twice", async () => {
const again = await import("./kuhy-credit.js?again");
expect(customElements.get("kuhy-credit")).toBe(KuhyCredit);
expect(again.KuhyCredit).not.toBe(KuhyCredit);
});
it("builds its shadow DOM only once when re-attached", () => {
host.remove();
document.body.append(host);
expect(host.shadowRoot.querySelectorAll("button")).toHaveLength(1);
});
it("styles from the design tokens with dark and light fallbacks", () => {
const css = host.shadowRoot.querySelector("style").textContent;
for (const value of [TOKENS.dark.surface, TOKENS.light.surface, TOKENS.dark.text, TOKENS.light.text, TOKENS.focus]) {
expect(css).toContain(value);
}
expect(css).toContain("var(--surface-1");
expect(css).toContain("prefers-color-scheme: light");
expect(css).toContain(`${TOKENS.radius}px`);
});
});

View File

@ -0,0 +1,13 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
coverage: {
include: ["src/kuhy-credit.js"],
provider: "v8",
thresholds: { branches: 100, functions: 100, lines: 100, statements: 100 },
},
environment: "jsdom",
include: ["src/**/*.test.js"],
},
});

View File

@ -103,6 +103,7 @@ verify() {
check_tag game-recording game_recording
check_tag godot-dev-tools godot_dev_tools
check_tag app-errors app_errors
check_tag kuhy-credit kuhy_credit
check_sickdays
check_app_errors
if [[ "$FAILED" -ne 0 ]]; then