Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f897fe2498 | ||
|
|
705a1c4c79 | ||
|
|
449f628144 | ||
|
|
8964cec3e2 | ||
|
|
3e99ada77b | ||
|
|
04ea1db1ab | ||
|
|
33dfebab9e | ||
|
|
7afb6a022a | ||
|
|
fb2cb7bcfa | ||
|
|
28db4f707f | ||
|
|
0f9b40df9f | ||
|
|
d6bf6f94d8 | ||
|
|
7d5feb21a1 | ||
|
|
840e4e96e3 | ||
|
|
f4d7e3b1ab | ||
|
|
8774ef62ce | ||
|
|
e4f88485f2 | ||
|
|
03a1ce56d8 | ||
|
|
c5d7bdfef0 | ||
|
|
e09effa2ca | ||
|
|
148062ec28 | ||
|
|
3af449e9f9 | ||
|
|
d0e49b2365 | ||
|
|
b6a6298353 | ||
|
|
6b40ff059c | ||
|
|
000bb42240 | ||
|
|
31af3819b4 | ||
|
|
8875062fc5 | ||
|
|
adea139888 |
No files matched your search
@@ -0,0 +1 @@
|
||||
resume.sh
|
||||
@@ -0,0 +1,17 @@
|
||||
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||
|
||||
This software and its documentation are proprietary
|
||||
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
|
||||
publish, distribute, sublicense or sell copies of this software, in whole
|
||||
or in part, is granted without the prior written permission of the
|
||||
copyright holder.
|
||||
|
||||
Third-party components bundled in this repository keep their own licenses; see NOTICE.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,52 @@
|
||||
# yetano-webui-template is a library (package layout): nothing to build or
|
||||
# publish, only to check. A release is a git tag -- see README.md,
|
||||
# "Versioning note".
|
||||
|
||||
.PHONY: all
|
||||
all: ci
|
||||
|
||||
.PHONY: test
|
||||
test:
|
||||
go test ./... -race
|
||||
|
||||
.PHONY: fmt
|
||||
fmt:
|
||||
@out="$$(gofmt -l .)"; \
|
||||
if [ -n "$$out" ]; then \
|
||||
echo "not gofmt'ed:"; echo "$$out"; exit 1; \
|
||||
fi
|
||||
|
||||
.PHONY: fmt-fix
|
||||
fmt-fix:
|
||||
gofmt -w .
|
||||
|
||||
.PHONY: vet
|
||||
vet:
|
||||
go vet ./...
|
||||
|
||||
# govulncheck at a pinned version via "go run" -- no global install. Not
|
||||
# part of test on purpose: it needs network access to vuln.go.dev, and
|
||||
# since that database changes daily, a check would start failing without
|
||||
# any code change (see ../TODO.md "govulncheck in allen Go-Modulen").
|
||||
GOVULNCHECK ?= go run golang.org/x/vuln/cmd/govulncheck@v1.9.0
|
||||
|
||||
.PHONY: vulncheck
|
||||
vulncheck:
|
||||
$(GOVULNCHECK) ./...
|
||||
|
||||
.PHONY: tidy
|
||||
tidy:
|
||||
go mod tidy
|
||||
|
||||
.PHONY: ci
|
||||
ci: fmt vet test vulncheck
|
||||
|
||||
.PHONY: help
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " ci fmt + vet + test + vulncheck (the default)"
|
||||
@echo " fmt fail if a file is not gofmt'ed (fmt-fix rewrites them)"
|
||||
@echo " vet go vet"
|
||||
@echo " test go test -race"
|
||||
@echo " vulncheck govulncheck $(subst go run ,,$(GOVULNCHECK))"
|
||||
@echo " tidy go mod tidy"
|
||||
@@ -0,0 +1,10 @@
|
||||
yetano-webui-template
|
||||
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||
yetano-webui-template itself is proprietary, see LICENSE.
|
||||
|
||||
This repository bundles the following third-party files, which keep
|
||||
their own licenses:
|
||||
|
||||
- Bootstrap v5.3.3 (https://getbootstrap.com/): static/bootstrap.min.css,
|
||||
static/bootstrap.bundle.min.js -- MIT, Copyright 2011-2024 The
|
||||
Bootstrap Authors (https://github.com/twbs/bootstrap/blob/main/LICENSE).
|
||||
@@ -9,50 +9,19 @@ see `layout.go` for the API (`PageHeader`, `NavItem`, `NewRenderer`,
|
||||
|
||||
## Source of truth
|
||||
|
||||
This repo is the **source of truth** for the shared layout. `yak/yak-webui-template`
|
||||
and `yamase/yamase-webui-template` are git-history mirrors of it (each repo's
|
||||
root mirrors this repo's root — not a subdirectory — created via `git merge
|
||||
--allow-unrelated-histories`, so the histories are related and can be
|
||||
re-merged incrementally). Each mirror has exactly one intentional local
|
||||
difference: its `go.mod` `module` line, which names that repo's own import
|
||||
path instead of this one. Make layout changes *here first*, tag a new
|
||||
version, then pull the change into each mirror — never edit the mirrored
|
||||
copies directly.
|
||||
|
||||
### Pulling a change into a mirror
|
||||
|
||||
From inside `yak-webui-template` or `yamase-webui-template` (each already
|
||||
has a `source` remote pointing back here):
|
||||
|
||||
```sh
|
||||
git fetch source main
|
||||
git merge source/main
|
||||
# resolve the go.mod conflict: keep the mirror's own module line, take
|
||||
# everything else from source
|
||||
git checkout --ours go.mod # if go.mod conflicted
|
||||
git add go.mod
|
||||
git commit
|
||||
go test ./...
|
||||
git push origin main
|
||||
```
|
||||
|
||||
### One-time mirror setup (already done, kept here for reference/re-setup)
|
||||
|
||||
```sh
|
||||
git init -b main
|
||||
git remote add source git@teruna.dev:yetano/yetano-webui-template.git
|
||||
git fetch source main
|
||||
git merge --allow-unrelated-histories -m "Initial mirror of yetano-webui-template" source/main
|
||||
go mod edit -module teruna.dev/<org>/<org>-webui-template
|
||||
git remote add origin git@teruna.dev:<org>/<org>-webui-template.git
|
||||
git push -u origin main
|
||||
```
|
||||
This repo is the **single source of truth** for the shared layout. Every
|
||||
consumer -- in `yetano`, `yak` (`yakwui`) and `yamase` (`yamase-web`) --
|
||||
imports `teruna.dev/yetano/yetano-webui-template` directly: make layout
|
||||
changes here, tag a new version, then bump the consumers. The former
|
||||
git-history mirrors `yak/yak-webui-template` and
|
||||
`yamase/yamase-webui-template` were removed and their repositories
|
||||
archived on 2026-10-23 (nothing imported them).
|
||||
|
||||
## What's shared vs. what stays per-project
|
||||
|
||||
Shared here: the base HTML skeleton, navbar, sidebar (generic nav-item
|
||||
list), footer, and the CSS rules that style exactly those elements
|
||||
(`static/style.css` — theme root variables, navbar, `.sidebar .nav-link`
|
||||
(`static/style.css` — theme tokens and the Bootstrap bridge, navbar, `.sidebar .nav-link`
|
||||
incl. the `#0b82b8` inactive-link color, footer, flash-banner alerts).
|
||||
|
||||
Stays in each consuming project: page-specific templates
|
||||
@@ -61,22 +30,113 @@ forms, buttons, markdown, ...), and anything else specific to that tool.
|
||||
|
||||
## Theming
|
||||
|
||||
`static/style.css`'s palette is exposed as `--yw-*` CSS custom properties
|
||||
on `:root` (`--yw-bg`, `--yw-text`, `--yw-chrome-bg`, `--yw-accent`,
|
||||
`--yw-nav-link`, `--yw-success-*`/`--yw-danger-*`, ...) rather than baked
|
||||
directly into each rule — it's a documented, reusable theme, not just an
|
||||
implementation detail. This is the *only* theme the module ships: fixed
|
||||
dark, no `prefers-color-scheme`, no light mode. Don't add one here on a
|
||||
per-project basis (redefining `--yw-*` globally in one consumer would
|
||||
silently reskin every future consumer sharing this CSS file); a project
|
||||
that genuinely needs a different look — e.g. a light/dark toggle, like
|
||||
`yaais` has — should own that itself rather than pushing multi-theme
|
||||
complexity into this module, since `yaais` shows that need doesn't
|
||||
actually require *this* module either (it's a client-rendered SPA, not a
|
||||
server-rendered Go-template dashboard). If a real case for a second theme
|
||||
*in* this module shows up later, the `--yw-*` tokens are exactly the
|
||||
seam to add one through — redefine them under a `[data-theme="..."]`
|
||||
selector the way `yaais`'s own stylesheet does.
|
||||
Three independent axes, all set on `<html>` and resolved on the server:
|
||||
|
||||
| Axis | `PageHeader` field | Attribute | Values |
|
||||
|---|---|---|---|
|
||||
| Mode | `Theme` | `data-theme` | `layout.ThemeDark` (also `""`, unset), `ThemeLight`, `ThemeSystem` (follows `prefers-color-scheme`) |
|
||||
| Colors | `Palette` | `data-palette` | `layout.PaletteDefault` (also `""`), `PaletteGraphite` (grey/violet, after nessajina.tv), `PaletteContrast` (high contrast), `PaletteSlate` (slate/lavender) |
|
||||
| Shape | `Style` | `data-style` | `layout.StyleModern` (also `""`, the default since v0.5.0), `StyleClassic` (the look up to v0.4.x) |
|
||||
|
||||
A consumer that sets none gets the modern style, dark, palette Yetano.
|
||||
|
||||
### Styles: modern (default) and classic
|
||||
|
||||
Since v0.5.0 the default is the modern style: navbar without a rule,
|
||||
the sidebar as a floating rounded card with small group headings,
|
||||
icons and a pill for the active entry, and rounder, quieter Bootstrap
|
||||
components (cards, buttons, form fields, tables, list groups, tinted
|
||||
status badges). It is one block of `[data-style="modern"]` rules at
|
||||
the end of `static/style.css` over the classic rules; the template
|
||||
always sets `data-style` (`modern` when `Style` is empty), so
|
||||
`data-style="classic"` still gives exactly the old look. Visitors pick
|
||||
either in the appearance menu ("Style"/"Stil", cookie `yw_style`); a
|
||||
consumer that wants the old look by default sets `Style: StyleClassic`
|
||||
before `ApplyAppearance`.
|
||||
|
||||
Two optional `NavItem` fields feed it: `Group` (a heading above the
|
||||
first item of each run of equal groups, shown in both styles) and
|
||||
`Icon`, a name from `layout.NavIcons` (`dashboard`, `server`, `box`,
|
||||
`users`, `key`, `shield`, `settings`, ...; shown only in the modern
|
||||
style). In the modern style inactive sidebar links use the text color;
|
||||
the cross-project `#0b82b8` (`--yw-nav-link` of the default palette)
|
||||
now only colors them in the classic style (owner decision 2026-11-28).
|
||||
|
||||
`go run ./cmd/webui-demo` serves a sample page (http://127.0.0.1:8097/)
|
||||
for comparing styles, palettes and modes; `?style=`, `?palette=` and
|
||||
`?theme=` set the same cookies as the menu.
|
||||
|
||||
How `static/style.css` does it:
|
||||
|
||||
- **Every color token is written once**, as `--yw-x: light-dark(<light>,
|
||||
<dark>)`. The mode only sets `color-scheme` (`dark`, `light`, or
|
||||
`light dark` for system), so no mode repeats another's values and
|
||||
"system" needs no duplicated media-query block. Needs a browser from
|
||||
2024 or later (`light-dark()`, `color-mix()`).
|
||||
- **Triplets and images** (`--yw-*-rgb` for Bootstrap's `rgba(var(...),
|
||||
a)`, and the few `url()` icons Bootstrap swaps in dark mode) can't use
|
||||
`light-dark()`. They pick with the mode switches `--yw-if-light`/
|
||||
`--yw-if-dark`: `var(--yw-if-light, <light>) var(--yw-if-dark,
|
||||
<dark>)`.
|
||||
- **A palette is one `:root[data-palette="..."]` block** that lists only
|
||||
what it changes from the default (bare `:root`) block.
|
||||
- **Bootstrap follows the palette:** its theme-dependent `--bs-*`
|
||||
variables (body, emphasis, secondary/tertiary, links, borders, the
|
||||
`*-subtle`/`*-emphasis` colors, form validation) and the components
|
||||
that hard-code its primary blue (`.btn-primary`, `.list-group`,
|
||||
`.form-check-input:checked`, focus rings, ...) are mapped onto
|
||||
`--yw-*`. Bootstrap's own `data-bs-theme` is not used (it has no
|
||||
"system" mode without a script); a consumer's local
|
||||
`data-bs-theme="dark"` on one element still works.
|
||||
- `TestPaletteTokens` checks that every palette in `layout.Palettes` has
|
||||
a block, every color is one `light-dark()` pair, every `-rgb` triplet
|
||||
matches its color, and a palette only overrides default tokens.
|
||||
- `--yw-nav-link` is `#0b82b8` in the default palette in both modes (the
|
||||
cross-project design token, see the meta-repo `AGENTS.md`). The other
|
||||
palettes use their own nav-link color: blue would clash with
|
||||
graphite's violet, and it lacks contrast on black.
|
||||
|
||||
Tokens a consumer's own stylesheet can use: `--yw-bg`, `--yw-surface`,
|
||||
`--yw-surface-2`, `--yw-text`, `--yw-text-strong`, `--yw-muted`,
|
||||
`--yw-border`, `--yw-chrome-bg`/`-border`, `--yw-brand`, `--yw-accent`,
|
||||
`--yw-link`/`-hover`, `--yw-primary`, `--yw-on-primary`,
|
||||
`--yw-{success,danger,warning,info}-{bg,border,text}`, plus the `-rgb`
|
||||
triplets of bg/surface/text/accent/link/primary. For its own
|
||||
theme-dependent colors a consumer writes `light-dark()` as well, never
|
||||
redefines `--yw-*` (that would reskin only that project). The older
|
||||
pattern, separate `[data-theme="..."]` blocks, keeps working.
|
||||
|
||||
### Theme/palette menu
|
||||
|
||||
The module can store the visitor's choice itself, without any script
|
||||
(works under a strict `script-src 'self'` CSP):
|
||||
|
||||
```go
|
||||
mux.Handle("POST /appearance", layout.AppearanceHandler(basePath))
|
||||
...
|
||||
hdr := layout.PageHeader{BasePath: basePath, AppearancePath: "/appearance", ...}
|
||||
hdr.ApplyAppearance(r) // Theme/Palette from the cookies, AppearanceBack = current page
|
||||
```
|
||||
|
||||
`AppearancePath` set, the navbar shows a `<details>` dropdown (labels in
|
||||
German when `Lang` starts with `de`) with one POST form whose buttons
|
||||
submit `theme` or `palette`. `AppearanceHandler` stores the choice in
|
||||
the cookies `yw_theme`/`yw_palette` (path `BasePath/`, a year,
|
||||
`HttpOnly`, `SameSite=Lax`) and redirects to `back`, but only to a path
|
||||
inside the UI. Any other method gets 405. `ApplyAppearance` ignores
|
||||
unknown cookie values, so whatever the consumer set before stays the
|
||||
default. It works with and without `http.StripPrefix` in front of the
|
||||
UI: a path that differs from the request's `RequestURI` is taken as
|
||||
already relative and kept as it is (v0.3.1; up to v0.3.0 the page
|
||||
`/feeds` behind StripPrefix with base path `/feeds` was wrongly cut to
|
||||
`/`). A consumer whose middleware wants a CSRF token on every POST
|
||||
puts the hidden field into `AppearanceFormHTML`, which is rendered
|
||||
inside the menu's form. A consumer with its own switch can keep it and
|
||||
just set `Theme`/`Palette` (none does today).
|
||||
|
||||
**Adding a palette:** a `:root[data-palette="..."]` block in
|
||||
`static/style.css`, a constant and an entry in `Palettes` in
|
||||
`appearance.go`. `TestPaletteTokens` reports anything missing.
|
||||
|
||||
## Consuming this module
|
||||
|
||||
@@ -93,17 +153,130 @@ mux.Handle("/webui-static/", layout.StaticHandler("/webui-static/"))
|
||||
See `yetano/yasta` for a full worked example (the pilot migration of this
|
||||
module).
|
||||
|
||||
## Flash messages (v0.3.0)
|
||||
|
||||
A message after a form POST travels in the query parameters `flash` and
|
||||
`flashKind` (owner decision 2026-10-31): no server state, and it works
|
||||
behind a base path and through the Verse relay. The text lands in the
|
||||
browser history, so it never carries a secret.
|
||||
|
||||
```go
|
||||
layout.RedirectFlash(w, r, basePath+"/services", layout.FlashOK, "service a started") // 303
|
||||
...
|
||||
hdr.ApplyFlash(r) // fills Flash/FlashKind; an unknown kind shows as an error
|
||||
```
|
||||
|
||||
`FlashKind` is `FlashOK` (green), `FlashInfo` (blue) or `FlashError`
|
||||
(red). `ApplyAppearance` drops the flash parameters from
|
||||
`AppearanceBack` (`WithoutFlash`), so switching the theme does not show
|
||||
the message again.
|
||||
|
||||
## HTTP hardening: package `httpsec` (v0.3.0)
|
||||
|
||||
`teruna.dev/yetano/yetano-webui-template/httpsec`, net/http only. Owner
|
||||
decisions of 2026-10-31 are built in.
|
||||
|
||||
- `Headers(h, HeaderOptions{...})` -- outermost wrapper. Default set:
|
||||
`Content-Security-Policy` `DefaultCSP` (`default-src 'self'; img-src
|
||||
'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors
|
||||
'none'; form-action 'self'`), `nosniff`, `X-Frame-Options: DENY`,
|
||||
`Referrer-Policy: same-origin`, `Cross-Origin-Opener-Policy:
|
||||
same-origin`, `Cache-Control: no-store` except below
|
||||
`CacheablePrefixes`, HSTS only with `TLS: true`. `CSP` overrides the
|
||||
policy for a UI that needs more.
|
||||
- Host gate against DNS rebinding: `Gate(h, allowed, "<config key>")`
|
||||
answers 421. `HostAllowed` accepts IP addresses, `localhost`,
|
||||
`*.localhost` and the configured hosts (add a public URL's host with
|
||||
`HostOf`); an **empty Host is rejected**. `GateActive(loginOn,
|
||||
allowed)` is the family rule for when to install it: **always without
|
||||
a login, with a login only once hosts are configured**.
|
||||
- `SafeNext(next, basePath, "/login", "/logout")` -- the target after a
|
||||
login or a "back" link: a local path inside the UI, else
|
||||
`basePath + "/"`.
|
||||
- `CookiePath(basePath)` (`basePath + "/"`, `/` at the root) and
|
||||
`SecureCookies(r, publicURL)` (TLS or an https public URL).
|
||||
|
||||
Cross-origin protection stays `http.NewCrossOriginProtection()` from
|
||||
the standard library, wrapped inside `Headers`.
|
||||
|
||||
Order: `Headers(Gate(cop.Handler(app)))` -- the headers also reach a 421
|
||||
or 403.
|
||||
|
||||
- `BearerTokens(h, tokens)` (v0.4.0) -- for a UI without user
|
||||
management of its own: only requests with `Authorization: Bearer <one
|
||||
of tokens>` pass (constant-time compare), others get 401. A reverse
|
||||
proxy in front sets the header (Traefik `headers.customRequestHeaders`),
|
||||
or yasta for a UI shown over the bus. No tokens: everything passes --
|
||||
bind such a UI to loopback only.
|
||||
|
||||
## Web UI over the YAPL bus: package `busweb` (v0.4.0)
|
||||
|
||||
`teruna.dev/yetano/yetano-webui-template/busweb` (meta-repo
|
||||
`docs/verse/protocols.md` §18, D-200; types in `yetano.dev/yetano/verse/web`).
|
||||
A YAPL participant provides `<name>.web@1`; yasta mounts its UI at
|
||||
`/apps/<service>/` of yasta's web UI and sends each HTTP request as one
|
||||
call. The same `http.Handler` serves both ways:
|
||||
|
||||
```go
|
||||
app := myUI() // links/redirects use busweb.Prefix(r)
|
||||
// over the bus: in the capability handler
|
||||
resp := busweb.Serve(ctx, httpsec.BearerTokens(app, tokens), req) // req web.Request
|
||||
// on a TCP port (optional), e.g. behind Traefik
|
||||
h := busweb.WithPrefix(app, basePath)
|
||||
h = httpsec.BearerTokens(h, tokens)
|
||||
h = httpsec.Headers(httpsec.Gate(http.NewCrossOriginProtection().Handler(h), hosts, "web.allowed_hosts"), httpsec.HeaderOptions{})
|
||||
```
|
||||
|
||||
- `Prefix(r)` -- where the UI is mounted; set `PageHeader.BasePath` to it
|
||||
per request (it differs between the bus, the TCP port and yasta's web
|
||||
relay).
|
||||
- `User(r)` -- the yasta web user for a request over the bus (yasta's
|
||||
claim; require yasta's token if other participants may call the
|
||||
capability), `FromBus(r)`.
|
||||
- `Serve` hands the handler the path below the prefix with `RequestURI`
|
||||
as the browser sent it (so `ApplyAppearance` works), keeps only the
|
||||
allowed response headers and cuts bodies over 512 KiB.
|
||||
|
||||
## Migration status
|
||||
|
||||
All five projects are migrated, on `v0.1.5`.
|
||||
Fourteen projects use it (as of 2026-11-29). From v0.5.0 on, a bump brings
|
||||
the modern style as the default; the consumer then gives its
|
||||
`NavItems` a `Group` and an `Icon` (yasta is the reference).
|
||||
|
||||
| Project | Meta-repo | Status |
|
||||
|---|---|---|
|
||||
| `yasta` | yetano | migrated (pilot) |
|
||||
| `yasl` | yetano | migrated |
|
||||
| `yaiam` | yetano | migrated |
|
||||
| `yakwui` | yak | migrated |
|
||||
| `yamase-web` | yamase | migrated |
|
||||
A new tag is not rolled out by rebuilding every consumer: each one gets
|
||||
an item in its `TODO-next-build.md` and bumps with its next release
|
||||
(`yetano/AGENTS.md`, "Pre-build tasks"). All fourteen have the item for
|
||||
v0.5.3 (the sidebar link flicker on page load).
|
||||
|
||||
| Project | Meta-repo | Version | Status |
|
||||
|---|---|---|---|
|
||||
| `yasta` | yetano | v0.5.2 | migrated (pilot); sidebar with groups and icons |
|
||||
| `yasl` | yetano | v0.5.1 | migrated; sidebar with groups and icons |
|
||||
| `yaiam` | yetano | v0.5.2 | migrated (`yaiam-web` and the `yaiam-authd` login pages); sidebar with groups and icons |
|
||||
| `yakwui` | yak | v0.5.2 | migrated; sidebar with groups and icons |
|
||||
| `yamase-web` | yamase | v0.5.2 | migrated; sidebar with groups and icons |
|
||||
| `yamocir` | yetano | v0.5.2 | migrated; sidebar with groups and icons |
|
||||
| `yet` (`yet serve`) | yetano | v0.5.2 | built on it (a server-rendered shell whose content area a small JS app fills) |
|
||||
| `yareco` | yetano | v0.5.1 | built on it (reference consumer for themes) |
|
||||
| `yashatra` | yetano | v0.5.2 | built on it (web UI over the YAPL bus, `busweb`) |
|
||||
| `yawehopa` | yetano | v0.5.2 | built on it; sidebar with groups and icons |
|
||||
| `yacota` | yetano | v0.4.0 | built on it (`yacota serve`, also over the YAPL bus via `busweb`); classic look until the bump |
|
||||
| `yanos` | yetano | v0.4.0 | built on it (also over the YAPL bus via `busweb`); classic look until the bump |
|
||||
| `yanks-registry` | yetano | v0.4.0 | built on it (the Yanks Directory's moderation UI); classic look until the bump |
|
||||
| `yastadi` | yetano | v0.1.7 | built on it (`internal/webui`); far behind, check every page when bumping |
|
||||
|
||||
`yaais` was evaluated too and deliberately NOT migrated: it's a
|
||||
client-rendered SPA (static `index.html` + vanilla JS), not a
|
||||
server-rendered Go-template dashboard, so this module's actual
|
||||
deliverable (Go templates) doesn't apply. It adopted the same dark
|
||||
palette independently in its own stylesheet instead, plus its own
|
||||
light/dark toggle — see its `internal/yaais/static/style.css`.
|
||||
|
||||
## Checks
|
||||
|
||||
`make ci` (the default target) runs `fmt`, `vet`, `test` (with `-race`)
|
||||
and `vulncheck` (govulncheck at a pinned version, needs network access).
|
||||
Run it before tagging.
|
||||
|
||||
## Versioning note
|
||||
|
||||
@@ -114,19 +287,32 @@ concurrent-edit conflict during the initial rollout) and can produce a
|
||||
force-move an existing tag again for any future change — always cut a
|
||||
new one, even for a one-line fix.
|
||||
|
||||
## PageHeader fields (current as of v0.1.5)
|
||||
## PageHeader fields (current as of v0.2.5)
|
||||
|
||||
`Title`, `AppName` (lowercase product name for `<title>`/footer — not
|
||||
`Name`, which collides with a domain type's own `Name` field once
|
||||
embedded in the same struct, as yakwui's viewmodel types do), `Lang`
|
||||
(`<html lang>`, defaults to `"en"`), `Brand`, `BrandInitial`, `Subtitle`,
|
||||
(`<html lang>`, defaults to `"en"`), `Theme` (`<html data-theme>`, see
|
||||
Theming), `Brand`, `BrandInitial`, `Subtitle`,
|
||||
`BasePath`, `NavItems`/`ActiveNav`, `Flash`/`FlashKind`, `Username`,
|
||||
`LogoutPath` (a plain GET link — for a POST-form logout or any other
|
||||
markup mismatch, render it yourself into `NavbarRightExtra` instead and
|
||||
leave `Username`/`LogoutPath` unset), `NavbarBeforeBrand` (before the
|
||||
`Palette`, `AppearancePath`/`AppearanceBack` (since v0.2.0) and
|
||||
`AppearanceFormHTML` (since v0.2.4, see Theming), `LogoutPath` (since v0.1.10 a `<form method="post">` with a submit
|
||||
button styled like the former link, never a GET link: a logout reachable
|
||||
by GET can be triggered from any foreign page via an `<img>`/link and by
|
||||
link prefetchers; the consumer registers the route as `POST` only and
|
||||
answers `GET` with 405 + `Allow: POST`. If the form needs a hidden CSRF
|
||||
field or other markup, render it yourself into `NavbarRightExtra` and
|
||||
leave `LogoutPath` unset), `NavbarBeforeBrand` (before the
|
||||
brand link, e.g. a mobile sidebar-toggle button),
|
||||
`NavbarLeftExtra`/`NavbarRightExtra` (the navbar's two groups),
|
||||
`ExtraHeadHTML`/`ExtraBodyHTML`, and `BodyAttrs`/`SidebarAttrs` —
|
||||
`template.HTMLAttr`, not `template.HTML` — raw extra attributes on
|
||||
`<body>` and the sidebar `<nav>` for a consumer's own client-side
|
||||
framework state (e.g. yakwui's Alpine.js collapsible sidebar).
|
||||
framework state (e.g. yakwui's Alpine.js collapsible sidebar). A page
|
||||
without a sidebar (a login page) sets `BodyAttrs` to
|
||||
`` ` class="no-sidebar"` ``: since v0.2.5 `static/style.css` then hides
|
||||
the sidebar column and gives `<main>` the full width.
|
||||
|
||||
## License
|
||||
|
||||
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE). Third-party components bundled in this repository keep their own licenses; see [NOTICE](NOTICE).
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"teruna.dev/yetano/yetano-webui-template/httpsec"
|
||||
)
|
||||
|
||||
// Values for PageHeader.Palette; each has its own block in
|
||||
// static/style.css. "" is PaletteDefault.
|
||||
const (
|
||||
PaletteDefault = "default"
|
||||
PaletteGraphite = "graphite" // grey and violet, after nessajina.tv
|
||||
PaletteContrast = "contrast" // high contrast
|
||||
PaletteSlate = "slate" // dark slate and lavender, made for StyleModern
|
||||
)
|
||||
|
||||
// Values for PageHeader.Style, the shape of the chrome, rendered as
|
||||
// <html data-style="...">. "" is StyleModern, the default since v0.5.0
|
||||
// (floating sidebar card with group headings and icons, rounded
|
||||
// components); StyleClassic is the original look, still selectable
|
||||
// from the appearance menu.
|
||||
const (
|
||||
StyleClassic = "classic"
|
||||
StyleModern = "modern"
|
||||
)
|
||||
|
||||
// Cookies AppearanceHandler sets and ApplyAppearance reads. Scoped to
|
||||
// the consumer's BasePath, so two dashboards on one host keep their own
|
||||
// choice.
|
||||
const (
|
||||
ThemeCookie = "yw_theme"
|
||||
PaletteCookie = "yw_palette"
|
||||
StyleCookie = "yw_style"
|
||||
)
|
||||
|
||||
// Choice is one entry of the appearance menu.
|
||||
type Choice struct {
|
||||
ID string
|
||||
Label string // English
|
||||
LabelDE string
|
||||
Symbol string
|
||||
}
|
||||
|
||||
// Themes, Palettes and Styles are the choices ApplyAppearance and
|
||||
// AppearanceHandler accept, in menu order.
|
||||
var (
|
||||
Themes = []Choice{
|
||||
{ThemeSystem, "System", "System", "◐"},
|
||||
{ThemeLight, "Light", "Hell", "☀"},
|
||||
{ThemeDark, "Dark", "Dunkel", "☾"},
|
||||
}
|
||||
Palettes = []Choice{
|
||||
{PaletteDefault, "Yetano", "Yetano", ""},
|
||||
{PaletteGraphite, "Graphite", "Graphit", ""},
|
||||
{PaletteContrast, "High contrast", "Hoher Kontrast", ""},
|
||||
{PaletteSlate, "Slate", "Schiefer", ""},
|
||||
}
|
||||
Styles = []Choice{
|
||||
{StyleModern, "Modern", "Modern", ""},
|
||||
{StyleClassic, "Classic", "Klassisch", ""},
|
||||
}
|
||||
)
|
||||
|
||||
func known(choices []Choice, id string) bool {
|
||||
for _, c := range choices {
|
||||
if c.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ApplyAppearance overrides h.Theme, h.Palette and h.Style with the visitor's
|
||||
// choice from the cookies AppearanceHandler sets (unknown values are
|
||||
// ignored, so the consumer's own defaults stay), and records the
|
||||
// current page as AppearanceBack for the menu's return trip. Call it
|
||||
// after BasePath is set. Resolving this on the server lets the page
|
||||
// arrive in the right colors without an inline script.
|
||||
func (h *PageHeader) ApplyAppearance(r *http.Request) {
|
||||
if c, err := r.Cookie(ThemeCookie); err == nil && known(Themes, c.Value) {
|
||||
h.Theme = c.Value
|
||||
}
|
||||
if c, err := r.Cookie(PaletteCookie); err == nil && known(Palettes, c.Value) {
|
||||
h.Palette = c.Value
|
||||
}
|
||||
if c, err := r.Cookie(StyleCookie); err == nil && known(Styles, c.Value) {
|
||||
h.Style = c.Value
|
||||
}
|
||||
path := r.URL.Path
|
||||
if h.BasePath != "" && !strippedPath(r) &&
|
||||
(path == h.BasePath || strings.HasPrefix(path, h.BasePath+"/")) {
|
||||
path = strings.TrimPrefix(path, h.BasePath)
|
||||
}
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
back := url.URL{Path: path, RawQuery: r.URL.RawQuery}
|
||||
h.AppearanceBack = WithoutFlash(back.String())
|
||||
}
|
||||
|
||||
// strippedPath reports whether r.URL.Path is already relative to the
|
||||
// UI's base path, i.e. a handler such as http.StripPrefix cut it down
|
||||
// from what the client asked for. Those keep RequestURI as sent, so a
|
||||
// path that no longer matches RequestURI's was stripped -- and must not
|
||||
// be stripped again: for base path "/feeds" the relative page "/feeds"
|
||||
// is a page of its own, not the start page. Without a RequestURI (a
|
||||
// request built in code) only a whole leading BasePath segment is cut,
|
||||
// so "/r" never eats the start of "/release-notes".
|
||||
func strippedPath(r *http.Request) bool {
|
||||
if r.RequestURI == "" {
|
||||
return false
|
||||
}
|
||||
u, err := url.ParseRequestURI(r.RequestURI)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return u.Path != r.URL.Path
|
||||
}
|
||||
|
||||
// AppearanceHandler stores a theme, palette and/or style choice from a
|
||||
// POST form (fields "theme", "palette", "style", "back") in cookies and redirects to
|
||||
// back, a BasePath-relative path inside this UI (anything else goes to
|
||||
// the start page, so it is no open redirect). Register it for POST only
|
||||
// at BasePath + PageHeader.AppearancePath; other methods get 405.
|
||||
//
|
||||
// No CSRF token: a foreign page could at worst change the colors.
|
||||
func AppearanceHandler(basePath string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
theme, palette, style := r.FormValue("theme"), r.FormValue("palette"), r.FormValue("style")
|
||||
if (theme == "" && palette == "" && style == "") ||
|
||||
(theme != "" && !known(Themes, theme)) ||
|
||||
(palette != "" && !known(Palettes, palette)) ||
|
||||
(style != "" && !known(Styles, style)) {
|
||||
http.Error(w, "unknown theme, palette or style", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
set := func(name, value string) {
|
||||
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: httpsec.CookiePath(basePath),
|
||||
MaxAge: 365 * 24 * 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
||||
}
|
||||
if theme != "" {
|
||||
set(ThemeCookie, theme)
|
||||
}
|
||||
if palette != "" {
|
||||
set(PaletteCookie, palette)
|
||||
}
|
||||
if style != "" {
|
||||
set(StyleCookie, style)
|
||||
}
|
||||
http.Redirect(w, r, basePath+httpsec.SafeNext(r.FormValue("back"), ""), http.StatusSeeOther)
|
||||
})
|
||||
}
|
||||
|
||||
// AppearanceItem is one button of the rendered appearance menu.
|
||||
type AppearanceItem struct {
|
||||
ID, Label, Symbol string
|
||||
Current bool
|
||||
}
|
||||
|
||||
// AppearanceMenuData is what the navbar template renders the menu from.
|
||||
type AppearanceMenuData struct {
|
||||
Current AppearanceItem // the active theme, shown on the closed menu
|
||||
ThemeHeading, PaletteHeading, StyleHeading string
|
||||
Themes, Palettes, Styles []AppearanceItem
|
||||
}
|
||||
|
||||
// AppearanceMenu builds the menu's data, labeled in German when Lang
|
||||
// starts with "de", otherwise in English. The navbar template calls it.
|
||||
func (h PageHeader) AppearanceMenu() AppearanceMenuData {
|
||||
de := strings.HasPrefix(h.Lang, "de")
|
||||
items := func(choices []Choice, current string) []AppearanceItem {
|
||||
out := make([]AppearanceItem, len(choices))
|
||||
for i, c := range choices {
|
||||
label := c.Label
|
||||
if de {
|
||||
label = c.LabelDE
|
||||
}
|
||||
out[i] = AppearanceItem{ID: c.ID, Label: label, Symbol: c.Symbol, Current: c.ID == current}
|
||||
}
|
||||
return out
|
||||
}
|
||||
theme, palette, style := h.Theme, h.Palette, h.Style
|
||||
if theme == "" {
|
||||
theme = ThemeDark
|
||||
}
|
||||
if palette == "" {
|
||||
palette = PaletteDefault
|
||||
}
|
||||
if style == "" {
|
||||
style = StyleModern
|
||||
}
|
||||
m := AppearanceMenuData{
|
||||
Themes: items(Themes, theme),
|
||||
Palettes: items(Palettes, palette),
|
||||
Styles: items(Styles, style),
|
||||
ThemeHeading: "Theme",
|
||||
PaletteHeading: "Palette",
|
||||
StyleHeading: "Style",
|
||||
}
|
||||
if de {
|
||||
m.ThemeHeading, m.PaletteHeading, m.StyleHeading = "Modus", "Farben", "Stil"
|
||||
}
|
||||
for _, t := range m.Themes {
|
||||
if t.Current {
|
||||
m.Current = t
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// paletteBlocks returns the --yw-* declarations of every top-level
|
||||
// :root block in static/style.css that declares palette tokens, keyed by
|
||||
// palette ID (the bare :root block is PaletteDefault).
|
||||
func paletteBlocks(t *testing.T) map[string]map[string]string {
|
||||
t.Helper()
|
||||
css, err := staticFS.ReadFile("static/style.css")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blocks := map[string]map[string]string{}
|
||||
rxBlock := regexp.MustCompile(`(?m)^(:root[^{]*)\{([^}]*)\}`)
|
||||
rxDecl := regexp.MustCompile(`(?m)^\s*(--yw-[a-z0-9-]+):\s*(.*?);\s*$`)
|
||||
for _, m := range rxBlock.FindAllStringSubmatch(string(css), -1) {
|
||||
sel := strings.TrimSpace(m[1])
|
||||
var id string
|
||||
switch {
|
||||
case sel == ":root":
|
||||
id = PaletteDefault
|
||||
case strings.HasPrefix(sel, `:root[data-palette="`):
|
||||
id = strings.TrimSuffix(strings.TrimPrefix(sel, `:root[data-palette="`), `"]`)
|
||||
default:
|
||||
continue
|
||||
}
|
||||
decls := map[string]string{}
|
||||
for _, d := range rxDecl.FindAllStringSubmatch(m[2], -1) {
|
||||
if !strings.HasPrefix(d[1], "--yw-if-") {
|
||||
decls[d[1]] = d[2]
|
||||
}
|
||||
}
|
||||
if len(decls) == 0 {
|
||||
continue
|
||||
}
|
||||
if blocks[id] != nil {
|
||||
t.Fatalf("style.css: palette %q declared twice", id)
|
||||
}
|
||||
blocks[id] = decls
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func hexTriplet(h string) string {
|
||||
var r, g, b int
|
||||
fmt.Sscanf(h, "#%02x%02x%02x", &r, &g, &b)
|
||||
return fmt.Sprintf("%d, %d, %d", r, g, b)
|
||||
}
|
||||
|
||||
// TestPaletteTokens checks the palette blocks of static/style.css: every
|
||||
// palette in Palettes has one; each color is one light-dark() pair, so
|
||||
// no mode repeats another's values; each *-rgb triplet matches its
|
||||
// color; a palette only overrides tokens the default declares; and the
|
||||
// default keeps the cross-project nav-link color.
|
||||
func TestPaletteTokens(t *testing.T) {
|
||||
blocks := paletteBlocks(t)
|
||||
for _, p := range Palettes {
|
||||
if blocks[p.ID] == nil {
|
||||
t.Errorf("style.css: no block for palette %q", p.ID)
|
||||
}
|
||||
}
|
||||
if len(blocks) != len(Palettes) {
|
||||
t.Errorf("style.css has %d palette blocks, Palettes lists %d", len(blocks), len(Palettes))
|
||||
}
|
||||
|
||||
rxColor := regexp.MustCompile(`^light-dark\((#[0-9a-f]{6}), (#[0-9a-f]{6})\)$`)
|
||||
rxTriplet := regexp.MustCompile(`^var\(--yw-if-light, (\d+, \d+, \d+)\) var\(--yw-if-dark, (\d+, \d+, \d+)\)$`)
|
||||
def := blocks[PaletteDefault]
|
||||
for id, decls := range blocks {
|
||||
for name, value := range decls {
|
||||
if _, ok := def[name]; !ok {
|
||||
t.Errorf("palette %q: %s is not a default token", id, name)
|
||||
}
|
||||
if base, ok := strings.CutSuffix(name, "-rgb"); ok {
|
||||
tm := rxTriplet.FindStringSubmatch(value)
|
||||
cm := rxColor.FindStringSubmatch(decls[base])
|
||||
if tm == nil || cm == nil {
|
||||
t.Errorf("palette %q: %s = %q needs %s in the same block", id, name, value, base)
|
||||
continue
|
||||
}
|
||||
if tm[1] != hexTriplet(cm[1]) || tm[2] != hexTriplet(cm[2]) {
|
||||
t.Errorf("palette %q: %s = %q does not match %s = %q", id, name, value, base, decls[base])
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !rxColor.MatchString(value) {
|
||||
t.Errorf("palette %q: %s = %q, want light-dark(#rrggbb, #rrggbb)", id, name, value)
|
||||
}
|
||||
if _, hasRGB := def[name+"-rgb"]; hasRGB {
|
||||
if _, ok := decls[name+"-rgb"]; !ok {
|
||||
t.Errorf("palette %q: overrides %s but not %s-rgb", id, name, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if got, want := def["--yw-nav-link"], "light-dark(#0b82b8, #0b82b8)"; got != want {
|
||||
t.Errorf("default --yw-nav-link = %q, want %q (cross-project design token)", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaletteAttribute(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
for palette, want := range map[string]string{
|
||||
"": `<html lang="en" data-theme="light" data-style="modern">`,
|
||||
PaletteGraphite: `<html lang="en" data-theme="light" data-palette="graphite" data-style="modern">`,
|
||||
} {
|
||||
var buf bytes.Buffer
|
||||
if err := r.Page(&buf, "dashboard", PageHeader{Theme: ThemeLight, Palette: palette}); err != nil {
|
||||
t.Fatalf("Page: %v", err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), want) {
|
||||
t.Errorf("palette %q: rendered output missing %q\n---\n%s", palette, want, buf.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAppearance(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/ui/tasks?f=1", nil)
|
||||
req.AddCookie(&http.Cookie{Name: ThemeCookie, Value: ThemeLight})
|
||||
req.AddCookie(&http.Cookie{Name: PaletteCookie, Value: "nope"})
|
||||
h := PageHeader{BasePath: "/ui", Theme: ThemeSystem, Palette: PaletteContrast}
|
||||
h.ApplyAppearance(req)
|
||||
if h.Theme != ThemeLight {
|
||||
t.Errorf("Theme = %q, want %q from the cookie", h.Theme, ThemeLight)
|
||||
}
|
||||
if h.Palette != PaletteContrast {
|
||||
t.Errorf("Palette = %q, want the consumer default %q (cookie value unknown)", h.Palette, PaletteContrast)
|
||||
}
|
||||
if h.AppearanceBack != "/tasks?f=1" {
|
||||
t.Errorf("AppearanceBack = %q, want %q", h.AppearanceBack, "/tasks?f=1")
|
||||
}
|
||||
|
||||
// Without StripPrefix only a whole leading BasePath segment is cut.
|
||||
for path, want := range map[string]string{"/release-notes": "/release-notes", "/r": "/", "/r/x": "/x"} {
|
||||
h := PageHeader{BasePath: "/r"}
|
||||
h.ApplyAppearance(httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if h.AppearanceBack != want {
|
||||
t.Errorf("BasePath /r, path %s: AppearanceBack = %q, want %q", path, h.AppearanceBack, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Behind http.StripPrefix the path is already relative to BasePath and
|
||||
// must stay as it is, even when it looks like the base path itself.
|
||||
func TestApplyAppearanceBehindStripPrefix(t *testing.T) {
|
||||
cases := []struct{ base, request, want string }{
|
||||
{"/feeds", "/feeds/feeds", "/feeds"},
|
||||
{"/feeds", "/feeds/feeds/x?a=1", "/feeds/x?a=1"},
|
||||
{"/feeds", "/feeds/", "/"},
|
||||
{"/feeds", "/feeds/items", "/items"},
|
||||
{"/r", "/r/release-notes", "/release-notes"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
var got string
|
||||
h := http.StripPrefix(c.base, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hdr := PageHeader{BasePath: c.base}
|
||||
hdr.ApplyAppearance(r)
|
||||
got = hdr.AppearanceBack
|
||||
}))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, c.request, nil))
|
||||
if got != c.want {
|
||||
t.Errorf("base %s, request %s: AppearanceBack = %q, want %q", c.base, c.request, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppearanceHandler(t *testing.T) {
|
||||
h := AppearanceHandler("/ui")
|
||||
post := func(form url.Values) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/ui/appearance", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
rec := post(url.Values{"palette": {PaletteGraphite}, "back": {"/tasks?f=1"}})
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/ui/tasks?f=1" {
|
||||
t.Errorf("palette: got %d to %q, want 303 to /ui/tasks?f=1", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
cookies := rec.Result().Cookies()
|
||||
if len(cookies) != 1 || cookies[0].Name != PaletteCookie || cookies[0].Value != PaletteGraphite ||
|
||||
cookies[0].Path != "/ui/" || !cookies[0].HttpOnly {
|
||||
t.Errorf("palette: cookies = %+v", cookies)
|
||||
}
|
||||
|
||||
for _, back := range []string{"https://evil.example/", "//evil.example/", "/\\evil.example", "tasks", ""} {
|
||||
rec := post(url.Values{"theme": {ThemeDark}, "back": {back}})
|
||||
if loc := rec.Header().Get("Location"); loc != "/ui/" {
|
||||
t.Errorf("back %q: redirected to %q, want /ui/", back, loc)
|
||||
}
|
||||
}
|
||||
|
||||
for _, form := range []url.Values{{}, {"theme": {"pink"}}, {"palette": {"nope"}}} {
|
||||
if rec := post(form); rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("form %v: got %d, want 400", form, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ui/appearance?theme=dark", nil))
|
||||
if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != http.MethodPost {
|
||||
t.Errorf("GET: got %d, Allow %q; want 405, POST", rec.Code, rec.Header().Get("Allow"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppearanceMenu(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := r.Page(&buf, "dashboard", PageHeader{Title: "Dashboard"}); err != nil {
|
||||
t.Fatalf("Page: %v", err)
|
||||
}
|
||||
if strings.Contains(buf.String(), "yw-appearance") {
|
||||
t.Errorf("menu rendered without AppearancePath\n---\n%s", buf.String())
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
data := PageHeader{Title: "Dashboard", Lang: "de", BasePath: "/ui", AppearancePath: "/appearance",
|
||||
AppearanceBack: "/tasks", Theme: ThemeLight, Palette: PaletteGraphite,
|
||||
AppearanceFormHTML: `<input type="hidden" name="csrf_token" value="t0k">`}
|
||||
if err := r.Page(&buf, "dashboard", data); err != nil {
|
||||
t.Fatalf("Page: %v", err)
|
||||
}
|
||||
out := buf.String()
|
||||
for _, want := range []string{
|
||||
`<form method="post" action="/ui/appearance"`,
|
||||
`name="back" value="/tasks"><input type="hidden" name="csrf_token" value="t0k">`,
|
||||
`name="theme" value="light" aria-pressed="true"><span aria-hidden="true">☀</span> Hell</button>`,
|
||||
`name="theme" value="dark" aria-pressed="false">`,
|
||||
`name="palette" value="graphite" aria-pressed="true">Graphit</button>`,
|
||||
`<h6>Farben</h6>`,
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("rendered output missing %q\n---\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// Package busweb serves a web UI over the YAPL bus (meta-repository
|
||||
// docs/verse/protocols.md §18, D-200): yasta mounts a participant's UI in
|
||||
// its own web UI and sends each HTTP request as one call of the
|
||||
// participant's "<name>.web@N" capability. Serve runs such a request
|
||||
// against the UI's ordinary http.Handler, so the same handler can also
|
||||
// listen on a TCP port (behind a reverse proxy, see httpsec.BearerTokens).
|
||||
//
|
||||
// The handler learns where it is mounted from Prefix(r) -- it writes its
|
||||
// links and redirects with it, as with a layout.PageHeader BasePath --
|
||||
// and, over the bus, the web user yasta reports from User(r).
|
||||
package busweb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/verse/web"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
keyPrefix ctxKey = iota
|
||||
keyUser
|
||||
keyBus
|
||||
)
|
||||
|
||||
// Prefix is where the UI serving r is mounted ("" at the root), set by
|
||||
// Serve or WithPrefix.
|
||||
func Prefix(r *http.Request) string {
|
||||
p, _ := r.Context().Value(keyPrefix).(string)
|
||||
return p
|
||||
}
|
||||
|
||||
// User is the logged-in user of yasta's web UI for a request that came
|
||||
// over the bus ("" otherwise, or when yasta's login is off). It is yasta's
|
||||
// claim: trust it as far as yasta's "calls" gate for the capability (or
|
||||
// require yasta's bearer token).
|
||||
func User(r *http.Request) string {
|
||||
u, _ := r.Context().Value(keyUser).(string)
|
||||
return u
|
||||
}
|
||||
|
||||
// FromBus reports whether r came over the bus (Serve).
|
||||
func FromBus(r *http.Request) bool {
|
||||
b, _ := r.Context().Value(keyBus).(bool)
|
||||
return b
|
||||
}
|
||||
|
||||
// WithPrefix serves next below prefix ("" or "/..." without trailing
|
||||
// slash) on a TCP listener: it strips the prefix and records it for
|
||||
// Prefix. Requests outside it get 404.
|
||||
func WithPrefix(next http.Handler, prefix string) http.Handler {
|
||||
prefix = strings.TrimSuffix(prefix, "/")
|
||||
set := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), keyPrefix, prefix)))
|
||||
})
|
||||
if prefix == "" {
|
||||
return set
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle(prefix+"/", http.StripPrefix(prefix, set))
|
||||
mux.Handle(prefix, http.RedirectHandler(prefix+"/", http.StatusMovedPermanently))
|
||||
return mux
|
||||
}
|
||||
|
||||
// Serve runs req against h and returns its response. An invalid request
|
||||
// gets 400. The handler sees the path below the prefix (as after
|
||||
// http.StripPrefix), RequestURI as the browser sent it, Host "yapl" and
|
||||
// RemoteAddr "yapl"; headers outside web.ResponseHeaders are dropped and
|
||||
// a body over web.MaxResponseBody is cut (Truncated).
|
||||
func Serve(ctx context.Context, h http.Handler, req web.Request) web.Response {
|
||||
if err := req.Validate(); err != nil {
|
||||
return text(http.StatusBadRequest, err.Error())
|
||||
}
|
||||
u, err := url.ParseRequestURI(req.URL)
|
||||
if err != nil {
|
||||
return text(http.StatusBadRequest, "bad url")
|
||||
}
|
||||
ctx = context.WithValue(ctx, keyPrefix, req.Prefix)
|
||||
ctx = context.WithValue(ctx, keyUser, req.User)
|
||||
ctx = context.WithValue(ctx, keyBus, true)
|
||||
r, err := http.NewRequestWithContext(ctx, req.Method, req.URL, bytes.NewReader(req.Body))
|
||||
if err != nil {
|
||||
return text(http.StatusBadRequest, "bad request")
|
||||
}
|
||||
r.URL = u
|
||||
r.RequestURI = req.Prefix + req.URL
|
||||
r.Host = "yapl"
|
||||
r.RemoteAddr = "yapl"
|
||||
r.ContentLength = int64(len(req.Body))
|
||||
for k, vs := range req.Header {
|
||||
for _, v := range vs {
|
||||
r.Header.Add(k, v)
|
||||
}
|
||||
}
|
||||
rec := &recorder{header: http.Header{}}
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.status == 0 {
|
||||
rec.status = http.StatusOK
|
||||
}
|
||||
resp := web.Response{Status: rec.status, Header: web.FilterHeader(rec.header, web.ResponseHeaders),
|
||||
Truncated: rec.truncated}
|
||||
if req.Method != http.MethodHead {
|
||||
resp.Body = rec.body.Bytes()
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func text(status int, msg string) web.Response {
|
||||
return web.Response{Status: status, Header: map[string][]string{"Content-Type": {"text/plain; charset=utf-8"}},
|
||||
Body: []byte(msg + "\n")}
|
||||
}
|
||||
|
||||
// recorder is an http.ResponseWriter that keeps at most
|
||||
// web.MaxResponseBody bytes.
|
||||
type recorder struct {
|
||||
header http.Header
|
||||
status int
|
||||
body bytes.Buffer
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (r *recorder) Header() http.Header { return r.header }
|
||||
|
||||
func (r *recorder) WriteHeader(code int) {
|
||||
if r.status == 0 {
|
||||
r.status = code
|
||||
}
|
||||
}
|
||||
|
||||
func (r *recorder) Write(b []byte) (int, error) {
|
||||
r.WriteHeader(http.StatusOK)
|
||||
room := web.MaxResponseBody - r.body.Len()
|
||||
if len(b) > room {
|
||||
r.body.Write(b[:max(room, 0)])
|
||||
r.truncated = true
|
||||
return len(b), nil
|
||||
}
|
||||
return r.body.Write(b)
|
||||
}
|
||||
|
||||
// Flush is a no-op: the response leaves as one message.
|
||||
func (r *recorder) Flush() {}
|
||||
@@ -0,0 +1,104 @@
|
||||
package busweb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
layout "teruna.dev/yetano/yetano-webui-template"
|
||||
"yetano.dev/yetano/verse/web"
|
||||
)
|
||||
|
||||
func echo() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Header().Set("Server", "secret")
|
||||
w.Header().Set("Set-Cookie", "a=b")
|
||||
io.WriteString(w, "prefix="+Prefix(r)+" user="+User(r)+" path="+r.URL.Path+" q="+r.URL.Query().Get("q")+" ua="+r.UserAgent())
|
||||
})
|
||||
mux.HandleFunc("POST /form", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, Prefix(r)+"/hello?q="+r.FormValue("v"), http.StatusSeeOther)
|
||||
})
|
||||
mux.HandleFunc("GET /big", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(make([]byte, web.MaxResponseBody+10))
|
||||
})
|
||||
mux.HandleFunc("GET /appearance-back", func(w http.ResponseWriter, r *http.Request) {
|
||||
h := layout.PageHeader{BasePath: Prefix(r)}
|
||||
h.ApplyAppearance(r)
|
||||
io.WriteString(w, h.AppearanceBack)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
func TestServe(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/hello?q=1", Prefix: "/apps/x",
|
||||
User: "alice", Header: map[string][]string{"User-Agent": {"t"}}})
|
||||
if resp.Status != 200 || string(resp.Body) != "prefix=/apps/x user=alice path=/hello q=1 ua=t" {
|
||||
t.Fatalf("%d %q", resp.Status, resp.Body)
|
||||
}
|
||||
if resp.Header["Server"] != nil || resp.Header["Set-Cookie"][0] != "a=b" {
|
||||
t.Fatalf("headers %v", resp.Header)
|
||||
}
|
||||
if err := resp.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServePostRedirect(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "POST", URL: "/form", Prefix: "/p",
|
||||
Header: map[string][]string{"Content-Type": {"application/x-www-form-urlencoded"}}, Body: []byte("v=7")})
|
||||
if resp.Status != http.StatusSeeOther || resp.Header["Location"][0] != "/p/hello?q=7" {
|
||||
t.Fatalf("%d %v", resp.Status, resp.Header)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeTruncatesAndRejects(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/big"})
|
||||
if !resp.Truncated || len(resp.Body) != web.MaxResponseBody {
|
||||
t.Fatalf("truncated %v len %d", resp.Truncated, len(resp.Body))
|
||||
}
|
||||
if resp := Serve(context.Background(), echo(), web.Request{Method: "PUT", URL: "/hello"}); resp.Status != 400 {
|
||||
t.Fatalf("PUT: %d", resp.Status)
|
||||
}
|
||||
if resp := Serve(context.Background(), echo(), web.Request{Method: "HEAD", URL: "/hello"}); resp.Status != 405 && len(resp.Body) != 0 {
|
||||
t.Fatalf("HEAD body: %q", resp.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// The layout's appearance menu returns to the page below the prefix, not
|
||||
// to the prefix stripped twice.
|
||||
func TestServeAppearanceBack(t *testing.T) {
|
||||
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/appearance-back?x=1", Prefix: "/appearance-back"})
|
||||
if string(resp.Body) != "/appearance-back?x=1" {
|
||||
t.Fatalf("%q", resp.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithPrefix(t *testing.T) {
|
||||
srv := httptest.NewServer(WithPrefix(echo(), "/ui/"))
|
||||
defer srv.Close()
|
||||
res, err := http.Get(srv.URL + "/ui/hello?q=2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if !strings.HasPrefix(string(b), "prefix=/ui user= path=/hello q=2") {
|
||||
t.Fatalf("%q", b)
|
||||
}
|
||||
if res, _ := http.Get(srv.URL + "/hello"); res.StatusCode != 404 {
|
||||
t.Fatalf("outside prefix: %d", res.StatusCode)
|
||||
}
|
||||
root := httptest.NewServer(WithPrefix(echo(), ""))
|
||||
defer root.Close()
|
||||
res, _ = http.Get(root.URL + "/hello")
|
||||
b, _ = io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if !strings.HasPrefix(string(b), "prefix= user= path=/hello") {
|
||||
t.Fatalf("root: %q", b)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Command webui-demo serves a sample page on the shared layout, for
|
||||
// looking at themes, palettes and styles in a browser:
|
||||
//
|
||||
// go run ./cmd/webui-demo -addr 127.0.0.1:8097
|
||||
//
|
||||
// The appearance menu (top right) switches mode, palette and style;
|
||||
// ?style=, ?palette= and ?theme= set the same cookies (handy for links
|
||||
// and screenshots). It has no state and serves nothing but the sample.
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"flag"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
layout "teruna.dev/yetano/yetano-webui-template"
|
||||
)
|
||||
|
||||
//go:embed pages
|
||||
var pagesFS embed.FS
|
||||
|
||||
type page struct {
|
||||
layout.PageHeader
|
||||
Section string
|
||||
}
|
||||
|
||||
var nav = []layout.NavItem{
|
||||
{ID: "overview", Label: "Overview", Href: "/", Icon: "dashboard"},
|
||||
{ID: "services", Label: "Services", Href: "/services", Group: "Node", Icon: "box"},
|
||||
{ID: "hosts", Label: "Hosts", Href: "/hosts", Group: "Node", Icon: "server"},
|
||||
{ID: "network", Label: "Network", Href: "/network", Group: "Node", Icon: "network"},
|
||||
{ID: "logs", Label: "Logs", Href: "/logs", Group: "Node", Icon: "terminal"},
|
||||
{ID: "users", Label: "Users", Href: "/users", Group: "Access", Icon: "users"},
|
||||
{ID: "keys", Label: "Keys", Href: "/keys", Group: "Access", Icon: "key"},
|
||||
{ID: "security", Label: "Security", Href: "/security", Group: "Access", Icon: "shield"},
|
||||
{ID: "metrics", Label: "Metrics", Href: "/metrics", Group: "Data", Icon: "chart"},
|
||||
{ID: "storage", Label: "Storage", Href: "/storage", Group: "Data", Icon: "database"},
|
||||
{ID: "settings", Label: "Settings", Href: "/settings", Icon: "settings"},
|
||||
}
|
||||
|
||||
func main() {
|
||||
addr := flag.String("addr", "127.0.0.1:8097", "listen address")
|
||||
flag.Parse()
|
||||
|
||||
r, err := layout.NewRenderer(pagesFS, "pages", []string{"demo"}, ".html.tmpl", template.FuncMap{
|
||||
"buildInfo": func() string { return "demo" },
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("GET /webui-static/", layout.StaticHandler("/webui-static/"))
|
||||
mux.Handle("POST /appearance", layout.AppearanceHandler(""))
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, req *http.Request) {
|
||||
active := "overview"
|
||||
for _, n := range nav {
|
||||
if n.Href == req.URL.Path {
|
||||
active = n.ID
|
||||
}
|
||||
}
|
||||
p := page{PageHeader: layout.PageHeader{
|
||||
Title: "Overview", AppName: "demo", Brand: "YETANO", BrandInitial: "y",
|
||||
Subtitle: "night.local", NavItems: nav, ActiveNav: active,
|
||||
AppearancePath: "/appearance", Username: "admin", LogoutPath: "/logout",
|
||||
}}
|
||||
p.ApplyAppearance(req)
|
||||
// ?theme=/?palette=/?style= also go into the menu's cookies, so
|
||||
// the choice stays when you follow a sidebar link.
|
||||
q := req.URL.Query()
|
||||
for _, o := range []struct {
|
||||
key, cookie string
|
||||
choices []layout.Choice
|
||||
field *string
|
||||
}{
|
||||
{"theme", layout.ThemeCookie, layout.Themes, &p.Theme},
|
||||
{"palette", layout.PaletteCookie, layout.Palettes, &p.Palette},
|
||||
{"style", layout.StyleCookie, layout.Styles, &p.Style},
|
||||
} {
|
||||
v := q.Get(o.key)
|
||||
for _, c := range o.choices {
|
||||
if c.ID == v {
|
||||
*o.field = v
|
||||
http.SetCookie(w, &http.Cookie{Name: o.cookie, Value: v, Path: "/",
|
||||
MaxAge: 365 * 24 * 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
||||
}
|
||||
}
|
||||
}
|
||||
if v := q.Get("flash"); v != "" {
|
||||
p.Flash, p.FlashKind = v, layout.FlashOK
|
||||
}
|
||||
for _, n := range nav {
|
||||
if n.ID == active {
|
||||
p.Section, p.Title = n.Group, n.Label
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := r.Page(w, "demo", p); err != nil {
|
||||
log.Print(err)
|
||||
}
|
||||
})
|
||||
log.Printf("webui-demo on http://%s/", *addr)
|
||||
log.Fatal(http.ListenAndServe(*addr, mux))
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{{define "content"}}
|
||||
<nav aria-label="breadcrumb"><ol class="breadcrumb small mb-1"><li class="breadcrumb-item">{{if .Section}}{{.Section}}{{else}}Node{{end}}</li><li class="breadcrumb-item active">{{.Title}}</li></ol></nav>
|
||||
<h1 class="h3 mb-1">{{.Title}}</h1>
|
||||
<p class="text-body-secondary mb-3">Status of this node and the services it runs.</p>
|
||||
<hr class="mb-4">
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-sm-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-body-secondary small">Services</div><div class="fs-4 fw-bold">12</div><span class="badge text-bg-success">all running</span></div></div></div>
|
||||
<div class="col-sm-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-body-secondary small">Peers</div><div class="fs-4 fw-bold">3</div><span class="badge text-bg-secondary">kilrathi, yetano1, …</span></div></div></div>
|
||||
<div class="col-sm-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-body-secondary small">Uptime</div><div class="fs-4 fw-bold">4d 7h</div><span class="badge text-bg-info">since restart</span></div></div></div>
|
||||
<div class="col-sm-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-body-secondary small">Warnings</div><div class="fs-4 fw-bold">1</div><span class="badge text-bg-warning">certificate expires</span></div></div></div>
|
||||
</div>
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-7">
|
||||
<h2 class="h6 text-uppercase text-body-secondary mb-2">Services</h2>
|
||||
<div class="card mb-4">
|
||||
<table class="table table-hover mb-0 align-middle">
|
||||
<thead><tr><th>Name</th><th>Version</th><th>State</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><a href="#">yasl</a></td><td>0.9.2</td><td><span class="badge text-bg-success">running</span></td><td class="text-end"><button class="btn btn-sm btn-outline-primary">Restart</button></td></tr>
|
||||
<tr><td><a href="#">yaiam</a></td><td>1.4.0</td><td><span class="badge text-bg-success">running</span></td><td class="text-end"><button class="btn btn-sm btn-outline-primary">Restart</button></td></tr>
|
||||
<tr><td><a href="#">yamocir</a></td><td>0.7.1</td><td><span class="badge text-bg-danger">failed</span></td><td class="text-end"><button class="btn btn-sm btn-primary">Start</button></td></tr>
|
||||
<tr><td><a href="#">yareco</a></td><td>0.3.0</td><td><span class="badge text-bg-secondary">stopped</span></td><td class="text-end"><button class="btn btn-sm btn-primary">Start</button></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<h2 class="h6 text-uppercase text-body-secondary mb-2">Settings</h2>
|
||||
<div class="list-group">
|
||||
<a href="#" class="list-group-item list-group-item-action py-2"><div class="fw-semibold text-body-emphasis">Account</div><small class="text-body-secondary">Change your email or delete your account.</small></a>
|
||||
<a href="#" class="list-group-item list-group-item-action py-2"><div class="fw-semibold text-body-emphasis">Security</div><small class="text-body-secondary">Change your password or sign out all devices.</small></a>
|
||||
<a href="#" class="list-group-item list-group-item-action py-2"><div class="fw-semibold text-body-emphasis">Keys</div><small class="text-body-secondary">Manage API tokens and SSH keys.</small></a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-5">
|
||||
<h2 class="h6 text-uppercase text-body-secondary mb-2">Add a peer</h2>
|
||||
<div class="card"><div class="card-body">
|
||||
<form>
|
||||
<div class="mb-3"><label class="form-label" for="h">Host</label><input class="form-control" id="h" placeholder="kilrathi.local"></div>
|
||||
<div class="mb-3"><label class="form-label" for="r">Role</label><select class="form-select" id="r"><option>member</option><option>relay</option></select></div>
|
||||
<div class="form-check form-switch mb-3"><input class="form-check-input" type="checkbox" id="s" checked><label class="form-check-label" for="s">Trust on first use</label></div>
|
||||
<button type="button" class="btn btn-primary">Add peer</button>
|
||||
<button type="button" class="btn btn-outline-danger ms-1">Cancel</button>
|
||||
</form>
|
||||
</div></div>
|
||||
<div class="alert alert-info mt-3 mb-0">Peers join over the YAPL bus; a relay forwards for nodes behind NAT.</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,77 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Values for PageHeader.FlashKind.
|
||||
const (
|
||||
FlashOK = "ok"
|
||||
FlashError = "error"
|
||||
FlashInfo = "info"
|
||||
)
|
||||
|
||||
// Query parameters a flash message travels in across a redirect: no
|
||||
// server state, and it works behind a base path or a relay. The text
|
||||
// ends up in the browser history, so it never carries a secret.
|
||||
const (
|
||||
FlashParam = "flash"
|
||||
FlashKindParam = "flashKind"
|
||||
)
|
||||
|
||||
// FlashURL adds a flash message of kind (FlashOK, FlashError, FlashInfo)
|
||||
// to target's query, replacing one that is already there.
|
||||
func FlashURL(target, kind, msg string) string {
|
||||
u, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return target
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set(FlashParam, msg)
|
||||
q.Set(FlashKindParam, kind)
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// RedirectFlash answers a form POST with 303 See Other to target (a
|
||||
// path the handler has already made local, e.g. with httpsec.SafeNext),
|
||||
// carrying a flash message.
|
||||
func RedirectFlash(w http.ResponseWriter, r *http.Request, target, kind, msg string) {
|
||||
http.Redirect(w, r, FlashURL(target, kind, msg), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// ApplyFlash fills h.Flash and h.FlashKind from r's query. An unknown
|
||||
// kind is shown as an error, the way the base template renders it.
|
||||
func (h *PageHeader) ApplyFlash(r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
h.Flash = q.Get(FlashParam)
|
||||
if h.Flash == "" {
|
||||
h.FlashKind = ""
|
||||
return
|
||||
}
|
||||
switch kind := q.Get(FlashKindParam); kind {
|
||||
case FlashOK, FlashInfo:
|
||||
h.FlashKind = kind
|
||||
default:
|
||||
h.FlashKind = FlashError
|
||||
}
|
||||
}
|
||||
|
||||
// WithoutFlash removes the flash parameters from a (relative) URL, so a
|
||||
// link back to the current page -- e.g. AppearanceBack -- does not show
|
||||
// the message again.
|
||||
func WithoutFlash(target string) string {
|
||||
u, err := url.Parse(target)
|
||||
if err != nil || u.RawQuery == "" {
|
||||
return target
|
||||
}
|
||||
q := u.Query()
|
||||
if !q.Has(FlashParam) && !q.Has(FlashKindParam) {
|
||||
return target
|
||||
}
|
||||
q.Del(FlashParam)
|
||||
q.Del(FlashKindParam)
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFlashRoundTrip(t *testing.T) {
|
||||
u := FlashURL("/services?x=1", FlashOK, "service a started")
|
||||
var h PageHeader
|
||||
h.ApplyFlash(httptest.NewRequest("GET", u, nil))
|
||||
if h.Flash != "service a started" || h.FlashKind != FlashOK {
|
||||
t.Fatalf("ApplyFlash(%q) = %q/%q", u, h.Flash, h.FlashKind)
|
||||
}
|
||||
if got := WithoutFlash(u); got != "/services?x=1" {
|
||||
t.Errorf("WithoutFlash = %q", got)
|
||||
}
|
||||
if WithoutFlash("/a?b=c") != "/a?b=c" || WithoutFlash("/a") != "/a" {
|
||||
t.Error("WithoutFlash changed a URL without flash")
|
||||
}
|
||||
|
||||
h.ApplyFlash(httptest.NewRequest("GET", "/?flash=x&flashKind=bogus", nil))
|
||||
if h.FlashKind != FlashError {
|
||||
t.Errorf("unknown kind = %q", h.FlashKind)
|
||||
}
|
||||
h.ApplyFlash(httptest.NewRequest("GET", "/", nil))
|
||||
if h.Flash != "" || h.FlashKind != "" {
|
||||
t.Errorf("no flash = %q/%q", h.Flash, h.FlashKind)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectFlash(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
RedirectFlash(rec, httptest.NewRequest("POST", "/x", nil), "/ui/repos", FlashInfo, "nothing to do")
|
||||
if rec.Code != 303 || rec.Header().Get("Location") != "/ui/repos?flash=nothing+to+do&flashKind=info" {
|
||||
t.Fatalf("%d %q", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAppearanceDropsFlash(t *testing.T) {
|
||||
h := PageHeader{BasePath: "/ui"}
|
||||
h.ApplyAppearance(httptest.NewRequest("GET", "/ui/repos?flash=done&flashKind=ok&page=2", nil))
|
||||
if h.AppearanceBack != "/repos?page=2" {
|
||||
t.Fatalf("AppearanceBack = %q", h.AppearanceBack)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,10 @@
|
||||
module teruna.dev/yetano/yetano-webui-template
|
||||
|
||||
go 1.26.3
|
||||
|
||||
require yetano.dev/yetano/verse v0.10.0
|
||||
|
||||
require (
|
||||
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
|
||||
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
yetano.dev/yetano/verse v0.10.0 h1:NP7drY+nGW7R59CtDp30k0m+lvYj18GzyQ89oZ7LBVE=
|
||||
yetano.dev/yetano/verse v0.10.0/go.mod h1:TzVydtH9ljDTzhD98uufRW8V2OZECktqIcPxiaWH6p4=
|
||||
@@ -0,0 +1,216 @@
|
||||
// Package httpsec holds the HTTP hardening every Yetano/Yak/Yamase web
|
||||
// UI shares: security headers, the Host gate against DNS rebinding,
|
||||
// open-redirect-safe "next" targets and the cookie scope for a UI served
|
||||
// under a base path. It only builds on net/http; cross-origin protection
|
||||
// stays the standard library's http.CrossOriginProtection.
|
||||
package httpsec
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DefaultCSP allows the UI's own scripts, styles and images (plus data:
|
||||
// images, e.g. the template's favicon) and nothing else: no plugins, no
|
||||
// <base> rewriting, no framing, forms only to the UI itself.
|
||||
const DefaultCSP = "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
|
||||
|
||||
// HeaderOptions configures Headers. The zero value is the default set.
|
||||
type HeaderOptions struct {
|
||||
// CSP replaces DefaultCSP, e.g. for a UI that still needs inline
|
||||
// scripts or a WebSocket to another origin.
|
||||
CSP string
|
||||
// TLS adds Strict-Transport-Security. Set it only when the UI itself
|
||||
// serves HTTPS (or is only ever reached through an HTTPS proxy):
|
||||
// browsers remember it for a year.
|
||||
TLS bool
|
||||
// CacheablePrefixes are path prefixes (as the handler sees them) whose
|
||||
// responses may be cached, e.g. "/static/", "/webui-static/";
|
||||
// everything else gets Cache-Control: no-store, so pages with
|
||||
// session data never land in a shared or back-button cache.
|
||||
CacheablePrefixes []string
|
||||
}
|
||||
|
||||
// Headers sets the security headers on every response of next. Put it
|
||||
// outermost, so even a 421 from the Host gate or a 403 from cross-origin
|
||||
// protection carries them.
|
||||
func Headers(next http.Handler, opts HeaderOptions) http.Handler {
|
||||
csp := opts.CSP
|
||||
if csp == "" {
|
||||
csp = DefaultCSP
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Security-Policy", csp)
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
h.Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
if opts.TLS {
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000")
|
||||
}
|
||||
cacheable := false
|
||||
for _, p := range opts.CacheablePrefixes {
|
||||
if strings.HasPrefix(r.URL.Path, p) {
|
||||
cacheable = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !cacheable {
|
||||
h.Set("Cache-Control", "no-store")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// GateActive is the family's rule for when the Host gate runs: always
|
||||
// when the UI has no login (anyone who can make a browser send requests
|
||||
// to it could otherwise drive it through a rebound DNS name), and also
|
||||
// with a login once hosts are configured explicitly. A UI behind a
|
||||
// domain with a login keeps working without extra configuration.
|
||||
func GateActive(loginOn bool, allowed []string) bool {
|
||||
return !loginOn || len(allowed) > 0
|
||||
}
|
||||
|
||||
// HostAllowed reports whether a request's Host header names this UI: an
|
||||
// IP address, localhost or a *.localhost name, or one of allowed
|
||||
// (compared case-insensitively, a trailing dot ignored). A port is
|
||||
// ignored. An empty Host is rejected -- every browser sends one, so only
|
||||
// a hand-made request lacks it.
|
||||
func HostAllowed(host string, allowed []string) bool {
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
}
|
||||
host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".")
|
||||
if host == "" {
|
||||
return false
|
||||
}
|
||||
if net.ParseIP(host) != nil || host == "localhost" || strings.HasSuffix(host, ".localhost") {
|
||||
return true
|
||||
}
|
||||
for _, a := range allowed {
|
||||
if strings.TrimSuffix(strings.ToLower(a), ".") == host {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HostOf returns the host of a public URL (e.g. a configured external
|
||||
// address), for adding it to the allowed list; "" if there is none.
|
||||
func HostOf(publicURL string) string {
|
||||
u, err := url.Parse(publicURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return u.Hostname()
|
||||
}
|
||||
|
||||
// Gate answers 421 Misdirected Request for a Host HostAllowed rejects,
|
||||
// naming setting (the configuration key that lists allowed hosts, e.g.
|
||||
// "settings.webUI.allowedHosts") so the operator knows what to change.
|
||||
func Gate(next http.Handler, allowed []string, setting string) http.Handler {
|
||||
msg := "unknown host"
|
||||
if setting != "" {
|
||||
msg += " (see " + setting + ")"
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !HostAllowed(r.Host, allowed) {
|
||||
http.Error(w, msg, http.StatusMisdirectedRequest)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// SafeNext returns next if it is a local target inside the UI at
|
||||
// basePath ("" for a UI at the root) -- a path, optionally with query,
|
||||
// that cannot leave the host: no scheme, host or user, no "//" or "/\"
|
||||
// start, no backslash or control character -- and none of the
|
||||
// basePath-relative paths in exclude (e.g. "/login", "/logout", so a
|
||||
// login never returns to itself). Otherwise it returns basePath + "/".
|
||||
func SafeNext(next, basePath string, exclude ...string) string {
|
||||
fallback := basePath + "/"
|
||||
if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") {
|
||||
return fallback
|
||||
}
|
||||
for _, c := range next {
|
||||
if c < 0x20 || c == 0x7f || c == '\\' {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
u, err := url.Parse(next)
|
||||
if err != nil || u.Scheme != "" || u.Host != "" || u.User != nil || u.Opaque != "" {
|
||||
return fallback
|
||||
}
|
||||
rel := u.Path
|
||||
if basePath != "" {
|
||||
if rel != basePath && !strings.HasPrefix(rel, basePath+"/") {
|
||||
return fallback
|
||||
}
|
||||
rel = strings.TrimPrefix(rel, basePath)
|
||||
}
|
||||
for _, x := range exclude {
|
||||
if rel == x {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
// CookiePath is the Path for cookies of a UI at basePath: basePath + "/"
|
||||
// ("/" at the root), so two UIs on one host keep separate sessions and
|
||||
// "/app" never matches "/application". (A "__Host-" cookie needs Path
|
||||
// "/" and therefore a UI at the root.)
|
||||
func CookiePath(basePath string) string {
|
||||
return strings.TrimSuffix(basePath, "/") + "/"
|
||||
}
|
||||
|
||||
// SecureCookies reports whether cookies for r should carry Secure: when
|
||||
// the request came over TLS, or the UI's public URL is https (it then
|
||||
// sits behind a TLS-terminating proxy).
|
||||
func SecureCookies(r *http.Request, publicURL string) bool {
|
||||
return r.TLS != nil || strings.HasPrefix(strings.ToLower(publicURL), "https://")
|
||||
}
|
||||
|
||||
// BearerTokens lets a request through only when it carries
|
||||
// "Authorization: Bearer <token>" with one of tokens (compared in
|
||||
// constant time); others get 401. It is the access control of a UI
|
||||
// without user management of its own: a reverse proxy in front of it
|
||||
// (or yasta, for a UI shown over the YAPL bus) sets the header. Empty
|
||||
// tokens are ignored; with none left every request passes.
|
||||
func BearerTokens(next http.Handler, tokens []string) http.Handler {
|
||||
var keep [][]byte
|
||||
for _, t := range tokens {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
keep = append(keep, []byte(t))
|
||||
}
|
||||
}
|
||||
if len(keep) == 0 {
|
||||
return next
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if tokenAllowed(r.Header.Get("Authorization"), keep) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="web UI"`)
|
||||
http.Error(w, "missing or wrong bearer token", http.StatusUnauthorized)
|
||||
})
|
||||
}
|
||||
|
||||
func tokenAllowed(header string, tokens [][]byte) bool {
|
||||
scheme, got, ok := strings.Cut(header, " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return false
|
||||
}
|
||||
g := []byte(strings.TrimSpace(got))
|
||||
match := 0
|
||||
for _, t := range tokens {
|
||||
match |= subtle.ConstantTimeCompare(g, t)
|
||||
}
|
||||
return match == 1
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package httpsec
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var ok = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
|
||||
|
||||
func TestHeaders(t *testing.T) {
|
||||
h := Headers(ok, HeaderOptions{CacheablePrefixes: []string{"/static/"}})
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("GET", "/page", nil))
|
||||
for k, want := range map[string]string{
|
||||
"Content-Security-Policy": DefaultCSP,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Frame-Options": "DENY",
|
||||
"Referrer-Policy": "same-origin",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cache-Control": "no-store",
|
||||
"Strict-Transport-Security": "",
|
||||
} {
|
||||
if got := rec.Header().Get(k); got != want {
|
||||
t.Errorf("%s = %q, want %q", k, got, want)
|
||||
}
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("GET", "/static/app.css", nil))
|
||||
if got := rec.Header().Get("Cache-Control"); got != "" {
|
||||
t.Errorf("static Cache-Control = %q", got)
|
||||
}
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
Headers(ok, HeaderOptions{CSP: "default-src 'none'", TLS: true}).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
|
||||
if rec.Header().Get("Content-Security-Policy") != "default-src 'none'" || rec.Header().Get("Strict-Transport-Security") == "" {
|
||||
t.Errorf("options ignored: %v", rec.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateActive(t *testing.T) {
|
||||
if !GateActive(false, nil) || GateActive(true, nil) || !GateActive(true, []string{"a.example"}) {
|
||||
t.Fatal("GateActive rule")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostAllowed(t *testing.T) {
|
||||
allowed := []string{"Ops.Example.", "b.example"}
|
||||
for host, want := range map[string]bool{
|
||||
"": false,
|
||||
":8080": false,
|
||||
"127.0.0.1:8080": true,
|
||||
"[::1]:8080": true,
|
||||
"::1": true,
|
||||
"localhost": true,
|
||||
"LOCALHOST:1": true,
|
||||
"app.localhost": true,
|
||||
"ops.example": true,
|
||||
"ops.example.:443": true,
|
||||
"b.example": true,
|
||||
"evil.example": false,
|
||||
"localhost.evil.com": false,
|
||||
} {
|
||||
if got := HostAllowed(host, allowed); got != want {
|
||||
t.Errorf("HostAllowed(%q) = %v, want %v", host, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGate(t *testing.T) {
|
||||
g := Gate(ok, nil, "web.allowed_hosts")
|
||||
for host, code := range map[string]int{"localhost": 200, "evil.example": 421, "": 421} {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.Host = host
|
||||
rec := httptest.NewRecorder()
|
||||
g.ServeHTTP(rec, r)
|
||||
if rec.Code != code {
|
||||
t.Errorf("Host %q: %d, want %d", host, rec.Code, code)
|
||||
}
|
||||
if code == 421 && rec.Body.String() != "unknown host (see web.allowed_hosts)\n" {
|
||||
t.Errorf("body %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostOf(t *testing.T) {
|
||||
if HostOf("https://ops.example:8443/ui") != "ops.example" || HostOf("") != "" {
|
||||
t.Fatal("HostOf")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeNext(t *testing.T) {
|
||||
for _, tc := range []struct{ next, base, want string }{
|
||||
{"/services?x=1", "", "/services?x=1"},
|
||||
{"", "", "/"},
|
||||
{"services", "", "/"},
|
||||
{"//evil.example", "", "/"},
|
||||
{"/\\evil.example", "", "/"},
|
||||
{"/a\\b", "", "/"},
|
||||
{"/a\nb", "", "/"},
|
||||
{"/a\x7f", "", "/"},
|
||||
{"https://evil.example/", "", "/"},
|
||||
{"/login", "", "/"},
|
||||
{"/logout", "", "/"},
|
||||
{"/login/help", "", "/login/help"},
|
||||
{"/ui/repos", "/ui", "/ui/repos"},
|
||||
{"/ui", "/ui", "/ui"},
|
||||
{"/other", "/ui", "/ui/"},
|
||||
{"/uix", "/ui", "/ui/"},
|
||||
{"/ui/login", "/ui", "/ui/"},
|
||||
} {
|
||||
if got := SafeNext(tc.next, tc.base, "/login", "/logout"); got != tc.want {
|
||||
t.Errorf("SafeNext(%q, %q) = %q, want %q", tc.next, tc.base, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookiePath(t *testing.T) {
|
||||
if CookiePath("") != "/" || CookiePath("/ui") != "/ui/" || CookiePath("/ui/") != "/ui/" {
|
||||
t.Fatal("CookiePath")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecureCookies(t *testing.T) {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
if SecureCookies(r, "") || !SecureCookies(r, "HTTPS://ops.example") {
|
||||
t.Fatal("public URL")
|
||||
}
|
||||
r.TLS = &tls.ConnectionState{}
|
||||
if !SecureCookies(r, "") {
|
||||
t.Fatal("TLS")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokens(t *testing.T) {
|
||||
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
|
||||
h := BearerTokens(ok, []string{" one ", "", "two"})
|
||||
for auth, want := range map[string]int{
|
||||
"": 401, "Bearer one": 204, "bearer two": 204, "Bearer three": 401, "Basic one": 401, "Bearer": 401, "Bearer onex": 401,
|
||||
} {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
if auth != "" {
|
||||
r.Header.Set("Authorization", auth)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Errorf("%q: %d, want %d", auth, w.Code, want)
|
||||
}
|
||||
if want == 401 && w.Header().Get("WWW-Authenticate") == "" {
|
||||
t.Errorf("%q: no WWW-Authenticate", auth)
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
BearerTokens(ok, []string{" ", ""}).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
||||
if w.Code != 204 {
|
||||
t.Errorf("no tokens: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package layout
|
||||
|
||||
import "html/template"
|
||||
|
||||
// NavIcons are the sidebar icons NavItem.Icon can name: simple 24x24
|
||||
// stroke icons drawn for this module, colored by currentColor. A
|
||||
// consumer may add its own (an <svg> with the same attributes) at
|
||||
// program start, before the first page is rendered; the map is not
|
||||
// safe for writes while pages render.
|
||||
var NavIcons = map[string]template.HTML{
|
||||
"dashboard": icon(`<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>`),
|
||||
"home": icon(`<path d="M3 11 12 4l9 7"/><path d="M5 10v10h14V10"/><path d="M10 20v-6h4v6"/>`),
|
||||
"list": icon(`<path d="M9 6h12M9 12h12M9 18h12"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/>`),
|
||||
"settings": icon(`<path d="M4 6h10M18 6h2M4 12h4M12 12h8M4 18h12"/><circle cx="16" cy="6" r="2"/><circle cx="10" cy="12" r="2"/><circle cx="18" cy="18" r="2"/>`),
|
||||
"server": icon(`<rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><path d="M7 7.5h.01M7 16.5h.01"/>`),
|
||||
"database": icon(`<ellipse cx="12" cy="5.5" rx="8" ry="2.5"/><path d="M4 5.5v13c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-13"/><path d="M4 12c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5"/>`),
|
||||
"box": icon(`<path d="M3 7.5 12 3l9 4.5v9L12 21l-9-4.5z"/><path d="M3 7.5 12 12l9-4.5M12 12v9"/>`),
|
||||
"user": icon(`<circle cx="12" cy="8" r="4"/><path d="M4 21c1-4 4.5-6 8-6s7 2 8 6"/>`),
|
||||
"users": icon(`<circle cx="9" cy="8" r="3.5"/><path d="M2.5 20c.8-3.5 3.5-5.5 6.5-5.5s5.7 2 6.5 5.5"/><path d="M15.5 4.8a3.5 3.5 0 0 1 0 6.4M18 14.8c1.8.8 3 2.6 3.5 5.2"/>`),
|
||||
"key": icon(`<circle cx="8" cy="15" r="4"/><path d="m11 12 9-9M16 7l3 3M14 9l2 2"/>`),
|
||||
"shield": icon(`<path d="M12 3 4.5 6v6c0 4.5 3.2 7.8 7.5 9 4.3-1.2 7.5-4.5 7.5-9V6z"/><path d="m9 12 2 2 4-4"/>`),
|
||||
"activity": icon(`<path d="M3 12h4l3-8 4 16 3-8h4"/>`),
|
||||
"chart": icon(`<path d="M4 20V4"/><path d="M4 20h16"/><path d="M8 16v-5M12 16V8M16 16v-3"/>`),
|
||||
"terminal": icon(`<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3M13 15h4"/>`),
|
||||
"globe": icon(`<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.5 3.8 5.5 3.8 9s-1.3 6.5-3.8 9c-2.5-2.5-3.8-5.5-3.8-9S9.5 5.5 12 3z"/>`),
|
||||
"cloud": icon(`<path d="M7 19a4.5 4.5 0 0 1-.6-9A6 6 0 0 1 18 9.5a4.8 4.8 0 0 1-.5 9.5z"/>`),
|
||||
"file": icon(`<path d="M6 3h8l5 5v13H6z"/><path d="M14 3v5h5M9 13h7M9 17h7"/>`),
|
||||
"folder": icon(`<path d="M3 6.5A1.5 1.5 0 0 1 4.5 5H9l2 2.5h8.5A1.5 1.5 0 0 1 21 9v9.5a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18.5z"/>`),
|
||||
"bell": icon(`<path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z"/><path d="M10 21h4"/>`),
|
||||
"compass": icon(`<circle cx="12" cy="12" r="9"/><path d="m15.5 8.5-2 5-5 2 2-5z"/>`),
|
||||
"search": icon(`<circle cx="11" cy="11" r="6.5"/><path d="m16 16 4.5 4.5"/>`),
|
||||
"lock": icon(`<rect x="4.5" y="10.5" width="15" height="10" rx="2"/><path d="M8 10.5V7.5a4 4 0 0 1 8 0v3"/>`),
|
||||
"network": icon(`<rect x="9.5" y="3" width="5" height="5" rx="1"/><rect x="3" y="16" width="5" height="5" rx="1"/><rect x="16" y="16" width="5" height="5" rx="1"/><path d="M12 8v4M5.5 16v-4h13v4"/>`),
|
||||
"download": icon(`<path d="M12 4v11M7 10.5l5 5 5-5"/><path d="M4 19.5h16"/>`),
|
||||
"info": icon(`<circle cx="12" cy="12" r="9"/><path d="M12 11v5.5M12 7.5h.01"/>`),
|
||||
}
|
||||
|
||||
func icon(body string) template.HTML {
|
||||
return template.HTML(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">` + body + `</svg>`)
|
||||
}
|
||||
|
||||
func navIcon(name string) template.HTML {
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
return NavIcons[name]
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// Package layout provides the shared server-rendered web UI chrome (base
|
||||
// layout, navbar, sidebar, footer) used by every Yetano/Yak/Yamase
|
||||
// ops-tool admin dashboard: yasta, yasl, yaiam, yakwui, and yamase-web.
|
||||
// ops-tool admin dashboard: yasta, yasl, yaiam, yakwui, yamase-web, and
|
||||
// yamocir.
|
||||
//
|
||||
// Consumers embed PageHeader in their own per-page data struct and use
|
||||
// NewRenderer to parse the shared layout templates together with their
|
||||
@@ -28,11 +29,49 @@ var staticFS embed.FS
|
||||
// base/navbar/sidebar/footer templates.
|
||||
const LayoutGlob = "templates/layout/*.tmpl"
|
||||
|
||||
// Values for PageHeader.Theme, the color mode; see static/style.css.
|
||||
const (
|
||||
ThemeDark = "dark"
|
||||
ThemeLight = "light"
|
||||
ThemeSystem = "system"
|
||||
)
|
||||
|
||||
// NavItem is one sidebar entry.
|
||||
type NavItem struct {
|
||||
ID string // matches PageHeader.ActiveNav to mark this item active
|
||||
Label string
|
||||
Href string // BasePath-relative, e.g. "/tasks"
|
||||
// Group, when set, puts a small heading above the first item of a
|
||||
// run of items with the same Group ("Account", "Downloads", ...).
|
||||
Group string
|
||||
// Icon names one of NavIcons ("dashboard", "settings", ...); unknown
|
||||
// names render nothing. Only StyleModern shows icons, so setting it
|
||||
// leaves the classic look unchanged.
|
||||
Icon string
|
||||
}
|
||||
|
||||
// SidebarEntry is one NavItem as the sidebar template renders it.
|
||||
type SidebarEntry struct {
|
||||
NavItem
|
||||
Active bool
|
||||
GroupHead string // the group heading to render before this item, if any
|
||||
IconSVG template.HTML // NavIcons[Icon]
|
||||
}
|
||||
|
||||
// SidebarEntries resolves NavItems for the sidebar template: active
|
||||
// state, group headings (once per run of equal Group values) and icons.
|
||||
func (h PageHeader) SidebarEntries() []SidebarEntry {
|
||||
out := make([]SidebarEntry, len(h.NavItems))
|
||||
prev := ""
|
||||
for i, n := range h.NavItems {
|
||||
e := SidebarEntry{NavItem: n, Active: n.ID == h.ActiveNav, IconSVG: navIcon(n.Icon)}
|
||||
if n.Group != "" && n.Group != prev {
|
||||
e.GroupHead = n.Group
|
||||
}
|
||||
prev = n.Group
|
||||
out[i] = e
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// PageHeader holds the fields every page's own data struct should embed
|
||||
@@ -51,6 +90,30 @@ type PageHeader struct {
|
||||
// execution time, not at parse time.
|
||||
AppName string
|
||||
Lang string // <html lang="...">; "" defaults to "en"
|
||||
// Theme is the color mode, rendered as <html data-theme="...">:
|
||||
// ThemeDark, ThemeLight or ThemeSystem (follows
|
||||
// prefers-color-scheme). "" omits the attribute, which is dark, so a
|
||||
// consumer that never sets Theme keeps its look.
|
||||
Theme string
|
||||
// Palette is the color set, rendered as <html data-palette="...">:
|
||||
// PaletteDefault, PaletteGraphite or PaletteContrast; "" is
|
||||
// PaletteDefault. ApplyAppearance fills Theme and Palette from the
|
||||
// visitor's cookies (see README.md's Theming section).
|
||||
Palette string
|
||||
// Style is the shape of the chrome, rendered as <html
|
||||
// data-style="...">: StyleModern (also "") or StyleClassic.
|
||||
// ApplyAppearance fills it from the visitor's cookie.
|
||||
Style string
|
||||
// AppearancePath is the BasePath-relative POST route of
|
||||
// AppearanceHandler, e.g. "/appearance"; set, the navbar shows the
|
||||
// theme/palette menu. AppearanceBack is the BasePath-relative page
|
||||
// the menu returns to (ApplyAppearance sets it).
|
||||
AppearancePath string
|
||||
AppearanceBack string
|
||||
// AppearanceFormHTML is extra markup inside the menu's POST form,
|
||||
// e.g. a hidden CSRF token field for a consumer whose middleware
|
||||
// demands one on every POST.
|
||||
AppearanceFormHTML template.HTML
|
||||
Brand string // navbar brand text, e.g. "YASTA"
|
||||
BrandInitial string // single-letter favicon glyph, e.g. "y"
|
||||
Subtitle string
|
||||
@@ -58,9 +121,9 @@ type PageHeader struct {
|
||||
NavItems []NavItem
|
||||
ActiveNav string
|
||||
Flash string
|
||||
FlashKind string // "ok" or "error"; meaningless if Flash == ""
|
||||
FlashKind string // FlashOK, FlashError or FlashInfo (flash.go); meaningless if Flash == ""
|
||||
Username string
|
||||
LogoutPath string // BasePath-relative, e.g. "/logout"; "" hides the logout link
|
||||
LogoutPath string // BasePath-relative, e.g. "/logout"; rendered as a POST form (never a GET link); "" hides it
|
||||
NavbarBeforeBrand template.HTML // extra markup rendered before the brand link, e.g. a mobile sidebar toggle
|
||||
NavbarLeftExtra template.HTML // extra markup rendered after Subtitle in the navbar's left group
|
||||
NavbarRightExtra template.HTML // extra markup rendered after Username/Logout in the navbar's right group
|
||||
|
||||
+53
-2
@@ -47,7 +47,7 @@ func TestNewRendererAndPage(t *testing.T) {
|
||||
`class="nav-link active"`,
|
||||
"test-build",
|
||||
"<title>Dashboard · example</title>",
|
||||
`<html lang="en">`,
|
||||
`<html lang="en" data-style="modern">`,
|
||||
"<body>",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
@@ -75,7 +75,7 @@ func TestPageHeaderOverrides(t *testing.T) {
|
||||
out := buf.String()
|
||||
|
||||
for _, want := range []string{
|
||||
`<html lang="de">`,
|
||||
`<html lang="de" data-style="modern">`,
|
||||
`<body x-data="{ open: true }">`,
|
||||
`sidebar d-md-block" :class="{ hidden: !open }">`,
|
||||
} {
|
||||
@@ -85,6 +85,35 @@ func TestPageHeaderOverrides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestThemeAttribute(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
theme string
|
||||
want string
|
||||
}{
|
||||
{"unset resolves to the bare :root theme", "", `<html lang="en" data-style="modern">`},
|
||||
{"explicit dark", ThemeDark, `<html lang="en" data-theme="dark" data-style="modern">`},
|
||||
{"light", ThemeLight, `<html lang="en" data-theme="light" data-style="modern">`},
|
||||
{"system", ThemeSystem, `<html lang="en" data-theme="system" data-style="modern">`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := r.Page(&buf, "dashboard", PageHeader{Title: "Dashboard", Theme: c.theme}); err != nil {
|
||||
t.Fatalf("Page: %v", err)
|
||||
}
|
||||
if out := buf.String(); !strings.Contains(out, c.want) {
|
||||
t.Errorf("rendered output missing %q\n---\n%s", c.want, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteNamed(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
@@ -109,3 +138,25 @@ func TestPageUnknown(t *testing.T) {
|
||||
t.Fatal("expected error for unknown page")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutIsPostForm pins the navbar's logout control to a POST form:
|
||||
// a GET link would let any foreign page (an <img>, a link prefetcher)
|
||||
// log the user out.
|
||||
func TestLogoutIsPostForm(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
data := PageHeader{Title: "Dashboard", BasePath: "/ui", Username: "alice", LogoutPath: "/logout"}
|
||||
if err := r.Page(&buf, "dashboard", data); err != nil {
|
||||
t.Fatalf("Page: %v", err)
|
||||
}
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, `<form method="post" action="/ui/logout"`) {
|
||||
t.Errorf("logout is not a POST form\n---\n%s", out)
|
||||
}
|
||||
if strings.Contains(out, `href="/ui/logout"`) {
|
||||
t.Errorf("logout still rendered as a GET link\n---\n%s", out)
|
||||
}
|
||||
}
|
||||
+837
-40
@@ -1,44 +1,394 @@
|
||||
/* Shared web UI chrome -- the dark-theme base layout, navbar, sidebar, and
|
||||
footer used by every ops-tool dashboard built on this module (yasta,
|
||||
yasl, yaiam, yakwui, yamase-web, yamocir). Loaded after
|
||||
bootstrap.min.css. Page-content styling (cards, tables, badges,
|
||||
forms, ...) is each project's own concern and lives in that project's
|
||||
own stylesheet, loaded alongside this one -- see
|
||||
PageHeader.ExtraHeadHTML. Fixed dark theme only -- no
|
||||
prefers-color-scheme, no light mode (see README.md's Theming section
|
||||
before assuming that's a gap to fill here).
|
||||
/* Shared web UI chrome -- the base layout, navbar, sidebar, and footer
|
||||
used by every ops-tool dashboard built on this module (yasta, yasl,
|
||||
yaiam, yakwui, yamase-web, yamocir). Loaded after bootstrap.min.css.
|
||||
Page-content styling (cards, tables, badges, forms, ...) is each
|
||||
project's own concern and lives in that project's own stylesheet,
|
||||
loaded alongside this one -- see PageHeader.ExtraHeadHTML.
|
||||
|
||||
The palette below is exposed as --yw-* custom properties, not just
|
||||
baked into each rule -- it's the shared "theme" every migrated
|
||||
project inherits, not an implementation detail. A project needing a
|
||||
genuinely different look (not just a different accent) should not
|
||||
redefine these globally -- see README.md. */
|
||||
Theming has two independent axes, both set on <html> (see layout.go):
|
||||
|
||||
- data-theme (PageHeader.Theme): the mode -- "dark", "light" or
|
||||
"system" (follows the browser's prefers-color-scheme). Unset is
|
||||
dark, the look every consumer had before themes existed. The mode
|
||||
only sets color-scheme and the --yw-if-* switches below.
|
||||
- data-palette (PageHeader.Palette): the colors -- "default",
|
||||
"graphite", "contrast" or "slate". Unset is "default".
|
||||
- data-style (PageHeader.Style): the shape -- "modern" (the
|
||||
default; the template always sets the attribute) or "classic".
|
||||
The rules without a data-style selector are the classic look;
|
||||
the modern section at the end of this file overrides them.
|
||||
|
||||
Every color token is written once, as light-dark(<light>, <dark>), so
|
||||
a palette is one block and no mode duplicates another's values. The
|
||||
palette is exposed as --yw-* custom properties and bridged into
|
||||
Bootstrap's own --bs-* variables further down, so Bootstrap's
|
||||
components (tables, forms, links, ...) follow the theme too. See
|
||||
README.md's Theming section. */
|
||||
|
||||
/* --- Mode --------------------------------------------------------- */
|
||||
|
||||
/* --yw-if-light/--yw-if-dark pick between two values where
|
||||
light-dark() can't: it only takes colors, not the r, g, b triplets
|
||||
Bootstrap builds rgba() from or url() images. The active mode's
|
||||
switch is "initial" (guaranteed-invalid), so var(--yw-if-dark, X)
|
||||
falls back to X; the other one is empty, so its var() adds nothing:
|
||||
--x: var(--yw-if-light, <light>) var(--yw-if-dark, <dark>); */
|
||||
:root {
|
||||
--yw-bg: #1a1d23;
|
||||
--yw-text: #d4d8e0;
|
||||
--yw-border: #333;
|
||||
--yw-chrome-bg: #14171e;
|
||||
--yw-chrome-border: #272d3a;
|
||||
--yw-accent: #4fc3f7;
|
||||
--yw-accent-rgb: 79, 195, 247;
|
||||
--yw-nav-link: #0b82b8;
|
||||
--yw-nav-link-hover-text: #c8d4e4;
|
||||
--yw-subtitle: #5a7a9a;
|
||||
--yw-subtitle-sep: #333c4a;
|
||||
--yw-footer-text: #4a5a72;
|
||||
--yw-success-bg: #192e22;
|
||||
--yw-success-border: #2a5c3a;
|
||||
--yw-success-text: #7ecf98;
|
||||
--yw-danger-bg: #2e1820;
|
||||
--yw-danger-border: #5c2a32;
|
||||
--yw-danger-text: #e08090;
|
||||
|
||||
--bs-body-bg: var(--yw-bg);
|
||||
--bs-body-color: var(--yw-text);
|
||||
--bs-border-color: var(--yw-border);
|
||||
color-scheme: dark;
|
||||
--yw-if-dark: initial;
|
||||
--yw-if-light: ;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
color-scheme: light;
|
||||
--yw-if-dark: ;
|
||||
--yw-if-light: initial;
|
||||
}
|
||||
|
||||
:root[data-theme="system"] {
|
||||
color-scheme: light dark;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root[data-theme="system"] {
|
||||
--yw-if-dark: ;
|
||||
--yw-if-light: initial;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Palettes ----------------------------------------------------- */
|
||||
|
||||
/* default: the original Yetano look. Also the base every other palette
|
||||
starts from -- a palette block only lists what it changes. Each
|
||||
*-rgb triplet repeats its color for Bootstrap's rgba(var(...), a);
|
||||
TestPaletteTripletsMatch keeps the two in step. --yw-nav-link stays
|
||||
#0b82b8 in both modes (a cross-project design token, see the
|
||||
meta-repo AGENTS.md). */
|
||||
:root {
|
||||
--yw-bg: light-dark(#f4f6f9, #1a1d23);
|
||||
--yw-bg-rgb: var(--yw-if-light, 244, 246, 249) var(--yw-if-dark, 26, 29, 35);
|
||||
--yw-surface: light-dark(#ffffff, #20242c);
|
||||
--yw-surface-rgb: var(--yw-if-light, 255, 255, 255) var(--yw-if-dark, 32, 36, 44);
|
||||
--yw-surface-2: light-dark(#e9edf2, #272c35);
|
||||
--yw-surface-2-rgb: var(--yw-if-light, 233, 237, 242) var(--yw-if-dark, 39, 44, 53);
|
||||
--yw-text: light-dark(#1f2530, #d4d8e0);
|
||||
--yw-text-rgb: var(--yw-if-light, 31, 37, 48) var(--yw-if-dark, 212, 216, 224);
|
||||
--yw-text-strong: light-dark(#000000, #f1f3f6);
|
||||
--yw-text-strong-rgb: var(--yw-if-light, 0, 0, 0) var(--yw-if-dark, 241, 243, 246);
|
||||
--yw-muted: light-dark(#5a6678, #8a94a6);
|
||||
--yw-border: light-dark(#d3d9e2, #333333);
|
||||
--yw-chrome-bg: light-dark(#ffffff, #14171e);
|
||||
--yw-chrome-border: light-dark(#dde2ea, #272d3a);
|
||||
--yw-brand: light-dark(#0a72a3, #4fc3f7);
|
||||
--yw-accent: light-dark(#0a72a3, #4fc3f7);
|
||||
--yw-accent-rgb: var(--yw-if-light, 10, 114, 163) var(--yw-if-dark, 79, 195, 247);
|
||||
--yw-link: light-dark(#0a72a3, #4fc3f7);
|
||||
--yw-link-rgb: var(--yw-if-light, 10, 114, 163) var(--yw-if-dark, 79, 195, 247);
|
||||
--yw-link-hover: light-dark(#085a80, #81d4fa);
|
||||
--yw-link-hover-rgb: var(--yw-if-light, 8, 90, 128) var(--yw-if-dark, 129, 212, 250);
|
||||
--yw-primary: light-dark(#2595c8, #2595c8);
|
||||
--yw-primary-rgb: var(--yw-if-light, 37, 149, 200) var(--yw-if-dark, 37, 149, 200);
|
||||
--yw-on-primary: light-dark(#ffffff, #ffffff);
|
||||
--yw-nav-link: light-dark(#0b82b8, #0b82b8);
|
||||
--yw-nav-link-hover-text: light-dark(#0a4f72, #c8d4e4);
|
||||
--yw-subtitle: light-dark(#5a7088, #5a7a9a);
|
||||
--yw-subtitle-sep: light-dark(#c3cad5, #333c4a);
|
||||
--yw-footer-text: light-dark(#6a7a90, #4a5a72);
|
||||
--yw-success-bg: light-dark(#e5f4ea, #192e22);
|
||||
--yw-success-border: light-dark(#a6d4b4, #2a5c3a);
|
||||
--yw-success-text: light-dark(#1c5e33, #7ecf98);
|
||||
--yw-danger-bg: light-dark(#fbe9ec, #2e1820);
|
||||
--yw-danger-border: light-dark(#e6b0b8, #5c2a32);
|
||||
--yw-danger-text: light-dark(#9b2335, #e08090);
|
||||
--yw-warning-bg: light-dark(#fff4dc, #2e2716);
|
||||
--yw-warning-border: light-dark(#f0d08a, #5c4a1f);
|
||||
--yw-warning-text: light-dark(#7a5300, #e8c76a);
|
||||
--yw-info-bg: light-dark(#e3f3fb, #15283a);
|
||||
--yw-info-border: light-dark(#a8d8ef, #24506b);
|
||||
--yw-info-text: light-dark(#0b5a80, #7fc8ec);
|
||||
}
|
||||
|
||||
/* graphite: grey and violet, after nessajina.tv -- near-black graphite
|
||||
(#1a1a1a), violet accent (#aa88ff), deep violet (#463a59), and the
|
||||
brand in the logo's brushed silver. */
|
||||
:root[data-palette="graphite"] {
|
||||
--yw-bg: light-dark(#f3f2f5, #1a1a1a);
|
||||
--yw-bg-rgb: var(--yw-if-light, 243, 242, 245) var(--yw-if-dark, 26, 26, 26);
|
||||
--yw-surface: light-dark(#ffffff, #222222);
|
||||
--yw-surface-rgb: var(--yw-if-light, 255, 255, 255) var(--yw-if-dark, 34, 34, 34);
|
||||
--yw-surface-2: light-dark(#ebe9ef, #2a2a2a);
|
||||
--yw-surface-2-rgb: var(--yw-if-light, 235, 233, 239) var(--yw-if-dark, 42, 42, 42);
|
||||
--yw-text: light-dark(#232029, #e2e0e8);
|
||||
--yw-text-rgb: var(--yw-if-light, 35, 32, 41) var(--yw-if-dark, 226, 224, 232);
|
||||
--yw-text-strong: light-dark(#000000, #ffffff);
|
||||
--yw-text-strong-rgb: var(--yw-if-light, 0, 0, 0) var(--yw-if-dark, 255, 255, 255);
|
||||
--yw-muted: light-dark(#6b6675, #888888);
|
||||
--yw-border: light-dark(#d6d2dd, #3a3a40);
|
||||
--yw-chrome-bg: light-dark(#fbfafc, #141414);
|
||||
--yw-chrome-border: light-dark(#e0dce6, #2a2a2a);
|
||||
--yw-brand: light-dark(#463a59, #cfcfd8);
|
||||
--yw-accent: light-dark(#6c4bc4, #aa88ff);
|
||||
--yw-accent-rgb: var(--yw-if-light, 108, 75, 196) var(--yw-if-dark, 170, 136, 255);
|
||||
--yw-link: light-dark(#6c4bc4, #aa88ff);
|
||||
--yw-link-rgb: var(--yw-if-light, 108, 75, 196) var(--yw-if-dark, 170, 136, 255);
|
||||
--yw-link-hover: light-dark(#523599, #c4adff);
|
||||
--yw-link-hover-rgb: var(--yw-if-light, 82, 53, 153) var(--yw-if-dark, 196, 173, 255);
|
||||
--yw-primary: light-dark(#6c4bc4, #7c5ce0);
|
||||
--yw-primary-rgb: var(--yw-if-light, 108, 75, 196) var(--yw-if-dark, 124, 92, 224);
|
||||
--yw-nav-link: light-dark(#7a5fd0, #9a82d6);
|
||||
--yw-nav-link-hover-text: light-dark(#463a59, #d8ccff);
|
||||
--yw-subtitle: light-dark(#6b6675, #8a8494);
|
||||
--yw-subtitle-sep: light-dark(#cfcad6, #3a3a40);
|
||||
--yw-footer-text: light-dark(#7a7584, #6a6670);
|
||||
--yw-info-bg: light-dark(#efe9fb, #241e33);
|
||||
--yw-info-border: light-dark(#cbbcef, #463a59);
|
||||
--yw-info-text: light-dark(#463a59, #c4adff);
|
||||
}
|
||||
|
||||
/* contrast: high contrast for readability -- black/white, a bright
|
||||
cyan accent in dark mode, deep blue in light. Not the classic yellow:
|
||||
in these dashboards yellow means "warning", and an accent in that
|
||||
color reads as a status. */
|
||||
:root[data-palette="contrast"] {
|
||||
--yw-bg: light-dark(#ffffff, #000000);
|
||||
--yw-bg-rgb: var(--yw-if-light, 255, 255, 255) var(--yw-if-dark, 0, 0, 0);
|
||||
--yw-surface: light-dark(#ffffff, #0a0a0a);
|
||||
--yw-surface-rgb: var(--yw-if-light, 255, 255, 255) var(--yw-if-dark, 10, 10, 10);
|
||||
--yw-surface-2: light-dark(#f0f0f0, #161616);
|
||||
--yw-surface-2-rgb: var(--yw-if-light, 240, 240, 240) var(--yw-if-dark, 22, 22, 22);
|
||||
--yw-text: light-dark(#000000, #ffffff);
|
||||
--yw-text-rgb: var(--yw-if-light, 0, 0, 0) var(--yw-if-dark, 255, 255, 255);
|
||||
--yw-text-strong: light-dark(#000000, #ffffff);
|
||||
--yw-text-strong-rgb: var(--yw-if-light, 0, 0, 0) var(--yw-if-dark, 255, 255, 255);
|
||||
--yw-muted: light-dark(#333333, #d0d0d0);
|
||||
--yw-border: light-dark(#555555, #8a8a8a);
|
||||
--yw-chrome-bg: light-dark(#ffffff, #000000);
|
||||
--yw-chrome-border: light-dark(#555555, #8a8a8a);
|
||||
--yw-brand: light-dark(#0040a0, #66e0ff);
|
||||
--yw-accent: light-dark(#0040a0, #66e0ff);
|
||||
--yw-accent-rgb: var(--yw-if-light, 0, 64, 160) var(--yw-if-dark, 102, 224, 255);
|
||||
--yw-link: light-dark(#0040a0, #66e0ff);
|
||||
--yw-link-rgb: var(--yw-if-light, 0, 64, 160) var(--yw-if-dark, 102, 224, 255);
|
||||
--yw-link-hover: light-dark(#002a6b, #b3f0ff);
|
||||
--yw-link-hover-rgb: var(--yw-if-light, 0, 42, 107) var(--yw-if-dark, 179, 240, 255);
|
||||
--yw-primary: light-dark(#0040a0, #66e0ff);
|
||||
--yw-primary-rgb: var(--yw-if-light, 0, 64, 160) var(--yw-if-dark, 102, 224, 255);
|
||||
--yw-on-primary: light-dark(#ffffff, #000000);
|
||||
--yw-nav-link: light-dark(#00549e, #a8e6ff);
|
||||
--yw-nav-link-hover-text: light-dark(#000000, #ffffff);
|
||||
--yw-subtitle: light-dark(#333333, #d0d0d0);
|
||||
--yw-subtitle-sep: light-dark(#888888, #8a8a8a);
|
||||
--yw-footer-text: light-dark(#333333, #d0d0d0);
|
||||
--yw-success-text: light-dark(#0a4d1f, #8ff0a8);
|
||||
--yw-danger-text: light-dark(#7a0010, #ffa0ae);
|
||||
--yw-warning-text: light-dark(#5a3d00, #ffe08a);
|
||||
--yw-info-text: light-dark(#003f5c, #a0dcff);
|
||||
}
|
||||
|
||||
/* slate: dark slate blue-grey with a soft lavender accent, made to go
|
||||
with data-style="modern" (but works with either style). The primary
|
||||
is light enough in dark mode that buttons carry dark text. */
|
||||
:root[data-palette="slate"] {
|
||||
--yw-bg: light-dark(#f5f5fa, #11131a);
|
||||
--yw-bg-rgb: var(--yw-if-light, 245, 245, 250) var(--yw-if-dark, 17, 19, 26);
|
||||
--yw-surface: light-dark(#ffffff, #1a1d27);
|
||||
--yw-surface-rgb: var(--yw-if-light, 255, 255, 255) var(--yw-if-dark, 26, 29, 39);
|
||||
--yw-surface-2: light-dark(#ececf4, #222634);
|
||||
--yw-surface-2-rgb: var(--yw-if-light, 236, 236, 244) var(--yw-if-dark, 34, 38, 52);
|
||||
--yw-text: light-dark(#23242e, #d5d8e2);
|
||||
--yw-text-rgb: var(--yw-if-light, 35, 36, 46) var(--yw-if-dark, 213, 216, 226);
|
||||
--yw-text-strong: light-dark(#0d0e14, #f4f5f9);
|
||||
--yw-text-strong-rgb: var(--yw-if-light, 13, 14, 20) var(--yw-if-dark, 244, 245, 249);
|
||||
--yw-muted: light-dark(#626679, #9095a8);
|
||||
--yw-border: light-dark(#d9dae6, #2e3345);
|
||||
--yw-chrome-bg: light-dark(#f5f5fa, #11131a);
|
||||
--yw-chrome-border: light-dark(#e2e3ec, #262a39);
|
||||
--yw-brand: light-dark(#1d1b2e, #f4f5f9);
|
||||
--yw-accent: light-dark(#5b45c9, #b4a2ff);
|
||||
--yw-accent-rgb: var(--yw-if-light, 91, 69, 201) var(--yw-if-dark, 180, 162, 255);
|
||||
--yw-link: light-dark(#5b45c9, #b4a2ff);
|
||||
--yw-link-rgb: var(--yw-if-light, 91, 69, 201) var(--yw-if-dark, 180, 162, 255);
|
||||
--yw-link-hover: light-dark(#4632a8, #cfc3ff);
|
||||
--yw-link-hover-rgb: var(--yw-if-light, 70, 50, 168) var(--yw-if-dark, 207, 195, 255);
|
||||
--yw-primary: light-dark(#5b45c9, #b9a8ff);
|
||||
--yw-primary-rgb: var(--yw-if-light, 91, 69, 201) var(--yw-if-dark, 185, 168, 255);
|
||||
--yw-on-primary: light-dark(#ffffff, #19142e);
|
||||
--yw-nav-link: light-dark(#3a3d4d, #c3c6d3);
|
||||
--yw-nav-link-hover-text: light-dark(#1d1b2e, #ffffff);
|
||||
--yw-subtitle: light-dark(#626679, #9095a8);
|
||||
--yw-subtitle-sep: light-dark(#cfd0dc, #2e3345);
|
||||
--yw-footer-text: light-dark(#7a7e90, #646a7e);
|
||||
--yw-info-bg: light-dark(#eeebfb, #1f1c33);
|
||||
--yw-info-border: light-dark(#cdc4f1, #3d3566);
|
||||
--yw-info-text: light-dark(#463399, #cfc3ff);
|
||||
}
|
||||
|
||||
/* --- Bootstrap bridge --------------------------------------------- */
|
||||
|
||||
/* Bootstrap's theme-dependent variables, taken from the palette. This
|
||||
replaces Bootstrap's own data-bs-theme switch, which has no "follow
|
||||
the system" mode without a script. Same selector weight as
|
||||
Bootstrap's own :root block and loaded after it, so these win. */
|
||||
:root {
|
||||
--bs-body-bg: var(--yw-bg);
|
||||
--bs-body-bg-rgb: var(--yw-bg-rgb);
|
||||
--bs-body-color: var(--yw-text);
|
||||
--bs-body-color-rgb: var(--yw-text-rgb);
|
||||
--bs-emphasis-color: var(--yw-text-strong);
|
||||
--bs-emphasis-color-rgb: var(--yw-text-strong-rgb);
|
||||
--bs-secondary-color: color-mix(in srgb, var(--yw-text) 75%, transparent);
|
||||
--bs-secondary-color-rgb: var(--yw-text-rgb);
|
||||
--bs-secondary-bg: var(--yw-surface-2);
|
||||
--bs-secondary-bg-rgb: var(--yw-surface-2-rgb);
|
||||
--bs-tertiary-color: color-mix(in srgb, var(--yw-text) 50%, transparent);
|
||||
--bs-tertiary-color-rgb: var(--yw-text-rgb);
|
||||
--bs-tertiary-bg: var(--yw-surface);
|
||||
--bs-tertiary-bg-rgb: var(--yw-surface-rgb);
|
||||
--bs-heading-color: inherit;
|
||||
--bs-link-color: var(--yw-link);
|
||||
--bs-link-color-rgb: var(--yw-link-rgb);
|
||||
--bs-link-hover-color: var(--yw-link-hover);
|
||||
--bs-link-hover-color-rgb: var(--yw-link-hover-rgb);
|
||||
--bs-border-color: var(--yw-border);
|
||||
--bs-border-color-translucent: color-mix(in srgb, var(--yw-text) 15%, transparent);
|
||||
--bs-focus-ring-color: color-mix(in srgb, var(--yw-accent) 25%, transparent);
|
||||
--bs-code-color: light-dark(#d63384, #e685b5);
|
||||
--bs-highlight-color: var(--yw-text);
|
||||
--bs-highlight-bg: var(--yw-warning-bg);
|
||||
|
||||
--bs-primary: var(--yw-primary);
|
||||
--bs-primary-rgb: var(--yw-primary-rgb);
|
||||
--bs-primary-text-emphasis: var(--yw-accent);
|
||||
--bs-primary-bg-subtle: color-mix(in srgb, var(--yw-accent) 15%, var(--yw-bg));
|
||||
--bs-primary-border-subtle: color-mix(in srgb, var(--yw-accent) 45%, var(--yw-bg));
|
||||
--bs-secondary-text-emphasis: var(--yw-muted);
|
||||
--bs-secondary-bg-subtle: var(--yw-surface-2);
|
||||
--bs-secondary-border-subtle: var(--yw-border);
|
||||
--bs-success-text-emphasis: var(--yw-success-text);
|
||||
--bs-success-bg-subtle: var(--yw-success-bg);
|
||||
--bs-success-border-subtle: var(--yw-success-border);
|
||||
--bs-danger-text-emphasis: var(--yw-danger-text);
|
||||
--bs-danger-bg-subtle: var(--yw-danger-bg);
|
||||
--bs-danger-border-subtle: var(--yw-danger-border);
|
||||
--bs-warning-text-emphasis: var(--yw-warning-text);
|
||||
--bs-warning-bg-subtle: var(--yw-warning-bg);
|
||||
--bs-warning-border-subtle: var(--yw-warning-border);
|
||||
--bs-info-text-emphasis: var(--yw-info-text);
|
||||
--bs-info-bg-subtle: var(--yw-info-bg);
|
||||
--bs-info-border-subtle: var(--yw-info-border);
|
||||
--bs-light-text-emphasis: light-dark(#495057, #f8f9fa);
|
||||
--bs-light-bg-subtle: light-dark(#fcfcfd, #343a40);
|
||||
--bs-light-border-subtle: light-dark(#e9ecef, #495057);
|
||||
--bs-dark-text-emphasis: light-dark(#495057, #dee2e6);
|
||||
--bs-dark-bg-subtle: light-dark(#ced4da, #1a1d20);
|
||||
--bs-dark-border-subtle: light-dark(#adb5bd, #343a40);
|
||||
|
||||
--bs-form-valid-color: var(--yw-success-text);
|
||||
--bs-form-valid-border-color: var(--yw-success-text);
|
||||
--bs-form-invalid-color: var(--yw-danger-text);
|
||||
--bs-form-invalid-border-color: var(--yw-danger-text);
|
||||
}
|
||||
|
||||
/* Bootstrap writes its primary blue straight into these components
|
||||
rather than reading --bs-primary, so they get the palette's here.
|
||||
The default palette's #2595c8 is the button color every consumer's
|
||||
own stylesheet used (as yasta), so those rules can go. */
|
||||
.btn-primary {
|
||||
--bs-btn-color: var(--yw-on-primary);
|
||||
--bs-btn-bg: var(--yw-primary);
|
||||
--bs-btn-border-color: var(--yw-primary);
|
||||
--bs-btn-hover-color: var(--yw-on-primary);
|
||||
--bs-btn-hover-bg: color-mix(in srgb, var(--yw-primary) 85%, #000000);
|
||||
--bs-btn-hover-border-color: color-mix(in srgb, var(--yw-primary) 80%, #000000);
|
||||
--bs-btn-focus-shadow-rgb: var(--yw-primary-rgb);
|
||||
--bs-btn-active-color: var(--yw-on-primary);
|
||||
--bs-btn-active-bg: color-mix(in srgb, var(--yw-primary) 80%, #000000);
|
||||
--bs-btn-active-border-color: color-mix(in srgb, var(--yw-primary) 75%, #000000);
|
||||
--bs-btn-disabled-color: var(--yw-on-primary);
|
||||
--bs-btn-disabled-bg: var(--yw-primary);
|
||||
--bs-btn-disabled-border-color: var(--yw-primary);
|
||||
}
|
||||
|
||||
.btn-outline-primary {
|
||||
--bs-btn-color: var(--yw-primary);
|
||||
--bs-btn-border-color: var(--yw-primary);
|
||||
--bs-btn-hover-color: var(--yw-on-primary);
|
||||
--bs-btn-hover-bg: var(--yw-primary);
|
||||
--bs-btn-hover-border-color: var(--yw-primary);
|
||||
--bs-btn-focus-shadow-rgb: var(--yw-primary-rgb);
|
||||
--bs-btn-active-color: var(--yw-on-primary);
|
||||
--bs-btn-active-bg: var(--yw-primary);
|
||||
--bs-btn-active-border-color: var(--yw-primary);
|
||||
--bs-btn-disabled-color: var(--yw-primary);
|
||||
--bs-btn-disabled-border-color: var(--yw-primary);
|
||||
}
|
||||
|
||||
.list-group {
|
||||
--bs-list-group-active-color: var(--yw-on-primary);
|
||||
--bs-list-group-active-bg: var(--yw-primary);
|
||||
--bs-list-group-active-border-color: var(--yw-primary);
|
||||
}
|
||||
|
||||
.nav-pills {
|
||||
--bs-nav-pills-link-active-color: var(--yw-on-primary);
|
||||
--bs-nav-pills-link-active-bg: var(--yw-primary);
|
||||
}
|
||||
|
||||
.dropdown-menu {
|
||||
--bs-dropdown-link-active-color: var(--yw-on-primary);
|
||||
--bs-dropdown-link-active-bg: var(--yw-primary);
|
||||
}
|
||||
|
||||
.pagination {
|
||||
--bs-pagination-focus-box-shadow: 0 0 0 .25rem color-mix(in srgb, var(--yw-primary) 25%, transparent);
|
||||
--bs-pagination-active-color: var(--yw-on-primary);
|
||||
--bs-pagination-active-bg: var(--yw-primary);
|
||||
--bs-pagination-active-border-color: var(--yw-primary);
|
||||
}
|
||||
|
||||
.progress,
|
||||
.progress-stacked {
|
||||
--bs-progress-bar-color: var(--yw-on-primary);
|
||||
--bs-progress-bar-bg: var(--yw-primary);
|
||||
}
|
||||
|
||||
.form-check-input:checked {
|
||||
background-color: var(--yw-primary);
|
||||
border-color: var(--yw-primary);
|
||||
}
|
||||
|
||||
.form-control:focus,
|
||||
.form-select:focus,
|
||||
.form-check-input:focus {
|
||||
border-color: color-mix(in srgb, var(--yw-primary) 50%, var(--yw-bg));
|
||||
box-shadow: 0 0 0 .25rem color-mix(in srgb, var(--yw-primary) 25%, transparent);
|
||||
}
|
||||
|
||||
.form-range::-webkit-slider-thumb { background-color: var(--yw-primary); }
|
||||
.form-range::-moz-range-thumb { background-color: var(--yw-primary); }
|
||||
|
||||
/* The images Bootstrap swaps under data-bs-theme="dark": they carry a
|
||||
fixed color, so each needs both versions. */
|
||||
.form-select {
|
||||
--bs-form-select-bg-img: var(--yw-if-light, url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e")) var(--yw-if-dark, url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23dee2e6' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e"));
|
||||
}
|
||||
|
||||
.form-switch .form-check-input:not(:checked):not(:focus) {
|
||||
--bs-form-switch-bg: var(--yw-if-light, url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e")) var(--yw-if-dark, url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%28255, 255, 255, 0.25%29'/%3e%3c/svg%3e"));
|
||||
}
|
||||
|
||||
.navbar-toggler-icon {
|
||||
--bs-navbar-toggler-icon-bg: var(--yw-if-light, url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%2833, 37, 41, 0.75%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")) var(--yw-if-dark, url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e"));
|
||||
}
|
||||
|
||||
/* Light has no filter: the empty value leaves filter at its initial
|
||||
"none". */
|
||||
.btn-close {
|
||||
filter: var(--yw-if-dark, var(--bs-btn-close-white-filter));
|
||||
}
|
||||
|
||||
/* --- Page ---------------------------------------------------------- */
|
||||
|
||||
html {
|
||||
height: 100%;
|
||||
}
|
||||
@@ -77,14 +427,22 @@ body > .container-fluid > .row {
|
||||
}
|
||||
|
||||
/* --- Navbar ------------------------------------------------ */
|
||||
/* Bootstrap's own navbar colors come from the palette (the navbar has
|
||||
no .navbar-dark, which would pin them to white). */
|
||||
.navbar {
|
||||
--bs-navbar-color: var(--yw-subtitle);
|
||||
--bs-navbar-hover-color: var(--yw-accent);
|
||||
--bs-navbar-active-color: var(--yw-accent);
|
||||
--bs-navbar-brand-color: var(--yw-brand);
|
||||
--bs-navbar-brand-hover-color: var(--yw-brand);
|
||||
--bs-navbar-toggler-border-color: var(--yw-chrome-border);
|
||||
background: var(--yw-chrome-bg) !important;
|
||||
border-bottom: 1px solid var(--yw-chrome-border);
|
||||
padding: .6rem 1.2rem;
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
color: var(--yw-accent) !important;
|
||||
color: var(--yw-brand) !important;
|
||||
letter-spacing: 2.5px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
@@ -104,6 +462,68 @@ a.navbar-subtitle:hover {
|
||||
margin: 0 .5rem;
|
||||
}
|
||||
|
||||
/* --- Appearance menu (PageHeader.AppearancePath) ------------------- */
|
||||
/* A <details> dropdown: opens and closes without a script, so it works
|
||||
under a strict script-src CSP. Each choice is a submit button of one
|
||||
POST form. */
|
||||
.yw-appearance {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.yw-appearance > summary {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.yw-appearance > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.yw-appearance-menu {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: calc(100% + .35rem);
|
||||
z-index: 1030;
|
||||
min-width: 12rem;
|
||||
padding: .35rem 0;
|
||||
background: var(--yw-chrome-bg);
|
||||
border: 1px solid var(--yw-chrome-border);
|
||||
border-radius: .375rem;
|
||||
box-shadow: 0 .5rem 1rem rgba(0, 0, 0, .25);
|
||||
}
|
||||
|
||||
.yw-appearance-menu h6 {
|
||||
color: var(--yw-muted);
|
||||
font-size: .72rem;
|
||||
letter-spacing: .08em;
|
||||
text-transform: uppercase;
|
||||
margin: .35rem .9rem .2rem;
|
||||
}
|
||||
|
||||
.yw-appearance-menu button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: .3rem .9rem;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--yw-text);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.yw-appearance-menu button:hover {
|
||||
background: color-mix(in srgb, var(--yw-accent) 10%, transparent);
|
||||
}
|
||||
|
||||
.yw-appearance-menu button[aria-pressed="true"] {
|
||||
color: var(--yw-accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.yw-appearance-menu hr {
|
||||
margin: .35rem 0;
|
||||
border-color: var(--yw-chrome-border);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* --- Sidebar ------------------------------------------------ */
|
||||
.sidebar {
|
||||
background: var(--yw-chrome-bg);
|
||||
@@ -111,25 +531,46 @@ a.navbar-subtitle:hover {
|
||||
padding-top: .5rem;
|
||||
}
|
||||
|
||||
/* transition: none -- Bootstrap's .nav-link fades color, background and
|
||||
border over .15s. The browser may compute styles once while only
|
||||
bootstrap.min.css has loaded; when style.css arrives, that fade ran
|
||||
from Bootstrap's blue link color to ours, so every sidebar link
|
||||
flickered blue on each page load (and the active link's border faded
|
||||
in). Whether a change animates depends on the new style, so turning
|
||||
the transition off here stops it. */
|
||||
.sidebar .nav-link {
|
||||
color: var(--yw-nav-link);
|
||||
font-size: .85rem;
|
||||
padding: .5rem 1rem;
|
||||
border-radius: 0;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.sidebar .nav-link:hover {
|
||||
background: rgba(var(--yw-accent-rgb), .08);
|
||||
background: color-mix(in srgb, var(--yw-accent) 8%, transparent);
|
||||
color: var(--yw-nav-link-hover-text);
|
||||
}
|
||||
|
||||
.sidebar .nav-link.active {
|
||||
background: rgba(var(--yw-accent-rgb), .1);
|
||||
background: color-mix(in srgb, var(--yw-accent) 10%, transparent);
|
||||
color: var(--yw-accent);
|
||||
font-weight: 600;
|
||||
border-left: 2px solid var(--yw-accent);
|
||||
}
|
||||
|
||||
/* A page without a sidebar (a login page): BodyAttrs ` class="no-sidebar"`.
|
||||
The layout always renders the sidebar column; this hides it and gives
|
||||
<main> the full width. !important: Bootstrap's d-md-block, column and
|
||||
ms-sm-auto classes on those elements are !important or more specific. */
|
||||
body.no-sidebar .sidebar {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
body.no-sidebar main {
|
||||
width: 100% !important;
|
||||
margin-left: 0 !important;
|
||||
}
|
||||
|
||||
/* --- Alerts (flash banners) ---------------------------------------- */
|
||||
.alert-success { background: var(--yw-success-bg); border-color: var(--yw-success-border); color: var(--yw-success-text); }
|
||||
.alert-danger { background: var(--yw-danger-bg); border-color: var(--yw-danger-border); color: var(--yw-danger-text); }
|
||||
@@ -143,6 +584,362 @@ a.navbar-subtitle:hover {
|
||||
border-top: 1px solid var(--yw-chrome-border);
|
||||
}
|
||||
|
||||
/* Narrow screens (below Bootstrap's md breakpoint, where the sidebar
|
||||
column stacks above the content): the sidebar becomes a tab bar --
|
||||
the same look as a page's own Bootstrap .nav-tabs (e.g. a manual's
|
||||
topic tabs): one row of links that wraps onto further rows when they
|
||||
don't fit, never a sideways-scrolling strip, the active one
|
||||
underlined in the accent color. */
|
||||
@media (max-width: 767.98px) {
|
||||
.sidebar { border-right: none; border-bottom: 1px solid var(--yw-chrome-border); }
|
||||
.sidebar {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--yw-chrome-border);
|
||||
padding-top: 0;
|
||||
}
|
||||
/* !important: Bootstrap's .flex-column utility is !important itself. */
|
||||
.sidebar .nav.flex-column {
|
||||
flex-direction: row !important;
|
||||
flex-wrap: wrap;
|
||||
padding-top: 0 !important;
|
||||
}
|
||||
.sidebar .nav-link {
|
||||
padding: .55rem .85rem;
|
||||
border-bottom: 2px solid transparent;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sidebar .nav-link.active {
|
||||
border-left: none;
|
||||
border-bottom: 2px solid var(--yw-accent);
|
||||
}
|
||||
/* The navbar's own extras (a project's config path, action buttons)
|
||||
wrap onto a second line instead of widening the page past the
|
||||
screen. */
|
||||
.navbar > .container-fluid {
|
||||
flex-wrap: wrap;
|
||||
row-gap: .4rem;
|
||||
}
|
||||
.navbar > .container-fluid > div {
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
}
|
||||
.navbar-subtitle {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
/* The stacked row still grows to fill the page (see above); without
|
||||
this, the extra height is shared out between its wrapped lines and
|
||||
the tab bar gets an empty band below its links. */
|
||||
body > .container-fluid > .row {
|
||||
align-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Style: modern (data-style="modern", PageHeader.Style) ---------- */
|
||||
/* The default design since v0.5.0, over the same markup and the same
|
||||
palettes: a calm navbar without a rule, the sidebar as a
|
||||
floating rounded card with group headings and icons, a pill for the
|
||||
active entry, and softer, rounder Bootstrap components. Everything
|
||||
here is scoped to [data-style="modern"], so data-style="classic"
|
||||
still gives exactly the classic look above. Icons and group headings come from
|
||||
NavItem.Icon/Group; classic hides the icons. */
|
||||
|
||||
.yw-nav-icon {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.yw-nav-group {
|
||||
color: var(--yw-muted);
|
||||
font-size: .68rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: .09em;
|
||||
text-transform: uppercase;
|
||||
padding: .9rem 1rem .3rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] {
|
||||
--yw-radius: .75rem;
|
||||
--yw-radius-sm: .5rem;
|
||||
--bs-border-radius: var(--yw-radius-sm);
|
||||
--bs-border-radius-sm: .375rem;
|
||||
--bs-border-radius-lg: var(--yw-radius);
|
||||
--bs-border-radius-xl: 1rem;
|
||||
--bs-body-font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
|
||||
[data-style="modern"] body {
|
||||
font-size: .9rem;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
[data-style="modern"] h1,
|
||||
[data-style="modern"] h2,
|
||||
[data-style="modern"] h3 {
|
||||
color: var(--yw-text-strong);
|
||||
font-weight: 700;
|
||||
letter-spacing: -.02em;
|
||||
}
|
||||
|
||||
/* Navbar: same surface as the page, no rule; the brand reads as a
|
||||
product name, not a code. */
|
||||
[data-style="modern"] .navbar {
|
||||
background: var(--yw-bg) !important;
|
||||
border-bottom: 0;
|
||||
padding: .9rem 1.5rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .navbar-brand {
|
||||
color: var(--yw-text-strong) !important;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -.01em;
|
||||
}
|
||||
|
||||
[data-style="modern"] .navbar-subtitle-sep {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-style="modern"] .navbar .btn-sm,
|
||||
[data-style="modern"] .yw-user {
|
||||
border-radius: var(--yw-radius-sm);
|
||||
padding: .35rem .8rem;
|
||||
}
|
||||
|
||||
/* Navbar buttons and the menu toggle stay on one line; a consumer's
|
||||
long left-hand extra (yasta's config path) wraps instead. */
|
||||
[data-style="modern"] .navbar .btn,
|
||||
[data-style="modern"] .yw-user {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-style="modern"] .navbar > .container-fluid > div:first-child {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
[data-style="modern"] .navbar .btn-outline-secondary {
|
||||
--bs-btn-color: var(--yw-text);
|
||||
--bs-btn-border-color: var(--yw-border);
|
||||
--bs-btn-hover-color: var(--yw-text-strong);
|
||||
--bs-btn-hover-bg: var(--yw-surface-2);
|
||||
--bs-btn-hover-border-color: var(--yw-border);
|
||||
--bs-btn-active-color: var(--yw-text-strong);
|
||||
--bs-btn-active-bg: var(--yw-surface-2);
|
||||
--bs-btn-active-border-color: var(--yw-border);
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-user {
|
||||
color: var(--yw-text);
|
||||
background: var(--yw-surface);
|
||||
border: 1px solid var(--yw-border);
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-appearance-menu {
|
||||
background: var(--yw-surface);
|
||||
border-color: var(--yw-border);
|
||||
border-radius: var(--yw-radius);
|
||||
padding: .4rem;
|
||||
box-shadow: 0 .75rem 2rem rgba(0, 0, 0, .3);
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-appearance-menu h6 {
|
||||
margin: .4rem .6rem .2rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-appearance-menu button {
|
||||
border-radius: var(--yw-radius-sm);
|
||||
padding: .35rem .6rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-appearance-menu button[aria-pressed="true"] {
|
||||
background: color-mix(in srgb, var(--yw-accent) 16%, transparent);
|
||||
}
|
||||
|
||||
/* Sidebar: no full-height column any more, but a card that floats
|
||||
in the column and stays in view while the page scrolls. */
|
||||
[data-style="modern"] .sidebar {
|
||||
background: transparent;
|
||||
border-right: 0;
|
||||
padding: .5rem .25rem 1rem 1rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .sidebar > .nav {
|
||||
position: sticky;
|
||||
top: 1rem;
|
||||
background: var(--yw-surface);
|
||||
border: 1px solid var(--yw-border);
|
||||
border-radius: var(--yw-radius);
|
||||
padding: .5rem !important;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-nav-group {
|
||||
padding: .8rem .65rem .3rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-nav-group:first-child {
|
||||
padding-top: .35rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .sidebar .nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: .6rem;
|
||||
color: var(--yw-text);
|
||||
font-size: .875rem;
|
||||
padding: .45rem .65rem;
|
||||
border-radius: var(--yw-radius-sm);
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
[data-style="modern"] .yw-nav-icon {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
color: var(--yw-muted);
|
||||
}
|
||||
|
||||
[data-style="modern"] .sidebar .nav-link:hover {
|
||||
background: var(--yw-surface-2);
|
||||
color: var(--yw-text-strong);
|
||||
}
|
||||
|
||||
[data-style="modern"] .sidebar .nav-link.active {
|
||||
background: color-mix(in srgb, var(--yw-accent) 18%, var(--yw-surface));
|
||||
color: var(--yw-accent);
|
||||
font-weight: 600;
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
[data-style="modern"] .sidebar .nav-link.active .yw-nav-icon {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
[data-style="modern"] main {
|
||||
padding-top: 1.25rem !important;
|
||||
padding-bottom: 2rem !important;
|
||||
}
|
||||
|
||||
[data-style="modern"] .footer {
|
||||
border-top: 0;
|
||||
color: var(--yw-muted);
|
||||
opacity: .75;
|
||||
}
|
||||
|
||||
/* Bootstrap components the consumers' pages use: rounder, quieter,
|
||||
cards on the surface color with a hairline border. */
|
||||
[data-style="modern"] .card {
|
||||
--bs-card-bg: var(--yw-surface);
|
||||
--bs-card-border-color: var(--yw-border);
|
||||
--bs-card-border-radius: var(--yw-radius);
|
||||
--bs-card-inner-border-radius: calc(var(--yw-radius) - 1px);
|
||||
--bs-card-cap-bg: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
[data-style="modern"] .card-header {
|
||||
font-weight: 600;
|
||||
color: var(--yw-text-strong);
|
||||
}
|
||||
|
||||
[data-style="modern"] .list-group {
|
||||
--bs-list-group-bg: var(--yw-surface);
|
||||
--bs-list-group-border-color: var(--yw-border);
|
||||
--bs-list-group-border-radius: var(--yw-radius);
|
||||
--bs-list-group-action-hover-bg: var(--yw-surface-2);
|
||||
}
|
||||
|
||||
[data-style="modern"] .btn {
|
||||
--bs-btn-font-weight: 600;
|
||||
--bs-btn-padding-x: 1rem;
|
||||
--bs-btn-border-radius: var(--yw-radius-sm);
|
||||
}
|
||||
|
||||
[data-style="modern"] .btn-sm {
|
||||
--bs-btn-padding-x: .7rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .form-control,
|
||||
[data-style="modern"] .form-select {
|
||||
background-color: color-mix(in srgb, var(--yw-bg) 60%, var(--yw-surface));
|
||||
border-color: var(--yw-border);
|
||||
border-radius: var(--yw-radius-sm);
|
||||
padding-top: .5rem;
|
||||
padding-bottom: .5rem;
|
||||
}
|
||||
|
||||
[data-style="modern"] .form-label {
|
||||
font-weight: 600;
|
||||
color: var(--yw-text-strong);
|
||||
}
|
||||
|
||||
[data-style="modern"] .table {
|
||||
--bs-table-bg: transparent;
|
||||
--bs-table-border-color: var(--yw-border);
|
||||
}
|
||||
|
||||
[data-style="modern"] .table > thead th {
|
||||
color: var(--yw-muted);
|
||||
font-size: .72rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: .06em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
[data-style="modern"] a:not(.btn):not(.nav-link):not(.navbar-brand):not(.list-group-item) {
|
||||
text-decoration-color: color-mix(in srgb, currentColor 35%, transparent);
|
||||
text-underline-offset: .2em;
|
||||
}
|
||||
|
||||
[data-style="modern"] a:not(.btn):not(.nav-link):not(.navbar-brand):not(.list-group-item):hover {
|
||||
text-decoration-color: currentColor;
|
||||
}
|
||||
|
||||
/* A table as the whole body of a card: the card draws the outline. */
|
||||
[data-style="modern"] .card > .table:last-child > tbody > tr:last-child > * {
|
||||
border-bottom-width: 0;
|
||||
}
|
||||
|
||||
/* Status badges as quiet tinted chips instead of solid blocks. */
|
||||
[data-style="modern"] .badge.text-bg-success { background: var(--yw-success-bg) !important; color: var(--yw-success-text) !important; box-shadow: inset 0 0 0 1px var(--yw-success-border); }
|
||||
[data-style="modern"] .badge.text-bg-danger { background: var(--yw-danger-bg) !important; color: var(--yw-danger-text) !important; box-shadow: inset 0 0 0 1px var(--yw-danger-border); }
|
||||
[data-style="modern"] .badge.text-bg-warning { background: var(--yw-warning-bg) !important; color: var(--yw-warning-text) !important; box-shadow: inset 0 0 0 1px var(--yw-warning-border); }
|
||||
[data-style="modern"] .badge.text-bg-info { background: var(--yw-info-bg) !important; color: var(--yw-info-text) !important; box-shadow: inset 0 0 0 1px var(--yw-info-border); }
|
||||
[data-style="modern"] .badge.text-bg-secondary { background: var(--yw-surface-2) !important; color: var(--yw-muted) !important; box-shadow: inset 0 0 0 1px var(--yw-border); }
|
||||
|
||||
[data-style="modern"] .alert {
|
||||
border-radius: var(--yw-radius-sm);
|
||||
}
|
||||
|
||||
[data-style="modern"] .badge {
|
||||
border-radius: 999px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
[data-style="modern"] hr {
|
||||
border-color: var(--yw-border);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Narrow screens: the card becomes a wrapping row of pills; group
|
||||
headings would only break the row, so they go. */
|
||||
@media (max-width: 767.98px) {
|
||||
[data-style="modern"] .sidebar {
|
||||
border-bottom: 0;
|
||||
padding: .25rem .75rem .5rem;
|
||||
}
|
||||
[data-style="modern"] .sidebar > .nav {
|
||||
position: static;
|
||||
padding: .35rem !important;
|
||||
gap: .25rem;
|
||||
}
|
||||
[data-style="modern"] .yw-nav-group {
|
||||
display: none;
|
||||
}
|
||||
[data-style="modern"] .sidebar .nav-link {
|
||||
border-bottom: 0;
|
||||
padding: .4rem .7rem;
|
||||
}
|
||||
[data-style="modern"] .sidebar .nav-link.active {
|
||||
border-bottom: 0;
|
||||
}
|
||||
[data-style="modern"] .navbar {
|
||||
padding: .7rem 1rem;
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStyleAttributeAndMenu(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := r.Page(&buf, "dashboard", PageHeader{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), `<html lang="en" data-style="modern">`) {
|
||||
t.Errorf("unset Style does not render the modern default\n---\n%s", buf.String())
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
data := PageHeader{Lang: "de", Style: StyleClassic, AppearancePath: "/appearance"}
|
||||
if err := r.Page(&buf, "dashboard", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := buf.String()
|
||||
for _, want := range []string{
|
||||
`<html lang="de" data-style="classic">`,
|
||||
`<h6>Stil</h6>`,
|
||||
`name="style" value="modern" aria-pressed="false">Modern</button>`,
|
||||
`name="style" value="classic" aria-pressed="true">Klassisch</button>`,
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("rendered output missing %q\n---\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStyleCookie(t *testing.T) {
|
||||
h := AppearanceHandler("/ui")
|
||||
form := url.Values{"style": {StyleModern}, "back": {"/x"}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/ui/appearance", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
cookies := rec.Result().Cookies()
|
||||
if rec.Code != http.StatusSeeOther || len(cookies) != 1 || cookies[0].Name != StyleCookie || cookies[0].Value != StyleModern {
|
||||
t.Fatalf("got %d, cookies %+v", rec.Code, cookies)
|
||||
}
|
||||
|
||||
bad := httptest.NewRequest(http.MethodPost, "/ui/appearance", strings.NewReader("style=fancy"))
|
||||
bad.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, bad)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("unknown style: got %d, want 400", rec.Code)
|
||||
}
|
||||
|
||||
get := httptest.NewRequest(http.MethodGet, "/ui/x", nil)
|
||||
get.AddCookie(cookies[0])
|
||||
hdr := PageHeader{BasePath: "/ui"}
|
||||
hdr.ApplyAppearance(get)
|
||||
if hdr.Style != StyleModern {
|
||||
t.Errorf("Style = %q, want %q from the cookie", hdr.Style, StyleModern)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSidebarGroupsAndIcons(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
data := PageHeader{
|
||||
BasePath: "/ui",
|
||||
ActiveNav: "b",
|
||||
NavItems: []NavItem{
|
||||
{ID: "o", Label: "Overview", Href: "/"},
|
||||
{ID: "a", Label: "Account", Href: "/a", Group: "Account", Icon: "user"},
|
||||
{ID: "b", Label: "Security", Href: "/b", Group: "Account", Icon: "shield"},
|
||||
{ID: "c", Label: "Hosts", Href: "/c", Group: "Infra", Icon: "no-such-icon"},
|
||||
},
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := r.Page(&buf, "dashboard", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := buf.String()
|
||||
if n := strings.Count(out, `<div class="yw-nav-group">Account</div>`); n != 1 {
|
||||
t.Errorf("group heading Account rendered %d times, want 1\n---\n%s", n, out)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`<div class="yw-nav-group">Infra</div>`,
|
||||
`<a class="nav-link active" href="/ui/b" aria-current="page"><span class="yw-nav-icon" aria-hidden="true"><svg`,
|
||||
`<a class="nav-link" href="/ui/c">Hosts</a>`,
|
||||
`<a class="nav-link" href="/ui/">Overview</a>`,
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("rendered output missing %q\n---\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A page without NavItems (a login page) renders no sidebar container:
|
||||
// the modern style draws it as a card, which would show up empty.
|
||||
func TestSidebarWithoutItems(t *testing.T) {
|
||||
r, err := NewRenderer(testPagesFS(), "pages", []string{"dashboard"}, ".html.tmpl", testFuncs())
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer: %v", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := r.Page(&buf, "dashboard", PageHeader{Title: "Log in"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(buf.String(), `class="nav flex-column`) {
|
||||
t.Errorf("empty sidebar container rendered\n---\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{{define "base"}}<!doctype html>
|
||||
<html lang="{{if .Lang}}{{.Lang}}{{else}}en{{end}}">
|
||||
<html lang="{{if .Lang}}{{.Lang}}{{else}}en{{end}}"{{if .Theme}} data-theme="{{.Theme}}"{{end}}{{if .Palette}} data-palette="{{.Palette}}"{{end}} data-style="{{if .Style}}{{.Style}}{{else}}modern{{end}}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
@@ -18,7 +18,7 @@
|
||||
{{template "sidebar" .}}
|
||||
</nav>
|
||||
<main class="col-md-10 col-lg-10 ms-sm-auto px-md-4 py-3">
|
||||
{{if .Flash}}<div class="alert alert-{{if eq .FlashKind "ok"}}success{{else}}danger{{end}}">{{.Flash}}</div>{{end}}
|
||||
{{if .Flash}}<div class="alert alert-{{if eq .FlashKind "ok"}}success{{else if eq .FlashKind "info"}}info{{else}}danger{{end}}">{{.Flash}}</div>{{end}}
|
||||
{{template "content" .}}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{{define "navbar"}}
|
||||
<nav class="navbar navbar-dark navbar-expand">
|
||||
<nav class="navbar navbar-expand">
|
||||
<div class="container-fluid d-flex justify-content-between align-items-center">
|
||||
<div class="d-flex align-items-center">
|
||||
{{.NavbarBeforeBrand}}
|
||||
@@ -8,8 +8,22 @@
|
||||
{{.NavbarLeftExtra}}
|
||||
</div>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
{{if .Username}}<span class="navbar-subtitle">{{.Username}}</span>{{end}}
|
||||
{{if .LogoutPath}}<a href="{{.BasePath}}{{.LogoutPath}}" class="btn btn-outline-secondary btn-sm">Logout</a>{{end}}
|
||||
{{if .Username}}<span class="navbar-subtitle yw-user">{{.Username}}</span>{{end}}
|
||||
{{if .AppearancePath}}{{with .AppearanceMenu}}<details class="yw-appearance">
|
||||
<summary class="btn btn-outline-secondary btn-sm" title="{{.ThemeHeading}}: {{.Current.Label}}"><span aria-hidden="true">{{.Current.Symbol}}</span> {{.Current.Label}}</summary>
|
||||
<form method="post" action="{{$.BasePath}}{{$.AppearancePath}}" class="yw-appearance-menu m-0">
|
||||
<input type="hidden" name="back" value="{{$.AppearanceBack}}">{{$.AppearanceFormHTML}}
|
||||
<h6>{{.ThemeHeading}}</h6>
|
||||
{{range .Themes}}<button type="submit" name="theme" value="{{.ID}}" aria-pressed="{{.Current}}"><span aria-hidden="true">{{.Symbol}}</span> {{.Label}}</button>
|
||||
{{end}}<hr>
|
||||
<h6>{{.PaletteHeading}}</h6>
|
||||
{{range .Palettes}}<button type="submit" name="palette" value="{{.ID}}" aria-pressed="{{.Current}}">{{.Label}}</button>
|
||||
{{end}}<hr>
|
||||
<h6>{{.StyleHeading}}</h6>
|
||||
{{range .Styles}}<button type="submit" name="style" value="{{.ID}}" aria-pressed="{{.Current}}">{{.Label}}</button>
|
||||
{{end}}</form>
|
||||
</details>
|
||||
{{end}}{{end}}{{if .LogoutPath}}<form method="post" action="{{.BasePath}}{{.LogoutPath}}" class="d-inline m-0"><button type="submit" class="btn btn-outline-secondary btn-sm">Logout</button></form>{{end}}
|
||||
{{.NavbarRightExtra}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{{define "sidebar"}}
|
||||
<div class="nav flex-column pt-2">
|
||||
{{range .NavItems}}<a class="nav-link{{if eq $.ActiveNav .ID}} active{{end}}" href="{{$.BasePath}}{{.Href}}">{{.Label}}</a>
|
||||
{{if .NavItems}}<div class="nav flex-column pt-2">
|
||||
{{range .SidebarEntries}}{{if .GroupHead}}<div class="yw-nav-group">{{.GroupHead}}</div>
|
||||
{{end}}<a class="nav-link{{if .Active}} active{{end}}" href="{{$.BasePath}}{{.Href}}"{{if .Active}} aria-current="page"{{end}}>{{if .IconSVG}}<span class="yw-nav-icon" aria-hidden="true">{{.IconSVG}}</span>{{end}}{{.Label}}</a>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>{{end}}
|
||||
{{end}}
|
||||
Reference in new issue
Block a user