Add curated DMPaint logo, service and character designs

This commit is contained in:
unimatrixgit 2026-11-21 01:42:39 +01:00
commit 4d89020c0f
9 changed files with 167 additions and 9 deletions

View file

@ -0,0 +1,21 @@
# DMPaint curated designs
Ticket 413 extends the existing standalone SVG-Edit workspace. It does not create a J.A.R.V.I.S. bridge, save user artwork on the server or modify accounts, clans or companies.
The library has five version-one designs:
| Design | Availability | Editable elements |
| --- | --- | --- |
| Desert crest | Clan and company | Shield, dunes, star, name and three colours |
| Caravan mark | Clan and company | Hexagonal mark, caravan motif, name and colours |
| Service seal | Existing staff authority | Existing SPost seal artwork inside an editable ring, name and colours |
| Service award | Existing staff authority | Existing Network Staff award artwork, ribbons, name and colours |
| Desert traveller | All signed-in users | Minecraft-style character, name, colours and hood/headscarf/armour starting outfits |
Existing source artwork remains unchanged. POL seals and artwork are excluded. The service templates embed the existing PNG artwork directly in the SVG, so exported drawings have no remote image dependency. Those embedded insignia remain intact while the surrounding shapes and text can be edited.
Every template list, preview and SVG request rechecks the current session and existing staff permission. Rendering accepts only curated design IDs, six-digit colours, bounded escaped text and known outfits. Templates contain no scripts, remote resources or user-supplied SVG. These rules do not replace the existing editor's handling of files a user opens themselves.
Opening the library or changing its fields does not change the canvas. Loading a design into a changed canvas requires confirmation. Existing SVG and PNG download actions are reused. Download the SVG to retain editable vector shapes; PNG is the raster export. Manual upload to existing organisation settings remains the workflow.
Focused checks cover every design, ordinary/staff/anonymous access, cross-mode rejection, label escaping, colour injection, outfit variants and cancelled/confirmed dirty-canvas replacement through the real template route.

View file

