From 9a6ec940f73e070de75fa0e5eef528b8022fe68b Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Tue, 1 Sep 2026 01:34:48 +0200 Subject: [PATCH] Migrate auth to AuthGuard, retiring local Postgres-backed accounts Same pattern as GameStream (commit 6a46007), adapted for CollabTable being genuinely multi-user (not single-admin): admin user management (list/create/update/delete, role reassignment, superadmin protection) is fully proxied to AuthGuard, which already enforces the same rules CollabTable checked locally. Cookie forwarding, no local session token, AUTHGUARD_URL optional (unset = auth fully disabled), transport failures always surface as errAuthGuardUnavailable rather than ever letting a request through - proven with live tests against a closed socket. CollabTable's device-sync API token feature (separate from browser sessions) is deliberately left local-only regardless of AUTHGUARD_URL, keyed by a new currentUserID helper (AuthGuard's id when enabled, the shared placeholder id 0 when disabled) - a real, functional token either way, not faked data. Real bug found and fixed: api_tokens.user_id had a hard FK into the local auth_users table, which would reject new tokens once accounts stop being written locally. Dropped the now-invalid FK. Known, accepted gap (same as GameStream): self-service profile editing for non-admin accounts is lost, since AuthGuard only exposes an admin endpoint, no self-edit. TOTP QR issuer branding now comes from AuthGuard rather than CollabTable. Co-Authored-By: Claude Sonnet 5 --- backend/.env.example | 73 +- backend/README.md | 22 +- backend/auth.go | 955 ++- backend/auth_test.go | 194 + backend/db.go | 296 +- backend/server.go | 49 +- backend/web.go | 2 +- shared/backend/README.md | 2 + shared/backend/authclient/client.go | 497 ++ .../packages/media-shared-assets/.env.example | 2 + .../MediaDesktop/assets/icon.png | Bin 0 -> 1268 bytes shared/packages/media-shared-assets/README.md | 7 + .../packages/media-shared-assets/package.json | 19 + .../media-shared-assets/public/css/index.css | 5202 +++++++++++++++++ .../media-shared-assets/public/favicon.svg | 4 + .../public/images/default-avatar.svg | 5 + .../public/js/admin/admin-users-page.js | 17 + .../public/js/auth/auth-form.js | 47 + .../public/js/auth/auth-guard.js | 13 + .../public/js/auth/auth-modal.js | 646 ++ .../public/js/auth/auth-required-open.js | 15 + .../public/js/auth/auth-required.js | 63 + .../public/js/auth/auth-reset-perform.js | 24 + .../public/js/auth/auth-reset-request.js | 15 + .../public/js/auth/login-gate.js | 21 + .../public/js/auth/profile-page.js | 485 ++ .../public/js/layout/component-loader.js | 920 +++ .../public/js/layout/expandable-container.js | 204 + .../public/js/layout/header-controls.js | 266 + .../public/js/layout/results-container.js | 442 ++ .../js/layout/search-filter-container.js | 433 ++ .../public/js/media/media-detail-view.js | 28 + .../public/js/media/media-preview.js | 481 ++ .../public/js/media/thumbnails.js | 287 + .../public/js/navigation/pagination-bottom.js | 15 + .../public/js/navigation/pagination-top.js | 178 + .../public/js/navigation/redirect-home.js | 3 + .../public/js/theme/theme-toggle-footer.js | 15 + .../public/js/theme/theme-toggle.js | 106 + .../public/js/ui/confirm.js | 184 + .../public/js/ui/overlay.js | 142 + .../public/js/ui/progress-bar.js | 133 + .../public/js/ui/spinner.js | 122 + .../media-shared-assets/public/js/ui/toast.js | 73 + .../public/js/utils/clientLogger.js | 23 + .../public/js/utils/debounce.js | 147 + .../scripts/build-theme-css.mjs | 20 + shared/scripts/sync-consumers.ps1 | 15 +- 48 files changed, 12401 insertions(+), 511 deletions(-) create mode 100644 backend/auth_test.go create mode 100644 shared/backend/authclient/client.go create mode 100644 shared/packages/media-shared-assets/.env.example create mode 100644 shared/packages/media-shared-assets/MediaDesktop/assets/icon.png create mode 100644 shared/packages/media-shared-assets/README.md create mode 100644 shared/packages/media-shared-assets/package.json create mode 100644 shared/packages/media-shared-assets/public/css/index.css create mode 100644 shared/packages/media-shared-assets/public/favicon.svg create mode 100644 shared/packages/media-shared-assets/public/images/default-avatar.svg create mode 100644 shared/packages/media-shared-assets/public/js/admin/admin-users-page.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-form.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-guard.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-modal.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-required-open.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-required.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-reset-perform.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/auth-reset-request.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/login-gate.js create mode 100644 shared/packages/media-shared-assets/public/js/auth/profile-page.js create mode 100644 shared/packages/media-shared-assets/public/js/layout/component-loader.js create mode 100644 shared/packages/media-shared-assets/public/js/layout/expandable-container.js create mode 100644 shared/packages/media-shared-assets/public/js/layout/header-controls.js create mode 100644 shared/packages/media-shared-assets/public/js/layout/results-container.js create mode 100644 shared/packages/media-shared-assets/public/js/layout/search-filter-container.js create mode 100644 shared/packages/media-shared-assets/public/js/media/media-detail-view.js create mode 100644 shared/packages/media-shared-assets/public/js/media/media-preview.js create mode 100644 shared/packages/media-shared-assets/public/js/media/thumbnails.js create mode 100644 shared/packages/media-shared-assets/public/js/navigation/pagination-bottom.js create mode 100644 shared/packages/media-shared-assets/public/js/navigation/pagination-top.js create mode 100644 shared/packages/media-shared-assets/public/js/navigation/redirect-home.js create mode 100644 shared/packages/media-shared-assets/public/js/theme/theme-toggle-footer.js create mode 100644 shared/packages/media-shared-assets/public/js/theme/theme-toggle.js create mode 100644 shared/packages/media-shared-assets/public/js/ui/confirm.js create mode 100644 shared/packages/media-shared-assets/public/js/ui/overlay.js create mode 100644 shared/packages/media-shared-assets/public/js/ui/progress-bar.js create mode 100644 shared/packages/media-shared-assets/public/js/ui/spinner.js create mode 100644 shared/packages/media-shared-assets/public/js/ui/toast.js create mode 100644 shared/packages/media-shared-assets/public/js/utils/clientLogger.js create mode 100644 shared/packages/media-shared-assets/public/js/utils/debounce.js create mode 100644 shared/packages/media-shared-assets/scripts/build-theme-css.mjs diff --git a/backend/.env.example b/backend/.env.example index 8a86188..e66d7ef 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,31 +1,42 @@ -################################################################# -# Server -################################################################# -PORT=3000 -APP_VERSION=dev - -# Set to "true" once served over HTTPS - marks the admin session cookie Secure. -COOKIE_SECURE=false - -################################################################# -# PostgreSQL configuration -################################################################# -# Postgres connection string (bring your own - this app does not run Postgres for you). -# Example: postgres://user:password@localhost:5432/collabtable -DATABASE_URL= - -################################################################# -# Startup resilience and sync tuning -################################################################# -# DB init retry interval in milliseconds (default: 5000) -DB_INIT_RETRY_INTERVAL_MS=5000 - -# Max DB init retry attempts. 0 means retry forever (default: 0) -DB_INIT_RETRY_MAX_ATTEMPTS=0 - -# Allow at most this much client clock skew into sync timestamps (default: 0) -# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops. -SYNC_MAX_FUTURE_SKEW_MS=0 - -# Notification retention period in milliseconds (default: 7 days) -NOTIF_RETENTION_MS=604800000 +################################################################# +# Server +################################################################# +PORT=3000 +APP_VERSION=dev + +# Set to "true" once served over HTTPS - marks the admin session cookie Secure. +COOKIE_SECURE=false + +################################################################# +# Authentication (AuthGuard) +################################################################# +# Base URL of the AuthGuard centralized identity service this app authenticates +# through instead of a local user table. +# AUTHGUARD_URL=https://auth.example.com +# Leaving AUTHGUARD_URL unset does NOT fall back to any local account store -- +# it disables authentication entirely (no login screen, everything open). +# Only run without it for local development or a deployment you are certain +# does not need access control. + +################################################################# +# PostgreSQL configuration +################################################################# +# Postgres connection string (bring your own - this app does not run Postgres for you). +# Example: postgres://user:password@localhost:5432/collabtable +DATABASE_URL= + +################################################################# +# Startup resilience and sync tuning +################################################################# +# DB init retry interval in milliseconds (default: 5000) +DB_INIT_RETRY_INTERVAL_MS=5000 + +# Max DB init retry attempts. 0 means retry forever (default: 0) +DB_INIT_RETRY_MAX_ATTEMPTS=0 + +# Allow at most this much client clock skew into sync timestamps (default: 0) +# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops. +SYNC_MAX_FUTURE_SKEW_MS=0 + +# Notification retention period in milliseconds (default: 7 days) +NOTIF_RETENTION_MS=604800000 diff --git a/backend/README.md b/backend/README.md index 5d6ad77..78beb4a 100644 --- a/backend/README.md +++ b/backend/README.md @@ -8,8 +8,10 @@ Svelte dashboard and the Android synchronization API from one container. - REST API for lists, fields, items, and item values - Transactional HTTP synchronization with soft-delete tombstones - Notification polling for background refreshes -- Single-admin browser session with bcrypt-hashed credentials -- Long-lived bearer API token for Android and other sync clients +- Multi-user browser sessions (with per-account roles/admin user management) authenticated + through AuthGuard, a centralized identity service shared across projects (optional -- see + `AUTHGUARD_URL` below) +- Long-lived bearer API token for Android and other sync clients (independent of AuthGuard) - Embedded SvelteKit dashboard - Idempotent PostgreSQL schema initialization @@ -21,11 +23,12 @@ docker build -f docker/Dockerfile -t collabtable-server . docker run -d --name collabtable-server --restart unless-stopped \ -p 3000:3000 \ -e DATABASE_URL=postgres://user:password@host:5432/collabtable \ + -e AUTHGUARD_URL=https://auth.example.com \ -e COOKIE_SECURE=false \ collabtable-server ``` -Open `http://localhost:3000` to create the administrator account. Generate an API token from +Open `http://localhost:3000` to create the first account. Generate an API token from the dashboard's Settings menu and enter it in the Android app. ## Local development @@ -73,8 +76,13 @@ notification events. - `GET /api/auth/token/status` - `POST /api/auth/token/regenerate` -Browser authentication uses the `collabtable_session` HTTP-only cookie. There is one admin -account per database. API tokens are hashed at rest and shown only when generated. +Browser authentication proxies to AuthGuard (`AUTHGUARD_URL`), which sets and reads its own +`auth_session` HTTP-only cookie; CollabTable itself mints no session token. Any number of +accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/auth/users`. +`AUTHGUARD_URL` is optional: leaving it unset disables authentication entirely (no login +screen, nothing gated) rather than falling back to any local account store -- only use that for +local development or a deployment you are certain does not need access control. API tokens are +unrelated to AuthGuard (see below), hashed at rest, and shown only when generated. ### Data @@ -104,6 +112,10 @@ account per database. API tokens are hashed at rest and shown only when generate - `APP_VERSION` — optional version displayed in the dashboard, default `dev` - `COOKIE_SECURE` — set to `true` when served over HTTPS - `DATABASE_URL` — PostgreSQL connection string, required +- `AUTHGUARD_URL` — base URL of the AuthGuard identity service CollabTable authenticates + against, default unset (auth disabled). Leaving it unset does not fall back to any local + account store -- it disables authentication entirely, treating every request as + authenticated with nothing gated. - `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000` - `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever - `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0` diff --git a/backend/auth.go b/backend/auth.go index cf0eba8..5d4c1f2 100644 --- a/backend/auth.go +++ b/backend/auth.go @@ -10,14 +10,158 @@ import ( "net/http" "strconv" "strings" - "time" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" + authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" ) +// AuthGuard migration +// ==================== +// +// CollabTable used to be a fully self-contained, multi-user auth +// implementation: account and session state lived in this service's own +// PostgreSQL `auth_users`/`auth_sessions` tables (see db.go's schema, which +// is kept but no longer used for this -- see initSchema's doc comment). +// Unlike GameStream (a single-admin tool this migration was first proven +// against), CollabTable is a real multi-user collaboration app: it already +// had full admin user management (list/create/edit/delete other accounts, +// assign roles) before this migration, not just a single local admin +// account. That feature maps directly onto AuthGuard's own +// /api/admin/users endpoints (see AuthGuard/README.md), which enforce the +// exact same rules CollabTable's local implementation did (protected +// superadmin, no self-delete, role-reassignment restricted to superadmin +// actors) -- so handleUsers/handleUser below simply proxy and trust +// AuthGuard's authorization instead of re-checking those rules locally. +// +// It now proxies every browser-session auth operation to AuthGuard +// (Web/Central/AuthGuard), a centralized identity service other projects +// share, via the `authclient` package (Web/Central/shared/backend/ +// authclient, vendored here at shared/backend/authclient). CollabTable's own +// /api/auth/... URL paths and JSON response shapes are UNCHANGED -- the +// frontend was not touched -- only what backs them changed. +// +// One CollabTable feature this migration deliberately leaves alone: the +// long-lived per-account API bearer token used by a user's own devices to +// call the sync API (requireAPIToken below, and handleTokenStatus/ +// handleTokenRegenerate). That token is a device-pairing credential, not a +// browser session, and AuthGuard has no equivalent concept -- it stays +// entirely local, keyed by whatever numeric id currentUserID resolves to +// (an AuthGuard account id, or the fixed placeholder id when auth is +// disabled; see "Auth-disabled mode" below). Its api_tokens table no longer +// foreign-keys into auth_users; see db.go's comment on that table. +// +// Session cookie / token model +// ----------------------------- +// AuthGuard sets its own `auth_session` cookie (authclient.DefaultCookieName) +// on register/login, whose scope (host-only, or a shared parent domain for +// real cross-project SSO) is entirely controlled by AuthGuard's own +// AUTH_COOKIE_DOMAIN setting -- CollabTable has no opinion on it. Rather +// than inventing a second cookie and a mapping between "CollabTable's +// session token" and "AuthGuard's session token", CollabTable forwards +// AuthGuard's Set-Cookie header straight through to the browser on +// register/login/logout (authclient.ForwardCookies), and reads that same +// `auth_session` cookie back off every incoming request to use as the +// bearer token on its server-to-server calls to AuthGuard (sessionToken/ +// currentUser below). CollabTable mints no session token of its own at all, +// which is both less code and automatically correct under whatever +// cookie-domain SSO topology AuthGuard is configured with. The frontend +// requires no changes for this -- it never reads the cookie's name or value +// itself, only relies on the browser sending it back. +// +// The pre-migration `collabtable_session` cookie name is retained only as +// something logout additionally clears, so a browser that still holds one +// from before this migration doesn't keep sending a now-meaningless cookie +// forever. +// +// Setup flow +// ---------- +// CollabTable's "first launch: create the first (superadmin) account" flow +// doesn't map onto AuthGuard, which is not scoped to a single project and +// has no concept of "this is CollabTable's initial account" -- and unlike a +// single-admin tool, "no accounts registered yet" can't be answered by +// asking AuthGuard either, since AuthGuard is a shared identity store other +// projects (and other CollabTable instances) may already have accounts in. +// Rather than trying to derive SetupRequired from AuthGuard state, CollabTable +// keeps a tiny local flag of its own -- collabtable_setup_state.claimed +// (db.go) -- that means only "has this CollabTable instance completed its +// setup screen once", with no credentials of any kind in it. handleSetup +// atomically claims that flag, registers the account against AuthGuard's +// POST /api/register, and unclaims it again if registration fails (so a bad +// attempt doesn't permanently lock out setup). This is the smallest change +// that preserves the existing one-time-setup UX without forcing AuthGuard to +// answer a question it has no way to answer. +// +// Known gaps versus the pre-migration behavior (AuthGuard was deliberately +// not modified for this migration, so these can only be closed by adding to +// AuthGuard itself later): +// - Self-service profile editing (POST /api/auth/credentials) needs +// AuthGuard's admin/users endpoint, which requires CanManageUsers. A +// plain "user"-role account (not admin/superadmin) has no self-service +// way to change its own username/email/password via AuthGuard today; see +// handleUpdateCredentials. This is a real regression for CollabTable +// specifically (a genuinely multi-user app): a plain collaborator who +// could previously edit their own profile now cannot, until AuthGuard +// grows a true self-service endpoint. +// - AuthGuard has no "is TOTP enabled" read endpoint, only +// enable/verify/disable, so handleTOTPStatus answers from a local +// best-effort cache instead of AuthGuard directly; see its doc comment. +// - The admin user list (GET /api/auth/users) similarly can't ask AuthGuard +// for other accounts' TOTP status, so TotpEnabled on entries other than +// the cache's own observations defaults to false. +// - The TOTP setup QR code's issuer name now comes from AuthGuard's own +// otpauth:// URI rather than being branded "CollabTable" locally, since +// AuthGuard (not CollabTable) generates the secret/URI now. +// - Changing a user's own credentials used to invalidate every session for +// that account (deleteSessionsForUser). AuthGuard has no bulk +// "invalidate every session for this account" call, only single-session +// Logout, so only the session used for the credentials request itself is +// guaranteed revoked; see handleUpdateCredentials. +// +// Auth-disabled mode (AUTHGUARD_URL unset) +// ----------------------------------------- +// AUTHGUARD_URL is optional. When it is unset, AuthService.authGuard is nil +// (AuthService.enabled() reports false) and CollabTable runs with +// authentication turned off entirely: every request is treated as already +// authenticated, with no login screen and nothing gated -- this is an +// explicit mode for local development or a standalone deployment that +// doesn't want centralized identity, not an error condition (unlike the +// pre-migration local-Postgres-auth design this replaced, there is no +// degraded/partial fallback state; it is either "AuthGuard" or "no auth" and +// never silently "local auth"). +// +// requireSession (gating logout/credentials/users/totp/token/tech-stack/web +// data) simply calls through to next without resolving a session at all in +// this mode. handleStatus/handleSetup/handleLogin each special-case this and +// return a fixed placeholder "authenticated" identity (localProfile) without +// ever touching AuthGuard or the local setup-claim flag, so the frontend +// never shows a login or setup screen. handleLogout is a no-op success. +// +// Features that need a *real* backing identity rather than just an access +// gate -- TOTP (setup/enable/disable; handleTOTPStatus alone still answers +// {enabled: false}), self-service profile editing, and admin user +// management's mutating calls -- have nothing meaningful to do without +// AuthGuard (there is no account to attach a TOTP secret to, no profile to +// edit, no user store to create/update/delete against) and return a clear +// errFeatureRequiresAuthGuard error instead of silently no-opping or faking +// data. GET /api/auth/users is the one exception: consistent with "nothing +// gated", it returns an empty list rather than an error, since listing +// (unlike mutating) has an honest, unsurprising answer when there is no user +// store: there are no managed users to show. +// +// The device-sync API token (handleTokenStatus/handleTokenRegenerate) is +// different from the features above: it has nothing to do with AuthGuard +// accounts even when AuthGuard IS configured (see the top of this comment), +// so it keeps working in disabled mode too, scoped to the fixed placeholder +// identity every request shares -- a real, functional token, not faked data; +// see currentUserID. + const ( - sessionCookieName = "collabtable_session" - sessionTTL = 24 * time.Hour + // legacySessionCookieName is the cookie CollabTable itself used to mint + // and read before the AuthGuard migration. Nothing sets it anymore; it is + // only referenced so logout can clear a stale copy left over in a browser + // from before the migration. + legacySessionCookieName = "collabtable_session" + minPasswordLength = 8 maxUsernameLength = 64 maxEmailLength = 254 @@ -30,17 +174,51 @@ var ( errUsernameRequired = errors.New("Username is required.") errEmailRequired = errors.New("Email is required and must be valid.") errPasswordTooShort = errors.New("Password must be at least 8 characters.") - errCurrentPasswordBad = errors.New("Current password is incorrect.") + errInvalidAuthInput = errors.New("invalid authentication input") + errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.") + // errFeatureRequiresAuthGuard is returned by the handlers that need a real + // backing identity (not just an access gate) when AUTHGUARD_URL is unset; + // see the top-of-file doc comment's "Auth-disabled mode" section. + errFeatureRequiresAuthGuard = errors.New("This feature requires AUTHGUARD_URL to be configured.") + // errAuthGuardUnavailable is returned whenever currentUser/currentProfile + // propagate a non-nil error: by construction (see their doc comments) + // that only happens when AuthGuard could not be reached or gave an + // unusable response -- a real "invalid or expired session" is always + // resolved to (nil, nil) instead, never an error -- so every caller of + // these two can safely report this same, specific message rather than a + // generic "internal error" that would be indistinguishable from any + // other server bug. This matters most for handleStatus/requireSession: + // AUTHGUARD_URL being configured but unreachable must surface as a + // visible, distinct error in the UI rather than ever being confused with + // "please log in" or silently letting the request through unauthenticated. + errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.") ) +// localProfile is the fixed placeholder identity handleStatus/handleSetup/ +// handleLogin report when auth is disabled (AUTHGUARD_URL unset). Role is +// superadmin so CanManageUsers reports true, consistent with "nothing +// gated": the frontend's own admin-only UI sections become visible too, even +// though the underlying admin endpoints have nothing to manage (see +// handleUsers/handleUser). Its ID (0) also doubles as the shared identity +// every request's device-sync API token is scoped to in this mode; see +// currentUserID. +var localProfile = authclient.PublicUser{ID: 0, Username: "local", Email: "", Role: string(sharedauth.RoleSuperAdmin)} + +// AuthService proxies CollabTable's existing /api/auth/... handlers to +// AuthGuard. See this file's top-of-file doc comment for the overall design. type AuthService struct { db *DB + authGuard *authclient.Client secureCookie bool - reset *sharedauth.ResetManager + // reset backs CollabTable's own local break-glass recovery flow (see + // handleResetRequest/handleResetConfirm); it is unrelated to AuthGuard, + // which runs its own separate instance of the same ResetManager type for + // its own recovery flow. + reset *sharedauth.ResetManager } -func newAuthService(db *DB, secureCookie bool) *AuthService { - return &AuthService{db: db, secureCookie: secureCookie, reset: sharedauth.NewResetManager()} +func newAuthService(authGuard *authclient.Client, db *DB, secureCookie bool) *AuthService { + return &AuthService{db: db, authGuard: authGuard, secureCookie: secureCookie, reset: sharedauth.NewResetManager()} } func normalizeUsername(value string) (string, error) { @@ -83,63 +261,115 @@ func hashToken(token string) string { return hex.EncodeToString(sum[:]) } -func (a *AuthService) setSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time) { - http.SetCookie(w, &http.Cookie{ - Name: sessionCookieName, - Value: token, - Path: "/", - HttpOnly: true, - Secure: a.secureCookie, - SameSite: http.SameSiteLaxMode, - Expires: expiresAt, - }) +// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file +// doc comment's "Auth-disabled mode" section. +func (a *AuthService) enabled() bool { + return a.authGuard != nil } -func (a *AuthService) clearSessionCookie(w http.ResponseWriter) { - http.SetCookie(w, &http.Cookie{ - Name: sessionCookieName, - Value: "", - Path: "/", - HttpOnly: true, - Secure: a.secureCookie, - SameSite: http.SameSiteLaxMode, - MaxAge: -1, - }) -} - -func (a *AuthService) startSession(ctx context.Context, w http.ResponseWriter, userID int64) error { - token, err := randomToken() - if err != nil { - return err - } - expiresAt := time.Now().Add(sessionTTL) - if err := a.db.createSession(ctx, userID, hashToken(token), expiresAt); err != nil { - return err - } - a.setSessionCookie(w, token, expiresAt) - return nil -} - -func (a *AuthService) currentUser(r *http.Request) (*AuthUser, error) { - cookie, err := r.Cookie(sessionCookieName) +// sessionToken reads the AuthGuard session cookie off the incoming request. +// See the top-of-file doc comment's "Session cookie / token model" section. +func (a *AuthService) sessionToken(r *http.Request) string { + cookie, err := r.Cookie(authclient.DefaultCookieName) if err != nil || cookie.Value == "" { + return "" + } + return cookie.Value +} + +// clearSessionCookies clears both the AuthGuard cookie (as a fallback -- +// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies, +// already does this) and the pre-migration CollabTable cookie name. +func (a *AuthService) clearSessionCookies(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true, + Secure: a.secureCookie, SameSite: http.SameSiteLaxMode, MaxAge: -1, + }) + http.SetCookie(w, &http.Cookie{ + Name: legacySessionCookieName, Value: "", Path: "/", HttpOnly: true, + Secure: a.secureCookie, SameSite: http.SameSiteLaxMode, MaxAge: -1, + }) +} + +// currentUser resolves the request's AuthGuard session cookie via the +// lightweight GET /api/session/validate call, or nil if the request is +// unauthenticated or the session is invalid/expired. This is intentionally +// the cheap check (no email, no role-derived fields) -- it's what gates +// every request through requireSession. +func (a *AuthService) currentUser(r *http.Request) (*authclient.User, error) { + token := a.sessionToken(r) + if token == "" { return nil, nil } - return a.db.getSessionUser(r.Context(), hashToken(cookie.Value)) + user, err := a.authGuard.Validate(r.Context(), token) + if err != nil { + if errors.Is(err, authclient.ErrInvalidSession) { + return nil, nil + } + return nil, err + } + return user, nil } -func (a *AuthService) requireSession(next func(http.ResponseWriter, *http.Request, *AuthUser)) http.Handler { +// currentProfile resolves the full account profile (email included) via +// AuthGuard's GET /api/me, for handlers that need more than currentUser's +// slim shape, alongside the session token itself (so the caller can make a +// further authenticated call to AuthGuard without re-reading the cookie). +func (a *AuthService) currentProfile(r *http.Request) (*authclient.PublicUser, string, error) { + token := a.sessionToken(r) + if token == "" { + return nil, "", nil + } + user, err := a.authGuard.Me(r.Context(), token) + if err != nil { + var apiErr *authclient.APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized { + return nil, "", nil + } + return nil, "", err + } + return user, token, nil +} + +// currentUserID resolves the caller's identity to a stable numeric id for +// purely-local, identity-keyed state that has nothing to do with AuthGuard's +// own account data -- currently just the device-sync API token (see +// handleTokenStatus/handleTokenRegenerate). When auth is disabled this is +// the fixed localProfile.ID (0): every request shares the same "local" +// identity, so a device-sync token minted in this mode is real and +// functional, just scoped to that one shared identity rather than a +// per-account AuthGuard identity. ok is false when auth is enabled but the +// caller has no valid session. +func (a *AuthService) currentUserID(r *http.Request) (id int64, ok bool, err error) { + if !a.enabled() { + return localProfile.ID, true, nil + } + user, err := a.currentUser(r) + if err != nil { + return 0, false, err + } + if user == nil { + return 0, false, nil + } + return user.ID, true, nil +} + +func (a *AuthService) requireSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + next.ServeHTTP(w, r) + return + } user, err := a.currentUser(r) if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } if user == nil { writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) return } - next(w, r, user) + next.ServeHTTP(w, r) }) } @@ -190,29 +420,69 @@ type credentialsRequest struct { TotpToken string `json:"totpToken"` } +func (a *AuthService) statusResponse(ctx context.Context, user authclient.PublicUser) authStatusResponse { + totpEnabled, err := a.db.GetCachedTOTPEnabled(ctx, user.ID) + if err != nil { + // Best-effort cache; a read failure just means "assume disabled" rather + // than failing the whole status/login/setup response. + totpEnabled = false + } + return authStatusResponse{ + Authenticated: true, + ID: user.ID, + Username: user.Username, + Email: user.Email, + Role: user.Role, + CanManageUsers: sharedauth.CanManageUsers(user.Role), + TotpEnabled: totpEnabled, + } +} + func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) { - count, err := a.db.countUsers(r.Context()) + if !a.enabled() { + writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), localProfile)) + return + } + + claimed, err := a.db.IsSetupClaimed(r.Context()) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - if count == 0 { + if !claimed { writeJSON(w, http.StatusOK, authStatusResponse{SetupRequired: true}) return } - user, err := a.currentUser(r) + profile, _, err := a.currentProfile(r) if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") + // Reachable-but-invalid-session already resolved to (nil, "", nil) + // inside currentProfile; getting here means AuthGuard itself could not + // be reached or gave an unusable response. This must never be + // conflated with "not authenticated" (which would incorrectly show the + // frontend's login screen with no indication anything is wrong) or + // silently proceed as authenticated -- see errAuthGuardUnavailable. + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } - if user == nil { + if profile == nil { writeJSON(w, http.StatusOK, authStatusResponse{}) return } - writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role), TotpEnabled: user.TOTPEnabled}) + writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), *profile)) } +// handleResetRequest and handleResetConfirm are CollabTable's own local +// "break glass" account recovery: an operator with shell/log access to this +// container (not to AuthGuard) can recover access to CollabTable's UI +// without knowing the current AuthGuard account's password. This is +// deliberately NOT proxied to AuthGuard's own POST +// /api/password-reset/request|confirm -- a break-glass flow should never +// depend on the very identity service it exists to recover access to, and +// (like GameStream before it) CollabTable's existing frontend only ever +// sends {code}, not a new password, so it was built for a "wipe and redo +// setup" recovery model rather than AuthGuard's "set a specific new +// password" one in any case. func (a *AuthService) handleResetRequest(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) @@ -225,6 +495,21 @@ func (a *AuthService) handleResetRequest(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } +// handleResetConfirm validates the one-time code handleResetRequest printed +// to this process's own stdout and, on success, resets the local "setup +// completed" flag so CollabTable's setup screen reappears. +// +// This intentionally does NOT touch the underlying AuthGuard account at all +// (does not delete it, does not change its password): CollabTable's local +// console-access recovery is only ever allowed to affect CollabTable's own +// claim on an identity, never to reach into and mutate the centralized +// identity store other projects may come to share. Concretely, this means +// the account AuthGuard already has is left behind (orphaned, from +// CollabTable's perspective) once this runs; re-running setup with the same +// username/email will hit AuthGuard's own 409 "already in use" and the +// operator will need to either choose a different identity at the setup +// screen or resolve the original account directly against AuthGuard (which +// has its own equivalent break-glass recovery). func (a *AuthService) handleResetConfirm(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) @@ -241,31 +526,29 @@ func (a *AuthService) handleResetConfirm(w http.ResponseWriter, r *http.Request) writeJSONError(w, http.StatusUnauthorized, "Invalid or expired reset code.") return } - if err := a.db.deleteAllUsers(r.Context()); err != nil { + if err := a.db.ClearSetupClaim(r.Context()); err != nil { writeJSONError(w, http.StatusInternalServerError, "Reset failed") return } - a.clearSessionCookie(w) + a.clearSessionCookies(w) writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } +// handleSetup registers CollabTable's first account against AuthGuard's +// POST /api/register. See the top-of-file doc comment's "Setup flow" section +// for why this needs a small local claim flag instead of a count-based +// check. func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), localProfile)) + return + } + var request credentialsRequest if err := decodeJSON(r, &request); err != nil { writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") return } - - count, err := a.db.countUsers(r.Context()) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - if count > 0 { - writeJSONError(w, http.StatusConflict, errSetupComplete.Error()) - return - } - username, err := normalizeUsername(request.Username) if err != nil { writeJSONError(w, http.StatusBadRequest, err.Error()) @@ -281,143 +564,248 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) { return } - hash, err := sharedauth.HashPassword(request.Password) + claimed, err := a.db.TryClaimSetup(r.Context()) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - user, err := a.db.createUser(r.Context(), username, email, string(hash)) + if !claimed { + writeJSONError(w, http.StatusConflict, errSetupComplete.Error()) + return + } + + result, err := a.authGuard.Register(r.Context(), username, email, request.Password) if err != nil { - if errors.Is(err, ErrSingletonUserExists) { - writeJSONError(w, http.StatusConflict, errSetupComplete.Error()) + // The claim slot is only valid once actually backed by a real + // AuthGuard account; reopen it so a corrected retry can proceed. + if unclaimErr := a.db.UnclaimSetup(r.Context()); unclaimErr != nil { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } + writeAuthGuardError(w, err, "Unable to create account") + return + } + + if err := a.db.SetCachedTOTPEnabled(r.Context(), result.User.ID, false); err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - if err := a.startSession(r.Context(), w, user.ID); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role)}) + authclient.ForwardCookies(w, result.Cookies) + writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), result.User)) } func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), localProfile)) + return + } + var request credentialsRequest if err := decodeJSON(r, &request); err != nil { writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") return } - identifier := strings.TrimSpace(request.Identifier) if identifier == "" { identifier = strings.TrimSpace(request.Username) } - if identifier == "" { + if identifier == "" || len([]rune(identifier)) > maxEmailLength { writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error()) return } - if len([]rune(identifier)) > maxEmailLength { - writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error()) + + result, err := a.authGuard.Login(r.Context(), identifier, request.Password, request.TotpToken) + if err != nil { + var apiErr *authclient.APIError + if errors.As(err, &apiErr) { + if apiErr.TOTPRequired { + writeJSONError(w, http.StatusUnauthorized, "Two-factor authentication code required.") + return + } + if apiErr.StatusCode == http.StatusUnauthorized { + writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error()) + return + } + writeAuthGuardError(w, err, "Unable to sign in") + return + } + // A non-APIError here means the call to AuthGuard itself failed + // (transport/connectivity), as opposed to AuthGuard giving a real + // answer we didn't like above; see errAuthGuardUnavailable. + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } - user, err := a.db.getUserByIdentifier(r.Context(), identifier) + + // See this file's top-of-file doc comment: a successful login attempted + // WITHOUT a TOTP token is only possible when the account does not have + // TOTP enabled (AuthGuard would otherwise have rejected it), so this is an + // authoritative point to refresh the local cache. A successful login WITH + // a token is not equally conclusive (AuthGuard ignores an unnecessary + // token for an account that doesn't have TOTP enabled), so the cache is + // left as whatever handleTOTPEnable/Disable last set it to rather than + // guessed at here. + if strings.TrimSpace(request.TotpToken) == "" { + if err := a.db.SetCachedTOTPEnabled(r.Context(), result.User.ID, false); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") + return + } + } + + authclient.ForwardCookies(w, result.Cookies) + writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), result.User)) +} + +func (a *AuthService) handleTOTPStatus(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSON(w, http.StatusOK, map[string]bool{"enabled": false}) + return + } + user, err := a.currentUser(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + if user == nil { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } + enabled, err := a.db.GetCachedTOTPEnabled(r.Context(), user.ID) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - if user == nil || !sharedauth.VerifyPassword(user.PasswordHash, request.Password) { - writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error()) + writeJSON(w, http.StatusOK, map[string]bool{"enabled": enabled}) +} + +// handleTOTPSetup provisions a pending TOTP secret via AuthGuard's POST +// /api/totp/enable (AuthGuard's "enable" is CollabTable's "setup" step -- +// naming differs, the two-step provision-then-confirm flow is identical). +// +// AuthGuard always (re-)provisions regardless of current state; the +// "already enabled" guard CollabTable had locally is reproduced here from +// the local cache to keep the same user-facing contract (the frontend only +// ever shows this action when it believes TOTP is currently off). +func (a *AuthService) handleTOTPSetup(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } - if user.TOTPEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, request.TotpToken, time.Now()) { - writeJSONError(w, http.StatusUnauthorized, "Two-factor authentication code required.") + user, err := a.currentUser(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } - if err := a.startSession(r.Context(), w, user.ID); err != nil { + if user == nil { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } + if enabled, err := a.db.GetCachedTOTPEnabled(r.Context(), user.ID); err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return - } - writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role), TotpEnabled: user.TOTPEnabled}) -} - -type totpTokenRequest struct { - Token string `json:"token"` -} - -func (a *AuthService) handleTOTPStatus(w http.ResponseWriter, _ *http.Request, user *AuthUser) { - writeJSON(w, http.StatusOK, map[string]bool{"enabled": user.TOTPEnabled}) -} - -func (a *AuthService) handleTOTPSetup(w http.ResponseWriter, r *http.Request, user *AuthUser) { - if user.TOTPEnabled { + } else if enabled { writeJSONError(w, http.StatusConflict, "disable two-factor authentication before setting up a new secret") return } - secret, err := sharedauth.GenerateTOTPSecret() + + result, err := a.authGuard.TOTPEnable(r.Context(), a.sessionToken(r)) if err != nil { - writeJSONError(w, http.StatusInternalServerError, "unable to create two-factor setup") + writeAuthGuardError(w, err, "unable to create two-factor setup") return } - if err := a.db.setTOTPSecret(r.Context(), user.ID, secret); err != nil { - writeJSONError(w, http.StatusInternalServerError, "unable to create two-factor setup") - return - } - account := user.Email - if account == "" { - account = user.Username - } writeJSON(w, http.StatusOK, map[string]any{ - "secret": secret, - "otpauthUrl": sharedauth.TOTPProvisioningURI("CollabTable", account, secret), - "enabled": false, + "secret": result.Secret, + "otpauthUrl": result.OTPAuthURL, + "enabled": result.Enabled, }) } -func (a *AuthService) handleTOTPEnable(w http.ResponseWriter, r *http.Request, user *AuthUser) { - var request totpTokenRequest +// handleTOTPEnable confirms a generated code via AuthGuard's POST +// /api/totp/verify, activating two-factor authentication (AuthGuard's +// "verify" is CollabTable's "enable" step; see handleTOTPSetup). +func (a *AuthService) handleTOTPEnable(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + user, err := a.currentUser(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + if user == nil { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } + var request struct { + Token string `json:"token"` + } if err := decodeJSON(r, &request); err != nil { writeJSONError(w, http.StatusBadRequest, "invalid JSON body") return } - secret, _, err := a.db.getTOTPState(r.Context(), user.ID) - if err != nil || !sharedauth.VerifyTOTP(secret, request.Token, time.Now()) { + if err := a.authGuard.TOTPVerify(r.Context(), a.sessionToken(r), request.Token); err != nil { writeJSONError(w, http.StatusUnauthorized, "Invalid authenticator code.") return } - if err := a.db.enableTOTP(r.Context(), user.ID); err != nil { - writeJSONError(w, http.StatusInternalServerError, "unable to enable two-factor authentication") + if err := a.db.SetCachedTOTPEnabled(r.Context(), user.ID, true); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } writeJSON(w, http.StatusOK, map[string]bool{"enabled": true}) } -func (a *AuthService) handleTOTPDisable(w http.ResponseWriter, r *http.Request, user *AuthUser) { - var request totpTokenRequest +func (a *AuthService) handleTOTPDisable(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + user, err := a.currentUser(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + if user == nil { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } + var request struct { + Token string `json:"token"` + } if err := decodeJSON(r, &request); err != nil { writeJSONError(w, http.StatusBadRequest, "invalid JSON body") return } - secret, enabled, err := a.db.getTOTPState(r.Context(), user.ID) - if err != nil || !enabled || !sharedauth.VerifyTOTP(secret, request.Token, time.Now()) { + if err := a.authGuard.TOTPDisable(r.Context(), a.sessionToken(r), request.Token); err != nil { writeJSONError(w, http.StatusUnauthorized, "Invalid authenticator code.") return } - if err := a.db.disableTOTP(r.Context(), user.ID); err != nil { - writeJSONError(w, http.StatusInternalServerError, "unable to disable two-factor authentication") + if err := a.db.SetCachedTOTPEnabled(r.Context(), user.ID, false); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } writeJSON(w, http.StatusOK, map[string]bool{"enabled": false}) } -func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) { - if cookie, err := r.Cookie(sessionCookieName); err == nil && cookie.Value != "" { - if err := a.db.deleteSession(r.Context(), hashToken(cookie.Value)); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return +func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) + return + } + if token := a.sessionToken(r); token != "" { + cookies, err := a.authGuard.Logout(r.Context(), token) + if err != nil { + var apiErr *authclient.APIError + if !errors.As(err, &apiErr) { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") + return + } + // An already-invalid/expired session is fine to treat as "already + // logged out" rather than an error. + } else { + authclient.ForwardCookies(w, cookies) } } - a.clearSessionCookie(w) + a.clearSessionCookies(w) writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } @@ -428,63 +816,103 @@ type updateCredentialsRequest struct { NewPassword *string `json:"newPassword"` } -func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request, user *AuthUser) { +// handleUpdateCredentials lets the caller edit their own username/email/ +// password. See the top-of-file doc comment's "Known gaps" section: +// AuthGuard only exposes account editing through its admin/users endpoint, +// which requires CanManageUsers, so a plain "user"-role account has no +// AuthGuard-backed way to self-edit today. CollabTable's existing frontend +// never sends CurrentPassword (see lib/api.js's updateCredentials), and +// AuthGuard's admin update endpoint has no notion of it either (an +// authorized caller is trusted without re-proving the current password), so +// that field is accepted for backward compatibility but not acted on. +func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + current, token, err := a.currentProfile(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + if current == nil { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } + var request updateCredentialsRequest if err := decodeJSON(r, &request); err != nil { writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") return } - if request.CurrentPassword != nil && *request.CurrentPassword != "" && !sharedauth.VerifyPassword(user.PasswordHash, *request.CurrentPassword) { - writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error()) - return - } - username := user.Username + input := authclient.ManagedUserInput{} if request.NewUsername != nil { - username, _ = normalizeUsername(*request.NewUsername) - if username == "" { - writeJSONError(w, http.StatusBadRequest, errUsernameRequired.Error()) - return - } - } - email := user.Email - if request.NewEmail != nil { - normalized, err := normalizeEmail(*request.NewEmail) + username, err := normalizeUsername(*request.NewUsername) if err != nil { writeJSONError(w, http.StatusBadRequest, err.Error()) return } - email = normalized + input.Username = username + } + if request.NewEmail != nil { + email, err := normalizeEmail(*request.NewEmail) + if err != nil { + writeJSONError(w, http.StatusBadRequest, err.Error()) + return + } + input.Email = email } - - passwordHash := user.PasswordHash if request.NewPassword != nil && *request.NewPassword != "" { if err := validatePassword(*request.NewPassword); err != nil { writeJSONError(w, http.StatusBadRequest, err.Error()) return } - hash, err := sharedauth.HashPassword(*request.NewPassword) - if err != nil { + input.Password = *request.NewPassword + } + if request.NewUsername == nil && request.NewEmail == nil && input.Password == "" { + writeJSONError(w, http.StatusBadRequest, errInvalidAuthInput.Error()) + return + } + + if !sharedauth.CanManageUsers(current.Role) { + writeJSONError(w, http.StatusForbidden, errSelfServiceProfile.Error()) + return + } + + if err := a.authGuard.UpdateManagedUser(r.Context(), token, current.ID, input); err != nil { + writeAuthGuardError(w, err, "Unable to update account") + return + } + + // Match the pre-migration behavior of forcing re-authentication after a + // credential change. AuthGuard's admin-update endpoint does not itself + // invalidate sessions, and there is no self-service "invalidate all my + // other sessions" call, so only the session used for this request is + // guaranteed to be revoked; see the top-of-file doc comment's "Known + // gaps" section. + if _, err := a.authGuard.Logout(r.Context(), token); err != nil { + var apiErr *authclient.APIError + if !errors.As(err, &apiErr) { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - passwordHash = string(hash) } - - if err := a.db.updateUserCredentials(r.Context(), user.ID, username, email, passwordHash); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - if err := a.db.deleteSessionsForUser(r.Context(), user.ID); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - a.clearSessionCookie(w) + a.clearSessionCookies(w) writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } -func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request, user *AuthUser) { - hasToken, err := a.db.hasAPIToken(r.Context(), user.ID) +func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request) { + userID, ok, err := a.currentUserID(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + if !ok { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } + hasToken, err := a.db.hasAPIToken(r.Context(), userID) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return @@ -492,13 +920,22 @@ func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request, writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken}) } -func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request, user *AuthUser) { +func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request) { + userID, ok, err := a.currentUserID(r) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + if !ok { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) + return + } token, err := randomToken() if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - if err := a.db.regenerateAPIToken(r.Context(), user.ID, hashToken(token)); err != nil { + if err := a.db.regenerateAPIToken(r.Context(), userID, hashToken(token)); err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } @@ -513,83 +950,112 @@ type managedUserResponse struct { TotpEnabled bool `json:"totpEnabled"` } -type managedUserRequest struct { - Username string `json:"username"` - Email string `json:"email"` - Password string `json:"password"` - Role *string `json:"role"` +// managedUserView translates an AuthGuard ManagedUser into CollabTable's +// existing response shape. TotpEnabled reflects only what this CollabTable +// instance's local best-effort cache has observed for that account (see the +// top-of-file doc comment's "Known gaps" section) -- AuthGuard's admin/users +// endpoints do not report TOTP status at all, so an account this instance +// has never toggled 2FA for is reported as false regardless of its real +// state. +func (a *AuthService) managedUserView(ctx context.Context, user authclient.ManagedUser) managedUserResponse { + enabled, _ := a.db.GetCachedTOTPEnabled(ctx, user.ID) + return managedUserResponse{ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, TotpEnabled: enabled} } -func managedUserView(user AuthUser) managedUserResponse { - return managedUserResponse{ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, TotpEnabled: user.TOTPEnabled} -} - -func (a *AuthService) requireUserManager(w http.ResponseWriter, user *AuthUser) bool { - if sharedauth.CanManageUsers(user.Role) { - return true +// writeAuthGuardError translates an authclient error into CollabTable's +// {"error": "...", "message": "..."} response shape. AuthGuard's own +// httpapi handlers were built directly from CollabTable's (and the other +// projects') original local implementations, so their status codes and +// messages already match -- AuthGuard's *APIError is forwarded close to +// verbatim rather than re-mapped by hand. A non-APIError (a transport +// failure actually reaching AuthGuard) falls back to a generic 500 with +// fallbackMessage. +func writeAuthGuardError(w http.ResponseWriter, err error, fallbackMessage string) { + var apiErr *authclient.APIError + if errors.As(err, &apiErr) { + writeJSONError(w, apiErr.StatusCode, apiErr.Message) + return } - writeJSONError(w, http.StatusForbidden, "administrator access required") - return false + writeJSONError(w, http.StatusInternalServerError, fallbackMessage) } -func (a *AuthService) handleUsers(w http.ResponseWriter, r *http.Request, actor *AuthUser) { - if !a.requireUserManager(w, actor) { +// handleUsers proxies admin user listing/creation to AuthGuard's +// GET/POST /api/admin/users. Authorization (CanManageUsers) is enforced by +// AuthGuard itself from the forwarded session token; CollabTable does not +// re-implement that check locally, so its 401/403 responses come straight +// from AuthGuard via writeAuthGuardError. See the top-of-file doc comment: +// AuthGuard's admin endpoints enforce the exact same rules CollabTable's +// local implementation did. +func (a *AuthService) handleUsers(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + switch r.Method { + case http.MethodGet: + // Nothing is gated in auth-disabled mode, and an empty list is an + // honest answer: there is no user store to list from. See the + // top-of-file doc comment's "Auth-disabled mode" section. + writeJSON(w, http.StatusOK, []managedUserResponse{}) + case http.MethodPost: + writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + return + } + token := a.sessionToken(r) + if token == "" { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) return } switch r.Method { case http.MethodGet: - users, err := a.db.listUsers(r.Context()) + users, err := a.authGuard.ListManagedUsers(r.Context(), token) if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Unable to list users") + writeAuthGuardError(w, err, "Unable to list users") return } result := make([]managedUserResponse, 0, len(users)) for _, user := range users { - result = append(result, managedUserView(user)) + result = append(result, a.managedUserView(r.Context(), user)) } writeJSON(w, http.StatusOK, result) case http.MethodPost: - var request managedUserRequest - if err := decodeJSON(r, &request); err != nil { + var input authclient.ManagedUserInput + if err := decodeJSON(r, &input); err != nil { writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") return } - username, err := normalizeUsername(request.Username) + created, err := a.authGuard.CreateManagedUser(r.Context(), token, input) if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) + writeAuthGuardError(w, err, "Unable to create user") return } - email, err := normalizeEmail(request.Email) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) + if err := a.db.SetCachedTOTPEnabled(r.Context(), created.ID, false); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - if err := validatePassword(request.Password); err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - hash, err := sharedauth.HashPassword(request.Password) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Unable to create user") - return - } - role := string(sharedauth.RoleUser) - if actor.Role == string(sharedauth.RoleSuperAdmin) && request.Role != nil { - role = string(sharedauth.NormalizeRole(*request.Role)) - } - created, err := a.db.createManagedUser(r.Context(), username, email, string(hash), role) - if err != nil { - writeJSONError(w, http.StatusConflict, "Username or email is already in use.") - return - } - writeJSON(w, http.StatusCreated, managedUserView(*created)) + writeJSON(w, http.StatusCreated, a.managedUserView(r.Context(), *created)) default: w.WriteHeader(http.StatusMethodNotAllowed) } } -func (a *AuthService) handleUser(w http.ResponseWriter, r *http.Request, actor *AuthUser) { - if !a.requireUserManager(w, actor) { +// handleUser proxies admin user update/delete to AuthGuard's +// PUT/DELETE /api/admin/users/{id}. See handleUsers's doc comment: AuthGuard +// enforces authorization (including the "the superadmin account is +// protected" and "this user cannot be deleted" rules) itself. +func (a *AuthService) handleUser(w http.ResponseWriter, r *http.Request) { + if !a.enabled() { + switch r.Method { + case http.MethodPut, http.MethodPatch, http.MethodDelete: + writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + return + } + token := a.sessionToken(r) + if token == "" { + writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) return } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) @@ -597,72 +1063,21 @@ func (a *AuthService) handleUser(w http.ResponseWriter, r *http.Request, actor * writeJSONError(w, http.StatusBadRequest, "Invalid user id") return } - target, err := a.db.getUserByID(r.Context(), id) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Unable to find user") - return - } - if target == nil { - writeJSONError(w, http.StatusNotFound, "User not found") - return - } - if target.Role == string(sharedauth.RoleSuperAdmin) && target.ID != actor.ID { - writeJSONError(w, http.StatusForbidden, "The superadmin account is protected") - return - } - switch r.Method { case http.MethodPut, http.MethodPatch: - var request managedUserRequest - if err := decodeJSON(r, &request); err != nil { + var input authclient.ManagedUserInput + if err := decodeJSON(r, &input); err != nil { writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") return } - username := target.Username - if request.Username != "" { - username, err = normalizeUsername(request.Username) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - } - email := target.Email - if request.Email != "" { - email, err = normalizeEmail(request.Email) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - } - passwordHash := target.PasswordHash - if request.Password != "" { - if err := validatePassword(request.Password); err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - hash, hashErr := sharedauth.HashPassword(request.Password) - if hashErr != nil { - writeJSONError(w, http.StatusInternalServerError, "Unable to update user") - return - } - passwordHash = string(hash) - } - role := target.Role - if actor.Role == string(sharedauth.RoleSuperAdmin) && request.Role != nil && target.Role != string(sharedauth.RoleSuperAdmin) { - role = string(sharedauth.NormalizeRole(*request.Role)) - } - if err := a.db.updateManagedUser(r.Context(), id, username, email, passwordHash, role); err != nil { - writeJSONError(w, http.StatusConflict, "Username or email is already in use.") + if err := a.authGuard.UpdateManagedUser(r.Context(), token, id, input); err != nil { + writeAuthGuardError(w, err, "Unable to update user") return } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) case http.MethodDelete: - if target.ID == actor.ID || target.Role == string(sharedauth.RoleSuperAdmin) { - writeJSONError(w, http.StatusForbidden, "This user cannot be deleted") - return - } - if err := a.db.deleteUser(r.Context(), id); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Unable to delete user") + if err := a.authGuard.DeleteManagedUser(r.Context(), token, id); err != nil { + writeAuthGuardError(w, err, "Unable to delete user") return } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) diff --git a/backend/auth_test.go b/backend/auth_test.go new file mode 100644 index 0000000..38b038d --- /dev/null +++ b/backend/auth_test.go @@ -0,0 +1,194 @@ +package main + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" +) + +// unreachableAuthGuardClient returns an authclient.Client pointed at a real +// address that is guaranteed to refuse the connection: an httptest.Server +// that has already been closed. This exercises a genuine transport-level +// failure (connection refused), the same failure mode as "AUTHGUARD_URL is +// configured but AuthGuard is down/unreachable", rather than simulating it by +// hand. +func unreachableAuthGuardClient(t *testing.T) *authclient.Client { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + url := srv.URL + srv.Close() + return authclient.New(url) +} + +func TestAuthNormalization(t *testing.T) { + username, err := normalizeUsername(" admin ") + if err != nil || username != "admin" { + t.Fatalf("normalizeUsername() = %q, %v", username, err) + } + + email, err := normalizeEmail(" Admin@Example.COM ") + if err != nil || email != "admin@example.com" { + t.Fatalf("normalizeEmail() = %q, %v", email, err) + } + + if err := validatePassword("short"); err == nil { + t.Fatal("validatePassword() accepted a short password") + } +} + +func TestSessionTokenReadsAuthGuardCookie(t *testing.T) { + a := &AuthService{} + req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil) + req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"}) + + if got := a.sessionToken(req); got != "sometoken" { + t.Fatalf("sessionToken() = %q, want %q", got, "sometoken") + } +} + +func TestSessionTokenIgnoresLegacyCookieName(t *testing.T) { + // The pre-migration collabtable_session cookie is no longer read as a + // session credential; only AuthGuard's own auth_session cookie is. + a := &AuthService{} + req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil) + req.AddCookie(&http.Cookie{Name: legacySessionCookieName, Value: "stale-value"}) + + if got := a.sessionToken(req); got != "" { + t.Fatalf("sessionToken() = %q, want empty for a legacy-only cookie", got) + } +} + +func TestWriteAuthGuardErrorForwardsAPIError(t *testing.T) { + rec := httptest.NewRecorder() + writeAuthGuardError(rec, &authclient.APIError{StatusCode: http.StatusConflict, Message: "username or email is already in use"}, "fallback") + + if rec.Code != http.StatusConflict { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusConflict) + } + if body := rec.Body.String(); body == "" { + t.Fatal("response body was empty") + } +} + +func TestWriteAuthGuardErrorFallsBackForTransportFailures(t *testing.T) { + rec := httptest.NewRecorder() + writeAuthGuardError(rec, errors.New("dial tcp: connection refused"), "unable to reach AuthGuard") + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError) + } +} + +func TestCurrentUserIDUsesPlaceholderWhenAuthDisabled(t *testing.T) { + a := &AuthService{} + req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil) + + id, ok, err := a.currentUserID(req) + if err != nil { + t.Fatalf("currentUserID() error = %v, want nil in disabled mode", err) + } + if !ok { + t.Fatal("currentUserID() ok = false, want true in disabled mode (every request shares the placeholder identity)") + } + if id != localProfile.ID { + t.Fatalf("currentUserID() id = %d, want %d (localProfile.ID)", id, localProfile.ID) + } +} + +func TestRequireSessionLetsRequestThroughWhenAuthDisabled(t *testing.T) { + a := &AuthService{} + nextCalled := false + handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + nextCalled = true + })) + + req := httptest.NewRequest(http.MethodGet, "/api/tech-stack", nil) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + if !nextCalled { + t.Fatal("requireSession did not let the request through despite auth being disabled (AUTHGUARD_URL unset)") + } + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } +} + +// The following tests cover the specific failure mode of AUTHGUARD_URL being +// configured but AuthGuard being unreachable (connection refused). This must +// never be silently treated as "no session" (which would either let an +// unauthenticated request through, for requireSession, or show a bare "please +// log in" screen with no indication anything is wrong, for handleStatus) -- +// it must surface as a distinct, visible error. See currentUser/ +// currentProfile's doc comments and errAuthGuardUnavailable. + +func TestCurrentUserSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) { + a := &AuthService{authGuard: unreachableAuthGuardClient(t)} + req := httptest.NewRequest(http.MethodGet, "/api/status", nil) + req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"}) + + user, err := a.currentUser(req) + if err == nil { + t.Fatal("currentUser() returned no error for an unreachable AuthGuard; want a transport error") + } + if errors.Is(err, authclient.ErrInvalidSession) { + t.Fatal("currentUser() classified a transport failure as ErrInvalidSession -- this would make requireSession treat 'AuthGuard is down' as 'not logged in' instead of a 500") + } + if user != nil { + t.Fatalf("currentUser() returned a user (%+v) despite AuthGuard being unreachable", user) + } +} + +func TestCurrentProfileSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) { + a := &AuthService{authGuard: unreachableAuthGuardClient(t)} + req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil) + req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"}) + + profile, token, err := a.currentProfile(req) + if err == nil { + t.Fatal("currentProfile() returned no error for an unreachable AuthGuard; want a transport error") + } + if profile != nil { + t.Fatalf("currentProfile() returned a profile (%+v) despite AuthGuard being unreachable", profile) + } + if token != "" { + t.Fatalf("currentProfile() returned a token (%q) alongside an error", token) + } +} + +func TestCurrentUserIDSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) { + a := &AuthService{authGuard: unreachableAuthGuardClient(t)} + req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil) + req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"}) + + if _, ok, err := a.currentUserID(req); err == nil || ok { + t.Fatalf("currentUserID() = (ok=%v, err=%v), want ok=false and a non-nil transport error", ok, err) + } +} + +func TestRequireSessionReturns500RatherThanLettingRequestThroughWhenAuthGuardUnreachable(t *testing.T) { + a := &AuthService{authGuard: unreachableAuthGuardClient(t)} + nextCalled := false + handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + nextCalled = true + })) + + req := httptest.NewRequest(http.MethodGet, "/api/status", nil) + req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"}) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + if nextCalled { + t.Fatal("requireSession let the request through to the wrapped handler despite AuthGuard being unreachable") + } + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want %d (must not be 401 'please log in' or 200)", rec.Code, http.StatusInternalServerError) + } + if body := rec.Body.String(); !strings.Contains(strings.ToLower(body), "authentication service") { + t.Fatalf("response body = %q, want a message identifying the authentication service as the problem", body) + } +} diff --git a/backend/db.go b/backend/db.go index 4d011ce..ef50202 100644 --- a/backend/db.go +++ b/backend/db.go @@ -9,7 +9,6 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" - sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres" ) @@ -100,6 +99,15 @@ func (d *DB) initSchema(ctx context.Context) error { ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start'; + -- auth_users/auth_sessions are RETIRED as of the AuthGuard migration: + -- account and session state now lives in AuthGuard's own database, + -- reached over HTTP via authclient (see auth.go). These two tables and + -- their schema are deliberately left in place rather than dropped -- + -- dropping tables/data is a separate, more destructive decision outside + -- the scope of that migration -- but no Go code reads or writes them for + -- authentication purposes anymore. pruneExpiredSessions keeps running + -- only as harmless best-effort cleanup of whatever rows a pre-migration + -- deployment already had. CREATE TABLE IF NOT EXISTS auth_users ( id BIGSERIAL PRIMARY KEY, username TEXT NOT NULL UNIQUE, @@ -131,13 +139,53 @@ func (d *DB) initSchema(ctx context.Context) error { CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions(expires_at); CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions(user_id); + -- collabtable_setup_state tracks only whether THIS CollabTable instance + -- has completed its one-time "create the first account" setup flow + -- against AuthGuard (see handleSetup in auth.go). It intentionally holds + -- no credentials or account identity of its own -- AuthGuard is the sole + -- source of truth for accounts -- just the boolean that used to be + -- derived from "COUNT(*) FROM auth_users" before the migration. + CREATE TABLE IF NOT EXISTS collabtable_setup_state ( + id SMALLINT PRIMARY KEY DEFAULT 1, + claimed BOOLEAN NOT NULL DEFAULT FALSE, + claimed_at TIMESTAMPTZ, + CHECK (id = 1) + ); + + -- authguard_totp_cache is a best-effort, locally-cached mirror of "does + -- this AuthGuard account have TOTP enabled", keyed by AuthGuard's own + -- numeric user id. AuthGuard's HTTP API (deliberately not modified by + -- this migration) has no endpoint to query current TOTP status, only to + -- enable/verify/disable it, so CollabTable keeps this cache updated + -- itself at every point it can observe the true state (successful TOTP + -- verify/disable calls, and a successful login attempted without a TOTP + -- token, which AuthGuard would have rejected had TOTP been enabled). See + -- handleTOTPStatus's doc comment in auth.go for the full reasoning and + -- its known staleness caveat. + CREATE TABLE IF NOT EXISTS authguard_totp_cache ( + authguard_user_id BIGINT PRIMARY KEY, + totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + + -- api_tokens backs the long-lived per-account bearer token CollabTable's + -- own devices use for the sync API (requireAPIToken in auth.go) -- a + -- concern entirely separate from browser-session auth, so it is NOT + -- proxied to AuthGuard. Its user_id used to be a foreign key into this + -- database's own auth_users; now that account identity lives in + -- AuthGuard (or, when AUTHGUARD_URL is unset, every caller shares the + -- fixed placeholder id 0 -- see localProfile/currentUserID in auth.go), + -- user_id is just an opaque identity id with no matching row in the + -- (now dormant) local auth_users table, so the FK constraint a + -- pre-migration deployment already has is dropped below. CREATE TABLE IF NOT EXISTS api_tokens ( id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE, + user_id BIGINT NOT NULL, token_hash TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id); + ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey; `) if err != nil { return fmt.Errorf("initialize schema: %w", err) @@ -181,210 +229,86 @@ func (d *DB) cleanupNotifications(ctx context.Context) { } } -type AuthUser struct { - ID int64 - Username string - Email string - PasswordHash string - TOTPSecret string - TOTPEnabled bool - Role string -} +// --- AuthGuard migration: local-only auxiliary state ------------------------ +// +// Everything below is new state introduced by the AuthGuard migration. None +// of it is account/credential data -- that all lives in AuthGuard now -- it +// is bookkeeping CollabTable keeps about itself. See auth.go for how each is +// used. -var ErrSingletonUserExists = errors.New("a user already exists") - -func (d *DB) countUsers(ctx context.Context) (int, error) { - var count int - if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil { - return 0, fmt.Errorf("count users: %w", err) - } - return count, nil -} - -func (d *DB) deleteAllUsers(ctx context.Context) error { - if _, err := d.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil { - return fmt.Errorf("delete all users: %w", err) - } - return nil -} - -func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) { - var user AuthUser - err := d.pool.QueryRow(ctx, ` - INSERT INTO auth_users (username, email, password_hash, role, updated_at) - VALUES ($1, $2, $3, 'superadmin', now()) - RETURNING id, username, email, role - `, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email, &user.Role) - if err != nil { - if sharedpostgres.IsUniqueViolation(err) { - return nil, ErrSingletonUserExists - } - return nil, fmt.Errorf("create user: %w", err) - } - user.PasswordHash = passwordHash - return &user, nil -} - -func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) { - var user AuthUser - err := d.pool.QueryRow(ctx, ` - SELECT id, username, email, password_hash, COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(role, 'user') - FROM auth_users - WHERE username = $1 OR lower(email) = lower($1) - `, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role) +// IsSetupClaimed reports whether this CollabTable instance has already +// completed its one-time setup flow (see TryClaimSetup). +func (d *DB) IsSetupClaimed(ctx context.Context) (bool, error) { + var claimed bool + err := d.pool.QueryRow(ctx, `SELECT claimed FROM collabtable_setup_state WHERE id = 1`).Scan(&claimed) if errors.Is(err, pgx.ErrNoRows) { - return nil, nil + return false, nil } if err != nil { - return nil, fmt.Errorf("get user: %w", err) + return false, fmt.Errorf("check setup claim: %w", err) } - return &user, nil + return claimed, nil } -func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) { - var user AuthUser - err := d.pool.QueryRow(ctx, ` - SELECT u.id, u.username, u.email, u.password_hash, COALESCE(u.totp_secret, ''), COALESCE(u.totp_enabled, false), COALESCE(u.role, 'user') - FROM auth_sessions s - JOIN auth_users u ON u.id = s.user_id - WHERE s.token_hash = $1 AND s.expires_at > now() - `, tokenHash).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role) - if errors.Is(err, pgx.ErrNoRows) { - return nil, nil - } - if err != nil { - return nil, fmt.Errorf("get session user: %w", err) - } - return &user, nil -} - -func (d *DB) createSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error { - _, err := d.pool.Exec(ctx, ` - INSERT INTO auth_sessions (user_id, token_hash, expires_at) - VALUES ($1, $2, $3) - `, userID, tokenHash, expiresAt) - if err != nil { - return fmt.Errorf("create session: %w", err) - } - return nil -} - -func (d *DB) deleteSession(ctx context.Context, tokenHash string) error { - _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash) - if err != nil { - return fmt.Errorf("delete session: %w", err) - } - return nil -} - -func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, email, passwordHash string) error { - _, err := d.pool.Exec(ctx, ` - UPDATE auth_users - SET username = $1, email = $2, password_hash = $3, updated_at = now() - WHERE id = $4 - `, username, email, passwordHash, userID) - if err != nil { - return fmt.Errorf("update user credentials: %w", err) - } - return nil -} - -func (d *DB) listUsers(ctx context.Context) ([]AuthUser, error) { - rows, err := d.pool.Query(ctx, ` - SELECT id, username, email, COALESCE(role, 'user'), COALESCE(totp_enabled, false) - FROM auth_users ORDER BY created_at, id +// TryClaimSetup atomically flips the local "setup completed" flag from +// unclaimed to claimed and reports whether this call was the one that did so. +// A caller that wins the claim but then fails to actually create the +// AuthGuard account (e.g. a validation error, or AuthGuard being unreachable) +// must call UnclaimSetup to reopen the slot for a later retry. +func (d *DB) TryClaimSetup(ctx context.Context) (bool, error) { + tag, err := d.pool.Exec(ctx, ` + INSERT INTO collabtable_setup_state (id, claimed, claimed_at) VALUES (1, TRUE, now()) + ON CONFLICT (id) DO UPDATE SET claimed = TRUE, claimed_at = now() + WHERE collabtable_setup_state.claimed = FALSE `) if err != nil { - return nil, fmt.Errorf("list users: %w", err) + return false, fmt.Errorf("claim setup: %w", err) } - defer rows.Close() - users := make([]AuthUser, 0) - for rows.Next() { - var user AuthUser - if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.TOTPEnabled); err != nil { - return nil, fmt.Errorf("scan user: %w", err) - } - users = append(users, user) - } - return users, rows.Err() + return tag.RowsAffected() > 0, nil } -func (d *DB) getUserByID(ctx context.Context, id int64) (*AuthUser, error) { - var user AuthUser - err := d.pool.QueryRow(ctx, ` - SELECT id, username, email, password_hash, COALESCE(totp_secret, ''), - COALESCE(totp_enabled, false), COALESCE(role, 'user') - FROM auth_users WHERE id = $1 - `, id).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role) - if errors.Is(err, pgx.ErrNoRows) { - return nil, nil - } - if err != nil { - return nil, fmt.Errorf("get user by id: %w", err) - } - return &user, nil -} - -func (d *DB) createManagedUser(ctx context.Context, username, email, passwordHash, role string) (*AuthUser, error) { - var user AuthUser - err := d.pool.QueryRow(ctx, ` - INSERT INTO auth_users (username, email, password_hash, role, updated_at) - VALUES ($1, $2, $3, $4, now()) - RETURNING id, username, email, role - `, username, email, passwordHash, sharedauth.NormalizeRole(role)).Scan(&user.ID, &user.Username, &user.Email, &user.Role) - if err != nil { - if sharedpostgres.IsUniqueViolation(err) { - return nil, ErrSingletonUserExists - } - return nil, fmt.Errorf("create managed user: %w", err) - } - return &user, nil -} - -func (d *DB) updateManagedUser(ctx context.Context, id int64, username, email, passwordHash, role string) error { - _, err := d.pool.Exec(ctx, ` - UPDATE auth_users SET username = $1, email = $2, password_hash = $3, role = $4, updated_at = now() - WHERE id = $5 - `, username, email, passwordHash, sharedauth.NormalizeRole(role), id) - if err != nil { - return fmt.Errorf("update managed user: %w", err) +// UnclaimSetup reopens the setup flow after a claimed-but-failed setup +// attempt (see TryClaimSetup). +func (d *DB) UnclaimSetup(ctx context.Context) error { + if _, err := d.pool.Exec(ctx, `UPDATE collabtable_setup_state SET claimed = FALSE, claimed_at = NULL WHERE id = 1`); err != nil { + return fmt.Errorf("unclaim setup: %w", err) } return nil } -func (d *DB) deleteUser(ctx context.Context, id int64) error { - if _, err := d.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil { - return fmt.Errorf("delete user: %w", err) - } - return nil +// ClearSetupClaim resets the local "setup completed" flag so the setup screen +// reappears. Used by the local break-glass password-reset flow (see +// handleResetConfirm in auth.go) -- it deliberately does not touch the +// underlying AuthGuard account at all. +func (d *DB) ClearSetupClaim(ctx context.Context) error { + return d.UnclaimSetup(ctx) } -func (d *DB) getTOTPState(ctx context.Context, userID int64) (string, bool, error) { - var secret string +// GetCachedTOTPEnabled returns the best-effort locally-cached TOTP-enabled +// state for an AuthGuard account, or false if this instance has never +// observed that account's TOTP state. See handleTOTPStatus's doc comment in +// auth.go. +func (d *DB) GetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64) (bool, error) { var enabled bool - err := d.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&secret, &enabled) - return secret, enabled, err -} - -func (d *DB) setTOTPSecret(ctx context.Context, userID int64, secret string) error { - _, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID) - return err -} - -func (d *DB) enableTOTP(ctx context.Context, userID int64) error { - _, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID) - return err -} - -func (d *DB) disableTOTP(ctx context.Context, userID int64) error { - _, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID) - return err -} - -func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error { - _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID) + err := d.pool.QueryRow(ctx, `SELECT totp_enabled FROM authguard_totp_cache WHERE authguard_user_id = $1`, authGuardUserID).Scan(&enabled) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } if err != nil { - return fmt.Errorf("delete sessions for user: %w", err) + return false, fmt.Errorf("get cached totp state: %w", err) + } + return enabled, nil +} + +// SetCachedTOTPEnabled upserts the best-effort locally-cached TOTP-enabled +// state for an AuthGuard account. +func (d *DB) SetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64, enabled bool) error { + _, err := d.pool.Exec(ctx, ` + INSERT INTO authguard_totp_cache (authguard_user_id, totp_enabled, updated_at) VALUES ($1, $2, now()) + ON CONFLICT (authguard_user_id) DO UPDATE SET totp_enabled = $2, updated_at = now() + `, authGuardUserID, enabled) + if err != nil { + return fmt.Errorf("set cached totp state: %w", err) } return nil } diff --git a/backend/server.go b/backend/server.go index 8456c58..c9b934b 100644 --- a/backend/server.go +++ b/backend/server.go @@ -15,6 +15,8 @@ import ( "time" _ "github.com/joho/godotenv/autoload" + + authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" ) // The SvelteKit build is copied here by the Docker builder before go build. @@ -50,7 +52,20 @@ func main() { go database.pruneExpiredSessions(ctx) go database.cleanupNotifications(ctx) - auth := newAuthService(database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true")) + // AuthGuard is optional (see auth.go's top-of-file "Auth-disabled mode" + // section): a nil client means every request is treated as already + // authenticated, with nothing gated -- an explicit choice for local + // development or a standalone deployment, not a degraded fallback. + authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL")) + var authGuard *authclient.Client + if authGuardURL != "" { + authGuard = authclient.New(authGuardURL) + fmt.Printf("auth: AuthGuard at %s\n", authGuardURL) + } else { + fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated") + } + + auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true")) server := &Server{db: database, auth: auth, startTime: time.Now()} webRoot, err := fs.Sub(webFS, "web") @@ -121,19 +136,19 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) { mux.HandleFunc("POST /api/auth/reset/confirm", s.auth.handleResetConfirm) mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup) mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin) - mux.Handle("POST /api/auth/logout", s.auth.requireSession(s.auth.handleLogout)) - mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials)) - mux.Handle("GET /api/auth/users", s.auth.requireSession(s.auth.handleUsers)) - mux.Handle("POST /api/auth/users", s.auth.requireSession(s.auth.handleUsers)) - mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser)) - mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser)) - mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser)) - mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(s.auth.handleTOTPStatus)) - mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(s.auth.handleTOTPSetup)) - mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(s.auth.handleTOTPEnable)) - mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(s.auth.handleTOTPDisable)) - mux.Handle("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus)) - mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate)) + mux.Handle("POST /api/auth/logout", s.auth.requireSession(http.HandlerFunc(s.auth.handleLogout))) + mux.Handle("POST /api/auth/credentials", s.auth.requireSession(http.HandlerFunc(s.auth.handleUpdateCredentials))) + mux.Handle("GET /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers))) + mux.Handle("POST /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers))) + mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser))) + mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser))) + mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser))) + mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPStatus))) + mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPSetup))) + mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPEnable))) + mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPDisable))) + mux.Handle("GET /api/auth/token/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenStatus))) + mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenRegenerate))) // Sync/collaboration API routes use a long-lived bearer token shared by the // user's devices. This is deliberately separate from browser sessions. @@ -163,8 +178,8 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) { // The dashboard is a public SPA shell, but its data and tech-stack endpoints // are protected by the browser session. - mux.Handle("GET /api/tech-stack", s.auth.requireSession(s.handleTechStack)) - mux.Handle("GET /web/data", s.auth.requireSession(s.handleWebData)) + mux.Handle("GET /api/tech-stack", s.auth.requireSession(http.HandlerFunc(s.handleTechStack))) + mux.Handle("GET /web/data", s.auth.requireSession(http.HandlerFunc(s.handleWebData))) mux.Handle("/", spaFileServer(webRoot)) } @@ -274,7 +289,7 @@ type stackEntry struct { Value string `json:"value"` } -func (s *Server) handleTechStack(w http.ResponseWriter, _ *http.Request, _ *AuthUser) { +func (s *Server) handleTechStack(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, techStackResponse{ AppVersion: envOrDefault("APP_VERSION", "dev"), Stack: []stackEntry{ diff --git a/backend/web.go b/backend/web.go index e003af9..34c4214 100644 --- a/backend/web.go +++ b/backend/web.go @@ -6,7 +6,7 @@ import ( "time" ) -func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request, _ *AuthUser) { +func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) { lists, err := s.db.queryLists(r.Context(), false, nil) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data") diff --git a/shared/backend/README.md b/shared/backend/README.md index 7d4f5d5..2beb52c 100644 --- a/shared/backend/README.md +++ b/shared/backend/README.md @@ -6,7 +6,9 @@ services, not application-specific SQL or HTTP handlers. - `config` — environment string, required value, boolean, integer, and duration helpers. - `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification. - `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence. +- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. - `migrate` — embedded filesystem adapter for Goose migrations. +- `logshipper` — client adapter for LoggingServer (Web/LoggingServer): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package. Run `go test ./...` and `go vet ./...` from this directory. The module path is `repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is diff --git a/shared/backend/authclient/client.go b/shared/backend/authclient/client.go new file mode 100644 index 0000000..ab0277d --- /dev/null +++ b/shared/backend/authclient/client.go @@ -0,0 +1,497 @@ +// Package authclient is how any Go service in this workspace adopts a +// centralized AuthServer (see the AuthServer project, a sibling of this +// shared/backend module) instead of embedding shared/backend/auth's +// Store directly against its own private database. +// +// A service that switches to AuthServer trades "its own local user table" +// for "one HTTP call per request to AuthServer's /api/session/validate", +// gaining a single shared identity across every project that does the +// same. This package is additive: it does not change how +// shared/backend/auth works, and no project in this workspace is wired up +// to use it yet — that migration is a deliberate per-project decision, not +// something this package does automatically. See AuthServer/README.md's +// "Migration notes" section. +package authclient + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +// User is the account AuthServer resolved for a validated session. It +// mirrors the fields returned by GET /api/session/validate. +type User struct { + ID int64 `json:"user_id"` + Username string `json:"username"` + Role string `json:"role"` +} + +// ErrInvalidSession is returned by Validate when AuthServer reports the +// token/cookie as not currently valid (expired, unknown, or missing). +var ErrInvalidSession = errors.New("authclient: invalid or missing session") + +// DefaultCookieName is the session cookie AuthServer sets and reads +// (AuthServer's own httpapi.SessionCookieName). A service that forwards +// AuthServer's Set-Cookie header straight through to its own browser client +// (see the "Cookie forwarding" note below) ends up reading this same cookie +// name back off incoming requests, so it is exported here rather than left +// as an unexported default only Middleware can see. +const DefaultCookieName = "auth_session" + +// Client calls a centralized AuthServer instance over HTTP. +type Client struct { + // BaseURL is AuthServer's base URL, e.g. "https://auth.example.com" + // (no trailing slash required). + baseURL string + // HTTPClient is used for every request; defaults to a client with a + // short timeout suitable for a per-request auth check. + httpClient *http.Client + // CookieName is the cookie this client looks for on incoming requests + // when Middleware has no Authorization header to use. Defaults to + // "auth_session", matching AuthServer's SessionCookieName. + cookieName string +} + +// Option configures optional Client behavior. +type Option func(*Client) + +// WithHTTPClient overrides the default HTTP client (e.g. to tune timeouts +// or transport pooling). +func WithHTTPClient(hc *http.Client) Option { + return func(c *Client) { c.httpClient = hc } +} + +// WithCookieName overrides the cookie name Middleware reads from incoming +// requests. Only needed if the AuthServer deployment was configured with a +// non-default session cookie name. +func WithCookieName(name string) Option { + return func(c *Client) { c.cookieName = name } +} + +// New creates a Client for the AuthServer instance at baseURL. +func New(baseURL string, opts ...Option) *Client { + c := &Client{ + baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), + httpClient: &http.Client{Timeout: 5 * time.Second}, + cookieName: DefaultCookieName, + } + for _, opt := range opts { + opt(c) + } + return c +} + +// Validate calls AuthServer's GET /api/session/validate with token as a +// Bearer credential and returns the resolved user. It returns +// ErrInvalidSession (wrapped) when AuthServer reports the session as not +// valid, and a plain error for any transport/decoding failure. +func (c *Client) Validate(ctx context.Context, token string) (*User, error) { + if c == nil || c.baseURL == "" { + return nil, errors.New("authclient: client has no base URL") + } + token = strings.TrimSpace(token) + if token == "" { + return nil, ErrInvalidSession + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/session/validate", nil) + if err != nil { + return nil, fmt.Errorf("authclient: build request: %w", err) + } + req.Header.Set("Authorization", "Bearer "+token) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("authclient: call AuthServer: %w", err) + } + defer resp.Body.Close() + + var payload struct { + Valid bool `json:"valid"` + UserID int64 `json:"user_id"` + Username string `json:"username"` + Role string `json:"role"` + } + if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { + if resp.StatusCode == http.StatusUnauthorized { + return nil, ErrInvalidSession + } + return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err) + } + + if resp.StatusCode != http.StatusOK || !payload.Valid { + return nil, ErrInvalidSession + } + return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil +} + +// contextKey is unexported so only this package can set/read the resolved +// user on a request context. +type contextKey struct{} + +var userContextKey contextKey + +// UserFromContext returns the user Middleware attached to the request +// context, or nil if none is present (e.g. called outside Middleware). +func UserFromContext(ctx context.Context) *User { + user, _ := ctx.Value(userContextKey).(*User) + return user +} + +// Middleware extracts the session token from an incoming request — the +// cookie named by WithCookieName (default "auth_session"), falling back to +// an Authorization: Bearer header — validates it against AuthServer, and +// either responds 401 or attaches the resolved *User to the request +// context (retrieve it with UserFromContext) before calling next. +func (c *Client) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := c.tokenFromRequest(r) + user, err := c.Validate(r.Context(), token) + if err != nil { + status := http.StatusUnauthorized + if !errors.Is(err, ErrInvalidSession) { + // A transport/decoding failure talking to AuthServer is not + // the same as "this visitor is unauthenticated"; still fail + // closed (401) rather than letting the request through, but + // keep the two cases distinguishable for callers that want + // to log or alert differently. + status = http.StatusUnauthorized + } + http.Error(w, "authentication required", status) + return + } + r = r.WithContext(context.WithValue(r.Context(), userContextKey, user)) + next.ServeHTTP(w, r) + }) +} + +func (c *Client) tokenFromRequest(r *http.Request) string { + if header := r.Header.Get("Authorization"); header != "" { + if token, ok := strings.CutPrefix(header, "Bearer "); ok { + if token = strings.TrimSpace(token); token != "" { + return token + } + } + } + if cookie, err := r.Cookie(c.cookieName); err == nil { + return cookie.Value + } + return "" +} + +// --- Full API surface ------------------------------------------------------- +// +// Validate/Middleware above are all a service needs when it only ever +// forwards an already-established AuthServer session to check it's still +// valid. A service that used to run its own local register/login/logout/ +// TOTP/password-reset/admin-user-management flow (backed by its own copy of +// shared/backend/auth's Store) and is migrating that flow onto AuthServer +// instead needs to originate those same calls itself — that's what the rest +// of this file adds. Every method mirrors one of AuthServer's +// internal/httpapi handlers exactly (method, path, request/response JSON +// shape); see AuthServer/README.md's HTTP API table and +// AuthServer/internal/httpapi/*.go for the source of truth this was written +// against. +// +// # Cookie forwarding +// +// Register and Login both return the Set-Cookie header(s) AuthServer's +// response carried, as SessionResult.Cookies (Logout returns them directly). +// A service proxying its own e.g. POST /login to AuthServer's POST +// /api/login should generally pass these straight through to its own +// http.ResponseWriter with ForwardCookies (or by hand with http.SetCookie): +// the browser then transparently holds AuthServer's own auth_session cookie +// under whatever Domain/Secure/SameSite/Max-Age AuthServer was configured +// with (see AUTH_COOKIE_DOMAIN in AuthServer's README for the cross-project +// SSO implications of that Domain scope), and every subsequent request's +// session token is that same cookie value — no separate mapping between "the +// proxying service's own session cookie" and "the AuthServer token" is +// needed anywhere. A service adopting this pattern should stop minting a +// session cookie of its own and read/forward the incoming auth_session +// cookie the same way Middleware does (see tokenFromRequest). + +// PublicUser is the account payload register/login/me return: {"id", +// "username", "email", "role"}. It is deliberately distinct from the slimmer +// User type Validate/Middleware use (which mirrors GET +// /api/session/validate's {"user_id", "username", "role"} instead). +type PublicUser struct { + ID int64 `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Role string `json:"role"` +} + +// ManagedUser is one row of GET /api/admin/users, and the payload returned +// by CreateManagedUser. It additionally carries CreatedAt, which PublicUser +// does not. +type ManagedUser struct { + ID int64 `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Role string `json:"role"` + CreatedAt time.Time `json:"created_at"` +} + +// SessionResult is returned by Register and Login: the account AuthServer +// resolved, plus the Set-Cookie header(s) its response carried. See the +// "Cookie forwarding" note above. +type SessionResult struct { + User PublicUser + Cookies []*http.Cookie +} + +// TOTPEnableResult is returned by TOTPEnable: a freshly provisioned, not yet +// active TOTP secret and its otpauth:// URI for a QR code / authenticator +// app. Confirm it with TOTPVerify. +type TOTPEnableResult struct { + Secret string `json:"secret"` + OTPAuthURL string `json:"otpauth_url"` + Enabled bool `json:"enabled"` +} + +// ManagedUserInput is the body of CreateManagedUser (POST /api/admin/users) +// and UpdateManagedUser (PUT /api/admin/users/{id}). On update, a zero-value +// Username/Email/Password field means "leave unchanged" (AuthServer applies +// only non-empty fields), and Role is only honored when AuthServer's own +// authorization rules let the caller reassign it (only a superadmin actor, +// and never onto/away from a superadmin target) — see AuthServer's +// admin_users.go doc comments for the exact rules, which this client does +// not re-implement or pre-validate. +type ManagedUserInput struct { + Username string `json:"username,omitempty"` + Email string `json:"email,omitempty"` + Password string `json:"password,omitempty"` + Role *string `json:"role,omitempty"` +} + +// APIError is returned when AuthServer responds with a non-2xx status. It +// carries the status code and (when AuthServer's JSON body decoded +// successfully) its {"error": "..."} message, so a caller can map it back +// onto its own service's response shape/status code rather than exposing +// AuthServer's wording verbatim. Use errors.As to recover it. +type APIError struct { + StatusCode int + Message string + // TOTPRequired is set only by Login, mirroring AuthServer's + // {"totp_required": true} flag on a 401 that means "credentials were + // correct, but this account has two-factor auth enabled and no (or an + // incorrect) code was supplied" — distinct from a plain invalid- + // credentials 401. + TOTPRequired bool +} + +func (e *APIError) Error() string { + return fmt.Sprintf("authclient: authserver responded %d: %s", e.StatusCode, e.Message) +} + +// ForwardCookies re-sets each cookie (typically SessionResult.Cookies or +// Logout's return value) on w. This is the mechanical half of the "cookie +// forwarding" pattern described above. +func ForwardCookies(w http.ResponseWriter, cookies []*http.Cookie) { + for _, cookie := range cookies { + if cookie != nil { + http.SetCookie(w, cookie) + } + } +} + +// call is the shared request/response plumbing for every method below: it +// builds a JSON request (skipped when body is nil), attaches token as a +// Bearer credential (skipped when token is ""), and on a 2xx response +// decodes the JSON body into out (skipped when out is nil). A non-2xx +// response is translated into *APIError. The returned *http.Response (nil +// on a transport-level failure) is provided so callers can read Cookies(); +// its Body is always already fully read and closed. +func (c *Client) call(ctx context.Context, method, path, token string, body, out any) (*http.Response, error) { + if c == nil || c.baseURL == "" { + return nil, errors.New("authclient: client has no base URL") + } + + var reader io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("authclient: encode request body: %w", err) + } + reader = bytes.NewReader(data) + } + req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader) + if err != nil { + return nil, fmt.Errorf("authclient: build request: %w", err) + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("authclient: call AuthServer: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + var payload struct { + Error string `json:"error"` + TOTPRequired bool `json:"totp_required"` + } + _ = json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&payload) + message := payload.Error + if message == "" { + message = resp.Status + } + return resp, &APIError{StatusCode: resp.StatusCode, Message: message, TOTPRequired: payload.TOTPRequired} + } + if out != nil { + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out); err != nil { + return resp, fmt.Errorf("authclient: decode AuthServer response: %w", err) + } + } + return resp, nil +} + +// Register calls POST /api/register, creating a new AuthServer account and +// starting a session for it. +func (c *Client) Register(ctx context.Context, username, email, password string) (*SessionResult, error) { + var out struct { + User PublicUser `json:"user"` + } + body := map[string]string{"username": username, "email": email, "password": password} + resp, err := c.call(ctx, http.MethodPost, "/api/register", "", body, &out) + if err != nil { + return nil, err + } + return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil +} + +// Login calls POST /api/login. totpToken may be empty; AuthServer returns an +// *APIError with TOTPRequired set when the account has two-factor auth +// enabled and no valid code was supplied. +func (c *Client) Login(ctx context.Context, usernameOrEmail, password, totpToken string) (*SessionResult, error) { + var out struct { + User PublicUser `json:"user"` + } + body := map[string]string{"username_or_email": usernameOrEmail, "password": password} + if totpToken != "" { + body["totp_token"] = totpToken + } + resp, err := c.call(ctx, http.MethodPost, "/api/login", "", body, &out) + if err != nil { + return nil, err + } + return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil +} + +// Logout calls POST /api/logout, deleting the session identified by token +// server-side. It returns the (cookie-clearing) Set-Cookie header(s) +// AuthServer's response carried; see ForwardCookies. +func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, error) { + resp, err := c.call(ctx, http.MethodPost, "/api/logout", token, nil, nil) + if err != nil { + return nil, err + } + return resp.Cookies(), nil +} + +// Me calls GET /api/me, resolving token to its account. +func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) { + var out struct { + User PublicUser `json:"user"` + } + if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil { + return nil, err + } + return &out.User, nil +} + +// TOTPEnable calls POST /api/totp/enable, provisioning (or re-provisioning) +// a pending TOTP secret for token's account. The secret is not active until +// TOTPVerify confirms a generated code. +func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResult, error) { + var out TOTPEnableResult + if _, err := c.call(ctx, http.MethodPost, "/api/totp/enable", token, nil, &out); err != nil { + return nil, err + } + return &out, nil +} + +// TOTPVerify calls POST /api/totp/verify, confirming code against the +// pending secret TOTPEnable provisioned and activating two-factor auth. +func (c *Client) TOTPVerify(ctx context.Context, token, code string) error { + _, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil) + return err +} + +// TOTPDisable calls POST /api/totp/disable, turning two-factor auth off for +// token's account. AuthServer requires code to be one last valid TOTP code +// as proof of possession. +func (c *Client) TOTPDisable(ctx context.Context, token, code string) error { + _, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil) + return err +} + +// RequestPasswordReset calls POST /api/password-reset/request. See +// AuthServer's README for an important caveat: this is not an "email me a +// link" flow — AuthServer prints a one-time code to its own process +// console, and only an operator with access to that console can relay it to +// the user. The response never reveals whether usernameOrEmail matched an +// account. +func (c *Client) RequestPasswordReset(ctx context.Context, usernameOrEmail string) error { + _, err := c.call(ctx, http.MethodPost, "/api/password-reset/request", "", map[string]string{"username_or_email": usernameOrEmail}, nil) + return err +} + +// ConfirmPasswordReset calls POST /api/password-reset/confirm with the code +// an operator relayed out-of-band (see RequestPasswordReset) and a new +// password, and invalidates every existing session for that account. +func (c *Client) ConfirmPasswordReset(ctx context.Context, code, newPassword string) error { + _, err := c.call(ctx, http.MethodPost, "/api/password-reset/confirm", "", map[string]string{"code": code, "password": newPassword}, nil) + return err +} + +// ListManagedUsers calls GET /api/admin/users. token's account must satisfy +// AuthServer's CanManageUsers check (admin or superadmin), or this returns +// an *APIError with StatusCode 401/403. +func (c *Client) ListManagedUsers(ctx context.Context, token string) ([]ManagedUser, error) { + var out struct { + Users []ManagedUser `json:"users"` + } + if _, err := c.call(ctx, http.MethodGet, "/api/admin/users", token, nil, &out); err != nil { + return nil, err + } + return out.Users, nil +} + +// CreateManagedUser calls POST /api/admin/users. Only honored when token's +// account can manage users; see ManagedUserInput's doc comment for the Role +// authorization rule. +func (c *Client) CreateManagedUser(ctx context.Context, token string, input ManagedUserInput) (*ManagedUser, error) { + var out struct { + User ManagedUser `json:"user"` + } + if _, err := c.call(ctx, http.MethodPost, "/api/admin/users", token, input, &out); err != nil { + return nil, err + } + return &out.User, nil +} + +// UpdateManagedUser calls PUT /api/admin/users/{id}. +func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error { + _, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil) + return err +} + +// DeleteManagedUser calls DELETE /api/admin/users/{id}. +func (c *Client) DeleteManagedUser(ctx context.Context, token string, id int64) error { + _, err := c.call(ctx, http.MethodDelete, fmt.Sprintf("/api/admin/users/%d", id), token, nil, nil) + return err +} diff --git a/shared/packages/media-shared-assets/.env.example b/shared/packages/media-shared-assets/.env.example new file mode 100644 index 0000000..05536df --- /dev/null +++ b/shared/packages/media-shared-assets/.env.example @@ -0,0 +1,2 @@ +# Backend configuration lives in ../backend/.env.example. +# This package contains browser assets only; it does not run a server. diff --git a/shared/packages/media-shared-assets/MediaDesktop/assets/icon.png b/shared/packages/media-shared-assets/MediaDesktop/assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..18efb5fc9ad08a1509b7df464d16c598e7516a22 GIT binary patch literal 1268 zcmc&!ZA@EL7=F*~&DNr|K#2?_X}b@$#AHJTEo$N|2o7dwnOQOW1CW!c4p(tG#W#2qPxO-}`mW z^E~fK&hwt;+G;qbV2V&jK1|@oE~r#P z!;>PXtg_~omNT?0I(!szBh?0#al^>Y4Cd)aXKEzu?1y?Tl_l#ymPVN$mY|-2dgThiE?Zfp_^FCBwlSnu7hVc~rDF<20Ivt9@BcZF7GAquMW^ytM5CebWpyPiS8 z!>o6{SHXosVzFiq{P{Xd{Cr%_g|5T~sS*?%HqbMwtq||=g_nEf97PMY$)nf+F)Q|` zPQb#lfqp=2UzbCk*gU00!I$;)J(WbC_i6qp#p_5i+10)UoK~U9RfK}=2Krhwok`RQ zQD-g+8dzfHO9l4|nXFf11K%u!cfqg8zfu`%M$WQ?Ux#;0iw$j?89(3tfp*P%B*}Wm zZmzdwkvH2F*w7q*!<&v~-WLWfZSZg~=DS?^xVMK%D%z*!J~j})E9H?+*1fD>f07Bl z)}uiO-xi#qufP-*JD2mBUIQ_|sEGJ|s!cj(UQZl42|rGWwqmU09pUq0MV&X+e+w@N ztz=>~9zTgCE-6JMl{1>pM6Hy1bo=8>slsB`NExVRMEOV+P>CY+C?3EglV&wzA*vyn zl!&D@!YdK~RICuctyTQrkqInhUwnVZajG% .nc-scroll-host, +body.nc-content-scroll-shell > .page-panel > .nc-scroll-host { + position: fixed; + left: 0; + right: calc(100% - 100vw); + top: var(--topbar-height, 56px); + bottom: var(--bottom-nav-height, 0px); + height: calc(100dvh - var(--topbar-height, 56px) - var(--bottom-nav-height, 0px)); + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior-y: contain; + -webkit-overflow-scrolling: touch; +} + +@supports not (height: 100dvh) { + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host { + height: calc(100vh - var(--topbar-height, 56px) - var(--bottom-nav-height, 0px)); + } +} + +body.nc-content-scroll-shell > .fixed.left-0.right-0.overflow-y-auto, +body.nc-content-scroll-shell > .page-panel > .fixed.left-0.right-0.overflow-y-auto { + bottom: var(--bottom-nav-height, 0px); +} + +/* Custom scrollbar styling for page-content scrolling regions. */ +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +), +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) * { + scrollbar-width: thin; + scrollbar-color: var(--color-scrollbar-thumb) var(--color-scrollbar-track); +} + +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +)::-webkit-scrollbar, +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) *::-webkit-scrollbar { + width: var(--scrollbar-size); + height: var(--scrollbar-size); +} + +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +)::-webkit-scrollbar-track, +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) *::-webkit-scrollbar-track { + border-radius: var(--scrollbar-radius); + background: var(--color-scrollbar-track); +} + +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +)::-webkit-scrollbar-thumb, +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) *::-webkit-scrollbar-thumb { + border: 2px solid var(--color-scrollbar-track); + border-radius: var(--scrollbar-radius); + background: var(--color-scrollbar-thumb); + background-clip: padding-box; + min-height: 1.5rem; +} + +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +)::-webkit-scrollbar-thumb:hover, +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) *::-webkit-scrollbar-thumb:hover { + background: var(--color-scrollbar-thumb-hover); +} + +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +)::-webkit-scrollbar-thumb:active, +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) *::-webkit-scrollbar-thumb:active { + background: var(--color-scrollbar-thumb-active); +} + +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +)::-webkit-scrollbar-corner, +:where( + body.nc-content-scroll-shell > .nc-scroll-host, + body.nc-content-scroll-shell > .page-panel > .nc-scroll-host, + body > main, + body > #main-content, + body > .page-panel > main, + body > .page-panel > #main-content +) *::-webkit-scrollbar-corner { + background: var(--color-scrollbar-track); +} + +/* Player */ +.volume-slider { + appearance: none; + width: 68px; + height: 3px; + border-radius: 2px; + background: rgb(255 255 255/25%); + outline: none; + cursor: pointer; + vertical-align: middle; + flex-shrink: 0; +} +.volume-slider::-webkit-slider-runnable-track { + height: 3px; + border-radius: 2px; + background: rgb(255 255 255/25%); +} +.volume-slider::-webkit-slider-thumb { + appearance: none; + width: 12px; + height: 12px; + margin-top: -4.5px; + border-radius: 50%; + background: #fff; + cursor: pointer; + box-shadow: 0 0 0 2px rgb(0 0 0/30%); +} +.volume-slider::-moz-range-track { + height: 3px; + border-radius: 2px; + background: rgb(255 255 255/25%); + border: none; +} +.volume-slider::-moz-range-thumb { + width: 12px; + height: 12px; + border-radius: 50%; + background: #fff; + border: none; + cursor: pointer; + box-shadow: 0 0 0 2px rgb(0 0 0/30%); +} + +/* Dual-handle range slider used by media filter popovers. */ +.c-range-slider { + position: relative; + width: 100%; + height: 1.5rem; +} +.c-range-slider__track { + position: absolute; + left: 0; + right: 0; + top: 50%; + height: 0.375rem; + transform: translateY(-50%); + border-radius: var(--radius-pill, 9999px); + background: rgb(148 163 184 / 28%); +} +.c-range-slider__fill { + position: absolute; + top: 0; + height: 100%; + border-radius: var(--radius-pill, 9999px); + background: var(--color-accent, #4f9cff); +} +.c-range-slider__input { + position: absolute; + inset: 0; + width: 100%; + margin: 0; + background: transparent; + -webkit-appearance: none; + appearance: none; + pointer-events: none; +} +.c-range-slider__input::-webkit-slider-runnable-track { + height: 0.375rem; + background: transparent; +} +.c-range-slider__input::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 0.95rem; + height: 0.95rem; + margin-top: calc((0.375rem - 0.95rem) / 2); + border-radius: var(--radius-pill, 9999px); + border: 2px solid var(--color-accent, #4f9cff); + background: var(--color-surface, #13203a); + box-shadow: 0 1px 4px rgb(0 0 0 / 45%); + pointer-events: auto; + cursor: pointer; +} +.c-range-slider__input::-moz-range-track { + height: 0.375rem; + background: transparent; + border: none; +} +.c-range-slider__input::-moz-range-progress { + background: transparent; +} +.c-range-slider__input::-moz-range-thumb { + width: 0.95rem; + height: 0.95rem; + border-radius: var(--radius-pill, 9999px); + border: 2px solid var(--color-accent, #4f9cff); + background: var(--color-surface, #13203a); + box-shadow: 0 1px 4px rgb(0 0 0 / 45%); + pointer-events: auto; + cursor: pointer; +} +.c-range-slider__input:focus-visible { + outline: none; +} +.c-range-slider__input:focus-visible::-webkit-slider-thumb { + box-shadow: 0 0 0 3px var(--color-accent-soft, rgb(79 156 255 / 25%)); +} +.c-range-slider__input:focus-visible::-moz-range-thumb { + box-shadow: 0 0 0 3px var(--color-accent-soft, rgb(79 156 255 / 25%)); +} + +*, +:after, +:before { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(59, 130, 246, 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + --tw-contain-size: ; + --tw-contain-layout: ; + --tw-contain-paint: ; + --tw-contain-style: ; +} +::backdrop { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(59, 130, 246, 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + --tw-contain-size: ; + --tw-contain-layout: ; + --tw-contain-paint: ; + --tw-contain-style: ; +} +*, +:after, +:before { + box-sizing: border-box; + border: 0 solid #e5e7eb; +} +:after, +:before { + --tw-content: ""; +} +:host, +html { + line-height: 1.5; + -webkit-text-size-adjust: 100%; + -moz-tab-size: 4; + -o-tab-size: 4; + tab-size: 4; + font-family: + ui-sans-serif, + system-ui, + sans-serif, + Apple Color Emoji, + Segoe UI Emoji, + Segoe UI Symbol, + Noto Color Emoji; + font-feature-settings: normal; + font-variation-settings: normal; + -webkit-tap-highlight-color: transparent; + scrollbar-gutter: stable; +} +body { + margin: 0; + line-height: inherit; +} +hr { + height: 0; + color: inherit; + border-top-width: 1px; +} +abbr:where([title]) { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: inherit; + font-weight: inherit; +} +a, +a:link, +a:visited, +a:hover, +a:active { + color: inherit; + text-decoration: none; +} +b, +strong { + font-weight: bolder; +} +code, +kbd, +pre, +samp { + font-family: + ui-monospace, + SFMono-Regular, + Menlo, + Monaco, + Consolas, + Liberation Mono, + Courier New, + monospace; + font-feature-settings: normal; + font-variation-settings: normal; + font-size: 1em; +} +small { + font-size: 80%; +} +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} +sub { + bottom: -0.25em; +} +sup { + top: -0.5em; +} +table { + text-indent: 0; + border-color: inherit; + border-collapse: collapse; +} +button, +input, +optgroup, +select, +textarea { + font-family: inherit; + font-feature-settings: inherit; + font-variation-settings: inherit; + font-size: 100%; + font-weight: inherit; + line-height: inherit; + letter-spacing: inherit; + color: inherit; + margin: 0; + padding: 0; +} +button, +select { + text-transform: none; +} +button, +input:where([type="button"]), +input:where([type="reset"]), +input:where([type="submit"]) { + -webkit-appearance: button; + background-color: transparent; + background-image: none; +} +:-moz-focusring { + outline: auto; +} +:-moz-ui-invalid { + box-shadow: none; +} +progress { + vertical-align: baseline; +} +::-webkit-inner-spin-button, +::-webkit-outer-spin-button { + height: auto; +} +[type="search"] { + -webkit-appearance: textfield; + outline-offset: -2px; +} +::-webkit-search-decoration { + -webkit-appearance: none; +} +::-webkit-file-upload-button { + -webkit-appearance: button; + font: inherit; +} +summary { + display: list-item; +} +blockquote, +dd, +dl, +figure, +h1, +h2, +h3, +h4, +h5, +h6, +hr, +p, +pre { + margin: 0; +} +fieldset { + margin: 0; +} +fieldset, +legend { + padding: 0; +} +menu, +ol, +ul { + list-style: none; + margin: 0; + padding: 0; +} +dialog { + padding: 0; +} +textarea { + resize: vertical; +} +input::-moz-placeholder, +textarea::-moz-placeholder { + opacity: 1; + color: #9ca3af; +} +input::placeholder, +textarea::placeholder { + opacity: 1; + color: #9ca3af; +} +[role="button"], +button { + cursor: pointer; +} +:disabled { + cursor: default; +} +audio, +canvas, +embed, +iframe, +img, +object, +svg, +video { + display: block; + vertical-align: middle; +} +img, +video { + max-width: 100%; + height: auto; +} +[hidden]:where(:not([hidden="until-found"])) { + display: none; +} + +/* Shared controls: enforce one size/radius system for single-line controls across apps */ +input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="image"]):not([type="hidden"]), +select, +textarea { + box-sizing: border-box; + border: 1px solid var(--color-input-border); + background-color: var(--color-input-bg); + color: var(--color-text); + transition: + border-color var(--transition-fast), + box-shadow var(--transition-fast), + background-color var(--transition-fast); +} +input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="image"]):not([type="hidden"]):not(textarea), +select:not([multiple]):not([size]) { + min-height: var(--control-height); + height: var(--control-height); + border-radius: var(--control-radius); + padding: 0 var(--control-padding-x); + line-height: 1.2; +} +textarea { + border-radius: var(--control-radius); + padding: 0.5rem var(--control-padding-x); +} +input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="image"]):not([type="hidden"]):focus, +select:focus, +textarea:focus { + border-color: var(--color-accent); + box-shadow: 0 0 0 2px var(--color-accent-soft); + outline: none; +} +select:not([multiple]):not([size]) { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + padding-right: calc(var(--control-padding-x) + 1.25rem); + background-image: + linear-gradient(45deg, transparent 50%, var(--color-text-dim) 50%), + linear-gradient(135deg, var(--color-text-dim) 50%, transparent 50%); + background-position: + calc(100% - 0.95rem) calc(50% + 0.12rem), + calc(100% - 0.65rem) calc(50% + 0.12rem); + background-size: 0.35rem 0.35rem; + background-repeat: no-repeat; +} + +/* Utility: force a control to use shared single-line control height. */ +.u-control-height { + min-height: var(--control-height); + height: var(--control-height); +} + +input[type="checkbox"], +input[type="radio"] { + accent-color: var(--color-action); + inline-size: var(--control-check-size); + block-size: var(--control-check-size); + border-radius: var(--control-check-radius); + flex: 0 0 auto; +} +input[type="radio"] { + border-radius: var(--radius-pill); +} +input[type="range"] { + accent-color: var(--color-action); +} +input[type="file"] { + min-height: var(--control-height); + border: 1px solid var(--color-input-border); + border-radius: var(--control-radius); + background-color: var(--color-input-bg); + color: var(--color-text); + padding: 0.25rem; +} +input[type="file"]::file-selector-button { + height: calc(var(--control-height) - 0.5rem); + margin-right: 0.6rem; + border: 1px solid var(--color-border-strong); + border-radius: calc(var(--control-radius) - 2px); + background-color: var(--color-surface-alt); + color: var(--color-text); + padding: 0 0.65rem; + line-height: 1; +} + +/* Shared button components used by Downloader/Desktop and dynamic UIs */ +.c-btn, +.btn-ghost, +.btn-primary, +.btn-secondary, +.btn-outline, +.btn-danger, +:where(button:not([class])), +:where(input[type="button"]:not([class])), +:where(input[type="submit"]:not([class])), +:where(input[type="reset"]:not([class])) { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.375rem; + min-height: 2.25rem; + padding: 0.45rem 0.85rem; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-md); + background-color: var(--color-surface-alt); + color: var(--color-text); + font-size: var(--font-size-sm); + font-weight: 600; + line-height: 1.2; + text-decoration: none; + transition: + background-color var(--transition-fast), + border-color var(--transition-fast), + box-shadow var(--transition-fast), + color var(--transition-fast), + opacity var(--transition-fast); +} +.c-btn:hover, +.btn-ghost:hover, +.btn-primary:hover, +.btn-secondary:hover, +.btn-outline:hover, +.btn-danger:hover, +:where(button:not([class])):hover, +:where(input[type="button"]:not([class])):hover, +:where(input[type="submit"]:not([class])):hover, +:where(input[type="reset"]:not([class])):hover { + background-color: var(--color-surface-raised); +} +.c-btn:focus-visible, +.btn-ghost:focus-visible, +.btn-primary:focus-visible, +.btn-secondary:focus-visible, +.btn-outline:focus-visible, +.btn-danger:focus-visible, +:where(button:not([class])):focus-visible, +:where(input[type="button"]:not([class])):focus-visible, +:where(input[type="submit"]:not([class])):focus-visible, +:where(input[type="reset"]:not([class])):focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--color-accent-soft); +} +.c-btn:disabled, +.btn-ghost:disabled, +.btn-primary:disabled, +.btn-secondary:disabled, +.btn-outline:disabled, +.btn-danger:disabled, +:where(button:not([class])):disabled, +:where(input[type="button"]:not([class])):disabled, +:where(input[type="submit"]:not([class])):disabled, +:where(input[type="reset"]:not([class])):disabled, +.c-btn[aria-disabled="true"], +.btn-ghost[aria-disabled="true"], +.btn-primary[aria-disabled="true"], +.btn-secondary[aria-disabled="true"], +.btn-outline[aria-disabled="true"], +.btn-danger[aria-disabled="true"] { + opacity: 0.6; + pointer-events: none; +} +.c-btn-primary, +.btn-primary { + border-color: var(--color-action-border); + background-color: var(--color-action); + color: #fff; +} +.c-btn-primary:hover, +.btn-primary:hover { + border-color: var(--color-action-hover); + background-color: var(--color-action-hover); +} +.c-btn-secondary, +.btn-secondary { + border-color: var(--color-action-border); + background-color: var(--color-primary-dim); + color: var(--color-action-alt-text); +} +.c-btn-secondary:hover, +.btn-secondary:hover { + border-color: var(--color-action); + background-color: var(--color-accent-soft); +} +.c-btn-ghost, +.btn-ghost, +.c-btn-outline, +.btn-outline { + border-color: var(--color-border-strong); + background-color: transparent; + color: var(--color-text); +} +.c-btn-ghost:hover, +.btn-ghost:hover { + background-color: var(--color-surface-muted); +} +.c-btn-outline:hover, +.btn-outline:hover { + background-color: var(--color-surface-alt); +} +.c-btn-danger, +.btn-danger { + border-color: var(--color-danger); + background-color: var(--color-danger); + color: #fff; +} +.c-btn-danger:hover, +.btn-danger:hover { + border-color: var(--color-danger-hover); + background-color: var(--color-danger-hover); +} +.c-btn-sq { + width: 2.25rem; + min-width: 2.25rem; + padding: 0; +} + +/* Shared responsive nav: desktop modern top nav, mobile fixed icon bar */ +[data-bottom-nav] { + box-sizing: border-box; + z-index: 49; + display: flex; + align-items: center; + gap: 0.35rem; + border: 1px solid var(--color-bar-surface-border); + background: var(--color-bar-bg); +} +[data-bottom-nav]:empty { + display: none; +} +[data-bottom-nav] [data-navbar-layout] { + display: none; + width: 100%; + align-items: center; + gap: 0.35rem; +} +[data-bottom-nav] a { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.45rem; + min-height: 2.25rem; + padding: 0.45rem 0.8rem; + border: 1px solid transparent; + border-radius: var(--radius-md); + color: var(--color-bar-text-muted); + text-decoration: none; + font-size: 0.82rem; + font-weight: 600; + line-height: 1.1; + transition: + background-color var(--transition-fast), + border-color var(--transition-fast), + color var(--transition-fast), + box-shadow var(--transition-fast); +} +[data-bottom-nav] a i { + font-size: 0.95rem; +} +[data-bottom-nav] a:hover { + border-color: var(--color-bar-surface-border); + background-color: var(--color-bar-surface); + color: var(--color-bar-text); +} +[data-bottom-nav] a.is-active { + border-color: var(--color-action-border); + background-color: var(--color-primary-dim); + color: var(--color-bar-text); +} +[data-bottom-nav] a:focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--color-accent-soft); +} + +.pt-topbar-gap { + padding-top: calc(var(--topbar-height) + var(--tab-content-top-gap, 0.75rem)); +} + +/* Fixed-scroll main shells already reserve topbar space via `top: var(--topbar-height)`. + Apply the final content gap immediately to avoid post-load jump. */ +main.fixed.left-0.right-0.overflow-y-auto > .pt-topbar-gap, +main.fixed.left-0.right-0.overflow-y-auto > #main-content.pt-topbar-gap { + padding-top: var(--tab-content-top-gap, 0.75rem); +} + +body.nc-content-scroll-shell .pt-topbar-gap { + padding-top: var(--tab-content-top-gap, 0.75rem); +} +body.nc-auto-topbar-gap:not(.is-fullscreen):not(.is-chrome-hidden) { + padding-top: calc(var(--topbar-height) + var(--tab-content-top-gap, 0.75rem)); +} +.pb-navbar-gap { + padding-bottom: calc(var(--bottom-nav-height) + var(--overlay-gap, 0.75rem)); +} + +/* Normalize the header-to-content gap across tabbed panels in all projects. + Excludes no-scroll feed stages (e.g. MediaViewer home), which manage + their own top spacing separately. */ +body.nc-content-scroll-shell:not(.is-feed-stage-active) > .page-panel > main.pt-topbar-gap, +body.nc-content-scroll-shell:not(.is-feed-stage-active) > .page-panel > #main-content.pt-topbar-gap, +body.nc-content-scroll-shell:not(.is-feed-stage-active) + > .nc-scroll-host + > .page-panel + > main.pt-topbar-gap, +body.nc-content-scroll-shell:not(.is-feed-stage-active) + > .nc-scroll-host + > .page-panel + > #main-content.pt-topbar-gap { + padding-top: var(--tab-content-top-gap, 0.75rem); +} + +/* Semantic worker badges/pills used by MediaAnalyzer history rows. */ +.worker-badge-image, +.worker-badge-video, +.worker-badge-audio, +.worker-badge-unknown, +.worker-pill-default, +.worker-pill-meta, +.worker-pill-sfw, +.worker-pill-suggestive, +.worker-pill-nsfw { + border: 1px solid transparent; +} + +.worker-badge-image { + color: rgb(147 197 253); + background-color: rgb(37 99 235 / 0.2); + border-color: rgb(59 130 246 / 0.35); +} + +.worker-badge-video { + color: rgb(110 231 183); + background-color: rgb(5 150 105 / 0.2); + border-color: rgb(16 185 129 / 0.35); +} + +.worker-badge-audio { + color: rgb(252 211 77); + background-color: rgb(180 83 9 / 0.2); + border-color: rgb(245 158 11 / 0.35); +} + +.worker-badge-unknown { + color: rgb(203 213 225); + background-color: rgb(51 65 85 / 0.35); + border-color: rgb(100 116 139 / 0.45); +} + +.worker-pill-default { + color: rgb(203 213 225); + background-color: rgb(51 65 85 / 0.35); + border-color: rgb(100 116 139 / 0.45); +} + +.worker-pill-meta { + color: rgb(147 197 253); + background-color: rgb(37 99 235 / 0.2); + border-color: rgb(59 130 246 / 0.35); +} + +.worker-pill-sfw { + color: rgb(110 231 183); + background-color: rgb(5 150 105 / 0.2); + border-color: rgb(16 185 129 / 0.35); +} + +.worker-pill-suggestive { + color: rgb(252 211 77); + background-color: rgb(180 83 9 / 0.2); + border-color: rgb(245 158 11 / 0.35); +} + +.worker-pill-nsfw { + color: rgb(252 165 165); + background-color: rgb(153 27 27 / 0.25); + border-color: rgb(248 113 113 / 0.4); +} + +.worker-pill-compact { + padding: 0.125rem 0.375rem; + font-size: 0.6875rem; + line-height: 1rem; + font-weight: 500; +} + +/* Immersive feed stage + media stack behavior */ +body.is-feed-stage-active:not(.is-fullscreen):not(.is-chrome-hidden) { + overflow-x: hidden; +} + +body.is-feed-stage-active.is-fullscreen { + --topbar-height: 0px; +} + +body.is-feed-stage-active.is-fullscreen [data-topbar='1'] { + display: none !important; +} + +@media (min-width: 768px) { + body.is-feed-stage-active [data-float-controls='1'] { + bottom: 0.85rem; + } +} + +[data-stage-panel='feed'] [data-stage-main='1'] { + margin-left: auto; + margin-right: auto; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] { + position: relative; + width: 100%; + min-height: 320px; + height: calc( + 100dvh - var(--topbar-height) - var(--bottom-nav-height) - (var(--overlay-gap, 0.75rem) * 2) + ); + overflow: hidden; + border-radius: var(--radius-md); + background: color-mix(in srgb, var(--color-surface-alt) 65%, transparent); + overscroll-behavior: none; + touch-action: pan-y; +} + +/* When the shared scroll shell already reserves topbar/bottom-nav space, + keep feed-stage content flush to the header and fully contained in the host. */ +body.nc-content-scroll-shell.is-feed-stage-active [data-stage-main='1'].pt-topbar-gap { + padding-top: 0; +} + +body.nc-content-scroll-shell.is-feed-stage-active [data-stage-main='1'].pb-navbar-gap { + padding-bottom: 0; +} + +body.nc-content-scroll-shell.is-feed-stage-active [data-stage-panel='feed'] [data-media-stage='feed'] { + min-height: 0; + height: 100%; +} + +@supports not (height: 100dvh) { + [data-stage-panel='feed'] [data-media-stage='feed'] { + height: calc( + 100vh - var(--topbar-height) - var(--bottom-nav-height) - (var(--overlay-gap, 0.75rem) * 2) + ); + } +} + +@media (min-width: 768px) { + body.is-feed-stage-active [data-stage-main='1'].pt-topbar-gap { + padding-top: var(--overlay-gap, 0.75rem); + } + + body.is-feed-stage-active [data-stage-main='1'].pb-navbar-gap { + padding-bottom: 0; + } + + body.is-feed-stage-active [data-stage-panel='feed'] [data-media-stage='feed'] { + height: calc(100dvh - var(--topbar-height)); + } + + @supports not (height: 100dvh) { + body.is-feed-stage-active [data-stage-panel='feed'] [data-media-stage='feed'] { + height: calc(100vh - var(--topbar-height)); + } + } +} + +/* Feed home panels are no-scroll stages; keep their final no-gap state from first paint. */ +.page-panel[data-stage-panel='feed'] [data-stage-main='1'].pt-topbar-gap { + padding-top: 0; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] .media { + position: absolute; + inset: 0; + display: block; + visibility: hidden; + opacity: 0; + z-index: 0; + transition: + opacity 0.32s ease, + transform 0.32s ease, + visibility 0s linear 0.32s; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] .media.is-active { + visibility: visible; + opacity: 1; + z-index: 1; + transition: + opacity 0.32s ease, + transform 0.32s ease, + visibility 0s linear 0s; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] img.media, +[data-stage-panel='feed'] [data-media-stage='feed'] video.media { + width: 100%; + height: 100%; + object-fit: contain !important; + object-position: center; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] .media.fly-in-up { + z-index: 2; + animation: nc-media-stack-fly-in-up 0.32s ease both; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] .media.fly-in-down { + z-index: 2; + animation: nc-media-stack-fly-in-down 0.32s ease both; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] .media.fly-out-up { + animation: nc-media-stack-fly-out-up 0.32s ease both; +} + +[data-stage-panel='feed'] [data-media-stage='feed'] .media.fly-out-down { + animation: nc-media-stack-fly-out-down 0.32s ease both; +} + +@keyframes nc-media-stack-fly-in-up { + from { + transform: translateY(9%); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +@keyframes nc-media-stack-fly-in-down { + from { + transform: translateY(-9%); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +@keyframes nc-media-stack-fly-out-up { + from { + transform: translateY(0); + opacity: 1; + } + to { + transform: translateY(-9%); + opacity: 0; + } +} + +@keyframes nc-media-stack-fly-out-down { + from { + transform: translateY(0); + opacity: 1; + } + to { + transform: translateY(9%); + opacity: 0; + } +} + +/* Shared pagination utility */ +.nc-pagination-container { + display: grid; + width: 100%; + align-items: center; + gap: 0.625rem; +} +.nc-pagination-container.nc-pagination-top { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + 'info' + 'center' + 'buttons'; +} +.nc-pagination-container.nc-pagination-bottom { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + 'buttons' + 'center' + 'info'; +} +.nc-pagination-meta { + grid-area: info; + display: flex; + min-width: 0; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 0.625rem; +} +.nc-pagination-info { + display: block; + min-width: 0; + flex: 1 1 auto; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + text-align: center; + color: var(--color-text-dim); + font-size: var(--font-size-xs); +} +.nc-pagination-page-size-label { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: 0.375rem; + color: var(--color-text-dim); + font-size: var(--font-size-xs); + white-space: nowrap; +} +.nc-pagination-page-size { + min-height: 2.1rem; + min-width: 4.5rem; + padding: 0.35rem 0.5rem; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-md); + background: var(--color-surface-alt); + color: var(--color-text); + font-size: var(--font-size-sm); +} +.nc-pagination-center { + grid-area: center; + display: flex; + width: 100%; + justify-content: center; +} +.nc-pagination-center-slot { + display: inline-flex; + align-items: center; + justify-content: center; +} +.nc-pagination-btns { + grid-area: buttons; + display: flex; + width: 100%; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 0.25rem; +} +.nc-pagination-btn { + box-sizing: border-box; + display: inline-flex; + min-height: 2.1rem; + min-width: 2.1rem; + flex: 1 1 0; + align-items: center; + justify-content: center; + gap: 0.25rem; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-md); + background: var(--color-surface-alt); + color: var(--color-text); + font-size: var(--font-size-sm); + font-weight: 600; + line-height: 1; + white-space: nowrap; + cursor: pointer; + transition: + background-color var(--transition-fast), + border-color var(--transition-fast), + box-shadow var(--transition-fast), + color var(--transition-fast), + opacity var(--transition-fast); +} +.nc-pagination-btn svg { + width: 1rem; + height: 1rem; + pointer-events: none; +} +.nc-pagination-btn:hover:not(:disabled) { + background: var(--color-surface-raised); +} +.nc-pagination-btn:focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--color-accent-soft); +} +.nc-pagination-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.nc-pagination-btn-active, +.nc-pagination-btn[aria-current='page'] { + border-color: var(--color-action-border); + background: var(--color-primary-dim); + color: var(--color-action-alt-text); +} + +@media (min-width: 640px) { + .nc-pagination-container.nc-pagination-top, + .nc-pagination-container.nc-pagination-bottom { + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + grid-template-areas: 'info center buttons'; + } + .nc-pagination-info { + width: auto; + max-width: 100%; + text-align: left; + } + .nc-pagination-meta { + justify-self: start; + justify-content: flex-start; + } + .nc-pagination-center { + width: auto; + justify-self: center; + } + .nc-pagination-btns { + width: auto; + justify-self: end; + flex-wrap: nowrap; + overflow-x: auto; + } + .nc-pagination-btn { + flex: 0 0 auto; + min-width: 2.25rem; + padding: 0.35rem 0.55rem; + } +} + +/* Shared results-card mode layouts */ +[data-nc-result-card='1'] [data-nc-result-card-preview='1'] { + overflow: hidden; + border-radius: var(--radius-md); +} + +[data-nc-result-card='1'] [data-nc-result-card-body='1'] { + min-width: 0; + display: flex; + flex: 1 1 auto; + flex-direction: column; + gap: 0.45rem; +} + +[data-nc-result-card='1'] [data-nc-result-card-title='1'] { + min-width: 0; + color: var(--color-text); + font-weight: 600; + overflow-wrap: anywhere; +} + +[data-nc-result-card='1'] [data-nc-result-card-meta='1'] { + min-width: 0; + color: var(--color-text-dim); + font-size: var(--font-size-xs); +} + +[data-nc-result-card='1'] [data-nc-result-card-actions='1'] { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} + +[data-nc-results-content='1'][data-nc-display-mode='grid'] [data-nc-result-card='1'] { + display: flex; + flex-direction: column; +} + +[data-nc-results-content='1'][data-nc-display-mode='list'] [data-nc-result-card='1'] { + display: grid; + grid-template-columns: clamp(108px, 18vw, 188px) minmax(0, 1fr) auto; + align-items: stretch; + gap: 0.75rem; + text-align: left; +} + +[data-nc-results-content='1'][data-nc-display-mode='list'] + [data-nc-result-card='1'][data-nc-result-card-no-actions='1'] { + grid-template-columns: clamp(108px, 18vw, 188px) minmax(0, 1fr); +} + +[data-nc-results-content='1'][data-nc-display-mode='list'] + [data-nc-result-card='1'] + [data-nc-result-card-preview='1'] { + height: 100%; + min-height: 92px; +} + +[data-nc-results-content='1'][data-nc-display-mode='list'] + [data-nc-result-card='1'] + [data-nc-result-card-preview='1'][data-nc-thumb-ratio='16-9'] { + align-self: start; + height: auto; + min-height: 0; + aspect-ratio: 16/9; +} + +[data-nc-results-content='1'][data-nc-display-mode='list'] + [data-nc-result-card='1'] + [data-nc-result-card-actions='1'] { + justify-content: flex-end; + align-self: center; +} + +@media (max-width: 640px) { + [data-nc-results-content='1'][data-nc-display-mode='list'] [data-nc-result-card='1'] { + grid-template-columns: 96px minmax(0, 1fr); + } + + [data-nc-results-content='1'][data-nc-display-mode='list'] + [data-nc-result-card='1'] + [data-nc-result-card-actions='1'] { + grid-column: 1/-1; + justify-content: stretch; + } +} + +@media (max-width: 767px) { + [data-bottom-nav][data-page-switcher='1'] { + display: none !important; + } + [data-bottom-nav] { + position: fixed; + left: 0; + right: 0; + bottom: 0; + min-height: var(--bottom-nav-height); + justify-content: space-around; + border-width: 1px 0 0; + border-radius: 0; + padding: 0.35rem max(0.5rem, env(safe-area-inset-right)) + calc(0.35rem + env(safe-area-inset-bottom)) max(0.5rem, env(safe-area-inset-left)); + box-shadow: var(--shadow-md); + } + [data-bottom-nav] [data-navbar-layout='mobile'] { + display: flex; + justify-content: space-around; + } + [data-bottom-nav] [data-navbar-layout='desktop'] { + display: none !important; + } + [data-bottom-nav] a { + flex: 1 1 0; + max-width: 8rem; + flex-direction: column; + gap: 0.22rem; + min-height: calc(var(--bottom-nav-height) - 0.75rem); + padding: 0.25rem 0.4rem; + font-size: 0.68rem; + letter-spacing: 0.02em; + } + [data-bottom-nav] a span { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +@media (min-width: 768px) { + [data-bottom-nav][data-mobile-nav='1'] { + display: none !important; + } + [data-bottom-nav] { + position: sticky; + left: auto; + right: auto; + bottom: auto; + top: calc(var(--topbar-height, 56px) + var(--overlay-gap, 0.75rem)); + z-index: 51; + width: min(1504px, calc(100% - 2rem)); + margin: calc(var(--topbar-height, 56px) + var(--overlay-gap, 0.75rem)) auto 0.85rem; + justify-content: stretch; + border-radius: var(--radius-lg); + padding: 0.45rem 0.5rem; + box-shadow: var(--shadow-sm); + } + [data-topbar='1'] [data-bottom-nav][data-page-switcher='1'] { + position: static; + left: auto; + right: auto; + top: auto; + bottom: auto; + transform: none; + z-index: auto; + display: inline-flex; + align-items: center; + justify-content: flex-end; + width: auto; + max-width: 100%; + height: auto; + margin: 0; + border: 1px solid var(--color-bar-surface-border); + border-radius: var(--radius-pill); + background: var(--color-bar-surface); + box-shadow: var(--shadow-sm); + padding: 0.22rem; + } + [data-topbar='1'] [data-bottom-nav][data-page-switcher='1'] [data-navbar-layout='desktop'] { + width: auto; + max-width: 100%; + justify-content: flex-end; + gap: 0.22rem; + overflow-x: auto; + scrollbar-width: thin; + } + [data-topbar='1'] [data-bottom-nav][data-page-switcher='1'] a { + flex: 0 0 auto; + min-height: 2rem; + padding: 0.35rem 0.75rem; + border-radius: var(--radius-pill); + border-color: transparent; + background: transparent; + color: var(--color-bar-text-muted); + } + [data-topbar='1'] [data-bottom-nav][data-page-switcher='1'] a:hover { + border-color: var(--color-bar-surface-border); + background: var(--color-bar-bg); + color: var(--color-bar-text); + } + [data-topbar='1'] [data-bottom-nav][data-page-switcher='1'] a.is-active { + border-color: var(--color-action-border); + background: var(--color-primary-dim); + color: var(--color-bar-text); + } + [data-bottom-nav] [data-navbar-layout='mobile'] { + display: none !important; + } + [data-bottom-nav] [data-navbar-layout='desktop'] { + display: flex; + justify-content: stretch; + } + [data-bottom-nav] a { + flex: 1 1 0; + min-width: 0; + } + [data-bottom-nav] a span { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .pb-navbar-gap { + padding-bottom: 1rem; + } +} + +.\!container { + width: 100% !important; +} +.container { + width: 100%; +} +@media (min-width: 640px) { + .\!container { + max-width: 640px !important; + } + .container { + max-width: 640px; + } +} +@media (min-width: 768px) { + .\!container { + max-width: 768px !important; + } + .container { + max-width: 768px; + } +} +@media (min-width: 1024px) { + .\!container { + max-width: 1024px !important; + } + .container { + max-width: 1024px; + } +} +@media (min-width: 1280px) { + .\!container { + max-width: 1280px !important; + } + .container { + max-width: 1280px; + } +} +@media (min-width: 1536px) { + .\!container { + max-width: 1536px !important; + } + .container { + max-width: 1536px; + } +} +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} +.pointer-events-none { + pointer-events: none; +} +.pointer-events-auto { + pointer-events: auto; +} +.\!visible { + visibility: visible !important; +} +.visible { + visibility: visible; +} +.invisible { + visibility: hidden; +} +.collapse { + visibility: collapse; +} +.static { + position: static; +} +.\!fixed { + position: fixed !important; +} +.fixed { + position: fixed; +} +.absolute { + position: absolute; +} +.relative { + position: relative; +} +.sticky { + position: sticky; +} +.inset-0 { + inset: 0; +} +.inset-4 { + inset: 1rem; +} +.inset-8 { + inset: 2rem; +} +.inset-x-0 { + left: 0; + right: 0; +} +.inset-y-0 { + top: 0; + bottom: 0; +} +.-right-1 { + right: -0.25rem; +} +.-right-3 { + right: -0.75rem; +} +.-top-1 { + top: -0.25rem; +} +.-top-3 { + top: -0.75rem; +} +.bottom-0 { + bottom: 0; +} +.bottom-1\.5 { + bottom: 0.375rem; +} +.bottom-\[-34px\] { + bottom: -34px; +} +.bottom-\[calc\(var\(--bottom-nav-height\)\+0\.85rem\)\] { + bottom: calc(var(--bottom-nav-height) + 0.85rem); +} +.bottom-\[calc\(var\(--bottom-nav-height\2c 56px\)\+0\.85rem\)\] { + bottom: calc(var(--bottom-nav-height, 56px) + 0.85rem); +} +.bottom-\[calc\(var\(--bottom-nav-height\2c 56px\)\+4rem\)\] { + bottom: calc(var(--bottom-nav-height, 56px) + 4rem); +} +.bottom-full { + bottom: 100%; +} +.left-0 { + left: 0; +} +.left-1\.5 { + left: 0.375rem; +} +.left-1\/2 { + left: 50%; +} +.left-3 { + left: 0.75rem; +} +.right-0 { + right: 0; +} +.right-1\.5 { + right: 0.375rem; +} +.right-14 { + right: 3.5rem; +} +.right-2 { + right: 0.5rem; +} +.right-2\.5 { + right: 0.625rem; +} +.right-3 { + right: 0.75rem; +} +.right-4 { + right: 1rem; +} +.right-\[0\.6rem\] { + right: 0.6rem; +} +.right-\[0\.85rem\] { + right: 0.85rem; +} +.right-\[var\(--overlay-gap\2c \.75rem\)\] { + right: var(--overlay-gap, 0.75rem); +} +.top-0 { + top: 0; +} +.top-1\.5 { + top: 0.375rem; +} +.top-1\/2 { + top: 50%; +} +.top-2 { + top: 0.5rem; +} +.top-2\.5 { + top: 0.625rem; +} +.top-3 { + top: 0.75rem; +} +.top-4 { + top: 1rem; +} +.top-\[-38px\] { + top: -38px; +} +.top-\[0\.4rem\] { + top: 0.4rem; +} +.top-\[calc\(100\%\+6px\)\] { + top: calc(100% + 6px); +} +.top-\[calc\(var\(--topbar-height\)\+1rem\)\] { + top: calc(var(--topbar-height) + 1rem); +} +.top-\[var\(--overlay-gap\2c \.75rem\)\] { + top: var(--overlay-gap, 0.75rem); +} +.top-\[var\(--topbar-height\)\] { + top: var(--topbar-height); +} +.top-full { + top: 100%; +} +.isolate { + isolation: isolate; +} +.z-10 { + z-index: 10; +} +.z-20 { + z-index: 20; +} +.z-30 { + z-index: 30; +} +.z-40 { + z-index: 40; +} +.z-50 { + z-index: 50; +} +.z-\[1000\] { + z-index: 1000; +} +.z-\[10050\] { + z-index: 10050; +} +.z-\[10100\] { + z-index: 10100; +} +.z-\[120\] { + z-index: 120; +} +.z-\[130\] { + z-index: 130; +} +.z-\[160\] { + z-index: 160; +} +.z-\[180\] { + z-index: 180; +} +.z-\[190\] { + z-index: 190; +} +.z-\[1\] { + z-index: 1; +} +.z-\[200\] { + z-index: 200; +} +.z-\[220\] { + z-index: 220; +} +.z-\[2\] { + z-index: 2; +} +.z-\[300\] { + z-index: 300; +} +.z-\[48\] { + z-index: 48; +} +.z-\[5000\] { + z-index: 5000; +} +.z-\[60\] { + z-index: 60; +} +.z-\[9980\] { + z-index: 9980; +} +.z-\[9990\] { + z-index: 9990; +} +.z-\[9999\] { + z-index: 9999; +} +.col-\[1\/-1\], +.col-span-full { + grid-column: 1/-1; +} +.m-0 { + margin: 0; +} +.-mx-4 { + margin-left: -1rem; + margin-right: -1rem; +} +.mx-1 { + margin-left: 0.25rem; + margin-right: 0.25rem; +} +.mx-2 { + margin-left: 0.5rem; + margin-right: 0.5rem; +} +.mx-auto { + margin-left: auto; + margin-right: auto; +} +.my-1 { + margin-top: 0.25rem; + margin-bottom: 0.25rem; +} +.my-2 { + margin-top: 0.5rem; + margin-bottom: 0.5rem; +} +.-mb-4 { + margin-bottom: -1rem; +} +.mb-1 { + margin-bottom: 0.25rem; +} +.mb-2 { + margin-bottom: 0.5rem; +} +.mb-4 { + margin-bottom: 1rem; +} +.ml-1 { + margin-left: 0.25rem; +} +.ml-auto { + margin-left: auto; +} +.mr-1 { + margin-right: 0.25rem; +} +.mr-2 { + margin-right: 0.5rem; +} +.mr-auto { + margin-right: auto; +} +.mt-0 { + margin-top: 0; +} +.mt-1 { + margin-top: 0.25rem; +} +.mt-2 { + margin-top: 0.5rem; +} +.mt-4 { + margin-top: 1rem; +} +.mt-auto { + margin-top: auto; +} +.box-border { + box-sizing: border-box; +} +.line-clamp-2 { + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; +} +.block { + display: block; +} +.inline-block { + display: inline-block; +} +.inline { + display: inline; +} +.flex { + display: flex; +} +.inline-flex { + display: inline-flex; +} +.table { + display: table; +} +.\!grid { + display: grid !important; +} +.grid { + display: grid; +} +.contents { + display: contents; +} +.\!hidden { + display: none !important; +} +.hidden { + display: none; +} +.aspect-video { + aspect-ratio: 16/9; +} +.h-1\.5 { + height: 0.375rem; +} +.h-10 { + height: 2.5rem; +} +.h-11 { + height: 2.75rem; +} +.h-12 { + height: 3rem; +} +.h-14 { + height: 3.5rem; +} +.h-16 { + height: 4rem; +} +.h-2 { + height: 0.5rem; +} +.h-2\.5 { + height: 0.625rem; +} +.h-3 { + height: 0.75rem; +} +.h-3\.5 { + height: 0.875rem; +} +.h-36 { + height: 9rem; +} +.h-4 { + height: 1rem; +} +.h-40 { + height: 10rem; +} +.h-5 { + height: 1.25rem; +} +.h-6 { + height: 1.5rem; +} +.h-64 { + height: 16rem; +} +.h-7 { + height: 1.75rem; +} +.h-8 { + height: 2rem; +} +.h-9 { + height: 2.25rem; +} +.h-\[100px\] { + height: 100px; +} +.h-\[130px\] { + height: 130px; +} +.h-\[14px\] { + height: 14px; +} +.h-\[15px\] { + height: 15px; +} +.h-\[200px\] { + height: 200px; +} +.h-\[220px\] { + height: 220px; +} +.h-\[2px\] { + height: 2px; +} +.h-\[360px\] { + height: 360px; +} +.h-\[3px\] { + height: 3px; +} +.h-\[42px\] { + height: 42px; +} +.h-\[72px\] { + height: 72px; +} +.h-\[88px\] { + height: 88px; +} +.h-\[min\(74vh\2c + calc\(100vh-var\(--topbar-height\)-var\(--bottom-nav-height\)-2rem\)\)\] { + height: min( + 74vh, + calc(100vh - var(--topbar-height) - var(--bottom-nav-height) - 2rem) + ); +} +.h-\[var\(--bar-height\2c 56px\)\] { + height: var(--bar-height, 56px); +} +.h-full { + height: 100%; +} +.h-px { + height: 1px; +} +.h-screen { + height: 100vh; +} +.max-h-52 { + max-height: 13rem; +} +.max-h-\[320px\] { + max-height: 320px; +} +.max-h-\[360px\] { + max-height: 360px; +} +.max-h-\[55vh\] { + max-height: 55vh; +} +.max-h-\[70vh\] { + max-height: 70vh; +} +.max-h-\[80vh\] { + max-height: 80vh; +} +.max-h-\[90vh\] { + max-height: 90vh; +} +.max-h-\[min\(85vh\2c 740px\)\] { + max-height: min(85vh, 740px); +} +.max-h-full { + max-height: 100%; +} +.max-h-none { + max-height: none; +} +.min-h-0 { + min-height: 0; +} +.min-h-\[200px\] { + min-height: 200px; +} +.min-h-\[240px\] { + min-height: 240px; +} +.min-h-\[360px\] { + min-height: 360px; +} +.min-h-\[50vh\] { + min-height: 50vh; +} +.min-h-\[60vh\] { + min-height: 60vh; +} +.min-h-\[92px\] { + min-height: 92px; +} +.min-h-full { + min-height: 100%; +} +.min-h-screen { + min-height: 100vh; +} +.w-0 { + width: 0; +} +.w-1\.5 { + width: 0.375rem; +} +.w-10 { + width: 2.5rem; +} +.w-11 { + width: 2.75rem; +} +.w-12 { + width: 3rem; +} +.w-14 { + width: 3.5rem; +} +.w-16 { + width: 4rem; +} +.w-2 { + width: 0.5rem; +} +.w-2\.5 { + width: 0.625rem; +} +.w-20 { + width: 5rem; +} +.w-3 { + width: 0.75rem; +} +.w-3\.5 { + width: 0.875rem; +} +.w-32 { + width: 8rem; +} +.w-36 { + width: 9rem; +} +.w-4 { + width: 1rem; +} +.w-48 { + width: 12rem; +} +.w-5 { + width: 1.25rem; +} +.w-56 { + width: 14rem; +} +.w-6 { + width: 1.5rem; +} +.w-60 { + width: 15rem; +} +.w-64 { + width: 16rem; +} +.w-7 { + width: 1.75rem; +} +.w-8 { + width: 2rem; +} +.w-9 { + width: 2.25rem; +} +.w-\[11\.1\%\] { + width: 11.1%; +} +.w-\[18px\] { + width: 18px; +} +.w-\[33\.3\%\] { + width: 33.3%; +} +.w-\[380px\] { + width: 380px; +} +.w-\[min\(100\%\2c 1200px\)\] { + width: min(100%, 1200px); +} +.w-\[min\(100\%\2c 560px\)\] { + width: min(100%, 560px); +} +.w-\[min\(340px\2c calc\(100vw-1\.5rem\)\)\] { + width: min(340px, calc(100vw - 1.5rem)); +} +.w-\[min\(520px\2c 92vw\)\] { + width: min(520px, 92vw); +} +.w-\[min\(720px\2c 92vw\)\] { + width: min(720px, 92vw); +} +.w-\[min\(96vw\2c 1100px\)\] { + width: min(96vw, 1100px); +} +.w-fit { + width: -moz-fit-content; + width: fit-content; +} +.w-full { + width: 100%; +} +.w-px { + width: 1px; +} +.min-w-0 { + min-width: 0; +} +.min-w-5 { + min-width: 1.25rem; +} +.min-w-\[110px\] { + min-width: 110px; +} +.min-w-\[160px\] { + min-width: 160px; +} +.min-w-\[220px\] { + min-width: 220px; +} +.min-w-\[40px\] { + min-width: 40px; +} +.min-w-\[60px\] { + min-width: 60px; +} +.max-w-6xl { + max-width: 72rem; +} +.max-w-\[120px\] { + max-width: 120px; +} +.max-w-\[160px\] { + max-width: 160px; +} +.max-w-\[220px\] { + max-width: 220px; +} +.max-w-\[360px\] { + max-width: 360px; +} +.max-w-\[520px\] { + max-width: 520px; +} +.max-w-\[760px\] { + max-width: 760px; +} +.max-w-\[95vw\] { + max-width: 95vw; +} +.max-w-\[960px\] { + max-width: 960px; +} +.max-w-\[min\(520px\2c 90vw\)\] { + max-width: min(520px, 90vw); +} +.max-w-full { + max-width: 100%; +} +.max-w-md { + max-width: 28rem; +} +.max-w-screen-2xl { + max-width: 1536px; + margin-left: auto; + margin-right: auto; +} +.max-w-sm { + max-width: 24rem; +} +.max-w-xs { + max-width: 20rem; +} +.flex-1 { + flex: 1 1 0%; +} +.flex-\[1_1_0\] { + flex: 1 1 0; +} +.flex-\[1_1_140px\] { + flex: 1 1 140px; +} +.flex-\[1_1_160px\] { + flex: 1 1 160px; +} +.flex-\[1_1_260px\] { + flex: 1 1 260px; +} +.flex-shrink-0, +.shrink-0 { + flex-shrink: 0; +} +.grow { + flex-grow: 1; +} +.table-fixed { + table-layout: fixed; +} +.origin-left { + transform-origin: left; +} +.-translate-x-1\/2 { + --tw-translate-x: -50%; +} +.-translate-x-1\/2, +.-translate-y-1\/2 { + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} +.-translate-y-1\/2 { + --tw-translate-y: -50%; +} +.translate-y-0 { + --tw-translate-y: 0px; +} +.translate-y-0, +.translate-y-2 { + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} +.translate-y-2 { + --tw-translate-y: 0.5rem; +} +.rotate-180 { + --tw-rotate: 180deg; +} +.rotate-180, +.transform { + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} +@keyframes pulse { + 50% { + opacity: 0.5; + } +} +.animate-pulse { + animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; +} +@keyframes spin { + to { + transform: rotate(1turn); + } +} +.animate-spin { + animation: spin 1s linear infinite; +} +.cursor-grab { + cursor: grab; +} +.cursor-help { + cursor: help; +} +.cursor-not-allowed { + cursor: not-allowed; +} +.cursor-pointer { + cursor: pointer; +} +.select-none { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} +.resize-y { + resize: vertical; +} +.resize { + resize: both; +} +.list-disc { + list-style-type: disc; +} +.list-none { + list-style-type: none; +} +.appearance-none { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; +} +.auto-rows-\[minmax\(0\2c 1fr\)\] { + grid-auto-rows: minmax(0, 1fr); +} +.grid-cols-1 { + grid-template-columns: repeat(1, minmax(0, 1fr)); +} +.grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} +.grid-cols-6 { + grid-template-columns: repeat(6, minmax(0, 1fr)); +} +.grid-cols-\[90px_minmax\(0\2c 1fr\)\] { + grid-template-columns: 90px minmax(0, 1fr); +} +.grid-cols-\[repeat\(auto-fit\2c minmax\(140px\2c 1fr\)\)\] { + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); +} +.flex-row { + flex-direction: row; +} +.flex-col { + flex-direction: column; +} +.flex-col-reverse { + flex-direction: column-reverse; +} +.flex-wrap { + flex-wrap: wrap; +} +.place-items-center { + place-items: center; +} +.items-start { + align-items: flex-start; +} +.items-end { + align-items: flex-end; +} +.items-center { + align-items: center; +} +.items-stretch { + align-items: stretch; +} +.justify-start { + justify-content: flex-start; +} +.justify-end { + justify-content: flex-end; +} +.justify-center { + justify-content: center; +} +.justify-between { + justify-content: space-between; +} +.gap-0 { + gap: 0; +} +.gap-1\.5 { + gap: 0.375rem; +} +.gap-2 { + gap: 0.5rem; +} +.gap-3 { + gap: 0.75rem; +} +.gap-x-1\.5 { + -moz-column-gap: 0.375rem; + column-gap: 0.375rem; +} +.gap-x-3 { + -moz-column-gap: 0.75rem; + column-gap: 0.75rem; +} +.gap-y-1\.5 { + row-gap: 0.375rem; +} +.space-y-1 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.25rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); +} +.space-y-1\.5 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.375rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.375rem * var(--tw-space-y-reverse)); +} +.space-y-2 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.5rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.5rem * var(--tw-space-y-reverse)); +} +.space-y-3 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.75rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.75rem * var(--tw-space-y-reverse)); +} +.space-y-4 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(1rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(1rem * var(--tw-space-y-reverse)); +} +.space-y-5 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(1.25rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(1.25rem * var(--tw-space-y-reverse)); +} +.divide-y > :not([hidden]) ~ :not([hidden]) { + --tw-divide-y-reverse: 0; + border-top-width: calc(1px * (1 - var(--tw-divide-y-reverse))); + border-bottom-width: calc(1px * var(--tw-divide-y-reverse)); +} +.divide-slate-800\/50 > :not([hidden]) ~ :not([hidden]) { + border-color: rgba(30, 41, 59, 0.5); +} +.self-start { + align-self: flex-start; +} +.self-end { + align-self: flex-end; +} +.self-center { + align-self: center; +} +.overflow-auto { + overflow: auto; +} +.overflow-hidden { + overflow: hidden; +} +.overflow-visible { + overflow: visible; +} +.overflow-x-auto { + overflow-x: auto; +} +.overflow-y-auto { + overflow-y: auto; +} +.overflow-x-hidden { + overflow-x: hidden; +} +.truncate { + overflow: hidden; + white-space: nowrap; +} +.text-ellipsis, +.truncate { + text-overflow: ellipsis; +} +.whitespace-nowrap { + white-space: nowrap; +} +.whitespace-pre-line { + white-space: pre-line; +} +.break-words { + overflow-wrap: break-word; +} +.break-all { + word-break: break-all; +} +.rounded { + border-radius: 0.25rem; +} +.rounded-full { + border-radius: 9999px; +} +.rounded-lg { + border-radius: 0.5rem; +} +.rounded-md { + border-radius: 0.375rem; +} +.rounded-l-lg { + border-top-left-radius: 0.5rem; + border-bottom-left-radius: 0.5rem; +} +.rounded-r-lg { + border-top-right-radius: 0.5rem; + border-bottom-right-radius: 0.5rem; +} +.border { + border-width: 1px; +} +.border-0 { + border-width: 0; +} +.border-2 { + border-width: 2px; +} +.border-b { + border-bottom-width: 1px; +} +.border-l { + border-left-width: 1px; +} +.border-l-0 { + border-left-width: 0; +} +.border-l-4 { + border-left-width: 4px; +} +.border-r-0 { + border-right-width: 0; +} +.border-t { + border-top-width: 1px; +} +.border-dashed { + border-style: dashed; +} +.border-none { + border-style: none; +} +.border-\[\#333\] { + --tw-border-opacity: 1; + border-color: rgb(51 51 51 / var(--tw-border-opacity, 1)); +} +.border-\[\#444\] { + --tw-border-opacity: 1; + border-color: rgb(68 68 68 / var(--tw-border-opacity, 1)); +} +.border-\[var\(--color-accent\)\] { + border-color: var(--color-accent); +} +.border-\[var\(--color-action-border\)\] { + border-color: var(--color-action-border); +} +.border-\[var\(--color-bar-border\)\] { + border-color: var(--color-bar-border); +} +.border-\[var\(--color-bar-border\2c \#1e1e1e\)\] { + border-color: var(--color-bar-border, #1e1e1e); +} +.border-\[var\(--color-bar-surface-border\)\] { + border-color: var(--color-bar-surface-border); +} +.border-\[var\(--color-bar-surface-border\2c \#2a2f3a\)\] { + border-color: var(--color-bar-surface-border, #2a2f3a); +} +.border-\[var\(--color-border\)\] { + border-color: var(--color-border); +} +.border-\[var\(--color-border\2c \#222\)\] { + border-color: var(--color-border, #222); +} +.border-\[var\(--color-border\2c \#333\)\] { + border-color: var(--color-border, #333); +} +.border-\[var\(--color-border-strong\)\] { + border-color: var(--color-border-strong); +} +.border-\[var\(--color-danger-strong\)\] { + border-color: var(--color-danger-strong); +} +.border-\[var\(--color-input-border\)\] { + border-color: var(--color-input-border); +} +.border-\[var\(--color-success-strong\)\] { + border-color: var(--color-success-strong); +} +.border-amber-500 { + --tw-border-opacity: 1; + border-color: rgb(245 158 11 / var(--tw-border-opacity, 1)); +} +.border-amber-500\/30 { + border-color: rgba(245, 158, 11, 0.3); +} +.border-amber-600 { + --tw-border-opacity: 1; + border-color: rgb(217 119 6 / var(--tw-border-opacity, 1)); +} +.border-blue-500 { + --tw-border-opacity: 1; + border-color: rgb(59 130 246 / var(--tw-border-opacity, 1)); +} +.border-blue-500\/30 { + border-color: rgba(59, 130, 246, 0.3); +} +.border-emerald-500\/30 { + border-color: rgba(16, 185, 129, 0.3); +} +.border-red-500 { + --tw-border-opacity: 1; + border-color: rgb(239 68 68 / var(--tw-border-opacity, 1)); +} +.border-red-500\/30 { + border-color: rgba(239, 68, 68, 0.3); +} +.border-slate-600 { + --tw-border-opacity: 1; + border-color: rgb(71 85 105 / var(--tw-border-opacity, 1)); +} +.border-slate-700 { + --tw-border-opacity: 1; + border-color: rgb(51 65 85 / var(--tw-border-opacity, 1)); +} +.border-slate-700\/50 { + border-color: rgba(51, 65, 85, 0.5); +} +.border-slate-800 { + --tw-border-opacity: 1; + border-color: rgb(30 41 59 / var(--tw-border-opacity, 1)); +} +.border-transparent { + border-color: transparent; +} +.border-white\/10 { + border-color: hsla(0, 0%, 100%, 0.1); +} +.border-white\/15 { + border-color: hsla(0, 0%, 100%, 0.15); +} +.border-white\/20 { + border-color: hsla(0, 0%, 100%, 0.2); +} +.border-white\/30 { + border-color: hsla(0, 0%, 100%, 0.3); +} +.bg-\[\#111\] { + --tw-bg-opacity: 1; + background-color: rgb(17 17 17 / var(--tw-bg-opacity, 1)); +} +.bg-\[\#2cd3a7\] { + --tw-bg-opacity: 1; + background-color: rgb(44 211 167 / var(--tw-bg-opacity, 1)); +} +.bg-\[\#5b8cff\] { + --tw-bg-opacity: 1; + background-color: rgb(91 140 255 / var(--tw-bg-opacity, 1)); +} +.bg-\[\#a78bfa\] { + --tw-bg-opacity: 1; + background-color: rgb(167 139 250 / var(--tw-bg-opacity, 1)); +} +.bg-\[\#f87171\] { + --tw-bg-opacity: 1; + background-color: rgb(248 113 113 / var(--tw-bg-opacity, 1)); +} +.bg-\[\#fbbf24\] { + --tw-bg-opacity: 1; + background-color: rgb(251 191 36 / var(--tw-bg-opacity, 1)); +} +.bg-\[rgba\(0\2c 0\2c 0\2c \.55\)\] { + background-color: rgba(0, 0, 0, 0.55); +} +.bg-\[rgba\(0\2c 0\2c 0\2c \.82\)\] { + background-color: rgba(0, 0, 0, 0.82); +} +.bg-\[rgba\(168\2c 85\2c 247\2c \.18\)\] { + background-color: rgba(168, 85, 247, 0.18); +} +.bg-\[rgba\(255\2c 255\2c 255\2c 0\.3\)\] { + background-color: hsla(0, 0%, 100%, 0.3); +} +.bg-\[rgba\(30\2c 32\2c 38\2c 0\.8\)\] { + background-color: rgba(30, 32, 38, 0.8); +} +.bg-\[rgba\(30\2c 32\2c 38\2c 0\.82\)\] { + background-color: rgba(30, 32, 38, 0.82); +} +.bg-\[rgba\(30\2c 32\2c 38\2c 0\.85\)\] { + background-color: rgba(30, 32, 38, 0.85); +} +.bg-\[rgba\(30\2c 32\2c 38\2c 0\.9\)\] { + background-color: rgba(30, 32, 38, 0.9); +} +.bg-\[rgba\(34\2c 197\2c 94\2c \.18\)\] { + background-color: rgba(34, 197, 94, 0.18); +} +.bg-\[rgba\(59\2c 130\2c 246\2c \.18\)\] { + background-color: rgba(59, 130, 246, 0.18); +} +.bg-\[var\(--_accent\)\] { + background-color: var(-- accent); +} +.bg-\[var\(--color-accent\)\] { + background-color: var(--color-accent); +} +.bg-\[var\(--color-action\)\] { + background-color: var(--color-action); +} +.bg-\[var\(--color-bar-bg\)\] { + background-color: var(--color-bar-bg); +} +.bg-\[var\(--color-bar-bg\2c \#121212\)\] { + background-color: var(--color-bar-bg, #121212); +} +.bg-\[var\(--color-bar-surface\)\] { + background-color: var(--color-bar-surface); +} +.bg-\[var\(--color-bar-surface\2c \#11131a\)\] { + background-color: var(--color-bar-surface, #11131a); +} +.bg-\[var\(--color-bg\)\] { + background-color: var(--color-bg); +} +.bg-\[var\(--color-bg\2c \#0a0a0a\)\] { + background-color: var(--color-bg, #0a0a0a); +} +.bg-\[var\(--color-bg\2c \#0b0c0f\)\] { + background-color: var(--color-bg, #0b0c0f); +} +.bg-\[var\(--color-bg\2c \#0f1117\)\] { + background-color: var(--color-bg, #0f1117); +} +.bg-\[var\(--color-bg-soft\)\] { + background-color: var(--color-bg-soft); +} +.bg-\[var\(--color-canvas-bg\2c \#0f1117\)\] { + background-color: var(--color-canvas-bg, #0f1117); +} +.bg-\[var\(--color-danger-strong\)\] { + background-color: var(--color-danger-strong); +} +.bg-\[var\(--color-dropzone-bg\)\] { + background-color: var(--color-dropzone-bg); +} +.bg-\[var\(--color-input-bg\)\] { + background-color: var(--color-input-bg); +} +.bg-\[var\(--color-input-bg\2c \#11131a\)\] { + background-color: var(--color-input-bg, #11131a); +} +.bg-\[var\(--color-overlay\)\] { + background-color: var(--color-overlay); +} +.bg-\[var\(--color-panel-bg\)\] { + background-color: var(--color-panel-bg); +} +.bg-\[var\(--color-primary-dim\2c \#1a3a5c\)\] { + background-color: var(--color-primary-dim, #1a3a5c); +} +.bg-\[var\(--color-success-strong\)\] { + background-color: var(--color-success-strong); +} +.bg-\[var\(--color-surface\)\] { + background-color: var(--color-surface); +} +.bg-\[var\(--color-surface\2c \#0f172a\)\] { + background-color: var(--color-surface, #0f172a); +} +.bg-\[var\(--color-surface\2c \#1e1e1e\)\] { + background-color: var(--color-surface, #1e1e1e); +} +.bg-\[var\(--color-surface-alt\)\] { + background-color: var(--color-surface-alt); +} +.bg-\[var\(--color-text-dim\)\] { + background-color: var(--color-text-dim); +} +.bg-amber-400 { + --tw-bg-opacity: 1; + background-color: rgb(251 191 36 / var(--tw-bg-opacity, 1)); +} +.bg-amber-500 { + --tw-bg-opacity: 1; + background-color: rgb(245 158 11 / var(--tw-bg-opacity, 1)); +} +.bg-amber-500\/20 { + background-color: rgba(245, 158, 11, 0.2); +} +.bg-black { + --tw-bg-opacity: 1; + background-color: rgb(0 0 0 / var(--tw-bg-opacity, 1)); +} +.bg-black\/0 { + background-color: transparent; +} +.bg-black\/35 { + background-color: rgba(0, 0, 0, 0.35); +} +.bg-black\/50 { + background-color: rgba(0, 0, 0, 0.5); +} +.bg-black\/55 { + background-color: rgba(0, 0, 0, 0.55); +} +.bg-black\/60 { + background-color: rgba(0, 0, 0, 0.6); +} +.bg-black\/70 { + background-color: rgba(0, 0, 0, 0.7); +} +.bg-black\/80 { + background-color: rgba(0, 0, 0, 0.8); +} +.bg-black\/85 { + background-color: rgba(0, 0, 0, 0.85); +} +.bg-black\/\[\.35\] { + background-color: rgba(0, 0, 0, 0.35); +} +.bg-blue-500 { + --tw-bg-opacity: 1; + background-color: rgb(59 130 246 / var(--tw-bg-opacity, 1)); +} +.bg-blue-500\/20 { + background-color: rgba(59, 130, 246, 0.2); +} +.bg-blue-600 { + --tw-bg-opacity: 1; + background-color: rgb(37 99 235 / var(--tw-bg-opacity, 1)); +} +.bg-emerald-400 { + --tw-bg-opacity: 1; + background-color: rgb(52 211 153 / var(--tw-bg-opacity, 1)); +} +.bg-emerald-500 { + --tw-bg-opacity: 1; + background-color: rgb(16 185 129 / var(--tw-bg-opacity, 1)); +} +.bg-emerald-500\/20 { + background-color: rgba(16, 185, 129, 0.2); +} +.bg-emerald-600 { + --tw-bg-opacity: 1; + background-color: rgb(5 150 105 / var(--tw-bg-opacity, 1)); +} +.bg-red-400 { + --tw-bg-opacity: 1; + background-color: rgb(248 113 113 / var(--tw-bg-opacity, 1)); +} +.bg-red-500 { + --tw-bg-opacity: 1; + background-color: rgb(239 68 68 / var(--tw-bg-opacity, 1)); +} +.bg-red-500\/20 { + background-color: rgba(239, 68, 68, 0.2); +} +.bg-red-600 { + --tw-bg-opacity: 1; + background-color: rgb(220 38 38 / var(--tw-bg-opacity, 1)); +} +.bg-slate-400 { + --tw-bg-opacity: 1; + background-color: rgb(148 163 184 / var(--tw-bg-opacity, 1)); +} +.bg-slate-600 { + --tw-bg-opacity: 1; + background-color: rgb(71 85 105 / var(--tw-bg-opacity, 1)); +} +.bg-slate-700 { + --tw-bg-opacity: 1; + background-color: rgb(51 65 85 / var(--tw-bg-opacity, 1)); +} +.bg-slate-800 { + --tw-bg-opacity: 1; + background-color: rgb(30 41 59 / var(--tw-bg-opacity, 1)); +} +.bg-slate-800\/20 { + background-color: rgba(30, 41, 59, 0.2); +} +.bg-slate-800\/50 { + background-color: rgba(30, 41, 59, 0.5); +} +.bg-slate-800\/80 { + background-color: rgba(30, 41, 59, 0.8); +} +.bg-slate-900 { + --tw-bg-opacity: 1; + background-color: rgb(15 23 42 / var(--tw-bg-opacity, 1)); +} +.bg-transparent { + background-color: transparent; +} +.bg-white { + --tw-bg-opacity: 1; + background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); +} +.bg-white\/20 { + background-color: hsla(0, 0%, 100%, 0.2); +} +.bg-white\/30 { + background-color: hsla(0, 0%, 100%, 0.3); +} +.bg-gradient-to-br { + background-image: linear-gradient(to bottom right, var(--tw-gradient-stops)); +} +.bg-gradient-to-t { + background-image: linear-gradient(to top, var(--tw-gradient-stops)); +} +.from-\[var\(--color-action\)\] { + --tw-gradient-from: var(--color-action) var(--tw-gradient-from-position); + --tw-gradient-to: hsla(0, 0%, 100%, 0) var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); +} +.from-black\/60 { + --tw-gradient-from: rgba(0, 0, 0, 0.6) var(--tw-gradient-from-position); + --tw-gradient-to: transparent var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); +} +.to-\[var\(--color-action-border\)\] { + --tw-gradient-to: var(--color-action-border) var(--tw-gradient-to-position); +} +.to-transparent { + --tw-gradient-to: transparent var(--tw-gradient-to-position); +} +.bg-clip-text { + -webkit-background-clip: text; + background-clip: text; +} +.object-contain { + -o-object-fit: contain; + object-fit: contain; +} +.object-cover { + -o-object-fit: cover; + object-fit: cover; +} +.p-0 { + padding: 0; +} +.p-2 { + padding: 0.5rem; +} +.p-3 { + padding: 0.75rem; +} +.p-4 { + padding: 1rem; +} +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} +.px-3 { + padding-left: 0.75rem; + padding-right: 0.75rem; +} +.px-4 { + padding-left: 1rem; + padding-right: 1rem; +} +.px-\[var\(--overlay-gap\2c \.75rem\)\] { + padding-left: var(--overlay-gap, 0.75rem); + padding-right: var(--overlay-gap, 0.75rem); +} +.py-0 { + padding-top: 0; + padding-bottom: 0; +} +.py-2 { + padding-top: 0.5rem; + padding-bottom: 0.5rem; +} +.py-3 { + padding-top: 0.75rem; + padding-bottom: 0.75rem; +} +.py-4 { + padding-top: 1rem; + padding-bottom: 1rem; +} +.\!pl-9 { + padding-left: 2.25rem !important; +} +.pb-2 { + padding-bottom: 0.5rem; +} +.pb-3 { + padding-bottom: 0.75rem; +} +.pb-4 { + padding-bottom: 1rem; +} +.pb-\[calc\(var\(--bottom-nav-height\)\+var\(--overlay-gap\2c \.75rem\)\)\] { + padding-bottom: calc(var(--bottom-nav-height) + var(--overlay-gap, 0.75rem)); +} +.pl-4 { + padding-left: 1rem; +} +.pl-9 { + padding-left: 2.25rem; +} +.pr-9 { + padding-right: 2.25rem; +} +.pr-\[2\.1rem\] { + padding-right: 2.1rem; +} +.pr-\[3rem\] { + padding-right: 3rem; +} +.pt-2 { + padding-top: 0.5rem; +} +.pt-3 { + padding-top: 0.75rem; +} +.pt-4 { + padding-top: 1rem; +} +.pt-\[calc\(var\(--topbar-height\)\+1rem\)\] { + padding-top: calc(var(--topbar-height) + 1rem); +} +.pt-\[calc\(var\(--topbar-height\)\+var\(--overlay-gap\2c \.75rem\)\)\] { + padding-top: calc(var(--topbar-height) + var(--overlay-gap, 0.75rem)); +} +.pt-\[var\(--topbar-height\)\] { + padding-top: var(--topbar-height); +} +.text-left { + text-align: left; +} +.text-center { + text-align: center; +} +.text-right { + text-align: right; +} +.align-top { + vertical-align: top; +} +.align-middle { + vertical-align: middle; +} +.font-mono { + font-family: + ui-monospace, + SFMono-Regular, + Menlo, + Monaco, + Consolas, + Liberation Mono, + Courier New, + monospace; +} +.text-2xl { + font-size: 1.5rem; + line-height: 2rem; +} +.text-3xl { + font-size: 1.875rem; + line-height: 2.25rem; +} +.text-4xl { + font-size: 2.25rem; + line-height: 2.5rem; +} +.text-\[6rem\] { + font-size: 6rem; +} +.text-base { + font-size: 1rem; + line-height: 1.5rem; +} +.text-lg { + font-size: 1.125rem; + line-height: 1.75rem; +} +.text-sm { + font-size: 0.875rem; + line-height: 1.25rem; +} +.text-xl { + font-size: 1.25rem; + line-height: 1.75rem; +} +.text-xs { + font-size: 0.75rem; + line-height: 1rem; +} +.font-\[650\] { + font-weight: 650; +} +.font-black { + font-weight: 900; +} +.font-bold { + font-weight: 700; +} +.font-extrabold { + font-weight: 800; +} +.font-medium { + font-weight: 500; +} +.font-normal { + font-weight: 400; +} +.font-semibold { + font-weight: 600; +} +.uppercase { + text-transform: uppercase; +} +.lowercase { + text-transform: lowercase; +} +.capitalize { + text-transform: capitalize; +} +.normal-case { + text-transform: none; +} +.italic { + font-style: italic; +} +.tabular-nums { + --tw-numeric-spacing: tabular-nums; + font-variant-numeric: var(--tw-ordinal) var(--tw-slashed-zero) + var(--tw-numeric-figure) var(--tw-numeric-spacing) + var(--tw-numeric-fraction); +} +.leading-5 { + line-height: 1.25rem; +} +.leading-6 { + line-height: 1.5rem; +} +.leading-\[1\.1\] { + line-height: 1.1; +} +.leading-\[1\.2\] { + line-height: 1.2; +} +.leading-\[1\.3\] { + line-height: 1.3; +} +.leading-\[1\.45\] { + line-height: 1.45; +} +.leading-\[1\.4\] { + line-height: 1.4; +} +.leading-none { + line-height: 1; +} +.leading-relaxed { + line-height: 1.625; +} +.leading-snug { + line-height: 1.375; +} +.leading-tight { + line-height: 1.25; +} +.tracking-\[0\.05em\] { + letter-spacing: 0.05em; +} +.tracking-\[0\.08em\] { + letter-spacing: 0.08em; +} +.tracking-\[0\.3px\] { + letter-spacing: 0.3px; +} +.tracking-\[0\.4px\] { + letter-spacing: 0.4px; +} +.tracking-\[0\.5px\] { + letter-spacing: 0.5px; +} +.tracking-tight { + letter-spacing: -0.025em; +} +.tracking-tighter { + letter-spacing: -0.05em; +} +.tracking-wide { + letter-spacing: 0.025em; +} +.tracking-wider { + letter-spacing: 0.05em; +} +.tracking-widest { + letter-spacing: 0.1em; +} +.text-\[\#23272f\] { + --tw-text-opacity: 1; + color: rgb(35 39 47 / var(--tw-text-opacity, 1)); +} +.text-\[\#4ade80\] { + --tw-text-opacity: 1; + color: rgb(74 222 128 / var(--tw-text-opacity, 1)); +} +.text-\[\#60a5fa\] { + --tw-text-opacity: 1; + color: rgb(96 165 250 / var(--tw-text-opacity, 1)); +} +.text-\[\#9ca3af\] { + --tw-text-opacity: 1; + color: rgb(156 163 175 / var(--tw-text-opacity, 1)); +} +.text-\[\#c084fc\] { + --tw-text-opacity: 1; + color: rgb(192 132 252 / var(--tw-text-opacity, 1)); +} +.text-\[\#ddd\] { + --tw-text-opacity: 1; + color: rgb(221 221 221 / var(--tw-text-opacity, 1)); +} +.text-\[\#eee\] { + --tw-text-opacity: 1; + color: rgb(238 238 238 / var(--tw-text-opacity, 1)); +} +.text-\[\#f87171\] { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity, 1)); +} +.text-\[\#fbbf24\] { + --tw-text-opacity: 1; + color: rgb(251 191 36 / var(--tw-text-opacity, 1)); +} +.text-\[\#fff\] { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity, 1)); +} +.text-\[var\(--color-accent\)\] { + color: var(--color-accent); +} +.text-\[var\(--color-accent-glow\)\] { + color: var(--color-accent-glow); +} +.text-\[var\(--color-accent-glow\2c \#a78bfa\)\] { + color: var(--color-accent-glow, #a78bfa); +} +.text-\[var\(--color-action-alt-text\)\] { + color: var(--color-action-alt-text); +} +.text-\[var\(--color-action-border\)\] { + color: var(--color-action-border); +} +.text-\[var\(--color-bar-text\)\] { + color: var(--color-bar-text); +} +.text-\[var\(--color-bar-text\2c \#e6e6e6\)\] { + color: var(--color-bar-text, #e6e6e6); +} +.text-\[var\(--color-bar-text-muted\)\] { + color: var(--color-bar-text-muted); +} +.text-\[var\(--color-danger\)\] { + color: var(--color-danger); +} +.text-\[var\(--color-text\)\] { + color: var(--color-text); +} +.text-\[var\(--color-text\2c \#e6e6e6\)\] { + color: var(--color-text, #e6e6e6); +} +.text-\[var\(--color-text-dim\)\] { + color: var(--color-text-dim); +} +.text-\[var\(--color-text-muted\2c \#888\)\] { + color: var(--color-text-muted, #888); +} +.text-\[var\(--color-text-muted\2c \#a0a0a0\)\] { + color: var(--color-text-muted, #a0a0a0); +} +.text-\[var\(--color-text-muted\2c \#aaa\)\] { + color: var(--color-text-muted, #aaa); +} +.text-\[var\(--color-text-muted\2c \#bbb\)\] { + color: var(--color-text-muted, #bbb); +} +.text-\[var\(--font-size-sm\)\] { + color: var(--font-size-sm); +} +.text-\[var\(--font-size-xs\)\] { + color: var(--font-size-xs); +} +.text-amber-300 { + --tw-text-opacity: 1; + color: rgb(252 211 77 / var(--tw-text-opacity, 1)); +} +.text-amber-400 { + --tw-text-opacity: 1; + color: rgb(251 191 36 / var(--tw-text-opacity, 1)); +} +.text-black { + --tw-text-opacity: 1; + color: rgb(0 0 0 / var(--tw-text-opacity, 1)); +} +.text-blue-300 { + --tw-text-opacity: 1; + color: rgb(147 197 253 / var(--tw-text-opacity, 1)); +} +.text-blue-400 { + --tw-text-opacity: 1; + color: rgb(96 165 250 / var(--tw-text-opacity, 1)); +} +.text-emerald-300 { + --tw-text-opacity: 1; + color: rgb(110 231 183 / var(--tw-text-opacity, 1)); +} +.text-emerald-400 { + --tw-text-opacity: 1; + color: rgb(52 211 153 / var(--tw-text-opacity, 1)); +} +.text-inherit { + color: inherit; +} +.text-red-300 { + --tw-text-opacity: 1; + color: rgb(252 165 165 / var(--tw-text-opacity, 1)); +} +.text-red-400 { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity, 1)); +} +.text-slate-200 { + --tw-text-opacity: 1; + color: rgb(226 232 240 / var(--tw-text-opacity, 1)); +} +.text-slate-300 { + --tw-text-opacity: 1; + color: rgb(203 213 225 / var(--tw-text-opacity, 1)); +} +.text-slate-400 { + --tw-text-opacity: 1; + color: rgb(148 163 184 / var(--tw-text-opacity, 1)); +} +.text-slate-500 { + --tw-text-opacity: 1; + color: rgb(100 116 139 / var(--tw-text-opacity, 1)); +} +.text-slate-600 { + --tw-text-opacity: 1; + color: rgb(71 85 105 / var(--tw-text-opacity, 1)); +} +.text-transparent { + color: transparent; +} +.text-white { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity, 1)); +} +.text-white\/0 { + color: hsla(0, 0%, 100%, 0); +} +.text-white\/40 { + color: hsla(0, 0%, 100%, 0.4); +} +.text-white\/70 { + color: hsla(0, 0%, 100%, 0.7); +} +.text-white\/80 { + color: hsla(0, 0%, 100%, 0.8); +} +.text-white\/90 { + color: hsla(0, 0%, 100%, 0.9); +} +.no-underline { + text-decoration-line: none; +} +.placeholder-\[var\(--color-text-dim\)\]::-moz-placeholder { + color: var(--color-text-dim); +} +.placeholder-\[var\(--color-text-dim\)\]::placeholder { + color: var(--color-text-dim); +} +.placeholder-slate-500::-moz-placeholder { + --tw-placeholder-opacity: 1; + color: rgb(100 116 139 / var(--tw-placeholder-opacity, 1)); +} +.placeholder-slate-500::placeholder { + --tw-placeholder-opacity: 1; + color: rgb(100 116 139 / var(--tw-placeholder-opacity, 1)); +} +.accent-\[var\(--color-accent\)\] { + accent-color: var(--color-accent); +} +.accent-blue-500 { + accent-color: #3b82f6; +} +.opacity-0 { + opacity: 0; +} +.opacity-100 { + opacity: 1; +} +.opacity-20 { + opacity: 0.2; +} +.opacity-25 { + opacity: 0.25; +} +.opacity-30 { + opacity: 0.3; +} +.opacity-40 { + opacity: 0.4; +} +.opacity-50 { + opacity: 0.5; +} +.opacity-60 { + opacity: 0.6; +} +.opacity-70 { + opacity: 0.7; +} +.opacity-75 { + opacity: 0.75; +} +.opacity-80 { + opacity: 0.8; +} +.opacity-85 { + opacity: 0.85; +} +.opacity-\[\.55\] { + opacity: 0.55; +} +.shadow { + --tw-shadow: + 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1); + --tw-shadow-colored: + 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color); +} +.shadow, +.shadow-2xl { + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-2xl { + --tw-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + --tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color); +} +.shadow-\[0_0_0_1px_\#333\2c 0_4px_28px_rgba\(0\2c 0\2c 0\2c \.6\)\] { + --tw-shadow: 0 0 0 1px #333, 0 4px 28px rgba(0, 0, 0, 0.6); + --tw-shadow-colored: + 0 0 0 1px var(--tw-shadow-color), 0 4px 28px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-\[0_10px_30px_rgba\(0\2c 0\2c 0\2c 0\.35\)\] { + --tw-shadow: 0 10px 30px rgba(0, 0, 0, 0.35); + --tw-shadow-colored: 0 10px 30px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-\[0_24px_64px_rgba\(0\2c 0\2c 0\2c \.6\)\] { + --tw-shadow: 0 24px 64px rgba(0, 0, 0, 0.6); + --tw-shadow-colored: 0 24px 64px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-\[0_4px_20px_rgba\(0\2c 0\2c 0\2c 0\.4\)\] { + --tw-shadow: 0 4px 20px rgba(0, 0, 0, 0.4); + --tw-shadow-colored: 0 4px 20px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-\[0_8px_24px_rgba\(0\2c 0\2c 0\2c 0\.5\)\] { + --tw-shadow: 0 8px 24px rgba(0, 0, 0, 0.5); + --tw-shadow-colored: 0 8px 24px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-\[0_8px_24px_rgba\(0\2c 0\2c 0\2c 0\.6\)\] { + --tw-shadow: 0 8px 24px rgba(0, 0, 0, 0.6); + --tw-shadow-colored: 0 8px 24px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-\[var\(--shadow-2xl\2c 0_10px_40px_rgba\(0\2c 0\2c 0\2c \.6\)\)\] { + --tw-shadow: var(--shadow-2xl, 0 10px 40px rgba(0, 0, 0, 0.6)); + --tw-shadow-colored: 10px 40px var(--tw-shadow-color); +} +.shadow-\[var\(--shadow-2xl\2c 0_10px_40px_rgba\(0\2c 0\2c 0\2c \.6\)\)\], +.shadow-inner { + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-inner { + --tw-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.05); + --tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color); +} +.shadow-lg { + --tw-shadow: + 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1); + --tw-shadow-colored: + 0 10px 15px -3px var(--tw-shadow-color), + 0 4px 6px -4px var(--tw-shadow-color); +} +.shadow-lg, +.shadow-md { + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-md { + --tw-shadow: + 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); + --tw-shadow-colored: + 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color); +} +.shadow-sm { + --tw-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); +} +.shadow-sm, +.shadow-xl { + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-xl { + --tw-shadow: + 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1); + --tw-shadow-colored: + 0 20px 25px -5px var(--tw-shadow-color), + 0 8px 10px -6px var(--tw-shadow-color); +} +.shadow-\[var\(--shadow-lg\)\] { + --tw-shadow-color: var(--shadow-lg); + --tw-shadow: var(--tw-shadow-colored); +} +.shadow-\[var\(--shadow-md\)\] { + --tw-shadow-color: var(--shadow-md); + --tw-shadow: var(--tw-shadow-colored); +} +.shadow-\[var\(--shadow-sm\)\] { + --tw-shadow-color: var(--shadow-sm); + --tw-shadow: var(--tw-shadow-colored); +} +.outline { + outline-style: solid; +} +.ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 + var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 + calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color); +} +.ring, +.ring-1 { + box-shadow: + var(--tw-ring-offset-shadow), var(--tw-ring-shadow), + var(--tw-shadow, 0 0 #0000); +} +.ring-1 { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 + var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 + calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); +} +.ring-slate-700 { + --tw-ring-opacity: 1; + --tw-ring-color: rgb(51 65 85/var(--tw-ring-opacity, 1)); +} +.blur { + --tw-blur: blur(8px); +} +.blur, +.drop-shadow-\[0_1px_4px_rgba\(0\2c 0\2c 0\2c 0\.7\)\] { + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) + var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) + var(--tw-sepia) var(--tw-drop-shadow); +} +.drop-shadow-\[0_1px_4px_rgba\(0\2c 0\2c 0\2c 0\.7\)\] { + --tw-drop-shadow: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.7)); +} +.drop-shadow-lg { + --tw-drop-shadow: drop-shadow(0 10px 8px rgba(0, 0, 0, 0.04)) + drop-shadow(0 4px 3px rgba(0, 0, 0, 0.1)); +} +.drop-shadow-lg, +.invert { + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) + var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) + var(--tw-sepia) var(--tw-drop-shadow); +} +.invert { + --tw-invert: invert(100%); +} +.filter { + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) + var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) + var(--tw-sepia) var(--tw-drop-shadow); +} +.backdrop-blur { + --tw-backdrop-blur: blur(8px); + -webkit-backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) + var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) + var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) + var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) + var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) + var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) + var(--tw-backdrop-sepia); +} +.backdrop-blur-\[4px\], +.backdrop-blur-sm { + --tw-backdrop-blur: blur(4px); + -webkit-backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) + var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) + var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) + var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) + var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) + var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) + var(--tw-backdrop-sepia); +} +.transition { + transition-property: + color, + background-color, + border-color, + text-decoration-color, + fill, + stroke, + opacity, + box-shadow, + transform, + filter, + -webkit-backdrop-filter; + transition-property: + color, background-color, border-color, text-decoration-color, fill, stroke, + opacity, box-shadow, transform, filter, backdrop-filter; + transition-property: + color, + background-color, + border-color, + text-decoration-color, + fill, + stroke, + opacity, + box-shadow, + transform, + filter, + backdrop-filter, + -webkit-backdrop-filter; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-\[background\2c transform\] { + transition-property: background, transform; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-\[opacity\2c transform\] { + transition-property: opacity, transform; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-\[top\] { + transition-property: top; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-\[width\2c background-color\] { + transition-property: width, background-color; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-\[width\] { + transition-property: width; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-all { + transition-property: all; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-colors { + transition-property: + color, background-color, border-color, text-decoration-color, fill, stroke; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-opacity { + transition-property: opacity; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.transition-transform { + transition-property: transform; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 0.15s; +} +.duration-200 { + transition-duration: 0.2s; +} +.duration-300 { + transition-duration: 0.3s; +} +.duration-\[var\(--transition-fast\)\] { + transition-duration: var(--transition-fast); +} +.ease-in-out { + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); +} +.\[animation-direction\:reverse\] { + animation-direction: reverse; +} +.\[animation-duration\:12s\] { + animation-duration: 12s; +} +.\[animation-duration\:5s\] { + animation-duration: 5s; +} +.\[animation-duration\:8s\] { + animation-duration: 8s; +} +.\[filter\:drop-shadow\(0_2px_6px_rgba\(0\2c 0\2c 0\2c 0\.4\)\)\] { + filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.4)); +} +.\[grid-template-columns\:repeat\(auto-fill\2c minmax\(220px\2c 1fr\)\)\] { + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); +} +.\[grid-template-columns\:repeat\(auto-fit\2c minmax\(180px\2c 1fr\)\)\] { + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); +} +.\[grid-template-columns\:repeat\(auto-fit\2c minmax\(200px\2c 1fr\)\)\] { + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); +} +.\[grid-template-columns\:repeat\(auto-fit\2c minmax\(260px\2c 1fr\)\)\] { + grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); +} +.\[max-height\:calc\(100vh-var\(--topbar-height\)-var\(--bottom-nav-height\)-7rem\)\] { + max-height: calc( + 100vh - var(--topbar-height) - var(--bottom-nav-height) - 7rem + ); +} +.\[text-shadow\:0_1px_2px_rgba\(0\2c 0\2c 0\2c 0\.8\)\2c _0_0_4px_rgba\(0\2c 0\2c 0\2c 0\.8\)\] { + text-shadow: + 0 1px 2px rgba(0, 0, 0, 0.8), + 0 0 4px rgba(0, 0, 0, 0.8); +} +.\[width\:min\(320px\2c calc\(100vw-2rem\)\)\] { + width: min(320px, calc(100vw - 2rem)); +} +.placeholder\:text-\[var\(--color-text-dim\)\]::-moz-placeholder { + color: var(--color-text-dim); +} +.placeholder\:text-\[var\(--color-text-dim\)\]::placeholder { + color: var(--color-text-dim); +} +.before\:block:before { + content: var(--tw-content); + display: block; +} +.before\:pt-\[56\.25\%\]:before { + content: var(--tw-content); + padding-top: 56.25%; +} +.before\:content-\[\'\'\]:before { + --tw-content: ""; + content: var(--tw-content); +} +.first\:mt-0:first-child { + margin-top: 0; +} +.last\:border-0:last-child { + border-width: 0; +} +.empty\:hidden:empty { + display: none; +} +.hover\:border-\[var\(--color-accent\)\]:hover { + border-color: var(--color-accent); +} +.hover\:border-\[var\(--color-border-strong\)\]:hover { + border-color: var(--color-border-strong); +} +.hover\:border-\[var\(--color-danger-strong\)\]:hover { + border-color: var(--color-danger-strong); +} +.hover\:border-red-400:hover { + --tw-border-opacity: 1; + border-color: rgb(248 113 113 / var(--tw-border-opacity, 1)); +} +.hover\:border-red-500:hover { + --tw-border-opacity: 1; + border-color: rgb(239 68 68 / var(--tw-border-opacity, 1)); +} +.hover\:border-slate-600:hover { + --tw-border-opacity: 1; + border-color: rgb(71 85 105 / var(--tw-border-opacity, 1)); +} +.hover\:border-slate-700:hover { + --tw-border-opacity: 1; + border-color: rgb(51 65 85 / var(--tw-border-opacity, 1)); +} +.hover\:bg-\[var\(--color-accent\)\]:hover { + background-color: var(--color-accent); +} +.hover\:bg-\[var\(--color-action-hover\)\]:hover { + background-color: var(--color-action-hover); +} +.hover\:bg-\[var\(--color-bar-bg\)\]:hover { + background-color: var(--color-bar-bg); +} +.hover\:bg-\[var\(--color-bar-surface\)\]:hover { + background-color: var(--color-bar-surface); +} +.hover\:bg-\[var\(--color-bg-soft\)\]:hover { + background-color: var(--color-bg-soft); +} +.hover\:bg-\[var\(--color-danger\)\]:hover { + background-color: var(--color-danger); +} +.hover\:bg-\[var\(--color-danger-hover\)\]:hover { + background-color: var(--color-danger-hover); +} +.hover\:bg-\[var\(--color-danger-strong\)\]:hover { + background-color: var(--color-danger-strong); +} +.hover\:bg-\[var\(--color-success-hover\)\]:hover { + background-color: var(--color-success-hover); +} +.hover\:bg-\[var\(--color-surface\)\]:hover { + background-color: var(--color-surface); +} +.hover\:bg-\[var\(--color-surface-alt\)\]:hover { + background-color: var(--color-surface-alt); +} +.hover\:bg-\[var\(--color-surface-muted\)\]:hover { + background-color: var(--color-surface-muted); +} +.hover\:bg-\[var\(--color-surface-muted\2c \#1a1f2e\)\]:hover { + background-color: var(--color-surface-muted, #1a1f2e); +} +.hover\:bg-\[var\(--color-surface-raised\2c \#1e2030\)\]:hover { + background-color: var(--color-surface-raised, #1e2030); +} +.hover\:bg-black\/80:hover { + background-color: rgba(0, 0, 0, 0.8); +} +.hover\:bg-black\/90:hover { + background-color: rgba(0, 0, 0, 0.9); +} +.hover\:bg-blue-500:hover { + --tw-bg-opacity: 1; + background-color: rgb(59 130 246 / var(--tw-bg-opacity, 1)); +} +.hover\:bg-emerald-500:hover { + --tw-bg-opacity: 1; + background-color: rgb(16 185 129 / var(--tw-bg-opacity, 1)); +} +.hover\:bg-slate-600:hover { + --tw-bg-opacity: 1; + background-color: rgb(71 85 105 / var(--tw-bg-opacity, 1)); +} +.hover\:bg-slate-700:hover { + --tw-bg-opacity: 1; + background-color: rgb(51 65 85 / var(--tw-bg-opacity, 1)); +} +.hover\:bg-slate-800:hover { + --tw-bg-opacity: 1; + background-color: rgb(30 41 59 / var(--tw-bg-opacity, 1)); +} +.hover\:bg-slate-800\/50:hover { + background-color: rgba(30, 41, 59, 0.5); +} +.hover\:bg-white\/10:hover { + background-color: hsla(0, 0%, 100%, 0.1); +} +.hover\:text-\[var\(--color-accent-glow\)\]:hover { + color: var(--color-accent-glow); +} +.hover\:text-\[var\(--color-text\)\]:hover { + color: var(--color-text); +} +.hover\:text-black:hover { + --tw-text-opacity: 1; + color: rgb(0 0 0 / var(--tw-text-opacity, 1)); +} +.hover\:text-blue-300:hover { + --tw-text-opacity: 1; + color: rgb(147 197 253 / var(--tw-text-opacity, 1)); +} +.hover\:text-red-300:hover { + --tw-text-opacity: 1; + color: rgb(252 165 165 / var(--tw-text-opacity, 1)); +} +.hover\:text-red-400:hover { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity, 1)); +} +.hover\:text-slate-200:hover { + --tw-text-opacity: 1; + color: rgb(226 232 240 / var(--tw-text-opacity, 1)); +} +.hover\:text-slate-300:hover { + --tw-text-opacity: 1; + color: rgb(203 213 225 / var(--tw-text-opacity, 1)); +} +.hover\:text-white:hover { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity, 1)); +} +.hover\:underline:hover { + text-decoration-line: underline; +} +.hover\:opacity-100:hover { + opacity: 1; +} +.hover\:opacity-80:hover { + opacity: 0.8; +} +.hover\:ring-2:hover { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 + var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 + calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); + box-shadow: + var(--tw-ring-offset-shadow), var(--tw-ring-shadow), + var(--tw-shadow, 0 0 #0000); +} +.hover\:ring-\[var\(--color-action\)\]:hover { + --tw-ring-color: var(--color-action); +} +.hover\:brightness-110:hover { + --tw-brightness: brightness(1.1); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) + var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) + var(--tw-sepia) var(--tw-drop-shadow); +} +.focus\:border-\[var\(--color-accent\)\]:focus { + border-color: var(--color-accent); +} +.focus\:border-\[var\(--color-action\)\]:focus { + border-color: var(--color-action); +} +.focus\:border-\[var\(--color-action-border\)\]:focus { + border-color: var(--color-action-border); +} +.focus\:border-blue-500:focus { + --tw-border-opacity: 1; + border-color: rgb(59 130 246 / var(--tw-border-opacity, 1)); +} +.focus\:border-emerald-500:focus { + --tw-border-opacity: 1; + border-color: rgb(16 185 129 / var(--tw-border-opacity, 1)); +} +.focus\:shadow-\[0_0_0_2px_\#ffb84d33\]:focus { + --tw-shadow: 0 0 0 2px #ffb84d33; + --tw-shadow-colored: 0 0 0 2px var(--tw-shadow-color); + box-shadow: + var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.focus\:outline-none:focus { + outline: 2px solid transparent; + outline-offset: 2px; +} +.focus\:outline:focus { + outline-style: solid; +} +.focus\:outline-2:focus, +.focus\:outline-\[2px\]:focus { + outline-width: 2px; +} +.focus\:outline-offset-2:focus { + outline-offset: 2px; +} +.focus\:outline-\[\#3b4457\]:focus { + outline-color: #3b4457; +} +.focus\:outline-\[var\(--color-accent\)\]:focus { + outline-color: var(--color-accent); +} +.focus\:ring-1:focus { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 + var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 + calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); +} +.focus\:ring-1:focus, +.focus\:ring-2:focus { + box-shadow: + var(--tw-ring-offset-shadow), var(--tw-ring-shadow), + var(--tw-shadow, 0 0 #0000); +} +.focus\:ring-2:focus { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 + var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 + calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); +} +.focus\:ring-\[var\(--color-accent-soft\)\]:focus { + --tw-ring-color: var(--color-accent-soft); +} +.focus\:ring-\[var\(--color-action\)\]\/20:focus { + --tw-ring-color: color-mix(in srgb, var(--color-action) 20%, transparent); +} +.focus\:ring-\[var\(--color-action\)\]\/40:focus { + --tw-ring-color: color-mix(in srgb, var(--color-action) 40%, transparent); +} +.focus\:ring-\[var\(--color-action-border\)\]\/50:focus { + --tw-ring-color: color-mix(in srgb, var(--color-action-border) 50%, transparent); +} +.focus\:ring-blue-300\/20:focus { + --tw-ring-color: rgba(147, 197, 253, 0.2); +} +.focus\:ring-blue-300\/50:focus { + --tw-ring-color: rgba(147, 197, 253, 0.5); +} +.focus\:ring-blue-400:focus { + --tw-ring-opacity: 1; + --tw-ring-color: rgb(96 165 250/var(--tw-ring-opacity, 1)); +} +.focus\:ring-blue-400\/40:focus { + --tw-ring-color: rgba(96, 165, 250, 0.4); +} +.focus\:ring-blue-500:focus { + --tw-ring-opacity: 1; + --tw-ring-color: rgb(59 130 246/var(--tw-ring-opacity, 1)); +} +.focus\:ring-emerald-500:focus { + --tw-ring-opacity: 1; + --tw-ring-color: rgb(16 185 129/var(--tw-ring-opacity, 1)); +} +.focus\:ring-red-500\/50:focus { + --tw-ring-color: rgba(239, 68, 68, 0.5); +} +.focus\:ring-white\/30:focus { + --tw-ring-color: hsla(0, 0%, 100%, 0.3); +} +.focus\:ring-offset-1:focus { + --tw-ring-offset-width: 1px; +} +.focus\:ring-offset-2:focus { + --tw-ring-offset-width: 2px; +} +.focus\:ring-offset-\[var\(--color-bg\)\]:focus { + --tw-ring-offset-color: var(--color-bg); +} +.focus\:ring-offset-slate-900:focus { + --tw-ring-offset-color: #0f172a; +} +.focus-visible\:outline-none:focus-visible { + outline: 2px solid transparent; + outline-offset: 2px; +} +.active\:scale-90:active { + --tw-scale-x: 0.9; + --tw-scale-y: 0.9; + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} +.disabled\:cursor-default:disabled { + cursor: default; +} +.disabled\:cursor-not-allowed:disabled { + cursor: not-allowed; +} +.disabled\:opacity-40:disabled { + opacity: 0.4; +} +.disabled\:opacity-45:disabled { + opacity: 0.45; +} +.disabled\:opacity-60:disabled { + opacity: 0.6; +} +.group:hover .group-hover\:bg-black\/30 { + background-color: rgba(0, 0, 0, 0.3); +} +.group:hover .group-hover\:text-white { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity, 1)); +} +.group:hover .group-hover\:text-white\/80 { + color: hsla(0, 0%, 100%, 0.8); +} +.group:hover .group-hover\:opacity-100 { + opacity: 1; +} +.group:hover .group-hover\:ring-\[var\(--color-action\)\] { + --tw-ring-color: var(--color-action); +} +@media (max-width: 768px) { + .max-\[768px\]\:h-\[300px\] { + height: 300px; + } + .max-\[768px\]\:min-h-\[300px\] { + min-height: 300px; + } + .max-\[768px\]\:min-w-full { + min-width: 100%; + } + .max-\[768px\]\:flex-col { + flex-direction: column; + } + .max-\[768px\]\:p-4 { + padding: 1rem; + } + .max-\[768px\]\:px-3 { + padding-left: 0.75rem; + padding-right: 0.75rem; + } + .max-\[768px\]\:px-4 { + padding-left: 1rem; + padding-right: 1rem; + } + .max-\[768px\]\:pb-4 { + padding-bottom: 1rem; + } +} +@media (max-width: 700px) { + .max-\[700px\]\:left-4 { + left: 1rem; + } + .max-\[700px\]\:right-4 { + right: 1rem; + } + .max-\[700px\]\:w-auto { + width: auto; + } +} +@media (max-width: 680px) { + .max-\[680px\]\:bottom-2 { + bottom: 0.5rem; + } + .max-\[680px\]\:left-2 { + left: 0.5rem; + } + .max-\[680px\]\:right-2 { + right: 0.5rem; + } + .max-\[680px\]\:top-2 { + top: 0.5rem; + } +} +@media (max-width: 600px) { + .max-\[600px\]\:static { + position: static; + } + .max-\[600px\]\:col-\[1\/-1\] { + grid-column: 1/-1; + } + .max-\[600px\]\:row-\[1\] { + grid-row: 1; + } + .max-\[600px\]\:grid { + display: grid; + } + .max-\[600px\]\:h-11 { + height: 2.75rem; + } + .max-\[600px\]\:w-11 { + width: 2.75rem; + } + .max-\[600px\]\:translate-y-0 { + --tw-translate-y: 0px; + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + } + .max-\[600px\]\:grid-cols-\[auto_auto\] { + grid-template-columns: auto auto; + } + .max-\[600px\]\:grid-rows-\[1fr_auto\] { + grid-template-rows: 1fr auto; + } + .max-\[600px\]\:content-stretch { + align-content: stretch; + } + .max-\[600px\]\:items-center { + align-items: center; + } + .max-\[600px\]\:justify-center { + justify-content: center; + } + .max-\[600px\]\:justify-items-center { + justify-items: center; + } + .max-\[600px\]\:gap-\[var\(--overlay-gap\2c \.75rem\)\] { + gap: var(--overlay-gap, 0.75rem); + } + .max-\[600px\]\:justify-self-start { + justify-self: start; + } + .max-\[600px\]\:justify-self-end { + justify-self: end; + } + .max-\[600px\]\:pb-\[calc\(var\(--bottom-nav-height\)\+var\(--overlay-gap\2c \.75rem\)\+env\(safe-area-inset-bottom\2c 0px\)\)\] { + padding-bottom: calc( + var(--bottom-nav-height) + var(--overlay-gap, 0.75rem) + + env(safe-area-inset-bottom, 0px) + ); + } + .max-\[600px\]\:pl-\[calc\(var\(--overlay-gap\2c \.75rem\)\+env\(safe-area-inset-left\2c 0px\)\)\] { + padding-left: calc( + var(--overlay-gap, 0.75rem) + env(safe-area-inset-left, 0px) + ); + } + .max-\[600px\]\:pr-\[calc\(var\(--overlay-gap\2c \.75rem\)\+env\(safe-area-inset-right\2c 0px\)\)\] { + padding-right: calc( + var(--overlay-gap, 0.75rem) + env(safe-area-inset-right, 0px) + ); + } +} +@media (max-width: 480px) { + .max-\[480px\]\:h-\[240px\] { + height: 240px; + } + .max-\[480px\]\:min-h-\[240px\] { + min-height: 240px; + } + .max-\[480px\]\:text-xs { + font-size: 0.75rem; + line-height: 1rem; + } +.max-\[480px\]\:text-base { + font-size: 1rem; + line-height: 1.5rem; + } +} +@media (min-width: 640px) { + .sm\:ml-auto { + margin-left: auto; + } + .sm\:table-cell { + display: table-cell; + } + .sm\:h-\[92px\] { + height: 92px; + } + .sm\:w-\[180px\] { + width: 180px; + } + .sm\:w-\[92px\] { + width: 92px; + } + .sm\:w-auto { + width: auto; + } + .sm\:flex-none { + flex: none; + } + .sm\:grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .sm\:grid-cols-4 { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + .sm\:flex-row { + flex-direction: row; + } + .sm\:flex-nowrap { + flex-wrap: nowrap; + } + .sm\:items-start { + align-items: flex-start; + } + .sm\:items-center { + align-items: center; + } + .sm\:justify-end { + justify-content: flex-end; + } + .sm\:justify-between { + justify-content: space-between; + } + .sm\:gap-1\.5 { + gap: 0.375rem; + } + .sm\:gap-2 { + gap: 0.5rem; + } + .sm\:gap-3 { + gap: 0.75rem; + } +.sm\:space-y-6 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(1.5rem * (1 - var(--tw-space-y-reverse))); + margin-bottom: calc(1.5rem * var(--tw-space-y-reverse)); + } +.sm\:px-0 { + padding-left: 0; + padding-right: 0; + } + .sm\:px-4 { + padding-left: 1rem; + padding-right: 1rem; + } +.sm\:py-4 { + padding-top: 1rem; + padding-bottom: 1rem; + } +.sm\:text-left { + text-align: left; + } + .sm\:text-xs { + font-size: 0.75rem; + line-height: 1rem; + } + .sm\:text-sm { + font-size: 0.875rem; + line-height: 1.25rem; + } + .sm\:text-xl { + font-size: 1.25rem; + line-height: 1.75rem; + } +.sm\:leading-normal { + line-height: 1.5; + } + .sm\:\[grid-template-columns\:repeat\(auto-fill\2c minmax\(180px\2c 1fr\)\)\] { + grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); + } +} +@media (min-width: 768px) { + .md\:sticky { + position: sticky; + } + .md\:top-\[0\.5rem\] { + top: 0.5rem; + } + .md\:mt-0 { + margin-top: 0; + } + .md\:table-cell { + display: table-cell; + } + .md\:grid { + display: grid; + } + .md\:hidden { + display: none; + } + .md\:w-80 { + width: 20rem; + } + .md\:w-\[360px\] { + width: 360px; + } +.md\:w-auto { + width: auto; + } + .md\:min-w-\[160px\] { + min-width: 160px; + } + .md\:grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .md\:grid-cols-\[24px_1fr_auto\] { + grid-template-columns: 24px 1fr auto; + } + .md\:grid-cols-\[26px_88px_1fr_auto\] { + grid-template-columns: 26px 88px 1fr auto; + } + .md\:grid-cols-\[28px_1fr_auto\] { + grid-template-columns: 28px 1fr auto; + } + .md\:flex-row { + flex-direction: row; + } + .md\:flex-col { + flex-direction: column; + } + .md\:items-start { + align-items: flex-start; + } + .md\:items-center { + align-items: center; + } + .md\:gap-2 { + gap: 0.5rem; + } + .md\:gap-3 { + gap: 0.75rem; + } +} +@media (min-width: 1024px) { + .lg\:table-cell { + display: table-cell; + } + .lg\:w-\[460px\] { + width: 460px; + } + .lg\:grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .lg\:grid-cols-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .lg\:grid-cols-4 { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } +} +@media (min-width: 1280px) { +.xl\:grid-cols-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .xl\:grid-cols-6 { + grid-template-columns: repeat(6, minmax(0, 1fr)); + } +} +#main-content[data-banner-offset="1"] + .\[\#main-content\[data-banner-offset\=\'1\'\]_\&\]\:top-\[calc\(var\(--topbar-height\)\+3\.5rem\)\] { + top: calc(var(--topbar-height) + 3.5rem); +} +.\[\&_\.u-span-2\]\:col-span-2 .u-span-2 { + grid-column: span 2 / span 2; +} +@media (max-width: 900px) { + .max-\[900px\]\:\[\&_\.u-span-2\]\:col-span-1 .u-span-2 { + grid-column: span 1 / span 1; + } +} +.\[\&_\.u-span-3\]\:col-span-3 .u-span-3 { + grid-column: span 3 / span 3; +} +@media (max-width: 900px) { + .max-\[900px\]\:\[\&_\.u-span-3\]\:col-span-1 .u-span-3 { + grid-column: span 1 / span 1; + } +} +.\[\&_label\]\:text-\[var\(--color-text-dim\)\] label { + color: var(--color-text-dim); +} +.\[\&_label\]\:text-\[var\(--font-size-sm\)\] label { + font-size: var(--font-size-sm); +} + +/* Immersive media stage styles */ +body[data-ui-shell='immersive-media'] { + --kiosk-edge-offset: 0.85rem; + --kiosk-control-size: 2.5rem; + overflow: hidden; +} + +body[data-ui-shell='immersive-media'] [data-media-canvas='1'] { + position: fixed; + left: 0; + right: 0; + top: var(--topbar-height, 56px); + bottom: 0; + overflow: hidden; + background: var(--color-canvas-bg); +} + +@media (max-width: 767px) { + body[data-ui-shell='immersive-media'] [data-media-canvas='1'] { + bottom: var(--bottom-nav-height, 56px); + } +} + +body[data-ui-shell='immersive-media'].is-fullscreen [data-media-canvas='1'], +body[data-ui-shell='immersive-media'].is-chrome-hidden [data-media-canvas='1'] { + top: 0; + bottom: 0; + right: calc(100% - 100vw); +} + +body[data-ui-shell='immersive-media'].is-fullscreen [data-media-canvas='1'] { + right: 0; +} + +body[data-ui-shell='immersive-media'].is-fullscreen [data-topbar='1'], +body[data-ui-shell='immersive-media'].is-fullscreen [data-bottom-nav], +body[data-ui-shell='immersive-media'].is-chrome-hidden [data-topbar='1'], +body[data-ui-shell='immersive-media'].is-chrome-hidden [data-bottom-nav] { + display: none !important; +} + +body[data-ui-shell='immersive-media'] [data-media-primary='1'], +body[data-ui-shell='immersive-media'] [data-media-waiting='1'] { + position: absolute; + inset: 0; +} + +body[data-ui-shell='immersive-media'] [data-media-primary='1'] { + width: 100%; + height: 100%; + object-fit: contain; +} + +body[data-ui-shell='immersive-media'] [data-media-waiting='1'] { + display: flex; + align-items: center; + justify-content: center; + pointer-events: none; +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'], +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'], +body[data-ui-shell='immersive-media'] [data-overlay-progress='1'] { + position: absolute; +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'] { + z-index: 30; + display: flex; + gap: 0.5rem; +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'] button { + display: inline-flex; + align-items: center; + justify-content: center; + width: var(--kiosk-control-size); + height: var(--kiosk-control-size); + border: 1px solid var(--color-border-strong); + border-radius: 9999px; + background: color-mix(in srgb, var(--color-surface-raised) 85%, transparent); + color: var(--color-text); + box-shadow: var(--shadow-sm); + opacity: 0; + pointer-events: none; + transition: + opacity var(--transition-fast), + background-color var(--transition-fast), + border-color var(--transition-fast); +} + +body[data-ui-shell='immersive-media'].mouse-active [data-overlay-controls='1'] button, +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'] button.is-always-visible { + opacity: 1; + pointer-events: auto; +} + +@media (hover: none), (pointer: coarse) { + body[data-ui-shell='immersive-media'] [data-overlay-controls='1'] button { + opacity: 1; + pointer-events: auto; + } +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'] button:hover { + border-color: var(--color-input-border); + background: var(--color-surface-raised); +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'] button:focus-visible { + outline: none; + box-shadow: 0 0 0 2px var(--color-accent-soft); +} + +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'] { + z-index: 28; + pointer-events: none; + opacity: 0; + transition: opacity var(--transition-fast); +} + +body[data-ui-shell='immersive-media'].mouse-active [data-overlay-stats='1'], +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].is-visible, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].is-always-visible { + opacity: 1; +} + +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'] .u-hidden { + display: none !important; +} + +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'] .is-hover-only { + opacity: 0; + transition: opacity var(--transition-fast); +} + +body[data-ui-shell='immersive-media'].mouse-active [data-overlay-stats='1'] .is-hover-only, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].is-visible .is-hover-only, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].is-always-visible .is-hover-only { + opacity: 1; +} + +body[data-ui-shell='immersive-media'] [data-stats-shell='1'] { + display: inline-flex; + align-items: center; + gap: 0.5rem; + min-height: 2rem; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--color-surface) 84%, transparent); + color: var(--color-text); + padding: 0.35rem 0.7rem; + box-shadow: var(--shadow-sm); + backdrop-filter: blur(4px); +} + +body[data-ui-shell='immersive-media'] [data-stat='queue'], +body[data-ui-shell='immersive-media'] [data-stat='duration'] { + display: inline-flex; + align-items: center; + gap: 0.35rem; + font-size: var(--font-size-sm); +} + +body[data-ui-shell='immersive-media'] [data-stat-divider='1'] { + display: inline-block; +} + +body[data-ui-shell='immersive-media'] [data-overlay-progress='1'] { + left: 0; + right: 0; + bottom: 0; + z-index: 26; + height: 0.35rem; + background: color-mix(in srgb, var(--color-border-strong) 45%, transparent); + opacity: 0; + transition: opacity var(--transition-fast); +} + +body[data-ui-shell='immersive-media'] [data-overlay-progress='1'].is-visible, +body[data-ui-shell='immersive-media'] [data-overlay-progress='1'].is-always-visible { + opacity: 1; +} + +body[data-ui-shell='immersive-media'] [data-overlay-progress='1'].u-hidden { + display: none !important; +} + +body[data-ui-shell='immersive-media'] [data-progress-fill='1'] { + width: 0; + height: 100%; + background: linear-gradient(90deg, var(--color-action), var(--color-accent)); + transition: width 0.12s linear; +} + +body[data-ui-shell='immersive-media'] [data-overlay-backdrop='1'] { + position: fixed; + inset: 0; + z-index: 80; + background: transparent; + opacity: 0; + pointer-events: none; + transition: opacity var(--transition-fast); +} + +body[data-ui-shell='immersive-media'] [data-overlay-backdrop='1'].is-open { + opacity: 1; + pointer-events: auto; +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] { + position: fixed; + top: 0; + left: 0; + transform: translateY(0.35rem) scale(0.98); + transform-origin: top right; + width: min(440px, calc(100vw - 1.5rem)); + max-height: calc(100vh - 1.5rem); + max-height: calc(100dvh - 1.5rem); + overflow: auto; + z-index: 81; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-md); + background: var(--color-surface); + box-shadow: var(--shadow-2xl); + padding: 1rem; + opacity: 0; + pointer-events: none; + transition: + opacity var(--transition-fast), + transform var(--transition-fast); +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'].is-open { + opacity: 1; + pointer-events: auto; + transform: translateY(0) scale(1); +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'][data-anchor='above'] { + transform-origin: bottom right; +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'][data-anchor='below'] { + transform-origin: top right; +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] [data-ui-input='1'] { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] label { + font-size: var(--font-size-sm); + color: var(--color-text-dim); +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] label[data-inline-toggle='1'] { + flex-direction: row; + align-items: center; + color: var(--color-text); +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] input:not([type='checkbox']), +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] select { + width: 100%; +} + +body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] input[type='checkbox'] { + width: auto; + flex: 0 0 auto; +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'].u-pos-top-left, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].u-pos-top-left { + top: var(--kiosk-edge-offset); + left: var(--kiosk-edge-offset); +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'].u-pos-top-middle, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].u-pos-top-middle { + top: var(--kiosk-edge-offset); + left: 50%; + transform: translateX(-50%); +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'].u-pos-top-right, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].u-pos-top-right { + top: var(--kiosk-edge-offset); + right: var(--kiosk-edge-offset); +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'].u-pos-bottom-left, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].u-pos-bottom-left { + bottom: calc(var(--kiosk-edge-offset) + 0.35rem); + left: var(--kiosk-edge-offset); +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'].u-pos-bottom-middle, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].u-pos-bottom-middle { + bottom: calc(var(--kiosk-edge-offset) + 0.35rem); + left: 50%; + transform: translateX(-50%); +} + +body[data-ui-shell='immersive-media'] [data-overlay-controls='1'].u-pos-bottom-right, +body[data-ui-shell='immersive-media'] [data-overlay-stats='1'].u-pos-bottom-right { + bottom: calc(var(--kiosk-edge-offset) + 0.35rem); + right: var(--kiosk-edge-offset); +} + +@media (max-width: 767px) { + body[data-ui-shell='immersive-media'] { + --kiosk-edge-offset: 0.65rem; + --kiosk-control-size: 2.25rem; + } + + body[data-ui-shell='immersive-media'] [data-overlay-panel='1'] { + width: min(360px, calc(100vw - 1rem)); + max-height: calc(100dvh - 1rem); + padding: 0.85rem; + } + + body[data-ui-shell='immersive-media'] [data-stats-shell='1'] { + font-size: var(--font-size-xs); + padding: 0.3rem 0.55rem; + } + + body[data-ui-shell='immersive-media'] [data-stat='queue'], + body[data-ui-shell='immersive-media'] [data-stat='duration'] { + font-size: var(--font-size-xs); + } +} + +/* ============================================================ + DESIGN HARMONIZATION LAYER + Unifies visual language across apps still using slate utility classes. + ============================================================ */ + +/* Slate backgrounds -> shared surface tokens */ +.bg-slate-900 { + background-color: var(--color-surface); +} +.bg-slate-800 { + background-color: var(--color-surface-raised); +} +.bg-slate-800\/80 { + background-color: color-mix(in srgb, var(--color-surface-raised) 80%, transparent); +} +.bg-slate-800\/50 { + background-color: color-mix(in srgb, var(--color-surface-raised) 50%, transparent); +} +.bg-slate-800\/20 { + background-color: color-mix(in srgb, var(--color-surface-raised) 20%, transparent); +} +.bg-slate-700 { + background-color: var(--color-surface-muted); +} +/* Slate borders -> shared border tokens */ +.border-slate-800 { + border-color: var(--color-border); +} +.border-slate-700 { + border-color: var(--color-border-strong); +} +.border-slate-700\/50 { + border-color: color-mix(in srgb, var(--color-border-strong) 50%, transparent); +} +.border-slate-600 { + border-color: var(--color-input-border); +} +/* Slate text -> shared text tokens */ +.text-slate-200, +.text-slate-300 { + color: var(--color-text); +} +.text-slate-400 { + color: var(--color-text-muted); +} +.text-slate-500, +.text-slate-600 { + color: var(--color-text-dim); +} +/* Keep card/panel depth coherent across apps */ +:where(section, article, aside, nav, div).rounded-xl.border.border-slate-800.bg-slate-900, +:where(section, article, aside, nav, div).rounded-xl.border.border-slate-700.bg-slate-900 { + box-shadow: var(--shadow-sm); +} + +/* Harmonize heavier elevation utility with tokenized shadow */ +.shadow-xl { + box-shadow: var(--shadow-lg); +} diff --git a/shared/packages/media-shared-assets/public/favicon.svg b/shared/packages/media-shared-assets/public/favicon.svg new file mode 100644 index 0000000..32a7e66 --- /dev/null +++ b/shared/packages/media-shared-assets/public/favicon.svg @@ -0,0 +1,4 @@ + + MediaViewer + + diff --git a/shared/packages/media-shared-assets/public/images/default-avatar.svg b/shared/packages/media-shared-assets/public/images/default-avatar.svg new file mode 100644 index 0000000..e3abf76 --- /dev/null +++ b/shared/packages/media-shared-assets/public/images/default-avatar.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/shared/packages/media-shared-assets/public/js/admin/admin-users-page.js b/shared/packages/media-shared-assets/public/js/admin/admin-users-page.js new file mode 100644 index 0000000..7e6c308 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/admin/admin-users-page.js @@ -0,0 +1,17 @@ +(async () => { + try { + const response = await fetch('/admin/users'); + const payload = await response.json(); + const list = document.getElementById('usersList'); + if (!list) return; + list.textContent = ''; + (payload.users || []).forEach(user => { + const row = document.createElement('div'); + row.className = 'u-row'; + row.textContent = `${user.id} · ${user.email} · ${user.created_at}`; + list.appendChild(row); + }); + } catch (error) { + console.error(error); + } +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-form.js b/shared/packages/media-shared-assets/public/js/auth/auth-form.js new file mode 100644 index 0000000..5d4afab --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-form.js @@ -0,0 +1,47 @@ +(() => { + if (window.NCAuthForm) return; + + function bindJsonSubmit(options) { + const { endpoint, formId, resultId, buildPayload, onSuccess, onError } = options || {}; + + if (!endpoint || !formId || !resultId || typeof buildPayload !== 'function') { + return false; + } + + const form = document.getElementById(formId); + const result = document.getElementById(resultId); + if (!form || !result) return false; + + form.addEventListener('submit', async event => { + event.preventDefault(); + + try { + const response = await fetch(endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(buildPayload()), + }); + + const payload = await response.json(); + result.textContent = payload.message || JSON.stringify(payload); + + if (response.ok && typeof onSuccess === 'function') { + onSuccess(payload, response); + } else if (!response.ok && typeof onError === 'function') { + onError(payload, response); + } + } catch (error) { + result.textContent = 'Request failed. Please try again.'; + if (typeof onError === 'function') { + onError({ error: error && error.message ? error.message : String(error) }, null); + } + } + }); + + return true; + } + + window.NCAuthForm = { + bindJsonSubmit, + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-guard.js b/shared/packages/media-shared-assets/public/js/auth/auth-guard.js new file mode 100644 index 0000000..12d1813 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-guard.js @@ -0,0 +1,13 @@ +(() => { + const opener = document.getElementById('authLoginOpenBtn'); + if (!opener) return; + const buttons = document.querySelectorAll('[data-auth-guard-login]'); + buttons.forEach(button => { + if (button.dataset.authGuardWired === '1') return; + button.dataset.authGuardWired = '1'; + button.addEventListener('click', event => { + event.preventDefault(); + opener.click(); + }); + }); +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-modal.js b/shared/packages/media-shared-assets/public/js/auth/auth-modal.js new file mode 100644 index 0000000..96b047e --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-modal.js @@ -0,0 +1,646 @@ +// Shared Auth Modals (login + signup) +/* global toast */ +(function () { + // Button references - may not exist yet if using dynamic component loading + let loginOpenBtn = document.getElementById('authLoginOpenBtn'); + let signupOpenBtn = document.getElementById('authSignupOpenBtn'); + let logoutBtn = document.getElementById('authLogoutBtn'); + let profileMenu = document.getElementById('authProfileMenu'); + + // Overlay references - may not exist yet if using dynamic component loading + let loginOverlay = document.getElementById('authLoginOverlay'); + let signupOverlay = document.getElementById('authSignupOverlay'); + let overlays = [loginOverlay, signupOverlay].filter(Boolean); + // eslint-disable-next-line no-unused-vars + let _loginPanel = loginOverlay ? loginOverlay.querySelector('#authLoginPanel') : null; + let signupPanel = signupOverlay ? signupOverlay.querySelector('#authSignupPanel') : null; + let submitBtns = document.querySelectorAll('[data-auth-submit]'); + let pwInput = document.getElementById('signupPassword'); + let pwMeter = document.getElementById('signupPwMeter'); + let pwFeedback = document.getElementById('signupPwFeedback'); + let pwConfirm = document.getElementById('signupConfirm'); + let pwConfirmErr = document.getElementById('signupConfirmError'); + let loginTotpRow = document.getElementById('loginTotpRow'); + let loginTotpInput = document.getElementById('loginTotp'); + let loginTotpHint = document.getElementById('loginTotpHint'); + let isAdminApp = !!document.querySelector('[data-bottom-nav] a[href="/dashboard"]'); + + const STORAGE_KEY = 'authLoggedIn'; + let authKnown = false; + let authLoggedIn = false; + let buttonListenersAttached = false; + let overlayListenersAttached = false; + + // Optimistically initialize from localStorage to avoid button flicker on page load + // This will be confirmed/corrected by the /auth/me fetch below + try { + const storedAuth = localStorage.getItem(STORAGE_KEY); + if (storedAuth === '1') { + authKnown = true; + authLoggedIn = true; + } + } catch { + // LocalStorage might not be available in some contexts + } + + // Function to refresh button references (for dynamic component loading) + function refreshButtonReferences() { + loginOpenBtn = document.getElementById('authLoginOpenBtn'); + signupOpenBtn = document.getElementById('authSignupOpenBtn'); + logoutBtn = document.getElementById('authLogoutBtn'); + profileMenu = document.getElementById('authProfileMenu'); + // Reset dropdown listener flag so toggle is re-attached to fresh DOM elements + buttonListenersAttached = false; + } + + // Function to refresh overlay references (for dynamic component loading) + function refreshOverlayReferences() { + loginOverlay = document.getElementById('authLoginOverlay'); + signupOverlay = document.getElementById('authSignupOverlay'); + overlays = [loginOverlay, signupOverlay].filter(Boolean); + _loginPanel = loginOverlay ? loginOverlay.querySelector('#authLoginPanel') : null; + signupPanel = signupOverlay ? signupOverlay.querySelector('#authSignupPanel') : null; + submitBtns = document.querySelectorAll('[data-auth-submit]'); + pwInput = document.getElementById('signupPassword'); + pwMeter = document.getElementById('signupPwMeter'); + pwFeedback = document.getElementById('signupPwFeedback'); + pwConfirm = document.getElementById('signupConfirm'); + pwConfirmErr = document.getElementById('signupConfirmError'); + loginTotpRow = document.getElementById('loginTotpRow'); + loginTotpInput = document.getElementById('loginTotp'); + loginTotpHint = document.getElementById('loginTotpHint'); + isAdminApp = !!document.querySelector('[data-bottom-nav] a[href="/dashboard"]'); + // Reset listener flags when overlays are re-loaded + overlayListenersAttached = false; + } + + function setHiddenClass(element, hidden) { + if (!element) return; + element.classList.toggle('hidden', !!hidden); + } + + function setLoginTotpPrompt(visible, message = '') { + if (!loginTotpRow) return; + setHiddenClass(loginTotpRow, !visible); + if (loginTotpHint) { + loginTotpHint.textContent = + message || 'Two-factor authentication is enabled for this account.'; + } + if (!visible && loginTotpInput) { + loginTotpInput.value = ''; + } + } + + function isLoggedIn() { + return authKnown && authLoggedIn; + } + function setLoggedIn(v) { + authKnown = true; + authLoggedIn = !!v; + if (v) { + localStorage.setItem(STORAGE_KEY, '1'); + } else { + localStorage.removeItem(STORAGE_KEY); + } + updateHeaderButton(); + } + + // Toggle both the HTML hidden attribute (accessibility/semantics) and the + // Tailwind .hidden CSS class. Tailwind's preflight wraps [hidden] in + // :where() (zero specificity) so utility classes like .inline-flex override + // it. The .hidden utility class has normal specificity and wins correctly. + function setHidden(el, hide) { + if (!el) return; + el.hidden = !!hide; + el.classList.toggle('hidden', !!hide); + } + + function updateHeaderButton() { + if (isLoggedIn()) { + setHidden(loginOpenBtn, true); + setHidden(signupOpenBtn, true); + setHidden(profileMenu, false); + } else { + setHidden(loginOpenBtn, false); + if (loginOpenBtn) { + loginOpenBtn.setAttribute('aria-haspopup', 'dialog'); + loginOpenBtn.title = 'Log in'; + } + // Keep signup button hidden - users can access signup via the "Sign up" link in the login modal + setHidden(signupOpenBtn, true); + setHidden(profileMenu, true); + // Ensure dropdown is closed when logging out + const dropdown = document.getElementById('authProfileDropdown'); + const profileBtn = document.getElementById('authProfileBtn'); + if (dropdown) { + dropdown.classList.add('hidden'); + } + if (profileBtn) { + profileBtn.setAttribute('aria-expanded', 'false'); + } + } + } + + function isBootstrapLocked(overlay) { + return overlay && overlay.querySelector('[data-admin-bootstrap]') != null; + } + function anyOverlayOpen() { + return overlays.some(item => item && item.hidden === false); + } + + function setNoScroll(enabled) { + document.documentElement.classList.toggle('overflow-hidden', !!enabled); + document.body.classList.toggle('overflow-hidden', !!enabled); + } + + function openOverlay(overlay) { + if (!overlay) return; + overlays.forEach(item => { + if (item) setHidden(item, item !== overlay); + }); + if (overlay === loginOverlay) setLoginTotpPrompt(false); + setHidden(overlay, false); + setNoScroll(true); + setTimeout(() => { + const el = overlay.querySelector('input'); + if (el) el.focus(); + }, 0); + } + + function switchOverlay(fromOverlay, toOverlay) { + if (!fromOverlay || !toOverlay) return; + setHidden(fromOverlay, true); + setHidden(toOverlay, false); + if (toOverlay === loginOverlay) setLoginTotpPrompt(false); + // Keep scroll lock active during switch + setTimeout(() => { + const el = toOverlay.querySelector('input'); + if (el) el.focus(); + }, 0); + } + + function closeOverlay(overlay) { + if (!overlay) return; + setHidden(overlay, true); + if (!anyOverlayOpen()) setNoScroll(false); + } + + function closeAll() { + overlays.forEach(item => { + if (item) setHidden(item, true); + }); + setNoScroll(false); + } + + async function handleLogout() { + // Verify session still valid first (in case local flag drifted) + try { + const r = await fetch('/auth/me'); + const j = await r.json().catch(() => ({})); + if (!r.ok || !j?.user) { + setLoggedIn(false); + // Always redirect to root; each app's root resolves to its main page (Admin -> /dashboard, Forge -> /generator) + window.location.replace('/'); + return; + } + } catch { + /* ignore session probe failure */ + } + try { + await fetch('/auth/logout', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }); + } catch { + /* ignore network */ + } + setLoggedIn(false); + // Provide lightweight feedback then redirect to canonical root for ALL apps + if (window.toast && typeof toast?.info === 'function') { + toast.info('Logged out'); + } else { + console.info('[LOGOUT] Logged out'); + } + // Unified behavior: always navigate to root. Individual apps define their own root redirect target. + window.location.replace('/'); + } + + // Header login/signup buttons - wrapped in function to support dynamic loading + function attachButtonListeners() { + // Only attach once to prevent duplicate listeners + if (buttonListenersAttached) return; + + if (loginOpenBtn) { + loginOpenBtn.addEventListener('click', () => { + openOverlay(loginOverlay); + }); + } + if (signupOpenBtn) { + signupOpenBtn.addEventListener('click', () => { + openOverlay(signupOverlay); + }); + } + + if (logoutBtn) { + logoutBtn.addEventListener('click', handleLogout); + } + + // Profile dropdown toggle + const profileBtn = document.getElementById('authProfileBtn'); + const profileDropdown = document.getElementById('authProfileDropdown'); + if (profileBtn && profileDropdown) { + profileBtn.addEventListener('click', e => { + e.stopPropagation(); + const isOpen = !profileDropdown.classList.contains('hidden'); + profileDropdown.classList.toggle('hidden', isOpen); + profileBtn.setAttribute('aria-expanded', String(!isOpen)); + profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => { + el.tabIndex = isOpen ? -1 : 0; + }); + }); + // Close when clicking outside + document.addEventListener('click', () => { + if (!profileDropdown.classList.contains('hidden')) { + profileDropdown.classList.add('hidden'); + profileBtn.setAttribute('aria-expanded', 'false'); + profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => { + el.tabIndex = -1; + }); + } + }); + // Close on Escape + document.addEventListener('keydown', e => { + if (e.key === 'Escape' && !profileDropdown.classList.contains('hidden')) { + profileDropdown.classList.add('hidden'); + profileBtn.setAttribute('aria-expanded', 'false'); + profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => { + el.tabIndex = -1; + }); + profileBtn.focus(); + } + }); + } + + if (loginOpenBtn || signupOpenBtn || logoutBtn || profileMenu) { + buttonListenersAttached = true; + } + } + + // Initial attachment (buttons may not exist yet if using component loader) + attachButtonListeners(); + + // Initial button visibility update (will be called again after components load or /auth/me completes) + updateHeaderButton(); + + // Function to attach overlay listeners (for dynamic component loading) + function attachOverlayListeners() { + // Only attach once to prevent duplicate listeners + if (overlayListenersAttached || overlays.length === 0) return; + + // Close handlers + // Close logic disabled when bootstrap admin (modal element has data-admin-bootstrap). + // Additionally, if overlay has data-lock-close (set by MediaModerator), backdrop click will not close. + overlays.forEach(overlay => { + if (!overlay) return; + const closeBtn = overlay.querySelector('button[aria-label="Close"]'); + if (closeBtn) { + closeBtn.addEventListener('click', () => { + closeOverlay(overlay); + }); + } + overlay.addEventListener('click', e => { + const lockBackdrop = overlay.hasAttribute('data-lock-close'); + if (e.target === overlay && !isBootstrapLocked(overlay) && !lockBackdrop) + closeOverlay(overlay); + }); + }); + + // Escape key handler + const escapeHandler = e => { + if (e.key !== 'Escape') return; + overlays.forEach(overlay => { + if (!overlay || overlay.hidden) return; + const lockBackdrop = overlay.hasAttribute('data-lock-close'); + if (!isBootstrapLocked(overlay) && !lockBackdrop) closeOverlay(overlay); + }); + }; + // Store handler reference to prevent duplicates + if (!window.__authModalEscapeHandler) { + window.__authModalEscapeHandler = escapeHandler; + window.addEventListener('keydown', escapeHandler); + } + + // Prevent form submission and call backend + overlays.forEach(overlay => { + if (!overlay) return; + overlay.addEventListener('submit', e => e.preventDefault()); + }); + + // Enter key submits the active overlay (but not when a non-submit button has focus, + // e.g. the switchToLogin / switchToSignup links — let the browser fire their click) + overlays.forEach(overlay => { + if (!overlay) return; + overlay.addEventListener('keydown', e => { + if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.altKey) { + const focused = document.activeElement; + if ( + focused && + focused.tagName === 'BUTTON' && + !focused.hasAttribute('data-auth-submit') + ) { + return; // let the focused button handle its own click + } + e.preventDefault(); + const mode = overlay.getAttribute('data-auth-mode') || 'login'; + handleSubmit(mode); + } + }); + }); + + // Submit button handlers + submitBtns.forEach(btn => { + btn.addEventListener('click', async () => { + const mode = btn.getAttribute('data-mode'); + await handleSubmit(mode); + }); + }); + + // Password strength listeners + if (pwInput) { + pwInput.addEventListener('input', () => { + updatePwStrength(); + updateSignupState(); + }); + } + if (pwConfirm) { + pwConfirm.addEventListener('input', updateSignupState); + } + updatePwStrength(); + updateSignupState(); + + // Password visibility toggles + overlays.forEach(overlay => { + if (!overlay) return; + overlay.querySelectorAll('button[data-target]').forEach(btn => { + btn.addEventListener('click', () => { + const targetId = btn.getAttribute('data-target'); + const input = targetId ? overlay.querySelector('#' + CSS.escape(targetId)) : null; + if (!input) return; + const isPw = input.getAttribute('type') === 'password'; + input.setAttribute('type', isPw ? 'text' : 'password'); + // Swap icon + const icon = btn.querySelector('i'); + if (icon) { + icon.classList.toggle('fa-eye'); + icon.classList.toggle('fa-eye-slash'); + } + // Keep focus on input + input.focus(); + }); + }); + }); + + // Switch between login and signup overlays + const switchToSignupBtn = document.getElementById('switchToSignup'); + const switchToLoginBtn = document.getElementById('switchToLogin'); + + if (switchToSignupBtn && loginOverlay && signupOverlay) { + switchToSignupBtn.addEventListener('click', e => { + e.preventDefault(); + switchOverlay(loginOverlay, signupOverlay); + }); + } + + if (switchToLoginBtn && loginOverlay && signupOverlay) { + switchToLoginBtn.addEventListener('click', e => { + e.preventDefault(); + switchOverlay(signupOverlay, loginOverlay); + }); + } + + // Initialize overlays to hidden + overlays.forEach(overlay => { + if (!overlay) return; + setHidden(overlay, true); + overlay.classList.remove('active'); + }); + + overlayListenersAttached = true; + } + + // Initial overlay setup + attachOverlayListeners(); + + // Submission helper used by both buttons and Enter key (needs to be accessible before listeners) + async function handleSubmit(mode) { + try { + const isSignup = mode === 'signup' && signupPanel; + let payload; + if (isSignup) { + const email = document.getElementById('signupEmail')?.value || ''; + const password = document.getElementById('signupPassword')?.value || ''; + const confirm = document.getElementById('signupConfirm')?.value || ''; + const username = document.getElementById('signupUsername')?.value || ''; + if (password !== confirm) { + if (window.toast) { + toast.error('Passwords do not match'); + } else { + alert('Passwords do not match'); + } + return; + } + if (scorePassword(password) < 3) { + if (window.toast) { + toast.error('Password is too weak'); + } else { + alert('Password is too weak'); + } + return; + } + payload = { email, password, username }; + } else { + payload = { + email: document.getElementById('loginEmail')?.value || '', + password: document.getElementById('loginPassword')?.value || '', + totpToken: (loginTotpInput?.value || '').trim(), + }; + } + const res = await fetch(`/auth/${isSignup ? 'signup' : 'login'}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + if (!isSignup && data?.mfaRequired) { + setLoginTotpPrompt(true, data?.error || 'Authenticator code required'); + if (loginTotpInput) loginTotpInput.focus(); + } + throw new Error(data?.error || 'Request failed'); + } + if (!isSignup) setLoginTotpPrompt(false); + setLoggedIn(true); + const activeOverlay = isSignup ? signupOverlay : loginOverlay; + if (!isBootstrapLocked(activeOverlay)) closeAll(); + try { + window.dispatchEvent( + new CustomEvent('auth:login-success', { detail: { mode: isSignup ? 'signup' : 'login' } }) + ); + } catch { + /* ignore */ + } + if (window.toast && typeof toast?.success === 'function') { + toast.success( + isSignup ? 'Account created. You are now logged in.' : 'Logged in successfully.' + ); + } + // If inside admin app, always redirect to dashboard after login + if (isAdminApp) { + window.location.replace('/dashboard'); + } + } catch (e) { + if (window.toast && typeof toast?.error === 'function') { + toast.error(e?.message || 'Login failed'); + } else { + alert(e?.message || 'Login failed'); + } + } + } + + // (keydown submit handler is registered inside attachOverlayListeners above) + // Password strength evaluation + function scorePassword(p) { + if (!p) return 0; + let score = 0; + const length = p.length; + if (length >= 6) score += 1; + if (length >= 10) score += 1; + if (/[a-z]/.test(p) && /[A-Z]/.test(p)) score += 1; + if (/\d/.test(p)) score += 1; + if (/[^A-Za-z0-9]/.test(p)) score += 1; + if (length >= 14) score += 1; + return Math.min(score, 5); // 0-5 + } + function describeScore(s) { + switch (s) { + case 0: + return 'Enter a password'; + case 1: + return 'Very weak'; + case 2: + return 'Weak'; + case 3: + return 'Fair'; + case 4: + return 'Good'; + case 5: + return 'Strong'; + default: + return ''; + } + } + function updatePwStrength() { + if (!pwInput || !pwMeter || !pwFeedback) return; + const val = pwInput.value || ''; + const s = scorePassword(val); + pwMeter.dataset.score = String(s); + pwFeedback.textContent = describeScore(s); + // Visual width & color via inline style (can be refined in CSS) + const bar = pwMeter.querySelector('span'); + if (bar) { + const pct = (s / 5) * 100; + bar.style.width = pct + '%'; + const colorClasses = [ + 'bg-red-500', + 'bg-amber-500', + 'bg-amber-400', + 'bg-emerald-500', + 'bg-emerald-500', + ]; + colorClasses.forEach(c => bar.classList.remove(c)); + if (s >= 5) bar.classList.add('bg-emerald-500'); + else if (s >= 4) bar.classList.add('bg-emerald-500'); + else if (s >= 3) bar.classList.add('bg-amber-400'); + else if (s >= 2) bar.classList.add('bg-amber-500'); + else bar.classList.add('bg-red-500'); + } + } + function updateSignupState() { + const btn = signupOverlay + ? signupOverlay.querySelector('[data-auth-submit][data-mode="signup"]') + : null; + if (!btn) return; + const pw = pwInput ? pwInput.value || '' : ''; + const cf = pwConfirm ? pwConfirm.value || '' : ''; + const s = scorePassword(pw); + const okStrength = s >= 3; // Fair or better + const match = pw && cf && pw === cf; + if (pwConfirmErr) { + setHiddenClass(pwConfirmErr, !(cf && !match)); + } + btn.disabled = !(okStrength && match); + } + + // Initialize scroll lock state (uses overflow-hidden Tailwind class) + setNoScroll(false); + + // Check authentication status + (async () => { + try { + const r = await fetch('/auth/me'); + if (r.ok) { + const j = await r.json(); + const isLoggedIn = !!(j && j.user); + setLoggedIn(isLoggedIn); + } else { + setLoggedIn(false); + } + } catch { + setLoggedIn(false); + } + // Admin bootstrap detection must run only in MediaModerator. + if (isAdminApp) { + try { + const r2 = await fetch('/auth/bootstrap/admin-needed'); + if (r2.ok) { + const j2 = await r2.json().catch(() => ({})); + if (j2 && j2.adminNeeded) { + const modalEl = signupOverlay ? signupOverlay.querySelector('[role="document"]') : null; + if (modalEl) modalEl.removeAttribute('data-admin-bootstrap'); + setHidden(loginOpenBtn, false); + setHidden(signupOpenBtn, false); + const note = + (signupOverlay && + signupOverlay.querySelector('[data-auth-note], #authNote, .u-text-dim')) || + document.querySelector('[data-auth-note], #authNote, .u-text-dim'); + if (note) { + note.textContent = + 'No admin account exists yet. Sign up to create the first admin account.'; + } + } else { + const modalEl = signupOverlay ? signupOverlay.querySelector('[role="document"]') : null; + if (modalEl) modalEl.removeAttribute('data-admin-bootstrap'); + const note = + (loginOverlay && + loginOverlay.querySelector('[data-auth-note], #authNote, .u-text-dim')) || + document.querySelector('[data-auth-note], #authNote, .u-text-dim'); + if (note && !signupPanel) { + note.textContent = 'Sign up disabled for admin panel.'; + } + } + } + } catch { + /* ignore */ + } + } + })(); + + // Listen for dynamic component loading (when header is injected after initial page load) + document.addEventListener('nc:componentsLoaded', () => { + refreshButtonReferences(); + refreshOverlayReferences(); + attachButtonListeners(); + attachOverlayListeners(); + updateHeaderButton(); + }); +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-required-open.js b/shared/packages/media-shared-assets/public/js/auth/auth-required-open.js new file mode 100644 index 0000000..0a05f9d --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-required-open.js @@ -0,0 +1,15 @@ +(() => { + const openAuth = () => { + const mode = + document.body?.dataset?.authOpenMode || + document.querySelector('[data-auth-open-mode]')?.getAttribute('data-auth-open-mode') || + 'login'; + const button = document.getElementById( + mode === 'signup' ? 'authSignupOpenBtn' : 'authLoginOpenBtn' + ); + if (button) button.click(); + }; + + const forceButton = document.getElementById('forceAuthOpen'); + if (forceButton) forceButton.addEventListener('click', openAuth); +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-required.js b/shared/packages/media-shared-assets/public/js/auth/auth-required.js new file mode 100644 index 0000000..abb8f1c --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-required.js @@ -0,0 +1,63 @@ +/** + * NCAuthRequired — standardized "login required" screen. + * + * Usage: + * NCAuthRequired.render(containerEl); + * + * The rendered prompt includes a "Log In" button that opens the shared auth + * modal. On successful login (auth:login-success event) the page reloads + * automatically so the protected content can be fetched. + */ +window.NCAuthRequired = (() => { + function escapeHtml(s) { + const d = document.createElement('div'); + d.textContent = s; + return d.innerHTML; + } + + /** + * Render a login-required prompt inside `container`. + * @param {HTMLElement} container — element whose innerHTML will be replaced. + */ + function render(container) { + if (!container) return; + const message = 'You need to log in to view this page.'; + const icon = 'fas fa-lock'; + + // Reset container layout so the prompt always spans full width and centers. + container.classList.add('flex', 'justify-center'); + container.innerHTML = [ + '
', + ' ', + '

' + + escapeHtml(message) + + '

', + ' ', + '
', + ].join('\n'); + + // Wire the Log In button to open the shared auth modal + const btn = container.querySelector('[data-auth-required-login]'); + if (btn) { + btn.addEventListener('click', () => { + const opener = document.getElementById('authLoginOpenBtn'); + if (opener) opener.click(); + }); + } + + // Auto-reload on successful login so the page can fetch protected data + window.addEventListener( + 'auth:login-success', + () => { + window.location.reload(); + }, + { once: true } + ); + } + + return { render }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-reset-perform.js b/shared/packages/media-shared-assets/public/js/auth/auth-reset-perform.js new file mode 100644 index 0000000..b98c94a --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-reset-perform.js @@ -0,0 +1,24 @@ +(() => { + const tokenInput = document.getElementById('token'); + const passwordInput = document.getElementById('newPassword'); + if ( + !tokenInput || + !passwordInput || + !window.NCAuthForm || + typeof window.NCAuthForm.bindJsonSubmit !== 'function' + ) { + return; + } + + window.NCAuthForm.bindJsonSubmit({ + endpoint: '/auth/reset/perform', + formId: 'resetForm', + resultId: 'resetDone', + buildPayload() { + return { + token: tokenInput.value, + password: passwordInput.value, + }; + }, + }); +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/auth-reset-request.js b/shared/packages/media-shared-assets/public/js/auth/auth-reset-request.js new file mode 100644 index 0000000..e9c3705 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/auth-reset-request.js @@ -0,0 +1,15 @@ +(() => { + const emailInput = document.getElementById('resetEmail'); + if (!emailInput || !window.NCAuthForm || typeof window.NCAuthForm.bindJsonSubmit !== 'function') { + return; + } + + window.NCAuthForm.bindJsonSubmit({ + endpoint: '/auth/reset/request', + formId: 'resetReqForm', + resultId: 'resetResult', + buildPayload() { + return { email: emailInput.value }; + }, + }); +})(); diff --git a/shared/packages/media-shared-assets/public/js/auth/login-gate.js b/shared/packages/media-shared-assets/public/js/auth/login-gate.js new file mode 100644 index 0000000..62bf833 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/login-gate.js @@ -0,0 +1,21 @@ +/** + * login-gate.js + * Client-side initialiser for the server-side login gate page + * (served by requireLoginIfConfigured middleware in MediaShared). + * + * Sources: /shared/js/ui/toast.js, /shared/js/auth/auth-modal.js, + * /shared/js/auth/auth-required.js must be loaded before this script. + * + * On successful login the page is reloaded so the browser re-enters the + * protected service with a valid session. + */ +document.addEventListener('DOMContentLoaded', function () { + const gate = document.getElementById('auth-gate'); + if (gate && window.NCAuthRequired) { + window.NCAuthRequired.render(gate); + } + + document.addEventListener('auth:login-success', function () { + window.location.reload(); + }); +}); diff --git a/shared/packages/media-shared-assets/public/js/auth/profile-page.js b/shared/packages/media-shared-assets/public/js/auth/profile-page.js new file mode 100644 index 0000000..6c97fbf --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/auth/profile-page.js @@ -0,0 +1,485 @@ +const toast = globalThis.toast; +const profileEditState = { + editing: false, + snapshot: { username: '', email: '' }, +}; + +function byId(id) { + return document.getElementById(id); +} + +function setText(id, value) { + const element = byId(id); + if (element) element.textContent = value; +} + +function setValue(id, value) { + const element = byId(id); + if (element) element.value = value; +} + +function parseApiError(payload, fallback) { + return payload?.error || payload?.message || payload?.data?.error || fallback; +} + +function setButtonBusy(id, busy) { + const button = byId(id); + if (!button) return; + button.disabled = !!busy; +} + +function setMfaBadge(enabled) { + const badge = byId('mfaBadge'); + if (!badge) return; + if (enabled) { + badge.className = + 'inline-flex items-center rounded-full border border-emerald-500/40 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300'; + badge.textContent = 'MFA Enabled'; + return; + } + badge.className = + 'inline-flex items-center rounded-full border border-amber-500/40 bg-amber-500/10 px-3 py-1 text-xs font-semibold text-amber-300'; + badge.textContent = 'MFA Disabled'; +} + +function resetTotpWizard() { + const wizard = byId('totpWizard'); + if (wizard) wizard.hidden = true; + setValue('totpCode', ''); + const manualLabel = byId('totpManualLabel'); + if (manualLabel) manualLabel.hidden = true; + setText('totpManualKey', ''); +} + +function extractTotpSecret(otpauth) { + try { + const parsed = new URL(String(otpauth || '')); + return parsed.searchParams.get('secret') || ''; + } catch { + return ''; + } +} + +function normalizeTotpCode(raw) { + return String(raw || '') + .replace(/\D+/g, '') + .slice(0, 6); +} + +function showBackupCodes(codes) { + const panel = byId('backupCodesPanel'); + const list = byId('backupCodesList'); + if (!panel || !list || !Array.isArray(codes)) return; + list.innerHTML = ''; + codes.forEach(code => { + const li = document.createElement('li'); + li.textContent = code; + list.appendChild(li); + }); + panel.hidden = false; +} + +function hideBackupCodes() { + const panel = byId('backupCodesPanel'); + if (panel) panel.hidden = true; + const list = byId('backupCodesList'); + if (list) list.innerHTML = ''; +} + +function hideBackupCodesRegenerateForm() { + const form = byId('backupCodesRegenerateForm'); + if (form) form.hidden = true; +} + +async function loadBackupCodesStatus() { + const manage = byId('backupCodesManage'); + if (!manage) return; + try { + const response = await fetch('/api/security/totp/backup-codes/status'); + const payload = await response.json().catch(() => ({})); + if (!response.ok || !payload?.data?.mfaEnabled) { + manage.hidden = true; + return; + } + manage.hidden = false; + const remaining = Number(payload.data.remaining) || 0; + setText( + 'backupCodesRemaining', + `Backup codes: ${remaining} of 10 remaining.` + + (remaining <= 2 ? ' Consider regenerating soon.' : '') + ); + } catch { + manage.hidden = true; + } +} + +function normalizeProfileEntryValue(value) { + return String(value || '').trim(); +} + +function readProfileEntryInputs() { + return { + username: normalizeProfileEntryValue(byId('usernameInput')?.value), + email: normalizeProfileEntryValue(byId('emailInput')?.value), + }; +} + +function applyProfileEntryInputs({ username = '', email = '' } = {}) { + setValue('usernameInput', username); + setValue('emailInput', email); +} + +function profileEntryValuesEqual(a, b) { + return ( + normalizeProfileEntryValue(a?.username) === normalizeProfileEntryValue(b?.username) && + normalizeProfileEntryValue(a?.email) === normalizeProfileEntryValue(b?.email) + ); +} + +function setProfileEditMode(editing, { restore = false } = {}) { + const isEditing = Boolean(editing); + const form = byId('editProfileForm'); + if (form) form.hidden = !isEditing; + if (!isEditing && restore) { + applyProfileEntryInputs(profileEditState.snapshot); + } + const editButton = byId('editProfileButton'); + if (editButton) editButton.disabled = isEditing; + profileEditState.editing = isEditing; +} + +async function fetchUserProfile({ silent = false } = {}) { + if (!byId('profile-container')) return; + try { + const response = await fetch('/api/profile'); + const payload = await response.json().catch(() => ({})); + const user = payload?.data || payload?.profile || payload?.user || null; + if (!response.ok || !user) { + throw new Error(parseApiError(payload, 'Failed to load profile')); + } + + const entries = { + username: normalizeProfileEntryValue(user.username || 'Anonymous'), + email: normalizeProfileEntryValue(user.email || 'Not set'), + }; + + setText('username', entries.username); + setText('email', entries.email); + + const profilePicture = byId('profilePicture'); + if (profilePicture) { + profilePicture.src = + user.avatar_url || user.profilePicture || '/shared/images/default-avatar.svg'; + } + + if (!profileEditState.editing) { + applyProfileEntryInputs(entries); + profileEditState.snapshot = entries; + } + + const mfaEnabled = !!user.mfaEnabled; + setMfaBadge(mfaEnabled); + setText('mfaStatus', mfaEnabled ? 'TOTP is enabled on your account.' : 'TOTP is not enabled.'); + + const setup = byId('mfaSetup'); + const disable = byId('mfaDisable'); + if (setup) setup.hidden = mfaEnabled; + if (disable) disable.hidden = !mfaEnabled; + if (mfaEnabled) resetTotpWizard(); + if (mfaEnabled) { + await loadBackupCodesStatus(); + } else { + const manage = byId('backupCodesManage'); + if (manage) manage.hidden = true; + hideBackupCodesRegenerateForm(); + } + } catch (error) { + if (!silent) { + toast?.error?.(error?.message || 'Profile load error'); + } + } +} + +function openProfileEdit() { + if (profileEditState.editing) return; + profileEditState.snapshot = { + username: normalizeProfileEntryValue( + byId('usernameInput')?.value || byId('username')?.textContent || '' + ), + email: normalizeProfileEntryValue( + byId('emailInput')?.value || byId('email')?.textContent || '' + ), + }; + applyProfileEntryInputs(profileEditState.snapshot); + setProfileEditMode(true); + byId('usernameInput')?.focus(); +} + +function closeProfileEdit({ restore = true } = {}) { + setProfileEditMode(false, { restore }); +} + +async function saveProfileChanges() { + const draft = readProfileEntryInputs(); + if (profileEntryValuesEqual(draft, profileEditState.snapshot)) { + closeProfileEdit({ restore: false }); + return; + } + + setButtonBusy('profileSaveBtn', true); + setButtonBusy('profileCancelBtn', true); + try { + const response = await fetch('/api/profile', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(draft), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(parseApiError(payload, 'Save failed')); + } + profileEditState.snapshot = draft; + toast?.success?.('Profile updated'); + closeProfileEdit({ restore: false }); + await fetchUserProfile({ silent: true }); + } catch (error) { + toast?.error?.(error?.message || 'Save failed'); + } finally { + setButtonBusy('profileSaveBtn', false); + setButtonBusy('profileCancelBtn', false); + const editButton = byId('editProfileButton'); + if (editButton) editButton.disabled = profileEditState.editing; + } +} + +async function changePassword() { + const newPassword = byId('newPw')?.value || ''; + if (!newPassword) { + toast?.error?.('New password is required'); + return; + } + + setButtonBusy('btnChangePw', true); + try { + const response = await fetch('/api/profile/password', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ newPassword }), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(parseApiError(payload, 'Change failed')); + } + toast?.success?.('Password updated'); + setValue('newPw', ''); + } catch (error) { + toast?.error?.(error?.message || 'Change failed'); + } finally { + setButtonBusy('btnChangePw', false); + } +} + +async function startTotpSetup() { + setButtonBusy('btnStartTotp', true); + try { + const response = await fetch('/api/security/totp/initiate'); + const payload = await response.json().catch(() => ({})); + if (!response.ok || !(payload?.data?.qr || payload?.data?.otpauth)) { + throw new Error(parseApiError(payload, 'Failed to start TOTP')); + } + + const wizard = byId('totpWizard'); + const qrImage = byId('totpQr'); + if (wizard) wizard.hidden = false; + if (qrImage && payload?.data?.qr) qrImage.src = payload.data.qr; + + const secret = extractTotpSecret(payload?.data?.otpauth); + if (secret) { + setText('totpManualKey', secret); + const manualLabel = byId('totpManualLabel'); + if (manualLabel) manualLabel.hidden = false; + } + byId('totpCode')?.focus(); + } catch (error) { + toast?.error?.(error?.message || 'Failed to start TOTP'); + } finally { + setButtonBusy('btnStartTotp', false); + } +} + +async function verifyTotpSetup() { + const token = normalizeTotpCode(byId('totpCode')?.value || ''); + if (token.length !== 6) { + toast?.error?.('Enter a valid 6-digit TOTP code'); + return; + } + + setButtonBusy('btnVerifyTotp', true); + try { + const response = await fetch('/api/security/totp/verify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token }), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(parseApiError(payload, 'Invalid code')); + } + + toast?.success?.('MFA enabled'); + resetTotpWizard(); + if (Array.isArray(payload?.data?.backupCodes)) { + showBackupCodes(payload.data.backupCodes); + } + await fetchUserProfile({ silent: true }); + } catch (error) { + toast?.error?.(error?.message || 'Invalid code'); + } finally { + setButtonBusy('btnVerifyTotp', false); + } +} + +async function regenerateBackupCodes() { + setButtonBusy('btnConfirmRegenerateBackupCodes', true); + try { + const response = await fetch('/api/security/totp/backup-codes/regenerate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(parseApiError(payload, 'Failed to regenerate backup codes')); + } + + toast?.success?.('Backup codes regenerated'); + hideBackupCodesRegenerateForm(); + if (Array.isArray(payload?.data?.backupCodes)) { + showBackupCodes(payload.data.backupCodes); + } + await loadBackupCodesStatus(); + } catch (error) { + toast?.error?.(error?.message || 'Failed to regenerate backup codes'); + } finally { + setButtonBusy('btnConfirmRegenerateBackupCodes', false); + } +} + +async function disableTotp() { + const token = normalizeTotpCode(window.prompt('Enter the current 6-digit authenticator code to disable MFA:') || ''); + if (token.length !== 6) { + toast?.error?.('Enter a valid 6-digit TOTP code'); + return; + } + setButtonBusy('btnDisableTotp', true); + try { + const response = await fetch('/api/security/totp/disable', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token }), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(parseApiError(payload, 'Disable failed')); + } + + toast?.success?.('MFA disabled'); + await fetchUserProfile({ silent: true }); + } catch (error) { + toast?.error?.(error?.message || 'Disable failed'); + } finally { + setButtonBusy('btnDisableTotp', false); + } +} + +async function uploadAvatar() { + const file = byId('avatarFile')?.files?.[0]; + if (!file) { + toast?.error?.('Choose an image'); + return; + } + + setButtonBusy('btnUploadAvatar', true); + try { + const formData = new FormData(); + formData.append('avatar', file); + const response = await fetch('/api/profile/avatar', { method: 'POST', body: formData }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(parseApiError(payload, 'Upload failed')); + } + + toast?.success?.('Avatar updated'); + await fetchUserProfile({ silent: true }); + } catch (error) { + toast?.error?.(error?.message || 'Upload failed'); + } finally { + setButtonBusy('btnUploadAvatar', false); + } +} + +function wireProfileEvents() { + byId('editProfileButton')?.addEventListener('click', openProfileEdit); + byId('editProfileForm')?.addEventListener('submit', event => { + event.preventDefault(); + saveProfileChanges(); + }); + byId('profileCancelBtn')?.addEventListener('click', () => closeProfileEdit({ restore: true })); + byId('changePasswordForm')?.addEventListener('submit', event => { + event.preventDefault(); + changePassword(); + }); + byId('btnStartTotp')?.addEventListener('click', startTotpSetup); + byId('btnVerifyTotp')?.addEventListener('click', verifyTotpSetup); + byId('mfaDisableForm')?.addEventListener('submit', event => { + event.preventDefault(); + disableTotp(); + }); + byId('btnUploadAvatar')?.addEventListener('click', uploadAvatar); + + byId('btnDismissBackupCodes')?.addEventListener('click', hideBackupCodes); + byId('btnCopyBackupCodes')?.addEventListener('click', async () => { + const codes = Array.from(byId('backupCodesList')?.children || []).map(li => li.textContent); + if (!codes.length) return; + try { + await navigator.clipboard.writeText(codes.join('\n')); + toast?.success?.('Backup codes copied'); + } catch { + toast?.error?.('Could not copy — please copy manually'); + } + }); + byId('btnRegenerateBackupCodes')?.addEventListener('click', () => { + const form = byId('backupCodesRegenerateForm'); + if (form) form.hidden = false; + }); + byId('btnCancelRegenerateBackupCodes')?.addEventListener('click', hideBackupCodesRegenerateForm); + byId('backupCodesRegenerateForm')?.addEventListener('submit', event => { + event.preventDefault(); + regenerateBackupCodes(); + }); + + byId('totpCode')?.addEventListener('keydown', event => { + if (event.key === 'Enter') { + event.preventDefault(); + verifyTotpSetup(); + } + }); + + const profileImage = byId('profilePicture'); + if (profileImage) { + profileImage.addEventListener( + 'error', + () => { + const fallbackSrc = profileImage.getAttribute('data-fallback-src'); + if (fallbackSrc && profileImage.src !== fallbackSrc) profileImage.src = fallbackSrc; + }, + { once: true } + ); + } +} + +document.addEventListener('DOMContentLoaded', () => { + if (!byId('profile-container')) return; + wireProfileEvents(); + fetchUserProfile(); +}); diff --git a/shared/packages/media-shared-assets/public/js/layout/component-loader.js b/shared/packages/media-shared-assets/public/js/layout/component-loader.js new file mode 100644 index 0000000..85fedd5 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/layout/component-loader.js @@ -0,0 +1,920 @@ +/** + * @file component-loader.js + * @description Loads shared EJS components (header, navbar) dynamically into static HTML pages + * + * Usage: + * await NCComponentLoader.load({ + * siteTitle: 'MediaViewer', + * title: 'Home', + * headerCenterHTML: '
Custom header content
', + * navbarVariant: 'default', + * navbarItems: [{ label: 'Home', href: '/', icon: 'fas fa-home' }], + * navbarCurrentPath: window.location.pathname, + * }); + * + * headerCenterHTML is rendered directly in the browser (never sent to the server as + * a query param) and inserted into the header's `[data-header-center-slot]` element. + * It must be a hardcoded string the caller owns — never interpolate user-controlled + * data into it, since it's set via innerHTML with no escaping. + */ + +(function (window) { + 'use strict'; + + const TOPBAR_SELECTOR = 'header[data-topbar="1"]'; + + const NCComponentLoader = { + /** + * Load shared header and navbar components + * @param {Object} options - Configuration for header/navbar rendering + * @param {string} options.siteTitle - Site/app title (e.g., 'MediaViewer') + * @param {string} options.title - Page title (e.g., 'Home') + * @param {string} [options.headerCenterHTML] - Hardcoded HTML the caller owns, inserted + * client-side into the header's center slot. Never derive this from user input. + * @param {boolean} [options.disableSignup] - Hide signup button + * @param {boolean} [options.enableSocketIO] - Load Socket.IO script + * @param {string} [options.appCssHref] - Additional app-specific CSS href + * @param {string} [options.extraScripts] - Additional scripts to load in footer + * @param {string} [options.navbarVariant] - Navbar variant identifier (e.g. 'default', 'admin') + * @param {Array} [options.navbarItems] - Array of { label, href, icon } nav items + * @param {string} [options.navbarCurrentPath] - Current path for active-link highlighting + * @param {string} [options.authPageToken] - Explicit token for /auth/me page-level requirement lookup + * @param {string} [options.navbarActive] - Explicit active item href (fallback) + * @returns {Promise} + */ + async load(options = {}) { + const { + siteTitle = 'App', + title = '', + headerCenterHTML = '', + disableSignup = false, + enableSocketIO = false, + appCssHref = '', + // eslint-disable-next-line no-unused-vars + extraScripts: _extraScripts = '', + navbarVariant = '', + navbarItems = [], + navbarCurrentPath = '', + authPageToken = '', + // eslint-disable-next-line no-unused-vars + navbarActive: _navbarActive = '', + } = options; + + try { + const resolvedNavbarCurrentPath = navbarCurrentPath || window.location.pathname; + const resolvedTitle = this._resolveTitleForLoad({ + siteTitle, + title, + navbarItems, + navbarCurrentPath: resolvedNavbarCurrentPath, + }); + + this._navbarTitleContext = { + siteTitle, + navbarItems: Array.isArray(navbarItems) ? navbarItems : [], + }; + this._bindNavbarTitleSync(); + this._setDocumentTitle(siteTitle, resolvedTitle); + + const resolvedAuthPageToken = this._resolveAuthPageToken( + authPageToken, + resolvedNavbarCurrentPath + ); + + const authState = await this._getAuthState(resolvedAuthPageToken); + window.__NC_AUTH_STATE = authState; + window.__NC_ACTIVE_PAGE_TOKEN = + authState.pageToken || this._normalizePageToken(resolvedAuthPageToken); + this._bindProtectedNavGuard(); + const hideHeaderForAuth = this._isAuthRequiredWithoutUser(authState); + const hasNavbarConfig = + !!navbarVariant && Array.isArray(navbarItems) && navbarItems.length > 1; + const isDesktopViewport = this._isDesktopViewport(); + const renderDesktopNavbar = hasNavbarConfig && isDesktopViewport && !hideHeaderForAuth; + + // Build query string for header endpoint + const headerParams = new URLSearchParams({ + siteTitle, + title: resolvedTitle, + disableSignup: disableSignup.toString(), + enableSocketIO: enableSocketIO.toString(), + appCssHref, + navbarVariant, + navbarItems: JSON.stringify(hasNavbarConfig ? navbarItems : []), + navbarCurrentPath: resolvedNavbarCurrentPath, + renderDesktopNavbar: renderDesktopNavbar.toString(), + }); + + // Fetch header + const headerResponse = await fetch(`/api/components/header?${headerParams}`); + if (!headerResponse.ok) { + throw new Error(`Failed to load header: ${headerResponse.status}`); + } + const headerHTML = await headerResponse.text(); + + // Inject header into placeholder + const headerPlaceholder = document.getElementById('header-placeholder'); + if (headerPlaceholder) { + headerPlaceholder.innerHTML = headerHTML; + } else { + console.warn( + '[ComponentLoader] #header-placeholder not found; prepending header to body' + ); + document.body.insertAdjacentHTML('afterbegin', headerHTML); + } + + if (headerCenterHTML) { + const centerSlot = document.querySelector('[data-header-center-slot]'); + if (centerSlot) centerSlot.innerHTML = headerCenterHTML; + } + + if (hideHeaderForAuth) { + this._hideHeaderForAuthState(); + } + + // Re-initialize scripts that depend on dynamically loaded elements + // (auth-modal.js, theme-toggle.js, etc. should auto-initialize on DOMContentLoaded) + + // Fetch and inject mobile navbar markup whenever nav config exists. + // CSS media queries handle visibility per viewport. + if (hasNavbarConfig) { + try { + const shouldRenderMobileNavbar = !hideHeaderForAuth; + if (!shouldRenderMobileNavbar) { + const existingNav = document.querySelector('nav[data-mobile-nav="1"]'); + if (existingNav) existingNav.remove(); + const navbarPlaceholder = document.getElementById('navbar-placeholder'); + if (navbarPlaceholder) navbarPlaceholder.innerHTML = ''; + } else { + const navbarParams = new URLSearchParams({ + navbarVariant, + navbarItems: JSON.stringify(navbarItems), + navbarCurrentPath: resolvedNavbarCurrentPath, + }); + const navbarResponse = await fetch(`/api/components/navbar?${navbarParams}`); + if (navbarResponse.ok) { + const navbarHTML = await navbarResponse.text(); + const existingNav = document.querySelector('nav[data-mobile-nav="1"]'); + if (existingNav) { + existingNav.remove(); + } + const navbarPlaceholder = document.getElementById('navbar-placeholder'); + const headerPlaceholder = document.getElementById('header-placeholder'); + if (navbarPlaceholder) { + navbarPlaceholder.outerHTML = navbarHTML; + } else if (headerPlaceholder) { + headerPlaceholder.insertAdjacentHTML('beforeend', navbarHTML); + } else { + const topbar = document.querySelector('header[data-topbar="1"]'); + if (topbar) { + topbar.insertAdjacentHTML('afterend', navbarHTML); + } else { + document.body.insertAdjacentHTML('beforeend', navbarHTML); + } + } + } + } + } catch (navErr) { + console.warn('[ComponentLoader] Failed to load navbar:', navErr); + } + } else { + const existingNav = document.querySelector('nav[data-mobile-nav="1"]'); + if (existingNav) existingNav.remove(); + const navbarPlaceholder = document.getElementById('navbar-placeholder'); + if (navbarPlaceholder) navbarPlaceholder.innerHTML = ''; + } + + this._syncTopbarMetrics(); + this._syncBottomNavMetrics(); + this._syncScrollShell(); + this._applyAutoTopbarGap(); + this._bindScrollShellObserver(); + + this._triggerScriptInitialization(); + } catch (error) { + console.error('[ComponentLoader] Failed to load components:', error); + // Fallback: show a basic error message + document.body.insertAdjacentHTML( + 'afterbegin', + ` +
+ Failed to load page components. Please refresh the page. +
+ ` + ); + } + }, + + /** + * Trigger re-initialization of scripts that need dynamically loaded DOM elements + * @private + */ + _triggerScriptInitialization() { + // Dispatch custom event for scripts that need to re-initialize + const event = new CustomEvent('nc:componentsLoaded', { + bubbles: true, + cancelable: false, + }); + document.dispatchEvent(event); + }, + + /** + * Keep topbar-related CSS variables in sync with rendered header height. + * This avoids overlap when the fixed header height changes due to responsive content. + * @private + */ + _syncTopbarMetrics() { + const topbar = document.querySelector(TOPBAR_SELECTOR); + if (topbar) { + const height = Math.ceil(topbar.getBoundingClientRect().height || 0); + if (height) { + const px = `${height}px`; + document.documentElement.style.setProperty('--bar-height', px); + document.documentElement.style.setProperty('--topbar-height', px); + } + } + + if (!this._resizeSyncBound) { + this._resizeSyncBound = true; + window.addEventListener('resize', () => { + if (this._resizeRaf) { + window.cancelAnimationFrame(this._resizeRaf); + } + this._resizeRaf = window.requestAnimationFrame(() => { + this._syncTopbarMetrics(); + this._syncBottomNavMetrics(); + this._syncScrollShell(); + this._applyAutoTopbarGap(); + }); + }); + } + }, + + /** + * Resolve the currently visible fixed mobile navigation bar. + * @returns {HTMLElement | null} + * @private + */ + _getVisibleMobileNav() { + const nav = document.querySelector('nav[data-bottom-nav][data-mobile-nav="1"]'); + if (!nav || nav.hidden || nav.classList.contains('hidden')) return null; + + const style = window.getComputedStyle(nav); + if (style.display === 'none' || style.visibility === 'hidden') return null; + if (style.position !== 'fixed') return null; + + return nav; + }, + + /** + * Keep bottom-nav height variable in sync with the currently visible fixed mobile nav. + * @private + */ + _syncBottomNavMetrics() { + const mobileNav = this._getVisibleMobileNav(); + const navHeight = mobileNav ? Math.ceil(mobileNav.getBoundingClientRect().height || 0) : 0; + document.documentElement.style.setProperty( + '--bottom-nav-height', + `${Math.max(0, navHeight)}px` + ); + }, + + /** + * Determine whether a candidate scroll host is currently visible. + * @param {HTMLElement | null} element + * @returns {boolean} + * @private + */ + _isElementScrollHostVisible(element) { + if (!element) return false; + + let node = element; + while (node && node.nodeType === 1) { + if (node.hidden || node.classList.contains('hidden')) return false; + if (String(node.getAttribute('aria-hidden') || '').toLowerCase() === 'true') return false; + + const style = window.getComputedStyle(node); + if (style.display === 'none' || style.visibility === 'hidden') return false; + + node = node.parentElement; + } + + return true; + }, + + /** + * Pick the primary page content scroll host. + * @returns {HTMLElement | null} + * @private + */ + _resolveScrollHost() { + const selectors = [ + 'main.fixed.left-0.right-0.overflow-y-auto', + 'body > main', + 'body > #main-content', + 'body > .page-panel > main', + 'body > .page-panel > #main-content', + ]; + + for (const selector of selectors) { + const candidates = Array.from(document.querySelectorAll(selector)); + const visibleCandidate = candidates.find(candidate => + this._isElementScrollHostVisible(candidate) + ); + if (visibleCandidate) return visibleCandidate; + } + + for (const selector of selectors) { + const fallbackCandidate = document.querySelector(selector); + if (fallbackCandidate) return fallbackCandidate; + } + + return null; + }, + + /** + * Parse a CSS length-like value into pixels with a safe fallback. + * @param {string} value + * @param {number} fallback + * @returns {number} + * @private + */ + _parsePixelValue(value, fallback = 0) { + const parsed = Number.parseFloat(String(value || '').trim()); + return Number.isFinite(parsed) ? parsed : fallback; + }, + + /** + * Keep non-fixed scroll hosts constrained to the viewport so they can scroll internally. + * @param {HTMLElement | null} scrollHost + * @private + */ + _syncScrollHostHeight(scrollHost) { + if (!scrollHost || scrollHost.classList.contains('fixed')) return; + + const rootStyle = window.getComputedStyle(document.documentElement); + const topbarHeight = this._parsePixelValue(rootStyle.getPropertyValue('--topbar-height'), 56); + const bottomNavHeight = this._parsePixelValue( + rootStyle.getPropertyValue('--bottom-nav-height'), + 0 + ); + const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0; + const boundedHeight = Math.max( + 0, + Math.round(viewportHeight - topbarHeight - bottomNavHeight) + ); + + if (boundedHeight > 0) { + scrollHost.style.height = `${boundedHeight}px`; + scrollHost.dataset.ncScrollHostHeightManaged = '1'; + } + }, + + /** + * Keep non-fixed scroll host scrollbar at the viewport edge while preserving centered content gutters. + * @param {HTMLElement | null} scrollHost + * @private + */ + _syncScrollHostInlineGutters(scrollHost) { + if (!scrollHost || scrollHost.classList.contains('fixed')) { + this._clearManagedScrollHostInlineGutters(scrollHost); + return; + } + + if (scrollHost.dataset.ncScrollHostInlineGutterManaged === '1') { + this._clearManagedScrollHostInlineGutters(scrollHost); + } + + const style = window.getComputedStyle(scrollHost); + const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0; + const hostMaxWidth = this._parsePixelValue(style.maxWidth, 0); + const hostRectWidth = Math.round(scrollHost.getBoundingClientRect().width || 0); + const constrainedWidth = hostMaxWidth > 0 ? hostMaxWidth : hostRectWidth; + + // Only widen hosts that are intentionally constrained and centered. + if (!(constrainedWidth > 0 && viewportWidth - constrainedWidth > 1)) return; + + const basePaddingLeft = this._parsePixelValue(style.paddingLeft, 0); + const basePaddingRight = this._parsePixelValue(style.paddingRight, 0); + const sideGutter = Math.max(0, Math.round((viewportWidth - constrainedWidth) / 2)); + + scrollHost.dataset.ncPrevInlineMaxWidth = scrollHost.style.maxWidth || ''; + scrollHost.dataset.ncPrevInlineMarginLeft = scrollHost.style.marginLeft || ''; + scrollHost.dataset.ncPrevInlineMarginRight = scrollHost.style.marginRight || ''; + scrollHost.dataset.ncPrevInlineWidth = scrollHost.style.width || ''; + scrollHost.dataset.ncPrevInlinePaddingLeft = scrollHost.style.paddingLeft || ''; + scrollHost.dataset.ncPrevInlinePaddingRight = scrollHost.style.paddingRight || ''; + + // Width:auto ensures left/right fixed offsets remain authoritative on the scroll host. + scrollHost.style.width = 'auto'; + scrollHost.style.maxWidth = 'none'; + scrollHost.style.marginLeft = '0'; + scrollHost.style.marginRight = '0'; + scrollHost.style.paddingLeft = `${basePaddingLeft + sideGutter}px`; + scrollHost.style.paddingRight = `${basePaddingRight + sideGutter}px`; + scrollHost.dataset.ncScrollHostInlineGutterManaged = '1'; + }, + + /** + * Remove inline gutter overrides used to keep the scrollbar at viewport edge. + * @param {HTMLElement | null} scrollHost + * @private + */ + _clearManagedScrollHostInlineGutters(scrollHost) { + if (!scrollHost || scrollHost.dataset.ncScrollHostInlineGutterManaged !== '1') return; + + scrollHost.style.maxWidth = scrollHost.dataset.ncPrevInlineMaxWidth || ''; + scrollHost.style.marginLeft = scrollHost.dataset.ncPrevInlineMarginLeft || ''; + scrollHost.style.marginRight = scrollHost.dataset.ncPrevInlineMarginRight || ''; + scrollHost.style.width = scrollHost.dataset.ncPrevInlineWidth || ''; + scrollHost.style.paddingLeft = scrollHost.dataset.ncPrevInlinePaddingLeft || ''; + scrollHost.style.paddingRight = scrollHost.dataset.ncPrevInlinePaddingRight || ''; + + delete scrollHost.dataset.ncPrevInlineMaxWidth; + delete scrollHost.dataset.ncPrevInlineMarginLeft; + delete scrollHost.dataset.ncPrevInlineMarginRight; + delete scrollHost.dataset.ncPrevInlineWidth; + delete scrollHost.dataset.ncPrevInlinePaddingLeft; + delete scrollHost.dataset.ncPrevInlinePaddingRight; + delete scrollHost.dataset.ncScrollHostInlineGutterManaged; + }, + + /** + * Remove previously managed scroll-host height overrides. + * @param {HTMLElement | null} scrollHost + * @private + */ + _clearManagedScrollHostHeight(scrollHost) { + if (!scrollHost || scrollHost.dataset.ncScrollHostHeightManaged !== '1') return; + scrollHost.style.removeProperty('height'); + delete scrollHost.dataset.ncScrollHostHeightManaged; + }, + + /** + * Ensure page scrolling happens inside content instead of the document body. + * @private + */ + _syncScrollShell() { + if (!document.body) return; + + const scrollHost = this._resolveScrollHost(); + const root = document.documentElement; + + if (this._scrollHost && this._scrollHost !== scrollHost) { + this._clearManagedScrollHostHeight(this._scrollHost); + this._clearManagedScrollHostInlineGutters(this._scrollHost); + this._scrollHost.classList.remove('nc-scroll-host'); + } + + this._scrollHost = scrollHost || null; + + if (!scrollHost) { + document.body.classList.remove('nc-content-scroll-shell'); + root.classList.remove('nc-content-scroll-shell-root'); + return; + } + + document.body.classList.add('nc-content-scroll-shell'); + root.classList.add('nc-content-scroll-shell-root'); + + if (scrollHost.classList.contains('fixed')) { + this._clearManagedScrollHostHeight(scrollHost); + this._clearManagedScrollHostInlineGutters(scrollHost); + scrollHost.classList.remove('nc-scroll-host'); + } else { + scrollHost.classList.add('nc-scroll-host'); + this._syncScrollHostHeight(scrollHost); + this._syncScrollHostInlineGutters(scrollHost); + } + }, + + /** + * Schedule a single-frame sync for topbar/nav metrics and scroll shell classes. + * @private + */ + _scheduleScrollShellSync() { + if (this._scrollShellRaf) { + window.cancelAnimationFrame(this._scrollShellRaf); + } + + this._scrollShellRaf = window.requestAnimationFrame(() => { + this._scrollShellRaf = null; + this._syncTopbarMetrics(); + this._syncBottomNavMetrics(); + this._syncScrollShell(); + this._applyAutoTopbarGap(); + }); + }, + + /** + * Determine whether a mutation can affect scroll-shell host selection or offsets. + * @param {MutationRecord[]} mutationList + * @returns {boolean} + * @private + */ + _shouldResyncScrollShellForMutation(mutationList) { + const relevantSelector = + 'main, #main-content, .page-panel, nav[data-bottom-nav], header[data-topbar="1"], body'; + + const isElementNode = node => node && node.nodeType === 1; + const hasRelevantNode = node => { + if (!isElementNode(node)) return false; + if (node.matches(relevantSelector)) return true; + return !!node.querySelector(relevantSelector); + }; + + for (const mutation of mutationList) { + if (mutation.type === 'attributes') { + if (isElementNode(mutation.target) && mutation.target.matches(relevantSelector)) { + return true; + } + continue; + } + + if (mutation.type === 'childList') { + const target = mutation.target; + if ( + !isElementNode(target) || + !target.matches('body, .page-panel, #header-placeholder, #navbar-placeholder') + ) { + continue; + } + + for (const node of mutation.addedNodes) { + if (hasRelevantNode(node)) return true; + } + + for (const node of mutation.removedNodes) { + if (hasRelevantNode(node)) return true; + } + } + } + + return false; + }, + + /** + * Keep the scroll shell in sync when panel visibility or fixed chrome changes at runtime. + * @private + */ + _bindScrollShellObserver() { + if (this._scrollShellObserverBound || !document.body || !window.MutationObserver) return; + this._scrollShellObserverBound = true; + + this._scrollShellObserver = new MutationObserver(mutationList => { + if (!this._shouldResyncScrollShellForMutation(mutationList)) return; + this._scheduleScrollShellSync(); + }); + + this._scrollShellObserver.observe(document.body, { + subtree: true, + childList: true, + attributes: true, + attributeFilter: ['class', 'hidden', 'style', 'aria-hidden'], + }); + + if (!this._scrollShellHistoryBound) { + this._scrollShellHistoryBound = true; + window.addEventListener('hashchange', () => this._scheduleScrollShellSync()); + window.addEventListener('popstate', () => this._scheduleScrollShellSync()); + } + }, + + /** + * Detect whether page content already has a topbar offset. + * @returns {boolean} + * @private + */ + _hasExplicitTopbarOffset() { + const classBasedOffset = document.querySelector( + '.pt-topbar-gap, [class*="pt-[var(--topbar-height"], [class*="pt-[calc(var(--topbar-height"]' + ); + if (classBasedOffset) return true; + + const inlineOffset = document.querySelector( + '[style*="padding-top"][style*="--topbar-height"], [style*="top: calc(var(--topbar-height"], [style*="top: var(--topbar-height"]' + ); + return !!inlineOffset; + }, + + /** + * Apply a safe fallback top gap only when a fixed topbar is present and no explicit gap exists. + * @private + */ + _applyAutoTopbarGap() { + const topbar = document.querySelector(TOPBAR_SELECTOR); + const topbarHidden = + !topbar || topbar.hidden || topbar.classList.contains('hidden') || !topbar.offsetParent; + if (topbarHidden || !document.body) { + if (document.body) document.body.classList.remove('nc-auto-topbar-gap'); + return; + } + if (document.body.classList.contains('nc-content-scroll-shell')) { + document.body.classList.remove('nc-auto-topbar-gap'); + return; + } + if (this._hasExplicitTopbarOffset()) { + document.body.classList.remove('nc-auto-topbar-gap'); + return; + } + document.body.classList.add('nc-auto-topbar-gap'); + }, + + /** + * Determine whether current viewport is desktop width. + * @returns {boolean} + * @private + */ + _isDesktopViewport() { + try { + return !!window.matchMedia && window.matchMedia('(min-width: 768px)').matches; + } catch { + return false; + } + }, + + /** + * Normalize a page token (path+query or hash token) for reliable key lookups. + * @param {string} value + * @returns {string} + * @private + */ + _normalizePageToken(value) { + const raw = String(value || '').trim(); + if (!raw) return '/'; + if (raw.startsWith('#')) return raw.toLowerCase(); + try { + const parsed = new URL(raw, window.location.origin); + const pathname = String(parsed.pathname || '/').toLowerCase(); + const search = parsed.searchParams.toString().toLowerCase(); + const hash = String(parsed.hash || '').toLowerCase(); + if (hash && (pathname === '/' || pathname === '') && !search) return hash; + return search ? `${pathname}?${search}` : pathname; + } catch { + return raw.toLowerCase(); + } + }, + + /** + * Compose a canonical browser title in "Project - Tab" form. + * @param {string} siteTitle + * @param {string} tabTitle + * @returns {string} + * @private + */ + _composeDocumentTitle(siteTitle, tabTitle = '') { + const normalizedSiteTitle = String(siteTitle || '').trim() || 'App'; + const normalizedTabTitle = String(tabTitle || '').trim(); + return normalizedTabTitle + ? `${normalizedSiteTitle} - ${normalizedTabTitle}` + : normalizedSiteTitle; + }, + + /** + * Update the active browser tab title. + * @param {string} siteTitle + * @param {string} tabTitle + * @private + */ + _setDocumentTitle(siteTitle, tabTitle = '') { + document.title = this._composeDocumentTitle(siteTitle, tabTitle); + }, + + /** + * Resolve navbar label by href/path token. + * @param {Array} navbarItems + * @param {string} hrefValue + * @returns {string} + * @private + */ + _resolveNavbarLabel(navbarItems, hrefValue) { + if (!Array.isArray(navbarItems) || navbarItems.length === 0) return ''; + + const normalizedTarget = this._normalizePageToken(hrefValue); + for (const item of navbarItems) { + const normalizedItem = this._normalizePageToken(item && item.href ? item.href : ''); + if (normalizedItem !== normalizedTarget) continue; + const label = String(item && item.label ? item.label : '').trim(); + if (label) return label; + } + + return ''; + }, + + /** + * Determine the title to render for initial component load. + * @param {{siteTitle: string, title: string, navbarItems: Array, navbarCurrentPath: string}} input + * @returns {string} + * @private + */ + _resolveTitleForLoad(input = {}) { + const explicitTitle = String(input.title || '').trim(); + if (explicitTitle) return explicitTitle; + + const navbarItems = Array.isArray(input.navbarItems) ? input.navbarItems : []; + const fromCurrentPath = this._resolveNavbarLabel(navbarItems, input.navbarCurrentPath || ''); + if (fromCurrentPath) return fromCurrentPath; + + const fromLocation = this._resolveNavbarLabel( + navbarItems, + `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}` + ); + if (fromLocation) return fromLocation; + + const firstLabel = String( + navbarItems[0] && navbarItems[0].label ? navbarItems[0].label : '' + ).trim(); + return firstLabel || ''; + }, + + /** + * Keep browser title in sync with bottom-nav tab clicks. + * @private + */ + _bindNavbarTitleSync() { + if (this._navbarTitleSyncBound) return; + this._navbarTitleSyncBound = true; + + document.addEventListener( + 'click', + event => { + const link = event.target.closest('nav[data-bottom-nav] a[href]'); + if (!link) return; + + const context = this._navbarTitleContext || {}; + const contextSiteTitle = String(context.siteTitle || '').trim(); + const contextNavbarItems = Array.isArray(context.navbarItems) ? context.navbarItems : []; + if (!contextSiteTitle || contextNavbarItems.length === 0) return; + + const href = link.getAttribute('href') || link.href || ''; + const tabTitle = + this._resolveNavbarLabel(contextNavbarItems, href) || + String(link.textContent || '').trim(); + if (!tabTitle) return; + + this._setDocumentTitle(contextSiteTitle, tabTitle); + }, + true + ); + }, + + /** + * Resolve which page token should be used when probing /auth/me. + * @param {string} authPageToken + * @param {string} navbarCurrentPath + * @returns {string} + * @private + */ + _resolveAuthPageToken(authPageToken, navbarCurrentPath) { + const explicitToken = String(authPageToken || '').trim(); + if (explicitToken) return this._normalizePageToken(explicitToken); + + const navbarToken = String(navbarCurrentPath || '').trim(); + if (navbarToken) return this._normalizePageToken(navbarToken); + + const locationToken = `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`; + return this._normalizePageToken(locationToken); + }, + + /** + * Determine whether the given page token is protected for current auth state. + * @param {string} pageToken + * @param {{loginRequiredPages?: object, loginRequiredAllPages?: boolean}} [authState] + * @returns {boolean} + * @private + */ + _isPageLoginRequired(pageToken, authState = window.__NC_AUTH_STATE || {}) { + const requiredAllPages = authState.loginRequiredAllPages === true; + const requiredPages = + authState.loginRequiredPages && typeof authState.loginRequiredPages === 'object' + ? authState.loginRequiredPages + : {}; + + const normalizedToken = this._normalizePageToken(pageToken); + return requiredAllPages || requiredPages[normalizedToken] === true; + }, + + /** + * Attach a capturing nav click guard so protected tabs cannot be entered when logged out. + * @private + */ + _bindProtectedNavGuard() { + if (this._protectedNavGuardBound) return; + this._protectedNavGuardBound = true; + + window.addEventListener('auth:login-success', () => { + const state = window.__NC_AUTH_STATE || {}; + window.__NC_AUTH_STATE = { + ...state, + user: state.user || { id: 'session' }, + }; + }); + + document.addEventListener( + 'click', + event => { + const link = event.target.closest('nav[data-bottom-nav] a[href]'); + if (!link) return; + + const href = link.getAttribute('href') || link.href || ''; + const pageToken = this._normalizePageToken(href); + window.__NC_ACTIVE_PAGE_TOKEN = pageToken; + + const authState = window.__NC_AUTH_STATE || {}; + if (authState.user) return; + + const isProtected = this._isPageLoginRequired(pageToken, authState); + if (!isProtected) return; + + event.preventDefault(); + event.stopImmediatePropagation(); + + const loginButton = document.getElementById('authLoginOpenBtn'); + if (loginButton) { + loginButton.click(); + } + if (window.toast && typeof window.toast.info === 'function') { + window.toast.info('Log in is required for this page.'); + } + }, + true + ); + }, + + /** + * Fetch current auth state. Fail-open to avoid blocking page chrome on probe errors. + * @param {string} pageToken + * @returns {Promise<{authRequired: boolean, user: object | null}>} + * @private + */ + async _getAuthState(pageToken) { + const fallbackPage = `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`; + const currentPage = this._normalizePageToken(pageToken || fallbackPage); + + try { + const res = await fetch(`/auth/me?page=${encodeURIComponent(currentPage)}`, { + credentials: 'same-origin', + headers: { Accept: 'application/json' }, + }); + if (!res.ok) { + return { + authRequired: false, + user: null, + loginRequiredPages: {}, + loginRequiredAllPages: false, + pageToken: currentPage, + }; + } + const auth = await res.json(); + const pages = + auth && auth.loginRequiredPages && typeof auth.loginRequiredPages === 'object' + ? auth.loginRequiredPages + : {}; + return { + authRequired: !!(auth && auth.authRequired === true), + user: (auth && auth.user) || null, + loginRequiredPages: pages, + loginRequiredAllPages: !!(auth && auth.loginRequiredAllPages === true), + pageToken: currentPage, + }; + } catch { + return { + authRequired: false, + user: null, + loginRequiredPages: {}, + loginRequiredAllPages: false, + pageToken: currentPage, + }; + } + }, + + /** + * Whether auth gate is enabled and there is no active session. + * @param {{authRequired: boolean, user: object | null}} authState + * @returns {boolean} + * @private + */ + _isAuthRequiredWithoutUser(authState) { + return !!(authState && authState.authRequired === true && !authState.user); + }, + + /** + * Hide visible topbar chrome while keeping auth modal DOM available. + * @private + */ + _hideHeaderForAuthState() { + const topbar = document.querySelector(TOPBAR_SELECTOR); + if (topbar) { + topbar.classList.add('hidden'); + topbar.setAttribute('aria-hidden', 'true'); + } + document.documentElement.style.setProperty('--bar-height', '0px'); + document.documentElement.style.setProperty('--topbar-height', '0px'); + document.documentElement.style.setProperty('--bottom-nav-height', '0px'); + if (document.body) document.body.classList.remove('nc-auto-topbar-gap'); + }, + }; + + // Export to global namespace + window.NCComponentLoader = NCComponentLoader; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/layout/expandable-container.js b/shared/packages/media-shared-assets/public/js/layout/expandable-container.js new file mode 100644 index 0000000..c15c9d8 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/layout/expandable-container.js @@ -0,0 +1,204 @@ +// NCExpandableContainer +// Shared helper for expandable/collapsible containers with optional persistence. +// +// Usage: +// const controller = window.NCExpandableContainer.bind({ +// toggleEl: 'filtersToggle', +// contentEl: 'filtersBody', +// chevronEl: 'filtersChevron', +// storageKey: 'app:filters-open', +// storageFormat: 'flag', // 'json' | 'flag' +// defaultExpanded: false, +// initFromAria: true, +// chevronMode: 'class', // 'class' | 'style' +// chevronRotateClass: 'rotate-180', +// syncHiddenAttribute: true, +// onChange: expanded => { ... }, +// }); + +(function (global) { + 'use strict'; + + var controllerByToggle = new WeakMap(); + + function toElement(target) { + if (!target) return null; + if (target instanceof Element) return target; + + var value = String(target || '').trim(); + if (!value) return null; + + if (value.charAt(0) === '#') { + try { + return document.querySelector(value); + } catch { + return null; + } + } + + var byId = document.getElementById(value); + if (byId) return byId; + + try { + return document.querySelector(value); + } catch { + return null; + } + } + + function readStorageBoolean(storageKey, storageFormat) { + if (!storageKey) return null; + try { + var raw = localStorage.getItem(storageKey); + if (raw == null) return null; + if (storageFormat === 'flag') return raw === '1'; + return !!JSON.parse(raw); + } catch { + return null; + } + } + + function writeStorageBoolean(storageKey, value, storageFormat) { + if (!storageKey) return; + try { + if (storageFormat === 'flag') localStorage.setItem(storageKey, value ? '1' : '0'); + else localStorage.setItem(storageKey, JSON.stringify(!!value)); + } catch { + // Ignore storage failures. + } + } + + function applyChevronState(chevronEl, expanded, chevronMode, chevronRotateClass) { + if (!chevronEl) return; + if (chevronMode === 'style') { + chevronEl.style.transform = expanded ? 'rotate(180deg)' : ''; + return; + } + chevronEl.classList.toggle(chevronRotateClass, !!expanded); + } + + function bind(options) { + var config = options || {}; + var toggleEl = toElement(config.toggleEl || config.toggle || config.toggleId); + var contentEl = toElement(config.contentEl || config.content || config.contentId); + if (!toggleEl || !contentEl) return null; + + if (config.allowRebind !== true && controllerByToggle.has(toggleEl)) { + return controllerByToggle.get(toggleEl); + } + + var chevronEl = toElement(config.chevronEl || config.chevron || config.chevronId); + var hiddenClass = String(config.hiddenClass || 'hidden'); + var eventName = String(config.eventName || 'click'); + var storageKey = config.storageKey ? String(config.storageKey) : ''; + var storageFormat = config.storageFormat === 'flag' ? 'flag' : 'json'; + var defaultExpanded = config.defaultExpanded === true; + var initFromAria = config.initFromAria !== false; + var updateAria = config.updateAria !== false; + var syncHiddenAttribute = config.syncHiddenAttribute === true; + var persistState = config.persistState !== false; + var emitInitial = config.emitInitial !== false; + var chevronMode = config.chevronMode === 'style' ? 'style' : 'class'; + var chevronRotateClass = String(config.chevronRotateClass || 'rotate-180'); + var onChange = typeof config.onChange === 'function' ? config.onChange : null; + var onBeforeToggle = + typeof config.onBeforeToggle === 'function' ? config.onBeforeToggle : null; + + var expanded = defaultExpanded; + + var stored = readStorageBoolean(storageKey, storageFormat); + if (typeof stored === 'boolean') { + expanded = stored; + } else if (initFromAria && toggleEl.hasAttribute('aria-expanded')) { + expanded = toggleEl.getAttribute('aria-expanded') === 'true'; + } + + function applyExpanded(nextExpanded, opts) { + var applyOptions = opts || {}; + var persist = applyOptions.persist !== false; + var emit = applyOptions.emit !== false; + + expanded = !!nextExpanded; + + contentEl.classList.toggle(hiddenClass, !expanded); + + if (syncHiddenAttribute) { + contentEl.hidden = !expanded; + } + + if (updateAria) { + toggleEl.setAttribute('aria-expanded', String(expanded)); + } + + applyChevronState(chevronEl, expanded, chevronMode, chevronRotateClass); + + if (persist && persistState && storageKey) { + writeStorageBoolean(storageKey, expanded, storageFormat); + } + + if (emit && onChange) { + onChange(expanded, { + toggleEl: toggleEl, + contentEl: contentEl, + chevronEl: chevronEl, + controller: controller, + }); + } + } + + function handleToggle(event) { + if (onBeforeToggle) { + try { + if (onBeforeToggle(event, expanded) === false) return; + } catch { + // Ignore before-toggle hook errors. + } + } + applyExpanded(!expanded); + } + + toggleEl.addEventListener(eventName, handleToggle); + + var controller = { + elements: { + toggleEl: toggleEl, + contentEl: contentEl, + chevronEl: chevronEl, + }, + isExpanded: function () { + return expanded; + }, + setExpanded: function (nextExpanded, opts) { + applyExpanded(nextExpanded, opts); + }, + toggle: function (opts) { + applyExpanded(!expanded, opts); + }, + destroy: function () { + toggleEl.removeEventListener(eventName, handleToggle); + controllerByToggle.delete(toggleEl); + }, + }; + + controllerByToggle.set(toggleEl, controller); + + applyExpanded(expanded, { persist: false, emit: emitInitial }); + + return controller; + } + + function bindMany(configs) { + if (!Array.isArray(configs)) return []; + return configs.map(function (config) { + return bind(config); + }); + } + + global.NCExpandableContainer = { + bind: bind, + bindMany: bindMany, + readStorageBoolean: readStorageBoolean, + writeStorageBoolean: writeStorageBoolean, + applyChevronState: applyChevronState, + }; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/layout/header-controls.js b/shared/packages/media-shared-assets/public/js/layout/header-controls.js new file mode 100644 index 0000000..2aa095b --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/layout/header-controls.js @@ -0,0 +1,266 @@ +(() => { + if (window.NCHeaderControls) return; + + const state = { + level: 'checking', + health: null, + readiness: null, + service: '', + checkedAt: null, + loading: false, + }; + const boundButtons = new WeakSet(); + let statusRequest = null; + let statusTimer = null; + let activeDialog = null; + let activeOpener = null; + + const levelLabels = { + checking: 'Checking', + healthy: 'Healthy', + degraded: 'Degraded', + offline: 'Offline', + }; + const levelIcons = { + checking: 'fa-circle-question', + healthy: 'fa-circle-check', + degraded: 'fa-triangle-exclamation', + offline: 'fa-circle-xmark', + }; + const levelColors = { + checking: 'var(--color-bar-text-muted)', + healthy: 'var(--color-success-strong, #16a34a)', + degraded: 'var(--color-warning, #f59e0b)', + offline: 'var(--color-danger, #ef4444)', + }; + + function setDialogVisible(dialog, visible) { + if (!dialog) return; + dialog.hidden = !visible; + dialog.style.display = visible ? 'grid' : 'none'; + dialog.setAttribute('aria-hidden', visible ? 'false' : 'true'); + } + + function createOverlay(id, title, description) { + const overlay = document.createElement('div'); + overlay.id = id; + overlay.hidden = true; + overlay.setAttribute('aria-hidden', 'true'); + overlay.setAttribute('role', 'dialog'); + overlay.setAttribute('aria-modal', 'true'); + overlay.setAttribute('aria-labelledby', `${id}Title`); + overlay.className = 'fixed inset-0 z-[210] hidden place-items-center bg-black/70 p-4'; + overlay.style.background = 'var(--color-overlay, rgba(0, 0, 0, 0.7))'; + overlay.innerHTML = ` +
+ +
+

${title}

+

${description}

+
+
+
+ `; + document.body.appendChild(overlay); + overlay.addEventListener('click', event => { + if (event.target === overlay) closeDialog(overlay); + }); + overlay.querySelector('[data-dialog-close]')?.addEventListener('click', () => closeDialog(overlay)); + return overlay; + } + + function ensureSettingsDialog() { + let overlay = document.getElementById('ncSettingsOverlay'); + if (overlay) return overlay; + + overlay = createOverlay('ncSettingsOverlay', 'Settings', 'Personalize the shared MediaCollection interface.'); + const body = overlay.querySelector('[data-dialog-body]'); + body.innerHTML = ` +
+
+
Theme
+
Switch between the light and dark appearance.
+
+ +
+ `; + return overlay; + } + + function ensureStatusDialog() { + let overlay = document.getElementById('ncStatusOverlay'); + if (overlay) return overlay; + + overlay = createOverlay('ncStatusOverlay', 'Status', 'Live liveness and database readiness checks.'); + const body = overlay.querySelector('[data-dialog-body]'); + body.innerHTML = ` +
+ + Checking + +
+
+
LivenessNot checked
+
Readiness / databaseNot checked
+
+

+
+ + +
+ `; + overlay.querySelector('[data-status-refresh]')?.addEventListener('click', () => void refreshStatus()); + overlay.querySelectorAll('[data-dialog-close]').forEach(button => { + button.addEventListener('click', () => closeDialog(overlay)); + }); + return overlay; + } + + function openDialog(dialog, opener) { + activeDialog = dialog; + activeOpener = opener || null; + setDialogVisible(dialog, true); + window.setTimeout(() => dialog.querySelector('[data-dialog-close]')?.focus(), 0); + } + + function closeDialog(dialog) { + if (!dialog) return; + setDialogVisible(dialog, false); + if (activeDialog === dialog) { + const opener = activeOpener; + activeDialog = null; + activeOpener = null; + opener?.focus?.(); + } + } + + async function probe(path) { + try { + const response = await fetch(path, { + credentials: 'same-origin', + headers: { Accept: 'application/json' }, + }); + const payload = await response.json().catch(() => null); + return { + ok: response.ok && payload?.ok !== false, + status: response.status, + service: payload?.service || '', + error: response.ok ? '' : payload?.error || response.statusText || `HTTP ${response.status}`, + }; + } catch (error) { + return { + ok: false, + status: null, + service: '', + error: error instanceof Error ? error.message : 'Unavailable', + }; + } + } + + function resultLabel(result) { + if (!result) return 'Not checked'; + if (result.ok) return 'OK'; + return result.error || (result.status ? `HTTP ${result.status}` : 'Unavailable'); + } + + function renderStatus() { + const iconClass = levelIcons[state.level]; + const color = levelColors[state.level]; + document.querySelectorAll('[data-status-button]').forEach(button => { + const icon = button.querySelector('[data-status-icon]'); + if (icon) { + icon.className = `fas ${iconClass}`; + icon.style.color = color; + } + button.title = `Service status: ${levelLabels[state.level]}`; + button.setAttribute('aria-label', `Service status: ${levelLabels[state.level]}`); + }); + + const dialog = document.getElementById('ncStatusOverlay'); + if (!dialog) return; + const overallIcon = dialog.querySelector('[data-status-overall-icon]'); + if (overallIcon) { + overallIcon.className = `fas ${iconClass} text-lg`; + overallIcon.style.color = color; + } + const overall = dialog.querySelector('[data-status-overall]'); + if (overall) { + overall.textContent = levelLabels[state.level]; + overall.style.color = color; + } + const checked = dialog.querySelector('[data-status-checked]'); + if (checked) checked.textContent = state.checkedAt ? new Date(state.checkedAt).toLocaleTimeString() : ''; + const health = dialog.querySelector('[data-status-health]'); + if (health) { + health.textContent = resultLabel(state.health); + health.style.color = state.health?.ok ? 'var(--color-success-strong, #16a34a)' : 'var(--color-danger, #ef4444)'; + } + const readiness = dialog.querySelector('[data-status-readiness]'); + if (readiness) { + readiness.textContent = resultLabel(state.readiness); + readiness.style.color = state.readiness?.ok ? 'var(--color-success-strong, #16a34a)' : 'var(--color-danger, #ef4444)'; + } + const service = dialog.querySelector('[data-status-service]'); + if (service) service.textContent = state.service ? `Service: ${state.service}` : ''; + const refreshButton = dialog.querySelector('[data-status-refresh]'); + if (refreshButton) refreshButton.disabled = state.loading; + } + + function refreshStatus() { + if (statusRequest) return statusRequest; + state.loading = true; + renderStatus(); + statusRequest = Promise.all([probe('/healthz'), probe('/ready')]) + .then(([health, readiness]) => { + state.health = health; + state.readiness = readiness; + state.service = health.service || readiness.service || ''; + state.level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline'; + state.checkedAt = new Date().toISOString(); + }) + .finally(() => { + state.loading = false; + statusRequest = null; + renderStatus(); + }); + return statusRequest; + } + + function bindHeaderButtons() { + document.querySelectorAll('[data-settings-button], [data-settings-menu-button]').forEach(button => { + if (boundButtons.has(button)) return; + boundButtons.add(button); + button.addEventListener('click', () => openDialog(ensureSettingsDialog(), button)); + }); + document.querySelectorAll('[data-status-button]').forEach(button => { + if (boundButtons.has(button)) return; + boundButtons.add(button); + button.addEventListener('click', () => { + const dialog = ensureStatusDialog(); + openDialog(dialog, button); + void refreshStatus(); + }); + }); + renderStatus(); + } + + function init() { + if (!document.body) return; + ensureSettingsDialog(); + ensureStatusDialog(); + bindHeaderButtons(); + window.NCThemeToggle?.init?.(); + if (!statusTimer) { + void refreshStatus(); + statusTimer = window.setInterval(() => void refreshStatus(), 15_000); + } + } + + document.addEventListener('keydown', event => { + if (event.key === 'Escape' && activeDialog) closeDialog(activeDialog); + }); + document.addEventListener('DOMContentLoaded', init, { once: true }); + document.addEventListener('nc:componentsLoaded', init); + + window.NCHeaderControls = { init, refreshStatus }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/layout/results-container.js b/shared/packages/media-shared-assets/public/js/layout/results-container.js new file mode 100644 index 0000000..415b6c8 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/layout/results-container.js @@ -0,0 +1,442 @@ +/** + * Shared Results container helpers. + * + * Exposes: + * - window.NCResultsContainer.apply(config) + * - window.NCResultsContainer.ensurePaginationBars(paginationBars) + */ +(() => { + const VIEW_MODES = [ + { + value: 'list', + label: 'List view', + icon: '', + }, + { + value: 'grid', + label: 'Grid view', + icon: '', + }, + ]; + + const VIEW_MODE_SYNC_KEY = '__ncViewModeSelectorSync'; + const VIEW_MODE_CHANGE_KEY = '__ncViewModeSelectorChange'; + const DEFAULT_RESULTS_CONTAINER_CLASSES = [ + 'rounded-lg', + 'border', + 'border-[var(--color-border)]', + 'bg-[var(--color-surface)]', + ]; + + function toElement(target) { + if (!target) return null; + if (target instanceof Element) return target; + if (typeof target === 'string') { + return document.getElementById(target) || document.querySelector(target); + } + return null; + } + + function toElementList(targets) { + if (!targets) return []; + const list = Array.isArray(targets) ? targets : [targets]; + return list.map(toElement).filter(el => el instanceof Element); + } + + function addClasses(el, classNames) { + if (!el || !classNames) return; + const list = Array.isArray(classNames) ? classNames : String(classNames).split(/\s+/); + for (const name of list) { + const token = String(name || '').trim(); + if (token) el.classList.add(token); + } + } + + function ensurePaginationBars(bars) { + for (const bar of toElementList(bars)) { + if (!bar.style.minHeight) bar.style.minHeight = '48px'; + bar.classList.add('w-full'); + bar.dataset.ncPaginationSlot = '1'; + } + } + + function normalizeViewModeConfig(config) { + if (!config) return null; + if (config instanceof Element || typeof config === 'string') { + return { select: config }; + } + return config; + } + + function normalizeModeValue(mode, fallback = 'grid') { + const value = String(mode || '').toLowerCase(); + if (value === 'compact') return 'list'; + if (value === 'list' || value === 'grid') return value; + return fallback; + } + + function readStoredMode(storageKey) { + if (!storageKey) return null; + try { + const raw = window.localStorage.getItem(storageKey); + return raw ? normalizeModeValue(raw, null) : null; + } catch { + return null; + } + } + + function writeStoredMode(storageKey, mode) { + if (!storageKey) return; + try { + window.localStorage.setItem(storageKey, mode); + } catch { + // ignore storage errors + } + } + + function applyViewModeSelector(resultsContainer, config) { + const viewMode = normalizeViewModeConfig(config); + if (!resultsContainer || !viewMode) return; + + const resultsContent = resultsContainer.querySelector('[data-nc-results-content="1"]'); + + function applyModeToResultsContent(mode) { + if (!resultsContent) return; + resultsContent.dataset.ncDisplayMode = normalizeModeValue(mode, 'grid'); + } + + const select = toElement( + viewMode.select || + viewMode.selectInput || + viewMode.selectElement || + viewMode.target || + viewMode.id + ); + const selectEl = select && select.tagName === 'SELECT' ? select : null; + + const selectId = (selectEl && selectEl.id) || String(viewMode.key || 'view-mode'); + const selectorId = `nc-view-mode-selector-${selectId}`; + + let modes = VIEW_MODES; + if (Array.isArray(viewMode.modes) && viewMode.modes.length > 0) { + const allowed = new Set( + viewMode.modes.map(mode => normalizeModeValue(mode, null)).filter(Boolean) + ); + modes = VIEW_MODES.filter(mode => allowed.has(mode.value)); + } + if (selectEl) { + const modeValues = new Set( + Array.from(selectEl.options || []) + .map(opt => normalizeModeValue(opt.value, null)) + .filter(Boolean) + ); + modes = modes.filter(mode => modeValues.has(mode.value)); + } + if (!modes.length) return; + + const defaultMode = normalizeModeValue(viewMode.defaultMode, 'grid'); + const storageKey = + typeof viewMode.storageKey === 'string' && viewMode.storageKey.trim().length > 0 + ? viewMode.storageKey.trim() + : null; + + let inlineMode = defaultMode; + if (!selectEl) { + const fromGetter = + typeof viewMode.getMode === 'function' + ? normalizeModeValue(viewMode.getMode(), defaultMode) + : null; + const fromStorage = readStoredMode(storageKey); + inlineMode = fromGetter || fromStorage || defaultMode; + } + + function getActiveMode() { + if (selectEl) return normalizeModeValue(selectEl.value, defaultMode); + return normalizeModeValue(inlineMode, defaultMode); + } + + function setActiveMode(mode, source = 'ui') { + const nextMode = normalizeModeValue(mode, defaultMode); + const available = modes.some(m => m.value === nextMode); + if (!available) return; + + applyModeToResultsContent(nextMode); + + if (selectEl) { + if (normalizeModeValue(selectEl.value, defaultMode) !== nextMode) { + selectEl.value = nextMode; + if (source !== 'select') { + selectEl.dispatchEvent(new Event('change', { bubbles: true })); + } + } + } else { + inlineMode = nextMode; + if (typeof viewMode.setMode === 'function') { + try { + viewMode.setMode(nextMode); + } catch { + // ignore consumer callback errors + } + } + writeStoredMode(storageKey, nextMode); + } + + if (!selectEl && typeof viewMode.onModeChange === 'function') { + try { + viewMode.onModeChange(nextMode); + } catch { + // ignore consumer callback errors + } + } + } + + const ownedHostSelector = '[data-nc-display-mode-host="1"]'; + + function getOwnedHosts() { + return Array.from(resultsContainer.querySelectorAll(ownedHostSelector)).filter( + host => host.dataset.ncViewModeOwner === selectorId + ); + } + + function hasResultCards() { + if (!(resultsContent instanceof Element)) return false; + return Boolean(resultsContent.querySelector('[data-nc-result-card="1"]')); + } + + function syncSelectorVisibility() { + const showSelector = hasResultCards(); + for (const host of getOwnedHosts()) { + host.classList.toggle('hidden', !showSelector); + } + + if (selectEl && viewMode.hideSelect === false) { + selectEl.classList.toggle('hidden', !showSelector); + selectEl.setAttribute('aria-hidden', showSelector ? 'false' : 'true'); + } + } + + function resolveRenderHosts() { + const centerSlots = Array.from( + resultsContainer.querySelectorAll('[data-nc-pagination-center-slot="1"]') + ); + const paginationBars = Array.from( + resultsContainer.querySelectorAll('[data-nc-pagination-slot="1"]') + ); + const hosts = []; + + if (centerSlots.length) { + for (const slot of centerSlots) { + let host = Array.from(slot.querySelectorAll(ownedHostSelector)).find( + candidate => candidate.dataset.ncViewModeOwner === selectorId + ); + if (!host) { + host = document.createElement('div'); + host.className = 'flex items-center justify-center'; + host.dataset.ncDisplayModeHost = '1'; + host.dataset.ncViewModeOwner = selectorId; + slot.appendChild(host); + } + hosts.push(host); + } + } else { + let host = getOwnedHosts().find(candidate => candidate.dataset.ncViewModeFallback === '1'); + if (!host) { + host = document.createElement('div'); + host.className = 'mb-3 flex items-center justify-center'; + host.dataset.ncDisplayModeHost = '1'; + host.dataset.ncViewModeOwner = selectorId; + host.dataset.ncViewModeFallback = '1'; + } + + const anchor = paginationBars.find(bar => bar && bar.parentElement === resultsContainer); + if (anchor) { + resultsContainer.insertBefore(host, anchor); + } else { + resultsContainer.insertBefore(host, resultsContainer.firstChild); + } + hosts.push(host); + } + + const keep = new Set(hosts); + for (const existingHost of getOwnedHosts()) { + if (!keep.has(existingHost)) existingHost.remove(); + } + + return hosts; + } + + let syncActiveButtons = () => {}; + + function renderSelectorHosts() { + const hosts = resolveRenderHosts(); + const buttonGroups = []; + + for (const host of hosts) { + host.innerHTML = ''; + + const shell = document.createElement('div'); + shell.className = 'inline-flex items-center justify-center'; + + const group = document.createElement('div'); + group.className = 'inline-flex items-center gap-1.5'; + group.setAttribute('role', 'group'); + group.setAttribute('aria-label', viewMode.ariaLabel || 'Display mode'); + + const buttonByMode = new Map(); + for (const mode of modes) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = + 'inline-flex h-8 w-8 items-center justify-center rounded border border-transparent text-[var(--color-text-dim)] transition-colors hover:text-[var(--color-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-300/20'; + button.setAttribute('aria-label', mode.label); + button.setAttribute('title', mode.label); + button.dataset.ncDisplayMode = mode.value; + button.innerHTML = mode.icon; + button.addEventListener('click', () => { + if (getActiveMode() === mode.value) return; + setActiveMode(mode.value, 'ui'); + syncActiveButtons(); + }); + buttonByMode.set(mode.value, button); + group.appendChild(button); + } + + buttonGroups.push(buttonByMode); + shell.appendChild(group); + host.appendChild(shell); + } + + syncActiveButtons = () => { + const activeMode = getActiveMode(); + for (const group of buttonGroups) { + for (const mode of modes) { + const button = group.get(mode.value); + if (!button) continue; + const active = mode.value === activeMode; + button.setAttribute('aria-pressed', active ? 'true' : 'false'); + button.classList.toggle('text-[var(--color-text)]', active); + button.classList.toggle('text-[var(--color-text-dim)]', !active); + button.classList.toggle('bg-[var(--color-surface)]', active); + button.classList.toggle('border-[var(--color-border-strong)]', active); + button.classList.toggle('shadow-[var(--shadow-sm)]', active); + button.classList.toggle('opacity-100', active); + button.classList.toggle('border-transparent', !active); + button.classList.toggle('opacity-80', !active); + } + } + }; + + syncActiveButtons(); + syncSelectorVisibility(); + } + + if (selectEl && viewMode.hideSelect !== false) { + selectEl.style.display = 'none'; + selectEl.setAttribute('aria-hidden', 'true'); + selectEl.tabIndex = -1; + } + + if (selectEl && typeof selectEl[VIEW_MODE_SYNC_KEY] === 'function') { + selectEl.removeEventListener('change', selectEl[VIEW_MODE_SYNC_KEY]); + } + if (selectEl && typeof selectEl[VIEW_MODE_CHANGE_KEY] === 'function') { + selectEl.removeEventListener('change', selectEl[VIEW_MODE_CHANGE_KEY]); + } + if (selectEl) { + selectEl[VIEW_MODE_SYNC_KEY] = () => syncActiveButtons(); + selectEl[VIEW_MODE_CHANGE_KEY] = () => { + const currentMode = getActiveMode(); + applyModeToResultsContent(currentMode); + if (storageKey) writeStoredMode(storageKey, currentMode); + if (typeof viewMode.onModeChange === 'function') { + try { + viewMode.onModeChange(currentMode); + } catch { + // ignore consumer callback errors + } + } + }; + selectEl.addEventListener('change', selectEl[VIEW_MODE_SYNC_KEY]); + selectEl.addEventListener('change', selectEl[VIEW_MODE_CHANGE_KEY]); + + const stored = readStoredMode(storageKey); + if (stored && modes.some(mode => mode.value === stored) && selectEl.value !== stored) { + selectEl.value = stored; + selectEl.dispatchEvent(new Event('change', { bubbles: true })); + } + } else { + setActiveMode(inlineMode, 'init'); + } + + const paginationListenerKey = `__ncViewModePaginationListener_${selectorId}`; + if (typeof resultsContainer[paginationListenerKey] === 'function') { + resultsContainer.removeEventListener( + 'nc:pagination-rendered', + resultsContainer[paginationListenerKey] + ); + } + const onPaginationRendered = event => { + const target = event?.target; + if (!(target instanceof Element)) return; + if (!resultsContainer.contains(target)) return; + if (target.dataset.ncPaginationSlot !== '1') return; + renderSelectorHosts(); + }; + resultsContainer[paginationListenerKey] = onPaginationRendered; + resultsContainer.addEventListener('nc:pagination-rendered', onPaginationRendered); + + const resultsObserverKey = `__ncViewModeResultsObserver_${selectorId}`; + const existingObserver = resultsContainer[resultsObserverKey]; + if (existingObserver && typeof existingObserver.disconnect === 'function') { + existingObserver.disconnect(); + } + if (resultsContent instanceof Element && typeof MutationObserver !== 'undefined') { + const observer = new MutationObserver(() => { + syncSelectorVisibility(); + }); + observer.observe(resultsContent, { childList: true, subtree: true }); + resultsContainer[resultsObserverKey] = observer; + } + + renderSelectorHosts(); + applyModeToResultsContent(getActiveMode()); + syncSelectorVisibility(); + } + + function applyResultsContainer(config = {}) { + const container = toElement(config.container || config.resultsContainer || config.id); + if (!container) return null; + + if (config.useDefaultShellClasses === true) { + addClasses(container, DEFAULT_RESULTS_CONTAINER_CLASSES); + } + addClasses(container, config.classes); + + const role = Object.prototype.hasOwnProperty.call(config, 'role') ? config.role : 'region'; + if (role) container.setAttribute('role', role); + if (config.label) container.setAttribute('aria-label', config.label); + + container.dataset.ncResultsContainer = '1'; + + const content = toElement(config.resultsContent || config.grid || config.list); + if (content) { + content.dataset.ncResultsContent = '1'; + if (!content.hasAttribute('aria-live')) content.setAttribute('aria-live', 'polite'); + } + + const emptyState = toElement(config.emptyState); + if (emptyState) emptyState.dataset.ncResultsEmpty = '1'; + + ensurePaginationBars(config.topPagination); + ensurePaginationBars(config.bottomPagination); + ensurePaginationBars(config.paginationBars); + applyViewModeSelector(container, config.viewModeSelector || config.viewMode); + + return container; + } + + window.NCResultsContainer = { + apply: applyResultsContainer, + ensurePaginationBars, + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/layout/search-filter-container.js b/shared/packages/media-shared-assets/public/js/layout/search-filter-container.js new file mode 100644 index 0000000..9063798 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/layout/search-filter-container.js @@ -0,0 +1,433 @@ +/** + * Shared Search/Filter container helpers. + * + * Exposes: + * - window.NCSearchFilterContainer.apply(config) + * - window.NCSearchFilterContainer.applyStandardControls(config) + */ +(() => { + const DEFAULT_FILTER_CONTAINER_CLASSES = [ + 'rounded-lg', + 'border', + 'border-[var(--color-border)]', + 'bg-[var(--color-surface)]', + ]; + + const DEFAULT_PER_PAGE_VALUES = [12, 24, 48, 96]; + const DEFAULT_PER_PAGE_VALUE = 24; + + const DEFAULT_SORT_OPTIONS = [ + { value: 'time_desc', label: 'Time (Newest first)' }, + { value: 'time_asc', label: 'Time (Oldest first)' }, + { value: 'title_asc', label: 'Title (A-Z)' }, + { value: 'title_desc', label: 'Title (Z-A)' }, + { value: 'length_asc', label: 'Length (Short to long)' }, + { value: 'length_desc', label: 'Length (Long to short)' }, + { value: 'resolution_asc', label: 'Resolution (Low to high)' }, + { value: 'resolution_desc', label: 'Resolution (High to low)' }, + { value: 'speed_asc', label: 'Speed (Slow to fast)' }, + { value: 'speed_desc', label: 'Speed (Fast to slow)' }, + ]; + + function toElement(target) { + if (!target) return null; + if (target instanceof Element) return target; + if (typeof target === 'string') { + return document.getElementById(target) || document.querySelector(target); + } + return null; + } + + function addClasses(el, classNames) { + if (!el || !classNames) return; + const list = Array.isArray(classNames) ? classNames : String(classNames).split(/\s+/); + for (const name of list) { + const token = String(name || '').trim(); + if (token) el.classList.add(token); + } + } + + function normalizeSearchInputAria(inputEl, fallbackLabel) { + if (!inputEl || inputEl.hasAttribute('aria-label')) return; + const placeholder = String(inputEl.getAttribute('placeholder') || '').trim(); + inputEl.setAttribute('aria-label', placeholder || fallbackLabel || 'Search'); + } + + function cloneOptions(options) { + return (Array.isArray(options) ? options : []).map(option => ({ + value: String(option.value), + label: String(option.label), + })); + } + + function normalizePerPageOptions() { + return DEFAULT_PER_PAGE_VALUES.map(value => ({ + value: String(value), + label: `${value} per page`, + })); + } + + function normalizeSortOptions(options) { + const source = Array.isArray(options) && options.length ? options : DEFAULT_SORT_OPTIONS; + return source + .map(entry => { + if (!entry) return null; + if (typeof entry === 'object') { + const value = String(entry.value ?? '').trim(); + if (!value) return null; + const label = String(entry.label ?? value).trim() || value; + return { value, label }; + } + const value = String(entry).trim(); + if (!value) return null; + return { value, label: value }; + }) + .filter(Boolean); + } + + function setSelectOptions(selectEl, options, selectedValue, fallbackValue = options[0]?.value) { + if (!selectEl || !options.length) return null; + + const normalizedSelected = String(selectedValue ?? selectEl.value ?? '').trim(); + const values = new Set(options.map(option => option.value)); + const resolvedValue = + normalizedSelected && values.has(normalizedSelected) + ? normalizedSelected + : values.has(String(fallbackValue)) + ? String(fallbackValue) + : String(options[0].value); + + selectEl.innerHTML = ''; + options.forEach(option => { + const opt = document.createElement('option'); + opt.value = option.value; + opt.textContent = option.label; + selectEl.appendChild(opt); + }); + selectEl.value = resolvedValue; + return resolvedValue; + } + + function applyStandardControls(config = {}) { + const searchInput = toElement(config.searchInput); + const perPageSelect = toElement(config.perPageSelect || config.perPageInput); + const sortSelect = toElement(config.sortSelect || config.sortInput); + + if (searchInput) { + const placeholder = String(config.searchPlaceholder || '').trim(); + const shouldSetPlaceholder = + !!placeholder && + (config.forceSearchPlaceholder === true || + !String(searchInput.getAttribute('placeholder') || '').trim()); + if (shouldSetPlaceholder) searchInput.setAttribute('placeholder', placeholder); + normalizeSearchInputAria(searchInput, config.searchLabel || config.label); + } + + const perPageOptions = normalizePerPageOptions(); + const sortOptions = normalizeSortOptions(config.sortOptions); + + const perPageValue = perPageSelect + ? setSelectOptions(perPageSelect, perPageOptions, config.perPageValue, DEFAULT_PER_PAGE_VALUE) + : null; + const sortValue = sortSelect + ? setSelectOptions(sortSelect, sortOptions, config.sortValue) + : null; + + return { + searchInput, + perPageSelect, + sortSelect, + perPageValue, + sortValue, + }; + } + + function toElementInContainer(target, container) { + if (!target || !container) return null; + if (target instanceof Element) { + return container.contains(target) ? target : null; + } + if (typeof target === 'string') { + const value = target.trim(); + if (!value) return null; + + const safeValue = value.split('"').join('\\"'); + const byIdInContainer = container.querySelector(`[id="${safeValue}"]`); + if (byIdInContainer) return byIdInContainer; + + try { + const bySelectorInContainer = container.querySelector(value); + if (bySelectorInContainer) return bySelectorInContainer; + } catch { + // Ignore invalid selectors and continue to ID lookup. + } + + const byId = document.getElementById(value); + if (byId && container.contains(byId)) return byId; + } + return null; + } + + function normalizeFilterTargets(filterControls) { + if (!filterControls) return []; + if (Array.isArray(filterControls)) return filterControls; + return [filterControls]; + } + + function resolveControlNode(controlEl, container) { + if (!controlEl || !container.contains(controlEl)) return null; + + let node = controlEl; + const parent = controlEl.parentElement; + + if (parent && parent !== container) { + const hasAssociatedLabel = + !!controlEl.id && + Array.from(parent.children).some(child => { + return child.tagName === 'LABEL' && child.getAttribute('for') === controlEl.id; + }); + + if (parent.tagName === 'LABEL' || parent.children.length === 1 || hasAssociatedLabel) { + node = parent; + } + } + + if (!container.contains(node)) return null; + return node; + } + + function resolveDropdownHost(container, searchInput, placement) { + const placementValue = String(placement || '').toLowerCase(); + const desiredPlacement = placementValue === 'inline' ? 'inline' : 'below-search'; + + let row = null; + if (searchInput && container.contains(searchInput)) { + const matchedRow = searchInput.closest('.flex'); + if (matchedRow && container.contains(matchedRow)) { + row = matchedRow; + } + } + + if (desiredPlacement === 'below-search') { + if (row?.parentElement && container.contains(row.parentElement)) { + return { + host: row.parentElement, + row, + mode: 'below-search', + }; + } + + return { + host: container, + row, + mode: 'below-search', + }; + } + + if (row) { + return { + host: row, + row, + mode: 'inline', + }; + } + + return { + host: container, + row: null, + mode: desiredPlacement, + }; + } + + function hidePrimaryTitle(container) { + const headings = Array.from(container.querySelectorAll('h1, h2, h3, h4, h5, h6')); + const target = headings.find(heading => !heading.closest('button, summary')); + if (!target) return; + + const parent = target.parentElement; + target.remove(); + + if ( + parent && + parent !== container && + parent.children.length === 0 && + !String(parent.textContent || '').trim() + ) { + parent.remove(); + } + } + + function ensureFiltersDropdown(config = {}) { + const container = config.container; + if (!container) return null; + + const targets = []; + const explicitTargets = normalizeFilterTargets(config.filterControls); + explicitTargets.forEach(target => { + const el = toElementInContainer(target, container); + if (el) targets.push(el); + }); + + if (config.includeStandardControls === true) { + const perPage = toElementInContainer(config.perPageSelect, container); + const sort = toElementInContainer(config.sortSelect, container); + if (perPage) targets.push(perPage); + if (sort) targets.push(sort); + } + + if (!targets.length) { + const existing = container.querySelector('[data-nc-filters-dropdown="1"]'); + if (existing) existing.remove(); + return null; + } + + const placement = resolveDropdownHost( + container, + config.searchInput, + config.filterDropdownPlacement + ); + const host = placement.host; + if (!host) return null; + + let details = container.querySelector('[data-nc-filters-dropdown="1"]'); + let panel = container.querySelector('[data-nc-filters-dropdown-panel="1"]'); + let summary = container.querySelector('[data-nc-filters-dropdown-toggle="1"]'); + + if (!details || !panel || !summary) { + details = document.createElement('details'); + details.dataset.ncFiltersDropdown = '1'; + details.className = placement.mode === 'below-search' ? 'relative mt-2 w-full' : 'relative'; + + summary = document.createElement('summary'); + summary.dataset.ncFiltersDropdownToggle = '1'; + summary.className = + placement.mode === 'below-search' + ? 'inline-flex w-full cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]' + : 'inline-flex cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]'; + summary.textContent = String(config.filterDropdownLabel || 'FILTERS'); + summary.style.listStyle = 'none'; + + panel = document.createElement('div'); + panel.dataset.ncFiltersDropdownPanel = '1'; + panel.className = + 'mt-2 flex flex-wrap items-center gap-3 rounded-md border border-[var(--color-border)] bg-[var(--color-surface)] p-3'; + + details.appendChild(summary); + details.appendChild(panel); + } else { + details.className = placement.mode === 'below-search' ? 'relative mt-2 w-full' : 'relative'; + summary.className = + placement.mode === 'below-search' + ? 'inline-flex w-full cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]' + : 'inline-flex cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]'; + summary.textContent = String(config.filterDropdownLabel || 'FILTERS'); + } + + if ( + placement.mode === 'below-search' && + placement.row && + placement.row.parentElement === host + ) { + host.insertBefore(details, placement.row.nextSibling); + } else if (!host.contains(details)) { + host.appendChild(details); + } + + const movedNodes = []; + const seen = new Set(); + const searchNode = resolveControlNode(config.searchInput, container); + + targets.forEach(target => { + const node = resolveControlNode(target, container); + if (!node || node === searchNode || node.contains(searchNode)) return; + if (seen.has(node)) return; + + const hiddenControl = + target.type === 'hidden' || + target.hidden === true || + target.classList?.contains('hidden') || + node.hidden === true || + node.classList?.contains('hidden'); + if (hiddenControl) return; + + seen.add(node); + movedNodes.push(node); + }); + + movedNodes.forEach(node => { + if (!panel.contains(node)) panel.appendChild(node); + }); + + if (!panel.children.length) { + details.remove(); + return null; + } + + return details; + } + + function applyFilterContainer(config = {}) { + const container = toElement(config.container || config.filterContainer || config.id); + if (!container) return null; + + if (config.useDefaultShellClasses === true) { + addClasses(container, DEFAULT_FILTER_CONTAINER_CLASSES); + } + addClasses(container, config.classes); + + const role = Object.prototype.hasOwnProperty.call(config, 'role') ? config.role : 'region'; + if (role) container.setAttribute('role', role); + if (config.label) container.setAttribute('aria-label', config.label); + + container.dataset.ncFilterContainer = '1'; + + const searchInput = toElement(config.searchInput); + normalizeSearchInputAria(searchInput, config.searchLabel || config.label); + + let standardControlsResult = null; + if (config.standardControls === true) { + standardControlsResult = applyStandardControls({ + label: config.label, + searchLabel: config.searchLabel, + searchInput: searchInput || config.searchInput, + searchPlaceholder: config.searchPlaceholder, + forceSearchPlaceholder: config.forceSearchPlaceholder, + perPageSelect: config.perPageSelect, + perPageOptions: config.perPageOptions, + perPageValue: config.perPageValue, + sortSelect: config.sortSelect, + sortOptions: config.sortOptions, + sortValue: config.sortValue, + }); + } + + const resolvedSearchInput = standardControlsResult?.searchInput || searchInput; + + if (config.hideTitle !== false) { + hidePrimaryTitle(container); + } + + if (config.filtersDropdown !== false) { + ensureFiltersDropdown({ + container, + searchInput: resolvedSearchInput, + filterControls: config.filterControls, + includeStandardControls: config.includeStandardControlsInDropdown === true, + perPageSelect: + standardControlsResult?.perPageSelect || config.perPageSelect || config.perPageInput, + sortSelect: standardControlsResult?.sortSelect || config.sortSelect || config.sortInput, + filterDropdownPlacement: config.filterDropdownPlacement, + filterDropdownLabel: config.filterDropdownLabel, + }); + } + + return container; + } + + window.NCSearchFilterContainer = { + apply: applyFilterContainer, + applyStandardControls, + getDefaultPerPageOptions: () => normalizePerPageOptions(DEFAULT_PER_PAGE_VALUES), + getDefaultSortOptions: () => cloneOptions(DEFAULT_SORT_OPTIONS), + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/media/media-detail-view.js b/shared/packages/media-shared-assets/public/js/media/media-detail-view.js new file mode 100644 index 0000000..50ce2ee --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/media/media-detail-view.js @@ -0,0 +1,28 @@ +(() => { + function normalizeBlocks(blocks) { + if (Array.isArray(blocks)) return blocks; + if (blocks == null) return []; + return [blocks]; + } + + function renderLayout(config = {}) { + const previewHtml = String(config.previewHtml || ''); + const contentBlocks = normalizeBlocks(config.contentBlocks) + .map(block => String(block || '').trim()) + .filter(Boolean) + .join(''); + const rootClass = String(config.rootClass || 'flex flex-col gap-3 md:flex-row md:gap-3').trim(); + const contentClass = String(config.contentClass || 'flex-1 min-w-0 space-y-5').trim(); + + return `
+ ${previewHtml} +
+ ${contentBlocks} +
+
`; + } + + window.NCMediaDetailView = { + renderLayout, + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/media/media-preview.js b/shared/packages/media-shared-assets/public/js/media/media-preview.js new file mode 100644 index 0000000..ed36cc6 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/media/media-preview.js @@ -0,0 +1,481 @@ +// NCMediaPreview - shared fullscreen image / video preview component. +// Served at /shared/js/media/media-preview.js by applySharedBase. +// +// Two modes: +// attach(opts) -> attach to existing overlay + frame elements in the DOM. +// Returns a controller with { open, close, prev, next, +// setItems, isOpen, currentIndex, preloader, destroy }. +// +// lightbox(opts) -> dynamically create a minimal single-image lightbox. +// Returns { open(url, alt), close, destroy }. +// +// attach() opts: +// overlayEl {Element} required - fixed fullscreen overlay div +// frameEl {Element} required - inner div where img/video is mounted +// preloadRadius {number} default 2 - neighbors to eagerly preload +// loop {boolean} default false - wrap-around navigation +// renderItem {function(frameEl, item)} - custom render; used instead of +// default img/video creation when provided +// onClose {function()} +// onNavigate {function(idx, item)} +// +// Items shape for setItems(): [{ url, thumbnail?, name?, mediaType? }] +// mediaType 'video' forces video element; otherwise URL extension is used. +// +// lightbox() opts: +// id {string} default 'ncLightboxOverlay' +// zIndex {string} default 'z-50' +// imgClass {string} default: centered object-contain image style + +(function (global) { + 'use strict'; + + var VIDEO_EXT = /\.(mp4|webm|mov|avi|mkv)$/i; + var AUDIO_EXT = /\.(mp3|flac|wav|ogg|aac|m4a|opus|wma|aiff)$/i; + + /** Returns true when the URL path has a recognised video extension. */ + function isVideo(url) { + return VIDEO_EXT.test(String(url || '').split('?')[0]); + } + + /** Returns true when the URL path has a recognised audio extension. */ + function isAudio(url) { + return AUDIO_EXT.test(String(url || '').split('?')[0]); + } + + /** Build a simple image-preload cache. */ + function makePreloader() { + var cache = new Map(); + return { + load: function (url) { + if (!url) return Promise.reject(new Error('no url')); + if (cache.has(url)) return cache.get(url); + var p = new Promise(function (res, rej) { + var im = new Image(); + im.onload = function () { + res(im); + }; + im.onerror = rej; + im.src = url; + }); + cache.set(url, p); + return p; + }, + clear: function () { + cache.clear(); + }, + }; + } + + /** Shared CSS for the media element inside the frame. */ + var MEDIA_CLS = + 'max-h-full max-w-full rounded-md bg-black object-contain shadow-[var(--shadow-2xl,0_10px_40px_rgba(0,0,0,.6))]'; + + /** + * Keep fullscreen media inside comfortable insets so content is not clipped + * by overlay edges or covered by overlay chrome. + */ + function applySafeMediaLayout(node) { + if (!node) return; + try { + node.style.width = 'auto'; + node.style.height = 'auto'; + node.style.maxWidth = 'calc(100% - 1.5rem)'; + node.style.maxHeight = 'calc(100% - 1.5rem)'; + node.style.objectFit = 'contain'; + node.style.objectPosition = 'center'; + // eslint-disable-next-line no-empty + } catch {} + } + + /** + * Toggle overlay visibility using both class-based and attribute-based + * strategies so it works with all existing overlay markup in the codebase. + */ + function setVisible(overlayEl, visible) { + if (!overlayEl) return; + if (visible) { + overlayEl.classList.remove('hidden'); + overlayEl.classList.add('flex', 'is-active'); + overlayEl.style.removeProperty('display'); + overlayEl.hidden = false; + overlayEl.setAttribute('aria-hidden', 'false'); + try { + document.body.classList.add('overflow-hidden'); + document.documentElement.classList.add('overflow-hidden'); + // eslint-disable-next-line no-empty + } catch {} + } else { + overlayEl.classList.remove('flex', 'is-active'); + overlayEl.classList.add('hidden'); + overlayEl.style.setProperty('display', 'none', 'important'); + overlayEl.hidden = true; + overlayEl.setAttribute('aria-hidden', 'true'); + try { + document.body.classList.remove('overflow-hidden'); + document.documentElement.classList.remove('overflow-hidden'); + // eslint-disable-next-line no-empty + } catch {} + } + } + + // -- attach() ---------------------------------------------------------------- + + /** + * Attach a media preview controller to existing overlay + frame DOM elements. + * + * The component automatically wires: + * • [data-overlay-prev] -> prev() + * • [data-overlay-next] -> next() + * • [aria-label="Close"] -> close() (searched inside overlayEl) + * • Backdrop click (click directly on overlayEl) -> close() + * • Keyboard: Escape -> close, ArrowLeft -> prev, ArrowRight -> next + * + * @param {object} opts + * @returns controller + */ + function attach(opts) { + opts = opts || {}; + var overlayEl = opts.overlayEl; + var frameEl = opts.frameEl; + if (!overlayEl || !frameEl) { + throw new Error('NCMediaPreview.attach: overlayEl and frameEl are required'); + } + + var radius = Math.max(0, Number(opts.preloadRadius) || 2); + var loop = !!opts.loop; + var items = []; // [{ url, thumbnail, name, mediaType }] + var _idx = -1; + var _open = false; + var preloader = makePreloader(); + + // Auto-discover standard buttons within the overlay + var closeBtn = overlayEl.querySelector('[aria-label="Close"]'); + var prevBtn = overlayEl.querySelector('[data-overlay-prev]'); + var nextBtn = overlayEl.querySelector('[data-overlay-next]'); + + var hasInFrameClose = !!(closeBtn && frameEl.contains(closeBtn)); + + // Reserve safe space inside the frame so media is never hidden under + // in-frame close controls and never touches overlay boundaries. + try { + frameEl.style.boxSizing = 'border-box'; + frameEl.style.padding = hasInFrameClose ? '3.25rem 0.75rem 0.75rem 0.75rem' : '0.75rem'; + // eslint-disable-next-line no-empty + } catch {} + + function applyFramePaddingForItem(item) { + try { + if (!hasInFrameClose) { + frameEl.style.padding = '0.75rem'; + return; + } + + var kind = String((item && item.mediaType) || '').toLowerCase(); + var url = String((item && item.url) || ''); + var isImageLike = kind !== 'video' && kind !== 'audio' && !isVideo(url) && !isAudio(url); + + // For image previews, keep vertical insets symmetric. + frameEl.style.padding = isImageLike + ? '3.25rem 0.75rem 3.25rem 0.75rem' + : '3.25rem 0.75rem 0.75rem 0.75rem'; + // eslint-disable-next-line no-empty + } catch {} + } + + // Ensure overlays always start hidden after attach in case responsive + // display utilities override class-based hidden rules on first paint. + setVisible(overlayEl, false); + + function updateButtons() { + if (prevBtn) prevBtn.disabled = loop ? false : _idx <= 0; + if (nextBtn) nextBtn.disabled = loop ? false : _idx >= items.length - 1; + } + + /** Pause + remove any img/video/audio children from the frame. */ + function clearFrame() { + Array.from(frameEl.querySelectorAll('video,audio')).forEach(function (v) { + try { + v.pause(); + // eslint-disable-next-line no-empty + } catch {} + }); + Array.from(frameEl.querySelectorAll('img,video,audio')).forEach(function (n) { + if (n.parentNode === frameEl) frameEl.removeChild(n); + }); + } + + /** Mount the media element for the given item. */ + function renderFrame(item) { + clearFrame(); + if (!item) return; + applyFramePaddingForItem(item); + + // Delegate to caller-supplied renderer if provided + if (opts.renderItem) { + try { + opts.renderItem(frameEl, item); + // eslint-disable-next-line no-empty + } catch {} + return; + } + + if (isVideo(item.url) || item.mediaType === 'video') { + var v = document.createElement('video'); + v.className = MEDIA_CLS; + v.src = item.url; + v.controls = true; + v.autoplay = true; + v.loop = true; + v.muted = false; + v.playsInline = true; + applySafeMediaLayout(v); + frameEl.appendChild(v); + } else if (isAudio(item.url) || item.mediaType === 'audio') { + var a = document.createElement('audio'); + a.src = item.url; + a.controls = true; + a.autoplay = true; + a.style.minWidth = '320px'; + a.style.maxWidth = '90vw'; + frameEl.appendChild(a); + } else { + var img = document.createElement('img'); + img.className = MEDIA_CLS; + img.alt = item.name || 'Media preview'; + applySafeMediaLayout(img); + frameEl.appendChild(img); + // Show thumbnail immediately, swap to full-res when ready + if (item.thumbnail) img.src = item.thumbnail; + var capturedIdx = _idx; + preloader + .load(item.url) + .then(function () { + img.src = item.url; + }) + .catch(function () { + img.src = item.url; + }) + .finally(function () { + // Preload neighbors after current is resolved + for (var d = 1; d <= radius; d++) { + var li = capturedIdx - d, + ri = capturedIdx + d; + if (li >= 0 && items[li]) preloader.load(items[li].url).catch(function () {}); + if (ri < items.length && items[ri]) + preloader.load(items[ri].url).catch(function () {}); + } + }); + } + } + + function open(i) { + if (!items.length) return; + _idx = Math.max(0, Math.min(i, items.length - 1)); + _open = true; + renderFrame(items[_idx]); + setVisible(overlayEl, true); + updateButtons(); + if (opts.onNavigate) + try { + opts.onNavigate(_idx, items[_idx]); + // eslint-disable-next-line no-empty + } catch {} + } + + function close() { + _open = false; + clearFrame(); + _idx = -1; + setVisible(overlayEl, false); + if (opts.onClose) + try { + opts.onClose(); + // eslint-disable-next-line no-empty + } catch {} + } + + function prev() { + if (!_open || !items.length) return; + var n = loop ? (_idx - 1 + items.length) % items.length : _idx - 1; + if (!loop && n < 0) return; + _idx = n; + renderFrame(items[_idx]); + updateButtons(); + if (opts.onNavigate) + try { + opts.onNavigate(_idx, items[_idx]); + // eslint-disable-next-line no-empty + } catch {} + } + + function next() { + if (!_open || !items.length) return; + var n = loop ? (_idx + 1) % items.length : _idx + 1; + if (!loop && n >= items.length) return; + _idx = n; + renderFrame(items[_idx]); + updateButtons(); + if (opts.onNavigate) + try { + opts.onNavigate(_idx, items[_idx]); + // eslint-disable-next-line no-empty + } catch {} + } + + /** + * Replace the item list. Clears the preload cache. + * Must be called with the full up-to-date list before open(). + */ + function setItems(newItems) { + items = Array.isArray(newItems) ? newItems : []; + preloader.clear(); + } + + // Wire built-in buttons + if (closeBtn) closeBtn.addEventListener('click', close); + if (prevBtn) prevBtn.addEventListener('click', prev); + if (nextBtn) nextBtn.addEventListener('click', next); + + // Backdrop click - close when clicking directly on the overlay backdrop + overlayEl.addEventListener('click', function (e) { + if (e.target === overlayEl) close(); + }); + + // Keyboard - Escape / arrows + function onKey(e) { + if (!_open) return; + if (e.key === 'Escape') close(); + else if (e.key === 'ArrowLeft') prev(); + else if (e.key === 'ArrowRight') next(); + } + window.addEventListener('keydown', onKey); + + var ctrl = { + open: open, + close: close, + prev: prev, + next: next, + setItems: setItems, + isOpen: function () { + return _open; + }, + preloader: preloader, + destroy: function () { + window.removeEventListener('keydown', onKey); + }, + }; + Object.defineProperty(ctrl, 'currentIndex', { + get: function () { + return _idx; + }, + }); + return ctrl; + } + + // -- lightbox() -------------------------------------------------------------- + + /** + * Build a minimal single-item image lightbox that creates its own DOM. + * Useful for cases where no overlay markup exists (e.g. MediaModerator). + * + * @param {object} [opts] { id, zIndex, imgClass } + * @returns {{ open(url, alt?), close, destroy }} + */ + function lightbox(opts) { + opts = opts || {}; + var id = opts.id || 'ncLightboxOverlay'; + var zIndex = opts.zIndex || 'z-50'; + var imgCls = + opts.imgClass || + 'block max-h-full max-w-full rounded-lg object-contain shadow-[0_8px_24px_rgba(0,0,0,0.5)]'; + + var el = null, + img = null; + + function ensure() { + if (el) return; + el = document.createElement('div'); + el.id = id; + el.setAttribute('role', 'dialog'); + el.setAttribute('aria-modal', 'true'); + el.className = [ + 'fixed inset-0', + zIndex, + 'hidden items-center justify-center bg-black/85 p-4', + ].join(' '); + + var inner = document.createElement('div'); + inner.className = 'relative flex h-full w-full items-center justify-center'; + + var closeBtn = document.createElement('button'); + closeBtn.type = 'button'; + closeBtn.setAttribute('aria-label', 'Close'); + closeBtn.className = + 'absolute right-4 top-4 z-10 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-slate-700 bg-black text-white'; + closeBtn.innerHTML = + ''; + closeBtn.addEventListener('click', close); + + img = document.createElement('img'); + img.alt = 'Preview'; + img.className = imgCls; + + inner.appendChild(closeBtn); + inner.appendChild(img); + el.appendChild(inner); + document.body.appendChild(el); + + el.addEventListener('click', function (e) { + if (e.target === el) close(); + }); + document.addEventListener('keydown', function (e) { + if (e.key === 'Escape' && !el.classList.contains('hidden')) close(); + }); + } + + function open(url, alt) { + ensure(); + img.src = url || ''; + if (alt) img.alt = alt; + applySafeMediaLayout(img); + try { + // Use equal viewport insets so image top and bottom spacing match. + img.style.maxWidth = 'calc(100vw - 4rem)'; + img.style.maxHeight = 'calc(100vh - 4rem)'; + img.style.margin = '0 auto'; + // eslint-disable-next-line no-empty + } catch {} + el.classList.remove('hidden'); + el.classList.add('flex'); + try { + document.body.classList.add('overflow-hidden'); + // eslint-disable-next-line no-empty + } catch {} + } + + function close() { + if (!el) return; + el.classList.add('hidden'); + el.classList.remove('flex'); + img.src = ''; + try { + document.body.classList.remove('overflow-hidden'); + // eslint-disable-next-line no-empty + } catch {} + } + + function destroy() { + close(); + if (el) { + el.remove(); + el = null; + img = null; + } + } + + return { open: open, close: close, destroy: destroy }; + } + + global.NCMediaPreview = { attach: attach, lightbox: lightbox, isVideo: isVideo }; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/media/thumbnails.js b/shared/packages/media-shared-assets/public/js/media/thumbnails.js new file mode 100644 index 0000000..e49e6d6 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/media/thumbnails.js @@ -0,0 +1,287 @@ +/** + * NCThumbnail - Shared thumbnail loading utility. + * + * Provides consistent image element creation, error handling, + * path encoding, and deferred loading across all services. + * + * Available at /shared/js/media/thumbnails.js via mountSharedStatic. + */ +window.NCThumbnail = (() => { + /* ------------------------------------------------------------------ */ + /* Utility */ + /* ------------------------------------------------------------------ */ + + /** + * Encode each segment of a path individually for safe URL embedding. + * @param {string} p - e.g. 'folder/sub dir/file.jpg' + * @returns {string} 'folder/sub%20dir/file.jpg' + */ + function encodePathSegments(p) { + return String(p || '') + .split('/') + .map(encodeURIComponent) + .join('/'); + } + + /* ------------------------------------------------------------------ */ + /* Image Element Creation */ + /* ------------------------------------------------------------------ */ + + /** + * Create a thumbnail `` with lazy loading and configurable error handling. + * + * @param {Object} opts + * @param {string} opts.src - Image source URL + * @param {string} [opts.alt=''] - Alt text + * @param {string} [opts.className=''] - CSS class(es) + * @param {boolean} [opts.lazy=true] - Set loading="lazy" + * @param {boolean} [opts.asyncDecode=true] - Set decoding="async" + * @param {string} [opts.fallbackSrc] - Swap to this URL on error + * @param {string} [opts.fallbackIcon] - FA icon class for placeholder (e.g. 'fas fa-image') + * @param {string} [opts.fallbackText] - Text shown inside placeholder + * @param {string} [opts.fallbackClass] - Extra CSS class(es) on placeholder div + * @param {Function}[opts.onError] - Custom onerror (overrides other fallbacks) + * @param {Object} [opts.dataset={}] - data-* attributes + * @returns {HTMLImageElement} + */ + function createImg(opts) { + const img = document.createElement('img'); + if (opts.className) img.className = opts.className; + img.alt = opts.alt || ''; + if (opts.lazy !== false) img.loading = 'lazy'; + if (opts.asyncDecode !== false) img.decoding = 'async'; + if (opts.src) img.src = opts.src; + if (opts.dataset) { + for (const [k, v] of Object.entries(opts.dataset)) img.dataset[k] = v; + } + + if (typeof opts.onError === 'function') { + img.onerror = opts.onError; + } else if (opts.fallbackSrc) { + img.onerror = function () { + this.onerror = null; + this.src = opts.fallbackSrc; + }; + } else if (opts.fallbackIcon || opts.fallbackText) { + img.onerror = function () { + this.onerror = null; + const parent = this.parentElement; + if (!parent) { + this.style.display = 'none'; + return; + } + this.remove(); + const fb = document.createElement('div'); + fb.className = + opts.fallbackClass || 'flex flex-col items-center justify-center gap-1.5 text-slate-400'; + if (opts.fallbackIcon) { + const i = document.createElement('i'); + i.className = opts.fallbackIcon; + i.setAttribute('aria-hidden', 'true'); + fb.appendChild(i); + } + if (opts.fallbackText) { + const s = document.createElement('span'); + s.className = 'text-xs'; + s.textContent = opts.fallbackText; + fb.appendChild(s); + } + parent.appendChild(fb); + }; + } + + return img; + } + + /** + * Create an `` paired with a hidden fallback sibling. + * On error the image hides and the fallback shows - preserves layout. + * + * @param {Object} opts + * @param {string} opts.src - Image source URL + * @param {string} [opts.alt=''] - Alt text + * @param {string} [opts.className=''] - CSS class(es) for the image + * @param {string} [opts.fallbackHtml=''] - Inner HTML for the fallback + * @param {string} [opts.fallbackClassName=''] - Extra class(es) on fallback + * @param {Object} [opts.dataset={}] - data-* attributes on the image + * @returns {{ img: HTMLImageElement, fallback: HTMLSpanElement }} + */ + function createImgWithFallback(opts) { + const img = document.createElement('img'); + if (opts.className) img.className = opts.className; + img.alt = opts.alt || ''; + img.loading = 'lazy'; + img.decoding = 'async'; + if (opts.src) img.src = opts.src; + if (opts.dataset) { + for (const [k, v] of Object.entries(opts.dataset)) img.dataset[k] = v; + } + + const fallback = document.createElement('span'); + fallback.className = 'hidden' + (opts.fallbackClassName ? ' ' + opts.fallbackClassName : ''); + if (opts.fallbackHtml) fallback.innerHTML = opts.fallbackHtml; + + img.onerror = function () { + this.onerror = null; + this.classList.add('hidden'); + fallback.classList.remove('hidden'); + }; + + return { img, fallback }; + } + + /* ------------------------------------------------------------------ */ + /* Deferred Loading */ + /* ------------------------------------------------------------------ */ + + /** + * Deferred thumbnail loading via IntersectionObserver with a throttled + * concurrent-request queue. + * + * Target images must use `data-src` (not `src`). When intersecting the + * viewport, `data-src` is copied to `src`. + * + * @param {Object} opts + * @param {string} [opts.selector='img[data-src]'] - Query selector + * @param {Element} [opts.root=null] - Scroll container (null = viewport) + * @param {string} [opts.rootMargin='300px'] - Preload margin + * @param {number} [opts.maxConcurrent=4] - Max simultaneous loads + * @param {Function}[opts.onLoad] - Callback per loaded image + * @param {Function}[opts.onError] - Callback per failed image + * @returns {{ destroy: Function, observe: Function }} + */ + function initDeferredLoading(opts = {}) { + const { + selector = 'img[data-src]', + root = null, + rootMargin = '300px', + maxConcurrent = 4, + onLoad, + onError, + } = opts; + + const queue = []; + let inFlight = 0; + + const pump = () => { + while (inFlight < maxConcurrent && queue.length) { + const img = queue.shift(); + if (!img || !img.isConnected) continue; + const src = img.getAttribute('data-src'); + if (!src) continue; + img.removeAttribute('data-src'); + inFlight++; + const done = () => { + inFlight = Math.max(0, inFlight - 1); + pump(); + }; + img.addEventListener( + 'load', + () => { + if (onLoad) onLoad(img); + done(); + }, + { once: true } + ); + img.addEventListener( + 'error', + () => { + if (onError) onError(img); + done(); + }, + { once: true } + ); + img.src = src; + } + }; + + const observer = new IntersectionObserver( + entries => { + for (const e of entries) { + if (!e.isIntersecting) continue; + observer.unobserve(e.target); + queue.push(e.target); + } + pump(); + }, + { root, rootMargin, threshold: 0.01 } + ); + + const elements = document.querySelectorAll(selector); + for (const el of elements) observer.observe(el); + + return { + destroy() { + observer.disconnect(); + queue.length = 0; + }, + observe(el) { + observer.observe(el); + }, + }; + } + + /** + * Attach load / error tracking to existing `` elements, toggling + * an adjacent status-overlay element (e.g. "Loading..." -> hidden on + * success, or "Couldn't load" on error). + * + * @param {Object} opts + * @param {string} [opts.imgSelector='img[data-card-media]'] + * @param {string} [opts.statusAttr='data-card-status'] + * @param {string} [opts.errorText="Thumbnail couldn\u2019t load"] + * @param {boolean} [opts.skipDeferred=false] - Skip imgs with data-src (handled by initDeferredLoading) + */ + function initStatusTracking(opts = {}) { + const { + imgSelector = 'img[data-card-media]', + statusAttr = 'data-card-status', + errorText = 'Thumbnail couldn\u2019t load', + skipDeferred = false, + } = opts; + + const images = document.querySelectorAll(imgSelector); + for (const img of images) { + if (skipDeferred && img.hasAttribute('data-src')) continue; + + const card = img.closest('[data-card]') || img.parentElement; + const statusEl = card?.querySelector(`[${statusAttr}]`); + + img.addEventListener( + 'load', + () => { + if (statusEl) statusEl.classList.add('hidden'); + }, + { once: true } + ); + + img.addEventListener( + 'error', + () => { + if (statusEl) { + statusEl.textContent = errorText; + statusEl.classList.remove('hidden'); + } + }, + { once: true } + ); + + // Handle already-cached images. + try { + if (img.complete && img.naturalWidth > 0 && statusEl) statusEl.classList.add('hidden'); + } catch { + /* ignore */ + } + } + } + + /* ------------------------------------------------------------------ */ + + return { + encodePathSegments, + createImg, + createImgWithFallback, + initDeferredLoading, + initStatusTracking, + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/navigation/pagination-bottom.js b/shared/packages/media-shared-assets/public/js/navigation/pagination-bottom.js new file mode 100644 index 0000000..a8a357b --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/navigation/pagination-bottom.js @@ -0,0 +1,15 @@ +/** + * Shared Pagination Component (Bottom) + * The core renderer lives in pagination-top.js as window.NCPagination. + */ +(() => { + window.NCPaginationBottom = { + render(container, state, onPageChange) { + if (!window.NCPagination || typeof window.NCPagination.render !== 'function') { + console.error('NCPagination core is not available. Load pagination-top.js first.'); + return; + } + window.NCPagination.render(container, state, onPageChange, 'bottom'); + }, + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/navigation/pagination-top.js b/shared/packages/media-shared-assets/public/js/navigation/pagination-top.js new file mode 100644 index 0000000..cd35a98 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/navigation/pagination-top.js @@ -0,0 +1,178 @@ +/** + * Shared Pagination Core + * Exposes: + * - window.NCPagination.render(container, state, onPageChange, variant) + * - window.NCPaginationTop.render(container, state, onPageChange) + * - window.NCPaginationBottom.render(container, state, onPageChange) + * onPageChange receives (page, pageSize), where pageSize is one of 12, 24, 48, or 96. + */ +(() => { + if (window.NCPagination && typeof window.NCPagination.render === 'function') { + window.NCPaginationTop = { + render(container, state, onPageChange) { + window.NCPagination.render(container, state, onPageChange, 'top'); + }, + }; + window.NCPaginationBottom = { + render(container, state, onPageChange) { + window.NCPagination.render(container, state, onPageChange, 'bottom'); + }, + }; + return; + } + + function fmtNum(n) { + return String(Number(n) || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ','); + } + + const PAGE_SIZE_OPTIONS = [12, 24, 48, 96]; + const DEFAULT_PAGE_SIZE = 24; + + const icons = { + first: + '', + prev: '', + next: '', + last: '', + }; + + function render(container, state = {}, onPageChange, variant = 'top') { + if (!container) return; + + const page = Math.max(1, Number(state.page) || 1); + const pages = Math.max(1, Number(state.pages) || 1); + const total = Math.max(0, Number(state.total) || 0); + const requestedPageSize = Number(state.pageSize); + const pageSize = PAGE_SIZE_OPTIONS.includes(requestedPageSize) + ? requestedPageSize + : DEFAULT_PAGE_SIZE; + const visible = pages > 1 || (state.total !== undefined && total > 0); + + container.hidden = !visible; + container.style.display = visible ? '' : 'none'; + container.classList.remove('hidden'); + container.classList.add('nc-pagination-container'); + container.classList.remove('nc-pagination-top', 'nc-pagination-bottom'); + container.classList.add(variant === 'bottom' ? 'nc-pagination-bottom' : 'nc-pagination-top'); + + if (!visible) { + container.innerHTML = ''; + return; + } + + container.innerHTML = ''; + + const meta = document.createElement('div'); + meta.className = 'nc-pagination-meta'; + + const infoSpan = document.createElement('span'); + infoSpan.className = 'nc-pagination-info'; + if (state.infoText !== undefined) { + infoSpan.textContent = state.infoText; + } else { + infoSpan.textContent = `Page ${fmtNum(page)} of ${fmtNum(pages)} (${fmtNum(total)} total)`; + } + + const pageSizeLabel = document.createElement('label'); + pageSizeLabel.className = 'nc-pagination-page-size-label'; + pageSizeLabel.textContent = 'Entries per page'; + + const pageSizeSelect = document.createElement('select'); + pageSizeSelect.className = 'nc-pagination-page-size'; + pageSizeSelect.setAttribute('aria-label', 'Entries per page'); + PAGE_SIZE_OPTIONS.forEach(size => { + const option = document.createElement('option'); + option.value = String(size); + option.textContent = String(size); + option.selected = size === pageSize; + pageSizeSelect.appendChild(option); + }); + pageSizeSelect.addEventListener('change', () => { + if (typeof onPageChange === 'function') onPageChange(1, Number(pageSizeSelect.value)); + }); + pageSizeLabel.appendChild(pageSizeSelect); + meta.appendChild(infoSpan); + meta.appendChild(pageSizeLabel); + + const centerWrap = document.createElement('div'); + centerWrap.className = 'nc-pagination-center'; + const centerSlot = document.createElement('div'); + centerSlot.className = 'nc-pagination-center-slot'; + centerSlot.dataset.ncPaginationCenterSlot = '1'; + centerWrap.appendChild(centerSlot); + + const btnContainer = document.createElement('div'); + btnContainer.className = 'nc-pagination-btns'; + + const buttonClass = 'nc-pagination-btn'; + const activeClass = 'nc-pagination-btn nc-pagination-btn-active'; + + const addButton = (labelHtml, targetPage, isActive, ariaLabel) => { + const btn = document.createElement('button'); + btn.type = 'button'; + btn.innerHTML = labelHtml; + btn.className = isActive ? activeClass : buttonClass; + if (ariaLabel) btn.setAttribute('aria-label', ariaLabel); + if (isActive) btn.setAttribute('aria-current', 'page'); + + const canGo = !isActive && targetPage >= 1 && targetPage <= pages && targetPage !== page; + if (canGo) { + btn.addEventListener('click', () => { + if (typeof onPageChange === 'function') onPageChange(targetPage, pageSize); + }); + } else if (!isActive) { + btn.disabled = true; + } + + btnContainer.appendChild(btn); + }; + + addButton(icons.first, 1, false, 'First page'); + addButton(icons.prev, page - 1, false, 'Previous page'); + + let start = Math.max(1, page - 2); + let end = start + 4; + if (end > pages) { + end = Math.max(1, pages); + start = Math.max(1, end - 4); + } + + const pageButtonCount = Math.min(5, pages); + for (let i = 0; i < pageButtonCount; i += 1) { + const targetPage = start + i; + addButton(String(targetPage), targetPage, targetPage === page, `Page ${targetPage}`); + } + + addButton(icons.next, page + 1, false, 'Next page'); + addButton(icons.last, pages, false, 'Last page'); + + container.appendChild(meta); + container.appendChild(centerWrap); + container.appendChild(btnContainer); + + container.dispatchEvent( + new CustomEvent('nc:pagination-rendered', { + bubbles: true, + detail: { + variant, + page, + pages, + total, + pageSize, + }, + }) + ); + } + + window.NCPagination = { render }; + window.NCPaginationTop = { + render(container, state, onPageChange) { + render(container, state, onPageChange, 'top'); + }, + }; + window.NCPaginationBottom = { + render(container, state, onPageChange) { + render(container, state, onPageChange, 'bottom'); + }, + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/navigation/redirect-home.js b/shared/packages/media-shared-assets/public/js/navigation/redirect-home.js new file mode 100644 index 0000000..912e50c --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/navigation/redirect-home.js @@ -0,0 +1,3 @@ +(() => { + window.location.replace('/'); +})(); diff --git a/shared/packages/media-shared-assets/public/js/theme/theme-toggle-footer.js b/shared/packages/media-shared-assets/public/js/theme/theme-toggle-footer.js new file mode 100644 index 0000000..e8f3b5e --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/theme/theme-toggle-footer.js @@ -0,0 +1,15 @@ +(() => { + const initThemeToggle = () => { + if (window.NCThemeToggle && typeof window.NCThemeToggle.init === 'function') { + window.NCThemeToggle.init(); + } + }; + + if (window.NCThemeToggle) { + initThemeToggle(); + return; + } + + document.addEventListener('DOMContentLoaded', initThemeToggle, { once: true }); + document.addEventListener('nc:componentsLoaded', initThemeToggle); +})(); diff --git a/shared/packages/media-shared-assets/public/js/theme/theme-toggle.js b/shared/packages/media-shared-assets/public/js/theme/theme-toggle.js new file mode 100644 index 0000000..a6a6234 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/theme/theme-toggle.js @@ -0,0 +1,106 @@ +(() => { + if (window.NCThemeToggle) return; + + const storageKey = 'app-theme-preference'; + const root = document.documentElement; + const boundButtons = new WeakSet(); + + function safeStorageGet(key) { + try { + return localStorage.getItem(key); + } catch { + return null; + } + } + + function safeStorageSet(key, value) { + try { + localStorage.setItem(key, value); + return true; + } catch { + return false; + } + } + + function getSystemTheme() { + if (typeof window.matchMedia === 'function') { + return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; + } + return 'dark'; + } + + function getCurrentTheme() { + const current = root.getAttribute('data-theme'); + if (current === 'light' || current === 'dark') return current; + return getSystemTheme(); + } + + function updateToggleButton(button, theme) { + if (!button) return; + button.textContent = theme === 'dark' ? '🌙' : '☀️'; + } + + function refreshAllToggleButtons(theme) { + document.querySelectorAll('#themeToggleBtn, [data-theme-toggle]').forEach(button => { + updateToggleButton(button, theme); + }); + } + + function applyTheme(theme) { + if (theme !== 'light' && theme !== 'dark') return; + root.setAttribute('data-theme', theme); + refreshAllToggleButtons(theme); + } + + function toggleTheme() { + const next = getCurrentTheme() === 'dark' ? 'light' : 'dark'; + safeStorageSet(storageKey, next); + applyTheme(next); + return next; + } + + function bindToggleButton(button) { + if (!button || boundButtons.has(button)) return; + boundButtons.add(button); + button.addEventListener('click', toggleTheme); + updateToggleButton(button, getCurrentTheme()); + } + + function init(options = {}) { + const selector = options.selector || '#themeToggleBtn, [data-theme-toggle]'; + const stored = safeStorageGet(storageKey); + applyTheme(stored || getCurrentTheme()); + document.querySelectorAll(selector).forEach(bindToggleButton); + } + + window.NCThemeToggle = { + applyTheme, + init, + storageKey, + toggleTheme, + }; + + document.addEventListener('DOMContentLoaded', () => init(), { once: true }); + document.addEventListener('nc:componentsLoaded', () => init()); + + if (typeof window.matchMedia === 'function') { + const mqDark = window.matchMedia('(prefers-color-scheme: dark)'); + const onSystemThemeChange = event => { + if (!safeStorageGet(storageKey)) { + applyTheme(event.matches ? 'dark' : 'light'); + } + }; + if (typeof mqDark.addEventListener === 'function') { + mqDark.addEventListener('change', onSystemThemeChange); + } else if (typeof mqDark.addListener === 'function') { + mqDark.addListener(onSystemThemeChange); + } + } + + window.addEventListener('storage', event => { + if (event.key !== storageKey) return; + if (event.newValue === 'light' || event.newValue === 'dark') { + applyTheme(event.newValue); + } + }); +})(); diff --git a/shared/packages/media-shared-assets/public/js/ui/confirm.js b/shared/packages/media-shared-assets/public/js/ui/confirm.js new file mode 100644 index 0000000..d2c28e8 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/ui/confirm.js @@ -0,0 +1,184 @@ +// Shared confirm dialog utility — matches the dark design language of the monorepo. +// Usage: const ok = await NCConfirm.show({ title, message, confirmLabel, cancelLabel, danger }); +// Returns a Promise: true = confirmed, false = cancelled. + +(function (global) { + if (global.NCConfirm) return; + + const DIALOG_ID = 'nc-confirm-dialog'; + + function ensureDialog() { + let dialog = document.getElementById(DIALOG_ID); + if (dialog) return dialog; + + dialog = document.createElement('div'); + dialog.id = DIALOG_ID; + dialog.setAttribute('role', 'dialog'); + dialog.setAttribute('aria-modal', 'true'); + dialog.setAttribute('hidden', ''); + dialog.style.display = 'none'; + // Backdrop + centering + dialog.className = 'fixed inset-0 z-[10100] flex items-center justify-center p-4'; + dialog.style.background = 'rgba(0,0,0,0.65)'; + dialog.style.backdropFilter = 'blur(2px)'; + + dialog.innerHTML = ` +
+

+

+
+ + +
+
+ `; + + document.body.appendChild(dialog); + return dialog; + } + + let _resolve = null; + let _lastActive = null; + + function focusables(dialog) { + return [ + ...dialog.querySelectorAll( + 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' + ), + ].filter(el => !el.disabled && el.offsetParent !== null); + } + + function onKeyDown(e) { + const dialog = document.getElementById(DIALOG_ID); + if (!dialog || dialog.style.display === 'none') return; + + if (e.key === 'Escape') { + e.preventDefault(); + close(false); + return; + } + + if (e.key === 'Tab') { + const els = focusables(dialog); + if (!els.length) return; + const first = els[0]; + const last = els[els.length - 1]; + if (e.shiftKey && document.activeElement === first) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault(); + first.focus(); + } + } + } + + function close(result) { + const dialog = document.getElementById(DIALOG_ID); + if (dialog) { + dialog.style.display = 'none'; + } + document.removeEventListener('keydown', onKeyDown); + if (_lastActive && typeof _lastActive.focus === 'function') { + try { + _lastActive.focus(); + } catch { + /* ignore */ + } + } + _lastActive = null; + if (_resolve) { + const r = _resolve; + _resolve = null; + r(result); + } + } + + function show({ + title = 'Confirm', + message = '', + confirmLabel = 'Confirm', + cancelLabel = 'Cancel', + danger = false, + } = {}) { + return new Promise(resolve => { + const dialog = ensureDialog(); + + document.getElementById('nc-confirm-title').textContent = title; + document.getElementById('nc-confirm-message').textContent = message; + document.getElementById('nc-confirm-cancel').textContent = cancelLabel; + + const okBtn = document.getElementById('nc-confirm-ok'); + okBtn.textContent = confirmLabel; + + // Danger vs primary style for confirm button + if (danger) { + okBtn.className = okBtn.className.replace(/focus:ring-\S+/g, 'focus:ring-red-500/50'); + okBtn.style.background = 'var(--color-danger-strong, #ef4444)'; + okBtn.onmouseover = () => { + okBtn.style.background = 'var(--color-danger-hover, #dc2626)'; + }; + okBtn.onmouseout = () => { + okBtn.style.background = 'var(--color-danger-strong, #ef4444)'; + }; + } else { + okBtn.style.background = 'var(--color-action, #2563eb)'; + okBtn.onmouseover = () => { + okBtn.style.background = 'var(--color-action-hover, #1d4ed8)'; + }; + okBtn.onmouseout = () => { + okBtn.style.background = 'var(--color-action, #2563eb)'; + }; + // Reset ring class in case it was set to danger previously + const cls = okBtn.className; + if (!cls.includes('focus:ring-blue')) { + okBtn.className = cls.replace(/focus:ring-\S+/g, 'focus:ring-blue-300/50'); + } + } + + // Wire up resolve + _resolve = resolve; + _lastActive = document.activeElement; + + // Re-attach listeners (removes stale ones first) + const cancelBtn = document.getElementById('nc-confirm-cancel'); + const freshCancel = cancelBtn.cloneNode(true); + cancelBtn.parentNode.replaceChild(freshCancel, cancelBtn); + const freshOk = okBtn.cloneNode(true); + okBtn.parentNode.replaceChild(freshOk, okBtn); + + // Re-query after replacement + document.getElementById('nc-confirm-cancel').addEventListener('click', () => close(false)); + document.getElementById('nc-confirm-ok').addEventListener('click', () => close(true)); + + document.addEventListener('keydown', onKeyDown); + + dialog.style.display = ''; + // Move focus to confirm button after paint + setTimeout(() => { + const btn = document.getElementById('nc-confirm-ok'); + if (btn) btn.focus(); + }, 10); + }); + } + + global.NCConfirm = { show }; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/ui/overlay.js b/shared/packages/media-shared-assets/public/js/ui/overlay.js new file mode 100644 index 0000000..dd7b003 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/ui/overlay.js @@ -0,0 +1,142 @@ +// Shared overlay + live region utilities +// Pattern centralization to avoid repetition across admin pages. +// Usage: const ov = createOverlayController({ overlayId:'mediaOverlay', liveId:'mediaLive', showDelay:250 }); +// Then ov.runWithOverlay(async ()=> { ...loading work... }); +// Provide announce(msg) for polite updates and announceError(msg) for errors (also logs console + optional toast). + +(function (global) { + function createOverlayController({ + overlayId, + liveId, + showDelay = 250, + toast, + focusSelector, + restoreFocus = true, + escToClose = true, + trapFocus = true, + } = {}) { + const overlay = document.getElementById(overlayId); + const live = document.getElementById(liveId); + let timer; + let lastActive = null; + function moveFocusIn() { + if (!overlay) return; + let target = null; + if (focusSelector) { + target = overlay.querySelector(focusSelector); + } + if (!target) { + // find first focusable + target = overlay.querySelector( + 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' + ); + } + if (target && typeof target.focus === 'function') { + try { + target.focus(); + } catch { + /* ignore focus error */ + } + } + } + function showSoon() { + clearTimeout(timer); + timer = setTimeout(() => { + if (!overlay) return; + if (restoreFocus) { + lastActive = document.activeElement; + } + if (!overlay.getAttribute('role')) overlay.setAttribute('role', 'dialog'); + overlay.setAttribute('aria-modal', 'true'); + overlay.removeAttribute('hidden'); + overlay.classList.add('is-active'); + overlay.setAttribute('aria-hidden', 'false'); + console.info('[ACTION] overlay_show', overlayId); + // Slight defer to allow rendering + setTimeout(moveFocusIn, 10); + }, showDelay); + } + function hide() { + clearTimeout(timer); + if (!overlay) return; + overlay.classList.remove('is-active'); + overlay.setAttribute('aria-hidden', 'true'); + overlay.setAttribute('hidden', ''); + console.info('[ACTION] overlay_hide', overlayId); + if (restoreFocus && lastActive && typeof lastActive.focus === 'function') { + try { + lastActive.focus(); + } catch { + /* ignore */ + } + lastActive = null; + } + } + function onKey(e) { + if (!overlay || overlay.hasAttribute('hidden')) return; + if (e.key === 'Escape' && escToClose) { + // Attempt to refocus original trigger immediately after hiding + const trigger = lastActive; + hide(); + if (trigger && typeof trigger.focus === 'function') { + try { + trigger.focus(); + } catch { + /* ignore */ + } + } + return; + } + if (trapFocus && e.key === 'Tab') { + const focusables = [ + ...overlay.querySelectorAll( + 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' + ), + ].filter(el => !el.disabled && el.offsetParent !== null); + if (focusables.length) { + const first = focusables[0]; + const last = focusables[focusables.length - 1]; + if (e.shiftKey && document.activeElement === first) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault(); + first.focus(); + } + } + } + } + document.addEventListener('keydown', onKey); + function announce(msg) { + if (live) { + live.textContent = msg; + } + } + function announceError(msg) { + if (live) { + live.textContent = msg; + } + if (toast && toast.error) { + toast.error(msg); + } + console.error('[OVERLAY_ERROR]', msg); + } + async function runWithOverlay(fn) { + showSoon(); + try { + const r = await fn(); + hide(); + return r; + } catch (e) { + hide(); + announceError(e.message || 'Load failed'); + throw e; + } + } + function destroy() { + document.removeEventListener('keydown', onKey); + } + return { showSoon, hide, announce, announceError, runWithOverlay, destroy }; + } + global.NCOverlay = { createOverlayController }; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/ui/progress-bar.js b/shared/packages/media-shared-assets/public/js/ui/progress-bar.js new file mode 100644 index 0000000..138f657 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/ui/progress-bar.js @@ -0,0 +1,133 @@ +// NCProgressBar - shared horizontal progress bar component +// Served at /shared/js/ui/progress-bar.js by applySharedBase. +// +// The 'progress-shimmer' CSS class (defined in index.css) drives the animated +// gradient fill used during indeterminate/in-progress states. +// +// API: +// const {track, fill} = NCProgressBar.create([opts]) -> builds DOM pair (NOT inserted) +// NCProgressBar.set(fill, pct, [opts]) -> set fill to pct (0-100); opts.shimmer=bool +// NCProgressBar.setShimmer(fill, on) -> add/remove 'progress-shimmer' class +// +// create() opts: +// height : CSS height utility class from index.css (default 'h-2') +// rounded : CSS rounded utility class from index.css (default 'rounded-full') +// trackClass : CSS bg utility class for the track (default 'bg-slate-800') +// fillClass : CSS bg utility class for the fill (default 'bg-[var(--color-action)]') +// shimmer : bool - start with shimmer on (default false) + +(function (global) { + 'use strict'; + + /** + * Build a progress-bar track+fill pair without inserting into DOM. + * @param {object} [opts] + * @returns {{ track: HTMLElement, fill: HTMLElement }} + */ + function create(opts) { + opts = opts || {}; + var height = opts.height || 'h-2'; + var rounded = opts.rounded || 'rounded-full'; + var trackCls = opts.trackClass || 'bg-slate-800'; + var fillCls = opts.fillClass || 'bg-[var(--color-action)]'; + var shimmer = !!opts.shimmer; + + var track = document.createElement('div'); + track.className = [height, rounded, trackCls, 'overflow-hidden'].join(' '); + + var fill = document.createElement('div'); + fill.className = ['h-full', rounded, fillCls, 'transition-[width]', 'duration-300'].join(' '); + if (shimmer) fill.classList.add('progress-shimmer'); + fill.style.width = '0%'; + + track.appendChild(fill); + return { track: track, fill: fill }; + } + + /** + * Toggle the shimmer animation on a fill element. + * @param {Element} fillEl + * @param {boolean} on + */ + function setShimmer(fillEl, on) { + if (!fillEl) return; + if (on) fillEl.classList.add('progress-shimmer'); + else fillEl.classList.remove('progress-shimmer'); + } + + /** + * Set the fill width percentage (clamped 0-100). + * @param {Element} fillEl + * @param {number} pct 0-100 + * @param {object} [opts] opts.shimmer - if boolean, also toggle shimmer + */ + function set(fillEl, pct, opts) { + if (!fillEl) return; + var clamped = Math.max(0, Math.min(100, Number(pct) || 0)); + fillEl.style.width = clamped + '%'; + if (opts && typeof opts.shimmer === 'boolean') setShimmer(fillEl, opts.shimmer); + } + + /** + * Renders a highly styled processing progress bar into the specified container. + * Useful for showing download or generation progress with a label. + * @param {HTMLElement} container - DOM element to render into + * @param {object} [opts] - opts.barId, opts.labelId, opts.metaId, opts.statusDotId, opts.statusTextId, opts.statusText + */ + function renderProcessingContainer(container, opts) { + if (!container) return; + opts = opts || {}; + var barId = opts.barId || 'processingProgressBar'; + var labelId = opts.labelId || 'processingProgressLabel'; + var metaId = opts.metaId || ''; + var statusDotId = opts.statusDotId || ''; + var statusTextId = opts.statusTextId || ''; + var statusText = opts.statusText || 'ComfyUI: checking\u2026'; + + var metaHtml = metaId + ? '
' + : ''; + + var barTrackHtml = `
+
+
+ Idle +
+
`; + + var statusHtml = statusDotId + ? `
+ + ${statusText} +
` + : ''; + + var innerHtml = statusDotId + ? `
${barTrackHtml}${statusHtml}
` + : barTrackHtml; + + container.innerHTML = ` +
+
+ ${innerHtml} + ${metaHtml} +
+
+ `; + } + + global.NCProgressBar = { + create: create, + set: set, + setShimmer: setShimmer, + renderProcessingContainer: renderProcessingContainer, + }; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/ui/spinner.js b/shared/packages/media-shared-assets/public/js/ui/spinner.js new file mode 100644 index 0000000..7ee8f7b --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/ui/spinner.js @@ -0,0 +1,122 @@ +// NCSpinner - shared circular loading spinner component +// Served at /shared/js/ui/spinner.js by applySharedBase. +// +// API: +// NCSpinner.create([opts]) -> returns wrapper element (not inserted into DOM) +// NCSpinner.show(container, [opts]) -> inserts full-area overlay spinner; returns element +// NCSpinner.hide(el) -> removes element from DOM safely +// +// opts: +// size : 'sm'|'md'|'lg'|'xl' - maps to CSS utility class pairs in index.css (default 'lg') +// color : CSS text-color utility class from index.css (default 'text-slate-400') +// label : accessible label string (default 'Loading...') +// text : visible text string displayed below the spinner (default none) +// id : optional id attribute on the wrapper +// overlay : bool - if true (default), wrapper fills its positioned parent absolutely + +(function (global) { + 'use strict'; + + var SIZES = { sm: 'h-8 w-8', md: 'h-10 w-10', lg: 'h-12 w-12', xl: 'h-16 w-16' }; + var SVG_NS = 'http://www.w3.org/2000/svg'; + + function makeSvg(sizeClass, color) { + var svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('class', 'animate-spin ' + sizeClass + ' ' + color); + svg.setAttribute('fill', 'none'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + + var circle = document.createElementNS(SVG_NS, 'circle'); + circle.setAttribute('class', 'opacity-25'); + circle.setAttribute('cx', '12'); + circle.setAttribute('cy', '12'); + circle.setAttribute('r', '10'); + circle.setAttribute('stroke', 'currentColor'); + circle.setAttribute('stroke-width', '4'); + svg.appendChild(circle); + + var path = document.createElementNS(SVG_NS, 'path'); + path.setAttribute('class', 'opacity-75'); + path.setAttribute('fill', 'currentColor'); + path.setAttribute('d', 'M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z'); + svg.appendChild(path); + + return svg; + } + + /** + * Create a spinner wrapper element without inserting it. + * @param {object} [opts] + * @returns {HTMLElement} + */ + function create(opts) { + opts = opts || {}; + var size = opts.size || 'md'; + var color = opts.color || 'text-slate-400'; + var label = opts.label || 'Loading\u2026'; + var text = opts.text || ''; + var extraCls = opts.wrapClass || ''; + + var sizeClass = SIZES[size] || size; + + var wrap = document.createElement('div'); + var flexDir = text ? 'flex-col gap-3 ' : ''; + wrap.className = ( + 'pointer-events-none flex ' + + flexDir + + 'items-center justify-center ' + + extraCls + ).trim(); + wrap.setAttribute('role', 'status'); + wrap.setAttribute('aria-label', label); + wrap.appendChild(makeSvg(sizeClass, color)); + + if (text) { + var textEl = document.createElement('div'); + textEl.className = + 'text-xs font-semibold uppercase tracking-[0.5px] text-[var(--color-text-dim)]'; + textEl.textContent = text; + wrap.appendChild(textEl); + } + + return wrap; + } + + /** + * Insert an overlay spinner as a child of `container` (defaults to document.body). + * @param {Element|null} container + * @param {object} [opts] + * @returns {HTMLElement} the inserted element + */ + function show(container, opts) { + opts = opts || {}; + var overlay = opts.overlay !== false; + var wrapClass = overlay ? 'absolute inset-0 z-10' : ''; + + var el = create({ + size: opts.size || 'lg', + color: opts.color || 'text-slate-400', + label: opts.label || 'Loading\u2026', + text: opts.text || '', + wrapClass: wrapClass, + }); + + if (opts.id) el.id = opts.id; + (container || document.body).appendChild(el); + return el; + } + + /** + * Remove a spinner element previously returned by show(). + * @param {Element|null} el + */ + function hide(el) { + try { + if (el && el.parentNode) el.parentNode.removeChild(el); + // eslint-disable-next-line no-empty + } catch {} + } + + global.NCSpinner = { create: create, show: show, hide: hide }; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/ui/toast.js b/shared/packages/media-shared-assets/public/js/ui/toast.js new file mode 100644 index 0000000..3360694 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/ui/toast.js @@ -0,0 +1,73 @@ +(function () { + if (window.toast) return; + const rootId = 'toast-root'; + function ensureRoot() { + let el = document.getElementById(rootId); + if (!el) { + el = document.createElement('div'); + el.id = rootId; + el.setAttribute('data-toast-root', '1'); + el.className = + 'fixed right-3 z-[10050] flex w-[min(340px,calc(100vw-1.5rem))] flex-col gap-2 hidden'; + el.style.top = 'calc(var(--bar-height, 56px) + 0.75rem)'; + document.body.appendChild(el); + } + return el; + } + function create(type, message, opts = {}) { + const root = ensureRoot(); + const ttl = opts.duration ?? 4800; + const title = + opts.title || + { info: 'Info', success: 'Success', warn: 'Warning', error: 'Error' }[type] || + 'Notice'; + const accent = + { + info: 'var(--color-info)', + success: 'var(--color-success)', + warn: 'var(--color-warning)', + error: 'var(--color-danger)', + }[type] || 'var(--color-accent)'; + const el = document.createElement('div'); + el.setAttribute('data-toast-item', '1'); + el.className = + 'relative isolate flex items-start gap-3 overflow-hidden rounded-md border border-[var(--color-border)] border-l-4 bg-[var(--color-surface)] px-4 py-3 text-[var(--font-size-sm)] leading-[1.3] text-[var(--color-text)] shadow-[var(--shadow-lg)]'; + el.style.setProperty('--_accent', accent); + el.style.borderLeftColor = 'var(--_accent)'; + el.setAttribute('role', 'status'); + el.setAttribute('aria-live', 'polite'); + el.innerHTML = `

${title}

${message}
`; + el.style.setProperty('--toast-ttl', `${ttl}ms`); + const progress = el.querySelector('[data-toast-progress]'); + if (progress) { + progress.className = + 'absolute bottom-0 left-0 h-[3px] w-full origin-left bg-[var(--_accent)]'; + progress.style.animation = 'toast-progress linear forwards'; + progress.style.animationDuration = `${ttl}ms`; + } + const closeBtn = el.querySelector('[data-toast-close]'); + let closed = false; + function remove() { + if (closed) return; + closed = true; + el.style.animation = 'toast-out .35s forwards'; + setTimeout(() => { + el.remove(); + if (root.childElementCount === 0) root.classList.add('hidden'); + }, 340); + } + closeBtn.addEventListener('click', remove); + if (ttl > 0) { + setTimeout(remove, ttl); + } + root.classList.remove('hidden'); + root.appendChild(el); + return { remove }; + } + window.toast = { + info: (m, o) => create('info', m, o), + success: (m, o) => create('success', m, o), + warn: (m, o) => create('warn', m, o), + error: (m, o) => create('error', m, o), + }; +})(); diff --git a/shared/packages/media-shared-assets/public/js/utils/clientLogger.js b/shared/packages/media-shared-assets/public/js/utils/clientLogger.js new file mode 100644 index 0000000..58005e2 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/utils/clientLogger.js @@ -0,0 +1,23 @@ +(function (global) { + if (global.ClientLogger) return; // singleton + const PREFIX = '[Client]'; + const isDebug = () => { + try { + return localStorage.getItem('clientDebug'); + } catch { + return false; + } + }; + const ts = () => new Date().toISOString(); + const fmt = (level, args) => [ts(), PREFIX, level + ':', ...args]; + const api = { + log: (...a) => console.log(...fmt('LOG', a)), + info: (...a) => console.info(...fmt('INFO', a)), + warn: (...a) => console.warn(...fmt('WARN', a)), + error: (...a) => console.error(...fmt('ERR', a)), + debug: (...a) => { + if (isDebug()) console.debug(...fmt('DBG', a)); + }, + }; + global.ClientLogger = api; +})(window); diff --git a/shared/packages/media-shared-assets/public/js/utils/debounce.js b/shared/packages/media-shared-assets/public/js/utils/debounce.js new file mode 100644 index 0000000..a0db7f5 --- /dev/null +++ b/shared/packages/media-shared-assets/public/js/utils/debounce.js @@ -0,0 +1,147 @@ +// Shared debounce utility (ESM) +// Usage: const debounced = debounce(fn, 150, { leading:true, trailing:true }); +// debounced.cancel() / debounced.flush() +/** + * Debounce a function so it only executes after `wait` ms have elapsed since the last call. + * Supports immediate (leading) invocation, trailing invocation, and an optional maxWait + * that guarantees the function is invoked no later than the max wait even under continual calls. + * + * Typical usage: + * const d = debounce(expensiveFn, 150, { leading: true, trailing: true, maxWait: 500 }); + * element.addEventListener('input', e => d(e.target.value)); + * + * Returned debounced function API: + * d.cancel() -> clears any pending invocation and resets state. + * d.flush() -> immediately invokes pending trailing call (if any) and returns its result. + * d.pending() -> boolean indicating if a timer is active. + * + * Option semantics: + * leading (boolean, default false) - invoke on the first call of a burst. + * trailing (boolean, default true) - invoke after burst settles. If both leading & trailing + * are true the function can fire twice per burst (start & end). + * maxWait (number, >= wait) - maximum time allowed before forcing an invoke while calls + * continue. Ensures periodic execution for rapid streams. + * + * Edge details: + * - If leading is true and trailing is false the function fires immediately on first call then + * suppresses further calls until inactivity >= wait. + * - If leading is false and trailing true (default) it behaves like a classic debounce. + * - maxWait only matters when there is a continuous series of calls preventing the trailing + * timer from expiring; once exceeded it forces an invocation and the cycle restarts. + * - cancel() clears all stored arguments; flush() ignores leading semantics and only processes + * a pending trailing invocation. + * + * @template {(...args: any[]) => any} F + * @param {F} fn Function to debounce. + * @param {number} [wait=100] Base wait interval in milliseconds. + * @param {{ leading?: boolean; trailing?: boolean; maxWait?: number }} [options] + * @returns {F & { cancel():void; flush():ReturnType; pending():boolean }} + */ +export function debounce(fn, wait = 100, options = {}) { + if (typeof fn !== 'function') throw new TypeError('Expected function'); + let timer = null; + let lastArgs; + let lastThis; + let result; + let lastInvoke = 0; + const leading = options.leading === true; + const trailing = options.trailing !== false; // default true + const maxWait = typeof options.maxWait === 'number' ? Math.max(options.maxWait, wait) : null; + let lastCallTime = 0; // tracks latest call to debounced wrapper + + function invoke(now) { + lastInvoke = now; + const args = lastArgs; + const ctx = lastThis; + lastArgs = lastThis = undefined; + result = fn.apply(ctx, args); + return result; + } + + function startTimer(pending, ms) { + if (timer) clearTimeout(timer); + timer = setTimeout(pending, ms); + } + + function remainingWait(now) { + const sinceLastInvoke = now - lastInvoke; + const sinceLastCall = now - lastCallTime; + const timeWaiting = wait - sinceLastCall; + return maxWait != null ? Math.min(timeWaiting, maxWait - sinceLastInvoke) : timeWaiting; + } + + function shouldInvoke(now) { + if (lastArgs === undefined) return false; + const sinceLastCall = now - lastCallTime; + const sinceLastInvoke = now - lastInvoke; + if (sinceLastCall < 0) return true; // clock skew + if (sinceLastCall >= wait) return true; + return maxWait != null && sinceLastInvoke >= maxWait; + } + + function trailingEdge(now) { + timer = null; + if (trailing && lastArgs) return invoke(now); + lastArgs = lastThis = undefined; + return result; + } + + function timerExpired() { + const now = Date.now(); + if (shouldInvoke(now)) return trailingEdge(now); + startTimer(timerExpired, remainingWait(now)); + } + + function leadingInvoke(now) { + if (leading) { + result = invoke(now); + } + startTimer(timerExpired, wait); // schedule trailing check + return result; + } + + function debounced(...args) { + lastCallTime = Date.now(); + lastArgs = args; + lastThis = this; + const now = lastCallTime; + const invokeNow = shouldInvoke(now); + + if (!timer) { + // First call: optionally invoke leading immediately + return leadingInvoke(now); + } + + if (invokeNow) { + if (maxWait != null) { + // Max wait reached or standard wait elapsed with continuous calls + startTimer(timerExpired, wait); // restart timer for trailing sequence + return invoke(now); + } + } + + // Reschedule timer to ensure trailing fires after remaining wait + const timeLeft = remainingWait(now); + startTimer(timerExpired, timeLeft); + return result; + } + + debounced.cancel = function () { + if (timer) clearTimeout(timer); + timer = null; + lastArgs = lastThis = undefined; + lastCallTime = 0; + }; + debounced.flush = function () { + if (!timer) return result; + return trailingEdge(Date.now()); + }; + debounced.pending = () => !!timer; + return debounced; +} + +if (typeof window !== 'undefined') { + window.debounce = debounce; +} + +export default debounce; diff --git a/shared/packages/media-shared-assets/scripts/build-theme-css.mjs b/shared/packages/media-shared-assets/scripts/build-theme-css.mjs new file mode 100644 index 0000000..d5c9f0e --- /dev/null +++ b/shared/packages/media-shared-assets/scripts/build-theme-css.mjs @@ -0,0 +1,20 @@ +/** + * build-theme-css.mjs + * + * index.css is now a static file — no Tailwind build step is needed. + * This script simply syncs MediaShared/public/css/index.css to + * MediaDesktop/public/index.css (the Electron bundle copy). + */ +import fs from 'fs/promises'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const repoRoot = path.resolve(__dirname, '..', '..'); + +const sourcePath = path.join(repoRoot, 'MediaShared', 'public', 'css', 'index.css'); +const desktopPath = path.join(repoRoot, 'MediaDesktop', 'public', 'index.css'); + +await fs.copyFile(sourcePath, desktopPath); +console.log('Synced MediaShared/public/css/index.css → MediaDesktop/public/index.css'); diff --git a/shared/scripts/sync-consumers.ps1 b/shared/scripts/sync-consumers.ps1 index 50bcea5..596e789 100644 --- a/shared/scripts/sync-consumers.ps1 +++ b/shared/scripts/sync-consumers.ps1 @@ -26,7 +26,8 @@ $consumerProjects = @( 'Original/InfiniteVideo', 'Forks/MegaBasterd', 'Forks/HordeWorker', - 'Original/OutdoorGames' + 'Original/OutdoorGames', + 'Original/MediaEngine' ) function Invoke-GitText { @@ -192,7 +193,19 @@ if ([string]::IsNullOrWhiteSpace($SourceRepository)) { $sourceRoot = Resolve-FullPath $SourceRepository $sourceRepositoryRoot = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('rev-parse', '--show-toplevel') | Select-Object -First 1).Trim() $sourceRoot = Resolve-FullPath $sourceRepositoryRoot + +# The workspace root is the ancestor directory that contains both 'Original' +# and 'Forks' (every consumer project lives under one of those). Walk up from +# the shared repo instead of assuming a fixed nesting depth, since shared/ has +# moved before (e.g. Web/shared -> Web/Central/shared) and may move again. $workspaceRoot = Split-Path -Parent $sourceRoot +while ($workspaceRoot -and -not ((Test-Path -LiteralPath (Join-Path $workspaceRoot 'Original') -PathType Container) -and (Test-Path -LiteralPath (Join-Path $workspaceRoot 'Forks') -PathType Container))) { + $parent = Split-Path -Parent $workspaceRoot + if (-not $parent -or $parent -eq $workspaceRoot) { + throw "Could not locate the workspace root (a directory containing both 'Original' and 'Forks') above $sourceRoot." + } + $workspaceRoot = $parent +} $sourceCommit = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('rev-parse', '--short', 'HEAD') | Select-Object -First 1).Trim() $sourceFiles = @(Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('ls-files') | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })