Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-05-04 08:30:15 +03:00
commit 75e03b42f7
99 files changed
+12285

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
node_modules
.next
out
dist
.env
.env.local
prisma/dev.db
prisma/dev.db-journal
prisma/migrations/*/migration_lock.toml
*.log
.DS_Store
+115
View File
@@ -0,0 +1,115 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Commands
```bash
npm run dev # start dev server on :3000
npm run build # prisma generate + migrate deploy + next build
npm run lint # next lint
npm run db:migrate # prisma migrate dev (create + apply a new migration)
npm run db:push # prisma db push (apply schema without creating migration files)
npm run db:studio # open Prisma Studio GUI
```
There are no automated tests. Verification is done by running `npm run build` (TypeScript + Next.js compilation) and manual browser testing.
## Required environment variables (`.env`)
```
DATABASE_URL="file:./dev.db"
SESSION_SECRET="<at least 32 random characters>"
```
`SESSION_SECRET` is validated at startup in `src/lib/session.ts` — the server will refuse to start without it.
## Architecture
### Stack
- **Next.js 14.2** App Router, TypeScript, no test framework
- **Prisma 5.22** + **SQLite** (`prisma/dev.db`)
- **iron-session** for cookie auth (`florthoritania_session`)
- **bcryptjs** for password hashing
### Auth model
Two roles: `"dm"` and `"player"`. DM sees everything; players see only entries where `isPublic = true` OR an `EntryReveal` record exists linking that entry to one of the player's campaigns.
`src/lib/session.ts` exports three helpers used throughout API routes:
- `getSession()` — reads the iron-session cookie (no auth required)
- `requireAuth()` — throws a `Response(401)` if no session
- `requireDm()` — throws a `Response(403)` if role ≠ "dm"
Both throw `Response` objects deliberately — `asResponse()` in `src/lib/api.ts` catches and re-returns them.
### API route conventions
Every route file must have `export const dynamic = "force-dynamic"` (required because all routes call `cookies()`).
Route handlers follow this pattern:
```ts
export async function GET(req: Request) {
try {
await requireDm(); // or requireAuth() or getSession()
// ...
return json(data); // NextResponse.json wrapper
} catch (e) {
return asResponse(e); // handles thrown Response + unknown errors
}
}
```
`json()`, `err()`, and `asResponse()` are all in `src/lib/api.ts`. Never pass a bare status number to `json()` — it takes `ResponseInit`: `json(data, { status: 201 })`.
### Client-side data fetching
All client components fetch via `src/lib/client.ts`'s `api<T>(url, init?)` helper. It sets `Content-Type: application/json`, `cache: "no-store"`, and throws on non-OK responses with the `error` field from the JSON body.
### Context / providers
`src/components/ClientProviders.tsx` is the single React context for the whole app. It provides:
- `world` / `setWorld` — world settings (name, theme, accent colour, etc.)
- `session` / `setSession` — authenticated user state
- `lang` / `setLang` — current language ("en" | "ru"), persisted in `florte_lang` cookie
- `t(key)` — i18n lookup function; dictionaries are in `src/lib/i18n.ts`
- `refresh()` — re-fetches `/api/auth/me` and `/api/world` and updates both states
`ClientProviders` is initialised server-side in `src/app/layout.tsx` with `initialWorld` and `initialSession` props (fetched via Prisma + iron-session before the page renders).
### Rendering shell
`src/components/RootBody.tsx` decides whether to render the full `AppShell` (sidebar + topbar) or a bare layout (for `/login`, `/setup`, `/register`). `AppShell` also wires the `/` keyboard shortcut to navigate to search.
### Entry model
The central model is `Entry`. JSON columns (`fields`, `tags`, `stats`, `abilities`) are stored as JSON strings in SQLite and deserialized by `entryToDTO()` in `src/lib/serialize.ts`. Always go through `entryToDTO()` before returning entries from API routes.
Valid `kind` values are defined in `src/lib/kinds.ts` as `KindId`. Use `isKind(s)` to validate.
Entry body syntax (parsed client-side in the article page):
- `## Heading` — section heading
- `> Quote text` — blockquote (last line starting with `—` becomes attribution)
- `[[Entry Title]]` — wikilink, resolved to `/article/<slug>`
- `::secret … ::end` — DM-only block, invisible to players
### Wikilinks / backlinks
`src/lib/links.ts` exports `syncLinks(fromId, body)`. Call it after every create or update of an entry's body. It re-derives all `[[wikilinks]]` in the body, deletes old `Link` records for that entry, and inserts new ones. The `Link` table powers the "Mentioned in" backlinks on article pages.
### Campaigns and visibility
- `Campaign` has many `CampaignMember` (users) and many `EntryReveal` (entries revealed to that campaign)
- `InviteCode` is DM-created; on registration the code is consumed and the new user is added to the associated campaign
- Player entry visibility check in `GET /api/entries`: `isPublic OR reveals.some(r => campaignIds.includes(r.campaignId))`
### Import system
`src/lib/import.ts` defines `ImportPlan` and `applyPlan()`. Parsers for each source live in `src/app/api/import/{donjon,azgaar,fantasytown}/route.ts`. Each import route supports `?action=preview` (returns the plan as JSON) and `?action=apply` (commits it). `applyPlan()` calls `sanitize()` on all string fields before insertion to strip lone surrogate code points that Azgaar JSONs sometimes contain.
### Map
The map page (`src/app/map/page.tsx`) is fully client-side. Pan/zoom state (`scale`, `tx`, `ty`) is stored in React state; the CSS transform is applied to `.flo-map-stage`. Wheel zoom anchors to the cursor position. Pin positions are stored as 0..1 relative coordinates so they work at any scale. Map layers store background images as data: URLs in `MapLayer.imageData`.
### Styling
Three CSS files loaded globally via `src/styles/globals.css`:
- `florthoritania.css` — design system (CSS vars, layout primitives, all `.flo-*` classes)
- `extras.css` — additions: auth cards, modals, map overlays, theme switcher, responsive collapse
Themes (`midnight`, `parchment`, etc.) are applied as `data-theme` on `<html>`. Accent colour is a CSS var `--brass` overridden inline. Never use Tailwind — the entire design system is custom CSS classes.
### World model
`World` is a singleton (always `id = 1`). `src/lib/world.ts` exports `getOrCreateWorld()` which upserts it on first access.
### OpenAPI / Swagger
The spec is hand-authored in `src/lib/openapi.ts` and served at `/api/openapi.json`. The Swagger UI at `/api-docs` loads `swagger-ui-bundle.js` (not the standalone preset — the standalone preset crashes with a `specActions` error before the spec loads).
+5
View File
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
+9
View File
@@ -0,0 +1,9 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
experimental: {
serverActions: { bodySizeLimit: "2mb" },
},
};
export default nextConfig;
+669
View File
@@ -0,0 +1,669 @@
{
"name": "florthoritania",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "florthoritania",
"version": "0.1.0",
"dependencies": {
"@prisma/client": "^5.22.0",
"bcryptjs": "^2.4.3",
"iron-session": "^8.0.4",
"next": "^14.2.35",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.17.6",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"prisma": "^5.22.0",
"typescript": "^5.6.3"
}
},
"node_modules/@next/env": {
"version": "14.2.35",
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.35.tgz",
"integrity": "sha512-DuhvCtj4t9Gwrx80dmz2F4t/zKQ4ktN8WrMwOuVzkJfBilwAwGr6v16M5eI8yCuZ63H9TTuEU09Iu2HqkzFPVQ==",
"license": "MIT"
},
"node_modules/@next/swc-darwin-arm64": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.33.tgz",
"integrity": "sha512-HqYnb6pxlsshoSTubdXKu15g3iivcbsMXg4bYpjL2iS/V6aQot+iyF4BUc2qA/J/n55YtvE4PHMKWBKGCF/+wA==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.33.tgz",
"integrity": "sha512-8HGBeAE5rX3jzKvF593XTTFg3gxeU4f+UWnswa6JPhzaR6+zblO5+fjltJWIZc4aUalqTclvN2QtTC37LxvZAA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.33.tgz",
"integrity": "sha512-JXMBka6lNNmqbkvcTtaX8Gu5by9547bukHQvPoLe9VRBx1gHwzf5tdt4AaezW85HAB3pikcvyqBToRTDA4DeLw==",
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.33.tgz",
"integrity": "sha512-Bm+QulsAItD/x6Ih8wGIMfRJy4G73tu1HJsrccPW6AfqdZd0Sfm5Imhgkgq2+kly065rYMnCOxTBvmvFY1BKfg==",
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.33.tgz",
"integrity": "sha512-FnFn+ZBgsVMbGDsTqo8zsnRzydvsGV8vfiWwUo1LD8FTmPTdV+otGSWKc4LJec0oSexFnCYVO4hX8P8qQKaSlg==",
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.33.tgz",
"integrity": "sha512-345tsIWMzoXaQndUTDv1qypDRiebFxGYx9pYkhwY4hBRaOLt8UGfiWKr9FSSHs25dFIf8ZqIFaPdy5MljdoawA==",
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.33.tgz",
"integrity": "sha512-nscpt0G6UCTkrT2ppnJnFsYbPDQwmum4GNXYTeoTIdsmMydSKFz9Iny2jpaRupTb+Wl298+Rh82WKzt9LCcqSQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-ia32-msvc": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.33.tgz",
"integrity": "sha512-pc9LpGNKhJ0dXQhZ5QMmYxtARwwmWLpeocFmVG5Z0DzWq5Uf0izcI8tLc+qOpqxO1PWqZ5A7J1blrUIKrIFc7Q==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "14.2.33",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.33.tgz",
"integrity": "sha512-nOjfZMy8B94MdisuzZo9/57xuFVLHJaDj5e/xrduJp9CV2/HrfxTRH2fbyLe+K9QT41WBLUd4iXX3R7jBp0EUg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@prisma/client": {
"version": "5.22.0",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-5.22.0.tgz",
"integrity": "sha512-M0SVXfyHnQREBKxCgyo7sffrKttwE6R8PMq330MIUF0pTwjUhLbW84pFDlf06B27XyCR++VtjugEnIHdr07SVA==",
"hasInstallScript": true,
"license": "Apache-2.0",
"engines": {
"node": ">=16.13"
},
"peerDependencies": {
"prisma": "*"
},
"peerDependenciesMeta": {
"prisma": {
"optional": true
}
}
},
"node_modules/@prisma/debug": {
"version": "5.22.0",
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-5.22.0.tgz",
"integrity": "sha512-AUt44v3YJeggO2ZU5BkXI7M4hu9BF2zzH2iF2V5pyXT/lRTyWiElZ7It+bRH1EshoMRxHgpYg4VB6rCM+mG5jQ==",
"devOptional": true,
"license": "Apache-2.0"
},
"node_modules/@prisma/engines": {
"version": "5.22.0",
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-5.22.0.tgz",
"integrity": "sha512-UNjfslWhAt06kVL3CjkuYpHAWSO6L4kDCVPegV6itt7nD1kSJavd3vhgAEhjglLJJKEdJ7oIqDJ+yHk6qO8gPA==",
"devOptional": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "5.22.0",
"@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2",
"@prisma/fetch-engine": "5.22.0",
"@prisma/get-platform": "5.22.0"
}
},
"node_modules/@prisma/engines-version": {
"version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2",
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2.tgz",
"integrity": "sha512-2PTmxFR2yHW/eB3uqWtcgRcgAbG1rwG9ZriSvQw+nnb7c4uCr3RAcGMb6/zfE88SKlC1Nj2ziUvc96Z379mHgQ==",
"devOptional": true,
"license": "Apache-2.0"
},
"node_modules/@prisma/fetch-engine": {
"version": "5.22.0",
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-5.22.0.tgz",
"integrity": "sha512-bkrD/Mc2fSvkQBV5EpoFcZ87AvOgDxbG99488a5cexp5Ccny+UM6MAe/UFkUC0wLYD9+9befNOqGiIJhhq+HbA==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "5.22.0",
"@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2",
"@prisma/get-platform": "5.22.0"
}
},
"node_modules/@prisma/get-platform": {
"version": "5.22.0",
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-5.22.0.tgz",
"integrity": "sha512-pHhpQdr1UPFpt+zFfnPazhulaZYCUqeIcPpJViYoq9R+D/yw4fjE+CtnsnKzPYm0ddUbeXUzjGVGIRVgPDCk4Q==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "5.22.0"
}
},
"node_modules/@swc/counter": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
"license": "Apache-2.0"
},
"node_modules/@swc/helpers": {
"version": "0.5.5",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.5.tgz",
"integrity": "sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==",
"license": "Apache-2.0",
"dependencies": {
"@swc/counter": "^0.1.3",
"tslib": "^2.4.0"
}
},
"node_modules/@types/bcryptjs": {
"version": "2.4.6",
"resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.19.39",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz",
"integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.28",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",
"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
}
},
"node_modules/bcryptjs": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
"integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==",
"license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/caniuse-lite": {
"version": "1.0.30001791",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001791.tgz",
"integrity": "sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/browserslist"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/caniuse-lite"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "CC-BY-4.0"
},
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
"license": "MIT"
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/iron-session": {
"version": "8.0.4",
"resolved": "https://registry.npmjs.org/iron-session/-/iron-session-8.0.4.tgz",
"integrity": "sha512-9ivNnaKOd08osD0lJ3i6If23GFS2LsxyMU8Gf/uBUEgm8/8CC1hrrCHFDpMo3IFbpBgwoo/eairRsaD3c5itxA==",
"funding": [
"https://github.com/sponsors/vvo",
"https://github.com/sponsors/brc-dd"
],
"license": "MIT",
"dependencies": {
"cookie": "^0.7.2",
"iron-webcrypto": "^1.2.1",
"uncrypto": "^0.1.3"
}
},
"node_modules/iron-webcrypto": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz",
"integrity": "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/brc-dd"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/next": {
"version": "14.2.35",
"resolved": "https://registry.npmjs.org/next/-/next-14.2.35.tgz",
"integrity": "sha512-KhYd2Hjt/O1/1aZVX3dCwGXM1QmOV4eNM2UTacK5gipDdPN/oHHK/4oVGy7X8GMfPMsUTUEmGlsy0EY1YGAkig==",
"license": "MIT",
"dependencies": {
"@next/env": "14.2.35",
"@swc/helpers": "0.5.5",
"busboy": "1.6.0",
"caniuse-lite": "^1.0.30001579",
"graceful-fs": "^4.2.11",
"postcss": "8.4.31",
"styled-jsx": "5.1.1"
},
"bin": {
"next": "dist/bin/next"
},
"engines": {
"node": ">=18.17.0"
},
"optionalDependencies": {
"@next/swc-darwin-arm64": "14.2.33",
"@next/swc-darwin-x64": "14.2.33",
"@next/swc-linux-arm64-gnu": "14.2.33",
"@next/swc-linux-arm64-musl": "14.2.33",
"@next/swc-linux-x64-gnu": "14.2.33",
"@next/swc-linux-x64-musl": "14.2.33",
"@next/swc-win32-arm64-msvc": "14.2.33",
"@next/swc-win32-ia32-msvc": "14.2.33",
"@next/swc-win32-x64-msvc": "14.2.33"
},
"peerDependencies": {
"@opentelemetry/api": "^1.1.0",
"@playwright/test": "^1.41.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sass": "^1.3.0"
},
"peerDependenciesMeta": {
"@opentelemetry/api": {
"optional": true
},
"@playwright/test": {
"optional": true
},
"sass": {
"optional": true
}
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/postcss": {
"version": "8.4.31",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
"integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.6",
"picocolors": "^1.0.0",
"source-map-js": "^1.0.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/prisma": {
"version": "5.22.0",
"resolved": "https://registry.npmjs.org/prisma/-/prisma-5.22.0.tgz",
"integrity": "sha512-vtpjW3XuYCSnMsNVBjLMNkTj6OZbudcPPTPYHqX0CJfpcdWciI1dM8uHETwmDxxiqEwCIE6WvXucWUetJgfu/A==",
"devOptional": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/engines": "5.22.0"
},
"bin": {
"prisma": "build/index.js"
},
"engines": {
"node": ">=16.13"
},
"optionalDependencies": {
"fsevents": "2.3.3"
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
},
"peerDependencies": {
"react": "^18.3.1"
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/styled-jsx": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.1.tgz",
"integrity": "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==",
"license": "MIT",
"dependencies": {
"client-only": "0.0.1"
},
"engines": {
"node": ">= 12.0.0"
},
"peerDependencies": {
"react": ">= 16.8.0 || 17.x.x || ^18.0.0-0"
},
"peerDependenciesMeta": {
"@babel/core": {
"optional": true
},
"babel-plugin-macros": {
"optional": true
}
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/uncrypto": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz",
"integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==",
"license": "MIT"
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}
+30
View File
@@ -0,0 +1,30 @@
{
"name": "florthoritania",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3000",
"build": "prisma generate && prisma migrate deploy && next build",
"start": "next start -p 3000",
"lint": "next lint",
"db:push": "prisma db push",
"db:migrate": "prisma migrate dev",
"db:studio": "prisma studio"
},
"dependencies": {
"@prisma/client": "^5.22.0",
"bcryptjs": "^2.4.3",
"iron-session": "^8.0.4",
"next": "^14.2.35",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.17.6",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"prisma": "^5.22.0",
"typescript": "^5.6.3"
}
}
@@ -0,0 +1,136 @@
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL PRIMARY KEY,
"username" TEXT NOT NULL,
"passwordHash" TEXT NOT NULL,
"role" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateTable
CREATE TABLE "World" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT DEFAULT 1,
"name" TEXT NOT NULL DEFAULT 'My World',
"tagline" TEXT NOT NULL DEFAULT '',
"era" TEXT NOT NULL DEFAULT '',
"theme" TEXT NOT NULL DEFAULT 'midnight',
"accent" TEXT NOT NULL DEFAULT '#d9b46a',
"showFog" BOOLEAN NOT NULL DEFAULT true,
"updatedAt" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "Entry" (
"id" TEXT NOT NULL PRIMARY KEY,
"slug" TEXT NOT NULL,
"kind" TEXT NOT NULL,
"title" TEXT NOT NULL,
"subtitle" TEXT NOT NULL DEFAULT '',
"summary" TEXT NOT NULL DEFAULT '',
"body" TEXT NOT NULL DEFAULT '',
"fields" TEXT NOT NULL DEFAULT '{}',
"tags" TEXT NOT NULL DEFAULT '[]',
"isPublic" BOOLEAN NOT NULL DEFAULT false,
"stats" TEXT NOT NULL DEFAULT '{}',
"abilities" TEXT NOT NULL DEFAULT '[]',
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "Link" (
"id" TEXT NOT NULL PRIMARY KEY,
"fromId" TEXT NOT NULL,
"toId" TEXT NOT NULL,
CONSTRAINT "Link_fromId_fkey" FOREIGN KEY ("fromId") REFERENCES "Entry" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "Link_toId_fkey" FOREIGN KEY ("toId") REFERENCES "Entry" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "TimelineEvent" (
"id" TEXT NOT NULL PRIMARY KEY,
"year" INTEGER NOT NULL,
"era" TEXT NOT NULL DEFAULT '',
"label" TEXT NOT NULL,
"text" TEXT NOT NULL DEFAULT '',
"kind" TEXT NOT NULL DEFAULT 'lore',
"entryId" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TimelineEvent_entryId_fkey" FOREIGN KEY ("entryId") REFERENCES "Entry" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "MapPin" (
"id" TEXT NOT NULL PRIMARY KEY,
"x" REAL NOT NULL,
"y" REAL NOT NULL,
"label" TEXT NOT NULL,
"kind" TEXT NOT NULL DEFAULT 'location',
"entryId" TEXT,
CONSTRAINT "MapPin_entryId_fkey" FOREIGN KEY ("entryId") REFERENCES "Entry" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "Quest" (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT NOT NULL,
"meta" TEXT NOT NULL DEFAULT '',
"priority" TEXT NOT NULL DEFAULT 'normal',
"status" TEXT NOT NULL DEFAULT 'active',
"isPublic" BOOLEAN NOT NULL DEFAULT true,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateTable
CREATE TABLE "PartyMember" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"klass" TEXT NOT NULL DEFAULT '',
"hpCur" INTEGER NOT NULL DEFAULT 0,
"hpMax" INTEGER NOT NULL DEFAULT 0,
"color" TEXT NOT NULL DEFAULT '#d9b46a',
"order" INTEGER NOT NULL DEFAULT 0
);
-- CreateTable
CREATE TABLE "JournalEntry" (
"id" TEXT NOT NULL PRIMARY KEY,
"who" TEXT NOT NULL,
"color" TEXT NOT NULL DEFAULT '#d9b46a',
"text" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateTable
CREATE TABLE "SessionBeat" (
"id" TEXT NOT NULL PRIMARY KEY,
"entryId" TEXT NOT NULL,
"time" TEXT NOT NULL DEFAULT '',
"title" TEXT NOT NULL,
"text" TEXT NOT NULL DEFAULT '',
"flag" TEXT NOT NULL DEFAULT '',
"order" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "SessionBeat_entryId_fkey" FOREIGN KEY ("entryId") REFERENCES "Entry" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "Thread" (
"id" TEXT NOT NULL PRIMARY KEY,
"text" TEXT NOT NULL,
"who" TEXT NOT NULL DEFAULT '',
"primary" BOOLEAN NOT NULL DEFAULT false,
"resolved" BOOLEAN NOT NULL DEFAULT false,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
-- CreateIndex
CREATE UNIQUE INDEX "Entry_slug_key" ON "Entry"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "Link_fromId_toId_key" ON "Link"("fromId", "toId");
-- CreateIndex
CREATE UNIQUE INDEX "MapPin_entryId_key" ON "MapPin"("entryId");
@@ -0,0 +1,32 @@
-- CreateTable
CREATE TABLE "MapLayer" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"imageData" TEXT NOT NULL DEFAULT '',
"width" INTEGER NOT NULL DEFAULT 1000,
"height" INTEGER NOT NULL DEFAULT 700,
"isDefault" BOOLEAN NOT NULL DEFAULT false,
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_MapPin" (
"id" TEXT NOT NULL PRIMARY KEY,
"x" REAL NOT NULL,
"y" REAL NOT NULL,
"label" TEXT NOT NULL,
"kind" TEXT NOT NULL DEFAULT 'location',
"entryId" TEXT,
"layerId" TEXT,
CONSTRAINT "MapPin_entryId_fkey" FOREIGN KEY ("entryId") REFERENCES "Entry" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "MapPin_layerId_fkey" FOREIGN KEY ("layerId") REFERENCES "MapLayer" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
INSERT INTO "new_MapPin" ("entryId", "id", "kind", "label", "x", "y") SELECT "entryId", "id", "kind", "label", "x", "y" FROM "MapPin";
DROP TABLE "MapPin";
ALTER TABLE "new_MapPin" RENAME TO "MapPin";
CREATE UNIQUE INDEX "MapPin_entryId_key" ON "MapPin"("entryId");
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
@@ -0,0 +1,46 @@
-- CreateTable
CREATE TABLE "Campaign" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- CreateTable
CREATE TABLE "CampaignMember" (
"id" TEXT NOT NULL PRIMARY KEY,
"userId" TEXT NOT NULL,
"campaignId" TEXT NOT NULL,
CONSTRAINT "CampaignMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "CampaignMember_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "Campaign" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "EntryReveal" (
"id" TEXT NOT NULL PRIMARY KEY,
"entryId" TEXT NOT NULL,
"campaignId" TEXT NOT NULL,
CONSTRAINT "EntryReveal_entryId_fkey" FOREIGN KEY ("entryId") REFERENCES "Entry" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "EntryReveal_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "Campaign" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "InviteCode" (
"id" TEXT NOT NULL PRIMARY KEY,
"code" TEXT NOT NULL,
"campaignId" TEXT,
"role" TEXT NOT NULL DEFAULT 'player',
"usedById" TEXT,
"expiresAt" DATETIME,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "InviteCode_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "Campaign" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "InviteCode_usedById_fkey" FOREIGN KEY ("usedById") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "CampaignMember_userId_campaignId_key" ON "CampaignMember"("userId", "campaignId");
-- CreateIndex
CREATE UNIQUE INDEX "EntryReveal_entryId_campaignId_key" ON "EntryReveal"("entryId", "campaignId");
-- CreateIndex
CREATE UNIQUE INDEX "InviteCode_code_key" ON "InviteCode"("code");
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"
+185
View File
@@ -0,0 +1,185 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
username String @unique
passwordHash String
role String // "dm" | "player"
createdAt DateTime @default(now())
campaigns CampaignMember[]
usedInvites InviteCode[] @relation("UsedInvites")
}
model World {
id Int @id @default(1)
name String @default("My World")
tagline String @default("")
era String @default("")
theme String @default("midnight")
accent String @default("#d9b46a")
showFog Boolean @default(true)
updatedAt DateTime @updatedAt
}
model Entry {
id String @id @default(cuid())
slug String @unique
kind String // location | npc | pc | faction | item | lore | session | beast | deity | rule | quest | culture
title String
subtitle String @default("")
summary String @default("")
body String @default("") // markdown-like, supports [[wikilinks]] and ::secret blocks
fields String @default("{}") // JSON object {key:value}
tags String @default("[]") // JSON array
isPublic Boolean @default(false)
// Bestiary-specific (JSON-encoded)
stats String @default("{}") // JSON object
abilities String @default("[]") // JSON array of {name,text}
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
outgoing Link[] @relation("from")
incoming Link[] @relation("to")
pin MapPin?
beats SessionBeat[]
timelineEvents TimelineEvent[]
reveals EntryReveal[]
}
model Link {
id String @id @default(cuid())
fromId String
toId String
from Entry @relation("from", fields: [fromId], references: [id], onDelete: Cascade)
to Entry @relation("to", fields: [toId], references: [id], onDelete: Cascade)
@@unique([fromId, toId])
}
model TimelineEvent {
id String @id @default(cuid())
year Int
era String @default("") // "Pre-Concord" / "Concord" etc.
label String
text String @default("")
kind String @default("lore")
entryId String?
entry Entry? @relation(fields: [entryId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
}
model MapPin {
id String @id @default(cuid())
x Float
y Float
label String
kind String @default("location")
entryId String? @unique
entry Entry? @relation(fields: [entryId], references: [id], onDelete: SetNull)
layerId String?
layer MapLayer? @relation(fields: [layerId], references: [id], onDelete: SetNull)
}
model MapLayer {
id String @id @default(cuid())
name String
imageData String @default("") // data: URL of an uploaded background, or "" for the procedural canvas
width Int @default(1000)
height Int @default(700)
isDefault Boolean @default(false)
order Int @default(0)
createdAt DateTime @default(now())
pins MapPin[]
}
model Quest {
id String @id @default(cuid())
title String
meta String @default("")
priority String @default("normal") // critical | normal
status String @default("active") // active | completed
isPublic Boolean @default(true)
createdAt DateTime @default(now())
}
model PartyMember {
id String @id @default(cuid())
name String
klass String @default("")
hpCur Int @default(0)
hpMax Int @default(0)
color String @default("#d9b46a")
order Int @default(0)
}
model JournalEntry {
id String @id @default(cuid())
who String
color String @default("#d9b46a")
text String
createdAt DateTime @default(now())
}
model SessionBeat {
id String @id @default(cuid())
entryId String
entry Entry @relation(fields: [entryId], references: [id], onDelete: Cascade)
time String @default("")
title String
text String @default("")
flag String @default("") // "" | rp | key | fight
order Int @default(0)
}
model Thread {
id String @id @default(cuid())
text String
who String @default("")
primary Boolean @default(false)
resolved Boolean @default(false)
createdAt DateTime @default(now())
}
model Campaign {
id String @id @default(cuid())
name String
createdAt DateTime @default(now())
members CampaignMember[]
reveals EntryReveal[]
invites InviteCode[]
}
model CampaignMember {
id String @id @default(cuid())
userId String
campaignId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
@@unique([userId, campaignId])
}
model EntryReveal {
id String @id @default(cuid())
entryId String
campaignId String
entry Entry @relation(fields: [entryId], references: [id], onDelete: Cascade)
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
@@unique([entryId, campaignId])
}
model InviteCode {
id String @id @default(cuid())
code String @unique @default(cuid())
campaignId String?
role String @default("player")
usedById String?
expiresAt DateTime?
createdAt DateTime @default(now())
campaign Campaign? @relation(fields: [campaignId], references: [id], onDelete: SetNull)
usedBy User? @relation("UsedInvites", fields: [usedById], references: [id], onDelete: SetNull)
}
+107
View File
@@ -0,0 +1,107 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
type Spec = {
info: { title: string; version: string; description?: string };
paths: Record<string, Record<string, { tags?: string[]; summary?: string }>>;
};
export default function ApiInfoPage() {
const [spec, setSpec] = useState<Spec | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetch("/api/openapi.json")
.then((r) => r.json())
.then(setSpec)
.catch((e) => setError(String(e)));
}, []);
if (error)
return <div className="flo-settings-section"><div className="flo-error">{error}</div></div>;
if (!spec) return <div className="flo-settings-section">Loading…</div>;
const grouped: Record<string, { method: string; path: string; summary?: string }[]> = {};
for (const [path, methods] of Object.entries(spec.paths)) {
for (const [method, op] of Object.entries(methods)) {
const tag = op.tags?.[0] ?? "other";
grouped[tag] ||= [];
grouped[tag].push({ method: method.toUpperCase(), path, summary: op.summary });
}
}
return (
<>
<div className="flo-settings-section">
<h2>{spec.info.title}</h2>
{spec.info.description && (
<p className="flo-mono flo-mono-dim">{spec.info.description}</p>
)}
<div className="flo-row" style={{ marginTop: 12 }}>
<Link href="/api-docs" className="flo-btn">Open Swagger UI →</Link>
<a className="flo-btn flo-btn-ghost" href="/api/openapi.json" target="_blank" rel="noreferrer">
Download openapi.json
</a>
<span className="flo-mono flo-mono-dim">v{spec.info.version}</span>
</div>
</div>
{Object.entries(grouped)
.sort(([a], [b]) => a.localeCompare(b))
.map(([tag, ops]) => (
<div key={tag} className="flo-settings-section">
<h2>{tag}</h2>
<ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
{ops.map((o, i) => (
<li
key={i}
style={{
display: "grid",
gridTemplateColumns: "70px 1fr",
gap: 12,
padding: "6px 0",
borderBottom: "1px solid var(--line)",
}}
>
<span
className="flo-mono"
style={{
padding: "2px 6px",
fontSize: 10,
borderRadius: 4,
background: methodBg(o.method),
color: "#1a1430",
fontWeight: 500,
textAlign: "center",
alignSelf: "start",
}}
>
{o.method}
</span>
<div>
<code className="flo-mono">{o.path}</code>
{o.summary && (
<div className="flo-mono flo-mono-dim" style={{ marginTop: 2 }}>
{o.summary}
</div>
)}
</div>
</li>
))}
</ul>
</div>
))}
</>
);
}
function methodBg(m: string) {
switch (m) {
case "GET": return "#9ad6b8";
case "POST": return "#d9b46a";
case "PATCH": return "#e09a6b";
case "DELETE": return "#d68a8a";
default: return "#b9b3d6";
}
}
+318
View File
@@ -0,0 +1,318 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { AdminTabs } from "@/components/AdminTabs";
import { useFlorte } from "@/components/ClientProviders";
type User = { id: string; username: string; role: string };
type CampaignMember = { id: string; userId: string; user: User };
type Campaign = {
id: string;
name: string;
createdAt: string;
members: CampaignMember[];
_count: { reveals: number };
};
type Invite = {
id: string;
code: string;
role: string;
campaignId: string | null;
campaign: { id: string; name: string } | null;
usedBy: { id: string; username: string } | null;
expiresAt: string | null;
createdAt: string;
};
export default function CampaignsPage() {
const { t } = useFlorte();
const router = useRouter();
const [campaigns, setCampaigns] = useState<Campaign[]>([]);
const [invites, setInvites] = useState<Invite[]>([]);
const [users, setUsers] = useState<User[]>([]);
const [newName, setNewName] = useState("");
const [creating, setCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [copiedId, setCopiedId] = useState<string | null>(null);
const [inviteForm, setInviteForm] = useState<{
campaignId: string;
role: string;
expiresAt: string;
}>({ campaignId: "", role: "player", expiresAt: "" });
const load = async () => {
const [c, i, u] = await Promise.all([
fetch("/api/campaigns").then((r) => r.json()),
fetch("/api/invites").then((r) => r.json()),
fetch("/api/users").then((r) => r.json()),
]);
setCampaigns(Array.isArray(c) ? c : []);
setInvites(Array.isArray(i) ? i : []);
setUsers(Array.isArray(u) ? u : []);
};
useEffect(() => { load(); }, []);
const createCampaign = async (e: React.FormEvent) => {
e.preventDefault();
if (!newName.trim()) return;
setCreating(true);
setError(null);
const res = await fetch("/api/campaigns", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newName.trim() }),
});
setCreating(false);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
setError(j.error ?? "Failed");
return;
}
setNewName("");
load();
};
const deleteCampaign = async (id: string) => {
if (!confirm("Delete this campaign? All reveals will be removed.")) return;
await fetch(`/api/campaigns/${id}`, { method: "DELETE" });
load();
};
const addMember = async (campaignId: string, userId: string) => {
await fetch(`/api/campaigns/${campaignId}/members`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId }),
});
load();
};
const removeMember = async (campaignId: string, userId: string) => {
await fetch(`/api/campaigns/${campaignId}/members`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId }),
});
load();
};
const createInvite = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch("/api/invites", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
campaignId: inviteForm.campaignId || null,
role: inviteForm.role,
expiresAt: inviteForm.expiresAt || null,
}),
});
if (res.ok) load();
};
const revokeInvite = async (id: string) => {
await fetch(`/api/invites/${id}`, { method: "DELETE" });
load();
};
const copyInviteLink = (code: string, id: string) => {
const url = `${window.location.origin}/register?code=${code}`;
navigator.clipboard.writeText(url);
setCopiedId(id);
setTimeout(() => setCopiedId(null), 2000);
};
return (
<div>
<AdminTabs />
<h1 style={{ fontFamily: "Cormorant Garamond, serif", fontWeight: 400, fontSize: 32, marginBottom: 24 }}>
{t("campaign_title")}
</h1>
{error && <div className="flo-error">{error}</div>}
{/* Create campaign */}
<div className="flo-settings-section">
<h2>{t("campaign_create")}</h2>
<form onSubmit={createCampaign} style={{ display: "flex", gap: 8 }}>
<input
className="flo-input"
style={{ flex: 1 }}
placeholder={t("campaign_name")}
value={newName}
onChange={(e) => setNewName(e.target.value)}
required
/>
<button className="flo-btn" type="submit" disabled={creating}>
{creating ? t("action_creating") : t("action_create")}
</button>
</form>
</div>
{/* Campaign list */}
{campaigns.length === 0 ? (
<div className="flo-empty-card">{t("campaign_no_campaigns")}</div>
) : (
campaigns.map((c) => {
const memberUserIds = new Set(c.members.map((m) => m.userId));
const nonMembers = users.filter((u) => !memberUserIds.has(u.id));
return (
<div key={c.id} className="flo-settings-section" style={{ marginBottom: 16 }}>
<div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
<h2 style={{ margin: 0, flex: 1 }}>{c.name}</h2>
<span style={{ fontSize: 12, color: "var(--ink-3)", fontFamily: "JetBrains Mono, monospace" }}>
{c._count.reveals} reveals
</span>
<button
className="flo-btn flo-btn-danger"
style={{ fontSize: 12 }}
onClick={() => deleteCampaign(c.id)}
>
{t("action_delete")}
</button>
</div>
<div style={{ marginBottom: 10 }}>
<div style={{ fontSize: 11, fontFamily: "JetBrains Mono, monospace", letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)", marginBottom: 6 }}>
{t("campaign_members")}
</div>
{c.members.length === 0 ? (
<div style={{ fontSize: 13, color: "var(--ink-3)", fontStyle: "italic" }}>{t("empty_no_members")}</div>
) : (
<div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
{c.members.map((m) => (
<span key={m.id} className="flo-chip" style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>
{m.user.username}
<button
style={{ background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", fontSize: 12, padding: 0 }}
onClick={() => removeMember(c.id, m.userId)}
title={t("action_remove")}
>
✕
</button>
</span>
))}
</div>
)}
{nonMembers.length > 0 && (
<div style={{ marginTop: 8 }}>
<select
className="flo-select"
onChange={(e) => { if (e.target.value) { addMember(c.id, e.target.value); e.target.value = ""; } }}
defaultValue=""
>
<option value="" disabled>{t("action_add")} member…</option>
{nonMembers.map((u) => (
<option key={u.id} value={u.id}>{u.username} ({u.role})</option>
))}
</select>
</div>
)}
</div>
</div>
);
})
)}
{/* Invite codes */}
<div className="flo-settings-section" style={{ marginTop: 24 }}>
<h2>{t("invite_create")}</h2>
<form onSubmit={createInvite} style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "flex-end" }}>
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<label style={{ fontSize: 10, fontFamily: "JetBrains Mono, monospace", letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>
Campaign
</label>
<select
className="flo-select"
value={inviteForm.campaignId}
onChange={(e) => setInviteForm((f) => ({ ...f, campaignId: e.target.value }))}
>
<option value="">No campaign</option>
{campaigns.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<label style={{ fontSize: 10, fontFamily: "JetBrains Mono, monospace", letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>
{t("admin_users_role")}
</label>
<select
className="flo-select"
value={inviteForm.role}
onChange={(e) => setInviteForm((f) => ({ ...f, role: e.target.value }))}
>
<option value="player">{t("admin_users_player")}</option>
<option value="dm">{t("admin_users_dm")}</option>
</select>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
<label style={{ fontSize: 10, fontFamily: "JetBrains Mono, monospace", letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>
{t("invite_expires")}
</label>
<input
type="datetime-local"
className="flo-input"
value={inviteForm.expiresAt}
onChange={(e) => setInviteForm((f) => ({ ...f, expiresAt: e.target.value }))}
/>
</div>
<button className="flo-btn" type="submit">
{t("invite_create")}
</button>
</form>
{invites.length > 0 && (
<table style={{ width: "100%", borderCollapse: "collapse", marginTop: 18, fontSize: 13 }}>
<thead>
<tr style={{ borderBottom: "1px solid var(--line)" }}>
<th style={{ textAlign: "left", padding: "6px 8px", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>{t("invite_code")}</th>
<th style={{ textAlign: "left", padding: "6px 8px", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>Campaign</th>
<th style={{ textAlign: "left", padding: "6px 8px", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>{t("admin_users_role")}</th>
<th style={{ textAlign: "left", padding: "6px 8px", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>{t("invite_used_by")}</th>
<th />
</tr>
</thead>
<tbody>
{invites.map((inv) => (
<tr key={inv.id} style={{ borderBottom: "1px solid var(--line-2)" }}>
<td style={{ padding: "6px 8px", fontFamily: "JetBrains Mono, monospace", fontSize: 11 }}>
{inv.code.slice(0, 8)}…
</td>
<td style={{ padding: "6px 8px", color: "var(--ink-3)" }}>
{inv.campaign?.name ?? "—"}
</td>
<td style={{ padding: "6px 8px" }}>{inv.role}</td>
<td style={{ padding: "6px 8px", color: inv.usedBy ? "var(--teal)" : "var(--ink-3)" }}>
{inv.usedBy?.username ?? t("invite_unused")}
</td>
<td style={{ padding: "6px 8px", display: "flex", gap: 6 }}>
{!inv.usedBy && (
<>
<button
className="flo-btn flo-btn-ghost"
style={{ fontSize: 11, padding: "3px 8px" }}
onClick={() => copyInviteLink(inv.code, inv.id)}
>
{copiedId === inv.id ? t("action_copied") : t("invite_copy")}
</button>
<button
className="flo-btn flo-btn-danger"
style={{ fontSize: 11, padding: "3px 8px" }}
onClick={() => revokeInvite(inv.id)}
>
{t("invite_revoke")}
</button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}
+453
View File
@@ -0,0 +1,453 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { api } from "@/lib/client";
import { KIND_ORDER, KINDS, type KindId } from "@/lib/kinds";
type Source = "donjon" | "azgaar" | "fantasytown";
type PlanEntry = {
kind: string; title: string; subtitle?: string; summary?: string;
body?: string; isPublic?: boolean; tags?: string[];
};
type Plan = {
source: Source;
entries: PlanEntry[];
pins?: { x: number; y: number; label: string; kind?: string }[];
layerName?: string;
warnings?: string[];
};
type Result = {
entriesCreated: number;
pinsCreated: number;
created: { slug: string; title: string; kind: string }[];
};
export default function ImportPage() {
const [tab, setTab] = useState<Source>("azgaar");
return (
<>
<div className="flo-kind-tabs" style={{ marginBottom: 14 }}>
{(["donjon", "azgaar", "fantasytown"] as Source[]).map((s) => (
<button
key={s}
className={"flo-kind-tab" + (tab === s ? " is-active" : "")}
onClick={() => setTab(s)}
>
{labels[s]}
</button>
))}
</div>
{tab === "donjon" && <DonjonTab />}
{tab === "azgaar" && <AzgaarTab />}
{tab === "fantasytown" && <FantasyTownTab />}
</>
);
}
const labels: Record<Source, string> = {
donjon: "Donjon (paste text/JSON)",
azgaar: "Azgaar Fantasy Map (.json)",
fantasytown: "Fantasy Town Generator (.json)",
};
function PlanPreview({ plan, onApply, applying, result }: {
plan: Plan | null;
onApply: () => void;
applying: boolean;
result: Result | null;
}) {
if (!plan && !result) return null;
return (
<div className="flo-settings-section" style={{ marginTop: 14 }}>
<h2>Preview</h2>
{plan?.warnings && plan.warnings.length > 0 && (
<div className="flo-error" style={{ marginBottom: 12 }}>
{plan.warnings.join(" · ")}
</div>
)}
{plan && (
<>
<p className="flo-mono flo-mono-dim">
{plan.entries.length} entries · {plan.pins?.length ?? 0} pins
</p>
{plan.entries.length > 0 && (
<ul style={{ listStyle: "none", padding: 0, margin: "0 0 14px", display: "flex", flexDirection: "column", gap: 4, maxHeight: 320, overflow: "auto" }}>
{plan.entries.slice(0, 100).map((e, i) => (
<li
key={i}
style={{
display: "grid",
gridTemplateColumns: "120px 1fr",
gap: 12,
padding: "6px 0",
borderBottom: "1px solid var(--line)",
}}
>
<span className="flo-mono flo-mono-dim">
{KINDS[e.kind as KindId]?.glyph ?? "•"} {e.kind}
</span>
<div>
<div style={{ fontFamily: "Cormorant Garamond, serif", fontSize: 16 }}>
{e.title}
</div>
{e.summary && (
<div className="flo-mono flo-mono-dim" style={{ marginTop: 2 }}>
{e.summary.slice(0, 160)}
</div>
)}
</div>
</li>
))}
{plan.entries.length > 100 && (
<li className="flo-mono flo-mono-dim">…and {plan.entries.length - 100} more</li>
)}
</ul>
)}
{!result && (
<button className="flo-btn" onClick={onApply} disabled={applying || plan.entries.length === 0}>
{applying ? "Importing…" : `Import ${plan.entries.length} entries`}
</button>
)}
</>
)}
{result && (
<div className="flo-success" style={{ marginTop: 8 }}>
Imported {result.entriesCreated} entries and {result.pinsCreated} pins.{" "}
<Link className="flo-link" href="/search">Browse the codex →</Link>
</div>
)}
</div>
);
}
// ── Donjon tab ───────────────────────────────────────────────────────────────
function DonjonTab() {
const [input, setInput] = useState("");
const [kind, setKind] = useState<KindId>("lore");
const [title, setTitle] = useState("");
const [isPublic, setIsPublic] = useState(false);
const [plan, setPlan] = useState<Plan | null>(null);
const [result, setResult] = useState<Result | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const preview = async () => {
setError(null);
setResult(null);
setBusy(true);
try {
const r = await api<{ plan: Plan }>("/api/import/donjon", {
method: "POST",
body: JSON.stringify({ input, kind, title, isPublic }),
});
setPlan(r.plan);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const apply = async () => {
setBusy(true);
setError(null);
try {
const r = await api<{ plan: Plan; result: Result }>("/api/import/donjon?action=apply", {
method: "POST",
body: JSON.stringify({ input, kind, title, isPublic }),
});
setPlan(r.plan);
setResult(r.result);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
return (
<>
<div className="flo-settings-section">
<h2>Donjon import</h2>
<p className="flo-mono flo-mono-dim" style={{ marginBottom: 12 }}>
Paste raw text from a donjon.bin.sh generator (NPC, town, dungeon…)
to create one entry. Or paste JSON like <code>{"{ \"entries\": [...] }"}</code>{" "}
to batch-create multiple.
</p>
{error && <div className="flo-error">{error}</div>}
<div className="flo-form-row">
<label>Default kind</label>
<select className="flo-select" value={kind} onChange={(e) => setKind(e.target.value as KindId)}>
{KIND_ORDER.map((k) => (
<option key={k} value={k}>{KINDS[k].label}</option>
))}
</select>
</div>
<div className="flo-form-row">
<label>Title (optional)</label>
<input
className="flo-input"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Used when the input is plain text"
/>
</div>
<div className="flo-form-row">
<label>Visibility</label>
<label className="flo-pill-toggle">
<input
type="checkbox"
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
/>
mark created entries as public
</label>
</div>
<div className="flo-form-row">
<label>Input</label>
<textarea
className="flo-textarea"
style={{ minHeight: 220, fontFamily: "JetBrains Mono, monospace", fontSize: 12 }}
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder={`Paste text from donjon, e.g. an NPC block, or:\n\n{\n "entries": [\n {\n "kind": "npc",\n "title": "Mira the Calm",\n "summary": "Half-orc bartender",\n "fields": { "Race": "half-orc" }\n }\n ]\n}`}
/>
</div>
<div className="flo-row" style={{ marginTop: 12 }}>
<button className="flo-btn flo-btn-ghost" onClick={preview} disabled={busy || !input.trim()}>
Preview
</button>
</div>
</div>
<PlanPreview plan={plan} onApply={apply} applying={busy} result={result} />
</>
);
}
// ── Azgaar tab ───────────────────────────────────────────────────────────────
function AzgaarTab() {
const [input, setInput] = useState("");
const [isPublic, setIsPublic] = useState(false);
const [createLayer, setCreateLayer] = useState(true);
const [layerName, setLayerName] = useState("Azgaar import");
const [plan, setPlan] = useState<Plan | null>(null);
const [result, setResult] = useState<Result | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const onFile = (f: File | undefined) => {
if (!f) return;
const reader = new FileReader();
reader.onload = () => setInput(String(reader.result || ""));
reader.readAsText(f);
};
const preview = async () => {
setError(null);
setResult(null);
setBusy(true);
try {
const r = await api<{ plan: Plan }>("/api/import/azgaar", {
method: "POST",
body: JSON.stringify({ input, isPublic }),
});
setPlan(r.plan);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const apply = async () => {
setBusy(true);
setError(null);
try {
const r = await api<{ plan: Plan; result: Result }>("/api/import/azgaar?action=apply", {
method: "POST",
body: JSON.stringify({
input, isPublic, createLayer,
layerName: layerName || (plan?.layerName ?? "Azgaar import"),
}),
});
setPlan(r.plan);
setResult(r.result);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
return (
<>
<div className="flo-settings-section">
<h2>Azgaar Fantasy Map Generator</h2>
<p className="flo-mono flo-mono-dim" style={{ marginBottom: 12 }}>
Export your map from Azgaar with “Save as JSON”. We extract states (factions),
provinces and burgs (locations + map pins), religions (deities), cultures,
and any markers with notes.
</p>
{error && <div className="flo-error">{error}</div>}
<div className="flo-form-row">
<label>JSON file</label>
<input
className="flo-input"
type="file"
accept="application/json,.json,.map"
onChange={(e) => onFile(e.target.files?.[0])}
/>
</div>
<div className="flo-form-row">
<label>or paste</label>
<textarea
className="flo-textarea"
style={{ minHeight: 180, fontFamily: "JetBrains Mono, monospace", fontSize: 11 }}
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder='{"info":{"width":1000,...},"pack":{"states":[...],"burgs":[...]}}'
/>
</div>
<div className="flo-form-row">
<label>Visibility</label>
<label className="flo-pill-toggle">
<input
type="checkbox"
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
/>
mark imported entries as public
</label>
</div>
<div className="flo-form-row">
<label>Map layer</label>
<div className="flo-row">
<label className="flo-pill-toggle">
<input
type="checkbox"
checked={createLayer}
onChange={(e) => setCreateLayer(e.target.checked)}
/>
create a new map layer for the imported pins
</label>
<input
className="flo-input"
value={layerName}
onChange={(e) => setLayerName(e.target.value)}
placeholder="Layer name"
disabled={!createLayer}
style={{ width: 220 }}
/>
</div>
</div>
<div className="flo-row" style={{ marginTop: 12 }}>
<button className="flo-btn flo-btn-ghost" onClick={preview} disabled={busy || !input.trim()}>
Preview
</button>
</div>
</div>
<PlanPreview plan={plan} onApply={apply} applying={busy} result={result} />
</>
);
}
// ── Fantasy Town tab ─────────────────────────────────────────────────────────
function FantasyTownTab() {
const [input, setInput] = useState("");
const [isPublic, setIsPublic] = useState(false);
const [plan, setPlan] = useState<Plan | null>(null);
const [result, setResult] = useState<Result | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const onFile = (f: File | undefined) => {
if (!f) return;
const reader = new FileReader();
reader.onload = () => setInput(String(reader.result || ""));
reader.readAsText(f);
};
const preview = async () => {
setError(null);
setResult(null);
setBusy(true);
try {
const r = await api<{ plan: Plan }>("/api/import/fantasytown", {
method: "POST",
body: JSON.stringify({ input, isPublic }),
});
setPlan(r.plan);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const apply = async () => {
setBusy(true);
setError(null);
try {
const r = await api<{ plan: Plan; result: Result }>("/api/import/fantasytown?action=apply", {
method: "POST",
body: JSON.stringify({ input, isPublic }),
});
setPlan(r.plan);
setResult(r.result);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
return (
<>
<div className="flo-settings-section">
<h2>Fantasy Town Generator</h2>
<p className="flo-mono flo-mono-dim" style={{ marginBottom: 12 }}>
From fantasytowngenerator.com, click “Save Town”. We import the town
as a Location and each NPC as a Character, with the town’s buildings
listed in the Location’s body.
</p>
{error && <div className="flo-error">{error}</div>}
<div className="flo-form-row">
<label>JSON file</label>
<input
className="flo-input"
type="file"
accept="application/json,.json"
onChange={(e) => onFile(e.target.files?.[0])}
/>
</div>
<div className="flo-form-row">
<label>or paste</label>
<textarea
className="flo-textarea"
style={{ minHeight: 180, fontFamily: "JetBrains Mono, monospace", fontSize: 11 }}
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder='{"name":"…","population":…,"npcs":[…],"buildings":[…]}'
/>
</div>
<div className="flo-form-row">
<label>Visibility</label>
<label className="flo-pill-toggle">
<input
type="checkbox"
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
/>
mark created entries as public
</label>
</div>
<div className="flo-row" style={{ marginTop: 12 }}>
<button className="flo-btn flo-btn-ghost" onClick={preview} disabled={busy || !input.trim()}>
Preview
</button>
</div>
</div>
<PlanPreview plan={plan} onApply={apply} applying={busy} result={result} />
</>
);
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { RequireRole } from "@/components/RequireRole";
import { AdminTabs } from "@/components/AdminTabs";
export default function AdminLayout({ children }: { children: React.ReactNode }) {
return (
<RequireRole role="dm">
<div className="flo-screen">
<AdminTabs />
{children}
</div>
</RequireRole>
);
}
+206
View File
@@ -0,0 +1,206 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { api } from "@/lib/client";
type Layer = {
id: string;
name: string;
width: number;
height: number;
isDefault: boolean;
order: number;
};
export default function MapsPage() {
const [rows, setRows] = useState<Layer[]>([]);
const [draft, setDraft] = useState({ name: "", width: 1000, height: 700 });
const [draftImage, setDraftImage] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const reload = async () => setRows(await api<Layer[]>("/api/layers"));
useEffect(() => {
reload().catch(() => {});
}, []);
const onFile = (f: File | undefined) => {
if (!f) return;
if (f.size > 4_500_000) {
setError("File too large (max ~4.5MB)");
return;
}
const reader = new FileReader();
reader.onload = () => {
const data = String(reader.result || "");
setDraftImage(data);
const img = new Image();
img.onload = () => setDraft((d) => ({ ...d, width: img.naturalWidth, height: img.naturalHeight }));
img.src = data;
};
reader.readAsDataURL(f);
};
const create = async () => {
setError(null);
setBusy(true);
try {
await api("/api/layers", {
method: "POST",
body: JSON.stringify({
name: draft.name.trim() || "Untitled layer",
imageData: draftImage,
width: draft.width,
height: draft.height,
isDefault: rows.length === 0,
}),
});
setDraft({ name: "", width: 1000, height: 700 });
setDraftImage("");
if (fileRef.current) fileRef.current.value = "";
await reload();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const setDefault = async (l: Layer) => {
await api(`/api/layers/${l.id}`, {
method: "PATCH",
body: JSON.stringify({ isDefault: true }),
});
await reload();
};
const rename = async (l: Layer, name: string) => {
await api(`/api/layers/${l.id}`, {
method: "PATCH",
body: JSON.stringify({ name }),
});
await reload();
};
const remove = async (l: Layer) => {
if (!confirm(`Remove layer "${l.name}"? Pins on it become unassigned.`)) return;
await api(`/api/layers/${l.id}`, { method: "DELETE" });
await reload();
};
return (
<>
<div className="flo-settings-section">
<h2>Map layers</h2>
{error && <div className="flo-error">{error}</div>}
{rows.length === 0 ? (
<div className="flo-empty-card">
No custom layers yet. The map shows a procedural canvas by default.
</div>
) : (
<ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
{rows.map((l) => (
<li
key={l.id}
style={{
display: "grid",
gridTemplateColumns: "1fr 100px 100px auto",
gap: 12,
alignItems: "center",
padding: "10px 0",
borderBottom: "1px solid var(--line)",
}}
>
<input
className="flo-input"
defaultValue={l.name}
onBlur={(e) => rename(l, e.target.value)}
/>
<span className="flo-mono flo-mono-dim">
{l.width}×{l.height}
</span>
<button
className={"flo-chip" + (l.isDefault ? " is-active" : "")}
onClick={() => !l.isDefault && setDefault(l)}
disabled={l.isDefault}
>
{l.isDefault ? "default" : "make default"}
</button>
<button className="flo-link is-danger" onClick={() => remove(l)}>
delete
</button>
</li>
))}
</ul>
)}
</div>
<div className="flo-settings-section">
<h2>Add layer</h2>
<div className="flo-form-row">
<label>Name</label>
<input
className="flo-input"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
placeholder="World, Region, City…"
/>
</div>
<div className="flo-form-row">
<label>Image</label>
<input
ref={fileRef}
className="flo-input"
type="file"
accept="image/png,image/jpeg,image/webp,image/svg+xml"
onChange={(e) => onFile(e.target.files?.[0])}
/>
</div>
{draftImage && (
<div className="flo-form-row">
<label>Preview</label>
<img
src={draftImage}
alt="preview"
style={{
maxWidth: 320,
maxHeight: 200,
border: "1px solid var(--line)",
borderRadius: 6,
}}
/>
</div>
)}
<div className="flo-form-row">
<label>Dimensions</label>
<div className="flo-row">
<input
className="flo-input flo-input-mono"
type="number"
value={draft.width}
onChange={(e) => setDraft({ ...draft, width: parseInt(e.target.value, 10) || 1000 })}
style={{ width: 100 }}
/>
<span className="flo-mono flo-mono-dim">×</span>
<input
className="flo-input flo-input-mono"
type="number"
value={draft.height}
onChange={(e) => setDraft({ ...draft, height: parseInt(e.target.value, 10) || 700 })}
style={{ width: 100 }}
/>
</div>
</div>
<div className="flo-row" style={{ marginTop: 14 }}>
<button className="flo-btn" onClick={create} disabled={busy}>
{busy ? "Adding…" : "Add layer"}
</button>
<span className="flo-mono flo-mono-dim">
Empty image keeps the procedural background but lets you place pins on a named layer.
</span>
</div>
</div>
</>
);
}
+102
View File
@@ -0,0 +1,102 @@
"use client";
import { useState } from "react";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
const THEMES = ["midnight", "obsidian", "parchment"] as const;
export default function AdminWorldPage() {
const { world, setWorld } = useFlorte();
const [name, setName] = useState(world.name);
const [tagline, setTagline] = useState(world.tagline);
const [era, setEra] = useState(world.era);
const [theme, setTheme] = useState(world.theme);
const [accent, setAccent] = useState(world.accent);
const [showFog, setShowFog] = useState(world.showFog);
const [savedAt, setSavedAt] = useState<string | null>(null);
const save = async () => {
const updated = await api<{
name: string; tagline: string; era: string;
theme: string; accent: string; showFog: boolean;
}>("/api/world", {
method: "PATCH",
body: JSON.stringify({ name, tagline, era, theme, accent, showFog }),
});
setWorld({
name: updated.name,
tagline: updated.tagline,
era: updated.era,
theme: updated.theme,
accent: updated.accent,
showFog: updated.showFog,
});
setSavedAt(new Date().toLocaleTimeString());
};
return (
<div className="flo-settings-section">
<h2>World</h2>
<div className="flo-form-row">
<label>Name</label>
<input className="flo-input" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="flo-form-row">
<label>Tagline</label>
<input className="flo-input" value={tagline} onChange={(e) => setTagline(e.target.value)} />
</div>
<div className="flo-form-row">
<label>Era</label>
<input className="flo-input" value={era} onChange={(e) => setEra(e.target.value)} />
</div>
<div className="flo-form-row">
<label>Theme</label>
<div className="flo-theme-row">
{THEMES.map((t) => (
<button
key={t}
type="button"
className={"flo-theme-pill" + (theme === t ? " is-active" : "")}
onClick={() => setTheme(t)}
>
{t}
</button>
))}
</div>
</div>
<div className="flo-form-row">
<label>Accent</label>
<div className="flo-row">
<input
type="color"
value={accent}
onChange={(e) => setAccent(e.target.value)}
style={{ width: 50, height: 36, border: "1px solid var(--line)", borderRadius: 6, background: "transparent" }}
/>
<input
className="flo-input flo-input-mono"
value={accent}
onChange={(e) => setAccent(e.target.value)}
style={{ width: 120 }}
/>
</div>
</div>
<div className="flo-form-row">
<label>Map fog</label>
<label className="flo-pill-toggle">
<input
type="checkbox"
checked={showFog}
onChange={(e) => setShowFog(e.target.checked)}
/>
show fog of war by default
</label>
</div>
<div className="flo-row" style={{ marginTop: 14 }}>
<button className="flo-btn" onClick={save}>Save world</button>
{savedAt && <span className="flo-mono flo-mono-dim">saved at {savedAt}</span>}
</div>
</div>
);
}
+144
View File
@@ -0,0 +1,144 @@
"use client";
import { useEffect, useState } from "react";
import { api } from "@/lib/client";
type Party = {
id: string;
name: string;
klass: string;
hpCur: number;
hpMax: number;
color: string;
order: number;
};
export default function PartyPage() {
const [party, setParty] = useState<Party[]>([]);
const [draft, setDraft] = useState({ name: "", klass: "", hpCur: 0, hpMax: 0, color: "#d9b46a" });
const reload = async () => setParty(await api<Party[]>("/api/party"));
useEffect(() => {
reload().catch(() => {});
}, []);
const add = async () => {
if (!draft.name.trim()) return;
await api("/api/party", {
method: "POST",
body: JSON.stringify({ ...draft, order: party.length }),
});
setDraft({ name: "", klass: "", hpCur: 0, hpMax: 0, color: "#d9b46a" });
await reload();
};
const remove = async (id: string) => {
await api(`/api/party/${id}`, { method: "DELETE" });
await reload();
};
const update = async (id: string, patch: Partial<Party>) => {
await api(`/api/party/${id}`, { method: "PATCH", body: JSON.stringify(patch) });
await reload();
};
return (
<div className="flo-settings-section">
<h2>Party</h2>
{party.length === 0 ? (
<div className="flo-empty-card">No party members yet.</div>
) : (
<ul className="flo-party" style={{ marginBottom: 16 }}>
{party.map((p) => (
<li key={p.id} className="flo-party-row" style={{ gap: 8 }}>
<input
type="color"
value={p.color}
onChange={(e) => update(p.id, { color: e.target.value })}
style={{ width: 32, height: 32, padding: 0, border: "1px solid var(--line)", borderRadius: 16, background: "transparent" }}
/>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, flex: 1 }}>
<input
className="flo-input"
defaultValue={p.name}
onBlur={(e) => update(p.id, { name: e.target.value })}
/>
<input
className="flo-input"
defaultValue={p.klass}
onBlur={(e) => update(p.id, { klass: e.target.value })}
placeholder="class & level"
/>
</div>
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
<input
className="flo-input flo-input-mono"
type="number"
defaultValue={p.hpCur}
onBlur={(e) =>
update(p.id, { hpCur: parseInt(e.target.value, 10) || 0 })
}
style={{ width: 70 }}
/>
<span className="flo-mono flo-mono-dim">/</span>
<input
className="flo-input flo-input-mono"
type="number"
defaultValue={p.hpMax}
onBlur={(e) =>
update(p.id, { hpMax: parseInt(e.target.value, 10) || 0 })
}
style={{ width: 70 }}
/>
</div>
<button className="flo-link is-danger" onClick={() => remove(p.id)}>
remove
</button>
</li>
))}
</ul>
)}
<div style={{ display: "grid", gap: 8, gridTemplateColumns: "1fr 1fr 80px 80px 60px auto" }}>
<input
className="flo-input"
placeholder="Name"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
<input
className="flo-input"
placeholder="Class & level"
value={draft.klass}
onChange={(e) => setDraft({ ...draft, klass: e.target.value })}
/>
<input
className="flo-input flo-input-mono"
type="number"
placeholder="HP"
value={draft.hpCur}
onChange={(e) =>
setDraft({ ...draft, hpCur: parseInt(e.target.value, 10) || 0 })
}
/>
<input
className="flo-input flo-input-mono"
type="number"
placeholder="Max"
value={draft.hpMax}
onChange={(e) =>
setDraft({ ...draft, hpMax: parseInt(e.target.value, 10) || 0 })
}
/>
<input
type="color"
value={draft.color}
onChange={(e) => setDraft({ ...draft, color: e.target.value })}
style={{ width: 60, height: 38, border: "1px solid var(--line)", background: "transparent", borderRadius: 6 }}
/>
<button className="flo-btn" onClick={add}>
Add
</button>
</div>
</div>
);
}
+105
View File
@@ -0,0 +1,105 @@
"use client";
import { useEffect, useState } from "react";
import { api } from "@/lib/client";
type Quest = {
id: string;
title: string;
meta: string;
priority: string;
status: string;
isPublic: boolean;
};
export default function QuestsPage() {
const [quests, setQuests] = useState<Quest[]>([]);
const [draft, setDraft] = useState({ title: "", meta: "", priority: "normal", isPublic: true });
const reload = async () => setQuests(await api<Quest[]>("/api/quests"));
useEffect(() => {
reload().catch(() => {});
}, []);
const add = async () => {
if (!draft.title.trim()) return;
await api("/api/quests", { method: "POST", body: JSON.stringify(draft) });
setDraft({ title: "", meta: "", priority: "normal", isPublic: true });
await reload();
};
const remove = async (id: string) => {
await api(`/api/quests/${id}`, { method: "DELETE" });
await reload();
};
const toggle = async (q: Quest) => {
await api(`/api/quests/${q.id}`, {
method: "PATCH",
body: JSON.stringify({ status: q.status === "completed" ? "active" : "completed" }),
});
await reload();
};
return (
<div className="flo-settings-section">
<h2>Quests</h2>
{quests.length === 0 ? (
<div className="flo-empty-card">No quests yet.</div>
) : (
<ul style={{ listStyle: "none", padding: 0, margin: "0 0 16px" }}>
{quests.map((q) => (
<li
key={q.id}
style={{
display: "flex",
gap: 10,
alignItems: "center",
padding: "10px 0",
borderBottom: "1px solid var(--line)",
}}
>
<span className="flo-quest-mark">
{q.priority === "critical" ? "★" : "◇"}
</span>
<div style={{ flex: 1 }}>
<div className="flo-quest-title">{q.title}</div>
{q.meta && <div className="flo-quest-meta">{q.meta}</div>}
</div>
<span className="flo-mono flo-mono-dim">{q.status}</span>
<button className="flo-link" onClick={() => toggle(q)}>
{q.status === "completed" ? "reopen" : "complete"}
</button>
<button className="flo-link is-danger" onClick={() => remove(q.id)}>
delete
</button>
</li>
))}
</ul>
)}
<div style={{ display: "grid", gap: 8, gridTemplateColumns: "2fr 2fr 120px auto" }}>
<input
className="flo-input"
placeholder="Quest title"
value={draft.title}
onChange={(e) => setDraft({ ...draft, title: e.target.value })}
/>
<input
className="flo-input"
placeholder="Meta (giver, reward, etc.)"
value={draft.meta}
onChange={(e) => setDraft({ ...draft, meta: e.target.value })}
/>
<select
className="flo-select"
value={draft.priority}
onChange={(e) => setDraft({ ...draft, priority: e.target.value })}
>
<option value="normal">normal</option>
<option value="critical">critical</option>
</select>
<button className="flo-btn" onClick={add}>
Add quest
</button>
</div>
</div>
);
}
+201
View File
@@ -0,0 +1,201 @@
"use client";
import { useEffect, useState } from "react";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
type User = {
id: string;
username: string;
role: "dm" | "player";
createdAt: string;
};
export default function UsersPage() {
const { session } = useFlorte();
const [rows, setRows] = useState<User[]>([]);
const [draft, setDraft] = useState({ username: "", password: "", role: "player" as "dm" | "player" });
const [pwReset, setPwReset] = useState<Record<string, string>>({});
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const reload = async () => {
setRows(await api<User[]>("/api/users"));
};
useEffect(() => {
reload().catch((e) => setError(e.message));
}, []);
const create = async () => {
setError(null);
setBusy(true);
try {
await api("/api/users", {
method: "POST",
body: JSON.stringify(draft),
});
setDraft({ username: "", password: "", role: "player" });
await reload();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const setRole = async (u: User, role: "dm" | "player") => {
try {
await api(`/api/users/${u.id}`, { method: "PATCH", body: JSON.stringify({ role }) });
await reload();
} catch (e) {
setError((e as Error).message);
}
};
const resetPw = async (u: User) => {
const pw = pwReset[u.id] ?? "";
if (pw.length < 6) {
setError("Password must be 6+ chars");
return;
}
try {
await api(`/api/users/${u.id}`, { method: "PATCH", body: JSON.stringify({ password: pw }) });
setPwReset((p) => ({ ...p, [u.id]: "" }));
setError(null);
} catch (e) {
setError((e as Error).message);
}
};
const remove = async (u: User) => {
if (!confirm(`Delete ${u.username}?`)) return;
try {
await api(`/api/users/${u.id}`, { method: "DELETE" });
await reload();
} catch (e) {
setError((e as Error).message);
}
};
return (
<div className="flo-settings-section">
<h2>Users</h2>
{error && <div className="flo-error">{error}</div>}
{rows.length === 0 ? (
<div className="flo-empty-card">No users yet.</div>
) : (
<table style={{ width: "100%", borderCollapse: "collapse", marginBottom: 18 }}>
<thead>
<tr style={{ textAlign: "left", borderBottom: "1px solid var(--line)" }}>
<th style={th}>Username</th>
<th style={th}>Role</th>
<th style={th}>Created</th>
<th style={th}>Reset password</th>
<th style={th} />
</tr>
</thead>
<tbody>
{rows.map((u) => (
<tr key={u.id} style={{ borderBottom: "1px solid var(--line)" }}>
<td style={td}>
<div style={{ fontFamily: "Cormorant Garamond, serif", fontSize: 18 }}>
{u.username}{" "}
{session.userId === u.id && (
<span className="flo-mono flo-mono-dim">(you)</span>
)}
</div>
</td>
<td style={td}>
<select
className="flo-select"
value={u.role}
onChange={(e) => setRole(u, e.target.value as "dm" | "player")}
>
<option value="dm">dm</option>
<option value="player">player</option>
</select>
</td>
<td style={td}>
<span className="flo-mono flo-mono-dim">
{new Date(u.createdAt).toLocaleDateString()}
</span>
</td>
<td style={td}>
<div style={{ display: "flex", gap: 6 }}>
<input
className="flo-input flo-input-mono"
type="password"
placeholder="new password"
value={pwReset[u.id] ?? ""}
onChange={(e) =>
setPwReset((p) => ({ ...p, [u.id]: e.target.value }))
}
style={{ width: 150 }}
/>
<button className="flo-btn flo-btn-ghost" onClick={() => resetPw(u)}>
reset
</button>
</div>
</td>
<td style={td}>
<button
className="flo-link is-danger"
onClick={() => remove(u)}
disabled={session.userId === u.id}
>
delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
<h3 style={{ fontFamily: "Cormorant Garamond, serif", fontSize: 18, fontWeight: 500, margin: "20px 0 8px" }}>
Add user
</h3>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 120px auto", gap: 8 }}>
<input
className="flo-input"
placeholder="Username"
value={draft.username}
onChange={(e) => setDraft({ ...draft, username: e.target.value })}
/>
<input
className="flo-input"
type="password"
placeholder="Password (6+ chars)"
value={draft.password}
onChange={(e) => setDraft({ ...draft, password: e.target.value })}
/>
<select
className="flo-select"
value={draft.role}
onChange={(e) => setDraft({ ...draft, role: e.target.value as "dm" | "player" })}
>
<option value="player">player</option>
<option value="dm">dm</option>
</select>
<button className="flo-btn" onClick={create} disabled={busy}>
{busy ? "Adding…" : "Add user"}
</button>
</div>
<p className="flo-mono flo-mono-dim" style={{ marginTop: 12 }}>
DMs can read and edit everything. Players can only see entries marked
“Players can see”.
</p>
</div>
);
}
const th: React.CSSProperties = {
padding: "10px 8px",
fontFamily: "JetBrains Mono, monospace",
fontSize: 10,
letterSpacing: ".12em",
textTransform: "uppercase",
color: "var(--ink-4)",
};
const td: React.CSSProperties = { padding: "10px 8px", verticalAlign: "middle" };
+72
View File
@@ -0,0 +1,72 @@
"use client";
import { useEffect, useRef, useState } from "react";
declare global {
interface Window {
SwaggerUIBundle?: (cfg: Record<string, unknown>) => unknown;
}
}
const SWAGGER_VERSION = "5.17.14";
export default function ApiDocsPage() {
const inited = useRef(false);
const [loaded, setLoaded] = useState(
typeof window !== "undefined" && typeof window.SwaggerUIBundle === "function"
);
useEffect(() => {
// Inject CSS once
const cssId = "swagger-ui-css";
if (!document.getElementById(cssId)) {
const link = document.createElement("link");
link.id = cssId;
link.rel = "stylesheet";
link.href = `https://unpkg.com/swagger-ui-dist@${SWAGGER_VERSION}/swagger-ui.css`;
document.head.appendChild(link);
}
// Inject bundle (NOT the standalone preset — that one drags in the
// download/topbar plugin which expects specActions on the spec store
// and crashes when downloadConfig is dispatched before the spec loads).
const scriptId = "swagger-ui-bundle";
const existing = document.getElementById(scriptId) as HTMLScriptElement | null;
if (existing) {
if (typeof window.SwaggerUIBundle === "function") setLoaded(true);
else existing.addEventListener("load", () => setLoaded(true));
return;
}
const script = document.createElement("script");
script.id = scriptId;
script.src = `https://unpkg.com/swagger-ui-dist@${SWAGGER_VERSION}/swagger-ui-bundle.js`;
script.crossOrigin = "anonymous";
script.onload = () => setLoaded(true);
document.head.appendChild(script);
}, []);
useEffect(() => {
if (!loaded || inited.current) return;
if (typeof window.SwaggerUIBundle !== "function") return;
inited.current = true;
window.SwaggerUIBundle({
url: "/api/openapi.json",
dom_id: "#swagger-ui",
deepLinking: true,
tryItOutEnabled: true,
// No `presets`, no `plugins` — defaults are fine and avoid the
// standalone-preset crash about C.specActions being undefined.
});
}, [loaded]);
return (
<div
id="swagger-ui"
style={{
background: "#fafafa",
minHeight: "100vh",
color: "#111",
padding: "12px 0",
}}
/>
);
}
+29
View File
@@ -0,0 +1,29 @@
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
const body = (await req.json()) as { username?: string; password?: string };
const username = (body.username ?? "").trim();
const password = body.password ?? "";
if (!username || !password) return err("Username and password required");
const user = await prisma.user.findUnique({ where: { username } });
if (!user) return err("Invalid credentials", 401);
const ok = await bcrypt.compare(password, user.passwordHash);
if (!ok) return err("Invalid credentials", 401);
const session = await getSession();
session.userId = user.id;
session.username = user.username;
session.role = user.role as "dm" | "player";
await session.save();
return json({ ok: true, role: user.role });
} catch (e) {
return asResponse(e);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { getSession } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function POST() {
try {
const s = await getSession();
s.destroy();
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+17
View File
@@ -0,0 +1,17 @@
import { getSession } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const s = await getSession();
return json({
userId: s.userId ?? null,
username: s.username ?? null,
role: s.role ?? null,
});
} catch (e) {
return asResponse(e);
}
}
+63
View File
@@ -0,0 +1,63 @@
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
const body = (await req.json()) as {
username?: string;
password?: string;
code?: string;
};
const username = (body.username ?? "").trim();
const password = body.password ?? "";
const code = (body.code ?? "").trim();
if (!username || !password) return err("Username and password required");
if (username.length < 2) return err("Username must be at least 2 characters");
if (password.length < 6) return err("Password must be at least 6 characters");
if (!code) return err("Invite code required");
const invite = await prisma.inviteCode.findUnique({
where: { code },
});
if (!invite) return err("Invalid invite code", 404);
if (invite.usedById) return err("This invite has already been used", 409);
if (invite.expiresAt && invite.expiresAt < new Date())
return err("This invite has expired", 410);
const existing = await prisma.user.findUnique({ where: { username } });
if (existing) return err("Username already taken", 409);
const passwordHash = await bcrypt.hash(password, 12);
const user = await prisma.$transaction(async (tx) => {
const newUser = await tx.user.create({
data: { username, passwordHash, role: invite.role },
});
await tx.inviteCode.update({
where: { id: invite.id },
data: { usedById: newUser.id },
});
if (invite.campaignId) {
await tx.campaignMember.create({
data: { userId: newUser.id, campaignId: invite.campaignId },
});
}
return newUser;
});
const session = await getSession();
session.userId = user.id;
session.username = user.username;
session.role = user.role as "dm" | "player";
await session.save();
return json({ ok: true, role: user.role }, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+71
View File
@@ -0,0 +1,71 @@
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
import { getOrCreateWorld } from "@/lib/world";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const dmCount = await prisma.user.count({ where: { role: "dm" } });
return json({ needsSetup: dmCount === 0 });
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
const dmCount = await prisma.user.count({ where: { role: "dm" } });
if (dmCount > 0) return err("Setup already completed", 409);
const body = (await req.json()) as {
username?: string;
password?: string;
worldName?: string;
tagline?: string;
era?: string;
playerPassword?: string;
};
const username = (body.username ?? "").trim();
const password = body.password ?? "";
if (!username || password.length < 6)
return err("Username and a password of 6+ chars are required");
const passwordHash = await bcrypt.hash(password, 10);
const dm = await prisma.user.create({
data: { username, passwordHash, role: "dm" },
});
if (body.playerPassword && body.playerPassword.length >= 4) {
const ph = await bcrypt.hash(body.playerPassword, 10);
await prisma.user.create({
data: { username: "player", passwordHash: ph, role: "player" },
});
}
await getOrCreateWorld();
if (body.worldName || body.tagline || body.era) {
await prisma.world.update({
where: { id: 1 },
data: {
name: body.worldName?.trim() || "My World",
tagline: body.tagline?.trim() ?? "",
era: body.era?.trim() ?? "",
},
});
}
const session = await getSession();
session.userId = dm.id;
session.username = dm.username;
session.role = "dm";
await session.save();
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+33
View File
@@ -0,0 +1,33 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{ time: string; title: string; text: string; flag: string; order: number }>;
const beat = await prisma.sessionBeat.update({
where: { id },
data: { time: b.time, title: b.title, text: b.text, flag: b.flag, order: b.order },
});
return json(beat);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.sessionBeat.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
@@ -0,0 +1,46 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function POST(
req: Request,
{ params }: { params: { id: string } }
) {
try {
await requireDm();
const body = (await req.json()) as { userId?: string };
const userId = (body.userId ?? "").trim();
if (!userId) return err("userId required");
const campaign = await prisma.campaign.findUnique({ where: { id: params.id } });
if (!campaign) return err("Campaign not found", 404);
const member = await prisma.campaignMember.upsert({
where: { userId_campaignId: { userId, campaignId: params.id } },
create: { userId, campaignId: params.id },
update: {},
});
return json(member, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(
req: Request,
{ params }: { params: { id: string } }
) {
try {
await requireDm();
const { userId } = (await req.json()) as { userId?: string };
if (!userId) return err("userId required");
await prisma.campaignMember.delete({
where: { userId_campaignId: { userId, campaignId: params.id } },
});
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+37
View File
@@ -0,0 +1,37 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function PATCH(
req: Request,
{ params }: { params: { id: string } }
) {
try {
await requireDm();
const body = (await req.json()) as { name?: string };
const name = (body.name ?? "").trim();
if (!name) return err("Campaign name required");
const campaign = await prisma.campaign.update({
where: { id: params.id },
data: { name },
});
return json(campaign);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(
_req: Request,
{ params }: { params: { id: string } }
) {
try {
await requireDm();
await prisma.campaign.delete({ where: { id: params.id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+36
View File
@@ -0,0 +1,36 @@
import { prisma } from "@/lib/db";
import { requireDm, requireAuth } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await requireAuth();
const campaigns = await prisma.campaign.findMany({
orderBy: { createdAt: "asc" },
include: {
members: {
include: { user: { select: { id: true, username: true, role: true } } },
},
_count: { select: { reveals: true } },
},
});
return json(campaigns);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const body = (await req.json()) as { name?: string };
const name = (body.name ?? "").trim();
if (!name) return err("Campaign name required");
const campaign = await prisma.campaign.create({ data: { name } });
return json(campaign, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+123
View File
@@ -0,0 +1,123 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
import { entryToDTO } from "@/lib/serialize";
import { syncLinks } from "@/lib/links";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ slug: string }> };
export async function GET(_req: Request, ctx: Ctx) {
try {
const s = await getSession();
const { slug } = await ctx.params;
const entry = await prisma.entry.findUnique({
where: { slug },
include: { reveals: { select: { campaignId: true } } },
});
if (!entry) return err("Not found", 404);
if (!entry.isPublic && s.role !== "dm") {
// Check campaign reveals
if (!s.userId) return err("Not found", 404);
const campaignIds = (
await prisma.campaignMember.findMany({
where: { userId: s.userId },
select: { campaignId: true },
})
).map((m) => m.campaignId);
const isRevealed = entry.reveals.some((r) =>
campaignIds.includes(r.campaignId)
);
if (!isRevealed) return err("Not found", 404);
}
// Backlinks: who links TO this entry
const incoming = await prisma.link.findMany({
where: { toId: entry.id },
include: { from: { include: { reveals: { select: { campaignId: true } } } } },
});
let playerCampaignIds: string[] = [];
if (s.role !== "dm" && s.userId) {
const memberships = await prisma.campaignMember.findMany({
where: { userId: s.userId },
select: { campaignId: true },
});
playerCampaignIds = memberships.map((m) => m.campaignId);
}
const visibleIncoming = incoming
.filter((l) => {
if (s.role === "dm") return true;
if (l.from.isPublic) return true;
return l.from.reveals.some((r) => playerCampaignIds.includes(r.campaignId));
})
.map((l) => ({
slug: l.from.slug,
title: l.from.title,
kind: l.from.kind,
}));
return json({ entry: entryToDTO(entry), backlinks: visibleIncoming });
} catch (e) {
return asResponse(e);
}
}
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { slug } = await ctx.params;
const existing = await prisma.entry.findUnique({ where: { slug } });
if (!existing) return err("Not found", 404);
const body = (await req.json()) as Partial<{
kind: string;
title: string;
subtitle: string;
summary: string;
body: string;
fields: Record<string, string>;
tags: string[];
isPublic: boolean;
stats: Record<string, string | number>;
abilities: { name: string; text: string }[];
}>;
const updated = await prisma.entry.update({
where: { slug },
data: {
kind: body.kind,
title: body.title,
subtitle: body.subtitle,
summary: body.summary,
body: body.body,
fields: body.fields !== undefined ? JSON.stringify(body.fields) : undefined,
tags: body.tags !== undefined ? JSON.stringify(body.tags) : undefined,
isPublic: body.isPublic,
stats: body.stats !== undefined ? JSON.stringify(body.stats) : undefined,
abilities:
body.abilities !== undefined ? JSON.stringify(body.abilities) : undefined,
},
});
if (body.body !== undefined) await syncLinks(updated.id, body.body);
return json(entryToDTO(updated));
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { slug } = await ctx.params;
const existing = await prisma.entry.findUnique({ where: { slug } });
if (!existing) return err("Not found", 404);
await prisma.entry.delete({ where: { slug } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+112
View File
@@ -0,0 +1,112 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
import { entryToDTO, slugify } from "@/lib/serialize";
import { isKind } from "@/lib/kinds";
import { syncLinks } from "@/lib/links";
export const dynamic = "force-dynamic";
async function getPlayerCampaignIds(userId: string): Promise<string[]> {
const memberships = await prisma.campaignMember.findMany({
where: { userId },
select: { campaignId: true },
});
return memberships.map((m) => m.campaignId);
}
export async function GET(req: Request) {
try {
const s = await getSession();
const url = new URL(req.url);
const kind = url.searchParams.get("kind") || undefined;
const q = (url.searchParams.get("q") || "").trim().toLowerCase();
const onlyPublic = s.role !== "dm";
let where: Record<string, unknown> = {};
if (kind && kind !== "all") where.kind = kind;
if (onlyPublic) {
const campaignIds = s.userId ? await getPlayerCampaignIds(s.userId) : [];
where.OR = [
{ isPublic: true },
...(campaignIds.length > 0
? [{ reveals: { some: { campaignId: { in: campaignIds } } } }]
: []),
];
}
const rows = await prisma.entry.findMany({
where,
orderBy: { updatedAt: "desc" },
});
const dtos = rows.map(entryToDTO);
const filtered = q
? dtos.filter((e) =>
(e.title + " " + e.subtitle + " " + e.summary + " " + e.body)
.toLowerCase()
.includes(q)
)
: dtos;
return json(filtered);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const body = (await req.json()) as {
kind?: string;
title?: string;
slug?: string;
subtitle?: string;
summary?: string;
body?: string;
fields?: Record<string, string>;
tags?: string[];
isPublic?: boolean;
stats?: Record<string, string | number>;
abilities?: { name: string; text: string }[];
};
const title = (body.title ?? "").trim();
if (!title) return err("Title required");
const kind = body.kind ?? "lore";
if (!isKind(kind)) return err("Unknown kind");
let slug = (body.slug?.trim() || slugify(title)).toLowerCase();
if (!slug) return err("Could not derive slug");
let n = 0;
let candidate = slug;
while (true) {
const exists = await prisma.entry.findUnique({ where: { slug: candidate } });
if (!exists) break;
n += 1;
candidate = `${slug}-${n}`;
}
slug = candidate;
const entry = await prisma.entry.create({
data: {
slug,
kind,
title,
subtitle: body.subtitle?.trim() ?? "",
summary: body.summary?.trim() ?? "",
body: body.body ?? "",
fields: JSON.stringify(body.fields ?? {}),
tags: JSON.stringify(body.tags ?? []),
isPublic: !!body.isPublic,
stats: JSON.stringify(body.stats ?? {}),
abilities: JSON.stringify(body.abilities ?? []),
},
});
await syncLinks(entry.id, body.body ?? "");
return json(entryToDTO(entry), { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+49
View File
@@ -0,0 +1,49 @@
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
import { applyPlan, parseAzgaar } from "@/lib/import";
import { prisma } from "@/lib/db";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
await requireDm();
const url = new URL(req.url);
const action = url.searchParams.get("action") ?? "preview";
const b = (await req.json()) as Partial<{
input: string;
isPublic: boolean;
mapWidth: number;
mapHeight: number;
createLayer: boolean;
layerName: string;
layerImage: string; // optional data: URL
}>;
if (!b.input || typeof b.input !== "string")
return err("input (string) required");
const plan = parseAzgaar(b.input, {
isPublic: b.isPublic,
mapWidth: b.mapWidth,
mapHeight: b.mapHeight,
});
if (action === "apply") {
let layerId: string | null = null;
if (b.createLayer ?? plan.pins?.length) {
const layer = await prisma.mapLayer.create({
data: {
name: (b.layerName ?? plan.layerName ?? "Azgaar import").trim(),
imageData: b.layerImage ?? "",
width: b.mapWidth ?? 1000,
height: b.mapHeight ?? 1000,
},
});
layerId = layer.id;
}
const result = await applyPlan(plan, { layerId });
return json({ plan, result, layerId });
}
return json({ plan });
} catch (e) {
return asResponse(e);
}
}
+31
View File
@@ -0,0 +1,31 @@
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
import { applyPlan, parseDonjon } from "@/lib/import";
import type { KindId } from "@/lib/kinds";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
await requireDm();
const url = new URL(req.url);
const action = url.searchParams.get("action") ?? "preview"; // preview | apply
const b = (await req.json()) as Partial<{
input: string; kind: KindId; title: string; isPublic: boolean;
}>;
if (!b.input || typeof b.input !== "string")
return err("input (string) required");
const plan = parseDonjon(b.input, {
kind: b.kind,
title: b.title,
isPublic: b.isPublic,
});
if (action === "apply") {
const result = await applyPlan(plan, {});
return json({ plan, result });
}
return json({ plan });
} catch (e) {
return asResponse(e);
}
}
+26
View File
@@ -0,0 +1,26 @@
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
import { applyPlan, parseFantasyTown } from "@/lib/import";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
await requireDm();
const url = new URL(req.url);
const action = url.searchParams.get("action") ?? "preview";
const b = (await req.json()) as Partial<{
input: string; isPublic: boolean;
}>;
if (!b.input || typeof b.input !== "string")
return err("input (string) required");
const plan = parseFantasyTown(b.input, { isPublic: b.isPublic });
if (action === "apply") {
const result = await applyPlan(plan, {});
return json({ plan, result });
}
return json({ plan });
} catch (e) {
return asResponse(e);
}
}
+23
View File
@@ -0,0 +1,23 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function DELETE(
_req: Request,
{ params }: { params: { id: string } }
) {
try {
await requireDm();
const invite = await prisma.inviteCode.findUnique({
where: { id: params.id },
});
if (!invite) return err("Not found", 404);
if (invite.usedById) return err("Cannot revoke a used invite", 409);
await prisma.inviteCode.delete({ where: { id: params.id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+32
View File
@@ -0,0 +1,32 @@
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
try {
const body = (await req.json()) as { code?: string };
const code = (body.code ?? "").trim();
if (!code) return err("Invite code required");
const invite = await prisma.inviteCode.findUnique({
where: { code },
include: { campaign: true },
});
if (!invite) return err("Invalid invite code", 404);
if (invite.usedById) return err("This invite has already been used", 409);
if (invite.expiresAt && invite.expiresAt < new Date())
return err("This invite has expired", 410);
// Return invite info (does not consume it — consumption happens on register)
return json({
valid: true,
role: invite.role,
campaignId: invite.campaignId,
campaignName: invite.campaign?.name ?? null,
});
} catch (e) {
return asResponse(e);
}
}
+45
View File
@@ -0,0 +1,45 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await requireDm();
const invites = await prisma.inviteCode.findMany({
orderBy: { createdAt: "desc" },
include: {
campaign: { select: { id: true, name: true } },
usedBy: { select: { id: true, username: true } },
},
});
return json(invites);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const body = (await req.json()) as {
campaignId?: string;
role?: string;
expiresAt?: string;
};
const invite = await prisma.inviteCode.create({
data: {
campaignId: body.campaignId || null,
role: body.role === "dm" ? "dm" : "player",
expiresAt: body.expiresAt ? new Date(body.expiresAt) : null,
},
include: {
campaign: { select: { id: true, name: true } },
},
});
return json(invite, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireAuth();
const { id } = await ctx.params;
await prisma.journalEntry.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+31
View File
@@ -0,0 +1,31 @@
import { prisma } from "@/lib/db";
import { getSession, requireAuth } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await getSession();
const rows = await prisma.journalEntry.findMany({
orderBy: { createdAt: "desc" },
});
return json(rows);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireAuth();
const b = (await req.json()) as Partial<{ who: string; color: string; text: string }>;
if (!b.who || !b.text) return err("who and text required");
const e = await prisma.journalEntry.create({
data: { who: b.who, text: b.text, color: b.color ?? "#d9b46a" },
});
return json(e, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+65
View File
@@ -0,0 +1,65 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function GET(_req: Request, ctx: Ctx) {
try {
await getSession();
const { id } = await ctx.params;
const layer = await prisma.mapLayer.findUnique({ where: { id } });
if (!layer) return err("Not found", 404);
return json(layer); // includes imageData
} catch (e) {
return asResponse(e);
}
}
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{
name: string; imageData: string; width: number; height: number;
isDefault: boolean; order: number;
}>;
if (b.imageData !== undefined && b.imageData !== "" &&
!/^data:image\/(png|jpeg|jpg|webp|svg\+xml);base64,/.test(b.imageData)) {
return err("imageData must be a data: URL of an image");
}
if (b.isDefault) {
await prisma.mapLayer.updateMany({
where: { NOT: { id } },
data: { isDefault: false },
});
}
const updated = await prisma.mapLayer.update({
where: { id },
data: {
name: b.name,
imageData: b.imageData,
width: b.width,
height: b.height,
isDefault: b.isDefault,
order: b.order,
},
});
return json(updated);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.mapLayer.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+67
View File
@@ -0,0 +1,67 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await getSession();
const layers = await prisma.mapLayer.findMany({
orderBy: [{ order: "asc" }, { createdAt: "asc" }],
select: {
id: true,
name: true,
width: true,
height: true,
isDefault: true,
order: true,
// imageData omitted from list (huge); fetch per-layer
},
});
return json(layers);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as Partial<{
name: string;
imageData: string;
width: number;
height: number;
isDefault: boolean;
}>;
const name = (b.name ?? "").trim();
if (!name) return err("Name required");
const imageData = (b.imageData ?? "").trim();
if (imageData && !/^data:image\/(png|jpeg|jpg|webp|svg\+xml);base64,/.test(imageData)) {
return err("imageData must be a data: URL of an image");
}
if (imageData.length > 6_000_000)
return err("Image too large (max ~4.5MB encoded)", 413);
if (b.isDefault) {
await prisma.mapLayer.updateMany({ data: { isDefault: false } });
}
const last = await prisma.mapLayer.findFirst({ orderBy: { order: "desc" } });
const created = await prisma.mapLayer.create({
data: {
name,
imageData,
width: b.width ?? 1000,
height: b.height ?? 700,
isDefault: b.isDefault ?? false,
order: (last?.order ?? -1) + 1,
},
select: {
id: true, name: true, width: true, height: true, isDefault: true, order: true,
},
});
return json(created, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { openapi } from "@/lib/openapi";
export const dynamic = "force-dynamic";
export async function GET() {
return NextResponse.json(openapi, {
headers: {
"Cache-Control": "no-store",
"Access-Control-Allow-Origin": "*",
},
});
}
+35
View File
@@ -0,0 +1,35 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{
name: string; klass: string; hpCur: number; hpMax: number; color: string; order: number;
}>;
const m = await prisma.partyMember.update({
where: { id },
data: { name: b.name, klass: b.klass, hpCur: b.hpCur, hpMax: b.hpMax, color: b.color, order: b.order },
});
return json(m);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.partyMember.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+38
View File
@@ -0,0 +1,38 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await getSession();
const rows = await prisma.partyMember.findMany({ orderBy: { order: "asc" } });
return json(rows);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as Partial<{
name: string; klass: string; hpCur: number; hpMax: number; color: string; order: number;
}>;
if (!b.name) return err("Name required");
const m = await prisma.partyMember.create({
data: {
name: b.name,
klass: b.klass ?? "",
hpCur: b.hpCur ?? 0,
hpMax: b.hpMax ?? 0,
color: b.color ?? "#d9b46a",
order: b.order ?? 0,
},
});
return json(m, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+52
View File
@@ -0,0 +1,52 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{
x: number; y: number; label: string; kind: string;
entrySlug: string | null; layerId: string | null;
}>;
let entryId: string | null | undefined = undefined;
if (b.entrySlug !== undefined) {
if (b.entrySlug === null) entryId = null;
else {
const e = await prisma.entry.findUnique({ where: { slug: b.entrySlug } });
if (!e) return err("Linked entry not found", 404);
entryId = e.id;
}
}
const pin = await prisma.mapPin.update({
where: { id },
data: {
x: b.x,
y: b.y,
label: b.label,
kind: b.kind,
entryId,
layerId: b.layerId === undefined ? undefined : b.layerId,
},
});
return json(pin);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.mapPin.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+72
View File
@@ -0,0 +1,72 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET(req: Request) {
try {
const s = await getSession();
const url = new URL(req.url);
const layerId = url.searchParams.get("layerId");
const where: { layerId?: string | null } = {};
if (layerId === "null" || layerId === "") where.layerId = null;
else if (layerId) where.layerId = layerId;
const pins = await prisma.mapPin.findMany({
where,
include: { entry: { select: { slug: true, isPublic: true, title: true, kind: true } } },
});
const visible =
s.role === "dm" ? pins : pins.filter((p) => !p.entry || p.entry.isPublic);
return json(
visible.map((p) => ({
id: p.id,
x: p.x,
y: p.y,
label: p.label,
kind: p.entry?.kind ?? p.kind,
entrySlug: p.entry?.slug ?? null,
layerId: p.layerId ?? null,
}))
);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as {
x?: number; y?: number; label?: string; kind?: string;
entrySlug?: string | null; layerId?: string | null;
};
if (
typeof b.x !== "number" ||
typeof b.y !== "number" ||
!b.label ||
b.x < 0 || b.x > 1 || b.y < 0 || b.y > 1
) {
return err("x, y (0..1) and label required");
}
let entryId: string | undefined;
if (b.entrySlug) {
const e = await prisma.entry.findUnique({ where: { slug: b.entrySlug } });
if (!e) return err("Linked entry not found", 404);
entryId = e.id;
}
const pin = await prisma.mapPin.create({
data: {
x: b.x,
y: b.y,
label: b.label,
kind: b.kind ?? "location",
entryId,
layerId: b.layerId ?? null,
},
});
return json(pin, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+41
View File
@@ -0,0 +1,41 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{
title: string; meta: string; priority: string; status: string; isPublic: boolean;
}>;
const q = await prisma.quest.update({
where: { id },
data: {
title: b.title,
meta: b.meta,
priority: b.priority,
status: b.status,
isPublic: b.isPublic,
},
});
return json(q);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.quest.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+40
View File
@@ -0,0 +1,40 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const s = await getSession();
const where = s.role === "dm" ? undefined : { isPublic: true };
const rows = await prisma.quest.findMany({
where,
orderBy: [{ status: "asc" }, { createdAt: "desc" }],
});
return json(rows);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as Partial<{
title: string; meta: string; priority: string; isPublic: boolean;
}>;
if (!b.title) return err("Title required");
const q = await prisma.quest.create({
data: {
title: b.title,
meta: b.meta ?? "",
priority: b.priority === "critical" ? "critical" : "normal",
isPublic: b.isPublic ?? true,
},
});
return json(q, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+56
View File
@@ -0,0 +1,56 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
// GET /api/reveals?entryId=xxx → list campaigns this entry is revealed to
export async function GET(req: Request) {
try {
await requireDm();
const { searchParams } = new URL(req.url);
const entryId = searchParams.get("entryId");
if (!entryId) return err("entryId required");
const reveals = await prisma.entryReveal.findMany({
where: { entryId },
include: { campaign: { select: { id: true, name: true } } },
});
return json(reveals);
} catch (e) {
return asResponse(e);
}
}
// POST /api/reveals { entryId, campaignId } → reveal
export async function POST(req: Request) {
try {
await requireDm();
const body = (await req.json()) as { entryId?: string; campaignId?: string };
if (!body.entryId || !body.campaignId) return err("entryId and campaignId required");
const reveal = await prisma.entryReveal.upsert({
where: { entryId_campaignId: { entryId: body.entryId, campaignId: body.campaignId } },
create: { entryId: body.entryId, campaignId: body.campaignId },
update: {},
});
return json(reveal, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
// DELETE /api/reveals { entryId, campaignId } → hide
export async function DELETE(req: Request) {
try {
await requireDm();
const body = (await req.json()) as { entryId?: string; campaignId?: string };
if (!body.entryId || !body.campaignId) return err("entryId and campaignId required");
await prisma.entryReveal.deleteMany({
where: { entryId: body.entryId, campaignId: body.campaignId },
});
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
@@ -0,0 +1,54 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ slug: string }> };
export async function GET(_req: Request, ctx: Ctx) {
try {
const s = await getSession();
const { slug } = await ctx.params;
const session = await prisma.entry.findUnique({ where: { slug } });
if (!session || session.kind !== "session") return err("Session not found", 404);
if (!session.isPublic && s.role !== "dm") return err("Not found", 404);
const beats = await prisma.sessionBeat.findMany({
where: { entryId: session.id },
orderBy: { order: "asc" },
});
return json(beats);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request, ctx: Ctx) {
try {
await requireDm();
const { slug } = await ctx.params;
const session = await prisma.entry.findUnique({ where: { slug } });
if (!session || session.kind !== "session") return err("Session not found", 404);
const b = (await req.json()) as Partial<{
time: string; title: string; text: string; flag: string; order: number;
}>;
if (!b.title) return err("Beat title required");
const last = await prisma.sessionBeat.findFirst({
where: { entryId: session.id },
orderBy: { order: "desc" },
});
const beat = await prisma.sessionBeat.create({
data: {
entryId: session.id,
time: b.time ?? "",
title: b.title,
text: b.text ?? "",
flag: b.flag ?? "",
order: b.order ?? (last?.order ?? -1) + 1,
},
});
return json(beat, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+24
View File
@@ -0,0 +1,24 @@
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const s = await getSession();
const onlyPublic = s.role !== "dm";
const grouped = await prisma.entry.groupBy({
by: ["kind"],
_count: { _all: true },
where: onlyPublic ? { isPublic: true } : undefined,
});
const totalAll = await prisma.entry.count();
const totalPublic = await prisma.entry.count({ where: { isPublic: true } });
const byKind: Record<string, number> = {};
for (const g of grouped) byKind[g.kind] = g._count._all;
return json({ totalAll, totalPublic, byKind });
} catch (e) {
return asResponse(e);
}
}
+33
View File
@@ -0,0 +1,33 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{ text: string; who: string; primary: boolean; resolved: boolean }>;
const t = await prisma.thread.update({
where: { id },
data: { text: b.text, who: b.who, primary: b.primary, resolved: b.resolved },
});
return json(t);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.thread.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+32
View File
@@ -0,0 +1,32 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await requireDm();
const rows = await prisma.thread.findMany({
where: { resolved: false },
orderBy: [{ primary: "desc" }, { createdAt: "desc" }],
});
return json(rows);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as Partial<{ text: string; who: string; primary: boolean }>;
if (!b.text) return err("text required");
const t = await prisma.thread.create({
data: { text: b.text, who: b.who ?? "", primary: !!b.primary },
});
return json(t, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+44
View File
@@ -0,0 +1,44 @@
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
const b = (await req.json()) as Partial<{
year: number; era: string; label: string; text: string; kind: string; entrySlug: string | null;
}>;
let entryId: string | null | undefined = undefined;
if (b.entrySlug !== undefined) {
if (b.entrySlug === null) entryId = null;
else {
const e = await prisma.entry.findUnique({ where: { slug: b.entrySlug } });
if (!e) return err("Linked entry not found", 404);
entryId = e.id;
}
}
const ev = await prisma.timelineEvent.update({
where: { id },
data: { year: b.year, era: b.era, label: b.label, text: b.text, kind: b.kind, entryId },
});
return json(ev);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
await requireDm();
const { id } = await ctx.params;
await prisma.timelineEvent.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+66
View File
@@ -0,0 +1,66 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
const s = await getSession();
const events = await prisma.timelineEvent.findMany({
orderBy: { year: "asc" },
include: { entry: { select: { isPublic: true, slug: true, title: true } } },
});
const visible =
s.role === "dm"
? events
: events.filter((e) => !e.entry || e.entry.isPublic);
return json(
visible.map((e) => ({
id: e.id,
year: e.year,
era: e.era,
label: e.label,
text: e.text,
kind: e.kind,
entrySlug: e.entry?.slug ?? null,
}))
);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as {
year?: number;
era?: string;
label?: string;
text?: string;
kind?: string;
entrySlug?: string | null;
};
if (typeof b.year !== "number" || !b.label) return err("year and label required");
let entryId: string | undefined;
if (b.entrySlug) {
const e = await prisma.entry.findUnique({ where: { slug: b.entrySlug } });
if (!e) return err("Linked entry not found", 404);
entryId = e.id;
}
const ev = await prisma.timelineEvent.create({
data: {
year: b.year,
era: b.era ?? "",
label: b.label,
text: b.text ?? "",
kind: b.kind ?? "lore",
entryId,
},
});
return json(ev, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+79
View File
@@ -0,0 +1,79 @@
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(req: Request, ctx: Ctx) {
try {
const me = await requireDm();
const { id } = await ctx.params;
const target = await prisma.user.findUnique({ where: { id } });
if (!target) return err("Not found", 404);
const b = (await req.json()) as Partial<{
username: string; password: string; role: string;
}>;
const data: {
username?: string;
role?: string;
passwordHash?: string;
} = {};
if (b.username !== undefined) {
const u = b.username.trim();
if (!u) return err("Username cannot be empty");
if (u !== target.username) {
const dup = await prisma.user.findUnique({ where: { username: u } });
if (dup) return err("Username already taken", 409);
}
data.username = u;
}
if (b.password !== undefined) {
if (b.password.length < 6) return err("Password must be 6+ chars");
data.passwordHash = await bcrypt.hash(b.password, 10);
}
if (b.role !== undefined) {
const role = b.role === "dm" ? "dm" : "player";
if (target.role === "dm" && role !== "dm") {
const dms = await prisma.user.count({ where: { role: "dm" } });
if (dms <= 1) return err("Cannot demote the last DM", 400);
}
data.role = role;
}
const updated = await prisma.user.update({
where: { id },
data,
select: { id: true, username: true, role: true, createdAt: true },
});
return json(updated);
} catch (e) {
return asResponse(e);
}
}
export async function DELETE(_req: Request, ctx: Ctx) {
try {
const me = await requireDm();
const { id } = await ctx.params;
const target = await prisma.user.findUnique({ where: { id } });
if (!target) return err("Not found", 404);
if (target.role === "dm") {
const dms = await prisma.user.count({ where: { role: "dm" } });
if (dms <= 1) return err("Cannot delete the last DM", 400);
}
if (target.id === me.userId) {
return err("Use another DM to delete your own account", 400);
}
await prisma.user.delete({ where: { id } });
return json({ ok: true });
} catch (e) {
return asResponse(e);
}
}
+43
View File
@@ -0,0 +1,43 @@
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/db";
import { requireDm } from "@/lib/session";
import { json, err, asResponse } from "@/lib/api";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await requireDm();
const users = await prisma.user.findMany({
orderBy: { createdAt: "asc" },
select: { id: true, username: true, role: true, createdAt: true },
});
return json(users);
} catch (e) {
return asResponse(e);
}
}
export async function POST(req: Request) {
try {
await requireDm();
const b = (await req.json()) as Partial<{
username: string; password: string; role: string;
}>;
const username = (b.username ?? "").trim();
const password = b.password ?? "";
const role = b.role === "dm" ? "dm" : "player";
if (!username || password.length < 6)
return err("username + password (6+ chars) required");
const exists = await prisma.user.findUnique({ where: { username } });
if (exists) return err("Username already taken", 409);
const passwordHash = await bcrypt.hash(password, 10);
const u = await prisma.user.create({
data: { username, passwordHash, role },
select: { id: true, username: true, role: true, createdAt: true },
});
return json(u, { status: 201 });
} catch (e) {
return asResponse(e);
}
}
+41
View File
@@ -0,0 +1,41 @@
import { prisma } from "@/lib/db";
import { getSession, requireDm } from "@/lib/session";
import { json, asResponse } from "@/lib/api";
import { getOrCreateWorld } from "@/lib/world";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await getSession();
const world = await getOrCreateWorld();
return json(world);
} catch (e) {
return asResponse(e);
}
}
export async function PATCH(req: Request) {
try {
await requireDm();
const body = (await req.json()) as Partial<{
name: string; tagline: string; era: string;
theme: string; accent: string; showFog: boolean;
}>;
await getOrCreateWorld();
const updated = await prisma.world.update({
where: { id: 1 },
data: {
name: body.name,
tagline: body.tagline,
era: body.era,
theme: body.theme,
accent: body.accent,
showFog: body.showFog,
},
});
return json(updated);
} catch (e) {
return asResponse(e);
}
}
+436
View File
@@ -0,0 +1,436 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { RequireRole } from "@/components/RequireRole";
import { KindPill, VisibilityBadge } from "@/components/Pills";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import type { EntryDTO } from "@/lib/serialize";
import { KINDS, isKind } from "@/lib/kinds";
type Backlink = { slug: string; title: string; kind: string };
type ApiResp = { entry: EntryDTO; backlinks: Backlink[] };
export default function Page({ params }: { params: { slug: string } }) {
return (
<RequireRole>
<ArticleScreen slug={params.slug} />
</RequireRole>
);
}
type Campaign = { id: string; name: string };
type RevealRecord = { id: string; campaignId: string; campaign: Campaign };
function RevealPanel({ entryId }: { entryId: string }) {
const { t } = useFlorte();
const [campaigns, setCampaigns] = useState<Campaign[]>([]);
const [reveals, setReveals] = useState<RevealRecord[]>([]);
const [open, setOpen] = useState(false);
useEffect(() => {
if (!open) return;
Promise.all([
fetch("/api/campaigns").then((r) => r.json()),
fetch(`/api/reveals?entryId=${entryId}`).then((r) => r.json()),
]).then(([c, r]) => {
setCampaigns(Array.isArray(c) ? c : []);
setReveals(Array.isArray(r) ? r : []);
});
}, [open, entryId]);
const isRevealed = (campaignId: string) =>
reveals.some((r) => r.campaignId === campaignId);
const toggle = async (campaignId: string) => {
const revealed = isRevealed(campaignId);
await fetch("/api/reveals", {
method: revealed ? "DELETE" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ entryId, campaignId }),
});
const r = await fetch(`/api/reveals?entryId=${entryId}`).then((res) =>
res.json()
);
setReveals(Array.isArray(r) ? r : []);
};
if (campaigns.length === 0 && !open) return null;
return (
<div style={{ position: "relative" }}>
<button
className="flo-btn flo-btn-ghost"
onClick={() => setOpen((v) => !v)}
>
<span className="flo-glyph">◈</span> Campaigns
</button>
{open && (
<div
style={{
position: "absolute",
top: "100%",
left: 0,
zIndex: 30,
marginTop: 4,
background: "var(--bg-2)",
border: "1px solid var(--line-2)",
borderRadius: "var(--radius-sm)",
padding: "10px 14px",
minWidth: 200,
boxShadow: "0 8px 24px rgba(0,0,0,.5)",
}}
>
{campaigns.length === 0 ? (
<div style={{ fontSize: 13, color: "var(--ink-3)", fontStyle: "italic" }}>
{t("campaign_no_campaigns")}
</div>
) : (
campaigns.map((c) => (
<label
key={c.id}
style={{
display: "flex",
alignItems: "center",
gap: 8,
fontSize: 13,
cursor: "pointer",
padding: "4px 0",
}}
>
<input
type="checkbox"
checked={isRevealed(c.id)}
onChange={() => toggle(c.id)}
style={{ accentColor: "var(--brass)" }}
/>
{c.name}
</label>
))
)}
</div>
)}
</div>
);
}
function ArticleScreen({ slug }: { slug: string }) {
const router = useRouter();
const { session } = useFlorte();
const [data, setData] = useState<ApiResp | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setData(null);
setError(null);
api<ApiResp>(`/api/entries/${encodeURIComponent(slug)}`)
.then(setData)
.catch((e) => setError(e.message));
}, [slug]);
if (error)
return (
<div className="flo-screen">
<div className="flo-empty-card">
{error}.{" "}
<Link href="/search" className="flo-link">
Back to search →
</Link>
</div>
</div>
);
if (!data) return <div className="flo-screen" />;
const { entry, backlinks } = data;
const onDelete = async () => {
if (!confirm(`Delete "${entry.title}"? This cannot be undone.`)) return;
await api(`/api/entries/${entry.slug}`, { method: "DELETE" });
router.push("/search");
};
return (
<div className="flo-screen flo-article">
<div className="flo-article-head">
<div className="flo-article-meta">
<KindPill kind={entry.kind} />
<VisibilityBadge isPublic={entry.isPublic} />
{entry.tags.map((t) => (
<span key={t} className="flo-tag-sm">
#{t}
</span>
))}
</div>
<h1 className="flo-article-title">{entry.title}</h1>
{entry.subtitle && <p className="flo-article-sub">{entry.subtitle}</p>}
{session.role === "dm" && (
<div className="flo-article-actions">
<Link href={`/editor/${entry.slug}`} className="flo-btn flo-btn-ghost">
<span className="flo-glyph">✎</span> Edit
</Link>
<button
className="flo-btn flo-btn-ghost"
onClick={async () => {
await api(`/api/entries/${entry.slug}`, {
method: "PATCH",
body: JSON.stringify({ isPublic: !entry.isPublic }),
});
const r = await api<ApiResp>(`/api/entries/${entry.slug}`);
setData(r);
}}
>
<span className="flo-glyph">⤴</span>{" "}
{entry.isPublic ? "Hide from players" : "Reveal to players"}
</button>
<RevealPanel entryId={entry.id} />
<button className="flo-btn flo-btn-ghost flo-btn-danger" onClick={onDelete}>
<span className="flo-glyph">⊖</span> Delete
</button>
</div>
)}
</div>
<div className="flo-article-grid">
<div className="flo-article-main">
{entry.summary && (
<div className="flo-article-summary">
<span className="flo-pull-quote">“</span>
{entry.summary}
</div>
)}
<RenderBody body={entry.body} canSeeSecrets={session.role === "dm"} />
{backlinks.length > 0 && (
<section className="flo-backlinks">
<h3>Mentioned in</h3>
<ul>
{backlinks.map((b) => (
<li key={b.slug}>
<Link href={`/article/${b.slug}`} className="flo-backlink">
<KindPill kind={b.kind} small />
<span>{b.title}</span>
</Link>
</li>
))}
</ul>
</section>
)}
</div>
<aside className="flo-article-side">
{Object.keys(entry.fields).length > 0 && (
<div className="flo-infobox">
<div className="flo-infobox-portrait">
<div className="flo-portrait-placeholder">
<div className="flo-portrait-glyph">
{isKind(entry.kind) ? KINDS[entry.kind].glyph : "❖"}
</div>
<div className="flo-portrait-label">infobox</div>
</div>
</div>
<dl className="flo-infobox-fields">
{Object.entries(entry.fields).map(([k, v]) => (
<Row key={k} k={k} v={String(v)} />
))}
</dl>
</div>
)}
<LocalGraph slug={slug} backlinks={backlinks} centerTitle={entry.title} centerKind={entry.kind} />
</aside>
</div>
</div>
);
}
function Row({ k, v }: { k: string; v: string }) {
return (
<>
<dt>{k}</dt>
<dd>{v}</dd>
</>
);
}
function RenderBody({ body, canSeeSecrets }: { body: string; canSeeSecrets: boolean }) {
const blocks = useMemo(() => parseBody(body), [body]);
return (
<>
{blocks.map((b, i) => {
if (b.type === "h") return <h2 key={i} className="flo-article-h">{b.text}</h2>;
if (b.type === "quote")
return (
<blockquote key={i} className="flo-article-quote">
<div>{b.text}</div>
{b.attrib && <cite>{b.attrib}</cite>}
</blockquote>
);
if (b.type === "p") {
if (b.secret && !canSeeSecrets) return null;
return (
<p key={i} className={"flo-article-p" + (b.secret ? " is-secret" : "")}>
{b.secret && <span className="flo-secret-mark">DM</span>}
{renderInline(b.text)}
</p>
);
}
return null;
})}
</>
);
}
type Block =
| { type: "h"; text: string }
| { type: "p"; text: string; secret?: boolean }
| { type: "quote"; text: string; attrib?: string };
function parseBody(body: string): Block[] {
if (!body.trim()) return [];
const out: Block[] = [];
const lines = body.replace(/\r\n/g, "\n").split("\n");
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (/^\s*##\s+/.test(line)) {
out.push({ type: "h", text: line.replace(/^\s*##\s+/, "").trim() });
i++;
} else if (/^\s*>\s/.test(line)) {
// blockquote: consume contiguous > lines
const buf: string[] = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
buf.push(lines[i].replace(/^\s*>\s?/, ""));
i++;
}
const all = buf.join("\n").trim();
const attribMatch = all.match(/\s*[—-]\s*(.+)$/m);
let text = all;
let attrib: string | undefined;
if (attribMatch) {
attrib = attribMatch[0].trim();
text = all.slice(0, attribMatch.index).trim();
}
out.push({ type: "quote", text, attrib });
} else if (/^\s*::secret\s*$/.test(line)) {
// ::secret block (until ::end)
i++;
const buf: string[] = [];
while (i < lines.length && !/^\s*::end\s*$/.test(lines[i])) {
buf.push(lines[i]);
i++;
}
if (i < lines.length) i++;
const text = buf.join("\n").trim();
if (text) out.push({ type: "p", text, secret: true });
} else if (line.trim() === "") {
i++;
} else {
// paragraph: collect until blank line
const buf: string[] = [];
while (
i < lines.length &&
lines[i].trim() !== "" &&
!/^\s*##\s+/.test(lines[i]) &&
!/^\s*>\s/.test(lines[i]) &&
!/^\s*::secret\s*$/.test(lines[i])
) {
buf.push(lines[i]);
i++;
}
out.push({ type: "p", text: buf.join(" ") });
}
}
return out;
}
function renderInline(text: string) {
const parts: (string | React.ReactNode)[] = [];
const re = /\[\[([^\]]+)\]\]/g;
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (m.index > last) parts.push(text.slice(last, m.index));
const target = m[1].trim();
const slug = target
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
parts.push(
<Link key={m.index} href={`/article/${slug}`} className="flo-wikilink">
{target}
</Link>
);
last = m.index + m[0].length;
}
if (last < text.length) parts.push(text.slice(last));
return parts;
}
function LocalGraph({
slug,
backlinks,
centerTitle,
centerKind,
}: {
slug: string;
backlinks: Backlink[];
centerTitle: string;
centerKind: string;
}) {
const router = useRouter();
const links = backlinks.slice(0, 6);
const cx = 130, cy = 110, R = 78;
return (
<div className="flo-graph">
<div className="flo-graph-head">
<h3>Local graph</h3>
<span className="flo-mono">{links.length + 1} nodes</span>
</div>
<svg viewBox="0 0 260 220" className="flo-graph-svg">
<defs>
<radialGradient id={`rg-${slug}`} cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor="rgba(217,180,106,.35)" />
<stop offset="100%" stopColor="rgba(217,180,106,0)" />
</radialGradient>
</defs>
<circle cx={cx} cy={cy} r="92" fill={`url(#rg-${slug})`} />
{links.map((l, i) => {
const a = (i / Math.max(1, links.length)) * Math.PI * 2 - Math.PI / 2;
const x = cx + R * Math.cos(a);
const y = cy + R * Math.sin(a);
const color = isKind(l.kind) ? KINDS[l.kind].color : "#aaa";
return (
<g
key={l.slug}
className="flo-graph-node"
onClick={() => router.push(`/article/${l.slug}`)}
>
<line x1={cx} y1={cy} x2={x} y2={y} stroke="rgba(217,180,106,.35)" strokeWidth=".6" />
<circle cx={x} cy={y} r="6" fill={color} opacity=".85" />
<text x={x} y={y + 18} textAnchor="middle" className="flo-graph-text">
{l.title.split(/\s+/)[0]}
</text>
</g>
);
})}
<circle
cx={cx}
cy={cy}
r="10"
fill={isKind(centerKind) ? KINDS[centerKind].color : "#f4e6c2"}
/>
<circle
cx={cx}
cy={cy}
r="14"
fill="none"
stroke="rgba(244,230,194,.5)"
strokeWidth=".5"
/>
<text x={cx} y={cy + 28} textAnchor="middle" className="flo-graph-text is-center">
{centerTitle.split(/\s+/)[0]}
</text>
</svg>
</div>
);
}
+211
View File
@@ -0,0 +1,211 @@
"use client";
import { use, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { RequireRole } from "@/components/RequireRole";
import { KindPill, VisibilityBadge } from "@/components/Pills";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import type { EntryDTO } from "@/lib/serialize";
type ApiResp = {
entry: EntryDTO;
backlinks: { slug: string; title: string; kind: string }[];
};
export default function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = use(params);
return (
<RequireRole>
<BestiaryDetail slug={slug} />
</RequireRole>
);
}
function BestiaryDetail({ slug }: { slug: string }) {
const router = useRouter();
const { session } = useFlorte();
const [list, setList] = useState<EntryDTO[]>([]);
const [data, setData] = useState<ApiResp | null>(null);
const [q, setQ] = useState("");
useEffect(() => {
api<EntryDTO[]>("/api/entries?kind=beast").then(setList);
}, []);
useEffect(() => {
api<ApiResp>(`/api/entries/${encodeURIComponent(slug)}`).then(setData).catch(() => router.replace("/bestiary"));
}, [slug, router]);
if (!data) return <div className="flo-screen" />;
const e = data.entry;
const stats = e.stats as Record<string, string | number>;
const filtered = q
? list.filter((r) => (r.title + r.subtitle).toLowerCase().includes(q.toLowerCase()))
: list;
const abilityMod = (n: unknown) => {
const v = typeof n === "number" ? n : parseInt(String(n ?? ""), 10);
if (Number.isNaN(v)) return "";
const m = Math.floor((v - 10) / 2);
return (m >= 0 ? "+" : "") + m;
};
return (
<div className="flo-screen flo-bestiary">
<div className="flo-bestiary-grid">
<aside className="flo-bestiary-list">
<div className="flo-bestiary-search">
<span className="flo-search-glyph">⌕</span>
<input
placeholder={`Search ${list.length} beasts…`}
value={q}
onChange={(ev) => setQ(ev.target.value)}
/>
</div>
<ul className="flo-bestiary-rows">
{filtered.map((b) => (
<li
key={b.slug}
className={"flo-bestiary-row" + (b.slug === slug ? " is-active" : "")}
onClick={() => router.push(`/bestiary/${b.slug}`)}
>
<div className="flo-bestiary-row-glyph">✺</div>
<div className="flo-bestiary-row-body">
<div className="flo-bestiary-row-title">{b.title}</div>
<div className="flo-bestiary-row-meta flo-mono">
{String(b.stats?.["HP"] ?? "—")}
</div>
</div>
<div className="flo-bestiary-cr">CR {String(b.stats?.["Challenge"] ?? "?")}</div>
</li>
))}
</ul>
</aside>
<div className="flo-statblock-wrap">
<article className="flo-statblock">
<header className="flo-sb-head">
<div className="flo-sb-eyebrow">
<KindPill kind="beast" small />
<VisibilityBadge isPublic={e.isPublic} />
</div>
<h1 className="flo-sb-title">{e.title}</h1>
{e.subtitle && (
<p className="flo-sb-sub">
<em>{e.subtitle}</em>
</p>
)}
<div className="flo-sb-rule" />
</header>
{(stats.AC || stats.HP || stats.Speed) && (
<>
<dl className="flo-sb-top">
{stats.AC != null && (
<div>
<dt>Armor Class</dt>
<dd>{String(stats.AC)}</dd>
</div>
)}
{stats.HP != null && (
<div>
<dt>Hit Points</dt>
<dd>{String(stats.HP)}</dd>
</div>
)}
{stats.Speed != null && (
<div>
<dt>Speed</dt>
<dd>{String(stats.Speed)}</dd>
</div>
)}
</dl>
<div className="flo-sb-rule" />
</>
)}
{(["STR", "DEX", "CON", "INT", "WIS", "CHA"].some((k) => stats[k] != null)) && (
<>
<div className="flo-sb-abilities">
{(["STR", "DEX", "CON", "INT", "WIS", "CHA"] as const).map((k) => (
<div key={k} className="flo-sb-ab">
<div className="flo-sb-ab-key">{k}</div>
<div className="flo-sb-ab-val">{String(stats[k] ?? "—")}</div>
<div className="flo-sb-ab-mod flo-mono">
{stats[k] != null ? abilityMod(stats[k]) : ""}
</div>
</div>
))}
</div>
<div className="flo-sb-rule" />
</>
)}
{["Saving Throws", "Damage Resist.", "Condition Imm.", "Senses", "Languages", "Challenge"]
.some((k) => stats[k] != null) && (
<dl className="flo-sb-extras">
{["Saving Throws", "Damage Resist.", "Condition Imm.", "Senses", "Languages", "Challenge"]
.filter((k) => stats[k] != null)
.map((k) => (
<div key={k}>
<dt>{k}</dt>
<dd>{String(stats[k])}</dd>
</div>
))}
</dl>
)}
{e.abilities.length > 0 && (
<>
<div className="flo-sb-rule" />
<section className="flo-sb-section">
<h2>Traits & Actions</h2>
{e.abilities.map((a, i) => (
<p key={i}>
<strong><em>{a.name}.</em></strong> {a.text}
</p>
))}
</section>
</>
)}
{e.body && (
<>
<div className="flo-sb-rule" />
<section className="flo-sb-section">
<h2>Notes</h2>
<p style={{ whiteSpace: "pre-wrap" }}>{e.body}</p>
</section>
</>
)}
</article>
<div className="flo-sb-side">
{session.role === "dm" && (
<>
<Link href={`/editor/${e.slug}`} className="flo-btn">
Edit stat block
</Link>
<Link href={`/article/${e.slug}`} className="flo-btn flo-btn-ghost">
Open article view
</Link>
</>
)}
{data.backlinks.length > 0 && (
<div className="flo-sb-side-card">
<div className="flo-mono flo-mono-dim">Encountered in</div>
{data.backlinks.map((b) => (
<Link key={b.slug} href={`/article/${b.slug}`} className="flo-backlink">
<KindPill kind={b.kind} small />
<span>{b.title}</span>
</Link>
))}
</div>
)}
</div>
</div>
</div>
</div>
);
}
+96
View File
@@ -0,0 +1,96 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { RequireRole } from "@/components/RequireRole";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import type { EntryDTO } from "@/lib/serialize";
export default function Page() {
return (
<RequireRole>
<BestiaryListScreen />
</RequireRole>
);
}
function BestiaryListScreen() {
const router = useRouter();
const { session } = useFlorte();
const [rows, setRows] = useState<EntryDTO[]>([]);
const [q, setQ] = useState("");
useEffect(() => {
api<EntryDTO[]>("/api/entries?kind=beast").then(setRows);
}, []);
// If we have at least one beast, deep-link to first one (so the list+article
// pattern from the design works)
useEffect(() => {
if (rows.length > 0) {
router.replace(`/bestiary/${rows[0].slug}`);
}
}, [rows, router]);
const filtered = q
? rows.filter((r) =>
(r.title + r.subtitle + (r.tags || []).join(" ")).toLowerCase().includes(q.toLowerCase())
)
: rows;
if (rows.length === 0) {
return (
<div className="flo-screen">
<div className="flo-empty-card" style={{ padding: 64 }}>
The bestiary is empty.
{session.role === "dm" && (
<>
{" "}
<Link className="flo-link" href="/editor">
Add a beast →
</Link>
</>
)}
</div>
</div>
);
}
// While redirecting, show the list briefly
return (
<div className="flo-screen flo-bestiary">
<div className="flo-bestiary-grid">
<aside className="flo-bestiary-list">
<div className="flo-bestiary-search">
<span className="flo-search-glyph">⌕</span>
<input
placeholder={`Search ${rows.length} beasts…`}
value={q}
onChange={(e) => setQ(e.target.value)}
/>
</div>
<div className="flo-mono flo-mono-dim flo-bestiary-meta">
{filtered.length} entries
</div>
<ul className="flo-bestiary-rows">
{filtered.map((b) => (
<li key={b.slug} className="flo-bestiary-row" onClick={() => router.push(`/bestiary/${b.slug}`)}>
<div className="flo-bestiary-row-glyph">✺</div>
<div className="flo-bestiary-row-body">
<div className="flo-bestiary-row-title">{b.title}</div>
<div className="flo-bestiary-row-meta flo-mono">
{String(b.stats?.["HP"] ?? "—")}
</div>
</div>
<div className="flo-bestiary-cr">CR {String(b.stats?.["Challenge"] ?? "?")}</div>
</li>
))}
</ul>
</aside>
<div />
</div>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
"use client";
import { use, useEffect, useState } from "react";
import { RequireRole } from "@/components/RequireRole";
import { EditorScreen } from "@/components/EditorScreen";
import { api } from "@/lib/client";
import type { EntryDTO } from "@/lib/serialize";
export default function EditEntryPage({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = use(params);
const [entry, setEntry] = useState<EntryDTO | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
api<{ entry: EntryDTO }>(`/api/entries/${encodeURIComponent(slug)}`)
.then((r) => setEntry(r.entry))
.catch((e) => setError(e.message));
}, [slug]);
return (
<RequireRole role="dm">
{error ? (
<div className="flo-screen">
<div className="flo-empty-card">{error}</div>
</div>
) : entry ? (
<EditorScreen existing={entry} />
) : (
<div className="flo-screen" />
)}
</RequireRole>
);
}
+12
View File
@@ -0,0 +1,12 @@
"use client";
import { RequireRole } from "@/components/RequireRole";
import { EditorScreen } from "@/components/EditorScreen";
export default function NewEntryPage() {
return (
<RequireRole role="dm">
<EditorScreen />
</RequireRole>
);
}
+55
View File
@@ -0,0 +1,55 @@
import type { Metadata } from "next";
import "@/styles/globals.css";
import { getOrCreateWorld } from "@/lib/world";
import { getSession } from "@/lib/session";
import { ClientProviders } from "@/components/ClientProviders";
import { RootBody } from "@/components/RootBody";
export const metadata: Metadata = {
title: "Codex of Florthoritania",
description: "An archive for tabletop worlds — store, link, and reveal.",
};
export const dynamic = "force-dynamic";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const world = await getOrCreateWorld();
const session = await getSession();
return (
<html lang="en" data-theme={world.theme}>
<head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600&family=Spectral:ital,wght@0,300;0,400;0,500;0,600;1,400;1,500&family=JetBrains+Mono:wght@400;500&display=swap"
/>
<style>{`:root{--brass:${world.accent};}`}</style>
</head>
<body>
<ClientProviders
initialWorld={{
name: world.name,
tagline: world.tagline,
era: world.era,
theme: world.theme,
accent: world.accent,
showFog: world.showFog,
}}
initialSession={{
userId: session.userId ?? null,
username: session.username ?? null,
role: session.role ?? null,
}}
>
<RootBody>{children}</RootBody>
</ClientProviders>
</body>
</html>
);
}
+94
View File
@@ -0,0 +1,94 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useFlorte } from "@/components/ClientProviders";
export default function LoginPage() {
const router = useRouter();
const { refresh, t } = useFlorte();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [needsSetup, setNeedsSetup] = useState(false);
useEffect(() => {
fetch("/api/auth/setup")
.then((r) => r.json())
.then((d) => {
if (d.needsSetup) {
setNeedsSetup(true);
router.replace("/setup");
}
});
}, [router]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setBusy(true);
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
setBusy(false);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
setError(j.error ?? "Login failed");
return;
}
await refresh();
const j = await res.json();
router.push(j.role === "player" ? "/portal" : "/");
router.refresh();
};
if (needsSetup) return null;
return (
<div className="flo-shell">
<form className="flo-auth-card" onSubmit={submit}>
<h1>{t("auth_welcome_back")}</h1>
<p className="flo-auth-sub">{t("auth_welcome_back_sub")}</p>
{error && <div className="flo-error">{error}</div>}
<div className="flo-auth-row">
<label>{t("auth_username")}</label>
<input
className="flo-input"
value={username}
onChange={(e) => setUsername(e.target.value)}
autoFocus
required
/>
</div>
<div className="flo-auth-row">
<label>{t("auth_password")}</label>
<input
className="flo-input"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<div className="flo-auth-actions">
<button type="submit" className="flo-btn" disabled={busy}>
{busy ? t("auth_signing_in") : t("auth_sign_in")}
</button>
<Link href="/setup" className="flo-link">
First-run setup →
</Link>
</div>
<div className="flo-auth-foot">
{t("auth_no_account")}{" "}
<Link href="/register" className="flo-link">
{t("auth_register")} →
</Link>
</div>
</form>
</div>
);
}
+609
View File
@@ -0,0 +1,609 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { RequireRole } from "@/components/RequireRole";
import { KindPill, VisibilityBadge } from "@/components/Pills";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import { KIND_ORDER, KINDS, type KindId, isKind } from "@/lib/kinds";
import type { EntryDTO } from "@/lib/serialize";
type Pin = {
id: string;
x: number;
y: number;
label: string;
kind: string;
entrySlug: string | null;
layerId: string | null;
};
type LayerSummary = {
id: string;
name: string;
width: number;
height: number;
isDefault: boolean;
order: number;
};
type LayerFull = LayerSummary & { imageData: string };
const PROCEDURAL_LAYER: LayerFull = {
id: "__procedural__",
name: "Procedural",
width: 1000,
height: 700,
isDefault: true,
order: 0,
imageData: "",
};
export default function Page() {
return (
<RequireRole>
<MapScreen />
</RequireRole>
);
}
function MapScreen() {
const { world, session } = useFlorte();
const [layers, setLayers] = useState<LayerSummary[]>([]);
const [activeLayerId, setActiveLayerId] = useState<string | null>(null);
const [activeLayer, setActiveLayer] = useState<LayerFull | null>(null);
const [pins, setPins] = useState<Pin[]>([]);
const [active, setActive] = useState<string | null>(null);
const [showFog, setShowFog] = useState(world.showFog);
const [adding, setAdding] = useState(false);
const [editPins, setEditPins] = useState(false);
const [draft, setDraft] = useState<{ x: number; y: number } | null>(null);
const [draftLabel, setDraftLabel] = useState("");
const [draftKind, setDraftKind] = useState<KindId>("location");
const [draftSlug, setDraftSlug] = useState<string>("");
const [entries, setEntries] = useState<EntryDTO[]>([]);
const canvasRef = useRef<HTMLDivElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
// Pan & zoom state
const [scale, setScale] = useState(1);
const [tx, setTx] = useState(0);
const [ty, setTy] = useState(0);
const panRef = useRef<{ active: boolean; sx: number; sy: number; tx: number; ty: number; moved: boolean }>({
active: false, sx: 0, sy: 0, tx: 0, ty: 0, moved: false,
});
// Pin drag state (DM, edit-pins mode)
const dragRef = useRef<{ id: string | null; moved: boolean }>({ id: null, moved: false });
// Bootstrap
useEffect(() => {
(async () => {
const ls = await api<LayerSummary[]>("/api/layers");
setLayers(ls);
const def = ls.find((l) => l.isDefault) ?? ls[0];
setActiveLayerId(def?.id ?? null);
})();
api<EntryDTO[]>("/api/entries").then(setEntries).catch(() => {});
}, []);
// Load full layer (with imageData) when active changes
useEffect(() => {
if (!activeLayerId) {
setActiveLayer(PROCEDURAL_LAYER);
return;
}
api<LayerFull>(`/api/layers/${activeLayerId}`).then(setActiveLayer).catch(() => {
setActiveLayer(PROCEDURAL_LAYER);
});
}, [activeLayerId]);
// Reload pins when layer changes
useEffect(() => {
if (activeLayerId === null) {
api<Pin[]>("/api/pins?layerId=null").then(setPins);
} else {
api<Pin[]>(`/api/pins?layerId=${encodeURIComponent(activeLayerId)}`).then(setPins);
}
}, [activeLayerId]);
useEffect(() => setShowFog(world.showFog), [world.showFog]);
const reloadPins = async () => {
const url = activeLayerId === null
? "/api/pins?layerId=null"
: `/api/pins?layerId=${encodeURIComponent(activeLayerId)}`;
setPins(await api<Pin[]>(url));
};
// ── Pan/zoom ────────────────────────────────────────────────────────────
const onWheel = (e: React.WheelEvent<HTMLDivElement>) => {
e.preventDefault();
const rect = canvasRef.current!.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
// World-space point under cursor
const wx = (mx - tx) / scale;
const wy = (my - ty) / scale;
const factor = e.deltaY > 0 ? 0.9 : 1.1;
const next = clamp(scale * factor, 0.4, 6);
// Keep cursor anchored
setTx(mx - wx * next);
setTy(my - wy * next);
setScale(next);
};
const onMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
// Don't pan if clicking on a pin in DM mode (handled by pin's own listener)
const target = e.target as HTMLElement;
if (target.closest(".flo-pin")) return;
panRef.current = { active: true, sx: e.clientX, sy: e.clientY, tx, ty, moved: false };
canvasRef.current?.classList.add("is-grabbing");
};
const onMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
const p = panRef.current;
if (!p.active) return;
const dx = e.clientX - p.sx;
const dy = e.clientY - p.sy;
if (Math.abs(dx) + Math.abs(dy) > 3) p.moved = true;
setTx(p.tx + dx);
setTy(p.ty + dy);
};
const onMouseUp = (e: React.MouseEvent<HTMLDivElement>) => {
const wasMoved = panRef.current.moved;
panRef.current.active = false;
canvasRef.current?.classList.remove("is-grabbing");
// If we're in pin-add mode and didn't drag, drop a pin at click point.
if (adding && !wasMoved) {
const rect = canvasRef.current!.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const wx = (mx - tx) / scale;
const wy = (my - ty) / scale;
const w = canvasRef.current!.clientWidth;
const h = canvasRef.current!.clientHeight;
const x = clamp(wx / w, 0, 1);
const y = clamp(wy / h, 0, 1);
setDraft({ x, y });
}
};
const onMouseLeave = () => {
panRef.current.active = false;
canvasRef.current?.classList.remove("is-grabbing");
};
const resetView = () => {
setScale(1);
setTx(0);
setTy(0);
};
// ── Pin drag (DM, editPins mode) ────────────────────────────────────────
const onPinPointerDown = (
e: React.PointerEvent<HTMLButtonElement>,
pin: Pin
) => {
if (!editPins) return;
e.stopPropagation();
e.preventDefault();
dragRef.current = { id: pin.id, moved: false };
(e.target as HTMLElement).setPointerCapture?.(e.pointerId);
};
const onPinPointerMove = (
e: React.PointerEvent<HTMLButtonElement>,
pin: Pin
) => {
if (dragRef.current.id !== pin.id) return;
const rect = canvasRef.current!.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const wx = (mx - tx) / scale;
const wy = (my - ty) / scale;
const w = canvasRef.current!.clientWidth;
const h = canvasRef.current!.clientHeight;
const nx = clamp(wx / w, 0, 1);
const ny = clamp(wy / h, 0, 1);
if (Math.abs(nx - pin.x) + Math.abs(ny - pin.y) > 0.001) {
dragRef.current.moved = true;
setPins((arr) => arr.map((p) => (p.id === pin.id ? { ...p, x: nx, y: ny } : p)));
}
};
const onPinPointerUp = async (
e: React.PointerEvent<HTMLButtonElement>,
pin: Pin
) => {
if (dragRef.current.id !== pin.id) return;
const moved = dragRef.current.moved;
dragRef.current = { id: null, moved: false };
if (moved) {
const cur = pins.find((p) => p.id === pin.id) ?? pin;
await api(`/api/pins/${pin.id}`, {
method: "PATCH",
body: JSON.stringify({ x: cur.x, y: cur.y }),
});
} else {
setActive(pin.id);
}
};
const savePin = async () => {
if (!draft) return;
const label = draftLabel.trim();
if (!label) return;
await api("/api/pins", {
method: "POST",
body: JSON.stringify({
x: draft.x,
y: draft.y,
label,
kind: draftKind,
entrySlug: draftSlug || null,
layerId: activeLayerId ?? null,
}),
});
setDraft(null);
setDraftLabel("");
setDraftSlug("");
setAdding(false);
await reloadPins();
};
const removePin = async (id: string) => {
if (!confirm("Remove this pin?")) return;
await api(`/api/pins/${id}`, { method: "DELETE" });
setActive(null);
await reloadPins();
};
const moveToLayer = async (id: string, layerId: string | null) => {
await api(`/api/pins/${id}`, { method: "PATCH", body: JSON.stringify({ layerId }) });
await reloadPins();
};
const activePin = pins.find((p) => p.id === active);
const layerWidth = activeLayer?.width ?? 1000;
const layerHeight = activeLayer?.height ?? 700;
// Build layer tabs (procedural always available)
const layerTabs = useMemo(() => {
const arr: { id: string | null; name: string }[] = [
{ id: null, name: "Procedural" },
];
for (const l of layers) arr.push({ id: l.id, name: l.name });
return arr;
}, [layers]);
return (
<div className="flo-screen flo-map">
<div className="flo-map-controls">
<div className="flo-map-layers">
<span className="flo-mono flo-mono-dim">
{pins.length} pin{pins.length === 1 ? "" : "s"}
</span>
<span className="flo-mono flo-mono-dim">·</span>
<span className="flo-mono flo-mono-dim">
zoom {scale.toFixed(2)}×
</span>
</div>
<div className="flo-map-toggles">
{session.role === "dm" && (
<>
<button
className={"flo-chip" + (adding ? " is-active" : "")}
onClick={() => {
setAdding((a) => !a);
setEditPins(false);
setDraft(null);
}}
>
<span className="flo-glyph">+</span> {adding ? "Cancel" : "Drop pin"}
</button>
<button
className={"flo-chip" + (editPins ? " is-active" : "")}
onClick={() => {
setEditPins((e) => !e);
setAdding(false);
}}
title="Drag pins to reposition them"
>
<span className="flo-glyph">✎</span> Move pins
</button>
<Link href="/admin/maps" className="flo-chip">
<span className="flo-glyph">▤</span> Layers…
</Link>
</>
)}
<button
className={"flo-chip" + (showFog ? " is-active" : "")}
onClick={() => setShowFog(!showFog)}
>
<span className="flo-glyph">☁</span> Fog of war
</button>
</div>
</div>
<div
ref={canvasRef}
className={
"flo-map-canvas" +
(adding ? " is-pinning" : "") +
(editPins ? "" : "")
}
onWheel={onWheel}
onMouseDown={onMouseDown}
onMouseMove={onMouseMove}
onMouseUp={onMouseUp}
onMouseLeave={onMouseLeave}
>
<div
ref={stageRef}
className="flo-map-stage"
style={{
transform: `translate(${tx}px, ${ty}px) scale(${scale})`,
}}
>
{activeLayer && activeLayer.imageData ? (
<img
src={activeLayer.imageData}
alt={activeLayer.name}
className="flo-map-img"
draggable={false}
style={{
width: "100%",
height: "100%",
aspectRatio: `${layerWidth} / ${layerHeight}`,
}}
/>
) : (
<ProceduralBg />
)}
{showFog && (
<div className="flo-map-fog" style={{ position: "absolute", inset: 0 }}>
<div className="flo-fog-blob" style={{ left: "65%", top: "70%", width: "30%", height: "35%" }} />
<div className="flo-fog-blob" style={{ left: "5%", top: "5%", width: "20%", height: "25%" }} />
</div>
)}
{pins.map((p) => {
const k = isKind(p.kind) ? KINDS[p.kind] : KINDS.location;
const isA = active === p.id;
return (
<button
key={p.id}
className={
"flo-pin" +
(isA ? " is-active" : "") +
(dragRef.current.id === p.id ? " is-dragging" : "")
}
style={{
left: `${p.x * 100}%`,
top: `${p.y * 100}%`,
["--k-color" as string]: k.color,
} as React.CSSProperties}
onPointerDown={(e) => onPinPointerDown(e, p)}
onPointerMove={(e) => onPinPointerMove(e, p)}
onPointerUp={(e) => onPinPointerUp(e, p)}
onClick={(e) => {
if (editPins) return;
e.stopPropagation();
setActive(p.id);
}}
>
<span className="flo-pin-dot" />
<span className="flo-pin-pulse" />
<span className="flo-pin-label" style={{ transform: `scale(${1 / scale})`, transformOrigin: "left center" }}>
{p.label}
</span>
</button>
);
})}
{draft && (
<div
className="flo-pin is-active"
style={{
left: `${draft.x * 100}%`,
top: `${draft.y * 100}%`,
["--k-color" as string]: KINDS[draftKind].color,
pointerEvents: "none",
} as React.CSSProperties}
>
<span className="flo-pin-dot" />
<span className="flo-pin-pulse" />
</div>
)}
</div>
{/* Layer switcher (top-left) */}
<div className="flo-map-layerbar">
{layerTabs.map((t) => (
<button
key={t.id ?? "__procedural__"}
className={"flo-chip" + (activeLayerId === t.id ? " is-active" : "")}
onClick={() => {
setActiveLayerId(t.id);
setActive(null);
setDraft(null);
resetView();
}}
>
{t.name}
</button>
))}
</div>
{/* Zoom controls (bottom-left) */}
<div className="flo-map-zoombar">
<button className="flo-chip" onClick={() => setScale((s) => clamp(s * 1.2, 0.4, 6))}>+</button>
<button className="flo-chip" onClick={() => setScale((s) => clamp(s / 1.2, 0.4, 6))}>−</button>
<button className="flo-chip" onClick={resetView}>reset</button>
</div>
{activePin && !editPins && (
<div className="flo-map-card" onClick={(e) => e.stopPropagation()} onMouseDown={(e) => e.stopPropagation()}>
<div className="flo-map-card-head">
<KindPill kind={activePin.kind} small />
{activePin.entrySlug ? (
<VisibilityBadge isPublic={true} />
) : (
<span className="flo-mono flo-mono-dim">unlinked</span>
)}
</div>
<h3 className="flo-map-card-title">{activePin.label}</h3>
<div className="flo-map-card-coords flo-mono">
x {activePin.x.toFixed(3)} · y {activePin.y.toFixed(3)}
</div>
<div className="flo-map-card-actions">
{activePin.entrySlug && (
<Link href={`/article/${activePin.entrySlug}`} className="flo-btn">
Open inscription ›
</Link>
)}
{session.role === "dm" && (
<>
<select
className="flo-select"
value={activePin.layerId ?? ""}
onChange={(e) =>
moveToLayer(activePin.id, e.target.value || null)
}
>
<option value="">(procedural)</option>
{layers.map((l) => (
<option key={l.id} value={l.id}>{l.name}</option>
))}
</select>
<button
className="flo-btn flo-btn-ghost flo-btn-danger"
onClick={() => removePin(activePin.id)}
>
Remove pin
</button>
</>
)}
</div>
</div>
)}
{draft && (
<div className="flo-map-card" style={{ top: "auto", bottom: 18 }}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}>
<div className="flo-map-card-head">
<span className="flo-mono flo-mono-dim">New pin</span>
</div>
<input
className="flo-input"
placeholder="Label (e.g. Umbervale)"
value={draftLabel}
onChange={(e) => setDraftLabel(e.target.value)}
autoFocus
/>
<div style={{ display: "flex", gap: 8, margin: "10px 0" }}>
<select
className="flo-select"
value={draftKind}
onChange={(e) => setDraftKind(e.target.value as KindId)}
>
{KIND_ORDER.map((k) => (
<option key={k} value={k}>
{KINDS[k].label}
</option>
))}
</select>
<select
className="flo-select"
value={draftSlug}
onChange={(e) => setDraftSlug(e.target.value)}
style={{ flex: 1 }}
>
<option value="">— link to entry (optional) —</option>
{entries.map((e) => (
<option key={e.slug} value={e.slug}>
{e.title}
</option>
))}
</select>
</div>
<div className="flo-map-card-actions">
<button className="flo-btn" onClick={savePin}>
Save pin
</button>
<button
className="flo-btn flo-btn-ghost"
onClick={() => {
setDraft(null);
setDraftLabel("");
}}
>
Cancel
</button>
</div>
</div>
)}
<div className="flo-map-legend">
<div className="flo-mono flo-mono-dim">Legend</div>
{(["location", "faction", "npc", "lore"] as const).map((k) => (
<div key={k} className="flo-legend-row">
<span className="flo-legend-dot" style={{ background: KINDS[k].color }} />
<span>{KINDS[k].label}</span>
</div>
))}
</div>
</div>
</div>
);
}
function clamp(n: number, lo: number, hi: number) {
return Math.max(lo, Math.min(hi, n));
}
function ProceduralBg() {
return (
<svg
viewBox="0 0 1000 700"
preserveAspectRatio="xMidYMid slice"
className="flo-map-svg"
style={{ width: "100%", height: "100%", display: "block" }}
>
<defs>
<pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
<path d="M 40 0 L 0 0 0 40" fill="none" stroke="rgba(217,180,106,.08)" strokeWidth=".5" />
</pattern>
<radialGradient id="vignette" cx="50%" cy="50%" r="60%">
<stop offset="0%" stopColor="rgba(0,0,0,0)" />
<stop offset="100%" stopColor="rgba(0,0,0,.55)" />
</radialGradient>
<radialGradient id="land" cx="40%" cy="45%" r="50%">
<stop offset="0%" stopColor="rgba(40,38,72,.7)" />
<stop offset="100%" stopColor="rgba(20,18,42,.95)" />
</radialGradient>
</defs>
<rect width="1000" height="700" fill="url(#land)" />
<rect width="1000" height="700" fill="url(#grid)" />
<polygon
points="120,180 260,90 460,140 620,80 820,140 920,260 880,460 740,560 540,620 320,560 180,460 100,320"
fill="rgba(72,86,140,.18)" stroke="rgba(217,180,106,.25)" strokeWidth="1"
/>
<polygon
points="280,520 360,480 520,520 600,580 540,640 380,620"
fill="rgba(72,86,140,.10)" stroke="rgba(217,180,106,.18)" strokeWidth=".7"
/>
<g transform="translate(900,560)" opacity=".55">
<circle r="36" fill="none" stroke="rgba(217,180,106,.5)" strokeWidth=".6" />
<circle r="22" fill="none" stroke="rgba(217,180,106,.3)" strokeWidth=".4" />
<line x1="0" y1="-36" x2="0" y2="36" stroke="rgba(217,180,106,.5)" strokeWidth=".5" />
<line x1="-36" y1="0" x2="36" y2="0" stroke="rgba(217,180,106,.5)" strokeWidth=".5" />
<text textAnchor="middle" y="-42" fill="rgba(217,180,106,.7)" fontSize="9" fontFamily="serif">N</text>
</g>
<rect width="1000" height="700" fill="url(#vignette)" />
</svg>
);
}
+297
View File
@@ -0,0 +1,297 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useFlorte } from "@/components/ClientProviders";
import { RequireRole } from "@/components/RequireRole";
import { KindPill } from "@/components/Pills";
import { api } from "@/lib/client";
import type { EntryDTO } from "@/lib/serialize";
import { KIND_ORDER, KINDS, type KindId } from "@/lib/kinds";
type Stats = { totalAll: number; totalPublic: number; byKind: Record<string, number> };
type Thread = { id: string; text: string; who: string; primary: boolean };
export default function HomePage() {
return (
<RequireRole>
<Dashboard />
</RequireRole>
);
}
function Dashboard() {
const { world, session } = useFlorte();
const router = useRouter();
const [stats, setStats] = useState<Stats | null>(null);
const [recent, setRecent] = useState<EntryDTO[]>([]);
const [threads, setThreads] = useState<Thread[]>([]);
const [newThread, setNewThread] = useState("");
const [adding, setAdding] = useState(false);
const reload = async () => {
const [s, r] = await Promise.all([
api<Stats>("/api/stats"),
api<EntryDTO[]>("/api/entries"),
]);
setStats(s);
setRecent(r.slice(0, 6));
if (session.role === "dm") {
try {
setThreads(await api<Thread[]>("/api/threads"));
} catch {
/* ignore */
}
}
};
useEffect(() => {
reload();
}, []);
// Player view: redirect to /portal
useEffect(() => {
if (session.role === "player") router.replace("/portal");
}, [session.role, router]);
if (session.role !== "dm") return null;
const statCards: { label: string; value: number }[] = stats
? [
{ label: "Articles", value: stats.totalAll },
{ label: "Locations", value: stats.byKind["location"] ?? 0 },
{ label: "Characters", value: stats.byKind["npc"] ?? 0 },
{ label: "Factions", value: stats.byKind["faction"] ?? 0 },
{ label: "Items", value: stats.byKind["item"] ?? 0 },
{ label: "Sessions", value: stats.byKind["session"] ?? 0 },
]
: [];
const visibilityPercent =
stats && stats.totalAll > 0
? Math.round((stats.totalPublic / stats.totalAll) * 100)
: 0;
const visibilityRows: { kind: KindId; label: string }[] = [
{ kind: "npc", label: "characters" },
{ kind: "location", label: "locations" },
{ kind: "faction", label: "factions" },
{ kind: "item", label: "items" },
];
const addThread = async (e: React.FormEvent) => {
e.preventDefault();
if (!newThread.trim()) return;
setAdding(true);
try {
await api("/api/threads", {
method: "POST",
body: JSON.stringify({ text: newThread.trim() }),
});
setNewThread("");
const t = await api<Thread[]>("/api/threads");
setThreads(t);
} finally {
setAdding(false);
}
};
const togglePrimary = async (t: Thread) => {
await api(`/api/threads/${t.id}`, {
method: "PATCH",
body: JSON.stringify({ primary: !t.primary }),
});
const fresh = await api<Thread[]>("/api/threads");
setThreads(fresh);
};
const resolveThread = async (t: Thread) => {
await api(`/api/threads/${t.id}`, {
method: "PATCH",
body: JSON.stringify({ resolved: true }),
});
const fresh = await api<Thread[]>("/api/threads");
setThreads(fresh);
};
return (
<div className="flo-screen flo-dashboard">
<header className="flo-hero">
{world.era && <div className="flo-hero-eyebrow">{world.era}</div>}
<h1 className="flo-hero-title">
The Codex of <em>{world.name || "Florthoritania"}</em>
</h1>
{world.tagline && <p className="flo-hero-tag">{world.tagline}</p>}
<div className="flo-hero-divider">
<span />
<span className="dot">✦</span>
<span />
</div>
</header>
<section className="flo-stats">
{statCards.map((s) => (
<div key={s.label} className="flo-stat">
<div className="flo-stat-value">{s.value}</div>
<div className="flo-stat-label">{s.label}</div>
</div>
))}
</section>
<div className="flo-grid-2">
<section className="flo-card">
<div className="flo-card-head">
<h2>Recent inscriptions</h2>
<Link className="flo-link" href="/search">
View all →
</Link>
</div>
{recent.length === 0 ? (
<div className="flo-empty-card">
No inscriptions yet. <Link className="flo-link" href="/editor">Begin one →</Link>
</div>
) : (
<ul className="flo-recent">
{recent.map((e) => (
<li
key={e.slug}
className="flo-recent-row"
onClick={() => router.push(`/article/${e.slug}`)}
>
<KindPill kind={e.kind} small />
<div className="flo-recent-body">
<div className="flo-recent-title">{e.title}</div>
<div className="flo-recent-sub">{e.subtitle || "—"}</div>
</div>
<div className="flo-recent-when">
<div>edited</div>
<div className="flo-mono">{relTime(e.updatedAt)}</div>
</div>
</li>
))}
</ul>
)}
</section>
<section className="flo-card flo-card-prep">
<div className="flo-card-head">
<h2>Quick actions</h2>
<span className="flo-tag">DM tools</span>
</div>
<ul className="flo-prep-list">
<li><span className="flo-prep-mark">◇</span> <Link className="flo-link" href="/editor">Inscribe a new entry</Link></li>
<li><span className="flo-prep-mark">◇</span> <Link className="flo-link" href="/map">Open the world map</Link></li>
<li><span className="flo-prep-mark">◇</span> <Link className="flo-link" href="/timeline">Edit the timeline</Link></li>
<li><span className="flo-prep-mark">◇</span> <Link className="flo-link" href="/portal">Preview the player portal</Link></li>
<li><span className="flo-prep-mark">◇</span> <Link className="flo-link" href="/settings">World & theme settings</Link></li>
</ul>
</section>
<section className="flo-card">
<div className="flo-card-head">
<h2>Open threads</h2>
<span className="flo-tag">{threads.length} unresolved</span>
</div>
<form
onSubmit={addThread}
style={{ display: "flex", gap: 8, marginBottom: 12 }}
>
<input
className="flo-input"
style={{ flex: 1 }}
placeholder="A loose thread to remember…"
value={newThread}
onChange={(e) => setNewThread(e.target.value)}
/>
<button className="flo-btn" type="submit" disabled={adding || !newThread.trim()}>
Add
</button>
</form>
{threads.length === 0 ? (
<div className="flo-empty-card">No open threads.</div>
) : (
<ul className="flo-threads">
{threads.map((t) => (
<li key={t.id} className={"flo-thread " + (t.primary ? "primary" : "")}>
<span className="flo-thread-mark">{t.primary ? "★" : "·"}</span>
<div>
<div className="flo-thread-text">{t.text}</div>
<div className="flo-thread-who">
<button className="flo-link" onClick={() => togglePrimary(t)}>
{t.primary ? "demote" : "mark primary"}
</button>
{" · "}
<button className="flo-link is-danger" onClick={() => resolveThread(t)}>
resolve
</button>
</div>
</div>
</li>
))}
</ul>
)}
</section>
<section className="flo-card">
<div className="flo-card-head">
<h2>Player visibility</h2>
<Link className="flo-link" href="/portal">Preview portal →</Link>
</div>
<div className="flo-vis-summary">
<div className="flo-vis-bar">
<div className="flo-vis-bar-fill" style={{ width: `${visibilityPercent}%` }} />
</div>
<div className="flo-vis-row">
<div>
<strong>{stats?.totalPublic ?? 0}</strong> articles revealed
</div>
<div className="flo-mono">
{visibilityPercent}% of {stats?.totalAll ?? 0}
</div>
</div>
</div>
<ul className="flo-vis-list">
{visibilityRows.map((r) => (
<li key={r.kind}>
<KindPill kind={r.kind} small /> {stats?.byKind[r.kind] ?? 0} {r.label}
</li>
))}
</ul>
</section>
</div>
<section className="flo-card" style={{ marginTop: 20 }}>
<div className="flo-card-head">
<h2>Volumes</h2>
</div>
<ul className="flo-vis-list">
{KIND_ORDER.map((k) => (
<li key={k}>
<KindPill kind={k} small />
<Link className="flo-link" href={`/search?kind=${k}`}>
{KINDS[k].label}
</Link>
<span className="flo-mono flo-mono-dim" style={{ marginLeft: "auto" }}>
{stats?.byKind[k] ?? 0}
</span>
</li>
))}
</ul>
</section>
</div>
);
}
function relTime(iso: string): string {
const d = new Date(iso);
const diffMs = Date.now() - d.getTime();
const m = Math.round(diffMs / 60000);
if (m < 1) return "just now";
if (m < 60) return `${m} min ago`;
const h = Math.round(m / 60);
if (h < 24) return `${h} hr ago`;
const days = Math.round(h / 24);
if (days < 30) return `${days}d ago`;
return d.toISOString().slice(0, 10);
}
+286
View File
@@ -0,0 +1,286 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { RequireRole } from "@/components/RequireRole";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import { KINDS, type KindId, isKind } from "@/lib/kinds";
import type { EntryDTO } from "@/lib/serialize";
type Quest = {
id: string;
title: string;
meta: string;
priority: string;
status: string;
isPublic: boolean;
};
type Party = {
id: string;
name: string;
klass: string;
hpCur: number;
hpMax: number;
color: string;
order: number;
};
type Journal = {
id: string;
who: string;
color: string;
text: string;
createdAt: string;
};
export default function Page() {
return (
<RequireRole>
<PortalScreen />
</RequireRole>
);
}
function PortalScreen() {
const router = useRouter();
const { world, session, refresh } = useFlorte();
const [revealed, setRevealed] = useState<EntryDTO[]>([]);
const [quests, setQuests] = useState<Quest[]>([]);
const [party, setParty] = useState<Party[]>([]);
const [journal, setJournal] = useState<Journal[]>([]);
const [draft, setDraft] = useState({ who: "", text: "", color: "#d9b46a" });
const [adding, setAdding] = useState(false);
const reload = async () => {
const [r, q, p, j] = await Promise.all([
api<EntryDTO[]>("/api/entries"),
api<Quest[]>("/api/quests"),
api<Party[]>("/api/party"),
api<Journal[]>("/api/journal"),
]);
setRevealed(r.filter((e) => e.isPublic).slice(0, 8));
setQuests(q.filter((x) => x.status !== "completed"));
setParty(p);
setJournal(j.slice(0, 8));
};
useEffect(() => {
reload().catch(() => {});
}, []);
const switchToDm = async () => {
await fetch("/api/auth/logout", { method: "POST" });
await refresh();
router.push("/login");
};
const addJournal = async () => {
if (!draft.who.trim() || !draft.text.trim()) return;
setAdding(true);
try {
await api("/api/journal", {
method: "POST",
body: JSON.stringify(draft),
});
setDraft({ who: "", text: "", color: "#d9b46a" });
await reload();
} finally {
setAdding(false);
}
};
return (
<div className="flo-screen flo-player flo-player-portal">
<div className="flo-player-banner">
<span className="flo-player-banner-mark">◐</span>
<div>
<strong>
{session.role === "dm" ? "Player view (preview)." : "Player view."}
</strong>{" "}
You are seeing the Codex as your party sees it. DM-only material is hidden.
{session.role === "dm" ? (
<Link className="flo-link" href="/" style={{ marginLeft: 12 }}>
Switch back to DM →
</Link>
) : (
<button className="flo-link" onClick={switchToDm} style={{ marginLeft: 12 }}>
Sign out →
</button>
)}
</div>
</div>
<header className="flo-player-hero">
<div className="flo-hero-eyebrow">{world.era || "Welcome, party"}</div>
<h1>
The Codex of <em>{world.name || "Florthoritania"}</em>
</h1>
{world.tagline && <p>{world.tagline}</p>}
</header>
<div className="flo-player-grid">
<section className="flo-card">
<div className="flo-card-head">
<h2>Recently revealed</h2>
<span className="flo-mono flo-mono-dim">{revealed.length} entries</span>
</div>
{revealed.length === 0 ? (
<div className="flo-empty-card">No revealed entries yet.</div>
) : (
<ul className="flo-revealed">
{revealed.map((e) => (
<li
key={e.slug}
className="flo-revealed-row"
onClick={() => router.push(`/article/${e.slug}`)}
>
<div className="flo-revealed-mark">
<span
className="flo-glyph"
style={{
color: isKind(e.kind) ? KINDS[e.kind as KindId].color : "#aaa",
}}
>
{isKind(e.kind) ? KINDS[e.kind as KindId].glyph : "❖"}
</span>
</div>
<div>
<div className="flo-revealed-title">{e.title}</div>
{e.summary && <div className="flo-revealed-excerpt">{e.summary}</div>}
<div className="flo-mono flo-mono-dim">
updated {new Date(e.updatedAt).toLocaleDateString()}
</div>
</div>
</li>
))}
</ul>
)}
</section>
<section className="flo-card">
<div className="flo-card-head">
<h2>The party</h2>
{session.role === "dm" && (
<Link href="/settings" className="flo-link">
Manage →
</Link>
)}
</div>
{party.length === 0 ? (
<div className="flo-empty-card">No party members yet.</div>
) : (
<ul className="flo-party">
{party.map((p) => {
const pct = p.hpMax > 0 ? Math.max(0, Math.min(100, (p.hpCur / p.hpMax) * 100)) : 0;
return (
<li key={p.id} className="flo-party-row">
<div
className="flo-party-portrait"
style={{ ["--c" as string]: p.color } as React.CSSProperties}
>
{p.name[0]?.toUpperCase()}
</div>
<div className="flo-party-body">
<div className="flo-party-name">{p.name}</div>
<div className="flo-party-cls flo-mono">{p.klass}</div>
</div>
<div className="flo-party-hp">
<div className="flo-mono">
HP {p.hpCur}/{p.hpMax}
</div>
<div className="flo-party-bar">
<div style={{ width: `${pct}%`, background: p.color }} />
</div>
</div>
</li>
);
})}
</ul>
)}
</section>
<section className="flo-card flo-card-quests">
<div className="flo-card-head">
<h2>Active quests</h2>
<span className="flo-tag">{quests.length} open</span>
</div>
{quests.length === 0 ? (
<div className="flo-empty-card">No active quests.</div>
) : (
<ul className="flo-quests">
{quests.map((q) => (
<li key={q.id}>
<div className="flo-quest-mark">{q.priority === "critical" ? "★" : "◇"}</div>
<div>
<div className="flo-quest-title">{q.title}</div>
{q.meta && <div className="flo-quest-meta">{q.meta}</div>}
</div>
</li>
))}
</ul>
)}
</section>
<section className="flo-card">
<div className="flo-card-head">
<h2>Party journal</h2>
</div>
<ul className="flo-journal">
{journal.length === 0 && (
<div className="flo-empty-card">
No journal entries yet. Add the first one below.
</div>
)}
{journal.map((j) => (
<li key={j.id} className="flo-journal-entry">
<div
className="flo-journal-portrait"
style={{ ["--c" as string]: j.color } as React.CSSProperties}
>
{j.who[0]?.toUpperCase()}
</div>
<div>
<div className="flo-journal-who">{j.who}</div>
<p>{j.text}</p>
<div className="flo-mono flo-mono-dim">
{new Date(j.createdAt).toLocaleString()}
</div>
</div>
</li>
))}
</ul>
<div style={{ marginTop: 14, display: "grid", gap: 8 }}>
<div style={{ display: "flex", gap: 8 }}>
<input
className="flo-input"
placeholder="Your name"
value={draft.who}
onChange={(e) => setDraft({ ...draft, who: e.target.value })}
style={{ width: 160 }}
/>
<input
type="color"
value={draft.color}
onChange={(e) => setDraft({ ...draft, color: e.target.value })}
style={{ width: 40, height: 38, border: "1px solid var(--line)", background: "transparent", borderRadius: 6 }}
/>
</div>
<textarea
className="flo-textarea"
placeholder="Note something the party should remember…"
value={draft.text}
onChange={(e) => setDraft({ ...draft, text: e.target.value })}
/>
<div>
<button className="flo-btn" onClick={addJournal} disabled={adding}>
Add to journal
</button>
</div>
</div>
</section>
</div>
</div>
);
}
+135
View File
@@ -0,0 +1,135 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { useFlorte } from "@/components/ClientProviders";
export default function RegisterPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { refresh, t } = useFlorte();
const [code, setCode] = useState(searchParams.get("code") ?? "");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [preview, setPreview] = useState<{
campaignName: string | null;
role: string;
} | null>(null);
// Auto-preview invite when code is pre-filled
useEffect(() => {
const prefilledCode = searchParams.get("code");
if (prefilledCode) {
setCode(prefilledCode);
previewCode(prefilledCode);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const previewCode = async (c: string) => {
if (!c.trim()) { setPreview(null); return; }
const res = await fetch("/api/invites/redeem", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code: c.trim() }),
});
if (res.ok) {
const d = await res.json();
setPreview({ campaignName: d.campaignName, role: d.role });
setError(null);
} else {
const d = await res.json().catch(() => ({}));
setPreview(null);
setError(d.error ?? "Invalid invite code");
}
};
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setBusy(true);
const res = await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password, code: code.trim() }),
});
setBusy(false);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
setError(j.error ?? "Registration failed");
return;
}
await refresh();
const j = await res.json();
router.push(j.role === "player" ? "/portal" : "/");
router.refresh();
};
return (
<div className="flo-shell">
<form className="flo-auth-card" onSubmit={submit}>
<h1>{t("auth_register")}</h1>
<p className="flo-auth-sub">{t("auth_join_sub")}</p>
{error && <div className="flo-error">{error}</div>}
<div className="flo-auth-row">
<label>{t("auth_invite_code")}</label>
<input
className="flo-input flo-input-mono"
value={code}
onChange={(e) => setCode(e.target.value)}
onBlur={() => previewCode(code)}
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
required
/>
</div>
{preview && (
<div className="flo-success" style={{ fontSize: 12 }}>
{preview.campaignName
? `Joining campaign: ${preview.campaignName} as ${preview.role}`
: `Joining as ${preview.role}`}
</div>
)}
<div className="flo-auth-row">
<label>{t("auth_username")}</label>
<input
className="flo-input"
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
required
/>
</div>
<div className="flo-auth-row">
<label>{t("auth_password")}</label>
<input
className="flo-input"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="new-password"
required
/>
</div>
<div className="flo-auth-actions">
<button type="submit" className="flo-btn" disabled={busy}>
{busy ? t("auth_registering") : t("auth_register")}
</button>
</div>
<div className="flo-auth-foot">
{t("auth_have_account")}{" "}
<Link href="/login" className="flo-link">
{t("auth_sign_in")} →
</Link>
</div>
</form>
</div>
);
}
+157
View File
@@ -0,0 +1,157 @@
"use client";
import { Suspense, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { RequireRole } from "@/components/RequireRole";
import { KindPill, VisibilityBadge } from "@/components/Pills";
import { api } from "@/lib/client";
import { KIND_ORDER, KINDS } from "@/lib/kinds";
import type { EntryDTO } from "@/lib/serialize";
export default function Page() {
return (
<RequireRole>
<Suspense fallback={null}>
<SearchScreen />
</Suspense>
</RequireRole>
);
}
type Sort = "recent" | "alpha" | "linked";
function SearchScreen() {
const router = useRouter();
const params = useSearchParams();
const initialKind = params?.get("kind") ?? "all";
const [kind, setKind] = useState<string>(initialKind);
const [q, setQ] = useState("");
const [rows, setRows] = useState<EntryDTO[]>([]);
const [loading, setLoading] = useState(true);
const [sort, setSort] = useState<Sort>("recent");
useEffect(() => {
setLoading(true);
const sp = new URLSearchParams();
if (kind && kind !== "all") sp.set("kind", kind);
if (q.trim()) sp.set("q", q.trim());
api<EntryDTO[]>("/api/entries?" + sp.toString())
.then((r) => setRows(r))
.finally(() => setLoading(false));
}, [kind, q]);
// Update URL when kind changes (preserve shareable filter URLs)
useEffect(() => {
const sp = new URLSearchParams(params?.toString() ?? "");
if (kind === "all") sp.delete("kind");
else sp.set("kind", kind);
const next = "/search" + (sp.toString() ? `?${sp.toString()}` : "");
if (typeof window !== "undefined" && window.location.search !== `?${sp.toString()}`) {
router.replace(next);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [kind]);
const sorted = useMemo(() => {
const xs = rows.slice();
if (sort === "alpha") xs.sort((a, b) => a.title.localeCompare(b.title));
else if (sort === "recent")
xs.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
return xs;
}, [rows, sort]);
const tabs: [string, string][] = [
["all", "All"],
...KIND_ORDER.map((k) => [k, KINDS[k].label] as [string, string]),
];
return (
<div className="flo-screen flo-search">
<div className="flo-search-bar">
<span className="flo-search-glyph">⌕</span>
<input
autoFocus
className="flo-search-input"
placeholder="Search the codex…"
value={q}
onChange={(e) => setQ(e.target.value)}
/>
{q && (
<button className="flo-search-clear" onClick={() => setQ("")}>
clear
</button>
)}
</div>
<div className="flo-kind-tabs">
{tabs.map(([k, label]) => (
<button
key={k}
className={"flo-kind-tab" + (kind === k ? " is-active" : "")}
onClick={() => setKind(k)}
>
{k !== "all" && (
<span className="flo-glyph" style={{ color: KINDS[k as keyof typeof KINDS].color }}>
{KINDS[k as keyof typeof KINDS].glyph}
</span>
)}
{label}
</button>
))}
</div>
<div className="flo-search-meta">
<span className="flo-mono">
{sorted.length} result{sorted.length === 1 ? "" : "s"}
</span>
<div className="flo-search-sort">
<span>Sort:</span>
<button
className={"flo-chip" + (sort === "recent" ? " is-active" : "")}
onClick={() => setSort("recent")}
>
Recent
</button>
<button
className={"flo-chip" + (sort === "alpha" ? " is-active" : "")}
onClick={() => setSort("alpha")}
>
Alphabetical
</button>
</div>
</div>
{loading ? (
<div className="flo-empty">Reading the stacks…</div>
) : sorted.length === 0 ? (
<div className="flo-empty">
No inscriptions match. <Link href="/editor" className="flo-link">Inscribe one →</Link>
</div>
) : (
<div className="flo-results">
{sorted.map((e) => (
<Link key={e.slug} className="flo-result" href={`/article/${e.slug}`}>
<div className="flo-result-head">
<KindPill kind={e.kind} small />
<VisibilityBadge isPublic={e.isPublic} />
</div>
<div className="flo-result-title">{e.title}</div>
{e.subtitle && <div className="flo-result-sub">{e.subtitle}</div>}
{e.summary && <div className="flo-result-summary">{e.summary}</div>}
{e.tags.length > 0 && (
<div className="flo-result-tags">
{e.tags.slice(0, 3).map((t) => (
<span key={t} className="flo-tag-sm">
#{t}
</span>
))}
</div>
)}
</Link>
))}
</div>
)}
</div>
);
}
+239
View File
@@ -0,0 +1,239 @@
"use client";
import { use, useEffect, useState } from "react";
import Link from "next/link";
import { RequireRole } from "@/components/RequireRole";
import { KindPill, VisibilityBadge } from "@/components/Pills";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import type { EntryDTO } from "@/lib/serialize";
type Beat = {
id: string;
time: string;
title: string;
text: string;
flag: string;
order: number;
};
type ApiResp = {
entry: EntryDTO;
backlinks: { slug: string; title: string; kind: string }[];
};
export default function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = use(params);
return (
<RequireRole>
<SessionScreen slug={slug} />
</RequireRole>
);
}
function SessionScreen({ slug }: { slug: string }) {
const { session } = useFlorte();
const [data, setData] = useState<ApiResp | null>(null);
const [beats, setBeats] = useState<Beat[]>([]);
const [draft, setDraft] = useState({ time: "", title: "", text: "", flag: "" });
const [busy, setBusy] = useState(false);
const reload = async () => {
const [d, b] = await Promise.all([
api<ApiResp>(`/api/entries/${encodeURIComponent(slug)}`),
api<Beat[]>(`/api/sessions/${encodeURIComponent(slug)}/beats`),
]);
setData(d);
setBeats(b);
};
useEffect(() => {
reload().catch(() => {});
}, [slug]);
if (!data) return <div className="flo-screen" />;
const e = data.entry;
const addBeat = async () => {
if (!draft.title.trim()) return;
setBusy(true);
try {
await api(`/api/sessions/${encodeURIComponent(slug)}/beats`, {
method: "POST",
body: JSON.stringify(draft),
});
setDraft({ time: "", title: "", text: "", flag: "" });
await reload();
} finally {
setBusy(false);
}
};
const removeBeat = async (id: string) => {
if (!confirm("Delete this beat?")) return;
await api(`/api/beats/${id}`, { method: "DELETE" });
await reload();
};
return (
<div className="flo-screen flo-session">
<header className="flo-session-head">
<div className="flo-session-eyebrow">
<KindPill kind="session" /> <VisibilityBadge isPublic={e.isPublic} />
<span className="flo-mono flo-mono-dim">
{new Date(e.createdAt).toLocaleString()}
</span>
</div>
<h1>{e.title}</h1>
{e.subtitle && <p className="flo-session-sub">{e.subtitle}</p>}
</header>
<div className="flo-session-grid">
<section className="flo-session-main">
{e.summary && (
<div className="flo-article-summary">
<span className="flo-pull-quote">“</span>
{e.summary}
</div>
)}
{beats.length === 0 ? (
<div className="flo-empty-card">
No beats recorded yet.
{session.role === "dm" && " Add the first one below."}
</div>
) : (
<ol className="flo-beats">
{beats.map((b, i) => (
<li
key={b.id}
className={"flo-beat" + (b.flag ? " is-flag-" + b.flag : "")}
>
<div className="flo-beat-time flo-mono">{b.time || "—"}</div>
<div className="flo-beat-marker">
<span className="flo-beat-dot" />
{i < beats.length - 1 && <span className="flo-beat-line" />}
</div>
<div className="flo-beat-body">
<div className="flo-beat-head">
<h3>{b.title}</h3>
{b.flag === "key" && <span className="flo-tag">key beat</span>}
{b.flag === "fight" && <span className="flo-tag is-fight">combat</span>}
{b.flag === "rp" && <span className="flo-tag is-rp">roleplay</span>}
{session.role === "dm" && (
<button
className="flo-link is-danger"
style={{ fontSize: 12 }}
onClick={() => removeBeat(b.id)}
>
delete
</button>
)}
</div>
{b.text && (
<p>
{renderInline(b.text)}
</p>
)}
</div>
</li>
))}
</ol>
)}
{session.role === "dm" && (
<div className="flo-side-section" style={{ marginTop: 24 }}>
<h3>Add beat</h3>
<div style={{ display: "grid", gap: 8 }}>
<div style={{ display: "flex", gap: 8 }}>
<input
className="flo-input flo-input-mono"
style={{ width: 120 }}
placeholder="00:00"
value={draft.time}
onChange={(ev) => setDraft({ ...draft, time: ev.target.value })}
/>
<input
className="flo-input"
placeholder="Beat title"
value={draft.title}
onChange={(ev) => setDraft({ ...draft, title: ev.target.value })}
style={{ flex: 1 }}
/>
<select
className="flo-select"
value={draft.flag}
onChange={(ev) => setDraft({ ...draft, flag: ev.target.value })}
>
<option value="">no flag</option>
<option value="rp">roleplay</option>
<option value="key">key beat</option>
<option value="fight">combat</option>
</select>
</div>
<textarea
className="flo-textarea"
placeholder="What happened. Use [[wikilinks]] freely."
value={draft.text}
onChange={(ev) => setDraft({ ...draft, text: ev.target.value })}
/>
<div>
<button className="flo-btn" onClick={addBeat} disabled={busy}>
Add beat
</button>
</div>
</div>
</div>
)}
</section>
<aside className="flo-session-side">
{data.backlinks.length > 0 && (
<div className="flo-side-section">
<h3>Linked entries</h3>
<ul className="flo-side-list">
{data.backlinks.map((b) => (
<li key={b.slug}>
<Link href={`/article/${b.slug}`} className="flo-backlink">
<KindPill kind={b.kind} small />
<span>{b.title}</span>
</Link>
</li>
))}
</ul>
</div>
)}
{session.role === "dm" && (
<div className="flo-side-section">
<h3>Manage</h3>
<Link href={`/editor/${e.slug}`} className="flo-btn flo-btn-ghost">
Edit session metadata
</Link>
</div>
)}
</aside>
</div>
</div>
);
}
function renderInline(text: string) {
const parts: (string | React.ReactNode)[] = [];
const re = /\[\[([^\]]+)\]\]/g;
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (m.index > last) parts.push(text.slice(last, m.index));
const target = m[1].trim();
const slug = target
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
parts.push(
<Link key={m.index} href={`/article/${slug}`} className="flo-wikilink">
{target}
</Link>
);
last = m.index + m[0].length;
}
if (last < text.length) parts.push(text.slice(last));
return parts;
}
+12
View File
@@ -0,0 +1,12 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
export default function SettingsRedirect() {
const router = useRouter();
useEffect(() => {
router.replace("/admin");
}, [router]);
return null;
}
+140
View File
@@ -0,0 +1,140 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useFlorte } from "@/components/ClientProviders";
export default function SetupPage() {
const router = useRouter();
const { refresh } = useFlorte();
const [needsSetup, setNeedsSetup] = useState<boolean | null>(null);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [worldName, setWorldName] = useState("");
const [tagline, setTagline] = useState("");
const [era, setEra] = useState("");
const [playerPassword, setPlayerPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
fetch("/api/auth/setup")
.then((r) => r.json())
.then((d) => {
setNeedsSetup(!!d.needsSetup);
if (!d.needsSetup) router.replace("/login");
});
}, [router]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setBusy(true);
const res = await fetch("/api/auth/setup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username,
password,
worldName,
tagline,
era,
playerPassword,
}),
});
setBusy(false);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
setError(j.error ?? "Setup failed");
return;
}
await refresh();
router.push("/");
router.refresh();
};
if (needsSetup === null) return <div className="flo-shell" />;
if (needsSetup === false) return null;
return (
<div className="flo-shell">
<form className="flo-auth-card" onSubmit={submit}>
<h1>Begin a new Codex</h1>
<p className="flo-auth-sub">
Create your DM account and inscribe the first stones of your world.
</p>
{error && <div className="flo-error">{error}</div>}
<div className="flo-auth-row">
<label>DM username</label>
<input
className="flo-input"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoFocus
/>
</div>
<div className="flo-auth-row">
<label>DM password (6+ chars)</label>
<input
className="flo-input"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={6}
/>
</div>
<div className="flo-auth-row">
<label>World name</label>
<input
className="flo-input"
value={worldName}
onChange={(e) => setWorldName(e.target.value)}
placeholder="e.g. Florthoritania"
/>
</div>
<div className="flo-auth-row">
<label>Tagline</label>
<input
className="flo-input"
value={tagline}
onChange={(e) => setTagline(e.target.value)}
placeholder="An archive of the sundered reaches"
/>
</div>
<div className="flo-auth-row">
<label>Era label</label>
<input
className="flo-input"
value={era}
onChange={(e) => setEra(e.target.value)}
placeholder="Year 1142 of the Sable Concord"
/>
</div>
<div className="flo-auth-row">
<label>Player portal password (optional)</label>
<input
className="flo-input"
type="password"
value={playerPassword}
onChange={(e) => setPlayerPassword(e.target.value)}
placeholder="Shared with your party"
/>
</div>
<div className="flo-auth-actions">
<button className="flo-btn" disabled={busy} type="submit">
{busy ? "Inscribing…" : "Open the Codex"}
</button>
</div>
</form>
</div>
);
}
+268
View File
@@ -0,0 +1,268 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { RequireRole } from "@/components/RequireRole";
import { useFlorte } from "@/components/ClientProviders";
import { api } from "@/lib/client";
import { KIND_ORDER, KINDS, type KindId } from "@/lib/kinds";
import type { EntryDTO } from "@/lib/serialize";
type Event = {
id: string;
year: number;
era: string;
label: string;
text: string;
kind: string;
entrySlug: string | null;
};
export default function Page() {
return (
<RequireRole>
<TimelineScreen />
</RequireRole>
);
}
function TimelineScreen() {
const { session } = useFlorte();
const [events, setEvents] = useState<Event[]>([]);
const [filter, setFilter] = useState<string>("all");
const [entries, setEntries] = useState<EntryDTO[]>([]);
const [adding, setAdding] = useState(false);
const [draft, setDraft] = useState<{
year: string;
era: string;
label: string;
text: string;
kind: KindId;
entrySlug: string;
}>({ year: "0", era: "", label: "", text: "", kind: "lore", entrySlug: "" });
const reload = async () => {
setEvents(await api<Event[]>("/api/timeline"));
};
useEffect(() => {
reload();
if (session.role === "dm") {
api<EntryDTO[]>("/api/entries").then(setEntries).catch(() => {});
}
}, [session.role]);
const filtered = useMemo(
() => (filter === "all" ? events : events.filter((e) => e.kind === filter)),
[events, filter]
);
const submit = async () => {
const y = parseInt(draft.year, 10);
if (!draft.label.trim() || Number.isNaN(y)) return;
await api("/api/timeline", {
method: "POST",
body: JSON.stringify({
year: y,
era: draft.era.trim(),
label: draft.label.trim(),
text: draft.text.trim(),
kind: draft.kind,
entrySlug: draft.entrySlug || null,
}),
});
setDraft({ year: "0", era: "", label: "", text: "", kind: "lore", entrySlug: "" });
setAdding(false);
await reload();
};
const remove = async (id: string) => {
if (!confirm("Delete this event?")) return;
await api(`/api/timeline/${id}`, { method: "DELETE" });
await reload();
};
const minYear = filtered.length ? Math.min(...filtered.map((e) => e.year)) : 0;
const maxYear = filtered.length ? Math.max(...filtered.map((e) => e.year)) : 1;
const span = Math.max(1, maxYear - minYear);
return (
<div className="flo-screen flo-timeline">
<div className="flo-timeline-head">
<h1>Timeline</h1>
<p>
A river of years. Click an event to open its inscription.
{session.role === "dm" && " Add events to mark what mattered."}
</p>
<div className="flo-timeline-filters">
<button
className={"flo-chip" + (filter === "all" ? " is-active" : "")}
onClick={() => setFilter("all")}
>
all
</button>
{KIND_ORDER.map((k) => (
<button
key={k}
className={"flo-chip" + (filter === k ? " is-active" : "")}
onClick={() => setFilter(k)}
>
<span className="flo-glyph" style={{ color: KINDS[k].color }}>
{KINDS[k].glyph}
</span>
{k}
</button>
))}
</div>
{session.role === "dm" && (
<div style={{ marginTop: 18 }}>
<button className="flo-btn" onClick={() => setAdding(true)}>
<span className="flo-glyph">✎</span> Add event
</button>
</div>
)}
</div>
{filtered.length === 0 ? (
<div className="flo-empty-card">No events recorded yet.</div>
) : (
<div className="flo-timeline-rail">
<div className="flo-timeline-line" />
{filtered.map((ev, i) => {
const k = KINDS[ev.kind as KindId] ?? KINDS.lore;
const side: "top" | "bot" = i % 2 === 0 ? "top" : "bot";
const left = ((ev.year - minYear) / span) * 100;
return (
<div
key={ev.id}
className={"flo-tl-event flo-tl-" + side}
style={{ left: `${left}%` }}
>
<div className="flo-tl-stem" />
{ev.entrySlug ? (
<Link href={`/article/${ev.entrySlug}`} className="flo-tl-card">
<Card ev={ev} k={k} />
</Link>
) : (
<div className="flo-tl-card" style={{ cursor: "default" }}>
<Card ev={ev} k={k} />
{session.role === "dm" && (
<button
className="flo-link is-danger"
style={{ marginTop: 6, fontSize: 12 }}
onClick={() => remove(ev.id)}
>
delete
</button>
)}
</div>
)}
</div>
);
})}
</div>
)}
{adding && (
<div className="flo-modal-back" onClick={() => setAdding(false)}>
<div className="flo-modal" onClick={(e) => e.stopPropagation()}>
<h2>New timeline event</h2>
<div className="flo-form-row">
<label>Year</label>
<input
className="flo-input flo-input-mono"
type="number"
value={draft.year}
onChange={(e) => setDraft({ ...draft, year: e.target.value })}
/>
</div>
<div className="flo-form-row">
<label>Era</label>
<input
className="flo-input"
value={draft.era}
onChange={(e) => setDraft({ ...draft, era: e.target.value })}
placeholder="e.g. Sable Concord"
/>
</div>
<div className="flo-form-row">
<label>Label</label>
<input
className="flo-input"
value={draft.label}
onChange={(e) => setDraft({ ...draft, label: e.target.value })}
/>
</div>
<div className="flo-form-row">
<label>Description</label>
<textarea
className="flo-textarea"
value={draft.text}
onChange={(e) => setDraft({ ...draft, text: e.target.value })}
/>
</div>
<div className="flo-form-row">
<label>Kind</label>
<select
className="flo-select"
value={draft.kind}
onChange={(e) => setDraft({ ...draft, kind: e.target.value as KindId })}
>
{KIND_ORDER.map((k) => (
<option key={k} value={k}>
{KINDS[k].label}
</option>
))}
</select>
</div>
<div className="flo-form-row">
<label>Linked entry</label>
<select
className="flo-select"
value={draft.entrySlug}
onChange={(e) => setDraft({ ...draft, entrySlug: e.target.value })}
>
<option value="">— none —</option>
{entries.map((e) => (
<option key={e.slug} value={e.slug}>
{e.title}
</option>
))}
</select>
</div>
<div className="flo-modal-actions">
<button className="flo-btn flo-btn-ghost" onClick={() => setAdding(false)}>
Cancel
</button>
<button className="flo-btn" onClick={submit}>
Add event
</button>
</div>
</div>
</div>
)}
</div>
);
}
function Card({
ev,
k,
}: {
ev: Event;
k: { color: string; glyph: string; label: string };
}) {
return (
<>
<div className="flo-tl-meta">
<span className="flo-tl-year flo-mono">
{ev.era ? `${ev.year} ${ev.era}` : ev.year}
</span>
<span className="flo-tl-glyph" style={{ color: k.color }}>
{k.glyph}
</span>
</div>
<div className="flo-tl-label">{ev.label}</div>
{ev.text && <div className="flo-tl-text">{ev.text}</div>}
</>
);
}
+36
View File
@@ -0,0 +1,36 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
const TABS: { href: string; label: string; match: RegExp | string }[] = [
{ href: "/admin", label: "World", match: /^\/admin\/?$/ },
{ href: "/admin/users", label: "Users", match: /^\/admin\/users/ },
{ href: "/admin/campaigns", label: "Campaigns", match: /^\/admin\/campaigns/ },
{ href: "/admin/party", label: "Party", match: /^\/admin\/party/ },
{ href: "/admin/quests", label: "Quests", match: /^\/admin\/quests/ },
{ href: "/admin/maps", label: "Maps", match: /^\/admin\/maps/ },
{ href: "/admin/import", label: "Import", match: /^\/admin\/import/ },
{ href: "/admin/api", label: "API", match: /^\/admin\/api/ },
];
export function AdminTabs() {
const pathname = usePathname() || "/admin";
return (
<div className="flo-session-tabs" style={{ marginBottom: 28 }}>
{TABS.map((t) => {
const active =
typeof t.match === "string" ? pathname === t.match : t.match.test(pathname);
return (
<Link
key={t.href}
href={t.href}
className={"flo-tab" + (active ? " is-active" : "")}
>
{t.label}
</Link>
);
})}
</div>
);
}
+46
View File
@@ -0,0 +1,46 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Sidebar } from "./Sidebar";
import { Topbar } from "./Topbar";
import { useFlorte } from "./ClientProviders";
export function AppShell({ children }: { children: React.ReactNode }) {
const { session } = useFlorte();
const [collapsed, setCollapsed] = useState(false);
const router = useRouter();
// Keyboard: "/" focuses search by routing to /search
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key !== "/") return;
const t = e.target as HTMLElement | null;
if (!t) return;
if (
t.tagName === "INPUT" ||
t.tagName === "TEXTAREA" ||
t.isContentEditable
)
return;
e.preventDefault();
router.push("/search");
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [router]);
if (!session.role) {
return <>{children}</>;
}
return (
<div className={"flo-app" + (collapsed ? " is-collapsed" : "")}>
<Sidebar collapsed={collapsed} />
<div className="flo-main">
<Topbar onToggleSidebar={() => setCollapsed((c) => !c)} />
{children}
</div>
</div>
);
}
+120
View File
@@ -0,0 +1,120 @@
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import {
DICTS,
detectLang,
setLangCookie,
type Dict,
type Lang,
} from "@/lib/i18n";
export type Role = "dm" | "player";
export type WorldState = {
name: string;
tagline: string;
era: string;
theme: string;
accent: string;
showFog: boolean;
};
export type SessionState = {
userId: string | null;
username: string | null;
role: Role | null;
};
type Ctx = {
world: WorldState;
setWorld: (w: WorldState) => void;
session: SessionState;
setSession: (s: SessionState) => void;
refresh: () => Promise<void>;
lang: Lang;
setLang: (l: Lang) => void;
t: (key: keyof Dict) => string;
};
const FlorteCtx = createContext<Ctx | null>(null);
export function useFlorte() {
const v = useContext(FlorteCtx);
if (!v) throw new Error("useFlorte must be used within ClientProviders");
return v;
}
export function ClientProviders({
children,
initialWorld,
initialSession,
}: {
children: ReactNode;
initialWorld: WorldState;
initialSession: SessionState;
}) {
const [world, setWorld] = useState<WorldState>(initialWorld);
const [session, setSession] = useState<SessionState>(initialSession);
const [lang, setLangState] = useState<Lang>("en");
useEffect(() => {
setLangState(detectLang());
}, []);
const setLang = useCallback((l: Lang) => {
setLangState(l);
setLangCookie(l);
}, []);
const t = useCallback(
(key: keyof Dict): string => DICTS[lang][key] as string,
[lang]
);
// Apply theme + accent to <html> on change
useEffect(() => {
const root = document.documentElement;
root.setAttribute("data-theme", world.theme);
root.style.setProperty("--brass", world.accent);
root.style.setProperty(
"--brass-bright",
world.accent.toLowerCase() === "#d9b46a" ? "#f0cf85" : world.accent
);
}, [world.theme, world.accent]);
const refresh = async () => {
const [me, w] = await Promise.all([
fetch("/api/auth/me").then((r) => r.json()),
fetch("/api/world").then((r) => r.json()),
]);
setSession({
userId: me.userId ?? null,
username: me.username ?? null,
role: me.role ?? null,
});
setWorld({
name: w.name,
tagline: w.tagline,
era: w.era,
theme: w.theme,
accent: w.accent,
showFog: w.showFog,
});
};
const value = useMemo(
() => ({ world, setWorld, session, setSession, refresh, lang, setLang, t }),
[world, session, lang, setLang, t]
);
return <FlorteCtx.Provider value={value}>{children}</FlorteCtx.Provider>;
}
+606
View File
@@ -0,0 +1,606 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { KindPill } from "@/components/Pills";
import { api } from "@/lib/client";
import { KIND_ORDER, KINDS, type KindId } from "@/lib/kinds";
import type { EntryDTO } from "@/lib/serialize";
type Mode = "rich" | "fields" | "stats";
const DEFAULT_FIELDS_BY_KIND: Partial<Record<KindId, [string, string][]>> = {
npc: [
["Race", ""],
["Pronouns", ""],
["Alignment", ""],
["Status", ""],
["Location", ""],
["Affiliation", ""],
],
pc: [
["Class & Level", ""],
["Player", ""],
["Race", ""],
["Background", ""],
],
location: [
["Region", ""],
["Population", ""],
["Government", ""],
["Climate", ""],
],
faction: [
["Headquarters", ""],
["Leader", ""],
["Allies", ""],
["Enemies", ""],
],
item: [
["Type", ""],
["Rarity", ""],
["Attunement", ""],
["Owner", ""],
],
deity: [
["Domain", ""],
["Symbol", ""],
["Alignment", ""],
],
beast: [
["Type", ""],
["Size", ""],
["Habitat", ""],
],
};
const STAT_KEYS = ["AC", "HP", "Speed", "STR", "DEX", "CON", "INT", "WIS", "CHA",
"Saving Throws", "Damage Resist.", "Condition Imm.", "Senses", "Languages", "Challenge"];
export function EditorScreen({ existing }: { existing?: EntryDTO }) {
const router = useRouter();
const isEdit = !!existing;
const [kind, setKind] = useState<KindId>((existing?.kind as KindId) ?? "npc");
const [title, setTitle] = useState(existing?.title ?? "");
const [subtitle, setSubtitle] = useState(existing?.subtitle ?? "");
const [summary, setSummary] = useState(existing?.summary ?? "");
const [body, setBody] = useState(existing?.body ?? "");
const [isPublic, setIsPublic] = useState(existing?.isPublic ?? false);
const [tags, setTags] = useState<string[]>(existing?.tags ?? []);
const [tagDraft, setTagDraft] = useState("");
const [fields, setFields] = useState<[string, string][]>(() => {
if (existing?.fields && Object.keys(existing.fields).length)
return Object.entries(existing.fields).map(([k, v]) => [k, String(v)]);
return DEFAULT_FIELDS_BY_KIND[(existing?.kind as KindId) ?? "npc"]?.slice() ?? [];
});
const [newFieldKey, setNewFieldKey] = useState("");
const [stats, setStats] = useState<[string, string][]>(() =>
Object.entries(existing?.stats ?? {}).map(([k, v]) => [k, String(v)])
);
const [abilities, setAbilities] = useState<{ name: string; text: string }[]>(
existing?.abilities ?? []
);
const [mode, setMode] = useState<Mode>("rich");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [suggestions, setSuggestions] = useState<EntryDTO[]>([]);
const [showSuggest, setShowSuggest] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// load suggestion candidates once
useEffect(() => {
api<EntryDTO[]>("/api/entries").then(setSuggestions).catch(() => {});
}, []);
// Caret-aware [[ suggestion popover
useEffect(() => {
const ta = textareaRef.current;
if (!ta) return;
const txt = body.slice(0, ta.selectionStart ?? body.length);
setShowSuggest(/\[\[$/.test(txt));
}, [body]);
const wordCount = useMemo(
() => (body.trim() ? body.trim().split(/\s+/).length : 0),
[body]
);
const linkCount = useMemo(() => {
const re = /\[\[([^\]]+)\]\]/g;
let n = 0;
while (re.exec(body) !== null) n++;
return n;
}, [body]);
const insertSuggestion = (title: string) => {
const ta = textareaRef.current;
if (!ta) return;
const start = ta.selectionStart ?? body.length;
const next = body.slice(0, start) + title + "]]" + body.slice(start);
setBody(next);
setShowSuggest(false);
requestAnimationFrame(() => {
ta.focus();
ta.selectionStart = ta.selectionEnd = start + title.length + 2;
});
};
const addField = () => {
if (!newFieldKey.trim()) return;
setFields((f) => [...f, [newFieldKey.trim(), ""]]);
setNewFieldKey("");
};
const updateField = (i: number, k: string, v: string) =>
setFields((f) => f.map((x, idx) => (idx === i ? [k, v] : x)));
const removeField = (i: number) =>
setFields((f) => f.filter((_, idx) => idx !== i));
const addTag = () => {
const t = tagDraft.trim().replace(/^#/, "").toLowerCase();
if (!t) return;
if (!tags.includes(t)) setTags((s) => [...s, t]);
setTagDraft("");
};
const setStat = (i: number, k: string, v: string) =>
setStats((s) => s.map((x, idx) => (idx === i ? [k, v] : x)));
const addStat = (k?: string) => setStats((s) => [...s, [k ?? "", ""]]);
const removeStat = (i: number) => setStats((s) => s.filter((_, idx) => idx !== i));
const addAbility = () => setAbilities((a) => [...a, { name: "", text: "" }]);
const removeAbility = (i: number) =>
setAbilities((a) => a.filter((_, idx) => idx !== i));
const submit = async () => {
if (!title.trim()) {
setError("Title required");
return;
}
setBusy(true);
setError(null);
const fieldsObj: Record<string, string> = {};
for (const [k, v] of fields) {
if (k.trim()) fieldsObj[k.trim()] = v;
}
const statsObj: Record<string, string> = {};
for (const [k, v] of stats) {
if (k.trim()) statsObj[k.trim()] = v;
}
const payload = {
kind,
title: title.trim(),
subtitle: subtitle.trim(),
summary: summary.trim(),
body,
isPublic,
tags,
fields: fieldsObj,
stats: statsObj,
abilities,
};
try {
if (isEdit && existing) {
await api(`/api/entries/${existing.slug}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
router.push(`/article/${existing.slug}`);
} else {
const created = await api<EntryDTO>("/api/entries", {
method: "POST",
body: JSON.stringify(payload),
});
router.push(`/article/${created.slug}`);
}
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const onDelete = async () => {
if (!existing) return;
if (!confirm(`Delete "${existing.title}"?`)) return;
await api(`/api/entries/${existing.slug}`, { method: "DELETE" });
router.push("/search");
};
return (
<div className="flo-screen flo-editor">
<div className="flo-editor-bar">
<div className="flo-editor-left">
<KindPill kind={kind} />
<select
className="flo-select"
value={kind}
onChange={(e) => setKind(e.target.value as KindId)}
>
{KIND_ORDER.map((k) => (
<option key={k} value={k}>
{KINDS[k].label}
</option>
))}
</select>
{isEdit && (
<span className="flo-mono flo-mono-dim">
editing · {existing!.slug}
</span>
)}
</div>
<div className="flo-editor-right">
{isEdit && (
<button className="flo-btn flo-btn-ghost flo-btn-danger" onClick={onDelete}>
Delete
</button>
)}
<button
className="flo-btn flo-btn-ghost"
onClick={() => router.back()}
>
Cancel
</button>
<button className="flo-btn" onClick={submit} disabled={busy}>
{busy ? "Saving…" : isEdit ? "Save changes" : "Publish to Codex"}
</button>
</div>
</div>
{error && <div className="flo-error">{error}</div>}
<div className="flo-editor-grid">
<div className="flo-editor-main">
<input
className="flo-editor-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Inscribe a title…"
/>
<input
className="flo-editor-sub"
value={subtitle}
onChange={(e) => setSubtitle(e.target.value)}
placeholder="Subtitle, epithet, or kenning…"
/>
<div className="flo-editor-toolbar">
<button
className="flo-tool"
type="button"
title="Heading"
onClick={() => insertAtCaret(textareaRef, body, setBody, "\n## Heading\n")}
>H</button>
<button
className="flo-tool"
type="button"
title="Quote"
onClick={() => insertAtCaret(textareaRef, body, setBody, "\n> ")}
>❝</button>
<button
className="flo-tool"
type="button"
title="Wikilink"
onClick={() => insertAtCaret(textareaRef, body, setBody, "[[")}
>
<span className="flo-mono">[[</span>
</button>
<button
className="flo-tool"
type="button"
title="Secret block"
onClick={() =>
insertAtCaret(
textareaRef,
body,
setBody,
"\n::secret\nDM-only paragraph here.\n::end\n"
)
}
>🜂</button>
<div className="flo-tool-sep" />
<button
className={"flo-tool flo-tool-mode " + (mode === "rich" ? "is-active" : "")}
onClick={() => setMode("rich")}
type="button"
>Body</button>
<button
className={"flo-tool flo-tool-mode " + (mode === "fields" ? "is-active" : "")}
onClick={() => setMode("fields")}
type="button"
>Fields</button>
{kind === "beast" && (
<button
className={"flo-tool flo-tool-mode " + (mode === "stats" ? "is-active" : "")}
onClick={() => setMode("stats")}
type="button"
>Stat block</button>
)}
</div>
{mode === "rich" && (
<>
<input
className="flo-input"
style={{ marginBottom: 12 }}
value={summary}
onChange={(e) => setSummary(e.target.value)}
placeholder="One-line summary (shown in the codex stack)"
/>
<div className="flo-editor-canvas">
<textarea
ref={textareaRef}
className="flo-editor-textarea"
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Inscribe the body. Use ## for headings, > for quotes, [[Link]] for cross-references, and ::secret …::end blocks for DM-only sections."
/>
{showSuggest && (
<div className="flo-suggest">
<div className="flo-suggest-hd">Link to existing entry</div>
{suggestions
.slice(0, 6)
.map((s) => (
<button
key={s.slug}
type="button"
className="flo-suggest-item"
onClick={() => insertSuggestion(s.title)}
>
<span className="flo-suggest-glyph">
{KINDS[s.kind as KindId]?.glyph ?? "❖"}
</span>
<span>{s.title}</span>
<span className="flo-mono flo-mono-dim">↵</span>
</button>
))}
{suggestions.length === 0 && (
<div className="flo-suggest-item is-new">
<span className="flo-suggest-glyph">+</span>
<span>No entries yet. Type a name and continue.</span>
</div>
)}
</div>
)}
</div>
<div className="flo-editor-meta">
<div>
<span className="flo-mono flo-mono-dim">words</span>
<span className="flo-mono">{wordCount}</span>
</div>
<div>
<span className="flo-mono flo-mono-dim">[[links]]</span>
<span className="flo-mono">{linkCount}</span>
</div>
</div>
</>
)}
{mode === "fields" && (
<div className="flo-side-section">
<h3>Structured fields</h3>
<div className="flo-fields-edit">
{fields.map(([k, v], i) => (
<div key={i} className="flo-field-row">
<input
className="flo-input flo-input-mono"
style={{ padding: "5px 8px", fontSize: 11 }}
value={k}
onChange={(e) => updateField(i, e.target.value, v)}
/>
<div style={{ display: "flex", gap: 6 }}>
<input
className="flo-field-val"
value={v}
onChange={(e) => updateField(i, k, e.target.value)}
/>
<button
className="flo-x"
type="button"
title="Remove"
onClick={() => removeField(i)}
>
×
</button>
</div>
</div>
))}
<div style={{ display: "flex", gap: 6, marginTop: 6 }}>
<input
className="flo-input flo-input-mono"
style={{ padding: "6px 8px", flex: 1, fontSize: 11 }}
placeholder="new field name…"
value={newFieldKey}
onChange={(e) => setNewFieldKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addField();
}
}}
/>
<button className="flo-add-field" type="button" onClick={addField}>
+ add field
</button>
</div>
</div>
</div>
)}
{mode === "stats" && (
<div className="flo-side-section">
<h3>Bestiary stat block</h3>
<div className="flo-fields-edit">
{stats.map(([k, v], i) => (
<div key={i} className="flo-field-row">
<input
className="flo-input flo-input-mono"
style={{ padding: "5px 8px", fontSize: 11 }}
value={k}
onChange={(e) => setStat(i, e.target.value, v)}
/>
<div style={{ display: "flex", gap: 6 }}>
<input
className="flo-field-val"
value={v}
onChange={(e) => setStat(i, k, e.target.value)}
/>
<button
className="flo-x"
type="button"
title="Remove"
onClick={() => removeStat(i)}
>
×
</button>
</div>
</div>
))}
<div style={{ display: "flex", gap: 4, flexWrap: "wrap", marginTop: 6 }}>
{STAT_KEYS.map((k) => (
<button
key={k}
type="button"
className="flo-chip"
onClick={() => addStat(k)}
>
+ {k}
</button>
))}
</div>
</div>
<h3 style={{ marginTop: 18 }}>Traits / Actions</h3>
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
{abilities.map((ab, i) => (
<div
key={i}
style={{ display: "flex", gap: 8, alignItems: "flex-start" }}
>
<input
className="flo-input"
style={{ width: 180, fontSize: 13 }}
placeholder="Name"
value={ab.name}
onChange={(e) =>
setAbilities((arr) =>
arr.map((x, idx) => (idx === i ? { ...x, name: e.target.value } : x))
)
}
/>
<textarea
className="flo-textarea"
style={{ flex: 1, minHeight: 60, fontSize: 13 }}
placeholder="Description"
value={ab.text}
onChange={(e) =>
setAbilities((arr) =>
arr.map((x, idx) => (idx === i ? { ...x, text: e.target.value } : x))
)
}
/>
<button
type="button"
className="flo-x"
onClick={() => removeAbility(i)}
>
×
</button>
</div>
))}
<button type="button" className="flo-add-field" onClick={addAbility}>
+ add ability
</button>
</div>
</div>
)}
</div>
<aside className="flo-editor-side">
<div className="flo-side-section">
<h3>Visibility</h3>
<div className="flo-vis-toggle">
<button
type="button"
className={"flo-vis-opt " + (isPublic ? "is-active" : "")}
onClick={() => setIsPublic(true)}
>
<span className="flo-glyph">◐</span>
<div>
<div>Players & DM</div>
<small>Visible in player portal</small>
</div>
</button>
<button
type="button"
className={"flo-vis-opt " + (!isPublic ? "is-active" : "")}
onClick={() => setIsPublic(false)}
>
<span className="flo-glyph">●</span>
<div>
<div>DM only</div>
<small>Hidden from the player portal</small>
</div>
</button>
</div>
<div className="flo-vis-hint">
Sections wrapped in <code className="flo-mono">::secret … ::end</code>
{" "}stay hidden from players even on a public page.
</div>
</div>
<div className="flo-side-section">
<h3>Tags</h3>
<div className="flo-tag-edit">
{tags.map((t) => (
<span key={t} className="flo-tag-pill">
#{t}{" "}
<span
className="flo-x"
onClick={() => setTags((arr) => arr.filter((x) => x !== t))}
>
×
</span>
</span>
))}
<input
className="flo-tag-input"
placeholder="add tag…"
value={tagDraft}
onChange={(e) => setTagDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
addTag();
}
}}
/>
</div>
</div>
</aside>
</div>
</div>
);
}
function insertAtCaret(
ref: React.RefObject<HTMLTextAreaElement | null>,
body: string,
setBody: (s: string) => void,
insert: string
) {
const ta = ref.current;
if (!ta) {
setBody(body + insert);
return;
}
const start = ta.selectionStart ?? body.length;
const end = ta.selectionEnd ?? body.length;
const next = body.slice(0, start) + insert + body.slice(end);
setBody(next);
requestAnimationFrame(() => {
ta.focus();
const pos = start + insert.length;
ta.selectionStart = ta.selectionEnd = pos;
});
}
+26
View File
@@ -0,0 +1,26 @@
"use client";
import { KINDS, isKind } from "@/lib/kinds";
export function KindPill({ kind, small }: { kind: string; small?: boolean }) {
if (!isKind(kind)) return null;
const k = KINDS[kind];
return (
<span
className={"flo-kind" + (small ? " is-small" : "")}
style={{ ["--k-color" as string]: k.color } as React.CSSProperties}
>
<span className="flo-kind-glyph">{k.glyph}</span>
<span className="flo-kind-label">{k.label}</span>
</span>
);
}
export function VisibilityBadge({ isPublic }: { isPublic: boolean }) {
return (
<span className={"flo-vis " + (isPublic ? "is-public" : "is-secret")}>
<span className="flo-vis-dot" />
{isPublic ? "Players can see" : "DM only"}
</span>
);
}
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useFlorte } from "./ClientProviders";
import type { Role } from "./ClientProviders";
export function RequireRole({
children,
role,
}: {
children: React.ReactNode;
role?: Role; // undefined = any signed-in user
}) {
const { session } = useFlorte();
const router = useRouter();
useEffect(() => {
if (!session.role) {
router.replace("/login");
} else if (role && session.role !== role) {
router.replace("/");
}
}, [session.role, role, router]);
if (!session.role) return null;
if (role && session.role !== role) return null;
return <>{children}</>;
}
+13
View File
@@ -0,0 +1,13 @@
"use client";
import { usePathname } from "next/navigation";
import { AppShell } from "./AppShell";
const PUBLIC_PATHS = ["/login", "/setup"];
export function RootBody({ children }: { children: React.ReactNode }) {
const pathname = usePathname() || "/";
const isPublic = PUBLIC_PATHS.some((p) => pathname.startsWith(p));
if (isPublic) return <>{children}</>;
return <AppShell>{children}</AppShell>;
}
+161
View File
@@ -0,0 +1,161 @@
"use client";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useFlorte } from "./ClientProviders";
import type { Dict } from "@/lib/i18n";
type Item = {
href: string;
nameKey: keyof Dict;
glyph: string;
matchPrefix?: string;
exact?: boolean;
};
type Section = { labelKey: keyof Dict; items: Item[] };
const DM_NAV: Section[] = [
{
labelKey: "nav_compendium",
items: [
{ href: "/", nameKey: "nav_codex_home", glyph: "❦" },
{ href: "/search", nameKey: "nav_browse_search", glyph: "⌕" },
{ href: "/map", nameKey: "nav_world_map", glyph: "✦" },
{ href: "/timeline", nameKey: "nav_timeline", glyph: "⌖" },
],
},
{
labelKey: "nav_volumes",
items: [
{ href: "/search?kind=npc", nameKey: "nav_characters", glyph: "❖" },
{ href: "/search?kind=location", nameKey: "nav_locations", glyph: "✦" },
{ href: "/search?kind=faction", nameKey: "nav_factions", glyph: "⚜" },
{ href: "/search?kind=item", nameKey: "nav_items", glyph: "✜" },
{ href: "/bestiary", nameKey: "nav_bestiary", glyph: "✺", matchPrefix: "/bestiary" },
{ href: "/search?kind=lore", nameKey: "nav_lore", glyph: "☽" },
{ href: "/search?kind=deity", nameKey: "nav_pantheon", glyph: "✷" },
],
},
{
labelKey: "nav_table",
items: [
{ href: "/search?kind=session", nameKey: "nav_session_logs", glyph: "§" },
{ href: "/editor", nameKey: "nav_new_entry", glyph: "✎" },
{ href: "/portal", nameKey: "nav_player_portal", glyph: "◐" },
],
},
{
labelKey: "nav_admin",
items: [
{ href: "/admin", nameKey: "nav_world_settings", glyph: "⚙", exact: true },
{ href: "/admin/users", nameKey: "nav_users", glyph: "☉" },
{ href: "/admin/maps", nameKey: "nav_map_layers", glyph: "▤" },
{ href: "/admin/import", nameKey: "nav_import", glyph: "⤓" },
{ href: "/admin/api", nameKey: "nav_api_docs", glyph: "{ }" },
],
},
];
const PLAYER_NAV: Section[] = [
{
labelKey: "nav_compendium",
items: [
{ href: "/portal", nameKey: "nav_player_portal", glyph: "◐" },
{ href: "/search", nameKey: "nav_browse_search", glyph: "⌕" },
{ href: "/map", nameKey: "nav_world_map", glyph: "✦" },
{ href: "/timeline", nameKey: "nav_timeline", glyph: "⌖" },
],
},
];
export function Sidebar({ collapsed }: { collapsed: boolean }) {
const { world, session, t } = useFlorte();
const pathname = usePathname() || "/";
const router = useRouter();
const sections = session.role === "player" ? PLAYER_NAV : DM_NAV;
const isActive = (it: Item) => {
if (it.matchPrefix && pathname.startsWith(it.matchPrefix)) return true;
if (it.href === "/" && pathname === "/") return true;
if (it.exact) return pathname === it.href.split("?")[0];
if (it.href !== "/" && pathname.startsWith(it.href.split("?")[0])) return true;
return false;
};
const onLogout = async () => {
await fetch("/api/auth/logout", { method: "POST" });
router.push("/login");
router.refresh();
};
const roleLabel =
session.role === "dm"
? t("user_owner_all")
: session.role === "player"
? t("user_player_revealed")
: t("user_not_signed_in");
return (
<aside className={"flo-sidebar" + (collapsed ? " is-collapsed" : "")}>
<div className="flo-brand">
<div className="flo-brand-mark">
<svg viewBox="0 0 40 40" width="28" height="28" aria-hidden="true">
<circle cx="20" cy="20" r="18" fill="none" stroke="currentColor" strokeWidth=".7" opacity=".4" />
<circle cx="20" cy="20" r="12" fill="none" stroke="currentColor" strokeWidth=".7" opacity=".55" />
<circle cx="20" cy="20" r="3" fill="currentColor" opacity=".9" />
<line x1="20" y1="2" x2="20" y2="38" stroke="currentColor" strokeWidth=".5" opacity=".25" />
<line x1="2" y1="20" x2="38" y2="20" stroke="currentColor" strokeWidth=".5" opacity=".25" />
</svg>
</div>
<div className="flo-brand-text">
<div className="flo-brand-title">Codex of</div>
<div className="flo-brand-name">{world.name || "Florthoritania"}</div>
</div>
</div>
<nav className="flo-nav">
{sections.map((sec) => (
<div key={sec.labelKey} className="flo-nav-section">
<div className="flo-nav-label">{t(sec.labelKey)}</div>
{sec.items.map((it) => {
const active = isActive(it);
return (
<Link
key={it.href + it.nameKey}
href={it.href}
className={"flo-nav-item" + (active ? " is-active" : "")}
>
<span className="flo-nav-glyph" aria-hidden="true">
{it.glyph}
</span>
<span className="flo-nav-name">{t(it.nameKey)}</span>
</Link>
);
})}
</div>
))}
</nav>
<div className="flo-sidebar-foot">
<div className="flo-user">
<div className="flo-avatar" aria-hidden="true">
{(session.username ?? "?").slice(0, 2).toUpperCase()}
</div>
<div className="flo-user-meta">
<div className="flo-user-name">{session.username ?? "Anonymous"}</div>
<div className="flo-user-role">{roleLabel}</div>
</div>
</div>
{session.role && (
<button
className="flo-link"
onClick={onLogout}
style={{ marginTop: 8, fontSize: 13 }}
>
{t("auth_sign_out")}
</button>
)}
</div>
</aside>
);
}
+81
View File
@@ -0,0 +1,81 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useFlorte } from "./ClientProviders";
import type { Dict } from "@/lib/i18n";
type TitleEntry = { match: RegExp | string; key: keyof Dict };
const TITLES: TitleEntry[] = [
{ match: /^\/$/, key: "topbar_title_home" },
{ match: /^\/search/, key: "topbar_title_search" },
{ match: /^\/map/, key: "topbar_title_map" },
{ match: /^\/timeline/, key: "topbar_title_timeline" },
{ match: /^\/article\//, key: "topbar_title_article" },
{ match: /^\/editor\/.+/, key: "topbar_title_edit" },
{ match: /^\/editor\/?$/, key: "topbar_title_new" },
{ match: /^\/bestiary/, key: "topbar_title_bestiary" },
{ match: /^\/sessions\//, key: "topbar_title_session" },
{ match: /^\/portal/, key: "topbar_title_portal" },
{ match: /^\/settings/, key: "topbar_title_settings" },
];
function titleKeyFor(pathname: string): keyof Dict {
for (const entry of TITLES) {
if (typeof entry.match === "string") {
if (pathname === entry.match) return entry.key;
} else if (entry.match.test(pathname)) return entry.key;
}
return "topbar_title_codex";
}
export function Topbar({
onToggleSidebar,
}: {
onToggleSidebar: () => void;
}) {
const { world, session, t, lang, setLang } = useFlorte();
const pathname = usePathname() || "/";
const titleKey = titleKeyFor(pathname);
return (
<div className="flo-topbar">
<button className="flo-icon-btn" onClick={onToggleSidebar} aria-label="Toggle sidebar">
☰
</button>
<div className="flo-crumbs">
<span className="flo-crumb">{world.name || "Florthoritania"}</span>
<span className="flo-crumb-sep">›</span>
<span className="flo-crumb is-current">{t(titleKey)}</span>
</div>
<div className="flo-topbar-spacer" />
<Link href="/search" className="flo-btn flo-btn-ghost">
<span className="flo-glyph">⌕</span>
<span>{t("topbar_search_placeholder")}</span>
<span className="flo-kbd">/</span>
</Link>
{session.role === "dm" && (
<Link href="/editor" className="flo-btn">
<span className="flo-glyph">✎</span> {t("topbar_new_entry")}
</Link>
)}
<div className="flo-theme-row" style={{ marginLeft: 4 }}>
<button
className={"flo-theme-pill" + (lang === "en" ? " is-active" : "")}
onClick={() => setLang("en")}
title={t("lang_en")}
>
EN
</button>
<button
className={"flo-theme-pill" + (lang === "ru" ? " is-active" : "")}
onClick={() => setLang("ru")}
title={t("lang_ru")}
>
RU
</button>
</div>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
export function json<T>(data: T, init?: ResponseInit) {
return NextResponse.json(data, init);
}
export function err(message: string, status = 400) {
return NextResponse.json({ error: message }, { status });
}
export function asResponse(e: unknown): Response {
if (e instanceof Response) return e;
console.error(e);
const msg = e instanceof Error ? e.message : "Internal error";
return NextResponse.json({ error: msg }, { status: 500 });
}
+25
View File
@@ -0,0 +1,25 @@
export async function api<T = unknown>(
url: string,
init?: RequestInit
): Promise<T> {
const res = await fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
cache: "no-store",
});
if (!res.ok) {
let msg = `Request failed (${res.status})`;
try {
const j = await res.json();
if (j?.error) msg = j.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
}
+11
View File
@@ -0,0 +1,11 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
+376
View File
@@ -0,0 +1,376 @@
export type Lang = "en" | "ru";
const EN_BASE = {
// Nav sections
nav_compendium: "Compendium",
nav_volumes: "Volumes",
nav_table: "Table",
nav_admin: "Admin",
// Nav items
nav_codex_home: "Codex Home",
nav_browse_search: "Browse / Search",
nav_world_map: "World Map",
nav_timeline: "Timeline",
nav_characters: "Characters",
nav_locations: "Locations",
nav_factions: "Factions",
nav_items: "Items",
nav_bestiary: "Bestiary",
nav_lore: "Lore",
nav_pantheon: "Pantheon",
nav_session_logs: "Session Logs",
nav_new_entry: "New Entry",
nav_player_portal: "Player Portal",
nav_world_settings: "World",
nav_users: "Users",
nav_map_layers: "Map layers",
nav_import: "Import",
nav_api_docs: "API & docs",
// Topbar
topbar_search_placeholder: "Search the Codex…",
topbar_new_entry: "New entry",
topbar_title_home: "Codex Home",
topbar_title_search: "Browse / Search",
topbar_title_map: "World Map",
topbar_title_timeline: "Timeline",
topbar_title_article: "Article",
topbar_title_edit: "Edit Entry",
topbar_title_new: "New Entry",
topbar_title_bestiary: "Bestiary",
topbar_title_session: "Session Log",
topbar_title_portal: "Player Portal",
topbar_title_settings: "Settings",
topbar_title_codex: "Codex",
// Auth
auth_sign_in: "Sign in",
auth_sign_out: "Sign out →",
auth_signing_in: "Signing in…",
auth_username: "Username",
auth_password: "Password",
auth_invite_code: "Invite code",
auth_register: "Create account",
auth_registering: "Creating…",
auth_no_account: "No account?",
auth_have_account: "Have an account?",
auth_welcome_back: "Welcome back.",
auth_welcome_back_sub: "Enter your credentials to continue.",
auth_join_sub: "Enter your invite code to join.",
// User meta
user_owner_all: "Owner · all keys",
user_player_revealed: "Player · revealed only",
user_not_signed_in: "Not signed in",
// Common actions
action_save: "Save",
action_saving: "Saving…",
action_cancel: "Cancel",
action_delete: "Delete",
action_deleting: "Deleting…",
action_edit: "Edit",
action_create: "Create",
action_creating: "Creating…",
action_confirm: "Confirm",
action_close: "Close",
action_add: "Add",
action_remove: "Remove",
action_preview: "Preview",
action_import: "Import",
action_importing: "Importing…",
action_upload: "Upload image",
action_reset: "Reset password",
action_apply: "Apply",
action_reveal: "Reveal to players",
action_hide: "Hide from players",
action_back: "← Back",
action_view: "View",
action_copy: "Copy",
action_copied: "Copied!",
// Status
status_public: "Public",
status_private: "Private (DM only)",
status_revealed: "Revealed",
status_hidden: "Hidden",
// Entry editor
editor_title: "Title",
editor_kind: "Kind",
editor_tags: "Tags",
editor_body: "Body",
editor_is_public: "Visible to players",
editor_slug: "Slug",
editor_add_tag: "Add tag",
editor_unsaved: "Unsaved changes",
editor_saved: "Saved",
editor_delete_confirm: "Delete this entry? This cannot be undone.",
// Search / browse
search_placeholder: "Search entries…",
search_no_results: "No entries found.",
search_filter_all: "All kinds",
// Map
map_add_pin: "Add pin",
map_edit_pins: "Edit pins",
map_layers: "Layers",
map_zoom_in: "Zoom in",
map_zoom_out: "Zoom out",
map_reset_view: "Reset view",
map_pin_name: "Pin name",
map_pin_link: "Linked entry (optional)",
map_pin_kind: "Kind",
// Timeline
timeline_add_event: "Add event",
timeline_year: "Year",
timeline_era: "Era",
timeline_title: "Title",
timeline_description: "Description",
// Admin
admin_world_title: "World settings",
admin_world_name: "World name",
admin_world_tagline: "Tagline",
admin_world_era: "Current era",
admin_world_theme: "Theme",
admin_world_accent: "Accent colour",
admin_world_fog: "Show fog of war",
admin_users_title: "User management",
admin_users_create: "Create user",
admin_users_role: "Role",
admin_users_dm: "DM",
admin_users_player: "Player",
admin_import_title: "Import",
admin_import_donjon: "Donjon",
admin_import_azgaar: "Azgaar",
admin_import_fantasytown: "Fantasy Town",
admin_import_paste: "Paste content here…",
admin_import_or_upload: "or upload a file",
admin_import_preview: "Preview import plan",
admin_import_warnings: "Warnings",
admin_import_commit: "Commit import",
admin_maps_title: "Map layers",
admin_maps_create: "Create layer",
admin_maps_set_default: "Set as default",
admin_maps_is_default: "Default",
admin_api_title: "API & docs",
// Portal
portal_welcome: "Player Portal",
portal_revealed: "Revealed entries",
portal_nothing_revealed: "Nothing has been revealed to you yet.",
// Session logs
session_beats: "Session beats",
session_add_beat: "Add beat",
// Bestiary
bestiary_title: "Bestiary",
// Empty / error states
empty_no_entries: "The codex is empty.",
empty_no_pins: "No pins on this layer.",
empty_no_events: "No events recorded.",
empty_no_members: "No members yet.",
error_generic: "Something went wrong.",
error_not_found: "Not found.",
error_unauthorized: "Unauthorized.",
error_forbidden: "Forbidden.",
// Language
lang_en: "EN",
lang_ru: "RU",
lang_switch: "Language",
// Invites
invite_create: "Create invite",
invite_code: "Code",
invite_used_by: "Used by",
invite_unused: "Unused",
invite_expires: "Expires",
invite_copy: "Copy link",
invite_revoke: "Revoke",
// Campaigns
campaign_title: "Campaigns",
campaign_create: "Create campaign",
campaign_name: "Campaign name",
campaign_members: "Members",
campaign_no_campaigns: "No campaigns yet.",
campaign_switch: "Switch campaign",
campaign_current: "Current campaign",
} as const;
export type DictKey = keyof typeof EN_BASE;
export type Dict = Record<DictKey, string>;
export const EN: Dict = EN_BASE;
export const RU: Dict = {
nav_compendium: "Компендиум",
nav_volumes: "Тома",
nav_table: "Стол",
nav_admin: "Управление",
nav_codex_home: "Главная кодекса",
nav_browse_search: "Обзор / Поиск",
nav_world_map: "Карта мира",
nav_timeline: "Хронология",
nav_characters: "Персонажи",
nav_locations: "Локации",
nav_factions: "Фракции",
nav_items: "Предметы",
nav_bestiary: "Бестиарий",
nav_lore: "Лор",
nav_pantheon: "Пантеон",
nav_session_logs: "Журналы сессий",
nav_new_entry: "Новая запись",
nav_player_portal: "Портал игрока",
nav_world_settings: "Мир",
nav_users: "Пользователи",
nav_map_layers: "Слои карты",
nav_import: "Импорт",
nav_api_docs: "API и документация",
topbar_search_placeholder: "Поиск в кодексе…",
topbar_new_entry: "Новая запись",
topbar_title_home: "Главная кодекса",
topbar_title_search: "Обзор / Поиск",
topbar_title_map: "Карта мира",
topbar_title_timeline: "Хронология",
topbar_title_article: "Статья",
topbar_title_edit: "Редактирование",
topbar_title_new: "Новая запись",
topbar_title_bestiary: "Бестиарий",
topbar_title_session: "Журнал сессии",
topbar_title_portal: "Портал игрока",
topbar_title_settings: "Настройки",
topbar_title_codex: "Кодекс",
auth_sign_in: "Войти",
auth_sign_out: "Выйти →",
auth_signing_in: "Вход…",
auth_username: "Имя пользователя",
auth_password: "Пароль",
auth_invite_code: "Код приглашения",
auth_register: "Создать аккаунт",
auth_registering: "Создание…",
auth_no_account: "Нет аккаунта?",
auth_have_account: "Есть аккаунт?",
auth_welcome_back: "С возвращением.",
auth_welcome_back_sub: "Введите данные для входа.",
auth_join_sub: "Введите код приглашения для присоединения.",
user_owner_all: "Мастер · все записи",
user_player_revealed: "Игрок · только открытые",
user_not_signed_in: "Не вошли",
action_save: "Сохранить",
action_saving: "Сохранение…",
action_cancel: "Отмена",
action_delete: "Удалить",
action_deleting: "Удаление…",
action_edit: "Редактировать",
action_create: "Создать",
action_creating: "Создание…",
action_confirm: "Подтвердить",
action_close: "Закрыть",
action_add: "Добавить",
action_remove: "Убрать",
action_preview: "Предпросмотр",
action_import: "Импортировать",
action_importing: "Импорт…",
action_upload: "Загрузить изображение",
action_reset: "Сбросить пароль",
action_apply: "Применить",
action_reveal: "Открыть игрокам",
action_hide: "Скрыть от игроков",
action_back: "← Назад",
action_view: "Просмотр",
action_copy: "Копировать",
action_copied: "Скопировано!",
status_public: "Открыто",
status_private: "Приватно (только МП)",
status_revealed: "Открыто",
status_hidden: "Скрыто",
editor_title: "Заголовок",
editor_kind: "Тип",
editor_tags: "Теги",
editor_body: "Текст",
editor_is_public: "Видно игрокам",
editor_slug: "Идентификатор",
editor_add_tag: "Добавить тег",
editor_unsaved: "Несохранённые изменения",
editor_saved: "Сохранено",
editor_delete_confirm: "Удалить эту запись? Это нельзя отменить.",
search_placeholder: "Поиск записей…",
search_no_results: "Записей не найдено.",
search_filter_all: "Все типы",
map_add_pin: "Добавить метку",
map_edit_pins: "Редактировать метки",
map_layers: "Слои",
map_zoom_in: "Приблизить",
map_zoom_out: "Отдалить",
map_reset_view: "Сбросить вид",
map_pin_name: "Название метки",
map_pin_link: "Связанная запись (необязательно)",
map_pin_kind: "Тип",
timeline_add_event: "Добавить событие",
timeline_year: "Год",
timeline_era: "Эра",
timeline_title: "Название",
timeline_description: "Описание",
admin_world_title: "Настройки мира",
admin_world_name: "Название мира",
admin_world_tagline: "Подзаголовок",
admin_world_era: "Текущая эра",
admin_world_theme: "Тема",
admin_world_accent: "Акцентный цвет",
admin_world_fog: "Туман войны",
admin_users_title: "Управление пользователями",
admin_users_create: "Создать пользователя",
admin_users_role: "Роль",
admin_users_dm: "МП",
admin_users_player: "Игрок",
admin_import_title: "Импорт",
admin_import_donjon: "Donjon",
admin_import_azgaar: "Azgaar",
admin_import_fantasytown: "Fantasy Town",
admin_import_paste: "Вставьте содержимое здесь…",
admin_import_or_upload: "или загрузите файл",
admin_import_preview: "Предпросмотр плана импорта",
admin_import_warnings: "Предупреждения",
admin_import_commit: "Применить импорт",
admin_maps_title: "Слои карты",
admin_maps_create: "Создать слой",
admin_maps_set_default: "Сделать основным",
admin_maps_is_default: "Основной",
admin_api_title: "API и документация",
portal_welcome: "Портал игрока",
portal_revealed: "Открытые записи",
portal_nothing_revealed: "Вам ещё ничего не открыли.",
session_beats: "Моменты сессии",
session_add_beat: "Добавить момент",
bestiary_title: "Бестиарий",
empty_no_entries: "Кодекс пуст.",
empty_no_pins: "Нет меток на этом слое.",
empty_no_events: "Нет записанных событий.",
empty_no_members: "Пока нет участников.",
error_generic: "Что-то пошло не так.",
error_not_found: "Не найдено.",
error_unauthorized: "Не авторизованы.",
error_forbidden: "Доступ запрещён.",
lang_en: "EN",
lang_ru: "RU",
lang_switch: "Язык",
invite_create: "Создать приглашение",
invite_code: "Код",
invite_used_by: "Использовал",
invite_unused: "Не использовано",
invite_expires: "Истекает",
invite_copy: "Копировать ссылку",
invite_revoke: "Отозвать",
campaign_title: "Кампании",
campaign_create: "Создать кампанию",
campaign_name: "Название кампании",
campaign_members: "Участники",
campaign_no_campaigns: "Кампаний пока нет.",
campaign_switch: "Сменить кампанию",
campaign_current: "Текущая кампания",
};
export const DICTS: Record<Lang, Dict> = { en: EN, ru: RU };
export const LANG_COOKIE = "florte_lang";
export function detectLang(): Lang {
if (typeof document === "undefined") return "en";
const match = document.cookie.match(/(?:^|;\s*)florte_lang=([^;]+)/);
if (match?.[1] === "ru") return "ru";
return "en";
}
export function setLangCookie(lang: Lang) {
document.cookie = `${LANG_COOKIE}=${lang};path=/;max-age=31536000;samesite=lax`;
}
+538
View File
@@ -0,0 +1,538 @@
// Parsers and importers for external generators.
//
// Every parser returns a normalized "import plan" — a flat list of entries to
// create, plus optional pins. The /api/import/* routes preview or commit the
// plan in a single transaction.
import { prisma } from "./db";
import { slugify } from "./serialize";
import { syncLinks } from "./links";
import type { KindId } from "./kinds";
export type PlanEntry = {
kind: KindId;
title: string;
subtitle?: string;
summary?: string;
body?: string;
fields?: Record<string, string>;
tags?: string[];
isPublic?: boolean;
stats?: Record<string, string | number>;
abilities?: { name: string; text: string }[];
};
export type PlanPin = {
x: number; // 0..1
y: number; // 0..1
label: string;
kind?: KindId;
/** Index into plan.entries[] to link to (preferred). */
entryIndex?: number;
/** Or an explicit slug if importing pins for already-existing entries. */
entrySlug?: string;
};
export type ImportPlan = {
source: "donjon" | "azgaar" | "fantasytown";
entries: PlanEntry[];
pins?: PlanPin[];
layerName?: string;
warnings?: string[];
};
// ── Apply a plan ───────────────────────────────────────────────────────────
// SQLite/Prisma rejects strings containing lone surrogates (U+D800–U+DFFF).
// Azgaar JSONs sometimes embed them in place-name text. Strip them.
function sanitize(s: string): string {
return s.replace(/[\uD800-\uDFFF]/g, "�");
}
export async function applyPlan(plan: ImportPlan, opts: { layerId?: string | null }) {
const created: { slug: string; title: string; kind: string }[] = [];
const idByIndex: Record<number, string> = {};
for (let i = 0; i < plan.entries.length; i++) {
const e = plan.entries[i];
const slug = await uniqueSlug(slugify(sanitize(e.title)));
const row = await prisma.entry.create({
data: {
slug,
kind: e.kind,
title: sanitize(e.title),
subtitle: sanitize(e.subtitle ?? ""),
summary: sanitize(e.summary ?? ""),
body: sanitize(e.body ?? ""),
fields: JSON.stringify(e.fields ?? {}),
tags: JSON.stringify(e.tags ?? []),
isPublic: !!e.isPublic,
stats: JSON.stringify(e.stats ?? {}),
abilities: JSON.stringify(e.abilities ?? []),
},
});
created.push({ slug: row.slug, title: row.title, kind: row.kind });
idByIndex[i] = row.id;
}
// Re-sync links across all imported entries (for [[wikilink]]s in bodies)
for (let i = 0; i < plan.entries.length; i++) {
const id = idByIndex[i];
if (!id) continue;
await syncLinks(id, plan.entries[i].body ?? "");
}
let pinsCreated = 0;
for (const pin of plan.pins ?? []) {
let entryId: string | undefined;
if (pin.entryIndex !== undefined && idByIndex[pin.entryIndex]) {
entryId = idByIndex[pin.entryIndex];
} else if (pin.entrySlug) {
const e = await prisma.entry.findUnique({ where: { slug: pin.entrySlug } });
if (e) entryId = e.id;
}
if (
typeof pin.x !== "number" || typeof pin.y !== "number" ||
pin.x < 0 || pin.x > 1 || pin.y < 0 || pin.y > 1
) continue;
await prisma.mapPin.create({
data: {
x: pin.x,
y: pin.y,
label: sanitize(pin.label),
kind: pin.kind ?? "location",
entryId,
layerId: opts.layerId ?? null,
},
});
pinsCreated++;
}
return { entriesCreated: created.length, pinsCreated, created };
}
async function uniqueSlug(base: string): Promise<string> {
const cleaned = base || "entry";
let candidate = cleaned;
let n = 0;
while (await prisma.entry.findUnique({ where: { slug: candidate } })) {
n++;
candidate = `${cleaned}-${n}`;
}
return candidate;
}
// ── Donjon parser ──────────────────────────────────────────────────────────
// donjon outputs vary by tool. We support two shapes:
// 1) A user-shaped JSON: { entries: [{kind, title, ...}], pins?: [...] }
// 2) Free text — parsed as a single entry with the body kept verbatim.
export function parseDonjon(input: string, opts: { kind?: KindId; title?: string; isPublic?: boolean }): ImportPlan {
const trimmed = input.trim();
const warnings: string[] = [];
if (!trimmed) return { source: "donjon", entries: [], warnings: ["Empty input"] };
// Try JSON first
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
const obj = JSON.parse(trimmed);
// Shape A: { entries: [...] }
if (Array.isArray(obj?.entries)) {
const entries: PlanEntry[] = obj.entries
.filter((e: unknown) => e && typeof (e as { title?: string }).title === "string")
.map((e: PlanEntry) => ({
kind: ((e as PlanEntry).kind ?? "lore") as KindId,
title: e.title,
subtitle: e.subtitle ?? "",
summary: e.summary ?? "",
body: e.body ?? "",
fields: e.fields ?? {},
tags: e.tags ?? [],
isPublic: e.isPublic ?? !!opts.isPublic,
stats: e.stats ?? {},
abilities: e.abilities ?? [],
}));
return { source: "donjon", entries, pins: obj.pins ?? [], warnings };
}
// Shape B: a single object — coerce
if (typeof obj === "object" && obj !== null) {
const title = (obj.title ?? obj.name ?? opts.title ?? "Untitled").toString();
const summaryParts: string[] = [];
const fields: Record<string, string> = {};
for (const [k, v] of Object.entries(obj)) {
if (["title", "name", "body", "description", "summary"].includes(k)) continue;
if (v == null) continue;
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
fields[k] = String(v);
} else {
summaryParts.push(`${k}: ${JSON.stringify(v)}`);
}
}
const body =
(obj.body as string | undefined) ??
(obj.description as string | undefined) ??
(obj.summary as string | undefined) ??
summaryParts.join("\n");
return {
source: "donjon",
entries: [{
kind: opts.kind ?? "lore",
title,
subtitle: (obj.subtitle as string | undefined) ?? "",
summary: (obj.summary as string | undefined) ?? "",
body,
fields,
isPublic: !!opts.isPublic,
}],
warnings,
};
}
} catch {
warnings.push("Looked like JSON but failed to parse — falling back to text");
}
}
// Plain text → one entry
const title = opts.title?.trim() || firstLine(trimmed) || "Imported note";
const body = trimmed;
return {
source: "donjon",
entries: [{
kind: opts.kind ?? "lore",
title,
summary: "",
body,
isPublic: !!opts.isPublic,
}],
warnings,
};
}
function firstLine(s: string): string {
const i = s.indexOf("\n");
return (i === -1 ? s : s.slice(0, i)).slice(0, 80).trim();
}
// ── Azgaar's Fantasy Map Generator parser ───────────────────────────────────
// Azgaar's "save as JSON" exports a large object. We extract the parts that
// map cleanly onto our entity model.
//
// Supported fields (best-effort; missing fields are skipped):
// states -> faction
// provinces -> location
// burgs -> location (+ pin if coords present)
// religions -> deity
// cultures -> culture
// markers -> location (+ pin)
// notes -> attached as bodies for matching cells/burgs/states by id
type AzObj = Record<string, unknown>;
type AzMarker = { i?: number; x?: number; y?: number; type?: string; icon?: string };
type AzNote = { id?: string; name?: string; legend?: string };
export function parseAzgaar(
raw: string,
opts: { isPublic?: boolean; mapWidth?: number; mapHeight?: number }
): ImportPlan {
const warnings: string[] = [];
let json: AzObj;
try {
json = JSON.parse(raw);
} catch (e) {
return { source: "azgaar", entries: [], warnings: ["Invalid JSON"] };
}
// Map width/height (Azgaar maps are usually 1000x1000-ish)
const info = (json.info as AzObj) ?? {};
const w = Number(info.width) || opts.mapWidth || 1000;
const h = Number(info.height) || opts.mapHeight || 1000;
const entries: PlanEntry[] = [];
const pins: PlanPin[] = [];
// Notes index
const notes: Map<string, AzNote> = new Map();
for (const n of (json.notes as AzNote[]) ?? []) {
if (n?.id) notes.set(n.id, n);
}
const states = (json.pack as AzObj | undefined)?.states ?? json.states ?? [];
if (Array.isArray(states)) {
for (const s of states as AzObj[]) {
if (!s || s.removed || (s.i === 0 && !s.name)) continue;
const name = (s.name as string) ?? (s.fullName as string);
if (!name) continue;
const note = notes.get(`state${s.i}`);
entries.push({
kind: "faction",
title: String(name),
subtitle: (s.formName as string) ?? "",
summary: note?.legend
? stripTags(note.legend).slice(0, 240)
: `Population: ${fmtNum(s.urban)} urban, ${fmtNum(s.rural)} rural`,
body: note?.legend ? stripTags(note.legend) : "",
fields: {
...(s.color ? { Color: String(s.color) } : {}),
...(s.culture != null ? { "Culture id": String(s.culture) } : {}),
...(s.expansionism != null ? { Expansionism: String(s.expansionism) } : {}),
...(s.area ? { Area: String(s.area) } : {}),
},
tags: ["azgaar", "state"],
isPublic: !!opts.isPublic,
});
}
}
const provinces = (json.pack as AzObj | undefined)?.provinces ?? json.provinces ?? [];
if (Array.isArray(provinces)) {
for (const p of provinces as AzObj[]) {
if (!p || p.removed) continue;
const name = p.name as string;
if (!name) continue;
const note = notes.get(`province${p.i}`);
entries.push({
kind: "location",
title: name,
subtitle: (p.formName as string) ?? "Province",
summary: note?.legend ? stripTags(note.legend).slice(0, 240) : "",
body: note?.legend ? stripTags(note.legend) : "",
fields: {
...(p.fullName ? { "Full name": String(p.fullName) } : {}),
...(p.color ? { Color: String(p.color) } : {}),
...(p.area ? { Area: String(p.area) } : {}),
},
tags: ["azgaar", "province"],
isPublic: !!opts.isPublic,
});
}
}
const burgs = (json.pack as AzObj | undefined)?.burgs ?? json.burgs ?? [];
if (Array.isArray(burgs)) {
for (const b of burgs as AzObj[]) {
if (!b || !b.name || (b as { i?: number }).i === 0 || b.removed) continue;
const name = b.name as string;
const note = notes.get(`burg${b.i}`);
const idx = entries.length;
entries.push({
kind: "location",
title: name,
subtitle: b.capital ? "Capital city" : "Settlement",
summary: note?.legend
? stripTags(note.legend).slice(0, 240)
: `Population: ${fmtNum(b.population)}${b.port ? " · port" : ""}${b.capital ? " · capital" : ""}`,
body: note?.legend ? stripTags(note.legend) : "",
fields: {
...(b.population != null ? { Population: fmtNum(b.population) } : {}),
...(b.port ? { Port: "yes" } : {}),
...(b.capital ? { Capital: "yes" } : {}),
...(b.culture != null ? { "Culture id": String(b.culture) } : {}),
...(b.state != null ? { "State id": String(b.state) } : {}),
},
tags: ["azgaar", "burg", b.capital ? "capital" : "settlement"].filter(Boolean) as string[],
isPublic: !!opts.isPublic,
});
const x = Number(b.x);
const y = Number(b.y);
if (!Number.isNaN(x) && !Number.isNaN(y) && w > 0 && h > 0) {
pins.push({
x: clamp01(x / w),
y: clamp01(y / h),
label: name,
kind: "location",
entryIndex: idx,
});
}
}
}
const religions = (json.pack as AzObj | undefined)?.religions ?? json.religions ?? [];
if (Array.isArray(religions)) {
for (const r of religions as AzObj[]) {
if (!r || !r.name || r.removed || (r as { i?: number }).i === 0) continue;
entries.push({
kind: "deity",
title: r.name as string,
subtitle: (r.type as string) ?? (r.form as string) ?? "Religion",
summary: r.deity ? `Chief deity: ${r.deity}` : "",
fields: {
...(r.deity ? { Deity: String(r.deity) } : {}),
...(r.form ? { Form: String(r.form) } : {}),
...(r.expansion ? { Expansion: String(r.expansion) } : {}),
},
tags: ["azgaar", "religion"],
isPublic: !!opts.isPublic,
});
}
}
const cultures = (json.pack as AzObj | undefined)?.cultures ?? json.cultures ?? [];
if (Array.isArray(cultures)) {
for (const c of cultures as AzObj[]) {
if (!c || !c.name || (c as { i?: number }).i === 0 || c.removed) continue;
entries.push({
kind: "culture",
title: c.name as string,
subtitle: (c.type as string) ?? "Culture",
summary: "",
fields: {
...(c.type ? { Type: String(c.type) } : {}),
...(c.expansionism ? { Expansionism: String(c.expansionism) } : {}),
},
tags: ["azgaar", "culture"],
isPublic: !!opts.isPublic,
});
}
}
const markers = (json.pack as AzObj | undefined)?.markers ?? json.markers ?? [];
if (Array.isArray(markers)) {
for (const m of markers as AzMarker[]) {
if (!m || m.x == null || m.y == null) continue;
const note = notes.get(`marker${m.i}`);
const title = note?.name ?? `${m.type ?? "Marker"} ${m.i ?? ""}`.trim();
const idx = entries.length;
entries.push({
kind: "lore",
title,
subtitle: m.type ?? "Marker",
summary: note?.legend ? stripTags(note.legend).slice(0, 240) : "",
body: note?.legend ? stripTags(note.legend) : "",
tags: ["azgaar", "marker", m.type ?? "marker"].filter(Boolean) as string[],
isPublic: !!opts.isPublic,
});
pins.push({
x: clamp01(Number(m.x) / w),
y: clamp01(Number(m.y) / h),
label: title,
kind: "lore",
entryIndex: idx,
});
}
}
if (entries.length === 0) warnings.push("No recognizable Azgaar fields found");
return { source: "azgaar", entries, pins, warnings, layerName: "Azgaar import" };
}
function fmtNum(n: unknown) {
const v = Number(n);
if (!Number.isFinite(v)) return "—";
return v >= 1000 ? Math.round(v).toLocaleString() : String(v);
}
function stripTags(s: string) {
return s.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ").trim();
}
function clamp01(n: number) {
return Math.max(0, Math.min(1, n));
}
// ── Fantasy Town Generator parser ───────────────────────────────────────────
// fantasytowngenerator.com lets you "Save Town" as JSON. The shape varies by
// version, but the most common keys are name, population, race, government,
// economy, military, NPCs (with .name, .race, .occupation, .description),
// and buildings/businesses (with .type, .name, .owner, .description).
//
// We create one Location for the town and one NPC per resident.
type FTGNpc = AzObj & {
name?: string; race?: string; occupation?: string;
description?: string; class?: string; gender?: string;
};
type FTGBuilding = AzObj & {
type?: string; name?: string; owner?: string; description?: string;
};
export function parseFantasyTown(
raw: string,
opts: { isPublic?: boolean }
): ImportPlan {
const warnings: string[] = [];
let town: AzObj;
try {
town = JSON.parse(raw);
} catch {
return { source: "fantasytown", entries: [], warnings: ["Invalid JSON"] };
}
const name = (town.name as string) || (town.townName as string) || "Untitled town";
const race = (town.race as string) ?? (town.dominantRace as string) ?? "";
const government = (town.government as string) ?? "";
const economy = (town.economy as string) ?? "";
const wealth = (town.wealth as string) ?? "";
const population = (town.population as number | string) ?? "";
const military = (town.military as string) ?? "";
const walls = (town.walls as string) ?? "";
const entries: PlanEntry[] = [];
// 1. The town itself
const townFields: Record<string, string> = {};
if (population) townFields.Population = String(population);
if (race) townFields["Dominant race"] = race;
if (government) townFields.Government = government;
if (economy) townFields.Economy = economy;
if (wealth) townFields.Wealth = wealth;
if (walls) townFields.Walls = walls;
if (military) townFields.Military = military;
const npcs = ((town.npcs as FTGNpc[]) ?? (town.NPCs as FTGNpc[]) ?? []).filter(
(n) => n && n.name
);
const buildings = (
(town.buildings as FTGBuilding[]) ??
(town.businesses as FTGBuilding[]) ??
(town.places as FTGBuilding[]) ??
[]
).filter((b) => b && (b.name || b.type));
const bodyParts: string[] = [];
if (npcs.length) {
bodyParts.push("## Notable people");
bodyParts.push(npcs.slice(0, 12).map((n) => `- [[${n.name}]]${n.occupation ? ` — ${n.occupation}` : ""}`).join("\n"));
}
if (buildings.length) {
bodyParts.push("\n## Buildings");
bodyParts.push(buildings.slice(0, 24).map((b) => `- ${b.name ?? b.type}${b.owner ? ` (owned by ${b.owner})` : ""}${b.type && b.name ? ` — ${b.type}` : ""}${b.description ? ` — ${b.description.slice(0, 120)}` : ""}`).join("\n"));
}
const townIndex = entries.length;
entries.push({
kind: "location",
title: name,
subtitle: race ? `${race} settlement` : "Town",
summary:
[population ? `pop. ${population}` : "", race, government, wealth]
.filter(Boolean)
.join(" · "),
body: bodyParts.join("\n"),
fields: townFields,
tags: ["fantasytowngenerator", "town"],
isPublic: !!opts.isPublic,
});
// 2. NPCs as separate entries
for (const n of npcs) {
entries.push({
kind: "npc",
title: String(n.name),
subtitle: n.occupation ? String(n.occupation) : (n.race ? `${n.race}` : ""),
summary: n.description ? String(n.description).slice(0, 240) : "",
body: n.description ? String(n.description) : "",
fields: {
...(n.race ? { Race: String(n.race) } : {}),
...(n.gender ? { Gender: String(n.gender) } : {}),
...(n.class ? { Class: String(n.class) } : {}),
...(n.occupation ? { Occupation: String(n.occupation) } : {}),
Hometown: name,
},
tags: ["fantasytowngenerator", "resident"],
isPublic: !!opts.isPublic,
});
}
if (entries.length === 1) warnings.push("Only the town itself was imported (no NPCs or buildings detected)");
return { source: "fantasytown", entries, warnings };
}
+27
View File
@@ -0,0 +1,27 @@
export type KindId =
| "location" | "npc" | "pc" | "faction" | "item" | "lore"
| "session" | "beast" | "deity" | "rule" | "quest" | "culture";
export const KINDS: Record<KindId, { label: string; glyph: string; color: string }> = {
location: { label: "Location", glyph: "✦", color: "#8aa9d6" },
npc: { label: "Character", glyph: "❖", color: "#d9b46a" },
pc: { label: "Player", glyph: "✶", color: "#c08ad6" },
faction: { label: "Faction", glyph: "⚜", color: "#e09a6b" },
item: { label: "Item", glyph: "✜", color: "#9ad6b8" },
lore: { label: "Lore", glyph: "☽", color: "#b9b3d6" },
session: { label: "Session", glyph: "§", color: "#d6a5a5" },
beast: { label: "Bestiary", glyph: "✺", color: "#d68a8a" },
deity: { label: "Deity", glyph: "✷", color: "#e6c878" },
rule: { label: "Rule", glyph: "▲", color: "#a5b8d6" },
quest: { label: "Quest", glyph: "◈", color: "#d6c08a" },
culture: { label: "Culture", glyph: "✿", color: "#a5d6c0" },
};
export const KIND_ORDER: KindId[] = [
"location", "npc", "pc", "faction", "item", "lore",
"session", "beast", "deity", "rule", "quest", "culture",
];
export function isKind(s: string): s is KindId {
return s in KINDS;
}
+35
View File
@@ -0,0 +1,35 @@
import { prisma } from "./db";
import { extractWikilinks } from "./serialize";
function slugifyBasic(s: string) {
return s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
export async function syncLinks(fromId: string, body: string) {
const titles = extractWikilinks(body);
await prisma.link.deleteMany({ where: { fromId } });
if (titles.length === 0) return;
const targets = await prisma.entry.findMany({
where: {
OR: titles.flatMap((t) => [
{ title: { equals: t } },
{ slug: { equals: slugifyBasic(t) } },
]),
},
select: { id: true },
});
const seen = new Set<string>();
for (const t of targets) {
if (t.id === fromId) continue;
if (seen.has(t.id)) continue;
seen.add(t.id);
await prisma.link.upsert({
where: { fromId_toId: { fromId, toId: t.id } },
update: {},
create: { fromId, toId: t.id },
});
}
}
+636
View File
@@ -0,0 +1,636 @@
// Hand-authored OpenAPI 3.1 document mirroring the routes in src/app/api/*.
// Kept in one file so /api/openapi.json is a thin wrapper.
export const openapi = {
openapi: "3.1.0",
info: {
title: "Codex of Florthoritania API",
version: "1.0.0",
description:
"REST API for the Codex. Authentication is cookie-based (`florthoritania_session`). " +
"Two roles exist: `dm` (full access) and `player` (read-only public content).",
},
servers: [{ url: "/", description: "this server" }],
tags: [
{ name: "auth" },
{ name: "world" },
{ name: "entries" },
{ name: "stats" },
{ name: "timeline" },
{ name: "pins" },
{ name: "layers" },
{ name: "quests" },
{ name: "party" },
{ name: "journal" },
{ name: "threads" },
{ name: "sessions" },
{ name: "users" },
{ name: "import" },
],
components: {
securitySchemes: {
sessionCookie: {
type: "apiKey",
in: "cookie",
name: "florthoritania_session",
},
},
schemas: {
Error: {
type: "object",
required: ["error"],
properties: { error: { type: "string" } },
},
Ok: {
type: "object",
required: ["ok"],
properties: { ok: { type: "boolean", const: true } },
},
Role: { type: "string", enum: ["dm", "player"] },
Kind: {
type: "string",
enum: [
"location", "npc", "pc", "faction", "item", "lore",
"session", "beast", "deity", "rule", "quest", "culture",
],
},
Me: {
type: "object",
properties: {
userId: { type: ["string", "null"] },
username: { type: ["string", "null"] },
role: { oneOf: [{ $ref: "#/components/schemas/Role" }, { type: "null" }] },
},
},
LoginBody: {
type: "object",
required: ["username", "password"],
properties: {
username: { type: "string" },
password: { type: "string", minLength: 6 },
},
},
SetupBody: {
type: "object",
required: ["username", "password"],
properties: {
username: { type: "string" },
password: { type: "string", minLength: 6 },
worldName: { type: "string" },
tagline: { type: "string" },
era: { type: "string" },
playerPassword: { type: "string", minLength: 4 },
},
},
World: {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
tagline: { type: "string" },
era: { type: "string" },
theme: { type: "string", enum: ["midnight", "obsidian", "parchment"] },
accent: { type: "string", description: "CSS color (hex)" },
showFog: { type: "boolean" },
updatedAt: { type: "string", format: "date-time" },
},
},
Entry: {
type: "object",
properties: {
id: { type: "string" },
slug: { type: "string" },
kind: { $ref: "#/components/schemas/Kind" },
title: { type: "string" },
subtitle: { type: "string" },
summary: { type: "string" },
body: { type: "string" },
fields: {
type: "object",
additionalProperties: { type: "string" },
},
tags: { type: "array", items: { type: "string" } },
isPublic: { type: "boolean" },
stats: {
type: "object",
additionalProperties: { oneOf: [{ type: "string" }, { type: "number" }] },
},
abilities: {
type: "array",
items: {
type: "object",
required: ["name", "text"],
properties: { name: { type: "string" }, text: { type: "string" } },
},
},
createdAt: { type: "string", format: "date-time" },
updatedAt: { type: "string", format: "date-time" },
},
},
EntryWriteBody: {
type: "object",
properties: {
kind: { $ref: "#/components/schemas/Kind" },
title: { type: "string" },
slug: { type: "string", description: "Optional override" },
subtitle: { type: "string" },
summary: { type: "string" },
body: { type: "string" },
fields: { type: "object", additionalProperties: { type: "string" } },
tags: { type: "array", items: { type: "string" } },
isPublic: { type: "boolean" },
stats: { type: "object" },
abilities: { type: "array", items: { type: "object" } },
},
},
EntryDetail: {
type: "object",
properties: {
entry: { $ref: "#/components/schemas/Entry" },
backlinks: {
type: "array",
items: {
type: "object",
properties: {
slug: { type: "string" },
title: { type: "string" },
kind: { $ref: "#/components/schemas/Kind" },
},
},
},
},
},
Stats: {
type: "object",
properties: {
totalAll: { type: "integer" },
totalPublic: { type: "integer" },
byKind: {
type: "object",
additionalProperties: { type: "integer" },
},
},
},
TimelineEvent: {
type: "object",
properties: {
id: { type: "string" },
year: { type: "integer" },
era: { type: "string" },
label: { type: "string" },
text: { type: "string" },
kind: { $ref: "#/components/schemas/Kind" },
entrySlug: { type: ["string", "null"] },
},
},
MapPin: {
type: "object",
properties: {
id: { type: "string" },
x: { type: "number", minimum: 0, maximum: 1 },
y: { type: "number", minimum: 0, maximum: 1 },
label: { type: "string" },
kind: { $ref: "#/components/schemas/Kind" },
entrySlug: { type: ["string", "null"] },
layerId: { type: ["string", "null"] },
},
},
MapLayerSummary: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
width: { type: "integer" },
height: { type: "integer" },
isDefault: { type: "boolean" },
order: { type: "integer" },
},
},
MapLayer: {
allOf: [
{ $ref: "#/components/schemas/MapLayerSummary" },
{
type: "object",
properties: {
imageData: { type: "string", description: "data: URL or empty for procedural canvas" },
createdAt: { type: "string", format: "date-time" },
},
},
],
},
Quest: {
type: "object",
properties: {
id: { type: "string" },
title: { type: "string" },
meta: { type: "string" },
priority: { type: "string", enum: ["normal", "critical"] },
status: { type: "string", enum: ["active", "completed"] },
isPublic: { type: "boolean" },
createdAt: { type: "string", format: "date-time" },
},
},
PartyMember: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
klass: { type: "string" },
hpCur: { type: "integer" },
hpMax: { type: "integer" },
color: { type: "string" },
order: { type: "integer" },
},
},
JournalEntry: {
type: "object",
properties: {
id: { type: "string" },
who: { type: "string" },
color: { type: "string" },
text: { type: "string" },
createdAt: { type: "string", format: "date-time" },
},
},
Thread: {
type: "object",
properties: {
id: { type: "string" },
text: { type: "string" },
who: { type: "string" },
primary: { type: "boolean" },
resolved: { type: "boolean" },
createdAt: { type: "string", format: "date-time" },
},
},
SessionBeat: {
type: "object",
properties: {
id: { type: "string" },
time: { type: "string" },
title: { type: "string" },
text: { type: "string" },
flag: { type: "string", enum: ["", "rp", "key", "fight"] },
order: { type: "integer" },
},
},
User: {
type: "object",
properties: {
id: { type: "string" },
username: { type: "string" },
role: { $ref: "#/components/schemas/Role" },
createdAt: { type: "string", format: "date-time" },
},
},
ImportPlan: {
type: "object",
properties: {
source: { type: "string", enum: ["donjon", "azgaar", "fantasytown"] },
entries: { type: "array", items: { type: "object" } },
pins: { type: "array", items: { type: "object" } },
layerName: { type: "string" },
warnings: { type: "array", items: { type: "string" } },
},
},
ImportResult: {
type: "object",
properties: {
plan: { $ref: "#/components/schemas/ImportPlan" },
result: {
type: "object",
properties: {
entriesCreated: { type: "integer" },
pinsCreated: { type: "integer" },
created: {
type: "array",
items: {
type: "object",
properties: {
slug: { type: "string" },
title: { type: "string" },
kind: { type: "string" },
},
},
},
},
},
layerId: { type: ["string", "null"] },
},
},
},
},
security: [{ sessionCookie: [] }],
paths: buildPaths(),
} as const;
type AnyOpenApi = Record<string, unknown>;
function buildPaths(): AnyOpenApi {
const ok = (schemaRef: string) => ({
"200": {
description: "OK",
content: {
"application/json": { schema: { $ref: `#/components/schemas/${schemaRef}` } },
},
},
});
const okList = (schemaRef: string) => ({
"200": {
description: "OK",
content: {
"application/json": {
schema: { type: "array", items: { $ref: `#/components/schemas/${schemaRef}` } },
},
},
},
});
const created = (schemaRef: string) => ({
"201": {
description: "Created",
content: {
"application/json": { schema: { $ref: `#/components/schemas/${schemaRef}` } },
},
},
});
const okOk = {
"200": {
description: "OK",
content: {
"application/json": { schema: { $ref: "#/components/schemas/Ok" } },
},
},
};
const errSchema = {
description: "Error",
content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } },
};
const idParam = {
name: "id",
in: "path",
required: true,
schema: { type: "string" },
};
const slugParam = {
name: "slug",
in: "path",
required: true,
schema: { type: "string" },
};
const reqBody = (schemaRef: string) => ({
required: true,
content: {
"application/json": { schema: { $ref: `#/components/schemas/${schemaRef}` } },
},
});
return {
"/api/auth/setup": {
get: {
tags: ["auth"], summary: "Whether first-run setup is required",
security: [],
responses: {
"200": {
description: "OK",
content: {
"application/json": {
schema: {
type: "object",
properties: { needsSetup: { type: "boolean" } },
},
},
},
},
},
},
post: {
tags: ["auth"], summary: "Create the initial DM and (optional) player user",
security: [],
requestBody: reqBody("SetupBody"),
responses: { ...okOk, "409": errSchema, "400": errSchema },
},
},
"/api/auth/login": {
post: {
tags: ["auth"], summary: "Sign in",
security: [],
requestBody: reqBody("LoginBody"),
responses: {
"200": {
description: "OK",
content: {
"application/json": {
schema: {
type: "object",
properties: {
ok: { type: "boolean" },
role: { $ref: "#/components/schemas/Role" },
},
},
},
},
},
"401": errSchema,
},
},
},
"/api/auth/logout": {
post: {
tags: ["auth"], summary: "Sign out (clear session cookie)",
responses: okOk,
},
},
"/api/auth/me": {
get: {
tags: ["auth"], summary: "Current session",
security: [],
responses: ok("Me"),
},
},
"/api/world": {
get: { tags: ["world"], summary: "Get world settings", responses: ok("World") },
patch: {
tags: ["world"], summary: "Update world settings (DM)",
requestBody: reqBody("World"),
responses: { ...ok("World"), "403": errSchema },
},
},
"/api/entries": {
get: {
tags: ["entries"], summary: "List entries (player sees only public)",
parameters: [
{ name: "kind", in: "query", schema: { $ref: "#/components/schemas/Kind" } },
{ name: "q", in: "query", schema: { type: "string" } },
],
responses: okList("Entry"),
},
post: {
tags: ["entries"], summary: "Create entry (DM)",
requestBody: reqBody("EntryWriteBody"),
responses: { ...created("Entry"), "400": errSchema, "403": errSchema },
},
},
"/api/entries/{slug}": {
parameters: [slugParam],
get: {
tags: ["entries"], summary: "Read entry + backlinks",
responses: { ...ok("EntryDetail"), "404": errSchema },
},
patch: {
tags: ["entries"], summary: "Update entry (DM)",
requestBody: reqBody("EntryWriteBody"),
responses: ok("Entry"),
},
delete: {
tags: ["entries"], summary: "Delete entry (DM)",
responses: okOk,
},
},
"/api/stats": {
get: { tags: ["stats"], summary: "Counts by kind", responses: ok("Stats") },
},
"/api/timeline": {
get: { tags: ["timeline"], summary: "List events", responses: okList("TimelineEvent") },
post: {
tags: ["timeline"], summary: "Create event (DM)",
responses: { ...created("TimelineEvent"), "400": errSchema },
},
},
"/api/timeline/{id}": {
parameters: [idParam],
patch: { tags: ["timeline"], summary: "Update event (DM)", responses: ok("TimelineEvent") },
delete: { tags: ["timeline"], summary: "Delete event (DM)", responses: okOk },
},
"/api/pins": {
get: {
tags: ["pins"], summary: "List map pins (filterable by layer)",
parameters: [{ name: "layerId", in: "query", schema: { type: "string" } }],
responses: okList("MapPin"),
},
post: {
tags: ["pins"], summary: "Create pin (DM)",
responses: { ...created("MapPin"), "400": errSchema },
},
},
"/api/pins/{id}": {
parameters: [idParam],
patch: { tags: ["pins"], summary: "Update pin (DM)", responses: ok("MapPin") },
delete: { tags: ["pins"], summary: "Delete pin (DM)", responses: okOk },
},
"/api/layers": {
get: { tags: ["layers"], summary: "List map layers", responses: okList("MapLayerSummary") },
post: {
tags: ["layers"], summary: "Create layer (DM)",
responses: { ...created("MapLayerSummary"), "413": errSchema },
},
},
"/api/layers/{id}": {
parameters: [idParam],
get: { tags: ["layers"], summary: "Get layer with imageData", responses: ok("MapLayer") },
patch: { tags: ["layers"], summary: "Update layer (DM)", responses: ok("MapLayer") },
delete: { tags: ["layers"], summary: "Delete layer (DM)", responses: okOk },
},
"/api/quests": {
get: { tags: ["quests"], summary: "List quests", responses: okList("Quest") },
post: { tags: ["quests"], summary: "Create quest (DM)", responses: created("Quest") },
},
"/api/quests/{id}": {
parameters: [idParam],
patch: { tags: ["quests"], summary: "Update quest (DM)", responses: ok("Quest") },
delete: { tags: ["quests"], summary: "Delete quest (DM)", responses: okOk },
},
"/api/party": {
get: { tags: ["party"], summary: "List party members", responses: okList("PartyMember") },
post: { tags: ["party"], summary: "Create party member (DM)", responses: created("PartyMember") },
},
"/api/party/{id}": {
parameters: [idParam],
patch: { tags: ["party"], summary: "Update member (DM)", responses: ok("PartyMember") },
delete: { tags: ["party"], summary: "Delete member (DM)", responses: okOk },
},
"/api/journal": {
get: { tags: ["journal"], summary: "List journal entries", responses: okList("JournalEntry") },
post: { tags: ["journal"], summary: "Add journal entry", responses: created("JournalEntry") },
},
"/api/journal/{id}": {
parameters: [idParam],
delete: { tags: ["journal"], summary: "Delete journal entry", responses: okOk },
},
"/api/threads": {
get: { tags: ["threads"], summary: "List unresolved threads (DM)", responses: okList("Thread") },
post: { tags: ["threads"], summary: "Create thread (DM)", responses: created("Thread") },
},
"/api/threads/{id}": {
parameters: [idParam],
patch: { tags: ["threads"], summary: "Update thread (DM)", responses: ok("Thread") },
delete: { tags: ["threads"], summary: "Delete thread (DM)", responses: okOk },
},
"/api/sessions/{slug}/beats": {
parameters: [slugParam],
get: { tags: ["sessions"], summary: "List beats for a session", responses: okList("SessionBeat") },
post: { tags: ["sessions"], summary: "Add beat (DM)", responses: created("SessionBeat") },
},
"/api/beats/{id}": {
parameters: [idParam],
patch: { tags: ["sessions"], summary: "Update beat (DM)", responses: ok("SessionBeat") },
delete: { tags: ["sessions"], summary: "Delete beat (DM)", responses: okOk },
},
"/api/users": {
get: { tags: ["users"], summary: "List users (DM)", responses: okList("User") },
post: { tags: ["users"], summary: "Create user (DM)", responses: { ...created("User"), "409": errSchema } },
},
"/api/users/{id}": {
parameters: [idParam],
patch: { tags: ["users"], summary: "Update user (DM): username, password, role", responses: ok("User") },
delete: { tags: ["users"], summary: "Delete user (DM)", responses: okOk },
},
"/api/import/donjon": {
post: {
tags: ["import"], summary: "Parse Donjon-style input. Use ?action=apply to commit.",
parameters: [{ name: "action", in: "query", schema: { type: "string", enum: ["preview", "apply"] } }],
responses: ok("ImportResult"),
},
},
"/api/import/azgaar": {
post: {
tags: ["import"],
summary: "Parse Azgaar Fantasy Map JSON. Use ?action=apply to commit (creates entries + optional map layer + pins).",
parameters: [{ name: "action", in: "query", schema: { type: "string", enum: ["preview", "apply"] } }],
responses: ok("ImportResult"),
},
},
"/api/import/fantasytown": {
post: {
tags: ["import"], summary: "Parse fantasytowngenerator.com JSON. Use ?action=apply to commit.",
parameters: [{ name: "action", in: "query", schema: { type: "string", enum: ["preview", "apply"] } }],
responses: ok("ImportResult"),
},
},
"/api/openapi.json": {
get: {
tags: ["meta"], summary: "This OpenAPI document",
security: [],
responses: {
"200": {
description: "OpenAPI spec",
content: { "application/json": { schema: { type: "object" } } },
},
},
},
},
};
}
+63
View File
@@ -0,0 +1,63 @@
import type { Entry } from "@prisma/client";
export type EntryDTO = {
id: string;
slug: string;
kind: string;
title: string;
subtitle: string;
summary: string;
body: string;
fields: Record<string, string>;
tags: string[];
isPublic: boolean;
stats: Record<string, string | number>;
abilities: { name: string; text: string }[];
createdAt: string;
updatedAt: string;
};
export function entryToDTO(e: Entry): EntryDTO {
return {
id: e.id,
slug: e.slug,
kind: e.kind,
title: e.title,
subtitle: e.subtitle,
summary: e.summary,
body: e.body,
fields: parseJSON(e.fields, {}),
tags: parseJSON(e.tags, []),
isPublic: e.isPublic,
stats: parseJSON(e.stats, {}),
abilities: parseJSON(e.abilities, []),
createdAt: e.createdAt.toISOString(),
updatedAt: e.updatedAt.toISOString(),
};
}
export function parseJSON<T>(s: string, fallback: T): T {
try {
return JSON.parse(s) as T;
} catch {
return fallback;
}
}
export function slugify(s: string): string {
return s
.toLowerCase()
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 96);
}
export function extractWikilinks(body: string): string[] {
const out = new Set<string>();
const re = /\[\[([^\]]+)\]\]/g;
let m: RegExpExecArray | null;
while ((m = re.exec(body)) !== null) out.add(m[1].trim());
return [...out];
}
+49
View File
@@ -0,0 +1,49 @@
import { cookies } from "next/headers";
import { getIronSession, type SessionOptions } from "iron-session";
export type Role = "dm" | "player";
export interface SessionData {
userId?: string;
username?: string;
role?: Role;
}
const password = process.env.SESSION_SECRET;
if (!password || password.length < 32) {
throw new Error(
"SESSION_SECRET env var must be set and at least 32 characters long"
);
}
export const sessionOptions: SessionOptions = {
password,
cookieName: "florthoritania_session",
cookieOptions: {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
path: "/",
},
};
export async function getSession() {
const cookieStore = await cookies();
return getIronSession<SessionData>(cookieStore, sessionOptions);
}
export async function requireDm() {
const s = await getSession();
if (s.role !== "dm") {
throw new Response("Forbidden", { status: 403 });
}
return s;
}
export async function requireAuth() {
const s = await getSession();
if (!s.userId || !s.role) {
throw new Response("Unauthorized", { status: 401 });
}
return s;
}
+9
View File
@@ -0,0 +1,9 @@
import { prisma } from "./db";
export async function getOrCreateWorld() {
let w = await prisma.world.findUnique({ where: { id: 1 } });
if (!w) {
w = await prisma.world.create({ data: { id: 1 } });
}
return w;
}
+255
View File
@@ -0,0 +1,255 @@
/* Florthoritania additions on top of the ported design CSS.
Auth screens, action affordances, empty states, danger button. */
.flo-shell {
min-height: 100vh;
display: grid;
place-items: center;
padding: 32px 18px;
position: relative;
z-index: 1;
}
.flo-auth-card {
width: 100%;
max-width: 440px;
background: linear-gradient(180deg, var(--bg-2), var(--bg-1));
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 32px 32px 28px;
box-shadow: var(--shadow-card);
}
.flo-auth-card h1 {
font-family: "Cormorant Garamond", serif;
font-size: 36px; font-weight: 400; margin: 0 0 4px; letter-spacing: -.005em;
}
.flo-auth-card p.flo-auth-sub {
color: var(--ink-3); font-style: italic; margin: 0 0 20px;
font-family: "Cormorant Garamond", serif; font-size: 16px;
}
.flo-auth-row { display: flex; flex-direction: column; gap: 4px; margin-bottom: 14px; }
.flo-auth-row label {
font-family: "JetBrains Mono", monospace;
font-size: 10px; letter-spacing: .14em; text-transform: uppercase;
color: var(--ink-4);
}
.flo-input {
background: var(--bg-1);
border: 1px solid var(--line);
color: var(--ink); font: inherit; font-size: 14px;
padding: 9px 12px; border-radius: var(--radius-sm); outline: 0;
font-family: "Spectral", Georgia, serif;
}
.flo-input:focus { border-color: var(--brass); }
.flo-input.flo-input-mono { font-family: "JetBrains Mono", monospace; font-size: 13px; }
.flo-textarea {
background: var(--bg-1);
border: 1px solid var(--line);
color: var(--ink); font: inherit;
padding: 12px 14px; border-radius: var(--radius-sm); outline: 0;
font-family: "Spectral", Georgia, serif;
font-size: 14.5px; line-height: 1.6;
resize: vertical;
min-height: 110px;
}
.flo-textarea:focus { border-color: var(--brass); }
.flo-select {
background: var(--bg-1);
border: 1px solid var(--line);
color: var(--ink); font: inherit; font-size: 13px;
padding: 8px 10px; border-radius: var(--radius-sm); outline: 0;
}
.flo-auth-actions { display: flex; gap: 8px; margin-top: 18px; align-items: center; }
.flo-auth-foot { margin-top: 18px; font-size: 12px; color: var(--ink-3); }
.flo-error {
background: rgba(214,138,138,.08);
border: 1px solid rgba(214,138,138,.3);
color: var(--rust);
border-radius: var(--radius-sm);
padding: 8px 12px; margin-bottom: 12px; font-size: 13px;
}
.flo-success {
background: rgba(107,214,192,.08);
border: 1px solid rgba(107,214,192,.3);
color: var(--teal);
border-radius: var(--radius-sm);
padding: 8px 12px; margin-bottom: 12px; font-size: 13px;
}
.flo-btn-danger {
background: rgba(214,138,138,.1);
border: 1px solid rgba(214,138,138,.4);
color: var(--rust);
box-shadow: none;
}
.flo-btn-danger:hover { background: rgba(214,138,138,.18); }
.flo-empty-card {
text-align: center;
padding: 48px 32px;
border: 1px dashed var(--line-2);
border-radius: var(--radius);
color: var(--ink-3);
font-style: italic;
font-family: "Cormorant Garamond", serif;
font-size: 17px;
background: rgba(0,0,0,.06);
}
.flo-pill-toggle {
display: inline-flex; gap: 6px; align-items: center;
font-family: "JetBrains Mono", monospace;
font-size: 11px; color: var(--ink-3);
cursor: pointer;
user-select: none;
}
.flo-pill-toggle input { accent-color: var(--brass); }
.flo-modal-back {
position: fixed; inset: 0; z-index: 50;
background: rgba(0,0,0,.62);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
display: grid; place-items: center;
padding: 24px;
}
.flo-modal {
width: 100%; max-width: 540px;
background: linear-gradient(180deg, var(--bg-2), var(--bg-1));
border: 1px solid var(--line-2);
border-radius: var(--radius);
padding: 22px 24px;
box-shadow: 0 20px 60px rgba(0,0,0,.7);
}
.flo-modal h2 { font-family: "Cormorant Garamond", serif; font-weight: 500; font-size: 22px; margin: 0 0 14px; }
.flo-modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 14px; }
.flo-toolbar {
display: flex; gap: 8px; flex-wrap: wrap; align-items: center;
padding: 12px 14px;
background: var(--bg-2);
border: 1px solid var(--line);
border-radius: var(--radius);
margin-bottom: 16px;
}
.flo-toolbar .flo-toolbar-spacer { flex: 1; }
.flo-grid-1 { display: grid; grid-template-columns: 1fr; gap: 16px; }
.flo-tag-pill .flo-x:hover { color: var(--rust); }
.flo-link.is-danger { color: var(--rust); }
.flo-link.is-danger:hover { color: #f0a3a3; }
.flo-row { display: flex; gap: 10px; align-items: center; }
.flo-row.is-wrap { flex-wrap: wrap; }
/* Settings page */
.flo-settings-section {
background: linear-gradient(180deg, var(--bg-2), var(--bg-1));
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 22px 24px;
margin-bottom: 18px;
}
.flo-settings-section h2 {
font-family: "Cormorant Garamond", serif; font-weight: 500; font-size: 22px;
margin: 0 0 14px;
}
.flo-form-row {
display: grid; grid-template-columns: 160px 1fr; gap: 14px;
align-items: center; margin-bottom: 12px;
}
@media (max-width: 640px) {
.flo-form-row { grid-template-columns: 1fr; }
}
.flo-form-row label {
font-family: "JetBrains Mono", monospace;
font-size: 10.5px; letter-spacing: .12em; text-transform: uppercase;
color: var(--ink-4);
}
/* Map editor cursor for adding pins */
.flo-map-canvas.is-pinning { cursor: crosshair; }
.flo-map-canvas.is-pinning .flo-pin { cursor: default; }
/* Theme switcher inline */
.flo-theme-row {
display: inline-flex; gap: 6px; align-items: center;
}
.flo-theme-pill {
display: inline-flex; gap: 6px; align-items: center;
font-family: "JetBrains Mono", monospace;
font-size: 10px; letter-spacing: .08em; text-transform: uppercase;
padding: 4px 10px; border-radius: 999px;
border: 1px solid var(--line);
background: transparent; color: var(--ink-3); cursor: pointer;
}
.flo-theme-pill.is-active {
border-color: var(--brass); color: var(--brass);
background: rgba(217,180,106,.06);
}
/* Pulled-quote SVG portrait fallback uses brass */
.flo-portrait-glyph { color: var(--brass); }
/* Responsive: collapse sidebar text on narrow viewports */
@media (max-width: 880px) {
.flo-app { grid-template-columns: 64px 1fr; }
.flo-app .flo-brand-text,
.flo-app .flo-nav-label,
.flo-app .flo-nav-name,
.flo-app .flo-nav-count,
.flo-app .flo-user-meta { display: none; }
}
/* ── Enhanced map ────────────────────────────────────────────────────────── */
.flo-map-canvas { cursor: grab; }
.flo-map-canvas.is-grabbing { cursor: grabbing; }
.flo-map-stage {
position: absolute; left: 0; top: 0;
transform-origin: 0 0;
width: 100%; height: 100%;
will-change: transform;
}
.flo-map-img {
position: absolute; left: 0; top: 0;
width: 100%; height: 100%;
object-fit: cover;
pointer-events: none;
user-select: none;
}
.flo-pin.is-dragging { z-index: 20; }
.flo-pin.is-dragging .flo-pin-dot { transform: translate(-50%, -50%) scale(1.5); }
.flo-map-layerbar {
position: absolute;
left: 18px; top: 18px;
display: flex; gap: 6px; flex-wrap: wrap;
background: rgba(17, 16, 42, .85);
-webkit-backdrop-filter: blur(16px); backdrop-filter: blur(16px);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 6px;
max-width: 50vw;
}
.flo-map-zoombar {
position: absolute;
left: 18px; bottom: 18px;
display: flex; gap: 4px; align-items: center;
background: rgba(17, 16, 42, .85);
-webkit-backdrop-filter: blur(16px); backdrop-filter: blur(16px);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 4px;
}
.flo-map-zoombar .flo-chip { padding: 4px 8px; }
[data-theme="parchment"] .flo-map-layerbar,
[data-theme="parchment"] .flo-map-zoombar,
[data-theme="parchment"] .flo-map-card,
[data-theme="parchment"] .flo-map-legend {
background: rgba(232, 220, 184, .9);
}
File diff suppressed because it is too large. Load diff
+2
View File
@@ -0,0 +1,2 @@
@import "./florthoritania.css";
@import "./extras.css";
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}