Compare commits

...
22 Commits
Author SHA1 Message Date
traberphandClaude Opus 5.5 b338e1abb4 Use a minimal Alpine runtime image without npm
The node:24-slim image had 262 known vulnerabilities (Trivy), almost
all in Debian system packages, plus 21 in the npm bundled with Node.
None were in the app's own dependencies. The runtime now uses
node:24-alpine with npm, npx, corepack and yarn removed and Alpine
security updates applied: 0 known vulnerabilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:34:49 +02:00
traberphandClaude Opus 5.5 95c27e7353 Update GitHub Actions to their Node 24 versions
Node 20 is deprecated on GitHub runners. All inputs used here are
unchanged in the new major versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:26:41 +02:00
traberphandClaude Opus 5.5 8b7d83aa14 Publish to registry.traberph.de/public/short
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:22:14 +02:00
traberphandClaude Opus 5.5 26c17228f8 Also publish the Docker image to registry.traberph.de
Uses the REGISTRY_USERNAME and REGISTRY_TOKEN secrets; the image is
registry.traberph.de/traberph/short with the same tags as on GHCR and
Docker Hub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:53:05 +02:00
traberphandClaude Opus 5.5 3dc2c28330 Review fixes: forwarded IP, sign-in errors, revoking access
- take the visitor IP from the last X-Forwarded-For entry (the one
  the proxy adds); the first can be set by the client to fake unique
  visitors
- show "Sign-in failed" with a retry link when the identity provider
  rejects the callback instead of a generic 500 page
- report concurrent unique-constraint conflicts (e.g. two requests
  claiming the same shortcode) as 409 instead of 500
- admins can revoke a user's access (end sessions, delete API tokens)
  from Administration; previously a removed user kept working tokens
- README: security notes on the proxy header, offboarding and rate
  limiting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:49:30 +02:00
traberphandClaude Opus 5.5 00f5fe1f33 Open a link button's short link from the content tab
Link blocks get an arrow button, and their path becomes a link, both
leading to the short link's own page (analytics, QR code, settings).
Block targets now include their namespace so other users' links open
under Administration. The Link component accepts all anchor attributes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:36:03 +02:00
traberphandClaude Opus 5.5 5f30a6d448 Remove the built-in "Colourful" palettes
Users import their own palettes from coolors.co, so the four built-in
ones aren't needed. The usage hint moved to "Your palettes"; the
palette mapping tests keep the four palettes as sample data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:33:13 +02:00
traberphandClaude Opus 5.5 50dfdf53b9 Show which link pages use a short link
Page summaries include `usedOn` (the link pages with a button to the
short link). The short link list shows it as a badge next to the
path: "on /home" for one page, "on 2 pages" for several, with all
paths in the tooltip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:26:15 +02:00
traberphandClaude Opus 5.5 6d427db2c4 Choose a palette's dark or light version from a dropdown
The two thumbnail buttons on each palette card are replaced by a menu
on the card's name row, like the one for single colors: "Dark
background" and "Light background", each with a small preview. The
active version is shown next to the name. Both menus now share one
popover component.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:22:09 +02:00
traberphandClaude Opus 5.5 03fb4dcf0c List short links before link pages, matching the sidebar
On the admin user screen the sections were reversed, and the create
buttons on that screen and the overview put link pages first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:16:50 +02:00
traberphandClaude Opus 5.5 ab2150330a Show website logos and the logo.dev credit in the appearance preview
The preview of unsaved changes now draws button icons like the public
page: website logos when logos are enabled, the first letter when
not, plus the "Logos provided by Logo.dev" credit. /me exposes the
publishable logo.dev key for this (it's already part of every public
logo URL).

Also fixes the sticky phone preview on the content and appearance
tabs, which scrolled away because its column was only as tall as the
phone itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:00:28 +02:00
traberphandClaude Opus 5.5 3eea5c23ef Rename the trending palettes section to "Colourful"
The palettes are a snapshot and don't follow coolors.co's trending
list, so the heading no longer claims they do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:58:38 +02:00
traberphandClaude Opus 5.5 26d2883935 Link to the coolors.co palette explorer instead of the generator
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:56:33 +02:00
traberphandClaude Opus 5.5 767290e1b5 Replace the palette dark/light toggle with per-palette thumbnails
The global "Dark background / Light background" switch sat in the
trending header but also affected saved palettes and meant nothing
for single colors. Each palette now shows two small page thumbnails
(dark and light version) that apply exactly what they show; the
selected one is highlighted, and editing a single color deselects it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:56:27 +02:00
traberphandClaude Opus 5.5 35cb7da929 Separate admins' own content from managing other users
- Short links, Link pages and Overview now show only the admin's own
  namespace and root; other users' content moved to Administration
- Administration lists users with their link/page/click counts; each
  opens /~/admin/users/<name> with that user's pages and links and
  lets admins create content in their namespace
- other users' pages open under /~/admin/users/<name>/…, keep the
  Administration section active and link back to the user
- one PageTable component for all lists, so search and the namespace
  filter (All / mine / Root, admins only) behave the same everywhere
- the create dialog offers admins only their own namespace and root;
  the existing-link picker groups links by namespace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:52:22 +02:00
traberphandClaude Opus 5.5 e44e56fd2d Save imported palettes per user and assign single palette colors
- imported coolors.co palettes are stored per user (new palettes
  table, GET/POST/DELETE /palettes, duplicates ignored, max 50) and
  listed under "Your palettes" with a remove button
- clicking a single color of any palette opens a menu to use it as
  background, text, buttons or button text; the name row still
  applies the whole palette
- theme picker moved into its own component

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:46:36 +02:00
traberphandClaude Opus 5.5 c3640c8966 Create short links directly from the link button dialog
The "Add link button" dialog can now either pick an existing short
link or create a new one (destination + optional shortcode) in the
page's namespace. The block API accepts `newLink` as an alternative
to `targetId`; link and button are created in one transaction, so a
failed request leaves nothing behind. Field errors such as a taken
shortcode are shown inline, and the label is suggested from the
destination's hostname.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:37:50 +02:00
traberphandClaude Opus 5.5 55d2b9433f Let page owners turn logo.dev logos on and off
Link pages get a "Website logos" switch on the appearance tab
(stored as pages.show_logos, default on). When off, buttons show
the letter placeholder and the logo.dev credit is hidden. The switch
is disabled with a hint when the server has no LOGO_DEV_TOKEN, which
/me now reports as `logoDev`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:31:56 +02:00
traberphandClaude Opus 5.5 624517e010 Add dark/light mode toggle and coolors.co palettes
Admin UI:
- system / light / dark switch in the sidebar (cycle button on
  mobile), stored in localStorage and applied before first paint
- dark mode now driven by data-theme instead of only the media query

Link page themes:
- keep the Midnight and Paper presets, replace the others with the
  4 trending palettes from coolors.co
- paste a coolors.co link (or a bare hex list) to use any palette;
  the colors are read from the URL, nothing is fetched
- palettes are mapped to background, text and button colors by
  contrast, with a dark/light background choice

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:27:21 +02:00
traberphandClaude Opus 5.5 74ce76ab8b Keep link page footer at the bottom of the screen
On pages with little content the "powered by" footer floated in the
middle of the screen. The page column now fills the viewport and the
footer is pushed to the bottom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:09:57 +02:00
traberphandGitHub 8998e0e0e1 Merge pull request #7 from traberph/v2
Allow renaming shortcodes
2026-10-14 16:04:42 +02:00
traberphandClaude Opus 5.5 90cc10de10 Allow renaming shortcodes
Shortcodes can now be changed via PATCH /pages/:id with the same
validation as on create (format, collisions, reserved root codes,
usernames). Stats, link buttons and the homepage pin follow the page.

