import { useEffect, useMemo, useRef, useState } from 'react'; import type { ReactNode } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import type { DocumentField, DocumentTemplate } from '@cra-compliance/types'; import { OPEN_TEMPLATE_KEY } from '../App'; import { wpApiFetch, useConfig, errorMessage } from '../hooks/useApi'; import { useNotify } from '../hooks/useNotify'; import { useDocuments } from '../hooks/useDocuments'; import type { SavedDocument } from '../hooks/useDocuments'; import { APPLIES_NOW_TEMPLATES, TEMPLATES, findTemplate, summary } from '../content/templates'; import { copyText, downloadText, slugify } from '../lib/files'; import { buildCycloneDx } from '../lib/cyclonedx'; import { dateOnly, fromMysqlUtc } from '../lib/format'; import { Cite, ErrorState, Mark, PageHead, Panel, Skel } from '../components/ui'; const START = '\u0000'; const END = '\u0001'; function today(): string { return new Date().toLocaleDateString('en-GB', { year: 'numeric', month: 'long', day: 'numeric' }); } /** Fill the template. Empty fields become "[Label]", or marked tokens for the preview. */ function fill(template: DocumentTemplate, values: Record, markers = false): string { const labels = new Map(template.fields.map((field) => [field.id, field.label])); return template.template_content.replace(/\{\{(\w+)\}\}/g, (_match, key: string) => { if (key === 'current_date') return values.current_date || today(); const value = (values[key] || '').trim(); if (value) return value; const label = labels.get(key) || key; return markers ? `${START}[${label}]${END}` : `[${label}]`; }); } function renderPreview(text: string): ReactNode[] { const parts: ReactNode[] = []; const pattern = new RegExp(`${START}(.*?)${END}`, 'g'); let last = 0; let match: RegExpExecArray | null; let key = 0; while ((match = pattern.exec(text)) !== null) { if (match.index > last) parts.push(text.slice(last, match.index)); parts.push({match[1]}); last = match.index + match[0].length; } if (last < text.length) parts.push(text.slice(last)); return parts; } function takeRequestedTemplate(): DocumentTemplate | undefined { try { const id = window.sessionStorage.getItem(OPEN_TEMPLATE_KEY); window.sessionStorage.removeItem(OPEN_TEMPLATE_KEY); return findTemplate(id); } catch { return undefined; } } export function Documents() { const [active, setActive] = useState<{ template: DocumentTemplate; values?: Record } | null>(() => { const requested = takeRequestedTemplate(); return requested ? { template: requested } : null; }); useEffect(() => { window.scrollTo(0, 0); }, [active]); if (active) { return ( setActive(null)} /> ); } return setActive({ template, values })} />; } function Library({ onOpen }: { onOpen: (template: DocumentTemplate, values?: Record) => void }) { const documents = useDocuments(); const queryClient = useQueryClient(); const { confirm, toast, NotifyPortal } = useNotify(); const saved = documents.data ?? []; const savedTemplateIds = new Set(saved.map((doc) => doc.template_id)); const remove = async (doc: SavedDocument) => { const ok = await confirm({ title: 'Delete this document?', message: `"${doc.title}" will be removed from this site. Copies you downloaded are not affected.`, confirmLabel: 'Delete', danger: true, }); if (!ok) return; try { await wpApiFetch(`documents/${doc.id}`, { method: 'DELETE' }); queryClient.setQueryData(['documents'], (current) => (current ?? []).filter((d) => d.id !== doc.id)); toast({ message: 'Document deleted.' }); } catch (error) { toast({ message: errorMessage(error, 'The document could not be deleted.'), type: 'error' }); } }; const edit = (doc: SavedDocument) => { const template = findTemplate(doc.template_id); if (!template) { toast({ message: 'This template is no longer available. Download the saved text instead.', type: 'error' }); return; } let values: Record | undefined; try { const parsed = JSON.parse(doc.field_values || '{}'); values = parsed && typeof parsed === 'object' ? parsed : undefined; } catch { values = undefined; } onOpen(template, values); }; const copy = async (doc: SavedDocument) => { const ok = await copyText(doc.content); toast({ message: ok ? 'Copied to the clipboard.' : 'Copying is blocked in this browser. Use Download instead.', type: ok ? 'info' : 'error' }); }; return (
{documents.isLoading && (
{[0, 1].map((i) => )}
)} {documents.isError && ( void documents.refetch()} /> )} {saved.length > 0 && (
{saved.map((doc) => ( ))}
Document Saved Actions
{findTemplate(doc.template_id)?.title ?? doc.title} {dateOnly(fromMysqlUtc(doc.created_at))}
)}

Templates

{TEMPLATES.length} templates
    {TEMPLATES.map((template) => (
  • ))}
{!documents.isLoading && !documents.isError && saved.length === 0 && (

Nothing saved yet. Documents you save appear above the templates.

)}
); } function Generator({ template, initialValues, onClose }: { template: DocumentTemplate; initialValues?: Record; onClose: () => void; }) { const config = useConfig(); const queryClient = useQueryClient(); const { toast, NotifyPortal } = useNotify(); const [values, setValues] = useState>(() => { const base: Record = {}; template.fields.forEach((field) => { base[field.id] = ''; }); return { ...base, ...(initialValues ?? {}), current_date: initialValues?.current_date || today() }; }); const [errors, setErrors] = useState>({}); const [saving, setSaving] = useState(false); const formRef = useRef(null); const text = useMemo(() => fill(template, values), [template, values]); const preview = useMemo(() => renderPreview(fill(template, values, true)), [template, values]); const missing = template.fields.filter((field) => field.required && !(values[field.id] || '').trim()).length; const isSecurityTxt = template.id === 'security-txt'; const validate = (): boolean => { const next: Record = {}; for (const field of template.fields) { const value = (values[field.id] || '').trim(); if (field.required && !value) { next[field.id] = 'Required.'; continue; } if (!value) continue; if (field.type === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) { next[field.id] = 'Enter an email address, such as security@example.com.'; } if (field.type === 'url') { try { const url = new URL(value); if (!/^https?:$/.test(url.protocol)) next[field.id] = 'Use an address that starts with https://.'; } catch { next[field.id] = 'Enter a full address, such as https://example.com.'; } } } setErrors(next); const first = Object.keys(next)[0]; if (first) { formRef.current?.querySelector(`[name="${first}"]`)?.focus(); } return !first; }; const save = async () => { if (!validate()) { toast({ message: 'Fill in the required fields before saving.', type: 'error' }); return; } setSaving(true); try { const res = await wpApiFetch<{ data: SavedDocument }>('documents', { method: 'POST', body: JSON.stringify({ template_id: template.id, title: template.title, content: text, field_values: JSON.stringify(values), }), }); queryClient.setQueryData(['documents'], (current) => [res.data, ...(current ?? [])]); void queryClient.invalidateQueries({ queryKey: ['documents'] }); toast({ message: `${template.title} saved.` }); onClose(); } catch (error) { toast({ message: errorMessage(error, 'The document could not be saved.'), type: 'error' }); } finally { setSaving(false); } }; const copy = async () => { const ok = await copyText(text); toast({ message: ok ? 'Copied to the clipboard.' : 'Copying is blocked in this browser. Use Download instead.', type: ok ? 'info' : 'error' }); }; const setField = (id: string, value: string) => { setValues((current) => ({ ...current, [id]: value })); if (errors[id]) { setErrors((current) => { const next = { ...current }; delete next[id]; return next; }); } }; return (
{template.cra_articles.map((a) => {a})}
} />
0 ? `${missing} required ${missing === 1 ? 'field is' : 'fields are'} still empty.` : 'All required fields are filled in.'} >
{ event.preventDefault(); void save(); }} > {template.fields.map((field) => ( setField(field.id, value)} /> ))}
{isSecurityTxt ? ( ) : ( <> )} {template.id === 'sbom' && ( )}

A template is a starting point. Check the result against your product before you publish or sign it.

Preview

Highlighted text is still a placeholder.

{preview}
); } function Field({ field, value, error, onChange }: { field: DocumentField; value: string; error?: string; onChange: (value: string) => void; }) { const id = `rwp-field-${field.id}`; const errorId = `${id}-error`; const common = { id, name: field.id, className: 'rwp-input', value, 'aria-invalid': error ? true : undefined, 'aria-describedby': error ? errorId : undefined, 'aria-required': field.required || undefined, }; let control: ReactNode; if (field.type === 'textarea') { control =