Merge pull request #187 from jhd3197/dev

Add a solid set of form controls and fix remote Docker image listings
This commit is contained in:
Juan Denis authored and GitHub committed 2026-10-26 00:09:52 -04:00
commit 6670c8b490
50 files changed
+6020 -148

No files matched your search

+21 -8
View File
@@ -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 `# <Title>` 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.
+25 -4
View File
@@ -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
+6
View File
@@ -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.
+1 -1
View File
@@ -1 +1 @@
1.11.26
1.11.27
+42 -2
View File
@@ -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)
+980
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -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",
+6 -3
View File
@@ -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>
+29 -7
View File
@@ -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>
);
}
+20 -15
View File
@@ -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>
);
}
+45 -3
View File
@@ -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>
);
+5 -61
View File
@@ -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
@@ -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);
});
@@ -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;
};
+90
View File
@@ -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;
+205
View File
@@ -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;
@@ -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>
);
},
},
];
@@ -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>
);
}
+30 -3
View File
@@ -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';
+241
View File
@@ -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 };
+280
View File
@@ -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 };
+226
View File
@@ -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 };
@@ -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) };
},
},
];
}
@@ -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),
};
}
@@ -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 };
+14 -10
View File
@@ -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 };
+215
View File
@@ -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 };
+153
View File
@@ -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 };
+7 -2
View File
@@ -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;
@@ -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 };
+2 -1
View File
@@ -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>
+93
View File
@@ -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 };
+159
View File
@@ -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 };
+11 -9
View File
@@ -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 };
+70
View File
@@ -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 };
+1
View File
@@ -26,6 +26,7 @@ export default function useFormat() {
formatCompactNumber: intl.formatCompactNumber,
formatPercent: intl.formatPercent,
formatList: intl.formatList,
getWeekStart: intl.getWeekStart,
locale: language,
}), [language]);
+169
View File
@@ -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",
@@ -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'],
]);
});
+103
View File
@@ -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;
}
+44
View File
@@ -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 };
}
+64
View File
@@ -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;
}
+9
View File
@@ -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')} />
+6
View File
@@ -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;
@@ -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)
File diff suppressed because it is too large. Load diff
@@ -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)
+14 -1
View File
@@ -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;
}
+1
View File
@@ -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
+107
View File
@@ -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;
}
}
+22
View File
@@ -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,