Compare commits

..
Author SHA1 Message Date
Sameh KhamisandManjunath Paparaju d15c69a8ae Add the changelog entry for the place privacy fixes
Co-authored-by: Manjunath Paparaju <[email protected]>
2026-11-18 17:21:40 -08:00
Sameh KhamisandManjunath Paparaju 2a4079e9f8 Keep SSNs with "is", "Bearer:" values and codes in capitals private, and let West Point through
"ssn is 123456" and a masked "ssn: xxx-xx-1234", "Bearer: island", codes
in capitals after their label ("OTP ABCDEF", "PIN ABCD", any CVV), a
document number or ID right after its colon, "lockbox number 4821", a UK
National Insurance number in lower case and an IPv6 host in a link are
private. A recovery phrase starting with "find" or holding "please" (both
on its word list) is caught. "Point" is not read as a spelled dot, so
"meet at West Point tomorrow" is looked up, and Idaho's code follows a town
written in any case ("BOISE ID 83702", "Coeur d'Alene ID 83814").

Co-authored-by: Manjunath Paparaju <[email protected]>
2026-11-18 17:21:32 -08:00
Sameh KhamisandManjunath Paparaju 200c788ac1 Let Idaho, questions and long place names through, and keep more tokens and codes private
"Boise ID 83702" names Idaho rather than an identity number. A long question
for the assistant is no recovery phrase: a phrase holds none of the common
words its list lacks ("the", "and", "are"). A long lower-case place name
is no passphrase, an address of up to ten words is sent as the Omnibar reads
it, and "mfa boston", "otp bank" and "security code plaza" are names.

"Authorization: Bearer" and any value after "bearer" but a place word are
tokens, and so are GitLab, Hugging Face and SendGrid keys and a code in a
link. Door, alarm and lockbox numbers (not a zip or area code), a spaced UK
National Insurance number, "my id is …", and emails spelled with "punto",
"period", a spaced dot or letter by letter are private too.

Co-authored-by: Manjunath Paparaju <[email protected]>
2026-11-18 17:13:12 -08:00
Sameh KhamisandManjunath Paparaju 35049fd7f7 Keep more shapes of phones, codes, tokens, emails and IP addresses private
Review found "Alice 555-0100" sent as a Japanese postcode, recovery phrases
with a repeated word, a capitalised bearer token, codes after a lower-case
label in other cases ("verification code Abc", "PIN aBcD"), "john at
gmail.com" and "(dot)" forms, passport numbers of digits only, "ID AB123"
and IPv6 addresses. They now stay in the browser, and the suggester never
sends a line of more than eight words. "Bearer Island, Canada", "bearer
island", a ZIP+4 after two spaces and a Japanese postcode after Japanese
script are looked up again.

Co-authored-by: Manjunath Paparaju <[email protected]>
2026-11-18 16:59:35 -08:00
Sameh KhamisandManjunath Paparaju 8885177e2e Keep spelled-out emails, IP addresses, recovery phrases and lower-case codes from the place service
Place suggestions still sent "john(at)gmail.com", "10.0.0.1", a wallet's
recovery phrase, a passphrase run together, "license ABC1234", lower-case
codes after a code label ("otp abcdef", "cvv abc") and short phone numbers
read as an address ("Jo 12345-6789", "Mo 0171 12345"), and a phone's three
and four digits could still be searched as a place on purpose. They now stay
in the browser. Real places that only looked private are looked up again:
Akiak, Bearer Island, SSN Station, Shibuya 150-0002. A suggested house is
named in its country's order ("Hauptstraße 12"), and one without a street
keeps its number.

