Files
2026-12-02 21:10:42 -05:00

60 lines
7.2 KiB
JavaScript

import {ID,PACKS,ENABLE,DISABLE,preflight,applyPlan,artPaths,lookup,routeNew} from './core.mjs';
import {openVault} from './vault.mjs';
let busy=false;
const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function apis(){
const a={Folder:CONFIG.Folder.documentClass,Compendium:foundry.documents.collections.CompendiumCollection,Picker:foundry.applications.apps.FilePicker};
if(!a.Folder?.create || !a.Compendium?.createCompendium || !a.Picker?.browse || !a.Picker?.createDirectory)throw Error('Required Foundry APIs unavailable.');
return a;
}
async function run(campaign){
if(busy)return;
busy=true;const log=[];
try {
const api=apis();checkSandbox();const scriptPolicy=game.settings.get(ID,'scriptPolicy');const plan=preflight(game,CONST,{campaign,scriptPolicy});
const paths=artPaths(game.world.id,plan.names);
const listed=await api.Picker.browse('data',`worlds/${game.world.id}`);
if(!Array.isArray(listed?.dirs))throw Error('World art directory not readable.');
const list=(items)=>`<ul>${items.map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`;
const html=`<p><strong>World:</strong> ${esc(game.world.id)}. Back up first; have other users log out. This changes only the listed actors, folders, new world packs and selected player permissions.</p><details open><summary>Character moves and ownership (${plan.actors.length} actors)</summary>${list(plan.actors.map(a=>`${a.actor.name}: ${a.actor.folder?.name??'(root)'} → ${a.path.join('/')} | owner ${a.name}; Jason retains owner; other player access removed`))}</details><details><summary>Folders (${plan.folders.length})</summary>${list(plan.folders.map(f=>`${lookup(game,f.type,f.path)?'Reuse':'Create'} ${f.type}/${f.path.join('/')}`))}</details><details><summary>Homebrew packs (4)</summary>${list(PACKS.map(p=>`${p[0]}: ${p[3]?'both player roles can edit':'players read only'}`))}</details><details><summary>Artwork directories (${paths.length})</summary>${list(paths)}</details><details><summary>Permissions</summary>${list([...ENABLE.map(k=>`Enable ${k}`),...DISABLE.map(k=>`Disable ${k}`)])}</details><p>Token creation/deletion applies on accessible scenes. Shared packs are collaboratively editable. A blank shared testing scene will be created if not already provisioned. Script macro policy: ${esc(scriptPolicy)}. Art folders are not private. Setup can stop partway on an API error; restore backup for full rollback.</p>`;
if(!await foundry.applications.api.DialogV2.confirm({window:{title:'Player Workshop — review changes'},position:{width:640},content:html,rejectClose:false,modal:true}))return;
const fresh=preflight(game,CONST,{campaign,scriptPolicy});
if(JSON.stringify(fresh.actors.map(a=>a.actor.id))!==JSON.stringify(plan.actors.map(a=>a.actor.id)))throw Error('Actor identities changed during preview. Reopen setup.');
checkSandbox();
await applyPlan(game,CONST,api,fresh,log);
await ensureSandbox(log);
await game.settings.set(ID,'routing',true);
console.info(`${ID}: setup complete`,log);
await foundry.applications.api.DialogV2.prompt({window:{title:'Player Workshop — complete'},content:`<p>Setup completed. ${log.length} changes recorded. Automatic filing enabled for newly created root-level personal characters and items. Refresh all clients and test as a player.</p><details><summary>Change log</summary>${list(log)}</details>`,ok:{label:'Close'},rejectClose:false});
}catch(error){console.error(`${ID}: setup stopped`,log,error);ui.notifications.error(`Player Workshop stopped: ${error.message}. ${log.length} completed steps; check console. No automatic rollback.`);}
finally{busy=false;}
}
Hooks.once('init',()=>{
if(game.release.generation!==14 || game.system.id!=='dnd5e')return;
game.settings.register(ID,'routing',{name:'Automatically file new personal characters and homebrew',hint:'Routes root-level new world characters and items for provisioned players. Existing documents and explicit folder selections are not moved.',scope:'world',config:true,type:Boolean,default:false,restricted:true});
game.settings.register(ID,'scriptPolicy',{name:'Player script macro policy',hint:'Applied only when setup runs. Preserve existing settings by default; enable or disable explicitly after checking your automation.',scope:'world',config:true,type:String,choices:{preserve:'Preserve current permissions',enable:'Enable for players',disable:'Disable for players'},default:'preserve',restricted:true});
class WorkshopMenu extends foundry.applications.api.DialogV2 {
constructor(options={}){super({...options,window:{title:'Player Workshop'},content:'<p>Prepare your existing campaign for player-owned characters, homebrew and artwork. Review every proposed change before applying.</p><p>Sign in as Gamemaster. Back up your world first.</p>',buttons:[{action:'review',label:'Provision this world (no actor moves)',default:true,callback:()=>{void run(false);}},{action:'campaign',label:'Organize named Phandelver characters',callback:()=>{void run(true);}},{action:'cancel',label:'Cancel'}]});}
}
game.settings.registerMenu(ID,'setup',{name:'Player Workshop setup',label:'Open setup',hint:'Preview and apply the named campaign setup. No changes are applied on module activation.',icon:'fas fa-folder-tree',type:WorkshopMenu,restricted:true});
class VaultMenu extends foundry.applications.api.DialogV2 {constructor(options={}){super({...options,window:{title:'Player Vault'},content:'<p>Manage and export your owned content.</p>',buttons:[{action:'open',label:'Open my vault',default:true,callback:()=>{void openVault();}},{action:'cancel',label:'Cancel'}]});}}
game.settings.registerMenu(ID,'vault',{name:'Player Vault',label:'Open Player Vault',hint:'Characters, homebrew, artwork and portable exports',icon:'fas fa-box-archive',type:VaultMenu,restricted:false});
for(const type of ['Actor','Item'])Hooks.on(`preCreate${type}`,(doc,data,options,userId)=>{try{routeNew(game,doc,data,options,userId);}catch(e){console.warn(`${ID}: automatic filing skipped`,e);}});
});
function checkSandbox(){
const matches=[...game.scenes].filter(s=>s.name==='Player Workshop — Testing Grounds');
if(matches.length>1)throw Error('Ambiguous testing scene name.');
if(matches.length&&!matches[0].getFlag(ID,'sandbox'))throw Error('Existing testing scene name collision; rename it before setup.');return matches[0];
}
async function ensureSandbox(log){
if(checkSandbox())return;
const scene=await CONFIG.Scene.documentClass.create({name:'Player Workshop — Testing Grounds',navigation:true,active:false,ownership:{default:2},width:2400,height:1600,padding:0.1,backgroundColor:'#30363d',tokenVision:false,grid:{type:1,size:100,distance:5,units:'ft'},flags:{[ID]:{sandbox:true}}});
if(!scene||scene.active)throw Error('Testing scene creation failed or activated unexpectedly.');log.push('Created testing scene');
}
Hooks.on('renderActorDirectory',(_app,html)=>{
const root=html instanceof HTMLElement?html:html?.[0];if(game.release.generation!==14||game.system.id!=='dnd5e'||!root||root.querySelector('[data-player-workshop-vault]'))return;
const header=root.querySelector('.directory-header')??root.querySelector('header');if(!header)return;
const b=document.createElement('button');b.type='button';b.dataset.playerWorkshopVault='1';b.textContent='Player Vault';b.addEventListener('click',()=>void openVault());header.append(b);
});