Files
Investidor-V2/resources/js/lib/form-help-dom.ts
T
2026-11-17 10:01:43 +02:00

175 lines
6.0 KiB
TypeScript

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: '',
};
}