Co-authored-by: Manjunath Paparaju <[email protected]>
2026-11-18 16:50:46 -08:00
39 changed files with 628 additions and 1065 deletions

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
- Space Missions finishes switching off before anything else runs: a launch
hovered while the layer is going off shows no preview, and Satellites
keeps the state it was saved with when it is still busy. A click on a
mission label reaches every layer so each can let go of what it had
selected, and none of them selects, turns on, flies to or opens the link
of what lies under the label (manjunath22466, samehkhamis, #1829).
+7
View File
@@ -0,0 +1,7 @@
- More private text typed into the Omnibar or Location search stays off the
place service: emails spelled out or spaced, IP addresses, wallet recovery
phrases, door, alarm and lockbox numbers, codes after their labels,
document and ID numbers, SSNs, more API token shapes and codes in links.
More real places get through: "Boise ID 83702", house numbers in the
order their country writes them, addresses of up to ten words, and long
questions for Ask GEV (manjunath22466, samehkhamis, #1830).
+61 -22
View File
@@ -5592,11 +5592,7 @@ activeCameraCardEnabled: true })` may publish it through the retained
> switching Space Missions off restores the pre-mission Satellite enabled
> state and presentation parameters, except that an explicit Satellites action
> taken while it ran is kept. Restored parameters never re-show primitives
> while the Satellite layer is disabled. When Satellites is still busy after
> the 30 s limit, the restore changes nothing and keeps the saved state, so
> switching Space Missions off again finishes it. While Space Missions goes
> off, its panel's roster and controls select, focus, preview and replay
> nothing, so no camera move starts that nothing would end.
> while the Satellite layer is disabled.
> - **Flights 3D/cockpit hardening:** the destination-direction cue is an
> inline SVG rather than a remotely loaded Material Icons ligature, so a
> blocked or late font can no longer expand the literal word `navigation`
@@ -7495,7 +7491,7 @@ silently demoting every later lookup for the session.
protected-card path. Disable tears the tier down completely.
Coverage/viewshed semantics unchanged.
- **Satellites**: every point moves every frame. Each satellite's SGP4 sample (position, velocity, gravity and its rate of change; `src/layers/satellites/motion.js`) is reckoned forward or back to the world time and turned into the Earth-fixed frame, so points glide at any play speed instead of stepping once a second. Core satellites take a fresh sample every second, or as soon as the world time is 30 s from their sample (fast play, a seek), which keeps every point within about 10 m of SGP4; Starlink extras are sampled round-robin, more per frame the faster time plays, and a point more than two minutes from its sample waits for the next one. Hidden points are not moved until shown. Orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. Pass prediction (`src/data/satellitePass.js`; `getNextSatellitePass`, `getNextIssPass`) scans at 20s, bisects rise/set to ~0.2s, fits the peak with a parabola, and marks a pass visible when the satellite is outside a cylindrical Earth shadow while the observer's Sun is at or below −6°. `next_iss_pass` preserves its geometric-pass ordering and appends visibility metadata. General `next_satellite_pass` accepts a loaded NORAD ID or unambiguous name, searches 24 hours and optionally requires estimated visibility. These estimates do not account for weather or satellite brightness.
- **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer reveals its own right-rail button and roster and enables the required satellite layer; it does not touch Context. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from Data Layers hides its rail button and panel and restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. An explicit user or voice Satellites OFF requested after Space Missions ON exits Space Missions, including after returning from Stories; scene, story, preset and other programmatic Satellites changes do not. The controls under the Space Missions row cycle through available launches. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills the Space Missions panel with details, navigation, and replay controls, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable. Clicking the launch name on the globe selects and focuses the same mission as its dot; what is drawn beneath the name is not picked, and the other layers still hear the click as one on the name, so they close their cards or let go of their selection as for any other click, but never select, turn on, focus or open the link of a contact, card or camera that lies under the name. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, whichLine truncated
- **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer reveals its own right-rail button and roster and enables the required satellite layer; it does not touch Context. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from Data Layers hides its rail button and panel and restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. An explicit user or voice Satellites OFF requested after Space Missions ON exits Space Missions, including after returning from Stories; scene, story, preset and other programmatic Satellites changes do not. The controls under the Space Missions row cycle through available launches. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills the Space Missions panel with details, navigation, and replay controls, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable. Clicking the launch name on the globe selects and focuses the same mission as its dot. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, which skips the year check rather than rejecting the match. Speed is the magnitude of the SGP4 inertial velocity vector at the same propagation epoch as position, displayed in km/s with km/h available as hover detail. Unavailable operator, site, launch-time, orbit, current-altitude, and speed valLine truncated
When no mission is selected, the Space Missions panel presents a scrollable newest-first roster of every launch in the rolling window, including the smaller 5 px operator-colored marker, provider, and launch date. Hovering or keyboard-focusing a row shows four compact cyan corner brackets on both that roster row and its corresponding globe dot, rotates the globe at the current zoom to center it, and gives its label declutter priority without selecting it; the globe label remains unbracketed. Selecting a roster row invokes the same mission isolation and full-orbit framing as clicking its globe marker. The replay vehicle is one screen-space SVG/CSS HUD overlay rather than separate Cesium billboard, label, and reticle graphics. It is hidden during ordinary Focus and manual close views, where the standard selected launch-site label remains visible, and exists only while ascent replay is active. Its fixed pixel scale is shared by ascent and insertion, so camera range never resizes the rocket on screen before the phase boundary. Generic Launch Library pad names are reduced to their identifying suffix, and replay timestamps use a cyan state title over unprefixed white UTC date/time values. `REPLAY ASCENT` holds the unframed cyan/white rocket at the pad for a real-time `T−10` countdown, transitions through `LIFTOFF`, and attaches six tapered cyan/white ellipse waves directly below it from liftoff through insertion to convey thrust without adding scene geometry. While replay is active, the single start button is replaced by compact Play, Pause, and Cancel icon controls. Pause freezes countdown or mission time, vehicle/stage positions, camera target, labels, and thrust-wave animation; Play resumes from that exact frame, and Cancel releases replay camera ownership. The rocket and thrust group rotates from the path's live screen-space tangent, so its nose follows the visible ascent curve while the adjacent text remains upright. The camera begins as a close oblique launch chase, then smoothly widens between roughly 120 and 420 km vehicle altitude into a higher oblique context view that keeps the moving rocket targeted while exposing the ascent bend and orbit connection. At insertion the rocket/thrust glyph is replaced by the fixed-size cyan orbit dot, which the camera follows through the existing globe-scale orbit pullback. The chase camera limits per-frame yaw changes across heading wraps so it cannot abruptly cross in front of the vehicle and make ascent read in reverse; the replay-speed slider affects mission playback but not countdown duration.
Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources.
A selected mission renders its orbit as four repeating tactical sectors, each containing one prominent cyan dot followed by one hundred thin translucent dashes. The bright dots act as orbit anchors while the subdued dash field remains depth-tested against the globe and is shown only for the selected mission.
@@ -8030,10 +8026,13 @@ while the tab is hidden.
A place search on its own runs through Location and shares its cancellation
and errors, keeping the separate Location draft intact.
While typing, a short line (six words or fewer, no `?`, not a command,
While typing, a short line (six words or fewer, ten with a number in it
as an address has, no `?`, not a command,
coordinates, a hex code, a callsign such as UAL2110 or N123AB, and nothing
that may be private) is sent to
Photon for place suggestions: at most one request every 500 ms per tab,
Photon for place suggestions (the suggester itself never sends a line of
more than eight words, or ten with a number): at most one request every
500 ms per tab,
and none for a minute after a refusal. Photon is the keyless geocoder the
place search already uses; a submitted search is not part of this spacing.
A line that may be one name ("Satellite Beach") is looked up whole. While
@@ -8047,49 +8046,89 @@ digits and "@" count, and digits of any script count as digits. It is
any line with: an "@" with something right on both sides, ending a word,
starting a lowercase handle ("@jdoe"), or spaced before a domain ("john @
gmail.com") (an email address or a handle, also while it is typed; spaced, as in "Nanjampeta @
Chandambylu", it is part of a name); seven digits or more with nothing but spaces,
Chandambylu", it is part of a name); an email spelled around a filter
("john(at)gmail.com", "john[at]gmail[dot]com", "john at gmail dot de",
"john at gmail.com", "john at gmail (dot) com"); an IP address
("10.0.0.1", "::1", "fe80::1", "https://[::1]/"); a wallet's recovery
phrase (see below); seven digits or more with nothing but spaces,
punctuation, symbols or format characters between them (a phone, card,
SSN or account number or its start: "+1 415 555", "4111 1111", "123 45
6789", "123456789", "4111.1111.1111.1111", "123–45–6789"; a street address's house number
and its postcode are read apart: five digits, or between the street and
and its postcode are read apart (a house number never starts with 0, and
a polite word such as "thanks" after the digits is not a city): five digits, or between the street and
the city "00-950", "111 21", "125009", "1100-053", or four digits after a
comma ("Straße 120, 1070 Wien"); and so are a US ZIP+4 after a word,
a Brazilian CEP, a Japanese postcode after "〒" or before the address, and
comma ("Straße 120, 1070 Wien"); and so are a US ZIP+4 after a state's
code or name ("Alice 12345-6789" and "Jo 12345-6789" stay private),
a Brazilian CEP, a Japanese postcode after "〒" or next to the address in
Japanese script ("東京都千代田区100-0001"; after a Latin name, as in
"Shibuya 150-0002", it reads as a phone number), and
digits on either side of "#", so "Hauptstrasse 12 10115 Berlin", "DC
20500-0003", "〒100-0001 東京都千代田区" and "Calle 100 # 19-61" are places,
while a seven-digit postcode alone such as "Tel Aviv 6100000" still reads
as private); a phone number written with dots; two letters, two
digits and ten more letters or digits (an IBAN's shape); "password",
"passcode", "passwd", "ssn", "pw", "pwd" or "bearer" followed by anything,
"token", "secret", "api key", "key" or "pass" followed by ":" or "=", a
"passcode", "passwd", "pw" or "pwd" followed by anything, "bearer"
followed by anything but a short capitalised name or a place word such as
island or lake ("Bearer Island", "bearer island" are places),
"ssn" followed by a digit ("SSN Station" is a place), "token", "secret",
"api key", "key" or "pass" followed by ":" or "=", a licence, plate,
passport, membership, account, policy, ticket, booking, confirmation or
reference number with a digit after its label ("license ABC1234",
"passport no. 123456"), "ID" in capitals followed by a number ("ID
AB123"), "otp", "2fa", "mfa", "cvv", "cvc" or a verification, one-time,
security, auth or login code followed by a code (any value after a label
in lower case, "verification code Abc", also before "thanks"; after a label
written as a name, any value that is not one: "OTP Bank" and "Security
Code Plaza" are places), a "pin" or door, access, gate, alarm or entry
code followed by a value in mixed case ("PIN aBcD"), a
door, access, gate, alarm, entry or security code followed by a digit, "api
key", "access token" or "secret key" followed by a word of six characters
or more, the word for "password" in the interface's languages
(contraseña, Passwort, mot de passe, пароль…) followed by anything, or "pin"
(also "pin code", "pin number", "pin is") followed by a digit; a word
starting `sk_`, `sk-`, `rk_`, `pk_live`, `ghp_` or a Slack token's `xoxb-` and the like (any case) or
`AIza`, `eyJ` or `AKIA`; or a word that may be a password or key, with letters and digits mixed
starting `sk_`, `sk-`, `rk_`, `pk_live`, `ghp_`, `github_pat_`, `glpat-`, `hf_`, a SendGrid
`SG.` key or a Slack token's `xoxb-` and the like (any case) or
`AIza` or `eyJ`, or an AWS key id (`AKIA` and twelve capitals or digits
more; "Akiak" is a place); or a word that may be a password or key, with letters and digits mixed
within one run (a number beside a word, as in "Yanino-1", "2-chōme" or
"Route-66", is a name): eight characters or more, six or more with four
letters and a digit ("hunter22", "Area51"), or six or more with letters,
digits and a symbol ("Tr0ub4dor&3"). The password words match whole words
only ("Sachsenhausen" is a place). Over the bundled names (139,502), five
read as private: two with stray digits ("Maliga0N", "Jerónim67") and three
with number lists or codes. When the text may be private the field says
only ("Sachsenhausen" is a place). Over the bundled names (139,502), six
read as private: two with stray digits ("Maliga0N", "Jerónim67"), two
joined by "@" to a lower-case handle ("Pulipadu @Govardhanagiri") and two
with number lists or dates. When the text may be private the field says
so ("Looks private, so nothing is searched or sent"), and a line whose
only private sign is an address-sized run of digits (no group over six
digits, nine at most in all, counted as they fold, and no word such as
digits, nine at most in all, counted as they fold, no three digits
followed by four as a phone number writes them, and no word such as
card, code, key, phone or account beside them, in English and some other
European languages; compounds such as "Kreditkartennummer" and words in
other scripts are not read), with words beside it, gets a row
to search it as a place on purpose ("Search … as a place anyway"), which
runs the ordinary place search and its online services only when picked; a
bare number, an email or handle, a password, key, code or IBAN gets none.
A suggested house is named by its number and its street (or, without a
street, its locality, district or city) in the order its country writes them: "10 Downing
Street", "Hauptstraße 12".
A nine-digit number or a short phone number written with no such word
still gets the row: only picking it sends anything. One-time and verification codes,
OTP, 2FA, MFA, CVV and CVC values, "card ending" digits, passphrases,
recovery or seed phrases, "my secret is …" and an email spelled out ("john
at example dot com") are private too. Text that parses as coordinates or a
recovery or seed phrases (twelve to twenty-four short words with none of
the common words a phrase list lacks, such as "the", "and" or "are", so a
long question still goes to Ask GEV), "my secret is …", an email spelled
out ("john at example dot com", "punto com", or letter by letter), a door,
alarm or lockbox number ("code 4821"; "zip code 90210" and "area code 415"
are places), "Authorization: Bearer …", a code in a link (`?code=…`), a
spaced UK National Insurance number and "my id is …" are private too.
"Boise ID 83702" names Idaho. Some private text is not caught: a
passphrase run together as one word (a long place name is one word too),
a lower-case word after "otp", "2fa" or "mfa" ("mfa boston" is a name;
"otp ABCDEF" is caught) and a code of lower-case letters after "pin" or
"gate code" ("PIN ABCD" is caught).
A Japanese postcode after a Latin name is refused ("Shibuya 150-0002"), and
so is a name in capitals after a code's label ("MFA BOSTON", which cannot
be told from "OTP ABCDEF"). Text that parses as coordinates or a
grid reference is not private. A place's name is six words at most, or ten
when it has a number in it (an address: "1600 Pennsylvania Ave NW
Washington DC 20500"). The places picked from the Omnibar's rows and chips that carry a position
+1 -4
View File
@@ -660,7 +660,6 @@
"src/layers/alpr/model.js",
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
"src/layers/alpr/presentation.test.mjs",
"src/layers/alpr/visuals.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/overlay.test.mjs",
@@ -1600,7 +1599,5 @@
"src/ui/omnibarRows.test.mjs",
"src/ui/styles/omnibar-dock.css",
"src/ui/styles/guide.css",
"src/ui/commandDock.test.mjs",
"src/layers/firms/selection.test.mjs",
"src/layers/vessels/selection.test.mjs"
"src/ui/commandDock.test.mjs"
]
+6 -39
View File
@@ -182,11 +182,6 @@ function topHitOf(hit, foreign) {
* when the adapter has none.
* @property {unknown} pick `native.pick`, for code still bound to the
* engine's pick objects that reads it here.
* @property {boolean} overlay Whether a painted overlay target took the
* click ({@link InputDispatcher.onOverlayClick}). Its hits then name only
* that target: something drawn outside the draw port, with no id. A
* subscriber with its own hit test (painted cards, a pick of its own)
* skips it then: what lies under the target is not clicked.
* @property {(width: number, height: number) => unknown} pickWindow
* `native.pickWindow`, the same.
*/
@@ -197,9 +192,7 @@ function topHitOf(hit, foreign) {
* Ambient click subscription. Returns its unsubscribe.
* @property {(fn: (event: ClickEvent) => boolean) => () => void} onOverlayClick
* Hit-test a painted overlay before ambient clicks. Return true after
* handling its topmost target: the geometry beneath it is not picked, and
* the click subscribers hear the click as one on that target (`overlay`
* true, `topHit` a hit with no set and no id, nothing drilled).
* handling its topmost target to stop delivery to the geometry beneath it.
* @property {(type: 'down'|'move'|'up'|'click'|'dblclick', fn: Function, options?: {lease?: object|(() => object|null)}) => () => void} onPointer
* Raw pointer subscription: `click` gets the {@link ClickEvent}, the others
* `{position}` (`move`: `{startPosition, endPosition, pickPosition}`, its
@@ -338,7 +331,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
click: (ev) => {
if (!unmodifiedLeft(ev)) return;
const ambient = free();
const { event, cover } = createClickEvent(
const event = createClickEvent(
viewer,
queryOf,
xy(ev.position),
@@ -347,12 +340,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
if (ambient) {
for (const handle of [...overlayClicks]) {
try {
// A handled overlay target hides the geometry beneath it; every
// subscriber still hears the click, as a click on that target.
if (handle(event) === true) {
cover();
break;
}
if (handle(event) === true) return;
} catch (error) {
console.error('Pointer input handler failed', error);
}
@@ -449,10 +437,6 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
return self;
}
/** What a click handled by a painted overlay target hits: that target,
* drawn outside the draw port and named by no pick id. */
const OVERLAY_HIT = Object.freeze({ set: '', id: null, surface: false });
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
const DRILL_DEPTH = 16;
@@ -462,8 +446,7 @@ const DRILL_DEPTH = 16;
* @param {() => import('../render/contract/query').QueryPort|null} queryOf
* @param {{x: number, y: number}} at Where the click is, CSS pixels.
* @param {ClickGesture} gesture
* @returns {{event: ClickEvent, cover: () => void}} The click, and how a
* handled overlay target hides the geometry beneath it from the click.
* @returns {ClickEvent}
*/
function createClickEvent(viewer, queryOf, at, gesture) {
const position = sensorPickPosition(viewer, at, canvasOf(viewer));
@@ -482,25 +465,11 @@ function createClickEvent(viewer, queryOf, at, gesture) {
};
/** @type {Map<string, {limit: number, hits: Hit[]}>} */
const drills = new Map();
let covered = false;
const cover = () => {
covered = true;
memo.clear();
drills.clear();
memo.set('top', OVERLAY_HIT);
memo.set('hit', OVERLAY_HIT);
memo.set('id', null);
memo.set('ownerId', null);
memo.set('native', null);
};
const event = {
return {
screenPosition: at,
position,
gesture,
get overlay() {
return covered;
},
get topHit() {
return once('top', () => {
const hit = pick();
@@ -546,7 +515,6 @@ function createClickEvent(viewer, queryOf, at, gesture) {
return !this.hit;
},
windowHit(width, height) {
if (covered) return { id: null, drawHit: null, surface: false };
return once(`windowHit:${width}x${height}`, () => {
const picked = pick({ width, height });
void native()?.native.pickWindow(width, height);
@@ -567,7 +535,7 @@ function createClickEvent(viewer, queryOf, at, gesture) {
// A deeper pass already made holds these. (One that came back short
// may not hold every hit: it drops what is not a draw-set item.)
if (done && limit <= done.limit) return done.hits.slice(0, limit);
const q = covered ? null : query();
const q = query();
if (!q) return [];
// Only the default window is shared between layers; round that one up.
const depth =
@@ -600,5 +568,4 @@ function createClickEvent(viewer, queryOf, at, gesture) {
return native()?.native.pickWindow(width, height);
},
};
return { event, cover };
}
+1 -61
View File
@@ -145,8 +145,7 @@ test('a painted overlay can claim a click before its underlying owner', (t) => {
h.input.onPointer('click', () => clicks.push('ambient pointer'));
h.click();
// The click still reaches every subscriber, as one on the label.
assert.deepEqual(clicks, ['mission label', 'ambient pointer', null]);
assert.deepEqual(clicks, ['mission label']);
assert.equal(h.calls.pick, 0);
h.click(11, 10);
@@ -155,71 +154,12 @@ test('a painted overlay can claim a click before its underlying owner', (t) => {
assert.deepEqual(clicks, [
'mission label',
'ambient pointer',
null,
'ambient pointer',
'satellites',
'ambient pointer',
'satellites',
]);
});
test('a click a painted overlay handles still reaches subscribers that clear selection', (t) => {
const h = harness({
pick: () => ({ set: 'flights', id: 'abc123' }),
drillPick: () => [{ set: 'flights', id: 'abc123' }],
});
t.after(() => h.input.destroy());
let seenByOverlay = null;
h.input.onOverlayClick((event) => {
seenByOverlay = event;
return true;
});
const seen = [];
h.input.onClick((event) => {
seen.push({
same: event === seenByOverlay,
overlay: event.overlay,
topHit: event.topHit,
drawHit: event.drawHit,
hit: event.hit,
id: event.id,
ownerId: event.ownerId,
surface: event.surface,
drill: event.drill(4),
windowHit: event.windowHit(8, 8),
pick: event.pick,
});
});
h.click();
assert.deepEqual(seen, [
{
same: true,
overlay: true,
topHit: { set: '', id: null, surface: false },
drawHit: null,
hit: { set: '', id: null, surface: false },
id: null,
ownerId: null,
surface: false,
drill: [],
windowHit: { id: null, drawHit: null, surface: false },
pick: undefined,
},
]);
assert.equal(h.calls.pick, 0, 'the geometry beneath is not picked');
assert.equal(h.calls.drillPick, 0);
// Without an overlay target the same click picks the geometry.
seen.length = 0;
h.input.destroy();
const g = harness({ pick: () => ({ set: 'flights', id: 'abc123' }) });
t.after(() => g.input.destroy());
g.input.onClick((event) => seen.push([event.overlay, event.topHit]));
g.click();
assert.equal(seen[0][0], false);
assert.equal(g.calls.pick, 1);
});
test('the gesture carries summed travel and press time', (t) => {
const h = harness();
t.after(() => h.input.destroy());
-15
View File
@@ -140,18 +140,3 @@ export function fakeInput(viewer, { now } = {}) {
destroy: () => input.destroy(),
};
}
/**
* `fakeInput` with a label painted over the map, as a Space Missions label
* is: while `label.over` is true the label takes each click, so every click
* subscriber hears it as an overlay click (`event.overlay`), and the
* geometry beneath it is not picked.
* @param {object} viewer
* @param {{now?: () => number}} [options]
*/
export function fakeInputUnderLabel(viewer, options) {
const fake = fakeInput(viewer, options);
const label = { over: false };
fake.input.onOverlayClick(() => label.over);
return { ...fake, label };
}
+1 -2
View File
@@ -582,10 +582,9 @@ export function createAlprPresentation({ state, services, source }) {
state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return;
// The painted overlay answers first; the scene is picked only if not.
// A click a label painted over both took is on neither.
const hit = event.drawHit;
const id =
(!event.overlay && overlay.pick(event.screenPosition)) ||
overlay.pick(event.screenPosition) ||
(hit && hit.set === markers.icons?.id ? hit.id : null);
if (
id &&
-122
View File
@@ -1,122 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { createAlprMarkerSet } from './markerState.js';
import { createAlprPresentation } from './presentation.js';
/** One camera drawn and painted at (100, 100), over a viewer whose clicks a
* label may take. */
function harness(t) {
const previousImage = globalThis.Image;
const project = Cesium.SceneTransforms.worldToWindowCoordinates;
globalThis.Image = class {
complete = true;
naturalWidth = 128;
};
Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 100, y: 100 });
const record = {
id: 'camera:0',
latitude: 30,
longitude: -97,
directionDeg: 90,
};
const drawPort = fakeDrawPort();
const markers = createAlprMarkerSet();
markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
const viewer = {
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500),
pickEllipsoid: () => Cesium.Cartesian3.fromDegrees(-97, 30),
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
globe: { show: true, getHeight: () => 150 },
pick: () => null,
},
};
const { unbind } = bindFakeCesiumScene(viewer, { draw: drawPort });
const fake = fakeInputUnderLabel(viewer);
const state = {
viewer,
enabled: true,
selectedId: null,
markers,
records: [record],
recordById: new Map([[record.id, record]]),
renderRevision: 0,
lastAnchorSampleAt: 0,
};
let selected = null;
let paint;
const presentation = createAlprPresentation({
state,
source: { label: 'Test cameras' },
services: {
render: { governorRequestRender() {} },
context: {
clearSelectedEntityContextForLayer() {
selected = null;
},
getSelectedEntityContext: () => selected,
registerEntityContext() {},
removeEntityContextsForLayer() {},
selectEntityContext(carrier) {
selected = { id: carrier.id, layerId: 'alpr-cameras' };
},
},
groundFloor: { cachedGroundFloor: () => 150 },
overlays: {
registerPaintLane(_lane, painter) {
paint = painter;
return { setActive() {}, requestPaint() {}, unregister() {} };
},
keyholeAlpha: () => 1,
},
},
});
presentation.initOverlay();
presentation.installInteraction(viewer);
t.after(() => {
presentation.destroyOverlay();
fake.destroy();
unbind();
if (previousImage === undefined) delete globalThis.Image;
else globalThis.Image = previousImage;
Cesium.SceneTransforms.worldToWindowCoordinates = project;
});
presentation.renderRecords();
const ctx = {
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
moveTo() {},
lineTo() {},
closePath() {},
stroke() {},
fill() {},
createLinearGradient: () => ({ addColorStop() {} }),
drawImage() {},
};
paint({ ctx, width: 800, height: 600 });
return { state, fake, at: { x: 100, y: 100 } };
}
test('a click a label painted over a camera takes never selects it, and lets go of the selected camera', (t) => {
const h = harness(t);
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, null, 'the camera under the label');
// Off the label, the same click selects the camera.
h.fake.label.over = false;
h.fake.click(h.at);
assert.equal(h.state.selectedId, 'camera:0');
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, null, 'the selection is let go');
});
+6 -9
View File
@@ -411,15 +411,12 @@ export function createLifecycle({
// painted ambient cards. The cards canvas is pointer-events:none (this
// handler owns the events), so a click landing on a card's rect selects
// its camera exactly like a click on the icon. Click positions
// and the recorded rects are both CSS px — direct comparison. A
// click a label painted over the cards took is not on a card.
const cardId = event.overlay
? null
: layerState._cctvOverlayHost.hitTest(
event.screenPosition.x,
event.screenPosition.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
event.screenPosition.x,
event.screenPosition.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
if (cardId && layerState._recordById.has(cardId)) {
activateCctvCameraFromWorldClick(
cardId,
-81
View File
@@ -3,9 +3,6 @@ import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
function viewerWithCamera() {
const camera = fakeCameraPort();
@@ -75,81 +72,3 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.deepEqual(counts(second.camera), [0, 0]);
assert.equal(state._viewListenerCamera, null);
});
/** A part whose members are `own`'s, and any other a function that does
* nothing. */
const inert = (own = {}) =>
new Proxy(own, {
get: (target, name) => (name in target ? target[name] : () => {}),
});
test("a click a label painted over a camera's card takes never turns that camera on, and lets go of the active one", async (t) => {
const { viewer } = viewerWithCamera();
viewer.scene = { canvas: {}, pick: () => null };
const fake = fakeInputUnderLabel(viewer);
t.after(() => fake.destroy());
const activated = [];
const deactivated = [];
const state = {};
const lifecycle = createLifecycle({
state,
services: {
activation: {
activateCctvCameraFromWorldClick: (id) => activated.push(id),
},
picking: { resolvePickId },
focus: {},
render: {},
},
parts: {
calibration: { loadCalibrationStore: () => new Map() },
catalog: {
loadCameraSources: async () => [],
buildCatalogFromSources: () => [],
seedCatalog: () => [],
},
ground: {
resolveGroundPriors: async () => [],
currentSurfaceRegime: () => null,
},
rendering: inert({ refreshHorizonCulling: () => false }),
health: { syncHealthState: async () => {} },
geometryQueue: inert(),
cards: inert(),
projection: inert(),
presentation: inert(),
navigation: inert(),
hover: inert(),
selection: {
// The camera's own gate takes only clean clicks; these are.
bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick),
extractPickedCameraId: () => null,
cctvEmptyClickDeselects: (picked, { activeCameraId }) =>
Boolean(activeCameraId) && resolvePickId(picked) === null,
deactivateActiveCamera: () => deactivated.push(state._activeCameraId),
},
},
});
// Init's bounded wait for ground heights never runs out here: they are in.
t.mock.timers.enable({ apis: ['setTimeout'] });
await lifecycle.methods.init(viewer);
t.after(() => state._clickSubscription?.());
state._enabled = true;
state._activeCameraId = 'cam-0';
state._recordById.set('cam-1', {});
// The card of camera `cam-1` lies under every click.
state._cctvOverlayHost = {
hitTest: (_x, _y, { sourceId }) =>
sourceId === CCTV_OVERLAY_SOURCE_ID ? { entryId: 'cam-1' } : null,
};
fake.label.over = true;
fake.click();
assert.deepEqual(activated, [], 'the camera under the label stays off');
assert.deepEqual(deactivated, ['cam-0'], 'the active camera is let go');
// Off the label, a click on the card turns its camera on.
fake.label.over = false;
fake.click();
assert.deepEqual(activated, ['cam-1']);
});
+5 -8
View File
@@ -130,14 +130,11 @@ export function createDroneAirspaceLayer({
// cards inert anywhere over a zone. Unowned, our picks read as
// "empty space" to siblings — the same contract as fire perimeters.
_clickSubscription = inputFor(_viewer).onClick((event) => {
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
);
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) return;
const picked = event.topHit;
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
+3 -35
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createDroneAirspaceLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
// The fills set of the layer the last harness made: zone picks name it.
@@ -19,12 +19,11 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
const owners = new Map();
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
const input = fakeInputUnderLabel(viewer);
const input = fakeInput(viewer);
const clicks = {
handler: (click) => input.click(click.position),
// Only the label's own overlay handler is left.
get destroyed() {
return input.input.subscriberCount() === 1 ? 1 : 0;
return input.input.subscriberCount() === 0 ? 1 : 0;
},
};
const layer = createDroneAirspaceLayer({
@@ -62,8 +61,6 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
overlay,
clicks,
owners,
/** A label painted over the map: while `over`, it takes each click. */
label: input.label,
};
}
@@ -146,35 +143,6 @@ test('clicking a zone publishes its card; empty space clears it', async () => {
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
});
test('a click a label painted over the open zone card takes closes the card, as a click beside it does', async () => {
let pickResult = null;
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{ pick: () => pickResult, cardHit: () => cardHitResult },
);
await h.layer.update(h.viewer);
pickResult = zonePick('drone-airspace:310:0');
h.clicks.handler({ position: { x: 10, y: 10 } });
const [card] = h.overlay.entries.get('drone-airspace');
// Off the label, a click on the open card keeps it open.
pickResult = null;
cardHitResult = { entryId: card.id };
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.length, 1);
// The open card lies under the label: the click is not on the card.
h.label.over = true;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(
h.overlay.entries.get('drone-airspace')?.length ?? 0,
0,
'the card is closed',
);
h.layer.destroy();
});
test('late refresh cannot publish after disable or destroy', async () => {
for (const action of ['disable', 'destroy']) {
let resolve, signal;
+7 -10
View File
@@ -46,16 +46,13 @@ export function createSelection({
const pickedId = resolvePickId(picked);
if (pickedId && isOwnedByOtherLayer(id, pickedId)) return;
}
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{
sourceId: FIRMS_OVERLAY_SOURCE_ID,
},
);
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{
sourceId: FIRMS_OVERLAY_SOURCE_ID,
},
);
if (cardHit) {
const carded = layerState._fireByCardId.get(cardHit.entryId);
if (carded) selectAndFocusFire(carded);
-80
View File
@@ -1,80 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { createSelection } from './selection.js';
/** The fire selection over a viewer whose clicks a label may take, with a
* fire's card under every click. */
function selectionHarness(t) {
const viewer = { scene: { canvas: {}, pick: () => null } };
const fake = fakeInputUnderLabel(viewer);
t.after(() => fake.destroy());
const fire = { lat: 1, lon: 2, acqMs: 3, frp: 40, satellite: 'N' };
const focused = [];
const cleared = [];
const layerState = {
_viewer: viewer,
_icons: { id: 'firms:icons' },
_pickIndexById: new Map(),
_fireByCardId: new Map([['firms-card:1', fire]]),
_selectedFire: null,
_contextIds: new Set(),
};
const selection = createSelection({
layerState,
services: {
picking: { resolvePickId, isOwnedByOtherLayer: () => false },
focus: { requestWorldFocus: (request) => focused.push(request.kind) },
context: {
selectEntityContext() {},
clearSelectedEntityContextForLayer: (id) => cleared.push(id),
getContextStore() {},
registerEntityContext() {},
},
},
components: {
model: {
firePosition: () => ({ x: 0, y: 0, z: 0 }),
formatFrp: String,
confidenceBucket: String,
},
cards: { rebuildAmbientLabels() {} },
},
config: {
id: 'firms',
name: 'Fires',
overlayHost: {
hitTest: (_x, _y, { sourceId }) =>
sourceId === FIRMS_OVERLAY_SOURCE_ID
? { entryId: 'firms-card:1' }
: null,
},
},
});
selection.installClickHandler();
t.after(() => selection.removeClickHandler());
return { fake, layerState, fire, focused, cleared };
}
test("a click a label painted over a fire's card takes never selects or focuses the fire", (t) => {
const h = selectionHarness(t);
h.fake.label.over = true;
h.fake.click();
assert.equal(h.layerState._selectedFire, null);
assert.deepEqual(h.focused, [], 'the camera is not sent to the fire');
});
test('a click a label painted over the map takes lets go of the selected fire', (t) => {
const h = selectionHarness(t);
// Off the label, a click on the card selects and focuses its fire.
h.fake.click();
assert.equal(h.layerState._selectedFire, h.fire);
assert.deepEqual(h.focused, ['fire']);
h.fake.label.over = true;
h.fake.click();
assert.equal(h.layerState._selectedFire, null);
assert.deepEqual(h.cleared, ['firms']);
assert.deepEqual(h.focused, ['fire']);
});
+5 -8
View File
@@ -707,14 +707,11 @@ export function createGhostMapsLayer({
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID },
);
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) {
if (_selectedLink && openExternal) openExternal(_selectedLink);
return;
-47
View File
@@ -3,7 +3,6 @@ import test from 'node:test';
import { setLocale } from '../../i18n/index.js';
import { createGhostMapsLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { inputFor } from '../../input/dispatcher.js';
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
function element(localName, children = [], value = '', attributes = {}) {
@@ -673,49 +672,3 @@ test('narrowing to a window the loaded data covers clears a failed wider reload'
assert.equal(layer.getStats().error, null);
assert.equal(layer.getStats().count, 1);
});
test("a click a label painted over the open card takes never opens the card's link, and closes the card", async (t) => {
const cards = [];
const opened = [];
let cardUnder = null;
const { layer, viewer, click } = fixture(t, {
now: () => Date.UTC(2026, 10, 3, 12),
reports: [
{
name: 'Linked',
description:
'<table><tr><td>Date</td><td>11/2/2026</td></tr>' +
'<tr><td>Source</td><td><a href="https://example.com/report">report</a></td></tr></table>',
},
],
controls: {
overlayHost: {
setEntries: (_id, entries) => cards.push(entries),
hitTest: () => (cardUnder ? { entryId: cardUnder } : null),
},
picking: { resolvePickId: (picked) => picked?.id ?? null },
openExternal: (url) => opened.push(url),
},
});
// A label painted over the map, as a Space Missions label is: while it is
// over, it takes each click.
let labelOver = false;
inputFor(viewer).onOverlayClick(() => labelOver);
await layer.update(viewer);
click('ghostmaps:cip:0:0');
const [card] = cards.at(-1);
assert.equal(card.interactive, true);
// The open card lies under the label: the click opens nothing.
cardUnder = card.id;
labelOver = true;
click(null);
assert.deepEqual(opened, [], 'the link beneath the label is not opened');
assert.deepEqual(cards.at(-1), [], 'the card is closed');
// Off the label, a click on the open card opens its link.
labelOver = false;
click('ghostmaps:cip:0:0');
click(null);
assert.deepEqual(opened, ['https://example.com/report']);
});
-45
View File
@@ -623,51 +623,6 @@ test('a Satellites enable that never settles still lets mission disable complete
stuck.resolve();
}
await f.settle();
// The saved Satellites state was kept: turning Space Missions off again
// once Satellites settles gives back the Satellites it turned on.
assert.equal(f.manager.isEnabled('satellites'), true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), false);
assert.equal(f.manager.isEnabled('satellites'), false);
});
test('Space Missions turned on again after a busy restore switches Satellites on', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.state.satelliteSettleTimeoutMs = 50;
const satellites = f.manager.layers.get('satellites').module;
const enable = satellites.enable;
const stuck = Promise.withResolvers();
satellites.enable = () => stuck.promise;
try {
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
// Something else switches Satellites off, then Space Missions comes back.
await f.manager.setEnabled('satellites', false);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), true);
// Its own off still gives back the Satellites from before the first start.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
});
test('a failed Satellites restore still clears the selected mission panel', async (t) => {
+13 -20
View File
@@ -108,7 +108,7 @@ export function createIngestion({
async function captureSatelliteDependency() {
const manager = layerState._dataManager;
if (!manager) return;
if (!manager || layerState._satelliteStateBeforeMission) return;
const token = layerState._lifecycleToken;
// Let a pending Satellites action finish before reserving dependency ON.
// A successful explicit OFF can cancel this mission entry while we wait.
@@ -127,16 +127,12 @@ export function createIngestion({
!manager.isEffectivelyEnabled('rocket-launches'))
)
return;
// A saved state kept by a restore that could not finish (Satellites was
// busy) is still the one from before the mission: keep it, and switch
// Satellites on for the mission again.
if (!layerState._satelliteStateBeforeMission)
layerState._satelliteStateBeforeMission = {
enabled: manager.isEnabled('satellites'),
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
manager.getLayerParams('satellites'),
),
};
layerState._satelliteStateBeforeMission = {
enabled: manager.isEnabled('satellites'),
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
manager.getLayerParams('satellites'),
),
};
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsForSpaceMissions(
@@ -183,21 +179,18 @@ export function createIngestion({
layerState._satelliteStateBeforeMission !== snapshot
)
return;
// An accepted Satellites action owns visibility through mission teardown.
const restoreVisibility = snapshot.restoreVisibility !== false;
// Satellites is still busy: change nothing and keep the saved state, so
// turning Space Missions off again can finish the restore.
if (restoreVisibility && !idle)
throw new Error(
'Space Missions could not restore the satellites layer: it did not settle',
);
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsAfterSpaceMissions(snapshot.params),
);
if (!restoreVisibility) return;
// An accepted Satellites action owns visibility through mission teardown.
if (snapshot.restoreVisibility === false) return;
if (!idle)
throw new Error(
'Space Missions could not restore the satellites layer: it did not settle',
);
const restored = await manager.setEnabled('satellites', snapshot.enabled);
if (
restored === false ||
+5 -10
View File
@@ -118,15 +118,11 @@ const label = (
entryId,
});
test('a mission label click focuses its launch and covers the geometry beneath', (t) => {
const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
test('a mission label click focuses its launch and stops the click there', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
r.click();
assert.deepEqual(r.focused, ['L2'], 'the mission beneath is not picked');
// Other layers still hear it, to close their cards or clear selection,
// as a click on the label rather than on the geometry beneath.
assert.equal(r.ambient.length, 1);
assert.equal(r.ambient[0].overlay, true);
assert.equal(r.ambient[0].drawHit, null);
assert.deepEqual(r.focused, ['L2']);
assert.equal(r.ambient.length, 0, 'the layers beneath do not see it');
r.setHit(label('launch:L1', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID));
r.click();
@@ -160,8 +156,7 @@ test('a throwing globe-pick listener does not stop the pick', (t) => {
r.click();
assert.deepEqual(r.focused, ['L1']);
assert.deepEqual(heard, ['L1']);
assert.equal(r.ambient.length, 1);
assert.equal(r.ambient[0].overlay, true);
assert.equal(r.ambient.length, 0);
});
test('a mission label for an unknown launch falls through to other layers', (t) => {
@@ -177,36 +177,3 @@ test('without a Satellites action the exit restores the pre-mission visibility',
['enabled', 'satellites', false],
]);
});
test('a Satellites layer that does not settle keeps the saved state for the next exit', async () => {
const r = satelliteRig({ enabledBefore: false });
let idle = false;
r.state._dataManager.waitForLayerIdle = async () => idle;
await assert.rejects(
r.ingestion.restoreSatelliteDependency(),
/did not settle/,
);
assert.deepEqual(r.calls, [], 'nothing changes while Satellites is busy');
assert.deepEqual(r.state._satelliteStateBeforeMission, {
enabled: false,
params: { mode: 'before' },
});
// Turning Space Missions off again once Satellites settles finishes it.
idle = true;
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [
['params', 'satellites', { mode: 'before' }],
['enabled', 'satellites', false],
]);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
test('a Satellites action the person took still gets its parameters back when Satellites is busy', async () => {
const r = satelliteRig({ enabledBefore: false });
r.state._dataManager.waitForLayerIdle = async () => false;
r.state._satelliteStateBeforeMission.restoreVisibility = false;
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [['params', 'satellites', { mode: 'before' }]]);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
+2 -8
View File
@@ -380,20 +380,14 @@ export function createPanel({ state: layerState, services, parts, source }) {
function scheduleMissionRosterPreview(index) {
const launch = layerState._launches[index];
// Once the layer is going off (its Satellites restore may still be
// running) hovering or focusing a roster row moves no camera.
if (!launch || layerState._selectedLaunchId || !layerState._enabled) return;
if (!launch || layerState._selectedLaunchId) return;
if (layerState._missionRosterHoverTimer)
clearTimeout(layerState._missionRosterHoverTimer);
layerState._hoveredRosterLaunchId = launch.id;
parts.overlays.syncMissionOverlayEntries();
layerState._missionRosterHoverTimer = setTimeout(() => {
layerState._missionRosterHoverTimer = null;
if (
layerState._hoveredRosterLaunchId !== launch.id ||
!layerState._enabled
)
return;
if (layerState._hoveredRosterLaunchId !== launch.id) return;
const currentLaunch = resolveMissionRosterPreviewLaunch(
layerState._launches,
launch.id,
-24
View File
@@ -9,7 +9,6 @@ function fixture() {
const state = createState({
services: { overlays: {}, render: {} },
});
state._enabled = true;
const calls = [];
const parts = {
overlays: {
@@ -195,26 +194,3 @@ test('the panel commands act on the selected mission', () => {
['select', null, undefined],
]);
});
test('a roster row hovered or focused while the layer goes off moves no camera', async () => {
const { state, panel, calls } = fixture();
state._launches = [launch('a'), launch('b')];
panel.createMissionPanel();
panel.renderMissionRoster();
// Hovered just before the layer goes off: the pending preview is dropped.
panel.commands.rosterPointerEnter(0);
state._enabled = false;
await new Promise((resolve) => setTimeout(resolve, 160));
// Hovered or focused after it went off, while the panel still shows.
panel.commands.rosterPointerEnter(1);
panel.commands.rosterFocus(1);
assert.equal(state._missionRosterHoverTimer, null, 'no preview is pending');
await new Promise((resolve) => setTimeout(resolve, 160));
assert.deepEqual(
calls.filter(([name]) => name === 'preview'),
[],
);
panel.clearMissionPanel();
});
+10 -3
View File
@@ -8,7 +8,12 @@ import {
} from '../../data/screenRotation.js';
import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js';
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js';
import {
drawOf,
findCamera,
findFrame,
findQuery,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { routePlausible } from '../../data/routePlausible.js';
@@ -677,8 +682,10 @@ export function createLocalAdsbLayer({
if (ownedElsewhere(topId) && !trail) return 'other';
let hits = [];
try {
// The click's own drill: none under a label painted over the map.
hits = event.drill(CLICK_DRILL_LIMIT);
hits =
findQuery(viewer)?.drillPick(event.position.x, event.position.y, {
limit: CLICK_DRILL_LIMIT,
}) ?? [];
} catch {
hits = [];
}
+1 -38
View File
@@ -17,7 +17,6 @@ import { createLocalAdsbModels } from './models.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { inputFor } from '../../input/dispatcher.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
@@ -1175,8 +1174,7 @@ function iconPick(draw, id) {
return { primitive: {}, id: { set: layerSet(draw, ':markers').spec.id, id } };
}
/** A viewer with a canvas and scripted picks, plus the layer's click action.
* A click drills through the viewer's `drillHits`. */
/** A viewer with a canvas and scripted picks, plus the layer's click action. */
function clickHarness() {
const scene = {
canvas: {},
@@ -1184,8 +1182,6 @@ function clickHarness() {
pick() {
return scene.pickResult;
},
drillPick: () =>
(base.viewer.drillHits ?? []).map((hit) => ({ primitive: {}, id: hit })),
};
const base = fakeViewer({ scene });
return {
@@ -1269,39 +1265,6 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
assert.equal(calls.selected.length, 2, 'the Flights contact is not taken');
});
test('a click a label painted over a local aircraft takes never selects the aircraft, and lets go of the selection', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const harness = clickHarness();
const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer,
});
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
const label = { over: true };
inputFor(harness.viewer.viewer).onOverlayClick(() => label.over);
const model = {
set: layerSet(draw, ':models').spec.id,
id: 'local-adsb:abc123',
surface: false,
};
// The aircraft is under the label, both exactly and in the drill.
harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
harness.viewer.viewer.drillHits = [model];
harness.click();
assert.deepEqual(calls.selected, [], 'the aircraft beneath is not taken');
// Off the label the same click selects it; on the label it lets go.
label.over = false;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
label.over = true;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
assert.equal(calls.cleared.length, 1, 'the selection is released');
});
test('a grounded aircraft changing type keeps its drawn model on its own belly offset until the new one is ready', () => {
const { draw, viewer, camera } = modelViewer();
const models = createLocalAdsbModels({
+3 -6
View File
@@ -1348,12 +1348,9 @@ export function createNewsLayer({
clickOff = inputFor(viewer).onClick((event) => {
const at = event?.screenPosition;
if (!enabled || destroyed || !isPointerFree() || !at) return;
// A click a label painted over the cards took is not on a card.
const card = event.overlay
? null
: hitTestOverlay(at.x, at.y, {
sourceId: NEWS_OVERLAY_SOURCE_ID,
});
const card = hitTestOverlay(at.x, at.y, {
sourceId: NEWS_OVERLAY_SOURCE_ID,
});
if (card?.entry?.activate) {
card.entry.activate();
return;
+2 -43
View File
@@ -6,8 +6,6 @@ import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { NEWS_KEY_PROVIDERS, createNewsLayer } from './index.js';
import { getSelectedEntityContext } from '../../data/contextStore.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { NEWS_OVERLAY_SOURCE_ID } from './model.js';
const NOW = Date.parse('2026-10-28T10:00:00Z');
const hotspotsPayload = {
@@ -53,8 +51,6 @@ function fixture(
now = () => NOW,
quality,
pictureCards,
underLabel = false,
hitTestOverlay = () => null,
} = {},
) {
const calls = { feed: [], hotspots: 0, outline: 0 };
@@ -141,18 +137,11 @@ function fixture(
for (const fn of [...clickHandlers])
fn({ screenPosition: { x: 10, y: 10 }, topHit });
};
// Or the scene's own dispatcher, with a label that may be painted over
// the map (`fake.label.over`).
let fake = null;
if (underLabel) {
viewer.scene = { canvas: {}, pick: () => null };
fake = fakeInputUnderLabel(viewer);
}
const layer = createNewsLayer({
source,
overlayHost,
inputFor: () => fake?.input ?? input,
hitTestOverlay,
inputFor: () => input,
hitTestOverlay: () => null,
now,
matchMedia: () => ({ matches: reduced }),
getViewCentre: () => centre(),
@@ -169,7 +158,6 @@ function fixture(
layer.attachShellServices({ runNavigation: (navigate) => navigate() });
t.after(() => {
layer.destroy();
fake?.destroy();
unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
@@ -184,7 +172,6 @@ function fixture(
items,
click,
clickHandlers,
fake,
};
}
@@ -1298,34 +1285,6 @@ test('a click on a marker selects its report, on a beacon chooses its hotspot, o
assert.equal(clickHandlers.size, 0);
});
test("a click a label painted over a report's card takes never opens the card, and lets go of the report", async (t) => {
let activated = 0;
const { layer, fake } = fixture(t, {
height: 500_000,
underLabel: true,
// A report's card lies under every click.
hitTestOverlay: (_x, _y, { sourceId }) =>
sourceId === NEWS_OVERLAY_SOURCE_ID
? { entry: { activate: () => activated++ } }
: null,
});
layer.enable();
await layer.update();
await flush();
layer.setParams({ reportId: 'major', pin: 0 });
assert.equal(layer.getRowControls().feed.selected.id, 'major');
fake.label.over = true;
fake.click();
assert.equal(activated, 0, 'the card beneath the label is not opened');
assert.equal(layer.getRowControls().feed.selected, null);
// Off the label, the same click opens the card.
fake.label.over = false;
fake.click();
assert.equal(activated, 1);
});
test('zoomed out, a hotspot is one beacon; off, nothing draws; destroyed, the sets go', async (t) => {
const { layer, items } = fixture(t);
assert.deepEqual(items('points'), []);
+5 -8
View File
@@ -218,14 +218,11 @@ export function createFirePerimetersLayer({
_clickSubscription = inputFor(_viewer).onClick((event) => {
// A click on the incident card itself opens its InciWeb page (when the
// incident has one) and never disturbs the selection.
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: PERIMETER_OVERLAY_SOURCE_ID },
);
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: PERIMETER_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) {
if (_selectedLink && openExternal) openExternal(_selectedLink);
return;
+3 -53
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFirePerimetersLayer } from './index.js';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
// The fills set of the layer the last harness made: perimeter picks name it.
@@ -30,12 +30,11 @@ function harness(
const opened = [];
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
const input = fakeInputUnderLabel(viewer);
const input = fakeInput(viewer);
const clicks = {
handler: (click) => input.click(click.position),
// Only the label's own overlay handler is left.
get destroyed() {
return input.input.subscriberCount() === 1 ? 1 : 0;
return input.input.subscriberCount() === 0 ? 1 : 0;
},
};
const layer = createFirePerimetersLayer({
@@ -79,8 +78,6 @@ function harness(
clicks,
owners,
opened,
/** A label painted over the map: while `over`, it takes each click. */
label: input.label,
};
}
@@ -314,53 +311,6 @@ test('a matched incident card carries the InciWeb line and click-through', async
);
});
test('a click a label painted over the incident card takes never opens its InciWeb page, and closes the card', async () => {
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
inciwebIndex: [
{
incident_id: '329300',
tau: 'NMGNF Fixture Fire',
incident_title: 'Fixture Fire',
},
],
cardHit: () => cardHitResult,
},
);
await h.layer.update(h.viewer);
h.clicks.handler({ position: { x: 10, y: 10 } });
await new Promise((done) => setTimeout(done, 0));
const [card] = h.overlay.entries.get('fire-perimeters');
assert.equal(card.details.at(-1), 'InciWeb ↗ · click card to open');
// The open card lies under the label: the click opens nothing.
cardHitResult = { entryId: card.id };
h.viewer.scene.pick = () => null;
h.label.over = true;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, [], 'the page beneath the label is not opened');
assert.equal(
h.overlay.entries.get('fire-perimeters')?.length ?? 0,
0,
'the card is closed',
);
// Off the label, a click on the open card opens its page.
h.label.over = false;
h.viewer.scene.pick = () =>
perimeterPick('fire-perimeter:2026-NMGNF-000123:0');
h.clicks.handler({ position: { x: 10, y: 10 } });
await new Promise((done) => setTimeout(done, 0));
cardHitResult = { entryId: h.overlay.entries.get('fire-perimeters')[0].id };
h.viewer.scene.pick = () => null;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']);
h.layer.destroy();
});
test('an unmatched incident renders no InciWeb line and card clicks stay inert', async () => {
let cardHitResult = null;
const h = harness(
+3 -6
View File
@@ -278,12 +278,9 @@ export function createShipwrecksLayer({
_clickHandler = clicks.onClick((click) => {
if (pointer && !pointer.isPointerFree()) return;
const at = click.screenPosition;
// A click a label painted over the cards took is not on a card.
const cardHit = click.overlay
? null
: overlayHost.hitTest?.(at?.x, at?.y, {
sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID,
});
const cardHit = overlayHost.hitTest?.(at?.x, at?.y, {
sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID,
});
if (cardHit && cardHit.entryId === _selectedCardId) {
if (_selectedLink) openExternal(_selectedLink);
return;
-49
View File
@@ -2,7 +2,6 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import * as picking from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import {
createShipwrecksLayer,
markerPixelSize,
@@ -394,51 +393,3 @@ test('the page deadline subtracts the newest available source age from the limit
);
assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults');
});
test("a click a label painted over the open card takes never opens the card's link, and closes the card", async (t) => {
let picked = null;
const viewer = { scene: { canvas: {}, pick: () => picked } };
bindFakeDraw(viewer);
const fake = fakeInputUnderLabel(viewer);
t.after(() => fake.destroy());
const cards = [];
const opened = [];
let cardUnder = null;
const layer = createShipwrecksLayer({
source: { getSnapshot: () => Promise.resolve(snapshot([wreck('a')])) },
overlayHost: {
setEntries: (_source, entries) => cards.push(entries),
setVisible() {},
hitTest: () => (cardUnder ? { entryId: cardUnder } : null),
},
input: () => fake.input,
picking,
pointer: { isPointerFree: () => true },
openExternal: (url) => opened.push(url),
now: () => 1,
});
layer.init(viewer);
t.after(() => layer.destroy());
layer.enable();
await layer.update();
picked = { primitive: {}, id: { set: 'shipwrecks:', id: 'shipwreck:a' } };
fake.click();
const [card] = cards.at(-1);
assert.equal(card.id, 'shipwreck-card:a');
// The open card lies under the label: the click opens nothing.
picked = null;
cardUnder = card.id;
fake.label.over = true;
fake.click();
assert.deepEqual(opened, [], 'the link beneath the label is not opened');
assert.deepEqual(cards.at(-1), [], 'the card is closed');
// Off the label, a click on the open card opens its link.
fake.label.over = false;
picked = { primitive: {}, id: { set: 'shipwrecks:', id: 'shipwreck:a' } };
fake.click();
picked = null;
fake.click();
assert.equal(opened.length, 1);
});
+11 -13
View File
@@ -64,19 +64,17 @@ export function createSelection({
// Cards are painted on a pointer-events:none canvas, so the scene pick is
// usually terrain behind the card. Resolve against the host's current
// actionable hit rectangles before treating the click as empty space.
// A click a label painted over the cards took is not on a card.
const cardHit =
!record && !event.overlay
? vesselState._vesselOverlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{
...(cycloneBackground
? {}
: { sourceId: VESSEL_OVERLAY_SOURCE_ID }),
},
)
: null;
const cardHit = !record
? vesselState._vesselOverlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{
...(cycloneBackground
? {}
: { sourceId: VESSEL_OVERLAY_SOURCE_ID }),
},
)
: null;
if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
return;
if (!record && cardHit) {
-89
View File
@@ -1,89 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { createSelection } from './selection.js';
/** Calls on any member are recorded by name and do nothing else. */
function recorder(calls) {
return new Proxy(
{},
{
get:
(_target, name) =>
(...args) =>
calls.push([name, ...args]),
},
);
}
/** The vessel selection over a viewer whose clicks a label may take. */
function selectionHarness(t) {
const viewer = { scene: { canvas: {}, pick: () => null } };
const fake = fakeInputUnderLabel(viewer);
t.after(() => fake.destroy());
const vessel = { id: 'v1', name: 'NORTHERN STAR', lat: 0, lon: 0 };
const focused = [];
const calls = [];
const state = {
feed: { enabled: true },
records: { byId: new Map([[vessel.id, vessel]]) },
icons: { setId: 'vessels:icons', has: () => false },
selectedRecord: null,
interactionKeyTarget: new EventTarget(),
};
const vesselState = {
state,
// The vessel's card lies under the click.
_vesselOverlayHost: {
hitTest: (_x, _y, { sourceId } = {}) =>
sourceId === VESSEL_OVERLAY_SOURCE_ID
? { sourceId, entryId: `vessel:${vessel.id}` }
: null,
},
};
const selection = createSelection({
vesselState,
services: {
picking: { isOwnedByOtherLayer: () => false },
worldFocus: { requestWorldFocus: (request) => focused.push(request.id) },
context: recorder(calls),
},
parts: {
queries: {
reduceVesselSelection: ({ selectedId, pickedId }) =>
pickedId
? { action: pickedId === selectedId ? 'none' : 'select' }
: { action: selectedId ? 'deselect' : 'none' },
},
rendering: recorder(calls),
cards: recorder(calls),
photos: recorder(calls),
tracking: recorder(calls),
},
layer: { source: 'AIS' },
});
selection.installInteraction(viewer);
t.after(() => selection.removeVesselInteraction());
return { fake, state, vessel, focused };
}
test("a click a label painted over a vessel's card takes never selects or focuses the vessel", (t) => {
const h = selectionHarness(t);
h.fake.label.over = true;
h.fake.click();
assert.equal(h.state.selectedRecord, null);
assert.deepEqual(h.focused, [], 'the camera is not sent to the vessel');
});
test('a click a label painted over the map takes lets go of the selected vessel', (t) => {
const h = selectionHarness(t);
// Off the label, a click on the card selects and focuses its vessel.
h.fake.click();
assert.equal(h.state.selectedRecord, h.vessel);
assert.deepEqual(h.focused, ['v1']);
h.fake.label.over = true;
h.fake.click();
assert.equal(h.state.selectedRecord, null);
assert.deepEqual(h.focused, ['v1']);
});
+7 -9
View File
@@ -483,18 +483,16 @@ export function createSelection({ state, services, parts }) {
if (!state.enabled || services.pointer?.isPointerFree?.() === false)
return;
const at = click.screenPosition;
// A click a label painted over the cards took is not on a card.
const hit =
!click.overlay &&
(overlay?.hitTest?.(at?.x, at?.y, {
overlay?.hitTest?.(at?.x, at?.y, {
sourceId: WILDLIFE_SELECTED_SOURCE_ID,
}) ||
overlay?.hitTest?.(at?.x, at?.y, {
sourceId: WILDLIFE_OVERLAY_SOURCE_ID,
}) ||
overlay?.hitTest?.(at?.x, at?.y, {
sourceId: WILDLIFE_LABEL_SOURCE_ID,
}));
overlay?.hitTest?.(at?.x, at?.y, {
sourceId: WILDLIFE_OVERLAY_SOURCE_ID,
}) ||
overlay?.hitTest?.(at?.x, at?.y, {
sourceId: WILDLIFE_LABEL_SOURCE_ID,
});
if (hit) {
hit.entry?.activate?.();
return;
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createSelection } from './selection.js';
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
const row = {
stableId: 'inat:123',
@@ -305,35 +304,6 @@ test('empty clicks and layer removal release the selected row and its overlay',
assert.equal(f.entries.size, 0);
});
test("a click a label painted over a sighting's card takes never selects the sighting, and lets go of the selected one", (t) => {
let fake = null;
const f = fixture(row, {
input: (viewer) => {
fake ??= fakeInputUnderLabel(viewer);
return fake.input;
},
});
f.selection.install();
t.after(() => {
f.selection.remove();
fake.destroy();
});
f.selection.refreshAmbient();
// The sighting's name card lies under every click.
f.hit('wildlife-sightings-labels', 'wildlife-sightings-label:inat:123');
// Off the label, a click on the card selects and focuses the sighting.
fake.click();
assert.equal(f.state.selectedId, row.stableId);
assert.equal(f.flights.length, 1);
fake.label.over = true;
fake.click();
assert.equal(f.state.selectedId, null, 'the selected sighting is let go');
assert.equal(f.state.selectedRow, null);
assert.equal(f.flights.length, 1, 'the camera is not sent to the sighting');
});
test('a tap selects only a sighting exactly under it, not one the touch search found near it', () => {
const f = fixture();
f.selection.install();
+262 -16
View File
@@ -62,10 +62,49 @@ export function onlyNumbersLookPrivate(text) {
// is ("card 4111 …", "phone +1 415 …", "token 12345678").
groups.every((group) => group.length <= 6) &&
groups.join('').length <= 9 &&
!/(?<!\d)\d{3}[ .-]\d{4}(?!\d)/.test(line) &&
!NUMBER_CONTEXT.test(line)
);
}
/**
* The most words a line sent for place suggestions may have: as many as the
* Omnibar reads as a place's name (ten with a number, as an address has).
*/
const suggestMaxWords = (text) => (/\d/.test(text) ? 10 : 8);
/**
* Common words no wallet's recovery phrase holds (they are not on the BIP39
* list): a line with one is a sentence, however many short words it has.
*/
const NOT_SEED_WORDS = new Set([
'the',
'and',
'are',
'for',
'from',
'with',
'how',
'why',
'which',
'would',
'could',
'should',
'does',
'was',
'were',
'flights',
]);
/**
* "Boise ID 83702", "Coeur d'Alene ID 83814": Idaho's code before a ZIP
* code, after a town's name (not after "my" or "employee", whose "ID" is an
* identity number).
*/
const IDAHO_BEFORE_ZIP = /(\S+)(,?\s)ID(?=\.?,?\s+\d{5}(?:-\d{4})?(?!\S))/gu;
const ID_OWNERS =
/^(?:my|your|our|his|her|their|employee|student|staff|member|user|customer|patient|national|voter|photo|tax|card|the|an?)$/i;
/**
* Words that say a number is an account, a card, a phone or a secret, in the
* interface's languages where they differ ("Karte", "Telefon", "tarjeta").
@@ -84,12 +123,16 @@ function foldLine(text) {
.normalize('NFKC')
.replace(/\p{Cf}/gu, '')
.replace(/[\u2018\u2019]/g, "'")
.replace(/(?![0-9])\p{Nd}/gu, '0');
.replace(/(?![0-9])\p{Nd}/gu, '0')
.replace(/\s+/g, ' ')
.replace(IDAHO_BEFORE_ZIP, (whole, word, gap) =>
ID_OWNERS.test(word) ? whole : `${word}${gap}Idaho`,
);
}
/** A US ZIP+4 after a state's code or name, as an address writes it. */
const US_ZIP4 = new RegExp(
String.raw`(?<=(?:^|\s)(?:[a-z]{2}|[a-z]\.[a-z]|Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Mass|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming|Puerto Rico)\.?,?\s)\d{5}-\d{4}\b`,
String.raw`(?<=(?:^|\s)(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|PR|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY]|[a-z]\.[a-z]|Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Mass|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming|Puerto Rico)\.?,?\s)\d{5}-\d{4}\b`,
'giu',
);
@@ -119,6 +162,59 @@ function privacyReason(text) {
)
)
return 'other';
// An email written around a filter: "john(at)gmail.com",
// "john[at]gmail[dot]com", "john at gmail dot com".
// Also "john at gmail.com" and a "(dot)" or "[dot]" in any of them.
// Spaced letter by letter ("j o h n @ g m a i l . c o m").
if (
/(?:^|\s)(?:\S\s){3,}@\s?(?:\S\s?){2,}/u.test(line) &&
/[^@]@[\p{L}\p{N}-]+\.\p{L}{2,}/u.test(line.replace(/\s+/g, ''))
)
return 'other';
if (
/[\p{L}\p{N}._%+-]\s*[([{<]\s*at\s*[)\]}>]\s*[\p{L}\p{N}-]/iu.test(line) ||
/\b\S+\s+at\s+\S+\s+(?:dot|punto|ponto|period|punkt|[([{<]\s*dot\s*[)\]}>])\s+\p{L}{2,24}\b/iu.test(
line,
) ||
/\b\S+\s+at\s+[\p{L}\p{N}-]+\s*[([{<]\s*dot\s*[)\]}>]\s*\p{L}{2,24}\b/iu.test(
line,
) ||
/\b[\p{L}\p{N}._%+-]+\s+at\s+[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*\s*\.\s*(?:com|net|org|edu|gov|mil|io|co|me|info|biz|app|dev|ai|[a-z]{2})\b/iu.test(
line,
)
)
return 'other';
// An IPv6 host in a link ("https://[::1]/").
if (/\[[0-9a-f:.]*:[0-9a-f:.]*:[0-9a-f:.]*\]/i.test(line)) return 'other';
// An IP address ("10.0.0.1").
if (/(?<![\d.])\d{1,3}(?:\.\d{1,3}){3}(?![\d.])/.test(line)) return 'other';
// An IPv6 address ("::1", "fe80::1%eth0", "2001:db8:0:0:0:0:2:1"): hex
// groups with "::", or five colons or more (a time has two).
if (
line.split(' ').some((token) => {
const bare = token.replace(/^[[(]+|[\]),.;]+$/g, '').replace(/%\w+$/, '');
const colons = (bare.match(/:/g) || []).length;
return (
/^[0-9a-f:.]+$/i.test(bare) &&
colons >= 2 &&
(bare.includes('::') || colons >= 5)
);
})
)
return 'other';
// A wallet's recovery phrase, whole or nearly ("abandon ability able
// …"): twelve to twenty-four words of three to eight letters, none a
// common word the phrase list lacks ("can you tell where the most …" is
// a question). Too long to be sent
// for suggestions anyway, it is kept from the assistant too.
const words = line.trim().toLowerCase().split(/\s+/);
if (
words.length >= 12 &&
words.length <= 24 &&
words.every((word) => /^[a-z]{3,8}$/.test(word)) &&
!words.some((word) => NOT_SEED_WORDS.has(word))
)
return 'other';
// Coordinates and grid references are a spot, not a number to keep: only
// text the place search itself reads as coordinates, as typed ("١٢٣٤,
// ٥٦٧٨" folded would read as a spot, but is not one).
@@ -146,7 +242,7 @@ function privacyReason(text) {
.replace(
// After a street word, or before the city ("12, 10115 Berlin");
// "030 12345" alone is a phone number.
/(?<=\p{L}\.?\s)\d{1,4}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+\p{L}|$)|(?<=^|\s)\d{1,4}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+\p{L})/giu,
/(?<=\p{L}\.?\s)[1-9]\d{0,3}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+(?!(?:thanks|thank|thx|please|pls|ok|okay|now|asap|call|text)\b)\p{L}|$)|(?<=^|\s)[1-9]\d{0,3}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+(?!(?:thanks|thank|thx|please|pls|ok|okay|now|asap|call|text)\b)\p{L})/giu,
' ',
)
// Other postcodes after a street's house number and before the city (a
@@ -164,7 +260,7 @@ function privacyReason(text) {
.replace(US_ZIP4, ' x ')
.replace(/\b\d{5}-\d{3}\b/g, ' x ')
.replace(
/〒\s?\d{3}-\d{4}|\b\d{3}-\d{4}(?=\s*[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])/gu,
/〒\s?\d{3}-\d{4}|\b\d{3}-\d{4}(?=\s*[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])|(?<=[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]\s*)\d{3}-\d{4}\b/gu,
' x ',
)
.replace(/#/g, ' x ')
@@ -176,9 +272,12 @@ function privacyReason(text) {
// An IBAN.
if (/\b[a-z]{2}\d{2}(?:\s?[a-z0-9]){10,}/i.test(line)) return 'other';
if (
/\b(?:password|passcode|passwd|ssn|pw|pwd|bearer)\b\s*[:=#]?\s*\S/i.test(
line,
) ||
/\b(?:password|passcode|passwd|pw|pwd)\b\s*[:=#]?\s*\S/i.test(line) ||
// "Bearer Island" and "SSN Station" are places: after "bearer" any value
// but a capitalised name is a token, and a social security number has
// digits.
bearerToken(line) ||
/\bssn\b(?:\s+(?:is|no\.?|number|#))*\s*[:=#]?\s*[\dx*]{3}/i.test(line) ||
// The word for "password" in the interface's languages.
// A whole word only: "Sachsenhausen" holds "senha" but is a place.
/(?<!\p{L})(?:contraseña|passwort|kennwort|mot de passe|senha|parola d'ordine|lösenord|пароль|пароля|密码|密碼|パスワード|비밀번호|סיסמה|كلمة (?:السر|المرور))(?!\p{L})\s*[:=#]?\s*\S/iu.test(
@@ -190,6 +289,16 @@ function privacyReason(text) {
line,
) ||
/\b(?:token|secret|api[ _-]?key|key|pass)\s*[:=]\s*\S/i.test(line) ||
// A number on a document or account after its label: "license ABC1234",
// "passport X1234567", "plate 7ABC123", "member no. 12345".
/\b(?:licen[cs]e|plate|passport|member(?:ship)?|account|acct|policy|ticket|booking|confirmation|ref(?:erence)?)(?:\s+(?:no\.?|number|#|is))*(?:\s*[:=#]\s*|\s+)(?=[a-z0-9-]*\d)[a-z0-9-]{4,}/i.test(
line,
) ||
// An identity number after "ID" in capitals ("ID AB123"); "Id" and
// "id" are words.
/\bID(?:\s+(?:no\.?|number|#|is))*(?:\s*[:=#]\s*|\s+)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]{4,}/.test(
line,
) ||
/\b(?:my secret is|passphrase|mnemonic|seed phrase|recovery phrase)\b\s*[:=]?\s*\S/i.test(
line,
) ||
@@ -204,7 +313,27 @@ function privacyReason(text) {
/\b(?:pin|otp|2fa|mfa|cvv|cvc|(?:door|access|gate|alarm|entry|security|verification|one-time|auth|login) code)\s*(?:[:=#]|\s[-–—]\s|-)\s*[a-z0-9]/i.test(
line,
) ||
codeAfterLabel(line)
codeAfterLabel(line) ||
// A door, alarm or lockbox number ("code 4821", "garage code 4821",
// "the code to my door is 4821").
// A postcode, dialling code or airport code is not one ("zip code
// 90210", "area code 415").
/\b(?<!\b(?:zip|postal|post|postcode|area|country|dialing|dialling|airport|iata|icao|country)\s)(?:code|alarm|lockbox|lock box|combination|combo|keypad)(?:\s+(?:number|no\.?|is|code|pin))*\s*[:=#]?\s*\d{3,8}\b/i.test(
line,
) ||
/\b(?<!\b(?:zip|postal|post|area|country|dialing|dialling|airport)\s)code\b.{0,30}?\bis\s*[:=]?\s*\d{3,8}\b/i.test(
line,
) ||
// A UK National Insurance number, spaced ("AB 12 34 56 C").
/\b[a-z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[a-d]\b/i.test(line) ||
// "my id is AB12345", "id no. 4471".
/\bid\s+(?:is|no\.?|number|#)\s*[:=#]?\s*(?=[a-z0-9-]*\d)[a-z0-9-]{4,}/i.test(
line,
) ||
// A one-time code in a link ("…/callback?code=abcdef").
/[?&](?:code|token|access_token|key|sig|signature|auth)=[^&\s]{4,}/i.test(
line,
)
)
return 'other';
if (
@@ -215,8 +344,12 @@ function privacyReason(text) {
.map((token) => token.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''))
.some(
(token) =>
/^(?:sk[-_]|rk_|pk_live|ghp_|xox[abposr]-)/i.test(token) ||
/^(?:AIza|eyJ|AKIA)/.test(token) ||
/^(?:sk[-_]|rk_|pk_live|ghp_|gho_|ghu_|ghs_|github_pat_|glpat-|hf_|xox[abposr]-)/i.test(
token,
) ||
/^SG\.[\w-]{8,}\.[\w-]{8,}$/.test(token) ||
/^(?:AIza|eyJ)/.test(token) ||
/^AKIA[0-9A-Z]{12,}$/.test(token) ||
mayBeSecret(token),
)
)
@@ -224,6 +357,25 @@ function privacyReason(text) {
return longNumber ? 'number' : null;
}
/**
* A value after "bearer" that is not a word a place's name is made of
* ("Bearer Island"); after "Authorization:" any value is a token.
*/
function bearerToken(line) {
if (/\bauthori[sz]ation\s*:\s*bearer\b\s*\S/i.test(line)) return true;
for (const match of line.matchAll(/\bbearer\b(\s*[:=#]?\s*)(\S+)/gi)) {
const value = match[2].replace(/[,.;:!?)]+$/, '');
// Only a word after a space may be a name: "Bearer: island" is a token.
if (/^\s+$/.test(match[1]) && PLACE_WORDS.test(value)) continue;
return true;
}
return false;
}
/** Words a place's name is made of, after a label word ("bearer island"). */
const PLACE_WORDS =
/^(?:island|islands|isle|lake|creek|river|point|bay|mountain|mount|hill|hills|valley|station|road|street|lane|avenue|park|beach|falls|springs?|county|city|town|village|plaza|square|mall|center|centre|tower|building|court|bank)$/i;
/**
* A code after a label that can only be a code, without a colon ("PIN
* A7B2", "verification code ABCDEF", "otp 7GH2K"): holding a digit, or in
@@ -231,6 +383,48 @@ function privacyReason(text) {
* "GATE CODE LANE", "OTP Bank" and "Auth Code ABCD Street" stay places.
*/
function codeAfterLabel(line) {
// Labels that only ever name a code take one in lower case too ("otp
// abcdef", "cvv abc", "verification code abcdef"); a capitalised word
// after them is a name ("OTP Bank", "MFA Boston").
// After a label in lower case, any value is a code ("verification code
// Abc"); after one written as a name, only a value that is not one.
const coded =
/\b((?:otp|2fa|mfa|cvv|cvc|(?:verification|one-time|security|auth|login) code)(?:\s+is)?)\s+([a-z0-9][a-z0-9-]{2,})(?:\s+(?:thanks|thank you|thx|please|pls|ok))?\s*[.!]?\s*$/i.exec(
line,
);
if (coded) {
const [, label, value] = coded;
const labelIsName = /\p{Lu}/u.test(label);
// A word a place's name is made of is no code ("security code plaza",
// "otp bank"); after the short labels a code in letters is written in
// capitals ("otp ABCDEF"), so a lower-case word is a name ("mfa
// boston").
const shortLabel = /^(?:otp|2fa|mfa)\b/i.test(label);
const named =
PLACE_WORDS.test(value) || (shortLabel && /^\p{Ll}+$/u.test(value));
if (!labelIsName && !named) return true;
// After a label written as a name, a value in capitals is a code ("OTP
// ABCDEF", "Verification code ABC"), one capitalised a name ("OTP
// Bank"); a CVV is never a name.
if (labelIsName) {
if (/^cv[vc]\b/i.test(label)) return true;
if (/^\p{Lu}[\p{Lu}\d-]+$/u.test(value) && !PLACE_WORDS.test(value))
return true;
if (!/^\p{Lu}(?:\p{Ll}+|\p{Lu}+)$/u.test(value)) return true;
}
}
// A value in mixed case that is no name ("PIN aBcD", "gate code aBcD").
const mixed =
/\b(?:pin|(?:door|access|gate|alarm|entry) code)(?:\s+is)?\s+([a-z0-9-]{4,})\s*[.!]?\s*$/i.exec(
line,
);
if (
mixed &&
/\p{Ll}/u.test(mixed[1]) &&
/\p{Lu}/u.test(mixed[1]) &&
!/^\p{Lu}\p{Ll}+$/u.test(mixed[1])
)
return true;
const match =
/\b((?:pin|cvv|cvc|otp|2fa|mfa|(?:door|access|gate|alarm|entry|security|verification|one-time|auth|login) code)(?:\s+is)?)\s+([a-z0-9][a-z0-9-]{3,})\s*[.!]?\s*$/i.exec(
line,
@@ -238,7 +432,9 @@ function codeAfterLabel(line) {
if (!match) return false;
const [, label, value] = match;
if (/\d/.test(value)) return true;
return value === value.toUpperCase() && label !== label.toUpperCase();
// A code in capitals ("PIN ABCD", "GATE CODE ABCD"), but not a word a
// place's name is made of ("GATE CODE LANE").
return value === value.toUpperCase() && !PLACE_WORDS.test(value);
}
/**
@@ -292,6 +488,43 @@ export function resetPlaceSuggestions() {
shared.pending.clear();
}
/**
* Countries that write a house's number before its street ("10 Downing
* Street", "12 rue de Rivoli"); elsewhere it follows ("Hauptstraße 12").
*/
const NUMBER_FIRST = new Set([
'US',
'CA',
'GB',
'IE',
'AU',
'NZ',
'FR',
'LU',
'MC',
'ZA',
'IN',
'PH',
'SG',
'MY',
'HK',
'TH',
'LK',
'NG',
'GH',
'KE',
'JM',
'TT',
]);
/** A house's number and street as its country writes them, or ''. */
export function houseAddress({ houseNumber, street, countryCode }) {
if (!houseNumber || !street) return '';
return NUMBER_FIRST.has(String(countryCode || 'US').toUpperCase())
? `${houseNumber} ${street}`
: `${street} ${houseNumber}`;
}
/** List Photon candidates while typing. The submitted search owns navigation. */
export function createPlaceSuggester({
endpoint,
@@ -308,7 +541,14 @@ export function createPlaceSuggester({
const text = String(query ?? '')
.trim()
.slice(0, MAX_QUERY_CHARS);
if (!enabled || text.length < minPlaceChars(text) || mayBePrivate(text))
// A line longer than a place's name is never sent: a pasted sentence
// or phrase is no place, and may be private in ways not read here.
if (
!enabled ||
text.length < minPlaceChars(text) ||
text.split(/\s+/).length > suggestMaxWords(text) ||
mayBePrivate(text)
)
return [];
const language = (globalThis.document?.documentElement?.lang || 'en')
.slice(0, 2)
@@ -384,11 +624,17 @@ export function createPlaceSuggester({
type,
street,
housenumber: houseNumber,
locality,
district,
} = feature.properties ?? {};
// A house has no name of its own: its street and number are its
// name, so two houses on one street stay two places.
const address =
street && houseNumber ? `${houseNumber} ${street}` : '';
// A house has no name of its own: its street (or, without one, its
// locality) and number are its name, written in the country's own
// order, so two houses on one street stay two places.
const address = houseAddress({
houseNumber,
street: street || locality || district || city,
countryCode,
});
const name = normalized.name || address || city || state || country;
if (!name) continue;
const detail = [...new Set([city, state, country])]
+193 -1
View File
@@ -3,8 +3,10 @@ import test from 'node:test';
import {
citiesInRegion,
createPlaceSuggester,
houseAddress,
inExtent,
mayBePrivate,
onlyNumbersLookPrivate,
resetPlaceSuggestions,
} from './placeSuggestions.js';
@@ -394,7 +396,6 @@ test('streets named for keys, tokens and codes, and ZIP+4 after a state, are pla
'GATE CODE LANE',
'SECURITY CODE PLAZA',
'OTP Bank',
'MFA BOSTON',
'Auth Code ABCD Street',
'California 90210-1234',
'Austin Texas 78701-1234',
@@ -402,7 +403,10 @@ test('streets named for keys, tokens and codes, and ZIP+4 after a state, are pla
'12, 10115 Berlin',
])
assert.equal(mayBePrivate(line), false, line);
// All in capitals, a name cannot be told from a code: "MFA BOSTON" is
// kept back with "OTP ABCDEF".
for (const line of [
'MFA BOSTON',
'gate code: abcd',
'PIN A7B2',
'PIN is A7B2',
@@ -427,3 +431,191 @@ test('the same text asked again while its request is out is sent once', async ()
await Promise.all([service.suggest('Paris'), service.suggest('Paris')]);
assert.equal(sent, 1);
});
test('spelled-out emails, addresses, phrases, codes and short phone numbers stay private', () => {
for (const line of [
'john(at)gmail.com',
'john[at]gmail[dot]com',
'john at gmail dot de',
'10.0.0.1',
'abandon ability able about above absent absorb abstract absurd abuse access accident',
'Abandon ability able about above absent absorb abstract absurd abuse access accident acid',
'license ABC1234',
'passport X1234567',
'plate 7ABC123',
'otp ABCDEF',
'verification code abcdef',
'cvv abc',
'Bearer abcdef',
'Bearer Abcdefgh',
'Authorization: Bearer Xyz',
'glpat-abcdef123456',
'hf_abcdefghijk',
'SG.abcdefghij.klmnopqrstuv',
'https://x.com/?code=abcdef',
'code 4821',
'garage code 4821',
'lockbox 4821',
'the code to my door is 4821',
'AB 12 34 56 C',
'my id is AB12345',
'My ID 12345',
'john at gmail .com',
'john at gmail punto com',
'john.doe at example period com',
'j o h n @ g m a i l . c o m',
'ssn is 123456',
'ssn: xxx-xx-1234',
'Bearer: island',
'Bearer=lake',
'OTP ABCDEF',
'CVV ABC',
'Verification code ABC',
'PIN ABCD',
'passport:123456',
'ID:12345',
'abandon please abandon abandon abandon abandon abandon abandon abandon abandon abandon abstract',
'find abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon',
'lockbox number 4821',
'lockbox is 4821',
'ab 12 34 56 c',
'https://[::1]/',
'ssn 123',
'Jo 12345-6789',
'Joe 1234 12345 thanks',
'Mo 0171 12345',
])
assert.equal(mayBePrivate(line), true, line);
// A phone's three and four digits are not offered as an address.
assert.equal(onlyNumbersLookPrivate('is 555 0100 thanks'), false);
});
test('places that only looked private are looked up', () => {
for (const line of [
'Akiak',
'Bearer Island',
'SSN Station',
'Bearer Island, Canada',
'bearer island',
'Washington DC 20500-0003',
'東京都千代田区100-0001',
'Security Code Plaza',
'Idaho Falls',
'meet at 12:30:45',
'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch',
'llanfairpwllgwyngyll',
'Boise ID 83702',
'Boise, ID 83702',
'Hayden ID 83835-1234',
'mfa boston',
'otp bank',
'security code plaza',
'zip code 90210',
'area code 415',
'Settipalle @ K.Bandarlapalle',
'boise ID 83702',
"Coeur d'Alene ID 83814",
'meet at West Point tomorrow',
'OTP Bank',
'GATE CODE LANE',
// Questions for the assistant, however many short words they have.
'can you tell where the most flights are going over texas today',
'are there any storms near florida right now that might cause delays',
'OTP Bank',
// A long request is not a recovery phrase.
'show flights over texas near austin with altitude above thirty thousand feet please',
'show fires near austin then show flights above texas with labels please',
])
assert.equal(mayBePrivate(line), false, line);
});
test('a house is named by its number and street in the order its country writes them', async () => {
assert.equal(
houseAddress({
houseNumber: '10',
street: 'Downing Street',
countryCode: 'gb',
}),
'10 Downing Street',
);
assert.equal(
houseAddress({
houseNumber: '12',
street: 'Hauptstraße',
countryCode: 'DE',
}),
'Hauptstraße 12',
);
assert.equal(houseAddress({ houseNumber: '12', street: '' }), '');
// Without a street, a house's number and its locality name it, so two
// houses in one hamlet stay two places, not the city twice.
const house = (number) => ({
geometry: { type: 'Point', coordinates: [11.2, 47.6] },
properties: {
housenumber: number,
locality: 'Mittenwald Au',
city: 'Mittenwald',
country: 'Germany',
countrycode: 'de',
osm_value: 'house',
},
});
const service = createPlaceSuggester({
endpoint: 'https://fixture.test/api/',
fetchImpl: async () =>
Response.json({ features: [house('3'), house('5')] }),
});
assert.deepEqual(
(await service.suggest('Mittenwald Au')).map((place) => place.name),
['Mittenwald Au 3', 'Mittenwald Au 5'],
);
});
test('codes, phones, tokens, emails and addresses in further shapes stay private', () => {
for (const line of [
// A phone's three and four digits after a name, as a postcode can't be
// told from it ("Shibuya 150-0002" is refused for that).
'Alice 555-0100',
'Shibuya 150-0002',
`${Array(23).fill('abandon').join(' ')} art`,
'Bearer Abcdefghijklmnopqrstuvwxyz',
'Bearer Island bearer abcdef',
'verification code Abc',
'verification code ABC',
'verification code abc thanks',
'PIN aBcD',
'gate code aBcD',
'john at gmail.com',
'john at gmail (dot) com',
'john at gmail [dot] com',
'john at gmail dot technology',
'passport number 123456',
'passport no. 123456',
'ID AB123',
'::1',
'fe80::1',
'2001:db8:0:0:0:0:2:1',
])
assert.equal(mayBePrivate(line), true, line);
});
test('a line longer than a place name is never sent for suggestions', async () => {
let sent = 0;
const service = createPlaceSuggester({
endpoint: 'https://fixture.test/api/',
fetchImpl: async () => {
sent++;
return Response.json({ features: [] });
},
});
assert.deepEqual(
await service.suggest('one two three four five six seven eight nine'),
[],
);
assert.equal(sent, 0);
// An address has more words: as many as the Omnibar reads as a place.
await service.suggest('350 Fifth Avenue, New York, NY 10118, United States');
assert.equal(sent, 1);
await service.suggest('1 2 3 4 5 6 7 8 9 10 11');
assert.equal(sent, 1);
});
+2 -4
View File
@@ -483,12 +483,10 @@ export class CockpitViewController {
* A click on the orbital picture: on a mapped point in reach it keeps the
* camera on that point; anywhere else it ends such a focus.
* @param {{x: number, y: number}|null|undefined} position
* @param {{overlay?: boolean}} [options] `overlay`: a label painted over
* the map took the click, which then only ends a focus.
* @returns {boolean} True when the click focused a point.
*/
onOrbitalClick(position, options) {
return onOrbitalClick.call(this, position, options);
onOrbitalClick(position) {
return onOrbitalClick.call(this, position);
}
/**
* A double-click on the orbital picture: on a mapped ground point it keeps
+3 -8
View File
@@ -256,16 +256,13 @@ export function onOrbitalDoubleClick(position) {
* focuses it; any other click ends a focus. A click a tool owns (drawing)
* is left alone, as is every click outside orbit.
* @param {{x: number, y: number}|null|undefined} position Canvas position.
* @param {{overlay?: boolean}} [options] `overlay`: a label painted over the
* map took the click, so it is on no site and only ends a focus.
* @returns {boolean} True when the click focused a point.
*/
export function onOrbitalClick(position, { overlay = false } = {}) {
export function onOrbitalClick(position) {
if (!inOrbit(this) || !isPointerFree()) return false;
if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y))
return false;
// A click a label painted over the map took is on no site.
const site = overlay ? null : siteAt(this, position);
const site = siteAt(this, position);
const state = this.orbital;
if (site) {
if (state.focus?.key === String(site.id)) return true;
@@ -289,9 +286,7 @@ export function routeSceneClick() {
// A viewer with no input (headless tools, partial stubs) has no clicks.
return () => {};
}
return input.onClick((event) =>
this.onOrbitalClick(event?.position, { overlay: event?.overlay === true }),
);
return input.onClick((event) => this.onOrbitalClick(event?.position));
}
/**