@skolo-saka/school-search 0.0.0-stage → 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.
@@ -0,0 +1 @@
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&rsquo;t load schools. {retry}{link ? <>, or {link}</> : null}.</>,\n empty: ({ query, link }) => <>No school matches &ldquo;{query}&rdquo;. 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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAuG;;;ACAvG,mBAA4C;AAa5C,IAAM,QAAgC,EAAE,SAAS,kBAAkB,MAAM,eAAe,UAAU,kBAAkB;AAG7G,IAAM,cAAc,CAAC,MAC1B,CAAC,EAAE,QAAQ,MAAM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Ac,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"]}
@@ -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';
@@ -0,0 +1,5 @@
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 ADDED
@@ -0,0 +1,268 @@
1
+ 'use client';
2
+
3
+ // src/SchoolSearch.tsx
4
+ import { useEffect as useEffect2, useId, useRef as useRef2, useState as useState2 } from "react";
5
+
6
+ // src/useSchoolSearch.ts
7
+ import { useEffect, useRef, useState } from "react";
8
+ var LEVEL = { primary: "Primary school", high: "High school", combined: "Combined school" };
9
+ var schoolPlace = (s) => [s.level ? LEVEL[s.level] ?? s.level : null, [s.town || s.municipality, s.province].filter(Boolean).join(", ")].filter(Boolean).join(", ");
10
+ function useSchoolSearch({ searchSchools, limit = 6, debounceMs = 250, minChars = 2 }) {
11
+ const [query, setQuery] = useState("");
12
+ const [state, setState] = useState("idle");
13
+ const [results, setResults] = useState([]);
14
+ const [attempt, setAttempt] = useState(0);
15
+ const request = useRef(0);
16
+ const search = useRef(searchSchools);
17
+ search.current = searchSchools;
18
+ useEffect(() => {
19
+ const term = query.trim();
20
+ if (term.length < minChars) {
21
+ request.current++;
22
+ setState("idle");
23
+ setResults([]);
24
+ return;
25
+ }
26
+ const seq = ++request.current;
27
+ const controller = new AbortController();
28
+ setState("loading");
29
+ const timer = setTimeout(async () => {
30
+ try {
31
+ const found = await search.current(term, { signal: controller.signal });
32
+ if (seq !== request.current) return;
33
+ const items = (found || []).slice(0, limit);
34
+ setResults(items);
35
+ setState(items.length ? "results" : "empty");
36
+ } catch {
37
+ if (seq === request.current) {
38
+ setResults([]);
39
+ setState("error");
40
+ }
41
+ }
42
+ }, debounceMs);
43
+ return () => {
44
+ clearTimeout(timer);
45
+ controller.abort();
46
+ };
47
+ }, [query, attempt, limit, debounceMs, minChars]);
48
+ return { query, setQuery, state, results, retry: () => setAttempt((n) => n + 1) };
49
+ }
50
+
51
+ // src/icons.tsx
52
+ import { jsx, jsxs } from "react/jsx-runtime";
53
+ var 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" };
54
+ var SearchIcon = (props) => /* @__PURE__ */ jsxs("svg", { ...base, ...props, children: [
55
+ /* @__PURE__ */ jsx("path", { d: "m21 21-4.34-4.34" }),
56
+ /* @__PURE__ */ jsx("circle", { cx: "11", cy: "11", r: "8" })
57
+ ] });
58
+ var XIcon = (props) => /* @__PURE__ */ jsxs("svg", { ...base, ...props, children: [
59
+ /* @__PURE__ */ jsx("path", { d: "M18 6 6 18" }),
60
+ /* @__PURE__ */ jsx("path", { d: "m6 6 12 12" })
61
+ ] });
62
+ var BadgeCheckIcon = (props) => /* @__PURE__ */ jsxs("svg", { ...base, ...props, children: [
63
+ /* @__PURE__ */ jsx("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" }),
64
+ /* @__PURE__ */ jsx("path", { d: "m9 12 2 2 4-4" })
65
+ ] });
66
+
67
+ // src/SchoolSearch.tsx
68
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
69
+ var defaultMessages = {
70
+ label: "Search for a school",
71
+ placeholder: "School name or town",
72
+ submit: "Find school",
73
+ clear: "Clear search",
74
+ listLabel: "Schools",
75
+ verified: "Verified",
76
+ loading: "Searching schools\u2026",
77
+ retry: "Try again",
78
+ error: ({ retry, link }) => /* @__PURE__ */ jsxs2(Fragment, { children: [
79
+ "We couldn\u2019t load schools. ",
80
+ retry,
81
+ link ? /* @__PURE__ */ jsxs2(Fragment, { children: [
82
+ ", or ",
83
+ link
84
+ ] }) : null,
85
+ "."
86
+ ] }),
87
+ empty: ({ query, link }) => /* @__PURE__ */ jsxs2(Fragment, { children: [
88
+ "No school matches \u201C",
89
+ query,
90
+ "\u201D. Try fewer words or the town name",
91
+ link ? /* @__PURE__ */ jsxs2(Fragment, { children: [
92
+ ", or ",
93
+ link
94
+ ] }) : null,
95
+ "."
96
+ ] }),
97
+ announceResults: (count) => `${count} ${count === 1 ? "school" : "schools"} found. Choose one to see its page.`,
98
+ announceEmpty: "No schools found",
99
+ announceError: "We couldn\u2019t load schools"
100
+ };
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
+ }
112
+ function SchoolSearch({
113
+ searchSchools,
114
+ onSelectSchool,
115
+ onSearchAll,
116
+ links,
117
+ renderLink = plainLink,
118
+ messages,
119
+ formatPlace = schoolPlace,
120
+ limit,
121
+ debounceMs,
122
+ minChars = 2,
123
+ focusHash = "#find-school",
124
+ className
125
+ }) {
126
+ const t = { ...defaultMessages, ...messages };
127
+ const id = useId();
128
+ const listId = `${id}-schools`;
129
+ const { query, setQuery, state, results, retry } = useSchoolSearch({ searchSchools, limit, debounceMs, minChars });
130
+ const [active, setActive] = useState2(-1);
131
+ useEffect2(() => setActive(results.length ? 0 : -1), [results]);
132
+ const [open, setOpen] = useState2(false);
133
+ const input = useRef2(null);
134
+ useEffect2(() => {
135
+ if (!focusHash) return;
136
+ const focusFromHash = () => {
137
+ if (window.location.hash === focusHash) input.current?.focus({ preventScroll: true });
138
+ };
139
+ focusFromHash();
140
+ window.addEventListener("hashchange", focusFromHash);
141
+ return () => window.removeEventListener("hashchange", focusFromHash);
142
+ }, [focusHash]);
143
+ function pick(school) {
144
+ setOpen(false);
145
+ onSelectSchool(school);
146
+ }
147
+ function clear() {
148
+ setQuery("");
149
+ requestAnimationFrame(() => input.current?.focus());
150
+ }
151
+ function onKey(e) {
152
+ if (e.key === "Escape") {
153
+ setOpen(false);
154
+ return;
155
+ }
156
+ if (e.key === "Enter" && open && state === "results" && results[active]) {
157
+ e.preventDefault();
158
+ pick(results[active]);
159
+ return;
160
+ }
161
+ if (state !== "results" || e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
162
+ e.preventDefault();
163
+ const down = e.key === "ArrowDown";
164
+ if (!open) {
165
+ setOpen(true);
166
+ setActive(down ? 0 : results.length - 1);
167
+ return;
168
+ }
169
+ setActive((i) => down ? Math.min(results.length - 1, i + 1) : Math.max(0, i - 1));
170
+ }
171
+ function find(e) {
172
+ e.preventDefault();
173
+ const term = query.trim();
174
+ if (term.length < minChars) {
175
+ input.current?.focus();
176
+ return;
177
+ }
178
+ if (state === "results" && results.length === 1) {
179
+ pick(results[0]);
180
+ return;
181
+ }
182
+ if (state === "empty" || state === "error" && !onSearchAll) {
183
+ retry();
184
+ setOpen(true);
185
+ input.current?.focus();
186
+ return;
187
+ }
188
+ if (onSearchAll) {
189
+ setOpen(false);
190
+ onSearchAll(term);
191
+ return;
192
+ }
193
+ setOpen(true);
194
+ input.current?.focus();
195
+ }
196
+ const typed = query.trim();
197
+ const showList = open && state !== "idle";
198
+ const errorLink = links?.error ? renderLink({ href: links.error.href, children: links.error.label }) : null;
199
+ const emptyFallback = state === "empty" && links?.empty ? links.empty(typed) : null;
200
+ const emptyLink = emptyFallback ? renderLink({ href: emptyFallback.href, children: emptyFallback.label }) : null;
201
+ const retryButton = /* @__PURE__ */ jsx2("button", { type: "button", className: "skolo-search__retry", onClick: () => {
202
+ retry();
203
+ input.current?.focus();
204
+ }, children: t.retry });
205
+ return /* @__PURE__ */ jsxs2("form", { className: `skolo-search${className ? ` ${className}` : ""}`, role: "search", onSubmit: find, children: [
206
+ /* @__PURE__ */ jsx2("label", { htmlFor: `${id}-input`, className: "skolo-search__sr-only", children: t.label }),
207
+ /* @__PURE__ */ jsxs2("div", { className: `skolo-search__box${showList ? " skolo-search__box--open" : ""}`, children: [
208
+ /* @__PURE__ */ jsx2(SearchIcon, { "aria-hidden": "true", className: "skolo-search__icon" }),
209
+ /* @__PURE__ */ jsx2(
210
+ "input",
211
+ {
212
+ ref: input,
213
+ id: `${id}-input`,
214
+ role: "combobox",
215
+ "aria-expanded": showList,
216
+ "aria-controls": listId,
217
+ "aria-autocomplete": "list",
218
+ "aria-activedescendant": showList && state === "results" && active >= 0 ? `${listId}-${active}` : void 0,
219
+ value: query,
220
+ placeholder: t.placeholder,
221
+ autoComplete: "off",
222
+ spellCheck: false,
223
+ onChange: (e) => {
224
+ setQuery(e.target.value);
225
+ setOpen(true);
226
+ },
227
+ onFocus: () => setOpen(true),
228
+ onKeyDown: onKey,
229
+ onBlur: () => setTimeout(() => setOpen(false), 150)
230
+ }
231
+ ),
232
+ query && /* @__PURE__ */ jsx2("button", { type: "button", className: "skolo-search__clear", "aria-label": t.clear, onClick: clear, children: /* @__PURE__ */ jsx2(XIcon, { "aria-hidden": "true" }) }),
233
+ /* @__PURE__ */ jsx2("button", { type: "submit", className: "skolo-search__go", children: t.submit })
234
+ ] }),
235
+ showList && /* @__PURE__ */ jsxs2("div", { className: "skolo-search__panel", onMouseDown: (e) => e.preventDefault(), children: [
236
+ state === "loading" && /* @__PURE__ */ jsx2("p", { className: "skolo-search__status", children: t.loading }),
237
+ state === "error" && /* @__PURE__ */ jsx2("p", { className: "skolo-search__status", children: t.error({ retry: retryButton, link: errorLink }) }),
238
+ state === "empty" && /* @__PURE__ */ jsx2("p", { className: "skolo-search__status", children: t.empty({ query: typed, link: emptyLink }) }),
239
+ state === "results" && /* @__PURE__ */ jsx2("ul", { id: listId, role: "listbox", "aria-label": t.listLabel, children: results.map((school, i) => /* @__PURE__ */ jsxs2(
240
+ "li",
241
+ {
242
+ id: `${listId}-${i}`,
243
+ role: "option",
244
+ "aria-selected": i === active,
245
+ className: i === active ? "skolo-search__option--active" : void 0,
246
+ onMouseEnter: () => setActive(i),
247
+ onMouseDown: (e) => {
248
+ e.preventDefault();
249
+ pick(school);
250
+ },
251
+ children: [
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 }),
253
+ /* @__PURE__ */ jsx2("span", { children: formatPlace(school) })
254
+ ]
255
+ },
256
+ school.id
257
+ )) })
258
+ ] }),
259
+ /* @__PURE__ */ jsx2("p", { className: "skolo-search__sr-only", "aria-live": "polite", children: state === "results" ? t.announceResults(results.length) : state === "empty" ? t.announceEmpty : state === "error" ? t.announceError : "" })
260
+ ] });
261
+ }
262
+ export {
263
+ SchoolSearch,
264
+ defaultMessages,
265
+ schoolPlace,
266
+ useSchoolSearch
267
+ };
268
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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.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&rsquo;t load schools. {retry}{link ? <>, or {link}</> : null}.</>,\n empty: ({ query, link }) => <>No school matches &ldquo;{query}&rdquo;. 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,EAAE,QAAQ,EAAE,OAAO,OAAO,EAAE,KAAK,IAAI,CAAC,EAC3G,OAAO,OAAO,EACd,KAAK,IAAI;AAOP,SAAS,gBAAkC,EAAE,eAAe,QAAQ,GAAG,aAAa,KAAK,WAAW,EAAE,G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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"]}
@@ -0,0 +1,67 @@
1
+ /* Skolo Saka school search. Moved from the homepage hero (app/(site)/site.module.css on staging).
2
+ A solid white pill (not glass) so it reads as the page's main, active control over a dark hero.
3
+
4
+ Colours come from the website's tokens when the page defines them (--brand, --brand-deep, --sun,
5
+ --sun-deep, --ink, --muted, --line, --glass-tint, --radius-control, --shadow-3, --z-raised), so the
6
+ site's colour themes carry through. Elsewhere the default Skolo Saka values below apply. Any of the
7
+ --skolo-search-* properties can also be set directly on .skolo-search. Default values are plain
8
+ colours (no color-mix()) so older phones show them too. */
9
+ .skolo-search{
10
+ --skolo-search-brand:var(--brand,#0f5132);
11
+ --skolo-search-brand-deep:var(--brand-deep,#073824);
12
+ --skolo-search-sun:var(--sun,#f6d23f);
13
+ --skolo-search-sun-deep:var(--sun-deep,#e9c21f);
14
+ --skolo-search-ink:var(--ink,#0e261c);
15
+ --skolo-search-muted:var(--muted,#56655f);
16
+ --skolo-search-line:var(--line,#dae3df);
17
+ --skolo-search-tint:var(--glass-tint,rgba(232,243,238,.6));
18
+ --skolo-search-radius:var(--radius-control,6px);
19
+ --skolo-search-shadow:var(--shadow-3,0 18px 40px rgba(7,56,36,.35));
20
+ --skolo-search-focus-ring:rgba(246,210,63,.55);
21
+ --skolo-search-z:var(--z-raised,1);
22
+ position:relative;max-width:560px;margin-top:6px;box-sizing:border-box;text-align:left;
23
+ }
24
+ .skolo-search *,.skolo-search *::before,.skolo-search *::after{box-sizing:border-box}
25
+ .skolo-search__sr-only{position:absolute!important;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;margin:0;padding:0}
26
+ .skolo-search__box{display:flex;align-items:center;gap:12px;background:#fff;border-radius:var(--skolo-search-radius);padding:0 8px 0 22px;height:64px;box-shadow:var(--skolo-search-shadow);transition:border-radius .15s}
27
+ .skolo-search__box>svg{flex:none;width:22px;height:22px;color:var(--skolo-search-brand)}
28
+ .skolo-search__box input{flex:1;min-width:0;border:0;outline:0;background:transparent;font:inherit;font-size:18px;color:var(--skolo-search-ink);padding:0}
29
+ .skolo-search__box input::placeholder{color:var(--skolo-search-muted);opacity:1}
30
+ .skolo-search__box:focus-within{box-shadow:0 0 0 4px var(--skolo-search-focus-ring),var(--skolo-search-shadow)}
31
+ .skolo-search__box--open{border-radius:var(--skolo-search-radius) var(--skolo-search-radius) 0 0}
32
+ .skolo-search__clear{flex:none;display:grid;place-items:center;width:40px;height:40px;padding:0;border:0;border-radius:50%;background:var(--skolo-search-tint);color:var(--skolo-search-brand-deep);cursor:pointer}
33
+ .skolo-search__clear svg{width:18px;height:18px}
34
+ .skolo-search__go{flex:none;height:48px;padding:0 20px;border:0;border-radius:4px;background:var(--skolo-search-sun);color:var(--skolo-search-brand-deep);font:inherit;font-size:15px;font-weight:800;cursor:pointer}
35
+ @media (hover:hover){.skolo-search__go:hover{background:var(--skolo-search-sun-deep)}}
36
+ .skolo-search__go:focus-visible{outline:3px solid var(--skolo-search-brand-deep);outline-offset:2px}
37
+ .skolo-search__clear:focus-visible,.skolo-search__retry:focus-visible,.skolo-search__status a:focus-visible{outline:3px solid var(--skolo-search-brand);outline-offset:3px;border-radius:4px}
38
+ .skolo-search__retry{border:0;background:none;padding:0;font:inherit;font-weight:700;color:var(--skolo-search-brand);text-decoration:underline;cursor:pointer}
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
+ .skolo-search__panel ul{list-style:none;margin:0;padding:6px}
41
+ .skolo-search__panel li{display:grid;gap:2px;padding:12px 16px;border-radius:4px;cursor:pointer}
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}
52
+ .skolo-search__option--active{background:var(--skolo-search-tint)}
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}
54
+ .skolo-search__status a{color:var(--skolo-search-brand);font-weight:700}
55
+
56
+ @media (max-width:560px){
57
+ .skolo-search__box{height:56px;padding-left:18px;gap:8px}
58
+ .skolo-search__go{height:42px;padding:0 14px;font-size:14px}
59
+ .skolo-search__box input{font-size:16px}
60
+ }
61
+ /* Touch screens: 44px targets. */
62
+ @media (pointer:coarse){
63
+ .skolo-search__box input{align-self:stretch}
64
+ .skolo-search__go{height:44px}
65
+ }
66
+ /* Narrow phones: the box drops its icon so "School name or town" shows in full beside the button. */
67
+ @media (max-width:400px){.skolo-search__box{padding-left:16px}.skolo-search__box>svg{display:none}}
@@ -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,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
+ };
@@ -0,0 +1,24 @@
1
+ import type { School, SearchSchools, SearchState } from './types.js';
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
+ };