Compare commits

..

1 Commits

Author SHA1 Message Date
eeb2ef04fd Converts using full document state management 2025-07-02 17:01:56 -07:00
76 changed files with 1854 additions and 2053 deletions

153
README.md
View File

@@ -1,8 +1,6 @@
# DM Companion App Welcome to your new TanStack app!
## Development # Getting Started
### Getting Started
To run this application: To run this application:
@@ -11,7 +9,7 @@ npm install
npm run start npm run start
``` ```
### Building For Production # Building For Production
To build this application for production: To build this application for production:
@@ -19,7 +17,7 @@ To build this application for production:
npm run build npm run build
``` ```
### Testing ## Testing
This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with: This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with:
@@ -27,15 +25,17 @@ This project uses [Vitest](https://vitest.dev/) for testing. You can run the tes
npm run test npm run test
``` ```
### Styling ## Styling
This project uses [Tailwind CSS](https://tailwindcss.com/) for styling. This project uses [Tailwind CSS](https://tailwindcss.com/) for styling.
### Routing
## Routing
This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`. This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`.
#### Adding A Route ### Adding A Route
To add a new route to your application just add another a new file in the `./src/routes` directory. To add a new route to your application just add another a new file in the `./src/routes` directory.
@@ -43,7 +43,7 @@ TanStack will automatically generate the content of the route file for you.
Now that you have two routes you can use a `Link` component to navigate between them. Now that you have two routes you can use a `Link` component to navigate between them.
#### Adding Links ### Adding Links
To use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`. To use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`.
@@ -61,15 +61,15 @@ This will create a link that will navigate to the `/about` route.
More information on the `Link` component can be found in the [Link documentation](https://tanstack.com/router/v1/docs/framework/react/api/router/linkComponent). More information on the `Link` component can be found in the [Link documentation](https://tanstack.com/router/v1/docs/framework/react/api/router/linkComponent).
#### Using A Layout ### Using A Layout
In the File Based Routing setup the layout is located in `src/routes/__root.tsx`. Anything you add to the root route will appear in all the routes. The route content will appear in the JSX where you use the `<Outlet />` component. In the File Based Routing setup the layout is located in `src/routes/__root.tsx`. Anything you add to the root route will appear in all the routes. The route content will appear in the JSX where you use the `<Outlet />` component.
Here is an example layout that includes a header: Here is an example layout that includes a header:
```tsx ```tsx
import { Outlet, createRootRoute } from "@tanstack/react-router"; import { Outlet, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools"; import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { Link } from "@tanstack/react-router"; import { Link } from "@tanstack/react-router";
@@ -86,20 +86,129 @@ export const Route = createRootRoute({
<TanStackRouterDevtools /> <TanStackRouterDevtools />
</> </>
), ),
}); })
``` ```
The `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout. The `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout.
More information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts). More information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts).
### Data Fetching
#### Pocketbase ## Data Fetching
TODO There are multiple ways to fetch data in your application. You can use TanStack Query to fetch data from a server. But you can also use the `loader` functionality built into TanStack Router to load the data for a route before it's rendered.
### State Management For example:
```tsx
const peopleRoute = createRoute({
getParentRoute: () => rootRoute,
path: "/people",
loader: async () => {
const response = await fetch("https://swapi.dev/api/people");
return response.json() as Promise<{
results: {
name: string;
}[];
}>;
},
component: () => {
const data = peopleRoute.useLoaderData();
return (
<ul>
{data.results.map((person) => (
<li key={person.name}>{person.name}</li>
))}
</ul>
);
},
});
```
Loaders simplify your data fetching logic dramatically. Check out more information in the [Loader documentation](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#loader-parameters).
### React-Query
React-Query is an excellent addition or alternative to route loading and integrating it into you application is a breeze.
First add your dependencies:
```bash
npm install @tanstack/react-query @tanstack/react-query-devtools
```
Next we'll need to create a query client and provider. We recommend putting those in `main.tsx`.
```tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// ...
const queryClient = new QueryClient();
// ...
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
);
}
```
You can also add TanStack Query Devtools to the root route (optional).
```tsx
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
const rootRoute = createRootRoute({
component: () => (
<>
<Outlet />
<ReactQueryDevtools buttonPosition="top-right" />
<TanStackRouterDevtools />
</>
),
});
```
Now you can use `useQuery` to fetch your data.
```tsx
import { useQuery } from "@tanstack/react-query";
import "./App.css";
function App() {
const { data } = useQuery({
queryKey: ["people"],
queryFn: () =>
fetch("https://swapi.dev/api/people")
.then((res) => res.json())
.then((data) => data.results as { name: string }[]),
initialData: [],
});
return (
<div>
<ul>
{data.map((person) => (
<li key={person.name}>{person.name}</li>
))}
</ul>
</div>
);
}
export default App;
```
You can find out everything you need to know on how to use React-Query in the [React-Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
## State Management
Another common requirement for React applications is state management. There are many options for state management in React. TanStack Store provides a great starting point for your project. Another common requirement for React applications is state management. There are many options for state management in React. TanStack Store provides a great starting point for your project.
@@ -171,3 +280,11 @@ We use the `Derived` class to create a new store that is derived from another st
Once we've created the derived store we can use it in the `App` component just like we would any other store using the `useStore` hook. Once we've created the derived store we can use it in the `App` component just like we would any other store using the `useStore` hook.
You can find out everything you need to know on how to use TanStack Store in the [TanStack Store documentation](https://tanstack.com/store/latest). You can find out everything you need to know on how to use TanStack Store in the [TanStack Store documentation](https://tanstack.com/store/latest).
# Demo files
Files prefixed with `demo` can be safely deleted. They are there to provide a starting point for you to play around with the features you've installed.
# Learn More
You can learn more about all of the offerings from TanStack in the [TanStack documentation](https://tanstack.com).

View File

@@ -11,7 +11,7 @@
<title>Dungeon Master's Companion</title> <title>Dungeon Master's Companion</title>
</head> </head>
<body> <body>
<div id="app" class="flex flex-col h-full w-full"></div> <div id="app"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>

160
package-lock.json generated
View File

@@ -9,20 +9,19 @@
"@atlaskit/pragmatic-drag-and-drop": "^1.7.4", "@atlaskit/pragmatic-drag-and-drop": "^1.7.4",
"@headlessui/react": "^2.2.4", "@headlessui/react": "^2.2.4",
"@tailwindcss/vite": "^4.0.6", "@tailwindcss/vite": "^4.0.6",
"@tanstack/react-query": "^5.79.0",
"@tanstack/react-query-devtools": "^5.79.0", "@tanstack/react-query-devtools": "^5.79.0",
"@tanstack/react-router": "^1.114.3", "@tanstack/react-router": "^1.114.3",
"@tanstack/react-router-devtools": "^1.114.3", "@tanstack/react-router-devtools": "^1.114.3",
"@tanstack/router-plugin": "^1.114.3", "@tanstack/router-plugin": "^1.114.3",
"dompurify": "^3.2.6",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"marked": "^16.1.1",
"pocketbase": "^0.26.0", "pocketbase": "^0.26.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"tailwindcss": "^4.0.6", "tailwindcss": "^4.0.6"
"zod": "^4.0.5"
}, },
"devDependencies": { "devDependencies": {
"@astrojs/ts-plugin": "^1.10.4",
"@testing-library/dom": "^10.4.0", "@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0", "@testing-library/react": "^16.2.0",
"@types/lodash": "^4.17.17", "@types/lodash": "^4.17.17",
@@ -70,6 +69,52 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/@astrojs/compiler": {
"version": "2.12.2",
"resolved": "https://registry.npmjs.org/@astrojs/compiler/-/compiler-2.12.2.tgz",
"integrity": "sha512-w2zfvhjNCkNMmMMOn5b0J8+OmUaBL1o40ipMvqcG6NRpdC+lKxmTi48DT8Xw0SzJ3AfmeFLB45zXZXtmbsjcgw==",
"dev": true,
"license": "MIT"
},
"node_modules/@astrojs/ts-plugin": {
"version": "1.10.4",
"resolved": "https://registry.npmjs.org/@astrojs/ts-plugin/-/ts-plugin-1.10.4.tgz",
"integrity": "sha512-rapryQINgv5VLZF884R/wmgX3mM9eH1PC/I3kkPV9rP6lEWrRN1YClF3bGcDHFrf8EtTLc0Wqxne1Uetpevozg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@astrojs/compiler": "^2.10.3",
"@astrojs/yaml2ts": "^0.2.2",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@volar/language-core": "~2.4.7",
"@volar/typescript": "~2.4.7",
"semver": "^7.3.8",
"vscode-languageserver-textdocument": "^1.0.11"
}
},
"node_modules/@astrojs/ts-plugin/node_modules/semver": {
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/@astrojs/yaml2ts": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/@astrojs/yaml2ts/-/yaml2ts-0.2.2.tgz",
"integrity": "sha512-GOfvSr5Nqy2z5XiwqTouBBpy5FyI6DEe+/g/Mk5am9SjILN1S5fOEvYK0GuWHg98yS/dobP4m8qyqw/URW35fQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"yaml": "^2.5.0"
}
},
"node_modules/@atlaskit/pragmatic-drag-and-drop": { "node_modules/@atlaskit/pragmatic-drag-and-drop": {
"version": "1.7.4", "version": "1.7.4",
"resolved": "https://registry.npmjs.org/@atlaskit/pragmatic-drag-and-drop/-/pragmatic-drag-and-drop-1.7.4.tgz", "resolved": "https://registry.npmjs.org/@atlaskit/pragmatic-drag-and-drop/-/pragmatic-drag-and-drop-1.7.4.tgz",
@@ -1677,7 +1722,6 @@
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.79.0.tgz", "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.79.0.tgz",
"integrity": "sha512-s+epTqqLM0/TbJzMAK7OEhZIzh63P9sWz5HEFc5XHL4FvKQXQkcjI8F3nee+H/xVVn7mrP610nVXwOytTSYd0w==", "integrity": "sha512-s+epTqqLM0/TbJzMAK7OEhZIzh63P9sWz5HEFc5XHL4FvKQXQkcjI8F3nee+H/xVVn7mrP610nVXwOytTSYd0w==",
"license": "MIT", "license": "MIT",
"peer": true,
"funding": { "funding": {
"type": "github", "type": "github",
"url": "https://github.com/sponsors/tannerlinsley" "url": "https://github.com/sponsors/tannerlinsley"
@@ -1698,7 +1742,6 @@
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.79.0.tgz", "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.79.0.tgz",
"integrity": "sha512-DjC4JIYZnYzxaTzbg3osOU63VNLP67dOrWet2cZvXgmgwAXNxfS52AMq86M5++ILuzW+BqTUEVMTjhrZ7/XBuA==", "integrity": "sha512-DjC4JIYZnYzxaTzbg3osOU63VNLP67dOrWet2cZvXgmgwAXNxfS52AMq86M5++ILuzW+BqTUEVMTjhrZ7/XBuA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@tanstack/query-core": "5.79.0" "@tanstack/query-core": "5.79.0"
}, },
@@ -1882,15 +1925,6 @@
} }
} }
}, },
"node_modules/@tanstack/router-generator/node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/@tanstack/router-plugin": { "node_modules/@tanstack/router-plugin": {
"version": "1.120.10", "version": "1.120.10",
"resolved": "https://registry.npmjs.org/@tanstack/router-plugin/-/router-plugin-1.120.10.tgz", "resolved": "https://registry.npmjs.org/@tanstack/router-plugin/-/router-plugin-1.120.10.tgz",
@@ -1947,15 +1981,6 @@
} }
} }
}, },
"node_modules/@tanstack/router-plugin/node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/@tanstack/router-utils": { "node_modules/@tanstack/router-utils": {
"version": "1.115.0", "version": "1.115.0",
"resolved": "https://registry.npmjs.org/@tanstack/router-utils/-/router-utils-1.115.0.tgz", "resolved": "https://registry.npmjs.org/@tanstack/router-utils/-/router-utils-1.115.0.tgz",
@@ -2137,13 +2162,6 @@
"@types/react": "^19.0.0" "@types/react": "^19.0.0"
} }
}, },
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@vitejs/plugin-react": { "node_modules/@vitejs/plugin-react": {
"version": "4.5.0", "version": "4.5.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.5.0.tgz", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.5.0.tgz",
@@ -2278,6 +2296,35 @@
"url": "https://opencollective.com/vitest" "url": "https://opencollective.com/vitest"
} }
}, },
"node_modules/@volar/language-core": {
"version": "2.4.16",
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.16.tgz",
"integrity": "sha512-mcoAFkYVQV4iiLYjTlbolbsm9hhDLtz4D4wTG+rwzSCUbEnxEec+KBlneLMlfdVNjkVEh8lUUSsCGNEQR+hFdA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@volar/source-map": "2.4.16"
}
},
"node_modules/@volar/source-map": {
"version": "2.4.16",
"resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.16.tgz",
"integrity": "sha512-4rBiAhOw4MfFTpkvweDnjbDkixpmWNgBws95rpu2oFdMprkTtqFEb8pUOxQ/ruru8/zXSYLwRNXNozznjW9Vtw==",
"dev": true,
"license": "MIT"
},
"node_modules/@volar/typescript": {
"version": "2.4.16",
"resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.16.tgz",
"integrity": "sha512-CrRuG20euPerYc4H0kvDWSSLTBo6qgSI1/0BjXL9ogjm5j6l0gIffvNzEvfmVjr8TAuoMPD0NxuEkteIapfZQQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@volar/language-core": "2.4.16",
"path-browserify": "^1.0.1",
"vscode-uri": "^3.0.8"
}
},
"node_modules/acorn": { "node_modules/acorn": {
"version": "8.14.1", "version": "8.14.1",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz",
@@ -2687,15 +2734,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/dompurify": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.6.tgz",
"integrity": "sha512-/2GogDQlohXPZe6D6NOgQvXLPSYBqIWMnZ8zzOhn09REE4eyAzb+Hed3jhoM9OkuaJ8P6ZGTTVWQKAi8ieIzfQ==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.157", "version": "1.5.157",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.157.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.157.tgz",
@@ -3348,18 +3386,6 @@
"@jridgewell/sourcemap-codec": "^1.5.0" "@jridgewell/sourcemap-codec": "^1.5.0"
} }
}, },
"node_modules/marked": {
"version": "16.1.1",
"resolved": "https://registry.npmjs.org/marked/-/marked-16.1.1.tgz",
"integrity": "sha512-ij/2lXfCRT71L6u0M29tJPhP0bM5shLL3u5BePhFwPELj2blMJ6GDtD7PfJhRLhJ/c2UwrK17ySVcDzy2YHjHQ==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 20"
}
},
"node_modules/minipass": { "node_modules/minipass": {
"version": "7.1.2", "version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
@@ -3455,6 +3481,13 @@
"url": "https://github.com/inikulin/parse5?sponsor=1" "url": "https://github.com/inikulin/parse5?sponsor=1"
} }
}, },
"node_modules/path-browserify": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
"integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",
"dev": true,
"license": "MIT"
},
"node_modules/pathe": { "node_modules/pathe": {
"version": "2.0.3", "version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
@@ -4306,6 +4339,20 @@
} }
} }
}, },
"node_modules/vscode-languageserver-textdocument": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",
"integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==",
"dev": true,
"license": "MIT"
},
"node_modules/vscode-uri": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz",
"integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==",
"dev": true,
"license": "MIT"
},
"node_modules/w3c-xmlserializer": { "node_modules/w3c-xmlserializer": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
@@ -4445,9 +4492,8 @@
"version": "2.8.0", "version": "2.8.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz",
"integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==", "integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==",
"devOptional": true,
"license": "ISC", "license": "ISC",
"optional": true,
"peer": true,
"bin": { "bin": {
"yaml": "bin.mjs" "yaml": "bin.mjs"
}, },
@@ -4456,9 +4502,9 @@
} }
}, },
"node_modules/zod": { "node_modules/zod": {
"version": "4.0.5", "version": "3.25.28",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.0.5.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.28.tgz",
"integrity": "sha512-/5UuuRPStvHXu7RS+gmvRf4NXrNxpSllGwDnCBcJZtQsKrviYXm54yDGV2KYNLT5kq0lHGcl7lqWJLgSaG+tgA==", "integrity": "sha512-/nt/67WYKnr5by3YS7LroZJbtcCBurDKKPBPWWzaxvVCGuG/NOsiKkrjoOhI8mJ+SQUXEbUzeB3S+6XDUEEj7Q==",
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"

View File

@@ -5,7 +5,7 @@
"scripts": { "scripts": {
"dev": "mprocs \"npm run start\" \"pocketbase serve\"", "dev": "mprocs \"npm run start\" \"pocketbase serve\"",
"start": "VITE_POCKETBASE_URL=http://localhost:8090 vite --port 3000", "start": "VITE_POCKETBASE_URL=http://localhost:8090 vite --port 3000",
"build": "tsc && vite build", "build": "vite build && tsc",
"serve": "vite preview", "serve": "vite preview",
"test": "vitest run", "test": "vitest run",
"docker:build:app": "docker build -t docker.havenisms.com/lazy-dm/app -f docker/app.dockerfile --build-arg VITE_POCKETBASE_URL=/api .", "docker:build:app": "docker build -t docker.havenisms.com/lazy-dm/app -f docker/app.dockerfile --build-arg VITE_POCKETBASE_URL=/api .",
@@ -16,20 +16,19 @@
"@atlaskit/pragmatic-drag-and-drop": "^1.7.4", "@atlaskit/pragmatic-drag-and-drop": "^1.7.4",
"@headlessui/react": "^2.2.4", "@headlessui/react": "^2.2.4",
"@tailwindcss/vite": "^4.0.6", "@tailwindcss/vite": "^4.0.6",
"@tanstack/react-query": "^5.79.0",
"@tanstack/react-query-devtools": "^5.79.0", "@tanstack/react-query-devtools": "^5.79.0",
"@tanstack/react-router": "^1.114.3", "@tanstack/react-router": "^1.114.3",
"@tanstack/react-router-devtools": "^1.114.3", "@tanstack/react-router-devtools": "^1.114.3",
"@tanstack/router-plugin": "^1.114.3", "@tanstack/router-plugin": "^1.114.3",
"dompurify": "^3.2.6",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"marked": "^16.1.1",
"pocketbase": "^0.26.0", "pocketbase": "^0.26.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"tailwindcss": "^4.0.6", "tailwindcss": "^4.0.6"
"zod": "^4.0.5"
}, },
"devDependencies": { "devDependencies": {
"@astrojs/ts-plugin": "^1.10.4",
"@testing-library/dom": "^10.4.0", "@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0", "@testing-library/react": "^16.2.0",
"@types/lodash": "^4.17.17", "@types/lodash": "^4.17.17",

View File

@@ -1,54 +0,0 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_3332084752")
// update field
collection.fields.addAt(3, new Field({
"hidden": false,
"id": "select2363381545",
"maxSelect": 1,
"name": "type",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"location",
"monster",
"npc",
"scene",
"secret",
"session",
"treasure",
"thread",
"front"
]
}))
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_3332084752")
// update field
collection.fields.addAt(3, new Field({
"hidden": false,
"id": "select2363381545",
"maxSelect": 1,
"name": "type",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"location",
"monster",
"npc",
"scene",
"secret",
"session",
"treasure"
]
}))
return app.save(collection)
})

