Read a search box line into places, layers, actions and questions

A pure pipeline the search box will show its rows from: omnibarIntent.js
parses a line (a place, a layer, a verb, a question, a panel's text),
omnibarEnter.js picks what Enter does, omnibarGuide.js answers "how do
I" for each feature, and omnibarRows.js turns all of it into rows. Its
strings are translated into every shipped language.

Co-authored-by: Sameh Khamis <[email protected]>
This commit is contained in:
Manjunath PaparajuandSameh Khamis authored and Sameh Khamis committed 2026-11-18 14:31:45 -08:00
1 parent edc64bdf9a
commit ca77ecfa1d
19 files changed
+5881 -13

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
// What Enter does in the Omnibar before a row is chosen with the keyboard:
// the one rule, in one place. The rows come from src/ui/omnibarRows.js; the
// text this rule reads is the line after readLine (omnibarRows.js).
//
// Enter performs an action (a plan, a layer switch, a command, Ask GEV) only
// when the line asks for it outright:
// (a) the action's own clause starts with a verb from ACTION_VERB (one
// list, in omnibarIntent.js): "show flights", "play radio in Tokyo",
// "go to Austin and show flights". A verb inside a place's name asks
// for nothing ("radio near Clear Lake");
// (b) or the line is a command's exact label, alone or after ">" ("North
// up", "> Clear all layers"); a command row runs on nothing else;
// (c) or, for Ask GEV, it is a real question (isRealQuestion).
// A whole layer name with a place after near, in, around, over, across or
// above ("flights near Tokyo"; not "of" or "at": "Planes of Fame") asks
// outright too. Keywords without a verb ask for nothing, however many
// clauses they fill ("Fire and Rain", "noir and cctv near austin"). Otherwise
// the place row is the default, and any plan or command is offered after
// it. A guide found by forgiving a typo, or on a line written as a title
// ("How To Train Your Dragon"), is offered, never run. Some actions need
// more:
// - sound (the Radio layer and radio steps), clearing the map, closing
// panels and the cockpit need (a) or (b);
// - the microphone, sharing the view, resetting it and the globe view
// need (b);
// - a layer row runs only when the line names that layer before any
// other (the row's `best`): "show flights" with Flights already on
// offers Flights, never Military Flights.
// Only the first row can be the default, and the pointer never makes one:
// a hovered row is chosen by a click, and the arrow keys choose any row.
import { hasActionVerb, isRealQuestion } from './omnibarIntent.js';
/**
* Words that are both the name of a bundled place (wikidata_cities or
* wikidata_places) and, alone, a command, style or layer word. Typed alone
* they search the place first and offer the switch second. Found by sweeping
* every bundled name through the Omnibar (see docs/CURRENT-STATE.md); a test
* checks each is still a bundled name.
*/
export const PLACE_WORDS = new Set([
'bike',
'hurricane',
'normal',
'rain',
'ski',
'street',
'thermal',
]);
/** Whether the whole line is one of PLACE_WORDS, in any case. */
export function isPlaceWord(text) {
return PLACE_WORDS.has(
String(text || '')
.trim()
.toLowerCase(),
);
}
/** Layers whose switching on starts sound. */
export const SOUND_LAYERS = new Set(['radio']);
/** Camera moves that only their exact label asks for (b). */
const NAMED_ONLY = new Set(['share', 'reset', 'zoom_to_globe']);
/**
* Whether a plan's steps ask for themselves. Verbs are read per clause: the
* parser marks each step whose own clause had one (`parsed.asked`), so a verb
* inside a place's name ("radio near Clear Lake") asks for nothing.
* @param {Array<object>} steps
* @param {{named: boolean, parsed: object}} line
*/
function planAsked(steps, { named, parsed }) {
if (named) return true;
const asked = parsed?.asked || new Set();
const requests = steps.filter((step) => step.kind !== 'place');
for (const step of requests) {
if (step.kind === 'camera' && NAMED_ONLY.has(step.act || step.name))
return false;
const needsVerb =
(step.kind === 'camera' && step.act === 'clear') ||
(step.kind === 'panel' && step.action === 'close') ||
step.kind === 'cockpit' ||
step.kind === 'radio' ||
(step.kind === 'layer' && SOUND_LAYERS.has(step.layer.id));
if (needsVerb && !asked.has(step)) return false;
}
if (!requests.length) return false;
// Every request asked for by a verb in its own clause. Keywords alone ask
// for nothing, however many clauses they fill ("Fire and Rain", "Noir
// and Thermal", "New York City noir").
if (requests.every((step) => asked.has(step))) return true;
// "flights near Tokyo": a whole layer name, and a place after near/in.
const [only] = requests;
// Only that one request: a bare keyword beside it ("flights near Austin
// and noir") is not asked for.
return (
requests.length === 1 &&
only.kind === 'layer' &&
only.layer.exact !== false &&
parsed?.placeFrom === 'near'
);
}
/**
* Whether Enter may run this row without it being chosen.
* @param {object} item A row.
* @param {string} text The typed line.
* @param {object} parsed The line as parseOmnibar read it.
* @param {{named: boolean}} context `named`: the line is a command's exact
* label.
*/
export function mayRunOnEnter(item, text, parsed, context) {
const verb = hasActionVerb(text);
switch (item?.kind) {
case 'guide':
// A walk found by a typo, or a line written as a title ("How To Train
// Your Dragon"), is offered, never run.
return !item.loose && !item.titled;
case 'place':
// A row only for picking ("Search … anyway") never runs on Enter.
return !item.explicit;
case 'count-show':
case 'entity':
case 'view-ask':
case 'sel-fly':
case 'sel-follow':
case 'sel-cockpit':
case 'sel-ask':
case 'sel-close':
return true;
case 'ask':
return isRealQuestion(text);
case 'layer':
return (
Boolean(item.best) &&
(!SOUND_LAYERS.has(item.id) || !item.enabled || verb || context.named)
);
case 'mic':
return Boolean(item.named);
case 'open-draw':
return verb;
case 'plan':
// A command row runs on its exact label only; a verb that merely
// lists it ("hide", "turn off") offers it.
if (item.command) return Boolean(item.named);
return planAsked(item.steps || [], { named: context.named, parsed });
default:
return false;
}
}
/**
* The rows in the order shown: when the first may not run on Enter, the
* first place row moves ahead of it, so Enter searches the place.
*/
export function orderForEnter(items, text, parsed, context) {
const first = items[0];
// A question without "?" still offers a place first when there is one.
const askFirst = first?.kind === 'ask' && !String(text).includes('?');
if (!first || (!askFirst && mayRunOnEnter(first, text, parsed, context)))
return items;
const place = items.findIndex((item) => item.kind === 'place');
if (place <= 0) return items;
return [items[place], ...items.slice(0, place), ...items.slice(place + 1)];
}
/** The row Enter runs before one is chosen with the keyboard, or -1. */
export function enterDefault(items, text, parsed, context) {
const line = String(text || '').trim();
if (!line || /^>\s*$/.test(line)) return -1;
return items.length && mayRunOnEnter(items[0], line, parsed, context)
? 0
: -1;
}
+713
View File
@@ -0,0 +1,713 @@
// "Show me how": a short guided walk through the real controls. Each step
// spotlights the control to press, explains it in one line, and waits until
// the visitor presses it (or the step is already done), then moves on. It
// does not press the controls the walk is about. A layer walk clears
// layer-list filter chips only when they would hide the row it is about;
// steps scroll their target into view.
//
// The callout is a non-modal dialog: focus moves to it when a walk starts,
// the rest of the page stays usable (the walk is about pressing it), Escape
// ends the walk and no other key is taken.
//
// Recipes are data: any data layer gets one from its id, and the main
// features (styles, HUD, compass, tilt, globe view, share, clear) have their
// own. The walk works the same for all of them.
import { t } from '../i18n/index.js';
import { EXCLUSIVE_SURFACE_CLASSES } from '../exclusiveSurfaces.js';
import { LABEL_LAYERS } from './contextLayerTabs.js';
const LEFT_RAIL = '.ui-rail--left .ui-rail__item';
const RIGHT_RAIL = '.ui-rail--right .ui-rail__item';
const MOBILE_PANELS = {
'data-panel': 'layers',
'pp-toggles': 'more',
'global-context-panel': 'context',
};
const SEARCH_BUTTON = '#layer-finder-search-btn';
const SEARCH_INPUT = '#layer-finder-input';
const FILTER_BUTTON = '#data-panel .layer-finder__filter button';
const AIRCRAFT_LAYERS = new Set(['flights', 'military', 'local-adsb']);
/** Above this altitude (metres) the camera already shows the globe. */
const GLOBE_ALTITUDE = 2_500_000;
/**
* Layers spread wider than a street-level view, and the camera altitude
* (metres) from which enough of them are in frame. Traffic layers spread over
* a region: aircraft cruise kilometres up across hundreds of kilometres, so
* from a low, tilted camera almost none are in view. Global layers read best
* from the globe view.
*/
const VIEW_ALTITUDE = Object.freeze({
flights: 150_000,
military: 400_000,
'local-adsb': 60_000,
'ais-live-vessels': 120_000,
satellites: GLOBE_ALTITUDE,
'rocket-launches': GLOBE_ALTITUDE,
'weather-cyclones': GLOBE_ALTITUDE,
'telegeography-submarine-cables': GLOBE_ALTITUDE,
earthquakes: GLOBE_ALTITUDE,
'local-firms': GLOBE_ALTITUDE,
'weather-satellite': GLOBE_ALTITUDE,
});
const $ = (selector, doc = globalThis.document) => doc?.querySelector(selector);
/** The camera altitude from the share hash, the app's own record of it. */
function cameraAltitude() {
const alt = Number(
new URLSearchParams(globalThis.location?.hash.slice(1) || '').get('alt'),
);
return Number.isFinite(alt) ? alt : 0;
}
const pressed = (selector) =>
$(selector)?.getAttribute('aria-pressed') === 'true';
const screenIsOwned = (doc) =>
EXCLUSIVE_SURFACE_CLASSES.some((name) => doc.body.classList.contains(name));
/** Steps that open a side panel from its rail, unless it is already open. */
function openPanelSteps(rail, item, label) {
const button = () =>
MOBILE_PANELS[item] &&
globalThis.document?.body.classList.contains('mobile-shell')
? $(`#mobile-tab-bar [data-mobile-sheet="${MOBILE_PANELS[item]}"]`)
: $(`${rail}[data-rail-item="${item}"]`);
return [
{
targets: () => [button()],
text: () => t('Open {panel}', { panel: label }),
done: () =>
button()?.getAttribute('aria-pressed') === 'true' ||
button()?.getAttribute('aria-expanded') === 'true',
},
];
}
/** Steps that open the Visual panel from the left rail. */
function openVisualSteps() {
return openPanelSteps(LEFT_RAIL, 'pp-toggles', t('Visual'));
}
/** Steps that bring up a section of Context's Properties tab. */
function propertiesSteps(section, text) {
const pane = `#context-tab-${section}`;
const tab = () => $('#context-tab-btn-props');
return [
...openPanelSteps(RIGHT_RAIL, 'global-context-panel', t('Context')),
{
targets: () => [tab()],
text: () => t('Open Properties: settings for the layers that are on'),
skip: () => !tab(),
done: () => tab()?.getAttribute('aria-selected') === 'true',
},
{
prepare: () => $(pane)?.scrollIntoView?.({ block: 'center' }),
targets: () => [$(pane)?.closest('.context-props__section') || $(pane)],
text,
skip: () => !$(pane)?.offsetParent,
},
];
}
const rowHidden = (selector) =>
Boolean($(selector)?.classList.contains('is-filtered'));
const hasSearchQuery = () => Boolean($(SEARCH_INPUT)?.value.trim());
/**
* The settings that change what a layer shows: its own option chips in the
* Data layers row, then, where they apply, the Display panel's detection
* labels and how dense they are.
* @param {{id: string, shown: string}} layer
*/
export function layerSettingsGuide(layer) {
const rowSelector = `[data-layer-id="${layer.id}"]`;
const controls = `${rowSelector} .data-toggle-controls`;
const chipNames = () =>
[...(globalThis.document?.querySelectorAll(`${controls} button`) || [])]
.map((chip) => {
const name = chip.textContent.trim();
const what = chip.getAttribute('title');
// The title as translated: lowering its first letter is wrong in
// German and other languages.
return what ? `${name}: ${what}` : name;
})
.filter(Boolean)
.join(' · ');
return [
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
{
prepare: () => $(rowSelector)?.scrollIntoView?.({ block: 'center' }),
targets: () => [$(controls)],
text: () =>
chipNames()
? t('{layer} options. {options}', {
layer: layer.shown,
options: chipNames(),
})
: t('{layer} options appear here once it has loaded.', {
layer: layer.shown,
}),
skip: () => !$(controls),
},
// Labels and 3D models now sit in Context's Properties while their
// layers are on.
...(LABEL_LAYERS.has(layer.id)
? propertiesSteps('labels', () =>
t(
'Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.',
{
layer: layer.shown,
},
),
)
: []),
...(AIRCRAFT_LAYERS.has(layer.id)
? propertiesSteps('aircraft', () =>
t(
'3D models: Proximity shows them up close only, All shows every aircraft as a model.',
),
)
: []),
];
}
/**
* The walk for one data layer.
* @param {{id: string, shown: string}} layer
* @param {(id: string) => boolean} isEnabled
* @param {{readAltitude?: () => number}} [options] Current camera altitude in metres.
*/
export function layerGuide(
layer,
isEnabled,
{ readAltitude = cameraAltitude } = {},
) {
const rowSelector = `[data-layer-id="${layer.id}"]`;
return [
// The walk asks for Data layers to be opened (or skips that when it is
// open); it closes no panel the visitor has open.
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
{
// A filter left on from before could hide the row; start from the full list.
prepare: () => {
if (rowHidden(rowSelector) && !hasSearchQuery()) {
for (const chip of globalThis.document.querySelectorAll(
'#data-panel .layer-finder__chip',
))
chip.click();
}
},
targets: () => [$(SEARCH_BUTTON)],
text: () =>
t('Press search to find {layer} in the list', { layer: layer.shown }),
skip: () => isEnabled(layer.id) || !$(SEARCH_BUTTON),
done: () => pressed(SEARCH_BUTTON),
},
{
targets: () => [$(SEARCH_INPUT)],
text: () => t('Type {layer}', { layer: layer.shown }),
skip: () => isEnabled(layer.id) || !$(SEARCH_INPUT),
done: () => hasSearchQuery() && !rowHidden(rowSelector),
},
{
prepare: () => $(rowSelector)?.scrollIntoView?.({ block: 'center' }),
targets: () => [$(rowSelector), $(`${rowSelector} .data-toggle-btn`)],
text: () => t('Turn on {layer} with its switch', { layer: layer.shown }),
skip: () => isEnabled(layer.id),
done: () => isEnabled(layer.id),
},
{
// Too close to see them: zoom out (any way) or press the globe view.
targets: () => [$('#reset-globe-view')],
text: () =>
VIEW_ALTITUDE[layer.id] >= GLOBE_ALTITUDE
? t('{layer} are easiest to see from the globe view', {
layer: layer.shown,
})
: t(
'{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.',
{
layer: layer.shown,
},
),
skip: () =>
!VIEW_ALTITUDE[layer.id] || readAltitude() >= VIEW_ALTITUDE[layer.id],
done: () => readAltitude() >= VIEW_ALTITUDE[layer.id],
},
{
// The end: offer the settings that shape this layer.
text: () =>
t('{layer} is on. Want to fine-tune what it shows?', {
layer: layer.shown,
}),
offer: {
label: () => t('Show settings'),
steps: () => layerSettingsGuide(layer),
},
},
];
}
/** Walks for features, keyed like the omnibar's commands. */
export const FEATURE_GUIDES = Object.freeze({
styles: () => [
...openVisualSteps(),
{
prepare: () =>
$('.visual-presets__grid')?.scrollIntoView?.({ block: 'center' }),
targets: () => [$('.visual-presets__grid')],
text: () =>
t('Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)'),
},
],
'map-source': () => [
...openVisualSteps(),
{
prepare: () =>
$('#pp-toggles .visual-presets')?.scrollIntoView?.({ block: 'start' }),
targets: () => [$('#pp-toggles .visual-presets')],
text: () =>
t(
'Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap',
),
},
],
hud: () => [
...openVisualSteps(),
{
prepare: () => $('#hud-toggle')?.scrollIntoView?.({ block: 'center' }),
targets: () => [$('#hud-toggle')],
text: () =>
t(
'Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber',
),
},
],
scope: () => [
...openVisualSteps(),
{
prepare: () => $('#scope-toggle')?.scrollIntoView?.({ block: 'center' }),
targets: () => [$('#scope-toggle')?.closest('.pp-toggle-group')],
text: () =>
t(
'Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.',
),
},
],
clean: () => [
...openVisualSteps(),
{
prepare: () =>
$('#clean-view-toggle')?.scrollIntoView?.({ block: 'center' }),
targets: () => [$('#clean-view-toggle')],
text: () => t('Clean UI hides the panels and readouts for a clear view'),
},
],
'find-layer': () => [
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
{
targets: () => [$(SEARCH_BUTTON)],
text: () => t('Press search, then type part of a layer name or source'),
done: () => pressed(SEARCH_BUTTON),
},
{
targets: () => [$(SEARCH_INPUT)],
text: () => t('Type to narrow the list; Esc clears it'),
done: hasSearchQuery,
},
{
targets: () => [$(FILTER_BUTTON)],
text: () =>
t('Filter shows only layers that are on or off, or one category'),
},
],
'filter-layers': () => [
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
{
targets: () => [$(FILTER_BUTTON)],
text: () => t('Open the filter'),
done: () => $(FILTER_BUTTON)?.getAttribute('aria-expanded') === 'true',
},
{
targets: () => [$('.layer-finder__menu')],
text: () =>
t(
'Pick a status (On, Off) and a category; each shows as a chip you can clear',
),
},
],
'section-index': () => [
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
{
targets: () => [$('.layer-section-index')],
text: () => t('Hover a tick to see its group; click to jump there'),
},
],
preferences: () => [
{
targets: () => [$('#corner-actions')],
text: () => t('Add provider keys with Power Up, or change the language'),
},
],
edge: () => [
...openPanelSteps(LEFT_RAIL, 'data-panel', t('Data layers')),
{
targets: () => [$('#data-panel .ui-panel-edge')],
text: () =>
t(
'Press this to slide panels over the rail to the screen edge; press again to bring them back',
),
},
],
context: () => [
...openPanelSteps(RIGHT_RAIL, 'global-context-panel', t('Context')),
{
targets: () => [$('#global-context-panel .cyber-panel-body')],
text: () =>
t(
'Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map',
),
},
],
properties: () =>
propertiesSteps('labels', () =>
t(
'Properties holds the settings for the layers that are on, each layer marked by a coloured dot',
),
),
north: () => [
{
targets: () => [$('#north-up-view')],
text: () => t('Press the compass to face north'),
},
],
tilt: () => [
{
targets: () => [$('#tilt-map-view')],
text: () => t('Tilt the camera for a 3D view'),
},
],
globe: () => [
{
targets: () => [$('#reset-globe-view')],
text: () => t('Zoom out to the whole globe'),
},
],
share: () => [
{
targets: () => [$('#share-btn')],
text: () => t('Copy a link to exactly this view'),
},
],
clear: () => [
{
targets: () => [$('#clear-selected-layers')],
text: () => t('Turn off every layer at once'),
},
],
// Drawing, and measuring with it: a line shows its length and an area its
// size while it is drawn (src/annotations/drawMode.js).
draw: () => [
...openPanelSteps(LEFT_RAIL, 'utilities-panel', t('Utilities')),
{
prepare: () => $('#draw-group')?.scrollIntoView?.({ block: 'center' }),
targets: () => [$('#draw-toggle')],
text: () => t('Press Draw to start drawing on the map'),
skip: () => pressed('#draw-toggle'),
done: () => pressed('#draw-toggle'),
},
{
targets: () => [$('#draw-mode-row')],
text: () =>
t(
'Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes',
),
},
],
});
/** The omnibar command ids that have a feature walk. */
export function featureGuideFor(commandId) {
if (commandId.startsWith('style-')) return 'styles';
if (commandId.startsWith('map-')) return 'map-source';
if (commandId.startsWith('hud-')) return 'hud';
if (commandId === 'reset') return 'globe';
return FEATURE_GUIDES[commandId] ? commandId : null;
}
let active = null;
/**
* Run a walk. Starting another ends the one in progress.
* @param {Array<object>} steps
* @param {{title?: string}} [options]
*/
export function startGuide(steps, { title = '' } = {}) {
active?.stop();
const doc = globalThis.document;
if (!doc?.body || screenIsOwned(doc) || !steps?.length) return;
const root = doc.createElement('div');
root.className = 'gev-guide';
root.innerHTML =
'<div class="gev-guide-ring"><i></i></div>' +
'<div class="gev-guide-callout" role="dialog" aria-modal="false" tabindex="-1" aria-labelledby="gev-guide-title" aria-describedby="gev-guide-text">' +
'<div class="gev-guide-head"><p id="gev-guide-title" class="gev-guide-title"></p>' +
'<p class="gev-guide-count"></p>' +
'<button type="button" class="gev-guide-close"><span aria-hidden="true">×</span></button></div>' +
'<ol class="gev-guide-progress" aria-hidden="true"></ol>' +
'<div class="gev-guide-body"><p id="gev-guide-text" class="gev-guide-text"></p>' +
'<p class="gev-guide-hint"><span class="gev-guide-hint-dot"></span><span></span></p></div>' +
'<div class="gev-guide-actions"><p class="gev-guide-keys"><kbd></kbd><span></span></p>' +
'<span><button type="button" class="gev-guide-skip" hidden></button>' +
'<button type="button" class="gev-guide-offer" hidden></button>' +
'<button type="button" class="gev-guide-next"></button></span></div>' +
// Announces each step once; the dialog itself is not a live region, so
// its buttons and progress are not read out on every change.
'<p class="gev-guide-status" role="status" aria-live="polite"></p></div>';
// Focus returns where it was when the walk ends, if that is still there.
const returnFocus = doc.activeElement;
doc.body.append(root);
const ring = root.querySelector('.gev-guide-ring');
const callout = root.querySelector('.gev-guide-callout');
const subRings = [];
const endLabel = t('End guide');
root.querySelector('.gev-guide-close').setAttribute('aria-label', endLabel);
root.querySelector('.gev-guide-close').title = endLabel;
// i18n-ignore: the Escape keycap, matching the keyboard shortcut.
root.querySelector('.gev-guide-keys kbd').textContent = 'Esc';
root.querySelector('.gev-guide-keys span').textContent = t('to end');
root.querySelector('.gev-guide-title').textContent = title
? t('Guide · {topic}', { topic: title })
: t('Guide');
root.querySelector('.gev-guide-next').textContent = t('Next');
root.querySelector('.gev-guide-hint span:last-child').textContent = t(
'Press the highlighted control',
);
const live = steps.filter(Boolean);
let index = -1;
let frame = 0;
let advanceTimer = 0;
let stopped = false;
let current = null;
let shown = 0;
const stop = () => {
if (stopped) return;
stopped = true;
cancelAnimationFrame(frame);
clearInterval(poll);
clearTimeout(advanceTimer);
resizeObserver?.disconnect();
globalThis.removeEventListener?.('resize', schedule);
doc.removeEventListener('scroll', schedule, true);
doc.removeEventListener('click', onClick, true);
doc.removeEventListener('keydown', onKey, true);
const hadFocus = root.contains(doc.activeElement);
root.remove();
if (hadFocus && returnFocus?.isConnected) returnFocus.focus?.();
if (active?.stop === stop) active = null;
};
const next = () => {
clearTimeout(advanceTimer);
advanceTimer = 0;
void run(index + 1);
};
const advance = () => {
if (advanceTimer) return;
advanceTimer = setTimeout(next, 350);
};
async function run(at) {
if (stopped) return;
if (screenIsOwned(doc)) return stop();
current = null;
index = at;
const step = live[index];
if (!step) return stop();
await step.prepare?.();
if (stopped || at !== index) return;
if (step.skip?.() || step.done?.()) return run(index + 1);
current = step;
shown += 1;
// The total is what is shown so far plus the steps still to come that
// would not be skipped as things stand.
const total =
shown + live.slice(index + 1).filter((later) => !later.skip?.()).length;
root.querySelector('.gev-guide-count').textContent = `${shown} / ${total}`;
const progress = root.querySelector('.gev-guide-progress');
progress.replaceChildren(
...Array.from({ length: total }, (_, i) => {
const dot = doc.createElement('li');
if (i < shown - 1) dot.className = 'done';
if (i === shown - 1) dot.className = 'current';
return dot;
}),
);
const text = step.text();
root.querySelector('.gev-guide-text').textContent = text;
root.querySelector('.gev-guide-status').textContent =
`${shown} / ${total}: ${text}`;
// Steps that point at a control wait for it to be pressed; say so.
const waits = Boolean(step.targets) && !step.offer;
root.querySelector('.gev-guide-hint').hidden = !waits;
const offer = root.querySelector('.gev-guide-offer');
const skip = root.querySelector('.gev-guide-skip');
offer.hidden = !step.offer;
skip.hidden = !step.offer;
root.querySelector('.gev-guide-keys').hidden = Boolean(step.offer);
if (step.offer) {
offer.textContent = step.offer.label();
skip.textContent = t('Not now');
}
const last = index === live.length - 1;
const nextButton = root.querySelector('.gev-guide-next');
nextButton.hidden = Boolean(step.offer);
nextButton.textContent = last
? t('Finish')
: waits
? t('Skip step')
: t('Next');
nextButton.classList.toggle('quiet', waits && !last);
// Replay the entrance so each step reads as new.
callout.classList.remove('swap');
void callout.offsetWidth;
callout.classList.add('swap');
root.classList.add('visible');
schedule();
}
// The visitor pressed the spotlit control: give the app a moment to react,
// then move on (or let `done` decide, for steps that wait on a state).
function onClick(event) {
if (!current || callout.contains(event.target)) return;
const [target] = current.targets?.() || [];
if (target?.contains(event.target) && !current.done) advance();
}
// Only Escape is the walk's: it ends the walk and nothing else (the
// Omnibar or a panel behind it stays as it is). Every other key goes on to
// the page untouched.
function onKey(event) {
if (screenIsOwned(doc)) {
stop();
return;
}
if (event.key !== 'Escape' || event.isComposing) return;
event.preventDefault();
event.stopPropagation();
stop();
}
root.querySelector('.gev-guide-skip').addEventListener('click', stop);
root.querySelector('.gev-guide-close').addEventListener('click', stop);
root.querySelector('.gev-guide-next').addEventListener('click', () => {
if (current) next();
});
// Taking the offer carries the walk on with its steps.
root.querySelector('.gev-guide-offer').addEventListener('click', () => {
if (!current?.offer) return;
const extra = current.offer.steps() || [];
live.splice(index + 1, live.length, ...extra.filter(Boolean));
next();
});
doc.addEventListener('click', onClick, true);
doc.addEventListener('keydown', onKey, true);
// Follow the targets as panels open and scroll, and notice when a step's
// goal is reached however it happened: on resize and scroll, when the page
// changes size, and otherwise four times a second (panels slide open
// without an event to follow). Each is at most one frame's work.
let poll = 0;
let resizeObserver = null;
function schedule() {
if (stopped || frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
place();
});
}
const place = () => {
if (screenIsOwned(doc)) return stop();
if (!current) return;
if (current.done?.()) advance();
const targets = (current.targets?.() || []).filter(Boolean);
const [main, ...rest] = targets.map((element) =>
element.getBoundingClientRect(),
);
if (!main || !main.width) {
// Nothing to point at (the closing offer): centre the callout.
ring.style.opacity = '0';
subRings.forEach((sub) => (sub.style.opacity = '0'));
callout.dataset.side = 'none';
callout.style.left = `${(innerWidth - (callout.offsetWidth || 280)) / 2}px`;
callout.style.top = `${innerHeight * 0.32}px`;
return;
}
const pad = 6;
Object.assign(ring.style, {
opacity: '1',
left: `${main.left - pad}px`,
top: `${main.top - pad}px`,
width: `${main.width + pad * 2}px`,
height: `${main.height + pad * 2}px`,
});
while (subRings.length < rest.length) {
const sub = doc.createElement('div');
sub.className = 'gev-guide-ring gev-guide-ring--sub';
root.append(sub);
subRings.push(sub);
}
subRings.forEach((sub, i) => {
const box = rest[i];
Object.assign(
sub.style,
box?.width
? {
opacity: '1',
left: `${box.left - 4}px`,
top: `${box.top - 4}px`,
width: `${box.width + 8}px`,
height: `${box.height + 8}px`,
}
: { opacity: '0' },
);
});
// The callout sits beside the target, on whichever side has room.
const width = callout.offsetWidth || 280;
const height = callout.offsetHeight || 120;
const gap = 18;
const right = main.right + pad + gap;
const onRight = right + width < innerWidth - 12;
const left = onRight ? right : Math.max(12, main.left - pad - gap - width);
const centre = main.top + main.height / 2;
const top = Math.max(
12,
Math.min(innerHeight - height - 12, centre - height / 2),
);
// The arrow points at the target's middle, kept inside the callout.
callout.dataset.side = onRight ? 'right' : 'left';
callout.style.setProperty(
'--gev-guide-arrow-y',
`${Math.min(height - 18, Math.max(18, centre - top))}px`,
);
callout.style.left = `${left}px`;
callout.style.top = `${top}px`;
};
globalThis.addEventListener?.('resize', schedule);
doc.addEventListener('scroll', schedule, true);
if (typeof ResizeObserver === 'function') {
resizeObserver = new ResizeObserver(schedule);
resizeObserver.observe(doc.body);
}
// A hidden tab has nothing to follow: the poll rests until it is shown.
poll = setInterval(() => {
if (!doc.hidden) schedule();
}, 250);
schedule();
callout.focus({ preventScroll: true });
active = { stop };
void run(0);
return stop;
}
+876
View File
@@ -0,0 +1,876 @@
// What a line typed into the omnibar asks for. A line is split into clauses
// ("noir and cctv near austin, north up"); each clause can name a place,
// layers to show or hide, a visual style, the HUD, a map stack, a camera move,
// radio, the cockpit, the nearest aircraft or something to follow. What is
// left of a clause after those are read is taken as a place.
//
// The result is a plan of steps in the order they should run: the camera
// travels first, so layers and radio load for the new view, and following an
// entity comes last.
import { msg } from '../i18n/index.js';
/** Visual styles, by the words people use for them. */
const STYLES = [
[/\bblack[- ]and[- ]white\b|\bnoir\b/, 'noir'],
[/\b(thermal|flir|heat ?map|infra-?red)\b/, 'thermal'],
[/\b(night ?vision|nvg|surveillance)\b/, 'surveillance'],
[/\b(retro|crt)\b/, 'retro'],
[/\banime\b/, 'anime'],
[/\b(normal|default|plain) (style|view|look|colou?rs?)\b/, 'normal'],
];
/** Map stacks. */
const STACKS = [
[/\b(osm|openstreetmap|street map)\b/, 'osm'],
[/\bbing( aerial)?\b/, 'bing-aerial'],
[/\b(photo ?real(istic)?|3d tiles)\b/, 'photoreal'],
[/\b(esri|satellite imagery)\b/, 'esri-imagery'],
];
/**
* Whole-map clears: "turn off all layers", "hide everything", "remove
* everything" all clear the layers.
*/
const CLEAR_ALL =
/^(?:(?:(?:turn|switch) off|hide|clear|remove|disable|kill) (?:everything|(?:all|every)(?: the)?(?: data)?(?: layers?)?)|clear (?:the )?(?:layers|map)|no layers)$/;
/** Camera moves, as globe actions or runner actions. */
const CAMERA = [
// Whole-map commands come first, so "turn off all layers" is never a place.
[CLEAR_ALL, { act: 'clear' }],
[
/\b(share|copy)( this| the)? (view|link|map|url)\b|^share$/,
{ act: 'share' },
],
[/\breset( the)? (view|camera)\b|\bstart over\b|^home$/, { act: 'reset' }],
[/\bnorth[- ]?up\b|\bface north\b/, { act: 'northUp' }],
[/\b(tilt|3d view|perspective)\b/, { act: 'tilt' }],
[
/\b(globe view|whole (globe|earth|world)|reset (the )?globe)\b/,
{ name: 'zoom_to_globe', args: {} },
],
[/\bzoom in\b/, { name: 'adjust_camera_zoom', args: { direction: 'in' } }],
[/\bzoom out\b/, { name: 'adjust_camera_zoom', args: { direction: 'out' } }],
[
/\bstop (the )?(camera|orbit|moving|rotating)\b/,
{ name: 'move_camera', args: { motion: 'stop' } },
],
[
/\borbit\b/,
{
name: 'move_camera',
args: { motion: 'orbit', mode: 'continuous' },
},
],
];
/** Side panels by name, with the rail and rail item that open them. */
const PANEL_NAMES = [
[
/data ?layers?( panel)?|layers panel/,
'left',
'data-panel',
msg('Data layers'),
],
[
/utilities( panel)?|tools panel/,
'left',
'utilities-panel',
msg('Utilities'),
],
[/authoring( panel)?|scenes? panel/, 'left', 'scene-panel', msg('Authoring')],
[/display( panel)?|visual( panel)?/, 'left', 'pp-toggles', msg('Visual')],
[/cctv panel|cameras? panel/, 'right', 'cctv-panel', msg('CCTV')],
[/street ?level panel/, 'right', 'street-level-panel', msg('Street Level')],
[/context( panel)?/, 'right', 'global-context-panel', msg('Context')],
];
const CLOSE = /\b(collapse|close|hide|minimi[sz]e|dismiss|shut|fold)\b/;
const OPEN = /\b(open|expand|show|reveal)\b/;
/** Words that may sit around a panel's name without naming anything else. */
const PANEL_FILLER =
/\b(open|expand|show|reveal|collapse|close|hide|minimi[sz]e|dismiss|shut|fold|please|the|me|my|a|panel|sidebar|tab)\b/g;
/** Whether the clause names this panel and nothing besides it. */
const onlyNames = (clause, pattern) =>
!tidy(clause.replace(pattern, ' ').replace(PANEL_FILLER, ' '));
/** A clause about side panels, or null. */
function panelStep(clause) {
// "hide everything" clears the layers, as "remove everything" does.
if (CLEAR_ALL.test(clause)) return null;
if (CLOSE.test(clause)) {
if (
/\b(all|every|both)\b.*\b(panels?|sidebars?)\b|\b(panels|sidebars)\b/.test(
clause,
) ||
// "close everything" alone; "hide everything near tokyo" clears.
(/\beverything\b/.test(clause) && onlyNames(clause, /\beverything\b/))
)
return { kind: 'panel', action: 'close', side: 'all' };
if (/\bleft\b/.test(clause))
return { kind: 'panel', action: 'close', side: 'left' };
if (/\bright\b/.test(clause))
return { kind: 'panel', action: 'close', side: 'right' };
for (const [pattern, side, item, name] of PANEL_NAMES)
if (pattern.test(clause) && /panel/.test(clause))
return { kind: 'panel', action: 'close', side, item, name };
}
// "open data layers" opens the panel; "show earthquake data layer" names
// a layer, so a name with anything else beside it is not the panel.
if (OPEN.test(clause))
for (const [pattern, side, item, name] of PANEL_NAMES)
if (pattern.test(clause) && onlyNames(clause, pattern))
return { kind: 'panel', action: 'open', side, item, name };
return null;
}
/**
* Whether a line clears the whole map ("hide everything", "clear the map",
* "hide everything near tokyo"), so layer switches leave it to the plan.
*/
export function isWholeMapClear(text) {
const line = tidy(String(text || '').toLowerCase());
const near = line.match(NEAR);
return (
CLEAR_ALL.test(line) ||
Boolean(near && CLEAR_ALL.test(tidy(line.slice(0, near.index))))
);
}
/** Whether a line is about side panels, so layer switches leave it alone. */
export const isPanelText = (text) =>
Boolean(
panelStep(
String(text || '')
.toLowerCase()
.trim(),
),
);
const LAYER_OFF = /^(hide|turn off|switch off|disable|remove|no)\s+/;
const LAYER_ON = /^(show|turn on|switch on|enable|add|display)\s+(me\s+)?/;
// "go to" with the place after it, or alone at the end of the line.
// "goto" counts only with a place after it: "Goto" is a town in Japan.
const GO =
/^(?:(?:go to|fly to|take me to|zoom to|jump to|head to)(?:\s+|$)|goto\s+)/i;
const FOLLOW = /^(follow|track)\s+(.+)$/;
/**
* Something that can be followed: a callsign or ICAO address (a word or two
* with letters and a digit: "ual123", "a12b2e", "UAL 123"), a nine-digit
* MMSI, or the name of something loaded on the map. "Follow Me Bar", "Track
* Hill" and "Track 29" are places.
*/
const FOLLOWABLE = /^(?:the\s+)?(?:(?=.*\d)(?=.*\p{L})\S+(?:\s+\S+)?|\d{9})$/u;
/** "nearest plane to heathrow" as well as "near", "in" and the rest. */
const NEAR_TO = /\s*\b(?:near|in|at|around|over|across|above|of|to)\s+(.+)$/;
const NEAR = /\s*\b(?:near|in|at|around|over|across|above|of)\s+(.+)$/;
/** The words of NEAR that place a request somewhere (not "of" or "at"). */
const AROUND = /^\s*(?:near|in|around|over|across|above)\b/;
const FILLER =
/\b(please|the|a|an|me|on|mode|style|view|look|layer|layers|map|data|live)\b/g;
/**
* A question's form: a question word followed by an auxiliary or another
* question word ("what is", "how far", "where's"), or an auxiliary followed
* by a pronoun or determiner ("is it raining", "can you show"): "Can Tho
* City" and "Is Kinabalu Park" are places.
*/
const WH_FORM =
/^(?:what|where|when|who|why|how|which)(?:'s\b|\s+(?:is|are|was|were|do|does|did|can|could|should|would|will|many|much|far|long|to)\b)/i;
const AUX_FORM =
/^(?:is|are|was|were|do|does|did|can|could|should|would|will)\s+(?:it|there|you|i|we|they|he|she|the|a|an|this|that|my|your|our|any)\b/i;
/**
* Whether a line is a real question, which Ask GEV may answer on Enter (a
* billed call):
* - one ending with "?" that has two words and two letters or more (or
* three Han, Kana or Hangul characters);
* - without "?", only a question word's form ("what is here", "how far is
* paris") with a word about something after it, and not written as a
* name ("Where Is My Mind").
* An auxiliary's form without "?" is never one: "Can You Imagine", "Do it
* Best Hardware" and "Is This It" are names. A line with a comma and no "?"
* is a place ("Why, Arizona"). Read the line after normalizeLine, in its own
* letter case.
* @param {string} text
*/
/** Greetings shaped like questions ("what's up", "how's it going"). */
const SMALL_TALK =
/^(?:what'?s\s+(?:up|new|good|happening|going on|cooking)|how'?s\s+(?:it going|everything|life|things|your day)|how are (?:you|things)|what are you (?:up to|doing))\b/i;
export function isRealQuestion(text) {
// Full-width and Arabic question marks read as "?".
const line = String(text || '')
.trim()
.replace(/[?؟]/g, '?');
if (SMALL_TALK.test(line)) return false;
const words = line.replace(/\?+$/, '').split(/\s+/).filter(Boolean);
if (line.endsWith('?'))
// A name with "?" ("New York?", "Truth or Consequences?", "東京都?") is
// offered to GEV, not sent: a question's form, or four words or more
// (five Han, Kana or Hangul characters, written without spaces; two
// words in other non-Latin scripts).
return (
((WH_FORM.test(line) ||
AUX_FORM.test(line) ||
words.length >= 4 ||
// Question words in other scripts are not read: two words do.
(words.length >= 2 && !/\p{Script=Latin}/u.test(line))) &&
words.some((word) => (word.match(/\p{L}/gu) || []).length >= 2)) ||
(
line.match(
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu,
) || []
).length >= 5
);
if (line.includes(',')) return false;
// The form alone is too little ("how to", "who is it"): a word about
// something must follow ("what is here").
return (
WH_FORM.test(line) &&
words.some(
(word) => !FORM_WORDS.has(word.toLowerCase().replace(/'s$/, '')),
) &&
!writtenAsName(words)
);
}
/** Three words or more, each with a capital first letter: a title or a name. */
export const writtenAsName = (words) =>
words.length >= 3 &&
words.every((word) => !/\p{L}/u.test(word) || /^\p{Lu}/u.test(word));
/**
* An auxiliary's question without "?" ("can you show me", "is it raining
* in tokyo"): Ask GEV is offered first but never runs on Enter. Written with
* a capital after its first two words it is a name ("Can You Imagine", "Do
* it Best Hardware"), and the form alone ("Is there", "Can I") says nothing.
*/
function isUnmarkedQuestion(text) {
const line = String(text || '').trim();
const words = line.split(/\s+/).filter(Boolean);
return (
AUX_FORM.test(line) &&
!line.includes(',') &&
words.some((word) => !FORM_WORDS.has(word.toLowerCase())) &&
!words.slice(2).some((word) => /^\p{Lu}/u.test(word))
);
}
/** The words a question's form is made of, which say nothing on their own. */
const FORM_WORDS = new Set(
'what where when who why how which is are was were do does did can could should would will many much far long to it there you i we they he she the a an this that my your our any'.split(
' ',
),
);
/**
* A typed line as the Omnibar reads it, the one normalisation every reader
* shares: compatibility forms folded (full-width letters and "?"), curly
* apostrophes and quotes made straight, spaces collapsed, a "please" before
* or after the request dropped, and a closing full stop or "!" dropped (not
* an initial's: "Washington D.C."). Letter case is kept.
* @param {string} text
*/
export function normalizeLine(text, { isRequest = isPlainRequest } = {}) {
let line = String(text ?? '')
.normalize('NFKC')
.replace(/[\u2018\u2019\u201A\u201B\u2032\u02BC]/g, "'")
.replace(/[\u201C\u201D\u201E\u201F\u2033]/g, '"')
.replace(/؟/g, '?')
.replace(/\s+/g, ' ')
.trim();
const end = /(?<!(?:^|[\s.])\p{L})[.!。]+$/u;
line = line.replace(end, '');
// "please" is dropped only around a request: "Please Touch Museum",
// "Kindly Lane" and "Pretty Please" are names.
const polite = line
.replace(/^(?:please|pls|plz|kindly)\b[,!]?\s+(?=\S)/i, '')
.replace(/(?:\s*,\s*|\s+)(?:please|pls|plz)$/i, '')
.replace(end, '')
.trim();
return polite !== line && polite && isRequest(polite) ? polite : line;
}
/** A request by its own words: a verb starting it, or a real question. */
const isPlainRequest = (text) => hasActionVerb(text) || isRealQuestion(text);
/**
* Whether a clause starts with an action verb, in any letter case: the one
* test the parser and the Enter rule share.
*/
export function hasActionVerb(text) {
return ACTION_VERB.test(tidy(String(text || '').toLowerCase()));
}
/**
* The verbs that make a clause a request, the one list for the parser and
* for what Enter may run (src/ui/omnibarEnter.js). A verb counts where the
* clause starts ("show flights", "turn radio on"; "radio off" ends one), so
* a place named after it never does ("radio near Clear Lake", "radio in
* Show Low"). Words that also start names count only alone or before what
* they act on: "clear the map", "zoom in", "tilt", "orbit", "stop the
* radio", not "Clear Lake", "Zoom Hill", "Tilt Cove" or "Stop, Arkansas".
* A keyword in a clause without a verb may be part of a name, and a verb
* ends at a space or the line's end ("Hide-A-Way Lake" names a lake).
*/
export const ACTION_VERB =
/^(?:please\s+|now\s+|also\s+)?(?:show|hide|turn|switch|toggle|enable|disable|add|remove|display(?=\s+\S)|play|start|close|open|enter|listen|tune|mute|unmute|follow|track|draw|measure|share|copy|reset|kill(?=\s+(?:the\s+)?(?:radio|music|sound)\b)|silence|pause|face(?=\s+(?:north|south|east|west)\b)|go to|fly to|take me to|head to|jump to|goto|(?:find |select )?nearest|zoom(?=$|\s+(?:in|out|to)\b)|tilt(?=$|\s+(?:the\s+)?(?:camera|view|map|up|down)\b)|orbit(?=$|\s+(?:the\s+)?(?:camera|view|map|it|here|around)\b)|stop(?=$|\s+(?:the\s+)?(?:radio|camera|orbit|orbiting|moving|rotating|music|following)\b)|clear(?=$|\s+(?:the\s+)?(?:map|layers?|everything|all|it)\b))(?=\s|$)|^\S+\s+(?:on|off)$/;
/**
* The cockpit only with a verb, and only as the end of its clause ("enter
* the cockpit", "open cockpit view"): "Cockpit Country" is a place.
*/
const COCKPIT =
/\b(?:enter|open|go into|get in(?:to)?|switch to|show)\s+(?:the\s+)?cockpit(?:\s+(?:view|mode))?$/;
/**
* The radio only with a verb that applies to it: "play radio in Kill Devil
* Hills" turns it on, "Radio City Music Hall" is a place.
*/
const RADIO_ON =
/\b(?:(?:turn|switch) on|play|listen to|tune in(?: to)?|open|start|put on|enable|unmute)\s+(?:the\s+)?radio(?:\s+stations?)?\b|\b(?:turn|switch)\s+(?:the\s+)?radio\s+on\b|\bradio\s+on\b/;
const RADIO_OFF =
/\b(?:(?:turn|switch) off|stop|mute|disable|silence|pause|kill)\s+(?:the\s+)?radio\b|\b(?:turn|switch)\s+(?:the\s+)?radio\s+off\b|\bradio\s+off\b/;
/** Lines this long are not split into a layer and a place word by word. */
const MAX_PAIR_WORDS = 6;
/**
* A place's name has six words at most; an address with a number in it
* ("1600 Pennsylvania Ave NW Washington DC 20500") ten.
*/
export const placeWordLimit = (text) => (/\d/.test(text) ? 10 : 6);
/** Lines longer than this that ask for nothing outright are sentences. */
const MAX_SENTENCE_WORDS = 8;
/** A clause that is only a switch verb, once what it switched is read. */
const SWITCH_ONLY =
/^(?:(?:turn|switch) (?:on|off)|show|hide|enable|disable|remove|add|display|no)?$/;
/** Words beside a layer that say more about it, never a place. */
const NOT_A_PLACE =
/^(?:stations?|feeds?|data|layers?|live|now|here|map|overlay|tracker|tracking|updates?|info|status|positions?|activity|today|tonight)$/;
/** A camera move turned off: orbiting stops; clearing stays a clear. */
const cameraOff = (move) =>
move.act === 'clear'
? move
: move.name === 'move_camera' && move.args.motion === 'orbit'
? { name: 'move_camera', args: { motion: 'stop' } }
: null;
/**
* The end of a "go to" clause that is a request, not part of the name: "in
* noir", "with flights", "at night vision", "show flights".
*/
const GO_TAIL =
/^(.+?)\s+(?:(?:in|with|at)\s+|(show|hide|turn on|turn off|switch on|switch off|enable|disable)\s+)(.+)$/;
/** Clause separators; "black and white" is joined first so it survives. */
const SEPARATORS =
/(\s*(?:,|;|\+|&|\band then\b|\bthen\b|\band\b|\balso\b)\s*)/;
function tidy(text) {
return text.replace(/\s+/g, ' ').trim();
}
/** A place without the joining words a removed phrase left at its edges. */
const placeName = (text) => {
const name = tidy(text)
.replace(/^((in|at|near|over|on|of|to|with|and|the)\s+)+/, '')
.replace(/(\s+(in|at|near|over|on|of|to|with|and|the))+$/, '')
.trim();
// A joining word left on its own ("flights in") names no place.
return JOINING.test(name) ? '' : name;
};
const JOINING = /^(in|at|near|over|on|of|to|with|and|the)$/;
/**
* Take the first pattern that matches out of the clause.
* @returns {{value: *, rest: string}|null}
*/
function takeFirst(clause, table) {
for (const [pattern, value] of table) {
const match = clause.match(pattern);
// A whole word only, in any script: "bing" is no part of "Bingöl".
const before = match && clause[match.index - 1];
const after = match && clause[match.index + match[0].length];
if (match && (/\p{L}/u.test(before || '') || /\p{L}/u.test(after || '')))
continue;
if (match)
return {
value,
rest: tidy(clause.replace(match[0], ' ')),
text: match[0],
};
}
return null;
}
/**
* Read one line into a plan.
* @param {string} text What was typed.
* @param {(term: string) => Array<{id: string, shown: string, enabled: boolean, score: number}>} matchLayers
* @returns {{steps: Array<object>, question: boolean}}
*/
export function parseOmnibar(
text,
matchLayers,
{ isEntity = () => false } = {},
) {
const raw = String(text || '').trim();
const line = tidy(raw.toLowerCase()).replace(
/\b(black[- ]and[- ]white|b ?& ?w)\b/g,
'noir',
);
// `asks`: a real question, which Ask GEV may answer by default. Small talk
// ("hi", "help") also goes to GEV, but only when picked.
// A comma line without "?" is a place ("Why, Arizona"), not a question.
// Only a real question is read as one; any other line ("why", "help",
// "what cheer", "List") may still be a place, with Ask GEV offered after.
const asks = isRealQuestion(raw);
// A line ending in "?" is for GEV even when too short to ask by default.
const question = asks || /[??؟]$/.test(line) || isUnmarkedQuestion(raw);
if (!line || question) return { steps: [], question, asks, asked: new Set() };
const steps = [];
// The steps whose own clause asked for them with a verb, and the clause
// each step came from.
const asked = new Set();
const clauseOf = new Map();
// The clauses with a name left beside their keywords.
const placeClauses = new Set();
let place = null;
const clauses = line.split(SEPARATORS);
// Keyword steps read from a clause without a verb, and whether the place
// is what was left beside them: together they make the line ambiguous.
const bareSteps = new Set();
let placeBare = false;
// Further places joined with "and" ("near New York and Paris"): the plan
// goes to the first, and the rest are offered on their own.
const extraPlaces = [];
let previousHadPlace = false;
let previousBarePlace = false;
let previousGo = false;
// Whether a request was peeled off a "go to" clause, and how the place
// was named: after "go to", after "near"/"in", or bare.
let goPeeled = false;
let placeFrom = null;
/** A whole clause that is one style, map, camera move or layer, or null. */
const requestIn = (text) => {
const words = tidy(text.replace(/\b(mode|style|view|look)\b/g, ' '));
for (const table of [STYLES, STACKS, CAMERA]) {
const found = takeFirst(words, table);
if (found && !found.rest) {
if (table === STYLES) return { kind: 'style', style: found.value };
if (table === STACKS) return { kind: 'stack', stack: found.value };
return { kind: 'camera', ...found.value };
}
}
return layerRequest(words);
};
/** A layer named in full, switched on unless the verb says off. */
const layerRequest = (text, verb = '') => {
const [layer] = matchLayers(tidy(text.replace(FILLER, ' ')));
if (!named(layer)) return null;
return {
kind: 'layer',
layer,
enabled: !/^(hide|turn off|switch off|disable)$/.test(verb),
};
};
let previousLayerEnabled = null;
// Whether a clause was read whole as a switch that has no step ("osm
// off"): the line is then no place either.
let consumed = false;
for (let i = 0; i < clauses.length; i += 2) {
let clause = tidy(clauses[i]);
const separator = clauses[i - 1]?.trim();
const afterPlaceComma = previousHadPlace && separator === ',';
// "trinidad and tobago": a bare place joined to a bare place by "and".
const afterBarePlaceAnd = previousBarePlace && separator === 'and';
const continuedLayer = previousLayerEnabled;
const afterGo = previousGo;
previousGo = false;
previousHadPlace = false;
previousBarePlace = false;
previousLayerEnabled = null;
if (!clause) continue;
// "noir off", "flights on", "orbit off": a switch after what it switches
// reads as one before it ("turn off noir"), so "off" is never a place.
const switchAfter = clause.match(/^(.+?)\s+(on|off)$/);
if (
switchAfter &&
!/\b(?:radio|hud)\b/.test(switchAfter[1]) &&
requestIn(switchAfter[1])
)
clause = `turn ${switchAfter[2]} ${switchAfter[1]}`;
// Steps of a clause that has a verb are asked for; so are those joined
// to a "go to" clause by "and" or "then" ("go to Paris and noir").
const clauseVerb =
ACTION_VERB.test(clause) ||
(afterGo && /^(and|then|and then)$/.test(separator || ''));
// `wanted`: whether this step's own clause asked for it; a layer is
// asked for only by a switch right before its word (see below).
const add = (step, wanted = clauseVerb) => {
const key = JSON.stringify(step);
let kept = steps.find((existing) => JSON.stringify(existing) === key);
if (!kept) steps.push((kept = step));
if (!clauseOf.has(kept)) clauseOf.set(kept, i);
if (wanted && step.kind !== 'place') asked.add(kept);
return kept;
};
const addBare = (step, wanted = clauseVerb) => {
const kept = add(step, wanted);
if (!wanted) bareSteps.add(kept);
};
// `leftover`: a name left beside the clause's keywords ("Show Low
// noir"), not one named after near or in ("turn on radio in tokyo").
const addPlace = (value, { bare = false, leftover = false } = {}) => {
if (!value) return;
if (leftover) placeClauses.add(i);
if (place && bare && afterBarePlaceAnd) place += ` and ${value}`;
else if (place && !afterPlaceComma) {
if (separator === 'and') extraPlaces.push(value);
return;
} else if (!place) {
place = value;
placeBare = bare;
} else place += `, ${value}`;
previousHadPlace = true;
previousBarePlace = bare;
};
// "go to Thermal, California", "fly to Tilt Cove": the rest of a "go to"
// clause is the place, read before any keyword in it, and so is a part
// after a comma that has no verb of its own.
// A request that ends the clause is peeled off it ("go to tokyo in
// noir", "go to London with flights", "go to tokyo show flights", "go
// to tokyo, north up"); the line is then ambiguous, so the place row
// still comes first. Names that merely hold a keyword stay whole.
const go = clause.match(GO);
const tailStep =
afterGo && separator === ',' && !clauseVerb ? requestIn(clause) : null;
if (tailStep) {
add(tailStep);
goPeeled = true;
previousGo = true;
continue;
}
if (go || (afterGo && separator === ',' && !clauseVerb)) {
let value = go ? clause.slice(go[0].length) : clause;
const peel = go && value.match(GO_TAIL);
const peeled =
peel && (peel[2] ? layerRequest(peel[3], peel[2]) : requestIn(peel[3]));
if (peeled) {
value = peel[1];
add(peeled);
goPeeled = true;
}
value = placeName(value);
if (go) addPlace(value, { bare: true });
else if (value) place += `, ${value}`;
if (go && value) placeFrom = 'go';
previousHadPlace = true;
previousBarePlace = true;
previousGo = true;
continue;
}
// "hide everything near tokyo": a whole-map clear with a place after it.
const clearNear = clause.match(NEAR);
if (clearNear && CLEAR_ALL.test(tidy(clause.slice(0, clearNear.index)))) {
add({ kind: 'camera', act: 'clear' });
addPlace(placeName(clearNear[1]));
placeFrom ??= 'near';
continue;
}
const panel = panelStep(clause);
if (panel) {
add(panel);
continue;
}
const follow = clause.match(FOLLOW);
if (follow) {
// "track flights near austin" shows a layer there; "follow AAL123"
// follows a craft, and "track it over texas" still goes to Texas.
const where = follow[2].match(NEAR);
const target = where ? tidy(follow[2].slice(0, where.index)) : follow[2];
const [layer] = matchLayers(target.replace(FILLER, ' ').trim());
if (named(layer)) {
add({ kind: 'layer', layer, enabled: true });
previousLayerEnabled = true;
if (where) addPlace(placeName(where[1]));
continue;
}
if (FOLLOWABLE.test(target) || isEntity(target.replace(/^the\s+/, ''))) {
if (where) addPlace(placeName(where[1]));
add({ kind: 'follow', query: target.replace(/^the\s+/, '') });
continue;
}
// Not something to follow: read on, as a place.
}
// "nearest plane", alone or with a place: "Nearest Plane Crash Site" is
// a name.
if (
/\b(nearest|closest) (plane|aircraft|flight|jet)s?(?:$|\s+(?:to|near|in|at|around|over)\b)/.test(
clause,
)
) {
const where = clause.match(NEAR_TO);
if (where) addPlace(placeName(where[1]));
add({ kind: 'nearest' });
continue;
}
// "turn off noir" goes back to the normal style, "turn off orbit"
// stops the camera; a map or a camera move has nothing to turn off.
const switchOff = LAYER_OFF.test(clause);
let took = false;
const style = takeFirst(clause, STYLES);
if (style) {
addBare({ kind: 'style', style: switchOff ? 'normal' : style.value });
clause = style.rest;
took = true;
}
const stack = takeFirst(clause, STACKS);
if (stack) {
if (!switchOff) addBare({ kind: 'stack', stack: stack.value });
clause = stack.rest;
took = true;
}
const camera = takeFirst(clause, CAMERA);
if (camera) {
const move = switchOff ? cameraOff(camera.value) : camera.value;
if (move) addBare({ kind: 'camera', ...move });
clause = camera.rest;
took = true;
}
const hud = clause.match(
/\b(hide|show|turn off|turn on)?\s*hud\s*(on|off)?\b/,
);
if (hud) {
const off = /hide|off/.test(hud[0]) || switchOff;
addBare({ kind: 'hud', visible: off ? 'off' : 'on' });
clause = tidy(clause.replace(hud[0], ' '));
took = true;
}
// The switch verb is all that is left beside what it switched.
if (took && SWITCH_ONLY.test(clause)) {
consumed = true;
continue;
}
const cockpit = clause.match(COCKPIT);
if (cockpit) {
add({ kind: 'cockpit' });
clause = tidy(clause.replace(cockpit[0], ' '));
}
const radioOff = clause.match(RADIO_OFF);
const radio = radioOff || clause.match(RADIO_ON);
if (radio) {
// "turn off the radio", "stop the radio", "mute radio": radio off. The
// verbs are never a place.
const disable = Boolean(radioOff);
const rest = tidy(clause.replace(radio[0], ' '));
const where = rest.match(NEAR);
// "play radio in tokyo", or the place left beside it: "play radio tokyo".
const beside = tidy(rest.replace(FILLER, ' '));
if (where) addPlace(placeName(where[1]));
else if (beside && !disable) addPlace(placeName(beside));
add({ kind: 'radio', action: disable ? 'disable' : 'enable' });
continue;
}
// Layers: "hide flights", "cctv near austin", "earthquakes".
const off = clause.match(LAYER_OFF);
const on = LAYER_ON.test(clause);
let body = clause.replace(LAYER_OFF, '').replace(LAYER_ON, '');
body = tidy(body.replace(GO, ''));
const where = body.match(NEAR);
const what = (where ? tidy(body.slice(0, where.index)) : body).replace(
/(\s+(in|at|on|with|of|near|to))+$/,
'',
);
const subject = tidy(
what.replace(/^(?:all|every)\s+/, '').replace(FILLER, ' '),
);
const layers = subject ? matchLayers(subject) : [];
const enabled = off ? false : on ? true : (continuedLayer ?? true);
// A whole layer name: "rock" begins "rockets" but names no layer.
if (named(layers[0])) {
// Without a switch right before it a layer word may be a place's name
// ("Hurricane, Utah", "Kill Devil Hills" is no "kill").
addBare({ kind: 'layer', layer: layers[0], enabled }, Boolean(off || on));
previousLayerEnabled = enabled;
if (where) {
addPlace(placeName(where[1]));
// "of" and "at" may join the words of a name ("Planes of Fame Air
// Museum", "Boats at Sea"); near, in, around, over, across and above
// place a request ("flights near Tokyo", "flights over Texas").
placeFrom ??= AROUND.test(where[0]) ? 'near' : 'of';
}
continue;
}
// A layer and a place side by side, without "in": "tokyo traffic",
// "earthquakes japan". The place is whichever side is not the layer.
if (
!where &&
subject.includes(' ') &&
subject.split(' ').length <= MAX_PAIR_WORDS
) {
const words = subject.split(' ');
let pair = null;
// Only a whole layer name or synonym counts here.
for (let cut = 1; cut < words.length && !pair; cut++) {
const head = words.slice(0, cut).join(' ');
const tail = words.slice(cut).join(' ');
const [tailLayer] = matchLayers(tail);
const [headLayer] = matchLayers(head);
if (named(tailLayer))
pair = { layer: tailLayer, place: head, layerFirst: false };
else if (named(headLayer))
pair = { layer: headLayer, place: tail, layerFirst: true };
}
// "show radio stations", "flights here": a word about the layer, not
// a place.
if (pair && (off || on) && NOT_A_PLACE.test(pair.place)) {
addBare(
{ kind: 'layer', layer: pair.layer, enabled },
Boolean(off || on) && pair.layerFirst,
);
previousLayerEnabled = enabled;
continue;
}
if (pair) {
// Asked for only when the switch comes right before the layer word
// ("show traffic tokyo"); "show low radio" names Show Low.
addBare(
{ kind: 'layer', layer: pair.layer, enabled },
Boolean(off || on) && pair.layerFirst,
);
previousLayerEnabled = enabled;
addPlace(placeName(pair.place), { bare: true, leftover: true });
continue;
}
}
if (where && subject === '') addPlace(placeName(where[1]));
else if (tidy(body.replace(FILLER, ' '))) {
const before = place;
addPlace(placeName(body), { bare: !off && !on, leftover: true });
// Left over after a switch that switched nothing ("Show Low noir").
if (!before && place && (off || on)) placeFrom ??= 'verb';
}
}
// A verb with a name left beside its keywords asks for nothing but a layer
// switched right after it: "Show Low noir", "Start Point noir" and "Track
// Hill noir" name places, they do not ask for noir.
for (const [step, index] of clauseOf) {
if (step.kind === 'layer' || !asked.has(step)) continue;
if (!ACTION_VERB.test(tidy(clauses[index] || ''))) continue;
// "show noir" alone asks for noir; only a name left beside the switch
// ("Show Low noir") makes it a place.
if (!placeClauses.has(index)) continue;
const layerAsked = [...clauseOf].some(
([other, at]) =>
at === index && other.kind === 'layer' && asked.has(other),
);
if (!layerAsked) {
asked.delete(step);
bareSteps.add(step);
}
}
// A standalone place retains the user's spelling and punctuation. A comma
// before a real command still separates actions in a combined plan.
if (!steps.length && !consumed) place = raw.replace(GO, '');
// A place is a name of six words at most: anything longer is a sentence
// (pasted text, a remark), which names no place. With nothing asked for
// beside it, the line is for GEV only and Enter runs nothing.
// A long name dropped beside keywords nobody asked for ("San Jose, Santa
// Clara County, California, USA flights") makes the line a sentence too.
let droppedPlace = false;
if (place && place.split(/\s+/).length > placeWordLimit(place)) {
place = null;
droppedPlace = true;
}
const sentence =
(!place && !steps.length) ||
(droppedPlace && steps.every((step) => !asked.has(step))) ||
(line.split(' ').length > MAX_SENTENCE_WORDS &&
!(place && /\d/.test(place) && !steps.length) &&
placeFrom !== 'go' &&
steps.every((step) => !asked.has(step)));
if (sentence)
return {
steps: [],
question: false,
asks: false,
sentence: true,
asked: new Set(),
clauseOf: new Map(),
extraPlaces: [],
};
// One keyword without a verb beside what is left of the line ("Thermal,
// California", "Tilt Cove", "tokyo traffic") may be a place's own name:
// the whole line is offered as a place ahead of the plan.
const joined = /\b(and|then|also)\b|[;+&]/.test(line);
const ambiguous =
(Boolean(place) && goPeeled) ||
(Boolean(place) &&
placeBare &&
steps.length === 1 &&
bareSteps.has(steps[0]) &&
!joined) ||
// A switch that switched nothing and a keyword nobody asked for, beside
// what is left: "Show Low noir", "Show Low radio" name Show Low.
(Boolean(place) &&
placeFrom === 'verb' &&
steps.length > 0 &&
steps.every((step) => !asked.has(step)) &&
!joined) ||
// Keywords nobody asked for beside the rest of a name, joined or not:
// "Storm Lake and Spencer", "Thermal and Indio" may be one place, so the
// whole line is offered first.
(Boolean(place) &&
placeFrom !== 'near' &&
steps.length > 0 &&
steps.every((step) => !asked.has(step)));
// Several keywords and nothing asked for ("Fire and Rain", "Noir and
// Thermal"): no plan runs on Enter; the line may still be a name.
const unasked = steps.length > 0 && steps.every((step) => !asked.has(step));
if (place && !placeFrom) placeFrom = placeBare ? 'bare' : 'near';
if (place) steps.unshift({ kind: 'place', place });
steps.verb = LAYER_OFF.test(line) || LAYER_ON.test(line) || GO.test(line);
// Following happens once the camera has settled on the new view.
steps.sort((a, b) => (a.kind === 'follow') - (b.kind === 'follow'));
return {
steps,
question,
asks,
ambiguous,
unasked,
extraPlaces,
placeFrom,
peeled: goPeeled,
asked,
clauseOf,
};
}
/** A layer match that names the whole layer, not the start of its name. */
function named(layer) {
return layer?.score >= 2 && layer.exact !== false;
}
/** "above M5", "m4.5+", "magnitude 6": a magnitude floor in a line. */
const MAGNITUDE =
/\b(?:above|over|at least|greater than|>=?)?\s*m(?:ag(?:nitude)?)?\s*(\d+(?:\.\d+)?)\s*\+?(?=\s|$)/i;
/** Layers whose items have a magnitude. */
const MAGNITUDE_LAYERS = /^(earthquakes?|quakes?)$|earthquake/;
/**
* A count request's text without its magnitude floor, and the floor. Only an
* earthquake layer reads one: "flights over m25" keeps its words.
* @returns {{text: string, minMagnitude: ?number}}
*/
export function magnitudeFloor(text, matchLayers) {
const raw = String(text || '').trim();
const match = raw.match(MAGNITUDE);
if (!match) return { text: raw, minMagnitude: null };
const plain = tidy(raw.replace(match[0], ' '));
const layer = parseOmnibar(plain, matchLayers).steps.find(
(step) => step.kind === 'layer',
)?.layer;
return layer && MAGNITUDE_LAYERS.test(String(layer.id))
? { text: plain, minMagnitude: Number(match[1]) }
: { text: raw, minMagnitude: null };
}
+431
View File
@@ -0,0 +1,431 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { isPanelText, magnitudeFloor, parseOmnibar } from './omnibarIntent.js';
const matchLayers = (term) =>
['flights', 'ships'].includes(term) ? [{ id: term, score: 2 }] : [];
test('place lookup retains comma qualifiers in standalone and combined requests', () => {
assert.deepEqual(
[...parseOmnibar(' Paris, Texas ', matchLayers).steps],
[{ kind: 'place', place: 'Paris, Texas' }],
);
const { steps } = parseOmnibar(
'north up, flights near Paris, Texas, follow AAL123',
matchLayers,
);
assert.deepEqual(
steps.map(({ kind }) => kind),
['place', 'camera', 'layer', 'follow'],
);
assert.equal(steps[0].place, 'paris, texas');
});
test('named layer removals and orbit stop preserve the requested action', () => {
const { steps } = parseOmnibar(
'hide all flights and ships, stop orbit',
matchLayers,
);
assert.deepEqual(
[...steps],
[
{ kind: 'layer', layer: { id: 'flights', score: 2 }, enabled: false },
{ kind: 'layer', layer: { id: 'ships', score: 2 }, enabled: false },
{ kind: 'camera', name: 'move_camera', args: { motion: 'stop' } },
],
);
assert.deepEqual(
[...parseOmnibar('turn off all layers', matchLayers).steps],
[{ kind: 'camera', act: 'clear' }],
);
});
const layersOf = (steps) =>
[...steps].map((step) =>
step.kind === 'layer'
? { kind: 'layer', id: step.layer.id, enabled: step.enabled }
: step,
);
test('turning the radio off is a radio step, and its verb is never a place', () => {
assert.deepEqual(
layersOf(parseOmnibar('tokyo and turn off the radio', matchLayers).steps),
[
{ kind: 'place', place: 'tokyo' },
{ kind: 'radio', action: 'disable' },
],
);
assert.deepEqual(
layersOf(
parseOmnibar('show flights and stop the radio', matchLayers).steps,
),
[
{ kind: 'layer', id: 'flights', enabled: true },
{ kind: 'radio', action: 'disable' },
],
);
assert.deepEqual(
layersOf(parseOmnibar('go to austin, mute radio', matchLayers).steps),
[
{ kind: 'place', place: 'austin' },
{ kind: 'radio', action: 'disable' },
],
);
assert.deepEqual(
layersOf(parseOmnibar('play radio in tokyo', matchLayers).steps),
[
{ kind: 'place', place: 'tokyo' },
{ kind: 'radio', action: 'enable' },
],
);
});
// Layers as the Omnibar matches them: whole names are `exact`, a name's
// start is not.
const LAYERS = {
flights: ['flights'],
earthquakes: ['earthquakes', 'quakes'],
'local-firms': ['fires'],
'rocket-launches': ['rockets', 'launches'],
traffic: ['traffic'],
radio: ['radio'],
};
const matchNamed = (term) => {
const needle = term.trim().toLowerCase();
if (!needle) return [];
return Object.entries(LAYERS)
.filter(([, words]) =>
words.some((word) => needle.length >= 3 && word.startsWith(needle)),
)
.map(([id, words]) => ({
id,
score: 2,
exact: words.includes(needle) || words.includes(`${needle}s`),
}));
};
test('near-miss lines read as people mean them', () => {
const read = (text) => layersOf(parseOmnibar(text, matchNamed).steps);
const clear = [{ kind: 'camera', act: 'clear' }];
assert.deepEqual(read('hide everything'), clear);
assert.deepEqual(read('remove everything'), clear);
assert.equal(isPanelText('hide everything'), false);
assert.equal(isPanelText('close all panels'), true);
assert.deepEqual(read('track flights near austin'), [
{ kind: 'place', place: 'austin' },
{ kind: 'layer', id: 'flights', enabled: true },
]);
assert.deepEqual(read('follow AAL123'), [
{ kind: 'follow', query: 'aal123' },
]);
assert.deepEqual(read('show earthquake data layer'), [
{ kind: 'layer', id: 'earthquakes', enabled: true },
]);
assert.equal(isPanelText('show earthquake data layer'), false);
assert.equal(read('open data layers')[0].item, 'data-panel');
assert.deepEqual(read('go to trinidad and tobago and show flights'), [
{ kind: 'place', place: 'trinidad and tobago' },
{ kind: 'layer', id: 'flights', enabled: true },
]);
// "fire" is a whole layer word, so "Fire Island" is ambiguous: the whole
// line is offered as a place first (see the Omnibar test).
assert.equal(parseOmnibar('Fire Island', matchNamed).ambiguous, true);
assert.deepEqual(read('Show Low, AZ'), [
{ kind: 'place', place: 'Show Low, AZ' },
]);
// Words that also start place names ask only in a longer line.
for (const place of ['Can Tho', 'Tell City']) {
const { steps, question } = parseOmnibar(place, matchNamed);
assert.equal(question, false, place);
assert.deepEqual([...steps], [{ kind: 'place', place }]);
}
assert.equal(parseOmnibar('can you show me', matchNamed).question, true);
assert.equal(parseOmnibar('Can Tho?', matchNamed).question, true);
assert.equal(parseOmnibar('what is here', matchNamed).question, true);
});
test('a magnitude floor is read for earthquakes only', () => {
assert.deepEqual(magnitudeFloor('quakes above m5 in japan', matchNamed), {
text: 'quakes in japan',
minMagnitude: 5,
});
assert.deepEqual(magnitudeFloor('earthquakes m4.5+ near tokyo', matchNamed), {
text: 'earthquakes near tokyo',
minMagnitude: 4.5,
});
assert.deepEqual(magnitudeFloor('flights over m25', matchNamed), {
text: 'flights over m25',
minMagnitude: null,
});
assert.deepEqual(magnitudeFloor('flights near austin', matchNamed), {
text: 'flights near austin',
minMagnitude: null,
});
});
test('place names holding a command word are places, or ambiguous at most', () => {
const read = (text) => parseOmnibar(text, matchNamed);
// The cockpit and the radio need a verb.
for (const text of [
'Cockpit Country, Jamaica',
'cockpit',
'cockpit view',
'Rock and Roll Hall of Fame',
]) {
const { steps } = read(text);
assert.deepEqual([...steps], [{ kind: 'place', place: text }], text);
}
assert.deepEqual([...read('enter cockpit').steps], [{ kind: 'cockpit' }]);
assert.equal(
read('Radio City Music Hall').steps.some((step) => step.kind === 'radio'),
false,
);
// One keyword without a verb beside the rest of a name: the whole line is
// offered as a place ahead of the plan.
for (const text of [
'Radio City Music Hall',
'Radio Free Europe',
'Thermal, California',
'Tilt Cove',
'Hud Valley',
'tokyo traffic',
])
assert.equal(read(text).ambiguous, true, text);
// A verb, a joining "and" or "near" makes it a plan.
// Keywords nobody asked for, joined to the rest of a name, leave the
// whole line a place first too ("Storm Lake and Spencer").
assert.equal(read('noir and tokyo').ambiguous, true);
for (const text of [
'flights near austin',
'show traffic in tokyo',
'tilt and go to cove',
'show noir and tokyo',
])
assert.equal(read(text).ambiguous, false, text);
});
test('nearest to, several places, and what can be followed', () => {
const read = (text) => layersOf(parseOmnibar(text, matchNamed).steps);
assert.deepEqual(read('nearest plane to Heathrow'), [
{ kind: 'place', place: 'heathrow' },
{ kind: 'nearest' },
]);
const both = parseOmnibar('flights near New York and Paris', matchNamed);
assert.equal(both.steps[0].place, 'new york');
assert.deepEqual(both.extraPlaces, ['paris']);
assert.deepEqual(read('Follow Me Bar'), [
{ kind: 'place', place: 'Follow Me Bar' },
]);
// A name without a digit is followed only when it is loaded on the map.
assert.deepEqual(
layersOf(
parseOmnibar('follow the iss', matchNamed, {
isEntity: (name) => name === 'iss',
}).steps,
),
[{ kind: 'follow', query: 'iss' }],
);
assert.deepEqual(read('Track Hill'), [
{ kind: 'place', place: 'Track Hill' },
]);
assert.deepEqual(read('follow UAL 123'), [
{ kind: 'follow', query: 'ual 123' },
]);
});
test('a magnitude floor is no part of the place', () => {
const { text, minMagnitude } = magnitudeFloor(
'show me earthquakes above m5 in japan',
matchNamed,
);
assert.equal(minMagnitude, 5);
assert.deepEqual(layersOf(parseOmnibar(text, matchNamed).steps), [
{ kind: 'place', place: 'japan' },
{ kind: 'layer', id: 'earthquakes', enabled: true },
]);
});
test('ar and he mark every Omnibar string alike with a right-to-left mark', async () => {
const { readFile } = await import('node:fs/promises');
// Every message the Omnibar's code passes to t(), msg() or tn(): after a
// colon or comma, before a placeholder or Latin text, both catalogs put
// U+200F, so the punctuation stays with the right-to-left text before it.
const sources = await Promise.all(
[
'./views/panels/VoiceVisualizer.vue',
'./omnibarIntent.js',
'./omnibarRows.js',
'./omnibarGuide.js',
'./leftPanelRail.js',
].map((file) => readFile(new URL(file, import.meta.url), 'utf8')),
);
const code = sources.join('\n');
// Single- or double-quoted, as t('…') / msg("…") / tn(n, '…', "…").
const STRING = String.raw`'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"`;
const literal = (match, from) => match[from] ?? match[from + 1];
const keys = new Set([
...[
...code.matchAll(
new RegExp(String.raw`\b(?:t|msg)\(\s*(?:${STRING})`, 'g'),
),
].map((match) => literal(match, 1)),
...[
...code.matchAll(
new RegExp(
String.raw`\btn\([^,]+,\s*(?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"),\s*(?:${STRING})`,
'g',
),
),
].map((match) => literal(match, 1)),
]);
assert.ok(keys.size > 100, `${keys.size} Omnibar messages`);
const unmarked = /[:\u060c,] (?!\u200f)(?=[{A-Za-z\u00ab\u05f4"])/;
for (const locale of ['ar', 'he']) {
const catalog = JSON.parse(
await readFile(
new URL(`../i18n/locales/${locale}.json`, import.meta.url),
'utf8',
),
);
for (const key of keys) {
const entry = catalog[key];
assert.ok(entry, `${locale} has ${key}`);
for (const text of typeof entry === 'string'
? [entry]
: Object.values(entry))
assert.doesNotMatch(text, unmarked, `${locale}: ${key}`);
}
}
});
test('a "go to" clause is all place, and radio verbs apply to the radio', () => {
const read = (text) => layersOf(parseOmnibar(text, matchNamed).steps);
for (const [text, place] of [
['go to cockpit country', 'cockpit country'],
['go to Thermal, California', 'Thermal, California'],
['fly to Tilt Cove', 'Tilt Cove'],
['go to Night Vision Way', 'Night Vision Way'],
['go to Whole Earth Provision', 'Whole Earth Provision'],
])
assert.deepEqual(read(text), [{ kind: 'place', place }], text);
assert.deepEqual(read('go to austin, clear everything'), [
{ kind: 'place', place: 'austin' },
{ kind: 'camera', act: 'clear' },
]);
assert.deepEqual(read('go to'), []);
assert.deepEqual(read('play radio in Kill Devil Hills'), [
{ kind: 'place', place: 'kill devil hills' },
{ kind: 'radio', action: 'enable' },
]);
assert.deepEqual(read('enter the cockpit view'), [{ kind: 'cockpit' }]);
// Only a real question asks GEV by default; small talk goes there too.
assert.equal(parseOmnibar('hi', matchNamed).asks, false);
// Small talk is no question: it may be a place, with Ask GEV after it.
assert.equal(parseOmnibar('hi', matchNamed).question, false);
assert.equal(parseOmnibar('what is here', matchNamed).asks, true);
// A long line is not split word by word into a layer and a place.
let asked = 0;
parseOmnibar('a b c d e f g h i j k l m n o p', (term) => {
asked++;
return matchNamed(term);
});
assert.ok(asked <= 2, `${asked} layer lookups`);
});
test('a request ending a "go to" clause is peeled off, and the line is ambiguous', () => {
const read = (text) => parseOmnibar(text, matchNamed);
for (const [text, place, step] of [
['go to tokyo in noir', 'tokyo', { kind: 'style', style: 'noir' }],
['go to tokyo, noir', 'tokyo', { kind: 'style', style: 'noir' }],
['go to Tokyo, north up', 'tokyo', { kind: 'camera', act: 'northUp' }],
[
'take me to Austin in thermal',
'austin',
{ kind: 'style', style: 'thermal' },
],
[
'go to London with flights',
'london',
{ kind: 'layer', id: 'flights', enabled: true },
],
[
'go to tokyo show flights',
'tokyo',
{ kind: 'layer', id: 'flights', enabled: true },
],
]) {
const parsed = read(text);
assert.equal(parsed.ambiguous, true, text);
assert.equal(parsed.peeled, true, text);
assert.deepEqual(
layersOf(parsed.steps),
[{ kind: 'place', place }, step],
text,
);
}
for (const text of [
'go to Thermal, California',
'fly to Tilt Cove',
'go to Night Vision Way',
'go to cockpit country',
])
assert.equal(read(text).steps.length, 1, text);
// A joining word left alone names no place.
assert.deepEqual(
layersOf(read('go to Austin and show flights in noir').steps),
[
{ kind: 'place', place: 'austin' },
{ kind: 'style', style: 'noir' },
{ kind: 'layer', id: 'flights', enabled: true },
],
);
// A named layer without a verb may be a name: "Hurricane, Utah".
assert.equal(read('fires, utah').ambiguous, true);
assert.equal(read('flights near austin').placeFrom, 'near');
// A comma line without "?" is never a question.
for (const text of ['Why, Arizona', 'What Cheer, Iowa', 'Can Tho, Vietnam'])
assert.equal(read(text).question, false, text);
assert.equal(read('why, arizona?').question, true);
});
test('the one verb test reads any letter case', async () => {
const { hasActionVerb } = await import('./omnibarIntent.js');
for (const text of [
'Turn on the radio',
'Turn On Radio',
'Draw',
'CLEAR THE MAP',
])
assert.equal(hasActionVerb(text), true, text);
for (const text of [
'Kill Devil Hills',
'Show',
'See',
'Clear Lake',
'Tilt Cove',
])
assert.equal(hasActionVerb(text), text === 'Show', text);
});
test('every place word is still a bundled place name', async () => {
const { readFile, readdir } = await import('node:fs/promises');
const { PLACE_WORDS } = await import('./omnibarEnter.js');
const names = new Set();
const cities = JSON.parse(
await readFile(
new URL(
'../data/local_data/wikidata_cities/cities.json',
import.meta.url,
),
'utf8',
),
);
for (const row of cities.rows) names.add(row[0].toLowerCase());
const dir = new URL('../data/local_data/wikidata_places/', import.meta.url);
for (const file of await readdir(dir))
if (/^-?\d+_-?\d+\.json$/.test(file))
for (const row of JSON.parse(await readFile(new URL(file, dir), 'utf8'))
.rows)
names.add(row[0].toLowerCase());
for (const word of PLACE_WORDS) assert.ok(names.has(word), word);
});
File diff suppressed because it is too large. Load diff
+566
View File
@@ -0,0 +1,566 @@
// src/ui/omnibarRows.test.mjs — the Omnibar's one pipeline from typed text
// to rows, read without the DOM: what Enter runs for a line before any row is
// chosen, what may go to the place service, and the rows themselves.
import assert from 'node:assert/strict';
import test from 'node:test';
import { createOmnibar, readLine } from './omnibarRows.js';
import { normalizeLine } from './omnibarIntent.js';
const LAYERS = [
{ id: 'flights', name: 'Live Flights', enabled: false },
{ id: 'military', name: 'Military Flights', enabled: false },
{ id: 'radio', name: 'Radio', enabled: false },
{ id: 'cctv', name: 'CCTV', enabled: false },
{ id: 'earthquakes', name: 'Earthquakes', enabled: false },
{ id: 'traffic', name: 'Traffic', enabled: false },
{ id: 'weather-radar', name: 'Weather radar', enabled: false },
];
const layers = (on = []) =>
LAYERS.map((layer) => ({ ...layer, enabled: on.includes(layer.id) }));
/** One step of a plan, as the table writes it. */
function stepOutcome(step) {
switch (step.kind) {
case 'place':
return `fly(${step.place})`;
case 'layer':
return `layer(${step.layer.id},${step.enabled ? 'on' : 'off'})`;
case 'style':
return `style(${step.style})`;
case 'stack':
return `map(${step.stack})`;
case 'camera':
return `camera(${step.act || step.args?.motion || step.args?.direction || step.name})`;
case 'hud':
return `hud(${step.visible})`;
case 'panel':
return `panel(${step.action} ${step.item || step.side})`;
case 'radio':
return `radio(${step.action || 'enable'})`;
case 'follow':
return `follow(${step.query})`;
default:
return step.kind;
}
}
/** What Enter runs for a line before any row is chosen. */
function outcome(text, { on = [], places = [] } = {}) {
const omnibar = createOmnibar({ layers: layers(on) });
const { rows, defaultIndex } = omnibar.rows(text, { places });
const row = rows[defaultIndex];
if (!row) return 'nothing';
switch (row.kind) {
case 'place':
return `search(${row.place})`;
case 'layer':
return `layer(${row.id},${row.enabled ? 'on' : 'off'})`;
case 'ask':
return `ask(${row.query})`;
case 'plan':
return row.steps.map(stepOutcome).join(' + ');
default:
return row.kind;
}
}
// Every line is read with no row chosen. `search(q)` is the place search,
// `nothing` means Enter runs nothing.
const OUTCOMES = [
// A switch after what it switches is a switch, never a place.
['noir off', 'style(normal)'],
['Noir off', 'style(normal)'],
['noir on', 'style(noir)'],
['turn off noir', 'style(normal)'],
['thermal off', 'style(normal)'],
['night vision off', 'style(normal)'],
['orbit off', 'camera(stop)'],
['osm off', 'nothing'],
['hud off', 'hud(off)'],
['radio off', 'radio(disable)'],
['cctv off', 'layer(cctv,off)'],
['Bath on', 'search(Bath on)'],
// A verb ends at a space: hyphenated names are names.
['Hide-A-Way Lake noir', 'search(Hide-A-Way Lake noir)'],
['Hide-A-Way Lake', 'search(Hide-A-Way Lake)'],
['Show-Me Lake radio', 'search(Show-Me Lake radio)'],
// A closing full stop, curly apostrophes and "please".
['Show flights.', 'layer(flights,on)'],
['show flights!', 'layer(flights,on)'],
['please show flights', 'layer(flights,on)'],
['Please, show flights', 'layer(flights,on)'],
['show flights please', 'layer(flights,on)'],
['North up.', 'camera(northUp)'],
['please north up', 'camera(northUp)'],
['Clear all layers!', 'camera(clear)'],
['what’s here', 'ask(what’s here)'],
['what’s here?', 'ask(what’s here?)'],
['Paris, Texas.', 'search(Paris, Texas.)'],
['Washington D.C.', 'search(Washington D.C.)'],
['please', 'search(please)'],
// Ask GEV (a billed call) needs a question, not a name.
['Do it Best Hardware', 'search(Do it Best Hardware)'],
['Can You Imagine', 'search(Can You Imagine)'],
['Is This It', 'search(Is This It)'],
['Where Is My Mind', 'search(Where Is My Mind)'],
['can you show me', 'nothing'],
['is it raining in tokyo', 'nothing'],
['is it raining in tokyo?', 'ask(is it raining in tokyo?)'],
['where is my mind', 'ask(where is my mind)'],
['how far is paris', 'ask(how far is paris)'],
['Can Tho City', 'search(Can Tho City)'],
['Is there', 'search(Is there)'],
// Pasted sentences are no place, and words about a layer are no place.
['Show radio stations', 'layer(radio,on)'],
['show radio station', 'layer(radio,on)'],
['show flights here', 'layer(flights,on)'],
['flights here', 'search(flights here)'],
['I went to the store yesterday and it was really great', 'nothing'],
['the quick brown fox jumps over the lazy dog', 'nothing'],
['we saw so many flights over the city and it was loud', 'nothing'],
['go to Austin and show flights', 'fly(austin) + layer(flights,on)'],
// keywords without a verb ask for nothing,
// however many clauses they fill, and names keep their words.
['Fire and Rain', 'search(Fire and Rain)'],
['Rain, Thermal', 'search(Rain, Thermal)'],
['Weather and Traffic', 'search(Weather and Traffic)'],
// Each word alone is a command that runs ("orbit", "tilt").
['Orbit and Tilt', 'camera(orbit) + camera(tilt)'],
['Noir and Thermal', 'search(Noir and Thermal)'],
['Trains and Boats and Planes', 'search(Trains and Boats and Planes)'],
['Storm Lake and Spencer', 'search(Storm Lake and Spencer)'],
['Fire Island and Ocean Beach', 'search(Fire Island and Ocean Beach)'],
['Thermal and Indio', 'search(Thermal and Indio)'],
['Please Touch Museum', 'search(Please Touch Museum)'],
['Kindly Lane', 'search(Kindly Lane)'],
['Pretty Please', 'search(Pretty Please)'],
['Yahoo!', 'search(Yahoo!)'],
['Draw Bridge', 'search(Draw Bridge)'],
['draw well', 'search(draw well)'],
['draw a line', 'open-draw'],
['How To Train Your Dragon', 'nothing'],
['how to see satelites', 'ask(how to see satelites)'],
['Train Station', 'search(Train Station)'],
['Traffic Status', 'search(Traffic Status)'],
['Remove Island', 'search(Remove Island)'],
['Toggle Inn', 'search(Toggle Inn)'],
['Disable Canyon', 'search(Disable Canyon)'],
['remove island', 'nothing'],
['show noir and show cctv', 'style(noir) + layer(cctv,on)'],
// a name with "?" is offered to GEV,
// never sent; a question's form or four words are.
['New York?', 'nothing'],
['Truth or Consequences?', 'nothing'],
['東京都?', 'nothing'],
['東京はどこ?', 'ask(東京はどこ?)'],
['is it far?', 'ask(is it far?)'],
[
'how about the weather in paris today?',
'ask(how about the weather in paris today?)',
],
['123–45–6789', 'nothing'],
['what is 4111–1111–1111–1111?', 'nothing'],
// a switch with its place after "in" asks;
// a vague "how do I" runs no walk; names with "senha" or "xox" in them
// and addresses with numbers are places.
['turn on radio in tokyo', 'fly(tokyo) + radio(enable)'],
['enable radio in tokyo', 'fly(tokyo) + radio(enable)'],
['turn on noir in tokyo', 'fly(tokyo) + style(noir)'],
['how do I share', 'guide'],
['how do I sha', 'nothing'],
['Sachsenhausen', 'search(Sachsenhausen)'],
['Xoxocotla', 'search(Xoxocotla)'],
['Meguro Honmachi 2-chome', 'search(Meguro Honmachi 2-chome)'],
[
'1600 Pennsylvania Ave NW Washington DC 20500',
'search(1600 Pennsylvania Ave NW Washington DC 20500)',
],
// A long comma address beside a layer word is a sentence; a verb that
// starts a name asks for nothing; small talk asks no question.
['San Jose, Santa Clara County, California, USA flights', 'nothing'],
['Start Point noir', 'search(Start Point noir)'],
['Track Hill noir', 'search(Track Hill noir)'],
['Open Bay north up', 'search(Open Bay north up)'],
['show noir', 'style(noir)'],
['play radio tokyo', 'fly(tokyo) + radio(enable)'],
["what's up", "search(what's up)"],
["how's it going", "search(how's it going)"],
["what's the weather in paris", "ask(what's the weather in paris)"],
['Hauptstrasse 12 10115 Berlin', 'search(Hauptstrasse 12 10115 Berlin)'],
// "of" and "at" may join the words of a name; CJK addresses and
// postcodes are places.
['Planes of Fame Air Museum', 'search(Planes of Fame Air Museum)'],
['Boats at Sea', 'search(Boats at Sea)'],
['flights over texas', 'fly(texas) + layer(flights,on)'],
['北京市朝阳区建国路88号', 'search(北京市朝阳区建国路88号)'],
['東京都港区六本木6丁目', 'search(東京都港区六本木6丁目)'],
['Washington DC 20500-0003', 'search(Washington DC 20500-0003)'],
['Calle 100 # 19-61 Bogota', 'search(Calle 100 # 19-61 Bogota)'],
// Addresses that look like numbers to keep, and long names, are offered
// to search on purpose; Enter runs nothing. "Track 7" and "Nearest Plane
// Crash Site" are names.
['Tverskaya 13 125009 Moscow', 'search(Tverskaya 13 125009 Moscow)'],
['Москва, ул. Тверская, д. 13, 125009', 'nothing'],
['San Miguel de las Piedras Primera Sección', 'nothing'],
['Goto', 'search(Goto)'],
['goto tokyo', 'search(tokyo)'],
['Track 7', 'search(Track 7)'],
['Track 29', 'search(Track 29)'],
['Nearest Plane Crash Site', 'search(Nearest Plane Crash Site)'],
['nearest plane', 'nearest'],
// Lines the mounted Enter table pins too, read through the module.
['tokyo traffic', 'search(tokyo traffic)'],
['flights near tokyo', 'fly(tokyo) + layer(flights,on)'],
['radio near Clear Lake', 'search(clear lake)'],
['Thermal', 'search(Thermal)'],
['Thermal, California', 'search(Thermal, California)'],
['radio', 'search(radio)'],
['share', 'nothing'],
['hide', 'nothing'],
['Turn on the radio', 'layer(radio,on)'],
];
for (const [text, expected] of OUTCOMES)
test(`Enter on ${JSON.stringify(text)} runs ${expected}`, () => {
assert.equal(outcome(text), expected);
});
test('"show flights" with Live Flights on offers Live Flights, not Military Flights', () => {
assert.equal(
outcome('show flights', { on: ['flights'] }),
'layer(flights,on)',
);
assert.equal(
outcome('turn on flights', { on: ['flights'] }),
'layer(flights,on)',
);
const { rows, defaultIndex } = createOmnibar({
layers: layers(['flights']),
}).rows('show flights');
// Nothing to switch on the default row; Military Flights is offered after.
assert.equal(rows[defaultIndex].hint, 'Layer');
assert.ok(rows.some((row) => row.id === 'military'));
assert.equal(outcome('hide flights', { on: [] }), 'layer(flights,off)');
// "military" names Military Flights, never Live Flights.
assert.equal(outcome('show military'), 'layer(military,on)');
});
test('a layer near a place cannot admit an unrelated bare style step', () => {
assert.doesNotMatch(outcome('flights near Austin and noir'), /style\(noir\)/);
assert.equal(
outcome('flights near Austin'),
'fly(austin) + layer(flights,on)',
);
});
test('private text never reaches the place service, the search or GEV', () => {
const omnibar = createOmnibar({ layers: layers() });
for (const text of [
'123 45 6789',
'123456789',
'123-45-6789',
'4111 1111',
'١٢٣٤, ٥٦٧٨',
'what is my pass\u200bword: violet?',
'4111-1111-1111-1111',
'+1 415 555',
'415 555 0',
'415.555.0100',
'hunter22',
'letmein1',
'Tr0ub4dor&3',
'pa$$w0rd',
'token: abc',
'api key=xyz',
'password hunter2',
'[email protected]',
'4111 1111 1111 1111',
'john@example.com',
'sk_live_abc',
'٤١١١ ١١١١ ١١١١ ١١١١',
'४१११ ११११ ११११ ११११',
'4111.1111.1111.1111',
'what is 4111.1111.1111.1111',
'where is john@example.com',
'card ٤١١١١١١١١١١١١١١١ valid?',
'123–45–6789',
'415‐555‐0100',
'415−555−0100',
'4111:1111:1111:1111',
'4111|1111|1111|1111',
'4111\u200b1111\u200b1111\u200b1111',
'contraseña: hunter',
'Passwort: geheim',
'mot de passe: chat',
'пароль qwerty',
'api key abcdefgh',
]) {
assert.equal(omnibar.placeQuery(text), null, text);
assert.equal(omnibar.countRequest(text), null, text);
const { rows, defaultIndex } = omnibar.rows(text);
// Only a row to search it as a place on purpose, never by Enter.
assert.ok(
rows.every((row) => row.kind === 'place' && row.explicit),
text,
);
assert.equal(defaultIndex, -1, text);
}
// Callsigns, postcodes, coordinates and street numbers are not secrets.
assert.equal(omnibar.placeQuery('SW1A 1AA'), 'SW1A 1AA');
assert.equal(omnibar.placeQuery('10 Downing Street'), '10 Downing Street');
assert.equal(omnibar.placeQuery('Route 66'), 'Route 66');
for (const callsign of ['UAL2110', 'BAW15K', 'N123AB'])
assert.equal(omnibar.placeQuery(callsign), null, callsign);
for (const text of ['30.2672, -97.7431', '14R PU 2090 4906']) {
const { rows, defaultIndex } = omnibar.rows(text);
assert.equal(rows[defaultIndex].kind, 'place', text);
assert.ok(rows[defaultIndex].coords, text);
}
});
test('private text still finds things already on the map, locally', () => {
const omnibar = createOmnibar({ layers: layers() });
const found = [];
const { rows } = omnibar.rows('366123456', {
entities: (text) => {
found.push(text);
return [
{
key: 'v1',
icon: 'directions_boat',
identity: 'v1',
title: '366123456',
layerName: 'Vessels',
},
];
},
});
assert.deepEqual(found, ['366123456']);
assert.deepEqual(
rows.map((row) => row.kind),
['entity'],
);
});
test('a map item named like a place follows the place; a callsign leads', () => {
const omnibar = createOmnibar({ layers: layers() });
const entities = (text) =>
[
{
key: 's1',
icon: 'directions_boat',
identity: 's1',
title: 'HAMBURG',
layerName: 'Vessels',
},
{
key: 'f1',
icon: 'flight',
identity: 'f1',
title: 'UAL123',
layerName: 'Flights',
},
].filter((item) => item.title.toLowerCase().startsWith(text.toLowerCase()));
const hamburg = omnibar.rows('Hamburg', { entities });
assert.equal(hamburg.rows[hamburg.defaultIndex].kind, 'place');
assert.equal(hamburg.rows[1].kind, 'entity');
const callsign = omnibar.rows('UAL123', { entities });
assert.equal(callsign.rows[callsign.defaultIndex].kind, 'entity');
});
test('a long name or an address that looks private can be searched on purpose', () => {
const omnibar = createOmnibar({ layers: layers() });
for (const text of [
'Москва, ул. Тверская, д. 13, 125009',
'San Miguel de las Piedras Primera Sección',
]) {
const { rows, defaultIndex } = omnibar.rows(text);
assert.equal(defaultIndex, -1, text);
const row = rows.find((each) => each.explicit);
assert.equal(row?.place, text, text);
assert.equal(omnibar.placeQuery(text), null, text);
}
// A bare number names no place.
assert.deepEqual(omnibar.rows('4111 1111 1111 1111').rows, []);
});
test('a pasted sentence is never sent to the place service', () => {
const omnibar = createOmnibar({ layers: layers() });
for (const text of [
'I went to the store yesterday and it was really great',
'we saw so many flights over the city and it was loud',
'Show radio stations',
'noir off',
'can you show me',
])
assert.equal(omnibar.placeQuery(text), null, text);
assert.equal(omnibar.placeQuery('Tokyo traffic'), 'Tokyo traffic');
assert.equal(omnibar.placeQuery('flights near Tokyo.'), 'tokyo');
assert.equal(omnibar.placeQuery('Paris, Texas.'), 'Paris, Texas.');
assert.equal(omnibar.placeQuery('go to Paris, noir'), 'paris');
assert.equal(omnibar.placeQuery('turn on radio in tokyo'), 'tokyo');
assert.equal(omnibar.placeQuery('Sachsenhausen'), 'Sachsenhausen');
});
// The wording people use reaches each feature's own walk, and Enter starts
// it.
const GUIDE_PHRASES = [
['how do i change the map style', 'styles'],
['how to change the visual style', 'styles'],
['show me how to use night vision', 'styles'],
['how do i turn on the hud', 'hud'],
['how do i hide the hud', 'hud'],
['how do i tilt', 'tilt'],
['how do i tilt the map', 'tilt'],
['how to tilt the camera', 'tilt'],
['how to share this view', 'share'],
['how do i share a link', 'share'],
['how do i reset', 'globe'],
['how do i get back to the globe', 'globe'],
['how do i see the whole globe', 'globe'],
['how do i point north', 'north'],
['how do i use the compass', 'north'],
['how do i clear all layers', 'clear'],
['how to turn off all layers', 'clear'],
['how do i change the map', 'map-source'],
['how do i switch to openstreetmap', 'map-source'],
['how to measure distance', 'draw'],
['how do i draw', 'draw'],
['how do i draw a line', 'draw'],
['how do i measure an area', 'draw'],
['how do i search layers', 'find-layer'],
['how do i change language', 'preferences'],
];
for (const [text, feature] of GUIDE_PHRASES)
test(`${JSON.stringify(text)} starts the ${feature} walk`, () => {
const { rows, defaultIndex } = createOmnibar({ layers: layers() }).rows(
text,
);
assert.equal(rows[defaultIndex]?.kind, 'guide', text);
assert.equal(rows[defaultIndex].guide.feature, feature, text);
});
test('a layer named in full leads a feature topic its words also hold', () => {
const all = createOmnibar({
layers: [
...layers(),
{ id: 'recent-imagery', name: 'Recent Imagery', enabled: false },
{ id: 'weather-lightning', name: 'Lightning density', enabled: false },
],
});
for (const [text, id] of [
['how do I see recent imagery', 'recent-imagery'],
['how do I see lightning density', 'weather-lightning'],
]) {
const { rows, defaultIndex } = all.rows(text);
assert.equal(rows[defaultIndex].guide.layer?.id, id, text);
}
// The Context panel's walk stays first beside a layer named Global
// Context.
const context = createOmnibar({
layers: [
{ id: 'military-awareness', name: 'Global Context', enabled: false },
],
}).rows('how do I open global context');
assert.equal(context.rows[context.defaultIndex].guide.feature, 'context');
});
test('only an address that looks like a number may be searched anyway', () => {
const omnibar = createOmnibar({ layers: layers() });
for (const text of [
'password hunter2',
'[email protected]',
'hunter22',
'sk-abc123def',
'DE89 3704 0044 0532 0130 00',
'pin 1234567',
'door code 4421',
// A number beside a word that says what it is, or one too long for an
// address.
'code 12345678 Berlin',
'token 12345678 Berlin',
'user john pass 12345678',
'card 4111 1111 1111 1111 please',
'my card is 4111111111111111',
'routing 021000021 New York',
'phone +1 415 555 0100 office',
'BSN 123456782 Utrecht',
'medicare 1234567890 Sydney',
// Digits and words read as they fold: superscript, circled, full-width
// or split by a zero-width space; card and phone words in other
// languages.
'Berlin ⁴¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹',
'Berlin ①②③④⑤⑥⑦⑧⑨⑩',
'Main St 12 ¹²³⁴⁵⁶⁷⁸⁹¹²³⁴⁵⁶ Berlin',
'card 4111 1111 Berlin',
'ca\u200brd 4111 1111 Berlin',
'Visa 4111 1111 Berlin',
'Kreditkarte 4111 1111 Berlin',
'Telefon 912 34 567',
])
assert.deepEqual(omnibar.rows(text).rows, [], text);
for (const text of [
'Москва, ул. Тверская, д. 13, 125009',
'Jl. Jend. Sudirman No. 52-53, 12190 Jakarta',
])
assert.ok(
omnibar.rows(text).rows.some((row) => row.explicit),
text,
);
});
test("a line naming a layer still starts that layer's walk", () => {
const { rows, defaultIndex } = createOmnibar({ layers: layers() }).rows(
'how to turn on flights',
);
assert.equal(rows[defaultIndex].guide.layer.id, 'flights');
});
test('every feature the words name has a walk', async () => {
const { FEATURE_GUIDES } = await import('./omnibarGuide.js');
const omnibar = createOmnibar({ layers: layers() });
for (const [text] of GUIDE_PHRASES) {
const { rows, defaultIndex } = omnibar.rows(text);
const feature = rows[defaultIndex].guide.feature;
assert.equal(typeof FEATURE_GUIDES[feature], 'function', feature);
}
});
test('the line is normalised once, in one place', () => {
assert.equal(normalizeLine(' Show flights. '), 'Show flights');
// "please" goes only around a request; in a name it stays.
assert.equal(readLine('please, north up!'), 'north up');
assert.equal(readLine('please show flights'), 'show flights');
assert.equal(readLine('Please Touch Museum'), 'Please Touch Museum');
assert.equal(readLine('Kindly Lane'), 'Kindly Lane');
assert.equal(readLine('Pretty Please'), 'Pretty Please');
assert.equal(normalizeLine('please, north up!'), 'please, north up');
assert.equal(normalizeLine('what’s here'), "what's here");
assert.equal(normalizeLine('東京?'), '東京?');
assert.equal(normalizeLine('Tokyo'), 'Tokyo');
assert.equal(normalizeLine('Washington D.C.'), 'Washington D.C.');
assert.equal(normalizeLine('St. Louis.'), 'St. Louis');
assert.equal(normalizeLine('please'), 'please');
});
test('the rows the parser and the Enter rule agree on come from one place', () => {
// A command named exactly is the default; one merely begun only follows.
const omnibar = createOmnibar({ layers: layers() });
assert.equal(outcome('North up'), 'camera(northUp)');
assert.equal(outcome('> North up'), 'camera(northUp)');
const begun = omnibar.rows('> nort');
assert.equal(begun.defaultIndex, -1);
assert.equal(begun.rows[0].command, 'north');
// A Photon place counts for the credit.
const { rows } = omnibar.rows('Shibuya', {
places: [
{
name: 'Shibuya',
detail: 'Tokyo, Japan',
latitude: 35.66,
longitude: 139.7,
},
],
});
assert.equal(rows[0].source, 'photon');
});