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:
unknown committed 2026-06-22 23:21:53 +02:00
1 parent 98a7a2d774
commit 9568be0211
27 files changed
+5381 -56

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run typecheck
- run: npm run lint
- run: npm run format:check
- run: npm run test
- run: npm run build
+2
View File
@@ -0,0 +1,2 @@
dist/
node_modules/
+7
View File
@@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"printWidth": 100,
"trailingComma": "none"
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Nyukhu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+73
View File
@@ -0,0 +1,73 @@
# fvtt-ts-react-boilerplate
A TypeScript + React + Vite boilerplate for building Foundry VTT (V14) game systems on top of **ApplicationV2**, with full type safety via [`fvtt-types`](https://github.com/League-of-Foundry-Developers/foundry-vtt-types).
This is a starting point, not a ruleset: one `character` Actor type and one `item` Item type, each with a React-rendered sheet, just enough to prove the pipeline end-to-end (build → load in Foundry → render → write back to the document).
## Prerequisites
- Node.js 22+
- Foundry VTT V14
- This repo cloned/copied directly into your Foundry `Data/systems/<your-system-id>` folder (development is done live in place — there's no separate dev server)
## Quickstart
```sh
npm install
npm run dev # vite build --watch — rebuilds dist/ on every save
```
Then in Foundry: enable the system for a world (or create one), reload the world after each rebuild to see changes (`F5` in the Foundry window — AppV2/React state isn't hot-reloaded, only full document/sheet remounts pick up new JS).
## Scripts
| Script | What it does |
| ---------------------- | ---------------------------------------------------------------------------------------------------- |
| `npm run dev` | Vite build in watch mode |
| `npm run build` | One-shot production build to `dist/` |
| `npm run typecheck` | `tsc --noEmit` |
| `npm run lint` | ESLint over the repo |
| `npm run lint:fix` | ESLint with autofix |
| `npm run format` | Prettier write |
| `npm run format:check` | Prettier check (used in CI) |
| `npm run test` | Vitest (pure-logic unit tests only — see [docs/testing-and-linting.md](docs/testing-and-linting.md)) |
## Project structure
```
system.json Foundry manifest — documentTypes, esmodules, languages
LICENSE.txt
lang/en.json, fr.json i18n strings, BOILERPLATE.* namespace
src/
system.ts Entry point — registers DataModels + sheets on "init"
i18n.ts localize() helper
data/
character-data.ts CharacterData DataModel (schema for Actor type "character")
item-data.ts ItemData DataModel (schema for Item type "item")
sheets/
character-sheet.ts ActorSheetV2 subclass, mounts React
item-sheet.ts ItemSheetV2 subclass, mounts React
components/
CharacterSheetApp.tsx React sheet UI
CharacterSheetApp.logic.ts pure helpers (unit-tested)
CharacterSheetApp.module.scss
ItemSheetApp.tsx
ItemSheetApp.module.scss
types/
data-config.d.ts DataModelConfig augmentation (types actor.system/item.system)
foundry.d.ts *.module.scss ambient module declaration
dist/ build output (gitignored) — esmodules/styles in system.json point here
```
## Documentation
- [docs/architecture.md](docs/architecture.md) — how `documentTypes`, `DataModel`, AppV2, React mounting, and `fvtt-types` fit together
- [docs/adding-content.md](docs/adding-content.md) — step-by-step: add a new Actor/Item subtype
- [docs/styling.md](docs/styling.md) — SCSS module conventions
- [docs/localization.md](docs/localization.md) — `lang/*.json` + `game.i18n` usage
- [docs/testing-and-linting.md](docs/testing-and-linting.md) — what's tested, what isn't, and why
- [docs/renaming-the-system.md](docs/renaming-the-system.md) — checklist for forking this template under a new name
## License
MIT — see [LICENSE.txt](LICENSE.txt).
+81
View File
@@ -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.
+126
View File
@@ -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.
+38
View File
@@ -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.
+17
View 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).
+28
View File
@@ -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`.
+31
View File
@@ -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.
+27
View File
@@ -0,0 +1,27 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import react from "eslint-plugin-react";
import prettier from "eslint-config-prettier";
import globals from "globals";
export default tseslint.config(
{ ignores: ["dist/**", "node_modules/**"] },
js.configs.recommended,
...tseslint.configs.recommended,
{
files: ["src/**/*.{ts,tsx}"],
plugins: { react },
languageOptions: {
globals: { ...globals.browser }
},
rules: {
...react.configs.recommended.rules,
"react/react-in-jsx-scope": "off",
"react/prop-types": "off"
},
settings: {
react: { version: "18.3" }
}
},
prettier
);
+20
View File
@@ -0,0 +1,20 @@
{
"BOILERPLATE": {
"Attributes": {
"strength": "Strength",
"agility": "Agility",
"spirit": "Spirit"
},
"Sheet": {
"Biography": "Biography",
"Total": "Total",
"TotalMod": "Total mod",
"ChatPlaceholder": "Say something...",
"SendToChat": "Send to chat"
},
"Item": {
"Quantity": "Quantity",
"Description": "Description"
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"BOILERPLATE": {
"Attributes": {
"strength": "Force",
"agility": "Agilité",
"spirit": "Esprit"
},
"Sheet": {
"Biography": "Biographie",
"Total": "Total",
"TotalMod": "Modificateur total",
"ChatPlaceholder": "Dites quelque chose...",
"SendToChat": "Envoyer dans le chat"
},
"Item": {
"Quantity": "Quantité",
"Description": "Description"
}
}
}
+4750 -7
View File
File diff suppressed because it is too large. Load diff
+17 -3
View File
@@ -1,20 +1,34 @@
{ {
"name": "newsystem", "name": "fvtt-ts-react-boilerplate",
"version": "0.8.2", "version": "0.8.2",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite build --watch", "dev": "vite build --watch",
"build": "vite build" "build": "vite build",
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "vitest run"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.4",
"@types/react": "^18.3.0", "@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0", "@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.0", "@vitejs/plugin-react": "^4.3.0",
"eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"fvtt-types": "^13.346.0-beta.20251209192131", "fvtt-types": "^13.346.0-beta.20251209192131",
"globals": "^17.7.0",
"prettier": "^3.8.4",
"sass": "^1.101.0", "sass": "^1.101.0",
"typescript": "^5.6.0", "typescript": "^5.6.0",
"vite": "^5.4.0" "typescript-eslint": "^8.62.0",
"vite": "^5.4.0",
"vitest": "^4.1.9"
}, },
"dependencies": { "dependencies": {
"react": "^18.3.0", "react": "^18.3.0",
+18 -3
View File
@@ -3,9 +3,24 @@ function defineSchema() {
return { return {
biography: new fields.HTMLField({ initial: "" }), biography: new fields.HTMLField({ initial: "" }),
attributes: new fields.SchemaField({ attributes: new fields.SchemaField({
strength: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 10 }), strength: new fields.NumberField({
agility: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 10 }), required: true,
spirit: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 10 }) nullable: false,
integer: true,
initial: 10
}),
agility: new fields.NumberField({
required: true,
nullable: false,
integer: true,
initial: 10
}),
spirit: new fields.NumberField({
required: true,
nullable: false,
integer: true,
initial: 10
})
}) })
}; };
} }
+7 -1
View File
@@ -2,7 +2,13 @@ function defineSchema() {
const fields = foundry.data.fields; const fields = foundry.data.fields;
return { return {
description: new fields.HTMLField({ initial: "" }), description: new fields.HTMLField({ initial: "" }),
quantity: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 1, min: 0 }) quantity: new fields.NumberField({
required: true,
nullable: false,
integer: true,
initial: 1,
min: 0
})
}; };
} }
+3
View File
@@ -0,0 +1,3 @@
// `game` isn't ready until the "ready" hook fires; sheets only render after that,
// so the non-null assertion here is safe and keeps callers from repeating it.
export const localize = (key: string) => game.i18n!.localize(key);
+2 -4
View File
@@ -4,7 +4,7 @@ import { CharacterSheetApp } from "./components/CharacterSheetApp";
export class CharacterSheet extends foundry.applications.sheets.ActorSheetV2 { export class CharacterSheet extends foundry.applications.sheets.ActorSheetV2 {
static DEFAULT_OPTIONS = { static DEFAULT_OPTIONS = {
classes: ["newsystem", "sheet", "actor"], classes: ["fvtt-ts-react-boilerplate", "sheet", "actor"],
position: { width: 600, height: 480 } position: { width: 600, height: 480 }
}; };
@@ -24,9 +24,7 @@ export class CharacterSheet extends foundry.applications.sheets.ActorSheetV2 {
this.#root.render(React.createElement(CharacterSheetApp, { actor: this.document })); this.#root.render(React.createElement(CharacterSheetApp, { actor: this.document }));
} }
override async close( override async close(...args: Parameters<foundry.applications.sheets.ActorSheetV2["close"]>) {
...args: Parameters<foundry.applications.sheets.ActorSheetV2["close"]>
) {
this.#root?.unmount(); this.#root?.unmount();
this.#root = null; this.#root = null;
return super.close(...args); return super.close(...args);
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { fmtMod, modifier } from "./CharacterSheetApp.logic";
describe("modifier", () => {
it("matches the d20-style table around the 10 baseline", () => {
expect(modifier(10)).toBe(0);
expect(modifier(11)).toBe(0);
expect(modifier(12)).toBe(1);
expect(modifier(9)).toBe(-1);
expect(modifier(20)).toBe(5);
});
});
describe("fmtMod", () => {
it("prefixes non-negative values with +", () => {
expect(fmtMod(0)).toBe("+0");
expect(fmtMod(3)).toBe("+3");
});
it("leaves negative values as-is", () => {
expect(fmtMod(-2)).toBe("-2");
});
});
@@ -0,0 +1,6 @@
// Pure game-logic helpers, deliberately kept free of any Foundry global.
// Code that touches `actor`/`ChatMessage`/etc. needs a running Foundry instance
// and isn't realistically unit-testable — this is the boundary to keep that out.
export const modifier = (score: number) => Math.floor((score - 10) / 2);
export const fmtMod = (mod: number) => (mod >= 0 ? `+${mod}` : `${mod}`);
+13 -13
View File
@@ -1,8 +1,7 @@
import React, { useState } from "react"; import React, { useState } from "react";
import styles from "./CharacterSheetApp.module.scss"; import styles from "./CharacterSheetApp.module.scss";
import { localize } from "../../i18n";
const modifier = (score: number) => Math.floor((score - 10) / 2); import { modifier, fmtMod } from "./CharacterSheetApp.logic";
const fmtMod = (mod: number) => (mod >= 0 ? `+${mod}` : `${mod}`);
export function CharacterSheetApp({ actor }: { actor: Actor.Implementation }) { export function CharacterSheetApp({ actor }: { actor: Actor.Implementation }) {
const system = actor.system; const system = actor.system;
@@ -36,7 +35,7 @@ export function CharacterSheetApp({ actor }: { actor: Actor.Implementation }) {
<div className={styles.attributes}> <div className={styles.attributes}>
{(["strength", "agility", "spirit"] as const).map((key) => ( {(["strength", "agility", "spirit"] as const).map((key) => (
<label className={styles.attributeLabel} key={key}> <label className={styles.attributeLabel} key={key}>
{key} {localize(`BOILERPLATE.Attributes.${key}`)}
<input <input
type="number" type="number"
value={attrs[key]} value={attrs[key]}
@@ -47,27 +46,28 @@ export function CharacterSheetApp({ actor }: { actor: Actor.Implementation }) {
))} ))}
</div> </div>
<div className={styles.totals}> <div className={styles.totals}>
<span>Total: {total}</span> <span>
<span>Total mod: {fmtMod(totalMod)}</span> {localize("BOILERPLATE.Sheet.Total")}: {total}
</span>
<span>
{localize("BOILERPLATE.Sheet.TotalMod")}: {fmtMod(totalMod)}
</span>
</div> </div>
<label className={styles.attributeLabel}> <label className={styles.attributeLabel}>
Biography {localize("BOILERPLATE.Sheet.Biography")}
<textarea <textarea defaultValue={system.biography} onBlur={(e) => updateBiography(e.target.value)} />
defaultValue={system.biography}
onBlur={(e) => updateBiography(e.target.value)}
/>
</label> </label>
<div className={styles.chatRow}> <div className={styles.chatRow}>
<input <input
type="text" type="text"
placeholder="Say something..." placeholder={localize("BOILERPLATE.Sheet.ChatPlaceholder")}
value={chatMessage} value={chatMessage}
onChange={(e) => setChatMessage(e.target.value)} onChange={(e) => setChatMessage(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendChatMessage()} onKeyDown={(e) => e.key === "Enter" && sendChatMessage()}
/> />
<button type="button" onClick={sendChatMessage}> <button type="button" onClick={sendChatMessage}>
Send to chat {localize("BOILERPLATE.Sheet.SendToChat")}
</button> </button>
</div> </div>
</div> </div>
+3 -2
View File
@@ -1,5 +1,6 @@
import React from "react"; import React from "react";
import styles from "./ItemSheetApp.module.scss"; import styles from "./ItemSheetApp.module.scss";
import { localize } from "../../i18n";
export function ItemSheetApp({ item }: { item: Item.Implementation }) { export function ItemSheetApp({ item }: { item: Item.Implementation }) {
const system = item.system; const system = item.system;
@@ -16,7 +17,7 @@ export function ItemSheetApp({ item }: { item: Item.Implementation }) {
<div className={styles.sheet}> <div className={styles.sheet}>
<h1>{item.name}</h1> <h1>{item.name}</h1>
<label className={styles.label}> <label className={styles.label}>
Quantity {localize("BOILERPLATE.Item.Quantity")}
<input <input
type="number" type="number"
min={0} min={0}
@@ -25,7 +26,7 @@ export function ItemSheetApp({ item }: { item: Item.Implementation }) {
/> />
</label> </label>
<label className={styles.label}> <label className={styles.label}>
Description {localize("BOILERPLATE.Item.Description")}
<textarea <textarea
defaultValue={system.description} defaultValue={system.description}
onBlur={(e) => updateDescription(e.target.value)} onBlur={(e) => updateDescription(e.target.value)}
+2 -4
View File
@@ -4,7 +4,7 @@ import { ItemSheetApp } from "./components/ItemSheetApp";
export class ItemSheet extends foundry.applications.sheets.ItemSheetV2 { export class ItemSheet extends foundry.applications.sheets.ItemSheetV2 {
static DEFAULT_OPTIONS = { static DEFAULT_OPTIONS = {
classes: ["newsystem", "sheet", "item"], classes: ["fvtt-ts-react-boilerplate", "sheet", "item"],
position: { width: 480, height: 360 } position: { width: 480, height: 360 }
}; };
@@ -24,9 +24,7 @@ export class ItemSheet extends foundry.applications.sheets.ItemSheetV2 {
this.#root.render(React.createElement(ItemSheetApp, { item: this.document })); this.#root.render(React.createElement(ItemSheetApp, { item: this.document }));
} }
override async close( override async close(...args: Parameters<foundry.applications.sheets.ItemSheetV2["close"]>) {
...args: Parameters<foundry.applications.sheets.ItemSheetV2["close"]>
) {
this.#root?.unmount(); this.#root?.unmount();
this.#root = null; this.#root = null;
return super.close(...args); return super.close(...args);
+18 -8
View File
@@ -7,12 +7,22 @@ Hooks.once("init", () => {
CONFIG.Actor.dataModels.character = CharacterData; CONFIG.Actor.dataModels.character = CharacterData;
CONFIG.Item.dataModels.item = ItemData; CONFIG.Item.dataModels.item = ItemData;
foundry.applications.apps.DocumentSheetConfig.registerSheet(Actor, "newsystem", CharacterSheet, { foundry.applications.apps.DocumentSheetConfig.registerSheet(
types: ["character"], Actor,
makeDefault: true "fvtt-ts-react-boilerplate",
}); CharacterSheet,
foundry.applications.apps.DocumentSheetConfig.registerSheet(Item, "newsystem", ItemSheet, { {
types: ["item"], types: ["character"],
makeDefault: true makeDefault: true
}); }
);
foundry.applications.apps.DocumentSheetConfig.registerSheet(
Item,
"fvtt-ts-react-boilerplate",
ItemSheet,
{
types: ["item"],
makeDefault: true
}
);
}); });
+5 -11
View File
@@ -1,9 +1,9 @@
{ {
"id": "newsystem", "id": "fvtt-ts-react-boilerplate",
"version": "0.8.2", "version": "0.8.2",
"title": "Newsystem", "title": "FVTT TS+React Boilerplate",
"url": "", "url": "",
"description": "First edition of Newsystem", "description": "A TypeScript + React + Vite boilerplate for Foundry VTT V14 system development",
"license": "LICENSE.txt", "license": "LICENSE.txt",
"authors": [ "authors": [
{ {
@@ -12,12 +12,8 @@
"flags": {} "flags": {}
} }
], ],
"esmodules": [ "esmodules": ["dist/system.mjs"],
"dist/system.mjs" "styles": ["dist/style.css"],
],
"styles": [
"dist/style.css"
],
"languages": [ "languages": [
{ {
"lang": "en", "lang": "en",
@@ -44,8 +40,6 @@
"minimum": "14", "minimum": "14",
"verified": "14" "verified": "14"
}, },
"primaryTokenAttribute": "health",
"secondaryTokenAttribute": "power",
"manifest": "", "manifest": "",
"download": "", "download": "",
"grid": { "grid": {