-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
226 lines (185 loc) · 7.77 KB
/
Copy pathutils.ts
File metadata and controls
226 lines (185 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { MonsterData, ThemeConfig } from "./types";
import { mapAiToFoundry } from "./foundryMapper";
export const STORAGE_KEY_API = "dh_gemini_api_key";
export const STORAGE_KEY_LIBRARY = "dh_monster_library";
export const STORAGE_KEY_LAST_ID = "dh_last_active_id";
export const STORAGE_KEY_THEME = "dh_user_theme";
export const STORAGE_KEY_LANG = "dh_user_lang";
export const DEFAULT_THEME: ThemeConfig = {
// Card Defaults (Book Style Dark)
cardBgStart: "#111318",
cardBgEnd: "#161b22",
cardBorder: "#30363d",
cardTextHeader: "#f0f6fc",
cardTextMain: "#c9d1d9",
cardAccent: "#d4af37",
// Stats Specifics
cardValDiff: "#f0f6fc", // White/Blue-ish
cardValHp: "#4ade80", // Green
cardValStress: "#f472b6", // Pink
cardValThreshMajor: "#fbbf24", // Amber/Yellow
cardValThreshSevere: "#ef4444", // Red
cardValDamage: "#f87171", // Light Red
// Fonts
fontHeader: '"Crimson Text", serif',
fontBody: '"Inter", sans-serif',
// UI Defaults
uiBgMain: "#030712", // gray-950
uiBgSidebar: "#111827", // gray-900
uiTextPrimary: "#e5e7eb", // gray-200
uiAccent: "#4f46e5" // indigo-600
};
export const saveLibrary = (monsters: MonsterData[]) => {
localStorage.setItem(STORAGE_KEY_LIBRARY, JSON.stringify(monsters));
};
export const loadLibrary = (): MonsterData[] => {
const stored = localStorage.getItem(STORAGE_KEY_LIBRARY);
return stored ? JSON.parse(stored) : [];
};
export const generateId = (length = 16) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
};
// Map descriptive damage types to strict Foundry keys
export const sanitizeDamageType = (val: string): string => {
if (!val) return "physical";
const lower = val.toLowerCase().trim();
if (["physical", "fisico", "físico", "slashing", "piercing", "bludgeoning", "corte", "perfurante", "contundente"].includes(lower)) {
return "physical";
}
return "magical";
};
// Helper to prevent 404s in Web App Preview
export const sanitizeImageForHtml = (img: string | undefined): string => {
if (!img) return "";
if (img.startsWith("icons/") || img.startsWith("systems/") || !img.startsWith("http")) {
return "";
}
return img;
};
// --- NEW: PARSER FOR FOUNDRY OBJECT STRUCTURE ---
export const parseDaggerheartDamage = (formula: string) => {
const defaultStructure = {
multiplier: "flat",
flatMultiplier: 1,
dice: "d6",
bonus: 0,
custom: { enabled: false, formula: "" }
};
if (!formula) return defaultStructure;
// Remove HTML tags first
let clean = formula.replace(/<[^>]*>/g, '');
// Aggressive Extraction: Look for the first "XdY+Z" or "XdY" pattern in the string.
// This handles inputs like "1d8 de dano" -> extracts "1d8"
const strictRegex = /(\d+d\d+)(\s*[+\-]\s*\d+)?/i;
const extractMatch = clean.match(strictRegex);
if (extractMatch) {
// extractMatch[0] is the clean formula (e.g. "1d8" or "2d6+4")
const fullFormula = extractMatch[0].replace(/\s/g, '');
// Now parse the clean formula into components
const parseRegex = /^(\d+)(d\d+)(?:([+\-])(\d+))?$/i;
const parts = fullFormula.match(parseRegex);
if (parts) {
const count = parseInt(parts[1], 10);
const dice = parts[2].toLowerCase(); // d8
const operator = parts[3];
let bonus = 0;
if (operator && parts[4]) {
const rawBonus = parseInt(parts[4], 10);
bonus = operator === '-' ? -rawBonus : rawBonus;
}
return {
multiplier: "flat",
flatMultiplier: count,
dice: dice,
bonus: bonus,
custom: { enabled: false, formula: "" }
};
}
}
// Fallback: If no formula pattern found, assume it's custom text or fixed number.
// We clean whitespace to avoid "1d8deDano" if it failed regex (unlikely if it had dX),
// but useful for "5" or "Varies".
clean = clean.replace(/\s/g, '');
return {
...defaultStructure,
custom: { enabled: true, formula: clean }
};
};
// Helper to build a valid Cost Object
// CRITICAL FIX: itemId is required for the system to know where to deduct resources from if embedded
export const buildCost = (key: string, value: number, itemId: string | null = null) => ({
key,
value,
itemId: itemId,
scalable: false,
step: null,
consumeOnSuccess: false
});
// NEW: Simple Markdown to HTML converter for Foundry export
export const markdownToHtml = (text: string): string => {
if (!text) return "";
let html = text;
// Headers (## Title -> <h3>Title</h3>)
html = html.replace(/^### (.*$)/gim, '<h4>$1</h4>');
html = html.replace(/^## (.*$)/gim, '<h3>$1</h3>');
html = html.replace(/^# (.*$)/gim, '<h2>$1</h2>');
// Bold (**text** -> <strong>text</strong>)
html = html.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>');
// Italic (*text* -> <em>text</em>)
html = html.replace(/\*(.*?)\*/gim, '<em>$1</em>');
// Lists (- item -> <li>item</li>) - Basic
html = html.replace(/^\s*-\s+(.*$)/gim, '<li>$1</li>');
// Newlines to Paragraphs/Breaks
// Double newline -> P
html = html.replace(/\n\n/g, '</p><p>');
// Single newline -> BR
html = html.replace(/\n/g, '<br>');
// Wrap in initial p if not already
if (!html.startsWith('<')) {
html = `<p>${html}</p>`;
}
return html;
};
// Wrapper to maintain interface with index.tsx but use new mapper
export const enrichFoundryJson = (inputData: any, analysisText: string | null = null) => {
// If inputData is already a full Foundry structure (from import), passthrough mostly,
// but we can re-run map if it looks like the AI schema.
if (inputData.stats) {
return mapAiToFoundry(inputData, analysisText);
}
// Otherwise it's likely already Foundry Format (Legacy Import or simple update)
// CRITICAL: Ensure Analysis is injected into system.notes for Foundry
if (analysisText) {
if (!inputData.flags) inputData.flags = {};
if (!inputData.flags['daggerheart-generator']) inputData.flags['daggerheart-generator'] = {};
// Save raw markdown in flags for the Generator App
inputData.flags['daggerheart-generator'].analysis = analysisText;
// Save HTML version in system.notes for Foundry VTT display
// We override notes because the analysis IS the primary note in this workflow
inputData.system.notes = markdownToHtml(analysisText);
}
return inputData;
};
// NEW HELPER: Formats Markdown to ensure it renders beautifully
// Fixes "Word.##Title" glued together issues, but is LESS AGGRESSIVE
export const formatMarkdown = (text: string): string => {
if (!text) return "";
let formatted = text;
// 1. Ensure newlines before headers (Fixes "Text.## Header")
// Use regex to look for ## Header and force double newline before it
formatted = formatted.replace(/([^\n])\s*(#{1,3}\s)/g, '$1\n\n$2');
// 2. Ensure newlines AFTER headers (Fixes "## HeaderText")
// This looks for "## Header Text" followed immediately by text on next line or same line
// It captures the header line, ensures a newline char, then the body text
formatted = formatted.replace(/^(#{1,3}\s.*?)(\n)?([A-Za-z0-9])/gm, '$1\n\n$3');
// 3. Ensure list spacing
formatted = formatted.replace(/([^\n])\s*(- \w)/g, '$1\n$2');
// 4. Remove HTML break tags if they snuck in, replace with newline
formatted = formatted.replace(/<br\s*\/?>/gi, '\n\n');
return formatted;
};