385 lines
15 KiB
TypeScript
385 lines
15 KiB
TypeScript
import { useEffect, useId, useRef, useState } from 'react';
|
|
import {
|
|
formFieldGuidance,
|
|
formHelpPlacement,
|
|
readFormHelpAutomatic,
|
|
simulationStepGuidance,
|
|
} from '@/lib/form-help';
|
|
import {
|
|
formHelpControls,
|
|
formHelpGroupControls,
|
|
formHelpControlSelector,
|
|
formHelpControlVisible,
|
|
formHelpField,
|
|
formHelpStep,
|
|
} from '@/lib/form-help-dom';
|
|
|
|
const preferenceKey = 'investemoz:form-field-help:v1';
|
|
const button =
|
|
'min-h-11 rounded-lg border px-3 py-2 text-sm font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700';
|
|
type Step = { title: string; code: string; context: string };
|
|
|
|
/** Read-only assistance: observes labels and structure, never form values or submissions. */
|
|
export default function FormFieldHelp() {
|
|
const [control, setControl] = useState<HTMLElement | null>(null);
|
|
const [step, setStep] = useState<Step | null>(null);
|
|
const [available, setAvailable] = useState(false);
|
|
const [open, setOpen] = useState(false);
|
|
const [automatic, setAutomatic] = useState(true);
|
|
const [position, setPosition] = useState<'left' | 'right'>('right');
|
|
const [vertical, setVertical] = useState<'top' | 'bottom'>('bottom');
|
|
const [panelHeight, setPanelHeight] = useState<number | undefined>();
|
|
const automaticRef = useRef(true);
|
|
const paused = useRef(false);
|
|
const current = useRef<HTMLElement | null>(null);
|
|
const root = useRef<HTMLElement>(null);
|
|
const id = useId();
|
|
|
|
useEffect(() => {
|
|
try {
|
|
automaticRef.current = readFormHelpAutomatic(
|
|
localStorage.getItem(preferenceKey),
|
|
);
|
|
} catch {
|
|
/* Optional preference. */
|
|
}
|
|
setAutomatic(automaticRef.current);
|
|
let frame = 0;
|
|
let lastExplicitStep = '';
|
|
let lastDescription = '';
|
|
let page = location.pathname;
|
|
function place(target: HTMLElement) {
|
|
const layout = formHelpPlacement(
|
|
target.getBoundingClientRect(),
|
|
innerWidth,
|
|
innerHeight,
|
|
);
|
|
setPosition(layout.side);
|
|
setVertical(layout.vertical);
|
|
setPanelHeight(layout.maxHeight);
|
|
}
|
|
function select(target: HTMLElement, show: boolean) {
|
|
current.current = target;
|
|
setControl(target);
|
|
setStep(formHelpStep(target));
|
|
place(target);
|
|
if (show) setOpen(true);
|
|
}
|
|
function scan() {
|
|
frame = 0;
|
|
if (page !== location.pathname) {
|
|
page = location.pathname;
|
|
current.current = null;
|
|
paused.current = false;
|
|
lastExplicitStep = '';
|
|
setOpen(false);
|
|
}
|
|
const controls = formHelpControls(document);
|
|
const explicit = document.querySelector<HTMLElement>(
|
|
'[data-form-help-context="simulator"]',
|
|
);
|
|
setAvailable(Boolean(controls.length || explicit));
|
|
const signature = explicit
|
|
? `${page}:${explicit.dataset.formHelpStep}`
|
|
: '';
|
|
if (signature && signature !== lastExplicitStep) {
|
|
lastExplicitStep = signature;
|
|
const first = controls.find((node) => explicit?.contains(node));
|
|
current.current = first ?? null;
|
|
setControl(first ?? null);
|
|
setStep({
|
|
title:
|
|
explicit?.dataset.formHelpTitle ??
|
|
'Preencher este passo',
|
|
code: explicit?.dataset.formHelpStep ?? '',
|
|
context: 'simulator',
|
|
});
|
|
if (automaticRef.current && !paused.current) setOpen(true);
|
|
} else if (
|
|
current.current &&
|
|
!formHelpControlVisible(current.current)
|
|
) {
|
|
current.current = null;
|
|
setControl(null);
|
|
setOpen(false);
|
|
} else if (!current.current && controls[0] && !explicit) {
|
|
select(controls[0], false);
|
|
}
|
|
if (current.current && formHelpControlVisible(current.current)) {
|
|
place(current.current);
|
|
const description = JSON.stringify([
|
|
formHelpField(current.current),
|
|
formHelpStep(current.current),
|
|
]);
|
|
if (description !== lastDescription) {
|
|
lastDescription = description;
|
|
setStep(formHelpStep(current.current));
|
|
}
|
|
}
|
|
}
|
|
const schedule = () => {
|
|
if (!frame) frame = requestAnimationFrame(scan);
|
|
};
|
|
function focus(event: Event) {
|
|
if (
|
|
!(event.target instanceof Element) ||
|
|
event.target.closest('[data-form-field-help]')
|
|
)
|
|
return;
|
|
const target = event.target.closest<HTMLElement>(
|
|
formHelpControlSelector,
|
|
);
|
|
if (
|
|
target &&
|
|
target.closest('main,[role="main"],[role="dialog"]') &&
|
|
formHelpControlVisible(target)
|
|
)
|
|
select(target, automaticRef.current && !paused.current);
|
|
}
|
|
function click(event: Event) {
|
|
if (!(event.target instanceof Element)) return;
|
|
const trigger = event.target.closest<HTMLElement>(
|
|
'[data-form-help-open]',
|
|
);
|
|
if (!trigger) return;
|
|
paused.current = false;
|
|
const scope = trigger.closest<HTMLElement>(
|
|
'[data-form-help-context]',
|
|
);
|
|
if (scope) {
|
|
current.current = null;
|
|
setControl(null);
|
|
setStep({
|
|
title:
|
|
scope.dataset.formHelpTitle ?? 'Preencher este passo',
|
|
code: scope.dataset.formHelpStep ?? '',
|
|
context: scope.dataset.formHelpContext ?? '',
|
|
});
|
|
}
|
|
setOpen(true);
|
|
requestAnimationFrame(() =>
|
|
root.current
|
|
?.querySelector<HTMLElement>('[data-form-help-panel]')
|
|
?.focus({ preventScroll: true }),
|
|
);
|
|
}
|
|
const observer = new MutationObserver((records) => {
|
|
if (
|
|
records.some(
|
|
(record) =>
|
|
!(
|
|
record.target instanceof Element
|
|
? record.target
|
|
: record.target.parentElement
|
|
)?.closest('[data-form-field-help]'),
|
|
)
|
|
)
|
|
schedule();
|
|
});
|
|
observer.observe(document.body, {
|
|
childList: true,
|
|
characterData: true,
|
|
subtree: true,
|
|
attributes: true,
|
|
attributeFilter: [
|
|
'hidden',
|
|
'disabled',
|
|
'readonly',
|
|
'aria-hidden',
|
|
'aria-disabled',
|
|
'required',
|
|
'aria-required',
|
|
'aria-label',
|
|
'aria-labelledby',
|
|
'aria-describedby',
|
|
'placeholder',
|
|
'class',
|
|
'style',
|
|
'data-form-help-step',
|
|
'data-form-help-title',
|
|
],
|
|
});
|
|
document.addEventListener('focusin', focus);
|
|
document.addEventListener('click', click);
|
|
document.addEventListener('toggle', schedule, true);
|
|
window.addEventListener('resize', schedule);
|
|
const scroll = () => {
|
|
if (current.current) place(current.current);
|
|
};
|
|
window.addEventListener('scroll', scroll, { passive: true });
|
|
scan();
|
|
return () => {
|
|
observer.disconnect();
|
|
if (frame) cancelAnimationFrame(frame);
|
|
document.removeEventListener('focusin', focus);
|
|
document.removeEventListener('click', click);
|
|
document.removeEventListener('toggle', schedule, true);
|
|
window.removeEventListener('resize', schedule);
|
|
window.removeEventListener('scroll', scroll);
|
|
};
|
|
}, []);
|
|
|
|
if (!available) return null;
|
|
const field = control ? formHelpField(control) : null;
|
|
const guidance = field ? formFieldGuidance(field) : null;
|
|
function close() {
|
|
paused.current = true;
|
|
setOpen(false);
|
|
root.current
|
|
?.querySelector<HTMLButtonElement>('[data-form-help-toggle]')
|
|
?.focus({ preventScroll: true });
|
|
}
|
|
function move(direction: number) {
|
|
const fields = formHelpGroupControls(document, control);
|
|
const index = control ? fields.indexOf(control) : -1;
|
|
const target = fields[index + direction];
|
|
if (!target) return;
|
|
paused.current = false;
|
|
target.focus({ preventScroll: true });
|
|
target.scrollIntoView({ block: 'center', behavior: 'auto' });
|
|
current.current = target;
|
|
setControl(target);
|
|
setStep(formHelpStep(target));
|
|
}
|
|
const fields = formHelpGroupControls(document, control);
|
|
const index = control ? fields.indexOf(control) : -1;
|
|
return (
|
|
<aside
|
|
ref={root}
|
|
data-form-field-help
|
|
aria-label="Ajuda ao preenchimento"
|
|
className={`fixed z-40 max-w-[calc(100%-1.5rem)] text-slate-900 ${vertical === 'top' ? 'top-20' : 'bottom-3'} ${position === 'left' ? 'left-3' : 'right-3'}`}
|
|
onKeyDown={(event) => {
|
|
if (event.key === 'Escape' && open) {
|
|
event.preventDefault();
|
|
close();
|
|
}
|
|
}}
|
|
>
|
|
{open && (
|
|
<section
|
|
id={id}
|
|
data-form-help-panel
|
|
tabIndex={-1}
|
|
aria-labelledby={`${id}-title`}
|
|
style={{ maxHeight: panelHeight }}
|
|
className="mb-2 max-h-[45dvh] w-96 max-w-full space-y-3 overflow-y-auto rounded-xl border-2 border-emerald-700 bg-white p-4 shadow-xl focus-visible:outline-2"
|
|
>
|
|
<div className="flex items-start justify-between gap-3">
|
|
<h2 id={`${id}-title`} className="font-semibold">
|
|
{step?.title ?? 'Ajuda neste passo'}
|
|
</h2>
|
|
<button
|
|
type="button"
|
|
className={button}
|
|
onClick={close}
|
|
>
|
|
Fechar ajuda
|
|
</button>
|
|
</div>
|
|
{step?.context === 'simulator' && (
|
|
<p className="text-sm">
|
|
{simulationStepGuidance(step.code)}
|
|
</p>
|
|
)}
|
|
{field && guidance ? (
|
|
<div className="space-y-2 rounded-lg bg-emerald-50 p-3 text-sm">
|
|
<h3 className="font-semibold">{field.label}</h3>
|
|
<p>
|
|
<strong>O que preencher:</strong>{' '}
|
|
{guidance.instruction}
|
|
</p>
|
|
{guidance.example && (
|
|
<p>
|
|
<strong>Exemplo:</strong> {guidance.example}
|
|
</p>
|
|
)}
|
|
{field.required && (
|
|
<p>
|
|
Este campo está assinalado como obrigatório
|
|
no formulário.
|
|
</p>
|
|
)}
|
|
{field.hint && (
|
|
<p>
|
|
<strong>Indicação do formulário:</strong>{' '}
|
|
{field.hint}
|
|
</p>
|
|
)}
|
|
</div>
|
|
) : (
|
|
<p className="text-sm">
|
|
Seleccione um campo do formulário para consultar a
|
|
sua orientação.
|
|
</p>
|
|
)}
|
|
<div className="flex flex-wrap gap-2">
|
|
<button
|
|
type="button"
|
|
className={button}
|
|
disabled={index <= 0}
|
|
onClick={() => move(-1)}
|
|
>
|
|
Campo anterior
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className={button}
|
|
disabled={
|
|
!fields.length || index >= fields.length - 1
|
|
}
|
|
onClick={() => move(1)}
|
|
>
|
|
{index < 0
|
|
? 'Ver primeiro campo'
|
|
: 'Campo seguinte'}
|
|
</button>
|
|
</div>
|
|
<label className="flex min-h-11 items-center gap-2 text-sm">
|
|
<input
|
|
type="checkbox"
|
|
checked={automatic}
|
|
onChange={(event) => {
|
|
const enabled = event.target.checked;
|
|
setAutomatic(enabled);
|
|
automaticRef.current = enabled;
|
|
paused.current = !enabled;
|
|
try {
|
|
localStorage.setItem(
|
|
preferenceKey,
|
|
enabled ? 'on' : 'off',
|
|
);
|
|
} catch {
|
|
/* Optional preference. */
|
|
}
|
|
}}
|
|
/>
|
|
Orientações automáticas neste navegador
|
|
</label>
|
|
</section>
|
|
)}
|
|
<button
|
|
type="button"
|
|
data-form-help-toggle
|
|
aria-expanded={open}
|
|
aria-controls={id}
|
|
className={`${button} max-w-full border-emerald-800 bg-emerald-800 text-white shadow-lg`}
|
|
onClick={() => {
|
|
if (open) close();
|
|
else {
|
|
paused.current = false;
|
|
setOpen(true);
|
|
}
|
|
}}
|
|
>
|
|
<span aria-hidden="true">❔</span> Ajuda neste passo
|
|
{field && (
|
|
<span className="ml-2 hidden max-w-48 truncate align-bottom font-normal sm:inline">
|
|
· {field.label}
|
|
</span>
|
|
)}
|
|
</button>
|
|
</aside>
|
|
);
|
|
}
|