web/website/control-panel/public/kit-generator.mjs

23 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createKitEquipmentEditor} from './kit-equipment-editor.mjs';
import {validateKitEquipment} from './kit-design-model.mjs';
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
if(typeof document!=='undefined'&&!document.querySelector('link[href="/kit-generator.css"]')){const css=el('link');css.rel='stylesheet';css.href='/kit-generator.css';document.head.append(css);}
const profiles={common:['No enchantments · standard vanilla armour'],uncommon:['All armour · Protection I · Unbreaking I','Boots · Feather Falling I'],rare:['All armour · Protection II · Unbreaking II','Helmet · Respiration I · Aqua Affinity I','Boots · Feather Falling II · Depth Strider I'],very_rare:['All armour · Protection III · Unbreaking III · Mending I','Helmet · Respiration II · Aqua Affinity I','Leggings · Swift Sneak II','Boots · Feather Falling III · Depth Strider II'],legendary:['All armour · Protection IV · Unbreaking III · Mending I · Thorns III','Helmet · Respiration III · Aqua Affinity I','Leggings · Swift Sneak III','Boots · Feather Falling IV · Depth Strider III · Soul Speed III']};
export function createEnchantmentProfile(quality,kind='personal_sale'){const key=quality.toLowerCase().replaceAll(' ','_');const box=el('aside');box.className='kit-enchantment-profile';box.setAttribute('aria-label','Quality enchantment profile');box.append(el('h4','Enchantment profile'),el('p','Fixed by kit quality. Players cannot edit enchantments.'));const list=el('ul');for(const line of (kind==='faction_sale'?['Vanilla faction armour · no added enchantments']:profiles[key]||[]))list.append(el('li',line));box.append(list,el('small','Applied to your delivered kit.'));return box;}
export function createKitGenerator({initial={},kind='personal_sale',onUpgrade=null,context='Personal kit',quality='Uncommon',art='clan-atelier-v1.webp',maxNameLength=64,maxLoreLines=4,maxLoreLineLength=80,submitLabel='Save design',successMessage='Design saved.',onSave=async()=>{}}={}){
const root=el('div');root.className='kit-generator';const form=el('form'),preview=el('aside');form.className='kit-generator-form';preview.className='kit-generator-preview kit-collectible-card';preview.dataset.quality=quality.toLowerCase().replaceAll(' ','_');preview.setAttribute('aria-label','Live kit design preview');form.append(el('p',context.toUpperCase()),el('h3','Forge your kit'),el('p','Design netherite armour, choose your trims and add your own heraldry and item lore.'));
function field(title,type,value){const label=el('label',title),input=el(type==='textarea'?'textarea':'input');if(type!=='textarea')input.type=type;input.value=value;label.append(input);form.append(label);return input;}
const name=field('1 · Kit name','text',initial.name||'');name.required=true;name.minLength=3;name.maxLength=maxNameLength;name.placeholder='Give your stillsuit a name';const color=field('2 · Kit accent colour','color',initial.color||'#385B49');
const hex=field('Colour code · hex','text',color.value.toUpperCase());hex.maxLength=7;hex.pattern='#[A-Fa-f0-9]{6}';hex.spellcheck=false;hex.placeholder='#803C3F';hex.addEventListener('input',()=>{if(/^#[A-Fa-f0-9]{6}$/.test(hex.value)){color.value=hex.value;update(false);}});
const presets=el('div');presets.className='kit-colour-presets';for(const[label,value]of [['Emerald','#385B49'],['Imperial purple','#654478'],['Desert sand','#B09156'],['Crimson','#803C3F'],['Deep blue','#365C79']]){const b=el('button',label);b.type='button';b.style.setProperty('--swatch',value);b.onclick=()=>{color.value=value;update();};presets.append(b);}form.append(presets);
const lore=field('3 · Kit story · catalogue description','textarea',(initial.lore||[]).join('\n'));lore.rows=5;lore.maxLength=maxLoreLines*(maxLoreLineLength+1);lore.placeholder='A story carried across the desert…';const hint=el('small',`Up to ${maxLoreLines} lines, ${maxLoreLineLength} characters per line.`);const counter=el('output');counter.className='kit-lore-counter';form.append(hint,counter);
const namedPieces=['rare','very_rare','legendary'].includes(quality.toLowerCase().replaceAll(' ','_')),itemNames={};
if(namedPieces){const group=el('fieldset');group.className='kit-piece-names';group.append(el('legend','Individual armour names'),el('p','Optional names for Rare, Very Rare and Legendary kits. Leave blank to use the kit name.'));for(const[key,label]of [['helmet','Helmet'],['chestplate','Chestplate'],['leggings','Leggings'],['boots','Boots']]){const wrap=el('label',label),input=el('input');input.type='text';input.maxLength=64;input.value=initial.itemNames?.[key]||'';input.placeholder=label+' name';wrap.append(input);group.append(wrap);itemNames[key]=input;}form.append(group);}
const status=el('p');status.role='status';status.className='kit-generator-status';const save=el('button',submitLabel);save.type='submit';save.dataset.duneAction='eco';form.append(el('p','Your design sets the armour trims, names, lore and banner. Quality attributes and eligibility still apply.'),status,save);
const equipmentEditor=createKitEquipmentEditor(initial,{onChange:()=>update(),kitName:()=>name.value.trim()||'Stillsuit'});form.insertBefore(equipmentEditor.element,status);
const image=el('img');image.src='https://www.dunerealms.com/assets/'+art;image.alt='Illustrated stillsuit atelier';image.className='kit-generator-art';const heading=el('h3'),badge=el('span',quality+' · Netherite armour & heraldry'),figure=el('div');figure.className='kit-design-mannequin';figure.setAttribute('aria-label','Stillsuit colour preview');for(const part of ['head','hood','body','left-arm','right-arm','belt','left-leg','right-leg','left-boot','right-boot']){const piece=el('span');piece.className='kit-piece-'+part;figure.append(piece);}const lines=el('div');lines.className='kit-preview-lore';const state=el('p');state.className='kit-preview-state';const crest=el('div','DUNEREALMS · IMPERIAL ATELIER');crest.className='kit-card-imprint';const artPanel=el('div');artPanel.className='kit-card-art-panel';const enchants=el('section');enchants.className='kit-card-enchants';enchants.setAttribute('aria-label','Fixed quality enchantments');enchants.append(el('h4','✦ '+quality+' enchantments'));for(const line of (kind==='faction_sale'?['Vanilla faction armour · no added enchantments']:profiles[preview.dataset.quality]||[]))enchants.append(el('p',line));if(kind==='personal_sale'&&preview.dataset.quality==='legendary'){enchants.append(el('h4','Upgrade bonus'));for(const b of initial.upgrade?.bonuses||[])enchants.append(el('p',b.piece+' · '+b.enchantment.replaceAll('_',' ')+' +'+b.levels));if(!initial.upgrade)enchants.append(el('p','No Upgrade Token applied'));}enchants.append(el('small','Fixed quality profile · included with the kit'));artPanel.append(image,enchants);preview.append(crest,badge,heading,artPanel,equipmentEditor.preview,equipmentEditor.tooltip,lines,state,el('small','DESIGN PREVIEW · FOUR-PIECE ARMOUR'));
function value(){return{equipment:equipmentEditor.value(),name:name.value.trim(),color:color.value.toUpperCase(),lore:lore.value.trim()?lore.value.split('\n').map(s=>s.trim()).filter(Boolean):[],...(namedPieces?{itemNames:Object.fromEntries(Object.entries(equipmentEditor.value().armor).map(([k,v])=>[k,v.name.trim()]))}:{})};}let original=JSON.stringify(value());const baseline=structuredClone(value());const reset=el('button','Restore saved design');reset.type='button';reset.className='kit-reset-design';reset.onclick=()=>{if(form.dataset.dirty==='true'&&!window.confirm('Discard your unsaved design changes?'))return;name.value=baseline.name;color.value=baseline.color;lore.value=baseline.lore.join('\n');equipmentEditor.reset(baseline.equipment);for(const[key,input]of Object.entries(itemNames))input.value=baseline.itemNames?.[key]||'';status.textContent='Saved design restored in the preview.';update();};form.insertBefore(reset,status);
function update(syncHex=true){equipmentEditor.refresh();const v=value();if(syncHex)hex.value=v.color;heading.textContent=v.name||'Your stillsuit';figure.style.setProperty('--kit-colour',v.color);lines.replaceChildren(...v.lore.map(s=>el('p',s)));if(namedPieces){const names=el('dl');names.className='kit-piece-name-preview';for(const[key,label]of [['helmet','Helmet'],['chestplate','Chestplate'],['leggings','Leggings'],['boots','Boots']])names.append(el('dt',label),el('dd',v.itemNames[key]||(v.name||'Your stillsuit')+' '+label.toLowerCase()));lines.append(names);}const dirty=JSON.stringify(v)!==original;form.dataset.dirty=String(dirty);reset.disabled=!dirty;counter.textContent=v.lore.length+' / '+maxLoreLines+' lore lines · longest '+Math.max(0,...v.lore.map(s=>s.length))+' / '+maxLoreLineLength+' characters';state.textContent=dirty?'Unsaved preview':Number(initial.version)>0?'Current saved design':'New design preview · not saved';state.dataset.dirty=String(dirty);const invalid=v.lore.length>maxLoreLines||v.lore.some(s=>s.length>maxLoreLineLength);lore.setCustomValidity(invalid?`Use up to ${maxLoreLines} lines of ${maxLoreLineLength} characters.`:'');}
let saving=false;for(const input of [name,color,lore,...Object.values(itemNames)])input.addEventListener('input',()=>update());form.onsubmit=async e=>{e.preventDefault();if(saving)return;update(false);if(!form.reportValidity())return;try{validateKitEquipment(value().equipment);}catch(error){status.textContent=error.message;return;}saving=true;const submitted=structuredClone(value()),controls=[...form.querySelectorAll('input,select,textarea,button')],disabled=controls.map(c=>c.disabled);for(const control of controls)control.disabled=true;status.textContent='Saving your design…';try{await onSave(submitted);original=JSON.stringify(submitted);Object.assign(baseline,submitted);status.textContent=successMessage;}catch(error){status.textContent=error.message||'The design could not be saved. Your preview is still here.';}finally{saving=false;controls.forEach((c,i)=>c.disabled=disabled[i]);update(false);}};if(kind==='personal_sale'&&preview.dataset.quality==='legendary'){const box=el('fieldset');box.className='kit-upgrade-control';box.append(el('legend','Legendary Upgrade Token'),el('p','5,000 Dunemarks per token. Each code replaces your bonus with 1–3 points spread over random enchantments. Future Player Kit sales only; paid receipts and faction kits stay unchanged.'));const label=el('label','Private Upgrade Token code'),input=el('input');input.placeholder='DRU-…';input.maxLength=52;input.autocomplete='off';input.spellcheck=false;label.append(input);const button=el('button','Use token & reroll bonus');button.type='button';button.disabled=!initial.id||!onUpgrade;const note=el('p');note.role='status';if(!initial.id)note.textContent='Save your Legendary Player Kit first.';button.onclick=async()=>{if(JSON.stringify(value())!==original){note.textContent='Save your design changes before using a token.';return;}const code=input.value.trim().toUpperCase();if(!/^DRU-[A-F0-9]{48}$/.test(code)){note.textContent='Enter your complete private Upgrade Token code.';return;}button.disabled=true;note.textContent='Applying token…';try{await onUpgrade(code);}catch(e){note.textContent=e.message;button.disabled=false;}};const shop=el('a','Buy Upgrade Tokens →');shop.href='#rewards-codes';box.append(label,button,note,shop);form.append(box);}root.append(form,preview);update();return{element:root,value,form,submitButton:save,status,isDirty:()=>form.dataset.dirty==='true'};
}