feat: overseas birth places are found by typing; the country field filters as you type (BUG-2049)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
@@ -27515,3 +27515,15 @@
|
||||
- 验证与防复发:`frontend/tests/annual-two-step-2047.test.tsx` 覆盖两步切换、焦点、跳过与开始、前后往返和关闭重开后内容保留、点外面和 Esc 关闭、请求体不变、卡片尺寸和两栏样式;`annual-report.test.tsx` 里钉住旧版式的断言按原值、新值、原因更新。用产品的样式表把两步渲染成静态页面,在桌面和手机宽度下看过截图并量过滚动高度;登录后的真实页面本机起不来,没有在真实页面上看过。
|
||||
- 关联记录:BUG-1637、BUG-1650、BUG-2037、BUG-2044。
|
||||
- 修复版本:`claude/annual-two-step-2047`。
|
||||
|
||||
## BUG-2049 | 海外出生地只能在两个很长的下拉里一级级找,手机上几乎选不了
|
||||
|
||||
- 状态:fixed-pending-verify(待测试环境真机确认)。
|
||||
- 首次发现 / 最近更新:2026-11-20 / 2026-11-20。
|
||||
- 触发与现象:在测试环境用一张公开的海外盘建档:国家之后是「州 / 地区」「城市」两级下拉,没有搜索,名字全是英文;英国的地区有 221 项,手机上要滚动一万多像素才能找到;美国的城市有一万六千多个。产品负责人确认内测有海外出生的用户。
|
||||
- 触发条件:出生国家或「今年住在哪个城市」选了中国以外的任何国家。
|
||||
- 根因:2026-11-06 定的做法是「海外地点逐级选择,不使用搜索」,当时没有按真实的列表长度在手机上走过;产品里也没有可搜索的下拉组件。
|
||||
- 修复:选了国外之后先显示一个搜索框,在浏览器里搜已经下载的该国地点表(不联网、不调第三方):城市名优先于地区名,前缀优先于词中,不分大小写和重音,最多 20 条;选中一行同时定下地区和城市。国家一栏可以按中文名或英文名打字筛选。配了一张 185 条的常见城市中文别名表,输入中文也能搜到,别名只用于查找,定位仍用地点表里那一条。逐级选择保留为第二入口。中国的省、市、区三级不变。保存的字段、标签和时区查询流程都没有变。
|
||||
- 验证与防复发:`frontend/tests/overseas-place-search-2049.test.tsx`:排序、重音与标点、20 条上限、美国全表的耗时、别名表每一条都能在地点表里找到、中文别名与找不到的状态、国家筛选、搜索选中与两级下拉选中得到完全相同的结果、方向键与回车和 Esc、中国不出现搜索框、样式沿用下拉选项且没有左侧色条。`world-location-table.test.ts` 里「不使用搜索」的断言按原值、新值、原因更新。登录后的页面本机起不来,外观只用产品样式表渲染成静态页面看过(电脑和手机宽度、浅色和深色)。
|
||||
- 关联记录:BUG-1506、BUG-2047。
|
||||
- 修复版本:`claude/overseas-place-search-2049`。
|
||||
|
||||
@@ -809,6 +809,30 @@ section[popover]:has(> [data-sonner-toaster]), section[popover][aria-label^="页
|
||||
.birth-place-status > span { min-width: 0; text-wrap: pretty; word-break: auto-phrase; }
|
||||
.birth-place-retry { display: inline-flex; align-items: center; gap: 4px; flex: 0 0 auto; border: 0; background: transparent; color: var(--color-action); font: inherit; cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.birth-place-retry svg { width: 12px; height: 12px; }
|
||||
/* BUG-2049: a typed search for overseas places and for the country. The field looks like
|
||||
.select-trigger and the rows are .select-item, so it reads as one of the existing selects. */
|
||||
.birth-place-levels > label.birth-place-search { grid-column: 1 / -1; }
|
||||
.location-search { position: relative; min-width: 0; }
|
||||
.location-search-field { display: flex; align-items: center; gap: var(--space-3); min-width: 0; }
|
||||
.location-search-input { flex: 1 1 auto; width: 100%; min-width: 0; min-height: 44px; padding: 0 var(--space-3); border: 1px solid var(--color-border); border-radius: var(--radius-md); background: var(--color-canvas); color: var(--color-ink); font: inherit; text-align: left; transition: border-color 160ms ease-out, box-shadow 160ms ease-out, background-color 160ms ease-out; }
|
||||
.location-search-input::placeholder { color: var(--color-ink-tertiary); }
|
||||
.location-search-input:hover { border-color: color-mix(in srgb, var(--color-action) 42%, var(--color-border)); background: var(--color-canvas-soft); }
|
||||
.location-search-input:focus-visible { border-color: var(--color-action); outline: none; box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-action) 18%, transparent); }
|
||||
.location-search-input:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.location-search-panel { position: absolute; z-index: 30; top: calc(100% + 4px); left: 0; right: 0; max-height: min(320px, 56dvh); overflow-y: auto; overscroll-behavior: contain; border: 1px solid var(--color-border); border-radius: var(--radius-md); background: var(--color-canvas); padding: 5px; box-shadow: var(--shadow-elevated); }
|
||||
.location-search-list { display: grid; }
|
||||
.location-search-row { width: 100%; border: 0; background: transparent; font: inherit; text-align: left; }
|
||||
.location-search-primary { min-width: 0; overflow-wrap: anywhere; }
|
||||
.location-search-secondary { flex: 0 1 auto; min-width: 0; color: var(--color-ink-tertiary); font-size: var(--type-overline); text-align: right; overflow-wrap: anywhere; }
|
||||
.location-search-row[data-highlighted] .location-search-secondary { color: inherit; }
|
||||
.location-search-footer,
|
||||
.location-search-empty { margin: 0; padding: var(--space-2) var(--space-3); color: var(--color-ink-tertiary); font-size: var(--type-overline); line-height: 1.5; text-wrap: pretty; }
|
||||
.birth-place-text-button { flex: 0 0 auto; justify-self: start; border: 0; background: transparent; color: var(--color-action); font-size: var(--type-overline); cursor: pointer; text-decoration: underline; text-underline-offset: 2px; white-space: nowrap; }
|
||||
.birth-place-text-button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
@media (max-width: 640px) {
|
||||
/* On a phone the matches sit in the page under the field, so the keyboard never covers a floating list. */
|
||||
.location-search-panel { position: static; margin-top: 4px; max-height: 44dvh; box-shadow: none; }
|
||||
}
|
||||
.save-profile { justify-self: end; }
|
||||
.form-error { color: var(--color-danger); }
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { Check, MapPin, RotateCcw } from "lucide-react";
|
||||
import { InlineSpinner } from "@/components/inline-spinner";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import { PlaceSearchBox } from "@/components/ui/location-search-box";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
@@ -16,7 +17,24 @@ import {
|
||||
resolveBirthPlaceNode,
|
||||
} from "@/lib/china-birth-place";
|
||||
import { displayPlaceLabel, STORED_PLACE_SEPARATOR } from "@/lib/place-label";
|
||||
import { worldCityAliases } from "@/data/world-city-aliases";
|
||||
import { worldCountries, type WorldCountryData } from "@/data/world-countries";
|
||||
import {
|
||||
buildPlaceIndex,
|
||||
chosenPlaceText,
|
||||
filterCountryOptions,
|
||||
placeEntryTitle,
|
||||
searchPlaces,
|
||||
type CountryOption,
|
||||
} from "@/lib/world-place-search";
|
||||
|
||||
// BUG-2049: overseas places are found by typing; the level-by-level selects stay as a second way in.
|
||||
export const PLACE_SEARCH_PLACEHOLDER = "输入城市或地区的名字,可以输英文";
|
||||
export const PLACE_SEARCH_NOT_FOUND = "没有找到这个地方。可以选离它最近的城市,星盘差别很小。地名可以试试输英文。";
|
||||
export const PLACE_SEARCH_MORE = "显示前 20 条,继续输入可以缩小范围";
|
||||
export const PLACE_SEARCH_BY_LEVELS = "按地区一级级选";
|
||||
export const PLACE_SEARCH_BACK = "回到搜索";
|
||||
export const PLACE_SEARCH_CHANGE = "换一个";
|
||||
|
||||
/** Sentinel for "this city has districts but the user cannot name one". */
|
||||
const cityCentreOption = "__city_centre__";
|
||||
@@ -127,10 +145,13 @@ const otherCountryOptions = (() => {
|
||||
const collator = new Intl.Collator("zh-Hans-CN-u-co-pinyin");
|
||||
return worldCountries
|
||||
.filter((item) => item.code !== "CN")
|
||||
.map((item) => ({ code: item.code, label: countryLabel(item.code) }))
|
||||
.map((item) => ({ code: item.code, label: countryLabel(item.code), english: item.name }))
|
||||
.sort((left, right) => collator.compare(left.label, right.label));
|
||||
})();
|
||||
|
||||
/** China first, then the rest: the list the country field filters as the user types. */
|
||||
const countryOptions: readonly CountryOption[] = [{ code: "CN", label: "中国", english: "China" }, ...otherCountryOptions];
|
||||
|
||||
export function BirthPlacePicker({
|
||||
value,
|
||||
birthDate = "",
|
||||
@@ -155,6 +176,10 @@ export function BirthPlacePicker({
|
||||
const [globalLoadErrorCountry, setGlobalLoadErrorCountry] = useState("");
|
||||
const [outcome, setOutcome] = useState<TimezoneOutcome | null>(null);
|
||||
const [retryToken, setRetryToken] = useState(0);
|
||||
const [countryQuery, setCountryQuery] = useState("");
|
||||
const [placeQuery, setPlaceQuery] = useState("");
|
||||
// The country whose places are being picked level by level; any other country shows the search box.
|
||||
const [levelsCountry, setLevelsCountry] = useState("");
|
||||
// The birth moment the value's offset was resolved for. A historical offset depends on it.
|
||||
const birthMoment = `${birthDate}/${birthTime}`;
|
||||
const [valueMoment, setValueMoment] = useState(birthMoment);
|
||||
@@ -205,6 +230,15 @@ export function BirthPlacePicker({
|
||||
return () => controller.abort();
|
||||
}, [draft.countryCode]);
|
||||
|
||||
const placeIndex = useMemo(
|
||||
() => (globalData ? buildPlaceIndex(globalData, worldCityAliases) : null),
|
||||
[globalData],
|
||||
);
|
||||
const placeResult = placeIndex && placeIndex.country === draft.countryCode
|
||||
? searchPlaces(placeIndex, placeQuery)
|
||||
: null;
|
||||
const byLevels = !isChina && levelsCountry === draft.countryCode;
|
||||
|
||||
const globalRegion = !isChina && globalData?.code === draft.countryCode
|
||||
? globalData.regions.find((item) => item.code === draft.provinceCode)
|
||||
: undefined;
|
||||
@@ -349,6 +383,17 @@ export function BirthPlacePicker({
|
||||
setDraft((current) => ({ ...current, provinceCode: nextCode, cityCode: "", districtCode: "", cityCentre: false }));
|
||||
}
|
||||
|
||||
/** One row of the search sets both levels: the same draft the two selects would have built. */
|
||||
function chooseGlobalPlace(regionCode: string, cityCode: string) {
|
||||
setDraft((current) => ({ ...current, provinceCode: regionCode, cityCode, districtCode: "", cityCentre: false }));
|
||||
setPlaceQuery("");
|
||||
}
|
||||
|
||||
function clearGlobalPlace() {
|
||||
setDraft((current) => ({ ...current, provinceCode: "", cityCode: "", districtCode: "", cityCentre: false }));
|
||||
setPlaceQuery("");
|
||||
}
|
||||
|
||||
// A place with no lookup recorded against it is still being looked up.
|
||||
const settled: TimezoneState = syncKey === "empty"
|
||||
? { status: "idle" }
|
||||
@@ -389,28 +434,33 @@ export function BirthPlacePicker({
|
||||
? "选到区县就够了,同一个县内的差别不影响星盘。"
|
||||
: "选到城市就够了。";
|
||||
|
||||
const placeRows = (placeResult?.hits ?? []).map((item) => ({
|
||||
key: `${item.regionCode}/${item.cityCode}`,
|
||||
primary: placeEntryTitle(item),
|
||||
secondary: item.cityName ? item.regionName : undefined,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="birth-place-picker">
|
||||
<div className="birth-place-levels">
|
||||
<label htmlFor={`${fieldPrefix}-country`}>
|
||||
<span>国家 / 地区</span>
|
||||
<Select
|
||||
value={draft.countryCode || null}
|
||||
<PlaceSearchBox
|
||||
id={`${fieldPrefix}-country`}
|
||||
ariaLabel="出生国家或地区"
|
||||
placeholder="请选择"
|
||||
restingText={draft.countryCode === "CN" ? "中国" : countryLabel(draft.countryCode)}
|
||||
rows={filterCountryOptions(countryOptions, countryQuery).map((item) => ({
|
||||
key: item.code,
|
||||
primary: item.label,
|
||||
secondary: item.english,
|
||||
}))}
|
||||
onQuery={setCountryQuery}
|
||||
onChoose={(code) => { setCountryQuery(""); if (code !== draft.countryCode) chooseCountry(code); }}
|
||||
emptyText="没有这个国家或地区,换个写法试试。"
|
||||
openOnFocus
|
||||
disabled={disabled}
|
||||
onValueChange={(next) => { if (typeof next === "string") chooseCountry(next); }}
|
||||
>
|
||||
<SelectTrigger id={`${fieldPrefix}-country`} aria-label="出生国家或地区">
|
||||
<SelectValue placeholder="请选择">
|
||||
{(selected) => selected === "CN" ? "中国" : countryLabel(String(selected ?? "")) || "请选择"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="CN">中国</SelectItem>
|
||||
{otherCountryOptions.map((item) => (
|
||||
<SelectItem key={item.code} value={item.code}>{item.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
/>
|
||||
</label>
|
||||
|
||||
{isChina && (
|
||||
@@ -482,7 +532,32 @@ export function BirthPlacePicker({
|
||||
</label>
|
||||
)}
|
||||
|
||||
{!isChina && globalData && (
|
||||
{!isChina && !byLevels && globalData && (
|
||||
<label htmlFor={`${fieldPrefix}-place`} className="birth-place-search">
|
||||
<span>城市 / 地区</span>
|
||||
<PlaceSearchBox
|
||||
// A chosen place and an empty field are two fields: remount so the typed text never carries over.
|
||||
key={globalResolved ? globalResolved.providerPlaceId : "empty"}
|
||||
id={`${fieldPrefix}-place`}
|
||||
ariaLabel="出生海外地点"
|
||||
placeholder={PLACE_SEARCH_PLACEHOLDER}
|
||||
restingText={globalResolved ? chosenPlaceText(globalRegion?.name ?? "", globalCity?.name ?? "") : ""}
|
||||
rows={placeRows}
|
||||
onQuery={setPlaceQuery}
|
||||
onChoose={(key) => { const [regionCode, cityCode = ""] = key.split("/"); chooseGlobalPlace(regionCode, cityCode); }}
|
||||
footer={placeResult?.truncated ? PLACE_SEARCH_MORE : undefined}
|
||||
emptyText={placeResult?.searched ? PLACE_SEARCH_NOT_FOUND : undefined}
|
||||
disabled={disabled}
|
||||
trailing={globalResolved ? (
|
||||
<Button type="button" variant="ghost" className="birth-place-text-button h-auto px-0 font-normal shadow-none" disabled={disabled} onClick={clearGlobalPlace}>
|
||||
{PLACE_SEARCH_CHANGE}
|
||||
</Button>
|
||||
) : undefined}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{byLevels && globalData && (
|
||||
<label htmlFor={`${fieldPrefix}-region`}>
|
||||
<span>州 / 省 / 地区</span>
|
||||
<Select
|
||||
@@ -504,7 +579,7 @@ export function BirthPlacePicker({
|
||||
</label>
|
||||
)}
|
||||
|
||||
{!isChina && globalRegion && globalRegion.cities.length > 0 && (
|
||||
{byLevels && globalRegion && globalRegion.cities.length > 0 && (
|
||||
<label htmlFor={`${fieldPrefix}-global-city`}>
|
||||
<span>城市</span>
|
||||
<Select
|
||||
@@ -527,6 +602,18 @@ export function BirthPlacePicker({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isChina && globalData && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="birth-place-text-button h-auto px-0 font-normal shadow-none"
|
||||
disabled={disabled}
|
||||
onClick={() => setLevelsCountry(byLevels ? "" : draft.countryCode)}
|
||||
>
|
||||
{byLevels ? PLACE_SEARCH_BACK : PLACE_SEARCH_BY_LEVELS}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<p
|
||||
className={`birth-place-status${settled.status === "error" ? " is-error" : ""}${settled.status === "ready" ? " is-ready" : ""}`}
|
||||
role="status"
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useId, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* A text field with a list of matches under it (BUG-2049). The product had no
|
||||
* searchable select; this one is built from a plain input and rows styled as
|
||||
* `.select-item`, kept inline so it also works inside dialogs and sheets.
|
||||
*/
|
||||
|
||||
export type PlaceSearchRow = { key: string; primary: string; secondary?: string };
|
||||
|
||||
type PlaceSearchBoxProps = {
|
||||
id: string;
|
||||
ariaLabel: string;
|
||||
placeholder: string;
|
||||
/** What the field shows while it is not being typed in. */
|
||||
restingText: string;
|
||||
rows: readonly PlaceSearchRow[];
|
||||
/** Typed text, reported on every keystroke; empty when the list first opens. */
|
||||
onQuery: (text: string) => void;
|
||||
onChoose: (key: string) => void;
|
||||
/** A line under the rows, e.g. that only the first matches are shown. */
|
||||
footer?: string;
|
||||
/** Shown instead of rows when the query found nothing. */
|
||||
emptyText?: string;
|
||||
/** Open the list as soon as the field has focus, before anything is typed. */
|
||||
openOnFocus?: boolean;
|
||||
disabled?: boolean;
|
||||
trailing?: ReactNode;
|
||||
};
|
||||
|
||||
export function PlaceSearchBox({
|
||||
id,
|
||||
ariaLabel,
|
||||
placeholder,
|
||||
restingText,
|
||||
rows,
|
||||
onQuery,
|
||||
onChoose,
|
||||
footer,
|
||||
emptyText,
|
||||
openOnFocus = false,
|
||||
disabled = false,
|
||||
trailing,
|
||||
}: PlaceSearchBoxProps) {
|
||||
const listId = `${useId()}-list`;
|
||||
// null: the field rests on `restingText`; a string: the user is typing.
|
||||
const [typed, setTyped] = useState<string | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const editing = typed !== null;
|
||||
const hasPanel = editing && (rows.length > 0 || Boolean(emptyText));
|
||||
const activeIndex = rows.length === 0 ? -1 : Math.min(active, rows.length - 1);
|
||||
|
||||
function start(text: string) {
|
||||
setTyped(text);
|
||||
setActive(0);
|
||||
onQuery(text);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
setTyped(null);
|
||||
setActive(0);
|
||||
}
|
||||
|
||||
function choose(key: string) {
|
||||
stop();
|
||||
onChoose(key);
|
||||
}
|
||||
|
||||
function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
if (!editing) { start(""); event.preventDefault(); return; }
|
||||
if (rows.length === 0) return;
|
||||
event.preventDefault();
|
||||
const step = event.key === "ArrowDown" ? 1 : -1;
|
||||
setActive((activeIndex + step + rows.length) % rows.length);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
if (!editing) return;
|
||||
// Never submit the surrounding form from an open list.
|
||||
event.preventDefault();
|
||||
if (activeIndex >= 0) choose(rows[activeIndex].key);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape" && editing) {
|
||||
// Close the list only; the dialog around it stays open.
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
stop();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="location-search" data-open={hasPanel ? "" : undefined}>
|
||||
<div className="location-search-field">
|
||||
<input
|
||||
id={id}
|
||||
className="location-search-input"
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-label={ariaLabel}
|
||||
aria-autocomplete="list"
|
||||
aria-expanded={hasPanel}
|
||||
aria-controls={listId}
|
||||
aria-activedescendant={hasPanel && activeIndex >= 0 ? `${listId}-${activeIndex}` : undefined}
|
||||
autoComplete="off"
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
enterKeyHint="search"
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
value={typed ?? restingText}
|
||||
onFocus={(event) => {
|
||||
if (openOnFocus && !editing) start("");
|
||||
event.currentTarget.select?.();
|
||||
}}
|
||||
onChange={(event) => start(event.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
onBlur={stop}
|
||||
/>
|
||||
{trailing}
|
||||
</div>
|
||||
{hasPanel && (
|
||||
<div className="location-search-panel">
|
||||
{rows.length > 0 ? (
|
||||
<div className="location-search-list" role="listbox" id={listId} aria-label={ariaLabel}>
|
||||
{rows.map((row, index) => (
|
||||
<button
|
||||
key={row.key}
|
||||
id={`${listId}-${index}`}
|
||||
type="button"
|
||||
role="option"
|
||||
tabIndex={-1}
|
||||
aria-selected={index === activeIndex}
|
||||
data-highlighted={index === activeIndex ? "" : undefined}
|
||||
className="select-item location-search-row"
|
||||
// Keep the focus in the field so the blur does not close the list before the click lands.
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onMouseEnter={() => setActive(index)}
|
||||
onClick={() => choose(row.key)}
|
||||
>
|
||||
<span className="location-search-primary">{row.primary}</span>
|
||||
{row.secondary && <span className="location-search-secondary">{row.secondary}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="location-search-empty" role="status">{emptyText}</p>
|
||||
)}
|
||||
{rows.length > 0 && footer && <p className="location-search-footer">{footer}</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// Chinese names for major overseas cities, so a user can type 伦敦 and find London (BUG-2049).
|
||||
// An alias only helps the search: the place itself is the bundled entry it points at
|
||||
// (public/data/world-locations/<country>.json), whose coordinates and timezone are used unchanged.
|
||||
// tests/overseas-place-search-2049.test.ts resolves every row against that data.
|
||||
|
||||
export type WorldCityAlias = { zh: string; country: string; regionCode: string; cityCode: string };
|
||||
|
||||
const rows: ReadonlyArray<readonly [zh: string, country: string, regionCode: string, cityCode: string]> = [
|
||||
["纽约", "US", "US-NY", "122795"], // New York City, New York
|
||||
["洛杉矶", "US", "US-CA", "120784"], // Los Angeles, California
|
||||
["旧金山", "US", "US-CA", "125809"], // San Francisco, California
|
||||
["圣何塞", "US", "US-CA", "125816"], // San Jose, California
|
||||
["圣地亚哥", "US", "US-CA", "125802"], // San Diego, California
|
||||
["萨克拉门托", "US", "US-CA", "125577"], // Sacramento, California
|
||||
["尔湾", "US", "US-CA", "119004"], // Irvine, California
|
||||
["芝加哥", "US", "US-IL", "113931"], // Chicago, Illinois
|
||||
["休斯敦", "US", "US-TX", "118699"], // Houston, Texas
|
||||
["达拉斯", "US", "US-TX", "114990"], // Dallas, Texas
|
||||
["奥斯汀", "US", "US-TX", "111668"], // Austin, Texas
|
||||
["西雅图", "US", "US-WA", "126104"], // Seattle, Washington
|
||||
["波士顿", "US", "US-MA", "112589"], // Boston, Massachusetts
|
||||
["华盛顿", "US", "US-DC", "128587"], // Washington D.C., District of Columbia
|
||||
["费城", "US", "US-PA", "124126"], // Philadelphia, Pennsylvania
|
||||
["匹兹堡", "US", "US-PA", "124296"], // Pittsburgh, Pennsylvania
|
||||
["亚特兰大", "US", "US-GA", "111590"], // Atlanta, Georgia
|
||||
["迈阿密", "US", "US-FL", "121746"], // Miami, Florida
|
||||
["奥兰多", "US", "US-FL", "123562"], // Orlando, Florida
|
||||
["拉斯维加斯", "US", "US-NV", "120163"], // Las Vegas, Nevada
|
||||
["凤凰城", "US", "US-AZ", "124148"], // Phoenix, Arizona
|
||||
["丹佛", "US", "US-CO", "115253"], // Denver, Colorado
|
||||
["底特律", "US", "US-MI", "115291"], // Detroit, Michigan
|
||||
["明尼阿波利斯", "US", "US-MN", "121951"], // Minneapolis, Minnesota
|
||||
["波特兰", "US", "US-OR", "124565"], // Portland, Oregon
|
||||
["檀香山", "US", "US-HI", "118623"], // Honolulu, Hawaii
|
||||
["巴尔的摩", "US", "US-MD", "111783"], // Baltimore, Maryland
|
||||
["盐湖城", "US", "US-UT", "125767"], // Salt Lake City, Utah
|
||||
["新奥尔良", "US", "US-LA", "122756"], // New Orleans, Louisiana
|
||||
["纳什维尔", "US", "US-TN", "122577"], // Nashville, Tennessee
|
||||
["夏洛特", "US", "US-NC", "113776"], // Charlotte, North Carolina
|
||||
["圣路易斯", "US", "US-MO", "126928"], // St. Louis, Missouri
|
||||
["哥伦布", "US", "US-OH", "141234"], // Columbus, Ohio
|
||||
["克利夫兰", "US", "US-OH", "141223"], // Cleveland, Ohio
|
||||
["多伦多", "CA", "CA-ON", "17121"], // Toronto, Ontario
|
||||
["渥太华", "CA", "CA-ON", "16785"], // Ottawa, Ontario
|
||||
["温哥华", "CA", "CA-BC", "17145"], // Vancouver, British Columbia
|
||||
["维多利亚", "CA", "CA-BC", "17156"], // Victoria, British Columbia
|
||||
["蒙特利尔", "CA", "CA-QC", "16709"], // Montréal, Quebec
|
||||
["魁北克", "CA", "CA-QC", "16867"], // Québec, Quebec
|
||||
["卡尔加里", "CA", "CA-AB", "16259"], // Calgary, Alberta
|
||||
["埃德蒙顿", "CA", "CA-AB", "16396"], // Edmonton, Alberta
|
||||
["温尼伯", "CA", "CA-MB", "17215"], // Winnipeg, Manitoba
|
||||
["哈利法克斯", "CA", "CA-NS", "16482"], // Halifax, Nova Scotia
|
||||
["伦敦", "GB", "GB-WSM", "50388"], // London, Westminster
|
||||
["曼彻斯特", "GB", "GB-SKP", "50481"], // Manchester, Stockport
|
||||
["伯明翰", "GB", "GB-BIR", "48521"], // Birmingham, Birmingham
|
||||
["利物浦", "GB", "GB-LIV", "50337"], // Liverpool, Liverpool
|
||||
["爱丁堡", "GB", "GB-EDH", "49441"], // Edinburgh, Edinburgh
|
||||
["格拉斯哥", "GB", "GB-GLG", "49650"], // Glasgow, Glasgow
|
||||
["牛津", "GB", "GB-OXF", "50840"], // Oxford, Oxfordshire
|
||||
["剑桥", "GB", "GB-CAM", "48834"], // Cambridge, Cambridgeshire
|
||||
["利兹", "GB", "GB-LDS", "50270"], // Leeds, Leeds
|
||||
["布里斯托", "GB", "GB-BST", "48703"], // Bristol, Bristol
|
||||
["谢菲尔德", "GB", "GB-SHF", "51255"], // Sheffield, Sheffield
|
||||
["纽卡斯尔", "GB", "GB-NET", "50710"], // Newcastle upon Tyne, Newcastle upon Tyne
|
||||
["诺丁汉", "GB", "GB-NGM", "50786"], // Nottingham, Nottingham
|
||||
["卡迪夫", "GB", "GB-CRF", "48854"], // Cardiff, Cardiff
|
||||
["贝尔法斯特", "GB", "GB-BFS", "48458"], // Belfast, Belfast
|
||||
["悉尼", "AU", "AU-NSW", "7408"], // Sydney, New South Wales
|
||||
["墨尔本", "AU", "AU-VIC", "6235"], // Melbourne, Victoria
|
||||
["布里斯班", "AU", "AU-QLD", "4411"], // Brisbane, Queensland
|
||||
["珀斯", "AU", "AU-WA", "6840"], // Perth, Western Australia
|
||||
["阿德莱德", "AU", "AU-SA", "3919"], // Adelaide, South Australia
|
||||
["堪培拉", "AU", "AU-ACT", "4566"], // Canberra, Australian Capital Territory
|
||||
["黄金海岸", "AU", "AU-QLD", "5400"], // Gold Coast, Queensland
|
||||
["霍巴特", "AU", "AU-TAS", "5621"], // Hobart, Tasmania
|
||||
["奥克兰", "NZ", "NZ-AUK", "79773"], // Auckland, Auckland
|
||||
["惠灵顿", "NZ", "NZ-WGN", "79915"], // Wellington, Wellington
|
||||
["基督城", "NZ", "NZ-CAN", "79783"], // Christchurch, Canterbury
|
||||
["东京", "JP", "JP-13", "64500"], // Tokyo, Tokyo
|
||||
["大阪", "JP", "JP-27", "64214"], // Osaka, Ōsaka
|
||||
["京都", "JP", "JP-26", "63890"], // Kyoto, Kyōto
|
||||
["横滨", "JP", "JP-14", "64670"], // Yokohama, Kanagawa
|
||||
["名古屋", "JP", "JP-23", "64078"], // Nagoya, Aichi
|
||||
["神户", "JP", "JP-28", "63820"], // Kobe, Hyōgo
|
||||
["福冈", "JP", "JP-40", "63365"], // Fukuoka, Fukuoka
|
||||
["札幌", "JP", "JP-01", "64285"], // Sapporo, Hokkaidō
|
||||
["仙台", "JP", "JP-04", "64300"], // Sendai, Miyagi
|
||||
["广岛", "JP", "JP-34", "63499"], // Hiroshima, Hiroshima
|
||||
["那霸", "JP", "JP-47", "64079"], // Naha, Okinawa
|
||||
["首尔", "KR", "KR-11", "65498"], // Seoul, Seoul
|
||||
["釜山", "KR", "KR-26", "65278"], // Busan, Busan
|
||||
["仁川", "KR", "KR-28", "65400"], // Incheon, Incheon
|
||||
["大邱", "KR", "KR-27", "65300"], // Daegu, Daegu
|
||||
["济州", "KR", "KR-49", "65406"], // Jeju City, Jeju
|
||||
["新加坡", "SG", "SG-01", "104057"], // Singapore, Central Singapore
|
||||
["吉隆坡", "MY", "MY-14", "76497"], // Kuala Lumpur, Kuala Lumpur
|
||||
["槟城", "MY", "MY-07", "76447"], // George Town, Penang
|
||||
["新山", "MY", "MY-01", "76455"], // Johor Bahru, Johor
|
||||
["怡保", "MY", "MY-08", "76450"], // Ipoh, Perak
|
||||
["马六甲", "MY", "MY-04", "76520"], // Malacca, Malacca
|
||||
["古晋", "MY", "MY-13", "76506"], // Kuching, Sarawak
|
||||
["亚庇", "MY", "MY-12", "76490"], // Kota Kinabalu, Sabah
|
||||
["曼谷", "TH", "TH-10", "106448"], // Bangkok, Bangkok
|
||||
["清迈", "TH", "TH-50", "106474"], // Chiang Mai, Chiang Mai
|
||||
["普吉", "TH", "TH-83", "106650"], // Phuket, Phuket
|
||||
["胡志明市", "VN", "VN-SG", "130202"], // Ho Chi Minh City, Hồ Chí Minh
|
||||
["岘港", "VN", "VN-DN", "130195"], // Da Nang, Đà Nẵng
|
||||
["雅加达", "ID", "ID-JK", "154470"], // Jakarta Pusat, DKI Jakarta
|
||||
["泗水", "ID", "ID-JI", "57011"], // Surabaya, Jawa Timur
|
||||
["万隆", "ID", "ID-JB", "56196"], // Bandung, Jawa Barat
|
||||
["棉兰", "ID", "ID-SU", "56867"], // Medan, Sumatera Utara
|
||||
["马尼拉", "PH", "PH-00", "161633"], // Manila, National Capital Region (Metro Manila)
|
||||
["宿务", "PH", "PH-CEB", "82238"], // Cebu City, Cebu
|
||||
["奎松城", "PH", "PH-00", "161639"], // Quezon City, National Capital Region (Metro Manila)
|
||||
["新德里", "IN", "IN-DL", "133210"], // New Delhi, Delhi
|
||||
["德里", "IN", "IN-DL", "131679"], // Delhi, Delhi
|
||||
["孟买", "IN", "IN-MH", "133024"], // Mumbai, Maharashtra
|
||||
["班加罗尔", "IN", "IN-KA", "57933"], // Bengaluru, Karnataka
|
||||
["加尔各答", "IN", "IN-WB", "142001"], // Kolkata, West Bengal
|
||||
["金奈", "IN", "IN-TN", "131517"], // Chennai, Tamil Nadu
|
||||
["海得拉巴", "IN", "IN-TG", "132132"], // Hyderabad, Telangana
|
||||
["柏林", "DE", "DE-BE", "24053"], // Berlin, Berlin
|
||||
["慕尼黑", "DE", "DE-BY", "27540"], // Munich, Bavaria
|
||||
["法兰克福", "DE", "DE-HE", "25222"], // Frankfurt am Main, Hessen
|
||||
["汉堡", "DE", "DE-HH", "25866"], // Hamburg, Hamburg
|
||||
["科隆", "DE", "DE-NW", "26818"], // Köln, North Rhine-Westphalia
|
||||
["杜塞尔多夫", "DE", "DE-NW", "24817"], // Düsseldorf, North Rhine-Westphalia
|
||||
["斯图加特", "DE", "DE-BW", "29444"], // Stuttgart, Baden-Württemberg
|
||||
["巴黎", "FR", "FR-75C", "44856"], // Paris, Paris
|
||||
["里昂", "FR", "FR-69", "43678"], // Lyon, Rhône
|
||||
["马赛", "FR", "FR-13", "43883"], // Marseille, Bouches-du-Rhône
|
||||
["尼斯", "FR", "FR-06", "44587"], // Nice, Alpes-Maritimes
|
||||
["图卢兹", "FR", "FR-31", "47316"], // Toulouse, Haute-Garonne
|
||||
["波尔多", "FR", "FR-33", "40136"], // Bordeaux, Gironde
|
||||
["罗马", "IT", "IT-RM", "59582"], // Rome, Rome
|
||||
["米兰", "IT", "IT-MI", "140142"], // Milan, Milan
|
||||
["佛罗伦萨", "IT", "IT-FI", "138563"], // Florence, Florence
|
||||
["威尼斯", "IT", "IT-VE", "61822"], // Venice, Venice
|
||||
["那不勒斯", "IT", "IT-NA", "140713"], // Naples, Naples
|
||||
["都灵", "IT", "IT-TO", "61575"], // Turin, Turin
|
||||
["马德里", "ES", "ES-M", "35186"], // Madrid, Madrid
|
||||
["巴塞罗那", "ES", "ES-B", "32653"], // Barcelona, Barcelona
|
||||
["瓦伦西亚", "ES", "ES-V", "37816"], // Valencia, Valencia
|
||||
["塞维利亚", "ES", "ES-SE", "37239"], // Sevilla, Sevilla
|
||||
["阿姆斯特丹", "NL", "NL-NH", "77340"], // Amsterdam, North Holland
|
||||
["鹿特丹", "NL", "NL-ZH", "78642"], // Rotterdam, South Holland
|
||||
["海牙", "NL", "NL-ZH", "78779"], // The Hague, South Holland
|
||||
["乌得勒支", "NL", "NL-UT", "78822"], // Utrecht, Utrecht
|
||||
["苏黎世", "CH", "CH-ZH", "18809"], // Zürich, Zürich
|
||||
["日内瓦", "CH", "CH-GE", "17827"], // Geneva, Geneva
|
||||
["伯尔尼", "CH", "CH-BE", "17462"], // Bern, Bern
|
||||
["巴塞尔", "CH", "CH-BS", "149129"], // Basel, Basel-Stadt
|
||||
["莫斯科", "RU", "RU-MOW", "99972"], // Moscow, Moscow
|
||||
["圣彼得堡", "RU", "RU-SPE", "101074"], // Saint Petersburg, Saint Petersburg
|
||||
["海参崴", "RU", "RU-PRI", "102330"], // Vladivostok, Primorsky
|
||||
["迪拜", "AE", "AE-DU", "32"], // Dubai, Dubai
|
||||
["阿布扎比", "AE", "AE-AZ", "12"], // Abu Dhabi, Abu Dhabi
|
||||
["圣保罗", "BR", "BR-SP", "15101"], // São Paulo, São Paulo
|
||||
["里约热内卢", "BR", "BR-RJ", "14309"], // Rio de Janeiro, Rio de Janeiro
|
||||
["巴西利亚", "BR", "BR-DF", "10776"], // Brasília, Distrito Federal
|
||||
["都柏林", "IE", "IE-L", "57223"], // Dublin, Leinster
|
||||
["斯德哥尔摩", "SE", "SE-AB", "103758"], // Stockholm, Stockholm
|
||||
["奥斯陆", "NO", "NO-03", "79425"], // Oslo, Oslo
|
||||
["哥本哈根", "DK", "DK-84", "30620"], // Copenhagen, Denmark
|
||||
["赫尔辛基", "FI", "FI-18", "38770"], // Helsinki, Uusimaa
|
||||
["布鲁塞尔", "BE", "BE-BRU", "8693"], // Brussels, Brussels-Capital
|
||||
["维也纳", "AT", "AT-9", "3681"], // Vienna, Vienna
|
||||
["里斯本", "PT", "PT-11", "89245"], // Lisbon, Lisbon
|
||||
["雅典", "GR", "GR-I", "52515"], // Athens, Attica
|
||||
["伊斯坦布尔", "TR", "TR-34", "153786"], // Istanbul, İstanbul
|
||||
["安卡拉", "TR", "TR-06", "153787"], // Ankara, Ankara
|
||||
["特拉维夫", "IL", "IL-TA", "57564"], // Tel Aviv, Tel Aviv
|
||||
["利雅得", "SA", "SA-01", "102874"], // Riyadh, Riyadh
|
||||
["多哈", "QA", "QA-DA", "89864"], // Doha, Doha
|
||||
["开罗", "EG", "EG-C", "31802"], // Cairo, Cairo
|
||||
["约翰内斯堡", "ZA", "ZA-GP", "131136"], // Johannesburg, Gauteng
|
||||
["开普敦", "ZA", "ZA-WC", "131059"], // Cape Town, Western Cape
|
||||
["墨西哥城", "MX", "MX-CMX", "72102"], // Mexico City, Ciudad de México
|
||||
["圣地亚哥", "CL", "CL-RM", "19111"], // Santiago, Región Metropolitana de Santiago
|
||||
["利马", "PE", "PE-LIM", "80701"], // Lima, Lima
|
||||
["华沙", "PL", "PL-14", "88480"], // Warsaw, Mazovia
|
||||
["布拉格", "CZ", "CZ-10", "22970"], // Prague, Praha, Hlavní město
|
||||
["布达佩斯", "HU", "HU-BU", "55263"], // Budapest, Budapest
|
||||
["金边", "KH", "KH-12", "64970"], // Phnom Penh, Phnom Penh
|
||||
["仰光", "MM", "MM-06", "67703"], // Yangon, Yangon
|
||||
["万象", "LA", "LA-VT", "65927"], // Vientiane, Vientiane
|
||||
["加德满都", "NP", "NP-P3", "79726"], // Kathmandu, Bagmati
|
||||
["卡拉奇", "PK", "PK-SD", "85521"], // Karachi, Sindh
|
||||
["达卡", "BD", "BD-13", "153863"], // Dhaka, Dhaka
|
||||
["科伦坡", "LK", "LK-1", "66461"], // Colombo, Western
|
||||
["乌兰巴托", "MN", "MN-047", "153783"], // Ulan Bator, Töv
|
||||
["阿拉木图", "KZ", "KZ-75", "65607"], // Almaty, Almaty
|
||||
["河内", "VN", "VN-HN", "154446"], // Hoàn Kiếm, Hà Nội
|
||||
];
|
||||
|
||||
export const worldCityAliases: readonly WorldCityAlias[] = rows.map(([zh, country, regionCode, cityCode]) => ({ zh, country, regionCode, cityCode }));
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { WorldCountryData } from "@/data/world-countries";
|
||||
import type { WorldCityAlias } from "@/data/world-city-aliases";
|
||||
|
||||
/**
|
||||
* In-browser search over one country's bundled place table (BUG-2049).
|
||||
* Nothing leaves the page: the country file is already loaded by the picker.
|
||||
*/
|
||||
|
||||
export const PLACE_SEARCH_LIMIT = 20;
|
||||
/** Latin queries need two characters; one Chinese character is already a word. */
|
||||
export const PLACE_SEARCH_MIN_LATIN = 2;
|
||||
|
||||
export type PlaceEntry = {
|
||||
regionCode: string;
|
||||
regionName: string;
|
||||
/** Empty for a region the table lists without cities. */
|
||||
cityCode: string;
|
||||
cityName: string;
|
||||
/** Chinese name from the alias table, when the city has one. */
|
||||
alias: string;
|
||||
cityKey: string;
|
||||
regionKey: string;
|
||||
};
|
||||
|
||||
export type PlaceIndex = { country: string; entries: PlaceEntry[] };
|
||||
|
||||
export type PlaceSearchResult = {
|
||||
hits: PlaceEntry[];
|
||||
/** More places matched than `hits` holds. */
|
||||
truncated: boolean;
|
||||
/** The query was long enough to search. */
|
||||
searched: boolean;
|
||||
};
|
||||
|
||||
const HAN = /\p{Script=Han}/u;
|
||||
|
||||
/** Lower case, no diacritics, punctuation as spaces: "Québec" and "St. Louis" match "quebec" and "st louis". */
|
||||
export function placeSearchKey(text: string): string {
|
||||
return text
|
||||
.normalize("NFD")
|
||||
.replace(/\p{Mn}/gu, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function buildPlaceIndex(data: WorldCountryData, aliases: readonly WorldCityAlias[] = []): PlaceIndex {
|
||||
const aliasByCity = new Map<string, string>();
|
||||
for (const alias of aliases) {
|
||||
if (alias.country === data.code) aliasByCity.set(`${alias.regionCode}/${alias.cityCode}`, alias.zh);
|
||||
}
|
||||
const entries: PlaceEntry[] = [];
|
||||
for (const region of data.regions) {
|
||||
const regionKey = placeSearchKey(region.name);
|
||||
if (region.cities.length === 0) {
|
||||
entries.push({ regionCode: region.code, regionName: region.name, cityCode: "", cityName: "", alias: "", cityKey: "", regionKey });
|
||||
continue;
|
||||
}
|
||||
for (const city of region.cities) {
|
||||
entries.push({
|
||||
regionCode: region.code,
|
||||
regionName: region.name,
|
||||
cityCode: city.code,
|
||||
cityName: city.name,
|
||||
alias: aliasByCity.get(`${region.code}/${city.code}`) ?? "",
|
||||
cityKey: placeSearchKey(city.name),
|
||||
regionKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
entries.sort((left, right) => left.cityKey.localeCompare(right.cityKey) || left.regionKey.localeCompare(right.regionKey));
|
||||
return { country: data.code, entries };
|
||||
}
|
||||
|
||||
/**
|
||||
* City names first (prefix, then a later word's prefix, then anywhere), then
|
||||
* region names; inside a rank the order is alphabetical. Chinese input searches
|
||||
* the alias names only, because the table itself is spelled in Latin letters.
|
||||
*/
|
||||
export function searchPlaces(index: PlaceIndex, query: string, limit = PLACE_SEARCH_LIMIT): PlaceSearchResult {
|
||||
const raw = query.trim();
|
||||
if (HAN.test(raw)) {
|
||||
const prefix: PlaceEntry[] = [];
|
||||
const inside: PlaceEntry[] = [];
|
||||
for (const entry of index.entries) {
|
||||
if (!entry.alias) continue;
|
||||
if (entry.alias.startsWith(raw)) prefix.push(entry);
|
||||
else if (entry.alias.includes(raw)) inside.push(entry);
|
||||
}
|
||||
const all = [...prefix, ...inside];
|
||||
return { hits: all.slice(0, limit), truncated: all.length > limit, searched: true };
|
||||
}
|
||||
const key = placeSearchKey(raw);
|
||||
if (key.length < PLACE_SEARCH_MIN_LATIN) return { hits: [], truncated: false, searched: false };
|
||||
const buckets: PlaceEntry[][] = [[], [], [], [], []];
|
||||
let total = 0;
|
||||
const spaced = ` ${key}`;
|
||||
for (const entry of index.entries) {
|
||||
let rank = -1;
|
||||
if (entry.cityKey) {
|
||||
if (entry.cityKey.startsWith(key)) rank = 0;
|
||||
else if (entry.cityKey.includes(spaced)) rank = 1;
|
||||
else if (entry.cityKey.includes(key)) rank = 2;
|
||||
}
|
||||
if (rank < 0) {
|
||||
if (entry.regionKey.startsWith(key)) rank = 3;
|
||||
else if (entry.regionKey.includes(key)) rank = 4;
|
||||
}
|
||||
if (rank < 0) continue;
|
||||
total += 1;
|
||||
if (buckets[rank].length < limit) buckets[rank].push(entry);
|
||||
}
|
||||
return { hits: buckets.flat().slice(0, limit), truncated: total > limit, searched: true };
|
||||
}
|
||||
|
||||
/** "London(伦敦)": the table's own spelling first, the Chinese name as a gloss. */
|
||||
export function placeEntryTitle(entry: PlaceEntry): string {
|
||||
const name = entry.cityName || entry.regionName;
|
||||
return entry.alias ? `${name}(${entry.alias})` : name;
|
||||
}
|
||||
|
||||
/** What the search box shows for a chosen place: "Dersingham, Norfolk". */
|
||||
export function chosenPlaceText(regionName: string, cityName: string): string {
|
||||
return cityName && cityName !== regionName ? `${cityName}, ${regionName}` : regionName;
|
||||
}
|
||||
|
||||
export type CountryOption = { code: string; label: string; english: string };
|
||||
|
||||
/** Chinese name or English name, anywhere in the name; a two-letter code also matches. Pinyin is not searched. */
|
||||
export function filterCountryOptions(options: readonly CountryOption[], query: string): CountryOption[] {
|
||||
const raw = query.trim();
|
||||
if (!raw) return [...options];
|
||||
const key = placeSearchKey(raw);
|
||||
const prefix: CountryOption[] = [];
|
||||
const inside: CountryOption[] = [];
|
||||
for (const option of options) {
|
||||
const english = placeSearchKey(option.english);
|
||||
if (option.label.startsWith(raw) || (key && english.startsWith(key)) || option.code.toLowerCase() === raw.toLowerCase()) prefix.push(option);
|
||||
else if (option.label.includes(raw) || (key && english.includes(key))) inside.push(option);
|
||||
}
|
||||
return [...prefix, ...inside];
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import "./install-test-document";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
|
||||
import { createClientLifecycleHarness } from "./react-client-lifecycle-test-support";
|
||||
import {
|
||||
BirthPlacePicker,
|
||||
PLACE_SEARCH_BACK,
|
||||
PLACE_SEARCH_BY_LEVELS,
|
||||
PLACE_SEARCH_CHANGE,
|
||||
PLACE_SEARCH_MORE,
|
||||
PLACE_SEARCH_NOT_FOUND,
|
||||
PLACE_SEARCH_PLACEHOLDER,
|
||||
type BirthPlaceSelection,
|
||||
} from "../src/components/birth-place-picker";
|
||||
import { worldCityAliases } from "../src/data/world-city-aliases";
|
||||
import { worldCountries, type WorldCountryData } from "../src/data/world-countries";
|
||||
import {
|
||||
buildPlaceIndex,
|
||||
chosenPlaceText,
|
||||
filterCountryOptions,
|
||||
placeEntryTitle,
|
||||
placeSearchKey,
|
||||
searchPlaces,
|
||||
PLACE_SEARCH_LIMIT,
|
||||
} from "../src/lib/world-place-search";
|
||||
|
||||
// BUG-2049 (2026-11-20): overseas birth places are found by typing. The search runs in the
|
||||
// browser over the country file the picker already loads; choosing a row must give exactly
|
||||
// what the two selects gave.
|
||||
Object.assign(globalThis, { React });
|
||||
|
||||
const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");
|
||||
const country = (code: string) => JSON.parse(read(`../public/data/world-locations/${code}.json`)) as WorldCountryData;
|
||||
const gb = country("gb");
|
||||
const us = country("us");
|
||||
const ca = country("ca");
|
||||
|
||||
test("city names rank before region names, prefixes before the middle of a word", () => {
|
||||
const index = buildPlaceIndex(gb, worldCityAliases);
|
||||
const ders = searchPlaces(index, "ders");
|
||||
assert.equal(ders.searched, true);
|
||||
assert.equal(ders.hits[0].cityName, "Dersingham");
|
||||
assert.equal(ders.hits[0].regionName, "Norfolk");
|
||||
assert.ok(ders.hits.every((hit) => placeSearchKey(hit.cityName).includes("ders") || placeSearchKey(hit.regionName).includes("ders")));
|
||||
|
||||
// A region name finds that region's cities, after any city that matches by name.
|
||||
const norfolk = searchPlaces(index, "Norfolk");
|
||||
assert.ok(norfolk.hits.length > 0);
|
||||
assert.ok(norfolk.hits.some((hit) => hit.regionName === "Norfolk"));
|
||||
const firstRegionOnly = norfolk.hits.findIndex((hit) => !placeSearchKey(hit.cityName).includes("norfolk"));
|
||||
const lastCityMatch = norfolk.hits.map((hit) => placeSearchKey(hit.cityName).includes("norfolk")).lastIndexOf(true);
|
||||
assert.ok(firstRegionOnly === -1 || firstRegionOnly > lastCityMatch);
|
||||
|
||||
// One letter is not searched; nothing is listed and no "not found" is claimed.
|
||||
assert.deepEqual(searchPlaces(index, "d"), { hits: [], truncated: false, searched: false });
|
||||
});
|
||||
|
||||
test("case, accents and punctuation do not matter", () => {
|
||||
const canada = buildPlaceIndex(ca, worldCityAliases);
|
||||
assert.ok(searchPlaces(canada, "montreal").hits.some((hit) => hit.cityName === "Montréal"));
|
||||
assert.ok(searchPlaces(canada, "QUEBEC").hits.some((hit) => hit.cityName === "Québec"));
|
||||
const states = buildPlaceIndex(us, worldCityAliases);
|
||||
assert.ok(searchPlaces(states, "st louis").hits.some((hit) => hit.cityName === "St. Louis" && hit.regionName === "Missouri"));
|
||||
});
|
||||
|
||||
test("at most twenty rows are returned and the caller is told there are more", () => {
|
||||
const index = buildPlaceIndex(us, worldCityAliases);
|
||||
const san = searchPlaces(index, "san");
|
||||
assert.equal(san.hits.length, PLACE_SEARCH_LIMIT);
|
||||
assert.equal(san.truncated, true);
|
||||
assert.equal(PLACE_SEARCH_LIMIT, 20);
|
||||
assert.match(PLACE_SEARCH_MORE, /前 20 条/);
|
||||
const narrow = searchPlaces(index, "san francisco");
|
||||
assert.equal(narrow.hits[0].cityName, "San Francisco");
|
||||
assert.equal(narrow.hits[0].regionName, "California");
|
||||
assert.equal(placeEntryTitle(narrow.hits[0]), "San Francisco(旧金山)");
|
||||
});
|
||||
|
||||
test("the United States table is searched without a noticeable pause", () => {
|
||||
const cities = us.regions.reduce((sum, region) => sum + region.cities.length, 0);
|
||||
assert.ok(cities > 16000);
|
||||
const builtAt = performance.now();
|
||||
const index = buildPlaceIndex(us, worldCityAliases);
|
||||
const buildMs = performance.now() - builtAt;
|
||||
const startedAt = performance.now();
|
||||
for (const query of ["sa", "san", "new", "spring", "los angeles", "zz"]) searchPlaces(index, query);
|
||||
const perQuery = (performance.now() - startedAt) / 6;
|
||||
// Generous bounds for a loaded test machine; a keystroke is a few milliseconds in practice.
|
||||
assert.ok(buildMs < 1500, `index built in ${buildMs.toFixed(0)} ms`);
|
||||
assert.ok(perQuery < 60, `one search took ${perQuery.toFixed(1)} ms`);
|
||||
});
|
||||
|
||||
test("every Chinese alias points at a place that is in the bundled table", () => {
|
||||
assert.ok(worldCityAliases.length >= 150 && worldCityAliases.length <= 220, String(worldCityAliases.length));
|
||||
const files = new Set(readdirSync(new URL("../public/data/world-locations", import.meta.url)));
|
||||
const loaded = new Map<string, WorldCountryData>();
|
||||
const seen = new Set<string>();
|
||||
for (const alias of worldCityAliases) {
|
||||
assert.match(alias.zh, /^\p{Script=Han}+$/u, alias.zh);
|
||||
const file = `${alias.country.toLowerCase()}.json`;
|
||||
assert.ok(files.has(file), `${alias.zh}: no table for ${alias.country}`);
|
||||
if (!loaded.has(alias.country)) loaded.set(alias.country, country(alias.country.toLowerCase()));
|
||||
const region = loaded.get(alias.country)!.regions.find((item) => item.code === alias.regionCode);
|
||||
assert.ok(region, `${alias.zh}: region ${alias.regionCode} is missing`);
|
||||
const city = region.cities.find((item) => item.code === alias.cityCode);
|
||||
assert.ok(city, `${alias.zh}: city ${alias.cityCode} is missing from ${region.name}`);
|
||||
assert.ok(Number.isFinite(city.latitude) && Number.isFinite(city.longitude), alias.zh);
|
||||
const key = `${alias.country}/${alias.zh}`;
|
||||
assert.ok(!seen.has(key), `${key} is listed twice`);
|
||||
seen.add(key);
|
||||
assert.ok(worldCountries.some((item) => item.code === alias.country), alias.country);
|
||||
}
|
||||
});
|
||||
|
||||
test("Chinese input finds the alias and shows it as a gloss; anything else is not found", () => {
|
||||
const index = buildPlaceIndex(gb, worldCityAliases);
|
||||
const london = searchPlaces(index, "伦敦");
|
||||
assert.equal(london.hits.length, 1);
|
||||
assert.equal(london.hits[0].cityName, "London");
|
||||
assert.equal(placeEntryTitle(london.hits[0]), "London(伦敦)");
|
||||
// The alias only helps the search: the row is the bundled London entry itself.
|
||||
const bundled = gb.regions.flatMap((region) => region.cities.map((city) => ({ region, city })))
|
||||
.find((item) => item.city.code === london.hits[0].cityCode);
|
||||
assert.equal(bundled?.city.name, "London");
|
||||
assert.equal(bundled?.region.code, london.hits[0].regionCode);
|
||||
|
||||
const unknown = searchPlaces(index, "金斯林");
|
||||
assert.deepEqual(unknown.hits, []);
|
||||
assert.equal(unknown.searched, true);
|
||||
assert.match(PLACE_SEARCH_NOT_FOUND, /^没有找到这个地方。可以选离它最近的城市,星盘差别很小。地名可以试试输英文。$/);
|
||||
});
|
||||
|
||||
test("the country list filters by its Chinese or English name", () => {
|
||||
const options = [
|
||||
{ code: "CN", label: "中国", english: "China" },
|
||||
{ code: "GB", label: "英国", english: "United Kingdom" },
|
||||
{ code: "VG", label: "英属维尔京群岛", english: "Virgin Islands (British)" },
|
||||
{ code: "JP", label: "日本", english: "Japan" },
|
||||
{ code: "US", label: "美国", english: "United States" },
|
||||
];
|
||||
assert.deepEqual(filterCountryOptions(options, "英").map((item) => item.code), ["GB", "VG"]);
|
||||
assert.deepEqual(filterCountryOptions(options, "jap").map((item) => item.code), ["JP"]);
|
||||
assert.deepEqual(filterCountryOptions(options, "united").map((item) => item.code), ["GB", "US"]);
|
||||
assert.equal(filterCountryOptions(options, "").length, options.length);
|
||||
// Pinyin is not searched (out of scope for BUG-2049).
|
||||
assert.deepEqual(filterCountryOptions(options, "yingguo"), []);
|
||||
});
|
||||
|
||||
test("the chosen place reads City, Region", () => {
|
||||
assert.equal(chosenPlaceText("Norfolk", "Dersingham"), "Dersingham, Norfolk");
|
||||
assert.equal(chosenPlaceText("Singapore", ""), "Singapore");
|
||||
});
|
||||
|
||||
// ── the picker itself ───────────────────────────────────────────────────────
|
||||
|
||||
type Host = ReturnType<typeof createClientLifecycleHarness>;
|
||||
|
||||
async function mountPicker(initial: { countryCode: string; provinceCode?: string; cityCode?: string }) {
|
||||
const harness: Host = createClientLifecycleHarness();
|
||||
const selections: BirthPlaceSelection[] = [];
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
const table = /world-locations\/([a-z]{2})\.json/.exec(url);
|
||||
if (table) return new Response(read(`../public/data/world-locations/${table[1]}.json`), { status: 200 });
|
||||
return new Response(JSON.stringify({ timezoneId: "Europe/London", timezoneOffset: 1 }), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
await harness.render(
|
||||
<BirthPlacePicker
|
||||
value={{
|
||||
countryCode: initial.countryCode,
|
||||
provinceCode: initial.provinceCode ?? "",
|
||||
cityCode: initial.cityCode ?? "",
|
||||
districtCode: "",
|
||||
timezoneId: "",
|
||||
timezoneOffset: null,
|
||||
}}
|
||||
birthDate="1961-07-01"
|
||||
birthTime="19:45"
|
||||
onChange={(selection) => { selections.push(selection); }}
|
||||
/>,
|
||||
);
|
||||
await harness.idle();
|
||||
const all = () => harness.elements();
|
||||
const byLabel = (label: string) => all().find((node) => node.getAttribute("aria-label") === label && node.tagName === "INPUT");
|
||||
const options = () => all().filter((node) => node.getAttribute("role") === "option");
|
||||
const buttonWith = (text: string) => all().find((node) => node.tagName === "BUTTON" && node.text === text);
|
||||
return {
|
||||
harness,
|
||||
selections,
|
||||
all,
|
||||
byLabel,
|
||||
options,
|
||||
buttonWith,
|
||||
text: () => all().filter((node) => (node.getAttribute("class") ?? "").includes("birth-place-picker")).map((node) => node.text).join(""),
|
||||
async type(label: string, value: string) {
|
||||
const input = byLabel(label);
|
||||
assert.ok(input, `${label} is rendered`);
|
||||
await harness.event(input, "onChange", { target: Object.assign(input, { value }) });
|
||||
await harness.idle();
|
||||
},
|
||||
async key(label: string, key: string) {
|
||||
const input = byLabel(label);
|
||||
assert.ok(input, `${label} is rendered`);
|
||||
let stopped = false;
|
||||
await harness.event(input, "onKeyDown", { key, stopPropagation() { stopped = true; } });
|
||||
await harness.idle();
|
||||
return stopped;
|
||||
},
|
||||
async click(node: ReturnType<typeof buttonWith>) {
|
||||
assert.ok(node);
|
||||
await harness.event(node);
|
||||
await harness.idle();
|
||||
},
|
||||
async selectLevel(levelLabel: string, code: string) {
|
||||
const nodes = all();
|
||||
const trigger = nodes.findIndex((node) => node.getAttribute("aria-label") === levelLabel);
|
||||
assert.notEqual(trigger, -1, `${levelLabel} is rendered`);
|
||||
const input = nodes.slice(trigger).find((node) => node.tagName === "INPUT");
|
||||
assert.ok(input);
|
||||
await harness.event(input, "onChange", { target: Object.assign(input, { value: code }) });
|
||||
await harness.idle();
|
||||
},
|
||||
async close() {
|
||||
try { await harness.close(); } finally { globalThis.fetch = originalFetch; }
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("choosing Dersingham by search reports exactly what the two selects report", async () => {
|
||||
const norfolk = gb.regions.find((region) => region.name === "Norfolk")!;
|
||||
const dersingham = norfolk.cities.find((city) => city.name === "Dersingham")!;
|
||||
|
||||
const bySearch = await mountPicker({ countryCode: "GB" });
|
||||
let searched: BirthPlaceSelection | undefined;
|
||||
try {
|
||||
const input = bySearch.byLabel("出生海外地点");
|
||||
assert.ok(input, "the search box is the first thing shown for an overseas country");
|
||||
assert.equal(input.getAttribute("placeholder"), PLACE_SEARCH_PLACEHOLDER);
|
||||
assert.equal(bySearch.all().some((node) => node.getAttribute("aria-label") === "出生州省或地区"), false);
|
||||
|
||||
await bySearch.type("出生海外地点", "ders");
|
||||
const rows = bySearch.options();
|
||||
assert.ok(rows.length > 0 && rows.length <= 20);
|
||||
assert.match(rows[0].text, /^DersinghamNorfolk$/);
|
||||
await bySearch.click(rows[0]);
|
||||
assert.equal(bySearch.selections.length, 1);
|
||||
searched = bySearch.selections[0];
|
||||
// The field now rests on the choice, with a way to change it, and the usual confirmation line.
|
||||
assert.equal((bySearch.byLabel("出生海外地点") as unknown as { props: { value: string } }).props.value, "Dersingham, Norfolk");
|
||||
assert.ok(bySearch.buttonWith(PLACE_SEARCH_CHANGE));
|
||||
assert.match(bySearch.text(), /英国 Norfolk Dersingham/);
|
||||
assert.equal(bySearch.text().includes("·"), false, "no interpunct is displayed");
|
||||
} finally {
|
||||
await bySearch.close();
|
||||
}
|
||||
|
||||
const byLevels = await mountPicker({ countryCode: "GB" });
|
||||
try {
|
||||
await byLevels.click(byLevels.buttonWith(PLACE_SEARCH_BY_LEVELS));
|
||||
assert.ok(byLevels.buttonWith(PLACE_SEARCH_BACK));
|
||||
assert.equal(byLevels.byLabel("出生海外地点"), undefined);
|
||||
await byLevels.selectLevel("出生州省或地区", norfolk.code);
|
||||
await byLevels.selectLevel("出生海外城市", dersingham.code);
|
||||
assert.equal(byLevels.selections.length, 1);
|
||||
assert.deepEqual(byLevels.selections[0], searched);
|
||||
} finally {
|
||||
await byLevels.close();
|
||||
}
|
||||
|
||||
assert.deepEqual(searched, {
|
||||
countryCode: "GB",
|
||||
provinceCode: norfolk.code,
|
||||
cityCode: dersingham.code,
|
||||
districtCode: "",
|
||||
label: "英国 · Norfolk · Dersingham",
|
||||
placeType: "city",
|
||||
provider: "world_location_table",
|
||||
providerPlaceId: `world:GB:${norfolk.code}:${dersingham.code}`,
|
||||
latitude: dersingham.latitude,
|
||||
longitude: dersingham.longitude,
|
||||
timezoneId: "Europe/London",
|
||||
timezoneOffset: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test("arrow keys and Enter choose a row; Escape closes the list without leaving the dialog", async () => {
|
||||
const picker = await mountPicker({ countryCode: "GB" });
|
||||
try {
|
||||
await picker.type("出生海外地点", "伦敦");
|
||||
assert.equal(picker.options().length, 1);
|
||||
assert.match(picker.options()[0].text, /^London(伦敦)/);
|
||||
|
||||
await picker.type("出生海外地点", "oxf");
|
||||
const before = picker.options();
|
||||
assert.ok(before.length >= 2);
|
||||
assert.equal(before[0].getAttribute("aria-selected"), "true");
|
||||
await picker.key("出生海外地点", "ArrowDown");
|
||||
const moved = picker.options();
|
||||
assert.equal(moved[0].getAttribute("aria-selected"), "false");
|
||||
assert.equal(moved[1].getAttribute("aria-selected"), "true");
|
||||
await picker.key("出生海外地点", "ArrowUp");
|
||||
assert.equal(picker.options()[0].getAttribute("aria-selected"), "true");
|
||||
|
||||
const stopped = await picker.key("出生海外地点", "Escape");
|
||||
assert.equal(stopped, true, "Escape is kept from the dialog while the list is open");
|
||||
assert.equal(picker.options().length, 0);
|
||||
assert.equal(picker.selections.length, 0);
|
||||
|
||||
await picker.type("出生海外地点", "oxf");
|
||||
const first = picker.options()[0].text;
|
||||
await picker.key("出生海外地点", "Enter");
|
||||
assert.equal(picker.selections.length, 1);
|
||||
assert.ok(first.startsWith(picker.selections[0].label.split(" · ").at(-1)!));
|
||||
} finally {
|
||||
await picker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a place that is not in the table says so, and the country field filters as it is typed in", async () => {
|
||||
const picker = await mountPicker({ countryCode: "GB" });
|
||||
try {
|
||||
await picker.type("出生海外地点", "金斯林");
|
||||
assert.equal(picker.options().length, 0);
|
||||
assert.ok(picker.text().includes(PLACE_SEARCH_NOT_FOUND));
|
||||
|
||||
await picker.type("出生国家或地区", "日");
|
||||
const countries = picker.options().map((node) => node.text);
|
||||
assert.ok(countries.some((text) => text.startsWith("日本")));
|
||||
assert.ok(countries.every((text) => text.includes("日")));
|
||||
await picker.type("出生国家或地区", "jap");
|
||||
assert.deepEqual(picker.options().map((node) => node.text), ["日本Japan"]);
|
||||
} finally {
|
||||
await picker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("China keeps its three selects and never shows the search box", async () => {
|
||||
const picker = await mountPicker({ countryCode: "CN" });
|
||||
try {
|
||||
assert.equal(picker.byLabel("出生海外地点"), undefined);
|
||||
assert.ok(picker.all().some((node) => node.getAttribute("aria-label") === "出生省份"));
|
||||
assert.equal(picker.buttonWith(PLACE_SEARCH_BY_LEVELS), undefined);
|
||||
} finally {
|
||||
await picker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("the search uses the existing select look and no side bar", () => {
|
||||
const css = read("../src/app/globals.css");
|
||||
const block = css.slice(css.indexOf("/* BUG-2049"), css.indexOf(".birth-place-note") > css.indexOf("/* BUG-2049") ? css.indexOf(".birth-place-note") : css.indexOf("/* BUG-2049") + 4000);
|
||||
assert.ok(block.includes(".location-search-panel"));
|
||||
assert.equal(/border-left|border-inline-start/.test(block), false);
|
||||
const box = read("../src/components/ui/location-search-box.tsx");
|
||||
assert.match(box, /className="select-item location-search-row"/);
|
||||
assert.match(box, /role="combobox"/);
|
||||
assert.match(box, /role="listbox"/);
|
||||
// Every form reaches the picker through these two places; none builds its own country select.
|
||||
assert.match(read("../src/components/birth-location-fields.tsx"), /<BirthPlacePicker/);
|
||||
assert.match(read("../src/components/annual/annual-report-page.tsx"), /<BirthPlacePicker/);
|
||||
});
|
||||
@@ -38,7 +38,12 @@ test("country data keeps the coordinates and IANA timezone needed for confirmati
|
||||
assert.equal(existsSync(new URL("src/data/WORLD_LOCATION_DATA.md", root)), true);
|
||||
});
|
||||
|
||||
test("overseas UI uses cascading data files and has no search input", () => {
|
||||
// 原值:标题「overseas UI uses cascading data files and has no search input」,断言国家用下拉
|
||||
// (aria-label 写在本文件里)、源码里没有 role="combobox"
|
||||
// 新值:海外地点先按名字搜索(搜索框在 ui/location-search-box.tsx,role="combobox"),
|
||||
// 国家一栏也能打字筛选;逐级选择保留为第二入口,两级下拉的 aria-label 不变
|
||||
// 原因:BUG-2049,产品负责人 2026-11-20:内测有海外出生的用户,英国 221 个地区在手机上要滚一万多像素
|
||||
test("overseas UI searches the bundled data files and keeps the level-by-level selects", () => {
|
||||
assert.match(pickerSource, /world-locations\/\$\{draft\.countryCode\.toLowerCase\(\)\}\.json/);
|
||||
// 原值「海外地点按国家、地区、城市逐级选择,不使用搜索。」→ 新值「选到城市就够了。」:逐级选择从界面上就看得出来(2026-11-06)
|
||||
assert.match(pickerSource, /选到城市就够了/);
|
||||
@@ -46,8 +51,10 @@ test("overseas UI uses cascading data files and has no search input", () => {
|
||||
assert.match(pickerSource, /new Intl.DisplayNames\(\["zh-Hans"\], \{ type: "region" \}\)/);
|
||||
assert.match(pickerSource, /zh-Hans-CN-u-co-pinyin/);
|
||||
assert.equal(new Intl.DisplayNames(["zh-Hans"], { type: "region" }).of("US"), "美国");
|
||||
assert.match(pickerSource, /aria-label="出生国家或地区"/);
|
||||
assert.match(pickerSource, /ariaLabel="出生国家或地区"/);
|
||||
assert.match(pickerSource, /ariaLabel="出生海外地点"/);
|
||||
assert.match(pickerSource, /aria-label="出生州省或地区"/);
|
||||
assert.match(pickerSource, /aria-label="出生海外城市"/);
|
||||
assert.doesNotMatch(pickerSource, /role="combobox"/);
|
||||
// The search never leaves the browser: no geocoding call from the picker.
|
||||
assert.doesNotMatch(pickerSource, /api\/locations\/search|geoapify/i);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user