@skolo-saka/school-search 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -9
- package/dist/SchoolSearch.d.cts +45 -0
- package/dist/SchoolSearch.d.ts +1 -1
- package/dist/icons.d.cts +4 -0
- package/dist/index.cjs +18 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +18 -12
- package/dist/index.js.map +1 -1
- package/dist/styles.css +10 -3
- package/dist/types.d.cts +51 -0
- package/dist/useSchoolSearch.d.cts +24 -0
- package/dist/useSchoolSearch.d.ts +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# school-search
|
|
2
2
|
|
|
3
3
|
[](https://github.com/skolo-saka/school-search/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@skolo-saka/school-search)
|
|
4
5
|
[](LICENSE)
|
|
5
6
|
|
|
6
7
|
`@skolo-saka/school-search` is an accessible React and TypeScript combobox for finding a school as you type and picking it. It was extracted from the "Which school will you help?" search on [Skolo Saka](https://skolosaka.co.za)'s homepage, and works in any React 18 or 19 app.
|
|
7
8
|
|
|
8
|
-
**[Try the demo](https://skolo-saka.github.io/school-search/)
|
|
9
|
+
**[Try the demo](https://skolo-saka.github.io/school-search/)**, which searches the live Skolo Saka school directory. Type **sunnyside primary**: two real schools share that name, in Cape Town and Pretoria, and the one you pick is the one handed back, with a link to its page on the Skolo Saka website.
|
|
9
10
|
|
|
10
11
|
You supply two functions:
|
|
11
12
|
|
|
@@ -16,17 +17,15 @@ The component handles the rest: a 250 ms search delay and two-letter minimum, na
|
|
|
16
17
|
|
|
17
18
|
## Status
|
|
18
19
|
|
|
19
|
-
**
|
|
20
|
+
**Published on [npm](https://www.npmjs.com/package/@skolo-saka/school-search)** and used by the [Skolo Saka website](https://www.skolosaka.co.za)'s homepage search. Releases are listed on the [releases page](https://github.com/skolo-saka/school-search/releases). Each one is published from a version tag by GitHub Actions with npm provenance; see [RELEASING.md](RELEASING.md). The API may still change before 1.0. A change that can need work in your app gets a new minor version.
|
|
20
21
|
|
|
21
22
|
## Install
|
|
22
23
|
|
|
23
|
-
From the GitHub release tarball:
|
|
24
|
-
|
|
25
24
|
```bash
|
|
26
|
-
npm install
|
|
25
|
+
npm install @skolo-saka/school-search
|
|
27
26
|
```
|
|
28
27
|
|
|
29
|
-
React and React DOM 18 or later are peer dependencies. The package ships ES module and CommonJS builds, TypeScript declarations and one stylesheet.
|
|
28
|
+
React and React DOM 18 or later are peer dependencies. The package ships ES module and CommonJS builds, TypeScript declarations for each (`.d.ts` and `.d.cts`) and one stylesheet. The types work with TypeScript's `bundler`, `node16` and `nodenext` module resolution.
|
|
30
29
|
|
|
31
30
|
## Use it
|
|
32
31
|
|
|
@@ -79,6 +78,37 @@ export default function App() {
|
|
|
79
78
|
|
|
80
79
|
A school is `{ id, name, level?, town?, municipality?, province?, verified? }`. A `level` of `primary`, `high` or `combined` shows as "Primary school", "High school" or "Combined school". For a custom layout, the `useSchoolSearch` hook gives you the search state without the markup.
|
|
81
80
|
|
|
81
|
+
### Keyboard
|
|
82
|
+
|
|
83
|
+
The search box is an [editable combobox](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) with list autocomplete. Focus stays in the text box; `aria-activedescendant` points at the highlighted school.
|
|
84
|
+
|
|
85
|
+
| Key | List open | List closed (after Escape) |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| ArrowDown | Highlights the next school. Stops at the last one. | Opens the list on the first school. |
|
|
88
|
+
| ArrowUp | Highlights the previous school. Stops at the first one. | Opens the list on the last school. |
|
|
89
|
+
| Enter | Picks the highlighted school. | Same as "Find school": one match is picked, several go to `onSearchAll`. |
|
|
90
|
+
| Escape | Closes the list. The text stays. | Nothing. |
|
|
91
|
+
| Home / End | Move the text caret. The highlight stays where it is. | Move the text caret. |
|
|
92
|
+
| Tab | Leaves the box and closes the list without picking a school. | Leaves the box. |
|
|
93
|
+
|
|
94
|
+
The arrows do not wrap from the last school to the first. Home and End belong to the text box, as the ARIA Authoring Practices recommend for an editable combobox, so people can still edit their search while the list is open. The first school is highlighted when results arrive.
|
|
95
|
+
|
|
96
|
+
### Schools with the same name
|
|
97
|
+
|
|
98
|
+
School names are not unique. In the live demo, **sunnyside primary** finds two real Sunnyside Primary Schools, one in Cape Town and one in Pretoria. In testing mode, the fictional **Sunbird Primary School** results are in **Riverbend** and **Kopjeskloof**. The place line under each name tells them apart: by default, `schoolPlace` combines the level, town (or municipality when there is no town), and province. Return `town`, `municipality` and/or `province` from `searchSchools` so people can see which school they are choosing.
|
|
99
|
+
|
|
100
|
+
`onSelectSchool` receives the exact school object picked, including its `id` and any extra fields. Always use **`school.id`**, rather than `school.name`, to identify the selection in your app or navigate to its record.
|
|
101
|
+
|
|
102
|
+
If two schools share both a name and the same displayed place, those lines look the same; the component does not invent a distinction. Use `formatPlace` to add a suburb or school code supplied by your directory. For example, with the fictional data and functions above, you can append the unique id:
|
|
103
|
+
|
|
104
|
+
```tsx
|
|
105
|
+
<SchoolSearch
|
|
106
|
+
searchSchools={searchSchools}
|
|
107
|
+
onSelectSchool={school => console.log(school.id)}
|
|
108
|
+
formatPlace={school => `${schoolPlace(school)} · ${school.id}`}
|
|
109
|
+
/>
|
|
110
|
+
```
|
|
111
|
+
|
|
82
112
|
### Styles
|
|
83
113
|
|
|
84
114
|
Import `@skolo-saka/school-search/styles.css` once. Classes are prefixed `skolo-search`. Colours follow these CSS custom properties when the page defines them: `--brand`, `--brand-deep`, `--sun`, `--sun-deep`, `--ink`, `--muted`, `--line`, `--glass-tint`, `--radius-control`, `--shadow-3` and `--z-raised`; otherwise a default green and yellow apply. Any `--skolo-search-*` property can also be set on `.skolo-search`.
|
|
@@ -103,7 +133,48 @@ Run the demo at http://localhost:5173:
|
|
|
103
133
|
npm run demo
|
|
104
134
|
```
|
|
105
135
|
|
|
106
|
-
The demo imports `@skolo-saka/school-search` exactly as an app would (Vite points that name at `src/`)
|
|
136
|
+
The demo imports `@skolo-saka/school-search` exactly as an app would (Vite points that name at `src/`).
|
|
137
|
+
|
|
138
|
+
### Live search
|
|
139
|
+
|
|
140
|
+
By default the demo searches the **live Skolo Saka school directory** through the website's public API, `GET https://www.skolosaka.co.za/api/public/schools/search?q=<text>`. The API returns at most 10 real schools with public fields only: `id`, `name`, `town`, `municipality`, `province`, `level` and `verified`. The connection lives in the demo (`demo/src/liveSearch.ts`), not in the package. The package has no knowledge of Skolo Saka's backend, and any app supplies its own `searchSchools`.
|
|
141
|
+
|
|
142
|
+
- The request uses the `AbortSignal` the component passes, so a newer search cancels the older one.
|
|
143
|
+
- An answer without a `schools` array is treated as an error. Malformed schools in an answer are skipped.
|
|
144
|
+
- A failed request shows the error and **Try again**. It never falls back to fictional schools.
|
|
145
|
+
- Picking a school shows its name, place and ID, with a link to `https://www.skolosaka.co.za/school/<id>`.
|
|
146
|
+
- **Find school** with several matches opens the website's directory search (`/schools?q=`). The no-results and error messages link to the website's contact and donate pages.
|
|
147
|
+
|
|
148
|
+
Try **sunnyside primary** (two schools with the same name), **hoerskool ben vorster**, **st john's college** and **zzqqxx** (no matches).
|
|
149
|
+
|
|
150
|
+
#### Configuration
|
|
151
|
+
|
|
152
|
+
`VITE_SKOLO_SAKA_ORIGIN` chooses the website whose API and pages the demo uses. The default is production, `https://www.skolosaka.co.za`, and the GitHub Pages workflow sets it explicitly. Set it in the environment or in `demo/.env.local`.
|
|
153
|
+
|
|
154
|
+
- **Published demo (`npm run demo:build`):** the browser calls `<origin>/api/public/schools/search` directly. The API allows cross-origin requests only from `https://skolo-saka.github.io`.
|
|
155
|
+
- **Local demo (`npm run demo` or `vite preview`):** the browser calls the demo's own server, which forwards `/api/public/` to the origin. No CORS exception is needed.
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
# UAT: test data, and links open UAT school pages
|
|
159
|
+
VITE_SKOLO_SAKA_ORIGIN=https://skolo-saka-uat.azurewebsites.net npm run demo
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
# A website running locally on port 3000
|
|
164
|
+
VITE_SKOLO_SAKA_ORIGIN=http://localhost:3000 npm run demo
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
A built demo served from another local origin calls the website directly. That website must list the origin in `PUBLIC_API_DEV_ORIGINS`, which production ignores.
|
|
168
|
+
|
|
169
|
+
### Testing mode (fictional schools)
|
|
170
|
+
|
|
171
|
+
Choose **Testing mode: 8 fictional schools** under **Data source** to use made-up schools (`demo/src/schools.ts`). The simulation controls appear only in testing mode and affect only the fictional source:
|
|
172
|
+
|
|
173
|
+
- Try **sunbird** (same name, two towns) and **zzz** (no results).
|
|
174
|
+
- Choose "Every search fails", then press **Try again**.
|
|
175
|
+
- Choose "Slow short queries", then type **sun** and then **bird**. The late answer for "sun" is logged but not shown.
|
|
176
|
+
|
|
177
|
+
Switching between the live directory and testing mode clears the search and cancels any request in flight, so results from the two sources never mix. Fictional schools have no website page. The automated tests use fixtures only and never call the live API.
|
|
107
178
|
|
|
108
179
|
Run the checks that CI runs:
|
|
109
180
|
|
|
@@ -123,11 +194,16 @@ npm run build
|
|
|
123
194
|
npm run demo:build
|
|
124
195
|
```
|
|
125
196
|
|
|
126
|
-
`npm run build` writes the package to `dist/`; `npm run demo:build` writes the static demo to `demo/dist/`. `npm pack` builds and writes `skolo-saka-school-search-<version>.tgz`, which another app can install with `npm install ./skolo-saka-school-search-
|
|
197
|
+
`npm run build` writes the package to `dist/`; `npm run demo:build` writes the static demo to `demo/dist/`. `npm pack` builds and writes `skolo-saka-school-search-<version>.tgz`, which another app can install with `npm install ./skolo-saka-school-search-<version>.tgz`. `node scripts/check-package.mjs` packs the package and checks it in a clean app: its files, ES module and CommonJS builds, `styles.css` and TypeScript types.
|
|
198
|
+
|
|
199
|
+
## Related projects
|
|
200
|
+
|
|
201
|
+
- [school-directory](https://github.com/skolo-saka/school-directory): the open-source school directory behind Skolo Saka's search. It provides the PostgreSQL schema, the validated Department of Basic Education importer and a public search API you can connect to `searchSchools`.
|
|
202
|
+
- [Live demo](https://skolo-saka.github.io/school-search/): this component searching the real Skolo Saka directory.
|
|
127
203
|
|
|
128
204
|
## Contributing
|
|
129
205
|
|
|
130
|
-
See [CONTRIBUTING.md](CONTRIBUTING.md) for the fork, branch, test and pull-request workflow, and the [good first issues](https://github.com/skolo-saka/school-search/labels/good%20first%20issue). Everyone taking part follows the [code of conduct](CODE_OF_CONDUCT.md). Report security problems privately as described in [SECURITY.md](SECURITY.md).
|
|
206
|
+
Maintainers ([MAINTAINERS.md](MAINTAINERS.md)) release new versions as described in [RELEASING.md](RELEASING.md). See [CONTRIBUTING.md](CONTRIBUTING.md) for the fork, branch, test and pull-request workflow, and the [good first issues](https://github.com/skolo-saka/school-search/labels/good%20first%20issue). Everyone taking part follows the [code of conduct](CODE_OF_CONDUCT.md). Report security problems privately as described in [SECURITY.md](SECURITY.md).
|
|
131
207
|
|
|
132
208
|
## Licence
|
|
133
209
|
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types.cjs';
|
|
3
|
+
export declare const defaultMessages: SchoolSearchMessages;
|
|
4
|
+
export interface SchoolSearchProps<S extends School = School> {
|
|
5
|
+
/** Supplies the schools matching the typed text. */
|
|
6
|
+
searchSchools: SearchSchools<S>;
|
|
7
|
+
/** Receives the school the person picked (click, Enter on a highlighted school, or "Find school" with one match). */
|
|
8
|
+
onSelectSchool: (school: S) => void;
|
|
9
|
+
/**
|
|
10
|
+
* "Find school" (or Enter with nothing highlighted) when there are several matches, or while a search
|
|
11
|
+
* is loading or has failed. On the website this opens the full directory search. Without it, the
|
|
12
|
+
* button opens the results list instead.
|
|
13
|
+
*/
|
|
14
|
+
onSearchAll?: (query: string) => void;
|
|
15
|
+
/** Links shown inside the messages. Leave out to show the messages without links. */
|
|
16
|
+
links?: {
|
|
17
|
+
/** Shown after a failed search, e.g. donate without choosing a school. */
|
|
18
|
+
error?: FallbackLink | null;
|
|
19
|
+
/** Shown when nothing matches, e.g. "tell us about the school". Gets the trimmed search text. */
|
|
20
|
+
empty?: ((query: string) => FallbackLink | null) | null;
|
|
21
|
+
};
|
|
22
|
+
/** Renders a link, e.g. with Next.js `<Link>`. Default: a plain `<a>`. */
|
|
23
|
+
renderLink?: (link: {
|
|
24
|
+
href: string;
|
|
25
|
+
children: ReactNode;
|
|
26
|
+
}) => ReactNode;
|
|
27
|
+
/** Replace any of the text, e.g. for translations. */
|
|
28
|
+
messages?: Partial<SchoolSearchMessages>;
|
|
29
|
+
/** The line under a school's name. Default: "High school, Town, Province". */
|
|
30
|
+
formatPlace?: (school: S) => string;
|
|
31
|
+
/** Most results to show. Default 6. */
|
|
32
|
+
limit?: number;
|
|
33
|
+
/** Search delay after the last keystroke, in ms. Default 250. */
|
|
34
|
+
debounceMs?: number;
|
|
35
|
+
/** Shortest text that searches. Default 2. */
|
|
36
|
+
minChars?: number;
|
|
37
|
+
/** When the page URL has this hash (default '#find-school'), the box takes focus. null turns it off. */
|
|
38
|
+
focusHash?: string | null;
|
|
39
|
+
className?: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* "Which school will you help?" A combobox: type a school name or town, then pick a school with the
|
|
43
|
+
* mouse, or the arrow keys and Enter. The app decides where a picked school goes.
|
|
44
|
+
*/
|
|
45
|
+
export declare function SchoolSearch<S extends School = School>({ searchSchools, onSelectSchool, onSearchAll, links, renderLink, messages, formatPlace, limit, debounceMs, minChars, focusHash, className, }: SchoolSearchProps<S>): import("react").JSX.Element;
|
package/dist/SchoolSearch.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ReactNode } from 'react';
|
|
2
|
-
import type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types';
|
|
2
|
+
import type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types.js';
|
|
3
3
|
export declare const defaultMessages: SchoolSearchMessages;
|
|
4
4
|
export interface SchoolSearchProps<S extends School = School> {
|
|
5
5
|
/** Supplies the schools matching the typed text. */
|
package/dist/icons.d.cts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { SVGProps } from 'react';
|
|
2
|
+
export declare const SearchIcon: (props: SVGProps<SVGSVGElement>) => import("react").JSX.Element;
|
|
3
|
+
export declare const XIcon: (props: SVGProps<SVGSVGElement>) => import("react").JSX.Element;
|
|
4
|
+
export declare const BadgeCheckIcon: (props: SVGProps<SVGSVGElement>) => import("react").JSX.Element;
|
package/dist/index.cjs
CHANGED
|
@@ -127,6 +127,16 @@ var defaultMessages = {
|
|
|
127
127
|
announceError: "We couldn\u2019t load schools"
|
|
128
128
|
};
|
|
129
129
|
var plainLink = ({ href, children }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("a", { href, children });
|
|
130
|
+
function NameWithBadge({ name, badge }) {
|
|
131
|
+
const split = name.trimEnd().lastIndexOf(" ") + 1;
|
|
132
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
|
|
133
|
+
name.slice(0, split),
|
|
134
|
+
/* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "skolo-search__name-end", children: [
|
|
135
|
+
name.slice(split),
|
|
136
|
+
badge
|
|
137
|
+
] })
|
|
138
|
+
] });
|
|
139
|
+
}
|
|
130
140
|
function SchoolSearch({
|
|
131
141
|
searchSchools,
|
|
132
142
|
onSelectSchool,
|
|
@@ -176,16 +186,15 @@ function SchoolSearch({
|
|
|
176
186
|
pick(results[active]);
|
|
177
187
|
return;
|
|
178
188
|
}
|
|
179
|
-
if (state !== "results") return;
|
|
180
|
-
|
|
181
|
-
|
|
189
|
+
if (state !== "results" || e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
|
|
190
|
+
e.preventDefault();
|
|
191
|
+
const down = e.key === "ArrowDown";
|
|
192
|
+
if (!open) {
|
|
182
193
|
setOpen(true);
|
|
183
|
-
setActive(
|
|
184
|
-
|
|
185
|
-
if (e.key === "ArrowUp") {
|
|
186
|
-
e.preventDefault();
|
|
187
|
-
setActive((i) => Math.max(0, i - 1));
|
|
194
|
+
setActive(down ? 0 : results.length - 1);
|
|
195
|
+
return;
|
|
188
196
|
}
|
|
197
|
+
setActive((i) => down ? Math.min(results.length - 1, i + 1) : Math.max(0, i - 1));
|
|
189
198
|
}
|
|
190
199
|
function find(e) {
|
|
191
200
|
e.preventDefault();
|
|
@@ -268,10 +277,7 @@ function SchoolSearch({
|
|
|
268
277
|
pick(school);
|
|
269
278
|
},
|
|
270
279
|
children: [
|
|
271
|
-
/* @__PURE__ */ (0, import_jsx_runtime2.
|
|
272
|
-
school.name,
|
|
273
|
-
school.verified && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(BadgeCheckIcon, { role: "img", "aria-label": t.verified })
|
|
274
|
-
] }),
|
|
280
|
+
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: school.verified ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(NameWithBadge, { name: school.name, badge: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(BadgeCheckIcon, { role: "img", "aria-label": t.verified }) }) : school.name }),
|
|
275
281
|
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: formatPlace(school) })
|
|
276
282
|
]
|
|
277
283
|
},
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/SchoolSearch.tsx","../src/useSchoolSearch.ts","../src/icons.tsx"],"sourcesContent":["export { SchoolSearch, defaultMessages } from './SchoolSearch';\nexport type { SchoolSearchProps } from './SchoolSearch';\nexport { useSchoolSearch, schoolPlace } from './useSchoolSearch';\nexport type { UseSchoolSearchOptions } from './useSchoolSearch';\nexport type { School, SearchSchools, SearchState, FallbackLink, SchoolSearchMessages } from './types';\n","import { useEffect, useId, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from 'react';\nimport { schoolPlace, useSchoolSearch } from './useSchoolSearch';\nimport { BadgeCheckIcon, SearchIcon, XIcon } from './icons';\nimport type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types';\n\nexport const defaultMessages: SchoolSearchMessages = {\n label: 'Search for a school',\n placeholder: 'School name or town',\n submit: 'Find school',\n clear: 'Clear search',\n listLabel: 'Schools',\n verified: 'Verified',\n loading: 'Searching schools…',\n retry: 'Try again',\n error: ({ retry, link }) => <>We couldn’t load schools. {retry}{link ? <>, or {link}</> : null}.</>,\n empty: ({ query, link }) => <>No school matches “{query}”. Try fewer words or the town name{link ? <>, or {link}</> : null}.</>,\n announceResults: count => `${count} ${count === 1 ? 'school' : 'schools'} found. Choose one to see its page.`,\n announceEmpty: 'No schools found',\n announceError: 'We couldn’t load schools',\n};\n\nexport interface SchoolSearchProps<S extends School = School> {\n /** Supplies the schools matching the typed text. */\n searchSchools: SearchSchools<S>;\n /** Receives the school the person picked (click, Enter on a highlighted school, or \"Find school\" with one match). */\n onSelectSchool: (school: S) => void;\n /**\n * \"Find school\" (or Enter with nothing highlighted) when there are several matches, or while a search\n * is loading or has failed. On the website this opens the full directory search. Without it, the\n * button opens the results list instead.\n */\n onSearchAll?: (query: string) => void;\n /** Links shown inside the messages. Leave out to show the messages without links. */\n links?: {\n /** Shown after a failed search, e.g. donate without choosing a school. */\n error?: FallbackLink | null;\n /** Shown when nothing matches, e.g. \"tell us about the school\". Gets the trimmed search text. */\n empty?: ((query: string) => FallbackLink | null) | null;\n };\n /** Renders a link, e.g. with Next.js `<Link>`. Default: a plain `<a>`. */\n renderLink?: (link: { href: string; children: ReactNode }) => ReactNode;\n /** Replace any of the text, e.g. for translations. */\n messages?: Partial<SchoolSearchMessages>;\n /** The line under a school's name. Default: \"High school, Town, Province\". */\n formatPlace?: (school: S) => string;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Search delay after the last keystroke, in ms. Default 250. */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n /** When the page URL has this hash (default '#find-school'), the box takes focus. null turns it off. */\n focusHash?: string | null;\n className?: string;\n}\n\nconst plainLink = ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>;\n\n/**\n * \"Which school will you help?\" A combobox: type a school name or town, then pick a school with the\n * mouse, or the arrow keys and Enter. The app decides where a picked school goes.\n */\nexport function SchoolSearch<S extends School = School>({\n searchSchools, onSelectSchool, onSearchAll, links, renderLink = plainLink, messages, formatPlace = schoolPlace,\n limit, debounceMs, minChars = 2, focusHash = '#find-school', className,\n}: SchoolSearchProps<S>) {\n const t = { ...defaultMessages, ...messages };\n const id = useId();\n const listId = `${id}-schools`;\n const { query, setQuery, state, results, retry } = useSchoolSearch<S>({ searchSchools, limit, debounceMs, minChars });\n const [active, setActive] = useState(-1);\n useEffect(() => setActive(results.length ? 0 : -1), [results]);\n const [open, setOpen] = useState(false);\n const input = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (!focusHash) return;\n const focusFromHash = () => { if (window.location.hash === focusHash) input.current?.focus({ preventScroll: true }); };\n focusFromHash();\n window.addEventListener('hashchange', focusFromHash);\n return () => window.removeEventListener('hashchange', focusFromHash);\n }, [focusHash]);\n\n function pick(school: S) { setOpen(false); onSelectSchool(school); }\n function clear() { setQuery(''); requestAnimationFrame(() => input.current?.focus()); }\n\n function onKey(e: KeyboardEvent<HTMLInputElement>) {\n if (e.key === 'Escape') { setOpen(false); return; }\n // Enter with a school highlighted in the open list picks that school.\n if (e.key === 'Enter' && open && state === 'results' && results[active]) { e.preventDefault(); pick(results[active]); return; }\n if (state !== 'results') return;\n if (e.key === 'ArrowDown') { e.preventDefault(); setOpen(true); setActive(i => Math.min(results.length - 1, i + 1)); }\n if (e.key === 'ArrowUp') { e.preventDefault(); setActive(i => Math.max(0, i - 1)); }\n }\n\n // \"Find school\" (or Enter without a highlighted school): one match picks that school; several go to\n // onSearchAll. No matches searches again. While searching or after a failure, onSearchAll too.\n function find(e: FormEvent<HTMLFormElement>) {\n e.preventDefault();\n const term = query.trim();\n if (term.length < minChars) { input.current?.focus(); return; }\n if (state === 'results' && results.length === 1) { pick(results[0]); return; }\n if (state === 'empty' || (state === 'error' && !onSearchAll)) { retry(); setOpen(true); input.current?.focus(); return; }\n if (onSearchAll) { setOpen(false); onSearchAll(term); return; }\n setOpen(true); input.current?.focus();\n }\n\n const typed = query.trim();\n const showList = open && state !== 'idle';\n const errorLink = links?.error ? renderLink({ href: links.error.href, children: links.error.label }) : null;\n const emptyFallback = state === 'empty' && links?.empty ? links.empty(typed) : null;\n const emptyLink = emptyFallback ? renderLink({ href: emptyFallback.href, children: emptyFallback.label }) : null;\n const retryButton = <button type=\"button\" className=\"skolo-search__retry\" onClick={() => { retry(); input.current?.focus(); }}>{t.retry}</button>;\n\n return <form className={`skolo-search${className ? ` ${className}` : ''}`} role=\"search\" onSubmit={find}>\n <label htmlFor={`${id}-input`} className=\"skolo-search__sr-only\">{t.label}</label>\n <div className={`skolo-search__box${showList ? ' skolo-search__box--open' : ''}`}>\n <SearchIcon aria-hidden=\"true\" className=\"skolo-search__icon\" />\n <input ref={input} id={`${id}-input`} role=\"combobox\" aria-expanded={showList} aria-controls={listId} aria-autocomplete=\"list\"\n aria-activedescendant={showList && state === 'results' && active >= 0 ? `${listId}-${active}` : undefined}\n value={query} placeholder={t.placeholder} autoComplete=\"off\" spellCheck={false}\n onChange={e => { setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={onKey}\n onBlur={() => setTimeout(() => setOpen(false), 150)} />\n {query && <button type=\"button\" className=\"skolo-search__clear\" aria-label={t.clear} onClick={clear}><XIcon aria-hidden=\"true\" /></button>}\n <button type=\"submit\" className=\"skolo-search__go\">{t.submit}</button>\n </div>\n {/* Pressing inside the panel keeps focus in the box, so the panel stays open for its links and buttons. */}\n {showList && <div className=\"skolo-search__panel\" onMouseDown={e => e.preventDefault()}>\n {state === 'loading' && <p className=\"skolo-search__status\">{t.loading}</p>}\n {state === 'error' && <p className=\"skolo-search__status\">{t.error({ retry: retryButton, link: errorLink })}</p>}\n {state === 'empty' && <p className=\"skolo-search__status\">{t.empty({ query: typed, link: emptyLink })}</p>}\n {state === 'results' && <ul id={listId} role=\"listbox\" aria-label={t.listLabel}>\n {results.map((school, i) => <li key={school.id} id={`${listId}-${i}`} role=\"option\" aria-selected={i === active}\n className={i === active ? 'skolo-search__option--active' : undefined}\n onMouseEnter={() => setActive(i)} onMouseDown={e => { e.preventDefault(); pick(school); }}>\n <strong>{school.name}{school.verified && <BadgeCheckIcon role=\"img\" aria-label={t.verified} />}</strong>\n <span>{formatPlace(school)}</span>\n </li>)}\n </ul>}\n </div>}\n <p className=\"skolo-search__sr-only\" aria-live=\"polite\">{state === 'results' ? t.announceResults(results.length) : state === 'empty' ? t.announceEmpty : state === 'error' ? t.announceError : ''}</p>\n </form>;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { School, SearchSchools, SearchState } from './types';\n\nexport interface UseSchoolSearchOptions<S extends School> {\n searchSchools: SearchSchools<S>;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Wait after the last keystroke before searching, in ms. Default 250 (the homepage's delay). */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n}\n\nconst LEVEL: Record<string, string> = { primary: 'Primary school', high: 'High school', combined: 'Combined school' };\n\n/** \"High school, Polokwane, Limpopo\": the line under a school's name in the results. */\nexport const schoolPlace = (s: Pick<School, 'level' | 'town' | 'municipality' | 'province'>) =>\n [s.level ? LEVEL[s.level] ?? s.level : null, [s.town || s.municipality, s.province].filter(Boolean).join(', ')]\n .filter(Boolean)\n .join(', ');\n\n/**\n * Searches as the person types, keeping only the answer to the latest query: every new query (or\n * retry) bumps a sequence number and aborts the previous request, and a response is applied only if\n * its sequence number is still the current one. retry() runs the same search again.\n */\nexport function useSchoolSearch<S extends School>({ searchSchools, limit = 6, debounceMs = 250, minChars = 2 }: UseSchoolSearchOptions<S>) {\n const [query, setQuery] = useState('');\n const [state, setState] = useState<SearchState>('idle');\n const [results, setResults] = useState<S[]>([]);\n const [attempt, setAttempt] = useState(0);\n const request = useRef(0);\n // The latest search function, so an app passing a new function each render doesn't restart searches.\n const search = useRef(searchSchools);\n search.current = searchSchools;\n\n useEffect(() => {\n const term = query.trim();\n if (term.length < minChars) { request.current++; setState('idle'); setResults([]); return; }\n const seq = ++request.current;\n const controller = new AbortController();\n setState('loading');\n const timer = setTimeout(async () => {\n try {\n const found = await search.current(term, { signal: controller.signal });\n if (seq !== request.current) return;\n const items = (found || []).slice(0, limit);\n setResults(items);\n setState(items.length ? 'results' : 'empty');\n } catch {\n if (seq === request.current) { setResults([]); setState('error'); }\n }\n }, debounceMs);\n return () => { clearTimeout(timer); controller.abort(); };\n }, [query, attempt, limit, debounceMs, minChars]);\n\n return { query, setQuery, state, results, retry: () => setAttempt(n => n + 1) };\n}\n","import type { SVGProps } from 'react';\n\n// Search, X and BadgeCheck from Lucide (https://lucide.dev, ISC licence), inlined so the package has\n// no icon dependency. They match the lucide-react icons the website used. Licence: THIRD_PARTY_NOTICES.md.\nconst base = { xmlns: 'http://www.w3.org/2000/svg', width: 24, height: 24, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' } as const;\n\nexport const SearchIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"m21 21-4.34-4.34\" /><circle cx=\"11\" cy=\"11\" r=\"8\" /></svg>;\n\nexport const XIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M18 6 6 18\" /><path d=\"m6 6 12 12\" /></svg>;\n\nexport const BadgeCheckIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 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AE,eAAe;AAAG,iBAAK,MAAM;AAAA,UAAG;AAAA,UACxF;AAAA,0DAAC,YAAQ;AAAA,qBAAO;AAAA,cAAM,OAAO,YAAY,6CAAC,kBAAe,MAAK,OAAM,cAAY,EAAE,UAAU;AAAA,eAAG;AAAA,YAC/F,6CAAC,UAAM,sBAAY,MAAM,GAAE;AAAA;AAAA;AAAA,QAJQ,OAAO;AAAA,MAK5C,CAAK,GACP;AAAA,OACF;AAAA,IACA,6CAAC,OAAE,WAAU,yBAAwB,aAAU,UAAU,oBAAU,YAAY,EAAE,gBAAgB,QAAQ,MAAM,IAAI,UAAU,UAAU,EAAE,gBAAgB,UAAU,UAAU,EAAE,gBAAgB,IAAG;AAAA,KACpM;AACF;","names":["import_react","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/SchoolSearch.tsx","../src/useSchoolSearch.ts","../src/icons.tsx"],"sourcesContent":["export { SchoolSearch, defaultMessages } from './SchoolSearch.js';\nexport type { SchoolSearchProps } from './SchoolSearch.js';\nexport { useSchoolSearch, schoolPlace } from './useSchoolSearch.js';\nexport type { UseSchoolSearchOptions } from './useSchoolSearch.js';\nexport type { School, SearchSchools, SearchState, FallbackLink, SchoolSearchMessages } from './types.js';\n","import { useEffect, useId, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from 'react';\nimport { schoolPlace, useSchoolSearch } from './useSchoolSearch.js';\nimport { BadgeCheckIcon, SearchIcon, XIcon } from './icons.js';\nimport type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types.js';\n\nexport const defaultMessages: SchoolSearchMessages = {\n label: 'Search for a school',\n placeholder: 'School name or town',\n submit: 'Find school',\n clear: 'Clear search',\n listLabel: 'Schools',\n verified: 'Verified',\n loading: 'Searching schools…',\n retry: 'Try again',\n error: ({ retry, link }) => <>We couldn’t load schools. {retry}{link ? <>, or {link}</> : null}.</>,\n empty: ({ query, link }) => <>No school matches “{query}”. Try fewer words or the town name{link ? <>, or {link}</> : null}.</>,\n announceResults: count => `${count} ${count === 1 ? 'school' : 'schools'} found. Choose one to see its page.`,\n announceEmpty: 'No schools found',\n announceError: 'We couldn’t load schools',\n};\n\nexport interface SchoolSearchProps<S extends School = School> {\n /** Supplies the schools matching the typed text. */\n searchSchools: SearchSchools<S>;\n /** Receives the school the person picked (click, Enter on a highlighted school, or \"Find school\" with one match). */\n onSelectSchool: (school: S) => void;\n /**\n * \"Find school\" (or Enter with nothing highlighted) when there are several matches, or while a search\n * is loading or has failed. On the website this opens the full directory search. Without it, the\n * button opens the results list instead.\n */\n onSearchAll?: (query: string) => void;\n /** Links shown inside the messages. Leave out to show the messages without links. */\n links?: {\n /** Shown after a failed search, e.g. donate without choosing a school. */\n error?: FallbackLink | null;\n /** Shown when nothing matches, e.g. \"tell us about the school\". Gets the trimmed search text. */\n empty?: ((query: string) => FallbackLink | null) | null;\n };\n /** Renders a link, e.g. with Next.js `<Link>`. Default: a plain `<a>`. */\n renderLink?: (link: { href: string; children: ReactNode }) => ReactNode;\n /** Replace any of the text, e.g. for translations. */\n messages?: Partial<SchoolSearchMessages>;\n /** The line under a school's name. Default: \"High school, Town, Province\". */\n formatPlace?: (school: S) => string;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Search delay after the last keystroke, in ms. Default 250. */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n /** When the page URL has this hash (default '#find-school'), the box takes focus. null turns it off. */\n focusHash?: string | null;\n className?: string;\n}\n\nconst plainLink = ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>;\n\n/** A name with its badge, the badge kept on one line with the last word so it never wraps alone. */\nfunction NameWithBadge({ name, badge }: { name: string; badge: ReactNode }) {\n const split = name.trimEnd().lastIndexOf(' ') + 1;\n return <>{name.slice(0, split)}<span className=\"skolo-search__name-end\">{name.slice(split)}{badge}</span></>;\n}\n\n/**\n * \"Which school will you help?\" A combobox: type a school name or town, then pick a school with the\n * mouse, or the arrow keys and Enter. The app decides where a picked school goes.\n */\nexport function SchoolSearch<S extends School = School>({\n searchSchools, onSelectSchool, onSearchAll, links, renderLink = plainLink, messages, formatPlace = schoolPlace,\n limit, debounceMs, minChars = 2, focusHash = '#find-school', className,\n}: SchoolSearchProps<S>) {\n const t = { ...defaultMessages, ...messages };\n const id = useId();\n const listId = `${id}-schools`;\n const { query, setQuery, state, results, retry } = useSchoolSearch<S>({ searchSchools, limit, debounceMs, minChars });\n const [active, setActive] = useState(-1);\n useEffect(() => setActive(results.length ? 0 : -1), [results]);\n const [open, setOpen] = useState(false);\n const input = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (!focusHash) return;\n const focusFromHash = () => { if (window.location.hash === focusHash) input.current?.focus({ preventScroll: true }); };\n focusFromHash();\n window.addEventListener('hashchange', focusFromHash);\n return () => window.removeEventListener('hashchange', focusFromHash);\n }, [focusHash]);\n\n function pick(school: S) { setOpen(false); onSelectSchool(school); }\n function clear() { setQuery(''); requestAnimationFrame(() => input.current?.focus()); }\n\n function onKey(e: KeyboardEvent<HTMLInputElement>) {\n if (e.key === 'Escape') { setOpen(false); return; }\n // Enter with a school highlighted in the open list picks that school.\n if (e.key === 'Enter' && open && state === 'results' && results[active]) { e.preventDefault(); pick(results[active]); return; }\n if (state !== 'results' || (e.key !== 'ArrowDown' && e.key !== 'ArrowUp')) return;\n // Home and End are left to the text box, where they move the caret (the ARIA editable combobox pattern).\n e.preventDefault();\n const down = e.key === 'ArrowDown';\n // On a closed list, an arrow key opens it: ArrowDown on the first school, ArrowUp on the last.\n // The hidden highlight never moves, so every key press has a visible, announced result.\n if (!open) { setOpen(true); setActive(down ? 0 : results.length - 1); return; }\n // In the open list the arrows stop at the first and last school; they do not wrap.\n setActive(i => (down ? Math.min(results.length - 1, i + 1) : Math.max(0, i - 1)));\n }\n\n // \"Find school\" (or Enter without a highlighted school): one match picks that school; several go to\n // onSearchAll. No matches searches again. While searching or after a failure, onSearchAll too.\n function find(e: FormEvent<HTMLFormElement>) {\n e.preventDefault();\n const term = query.trim();\n if (term.length < minChars) { input.current?.focus(); return; }\n if (state === 'results' && results.length === 1) { pick(results[0]); return; }\n if (state === 'empty' || (state === 'error' && !onSearchAll)) { retry(); setOpen(true); input.current?.focus(); return; }\n if (onSearchAll) { setOpen(false); onSearchAll(term); return; }\n setOpen(true); input.current?.focus();\n }\n\n const typed = query.trim();\n const showList = open && state !== 'idle';\n const errorLink = links?.error ? renderLink({ href: links.error.href, children: links.error.label }) : null;\n const emptyFallback = state === 'empty' && links?.empty ? links.empty(typed) : null;\n const emptyLink = emptyFallback ? renderLink({ href: emptyFallback.href, children: emptyFallback.label }) : null;\n const retryButton = <button type=\"button\" className=\"skolo-search__retry\" onClick={() => { retry(); input.current?.focus(); }}>{t.retry}</button>;\n\n return <form className={`skolo-search${className ? ` ${className}` : ''}`} role=\"search\" onSubmit={find}>\n <label htmlFor={`${id}-input`} className=\"skolo-search__sr-only\">{t.label}</label>\n <div className={`skolo-search__box${showList ? ' skolo-search__box--open' : ''}`}>\n <SearchIcon aria-hidden=\"true\" className=\"skolo-search__icon\" />\n <input ref={input} id={`${id}-input`} role=\"combobox\" aria-expanded={showList} aria-controls={listId} aria-autocomplete=\"list\"\n aria-activedescendant={showList && state === 'results' && active >= 0 ? `${listId}-${active}` : undefined}\n value={query} placeholder={t.placeholder} autoComplete=\"off\" spellCheck={false}\n onChange={e => { setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={onKey}\n onBlur={() => setTimeout(() => setOpen(false), 150)} />\n {query && <button type=\"button\" className=\"skolo-search__clear\" aria-label={t.clear} onClick={clear}><XIcon aria-hidden=\"true\" /></button>}\n <button type=\"submit\" className=\"skolo-search__go\">{t.submit}</button>\n </div>\n {/* Pressing inside the panel keeps focus in the box, so the panel stays open for its links and buttons. */}\n {showList && <div className=\"skolo-search__panel\" onMouseDown={e => e.preventDefault()}>\n {state === 'loading' && <p className=\"skolo-search__status\">{t.loading}</p>}\n {state === 'error' && <p className=\"skolo-search__status\">{t.error({ retry: retryButton, link: errorLink })}</p>}\n {state === 'empty' && <p className=\"skolo-search__status\">{t.empty({ query: typed, link: emptyLink })}</p>}\n {state === 'results' && <ul id={listId} role=\"listbox\" aria-label={t.listLabel}>\n {results.map((school, i) => <li key={school.id} id={`${listId}-${i}`} role=\"option\" aria-selected={i === active}\n className={i === active ? 'skolo-search__option--active' : undefined}\n onMouseEnter={() => setActive(i)} onMouseDown={e => { e.preventDefault(); pick(school); }}>\n <strong>{school.verified ? <NameWithBadge name={school.name} badge={<BadgeCheckIcon role=\"img\" aria-label={t.verified} />} /> : school.name}</strong>\n <span>{formatPlace(school)}</span>\n </li>)}\n </ul>}\n </div>}\n <p className=\"skolo-search__sr-only\" aria-live=\"polite\">{state === 'results' ? t.announceResults(results.length) : state === 'empty' ? t.announceEmpty : state === 'error' ? t.announceError : ''}</p>\n </form>;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { School, SearchSchools, SearchState } from './types.js';\n\nexport interface UseSchoolSearchOptions<S extends School> {\n searchSchools: SearchSchools<S>;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Wait after the last keystroke before searching, in ms. Default 250 (the homepage's delay). */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n}\n\nconst LEVEL: Record<string, string> = { primary: 'Primary school', high: 'High school', combined: 'Combined school' };\n\n/** \"High school, Polokwane, Limpopo\": the line under a school's name in the results. */\nexport const schoolPlace = (s: Pick<School, 'level' | 'town' | 'municipality' | 'province'>) =>\n [s.level ? LEVEL[s.level] ?? s.level : null, [s.town || s.municipality, s.province].filter(Boolean).join(', ')]\n .filter(Boolean)\n .join(', ');\n\n/**\n * Searches as the person types, keeping only the answer to the latest query: every new query (or\n * retry) bumps a sequence number and aborts the previous request, and a response is applied only if\n * its sequence number is still the current one. retry() runs the same search again.\n */\nexport function useSchoolSearch<S extends School>({ searchSchools, limit = 6, debounceMs = 250, minChars = 2 }: UseSchoolSearchOptions<S>) {\n const [query, setQuery] = useState('');\n const [state, setState] = useState<SearchState>('idle');\n const [results, setResults] = useState<S[]>([]);\n const [attempt, setAttempt] = useState(0);\n const request = useRef(0);\n // The latest search function, so an app passing a new function each render doesn't restart searches.\n const search = useRef(searchSchools);\n search.current = searchSchools;\n\n useEffect(() => {\n const term = query.trim();\n if (term.length < minChars) { request.current++; setState('idle'); setResults([]); return; }\n const seq = ++request.current;\n const controller = new AbortController();\n setState('loading');\n const timer = setTimeout(async () => {\n try {\n const found = await search.current(term, { signal: controller.signal });\n if (seq !== request.current) return;\n const items = (found || []).slice(0, limit);\n setResults(items);\n setState(items.length ? 'results' : 'empty');\n } catch {\n if (seq === request.current) { setResults([]); setState('error'); }\n }\n }, debounceMs);\n return () => { clearTimeout(timer); controller.abort(); };\n }, [query, attempt, limit, debounceMs, minChars]);\n\n return { query, setQuery, state, results, retry: () => setAttempt(n => n + 1) };\n}\n","import type { SVGProps } from 'react';\n\n// Search, X and BadgeCheck from Lucide (https://lucide.dev, ISC licence), inlined so the package has\n// no icon dependency. They match the lucide-react icons the website used. Licence: THIRD_PARTY_NOTICES.md.\nconst base = { xmlns: 'http://www.w3.org/2000/svg', width: 24, height: 24, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' } as const;\n\nexport const SearchIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"m21 21-4.34-4.34\" /><circle cx=\"11\" cy=\"11\" r=\"8\" /></svg>;\n\nexport const XIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M18 6 6 18\" /><path d=\"m6 6 12 12\" /></svg>;\n\nexport const BadgeCheckIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6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AI,CAAC,QAAQ,MAAM;AAAA,QAAC;AAAA;AAAA,UAAmB,IAAI,GAAG,MAAM,IAAI,CAAC;AAAA,UAAI,MAAK;AAAA,UAAS,iBAAe,MAAM;AAAA,UACvG,WAAW,MAAM,SAAS,iCAAiC;AAAA,UAC3D,cAAc,MAAM,UAAU,CAAC;AAAA,UAAG,aAAa,OAAK;AAAE,cAAE,eAAe;AAAG,iBAAK,MAAM;AAAA,UAAG;AAAA,UACxF;AAAA,yDAAC,YAAQ,iBAAO,WAAW,6CAAC,iBAAc,MAAM,OAAO,MAAM,OAAO,6CAAC,kBAAe,MAAK,OAAM,cAAY,EAAE,UAAU,GAAI,IAAK,OAAO,MAAK;AAAA,YAC5I,6CAAC,UAAM,sBAAY,MAAM,GAAE;AAAA;AAAA;AAAA,QAJQ,OAAO;AAAA,MAK5C,CAAK,GACP;AAAA,OACF;AAAA,IACA,6CAAC,OAAE,WAAU,yBAAwB,aAAU,UAAU,oBAAU,YAAY,EAAE,gBAAgB,QAAQ,MAAM,IAAI,UAAU,UAAU,EAAE,gBAAgB,UAAU,UAAU,EAAE,gBAAgB,IAAG;AAAA,KACpM;AACF;","names":["import_react","import_jsx_runtime"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { SchoolSearch, defaultMessages } from './SchoolSearch.cjs';
|
|
2
|
+
export type { SchoolSearchProps } from './SchoolSearch.cjs';
|
|
3
|
+
export { useSchoolSearch, schoolPlace } from './useSchoolSearch.cjs';
|
|
4
|
+
export type { UseSchoolSearchOptions } from './useSchoolSearch.cjs';
|
|
5
|
+
export type { School, SearchSchools, SearchState, FallbackLink, SchoolSearchMessages } from './types.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { SchoolSearch, defaultMessages } from './SchoolSearch';
|
|
2
|
-
export type { SchoolSearchProps } from './SchoolSearch';
|
|
3
|
-
export { useSchoolSearch, schoolPlace } from './useSchoolSearch';
|
|
4
|
-
export type { UseSchoolSearchOptions } from './useSchoolSearch';
|
|
5
|
-
export type { School, SearchSchools, SearchState, FallbackLink, SchoolSearchMessages } from './types';
|
|
1
|
+
export { SchoolSearch, defaultMessages } from './SchoolSearch.js';
|
|
2
|
+
export type { SchoolSearchProps } from './SchoolSearch.js';
|
|
3
|
+
export { useSchoolSearch, schoolPlace } from './useSchoolSearch.js';
|
|
4
|
+
export type { UseSchoolSearchOptions } from './useSchoolSearch.js';
|
|
5
|
+
export type { School, SearchSchools, SearchState, FallbackLink, SchoolSearchMessages } from './types.js';
|
package/dist/index.js
CHANGED
|
@@ -99,6 +99,16 @@ var defaultMessages = {
|
|
|
99
99
|
announceError: "We couldn\u2019t load schools"
|
|
100
100
|
};
|
|
101
101
|
var plainLink = ({ href, children }) => /* @__PURE__ */ jsx2("a", { href, children });
|
|
102
|
+
function NameWithBadge({ name, badge }) {
|
|
103
|
+
const split = name.trimEnd().lastIndexOf(" ") + 1;
|
|
104
|
+
return /* @__PURE__ */ jsxs2(Fragment, { children: [
|
|
105
|
+
name.slice(0, split),
|
|
106
|
+
/* @__PURE__ */ jsxs2("span", { className: "skolo-search__name-end", children: [
|
|
107
|
+
name.slice(split),
|
|
108
|
+
badge
|
|
109
|
+
] })
|
|
110
|
+
] });
|
|
111
|
+
}
|
|
102
112
|
function SchoolSearch({
|
|
103
113
|
searchSchools,
|
|
104
114
|
onSelectSchool,
|
|
@@ -148,16 +158,15 @@ function SchoolSearch({
|
|
|
148
158
|
pick(results[active]);
|
|
149
159
|
return;
|
|
150
160
|
}
|
|
151
|
-
if (state !== "results") return;
|
|
152
|
-
|
|
153
|
-
|
|
161
|
+
if (state !== "results" || e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
|
|
162
|
+
e.preventDefault();
|
|
163
|
+
const down = e.key === "ArrowDown";
|
|
164
|
+
if (!open) {
|
|
154
165
|
setOpen(true);
|
|
155
|
-
setActive(
|
|
156
|
-
|
|
157
|
-
if (e.key === "ArrowUp") {
|
|
158
|
-
e.preventDefault();
|
|
159
|
-
setActive((i) => Math.max(0, i - 1));
|
|
166
|
+
setActive(down ? 0 : results.length - 1);
|
|
167
|
+
return;
|
|
160
168
|
}
|
|
169
|
+
setActive((i) => down ? Math.min(results.length - 1, i + 1) : Math.max(0, i - 1));
|
|
161
170
|
}
|
|
162
171
|
function find(e) {
|
|
163
172
|
e.preventDefault();
|
|
@@ -240,10 +249,7 @@ function SchoolSearch({
|
|
|
240
249
|
pick(school);
|
|
241
250
|
},
|
|
242
251
|
children: [
|
|
243
|
-
/* @__PURE__ */
|
|
244
|
-
school.name,
|
|
245
|
-
school.verified && /* @__PURE__ */ jsx2(BadgeCheckIcon, { role: "img", "aria-label": t.verified })
|
|
246
|
-
] }),
|
|
252
|
+
/* @__PURE__ */ jsx2("strong", { children: school.verified ? /* @__PURE__ */ jsx2(NameWithBadge, { name: school.name, badge: /* @__PURE__ */ jsx2(BadgeCheckIcon, { role: "img", "aria-label": t.verified }) }) : school.name }),
|
|
247
253
|
/* @__PURE__ */ jsx2("span", { children: formatPlace(school) })
|
|
248
254
|
]
|
|
249
255
|
},
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/SchoolSearch.tsx","../src/useSchoolSearch.ts","../src/icons.tsx"],"sourcesContent":["import { useEffect, useId, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from 'react';\nimport { schoolPlace, useSchoolSearch } from './useSchoolSearch';\nimport { BadgeCheckIcon, SearchIcon, XIcon } from './icons';\nimport type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types';\n\nexport const defaultMessages: SchoolSearchMessages = {\n label: 'Search for a school',\n placeholder: 'School name or town',\n submit: 'Find school',\n clear: 'Clear search',\n listLabel: 'Schools',\n verified: 'Verified',\n loading: 'Searching schools…',\n retry: 'Try again',\n error: ({ retry, link }) => <>We couldn’t load schools. {retry}{link ? <>, or {link}</> : null}.</>,\n empty: ({ query, link }) => <>No school matches “{query}”. Try fewer words or the town name{link ? <>, or {link}</> : null}.</>,\n announceResults: count => `${count} ${count === 1 ? 'school' : 'schools'} found. Choose one to see its page.`,\n announceEmpty: 'No schools found',\n announceError: 'We couldn’t load schools',\n};\n\nexport interface SchoolSearchProps<S extends School = School> {\n /** Supplies the schools matching the typed text. */\n searchSchools: SearchSchools<S>;\n /** Receives the school the person picked (click, Enter on a highlighted school, or \"Find school\" with one match). */\n onSelectSchool: (school: S) => void;\n /**\n * \"Find school\" (or Enter with nothing highlighted) when there are several matches, or while a search\n * is loading or has failed. On the website this opens the full directory search. Without it, the\n * button opens the results list instead.\n */\n onSearchAll?: (query: string) => void;\n /** Links shown inside the messages. Leave out to show the messages without links. */\n links?: {\n /** Shown after a failed search, e.g. donate without choosing a school. */\n error?: FallbackLink | null;\n /** Shown when nothing matches, e.g. \"tell us about the school\". Gets the trimmed search text. */\n empty?: ((query: string) => FallbackLink | null) | null;\n };\n /** Renders a link, e.g. with Next.js `<Link>`. Default: a plain `<a>`. */\n renderLink?: (link: { href: string; children: ReactNode }) => ReactNode;\n /** Replace any of the text, e.g. for translations. */\n messages?: Partial<SchoolSearchMessages>;\n /** The line under a school's name. Default: \"High school, Town, Province\". */\n formatPlace?: (school: S) => string;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Search delay after the last keystroke, in ms. Default 250. */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n /** When the page URL has this hash (default '#find-school'), the box takes focus. null turns it off. */\n focusHash?: string | null;\n className?: string;\n}\n\nconst plainLink = ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>;\n\n/**\n * \"Which school will you help?\" A combobox: type a school name or town, then pick a school with the\n * mouse, or the arrow keys and Enter. The app decides where a picked school goes.\n */\nexport function SchoolSearch<S extends School = School>({\n searchSchools, onSelectSchool, onSearchAll, links, renderLink = plainLink, messages, formatPlace = schoolPlace,\n limit, debounceMs, minChars = 2, focusHash = '#find-school', className,\n}: SchoolSearchProps<S>) {\n const t = { ...defaultMessages, ...messages };\n const id = useId();\n const listId = `${id}-schools`;\n const { query, setQuery, state, results, retry } = useSchoolSearch<S>({ searchSchools, limit, debounceMs, minChars });\n const [active, setActive] = useState(-1);\n useEffect(() => setActive(results.length ? 0 : -1), [results]);\n const [open, setOpen] = useState(false);\n const input = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (!focusHash) return;\n const focusFromHash = () => { if (window.location.hash === focusHash) input.current?.focus({ preventScroll: true }); };\n focusFromHash();\n window.addEventListener('hashchange', focusFromHash);\n return () => window.removeEventListener('hashchange', focusFromHash);\n }, [focusHash]);\n\n function pick(school: S) { setOpen(false); onSelectSchool(school); }\n function clear() { setQuery(''); requestAnimationFrame(() => input.current?.focus()); }\n\n function onKey(e: KeyboardEvent<HTMLInputElement>) {\n if (e.key === 'Escape') { setOpen(false); return; }\n // Enter with a school highlighted in the open list picks that school.\n if (e.key === 'Enter' && open && state === 'results' && results[active]) { e.preventDefault(); pick(results[active]); return; }\n if (state !== 'results') return;\n if (e.key === 'ArrowDown') { e.preventDefault(); setOpen(true); setActive(i => Math.min(results.length - 1, i + 1)); }\n if (e.key === 'ArrowUp') { e.preventDefault(); setActive(i => Math.max(0, i - 1)); }\n }\n\n // \"Find school\" (or Enter without a highlighted school): one match picks that school; several go to\n // onSearchAll. No matches searches again. While searching or after a failure, onSearchAll too.\n function find(e: FormEvent<HTMLFormElement>) {\n e.preventDefault();\n const term = query.trim();\n if (term.length < minChars) { input.current?.focus(); return; }\n if (state === 'results' && results.length === 1) { pick(results[0]); return; }\n if (state === 'empty' || (state === 'error' && !onSearchAll)) { retry(); setOpen(true); input.current?.focus(); return; }\n if (onSearchAll) { setOpen(false); onSearchAll(term); return; }\n setOpen(true); input.current?.focus();\n }\n\n const typed = query.trim();\n const showList = open && state !== 'idle';\n const errorLink = links?.error ? renderLink({ href: links.error.href, children: links.error.label }) : null;\n const emptyFallback = state === 'empty' && links?.empty ? links.empty(typed) : null;\n const emptyLink = emptyFallback ? renderLink({ href: emptyFallback.href, children: emptyFallback.label }) : null;\n const retryButton = <button type=\"button\" className=\"skolo-search__retry\" onClick={() => { retry(); input.current?.focus(); }}>{t.retry}</button>;\n\n return <form className={`skolo-search${className ? ` ${className}` : ''}`} role=\"search\" onSubmit={find}>\n <label htmlFor={`${id}-input`} className=\"skolo-search__sr-only\">{t.label}</label>\n <div className={`skolo-search__box${showList ? ' skolo-search__box--open' : ''}`}>\n <SearchIcon aria-hidden=\"true\" className=\"skolo-search__icon\" />\n <input ref={input} id={`${id}-input`} role=\"combobox\" aria-expanded={showList} aria-controls={listId} aria-autocomplete=\"list\"\n aria-activedescendant={showList && state === 'results' && active >= 0 ? `${listId}-${active}` : undefined}\n value={query} placeholder={t.placeholder} autoComplete=\"off\" spellCheck={false}\n onChange={e => { setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={onKey}\n onBlur={() => setTimeout(() => setOpen(false), 150)} />\n {query && <button type=\"button\" className=\"skolo-search__clear\" aria-label={t.clear} onClick={clear}><XIcon aria-hidden=\"true\" /></button>}\n <button type=\"submit\" className=\"skolo-search__go\">{t.submit}</button>\n </div>\n {/* Pressing inside the panel keeps focus in the box, so the panel stays open for its links and buttons. */}\n {showList && <div className=\"skolo-search__panel\" onMouseDown={e => e.preventDefault()}>\n {state === 'loading' && <p className=\"skolo-search__status\">{t.loading}</p>}\n {state === 'error' && <p className=\"skolo-search__status\">{t.error({ retry: retryButton, link: errorLink })}</p>}\n {state === 'empty' && <p className=\"skolo-search__status\">{t.empty({ query: typed, link: emptyLink })}</p>}\n {state === 'results' && <ul id={listId} role=\"listbox\" aria-label={t.listLabel}>\n {results.map((school, i) => <li key={school.id} id={`${listId}-${i}`} role=\"option\" aria-selected={i === active}\n className={i === active ? 'skolo-search__option--active' : undefined}\n onMouseEnter={() => setActive(i)} onMouseDown={e => { e.preventDefault(); pick(school); }}>\n <strong>{school.name}{school.verified && <BadgeCheckIcon role=\"img\" aria-label={t.verified} />}</strong>\n <span>{formatPlace(school)}</span>\n </li>)}\n </ul>}\n </div>}\n <p className=\"skolo-search__sr-only\" aria-live=\"polite\">{state === 'results' ? t.announceResults(results.length) : state === 'empty' ? t.announceEmpty : state === 'error' ? t.announceError : ''}</p>\n </form>;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { School, SearchSchools, SearchState } from './types';\n\nexport interface UseSchoolSearchOptions<S extends School> {\n searchSchools: SearchSchools<S>;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Wait after the last keystroke before searching, in ms. Default 250 (the homepage's delay). */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n}\n\nconst LEVEL: Record<string, string> = { primary: 'Primary school', high: 'High school', combined: 'Combined school' };\n\n/** \"High school, Polokwane, Limpopo\": the line under a school's name in the results. */\nexport const schoolPlace = (s: Pick<School, 'level' | 'town' | 'municipality' | 'province'>) =>\n [s.level ? LEVEL[s.level] ?? s.level : null, [s.town || s.municipality, s.province].filter(Boolean).join(', ')]\n .filter(Boolean)\n .join(', ');\n\n/**\n * Searches as the person types, keeping only the answer to the latest query: every new query (or\n * retry) bumps a sequence number and aborts the previous request, and a response is applied only if\n * its sequence number is still the current one. retry() runs the same search again.\n */\nexport function useSchoolSearch<S extends School>({ searchSchools, limit = 6, debounceMs = 250, minChars = 2 }: UseSchoolSearchOptions<S>) {\n const [query, setQuery] = useState('');\n const [state, setState] = useState<SearchState>('idle');\n const [results, setResults] = useState<S[]>([]);\n const [attempt, setAttempt] = useState(0);\n const request = useRef(0);\n // The latest search function, so an app passing a new function each render doesn't restart searches.\n const search = useRef(searchSchools);\n search.current = searchSchools;\n\n useEffect(() => {\n const term = query.trim();\n if (term.length < minChars) { request.current++; setState('idle'); setResults([]); return; }\n const seq = ++request.current;\n const controller = new AbortController();\n setState('loading');\n const timer = setTimeout(async () => {\n try {\n const found = await search.current(term, { signal: controller.signal });\n if (seq !== request.current) return;\n const items = (found || []).slice(0, limit);\n setResults(items);\n setState(items.length ? 'results' : 'empty');\n } catch {\n if (seq === request.current) { setResults([]); setState('error'); }\n }\n }, debounceMs);\n return () => { clearTimeout(timer); controller.abort(); };\n }, [query, attempt, limit, debounceMs, minChars]);\n\n return { query, setQuery, state, results, retry: () => setAttempt(n => n + 1) };\n}\n","import type { SVGProps } from 'react';\n\n// Search, X and BadgeCheck from Lucide (https://lucide.dev, ISC licence), inlined so the package has\n// no icon dependency. They match the lucide-react icons the website used. Licence: THIRD_PARTY_NOTICES.md.\nconst base = { xmlns: 'http://www.w3.org/2000/svg', width: 24, height: 24, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' } as const;\n\nexport const SearchIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"m21 21-4.34-4.34\" /><circle cx=\"11\" cy=\"11\" r=\"8\" /></svg>;\n\nexport const XIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M18 6 6 18\" /><path d=\"m6 6 12 12\" /></svg>;\n\nexport const BadgeCheckIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z\" /><path d=\"m9 12 2 2 4-4\" /></svg>;\n"],"mappings":";;;AAAA,SAAS,aAAAA,YAAW,OAAO,UAAAC,SAAQ,YAAAC,iBAAoE;;;ACAvG,SAAS,WAAW,QAAQ,gBAAgB;AAa5C,IAAM,QAAgC,EAAE,SAAS,kBAAkB,MAAM,eAAe,UAAU,kBAAkB;AAG7G,IAAM,cAAc,CAAC,MAC1B,CAAC,EAAE,QAAQ,MAAM,EAAE,KAAK,KAAK,EAAE,QAAQ,MAAM,CA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AE;AAAA;AAAA;AAAA,QAJQ,OAAO;AAAA,MAK5C,CAAK,GACP;AAAA,OACF;AAAA,IACA,gBAAAA,KAAC,OAAE,WAAU,yBAAwB,aAAU,UAAU,oBAAU,YAAY,EAAE,gBAAgB,QAAQ,MAAM,IAAI,UAAU,UAAU,EAAE,gBAAgB,UAAU,UAAU,EAAE,gBAAgB,IAAG;AAAA,KACpM;AACF;","names":["useEffect","useRef","useState","jsx","jsxs","useState","useEffect","useRef"]}
|
|
1
|
+
{"version":3,"sources":["../src/SchoolSearch.tsx","../src/useSchoolSearch.ts","../src/icons.tsx"],"sourcesContent":["import { useEffect, useId, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from 'react';\nimport { schoolPlace, useSchoolSearch } from './useSchoolSearch.js';\nimport { BadgeCheckIcon, SearchIcon, XIcon } from './icons.js';\nimport type { FallbackLink, School, SchoolSearchMessages, SearchSchools } from './types.js';\n\nexport const defaultMessages: SchoolSearchMessages = {\n label: 'Search for a school',\n placeholder: 'School name or town',\n submit: 'Find school',\n clear: 'Clear search',\n listLabel: 'Schools',\n verified: 'Verified',\n loading: 'Searching schools…',\n retry: 'Try again',\n error: ({ retry, link }) => <>We couldn’t load schools. {retry}{link ? <>, or {link}</> : null}.</>,\n empty: ({ query, link }) => <>No school matches “{query}”. Try fewer words or the town name{link ? <>, or {link}</> : null}.</>,\n announceResults: count => `${count} ${count === 1 ? 'school' : 'schools'} found. Choose one to see its page.`,\n announceEmpty: 'No schools found',\n announceError: 'We couldn’t load schools',\n};\n\nexport interface SchoolSearchProps<S extends School = School> {\n /** Supplies the schools matching the typed text. */\n searchSchools: SearchSchools<S>;\n /** Receives the school the person picked (click, Enter on a highlighted school, or \"Find school\" with one match). */\n onSelectSchool: (school: S) => void;\n /**\n * \"Find school\" (or Enter with nothing highlighted) when there are several matches, or while a search\n * is loading or has failed. On the website this opens the full directory search. Without it, the\n * button opens the results list instead.\n */\n onSearchAll?: (query: string) => void;\n /** Links shown inside the messages. Leave out to show the messages without links. */\n links?: {\n /** Shown after a failed search, e.g. donate without choosing a school. */\n error?: FallbackLink | null;\n /** Shown when nothing matches, e.g. \"tell us about the school\". Gets the trimmed search text. */\n empty?: ((query: string) => FallbackLink | null) | null;\n };\n /** Renders a link, e.g. with Next.js `<Link>`. Default: a plain `<a>`. */\n renderLink?: (link: { href: string; children: ReactNode }) => ReactNode;\n /** Replace any of the text, e.g. for translations. */\n messages?: Partial<SchoolSearchMessages>;\n /** The line under a school's name. Default: \"High school, Town, Province\". */\n formatPlace?: (school: S) => string;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Search delay after the last keystroke, in ms. Default 250. */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n /** When the page URL has this hash (default '#find-school'), the box takes focus. null turns it off. */\n focusHash?: string | null;\n className?: string;\n}\n\nconst plainLink = ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>;\n\n/** A name with its badge, the badge kept on one line with the last word so it never wraps alone. */\nfunction NameWithBadge({ name, badge }: { name: string; badge: ReactNode }) {\n const split = name.trimEnd().lastIndexOf(' ') + 1;\n return <>{name.slice(0, split)}<span className=\"skolo-search__name-end\">{name.slice(split)}{badge}</span></>;\n}\n\n/**\n * \"Which school will you help?\" A combobox: type a school name or town, then pick a school with the\n * mouse, or the arrow keys and Enter. The app decides where a picked school goes.\n */\nexport function SchoolSearch<S extends School = School>({\n searchSchools, onSelectSchool, onSearchAll, links, renderLink = plainLink, messages, formatPlace = schoolPlace,\n limit, debounceMs, minChars = 2, focusHash = '#find-school', className,\n}: SchoolSearchProps<S>) {\n const t = { ...defaultMessages, ...messages };\n const id = useId();\n const listId = `${id}-schools`;\n const { query, setQuery, state, results, retry } = useSchoolSearch<S>({ searchSchools, limit, debounceMs, minChars });\n const [active, setActive] = useState(-1);\n useEffect(() => setActive(results.length ? 0 : -1), [results]);\n const [open, setOpen] = useState(false);\n const input = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (!focusHash) return;\n const focusFromHash = () => { if (window.location.hash === focusHash) input.current?.focus({ preventScroll: true }); };\n focusFromHash();\n window.addEventListener('hashchange', focusFromHash);\n return () => window.removeEventListener('hashchange', focusFromHash);\n }, [focusHash]);\n\n function pick(school: S) { setOpen(false); onSelectSchool(school); }\n function clear() { setQuery(''); requestAnimationFrame(() => input.current?.focus()); }\n\n function onKey(e: KeyboardEvent<HTMLInputElement>) {\n if (e.key === 'Escape') { setOpen(false); return; }\n // Enter with a school highlighted in the open list picks that school.\n if (e.key === 'Enter' && open && state === 'results' && results[active]) { e.preventDefault(); pick(results[active]); return; }\n if (state !== 'results' || (e.key !== 'ArrowDown' && e.key !== 'ArrowUp')) return;\n // Home and End are left to the text box, where they move the caret (the ARIA editable combobox pattern).\n e.preventDefault();\n const down = e.key === 'ArrowDown';\n // On a closed list, an arrow key opens it: ArrowDown on the first school, ArrowUp on the last.\n // The hidden highlight never moves, so every key press has a visible, announced result.\n if (!open) { setOpen(true); setActive(down ? 0 : results.length - 1); return; }\n // In the open list the arrows stop at the first and last school; they do not wrap.\n setActive(i => (down ? Math.min(results.length - 1, i + 1) : Math.max(0, i - 1)));\n }\n\n // \"Find school\" (or Enter without a highlighted school): one match picks that school; several go to\n // onSearchAll. No matches searches again. While searching or after a failure, onSearchAll too.\n function find(e: FormEvent<HTMLFormElement>) {\n e.preventDefault();\n const term = query.trim();\n if (term.length < minChars) { input.current?.focus(); return; }\n if (state === 'results' && results.length === 1) { pick(results[0]); return; }\n if (state === 'empty' || (state === 'error' && !onSearchAll)) { retry(); setOpen(true); input.current?.focus(); return; }\n if (onSearchAll) { setOpen(false); onSearchAll(term); return; }\n setOpen(true); input.current?.focus();\n }\n\n const typed = query.trim();\n const showList = open && state !== 'idle';\n const errorLink = links?.error ? renderLink({ href: links.error.href, children: links.error.label }) : null;\n const emptyFallback = state === 'empty' && links?.empty ? links.empty(typed) : null;\n const emptyLink = emptyFallback ? renderLink({ href: emptyFallback.href, children: emptyFallback.label }) : null;\n const retryButton = <button type=\"button\" className=\"skolo-search__retry\" onClick={() => { retry(); input.current?.focus(); }}>{t.retry}</button>;\n\n return <form className={`skolo-search${className ? ` ${className}` : ''}`} role=\"search\" onSubmit={find}>\n <label htmlFor={`${id}-input`} className=\"skolo-search__sr-only\">{t.label}</label>\n <div className={`skolo-search__box${showList ? ' skolo-search__box--open' : ''}`}>\n <SearchIcon aria-hidden=\"true\" className=\"skolo-search__icon\" />\n <input ref={input} id={`${id}-input`} role=\"combobox\" aria-expanded={showList} aria-controls={listId} aria-autocomplete=\"list\"\n aria-activedescendant={showList && state === 'results' && active >= 0 ? `${listId}-${active}` : undefined}\n value={query} placeholder={t.placeholder} autoComplete=\"off\" spellCheck={false}\n onChange={e => { setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={onKey}\n onBlur={() => setTimeout(() => setOpen(false), 150)} />\n {query && <button type=\"button\" className=\"skolo-search__clear\" aria-label={t.clear} onClick={clear}><XIcon aria-hidden=\"true\" /></button>}\n <button type=\"submit\" className=\"skolo-search__go\">{t.submit}</button>\n </div>\n {/* Pressing inside the panel keeps focus in the box, so the panel stays open for its links and buttons. */}\n {showList && <div className=\"skolo-search__panel\" onMouseDown={e => e.preventDefault()}>\n {state === 'loading' && <p className=\"skolo-search__status\">{t.loading}</p>}\n {state === 'error' && <p className=\"skolo-search__status\">{t.error({ retry: retryButton, link: errorLink })}</p>}\n {state === 'empty' && <p className=\"skolo-search__status\">{t.empty({ query: typed, link: emptyLink })}</p>}\n {state === 'results' && <ul id={listId} role=\"listbox\" aria-label={t.listLabel}>\n {results.map((school, i) => <li key={school.id} id={`${listId}-${i}`} role=\"option\" aria-selected={i === active}\n className={i === active ? 'skolo-search__option--active' : undefined}\n onMouseEnter={() => setActive(i)} onMouseDown={e => { e.preventDefault(); pick(school); }}>\n <strong>{school.verified ? <NameWithBadge name={school.name} badge={<BadgeCheckIcon role=\"img\" aria-label={t.verified} />} /> : school.name}</strong>\n <span>{formatPlace(school)}</span>\n </li>)}\n </ul>}\n </div>}\n <p className=\"skolo-search__sr-only\" aria-live=\"polite\">{state === 'results' ? t.announceResults(results.length) : state === 'empty' ? t.announceEmpty : state === 'error' ? t.announceError : ''}</p>\n </form>;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { School, SearchSchools, SearchState } from './types.js';\n\nexport interface UseSchoolSearchOptions<S extends School> {\n searchSchools: SearchSchools<S>;\n /** Most results to show. Default 6. */\n limit?: number;\n /** Wait after the last keystroke before searching, in ms. Default 250 (the homepage's delay). */\n debounceMs?: number;\n /** Shortest text that searches. Default 2. */\n minChars?: number;\n}\n\nconst LEVEL: Record<string, string> = { primary: 'Primary school', high: 'High school', combined: 'Combined school' };\n\n/** \"High school, Polokwane, Limpopo\": the line under a school's name in the results. */\nexport const schoolPlace = (s: Pick<School, 'level' | 'town' | 'municipality' | 'province'>) =>\n [s.level ? LEVEL[s.level] ?? s.level : null, [s.town || s.municipality, s.province].filter(Boolean).join(', ')]\n .filter(Boolean)\n .join(', ');\n\n/**\n * Searches as the person types, keeping only the answer to the latest query: every new query (or\n * retry) bumps a sequence number and aborts the previous request, and a response is applied only if\n * its sequence number is still the current one. retry() runs the same search again.\n */\nexport function useSchoolSearch<S extends School>({ searchSchools, limit = 6, debounceMs = 250, minChars = 2 }: UseSchoolSearchOptions<S>) {\n const [query, setQuery] = useState('');\n const [state, setState] = useState<SearchState>('idle');\n const [results, setResults] = useState<S[]>([]);\n const [attempt, setAttempt] = useState(0);\n const request = useRef(0);\n // The latest search function, so an app passing a new function each render doesn't restart searches.\n const search = useRef(searchSchools);\n search.current = searchSchools;\n\n useEffect(() => {\n const term = query.trim();\n if (term.length < minChars) { request.current++; setState('idle'); setResults([]); return; }\n const seq = ++request.current;\n const controller = new AbortController();\n setState('loading');\n const timer = setTimeout(async () => {\n try {\n const found = await search.current(term, { signal: controller.signal });\n if (seq !== request.current) return;\n const items = (found || []).slice(0, limit);\n setResults(items);\n setState(items.length ? 'results' : 'empty');\n } catch {\n if (seq === request.current) { setResults([]); setState('error'); }\n }\n }, debounceMs);\n return () => { clearTimeout(timer); controller.abort(); };\n }, [query, attempt, limit, debounceMs, minChars]);\n\n return { query, setQuery, state, results, retry: () => setAttempt(n => n + 1) };\n}\n","import type { SVGProps } from 'react';\n\n// Search, X and BadgeCheck from Lucide (https://lucide.dev, ISC licence), inlined so the package has\n// no icon dependency. They match the lucide-react icons the website used. Licence: THIRD_PARTY_NOTICES.md.\nconst base = { xmlns: 'http://www.w3.org/2000/svg', width: 24, height: 24, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round' } as const;\n\nexport const SearchIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"m21 21-4.34-4.34\" /><circle cx=\"11\" cy=\"11\" r=\"8\" /></svg>;\n\nexport const XIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M18 6 6 18\" /><path d=\"m6 6 12 12\" /></svg>;\n\nexport const BadgeCheckIcon = (props: SVGProps<SVGSVGElement>) =>\n <svg {...base} {...props}><path d=\"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z\" /><path d=\"m9 12 2 2 4-4\" /></svg>;\n"],"mappings":";;;AAAA,SAAS,aAAAA,YAAW,OAAO,UAAAC,SAAQ,YAAAC,iBAAoE;;;ACAvG,SAAS,WAAW,QAAQ,gBAAgB;AAa5C,IAAM,QAAgC,EAAE,SAAS,kBAAkB,MAAM,eAAe,UAAU,kBAAkB;AAG7G,IAAM,cAAc,CAAC,MAC1B,CAAC,EAAE,QAAQ,MAAM,EAAE,KAAK,KAAK,EAAE,QAAQ,MAAM,CAAC,EAAE,QAAQ,EAAE,cAAc,EAA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cAAc,MAAM,UAAU,CAAC;AAAA,UAAG,aAAa,OAAK;AAAE,cAAE,eAAe;AAAG,iBAAK,MAAM;AAAA,UAAG;AAAA,UACxF;AAAA,4BAAAD,KAAC,YAAQ,iBAAO,WAAW,gBAAAA,KAAC,iBAAc,MAAM,OAAO,MAAM,OAAO,gBAAAA,KAAC,kBAAe,MAAK,OAAM,cAAY,EAAE,UAAU,GAAI,IAAK,OAAO,MAAK;AAAA,YAC5I,gBAAAA,KAAC,UAAM,sBAAY,MAAM,GAAE;AAAA;AAAA;AAAA,QAJQ,OAAO;AAAA,MAK5C,CAAK,GACP;AAAA,OACF;AAAA,IACA,gBAAAA,KAAC,OAAE,WAAU,yBAAwB,aAAU,UAAU,oBAAU,YAAY,EAAE,gBAAgB,QAAQ,MAAM,IAAI,UAAU,UAAU,EAAE,gBAAgB,UAAU,UAAU,EAAE,gBAAgB,IAAG;AAAA,KACpM;AACF;","names":["useEffect","useRef","useState","jsx","jsxs","useState","useEffect","useRef"]}
|
package/dist/styles.css
CHANGED
|
@@ -39,9 +39,16 @@
|
|
|
39
39
|
.skolo-search__panel{position:relative;z-index:var(--skolo-search-z);background:#fff;border-top:1px solid var(--skolo-search-line);border-radius:0 0 var(--skolo-search-radius) var(--skolo-search-radius);box-shadow:var(--skolo-search-shadow);overflow:hidden}
|
|
40
40
|
.skolo-search__panel ul{list-style:none;margin:0;padding:6px}
|
|
41
41
|
.skolo-search__panel li{display:grid;gap:2px;padding:12px 16px;border-radius:4px;cursor:pointer}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
.
|
|
42
|
+
/* The name is plain text with the verified badge inline, kept on one line with the name's last word.
|
|
43
|
+
On a narrow phone a name that wraps keeps its badge beside it, not pushed to the far edge or left
|
|
44
|
+
alone on a line. Very long words break rather than widen the list. */
|
|
45
|
+
.skolo-search__panel li strong{display:block;color:var(--skolo-search-brand-deep);font-size:16px;overflow-wrap:anywhere}
|
|
46
|
+
/* An inline flex box moves to the next line whole, like nowrap, but a last word too long for the row
|
|
47
|
+
can still break inside it, so the badge stays in the row instead of being pushed out and clipped.
|
|
48
|
+
flex-end keeps the badge on the word's last line; 2px puts it where the desktop badge always sat. */
|
|
49
|
+
.skolo-search__name-end{display:inline-flex;align-items:flex-end;max-width:100%}
|
|
50
|
+
.skolo-search__panel li strong svg{flex:none;width:17px;height:17px;margin:0 0 2px 6px;color:var(--skolo-search-brand)}
|
|
51
|
+
.skolo-search__panel li>span{font-size:13.5px;color:var(--skolo-search-muted);overflow-wrap:anywhere}
|
|
45
52
|
.skolo-search__option--active{background:var(--skolo-search-tint)}
|
|
46
53
|
.skolo-search .skolo-search__status{margin:0;padding:16px 20px;font-size:14.5px;line-height:1.65;color:var(--skolo-search-muted);max-width:none}
|
|
47
54
|
.skolo-search__status a{color:var(--skolo-search-brand);font-weight:700}
|
package/dist/types.d.cts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
/** A school as the search shows it. Apps may pass extra fields; they are handed back on selection. */
|
|
3
|
+
export interface School {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
/** 'primary' | 'high' | 'combined', or any other label the app uses. */
|
|
7
|
+
level?: string | null;
|
|
8
|
+
town?: string | null;
|
|
9
|
+
municipality?: string | null;
|
|
10
|
+
province?: string | null;
|
|
11
|
+
verified?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export type SearchState = 'idle' | 'loading' | 'results' | 'empty' | 'error';
|
|
14
|
+
/**
|
|
15
|
+
* Supplies the schools that match the typed text. Called after the search delay with the trimmed
|
|
16
|
+
* text (at least `minChars` long). `signal` is aborted when a newer search replaces this one.
|
|
17
|
+
* Throw (or reject) to show the error message and its "Try again" button.
|
|
18
|
+
*/
|
|
19
|
+
export type SearchSchools<S extends School = School> = (query: string, options: {
|
|
20
|
+
signal: AbortSignal;
|
|
21
|
+
}) => Promise<S[]>;
|
|
22
|
+
/** A link shown inside a message, e.g. "donate without choosing a school". */
|
|
23
|
+
export interface FallbackLink {
|
|
24
|
+
href: string;
|
|
25
|
+
label: ReactNode;
|
|
26
|
+
}
|
|
27
|
+
/** Every piece of text the search shows, so the app can translate it. */
|
|
28
|
+
export interface SchoolSearchMessages {
|
|
29
|
+
label: string;
|
|
30
|
+
placeholder: string;
|
|
31
|
+
submit: string;
|
|
32
|
+
clear: string;
|
|
33
|
+
listLabel: string;
|
|
34
|
+
verified: string;
|
|
35
|
+
loading: ReactNode;
|
|
36
|
+
retry: string;
|
|
37
|
+
/** `retry` is the "Try again" button; `link` is the app's error fallback link, or null. */
|
|
38
|
+
error: (parts: {
|
|
39
|
+
retry: ReactNode;
|
|
40
|
+
link: ReactNode | null;
|
|
41
|
+
}) => ReactNode;
|
|
42
|
+
/** `query` is the trimmed search text; `link` is the app's no-results link, or null. */
|
|
43
|
+
empty: (parts: {
|
|
44
|
+
query: string;
|
|
45
|
+
link: ReactNode | null;
|
|
46
|
+
}) => ReactNode;
|
|
47
|
+
/** Screen-reader announcements. */
|
|
48
|
+
announceResults: (count: number) => string;
|
|
49
|
+
announceEmpty: string;
|
|
50
|
+
announceError: string;
|
|
51
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { School, SearchSchools, SearchState } from './types.cjs';
|
|
2
|
+
export interface UseSchoolSearchOptions<S extends School> {
|
|
3
|
+
searchSchools: SearchSchools<S>;
|
|
4
|
+
/** Most results to show. Default 6. */
|
|
5
|
+
limit?: number;
|
|
6
|
+
/** Wait after the last keystroke before searching, in ms. Default 250 (the homepage's delay). */
|
|
7
|
+
debounceMs?: number;
|
|
8
|
+
/** Shortest text that searches. Default 2. */
|
|
9
|
+
minChars?: number;
|
|
10
|
+
}
|
|
11
|
+
/** "High school, Polokwane, Limpopo": the line under a school's name in the results. */
|
|
12
|
+
export declare const schoolPlace: (s: Pick<School, 'level' | 'town' | 'municipality' | 'province'>) => string;
|
|
13
|
+
/**
|
|
14
|
+
* Searches as the person types, keeping only the answer to the latest query: every new query (or
|
|
15
|
+
* retry) bumps a sequence number and aborts the previous request, and a response is applied only if
|
|
16
|
+
* its sequence number is still the current one. retry() runs the same search again.
|
|
17
|
+
*/
|
|
18
|
+
export declare function useSchoolSearch<S extends School>({ searchSchools, limit, debounceMs, minChars }: UseSchoolSearchOptions<S>): {
|
|
19
|
+
query: string;
|
|
20
|
+
setQuery: import("react").Dispatch<import("react").SetStateAction<string>>;
|
|
21
|
+
state: SearchState;
|
|
22
|
+
results: S[];
|
|
23
|
+
retry: () => void;
|
|
24
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { School, SearchSchools, SearchState } from './types';
|
|
1
|
+
import type { School, SearchSchools, SearchState } from './types.js';
|
|
2
2
|
export interface UseSchoolSearchOptions<S extends School> {
|
|
3
3
|
searchSchools: SearchSchools<S>;
|
|
4
4
|
/** Most results to show. Default 6. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skolo-saka/school-search",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Skolo Saka's homepage school search: a reusable React combobox that finds schools as people type and reports the school they pick.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/skolo-saka/school-search#readme",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"default": "./dist/index.js"
|
|
32
32
|
},
|
|
33
33
|
"require": {
|
|
34
|
-
"types": "./dist/index.d.
|
|
34
|
+
"types": "./dist/index.d.cts",
|
|
35
35
|
"default": "./dist/index.cjs"
|
|
36
36
|
}
|
|
37
37
|
},
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"dev": "vite --config demo/vite.config.ts",
|
|
49
49
|
"demo": "vite --config demo/vite.config.ts",
|
|
50
50
|
"demo:build": "vite build --config demo/vite.config.ts",
|
|
51
|
-
"build": "tsup && tsc -p tsconfig.build.json && node scripts/copy-css.mjs",
|
|
51
|
+
"build": "tsup && tsc -p tsconfig.build.json && node scripts/declarations.mjs && node scripts/copy-css.mjs",
|
|
52
52
|
"test": "vitest run",
|
|
53
53
|
"test:watch": "vitest",
|
|
54
54
|
"typecheck": "tsc --noEmit",
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
"react-dom": ">=18"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
62
63
|
"@testing-library/jest-dom": "^7.0.1",
|
|
63
64
|
"@testing-library/react": "^16.3.3",
|
|
64
65
|
"@testing-library/user-event": "^14.6.12",
|