From ca77ecfa1d0215027c406f6600de7510e2ac1e93 Mon Sep 17 00:00:00 2001 From: Manjunath Paparaju Date: Wed, 18 Nov 2026 12:37:39 -0800 Subject: [PATCH] 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 --- src/i18n/locales/ar.json | 126 ++- src/i18n/locales/de.json | 122 ++- src/i18n/locales/es.json | 123 ++- src/i18n/locales/fr.json | 123 ++- src/i18n/locales/he.json | 123 ++- src/i18n/locales/it.json | 123 ++- src/i18n/locales/ja.json | 121 ++- src/i18n/locales/pt.json | 123 ++- src/i18n/locales/ru.json | 124 ++- src/i18n/locales/sv.json | 122 ++- src/i18n/locales/uk.json | 124 ++- src/i18n/locales/zh-CN.json | 121 ++- src/i18n/locales/zh-Hant.json | 121 ++- src/ui/omnibarEnter.js | 174 ++++ src/ui/omnibarGuide.js | 713 +++++++++++++++ src/ui/omnibarIntent.js | 876 +++++++++++++++++++ src/ui/omnibarIntent.test.mjs | 431 +++++++++ src/ui/omnibarRows.js | 1538 +++++++++++++++++++++++++++++++++ src/ui/omnibarRows.test.mjs | 566 ++++++++++++ 19 files changed, 5881 insertions(+), 13 deletions(-) create mode 100644 src/ui/omnibarEnter.js create mode 100644 src/ui/omnibarGuide.js create mode 100644 src/ui/omnibarIntent.js create mode 100644 src/ui/omnibarIntent.test.mjs create mode 100644 src/ui/omnibarRows.js create mode 100644 src/ui/omnibarRows.test.mjs diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index a3e3957f7b..a14abe67f5 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -4551,5 +4551,129 @@ "Move down": "نقل لأسفل", "Click a shot to go to it, double-click to rename.": "انقر على لقطة للانتقال إليها، وانقر عليها نقرًا مزدوجًا لإعادة تسميتها.", "Back to live at the starting view": "العودة إلى البث المباشر في العرض الأولي", - "Exit cockpit to fly to a bike share city": "اخرج من قمرة القيادة للانتقال إلى مدينة بها مشاركة دراجات" + "Exit cockpit to fly to a bike share city": "اخرج من قمرة القيادة للانتقال إلى مدينة بها مشاركة دراجات", + "Open {panel}": "فتح {panel}", + "Visual": "العرض المرئي", + "Open Properties: settings for the layers that are on": "افتح الخصائص: إعدادات الطبقات المفعّلة", + "Data layers": "طبقات البيانات", + "{layer} options. {options}": "خيارات {layer}: ‏{options}", + "{layer} options appear here once it has loaded.": "تظهر خيارات {layer} هنا بعد اكتمال التحميل.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "تحدد التسميات عناصر {layer} على الخريطة. تضبط الكثافة عدد التسميات، ويحدد التلاشي والخارج مدى تناقصها خارج المنظار.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "النماذج الثلاثية الأبعاد: يعرض خيار القريبة نماذج للطائرات القريبة فقط، بينما يعرض خيار الكل نموذجًا لكل طائرة.", + "Press search to find {layer} in the list": "اضغط على البحث للعثور على {layer} في القائمة", + "Type {layer}": "اكتب {layer}", + "Turn on {layer} with its switch": "فعّل {layer} باستخدام مفتاح التبديل", + "{layer} are easiest to see from the globe view": "تظهر عناصر {layer} بأوضح صورة في عرض الكرة الأرضية", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "تنتشر عناصر {layer} على مساحة واسعة، فلا يظهر منها إلا القليل عند هذا التقريب. أبعد العرض أو انتقل إلى عرض الكرة الأرضية.", + "{layer} is on. Want to fine-tune what it shows?": "طبقة {layer} مفعّلة. هل تريد ضبط ما تعرضه؟", + "Show settings": "عرض الإعدادات", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "اختر نمطًا: عادي أو CRT أو NVG أو FLIR أو أنمي أو نوار (المفاتيح 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "اختر خريطة الأساس ضمن مصدر الخريطة: ‏Google 3D أو Bing أو Esri أو OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "فعّل شاشة العرض الأمامية أو أوقفها هنا. يتيح التخطيط اختيار تكتيكي أو مبسّط أو سيبراني", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "يؤطر المنظار العرض داخل دائرة. ينعّم التنعيم حافة الدائرة، ويحدد التعتيم درجة قتامة المنطقة خارجها.", + "Clean UI hides the panels and readouts for a clear view": "تخفي الواجهة النظيفة اللوحات والقراءات لإظهار العرض بوضوح", + "Press search, then type part of a layer name or source": "اضغط على البحث، ثم اكتب جزءًا من اسم الطبقة أو مصدرها", + "Type to narrow the list; Esc clears it": "اكتب لتضييق نطاق القائمة، واضغط Esc لمسح البحث", + "Filter shows only layers that are on or off, or one category": "يعرض التصفية الطبقات المفعّلة أو المتوقفة فقط، أو طبقات فئة واحدة", + "Open the filter": "افتح خيارات التصفية", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "اختر الحالة (تشغيل أو إيقاف) والفئة. يظهر كل اختيار كوسم يمكن إزالته", + "Hover a tick to see its group; click to jump there": "مرّر المؤشر فوق العلامة لمعرفة مجموعتها، وانقر للانتقال إليها", + "Add provider keys with Power Up, or change the language": "أضف مفاتيح مزوّدي الخدمة عبر Power Up، أو غيّر اللغة", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "اضغط لتحريك اللوحات عبر الشريط إلى حافة الشاشة، واضغط مرة أخرى لإعادتها", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "يعرض السياق الطقس والمخاطر والبيانات القريبة في طبقاتك وأي عنصر تختاره على الخريطة", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "تضم الخصائص إعدادات الطبقات المفعّلة، وتُميَّز كل طبقة بنقطة ملوّنة", + "Press the compass to face north": "اضغط على البوصلة للاتجاه شمالًا", + "Tilt the camera for a 3D view": "أمِل الكاميرا للحصول على عرض ثلاثي الأبعاد", + "Zoom out to the whole globe": "أبعد العرض حتى تظهر الكرة الأرضية بأكملها", + "Copy a link to exactly this view": "انسخ رابطًا يفتح هذا العرض بالضبط", + "Turn off every layer at once": "أوقف جميع الطبقات دفعة واحدة", + "Press Draw to start drawing on the map": "اضغط «الرسم» لبدء الرسم على الخريطة", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "اختر «خط» لقياس مسافة أو «مساحة» لقياس حجمها، ثم انقر نقاطًا على الخريطة؛ وانقر نقرًا مزدوجًا أو اضغط Enter للإنهاء", + "End guide": "إنهاء الدليل", + "to end": "للإنهاء", + "Guide · {topic}": "الدليل · {topic}", + "Guide": "دليل", + "Next": "التالي", + "Press the highlighted control": "اضغط على عنصر التحكم المميّز", + "Finish": "إنهاء", + "Skip step": "تخطّي الخطوة", + "Authoring": "أدوات الإنشاء", + "Visual styles": "أنماط العرض", + "HUD": "شاشة العرض الأمامية", + "Tilt / 3D view": "الإمالة والعرض الثلاثي الأبعاد", + "Sharing this view": "مشاركة هذا العرض", + "Clearing all layers": "إيقاف جميع الطبقات", + "Changing the map": "تغيير الخريطة", + "The scope": "المنظار", + "Searching layers": "البحث عن الطبقات", + "Filtering layers": "تصفية الطبقات", + "Jumping between layer groups": "التنقّل بين مجموعات الطبقات", + "Keys and language": "المفاتيح واللغة", + "Panels at the screen edge": "اللوحات عند حافة الشاشة", + "The Context panel": "لوحة السياق", + "Layer properties": "خصائص الطبقات", + "Drawing and measuring": "الرسم والقياس", + "Style: Noir": "النمط: نوار", + "Style: Thermal": "النمط: حراري", + "Style: Night vision": "النمط: رؤية ليلية", + "Style: Retro": "النمط: كلاسيكي", + "Style: Anime": "النمط: أنمي", + "Style: Normal": "النمط: عادي", + "Map: OpenStreetMap": "الخريطة: ‏OpenStreetMap", + "Map: Bing aerial": "الخريطة: صور Bing الجوية", + "Map: Photoreal 3D": "الخريطة: ثلاثية الأبعاد واقعية", + "Map: Esri imagery": "الخريطة: صور Esri", + "Clear all layers": "إيقاف كل الطبقات", + "Share this view": "مشاركة هذا العرض", + "Orbit": "دوران حول الهدف", + "Close all panels": "إغلاق جميع اللوحات", + "Close left panel": "إغلاق اللوحة اليسرى", + "Close right panel": "إغلاق اللوحة اليمنى", + "Open Utilities": "فتح الأدوات", + "Open Authoring": "فتح أدوات الإنشاء", + "Open Visual": "فتح إعدادات العرض المرئي", + "Open Context": "فتح لوحة السياق", + "Stop camera": "إيقاف حركة الكاميرا", + "HUD on": "تشغيل شاشة العرض الأمامية", + "HUD off": "إيقاف شاشة العرض الأمامية", + "Enter cockpit": "الدخول إلى قمرة القيادة", + "Talk to GEV": "تحدث إلى GEV", + "{layer} on": "تشغيل {layer}", + "{layer} off": "إيقاف {layer}", + "Close {panel}": "إغلاق {panel}", + "Cockpit": "قمرة القيادة", + "Follow {target}": "تتبّع {target}", + "Coordinates": "الإحداثيات", + "Go to {where}": "انتقل إلى {where}", + "Ask GEV: “{query}”": "اسأل GEV: ‏«{query}»", + "Opens chat": "يفتح المحادثة", + "Go to {place}": "انتقل إلى {place}", + "Place or coordinates": "مكان أو إحداثيات", + "Search “{query}” as a place anyway": "ابحث عن «{query}» كمكان على أي حال", + "Turn on": "تشغيل", + "Turn off": "إيقاف", + "Command": "أمر", + "No layers are on": "لا توجد طبقات مفعّلة", + "No matching layers": "لا توجد طبقات مطابقة", + "Show me {thing} settings": "عرض إعدادات {thing}", + "Show me how: {thing}": "طريقة الاستخدام: ‏{thing}", + "Do all": "نفّذ الكل", + "Do it": "نفّذ الإجراء", + "Follow {name}": "تتبّع {name}", + "Camera": "الكاميرا", + "Cockpit behind {name}": "منظور قمرة القيادة خلف {name}", + "Close {name}": "إغلاق {name}", + "Turn on {layer} here": "تشغيل {layer} هنا", + "this view": "هذا العرض", + "What's here?": "ماذا يوجد هنا؟", + "Show {what} in {place} ({count} items)": { + "zero": "عرض {what} في {place} ({count} عنصر)", + "one": "عرض {what} في {place} ({count} عنصر)", + "two": "عرض {what} في {place} ({count} عنصران)", + "few": "عرض {what} في {place} ({count} عناصر)", + "many": "عرض {what} في {place} ({count} عنصرًا)", + "other": "عرض {what} في {place} ({count} عنصر)" + }, + "Go there": "انتقل إلى هناك", + "Open draw options": "فتح خيارات الرسم" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 7a31f7310c..786bfa741e 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -4139,5 +4139,125 @@ "Move down": "Nach unten verschieben", "Click a shot to go to it, double-click to rename.": "Aufnahme anklicken, um zu ihr zu wechseln, Doppelklick zum Umbenennen.", "Back to live at the starting view": "Zurück zu Live in der Startansicht", - "Exit cockpit to fly to a bike share city": "Cockpit verlassen, um zu einer Stadt mit Bike-Sharing zu fliegen" + "Exit cockpit to fly to a bike share city": "Cockpit verlassen, um zu einer Stadt mit Bike-Sharing zu fliegen", + "Open {panel}": "{panel} öffnen", + "Visual": "Darstellung", + "Open Properties: settings for the layers that are on": "Öffne die Eigenschaften, um aktive Ebenen einzustellen", + "Data layers": "Datenebenen", + "{layer} options. {options}": "Optionen für {layer}. {options}", + "{layer} options appear here once it has loaded.": "Die Optionen für {layer} erscheinen hier, sobald die Ebene geladen ist.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Beschriftungen kennzeichnen Elemente von {layer} auf der Karte. Dichte legt ihre Anzahl fest. Ausblenden und Außen regeln, wie stark sie außerhalb des Scope abnehmen.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3D-Modelle: Nähe zeigt nur Flugzeuge in der Umgebung als Modell. Alle zeigt jedes Flugzeug als Modell.", + "Press search to find {layer} in the list": "Drücke die Suchtaste, um {layer} in der Liste zu finden", + "Type {layer}": "Gib {layer} ein", + "Turn on {layer} with its switch": "Aktiviere {layer} mit dem zugehörigen Schalter", + "{layer} are easiest to see from the globe view": "In der Globusansicht siehst du {layer} am besten", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Die Elemente von {layer} sind weit verteilt. Aus dieser Nähe sind nur wenige zu sehen. Zoome heraus oder drücke die Globustaste.", + "{layer} is on. Want to fine-tune what it shows?": "{layer} ist aktiv. Möchtest du die Anzeige genauer einstellen?", + "Show settings": "Einstellungen anzeigen", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Wähle einen Stil: Normal, CRT, NVG, FLIR, Anime oder Noir (Tasten 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "Wähle unter Kartenquelle die Grundkarte: Google 3D, Bing, Esri oder OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Schalte hier das HUD ein oder aus. Wähle unter Layout Taktisch, Minimal oder Cyber.", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "Der Scope rahmt die Ansicht kreisförmig ein. Weichzeichnung glättet den Rand, die Deckkraft bestimmt die Abdunklung außen.", + "Clean UI hides the panels and readouts for a clear view": "Reine Ansicht blendet Bedienfelder und Anzeigen aus", + "Press search, then type part of a layer name or source": "Drücke die Suchtaste und gib einen Teil des Ebenennamens oder der Quellenbezeichnung ein", + "Type to narrow the list; Esc clears it": "Tippe, um die Liste einzugrenzen. Mit Esc löschst du die Suche.", + "Filter shows only layers that are on or off, or one category": "Der Filter zeigt nur aktive Ebenen, inaktive Ebenen oder Ebenen einer Kategorie", + "Open the filter": "Öffne den Filter", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Wähle einen Status (an oder aus) und eine Kategorie. Jeder Filter erscheint als Markierung, die du entfernen kannst.", + "Hover a tick to see its group; click to jump there": "Zeige auf eine Markierung, um ihre Gruppe zu sehen, und klicke darauf, um dorthin zu springen", + "Add provider keys with Power Up, or change the language": "Füge über Power Up Anbieterschlüssel hinzu oder ändere die Sprache", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Drücke hier, um die Bedienfelder über die Seitenleiste an den Bildschirmrand zu schieben. Drücke erneut, um sie zurückzuholen.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "Kontext beschreibt die Ansicht: Wetter, Gefahren, Elemente deiner Ebenen in der Nähe und deine Auswahl auf der Karte.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "Unter Eigenschaften findest du die Einstellungen der aktiven Ebenen. Ein farbiger Punkt kennzeichnet jede Ebene.", + "Press the compass to face north": "Drücke auf den Kompass, um die Ansicht nach Norden auszurichten", + "Tilt the camera for a 3D view": "Neige die Kamera für eine 3D-Ansicht", + "Zoom out to the whole globe": "Zoome heraus, um den ganzen Globus zu sehen", + "Copy a link to exactly this view": "Kopiere einen Link zu genau dieser Ansicht", + "Turn off every layer at once": "Deaktiviere alle Ebenen auf einmal", + "Press Draw to start drawing on the map": "Drücke „Zeichnen“, um auf der Karte zu zeichnen", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Wähle „Linie“, um eine Strecke zu messen, oder „Fläche“ für ihre Größe, und klicke Punkte auf der Karte; Doppelklick oder Enter schließt ab", + "End guide": "Anleitung beenden", + "to end": "zum Beenden", + "Guide · {topic}": "Anleitung · {topic}", + "Guide": "Anleitung", + "Next": "Weiter", + "Press the highlighted control": "Drücke das hervorgehobene Bedienelement", + "Finish": "Fertig", + "Skip step": "Schritt überspringen", + "Authoring": "Szenen", + "Visual styles": "Darstellungsstile", + "HUD": "HUD-Anzeige", + "Tilt / 3D view": "Neigung und 3D-Ansicht", + "Sharing this view": "Diese Ansicht teilen", + "Clearing all layers": "Alle Ebenen deaktivieren", + "Changing the map": "Karte wechseln", + "The scope": "Der Scope", + "Searching layers": "Ebenen suchen", + "Filtering layers": "Ebenen filtern", + "Jumping between layer groups": "Zwischen Ebenengruppen springen", + "Keys and language": "Schlüssel und Sprache", + "Panels at the screen edge": "Bedienfelder am Bildschirmrand", + "The Context panel": "Das Bedienfeld Kontext", + "Layer properties": "Ebeneneigenschaften", + "Drawing and measuring": "Zeichnen und Messen", + "Style: Noir": "Stil: Noir", + "Style: Thermal": "Stil: Wärmebild", + "Style: Night vision": "Stil: Nachtsicht", + "Style: Retro": "Stil: Retro", + "Style: Anime": "Stil: Anime", + "Style: Normal": "Stil: Normal", + "Map: OpenStreetMap": "Karte: OpenStreetMap", + "Map: Bing aerial": "Karte: Bing-Luftbilder", + "Map: Photoreal 3D": "Karte: Fotorealistisches 3D", + "Map: Esri imagery": "Karte: Esri-Bildmaterial", + "Clear all layers": "Alle Ebenen deaktivieren", + "Share this view": "Diese Ansicht teilen", + "Orbit": "Umlauf", + "Close all panels": "Alle Bedienfelder schließen", + "Close left panel": "Linkes Bedienfeld schließen", + "Close right panel": "Rechtes Bedienfeld schließen", + "Open Utilities": "Werkzeuge öffnen", + "Open Authoring": "Szenen öffnen", + "Open Visual": "Darstellung öffnen", + "Open Context": "Kontext öffnen", + "Stop camera": "Kamerabewegung stoppen", + "HUD on": "HUD einschalten", + "HUD off": "HUD ausschalten", + "Enter cockpit": "Ins Cockpit wechseln", + "Talk to GEV": "Mit GEV sprechen", + "{layer} on": "{layer} aktiv", + "{layer} off": "{layer} inaktiv", + "Close {panel}": "{panel} schließen", + "Cockpit": "Cockpit-Ansicht", + "Follow {target}": "{target} verfolgen", + "Coordinates": "Koordinaten", + "Go to {where}": "Zu {where} wechseln", + "Ask GEV: “{query}”": "GEV fragen: „{query}“", + "Opens chat": "Öffnet den Chat", + "Go to {place}": "Zu {place} wechseln", + "Place or coordinates": "Ort oder Koordinaten", + "Search “{query}” as a place anyway": "„{query}“ trotzdem als Ort suchen", + "Turn on": "Einschalten", + "Turn off": "Ausschalten", + "Command": "Befehl", + "No layers are on": "Keine Ebenen aktiv", + "No matching layers": "Keine passenden Ebenen", + "Show me {thing} settings": "Einstellungen für {thing} zeigen", + "Show me how: {thing}": "Anleitung anzeigen: {thing}", + "Do all": "Alles ausführen", + "Do it": "Ausführen", + "Follow {name}": "{name} verfolgen", + "Camera": "Kamera", + "Cockpit behind {name}": "Cockpit-Ansicht hinter {name}", + "Close {name}": "{name} schließen", + "Turn on {layer} here": "{layer} hier aktivieren", + "this view": "diese Ansicht", + "What's here?": "Was gibt es hier?", + "Show {what} in {place} ({count} items)": { + "one": "{what} in der Region {place} anzeigen ({count} Element)", + "other": "{what} in der Region {place} anzeigen ({count} Elemente)" + }, + "Go there": "Dorthin wechseln", + "Open draw options": "Zeichenoptionen öffnen" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 511439532a..38c484b85f 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -4242,5 +4242,126 @@ "Move down": "Bajar", "Click a shot to go to it, double-click to rename.": "Haz clic en un plano para ir a él y doble clic para cambiarle el nombre.", "Back to live at the starting view": "Volver al directo en la vista inicial", - "Exit cockpit to fly to a bike share city": "Sal de la cabina para volar a una ciudad con bicicletas compartidas" + "Exit cockpit to fly to a bike share city": "Sal de la cabina para volar a una ciudad con bicicletas compartidas", + "Open {panel}": "Abrir {panel}", + "Visual": "Apariencia", + "Open Properties: settings for the layers that are on": "Abre Propiedades para ajustar las capas activas", + "Data layers": "Capas de datos", + "{layer} options. {options}": "Opciones de {layer}. {options}", + "{layer} options appear here once it has loaded.": "Las opciones de {layer} aparecerán aquí cuando se cargue la capa.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Las etiquetas identifican los elementos de {layer} en el mapa. Densidad ajusta cuántos se etiquetan. Desvanecimiento y Exterior controlan cómo se atenúan fuera de la mirilla.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "Modelos 3D: Proximidad solo muestra los aviones cercanos en 3D. Todos muestra cada avión en 3D.", + "Press search to find {layer} in the list": "Pulsa el botón de búsqueda para encontrar {layer} en la lista", + "Type {layer}": "Escribe {layer}", + "Turn on {layer} with its switch": "Activa {layer} con su interruptor", + "{layer} are easiest to see from the globe view": "La vista del globo es la mejor para ver {layer}", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Los elementos de {layer} están repartidos por una zona amplia y apenas se ven a esta distancia. Aleja el mapa o pulsa el botón del globo.", + "{layer} is on. Want to fine-tune what it shows?": "{layer} está activa. ¿Quieres ajustar lo que se muestra?", + "Show settings": "Mostrar ajustes", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Elige un estilo: Normal, CRT, NVG, FLIR, Anime o Noir (teclas 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "En Fuente del mapa, elige el mapa base: Google 3D, Bing, Esri u OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Activa o desactiva aquí el HUD. En Disposición, elige Táctica, Mínima o Ciber.", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "Mirilla encuadra la vista en un círculo. Difuminado suaviza el borde y Opacidad regula la sombra exterior.", + "Clean UI hides the panels and readouts for a clear view": "Interfaz limpia oculta los paneles y los indicadores para despejar la vista", + "Press search, then type part of a layer name or source": "Pulsa el botón de búsqueda y escribe parte del nombre o la fuente de una capa", + "Type to narrow the list; Esc clears it": "Escribe para acotar la lista. Pulsa Esc para borrar la búsqueda.", + "Filter shows only layers that are on or off, or one category": "El filtro muestra solo las capas activas, las inactivas o las de una categoría", + "Open the filter": "Abre el filtro", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Elige un estado (activadas o desactivadas) y una categoría. Cada filtro aparece como una etiqueta que puedes quitar.", + "Hover a tick to see its group; click to jump there": "Pasa el cursor sobre una marca para ver su grupo y haz clic para ir a él", + "Add provider keys with Power Up, or change the language": "Usa Power Up para añadir claves de proveedores o cambia el idioma", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Pulsa este botón para deslizar los paneles sobre la barra lateral hasta el borde de la pantalla. Vuelve a pulsarlo para devolverlos a su sitio.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "Contexto describe la vista: el tiempo, los peligros, los elementos cercanos de tus capas y lo que selecciones en el mapa.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "Propiedades reúne los ajustes de las capas activas. Cada capa se indica con un punto de color.", + "Press the compass to face north": "Pulsa la brújula para orientar la vista hacia el norte", + "Tilt the camera for a 3D view": "Inclina la cámara para obtener una vista 3D", + "Zoom out to the whole globe": "Aleja el mapa para ver todo el globo", + "Copy a link to exactly this view": "Copia un enlace a esta vista exacta", + "Turn off every layer at once": "Desactiva todas las capas de una vez", + "Press Draw to start drawing on the map": "Pulsa «Dibujo» para empezar a dibujar en el mapa", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Elige «Línea» para medir una distancia o «Área» para su tamaño y haz clic en puntos del mapa; doble clic o Intro para terminar", + "End guide": "Finalizar guía", + "to end": "para salir", + "Guide · {topic}": "Guía · {topic}", + "Guide": "Guía", + "Next": "Siguiente", + "Press the highlighted control": "Pulsa el control resaltado", + "Finish": "Finalizar", + "Skip step": "Omitir paso", + "Authoring": "Creación", + "Visual styles": "Estilos visuales", + "HUD": "Indicador HUD", + "Tilt / 3D view": "Inclinación y vista 3D", + "Sharing this view": "Compartir esta vista", + "Clearing all layers": "Desactivar todas las capas", + "Changing the map": "Cambiar el mapa", + "The scope": "La mirilla", + "Searching layers": "Buscar capas", + "Filtering layers": "Filtrar capas", + "Jumping between layer groups": "Saltar entre grupos de capas", + "Keys and language": "Claves e idioma", + "Panels at the screen edge": "Paneles en el borde de la pantalla", + "The Context panel": "El panel de contexto", + "Layer properties": "Propiedades de las capas", + "Drawing and measuring": "Dibujar y medir", + "Style: Noir": "Estilo: Noir", + "Style: Thermal": "Estilo: Térmico", + "Style: Night vision": "Estilo: Visión nocturna", + "Style: Retro": "Estilo: Retro", + "Style: Anime": "Estilo: Anime", + "Style: Normal": "Estilo: Normal", + "Map: OpenStreetMap": "Mapa: OpenStreetMap", + "Map: Bing aerial": "Mapa: Vista aérea de Bing", + "Map: Photoreal 3D": "Mapa: 3D fotorrealista", + "Map: Esri imagery": "Mapa: Imágenes de Esri", + "Clear all layers": "Desactivar todas las capas", + "Share this view": "Compartir esta vista", + "Orbit": "Orbitar", + "Close all panels": "Cerrar todos los paneles", + "Close left panel": "Cerrar el panel izquierdo", + "Close right panel": "Cerrar el panel derecho", + "Open Utilities": "Abrir Utilidades", + "Open Authoring": "Abrir Creación", + "Open Visual": "Abrir Apariencia", + "Open Context": "Abrir Contexto", + "Stop camera": "Detener la cámara", + "HUD on": "Activar HUD", + "HUD off": "Desactivar HUD", + "Enter cockpit": "Entrar en la cabina", + "Talk to GEV": "Hablar con GEV", + "{layer} on": "{layer} activada", + "{layer} off": "{layer} desactivada", + "Close {panel}": "Cerrar {panel}", + "Cockpit": "Cabina", + "Follow {target}": "Seguir a {target}", + "Coordinates": "Coordenadas", + "Go to {where}": "Ir a {where}", + "Ask GEV: “{query}”": "Preguntar a GEV: «{query}»", + "Opens chat": "Abre el chat", + "Go to {place}": "Ir a {place}", + "Place or coordinates": "Lugar o coordenadas", + "Search “{query}” as a place anyway": "Buscar «{query}» como lugar de todos modos", + "Turn on": "Activar", + "Turn off": "Desactivar", + "Command": "Comando", + "No layers are on": "No hay capas activas", + "No matching layers": "No se encontraron capas", + "Show me {thing} settings": "Muéstrame los ajustes de {thing}", + "Show me how: {thing}": "Muéstrame cómo: {thing}", + "Do all": "Ejecutar todo", + "Do it": "Ejecutar", + "Follow {name}": "Seguir a {name}", + "Camera": "Cámara", + "Cockpit behind {name}": "Vista de cabina detrás de {name}", + "Close {name}": "Cerrar {name}", + "Turn on {layer} here": "Activar {layer} aquí", + "this view": "esta vista", + "What's here?": "¿Qué hay aquí?", + "Show {what} in {place} ({count} items)": { + "one": "Mostrar {what} en {place} ({count} elemento)", + "many": "Mostrar {what} en {place} ({count} de elementos)", + "other": "Mostrar {what} en {place} ({count} elementos)" + }, + "Go there": "Ir allí", + "Open draw options": "Abrir opciones de dibujo" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 117b8d7129..95725609fb 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -4242,5 +4242,126 @@ "Move down": "Descendre", "Click a shot to go to it, double-click to rename.": "Cliquez sur un plan pour y aller, double-cliquez pour le renommer.", "Back to live at the starting view": "Revenir au direct dans la vue de départ", - "Exit cockpit to fly to a bike share city": "Quittez le cockpit pour aller vers une ville avec vélos en libre-service" + "Exit cockpit to fly to a bike share city": "Quittez le cockpit pour aller vers une ville avec vélos en libre-service", + "Open {panel}": "Ouvrir {panel}", + "Visual": "Affichage", + "Open Properties: settings for the layers that are on": "Ouvrez Propriétés pour régler les couches actives", + "Data layers": "Couches de données", + "{layer} options. {options}": "Options de {layer}. {options}", + "{layer} options appear here once it has loaded.": "Les options de {layer} s’affichent ici une fois la couche chargée.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Les étiquettes identifient les éléments de {layer} sur la carte. Densité règle leur nombre. Fondu et Extérieur règlent leur atténuation hors de la lunette.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "Modèles 3D : Proximité affiche les appareils en 3D uniquement de près. Tous affiche chaque appareil en 3D.", + "Press search to find {layer} in the list": "Appuyez sur le bouton de recherche pour trouver {layer} dans la liste", + "Type {layer}": "Saisissez {layer}", + "Turn on {layer} with its switch": "Activez {layer} avec son interrupteur", + "{layer} are easiest to see from the globe view": "La vue du globe est idéale pour voir {layer}", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Les éléments de {layer} sont répartis sur une grande zone et peu sont visibles à cette distance. Dézoomez ou appuyez sur le bouton du globe.", + "{layer} is on. Want to fine-tune what it shows?": "{layer} est activée. Voulez-vous affiner son affichage ?", + "Show settings": "Afficher les réglages", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Choisissez un style : Normal, CRT, NVG, FLIR, Anime ou Noir (touches 1 à 6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "Dans Source de la carte, choisissez le fond de carte : Google 3D, Bing, Esri ou OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Activez ou désactivez ici le HUD. Dans Disposition, choisissez Tactique, Minimal ou Cyber.", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "La lunette cadre la vue dans un cercle. Adouci lisse le bord et Opacité règle l’assombrissement à l’extérieur.", + "Clean UI hides the panels and readouts for a clear view": "Vue épurée masque les panneaux et les indicateurs pour dégager la vue", + "Press search, then type part of a layer name or source": "Appuyez sur Rechercher, puis saisissez une partie du nom ou de la source d’une couche", + "Type to narrow the list; Esc clears it": "Saisissez du texte pour affiner la liste. Échap efface la recherche.", + "Filter shows only layers that are on or off, or one category": "Le filtre affiche uniquement les couches actives, inactives ou d’une catégorie", + "Open the filter": "Ouvrir le filtre", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Choisissez un état (actives ou inactives) et une catégorie. Chaque filtre s’affiche sous forme d’étiquette que vous pouvez retirer.", + "Hover a tick to see its group; click to jump there": "Survolez un repère pour voir son groupe, puis cliquez pour y accéder", + "Add provider keys with Power Up, or change the language": "Ajoutez des clés de fournisseur avec Power Up ou changez la langue", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Appuyez ici pour faire glisser les panneaux sur la barre latérale jusqu’au bord de l’écran. Appuyez à nouveau pour les remettre en place.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "Contexte décrit la vue : la météo, les dangers, les éléments à proximité dans vos couches et ce que vous sélectionnez sur la carte.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "Propriétés réunit les réglages des couches actives, chacune signalée par un point de couleur.", + "Press the compass to face north": "Appuyez sur la boussole pour orienter la vue vers le nord", + "Tilt the camera for a 3D view": "Inclinez la caméra pour obtenir une vue 3D", + "Zoom out to the whole globe": "Dézoomez pour voir le globe entier", + "Copy a link to exactly this view": "Copiez un lien vers cette vue exacte", + "Turn off every layer at once": "Désactivez toutes les couches d’un coup", + "Press Draw to start drawing on the map": "Appuyez sur « Dessin » pour commencer à dessiner sur la carte", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Choisissez « Ligne » pour mesurer une distance ou « Zone » pour sa surface, puis cliquez des points sur la carte ; double-clic ou Entrée pour terminer", + "End guide": "Quitter le guide", + "to end": "pour quitter", + "Guide · {topic}": "Guide : {topic}", + "Guide": "Aide", + "Next": "Suivant", + "Press the highlighted control": "Appuyez sur la commande mise en évidence", + "Finish": "Terminer", + "Skip step": "Passer cette étape", + "Authoring": "Création", + "Visual styles": "Styles visuels", + "HUD": "Affichage tête haute", + "Tilt / 3D view": "Inclinaison et vue 3D", + "Sharing this view": "Partager cette vue", + "Clearing all layers": "Désactiver toutes les couches", + "Changing the map": "Changer le fond de carte", + "The scope": "La lunette", + "Searching layers": "Rechercher des couches", + "Filtering layers": "Filtrer les couches", + "Jumping between layer groups": "Passer d’un groupe de couches à l’autre", + "Keys and language": "Clés et langue", + "Panels at the screen edge": "Panneaux au bord de l’écran", + "The Context panel": "Le panneau Contexte", + "Layer properties": "Propriétés des couches", + "Drawing and measuring": "Dessiner et mesurer", + "Style: Noir": "Style : Noir", + "Style: Thermal": "Style : Thermique", + "Style: Night vision": "Style : Vision nocturne", + "Style: Retro": "Style : Rétro", + "Style: Anime": "Style : Anime", + "Style: Normal": "Style : Normal", + "Map: OpenStreetMap": "Carte : OpenStreetMap", + "Map: Bing aerial": "Carte : Vue aérienne Bing", + "Map: Photoreal 3D": "Carte : 3D photoréaliste", + "Map: Esri imagery": "Carte : Imagerie Esri", + "Clear all layers": "Désactiver toutes les couches", + "Share this view": "Partager cette vue", + "Orbit": "Orbite", + "Close all panels": "Fermer tous les panneaux", + "Close left panel": "Fermer le panneau de gauche", + "Close right panel": "Fermer le panneau de droite", + "Open Utilities": "Ouvrir Outils", + "Open Authoring": "Ouvrir Création", + "Open Visual": "Ouvrir Affichage", + "Open Context": "Ouvrir Contexte", + "Stop camera": "Arrêter la caméra", + "HUD on": "Activer le HUD", + "HUD off": "Désactiver le HUD", + "Enter cockpit": "Entrer dans le cockpit", + "Talk to GEV": "Parler à GEV", + "{layer} on": "{layer} activée", + "{layer} off": "{layer} désactivée", + "Close {panel}": "Fermer {panel}", + "Cockpit": "Poste de pilotage", + "Follow {target}": "Suivre {target}", + "Coordinates": "Coordonnées", + "Go to {where}": "Aller à {where}", + "Ask GEV: “{query}”": "Demander à GEV : « {query} »", + "Opens chat": "Ouvre le chat", + "Go to {place}": "Aller à {place}", + "Place or coordinates": "Lieu ou coordonnées", + "Search “{query}” as a place anyway": "Rechercher « {query} » comme lieu quand même", + "Turn on": "Activer", + "Turn off": "Désactiver", + "Command": "Commande", + "No layers are on": "Aucune couche active", + "No matching layers": "Aucune couche correspondante", + "Show me {thing} settings": "Montrez-moi les réglages de {thing}", + "Show me how: {thing}": "Montrez-moi comment faire : {thing}", + "Do all": "Tout exécuter", + "Do it": "Exécuter", + "Follow {name}": "Suivre {name}", + "Camera": "Caméra", + "Cockpit behind {name}": "Vue cockpit derrière {name}", + "Close {name}": "Fermer {name}", + "Turn on {layer} here": "Activer {layer} ici", + "this view": "cette vue", + "What's here?": "Qu’y a-t-il ici ?", + "Show {what} in {place} ({count} items)": { + "one": "Afficher {what} dans la zone de {place} ({count} élément)", + "many": "Afficher {what} dans la zone de {place} ({count} d’éléments)", + "other": "Afficher {what} dans la zone de {place} ({count} éléments)" + }, + "Go there": "Y aller", + "Open draw options": "Ouvrir les options de dessin" } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 16aabce453..bda1806ab2 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -4242,5 +4242,126 @@ "Move down": "הזזה למטה", "Click a shot to go to it, double-click to rename.": "לחץ על שוט כדי לעבור אליו, לחיצה כפולה לשינוי שם.", "Back to live at the starting view": "חזרה לשידור החי בתצוגת הפתיחה", - "Exit cockpit to fly to a bike share city": "צא מתא הטייס כדי לטוס לעיר עם שיתוף אופניים" + "Exit cockpit to fly to a bike share city": "צא מתא הטייס כדי לטוס לעיר עם שיתוף אופניים", + "Open {panel}": "פתיחת {panel}", + "Visual": "תצוגה", + "Open Properties: settings for the layers that are on": "פתיחת מאפיינים: הגדרות השכבות הפעילות", + "Data layers": "שכבות נתונים", + "{layer} options. {options}": "אפשרויות {layer}: ‏{options}", + "{layer} options appear here once it has loaded.": "האפשרויות של {layer} יופיעו כאן לאחר הטעינה.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "תוויות מסמנות את {layer} במפה. צפיפות קובעת כמה תוויות יוצגו, ועמעום וחוץ קובעים כיצד הן מתמעטות מחוץ לסקופ.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "מודלים בתלת־ממד: קרבה מציגה מודלים רק לכלי טיס קרובים. הכול מציגה מודל לכל כלי טיס.", + "Press search to find {layer} in the list": "לחצו על החיפוש כדי למצוא את {layer} ברשימה", + "Type {layer}": "הקלידו {layer}", + "Turn on {layer} with its switch": "הפעילו את {layer} באמצעות המתג", + "{layer} are easiest to see from the globe view": "הכי קל לראות את {layer} בתצוגת הגלובוס", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "פריטי {layer} פרוסים על פני שטח רחב, ולכן רק מעטים נראים בתקריב הזה. התרחקו או עברו לתצוגת הגלובוס.", + "{layer} is on. Want to fine-tune what it shows?": "השכבה {layer} פעילה. לשנות את מה שמופיע בה?", + "Show settings": "הצגת הגדרות", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "בחרו סגנון: רגיל, ‏CRT, ‏NVG, ‏FLIR, אנימה או נואר (מקשים 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "במקור מפה, בחרו את מפת הבסיס: ‏Google 3D, ‏Bing, ‏Esri או OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "כאן אפשר להפעיל או לכבות את התצוגה העילית. באפשרויות הפריסה בחרו טקטי, מינימלי או סייבר", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "הסקופ תוחם את התצוגה בעיגול. ריכוך מרכך את השוליים, ואטימות קובעת כמה כהה האזור שמחוץ לעיגול.", + "Clean UI hides the panels and readouts for a clear view": "הממשק הנקי מסתיר את הלוחות והנתונים כדי לפנות את התצוגה", + "Press search, then type part of a layer name or source": "לחצו על החיפוש והקלידו חלק משם השכבה או המקור שלה", + "Type to narrow the list; Esc clears it": "הקלידו כדי לצמצם את הרשימה, והקישו Esc כדי לנקות את החיפוש", + "Filter shows only layers that are on or off, or one category": "אפשר לסנן לפי שכבות פעילות או כבויות, או לפי קטגוריה אחת", + "Open the filter": "פתיחת הסינון", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "בחרו מצב (פעיל או כבוי) וקטגוריה. כל בחירה מופיעה כתג שאפשר להסיר", + "Hover a tick to see its group; click to jump there": "רחפו מעל סימון כדי לראות את הקבוצה שלו ולחצו כדי לעבור אליה", + "Add provider keys with Power Up, or change the language": "הוסיפו מפתחות של ספקים דרך Power Up, או שנו את השפה", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "לחצו כדי להעביר את הלוחות מעבר לסרגל אל קצה המסך, ולחצו שוב כדי להחזיר אותם", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "לוח ההקשר מתאר את מה שנראה בתצוגה: מזג אוויר, סכנות, נתונים מהשכבות באזור וכל פריט שתבחרו במפה", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "במאפיינים נמצאות הגדרות השכבות הפעילות. כל שכבה מסומנת בנקודה צבעונית", + "Press the compass to face north": "לחצו על המצפן כדי לפנות צפונה", + "Tilt the camera for a 3D view": "הטו את המצלמה כדי לקבל תצוגה תלת־ממדית", + "Zoom out to the whole globe": "התרחקו עד שכל כדור הארץ יופיע", + "Copy a link to exactly this view": "העתיקו קישור שפותח את התצוגה הזאת בדיוק", + "Turn off every layer at once": "כבו את כל השכבות בבת אחת", + "Press Draw to start drawing on the map": "לחצו על „שרטוט” כדי להתחיל לשרטט על המפה", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "בחרו „קו” כדי למדוד מרחק או „שטח” כדי למדוד גודל, ואז לחצו על נקודות במפה; לחיצה כפולה או Enter מסיימים", + "End guide": "סיום המדריך", + "to end": "לסיום", + "Guide · {topic}": "מדריך · {topic}", + "Guide": "מדריך", + "Next": "הבא", + "Press the highlighted control": "לחצו על הפקד המודגש", + "Finish": "סיום", + "Skip step": "דילוג על השלב", + "Authoring": "כלי היצירה", + "Visual styles": "סגנונות תצוגה", + "HUD": "תצוגה עילית", + "Tilt / 3D view": "הטיה ותצוגה תלת־ממדית", + "Sharing this view": "שיתוף התצוגה הזאת", + "Clearing all layers": "כיבוי כל השכבות", + "Changing the map": "שינוי המפה", + "The scope": "הסקופ", + "Searching layers": "חיפוש שכבות", + "Filtering layers": "סינון שכבות", + "Jumping between layer groups": "מעבר בין קבוצות שכבות", + "Keys and language": "מפתחות ושפה", + "Panels at the screen edge": "לוחות בקצה המסך", + "The Context panel": "לוח ההקשר", + "Layer properties": "מאפייני שכבות", + "Drawing and measuring": "שרטוט ומדידה", + "Style: Noir": "סגנון: נואר", + "Style: Thermal": "סגנון: תרמי", + "Style: Night vision": "סגנון: ראיית לילה", + "Style: Retro": "סגנון: רטרו", + "Style: Anime": "סגנון: אנימה", + "Style: Normal": "סגנון: רגיל", + "Map: OpenStreetMap": "מפה: ‏OpenStreetMap", + "Map: Bing aerial": "מפה: תצלומי אוויר של Bing", + "Map: Photoreal 3D": "מפה: תלת־ממד מציאותי", + "Map: Esri imagery": "מפה: תצלומי Esri", + "Clear all layers": "כיבוי כל השכבות", + "Share this view": "שיתוף התצוגה הזאת", + "Orbit": "הקפה", + "Close all panels": "סגירת כל הלוחות", + "Close left panel": "סגירת הלוח השמאלי", + "Close right panel": "סגירת הלוח הימני", + "Open Utilities": "פתיחת כלי העזר", + "Open Authoring": "פתיחת כלי היצירה", + "Open Visual": "פתיחת הגדרות התצוגה", + "Open Context": "פתיחת לוח ההקשר", + "Stop camera": "עצירת תנועת המצלמה", + "HUD on": "הפעלת תצוגה עילית", + "HUD off": "כיבוי תצוגה עילית", + "Enter cockpit": "כניסה לתא הטייס", + "Talk to GEV": "דיבור עם GEV", + "{layer} on": "הפעלת {layer}", + "{layer} off": "כיבוי {layer}", + "Close {panel}": "סגירת {panel}", + "Cockpit": "תא טייס", + "Follow {target}": "מעקב אחר {target}", + "Coordinates": "קואורדינטות", + "Go to {where}": "מעבר אל {where}", + "Ask GEV: “{query}”": "לשאול את GEV: ‏״{query}״", + "Opens chat": "פותח את הצ׳אט", + "Go to {place}": "מעבר אל {place}", + "Place or coordinates": "מקום או קואורדינטות", + "Search “{query}” as a place anyway": "חפש את „{query}” כמקום בכל זאת", + "Turn on": "הפעלה", + "Turn off": "כיבוי", + "Command": "פקודה", + "No layers are on": "אין שכבות פעילות", + "No matching layers": "אין שכבות תואמות", + "Show me {thing} settings": "הצגת ההגדרות של {thing}", + "Show me how: {thing}": "איך עושים זאת: ‏{thing}", + "Do all": "ביצוע כל הפעולות", + "Do it": "ביצוע הפעולה", + "Follow {name}": "מעקב אחר {name}", + "Camera": "מצלמה", + "Cockpit behind {name}": "תצוגת תא טייס מאחורי {name}", + "Close {name}": "סגירת {name}", + "Turn on {layer} here": "הפעלת {layer} כאן", + "this view": "התצוגה הזאת", + "What's here?": "מה יש כאן?", + "Show {what} in {place} ({count} items)": { + "one": "הצגת {what} ב{place} ({count} פריט)", + "two": "הצגת {what} ב{place} ({count} פריטים)", + "other": "הצגת {what} ב{place} ({count} פריטים)" + }, + "Go there": "מעבר למקום", + "Open draw options": "פתיחת אפשרויות הציור" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 8ab4346305..45b64e9c08 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -4242,5 +4242,126 @@ "Move down": "Sposta giù", "Click a shot to go to it, double-click to rename.": "Fai clic su uno scatto per andarci, doppio clic per rinominarlo.", "Back to live at the starting view": "Torna alla diretta nella vista iniziale", - "Exit cockpit to fly to a bike share city": "Esci dalla cabina per volare verso una città con bike sharing" + "Exit cockpit to fly to a bike share city": "Esci dalla cabina per volare verso una città con bike sharing", + "Open {panel}": "Apri {panel}", + "Visual": "Aspetto", + "Open Properties: settings for the layers that are on": "Apri Proprietà per configurare i livelli attivi", + "Data layers": "Livelli dati", + "{layer} options. {options}": "Opzioni di {layer}. {options}", + "{layer} options appear here once it has loaded.": "Le opzioni di {layer} appaiono qui dopo il caricamento del livello.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Le etichette identificano gli elementi di {layer} sulla mappa. Densità ne regola il numero. Dissolvenza ed Esterno regolano quanto si attenuano fuori dallo Scope.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "Modelli 3D: Prossimità mostra in 3D solo gli aerei vicini. Tutti mostra in 3D ogni aereo.", + "Press search to find {layer} in the list": "Premi il pulsante di ricerca per trovare {layer} nell’elenco", + "Type {layer}": "Digita {layer}", + "Turn on {layer} with its switch": "Attiva {layer} con il suo interruttore", + "{layer} are easiest to see from the globe view": "La vista del globo è ideale per vedere {layer}", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Gli elementi di {layer} sono sparsi su un’area ampia e da vicino se ne vedono pochi. Riduci lo zoom o premi il pulsante del globo.", + "{layer} is on. Want to fine-tune what it shows?": "{layer} è attivo. Vuoi regolare ciò che mostra?", + "Show settings": "Mostra impostazioni", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Scegli uno stile: Normale, CRT, NVG, FLIR, Anime o Noir (tasti 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "In Fonte mappa, scegli la mappa di base: Google 3D, Bing, Esri o OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Attiva o disattiva qui l’HUD. In Layout, scegli Tattico, Minimale o Cyber.", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "Scope inquadra la vista in un cerchio. Sfumatura ne ammorbidisce il bordo e Opacità regola quanto scurire l’esterno.", + "Clean UI hides the panels and readouts for a clear view": "UI pulita nasconde i pannelli e gli indicatori per lasciare libera la vista", + "Press search, then type part of a layer name or source": "Premi il pulsante di ricerca, poi digita parte del nome o della fonte di un livello", + "Type to narrow the list; Esc clears it": "Digita per restringere l’elenco. Premi Esc per azzerare la ricerca.", + "Filter shows only layers that are on or off, or one category": "Il filtro mostra solo i livelli attivi, quelli inattivi o quelli di una categoria", + "Open the filter": "Apri il filtro", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Scegli uno stato (attivi o disattivati) e una categoria. Ogni filtro appare come un’etichetta che puoi rimuovere.", + "Hover a tick to see its group; click to jump there": "Passa il puntatore su un segno per vederne il gruppo e fai clic per raggiungerlo", + "Add provider keys with Power Up, or change the language": "Aggiungi le chiavi dei fornitori con Power Up o cambia la lingua", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Premi qui per far scorrere i pannelli sopra la barra laterale fino al bordo dello schermo. Premi di nuovo per riportarli al loro posto.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "Contesto descrive la vista: meteo, pericoli, elementi vicini dei tuoi livelli e ciò che selezioni sulla mappa.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "Proprietà raccoglie le impostazioni dei livelli attivi. Ogni livello è indicato da un punto colorato.", + "Press the compass to face north": "Premi la bussola per orientare la vista a nord", + "Tilt the camera for a 3D view": "Inclina la fotocamera per una vista 3D", + "Zoom out to the whole globe": "Riduci lo zoom per vedere l’intero globo", + "Copy a link to exactly this view": "Copia un link a questa esatta vista", + "Turn off every layer at once": "Disattiva tutti i livelli in una volta", + "Press Draw to start drawing on the map": "Premi «Disegno» per iniziare a disegnare sulla mappa", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Scegli «Linea» per misurare una distanza o «Area» per la sua superficie, poi fai clic sui punti della mappa; doppio clic o Invio per finire", + "End guide": "Chiudi guida", + "to end": "per uscire", + "Guide · {topic}": "Guida · {topic}", + "Guide": "Guida", + "Next": "Avanti", + "Press the highlighted control": "Premi il comando evidenziato", + "Finish": "Fine", + "Skip step": "Salta passaggio", + "Authoring": "Creazione", + "Visual styles": "Stili visivi", + "HUD": "Visore HUD", + "Tilt / 3D view": "Inclinazione e vista 3D", + "Sharing this view": "Condividere questa vista", + "Clearing all layers": "Disattivare tutti i livelli", + "Changing the map": "Cambiare la mappa", + "The scope": "Lo Scope", + "Searching layers": "Cercare livelli", + "Filtering layers": "Filtrare i livelli", + "Jumping between layer groups": "Passare da un gruppo di livelli all’altro", + "Keys and language": "Chiavi e lingua", + "Panels at the screen edge": "Pannelli al bordo dello schermo", + "The Context panel": "Il pannello Contesto", + "Layer properties": "Proprietà dei livelli", + "Drawing and measuring": "Disegnare e misurare", + "Style: Noir": "Stile: Noir", + "Style: Thermal": "Stile: Termico", + "Style: Night vision": "Stile: Visione notturna", + "Style: Retro": "Stile: Retrò", + "Style: Anime": "Stile: Anime", + "Style: Normal": "Stile: Normale", + "Map: OpenStreetMap": "Mappa: OpenStreetMap", + "Map: Bing aerial": "Mappa: Vista aerea Bing", + "Map: Photoreal 3D": "Mappa: 3D fotorealistico", + "Map: Esri imagery": "Mappa: Immagini Esri", + "Clear all layers": "Disattiva tutti i livelli", + "Share this view": "Condividi questa vista", + "Orbit": "Orbita", + "Close all panels": "Chiudi tutti i pannelli", + "Close left panel": "Chiudi il pannello sinistro", + "Close right panel": "Chiudi il pannello destro", + "Open Utilities": "Apri Strumenti", + "Open Authoring": "Apri Creazione", + "Open Visual": "Apri Aspetto", + "Open Context": "Apri Contesto", + "Stop camera": "Ferma la fotocamera", + "HUD on": "Attiva HUD", + "HUD off": "Disattiva HUD", + "Enter cockpit": "Entra nella cabina", + "Talk to GEV": "Parla con GEV", + "{layer} on": "{layer} attivo", + "{layer} off": "{layer} disattivo", + "Close {panel}": "Chiudi {panel}", + "Cockpit": "Cabina di pilotaggio", + "Follow {target}": "Segui {target}", + "Coordinates": "Coordinate", + "Go to {where}": "Vai a {where}", + "Ask GEV: “{query}”": "Chiedi a GEV: «{query}»", + "Opens chat": "Apre la chat", + "Go to {place}": "Vai a {place}", + "Place or coordinates": "Luogo o coordinate", + "Search “{query}” as a place anyway": "Cerca «{query}» come luogo comunque", + "Turn on": "Attiva", + "Turn off": "Disattiva", + "Command": "Comando", + "No layers are on": "Nessun livello attivo", + "No matching layers": "Nessun livello corrispondente", + "Show me {thing} settings": "Mostrami le impostazioni di {thing}", + "Show me how: {thing}": "Mostrami come: {thing}", + "Do all": "Esegui tutto", + "Do it": "Esegui", + "Follow {name}": "Segui {name}", + "Camera": "Fotocamera", + "Cockpit behind {name}": "Vista cabina dietro {name}", + "Close {name}": "Chiudi {name}", + "Turn on {layer} here": "Attiva {layer} qui", + "this view": "questa vista", + "What's here?": "Cosa c’è qui?", + "Show {what} in {place} ({count} items)": { + "one": "Mostra {what} a {place} ({count} elemento)", + "many": "Mostra {what} a {place} ({count} di elementi)", + "other": "Mostra {what} a {place} ({count} elementi)" + }, + "Go there": "Vai lì", + "Open draw options": "Apri le opzioni di disegno" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 49d45a921b..0fe1a3c597 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -4036,5 +4036,124 @@ "Move down": "下へ移動", "Click a shot to go to it, double-click to rename.": "ショットをクリックしてそこへ移動、ダブルクリックで名前を変更します。", "Back to live at the starting view": "ライブに戻り、最初の表示へ", - "Exit cockpit to fly to a bike share city": "シェアサイクルのある都市へ移動するにはコックピットを終了してください" + "Exit cockpit to fly to a bike share city": "シェアサイクルのある都市へ移動するにはコックピットを終了してください", + "Open {panel}": "{panel}を開く", + "Visual": "表示", + "Open Properties: settings for the layers that are on": "プロパティを開く:オンになっているレイヤーの設定", + "Data layers": "データレイヤー", + "{layer} options. {options}": "{layer}のオプション:{options}", + "{layer} options appear here once it has loaded.": "読み込みが完了すると、{layer}のオプションがここに表示されます。", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "ラベルはマップ上の{layer}に名前を表示します。密度で表示数を、フェードと外側でスコープ外の表示を調整します。", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3Dモデル:近接は近くの機体だけを、すべては全機をモデルで表示します。", + "Press search to find {layer} in the list": "検索ボタンを押して、リストから{layer}を探します", + "Type {layer}": "{layer}を入力", + "Turn on {layer} with its switch": "スイッチを使って{layer}をオンにします", + "{layer} are easiest to see from the globe view": "{layer}は地球全体の表示で最も見やすくなります", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "{layer}は広範囲に分布しているため、拡大すると一部しか見えません。縮小するか、地球全体の表示に切り替えてください。", + "{layer} is on. Want to fine-tune what it shows?": "{layer}がオンになりました。表示内容を細かく調整しますか?", + "Show settings": "設定を表示", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "標準、CRT、NVG、FLIR、アニメ、ノワールからスタイルを選びます(キー1~6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "マップソースで背景地図を選びます:Google 3D、Bing、Esri、OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "ここでHUDをオン・オフできます。レイアウトでタクティカル、ミニマル、サイバーを選びます", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "スコープは表示範囲を円形に切り取ります。ぼかしで円の縁をなじませ、不透明度で円の外側の暗さを調整します。", + "Clean UI hides the panels and readouts for a clear view": "クリーンUIはパネルや表示情報を隠し、マップを見やすくします", + "Press search, then type part of a layer name or source": "検索ボタンを押し、レイヤー名やソース名の一部を入力します", + "Type to narrow the list; Esc clears it": "入力してリストを絞り込みます。Escキーで解除できます", + "Filter shows only layers that are on or off, or one category": "フィルターでは、オンかオフのレイヤーだけ、または指定したカテゴリだけを表示できます", + "Open the filter": "フィルターを開く", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "状態(オン・オフ)やカテゴリを選びます。選択項目は個別に解除できるチップとして表示されます", + "Hover a tick to see its group; click to jump there": "目盛りにカーソルを合わせるとグループがわかります。クリックするとそのグループに移動します", + "Add provider keys with Power Up, or change the language": "Power Upでプロバイダーのキーを追加するか、言語を変更します", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "ボタンを押すとパネルがレールを越えて画面の端に移動し、もう一度押すと戻ります", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "コンテキストでは、現在の表示範囲の天気や危険情報、近くのレイヤーデータ、マップ上で選んだ対象を確認できます", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "プロパティにはオンになっているレイヤーの設定があり、各レイヤーには色付きの点が付きます", + "Press the compass to face north": "コンパスを押して北を向きます", + "Tilt the camera for a 3D view": "カメラを傾けて3D表示にします", + "Zoom out to the whole globe": "地球全体が見えるまで縮小します", + "Copy a link to exactly this view": "現在の表示をそのまま開けるリンクをコピーします", + "Turn off every layer at once": "すべてのレイヤーを一度にオフにします", + "Press Draw to start drawing on the map": "「描画」を押すと地図に描き始めます", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "距離は「線」、面積は「範囲」を選び、地図上で点をクリックします。ダブルクリックまたは Enter で完了します", + "End guide": "ガイドを終了", + "to end": "で終了", + "Guide · {topic}": "ガイド · {topic}", + "Guide": "ガイド", + "Next": "次へ", + "Press the highlighted control": "強調表示されたコントロールを押してください", + "Finish": "完了", + "Skip step": "この手順をスキップ", + "Authoring": "作成ツール", + "Visual styles": "表示スタイル", + "HUD": "ヘッドアップ表示", + "Tilt / 3D view": "傾き・3D表示", + "Sharing this view": "現在の表示を共有", + "Clearing all layers": "すべてのレイヤーを解除", + "Changing the map": "マップを変更", + "The scope": "スコープ", + "Searching layers": "レイヤーを検索", + "Filtering layers": "レイヤーを絞り込む", + "Jumping between layer groups": "レイヤーグループ間を移動", + "Keys and language": "キーと言語", + "Panels at the screen edge": "画面端のパネル", + "The Context panel": "コンテキストパネル", + "Layer properties": "レイヤープロパティ", + "Drawing and measuring": "描画と計測", + "Style: Noir": "スタイル:ノワール", + "Style: Thermal": "スタイル:熱画像", + "Style: Night vision": "スタイル:暗視", + "Style: Retro": "スタイル:レトロ", + "Style: Anime": "スタイル:アニメ", + "Style: Normal": "スタイル:標準", + "Map: OpenStreetMap": "マップ:OpenStreetMap", + "Map: Bing aerial": "マップ:Bing航空写真", + "Map: Photoreal 3D": "マップ:写実的な3D", + "Map: Esri imagery": "マップ:Esri画像", + "Clear all layers": "すべてのレイヤーを解除", + "Share this view": "現在の表示を共有", + "Orbit": "周回", + "Close all panels": "すべてのパネルを閉じる", + "Close left panel": "左側のパネルを閉じる", + "Close right panel": "右側のパネルを閉じる", + "Open Utilities": "ユーティリティを開く", + "Open Authoring": "作成ツールを開く", + "Open Visual": "表示設定を開く", + "Open Context": "コンテキストを開く", + "Stop camera": "カメラを停止", + "HUD on": "HUDをオン", + "HUD off": "HUDをオフ", + "Enter cockpit": "コックピットに入る", + "Talk to GEV": "GEVと話す", + "{layer} on": "{layer}をオン", + "{layer} off": "{layer}をオフ", + "Close {panel}": "{panel}を閉じる", + "Cockpit": "コックピット", + "Follow {target}": "{target}を追跡", + "Coordinates": "座標", + "Go to {where}": "{where}に移動", + "Ask GEV: “{query}”": "GEVに質問:「{query}」", + "Opens chat": "チャットを開く", + "Go to {place}": "{place}に移動", + "Place or coordinates": "場所または座標", + "Search “{query}” as a place anyway": "「{query}」を場所として検索する", + "Turn on": "オンにする", + "Turn off": "オフにする", + "Command": "コマンド", + "No layers are on": "オンになっているレイヤーはありません", + "No matching layers": "該当するレイヤーはありません", + "Show me {thing} settings": "{thing}の設定を表示", + "Show me how: {thing}": "使い方を見る:{thing}", + "Do all": "まとめて実行", + "Do it": "実行", + "Follow {name}": "{name}を追跡", + "Camera": "カメラ", + "Cockpit behind {name}": "{name}の後方からコックピット表示", + "Close {name}": "{name}を閉じる", + "Turn on {layer} here": "ここで{layer}をオンにする", + "this view": "現在の表示", + "What's here?": "ここには何がある?", + "Show {what} in {place} ({count} items)": { + "other": "{place}の{what}を表示({count}件)" + }, + "Go there": "その場所に移動", + "Open draw options": "描画オプションを開く" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index c092ea9e8c..5e75f06d6c 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -4242,5 +4242,126 @@ "Move down": "Mover para baixo", "Click a shot to go to it, double-click to rename.": "Clique em um plano para ir até ele e clique duas vezes para renomeá-lo.", "Back to live at the starting view": "Voltar ao vivo na vista inicial", - "Exit cockpit to fly to a bike share city": "Saia do cockpit para voar até uma cidade com bicicletas compartilhadas" + "Exit cockpit to fly to a bike share city": "Saia do cockpit para voar até uma cidade com bicicletas compartilhadas", + "Open {panel}": "Abrir {panel}", + "Visual": "Aparência", + "Open Properties: settings for the layers that are on": "Abra Propriedades para ajustar as camadas ativas", + "Data layers": "Camadas de dados", + "{layer} options. {options}": "Opções de {layer}. {options}", + "{layer} options appear here once it has loaded.": "As opções de {layer} aparecem aqui quando a camada é carregada.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Os rótulos identificam os elementos de {layer} no mapa. Densidade ajusta quantos são rotulados. Esmaecimento e Fora controlam como eles vão desaparecendo fora da mira.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "Modelos 3D: Proximidade exibe em 3D apenas as aeronaves próximas. Todos exibe todas em 3D.", + "Press search to find {layer} in the list": "Use o botão de pesquisa para encontrar {layer} na lista", + "Type {layer}": "Digite {layer}", + "Turn on {layer} with its switch": "Ative {layer} com o botão correspondente", + "{layer} are easiest to see from the globe view": "A melhor maneira de ver {layer} é na vista do globo", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Os elementos de {layer} estão espalhados por uma área ampla e poucos aparecem de tão perto. Afaste o mapa ou use o botão da vista do globo.", + "{layer} is on. Want to fine-tune what it shows?": "{layer} está ativa. Quer ajustar o que ela exibe?", + "Show settings": "Mostrar configurações", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Escolha um estilo: Normal, CRT, NVG, FLIR, Anime ou Noir (teclas 1 a 6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "Em Fonte do mapa, escolha o mapa de base: Google 3D, Bing, Esri ou OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Ative ou desative o HUD aqui. Em Layout, escolha Tático, Mínimo ou Ciber.", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "A mira enquadra a vista em um círculo. A suavização deixa a borda menos marcada e Opacidade controla o escurecimento da área externa.", + "Clean UI hides the panels and readouts for a clear view": "Interface limpa oculta os painéis e os indicadores para liberar a vista", + "Press search, then type part of a layer name or source": "Use o botão de pesquisa e digite parte do nome ou da fonte de uma camada", + "Type to narrow the list; Esc clears it": "Digite para restringir a lista. Pressione Esc para limpar a pesquisa.", + "Filter shows only layers that are on or off, or one category": "O filtro mostra só as camadas ativas, as inativas ou as de uma categoria", + "Open the filter": "Abra o filtro", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Escolha um estado (ativadas ou desativadas) e uma categoria. Cada filtro aparece como uma etiqueta que você pode remover.", + "Hover a tick to see its group; click to jump there": "Passe o ponteiro sobre uma marca para ver seu grupo e clique para ir até ele", + "Add provider keys with Power Up, or change the language": "Use Power Up para adicionar chaves de provedores ou troque o idioma", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Use este botão para deslizar os painéis sobre a barra lateral até a borda da tela. Pressione de novo para trazê-los de volta.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "Contexto descreve a vista: o clima, os riscos, os elementos próximos nas suas camadas e o que você seleciona no mapa.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "Propriedades reúne as configurações das camadas ativas. Um ponto colorido identifica cada camada.", + "Press the compass to face north": "Use a bússola para orientar a vista para o norte", + "Tilt the camera for a 3D view": "Incline a câmera para ver em 3D", + "Zoom out to the whole globe": "Afaste o mapa para ver o globo inteiro", + "Copy a link to exactly this view": "Copie um link para esta vista exata", + "Turn off every layer at once": "Desative todas as camadas de uma vez", + "Press Draw to start drawing on the map": "Prima «Desenho» para começar a desenhar no mapa", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Escolha «Linha» para medir uma distância ou «Área» para o seu tamanho e clique em pontos no mapa; duplo clique ou Enter termina", + "End guide": "Encerrar guia", + "to end": "para sair", + "Guide · {topic}": "Guia · {topic}", + "Guide": "Guia", + "Next": "Avançar", + "Press the highlighted control": "Use o controle destacado", + "Finish": "Concluir", + "Skip step": "Pular etapa", + "Authoring": "Criação", + "Visual styles": "Estilos visuais", + "HUD": "Painel HUD", + "Tilt / 3D view": "Inclinação e vista 3D", + "Sharing this view": "Compartilhar esta vista", + "Clearing all layers": "Desativar todas as camadas", + "Changing the map": "Trocar o mapa", + "The scope": "A mira", + "Searching layers": "Pesquisar camadas", + "Filtering layers": "Filtrar camadas", + "Jumping between layer groups": "Alternar entre grupos de camadas", + "Keys and language": "Chaves e idioma", + "Panels at the screen edge": "Painéis na borda da tela", + "The Context panel": "O painel Contexto", + "Layer properties": "Propriedades das camadas", + "Drawing and measuring": "Desenhar e medir", + "Style: Noir": "Estilo: Noir", + "Style: Thermal": "Estilo: Térmico", + "Style: Night vision": "Estilo: Visão noturna", + "Style: Retro": "Estilo: Retrô", + "Style: Anime": "Estilo: Anime", + "Style: Normal": "Estilo: Normal", + "Map: OpenStreetMap": "Mapa: OpenStreetMap", + "Map: Bing aerial": "Mapa: Vista aérea do Bing", + "Map: Photoreal 3D": "Mapa: 3D fotorrealista", + "Map: Esri imagery": "Mapa: Imagens Esri", + "Clear all layers": "Desativar todas as camadas", + "Share this view": "Compartilhar esta vista", + "Orbit": "Orbitar", + "Close all panels": "Fechar todos os painéis", + "Close left panel": "Fechar o painel esquerdo", + "Close right panel": "Fechar o painel direito", + "Open Utilities": "Abrir Utilitários", + "Open Authoring": "Abrir Criação", + "Open Visual": "Abrir Aparência", + "Open Context": "Abrir Contexto", + "Stop camera": "Parar a câmera", + "HUD on": "Ativar HUD", + "HUD off": "Desativar HUD", + "Enter cockpit": "Entrar na cabine", + "Talk to GEV": "Falar com o GEV", + "{layer} on": "{layer} ativada", + "{layer} off": "{layer} desativada", + "Close {panel}": "Fechar {panel}", + "Cockpit": "Cabine", + "Follow {target}": "Seguir {target}", + "Coordinates": "Coordenadas", + "Go to {where}": "Ir para {where}", + "Ask GEV: “{query}”": "Perguntar ao GEV: “{query}”", + "Opens chat": "Abre o chat", + "Go to {place}": "Ir para {place}", + "Place or coordinates": "Lugar ou coordenadas", + "Search “{query}” as a place anyway": "Pesquisar «{query}» como lugar mesmo assim", + "Turn on": "Ativar", + "Turn off": "Desativar", + "Command": "Comando", + "No layers are on": "Nenhuma camada ativa", + "No matching layers": "Nenhuma camada encontrada", + "Show me {thing} settings": "Mostre as configurações de {thing}", + "Show me how: {thing}": "Mostre como fazer: {thing}", + "Do all": "Executar tudo", + "Do it": "Executar", + "Follow {name}": "Seguir {name}", + "Camera": "Câmera", + "Cockpit behind {name}": "Vista da cabine atrás de {name}", + "Close {name}": "Fechar {name}", + "Turn on {layer} here": "Ativar {layer} aqui", + "this view": "esta vista", + "What's here?": "O que tem aqui?", + "Show {what} in {place} ({count} items)": { + "one": "Mostrar {what} em {place} ({count} item)", + "many": "Mostrar {what} em {place} ({count} de itens)", + "other": "Mostrar {what} em {place} ({count} itens)" + }, + "Go there": "Ir até lá", + "Open draw options": "Abrir opções de desenho" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 3eb475d768..3f3f224cfd 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -4345,5 +4345,127 @@ "Move down": "Переместить вниз", "Click a shot to go to it, double-click to rename.": "Щёлкните кадр, чтобы перейти к нему, дважды — чтобы переименовать.", "Back to live at the starting view": "Вернуться в прямой эфир в начальном виде", - "Exit cockpit to fly to a bike share city": "Выйдите из кабины, чтобы перелететь в город с прокатом велосипедов" + "Exit cockpit to fly to a bike share city": "Выйдите из кабины, чтобы перелететь в город с прокатом велосипедов", + "Open {panel}": "Открыть {panel}", + "Visual": "Внешний вид", + "Open Properties: settings for the layers that are on": "Откройте «Свойства», чтобы настроить включённые слои", + "Data layers": "Слои данных", + "{layer} options. {options}": "Параметры слоя {layer}. {options}", + "{layer} options appear here once it has loaded.": "Параметры слоя {layer} появятся здесь после загрузки.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Подписи отмечают объекты слоя {layer} на карте. «Плотность» задаёт их количество. «Затухание» и «Снаружи» регулируют видимость подписей за пределами прицела.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3D-модели: «Вблизи» показывает модели только для ближайших самолётов. «Все» показывает модель каждого самолёта.", + "Press search to find {layer} in the list": "Нажмите кнопку поиска, чтобы найти {layer} в списке", + "Type {layer}": "Введите {layer}", + "Turn on {layer} with its switch": "Включите {layer} соответствующим переключателем", + "{layer} are easiest to see from the globe view": "Слой {layer} лучше всего виден в режиме глобуса", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Объекты слоя {layer} разбросаны по большой территории, поэтому вблизи видны лишь некоторые из них. Уменьшите масштаб или нажмите кнопку глобуса.", + "{layer} is on. Want to fine-tune what it shows?": "Слой {layer} включён. Хотите настроить, что он показывает?", + "Show settings": "Показать настройки", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Выберите стиль: Обычный, CRT, NVG, FLIR, Аниме или Нуар (клавиши 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "В разделе «Источник карты» выберите базовую карту: Google 3D, Bing, Esri или OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Здесь можно включить или выключить HUD. В разделе «Макет» выберите «Тактический», «Минимальный» или «Кибер».", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "«Прицел» обрамляет вид кругом. «Растушёвка» смягчает край, а «Непрозрачность» задаёт затемнение снаружи.", + "Clean UI hides the panels and readouts for a clear view": "«Чистый интерфейс» скрывает панели и индикаторы, освобождая обзор", + "Press search, then type part of a layer name or source": "Нажмите кнопку поиска и введите часть названия слоя или источника", + "Type to narrow the list; Esc clears it": "Введите текст, чтобы сузить список. Нажмите Esc, чтобы очистить поиск.", + "Filter shows only layers that are on or off, or one category": "Фильтр показывает только включённые слои, выключенные слои или слои одной категории", + "Open the filter": "Откройте фильтр", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Выберите состояние («Включены» или «Выключены») и категорию. Каждый фильтр показан в виде метки, которую можно убрать.", + "Hover a tick to see its group; click to jump there": "Наведите указатель на отметку, чтобы увидеть группу, и нажмите, чтобы перейти к ней", + "Add provider keys with Power Up, or change the language": "Добавьте ключи поставщиков через Power Up или измените язык", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Нажмите, чтобы сдвинуть панели поверх боковой панели к краю экрана. Нажмите ещё раз, чтобы вернуть их на место.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "«Контекст» описывает текущий вид: погоду, опасности, ближайшие объекты в ваших слоях и выбранное на карте.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "В «Свойствах» собраны настройки включённых слоёв. Каждый слой отмечен цветной точкой.", + "Press the compass to face north": "Нажмите на компас, чтобы направить вид на север", + "Tilt the camera for a 3D view": "Наклоните камеру для просмотра в 3D", + "Zoom out to the whole globe": "Уменьшите масштаб, чтобы увидеть весь глобус", + "Copy a link to exactly this view": "Скопируйте ссылку на этот точный ракурс", + "Turn off every layer at once": "Выключите все слои сразу", + "Press Draw to start drawing on the map": "Нажмите «Рисование», чтобы рисовать на карте", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Выберите «Линия», чтобы измерить расстояние, или «Зона» — площадь, и щёлкайте точки на карте; двойной щелчок или Enter завершает", + "End guide": "Завершить обучение", + "to end": "для завершения", + "Guide · {topic}": "Руководство · {topic}", + "Guide": "Инструкция", + "Next": "Далее", + "Press the highlighted control": "Нажмите выделенный элемент управления", + "Finish": "Завершить", + "Skip step": "Пропустить шаг", + "Authoring": "Редактор", + "Visual styles": "Стили отображения", + "HUD": "Индикация HUD", + "Tilt / 3D view": "Наклон и 3D-вид", + "Sharing this view": "Как поделиться этим видом", + "Clearing all layers": "Отключение всех слоёв", + "Changing the map": "Смена карты", + "The scope": "Прицел", + "Searching layers": "Поиск слоёв", + "Filtering layers": "Фильтрация слоёв", + "Jumping between layer groups": "Переход между группами слоёв", + "Keys and language": "Ключи и язык", + "Panels at the screen edge": "Панели у края экрана", + "The Context panel": "Панель «Контекст»", + "Layer properties": "Свойства слоёв", + "Drawing and measuring": "Рисование и измерение", + "Style: Noir": "Стиль: нуар", + "Style: Thermal": "Стиль: тепловизор", + "Style: Night vision": "Стиль: ночное видение", + "Style: Retro": "Стиль: ретро", + "Style: Anime": "Стиль: аниме", + "Style: Normal": "Стиль: обычный", + "Map: OpenStreetMap": "Карта: OpenStreetMap", + "Map: Bing aerial": "Карта: аэрофотоснимки Bing", + "Map: Photoreal 3D": "Карта: фотореалистичное 3D", + "Map: Esri imagery": "Карта: снимки Esri", + "Clear all layers": "Выключить все слои", + "Share this view": "Поделиться этим видом", + "Orbit": "Вращать камеру", + "Close all panels": "Закрыть все панели", + "Close left panel": "Закрыть левую панель", + "Close right panel": "Закрыть правую панель", + "Open Utilities": "Открыть «Инструменты»", + "Open Authoring": "Открыть редактор", + "Open Visual": "Открыть «Внешний вид»", + "Open Context": "Открыть «Контекст»", + "Stop camera": "Остановить камеру", + "HUD on": "Включить HUD", + "HUD off": "Выключить HUD", + "Enter cockpit": "Перейти в кабину", + "Talk to GEV": "Поговорить с GEV", + "{layer} on": "Слой {layer} включён", + "{layer} off": "Слой {layer} выключен", + "Close {panel}": "Закрыть {panel}", + "Cockpit": "Кабина пилота", + "Follow {target}": "Следить за {target}", + "Coordinates": "Координаты", + "Go to {where}": "Перейти к {where}", + "Ask GEV: “{query}”": "Спросить GEV: «{query}»", + "Opens chat": "Открывает чат", + "Go to {place}": "Перейти к {place}", + "Place or coordinates": "Место или координаты", + "Search “{query}” as a place anyway": "Всё равно искать «{query}» как место", + "Turn on": "Включить", + "Turn off": "Выключить", + "Command": "Команда", + "No layers are on": "Нет включённых слоёв", + "No matching layers": "Подходящие слои не найдены", + "Show me {thing} settings": "Показать настройки для {thing}", + "Show me how: {thing}": "Показать как: {thing}", + "Do all": "Выполнить все действия", + "Do it": "Выполнить", + "Follow {name}": "Следить за {name}", + "Camera": "Камера", + "Cockpit behind {name}": "Вид из кабины позади {name}", + "Close {name}": "Закрыть {name}", + "Turn on {layer} here": "Включить {layer} в этой области", + "this view": "этот вид", + "What's here?": "Что здесь?", + "Show {what} in {place} ({count} items)": { + "one": "Показать {what} · {place} ({count} объект)", + "few": "Показать {what} · {place} ({count} объекта)", + "many": "Показать {what} · {place} ({count} объектов)", + "other": "Показать {what} · {place} ({count} объекта)" + }, + "Go there": "Перейти туда", + "Open draw options": "Открыть параметры рисования" } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 4a1a2e1fdd..14c8ed02ee 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -4139,5 +4139,125 @@ "Move down": "Flytta ned", "Click a shot to go to it, double-click to rename.": "Klicka på en tagning för att gå till den, dubbelklicka för att byta namn.", "Back to live at the starting view": "Tillbaka till live i startvyn", - "Exit cockpit to fly to a bike share city": "Lämna cockpit för att flyga till en stad med lånecyklar" + "Exit cockpit to fly to a bike share city": "Lämna cockpit för att flyga till en stad med lånecyklar", + "Open {panel}": "Öppna {panel}", + "Visual": "Visning", + "Open Properties: settings for the layers that are on": "Öppna Egenskaper för att ställa in lagren som är på", + "Data layers": "Datalager", + "{layer} options. {options}": "Alternativ för {layer}. {options}", + "{layer} options appear here once it has loaded.": "Inställningar för {layer} visas här när lagret har lästs in.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Etiketter märker ut objekt i {layer} på kartan. Täthet styr hur många som märks ut. Uttoning och Utanför styr hur etiketterna tonas ut utanför siktet.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3D-modeller: Närhet visar bara flygplan på nära håll som modeller. Alla visar varje flygplan som modell.", + "Press search to find {layer} in the list": "Tryck på sökknappen för att hitta {layer} i listan", + "Type {layer}": "Skriv {layer}", + "Turn on {layer} with its switch": "Slå på {layer} med lagrets reglage", + "{layer} are easiest to see from the globe view": "{layer} syns bäst i globvyn", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Objekten i {layer} är utspridda över ett stort område. Få syns så här nära. Zooma ut eller tryck på globknappen.", + "{layer} is on. Want to fine-tune what it shows?": "{layer} är på. Vill du finjustera vad som visas?", + "Show settings": "Visa inställningar", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Välj en stil: Normal, CRT, NVG, FLIR, Anime eller Noir (tangenterna 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "Välj baskarta under Kartkälla: Google 3D, Bing, Esri eller OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Slå på eller av HUD här. Välj Taktisk, Minimal eller Cyber under Layout.", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "Scope ramar in vyn med en cirkel. Mjuk kant tonar ut kanten och Opacitet styr hur mörkt det är utanför.", + "Clean UI hides the panels and readouts for a clear view": "Rent gränssnitt döljer paneler och indikatorer för att ge fri sikt", + "Press search, then type part of a layer name or source": "Tryck på sökknappen och skriv en del av lagrets namn eller källa", + "Type to narrow the list; Esc clears it": "Skriv för att begränsa listan. Tryck på Esc för att rensa sökningen.", + "Filter shows only layers that are on or off, or one category": "Filtret visar bara lager som är på, lager som är av eller lager i en viss kategori", + "Open the filter": "Öppna filtret", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Välj status (På eller Av) och en kategori. Varje filter visas som en etikett du kan ta bort.", + "Hover a tick to see its group; click to jump there": "Håll pekaren över en markering för att se gruppen och klicka för att hoppa dit", + "Add provider keys with Power Up, or change the language": "Lägg till leverantörsnycklar med Power Up eller ändra språk", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Tryck här för att skjuta panelerna över sidofältet till skärmkanten. Tryck igen för att flytta tillbaka dem.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "Kontext beskriver vyn: väder, faror, närliggande objekt i dina lager och det du väljer på kartan.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "Egenskaper samlar inställningarna för aktiva lager. En färgad punkt markerar varje lager.", + "Press the compass to face north": "Tryck på kompassen för att rikta vyn mot norr", + "Tilt the camera for a 3D view": "Luta kameran för en 3D-vy", + "Zoom out to the whole globe": "Zooma ut för att se hela jordklotet", + "Copy a link to exactly this view": "Kopiera en länk till exakt den här vyn", + "Turn off every layer at once": "Slå av alla lager på en gång", + "Press Draw to start drawing on the map": "Tryck på Rita för att börja rita på kartan", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Välj Linje för att mäta ett avstånd eller Område för dess storlek och klicka sedan på punkter på kartan; dubbelklick eller Enter avslutar", + "End guide": "Avsluta guiden", + "to end": "för att avsluta", + "Guide · {topic}": "Guide om {topic}", + "Guide": "Vägledning", + "Next": "Nästa", + "Press the highlighted control": "Tryck på det markerade reglaget", + "Finish": "Slutför", + "Skip step": "Hoppa över steg", + "Authoring": "Redigering", + "Visual styles": "Visuella stilar", + "HUD": "HUD-visning", + "Tilt / 3D view": "Lutning och 3D-vy", + "Sharing this view": "Dela den här vyn", + "Clearing all layers": "Stänga av alla lager", + "Changing the map": "Byta karta", + "The scope": "Cirkelsiktet", + "Searching layers": "Söka bland lager", + "Filtering layers": "Filtrera lager", + "Jumping between layer groups": "Hoppa mellan lagergrupper", + "Keys and language": "Nycklar och språk", + "Panels at the screen edge": "Paneler vid skärmkanten", + "The Context panel": "Kontextpanelen", + "Layer properties": "Lageregenskaper", + "Drawing and measuring": "Rita och mäta", + "Style: Noir": "Stil: Noir", + "Style: Thermal": "Stil: Värmekamera", + "Style: Night vision": "Stil: Mörkerseende", + "Style: Retro": "Stil: Retro", + "Style: Anime": "Stil: Anime", + "Style: Normal": "Stil: Normal", + "Map: OpenStreetMap": "Karta: OpenStreetMap", + "Map: Bing aerial": "Karta: Flygbilder från Bing", + "Map: Photoreal 3D": "Karta: Fotorealistisk 3D", + "Map: Esri imagery": "Karta: Esri-bilder", + "Clear all layers": "Stäng av alla lager", + "Share this view": "Dela den här vyn", + "Orbit": "Rotera runt målet", + "Close all panels": "Stäng alla paneler", + "Close left panel": "Stäng vänster panel", + "Close right panel": "Stäng höger panel", + "Open Utilities": "Öppna Verktyg", + "Open Authoring": "Öppna Redigering", + "Open Visual": "Öppna Visning", + "Open Context": "Öppna Kontext", + "Stop camera": "Stoppa kameran", + "HUD on": "Slå på HUD", + "HUD off": "Slå av HUD", + "Enter cockpit": "Öppna cockpitvyn", + "Talk to GEV": "Prata med GEV", + "{layer} on": "{layer} på", + "{layer} off": "{layer} av", + "Close {panel}": "Stäng {panel}", + "Cockpit": "Cockpitvy", + "Follow {target}": "Följ {target}", + "Coordinates": "Koordinater", + "Go to {where}": "Gå till {where}", + "Ask GEV: “{query}”": "Fråga GEV: ”{query}”", + "Opens chat": "Öppnar chatten", + "Go to {place}": "Gå till {place}", + "Place or coordinates": "Plats eller koordinater", + "Search “{query}” as a place anyway": "Sök ”{query}” som plats ändå", + "Turn on": "Slå på", + "Turn off": "Slå av", + "Command": "Kommando", + "No layers are on": "Inga lager är på", + "No matching layers": "Inga matchande lager", + "Show me {thing} settings": "Visa inställningarna för {thing}", + "Show me how: {thing}": "Visa hur: {thing}", + "Do all": "Utför alla steg", + "Do it": "Utför", + "Follow {name}": "Följ {name}", + "Camera": "Kamera", + "Cockpit behind {name}": "Cockpitvy bakom {name}", + "Close {name}": "Stäng {name}", + "Turn on {layer} here": "Slå på {layer} här", + "this view": "den här vyn", + "What's here?": "Vad finns här?", + "Show {what} in {place} ({count} items)": { + "one": "Visa {what} i {place} ({count} objekt)", + "other": "Visa {what} i {place} ({count} objekt)" + }, + "Go there": "Gå dit", + "Open draw options": "Öppna ritalternativ" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index fedb158454..d778b54801 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -4345,5 +4345,127 @@ "Move down": "Перемістити вниз", "Click a shot to go to it, double-click to rename.": "Клацніть кадр, щоб перейти до нього, двічі — щоб перейменувати.", "Back to live at the starting view": "Повернутися до прямого ефіру в початковому вигляді", - "Exit cockpit to fly to a bike share city": "Вийдіть із кабіни, щоб перелетіти до міста з прокатом велосипедів" + "Exit cockpit to fly to a bike share city": "Вийдіть із кабіни, щоб перелетіти до міста з прокатом велосипедів", + "Open {panel}": "Відкрити {panel}", + "Visual": "Вигляд", + "Open Properties: settings for the layers that are on": "Відкрийте «Властивості», щоб налаштувати увімкнені шари", + "Data layers": "Шари даних", + "{layer} options. {options}": "Параметри шару {layer}. {options}", + "{layer} options appear here once it has loaded.": "Параметри шару {layer} з’являться тут після завантаження.", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "Підписи позначають об’єкти шару {layer} на карті. «Щільність» визначає їхню кількість. «Згасання» та «Ззовні» керують згасанням підписів за межами прицілу.", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3D-моделі: «Поблизу» показує моделі лише для близьких літаків. «Усі» показує модель кожного літака.", + "Press search to find {layer} in the list": "Натисніть кнопку пошуку, щоб знайти {layer} у списку", + "Type {layer}": "Введіть {layer}", + "Turn on {layer} with its switch": "Увімкніть {layer} відповідним перемикачем", + "{layer} are easiest to see from the globe view": "Шар {layer} найкраще видно в режимі глобуса", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "Об’єкти шару {layer} розкидані по великій території, тож зблизька видно лише деякі з них. Зменште масштаб або натисніть кнопку глобуса.", + "{layer} is on. Want to fine-tune what it shows?": "Шар {layer} увімкнено. Хочете налаштувати, що він показує?", + "Show settings": "Показати налаштування", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "Виберіть стиль: Звичайний, CRT, NVG, FLIR, Аніме або Нуар (клавіші 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "У розділі «Джерело карти» виберіть базову карту: Google 3D, Bing, Esri або OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "Увімкніть або вимкніть HUD тут. У розділі «Компонування» виберіть «Тактичне», «Мінімальне» або «Кібер».", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "«Приціл» обрамляє огляд колом. «Розмиття» пом’якшує край, а «Непрозорість» визначає затемнення зовні.", + "Clean UI hides the panels and readouts for a clear view": "«Чистий інтерфейс» приховує панелі та індикатори, щоб ніщо не заважало огляду", + "Press search, then type part of a layer name or source": "Натисніть кнопку пошуку й введіть частину назви шару або джерела", + "Type to narrow the list; Esc clears it": "Введіть текст, щоб звузити список. Натисніть Esc, щоб очистити пошук.", + "Filter shows only layers that are on or off, or one category": "Фільтр показує лише увімкнені чи вимкнені шари або шари однієї категорії", + "Open the filter": "Відкрийте фільтр", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "Виберіть стан («Увімкнені» або «Вимкнені») і категорію. Кожен фільтр показано як мітку, яку можна прибрати.", + "Hover a tick to see its group; click to jump there": "Наведіть вказівник на позначку, щоб побачити групу, і натисніть, щоб перейти до неї", + "Add provider keys with Power Up, or change the language": "Додайте ключі постачальників через Power Up або змініть мову", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "Натисніть, щоб зсунути панелі поверх бічної панелі до краю екрана. Натисніть ще раз, щоб повернути їх.", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "«Контекст» описує поточний огляд: погоду, небезпеки, об’єкти з ваших шарів поблизу та вибране на карті.", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "У «Властивостях» зібрано налаштування увімкнених шарів. Кожен шар позначено кольоровою крапкою.", + "Press the compass to face north": "Натисніть компас, щоб спрямувати огляд на північ", + "Tilt the camera for a 3D view": "Нахиліть камеру для перегляду в 3D", + "Zoom out to the whole globe": "Зменште масштаб, щоб побачити весь глобус", + "Copy a link to exactly this view": "Скопіюйте посилання на цю точну позицію огляду", + "Turn off every layer at once": "Вимкніть усі шари одразу", + "Press Draw to start drawing on the map": "Натисніть «Малювання», щоб малювати на мапі", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "Виберіть «Лінія», щоб виміряти відстань, або «Зона» — площу, і клацайте точки на мапі; подвійне клацання або Enter завершує", + "End guide": "Завершити посібник", + "to end": "для завершення", + "Guide · {topic}": "Посібник · {topic}", + "Guide": "Інструкція", + "Next": "Далі", + "Press the highlighted control": "Натисніть виділений елемент керування", + "Finish": "Завершити", + "Skip step": "Пропустити крок", + "Authoring": "Редактор", + "Visual styles": "Стилі відображення", + "HUD": "Індикація HUD", + "Tilt / 3D view": "Нахил і 3D-огляд", + "Sharing this view": "Поширення цього огляду", + "Clearing all layers": "Вимкнення всіх шарів", + "Changing the map": "Зміна карти", + "The scope": "Приціл", + "Searching layers": "Пошук шарів", + "Filtering layers": "Фільтрування шарів", + "Jumping between layer groups": "Перехід між групами шарів", + "Keys and language": "Ключі та мова", + "Panels at the screen edge": "Панелі біля краю екрана", + "The Context panel": "Панель «Контекст»", + "Layer properties": "Властивості шарів", + "Drawing and measuring": "Малювання й вимірювання", + "Style: Noir": "Стиль: нуар", + "Style: Thermal": "Стиль: тепловізор", + "Style: Night vision": "Стиль: нічне бачення", + "Style: Retro": "Стиль: ретро", + "Style: Anime": "Стиль: аніме", + "Style: Normal": "Стиль: звичайний", + "Map: OpenStreetMap": "Карта: OpenStreetMap", + "Map: Bing aerial": "Карта: аерознімки Bing", + "Map: Photoreal 3D": "Карта: фотореалістичне 3D", + "Map: Esri imagery": "Карта: знімки Esri", + "Clear all layers": "Вимкнути всі шари", + "Share this view": "Поділитися цим оглядом", + "Orbit": "Обертати камеру", + "Close all panels": "Закрити всі панелі", + "Close left panel": "Закрити ліву панель", + "Close right panel": "Закрити праву панель", + "Open Utilities": "Відкрити «Інструменти»", + "Open Authoring": "Відкрити редактор", + "Open Visual": "Відкрити «Вигляд»", + "Open Context": "Відкрити «Контекст»", + "Stop camera": "Зупинити камеру", + "HUD on": "Увімкнути HUD", + "HUD off": "Вимкнути HUD", + "Enter cockpit": "Перейти в кабіну", + "Talk to GEV": "Поговорити з GEV", + "{layer} on": "Шар {layer} увімкнено", + "{layer} off": "Шар {layer} вимкнено", + "Close {panel}": "Закрити {panel}", + "Cockpit": "Кабіна пілота", + "Follow {target}": "Стежити за {target}", + "Coordinates": "Координати", + "Go to {where}": "Перейти до {where}", + "Ask GEV: “{query}”": "Запитати GEV: «{query}»", + "Opens chat": "Відкриває чат", + "Go to {place}": "Перейти до {place}", + "Place or coordinates": "Місце або координати", + "Search “{query}” as a place anyway": "Усе одно шукати «{query}» як місце", + "Turn on": "Увімкнути", + "Turn off": "Вимкнути", + "Command": "Команда", + "No layers are on": "Немає увімкнених шарів", + "No matching layers": "Відповідних шарів не знайдено", + "Show me {thing} settings": "Показати налаштування для {thing}", + "Show me how: {thing}": "Показати як: {thing}", + "Do all": "Виконати всі дії", + "Do it": "Виконати", + "Follow {name}": "Стежити за {name}", + "Camera": "Камера", + "Cockpit behind {name}": "Огляд із кабіни позаду {name}", + "Close {name}": "Закрити {name}", + "Turn on {layer} here": "Увімкнути {layer} тут", + "this view": "цей огляд", + "What's here?": "Що тут є?", + "Show {what} in {place} ({count} items)": { + "one": "Показати {what} · {place} ({count} об’єкт)", + "few": "Показати {what} · {place} ({count} об’єкти)", + "many": "Показати {what} · {place} ({count} об’єктів)", + "other": "Показати {what} · {place} ({count} об’єкта)" + }, + "Go there": "Перейти туди", + "Open draw options": "Відкрити параметри малювання" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 394148c70e..c2d1f49e94 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -4036,5 +4036,124 @@ "Move down": "下移", "Click a shot to go to it, double-click to rename.": "单击镜头即可转到该镜头,双击可重命名。", "Back to live at the starting view": "回到实时并返回初始视图", - "Exit cockpit to fly to a bike share city": "退出驾驶舱以飞往有共享单车的城市" + "Exit cockpit to fly to a bike share city": "退出驾驶舱以飞往有共享单车的城市", + "Open {panel}": "打开{panel}", + "Visual": "视觉", + "Open Properties: settings for the layers that are on": "打开属性:设置已启用的图层", + "Data layers": "数据图层", + "{layer} options. {options}": "{layer}的选项:{options}", + "{layer} options appear here once it has loaded.": "加载完成后,{layer}的选项会显示在此处。", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "标签会在地图上标记{layer}。密度决定显示多少标签,淡出和外部决定视域外的标签如何减少。", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3D 模型:近处仅为近处的飞机显示模型,全部则为每架飞机显示模型。", + "Press search to find {layer} in the list": "点击搜索,在列表中查找{layer}", + "Type {layer}": "输入{layer}", + "Turn on {layer} with its switch": "用开关启用{layer}", + "{layer} are easiest to see from the globe view": "在全球视图中最容易看到{layer}", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "{layer}分布范围很广,当前视角太近,只能看到少量内容。请缩小视图或切换到全球视图。", + "{layer} is on. Want to fine-tune what it shows?": "{layer}已启用。要进一步调整显示内容吗?", + "Show settings": "显示设置", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "选择一种样式:常规、CRT、NVG、FLIR、动漫或黑色电影(按键 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "在地图源中选择底图:Google 3D、Bing、Esri 或 OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "在此开启或关闭 HUD。在布局中选择战术、精简或赛博", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "视域用圆形框出视野。羽化柔化边缘,不透明度决定圆外的明暗。", + "Clean UI hides the panels and readouts for a clear view": "简洁界面会隐藏面板和读数,让视图更清晰", + "Press search, then type part of a layer name or source": "点击搜索,然后输入部分图层名称或来源", + "Type to narrow the list; Esc clears it": "输入内容以缩小列表范围,按 Esc 清除", + "Filter shows only layers that are on or off, or one category": "筛选可只显示已开启或已关闭的图层,也可只显示某一类别", + "Open the filter": "打开筛选", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "选择状态(开启、关闭)和类别。每个条件都会显示为可移除的标签", + "Hover a tick to see its group; click to jump there": "将鼠标悬停在刻度线上可查看对应分组,点击即可跳转", + "Add provider keys with Power Up, or change the language": "在 Power Up 中添加服务提供商密钥,或切换语言", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "点击此按钮可让面板越过侧栏移到屏幕边缘,再点一次即可移回", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "态势介绍当前画面中的天气、风险、附近的图层数据,以及在地图上选中的对象", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "属性包含已启用图层的设置,每个图层都以彩色圆点标记", + "Press the compass to face north": "点击指南针朝向北方", + "Tilt the camera for a 3D view": "倾斜相机以查看 3D 视图", + "Zoom out to the whole globe": "缩小到可查看整个地球", + "Copy a link to exactly this view": "复制能打开当前视图的链接", + "Turn off every layer at once": "一次关闭所有图层", + "Press Draw to start drawing on the map": "按“绘制”开始在地图上绘制", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "选择“线”测量距离,或选择“面”测量面积,然后在地图上点击各点;双击或按 Enter 完成", + "End guide": "结束指南", + "to end": "退出", + "Guide · {topic}": "指南 · {topic}", + "Guide": "指南", + "Next": "下一步", + "Press the highlighted control": "点击高亮显示的控件", + "Finish": "完成", + "Skip step": "跳过此步骤", + "Authoring": "创作工具", + "Visual styles": "视觉样式", + "HUD": "平视显示", + "Tilt / 3D view": "倾斜与 3D 视图", + "Sharing this view": "共享此视图", + "Clearing all layers": "关闭所有图层", + "Changing the map": "更换地图", + "The scope": "视域", + "Searching layers": "搜索图层", + "Filtering layers": "筛选图层", + "Jumping between layer groups": "在图层分组之间跳转", + "Keys and language": "密钥和语言", + "Panels at the screen edge": "屏幕边缘的面板", + "The Context panel": "态势面板", + "Layer properties": "图层属性", + "Drawing and measuring": "绘制与测量", + "Style: Noir": "样式:黑色电影", + "Style: Thermal": "样式:热成像", + "Style: Night vision": "样式:夜视", + "Style: Retro": "样式:复古", + "Style: Anime": "样式:动漫", + "Style: Normal": "样式:常规", + "Map: OpenStreetMap": "地图:OpenStreetMap", + "Map: Bing aerial": "地图:Bing 航拍影像", + "Map: Photoreal 3D": "地图:实景 3D", + "Map: Esri imagery": "地图:Esri 影像", + "Clear all layers": "关闭所有图层", + "Share this view": "共享此视图", + "Orbit": "环绕", + "Close all panels": "关闭所有面板", + "Close left panel": "关闭左侧面板", + "Close right panel": "关闭右侧面板", + "Open Utilities": "打开工具", + "Open Authoring": "打开创作工具", + "Open Visual": "打开视觉设置", + "Open Context": "打开态势", + "Stop camera": "停止相机移动", + "HUD on": "开启 HUD", + "HUD off": "关闭 HUD", + "Enter cockpit": "进入驾驶舱", + "Talk to GEV": "与 GEV 对话", + "{layer} on": "开启{layer}", + "{layer} off": "关闭{layer}", + "Close {panel}": "关闭{panel}", + "Cockpit": "驾驶舱", + "Follow {target}": "跟踪{target}", + "Coordinates": "坐标", + "Go to {where}": "前往{where}", + "Ask GEV: “{query}”": "问 GEV:“{query}”", + "Opens chat": "打开聊天", + "Go to {place}": "前往{place}", + "Place or coordinates": "地点或坐标", + "Search “{query}” as a place anyway": "仍将“{query}”作为地点搜索", + "Turn on": "开启", + "Turn off": "关闭", + "Command": "命令", + "No layers are on": "没有已启用的图层", + "No matching layers": "没有匹配的图层", + "Show me {thing} settings": "显示{thing}的设置", + "Show me how: {thing}": "查看操作方法:{thing}", + "Do all": "全部执行", + "Do it": "执行", + "Follow {name}": "跟踪{name}", + "Camera": "相机", + "Cockpit behind {name}": "从{name}后方进入驾驶舱视角", + "Close {name}": "关闭{name}", + "Turn on {layer} here": "在此开启{layer}", + "this view": "当前视图", + "What's here?": "这里有什么?", + "Show {what} in {place} ({count} items)": { + "other": "显示{place}的{what}({count} 个)" + }, + "Go there": "前往该地点", + "Open draw options": "打开绘制选项" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 2d7e5b00cb..640f5bb730 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -4036,5 +4036,124 @@ "Move down": "下移", "Click a shot to go to it, double-click to rename.": "單擊鏡頭即可轉到該鏡頭,雙擊可重命名。", "Back to live at the starting view": "回到實時並返回初始視圖", - "Exit cockpit to fly to a bike share city": "退出駕駛艙以飛往有共享單車的城市" + "Exit cockpit to fly to a bike share city": "退出駕駛艙以飛往有共享單車的城市", + "Open {panel}": "打開{panel}", + "Visual": "視覺", + "Open Properties: settings for the layers that are on": "打開屬性:設置已啟用的圖層", + "Data layers": "數據圖層", + "{layer} options. {options}": "{layer}的選項:{options}", + "{layer} options appear here once it has loaded.": "加載完成後,{layer}的選項會顯示在此處。", + "Labels tag {layer} on the map. Density sets how many are labelled; Fade and Outside set how they thin out beyond the scope.": "標籤會在地圖上標記{layer}。密度決定顯示多少標籤,淡出和外部決定視域外的標籤如何減少。", + "3D models: Proximity shows them up close only, All shows every aircraft as a model.": "3D 模型:近處僅為近處的飛機顯示模型,全部則為每架飛機顯示模型。", + "Press search to find {layer} in the list": "點擊搜索,在列表中查找{layer}", + "Type {layer}": "輸入{layer}", + "Turn on {layer} with its switch": "用開關啟用{layer}", + "{layer} are easiest to see from the globe view": "在全球視圖中最容易看到{layer}", + "{layer} spread over a wide area, so few are in view this close. Zoom out, or press the globe view.": "{layer}分佈範圍很廣,當前視角太近,只能看到少量內容。請縮小視圖或切換到全球視圖。", + "{layer} is on. Want to fine-tune what it shows?": "{layer}已啟用。要進一步調整顯示內容嗎?", + "Show settings": "顯示設置", + "Pick a look: Normal, CRT, NVG, FLIR, Anime or Noir (keys 1–6)": "選擇一種樣式:常規、CRT、NVG、FLIR、動漫或黑色電影(按鍵 1–6)", + "Under Map source, pick the map underneath: Google 3D, Bing, Esri or OpenStreetMap": "在地圖源中選擇底圖:Google 3D、Bing、Esri 或 OpenStreetMap", + "Switch the HUD on or off here; Layout picks Tactical, Minimal or Cyber": "在此開啟或關閉 HUD。在佈局中選擇戰術、精簡或賽博", + "Scope frames the view in a circle. Feather softens its edge, Opacity sets how dark it shades outside.": "視域用圓形框出視野。羽化柔化邊緣,不透明度決定圓外的明暗。", + "Clean UI hides the panels and readouts for a clear view": "簡潔界面會隱藏面板和讀數,讓視圖更清晰", + "Press search, then type part of a layer name or source": "點擊搜索,然後輸入部分圖層名稱或來源", + "Type to narrow the list; Esc clears it": "輸入內容以縮小列表範圍,按 Esc 清除", + "Filter shows only layers that are on or off, or one category": "篩選可只顯示已開啟或已關閉的圖層,也可只顯示某一類別", + "Open the filter": "打開篩選", + "Pick a status (On, Off) and a category; each shows as a chip you can clear": "選擇狀態(開啟、關閉)和類別。每個條件都會顯示為可移除的標籤", + "Hover a tick to see its group; click to jump there": "將鼠標懸停在刻度線上可查看對應分組,點擊即可跳轉", + "Add provider keys with Power Up, or change the language": "在 Power Up 中添加服務提供商密鑰,或切換語言", + "Press this to slide panels over the rail to the screen edge; press again to bring them back": "點擊此按鈕可讓面板越過側欄移到屏幕邊緣,再點一次即可移回", + "Context describes the view: weather, hazards, what your layers have nearby, and whatever you pick on the map": "態勢介紹當前畫面中的天氣、風險、附近的圖層數據,以及在地圖上選中的對象", + "Properties holds the settings for the layers that are on, each layer marked by a coloured dot": "屬性包含已啟用圖層的設置,每個圖層都以彩色圓點標記", + "Press the compass to face north": "點擊指南針朝向北方", + "Tilt the camera for a 3D view": "傾斜相機以查看 3D 視圖", + "Zoom out to the whole globe": "縮小到可查看整個地球", + "Copy a link to exactly this view": "複製能打開當前視圖的鏈接", + "Turn off every layer at once": "一次關閉所有圖層", + "Press Draw to start drawing on the map": "按“繪製”開始在地圖上繪製", + "Pick Line to measure a distance or Area for its size, then click points on the map; double-click or Enter finishes": "選擇“線”測量距離,或選擇“面”測量面積,然後在地圖上點擊各點;雙擊或按 Enter 完成", + "End guide": "結束指南", + "to end": "退出", + "Guide · {topic}": "指南 · {topic}", + "Guide": "指南", + "Next": "下一步", + "Press the highlighted control": "點擊高亮顯示的控件", + "Finish": "完成", + "Skip step": "跳過此步驟", + "Authoring": "創作工具", + "Visual styles": "視覺樣式", + "HUD": "平視顯示", + "Tilt / 3D view": "傾斜與 3D 視圖", + "Sharing this view": "共享此視圖", + "Clearing all layers": "關閉所有圖層", + "Changing the map": "更換地圖", + "The scope": "視域", + "Searching layers": "搜索圖層", + "Filtering layers": "篩選圖層", + "Jumping between layer groups": "在圖層分組之間跳轉", + "Keys and language": "密鑰和語言", + "Panels at the screen edge": "屏幕邊緣的面板", + "The Context panel": "態勢面板", + "Layer properties": "圖層屬性", + "Drawing and measuring": "繪製與測量", + "Style: Noir": "樣式:黑色電影", + "Style: Thermal": "樣式:熱成像", + "Style: Night vision": "樣式:夜視", + "Style: Retro": "樣式:復古", + "Style: Anime": "樣式:動漫", + "Style: Normal": "樣式:常規", + "Map: OpenStreetMap": "地圖:OpenStreetMap", + "Map: Bing aerial": "地圖:Bing 航拍影像", + "Map: Photoreal 3D": "地圖:實景 3D", + "Map: Esri imagery": "地圖:Esri 影像", + "Clear all layers": "關閉所有圖層", + "Share this view": "共享此視圖", + "Orbit": "環繞", + "Close all panels": "關閉所有面板", + "Close left panel": "關閉左側面板", + "Close right panel": "關閉右側面板", + "Open Utilities": "打開工具", + "Open Authoring": "打開創作工具", + "Open Visual": "打開視覺設置", + "Open Context": "打開態勢", + "Stop camera": "停止相機移動", + "HUD on": "開啟 HUD", + "HUD off": "關閉 HUD", + "Enter cockpit": "進入駕駛艙", + "Talk to GEV": "與 GEV 對話", + "{layer} on": "開啟{layer}", + "{layer} off": "關閉{layer}", + "Close {panel}": "關閉{panel}", + "Cockpit": "駕駛艙", + "Follow {target}": "跟蹤{target}", + "Coordinates": "座標", + "Go to {where}": "前往{where}", + "Ask GEV: “{query}”": "問 GEV:“{query}”", + "Opens chat": "打開聊天", + "Go to {place}": "前往{place}", + "Place or coordinates": "地點或座標", + "Search “{query}” as a place anyway": "仍將“{query}”作為地點搜索", + "Turn on": "開啟", + "Turn off": "關閉", + "Command": "命令", + "No layers are on": "沒有已啟用的圖層", + "No matching layers": "沒有匹配的圖層", + "Show me {thing} settings": "顯示{thing}的設置", + "Show me how: {thing}": "查看操作方法:{thing}", + "Do all": "全部執行", + "Do it": "執行", + "Follow {name}": "跟蹤{name}", + "Camera": "相機", + "Cockpit behind {name}": "從{name}後方進入駕駛艙視角", + "Close {name}": "關閉{name}", + "Turn on {layer} here": "在此開啟{layer}", + "this view": "當前視圖", + "What's here?": "這裡有什麼?", + "Show {what} in {place} ({count} items)": { + "other": "顯示{place}的{what}({count} 個)" + }, + "Go there": "前往該地點", + "Open draw options": "打開繪製選項" } diff --git a/src/ui/omnibarEnter.js b/src/ui/omnibarEnter.js new file mode 100644 index 0000000000..861f243d3b --- /dev/null +++ b/src/ui/omnibarEnter.js @@ -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} 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; +} diff --git a/src/ui/omnibarGuide.js b/src/ui/omnibarGuide.js new file mode 100644 index 0000000000..a2a844af7b --- /dev/null +++ b/src/ui/omnibarGuide.js @@ -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} 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 = + '
' + + ''; + // 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; +} diff --git a/src/ui/omnibarIntent.js b/src/ui/omnibarIntent.js new file mode 100644 index 0000000000..89a359f57f --- /dev/null +++ b/src/ui/omnibarIntent.js @@ -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 = /(? 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, 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 }; +} diff --git a/src/ui/omnibarIntent.test.mjs b/src/ui/omnibarIntent.test.mjs new file mode 100644 index 0000000000..08a6df10e7 --- /dev/null +++ b/src/ui/omnibarIntent.test.mjs @@ -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); +}); diff --git a/src/ui/omnibarRows.js b/src/ui/omnibarRows.js new file mode 100644 index 0000000000..066769362e --- /dev/null +++ b/src/ui/omnibarRows.js @@ -0,0 +1,1538 @@ +// What the Omnibar offers for a typed line, and which row Enter runs. The +// one pipeline from text to rows: the line is normalised once +// (normalizeLine), read once (parseOmnibar), turned into rows here, and the +// Enter rule (src/ui/omnibarEnter.js) orders them and picks the default. +// Omnibar.vue only supplies what the app knows (layers, place suggestions, +// things on the map, the selection) and runs the row that is chosen. +// +// Pure: no DOM, no stores. Tested by an input-to-outcome table in +// src/ui/omnibarRows.test.mjs. + +import { msg, t, tn } from '../i18n/index.js'; +import { parseCoordinateQuery } from '../search/coordinateParser.js'; +import { + mayBePrivate, + minPlaceChars, + onlyNumbersLookPrivate, +} from '../search/placeSuggestions.js'; +import { shownLayerName } from './layerNames.js'; +import { featureGuideFor } from './omnibarGuide.js'; +import { enterDefault, isPlaceWord, orderForEnter } from './omnibarEnter.js'; +import { + hasActionVerb, + isPanelText, + isRealQuestion, + isWholeMapClear, + magnitudeFloor, + normalizeLine, + parseOmnibar, + placeWordLimit, + writtenAsName, +} from './omnibarIntent.js'; + +export const GUIDE_LABELS = { + styles: msg('Visual styles'), + hud: msg('HUD'), + north: msg('North up'), + tilt: msg('Tilt / 3D view'), + globe: msg('Globe view'), + share: msg('Sharing this view'), + clear: msg('Clearing all layers'), + 'map-source': msg('Changing the map'), + scope: msg('The scope'), + clean: msg('Clean UI'), + 'find-layer': msg('Searching layers'), + 'filter-layers': msg('Filtering layers'), + 'section-index': msg('Jumping between layer groups'), + preferences: msg('Keys and language'), + edge: msg('Panels at the screen edge'), + context: msg('The Context panel'), + properties: msg('Layer properties'), + draw: msg('Drawing and measuring'), +}; + +// Guides for parts of the interface that are not commands: matched on the +// words after "show me how", "how do I", etc. +const GUIDE_TOPICS = [ + { + id: 'find-layer', + words: + /^layers?$|\b(search|find|look ?up)\b.*\blayers?\b|\blayers?\b.*\bsearch\b|^(search|find)( a)? layer/, + }, + { + id: 'filter-layers', + words: /\bfilter|\bcategor|\bonly (the )?(on|off|active)\b/, + }, + { + id: 'section-index', + words: + /\b(jump|skip|go) to (a )?(group|section|category)|\bsection index|\blayer groups?\b/, + }, + { + id: 'preferences', + words: + /\b(preferences?|prefs|settings|language|translat|api keys?|keys?|power ?up)\b/, + }, + { + id: 'edge', + words: + /\b(edge|dock|align|move|slide)\b.*\bpanels?\b|\bpanels?\b.*\b(edge|align|over the rail)\b/, + }, + { + id: 'properties', + words: /\bproperties\b|\blabels?\b|\b3d (models?|aircraft)\b|\bdensity\b/, + }, + { + id: 'context', + words: /\bcontext\b|\binspector\b|\bwhat'?s (in view|here)\b/, + }, + { id: 'scope', words: /\bscope\b|\bkeyhole\b|\bfeather\b/ }, + { + id: 'clean', + words: /\bclean (ui|view|screen)|\bhide (the )?(ui|panels|interface)/, + }, + { + id: 'map-source', + words: + /\bmap (source|imagery|layer)|\b(base ?map|imagery)\b|\b(google 3d|bing|esri|osm|openstreetmap)\b/, + }, +]; +// The words people use for the features that have their own walk +// (src/ui/omnibarGuide.js FEATURE_GUIDES), read after GUIDE_TOPICS and +// before any layer: "how do I change the map style", "how do I tilt the +// map", "how do I get back to the globe", "how to measure distance". +const FEATURE_TOPICS = [ + { + id: 'styles', + words: + /\b(?:visual |map |view )?styles?\b|\blooks?\b|\bfilters?\b|\b(?:noir|thermal|night vision|nvg|flir|retro|crt|anime|black and white)\b/, + }, + { + id: 'map-source', + words: + /^(?:base ?)?maps?$|\b(?:base ?map|map (?:type|view|provider)|satellite (?:view|imagery)|google 3d|bing|esri|osm|openstreetmap|photoreal)\b/, + }, + { id: 'hud', words: /\bhud\b|\bheads?[- ]up\b/ }, + { id: 'north', words: /\bnorth\b|\bcompass\b|\bheading\b/ }, + { + id: 'tilt', + words: /\btilt|\b3d (?:view|mode)\b|\bperspective\b|\bpitch\b/, + }, + { + id: 'globe', + words: + /\bglobe\b|\bwhole (?:earth|world|planet)\b|\breset\b|\bzoom (?:all the way )?out\b|\bstart over\b|\bhome view\b/, + }, + { id: 'share', words: /\bshare|\blink\b|\burl\b/ }, + { + id: 'clear', + words: /\bclear\b|\b(?:all|every) (?:the )?(?:data )?layers?\b/, + }, + { + id: 'draw', + words: + /\bdraw|\bsketch|\bannotat|\bmeasur|\bdistance\b|\bruler\b|\bmarkup\b|\bpolygon\b/, + }, +]; +const guideTopic = (subject) => + GUIDE_TOPICS.find((topic) => topic.words.test(subject))?.id || + FEATURE_TOPICS.find((topic) => topic.words.test(subject))?.id || + null; + +// "how do I see …", "show me how to turn on …", "guide me to …". The first +// group is a verb that turns something off ("how do I turn off flights"), +// the second what it is about. +const HOW_TO = + /^(?:can you |could you )?(?:(?:show|tell|teach) me how|how (?:do|can|would|should) i|how to|guide me|walk me through)(?: to)?\s+(?:(turn off|switch off|disable|hide|remove)\s+|(?:see|view|turn on|switch on|enable|show|find|use|get|watch|open|change|switch|set|pick|add)\s+)?(?:the\s+)?(.+)$/; +// "satellite settings", "options for flights": straight to the settings walk. +const SETTINGS_FOR = + /^(?:(?:open|show|change)\s+)?(.+?)\s+(?:settings|options|preferences|prefs)$|^(?:settings|options|preferences)\s+(?:for|of)\s+(.+)$/; + +// "turn on …" / "hide …" / "toggle …": a switch, not a place. +const SWITCH = + /^(turn on|switch on|enable|show|display|add|turn off|switch off|disable|hide|remove|toggle)(?:\s+(.*))?$/; +const SWITCH_OFF = /^(turn off|switch off|disable|hide|remove)\b/; +// Layers people reach for first, so "turn on" offers these before the rest. +export const POPULAR_LAYERS = [ + 'flights', + 'ais-live-vessels', + 'satellites', + 'cctv', + 'earthquakes', + 'weather-radar', + 'local-firms', + 'traffic', + 'military', + 'rocket-launches', +]; + +// Everyday words for layers whose names do not contain them. +export const ALIASES = Object.freeze({ + plane: ['flights'], + planes: ['flights'], + aircraft: ['flights'], + ship: ['ais-live-vessels'], + ships: ['ais-live-vessels'], + boats: ['ais-live-vessels'], + vessels: ['ais-live-vessels'], + camera: ['cctv'], + cameras: ['cctv'], + webcams: ['cctv'], + quakes: ['earthquakes'], + fires: ['local-firms', 'fire-perimeters'], + wildfires: ['local-firms', 'fire-perimeters'], + rain: ['weather-radar'], + weather: ['weather-radar', 'weather-satellite'], + clouds: ['weather-satellite'], + lightning: ['weather-lightning'], + storms: ['weather-cyclones'], + hurricanes: ['weather-cyclones'], + cables: ['telegeography-submarine-cables'], + launches: ['rocket-launches'], + rockets: ['rocket-launches'], + bikes: ['bikeshare'], + trains: ['transit'], + buses: ['transit'], + 'radio stations': ['radio'], + 'radio station': ['radio'], +}); + +export const escapeRegExp = (text) => + text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +/** A match that starts a word: "air" finds "Air quality", "hi" not "Prohibited". */ +const wordStart = (needle) => + new RegExp(`(^|[^a-z0-9])${escapeRegExp(needle)}`); + +// Words in layer names that say what kind, not which: alone they name no +// layer ("Local" is not Local ADS-B, "Global" no global layer). +const GENERIC_LAYER_WORDS = new Set([ + 'local', + 'global', + 'live', + 'world', + 'real', + 'time', + 'new', + 'open', + 'all', + 'data', + 'map', + 'maps', + 'view', + 'level', + 'area', + 'areas', + 'zone', + 'zones', + 'of', + 'and', + 'the', +]); + +/** Edit distance, for typos like "satelite". */ +function editDistance(a, b) { + const row = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 1; i <= a.length; i++) { + let previous = row[0]; + row[0] = i; + for (let j = 1; j <= b.length; j++) { + const kept = row[j]; + row[j] = Math.min( + row[j] + 1, + row[j - 1] + 1, + previous + (a[i - 1] === b[j - 1] ? 0 : 1), + ); + previous = kept; + } + } + return row[b.length]; +} + +/** + * The layers' names, read once, and the matchers over them. A match carries + * the live layer's fields (its `enabled` as the app reports it), its shown + * name, a score and whether it names the whole layer (`exact`). + * @param {Array<{id: string, name: string, enabled?: boolean, showInTogglePanel?: boolean}>} layers + */ +export function createLayerIndex(layers = []) { + const index = layers + .filter((layer) => layer.showInTogglePanel !== false) + .map((layer) => { + const shown = shownLayerName(layer.name, layer.id); + const names = [shown, String(layer.name), String(layer.id)].map((n) => + n.toLowerCase(), + ); + // Whole words come from the names people see, never from ids ("local", + // "global" name no layer). + const titles = names.slice(0, 2); + const words = titles + .flatMap((n) => n.split(/[^\p{L}\p{N}]+/u)) + .filter((word) => word && !GENERIC_LAYER_WORDS.has(word)); + return { layer, shown, names, titles, words: new Set(words) }; + }); + + /** Data layers matching a word or phrase, best first. */ + function matchLayers(term) { + const needle = String(term || '') + .trim() + .toLowerCase(); + if (!needle) return []; + // Synonyms match as they are typed: "cam" already means cameras. + const aliased = [ + ...new Set( + Object.entries(ALIASES) + .filter( + ([word]) => + word === needle || + (needle.length >= 3 && word.startsWith(needle)), + ) + .flatMap(([, ids]) => ids), + ), + ]; + const startsWord = wordStart(needle); + return index + .map(({ layer, shown, names, titles, words }) => { + // Synonyms rank in the order they are listed. + const score = aliased.includes(layer.id) + ? 4 - aliased.indexOf(layer.id) / 10 + : names.some((n) => n.startsWith(needle)) + ? 2 + : names.some((n) => startsWord.test(n)) + ? 1 + : 0; + // A whole name, a whole word of one or a whole synonym (a plural "s" + // from four letters: "fire" names fires, "new" does not name News), + // not the start of one: "rock" begins "rockets" but names no layer. + const exact = + Boolean( + ALIASES[needle]?.includes(layer.id) || + (needle.length >= 4 && ALIASES[`${needle}s`]?.includes(layer.id)), + ) || + titles.includes(needle) || + words.has(needle) || + (needle.length >= 4 && words.has(`${needle}s`)); + return { ...layer, shown, score, exact }; + }) + .filter((layer) => layer.score > 0) + .sort((a, b) => b.score - a.score || b.exact - a.exact); + } + + /** Layers for a phrase, forgiving a typo or two when nothing matches exactly. */ + function matchLayersLoosely(term) { + const exact = matchLayers(term); + if (exact.length) return exact; + const words = String(term || '') + .toLowerCase() + .split(/\s+/) + .filter((word) => word.length >= 4); + if (!words.length) return []; + const near = (word, candidate) => + editDistance(word, candidate) <= (word.length >= 7 ? 2 : 1); + return index + .filter(({ layer, words: names }) => { + const candidates = [ + ...names, + ...Object.entries(ALIASES) + .filter(([, ids]) => ids.includes(layer.id)) + .map(([word]) => word), + ].filter((candidate) => candidate.length >= 3); + return words.some((word) => + candidates.some((candidate) => near(word, candidate)), + ); + }) + .map(({ layer, shown }) => ({ ...layer, shown, score: 2 })); + } + + /** Every listed layer, with its shown name. */ + const all = () => index.map(({ layer, shown }) => ({ ...layer, shown })); + + return { matchLayers, matchLayersLoosely, all }; +} + +/** Words in "how do I …" that name no feature on their own. */ +const GUIDE_STOP_WORDS = new Set([ + 'this', + 'that', + 'it', + 'these', + 'those', + 'here', + 'app', + 'the', + 'a', + 'an', + 'my', + 'thing', + 'things', + 'one', + 'stuff', + 'feature', + 'features', + 'tool', + 'button', +]); + +/** A layer match that names the whole layer, not the start of its name. */ +const named = (layer) => layer?.score >= 2 && layer.exact !== false; + +/** + * "new york" → "New York", "trinidad and tobago" → "Trinidad and Tobago", for + * labels only; the search gets the text as typed. + */ +const SMALL_WORDS = new Set([ + 'and', + 'of', + 'the', + 'on', + 'upon', + 'de', + 'del', + 'la', + 'le', + 'du', + 'da', + 'des', +]); +export const titleCase = (text) => + text.replace(/\S+/g, (word, at) => + at > 0 && SMALL_WORDS.has(word) + ? word + : word[0].toUpperCase() + word.slice(1), + ); + +const STYLE_LABELS = { + noir: msg('Style: Noir'), + thermal: msg('Style: Thermal'), + surveillance: msg('Style: Night vision'), + retro: msg('Style: Retro'), + anime: msg('Style: Anime'), + normal: msg('Style: Normal'), +}; +const STACK_LABELS = { + osm: msg('Map: OpenStreetMap'), + 'bing-aerial': msg('Map: Bing aerial'), + photoreal: msg('Map: Photoreal 3D'), + 'esri-imagery': msg('Map: Esri imagery'), +}; +const CAMERA_LABELS = { + clear: msg('Clear all layers'), + share: msg('Share this view'), + reset: msg('Reset view'), + northUp: msg('North up'), + tilt: msg('Tilt / 3D view'), + zoom_to_globe: msg('Globe view'), + move_camera: msg('Orbit'), +}; + +// Every command the omnibar can run directly. Type ">" to list them all, or +// type a command's name or one of its words to find it among the results. +const cmd = (id, label, words, icon, step) => + Object.freeze({ id, label, words, icon, step }); +export const COMMANDS = Object.freeze([ + cmd( + 'clear', + msg('Clear all layers'), + 'turn off hide remove every everything layers', + 'layers_clear', + { kind: 'camera', act: 'clear' }, + ), + cmd( + 'layers', + msg('Open data layers'), + 'layers panel menu list show', + 'layers', + { kind: 'camera', name: 'show_data_layers_menu', args: {} }, + ), + cmd( + 'close-panels', + msg('Close all panels'), + 'collapse close hide minimise minimize fold all panels sidebars', + 'close_fullscreen', + { kind: 'panel', action: 'close', side: 'all' }, + ), + cmd( + 'close-left', + msg('Close left panel'), + 'collapse close hide left panel sidebar', + 'chevron_left', + { kind: 'panel', action: 'close', side: 'left' }, + ), + cmd( + 'close-right', + msg('Close right panel'), + 'collapse close hide right panel sidebar', + 'chevron_right', + { kind: 'panel', action: 'close', side: 'right' }, + ), + cmd( + 'open-utilities', + msg('Open Utilities'), + 'utilities tools panel open', + 'handyman', + { + kind: 'panel', + action: 'open', + side: 'left', + item: 'utilities-panel', + name: 'Utilities', + }, + ), + cmd( + 'open-authoring', + msg('Open Authoring'), + 'authoring scenes panel open', + 'movie', + { + kind: 'panel', + action: 'open', + side: 'left', + item: 'scene-panel', + name: 'Authoring', + }, + ), + cmd( + 'open-display', + msg('Open Visual'), + 'visual display settings presets looks styles panel open', + 'palette', + { + kind: 'panel', + action: 'open', + side: 'left', + item: 'pp-toggles', + name: 'Visual', + }, + ), + cmd( + 'open-context', + msg('Open Context'), + 'context missions panel open', + 'radar', + { + kind: 'panel', + action: 'open', + side: 'right', + item: 'global-context-panel', + name: 'Context', + }, + ), + cmd('reset', msg('Reset view'), 'home start over reset camera', 'public', { + kind: 'camera', + act: 'reset', + }), + cmd( + 'globe', + msg('Globe view'), + 'whole earth world zoom out globe', + 'public', + { kind: 'camera', name: 'zoom_to_globe', args: {} }, + ), + cmd('north', msg('North up'), 'face north compass heading', 'navigation', { + kind: 'camera', + act: 'northUp', + }), + cmd('tilt', msg('Tilt / 3D view'), 'perspective 3d tilt', 'view_in_ar', { + kind: 'camera', + act: 'tilt', + }), + cmd('zoom-in', msg('Zoom in'), 'closer zoom in', 'open_in_full', { + kind: 'camera', + name: 'adjust_camera_zoom', + args: { direction: 'in' }, + }), + cmd('zoom-out', msg('Zoom out'), 'further zoom out', 'close_fullscreen', { + kind: 'camera', + name: 'adjust_camera_zoom', + args: { direction: 'out' }, + }), + cmd('orbit', msg('Orbit'), 'rotate spin orbit circle', 'adjust', { + kind: 'camera', + name: 'move_camera', + args: { motion: 'orbit', mode: 'continuous' }, + }), + cmd('stop', msg('Stop camera'), 'stop orbit halt still', 'close', { + kind: 'camera', + name: 'move_camera', + args: { motion: 'stop' }, + }), + cmd('share', msg('Share this view'), 'share copy link url', 'east', { + kind: 'camera', + act: 'share', + }), + cmd('hud-on', msg('HUD on'), 'show hud overlay', 'visibility', { + kind: 'hud', + visible: 'on', + }), + cmd('hud-off', msg('HUD off'), 'hide hud overlay clean', 'visibility_off', { + kind: 'hud', + visible: 'off', + }), + cmd( + 'style-normal', + msg('Style: Normal'), + 'normal default plain style', + 'tune', + { kind: 'style', style: 'normal' }, + ), + cmd('style-noir', msg('Style: Noir'), 'noir black white style', 'dark_mode', { + kind: 'style', + style: 'noir', + }), + cmd( + 'style-thermal', + msg('Style: Thermal'), + 'thermal flir heat infrared style', + 'flare', + { kind: 'style', style: 'thermal' }, + ), + cmd( + 'style-nvg', + msg('Style: Night vision'), + 'night vision nvg surveillance green style', + 'light_mode', + { kind: 'style', style: 'surveillance' }, + ), + cmd('style-retro', msg('Style: Retro'), 'retro crt style', 'tune', { + kind: 'style', + style: 'retro', + }), + cmd('style-anime', msg('Style: Anime'), 'anime cartoon style', 'draw', { + kind: 'style', + style: 'anime', + }), + cmd( + 'map-photoreal', + msg('Map: Photoreal 3D'), + 'photoreal 3d tiles google map', + 'view_in_ar', + { kind: 'stack', stack: 'photoreal' }, + ), + cmd( + 'map-esri', + msg('Map: Esri imagery'), + 'esri satellite imagery map', + 'satellite_alt', + { kind: 'stack', stack: 'esri-imagery' }, + ), + cmd('map-bing', msg('Map: Bing aerial'), 'bing aerial map', 'satellite_alt', { + kind: 'stack', + stack: 'bing-aerial', + }), + cmd( + 'map-osm', + msg('Map: OpenStreetMap'), + 'osm openstreetmap street map', + 'location_on', + { kind: 'stack', stack: 'osm' }, + ), + cmd('cockpit', msg('Enter cockpit'), 'cockpit pilot fly plane', 'flight', { + kind: 'cockpit', + }), + cmd( + 'nearest', + msg('Nearest aircraft'), + 'nearest closest plane aircraft flight', + 'flight', + { kind: 'nearest' }, + ), + cmd('radio', msg('Enable Radio'), 'radio music news listen', 'radio', { + kind: 'radio', + }), + cmd('voice', msg('Talk to GEV'), 'voice mic microphone talk speak', 'radar', { + kind: 'mic', + }), +]); + +const withoutPrefix = (label) => label.replace(/^[^:]+:\s*/, ''); + +/** + * The command the text names exactly, by its label ("North up", "Style: + * Noir" or "Noir"), after the line's normalisation ("North up.", "please + * north up"). One of its search words alone ("music", "link", "heat") only + * finds it. + */ +export function exactCommand(text) { + return labelledCommand(readLine(text)); +} + +/** The command whose label is exactly this text, as typed, or null. */ +function labelledCommand(text) { + const needle = String(text || '') + .replace(/^>\s*/, '') + .replace(/\s+/g, ' ') + .trim() + .toLowerCase(); + if (!needle) return null; + return ( + COMMANDS.find((command) => { + const labels = [command.label, t(command.label)].map((label) => + label.toLowerCase(), + ); + return ( + labels.includes(needle) || labels.map(withoutPrefix).includes(needle) + ); + }) || null + ); +} + +/** + * The line as the Omnibar reads it: normalizeLine, with "please" dropped + * only around a request (a verb, a real question or a command's label). + * Place rows and the place service get the text as typed. + */ +export function readLine(text) { + return normalizeLine(text, { + isRequest: (rest) => + hasActionVerb(rest) || + isRealQuestion(rest) || + Boolean(labelledCommand(rest)), + }); +} + +/** Commands matching words typed in order from their starts, best first. */ +export function matchCommands(text) { + const words = String(text || '') + .toLowerCase() + .split(/\s+/) + .filter(Boolean); + if (!words.length) return [...COMMANDS]; + return COMMANDS.map((command) => { + const hay = `${command.label} ${command.words}`.toLowerCase(); + const hits = words.filter((word) => wordStart(word).test(hay)).length; + const label = command.label.toLowerCase(); + const score = + hits === words.length ? (label.startsWith(words.join(' ')) ? 3 : 2) : 0; + return { command, score }; + }) + .filter(({ score }) => score > 0) + .sort((a, b) => b.score - a.score) + .map(({ command }) => command); +} + +/** One step of a plan, in a few words. */ +export function stepLabel(step) { + switch (step.kind) { + case 'place': + return titleCase(step.place); + case 'layer': + return step.enabled + ? t('{layer} on', { layer: step.layer.shown }) + : t('{layer} off', { layer: step.layer.shown }); + case 'style': + return t(STYLE_LABELS[step.style]); + case 'stack': + return t(STACK_LABELS[step.stack]); + case 'camera': + if (step.name === 'adjust_camera_zoom') + return step.args.direction === 'in' ? t('Zoom in') : t('Zoom out'); + if (step.name === 'move_camera' && step.args.motion === 'stop') + return t('Stop camera'); + return t(CAMERA_LABELS[step.act || step.name]); + case 'hud': + return step.visible === 'off' ? t('HUD off') : t('HUD on'); + case 'panel': + if (step.action === 'open') + return t('Open {panel}', { panel: t(step.name) }); + if (step.side === 'all') return t('Close all panels'); + if (step.item) return t('Close {panel}', { panel: t(step.name) }); + return step.side === 'left' + ? t('Close left panel') + : t('Close right panel'); + case 'radio': + return step.action === 'disable' ? t('Radio off') : t('Radio'); + case 'cockpit': + return t('Cockpit'); + case 'nearest': + return t('Nearest aircraft'); + case 'follow': + return t('Follow {target}', { target: step.query.toUpperCase() }); + default: + return ''; + } +} + +/** A callsign (UAL2110, BAW15K, N123AB) or a hex transponder code (a12b2e). */ +export const CALLSIGN = + /^(?:[a-z]{2,3}\d{1,4}[a-z]{0,2}|n\d{1,5}[a-z]{0,2}|[0-9a-f]{6})$/i; + +// "villages near Manor", "towns around here": answered from the bundled packs. +export const VILLAGES = + /^(?:(?:show|list|find)\s+)?(?:me\s+)?(?:the\s+)?(?:villages?|towns?|small towns|hamlets?|settlements?|places)\s+(?:near|around|close to|in|by)\s+(.+)$/i; + +// "draw" (or the start of it) offers Draw's shapes and options, and so does +// a draw verb with something to draw ("draw a line"); "Draw Bridge" and +// "draw well" are names. +const DRAW_WORDS = ['draw', 'sketch', 'annotate', 'drawing', 'markup']; +const DRAW_SOMETHING = + /^(?:draw|sketch|annotate|markup)\s+(?:a|an|the|some|on|here|it|shapes?|lines?|areas?|pins?|polygons?|circles?|routes?|paths?|boxes?|zones?)(?:\s|$)/; +export function drawAsked(text) { + const low = readLine(text).toLowerCase(); + if (low.length < 3) return false; + return ( + DRAW_WORDS.some((word) => word.startsWith(low) || low === word) || + DRAW_SOMETHING.test(low) + ); +} + +/** + * Decimal degrees ("30.27, -97.74"), degrees-minutes-seconds ("30°16'N + * 97°44'W") or an MGRS grid ("14R PU 2090 4906"), or null. + */ +export function coordinateTarget(text) { + const point = parseCoordinateQuery(text); + if (!point) return null; + const grid = /^\d{1,2}[C-HJ-NP-X][A-HJ-NP-Z]{2}(\d{2}){1,5}$/i.test( + text.replace(/\s+/g, ''), + ); + return { ...point, kind: grid ? 'MGRS' : t('Coordinates') }; +} + +function coordinateRow(target, text) { + const where = `${Math.abs(target.lat).toFixed(4)}°${target.lat >= 0 ? 'N' : 'S'} ${Math.abs(target.lon).toFixed(4)}°${target.lon >= 0 ? 'E' : 'W'}`; + return { + key: `coords:${where}`, + kind: 'place', + icon: 'my_location', + place: text, + coords: { latitude: target.lat, longitude: target.lon }, + label: t('Go to {where}', { where }), + hint: target.kind, + }; +} + +const askRow = (text) => ({ + key: 'ask', + kind: 'ask', + icon: null, + query: text, + label: t('Ask GEV: “{query}”', { query: text }), + hint: t('Opens chat'), +}); +const placeRow = (place) => ({ + key: `place:${place}`, + kind: 'place', + icon: 'location_on', + place, + label: t('Go to {place}', { place: titleCase(place) }), + hint: t('Place or coordinates'), +}); +/** + * The line searched as a place only when picked: offered for a long name + * read as a sentence, and for text that may be private ("Tverskaya 13 + * 125009 Moscow" looks like a number to keep). Never the Enter default, and + * nothing is looked up while typing. + */ +const explicitPlaceRow = (text, { private: secret = false } = {}) => ({ + ...placeRow(text), + key: `place-explicit:${text}`, + explicit: true, + ...(secret && { + label: t('Search “{query}” as a place anyway', { query: text }), + }), +}); +/** + * A layer's switch. `best`: the line names this layer before any other, so + * Enter may run it (see mayRunOnEnter). + */ +const layerRow = (layer, enabled = !layer.enabled, { best = false } = {}) => ({ + key: `layer:${layer.id}:${enabled}`, + kind: 'layer', + id: layer.id, + enabled, + best, + icon: 'layers', + label: layer.shown, + hint: + Boolean(layer.enabled) === enabled + ? t('Layer') + : enabled + ? t('Turn on') + : t('Turn off'), +}); +const commandRow = (command, line = '') => ({ + key: `cmd:${command.id}`, + command: command.id, + // The line named this command exactly (see mayRunOnEnter). + named: exactCommand(line) === command, + kind: command.step.kind === 'mic' ? 'mic' : 'plan', + icon: command.icon, + steps: [command.step], + label: t(command.label), + hint: t('Command'), +}); +/** + * A guided walk. `loose`: found by forgiving a typo; `titled`: the line is + * written as a title. Either way it is offered, never run on Enter. + */ +const guideRow = (key, guide, label, icon = 'east', flags = {}) => ({ + key: `guide:${key}`, + kind: 'guide', + icon, + guide, + label, + hint: t('Guide'), + ...flags, +}); + +/** + * The Omnibar's reader for one set of layers: what a line asks for, the rows + * it offers, and what may go to the place service. + * @param {{layers?: Array, isEntity?: (text: string) => boolean}} options + */ +export function createOmnibar({ layers = [], isEntity = () => false } = {}) { + const { matchLayers, matchLayersLoosely, all } = createLayerIndex(layers); + const cache = new Map(); + + /** + * A line, normalised once and read once: `line` is what the user meant + * ("Show flights." → "Show flights"), `plain` the line without a + * magnitude floor, `parsed` how parseOmnibar read it. + */ + function read(text) { + const line = readLine(text); + if (!cache.has(line)) { + if (cache.size >= 16) cache.delete(cache.keys().next().value); + const { text: plain, minMagnitude } = magnitudeFloor(line, matchLayers); + cache.set(line, { + line, + plain, + minMagnitude, + parsed: parseOmnibar(plain, matchLayers, { isEntity }), + }); + } + return cache.get(line); + } + + /** + * "turn on …", "hide …", "toggle …", alone or with a few letters: the + * layers and features that switch that way, never places. Null when the + * line is not such a switch, or names nothing to switch and may be a place + * ("Show Low, AZ"). + */ + function switchRows(line, ask) { + const switching = line.toLowerCase().match(SWITCH); + if ( + !switching || + isPanelText(line) || + isWholeMapClear(line) || + /\b(near|in|at|over|around|and|then)\b/.test(switching[2] || '') + ) + return null; + const verb = switching[1]; + const rest = (switching[2] || '') + .replace(/^((me|the|all|my)\s+)+/, '') + .trim(); + // "turn off noir", "show osm", "turn on orbit": a style, map or camera + // move is read by the parser, not listed as a layer switch. + if ( + rest && + read(line).parsed.steps.some((step) => + ['style', 'stack', 'camera'].includes(step.kind), + ) + ) + return null; + const wantOff = SWITCH_OFF.test(verb); + const toggle = verb === 'toggle'; + const want = (layer) => (toggle ? !layer.enabled : !wantOff); + const pool = rest + ? matchLayers(rest) + : all().sort((a, b) => { + const rank = (id) => { + const at = POPULAR_LAYERS.indexOf(id); + return at === -1 ? POPULAR_LAYERS.length : at; + }; + return rank(a.id) - rank(b.id); + }); + // The layer the words name leads, whatever its state: "show flights" + // with Flights already on offers Flights (nothing to do), never the next + // layer that has the word in its name. + const [first] = pool; + const best = rest && named(first) ? first : null; + const layerRows = [ + ...(best ? [layerRow(best, want(best), { best: true })] : []), + ...pool + .filter((layer) => layer !== best) + .filter((layer) => toggle || (wantOff ? layer.enabled : !layer.enabled)) + .map((layer) => layerRow(layer, want(layer))), + ].slice(0, rest ? 5 : 6); + const featureIds = wantOff + ? ['clear', 'hud-off', 'stop'] + : toggle + ? ['hud-on', 'hud-off', 'radio'] + : ['hud-on', 'radio', 'orbit']; + const features = COMMANDS.filter((command) => + featureIds.includes(command.id), + ) + .filter((command) => !rest || matchCommands(rest).includes(command)) + .map((command) => commandRow(command, line)); + const found = [...layerRows, ...features]; + if (found.length) return [...found, ask]; + // "Show Low, AZ" names no layer or feature: it may be a place, and so + // may "Remove Island" or "Toggle Inn", written as names. + if (rest && !wantOff && !toggle) return null; + if (rest && /\p{Lu}/u.test(line.slice(verb.length))) return null; + return [ + { + key: 'none', + kind: 'none', + icon: 'layers', + label: wantOff ? t('No layers are on') : t('No matching layers'), + hint: '', + }, + ask, + ]; + } + + /** + * Things loaded on the map whose name or id matches, added to a list. A + * callsign, tail number or transponder code leads it; otherwise a place + * row keeps the top ("Hamburg" goes to Hamburg, not to the ship HAMBURG), + * with exact names right after it, and they lead only when there is no + * place row. + */ + function withEntities(list, line, entities) { + if (!entities || line.length < 2 || line.startsWith('>')) return list; + const callsign = CALLSIGN.test(line.replace(/\s+/g, '')); + const rows = entities(line.replace(/\s+/g, callsign ? '' : ' '), { + limit: callsign ? 5 : 3, + }).map((found) => ({ + key: `entity:${found.key}`, + kind: 'entity', + icon: found.icon, + identity: found.identity, + exact: found.title.toLowerCase() === line.toLowerCase(), + label: found.title, + hint: found.layerName, + })); + if (!rows.length) return list; + const place = list.findIndex((item) => item.kind === 'place'); + const exact = rows.filter((row) => row.exact); + const leads = callsign ? rows : place === -1 ? exact : []; + const rest = [ + ...(callsign || place === -1 ? [] : exact), + ...rows.filter((row) => !leads.includes(row) && !exact.includes(row)), + ]; + const ask = list.findIndex((item) => item.kind === 'ask'); + const at = place !== -1 ? place + 1 : ask !== -1 ? ask : list.length; + return [...leads, ...list.slice(0, at), ...rest, ...list.slice(at)]; + } + + /** The rows for a line that is neither private, coordinates nor a count. */ + function lineRows(text, line, { places = [], entities } = {}) { + const ask = askRow(text); + const low = line.toLowerCase(); + // Real places for this text once the suggester answers; the line itself + // only stands in while it has nothing. + const realPlaces = places.map((found) => ({ + key: `place:${found.name}|${found.detail}`, + kind: 'place', + icon: 'location_on', + place: found.name, + coords: { latitude: found.latitude, longitude: found.longitude }, + source: 'photon', + label: t('Go to {place}', { place: found.name }), + hint: found.detail || t('Place'), + })); + const placeRows = (place) => + realPlaces.length + ? realPlaces + : place.trim().length >= minPlaceChars(place) + ? [placeRow(place)] + : []; + + const titled = writtenAsName(text.split(/\s+/)); + const settingsFor = low.match(SETTINGS_FOR); + if (settingsFor) { + const term = (settingsFor[1] || settingsFor[2]).trim(); + const [layer] = matchLayersLoosely(term); + if (layer) + return [ + guideRow( + `settings:${layer.id}`, + { settings: layer }, + t('Show me {thing} settings', { thing: layer.shown }), + 'tune', + { loose: !matchLayers(term).length, titled }, + ), + ask, + ]; + } + + // "show me how to see satellites": a guided walk through the real + // controls, doing it directly, and asking GEV. + const howTo = low.match(HOW_TO); + if (howTo) { + const wantOff = Boolean(howTo[1]); + const subject = howTo[2].replace(/^((the|a|an|my|some)\s+)+/, '').trim(); + const [layer] = matchLayersLoosely(subject); + // Words that say what the walk is about: "how do I use this" names + // nothing ("this" is no part of "Share this view"). + const content = subject + .split(/\s+/) + .filter((word) => word && !GUIDE_STOP_WORDS.has(word)); + const [command] = content.length + ? matchCommands(content.join(' ')).filter((found) => + featureGuideFor(found.id), + ) + : []; + // A walk is run on Enter only when every word is a whole word of the + // command ("how do I share"); a word it merely begins is offered. + const commandWords = command + ? new Set( + `${command.label} ${command.words}`.toLowerCase().split(/\W+/), + ) + : new Set(); + const commandLoose = !content.every((word) => commandWords.has(word)); + const guides = []; + const topic = guideTopic(subject); + if (topic) + guides.push( + guideRow( + `feature:${topic}`, + { feature: topic }, + t('Show me how: {thing}', { thing: t(GUIDE_LABELS[topic]) }), + 'east', + { titled }, + ), + // Doing it directly, when the line names the walk's own command + // ("how do I turn on the HUD": HUD on). + ...(command && featureGuideFor(command.id) === topic + ? [commandRow(command, line)] + : []), + ); + // A feature's own walk wins over a layer the words only resemble + // ("tilt the camera" is no CCTV walk, "change the map" no layer's). + const layerNamed = named(matchLayers(subject)[0]); + if (layer && !(topic && (/layers?$/.test(subject) || !layerNamed))) { + const layerGuides = [ + guideRow( + `layer:${layer.id}`, + { layer }, + t('Show me how: {thing}', { thing: layer.shown }), + 'east', + { loose: !matchLayers(subject).length, titled }, + ), + layerRow(layer, !wantOff), + ]; + // A layer named in full leads a topic its words also hold: "how do + // I see recent imagery" is the Recent Imagery walk, not the map's. + // The Context panel's own walk stays first for "open global context". + if ( + layerNamed && + matchLayers(subject)[0].id === layer.id && + topic !== 'context' + ) + guides.unshift(...layerGuides); + else guides.push(...layerGuides); + } else if (command && !topic) + guides.push( + guideRow( + `feature:${command.id}`, + { feature: featureGuideFor(command.id) }, + t('Show me how: {thing}', { + thing: t( + GUIDE_LABELS[featureGuideFor(command.id)] || command.label, + ), + }), + 'east', + { titled, loose: commandLoose }, + ), + commandRow(command, line), + ); + return [...guides, ask]; + } + + const switched = switchRows(line, ask); + if (switched) return switched; + + // ">" lists commands, filtered by whatever follows it. + if (line.startsWith('>')) { + const term = line.slice(1).trim(); + const verb = /^(show|hide|enable|disable)\s+(.+)$/i.exec(term); + if (verb) { + const needle = verb[2].toLowerCase(); + const exact = matchLayers(needle).find((layer) => + [layer.id, layer.name, layer.shown].some( + (name) => String(name).toLowerCase() === needle, + ), + ); + if (exact) + return [ + layerRow(exact, /^(show|enable)$/i.test(verb[1]), { best: true }), + ]; + } + // A bare ">" lists them all with none picked. + return matchCommands(term) + .slice(0, 8) + .map((command) => commandRow(command, line)); + } + + // A command leads only when the line is its exact label; one the line + // merely begins or holds a word of ("voi", "globe") follows the first + // row, so Enter never starts voice or a cockpit by accident. + const found = line.length >= 3 ? matchCommands(line).slice(0, 2) : []; + const exact = exactCommand(line); + const leading = exact ? [exact] : []; + const trailing = found.filter((command) => command !== exact).slice(0, 2); + const withCommands = (rows) => [ + ...leading.map((command) => commandRow(command, line)), + ...rows.slice(0, 1), + ...trailing.map((command) => commandRow(command, line)), + ...rows.slice(1), + ]; + const { parsed } = read(line); + const { steps, question, ambiguous, peeled, sentence, unasked } = parsed; + const extraPlaces = parsed.extraPlaces || []; + // The whole line as a place is searched as typed ("Paris, Texas.", + // "Yahoo!"); only commands read the normalised line. + const asTyped = (place) => (place === line ? text : place); + if (question) + return [ + ask, + ...found.map((command) => commandRow(command, line)), + ...matchLayers(line) + .slice(0, 3) + .map((layer) => layerRow(layer)), + ]; + // A pasted sentence is no place and asks for nothing: only GEV is + // offered, and Enter runs nothing. + if (sentence) + return [ + ask, + ...(text.length >= minPlaceChars(text) ? [explicitPlaceRow(text)] : []), + ]; + if (!steps.length) + return withEntities( + withCommands([...placeRows(text), ask]), + line, + entities, + ); + const [first] = steps; + const placeStep = steps.find((step) => step.kind === 'place'); + if (steps.length === 1 && first.kind === 'place') { + if (leading.length || trailing.length) + return withEntities( + withCommands([...placeRows(asTyped(first.place)).slice(0, 2), ask]), + line, + entities, + ); + return withEntities( + [ + ...placeRows(asTyped(first.place)), + ...matchLayers(line) + .slice(0, 2) + .map((layer) => layerRow(layer)), + ask, + ], + line, + entities, + ); + } + if (steps.length === 1 && first.kind === 'layer') + return [ + layerRow(first.layer, first.enabled, { best: true }), + // "earth" might be a place; "hide flights" is not. + ...(steps.verb ? [] : placeRows(text).slice(0, 2)), + ask, + ]; + + const plan = { + key: `plan:${JSON.stringify(steps)}`, + kind: 'plan', + icon: 'bolt', + steps, + label: steps.map(stepLabel).filter(Boolean).join(' · '), + hint: steps.length > 1 ? t('Do all') : t('Do it'), + }; + const alternatives = [ + ...(placeStep ? placeRows(placeStep.place).slice(0, 2) : []), + // "near New York and Paris": the plan goes to the first; the others + // are offered rather than dropped. + ...extraPlaces.map((extra) => placeRow(extra)), + ...steps + .filter((step) => step.kind === 'layer') + .map((step) => layerRow(step.layer, step.enabled)), + ]; + // "Thermal, California", "Tilt Cove", "tokyo traffic": one keyword + // without a verb may be part of the place's name, so the whole line as a + // place comes first and the plan second. After "go to …" with a request + // peeled off, the place is the one read ("go to London with flights"). + if (ambiguous) + return withEntities( + [ + placeRow(peeled ? placeStep.place : text), + plan, + ...alternatives.filter((row) => row.kind !== 'place'), + ask, + ], + line, + entities, + ); + // Keywords alone and nothing asked for ("Fire and Rain", "Noir and + // Thermal"): the plan is offered, never run; the line may be a name. + if (unasked && !placeStep && steps.length >= 2 && !exact) + return withEntities( + [placeRow(text), plan, ...alternatives, ask], + line, + entities, + ); + return [plan, ...alternatives, ask]; + } + + /** + * A bundled place's name that is also a command or layer word ("Thermal", + * "Normal", "Hurricane"): the place comes first, the switch after it. + */ + function withPlaceWord(list, line) { + if (!isPlaceWord(line) || list[0]?.kind === 'place') return list; + const place = placeRow(line); + return [place, ...list.filter((item) => item.key !== place.key)]; + } + + /** Rows for the selected item, offered when the field is empty. */ + function selectionRows(selection) { + const name = selection.title; + return [ + { + key: 'sel:fly', + kind: 'sel-fly', + icon: 'my_location', + label: t('Fly to {name}', { name }), + hint: selection.layerName, + }, + ...(selection.canFollow + ? [ + { + key: 'sel:follow', + kind: 'sel-follow', + icon: 'navigation', + label: t('Follow {name}', { name }), + hint: t('Camera'), + }, + ] + : []), + ...(selection.canCockpit + ? [ + { + key: 'sel:cockpit', + kind: 'sel-cockpit', + icon: 'airline_seat_recline_normal', + label: t('Cockpit behind {name}', { name }), + hint: t('Cockpit'), + }, + ] + : []), + { + key: 'sel:ask', + kind: 'sel-ask', + icon: null, + label: t('Ask GEV about {name}', { name }), + hint: t('Opens chat'), + }, + { + key: 'sel:close', + kind: 'sel-close', + icon: 'close', + label: t('Close {name}', { name }), + hint: t('Context'), + }, + ]; + } + + /** + * With nothing typed or selected: "What's here?" and the most used layers + * that are off. + */ + function viewRows(viewPlace) { + const off = all() + .filter((layer) => !layer.enabled && POPULAR_LAYERS.includes(layer.id)) + .sort( + (a, b) => POPULAR_LAYERS.indexOf(a.id) - POPULAR_LAYERS.indexOf(b.id), + ) + .slice(0, 2) + .map((layer) => ({ + key: `view-on:${layer.id}`, + kind: 'layer', + id: layer.id, + enabled: true, + icon: 'layers', + label: t('Turn on {layer} here', { layer: layer.shown }), + hint: t('Layer'), + })); + const where = viewPlace + ? [viewPlace.name, viewPlace.state || viewPlace.country] + .filter(Boolean) + .join(', ') + : t('this view'); + return [ + { + key: 'view-ask', + kind: 'view-ask', + icon: null, + label: t("What's here?"), + hint: where, + }, + ...off, + ]; + } + + /** + * The rows for what is typed, in the order shown, and the one Enter runs + * before any is chosen (-1 for none). + * @param {string} typed + * @param {{ + * places?: Array, + * entities?: (text: string, options: {limit: number}) => Array, + * selection?: ?{title: string, layerName: string, canFollow: boolean, canCockpit: boolean}, + * viewPlace?: ?{name: string, state?: string, country?: string}, + * counted?: ?{count: number, what: string, placeName: string, place: object, layer: object}, + * }} context + * @returns {{rows: Array, defaultIndex: number}} + */ + function rows(typed, context = {}) { + const text = String(typed || '').trim(); + if (!text) { + const list = context.selection + ? selectionRows(context.selection) + : viewRows(context.viewPlace); + return { rows: list, defaultIndex: -1 }; + } + const line = readLine(text); + const { parsed } = read(line); + const enterContext = { named: Boolean(exactCommand(line)) }; + const finish = (list) => { + const ordered = orderForEnter( + withPlaceWord(list, line), + line, + parsed, + enterContext, + ); + return { + rows: ordered, + defaultIndex: enterDefault(ordered, line, parsed, enterContext), + }; + }; + const target = coordinateTarget(line); + // Coordinates are a spot, not a secret; nothing about them leaves the + // app unless GEV is asked. + if (target) + return finish([ + coordinateRow(target, line), + ...(mayBePrivate(text) ? [] : [askRow(text)]), + ]); + // Text that may be private (an email address, a card, phone, SSN or + // account number, a password or key) is never offered to the place + // service, the place search or GEV: only things already loaded on the + // map may match it. + if (mayBePrivate(text)) + return finish([ + ...withEntities([], line, context.entities), + // An address may look like a number to keep; a bare number never + // names a place, and an email, password, key or code is never + // offered as one. + ...(onlyNumbersLookPrivate(text) + ? [explicitPlaceRow(text, { private: true })] + : []), + ]); + const counted = context.counted; + if (counted) { + const show = { + key: 'count-show', + kind: 'count-show', + icon: + counted.layer.icon && /^[a-z_]+$/.test(counted.layer.icon) + ? counted.layer.icon + : 'travel_explore', + label: tn( + counted.count, + 'Show {what} in {place} ({count} item)', + 'Show {what} in {place} ({count} items)', + { what: counted.what, place: counted.placeName }, + ), + hint: t('Go there'), + coords: { + latitude: counted.place.latitude, + longitude: counted.place.longitude, + }, + place: counted.placeName, + source: counted.place.source, + }; + return finish([ + show, + ...lineRows(text, line, context).filter((item) => item.kind !== 'plan'), + ]); + } + const list = lineRows(text, line, context); + if (!drawAsked(line)) return finish(list); + return finish( + [ + { + key: 'tool:draw', + kind: 'open-draw', + icon: 'draw', + label: t('Open draw options'), + hint: t('Utilities'), + }, + ...list.filter((item) => item.kind !== 'place').slice(0, 3), + ...list.filter((item) => item.kind === 'place').slice(0, 1), + ].sort((a, b) => (a.kind === 'ask') - (b.kind === 'ask')), + ); + } + + /** + * What may go to the place service (Photon) for a line, or null: the part + * that names a place, or the whole line when it may be one name + * ("Satellite Beach", "Home, Washington"). Never private text, a question, + * a pasted sentence, a command, coordinates, a callsign, a switch or + * "villages near …". + */ + function placeQuery(typed) { + const text = String(typed || '').trim(); + if (!text || mayBePrivate(text)) return null; + const line = readLine(text); + if (line.length < minPlaceChars(line) || line.startsWith('>')) return null; + if (/^[0-9a-f]{6}$/i.test(line) || CALLSIGN.test(line.replace(/\s+/g, ''))) + return null; + if (line.includes('?') || line.split(/\s+/).length > placeWordLimit(line)) + return null; + if (VILLAGES.test(line) || exactCommand(line) || coordinateTarget(line)) + return null; + if (switchRows(line, askRow(text))) return null; + const { parsed } = read(line); + if (parsed.question || parsed.sentence) return null; + const place = parsed.steps.find((step) => step.kind === 'place'); + // A line of commands with no place in it ("night vision", "zoom in"). + if (parsed.steps.length && !place) return null; + // After "go to … , noir" the place read is the one to look up. + if (parsed.peeled && place) return place.place; + return parsed.ambiguous || !place + ? text + : place.place === line + ? text + : place.place; + } + + /** + * A count request ("flights over Texas", "quakes above M5 in Japan"): the + * layer to count and its magnitude floor, or null. + */ + function countRequest(typed) { + const text = String(typed || '').trim(); + if (text.length < 5 || text.startsWith('>') || mayBePrivate(text)) + return null; + const { parsed, minMagnitude } = read(text); + const layer = parsed.steps.find((step) => step.kind === 'layer'); + const place = parsed.steps.find((step) => step.kind === 'place'); + if (!layer || !place || layer.enabled === false) return null; + return { layer: layer.layer, minMagnitude }; + } + + return { + rows, + placeQuery, + countRequest, + matchLayers, + /** The line as read: for tests and diagnostics. */ + read, + }; +} diff --git a/src/ui/omnibarRows.test.mjs b/src/ui/omnibarRows.test.mjs new file mode 100644 index 0000000000..99048fcc70 --- /dev/null +++ b/src/ui/omnibarRows.test.mjs @@ -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', + 'me@example.com', + '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', + 'john.doe@example.com', + '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'); +});