39 lines
9.4 KiB
JavaScript
39 lines
9.4 KiB
JavaScript
import {itemTemplateCatalogue} from '../item-metadata-policy.mjs';
|
||
import {defaultItemDesign,itemDesignTemplate,validateItemDesign} from '../item-design-model.mjs';
|
||
import {TRIM_PATTERNS,TRIM_MATERIALS} from '../kit-design-model.mjs';
|
||
import {itemRoman,itemWords} from '../item-lore-model.mjs';
|
||
import {itemLoreCard} from '../item-lore-view.mjs';
|
||
|
||
const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;};
|
||
const button=(label,handler)=>{const node=el('button',label);node.type='button';node.onclick=handler;return node;};
|
||
function field(label,input){const wrap=el('label');wrap.append(el('span',label),input);return wrap;}
|
||
function select(values){const node=el('select');for(const [value,label]of values){const option=el('option',label);option.value=value;node.append(option);}return node;}
|
||
export function mountItemDesigner(host,{fetcher=fetch,initialDesign=null,onApply=null}={}){
|
||
if(!document.querySelector('link[data-item-designer]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-item-designer.css',import.meta.url).href;css.dataset.itemDesigner='';document.head.append(css);}
|
||
const embedded=typeof onApply==='function';
|
||
let active=true,ready=embedded,pending=false,published=false,id=crypto.randomUUID(),revision=0,lastSaved='',definitions=[],loreRows=[],enchantmentInputs=new Map();const controller=new AbortController();
|
||
const root=el('section',undefined,'item-designer'),status=el('p','Opening the item definition register…');status.setAttribute('role','status');
|
||
const saved=select([['','Choose a saved draft']]),load=button('Load draft',()=>{const row=definitions.find(row=>row.id===saved.value);if(row){id=row.id;revision=row.revision;published=row.state==='published';lastSaved=JSON.stringify(validateItemDesign(row.design));setDesign(row.design);status.textContent=published?'Published revision '+revision+' is sealed. Withdraw it before editing.':'Draft revision '+revision+' loaded.';}}),fresh=button('New item',()=>{id=crypto.randomUUID();revision=0;published=false;lastSaved="";setDesign(defaultItemDesign(template.value));status.textContent='New local draft. Save to record it in J.A.R.V.I.S.';}),refresh=button('Refresh drafts',()=>void readDefinitions());
|
||
const tools=el('div',undefined,'item-designer-tools');tools.append(field('Saved definitions',saved),load,fresh,refresh);
|
||
const form=el('form'),fields=el('fieldset'),layout=el('div',undefined,'item-designer-layout'),preview=el('div',undefined,'item-designer-preview');
|
||
const copyPreview=button('Copy ingame preview command',async()=>{const command='/dm previewitem '+id+' '+revision;try{await navigator.clipboard.writeText(command);status.textContent='Preview command copied. Paste it in Minecraft: '+command;}catch{status.textContent='Paste this command in Minecraft: '+command;}});copyPreview.disabled=true;
|
||
const ids=Object.keys(itemTemplateCatalogue().templates),template=select(ids.map(id=>{const t=itemDesignTemplate(id);return[id,t.name+' · '+itemWords(t.quality)+' · MK '+itemRoman(t.equipmentMark)];}));template.setAttribute('aria-label','Item template');
|
||
const name=el('input');name.maxLength=64;name.required=true;const identity=el('p',undefined,'item-designer-identity'),enchants=el('div',undefined,'item-designer-enchantments'),lore=el('div',undefined,'item-designer-lore');
|
||
const addLore=button('Add lore line',()=>{if(loreRows.length<6){addLine({text:'',color:'#AAAAAA',bold:false,italic:false});paint();}});
|
||
const trimPattern=select([['','No trim'],...TRIM_PATTERNS.map(v=>[v,itemWords(v)])]),trimMaterial=select(TRIM_MATERIALS.map(v=>[v,itemWords(v)])),trim=el('div',undefined,'item-designer-trim');trimPattern.setAttribute('aria-label','Armour trim');trimMaterial.setAttribute('aria-label','Trim material');trim.append(field('Armour trim',trimPattern),field('Trim material',trimMaterial));
|
||
fields.append(el('legend','Item design'),field('Progression template',template),identity,field('Item name',name),el('h4','Enchantments'),enchants,trim,el('h4','Lore'),lore,addLore);
|
||
const validation=el('p',undefined,'item-designer-validation');validation.setAttribute('role','alert');const save=el('button','Save draft');save.type='submit';if(embedded){save.textContent='Add to kitset';tools.hidden=true;copyPreview.hidden=true;}const note=el('p','A saved draft does not issue an item or publish it to the Exchange.','item-designer-note');if(embedded)note.textContent='Changes are kept in your kitset. Save the set before generating its key.';form.append(fields,validation,save,copyPreview,note);layout.append(form,preview);root.append(status,tools,layout);host.replaceChildren(root);
|
||
function addLine(line){const row=el('div',undefined,'item-designer-lore-line'),text=el('input'),color=el('input'),bold=el('input'),italic=el('input');text.value=line.text;text.maxLength=120;color.type='color';color.value=line.color;bold.type=italic.type='checkbox';bold.checked=line.bold;italic.checked=line.italic;
|
||
const entry={row,text,color,bold,italic};row.append(field('Lore text',text),field('Colour',color),field('Bold',bold),field('Italic',italic),button('Remove',()=>{loreRows=loreRows.filter(value=>value!==entry);row.remove();paint();}));for(const input of [text,color,bold,italic])input.oninput=paint;loreRows.push(entry);lore.append(row);
|
||
}
|
||
function readDesign(){const base=defaultItemDesign(template.value);return validateItemDesign({...base,name:name.value,lore:loreRows.map(row=>({text:row.text.value,color:row.color.value,bold:row.bold.checked,italic:row.italic.checked})),enchantments:Object.fromEntries([...enchantmentInputs].map(([key,input])=>[key,Number(input.value)])),trim:trim.hidden||!trimPattern.value?null:{pattern:trimPattern.value,material:trimMaterial.value}});}
|
||
function paint(){if(!active)return;let valid=true;try{const design=readDesign(),t=itemDesignTemplate(design.templateId);validation.textContent='';preview.replaceChildren(el('h4','Lore card preview'),itemLoreCard({...design,title:design.name,material:t.material,image:t.image,season:'S1'}));copyPreview.disabled=!ready||pending||revision<1||JSON.stringify(design)!==lastSaved;}catch(error){valid=false;copyPreview.disabled=true;validation.textContent=error.message;}save.disabled=!ready||pending||published||!valid;addLore.disabled=loreRows.length>=6;fields.disabled=!ready||pending||published;load.disabled=fresh.disabled=refresh.disabled=pending||!ready;}
|
||
function setDesign(design){template.value=design.templateId;name.value=design.name;const t=itemDesignTemplate(design.templateId);identity.textContent=itemWords(t.quality)+' · MK '+itemRoman(t.equipmentMark)+' · '+itemWords(t.itemClass);enchantmentInputs=new Map();enchants.replaceChildren();
|
||
for(const [key,bounds]of Object.entries(t.enchantments)){const input=el('input');input.type='number';input.min=bounds.min;input.max=bounds.max;input.step=1;input.value=design.enchantments[key];input.oninput=paint;enchantmentInputs.set(key,input);enchants.append(field(itemWords(key)+' · '+bounds.min+'–'+bounds.max,input));}if(!enchantmentInputs.size)enchants.append(el('p','This template has no editable enchantments.'));
|
||
trim.hidden=!t.armor;trimPattern.value=design.trim?.pattern||'';trimMaterial.value=design.trim?.material||'gold';loreRows=[];lore.replaceChildren();for(const line of design.lore)addLine(line);paint();
|
||
}
|
||
template.onchange=()=>setDesign(defaultItemDesign(template.value));name.oninput=trimPattern.onchange=trimMaterial.onchange=paint;
|
||
async function readDefinitions(){refresh.disabled=true;try{const response=await fetcher('/api/items/designs',{credentials:'same-origin',cache:'no-store',signal:controller.signal}),data=await response.json();if(!response.ok)throw Error(data.message||'Item definitions unavailable.');if(!Array.isArray(data.definitions))throw Error('Invalid item definition register.');if(!active)return;definitions=data.definitions;saved.replaceChildren(el('option','Choose a saved draft'));saved.firstChild.value='';for(const row of definitions){const option=el('option',row.design.name+' · revision '+row.revision);option.value=row.id;saved.append(option);}ready=true;status.textContent=definitions.length+' saved definitions. Quality and MK follow the selected progression template.';}catch(error){if(active&&!controller.signal.aborted){ready=false;status.textContent=error.message;}}finally{paint();}}
|
||
form.onsubmit=async event=>{event.preventDefault();if(pending||!ready||published)return;let design;try{design=readDesign();}catch(error){validation.textContent=error.message;return;}if(embedded){try{await onApply(design);}catch(error){validation.textContent=error.message;}return;}pending=true;paint();try{const response=await fetcher('/api/items/designs',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({action:'save',id,revision,design}),signal:controller.signal}),data=await response.json();if(!response.ok)throw Error(data.message||'Item definition was not saved.');if(!active)return;id=data.id;revision=data.revision;lastSaved=JSON.stringify(validateItemDesign(data.design));await readDefinitions();status.textContent='Draft revision '+revision+' saved. J.A.R.V.I.S. reference: '+data.keyId;}catch(error){if(active&&!controller.signal.aborted)status.textContent=error.message;}finally{pending=false;paint();}};
|
||
setDesign(initialDesign?validateItemDesign(initialDesign):defaultItemDesign('dr_s1_spice_shovel_mk1'));if(embedded)status.hidden=true;else void readDefinitions();return()=>{active=false;controller.abort();root.remove();};
|
||
}
|

Staff