227 lines
9.3 KiB
TypeScript
227 lines
9.3 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import {
|
|
correctionFieldHints,
|
|
fieldLabelMatches,
|
|
revealCorrectionTarget,
|
|
} from '@/lib/field-corrections';
|
|
|
|
type Correction = { message: string; targets: { id: string; label: string }[] };
|
|
let nextId = 0;
|
|
function labelOf(
|
|
control: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement,
|
|
) {
|
|
const label = control.labels?.[0];
|
|
if (label) {
|
|
const copy = label.cloneNode(true) as HTMLElement;
|
|
copy.querySelectorAll(
|
|
'input,select,textarea,button,[role="alert"],.sr-only',
|
|
).forEach((n) => n.remove());
|
|
return (
|
|
copy.textContent?.replace(/\s+/g, ' ').trim() ||
|
|
control.getAttribute('aria-label') ||
|
|
''
|
|
);
|
|
}
|
|
return control.getAttribute('aria-label') || '';
|
|
}
|
|
/** Maps live, existing messages to real controls; no inferred financial validations. */
|
|
export default function PortalCorrections() {
|
|
const marker = useRef<HTMLDivElement>(null);
|
|
const [items, setItems] = useState<Correction[]>([]);
|
|
const previous = useRef('');
|
|
useEffect(() => {
|
|
const root = marker.current?.closest('#portal-content');
|
|
if (!root) return;
|
|
let pending = 0;
|
|
const collect = () => {
|
|
pending = 0;
|
|
const controls = [
|
|
...root.querySelectorAll<
|
|
HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
|
|
>('input:not([type="hidden"]),select,textarea'),
|
|
].filter(
|
|
(c) =>
|
|
!c.disabled && !c.closest('[hidden],[aria-hidden="true"]'),
|
|
);
|
|
const names = controls.map((c) => ({
|
|
control: c,
|
|
label: labelOf(c),
|
|
}));
|
|
const target = (c: (typeof controls)[number], label: string) => {
|
|
if (!c.id) c.id = `portal-correction-field-${++nextId}`;
|
|
const group = c.closest('fieldset,[role="group"]');
|
|
const context =
|
|
group?.querySelector('legend')?.textContent?.trim() ||
|
|
group?.getAttribute('aria-label') ||
|
|
'';
|
|
return {
|
|
id: c.id,
|
|
label: context ? `${label} — ${context}` : label,
|
|
};
|
|
};
|
|
const grouped = new Map<string, Correction>();
|
|
const add = (message: string, targets: Correction['targets']) => {
|
|
if (!message || !targets.length) return;
|
|
const item = grouped.get(message) ?? { message, targets: [] };
|
|
for (const t of targets)
|
|
if (!item.targets.some((a) => a.id === t.id))
|
|
item.targets.push(t);
|
|
grouped.set(message, item);
|
|
};
|
|
for (const { control, label } of names) {
|
|
if (control.getAttribute('aria-invalid') !== 'true') continue;
|
|
const messages = (
|
|
control.getAttribute('aria-describedby') ?? ''
|
|
)
|
|
.split(/\s+/)
|
|
.map((id) =>
|
|
document.getElementById(id)?.textContent?.trim(),
|
|
)
|
|
.filter(Boolean);
|
|
const local = control
|
|
.closest('label')
|
|
?.querySelector('[role="alert"]')
|
|
?.textContent?.trim();
|
|
add(
|
|
messages.join(' ') || local || 'Confira o valor indicado.',
|
|
[target(control, label || 'Campo indicado')],
|
|
);
|
|
}
|
|
for (const node of root.querySelectorAll<HTMLElement>(
|
|
'[data-correction-message],[role="alert"]',
|
|
)) {
|
|
if (
|
|
node.closest(
|
|
'[data-correction-summary],[hidden],[aria-hidden="true"]',
|
|
)
|
|
)
|
|
continue;
|
|
const message =
|
|
node.dataset.correctionMessage ||
|
|
node.textContent?.replace(/\s+/g, ' ').trim() ||
|
|
'';
|
|
if (!message) continue;
|
|
const hints = correctionFieldHints(message);
|
|
const matches = names.filter(
|
|
({ label }) =>
|
|
label && hints.some((h) => fieldLabelMatches(label, h)),
|
|
);
|
|
// Restrict explicit product/parcel diagnostics to the matching real group, if present.
|
|
const index = /produto\s+(\d+)|parcela\s+(\d+)/i.exec(message);
|
|
const indexed = index
|
|
? matches.filter(({ control }) => {
|
|
const group = control.closest(
|
|
'fieldset,[role="group"],[aria-label]',
|
|
);
|
|
const name =
|
|
group?.getAttribute('aria-label') ||
|
|
group?.querySelector('legend')?.textContent ||
|
|
'';
|
|
return new RegExp(
|
|
`(?:produto|parcela)\\s+${index[1] || index[2]}\\b`,
|
|
'i',
|
|
).test(name);
|
|
})
|
|
: [];
|
|
add(
|
|
message,
|
|
(indexed.length ? indexed : matches).map(
|
|
({ control, label }) => target(control, label),
|
|
),
|
|
);
|
|
}
|
|
const next = [...grouped.values()];
|
|
const serial = JSON.stringify(next);
|
|
if (serial !== previous.current) {
|
|
previous.current = serial;
|
|
setItems(next);
|
|
}
|
|
};
|
|
const schedule = () => {
|
|
if (!pending) pending = requestAnimationFrame(collect);
|
|
};
|
|
const observer = new MutationObserver((records) => {
|
|
if (
|
|
records.some(
|
|
(r) =>
|
|
!(
|
|
r.target instanceof Element
|
|
? r.target
|
|
: r.target.parentElement
|
|
)?.closest('[data-correction-summary]'),
|
|
)
|
|
)
|
|
schedule();
|
|
});
|
|
observer.observe(root, {
|
|
subtree: true,
|
|
childList: true,
|
|
characterData: true,
|
|
attributes: true,
|
|
attributeFilter: ['aria-invalid', 'aria-describedby', 'hidden'],
|
|
});
|
|
root.addEventListener('input', schedule);
|
|
root.addEventListener('change', schedule);
|
|
collect();
|
|
return () => {
|
|
observer.disconnect();
|
|
root.removeEventListener('input', schedule);
|
|
root.removeEventListener('change', schedule);
|
|
if (pending) cancelAnimationFrame(pending);
|
|
};
|
|
}, []);
|
|
return (
|
|
<div
|
|
ref={marker}
|
|
data-correction-summary
|
|
className="mx-auto max-w-6xl px-4 print:hidden"
|
|
>
|
|
{items.length > 0 && (
|
|
<section
|
|
id="portal-corrections"
|
|
aria-label="Falta preencher ou corrigir"
|
|
className="my-3 space-y-3 rounded border border-amber-500 bg-amber-50 p-4 text-sm"
|
|
>
|
|
<h2 className="font-semibold">
|
|
Falta preencher ou corrigir
|
|
</h2>
|
|
<p>
|
|
Use as ligações para abrir a secção e chegar ao campo
|
|
indicado.
|
|
</p>
|
|
<ul className="space-y-3">
|
|
{items.map((item) => (
|
|
<li key={item.message}>
|
|
<p>{item.message}</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
{item.targets.map((t) => (
|
|
<a
|
|
key={t.id}
|
|
className="min-h-11 rounded border bg-white px-3 py-2 underline"
|
|
href={`#${t.id}`}
|
|
onClick={(e) => {
|
|
const node =
|
|
document.getElementById(
|
|
t.id,
|
|
);
|
|
if (node) {
|
|
e.preventDefault();
|
|
revealCorrectionTarget(
|
|
node,
|
|
);
|
|
}
|
|
}}
|
|
>
|
|
{t.label}
|
|
</a>
|
|
))}
|
|
</div>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</section>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|