@ -0,0 +1,32 @@
// Five curated, self-contained designs. No political seals or remote resources.
const designs=Object.freeze([
{id:'desert-crest',name:'Desert crest',modes:['clan','company']},
{id:'caravan-mark',name:'Caravan mark',modes:['clan','company']},
{id:'service-seal',name:'Service seal',modes:['seal']},
{id:'service-award',name:'Service award',modes:['award']},
{id:'desert-traveller',name:'Desert traveller',modes:['character']}
]);
export const templateModes=Object.freeze(['clan','company','character','seal','award']);
export const templateCatalogue=mode=>designs.filter(d=>d.modes.includes(mode)).map(({id,name})=>({id,name,version:1}));
const escape=value=>value.replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&apos;'}[c]));
export function renderPaintTemplate({mode,id,title='YOUR NAME',primary='#143E30',secondary='#D7B65D',trim='#F3E5B8',outfit='hood',sealData=null}){
if(!designs.some(d=>d.id===id&&d.modes.includes(mode)))throw TypeError('Choose an available design.');
if(typeof title!=='string'||title.length>40||/[\u0000-\u001f]/.test(title))throw TypeError('Use a name up to 40 characters.');
for(const colour of [primary,secondary,trim])if(typeof colour!=='string'||!/^#[a-f0-9]{6}$/i.test(colour))throw TypeError('Choose valid design colours.');
if(!['hood','armour','headscarf'].includes(outfit))throw TypeError('Choose a character outfit.');
const text=(y,size=27)=>`<text x="256" y="${y}" text-anchor="middle" font-family="Georgia,serif" font-size="${size}" fill="${trim}">${escape(title)}</text>`;
const star=`<path d="M256 116 274 164 325 168 285 201 297 251 256 223 215 251 227 201 187 168 238 164Z" fill="${secondary}" stroke="${trim}" stroke-width="4"/>`;
let art;
if(id==='desert-crest')art=`<path d="M92 58H420V264Q414 373 256 452 98 373 92 264Z" fill="${primary}" stroke="${secondary}" stroke-width="14"/><path d="M115 80H397V263Q389 354 256 425 123 354 115 263Z" fill="none" stroke="${trim}" stroke-width="3"/>${star}<path d="M130 308Q190 248 256 308 322 248 382 308M145 333Q210 290 256 333 302 290 367 333" fill="none" stroke="${secondary}" stroke-width="8"/>${text(379,24)}`;
if(id==='caravan-mark')art=`<path d="M256 44 450 154V358L256 468 62 358V154Z" fill="${primary}" stroke="${secondary}" stroke-width="12"/><path d="M256 72 425 169V343L256 440 87 343V169Z" fill="none" stroke="${trim}" stroke-width="3"/>${star}<path d="M126 280H386L362 337H150Z" fill="${secondary}"/><path d="M174 279 218 229 256 270 294 229 338 279" fill="none" stroke="${trim}" stroke-width="7"/>${text(386,24)}`;
if(id==='service-seal'||id==='service-award'){
if(typeof sealData!=='string'||!/^data:image\/png;base64,[a-zA-Z0-9+/]+=*$/.test(sealData))throw TypeError('Current service artwork is unavailable.');
const ribbons=id==='service-award'?`<path d="M154 300 110 466 185 432 225 477 255 326M258 326 294 477 334 432 406 466 360 300" fill="${primary}" stroke="${secondary}" stroke-width="8"/>`:'';
art=`${ribbons}<circle cx="256" cy="235" r="190" fill="${primary}" stroke="${secondary}" stroke-width="12"/><circle cx="256" cy="235" r="172" fill="none" stroke="${trim}" stroke-width="3"/><image href="${sealData}" x="151" y="102" width="210" height="210"/>${text(348,23)}<path d="M166 371H346" stroke="${secondary}" stroke-width="4"/>`;
}
if(id==='desert-traveller'){
const head=outfit==='hood'?`<path d="M128 240V112L192 48H320L384 112V240H344V135L304 96H208L168 135V240Z" fill="${primary}" stroke="${secondary}" stroke-width="8"/>`:outfit==='headscarf'?`<path d="M144 112V64H368V112H392V256H352V136H160V256H120V112Z" fill="${trim}"/><path d="M136 104H376V128H136Z" fill="${primary}"/>`:`<path d="M160 96V64H352V96H376V160H136V96Z" fill="${secondary}"/>`;
art=`<path d="M104 456V304L168 248H344L408 304V456Z" fill="${primary}" stroke="${secondary}" stroke-width="8"/><path d="M176 304H336V432H176Z" fill="${secondary}"/><path d="M200 320H312V352H200ZM200 376H312V408H200Z" fill="${primary}"/><path d="M176 112H336V224L304 256H208L176 224Z" fill="#C99670"/><path d="M192 160H224V176H192ZM288 160H320V176H288Z" fill="#80CFE6"/><path d="M224 216H288V224H224Z" fill="#81533F"/>${head}<path d="M152 268 200 300H312L360 268" fill="none" stroke="${trim}" stroke-width="12"/>${text(493,22)}`;
}
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" viewBox="0 0 512 512"><title>${escape(title)}</title><g id="editable-design">${art}</g></svg>`;
}

View file

@ -1,6 +1,7 @@
import {readFile} from 'node:fs/promises';
import {identity} from '../node/auth.mjs';
import {can} from '../node/permissions.mjs';
import {templateModes,templateCatalogue,renderPaintTemplate} from './dmpaint-templates.mjs';
const TYPES={html:'text/html',mjs:'text/javascript',js:'text/javascript',css:'text/css',svg:'image/svg+xml',png:'image/png',jpg:'image/jpeg',gif:'image/gif',json:'application/json',txt:'text/plain',woff:'font/woff',woff2:'font/woff2',ttf:'font/ttf'};
export const DMPAINT_CSP="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
@ -13,14 +14,31 @@ export function createDMPaint(db,{authenticate=request=>identity(request,db),aut
const user=await authenticate(request);
if(!user)return Response.json({message:'Sign in to use DMPaint.'},{status:401,headers:{'Cache-Control':'no-store'}});
const staff=await authorise(user,'web.accounts.assign');
if(path==='/api/dmpaint')return Response.json({name:'DMPaint',modes:staff?['clan','company','seal','award']:['clan','company']},{headers:{'Cache-Control':'private, no-store'}});
const modes=templateModes.filter(mode=>staff||!['seal','award'].includes(mode));
if(path==='/api/dmpaint')return Response.json({name:'DMPaint',modes},{headers:{'Cache-Control':'private, no-store'}});
if(path==='/dmpaint/templates.json'||path==='/dmpaint/template.svg'){
const mode=url.searchParams.get('mode')||'clan';
if(!templateModes.includes(mode))return new Response('Unknown design type',{status:400});
if(!modes.includes(mode))return new Response('Staff permission required',{status:403});
if(path.endsWith('.json'))return Response.json({templates:templateCatalogue(mode)},{headers:{'Cache-Control':'private, no-store'}});
try{
const input={mode,id:url.searchParams.get('design')};
for(const field of ['title','primary','secondary','trim','outfit'])if(url.searchParams.has(field))input[field]=url.searchParams.get(field);
if(mode==='seal'||mode==='award'){
const file=mode==='seal'?'imperial-post-seal-v2.png':'seals/award-network-staff.png';
input.sealData='data:image/png;base64,'+Buffer.from(await load(new URL('../web/assets/'+file,import.meta.url))).toString('base64');
}
const svg=renderPaintTemplate(input);
return new Response(request.method==='HEAD'?null:svg,{headers:{'Content-Type':'image/svg+xml; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':DMPAINT_CSP}});
}catch(error){if(error instanceof TypeError)return new Response(error.message,{status:400});throw error;}
}
if(path==='/dmpaint'||path==='/dmpaint/'){
const mode=url.searchParams.get('mode')||'clan';
if(!['clan','company','seal','award'].includes(mode))return new Response('Unknown design type',{status:400});
if(!templateModes.includes(mode))return new Response('Unknown design type',{status:400});
if(['seal','award'].includes(mode)&&!staff)return new Response('Staff permission required',{status:403});
return asset('./public/dmpaint/index.html','html',request);
}
const own=path.match(/^\/dmpaint\/(entry\.mjs|theme\.css)$/);
const own=path.match(/^\/dmpaint\/(entry\.mjs|templates\.mjs|theme\.css)$/);
if(own)return asset('./public/dmpaint/'+own[1],own[1].split('.').at(-1),request);
if(path.startsWith('/dmpaint/vendor/')||path.startsWith('/dmpaint/images/')){
const file=path.startsWith('/dmpaint/images/')?'images/'+path.slice('/dmpaint/images/'.length):path.slice('/dmpaint/vendor/'.length),extension=file.split('.').at(-1);

View file

@ -1,4 +1,4 @@
const labels={clan:'Clan logo',company:'Company logo',seal:'Seals',award:'Awards'};
const labels={clan:'Clan logo',company:'Company logo',character:'Character',seal:'Seals',award:'Awards'};
export async function mountDMPaint(host){
const link=document.createElement('link');link.rel='stylesheet';link.href='/v2/cp-v2-dmpaint.css';document.head.append(link);
const root=document.createElement('section');root.className='dmpaint-workspace';host.replaceChildren(root);

View file

@ -1,8 +1,9 @@
import {mountPaintTemplates} from '/dmpaint/templates.mjs';
import Editor from '/dmpaint/vendor/Editor.js';
const status=document.querySelector('#paint-status'),svgButton=document.querySelector('#download-svg'),pngButton=document.querySelector('#download-png');
const mode=new URL(location.href).searchParams.get('mode')||'clan';
const names={clan:'Clan logo',company:'Company logo',seal:'Staff seal',award:'Staff award'};
let editor;
const names={clan:'Clan logo',company:'Company logo',character:'Character',seal:'Staff seal',award:'Staff award'};
let editor,cleanCanvas;
const filename=()=>document.querySelector('#filename').value.replace(/[^a-zA-Z0-9_-]/g,'-').slice(0,64)||'dmpaint-design';
function download(blob,extension){const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename()+'.'+extension;link.click();setTimeout(()=>URL.revokeObjectURL(url),30000);}
async function start(){
@ -12,7 +13,7 @@ async function start(){
document.querySelector('#filename').value='my-'+mode;
editor=new Editor(document.querySelector('#editor-container'));
editor.setConfig({canvasName:'dmpaint',dimensions:[512,512],imgPath:'/dmpaint/vendor/images',extPath:'/dmpaint/vendor/extensions',lang:'en',initFill:{color:'D9BB69',opacity:1},initStroke:{color:'12362B',opacity:1,width:2},noDefaultExtensions:true,extensions:['ext-opensave','ext-polystar','ext-eyedropper','ext-layer_view','ext-panning','ext-grid'],userExtensions:[],allowedOrigins:[],preventAllURLConfig:true,preventURLContentLoading:true,lockExtensions:true,noStorageOnLoad:true,no_save_warning:false});
editor.ready(()=>{svgButton.disabled=pngButton.disabled=false;status.textContent='Draw, add text or open an existing image. Download before leaving this page.';});
editor.ready(()=>{cleanCanvas=editor.svgCanvas.getSvgString();svgButton.disabled=pngButton.disabled=false;status.textContent='Draw, choose a free design or open an existing image. Download before leaving this page.';mountPaintTemplates({editor,status,mode,cleanCanvas}).catch(error=>{status.textContent=error.message;});});
await editor.init();
}
svgButton.onclick=()=>{try{download(new Blob([editor.svgCanvas.getSvgString()],{type:'image/svg+xml'}),'svg');status.textContent='SVG downloaded. Keep this editable file to continue your design later.';}catch(error){status.textContent=error.message;}};

View file

@ -0,0 +1,28 @@
const element=(document,tag,text)=>{const node=document.createElement(tag);if(text)node.textContent=text;return node;};
export async function mountPaintTemplates({editor,status,mode,cleanCanvas,document=globalThis.document,fetcher=globalThis.fetch,confirmReplace=globalThis.confirm}){
const response=await fetcher('/dmpaint/templates.json?mode='+mode,{credentials:'same-origin',cache:'no-store'});
if(!response.ok)throw Error('The template library could not open. Your drawing is unchanged.');
const data=await response.json(),panel=element(document,'details');panel.className='paint-library';panel.append(element(document,'summary','Free designs · choose a starting point'));
const body=element(document,'div');body.className='paint-library-body';const cards=element(document,'div');cards.className='paint-template-cards';const form=element(document,'div');form.className='paint-template-fields';body.append(cards,form);panel.append(body);
const values={},controls={};
for(const [name,label,type,value]of [['title','Name','text',mode==='character'?'DESERT TRAVELLER':'YOUR NAME'],['primary','Primary','color','#143E30'],['secondary','Secondary','color','#D7B65D'],['trim','Trim','color','#F3E5B8']]){
const field=element(document,'label',label),input=element(document,'input');input.type=type;input.value=value;if(type==='text')input.maxLength=40;field.append(input);form.append(field);controls[name]=input;values[name]=()=>input.value;
}
if(mode==='character'){
const field=element(document,'label','Outfit'),select=element(document,'select');for(const [value,label]of [['hood','Desert hood'],['headscarf','Caravan headscarf'],['armour','House armour']]){const option=element(document,'option',label);option.value=value;select.append(option);}field.append(select);form.append(field);controls.outfit=select;values.outfit=()=>select.value;
}
let selected=data.templates[0]?.id;const buttons=[];
const url=id=>{const query=new URLSearchParams({mode,design:id});for(const [key,read]of Object.entries(values))query.set(key,read());return '/dmpaint/template.svg?'+query;};
const update=()=>{for(const {button,image,id}of buttons){button.setAttribute('aria-pressed',String(id===selected));image.src=url(id);}};
for(const design of data.templates){const button=element(document,'button'),image=element(document,'img');button.type='button';image.alt='';image.width=96;image.height=96;button.append(image,element(document,'span',design.name));button.onclick=()=>{selected=design.id;update();};cards.append(button);buttons.push({button,image,id:design.id});}
for(const control of Object.values(controls))control.addEventListener('change',update);
const apply=element(document,'button','Load design');apply.type='button';form.append(apply);
apply.onclick=async()=>{
if(!selected)return;
if(editor.svgCanvas.getSvgString()!==cleanCanvas&&!confirmReplace('Replace this drawing with the selected design? Download your current artwork first.'))return;
apply.disabled=true;
try{const response=await fetcher(url(selected),{credentials:'same-origin',cache:'no-store'});if(!response.ok)throw Error(await response.text());const svg=await response.text();if(editor.svgCanvas.setSvgString(svg)===false)throw Error('The design could not load.');status.textContent='Design loaded. Select its shapes, colours or text to edit. Download SVG to keep an editable copy.';panel.open=false;}
catch(error){status.textContent=error.message;}finally{apply.disabled=false;}
};
update();document.querySelector('#paint-status').before(panel);return panel;
}

View file

@ -1,3 +1,4 @@
:root{color-scheme:dark;--main-bg-color:#17382e;--text-color:#f0e5c8;--border-color:#88703c;--canvas-bg-color:#10291f;--link-color:#e6c774;--ruler-color:#b8a56d;--icon-bg-color:#214438;--icon-bg-color-hover:#476345;--input-color:#10291f;--orange-color:#e6c774}*{box-sizing:border-box}html,body{height:100%;margin:0;background:#0b211a;color:#f0e5c8;font-family:Arial,sans-serif}body{display:flex;flex-direction:column}.paint-header{display:flex;align-items:center;gap:14px;padding:10px 18px;background:linear-gradient(110deg,#244b38,#112d24);border-bottom:1px solid #a88b47}.paint-header img{object-fit:contain}.paint-header h1{margin:0;color:#e6c774;font:700 25px Georgia,serif}.paint-header p{margin:4px 0 0;font-size:12px;color:#c7cfbb}.paint-header label{margin-left:auto;display:flex;align-items:center;gap:8px;font-size:12px}.paint-header input{width:150px;padding:8px}.paint-actions{display:flex;gap:8px}button,.paint-header input{border:1px solid #9f8548;border-radius:6px;background:#10291f;color:#f0e5c8}button{padding:9px 12px;font-weight:600;cursor:pointer}button:hover{background:#34563c}button:disabled{opacity:.5;cursor:wait}button:focus-visible,input:focus-visible{outline:2px solid #f1d88a;outline-offset:3px}#paint-status{font-size:12px;margin:0;padding:8px 18px;color:#d1d7c8;border-bottom:1px solid #6c5c33;min-height:30px}#editor-container{width:100%;height:calc(100vh - 150px);min-height:460px;flex:1;min-width:0}#workarea{background-color:#10251f;background-image:linear-gradient(45deg,#1d392e 25%,transparent 25%),linear-gradient(-45deg,#1d392e 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#1d392e 75%),linear-gradient(-45deg,transparent 75%,#1d392e 75%);background-size:24px 24px;background-position:0 0,0 12px,12px -12px,-12px 0}#tools_top,#tools_left,#tools_bottom,#sidepanels{background:#17382e}footer{display:flex;justify-content:space-between;gap:12px;padding:10px 18px;font-size:11px;color:#b8c6b4;border-top:1px solid #6c5c33}footer a{color:#e6c774}@media(max-width:740px){.paint-header{flex-wrap:wrap;padding:10px}.paint-header label{margin-left:0}.paint-actions{margin-left:auto}.paint-header h1{font-size:21px}footer{flex-direction:column}#editor-container{height:650px}}
html,body{overflow:hidden}.paint-header,body>footer,#paint-status{flex-shrink:0}#editor-container{flex:1 1 auto;height:auto;min-height:0;overflow:hidden}
.paint-library{flex-shrink:0;border-bottom:1px solid #8c763e;background:linear-gradient(110deg,#203e31,#10291f);font-size:12px}.paint-library summary{padding:10px 18px;color:#e6c774;cursor:pointer;font-weight:bold}.paint-library-body{display:flex;gap:20px;padding:4px 18px 14px;max-height:270px;overflow:auto}.paint-template-cards{display:flex;gap:8px;align-items:start}.paint-template-cards button{display:grid;gap:5px;justify-items:center;width:128px;min-height:130px;font-size:11px}.paint-template-cards button[aria-pressed=true]{background:#34563c;outline:2px solid #e6c774;outline-offset:-3px}.paint-template-cards img{object-fit:contain}.paint-template-fields{display:flex;gap:10px;align-items:center;flex-wrap:wrap;max-width:560px}.paint-template-fields label{display:grid;gap:5px}.paint-template-fields input,.paint-template-fields select{background:#10291f;color:#f0e5c8;border:1px solid #9f8548;border-radius:5px;padding:6px;max-width:180px}.paint-template-fields input[type=color]{width:52px;height:34px;padding:2px}@media(max-width:740px){.paint-library-body{flex-direction:column;max-height:240px}.paint-template-cards{flex-wrap:wrap}.paint-template-cards button{width:115px}}

View file

@ -0,0 +1,57 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createDMPaint} from '../control-panel/dmpaint.mjs';
import {templateCatalogue,templateModes,renderPaintTemplate} from '../control-panel/dmpaint-templates.mjs';
import {mountPaintTemplates} from '../control-panel/public/dmpaint/templates.mjs';
const request=path=>new Request('https://cp.dunerealms.com'+path);
const route=(staff=false,user={id:'person'})=>createDMPaint({}, {authenticate:async()=>user,authorise:async()=>staff});
test('five curated designs serve clans and companies equally, with fixed POL artwork excluded',()=>{
const ids=new Set(templateModes.flatMap(mode=>templateCatalogue(mode).map(d=>d.id)));
assert.equal(ids.size,5);assert.deepEqual(templateCatalogue('clan'),templateCatalogue('company'));
assert.deepEqual(templateCatalogue('politics'),[]);
for(const mode of templateModes)for(const design of templateCatalogue(mode)){
const svg=renderPaintTemplate({mode,id:design.id,sealData:'data:image/png;base64,AAAA'});
assert.match(svg,/width="512" height="512"/);assert.doesNotMatch(svg,/<(?:script|foreignObject|style)\b|\bon\w+=|(?:https?:)?\/\/[^w]/i);
const tags=[...svg.matchAll(/<\/?([a-zA-Z]+)/g)].map(m=>m[1]);assert.ok(tags.every(t=>['svg','title','g','path','circle','image','text'].includes(t)));
}
});
test('editable labels escape markup and colours cannot inject SVG attributes',()=>{
const options={mode:'clan',id:'desert-crest',title:'<script>& "Clan"'};
const svg=renderPaintTemplate(options);assert.match(svg,/&lt;script&gt;&amp; &quot;Clan&quot;/);assert.doesNotMatch(svg,/<script>/);
for(const invalid of [{primary:'red" onclick="x'},{title:'x'.repeat(41)},{outfit:'javascript:'},{mode:'politics'}])assert.throws(()=>renderPaintTemplate({...options,...invalid}));
const a=renderPaintTemplate({mode:'character',id:'desert-traveller',outfit:'hood'}),b=renderPaintTemplate({mode:'character',id:'desert-traveller',outfit:'headscarf'}),c=renderPaintTemplate({mode:'character',id:'desert-traveller',outfit:'armour'});assert.notEqual(a,b);assert.notEqual(b,c);
});
test('template previews and downloads enforce the current session and staff modes on every read',async()=>{
const citizen=route(),staff=route(true);
for(const path of ['/dmpaint/templates.json?mode=seal','/dmpaint/template.svg?mode=award&design=service-award']){
assert.equal((await citizen(request(path))).status,403);assert.equal((await route(false,null)(request(path))).status,401);
}
assert.equal((await citizen(request('/dmpaint/template.svg?mode=clan&design=service-seal'))).status,400);
assert.equal((await citizen(request('/dmpaint/template.svg?mode=politics&design=desert-crest'))).status,400);
for(const mode of ['clan','company','character']){
const catalogue=await (await citizen(request('/dmpaint/templates.json?mode='+mode))).json();assert.ok(catalogue.templates.length);
for(const design of catalogue.templates){const response=await citizen(request('/dmpaint/template.svg?mode='+mode+'&design='+design.id));assert.equal(response.status,200);assert.match(response.headers.get('cache-control'),/private, no-store/);assert.match(await response.text(),/<svg/);}
}
for(const [mode,id]of [['seal','service-seal'],['award','service-award']]){const response=await staff(request('/dmpaint/template.svg?mode='+mode+'&design='+id));assert.equal(response.status,200);const svg=await response.text();assert.match(svg,/data:image\/png;base64,iVBOR/);assert.doesNotMatch(svg,/<image href="https?:/);}
});
class Element{
constructor(tag){this.tag=tag;this.children=[];this.textContent='';this.attributes={};this.listeners={};}
append(...items){this.children.push(...items);}
setAttribute(k,v){this.attributes[k]=v;}
addEventListener(k,fn){this.listeners[k]=fn;}
}
const tree=node=>[node,...node.children.flatMap(tree)];
test('loading a design preserves a dirty canvas when cancelled and uses the chosen editable fields when confirmed',async()=>{
let inserted,current='<svg>my existing drawing</svg>',confirmations=0,accept=false,writes=0;
const document={createElement:tag=>new Element(tag),querySelector:()=>({before:panel=>{inserted=panel;}})};
const editor={svgCanvas:{getSvgString:()=>current,setSvgString:svg=>{writes++;current=svg;return true;}}};
const handle=route(),status={};
await mountPaintTemplates({editor,status,mode:'clan',cleanCanvas:'<svg/>',document,fetcher:(url)=>handle(request(url)),confirmReplace:()=>{confirmations++;return accept;}});
const nodes=tree(inserted),apply=nodes.find(n=>n.textContent==='Load design');
await apply.onclick();assert.equal(writes,0);assert.equal(confirmations,1);assert.match(current,/my existing drawing/);
const title=nodes.find(n=>n.tag==='input'&&n.type==='text');title.value='MY CLAN';
const colour=nodes.find(n=>n.tag==='input'&&n.type==='color');colour.value='#AABBCC';
accept=true;await apply.onclick();assert.equal(writes,1);assert.match(current,/MY CLAN/);assert.match(current,/#AABBCC/);assert.equal(apply.disabled,false);assert.equal(inserted.open,false);
// A loaded template remains a drawing: subsequent replacement still needs consent.
accept=false;await apply.onclick();assert.equal(writes,1);assert.equal(confirmations,3);
});

View file

@ -11,13 +11,13 @@ test('the drawing service and vendor code require a registered session',async()=
});
test('ordinary users can design logos; direct staff modes are rejected server-side',async()=>{
const handle=route({id:'citizen'});
assert.deepEqual((await (await handle(request('/api/dmpaint'))).json()).modes,['clan','company']);
assert.deepEqual((await (await handle(request('/api/dmpaint'))).json()).modes,['clan','company','character']);
assert.equal((await handle(request('/dmpaint/?mode=clan'))).status,200);
for(const mode of ['seal','award'])assert.equal((await handle(request('/dmpaint/?mode='+mode))).status,403);
});
test('existing staff permission enables seals and awards',async()=>{
const handle=route({id:'staff'},true);
assert.deepEqual((await (await handle(request('/api/dmpaint'))).json()).modes,['clan','company','seal','award']);
assert.deepEqual((await (await handle(request('/api/dmpaint'))).json()).modes,['clan','company','character','seal','award']);
assert.equal((await handle(request('/dmpaint/?mode=seal'))).status,200);
});
test('no design upload or arbitrary file serving is exposed',async()=>{