// @requirements REQ-PRODUCT-PROCESSING-WORKBENCH REQ-PRODUCT-A11Y REQ-PRODUCT-MOBILE import {normalizeProcessingWorkbenchContext,normalizeProcessingNoticeSettings,assembleProcessingNoticeContent,formatProcessingNoticeSettings,processingWorkbenchHandoff} from './processing-workbench.js'; import {createProcessingNoticeView} from './processing-notice-content.js'; import {parseConfigSource,configSourceFormat} from './config-document.js'; import type {ProcessingNoticeSettings} from './processing-workbench.js'; import type {ProcessingActivity} from './types.js'; export interface MountedProcessingWorkbench {getSettings():ProcessingNoticeSettings;destroy():void} /** Settings authoring only. No controller, storage, network transport or authoritative notice is created. */ export function mountProcessingWorkbench(container:HTMLElement,options:{context:unknown}):MountedProcessingWorkbench { const context=normalizeProcessingWorkbenchContext(options.context),doc=container.ownerDocument,view=doc.defaultView;if(!view)throw Error('Use a browser document.');const browser=view; const id='nb-processing-workbench-'+crypto.randomUUID(),node=(tag:K,text?:string)=>{const e=doc.createElement(tag);if(text!==undefined)e.textContent=text;return e;}; const root=node('section');root.className='nb-processing-workbench'; const release=node('section');release.className='nb-pw-release';release.append(node('p','01 / Policy release'),node('h2',context.facts.document.title),node('p','Version '+context.facts.document.version+' · '+context.facts.document.effectiveDate+' · '+(context.facts.localization?.locale??'en')+' · '+(context.facts.mode==='preview'?'Preview release':'Production release'))); const ref=node('details');ref.append(node('summary','Release and service references'),node('code',context.facts.artifactId),node('p','Prepared public facts come from your build. Final compilation verifies the intact artifact again.')); const services=node('dl');for(const s of context.facts.services){const row=node('div');row.append(node('dt',s.id),node('dd',s.activities.length?s.activities.join(', '):'Explicitly classified: none of these activities'));services.append(row);}ref.append(context.facts.services.length?services:node('p','No services are declared in this release. This does not establish absence of processing.'));release.append(ref); const fileLabel=node('label','Continue from a settings file'),file=node('input');file.id=id+'-file';file.type='file';file.accept='.json,.yaml,.yml,.md';fileLabel.htmlFor=file.id;release.append(fileLabel,file,node('p','Local JSON, YAML or Markdown frontmatter. The file must name this release; nothing is uploaded.'));root.append(release); const layout=node('div');layout.className='nb-pw-layout';const editor=node('section');editor.className='nb-pw-editor';editor.append(node('p','02 / Scope and wording'),node('h2','What should this action cover?')); const fields=new Map(),fieldErrors=new Map(); function field(key:string,label:string,max:number,multiline=false){const wrap=node('div'),labelEl=node('label',label),input=multiline?node('textarea'):node('input');wrap.className='nb-pw-field';input.id=id+'-'+key;labelEl.htmlFor=input.id;input.maxLength=max;input.required=true;input.lang=key==='scopeId'?'en':context.facts.localization?.locale??'en';input.dir=key==='scopeId'?'ltr':context.facts.localization?.direction??'ltr';if(multiline)(input as HTMLTextAreaElement).rows=4;else(input as HTMLInputElement).type='text';fields.set(key,input);const error=node('p');error.id=input.id+'-error';error.className='nb-pw-field-error';error.hidden=true;input.setAttribute('aria-describedby',error.id);fieldErrors.set(key,error);wrap.append(labelEl,input,error);return wrap;} editor.append(field('scopeId','Workflow scope',120),node('p','Use a stable name for this restriction workflow, never a person or account identifier. Changing the scope creates a different restriction context; it does not clear earlier opt-outs.')); const group=node('fieldset'),legend=node('legend','Activities covered by the action');group.append(legend,node('p','Choose explicitly. The visitor’s action opts out of every selected activity; these are editor settings, not visitor toggles.')); const activities=new Map(); for(const [key,label,description] of [['sale','Sale','The activity your organization has assessed as a sale of personal information.'],['sharing','Sharing','The activity your organization has assessed as sharing for cross-context behavioral advertising.'],['targeted-advertising','Targeted advertising','The activity your organization has assessed as targeted advertising.']] as const){const row=node('label');row.className='nb-pw-activity';const box=node('input');box.type='checkbox';box.dataset.activity=key;const copy=node('span');copy.append(node('strong',label),node('span',description));row.append(box,copy);group.append(row);activities.set(key,box);}const activityError=node('p');activityError.id=id+'-activities-error';activityError.className='nb-pw-field-error';activityError.hidden=true;group.setAttribute('aria-describedby',activityError.id);group.append(activityError);editor.append(group,node('p','The release’s service classifications are reference facts, not an activity recommendation. Legal scope and applicability need your review.'),field('title','Notice heading',300),field('description','Explanation',2000,true),field('actionLabel','Opt-out button label',120)); if(context.facts.localization)editor.append(node('p','Status and recovery messages come from the release’s '+context.facts.localization.locale+' dictionary. Write these three notice fields in the intended language; this editor does not translate them.')); const preview=node('aside');preview.className='nb-pw-preview';preview.setAttribute('aria-label','Processing notice preview');preview.append(node('p','03 / Preview'),node('h2','Read it as a visitor'),node('p','The action and policy reference stay inactive. This preview creates no choice, receipt or permission.')); const previewButton=node('button','Preview notice');previewButton.type='button';preview.append(previewButton);const paper=node('div');paper.className='nb-pw-paper';paper.append(node('p','Choose the activities and write all three fields, then preview the notice.'));preview.append(paper);layout.append(editor,preview);root.append(layout); const actions=node('div');actions.className='nb-pw-actions';const label=node('label'),review=node('input');review.type='checkbox';review.dataset.processingRelease='';label.append(review,doc.createTextNode('Use this exact release for these settings.'));const exportButton=node('button','Get build settings');exportButton.type='button';exportButton.className='nb-pw-primary';actions.append(label,exportButton);root.append(actions); const status=node('p');status.className='nb-pw-status';status.setAttribute('role','status');status.setAttribute('aria-live','polite');root.append(status); const drawer=node('dialog');drawer.className='nb-pw-drawer';drawer.setAttribute('aria-labelledby',id+'-export-title');const close=node('button','Close settings');close.type='button';const title=node('h2','Build settings');title.id=id+'-export-title';title.tabIndex=-1;const formatLabel=node('label','File format'),format=node('select');format.id=id+'-format';formatLabel.htmlFor=format.id;for(const [value,text] of [['yaml','YAML'],['json','JSON'],['markdown','Markdown frontmatter']]){const option=node('option',text);option.value=value!;format.append(option);} const output=node('textarea');output.readOnly=true;output.rows=15;output.setAttribute('aria-label','Processing notice build settings');const copy=node('button','Copy settings');copy.type='button';const download=node('a','Download settings');const handoff=node('p',processingWorkbenchHandoff()),drawerStatus=node('p');drawerStatus.setAttribute('role','status');drawer.append(close,title,node('p','Save these settings, review the wording, then compile against the exact final artifact. The release pin is a selection, not approval of newly written text.'),formatLabel,format,output,copy,download,handoff,drawerStatus);root.append(drawer);container.append(root); let destroyed=false,revision=0,formatToken=0,importToken=0,url:string|undefined,opener:HTMLElement|null=null,selectedOrder:ProcessingActivity[]=[]; const clearOutput=()=>{formatToken++;if(url)browser.URL.revokeObjectURL(url);url=undefined;output.value='';download.removeAttribute('href');download.removeAttribute('download');download.hidden=true;copy.disabled=true;}; const closeDrawer=()=>{if(drawer.open)drawer.close();const target=opener;opener=null;if(target?.isConnected)target.focus();}; function invalidate(){revision++;importToken++;file.value='';for(const [key,error] of fieldErrors){error.hidden=true;error.textContent='';fields.get(key)!.removeAttribute('aria-invalid');}activityError.hidden=true;activityError.textContent='';clearOutput();review.checked=false;paper.replaceChildren(node('p','The settings changed. Preview again to see the current wording.'));if(drawer.open)closeDrawer();status.textContent='Settings changed. Preview and select the release again before exporting.';} const changed=(event:Event)=>{if(destroyed||event.target===file||drawer.contains(event.target as Node))return;if(event.target===review){if(!review.checked){revision++;clearOutput();closeDrawer();}return;}invalidate();}; root.addEventListener('input',changed);root.addEventListener('change',changed); function settings(){if(destroyed)throw Error('This workbench has closed.');if(!review.checked)throw Error('Select the exact release before exporting.');return draft();} function draft(){if(destroyed)throw Error('This workbench has closed.');const selected=selectedOrder.filter(a=>activities.get(a)!.checked);for(const [a,box] of activities)if(box.checked&&!selected.includes(a))selected.push(a);return normalizeProcessingNoticeSettings({schemaVersion:1,reviewedArtifactId:context.facts.artifactId,scopeId:fields.get('scopeId')!.value,activities:selected,wording:{title:fields.get('title')!.value,description:fields.get('description')!.value,actionLabel:fields.get('actionLabel')!.value}});} function populate(s:ProcessingNoticeSettings){for(const key of ['scopeId','title','description','actionLabel'])fields.get(key)!.value=key==='scopeId'?s.scopeId:s.wording[key as keyof typeof s.wording];for(const [a,box] of activities)box.checked=s.activities.includes(a);selectedOrder=[...s.activities];} function validateEditor(){let first:HTMLElement|undefined; for(const [key,input] of fields){const max=key==='scopeId'?120:key==='title'?300:key==='description'?2000:120,value=input.value;const error=fieldErrors.get(key)!;const invalid=!value.trim()||new TextEncoder().encode(value).length>max||/[\u0000-\u001f\u007f]/u.test(value)||key==='scopeId'&&!/^[a-z][a-z0-9-]{0,119}$/u.test(value);error.hidden=!invalid;if(invalid){error.textContent=key==='scopeId'?'Use 1–120 lowercase letters, digits or hyphens, starting with a letter.':'Enter '+(key==='title'?'a heading':key==='description'?'an explanation':'a button label')+' using at most '+max+' UTF-8 bytes and no control characters.';input.setAttribute('aria-invalid','true');first??=input;}else{input.removeAttribute('aria-invalid');error.textContent='';}} activityError.hidden=[...activities.values()].some(box=>box.checked);if(activityError.hidden)activityError.textContent='';if(!activityError.hidden){activityError.textContent='Choose at least one activity for this action.';first??=activities.values().next().value;} if(first){status.textContent='Review the highlighted fields before continuing.';first.focus();return false;}return true; } const show=()=>{if(destroyed||!validateEditor())return;try{const s=draft(),content=assembleProcessingNoticeContent(context.facts,s);paper.replaceChildren(createProcessingNoticeView(doc,content,true).root);status.textContent='Wording preview only. No choice was recorded.';}catch{status.textContent='Choose at least one activity and supply a stable scope, heading, explanation and button label within their limits.';}}; previewButton.addEventListener('click',show); async function renderOutput(){if(destroyed)return;const version=revision;clearOutput();const nextToken=formatToken;drawerStatus.textContent='Preparing settings…';try{const s=settings(),value=await formatProcessingNoticeSettings(s,format.value as 'yaml'|'json'|'markdown');if(destroyed||nextToken!==formatToken||version!==revision||!drawer.open)return;output.value=value;handoff.textContent=processingWorkbenchHandoff(format.value as 'yaml'|'json'|'markdown');const extension=format.value==='markdown'?'md':format.value;download.download='processing-notice.'+extension;url=browser.URL.createObjectURL(new Blob([value],{type:'text/plain;charset=utf-8'}));download.href=url;download.hidden=false;copy.disabled=false;drawerStatus.textContent='Settings only. No notice was published or registered.';}catch{if(!destroyed&&nextToken===formatToken&&version===revision&&drawer.open)drawerStatus.textContent='Could not prepare these settings. Close the drawer and review the fields.';}} const open=async()=>{if(destroyed||!validateEditor())return;if(!review.checked){status.textContent='Select the exact release before exporting.';review.focus();return;}try{settings();}catch{status.textContent='Complete the fields and select the exact release before exporting.';return;}opener=exportButton;drawer.showModal();title.focus();await renderOutput();};exportButton.addEventListener('click',open);format.addEventListener('change',renderOutput); const copied=async()=>{const token=formatToken,value=output.value;if(!value||destroyed)return;try{if(!browser.navigator.clipboard?.writeText)throw Error();await browser.navigator.clipboard.writeText(value);if(!destroyed&&token===formatToken&&drawer.open)drawerStatus.textContent='Settings copied.';}catch{if(!destroyed&&token===formatToken&&drawer.open){output.focus();output.select();drawerStatus.textContent='Select and copy the settings manually.';}}};copy.addEventListener('click',copied); const finished=()=>{clearOutput();closeDrawer();};close.addEventListener('click',finished);const cancelled=(event:Event)=>{event.preventDefault();finished();};drawer.addEventListener('cancel',cancelled);const closed=()=>{if(!drawer.open){clearOutput();closeDrawer();}};drawer.addEventListener('close',closed);const backdrop=(event:MouseEvent)=>{const rect=drawer.getBoundingClientRect();if(event.target===drawer&&(event.clientXrect.right||event.clientYrect.bottom))finished();};drawer.addEventListener('click',backdrop); const imported=async()=>{const selected=file.files?.[0],token=++importToken,version=revision;if(!selected)return;if(selected.size>512*1024){status.textContent='Use a settings file no larger than 512 KiB.';return;}status.textContent='Reading the local settings file…';try{const source=await selected.text(),parsed=await parseConfigSource(source,configSourceFormat(selected.name)),s=normalizeProcessingNoticeSettings(parsed.config);assembleProcessingNoticeContent(context.facts,s);if(destroyed||token!==importToken||version!==revision)return;invalidate();populate(s);file.value='';status.textContent='Settings loaded. Preview the wording and select the exact release before exporting.';}catch{if(!destroyed&&token===importToken&&version===revision)status.textContent='Could not load these settings for this release. The previous draft is unchanged.';}finally{if(!destroyed&&token===importToken)file.value='';}};file.addEventListener('change',imported); if(context.initial)populate(context.initial); return {getSettings:settings,destroy(){if(destroyed)return;destroyed=true;revision++;importToken++;clearOutput();root.removeEventListener('input',changed);root.removeEventListener('change',changed);previewButton.removeEventListener('click',show);exportButton.removeEventListener('click',open);format.removeEventListener('change',renderOutput);copy.removeEventListener('click',copied);close.removeEventListener('click',finished);file.removeEventListener('change',imported);drawer.removeEventListener('close',closed);drawer.removeEventListener('cancel',cancelled);drawer.removeEventListener('click',backdrop);if(drawer.open)drawer.close();root.remove();}}; }