The settings tab shows a warning while editing and asks for
confirmation, since the old URL stops working immediately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:02:52 +02:00
48 changed files with 3288 additions and 392 deletions
+19 -9
View File
@@ -13,14 +13,16 @@ env:
DOCKER_HUB_REGISTRY: docker.io DOCKER_HUB_REGISTRY: docker.io
IMAGE_NAME: ${{ github.repository }} IMAGE_NAME: ${{ github.repository }}
DOCKER_HUB_IMAGE_NAME: traberph/short DOCKER_HUB_IMAGE_NAME: traberph/short
PRIVATE_REGISTRY: registry.traberph.de
PRIVATE_IMAGE_NAME: public/short
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v7
- uses: pnpm/action-setup@v4 - uses: pnpm/action-setup@v6
- uses: actions/setup-node@v4 - uses: actions/setup-node@v7
with: with:
node-version: 24 node-version: 24
cache: pnpm cache: pnpm
@@ -39,39 +41,47 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v7
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v4
- name: Log in to GitHub Container Registry - name: Log in to GitHub Container Registry
uses: docker/login-action@v3 uses: docker/login-action@v4
with: with:
registry: ${{ env.REGISTRY }} registry: ${{ env.REGISTRY }}
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub - name: Log in to Docker Hub
uses: docker/login-action@v3 uses: docker/login-action@v4
with: with:
registry: ${{ env.DOCKER_HUB_REGISTRY }} registry: ${{ env.DOCKER_HUB_REGISTRY }}
username: ${{ secrets.DOCKERHUB_USERNAME }} username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Log in to registry.traberph.de
uses: docker/login-action@v4
with:
registry: ${{ env.PRIVATE_REGISTRY }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Extract metadata for Docker - name: Extract metadata for Docker
id: meta id: meta
uses: docker/metadata-action@v5 uses: docker/metadata-action@v6
with: with:
images: | images: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
${{ env.DOCKER_HUB_REGISTRY }}/${{ env.DOCKER_HUB_IMAGE_NAME }} ${{ env.DOCKER_HUB_REGISTRY }}/${{ env.DOCKER_HUB_IMAGE_NAME }}
${{ env.PRIVATE_REGISTRY }}/${{ env.PRIVATE_IMAGE_NAME }}
tags: | tags: |
type=semver,pattern={{version}} type=semver,pattern={{version}}
type=semver,pattern={{major}} type=semver,pattern={{major}}
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/heads/main') }} type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/heads/main') }}
- name: Build and push Docker images - name: Build and push Docker images
uses: docker/build-push-action@v5 uses: docker/build-push-action@v7
with: with:
context: . context: .
push: true push: true
+7 -2
View File
@@ -1,4 +1,4 @@
FROM node:24-slim AS base FROM node:24-alpine AS base
WORKDIR /app WORKDIR /app
RUN corepack enable RUN corepack enable
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
@@ -11,7 +11,12 @@ RUN pnpm build
FROM base AS prod-deps FROM base AS prod-deps
RUN pnpm install --frozen-lockfile --prod RUN pnpm install --frozen-lockfile --prod
FROM node:24-slim AS runner FROM node:24-alpine AS runner
# The app only needs the node binary. npm, npx, corepack and yarn ship with the base image and carry
# most of its known vulnerabilities, so they're removed; pending Alpine security updates are applied.
RUN apk upgrade --no-cache \
&& rm -rf /usr/local/lib/node_modules /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \
/usr/local/bin/yarn /usr/local/bin/yarnpkg /opt/yarn-*
WORKDIR /app WORKDIR /app
ENV NODE_ENV=production \ ENV NODE_ENV=production \
PORT=3000 \ PORT=3000 \
+13 -5
View File
@@ -2,12 +2,12 @@
A small self-hosted URL shortener and link-page tool for a handful of people, with login through Authentik (OIDC). A small self-hosted URL shortener and link-page tool for a handful of people, with login through Authentik (OIDC).
- **Short links**: `/<code>` for admins, `/<username>/<code>` for everyone else. Codes can be custom or random, and destinations can be edited later. - **Short links**: `/<code>` for admins, `/<username>/<code>` for everyone else. Codes can be custom or random, and both codes and destinations can be edited later.
- **Link pages**: a "link in bio" page with avatar, link buttons, Markdown text blocks and custom colours. Blocks are reordered by drag and drop. - **Link pages**: a "link in bio" page with avatar, link buttons, Markdown text blocks and colour themes, including palettes imported from [coolors.co](https://coolors.co). Blocks are reordered by drag and drop.
- **QR codes**: choose the error correction level and colours, then download as PNG or SVG. - **QR codes**: choose the error correction level and colours, then download as PNG or SVG.
- **Privacy-friendly stats**: clicks per day, daily unique visitors, last visit. No raw IPs are stored, the visitor hash uses a salt that rotates daily, and individual clicks are deleted after 90 days. - **Privacy-friendly stats**: clicks per day, daily unique visitors, last visit. No raw IPs are stored, the visitor hash uses a salt that rotates daily, and individual clicks are deleted after 90 days.
- **API with personal access tokens**: for scripts and iOS Shortcuts. - **API with personal access tokens**: for scripts and iOS Shortcuts.
- **Mobile-friendly admin UI**, installable as a PWA. Everything runs as a single container with SQLite. - **Mobile-friendly admin UI** with light and dark mode, installable as a PWA. Everything runs as a single container with SQLite.
See [REQUIREMENTS.md](REQUIREMENTS.md) for the full feature list. See [REQUIREMENTS.md](REQUIREMENTS.md) for the full feature list.
@@ -55,7 +55,7 @@ Copy `.env.template` to `.env` and fill it in:
| `TIMEZONE` | | Timezone for "today" and the daily stats, default `UTC` | | `TIMEZONE` | | Timezone for "today" and the daily stats, default `UTC` |
| `TRUST_PROXY` | | `true` behind a reverse proxy, so `X-Forwarded-For` is used for the visitor IP | | `TRUST_PROXY` | | `true` behind a reverse proxy, so `X-Forwarded-For` is used for the visitor IP |
| `DATA_DIR` | | Database and uploads, default `./data` (`/data` in Docker) | | `DATA_DIR` | | Database and uploads, default `./data` (`/data` in Docker) |
| `LOGO_DEV_TOKEN` | | Shows website logos on link page buttons via [logo.dev](https://logo.dev) (adds an attribution) | | `LOGO_DEV_TOKEN` | | Enables website logos on link page buttons via [logo.dev](https://logo.dev). Page owners can turn them off per page; the logo.dev credit only shows where logos are on |
| `DISABLE_ATTRIBUTION` | | `true` hides the "powered by" footer | | `DISABLE_ATTRIBUTION` | | `true` hides the "powered by" footer |
### 3. Run ### 3. Run
@@ -67,6 +67,12 @@ docker compose up -d
Put it behind a reverse proxy with TLS. Back up `data/`: it holds the SQLite database (`short.db`) and the uploaded avatars. Database migrations run automatically on startup. Put it behind a reverse proxy with TLS. Back up `data/`: it holds the SQLite database (`short.db`) and the uploaded avatars. Database migrations run automatically on startup.
## Security notes
- **Reverse proxy:** with `TRUST_PROXY=true` the visitor IP is taken from the last `X-Forwarded-For` entry, so the proxy in front of short must append to that header (Traefik, Caddy and nginx' `$proxy_add_x_forwarded_for` do).
- **Removing someone:** admin rights and access follow Authentik at each sign-in, but existing sessions (up to 30 days) and API tokens keep working. When someone leaves or loses admin rights, use **Administration → user → Revoke access** to end their sessions and delete their tokens, and remove their access in Authentik.
- **Rate limiting** isn't built in. Every visit is recorded, so very public links can be flooded to inflate stats; rate-limit at the reverse proxy if needed. Individual clicks are deleted after 90 days.
## API ## API
The admin UI uses the same JSON API. Create a token under **API tokens**; it has the same permissions as your account. The admin UI uses the same JSON API. Create a token under **API tokens**; it has the same permissions as your account.
@@ -78,9 +84,11 @@ curl -X POST https://short.example.com/~/api/pages \
-d '{"kind":"redirect","dest":"https://example.com","code":"optional"}' -d '{"kind":"redirect","dest":"https://example.com","code":"optional"}'
``` ```
Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /tokens`. Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /palettes`, `GET/POST/DELETE /tokens`.
Admin only: `PUT/DELETE /pin`, `GET /users`, `GET /conflicts`. Admin only: `PUT/DELETE /pin`, `GET /users`, `GET /conflicts`.
Link buttons can reference an existing short link (`{"kind":"link","label":"…","targetId":12}`) or create one in the page's namespace in the same request (`{"kind":"link","label":"…","newLink":{"dest":"https://…","code":"optional"}}`).
## Development ## Development
```sh ```sh
+2 -1
View File
@@ -19,7 +19,8 @@ authenticated against an existing Authentik instance.
## Links ## Links
- **R7** The shortcode is either typed in or, if left empty, randomly generated (5 characters). - **R7** The shortcode is either typed in or, if left empty, randomly generated (5 characters).
- **R8** Destinations must be `http(s)://`. Reserved codes are blocked. - **R8** Destinations must be `http(s)://`. Reserved codes are blocked.
- **R9** Destinations can be edited. Links use 302 redirects. - **R9** Destinations and shortcodes can be edited. Renaming a shortcode breaks the old URL, so the UI asks for
confirmation. Links use 302 redirects.
- **R10** Deleting a link removes its stats and its buttons on link pages, in one transaction. - **R10** Deleting a link removes its stats and its buttons on link pages, in one transaction.
- **R11** An admin can pin the root `/` to any page. - **R11** An admin can pin the root `/` to any page.
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `pages` ADD `show_logos` integer DEFAULT true NOT NULL;
+9
View File
@@ -0,0 +1,9 @@
CREATE TABLE `palettes` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`user_id` integer NOT NULL,
`colors` text NOT NULL,
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE UNIQUE INDEX `palettes_user_colors` ON `palettes` (`user_id`,`colors`);
+591
View File
@@ -0,0 +1,591 @@
{
"version": "6",
"dialect": "sqlite",
"id": "d686eb3d-38c6-4fa3-bdbd-6a774f85ddb0",
"prevId": "a6b76847-cea9-41ad-931d-e57ddc8613c4",
"tables": {
"api_tokens": {
"name": "api_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token_hash": {
"name": "token_hash",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
},
"last_used_at": {
"name": "last_used_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"api_tokens_token_hash_unique": {
"name": "api_tokens_token_hash_unique",
"columns": [
"token_hash"
],
"isUnique": true
}
},
"foreignKeys": {
"api_tokens_user_id_users_id_fk": {
"name": "api_tokens_user_id_users_id_fk",
"tableFrom": "api_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"blocks": {
"name": "blocks",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"position": {
"name": "position",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"label": {
"name": "label",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"markdown": {
"name": "markdown",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_id": {
"name": "target_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"blocks_page": {
"name": "blocks_page",
"columns": [
"page_id",
"position"
],
"isUnique": false
},
"blocks_target": {
"name": "blocks_target",
"columns": [
"target_id"
],
"isUnique": false
}
},
"foreignKeys": {
"blocks_page_id_pages_id_fk": {
"name": "blocks_page_id_pages_id_fk",
"tableFrom": "blocks",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"blocks_target_id_pages_id_fk": {
"name": "blocks_target_id_pages_id_fk",
"tableFrom": "blocks",
"tableTo": "pages",
"columnsFrom": [
"target_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"clicks": {
"name": "clicks",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"at": {
"name": "at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"day": {
"name": "day",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"visitor": {
"name": "visitor",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"clicks_page_day": {
"name": "clicks_page_day",
"columns": [
"page_id",
"day",
"visitor"
],
"isUnique": false
},
"clicks_at": {
"name": "clicks_at",
"columns": [
"at"
],
"isUnique": false
}
},
"foreignKeys": {
"clicks_page_id_pages_id_fk": {
"name": "clicks_page_id_pages_id_fk",
"tableFrom": "clicks",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"daily_stats": {
"name": "daily_stats",
"columns": {
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"day": {
"name": "day",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"clicks": {
"name": "clicks",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"uniques": {
"name": "uniques",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"last_at": {
"name": "last_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"daily_stats_page_id_pages_id_fk": {
"name": "daily_stats_page_id_pages_id_fk",
"tableFrom": "daily_stats",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"daily_stats_page_id_day_pk": {
"columns": [
"page_id",
"day"
],
"name": "daily_stats_page_id_day_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"pages": {
"name": "pages",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"namespace": {
"name": "namespace",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"code": {
"name": "code",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"dest": {
"name": "dest",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"avatar": {
"name": "avatar",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"theme": {
"name": "theme",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"show_logos": {
"name": "show_logos",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"created_by": {
"name": "created_by",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"pages_namespace_code": {
"name": "pages_namespace_code",
"columns": [
"namespace",
"code"
],
"isUnique": true
}
},
"foreignKeys": {
"pages_created_by_users_id_fk": {
"name": "pages_created_by_users_id_fk",
"tableFrom": "pages",
"tableTo": "users",
"columnsFrom": [
"created_by"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk",
"tableFrom": "sessions",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"sub": {
"name": "sub",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"username": {
"name": "username",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"is_admin": {
"name": "is_admin",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"users_sub_unique": {
"name": "users_sub_unique",
"columns": [
"sub"
],
"isUnique": true
},
"users_username_unique": {
"name": "users_username_unique",
"columns": [
"username"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+653
View File
@@ -0,0 +1,653 @@
{
"version": "6",
"dialect": "sqlite",
"id": "587766a4-dd62-4efe-bce3-dd939b9d72c2",
"prevId": "d686eb3d-38c6-4fa3-bdbd-6a774f85ddb0",
"tables": {
"api_tokens": {
"name": "api_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token_hash": {
"name": "token_hash",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
},
"last_used_at": {
"name": "last_used_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"api_tokens_token_hash_unique": {
"name": "api_tokens_token_hash_unique",
"columns": [
"token_hash"
],
"isUnique": true
}
},
"foreignKeys": {
"api_tokens_user_id_users_id_fk": {
"name": "api_tokens_user_id_users_id_fk",
"tableFrom": "api_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"blocks": {
"name": "blocks",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"position": {
"name": "position",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"label": {
"name": "label",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"markdown": {
"name": "markdown",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_id": {
"name": "target_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"blocks_page": {
"name": "blocks_page",
"columns": [
"page_id",
"position"
],
"isUnique": false
},
"blocks_target": {
"name": "blocks_target",
"columns": [
"target_id"
],
"isUnique": false
}
},
"foreignKeys": {
"blocks_page_id_pages_id_fk": {
"name": "blocks_page_id_pages_id_fk",
"tableFrom": "blocks",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"blocks_target_id_pages_id_fk": {
"name": "blocks_target_id_pages_id_fk",
"tableFrom": "blocks",
"tableTo": "pages",
"columnsFrom": [
"target_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"clicks": {
"name": "clicks",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"at": {
"name": "at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"day": {
"name": "day",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"visitor": {
"name": "visitor",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"clicks_page_day": {
"name": "clicks_page_day",
"columns": [
"page_id",
"day",
"visitor"
],
"isUnique": false
},
"clicks_at": {
"name": "clicks_at",
"columns": [
"at"
],
"isUnique": false
}
},
"foreignKeys": {
"clicks_page_id_pages_id_fk": {
"name": "clicks_page_id_pages_id_fk",
"tableFrom": "clicks",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"daily_stats": {
"name": "daily_stats",
"columns": {
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"day": {
"name": "day",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"clicks": {
"name": "clicks",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"uniques": {
"name": "uniques",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"last_at": {
"name": "last_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"daily_stats_page_id_pages_id_fk": {
"name": "daily_stats_page_id_pages_id_fk",
"tableFrom": "daily_stats",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"daily_stats_page_id_day_pk": {
"columns": [
"page_id",
"day"
],
"name": "daily_stats_page_id_day_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"pages": {
"name": "pages",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"namespace": {
"name": "namespace",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"code": {
"name": "code",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"dest": {
"name": "dest",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"avatar": {
"name": "avatar",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"theme": {
"name": "theme",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"show_logos": {
"name": "show_logos",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": true
},
"created_by": {
"name": "created_by",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"pages_namespace_code": {
"name": "pages_namespace_code",
"columns": [
"namespace",
"code"
],
"isUnique": true
}
},
"foreignKeys": {
"pages_created_by_users_id_fk": {
"name": "pages_created_by_users_id_fk",
"tableFrom": "pages",
"tableTo": "users",
"columnsFrom": [
"created_by"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"palettes": {
"name": "palettes",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"colors": {
"name": "colors",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"palettes_user_colors": {
"name": "palettes_user_colors",
"columns": [
"user_id",
"colors"
],
"isUnique": true
}
},
"foreignKeys": {
"palettes_user_id_users_id_fk": {
"name": "palettes_user_id_users_id_fk",
"tableFrom": "palettes",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk",
"tableFrom": "sessions",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"sub": {
"name": "sub",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"username": {
"name": "username",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"is_admin": {
"name": "is_admin",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"users_sub_unique": {
"name": "users_sub_unique",
"columns": [
"sub"
],
"isUnique": true
},
"users_username_unique": {
"name": "users_username_unique",
"columns": [
"username"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+14
View File
@@ -8,6 +8,20 @@
"when": 1791978231861, "when": 1791978231861,
"tag": "0000_init", "tag": "0000_init",
"breakpoints": true "breakpoints": true
},
{
"idx": 1,
"version": "6",
"when": 1791988240968,
"tag": "0001_page_show_logos",
"breakpoints": true
},
{
"idx": 2,
"version": "6",
"when": 1791989055221,
"tag": "0002_user_palettes",
"breakpoints": true
} }
] ]
} }
+23 -3
View File
@@ -2,9 +2,10 @@ import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit"; import { bodyLimit } from "hono/body-limit";
import { desc, eq, and } from "drizzle-orm"; import { desc, eq, and } from "drizzle-orm";
import type { z } from "zod"; import type { z } from "zod";
import type { ApiToken, CreatedToken } from "../shared/api-types.js"; import type { ApiToken, CreatedToken, Me } from "../shared/api-types.js";
import { import {
createBlockSchema, createBlockSchema,
createPaletteSchema,
createPageSchema, createPageSchema,
createTokenSchema, createTokenSchema,
pinSchema, pinSchema,
@@ -15,10 +16,11 @@ import {
} from "../shared/validation.js"; } from "../shared/validation.js";
import type { AppEnv, Deps } from "./app.js"; import type { AppEnv, Deps } from "./app.js";
import { requireActor } from "./auth/middleware.js"; import { requireActor } from "./auth/middleware.js";
import { createApiToken } from "./auth/sessions.js"; import { createApiToken, revokeAccess } from "./auth/sessions.js";
import { apiTokens } from "./db/schema.js"; import { apiTokens } from "./db/schema.js";
import { forbidden, HttpError, notFound } from "./lib/errors.js"; import { forbidden, HttpError, notFound } from "./lib/errors.js";
import { removeMedia, saveAvatar } from "./lib/media.js"; import { removeMedia, saveAvatar } from "./lib/media.js";
import { deletePalette, listPalettes, savePalette } from "./lib/palettes.js";
import * as pages from "./lib/pages.js"; import * as pages from "./lib/pages.js";
import { getStats, resetStats } from "./lib/stats.js"; import { getStats, resetStats } from "./lib/stats.js";
@@ -65,7 +67,7 @@ export function apiRoutes(deps: Deps) {
.get("/me", (c) => { .get("/me", (c) => {
const { username, isAdmin } = c.var.actor; const { username, isAdmin } = c.var.actor;
return c.json({ username, isAdmin }); return c.json({ username, isAdmin, logoDev: !!config.logoDevToken, logoDevToken: config.logoDevToken ?? null } satisfies Me);
}) })
// Pages (redirects and link pages) // Pages (redirects and link pages)
@@ -133,6 +135,18 @@ export function apiRoutes(deps: Deps) {
return c.body(null, 204); return c.body(null, 204);
}) })
// Saved color palettes (always the caller's own)
.get("/palettes", (c) => c.json(listPalettes(db, c.var.actor.id)))
.post("/palettes", async (c) => {
const { colors } = parse(createPaletteSchema, await jsonBody(c));
const { palette, created } = savePalette(db, c.var.actor.id, colors);
return c.json(palette, created ? 201 : 200);
})
.delete("/palettes/:id", (c) => {
deletePalette(db, c.var.actor.id, idParam(c.req.param("id")));
return c.body(null, 204);
})
// Personal access tokens (always the caller's own) // Personal access tokens (always the caller's own)
.get("/tokens", (c) => { .get("/tokens", (c) => {
const rows = db const rows = db
@@ -172,6 +186,12 @@ export function apiRoutes(deps: Deps) {
if (!c.var.actor.isAdmin) throw forbidden(); if (!c.var.actor.isAdmin) throw forbidden();
return c.json(pages.listUsernames(db)); return c.json(pages.listUsernames(db));
}) })
.delete("/users/:username/access", (c) => {
if (!c.var.actor.isAdmin) throw forbidden();
const revoked = revokeAccess(db, c.req.param("username"));
if (!revoked) throw notFound();
return c.json(revoked);
})
.get("/conflicts", (c) => { .get("/conflicts", (c) => {
if (!c.var.actor.isAdmin) throw forbidden(); if (!c.var.actor.isAdmin) throw forbidden();
return c.json(pages.listConflicts(db)); return c.json(pages.listConflicts(db));
+4
View File
@@ -48,6 +48,10 @@ export function createApp(deps: Deps) {
app.onError((err, c) => { app.onError((err, c) => {
const isApi = c.req.path.startsWith("/~/api/"); const isApi = c.req.path.startsWith("/~/api/");
// Two requests claiming the same unique value at once (e.g. a shortcode): the database rejects the second.
if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE") {
err = new HttpError(409, "This already exists. Please try again with a different value.");
}
if (err instanceof HttpError) { if (err instanceof HttpError) {
if (isApi) return c.json({ error: err.message, issues: err.issues }, err.status); if (isApi) return c.json({ error: err.message, issues: err.issues }, err.status);
return c.html(<MessagePage title="Something went wrong" message={err.message} link={{ href: "/~/", label: "Back" }} />, err.status); return c.html(<MessagePage title="Something went wrong" message={err.message} link={{ href: "/~/", label: "Back" }} />, err.status);
+9 -1
View File
@@ -2,6 +2,7 @@ import { Hono } from "hono";
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie"; import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
import type { AppEnv, Deps } from "../app.js"; import type { AppEnv, Deps } from "../app.js";
import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js"; import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js";
import { HttpError } from "../lib/errors.js";
import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js"; import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js";
export const SESSION_COOKIE = "short_session"; export const SESSION_COOKIE = "short_session";
@@ -38,7 +39,14 @@ export function authRoutes({ db, config, oidc }: Deps) {
// Behind a reverse proxy the request URL may be internal, so rebuild it from BASE_URL. // Behind a reverse proxy the request URL may be internal, so rebuild it from BASE_URL.
const requestUrl = new URL(c.req.url); const requestUrl = new URL(c.req.url);
const currentUrl = new URL(`${redirectUri}${requestUrl.search}`); const currentUrl = new URL(`${redirectUri}${requestUrl.search}`);
const claims = await oidc.exchange({ currentUrl, state, codeVerifier }); let claims;
try {
claims = await oidc.exchange({ currentUrl, state, codeVerifier });
} catch (err) {
// E.g. the login was cancelled at the identity provider or took too long.
console.warn("OIDC callback failed:", err instanceof Error ? err.message : err);
throw new HttpError(400, "Sign-in failed. Please try again.");
}
const actor = upsertUser(db, claims, config.adminGroup); const actor = upsertUser(db, claims, config.adminGroup);
setCookie(c, SESSION_COOKIE, createSession(db, actor.id), { setCookie(c, SESSION_COOKIE, createSession(db, actor.id), {
+11
View File
@@ -75,3 +75,14 @@ export function createApiToken(db: Db, userId: number, name: string) {
export function pruneSessions(db: Db, now = new Date()): number { export function pruneSessions(db: Db, now = new Date()): number {
return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes; return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes;
} }
// Ends all sessions and deletes all API tokens of a user, e.g. when they leave.
// They can sign in again only if Authentik still lets them.
export function revokeAccess(db: Db, username: string): { sessions: number; tokens: number } | null {
const user = db.select().from(users).where(eq(users.username, username)).get();
if (!user) return null;
return db.transaction((tx) => ({
sessions: tx.delete(sessions).where(eq(sessions.userId, user.id)).run().changes,
tokens: tx.delete(apiTokens).where(eq(apiTokens.userId, user.id)).run().changes,
}));
}
+16
View File
@@ -27,6 +27,8 @@ export const pages = sqliteTable(
title: text("title"), title: text("title"),
avatar: text("avatar"), avatar: text("avatar"),
theme: text("theme", { mode: "json" }), theme: text("theme", { mode: "json" }),
// Link pages only: show website logos from logo.dev (needs LOGO_DEV_TOKEN).
showLogos: integer("show_logos", { mode: "boolean" }).notNull().default(true),
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
createdAt: createdAt(), createdAt: createdAt(),
updatedAt: integer("updated_at", { mode: "timestamp" }) updatedAt: integer("updated_at", { mode: "timestamp" })
@@ -101,6 +103,20 @@ export const apiTokens = sqliteTable("api_tokens", {
lastUsedAt: integer("last_used_at", { mode: "timestamp" }), lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
}); });
// Color palettes a user imported (e.g. from coolors.co), stored as lowercase "rrggbb-rrggbb-…".
export const palettes = sqliteTable(
"palettes",
{
id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
colors: text("colors").notNull(),
createdAt: createdAt(),
},
(t) => [uniqueIndex("palettes_user_colors").on(t.userId, t.colors)],
);
export const settings = sqliteTable("settings", { export const settings = sqliteTable("settings", {
key: text("key").primaryKey(), key: text("key").primaryKey(),
value: text("value").notNull(), value: text("value").notNull(),
+48 -9
View File
@@ -103,8 +103,11 @@ export function createPage(db: Db, actor: Actor, input: CreatePageInput): PageSu
export function updatePage(db: Db, actor: Actor, id: number, input: UpdatePageInput): PageDetail { export function updatePage(db: Db, actor: Actor, id: number, input: UpdatePageInput): PageDetail {
const page = loadManagedPage(db, actor, id); const page = loadManagedPage(db, actor, id);
if (input.dest !== undefined && page.kind !== "redirect") throw new HttpError(400, "Only redirects have a destination"); if (input.dest !== undefined && page.kind !== "redirect") throw new HttpError(400, "Only redirects have a destination");
if ((input.title !== undefined || input.theme !== undefined) && page.kind !== "linkpage") { if ((input.title !== undefined || input.theme !== undefined || input.showLogos !== undefined) && page.kind !== "linkpage") {
throw new HttpError(400, "Only link pages have a title and theme"); throw new HttpError(400, "Only link pages have a title, theme and logos");
}
if (input.code !== undefined && input.code !== page.code && codeTaken(db, page.namespace, input.code)) {
throw new HttpError(409, "Shortcode is not available", { code: ["Already in use or reserved"] });
} }
db.update(pages) db.update(pages)
.set({ ...input, updatedAt: new Date() }) .set({ ...input, updatedAt: new Date() })
@@ -144,7 +147,25 @@ function totalClicks(db: Db, pageIds: number[]): Map<number, number> {
return new Map(rows.map((r) => [r.pageId, r.total])); return new Map(rows.map((r) => [r.pageId, r.total]));
} }
function toSummary(row: PageRow, clicks: number, pinned: boolean): PageSummary { // For each short link, the link pages whose buttons point at it.
function linkPagesUsing(db: Db, targetIds: number[]): Map<number, { id: number; path: string }[]> {
const result = new Map<number, { id: number; path: string }[]>();
if (targetIds.length === 0) return result;
const rows = db
.selectDistinct({ targetId: blocks.targetId, id: pages.id, namespace: pages.namespace, code: pages.code })
.from(blocks)
.innerJoin(pages, eq(pages.id, blocks.pageId))
.where(inArray(blocks.targetId, targetIds))
.orderBy(asc(pages.namespace), asc(pages.code))
.all();
for (const r of rows) {
if (r.targetId === null) continue;
result.set(r.targetId, [...(result.get(r.targetId) ?? []), { id: r.id, path: pagePath(r) }]);
}
return result;
}
function toSummary(row: PageRow, clicks: number, pinned: boolean, usedOn: { id: number; path: string }[] = []): PageSummary {
return { return {
id: row.id, id: row.id,
namespace: row.namespace, namespace: row.namespace,
@@ -155,6 +176,7 @@ function toSummary(row: PageRow, clicks: number, pinned: boolean): PageSummary {
title: row.title, title: row.title,
totalClicks: clicks, totalClicks: clicks,
pinned, pinned,
usedOn,
}; };
} }
@@ -168,7 +190,11 @@ export function listPages(db: Db, actor: Actor): PageSummary[] {
rows.map((r) => r.id), rows.map((r) => r.id),
); );
const pinned = getPinnedPageId(db); const pinned = getPinnedPageId(db);
return rows.map((r) => toSummary(r, counts.get(r.id) ?? 0, r.id === pinned)); const used = linkPagesUsing(
db,
rows.filter((r) => r.kind === "redirect").map((r) => r.id),
);
return rows.map((r) => toSummary(r, counts.get(r.id) ?? 0, r.id === pinned, used.get(r.id)));
} }
export function getBlocks(db: Db, pageId: number): Block[] { export function getBlocks(db: Db, pageId: number): Block[] {
@@ -193,7 +219,7 @@ export function getBlocks(db: Db, pageId: number): Block[] {
kind: b.kind, kind: b.kind,
label: b.label, label: b.label,
markdown: b.markdown, markdown: b.markdown,
target: target ? { id: target.id, path: pagePath(target), dest: target.dest } : null, target: target ? { id: target.id, namespace: target.namespace, path: pagePath(target), dest: target.dest } : null,
}; };
}); });
} }
@@ -202,8 +228,9 @@ export function getPageDetail(db: Db, actor: Actor, id: number): PageDetail {
const page = loadManagedPage(db, actor, id); const page = loadManagedPage(db, actor, id);
const clicks = totalClicks(db, [id]).get(id) ?? 0; const clicks = totalClicks(db, [id]).get(id) ?? 0;
return { return {
...toSummary(page, clicks, getPinnedPageId(db) === id), ...toSummary(page, clicks, getPinnedPageId(db) === id, page.kind === "redirect" ? linkPagesUsing(db, [id]).get(id) : []),
theme: (page.theme as Theme | null) ?? DEFAULT_THEME, theme: (page.theme as Theme | null) ?? DEFAULT_THEME,
showLogos: page.showLogos,
avatarUrl: avatarUrl(page.avatar), avatarUrl: avatarUrl(page.avatar),
blocks: page.kind === "linkpage" ? getBlocks(db, id) : [], blocks: page.kind === "linkpage" ? getBlocks(db, id) : [],
}; };
@@ -221,14 +248,27 @@ function loadLinkPage(db: Db, actor: Actor, id: number): PageRow {
export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] { export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] {
const page = loadLinkPage(db, actor, pageId); const page = loadLinkPage(db, actor, pageId);
// better-sqlite3 uses a single connection, so the calls on `db` below all run inside this transaction:
// a new short link is only kept if the button is added too.
db.transaction(() => {
let targetId: number | null = null; let targetId: number | null = null;
if (input.kind === "link") { if (input.kind === "link" && input.newLink) {
const target = db.select().from(pages).where(eq(pages.id, input.targetId)).get(); const { code, dest } = input.newLink;
// The new link lives next to the page, e.g. /alice/<code> for a page under /alice/.
targetId = createPage(db, actor, { kind: "redirect", namespace: page.namespace, code, dest }).id;
} else if (input.kind === "link") {
const target = input.targetId ? db.select().from(pages).where(eq(pages.id, input.targetId)).get() : undefined;
if (!target || !canLinkTo(actor, page, target)) { if (!target || !canLinkTo(actor, page, target)) {
throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] }); throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] });
} }
targetId = target.id; targetId = target.id;
} }
insertBlock(db, page.id, input, targetId);
});
return getBlocks(db, pageId);
}
function insertBlock(db: Db, pageId: number, input: CreateBlockInput, targetId: number | null): void {
const max = db const max = db
.select({ max: sql<number | null>`max(${blocks.position})` }) .select({ max: sql<number | null>`max(${blocks.position})` })
.from(blocks) .from(blocks)
@@ -244,7 +284,6 @@ export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBloc
targetId, targetId,
}) })
.run(); .run();
return getBlocks(db, pageId);
} }
function loadManagedBlock(db: Db, actor: Actor, blockId: number) { function loadManagedBlock(db: Db, actor: Actor, blockId: number) {
+50
View File
@@ -0,0 +1,50 @@
import { and, desc, eq, sql } from "drizzle-orm";
import type { SavedPalette } from "../../shared/api-types.js";
import { MAX_PALETTES } from "../../shared/validation.js";
import type { Db } from "../db/index.js";
import { palettes } from "../db/schema.js";
import { HttpError, notFound } from "./errors.js";
type PaletteRow = typeof palettes.$inferSelect;
function toApi(row: PaletteRow): SavedPalette {
return {
id: row.id,
colors: row.colors.split("-").map((c) => `#${c}`),
createdAt: row.createdAt.toISOString(),
};
}
export function listPalettes(db: Db, userId: number): SavedPalette[] {
return db.select().from(palettes).where(eq(palettes.userId, userId)).orderBy(desc(palettes.id)).all().map(toApi);
}
// Saving the same palette twice returns the existing entry instead of a duplicate.
export function savePalette(db: Db, userId: number, colors: string[]): { palette: SavedPalette; created: boolean } {
const key = colors.map((c) => c.slice(1).toLowerCase()).join("-");
const existing = db
.select()
.from(palettes)
.where(and(eq(palettes.userId, userId), eq(palettes.colors, key)))
.get();
if (existing) return { palette: toApi(existing), created: false };
const count = db
.select({ n: sql<number>`count(*)` })
.from(palettes)
.where(eq(palettes.userId, userId))
.get();
if ((count?.n ?? 0) >= MAX_PALETTES) {
throw new HttpError(409, `You can save up to ${MAX_PALETTES} palettes. Remove one first.`);
}
const row = db.insert(palettes).values({ userId, colors: key }).returning().get();
return { palette: toApi(row), created: true };
}
export function deletePalette(db: Db, userId: number, id: number): void {
const { changes } = db
.delete(palettes)
.where(and(eq(palettes.id, id), eq(palettes.userId, userId)))
.run();
if (!changes) throw notFound();
}
+4 -2
View File
@@ -11,7 +11,8 @@ import { LinkPage, MessagePage } from "./views.js";
export function publicRoutes({ db, config }: Deps) { export function publicRoutes({ db, config }: Deps) {
const clientIp = (c: Context<AppEnv>): string => { const clientIp = (c: Context<AppEnv>): string => {
if (config.trustProxy) { if (config.trustProxy) {
const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim(); // The last entry is the one added by our proxy; earlier ones can be set by the client.
const forwarded = c.req.header("x-forwarded-for")?.split(",").at(-1)?.trim();
if (forwarded) return forwarded; if (forwarded) return forwarded;
} }
try { try {
@@ -52,7 +53,8 @@ export function publicRoutes({ db, config }: Deps) {
avatarUrl={avatarUrl(page.avatar)} avatarUrl={avatarUrl(page.avatar)}
theme={(page.theme as Theme | null) ?? DEFAULT_THEME} theme={(page.theme as Theme | null) ?? DEFAULT_THEME}
blocks={getBlocks(db, page.id)} blocks={getBlocks(db, page.id)}
logoDevToken={config.logoDevToken} // Logos and their attribution only appear when the page owner enabled them.
logoDevToken={page.showLogos ? config.logoDevToken : undefined}
showAttribution={!config.disableAttribution} showAttribution={!config.disableAttribution}
/>, />,
); );
+2 -2
View File
@@ -7,7 +7,7 @@ import { renderMarkdown } from "./markdown.js";
const STYLES = ` const STYLES = `
*{box-sizing:border-box} *{box-sizing:border-box}
body{margin:0;min-height:100vh;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--bg);color:var(--fg)} body{margin:0;min-height:100vh;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--bg);color:var(--fg)}
main{display:flex;flex-direction:column;align-items:center;padding:3rem 1rem;max-width:28rem;margin:0 auto} main{display:flex;flex-direction:column;align-items:center;min-height:100vh;min-height:100dvh;padding:3rem 1rem 1.5rem;max-width:28rem;margin:0 auto}
.avatar{width:96px;height:96px;border-radius:9999px;object-fit:cover;animation:zoom .6s ease both} .avatar{width:96px;height:96px;border-radius:9999px;object-fit:cover;animation:zoom .6s ease both}
h1{font-size:2rem;margin:1.5rem 0 2rem;text-align:center;animation:zoom .6s ease both} h1{font-size:2rem;margin:1.5rem 0 2rem;text-align:center;animation:zoom .6s ease both}
.blocks{width:100%;display:flex;flex-direction:column;gap:.75rem} .blocks{width:100%;display:flex;flex-direction:column;gap:.75rem}
@@ -18,7 +18,7 @@ h1{font-size:2rem;margin:1.5rem 0 2rem;text-align:center;animation:zoom .6s ease
.icon{width:2rem;height:2rem;border-radius:9999px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.85);color:#374151;font-weight:700} .icon{width:2rem;height:2rem;border-radius:9999px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.85);color:#374151;font-weight:700}
.text{line-height:1.5;text-align:center} .text{line-height:1.5;text-align:center}
.text a{color:inherit} .text a{color:inherit}
footer{margin-top:3rem;font-size:.85rem;opacity:.5;text-align:center} footer{margin-top:auto;padding-top:3rem;font-size:.85rem;opacity:.5;text-align:center}
footer a{color:inherit} footer a{color:inherit}
.center{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:1rem} .center{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:1rem}
@keyframes zoom{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}} @keyframes zoom{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
+14 -1
View File
@@ -6,6 +6,10 @@ export type PageKind = "redirect" | "linkpage";
export interface Me { export interface Me {
username: string; username: string;
isAdmin: boolean; isAdmin: boolean;
/** Whether the server has a logo.dev token, i.e. link pages can show website logos. */
logoDev: boolean;
/** Publishable logo.dev key (it's part of every public logo URL), used for the editor preview. */
logoDevToken: string | null;
} }
export interface PageSummary { export interface PageSummary {
@@ -18,6 +22,8 @@ export interface PageSummary {
title: string | null; title: string | null;
totalClicks: number; totalClicks: number;
pinned: boolean; pinned: boolean;
/** Short links only: the link pages that have a button pointing to this link. */
usedOn: { id: number; path: string }[];
} }
export interface Block { export interface Block {
@@ -26,11 +32,12 @@ export interface Block {
kind: "link" | "text"; kind: "link" | "text";
label: string | null; label: string | null;
markdown: string | null; markdown: string | null;
target: { id: number; path: string; dest: string | null } | null; target: { id: number; namespace: string; path: string; dest: string | null } | null;
} }
export interface PageDetail extends PageSummary { export interface PageDetail extends PageSummary {
theme: Theme; theme: Theme;
showLogos: boolean;
avatarUrl: string | null; avatarUrl: string | null;
blocks: Block[]; blocks: Block[];
} }
@@ -49,6 +56,12 @@ export interface PageStats {
series: StatsDay[]; series: StatsDay[];
} }
export interface SavedPalette {
id: number;
colors: string[]; // "#rrggbb"
createdAt: string;
}
export interface ApiToken { export interface ApiToken {
id: number; id: number;
name: string; name: string;
+23 -3
View File
@@ -62,16 +62,30 @@ export const createPageSchema = z.discriminatedUnion("kind", [
export type CreatePageInput = z.infer<typeof createPageSchema>; export type CreatePageInput = z.infer<typeof createPageSchema>;
export const updatePageSchema = z.object({ export const updatePageSchema = z.object({
// Renaming breaks the old URL; the admin UI asks for confirmation first.
code: codeSchema.optional(),
dest: destSchema.optional(), dest: destSchema.optional(),
title: titleSchema.optional(), title: titleSchema.optional(),
theme: themeSchema.optional(), theme: themeSchema.optional(),
showLogos: z.boolean().optional(),
}); });
export type UpdatePageInput = z.infer<typeof updatePageSchema>; export type UpdatePageInput = z.infer<typeof updatePageSchema>;
export const createBlockSchema = z.discriminatedUnion("kind", [ // A link button points at an existing short link (targetId) or creates a new one in the page's namespace (newLink).
z.object({ kind: z.literal("link"), targetId: z.number().int().positive(), label: titleSchema }), export const createBlockSchema = z
.discriminatedUnion("kind", [
z.object({
kind: z.literal("link"),
label: titleSchema,
targetId: z.number().int().positive().optional(),
newLink: z.object({ dest: destSchema, code: codeSchema.optional() }).optional(),
}),
z.object({ kind: z.literal("text"), markdown: z.string().max(5000) }), z.object({ kind: z.literal("text"), markdown: z.string().max(5000) }),
]); ])
.refine((b) => b.kind !== "link" || (b.targetId === undefined) !== (b.newLink === undefined), {
message: "Pick an existing link or create a new one",
path: ["targetId"],
});
export type CreateBlockInput = z.infer<typeof createBlockSchema>; export type CreateBlockInput = z.infer<typeof createBlockSchema>;
export const updateBlockSchema = z.object({ export const updateBlockSchema = z.object({
@@ -87,6 +101,12 @@ export const statsRangeSchema = z.object({
days: z.coerce.number().pipe(z.union([z.literal(7), z.literal(30), z.literal(90)])).default(7), days: z.coerce.number().pipe(z.union([z.literal(7), z.literal(30), z.literal(90)])).default(7),
}); });
export const MAX_PALETTES = 50;
export const createPaletteSchema = z.object({
colors: z.array(hexColor).min(2).max(10),
});
export const pinSchema = z.object({ pageId: z.number().int().positive() }); export const pinSchema = z.object({ pageId: z.number().int().positive() });
export const createTokenSchema = z.object({ name: z.string().trim().min(1).max(100) }); export const createTokenSchema = z.object({ name: z.string().trim().min(1).max(100) });
+7 -2
View File
@@ -4,8 +4,9 @@ import { useApi } from "../api.js";
import { buttonClass } from "../components/ui/button.js"; import { buttonClass } from "../components/ui/button.js";
import { Link } from "../components/ui/misc.js"; import { Link } from "../components/ui/misc.js";
import { EmptyState } from "../components/ui/surface.js"; import { EmptyState } from "../components/ui/surface.js";
import { parseRoute, usePath } from "../router.js"; import { parseRoute, setViewer, usePath } from "../router.js";
import { AdminScreen } from "../screens/AdminScreen.js"; import { AdminScreen } from "../screens/AdminScreen.js";
import { AdminUserScreen } from "../screens/AdminUserScreen.js";
import { DetailScreen } from "../screens/detail/DetailScreen.js"; import { DetailScreen } from "../screens/detail/DetailScreen.js";
import { ListScreen } from "../screens/ListScreen.js"; import { ListScreen } from "../screens/ListScreen.js";
import { OverviewScreen } from "../screens/OverviewScreen.js"; import { OverviewScreen } from "../screens/OverviewScreen.js";
@@ -61,6 +62,7 @@ export function App() {
location.href = "/~/"; location.href = "/~/";
}; };
setViewer(me.data.username);
const route = parseRoute(path); const route = parseRoute(path);
let screen; let screen;
switch (route.name) { switch (route.name) {
@@ -77,7 +79,10 @@ export function App() {
screen = <TokensScreen />; screen = <TokensScreen />;
break; break;
case "admin": case "admin":
screen = me.data.isAdmin ? <AdminScreen /> : null; screen = me.data.isAdmin ? <AdminScreen me={me.data} /> : null;
break;
case "adminUser":
screen = me.data.isAdmin ? <AdminUserScreen key={route.username} username={route.username} me={me.data} /> : null;
break; break;
} }
+9
View File
@@ -1,6 +1,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { KeyRound, LayoutDashboard, Link2, LogOut, PanelsTopLeft, ShieldCheck } from "lucide-react"; import { KeyRound, LayoutDashboard, Link2, LogOut, PanelsTopLeft, ShieldCheck } from "lucide-react";
import type { Me } from "../../shared/api-types.js"; import type { Me } from "../../shared/api-types.js";
import { ThemeCycleButton, ThemeSwitch } from "../components/ThemeToggle.js";
import { Button } from "../components/ui/button.js"; import { Button } from "../components/ui/button.js";
import { Link } from "../components/ui/misc.js"; import { Link } from "../components/ui/misc.js";
import { cx } from "../lib/cx.js"; import { cx } from "../lib/cx.js";
@@ -14,8 +15,12 @@ function sectionOf(route: Route): Section | null {
case "tokens": case "tokens":
case "admin": case "admin":
return route.name; return route.name;
case "adminUser":
return "admin";
case "list": case "list":
case "detail": case "detail":
// Other users' pages are opened from Administration and stay in that section.
if (route.name === "detail" && route.owner) return "admin";
return route.kind === "redirect" ? "links" : "pages"; return route.kind === "redirect" ? "links" : "pages";
default: default:
return null; return null;
@@ -74,6 +79,9 @@ export function Shell({ me, route, onLogout, children }: { me: Me; route: Route;
</Link> </Link>
))} ))}
</nav> </nav>
<div className="px-4 pb-3">
<ThemeSwitch />
</div>
<div className="flex items-center gap-3 border-t border-border p-4"> <div className="flex items-center gap-3 border-t border-border p-4">
<UserAvatar username={me.username} /> <UserAvatar username={me.username} />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
@@ -90,6 +98,7 @@ export function Shell({ me, route, onLogout, children }: { me: Me; route: Route;
<header className="sticky top-0 z-30 flex h-14 items-center justify-between border-b border-border bg-surface/85 px-4 backdrop-blur lg:hidden"> <header className="sticky top-0 z-30 flex h-14 items-center justify-between border-b border-border bg-surface/85 px-4 backdrop-blur lg:hidden">
<Logo /> <Logo />
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<ThemeCycleButton />
<UserAvatar username={me.username} /> <UserAvatar username={me.username} />
<Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out"> <Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out">
<LogOut /> <LogOut />
+9 -11
View File
@@ -1,6 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js"; import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { api, ApiRequestError, errorMessage, useApi } from "../api.js"; import { api, ApiRequestError, errorMessage } from "../api.js";
import { Button } from "./ui/button.js"; import { Button } from "./ui/button.js";
import { Dialog } from "./ui/dialog.js"; import { Dialog } from "./ui/dialog.js";
import { Field, Input, PrefixInput, Select } from "./ui/form.js"; import { Field, Input, PrefixInput, Select } from "./ui/form.js";
@@ -24,15 +24,17 @@ export function CreatePageDialog({
open, open,
onClose, onClose,
onCreated, onCreated,
fixedNamespace,
}: { }: {
kind: PageKind; kind: PageKind;
me: Me; me: Me;
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
onCreated: (page: PageSummary) => void; onCreated: (page: PageSummary) => void;
/** Create in this namespace without offering a choice, e.g. when an admin manages another user. */
fixedNamespace?: string;
}) { }) {
const users = useApi<string[]>(me.isAdmin && open ? "/users" : null); const [namespace, setNamespace] = useState(fixedNamespace ?? me.username);
const [namespace, setNamespace] = useState(me.username);
const [code, setCode] = useState(""); const [code, setCode] = useState("");
const [value, setValue] = useState(""); const [value, setValue] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@@ -102,16 +104,12 @@ export function CreatePageDialog({
</Field> </Field>
)} )}
{me.isAdmin && ( {me.isAdmin && fixedNamespace === undefined && (
<Field label="Namespace" hint="Root links are only available to admins." error={errors.namespace}> <Field label="Namespace" error={errors.namespace}>
{(id) => ( {(id) => (
<Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}> <Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
<option value="">Root (/)</option> <option value={me.username}>/{me.username}/ (yours)</option>
{(users.data ?? [me.username]).map((u) => ( <option value="">Root /</option>
<option key={u} value={u}>
{u === me.username ? `${u} (you)` : u}
</option>
))}
</Select> </Select>
)} )}
</Field> </Field>
+129
View File
@@ -0,0 +1,129 @@
import { useMemo, useState, type ReactNode } from "react";
import { ChevronRight, Link2, PanelsTopLeft, Pin, Search } from "lucide-react";
import type { PageKind, PageSummary } from "../../shared/api-types.js";
import { detailPath } from "../router.js";
import { Input, Select } from "./ui/form.js";
import { CopyButton, DomainIcon, Link, publicUrl } from "./ui/misc.js";
import { Badge, Card, EmptyState, Skeleton } from "./ui/surface.js";
function Row({ page, showNamespace }: { page: PageSummary; showNamespace: boolean }) {
const isLink = page.kind === "redirect";
return (
<div className="group relative grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-4 py-3 transition-colors hover:bg-surface-2/60 md:grid-cols-[auto_minmax(0,2fr)_minmax(0,3fr)_5rem_auto] md:px-5">
{isLink ? (
<DomainIcon url={page.dest} />
) : (
<span className="flex size-8 items-center justify-center rounded-lg bg-accent-soft text-accent-soft-fg">
<PanelsTopLeft className="size-4" />
</span>
)}
<div className="min-w-0">
<div className="flex items-center gap-2">
{/* The link stretches over the whole row; the copy button sits above it. */}
<Link to={detailPath(page)} className="truncate font-mono text-sm font-medium text-fg after:absolute after:inset-0">
{page.path}
</Link>
{showNamespace && page.namespace === "" && <Badge>Root</Badge>}
{page.usedOn.length > 0 && (
<span className="shrink-0" title={`Used on ${page.usedOn.map((u) => u.path).join(", ")}`}>
<Badge icon={<PanelsTopLeft />}>{page.usedOn.length === 1 ? `on ${page.usedOn[0]!.path}` : `on ${page.usedOn.length} pages`}</Badge>
</span>
)}
{page.pinned && (
<Badge tone="accent" icon={<Pin />}>
Home
</Badge>
)}
</div>
<div className="truncate text-sm text-muted md:hidden">{isLink ? page.dest : page.title}</div>
</div>
<div className="hidden truncate text-sm text-muted md:block">{isLink ? page.dest : page.title}</div>
<div className="hidden text-right text-sm text-muted tabular-nums md:block">{page.totalClicks.toLocaleString()}</div>
<div className="flex items-center gap-1">
<div className="relative z-10">
<CopyButton value={publicUrl(page.path)} />
</div>
<ChevronRight className="hidden size-4 text-muted transition-transform group-hover:translate-x-0.5 md:block" />
</div>
</div>
);
}
export interface NamespaceOption {
label: string;
match: (namespace: string) => boolean;
}
// Searchable list of short links or link pages. The toolbar is the same everywhere it's used;
// `namespaces` adds a namespace filter (e.g. "Mine" / "Root" for admins).
export function PageTable({
kind,
pages,
namespaces,
empty,
}: {
kind: PageKind;
pages: PageSummary[] | undefined;
namespaces?: NamespaceOption[];
empty: { title: string; description: string; action?: ReactNode };
}) {
const [query, setQuery] = useState("");
const [filter, setFilter] = useState(0);
const ofKind = useMemo(() => (pages ?? []).filter((p) => p.kind === kind), [pages, kind]);
const q = query.trim().toLowerCase();
const option = namespaces?.[filter];
const visible = ofKind.filter(
(p) =>
(!option || option.match(p.namespace)) &&
(!q || p.path.toLowerCase().includes(q) || (p.dest ?? p.title ?? "").toLowerCase().includes(q)),
);
return (
<Card className="overflow-hidden">
<div className="flex flex-wrap items-center gap-2 border-b border-border p-3">
<div className="relative min-w-48 flex-1">
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted" />
<Input className="pl-9" placeholder="Search…" value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search" />
</div>
{namespaces && (
<div className="w-36">
<Select aria-label="Namespace" value={filter} onChange={(e) => setFilter(Number(e.target.value))}>
{namespaces.map((n, i) => (
<option key={n.label} value={i}>
{n.label}
</option>
))}
</Select>
</div>
)}
</div>
<div className="hidden grid-cols-[2rem_minmax(0,2fr)_minmax(0,3fr)_5rem_4.25rem] gap-x-3 border-b border-border bg-surface-2/40 px-5 py-2 text-xs font-medium text-muted uppercase md:grid">
<span />
<span>{kind === "redirect" ? "Short link" : "Page"}</span>
<span>{kind === "redirect" ? "Destination" : "Title"}</span>
<span className="text-right">Clicks</span>
<span />
</div>
{!pages ? (
<div className="flex flex-col gap-3 p-5">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-10" />
))}
</div>
) : visible.length ? (
<div className="divide-y divide-border">
{visible.map((p) => (
<Row key={p.id} page={p} showNamespace={!!namespaces} />
))}
</div>
) : ofKind.length ? (
<EmptyState icon={<Search />} title="No matches" description={namespaces ? "Try a different search or filter." : "Try a different search."} />
) : (
<EmptyState icon={kind === "redirect" ? <Link2 /> : <PanelsTopLeft />} title={empty.title} description={empty.description} action={empty.action} />
)}
</Card>
);
}
+55
View File
@@ -0,0 +1,55 @@
import { Monitor, Moon, Sun } from "lucide-react";
import { cx } from "../lib/cx.js";
import { setThemePreference, useThemePreference, type ThemePreference } from "../lib/theme.js";
import { Button } from "./ui/button.js";
const OPTIONS: { value: ThemePreference; label: string; icon: typeof Sun }[] = [
{ value: "system", label: "System", icon: Monitor },
{ value: "light", label: "Light", icon: Sun },
{ value: "dark", label: "Dark", icon: Moon },
];
// Three-way switch for the sidebar.
export function ThemeSwitch() {
const current = useThemePreference();
return (
<div role="radiogroup" aria-label="Color mode" className="flex rounded-lg border border-border bg-surface-2 p-0.5">
{OPTIONS.map(({ value, label, icon: Icon }) => (
<button
key={value}
type="button"
role="radio"
aria-checked={current === value}
title={label}
onClick={() => setThemePreference(value)}
className={cx(
"flex h-7 flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md text-xs font-medium transition",
current === value ? "bg-surface text-fg shadow-sm" : "text-muted hover:text-fg",
)}
>
<Icon className="size-3.5" />
{label}
</button>
))}
</div>
);
}
// Compact button that cycles system → light → dark, for the mobile top bar.
export function ThemeCycleButton() {
const current = useThemePreference();
const index = OPTIONS.findIndex((o) => o.value === current);
const { icon: Icon, label } = OPTIONS[index]!;
const next = OPTIONS[(index + 1) % OPTIONS.length]!;
return (
<Button
variant="ghost"
size="icon-sm"
onClick={() => setThemePreference(next.value)}
aria-label={`Color mode: ${label}. Switch to ${next.label}`}
title={`Color mode: ${label}`}
>
<Icon />
</Button>
);
}
+42
View File
@@ -102,3 +102,45 @@ export function ColorInput({ value, onChange, label }: { value: string; onChange
</div> </div>
); );
} }
// On/off switch with a label and optional description, e.g. for settings.
export function Switch({
checked,
onChange,
label,
description,
disabled,
}: {
checked: boolean;
onChange: (checked: boolean) => void;
label: string;
description?: ReactNode;
disabled?: boolean;
}) {
const id = useId();
return (
<div className={cx("flex items-start justify-between gap-4", disabled && "opacity-60")}>
<div className="min-w-0">
<label htmlFor={id} className="text-sm font-medium text-fg">
{label}
</label>
{description && <div className="mt-0.5 text-xs text-muted">{description}</div>}
</div>
<button
id={id}
type="button"
role="switch"
aria-checked={checked}
disabled={disabled}
onClick={() => onChange(!checked)}
className={cx(
"relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:cursor-not-allowed",
checked ? "bg-accent" : "bg-border-strong",
)}
>
<span className={cx("inline-block size-5 rounded-full bg-white shadow transition-transform", checked ? "translate-x-5.5" : "translate-x-0.5")} />
</button>
</div>
);
}
+4 -7
View File
@@ -1,16 +1,13 @@
import { useState, type ReactNode } from "react"; import { useState, type AnchorHTMLAttributes, type ReactNode } from "react";
import { Check, Copy } from "lucide-react"; import { Check, Copy } from "lucide-react";
import { cx } from "../../lib/cx.js"; import { cx } from "../../lib/cx.js";
import { linkHandler } from "../../router.js"; import { linkHandler } from "../../router.js";
import { Button } from "./button.js"; import { Button } from "./button.js";
import { useToast } from "./toast.js"; import { useToast } from "./toast.js";
export function Link({ to, className, children, ...rest }: { to: string; className?: string; children: ReactNode; "aria-current"?: "page" }) { // In-app link: a normal <a> that navigates without a page reload.
return ( export function Link({ to, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) {
<a href={to} onClick={linkHandler(to)} className={className} {...rest}> return <a href={to} onClick={linkHandler(to)} {...rest} />;
{children}
</a>
);
} }
export function publicUrl(path: string): string { export function publicUrl(path: string): string {
+1
View File
@@ -8,6 +8,7 @@
<link rel="manifest" href="/~/manifest.webmanifest" /> <link rel="manifest" href="/~/manifest.webmanifest" />
<link rel="apple-touch-icon" href="/~/icon-192x192.png" /> <link rel="apple-touch-icon" href="/~/icon-192x192.png" />
<title>short</title> <title>short</title>
<script src="/~/theme-init.js"></script>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+2 -1
View File
@@ -2,7 +2,8 @@
export function stripMarkdown(markdown: string): string { export function stripMarkdown(markdown: string): string {
return markdown return markdown
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`#>~]/g, "") .replace(/^\s*(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "")
.replace(/[*_`~]/g, "")
.replace(/\s+/g, " ") .replace(/\s+/g, " ")
.trim(); .trim();
} }
+81
View File
@@ -0,0 +1,81 @@
import type { Theme } from "../../shared/validation.js";
// Turning coolors.co palettes (5–10 colors) into a link page theme (4 roles).
function hexList(dashed: string): string[] {
return dashed.split("-").map((h) => `#${h.toLowerCase()}`);
}
// Accepts coolors.co links (generator "coolors.co/264653-2a9d8f-…" or "coolors.co/palette/264653-…")
// as well as a bare "264653-2a9d8f-…" list. The colors are part of the URL, so nothing needs to be fetched.
export function parseCoolorsInput(input: string): string[] | null {
const value = input.trim();
if (!value) return null;
let candidate = value;
if (/^(https?:\/\/)?([a-z0-9-]+\.)*coolors\.co\//i.test(value)) {
try {
const url = new URL(/^https?:\/\//i.test(value) ? value : `https://${value}`);
candidate = url.pathname.split("/").filter(Boolean).pop() ?? "";
} catch {
return null;
}
}
if (!/^([0-9a-f]{6}-)+[0-9a-f]{6}$/i.test(candidate)) return null;
const colors = hexList(candidate);
return colors.length >= 2 && colors.length <= 10 ? colors : null;
}
function channels(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
// WCAG relative luminance and contrast ratio.
function luminance(hex: string): number {
const [r, g, b] = channels(hex).map((c) => {
const s = c / 255;
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
}) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
export function contrast(a: string, b: string): number {
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number];
return (hi + 0.05) / (lo + 0.05);
}
function saturation(hex: string): number {
const [r, g, b] = channels(hex).map((c) => c / 255) as [number, number, number];
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
return max === min ? 0 : (max - min) / (1 - Math.abs(2 * l - 1));
}
const maxBy = <T>(items: T[], score: (item: T) => number): T =>
items.reduce((best, item) => (score(item) > score(best) ? item : best));
export type Variant = "dark" | "light";
// Background: darkest (or lightest) color. Text: the color that reads best on it.
// Buttons: the most colorful remaining color that stands out from the background.
// White or black is used whenever no palette color is readable enough.
export function themeFromPalette(colors: string[], variant: Variant): Theme {
const byLuminance = [...colors].sort((a, b) => luminance(a) - luminance(b));
const background = variant === "dark" ? byLuminance[0]! : byLuminance[byLuminance.length - 1]!;
const rest = colors.filter((c) => c !== background);
const readable = (on: string, options: string[]) => {
const best = maxBy([...options, "#ffffff", "#000000"], (c) => contrast(c, on));
const fromPalette = options.filter((c) => contrast(c, on) >= 4.5);
return fromPalette.length ? maxBy(fromPalette, (c) => contrast(c, on)) : best;
};
const text = readable(background, rest);
const buttonCandidates = rest.filter((c) => c !== text);
const visible = buttonCandidates.filter((c) => contrast(c, background) >= 1.4);
const button = (visible.length ? maxBy(visible, saturation) : buttonCandidates[0]) ?? text;
const buttonText = readable(button, colors.filter((c) => c !== button));
return { background, text, button, buttonText };
}
+17
View File
@@ -0,0 +1,17 @@
import type { Me, PageSummary } from "../../shared/api-types.js";
import type { NamespaceOption } from "../components/PageTable.js";
// "Your" content: your own namespace, plus root for admins. Other users' content is managed under Administration.
export function isMine(page: Pick<PageSummary, "namespace">, me: Me): boolean {
return page.namespace === me.username || (me.isAdmin && page.namespace === "");
}
// Namespace filter for admins, who see both their own and root content.
export function myNamespaceOptions(me: Me): NamespaceOption[] | undefined {
if (!me.isAdmin) return undefined;
return [
{ label: "All", match: () => true },
{ label: `/${me.username}/`, match: (ns) => ns === me.username },
{ label: "Root /", match: (ns) => ns === "" },
];
}
+50
View File
@@ -0,0 +1,50 @@
import { useSyncExternalStore } from "react";
// Light/dark preference of the admin UI. "system" follows the OS setting.
// theme-init.js applies the same logic before the app loads.
export type ThemePreference = "system" | "light" | "dark";
const STORAGE_KEY = "short-theme";
const media = matchMedia("(prefers-color-scheme: dark)");
const listeners = new Set<() => void>();
function readPreference(): ThemePreference {
const stored = localStorage.getItem(STORAGE_KEY);
return stored === "light" || stored === "dark" ? stored : "system";
}
let preference = readPreference();
function resolved(): "light" | "dark" {
return preference === "system" ? (media.matches ? "dark" : "light") : preference;
}
function apply() {
document.documentElement.dataset.theme = resolved();
listeners.forEach((l) => l());
}
media.addEventListener("change", () => {
if (preference === "system") apply();
});
export function setThemePreference(next: ThemePreference) {
preference = next;
if (next === "system") localStorage.removeItem(STORAGE_KEY);
else localStorage.setItem(STORAGE_KEY, next);
apply();
}
const subscribe = (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
export function useThemePreference(): ThemePreference {
return useSyncExternalStore(subscribe, () => preference);
}
export function useResolvedTheme(): "light" | "dark" {
return useSyncExternalStore(subscribe, resolved);
}
+8
View File
@@ -0,0 +1,8 @@
// Applies the saved light/dark preference before the first paint to avoid a flash.
(function () {
try {
var pref = localStorage.getItem("short-theme") || "system";
var dark = pref === "dark" || (pref === "system" && matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.dataset.theme = dark ? "dark" : "light";
} catch (e) {}
})();
+39 -3
View File
@@ -33,19 +33,47 @@ export function linkHandler(to: string) {
export type Route = export type Route =
| { name: "overview" } | { name: "overview" }
| { name: "list"; kind: PageKind } | { name: "list"; kind: PageKind }
| { name: "detail"; kind: PageKind; id: number; tab: string | undefined } /** `owner` is set when an admin opens another user's page via Administration. */
| { name: "detail"; kind: PageKind; id: number; tab: string | undefined; owner?: string }
| { name: "tokens" } | { name: "tokens" }
| { name: "admin" } | { name: "admin" }
| { name: "adminUser"; username: string }
| { name: "notFound" }; | { name: "notFound" };
const KIND_SEGMENT: Record<string, PageKind> = { links: "redirect", pages: "linkpage" }; const KIND_SEGMENT: Record<string, PageKind> = { links: "redirect", pages: "linkpage" };
// The signed-in user. Pages of other users are addressed through Administration,
// so the admin's own and root content stays separate from managing everyone else's.
let viewer: string | null = null;
export function setViewer(username: string) {
viewer = username;
}
const isOtherUsers = (namespace: string | undefined) => namespace !== undefined && namespace !== "" && namespace !== viewer;
export function listPath(kind: PageKind): string { export function listPath(kind: PageKind): string {
return kind === "redirect" ? "/~/links" : "/~/pages"; return kind === "redirect" ? "/~/links" : "/~/pages";
} }
export function detailPath(page: { id: number; kind: PageKind }, tab?: string): string { export function adminUserPath(username: string): string {
return `${listPath(page.kind)}/${page.id}${tab ? `/${tab}` : ""}`; return `/~/admin/users/${encodeURIComponent(username)}`;
}
export function detailPath(page: { id: number; kind: PageKind; namespace?: string }, tab?: string): string {
const segment = page.kind === "redirect" ? "links" : "pages";
const base = isOtherUsers(page.namespace) ? `${adminUserPath(page.namespace!)}/${segment}` : `/~/${segment}`;
return `${base}/${page.id}${tab ? `/${tab}` : ""}`;
}
// Where "back" leads from a page: its owner's admin view for other users' pages, otherwise the list.
export function backPath(page: { kind: PageKind; namespace: string }): string {
return isOtherUsers(page.namespace) ? adminUserPath(page.namespace) : listPath(page.kind);
}
// Replaces the current URL (no new history entry), e.g. to correct a link to the canonical address.
export function replacePath(to: string) {
history.replaceState(null, "", to);
listeners.forEach((l) => l());
} }
export function parseRoute(path: string): Route { export function parseRoute(path: string): Route {
@@ -53,6 +81,14 @@ export function parseRoute(path: string): Route {
if (p === "/~") return { name: "overview" }; if (p === "/~") return { name: "overview" };
if (p === "/~/tokens") return { name: "tokens" }; if (p === "/~/tokens") return { name: "tokens" };
if (p === "/~/admin") return { name: "admin" }; if (p === "/~/admin") return { name: "admin" };
const user = p.match(/^\/~\/admin\/users\/([^/]+)(?:\/(links|pages)\/(\d+)(?:\/([a-z]+))?)?$/);
if (user) {
const username = decodeURIComponent(user[1]!);
if (!user[2]) return { name: "adminUser", username };
return { name: "detail", kind: KIND_SEGMENT[user[2]]!, id: Number(user[3]), tab: user[4], owner: username };
}
const m = p.match(/^\/~\/(links|pages)(?:\/(\d+)(?:\/([a-z]+))?)?$/); const m = p.match(/^\/~\/(links|pages)(?:\/(\d+)(?:\/([a-z]+))?)?$/);
if (m) { if (m) {
const kind = KIND_SEGMENT[m[1]!]!; const kind = KIND_SEGMENT[m[1]!]!;
+51 -37
View File
@@ -1,13 +1,13 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { PinOff, TriangleAlert, Users } from "lucide-react"; import { ChevronRight, PinOff, TriangleAlert, Users } from "lucide-react";
import type { Conflict, PageSummary } from "../../shared/api-types.js"; import type { Conflict, Me, PageSummary } from "../../shared/api-types.js";
import { api, useApi } from "../api.js"; import { api, useApi } from "../api.js";
import { Button } from "../components/ui/button.js"; import { Button } from "../components/ui/button.js";
import { Select } from "../components/ui/form.js"; import { Select } from "../components/ui/form.js";
import { Link } from "../components/ui/misc.js"; import { Link } from "../components/ui/misc.js";
import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js"; import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { useAction } from "../components/ui/toast.js"; import { useAction } from "../components/ui/toast.js";
import { detailPath } from "../router.js"; import { adminUserPath, detailPath } from "../router.js";
function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => Promise<void> }) { function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => Promise<void> }) {
const pinned = pages.find((p) => p.pinned); const pinned = pages.find((p) => p.pinned);
@@ -52,19 +52,61 @@ function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => P
); );
} }
export function AdminScreen() { function UsersCard({ users, pages, me }: { users: string[] | undefined; pages: PageSummary[] | undefined; me: Me }) {
const others = users?.filter((u) => u !== me.username);
const stats = (u: string) => {
const theirs = (pages ?? []).filter((p) => p.namespace === u);
const links = theirs.filter((p) => p.kind === "redirect").length;
const linkPages = theirs.length - links;
const clicks = theirs.reduce((sum, p) => sum + p.totalClicks, 0);
return `${links} ${links === 1 ? "link" : "links"} · ${linkPages} ${linkPages === 1 ? "page" : "pages"} · ${clicks.toLocaleString()} clicks`;
};
return (
<Card className="overflow-hidden">
<CardHeader
title="Users"
description="Open a user to manage their short links and link pages. Your own and root content is under Short links and Link pages."
actions={others && <Badge>{others.length}</Badge>}
/>
{!others ? (
<Skeleton className="m-5 h-10" />
) : others.length ? (
<ul className="divide-y divide-border">
{others.map((u) => (
<li key={u} className="group relative flex items-center gap-3 px-5 py-3 transition-colors hover:bg-surface-2/60">
<span className="flex size-8 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
{u.charAt(0)}
</span>
<div className="min-w-0 flex-1">
<Link to={adminUserPath(u)} className="font-medium after:absolute after:inset-0">
{u}
</Link>
<div className="truncate text-xs text-muted">{pages ? stats(u) : " "}</div>
</div>
<ChevronRight className="size-4 text-muted transition-transform group-hover:translate-x-0.5" />
</li>
))}
</ul>
) : (
<EmptyState icon={<Users />} title="No other users yet" description="Users appear here after their first sign-in." />
)}
</Card>
);
}
export function AdminScreen({ me }: { me: Me }) {
const pages = useApi<PageSummary[]>("/pages"); const pages = useApi<PageSummary[]>("/pages");
const users = useApi<string[]>("/users"); const users = useApi<string[]>("/users");
const conflicts = useApi<Conflict[]>("/conflicts"); const conflicts = useApi<Conflict[]>("/conflicts");
const countByUser = new Map<string, number>();
for (const p of pages.data ?? []) countByUser.set(p.namespace, (countByUser.get(p.namespace) ?? 0) + 1);
return ( return (
<> <>
<PageHeader title="Administration" description="Settings that affect the whole instance." /> <PageHeader title="Administration" description="Other users' content and settings that affect the whole instance." />
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-6">
<UsersCard users={users.data} pages={pages.data} me={me} />
{pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />} {pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />}
<Card> <Card>
@@ -80,7 +122,7 @@ export function AdminScreen() {
<li key={c.pageId} className="flex items-center gap-3 px-5 py-3"> <li key={c.pageId} className="flex items-center gap-3 px-5 py-3">
<TriangleAlert className="size-4 text-warning-soft-fg" /> <TriangleAlert className="size-4 text-warning-soft-fg" />
<span className="flex-1 font-mono text-sm">/{c.username}</span> <span className="flex-1 font-mono text-sm">/{c.username}</span>
<Link to={detailPath({ id: c.pageId, kind: "redirect" }, "settings")} className="text-sm text-accent hover:underline"> <Link to={detailPath({ id: c.pageId, kind: "redirect", namespace: "" }, "settings")} className="text-sm text-accent hover:underline">
Open root link Open root link
</Link> </Link>
</li> </li>
@@ -90,34 +132,6 @@ export function AdminScreen() {
<CardBody className="text-sm text-muted">No conflicts.</CardBody> <CardBody className="text-sm text-muted">No conflicts.</CardBody>
)} )}
</Card> </Card>
<Card className="overflow-hidden">
<CardHeader
title="Users"
description="Everyone who has signed in. Admin rights and usernames are managed in Authentik."
actions={users.data && <Badge>{users.data.length}</Badge>}
/>
{!users.data ? (
<Skeleton className="m-5 h-10" />
) : users.data.length ? (
<ul className="divide-y divide-border">
{users.data.map((u) => (
<li key={u} className="flex items-center gap-3 px-5 py-3">
<span className="flex size-8 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
{u.charAt(0)}
</span>
<span className="flex-1 font-mono text-sm">/{u}/</span>
<span className="text-sm text-muted">
{countByUser.get(u) ?? 0} {(countByUser.get(u) ?? 0) === 1 ? "page" : "pages"}
</span>
</li>
))}
</ul>
) : (
<EmptyState icon={<Users />} title="No users yet" />
)}
</Card>
</div> </div>
</> </>
); );
+147
View File
@@ -0,0 +1,147 @@
import { useState } from "react";
import { ChevronRight, Link2, MousePointerClick, PanelsTopLeft, Plus, ShieldOff, UserX } from "lucide-react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { api, useApi } from "../api.js";
import { CreatePageDialog } from "../components/CreatePageDialog.js";
import { PageTable } from "../components/PageTable.js";
import { Button, buttonClass } from "../components/ui/button.js";
import { Link, Stat } from "../components/ui/misc.js";
import { useConfirm } from "../components/ui/dialog.js";
import { Card, CardHeader, EmptyState, Skeleton } from "../components/ui/surface.js";
import { useAction, useToast } from "../components/ui/toast.js";
import { detailPath, navigate } from "../router.js";
// Offboarding: ends the user's sessions and deletes their API tokens. Their content stays online.
function RevokeAccessCard({ username }: { username: string }) {
const confirm = useConfirm();
const { busy, run } = useAction();
const toast = useToast();
const revoke = async () => {
const ok = await confirm({
title: `Revoke ${username}'s access?`,
description: `${username} is signed out everywhere and their API tokens are deleted. Their links and pages stay online. To stop them from signing in again, remove their access in Authentik.`,
confirmLabel: "Revoke access",
danger: true,
});
if (!ok) return;
void run(async () => {
const { sessions, tokens } = await api<{ sessions: number; tokens: number }>("DELETE", `/users/${encodeURIComponent(username)}/access`);
toast(`Ended ${sessions} ${sessions === 1 ? "session" : "sessions"}, deleted ${tokens} API ${tokens === 1 ? "token" : "tokens"}`);
});
};
return (
<Card className="border-danger/30">
<CardHeader
title={<span className="text-danger">Revoke access</span>}
description="Sign this user out everywhere and delete their API tokens, e.g. when they leave. Their links and pages stay online."
actions={
<Button variant="danger" size="sm" icon={<ShieldOff />} loading={busy} onClick={() => void revoke()}>
Revoke access
</Button>
}
/>
</Card>
);
}
// Everything one user owns, for admins. Kept apart from the admin's own and root content.
export function AdminUserScreen({ username, me }: { username: string; me: Me }) {
const users = useApi<string[]>("/users");
const pages = useApi<PageSummary[]>("/pages");
const toast = useToast();
const [creating, setCreating] = useState<PageKind | null>(null);
if (users.data && !users.data.includes(username)) {
return (
<EmptyState
icon={<UserX />}
title="User not found"
description={`Nobody called "${username}" has signed in yet.`}
action={
<Link to="/~/admin" className={buttonClass("secondary")}>
Back to Administration
</Link>
}
/>
);
}
const theirs = pages.data?.filter((p) => p.namespace === username);
const count = (kind: PageKind) => theirs?.filter((p) => p.kind === kind).length ?? 0;
const clicks = theirs?.reduce((sum, p) => sum + p.totalClicks, 0) ?? 0;
return (
<>
<nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb">
<Link to="/~/admin" className="hover:text-fg">
Administration
</Link>
<ChevronRight className="size-3.5" />
<span className="text-fg">{username}</span>
</nav>
<header className="mb-6 flex flex-wrap items-center gap-4 lg:mb-8">
<span className="flex size-12 items-center justify-center rounded-full bg-accent-soft text-lg font-semibold text-accent-soft-fg uppercase">
{username.charAt(0)}
</span>
<div className="min-w-0 flex-1">
<h1 className="truncate text-2xl font-semibold tracking-tight">{username}</h1>
<p className="mt-0.5 text-sm text-muted">
Manage the links and pages under <span className="font-mono">/{username}/</span>.
</p>
</div>
<div className="flex flex-wrap gap-2">
<Button icon={<Plus />} onClick={() => setCreating("redirect")}>
New short link
</Button>
<Button variant="secondary" icon={<PanelsTopLeft />} onClick={() => setCreating("linkpage")}>
New link page
</Button>
</div>
</header>
<div className="flex flex-col gap-8">
<div className="grid grid-cols-3 gap-3 sm:gap-4">
{theirs ? (
<>
<Stat label="Short links" value={count("redirect")} icon={<Link2 />} />
<Stat label="Link pages" value={count("linkpage")} icon={<PanelsTopLeft />} />
<Stat label="Total clicks" value={clicks.toLocaleString()} icon={<MousePointerClick />} />
</>
) : (
[0, 1, 2].map((i) => <Skeleton key={i} className="h-24 rounded-xl" />)
)}
</div>
<section>
<h2 className="mb-3 text-base font-semibold">Short links</h2>
<PageTable kind="redirect" pages={theirs} empty={{ title: "No short links", description: `${username} hasn't created any short links.` }} />
</section>
<section>
<h2 className="mb-3 text-base font-semibold">Link pages</h2>
<PageTable kind="linkpage" pages={theirs} empty={{ title: "No link pages", description: `${username} hasn't created any link pages.` }} />
</section>
<RevokeAccessCard username={username} />
</div>
{creating && (
<CreatePageDialog
kind={creating}
me={me}
open
fixedNamespace={username}
onClose={() => setCreating(null)}
onCreated={(page) => {
if (page.kind === "linkpage") return navigate(detailPath(page));
toast(`Created ${page.path}`);
void pages.reload();
}}
/>
)}
</>
);
}
+16 -107
View File
@@ -1,19 +1,21 @@
import { useMemo, useState } from "react"; import { useState } from "react";
import { ChevronRight, Link2, PanelsTopLeft, Pin, Plus, Search } from "lucide-react"; import { Plus } from "lucide-react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js"; import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { useApi } from "../api.js"; import { useApi } from "../api.js";
import { CreatePageDialog } from "../components/CreatePageDialog.js"; import { CreatePageDialog } from "../components/CreatePageDialog.js";
import { PageTable } from "../components/PageTable.js";
import { Button } from "../components/ui/button.js"; import { Button } from "../components/ui/button.js";
import { Input, Select } from "../components/ui/form.js"; import { publicUrl } from "../components/ui/misc.js";
import { CopyButton, DomainIcon, Link, publicUrl } from "../components/ui/misc.js"; import { PageHeader } from "../components/ui/surface.js";
import { Badge, Card, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { useToast } from "../components/ui/toast.js"; import { useToast } from "../components/ui/toast.js";
import { isMine, myNamespaceOptions } from "../lib/scope.js";
import { detailPath, navigate } from "../router.js"; import { detailPath, navigate } from "../router.js";
const COPY: Record<PageKind, { title: string; description: string; create: string; empty: string; emptyText: string }> = { const COPY: Record<PageKind, { title: string; description: string; adminDescription: string; create: string; empty: string; emptyText: string }> = {
redirect: { redirect: {
title: "Short links", title: "Short links",
description: "Short URLs that redirect to another address.", description: "Short URLs that redirect to another address.",
adminDescription: "Your short links and root links. Other users' links are under Administration.",
create: "New short link", create: "New short link",
empty: "No short links yet", empty: "No short links yet",
emptyText: "Create your first short link to share long URLs and track clicks.", emptyText: "Create your first short link to share long URLs and track clicks.",
@@ -21,66 +23,19 @@ const COPY: Record<PageKind, { title: string; description: string; create: strin
linkpage: { linkpage: {
title: "Link pages", title: "Link pages",
description: "Pages that collect several links, like a link in bio.", description: "Pages that collect several links, like a link in bio.",
adminDescription: "Your link pages and root pages. Other users' pages are under Administration.",
create: "New link page", create: "New link page",
empty: "No link pages yet", empty: "No link pages yet",
emptyText: "Create a page with your avatar, link buttons and some text.", emptyText: "Create a page with your avatar, link buttons and some text.",
}, },
}; };
function Row({ page }: { page: PageSummary }) {
const isLink = page.kind === "redirect";
return (
<div className="group relative grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-4 py-3 transition-colors hover:bg-surface-2/60 md:grid-cols-[auto_minmax(0,2fr)_minmax(0,3fr)_5rem_auto] md:px-5">
{isLink ? (
<DomainIcon url={page.dest} />
) : (
<span className="flex size-8 items-center justify-center rounded-lg bg-accent-soft text-accent-soft-fg">
<PanelsTopLeft className="size-4" />
</span>
)}
<div className="min-w-0">
<div className="flex items-center gap-2">
{/* The link stretches over the whole row; the copy button sits above it. */}
<Link to={detailPath(page)} className="truncate font-mono text-sm font-medium text-fg after:absolute after:inset-0">
{page.path}
</Link>
{page.pinned && (
<Badge tone="accent" icon={<Pin />}>
Home
</Badge>
)}
</div>
<div className="truncate text-sm text-muted md:hidden">{isLink ? page.dest : page.title}</div>
</div>
<div className="hidden truncate text-sm text-muted md:block">{isLink ? page.dest : page.title}</div>
<div className="hidden text-right text-sm text-muted tabular-nums md:block">{page.totalClicks.toLocaleString()}</div>
<div className="flex items-center gap-1">
<div className="relative z-10">
<CopyButton value={publicUrl(page.path)} />
</div>
<ChevronRight className="hidden size-4 text-muted transition-transform group-hover:translate-x-0.5 md:block" />
</div>
</div>
);
}
export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) { export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) {
const pages = useApi<PageSummary[]>("/pages"); const pages = useApi<PageSummary[]>("/pages");
const toast = useToast(); const toast = useToast();
const [query, setQuery] = useState("");
const [namespace, setNamespace] = useState<string | null>(null);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const copy = COPY[kind]; const copy = COPY[kind];
const ofKind = useMemo(() => (pages.data ?? []).filter((p) => p.kind === kind), [pages.data, kind]);
const namespaces = useMemo(() => [...new Set(ofKind.map((p) => p.namespace))].sort(), [ofKind]);
const q = query.trim().toLowerCase();
const visible = ofKind.filter(
(p) =>
(namespace === null || p.namespace === namespace) &&
(!q || p.path.toLowerCase().includes(q) || (p.dest ?? p.title ?? "").toLowerCase().includes(q)),
);
const created = async (page: PageSummary) => { const created = async (page: PageSummary) => {
if (page.kind === "linkpage") return navigate(detailPath(page)); if (page.kind === "linkpage") return navigate(detailPath(page));
await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {}); await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {});
@@ -96,59 +51,13 @@ export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) {
return ( return (
<> <>
<PageHeader title={copy.title} description={copy.description} actions={createButton} /> <PageHeader title={copy.title} description={me.isAdmin ? copy.adminDescription : copy.description} actions={createButton} />
<PageTable
<Card className="overflow-hidden"> kind={kind}
<div className="flex flex-wrap items-center gap-2 border-b border-border p-3"> pages={pages.data?.filter((p) => isMine(p, me))}
<div className="relative min-w-48 flex-1"> namespaces={myNamespaceOptions(me)}
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted" /> empty={{ title: copy.empty, description: copy.emptyText, action: createButton }}
<Input className="pl-9" placeholder="Search…" value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search" /> />
</div>
{me.isAdmin && namespaces.length > 1 && (
<div className="w-44">
<Select
aria-label="Namespace"
value={namespace ?? "*"}
onChange={(e) => setNamespace(e.target.value === "*" ? null : e.target.value)}
>
<option value="*">All namespaces</option>
{namespaces.map((ns) => (
<option key={ns} value={ns}>
{ns ? `/${ns}/` : "Root /"}
</option>
))}
</Select>
</div>
)}
</div>
<div className="hidden grid-cols-[2rem_minmax(0,2fr)_minmax(0,3fr)_5rem_4.25rem] gap-x-3 border-b border-border bg-surface-2/40 px-5 py-2 text-xs font-medium text-muted uppercase md:grid">
<span />
<span>{kind === "redirect" ? "Short link" : "Page"}</span>
<span>{kind === "redirect" ? "Destination" : "Title"}</span>
<span className="text-right">Clicks</span>
<span />
</div>
{!pages.data ? (
<div className="flex flex-col gap-3 p-5">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-10" />
))}
</div>
) : visible.length ? (
<div className="divide-y divide-border">
{visible.map((p) => (
<Row key={p.id} page={p} />
))}
</div>
) : ofKind.length ? (
<EmptyState icon={<Search />} title="No matches" description="Try a different search or namespace." />
) : (
<EmptyState icon={kind === "redirect" ? <Link2 /> : <PanelsTopLeft />} title={copy.empty} description={copy.emptyText} action={createButton} />
)}
</Card>
<CreatePageDialog kind={kind} me={me} open={creating} onClose={() => setCreating(false)} onCreated={created} /> <CreatePageDialog kind={kind} me={me} open={creating} onClose={() => setCreating(false)} onCreated={created} />
</> </>
); );
+8 -6
View File
@@ -6,6 +6,7 @@ import { CreatePageDialog } from "../components/CreatePageDialog.js";
import { Button, buttonClass } from "../components/ui/button.js"; import { Button, buttonClass } from "../components/ui/button.js";
import { DomainIcon, Link, Stat } from "../components/ui/misc.js"; import { DomainIcon, Link, Stat } from "../components/ui/misc.js";
import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js"; import { Alert, Card, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { isMine } from "../lib/scope.js";
import { detailPath, navigate } from "../router.js"; import { detailPath, navigate } from "../router.js";
function TopPages({ pages }: { pages: PageSummary[] }) { function TopPages({ pages }: { pages: PageSummary[] }) {
@@ -47,11 +48,12 @@ export function OverviewScreen({ me }: { me: Me }) {
const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null); const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null);
const [creating, setCreating] = useState<PageKind | null>(null); const [creating, setCreating] = useState<PageKind | null>(null);
const all = pages.data ?? []; // Admins see their own and root content here; other users' content is under Administration.
const all = (pages.data ?? []).filter((p) => isMine(p, me));
const links = all.filter((p) => p.kind === "redirect"); const links = all.filter((p) => p.kind === "redirect");
const linkPages = all.filter((p) => p.kind === "linkpage"); const linkPages = all.filter((p) => p.kind === "linkpage");
const clicks = all.reduce((sum, p) => sum + p.totalClicks, 0); const clicks = all.reduce((sum, p) => sum + p.totalClicks, 0);
const scope = me.isAdmin ? "across all namespaces" : `in /${me.username}/`; const scope = me.isAdmin ? "yours & root" : `in /${me.username}/`;
return ( return (
<> <>
@@ -60,12 +62,12 @@ export function OverviewScreen({ me }: { me: Me }) {
description="Here's how your links are doing." description="Here's how your links are doing."
actions={ actions={
<> <>
<Button variant="secondary" icon={<PanelsTopLeft />} onClick={() => setCreating("linkpage")}>
New link page
</Button>
<Button icon={<Plus />} onClick={() => setCreating("redirect")}> <Button icon={<Plus />} onClick={() => setCreating("redirect")}>
New short link New short link
</Button> </Button>
<Button variant="secondary" icon={<PanelsTopLeft />} onClick={() => setCreating("linkpage")}>
New link page
</Button>
</> </>
} }
/> />
@@ -76,7 +78,7 @@ export function OverviewScreen({ me }: { me: Me }) {
{conflicts.data.map((c, i) => ( {conflicts.data.map((c, i) => (
<span key={c.pageId}> <span key={c.pageId}>
{i > 0 && ", "} {i > 0 && ", "}
<Link to={detailPath({ id: c.pageId, kind: "redirect" }, "settings")} className="font-mono underline"> <Link to={detailPath({ id: c.pageId, kind: "redirect", namespace: "" }, "settings")} className="font-mono underline">
/{c.username} /{c.username}
</Link> </Link>
</span> </span>
+4 -14
View File
@@ -10,26 +10,16 @@ import { Segmented } from "../../components/ui/form.js";
import { Stat } from "../../components/ui/misc.js"; import { Stat } from "../../components/ui/misc.js";
import { Card, CardHeader, Skeleton } from "../../components/ui/surface.js"; import { Card, CardHeader, Skeleton } from "../../components/ui/surface.js";
import { useAction } from "../../components/ui/toast.js"; import { useAction } from "../../components/ui/toast.js";
import { useResolvedTheme } from "../../lib/theme.js";
type Range = 7 | 30 | 90; type Range = 7 | 30 | 90;
const cssVar = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim(); const cssVar = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
// Re-renders when the system switches between light and dark, so the chart picks up the new colors.
function useColorScheme() {
const [dark, setDark] = useState(() => matchMedia("(prefers-color-scheme: dark)").matches);
useEffect(() => {
const mq = matchMedia("(prefers-color-scheme: dark)");
const update = () => setDark(mq.matches);
mq.addEventListener("change", update);
return () => mq.removeEventListener("change", update);
}, []);
return dark;
}
function Chart({ series }: { series: StatsDay[] }) { function Chart({ series }: { series: StatsDay[] }) {
const container = useRef<HTMLDivElement>(null); const container = useRef<HTMLDivElement>(null);
const dark = useColorScheme(); // Redraw when light/dark mode changes so the chart picks up the new colors.
const mode = useResolvedTheme();
useEffect(() => { useEffect(() => {
const el = container.current; const el = container.current;
@@ -70,7 +60,7 @@ function Chart({ series }: { series: StatsDay[] }) {
resize.disconnect(); resize.disconnect();
plot.destroy(); plot.destroy();
}; };
}, [series, dark]); }, [series, mode]);
return <div ref={container} className="w-full" />; return <div ref={container} className="w-full" />;
} }
+88 -64
View File
@@ -1,46 +1,72 @@
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { Check, ImageUp, Trash2 } from "lucide-react"; import { ImageUp, Trash2 } from "lucide-react";
import type { PageDetail } from "../../../shared/api-types.js"; import type { Me, PageDetail } from "../../../shared/api-types.js";
import type { Theme } from "../../../shared/validation.js"; import type { Theme } from "../../../shared/validation.js";
import { api } from "../../api.js"; import { api } from "../../api.js";
import { Button } from "../../components/ui/button.js"; import { Button } from "../../components/ui/button.js";
import { ColorInput, Field, Input } from "../../components/ui/form.js"; import { Field, Input, Switch } from "../../components/ui/form.js";
import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js"; import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
import { useAction } from "../../components/ui/toast.js"; import { useAction } from "../../components/ui/toast.js";
import { cx } from "../../lib/cx.js";
import { stripMarkdown } from "../../lib/markdown.js"; import { stripMarkdown } from "../../lib/markdown.js";
import { PhoneFrame } from "./PhonePreview.js"; import { PhoneFrame } from "./PhonePreview.js";
import { sameTheme, ThemePicker } from "./ThemePicker.js";
const PRESETS: { name: string; theme: Theme }[] = [ // Button icon like on the public page: the website's logo when logos are on, otherwise its first letter.
{ name: "Midnight", theme: { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" } }, function MockIcon({ dest, logoDevToken }: { dest: string | null; logoDevToken: string | null }) {
{ name: "Paper", theme: { background: "#fafaf9", text: "#1c1917", button: "#1c1917", buttonText: "#fafaf9" } }, const [failed, setFailed] = useState(false);
{ name: "Violet", theme: { background: "#2e1065", text: "#ede9fe", button: "#7c3aed", buttonText: "#ffffff" } }, let host = "";
{ name: "Forest", theme: { background: "#052e16", text: "#dcfce7", button: "#15803d", buttonText: "#ffffff" } }, try {
{ name: "Sunset", theme: { background: "#431407", text: "#ffedd5", button: "#ea580c", buttonText: "#ffffff" } }, host = dest ? new URL(dest).hostname : "";
{ name: "Ocean", theme: { background: "#082f49", text: "#e0f2fe", button: "#0284c7", buttonText: "#ffffff" } }, } catch {
]; // Keep the letter placeholder.
}
const COLOR_FIELDS: [keyof Theme, string][] = [ if (host && logoDevToken && !failed) {
["background", "Background"], return (
["text", "Text"], <img
["button", "Buttons"], src={`https://img.logo.dev/${encodeURIComponent(host)}?token=${encodeURIComponent(logoDevToken)}`}
["buttonText", "Button text"], alt=""
]; onError={() => setFailed(true)}
className="size-7 shrink-0 rounded-full bg-white/85 object-cover"
const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase()); />
);
}
return (
<span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-white/85 text-xs font-bold text-gray-700">
{host.replace(/^www\./, "").charAt(0).toUpperCase() || "•"}
</span>
);
}
// Renders the page with unsaved settings so changes are visible while editing. // Renders the page with unsaved settings so changes are visible while editing.
function MockPreview({ title, avatarUrl, theme, page }: { title: string; avatarUrl: string | null; theme: Theme; page: PageDetail }) { function MockPreview({
title,
avatarUrl,
theme,
page,
logoDevToken,
}: {
title: string;
avatarUrl: string | null;
theme: Theme;
page: PageDetail;
/** Set when logos are enabled for this page. */
logoDevToken: string | null;
}) {
return ( return (
<PhoneFrame caption="Preview of unsaved changes"> <PhoneFrame caption="Preview of unsaved changes">
<div className="absolute inset-0 overflow-y-auto px-5 py-10 text-center" style={{ background: theme.background, color: theme.text }}> <div className="absolute inset-0 flex flex-col overflow-y-auto px-5 pt-10 pb-5 text-center" style={{ background: theme.background, color: theme.text }}>
{avatarUrl && <img src={avatarUrl} alt="" className="mx-auto size-20 rounded-full object-cover" />} {avatarUrl && <img src={avatarUrl} alt="" className="mx-auto size-20 rounded-full object-cover" />}
<div className="mt-4 mb-6 text-xl font-bold">{title || "Untitled"}</div> <div className="mt-4 mb-6 text-xl font-bold">{title || "Untitled"}</div>
<div className="flex flex-col gap-2.5"> <div className="flex flex-col gap-2.5">
{page.blocks.map((b) => {page.blocks.map((b) =>
b.kind === "link" ? ( b.kind === "link" ? (
<div key={b.id} className="rounded-lg px-3 py-2.5 text-sm font-semibold" style={{ background: theme.button, color: theme.buttonText }}> <div
{b.label} key={b.id}
className="flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm font-semibold"
style={{ background: theme.button, color: theme.buttonText }}
>
<MockIcon dest={b.target?.dest ?? null} logoDevToken={logoDevToken} />
<span className="flex-1 truncate pr-7">{b.label}</span>
</div> </div>
) : ( ) : (
<p key={b.id} className="line-clamp-3 text-sm opacity-90"> <p key={b.id} className="line-clamp-3 text-sm opacity-90">
@@ -51,21 +77,23 @@ function MockPreview({ title, avatarUrl, theme, page }: { title: string; avatarU
{!page.blocks.length && {!page.blocks.length &&
[0, 1, 2].map((i) => <div key={i} className="h-10 rounded-lg opacity-60" style={{ background: theme.button }} />)} [0, 1, 2].map((i) => <div key={i} className="h-10 rounded-lg opacity-60" style={{ background: theme.button }} />)}
</div> </div>
{logoDevToken && <p className="mt-auto pt-8 text-[11px] opacity-50">Logos provided by Logo.dev</p>}
</div> </div>
</PhoneFrame> </PhoneFrame>
); );
} }
export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) { export function AppearanceTab({ page, me, onChange }: { page: PageDetail; me: Me; onChange: (page: PageDetail) => void }) {
const [title, setTitle] = useState(page.title ?? ""); const [title, setTitle] = useState(page.title ?? "");
const [theme, setTheme] = useState(page.theme); const [theme, setTheme] = useState(page.theme);
const [showLogos, setShowLogos] = useState(page.showLogos);
const { busy, run } = useAction(); const { busy, run } = useAction();
const upload = useAction(); const upload = useAction();
const fileInput = useRef<HTMLInputElement>(null); const fileInput = useRef<HTMLInputElement>(null);
const dirty = title !== (page.title ?? "") || !sameTheme(theme, page.theme); const dirty = title !== (page.title ?? "") || !sameTheme(theme, page.theme) || showLogos !== page.showLogos;
const save = () => run(async () => onChange(await api<PageDetail>("PATCH", `/pages/${page.id}`, { title, theme })), "Appearance saved"); const save = () => run(async () => onChange(await api<PageDetail>("PATCH", `/pages/${page.id}`, { title, theme, showLogos })), "Appearance saved");
const uploadAvatar = (file: File | undefined) => { const uploadAvatar = (file: File | undefined) => {
if (!file) return; if (!file) return;
@@ -125,40 +153,29 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange:
</Card> </Card>
<Card> <Card>
<CardHeader title="Theme" description="Pick a preset or set your own colors." /> <CardHeader title="Theme" description="Pick a preset, use a palette from coolors.co or set your own colors." />
<CardBody className="flex flex-col gap-6"> <CardBody className="flex flex-col gap-7">
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3"> <ThemePicker theme={theme} onChange={setTheme} />
{PRESETS.map((preset) => { <div className="border-t border-border pt-6">
const selected = sameTheme(preset.theme, theme); <Switch
return ( label="Website logos"
<button checked={me.logoDev && showLogos}
key={preset.name} onChange={setShowLogos}
type="button" disabled={!me.logoDev}
onClick={() => setTheme(preset.theme)} description={
className={cx( me.logoDev ? (
"relative cursor-pointer overflow-hidden rounded-xl border text-left transition", <>
selected ? "border-accent ring-3 ring-accent/20" : "border-border hover:border-border-strong", Show the logo of each link's website on its button, provided by{" "}
)} <a href="https://logo.dev" target="_blank" rel="noreferrer" className="underline">
> logo.dev
<div className="flex h-16 flex-col items-center justify-center gap-1.5 px-6" style={{ background: preset.theme.background }}> </a>
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} /> . When off, buttons show the first letter instead and the logo.dev credit is hidden.
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} /> </>
</div> ) : (
<div className="flex items-center justify-between px-3 py-2 text-sm font-medium"> "Not available on this server. An admin can enable it by setting LOGO_DEV_TOKEN."
{preset.name} )
{selected && <Check className="size-4 text-accent" />} }
</div> />
</button>
);
})}
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{COLOR_FIELDS.map(([key, label]) => (
<div key={key} className="flex flex-col gap-1.5">
<span className="text-sm font-medium">{label}</span>
<ColorInput label={label} value={theme[key]} onChange={(v) => setTheme({ ...theme, [key]: v })} />
</div>
))}
</div> </div>
</CardBody> </CardBody>
<CardFooter> <CardFooter>
@@ -169,6 +186,7 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange:
onClick={() => { onClick={() => {
setTitle(page.title ?? ""); setTitle(page.title ?? "");
setTheme(page.theme); setTheme(page.theme);
setShowLogos(page.showLogos);
}} }}
> >
Discard Discard
@@ -180,8 +198,14 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange:
</Card> </Card>
</div> </div>
<div className="hidden lg:block"> <div className="hidden lg:block lg:self-stretch">
<MockPreview title={title} avatarUrl={page.avatarUrl} theme={theme} page={page} /> <MockPreview
title={title}
avatarUrl={page.avatarUrl}
theme={theme}
page={page}
logoDevToken={me.logoDev && showLogos ? me.logoDevToken : null}
/>
</div> </div>
</div> </div>
); );
+189 -45
View File
@@ -2,20 +2,38 @@ import { useEffect, useState } from "react";
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core"; import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities"; import { CSS } from "@dnd-kit/utilities";
import { GripVertical, LayoutList, Link2, Pencil, Plus, Trash2, Type } from "lucide-react"; import { ArrowUpRight, GripVertical, LayoutList, Link2, Pencil, Plus, Trash2, Type } from "lucide-react";
import type { Block, Me, PageDetail, PageSummary } from "../../../shared/api-types.js"; import type { Block, Me, PageDetail, PageSummary } from "../../../shared/api-types.js";
import { api, useApi } from "../../api.js"; import { api, ApiRequestError, errorMessage, useApi } from "../../api.js";
import { Button } from "../../components/ui/button.js"; import { Button, buttonClass } from "../../components/ui/button.js";
import { Dialog, useConfirm } from "../../components/ui/dialog.js"; import { Dialog, useConfirm } from "../../components/ui/dialog.js";
import { Field, Input, Select, Textarea } from "../../components/ui/form.js"; import { Field, Input, PrefixInput, Segmented, Select, Textarea } from "../../components/ui/form.js";
import { Link } from "../../components/ui/misc.js"; import { Link } from "../../components/ui/misc.js";
import { Card, CardHeader, EmptyState } from "../../components/ui/surface.js"; import { Card, CardHeader, EmptyState } from "../../components/ui/surface.js";
import { useAction } from "../../components/ui/toast.js"; import { useAction, useToast } from "../../components/ui/toast.js";
import { cx } from "../../lib/cx.js"; import { cx } from "../../lib/cx.js";
import { stripMarkdown } from "../../lib/markdown.js"; import { stripMarkdown } from "../../lib/markdown.js";
import { detailPath } from "../../router.js";
import { LivePreview } from "./PhonePreview.js"; import { LivePreview } from "./PhonePreview.js";
type Editing = { kind: "link"; block?: Block } | { kind: "text"; block?: Block } | null; type Editing = { kind: "link"; block?: Block } | { kind: "text"; block?: Block } | null;
type LinkSource = "existing" | "new";
// Suggests a button label from a URL, e.g. "https://www.github.com/x" → "github.com".
function hostnameOf(url: string | null | undefined): string {
try {
return url ? new URL(url).hostname.replace(/^www\./, "") : "";
} catch {
return "";
}
}
// Groups links by namespace, with the page's own namespace first (admins can link across namespaces).
function groupByNamespace(links: PageSummary[], first: string): [string, PageSummary[]][] {
const groups = new Map<string, PageSummary[]>([[first, []]]);
for (const link of links) groups.set(link.namespace, [...(groups.get(link.namespace) ?? []), link]);
return [...groups].filter(([, l]) => l.length > 0);
}
function BlockDialog({ function BlockDialog({
editing, editing,
@@ -30,52 +48,98 @@ function BlockDialog({
onClose: () => void; onClose: () => void;
onSaved: (blocks: Block[]) => void; onSaved: (blocks: Block[]) => void;
}) { }) {
const pages = useApi<PageSummary[]>(editing?.kind === "link" && !editing.block ? "/pages" : null); const isNewLink = editing?.kind === "link" && !editing.block;
const { busy, run } = useAction(); const pages = useApi<PageSummary[]>(isNewLink ? "/pages" : null);
const toast = useToast();
const [busy, setBusy] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const [source, setSource] = useState<LinkSource>("existing");
const [targetId, setTargetId] = useState(""); const [targetId, setTargetId] = useState("");
const [dest, setDest] = useState("");
const [code, setCode] = useState("");
const [label, setLabel] = useState(""); const [label, setLabel] = useState("");
const [labelTouched, setLabelTouched] = useState(false);
const [markdown, setMarkdown] = useState(""); const [markdown, setMarkdown] = useState("");
useEffect(() => { useEffect(() => {
setErrors({});
setSource("existing");
setTargetId(""); setTargetId("");
setDest("");
setCode("");
setLabel(editing?.block?.label ?? ""); setLabel(editing?.block?.label ?? "");
setLabelTouched(!!editing?.block);
setMarkdown(editing?.block?.markdown ?? ""); setMarkdown(editing?.block?.markdown ?? "");
}, [editing]); }, [editing]);
if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
// Same rule as the server: own namespace only, unless admin. // Same rule as the server: own namespace only, unless admin.
const targets = (pages.data ?? []).filter((p) => p.kind === "redirect" && (me.isAdmin || p.namespace === page.namespace)); const targets = (pages.data ?? []).filter((p) => p.kind === "redirect" && (me.isAdmin || p.namespace === page.namespace));
const isNew = !editing.block; const noTargets = !!pages.data && targets.length === 0;
const submit = () => // Without existing links, creating one is the only option.
run(async () => { useEffect(() => {
let blocks: Block[]; if (noTargets) setSource("new");
if (editing.block) { }, [noTargets]);
blocks = await api<Block[]>("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label });
} else if (editing.kind === "link") { if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: Number(targetId), label });
} else { const isNew = !editing.block;
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "text", markdown }); const suggestLabel = (url: string | null | undefined) => {
} if (!labelTouched) setLabel(hostnameOf(url));
};
const body = (): unknown => {
if (editing.kind === "text") return { kind: "text", markdown };
if (source === "new") return { kind: "link", label, newLink: { dest: dest.trim(), ...(code.trim() && { code: code.trim() }) } };
return { kind: "link", label, targetId: Number(targetId) };
};
const submit = async () => {
setBusy(true);
setErrors({});
try {
const blocks = editing.block
? await api<Block[]>("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label })
: await api<Block[]>("POST", `/pages/${page.id}/blocks`, body());
onSaved(blocks); onSaved(blocks);
onClose(); onClose();
}, isNew ? "Block added" : "Block updated"); const created = isNewLink && source === "new" ? blocks[blocks.length - 1]?.target?.path : undefined;
toast(created ? `Created ${created} and added it` : isNew ? "Block added" : "Block updated");
} catch (err) {
// Show validation problems next to the field they belong to.
const issues = err instanceof ApiRequestError ? err.issues : undefined;
if (!issues) {
toast(errorMessage(err), true);
return;
}
const field = (key: string) => (key.startsWith("newLink.") ? key.slice(8) : key);
setErrors(Object.fromEntries(Object.entries(issues).map(([k, v]) => [field(k), v.join(", ")])));
} finally {
setBusy(false);
}
};
const canSubmit =
editing.kind === "text"
? !!markdown.trim()
: !!label.trim() && (!isNew || (source === "existing" ? !!targetId : !!dest.trim()));
const prefix = page.namespace ? `/${page.namespace}/` : "/";
return ( return (
<Dialog <Dialog
open open
onClose={onClose} onClose={onClose}
onSubmit={submit} onSubmit={() => void submit()}
title={editing.kind === "link" ? (isNew ? "Add link button" : "Edit link button") : isNew ? "Add text" : "Edit text"} title={editing.kind === "link" ? (isNew ? "Add link button" : "Edit link button") : isNew ? "Add text" : "Edit text"}
description={editing.kind === "link" ? "Buttons point at one of your short links, so every click is counted." : undefined} description={editing.kind === "link" && isNew ? "Buttons point at a short link, so every click is counted." : undefined}
footer={ footer={
<> <>
<Button variant="secondary" onClick={onClose}> <Button variant="secondary" onClick={onClose}>
Cancel Cancel
</Button> </Button>
<Button type="submit" loading={busy} disabled={editing.kind === "link" ? !label.trim() || (isNew && !targetId) : !markdown.trim()}> <Button type="submit" loading={busy} disabled={!canSubmit}>
{isNew ? "Add" : "Save"} {isNew ? (source === "new" && editing.kind === "link" ? "Create and add" : "Add") : "Save"}
</Button> </Button>
</> </>
} }
@@ -83,34 +147,95 @@ function BlockDialog({
{editing.kind === "link" ? ( {editing.kind === "link" ? (
<> <>
{isNew && ( {isNew && (
<Field <Segmented
label="Short link" ariaLabel="Link"
hint={ value={source}
pages.data && !targets.length ? ( onChange={(v) => {
<> setSource(v);
You don't have any short links yet.{" "} setErrors({});
<Link to="/~/links" className="underline"> }}
Create one first options={[
</Link> { value: "existing", label: "Existing link" },
. { value: "new", label: "New link" },
</> ]}
) : undefined />
} )}
>
{isNew && source === "existing" && (
<Field label="Short link" error={errors.targetId} hint={noTargets ? "You don't have any short links yet. Create a new one instead." : undefined}>
{(id) => ( {(id) => (
<Select id={id} required value={targetId} onChange={(e) => setTargetId(e.target.value)}> <Select
id={id}
required
value={targetId}
disabled={noTargets}
onChange={(e) => {
setTargetId(e.target.value);
suggestLabel(targets.find((t) => String(t.id) === e.target.value)?.dest);
}}
>
<option value="">Choose a short link…</option> <option value="">Choose a short link…</option>
{targets.map((p) => ( {groupByNamespace(targets, page.namespace).map(([ns, links]) => (
<optgroup key={ns} label={ns ? `/${ns}/` : "Root /"}>
{links.map((p) => (
<option key={p.id} value={p.id}> <option key={p.id} value={p.id}>
{p.path} → {p.dest} {p.path} → {p.dest}
</option> </option>
))} ))}
</optgroup>
))}
</Select> </Select>
)} )}
</Field> </Field>
)} )}
<Field label="Button label">
{(id) => <Input id={id} required autoFocus={!isNew} placeholder="My GitHub" value={label} onChange={(e) => setLabel(e.target.value)} />} {isNew && source === "new" && (
<>
<Field label="Destination URL" error={errors.dest}>
{(id) => (
<Input
id={id}
type="url"
required
autoFocus
placeholder="https://example.com"
value={dest}
onChange={(e) => {
setDest(e.target.value);
suggestLabel(e.target.value);
}}
/>
)}
</Field>
<Field label="Shortcode" hint="Optional. Leave empty for a random 5-character code." error={errors.code}>
{(id) => (
<PrefixInput
id={id}
prefix={prefix}
placeholder="random"
pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
)}
</Field>
</>
)}
<Field label="Button label" error={errors.label}>
{(id) => (
<Input
id={id}
required
autoFocus={!isNew}
placeholder="My GitHub"
value={label}
onChange={(e) => {
setLabel(e.target.value);
setLabelTouched(true);
}}
/>
)}
</Field> </Field>
</> </>
) : ( ) : (
@@ -122,6 +247,9 @@ function BlockDialog({
); );
} }
// The short link's own page in the dashboard (analytics, QR code, settings).
const targetPath = (target: NonNullable<Block["target"]>) => detailPath({ id: target.id, kind: "redirect", namespace: target.namespace });
function SortableBlock({ block, onEdit, onDelete }: { block: Block; onEdit: () => void; onDelete: () => void }) { function SortableBlock({ block, onEdit, onDelete }: { block: Block; onEdit: () => void; onDelete: () => void }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: block.id }); const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: block.id });
const isLink = block.kind === "link"; const isLink = block.kind === "link";
@@ -152,8 +280,24 @@ function SortableBlock({ block, onEdit, onDelete }: { block: Block; onEdit: () =
</span> </span>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">{isLink ? block.label : stripMarkdown(block.markdown ?? "")}</div> <div className="truncate text-sm font-medium">{isLink ? block.label : stripMarkdown(block.markdown ?? "")}</div>
<div className="truncate font-mono text-xs text-muted">{isLink ? block.target?.path : "Text"}</div> {isLink && block.target ? (
<Link to={targetPath(block.target)} className="block truncate font-mono text-xs text-muted hover:text-accent hover:underline">
{block.target.path}
</Link>
) : (
<div className="truncate font-mono text-xs text-muted">Text</div>
)}
</div> </div>
{isLink && block.target && (
<Link
to={targetPath(block.target)}
className={buttonClass("ghost", "icon-sm")}
aria-label={`Open short link ${block.target.path}`}
title={`Open ${block.target.path}`}
>
<ArrowUpRight />
</Link>
)}
<Button variant="ghost" size="icon-sm" onClick={onEdit} aria-label="Edit"> <Button variant="ghost" size="icon-sm" onClick={onEdit} aria-label="Edit">
<Pencil /> <Pencil />
</Button> </Button>
@@ -232,7 +376,7 @@ export function ContentTab({ page, me, onChange }: { page: PageDetail; me: Me; o
)} )}
</Card> </Card>
<div className="hidden lg:block"> <div className="hidden lg:block lg:self-stretch">
<LivePreview path={page.path} version={version} /> <LivePreview path={page.path} version={version} />
</div> </div>
+20 -5
View File
@@ -5,7 +5,7 @@ import { useApi } from "../../api.js";
import { buttonClass } from "../../components/ui/button.js"; import { buttonClass } from "../../components/ui/button.js";
import { CopyButton, DomainIcon, Link, publicUrl, Tabs } from "../../components/ui/misc.js"; import { CopyButton, DomainIcon, Link, publicUrl, Tabs } from "../../components/ui/misc.js";
import { Badge, EmptyState, Skeleton } from "../../components/ui/surface.js"; import { Badge, EmptyState, Skeleton } from "../../components/ui/surface.js";
import { detailPath, listPath } from "../../router.js"; import { backPath, detailPath, listPath, replacePath } from "../../router.js";
import { AnalyticsTab } from "./AnalyticsTab.js"; import { AnalyticsTab } from "./AnalyticsTab.js";
import { AppearanceTab } from "./AppearanceTab.js"; import { AppearanceTab } from "./AppearanceTab.js";
import { ContentTab } from "./ContentTab.js"; import { ContentTab } from "./ContentTab.js";
@@ -30,10 +30,13 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
const page = useApi<PageDetail>(`/pages/${id}`); const page = useApi<PageDetail>(`/pages/${id}`);
const p = page.data; const p = page.data;
// Links like /~/links/<id of a link page> are corrected to the right section. // Correct the URL to the canonical one, e.g. /~/links/<id of a link page>, or another user's
// page opened outside Administration.
useEffect(() => { useEffect(() => {
if (p && p.kind !== kind) history.replaceState(null, "", detailPath(p, tab)); if (!p) return;
}, [p, kind, tab]); const canonical = detailPath(p, tab);
if (location.pathname.replace(/\/+$/, "") !== canonical) replacePath(canonical);
}, [p, tab]);
if (page.error) { if (page.error) {
return ( return (
@@ -67,9 +70,21 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
return ( return (
<> <>
<nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb"> <nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb">
{backPath(p) === listPath(p.kind) ? (
<Link to={listPath(p.kind)} className="hover:text-fg"> <Link to={listPath(p.kind)} className="hover:text-fg">
{p.kind === "redirect" ? "Short links" : "Link pages"} {p.kind === "redirect" ? "Short links" : "Link pages"}
</Link> </Link>
) : (
<>
<Link to="/~/admin" className="hover:text-fg">
Administration
</Link>
<ChevronRight className="size-3.5" />
<Link to={backPath(p)} className="hover:text-fg">
{p.namespace}
</Link>
</>
)}
<ChevronRight className="size-3.5" /> <ChevronRight className="size-3.5" />
<span className="truncate text-fg">{p.path}</span> <span className="truncate text-fg">{p.path}</span>
</nav> </nav>
@@ -109,7 +124,7 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
<div className="animate-fade-in" key={active}> <div className="animate-fade-in" key={active}>
{active === "content" && <ContentTab page={p} me={me} onChange={page.set} />} {active === "content" && <ContentTab page={p} me={me} onChange={page.set} />}
{active === "appearance" && <AppearanceTab page={p} onChange={page.set} />} {active === "appearance" && <AppearanceTab page={p} me={me} onChange={page.set} />}
{active === "analytics" && <AnalyticsTab pageId={p.id} />} {active === "analytics" && <AnalyticsTab pageId={p.id} />}
{active === "qr" && <QrTab url={url} name={p.code} />} {active === "qr" && <QrTab url={url} name={p.code} />}
{active === "settings" && <SettingsTab page={p} me={me} onChange={page.set} reload={page.reload} />} {active === "settings" && <SettingsTab page={p} me={me} onChange={page.set} reload={page.reload} />}
+94 -13
View File
@@ -1,14 +1,14 @@
import { useState } from "react"; import { useState } from "react";
import { Pin, PinOff, Trash2 } from "lucide-react"; import { Pin, PinOff, Trash2 } from "lucide-react";
import type { Me, PageDetail } from "../../../shared/api-types.js"; import type { Me, PageDetail } from "../../../shared/api-types.js";
import { api } from "../../api.js"; import { api, ApiRequestError, errorMessage } from "../../api.js";
import { Button } from "../../components/ui/button.js"; import { Button } from "../../components/ui/button.js";
import { useConfirm } from "../../components/ui/dialog.js"; import { useConfirm } from "../../components/ui/dialog.js";
import { Field, Input } from "../../components/ui/form.js"; import { Field, Input, PrefixInput } from "../../components/ui/form.js";
import { CopyButton, publicUrl } from "../../components/ui/misc.js"; import { CopyButton, publicUrl } from "../../components/ui/misc.js";
import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js"; import { Alert, Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
import { useAction } from "../../components/ui/toast.js"; import { useAction, useToast } from "../../components/ui/toast.js";
import { listPath, navigate } from "../../router.js"; import { backPath, navigate } from "../../router.js";
function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) { function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
const [dest, setDest] = useState(page.dest ?? ""); const [dest, setDest] = useState(page.dest ?? "");
@@ -35,6 +35,93 @@ function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page
); );
} }
function AddressCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
const [code, setCode] = useState(page.code);
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
const confirm = useConfirm();
const toast = useToast();
const prefix = page.namespace ? `/${page.namespace}/` : "/";
const newPath = `${prefix}${code.trim()}`;
const changed = code.trim() !== page.code;
const rename = async () => {
const ok = await confirm({
title: "Change the address?",
description: (
<span className="flex flex-col gap-3">
<span>
<span className="font-mono">{page.path}</span> stops working immediately. Shared links, bookmarks and printed QR codes
that use it will show a "not found" page.
</span>
<span>
New address: <span className="font-mono text-fg">{newPath}</span>
</span>
</span>
),
confirmLabel: "Change address",
danger: true,
});
if (!ok) return;
setBusy(true);
setError(undefined);
try {
onChange(await api<PageDetail>("PATCH", `/pages/${page.id}`, { code: code.trim() }));
toast(`Address changed to ${newPath}`);
} catch (err) {
setError(err instanceof ApiRequestError && err.issues?.code ? err.issues.code.join(", ") : errorMessage(err));
} finally {
setBusy(false);
}
};
return (
<Card>
<form
onSubmit={(e) => {
e.preventDefault();
void rename();
}}
>
<CardHeader title="Address" description="The public URL of this page." actions={<CopyButton value={publicUrl(page.path)} label="Copy" />} />
<CardBody className="flex flex-col gap-4">
<Field label="Shortcode" error={error}>
{(id) => (
<PrefixInput
id={id}
prefix={prefix}
required
pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}"
value={code}
onChange={(e) => {
setCode(e.target.value);
setError(undefined);
}}
/>
)}
</Field>
{changed && (
<Alert title="Changing the shortcode breaks the current URL">
<span className="font-mono">{page.path}</span> will stop working, including QR codes you've already shared or printed.
</Alert>
)}
</CardBody>
<CardFooter>
{changed && (
<Button variant="secondary" onClick={() => setCode(page.code)}>
Cancel
</Button>
)}
<Button type="submit" variant={changed ? "danger" : "primary"} loading={busy} disabled={!changed || !code.trim()}>
Change address
</Button>
</CardFooter>
</form>
</Card>
);
}
export function SettingsTab({ export function SettingsTab({
page, page,
me, me,
@@ -66,7 +153,7 @@ export function SettingsTab({
if (!ok) return; if (!ok) return;
void run(async () => { void run(async () => {
await api("DELETE", `/pages/${page.id}`); await api("DELETE", `/pages/${page.id}`);
navigate(listPath(page.kind)); navigate(backPath(page));
}, `Deleted ${page.path}`); }, `Deleted ${page.path}`);
}; };
@@ -74,13 +161,7 @@ export function SettingsTab({
<div className="flex max-w-3xl flex-col gap-6"> <div className="flex max-w-3xl flex-col gap-6">
{page.kind === "redirect" && <DestinationCard page={page} onChange={onChange} />} {page.kind === "redirect" && <DestinationCard page={page} onChange={onChange} />}
<Card> <AddressCard key={page.code} page={page} onChange={onChange} />
<CardHeader title="Address" description="Shortcodes can't be changed. Create a new one if you need a different address." />
<CardBody className="flex items-center gap-2">
<code className="flex-1 truncate rounded-lg bg-surface-2 px-3 py-2 font-mono text-sm">{publicUrl(page.path)}</code>
<CopyButton value={publicUrl(page.path)} label="Copy" />
</CardBody>
</Card>
{me.isAdmin && ( {me.isAdmin && (
<Card> <Card>
+436
View File
@@ -0,0 +1,436 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Check, ChevronDown, ExternalLink, X } from "lucide-react";
import type { SavedPalette } from "../../../shared/api-types.js";
import type { Theme } from "../../../shared/validation.js";
import { api, errorMessage, useApi } from "../../api.js";
import { Button } from "../../components/ui/button.js";
import { useConfirm } from "../../components/ui/dialog.js";
import { ColorInput, Input } from "../../components/ui/form.js";
import { useToast } from "../../components/ui/toast.js";
import { cx } from "../../lib/cx.js";
import { parseCoolorsInput, themeFromPalette, type Variant } from "../../lib/palette.js";
export const COLOR_FIELDS: [keyof Theme, string][] = [
["background", "Background"],
["text", "Text"],
["button", "Buttons"],
["buttonText", "Button text"],
];
export const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase());
const PRESETS: { name: string; theme: Theme }[] = [
{ name: "Midnight", theme: { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" } },
{ name: "Paper", theme: { background: "#fafaf9", text: "#1c1917", button: "#1c1917", buttonText: "#fafaf9" } },
];
const paletteKey = (colors: string[]) => colors.join("-").toLowerCase();
const paletteLabel = (p: SavedPalette) => `Imported ${new Date(p.createdAt).toLocaleDateString(undefined, { month: "short", day: "numeric" })}`;
const cardClass = (selected: boolean) =>
cx(
"relative overflow-hidden rounded-xl border transition",
selected ? "border-accent ring-3 ring-accent/20" : "border-border hover:border-border-strong",
);
function SectionLabel({ children, actions, hint }: { children: ReactNode; actions?: ReactNode; hint?: ReactNode }) {
return (
<div className="mb-3 flex flex-wrap items-end justify-between gap-2">
<div>
<h3 className="text-sm font-medium">{children}</h3>
{hint && <p className="mt-0.5 text-xs text-muted">{hint}</p>}
</div>
{actions}
</div>
);
}
function PresetCard({ name, theme, selected, onClick }: { name: string; theme: Theme; selected: boolean; onClick: () => void }) {
return (
<button type="button" onClick={onClick} aria-pressed={selected} className={cx(cardClass(selected), "cursor-pointer text-left")}>
<div className="flex h-14 flex-col items-center justify-center gap-1.5 px-6" style={{ background: theme.background }}>
<div className="h-2.5 w-full rounded-full" style={{ background: theme.button }} />
<div className="h-2.5 w-full rounded-full" style={{ background: theme.button }} />
</div>
<div className="flex items-center justify-between gap-2 px-3 py-2 text-sm font-medium">
<span className="truncate">{name}</span>
{selected && <Check className="size-4 shrink-0 text-accent" />}
</div>
</button>
);
}
// Miniature of a link page: background, a line of text and a button.
function ThemeThumb({ theme }: { theme: Theme }) {
return (
<span
className="flex h-6 w-9 shrink-0 flex-col items-center justify-center gap-0.5 rounded border border-border px-1"
style={{ background: theme.background }}
aria-hidden
>
<span className="h-0.5 w-3/5 rounded-full" style={{ background: theme.text }} />
<span className="h-1.5 w-full rounded-sm" style={{ background: theme.button }} />
</span>
);
}
// A palette card: each color opens the role menu, the name row opens the dark/light menu.
function PaletteCard({
colors,
label,
selected,
onOpenVariants,
onPickColor,
onRemove,
}: {
colors: string[];
label: string;
selected: Variant | null;
onOpenVariants: (anchor: HTMLElement) => void;
onPickColor: (color: string, anchor: HTMLElement) => void;
onRemove?: () => void;
}) {
return (
<div className={cardClass(selected !== null)}>
<div className="flex h-12">
{colors.map((c, i) => (
<button
key={i}
type="button"
aria-haspopup="menu"
aria-label={`${c.toUpperCase()}: use for one color`}
title={c.toUpperCase()}
onClick={(e) => onPickColor(c, e.currentTarget)}
className="flex-1 cursor-pointer transition-[flex-grow] duration-150 hover:grow-[1.8] focus-visible:grow-[1.8] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-white"
style={{ background: c }}
/>
))}
</div>
<div className="flex items-center">
<button
type="button"
aria-haspopup="menu"
aria-label={`Use ${label}…`}
onClick={(e) => onOpenVariants(e.currentTarget)}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-3 py-2 text-left text-sm font-medium outline-none transition-colors hover:bg-surface-2/60 focus-visible:bg-surface-2/60 focus-visible:ring-2 focus-visible:ring-accent/40 focus-visible:ring-inset"
>
<span className="truncate">{label}</span>
{selected && <span className="shrink-0 text-xs font-normal text-muted">{selected === "dark" ? "Dark" : "Light"}</span>}
<span className="ml-auto flex shrink-0 items-center gap-1">
{selected && <Check className="size-4 text-accent" />}
<ChevronDown className="size-4 text-muted" />
</span>
</button>
{onRemove && (
<button
type="button"
onClick={onRemove}
aria-label={`Remove ${label}`}
title="Remove palette"
className="cursor-pointer self-stretch px-2.5 text-muted outline-none transition-colors hover:bg-surface-2/60 hover:text-danger focus-visible:ring-2 focus-visible:ring-accent/40 focus-visible:ring-inset"
>
<X className="size-4" />
</button>
)}
</div>
</div>
);
}
// Small menu anchored to an element: placed below it (or above when there's no room), closes on outside
// click, Escape, scroll and resize, and supports arrow keys.
function PopoverMenu({
anchor,
label,
header,
onClose,
children,
}: {
anchor: HTMLElement;
label: string;
header: ReactNode;
onClose: () => void;
children: ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState<{ top: number; left: number } | null>(null);
useLayoutEffect(() => {
const menu = ref.current;
if (!menu) return;
const a = anchor.getBoundingClientRect();
const { width, height } = menu.getBoundingClientRect();
const below = a.bottom + 6;
const top = below + height > innerHeight - 8 ? Math.max(8, a.top - height - 6) : below;
const left = Math.min(Math.max(8, a.left + a.width / 2 - width / 2), innerWidth - width - 8);
setPosition({ top, left });
}, [anchor]);
// Focus the first item once the menu is visible (hidden elements can't take focus).
useEffect(() => {
if (position) ref.current?.querySelector<HTMLButtonElement>("[role=menuitem]")?.focus({ preventScroll: true });
}, [position]);
useEffect(() => {
const outside = (e: PointerEvent) => {
if (!ref.current?.contains(e.target as Node) && !anchor.contains(e.target as Node)) onClose();
};
const dismiss = () => onClose();
const escape = (e: globalThis.KeyboardEvent) => {
if (e.key !== "Escape") return;
onClose();
anchor.focus();
};
document.addEventListener("pointerdown", outside);
document.addEventListener("keydown", escape);
window.addEventListener("resize", dismiss);
window.addEventListener("scroll", dismiss, true);
return () => {
document.removeEventListener("pointerdown", outside);
document.removeEventListener("keydown", escape);
window.removeEventListener("resize", dismiss);
window.removeEventListener("scroll", dismiss, true);
};
}, [anchor, onClose]);
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
e.preventDefault();
const items = [...(ref.current?.querySelectorAll<HTMLButtonElement>("[role=menuitem]") ?? [])];
const index = items.indexOf(document.activeElement as HTMLButtonElement);
items[(index + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length]?.focus();
};
return (
<div
ref={ref}
role="menu"
aria-label={label}
onKeyDown={onKeyDown}
className="fixed z-50 w-56 animate-pop-in rounded-xl border border-border bg-surface p-1 shadow-xl"
style={position ?? { visibility: "hidden", top: 0, left: 0 }}
>
<div className="flex items-center gap-2 px-2.5 pt-1.5 pb-2 text-xs text-muted">{header}</div>
{children}
</div>
);
}
function MenuItem({ leading, label, checked, onClick }: { leading: ReactNode; label: string; checked: boolean; onClick: () => void }) {
return (
<button
type="button"
role="menuitem"
onClick={onClick}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-sm outline-none hover:bg-surface-2 focus-visible:bg-surface-2"
>
{leading}
<span className="flex-1">{label}</span>
{checked && <Check className="size-4 text-accent" />}
</button>
);
}
type OpenMenu =
| { kind: "color"; color: string; anchor: HTMLElement }
| { kind: "variant"; colors: string[]; label: string; anchor: HTMLElement }
| null;
// Theme picker: basic presets, the user's saved coolors.co palettes, and custom colors.
export function ThemePicker({ theme, onChange }: { theme: Theme; onChange: (theme: Theme) => void }) {
const saved = useApi<SavedPalette[]>("/palettes");
const toast = useToast();
const confirm = useConfirm();
// The palette version the current theme was generated from, to mark it as selected.
const [source, setSource] = useState<{ colors: string[]; variant: Variant } | null>(null);
const [link, setLink] = useState("");
const [linkError, setLinkError] = useState<string>();
const [importing, setImporting] = useState(false);
const [menu, setMenu] = useState<OpenMenu>(null);
// Clicking the element that opened a menu again closes it.
const toggleMenu = (next: NonNullable<OpenMenu>) => setMenu((m) => (m?.anchor === next.anchor ? null : next));
const closeMenu = (refocus = false) => {
if (refocus) menu?.anchor.focus();
setMenu(null);
};
const applyPalette = (colors: string[], variant: Variant) => {
setSource({ colors, variant });
onChange(themeFromPalette(colors, variant));
};
const setColor = (role: keyof Theme, color: string) => {
setSource(null);
onChange({ ...theme, [role]: color });
};
// Which version of this palette is in use, if any (editing a single color deselects it).
const selectedVariant = (colors: string[]): Variant | null =>
source && paletteKey(source.colors) === paletteKey(colors) && sameTheme(themeFromPalette(colors, source.variant), theme)
? source.variant
: null;
const importLink = async () => {
const colors = parseCoolorsInput(link);
if (!colors) {
setLinkError("That doesn't look like a coolors.co palette link.");
return;
}
setImporting(true);
try {
await api<SavedPalette>("POST", "/palettes", { colors });
await saved.reload();
applyPalette(colors, "dark");
setLink("");
setLinkError(undefined);
} catch (err) {
setLinkError(errorMessage(err));
} finally {
setImporting(false);
}
};
const removePalette = async (palette: SavedPalette) => {
const ok = await confirm({ title: "Remove this palette?", description: "Pages that already use its colors keep them.", confirmLabel: "Remove", danger: true });
if (!ok) return;
try {
await api("DELETE", `/palettes/${palette.id}`);
await saved.reload();
toast("Palette removed");
} catch (err) {
toast(errorMessage(err), true);
}
};
const pickHint = "Click a palette's name to use it with a dark or light background, or a single color to use it for one part.";
return (
<div className="flex flex-col gap-7">
<div>
<SectionLabel>Basic</SectionLabel>
<div className="grid grid-cols-2 gap-3">
{PRESETS.map((preset) => (
<PresetCard
key={preset.name}
name={preset.name}
theme={preset.theme}
selected={sameTheme(preset.theme, theme)}
onClick={() => {
setSource(null);
onChange(preset.theme);
}}
/>
))}
</div>
</div>
<div>
<SectionLabel hint={saved.data?.length ? pickHint : "Import palettes from coolors.co to use them on your pages."}>Your palettes</SectionLabel>
<form
className="flex gap-2"
onSubmit={(e) => {
e.preventDefault();
void importLink();
}}
>
<Input
aria-label="coolors.co link"
placeholder="https://coolors.co/palette/264653-2a9d8f-e9c46a-f4a261-e76f51"
value={link}
onChange={(e) => {
setLink(e.target.value);
setLinkError(undefined);
}}
/>
<Button type="submit" variant="secondary" loading={importing} disabled={!link.trim()}>
Import
</Button>
</form>
{linkError ? (
<p className="mt-1.5 text-xs text-danger">{linkError}</p>
) : (
<p className="mt-1.5 text-xs text-muted">
Find a palette on{" "}
<a href="https://coolors.co/palettes" target="_blank" rel="noreferrer" className="inline-flex items-center gap-0.5 underline">
coolors.co <ExternalLink className="size-3" />
</a>{" "}
and paste its URL here.
</p>
)}
{!!saved.data?.length && (
<div className="mt-3 grid grid-cols-2 gap-3">
{saved.data.map((p) => (
<PaletteCard
key={p.id}
label={paletteLabel(p)}
colors={p.colors}
selected={selectedVariant(p.colors)}
onOpenVariants={(anchor) => toggleMenu({ kind: "variant", colors: p.colors, label: paletteLabel(p), anchor })}
onPickColor={(color, anchor) => toggleMenu({ kind: "color", color, anchor })}
onRemove={() => void removePalette(p)}
/>
))}
</div>
)}
</div>
<div>
<SectionLabel>Custom colors</SectionLabel>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{COLOR_FIELDS.map(([key, label]) => (
<div key={key} className="flex flex-col gap-1.5">
<span className="text-xs text-muted">{label}</span>
<ColorInput label={label} value={theme[key]} onChange={(v) => setColor(key, v)} />
</div>
))}
</div>
</div>
{menu?.kind === "color" && (
<PopoverMenu
anchor={menu.anchor}
label={`Use ${menu.color.toUpperCase()} for`}
onClose={closeMenu}
header={
<>
<span className="size-4 rounded border border-border" style={{ background: menu.color }} />
<span className="font-mono uppercase">{menu.color}</span>
<span>use for…</span>
</>
}
>
{COLOR_FIELDS.map(([key, label]) => (
<MenuItem
key={key}
label={label}
leading={<span className="size-4 rounded border border-border" style={{ background: theme[key] }} title={`Current: ${theme[key]}`} />}
checked={theme[key].toLowerCase() === menu.color.toLowerCase()}
onClick={() => {
setColor(key, menu.color);
closeMenu(true);
}}
/>
))}
</PopoverMenu>
)}
{menu?.kind === "variant" && (
<PopoverMenu anchor={menu.anchor} label={`Use ${menu.label} with`} onClose={closeMenu} header={<span>Use {menu.label} with…</span>}>
{(["dark", "light"] as const).map((v) => (
<MenuItem
key={v}
label={v === "dark" ? "Dark background" : "Light background"}
leading={<ThemeThumb theme={themeFromPalette(menu.colors, v)} />}
checked={selectedVariant(menu.colors) === v}
onClick={() => {
applyPalette(menu.colors, v);
closeMenu(true);
}}
/>
))}
</PopoverMenu>
)}
</div>
);
}
+4 -3
View File
@@ -1,5 +1,8 @@
@import "tailwindcss"; @import "tailwindcss";
/* Dark mode is controlled by data-theme on <html> (see theme-init.js), not only the system setting. */
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
/* Semantic color tokens. Components only use these, so light and dark mode stay in sync. */ /* Semantic color tokens. Components only use these, so light and dark mode stay in sync. */
@theme { @theme {
--color-canvas: #f6f6f8; --color-canvas: #f6f6f8;
@@ -40,8 +43,7 @@
} }
} }
@media (prefers-color-scheme: dark) { :root[data-theme="dark"] {
:root {
--color-canvas: #0c0c10; --color-canvas: #0c0c10;
--color-surface: #141419; --color-surface: #141419;
--color-surface-2: #1d1d24; --color-surface-2: #1d1d24;
@@ -62,7 +64,6 @@
--color-chart-2: #38bdf8; --color-chart-2: #38bdf8;
color-scheme: dark; color-scheme: dark;
} }
}
@layer base { @layer base {
html { html {
+181 -1
View File
@@ -46,7 +46,7 @@ describe("authentication", () => {
expect(callback.status).toBe(302); expect(callback.status).toBe(302);
const session = callback.headers.getSetCookie().find((c) => c.startsWith("short_session="))!.split(";")[0]!; const session = callback.headers.getSetCookie().find((c) => c.startsWith("short_session="))!.split(";")[0]!;
const me = await (await app.request("/~/api/me", { headers: { cookie: session } })).json(); const me = await (await app.request("/~/api/me", { headers: { cookie: session } })).json();
expect(me).toEqual({ username: "alice", isAdmin: true }); expect(me).toEqual({ username: "alice", isAdmin: true, logoDev: false, logoDevToken: null });
// A renamed account keeps its original namespace; losing the group removes admin. // A renamed account keeps its original namespace; losing the group removes admin.
const login2 = await app.request("/~/auth/login"); const login2 = await app.request("/~/auth/login");
@@ -58,9 +58,22 @@ describe("authentication", () => {
expect(await (await app.request("/~/api/me", { headers: { cookie: session2 } })).json()).toEqual({ expect(await (await app.request("/~/api/me", { headers: { cookie: session2 } })).json()).toEqual({
username: "alice", username: "alice",
isAdmin: false, isAdmin: false,
logoDev: false,
logoDevToken: null,
}); });
}); });
it("shows a friendly page when the identity provider rejects the login", async () => {
const { app, setNextLogin } = setup();
const login = await app.request("/~/auth/login");
setNextLogin(new Error("state mismatch"));
const res = await app.request("/~/auth/callback?code=c&state=s", {
headers: { cookie: login.headers.get("set-cookie")!.split(";")[0]! },
});
expect(res.status).toBe(400);
expect(await res.text()).toContain("Sign-in failed");
});
it("rejects usernames that aren't URL-safe", async () => { it("rejects usernames that aren't URL-safe", async () => {
const { app, setNextLogin } = setup(); const { app, setNextLogin } = setup();
const login = await app.request("/~/auth/login"); const login = await app.request("/~/auth/login");
@@ -134,6 +147,55 @@ describe("namespaces and permissions", () => {
expect(await (await admin.api("GET", "/conflicts")).json()).toEqual([{ username: "carol", pageId: expect.any(Number) }]); expect(await (await admin.api("GET", "/conflicts")).json()).toEqual([{ username: "carol", pageId: expect.any(Number) }]);
}); });
it("renames shortcodes and keeps stats and link buttons", async () => {
const { app, user } = setup();
user("bob");
const alice = user("alice");
const admin = user("root", true);
const link = await (await alice.api("POST", "/pages", { kind: "redirect", code: "old", dest: "https://a.test" })).json();
await alice.api("POST", "/pages", { kind: "redirect", code: "taken", dest: "https://b.test" });
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: link.id, label: "A" });
await app.request("/alice/old");
await flush();
expect((await alice.api("PATCH", `/pages/${link.id}`, { code: "taken" })).status).toBe(409);
expect((await alice.api("PATCH", `/pages/${link.id}`, { code: "bad code" })).status).toBe(400);
expect((await user("eve").api("PATCH", `/pages/${link.id}`, { code: "x" })).status).toBe(404);
const renamed = await alice.api("PATCH", `/pages/${link.id}`, { code: "new" });
expect((await renamed.json()).path).toBe("/alice/new");
expect((await app.request("/alice/old")).status).toBe(404);
expect((await app.request("/alice/new")).headers.get("location")).toBe("https://a.test");
expect((await (await alice.api("GET", `/pages/${link.id}/stats`)).json()).total).toBe(1);
expect((await (await alice.api("GET", `/pages/${page.id}`)).json()).blocks[0].target.path).toBe("/alice/new");
// Root renames follow the same reserved-code and username rules as creating.
const root = await (await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "r", dest: "https://r.test" })).json();
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "api" })).status).toBe(409);
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "bob" })).status).toBe(409);
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "r" })).status).toBe(200);
});
it("lets admins revoke a user's sessions and API tokens", async () => {
const { app, user } = setup();
const alice = user("alice");
const bob = user("bob");
const admin = user("root", true);
const cookie = `short_session=${alice.session}`;
expect((await bob.api("DELETE", "/users/alice/access")).status).toBe(403);
expect((await admin.api("DELETE", "/users/nobody/access")).status).toBe(404);
const res = await admin.api("DELETE", "/users/alice/access");
expect(await res.json()).toEqual({ sessions: 1, tokens: 1 });
expect((await alice.api("GET", "/me")).status).toBe(401);
expect((await app.request("/~/api/me", { headers: { cookie } })).status).toBe(401);
// Other users are unaffected.
expect((await bob.api("GET", "/me")).status).toBe(200);
});
it("restricts admin-only endpoints", async () => { it("restricts admin-only endpoints", async () => {
const { user } = setup(); const { user } = setup();
const alice = user("alice"); const alice = user("alice");
@@ -163,6 +225,54 @@ describe("link pages", () => {
expect((await alice.api("PUT", `/pages/${page.id}/blocks/order`, { ids: [blocks[0].id] })).status).toBe(400); expect((await alice.api("PUT", `/pages/${page.id}/blocks/order`, { ids: [blocks[0].id] })).status).toBe(400);
}); });
it("lists the link pages a short link is used on", async () => {
const { user } = setup();
const alice = user("alice");
const link = await (await alice.api("POST", "/pages", { kind: "redirect", code: "gh", dest: "https://github.com" })).json();
const unused = await (await alice.api("POST", "/pages", { kind: "redirect", code: "x", dest: "https://x.test" })).json();
for (const code of ["b", "a"]) {
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code, title: code })).json();
// Two buttons to the same link on one page still count as one page.
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: link.id, label: "GitHub" });
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: link.id, label: "GitHub again" });
}
const list: { id: number; usedOn: { path: string }[] }[] = await (await alice.api("GET", "/pages")).json();
expect(list.find((p) => p.id === link.id)!.usedOn.map((u) => u.path)).toEqual(["/alice/a", "/alice/b"]);
expect(list.find((p) => p.id === unused.id)!.usedOn).toEqual([]);
expect((await (await alice.api("GET", `/pages/${link.id}`)).json()).usedOn).toHaveLength(2);
});
it("creates a new short link while adding a link button", async () => {
const { app, user } = setup();
const alice = user("alice");
const admin = user("root", true);
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
await alice.api("POST", "/pages", { kind: "redirect", code: "taken", dest: "https://t.test" });
const blocks = await (
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "Blog", newLink: { dest: "https://blog.test", code: "blog" } })
).json();
expect(blocks[0].target.path).toBe("/alice/blog");
expect((await app.request("/alice/blog")).headers.get("location")).toBe("https://blog.test");
// A taken code fails without leaving a button behind.
const clash = await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "x", newLink: { dest: "https://x.test", code: "taken" } });
expect(clash.status).toBe(409);
expect((await (await alice.api("GET", `/pages/${page.id}`)).json()).blocks).toHaveLength(1);
// Exactly one of targetId and newLink.
expect((await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "x" })).status).toBe(400);
expect(
(await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "x", targetId: blocks[0].target.id, newLink: { dest: "https://x.test" } }))
.status,
).toBe(400);
// An admin editing Alice's page creates the link in Alice's namespace, with a random code.
const byAdmin = await (await admin.api("POST", `/pages/${page.id}/blocks`, { kind: "link", label: "Shop", newLink: { dest: "https://shop.test" } })).json();
expect(byAdmin[1].target.path).toMatch(/^\/alice\/[A-Za-z0-9]{5}$/);
});
it("renders markdown without raw HTML or script links", async () => { it("renders markdown without raw HTML or script links", async () => {
const { app, user } = setup(); const { app, user } = setup();
const alice = user("alice"); const alice = user("alice");
@@ -178,6 +288,29 @@ describe("link pages", () => {
expect(html).not.toContain('href="javascript:'); expect(html).not.toContain('href="javascript:');
}); });
it("shows logo.dev logos and attribution only when enabled for the page", async () => {
const { app, user } = setup({ logoDevToken: "pk_test" });
const alice = user("alice");
expect((await (await alice.api("GET", "/me")).json()).logoDev).toBe(true);
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
const link = await (await alice.api("POST", "/pages", { kind: "redirect", code: "gh", dest: "https://github.com" })).json();
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: link.id, label: "GitHub" });
const enabled = await (await app.request("/alice/me")).text();
expect(enabled).toContain("img.logo.dev/github.com");
expect(enabled).toContain("Logos provided by");
const updated = await (await alice.api("PATCH", `/pages/${page.id}`, { showLogos: false })).json();
expect(updated.showLogos).toBe(false);
const disabled = await (await app.request("/alice/me")).text();
expect(disabled).not.toContain("img.logo.dev");
expect(disabled).not.toContain("Logos provided by");
// Redirects have no logos setting.
expect((await alice.api("PATCH", `/pages/${link.id}`, { showLogos: false })).status).toBe(400);
});
it("removes blocks, stats and pin when a linked page is deleted", async () => { it("removes blocks, stats and pin when a linked page is deleted", async () => {
const { app, user } = setup(); const { app, user } = setup();
const admin = user("root", true); const admin = user("root", true);
@@ -219,6 +352,21 @@ describe("redirects and stats", () => {
expect((await (await alice.api("GET", `/pages/${page.id}/stats`)).json()).total).toBe(0); expect((await (await alice.api("GET", `/pages/${page.id}/stats`)).json()).total).toBe(0);
}); });
it("uses the proxy-added X-Forwarded-For entry, not the client-supplied ones", async () => {
const { app, user } = setup();
const alice = user("alice");
const page = await (await alice.api("POST", "/pages", { kind: "redirect", code: "cv", dest: "https://example.com/cv" })).json();
// Same real client (last entry) faking different addresses in front: still one visitor.
for (const fake of ["10.0.0.1", "10.9.9.9", "172.16.0.1"]) {
await app.request("/alice/cv", { headers: { "x-forwarded-for": `${fake}, 5.6.7.8`, "user-agent": "test" } });
}
await flush();
const stats = await (await alice.api("GET", `/pages/${page.id}/stats`)).json();
expect(stats.today).toBe(3);
expect(stats.uniquesToday).toBe(1);
});
it("returns 404 for unknown links and the pinned page at the root", async () => { it("returns 404 for unknown links and the pinned page at the root", async () => {
const { app, user } = setup(); const { app, user } = setup();
expect((await app.request("/nope")).status).toBe(404); expect((await app.request("/nope")).status).toBe(404);
@@ -233,6 +381,38 @@ describe("redirects and stats", () => {
}); });
}); });
describe("saved palettes", () => {
it("saves palettes per user without duplicates", async () => {
const { user } = setup();
const alice = user("alice");
const bob = user("bob");
const colors = ["#264653", "#2A9D8F", "#e9c46a"];
const created = await alice.api("POST", "/palettes", { colors });
expect(created.status).toBe(201);
const palette = await created.json();
expect(palette.colors).toEqual(["#264653", "#2a9d8f", "#e9c46a"]);
const again = await alice.api("POST", "/palettes", { colors: ["#264653", "#2a9d8f", "#E9C46A"] });
expect(again.status).toBe(200);
expect((await again.json()).id).toBe(palette.id);
expect(await (await alice.api("GET", "/palettes")).json()).toHaveLength(1);
expect(await (await bob.api("GET", "/palettes")).json()).toEqual([]);
expect((await bob.api("DELETE", `/palettes/${palette.id}`)).status).toBe(404);
expect((await alice.api("DELETE", `/palettes/${palette.id}`)).status).toBe(204);
expect(await (await alice.api("GET", "/palettes")).json()).toEqual([]);
});
it("rejects invalid palettes", async () => {
const { user } = setup();
const alice = user("alice");
expect((await alice.api("POST", "/palettes", { colors: ["#264653"] })).status).toBe(400);
expect((await alice.api("POST", "/palettes", { colors: ["#264653", "red"] })).status).toBe(400);
expect((await alice.api("POST", "/palettes", { colors: Array(11).fill("#264653") })).status).toBe(400);
});
});
describe("api tokens", () => { describe("api tokens", () => {
it("creates, lists and revokes the caller's tokens only", async () => { it("creates, lists and revokes the caller's tokens only", async () => {
const { app, user } = setup(); const { app, user } = setup();
+8 -4
View File
@@ -9,7 +9,7 @@ import { openDb } from "../src/server/db/index.js";
export const BASE_URL = "https://short.test"; export const BASE_URL = "https://short.test";
export function setup() { export function setup(overrides: Partial<Config> = {}) {
const config: Config = { const config: Config = {
baseUrl: BASE_URL, baseUrl: BASE_URL,
oidc: { issuer: "https://auth.test/", clientId: "id", clientSecret: "secret" }, oidc: { issuer: "https://auth.test/", clientId: "id", clientSecret: "secret" },
@@ -22,14 +22,18 @@ export function setup() {
disableAttribution: false, disableAttribution: false,
retentionDays: 90, retentionDays: 90,
port: 0, port: 0,
...overrides,
}; };
const db = openDb(":memory:"); const db = openDb(":memory:");
// The fake provider returns whatever claims the test queued for the next login. // The fake provider returns whatever claims the test queued for the next login.
let nextClaims: OidcClaims = { sub: "sub-x", username: "x", groups: [] }; let nextClaims: OidcClaims | Error = { sub: "sub-x", username: "x", groups: [] };
const oidc: OidcProvider = { const oidc: OidcProvider = {
authorizationUrl: async ({ state }) => new URL(`https://auth.test/authorize?state=${state}`), authorizationUrl: async ({ state }) => new URL(`https://auth.test/authorize?state=${state}`),
exchange: async () => nextClaims, exchange: async () => {
if (nextClaims instanceof Error) throw nextClaims;
return nextClaims;
},
}; };
const app = createApp({ db, config, oidc }); const app = createApp({ db, config, oidc });
@@ -52,7 +56,7 @@ export function setup() {
db, db,
config, config,
user, user,
setNextLogin: (claims: OidcClaims) => { setNextLogin: (claims: OidcClaims | Error) => {
nextClaims = claims; nextClaims = claims;
}, },
}; };
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { contrast, parseCoolorsInput, themeFromPalette } from "../src/web/lib/palette.js";
// A mix of real coolors.co palettes: dark, light, pastel and a 10-color one.
const SAMPLE_PALETTES = [
"780000-c1121f-fdf0d5-003049-669bbc",
"606c38-283618-fefae0-dda15e-bc6c25",
"cdb4db-ffc8dd-ffafcc-bde0fe-a2d2ff",
"001219-005f73-0a9396-94d2bd-e9d8a6-ee9b00-ca6702-bb3e03-ae2012-9b2226",
].map((p) => parseCoolorsInput(p)!);
describe("coolors.co palettes", () => {
it("parses palette and generator links as well as bare color lists", () => {
const expected = ["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"];
expect(parseCoolorsInput("https://coolors.co/palette/264653-2a9d8f-e9c46a-f4a261-e76f51")).toEqual(expected);
expect(parseCoolorsInput("https://coolors.co/264653-2a9d8f-e9c46a-f4a261-e76f51")).toEqual(expected);
expect(parseCoolorsInput("coolors.co/palette/264653-2A9D8F-e9c46a-f4a261-e76f51?ref=x")).toEqual(expected);
expect(parseCoolorsInput(" 264653-2a9d8f-e9c46a-f4a261-e76f51 ")).toEqual(expected);
});
it("rejects anything else", () => {
expect(parseCoolorsInput("")).toBeNull();
expect(parseCoolorsInput("https://example.com/264653-2a9d8f")).toBeNull();
expect(parseCoolorsInput("https://coolors.co/palettes/trending")).toBeNull();
expect(parseCoolorsInput("264653")).toBeNull();
expect(parseCoolorsInput("zzzzzz-2a9d8f")).toBeNull();
});
it("maps palettes to a readable theme in both variants", () => {
for (const colors of SAMPLE_PALETTES) {
for (const variant of ["dark", "light"] as const) {
const theme = themeFromPalette(colors, variant);
expect(contrast(theme.text, theme.background)).toBeGreaterThanOrEqual(4.5);
expect(contrast(theme.buttonText, theme.button)).toBeGreaterThanOrEqual(4.5);
expect(theme.button).not.toBe(theme.background);
}
}
});
it("uses the darkest color as dark background and the lightest as light background", () => {
const colors = ["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"];
expect(themeFromPalette(colors, "dark").background).toBe("#264653");
expect(themeFromPalette(colors, "light").background).toBe("#e9c46a");
});
});