Turn boilerplate into a maintained, documented template
Rename newsystem -> fvtt-ts-react-boilerplate, install fvtt-types for real typing throughout (DataModelConfig augmentation, typed sheet overrides), wire up i18n (lang/en.json was an empty directory and fr.json was empty), add MIT license, eslint/prettier/vitest tooling, GitHub Actions CI, and extensive docs/ covering the architecture, adding content, styling, localization, testing, and how to rename this again for a new system.
This commit is contained in:
1 parent
98a7a2d774
commit
9568be0211
28 files changed
+5383
-58
No files matched your search
@@ -0,0 +1,81 @@
|
||||
# Adding a new Actor or Item subtype
|
||||
|
||||
Worked example: adding an Actor subtype called `npc` alongside the existing `character`. The same steps apply to a new Item subtype.
|
||||
|
||||
## 1. Schema — `src/data/npc-data.ts`
|
||||
|
||||
```ts
|
||||
function defineSchema() {
|
||||
const fields = foundry.data.fields;
|
||||
return {
|
||||
threatLevel: new fields.NumberField({
|
||||
required: true,
|
||||
nullable: false,
|
||||
integer: true,
|
||||
initial: 1
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
export class NpcData extends foundry.abstract.TypeDataModel<
|
||||
ReturnType<typeof defineSchema>,
|
||||
Actor.Implementation
|
||||
> {
|
||||
static defineSchema = defineSchema;
|
||||
}
|
||||
```
|
||||
|
||||
See [docs/architecture.md](architecture.md#datamodel-classes) for why `defineSchema` is a standalone function rather than an inline class method, and why `nullable: false` matters.
|
||||
|
||||
## 2. Type it — `src/types/data-config.d.ts`
|
||||
|
||||
```ts
|
||||
import type { NpcData } from "../data/npc-data";
|
||||
|
||||
declare module "fvtt-types/configuration" {
|
||||
interface DataModelConfig {
|
||||
Actor: { character: typeof CharacterData; npc: typeof NpcData };
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Declare it — `system.json`
|
||||
|
||||
```json
|
||||
"documentTypes": {
|
||||
"Actor": { "character": {}, "npc": {} }
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Sheet — `src/sheets/npc-sheet.ts`
|
||||
|
||||
Copy `character-sheet.ts` verbatim, rename the class, point it at a new React component. The `_renderHTML`/`_replaceHTML`/`close` lifecycle is identical for every AppV2 sheet in this boilerplate.
|
||||
|
||||
## 5. React component — `src/sheets/components/NpcSheetApp.tsx`
|
||||
|
||||
Copy the shape of `CharacterSheetApp.tsx`: accept the typed document as a prop, read `actor.system.*`, write via `actor.update({ system: { ... } })` (nested object — see the architecture doc's gotcha), localize labels via `localize()` from `src/i18n.ts`.
|
||||
|
||||
## 6. Register — `src/system.ts`
|
||||
|
||||
```ts
|
||||
CONFIG.Actor.dataModels.npc = NpcData;
|
||||
|
||||
foundry.applications.apps.DocumentSheetConfig.registerSheet(
|
||||
Actor,
|
||||
"fvtt-ts-react-boilerplate",
|
||||
NpcSheet,
|
||||
{
|
||||
types: ["npc"],
|
||||
makeDefault: true
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## 7. i18n
|
||||
|
||||
Add `BOILERPLATE.Npc.*` keys to `lang/en.json` and `lang/fr.json` — see [docs/localization.md](localization.md).
|
||||
|
||||
## Verify
|
||||
|
||||
`npm run typecheck && npm run build`, then in Foundry create an Actor and pick the new subtype from the type dropdown.
|
||||
@@ -0,0 +1,126 @@
|
||||
# Architecture
|
||||
|
||||
## Why no `template.json`
|
||||
|
||||
Pre-V11 Foundry systems describe Actor/Item data shapes in `template.json`. This boilerplate uses the V11+ alternative instead: `system.json`'s `documentTypes` field declares which subtypes exist, and a `DataModel` class (registered at runtime) defines the actual schema. Two sources of truth (template.json + ad-hoc JS) collapses into one (the `DataModel` class), and you get real validation/casting for free.
|
||||
|
||||
```json
|
||||
// system.json
|
||||
"documentTypes": {
|
||||
"Actor": { "character": {} },
|
||||
"Item": { "item": {} }
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// src/system.ts
|
||||
Hooks.once("init", () => {
|
||||
CONFIG.Actor.dataModels.character = CharacterData;
|
||||
CONFIG.Item.dataModels.item = ItemData;
|
||||
});
|
||||
```
|
||||
|
||||
## DataModel classes
|
||||
|
||||
`src/data/character-data.ts`:
|
||||
|
||||
```ts
|
||||
function defineSchema() {
|
||||
const fields = foundry.data.fields;
|
||||
return {
|
||||
biography: new fields.HTMLField({ initial: "" }),
|
||||
attributes: new fields.SchemaField({
|
||||
strength: new fields.NumberField({
|
||||
required: true,
|
||||
nullable: false,
|
||||
integer: true,
|
||||
initial: 10
|
||||
})
|
||||
// ...
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
export class CharacterData extends foundry.abstract.TypeDataModel<
|
||||
ReturnType<typeof defineSchema>,
|
||||
Actor.Implementation
|
||||
> {
|
||||
static defineSchema = defineSchema;
|
||||
}
|
||||
```
|
||||
|
||||
The `defineSchema` function is declared standalone, then assigned as a static — not written inline as a class method. This is required so `ReturnType<typeof defineSchema>` can be used as the `TypeDataModel` generic's `Schema` argument; a class can't reference its own static method's return type in its own `extends` clause.
|
||||
|
||||
**`nullable: false` matters.** Without it, `NumberField`'s inferred type is `number | null` (Foundry fields are nullable by default), which then leaks into every place that reads `attrs.strength` as if it could be `null`. Set it explicitly wherever you don't actually want `null` to be a valid value.
|
||||
|
||||
## fvtt-types + DataModelConfig
|
||||
|
||||
[`fvtt-types`](https://github.com/League-of-Foundry-Developers/foundry-vtt-types) (installed as the `fvtt-types` npm package) supplies ambient types for `Hooks`, `CONFIG`, `game`, `foundry.*`, `Actor`, `Item`, etc. Wired in via `tsconfig.json`:
|
||||
|
||||
```json
|
||||
{ "compilerOptions": { "types": ["fvtt-types"] } }
|
||||
```
|
||||
|
||||
By default, `actor.system` is untyped without telling the types package which `DataModel` class backs each subtype. `src/types/data-config.d.ts` does that via module augmentation:
|
||||
|
||||
```ts
|
||||
declare module "fvtt-types/configuration" {
|
||||
interface DataModelConfig {
|
||||
Actor: { character: typeof CharacterData };
|
||||
Item: { item: typeof ItemData };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
After this, `actor.system.attributes.strength` resolves to `number`, not `any`.
|
||||
|
||||
**Gotcha**: with real types in place, `actor.update({ "system.attributes.strength": 5 })` (dotted-path key) no longer type-checks — `update()`'s type wants a nested object. Foundry's runtime supports both forms (it expands dotted paths internally), but only the nested form satisfies the types:
|
||||
|
||||
```ts
|
||||
actor.update({ system: { attributes: { strength: 5 } } });
|
||||
```
|
||||
|
||||
**Version mismatch risk**: `fvtt-types`'s published versions track Foundry V13 builds (no V14-specific release exists at the time this was written). The AppV2/DataModel surface is stable since V13 so this mostly just works, but if you hit a type error that looks wrong for an API you know exists in V14, it may be a types-package gap rather than a real bug — check `tsc` output carefully before assuming the type is right.
|
||||
|
||||
## AppV2 sheets with React (no Handlebars)
|
||||
|
||||
`src/sheets/character-sheet.ts` extends `ActorSheetV2` directly — no `HandlebarsApplicationMixin`. Three lifecycle methods matter:
|
||||
|
||||
```ts
|
||||
export class CharacterSheet extends foundry.applications.sheets.ActorSheetV2 {
|
||||
#root: Root | null = null;
|
||||
|
||||
override async _renderHTML(...args) {
|
||||
return args[0]; // pass-through: no HTML string/template needed
|
||||
}
|
||||
|
||||
override _replaceHTML(...args) {
|
||||
const content = args[1]; // the sheet's content HTMLElement
|
||||
if (!this.#root) this.#root = createRoot(content);
|
||||
this.#root.render(React.createElement(CharacterSheetApp, { actor: this.document }));
|
||||
}
|
||||
|
||||
override async close(...args) {
|
||||
this.#root?.unmount();
|
||||
this.#root = null;
|
||||
return super.close(...args);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `_renderHTML` would normally render a Handlebars template to a string; here it's a no-op pass-through since React owns the DOM.
|
||||
- `_replaceHTML` is where the React root gets created (once) and (re-)rendered on every Foundry-triggered re-render (e.g. after `actor.update()`, on any client watching the same actor). React reconciles internally — no manual diffing needed on our side.
|
||||
- `close()` must unmount the React root, or you leak it (and React will warn about it).
|
||||
|
||||
Method signatures use `Parameters<foundry.applications.sheets.ActorSheetV2["_renderHTML"]>` rather than hand-typed parameters — this way if the base class signature changes in a newer `fvtt-types` release, `tsc` will flag the mismatch instead of silently drifting.
|
||||
|
||||
## Build (Vite)
|
||||
|
||||
`vite.config.ts` builds `src/system.ts` in **library mode** to a single ESM file (`dist/system.mjs`) — Foundry loads this directly as an `esmodule`, it can't resolve `node_modules` imports at runtime, so React/ReactDOM are bundled in, not externalized.
|
||||
|
||||
Two non-obvious settings:
|
||||
|
||||
- `define: { "process.env.NODE_ENV": JSON.stringify("production") }` — Vite's lib mode doesn't auto-replace `process.env.NODE_ENV` the way app mode does. Without this, React throws `Uncaught ReferenceError: process is not defined` at runtime in Foundry (there's no Node `process` global in a browser). Setting it also lets Rollup dead-code-eliminate React's dev-only warning paths, shrinking the bundle.
|
||||
- `css.preprocessorOptions.scss.api: "modern-compiler"` — silences a Sass legacy-JS-API deprecation warning on build; functionally inert otherwise.
|
||||
|
||||
CSS Modules (`*.module.scss`) are handled by Vite natively — `sass` is a dev dependency for SCSS compilation, no extra plugin needed.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Localization
|
||||
|
||||
`system.json` registers two languages:
|
||||
|
||||
```json
|
||||
"languages": [
|
||||
{ "lang": "en", "name": "English", "path": "lang/en.json", "flags": {} },
|
||||
{ "lang": "fr", "name": "Français", "path": "lang/fr.json", "flags": {} }
|
||||
]
|
||||
```
|
||||
|
||||
All keys live under a single `BOILERPLATE` root namespace to avoid colliding with Foundry core or other systems/modules:
|
||||
|
||||
```json
|
||||
{
|
||||
"BOILERPLATE": {
|
||||
"Attributes": { "strength": "Strength", "agility": "Agility", "spirit": "Spirit" },
|
||||
"Sheet": { "Biography": "Biography", "SendToChat": "Send to chat", "...": "..." },
|
||||
"Item": { "Quantity": "Quantity", "Description": "Description" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In React components, use the `localize()` helper from `src/i18n.ts` rather than calling `game.i18n.localize()` directly:
|
||||
|
||||
```ts
|
||||
export const localize = (key: string) => game.i18n!.localize(key);
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { localize } from "../../i18n";
|
||||
|
||||
<label>{localize("BOILERPLATE.Sheet.Biography")}</label>;
|
||||
```
|
||||
|
||||
**Why the helper instead of inline `game.i18n.localize()`**: `fvtt-types` types `game` (and `game.i18n`) as possibly `undefined`, since `game` genuinely isn't populated until Foundry's `"ready"` hook fires. Sheets only ever render after that point, so a single non-null assertion in one shared helper is safe and keeps every call site from repeating `game.i18n!.localize(...)`.
|
||||
|
||||
When adding a new string: add the key to **both** `lang/en.json` and `lang/fr.json`. Foundry does not fall back to English for a missing key in the active non-English language — `localize()` just returns the raw key string (e.g. `"BOILERPLATE.Sheet.Foo"`) if it's missing from the active language file.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Renaming this template for a new system
|
||||
|
||||
If you're forking this boilerplate to start an actual system, every literal occurrence of `fvtt-ts-react-boilerplate` needs to change, plus the `character`/`item` placeholder type names if you're not keeping them. Checklist:
|
||||
|
||||
| Location | What to change |
|
||||
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Folder name | Rename the folder itself (`Data/systems/fvtt-ts-react-boilerplate` → `Data/systems/<your-id>`) |
|
||||
| `system.json` | `"id"`, `"title"`, `"description"`, `"authors"` |
|
||||
| `package.json` | `"name"` |
|
||||
| `src/system.ts` | The namespace string passed to `DocumentSheetConfig.registerSheet(..., "fvtt-ts-react-boilerplate", ...)` (two call sites) |
|
||||
| `src/sheets/character-sheet.ts`, `src/sheets/item-sheet.ts` | `DEFAULT_OPTIONS.classes` array — the `"fvtt-ts-react-boilerplate"` CSS class entry |
|
||||
| `lang/en.json`, `lang/fr.json` | The `BOILERPLATE` root key — pick a namespace that won't collide with other systems/modules (convention: uppercase, short, unique to your system) |
|
||||
| `LICENSE.txt` | Copyright holder name, if different from the original author |
|
||||
|
||||
If you're also renaming the placeholder `character`/`item` subtypes to your own (e.g. `hero`/`weapon`), that's a separate, larger change — follow [docs/adding-content.md](adding-content.md) to add the new subtype(s) first, then remove `character`/`item` (schema file, `DataModelConfig` entry, `documentTypes` entry, sheet, component, registration in `system.ts`) once nothing references them.
|
||||
|
||||
After renaming, run `npm run typecheck && npm run lint && npm run build` and reload Foundry — the system should appear under the new id in the system selection list (you may need to restart the Foundry server for it to notice the folder rename).
|
||||
@@ -0,0 +1,28 @@
|
||||
# Styling
|
||||
|
||||
Each sheet component has its own SCSS module, colocated and named after the component: `CharacterSheetApp.tsx` ↔ `CharacterSheetApp.module.scss`.
|
||||
|
||||
```tsx
|
||||
import styles from "./CharacterSheetApp.module.scss";
|
||||
|
||||
<div className={styles.sheet}> ... </div>;
|
||||
```
|
||||
|
||||
Vite compiles `*.module.scss` to locally-scoped, hashed class names automatically — no global CSS collisions between sheets, no need for a `newsystem`-prefixed BEM-style convention like older Foundry systems use.
|
||||
|
||||
Nest sub-element styles under their parent class using Sass nesting, e.g. in `CharacterSheetApp.module.scss`:
|
||||
|
||||
```scss
|
||||
.attributeLabel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.modifier {
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
All compiled CSS (across every component) gets concatenated by Vite into the single `dist/style.css` that `system.json`'s `styles` array points at — you don't need to import each module's CSS manually anywhere except inside the component that uses it (Vite's CSS-in-JS-import handles collection).
|
||||
|
||||
There's no global stylesheet in this boilerplate by design — if you need truly global rules (e.g. a CSS variable reset), add a plain (non-module) `.scss` file and import it once from `src/system.ts`.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Testing and linting
|
||||
|
||||
## What's tested, and why so little
|
||||
|
||||
`npm run test` (Vitest) only covers **pure game-logic functions** — currently `modifier`/`fmtMod` in `src/sheets/components/CharacterSheetApp.logic.ts`, exercised by `CharacterSheetApp.logic.test.ts`.
|
||||
|
||||
Anything that touches `actor`, `ChatMessage`, `game`, `Hooks`, or any other Foundry global needs a running Foundry server with a world loaded — there's no practical way to unit-test `actor.update(...)` or `ChatMessage.create(...)` calls in isolation, and mocking the entire Foundry runtime isn't worth the upkeep for a boilerplate.
|
||||
|
||||
**The pattern going forward**: when a component's logic is more than "read a prop, write an update," extract the part that's pure computation (no Foundry globals, no React) into a sibling `*.logic.ts` file, and unit-test _that_. The component itself stays thin glue between Foundry documents and the pure logic, and isn't tested directly.
|
||||
|
||||
## Linting
|
||||
|
||||
ESLint flat config (`eslint.config.js`): `typescript-eslint` recommended rules + `eslint-plugin-react` (JSX rules, `react-in-jsx-scope` and `prop-types` turned off — not relevant with the modern JSX transform + TypeScript prop typing) + `eslint-config-prettier` (turns off any ESLint formatting rules that would conflict with Prettier).
|
||||
|
||||
```sh
|
||||
npm run lint # check
|
||||
npm run lint:fix # autofix
|
||||
```
|
||||
|
||||
## Formatting
|
||||
|
||||
Prettier (`.prettierrc`): double quotes, semicolons, 2-space indent, no trailing commas, 100-char print width — matches the style already used throughout `src/`.
|
||||
|
||||
```sh
|
||||
npm run format # write
|
||||
npm run format:check # check only (used in CI)
|
||||
```
|
||||
|
||||
## CI
|
||||
|
||||
`.github/workflows/ci.yml` runs on every push/PR to `main`: `npm ci` → typecheck → lint → format:check → test → build. This only actually executes once the repo has a GitHub remote with Actions enabled — if you've forked this template, push to your own remote and it'll pick up from there.
|
||||
Reference in new issue
Block a user