// @requirements REQ-PRODUCT-MARKETING-AUTHORING REQ-PRODUCT-A11Y REQ-PRODUCT-MOBILE import {normalizeMarketingWorkbenchContext,normalizeMarketingRequestSettings,assembleMarketingRequestContent,formatMarketingRequestSettings,marketingWorkbenchHandoff} from './marketing-workbench.js'; import {createFormPermissionPresentation} from './form-permission-presentation.js'; import {isSafeLink} from './config.js'; import {formPermissionGrantSupported} from './form-permission.js'; import {parseConfigSource,configSourceFormat} from './config-document.js'; import type {MarketingRequestSettings} from './marketing-workbench.js'; export interface MountedMarketingWorkbench {getSettings():MarketingRequestSettings;destroy():void} /** One public request draft. No identity, controller, recipient data, persistence or recording transport. */ export function mountMarketingWorkbench(container:HTMLElement,options:{context:unknown}):MountedMarketingWorkbench { const context=normalizeMarketingWorkbenchContext(options.context),doc=container.ownerDocument,view=doc.defaultView;if(!view)throw Error('Use a browser document.');const browser=view; const id='nb-marketing-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 nb-marketing-workbench';root.lang='en';root.dir='ltr'; const release=node('section');release.className='nb-pw-release';release.append(node('p','01 / Policy and purpose'),node('h2',context.facts.document.title),node('p','Version '+context.facts.document.version+' · '+context.facts.document.effectiveDate+' · '+context.locale+' · '+(context.facts.mode==='preview'?'Preview release':'Production release'))); const refs=node('details');refs.append(node('summary','Release and purpose references'),node('code',context.facts.artifactId),node('p',context.facts.facts.purpose.id+' · '+context.facts.facts.purpose.description),node('p','This editor uses public facts from your build. Final compilation verifies the intact artifact again.'));release.append(refs); 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 and purpose; 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 / Request and choice'),node('h2','What are you asking for?'),node('p','One purpose and future contact method per request. Other methods need separate stable permissions. Review whether you may approach the person before using this request.')); const fields=new Map(),errors=new Map(),limits=new Map(); function field(key:string,label:string,max:number,multiline=false,optional=false){const wrap=node('div'),labelEl=node('label',label),input=multiline?node('textarea'):node('input');wrap.className='nb-pw-field'+(multiline?' nb-mw-wide':'');input.id=id+'-'+key.replaceAll('.','-');labelEl.htmlFor=input.id;input.maxLength=max;input.required=!optional;input.lang=['permissionId','revision','withdrawalUrl','deliveryWindowSeconds'].includes(key)?'en':context.locale;input.dir=['permissionId','revision','withdrawalUrl','deliveryWindowSeconds'].includes(key)?'ltr':context.facts.localization?.direction??'ltr';if(multiline)(input as HTMLTextAreaElement).rows=3;else(input as HTMLInputElement).type='text';fields.set(key,input);limits.set(key,max);const error=node('p');error.id=input.id+'-error';error.className='nb-pw-field-error';error.hidden=true;input.setAttribute('aria-describedby',error.id);errors.set(key,error);wrap.append(labelEl,input,error);return wrap;} const request=node('div');request.className='nb-mw-fields';request.append(field('goodsServices','Products or services to be marketed',2000,true)); const methodWrap=node('div');methodWrap.className='nb-pw-field';const methodLabel=node('label','Future contact method'),method=node('select');method.id=id+'-method';methodLabel.htmlFor=method.id;for(const [value,label] of [['','Choose a method'],['email','Email'],['sms','SMS'],['whatsapp','WhatsApp']]){const option=node('option',label);option.value=value!;method.append(option);}const methodError=node('p');methodError.id=method.id+'-error';methodError.hidden=true;methodError.className='nb-pw-field-error';method.setAttribute('aria-describedby',methodError.id);methodWrap.append(methodLabel,method,methodError);request.append(methodWrap,field('methodLabel','Method name in the request’s language',120));editor.append(request,node('p','This web form collects the choice. The selected method describes future marketing; it does not send a message.')); const wording=node('div');wording.className='nb-mw-fields';wording.append(field('title','Permission heading',300),field('statement','Permission statement',2000,true),field('optionality','Explain that the choice is optional',2000,true),field('withdrawalExplanation','How to withdraw',2000,true),field('grantLabel','Save permission button',120),field('withdrawLabel','Withdrawal button',120));editor.append(wording); function group(title:string){const d=node('details');d.className='nb-mw-group';d.append(node('summary',title));const body=node('div');body.className='nb-mw-fields';d.append(body);editor.append(d);return body;} const labels=group('Request section headings');labels.append(field('labelGoods','Heading above products/services',120),field('labelMethod','Heading above the contact method',120),field('labelParty','Heading above responsible-party details',120));labels.append(node('p','The responsible-party name, address and email come from the selected release. Correct those facts in the inventory and rebuild; do not override them in this request.')); const refusal=group('Refusal and confirmation copy');refusal.append(field('refusalLabel','Refusal button',120),field('refusalRecorded','Recorded refusal message',2000,true),field('refusalPending','Unconfirmed refusal message',2000,true),field('refusalRetry','Retry refusal button',120));refusal.append(node('p','Refusal is required in this profile. An unchecked box or ordinary form submission records nothing. These messages are editable copy, not a recording connection.')); const advanced=group('Identifiers, withdrawal route and delivery window');advanced.append(field('permissionId','Stable permission ID',120),field('revision','Request wording revision',200),field('withdrawalUrl','Withdrawal help URL',2048),field('deliveryWindowSeconds','Pending-command window in seconds (optional)',4,false,true));advanced.append(node('p','Use 30–3600 whole seconds, or leave blank for the builder’s 600-second default. This limits pending delivery, not permission lifetime. A changed method needs another stable permission. Material wording changes need a new revision; neither resets invitation or withholding history.')); const wordingReviewLabel=node('label','Request wording review'),wordingReview=node('select');wordingReview.id=id+'-wording-review';wordingReviewLabel.htmlFor=wordingReview.id;for(const [value,label] of [['draft','Draft — needs review'],['reviewed','Reviewed wording']]){const option=node('option',label);option.value=value!;wordingReview.append(option);}editor.append(wordingReviewLabel,wordingReview,node('p','This declaration concerns your request wording. It does not establish eligibility to ask or legal sufficiency.')); const preview=node('aside');preview.className='nb-pw-preview';preview.setAttribute('aria-label','Marketing request preview');preview.append(node('p','03 / Preview'),node('h2','Read it as a visitor'),node('p','The choice and links are inactive. This preview creates no permission, refusal, receipt or invitation history.'));const previewButton=node('button','Preview request');previewButton.type='button';preview.append(previewButton);const paper=node('div');paper.className='nb-pw-paper';paper.append(node('p','Write the request and choice, then preview them together.'));preview.append(paper);layout.append(editor,preview);root.append(layout); const scope=node('p','Scope assessments come from the release, not from this editor. They do not establish whether you may approach this person.');scope.className='nb-mw-scope';if(!formPermissionGrantSupported({facts:context.facts.facts}))scope.textContent+=' This release keeps grants blocked for the selected purpose; negative actions remain available in the connected mechanism.';root.append(scope); const actions=node('div');actions.className='nb-pw-actions';const releaseLabel=node('label'),releaseConfirmed=node('input');releaseConfirmed.type='checkbox';releaseConfirmed.dataset.marketingRelease='';releaseLabel.append(releaseConfirmed,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(releaseLabel,exportButton);root.append(actions); const status=node('p');status.className='nb-pw-status';status.setAttribute('role','status');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,label] of [['yaml','YAML'],['json','JSON'],['markdown','Markdown frontmatter']]){const option=node('option',label);option.value=value!;format.append(option);}const output=node('textarea');output.readOnly=true;output.rows=16;output.setAttribute('aria-label','Marketing request build settings');const copy=node('button','Copy settings');copy.type='button';const download=node('a','Download settings');const handoff=node('p'),drawerStatus=node('p');drawerStatus.setAttribute('role','status');drawer.append(close,title,node('p','Save and compile these settings against the exact final artifact. The editor exports no authoritative offer or review finding.'),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; 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(resetWording=true){revision++;importToken++;file.value='';for(const [key,e] of errors){e.hidden=true;e.textContent='';fields.get(key)!.removeAttribute('aria-invalid');}methodError.hidden=true;method.removeAttribute('aria-invalid');clearOutput();releaseConfirmed.checked=false;if(resetWording)wordingReview.value='draft';paper.replaceChildren(node('p','Settings changed. Preview again to read the current request.'));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===releaseConfirmed){if(!releaseConfirmed.checked){revision++;clearOutput();closeDrawer();}return;}invalidate(event.target!==wordingReview);};root.addEventListener('input',changed);root.addEventListener('change',changed); const value=(key:string)=>fields.get(key)!.value; function draft(){if(destroyed)throw Error('This editor has closed.');return normalizeMarketingRequestSettings({schemaVersion:1,reviewedArtifactId:context.facts.artifactId,permission:{purposeId:context.facts.facts.purpose.id,permissionId:value('permissionId'),revision:value('revision'),reviewStatus:wordingReview.value,methodLabel:value('methodLabel'),marketingRequest:{profile:'za-popia-web-request',version:1,goodsServices:value('goodsServices'),method:method.value,labels:{goodsServices:value('labelGoods'),method:value('labelMethod'),responsibleParty:value('labelParty')}},refusal:{label:value('refusalLabel'),recorded:value('refusalRecorded'),pending:value('refusalPending'),retry:value('refusalRetry')},wording:{title:value('title'),statement:value('statement'),grantLabel:value('grantLabel'),withdrawLabel:value('withdrawLabel'),optionality:value('optionality'),withdrawalExplanation:value('withdrawalExplanation')},withdrawalUrl:value('withdrawalUrl'),...(value('deliveryWindowSeconds')?{deliveryWindowSeconds:Number(value('deliveryWindowSeconds'))}:{})}});} function settings(){if(!releaseConfirmed.checked)throw Error('Select the exact release before exporting.');const s=draft();assembleMarketingRequestContent(context.facts,s);return s;} function populate(s:MarketingRequestSettings){const p=s.permission,values={...p.wording,permissionId:p.permissionId,revision:p.revision,withdrawalUrl:p.withdrawalUrl,methodLabel:p.methodLabel,goodsServices:p.marketingRequest.goodsServices,labelGoods:p.marketingRequest.labels.goodsServices,labelMethod:p.marketingRequest.labels.method,labelParty:p.marketingRequest.labels.responsibleParty,refusalLabel:p.refusal.label,refusalRecorded:p.refusal.recorded,refusalPending:p.refusal.pending,refusalRetry:p.refusal.retry,deliveryWindowSeconds:p.deliveryWindowSeconds===undefined?'':String(p.deliveryWindowSeconds)};for(const [key,input] of fields)input.value=values[key as keyof typeof values];method.value=p.marketingRequest.method;wordingReview.value=p.reviewStatus;releaseConfirmed.checked=false;} function focusError(el:HTMLElement){for(let parent=el.parentElement;parent&&parent!==root;parent=parent.parentElement)if(parent instanceof browser.HTMLDetailsElement)parent.open=true;el.focus();} function validateEditor(){let first:HTMLElement|undefined; for(const [key,input] of fields){const v=input.value,max=limits.get(key)!,invalid=key==='deliveryWindowSeconds'?!!v&&(!/^[0-9]+$/u.test(v)||Number(v)<30||Number(v)>3600):!v.trim()||new TextEncoder().encode(v).length>max||/[\u0000-\u001f\u007f]/u.test(v)||key==='permissionId'&&!/^[a-z][a-z0-9-]{0,119}$/u.test(v)||key==='withdrawalUrl'&&!isSafeLink(v);const e=errors.get(key)!;e.hidden=!invalid;if(invalid){e.textContent=key==='deliveryWindowSeconds'?'Use 30–3600 whole seconds, or leave blank.':key==='permissionId'?'Use 1–120 lowercase letters, digits or hyphens, starting with a letter.':key==='withdrawalUrl'?'Use a safe HTTPS, local-path or email withdrawal-help link.':'Enter this field within its '+max+' UTF-8-byte limit, without control characters.';input.setAttribute('aria-invalid','true');first??=input;}else{e.textContent='';input.removeAttribute('aria-invalid');}} methodError.hidden=['email','sms','whatsapp'].includes(method.value);if(!methodError.hidden){methodError.textContent='Choose the future contact method explicitly.';method.setAttribute('aria-invalid','true');first??=method;}if(first){status.textContent='Review the highlighted fields before continuing.';focusError(first);return false;}return true; } const show=()=>{if(destroyed||!validateEditor())return;try{const content=assembleMarketingRequestContent(context.facts,draft());const presentation=createFormPermissionPresentation(doc,content,{disclosureKey:id+'-preview',inert:true,grantSupported:formPermissionGrantSupported(content)});presentation.root.lang=context.locale;presentation.root.dir=context.facts.localization?.direction??'ltr';paper.replaceChildren(presentation.root);status.textContent='Wording preview only. No choice was recorded.';}catch{status.textContent='Check the withdrawal URL, complete copy and selected method. The draft must match this release and purpose.';}};previewButton.addEventListener('click',show); async function renderOutput(){if(destroyed)return;const version=revision;clearOutput();const token=formatToken;drawerStatus.textContent='Preparing settings…';try{const s=settings(),text=await formatMarketingRequestSettings(s,format.value as 'yaml'|'json'|'markdown');if(destroyed||token!==formatToken||version!==revision||!drawer.open)return;output.value=text;handoff.textContent=marketingWorkbenchHandoff(format.value as 'yaml'|'json'|'markdown');const extension=format.value==='markdown'?'md':format.value;download.download='marketing-request.'+extension;url=browser.URL.createObjectURL(new Blob([text],{type:'text/plain;charset=utf-8'}));download.href=url;download.hidden=false;copy.disabled=false;drawerStatus.textContent='Settings only. No offer was published, registered or activated.';}catch{if(!destroyed&&token===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(!releaseConfirmed.checked){status.textContent='Select the exact release before exporting.';releaseConfirmed.focus();return;}try{settings();}catch{status.textContent='Review the request settings and withdrawal URL 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,text=output.value;if(!text||destroyed)return;try{if(!browser.navigator.clipboard?.writeText)throw Error();await browser.navigator.clipboard.writeText(text);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=(e:Event)=>{e.preventDefault();finished();};drawer.addEventListener('cancel',cancelled);const closed=()=>{if(!drawer.open){clearOutput();closeDrawer();}};drawer.addEventListener('close',closed);const backdrop=(e:MouseEvent)=>{const rect=drawer.getBoundingClientRect();if(e.target===drawer&&(e.clientXrect.right||e.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){file.value='';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=normalizeMarketingRequestSettings(parsed.config);assembleMarketingRequestContent(context.facts,s);if(destroyed||token!==importToken||version!==revision)return;invalidate(false);populate(s);file.value='';status.textContent='Settings loaded. Preview and select the exact release before exporting.';}catch{if(!destroyed&&token===importToken&&version===revision)status.textContent='Could not load these settings for this release and purpose. 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();}}; }