// @requirements REQ-PRODUCT-COLLECTION-REHEARSAL // @requirements REQ-PRODUCT-COLLECTION-WORKBENCH REQ-PRODUCT-A11Y REQ-PRODUCT-MOBILE import {collectionPermissionAuthoring,normalizeCollectionWorkbenchContext,prepareCollectionFlowSettings,formatCollectionWorkbenchSettings,collectionWorkbenchHandoff} from './collection-workbench.js'; import {mountCollectionRehearsal} from './collection-rehearsal.js'; import type {MountedCollectionRehearsal} from './collection-rehearsal.js'; import {collectionPermissionEditor} from './collection-permission-editor.js'; import {parseConfigSource,configSourceFormat} from './config-document.js'; import type {ConfigSourceFormat} from './config-document.js'; import type {CollectionFlowDecision,CollectionFlowSettings} from './collection-flow.js'; export interface MountedCollectionWorkbench {getSettings():CollectionFlowSettings;destroy():void} /** Local settings authoring. No storage, transport, release replacement or permission action is installed. */ export function mountCollectionWorkbench(container:HTMLElement,options:{context:unknown}):MountedCollectionWorkbench { const doc=container.ownerDocument,view=doc.defaultView;if(!view)throw Error('Use a browser document.'); const context=normalizeCollectionWorkbenchContext(options.context),instance='nb-workbench-'+crypto.randomUUID(); const node=(tag:K,text?:string)=>{const el=doc.createElement(tag);if(text!==undefined)el.textContent=text;return el;}; const root=node('section');root.className='nb-collection-workbench';const header=node('div');header.className='nb-workbench-release'; const release=node('div');release.append(node('span','01 / Legal release'),node('h2',context.facts.document.title),node('p','Version '+context.facts.document.version+' · '+context.facts.document.effectiveDate+' · '+context.facts.locale+' · '+(context.facts.mode==='preview'?'Preview release':'Production release'))); const refs=node('details');refs.append(node('summary','Release reference'),node('code',context.facts.artifactId),node('p','Prepared public facts are supplied by your build. This editor does not authenticate an unknown sender or replace the final artifact check.')); const reviewLabel=node('label'),review=node('input');review.type='checkbox';review.dataset.workbench='release';reviewLabel.append(review,doc.createTextNode('Use this exact release for these settings.'));release.append(refs,reviewLabel);header.append(release); const imports=node('div');imports.className='nb-workbench-import';const importLabel=node('label','Continue from a settings file'),file=node('input');file.type='file';file.accept='.json,.yaml,.yml,.md,.markdown';file.id=instance+'-file';importLabel.htmlFor=file.id;imports.append(importLabel,file,node('p','Local JSON, YAML or Markdown frontmatter. It must name this release; nothing is uploaded.'));header.append(imports);root.append(header); const layout=node('div');layout.className='nb-workbench-layout';const editor=node('div');editor.className='nb-workbench-editor';const preview=node('aside');preview.className='nb-workbench-preview';preview.setAttribute('aria-label','Notice preview');preview.append(node('p','03 / Preview'),node('h2','Read it beside your form'),node('p','The preview uses your selected public facts. Preview the wording, or try the choices with a temporary local recorder. Links stay inactive; your application is not connected.')); const paper=node('div');paper.className='nb-workbench-paper';paper.append(node('p','Choose purposes and write the introduction, then open the preview.'));preview.append(paper);layout.append(editor,preview);root.append(layout); const wording=node('section');wording.append(node('p','02 / Form and wording'),node('h2','What should people know here?')); const fields=new Map(); function field(key:string,label:string,multiline=false,max=300){const wrap=node('div');wrap.className='nb-workbench-field';const input=multiline?node('textarea'):node('input');input.id=instance+'-'+key;input.maxLength=max;input.required=['scopeId','title','intro'].includes(key);if(key==='scopeId')(input as HTMLInputElement).pattern='[a-z][a-z0-9-]{0,119}';if(input.tagName==='TEXTAREA')(input as HTMLTextAreaElement).rows=3;else(input as HTMLInputElement).type='text';const title=node('label',label);title.htmlFor=input.id;wrap.append(title,input);fields.set(key,input);return wrap;} wording.append(field('scopeId','Form ID',false,120),node('p','Use a stable name such as contact-form. Keep person and submission identifiers out of it.'),field('title','Notice heading'),field('intro','Introduction',true,2000)); const labels=node('details');labels.append(node('summary','Link labels')); if(context.facts.localization)labels.append(node('p','Labels come from the release’s collection dictionary. Change and rebuild that dictionary to revise them.')); else labels.append(field('detailsLabel','Details label',false,160),field('privacyLinkLabel','Privacy link label',false,160),node('p','Leave blank to use the built-in English labels.')); wording.append(labels);const statusLabel=node('label','Notice wording review'),wordingStatus=node('select');wordingStatus.id=instance+'-wording-review';statusLabel.htmlFor=wordingStatus.id;for(const [value,text] of [['draft','Draft — still needs review'],['reviewed','Wording reviewed']] as const){const o=node('option',text);o.value=value;wordingStatus.append(o);}wording.append(statusLabel,wordingStatus,node('p','This is your declaration about the notice wording. It does not review the processing condition, permission wording or field instructions.'));editor.append(wording); const purposes=node('section');purposes.append(node('h2','Which purposes belong on this form?'),node('p','Choose each purpose used here. Then choose its presentation; neither its legal basis nor its optionality selects that route.')); const grid=node('div');grid.className='nb-workbench-purpose-grid';const choices=new Map|undefined}>(); for(const p of context.facts.purposes){const card=node('article');card.className='nb-workbench-purpose';const label=node('label'),box=node('input');box.type='checkbox';box.dataset.purpose=p.id;label.append(box,doc.createTextNode(p.name));card.append(label,node('p',p.description));const routeLabel=node('label','Presentation'),route=node('select');route.id=instance+'-route-'+p.id;routeLabel.htmlFor=route.id;for(const [value,text] of [['','Choose explicitly'],['notice-only','Notice only'],['separate-permission','Separate permission']] as const){const option=node('option',text);option.value=value;route.append(option);}route.disabled=true;card.append(routeLabel,route);const facts=node('details');facts.append(node('summary','Purpose facts'),node('p','Legal basis: '+p.legalBasis),node('p','Information: '+p.dataCategories.join(', ')),node('p','Retention: '+p.retention),node('p','If not provided: '+p.collection.consequences));card.append(facts);const existing=context.initial?.settings.decisions.find(d=>d.purposeId===p.id&&d.presentation==='separate-permission'),note=node('p');note.id=route.id+'-note';route.setAttribute('aria-describedby',note.id);card.append(note);const availability=collectionPermissionAuthoring(context,p.id),permission=context.permissionContext?collectionPermissionEditor(card,{idPrefix:instance+'-permission-'+p.id,onEdit(){invalidate(new view.Event('input'));},onReview(){invalidate(new view.Event('change'),false);}}):undefined; const updateNote=()=>{note.textContent=!box.checked?'Select this purpose if your form uses it.':route.value==='notice-only'?'Shown in the notice. No permission offer or control will be created.':route.value==='separate-permission'?permission?availability.reason:existing?'The existing permission settings will be preserved. Prepare a new workbench to edit them.':'No permission settings are included for this purpose. Prepare a new workbench from the release.':'Choose its presentation explicitly. This does not decide its legal basis.';permission?.setActive(box.checked&&route.value==='separate-permission'&&availability.available);};grid.append(card);choices.set(p.id,{included:box,route,updateNote,permission});box.addEventListener('change',()=>{route.disabled=!box.checked;updateNote();});route.addEventListener('change',updateNote);} purposes.append(grid);editor.append(purposes); const actions=node('div');actions.className='nb-workbench-actions';const show=node('button','Preview notice'),tryFlow=node('button','Try form flow'),exportButton=node('button','Copy build settings');for(const b of [show,tryFlow,exportButton])b.type='button';exportButton.className='nb-workbench-primary';actions.append(reviewLabel,exportButton);const previewActions=node('div');previewActions.className='nb-workbench-preview-actions';previewActions.append(show,tryFlow);preview.insertBefore(previewActions,paper);const status=node('p');status.className='nb-workbench-status';status.setAttribute('role','status');status.setAttribute('aria-live','polite');root.append(actions,status);container.append(root); const drawer=node('dialog');drawer.className='nb-workbench-drawer';drawer.setAttribute('aria-labelledby',instance+'-export-title');const drawerTitle=node('h2','Build settings');drawerTitle.id=instance+'-export-title';drawerTitle.tabIndex=-1;const close=node('button','Close settings');close.type='button';const formats=node('select');const formatLabel=node('label','File format');formats.id=instance+'-format';formatLabel.htmlFor=formats.id;for(const [value,label] of [['yaml','YAML'],['json','JSON'],['markdown','Markdown frontmatter']] as const){const option=node('option',label);option.value=value;formats.append(option);}const output=node('textarea');output.readOnly=true;output.setAttribute('aria-label','Collection flow settings');output.rows=16;const copy=node('button','Copy settings');copy.type='button';const handoff=node('p'),drawerStatus=node('p');drawerStatus.setAttribute('role','status');drawer.append(close,drawerTitle,node('p','Save this as contact-flow.yaml (or use the selected extension). Run the existing collection-flow build against the same final legal release. The preview is not a compiled descriptor.'),formatLabel,formats,output,copy,handoff,drawerStatus);root.append(drawer); let rehearsal:MountedCollectionRehearsal|undefined; const stopRehearsal=()=>{rehearsal?.destroy();rehearsal=undefined;}; let destroyed=false,epoch=0,opener:HTMLElement|null=null,exported:CollectionFlowSettings|undefined; const report=(message:string)=>{status.textContent=message;}; function collect():CollectionFlowSettings { for(const input of fields.values()){input.removeAttribute('aria-invalid');if(!input.checkValidity()){input.setAttribute('aria-invalid','true');input.focus();throw Error('Complete the highlighted form or wording field before continuing.');}} const purposeIds=[...choices].filter(([,c])=>c.included.checked).map(([id])=>id),decisions:CollectionFlowDecision[]=[];if(!purposeIds.length)throw Error('Choose at least one purpose used by this form.'); for(const id of purposeIds){const route=choices.get(id)!.route.value; if(route==='notice-only')decisions.push({purposeId:id,presentation:'notice-only'}); else if(route==='separate-permission'){const editable=choices.get(id)!.permission;if(editable){const available=collectionPermissionAuthoring(context,id);if(!available.available)throw Error(available.reason);decisions.push({purposeId:id,presentation:'separate-permission',permission:editable.read()});continue;}const saved=context.initial?.settings.decisions.find(d=>d.purposeId===id&&d.presentation==='separate-permission');if(!saved)throw Error('Complete the separate permission for '+id+' in your application, then prepare a context with those settings. No permission was inferred.');decisions.push(structuredClone(saved));} else throw Error('Choose a presentation for '+id+'.'); } const value=(key:string)=>fields.get(key)?.value??''; return {reviewedArtifactId:context.facts.artifactId,notice:{scopeId:value('scopeId'),purposeIds,reviewStatus:wordingStatus.value as 'draft'|'reviewed',wording:{title:value('title'),intro:value('intro'),...(value('detailsLabel')?{detailsLabel:value('detailsLabel')}:{}),...(value('privacyLinkLabel')?{privacyLinkLabel:value('privacyLinkLabel')}:{})}},decisions}; } function populate(settings:CollectionFlowSettings|undefined){ for(const [key,input] of fields)input.value=key==='scopeId'?settings?.notice.scopeId??'':settings?.notice.wording[key as keyof typeof settings.notice.wording]??''; wordingStatus.value=settings?.notice.reviewStatus??'draft';for(const [id,c] of choices){c.included.checked=settings?.notice.purposeIds.includes(id)??false;c.route.disabled=!c.included.checked;c.route.value=settings?.decisions.find(d=>d.purposeId===id)?.presentation??'';const d=settings?.decisions.find(d=>d.purposeId===id);c.permission?.populate(d?.presentation==='separate-permission'?d.permission:undefined);c.updateNote();}review.checked=false; } function invalidate(event:Event,resetNotice=true){if(destroyed||event.target&&drawer.contains(event.target as Node))return;stopRehearsal();epoch++;exported=undefined;review.checked=false;if(resetNotice)wordingStatus.value='draft';paper.replaceChildren(node('p','Settings changed. Open the preview again to read the current draft.'));} for(const input of fields.values())input.addEventListener('input',event=>invalidate(event)); wordingStatus.addEventListener('change',event=>invalidate(event,false)); for(const c of choices.values()){c.included.addEventListener('change',event=>invalidate(event));c.route.addEventListener('change',event=>invalidate(event));} show.addEventListener('click',()=>{if(destroyed)return;try{const plan=prepareCollectionFlowSettings(context,collect(),{releaseConfirmed:true,idPrefix:instance+'-preview'});paper.innerHTML=plan.previewHtml;for(const a of paper.querySelectorAll('a')){a.removeAttribute('href');a.setAttribute('role','link');a.setAttribute('aria-disabled','true');}report('Draft preview opened. No notice presentation or permission has been recorded.');}catch(error){paper.replaceChildren(node('p','Complete the settings before previewing.'));report(error instanceof Error?error.message:'Could not preview these settings.');}}); tryFlow.addEventListener('click',async()=>{if(destroyed)return;try{const settings=prepareCollectionFlowSettings(context,collect(),{releaseConfirmed:review.checked as true}).settings;tryFlow.focus();stopRehearsal();rehearsal=mountCollectionRehearsal(root,{context,settings,releaseConfirmed:true});await rehearsal.open();}catch(error){if(!destroyed)report(error instanceof Error?error.message:'Could not open the form rehearsal.');}}); review.addEventListener('change',stopRehearsal); async function format(){if(!exported||destroyed)return;const token=++epoch;output.value='';copy.disabled=true;try{const text=await formatCollectionWorkbenchSettings(context,exported,formats.value as ConfigSourceFormat);if(destroyed||epoch!==token||!exported)return;output.value=text;copy.disabled=false;handoff.textContent=collectionWorkbenchHandoff(context,exported,formats.value==='markdown'?'md':formats.value).command;drawerStatus.textContent='Settings only. Review field placement, final output and host behavior separately.';}catch{if(!destroyed&&epoch===token)drawerStatus.textContent='Could not format these settings. Choose JSON and try again.';}} exportButton.addEventListener('click',()=>{if(destroyed)return;try{exported=prepareCollectionFlowSettings(context,collect(),{releaseConfirmed:review.checked as true}).settings;opener=exportButton;drawer.showModal();drawerTitle.focus();void format();}catch(error){report(error instanceof Error?error.message:'Could not export these settings.');}}); formats.addEventListener('change',()=>void format());close.addEventListener('click',()=>drawer.close());drawer.addEventListener('close',()=>{if(drawer.open)return;epoch++;exported=undefined;output.value='';if(!destroyed&&opener?.isConnected)opener.focus();opener=null;}); copy.addEventListener('click',async()=>{if(destroyed||!drawer.open||!output.value)return;const token=epoch;try{await view.navigator.clipboard.writeText(output.value);if(!destroyed&&token===epoch&&drawer.open)drawerStatus.textContent='Settings copied. Save the file, then run the build command.';}catch{if(!destroyed&&token===epoch&&drawer.open){output.focus();output.select();drawerStatus.textContent='Clipboard unavailable. Copy the selected settings manually.';}}}); file.addEventListener('change',async()=>{const selected=file.files?.[0];if(!selected||destroyed)return;stopRehearsal();const token=++epoch;try{if(selected.size>128*1024)throw Error('Keep settings files within 128 KiB.');const text=await selected.text(),parsed=await parseConfigSource(text,configSourceFormat(selected.name));if(destroyed||token!==epoch)return;const settings=prepareCollectionFlowSettings(context,parsed.config,{releaseConfirmed:true}).settings;stopRehearsal();populate(settings);paper.replaceChildren(node('p','Imported settings need a fresh preview and release confirmation.'));report('Settings imported. Review the notice and permission fields, then confirm this exact release before export.');}catch(error){if(!destroyed&&token===epoch)report(error instanceof Error?error.message:'Could not import these settings.');}finally{if(!destroyed&&token===epoch)file.value='';}}); populate(context.initial?.settings); return {getSettings(){if(destroyed)throw Error('Workbench has ended.');return prepareCollectionFlowSettings(context,collect(),{releaseConfirmed:review.checked as true}).settings;},destroy(){if(destroyed)return;destroyed=true;stopRehearsal();epoch++;exported=undefined;if(drawer.open)drawer.close();opener=null;root.remove();}}; }