smartyfy.mrindigi.com

Web Development Pro | Lesson 058 | Capstone Build: Search, Filters, and State

Web Development Pro · Lesson 58 of 60

Module 6: Delivery and the capstone

In this lesson

Prerequisites and learning outcomes

Complete lesson 57 first. This lesson builds on modular rendering and url synchronization. By the end, you can connect hub filters to tested state transformations and shareable URLs. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Connect the directory through one state model

This snapshot activates the capstone's search interface. It loads local JSON, validates the complete contract, selects records with pure functions, and renders safe text. A controller owns the application state so controls, results, and URL filters do not each maintain incompatible copies of the same decision.

The state contains events, normalized filters, a loading status, and display density. The query and category are read from the current URL at startup. Density begins comfortable in this stage and lasts only for the current page. Persistent preferences are introduced separately in lesson 059.

Normalize input before using it

normalizeFilters accepts a query string, trims its outer whitespace, and limits it to eighty UTF-16 code units. It accepts only the three documented categories; anything else becomes all. This provides a predictable internal state even when someone edits a URL manually or supplies unexpected input types.

Selection compares lowercase titles and query text, combining that condition with category using AND. It returns a new array in the original record order. It does not mutate records or claim fuzzy matching. An empty query matches every title, and all means no category restriction.

const filters = { query: ' BIKE ', category: 'repair' };
const visible = selectEvents(events, filters);

The complete helper is supplied in state.mjs, alongside URL reading and writing functions. In the fixture, this selection produces only bike-basics. A craft category with the same query produces zero results, which catches an accidental OR between filter conditions.

Load relative to the module and validate the response

app.mjs requests new URL('./events.json', import.meta.url), making the data file's relationship to the module explicit. It checks response.ok before parsing JSON. The controller then validates the full array before entering ready state. A successful HTTP status does not by itself establish a valid event collection.

During loading, the static schedule remains visible and the enhancement controls stay hidden. If a request or validation fails, the page shows a useful explanation and Retry while retaining the static information. An error is not displayed as though a successful search found zero events.

The loader accepts an AbortSignal and the controller tracks a generation number. A new load aborts the earlier request where supported, while the generation check prevents an older result or error from overwriting newer state even if the underlying loader ignores cancellation. This combination separates efficiency from correctness.

Render only the selected view

renderCards creates list items, articles, headings, paragraphs, and time elements. Outside strings are assigned with textContent. The controller never builds a title into an HTML string. Each card retains its stable event id as data for inspection, while headings remain meaningful visitor-facing text.

The renderer formats dates with Intl.DateTimeFormat using an explicit UTC timezone and adds UTC to the displayed label. The original timestamp remains in the time element's datetime attribute. Published capacity and fictional access wording stay consistent with the static schedule, without implying live booking information.

renderView switches between fallback and enhanced sections according to status. Only a ready state hides the static schedule. A valid empty data array is still a successful load; it produces the clear no-match message. A malformed array produces an error and retains fallback, which is a different situation.

Keep event handling thin and deliberate

The form's submit handler prevents navigation and passes control values to controller.apply. The Reset button explicitly applies empty query and all categories. Because it is type=button, it does not depend on native form-reset timing. The controls themselves remain stable while result children are replaced. The controller requests control synchronization at initialization, Apply, Reset, and history restoration. Density-only and loading renders preserve an unfinished query or category draft instead of copying older committed filters over it.

The status region reports the number of fictional events or useful recovery wording. The intended behavior is to leave focus on the active control during ordinary filtering, rather than moving it into the first result on every Apply. Actual focus and announcements remain manual checks; the source design does not constitute observed assistive-technology evidence.

Make filter state shareable and navigable

writeFilters begins with the current URL, replaces only q and category, and preserves unrelated parameters and the fragment. Default filters are omitted so the ordinary directory URL stays concise. URLSearchParams handles encoding; a query containing an ampersand remains one value rather than becoming a second parameter.

A deliberate Apply pushes a new history entry only when the normalized URL changes. Reapplying the same filters does not create duplicates. The browser's popstate event calls restore, which reads the current URL and rerenders without pushing a new entry. Otherwise Back could create another entry and trap the visitor in a confusing loop.

Test pure rules and controlled connections

state.test.mjs covers normalization, selection, URL round trips, input preservation, and the explicit UTC suffix. controller.test.mjs covers loading, Apply, duplicate Apply, restore, reset, failures, retry, stale success, stale rejection, and disposal. Controlled promises make response ordering deterministic without a live server.

render.test.mjs uses a small operation recorder with visible helper definitions. It checks created structure, literal text assignment, replacement, empty results, and fallback transitions. It does not model a real DOM, CSS, focus, browser events, native form validation, or accessibility trees. These are useful code-level checks with explicitly limited claims.

Complete the real browser journey later

The authoring environment could not launch a browser, so event wiring, rendered layout, real history navigation, keyboard behavior, and announcements remain unverified here. The provided snapshot is complete enough to run those checks without depending on hidden helpers or earlier unpublished lesson files.

Worked practice

Worked exercise 1: Restore history without a loop

Task: Back changes the URL but results remain filtered by the newer choice. Worked answer: handle popstate by reading location.href into controller.restore and rendering that state. Do not call the Apply path that pushes another entry while processing navigation.

Worked exercise 2: Separate no match from bad data

Task: events.json contains a malformed timestamp. Worked answer: reject the loaded collection, show the failure explanation, and retain the static schedule. “No matching events” is appropriate only after valid data has been searched successfully.

Worked exercise 3: Guard a stale result

Task: A slow earlier request resolves after a successful retry. Worked answer: compare its generation with the latest load before accepting data. Abort helps cancel unnecessary work, but the generation guard also protects against loaders that do not honor cancellation.

Knowledge check

Question 1

Which component owns query and category decisions? A) Separate copies in every card. B) The controller's normalized state. C) The status text alone. D) The stylesheet's selected class alone.

Check question 1: answer and explanation

Answer: B. One state model keeps controls, URL, and results aligned.

Question 2

Why check response.ok before JSON parsing? A) Fetch can resolve for unsuccessful HTTP statuses. B) JSON parsing always checks authorization. C) It eliminates schema validation. D) It guarantees the body is current.

Check question 2: answer and explanation

Answer: A. HTTP success and valid application data are distinct checks.

Question 3

What should popstate restoration avoid? A) Reading the current URL. B) Updating visible controls. C) Pushing another history entry for the restored state. D) Selecting the corresponding records.

Check question 3: answer and explanation

Answer: C. Restoration should not create a new navigation loop.

Question 4

Why combine abort with a generation check? A) Abort guarantees the older server operation was reversed. B) A generation counter forces requests to finish in order. C) Abort alone guarantees every injected loader stops publishing. D) Cancellation may be ignored while stale results still need exclusion.

Check question 4: answer and explanation

Answer: D. The guard preserves latest-request correctness independently of cancellation.

Question 5

What remains outside the operation recorder? A) The assigned title string. B) Recorded child replacement. C) Real focus, layout, events, and assistive-technology behavior. D) The renderer's chosen tag names.

Check question 5: answer and explanation

Answer: C. Its implemented methods define a much narrower test scope.

Sources and further reading