fix: harmonizar pesquisa e navegacao dos catalogos em QA

This commit is contained in:
2026-10-20 18:53:41 +02:00
parent 1350b4df73
commit fd341b627e
34 changed files with 2311 additions and 1310 deletions
@@ -0,0 +1,140 @@
import { Link, usePage } from '@inertiajs/react';
const labels: Record<string, string> = {
q: 'Pesquisa',
query: 'Pesquisa',
sector: 'Sector',
kind: 'Tipo de ficha',
modality: 'Modalidade',
category: 'Categoria',
physical_category: 'Tipo de espaço',
legal_regime: 'Regime',
development_status: 'Desenvolvimento',
availability_status: 'Disponibilidade',
province_id: 'Província',
district_id: 'Distrito',
admin_post_id: 'Posto administrativo',
locality_id: 'Localidade',
geo_location_id: 'Localização',
territory_id: 'Território',
province: 'Província',
activity: 'Actividade',
document_type: 'Tipo de documento',
topic: 'Tema',
issuer: 'Entidade emissora',
language: 'Idioma',
legal_status: 'Situação documental',
source_confirmation: 'Fonte',
stage: 'Etapa',
module: 'Área',
association_type: 'Associação',
association_target: 'Referência',
association_purpose: 'Relação',
association_state: 'Confirmação',
chain_id: 'Cadeia de valor',
subsector_id: 'Actividade',
authority_id: 'Entidade',
};
const territoryKeys = [
'province_id',
'district_id',
'admin_post_id',
'locality_id',
];
const values: Record<string, string> = {
corridor: 'Corredores',
cluster: 'Clusters',
project: 'Projectos âncora',
zee: 'ZEE',
zfi: 'ZFI',
industrial_park: 'Parque industrial',
investment_project: 'Projecto de investimento',
company_sale: 'Venda de empresa',
company_purchase: 'Compra de empresa',
real_estate: 'Imobiliário',
land_right: 'Direitos fundiários',
turismo: 'Turismo',
agronegocio: 'Agronegócio',
fintech: 'Fintech — especialização do Mercado Financeiro',
'mercado-financeiro': 'Mercado Financeiro',
legislation: 'Legislação',
procedure: 'Procedimento oficial',
official_form: 'Formulário oficial',
guide: 'Guia',
study: 'Estudo',
unknown: 'Por confirmar',
pt: 'Português',
en: 'Inglês',
confirmed: 'Confirmada',
pending: 'Por confirmar',
};
/** Name each active criterion without exposing IDs or taxonomy codes. */
export default function CatalogueFilterContext() {
const page = usePage();
const filters = page.props.filters as Record<string, unknown> | undefined;
if (!filters) return null;
const active = Object.entries(filters).filter(
([key, value]) =>
!['page', 'per_page', 'sort', 'view', 'publication_state'].includes(
key,
) &&
value !== '' &&
value != null &&
value !== false &&
(!Array.isArray(value) || value.length),
);
if (!active.length) return null;
const describe = (key: string, value: unknown): string => {
const path = page.props.territorySelection as
| { id: string; name: string }[]
| undefined;
const place = path?.find((item) => item.id === value)?.name;
if (place) return place;
if (typeof value !== 'string') return 'seleccionado';
return (
values[value] ??
(['q', 'query', 'province', 'topic', 'issuer'].includes(key)
? value
: 'seleccionado')
);
};
const href = (remove?: string) => {
const url = new URL(page.url, 'https://portal.invalid');
const keys = remove
? [
remove,
...territoryKeys
.slice(territoryKeys.indexOf(remove) + 1)
.filter(() => territoryKeys.includes(remove)),
]
: Object.keys(filters);
for (const key of keys) {
url.searchParams.delete(key);
url.searchParams.delete(`${key}[]`);
}
url.searchParams.delete('page');
return url.pathname + url.search;
};
return (
<nav
aria-label="Filtros activos"
className="my-3 flex flex-wrap items-center gap-3"
>
<span className="font-semibold">Filtros activos:</span>
{active.map(([key, value]) => (
<Link
key={key}
href={href(key)}
className="rounded border px-3 py-2 underline"
aria-label={`Remover ${labels[key] ?? 'critério'}`}
>
{labels[key] ?? 'Critério seleccionado'}:{' '}
{describe(key, value)} ×
</Link>
))}
<Link href={href()} className="underline">
Limpar filtros
</Link>
</nav>
);
}
@@ -73,34 +73,32 @@ export default function CatalogueNavigation({
],
};
return (
<nav
className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4"
aria-label="Explorar dentro do catálogo"
>
{Object.entries(sections).map(([title, items]) => (
<section key={title}>
<h2 className="mb-2 font-semibold">{title}</h2>
<ul className="space-y-2">
{items.map(([label, href]) => (
<li key={label}>
<Link
className="underline"
href={withContext(href)}
>
{label}
</Link>
</li>
))}
</ul>
</section>
))}
<p className="text-sm sm:col-span-2 lg:col-span-4">
Filtros e vistas reutilizam os catálogos existentes.
Comprar/vender continua no consumidor /negocios; não duplica
anúncios nem unifica contagens. Selecionar um parque ou projeto
específico usa os filtros existentes; a ficha relacionada não é
uma oportunidade.
</p>
</nav>
<details className="my-4 rounded-xl border bg-white p-4">
<summary className="cursor-pointer font-semibold">
Catálogos relacionados
</summary>
<nav
className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4"
aria-label="Explorar dentro do catálogo"
>
{Object.entries(sections).map(([title, items]) => (
<section key={title}>
<h2 className="mb-2 font-semibold">{title}</h2>
<ul className="space-y-2">
{items.map(([label, href]) => (
<li key={label}>
<Link
className="underline"
href={withContext(href)}
>
{label}
</Link>
</li>
))}
</ul>
</section>
))}
</nav>
</details>
);
}
+8 -1
View File
@@ -50,7 +50,14 @@ export default function CountrySelect({
onChange={(event) => setSearch(event.target.value)}
placeholder="Pesquisar nome ou código do país"
/>
{search.trim() && <p role="status" aria-live="polite">{matches.length ? `${matches.length} resultados encontrados` : "Não foram encontrados resultados para esta pesquisa"}</p>}
{search.trim() && (
<p role="status" aria-live="polite">
Países:{' '}
{matches.length
? `${matches.length} opções disponíveis`
: 'Nenhuma opção encontrada'}
</p>
)}
<select
disabled={disabled}
id={id ?? generatedId}
@@ -24,7 +24,9 @@ export default function InvestmentMapPanel({
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams(JSON.parse(key));
setPoints(null); setError(''); setMissing([]);
setPoints(null);
setError('');
setMissing([]);
setAreas([]);
fetch(`/api/v1/investment/map?${params}`, {
signal: controller.signal,
@@ -46,13 +48,21 @@ export default function InvestmentMapPanel({
);
})
.catch(() => {
if (!controller.signal.aborted) setError('Não foi possível concluir a pesquisa.');
if (!controller.signal.aborted)
setError('Não foi possível concluir a pesquisa.');
});
return () => controller.abort();
}, [key, retry]);
return (
<section className="space-y-3">
<SearchState loading={points === null && !error} error={error} total={(points?.length ?? 0) + missing.length} retry={() => setRetry(value => value + 1)} />
<SearchState
scope="Registos consultados pelo mapa"
countLabel="registos, incluindo os que não têm coordenadas"
loading={points === null && !error}
error={error}
total={(points?.length ?? 0) + missing.length}
retry={() => setRetry((value) => value + 1)}
/>
<InteractiveInvestmentMap points={points} areas={areas} />
<TerritoryGeometryPreview
territoryId={
@@ -113,9 +113,7 @@ export function ProvinceSelect({
})
.catch(() => {
if (!controller.signal.aborted)
setError(
'Não foi possível concluir a pesquisa.',
);
setError('Não foi possível concluir a pesquisa.');
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
@@ -130,7 +128,13 @@ export function ProvinceSelect({
return (
<>
<SearchState loading={loading} error={error} total={options.length} retry={() => setRetry(value => value + 1)} />
<SearchState
scope="Localizações"
loading={loading}
error={error}
total={options.length}
retry={() => setRetry((value) => value + 1)}
/>
<input
className={className}
aria-label={`Pesquisar ${label}`}
@@ -300,9 +304,7 @@ export function TerritoryLevel({
setMore(Boolean(data.next_page_url));
} catch {
if (!controller.signal.aborted)
setError(
'Não foi possível concluir a pesquisa.',
);
setError('Não foi possível concluir a pesquisa.');
} finally {
if (!controller.signal.aborted) setLoading(false);
}
@@ -314,7 +316,15 @@ export function TerritoryLevel({
}, [index, parent, page, enabled, endpoint, retry, search]);
return (
<div className="space-y-2">
{enabled && <SearchState loading={loading} error={error} total={options.length} retry={() => setRetry(value => value + 1)} />}
{enabled && (
<SearchState
scope={labels[index]}
loading={loading}
error={error}
total={options.length}
retry={() => setRetry((value) => value + 1)}
/>
)}
<label htmlFor={id} className="font-medium">
{labels[index]}
</label>
@@ -831,7 +831,11 @@ export function ClassificationSummary({
<h2 className="text-xl font-bold">
Associações territoriais e produtivas
</h2>
<p>{help}</p>
<p>
As relações preliminares permanecem por confirmar. Uma
associação não comprova disponibilidade, incentivos ou direitos
concedidos.
</p>
{Object.entries({
territory: 'Enquadramento territorial',
production: 'Organização produtiva',
@@ -867,10 +871,7 @@ export function ClassificationSummary({
</p>
))
) : (
<p>
Sem informação tipada publicada nesta dimensão;
consulte também as relações anteriores abaixo.
</p>
<p>Sem associações publicadas neste grupo.</p>
)}
</section>
))}
@@ -0,0 +1,480 @@
import { Field, input, button, groupLabels } from '@/pages/investment/shared';
import type { References } from '@/pages/investment/shared';
import { TerritoryLevel, type TerritoryOption } from './investment-territory';
export const modalityLabels: Record<string, string> = {
investment_project: 'Projecto de investimento',
real_estate: 'Imobiliário',
land_rights: 'DUAT e direitos fundiários',
business_sale: 'Venda de negócio',
business_partnership: 'Parceria empresarial',
franchise: 'Franquia',
concession: 'Concessão',
financing: 'Financiamento',
supply: 'Fornecimento',
other: 'Outra modalidade',
};
type Values = Record<string, string | boolean | number[]>;
const labels: Record<string, string> = {
q: 'O que procura',
sector: 'Sector',
category: 'Modalidade da oportunidade',
preparation: 'Estado de preparação',
sort: 'Ordenar',
min_amount: 'Investimento mínimo',
max_amount: 'Investimento máximo',
currency: 'Moeda',
before: 'Data-alvo até',
cluster_id: 'Cluster',
corridor_id: 'Corredor',
project_id: 'Projecto âncora',
zee_id: 'ZEE',
zfi_id: 'ZFI',
park_id: 'Parque industrial',
chain_id: 'Cadeia de valor',
subsector_id: 'Actividade',
include_national: 'Incluir âmbito nacional',
education: 'Educação',
province: 'Província indicada',
district: 'Distrito indicado',
dimension: 'Grupo de oportunidades',
territory_basis: 'Localização considerada',
geo_location_id: 'Localização adicional',
maturity_level: 'Classificação histórica',
association_type: 'Associação herdada',
association_target: 'Referência herdada',
association_purpose: 'Relação indicada',
association_state: 'Critério herdado',
authority_id: 'Entidade',
publication_state: 'Critério herdado',
};
export default function OpportunitySearchFilters({
data,
references,
path,
change,
territory,
submit,
clear,
errors,
}: {
data: Values;
references: References;
path: TerritoryOption[];
change: (values: Values) => void;
territory: (path: TerritoryOption[]) => void;
submit: () => void;
clear: () => void;
errors: Record<string, string>;
}) {
const select = (
key: string,
choices: { value: string; label: string }[],
hint?: string,
) => (
<Field key={key} label={labels[key]}>
<select
className={input}
value={String(data[key] ?? '')}
onChange={(e) =>
change({
[key]: e.target.value,
...(key === 'sector'
? { subsector_id: '', chain_id: '' }
: {}),
})
}
>
<option value="">Todos</option>
{choices.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
{hint && <p className="text-sm text-slate-600">{hint}</p>}
</Field>
);
const zoneChoices = (category: string) =>
(references.zones ?? [])
.filter((z) => z.category === category)
.map((z) => ({ value: z.id, label: z.name }));
const choicesFor = (key: string) => {
if (key === 'sector')
return references.sectors.map((s) => ({
value: s.slug,
label:
s.slug === 'fintech'
? 'Fintech — especialização do Mercado Financeiro'
: s.name,
}));
if (key === 'category')
return (references.categories ?? []).map((c) => ({
value: c,
label: modalityLabels[c] ?? 'Outra modalidade',
}));
if (key === 'preparation') return references.preparationOptions ?? [];
if (key === 'dimension')
return [
{ value: 'cluster', label: 'Clusters' },
{ value: 'corridor', label: 'Corredores' },
{ value: 'zee', label: 'ZEE' },
{ value: 'zfi', label: 'ZFI' },
];
if (['zee_id', 'zfi_id', 'park_id'].includes(key))
return zoneChoices(
(
{
zee_id: 'zee',
zfi_id: 'zfi',
park_id: 'industrial_park',
} as Record<string, string>
)[key],
);
const group = (
{
cluster_id: 'clusters',
corridor_id: 'corridors',
project_id: 'projects',
} as const
)[key as 'cluster_id'];
if (group)
return references[group].map((e) => ({
value: e.id,
label: e.name,
}));
if (key === 'chain_id' || key === 'subsector_id')
return (
references.classification?.targets[
key === 'chain_id' ? 'chain' : 'activity'
] ?? []
).map((e) => ({ value: String(e.id), label: e.label }));
return [];
};
const remove = (key: string) => {
if (key === 'sector')
change({ sector: '', subsector_id: '', chain_id: '' });
else if (key === 'facets') change({ facets: [] });
else change({ [key]: typeof data[key] === 'boolean' ? false : '' });
};
const active = Object.entries(data).filter(
([k, v]) =>
![
'view',
'sort',
'province_id',
'district_id',
'admin_post_id',
'locality_id',
].includes(k) &&
v !== '' &&
v !== false &&
v !== null &&
(!Array.isArray(v) || v.length > 0) &&
!(k === 'territory_basis' && v === 'all'),
);
return (
<form
className="space-y-5 rounded-xl border bg-white p-4 sm:p-6"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
aria-label="Pesquisar oportunidades"
>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<Field label="O que procura">
<input
className={input}
value={String(data.q)}
placeholder="Palavras do título ou da descrição"
onChange={(e) => change({ q: e.target.value })}
/>
</Field>
{select('sector', choicesFor('sector'))}
{select('category', choicesFor('category'))}
</div>
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<legend className="mb-2 font-semibold">Localização</legend>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) =>
territory([
...path.slice(0, index),
...(value ? [value] : []),
])
}
/>
))}
</fieldset>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Field label="Estado de preparação">
<select
className={input}
value={String(data.preparation ?? '')}
onChange={(e) =>
change({
preparation: e.target.value,
maturity_level: '',
})
}
>
<option value="">Todos os estados</option>
{[
'Etapas de preparação',
'Classificações históricas',
].map((group) => (
<optgroup key={group} label={group}>
{(references.preparationOptions ?? [])
.filter((o) => o.group === group)
.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</optgroup>
))}
</select>
<p className="text-sm text-slate-600">
Os registos históricos são apresentados separadamente e
conservam a classificação indicada na ficha.
</p>
</Field>
{(['min_amount', 'max_amount'] as const).map((key) => (
<Field key={key} label={labels[key]}>
<input
className={input}
type="number"
min="0"
step="0.01"
value={String(data[key])}
onChange={(e) => change({ [key]: e.target.value })}
/>
</Field>
))}
{select(
'currency',
['MZN', 'USD', 'EUR', 'ZAR'].map((c) => ({
value: c,
label: c,
})),
'Seleccione uma moeda para comparar montantes. Não se efectuam conversões cambiais.',
)}
</div>
<details>
<summary className="cursor-pointer rounded border p-3 font-semibold focus-visible:outline-2">
Mais filtros
</summary>
<div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{[
'corridor_id',
'cluster_id',
'zee_id',
'zfi_id',
'park_id',
'project_id',
'subsector_id',
'chain_id',
].map((key) => select(key, choicesFor(key)))}
<Field label="Data-alvo até">
<input
className={input}
type="date"
value={String(data.before)}
onChange={(e) => change({ before: e.target.value })}
/>
</Field>
</div>
<p className="my-3 text-sm">
Estes filtros procuram associações documentadas. Estar perto
de um parque ou no mesmo distrito não constitui associação,
nem confirma incentivos ou disponibilidade.
</p>
<label className="flex gap-2">
<input
type="checkbox"
checked={Boolean(data.include_national)}
onChange={(e) =>
change({ include_national: e.target.checked })
}
/>
Incluir oportunidades de âmbito nacional
</label>
<details className="mt-3">
<summary className="cursor-pointer font-medium">
Outras características
</summary>
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{[
'education',
'infrastructure',
'labour',
'qualification',
'support',
'impact',
'partnership',
]
.filter((group) =>
references.options.some(
(o) => o.group === group,
),
)
.map((group) => (
<fieldset
key={group}
className="rounded border p-3"
>
<legend>{groupLabels[group]}</legend>
{references.options
.filter((o) => o.group === group)
.map((option) => (
<label
key={option.id}
className="flex gap-2 py-1"
>
<input
type="checkbox"
checked={
Array.isArray(
data.facets,
) &&
data.facets.includes(
option.id,
)
}
onChange={(e) => {
const selected =
Array.isArray(
data.facets,
)
? data.facets
: [];
change({
facets: e.target
.checked
? [
...selected,
option.id,
]
: selected.filter(
(id) =>
id !==
option.id,
),
});
}}
/>
{option.label}
</label>
))}
</fieldset>
))}
</div>
</details>
</details>
<section
aria-label="Filtros activos"
className="flex flex-wrap gap-2"
>
{path.map((node, index) => (
<button
className="rounded border px-3 py-2"
type="button"
key={node.id}
aria-label={`Remover localização ${node.name}`}
onClick={() => territory(path.slice(0, index))}
>
{node.name} ×
</button>
))}
{active.flatMap(([key, value]) =>
key === 'facets' && Array.isArray(value)
? value.map((id) => (
<button
key={`facet-${id}`}
type="button"
className="rounded border px-3 py-2"
onClick={() =>
change({
facets: value.filter((x) => x !== id),
})
}
>
{' '}
{references.options.find((o) => o.id === id)
?.label ?? 'Critério adicional'}{' '}
×
</button>
))
: [
<button
key={key}
type="button"
className="rounded border px-3 py-2 text-left"
aria-label={`Remover ${labels[key] ?? 'critério adicional'}`}
onClick={() => remove(key)}
>
{labels[key] ?? 'Critério adicional'}:{' '}
{typeof value === 'boolean'
? 'Sim'
: (choicesFor(key).find(
(o) => o.value === String(value),
)?.label ??
([
'q',
'min_amount',
'max_amount',
'currency',
'before',
'province',
'district',
].includes(key)
? String(value)
: 'seleccionado'))}{' '}
×
</button>,
],
)}
</section>
{Object.entries(errors).map(([key, value]) => (
<p key={key} role="alert">
{value}
</p>
))}
<div className="flex flex-wrap items-end gap-4">
{select('sort', [
{ value: 'recent', label: 'Mais recentes' },
{ value: 'title', label: 'Título' },
{
value: 'amount_asc',
label: 'Montante crescente, por moeda',
},
{
value: 'amount_desc',
label: 'Montante decrescente, por moeda',
},
])}
<button className={button}>Pesquisar</button>
<button
type="button"
className="rounded border px-4 py-2 underline"
onClick={clear}
>
Limpar filtros
</button>
</div>
</form>
);
}
+169 -26
View File
@@ -1,14 +1,45 @@
import { router, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import CatalogueFilterContext from './catalogue-filter-context';
// Shared feedback for existing Inertia search consumers; form state is never reset.
const collections = ['results','records','resources','partnerships','opportunities','interests','investors','leads','articles','services','items','entries','documents','requests','batches','users','assignments','zones','matches','businesses'];
const collections = [
'results',
'records',
'resources',
'partnerships',
'opportunities',
'interests',
'investors',
'leads',
'articles',
'services',
'items',
'entries',
'documents',
'requests',
'batches',
'users',
'assignments',
'zones',
'matches',
'businesses',
];
function count(props: Record<string, unknown>): number | null {
if (props.demands && props.capacities) return Number((props.demands as {total:number}).total) + Number((props.capacities as {total:number}).total);
if (props.plan && Array.isArray((props.plan as {rows:unknown[]}).rows)) return (props.plan as {rows:unknown[]}).rows.length;
if (props.demands && props.capacities)
return (
Number((props.demands as { total: number }).total) +
Number((props.capacities as { total: number }).total)
);
if (props.plan && Array.isArray((props.plan as { rows: unknown[] }).rows))
return (props.plan as { rows: unknown[] }).rows.length;
if (typeof props.total === 'number') return props.total;
if (typeof props.match === 'boolean' && Array.isArray(props.articles)) return props.match ? props.articles.length : 0;
if (typeof props.match === 'boolean' && Array.isArray(props.articles))
return props.match ? props.articles.length : 0;
for (const key of collections) {
const value = props[key] as {total?:number; meta?:{total?:number}; data?:unknown[]} | unknown[] | undefined;
const value = props[key] as
| { total?: number; meta?: { total?: number }; data?: unknown[] }
| unknown[]
| undefined;
if (!value) continue;
if (Array.isArray(value)) return value.length;
if (typeof value.total === 'number') return value.total;
@@ -19,28 +50,140 @@ function count(props: Record<string, unknown>): number | null {
}
export default function SearchFeedback() {
const page = usePage();
const [state, setState] = useState<'idle'|'loading'|'error'>('idle');
const latest = useRef<{url: string; data: Record<string, unknown>} | null>(null);
const handledLocally = page.component === 'investment/catalogue';
const [state, setState] = useState<'idle' | 'loading' | 'error'>('idle');
const latest = useRef<{
url: string;
data: Record<string, unknown>;
} | null>(null);
const active = useRef(false);
const searchable = page.props.filters !== undefined || ['portal/legacy','desk/catalogue','investment/zones','partnerships/catalogue','education/index','management/territory-geometry-import'].includes(page.component);
const total = searchable ? count(page.props) : null;
const searchable =
page.props.filters !== undefined ||
[
'portal/legacy',
'desk/catalogue',
'investment/zones',
'partnerships/catalogue',
'education/index',
'management/territory-geometry-import',
].includes(page.component);
// A page may contain several independent catalogues. Never infer a public
// result universe by whichever collection happens to occur first.
const descriptors: Record<string, [string, string]> = {
'portfolio/index': ['records', 'Fichas da carteira'],
'investment/zones': ['records', 'Zonas e parques'],
'investment/business-marketplace': ['results', 'Anúncios de negócios'],
'portal/legacy': ['articles', 'Artigos'],
};
const descriptor =
page.component === 'portal/services'
? page.props.section === 'documents' ||
page.props.section === 'legislation'
? ['resources', 'Documentos']
: page.props.section === 'sectors'
? ['sectors', 'Sectores']
: null
: descriptors[page.component];
const total = descriptor
? page.component === 'portal/legacy' && page.props.match === false
? 0
: count({ results: page.props[descriptor[0]] })
: searchable
? count(page.props)
: null;
const label = descriptor?.[1];
useEffect(() => {
const off = [router.on('before', event => {
const visit = event.detail.visit;
if (visit.method !== 'get') { active.current = false; return; }
const data = visit.data as Record<string, unknown>;
const url = visit.url;
const isSearch = total !== null || ['q','query','search','filter','status','sector'].some(key => key in data || url.searchParams.has(key));
active.current = isSearch;
if (isSearch) { latest.current = {url: url.toString(), data}; setState('loading'); }
}), router.on('success', () => { if (active.current) { active.current = false; setState('idle'); } }),
router.on('error', () => { if (active.current) setState('error'); }),
router.on('httpException', event => { if (active.current) { event.preventDefault(); setState('error'); } }),
router.on('networkError', event => { if (active.current) { event.preventDefault(); setState('error'); } })];
return () => off.forEach(remove => remove());
}, [total]);
if (handledLocally) return;
const off = [
router.on('before', (event) => {
const visit = event.detail.visit;
if (visit.method !== 'get') {
active.current = false;
return;
}
const data = visit.data as Record<string, unknown>;
const url = visit.url;
const isSearch =
total !== null ||
['q', 'query', 'search', 'filter', 'status', 'sector'].some(
(key) => key in data || url.searchParams.has(key),
);
active.current = isSearch;
if (isSearch) {
latest.current = { url: url.toString(), data };
setState('loading');
}
}),
router.on('success', () => {
if (active.current) {
active.current = false;
setState('idle');
}
}),
router.on('error', () => {
if (active.current) setState('error');
}),
router.on('httpException', (event) => {
if (active.current) {
event.preventDefault();
setState('error');
}
}),
router.on('networkError', (event) => {
if (active.current) {
event.preventDefault();
setState('error');
}
}),
];
return () => off.forEach((remove) => remove());
}, [total, handledLocally]);
if (handledLocally) return null;
if (total === null && state === 'idle') return null;
return <aside data-search-feedback role={state === 'error' ? 'alert' : 'status'} aria-live="polite" aria-atomic="true" className="sticky top-0 z-50 border-b bg-white p-3 text-center text-slate-950 shadow">
{state === 'loading' ? 'A pesquisar…' : state === 'error' ? <><span>Não foi possível concluir a pesquisa. Os resultados anteriores mantêm-se abaixo. </span><button type="button" className="underline" onClick={() => { const request = latest.current; if (request) router.get(request.url, request.data as never, {preserveState:true, preserveScroll:true}); }}>Tentar novamente</button></> : total === 0 ? 'Não foram encontrados resultados para esta pesquisa' : `${total} resultados encontrados`}
</aside>;
return (
<>
<aside
data-search-feedback
role={state === 'error' ? 'alert' : 'status'}
aria-live="polite"
aria-atomic="true"
className="border-b bg-white p-3 text-center text-slate-950"
>
{label && <strong>{label}: </strong>}
{state === 'loading' ? (
'A pesquisar…'
) : state === 'error' ? (
<>
<span>
Não foi possível concluir a pesquisa. Os resultados
anteriores mantêm-se abaixo.{' '}
</span>
<button
type="button"
className="underline"
onClick={() => {
const request = latest.current;
if (request)
router.get(
request.url,
request.data as never,
{
preserveState: true,
preserveScroll: true,
},
);
}}
>
Tentar novamente
</button>
</>
) : total === 0 ? (
'Não foram encontrados resultados para esta pesquisa'
) : (
`${total} ${total === 1 ? 'resultado encontrado' : 'resultados encontrados'}`
)}
</aside>
{descriptor && <CatalogueFilterContext />}
</>
);
}
+47 -4
View File
@@ -1,5 +1,48 @@
export default function SearchState({loading, error, total, retry}: {loading:boolean; error?:string; total:number; retry:()=>void}) {
return <div role={error ? 'alert' : 'status'} aria-live="polite" aria-atomic="true" className="my-3 rounded border p-3">
{loading ? 'A pesquisar…' : error ? <>Não foi possível concluir a pesquisa. <button type="button" className="underline" onClick={retry}>Tentar novamente</button></> : total === 0 ? 'Não foram encontrados resultados para esta pesquisa' : `${total} resultados encontrados`}
</div>;
export default function SearchState({
loading,
error,
total,
retry,
scope,
countLabel,
}: {
loading: boolean;
error?: string;
total: number;
retry: () => void;
scope?: string;
countLabel?: string;
}) {
return (
<div
role={error ? 'alert' : 'status'}
aria-live="polite"
aria-atomic="true"
className="my-3 rounded border p-3"
>
{scope && <span className="font-medium">{scope}: </span>}
{loading ? (
'A pesquisar…'
) : error ? (
<>
Não foi possível concluir a pesquisa.{' '}
<button type="button" className="underline" onClick={retry}>
Tentar novamente
</button>
</>
) : total === 0 ? (
scope ? (
'Nenhuma opção encontrada'
) : (
'Não foram encontrados resultados para esta pesquisa'
)
) : countLabel ? (
`${total} ${countLabel}`
) : scope ? (
`${total} ${total === 1 ? 'opção disponível' : 'opções disponíveis'}`
) : (
`${total} ${total === 1 ? 'resultado encontrado' : 'resultados encontrados'}`
)}
</div>
);
}