View File

@@ -1,6 +1,6 @@
{ {
"short_name": "DM Companion", "short_name": "TanStack App",
"name": "Dungeon Master Companion", "name": "Create TanStack App Sample",
"icons": [ "icons": [
{ {
"src": "favicon.ico", "src": "favicon.ico",

View File

@@ -1,15 +1,16 @@
import * as Icons from "@/components/Icons.tsx";
import type { AnyDocument, DocumentId } from "@/lib/types"; import type { AnyDocument, DocumentId } from "@/lib/types";
import { import {
Dialog, Dialog,
DialogPanel, DialogPanel,
DialogTitle,
Transition, Transition,
TransitionChild, TransitionChild,
} from "@headlessui/react"; } from "@headlessui/react";
import { Fragment, useCallback, useState } from "react"; import { Fragment, useCallback, useState } from "react";
import * as Icons from "@/components/Icons.tsx";
type Props<T extends AnyDocument> = { type Props<T extends AnyDocument> = {
title?: React.ReactNode; title: React.ReactNode;
error?: React.ReactNode; error?: React.ReactNode;
items: T[]; items: T[];
renderRow: (item: T) => React.ReactNode; renderRow: (item: T) => React.ReactNode;
@@ -47,9 +48,9 @@ export function DocumentList<T extends AnyDocument>({
}; };
return ( return (
<section className="w-full"> <section className="w-full max-w-2xl mx-auto">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between my-4">
{title && <h2 className="text-xl font-bold text-slate-100">{title}</h2>} <h2 className="text-xl font-bold text-slate-100">{title}</h2>
<div className="flex gap-2"> <div className="flex gap-2">
{isEditing && ( {isEditing && (
<button <button
@@ -74,13 +75,13 @@ export function DocumentList<T extends AnyDocument>({
{error && ( {error && (
<div className="bg-red-900 rounded p-4 text-slate-100">{error}</div> <div className="bg-red-900 rounded p-4 text-slate-100">{error}</div>
)} )}
<ul className="flex flex-col space-y-2"> <ul className="space-y-2">
{items.map((item) => ( {items.map((item) => (
<li <li
key={item.id} key={item.id}
className="p-2 m-0 border-b-1 last:border-0 border-slate-700 flex flex-row justify-between items-center" className="bg-slate-800 rounded p-4 text-slate-100 flex flex-row justify-between items-center"
> >
{renderRow(item)} <div>{renderRow(item)}</div>
{isEditing && ( {isEditing && (
<div> <div>

View File

@@ -1,35 +0,0 @@
import * as Icons from "./Icons";
import { useState, Children } from "react";
export function EditToggle({ children }: React.PropsWithChildren) {
const [isEditing, setIsEditing] = useState(false);
const editChildren = (
Children.toArray(children) as React.ReactElement[]
).filter((c) => c.type === Editing);
const nonEditChildren = (
Children.toArray(children) as React.ReactElement[]
).filter((c) => c.type !== Editing);
return (
<div className="relative">
<div className="absolute right-0 top-0 z-50">
<button
type="button"
className="inline-flex items-center justify-center rounded-full bg-violet-600 hover:bg-violet-700 text-white w-8 h-8 focus:outline-none focus:ring-2 focus:ring-violet-400"
aria-label={isEditing ? "Exit edit mode" : "Enter edit mode"}
onClick={() => setIsEditing(!isEditing)}
>
<Icons.Edit />
</button>
</div>
{isEditing ? editChildren : nonEditChildren}
</div>
);
}
export const Editing = ({ children }: React.PropsWithChildren) => (
<>{children}</>
);
export const NotEditing = ({ children }: React.PropsWithChildren) => (
<>{children}</>
);

View File

@@ -1,22 +0,0 @@
import DOMPurify from "dompurify";
import * as Marked from "marked";
export type Props = {
value: string;
};
function formatText(text: React.ReactNode): { __html: string } {
if (typeof text === "string") {
return {
__html: DOMPurify.sanitize(
Marked.parse(text, { async: false }) as string,
),
};
}
throw new Error("Attempted to safe-render a non-string.");
}
export function FormattedText({ children }: React.PropsWithChildren) {
return <div dangerouslySetInnerHTML={formatText(children)}></div>;
}

View File

@@ -1,5 +1,4 @@
import { DocumentList } from "@/components/DocumentList"; import { DocumentList } from "@/components/DocumentList";
import { useDocumentCache, useDocument } from "@/context/document/hooks";
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
import { displayName } from "@/lib/relationships"; import { displayName } from "@/lib/relationships";
import type { import type {
@@ -8,10 +7,12 @@ import type {
Relationship, Relationship,
RelationshipType, RelationshipType,
} from "@/lib/types"; } from "@/lib/types";
import { useState } from "react"; import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { Loader } from "./Loader"; import { Loader } from "./Loader";
import { DocumentRow } from "./documents/DocumentRow"; import { DocumentRow } from "./documents/DocumentRow";
import { NewRelatedDocumentForm } from "./documents/NewRelatedDocumentForm"; import { NewRelatedDocumentForm } from "./documents/NewRelatedDocumentForm";
import { useDocument } from "@/context/document/DocumentContext";
interface RelationshipListProps { interface RelationshipListProps {
root: AnyDocument; root: AnyDocument;
@@ -26,29 +27,108 @@ export function RelationshipList({
root, root,
relationshipType, relationshipType,
}: RelationshipListProps) { }: RelationshipListProps) {
const [_loading, setLoading] = useState(true); // const [items, setItems] = useState<AnyDocument[]>([]);
// const [relationshipId, setRelationshipId] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const { docResult, dispatch } = useDocument(root.id); // const queryClient = useQueryClient();
const { cache } = useDocumentCache();
if (docResult.type !== "ready") { // useEffect(() => {
// async function fetchItems() {
// const { relationship } = await queryClient.fetchQuery({
// queryKey: ["relationship", relationshipType, root.id],
// staleTime: 5 * 60 * 1000, // 5 mintues
// queryFn: async () => {
// setLoading(true);
// const relationship: Relationship = await pb
// .collection("relationships")
// .getFirstListItem(
// `primary = "${root.id}" && type = "${relationshipType}"`,
// {
// expand: "secondary",
// },
// );
//
// setLoading(false);
//
// return { relationship };
// },
// });
// setRelationshipId(relationship.id);
// setItems(relationship.expand?.secondary ?? []);
// }
//
// fetchItems();
// }, [root, relationshipType]);
// Handles creation of a new document and adds it to the relationship
// const handleCreate = async (doc: AnyDocument) => {
// setLoading(true);
// setError(null);
// try {
// // Check for existing relationship
// if (relationshipId) {
// console.debug("Adding to existing relationship", relationshipId);
// await pb.collection("relationships").update(relationshipId, {
// "+secondary": doc.id,
// });
// } else {
// console.debug("Creating new relationship");
// const relationship = await pb.collection("relationships").create({
// primary: root.id,
// secondary: [doc.id],
// type: relationshipType,
// });
// setRelationshipId(relationship.id);
// }
// queryClient.invalidateQueries({
// queryKey: ["relationship", relationshipType, root.id],
// });
// setItems((prev) => [doc, ...prev]);
// } catch (e: any) {
// setError(e?.message || "Failed to add document to relationship.");
// } finally {
// setLoading(false);
// }
// };
//
// const handleRemove = async (documentId: DocumentId) => {
// setLoading(true);
// setError(null);
//
// try {
// if (relationshipId) {
// console.debug("Removing from existing relationship", relationshipId);
// await pb.collection("relationships").update(relationshipId, {
// "secondary-": documentId,
// });
// }
// queryClient.invalidateQueries({
// queryKey: ["relationship", relationshipType, root.id],
// });
// setItems((prev) => prev.filter((item) => item.id != documentId));
// } catch (e: any) {
// setError(
// e?.message || `Failed to remove document from ${relationshipType}.`,
// );
// } finally {
// setLoading(false);
// }
// };
//
// if (loading) {
// <Loader />;
// }
const { state, dispatch } = useDocument();
if (state.status === "loading") {
return <Loader />; return <Loader />;
} }
const relationshipResult = docResult.value.relationships[relationshipType]; const relationship = state.relationships[relationshipType];
const itemIds = relationship?.secondary ?? [];
const relationship = const items = itemIds.map((id) => state.relatedDocs[id]).filter((d) => !!d);
relationshipResult?.type === "ready" ? relationshipResult.value : null;
const itemIds =
relationshipResult?.type === "ready"
? relationshipResult.value.secondary
: [];
const items = itemIds
.map((id) => cache.documents[id])
.filter((d) => d && d.type === "ready")
.map((d) => d.value.doc);
const handleCreate = async (doc: AnyDocument) => { const handleCreate = async (doc: AnyDocument) => {
setLoading(true); setLoading(true);
@@ -56,6 +136,7 @@ export function RelationshipList({
try { try {
// Check for existing relationship // Check for existing relationship
if (relationship) { if (relationship) {
console.debug("Adding to existing relationship", relationship.id);
const updatedRelationship: Relationship = await pb const updatedRelationship: Relationship = await pb
.collection("relationships") .collection("relationships")
.update(relationship.id, { .update(relationship.id, {
@@ -63,10 +144,10 @@ export function RelationshipList({
}); });
dispatch({ dispatch({
type: "setRelationship", type: "setRelationship",
docId: root.id,
relationship: updatedRelationship, relationship: updatedRelationship,
}); });
} else { } else {
console.debug("Creating new relationship");
const updatedRelationship: Relationship = await pb const updatedRelationship: Relationship = await pb
.collection("relationships") .collection("relationships")
.create({ .create({
@@ -76,9 +157,12 @@ export function RelationshipList({
}); });
dispatch({ dispatch({
type: "setRelationship", type: "setRelationship",
docId: root.id,
relationship: updatedRelationship, relationship: updatedRelationship,
}); });
dispatch({
type: "setRelatedDocument",
doc,
});
} }
} catch (e: any) { } catch (e: any) {
setError(e?.message || "Failed to add document to relationship."); setError(e?.message || "Failed to add document to relationship.");
@@ -93,6 +177,7 @@ export function RelationshipList({
try { try {
if (relationship) { if (relationship) {
console.debug("Removing from existing relationship", relationship.id);
const updatedRelationship: Relationship = await pb const updatedRelationship: Relationship = await pb
.collection("relationships") .collection("relationships")
.update(relationship.id, { .update(relationship.id, {
@@ -100,7 +185,6 @@ export function RelationshipList({
}); });
dispatch({ dispatch({
type: "setRelationship", type: "setRelationship",
docId: root.id,
relationship: updatedRelationship, relationship: updatedRelationship,
}); });
} }
@@ -118,7 +202,7 @@ export function RelationshipList({
title={displayName(relationshipType)} title={displayName(relationshipType)}
items={items} items={items}
error={error} error={error}
renderRow={(document) => <DocumentRow document={document} root={root} />} renderRow={(document) => <DocumentRow document={document} />}
removeItem={handleRemove} removeItem={handleRemove}
newItemForm={(onSubmit) => ( newItemForm={(onSubmit) => (
<NewRelatedDocumentForm <NewRelatedDocumentForm

View File

@@ -1,69 +0,0 @@
import {
type AnyDocument,
type CampaignId,
type DocumentId,
type DocumentType,
} from "@/lib/types";
import { useDocumentCache } from "@/context/document/hooks";
import { DocumentList } from "../DocumentList";
import { getAllDocumentsOfType } from "@/context/document/state";
import { DocumentRow } from "../documents/DocumentRow";
import { pb } from "@/lib/pocketbase";
import { useEffect } from "react";
import { NewCampaignDocumentForm } from "../documents/NewCampaignDocumentForm";
export type Props = {
campaignId: CampaignId;
docType: DocumentType;
};
export const CampaignDocuments = ({ campaignId, docType }: Props) => {
const { cache, dispatch } = useDocumentCache();
const items = getAllDocumentsOfType(docType, cache);
useEffect(() => {
async function fetchDocuments() {
const documents: AnyDocument[] = await pb
.collection("documents")
.getFullList({
filter: `campaign = "${campaignId}" && type = "${docType}"`,
sort: "created",
});
for (const doc of documents) {
dispatch({
type: "setDocument",
doc,
});
}
}
fetchDocuments();
}, [campaignId, docType]);
const handleRemove = (id: DocumentId) => {
pb.collection("documents").delete(id);
dispatch({
type: "removeDocument",
docId: id,
});
};
return (
<DocumentList
items={items}
renderRow={(doc) => <DocumentRow document={doc} />}
newItemForm={(onSubmit) => (
<NewCampaignDocumentForm
campaignId={campaignId}
docType={docType}
onCreate={async () => {
onSubmit();
}}
/>
)}
removeItem={handleRemove}
/>
);
};

View File

@@ -1,27 +0,0 @@
import { Link } from "@tanstack/react-router";
import { FormattedText } from "../FormattedText";
import type { DocumentId } from "@/lib/types";
export type Props = {
id: DocumentId;
title?: string;
description?: string;
};
export const BasicPreview = ({ id, title, description }: Props) => {
return (
<div>
<Link
to="/document/$documentId/$"
params={{
documentId: id,
}}
className="!no-underline text-violet-400 hover:underline hover:text-violet-500"
>
View
</Link>
{title && <h4 className="font-bold">{title}</h4>}
{description && <FormattedText>{description}</FormattedText>}
</div>
);
};

View File

@@ -1,10 +1,9 @@
import type { AnyDocument } from "@/lib/types"; import type { AnyDocument } from "@/lib/types";
import { FormattedText } from "../FormattedText"; import { Link } from "@tanstack/react-router";
import { DocumentLink } from "./DocumentLink";
export type Props = { export type Props = {
doc: AnyDocument; doc: AnyDocument;
title?: string; title: string;
description?: string; description?: string;
}; };
@@ -14,13 +13,14 @@ export type Props = {
export const BasicRow = ({ doc, title, description }: Props) => { export const BasicRow = ({ doc, title, description }: Props) => {
return ( return (
<div> <div>
<DocumentLink <Link
childDocId={doc.id} to="/document/$documentId"
className="!no-underline text-slate-100 hover:underline hover:text-violet-400" params={{ documentId: doc.id }}
className="text-lg !no-underline text-slate-100 hover:underline hover:text-violet-400"
> >
{title && <h4 className="font-bold">{title}</h4>} <h4>{title}</h4>
{description && <FormattedText>{description}</FormattedText>} </Link>
</DocumentLink> {description && <p>{description}</p>}
</div> </div>
); );
}; };

View File

@@ -0,0 +1,30 @@
import { type AnyDocument } from "@/lib/types";
import { LocationEditForm } from "./location/LocationEditForm";
import { MonsterEditForm } from "./monsters/MonsterEditForm";
import { NpcEditForm } from "./npc/NpcEditForm";
import { SceneEditForm } from "./scene/SceneEditForm";
import { SecretEditForm } from "./secret/SecretEditForm";
import { SessionEditForm } from "./session/SessionEditForm";
import { TreasureEditForm } from "./treasure/TreasureEditForm";
/**
* Renders a form for any document type depending on the relationship.
*/
export const DocumentEditForm = ({ document }: { document: AnyDocument }) => {
switch (document.type) {
case "location":
return <LocationEditForm location={document} />;
case "monster":
return <MonsterEditForm monster={document} />;
case "npc":
return <NpcEditForm npc={document} />;
case "scene":
return <SceneEditForm scene={document} />;
case "secret":
return <SecretEditForm secret={document} />;
case "session":
return <SessionEditForm session={document} />;
case "treasure":
return <TreasureEditForm treasure={document} />;
}
};

View File

@@ -1,53 +0,0 @@
import { makeDocumentPath } from "@/lib/documentPath";
import type { DocumentId } from "@/lib/types";
import { Link } from "@tanstack/react-router";
export type Props = React.PropsWithChildren<{
childDocId: DocumentId;
className?: string;
}>;
export function DocumentLink({ childDocId, className, children }: Props) {
// const docPath = useDocumentPath();
//
// const params = useParams({
// strict: false,
// });
//
// const campaignSearch = useSearch({
// from: "/_app/_authenticated/campaigns/$campaignId",
// shouldThrow: false,
// });
//
// const to = params.campaignId
// ? `/campaigns/${params.campaignId}`
// : docPath
// ? makeDocumentPath(
// docPath.documentId,
// docPath?.relationshipType,
// childDocId,
// )
// : undefined;
//
// const search = campaignSearch
// ? { tab: campaignSearch.tab, docId: childDocId }
// : undefined;
//
// if (to === undefined) {
// throw new Error("Not in a document or campaign context");
// }
//
// return (
// <Link to={to} search={search} className={className}>
// {children}
// </Link>
// );
const to = makeDocumentPath(childDocId);
return (
<Link to={to} className={className}>
{children}
</Link>
);
}

View File

@@ -1,86 +0,0 @@
// Shows a preview of a document with it's relationships.
import { makeDocumentPath } from "@/lib/documentPath";
import { relationshipsForDocument } from "@/lib/relationships";
import { type AnyDocument } from "@/lib/types";
import { Link } from "@tanstack/react-router";
import { Editing, EditToggle, NotEditing } from "../EditToggle";
import { BasicPreview } from "./BasicPreview";
import { GenericEditForm } from "./GenericEditForm";
export const DocumentPreview = ({ doc }: { doc: AnyDocument }) => {
const relationships = relationshipsForDocument(doc);
return (
<div>
<EditToggle>
<Editing>
<GenericEditForm doc={doc} />
</Editing>
<NotEditing>
<ShowDocument doc={doc} />
</NotEditing>
</EditToggle>
<ul>
{relationships.map((relType) => (
<li>
<Link to={makeDocumentPath(doc.id, relType)}>{relType}</Link>
</li>
))}
</ul>
</div>
);
};
const ShowDocument = ({ doc }: { doc: AnyDocument }) => {
switch (doc.type) {
case "front":
return (
<BasicPreview
id={doc.id}
title={doc.data.name}
description={doc.data.description}
/>
);
case "location":
return (
<BasicPreview
id={doc.id}
title={doc.data.name}
description={doc.data.description}
/>
);
case "monster":
return <BasicPreview id={doc.id} title={doc.data.name} />;
case "npc":
return (
<BasicPreview
id={doc.id}
title={doc.data.name}
description={doc.data.description}
/>
);
case "session":
return (
<BasicPreview
id={doc.id}
title={doc.data.name ?? doc.created}
description={doc.data.strongStart}
/>
);
case "secret":
return <BasicPreview id={doc.id} title={doc.data.text} />;
case "scene":
return <BasicPreview id={doc.id} description={doc.data.text} />;
case "thread":
return <BasicPreview id={doc.id} title={doc.data.text} />;
case "treasure":
return <BasicPreview id={doc.id} title={doc.data.text} />;
}
};

View File

@@ -0,0 +1,33 @@
// DocumentRow.tsx
// Generic row component for displaying any document type.
import { type AnyDocument } from "@/lib/types";
import { LocationPrintRow } from "./location/LocationPrintRow";
import { MonsterPrintRow } from "./monsters/MonsterPrintRow";
import { NpcPrintRow } from "./npc/NpcPrintRow";
import { ScenePrintRow } from "./scene/ScenePrintRow";
import { SecretPrintRow } from "./secret/SecretPrintRow";
import { SessionPrintRow } from "./session/SessionPrintRow";
import { TreasurePrintRow } from "./treasure/TreasurePrintRow";
/**
* Renders a row for any document type. Prioritizes Session, then Secret, then falls back to ID and creation time.
* If rendering a SecretRow, uses the provided session prop if available.
*/
export const DocumentPrintRow = ({ document }: { document: AnyDocument }) => {
switch (document.type) {
case "location":
return <LocationPrintRow location={document} />;
case "monster":
return <MonsterPrintRow monster={document} />;
case "npc":
return <NpcPrintRow npc={document} />;
case "scene":
return <ScenePrintRow scene={document} />;
case "secret":
return <SecretPrintRow secret={document} />;
case "session":
return <SessionPrintRow session={document} />;
case "treasure":
return <TreasurePrintRow treasure={document} />;
}
};

View File

@@ -1,7 +1,7 @@
// DocumentRow.tsx // DocumentRow.tsx
// Generic row component for displaying any document type. // Generic row component for displaying any document type.
import { SecretToggleRow } from "@/components/documents/secret/SecretToggleRow"; import { SecretToggleRow } from "@/components/documents/secret/SecretToggleRow";
import { type AnyDocument } from "@/lib/types"; import { type AnyDocument, type Session } from "@/lib/types";
import { BasicRow } from "./BasicRow"; import { BasicRow } from "./BasicRow";
import { TreasureToggleRow } from "./treasure/TreasureToggleRow"; import { TreasureToggleRow } from "./treasure/TreasureToggleRow";
@@ -11,21 +11,12 @@ import { TreasureToggleRow } from "./treasure/TreasureToggleRow";
*/ */
export const DocumentRow = ({ export const DocumentRow = ({
document, document,
root, session,
}: { }: {
document: AnyDocument; document: AnyDocument;
root?: AnyDocument; session?: Session;
}) => { }) => {
switch (document.type) { switch (document.type) {
case "front":
return (
<BasicRow
doc={document}
title={document.data.name}
description={document.data.description}
/>
);
case "location": case "location":
return ( return (
<BasicRow <BasicRow
@@ -51,21 +42,18 @@ export const DocumentRow = ({
return ( return (
<BasicRow <BasicRow
doc={document} doc={document}
title={document.data.name || document.created} title={document.created}
description={document.data.strongStart} description={document.data.strongStart}
/> />
); );
case "secret": case "secret":
return <SecretToggleRow secret={document} root={root} />; return <SecretToggleRow secret={document} session={session} />;
case "scene": case "scene":
return <BasicRow doc={document} description={document.data.text} />; return <BasicRow doc={document} title={document.data.text} />;
case "thread":
return <BasicRow doc={document} description={document.data.text} />;
case "treasure": case "treasure":
return <TreasureToggleRow treasure={document} root={root} />; return <TreasureToggleRow treasure={document} session={session} />;
} }
}; };

View File

@@ -1,28 +0,0 @@
import { type AnyDocument } from "@/lib/types";
import { FormattedDate } from "../FormattedDate";
/**
* Renders the document title to go at the top a document page.
*/
export const DocumentTitle = ({ doc }: { doc: AnyDocument }) => {
return (
<h1 className="text-2xl font-bold">
<TitleText doc={doc} />
</h1>
);
};
const TitleText = ({ doc }: { doc: AnyDocument }) => {
switch (doc.type) {
case "session":
if (doc.data.name) {
return doc.data.name;
}
return <FormattedDate date={doc.created} />;
default:
// TODO: Put in proper names for other document types
return doc.type;
}
};

View File

@@ -1,112 +1,55 @@
import { useDocument } from "@/context/document/hooks"; import { RelationshipList } from "@/components/RelationshipList";
import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
import { useDocument } from "@/context/document/DocumentContext";
import { displayName, relationshipsForDocument } from "@/lib/relationships"; import { displayName, relationshipsForDocument } from "@/lib/relationships";
import { RelationshipType, type DocumentId } from "@/lib/types"; import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
import { Link } from "@tanstack/react-router"; import { Link } from "@tanstack/react-router";
import _ from "lodash";
import { Tab, TabbedLayout } from "../layout/TabbedLayout";
import { Loader } from "../Loader"; import { Loader } from "../Loader";
import { DocumentPreview } from "./DocumentPreview";
import { DocumentTitle } from "./DocumentTitle";
import { GenericEditForm } from "./GenericEditForm";
import { RelatedDocumentList } from "./RelatedDocumentList";
export function DocumentView({ export function DocumentView() {
documentId, const { state } = useDocument();
relationshipType,
childDocId,
}: {
documentId: DocumentId;
relationshipType: RelationshipType | null;
childDocId: DocumentId | null;
}) {
const { docResult } = useDocument(documentId);
if (docResult?.type !== "ready") { if (state.status === "loading") {
return <Loader />; return <Loader />;
} }
const doc = docResult.value.doc; const doc = state.doc;
const relationshipCounts = _.mapValues(docResult.value.relationships, (v) => {
if (v.type === "ready") {
return v.value.secondary.length.toString();
}
if (v.type === "empty") {
return "0";
}
return "...";
});
const relationshipList = relationshipsForDocument(doc); const relationshipList = relationshipsForDocument(doc);
return ( return (
<TabbedLayout <div key={doc.id} className="max-w-xl mx-auto py-2 px-4">
navigation={ <Link
<> to="/document/$documentId/print"
<Link params={{ documentId: doc.id }}
to="/campaigns/$campaignId" className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
params={{ campaignId: doc.campaign }} >
search={{ tab: "sessions" }} Print
className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors" </Link>
> <DocumentEditForm document={doc} />
Back to campaign <TabGroup>
</Link> <TabList className="flex flex-row flex-wrap gap-1 mt-2">
{/* Print link isn't currently working */} {relationshipList.map((relationshipType) => (
{/* <Link */} <Tab
{/* to="/document/$documentId/print" */} key={relationshipType}
{/* params={{ documentId: doc.id }} */} className="px-3 py-2 rounded bg-slate-800 text-slate-100 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 data-selected:bg-violet-900 data-selected:border-violet-700"
{/* className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors" */} >
{/* > */} {displayName(relationshipType)}
{/* Print */} </Tab>
{/* </Link> */} ))}
</> </TabList>
} <TabPanels>
title={<DocumentTitle doc={doc} />} {relationshipList.map((relationshipType) => (
tabs={[ <TabPanel key={relationshipType}>
<Tab <RelationshipList
to="/document/$documentId" key={relationshipType}
key="attributes" root={doc}
params={{ relationshipType={relationshipType}
documentId, />
}} </TabPanel>
label="Attributes" ))}
active={relationshipType === null} </TabPanels>
/>, </TabGroup>
...relationshipList.map((relationshipEntry) => ( </div>
<Tab
to="/document/$documentId/$relationshipType"
key={relationshipEntry}
params={{
documentId,
relationshipType: relationshipEntry,
}}
label={`${displayName(relationshipEntry)} (${relationshipCounts[relationshipEntry] ?? 0})`}
active={relationshipEntry === relationshipType}
/>
)),
]}
content={
relationshipType === null ? (
<GenericEditForm doc={doc} />
) : (
<RelatedDocumentList
documentId={doc.id}
relationshipType={relationshipType}
/>
)
}
flyout={childDocId && <Flyout key={childDocId} docId={childDocId} />}
/>
); );
} }
function Flyout({ docId }: { docId: DocumentId }) {
const { docResult } = useDocument(docId);
if (docResult?.type !== "ready") {
return <Loader />;
}
const doc = docResult.value.doc;
return <DocumentPreview doc={doc} />;
}

View File

@@ -1,82 +0,0 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { pb } from "@/lib/pocketbase";
import { getDocumentType, type AnyDocument } from "@/lib/types";
import { useDocumentCache } from "@/context/document/hooks";
import {
getFieldsForType,
type DocumentField,
type FieldType,
} from "@/lib/fields";
import { ToggleInput } from "../form/ToggleInput";
export type GenericFieldType = "multiline" | "singleline" | "checkbox";
export type Props<T extends AnyDocument> = {
doc: T;
};
export const GenericEditForm = <T extends AnyDocument>({ doc }: Props<T>) => {
const docType = getDocumentType(doc) as T["type"];
const fields = getFieldsForType(docType);
return (
<div className="">
{
// The type checker seems to lose the types when using Object.entries here.
fields.map((documentField) => (
<GenericEditFormField doc={doc} field={documentField} />
))
}
</div>
);
};
const GenericEditFormField = <T extends AnyDocument>({
doc,
field,
}: {
doc: T;
field: DocumentField<T["type"], FieldType>;
}) => {
const { dispatch } = useDocumentCache();
// The type checker really doesn't like indexing into this type implicitly, so we'll store it in a temporary to give it the right hints.
const data = doc.data as T["data"];
async function saveField(value: string | boolean) {
const updated: T = await pb.collection("documents").update(doc.id, {
data: field.setter(value, doc.data),
});
dispatch({ type: "setDocument", doc: updated });
}
switch (field.fieldType) {
case "longText":
return (
<AutoSaveTextarea
multiline={true}
value={field.getter(data) as string}
onSave={saveField}
id={field.name}
/>
);
case "shortText":
return (
<AutoSaveTextarea
multiline={false}
value={field.getter(data) as string}
onSave={saveField}
id={field.name}
/>
);
case "toggle":
return (
<ToggleInput
label={field.name}
value={!!field.getter(data)}
onChange={saveField}
placeholder={field.name}
/>
);
}
};

View File

@@ -1,142 +0,0 @@
import { useDocumentCache } from "@/context/document/hooks";
import { DocumentTypeLabel } from "@/lib/documents";
import {
getFieldsForType,
type DocumentField,
type FieldType,
type ValueForFieldType,
} from "@/lib/fields";
import { pb } from "@/lib/pocketbase";
import {
type CampaignId,
type DocumentData,
type DocumentsByType,
type DocumentType,
} from "@/lib/types";
import { useCallback, useState } from "react";
import { BaseForm } from "../form/BaseForm";
import { MultiLineInput } from "../form/MultiLineInput";
import { SingleLineInput } from "../form/SingleLineInput";
import { ToggleInput } from "../form/ToggleInput";
export type GenericFieldType = "multiline" | "singleline" | "checkbox";
export type Props<T extends DocumentType> = {
docType: T;
campaignId: CampaignId;
onCreate: (doc: DocumentsByType[T]) => Promise<void>;
};
export const GenericNewDocumentForm = <T extends DocumentType>({
docType,
campaignId,
onCreate,
}: Props<T>) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const { dispatch } = useDocumentCache();
const fields = getFieldsForType(docType);
const [docData, setDocData] = useState<DocumentData<T>>(
fields.reduce((d, f) => f.setDefault(d), {} as DocumentData<T>),
);
const updateData =
<F extends FieldType>(field: DocumentField<T, F>) =>
(value: ValueForFieldType<F>) =>
setDocData(field.setter(value, docData));
const saveData = useCallback(async () => {
setIsLoading(true);
console.log(`Creating ${docType}: `, docData);
try {
const newDocument: DocumentsByType[T] = await pb
.collection("documents")
.create({
campaign: campaignId,
type: docType,
data: docData,
});
await onCreate(newDocument);
dispatch({
type: "setDocument",
doc: newDocument,
});
} catch (e: unknown) {
if (e instanceof Error) {
setError(e.message);
} else {
setError("An unknown error occurred while creating the session.");
}
}
setIsLoading(false);
}, [campaignId, setIsLoading, setError, docData]);
// TODO: display name for docType
return (
<BaseForm
title={`Create new ${DocumentTypeLabel[docType]}`}
onSubmit={saveData}
isLoading={isLoading}
error={error}
content={
// The type checker seems to lose the types when using Object.entries here.
fields.map((field) => (
<GenericNewFormField
key={field.name}
field={field}
value={field.getter(docData)}
isLoading={isLoading}
onUpdate={updateData(field)}
/>
))
}
/>
);
};
const GenericNewFormField = <T extends DocumentType, F extends FieldType>({
field,
value,
isLoading,
onUpdate,
}: {
field: DocumentField<T, F>;
value: ValueForFieldType<F>;
isLoading: boolean;
onUpdate: (value: ValueForFieldType<F>) => void;
}) => {
switch (field.fieldType) {
case "longText":
return (
<MultiLineInput
label={field.name}
value={value as string}
onChange={onUpdate as (v: string) => void}
disabled={isLoading}
placeholder={field.name}
/>
);
case "shortText":
return (
<SingleLineInput
label={field.name}
value={value as string}
onChange={onUpdate as (v: string) => void}
disabled={isLoading}
placeholder={field.name}
/>
);
case "toggle":
return (
<ToggleInput
label={field.name}
value={value as boolean}
onChange={onUpdate as (v: boolean) => void}
disabled={isLoading}
placeholder={field.name}
/>
);
}
};

View File

@@ -1,33 +0,0 @@
import {
type AnyDocument,
type CampaignId,
type DocumentType,
} from "@/lib/types";
import { NewSessionForm } from "./session/NewSessionForm";
import { GenericNewDocumentForm } from "./GenericNewDocumentForm";
/**
* Renders a form for any document type depending on the relationship.
*/
export const NewCampaignDocumentForm = ({
campaignId,
docType,
onCreate,
}: {
campaignId: CampaignId;
docType: DocumentType;
onCreate: (doc: AnyDocument) => Promise<void>;
}) => {
switch (docType) {
case "session":
return <NewSessionForm campaignId={campaignId} onCreate={onCreate} />;
default:
return (
<GenericNewDocumentForm
docType={docType}
campaignId={campaignId}
onCreate={onCreate}
/>
);
}
};

View File

@@ -3,11 +3,12 @@ import {
type CampaignId, type CampaignId,
type AnyDocument, type AnyDocument,
} from "@/lib/types"; } from "@/lib/types";
import { GenericNewDocumentForm } from "./GenericNewDocumentForm"; import { NewLocationForm } from "./location/NewLocationForm";
import { docTypeForRelationshipType } from "@/lib/relationships"; import { NewMonsterForm } from "./monsters/NewMonsterForm";
import { useState } from "react"; import { NewNpcForm } from "./npc/NewNpcForm";
import { DocumentSearchForm } from "../form/DocumentSearchForm"; import { NewSceneForm } from "./scene/NewSceneForm";
import { identifierForDocType } from "@/lib/documents"; import { NewSecretForm } from "./secret/NewSecretForm";
import { NewTreasureForm } from "./treasure/NewTreasureForm";
/** /**
* Renders a form for any document type depending on the relationship. * Renders a form for any document type depending on the relationship.
@@ -21,42 +22,20 @@ export const NewRelatedDocumentForm = ({
relationshipType: RelationshipType; relationshipType: RelationshipType;
onCreate: (doc: AnyDocument) => Promise<void>; onCreate: (doc: AnyDocument) => Promise<void>;
}) => { }) => {
const [newOrExisting, setNewOrExisting] = useState<"new" | "existing">("new"); switch (relationshipType) {
case RelationshipType.Locations:
const docType = docTypeForRelationshipType(relationshipType); return <NewLocationForm campaign={campaignId} onCreate={onCreate} />;
case RelationshipType.Monsters:
return ( return <NewMonsterForm campaign={campaignId} onCreate={onCreate} />;
<div> case RelationshipType.Npcs:
<div className="flex row gap-4"> return <NewNpcForm campaign={campaignId} onCreate={onCreate} />;
<button case RelationshipType.Secrets:
className={`${newOrExisting === "new" ? "font-bold" : "text-gray-400"}`} return <NewSecretForm campaign={campaignId} onCreate={onCreate} />;
onClick={() => setNewOrExisting("new")} case RelationshipType.Treasures:
> return <NewTreasureForm campaign={campaignId} onCreate={onCreate} />;
New case RelationshipType.Scenes:
</button> return <NewSceneForm campaign={campaignId} onCreate={onCreate} />;
<button case RelationshipType.DiscoveredIn:
className={`${newOrExisting === "existing" ? "font-bold" : "text-gray-400"}`} return "Form not supported here";
onClick={() => setNewOrExisting("existing")} }
>
Existing
</button>
</div>
{newOrExisting === "new" && (
<GenericNewDocumentForm
docType={docType}
campaignId={campaignId}
onCreate={onCreate}
/>
)}
{newOrExisting === "existing" && (
// TODO: Make this into a form with a "Add" button so it's not instant
<DocumentSearchForm
campaignId={campaignId}
onSubmit={onCreate}
docType={docType}
searchField={identifierForDocType(docType)}
/>
)}
</div>
);
}; };

View File

@@ -1,27 +0,0 @@
import { useDocument } from "@/context/document/hooks";
import type { DocumentId, RelationshipType } from "@/lib/types";
import { Loader } from "../Loader";
import { RelationshipList } from "../RelationshipList";
export type Props = {
documentId: DocumentId;
relationshipType: RelationshipType;
};
export function RelatedDocumentList({ documentId, relationshipType }: Props) {
const { docResult } = useDocument(documentId);
if (docResult?.type !== "ready") {
return <Loader />;
}
const doc = docResult.value.doc;
return (
<RelationshipList
key={relationshipType}
root={doc}
relationshipType={relationshipType}
/>
);
}

View File

@@ -0,0 +1,40 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { pb } from "@/lib/pocketbase";
import type { Location } from "@/lib/types";
/**
* Renders an editable location form
*/
export const LocationEditForm = ({ location }: { location: Location }) => {
async function saveLocationName(name: string) {
await pb.collection("documents").update(location.id, {
data: {
...location.data,
name,
},
});
}
async function saveLocationDescription(description: string) {
await pb.collection("documents").update(location.id, {
data: {
...location.data,
description,
},
});
}
return (
<div className="">
<AutoSaveTextarea
multiline={false}
value={location.data.name}
onSave={saveLocationName}
/>
<AutoSaveTextarea
value={location.data.description}
onSave={saveLocationDescription}
/>
</div>
);
};

View File

@@ -0,0 +1,13 @@
import type { Location } from "@/lib/types";
/**
* Renders an print-friendly location row
*/
export const LocationPrintRow = ({ location }: { location: Location }) => {
return (
<div>
<h4>{location.data.name}</h4>
<p>{location.data.description}</p>
</div>
);
};

View File

@@ -0,0 +1,73 @@
import { useState } from "react";
import type { CampaignId, Location } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { MultiLineInput } from "@/components/form/MultiLineInput";
import { SingleLineInput } from "@/components/form/SingleLineInput";
/**
* Renders a form to add a new location. Calls onCreate with the new location document.
*/
export const NewLocationForm = ({
campaign,
onCreate,
}: {
campaign: CampaignId;
onCreate: (location: Location) => Promise<void>;
}) => {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [adding, setAdding] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setAdding(true);
setError(null);
try {
const locationDoc: Location = await pb.collection("documents").create({
campaign,
type: "location",
data: {
name,
description,
},
});
setName("");
setDescription("");
await onCreate(locationDoc);
} catch (e: any) {
setError(e?.message || "Failed to add location.");
} finally {
setAdding(false);
}
}
return (
<BaseForm
title="Create new Location"
onSubmit={handleSubmit}
isLoading={adding || !name.trim()}
error={error}
content={
<>
<SingleLineInput
label="Name"
value={name}
onChange={setName}
disabled={adding}
placeholder="Enter location name"
/>
<MultiLineInput
label="Description"
value={description}
placeholder="Enter location description"
onChange={setDescription}
disabled={adding}
/>
</>
}
/>
);
};

View File

@@ -0,0 +1,27 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { pb } from "@/lib/pocketbase";
import type { Monster } from "@/lib/types";
/**
* Renders an editable monster row
*/
export const MonsterEditForm = ({ monster }: { monster: Monster }) => {
async function saveMonsterName(name: string) {
await pb.collection("documents").update(monster.id, {
data: {
...monster.data,
name,
},
});
}
return (
<div className="">
<AutoSaveTextarea
multiline={false}
value={monster.data.name}
onSave={saveMonsterName}
/>
</div>
);
};

View File

@@ -0,0 +1,8 @@
import type { Monster } from "@/lib/types";
/**
* Renders an editable monster row
*/
export const MonsterPrintRow = ({ monster }: { monster: Monster }) => {
return <div>{monster.data.name}</div>;
};

View File

@@ -0,0 +1,58 @@
import { useState } from "react";
import type { CampaignId, Monster } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { SingleLineInput } from "@/components/form/SingleLineInput";
/**
* Renders a form to add a new monster. Calls onCreate with the new monster document.
*/
export const NewMonsterForm = ({
campaign,
onCreate,
}: {
campaign: CampaignId;
onCreate: (monster: Monster) => Promise<void>;
}) => {
const [name, setName] = useState("");
const [adding, setAdding] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setAdding(true);
setError(null);
try {
const monsterDoc: Monster = await pb.collection("documents").create({
campaign,
type: "monster",
data: {
name,
},
});
setName("");
await onCreate(monsterDoc);
} catch (e: any) {
setError(e?.message || "Failed to add monster.");
} finally {
setAdding(false);
}
}
return (
<BaseForm
title="Create new monster"
isLoading={adding || !name.trim()}
onSubmit={handleSubmit}
error={error}
content={
<SingleLineInput
value={name}
onChange={setName}
placeholder="Monster description"
/>
}
/>
);
};

View File

@@ -0,0 +1,73 @@
import { useState } from "react";
import type { CampaignId, Npc } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { SingleLineInput } from "@/components/form/SingleLineInput";
import { MultiLineInput } from "@/components/form/MultiLineInput";
/**
* Renders a form to add a new npc. Calls onCreate with the new npc document.
*/
export const NewNpcForm = ({
campaign,
onCreate,
}: {
campaign: CampaignId;
onCreate: (npc: Npc) => Promise<void>;
}) => {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [adding, setAdding] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setAdding(true);
setError(null);
try {
const npcDoc: Npc = await pb.collection("documents").create({
campaign,
type: "npc",
data: {
name,
description,
},
});
setName("");
setDescription("");
await onCreate(npcDoc);
} catch (e: any) {
setError(e?.message || "Failed to add npc.");
} finally {
setAdding(false);
}
}
return (
<BaseForm
title="Create new NPC"
onSubmit={handleSubmit}
isLoading={adding}
error={error}
content={
<>
<SingleLineInput
label="Name"
value={name}
onChange={setName}
disabled={adding}
placeholder="Enter NPC name"
/>
<MultiLineInput
label="Description"
value={description}
placeholder="Enter NPC description"
onChange={setDescription}
disabled={adding}
/>
</>
}
/>
);
};

View File

@@ -0,0 +1,40 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { pb } from "@/lib/pocketbase";
import type { Npc } from "@/lib/types";
/**
* Renders an editable npc form
*/
export const NpcEditForm = ({ npc }: { npc: Npc }) => {
async function saveNpcName(name: string) {
await pb.collection("documents").update(npc.id, {
data: {
...npc.data,
name,
},
});
}
async function saveNpcDescription(description: string) {
await pb.collection("documents").update(npc.id, {
data: {
...npc.data,
description,
},
});
}
return (
<div className="">
<AutoSaveTextarea
multiline={false}
value={npc.data.name}
onSave={saveNpcName}
/>
<AutoSaveTextarea
value={npc.data.description}
onSave={saveNpcDescription}
/>
</div>
);
};

View File

@@ -0,0 +1,13 @@
import type { Npc } from "@/lib/types";
/**
* Renders an editable npc row
*/
export const NpcPrintRow = ({ npc }: { npc: Npc }) => {
return (
<div className="">
<h4>{npc.data.name}</h4>
<p>{npc.data.description}</p>
</div>
);
};

View File

@@ -0,0 +1,64 @@
// SceneForm.tsx
// Form for adding a new scene to a session.
import { useState } from "react";
import type { CampaignId, Scene } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { MultiLineInput } from "@/components/form/MultiLineInput";
/**
* Renders a form to add a new scene. Calls onCreate with the new scene document.
*/
export const NewSceneForm = ({
campaign,
onCreate,
}: {
campaign: CampaignId;
onCreate: (scene: Scene) => Promise<void>;
}) => {
const [text, setText] = useState("");
const [adding, setAdding] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!text.trim()) return;
setAdding(true);
setError(null);
try {
const sceneDoc: Scene = await pb.collection("documents").create({
campaign,
type: "scene",
data: {
text,
},
});
setText("");
await onCreate(sceneDoc);
} catch (e: any) {
setError(e?.message || "Failed to add scene.");
} finally {
setAdding(false);
}
}
return (
<BaseForm
title="Create new scene"
onSubmit={handleSubmit}
error={error}
buttonText={adding ? "Adding..." : "Create"}
content={
<>
<MultiLineInput
value={text}
onChange={(v) => setText(v)}
disabled={adding}
placeholder="Scene description..."
aria-label="Add new scene"
/>
</>
}
/>
);
};

View File

@@ -0,0 +1,29 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { pb } from "@/lib/pocketbase";
import type { Scene } from "@/lib/types";
import { useQueryClient } from "@tanstack/react-query";
/**
* Renders an editable scene form
*/
export const SceneEditForm = ({ scene }: { scene: Scene }) => {
const queryClient = useQueryClient();
async function saveScene(text: string) {
await pb.collection("documents").update(scene.id, {
data: {
...scene.data,
text,
},
});
queryClient.invalidateQueries({
queryKey: ["relationship"],
});
}
return (
<div className="">
<AutoSaveTextarea value={scene.data.text} onSave={saveScene} />
</div>
);
};

View File

@@ -0,0 +1,8 @@
import type { Scene } from "@/lib/types";
/**
* Renders an editable scene row
*/
export const ScenePrintRow = ({ scene }: { scene: Scene }) => {
return <div className="">{scene.data.text}</div>;
};

View File

@@ -0,0 +1,61 @@
// SecretForm.tsx
// Form for adding a new secret to a session.
import { useState } from "react";
import type { CampaignId, Secret } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { SingleLineInput } from "@/components/form/SingleLineInput";
/**
* Renders a form to add a new secret. Calls onCreate with the new secret document.
*/
export const NewSecretForm = ({
campaign,
onCreate,
}: {
campaign: CampaignId;
onCreate: (secret: Secret) => Promise<void>;
}) => {
const [newSecret, setNewSecret] = useState("");
const [adding, setAdding] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!newSecret.trim()) return;
setAdding(true);
setError(null);
try {
const secretDoc: Secret = await pb.collection("documents").create({
campaign,
type: "secret",
data: {
text: newSecret,
discovered: false,
},
});
setNewSecret("");
await onCreate(secretDoc);
} catch (e: any) {
setError(e?.message || "Failed to add secret.");
} finally {
setAdding(false);
}
}
return (
<BaseForm
title="Create new treasure"
isLoading={adding || !newSecret.trim()}
onSubmit={handleSubmit}
error={error}
content={
<SingleLineInput
value={newSecret}
onChange={setNewSecret}
placeholder="Treasure description"
/>
}
/>
);
};

View File

@@ -0,0 +1,84 @@
// Displays a single secret with discovered checkbox and text.
import type { Secret, Session } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { useState } from "react";
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
/**
* Renders an editable secret form.
* Handles updating the discovered state and discoveredIn relationship.
*/
export const SecretEditForm = ({
secret,
session,
}: {
secret: Secret;
session?: Session;
}) => {
const [checked, setChecked] = useState(
!!(secret.data as any)?.secret?.discovered,
);
const [loading, setLoading] = useState(false);
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const newChecked = e.target.checked;
setLoading(true);
setChecked(newChecked);
try {
await pb.collection("documents").update(secret.id, {
data: {
...secret.data,
discovered: newChecked,
},
});
if (session || !newChecked) {
// If the session exists or the element is being unchecked, remove any
// existing discoveredIn relationship
const rels = await pb.collection("relationships").getList(1, 1, {
filter: `primary = "${secret.id}" && type = "discoveredIn"`,
});
if (rels.items.length > 0) {
await pb.collection("relationships").delete(rels.items[0].id);
}
}
if (session) {
if (newChecked) {
await pb.collection("relationships").create({
primary: secret.id,
secondary: [session.id],
type: "discoveredIn",
});
}
}
} finally {
setLoading(false);
}
}
async function saveText(text: string) {
await pb.collection("documents").update(secret.id, {
data: {
...secret.data,
text,
},
});
}
return (
<div className="flex items-center gap-3">
<input
type="checkbox"
checked={checked}
onChange={handleChange}
className="accent-emerald-500 w-5 h-5"
aria-label="Discovered"
disabled={loading}
/>
<AutoSaveTextarea
multiline={false}
value={secret.data.text}
onSave={saveText}
/>
</div>
);
};

View File

@@ -0,0 +1,24 @@
// SecretRow.tsx
// Displays a single secret with discovered checkbox and text.
import type { Secret } from "@/lib/types";
/**
* Renders a secret row with a discovered checkbox and secret text.
* Handles updating the discovered state and discoveredIn relationship.
*/
export const SecretPrintRow = ({ secret }: { secret: Secret }) => {
return (
<li className="flex items-center gap-3">
<input
type="checkbox"
className="flex-none accent-emerald-500 w-5 h-5"
aria-label="Discovered"
/>
<span>
{(secret.data as any)?.secret?.text || (
<span className="italic text-slate-400">(No secret text)</span>
)}
</span>
</li>
);
};

View File

@@ -1,9 +1,8 @@
// SecretRow.tsx // SecretRow.tsx
// Displays a single secret with discovered checkbox and text. // Displays a single secret with discovered checkbox and text.
import type { Secret, Session } from "@/lib/types";
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
import type { AnyDocument, Secret } from "@/lib/types";
import { useState } from "react"; import { useState } from "react";
import { DocumentLink } from "../DocumentLink";
/** /**
* Renders a secret row with a discovered checkbox and secret text. * Renders a secret row with a discovered checkbox and secret text.
@@ -11,10 +10,10 @@ import { DocumentLink } from "../DocumentLink";
*/ */
export const SecretToggleRow = ({ export const SecretToggleRow = ({
secret, secret,
root, session,
}: { }: {
secret: Secret; secret: Secret;
root?: AnyDocument; session?: Session;
}) => { }) => {
const [checked, setChecked] = useState( const [checked, setChecked] = useState(
!!(secret.data as any)?.secret?.discovered, !!(secret.data as any)?.secret?.discovered,
@@ -22,8 +21,6 @@ export const SecretToggleRow = ({
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) { async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
e.stopPropagation();
e.preventDefault();
const newChecked = e.target.checked; const newChecked = e.target.checked;
setLoading(true); setLoading(true);
setChecked(newChecked); setChecked(newChecked);
@@ -37,7 +34,7 @@ export const SecretToggleRow = ({
}, },
}, },
}); });
if (root || !newChecked) { if (session || !newChecked) {
// If the session exists or the element is being unchecked, remove any // If the session exists or the element is being unchecked, remove any
// existing discoveredIn relationship // existing discoveredIn relationship
const rels = await pb.collection("relationships").getList(1, 1, { const rels = await pb.collection("relationships").getList(1, 1, {
@@ -47,11 +44,11 @@ export const SecretToggleRow = ({
await pb.collection("relationships").delete(rels.items[0].id); await pb.collection("relationships").delete(rels.items[0].id);
} }
} }
if (root) { if (session) {
if (newChecked) { if (newChecked) {
await pb.collection("relationships").create({ await pb.collection("relationships").create({
primary: secret.id, primary: secret.id,
secondary: [root.id], secondary: [session.id],
type: "discoveredIn", type: "discoveredIn",
}); });
} }
@@ -62,7 +59,7 @@ export const SecretToggleRow = ({
} }
return ( return (
<div className="flex items-center justify-stretch gap-3 w-full"> <div className="flex items-center gap-3">
<input <input
type="checkbox" type="checkbox"
checked={checked} checked={checked}
@@ -71,12 +68,7 @@ export const SecretToggleRow = ({
aria-label="Discovered" aria-label="Discovered"
disabled={loading} disabled={loading}
/> />
<DocumentLink <span>{secret.data.text}</span>
childDocId={secret.id}
className="!no-underline text-slate-100 hover:underline hover:text-violet-400"
>
{secret.data.text}
</DocumentLink>
</div> </div>
); );
}; };

View File

@@ -1,57 +0,0 @@
import { useDocumentCache } from "@/context/document/hooks";
import { pb } from "@/lib/pocketbase";
import type {
AnyDocument,
CampaignId,
Relationship,
Session,
} from "@/lib/types";
import { useCallback } from "react";
import { GenericNewDocumentForm } from "../GenericNewDocumentForm";
export type Props = {
campaignId: CampaignId;
onCreate: (doc: AnyDocument) => Promise<void>;
};
export const NewSessionForm = ({ campaignId, onCreate }: Props) => {
const { dispatch } = useDocumentCache();
const createSessionRelations = useCallback(
async (newSession: Session) => {
// Check for a previous session
const prevSession = await pb
.collection("documents")
.getFirstListItem(`campaign = "${campaignId}" && type = 'session'`, {
sort: "-created",
});
// If any relations, then copy things over
if (prevSession) {
const prevRelations = await pb
.collection<Relationship>("relationships")
.getFullList({
filter: `primary = "${prevSession.id}"`,
});
for (const relation of prevRelations) {
await pb.collection("relationships").create({
primary: newSession.id,
type: relation.type,
secondary: relation.secondary,
});
}
}
await onCreate(newSession);
},
[campaignId, dispatch],
);
return (
<GenericNewDocumentForm
docType="session"
campaignId={campaignId}
onCreate={createSessionRelations}
/>
);
};

View File

@@ -0,0 +1,28 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { pb } from "@/lib/pocketbase";
import type { Session } from "@/lib/types";
export const SessionEditForm = ({ session }: { session: Session }) => {
async function saveStrongStart(strongStart: string) {
const freshRecord: Session = await pb
.collection("documents")
.update(session.id, {
data: {
...session.data,
strongStart,
},
});
}
return (
<form>
<h3 className="text-lg font-bold mb-4 text-slate-100">Strong Start</h3>
<AutoSaveTextarea
value={session.data.strongStart}
onSave={saveStrongStart}
placeholder="Enter a strong start for this session..."
aria-label="Strong Start"
/>
</form>
);
};

View File

@@ -0,0 +1,10 @@
import type { Session } from "@/lib/types";
export const SessionPrintRow = ({ session }: { session: Session }) => {
return (
<div>
<h3 className="text-lg font-bold text-slate-600">StrongStart</h3>
<div className="">{session.data.strongStart}</div>
</div>
);
};

View File

@@ -0,0 +1,18 @@
import { FormattedDate } from "@/components/FormattedDate";
import type { Session } from "@/lib/types";
import { Link } from "@tanstack/react-router";
export const SessionRow = ({ session }: { session: Session }) => {
return (
<div>
<Link
to="/document/$documentId"
params={{ documentId: session.id }}
className="block font-semibold text-lg text-slate-300"
>
<FormattedDate date={session.created} />
</Link>
<div className="">{session.data.strongStart}</div>
</div>
);
};

View File

@@ -0,0 +1,61 @@
// TreasureForm.tsx
// Form for adding a new treasure to a session.
import { useState } from "react";
import type { CampaignId, Treasure } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { BaseForm } from "@/components/form/BaseForm";
import { SingleLineInput } from "@/components/form/SingleLineInput";
/**
* Renders a form to add a new treasure. Calls onCreate with the new treasure document.
*/
export const NewTreasureForm = ({
campaign,
onCreate,
}: {
campaign: CampaignId;
onCreate: (treasure: Treasure) => Promise<void>;
}) => {
const [newTreasure, setNewTreasure] = useState("");
const [adding, setAdding] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!newTreasure.trim()) return;
setAdding(true);
setError(null);
try {
const treasureDoc: Treasure = await pb.collection("documents").create({
campaign,
type: "treasure",
data: {
text: newTreasure,
discovered: false,
},
});
setNewTreasure("");
await onCreate(treasureDoc);
} catch (e: any) {
setError(e?.message || "Failed to add treasure.");
} finally {
setAdding(false);
}
}
return (
<BaseForm
title="Create new treasure"
isLoading={adding || !newTreasure.trim()}
onSubmit={handleSubmit}
error={error}
content={
<SingleLineInput
value={newTreasure}
onChange={setNewTreasure}
placeholder="Treasure description"
/>
}
/>
);
};

View File

@@ -0,0 +1,87 @@
// Displays a single treasure with discovered checkbox and text.
import type { Treasure, Session } from "@/lib/types";
import { pb } from "@/lib/pocketbase";
import { useState } from "react";
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
/**
* Renders an editable treasure form.
* Handles updating the discovered state and discoveredIn relationship.
*/
export const TreasureEditForm = ({
treasure,
session,
}: {
treasure: Treasure;
session?: Session;
}) => {
const [checked, setChecked] = useState(
!!(treasure.data as any)?.treasure?.discovered,
);
const [loading, setLoading] = useState(false);
async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const newChecked = e.target.checked;
setLoading(true);
setChecked(newChecked);
try {
await pb.collection("documents").update(treasure.id, {
data: {
...treasure.data,
treasure: {
...(treasure.data as any).treasure,
discovered: newChecked,
},
},
});
if (session || !newChecked) {
// If the session exists or the element is being unchecked, remove any
// existing discoveredIn relationship
const rels = await pb.collection("relationships").getList(1, 1, {
filter: `primary = "${treasure.id}" && type = "discoveredIn"`,
});
if (rels.items.length > 0) {
await pb.collection("relationships").delete(rels.items[0].id);
}
}
if (session) {
if (newChecked) {
await pb.collection("relationships").create({
primary: treasure.id,
secondary: [session.id],
type: "discoveredIn",
});
}
}
} finally {
setLoading(false);
}
}
async function saveText(text: string) {
await pb.collection("documents").update(treasure.id, {
data: {
...treasure.data,
text,
},
});
}
return (
<div className="flex items-center gap-3">
<input
type="checkbox"
checked={checked}
onChange={handleChange}
className="accent-emerald-500 w-5 h-5"
aria-label="Discovered"
disabled={loading}
/>
<AutoSaveTextarea
multiline={false}
value={treasure.data.text}
onSave={saveText}
/>
</div>
);
};

View File

@@ -0,0 +1,24 @@
// TreasureRow.tsx
// Displays a single treasure with discovered checkbox and text.
import type { Treasure } from "@/lib/types";
/**
* Renders a treasure row with a discovered checkbox and treasure text.
* Handles updating the discovered state and discoveredIn relationship.
*/
export const TreasurePrintRow = ({ treasure }: { treasure: Treasure }) => {
return (
<div className="flex items-center gap-3">
<input
type="checkbox"
className="flex-none accent-emerald-500 w-5 h-5"
aria-label="Discovered"
/>
<span>
{(treasure.data as any)?.treasure?.text || (
<span className="italic text-slate-400">(No treasure text)</span>
)}
</span>
</div>
);
};

View File

@@ -1,8 +1,7 @@
// TreasureRow.tsx // TreasureRow.tsx
// Displays a single treasure with discovered checkbox and text. // Displays a single treasure with discovered checkbox and text.
import type { Treasure, Session } from "@/lib/types";
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
import type { AnyDocument, Treasure } from "@/lib/types";
import { Link } from "@tanstack/react-router";
import { useState } from "react"; import { useState } from "react";
/** /**
@@ -11,10 +10,10 @@ import { useState } from "react";
*/ */
export const TreasureToggleRow = ({ export const TreasureToggleRow = ({
treasure, treasure,
root, session,
}: { }: {
treasure: Treasure; treasure: Treasure;
root?: AnyDocument; session?: Session;
}) => { }) => {
const [checked, setChecked] = useState( const [checked, setChecked] = useState(
!!(treasure.data as any)?.treasure?.discovered, !!(treasure.data as any)?.treasure?.discovered,
@@ -35,7 +34,7 @@ export const TreasureToggleRow = ({
}, },
}, },
}); });
if (root || !newChecked) { if (session || !newChecked) {
// If the session exists or the element is being unchecked, remove any // If the session exists or the element is being unchecked, remove any
// existing discoveredIn relationship // existing discoveredIn relationship
const rels = await pb.collection("relationships").getList(1, 1, { const rels = await pb.collection("relationships").getList(1, 1, {
@@ -45,11 +44,11 @@ export const TreasureToggleRow = ({
await pb.collection("relationships").delete(rels.items[0].id); await pb.collection("relationships").delete(rels.items[0].id);
} }
} }
if (root) { if (session) {
if (newChecked) { if (newChecked) {
await pb.collection("relationships").create({ await pb.collection("relationships").create({
primary: treasure.id, primary: treasure.id,
secondary: [root.id], secondary: [session.id],
type: "discoveredIn", type: "discoveredIn",
}); });
} }
@@ -69,13 +68,7 @@ export const TreasureToggleRow = ({
aria-label="Discovered" aria-label="Discovered"
disabled={loading} disabled={loading}
/> />
<Link <span>{treasure.data.text}</span>
to="/document/$documentId/$"
params={{ documentId: treasure.id }}
className="text-lg !no-underline text-slate-100 hover:underline hover:text-violet-400"
>
{treasure.data.text}
</Link>
</div> </div>
); );
}; };

View File

@@ -16,13 +16,7 @@ export const BaseForm = ({
onSubmit, onSubmit,
}: Props) => { }: Props) => {
return ( return (
<form <form className="flex flex-col items-left gap-2" onSubmit={onSubmit}>
className="flex flex-col items-left gap-2"
onSubmit={(e) => {
e.preventDefault();
onSubmit(e);
}}
>
<h3 className="text-lg font-semibold text-slate-100">{title}</h3> <h3 className="text-lg font-semibold text-slate-100">{title}</h3>
<div className="flex flex-col gap-2 w-full items-stretch">{content}</div> <div className="flex flex-col gap-2 w-full items-stretch">{content}</div>
{error && <div className="text-red-400 mt-2 text-sm">{error}</div>} {error && <div className="text-red-400 mt-2 text-sm">{error}</div>}

View File

@@ -1,105 +0,0 @@
import { DocumentTypeLoader } from "@/context/document/DocumentTypeLoader";
import { useDocumentCache } from "@/context/document/hooks";
import type { AnyDocument, CampaignId, DocumentType } from "@/lib/types";
import {
Combobox,
ComboboxInput,
ComboboxOption,
ComboboxOptions,
} from "@headlessui/react";
import { useEffect, useState } from "react";
import { BaseForm } from "./BaseForm";
import { DocumentTypeLabel } from "@/lib/documents";
export type Props = {
campaignId: CampaignId;
docType: DocumentType;
searchField: string;
onSubmit: (doc: AnyDocument) => void;
};
export const DocumentSearchForm = (props: Props) => (
<DocumentTypeLoader
documentType={props.docType}
campaignId={props.campaignId}
>
<DocumentSearchInput {...props} />
</DocumentTypeLoader>
);
/** Utility to help with typing */
function getField(doc: AnyDocument, field: string): string | undefined {
return (doc.data as Record<string, string>)[field];
}
export const DocumentSearchInput = ({
docType,
searchField,
onSubmit,
}: Props) => {
const { cache } = useDocumentCache();
const [allOptions, setAllOptions] = useState<AnyDocument[]>([]);
useEffect(() => {
setAllOptions(
Object.values(cache.documents).flatMap((docResult) => {
if (docResult.type !== "ready") {
return [];
}
if (docResult.value.doc.type !== docType) {
return [];
}
return [docResult.value.doc];
}),
);
}, [cache, setAllOptions]);
const [queryValue, setQueryValue] = useState("");
const [selectedDoc, setSelectedDoc] = useState<AnyDocument | null>(null);
const options = allOptions.filter((doc) =>
getField(doc, searchField)
?.toLowerCase()
?.includes(queryValue.toLowerCase()),
);
return (
<BaseForm
title={`Find ${DocumentTypeLabel[docType]}`}
buttonText="Add"
error={null}
onSubmit={() => selectedDoc && onSubmit(selectedDoc)}
content={
<Combobox<AnyDocument | null>
name={searchField}
value={selectedDoc}
onChange={(doc) => {
console.log("Selected", doc);
setSelectedDoc(doc);
}}
>
<ComboboxInput
displayValue={(doc: AnyDocument) =>
(doc && getField(doc, searchField)) ?? "(no value)"
}
onChange={(event) => setQueryValue(event.target.value)}
className={`w-full p-2 rounded border bg-slate-800 text-slate-100 border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 transition-colors`}
/>
<ComboboxOptions
anchor="bottom start"
className="border empty:invisible z-50 px-4 bg-black"
>
{options.map((doc) => (
<ComboboxOption
key={doc.id}
value={doc}
className="data-selected:font-bold data-focus:font-bold"
>
{getField(doc, searchField)}
</ComboboxOption>
))}
</ComboboxOptions>
</Combobox>
}
/>
);
};

View File

@@ -1,29 +0,0 @@
export type Props = {
value: boolean;
onChange: (value: boolean) => void;
label?: string;
className?: string;
} & Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"value" | "onChange" | "className"
>;
export const ToggleInput = ({
value,
onChange,
className = "",
label,
...props
}: Props) => (
<div className="flex flex-row gap-4 p-2">
<input
type="checkbox"
checked={value}
onChange={(e) => onChange(e.target.checked)}
className={`rounded border bg-slate-800 text-slate-100 border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 transition-colors ${className}`}
aria-label={label}
{...props}
/>
{label && <label>{label}</label>}
</div>
);

View File

@@ -1,64 +0,0 @@
import { Link } from "@tanstack/react-router";
export type Props = {
title: React.ReactNode;
navigation: React.ReactNode;
tabs: React.ReactNode[];
content: React.ReactNode;
flyout?: React.ReactNode;
};
export function TabbedLayout({
navigation,
title,
tabs,
content,
flyout,
}: Props) {
return (
<div className="grow p-2 flex flex-col gap-2">
<div className="flex flex-row gap-2">{navigation}</div>
<div>{title}</div>
<div className="flex flex-col md:flex-row justify-start grow">
<div className="shrink-0 grow-0 md:w-40 p-0 flex flex-row flex-wrap md:flex-col md:flex-nowrap">
{tabs}
</div>
<div
className={`grow md:w-md p-2 bg-slate-800 border-t border-b border-r border-slate-700 ${flyout && "hidden"} md:block`}
>
{content}
</div>
{flyout && (
<div className="grow md:w-md p-2 bg-slate-800 border border-slate-700">
{flyout}
</div>
)}
</div>
</div>
);
}
export type TabProps = {
label: string;
to: string;
params?: Record<string, any>;
search?: Record<string, any>;
active?: boolean;
};
const activeTabClass =
"text-slate-100 font-bold bg-slate-800 border-t border-b border-l";
const inactiveTabClass = "text-slate-300 bg-slate-900 border";
export function Tab({ label, to, params, active, search }: TabProps) {
return (
<Link
key={label}
to={to}
params={params}
search={search}
className={`block p-2 border-slate-700 whitespace-nowrap ${active ? activeTabClass : inactiveTabClass}`}
>
{label}
</Link>
);
}

View File

@@ -1,4 +1,5 @@
import { createContext, useContext, useCallback, useState } from "react"; import { createContext, useContext, useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
import type { AuthRecord } from "pocketbase"; import type { AuthRecord } from "pocketbase";
@@ -25,49 +26,91 @@ export interface AuthContextValue {
const AuthContext = createContext<AuthContextValue | undefined>(undefined); const AuthContext = createContext<AuthContextValue | undefined>(undefined);
/** /**
* Provider for authentication context. * Fetches the currently authenticated user from PocketBase.
*/
async function fetchUser(): Promise<AuthRecord | null> {
if (pb.authStore.isValid) {
return pb.authStore.record;
}
return null;
}
/**
* Provider for authentication context, using TanStack Query for state management.
*/ */
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [isLoading, setIsLoading] = useState(false); const queryClient = useQueryClient();
const [user, setUser] = useState<AuthRecord | null>( const { data: user, isLoading } = useQuery({
pb.authStore.isValid ? pb.authStore.record : null, queryKey: ["auth", "user"],
); queryFn: fetchUser,
});
const navigate = useNavigate(); const navigate = useNavigate();
function updateUser() { const loginMutation = useMutation({
if (pb.authStore.isValid) { mutationFn: async ({
setUser(pb.authStore.record); email,
} password,
setIsLoading(false); }: {
} email: string;
password: string;
}) => {
await pb.collection("users").authWithPassword(email, password);
return fetchUser();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["auth", "user"] });
},
});
const login = useCallback(async (email: string, password: string) => { const signupMutation = useMutation({
console.log("login"); mutationFn: async ({
setIsLoading(true); email,
await pb.collection("users").authWithPassword(email, password); password,
updateUser(); passwordConfirm,
navigate({ to: "/campaigns" }); }: {
}, []); email: string;
password: string;
passwordConfirm: string;
}) => {
await pb.collection("users").create({ email, password, passwordConfirm });
await pb.collection("users").authWithPassword(email, password);
return fetchUser();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["auth", "user"] });
},
});
const logoutMutation = useMutation({
mutationFn: async () => {
pb.authStore.clear();
return null;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["auth", "user"] });
},
});
const login = useCallback(
async (email: string, password: string) => {
await loginMutation.mutateAsync({ email, password });
navigate({ to: "/campaigns" });
},
[loginMutation],
);
const signup = useCallback( const signup = useCallback(
async (email: string, password: string, passwordConfirm: string) => { async (email: string, password: string, passwordConfirm: string) => {
console.log("signup"); await signupMutation.mutateAsync({ email, password, passwordConfirm });
setIsLoading(true);
await pb.collection("users").create({ email, password, passwordConfirm });
await pb.collection("users").authWithPassword(email, password);
updateUser();
navigate({ to: "/campaigns" }); navigate({ to: "/campaigns" });
}, },
[], [signupMutation],
); );
const logout = useCallback(async () => { const logout = useCallback(async () => {
console.log("logout"); await logoutMutation.mutateAsync();
pb.authStore.clear();
setUser(null);
navigate({ to: "/" }); navigate({ to: "/" });
}, []); }, [logoutMutation]);
return ( return (
<AuthContext.Provider <AuthContext.Provider

View File

@@ -1,28 +1,64 @@
import { pb } from "@/lib/pocketbase";
import { type AnyDocument, type DocumentId } from "@/lib/types";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { createContext, useReducer } from "react"; import { createContext, useContext, useEffect, useReducer } from "react";
import type { DocumentAction } from "./actions"; import type { DocumentAction } from "./actions";
import { reducer } from "./reducer"; import { reducer } from "./reducer";
import { initialState, type DocumentState } from "./state"; import { loading, type DocumentState } from "./state";
import { useQueryClient } from "@tanstack/react-query";
import type { RecordModel } from "pocketbase";
export type DocumentContextValue = { type DocumentContextValue = {
cache: DocumentState; state: DocumentState<AnyDocument>;
dispatch: (action: DocumentAction) => void; dispatch: (action: DocumentAction<AnyDocument>) => void;
}; };
export const DocumentContext = createContext<DocumentContextValue | undefined>( const DocumentContext = createContext<DocumentContextValue | undefined>(
undefined, undefined,
); );
/** /**
* Provider for the record cache context. Provides a singleton RecordCache instance to children. * Provider for the record cache context. Provides a singleton RecordCache instance to children.
*/ */
export function DocumentProvider({ children }: { children: ReactNode }) { export function DocumentProvider({
const [state, dispatch] = useReducer(reducer, initialState()); documentId,
children,
}: {
documentId: DocumentId;
children: ReactNode;
}) {
const queryClient = useQueryClient();
const [state, dispatch] = useReducer(reducer, loading());
useEffect(() => {
async function fetchDocumentAndRelations() {
const doc: AnyDocument = await queryClient.fetchQuery({
queryKey: ["document", documentId],
staleTime: 5 * 60 * 1000, // 5 mintues
queryFn: () =>
pb.collection("documents").getOne(documentId, {
expand:
"relationships_via_primary,relationships_via_primary.secondary",
}),
});
dispatch({
type: "ready",
doc,
relationships: doc.expand?.relationships_via_primary || [],
relatedDocuments:
doc.expand?.relationships_via_primary.flatMap(
(r: RecordModel) => r.expand?.secondary,
) || [],
});
}
fetchDocumentAndRelations();
}, [documentId]);
return ( return (
<DocumentContext.Provider <DocumentContext.Provider
value={{ value={{
cache: state, state,
dispatch, dispatch,
}} }}
> >
@@ -30,3 +66,10 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
</DocumentContext.Provider> </DocumentContext.Provider>
); );
} }
export function useDocument(): DocumentContextValue {
const ctx = useContext(DocumentContext);
if (!ctx)
throw new Error("useDocument must be used within a DocumentProvider");
return ctx;
}

View File

@@ -1,51 +0,0 @@
import { pb } from "@/lib/pocketbase";
import { type AnyDocument, type DocumentId } from "@/lib/types";
import type { RecordModel } from "pocketbase";
import type { ReactNode } from "react";
import { useEffect } from "react";
import { useDocumentCache } from "./hooks";
/**
* Provider for the record cache context. Provides a singleton RecordCache instance to children.
*/
export function DocumentLoader({
documentId,
children,
}: {
documentId: DocumentId;
children: ReactNode;
}) {
const { dispatch } = useDocumentCache();
useEffect(() => {
async function fetchDocumentAndRelations() {
dispatch({
type: "loadingDocument",
docId: documentId,
});
const doc: AnyDocument = await pb
.collection("documents")
.getOne(documentId, {
expand:
"relationships_via_primary,relationships_via_primary.secondary",
});
dispatch({
type: "setDocumentTree",
doc,
relationships: doc.expand?.relationships_via_primary || [],
relatedDocuments:
doc.expand?.relationships_via_primary?.flatMap(
(r: RecordModel): AnyDocument[] =>
// Note: If there are no entries in the expanded secondaries there
// just won't be an entry instead of an empty list.
r.expand?.secondary ?? [],
) ?? [],
});
}
fetchDocumentAndRelations();
}, [documentId]);
return children;
}

View File

@@ -1,41 +0,0 @@
import { pb } from "@/lib/pocketbase";
import {
type AnyDocument,
type CampaignId,
type DocumentType,
} from "@/lib/types";
import type { ReactNode } from "react";
import { useEffect } from "react";
import { useDocumentCache } from "./hooks";
/**
* Provider for the record cache context. Provides a singleton RecordCache instance to children.
*/
export function DocumentTypeLoader({
campaignId,
documentType,
children,
}: {
campaignId: CampaignId;
documentType: DocumentType;
children: ReactNode;
}) {
const { dispatch } = useDocumentCache();
useEffect(() => {
async function fetchDocuments() {
const docs: AnyDocument[] = await pb.collection("documents").getFullList({
filter: `campaign = "${campaignId}" && type = "${documentType}"`,
});
dispatch({
type: "setDocuments",
docs: docs,
});
}
fetchDocuments();
}, [campaignId, documentType]);
return children;
}

View File

@@ -1,30 +1,24 @@
import type { AnyDocument, DocumentId, Relationship } from "@/lib/types"; import type { AnyDocument, Relationship } from "@/lib/types";
export type DocumentAction = export type DocumentAction<D extends AnyDocument> =
| { | {
type: "loadingDocument"; type: "loading";
docId: DocumentId;
} }
| { | {
type: "setDocument"; type: "ready";
doc: AnyDocument; doc: D;
}
| {
type: "setDocuments";
docs: AnyDocument[];
}
| {
type: "setRelationship";
docId: DocumentId;
relationship: Relationship;
}
| {
type: "setDocumentTree";
doc: AnyDocument;
relationships: Relationship[]; relationships: Relationship[];
relatedDocuments: AnyDocument[]; relatedDocuments: AnyDocument[];
} }
| { | {
type: "removeDocument"; type: "update";
docId: DocumentId; data: D["data"];
}
| {
type: "setRelationship";
relationship: Relationship;
}
| {
type: "setRelatedDocument";
doc: AnyDocument;
}; };

View File

@@ -1,23 +0,0 @@
import type { DocumentId } from "@/lib/types";
import { useContext } from "react";
import { DocumentContext } from "./DocumentContext";
export function useDocument(id: DocumentId) {
const ctx = useContext(DocumentContext);
if (!ctx)
throw new Error("useDocument must be used within a DocumentProvider");
return {
docResult: ctx.cache.documents[id],
dispatch: ctx.dispatch,
};
}
export function useDocumentCache() {
const ctx = useContext(DocumentContext);
if (!ctx)
throw new Error("useDocument must be used within a DocumentProvider");
return {
cache: ctx.cache,
dispatch: ctx.dispatch,
};
}

View File

@@ -1,173 +1,75 @@
import { relationshipsForDocument } from "@/lib/relationships";
import type { AnyDocument, DocumentId, Relationship } from "@/lib/types";
import _ from "lodash"; import _ from "lodash";
import type {
AnyDocument,
DocumentId,
Relationship,
RelationshipId,
RelationshipType,
} from "@/lib/types";
import type { DocumentAction } from "./actions"; import type { DocumentAction } from "./actions";
import { import type { DocumentState } from "./state";
empty,
loading,
mapResult,
ready,
unloaded,
type DocumentState,
} from "./state";
function setLoadingDocument( function ifStatus<D extends AnyDocument, S extends DocumentState<D>["status"]>(
docId: DocumentId, status: S,
state: DocumentState, state: DocumentState<D>,
): DocumentState { newState: (state: DocumentState<D> & { status: S }) => DocumentState<D>,
return { ) {
...state, // TODO: Is there a better way to express the type of type narrowing?
documents: { return state.status === status
...state.documents, ? newState(state as DocumentState<D> & { status: S })
[docId]: loading(), : state;
},
};
} }
function setDocument(state: DocumentState, doc: AnyDocument): DocumentState { export function reducer<D extends AnyDocument>(
const previous = state.documents[doc.id]; state: DocumentState<D>,
const relationships = action: DocumentAction<D>,
previous?.type === "ready" ): DocumentState<D> {
? previous.value.relationships
: Object.fromEntries(
relationshipsForDocument(doc).map((relationshipType) => [
relationshipType,
unloaded(),
]),
);
return {
...state,
documents: {
...state.documents,
[doc.id]: ready({
doc: doc,
relationships,
}),
},
};
}
function setAllRelationshipsEmpty(
docId: DocumentId,
state: DocumentState,
): DocumentState {
const prevDocResult = state.documents[docId];
if (prevDocResult?.type !== "ready") {
return state;
}
const prevDoc = prevDocResult.value.doc;
const relationships = prevDocResult.value.relationships;
return {
...state,
documents: {
...state.documents,
[docId]: ready({
...prevDocResult.value,
relationships: Object.fromEntries(
relationshipsForDocument(prevDoc).map((relType) =>
relationships[relType]?.type === "ready"
? [relType, relationships[relType]]
: [relType, empty()],
),
),
}),
},
};
}
function setRelationship(
docId: DocumentId,
state: DocumentState,
relationship: Relationship,
): DocumentState {
const previousResult = state.documents[docId];
if (previousResult?.type !== "ready") {
return state;
}
const previousEntry = previousResult.value;
return {
...state,
documents: {
...state.documents,
[docId]: ready({
...previousEntry,
relationships: {
...previousEntry.relationships,
[relationship.type]: ready(relationship),
},
}),
},
};
}
function removeDocument(
docId: DocumentId,
state: DocumentState,
): DocumentState {
const remainingDocs: DocumentState["documents"] = _.omit(state.documents, [
docId,
]);
return {
...state,
documents: _.mapValues(remainingDocs, (result) => {
if (result.type !== "ready") {
return result;
}
return ready({
doc: result.value.doc,
relationships: _.mapValues(
result.value.relationships,
(relationshipResult) =>
mapResult(relationshipResult, (relationship) => ({
...relationship,
secondary: relationship.secondary.filter(
(relatedId) => relatedId !== docId,
),
})),
),
});
}),
};
}
export function reducer(
initialState: DocumentState,
action: DocumentAction,
): DocumentState {
console.debug("Processing action", action);
switch (action.type) { switch (action.type) {
case "loadingDocument": case "loading":
return setLoadingDocument(action.docId, initialState); return {
case "setDocument": status: "loading",
return setDocument(initialState, action.doc); };
case "setDocuments": case "ready":
return action.docs.reduce(setDocument, initialState); return {
status: "ready",
doc: action.doc,
relationships: _.keyBy(action.relationships, (r) => r.type) as Record<
RelationshipType,
Relationship
>,
relatedDocs: _.keyBy(action.relatedDocuments, (r) => r.id) as Record<
DocumentId,
AnyDocument
>,
};
case "update":
if (state.status === "ready") {
return {
...state,
doc: {
...state.doc,
data: action.data,
},
};
} else {
return state;
}
case "setRelationship": case "setRelationship":
return setRelationship(action.docId, initialState, action.relationship); return ifStatus("ready", state, (state) => ({
case "setDocumentTree": ...state,
const updatedDocumentState = setAllRelationshipsEmpty( relationships: {
action.doc.id, ...state.relationships,
setDocument(initialState, action.doc), [action.relationship.type]: action.relationship,
); },
}));
const updatedRelationshipsState = action.relationships.reduce( case "setRelatedDocument":
setRelationship.bind(null, action.doc.id), return ifStatus("ready", state, (state) => ({
updatedDocumentState, ...state,
); relatedDocs: {
...state.relatedDocs,
const emptyRemainingRelationships = setAllRelationshipsEmpty( [action.doc.id]: action.doc,
action.doc.id, },
updatedRelationshipsState, }));
);
return action.relatedDocuments.reduce(
setDocument,
emptyRemainingRelationships,
);
case "removeDocument":
return removeDocument(action.docId, initialState);
} }
} }

View File

@@ -1,55 +1,21 @@
import type { import type {
AnyDocument, AnyDocument,
DocumentId, DocumentId,
DocumentType,
Relationship, Relationship,
RelationshipType, RelationshipType,
} from "@/lib/types"; } from "@/lib/types";
export type Result<V> = export type DocumentState<D extends AnyDocument> =
| { type: "unloaded" } | {
| { type: "error"; err: unknown } status: "loading";
| { type: "loading" } }
| { type: "empty" } | {
| { type: "ready"; value: V }; status: "ready";
doc: D;
relationships: Record<RelationshipType, Relationship>;
relatedDocs: Record<DocumentId, AnyDocument>;
};
export const unloaded = (): Result<any> => ({ type: "unloaded" }); export const loading = <D extends AnyDocument>(): DocumentState<D> => ({
export const error = (err: unknown): Result<any> => ({ type: "error", err }); status: "loading",
export const loading = (): Result<any> => ({ type: "loading" }); });
export const empty = (): Result<any> => ({ type: "empty" });
export const ready = <V>(value: V): Result<V> => ({ type: "ready", value });
export const mapResult = <A, B>(
result: Result<A>,
f: (a: A) => B,
): Result<B> => {
if (result.type === "ready") {
return ready(f(result.value));
}
return result;
};
export type DocumentState = {
documents: Record<
DocumentId,
Result<{
doc: AnyDocument;
relationships: Record<RelationshipType, Result<Relationship>>;
}>
>;
};
export const initialState = (): DocumentState =>
({
documents: {},
}) as DocumentState;
export const getAllDocumentsOfType = <T extends DocumentType>(
docType: T,
state: DocumentState,
): (AnyDocument & { type: T })[] =>
Object.values(state.documents).flatMap((docRecord) =>
docRecord.type === "ready" && docRecord.value.doc.type === docType
? [docRecord.value.doc as AnyDocument & { type: T }]
: [],
);

View File

@@ -1,62 +0,0 @@
import { useParams } from "@tanstack/react-router";
import * as z from "zod";
import type { RelationshipType, DocumentId } from "./types";
const documentParams = z
.templateLiteral([
z.string(),
z.optional(z.literal("/")),
z.optional(z.string()),
])
.pipe(
z.transform((path: string) => {
if (path === "") {
return {
relationshipType: null,
childDocId: null,
};
}
const [relationshipType, childDocId] = path.split("/");
return {
relationshipType: (relationshipType ?? null) as RelationshipType | null,
childDocId: (childDocId ?? null) as DocumentId | null,
};
}),
);
export function useDocumentPath():
| {
documentId: DocumentId;
relationshipType: RelationshipType | null;
childDocId: DocumentId | null;
}
| undefined {
const params = useParams({
from: "/_app/_authenticated/document/$documentId/$",
shouldThrow: false,
});
if (params) {
const { relationshipType, childDocId } = documentParams.parse(
params._splat,
);
return {
documentId: params.documentId as DocumentId,
relationshipType,
childDocId,
};
}
return undefined;
}
export function makeDocumentPath(
documentId: DocumentId,
relationshipType?: RelationshipType | null,
childDocId?: DocumentId | null,
) {
return (
"/document/" +
[documentId, relationshipType, childDocId].filter((x) => x).join("/")
);
}

View File

@@ -1,37 +0,0 @@
import type { DocumentType } from "./types";
export const DocumentTypeLabel: Record<DocumentType, string> = {
session: "Session",
secret: "Secret",
npc: "NPC",
location: "Location",
thread: "Thread",
front: "Front",
monster: "Monster",
scene: "Scene",
treasure: "Treasure",
};
export const DocumentTypeLabePlural: Record<DocumentType, string> = {
session: "Sessions",
secret: "Secrets",
npc: "NPCs",
location: "Locations",
thread: "Threads",
front: "Fronts",
monster: "Monsters",
scene: "Scenes",
treasure: "Treasures",
};
export function identifierForDocType(docType: DocumentType): string {
switch (docType) {
case "scene":
case "secret":
case "thread":
case "treasure":
return "text";
default:
return "name";
}
}

View File

@@ -1,106 +0,0 @@
import { type DocumentData, type DocumentType } from "./types";
export type FieldType = "identifier" | "shortText" | "longText" | "toggle";
export type ValueForFieldType<F extends FieldType> = {
identifier: string;
shortText: string;
longText: string;
toggle: boolean;
}[F];
function defaultValue<F extends FieldType>(fieldType: F): ValueForFieldType<F> {
switch (fieldType) {
case "identifier":
case "shortText":
case "longText":
return "" as ValueForFieldType<F>;
case "toggle":
return false as ValueForFieldType<F>;
}
}
export type DocumentField<D extends DocumentType, F extends FieldType> = {
name: string;
fieldType: F;
getter: (doc: DocumentData<D>) => ValueForFieldType<F>;
setter: (
value: ValueForFieldType<F>,
doc: DocumentData<D>,
) => DocumentData<D>;
setDefault: (doc: DocumentData<D>) => DocumentData<D>;
};
const simpleField = <D extends DocumentType, F extends FieldType>(
name: string,
key: keyof DocumentData<D>,
fieldType: F,
): DocumentField<D, F> => ({
name,
fieldType,
getter: (doc) => doc[key] as unknown as ValueForFieldType<F>,
setter: (value, doc) => ({ ...doc, [key]: value }),
setDefault: (doc) => ({ ...doc, [key]: defaultValue(fieldType) }),
});
const simpleFields = <D extends DocumentType>(
fields: Record<string, [keyof DocumentData<D>, FieldType]>,
): DocumentField<D, FieldType>[] =>
Object.entries(fields).map(([name, [key, fieldType]]) =>
simpleField(name, key, fieldType),
);
export function getFieldsForType<D extends DocumentType>(
docType: D,
): DocumentField<D, FieldType>[] {
// Explicit casts are required because the getter function puts the type D in the parameters position and thus the specialized getter is not valid in the case of the more general document type.
// While the switch correctly sees that D is now "front", the _type_ could be a union and thus the getter needs to be able to accept any of them.
// I know this will only ever be called in the context of one value, but this is clearly abusing the type system.
// TODO: Fix the types
switch (docType) {
case "front":
return simpleFields<"front">({
Name: ["name", "shortText"],
Description: ["description", "longText"],
Resolved: ["resolved", "toggle"],
}) as unknown as DocumentField<D, FieldType>[];
case "location":
return simpleFields<"location">({
Name: ["name", "shortText"],
Description: ["description", "longText"],
}) as unknown as DocumentField<D, FieldType>[];
case "monster":
return simpleFields<"monster">({
Name: ["name", "shortText"],
}) as unknown as DocumentField<D, FieldType>[];
case "npc":
return simpleFields<"npc">({
Name: ["name", "shortText"],
Description: ["description", "longText"],
}) as unknown as DocumentField<D, FieldType>[];
case "scene":
return simpleFields<"scene">({
Text: ["text", "longText"],
}) as unknown as DocumentField<D, FieldType>[];
case "secret":
return simpleFields<"secret">({
Discovered: ["discovered", "toggle"],
Text: ["text", "shortText"],
}) as unknown as DocumentField<D, FieldType>[];
case "session":
return simpleFields<"session">({
Name: ["name", "shortText"],
"Strong Start": ["strongStart", "longText"],
}) as unknown as DocumentField<D, FieldType>[];
case "thread":
return simpleFields<"thread">({
Resolved: ["resolved", "toggle"],
Text: ["text", "shortText"],
}) as unknown as DocumentField<D, FieldType>[];
case "treasure":
return simpleFields<"treasure">({
Discovered: ["discovered", "toggle"],
Text: ["text", "shortText"],
}) as unknown as DocumentField<D, FieldType>[];
}
}

View File

@@ -1,9 +1,4 @@
import { import { getDocumentType, RelationshipType, type AnyDocument } from "./types";
getDocumentType,
RelationshipType,
type AnyDocument,
type DocumentType,
} from "./types";
export function displayName(relationshipType: RelationshipType) { export function displayName(relationshipType: RelationshipType) {
return relationshipType.charAt(0).toUpperCase() + relationshipType.slice(1); return relationshipType.charAt(0).toUpperCase() + relationshipType.slice(1);
@@ -24,17 +19,3 @@ export function relationshipsForDocument(doc: AnyDocument): RelationshipType[] {
return []; return [];
} }
} }
const DocTypeForRelationshipType: { [k in RelationshipType]: DocumentType } = {
[RelationshipType.DiscoveredIn]: "session",
[RelationshipType.Locations]: "location",
[RelationshipType.Monsters]: "monster",
[RelationshipType.Npcs]: "npc",
[RelationshipType.Scenes]: "scene",
[RelationshipType.Secrets]: "secret",
[RelationshipType.Treasures]: "treasure",
} as const;
export function docTypeForRelationshipType(rt: RelationshipType): DocumentType {
return DocTypeForRelationshipType[rt];
}

View File

@@ -65,16 +65,19 @@ export type Relationship = RecordModel & {
******************************************/ ******************************************/
export type DocumentType = export type DocumentType =
| "front"
| "location" | "location"
| "monster" | "monster"
| "npc" | "npc"
| "scene" | "scene"
| "secret" | "secret"
| "session" | "session"
| "thread"
| "treasure"; | "treasure";
export type DocumentData<Type extends DocumentType, Data> = {
type: Type;
data: Data;
};
export type Document<Type extends DocumentType, Data> = RecordModel & { export type Document<Type extends DocumentType, Data> = RecordModel & {
id: DocumentId; id: DocumentId;
collectionName: typeof CollectionIds.Documents; collectionName: typeof CollectionIds.Documents;
@@ -87,33 +90,14 @@ export type Document<Type extends DocumentType, Data> = RecordModel & {
}; };
export type AnyDocument = export type AnyDocument =
| Front
| Location | Location
| Monster | Monster
| Npc | Npc
| Scene | Scene
| Secret | Secret
| Session | Session
| Thread
| Treasure; | Treasure;
export type DocumentsByType = {
front: Front;
location: Location;
monster: Monster;
npc: Npc;
scene: Scene;
secret: Secret;
session: Session;
thread: Thread;
treasure: Treasure;
};
export type DocumentData<Type extends DocumentType> =
DocumentsByType[Type]["data"];
export type GetDocumentType<D extends AnyDocument> = D["type"];
export function getDocumentType(doc: AnyDocument): DocumentType { export function getDocumentType(doc: AnyDocument): DocumentType {
return doc.type; return doc.type;
} }
@@ -151,7 +135,6 @@ export type Npc = Document<
export type Session = Document< export type Session = Document<
"session", "session",
{ {
name?: string;
strongStart: string; strongStart: string;
} }
>; >;
@@ -184,24 +167,3 @@ export type Treasure = Document<
discovered: boolean; discovered: boolean;
} }
>; >;
/** Thread **/
export type Thread = Document<
"thread",
{
text: string;
resolved: boolean;
}
>;
/** Front **/
export type Front = Document<
"front",
{
name: string;
description: string;
resolved: boolean;
}
>;

View File

@@ -1,6 +1,7 @@
import { StrictMode } from "react"; import { StrictMode } from "react";
import ReactDOM from "react-dom/client"; import ReactDOM from "react-dom/client";
import { RouterProvider, createRouter } from "@tanstack/react-router"; import { RouterProvider, createRouter } from "@tanstack/react-router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Import the generated route tree // Import the generated route tree
import { routeTree } from "./routeTree.gen"; import { routeTree } from "./routeTree.gen";
@@ -8,13 +9,16 @@ import { routeTree } from "./routeTree.gen";
import "./styles.css"; import "./styles.css";
import reportWebVitals from "./reportWebVitals.ts"; import reportWebVitals from "./reportWebVitals.ts";
const queryClient = new QueryClient();
// Create a new router instance // Create a new router instance
const router = createRouter({ const router = createRouter({
routeTree, routeTree,
context: { queryClient },
defaultPreload: "intent", defaultPreload: "intent",
scrollRestoration: true, scrollRestoration: true,
defaultStructuralSharing: true, defaultStructuralSharing: true,
defaultPendingMinMs: 0, defaultPreloadStaleTime: 0,
}); });
// Register the router instance for type safety // Register the router instance for type safety
@@ -30,7 +34,9 @@ if (rootElement && !rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement); const root = ReactDOM.createRoot(rootElement);
root.render( root.render(
<StrictMode> <StrictMode>
<RouterProvider router={router} /> <QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</StrictMode>, </StrictMode>,
); );
} }

View File

@@ -17,8 +17,9 @@ import { Route as AppLoginImport } from './routes/_app/login'
import { Route as AppAboutImport } from './routes/_app/about' import { Route as AppAboutImport } from './routes/_app/about'
import { Route as AppAuthenticatedImport } from './routes/_app/_authenticated' import { Route as AppAuthenticatedImport } from './routes/_app/_authenticated'
import { Route as AppAuthenticatedCampaignsIndexImport } from './routes/_app/_authenticated/campaigns.index' import { Route as AppAuthenticatedCampaignsIndexImport } from './routes/_app/_authenticated/campaigns.index'
import { Route as AppAuthenticatedDocumentDocumentIdImport } from './routes/_app/_authenticated/document.$documentId'
import { Route as AppAuthenticatedCampaignsCampaignIdImport } from './routes/_app/_authenticated/campaigns.$campaignId' import { Route as AppAuthenticatedCampaignsCampaignIdImport } from './routes/_app/_authenticated/campaigns.$campaignId'
import { Route as AppAuthenticatedDocumentDocumentIdSplatImport } from './routes/_app/_authenticated/document.$documentId.$' import { Route as AppauthenticatedDocumentDocumentIdPrintImport } from './routes/_app_._authenticated.document_.$documentId.print'
// Create/Update Routes // Create/Update Routes
@@ -57,6 +58,13 @@ const AppAuthenticatedCampaignsIndexRoute =
getParentRoute: () => AppAuthenticatedRoute, getParentRoute: () => AppAuthenticatedRoute,
} as any) } as any)
const AppAuthenticatedDocumentDocumentIdRoute =
AppAuthenticatedDocumentDocumentIdImport.update({
id: '/document/$documentId',
path: '/document/$documentId',
getParentRoute: () => AppAuthenticatedRoute,
} as any)
const AppAuthenticatedCampaignsCampaignIdRoute = const AppAuthenticatedCampaignsCampaignIdRoute =
AppAuthenticatedCampaignsCampaignIdImport.update({ AppAuthenticatedCampaignsCampaignIdImport.update({
id: '/campaigns/$campaignId', id: '/campaigns/$campaignId',
@@ -64,11 +72,11 @@ const AppAuthenticatedCampaignsCampaignIdRoute =
getParentRoute: () => AppAuthenticatedRoute, getParentRoute: () => AppAuthenticatedRoute,
} as any) } as any)
const AppAuthenticatedDocumentDocumentIdSplatRoute = const AppauthenticatedDocumentDocumentIdPrintRoute =
AppAuthenticatedDocumentDocumentIdSplatImport.update({ AppauthenticatedDocumentDocumentIdPrintImport.update({
id: '/document/$documentId/$', id: '/_app_/_authenticated/document_/$documentId/print',
path: '/document/$documentId/$', path: '/document/$documentId/print',
getParentRoute: () => AppAuthenticatedRoute, getParentRoute: () => rootRoute,
} as any) } as any)
// Populate the FileRoutesByPath interface // Populate the FileRoutesByPath interface
@@ -117,6 +125,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppAuthenticatedCampaignsCampaignIdImport preLoaderRoute: typeof AppAuthenticatedCampaignsCampaignIdImport
parentRoute: typeof AppAuthenticatedImport parentRoute: typeof AppAuthenticatedImport
} }
'/_app/_authenticated/document/$documentId': {
id: '/_app/_authenticated/document/$documentId'
path: '/document/$documentId'
fullPath: '/document/$documentId'
preLoaderRoute: typeof AppAuthenticatedDocumentDocumentIdImport
parentRoute: typeof AppAuthenticatedImport
}
'/_app/_authenticated/campaigns/': { '/_app/_authenticated/campaigns/': {
id: '/_app/_authenticated/campaigns/' id: '/_app/_authenticated/campaigns/'
path: '/campaigns' path: '/campaigns'
@@ -124,12 +139,12 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppAuthenticatedCampaignsIndexImport preLoaderRoute: typeof AppAuthenticatedCampaignsIndexImport
parentRoute: typeof AppAuthenticatedImport parentRoute: typeof AppAuthenticatedImport
} }
'/_app/_authenticated/document/$documentId/$': { '/_app_/_authenticated/document_/$documentId/print': {
id: '/_app/_authenticated/document/$documentId/$' id: '/_app_/_authenticated/document_/$documentId/print'
path: '/document/$documentId/$' path: '/document/$documentId/print'
fullPath: '/document/$documentId/$' fullPath: '/document/$documentId/print'
preLoaderRoute: typeof AppAuthenticatedDocumentDocumentIdSplatImport preLoaderRoute: typeof AppauthenticatedDocumentDocumentIdPrintImport
parentRoute: typeof AppAuthenticatedImport parentRoute: typeof rootRoute
} }
} }
} }
@@ -138,16 +153,16 @@ declare module '@tanstack/react-router' {
interface AppAuthenticatedRouteChildren { interface AppAuthenticatedRouteChildren {
AppAuthenticatedCampaignsCampaignIdRoute: typeof AppAuthenticatedCampaignsCampaignIdRoute AppAuthenticatedCampaignsCampaignIdRoute: typeof AppAuthenticatedCampaignsCampaignIdRoute
AppAuthenticatedDocumentDocumentIdRoute: typeof AppAuthenticatedDocumentDocumentIdRoute
AppAuthenticatedCampaignsIndexRoute: typeof AppAuthenticatedCampaignsIndexRoute AppAuthenticatedCampaignsIndexRoute: typeof AppAuthenticatedCampaignsIndexRoute
AppAuthenticatedDocumentDocumentIdSplatRoute: typeof AppAuthenticatedDocumentDocumentIdSplatRoute
} }
const AppAuthenticatedRouteChildren: AppAuthenticatedRouteChildren = { const AppAuthenticatedRouteChildren: AppAuthenticatedRouteChildren = {
AppAuthenticatedCampaignsCampaignIdRoute: AppAuthenticatedCampaignsCampaignIdRoute:
AppAuthenticatedCampaignsCampaignIdRoute, AppAuthenticatedCampaignsCampaignIdRoute,
AppAuthenticatedDocumentDocumentIdRoute:
AppAuthenticatedDocumentDocumentIdRoute,
AppAuthenticatedCampaignsIndexRoute: AppAuthenticatedCampaignsIndexRoute, AppAuthenticatedCampaignsIndexRoute: AppAuthenticatedCampaignsIndexRoute,
AppAuthenticatedDocumentDocumentIdSplatRoute:
AppAuthenticatedDocumentDocumentIdSplatRoute,
} }
const AppAuthenticatedRouteWithChildren = const AppAuthenticatedRouteWithChildren =
@@ -175,8 +190,9 @@ export interface FileRoutesByFullPath {
'/login': typeof AppLoginRoute '/login': typeof AppLoginRoute
'/': typeof AppIndexRoute '/': typeof AppIndexRoute
'/campaigns/$campaignId': typeof AppAuthenticatedCampaignsCampaignIdRoute '/campaigns/$campaignId': typeof AppAuthenticatedCampaignsCampaignIdRoute
'/document/$documentId': typeof AppAuthenticatedDocumentDocumentIdRoute
'/campaigns': typeof AppAuthenticatedCampaignsIndexRoute '/campaigns': typeof AppAuthenticatedCampaignsIndexRoute
'/document/$documentId/$': typeof AppAuthenticatedDocumentDocumentIdSplatRoute '/document/$documentId/print': typeof AppauthenticatedDocumentDocumentIdPrintRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
@@ -185,8 +201,9 @@ export interface FileRoutesByTo {
'/login': typeof AppLoginRoute '/login': typeof AppLoginRoute
'/': typeof AppIndexRoute '/': typeof AppIndexRoute
'/campaigns/$campaignId': typeof AppAuthenticatedCampaignsCampaignIdRoute '/campaigns/$campaignId': typeof AppAuthenticatedCampaignsCampaignIdRoute
'/document/$documentId': typeof AppAuthenticatedDocumentDocumentIdRoute
'/campaigns': typeof AppAuthenticatedCampaignsIndexRoute '/campaigns': typeof AppAuthenticatedCampaignsIndexRoute
'/document/$documentId/$': typeof AppAuthenticatedDocumentDocumentIdSplatRoute '/document/$documentId/print': typeof AppauthenticatedDocumentDocumentIdPrintRoute
} }
export interface FileRoutesById { export interface FileRoutesById {
@@ -197,8 +214,9 @@ export interface FileRoutesById {
'/_app/login': typeof AppLoginRoute '/_app/login': typeof AppLoginRoute
'/_app/': typeof AppIndexRoute '/_app/': typeof AppIndexRoute
'/_app/_authenticated/campaigns/$campaignId': typeof AppAuthenticatedCampaignsCampaignIdRoute '/_app/_authenticated/campaigns/$campaignId': typeof AppAuthenticatedCampaignsCampaignIdRoute
'/_app/_authenticated/document/$documentId': typeof AppAuthenticatedDocumentDocumentIdRoute
'/_app/_authenticated/campaigns/': typeof AppAuthenticatedCampaignsIndexRoute '/_app/_authenticated/campaigns/': typeof AppAuthenticatedCampaignsIndexRoute
'/_app/_authenticated/document/$documentId/$': typeof AppAuthenticatedDocumentDocumentIdSplatRoute '/_app_/_authenticated/document_/$documentId/print': typeof AppauthenticatedDocumentDocumentIdPrintRoute
} }
export interface FileRouteTypes { export interface FileRouteTypes {
@@ -209,8 +227,9 @@ export interface FileRouteTypes {
| '/login' | '/login'
| '/' | '/'
| '/campaigns/$campaignId' | '/campaigns/$campaignId'
| '/document/$documentId'
| '/campaigns' | '/campaigns'
| '/document/$documentId/$' | '/document/$documentId/print'
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: to:
| '' | ''
@@ -218,8 +237,9 @@ export interface FileRouteTypes {
| '/login' | '/login'
| '/' | '/'
| '/campaigns/$campaignId' | '/campaigns/$campaignId'
| '/document/$documentId'
| '/campaigns' | '/campaigns'
| '/document/$documentId/$' | '/document/$documentId/print'
id: id:
| '__root__' | '__root__'
| '/_app' | '/_app'
@@ -228,17 +248,21 @@ export interface FileRouteTypes {
| '/_app/login' | '/_app/login'
| '/_app/' | '/_app/'
| '/_app/_authenticated/campaigns/$campaignId' | '/_app/_authenticated/campaigns/$campaignId'
| '/_app/_authenticated/document/$documentId'
| '/_app/_authenticated/campaigns/' | '/_app/_authenticated/campaigns/'
| '/_app/_authenticated/document/$documentId/$' | '/_app_/_authenticated/document_/$documentId/print'
fileRoutesById: FileRoutesById fileRoutesById: FileRoutesById
} }
export interface RootRouteChildren { export interface RootRouteChildren {
AppRoute: typeof AppRouteWithChildren AppRoute: typeof AppRouteWithChildren
AppauthenticatedDocumentDocumentIdPrintRoute: typeof AppauthenticatedDocumentDocumentIdPrintRoute
} }
const rootRouteChildren: RootRouteChildren = { const rootRouteChildren: RootRouteChildren = {
AppRoute: AppRouteWithChildren, AppRoute: AppRouteWithChildren,
AppauthenticatedDocumentDocumentIdPrintRoute:
AppauthenticatedDocumentDocumentIdPrintRoute,
} }
export const routeTree = rootRoute export const routeTree = rootRoute
@@ -251,7 +275,8 @@ export const routeTree = rootRoute
"__root__": { "__root__": {
"filePath": "__root.tsx", "filePath": "__root.tsx",
"children": [ "children": [
"/_app" "/_app",
"/_app_/_authenticated/document_/$documentId/print"
] ]
}, },
"/_app": { "/_app": {
@@ -268,8 +293,8 @@ export const routeTree = rootRoute
"parent": "/_app", "parent": "/_app",
"children": [ "children": [
"/_app/_authenticated/campaigns/$campaignId", "/_app/_authenticated/campaigns/$campaignId",
"/_app/_authenticated/campaigns/", "/_app/_authenticated/document/$documentId",
"/_app/_authenticated/document/$documentId/$" "/_app/_authenticated/campaigns/"
] ]
}, },
"/_app/about": { "/_app/about": {
@@ -288,13 +313,16 @@ export const routeTree = rootRoute
"filePath": "_app/_authenticated/campaigns.$campaignId.tsx", "filePath": "_app/_authenticated/campaigns.$campaignId.tsx",
"parent": "/_app/_authenticated" "parent": "/_app/_authenticated"
}, },
"/_app/_authenticated/document/$documentId": {
"filePath": "_app/_authenticated/document.$documentId.tsx",
"parent": "/_app/_authenticated"
},
"/_app/_authenticated/campaigns/": { "/_app/_authenticated/campaigns/": {
"filePath": "_app/_authenticated/campaigns.index.tsx", "filePath": "_app/_authenticated/campaigns.index.tsx",
"parent": "/_app/_authenticated" "parent": "/_app/_authenticated"
}, },
"/_app/_authenticated/document/$documentId/$": { "/_app_/_authenticated/document_/$documentId/print": {
"filePath": "_app/_authenticated/document.$documentId.$.tsx", "filePath": "_app_._authenticated.document_.$documentId.print.tsx"
"parent": "/_app/_authenticated"
} }
} }
} }

View File

@@ -1,5 +1,5 @@
import { AuthProvider } from "@/context/auth/AuthContext"; import { AuthProvider } from "@/context/auth/AuthContext";
import { DocumentProvider } from "@/context/document/DocumentContext"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { Outlet, createRootRoute } from "@tanstack/react-router"; import { Outlet, createRootRoute } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools"; import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
@@ -7,11 +7,10 @@ export const Route = createRootRoute({
component: () => ( component: () => (
<> <>
<AuthProvider> <AuthProvider>
<DocumentProvider> <Outlet />
<Outlet />
</DocumentProvider>
</AuthProvider> </AuthProvider>
<TanStackRouterDevtools /> <TanStackRouterDevtools />
<ReactQueryDevtools buttonPosition="bottom-right" />
</> </>
), ),
}); });

View File

@@ -1,111 +1,128 @@
import { CampaignDocuments } from "@/components/campaign/CampaignDocuments"; import { useCallback } from "react";
import { DocumentPreview } from "@/components/documents/DocumentPreview";
import { Tab, TabbedLayout } from "@/components/layout/TabbedLayout";
import { Loader } from "@/components/Loader";
import { DocumentLoader } from "@/context/document/DocumentLoader";
import { useDocument } from "@/context/document/hooks";
import { pb } from "@/lib/pocketbase";
import type { Campaign, DocumentId } from "@/lib/types";
import { createFileRoute, Link } from "@tanstack/react-router"; import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react"; import { pb } from "@/lib/pocketbase";
import { z } from "zod"; import { SessionRow } from "@/components/documents/session/SessionRow";
import { Button } from "@headlessui/react";
const CampaignTabs = { import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
sessions: { label: "Sessions", docType: "session" }, import { Loader } from "@/components/Loader";
secrets: { label: "Secrets", docType: "secret" }, import type { Relationship } from "@/lib/types";
npcs: { label: "NPCs", docType: "npc" },
locations: { label: "Locations", docType: "location" },
threads: { label: "Threads", docType: "thread" },
fronts: { label: "Fronts", docType: "front" },
} as const;
const campaignSearchSchema = z.object({
tab: z
.enum(Object.keys(CampaignTabs) as (keyof typeof CampaignTabs)[])
.default("sessions"),
docId: z.optional(z.string().transform((s) => s as DocumentId)),
});
export const Route = createFileRoute( export const Route = createFileRoute(
"/_app/_authenticated/campaigns/$campaignId", "/_app/_authenticated/campaigns/$campaignId",
)({ )({
component: RouteComponent, component: RouteComponent,
pendingComponent: Loader, pendingComponent: Loader,
validateSearch: (s) => campaignSearchSchema.parse(s),
}); });
function RouteComponent() { function RouteComponent() {
const queryClient = useQueryClient();
const params = Route.useParams(); const params = Route.useParams();
const { tab, docId } = Route.useSearch();
const [loading, setLoading] = useState(true); const {
const [campaign, setCampaign] = useState<Campaign | null>(null); data: { campaign, sessions },
} = useSuspenseQuery({
useEffect(() => { queryKey: ["campaign"],
async function fetchData() { queryFn: async () => {
setLoading(true);
const campaign = await pb const campaign = await pb
.collection("campaigns") .collection("campaigns")
.getOne(params.campaignId); .getOne(params.campaignId);
setCampaign(campaign as Campaign); // Fetch all documents for this campaign
setLoading(false); const sessions = await pb.collection("documents").getFullList({
} filter: `campaign = "${params.campaignId}" && type = 'session'`,
fetchData(); sort: "-created",
}, [setCampaign, setLoading]); });
return {
campaign,
sessions,
};
},
});
if (loading || campaign === null) { const createNewSession = useCallback(async () => {
return <Loader />; // Check for a previous session
} const prevSession = await pb
.collection("documents")
.getFirstListItem(`campaign = "${campaign.id}" && type = 'session'`, {
sort: "-created",
});
console.log("Previous session: ", {
id: prevSession.id,
created: prevSession.created,
});
const newSession = await pb.collection("documents").create({
campaign: campaign.id,
type: "session",
data: {
strongStart: "",
},
});
// If any relations, then copy things over
if (prevSession) {
const prevRelations = await pb
.collection<Relationship>("relationships")
.getFullList({
filter: `primary = "${prevSession.id}"`,
});
console.log(`Found ${prevRelations.length} previous relations`);
for (const relation of prevRelations) {
console.log(
`Adding ${relation.secondary.length} items to ${relation.type}`,
);
await pb.collection("relationships").create({
primary: newSession.id,
type: relation.type,
secondary: relation.secondary,
});
}
}
queryClient.invalidateQueries({ queryKey: ["campaign"] });
}, [campaign]);
return ( return (
<TabbedLayout <div className="max-w-xl mx-auto py-8">
title={ <div className="mb-2">
<h2 className="text-2xl font-bold text-slate-100">{campaign.name}</h2>
}
navigation={
<Link <Link
to="/campaigns" to="/campaigns"
className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors" className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors"
> >
Back to campaigns Back to campaigns
</Link> </Link>
} </div>
tabs={Object.entries(CampaignTabs).map(([key, { label }]) => ( <h2 className="text-2xl font-bold mb-4 text-slate-100">
<Tab {campaign.name}
key={key} </h2>
label={label} <div className="flex justify-between">
active={tab === key} <h3 className="text-lg font-semibold mb-2 text-slate-200">Sessions</h3>
to={Route.to} <div>
params={{ <Button
campaignId: campaign.id, onClick={() => createNewSession()}
}} className="inline-flex items-center justify-center rounded bg-violet-600 hover:bg-violet-700 text-white px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-violet-400"
search={{ >
tab: key, New Session
}} </Button>
/> </div>
))} </div>
content={ {sessions && sessions.length > 0 ? (
<CampaignDocuments <div>
campaignId={campaign.id} <ul className="space-y-2">
docType={CampaignTabs[tab].docType} {sessions.map((s: any) => (
/> <li key={s.id}>
} <SessionRow session={s} />
flyout={docId && <Flyout key={docId} docId={docId} />} </li>
/> ))}
</ul>
</div>
) : (
<div className="text-slate-400">
No sessions found for this campaign.
</div>
)}
</div>
); );
} }
function Flyout({ docId }: { docId: DocumentId }) {
const { docResult } = useDocument(docId);
if (docResult?.type !== "ready") {
return (
<DocumentLoader documentId={docId}>
<Loader />
</DocumentLoader>
);
}
const doc = docResult.value.doc;
return <DocumentPreview doc={doc} />;
}

View File

@@ -43,7 +43,6 @@ function RouteComponent() {
to="/campaigns/$campaignId" to="/campaigns/$campaignId"
params={{ campaignId: c.id }} params={{ campaignId: c.id }}
className="block px-4 py-2 rounded bg-slate-800 hover:bg-violet-700 text-slate-100 transition-colors" className="block px-4 py-2 rounded bg-slate-800 hover:bg-violet-700 text-slate-100 transition-colors"
search={{ tab: "sessions" }}
> >
{c.name} {c.name}
</Link> </Link>

View File

@@ -1,28 +0,0 @@
import { DocumentView } from "@/components/documents/DocumentView";
import { DocumentLoader } from "@/context/document/DocumentLoader";
import { useDocumentPath } from "@/lib/documentPath";
import type { DocumentId } from "@/lib/types";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute(
"/_app/_authenticated/document/$documentId/$",
)({
component: RouteComponent,
});
function RouteComponent() {
const path = useDocumentPath();
const documentId = path?.documentId;
const relationshipType = path?.relationshipType ?? null;
const childDocId = path?.childDocId ?? null;
return (
<DocumentLoader documentId={documentId as DocumentId}>
<DocumentView
documentId={documentId as DocumentId}
relationshipType={relationshipType}
childDocId={childDocId}
/>
</DocumentLoader>
);
}

View File

@@ -0,0 +1,21 @@
import { DocumentView } from "@/components/documents/DocumentView";
import { DocumentProvider } from "@/context/document/DocumentContext";
import type { DocumentId } from "@/lib/types";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute(
"/_app/_authenticated/document/$documentId",
)({
component: RouteComponent,
});
function RouteComponent() {
const { documentId } = Route.useParams();
console.info("Rendering document route: ", documentId);
return (
<DocumentProvider documentId={documentId as DocumentId}>
<DocumentView />
</DocumentProvider>
);
}

View File

@@ -0,0 +1,72 @@
import { DocumentPrintRow } from "@/components/documents/DocumentPrintRow";
import { SessionPrintRow } from "@/components/documents/session/SessionPrintRow";
import { Loader } from "@/components/Loader";
import { pb } from "@/lib/pocketbase";
import { RelationshipType, type Relationship, type Session } from "@/lib/types";
import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import _ from "lodash";
export const Route = createFileRoute(
"/_app_/_authenticated/document_/$documentId/print",
)({
component: RouteComponent,
pendingComponent: Loader,
});
function RouteComponent() {
const params = Route.useParams();
const {
data: { session, relationships },
} = useSuspenseQuery({
queryKey: ["session", "relationships"],
queryFn: async () => {
const session = await pb
.collection("documents")
.getOne(params.documentId);
const relationships: Relationship[] = await pb
.collection("relationships")
.getFullList({
filter: `primary = "${params.documentId}"`,
expand: "secondary",
});
console.log("Fetched data: ", relationships);
return {
session: session as Session,
relationships: _.mapValues(
_.groupBy(relationships, (r) => r.type),
(rs: Relationship[]) => rs.flatMap((r) => r.expand?.secondary),
),
};
},
});
console.log("Parsed data: ", relationships);
return (
<div className="fill-w py-8 columns-2 gap-8 text-sm">
<SessionPrintRow session={session}></SessionPrintRow>
{[
RelationshipType.Scenes,
RelationshipType.Secrets,
RelationshipType.Locations,
RelationshipType.Npcs,
RelationshipType.Monsters,
RelationshipType.Treasures,
].map((relationshipType) => (
<div className="break-inside-avoid">
<h3 className="text-lg font-bold text-slate-600">
{relationshipType.charAt(0).toUpperCase() +
relationshipType.slice(1)}
</h3>
<ul className="list-disc pl-5">
{(relationships[relationshipType] ?? []).map((item) => (
<DocumentPrintRow document={item} />
))}
</ul>
</div>
))}
</div>
);
}

View File

@@ -1,5 +1,5 @@
@import "tailwindcss"; @import "tailwindcss";
@import "tailwindcss/utilities"; @tailwind utilities;
html, html,
body { body {
@@ -17,12 +17,6 @@ body {
min-width: 320px; min-width: 320px;
} }
/* The container for all content */
#app {
height: 100%;
width: 100%;
}
code, code,
pre { pre {
font-family: "Fira Mono", "Menlo", "Monaco", "Consolas", monospace; font-family: "Fira Mono", "Menlo", "Monaco", "Consolas", monospace;

View File

@@ -7,21 +7,14 @@ import { resolve } from "node:path";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [TanStackRouterVite({ autoCodeSplitting: true }), viteReact(), tailwindcss()],
TanStackRouterVite({ autoCodeSplitting: true }),
viteReact(),
tailwindcss(),
],
test: { test: {
globals: true, globals: true,
environment: "jsdom", environment: "jsdom",
}, },
resolve: { resolve: {
alias: { alias: {
"@": resolve(__dirname, "./src"), '@': resolve(__dirname, './src'),
}, },
}, }
build: {
sourcemap: true,
},
}); });