Mapa de erros 4.4: o grupo escolhido nas zonas mantém-se após a pesquisa
A lista de grupos voltava a «Todas» depois de cada pesquisa, embora o endereço guardasse o grupo. Os grupos sem registos para a selecção passam a dizê-lo e não podem ser escolhidos, salvo o que já está aplicado. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
@@ -0,0 +1,19 @@
|
|||||||
|
/**
|
||||||
|
* Reset a search form to the filters the server applied.
|
||||||
|
*
|
||||||
|
* React only writes a select's defaultValue into the DOM on the first render,
|
||||||
|
* so a plain form.reset() after a search returns every select to the value the
|
||||||
|
* page opened with (for example "Todas"), while the URL keeps the chosen group.
|
||||||
|
* Selects that declare data-applied are aligned first, so the reset keeps the
|
||||||
|
* applied choice and the focus stays where the investor left it.
|
||||||
|
*/
|
||||||
|
export function resetToAppliedFilters(form: HTMLFormElement | null): void {
|
||||||
|
if (!form) return;
|
||||||
|
for (const select of Array.from(form.querySelectorAll("select"))) {
|
||||||
|
const applied = select.getAttribute("data-applied");
|
||||||
|
if (applied === null) continue;
|
||||||
|
for (const option of Array.from(select.options))
|
||||||
|
option.defaultSelected = option.value === applied;
|
||||||
|
}
|
||||||
|
form.reset();
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import { Link, router, usePage } from '@inertiajs/react';
|
|||||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { territorialSearchParams } from '@/lib/territorial-search-params';
|
import { territorialSearchParams } from '@/lib/territorial-search-params';
|
||||||
|
import { resetToAppliedFilters } from '@/lib/applied-form-reset';
|
||||||
import CatalogueFilterContext from '@/components/catalogue-filter-context';
|
import CatalogueFilterContext from '@/components/catalogue-filter-context';
|
||||||
import { catalogueDetailHref } from '@/lib/catalogue-context';
|
import { catalogueDetailHref } from '@/lib/catalogue-context';
|
||||||
import {
|
import {
|
||||||
@@ -116,7 +117,7 @@ export default function Zones({
|
|||||||
const [searchError, setSearchError] = useState('');
|
const [searchError, setSearchError] = useState('');
|
||||||
const appliedKey = JSON.stringify([filters, territorySelection]);
|
const appliedKey = JSON.stringify([filters, territorySelection]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
searchForm.current?.reset();
|
resetToAppliedFilters(searchForm.current);
|
||||||
}, [appliedKey]);
|
}, [appliedKey]);
|
||||||
useEffect(
|
useEffect(
|
||||||
() => () => {
|
() => () => {
|
||||||
@@ -301,23 +302,34 @@ export default function Zones({
|
|||||||
className={input}
|
className={input}
|
||||||
name="category"
|
name="category"
|
||||||
defaultValue={filters.category ?? ''}
|
defaultValue={filters.category ?? ''}
|
||||||
|
data-applied={filters.category ?? ''}
|
||||||
>
|
>
|
||||||
<option value="">Todas</option>
|
<option value="">Todas</option>
|
||||||
<option value="zee">
|
{(
|
||||||
ZEE
|
[
|
||||||
{groupAvailability.zee != null &&
|
['zee', 'ZEE'],
|
||||||
` — ${groupAvailability.zee} registos`}
|
['zfi', 'ZFI'],
|
||||||
</option>
|
['industrial_park', 'Parque industrial'],
|
||||||
<option value="zfi">
|
] as const
|
||||||
ZFI
|
).map(([value, label]) => {
|
||||||
{groupAvailability.zfi != null &&
|
const count = groupAvailability[value];
|
||||||
` — ${groupAvailability.zfi} registos`}
|
const empty =
|
||||||
</option>
|
count === 0 && filters.category !== value;
|
||||||
<option value="industrial_park">
|
return (
|
||||||
Parque industrial
|
<option
|
||||||
{groupAvailability.industrial_park != null &&
|
key={value}
|
||||||
` — ${groupAvailability.industrial_park} registos`}
|
value={value}
|
||||||
</option>
|
disabled={empty}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
{count == null
|
||||||
|
? ''
|
||||||
|
: count === 0
|
||||||
|
? ' — sem registos para esta selecção'
|
||||||
|
: ` — ${count} ${count === 1 ? 'registo' : 'registos'}`}
|
||||||
|
</option>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</select>
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
<details className="w-full rounded border p-3">
|
<details className="w-full rounded border p-3">
|
||||||
@@ -330,6 +342,7 @@ export default function Zones({
|
|||||||
className={input}
|
className={input}
|
||||||
name="physical_category"
|
name="physical_category"
|
||||||
defaultValue={filters.physical_category ?? ''}
|
defaultValue={filters.physical_category ?? ''}
|
||||||
|
data-applied={filters.physical_category ?? ''}
|
||||||
>
|
>
|
||||||
<option value="">Todas</option>
|
<option value="">Todas</option>
|
||||||
<option value="industrial_park">
|
<option value="industrial_park">
|
||||||
@@ -364,6 +377,7 @@ export default function Zones({
|
|||||||
className={input}
|
className={input}
|
||||||
name="legal_regime"
|
name="legal_regime"
|
||||||
defaultValue={filters.legal_regime ?? ''}
|
defaultValue={filters.legal_regime ?? ''}
|
||||||
|
data-applied={filters.legal_regime ?? ''}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">Todos</option>
|
||||||
<option value="zee">ZEE</option>
|
<option value="zee">ZEE</option>
|
||||||
@@ -380,6 +394,7 @@ export default function Zones({
|
|||||||
defaultValue={
|
defaultValue={
|
||||||
filters.development_status ?? ''
|
filters.development_status ?? ''
|
||||||
}
|
}
|
||||||
|
data-applied={filters.development_status ?? ''}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">Todos</option>
|
||||||
<option value="announced">Anunciado</option>
|
<option value="announced">Anunciado</option>
|
||||||
@@ -407,6 +422,7 @@ export default function Zones({
|
|||||||
defaultValue={
|
defaultValue={
|
||||||
filters.availability_status ?? ''
|
filters.availability_status ?? ''
|
||||||
}
|
}
|
||||||
|
data-applied={filters.availability_status ?? ''}
|
||||||
>
|
>
|
||||||
<option value="">Todas</option>
|
<option value="">Todas</option>
|
||||||
<option value="confirmed">
|
<option value="confirmed">
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import { compileFunction } from "node:vm";
|
||||||
|
import React from "react";
|
||||||
|
import { renderToStaticMarkup } from "react-dom/server";
|
||||||
|
import ts from "typescript";
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const root = path.resolve("resources/js");
|
||||||
|
function load(file) {
|
||||||
|
const absolute = path.resolve(root, file);
|
||||||
|
const module = { exports: {} };
|
||||||
|
const code = ts.transpileModule(fs.readFileSync(absolute, "utf8"), {
|
||||||
|
compilerOptions: {
|
||||||
|
module: ts.ModuleKind.CommonJS,
|
||||||
|
target: ts.ScriptTarget.ES2022,
|
||||||
|
jsx: ts.JsxEmit.ReactJSX,
|
||||||
|
},
|
||||||
|
}).outputText;
|
||||||
|
compileFunction(code, ["require", "module", "exports"])(
|
||||||
|
(id) => {
|
||||||
|
if (id === "@inertiajs/react")
|
||||||
|
return {
|
||||||
|
Link: ({ children, ...props }) =>
|
||||||
|
React.createElement("a", props, children),
|
||||||
|
usePage: () => ({ url: "/zonas", props: {} }),
|
||||||
|
router: { get() {} },
|
||||||
|
Head: () => null,
|
||||||
|
};
|
||||||
|
if (
|
||||||
|
id === "lucide-react" ||
|
||||||
|
id.startsWith("@/components/") ||
|
||||||
|
id.startsWith("@/layouts/")
|
||||||
|
)
|
||||||
|
return new Proxy(
|
||||||
|
{ __esModule: true },
|
||||||
|
{
|
||||||
|
get: (target, key) =>
|
||||||
|
key in target
|
||||||
|
? target[key]
|
||||||
|
: key === "Frame"
|
||||||
|
? ({ children }) =>
|
||||||
|
React.createElement(
|
||||||
|
"main",
|
||||||
|
null,
|
||||||
|
children,
|
||||||
|
)
|
||||||
|
: () => null,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (id.startsWith(".") || id.startsWith("@/")) {
|
||||||
|
const base = id.startsWith("@/")
|
||||||
|
? path.resolve(root, id.slice(2))
|
||||||
|
: path.resolve(path.dirname(absolute), id);
|
||||||
|
const found = [base, base + ".tsx", base + ".ts"].find(
|
||||||
|
(p) => fs.existsSync(p) && fs.statSync(p).isFile(),
|
||||||
|
);
|
||||||
|
if (found) return load(path.relative(root, found));
|
||||||
|
}
|
||||||
|
return require(id);
|
||||||
|
},
|
||||||
|
module,
|
||||||
|
module.exports,
|
||||||
|
);
|
||||||
|
return module.exports;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakeSelect(applied, values, opened) {
|
||||||
|
const options = values.map((value) => ({
|
||||||
|
value,
|
||||||
|
defaultSelected: value === opened,
|
||||||
|
}));
|
||||||
|
const select = {
|
||||||
|
value: applied,
|
||||||
|
options,
|
||||||
|
getAttribute: (name) => (name === "data-applied" ? applied : null),
|
||||||
|
};
|
||||||
|
return select;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('after a search the group list keeps the applied group instead of returning to "Todas" (mapa de erros 4.4)', () => {
|
||||||
|
const { resetToAppliedFilters } = load("lib/applied-form-reset.ts");
|
||||||
|
const group = fakeSelect("zee", ["", "zee", "zfi", "industrial_park"], "");
|
||||||
|
const unrelated = {
|
||||||
|
value: "x",
|
||||||
|
options: [{ value: "x", defaultSelected: true }],
|
||||||
|
getAttribute: () => null,
|
||||||
|
};
|
||||||
|
let resets = 0;
|
||||||
|
const form = {
|
||||||
|
querySelectorAll: () => [group, unrelated],
|
||||||
|
reset() {
|
||||||
|
resets++;
|
||||||
|
for (const select of [group, unrelated])
|
||||||
|
select.value =
|
||||||
|
select.options.find((o) => o.defaultSelected)?.value ?? "";
|
||||||
|
},
|
||||||
|
};
|
||||||
|
resetToAppliedFilters(form);
|
||||||
|
assert.equal(resets, 1);
|
||||||
|
assert.equal(group.value, "zee");
|
||||||
|
assert.equal(unrelated.value, "x");
|
||||||
|
resetToAppliedFilters(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a group known to have no records says so and cannot be chosen, unless it is the applied one (mapa de erros 4.4)", () => {
|
||||||
|
const { default: Zones } = load("pages/investment/zones.tsx");
|
||||||
|
const render = (category) =>
|
||||||
|
renderToStaticMarkup(
|
||||||
|
React.createElement(Zones, {
|
||||||
|
records: {
|
||||||
|
data: [],
|
||||||
|
total: 0,
|
||||||
|
next_page_url: null,
|
||||||
|
prev_page_url: null,
|
||||||
|
},
|
||||||
|
filters: category ? { category } : {},
|
||||||
|
groupAvailability: { zee: 1, zfi: 0, industrial_park: 3 },
|
||||||
|
management: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const html = render("");
|
||||||
|
assert.match(html, /<option value="zee">ZEE — 1 registo<\/option>/);
|
||||||
|
assert.match(
|
||||||
|
html,
|
||||||
|
/<option value="zfi" disabled="">ZFI — sem registos para esta selecção<\/option>/,
|
||||||
|
);
|
||||||
|
assert.match(html, /Parque industrial — 3 registos/);
|
||||||
|
assert.match(html, /name="category" data-applied=""/);
|
||||||
|
const applied = render("zfi");
|
||||||
|
assert.match(
|
||||||
|
applied,
|
||||||
|
/<option value="zfi" selected="">ZFI — sem registos para esta selecção<\/option>/,
|
||||||
|
);
|
||||||
|
assert.match(applied, /data-applied="zfi"/);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user