a new begining

This commit is contained in:
Byroks committed 2026-10-15 18:10:45 +02:00
1 parent 9568be0211
commit 24c81dbcf8
38 files changed
+1313 -424

No files matched your search

+378
View File
@@ -0,0 +1,378 @@
import { systemPath } from "../constants.mjs";
import { prepareActiveEffectCategories } from "../helpers/utils.mjs";
const { api, sheets } = foundry.applications;
/**
* Extend the basic ActorSheet with some very simple modifications.
*/
export class M6ActorSheet extends api.HandlebarsApplicationMixin(sheets.ActorSheetV2) {
/** @inheritdoc */
static DEFAULT_OPTIONS = {
classes: ["M6", "actor"],
window: {
icon: "fa-solid fa-dice-d10",
resizable: true
},
position: {
width: 800,
height: 800
},
actions: {
viewDoc: this.#viewDoc,
createDoc: this.#createDoc,
deleteDoc: this.#deleteDoc,
toggleEffect: this.#toggleEffect,
rollSkill: this.#rollSkill
},
form: {
submitOnChange: true
}
};
/* -------------------------------------------------- */
static TABS = {
primary: {
tabs: [
{
id: "properties"
},
{
id: "items"
},
{
id: "effects"
}
],
initial: "properties",
labelPrefix: "Midgard6.Sheets.Tabs"
}
};
/* -------------------------------------------------- */
/** @inheritdoc */
static PARTS = {
header: {
template: systemPath("templates/actor/header.hbs")
},
stats: {
template: systemPath("templates/actor/stats.hbs")
},
tabs: {
template: "templates/generic/tab-navigation.hbs"
},
properties: {
template: systemPath("templates/shared/properties.hbs"),
scrollable: [""]
},
items: {
template: systemPath("templates/actor/items.hbs"),
scrollable: [""]
},
effects: {
template: systemPath("templates/shared/effects.hbs"),
scrollable: [""]
}
};
/* -------------------------------------------------- */
/** @inheritdoc */
_initializeApplicationOptions(options) {
const initialized = super._initializeApplicationOptions(options);
initialized.classes.push(initialized.document.type);
return initialized;
}
/* -------------------------------------------------- */
/** @inheritdoc */
async _prepareContext(options) {
const context = await super._prepareContext(options);
Object.assign(context, {
owner: this.document.isOwner,
limited: this.document.limited,
actor: this.actor,
system: this.actor.system,
skills: this.actor.system.skills,
flags: this.actor.flags,
config: CONFIG
});
return context;
}
/* -------------------------------------------------- */
/** @inheritdoc */
async _preparePartContext(partId, context) {
switch (partId) {
case "effects":
context.effects = prepareActiveEffectCategories(this.actor.allApplicableEffects());
context.tab = context.tabs[partId];
break;
case "properties":
context.fields = await this._getSkills();
context.tab = context.tabs[partId];
break;
case "items":
context.itemTypes = this._getItems();
context.tab = context.tabs[partId];
break;
}
return context;
}
/**
* Handles the system fields for the form-fields generic.
* @returns {object[]}
*/
async _getFields() {
const doc = this.actor;
const source = doc._source;
const systemFields = CONFIG.Actor.dataModels[doc.type]?.schema.fields;
const fieldSets = [];
// TODO: Find a clever way to handle enrichment
for (const field of Object.values(systemFields ?? {})) {
const path = `system.${field.name}`;
if (field instanceof foundry.data.fields.SchemaField) {
const fieldset = { fieldset: true, legend: field.label, fields: [] };
await this.#addSystemFields(fieldset, field.fields, source, path);
fieldSets.push(fieldset);
} else {
fieldSets.push({ outer: { field, value: foundry.utils.getProperty(source, path) } });
}
}
return fieldSets;
}
async _getSkills() {
const doc = this.actor;
const source = doc._source;
const systemFields = CONFIG.Actor.dataModels[doc.type]?.schema.fields.skills.fields;
const fieldSets = [];
// TODO: Find a clever way to handle enrichment
for (const field of Object.values(systemFields ?? {})) {
const path = `system.skills.${field.name}`;
if (field instanceof foundry.data.fields.SchemaField) {
const fieldset = {
fieldset: true,
legend: `Midgard6.Skills.gruppen.${field.label}`,
fields: []
};
await this.#addSystemFields(fieldset, field.fields, source, path);
fieldSets.push(fieldset);
} else {
fieldSets.push({ outer: { field, value: foundry.utils.getProperty(source, path) } });
}
}
return fieldSets;
}
/* -------------------------------------------------- */
/**
* Recursively add system model fields to the fieldset.
*/
async #addSystemFields(fieldset, schema, source, _path = "system") {
for (const field of Object.values(schema)) {
const path = `${_path}.${field.name}`;
if (field instanceof foundry.data.fields.SchemaField) {
this.#addSystemFields(fieldset, field.fields, source, path);
} else if (field.constructor.hasFormSupport) {
fieldset.fields.push({
field,
value: foundry.utils.getProperty(source, path),
localizationName: "Midgard6.Skills." + field.name
});
}
}
}
/* -------------------------------------------------- */
/**
* Adapted from Actor#itemTypes.
*/
_getItems() {
const types = Object.fromEntries(
game.documentTypes.Item.map((t) => {
return [t, { label: game.i18n.localize(CONFIG.Item.typeLabels[t]), items: [] }];
})
);
for (const item of this.actor.items) {
types[item.type].items.push(item);
}
// Only show Base if it's actually being used
if (types.base.items.length === 0) delete types.base;
return types;
}
/* -------------------------------------------------- */
/**
* Actions performed after any render of the Application.
* Post-render steps are not awaited by the render process.
* @param {ApplicationRenderContext} context Prepared context data.
* @param {RenderOptions} options Provided render options.
* @protected
* @inheritdoc
*/
async _onRender(context, options) {
await super._onRender(context, options);
this.#disableOverrides();
}
/* -------------------------------------------------- */
/* Event handlers */
/* -------------------------------------------------- */
/**
* Renders an embedded document's sheet.
*
* @this M6ActorSheet
* @param {PointerEvent} event The originating click event.
* @param {HTMLElement} target The capturing HTML element which defined a [data-action].
* @protected
*/
static async #viewDoc(event, target) {
const doc = this._getEmbeddedDocument(target);
doc.sheet.render(true);
}
/* -------------------------------------------------- */
/**
* Handles item deletion.
*
* @this M6ActorSheet
* @param {PointerEvent} event The originating click event.
* @param {HTMLElement} target The capturing HTML element which defined a [data-action].
* @protected
*/
static async #deleteDoc(event, target) {
const doc = this._getEmbeddedDocument(target);
doc.delete();
}
/* -------------------------------------------------- */
/**
* Handle creating a new Owned Item or ActiveEffect for the actor using initial data defined in the HTML dataset.
*
* @this M6ActorSheet
* @param {PointerEvent} event The originating click event.
* @param {HTMLElement} target The capturing HTML element which defined a [data-action].
* @private
*/
static async #createDoc(event, target) {
const docCls = getDocumentClass(target.dataset.documentClass);
const docData = {
name: docCls.defaultName({
type: target.dataset.type,
parent: this.actor
})
};
for (const [dataKey, value] of Object.entries(target.dataset)) {
if (["action", "documentClass"].includes(dataKey)) continue;
foundry.utils.setProperty(docData, dataKey, value);
}
docCls.create(docData, { parent: this.actor });
}
/* -------------------------------------------------- */
/**
* Determines effect parent to pass to helper.
*
* @this M6ActorSheet
* @param {PointerEvent} event The originating click event.
* @param {HTMLElement} target The capturing HTML element which defined a [data-action].
* @private
*/
static async #toggleEffect(event, target) {
const effect = this._getEmbeddedDocument(target);
effect.update({ disabled: !effect.disabled });
}
static async #rollSkill(event, target) {
console.warn(event, target.dataset);
// Construct the Roll instance
const skillValue = target.dataset.value;
let roll = new Roll("2d20kh + @skill", { skill: skillValue }, { flavor: target.dataset.name });
// The parsed terms of the roll formula
console.log("Roll:", roll); // [Die, OperatorTerm, NumericTerm, OperatorTerm, NumericTerm]
// Execute the roll
await roll.evaluate();
roll.toMessage();
roll.toAnchor();
// let message = new Message(roll);
// console.warn(message);
}
/* -------------------------------------------------- */
/* Helper functions */
/* -------------------------------------------------- */
/**
* Fetches the embedded document representing the containing HTML element.
*
* @param {HTMLElement} target The element subject to search.
* @returns {Item|ActiveEffect} The embedded Item or ActiveEffect.
*/
_getEmbeddedDocument(target) {
const docRow = target.closest("li[data-document-class]");
if (docRow.dataset.documentClass === "Item") {
return this.actor.items.get(docRow.dataset.itemId);
} else if (docRow.dataset.documentClass === "ActiveEffect") {
const parent =
docRow.dataset.parentId === this.actor.id
? this.actor
: this.actor.items.get(docRow?.dataset.parentId);
return parent.effects.get(docRow.dataset.effectId);
} else {
console.warn("Could not find document class");
}
}
/* -------------------------------------------------- */
/* Actor override handling */
/* -------------------------------------------------- */
/**
* Submit a document update based on the processed form data.
* @param {SubmitEvent} event The originating form submission event.
* @param {HTMLFormElement} form The form element that was submitted.
* @param {object} submitData Processed and validated form data to be used for a document update.
* @returns {Promise<void>}
* @protected
* @inheritdoc
*/
async _processSubmitData(event, form, submitData) {
const overrides = foundry.utils.flattenObject(this.actor.overrides);
for (const k of Object.keys(overrides)) delete submitData[k];
this.document.update(submitData);
}
/* -------------------------------------------------- */
/**
* Disables inpM6 subject to active effects.
*/
#disableOverrides() {
const flatOverrides = foundry.utils.flattenObject(this.actor.overrides);
for (const override of Object.keys(flatOverrides)) {
const input = this.element.querySelector(`[name="${override}"]`);
if (input) input.disabled = true;
}
}
}
-32
View File
@@ -1,32 +0,0 @@
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { CharacterSheetApp } from "./components/CharacterSheetApp";
export class CharacterSheet extends foundry.applications.sheets.ActorSheetV2 {
static DEFAULT_OPTIONS = {
classes: ["fvtt-ts-react-boilerplate", "sheet", "actor"],
position: { width: 600, height: 480 }
};
#root: Root | null = null;
override async _renderHTML(
...args: Parameters<foundry.applications.sheets.ActorSheetV2["_renderHTML"]>
) {
return args[0];
}
override _replaceHTML(
...args: Parameters<foundry.applications.sheets.ActorSheetV2["_replaceHTML"]>
) {
const content = args[1];
if (!this.#root) this.#root = createRoot(content);
this.#root.render(React.createElement(CharacterSheetApp, { actor: this.document }));
}
override async close(...args: Parameters<foundry.applications.sheets.ActorSheetV2["close"]>) {
this.#root?.unmount();
this.#root = null;
return super.close(...args);
}
}
@@ -1,23 +0,0 @@
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");
});
});
@@ -1,6 +0,0 @@
// 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}`);
@@ -1,38 +0,0 @@
.sheet {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.5rem;
}
.attributes {
display: flex;
gap: 1rem;
}
.attributeLabel {
display: flex;
flex-direction: column;
font-size: 0.8rem;
text-transform: capitalize;
.modifier {
font-weight: bold;
text-align: center;
}
}
.totals {
display: flex;
gap: 1rem;
font-weight: bold;
}
.chatRow {
display: flex;
gap: 0.5rem;
input {
flex: 1;
}
}
@@ -1,75 +0,0 @@
import React, { useState } from "react";
import styles from "./CharacterSheetApp.module.scss";
import { localize } from "../../i18n";
import { modifier, fmtMod } from "./CharacterSheetApp.logic";
export function CharacterSheetApp({ actor }: { actor: Actor.Implementation }) {
const system = actor.system;
const attrs = system.attributes;
const [chatMessage, setChatMessage] = useState("");
const updateAttribute = (key: "strength" | "agility" | "spirit", value: number) => {
actor.update({ system: { attributes: { [key]: value } } });
};
const updateBiography = (value: string) => {
actor.update({ system: { biography: value } });
};
const sendChatMessage = () => {
if (!chatMessage.trim()) return;
ChatMessage.create({
speaker: ChatMessage.getSpeaker({ actor }),
content: chatMessage
});
setChatMessage("");
};
// derived purely from current doc state — recomputed every render, no local state needed
const total = attrs.strength + attrs.agility + attrs.spirit;
const totalMod = modifier(attrs.strength) + modifier(attrs.agility) + modifier(attrs.spirit);
return (
<div className={styles.sheet}>
<h1>{actor.name}</h1>
<div className={styles.attributes}>
{(["strength", "agility", "spirit"] as const).map((key) => (
<label className={styles.attributeLabel} key={key}>
{localize(`BOILERPLATE.Attributes.${key}`)}
<input
type="number"
value={attrs[key]}
onChange={(e) => updateAttribute(key, Number(e.target.value))}
/>
<span className={styles.modifier}>{fmtMod(modifier(attrs[key]))}</span>
</label>
))}
</div>
<div className={styles.totals}>
<span>
{localize("BOILERPLATE.Sheet.Total")}: {total}
</span>
<span>
{localize("BOILERPLATE.Sheet.TotalMod")}: {fmtMod(totalMod)}
</span>
</div>
<label className={styles.attributeLabel}>
{localize("BOILERPLATE.Sheet.Biography")}
<textarea defaultValue={system.biography} onBlur={(e) => updateBiography(e.target.value)} />
</label>
<div className={styles.chatRow}>
<input
type="text"
placeholder={localize("BOILERPLATE.Sheet.ChatPlaceholder")}
value={chatMessage}
onChange={(e) => setChatMessage(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendChatMessage()}
/>
<button type="button" onClick={sendChatMessage}>
{localize("BOILERPLATE.Sheet.SendToChat")}
</button>
</div>
</div>
);
}
@@ -1,13 +0,0 @@
.sheet {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.5rem;
}
.label {
display: flex;
flex-direction: column;
font-size: 0.8rem;
text-transform: capitalize;
}
-37
View File
@@ -1,37 +0,0 @@
import React from "react";
import styles from "./ItemSheetApp.module.scss";
import { localize } from "../../i18n";
export function ItemSheetApp({ item }: { item: Item.Implementation }) {
const system = item.system;
const updateQuantity = (value: number) => {
item.update({ system: { quantity: value } });
};
const updateDescription = (value: string) => {
item.update({ system: { description: value } });
};
return (
<div className={styles.sheet}>
<h1>{item.name}</h1>
<label className={styles.label}>
{localize("BOILERPLATE.Item.Quantity")}
<input
type="number"
min={0}
value={system.quantity}
onChange={(e) => updateQuantity(Number(e.target.value))}
/>
</label>
<label className={styles.label}>
{localize("BOILERPLATE.Item.Description")}
<textarea
defaultValue={system.description}
onBlur={(e) => updateDescription(e.target.value)}
/>
</label>
</div>
);
}
-32
View File
@@ -1,32 +0,0 @@
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { ItemSheetApp } from "./components/ItemSheetApp";
export class ItemSheet extends foundry.applications.sheets.ItemSheetV2 {
static DEFAULT_OPTIONS = {
classes: ["fvtt-ts-react-boilerplate", "sheet", "item"],
position: { width: 480, height: 360 }
};
#root: Root | null = null;
override async _renderHTML(
...args: Parameters<foundry.applications.sheets.ItemSheetV2["_renderHTML"]>
) {
return args[0];
}
override _replaceHTML(
...args: Parameters<foundry.applications.sheets.ItemSheetV2["_replaceHTML"]>
) {
const content = args[1];
if (!this.#root) this.#root = createRoot(content);
this.#root.render(React.createElement(ItemSheetApp, { item: this.document }));
}
override async close(...args: Parameters<foundry.applications.sheets.ItemSheetV2["close"]>) {
this.#root?.unmount();
this.#root = null;
return super.close(...args);
}
}