Add contextual filling help across forms and fiscal simulator steps
tests / ci (push) Waiting to run
tests / ci (push) Waiting to run
This commit is contained in:
@@ -10338,3 +10338,14 @@ Regressão final do candidato: 1 977 testes frontend aprovados após compilaçã
|
||||
## 17/11/2026 — GUIA-PASSO-20261117: correcção da abertura automática
|
||||
|
||||
Verificação autenticada online no dossier sintético db85f087-0737-4164-892a-4fa4fe1313df: os 19 botões de ajuda abriram/fecharam e o percurso Seguinte mostrou as 19 explicações completas. Identificado conflito entre focus/click do summary e o toggle nativo: uma etapa podia fechar-se depois da selecção automática da ajuda. Correcção limitada ao componente: ignorar summary em focus/click e observar o toggle nativo em captura depois da abertura. Fecho deliberado continua possível; o guia fechado permanece pausado. Regressão executa os handlers reais e confirma a sequência; ensaio do componente real no navegador confirmou fecho, reabertura e selecção de outra etapa. Tipos/lint focado aprovados. Sem alterações nos dados, estados, formulários ou permissões. Instalação pelo mesmo executor, com backup/restauro fresco; conferir recibo posterior e repetir as 19 etapas online antes da aceitação.
|
||||
|
||||
|
||||
## 17/11/2026 — AJUDA-FORMULARIOS-20261117: ajuda ao preenchimento transversal
|
||||
|
||||
Pedido expresso do proprietário: estender a ajuda ao simulador fiscal e aos restantes formulários. Implementação sobre c0d62d4e, mantendo o guia das 19 etapas e os formulários existentes. Componente comum montado uma vez em app.tsx, sem alterar/embrulhar os formulários nem os seus eventos de gravação. Detecta controlos nativos e ARIA editáveis dentro de main/dialog, acompanha o foco e apresenta Ajuda neste passo, instrução por campo, obrigatoriedade declarada pelo formulário, exemplos quando adequados e indicações já associadas via aria-describedby. Permite fechar, reabrir, consultar o campo anterior/seguinte do mesmo grupo e desligar a abertura automática neste navegador. Guarda apenas a preferência on/off; não lê valores, cria FormData, guarda dados nem faz pedidos de rede. Campos ocultos, desactivados, só de leitura e em details fechado ficam fora da sequência. Alterações de rótulo, indicação, estado e conteúdo são acompanhadas sem remontar os campos.
|
||||
|
||||
Simulador: metadados do passo adaptativo e botão junto ao título actual; instruções para intenção, identidade, mercado, localização, recursos, investimento/financiamento, operação fiscal, documentos, revisão e os restantes passos existentes. O catálogo de campos orienta NUIT, residência, moeda, períodos, volumes, receitas, custos, montantes, percentagens, documentos, fontes e contactos. Não cria taxas, regras, dispensas ou pagamentos; os cálculos, fontes e validações permanecem nos componentes existentes. Campos sem orientação específica usam o tipo/rótulo e as instruções já presentes; não se declara curadoria jurídica individual de todos os campos.
|
||||
|
||||
Inventário estático: 112 ficheiros com 160 declarações de formulário, incluindo componentes e páginas; não equivale a 160 demonstrações funcionais individuais. Cobertura comum por tipos/estrutura e botão contextual; origem em main/dialog permite também formulários dinâmicos e modais. Os formulários que não tenham controlos editáveis visíveis não apresentam navegação por campos. Recibo de cobertura: C:/Users/macbook/Documents/Codex/2026-11-17/no/outputs/ajuda-formularios-cobertura.json.
|
||||
|
||||
QA: seis testes novos (instruções fiscais/financeiras, tipos, percursos adaptativos, ausência de leitura de valores/transporte, preferência e posição móvel); regressão de 1 984 testes frontend aprovada. Lint focado, tipos e compilação QA aprovados; alterações posteriores de indicação/data revistas e testes focados repetidos. Navegador com componente real e dados sintéticos: passos, campo seguinte limitado ao grupo, campos ocultos/desactivados, e-mail, palavra-passe sem exposição do valor, checkbox ARIA com label for, ficheiro dinâmico, fecho/reabertura, preferência após recarregar, zero submissões e ecrã390px sem sobrepor o campo. Testes em StrictMode. A publicação segue o executor normal e terá recibo posterior. Backup/restauro fresco de 195 tabelas/417 ficheiros preparado em /var/backups/investmoz-form-help-20261117/backup; sem alterações de dados, schema, permissões, parâmetros fiscais ou executor. Mantidas as aprovações, limitações anteriores e os restantes critérios da matriz.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,6 +7,7 @@ import AppLayout from '@/layouts/app-layout';
|
||||
import AuthLayout from '@/layouts/auth-layout';
|
||||
import SettingsLayout from '@/layouts/settings/layout';
|
||||
import PortalNavigation from '@/layouts/portal-navigation';
|
||||
import FormFieldHelp from '@/components/form-field-help';
|
||||
|
||||
const appName = import.meta.env.VITE_APP_NAME || 'InvesteMoz';
|
||||
const pages = import.meta.glob<{ default: ComponentType }>('./pages/**/*.tsx');
|
||||
@@ -46,6 +47,7 @@ void createInertiaApp({
|
||||
return (
|
||||
<TooltipProvider delayDuration={0}>
|
||||
{app}
|
||||
<FormFieldHelp />
|
||||
<Toaster />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -2555,6 +2555,9 @@ export function SimulationForm() {
|
||||
return (
|
||||
<section
|
||||
className="space-y-6 rounded-xl border bg-white p-4 sm:p-6"
|
||||
data-form-help-context="simulator"
|
||||
data-form-help-step={current.id}
|
||||
data-form-help-title={current.title}
|
||||
aria-labelledby="simulator-step-title"
|
||||
aria-busy={!ready}
|
||||
>
|
||||
@@ -3295,6 +3298,13 @@ export function SimulationForm() {
|
||||
>
|
||||
{current.title}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
data-form-help-open
|
||||
className="inline-flex min-h-11 items-center gap-2 rounded-lg border border-emerald-700 px-3 py-2 text-sm font-semibold"
|
||||
>
|
||||
<span aria-hidden="true">❔</span> Ajuda neste passo
|
||||
</button>
|
||||
{current.id === 'review' && (
|
||||
<section
|
||||
className="rounded-lg border p-4"
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import type { HelpField } from './form-help';
|
||||
|
||||
export type HelpControl =
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLTextAreaElement
|
||||
| HTMLElement;
|
||||
export const formHelpControlSelector =
|
||||
'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]),select,textarea,[role="combobox"],[role="spinbutton"],[role="checkbox"],[role="radio"]';
|
||||
|
||||
function textWithoutControls(node: Element): string {
|
||||
const walker = node.ownerDocument.createTreeWalker(
|
||||
node,
|
||||
NodeFilter.SHOW_TEXT,
|
||||
);
|
||||
const parts: string[] = [];
|
||||
let text: Node | null;
|
||||
while ((text = walker.nextNode())) {
|
||||
if (
|
||||
!text.parentElement?.closest(
|
||||
'input,select,textarea,button,svg,[data-form-field-help]',
|
||||
)
|
||||
)
|
||||
parts.push(text.textContent ?? '');
|
||||
}
|
||||
return parts.join(' ').replace(/\s+/g, ' ').trim().slice(0, 220);
|
||||
}
|
||||
|
||||
export function formHelpControlVisible(control: HTMLElement): boolean {
|
||||
if (
|
||||
!control.isConnected ||
|
||||
control.closest(
|
||||
'[data-form-field-help],header,nav,[hidden],[inert],[aria-hidden="true"],details:not([open])',
|
||||
)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
control.matches(
|
||||
':disabled,[disabled],[aria-disabled="true"],[readonly]',
|
||||
)
|
||||
)
|
||||
return false;
|
||||
const style = control.ownerDocument.defaultView?.getComputedStyle(control);
|
||||
return (
|
||||
style?.display !== 'none' &&
|
||||
style?.visibility !== 'hidden' &&
|
||||
control.getClientRects().length > 0
|
||||
);
|
||||
}
|
||||
|
||||
export function formHelpControls(document: Document): HTMLElement[] {
|
||||
const roots = document.querySelectorAll(
|
||||
'main,[role="main"],[role="dialog"]',
|
||||
);
|
||||
return [
|
||||
...new Set(
|
||||
Array.from(roots).flatMap((root) =>
|
||||
Array.from(
|
||||
root.querySelectorAll<HTMLElement>(formHelpControlSelector),
|
||||
),
|
||||
),
|
||||
),
|
||||
].filter(formHelpControlVisible);
|
||||
}
|
||||
|
||||
export function formHelpGroupControls(
|
||||
document: Document,
|
||||
control: HTMLElement | null,
|
||||
): HTMLElement[] {
|
||||
const scope = control?.closest(
|
||||
'form,fieldset,[data-form-help-context],[role="dialog"]',
|
||||
);
|
||||
const controls = formHelpControls(document);
|
||||
return scope ? controls.filter((node) => scope.contains(node)) : controls;
|
||||
}
|
||||
|
||||
export function formHelpField(control: HTMLElement): HelpField {
|
||||
const document = control.ownerDocument;
|
||||
const labelledBy = (control.getAttribute('aria-labelledby') ?? '')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((node): node is HTMLElement => Boolean(node));
|
||||
const labels =
|
||||
'labels' in control
|
||||
? Array.from((control as HTMLInputElement).labels ?? [])
|
||||
: Array.from(document.querySelectorAll('label')).filter(
|
||||
(label) =>
|
||||
Boolean(control.id) && label.htmlFor === control.id,
|
||||
);
|
||||
const label =
|
||||
control.getAttribute('aria-label')?.trim() ||
|
||||
labelledBy.map(textWithoutControls).join(' ') ||
|
||||
labels.map(textWithoutControls).join(' ') ||
|
||||
textWithoutControls(
|
||||
control.closest('label') ?? document.createElement('span'),
|
||||
) ||
|
||||
control.getAttribute('placeholder') ||
|
||||
(control.getAttribute('name') ?? '')
|
||||
.replace(/[[\]_.-]+/g, ' ')
|
||||
.trim() ||
|
||||
'Campo deste formulário';
|
||||
const role = control.getAttribute('role');
|
||||
const type =
|
||||
role && ['combobox', 'checkbox', 'radio', 'spinbutton'].includes(role)
|
||||
? role === 'spinbutton'
|
||||
? 'number'
|
||||
: role
|
||||
: control.tagName === 'SELECT'
|
||||
? 'select'
|
||||
: control.tagName === 'TEXTAREA'
|
||||
? 'textarea'
|
||||
: (control.getAttribute('type') ?? 'text');
|
||||
const hint = (control.getAttribute('aria-describedby') ?? '')
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((node): node is HTMLElement => Boolean(node))
|
||||
.map(textWithoutControls)
|
||||
.join(' ')
|
||||
.slice(0, 450);
|
||||
return {
|
||||
label,
|
||||
type,
|
||||
required:
|
||||
control.hasAttribute('required') ||
|
||||
control.getAttribute('aria-required') === 'true',
|
||||
hint,
|
||||
context: control.closest<HTMLElement>('[data-form-help-context]')
|
||||
?.dataset.formHelpContext,
|
||||
};
|
||||
}
|
||||
|
||||
export function formHelpStep(control: HTMLElement): {
|
||||
title: string;
|
||||
code: string;
|
||||
context: string;
|
||||
} {
|
||||
const explicit = control.closest<HTMLElement>('[data-form-help-context]');
|
||||
if (explicit)
|
||||
return {
|
||||
title: explicit.dataset.formHelpTitle ?? 'Preencher este passo',
|
||||
code: explicit.dataset.formHelpStep ?? '',
|
||||
context: explicit.dataset.formHelpContext ?? '',
|
||||
};
|
||||
const investment = control.closest<HTMLElement>('[data-investment-step]');
|
||||
if (investment)
|
||||
return {
|
||||
title: (
|
||||
investment.querySelector(
|
||||
':scope > summary,:scope > h2,:scope > h3',
|
||||
)?.textContent ?? 'Preencher esta etapa'
|
||||
)
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim(),
|
||||
code: investment.dataset.investmentStep ?? '',
|
||||
context: 'investor-path',
|
||||
};
|
||||
const scope = control.closest('fieldset,section,form,[role="dialog"]');
|
||||
const titleId = scope?.getAttribute('aria-labelledby');
|
||||
const title =
|
||||
(titleId
|
||||
? control.ownerDocument.getElementById(titleId)?.textContent
|
||||
: undefined) ||
|
||||
scope?.getAttribute('aria-label') ||
|
||||
scope?.querySelector('legend,h2,h3,h4')?.textContent ||
|
||||
control.ownerDocument.querySelector('main h1')?.textContent ||
|
||||
'Preencher o formulário';
|
||||
return {
|
||||
title: title.replace(/\s+/g, ' ').trim().slice(0, 180),
|
||||
code: '',
|
||||
context: '',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
export type HelpField = {
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
hint?: string;
|
||||
context?: string;
|
||||
};
|
||||
|
||||
export function normaliseHelpLabel(value: string): string {
|
||||
return value
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export function formFieldGuidance(field: HelpField): {
|
||||
instruction: string;
|
||||
example?: string;
|
||||
} {
|
||||
const label = normaliseHelpLabel(field.label);
|
||||
if (field.type === 'password')
|
||||
return {
|
||||
instruction:
|
||||
'Introduza a palavra-passe desta conta. Use o controlo de mostrar palavra-passe apenas se precisar de conferir o que escreveu.',
|
||||
};
|
||||
if (field.type === 'file')
|
||||
return {
|
||||
instruction:
|
||||
'Escolha o ficheiro pedido neste campo. Confira o documento e os formatos indicados no formulário antes de o anexar.',
|
||||
};
|
||||
if (field.type === 'checkbox' || field.type === 'radio')
|
||||
return {
|
||||
instruction:
|
||||
'Leia a declaração ou opção apresentada. Seleccione-a apenas se corresponder à sua situação ou à autorização que pretende dar.',
|
||||
};
|
||||
if (/nuit/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Transcreva o NUIT da pessoa ou entidade a que este formulário se refere. Confira-o no documento correspondente.',
|
||||
};
|
||||
if (
|
||||
/email|e-mail|correio electronico/.test(label) ||
|
||||
field.type === 'email'
|
||||
)
|
||||
return {
|
||||
instruction:
|
||||
'Indique um endereço de correio electrónico ao qual tenha acesso.',
|
||||
example: 'nome@exemplo.co.mz',
|
||||
};
|
||||
if (
|
||||
/telefone|telemovel|contacto telefonico/.test(label) ||
|
||||
field.type === 'tel'
|
||||
)
|
||||
return {
|
||||
instruction:
|
||||
'Indique o número de contacto e confira o indicativo do país quando o formulário o pedir.',
|
||||
};
|
||||
if (/moeda|currency/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Escolha a moeda em que os montantes deste formulário estão expressos. Confira a coerência com os documentos e com os restantes valores.',
|
||||
};
|
||||
if (/residencia fiscal|regime fiscal|tipo de contribuinte/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Escolha o enquadramento que corresponde à pessoa ou entidade em análise. Consulte as indicações e fontes apresentadas no formulário se precisar de esclarecer a opção.',
|
||||
};
|
||||
if (/volume de negocios|volume de negocio|facturacao/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Indique o volume de negócios relativo ao período pedido, na moeda apresentada. Confira o período e a fonte do montante.',
|
||||
};
|
||||
if (/imposto.*liquidado|colecta/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Indique o montante identificado neste campo, a partir do apuramento ou documento correspondente. Confira o exercício e a referência apresentados.',
|
||||
};
|
||||
if (
|
||||
/retenc|montante.*pago|pagamento.*efectuado|pec.*pago|ppc.*pago/.test(
|
||||
label,
|
||||
)
|
||||
)
|
||||
return {
|
||||
instruction:
|
||||
'Introduza apenas o montante documentado a que este campo se refere e confira o período. Distinga os valores já registados das estimativas ou hipóteses de tesouraria.',
|
||||
};
|
||||
if (/taxa|percentagem|percentual/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Confira a unidade e o enquadramento indicados neste campo. Se for editável, introduza a percentagem correspondente ao pressuposto ou documento pedido; use os parâmetros apresentados pelo simulador quando forem fornecidos.',
|
||||
};
|
||||
if (/receita|vendas|rendimento/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Indique o valor relativo ao período e à unidade pedidos. Quando se tratar de uma previsão, use o seu pressuposto de receitas e conserve a respectiva referência.',
|
||||
};
|
||||
if (/custo|despesa|encargo/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Indique o custo ou despesa relativo ao período pedido. Confira se o campo pede valor unitário, mensal, anual ou total.',
|
||||
example:
|
||||
'Se o campo pedir um custo mensal, introduza o valor de um mês.',
|
||||
};
|
||||
if (
|
||||
/investimento|capital|financiamento|orcamento|montante|valor/.test(
|
||||
label,
|
||||
) &&
|
||||
field.type !== 'textarea'
|
||||
)
|
||||
return {
|
||||
instruction:
|
||||
'Indique o montante pedido, na moeda e unidade apresentadas. Distinga recursos disponíveis, necessidades de financiamento e valores previstos.',
|
||||
};
|
||||
if (
|
||||
/provincia|distrito|localidade|localizacao|territorio|posto administrativo/.test(
|
||||
label,
|
||||
)
|
||||
)
|
||||
return {
|
||||
instruction:
|
||||
'Escolha a localização correspondente ao investimento ou registo. Se existirem selecções dependentes, comece pela área mais abrangente e complete as opções seguintes.',
|
||||
};
|
||||
if (
|
||||
/exercicio|ano fiscal|periodo.*fiscal|inicio.*periodo|fim.*periodo/.test(
|
||||
label,
|
||||
)
|
||||
)
|
||||
return {
|
||||
instruction:
|
||||
'Indique a data ou o período a que a informação se refere. Confira a correspondência com os documentos e com os restantes campos deste exercício.',
|
||||
};
|
||||
if (['date', 'month', 'time', 'datetime-local'].includes(field.type))
|
||||
return {
|
||||
instruction:
|
||||
'Indique a data, o mês ou a hora pedidos neste campo, respeitando o formato apresentado. Confira a correspondência com o acontecimento ou prazo a que se refere.',
|
||||
};
|
||||
if (/referencia|fonte|fundamento/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Identifique o documento, a origem da informação ou o motivo pedido. Use uma referência que permita recuperar e conferir o que declarou.',
|
||||
};
|
||||
if (/titulo|designacao|nome do projecto|nome do investimento/.test(label))
|
||||
return {
|
||||
instruction:
|
||||
'Escreva uma designação clara que permita reconhecer este investimento ou registo.',
|
||||
example: 'Unidade de transformação de produtos agrícolas',
|
||||
};
|
||||
if (field.type === 'select' || field.type === 'combobox')
|
||||
return {
|
||||
instruction:
|
||||
'Escolha a opção que corresponde à sua situação. As opções disponíveis e as instruções do formulário orientam esta escolha.',
|
||||
};
|
||||
if (field.type === 'number' || field.type === 'range')
|
||||
return {
|
||||
instruction:
|
||||
'Introduza a quantidade ou o valor pedido e confira a unidade apresentada junto do campo. Respeite os limites indicados no formulário.',
|
||||
};
|
||||
if (field.type === 'url')
|
||||
return {
|
||||
instruction:
|
||||
'Introduza a ligação completa para a página ou documento pedido.',
|
||||
example: 'https://exemplo.co.mz/documento',
|
||||
};
|
||||
if (field.type === 'textarea')
|
||||
return {
|
||||
instruction:
|
||||
'Explique a informação pedida neste campo de forma clara e concreta. Inclua os elementos necessários para compreender a sua declaração.',
|
||||
};
|
||||
return {
|
||||
instruction: `Preencha «${field.label}» com a informação correspondente à pessoa, entidade ou investimento deste formulário. Confira as indicações junto do campo.`,
|
||||
};
|
||||
}
|
||||
|
||||
const simulationSteps: Record<string, string> = {
|
||||
purpose:
|
||||
'Indique o que pretende preparar, o nível de detalhe e o percurso adequado à sua situação. As respostas adaptam os passos seguintes.',
|
||||
promoter:
|
||||
'Identifique a situação do promotor e complete apenas os elementos pedidos para o perfil escolhido.',
|
||||
identity:
|
||||
'Confira a identificação e os contactos da pessoa ou entidade a que esta preparação se refere.',
|
||||
project:
|
||||
'Descreva o negócio, a actividade e os objectivos. Reutilize os dados já disponíveis e complete a informação em falta.',
|
||||
market: 'Descreva os clientes, o mercado e os pressupostos de vendas. Indique as fontes disponíveis para sustentar as suas estimativas.',
|
||||
location:
|
||||
'Indique a localização e os recursos relevantes para o investimento. Complete as escolhas territoriais apresentadas.',
|
||||
team: 'Descreva a equipa e a forma prevista de executar o investimento, incluindo as responsabilidades e recursos pedidos.',
|
||||
investment:
|
||||
'Organize o investimento inicial e confira a moeda, a unidade e os montantes previstos.',
|
||||
financial:
|
||||
'Complete os montantes e os pressupostos de investimento e financiamento pedidos. Confira a moeda e o período de cada valor.',
|
||||
operating:
|
||||
'Preencha as estimativas de receitas e custos, respeitando a unidade e o período de cada campo.',
|
||||
cashflow:
|
||||
'Distribua os pressupostos de tesouraria pelos períodos pedidos e compare os cenários apresentados.',
|
||||
tax: 'Seleccione a operação e o enquadramento fiscal. Confira o contribuinte, o período, a moeda, os valores e as referências pedidos antes de calcular.',
|
||||
impact: 'Indique os postos de trabalho e os impactos previstos, distinguindo estimativas de informação já documentada.',
|
||||
opportunity:
|
||||
'Explique a necessidade de negócio e os elementos pedidos para preparar a oportunidade.',
|
||||
documents:
|
||||
'Confira os documentos pedidos, associe os disponíveis e identifique a informação que ainda falta.',
|
||||
scenarios:
|
||||
'Compare os cenários com base nos pressupostos preenchidos. Reveja as entradas antes de interpretar diferenças nos resultados.',
|
||||
procedures:
|
||||
'Consulte os procedimentos e os documentos apresentados para o seu contexto e identifique o que precisa de preparar.',
|
||||
review: 'Reveja as entradas, os resultados e as pendências. Se alterar pressupostos, recalcule quando o formulário o indicar; use a acção de guardar apenas quando pretender conservar as alterações.',
|
||||
};
|
||||
|
||||
export function simulationStepGuidance(step: string): string {
|
||||
return (
|
||||
simulationSteps[step] ??
|
||||
'Confira os dados pedidos neste passo, complete o que souber e consulte a ajuda de cada campo quando precisar.'
|
||||
);
|
||||
}
|
||||
|
||||
export function readFormHelpAutomatic(value: string | null): boolean {
|
||||
return value !== 'off';
|
||||
}
|
||||
|
||||
export function formHelpPlacement(
|
||||
rect: { left: number; top: number; bottom: number },
|
||||
width: number,
|
||||
height: number,
|
||||
) {
|
||||
const above = Math.max(0, rect.top - 84);
|
||||
const below = Math.max(0, height - rect.bottom - 16);
|
||||
return {
|
||||
side: rect.left > width / 2 ? ('left' as const) : ('right' as const),
|
||||
vertical: above > below ? ('top' as const) : ('bottom' as const),
|
||||
maxHeight: Math.max(
|
||||
96,
|
||||
Math.min(height * 0.45, Math.max(above, below) - 64),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import {
|
||||
formFieldGuidance,
|
||||
formHelpPlacement,
|
||||
normaliseHelpLabel,
|
||||
readFormHelpAutomatic,
|
||||
simulationStepGuidance,
|
||||
} from '../../resources/js/lib/form-help.ts';
|
||||
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
test('guidance explains actual fiscal/financial inputs without inventing rates or replacing periods', () => {
|
||||
for (const [label, expected] of [
|
||||
['Volume de negócios anterior', /período pedido/],
|
||||
['Imposto liquidado', /documento correspondente/],
|
||||
['Retenções na fonte', /documentado/],
|
||||
['Receita mensal', /previsão/],
|
||||
['Custo unitário', /unitário, mensal, anual ou total/],
|
||||
['Moeda do projecto', /moeda/],
|
||||
['Residência fiscal', /enquadramento/],
|
||||
['NUIT', /documento/],
|
||||
['Fonte documental', /recuperar e conferir/],
|
||||
]) {
|
||||
const result = formFieldGuidance({
|
||||
label,
|
||||
type: 'text',
|
||||
required: false,
|
||||
value: 'PRIVATE-INPUT-123',
|
||||
});
|
||||
assert.match(result.instruction, expected);
|
||||
assert.doesNotMatch(JSON.stringify(result), /PRIVATE-INPUT|\d+%/);
|
||||
}
|
||||
});
|
||||
|
||||
test('native and accessible custom field types receive useful instructions', () => {
|
||||
for (const type of [
|
||||
'text',
|
||||
'number',
|
||||
'range',
|
||||
'select',
|
||||
'combobox',
|
||||
'checkbox',
|
||||
'radio',
|
||||
'date',
|
||||
'month',
|
||||
'email',
|
||||
'tel',
|
||||
'url',
|
||||
'password',
|
||||
'file',
|
||||
'textarea',
|
||||
]) {
|
||||
const result = formFieldGuidance({
|
||||
label: 'Campo de ensaio',
|
||||
type,
|
||||
required: true,
|
||||
});
|
||||
assert.ok(result.instruction.length > 30, type);
|
||||
}
|
||||
assert.match(
|
||||
formFieldGuidance({
|
||||
label: 'Autorização',
|
||||
type: 'checkbox',
|
||||
required: false,
|
||||
}).instruction,
|
||||
/apenas se/,
|
||||
);
|
||||
assert.match(
|
||||
formFieldGuidance({ label: 'Documento', type: 'file', required: false })
|
||||
.instruction,
|
||||
/formatos indicados/,
|
||||
);
|
||||
assert.equal(
|
||||
normaliseHelpLabel('RETENÇÕES — MOÇAMBIQUE'),
|
||||
'retencoes — mocambique',
|
||||
);
|
||||
});
|
||||
|
||||
test('all adaptive simulator sections have specific step guidance', () => {
|
||||
const seen = new Set();
|
||||
for (const draft of [
|
||||
{},
|
||||
{ purpose: 'simulate_only' },
|
||||
{ journey_type: 'company' },
|
||||
{ journey_type: 'personal' },
|
||||
{ journey_type: 'investor' },
|
||||
{ journey_type: 'small_business' },
|
||||
{ purpose: 'prepare_investment', journey_type: 'investor' },
|
||||
]) {
|
||||
for (const step of getSimulationSections(draft)) {
|
||||
seen.add(step.id);
|
||||
assert.notEqual(
|
||||
simulationStepGuidance(step.id),
|
||||
simulationStepGuidance('unknown-section'),
|
||||
step.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const code of [
|
||||
'purpose',
|
||||
'market',
|
||||
'investment',
|
||||
'financial',
|
||||
'operating',
|
||||
'cashflow',
|
||||
'tax',
|
||||
'review',
|
||||
'team',
|
||||
'scenarios',
|
||||
'procedures',
|
||||
]) {
|
||||
assert.ok(simulationStepGuidance(code).length > 40);
|
||||
}
|
||||
assert.ok(seen.size >= 11);
|
||||
});
|
||||
|
||||
test('browser help preference is optional and does not store field contents', () => {
|
||||
assert.equal(readFormHelpAutomatic(null), true);
|
||||
assert.equal(readFormHelpAutomatic('off'), false);
|
||||
assert.equal(readFormHelpAutomatic('on'), true);
|
||||
assert.equal(readFormHelpAutomatic('corrupt'), true);
|
||||
for (const file of [
|
||||
'components/form-field-help.tsx',
|
||||
'lib/form-help-dom.ts',
|
||||
]) {
|
||||
const source = readFileSync(
|
||||
new URL('../../resources/js/' + file, import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/\.value\b|FormData|fetch\(|router\.|\.submit\(|\.requestSubmit\(/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('help is placed above or below the focused mobile field without covering it', () => {
|
||||
for (const rect of [
|
||||
{ left: 24, top: 180, bottom: 224 },
|
||||
{ left: 24, top: 440, bottom: 484 },
|
||||
{ left: 24, top: 700, bottom: 744 },
|
||||
]) {
|
||||
const layout = formHelpPlacement(rect, 390, 844);
|
||||
assert.ok(layout.maxHeight >= 96 && layout.maxHeight <= 844 * 0.45);
|
||||
if (layout.vertical === 'top')
|
||||
assert.ok(80 + layout.maxHeight + 60 < rect.top);
|
||||
else assert.ok(844 - 12 - layout.maxHeight - 60 > rect.bottom);
|
||||
}
|
||||
});
|
||||
|
||||
test('help mounts once across portal pages and the simulator publishes its current adaptive step', () => {
|
||||
const app = readFileSync(
|
||||
new URL('../../resources/js/app.tsx', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.equal((app.match(/<FormFieldHelp\s*\/>/g) ?? []).length, 1);
|
||||
const simulator = readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/simulation-form.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(simulator, /data-form-help-step=\{current.id\}/);
|
||||
assert.match(simulator, /data-form-help-title=\{current.title\}/);
|
||||
assert.match(
|
||||
simulator,
|
||||
/<button[^>]*type="button"[^>]*data-form-help-open/s,
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user