Skip to content

Commit b3e0c89

Browse files
Corrige un problème sur la recherche en page d'accueil qui entre en conflit avec la recherche dans le menu (#1783)
* Corrige un problème sur la recherche en page d'accueil qui entre en conflit avec la recherche dans le menu * WIP * add e2e * Finish test * Fix test * Revert
1 parent 196a3f9 commit b3e0c89

File tree

9 files changed

+106
-23
lines changed

9 files changed

+106
-23
lines changed

core/context_processors.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,12 @@ def global_context(request) -> dict:
3939
if request.META.get("HTTP_HOST") not in settings.ASSISTANT["HOSTS"]:
4040
return base
4141

42+
search_form = SearchForm(prefix="header", initial={"id": "header"})
43+
home_search_form = SearchForm(prefix="home", initial={"id": "home"})
44+
4245
return {
4346
**base,
44-
"search_form": SearchForm(),
47+
"search_form": search_form,
48+
"home_search_form": home_search_form,
4549
**constants.ASSISTANT,
4650
}

e2e_tests/assistant.spec.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,57 @@ test("Le lien infotri est bien défini", async ({ page }) => {
3232
expect(href).toBe("https://www.ecologie.gouv.fr/info-tri")
3333
})
3434

35+
test(
36+
"Les deux recherches en page d'accueil fonctionnent",
37+
{
38+
annotation: [
39+
{
40+
type: "issue",
41+
description:
42+
"https://www.notion.so/accelerateur-transition-ecologique-ademe/Assistant-Probl-me-sur-la-double-recherche-en-page-d-accueil-22a6523d57d78057981df59c74704cf9?source=copy_link",
43+
},
44+
],
45+
},
46+
async ({ page }) => {
47+
// Navigate to the carte page
48+
await page.goto(`/`, { waitUntil: "domcontentloaded" })
49+
await hideDjangoToolbar(page)
50+
51+
await page.locator("#id_home-input").click()
52+
await page.locator("#id_home-input").pressSequentially("lave")
53+
// We expect at least on search result
54+
await page.waitForResponse(
55+
(response) =>
56+
response.url().includes("/assistant/recherche") && response.status() === 200,
57+
)
58+
expect(page.locator("#home [data-search-target=results] a").first()).toBeAttached()
59+
60+
await page.locator("#id_header-input").click()
61+
await page.waitForResponse(
62+
(response) =>
63+
response.url().includes("/assistant/recherche") && response.status() === 200,
64+
)
65+
expect(page.locator("#home [data-search-target=results] a")).toHaveCount(0)
66+
await page.locator("#id_header-input").pressSequentially("lave")
67+
await page.waitForResponse(
68+
(response) =>
69+
response.url().includes("/assistant/recherche") && response.status() === 200,
70+
)
71+
expect(page.locator("#home [data-search-target=results] a")).toHaveCount(0)
72+
expect(
73+
page.locator("#header [data-search-target=results] a").first(),
74+
).toBeAttached()
75+
76+
await page.locator("#id_home-input").click()
77+
await page.waitForResponse(
78+
(response) =>
79+
response.url().includes("/assistant/recherche") && response.status() === 200,
80+
)
81+
expect(page.locator("#home [data-search-target=results] a")).toHaveCount(0)
82+
expect(page.locator("#header [data-search-target=results] a")).toHaveCount(0)
83+
},
84+
)
85+
3586
test("Le tracking PostHog fonctionne comme prévu", async ({ page }) => {
3687
// Check that homepage scores 1
3788
await page.goto(`/`, { waitUntil: "domcontentloaded" })

package-lock.json

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
"eslint-config-prettier": "^10.1.5",
4646
"leaflet": "^1.9.4",
4747
"posthog-js": "^1.256.0",
48+
"stimulus-use": "^0.52.3",
4849
"tailwindcss": "^3.4.17"
4950
},
5051
"devDependencies": {

qfdmd/forms.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,10 @@ class SearchInput(forms.TextInput):
1919

2020

2121
class SearchForm(DsfrBaseForm):
22+
id = forms.CharField(required=False, widget=forms.HiddenInput())
2223
input = forms.CharField(
2324
help_text="Entrez un objet ou un déchet", required=False, widget=SearchInput
2425
)
25-
iframe = forms.BooleanField(
26-
required=False,
27-
help_text="Ce champ sert uniquement à faire persister le mode iframe d'une page"
28-
"à une recherche",
29-
widget=forms.HiddenInput,
30-
)
3126

3227
def search(self) -> dict[str, str]:
3328
search_query: str = self.cleaned_data.get("input")

qfdmd/views.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,16 @@ def get_assistant_script(request):
4747

4848

4949
def search_view(request) -> HttpResponse:
50-
form = SearchForm(request.GET)
51-
context = {}
50+
prefix_key = next(
51+
(key for key in request.GET.dict().keys() if key.endswith("-id")), ""
52+
)
53+
form_kwargs = {}
54+
55+
if prefix := request.GET[prefix_key]:
56+
form_kwargs.update(prefix=prefix, initial={"id": prefix})
57+
58+
form = SearchForm(request.GET, **form_kwargs)
59+
context = {"prefix": form_kwargs, "prefix_key": prefix_key}
5260
template_name = SEARCH_VIEW_TEMPLATE_NAME
5361

5462
if form.is_valid():

static/to_compile/controllers/assistant/search.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11
import { Controller } from "@hotwired/stimulus"
2+
import { ClickOutsideController } from "stimulus-use"
23

3-
export default class extends Controller<HTMLFormElement> {
4+
export default class extends ClickOutsideController {
45
declare readonly formTarget: HTMLFormElement
5-
static targets = ["form"]
6+
declare readonly resultsTarget: HTMLElement
7+
static targets = ["form", "results"]
68

79
submitForm() {
810
this.formTarget.requestSubmit()
911
}
1012

1113
submitFirstItem() {
12-
const firstResult = document.querySelector<HTMLAnchorElement>("#search-results > a")
14+
const firstResult = this.resultsTarget.querySelector<HTMLAnchorElement>("a")
1315
if (firstResult) {
1416
firstResult.click()
1517
}
1618
}
1719

1820
clear() {
19-
for (const inputElement of this.formTarget.querySelectorAll("input")) {
21+
for (const inputElement of this.formTarget.querySelectorAll("input[type=text]")) {
2022
inputElement.value = ""
2123
this.submitForm()
2224
}
2325
}
2426

2527
#move(direction: "up" | "down") {
26-
const searchResultAlreadyFocused = document.querySelector<HTMLAnchorElement>(
27-
"#search-results > a:focus",
28-
)
29-
let elementToFocus =
30-
document.querySelector<HTMLAnchorElement>("#search-results > a")
28+
const searchResultAlreadyFocused =
29+
this.resultsTarget.querySelector<HTMLAnchorElement>("a:focus")
30+
let elementToFocus = this.resultsTarget.querySelector<HTMLAnchorElement>("a")
3131

3232
if (searchResultAlreadyFocused) {
3333
searchResultAlreadyFocused.blur()

templates/components/search/view.html

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
<turbo-frame id="search">
1+
{% with id=search_form.id.value %}
2+
<turbo-frame id="{{ id }}">
23
<div
34
data-controller="search"
45
data-action="
6+
search:click:outside->search#clear:prevent
57
keydown.esc->search#clear:prevent
68
keydown.up->search#up:prevent
79
keydown.down->search#down:prevent"
@@ -16,7 +18,7 @@
1618
>
1719
<form
1820
data-search-target="form"
19-
data-turbo-frame="{{ id|default:'search-results' }}"
21+
data-turbo-frame="{{ id }}:search-results"
2022
action="{% url 'qfdmd:search' %}"
2123
class="qf-pl-4w {# should match the svg icon width #}
2224
qf-flex qf-flex-row-reverse qf-relative
@@ -25,7 +27,6 @@
2527
qf-content-center
2628
"
2729
>
28-
2930
{% for field in search_form %}
3031
{{ field }}
3132
{% endfor %}
@@ -45,7 +46,8 @@
4546
</form>
4647

4748
<turbo-frame
48-
id="search-results"
49+
id="{{ id }}:search-results"
50+
data-search-target="results"
4951
class="qf-flex qf-flex-col"
5052
>
5153
{% if search_form.results %}
@@ -56,3 +58,4 @@
5658
</turbo-frame>
5759
</div>
5860
</turbo-frame>
61+
{% endwith %}

templates/pages/home.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
{# search + patchwork #}
1515
<div class="qf-w-full qf-max-w-3xl qf-m-auto qf-relative qf-pb-6w">
1616
<div class="qf-absolute qf-left-0 qf-right-0 qf-top-0">
17-
{% include "components/search/view.html" with big=True id="search-home" %}
17+
{% include "components/search/view.html" with big=True search_form=home_search_form %}
1818
</div>
1919
</div>
2020

0 commit comments

Comments
 (0)