diff --git a/.claude/skills/create-pr/SKILL.md b/.claude/skills/create-pr/SKILL.md index 7840454d..99051c68 100644 --- a/.claude/skills/create-pr/SKILL.md +++ b/.claude/skills/create-pr/SKILL.md @@ -28,15 +28,20 @@ If the full diff is too large, diff individual areas (backend routes, frontend, ### 2. Write the PR file -Write the file to `.pr/YYYY-MM-DD.md` (using today's date). Create the `.pr/` directory if it doesn't exist. If a file for today's date already exists, append a counter: `YYYY-MM-DD-2.md`, `YYYY-MM-DD-3.md`, etc. +Write **two** files under `.pr/` (create the directory if it doesn't exist), sharing one base name from today's date: + +- `.pr/YYYY-MM-DD.title.txt` — the PR title, one line, nothing else. +- `.pr/YYYY-MM-DD.md` — the PR **body only**. It starts directly with the summary paragraph. + +If files for today's date already exist, append a counter to the base name: `YYYY-MM-DD-2`, `YYYY-MM-DD-3`, etc. + +**The body file must never contain the title.** No `# ` heading, no `Title:` line, no frontmatter, no "PR description:" preamble. GitHub already renders the title above the body, so anything title-like in the body file shows up twice — whoever opens the PR (you, another agent, or the user copy-pasting) pastes the body file verbatim and should not have to edit it. The structure depends on whether the PR introduces user-facing features or is purely internal (refactors, bug fixes, infra). #### When the PR has user-facing features: ~~~markdown -# <Title> - <4-6 sentence summary> ### Highlights @@ -58,8 +63,6 @@ The structure depends on whether the PR introduces user-facing features or is pu #### When the PR is purely internal (no user-facing features): ~~~markdown -# <Title> - <4-6 sentence summary> <details> @@ -82,7 +85,7 @@ Omit the Highlights section entirely for internal-only PRs — don't force it. - Bad: `feat(dns): add cloudflare provisioning` · `fix: subprocess injection` · `chore(deps): bump` - Capitalize the first word like a sentence; imperative or plain-descriptive are both fine; no trailing period. Keep it under ~70 chars. - Leading with the subsystem and a colon in plain words is fine when it aids scanning: `Backend: …`, `Extensions: …`. -- The `# <Title>` line at the top of the generated file **is** the PR title — when the PR is eventually opened, that same string is the `gh pr create --title` value. Don't write a second, different headline. +- The title lives **only** in the `.title.txt` file — that string is the `gh pr create --title` value. Don't repeat it, or a variant of it, as a headline in the body file. - **Where the release weight actually lives (so you can safely keep it out of the title):** `version-bump.yml` reads the *commit message* pushed to `dev` (`github.event.head_commit.message`), **not this title.** A `feat:`/`feature:`/`minor:` prefix or a `[minor]` tag in the commit → minor bump; `BREAKING:`/`major:` or `[major]` → major; anything else → patch. Put any bump intent in your **commits**; leave the PR title human. #### Summary @@ -123,6 +126,16 @@ Omit the Highlights section entirely for internal-only PRs — don't force it. - **No emoji.** - **No "Generated by" footer.** -### 3. Stop after writing the file +### 3. Stop after writing the files -This skill's job ends when the `.pr/` file is written. **Do not** run `gh pr create`, `git push`, or any other remote-affecting command to actually open the PR — that's a separate, explicit step the user requests on its own. Print the path of the file you wrote and a one-line note that it's ready to review/copy. +This skill's job ends when the `.pr/` files are written. **Do not** run `gh pr create`, `git push`, or any other remote-affecting command to actually open the PR — that's a separate, explicit step the user requests on its own. Print the title, the paths of both files, and a one-line note that they're ready to review/copy. + +### 4. Opening the PR (only when the user explicitly asks) + +Pass the two files separately — never derive the body from a file that has a heading in it: + +```bash +gh pr create --base main --head dev --title "$(cat .pr/YYYY-MM-DD.title.txt)" --body-file .pr/YYYY-MM-DD.md +``` + +Before running it, check the first line of the body file: if it is a `#` heading or repeats the title, delete that line first. After creating, run `gh pr view --json title,body -q .body | head -3` and confirm the body does not start with the title. diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 2b0ab8fd..db67f8e1 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -1,13 +1,34 @@ #!/bin/sh -# ServerKit pre-commit hook — lints staged frontend JS/JSX and blocks the commit -# on ESLint ERRORS only (warnings are allowed). It exits early for commits that -# touch no frontend JS/JSX (backend, SCSS, docs), so it never gets in the way of -# those. Enable once per clone with: +# ServerKit pre-commit hook — blocks internal plan citations in any staged app +# file, then lints staged frontend JS/JSX and blocks the commit on ESLint +# ERRORS only (warnings are allowed). The lint half exits early for commits +# that touch no frontend JS/JSX (backend, SCSS, docs). Enable once per clone with: # # git config core.hooksPath .githooks # # (Or run frontend/setup-hooks.sh.) +# Plan-citation guard: same patterns and allowlist as +# backend/tests/test_no_plan_references.py, run on the staged blobs of every +# file type (SCSS and Python included) so CI never has to catch it. +# First interpreter that actually runs (Windows ships a python3 stub that +# only opens the Store); none found means the CI test still covers it. +py="" +for candidate in python3 python; do + if "$candidate" -c 'import sys; sys.exit(sys.version_info < (3, 8))' 2>/dev/null; then + py=$candidate + break + fi +done +if [ -n "$py" ]; then + if ! "$py" backend/tests/test_no_plan_references.py --staged; then + echo "" + echo "✖ Commit blocked: remove the plan reference(s) above." + echo " To bypass for an emergency commit: git commit --no-verify" + exit 1 + fi +fi + files=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^frontend/src/.*\.(js|jsx)$' || true) [ -z "$files" ] && exit 0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 27e2f9df..8e447d1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,12 @@ release history; historical `agent-v*` tags are not panel releases. ### Fixed +- The Docker tab on a server's detail page lists that server's images by + name and tag again, with readable sizes and dates. The agent reports + images as `repo_tags`, byte counts and epoch seconds, but the tab read + the CLI fields, so every row showed `<none>` and raw numbers. It now + uses the Docker page's image accessors, moved to `dockerHelpers.js`. + - Importing a Git repository that has a `docker-compose.yml` now deploys the compose project — every service it declares — instead of building only its Dockerfile, which started the web container without its database. diff --git a/VERSION b/VERSION index 0ce40b95..32bf4405 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.26 +1.11.27 diff --git a/backend/tests/test_no_plan_references.py b/backend/tests/test_no_plan_references.py index df4ba244..d7b5b1a0 100644 --- a/backend/tests/test_no_plan_references.py +++ b/backend/tests/test_no_plan_references.py @@ -4,6 +4,10 @@ Plans live in a git-ignored folder, so "(plan 29 #9)" in a comment points at nothing for anyone but its author — 680 of them had piled up, and one reached users in a bottleneck hint. Say what the code does and why; the history belongs in the commit message. + +The pre-commit hook runs this file directly (``--staged``) so a citation is +caught at commit time, on any file type, instead of in a CI shard minutes +after the push. """ import re import subprocess @@ -33,6 +37,11 @@ def _tracked(): return [p for p in out.decode().split('\0') if p and p not in EXCLUDED] +def _hits(text): + return (len(PLAN_REF.findall(text)) + len(SPLIT_REF.findall(text)) + + len(SECTION_REF.findall(text))) + + def _counts(): found = {} for rel in _tracked(): @@ -40,8 +49,27 @@ def _counts(): text = (REPO / rel).read_text(encoding='utf-8') except (UnicodeDecodeError, FileNotFoundError): continue - hits = (len(PLAN_REF.findall(text)) + len(SPLIT_REF.findall(text)) - + len(SECTION_REF.findall(text))) + hits = _hits(text) + if hits: + found[rel] = hits + return found + + +def _staged_counts(): + """Hits in the staged (index) version of each staged file under ROOTS.""" + out = subprocess.run(['git', 'diff', '--cached', '--name-only', '-z', + '--diff-filter=ACMR', '--', *ROOTS], cwd=REPO, + capture_output=True, check=True).stdout + found = {} + for rel in out.decode().split('\0'): + if not rel or rel in EXCLUDED: + continue + blob = subprocess.run(['git', 'show', f':{rel}'], cwd=REPO, + capture_output=True, check=True).stdout + try: + hits = _hits(blob.decode('utf-8')) + except UnicodeDecodeError: + continue if hits: found[rel] = hits return found @@ -58,3 +86,15 @@ def test_pending_list_is_not_stale(): counts = _counts() stale = {rel: n for rel, n in PENDING.items() if counts.get(rel, 0) < n} assert not stale, f'Lower or remove these PENDING entries: {stale} (now {counts})' + + +if __name__ == '__main__': + import sys + counts = _staged_counts() if '--staged' in sys.argv else _counts() + over = {rel: n for rel, n in counts.items() if n > PENDING.get(rel, 0)} + for rel, n in sorted(over.items()): + print(f'{rel}: {n} internal plan reference(s), e.g. "plan 92" or a bare section sign') + if over: + print('Plans are git-ignored, so these point at nothing. Say what the code ' + 'does instead; the history belongs in the commit message.') + sys.exit(1 if over else 0) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index c4b33f12..6d825a2e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -14,10 +14,13 @@ "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-popover": "^1.1.15", + "@radix-ui/react-radio-group": "^1.5.1", "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-slider": "^1.6.1", "@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.4.1", "@xterm/addon-fit": "^0.10.0", "@xterm/addon-web-links": "^0.11.0", "@xterm/xterm": "^5.5.0", @@ -1371,6 +1374,319 @@ } } }, + "node_modules/@radix-ui/react-radio-group": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.5.1.tgz", + "integrity": "sha512-QbyVT1ddnjqB9H+CUYKkNWdU9fIK3QHCYtjf7mS6ekSqiuXkWtWn5UZW9mhA8qtl3vrVyIsmR9gePstAtKrqkw==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-roving-focus": "1.2.1", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-roving-focus": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.2.1.tgz", + "integrity": "sha512-UwraORzVUeEPMclhO1p0vz0qI+TbdDLO9i+FiOqhJyHKwdpCRCck9yVEscUnAMIzCiuNoQa8D4A9bIpOPXGt6Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-is-hydrated": "0.1.3", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-radio-group/node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-roving-focus": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz", @@ -1463,6 +1779,234 @@ } } }, + "node_modules/@radix-ui/react-slider": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.6.1.tgz", + "integrity": "sha512-IRNRR90moPqxfwCJ0XbMJIxo70W0/1ZExT/sNCxEHMaPx0SF9HoQrcPEC75+H28cFKa0b+KH63anfLYJmwKacw==", + "license": "MIT", + "dependencies": { + "@radix-ui/number": "1.1.3", + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-collection": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-direction": "1.2.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/number": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.3.tgz", + "integrity": "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-collection": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.2.0.tgz", + "integrity": "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-direction": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.2.0.tgz", + "integrity": "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slider/node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-slot": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz", @@ -1540,6 +2084,427 @@ } } }, + "node_modules/@radix-ui/react-tooltip": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.4.1.tgz", + "integrity": "sha512-NxLFGSFtZ78zVfcoOhTwR1xwqo5qx1Jh8Pw6FMZ9McCaqfRzz7/gIRahs2Oy5XlPgQ+8QkUcKbN5B0U44J/kCg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-dismissable-layer": "1.2.1", + "@radix-ui/react-focus-scope": "1.3.1", + "@radix-ui/react-id": "1.1.4", + "@radix-ui/react-popper": "1.4.0", + "@radix-ui/react-portal": "1.2.0", + "@radix-ui/react-presence": "1.1.11", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-slot": "1.5.0", + "@radix-ui/react-use-controllable-state": "1.3.0", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-visually-hidden": "1.2.13" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.2.0.tgz", + "integrity": "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==", + "license": "MIT" + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-arrow": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.17.tgz", + "integrity": "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.5.tgz", + "integrity": "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-context": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.3.0.tgz", + "integrity": "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-dismissable-layer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.2.1.tgz", + "integrity": "sha512-KIfDcAsx+oVylFZ4xryVKusJUrLLhTQmfnJW4kwk4Km5myvhHCrj04hnWWUC166+xD4DHdH8tQGylwYX1h6+Pg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-effect-event": "0.0.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-focus-scope": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.3.1.tgz", + "integrity": "sha512-ugeMhbXt4y5S2T1GnIqbWDKEN962PDwnX1fN0eKOOgf5f63Dh2mn8F1FUySlgW0iF6GiVsRF32DzuDIWTUyQJg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-id": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.4.tgz", + "integrity": "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-popper": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.4.0.tgz", + "integrity": "sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.0.0", + "@radix-ui/react-arrow": "1.1.17", + "@radix-ui/react-compose-refs": "1.1.5", + "@radix-ui/react-context": "1.3.0", + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-callback-ref": "1.1.5", + "@radix-ui/react-use-layout-effect": "1.1.4", + "@radix-ui/react-use-rect": "1.1.4", + "@radix-ui/react-use-size": "1.1.5", + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-portal": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.2.0.tgz", + "integrity": "sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-presence": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.11.tgz", + "integrity": "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-primitive": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.2.0.tgz", + "integrity": "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-slot": "1.5.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-slot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.5.0.tgz", + "integrity": "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.5" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-callback-ref": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.5.tgz", + "integrity": "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-controllable-state": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.3.0.tgz", + "integrity": "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==", + "license": "MIT", + "dependencies": { + "@radix-ui/primitive": "1.2.0", + "@radix-ui/react-use-effect-event": "0.0.5", + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-effect-event": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.5.tgz", + "integrity": "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-layout-effect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.4.tgz", + "integrity": "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-rect": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.4.tgz", + "integrity": "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==", + "license": "MIT", + "dependencies": { + "@radix-ui/rect": "1.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-use-size": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-size/-/react-use-size-1.1.5.tgz", + "integrity": "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-use-layout-effect": "1.1.4" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-visually-hidden": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.13.tgz", + "integrity": "sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-primitive": "2.2.0" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/rect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.3.tgz", + "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", + "license": "MIT" + }, "node_modules/@radix-ui/react-use-callback-ref": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz", @@ -1610,6 +2575,21 @@ } } }, + "node_modules/@radix-ui/react-use-is-hydrated": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.3.tgz", + "integrity": "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-use-layout-effect": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 8e5f9374..f6fcfc5b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -50,10 +50,13 @@ "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-popover": "^1.1.15", + "@radix-ui/react-radio-group": "^1.5.1", "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-slider": "^1.6.1", "@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.4.1", "@xterm/addon-fit": "^0.10.0", "@xterm/addon-web-links": "^0.11.0", "@xterm/xterm": "^5.5.0", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index fd512ad9..f632fc84 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -12,6 +12,7 @@ import { WorkspaceProvider } from './contexts/WorkspaceContext'; import { rememberRedirect } from './utils/redirectAfterLogin'; import { TUNNEL_BASE } from './services/tunnelBase.js'; import { Toaster } from './components/ui/sonner'; +import { TooltipProvider } from './components/ui/tooltip'; import ThemeSync from './components/ThemeSync'; import LocaleSync from './components/LocaleSync'; import DashboardLayout from './layouts/DashboardLayout'; @@ -264,9 +265,11 @@ function App() { <LocaleSync /> <ResourceTierProvider> <ToastProvider> - <NotificationsProvider> - <AppRoutes /> - </NotificationsProvider> + <TooltipProvider> + <NotificationsProvider> + <AppRoutes /> + </NotificationsProvider> + </TooltipProvider> <Toaster /> </ToastProvider> </ResourceTierProvider> diff --git a/frontend/src/components/FormField.jsx b/frontend/src/components/FormField.jsx index 98dffb56..4ec2a80a 100644 --- a/frontend/src/components/FormField.jsx +++ b/frontend/src/components/FormField.jsx @@ -1,12 +1,20 @@ +import { useId, useMemo } from 'react'; import { Label } from '@/components/ui/label'; +import { FieldContext } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; /** * Standard form field wrapper: label, hint, error message, and input slot. * - * <FormField label="Email" htmlFor="email" error="Required" hint="Used for notifications"> - * <Input id="email" ... /> + * <FormField label="Email" error="Required" hint="Used for notifications"> + * <Input ... /> * </FormField> + * + * The control inside receives the field's id, `aria-describedby` (hint or + * error), `aria-invalid` and `aria-required` through FieldContext, so a + * screen reader announces the hint and the validation message with the field. + * Every control in components/ui reads it; `htmlFor` is only needed when the + * control already has its own id. One control per field. */ export function FormField({ label, @@ -18,10 +26,22 @@ export function FormField({ className, labelClassName, }) { - const inputId = htmlFor; + const autoId = useId(); + const inputId = htmlFor || `${autoId}control`; + const hintId = `${autoId}hint`; + const errorId = `${autoId}error`; + const invalid = Boolean(error); + const showHint = Boolean(hint) && !invalid; + + const field = useMemo(() => ({ + id: inputId, + describedBy: invalid ? errorId : (showHint ? hintId : undefined), + invalid, + required, + }), [inputId, invalid, showHint, errorId, hintId, required]); return ( - <div className={cn('form-field', className)}> + <div className={cn('form-field', invalid && 'form-field--invalid', className)}> {label && ( <Label htmlFor={inputId} className={cn('form-field__label', labelClassName)}> {label} @@ -29,10 +49,12 @@ export function FormField({ </Label> )} <div className="form-field__control"> - {children} + <FieldContext.Provider value={field}> + {children} + </FieldContext.Provider> </div> - {hint && !error && <p className="form-field__hint">{hint}</p>} - {error && <p className="form-field__error" role="alert">{error}</p>} + {showHint && <p id={hintId} className="form-field__hint">{hint}</p>} + {invalid && <p id={errorId} className="form-field__error" role="alert">{error}</p>} </div> ); } diff --git a/frontend/src/components/IconButton.jsx b/frontend/src/components/IconButton.jsx index 0ff80fd2..f503ba6d 100644 --- a/frontend/src/components/IconButton.jsx +++ b/frontend/src/components/IconButton.jsx @@ -1,9 +1,12 @@ import { Button } from '@/components/ui/button'; +import { Tip } from '@/components/ui/tooltip'; import { cn } from '@/lib/utils'; /** - * Accessible icon-only button. Always provide a descriptive label; it is used - * for the aria-label and optional title. + * Accessible icon-only button. Always provide a descriptive label; it is the + * aria-label and the tooltip (a real one, shown on hover and keyboard focus, + * unlike `title`). `title` overrides the tooltip text; `shortcut` adds a key + * hint to it. * * <IconButton icon={<RefreshCw size={16} />} label="Refresh" onClick={load} /> */ @@ -15,23 +18,25 @@ export function IconButton({ size = 'sm', className, title, + shortcut, disabled, ...props }) { return ( - <Button - type="button" - variant={variant} - size="icon" - className={cn('icon-button', size === 'sm' && 'btn-sm', className)} - onClick={onClick} - disabled={disabled} - aria-label={label} - title={title || label} - {...props} - > - {icon} - </Button> + <Tip content={title || label} shortcut={shortcut}> + <Button + type="button" + variant={variant} + size="icon" + className={cn('icon-button', size === 'sm' && 'btn-sm', className)} + onClick={onClick} + disabled={disabled} + aria-label={label} + {...props} + > + {icon} + </Button> + </Tip> ); } diff --git a/frontend/src/components/ProgressBar.jsx b/frontend/src/components/ProgressBar.jsx index b528bd13..900c01b5 100644 --- a/frontend/src/components/ProgressBar.jsx +++ b/frontend/src/components/ProgressBar.jsx @@ -1,9 +1,51 @@ +import { cn } from '@/lib/utils'; -export function ProgressBar({ percent = 0, color, className = '' }) { +const TONES = new Set(['accent', 'success', 'warning', 'danger', 'info']); + +/** + * Determinate or indeterminate progress, announced as a progressbar. + * + * <ProgressBar percent={48} label="Disk" valueText="48 of 100 GB" /> + * <ProgressBar percent={92} tone="danger" size="md" /> + * <ProgressBar indeterminate label="Pulling image" /> + * + * `label` names it for screen readers (pass `aria-labelledby` instead when a + * visible label sits next to it). `tone` picks a semantic colour; `color` is + * the legacy raw-colour escape hatch and wins when both are set. + */ +export function ProgressBar({ + percent = 0, + tone, + color, + size = 'sm', + indeterminate = false, + label, + valueText, + className = '', + ...props +}) { const clamped = Math.max(0, Math.min(100, Number(percent) || 0)); - const fillStyle = { width: `${clamped}%`, ...(color && { background: color }) }; + const fillStyle = indeterminate + ? (color ? { background: color } : undefined) + : { width: `${clamped}%`, ...(color && { background: color }) }; return ( - <div className={`progress-bar ${className}`.trim()}> + <div + role="progressbar" + aria-label={label} + aria-valuemin={indeterminate ? undefined : 0} + aria-valuemax={indeterminate ? undefined : 100} + aria-valuenow={indeterminate ? undefined : Math.round(clamped)} + aria-valuetext={valueText} + aria-busy={indeterminate || undefined} + className={cn( + 'progress-bar', + size === 'md' && 'progress-bar--md', + TONES.has(tone) && `progress-bar--${tone}`, + indeterminate && 'progress-bar--indeterminate', + className, + )} + {...props} + > <div className="progress-fill" style={fillStyle} /> </div> ); diff --git a/frontend/src/components/docker/ImagesTab.jsx b/frontend/src/components/docker/ImagesTab.jsx index 4cae5802..754c746e 100644 --- a/frontend/src/components/docker/ImagesTab.jsx +++ b/frontend/src/components/docker/ImagesTab.jsx @@ -21,6 +21,11 @@ import { useTranslation } from 'react-i18next'; import { useServer, normalizeListResponse, + imageId, + imageRef, + imageSizeBytes, + imageSizeMb, + imageCreatedMs, } from './dockerHelpers'; import { toastError } from '@/utils/errorMessage'; import { formatDateTime } from '@/utils/intl'; @@ -38,67 +43,6 @@ export const PullImageButton = () => { ); }; -// The two transports describe the same image differently: `docker images` -// hands back repository/tag as separate strings, the agent hands back -// `repo_tags: ["nginx:latest"]` and nothing else. Every accessor below reads -// both, because a column that silently blanks on remote hosts is worse than no -// column at all. -const imageId = (image) => String(image.id || image.ID || '').replace(/^sha256:/, ''); - -const imageRef = (image) => { - if (image.repository || image.tag) { - return { repository: image.repository || '<none>', tag: image.tag || '<none>' }; - } - const first = Array.isArray(image.repo_tags) ? image.repo_tags[0] : null; - if (!first) return { repository: '<none>', tag: '<none>' }; - // A registry port ("registry:5000/app") puts a colon in the REPOSITORY - // half, so the last colon is only the tag separator when no '/' follows it. - const colon = first.lastIndexOf(':'); - if (colon > 0 && !first.slice(colon).includes('/')) { - return { repository: first.slice(0, colon), tag: first.slice(colon + 1) }; - } - return { repository: first, tag: '<none>' }; -}; - -// Docker's CLI prints sizes in SI units ("142MB" = 142 * 10^6); the agent sends -// a byte count. Parsed to MEGABYTES rather than bytes because this number is -// also what the filter drawer and the chips show — "size is over 500 MB" is a -// question you can ask, "is over 500000000" is not. The cell still renders -// through the app's canonical formatter, so one host's images read the same way -// as another's. -const SIZE_MULTIPLIERS = { - b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, - kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4, -}; - -const imageSizeBytes = (image) => { - const raw = image.size ?? image.Size; - if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null; - if (typeof raw !== 'string') return null; - const match = raw.trim().match(/^([\d.]+)\s*([a-z]+)?$/i); - if (!match) return null; - const amount = Number.parseFloat(match[1]); - if (!Number.isFinite(amount)) return null; - return amount * (SIZE_MULTIPLIERS[(match[2] || 'b').toLowerCase()] ?? 1); -}; - -// The number a filter rule compares against MUST be the number the cell shows, -// or "Size is over 400 MB" matches a row whose own cell reads "392.9 MB". The -// cell renders through the app-wide formatBytes, which is base-1024 with MB/GB -// labels, so the rule value is mebibytes too — not docker's base-1000 MB. -const imageSizeMb = (image) => { - const bytes = imageSizeBytes(image); - return bytes == null ? null : bytes / (1024 * 1024); -}; - -const imageCreatedMs = (image) => { - const raw = image.created ?? image.CreatedAt ?? image.Created; - // The agent sends epoch SECONDS, the CLI "2026-08-12 09:12:33 -0400 EDT". - if (typeof raw === 'number') return raw > 1e11 ? raw : raw * 1000; - const parsed = Date.parse(raw || ''); - return Number.isNaN(parsed) ? null : parsed; -}; - // Built-in views. Dangling is the one axis this payload really has: docker // reports an untagged layer as repository `<none>`, on both transports, so the // rule below is reading a fact rather than a guess. There is deliberately no diff --git a/frontend/src/components/docker/__tests__/dockerHelpers.test.mjs b/frontend/src/components/docker/__tests__/dockerHelpers.test.mjs new file mode 100644 index 00000000..40d4a4d3 --- /dev/null +++ b/frontend/src/components/docker/__tests__/dockerHelpers.test.mjs @@ -0,0 +1,56 @@ +// Proving test for the Docker image accessors shared by the Docker page and the +// server detail Docker tab. The two transports describe the same image +// differently: the `docker images` CLI gives repository/tag strings and sizes +// like "142MB", the agent gives `repo_tags`, a byte count and epoch seconds. +// Both must render the same name, tag, size and date. +// +// Run: node --test src/components/docker/__tests__/dockerHelpers.test.mjs +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { imageId, imageRef, imageSizeBytes, imageCreatedMs } from '../dockerHelpers.js'; + +test('imageRef splits an agent repo_tags entry into repository and tag', () => { + assert.deepEqual( + imageRef({ repo_tags: ['roundcube/roundcubemail:latest-apache'] }), + { repository: 'roundcube/roundcubemail', tag: 'latest-apache' }, + ); + assert.deepEqual( + imageRef({ repo_tags: ['ghcr.io/docker-mailserver/docker-mailserver:16.0.1'] }), + { repository: 'ghcr.io/docker-mailserver/docker-mailserver', tag: '16.0.1' }, + ); +}); + +test('imageRef does not split on a registry port', () => { + assert.deepEqual(imageRef({ repo_tags: ['registry:5000/app'] }), { repository: 'registry:5000/app', tag: '<none>' }); + assert.deepEqual(imageRef({ repo_tags: ['registry:5000/app:1.2'] }), { repository: 'registry:5000/app', tag: '1.2' }); +}); + +test('imageRef reports an untagged image as <none>', () => { + assert.deepEqual(imageRef({ repo_tags: [] }), { repository: '<none>', tag: '<none>' }); + assert.deepEqual(imageRef({}), { repository: '<none>', tag: '<none>' }); +}); + +test('imageRef passes CLI repository/tag fields through', () => { + assert.deepEqual(imageRef({ repository: 'nginx', tag: 'latest' }), { repository: 'nginx', tag: 'latest' }); +}); + +test('imageId drops the sha256: prefix', () => { + assert.equal(imageId({ id: 'sha256:734d9162c522' }), '734d9162c522'); + assert.equal(imageId({ ID: '734d9162c522' }), '734d9162c522'); +}); + +test('imageSizeBytes reads agent byte counts and CLI size strings', () => { + assert.equal(imageSizeBytes({ size: 1044290102 }), 1044290102); + assert.equal(imageSizeBytes({ size: '142MB' }), 142e6); + assert.equal(imageSizeBytes({ size: '1.5GB' }), 1.5e9); + assert.equal(imageSizeBytes({ size: 'n/a' }), null); + assert.equal(imageSizeBytes({}), null); +}); + +test('imageCreatedMs reads agent epoch seconds and CLI date strings', () => { + assert.equal(imageCreatedMs({ created: 1792605383 }), 1792605383000); + assert.equal(imageCreatedMs({ created: 1792605383000 }), 1792605383000); + assert.equal(imageCreatedMs({ CreatedAt: '2026-08-12T09:12:33Z' }), Date.parse('2026-08-12T09:12:33Z')); + assert.equal(imageCreatedMs({ created: 'not a date' }), null); +}); diff --git a/frontend/src/components/docker/dockerHelpers.js b/frontend/src/components/docker/dockerHelpers.js index 5c2d9ffb..d6986d72 100644 --- a/frontend/src/components/docker/dockerHelpers.js +++ b/frontend/src/components/docker/dockerHelpers.js @@ -106,3 +106,64 @@ export const getContainerProjectName = (container, details) => { const labels = details?.Config?.Labels || container?.Labels || {}; return labels['com.docker.compose.project'] || labels['com.docker.compose.service'] || '-'; }; + +// The two transports describe the same image differently: `docker images` +// hands back repository/tag as separate strings, the agent hands back +// `repo_tags: ["nginx:latest"]` and nothing else. Every accessor below reads +// both, because a column that silently blanks on remote hosts is worse than no +// column at all. +export const imageId = (image) => String(image.id || image.ID || '').replace(/^sha256:/, ''); + +export const imageRef = (image) => { + if (image.repository || image.tag) { + return { repository: image.repository || '<none>', tag: image.tag || '<none>' }; + } + const first = Array.isArray(image.repo_tags) ? image.repo_tags[0] : null; + if (!first) return { repository: '<none>', tag: '<none>' }; + // A registry port ("registry:5000/app") puts a colon in the REPOSITORY + // half, so the last colon is only the tag separator when no '/' follows it. + const colon = first.lastIndexOf(':'); + if (colon > 0 && !first.slice(colon).includes('/')) { + return { repository: first.slice(0, colon), tag: first.slice(colon + 1) }; + } + return { repository: first, tag: '<none>' }; +}; + +// Docker's CLI prints sizes in SI units ("142MB" = 142 * 10^6); the agent sends +// a byte count. Parsed to MEGABYTES rather than bytes because this number is +// also what the filter drawer and the chips show — "size is over 500 MB" is a +// question you can ask, "is over 500000000" is not. The cell still renders +// through the app's canonical formatter, so one host's images read the same way +// as another's. +const SIZE_MULTIPLIERS = { + b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, + kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4, +}; + +export const imageSizeBytes = (image) => { + const raw = image.size ?? image.Size; + if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null; + if (typeof raw !== 'string') return null; + const match = raw.trim().match(/^([\d.]+)\s*([a-z]+)?$/i); + if (!match) return null; + const amount = Number.parseFloat(match[1]); + if (!Number.isFinite(amount)) return null; + return amount * (SIZE_MULTIPLIERS[(match[2] || 'b').toLowerCase()] ?? 1); +}; + +// The number a filter rule compares against MUST be the number the cell shows, +// or "Size is over 400 MB" matches a row whose own cell reads "392.9 MB". The +// cell renders through the app-wide formatBytes, which is base-1024 with MB/GB +// labels, so the rule value is mebibytes too — not docker's base-1000 MB. +export const imageSizeMb = (image) => { + const bytes = imageSizeBytes(image); + return bytes == null ? null : bytes / (1024 * 1024); +}; + +export const imageCreatedMs = (image) => { + const raw = image.created ?? image.CreatedAt ?? image.Created; + // The agent sends epoch SECONDS, the CLI "2026-08-12 09:12:33 -0400 EDT". + if (typeof raw === 'number') return raw > 1e11 ? raw : raw * 1000; + const parsed = Date.parse(raw || ''); + return Number.isNaN(parsed) ? null : parsed; +}; diff --git a/frontend/src/components/ds/Stepper.jsx b/frontend/src/components/ds/Stepper.jsx new file mode 100644 index 00000000..dd3b0189 --- /dev/null +++ b/frontend/src/components/ds/Stepper.jsx @@ -0,0 +1,90 @@ +import { AlertTriangle, Check } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.sk-stepper*). + +// Read after the label by screen readers; the marker alone is visual only. +function statusCopy(t, status) { + if (status === 'complete') return t('common.controls.stepComplete', 'Completed'); + if (status === 'current') return t('common.controls.stepCurrent', 'Current step'); + if (status === 'error') return t('common.controls.stepError', 'Needs attention'); + return t('common.controls.stepUpcoming', 'Not started'); +} + +function statusOf(step, index, current) { + if (step.status) return step.status; + if (index < current) return 'complete'; + if (index === current) return 'current'; + return 'upcoming'; +} + +/** + * Progress through an ordered flow: setup, onboarding, a multi-page form, a + * deploy pipeline. + * + * <Stepper current={1} steps={[ + * { id: 'source', label: 'Source' }, + * { id: 'build', label: 'Build', description: 'Buildpack detected' }, + * { id: 'deploy', label: 'Deploy' }, + * ]} /> + * + * Status comes from `current` (before = complete, at = current, after = + * upcoming) unless a step sets its own `status` ('error' for a failed one). + * With `onStepClick`, completed steps become buttons to go back to; the + * current and later steps stay inert so a flow cannot be skipped ahead. + */ +export function Stepper({ + steps = [], + current = 0, + orientation = 'horizontal', + onStepClick, + className, + 'aria-label': ariaLabel, +}) { + const { t } = useTranslation(); + return ( + <ol + className={cn('sk-stepper', `sk-stepper--${orientation}`, className)} + aria-label={ariaLabel || t('common.controls.progress', 'Progress')} + > + {steps.map((step, index) => { + const status = statusOf(step, index, current); + const clickable = onStepClick && status === 'complete'; + const marker = ( + <> + <span className="sk-stepper__marker" aria-hidden="true"> + {status === 'complete' && <Check />} + {status === 'error' && <AlertTriangle />} + {(status === 'current' || status === 'upcoming') && index + 1} + </span> + <span className="sk-stepper__copy"> + <span className="sk-stepper__label">{step.label}</span> + {step.description && <span className="sk-stepper__description">{step.description}</span>} + <span className="sr-only">{statusCopy(t, status)}</span> + </span> + </> + ); + return ( + <li + key={step.id ?? index} + className={cn('sk-stepper__step', `is-${status}`)} + aria-current={status === 'current' ? 'step' : undefined} + > + {clickable ? ( + <Button variant="unstyled" type="button" className="sk-stepper__target" onClick={() => onStepClick(index, step)}> + {marker} + </Button> + ) : ( + <div className="sk-stepper__target">{marker}</div> + )} + {index < steps.length - 1 && <span className="sk-stepper__connector" aria-hidden="true" />} + </li> + ); + })} + </ol> + ); +} + +export default Stepper; diff --git a/frontend/src/components/ds/TreeView.jsx b/frontend/src/components/ds/TreeView.jsx new file mode 100644 index 00000000..d8f0947c --- /dev/null +++ b/frontend/src/components/ds/TreeView.jsx @@ -0,0 +1,205 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { ChevronRight, File, Folder, FolderOpen, Loader2 } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '@/lib/utils'; + +// Styling lives in styles/components/_controls.scss (.sk-tree*). + +// Typeahead: keystrokes within this window extend one search string. +const TYPEAHEAD_RESET_MS = 500; + +// Flatten the expanded part of the tree into visible rows, in reading order. +function visibleRows(nodes, expanded, level = 1, parentId = null, rows = []) { + nodes.forEach((node, index) => { + const hasChildren = Boolean(node.children?.length) || node.hasChildren; + rows.push({ node, level, parentId, hasChildren, posinset: index + 1, setsize: nodes.length }); + if (hasChildren && expanded.has(node.id) && node.children) { + visibleRows(node.children, expanded, level + 1, node.id, rows); + } + }); + return rows; +} + +/** + * Hierarchical list: files, DNS zones, config trees, resource groups. + * + * <TreeView nodes={tree} selectedId={path} onSelect={(node) => open(node)} /> + * + * Nodes are `{ id, label, icon?, children?, hasChildren?, meta?, disabled? }`. + * `hasChildren` without `children` marks a lazy branch: expanding it calls + * `onLoadChildren(node)` (return a promise; the caller then supplies the + * children) and shows a spinner meanwhile. Expansion is internal unless + * `expandedIds` + `onExpandedChange` control it. + * + * Keyboard (WAI tree pattern): ↑/↓ move, → opens or steps into a branch, + * ← closes or steps out to the parent, Home/End, Enter/Space select, `*` + * opens every sibling, and typing jumps to the next matching label. + */ +export function TreeView({ + nodes = [], + selectedId, + onSelect, + expandedIds, + defaultExpandedIds = [], + onExpandedChange, + onLoadChildren, + className, + 'aria-label': ariaLabel, +}) { + const { t } = useTranslation(); + const [ownExpanded, setOwnExpanded] = useState(() => new Set(defaultExpandedIds)); + const expanded = useMemo(() => (expandedIds ? new Set(expandedIds) : ownExpanded), [expandedIds, ownExpanded]); + const [loading, setLoading] = useState(() => new Set()); + const [focusedId, setFocusedId] = useState(null); + const rowRefs = useRef(new Map()); + const typeahead = useRef({ text: '', timer: null }); + const focusWithin = useRef(false); + + const rows = useMemo(() => visibleRows(nodes, expanded), [nodes, expanded]); + const activeId = rows.some((row) => row.node.id === focusedId) + ? focusedId + : (rows.find((row) => row.node.id === selectedId) || rows[0])?.node.id; + + useEffect(() => () => clearTimeout(typeahead.current.timer), []); + useEffect(() => { + if (focusWithin.current && activeId != null) rowRefs.current.get(activeId)?.focus(); + }, [activeId]); + + const setExpanded = useCallback((next) => { + if (!expandedIds) setOwnExpanded(next); + onExpandedChange?.([...next]); + }, [expandedIds, onExpandedChange]); + + const expand = async (node) => { + if (expanded.has(node.id)) return; + setExpanded(new Set(expanded).add(node.id)); + if (!node.children && node.hasChildren && onLoadChildren) { + setLoading((prev) => new Set(prev).add(node.id)); + try { + await onLoadChildren(node); + } finally { + setLoading((prev) => { const next = new Set(prev); next.delete(node.id); return next; }); + } + } + }; + + const collapse = (node) => { + if (!expanded.has(node.id)) return; + const next = new Set(expanded); + next.delete(node.id); + setExpanded(next); + }; + + const toggle = (row) => (expanded.has(row.node.id) ? collapse(row.node) : expand(row.node)); + + const select = (row) => { + if (row.node.disabled) return; + setFocusedId(row.node.id); + onSelect?.(row.node); + }; + + const handleKeyDown = (event) => { + const index = rows.findIndex((row) => row.node.id === activeId); + const row = rows[index]; + if (!row) return; + const focus = (target) => { if (target) setFocusedId(target.node.id); }; + const keyActions = { + ArrowDown: () => focus(rows[index + 1]), + ArrowUp: () => focus(rows[index - 1]), + Home: () => focus(rows[0]), + End: () => focus(rows[rows.length - 1]), + ArrowRight: () => { + if (!row.hasChildren) return; + if (!expanded.has(row.node.id)) expand(row.node); + else if (rows[index + 1]?.parentId === row.node.id) focus(rows[index + 1]); + }, + ArrowLeft: () => { + if (row.hasChildren && expanded.has(row.node.id)) collapse(row.node); + else focus(rows.find((candidate) => candidate.node.id === row.parentId)); + }, + Enter: () => select(row), + ' ': () => select(row), + '*': () => { + const siblings = rows.filter((candidate) => candidate.parentId === row.parentId && candidate.hasChildren); + siblings.forEach((sibling) => expand(sibling.node)); + }, + }; + const action = keyActions[event.key]; + if (action) { + event.preventDefault(); + action(); + return; + } + if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) { + const state = typeahead.current; + clearTimeout(state.timer); + state.text += event.key.toLowerCase(); + state.timer = setTimeout(() => { state.text = ''; }, TYPEAHEAD_RESET_MS); + const ordered = [...rows.slice(index + 1), ...rows.slice(0, index + 1)]; + const searchFrom = state.text.length === 1 ? ordered : [row, ...ordered]; + focus(searchFrom.find((candidate) => String(candidate.node.label).toLowerCase().startsWith(state.text))); + } + }; + + return ( + <ul + role="tree" + aria-label={ariaLabel || t('common.controls.tree', 'Tree')} + className={cn('sk-tree', className)} + onKeyDown={handleKeyDown} + onFocus={() => { focusWithin.current = true; }} + onBlur={(event) => { + if (!event.currentTarget.contains(event.relatedTarget)) focusWithin.current = false; + }} + > + {rows.map((row) => { + const { node } = row; + const isOpen = expanded.has(node.id); + const isLoading = loading.has(node.id); + const selected = node.id === selectedId; + const DefaultIcon = row.hasChildren ? (isOpen ? FolderOpen : Folder) : File; + const Icon = node.icon || DefaultIcon; + return ( + <li + key={node.id} + ref={(element) => { + if (element) rowRefs.current.set(node.id, element); + else rowRefs.current.delete(node.id); + }} + role="treeitem" + tabIndex={node.id === activeId ? 0 : -1} + aria-level={row.level} + aria-posinset={row.posinset} + aria-setsize={row.setsize} + aria-expanded={row.hasChildren ? isOpen : undefined} + aria-selected={selected} + aria-disabled={node.disabled || undefined} + aria-busy={isLoading || undefined} + className={cn('sk-tree__row', selected && 'is-selected', node.disabled && 'is-disabled')} + style={{ '--sk-tree-level': row.level - 1 }} + onClick={() => { select(row); }} + onDoubleClick={() => { if (row.hasChildren) toggle(row); }} + > + <span + className={cn('sk-tree__toggle', !row.hasChildren && 'is-leaf', isOpen && 'is-open')} + aria-hidden="true" + onClick={(event) => { + if (!row.hasChildren) return; + event.stopPropagation(); + setFocusedId(node.id); + toggle(row); + }} + > + {isLoading ? <Loader2 className="sk-tree__spinner" /> : row.hasChildren && <ChevronRight />} + </span> + <Icon className="sk-tree__icon" aria-hidden="true" /> + <span className="sk-tree__label">{node.label}</span> + {node.meta && <span className="sk-tree__meta">{node.meta}</span>} + </li> + ); + })} + </ul> + ); +} + +export default TreeView; diff --git a/frontend/src/components/serverdetail/ServerDockerTab.jsx b/frontend/src/components/serverdetail/ServerDockerTab.jsx index 6091c6b3..e454cc2f 100644 --- a/frontend/src/components/serverdetail/ServerDockerTab.jsx +++ b/frontend/src/components/serverdetail/ServerDockerTab.jsx @@ -15,6 +15,10 @@ import { TrashIcon, } from './serverDetailShared'; import { toastError } from '@/utils/errorMessage'; +import { formatBytes } from '@/utils/formatBytes'; +import { formatRelativeTime } from '@/utils/time'; +import { formatDateTime } from '@/utils/intl'; +import { imageId, imageRef, imageSizeBytes, imageCreatedMs } from '../docker/dockerHelpers'; // The /servers/<id>/docker/* endpoints return raw arrays from Flask // (route extracts result.get('data') before jsonify). The agent envelope's @@ -46,15 +50,6 @@ const formatPorts = (ports) => { return parts.join(', '); }; -// docker prints image sizes as strings ("25.5MB", "1.2GB") — parse to bytes -// so the Size column sorts numerically instead of lexicographically. -const SIZE_UNITS = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12 }; -const parseDockerSize = (size) => { - const match = /^([\d.]+)\s*(b|kb|mb|gb|tb)$/i.exec(size || ''); - if (!match) return null; - return parseFloat(match[1]) * (SIZE_UNITS[match[2].toLowerCase()] || 1); -}; - // Images table columns. Cell markup and classNames are identical to the // hand-rolled table they replace so the .data-table SCSS keeps applying. const IMAGE_COLUMNS = [ @@ -63,35 +58,43 @@ const IMAGE_COLUMNS = [ headerKey: 'app.serverDockerTab.repository', header: 'Repository', sortable: true, hideable: false, - sortValue: (image) => image.repository || '<none>', - render: (image) => image.repository || '<none>', + sortValue: (image) => imageRef(image).repository, + render: (image) => imageRef(image).repository, }, { key: 'tag', headerKey: 'app.serverDockerTab.tag', header: 'Tag', sortable: true, - sortValue: (image) => image.tag || '<none>', - render: (image) => image.tag || '<none>', + sortValue: (image) => imageRef(image).tag, + render: (image) => imageRef(image).tag, }, { key: 'id', headerKey: 'app.serverDockerTab.imageId', header: 'Image ID', cellClassName: 'sk-cell-mono', - render: (image) => image.id?.substring(0, 12), + render: (image) => imageId(image).substring(0, 12), }, { key: 'size', headerKey: 'common.labels.size', header: 'Size', sortable: true, - sortValue: (image) => parseDockerSize(image.size), - render: (image) => image.size, + sortValue: imageSizeBytes, + render: (image) => formatBytes(imageSizeBytes(image)), }, { key: 'created', headerKey: 'common.labels.created', header: 'Created', sortable: true, - sortValue: (image) => image.created || null, - render: (image) => image.created, + sortValue: imageCreatedMs, + render: (image) => { + const ms = imageCreatedMs(image); + if (ms == null) return '-'; + return ( + <span title={formatDateTime(ms)}> + {formatRelativeTime(new Date(ms).toISOString())} + </span> + ); + }, }, ]; diff --git a/frontend/src/components/styleguide/ControlsShowcase.jsx b/frontend/src/components/styleguide/ControlsShowcase.jsx new file mode 100644 index 00000000..dea805b7 --- /dev/null +++ b/frontend/src/components/styleguide/ControlsShowcase.jsx @@ -0,0 +1,476 @@ +import { useState } from 'react'; +import { usePolling } from '../../hooks/usePolling'; +import { useTranslation } from 'react-i18next'; +import { + Bell, Copy, Database, Globe, HardDrive, RefreshCw, Rocket, Server, Settings, Trash2, +} from 'lucide-react'; +import { FormField, FormRow } from '../FormField'; +import { IconButton } from '../IconButton'; +import { ProgressBar } from '../ProgressBar'; +import { Stepper } from '../ds/Stepper'; +import { TreeView } from '../ds/TreeView'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { Tip } from '@/components/ui/tooltip'; +import { NumberField } from '@/components/ui/number-field'; +import { Combobox } from '@/components/ui/combobox'; +import { TagInput } from '@/components/ui/tag-input'; +import { Calendar } from '@/components/ui/calendar'; +import { DatePicker, DateRangePicker } from '@/components/ui/date-picker'; +import { PinInput } from '@/components/ui/pin-input'; +import { Slider } from '@/components/ui/slider'; +import { RadioGroup } from '@/components/ui/radio-group'; +import { FileDropzone, FileUploadList } from '@/components/ui/file-dropzone'; +import { addDays, startOfDay } from '@/lib/dateMath'; + +const MB = 1024 * 1024; +const DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\.[a-z0-9-]{1,63})+$/i; +// Upload simulation: percent added per tick, and the tick length. +const UPLOAD_STEP = 7; +const UPLOAD_TICK_MS = 180; + +function Demo({ id, title, note, children }) { + return ( + <section className="styleguide__control-demo" data-demo={id}> + <header className="styleguide__control-head"> + <h3>{title}</h3> + {note && <p>{note}</p>} + </header> + <div className="styleguide__control-body">{children}</div> + </section> + ); +} + +function State({ label, children }) { + return ( + <div className="styleguide__control-state"> + <span className="styleguide__control-state-label">{label}</span> + {children} + </div> + ); +} + +function buildTree(t) { + return [ + { + id: 'etc', label: 'etc', children: [ + { + id: 'nginx', label: 'nginx', children: [ + { id: 'nginx.conf', label: 'nginx.conf', meta: '2.4 KB' }, + { + id: 'sites-enabled', label: 'sites-enabled', children: [ + { id: 'shop.conf', label: 'shop.example.com.conf', meta: '1.1 KB' }, + { id: 'api.conf', label: 'api.example.com.conf', meta: '0.9 KB' }, + ], + }, + ], + }, + { id: 'ssh', label: 'ssh', hasChildren: true }, + { id: 'hosts', label: 'hosts', meta: '212 B' }, + ], + }, + { id: 'var', label: 'var', hasChildren: true }, + { id: 'locked', label: t('app.styleGuide.controls.treeLocked', 'root (no access)'), disabled: true }, + ]; +} + +export default function ControlsShowcase() { + const { t } = useTranslation(); + const today = startOfDay(new Date()); + + const [name, setName] = useState(''); + const [workers, setWorkers] = useState(4); + const [memory, setMemory] = useState(512); + const [ratio, setRatio] = useState(null); + const [server, setServer] = useState('web-01'); + const [scopes, setScopes] = useState(['apps:read', 'apps:deploy', 'logs:read', 'backups:read']); + const [labels, setLabels] = useState(['production']); + const [labelOptions, setLabelOptions] = useState(['production', 'staging', 'internal'].map((v) => ({ value: v, label: v }))); + const [domains, setDomains] = useState(['example.com', 'www.example.com']); + const [expires, setExpires] = useState(addDays(today, 30)); + const [range, setRange] = useState({ start: addDays(today, -6), end: today }); + const [inlineDay, setInlineDay] = useState(today); + const [code, setCode] = useState(''); + const [verified, setVerified] = useState(null); + const [retention, setRetention] = useState(30); + const [memoryMb, setMemoryMb] = useState(2048); + const [ports, setPorts] = useState([3000, 8000]); + const [strategy, setStrategy] = useState('rolling'); + const [plan, setPlan] = useState('standard'); + const [step, setStep] = useState(2); + const [treeNodes, setTreeNodes] = useState(() => buildTree(t)); + const [selectedFile, setSelectedFile] = useState('nginx.conf'); + const [uploads, setUploads] = useState([ + { id: 'a', name: 'site-backup-2026-10-24.tar.gz', size: 182 * MB, status: 'done' }, + { id: 'b', name: 'database-dump.sql.gz', size: 48 * MB, status: 'uploading', progress: 62 }, + { id: 'c', name: 'uploads.zip', size: 310 * MB, status: 'error', error: t('app.styleGuide.controls.uploadErrorDemo', 'The connection dropped at 41%.') }, + { id: 'd', name: 'media-library.zip', size: 96 * MB, status: 'queued' }, + ]); + const [saving, setSaving] = useState(false); + + // Move the "uploading" rows forward so the list reads as live. + usePolling(() => { + setUploads((items) => items.map((item) => { + if (item.status !== 'uploading') return item; + const progress = Math.min(100, (item.progress || 0) + UPLOAD_STEP); + return progress >= 100 ? { ...item, status: 'done', progress: 100 } : { ...item, progress }; + })); + }, UPLOAD_TICK_MS, { immediate: false }); + + const servers = [ + { value: 'web-01', label: 'web-01', description: t('app.styleGuide.controls.hostWeb01', '10.0.0.11 · Ubuntu 24.04'), icon: Server, group: t('app.styleGuide.controls.groupProduction', 'Production') }, + { value: 'web-02', label: 'web-02', description: t('app.styleGuide.controls.hostWeb02', '10.0.0.12 · Ubuntu 24.04'), icon: Server, group: t('app.styleGuide.controls.groupProduction', 'Production') }, + { value: 'db-01', label: 'db-01', description: t('app.styleGuide.controls.hostDb01', '10.0.0.21 · Debian 13'), icon: Database, group: t('app.styleGuide.controls.groupProduction', 'Production') }, + { value: 'staging', label: 'staging-01', description: t('app.styleGuide.controls.hostStaging', '10.0.1.5 · Rocky 9'), icon: Server, group: t('app.styleGuide.controls.groupStaging', 'Staging') }, + { value: 'edge', label: 'edge-ams', description: t('app.styleGuide.controls.offline', 'Offline'), icon: Globe, group: t('app.styleGuide.controls.groupStaging', 'Staging'), disabled: true }, + ]; + const scopeOptions = ['apps:read', 'apps:deploy', 'apps:delete', 'logs:read', 'backups:read', 'backups:restore', 'dns:write'] + .map((value) => ({ value, label: value })); + + const loadChildren = (node) => new Promise((resolve) => { + setTimeout(() => { + const children = node.id === 'ssh' + ? [{ id: 'sshd_config', label: 'sshd_config', meta: '3.3 KB' }, { id: 'ssh_config', label: 'ssh_config', meta: '1.5 KB' }] + : [{ id: 'log', label: 'log', hasChildren: true }, { id: 'www', label: 'www', hasChildren: true }]; + const attach = (nodes) => nodes.map((item) => (item.id === node.id + ? { ...item, children } + : item.children ? { ...item, children: attach(item.children) } : item)); + setTreeNodes((nodes) => attach(nodes)); + resolve(); + }, 700); + }); + + const steps = [ + { id: 'source', label: t('app.styleGuide.controls.stepSource', 'Source'), description: 'github.com/acme/shop' }, + { id: 'build', label: t('app.styleGuide.controls.stepBuild', 'Build'), description: t('app.styleGuide.controls.stepBuildNote', 'Node 20 detected') }, + { id: 'configure', label: t('app.styleGuide.controls.stepConfigure', 'Configure') }, + { id: 'deploy', label: t('app.styleGuide.controls.stepDeploy', 'Deploy') }, + ]; + + return ( + <div className="styleguide__controls"> + {/* ── TIER 1 ── */} + <Demo + id="form-field" + title={t('app.styleGuide.controls.formFieldTitle', 'Form field wiring')} + note={t('app.styleGuide.controls.formFieldNote', 'The control gets the id, aria-describedby, aria-invalid and aria-required from FormField. No htmlFor needed.')} + > + <FormRow> + <FormField label={t('app.styleGuide.controls.serviceName', 'Service name')} hint={t('app.styleGuide.controls.serviceNameHint', 'Lowercase letters, numbers and dashes.')} required> + <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="shop-api" /> + </FormField> + <FormField label={t('app.styleGuide.controls.healthPath', 'Health check path')} error={t('app.styleGuide.controls.healthPathError', 'Must start with a slash.')} required> + <Input defaultValue="healthz" /> + </FormField> + </FormRow> + <FormField label={t('app.styleGuide.controls.notes', 'Notes')} hint={t('app.styleGuide.controls.notesHint', 'Shown to everyone with access to this service.')}> + <Textarea rows={2} /> + </FormField> + </Demo> + + <Demo + id="tooltip" + title={t('app.styleGuide.controls.tooltipTitle', 'Tooltip')} + note={t('app.styleGuide.controls.tooltipNote', 'Shows on hover and on keyboard focus. Moving along a row of icon buttons skips the delay.')} + > + <div className="styleguide__control-row"> + <IconButton icon={<RefreshCw size={16} />} label={t('app.styleGuide.controls.restart', 'Restart service')} shortcut="R" /> + <IconButton icon={<Copy size={16} />} label={t('app.styleGuide.controls.copyUrl', 'Copy URL')} /> + <IconButton icon={<Settings size={16} />} label={t('app.styleGuide.controls.settings', 'Settings')} /> + <IconButton icon={<Bell size={16} />} label={t('app.styleGuide.controls.alerts', 'Alert rules')} /> + <IconButton icon={<Trash2 size={16} />} label={t('app.styleGuide.controls.delete', 'Delete')} /> + <Tip content={t('app.styleGuide.controls.deployDisabledWhy', 'A deploy is already running')}> + <span className="styleguide__control-tip-wrap"> + <Button size="sm" disabled>{t('app.styleGuide.controls.deploy', 'Deploy')}</Button> + </span> + </Tip> + </div> + </Demo> + + <Demo + id="progress" + title={t('app.styleGuide.controls.progressTitle', 'Progress bar')} + note={t('app.styleGuide.controls.progressNote', 'role="progressbar" with value text; semantic tones; indeterminate for unknown length.')} + > + <div className="styleguide__control-stack"> + <State label={t('app.styleGuide.controls.progressDisk', 'Disk · 48 of 100 GB')}> + <ProgressBar percent={48} label={t('app.styleGuide.controls.disk', 'Disk')} valueText="48 of 100 GB" /> + </State> + <State label={t('app.styleGuide.controls.progressMemory', 'Memory · 78%')}> + <ProgressBar percent={78} tone="warning" size="md" label={t('app.styleGuide.controls.memory', 'Memory')} /> + </State> + <State label={t('app.styleGuide.controls.progressCpu', 'CPU · 94%')}> + <ProgressBar percent={94} tone="danger" size="md" label={t('app.styleGuide.controls.cpu', 'CPU')} /> + </State> + <State label={t('app.styleGuide.controls.progressPulling', 'Pulling image')}> + <ProgressBar indeterminate label={t('app.styleGuide.controls.pulling', 'Pulling image')} /> + </State> + </div> + </Demo> + + <Demo + id="button-loading" + title={t('app.styleGuide.controls.loadingTitle', 'Button loading')} + note={t('app.styleGuide.controls.loadingNote', 'The label stays in the layout, so the button keeps its width. aria-busy while it lasts.')} + > + <div className="styleguide__control-row"> + <Button loading loadingText={t('common.editing.saving', 'Saving…')}>{t('app.styleGuide.controls.saveChanges', 'Save changes')}</Button> + <Button variant="outline" loading>{t('app.styleGuide.controls.testConnection', 'Test connection')}</Button> + <Button variant="danger" loading>{t('app.styleGuide.controls.delete', 'Delete')}</Button> + <Button + variant="outline" + loading={saving} + onClick={() => { setSaving(true); setTimeout(() => setSaving(false), 1600); }} + > + <Rocket size={16} /> + {t('app.styleGuide.controls.tryIt', 'Click to try')} + </Button> + </div> + </Demo> + + {/* ── TIER 2 ── */} + <Demo + id="number-field" + title={t('app.styleGuide.controls.numberTitle', 'Number field')} + note={t('app.styleGuide.controls.numberNote', '↑/↓ step, Shift or PageUp/PageDown ×10, Home/End jump to the bounds. Hold a stepper to repeat.')} + > + <div className="styleguide__control-grid"> + <FormField label={t('app.styleGuide.controls.workers', 'Workers')} hint="1–64"> + <NumberField value={workers} onChange={setWorkers} min={1} max={64} /> + </FormField> + <FormField label={t('app.styleGuide.controls.memoryLimit', 'Memory limit')} hint={t('app.styleGuide.controls.memoryHint', 'Steps of 128 MB')}> + <NumberField value={memory} onChange={setMemory} min={128} max={16384} step={128} unit="MB" /> + </FormField> + <FormField label={t('app.styleGuide.controls.sampleRate', 'Sample rate')} error={ratio === null ? t('app.styleGuide.controls.required', 'Required') : null} required> + <NumberField value={ratio} onChange={setRatio} min={0} max={1} step={0.05} placeholder="0.25" /> + </FormField> + <FormField label={t('app.styleGuide.controls.disabled', 'Disabled')}> + <NumberField value={3} min={1} disabled /> + </FormField> + <FormField label={t('app.styleGuide.controls.compact', 'Compact')}> + <NumberField value={workers} onChange={setWorkers} min={1} max={64} size="sm" /> + </FormField> + </div> + </Demo> + + <Demo + id="combobox" + title={t('app.styleGuide.controls.comboboxTitle', 'Combobox')} + note={t('app.styleGuide.controls.comboboxNote', 'Searchable single or multiple choice with groups, descriptions and disabled options. Multiple stays open and toggles.')} + > + <div className="styleguide__control-grid"> + <FormField label={t('app.styleGuide.controls.server', 'Server')}> + <Combobox options={servers} value={server} onChange={setServer} placeholder={t('app.styleGuide.controls.pickServer', 'Pick a server')} /> + </FormField> + <FormField label={t('app.styleGuide.controls.apiScopes', 'API key scopes')}> + <Combobox multiple options={scopeOptions} value={scopes} onChange={setScopes} placeholder={t('app.styleGuide.controls.pickScopes', 'Choose scopes')} /> + </FormField> + <FormField label={t('app.styleGuide.controls.labels', 'Labels')} hint={t('app.styleGuide.controls.labelsHint', 'Type a new label to create it.')}> + <Combobox + multiple + creatable + options={labelOptions} + value={labels} + onChange={setLabels} + onCreate={(text) => { + setLabelOptions((options) => [...options, { value: text, label: text }]); + setLabels((current) => [...current, text]); + }} + /> + </FormField> + <FormField label={t('app.styleGuide.controls.empty', 'Empty')} error={t('app.styleGuide.controls.pickOne', 'Pick at least one server.')}> + <Combobox options={servers} value={null} onChange={() => {}} /> + </FormField> + </div> + </Demo> + + <Demo + id="tag-input" + title={t('app.styleGuide.controls.tagTitle', 'Tag input')} + note={t('app.styleGuide.controls.tagNote', 'Enter, comma or Tab adds; paste a list to add many; Backspace removes the last. Duplicates flash instead of repeating.')} + > + <FormField label={t('app.styleGuide.controls.domains', 'Domains')} hint={t('app.styleGuide.controls.domainsHint', 'Try “not a domain” or paste “a.com, b.com”.')}> + <TagInput + value={domains} + onChange={setDomains} + normalize={(text) => text.trim().toLowerCase()} + validate={(text) => (DOMAIN_PATTERN.test(text) ? null : t('app.styleGuide.controls.notADomain', '“{{value}}” is not a domain.', { value: text }))} + placeholder={t('app.styleGuide.controls.addDomain', 'Add a domain')} + /> + </FormField> + </Demo> + + <Demo + id="dates" + title={t('app.styleGuide.controls.datesTitle', 'Date and range pickers')} + note={t('app.styleGuide.controls.datesNote', 'Arrows move by day and week, PageUp/PageDown by month, Shift for a year. Month and weekday names follow the panel language.')} + > + <div className="styleguide__control-grid"> + <FormField label={t('app.styleGuide.controls.keyExpires', 'Key expires')}> + <DatePicker value={expires} onChange={setExpires} min={today} /> + </FormField> + <FormField label={t('app.styleGuide.controls.logRange', 'Log range')}> + <DateRangePicker value={range} onChange={setRange} max={today} /> + </FormField> + <FormField label={t('app.styleGuide.controls.empty', 'Empty')}> + <DatePicker value={null} onChange={() => {}} /> + </FormField> + </div> + <div className="styleguide__control-calendar"> + <Calendar value={inlineDay} onChange={setInlineDay} min={addDays(today, -10)} max={addDays(today, 60)} /> + <Calendar mode="range" months={2} value={range} onChange={(next) => { if (next.end) setRange(next); }} max={today} /> + </div> + </Demo> + + <Demo + id="pin-input" + title={t('app.styleGuide.controls.pinTitle', 'Pin input')} + note={t('app.styleGuide.controls.pinNote', 'Typing advances, Backspace walks back, paste fills every cell. Try 123456.')} + > + <div className="styleguide__control-row styleguide__control-row--top"> + <FormField + label={t('app.styleGuide.controls.authCode', 'Authenticator code')} + hint={verified === null ? t('app.styleGuide.controls.authCodeHint', 'Six digits from your app.') : null} + error={verified === false ? t('app.styleGuide.controls.authCodeWrong', 'That code did not match. Try again.') : null} + > + <PinInput + length={6} + groupSize={3} + value={code} + onChange={(next) => { setCode(next); if (next.length < 6) setVerified(null); }} + onComplete={(full) => setVerified(full === '123456')} + /> + </FormField> + <FormField label={t('app.styleGuide.controls.recoveryCode', 'Recovery code')}> + <PinInput length={8} type="alphanumeric" groupSize={4} value="A7K2" onChange={() => {}} /> + </FormField> + </div> + {verified && <p className="styleguide__control-ok">{t('app.styleGuide.controls.verified', 'Verified.')}</p>} + </Demo> + + <Demo + id="slider" + title={t('app.styleGuide.controls.sliderTitle', 'Slider')} + note={t('app.styleGuide.controls.sliderNote', 'Single value or a range, with marks and a formatted readout.')} + > + <div className="styleguide__control-stack"> + <FormField label={t('app.styleGuide.controls.logRetention', 'Log retention')}> + <Slider value={retention} onChange={setRetention} min={1} max={90} unit={t('app.styleGuide.controls.days', 'days')} /> + </FormField> + <FormField label={t('app.styleGuide.controls.memoryLimit', 'Memory limit')}> + <Slider + value={memoryMb} + onChange={setMemoryMb} + min={256} + max={8192} + step={256} + marks={[256, 2048, 4096, 8192]} + format={(mb) => (mb >= 1024 ? `${mb / 1024} GB` : `${mb} MB`)} + /> + </FormField> + <FormField label={t('app.styleGuide.controls.portRange', 'Port range')}> + <Slider value={ports} onChange={setPorts} min={1024} max={9999} step={1} aria-label={t('app.styleGuide.controls.portRange', 'Port range')} /> + </FormField> + </div> + </Demo> + + <Demo + id="radio" + title={t('app.styleGuide.controls.radioTitle', 'Radio group')} + note={t('app.styleGuide.controls.radioNote', 'For a few options that deserve to be read side by side. Arrow keys move and select.')} + > + <div className="styleguide__control-split"> + <RadioGroup + aria-label={t('app.styleGuide.controls.strategy', 'Deploy strategy')} + value={strategy} + onValueChange={setStrategy} + options={[ + { value: 'rolling', label: t('app.styleGuide.controls.rolling', 'Rolling'), description: t('app.styleGuide.controls.rollingNote', 'Replace containers one at a time. No downtime.') }, + { value: 'recreate', label: t('app.styleGuide.controls.recreate', 'Recreate'), description: t('app.styleGuide.controls.recreateNote', 'Stop everything, then start the new version.') }, + { value: 'manual', label: t('app.styleGuide.controls.manual', 'Manual'), description: t('app.styleGuide.controls.manualNote', 'Requires an admin.'), disabled: true }, + ]} + /> + <RadioGroup + variant="card" + orientation="horizontal" + aria-label={t('app.styleGuide.controls.storage', 'Storage')} + value={plan} + onValueChange={setPlan} + options={[ + { value: 'standard', label: t('app.styleGuide.controls.local', 'Local disk'), description: t('app.styleGuide.controls.localNote', 'Fast. Lost if the server is.'), icon: HardDrive }, + { value: 'replicated', label: t('app.styleGuide.controls.s3', 'S3 compatible'), description: t('app.styleGuide.controls.s3Note', 'Off-site copy after each backup.'), icon: Database }, + ]} + /> + </div> + </Demo> + + <Demo + id="stepper" + title={t('app.styleGuide.controls.stepperTitle', 'Stepper')} + note={t('app.styleGuide.controls.stepperNote', 'Completed steps are buttons back; later steps stay inert. A step can carry its own error status.')} + > + <Stepper steps={steps} current={step} onStepClick={(index) => setStep(index)} /> + <div className="styleguide__control-row"> + <Button size="sm" variant="outline" disabled={step === 0} onClick={() => setStep((s) => s - 1)}> + {t('common.actions.back', 'Back')} + </Button> + <Button size="sm" disabled={step >= steps.length} onClick={() => setStep((s) => s + 1)}> + {t('common.actions.next', 'Next')} + </Button> + </div> + <div className="styleguide__control-split"> + <Stepper + orientation="vertical" + current={2} + steps={[ + { id: 'pull', label: t('app.styleGuide.controls.pull', 'Pull image'), description: t('app.styleGuide.controls.pullTime', '12.4 s') }, + { id: 'migrate', label: t('app.styleGuide.controls.migrate', 'Run migrations'), description: t('app.styleGuide.controls.migrationsApplied', '3 applied') }, + { id: 'health', label: t('app.styleGuide.controls.health', 'Health check'), description: t('app.styleGuide.controls.healthFailed', '503 after 30 s'), status: 'error' }, + { id: 'switch', label: t('app.styleGuide.controls.switch', 'Switch traffic') }, + ]} + /> + </div> + </Demo> + + <Demo + id="tree" + title={t('app.styleGuide.controls.treeTitle', 'Tree view')} + note={t('app.styleGuide.controls.treeNote', 'Arrows walk and open branches, * opens siblings, typing jumps to a name. ssh and var load their children lazily.')} + > + <div className="styleguide__control-tree"> + <TreeView + aria-label={t('app.styleGuide.controls.files', 'Files')} + nodes={treeNodes} + defaultExpandedIds={['etc', 'nginx', 'sites-enabled']} + selectedId={selectedFile} + onSelect={(node) => setSelectedFile(node.id)} + onLoadChildren={loadChildren} + /> + </div> + </Demo> + + <Demo + id="dropzone" + title={t('app.styleGuide.controls.dropzoneTitle', 'File dropzone and upload list')} + note={t('app.styleGuide.controls.dropzoneNote', 'Type and size are re-checked on drop. Each file reports its own progress, error and retry.')} + > + <FileDropzone + accept=".zip,.tar.gz,.sql,.gz" + maxSize={512 * MB} + onFiles={(files) => setUploads((items) => [ + ...files.map((file, index) => ({ id: `${file.name}-${Date.now()}-${index}`, name: file.name, size: file.size, status: 'uploading', progress: 0 })), + ...items, + ])} + /> + <FileUploadList + items={uploads} + onRetry={(item) => setUploads((items) => items.map((x) => (x.id === item.id ? { ...x, status: 'uploading', progress: 0, error: null } : x)))} + onRemove={(item) => setUploads((items) => items.filter((x) => x.id !== item.id))} + onCancel={(item) => setUploads((items) => items.filter((x) => x.id !== item.id))} + /> + <FileDropzone compact disabled title={t('app.styleGuide.controls.dropDisabled', 'Uploads are paused while a restore runs')} /> + </Demo> + </div> + ); +} diff --git a/frontend/src/components/ui/button.jsx b/frontend/src/components/ui/button.jsx index 0d8e0488..6227a455 100644 --- a/frontend/src/components/ui/button.jsx +++ b/frontend/src/components/ui/button.jsx @@ -1,6 +1,7 @@ import * as React from 'react'; import { Slot } from '@radix-ui/react-slot'; import { buttonVariants } from './buttonVariants'; +import { Spinner } from '../Spinner'; // forwardRef is load-bearing, not ceremony: every Radix trigger used as // `<PopoverTrigger asChild><Button/></PopoverTrigger>` hands the button a ref @@ -9,15 +10,41 @@ import { buttonVariants } from './buttonVariants'; // floating-ui never gets a reference element, and the panel is left parked at // its pre-position `translate(0, -200%)` — open, focusable and completely // off-screen. That is why Sort/Columns/Views/Filter looked like dead buttons. -const Button = React.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => { +// +// `loading` keeps the label in the layout (transparent, .btn-loading in +// _spinner.scss) and centres a spinner over it, so a Save button does not +// change width mid-click and the row around it does not jump. The button is +// disabled and aria-busy while it lasts; `loadingText` replaces the +// accessible name ("Saving…") when the visible label would lie. +const Button = React.forwardRef(({ + className, variant, size, asChild = false, loading = false, loadingText, + disabled, children, ...props +}, ref) => { const Comp = asChild ? Slot : 'button'; + if (asChild) { + return ( + <Comp ref={ref} data-slot="button" className={buttonVariants({ variant, size, className })} disabled={disabled} {...props}> + {children} + </Comp> + ); + } return ( <Comp ref={ref} data-slot="button" - className={buttonVariants({ variant, size, className })} + className={buttonVariants({ variant, size, className: loading ? `btn-loading ${className || ''}` : className })} + disabled={disabled || loading} + aria-busy={loading || undefined} {...props} - /> + > + {loading ? ( + <> + <span className="btn__label" aria-hidden={loadingText ? true : undefined}>{children}</span> + <Spinner size="sm" /> + {loadingText && <span className="sr-only">{loadingText}</span>} + </> + ) : children} + </Comp> ); }); Button.displayName = 'Button'; diff --git a/frontend/src/components/ui/calendar.jsx b/frontend/src/components/ui/calendar.jsx new file mode 100644 index 00000000..1af5e89b --- /dev/null +++ b/frontend/src/components/ui/calendar.jsx @@ -0,0 +1,241 @@ +import * as React from 'react'; +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import useFormat from '@/hooks/useFormat'; +import { + addDays, addMonths, clampDay, endOfMonth, endOfWeek, isAfter, isBefore, isSameDay, isSameMonth, + isWithinRange, monthGrid, orderRange, startOfDay, startOfMonth, startOfWeek, +} from '@/lib/dateMath'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.ui-calendar*). + +function isRtl(node) { + return node?.closest('[dir]')?.getAttribute('dir') === 'rtl'; +} + +/** + * Month grid for picking one day or a range. Usually rendered by + * DatePicker / DateRangePicker; use it bare for an inline calendar. + * + * <Calendar value={day} onChange={setDay} min={today} /> + * <Calendar mode="range" value={{ start, end }} onChange={setRange} months={2} /> + * + * Values are local calendar days (lib/dateMath). Keyboard follows the WAI + * date-grid pattern: arrows move a day / week, Home/End the week edges, + * PageUp/PageDown a month, Shift+PageUp/PageDown a year, Enter/Space picks. + * Only the focused day is a tab stop. + */ +function Calendar({ + mode = 'single', + value, + onChange, + min, + max, + isDateDisabled, + months = 1, + defaultMonth, + autoFocus = false, + className, +}) { + const { t } = useTranslation(); + const { formatDate, getWeekStart } = useFormat(); + const weekStartsOn = getWeekStart(); + const today = startOfDay(new Date()); + const range = mode === 'range' ? (value || {}) : null; + const anchor = mode === 'range' ? range.start : value; + + const [visibleMonth, setVisibleMonth] = React.useState(() => startOfMonth(defaultMonth || anchor || today)); + const [focusedDay, setFocusedDay] = React.useState(() => anchor || clampDay(today, min, max)); + const [hoverDay, setHoverDay] = React.useState(null); + const gridRef = React.useRef(null); + const focusWithin = React.useRef(autoFocus); + + const lastVisible = addMonths(visibleMonth, months - 1); + const disabledDay = (day) => (min && isBefore(day, min)) + || (max && isAfter(day, max)) + || Boolean(isDateDisabled?.(day)); + + // Page the grid so `day` is inside one of the visible months. + const reveal = React.useCallback((day) => { + setVisibleMonth((first) => { + if (isBefore(day, first)) return startOfMonth(day); + if (isAfter(day, endOfMonth(addMonths(first, months - 1)))) { + return startOfMonth(addMonths(day, -(months - 1))); + } + return first; + }); + }, [months]); + + const moveFocus = (day) => { + const next = clampDay(day, min, max); + setFocusedDay(next); + reveal(next); + }; + + // A value set from outside (a preset, a typed date) brings its month in. + const anchorTime = anchor ? anchor.getTime() : null; + React.useEffect(() => { + if (anchorTime === null) return; + const day = new Date(anchorTime); + setFocusedDay(day); + reveal(day); + }, [anchorTime, reveal]); + + React.useLayoutEffect(() => { + if (!focusWithin.current) return; + gridRef.current?.querySelector('[data-focused="true"]')?.focus(); + }, [focusedDay, visibleMonth]); + + const pick = (day) => { + if (disabledDay(day)) return; + setFocusedDay(day); + if (mode !== 'range') { onChange?.(day); return; } + if (!range.start || range.end) { + onChange?.({ start: day, end: null }); + } else { + onChange?.(orderRange(range.start, day)); + setHoverDay(null); + } + }; + + const handleKeyDown = (event) => { + const rtl = isRtl(event.currentTarget); + const horizontal = rtl ? -1 : 1; + const moves = { + ArrowLeft: () => addDays(focusedDay, -horizontal), + ArrowRight: () => addDays(focusedDay, horizontal), + ArrowUp: () => addDays(focusedDay, -7), + ArrowDown: () => addDays(focusedDay, 7), + Home: () => startOfWeek(focusedDay, weekStartsOn), + End: () => endOfWeek(focusedDay, weekStartsOn), + PageUp: () => addMonths(focusedDay, event.shiftKey ? -12 : -1), + PageDown: () => addMonths(focusedDay, event.shiftKey ? 12 : 1), + }; + const move = moves[event.key]; + if (!move) return; + event.preventDefault(); + focusWithin.current = true; + moveFocus(move()); + }; + + const page = (delta) => { + setVisibleMonth((month) => addMonths(month, delta)); + setFocusedDay((day) => clampDay(addMonths(day, delta), min, max)); + }; + + const weekdays = monthGrid(visibleMonth, weekStartsOn)[0]; + const previewEnd = range && range.start && !range.end && hoverDay ? hoverDay : null; + const shownRange = previewEnd ? orderRange(range.start, previewEnd) : range; + const prevDisabled = min && !isAfter(visibleMonth, startOfMonth(min)); + const nextDisabled = max && !isBefore(lastVisible, startOfMonth(max)); + + return ( + <div + ref={gridRef} + className={cn('ui-calendar', months > 1 && 'ui-calendar--multi', className)} + onFocus={() => { focusWithin.current = true; }} + onBlur={(event) => { + if (!event.currentTarget.contains(event.relatedTarget)) focusWithin.current = false; + }} + > + <div className="ui-calendar__nav"> + <Button variant="unstyled" + type="button" + className="ui-calendar__nav-button" + aria-label={t('common.controls.previousMonth', 'Previous month')} + disabled={prevDisabled} + onClick={() => page(-1)} + > + <ChevronLeft aria-hidden="true" /> + </Button> + <Button variant="unstyled" + type="button" + className="ui-calendar__nav-button" + aria-label={t('common.controls.nextMonth', 'Next month')} + disabled={nextDisabled} + onClick={() => page(1)} + > + <ChevronRight aria-hidden="true" /> + </Button> + </div> + <div className="ui-calendar__months"> + {Array.from({ length: months }, (_, offset) => { + const month = addMonths(visibleMonth, offset); + const title = formatDate(month, { parts: { month: 'long', year: 'numeric' } }); + return ( + <div key={offset} className="ui-calendar__month"> + <div className="ui-calendar__title" aria-live="polite">{title}</div> + <div role="grid" aria-label={title} className="ui-calendar__grid" onKeyDown={handleKeyDown}> + <div role="row" className="ui-calendar__row ui-calendar__row--head"> + {weekdays.map((day) => ( + <span + key={day.getDay()} + role="columnheader" + aria-label={formatDate(day, { parts: { weekday: 'long' } })} + className="ui-calendar__weekday" + > + {formatDate(day, { parts: { weekday: 'narrow' } })} + </span> + ))} + </div> + {monthGrid(month, weekStartsOn).map((week) => ( + <div key={week[0].getTime()} role="row" className="ui-calendar__row"> + {week.map((day) => { + const outside = !isSameMonth(day, month); + if (outside && months > 1) { + return <span key={day.getTime()} role="gridcell" className="ui-calendar__cell is-outside" />; + } + const disabled = disabledDay(day); + const isStart = shownRange && isSameDay(day, shownRange.start); + const isEnd = shownRange && isSameDay(day, shownRange.end); + const inRange = shownRange && isWithinRange(day, shownRange.start, shownRange.end); + const selected = mode === 'range' ? (isStart || isEnd || inRange) : isSameDay(day, value); + const focused = isSameDay(day, focusedDay) && isSameMonth(day, month); + return ( + <span + key={day.getTime()} + role="gridcell" + aria-selected={selected || undefined} + className={cn( + 'ui-calendar__cell', + outside && 'is-outside', + inRange && 'is-in-range', + isStart && 'is-range-start', + isEnd && 'is-range-end', + )} + > + <Button variant="unstyled" + type="button" + tabIndex={focused ? 0 : -1} + data-focused={focused || undefined} + disabled={disabled} + aria-label={formatDate(day, { style: 'full' })} + aria-current={isSameDay(day, today) ? 'date' : undefined} + className={cn( + 'ui-calendar__day', + selected && 'is-selected', + (isStart || isEnd || mode !== 'range') && selected && 'is-endpoint', + isSameDay(day, today) && 'is-today', + )} + onClick={() => pick(day)} + onMouseEnter={() => { if (range?.start && !range.end) setHoverDay(day); }} + > + {day.getDate()} + </Button> + </span> + ); + })} + </div> + ))} + </div> + </div> + ); + })} + </div> + </div> + ); +} + +export { Calendar }; diff --git a/frontend/src/components/ui/combobox.jsx b/frontend/src/components/ui/combobox.jsx new file mode 100644 index 00000000..c557c830 --- /dev/null +++ b/frontend/src/components/ui/combobox.jsx @@ -0,0 +1,280 @@ +import * as React from 'react'; +import { Check, ChevronsUpDown, Plus, X } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { + Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, +} from '@/components/ui/command'; +import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; +import { useFieldProps } from '@/components/ui/field-context'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.ui-combobox*). + +// Chips shown in a multi trigger before the rest collapse into "+N". +const DEFAULT_MAX_CHIPS = 3; + +function groupOptions(options) { + const groups = []; + const byName = new Map(); + for (const option of options) { + const name = option.group || ''; + if (!byName.has(name)) { + const group = { name, options: [] }; + byName.set(name, group); + groups.push(group); + } + byName.get(name).options.push(option); + } + return groups; +} + +function OptionIcon({ icon: Icon }) { + if (!Icon) return null; + if (React.isValidElement(Icon)) return <span className="ui-combobox__option-icon">{Icon}</span>; + return <Icon className="ui-combobox__option-icon" aria-hidden="true" />; +} + +/** + * Searchable select for one value or many. + * + * <Combobox options={servers} value={id} onChange={setId} placeholder="Pick a server" /> + * <Combobox multiple options={scopes} value={picked} onChange={setPicked} /> + * <Combobox multiple creatable options={tags} value={tags} onChange={setTags} /> + * + * Options are `{ value, label, description?, icon?, group?, disabled? }`; + * `group` buckets them under a heading in the order they first appear. + * Single mode closes on pick; multiple stays open and toggles. `creatable` + * offers the typed text as a new value (calls `onCreate(text)` when given, + * otherwise adds the text itself). Search matches label, description and + * value. For server-side search pass `onSearch` and filter `options` yourself. + */ +const Combobox = React.forwardRef(({ + options = [], + value, + onChange, + multiple = false, + creatable = false, + onCreate, + onSearch, + clearable = true, + placeholder, + searchPlaceholder, + emptyMessage, + loading = false, + disabled = false, + size, + maxChips = DEFAULT_MAX_CHIPS, + className, + ...props +}, ref) => { + const { t } = useTranslation(); + const fieldProps = useFieldProps(props); + const [open, setOpen] = React.useState(false); + const [query, setQuery] = React.useState(''); + + const selectedValues = multiple ? (value || []) : (value == null || value === '' ? [] : [value]); + const selectedSet = new Set(selectedValues.map(String)); + const byValue = new Map(options.map((option) => [String(option.value), option])); + const selectedOptions = selectedValues.map((v) => byValue.get(String(v)) || { value: v, label: String(v) }); + const trimmed = query.trim(); + const exactMatch = trimmed && options.some((option) => option.label.toLowerCase() === trimmed.toLowerCase()); + const canCreate = creatable && trimmed && !exactMatch && !selectedSet.has(trimmed); + + const changeQuery = (next) => { + setQuery(next); + onSearch?.(next); + }; + + const setOpenState = (next) => { + setOpen(next); + if (!next) changeQuery(''); + }; + + const toggle = (option) => { + if (!multiple) { + onChange?.(option.value); + setOpenState(false); + return; + } + const key = String(option.value); + onChange?.(selectedSet.has(key) + ? selectedValues.filter((v) => String(v) !== key) + : [...selectedValues, option.value]); + }; + + const create = () => { + if (onCreate) onCreate(trimmed); + else if (multiple) onChange?.([...selectedValues, trimmed]); + else onChange?.(trimmed); + changeQuery(''); + if (!multiple) setOpenState(false); + }; + + const remove = (option) => { + onChange?.(selectedValues.filter((v) => String(v) !== String(option.value))); + }; + + const clear = () => onChange?.(multiple ? [] : null); + + const single = !multiple && selectedOptions[0]; + const hiddenCount = Math.max(0, selectedOptions.length - maxChips); + const showClear = clearable && !disabled && selectedOptions.length > 0; + + return ( + <Popover open={open} onOpenChange={setOpenState}> + <PopoverAnchor asChild> + <div + className={cn( + 'ui-combobox', + size === 'sm' && 'ui-combobox--sm', + multiple && 'ui-combobox--multiple', + fieldProps['aria-invalid'] && 'is-invalid', + disabled && 'is-disabled', + className, + )} + // The chip row is part of the control: a click on its + // empty space opens the list like the trigger does. + onClick={(event) => { + if (event.target === event.currentTarget && !disabled) setOpenState(true); + }} + > + {multiple && selectedOptions.slice(0, maxChips).map((option) => ( + <span key={String(option.value)} className="ui-combobox__chip"> + <OptionIcon icon={option.icon} /> + <span className="ui-combobox__chip-label">{option.label}</span> + {!disabled && ( + <Button variant="unstyled" + type="button" + className="ui-combobox__chip-remove" + aria-label={t('common.controls.removeItem', 'Remove {{label}}', { label: option.label })} + onClick={() => remove(option)} + > + <X aria-hidden="true" /> + </Button> + )} + </span> + ))} + {multiple && hiddenCount > 0 && ( + <span className="ui-combobox__more"> + {t('common.controls.moreCount', '+{{count}}', { count: hiddenCount })} + </span> + )} + <PopoverTrigger asChild> + <Button variant="unstyled" + ref={ref} + type="button" + role="combobox" + aria-expanded={open} + aria-haspopup="listbox" + disabled={disabled} + className="ui-combobox__trigger" + {...fieldProps} + > + {single ? ( + <span className="ui-combobox__value"> + <OptionIcon icon={single.icon} /> + <span className="ui-combobox__value-label">{single.label}</span> + </span> + ) : ( + (!multiple || selectedOptions.length === 0) && ( + <span className="ui-combobox__placeholder"> + {placeholder || t('common.controls.select', 'Select…')} + </span> + ) + )} + <ChevronsUpDown className="ui-combobox__chevron" aria-hidden="true" /> + </Button> + </PopoverTrigger> + {showClear && ( + <Button variant="unstyled" + type="button" + className="ui-combobox__clear" + aria-label={t('common.controls.clearSelection', 'Clear selection')} + onClick={clear} + > + <X aria-hidden="true" /> + </Button> + )} + </div> + </PopoverAnchor> + <PopoverContent className="ui-combobox__panel" align="start" sideOffset={4}> + <Command shouldFilter={!onSearch} loop> + <CommandInput + value={query} + onValueChange={changeQuery} + placeholder={searchPlaceholder || t('common.controls.search', 'Search…')} + /> + <CommandList> + {loading && ( + <div className="ui-combobox__message" role="status"> + {t('common.state.loading', 'Loading')} + </div> + )} + {!loading && ( + <CommandEmpty> + {emptyMessage || t('common.state.noResults', 'No results found')} + </CommandEmpty> + )} + {groupOptions(options).map((group) => ( + <CommandGroup key={group.name || '_'} heading={group.name || undefined}> + {group.options.map((option) => { + const selected = selectedSet.has(String(option.value)); + return ( + <CommandItem + key={String(option.value)} + value={String(option.value)} + keywords={[option.label, option.description].filter(Boolean)} + disabled={option.disabled} + onSelect={() => toggle(option)} + className="ui-combobox__option" + data-checked={selected || undefined} + > + {multiple && ( + <span className="ui-combobox__checkbox" aria-hidden="true"> + {selected && <Check />} + </span> + )} + <OptionIcon icon={option.icon} /> + <span className="ui-combobox__option-copy"> + <span>{option.label}</span> + {option.description && <small>{option.description}</small>} + </span> + {!multiple && selected && ( + <Check className="ui-combobox__check" aria-hidden="true" /> + )} + </CommandItem> + ); + })} + </CommandGroup> + ))} + {canCreate && ( + <CommandGroup forceMount> + <CommandItem + forceMount + value={`__create__${trimmed}`} + onSelect={create} + className="ui-combobox__option ui-combobox__create" + > + <Plus className="ui-combobox__option-icon" aria-hidden="true" /> + <span>{t('common.controls.createValue', 'Create “{{value}}”', { value: trimmed })}</span> + </CommandItem> + </CommandGroup> + )} + </CommandList> + {multiple && selectedOptions.length > 0 && ( + <div className="ui-combobox__footer"> + <span>{t('common.controls.selectedCount', '{{count}} selected', { count: selectedOptions.length })}</span> + <Button variant="unstyled" type="button" className="ui-combobox__footer-action" onClick={clear}> + {t('common.controls.clearAll', 'Clear all')} + </Button> + </div> + )} + </Command> + </PopoverContent> + </Popover> + ); +}); +Combobox.displayName = 'Combobox'; + +export { Combobox }; diff --git a/frontend/src/components/ui/date-picker.jsx b/frontend/src/components/ui/date-picker.jsx new file mode 100644 index 00000000..57ea425d --- /dev/null +++ b/frontend/src/components/ui/date-picker.jsx @@ -0,0 +1,226 @@ +import * as React from 'react'; +import { CalendarDays, X } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Calendar } from '@/components/ui/calendar'; +import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; +import { useFieldProps } from '@/components/ui/field-context'; +import useFormat from '@/hooks/useFormat'; +import { isSameDay, startOfDay } from '@/lib/dateMath'; +import { defaultRangePresets } from '@/components/ui/dateRangePresets'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.ui-date-picker*). + +/** Trigger + clear button shared by both pickers. */ +const PickerTrigger = React.forwardRef(({ + label, placeholder, open, disabled, size, invalid, onClear, clearLabel, fieldProps, className, +}, ref) => ( + <PopoverAnchor asChild> + <div className={cn( + 'ui-date-picker', + size === 'sm' && 'ui-date-picker--sm', + invalid && 'is-invalid', + disabled && 'is-disabled', + className, + )}> + <PopoverTrigger asChild> + <Button variant="unstyled" + ref={ref} + type="button" + aria-haspopup="dialog" + aria-expanded={open} + disabled={disabled} + className="ui-date-picker__trigger" + {...fieldProps} + > + <CalendarDays className="ui-date-picker__icon" aria-hidden="true" /> + {label + ? <span className="ui-date-picker__value">{label}</span> + : <span className="ui-date-picker__placeholder">{placeholder}</span>} + </Button> + </PopoverTrigger> + {onClear && ( + <Button variant="unstyled" type="button" className="ui-date-picker__clear" aria-label={clearLabel} onClick={onClear}> + <X aria-hidden="true" /> + </Button> + )} + </div> + </PopoverAnchor> +)); +PickerTrigger.displayName = 'PickerTrigger'; + +/** + * One calendar day. + * + * <DatePicker value={expires} onChange={setExpires} min={new Date()} /> + * + * `value` is a local-midnight Date or null (lib/dateMath has toISODate / + * fromISODate for the wire). Picking a day closes the popover. + */ +const DatePicker = React.forwardRef(({ + value, + onChange, + min, + max, + isDateDisabled, + placeholder, + clearable = true, + disabled = false, + size, + className, + ...props +}, ref) => { + const { t } = useTranslation(); + const { formatDate } = useFormat(); + const fieldProps = useFieldProps(props); + const [open, setOpen] = React.useState(false); + + return ( + <Popover open={open} onOpenChange={setOpen}> + <PickerTrigger + ref={ref} + label={value ? formatDate(value, { style: 'medium' }) : null} + placeholder={placeholder || t('common.controls.pickDate', 'Pick a date')} + open={open} + disabled={disabled} + size={size} + invalid={fieldProps['aria-invalid']} + fieldProps={fieldProps} + className={className} + clearLabel={t('common.controls.clearDate', 'Clear date')} + onClear={clearable && value && !disabled ? () => onChange?.(null) : null} + /> + <PopoverContent className="ui-date-picker__panel" align="start"> + <Calendar + autoFocus + value={value} + min={min} + max={max} + isDateDisabled={isDateDisabled} + onChange={(day) => { onChange?.(day); setOpen(false); }} + /> + </PopoverContent> + </Popover> + ); +}); +DatePicker.displayName = 'DatePicker'; + +/** + * A start–end range of days with quick presets, for log, metric and audit + * filters. + * + * <DateRangePicker value={range} onChange={setRange} max={new Date()} /> + * + * `value` is `{ start, end }` (either may be null). The first click picks the + * start, the second the end (in either order); the popover closes once both + * are set. `presets={[]}` hides the preset list. + */ +const DateRangePicker = React.forwardRef(({ + value, + onChange, + min, + max, + presets, + months = 2, + placeholder, + clearable = true, + disabled = false, + size, + className, + ...props +}, ref) => { + const { t } = useTranslation(); + const { formatDate } = useFormat(); + const fieldProps = useFieldProps(props); + const [open, setOpen] = React.useState(false); + const [draft, setDraft] = React.useState(value || { start: null, end: null }); + const presetList = presets ?? defaultRangePresets(t); + + // Each opening starts from the committed value; a half-picked range that + // was dismissed does not come back. + const openChange = (next) => { + if (next) setDraft(value || { start: null, end: null }); + setOpen(next); + }; + + const today = startOfDay(new Date()); + const activePreset = value?.start && value?.end && presetList.find((preset) => { + const range = preset.range(today); + return isSameDay(range.start, value.start) && isSameDay(range.end, value.end); + }); + + let label = null; + if (activePreset) label = activePreset.label; + else if (value?.start && value?.end) { + label = isSameDay(value.start, value.end) + ? formatDate(value.start, { style: 'medium' }) + : t('common.controls.dateRange', '{{start}} – {{end}}', { + start: formatDate(value.start, { style: 'medium' }), + end: formatDate(value.end, { style: 'medium' }), + }); + } + + const commit = (range) => { + setDraft(range); + if (range.start && range.end) { + onChange?.(range); + setOpen(false); + } + }; + + return ( + <Popover open={open} onOpenChange={openChange}> + <PickerTrigger + ref={ref} + label={label} + placeholder={placeholder || t('common.controls.pickDateRange', 'Pick a date range')} + open={open} + disabled={disabled} + size={size} + invalid={fieldProps['aria-invalid']} + fieldProps={fieldProps} + className={className} + clearLabel={t('common.controls.clearDateRange', 'Clear date range')} + onClear={clearable && value?.start && !disabled ? () => onChange?.({ start: null, end: null }) : null} + /> + <PopoverContent className="ui-date-picker__panel ui-date-picker__panel--range" align="start"> + {presetList.length > 0 && ( + <ul className="ui-date-picker__presets" aria-label={t('common.controls.presets', 'Presets')}> + {presetList.map((preset) => ( + <li key={preset.id}> + <Button variant="unstyled" + type="button" + className={cn('ui-date-picker__preset', activePreset?.id === preset.id && 'is-active')} + aria-pressed={activePreset?.id === preset.id} + onClick={() => commit(preset.range(today))} + > + {preset.label} + </Button> + </li> + ))} + </ul> + )} + <div className="ui-date-picker__range-body"> + <Calendar + autoFocus + mode="range" + months={months} + value={draft} + min={min} + max={max} + onChange={commit} + /> + <p className="ui-date-picker__hint" aria-live="polite"> + {draft.start && !draft.end + ? t('common.controls.pickEndDate', 'Now pick the end date.') + : t('common.controls.pickStartDate', 'Pick a start date, or choose a preset.')} + </p> + </div> + </PopoverContent> + </Popover> + ); +}); +DateRangePicker.displayName = 'DateRangePicker'; + +export { DatePicker, DateRangePicker }; diff --git a/frontend/src/components/ui/dateRangePresets.js b/frontend/src/components/ui/dateRangePresets.js new file mode 100644 index 00000000..fc5df0c4 --- /dev/null +++ b/frontend/src/components/ui/dateRangePresets.js @@ -0,0 +1,23 @@ +import { addDays, addMonths, endOfMonth, startOfMonth } from '@/lib/dateMath'; + +/** + * The presets most range filters want. Each is computed when opened, so + * "Last 7 days" means the seven days before today, not before page load. + */ +export function defaultRangePresets(t) { + return [ + { id: 'today', label: t('common.controls.presetToday', 'Today'), range: (today) => ({ start: today, end: today }) }, + { id: 'yesterday', label: t('common.controls.presetYesterday', 'Yesterday'), range: (today) => ({ start: addDays(today, -1), end: addDays(today, -1) }) }, + { id: 'last7', label: t('common.controls.presetLast7', 'Last 7 days'), range: (today) => ({ start: addDays(today, -6), end: today }) }, + { id: 'last30', label: t('common.controls.presetLast30', 'Last 30 days'), range: (today) => ({ start: addDays(today, -29), end: today }) }, + { id: 'thisMonth', label: t('common.controls.presetThisMonth', 'This month'), range: (today) => ({ start: startOfMonth(today), end: today }) }, + { + id: 'lastMonth', + label: t('common.controls.presetLastMonth', 'Last month'), + range: (today) => { + const previous = addMonths(startOfMonth(today), -1); + return { start: previous, end: endOfMonth(previous) }; + }, + }, + ]; +} diff --git a/frontend/src/components/ui/field-context.js b/frontend/src/components/ui/field-context.js new file mode 100644 index 00000000..3da95e00 --- /dev/null +++ b/frontend/src/components/ui/field-context.js @@ -0,0 +1,32 @@ +import { createContext, useContext } from 'react'; + +// FormField publishes the ids of its label, hint and error here so the control +// inside it can point at them without every call site threading +// `aria-describedby` by hand. Controls read it through useFieldProps(). +// +// Overlays (popover, dialog, sheet) reset it to null: their content is a +// portal but still a React child, and a search box inside a picker's popover +// must not claim the field's id. +export const FieldContext = createContext(null); + +export function useField() { + return useContext(FieldContext); +} + +/** + * Merge the surrounding FormField's wiring into a control's props. Explicit + * props win; `aria-describedby` is joined rather than replaced. + */ +export function useFieldProps(props = {}) { + const field = useContext(FieldContext); + if (!field) return props; + const describedBy = [props['aria-describedby'], field.describedBy] + .filter(Boolean).join(' ') || undefined; + return { + ...props, + id: props.id ?? field.id, + 'aria-describedby': describedBy, + 'aria-invalid': props['aria-invalid'] ?? (field.invalid || undefined), + 'aria-required': props['aria-required'] ?? (field.required || undefined), + }; +} diff --git a/frontend/src/components/ui/file-dropzone.jsx b/frontend/src/components/ui/file-dropzone.jsx new file mode 100644 index 00000000..a1cb3212 --- /dev/null +++ b/frontend/src/components/ui/file-dropzone.jsx @@ -0,0 +1,236 @@ +import * as React from 'react'; +import { AlertCircle, CheckCircle2, FileText, RotateCcw, UploadCloud, X } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { ProgressBar } from '@/components/ProgressBar'; +import { useFieldProps } from '@/components/ui/field-context'; +import { validateFiles } from '@/lib/fileAccept'; +import { formatBytes } from '@/utils/formatBytes'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.ui-dropzone*, .ui-upload-list*). + +/** + * Drop target + browse button. It validates and hands files over; uploading + * is the caller's job (show progress with FileUploadList). + * + * <FileDropzone accept=".zip,.tar.gz" maxSize={512 * MB} + * onFiles={(accepted) => startUpload(accepted)} + * onReject={(rejected) => …} /> + * + * `accept` uses <input accept> grammar and is re-checked on drop (the browser + * only filters its own picker). Rejections carry a reason ('type' | 'size' | + * 'count'); with no `onReject` they are listed inside the zone. The whole + * zone is one button: Enter / Space opens the picker. + */ +const FileDropzone = React.forwardRef(({ + accept, + maxSize, + maxFiles, + existingCount = 0, + multiple = true, + onFiles, + onReject, + disabled = false, + title, + hint, + compact = false, + className, + ...props +}, ref) => { + const { t } = useTranslation(); + const fieldProps = useFieldProps(props); + const inputRef = React.useRef(null); + const depth = React.useRef(0); + const [dragging, setDragging] = React.useState(false); + const [rejections, setRejections] = React.useState([]); + const hintId = React.useId(); + + const take = (fileList) => { + const files = Array.from(fileList || []); + if (!files.length) return; + const { accepted, rejected } = validateFiles(multiple ? files : files.slice(0, 1), { + accept, maxSize, maxFiles, existingCount, + }); + if (accepted.length) onFiles?.(accepted); + if (onReject) onReject(rejected); + else setRejections(rejected); + }; + + const reasonText = ({ file, reason }) => { + if (reason === 'size') { + return t('common.controls.fileTooLarge', '{{name}} is larger than {{max}}.', { name: file.name, max: formatBytes(maxSize) }); + } + if (reason === 'count') { + return t('common.controls.tooManyFiles', '{{name}} was not added: the limit is {{max}} files.', { name: file.name, max: maxFiles }); + } + return t('common.controls.fileTypeNotAllowed', '{{name}} is not an allowed file type.', { name: file.name }); + }; + + const open = () => { if (!disabled) inputRef.current?.click(); }; + + const limits = [ + accept && accept.split(',').map((part) => part.trim()).join(', '), + Number.isFinite(maxSize) && t('common.controls.upToSize', 'up to {{size}}', { size: formatBytes(maxSize) }), + ].filter(Boolean).join(' · '); + + return ( + <div className={cn('ui-dropzone-field', className)}> + <div + ref={ref} + role="button" + tabIndex={disabled ? -1 : 0} + aria-disabled={disabled || undefined} + aria-describedby={[hintId, fieldProps['aria-describedby']].filter(Boolean).join(' ')} + id={fieldProps.id} + className={cn( + 'ui-dropzone', + compact && 'ui-dropzone--compact', + dragging && 'is-dragging', + disabled && 'is-disabled', + fieldProps['aria-invalid'] && 'is-invalid', + )} + onClick={open} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); open(); } + }} + onDragEnter={(event) => { + event.preventDefault(); + if (disabled) return; + // dragenter/leave fire for every child crossed; count depth + // so the highlight does not flicker over the icon and text. + depth.current += 1; + setDragging(true); + }} + onDragOver={(event) => { + event.preventDefault(); + if (!disabled) event.dataTransfer.dropEffect = 'copy'; + }} + onDragLeave={() => { + depth.current = Math.max(0, depth.current - 1); + if (depth.current === 0) setDragging(false); + }} + onDrop={(event) => { + event.preventDefault(); + depth.current = 0; + setDragging(false); + if (!disabled) take(event.dataTransfer.files); + }} + > + <UploadCloud className="ui-dropzone__icon" aria-hidden="true" /> + <span className="ui-dropzone__copy"> + <span className="ui-dropzone__title"> + {dragging + ? t('common.controls.dropToUpload', 'Drop to add') + : (title || t('common.controls.dropOrBrowse', 'Drop files here or browse'))} + </span> + <span id={hintId} className="ui-dropzone__hint">{hint || limits}</span> + </span> + </div> + {/* Outside the zone: input.click() bubbles, and a click reaching + the zone would open the picker a second time. */} + <input + ref={inputRef} + type="file" + className="sr-only" + tabIndex={-1} + aria-hidden="true" + accept={accept} + multiple={multiple} + disabled={disabled} + onChange={(event) => { take(event.target.files); event.target.value = ''; }} + /> + {rejections.length > 0 && ( + <ul className="ui-dropzone__rejections" role="alert"> + {rejections.map((rejection) => ( + <li key={`${rejection.file.name}-${rejection.reason}`}> + <AlertCircle aria-hidden="true" /> + <span>{reasonText(rejection)}</span> + </li> + ))} + </ul> + )} + </div> + ); +}); +FileDropzone.displayName = 'FileDropzone'; + +const ITEM_ICONS = { done: CheckCircle2, error: AlertCircle }; + +/** + * The files of an upload and where each one is. + * + * <FileUploadList items={uploads} onRetry={retry} onRemove={remove} /> + * + * Items are `{ id, name, size, status, progress?, error? }` with status + * 'queued' | 'uploading' | 'done' | 'error'. Retry shows on errors, remove on + * anything not mid-upload (pass `onCancel` to offer cancelling those). + */ +function FileUploadList({ items = [], onRetry, onRemove, onCancel, className }) { + const { t } = useTranslation(); + if (!items.length) return null; + const statusText = (item) => { + if (item.status === 'uploading') { + return t('common.controls.uploadingPercent', 'Uploading {{percent}}%', { percent: Math.round(item.progress || 0) }); + } + if (item.status === 'done') return t('common.controls.uploaded', 'Uploaded'); + if (item.status === 'error') return item.error || t('common.controls.uploadFailed', 'Upload failed'); + return t('common.controls.queued', 'Queued'); + }; + return ( + <ul className={cn('ui-upload-list', className)}> + {items.map((item) => { + const Icon = ITEM_ICONS[item.status] || FileText; + const busy = item.status === 'uploading'; + return ( + <li key={item.id} className={cn('ui-upload-list__item', `is-${item.status || 'queued'}`)}> + <Icon className="ui-upload-list__icon" aria-hidden="true" /> + <div className="ui-upload-list__body"> + <div className="ui-upload-list__row"> + <span className="ui-upload-list__name" title={item.name}>{item.name}</span> + {Number.isFinite(item.size) && ( + <span className="ui-upload-list__size">{formatBytes(item.size)}</span> + )} + </div> + {busy && ( + <ProgressBar + percent={item.progress || 0} + label={t('common.controls.uploadingName', 'Uploading {{name}}', { name: item.name })} + /> + )} + <span className="ui-upload-list__status" aria-live={busy ? 'off' : 'polite'}> + {statusText(item)} + </span> + </div> + <div className="ui-upload-list__actions"> + {item.status === 'error' && onRetry && ( + <Button variant="unstyled" + type="button" + className="ui-upload-list__action" + aria-label={t('common.controls.retryItem', 'Retry {{name}}', { name: item.name })} + onClick={() => onRetry(item)} + > + <RotateCcw aria-hidden="true" /> + </Button> + )} + {(busy ? onCancel : onRemove) && ( + <Button variant="unstyled" + type="button" + className="ui-upload-list__action" + aria-label={busy + ? t('common.controls.cancelItem', 'Cancel {{name}}', { name: item.name }) + : t('common.controls.removeItem', 'Remove {{label}}', { label: item.name })} + onClick={() => (busy ? onCancel(item) : onRemove(item))} + > + <X aria-hidden="true" /> + </Button> + )} + </div> + </li> + ); + })} + </ul> + ); +} + +export { FileDropzone, FileUploadList }; diff --git a/frontend/src/components/ui/input.jsx b/frontend/src/components/ui/input.jsx index ecd4dddc..973b7380 100644 --- a/frontend/src/components/ui/input.jsx +++ b/frontend/src/components/ui/input.jsx @@ -1,14 +1,18 @@ +import * as React from 'react'; +import { useFieldProps } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; -function Input({ className, type, ...props }) { - return ( - <input - type={type} - data-slot="input" - className={cn('ui-input', className)} - {...props} - /> - ); -} +// forwardRef so composed controls (TagInput, NumberField) and callers can +// focus the element; a plain function component silently drops `ref`. +const Input = React.forwardRef(({ className, type, ...props }, ref) => ( + <input + ref={ref} + type={type} + data-slot="input" + className={cn('ui-input', className)} + {...useFieldProps(props)} + /> +)); +Input.displayName = 'Input'; export { Input }; diff --git a/frontend/src/components/ui/number-field.jsx b/frontend/src/components/ui/number-field.jsx new file mode 100644 index 00000000..fae79ffb --- /dev/null +++ b/frontend/src/components/ui/number-field.jsx @@ -0,0 +1,215 @@ +import * as React from 'react'; +import { Minus, Plus } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { useFieldProps } from '@/components/ui/field-context'; +import { + clamp, decimalsOf, isPartialNumber, normalizeNumber, parseNumber, stepNumber, +} from '@/lib/numberMath'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.ui-number-field*). + +// Press-and-hold on a stepper: one step at once, then repeat after a pause. +const HOLD_DELAY_MS = 400; +const HOLD_INTERVAL_MS = 60; +// PageUp/PageDown and Shift+Arrow move this many steps. +const LARGE_STEP_MULTIPLIER = 10; + +/** + * Numeric input with steppers, for ports, limits, counts and retention. + * + * <NumberField value={workers} onChange={setWorkers} min={1} max={64} /> + * <NumberField value={mem} onChange={setMem} min={128} step={128} unit="MB" /> + * + * `onChange` receives a number, or null while the field is empty. Typing is + * free; the value is clamped to [min, max] and snapped to `step` on blur and + * Enter, and the field reads as invalid while a typed value is out of range. + * Keyboard: ↑/↓ step, Shift+↑/↓ and PageUp/PageDown ×10, Home/End jump to + * min/max. The steppers repeat while held and are skipped by Tab, so the + * field is a single tab stop like a native spinbutton. + */ +const NumberField = React.forwardRef(({ + value, + onChange, + min, + max, + step = 1, + unit, + size, + placeholder, + disabled = false, + readOnly = false, + hideSteppers = false, + className, + onBlur, + onKeyDown, + ...props +}, ref) => { + const { t } = useTranslation(); + const fieldProps = useFieldProps(props); + const [draft, setDraft] = React.useState(null); + const latest = React.useRef(value); + latest.current = value; + const holdTimer = React.useRef(null); + + const current = value === '' || value === undefined ? null : value; + const text = draft ?? (current === null ? '' : String(current)); + const typed = draft === null ? current : parseNumber(draft); + const outOfRange = typed !== null && clamp(typed, min, max) !== typed; + const allowDecimal = decimalsOf(step) > 0 || (Number.isFinite(min) && decimalsOf(min) > 0); + const allowNegative = !Number.isFinite(min) || min < 0; + const options = { min, max, step }; + const interactive = !disabled && !readOnly; + + // Compare against the ref, not the render's `value`: the hold interval + // keeps one closure alive across many re-renders. + const emit = (next) => { + if (next === latest.current) return false; + latest.current = next; + onChange?.(next); + return true; + }; + + const commit = () => { + if (draft === null) return; + const parsed = parseNumber(draft); + setDraft(null); + emit(parsed === null ? null : normalizeNumber(parsed, options)); + }; + + const nudge = (direction, multiplier = 1) => { + const base = draft === null ? latest.current : parseNumber(draft); + setDraft(null); + emit(stepNumber(base ?? null, direction, { ...options, multiplier })); + }; + + const stopHold = () => { + clearTimeout(holdTimer.current); + holdTimer.current = null; + }; + React.useEffect(() => stopHold, []); + + // A timeout chain rather than an interval: each repeat schedules the next, + // so a bound reached mid-hold simply stops scheduling. (A disabled button + // never sees pointerup, so the chain cannot rely on it.) + const repeat = (direction) => { + holdTimer.current = setTimeout(() => { + if (emit(stepNumber(latest.current ?? null, direction, options))) repeat(direction); + else stopHold(); + }, HOLD_INTERVAL_MS); + }; + + const startHold = (direction) => (event) => { + if (!interactive || event.button !== 0) return; + event.preventDefault(); // keep focus where it was (usually the input) + nudge(direction); + holdTimer.current = setTimeout(() => repeat(direction), HOLD_DELAY_MS); + }; + + const handleKeyDown = (event) => { + onKeyDown?.(event); + if (event.defaultPrevented || !interactive) return; + const large = event.shiftKey ? LARGE_STEP_MULTIPLIER : 1; + const keyActions = { + ArrowUp: () => nudge(1, large), + ArrowDown: () => nudge(-1, large), + PageUp: () => nudge(1, LARGE_STEP_MULTIPLIER), + PageDown: () => nudge(-1, LARGE_STEP_MULTIPLIER), + Home: Number.isFinite(min) ? () => { setDraft(null); emit(min); } : null, + End: Number.isFinite(max) ? () => { setDraft(null); emit(max); } : null, + Enter: draft !== null ? commit : null, + }; + const action = keyActions[event.key]; + if (!action) return; + event.preventDefault(); + action(); + }; + + const handleChange = (event) => { + const next = event.target.value.trim(); + if (!isPartialNumber(next, { allowNegative, allowDecimal })) return; + setDraft(next); + const parsed = parseNumber(next); + // Emit while typing so a form sees the number before blur; clamping + // waits for commit so typing "1" on the way to "12" is not forced up. + if (parsed !== null || next === '') emit(parsed); + }; + + const atMin = current !== null && Number.isFinite(min) && current <= min; + const atMax = current !== null && Number.isFinite(max) && current >= max; + const invalid = fieldProps['aria-invalid'] || outOfRange || undefined; + + return ( + <div + className={cn( + 'ui-number-field', + size === 'sm' && 'ui-number-field--sm', + invalid && 'is-invalid', + disabled && 'is-disabled', + className, + )} + > + {!hideSteppers && ( + <Button variant="unstyled" + type="button" + tabIndex={-1} + className="ui-number-field__step" + aria-label={t('common.controls.decrease', 'Decrease')} + aria-controls={fieldProps.id} + disabled={!interactive || atMin} + onPointerDown={startHold(-1)} + onPointerUp={stopHold} + onPointerLeave={stopHold} + onPointerCancel={stopHold} + > + <Minus aria-hidden="true" /> + </Button> + )} + <div className="ui-number-field__input-wrap"> + <input + ref={ref} + type="text" + inputMode={allowDecimal ? 'decimal' : 'numeric'} + role="spinbutton" + autoComplete="off" + spellCheck={false} + className="ui-number-field__input" + value={text} + placeholder={placeholder} + disabled={disabled} + readOnly={readOnly} + aria-valuenow={current ?? undefined} + aria-valuemin={Number.isFinite(min) ? min : undefined} + aria-valuemax={Number.isFinite(max) ? max : undefined} + aria-valuetext={current !== null && unit ? `${current} ${unit}` : undefined} + {...fieldProps} + aria-invalid={invalid} + onChange={handleChange} + onKeyDown={handleKeyDown} + onBlur={(event) => { commit(); onBlur?.(event); }} + /> + {unit && <span className="ui-number-field__unit" aria-hidden="true">{unit}</span>} + </div> + {!hideSteppers && ( + <Button variant="unstyled" + type="button" + tabIndex={-1} + className="ui-number-field__step" + aria-label={t('common.controls.increase', 'Increase')} + aria-controls={fieldProps.id} + disabled={!interactive || atMax} + onPointerDown={startHold(1)} + onPointerUp={stopHold} + onPointerLeave={stopHold} + onPointerCancel={stopHold} + > + <Plus aria-hidden="true" /> + </Button> + )} + </div> + ); +}); +NumberField.displayName = 'NumberField'; + +export { NumberField }; diff --git a/frontend/src/components/ui/pin-input.jsx b/frontend/src/components/ui/pin-input.jsx new file mode 100644 index 00000000..b2b99e26 --- /dev/null +++ b/frontend/src/components/ui/pin-input.jsx @@ -0,0 +1,153 @@ +import * as React from 'react'; +import { useTranslation } from 'react-i18next'; +import { useFieldProps } from '@/components/ui/field-context'; +import { cn } from '@/lib/utils'; + +// Styling lives in styles/components/_controls.scss (.ui-pin-input*). + +const PATTERNS = { + numeric: /^\d$/, + alphanumeric: /^[a-z0-9]$/i, +}; + +/** + * One-time code entry: a row of single-character cells. + * + * <PinInput length={6} value={code} onChange={setCode} onComplete={verify} /> + * + * Typing advances, Backspace walks back (clearing as it goes), arrows move, + * and pasting a code fills every cell at once — including the SMS / password + * manager autofill that `autocomplete="one-time-code"` invites. `onComplete` + * fires once when the last cell fills. `groupSize={3}` adds a gap mid-code. + */ +const PinInput = React.forwardRef(({ + length = 6, + value = '', + onChange, + onComplete, + type = 'numeric', + mask = false, + groupSize, + disabled = false, + autoFocus = false, + className, + 'aria-label': ariaLabel, + ...props +}, ref) => { + const { t } = useTranslation(); + const fieldProps = useFieldProps(props); + const cells = React.useRef([]); + React.useImperativeHandle(ref, () => cells.current[0]); + const pattern = PATTERNS[type] || PATTERNS.numeric; + const chars = Array.from({ length }, (_, i) => value[i] || ''); + + const focusCell = (index) => { + const cell = cells.current[Math.max(0, Math.min(length - 1, index))]; + cell?.focus(); + cell?.select(); + }; + + // Focus that follows a write waits for the re-render: moving it at once + // runs the cell's onFocus guard against the OLD value, which sends focus + // back to the first empty cell and the next keystroke overwrites a digit. + const pendingFocus = React.useRef(null); + React.useLayoutEffect(() => { + if (pendingFocus.current === null) return; + const index = pendingFocus.current; + pendingFocus.current = null; + focusCell(index); + }); + + // The code is always contiguous: no holes, so focus never lands past the + // first empty cell and the value is always a prefix of the final code. + const write = (next, focusIndex) => { + const code = next.slice(0, length); + if (code !== value) { + onChange?.(code); + if (code.length === length) onComplete?.(code); + } + if (focusIndex === undefined) return; + if (code === value) focusCell(focusIndex); + else pendingFocus.current = focusIndex; + }; + + const accept = (text) => Array.from(text).filter((ch) => pattern.test(ch)).join(''); + + const handleInput = (index) => (event) => { + // A cell already holding a character receives old + new; keep the new. + const raw = event.target.value; + const typed = accept(chars[index] && raw.length > 1 && raw.startsWith(chars[index]) ? raw.slice(1) : raw); + if (!typed) return; + const at = Math.min(index, value.length); + write(value.slice(0, at) + typed + value.slice(at + typed.length), at + typed.length); + }; + + const handleKeyDown = (index) => (event) => { + const moves = { + ArrowLeft: index - 1, + ArrowRight: Math.min(index + 1, value.length), + Home: 0, + End: Math.min(value.length, length - 1), + }; + if (event.key in moves) { + event.preventDefault(); + focusCell(moves[event.key]); + } else if (event.key === 'Backspace' || event.key === 'Delete') { + event.preventDefault(); + if (chars[index]) write(value.slice(0, index) + value.slice(index + 1), index); + else if (event.key === 'Backspace' && index > 0) write(value.slice(0, index - 1), index - 1); + } + }; + + const handlePaste = (event) => { + const pasted = accept(event.clipboardData.getData('text')); + if (!pasted) return; + event.preventDefault(); + write(pasted, Math.min(pasted.length, length - 1)); + }; + + const groupLabel = ariaLabel || t('common.controls.verificationCode', 'Verification code'); + + return ( + <div + role="group" + aria-label={groupLabel} + aria-describedby={fieldProps['aria-describedby']} + className={cn('ui-pin-input', fieldProps['aria-invalid'] && 'is-invalid', className)} + > + {chars.map((char, index) => ( + <React.Fragment key={index}> + {groupSize && index > 0 && index % groupSize === 0 && ( + <span className="ui-pin-input__separator" aria-hidden="true" /> + )} + <input + ref={(node) => { cells.current[index] = node; }} + id={index === 0 ? fieldProps.id : undefined} + type={mask ? 'password' : 'text'} + inputMode={type === 'numeric' ? 'numeric' : 'text'} + autoComplete={index === 0 ? 'one-time-code' : 'off'} + autoCapitalize="off" + spellCheck={false} + maxLength={length} + className={cn('ui-pin-input__cell', char && 'is-filled')} + value={char} + disabled={disabled} + autoFocus={autoFocus && index === 0} + aria-label={t('common.controls.characterOf', 'Character {{index}} of {{count}}', { index: index + 1, count: length })} + aria-invalid={fieldProps['aria-invalid']} + onChange={handleInput(index)} + onKeyDown={handleKeyDown(index)} + onPaste={handlePaste} + onFocus={(event) => { + if (index > value.length) focusCell(value.length); + else event.target.select(); + }} + /> + </React.Fragment> + ))} + </div> + ); +}); +PinInput.displayName = 'PinInput'; + +export { PinInput }; diff --git a/frontend/src/components/ui/popover.jsx b/frontend/src/components/ui/popover.jsx index f500f3e2..e83e3683 100644 --- a/frontend/src/components/ui/popover.jsx +++ b/frontend/src/components/ui/popover.jsx @@ -1,12 +1,15 @@ import * as React from 'react'; import * as PopoverPrimitive from '@radix-ui/react-popover'; +import { FieldContext } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; const Popover = PopoverPrimitive.Root; const PopoverTrigger = PopoverPrimitive.Trigger; const PopoverAnchor = PopoverPrimitive.Anchor; -const PopoverContent = React.forwardRef(({ className, align = 'center', sideOffset = 4, ...props }, ref) => ( +// The panel is outside the field that opened it: reset FieldContext so an +// input inside (a search box, a time input) does not take the field's id. +const PopoverContent = React.forwardRef(({ className, align = 'center', sideOffset = 4, children, ...props }, ref) => ( <PopoverPrimitive.Portal> <PopoverPrimitive.Content ref={ref} @@ -14,7 +17,9 @@ const PopoverContent = React.forwardRef(({ className, align = 'center', sideOffs sideOffset={sideOffset} className={cn('ui-popover-panel', className)} {...props} - /> + > + <FieldContext.Provider value={null}>{children}</FieldContext.Provider> + </PopoverPrimitive.Content> </PopoverPrimitive.Portal> )); PopoverContent.displayName = PopoverPrimitive.Content.displayName; diff --git a/frontend/src/components/ui/radio-group.jsx b/frontend/src/components/ui/radio-group.jsx new file mode 100644 index 00000000..b7e5aa36 --- /dev/null +++ b/frontend/src/components/ui/radio-group.jsx @@ -0,0 +1,80 @@ +import * as React from 'react'; +import * as RadioGroupPrimitive from '@radix-ui/react-radio-group'; +import { Check } from 'lucide-react'; +import { cn } from '@/lib/utils'; + +// Styling lives in styles/components/_controls.scss (.ui-radio*). + +/** + * One choice from a short, visible list — when the options deserve to be + * read side by side. Longer lists are a Select; two or three terse options in + * a toolbar are a SegControl. + * + * <RadioGroup value={strategy} onValueChange={setStrategy} options={[ + * { value: 'rolling', label: 'Rolling', description: 'Replace one at a time' }, + * { value: 'recreate', label: 'Recreate', description: 'Stop all, then start' }, + * ]} /> + * <RadioGroup variant="card" orientation="horizontal" … /> + * + * Arrow keys move and select (roving focus, one tab stop) — that is Radix. + */ +const RadioGroup = React.forwardRef(({ + options = [], + variant = 'default', + orientation = 'vertical', + className, + ...props +}, ref) => { + const baseId = React.useId(); + // A card is its own selection target, so the radio becomes a check badge + // in the corner instead of a second circle next to the icon. + const isCard = variant === 'card'; + return ( + <RadioGroupPrimitive.Root + ref={ref} + orientation={orientation} + className={cn( + 'ui-radio-group', + `ui-radio-group--${orientation}`, + isCard && 'ui-radio-group--card', + className, + )} + {...props} + > + {options.map((option) => { + const id = `${baseId}${option.value}`; + const descriptionId = option.description ? `${id}-description` : undefined; + const Icon = option.icon; + return ( + <label + key={option.value} + htmlFor={id} + className={cn('ui-radio', option.disabled && 'is-disabled')} + > + <RadioGroupPrimitive.Item + id={id} + value={option.value} + disabled={option.disabled} + aria-describedby={descriptionId} + className="ui-radio__control" + > + <RadioGroupPrimitive.Indicator className="ui-radio__dot"> + {isCard && <Check />} + </RadioGroupPrimitive.Indicator> + </RadioGroupPrimitive.Item> + {Icon && <Icon className="ui-radio__icon" aria-hidden="true" />} + <span className="ui-radio__copy"> + <span className="ui-radio__label">{option.label}</span> + {option.description && ( + <span id={descriptionId} className="ui-radio__description">{option.description}</span> + )} + </span> + </label> + ); + })} + </RadioGroupPrimitive.Root> + ); +}); +RadioGroup.displayName = 'RadioGroup'; + +export { RadioGroup }; diff --git a/frontend/src/components/ui/select.jsx b/frontend/src/components/ui/select.jsx index 85bd3ed8..a570056a 100644 --- a/frontend/src/components/ui/select.jsx +++ b/frontend/src/components/ui/select.jsx @@ -1,6 +1,7 @@ import * as React from 'react'; import * as SelectPrimitive from '@radix-ui/react-select'; import { Check, ChevronDown, ChevronUp } from 'lucide-react'; +import { useFieldProps } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; const Select = SelectPrimitive.Root; @@ -13,7 +14,7 @@ const SelectTrigger = React.forwardRef(({ className, children, size, ...props }, <SelectPrimitive.Trigger ref={ref} className={cn('ui-select-trigger', size === 'sm' && 'ui-select-trigger--sm', className)} - {...props} + {...useFieldProps(props)} > {children} <SelectPrimitive.Icon asChild> diff --git a/frontend/src/components/ui/slider.jsx b/frontend/src/components/ui/slider.jsx new file mode 100644 index 00000000..f62d69fb --- /dev/null +++ b/frontend/src/components/ui/slider.jsx @@ -0,0 +1,93 @@ +import * as React from 'react'; +import * as SliderPrimitive from '@radix-ui/react-slider'; +import { useFieldProps } from '@/components/ui/field-context'; +import { cn } from '@/lib/utils'; + +// Styling lives in styles/components/_controls.scss (.ui-slider*). + +/** + * Pick a value (or a range) on a bounded scale: memory limits, retention + * days, CPU shares. + * + * <Slider value={days} onChange={setDays} min={1} max={90} unit="days" /> + * <Slider value={[lo, hi]} onChange={([a, b]) => …} min={0} max={100} /> + * <Slider value={mb} onChange={setMb} min={256} max={8192} step={256} + * marks={[256, 2048, 4096, 8192]} format={(v) => `${v / 1024} GB`} /> + * + * Passing a number gives a number back; an array gives an array. The current + * value reads out beside the track (`showValue={false}` hides it). Radix + * handles the keyboard: arrows step, PageUp/PageDown ×10, Home/End. + */ +const Slider = React.forwardRef(({ + value, + onChange, + onCommit, + min = 0, + max = 100, + step = 1, + unit, + format, + marks, + showValue = true, + disabled = false, + className, + 'aria-label': ariaLabel, + ...props +}, ref) => { + const fieldProps = useFieldProps(props); + const isRange = Array.isArray(value); + const values = isRange ? value : [value ?? min]; + const show = (v) => (format ? format(v) : (unit ? `${v} ${unit}` : String(v))); + const percent = (v) => ((v - min) / (max - min)) * 100; + const emit = (handler) => (next) => handler?.(isRange ? next : next[0]); + + return ( + <div className={cn('ui-slider', disabled && 'is-disabled', marks?.length && 'ui-slider--marked', className)}> + <div className="ui-slider__body"> + <SliderPrimitive.Root + ref={ref} + className="ui-slider__root" + value={values} + min={min} + max={max} + step={step} + disabled={disabled} + minStepsBetweenThumbs={isRange ? 1 : undefined} + onValueChange={emit(onChange)} + onValueCommit={emit(onCommit)} + > + <SliderPrimitive.Track className="ui-slider__track"> + <SliderPrimitive.Range className="ui-slider__range" /> + </SliderPrimitive.Track> + {values.map((v, index) => ( + <SliderPrimitive.Thumb + key={index} + className="ui-slider__thumb" + id={index === 0 ? fieldProps.id : undefined} + aria-label={ariaLabel} + aria-describedby={fieldProps['aria-describedby']} + aria-valuetext={show(v)} + /> + ))} + </SliderPrimitive.Root> + {marks?.length > 0 && ( + <div className="ui-slider__marks" aria-hidden="true"> + {marks.map((mark) => ( + <span key={mark} className="ui-slider__mark" style={{ insetInlineStart: `${percent(mark)}%` }}> + {show(mark)} + </span> + ))} + </div> + )} + </div> + {showValue && ( + <output className="ui-slider__value" htmlFor={fieldProps.id}> + {values.map(show).join(' – ')} + </output> + )} + </div> + ); +}); +Slider.displayName = 'Slider'; + +export { Slider }; diff --git a/frontend/src/components/ui/tag-input.jsx b/frontend/src/components/ui/tag-input.jsx new file mode 100644 index 00000000..1ad35eef --- /dev/null +++ b/frontend/src/components/ui/tag-input.jsx @@ -0,0 +1,159 @@ +import * as React from 'react'; +import { X } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { useFieldProps } from '@/components/ui/field-context'; +import { cn } from '@/lib/utils'; +import { Button } from '@/components/ui/button'; + +// Styling lives in styles/components/_controls.scss (.ui-tag-input*). + +// How long an existing chip flashes when its duplicate is typed again. +const DUPLICATE_FLASH_MS = 900; +const PASTE_SPLIT = /[\s,;]+/; + +/** + * Free-form list of short values: domains, IPs, tags, header names. + * + * <TagInput value={aliases} onChange={setAliases} placeholder="Add a domain" /> + * <TagInput value={ips} onChange={setIps} validate={(v) => isIp(v) ? null : 'Not an IP'} /> + * + * Enter, comma or Tab (with text) adds the typed value; pasting a list splits + * on commas, spaces and newlines. Backspace in an empty box removes the last + * chip. `validate` returns an error string to reject a value (it stays in the + * box, marked invalid). A duplicate is not added; its chip flashes instead. + */ +const TagInput = React.forwardRef(({ + value = [], + onChange, + validate, + normalize = (text) => text.trim(), + max, + placeholder, + disabled = false, + size, + className, + onBlur, + ...props +}, ref) => { + const { t } = useTranslation(); + const fieldProps = useFieldProps(props); + const inputRef = React.useRef(null); + React.useImperativeHandle(ref, () => inputRef.current); + const [text, setText] = React.useState(''); + const [error, setError] = React.useState(null); + const [flash, setFlash] = React.useState(null); + const flashTimer = React.useRef(null); + const errorId = React.useId(); + React.useEffect(() => () => clearTimeout(flashTimer.current), []); + + const full = Number.isFinite(max) && value.length >= max; + + const flashChip = (item) => { + clearTimeout(flashTimer.current); + setFlash(item); + flashTimer.current = setTimeout(() => setFlash(null), DUPLICATE_FLASH_MS); + }; + + // Add every candidate it can; return the ones that failed so they stay typed. + const add = (candidates) => { + const next = [...value]; + let rejected = null; + for (const raw of candidates) { + const item = normalize(raw); + if (!item) continue; + if (next.includes(item)) { flashChip(item); continue; } + if (Number.isFinite(max) && next.length >= max) { rejected = { raw, message: null }; break; } + const message = validate?.(item, next) || null; + if (message) { rejected = { raw, message }; break; } + next.push(item); + } + if (next.length !== value.length) onChange?.(next); + setError(rejected?.message || null); + return rejected ? rejected.raw : ''; + }; + + const removeAt = (index) => { + onChange?.(value.filter((_, i) => i !== index)); + inputRef.current?.focus(); + }; + + const handleKeyDown = (event) => { + if (event.key === 'Enter' || event.key === ',' || (event.key === 'Tab' && text.trim())) { + if (!text.trim()) { if (event.key !== 'Tab') event.preventDefault(); return; } + event.preventDefault(); + setText(add([text])); + } else if (event.key === 'Backspace' && !text && value.length) { + event.preventDefault(); + onChange?.(value.slice(0, -1)); + } else if (event.key === 'Escape' && text) { + setText(''); + setError(null); + } + }; + + const handlePaste = (event) => { + const pasted = event.clipboardData.getData('text'); + if (!PASTE_SPLIT.test(pasted.trim())) return; // a single value pastes normally + event.preventDefault(); + setText(add(pasted.split(PASTE_SPLIT))); + }; + + const invalid = fieldProps['aria-invalid'] || Boolean(error) || undefined; + const describedBy = [fieldProps['aria-describedby'], error && errorId].filter(Boolean).join(' ') || undefined; + + return ( + <div className="ui-tag-input-field"> + <div + className={cn( + 'ui-tag-input', + size === 'sm' && 'ui-tag-input--sm', + invalid && 'is-invalid', + disabled && 'is-disabled', + className, + )} + onClick={(event) => { if (event.target === event.currentTarget) inputRef.current?.focus(); }} + > + {value.map((item, index) => ( + <span key={item} className={cn('ui-tag-input__chip', flash === item && 'is-flashing')}> + <span className="ui-tag-input__chip-label">{item}</span> + {!disabled && ( + <Button variant="unstyled" + type="button" + tabIndex={-1} + className="ui-tag-input__chip-remove" + aria-label={t('common.controls.removeItem', 'Remove {{label}}', { label: item })} + onClick={() => removeAt(index)} + > + <X aria-hidden="true" /> + </Button> + )} + </span> + ))} + <input + ref={inputRef} + type="text" + className="ui-tag-input__input" + value={text} + disabled={disabled || full} + placeholder={full ? '' : placeholder} + autoComplete="off" + spellCheck={false} + {...fieldProps} + aria-invalid={invalid} + aria-describedby={describedBy} + onChange={(event) => { setText(event.target.value); if (error) setError(null); }} + onKeyDown={handleKeyDown} + onPaste={handlePaste} + onBlur={(event) => { + if (text.trim()) setText(add([text])); + onBlur?.(event); + }} + /> + </div> + {error && <p id={errorId} className="ui-tag-input__error" role="alert">{error}</p>} + </div> + ); +}); +TagInput.displayName = 'TagInput'; + +export { TagInput }; diff --git a/frontend/src/components/ui/textarea.jsx b/frontend/src/components/ui/textarea.jsx index 92b74b03..b38dd74e 100644 --- a/frontend/src/components/ui/textarea.jsx +++ b/frontend/src/components/ui/textarea.jsx @@ -1,13 +1,15 @@ +import * as React from 'react'; +import { useFieldProps } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; -function Textarea({ className, ...props }) { - return ( - <textarea - data-slot="textarea" - className={cn('ui-textarea', className)} - {...props} - /> - ); -} +const Textarea = React.forwardRef(({ className, ...props }, ref) => ( + <textarea + ref={ref} + data-slot="textarea" + className={cn('ui-textarea', className)} + {...useFieldProps(props)} + /> +)); +Textarea.displayName = 'Textarea'; export { Textarea }; diff --git a/frontend/src/components/ui/tooltip.jsx b/frontend/src/components/ui/tooltip.jsx new file mode 100644 index 00000000..068400ed --- /dev/null +++ b/frontend/src/components/ui/tooltip.jsx @@ -0,0 +1,70 @@ +import * as React from 'react'; +import * as TooltipPrimitive from '@radix-ui/react-tooltip'; +import { cn } from '@/lib/utils'; + +// Styling lives in styles/components/_controls.scss (.ui-tooltip*). +// +// One TooltipProvider sits at the app root (App.jsx). Its skip delay is what +// makes a row of icon buttons feel right: the first tooltip waits, moving to +// the neighbour shows the next one at once. +const OPEN_DELAY_MS = 400; +const SKIP_DELAY_MS = 300; + +// Radix throws when a Tooltip renders outside a provider. Surfaces mounted +// outside App (an extension preview, an isolated test render) still get a +// working tooltip: Tooltip below supplies a provider when none is in scope. +const HasProvider = React.createContext(false); + +function TooltipProvider({ children, ...props }) { + return ( + <TooltipPrimitive.Provider delayDuration={OPEN_DELAY_MS} skipDelayDuration={SKIP_DELAY_MS} {...props}> + <HasProvider.Provider value>{children}</HasProvider.Provider> + </TooltipPrimitive.Provider> + ); +} + +function Tooltip(props) { + const root = <TooltipPrimitive.Root {...props} />; + return React.useContext(HasProvider) ? root : <TooltipProvider>{root}</TooltipProvider>; +} + +const TooltipTrigger = TooltipPrimitive.Trigger; + +const TooltipContent = React.forwardRef(({ className, sideOffset = 6, children, ...props }, ref) => ( + <TooltipPrimitive.Portal> + <TooltipPrimitive.Content + ref={ref} + sideOffset={sideOffset} + collisionPadding={8} + className={cn('ui-tooltip', className)} + {...props} + > + {children} + </TooltipPrimitive.Content> + </TooltipPrimitive.Portal> +)); +TooltipContent.displayName = TooltipPrimitive.Content.displayName; + +/** + * The everyday tooltip: wrap one focusable element. + * + * <Tip content="Restart service" shortcut="R"><IconButton … /></Tip> + * + * `content` is a short label, not a paragraph. A disabled button never fires + * pointer events, so wrap it in a span if its tooltip explains why it is off. + * With no `content` the child renders untouched. + */ +function Tip({ content, shortcut, side = 'top', align = 'center', delayDuration, children }) { + if (!content) return children; + return ( + <Tooltip delayDuration={delayDuration}> + <TooltipTrigger asChild>{children}</TooltipTrigger> + <TooltipContent side={side} align={align}> + <span>{content}</span> + {shortcut && <kbd className="ui-tooltip__kbd">{shortcut}</kbd>} + </TooltipContent> + </Tooltip> + ); +} + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider, Tip }; diff --git a/frontend/src/hooks/useFormat.js b/frontend/src/hooks/useFormat.js index 3f47f489..442343b2 100644 --- a/frontend/src/hooks/useFormat.js +++ b/frontend/src/hooks/useFormat.js @@ -26,6 +26,7 @@ export default function useFormat() { formatCompactNumber: intl.formatCompactNumber, formatPercent: intl.formatPercent, formatList: intl.formatList, + getWeekStart: intl.getWeekStart, locale: language, }), [language]); diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 780d8b54..a76f0a17 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -6748,6 +6748,125 @@ "controlledMonitoringContent": "Controlled monitoring content.", "controlledSecurityContent": "Controlled security content.", "controlledValueOnvaluechangeUsageThisShould": "Controlled value/onValueChange usage. This should match URL-backed pages behaviorally.", + "controls": { + "addDomain": "Add a domain", + "alerts": "Alert rules", + "apiScopes": "API key scopes", + "authCode": "Authenticator code", + "authCodeHint": "Six digits from your app.", + "authCodeWrong": "That code did not match. Try again.", + "comboboxNote": "Searchable single or multiple choice with groups, descriptions and disabled options. Multiple stays open and toggles.", + "comboboxTitle": "Combobox", + "compact": "Compact", + "copyUrl": "Copy URL", + "cpu": "CPU", + "datesNote": "Arrows move by day and week, PageUp/PageDown by month, Shift for a year. Month and weekday names follow the panel language.", + "datesTitle": "Date and range pickers", + "days": "days", + "delete": "Delete", + "deploy": "Deploy", + "deployDisabledWhy": "A deploy is already running", + "disabled": "Disabled", + "disk": "Disk", + "domains": "Domains", + "domainsHint": "Try “not a domain” or paste “a.com, b.com”.", + "dropDisabled": "Uploads are paused while a restore runs", + "dropzoneNote": "Type and size are re-checked on drop. Each file reports its own progress, error and retry.", + "dropzoneTitle": "File dropzone and upload list", + "empty": "Empty", + "files": "Files", + "formFieldNote": "The control gets the id, aria-describedby, aria-invalid and aria-required from FormField. No htmlFor needed.", + "formFieldTitle": "Form field wiring", + "groupProduction": "Production", + "groupStaging": "Staging", + "health": "Health check", + "healthFailed": "503 after 30 s", + "healthPath": "Health check path", + "healthPathError": "Must start with a slash.", + "hostDb01": "10.0.0.21 · Debian 13", + "hostStaging": "10.0.1.5 · Rocky 9", + "hostWeb01": "10.0.0.11 · Ubuntu 24.04", + "hostWeb02": "10.0.0.12 · Ubuntu 24.04", + "keyExpires": "Key expires", + "labels": "Labels", + "labelsHint": "Type a new label to create it.", + "loadingNote": "The label stays in the layout, so the button keeps its width. aria-busy while it lasts.", + "loadingTitle": "Button loading", + "local": "Local disk", + "localNote": "Fast. Lost if the server is.", + "logRange": "Log range", + "logRetention": "Log retention", + "manual": "Manual", + "manualNote": "Requires an admin.", + "memory": "Memory", + "memoryHint": "Steps of 128 MB", + "memoryLimit": "Memory limit", + "migrate": "Run migrations", + "migrationsApplied": "3 applied", + "notADomain": "“{{value}}” is not a domain.", + "notes": "Notes", + "notesHint": "Shown to everyone with access to this service.", + "numberNote": "↑/↓ step, Shift or PageUp/PageDown ×10, Home/End jump to the bounds. Hold a stepper to repeat.", + "numberTitle": "Number field", + "offline": "Offline", + "pickOne": "Pick at least one server.", + "pickScopes": "Choose scopes", + "pickServer": "Pick a server", + "pinNote": "Typing advances, Backspace walks back, paste fills every cell. Try 123456.", + "pinTitle": "Pin input", + "portRange": "Port range", + "progressCpu": "CPU · 94%", + "progressDisk": "Disk · 48 of 100 GB", + "progressMemory": "Memory · 78%", + "progressNote": "role=\"progressbar\" with value text; semantic tones; indeterminate for unknown length.", + "progressPulling": "Pulling image", + "progressTitle": "Progress bar", + "pull": "Pull image", + "pullTime": "12.4 s", + "pulling": "Pulling image", + "radioNote": "For a few options that deserve to be read side by side. Arrow keys move and select.", + "radioTitle": "Radio group", + "recoveryCode": "Recovery code", + "recreate": "Recreate", + "recreateNote": "Stop everything, then start the new version.", + "required": "Required", + "restart": "Restart service", + "rolling": "Rolling", + "rollingNote": "Replace containers one at a time. No downtime.", + "s3": "S3 compatible", + "s3Note": "Off-site copy after each backup.", + "sampleRate": "Sample rate", + "saveChanges": "Save changes", + "server": "Server", + "serviceName": "Service name", + "serviceNameHint": "Lowercase letters, numbers and dashes.", + "settings": "Settings", + "sliderNote": "Single value or a range, with marks and a formatted readout.", + "sliderTitle": "Slider", + "stepBuild": "Build", + "stepBuildNote": "Node 20 detected", + "stepConfigure": "Configure", + "stepDeploy": "Deploy", + "stepSource": "Source", + "stepperNote": "Completed steps are buttons back; later steps stay inert. A step can carry its own error status.", + "stepperTitle": "Stepper", + "storage": "Storage", + "strategy": "Deploy strategy", + "switch": "Switch traffic", + "tagNote": "Enter, comma or Tab adds; paste a list to add many; Backspace removes the last. Duplicates flash instead of repeating.", + "tagTitle": "Tag input", + "testConnection": "Test connection", + "tooltipNote": "Shows on hover and on keyboard focus. Moving along a row of icon buttons skips the delay.", + "tooltipTitle": "Tooltip", + "treeLocked": "root (no access)", + "treeNote": "Arrows walk and open branches, * opens siblings, typing jumps to a name. ssh and var load their children lazily.", + "treeTitle": "Tree view", + "tryIt": "Click to try", + "uploadErrorDemo": "The connection dropped at 41%.", + "verified": "Verified.", + "workers": "Workers" + }, + "controlsTab": "Controls", "copyField": "Copy field (CopyField)", "createJob": "Create job", "createService": "Create service", @@ -8066,6 +8185,7 @@ "logOut": "Sign out", "moveDown": "Move down", "moveUp": "Move up", + "next": "Next", "open": "Open", "publish": "Publish", "refresh": "Refresh", @@ -8084,6 +8204,55 @@ "confirm": { "typeToConfirm": "Type <0>{{value}}</0> to confirm:" }, + "controls": { + "cancelItem": "Cancel {{name}}", + "characterOf": "Character {{index}} of {{count}}", + "clearAll": "Clear all", + "clearDate": "Clear date", + "clearDateRange": "Clear date range", + "clearSelection": "Clear selection", + "createValue": "Create “{{value}}”", + "dateRange": "{{start}} – {{end}}", + "decrease": "Decrease", + "dropOrBrowse": "Drop files here or browse", + "dropToUpload": "Drop to add", + "fileTooLarge": "{{name}} is larger than {{max}}.", + "fileTypeNotAllowed": "{{name}} is not an allowed file type.", + "increase": "Increase", + "moreCount": "+{{count}}", + "nextMonth": "Next month", + "pickDate": "Pick a date", + "pickDateRange": "Pick a date range", + "pickEndDate": "Now pick the end date.", + "pickStartDate": "Pick a start date, or choose a preset.", + "presetLast30": "Last 30 days", + "presetLast7": "Last 7 days", + "presetLastMonth": "Last month", + "presetThisMonth": "This month", + "presetToday": "Today", + "presetYesterday": "Yesterday", + "presets": "Presets", + "previousMonth": "Previous month", + "progress": "Progress", + "queued": "Queued", + "removeItem": "Remove {{label}}", + "retryItem": "Retry {{name}}", + "search": "Search…", + "select": "Select…", + "selectedCount": "{{count}} selected", + "stepComplete": "Completed", + "stepCurrent": "Current step", + "stepError": "Needs attention", + "stepUpcoming": "Not started", + "tooManyFiles": "{{name}} was not added: the limit is {{max}} files.", + "tree": "Tree", + "upToSize": "up to {{size}}", + "uploadFailed": "Upload failed", + "uploaded": "Uploaded", + "uploadingName": "Uploading {{name}}", + "uploadingPercent": "Uploading {{percent}}%", + "verificationCode": "Verification code" + }, "duration": { "hours": "{{count}}h", "hoursMinutes": "{{hours}}h {{minutes}}m", diff --git a/frontend/src/lib/__tests__/controls.test.mjs b/frontend/src/lib/__tests__/controls.test.mjs new file mode 100644 index 00000000..aa0944cd --- /dev/null +++ b/frontend/src/lib/__tests__/controls.test.mjs @@ -0,0 +1,106 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + clamp, decimalsOf, isPartialNumber, normalizeNumber, parseNumber, snapToStep, stepNumber, +} from '../numberMath.js'; +import { + addMonths, compareDays, fromISODate, isWithinRange, monthGrid, orderRange, + startOfWeek, toISODate, +} from '../dateMath.js'; +import { matchesAccept, validateFiles } from '../fileAccept.js'; + +test('decimalsOf reads step precision, including exponent notation', () => { + assert.equal(decimalsOf(1), 0); + assert.equal(decimalsOf(0.25), 2); + assert.equal(decimalsOf(1e-7), 7); +}); + +test('snapToStep removes float noise and anchors at min', () => { + assert.equal(snapToStep(0.1 + 0.2, 0.1), 0.3); + assert.equal(snapToStep(7, 5, 1), 6); // grid is 1, 6, 11 … + assert.equal(snapToStep(9, 5, 1), 11); +}); + +test('normalizeNumber clamps after snapping past a bound', () => { + assert.equal(normalizeNumber(99, { min: 0, max: 10, step: 3 }), 9); + assert.equal(normalizeNumber(10, { min: 0, max: 10, step: 3 }), 9); + assert.equal(normalizeNumber(-4, { min: 0, max: 10 }), 0); + assert.equal(normalizeNumber(null, { min: 0 }), null); +}); + +test('stepNumber starts an empty field at the bound it moves away from', () => { + assert.equal(stepNumber(null, 1, { min: 1, max: 10 }), 1); + assert.equal(stepNumber(null, -1, { min: 1, max: 10 }), 10); + assert.equal(stepNumber(null, 1, {}), 0); + assert.equal(stepNumber(5, 1, { step: 2, multiplier: 10, max: 12 }), 12); + assert.equal(stepNumber(0.2, 1, { step: 0.1 }), 0.3); +}); + +test('partial entry and parsing', () => { + for (const text of ['', '-', '1.', '-0.5', '12']) assert.ok(isPartialNumber(text), text); + assert.equal(isPartialNumber('1a'), false); + assert.equal(isPartialNumber('-1', { allowNegative: false }), false); + assert.equal(isPartialNumber('1.5', { allowDecimal: false }), false); + assert.equal(parseNumber('-'), null); + assert.equal(parseNumber('3.5'), 3.5); + assert.equal(clamp(5, undefined, 3), 3); +}); + +test('addMonths clamps the day instead of overflowing into the next month', () => { + assert.equal(toISODate(addMonths(new Date(2026, 0, 31), 1)), '2026-02-28'); + assert.equal(toISODate(addMonths(new Date(2028, 0, 31), 1)), '2028-02-29'); + assert.equal(toISODate(addMonths(new Date(2026, 2, 15), -3)), '2025-12-15'); +}); + +test('monthGrid is always 6×7 and starts on the requested weekday', () => { + const sundayFirst = monthGrid(new Date(2026, 9, 1), 0); + const mondayFirst = monthGrid(new Date(2026, 9, 1), 1); + assert.equal(sundayFirst.length, 6); + assert.ok(sundayFirst.every((row) => row.length === 7)); + assert.equal(sundayFirst[0][0].getDay(), 0); + assert.equal(mondayFirst[0][0].getDay(), 1); + assert.equal(toISODate(startOfWeek(new Date(2026, 9, 25), 1)), '2026-10-19'); +}); + +test('ISO dates round-trip as LOCAL days and reject impossible dates', () => { + const day = fromISODate('2026-10-25'); + assert.equal(day.getDate(), 25); + assert.equal(toISODate(day), '2026-10-25'); + assert.equal(fromISODate('2026-02-30'), null); + assert.equal(fromISODate('25/10/2026'), null); +}); + +test('ranges order themselves and include both ends', () => { + const a = new Date(2026, 9, 20); + const b = new Date(2026, 9, 10); + const { start, end } = orderRange(a, b); + assert.ok(compareDays(start, end) < 0); + assert.ok(isWithinRange(new Date(2026, 9, 10), start, end)); + assert.ok(isWithinRange(new Date(2026, 9, 20), start, end)); + assert.equal(isWithinRange(new Date(2026, 9, 21), start, end), false); +}); + +test('accept matching covers extensions, wildcards and exact MIME', () => { + const zip = { name: 'Site.ZIP', type: 'application/zip', size: 10 }; + const png = { name: 'logo.png', type: 'image/png', size: 10 }; + assert.ok(matchesAccept(zip, '.zip')); + assert.ok(matchesAccept(png, 'image/*')); + assert.ok(matchesAccept(png, 'application/json, image/png')); + assert.equal(matchesAccept(zip, 'image/*'), false); + assert.ok(matchesAccept(zip, '')); +}); + +test('validateFiles reports type, size and count rejections in order', () => { + const files = [ + { name: 'a.sql', type: '', size: 10 }, + { name: 'b.sql', type: '', size: 5000 }, + { name: 'c.txt', type: 'text/plain', size: 10 }, + { name: 'd.sql', type: '', size: 10 }, + ]; + const { accepted, rejected } = validateFiles(files, { accept: '.sql', maxSize: 1000, maxFiles: 2, existingCount: 1 }); + assert.deepEqual(accepted.map((f) => f.name), ['a.sql']); + assert.deepEqual(rejected.map((r) => [r.file.name, r.reason]), [ + ['b.sql', 'size'], ['c.txt', 'type'], ['d.sql', 'count'], + ]); +}); diff --git a/frontend/src/lib/dateMath.js b/frontend/src/lib/dateMath.js new file mode 100644 index 00000000..a58bfebc --- /dev/null +++ b/frontend/src/lib/dateMath.js @@ -0,0 +1,103 @@ +// Calendar-day arithmetic behind Calendar / DatePicker / DateRangePicker. +// +// Every value here is a LOCAL calendar day: a Date at local midnight. A date +// picker picks a day, not an instant, so nothing in this file touches UTC — +// `new Date('2026-10-25')` would parse as UTC midnight and render as the 24th +// west of Greenwich, which is the classic date-picker off-by-one. + +export function startOfDay(date) { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} + +export function addDays(date, days) { + return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days); +} + +/** Month arithmetic that clamps the day: Jan 31 + 1 month is Feb 28/29. */ +export function addMonths(date, months) { + const target = new Date(date.getFullYear(), date.getMonth() + months, 1); + const lastDay = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate(); + return new Date(target.getFullYear(), target.getMonth(), Math.min(date.getDate(), lastDay)); +} + +export function startOfMonth(date) { + return new Date(date.getFullYear(), date.getMonth(), 1); +} + +export function endOfMonth(date) { + return new Date(date.getFullYear(), date.getMonth() + 1, 0); +} + +export function isSameDay(a, b) { + return Boolean(a && b) + && a.getFullYear() === b.getFullYear() + && a.getMonth() === b.getMonth() + && a.getDate() === b.getDate(); +} + +export function isSameMonth(a, b) { + return Boolean(a && b) && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth(); +} + +/** Negative, zero or positive, comparing calendar days only. */ +export function compareDays(a, b) { + return startOfDay(a).getTime() - startOfDay(b).getTime(); +} + +export function isBefore(a, b) { return compareDays(a, b) < 0; } +export function isAfter(a, b) { return compareDays(a, b) > 0; } + +export function isWithinRange(day, start, end) { + if (!start || !end) return false; + return compareDays(day, start) >= 0 && compareDays(day, end) <= 0; +} + +/** First day of the week containing `date`; weekStartsOn is 0 (Sun) .. 6 (Sat). */ +export function startOfWeek(date, weekStartsOn = 0) { + const offset = (date.getDay() - weekStartsOn + 7) % 7; + return addDays(date, -offset); +} + +export function endOfWeek(date, weekStartsOn = 0) { + return addDays(startOfWeek(date, weekStartsOn), 6); +} + +/** + * The 6×7 grid shown for `month`: always six rows so the popover never + * changes height while paging through months. + */ +export function monthGrid(month, weekStartsOn = 0) { + const first = startOfWeek(startOfMonth(month), weekStartsOn); + return Array.from({ length: 6 }, (_, row) => ( + Array.from({ length: 7 }, (_, col) => addDays(first, row * 7 + col)) + )); +} + +/** Clamp a day into [min, max]; either bound may be null. */ +export function clampDay(day, min, max) { + if (min && isBefore(day, min)) return startOfDay(min); + if (max && isAfter(day, max)) return startOfDay(max); + return day; +} + +/** Order a picked pair so start <= end. */ +export function orderRange(a, b) { + return isAfter(a, b) ? { start: b, end: a } : { start: a, end: b }; +} + +/** `YYYY-MM-DD` for a local day (the wire format for date-only fields). */ +export function toISODate(date) { + if (!date) return ''; + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${date.getFullYear()}-${month}-${day}`; +} + +/** Parse `YYYY-MM-DD` as a LOCAL day; null when malformed. */ +export function fromISODate(text) { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text || ''); + if (!match) return null; + const [, year, month, day] = match.map(Number); + const date = new Date(year, month - 1, day); + return date.getMonth() === month - 1 ? date : null; +} diff --git a/frontend/src/lib/fileAccept.js b/frontend/src/lib/fileAccept.js new file mode 100644 index 00000000..b7c43652 --- /dev/null +++ b/frontend/src/lib/fileAccept.js @@ -0,0 +1,44 @@ +// File checks behind FileDropzone. The `accept` string has the same grammar +// as <input accept>: comma-separated extensions (".zip"), wildcards +// ("image/*") and exact MIME types ("application/json"). The browser only +// applies it to the picker dialog — a dropped file skips it entirely — so the +// dropzone re-checks every file here. + +export function parseAccept(accept) { + if (!accept) return []; + return accept.split(',').map((part) => part.trim().toLowerCase()).filter(Boolean); +} + +export function matchesAccept(file, accept) { + const rules = Array.isArray(accept) ? accept : parseAccept(accept); + if (!rules.length) return true; + const name = (file.name || '').toLowerCase(); + const type = (file.type || '').toLowerCase(); + return rules.some((rule) => { + if (rule.startsWith('.')) return name.endsWith(rule); + if (rule.endsWith('/*')) return type.startsWith(rule.slice(0, -1)); + return type === rule; + }); +} + +/** + * Split files into accepted and rejected. Each rejection carries a `reason` + * code ('type' | 'size' | 'count') the UI turns into copy. + */ +export function validateFiles(files, { accept, maxSize, maxFiles, existingCount = 0 } = {}) { + const rules = parseAccept(accept); + const accepted = []; + const rejected = []; + for (const file of files) { + if (!matchesAccept(file, rules)) { + rejected.push({ file, reason: 'type' }); + } else if (Number.isFinite(maxSize) && file.size > maxSize) { + rejected.push({ file, reason: 'size' }); + } else if (Number.isFinite(maxFiles) && existingCount + accepted.length >= maxFiles) { + rejected.push({ file, reason: 'count' }); + } else { + accepted.push(file); + } + } + return { accepted, rejected }; +} diff --git a/frontend/src/lib/numberMath.js b/frontend/src/lib/numberMath.js new file mode 100644 index 00000000..b64739ff --- /dev/null +++ b/frontend/src/lib/numberMath.js @@ -0,0 +1,64 @@ +// Pure number helpers behind NumberField and Slider. Kept out of the +// components so the rounding rules are unit-tested (lib/__tests__). + +/** Decimal places of a step: 0.25 -> 2, 1 -> 0, 1e-3 -> 3. */ +export function decimalsOf(step) { + if (!Number.isFinite(step)) return 0; + const text = String(step); + if (text.includes('e-')) return Number(text.split('e-')[1]); + const dot = text.indexOf('.'); + return dot === -1 ? 0 : text.length - dot - 1; +} + +export function clamp(value, min, max) { + let next = value; + if (Number.isFinite(min) && next < min) next = min; + if (Number.isFinite(max) && next > max) next = max; + return next; +} + +/** + * Snap to the step grid anchored at `min` (or 0), then round away float + * noise: 0.1 + 0.2 lands on 0.3, not 0.30000000000000004. + */ +export function snapToStep(value, step = 1, min) { + if (!Number.isFinite(value)) return value; + if (!Number.isFinite(step) || step <= 0) return value; + const base = Number.isFinite(min) ? min : 0; + const snapped = base + Math.round((value - base) / step) * step; + const places = Math.max(decimalsOf(step), decimalsOf(base)); + return Number(snapped.toFixed(places)); +} + +/** Clamp, then snap, then clamp again (snapping can step past a bound). */ +export function normalizeNumber(value, { min, max, step = 1 } = {}) { + if (value === null || value === undefined || !Number.isFinite(value)) return null; + return clamp(snapToStep(clamp(value, min, max), step, min), min, max); +} + +/** + * One step from `value` in `direction` (+1 / -1), `multiplier` steps at a + * time. An empty field starts from the bound it moves away from, so "+" on + * an empty 1..10 field gives 1, not 0 clamped up. + */ +export function stepNumber(value, direction, { min, max, step = 1, multiplier = 1 } = {}) { + if (value === null || value === undefined || !Number.isFinite(value)) { + if (direction > 0) return Number.isFinite(min) ? min : normalizeNumber(0, { min, max, step }); + return Number.isFinite(max) ? max : normalizeNumber(0, { min, max, step }); + } + return normalizeNumber(value + direction * step * multiplier, { min, max, step }); +} + +/** What may be typed so far: '', '-', '1.', '-0.5' are all mid-entry states. */ +export function isPartialNumber(text, { allowNegative = true, allowDecimal = true } = {}) { + const sign = allowNegative ? '-?' : ''; + const fraction = allowDecimal ? '(\\.\\d*)?' : ''; + return new RegExp(`^${sign}\\d*${fraction}$`).test(text); +} + +/** Parse typed text; null for empty or a lone sign/point. */ +export function parseNumber(text) { + if (text === '' || text === '-' || text === '.' || text === '-.') return null; + const number = Number(text); + return Number.isFinite(number) ? number : null; +} diff --git a/frontend/src/pages/StyleGuide.jsx b/frontend/src/pages/StyleGuide.jsx index f1867817..2270f2a8 100644 --- a/frontend/src/pages/StyleGuide.jsx +++ b/frontend/src/pages/StyleGuide.jsx @@ -41,6 +41,7 @@ import { import { Badge } from '@/components/ui/badge'; import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'; import { useTranslation } from 'react-i18next'; +import ControlsShowcase from '../components/styleguide/ControlsShowcase'; import { Sheet, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription, SheetClose, } from '@/components/ui/sheet'; @@ -53,6 +54,7 @@ const SECTIONS = [ { id: 'buttons', labelKey: 'app.styleGuide.buttons', label: 'Buttons', icon: Square }, { id: 'forms', labelKey: 'app.styleGuide.forms', label: 'Forms', icon: ToggleLeft }, { id: 'fields', labelKey: 'app.styleGuide.sharedFields', label: 'Shared fields', icon: Key }, + { id: 'controls', labelKey: 'app.styleGuide.controlsTab', label: 'Controls', icon: Settings }, { id: 'tables', labelKey: 'app.styleGuide.tables', label: 'Tables', icon: Table }, { id: 'cards', labelKey: 'app.styleGuide.cardsStats', label: 'Cards and stats', icon: Layout }, { id: 'badges', labelKey: 'app.styleGuide.badgesStatus', label: 'Badges and status', icon: Shield }, @@ -1397,6 +1399,13 @@ export default function StyleGuide() { )} {/* ── UTILITIES ── */} + {/* ── CONTROLS ── */} + {activeSection === 'controls' && ( + <div className="styleguide__section"> + <ControlsShowcase /> + </div> + )} + {activeSection === 'utilities' && ( <div className="styleguide__section"> <SectionTitle title={t('app.styleGuide.flexUtilities', 'Flex layouts')} /> diff --git a/frontend/src/styles/_variables.scss b/frontend/src/styles/_variables.scss index 70a97dc7..0f46c813 100644 --- a/frontend/src/styles/_variables.scss +++ b/frontend/src/styles/_variables.scss @@ -86,6 +86,9 @@ $accent-bright: var(--accent-bright); $accent-dim: var(--accent-dim); $accent-bg: var(--accent-bg); $accent-bg-soft: var(--accent-bg-soft); +// Text and marks drawn ON an accent fill (a selected day, a checked box, a +// completed step). A theme with a light accent sets --on-accent to a dark ink. +$on-accent: var(--on-accent, #fff); // -------------------------------------------- // COLORS - Semantic @@ -245,6 +248,9 @@ $control-lg: 40px; $shadow-raised: var(--shadow-md); // menus, popovers, dropdowns, toasts $shadow-overlay: var(--shadow-lg); // modals, drawers $focus-ring: 0 0 0 2px var(--accent-bg, rgba(99, 102, 241, 0.35)); +// Soft 4px halo marking a "you are here" state (stepper current/error step). +$halo-accent: 0 0 0 4px var(--accent-bg-soft); +$halo-danger: 0 0 0 4px $danger-bg; // Legacy names (extensions); core uses the names above. $shadow-sm: none; diff --git a/frontend/src/styles/components/_cards.scss b/frontend/src/styles/components/_cards.scss index 515ee6ee..50567076 100644 --- a/frontend/src/styles/components/_cards.scss +++ b/frontend/src/styles/components/_cards.scss @@ -248,9 +248,36 @@ .progress-fill { height: 100%; border-radius: $radius-badge; + background: $accent-primary; @include transition(width); } +// ProgressBar size, tone and indeterminate variants (components/ProgressBar.jsx). +.progress-bar--md { height: 8px; } // geometry: bar thickness +.progress-bar--accent .progress-fill { background: $accent-primary; } +.progress-bar--success .progress-fill { background: $success; } +.progress-bar--warning .progress-fill { background: $warning; } +.progress-bar--danger .progress-fill { background: $danger; } +.progress-bar--info .progress-fill { background: $info; } + +.progress-bar--indeterminate .progress-fill { + width: 35%; + animation: sk-progress-indeterminate 1.4s $ease-out-quart infinite; +} + +@keyframes sk-progress-indeterminate { + from { transform: translateX(-100%); } + to { transform: translateX(300%); } +} + +@media (prefers-reduced-motion: reduce) { + .progress-bar--indeterminate .progress-fill { + width: 100%; + animation: none; + opacity: 0.5; + } +} + // Empty state card // Card body (content area below card-header) diff --git a/frontend/src/styles/components/_controls.scss b/frontend/src/styles/components/_controls.scss new file mode 100644 index 00000000..e604d909 --- /dev/null +++ b/frontend/src/styles/components/_controls.scss @@ -0,0 +1,1379 @@ +// ============================================ +// CONTROLS — tooltip, number field, combobox, tag input, calendar and date +// pickers, pin input, slider, radio group, stepper, tree, dropzone. +// ============================================ +// +// One partial for the form and display controls in components/ui and components/ds. +// They share a "field shell": a bordered box at control height that takes the +// focus ring on :focus-within and turns red on .is-invalid, so a combobox, a +// tag input and a number field line up with .ui-input in the same form row. +// ============================================ + +%control-shell { + display: flex; + align-items: center; + width: 100%; + min-height: $control-md; + background: $bg-body; + border: 1px solid $border-default; + border-radius: $radius-control; + color: $text-primary; + font-size: $text-base; + @include transition(border-color); + + &:hover:not(.is-disabled) { border-color: $border-hover; } + + &:focus-within { + border-color: $accent-primary; + box-shadow: $focus-ring; + } + + &.is-invalid { border-color: $danger; } + + &.is-invalid:focus-within { + box-shadow: 0 0 0 2px $danger-bg; // geometry: focus ring in the error tone + } + + &.is-disabled { + opacity: 0.55; + cursor: not-allowed; + } +} + +%control-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + padding: 0; + background: none; + border: none; + border-radius: $radius-badge; + color: $text-tertiary; + cursor: pointer; + @include transition(color); + + svg { width: 14px; height: 14px; } + + &:hover:not(:disabled) { color: $text-primary; background: $bg-hover; } + + &:focus-visible { + outline: none; + box-shadow: $focus-ring; + } + + &:disabled { opacity: 0.4; cursor: not-allowed; } +} + +%chip { + display: inline-flex; + align-items: center; + gap: $space-1; + max-width: 100%; + min-height: 22px; // geometry: chip inside a 32px field + padding-block: 0; + padding-inline: $space-2 $space-1; + background: $bg-tertiary; + border: 1px solid $border-subtle; + border-radius: $radius-badge; + color: $text-primary; + font-size: $text-xs; + line-height: 1.2; +} + +// -------------------------------------------- +// TOOLTIP +// -------------------------------------------- +.ui-tooltip { + z-index: $z-tooltip + 10; + display: inline-flex; + align-items: center; + gap: $space-2; + max-width: 280px; + padding: $space-1 $space-2; + background: $bg-elevated; + border: 1px solid $border-active; + border-radius: $radius-control; + box-shadow: $shadow-raised; + color: $text-primary; + font-size: $text-xs; + line-height: 1.4; + transform-origin: var(--radix-tooltip-content-transform-origin); + animation: sk-tooltip-in 120ms $ease-out-quart; + + &__kbd { + padding: 0 $space-1; + border: 1px solid $border-default; + border-radius: $radius-badge; + background: $bg-body; + color: $text-secondary; + font-family: $font-mono; + font-size: $text-xs; + } +} + +@keyframes sk-tooltip-in { + from { opacity: 0; transform: scale(0.96); } + to { opacity: 1; transform: scale(1); } +} + +// -------------------------------------------- +// NUMBER FIELD +// -------------------------------------------- +.ui-number-field { + @extend %control-shell; + height: $control-md; + overflow: hidden; + + &--sm { height: $control-sm; min-height: $control-sm; } + + &__input-wrap { + display: flex; + align-items: center; + flex: 1; + min-width: 0; + height: 100%; + } + + &__input { + flex: 1; + min-width: 0; + height: 100%; + padding: 0 $space-2; + background: transparent; + border: none; + outline: none; + color: inherit; + font-family: $font-mono; + font-size: $text-base; + font-variant-numeric: tabular-nums; + text-align: center; + + &::placeholder { color: $text-tertiary; font-family: $font-main; } + } + + &__unit { + padding-inline-end: $space-2; + color: $text-tertiary; + font-size: $text-sm; + white-space: nowrap; + } + + &__step { + @extend %control-icon-button; + align-self: stretch; + width: $control-md; + border-radius: 0; + background: $bg-card; + color: $text-secondary; + + &:first-child { border-inline-end: 1px solid $border-subtle; } + &:last-child { border-inline-start: 1px solid $border-subtle; } + &:active:not(:disabled) { background: $bg-tertiary; } + } + + &--sm &__step { width: $control-sm; } +} + +// -------------------------------------------- +// COMBOBOX +// -------------------------------------------- +.ui-combobox { + @extend %control-shell; + flex-wrap: wrap; + gap: $space-1; + padding: $space-hair $space-1; + cursor: pointer; + + &--sm { min-height: $control-sm; } + + &__trigger { + display: flex; + flex: 1; + align-items: center; + gap: $space-2; + min-width: 6rem; + min-height: 26px; // geometry: trigger row inside the 32px shell + padding: 0 $space-2; + background: none; + border: none; + outline: none; + color: inherit; + font: inherit; + text-align: start; + cursor: pointer; + + &:disabled { cursor: not-allowed; } + } + + &--multiple &__trigger { padding-inline-start: $space-1; } + + &__value { + display: flex; + align-items: center; + gap: $space-2; + flex: 1; + min-width: 0; + } + + &__value-label { @include truncate(); } + + &__placeholder { + flex: 1; + color: $text-tertiary; + @include truncate(); + } + + &__chevron { + width: 14px; + height: 14px; + margin-inline-start: auto; + flex-shrink: 0; + color: $text-tertiary; + } + + &__clear { + @extend %control-icon-button; + width: 22px; + height: 22px; // geometry: icon hit area + margin-inline-end: $space-hair; + } + + &__chip { @extend %chip; } + &__chip-label { @include truncate(); } + + &__chip-remove { + @extend %control-icon-button; + width: 16px; + height: 16px; + + svg { width: 12px; height: 12px; } + } + + &__more { + padding: 0 $space-1; + color: $text-secondary; + font-size: $text-xs; + } + + &__panel { + width: var(--radix-popover-trigger-width); + min-width: 14rem; + max-width: min(28rem, 92vw); + padding: 0; + overflow: hidden; + } + + &__option { + gap: $space-2; + } + + &__option-icon { + display: inline-flex; + width: 16px; + height: 16px; + flex-shrink: 0; + color: $text-secondary; + } + + &__option-copy { + display: flex; + flex-direction: column; + flex: 1; + min-width: 0; + + > span { @include truncate(); } + + small { + color: $text-tertiary; + font-size: $text-xs; + @include truncate(); + } + } + + &__checkbox { + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + flex-shrink: 0; + border: 1px solid $border-active; + border-radius: $radius-badge; + color: $on-accent; + + svg { width: 12px; height: 12px; } + } + + &__option[data-checked] &__checkbox { + background: $accent-primary; + border-color: $accent-primary; + } + + &__check { + width: 14px; + height: 14px; + margin-inline-start: auto; + color: $accent-primary; + } + + &__create { color: $accent-bright; } + + &__message { + padding: $space-4 $space-3; + color: $text-tertiary; + font-size: $text-sm; + text-align: center; + } + + &__footer { + display: flex; + align-items: center; + justify-content: space-between; + padding: $space-2 $space-3; + border-top: 1px solid $border-default; + color: $text-secondary; + font-size: $text-xs; + } + + &__footer-action { + padding: 0; + background: none; + border: none; + color: $accent-bright; + font: inherit; + cursor: pointer; + + &:hover { text-decoration: underline; } + &:focus-visible { outline: none; box-shadow: $focus-ring; border-radius: $radius-badge; } + } +} + +// -------------------------------------------- +// TAG INPUT +// -------------------------------------------- +.ui-tag-input-field { + display: flex; + flex-direction: column; + gap: $space-1; + width: 100%; +} + +.ui-tag-input { + @extend %control-shell; + flex-wrap: wrap; + gap: $space-1; + padding: $space-hair $space-1; + cursor: text; + + &--sm { min-height: $control-sm; } + + &__chip { + @extend %chip; + font-family: $font-mono; + transition: background-color 120ms ease, border-color 120ms ease; + + &.is-flashing { + background: $warning-bg; + border-color: $warning-border; + } + } + + &__chip-label { @include truncate(); } + + &__chip-remove { + @extend %control-icon-button; + width: 16px; + height: 16px; + + svg { width: 12px; height: 12px; } + } + + &__input { + flex: 1; + min-width: 8rem; + min-height: 26px; // geometry: input row inside the 32px shell + padding: 0 $space-1; + background: transparent; + border: none; + outline: none; + color: inherit; + font: inherit; + + &::placeholder { color: $text-tertiary; } + &:disabled { cursor: not-allowed; } + } + + &__error { + margin: 0; + color: $danger; + font-size: $text-xs; + } +} + +// -------------------------------------------- +// DATE PICKER + DATE RANGE PICKER +// -------------------------------------------- +.ui-date-picker { + @extend %control-shell; + height: $control-md; + padding-inline-end: $space-1; + + &--sm { height: $control-sm; min-height: $control-sm; } + + &__trigger { + display: flex; + flex: 1; + align-items: center; + gap: $space-2; + min-width: 0; + height: 100%; + padding: 0 $space-3; + background: none; + border: none; + outline: none; + color: inherit; + font: inherit; + text-align: start; + cursor: pointer; + + &:disabled { cursor: not-allowed; } + } + + &__icon { + width: 16px; + height: 16px; + flex-shrink: 0; + color: $text-tertiary; + } + + &__value { + font-variant-numeric: tabular-nums; + @include truncate(); + } + + &__placeholder { + color: $text-tertiary; + @include truncate(); + } + + &__clear { + @extend %control-icon-button; + width: 22px; + height: 22px; // geometry: icon hit area + } + + &__panel { + width: auto; + padding: $space-3; + + &--range { + display: flex; + gap: $space-3; + padding: 0; + } + } + + &__presets { + display: flex; + flex-direction: column; + gap: $space-hair; + min-width: 9rem; + margin: 0; + padding: $space-2; + list-style: none; + border-inline-end: 1px solid $border-default; + } + + &__preset { + width: 100%; + padding: $space-tight $space-2; + background: none; + border: none; + border-radius: $radius-badge; + color: $text-secondary; + font: inherit; + font-size: $text-sm; + text-align: start; + cursor: pointer; + + &:hover { background: $bg-hover; color: $text-primary; } + &:focus-visible { outline: none; box-shadow: $focus-ring; } + + &.is-active { + background: $accent-bg-soft; + color: $accent-bright; + } + } + + &__range-body { + display: flex; + flex-direction: column; + gap: $space-2; + padding: $space-3; + } + + &__hint { + margin: 0; + color: $text-tertiary; + font-size: $text-xs; + } +} + +@include respond-to($breakpoint-md) { + .ui-date-picker__panel--range { flex-direction: column; } + + .ui-date-picker__presets { + flex-direction: row; + flex-wrap: wrap; + border-inline-end: none; + border-bottom: 1px solid $border-default; + } + + .ui-date-picker__presets li { flex: 0 0 auto; } +} + +// -------------------------------------------- +// CALENDAR +// -------------------------------------------- +$calendar-cell: 32px; + +.ui-calendar { + position: relative; + user-select: none; + + &__nav { + position: absolute; + inset-inline: 0; + top: 0; + display: flex; + justify-content: space-between; + pointer-events: none; + } + + &__nav-button { + @extend %control-icon-button; + width: $control-sm; + height: $control-sm; + color: $text-secondary; + pointer-events: auto; + + svg { width: 16px; height: 16px; } + } + + // In RTL the "previous" chevron sits on the right and must point there. + [dir='rtl'] &__nav-button svg { transform: scaleX(-1); } + + &__months { + display: flex; + gap: $space-6; + } + + &__title { + display: flex; + align-items: center; + justify-content: center; + height: $control-sm; + margin-bottom: $space-2; + font-size: $text-sm; + font-weight: $font-weight-semibold; + text-transform: capitalize; + } + + &__grid { + display: flex; + flex-direction: column; + } + + &__row { + display: flex; + + &--head { margin-bottom: $space-hair; } + } + + &__weekday { + display: inline-flex; + align-items: center; + justify-content: center; + width: $calendar-cell; + height: 24px; // geometry: weekday header row + color: $text-tertiary; + font-size: $text-xs; + font-weight: $font-weight-medium; + } + + &__cell { + display: block; + width: $calendar-cell; + height: $calendar-cell; + + &.is-in-range { background: $accent-bg-soft; } + &.is-range-start { border-start-start-radius: $radius-control; border-end-start-radius: $radius-control; } + &.is-range-end { border-start-end-radius: $radius-control; border-end-end-radius: $radius-control; } + } + + &__day { + position: relative; + width: $calendar-cell; + height: $calendar-cell; + padding: 0; + background: none; + border: 1px solid transparent; + border-radius: $radius-control; + color: $text-primary; + font: inherit; + font-size: $text-sm; + font-variant-numeric: tabular-nums; + cursor: pointer; + + &:hover:not(:disabled) { background: $bg-hover; } + + &:focus-visible { + outline: none; + box-shadow: $focus-ring; + border-color: $accent-primary; + } + + &:disabled { + color: $text-tertiary; + opacity: 0.35; + cursor: not-allowed; + } + + &.is-today::after { + content: ''; + position: absolute; + bottom: 4px; // geometry: today marker under the numeral + inset-inline-start: 50%; + width: 4px; + height: 4px; + border-radius: $radius-full; + background: $accent-primary; + transform: translateX(-50%); + } + + &.is-selected:not(.is-endpoint) { color: $accent-bright; } + + &.is-endpoint { + background: $accent-primary; + color: $on-accent; + + &:hover { background: $accent-hover; } + &.is-today::after { background: $on-accent; } + } + } + + &__cell.is-outside &__day { color: $text-tertiary; } +} + +// -------------------------------------------- +// PIN INPUT +// -------------------------------------------- +.ui-pin-input { + display: inline-flex; + align-items: center; + gap: $space-2; + + &__cell { + width: $control-lg; + height: $control-lg + 4px; // geometry: code cell is a little taller than wide + padding: 0; + background: $bg-body; + border: 1px solid $border-default; + border-radius: $radius-control; + color: $text-primary; + font-family: $font-mono; + font-size: $text-lg; + font-weight: $font-weight-medium; + text-align: center; + caret-color: $accent-primary; + @include transition(border-color); + + &:hover:not(:disabled) { border-color: $border-hover; } + + &:focus { + outline: none; + border-color: $accent-primary; + box-shadow: $focus-ring; + } + + &.is-filled { border-color: $border-active; } + &:disabled { opacity: 0.55; cursor: not-allowed; } + } + + &.is-invalid &__cell { border-color: $danger; } + + &__separator { + width: $space-2; + height: 2px; + border-radius: $radius-full; + background: $border-active; + } +} + +// -------------------------------------------- +// SLIDER +// -------------------------------------------- +.ui-slider { + display: flex; + align-items: flex-start; + gap: $space-4; + width: 100%; + + &--marked { padding-bottom: $space-5; } + + &__body { + position: relative; + flex: 1; + min-width: 0; + } + + &__root { + position: relative; + display: flex; + align-items: center; + width: 100%; + height: 20px; // geometry: thumb hit row + touch-action: none; + user-select: none; + + &[data-disabled] { opacity: 0.55; cursor: not-allowed; } + } + + &__track { + position: relative; + flex: 1; + height: 4px; + overflow: hidden; + background: $bg-tertiary; + border-radius: $radius-full; + } + + &__range { + position: absolute; + height: 100%; + background: $accent-primary; + } + + &__thumb { + display: block; + width: 16px; + height: 16px; + background: $on-accent; + border: 2px solid $accent-primary; + border-radius: $radius-full; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); // geometry: thumb edge on light tracks + cursor: grab; + @include transition(transform); + + &:hover { transform: scale(1.1); } + &:active { cursor: grabbing; } + + &:focus-visible { + outline: none; + box-shadow: 0 0 0 4px $accent-bg; // geometry: focus halo around the thumb + } + } + + &__marks { + position: absolute; + inset-inline: 0; + top: 24px; // geometry: labels under the track + } + + &__mark { + position: absolute; + color: $text-tertiary; + font-size: $text-xs; + font-variant-numeric: tabular-nums; + white-space: nowrap; + transform: translateX(-50%); + + &:first-child { transform: none; } + &:last-child { transform: translateX(-100%); } + } + + &__value { + min-width: 4.5rem; + padding-top: $space-hair; + color: $text-primary; + font-family: $font-mono; + font-size: $text-sm; + font-variant-numeric: tabular-nums; + text-align: end; + white-space: nowrap; + } +} + +// -------------------------------------------- +// RADIO GROUP +// -------------------------------------------- +.ui-radio-group { + display: flex; + gap: $space-3; + + &--vertical { flex-direction: column; } + &--horizontal { flex-wrap: wrap; } + + &--card { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); + align-content: start; + align-items: start; + gap: $space-2; + + &.ui-radio-group--vertical { grid-template-columns: 1fr; } + } +} + +.ui-radio { + display: flex; + align-items: flex-start; + gap: $space-2; + cursor: pointer; + + &.is-disabled { opacity: 0.55; cursor: not-allowed; } + + &__control { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 16px; + height: 16px; + margin-top: $space-hair; + padding: 0; + background: $bg-body; + border: 1px solid $border-active; + border-radius: $radius-full; + cursor: inherit; + @include transition(border-color); + + &[data-state='checked'] { border-color: $accent-primary; } + + &:focus-visible { + outline: 2px solid $accent-primary; + outline-offset: 2px; + } + } + + &__dot { + display: block; + width: 8px; + height: 8px; + border-radius: $radius-full; + background: $accent-primary; + } + + &__icon { + width: 16px; + height: 16px; + margin-top: $space-hair; + flex-shrink: 0; + color: $text-secondary; + } + + &__copy { + display: flex; + flex-direction: column; + gap: $space-hair; + min-width: 0; + } + + &__label { + color: $text-primary; + font-size: $text-base; + font-weight: $font-weight-medium; + line-height: 1.4; + } + + &__description { + color: $text-secondary; + font-size: $text-sm; + line-height: 1.4; + } + + .ui-radio-group--card & { + padding: $space-3; + background: $bg-card; + border: 1px solid $border-default; + border-radius: $radius-card; + @include transition(border-color); + + &:hover:not(.is-disabled) { border-color: $border-hover; } + + &:has([data-state='checked']) { + background: $accent-bg-soft; + border-color: $accent-primary; + } + + &:has(:focus-visible) { box-shadow: $focus-ring; } + + .ui-radio__copy { flex: 1; } + + // The radio moves to the end corner and only shows once picked: the + // card border and fill already say which one is selected. + .ui-radio__control { + order: 1; + width: 18px; + height: 18px; + border-color: transparent; + background: transparent; + + &[data-state='checked'] { + background: $accent-primary; + border-color: $accent-primary; + } + + &:focus-visible { outline: none; } + } + + .ui-radio__dot { + display: inline-flex; + width: auto; + height: auto; + background: none; + color: $on-accent; + + svg { width: 12px; height: 12px; stroke-width: 3; } + } + + .ui-radio__icon { + box-sizing: content-box; + margin-top: 0; + padding: $space-1 + $space-hair; + background: $bg-elevated; + border-radius: $radius-control; + } + + &:has([data-state='checked']) .ui-radio__icon { + background: $bg-card; + color: $accent-bright; + } + } +} + +// -------------------------------------------- +// STEPPER +// -------------------------------------------- +$stepper-marker: 28px; // geometry: step marker +$stepper-rail: 2px; + +.sk-stepper { + display: flex; + margin: 0; + padding: 0; + list-style: none; + + &__step { + position: relative; + display: flex; + flex: 1; + min-width: 0; + + // The last step has no rail after it, so it only takes its own width + // and the rails between steps share the row evenly. + &:last-child { flex: 0 0 auto; } + } + + &__target { + display: flex; + align-items: flex-start; + gap: $space-3; + min-width: 0; + padding: 0; + background: none; + border: none; + border-radius: $radius-control; + color: inherit; + font: inherit; + text-align: start; + } + + button.sk-stepper__target { + cursor: pointer; + + &:hover .sk-stepper__label { color: $text-primary; } + &:hover .sk-stepper__marker { box-shadow: $halo-accent; } + &:focus-visible { outline: none; box-shadow: $focus-ring; } + } + + &__marker { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: $stepper-marker; + height: $stepper-marker; + border: $stepper-rail solid $border-active; + border-radius: $radius-full; + background: $bg-elevated; + color: $text-tertiary; + font-size: $text-xs; + font-weight: $font-weight-semibold; + font-variant-numeric: tabular-nums; + @include transition(); + + svg { width: 14px; height: 14px; stroke-width: 3; } + } + + &__copy { + display: flex; + flex-direction: column; + gap: $space-hair; + min-width: 0; + padding-top: $space-1; + } + + &__label { + color: $text-secondary; + font-size: $text-sm; + font-weight: $font-weight-medium; + line-height: 1.4; + @include truncate(); + } + + &__description { + color: $text-tertiary; + font-size: $text-xs; + line-height: 1.4; + @include truncate(); + } + + &__connector { + flex: 1; + align-self: flex-start; + min-width: $space-6; + height: $stepper-rail; + margin: calc((#{$stepper-marker} - #{$stepper-rail}) / 2) $space-4 0; + border-radius: $radius-full; + background: $border-default; + @include transition(background); + } + + // Complete: solid accent disc with a check, rail filled up to the next step. + .is-complete &__marker { + background: $accent-primary; + border-color: $accent-primary; + color: $on-accent; + } + + .is-complete &__connector { background: $accent-primary; } + + // Current: ringed in accent with a soft halo, so it reads as "you are + // here" without looking like keyboard focus. + .is-current &__marker { + background: $accent-bg-soft; + border-color: $accent-primary; + color: $accent-primary; + box-shadow: $halo-accent; + } + + .is-current &__label { color: $text-primary; font-weight: $font-weight-semibold; } + .is-complete &__label { color: $text-primary; } + + .is-error &__marker { + background: $danger-bg; + border-color: $danger; + color: $danger; + box-shadow: $halo-danger; + } + + .is-error &__label { color: $danger; font-weight: $font-weight-semibold; } + + // Vertical: one continuous rail under the markers, running from each + // marker down to the next, with the copy hanging to its side. + &--vertical { + flex-direction: column; + + .sk-stepper__step { + flex: 0 0 auto; + padding-bottom: $space-5; + + &:last-child { padding-bottom: 0; } + } + + .sk-stepper__connector { + position: absolute; + inset-block-start: calc(#{$stepper-marker} + #{$space-1}); + inset-inline-start: calc((#{$stepper-marker} - #{$stepper-rail}) / 2); + width: $stepper-rail; + min-width: 0; + height: calc(100% - #{$stepper-marker} - #{$space-2}); + margin: 0; + } + + .sk-stepper__label, + .sk-stepper__description { white-space: normal; } + } +} + +// -------------------------------------------- +// TREE VIEW +// -------------------------------------------- +$tree-indent: 16px; + +.sk-tree { + margin: 0; + padding: $space-1; + list-style: none; + font-size: $text-sm; + + &__row { + display: flex; + align-items: center; + gap: $space-1; + height: $control-sm; + padding-inline: calc(var(--sk-tree-level, 0) * #{$tree-indent} + #{$space-1}) $space-2; + border-radius: $radius-badge; + color: $text-secondary; + cursor: pointer; + outline: none; + user-select: none; // double-click toggles a branch; it must not select text + + &:hover { background: $bg-hover; color: $text-primary; } + + &:focus-visible { box-shadow: inset 0 0 0 1px $accent-primary; } // geometry: inset focus inside a dense list + + &.is-selected { + background: $accent-bg-soft; + color: $text-primary; + + .sk-tree__icon { color: $accent-bright; } + } + + &.is-disabled { opacity: 0.5; cursor: not-allowed; } + } + + &__toggle { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 16px; + height: 16px; + border-radius: $radius-badge; + color: $text-tertiary; + + svg { + width: 14px; + height: 14px; + transition: transform 120ms $ease-out-quart; + } + + &:not(.is-leaf):hover { background: $bg-tertiary; color: $text-primary; } + &.is-open svg { transform: rotate(90deg); } + } + + [dir='rtl'] &__toggle:not(.is-open) svg { transform: scaleX(-1); } + + &__spinner { animation: spinner-rotate 0.8s linear infinite; } + + &__icon { + width: 16px; + height: 16px; + flex-shrink: 0; + color: $text-tertiary; + } + + &__label { + flex: 1; + min-width: 0; + @include truncate(); + } + + &__meta { + flex-shrink: 0; + color: $text-tertiary; + font-family: $font-mono; + font-size: $text-xs; + } +} + +// -------------------------------------------- +// FILE DROPZONE + UPLOAD LIST +// -------------------------------------------- +.ui-dropzone-field { + display: flex; + flex-direction: column; + gap: $space-2; + width: 100%; +} + +.ui-dropzone { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: $space-2; + padding: $space-6 $space-4; + background: $bg-body; + border: 1px dashed $border-active; + border-radius: $radius-card; + color: $text-secondary; + text-align: center; + cursor: pointer; + @include transition(); + + &:hover:not(.is-disabled) { border-color: $text-tertiary; background: $bg-card; } + + &:focus-visible { + outline: none; + border-color: $accent-primary; + box-shadow: $focus-ring; + } + + &.is-dragging { + border-style: solid; + border-color: $accent-primary; + background: $accent-bg-soft; + + .ui-dropzone__icon { color: $accent-bright; transform: translateY(-2px); } + } + + &.is-invalid { border-color: $danger; } + &.is-disabled { opacity: 0.55; cursor: not-allowed; } + + &--compact { + flex-direction: row; + justify-content: flex-start; + padding: $space-3 $space-4; + text-align: start; + } + + &__icon { + width: 24px; + height: 24px; // geometry: icon size + flex-shrink: 0; + color: $text-tertiary; + @include transition(transform); + } + + &__copy { + display: flex; + flex-direction: column; + gap: $space-hair; + } + + &__title { + color: $text-primary; + font-size: $text-base; + font-weight: $font-weight-medium; + } + + &__hint { + color: $text-tertiary; + font-size: $text-xs; + } + + &__rejections { + display: flex; + flex-direction: column; + gap: $space-1; + margin: 0; + padding: 0; + list-style: none; + + li { + display: flex; + align-items: flex-start; + gap: $space-2; + color: $danger; + font-size: $text-xs; + } + + svg { width: 14px; height: 14px; flex-shrink: 0; margin-top: 1px; } + } +} + +.ui-upload-list { + display: flex; + flex-direction: column; + gap: $space-1; + margin: 0; + padding: 0; + list-style: none; + + &__item { + display: flex; + align-items: flex-start; + gap: $space-3; + padding: $space-2 $space-3; + background: $bg-card; + border: 1px solid $border-subtle; + border-radius: $radius-control; + + &.is-error { border-color: $danger-border; } + } + + &__icon { + width: 16px; + height: 16px; + margin-top: $space-hair; + flex-shrink: 0; + color: $text-tertiary; + + .is-done & { color: $success; } + .is-error & { color: $danger; } + } + + &__body { + display: flex; + flex: 1; + flex-direction: column; + gap: $space-1; + min-width: 0; + + .progress-bar { margin-top: 0; } + } + + &__row { + display: flex; + align-items: baseline; + gap: $space-2; + min-width: 0; + } + + &__name { + flex: 1; + min-width: 0; + color: $text-primary; + font-size: $text-sm; + @include truncate(); + } + + &__size { + flex-shrink: 0; + color: $text-tertiary; + font-size: $text-xs; + font-variant-numeric: tabular-nums; + } + + &__status { + color: $text-tertiary; + font-size: $text-xs; + + .is-error & { color: $danger; } + .is-done & { color: $success; } + } + + &__actions { + display: flex; + gap: $space-1; + } + + &__action { + @extend %control-icon-button; + width: $control-sm; + height: $control-sm; + + svg { width: 16px; height: 16px; } + } +} + +@media (prefers-reduced-motion: reduce) { + .ui-tooltip { animation: none; } + .sk-tree__toggle svg, + .ui-slider__thumb, + .ui-dropzone__icon { transition: none; } +} diff --git a/frontend/src/styles/components/_forms.scss b/frontend/src/styles/components/_forms.scss index 5e676b28..e168314f 100644 --- a/frontend/src/styles/components/_forms.scss +++ b/frontend/src/styles/components/_forms.scss @@ -102,6 +102,10 @@ display: grid; margin-top: $space-1; margin-bottom: 0; } + + // The label carries the failure too, so a field scrolled half out of + // view still reads as the one to fix. + &--invalid &__label { color: $danger; } } // Inline form (input + button) diff --git a/frontend/src/styles/components/_spinner.scss b/frontend/src/styles/components/_spinner.scss index 46d06e24..15f43e4f 100644 --- a/frontend/src/styles/components/_spinner.scss +++ b/frontend/src/styles/components/_spinner.scss @@ -81,6 +81,17 @@ pointer-events: none; color: transparent !important; + // Button `loading` wraps the label so it can be hidden from assistive + // tech; `contents` keeps the icon/text gap of the unwrapped label. + .btn__label { display: contents; } + + // Loading is busy, not unavailable: keep full colour so the button does + // not read as disabled while the action it started is running. + &:disabled { + opacity: 1; + cursor: progress; + } + .spinner { position: absolute; top: 50%; @@ -98,8 +109,10 @@ border-top-color: #fff; } + // Runtime tokens, not the compile-time dark raw: on a light theme the + // faded light ring disappeared against a white outline button. &.btn-secondary .spinner .spinner-ring { - border-color: fade($text-primary-raw, 30%); + border-color: $border-default; border-top-color: $text-primary; } diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scss index 96666eb9..7dcd60f1 100644 --- a/frontend/src/styles/main.scss +++ b/frontend/src/styles/main.scss @@ -78,6 +78,7 @@ @import 'components/_walkthroughs'; @import 'components/_ai-assistant'; @import 'components/_ui'; +@import 'components/_controls'; // controls: tooltip, number, combobox, dates, pin, slider, radio, stepper, tree, dropzone @import 'components/_staging-banner'; @import 'components/_design-system'; // redesign shared primitives (sk-* namespace) @import 'components/_change-bar'; // local draft history + save/discard controls diff --git a/frontend/src/styles/pages/_style-guide.scss b/frontend/src/styles/pages/_style-guide.scss index ed9f4a71..10dae0d3 100644 --- a/frontend/src/styles/pages/_style-guide.scss +++ b/frontend/src/styles/pages/_style-guide.scss @@ -243,4 +243,111 @@ grid-template-columns: 1fr; } } + + // Controls tab (components/styleguide/ControlsShowcase.jsx). + &__controls { + display: flex; + flex-direction: column; + gap: $space-4; + } + + &__control-demo { + display: flex; + flex-direction: column; + gap: $space-4; + padding: $space-5; + background: $bg-card; + border: 1px solid $border-subtle; + border-radius: $radius-card; + } + + &__control-head { + h3 { + margin: 0; + font-size: $text-md; + font-weight: $font-weight-semibold; + } + + p { + margin: $space-1 0 0; + max-width: 72ch; + color: $text-secondary; + font-size: $text-sm; + } + } + + &__control-body { + display: flex; + flex-direction: column; + gap: $space-4; + + .form-field { margin-bottom: 0; } + } + + &__control-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: $space-2; + + &--top { align-items: flex-start; gap: $space-8; } + } + + &__control-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); + gap: $space-4; + } + + &__control-stack { + display: flex; + flex-direction: column; + gap: $space-4; + max-width: 36rem; + } + + &__control-state { + display: flex; + flex-direction: column; + gap: $space-tight; + } + + &__control-state-label { + color: $text-secondary; + font-size: $text-xs; + } + + &__control-split { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: $space-6; + + @media (max-width: $breakpoint-lg) { grid-template-columns: 1fr; } + } + + &__control-calendar { + display: flex; + flex-wrap: wrap; + gap: $space-8; + padding: $space-4; + border: 1px solid $border-subtle; + border-radius: $radius-card; + background: $bg-elevated; + width: fit-content; + } + + &__control-tree { + max-width: 26rem; + border: 1px solid $border-subtle; + border-radius: $radius-card; + background: $bg-body; + } + + &__control-tip-wrap { display: inline-flex; } + + &__control-ok { + margin: 0; + color: $success; + font-size: $text-sm; + } } diff --git a/frontend/src/utils/intl.js b/frontend/src/utils/intl.js index f65f8891..8055a9ad 100644 --- a/frontend/src/utils/intl.js +++ b/frontend/src/utils/intl.js @@ -265,7 +265,29 @@ export function formatList(items, { type = 'conjunction' } = {}) { })).format(list); } +// ------------------------------------------------------------- calendar --- + +// Locales whose week starts on Sunday when Intl.Locale#weekInfo is missing +// (Firefox, older Safari). Everything else falls back to Monday (ISO 8601). +const SUNDAY_FIRST_REGIONS = new Set(['US', 'CA', 'MX', 'BR', 'JP', 'KR', 'TW', 'HK', 'IL', 'PH', 'TH', 'IN', 'SA']); + +/** First day of the week for the panel locale: 0 (Sunday) .. 6 (Saturday). */ +export function getWeekStart() { + return cached('weekStart', {}, (locale) => { + try { + const info = new Intl.Locale(locale); + const week = typeof info.getWeekInfo === 'function' ? info.getWeekInfo() : info.weekInfo; + if (week?.firstDay) return week.firstDay % 7; // weekInfo: 1 = Monday … 7 = Sunday + const region = info.maximize().region; + return SUNDAY_FIRST_REGIONS.has(region) ? 0 : 1; + } catch { + return 0; + } + }); +} + export default { + getWeekStart, formatDate, formatTime, formatDateTime,