mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b338e1abb4 | ||
|
|
95c27e7353 | ||
|
|
8b7d83aa14 | ||
|
|
26c17228f8 | ||
|
|
3dc2c28330 | ||
|
|
00f5fe1f33 | ||
|
|
5f30a6d448 | ||
|
|
50dfdf53b9 | ||
|
|
6d427db2c4 | ||
|
|
03fb4dcf0c | ||
|
|
ab2150330a | ||
|
|
3eea5c23ef | ||
|
|
26d2883935 | ||
|
|
767290e1b5 | ||
|
|
35cb7da929 | ||
|
|
e44e56fd2d | ||
|
|
c3640c8966 | ||
|
|
55d2b9433f | ||
|
|
624517e010 | ||
|
|
74ce76ab8b | ||
|
|
8998e0e0e1 | ||
|
|
875773f795 |
@@ -13,14 +13,16 @@ env:
|
||||
DOCKER_HUB_REGISTRY: docker.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
DOCKER_HUB_IMAGE_NAME: traberph/short
|
||||
PRIVATE_REGISTRY: registry.traberph.de
|
||||
PRIVATE_IMAGE_NAME: public/short
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v7
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
@@ -39,39 +41,47 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.DOCKER_HUB_REGISTRY }}
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
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
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
${{ env.DOCKER_HUB_REGISTRY }}/${{ env.DOCKER_HUB_IMAGE_NAME }}
|
||||
${{ env.PRIVATE_REGISTRY }}/${{ env.PRIVATE_IMAGE_NAME }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}
|
||||
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/heads/main') }}
|
||||
|
||||
- name: Build and push Docker images
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
|
||||
+7
-2
@@ -1,4 +1,4 @@
|
||||
FROM node:24-slim AS base
|
||||
FROM node:24-alpine AS base
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
@@ -11,7 +11,12 @@ RUN pnpm build
|
||||
FROM base AS prod-deps
|
||||
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
|
||||
ENV NODE_ENV=production \
|
||||
PORT=3000 \
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
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 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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
@@ -55,7 +55,7 @@ Copy `.env.template` to `.env` and fill it in:
|
||||
| `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 |
|
||||
| `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 |
|
||||
|
||||
### 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.
|
||||
|
||||
## 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
|
||||
|
||||
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"}'
|
||||
```
|
||||
|
||||
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`.
|
||||
|
||||
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
|
||||
|
||||
```sh
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `pages` ADD `show_logos` integer DEFAULT true NOT NULL;
|
||||
@@ -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`);
|
||||
@@ -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": {}
|
||||
}
|
||||
}
|
||||
@@ -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": {}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,20 @@
|
||||
"when": 1791978231861,
|
||||
"tag": "0000_init",
|
||||
"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
@@ -2,9 +2,10 @@ import { Hono } from "hono";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
import { desc, eq, and } from "drizzle-orm";
|
||||
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 {
|
||||
createBlockSchema,
|
||||
createPaletteSchema,
|
||||
createPageSchema,
|
||||
createTokenSchema,
|
||||
pinSchema,
|
||||
@@ -15,10 +16,11 @@ import {
|
||||
} from "../shared/validation.js";
|
||||
import type { AppEnv, Deps } from "./app.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 { forbidden, HttpError, notFound } from "./lib/errors.js";
|
||||
import { removeMedia, saveAvatar } from "./lib/media.js";
|
||||
import { deletePalette, listPalettes, savePalette } from "./lib/palettes.js";
|
||||
import * as pages from "./lib/pages.js";
|
||||
import { getStats, resetStats } from "./lib/stats.js";
|
||||
|
||||
@@ -65,7 +67,7 @@ export function apiRoutes(deps: Deps) {
|
||||
|
||||
.get("/me", (c) => {
|
||||
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)
|
||||
@@ -133,6 +135,18 @@ export function apiRoutes(deps: Deps) {
|
||||
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)
|
||||
.get("/tokens", (c) => {
|
||||
const rows = db
|
||||
@@ -172,6 +186,12 @@ export function apiRoutes(deps: Deps) {
|
||||
if (!c.var.actor.isAdmin) throw forbidden();
|
||||
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) => {
|
||||
if (!c.var.actor.isAdmin) throw forbidden();
|
||||
return c.json(pages.listConflicts(db));
|
||||
|
||||
@@ -48,6 +48,10 @@ export function createApp(deps: Deps) {
|
||||
|
||||
app.onError((err, c) => {
|
||||
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 (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);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Hono } from "hono";
|
||||
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
|
||||
import type { AppEnv, Deps } from "../app.js";
|
||||
import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js";
|
||||
import { HttpError } from "../lib/errors.js";
|
||||
import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js";
|
||||
|
||||
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.
|
||||
const requestUrl = new URL(c.req.url);
|
||||
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);
|
||||
|
||||
setCookie(c, SESSION_COOKIE, createSession(db, actor.id), {
|
||||
|
||||
@@ -75,3 +75,14 @@ export function createApiToken(db: Db, userId: number, name: string) {
|
||||
export function pruneSessions(db: Db, now = new Date()): number {
|
||||
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,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export const pages = sqliteTable(
|
||||
title: text("title"),
|
||||
avatar: text("avatar"),
|
||||
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" }),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
@@ -101,6 +103,20 @@ export const apiTokens = sqliteTable("api_tokens", {
|
||||
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", {
|
||||
key: text("key").primaryKey(),
|
||||
value: text("value").notNull(),
|
||||
|
||||
+50
-14
@@ -103,8 +103,8 @@ export function createPage(db: Db, actor: Actor, input: CreatePageInput): PageSu
|
||||
export function updatePage(db: Db, actor: Actor, id: number, input: UpdatePageInput): PageDetail {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
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") {
|
||||
throw new HttpError(400, "Only link pages have a title and theme");
|
||||
if ((input.title !== undefined || input.theme !== undefined || input.showLogos !== undefined) && page.kind !== "linkpage") {
|
||||
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"] });
|
||||
@@ -147,7 +147,25 @@ function totalClicks(db: Db, pageIds: number[]): Map<number, number> {
|
||||
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 {
|
||||
id: row.id,
|
||||
namespace: row.namespace,
|
||||
@@ -158,6 +176,7 @@ function toSummary(row: PageRow, clicks: number, pinned: boolean): PageSummary {
|
||||
title: row.title,
|
||||
totalClicks: clicks,
|
||||
pinned,
|
||||
usedOn,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -171,7 +190,11 @@ export function listPages(db: Db, actor: Actor): PageSummary[] {
|
||||
rows.map((r) => r.id),
|
||||
);
|
||||
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[] {
|
||||
@@ -196,7 +219,7 @@ export function getBlocks(db: Db, pageId: number): Block[] {
|
||||
kind: b.kind,
|
||||
label: b.label,
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -205,8 +228,9 @@ export function getPageDetail(db: Db, actor: Actor, id: number): PageDetail {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
const clicks = totalClicks(db, [id]).get(id) ?? 0;
|
||||
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,
|
||||
showLogos: page.showLogos,
|
||||
avatarUrl: avatarUrl(page.avatar),
|
||||
blocks: page.kind === "linkpage" ? getBlocks(db, id) : [],
|
||||
};
|
||||
@@ -224,14 +248,27 @@ function loadLinkPage(db: Db, actor: Actor, id: number): PageRow {
|
||||
|
||||
export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] {
|
||||
const page = loadLinkPage(db, actor, pageId);
|
||||
let targetId: number | null = null;
|
||||
if (input.kind === "link") {
|
||||
const target = db.select().from(pages).where(eq(pages.id, input.targetId)).get();
|
||||
if (!target || !canLinkTo(actor, page, target)) {
|
||||
throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] });
|
||||
// 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;
|
||||
if (input.kind === "link" && input.newLink) {
|
||||
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)) {
|
||||
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
|
||||
.select({ max: sql<number | null>`max(${blocks.position})` })
|
||||
.from(blocks)
|
||||
@@ -247,7 +284,6 @@ export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBloc
|
||||
targetId,
|
||||
})
|
||||
.run();
|
||||
return getBlocks(db, pageId);
|
||||
}
|
||||
|
||||
function loadManagedBlock(db: Db, actor: Actor, blockId: number) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -11,7 +11,8 @@ import { LinkPage, MessagePage } from "./views.js";
|
||||
export function publicRoutes({ db, config }: Deps) {
|
||||
const clientIp = (c: Context<AppEnv>): string => {
|
||||
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;
|
||||
}
|
||||
try {
|
||||
@@ -52,7 +53,8 @@ export function publicRoutes({ db, config }: Deps) {
|
||||
avatarUrl={avatarUrl(page.avatar)}
|
||||
theme={(page.theme as Theme | null) ?? DEFAULT_THEME}
|
||||
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}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -7,7 +7,7 @@ import { renderMarkdown } from "./markdown.js";
|
||||
const STYLES = `
|
||||
*{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)}
|
||||
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}
|
||||
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}
|
||||
@@ -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}
|
||||
.text{line-height:1.5;text-align:center}
|
||||
.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}
|
||||
.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}}
|
||||
|
||||
+14
-1
@@ -6,6 +6,10 @@ export type PageKind = "redirect" | "linkpage";
|
||||
export interface Me {
|
||||
username: string;
|
||||
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 {
|
||||
@@ -18,6 +22,8 @@ export interface PageSummary {
|
||||
title: string | null;
|
||||
totalClicks: number;
|
||||
pinned: boolean;
|
||||
/** Short links only: the link pages that have a button pointing to this link. */
|
||||
usedOn: { id: number; path: string }[];
|
||||
}
|
||||
|
||||
export interface Block {
|
||||
@@ -26,11 +32,12 @@ export interface Block {
|
||||
kind: "link" | "text";
|
||||
label: 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 {
|
||||
theme: Theme;
|
||||
showLogos: boolean;
|
||||
avatarUrl: string | null;
|
||||
blocks: Block[];
|
||||
}
|
||||
@@ -49,6 +56,12 @@ export interface PageStats {
|
||||
series: StatsDay[];
|
||||
}
|
||||
|
||||
export interface SavedPalette {
|
||||
id: number;
|
||||
colors: string[]; // "#rrggbb"
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface ApiToken {
|
||||
id: number;
|
||||
name: string;
|
||||
|
||||
@@ -67,13 +67,25 @@ export const updatePageSchema = z.object({
|
||||
dest: destSchema.optional(),
|
||||
title: titleSchema.optional(),
|
||||
theme: themeSchema.optional(),
|
||||
showLogos: z.boolean().optional(),
|
||||
});
|
||||
export type UpdatePageInput = z.infer<typeof updatePageSchema>;
|
||||
|
||||
export const createBlockSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("link"), targetId: z.number().int().positive(), label: titleSchema }),
|
||||
z.object({ kind: z.literal("text"), markdown: z.string().max(5000) }),
|
||||
]);
|
||||
// A link button points at an existing short link (targetId) or creates a new one in the page's namespace (newLink).
|
||||
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) }),
|
||||
])
|
||||
.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 const updateBlockSchema = z.object({
|
||||
@@ -89,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),
|
||||
});
|
||||
|
||||
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 createTokenSchema = z.object({ name: z.string().trim().min(1).max(100) });
|
||||
|
||||
+7
-2
@@ -4,8 +4,9 @@ import { useApi } from "../api.js";
|
||||
import { buttonClass } from "../components/ui/button.js";
|
||||
import { Link } from "../components/ui/misc.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 { AdminUserScreen } from "../screens/AdminUserScreen.js";
|
||||
import { DetailScreen } from "../screens/detail/DetailScreen.js";
|
||||
import { ListScreen } from "../screens/ListScreen.js";
|
||||
import { OverviewScreen } from "../screens/OverviewScreen.js";
|
||||
@@ -61,6 +62,7 @@ export function App() {
|
||||
location.href = "/~/";
|
||||
};
|
||||
|
||||
setViewer(me.data.username);
|
||||
const route = parseRoute(path);
|
||||
let screen;
|
||||
switch (route.name) {
|
||||
@@ -77,7 +79,10 @@ export function App() {
|
||||
screen = <TokensScreen />;
|
||||
break;
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { KeyRound, LayoutDashboard, Link2, LogOut, PanelsTopLeft, ShieldCheck } from "lucide-react";
|
||||
import type { Me } from "../../shared/api-types.js";
|
||||
import { ThemeCycleButton, ThemeSwitch } from "../components/ThemeToggle.js";
|
||||
import { Button } from "../components/ui/button.js";
|
||||
import { Link } from "../components/ui/misc.js";
|
||||
import { cx } from "../lib/cx.js";
|
||||
@@ -14,8 +15,12 @@ function sectionOf(route: Route): Section | null {
|
||||
case "tokens":
|
||||
case "admin":
|
||||
return route.name;
|
||||
case "adminUser":
|
||||
return "admin";
|
||||
case "list":
|
||||
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";
|
||||
default:
|
||||
return null;
|
||||
@@ -74,6 +79,9 @@ export function Shell({ me, route, onLogout, children }: { me: Me; route: Route;
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<div className="px-4 pb-3">
|
||||
<ThemeSwitch />
|
||||
</div>
|
||||
<div className="flex items-center gap-3 border-t border-border p-4">
|
||||
<UserAvatar username={me.username} />
|
||||
<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">
|
||||
<Logo />
|
||||
<div className="flex items-center gap-1">
|
||||
<ThemeCycleButton />
|
||||
<UserAvatar username={me.username} />
|
||||
<Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out">
|
||||
<LogOut />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
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 { Dialog } from "./ui/dialog.js";
|
||||
import { Field, Input, PrefixInput, Select } from "./ui/form.js";
|
||||
@@ -24,15 +24,17 @@ export function CreatePageDialog({
|
||||
open,
|
||||
onClose,
|
||||
onCreated,
|
||||
fixedNamespace,
|
||||
}: {
|
||||
kind: PageKind;
|
||||
me: Me;
|
||||
open: boolean;
|
||||
onClose: () => 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(me.username);
|
||||
const [namespace, setNamespace] = useState(fixedNamespace ?? me.username);
|
||||
const [code, setCode] = useState("");
|
||||
const [value, setValue] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -102,16 +104,12 @@ export function CreatePageDialog({
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{me.isAdmin && (
|
||||
<Field label="Namespace" hint="Root links are only available to admins." error={errors.namespace}>
|
||||
{me.isAdmin && fixedNamespace === undefined && (
|
||||
<Field label="Namespace" error={errors.namespace}>
|
||||
{(id) => (
|
||||
<Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
|
||||
<option value="">Root (/)</option>
|
||||
{(users.data ?? [me.username]).map((u) => (
|
||||
<option key={u} value={u}>
|
||||
{u === me.username ? `${u} (you)` : u}
|
||||
</option>
|
||||
))}
|
||||
<option value={me.username}>/{me.username}/ (yours)</option>
|
||||
<option value="">Root /</option>
|
||||
</Select>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -102,3 +102,45 @@ export function ColorInput({ value, onChange, label }: { value: string; onChange
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 { cx } from "../../lib/cx.js";
|
||||
import { linkHandler } from "../../router.js";
|
||||
import { Button } from "./button.js";
|
||||
import { useToast } from "./toast.js";
|
||||
|
||||
export function Link({ to, className, children, ...rest }: { to: string; className?: string; children: ReactNode; "aria-current"?: "page" }) {
|
||||
return (
|
||||
<a href={to} onClick={linkHandler(to)} className={className} {...rest}>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
// In-app link: a normal <a> that navigates without a page reload.
|
||||
export function Link({ to, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) {
|
||||
return <a href={to} onClick={linkHandler(to)} {...rest} />;
|
||||
}
|
||||
|
||||
export function publicUrl(path: string): string {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="manifest" href="/~/manifest.webmanifest" />
|
||||
<link rel="apple-touch-icon" href="/~/icon-192x192.png" />
|
||||
<title>short</title>
|
||||
<script src="/~/theme-init.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
export function stripMarkdown(markdown: string): string {
|
||||
return markdown
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
||||
.replace(/[*_`#>~]/g, "")
|
||||
.replace(/^\s*(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "")
|
||||
.replace(/[*_`~]/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 === "" },
|
||||
];
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -33,19 +33,47 @@ export function linkHandler(to: string) {
|
||||
export type Route =
|
||||
| { name: "overview" }
|
||||
| { 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: "admin" }
|
||||
| { name: "adminUser"; username: string }
|
||||
| { name: "notFound" };
|
||||
|
||||
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 {
|
||||
return kind === "redirect" ? "/~/links" : "/~/pages";
|
||||
}
|
||||
|
||||
export function detailPath(page: { id: number; kind: PageKind }, tab?: string): string {
|
||||
return `${listPath(page.kind)}/${page.id}${tab ? `/${tab}` : ""}`;
|
||||
export function adminUserPath(username: string): string {
|
||||
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 {
|
||||
@@ -53,6 +81,14 @@ export function parseRoute(path: string): Route {
|
||||
if (p === "/~") return { name: "overview" };
|
||||
if (p === "/~/tokens") return { name: "tokens" };
|
||||
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]+))?)?$/);
|
||||
if (m) {
|
||||
const kind = KIND_SEGMENT[m[1]!]!;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { PinOff, TriangleAlert, Users } from "lucide-react";
|
||||
import type { Conflict, PageSummary } from "../../shared/api-types.js";
|
||||
import { ChevronRight, PinOff, TriangleAlert, Users } from "lucide-react";
|
||||
import type { Conflict, Me, PageSummary } from "../../shared/api-types.js";
|
||||
import { api, useApi } from "../api.js";
|
||||
import { Button } from "../components/ui/button.js";
|
||||
import { Select } from "../components/ui/form.js";
|
||||
import { Link } from "../components/ui/misc.js";
|
||||
import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.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> }) {
|
||||
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 users = useApi<string[]>("/users");
|
||||
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 (
|
||||
<>
|
||||
<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">
|
||||
<UsersCard users={users.data} pages={pages.data} me={me} />
|
||||
|
||||
{pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />}
|
||||
|
||||
<Card>
|
||||
@@ -80,7 +122,7 @@ export function AdminScreen() {
|
||||
<li key={c.pageId} className="flex items-center gap-3 px-5 py-3">
|
||||
<TriangleAlert className="size-4 text-warning-soft-fg" />
|
||||
<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
|
||||
</Link>
|
||||
</li>
|
||||
@@ -90,34 +132,6 @@ export function AdminScreen() {
|
||||
<CardBody className="text-sm text-muted">No conflicts.</CardBody>
|
||||
)}
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -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
@@ -1,19 +1,21 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { ChevronRight, Link2, PanelsTopLeft, Pin, Plus, Search } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
|
||||
import { useApi } from "../api.js";
|
||||
import { CreatePageDialog } from "../components/CreatePageDialog.js";
|
||||
import { PageTable } from "../components/PageTable.js";
|
||||
import { Button } from "../components/ui/button.js";
|
||||
import { Input, Select } from "../components/ui/form.js";
|
||||
import { CopyButton, DomainIcon, Link, publicUrl } from "../components/ui/misc.js";
|
||||
import { Badge, Card, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
|
||||
import { publicUrl } from "../components/ui/misc.js";
|
||||
import { PageHeader } from "../components/ui/surface.js";
|
||||
import { useToast } from "../components/ui/toast.js";
|
||||
import { isMine, myNamespaceOptions } from "../lib/scope.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: {
|
||||
title: "Short links",
|
||||
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",
|
||||
empty: "No short links yet",
|
||||
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: {
|
||||
title: "Link pages",
|
||||
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",
|
||||
empty: "No link pages yet",
|
||||
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 }) {
|
||||
const pages = useApi<PageSummary[]>("/pages");
|
||||
const toast = useToast();
|
||||
const [query, setQuery] = useState("");
|
||||
const [namespace, setNamespace] = useState<string | null>(null);
|
||||
const [creating, setCreating] = useState(false);
|
||||
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) => {
|
||||
if (page.kind === "linkpage") return navigate(detailPath(page));
|
||||
await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {});
|
||||
@@ -96,59 +51,13 @@ export function ListScreen({ kind, me }: { kind: PageKind; me: Me }) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={copy.title} description={copy.description} actions={createButton} />
|
||||
|
||||
<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>
|
||||
{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>
|
||||
|
||||
<PageHeader title={copy.title} description={me.isAdmin ? copy.adminDescription : copy.description} actions={createButton} />
|
||||
<PageTable
|
||||
kind={kind}
|
||||
pages={pages.data?.filter((p) => isMine(p, me))}
|
||||
namespaces={myNamespaceOptions(me)}
|
||||
empty={{ title: copy.empty, description: copy.emptyText, action: createButton }}
|
||||
/>
|
||||
<CreatePageDialog kind={kind} me={me} open={creating} onClose={() => setCreating(false)} onCreated={created} />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { CreatePageDialog } from "../components/CreatePageDialog.js";
|
||||
import { Button, buttonClass } from "../components/ui/button.js";
|
||||
import { DomainIcon, Link, Stat } from "../components/ui/misc.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";
|
||||
|
||||
function TopPages({ pages }: { pages: PageSummary[] }) {
|
||||
@@ -47,11 +48,12 @@ export function OverviewScreen({ me }: { me: Me }) {
|
||||
const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : 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 linkPages = all.filter((p) => p.kind === "linkpage");
|
||||
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 (
|
||||
<>
|
||||
@@ -60,12 +62,12 @@ export function OverviewScreen({ me }: { me: Me }) {
|
||||
description="Here's how your links are doing."
|
||||
actions={
|
||||
<>
|
||||
<Button variant="secondary" icon={<PanelsTopLeft />} onClick={() => setCreating("linkpage")}>
|
||||
New link page
|
||||
</Button>
|
||||
<Button icon={<Plus />} onClick={() => setCreating("redirect")}>
|
||||
New short link
|
||||
</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) => (
|
||||
<span key={c.pageId}>
|
||||
{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}
|
||||
</Link>
|
||||
</span>
|
||||
|
||||
@@ -10,26 +10,16 @@ import { Segmented } from "../../components/ui/form.js";
|
||||
import { Stat } from "../../components/ui/misc.js";
|
||||
import { Card, CardHeader, Skeleton } from "../../components/ui/surface.js";
|
||||
import { useAction } from "../../components/ui/toast.js";
|
||||
import { useResolvedTheme } from "../../lib/theme.js";
|
||||
|
||||
type Range = 7 | 30 | 90;
|
||||
|
||||
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[] }) {
|
||||
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(() => {
|
||||
const el = container.current;
|
||||
@@ -70,7 +60,7 @@ function Chart({ series }: { series: StatsDay[] }) {
|
||||
resize.disconnect();
|
||||
plot.destroy();
|
||||
};
|
||||
}, [series, dark]);
|
||||
}, [series, mode]);
|
||||
|
||||
return <div ref={container} className="w-full" />;
|
||||
}
|
||||
|
||||
@@ -1,46 +1,72 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Check, ImageUp, Trash2 } from "lucide-react";
|
||||
import type { PageDetail } from "../../../shared/api-types.js";
|
||||
import { ImageUp, Trash2 } from "lucide-react";
|
||||
import type { Me, PageDetail } from "../../../shared/api-types.js";
|
||||
import type { Theme } from "../../../shared/validation.js";
|
||||
import { api } from "../../api.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 { useAction } from "../../components/ui/toast.js";
|
||||
import { cx } from "../../lib/cx.js";
|
||||
import { stripMarkdown } from "../../lib/markdown.js";
|
||||
import { PhoneFrame } from "./PhonePreview.js";
|
||||
import { sameTheme, ThemePicker } from "./ThemePicker.js";
|
||||
|
||||
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" } },
|
||||
{ name: "Violet", theme: { background: "#2e1065", text: "#ede9fe", button: "#7c3aed", buttonText: "#ffffff" } },
|
||||
{ name: "Forest", theme: { background: "#052e16", text: "#dcfce7", button: "#15803d", buttonText: "#ffffff" } },
|
||||
{ name: "Sunset", theme: { background: "#431407", text: "#ffedd5", button: "#ea580c", buttonText: "#ffffff" } },
|
||||
{ name: "Ocean", theme: { background: "#082f49", text: "#e0f2fe", button: "#0284c7", buttonText: "#ffffff" } },
|
||||
];
|
||||
|
||||
const COLOR_FIELDS: [keyof Theme, string][] = [
|
||||
["background", "Background"],
|
||||
["text", "Text"],
|
||||
["button", "Buttons"],
|
||||
["buttonText", "Button text"],
|
||||
];
|
||||
|
||||
const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase());
|
||||
// Button icon like on the public page: the website's logo when logos are on, otherwise its first letter.
|
||||
function MockIcon({ dest, logoDevToken }: { dest: string | null; logoDevToken: string | null }) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
let host = "";
|
||||
try {
|
||||
host = dest ? new URL(dest).hostname : "";
|
||||
} catch {
|
||||
// Keep the letter placeholder.
|
||||
}
|
||||
if (host && logoDevToken && !failed) {
|
||||
return (
|
||||
<img
|
||||
src={`https://img.logo.dev/${encodeURIComponent(host)}?token=${encodeURIComponent(logoDevToken)}`}
|
||||
alt=""
|
||||
onError={() => setFailed(true)}
|
||||
className="size-7 shrink-0 rounded-full bg-white/85 object-cover"
|
||||
/>
|
||||
);
|
||||
}
|
||||
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.
|
||||
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 (
|
||||
<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" />}
|
||||
<div className="mt-4 mb-6 text-xl font-bold">{title || "Untitled"}</div>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{page.blocks.map((b) =>
|
||||
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 }}>
|
||||
{b.label}
|
||||
<div
|
||||
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>
|
||||
) : (
|
||||
<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 &&
|
||||
[0, 1, 2].map((i) => <div key={i} className="h-10 rounded-lg opacity-60" style={{ background: theme.button }} />)}
|
||||
</div>
|
||||
{logoDevToken && <p className="mt-auto pt-8 text-[11px] opacity-50">Logos provided by Logo.dev</p>}
|
||||
</div>
|
||||
</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 [theme, setTheme] = useState(page.theme);
|
||||
const [showLogos, setShowLogos] = useState(page.showLogos);
|
||||
const { busy, run } = useAction();
|
||||
const upload = useAction();
|
||||
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) => {
|
||||
if (!file) return;
|
||||
@@ -125,40 +153,29 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange:
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader title="Theme" description="Pick a preset or set your own colors." />
|
||||
<CardBody className="flex flex-col gap-6">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
{PRESETS.map((preset) => {
|
||||
const selected = sameTheme(preset.theme, theme);
|
||||
return (
|
||||
<button
|
||||
key={preset.name}
|
||||
type="button"
|
||||
onClick={() => setTheme(preset.theme)}
|
||||
className={cx(
|
||||
"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",
|
||||
)}
|
||||
>
|
||||
<div className="flex h-16 flex-col items-center justify-center gap-1.5 px-6" style={{ background: preset.theme.background }}>
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} />
|
||||
<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">
|
||||
{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>
|
||||
))}
|
||||
<CardHeader title="Theme" description="Pick a preset, use a palette from coolors.co or set your own colors." />
|
||||
<CardBody className="flex flex-col gap-7">
|
||||
<ThemePicker theme={theme} onChange={setTheme} />
|
||||
<div className="border-t border-border pt-6">
|
||||
<Switch
|
||||
label="Website logos"
|
||||
checked={me.logoDev && showLogos}
|
||||
onChange={setShowLogos}
|
||||
disabled={!me.logoDev}
|
||||
description={
|
||||
me.logoDev ? (
|
||||
<>
|
||||
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
|
||||
</a>
|
||||
. When off, buttons show the first letter instead and the logo.dev credit is hidden.
|
||||
</>
|
||||
) : (
|
||||
"Not available on this server. An admin can enable it by setting LOGO_DEV_TOKEN."
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
@@ -169,6 +186,7 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange:
|
||||
onClick={() => {
|
||||
setTitle(page.title ?? "");
|
||||
setTheme(page.theme);
|
||||
setShowLogos(page.showLogos);
|
||||
}}
|
||||
>
|
||||
Discard
|
||||
@@ -180,8 +198,14 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange:
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="hidden lg:block">
|
||||
<MockPreview title={title} avatarUrl={page.avatarUrl} theme={theme} page={page} />
|
||||
<div className="hidden lg:block lg:self-stretch">
|
||||
<MockPreview
|
||||
title={title}
|
||||
avatarUrl={page.avatarUrl}
|
||||
theme={theme}
|
||||
page={page}
|
||||
logoDevToken={me.logoDev && showLogos ? me.logoDevToken : null}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,20 +2,38 @@ import { useEffect, useState } from "react";
|
||||
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
|
||||
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
|
||||
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 { api, useApi } from "../../api.js";
|
||||
import { Button } from "../../components/ui/button.js";
|
||||
import { api, ApiRequestError, errorMessage, useApi } from "../../api.js";
|
||||
import { Button, buttonClass } from "../../components/ui/button.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 { 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 { stripMarkdown } from "../../lib/markdown.js";
|
||||
import { detailPath } from "../../router.js";
|
||||
import { LivePreview } from "./PhonePreview.js";
|
||||
|
||||
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({
|
||||
editing,
|
||||
@@ -30,52 +48,98 @@ function BlockDialog({
|
||||
onClose: () => void;
|
||||
onSaved: (blocks: Block[]) => void;
|
||||
}) {
|
||||
const pages = useApi<PageSummary[]>(editing?.kind === "link" && !editing.block ? "/pages" : null);
|
||||
const { busy, run } = useAction();
|
||||
const isNewLink = editing?.kind === "link" && !editing.block;
|
||||
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 [dest, setDest] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
const [label, setLabel] = useState("");
|
||||
const [labelTouched, setLabelTouched] = useState(false);
|
||||
const [markdown, setMarkdown] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setErrors({});
|
||||
setSource("existing");
|
||||
setTargetId("");
|
||||
setDest("");
|
||||
setCode("");
|
||||
setLabel(editing?.block?.label ?? "");
|
||||
setLabelTouched(!!editing?.block);
|
||||
setMarkdown(editing?.block?.markdown ?? "");
|
||||
}, [editing]);
|
||||
|
||||
if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
|
||||
|
||||
// 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 isNew = !editing.block;
|
||||
const noTargets = !!pages.data && targets.length === 0;
|
||||
|
||||
const submit = () =>
|
||||
run(async () => {
|
||||
let blocks: Block[];
|
||||
if (editing.block) {
|
||||
blocks = await api<Block[]>("PATCH", `/blocks/${editing.block.id}`, editing.kind === "text" ? { markdown } : { label });
|
||||
} else if (editing.kind === "link") {
|
||||
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: Number(targetId), label });
|
||||
} else {
|
||||
blocks = await api<Block[]>("POST", `/pages/${page.id}/blocks`, { kind: "text", markdown });
|
||||
}
|
||||
// Without existing links, creating one is the only option.
|
||||
useEffect(() => {
|
||||
if (noTargets) setSource("new");
|
||||
}, [noTargets]);
|
||||
|
||||
if (!editing) return <Dialog open={false} onClose={onClose} title="" />;
|
||||
|
||||
const isNew = !editing.block;
|
||||
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);
|
||||
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 (
|
||||
<Dialog
|
||||
open
|
||||
onClose={onClose}
|
||||
onSubmit={submit}
|
||||
onSubmit={() => void submit()}
|
||||
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={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={busy} disabled={editing.kind === "link" ? !label.trim() || (isNew && !targetId) : !markdown.trim()}>
|
||||
{isNew ? "Add" : "Save"}
|
||||
<Button type="submit" loading={busy} disabled={!canSubmit}>
|
||||
{isNew ? (source === "new" && editing.kind === "link" ? "Create and add" : "Add") : "Save"}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
@@ -83,34 +147,95 @@ function BlockDialog({
|
||||
{editing.kind === "link" ? (
|
||||
<>
|
||||
{isNew && (
|
||||
<Field
|
||||
label="Short link"
|
||||
hint={
|
||||
pages.data && !targets.length ? (
|
||||
<>
|
||||
You don't have any short links yet.{" "}
|
||||
<Link to="/~/links" className="underline">
|
||||
Create one first
|
||||
</Link>
|
||||
.
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<Segmented
|
||||
ariaLabel="Link"
|
||||
value={source}
|
||||
onChange={(v) => {
|
||||
setSource(v);
|
||||
setErrors({});
|
||||
}}
|
||||
options={[
|
||||
{ value: "existing", label: "Existing link" },
|
||||
{ value: "new", label: "New link" },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
|
||||
{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) => (
|
||||
<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>
|
||||
{targets.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.path} → {p.dest}
|
||||
</option>
|
||||
{groupByNamespace(targets, page.namespace).map(([ns, links]) => (
|
||||
<optgroup key={ns} label={ns ? `/${ns}/` : "Root /"}>
|
||||
{links.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.path} → {p.dest}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
</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>
|
||||
</>
|
||||
) : (
|
||||
@@ -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 }) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: block.id });
|
||||
const isLink = block.kind === "link";
|
||||
@@ -152,8 +280,24 @@ function SortableBlock({ block, onEdit, onDelete }: { block: Block; onEdit: () =
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<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>
|
||||
{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">
|
||||
<Pencil />
|
||||
</Button>
|
||||
@@ -232,7 +376,7 @@ export function ContentTab({ page, me, onChange }: { page: PageDetail; me: Me; o
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="hidden lg:block">
|
||||
<div className="hidden lg:block lg:self-stretch">
|
||||
<LivePreview path={page.path} version={version} />
|
||||
</div>
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useApi } from "../../api.js";
|
||||
import { buttonClass } from "../../components/ui/button.js";
|
||||
import { CopyButton, DomainIcon, Link, publicUrl, Tabs } from "../../components/ui/misc.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 { AppearanceTab } from "./AppearanceTab.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 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(() => {
|
||||
if (p && p.kind !== kind) history.replaceState(null, "", detailPath(p, tab));
|
||||
}, [p, kind, tab]);
|
||||
if (!p) return;
|
||||
const canonical = detailPath(p, tab);
|
||||
if (location.pathname.replace(/\/+$/, "") !== canonical) replacePath(canonical);
|
||||
}, [p, tab]);
|
||||
|
||||
if (page.error) {
|
||||
return (
|
||||
@@ -67,9 +70,21 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
|
||||
return (
|
||||
<>
|
||||
<nav className="mb-3 flex items-center gap-1 text-sm text-muted" aria-label="Breadcrumb">
|
||||
<Link to={listPath(p.kind)} className="hover:text-fg">
|
||||
{p.kind === "redirect" ? "Short links" : "Link pages"}
|
||||
</Link>
|
||||
{backPath(p) === listPath(p.kind) ? (
|
||||
<Link to={listPath(p.kind)} className="hover:text-fg">
|
||||
{p.kind === "redirect" ? "Short links" : "Link pages"}
|
||||
</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" />
|
||||
<span className="truncate text-fg">{p.path}</span>
|
||||
</nav>
|
||||
@@ -109,7 +124,7 @@ export function DetailScreen({ id, kind, tab, me }: { id: number; kind: PageKind
|
||||
|
||||
<div className="animate-fade-in" key={active}>
|
||||
{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 === "qr" && <QrTab url={url} name={p.code} />}
|
||||
{active === "settings" && <SettingsTab page={p} me={me} onChange={page.set} reload={page.reload} />}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Field, Input, PrefixInput } from "../../components/ui/form.js";
|
||||
import { CopyButton, publicUrl } from "../../components/ui/misc.js";
|
||||
import { Alert, Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.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 }) {
|
||||
const [dest, setDest] = useState(page.dest ?? "");
|
||||
@@ -153,7 +153,7 @@ export function SettingsTab({
|
||||
if (!ok) return;
|
||||
void run(async () => {
|
||||
await api("DELETE", `/pages/${page.id}`);
|
||||
navigate(listPath(page.kind));
|
||||
navigate(backPath(page));
|
||||
}, `Deleted ${page.path}`);
|
||||
};
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
+23
-22
@@ -1,5 +1,8 @@
|
||||
@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. */
|
||||
@theme {
|
||||
--color-canvas: #f6f6f8;
|
||||
@@ -40,28 +43,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-canvas: #0c0c10;
|
||||
--color-surface: #141419;
|
||||
--color-surface-2: #1d1d24;
|
||||
--color-border: #26262e;
|
||||
--color-border-strong: #34343e;
|
||||
--color-fg: #ececf1;
|
||||
--color-muted: #9898a6;
|
||||
--color-accent: #8b5cf6;
|
||||
--color-accent-hover: #7c3aed;
|
||||
--color-accent-soft: #241a3d;
|
||||
--color-accent-soft-fg: #c4b5fd;
|
||||
--color-danger: #ef4444;
|
||||
--color-danger-soft: #2c1517;
|
||||
--color-danger-soft-fg: #fca5a5;
|
||||
--color-warning-soft: #2b2112;
|
||||
--color-warning-soft-fg: #fcd34d;
|
||||
--color-chart-1: #a78bfa;
|
||||
--color-chart-2: #38bdf8;
|
||||
color-scheme: dark;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--color-canvas: #0c0c10;
|
||||
--color-surface: #141419;
|
||||
--color-surface-2: #1d1d24;
|
||||
--color-border: #26262e;
|
||||
--color-border-strong: #34343e;
|
||||
--color-fg: #ececf1;
|
||||
--color-muted: #9898a6;
|
||||
--color-accent: #8b5cf6;
|
||||
--color-accent-hover: #7c3aed;
|
||||
--color-accent-soft: #241a3d;
|
||||
--color-accent-soft-fg: #c4b5fd;
|
||||
--color-danger: #ef4444;
|
||||
--color-danger-soft: #2c1517;
|
||||
--color-danger-soft-fg: #fca5a5;
|
||||
--color-warning-soft: #2b2112;
|
||||
--color-warning-soft-fg: #fcd34d;
|
||||
--color-chart-1: #a78bfa;
|
||||
--color-chart-2: #38bdf8;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
||||
+150
-1
@@ -46,7 +46,7 @@ describe("authentication", () => {
|
||||
expect(callback.status).toBe(302);
|
||||
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();
|
||||
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.
|
||||
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({
|
||||
username: "alice",
|
||||
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 () => {
|
||||
const { app, setNextLogin } = setup();
|
||||
const login = await app.request("/~/auth/login");
|
||||
@@ -165,6 +178,24 @@ describe("namespaces and permissions", () => {
|
||||
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 () => {
|
||||
const { user } = setup();
|
||||
const alice = user("alice");
|
||||
@@ -194,6 +225,54 @@ describe("link pages", () => {
|
||||
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 () => {
|
||||
const { app, user } = setup();
|
||||
const alice = user("alice");
|
||||
@@ -209,6 +288,29 @@ describe("link pages", () => {
|
||||
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 () => {
|
||||
const { app, user } = setup();
|
||||
const admin = user("root", true);
|
||||
@@ -250,6 +352,21 @@ describe("redirects and stats", () => {
|
||||
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 () => {
|
||||
const { app, user } = setup();
|
||||
expect((await app.request("/nope")).status).toBe(404);
|
||||
@@ -264,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", () => {
|
||||
it("creates, lists and revokes the caller's tokens only", async () => {
|
||||
const { app, user } = setup();
|
||||
|
||||
+8
-4
@@ -9,7 +9,7 @@ import { openDb } from "../src/server/db/index.js";
|
||||
|
||||
export const BASE_URL = "https://short.test";
|
||||
|
||||
export function setup() {
|
||||
export function setup(overrides: Partial<Config> = {}) {
|
||||
const config: Config = {
|
||||
baseUrl: BASE_URL,
|
||||
oidc: { issuer: "https://auth.test/", clientId: "id", clientSecret: "secret" },
|
||||
@@ -22,14 +22,18 @@ export function setup() {
|
||||
disableAttribution: false,
|
||||
retentionDays: 90,
|
||||
port: 0,
|
||||
...overrides,
|
||||
};
|
||||
const db = openDb(":memory:");
|
||||
|
||||
// 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 = {
|
||||
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 });
|
||||
@@ -52,7 +56,7 @@ export function setup() {
|
||||
db,
|
||||
config,
|
||||
user,
|
||||
setNextLogin: (claims: OidcClaims) => {
|
||||
setNextLogin: (claims: OidcClaims | Error) => {
|
||||
nextClaims = claims;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user