Export as Datapack

This commit is contained in:
Maxime Reynier
2025-08-12 14:31:45 +02:00
parent 87c54a25f1
commit fb9443d79c
9 changed files with 435 additions and 331 deletions

95
package-lock.json generated
View File

@@ -9,12 +9,15 @@
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@tailwindcss/forms": "^0.5.10", "@tailwindcss/forms": "^0.5.10",
"file-saver": "^2.0.5",
"jszip": "^3.10.1",
"lucide-react": "^0.539.0", "lucide-react": "^0.539.0",
"react": "^19.1.1", "react": "^19.1.1",
"react-dom": "^19.1.1" "react-dom": "^19.1.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.32.0", "@eslint/js": "^9.32.0",
"@types/file-saver": "^2.0.7",
"@types/react": "^19.1.9", "@types/react": "^19.1.9",
"@types/react-dom": "^19.1.7", "@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^4.7.0", "@vitejs/plugin-react": "^4.7.0",
@@ -1448,6 +1451,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/file-saver": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/file-saver/-/file-saver-2.0.7.tgz",
"integrity": "sha512-dNKVfHd/jk0SkR/exKGj2ggkB45MAkzvWCaqLUUgkyjITkGNzH8H+yUwr+BLJUBjZOe9w8X3wgmXhZDRg1ED6A==",
"dev": true
},
"node_modules/@types/json-schema": { "node_modules/@types/json-schema": {
"version": "7.0.15", "version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -2112,6 +2121,11 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
"node_modules/cross-spawn": { "node_modules/cross-spawn": {
"version": "7.0.6", "version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -2527,6 +2541,11 @@
"node": ">=16.0.0" "node": ">=16.0.0"
} }
}, },
"node_modules/file-saver": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/file-saver/-/file-saver-2.0.5.tgz",
"integrity": "sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA=="
},
"node_modules/fill-range": { "node_modules/fill-range": {
"version": "7.1.1", "version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -2748,6 +2767,11 @@
"node": ">= 4" "node": ">= 4"
} }
}, },
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="
},
"node_modules/import-fresh": { "node_modules/import-fresh": {
"version": "3.3.1", "version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -2775,6 +2799,11 @@
"node": ">=0.8.19" "node": ">=0.8.19"
} }
}, },
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"node_modules/is-binary-path": { "node_modules/is-binary-path": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
@@ -2841,6 +2870,11 @@
"node": ">=0.12.0" "node": ">=0.12.0"
} }
}, },
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
},
"node_modules/isexe": { "node_modules/isexe": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
@@ -2941,6 +2975,17 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/jszip": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
"integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
"dependencies": {
"lie": "~3.3.0",
"pako": "~1.0.2",
"readable-stream": "~2.3.6",
"setimmediate": "^1.0.5"
}
},
"node_modules/keyv": { "node_modules/keyv": {
"version": "4.5.4", "version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -2965,6 +3010,14 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
"integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/lightningcss": { "node_modules/lightningcss": {
"version": "1.30.1", "version": "1.30.1",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.1.tgz", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.1.tgz",
@@ -3472,6 +3525,11 @@
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"license": "BlueOak-1.0.0" "license": "BlueOak-1.0.0"
}, },
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="
},
"node_modules/parent-module": { "node_modules/parent-module": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -3721,6 +3779,11 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
},
"node_modules/punycode": { "node_modules/punycode": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -3791,6 +3854,20 @@
"pify": "^2.3.0" "pify": "^2.3.0"
} }
}, },
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readdirp": { "node_modules/readdirp": {
"version": "3.6.0", "version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -3906,6 +3983,11 @@
"queue-microtask": "^1.2.2" "queue-microtask": "^1.2.2"
} }
}, },
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/scheduler": { "node_modules/scheduler": {
"version": "0.26.0", "version": "0.26.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz",
@@ -3922,6 +4004,11 @@
"semver": "bin/semver.js" "semver": "bin/semver.js"
} }
}, },
"node_modules/setimmediate": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
"integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="
},
"node_modules/shebang-command": { "node_modules/shebang-command": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
@@ -3964,6 +4051,14 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string-width": { "node_modules/string-width": {
"version": "5.1.2", "version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",

View File

@@ -11,12 +11,15 @@
}, },
"dependencies": { "dependencies": {
"@tailwindcss/forms": "^0.5.10", "@tailwindcss/forms": "^0.5.10",
"file-saver": "^2.0.5",
"jszip": "^3.10.1",
"lucide-react": "^0.539.0", "lucide-react": "^0.539.0",
"react": "^19.1.1", "react": "^19.1.1",
"react-dom": "^19.1.1" "react-dom": "^19.1.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.32.0", "@eslint/js": "^9.32.0",
"@types/file-saver": "^2.0.7",
"@types/react": "^19.1.9", "@types/react": "^19.1.9",
"@types/react-dom": "^19.1.7", "@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^4.7.0", "@vitejs/plugin-react": "^4.7.0",

View File

@@ -16,18 +16,20 @@ function App() {
const [activeTab, setActiveTab] = useState<Tab>('basic'); const [activeTab, setActiveTab] = useState<Tab>('basic');
const [npcConfig, setNpcConfig] = useState<NPCConfiguration>({ const [npcConfig, setNpcConfig] = useState<NPCConfiguration>({
id: 'my_npc',
name: 'My NPC',
hitbox: "player", hitbox: "player",
presets: [],
resourceIdentifier: "cobblemon:my_npc",
config: [], config: [],
names: ["My NPC"], names: ["My NPC"],
interaction: { type: "none" } interactions: [],
interaction: { type: 'none' },
resourceIdentifier: 'cobblemon:my_npc'
}); });
const [dialogueConfig, setDialogueConfig] = useState<DialogueConfiguration | null>(null); const [dialogueConfig, setDialogueConfig] = useState<DialogueConfiguration | null>(null);
useEffect(() => { useEffect(() => {
if (npcConfig.interaction.type === 'dialogue' && !dialogueConfig) { if (npcConfig.interactions && npcConfig.interactions.length > 0 && npcConfig.interactions[0].type === 'dialogue' && !dialogueConfig) {
const newDialogue: DialogueConfiguration = { const newDialogue: DialogueConfiguration = {
speakers: { speakers: {
npc: { npc: {
@@ -48,7 +50,7 @@ function App() {
}; };
setDialogueConfig(newDialogue); setDialogueConfig(newDialogue);
} }
}, [npcConfig.interaction.type]); }, [npcConfig.interactions, dialogueConfig]);
const tabs = [ const tabs = [
{ id: 'basic', name: 'Basic Settings', icon: Settings }, { id: 'basic', name: 'Basic Settings', icon: Settings },
@@ -80,10 +82,13 @@ function App() {
case 'import': case 'import':
return ( return (
<ImportExport <ImportExport
npcConfig={npcConfig} npcConfigs={[npcConfig]}
dialogueConfig={dialogueConfig} dialogueConfiguration={dialogueConfig}
onNPCConfigLoad={setNpcConfig} onImport={(configs) => {
onDialogueConfigLoad={setDialogueConfig} if (configs.length > 0) {
setNpcConfig(configs[0]);
}
}}
/> />
); );
default: default:
@@ -155,11 +160,15 @@ function App() {
</div> </div>
<div> <div>
<dt className="font-medium text-gray-700">Interaction</dt> <dt className="font-medium text-gray-700">Interaction</dt>
<dd className="text-gray-600 capitalize">{npcConfig.interaction.type}</dd> <dd className="text-gray-600 capitalize">
{npcConfig.interactions && npcConfig.interactions.length > 0
? npcConfig.interactions[0].type
: 'none'}
</dd>
</div> </div>
<div> <div>
<dt className="font-medium text-gray-700">Variables</dt> <dt className="font-medium text-gray-700">Variables</dt>
<dd className="text-gray-600">{npcConfig.config.length}</dd> <dd className="text-gray-600">{npcConfig.config?.length || 0}</dd>
</div> </div>
</dl> </dl>
</div> </div>
@@ -188,4 +197,4 @@ function App() {
); );
} }
export default App; export default App;

View File

@@ -18,19 +18,19 @@ export function ConfigVariablesEditor({ config, onChange }: ConfigVariablesEdito
onChange({ onChange({
...config, ...config,
config: [...config.config, newVariable] config: [...(config.config || []), newVariable]
}); });
}; };
const removeVariable = (index: number) => { const removeVariable = (index: number) => {
onChange({ onChange({
...config, ...config,
config: config.config.filter((_, i) => i !== index) config: (config.config || []).filter((_, i) => i !== index)
}); });
}; };
const updateVariable = (index: number, field: keyof MoLangConfigVariable, value: any) => { const updateVariable = (index: number, field: keyof MoLangConfigVariable, value: any) => {
const newConfig = [...config.config]; const newConfig = [...(config.config || [])];
newConfig[index] = { ...newConfig[index], [field]: value }; newConfig[index] = { ...newConfig[index], [field]: value };
onChange({ onChange({
...config, ...config,
@@ -57,13 +57,13 @@ export function ConfigVariablesEditor({ config, onChange }: ConfigVariablesEdito
These variables can be referenced in dialogues, scripts, and other configurations. These variables can be referenced in dialogues, scripts, and other configurations.
</p> </p>
{config.config.length === 0 ? ( {(config.config || []).length === 0 ? (
<div className="text-center py-8 text-gray-500"> <div className="text-center py-8 text-gray-500">
No configuration variables defined. Click "Add Variable" to create one. No configuration variables defined. Click "Add Variable" to create one.
</div> </div>
) : ( ) : (
<div className="space-y-4"> <div className="space-y-4">
{config.config.map((variable, index) => ( {(config.config || []).map((variable, index) => (
<div key={index} className="border rounded-lg p-4 space-y-3"> <div key={index} className="border rounded-lg p-4 space-y-3">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<h3 className="font-medium text-lg">Variable {index + 1}</h3> <h3 className="font-medium text-lg">Variable {index + 1}</h3>

View File

@@ -1,172 +1,202 @@
import { useRef, useState } from 'react'; import React, { useRef, useState } from 'react';
import { Upload, Download, FileText, AlertTriangle } from 'lucide-react'; import { Download, FileText, Package } from 'lucide-react';
import type { NPCConfiguration, DialogueConfiguration } from '../types/npc'; import JSZip from 'jszip';
import type {DialogueConfiguration, NPCConfig} from '../types/npc';
interface ImportExportProps { interface ImportExportProps {
npcConfig: NPCConfiguration; npcConfigs: NPCConfig[];
dialogueConfig: DialogueConfiguration | null; dialogueConfiguration: DialogueConfiguration | null;
onNPCConfigLoad: (config: NPCConfiguration) => void; onImport: (configs: NPCConfig[]) => void;
onDialogueConfigLoad: (config: DialogueConfiguration) => void;
} }
export function ImportExport({ const MINECRAFT_VERSIONS = [
npcConfig, { value: '1.20.1', label: 'Minecraft 1.20.1' },
dialogueConfig, { value: '1.20.2', label: 'Minecraft 1.20.2' },
onNPCConfigLoad, { value: '1.20.3', label: 'Minecraft 1.20.3' },
onDialogueConfigLoad { value: '1.20.4', label: 'Minecraft 1.20.4' },
}: ImportExportProps) { { value: '1.20.5', label: 'Minecraft 1.20.5' },
{ value: '1.20.6', label: 'Minecraft 1.20.6' },
{ value: '1.21', label: 'Minecraft 1.21' },
{ value: '1.21.1', label: 'Minecraft 1.21.1' },
];
const PACK_FORMAT: { [key: string]: number } = {
'1.20.1': 15,
'1.20.2': 18,
'1.20.3': 26,
'1.20.4': 26,
'1.20.5': 41,
'1.20.6': 48,
'1.21': 48,
'1.21.1': 48,
};
export function ImportExport({ npcConfigs, dialogueConfiguration, onImport }: ImportExportProps) {
const npcFileInputRef = useRef<HTMLInputElement>(null); const npcFileInputRef = useRef<HTMLInputElement>(null);
const dialogueFileInputRef = useRef<HTMLInputElement>(null); const [exportError, setExportError] = useState<string | null>(null);
const [importError, setImportError] = useState<string | null>(null); const [importError, setImportError] = useState<string | null>(null);
const [importSuccess, setImportSuccess] = useState<string | null>(null); const [importSuccess, setImportSuccess] = useState<string | null>(null);
const [minecraftVersion, setMinecraftVersion] = useState('1.20.1');
const [datapackName, setDatapackName] = useState('cobblemon_npcs');
const handleImportNPCs = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
setImportError(null);
setImportSuccess(null);
const handleFileRead = (
file: File,
onLoad: (config: any) => void,
configType: string
) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (e) => { reader.onload = (e) => {
try { try {
const content = e.target?.result as string; const content = e.target?.result as string;
const config = JSON.parse(content); const configs = JSON.parse(content);
// Basic validation if (!Array.isArray(configs)) {
if (configType === 'npc') { setImportError('Le fichier doit contenir un tableau de configurations NPC');
if (!config.resourceIdentifier || !config.names) { return;
throw new Error('Invalid NPC configuration: missing required fields'); }
}
} else if (configType === 'dialogue') { // Validation basique de la structure
if (!config.pages || !config.speakers) { for (let index = 0; index < configs.length; index++) {
throw new Error('Invalid dialogue configuration: missing required fields'); const config = configs[index];
if (!config.id || !config.name) {
setImportError(`Configuration NPC ${index + 1} invalide: id et name sont requis`);
return;
} }
} }
onLoad(config); onImport(configs);
setImportSuccess(`${configType} configuration loaded successfully!`); setImportSuccess(`${configs.length} configuration(s) NPC importée(s) avec succès`);
setImportError(null);
setTimeout(() => setImportSuccess(null), 3000); // Reset input
if (npcFileInputRef.current) {
npcFileInputRef.current.value = '';
}
} catch (error) { } catch (error) {
setImportError(`Error loading ${configType}: ${error instanceof Error ? error.message : 'Invalid JSON'}`); setImportError(error instanceof Error ? error.message : 'Erreur lors de l\'importation');
setImportSuccess(null);
} }
}; };
reader.readAsText(file); reader.readAsText(file);
}; };
const handleNPCFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => { const generatePackMcmeta = (version: string, packName: string) => {
const file = event.target.files?.[0]; const packFormat = PACK_FORMAT[version] || 15;
if (file) {
handleFileRead(file, onNPCConfigLoad, 'npc');
}
};
const handleDialogueFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => { return {
const file = event.target.files?.[0]; pack: {
if (file) { pack_format: packFormat,
handleFileRead(file, onDialogueConfigLoad, 'dialogue'); description: `${packName} - Datapack pour Cobblemon avec NPCs personnalisés`
}
};
const exportExample = () => {
const exampleNPC: NPCConfiguration = {
hitbox: "player",
presets: [],
resourceIdentifier: "mymod:example_npc",
config: [
{
variableName: "greeting_message",
displayName: "Greeting Message",
description: "The message displayed when first talking to the NPC",
type: "TEXT",
defaultValue: "Hello, trainer!"
}
],
isInvulnerable: true,
canDespawn: false,
names: ["Example NPC"],
interaction: {
type: "dialogue",
dialogue: "mymod:example_dialogue"
},
battleConfiguration: {
canChallenge: true
},
skill: 3,
party: {
type: "simple",
pokemon: [
"pikachu level=25 moves=thunderbolt,quick-attack",
"charmander level=24 moves=ember,scratch"
]
} }
}; };
};
const exampleDialogue: DialogueConfiguration = { const generateNPCFile = (npc: NPCConfig) => {
speakers: { return {
npc: { aspects: npc.aspects || [],
name: { type: "expression", expression: "q.npc.name" }, model: npc.model || "cobblemon:generic_npc",
face: "q.npc.face(false);" dialogue: npc.dialogue ? [`${npc.id}_dialogue`] : [],
}, party: npc.party || [],
player: { battleTheme: npc.battleConfiguration?.battleTheme || "",
name: { type: "expression", expression: "q.player.username" }, victoryTheme: npc.battleConfiguration?.victoryTheme || "",
face: "q.player.face();" defeatTheme: npc.battleConfiguration?.defeatTheme || "",
} canBattle: npc.battleConfiguration?.canBattle || false,
}, ...npc.configVariables
pages: [
{
id: "greeting",
speaker: "npc",
lines: ["Hello there, trainer! Would you like to battle?"],
input: {
type: "option",
vertical: true,
options: [
{
text: "Yes, let's battle!",
value: "accept",
action: ["q.npc.start_battle(q.player, 'single');"]
},
{
text: "Maybe later.",
value: "decline",
action: ["q.dialogue.close();"]
}
]
}
}
]
}; };
};
// Download both files const exportAsDatapack = async () => {
const downloadFile = (content: string, filename: string) => { try {
const blob = new Blob([content], { type: 'application/json' }); setExportError(null);
const url = URL.createObjectURL(blob);
if (npcConfigs.length === 0) {
setExportError('Aucune configuration NPC à exporter');
return;
}
if (!datapackName.trim()) {
setExportError('Le nom du datapack est requis');
return;
}
const zip = new JSZip();
// Générer pack.mcmeta
const packMcmeta = generatePackMcmeta(minecraftVersion, datapackName);
zip.file('pack.mcmeta', JSON.stringify(packMcmeta, null, 2));
// Créer les dossiers de structure
const dataFolder = zip.folder('data');
const cobblemonFolder = dataFolder!.folder('cobblemon');
const npcsFolder = cobblemonFolder!.folder('npc');
const dialogueFolder = cobblemonFolder!.folder('dialogue');
// Générer les fichiers pour chaque NPC
for (const npc of npcConfigs) {
// Fichier NPC
const npcFile = generateNPCFile(npc);
npcsFolder!.file(`${npc.id}.json`, JSON.stringify(npcFile, null, 2));
console.log(dialogueConfiguration)
if (dialogueConfiguration) {
console.log(dialogueConfiguration)
// Utiliser la même approche que JSONPreview.tsx - sérialisation directe
const dialogueJson = JSON.stringify(dialogueConfiguration, null, 2);
dialogueFolder!.file(`${npc.id}_dialogue.json`, dialogueJson);
}
}
// Générer le ZIP et déclencher le téléchargement
const content = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(content);
const a = document.createElement('a'); const a = document.createElement('a');
a.href = url; a.href = url;
a.download = filename; a.download = `${datapackName}.zip`;
document.body.appendChild(a);
a.click(); a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
};
downloadFile(JSON.stringify(exampleNPC, null, 2), 'example_npc.json'); } catch (error) {
downloadFile(JSON.stringify(exampleDialogue, null, 2), 'example_dialogue.json'); setExportError(error instanceof Error ? error.message : 'Erreur lors de l\'exportation');
}
};
const exportAsJSON = () => {
try {
setExportError(null);
const dataStr = JSON.stringify(npcConfigs, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = 'npc_configurations.json';
link.click();
URL.revokeObjectURL(url);
} catch (error) {
setExportError(error instanceof Error ? error.message : 'Erreur lors de l\'exportation');
}
}; };
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<h2 className="text-xl font-semibold text-gray-900">Import & Export</h2> <h2 className="text-xl font-semibold text-gray-900">Import / Export</h2>
{exportError && (
<div className="bg-red-50 border border-red-200 rounded-md p-4">
<div className="flex">
<FileText className="h-5 w-5 text-red-400" />
<div className="ml-3">
<p className="text-sm font-medium text-red-800">{exportError}</p>
</div>
</div>
</div>
)}
{/* Status Messages */}
{importError && ( {importError && (
<div className="bg-red-50 border border-red-200 rounded-md p-4"> <div className="bg-red-50 border border-red-200 rounded-md p-4">
<div className="flex"> <div className="flex">
<AlertTriangle className="h-5 w-5 text-red-400" /> <FileText className="h-5 w-5 text-red-400" />
<div className="ml-3"> <div className="ml-3">
<h3 className="text-sm font-medium text-red-800">Import Error</h3> <p className="text-sm font-medium text-red-800">{importError}</p>
<p className="text-sm text-red-700">{importError}</p>
</div> </div>
</div> </div>
</div> </div>
@@ -197,118 +227,81 @@ export function ImportExport({
ref={npcFileInputRef} ref={npcFileInputRef}
type="file" type="file"
accept=".json" accept=".json"
onChange={handleNPCFileSelect} onChange={handleImportNPCs}
className="hidden" className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
/> />
<button <p className="text-xs text-gray-500 mt-1">
type="button" Fichier JSON contenant un tableau de configurations NPC
onClick={() => npcFileInputRef.current?.click()} </p>
className="w-full inline-flex items-center justify-center px-4 py-2 border border-gray-300 shadow-sm bg-white text-sm font-medium text-gray-700 rounded-md hover:bg-gray-50"
>
<Upload className="h-4 w-4 mr-2" />
Choose NPC JSON File
</button>
</div> </div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Import Dialogue Configuration
</label>
<input
ref={dialogueFileInputRef}
type="file"
accept=".json"
onChange={handleDialogueFileSelect}
className="hidden"
/>
<button
type="button"
onClick={() => dialogueFileInputRef.current?.click()}
className="w-full inline-flex items-center justify-center px-4 py-2 border border-gray-300 shadow-sm bg-white text-sm font-medium text-gray-700 rounded-md hover:bg-gray-50"
>
<Upload className="h-4 w-4 mr-2" />
Choose Dialogue JSON File
</button>
</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h4 className="font-medium text-blue-900 text-sm">Import Tips</h4>
<ul className="mt-2 text-xs text-blue-800 space-y-1">
<li> Files must be valid JSON format</li>
<li> NPC configs require resourceIdentifier and names</li>
<li> Dialogue configs require pages and speakers</li>
<li> Import will override current configuration</li>
</ul>
</div> </div>
</div> </div>
{/* Export/Examples Section */} {/* Export Section */}
<div className="space-y-4"> <div className="space-y-4">
<h3 className="text-lg font-medium text-gray-900">Examples & Templates</h3> <h3 className="text-lg font-medium text-gray-900">Export Configurations</h3>
<div className="space-y-3"> <div className="space-y-4">
<button {/* Configuration du Datapack */}
type="button" <div className="bg-gray-50 p-4 rounded-lg space-y-3">
onClick={exportExample} <h4 className="text-sm font-medium text-gray-900">Configuration du Datapack</h4>
className="w-full inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
> <div>
<Download className="h-4 w-4 mr-2" /> <label className="block text-sm font-medium text-gray-700 mb-1">
Download Example Files Version Minecraft
</button> </label>
<select
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4"> value={minecraftVersion}
<h4 className="font-medium text-gray-900 text-sm mb-2">Example Includes:</h4> onChange={(e) => setMinecraftVersion(e.target.value)}
<ul className="text-xs text-gray-700 space-y-1"> className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
<li> Complete NPC with battle configuration</li> >
<li> Simple dialogue with options</li> {MINECRAFT_VERSIONS.map(version => (
<li> Configuration variables example</li> <option key={version.value} value={version.value}>
<li> Battle party setup</li> {version.label}
<li> MoLang expressions</li> </option>
</ul> ))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Nom du Datapack
</label>
<input
type="text"
value={datapackName}
onChange={(e) => setDatapackName(e.target.value)}
placeholder="nom_du_datapack"
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
/>
</div>
</div>
{/* Boutons d'export */}
<div className="space-y-3">
<button
onClick={exportAsDatapack}
disabled={npcConfigs.length === 0}
className="w-full flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:bg-gray-300 disabled:cursor-not-allowed"
>
<Package className="h-4 w-4 mr-2" />
Export Cobblemon Datapack (.zip)
</button>
<button
onClick={exportAsJSON}
disabled={npcConfigs.length === 0}
className="w-full flex items-center justify-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed"
>
<Download className="h-4 w-4 mr-2" />
Export JSON Configuration
</button>
<p className="text-xs text-gray-500">
{npcConfigs.length} configuration(s) prête(s) à l'export
</p>
</div> </div>
</div> </div>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
<h4 className="font-medium text-yellow-800 text-sm">Quick Start</h4>
<p className="mt-1 text-xs text-yellow-700">
Download the example files to see a complete working NPC configuration.
You can then import and modify them to create your own NPCs.
</p>
</div>
</div>
</div>
{/* Current Configuration Summary */}
<div className="border-t pt-6">
<h3 className="text-lg font-medium text-gray-900 mb-3">Current Configuration Summary</h3>
<div className="bg-gray-50 rounded-lg p-4">
<dl className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
<div>
<dt className="font-medium text-gray-900">NPC Name</dt>
<dd className="text-gray-700">{npcConfig.names[0] || 'Unnamed NPC'}</dd>
</div>
<div>
<dt className="font-medium text-gray-900">Resource ID</dt>
<dd className="text-gray-700 font-mono text-xs">{npcConfig.resourceIdentifier || 'Not set'}</dd>
</div>
<div>
<dt className="font-medium text-gray-900">Interaction</dt>
<dd className="text-gray-700 capitalize">{npcConfig.interaction.type}</dd>
</div>
<div>
<dt className="font-medium text-gray-900">Can Battle</dt>
<dd className="text-gray-700">{npcConfig.battleConfiguration?.canChallenge ? 'Yes' : 'No'}</dd>
</div>
<div>
<dt className="font-medium text-gray-900">Config Variables</dt>
<dd className="text-gray-700">{npcConfig.config.length}</dd>
</div>
<div>
<dt className="font-medium text-gray-900">Has Dialogue</dt>
<dd className="text-gray-700">{dialogueConfig ? 'Yes' : 'No'}</dd>
</div>
</dl>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -69,7 +69,7 @@ export function JSONPreview({ npcConfig, dialogueConfig }: JSONPreviewProps) {
}; };
const generateFilenames = () => { const generateFilenames = () => {
const baseName = npcConfig.resourceIdentifier const baseName = (npcConfig.resourceIdentifier || 'cobblemon:npc')
.split(':')[1] || 'npc'; .split(':')[1] || 'npc';
return { return {

View File

@@ -6,6 +6,8 @@ interface NPCInteractionEditorProps {
} }
export function NPCInteractionEditor({ config, onChange }: NPCInteractionEditorProps) { export function NPCInteractionEditor({ config, onChange }: NPCInteractionEditorProps) {
const currentInteraction = config.interaction || { type: 'none' };
const handleInteractionChange = (interaction: NPCInteraction) => { const handleInteractionChange = (interaction: NPCInteraction) => {
onChange({ ...config, interaction }); onChange({ ...config, interaction });
}; };
@@ -39,7 +41,7 @@ export function NPCInteractionEditor({ config, onChange }: NPCInteractionEditorP
<input <input
type="radio" type="radio"
value={type} value={type}
checked={config.interaction.type === type} checked={currentInteraction.type === type}
onChange={(e) => handleTypeChange(e.target.value as NPCInteraction['type'])} onChange={(e) => handleTypeChange(e.target.value as NPCInteraction['type'])}
className="form-radio" className="form-radio"
/> />
@@ -54,59 +56,48 @@ export function NPCInteractionEditor({ config, onChange }: NPCInteractionEditorP
</div> </div>
</div> </div>
{config.interaction.type === 'dialogue' && ( {currentInteraction.type === 'dialogue' && (
<div> <div>
<label className="block text-sm font-medium text-gray-700">Dialogue Resource Location</label> <label className="block text-sm font-medium text-gray-700">Dialogue Reference</label>
<input <input
type="text" type="text"
value={config.interaction.dialogue} value={currentInteraction.dialogue || ''}
onChange={(e) => handleInteractionChange({ type: 'dialogue', dialogue: e.target.value })} onChange={(e) => handleInteractionChange({ type: 'dialogue', dialogue: e.target.value })}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
placeholder="cobblemon:my_dialogue" placeholder="dialogue_id"
/> />
<p className="text-xs text-gray-500 mt-1">
Reference to a dialogue file (e.g., "cobblemon:my_dialogue" refers to data/cobblemon/dialogues/my_dialogue.json)
</p>
</div> </div>
)} )}
{config.interaction.type === 'script' && ( {currentInteraction.type === 'script' && (
<div> <div>
<label className="block text-sm font-medium text-gray-700">Script Resource Location</label> <label className="block text-sm font-medium text-gray-700">Script Path</label>
<input <input
type="text" type="text"
value={config.interaction.script} value={currentInteraction.script || ''}
onChange={(e) => handleInteractionChange({ type: 'script', script: e.target.value })} onChange={(e) => handleInteractionChange({ type: 'script', script: e.target.value })}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
placeholder="cobblemon:my_script" placeholder="path/to/script.js"
/> />
<p className="text-xs text-gray-500 mt-1">
Reference to a MoLang script file (e.g., "cobblemon:my_script" refers to data/cobblemon/molang/my_script.molang)
</p>
</div> </div>
)} )}
{config.interaction.type === 'custom_script' && ( {currentInteraction.type === 'custom_script' && (
<div> <div>
<label className="block text-sm font-medium text-gray-700">Custom MoLang Script</label> <label className="block text-sm font-medium text-gray-700">Custom Script</label>
<textarea <textarea
value={config.interaction.script} value={currentInteraction.script || ''}
onChange={(e) => handleInteractionChange({ type: 'custom_script', script: e.target.value })} onChange={(e) => handleInteractionChange({ type: 'custom_script', script: e.target.value })}
rows={4} rows={6}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
placeholder="q.player.send_message('Hello from custom script!');" placeholder="// Your custom script here..."
/> />
<p className="text-xs text-gray-500 mt-1">
Direct MoLang script code to execute when player interacts with NPC
</p>
</div> </div>
)} )}
{config.interaction.type === 'none' && ( {currentInteraction.type === 'none' && (
<div className="bg-gray-50 p-4 rounded-md"> <div className="text-gray-500 italic">
<p className="text-sm text-gray-600"> This NPC will not have any special interaction behavior.
This NPC will not respond to player interactions. Useful for decorative NPCs.
</p>
</div> </div>
)} )}
</div> </div>

View File

@@ -14,7 +14,11 @@ export interface MoLangConfigVariable {
} }
export interface NPCBattleConfiguration { export interface NPCBattleConfiguration {
canChallenge: boolean; canBattle?: boolean;
canChallenge?: boolean;
battleTheme?: string;
victoryTheme?: string;
defeatTheme?: string;
simultaneousBattles?: boolean; simultaneousBattles?: boolean;
healAfterwards?: boolean; healAfterwards?: boolean;
} }
@@ -49,51 +53,10 @@ export interface ScriptPartyProvider {
isStatic?: boolean; isStatic?: boolean;
} }
export type NPCPartyProvider = SimplePartyProvider | PoolPartyProvider | ScriptPartyProvider; export type PartyProvider = SimplePartyProvider | PoolPartyProvider | ScriptPartyProvider;
export interface DialogueInteraction { // Alias pour compatibilité avec les autres fichiers
type: "dialogue"; export type NPCPartyProvider = PartyProvider;
dialogue: string;
}
export interface ScriptInteraction {
type: "script";
script: string;
}
export interface CustomScriptInteraction {
type: "custom_script";
script: string;
}
export interface NoInteraction {
type: "none";
}
export type NPCInteraction = DialogueInteraction | ScriptInteraction | CustomScriptInteraction | NoInteraction;
export interface NPCConfiguration {
hitbox: NPCHitboxValue;
presets: string[];
resourceIdentifier: string;
config: MoLangConfigVariable[];
isInvulnerable?: boolean;
canDespawn?: boolean;
isMovable?: boolean;
isLeashable?: boolean;
allowProjectileHits?: boolean;
hideNameTag?: boolean;
names: string[];
aspects?: string[];
modelScale?: number;
interaction: NPCInteraction;
battleConfiguration?: NPCBattleConfiguration;
autoHealParty?: boolean;
randomizePartyOrder?: boolean;
skill?: number;
battleTheme?: string;
party?: NPCPartyProvider;
}
// Dialogue System Types // Dialogue System Types
export interface DialogueText { export interface DialogueText {
@@ -105,10 +68,17 @@ export interface DialogueText {
export interface DialogueOption { export interface DialogueOption {
text: DialogueText | string; text: DialogueText | string;
value: string; value: string;
action: string | string[]; action?: string | string[];
isSelectable?: string; isSelectable?: string;
} }
export interface DialogueEntry {
id: string;
text: DialogueText | string;
options?: DialogueOption[];
nextDialogue?: string;
}
export interface DialogueOptionInput { export interface DialogueOptionInput {
type: "option"; type: "option";
vertical?: boolean; vertical?: boolean;
@@ -129,7 +99,7 @@ export interface DialogueAutoContinueInput {
} }
export interface DialogueNoInput { export interface DialogueNoInput {
// No additional properties needed type: "none";
} }
export type DialogueInput = DialogueOptionInput | DialogueTextInput | DialogueAutoContinueInput | DialogueNoInput; export type DialogueInput = DialogueOptionInput | DialogueTextInput | DialogueAutoContinueInput | DialogueNoInput;
@@ -154,4 +124,46 @@ export interface DialogueConfiguration {
speakers: Record<string, DialogueSpeaker>; speakers: Record<string, DialogueSpeaker>;
pages: DialoguePage[]; pages: DialoguePage[];
background?: string; background?: string;
} }
export interface NPCInteraction {
type: string;
data?: any;
dialogue?: string;
script?: string;
}
export interface NPCConfiguration {
id: string;
name: string;
names: string[];
displayName?: string;
resourceIdentifier?: string;
model?: string;
modelScale?: number;
texture?: string;
aspects?: string[];
hitbox?: NPCHitboxValue;
battleConfiguration?: NPCBattleConfiguration;
party?: PartyProvider;
config?: MoLangConfigVariable[];
configVariables?: Record<string, any>;
dialogue?: DialogueEntry[];
canInteract?: boolean;
interactionDistance?: number;
interaction?: NPCInteraction;
interactions?: NPCInteraction[];
skill?: number;
battleTheme?: string;
autoHealParty?: boolean;
randomizePartyOrder?: boolean;
isInvulnerable?: boolean;
canDespawn?: boolean;
isMovable?: boolean;
isLeashable?: boolean;
allowProjectileHits?: boolean;
hideNameTag?: boolean;
}
// Alias pour l'interface NPCConfig pour la compatibilité avec ImportExport
export type NPCConfig = NPCConfiguration;

View File

@@ -107,7 +107,8 @@ export const validateNPCConfiguration = (config: NPCConfiguration): ValidationEr
} }
// Interaction validation // Interaction validation
if (config.interaction.type === 'dialogue' && !config.interaction.dialogue) { const interaction = config.interaction || { type: 'none' };
if (interaction.type === 'dialogue' && !interaction.dialogue) {
errors.push({ errors.push({
field: 'interaction.dialogue', field: 'interaction.dialogue',
message: 'Dialogue interaction must specify a dialogue resource location', message: 'Dialogue interaction must specify a dialogue resource location',
@@ -115,7 +116,7 @@ export const validateNPCConfiguration = (config: NPCConfiguration): ValidationEr
}); });
} }
if (config.interaction.type === 'script' && !config.interaction.script) { if (interaction.type === 'script' && !interaction.script) {
errors.push({ errors.push({
field: 'interaction.script', field: 'interaction.script',
message: 'Script interaction must specify a script resource location', message: 'Script interaction must specify a script resource location',
@@ -123,7 +124,7 @@ export const validateNPCConfiguration = (config: NPCConfiguration): ValidationEr
}); });
} }
if (config.interaction.type === 'custom_script' && !config.interaction.script) { if (interaction.type === 'custom_script' && !interaction.script) {
errors.push({ errors.push({
field: 'interaction.script', field: 'interaction.script',
message: 'Custom script interaction must provide script code', message: 'Custom script interaction must provide script code',
@@ -132,7 +133,7 @@ export const validateNPCConfiguration = (config: NPCConfiguration): ValidationEr
} }
// Configuration variables validation // Configuration variables validation
config.config.forEach((variable, index) => { (config.config || []).forEach((variable, index) => {
if (!variable.variableName) { if (!variable.variableName) {
errors.push({ errors.push({
field: `config.${index}.variableName`, field: `config.${index}.variableName`,