Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Improve map lifecycles and coordinate picking https://github.com/siyuan-note/siyuan/issues/20445 https://github.com/siyuan-note/siyuan/issues/20446

Daniel3c24ded00099
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 05410069d9..5b812414c8 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "اختيار على الخريطة",
+ "mapPickedPoint": "الموقع المحدد",
+ "mapCreateAtPoint": "إنشاء سجل هنا",
"syncConfig": "إعدادات خدمة المزامنة",
"clearSyncConfig": "مسح الإعدادات",
"clearSyncConfigConfirm": "هل تريد مسح العنوان وبيانات الاعتماد المحفوظة لهذه الخدمة؟ إذا كانت خدمة المزامنة الحالية، فسيتم تعطيل المزامنة أيضًا. لن تُحذف الملاحظات المحلية أو بيانات السحابة.",
@@ -33,7 +36,7 @@
"mapOffline": "الخريطة غير متصلة بالإنترنت. لا تزال سجلاتك متاحة",
"mapPublicFallback": "لا تُحمّل الخرائط في الصفحات المنشورة أو المحتوى المصدّر",
"mapTooManyMarkers": "تحتوي هذه الصفحة على أكثر من ${limit} موقعًا. استخدم عوامل التصفية أو قلّل حجم الصفحة لعرض الخريطة",
- "locationPasteInEditor": "أدخل خط الطول وخط العرض كلًّا على حدة في محرر الموقع وتأكّد من نظام الإحداثيات",
+ "locationPasteInEditor": "استخدم خط العرض، خط الطول بنظام WGS84 (خط العرض من -90 إلى 90؛ خط الطول من -180 إلى 180)، أو الاسم; خط العرض, خط الطول [WGS84]",
"location": "الموقع",
"locationName": "الاسم (اختياري)",
"latitude": "خط العرض",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 1500e70474..5a04386792 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Auf Karte auswählen",
+ "mapPickedPoint": "Ausgewählter Standort",
+ "mapCreateAtPoint": "Eintrag hier erstellen",
"syncConfig": "Konfiguration des Synchronisierungsdienstes",
"clearSyncConfig": "Konfiguration löschen",
"clearSyncConfigConfirm": "Gespeicherte Adresse und Zugangsdaten dieses Dienstes löschen? Wenn dies der aktuelle Synchronisierungsdienst ist, wird auch die Synchronisierung deaktiviert. Lokale Notizen und Cloud-Daten werden nicht gelöscht.",
@@ -33,7 +36,7 @@
"mapOffline": "Die Karte ist offline. Ihre Datensätze sind weiterhin verfügbar",
"mapPublicFallback": "In veröffentlichten Seiten oder Exporten werden keine Karten geladen",
"mapTooManyMarkers": "Diese Seite enthält mehr als ${limit} Standorte. Filter verwenden oder die Seitengröße verkleinern, um die Karte anzuzeigen",
- "locationPasteInEditor": "Längengrad und Breitengrad im Standorteditor getrennt eingeben und das Koordinatensystem überprüfen",
+ "locationPasteInEditor": "WGS84-Koordinaten als Breitengrad, Längengrad eingeben (Breitengrad -90 bis 90; Längengrad -180 bis 180) oder Name; Breitengrad, Längengrad [WGS84]",
"location": "Standort",
"locationName": "Name (optional)",
"latitude": "Breitengrad",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index e7d67d5d72..c10f8c0849 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Pick on map",
+ "mapPickedPoint": "Selected location",
+ "mapCreateAtPoint": "Create record here",
"syncConfig": "Sync service configuration",
"clearSyncConfig": "Clear configuration",
"clearSyncConfigConfirm": "Clear this service's saved address and credentials? If it is the current sync service, sync will also be disabled. Local notes and cloud data will not be deleted.",
@@ -33,7 +36,7 @@
"mapOffline": "Map is offline. Your records are still available",
"mapPublicFallback": "Maps are not loaded in published pages or exports",
"mapTooManyMarkers": "This page has more than ${limit} locations. Use filters or a smaller page size to display the map",
- "locationPasteInEditor": "Enter longitude and latitude separately in the location editor and confirm the coordinate system",
+ "locationPasteInEditor": "Use WGS84 latitude, longitude (latitude -90 to 90; longitude -180 to 180), or Name; latitude, longitude [WGS84]",
"location": "Location",
"locationName": "Name (optional)",
"latitude": "Latitude",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index b5250ed090..6c67fe5e4f 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Elegir en el mapa",
+ "mapPickedPoint": "Ubicación seleccionada",
+ "mapCreateAtPoint": "Crear registro aquí",
"syncConfig": "Configuración del servicio de sincronización",
"clearSyncConfig": "Borrar configuración",
"clearSyncConfigConfirm": "¿Borrar la dirección y las credenciales guardadas de este servicio? Si es el servicio de sincronización actual, también se desactivará la sincronización. No se eliminarán las notas locales ni los datos en la nube.",
@@ -33,7 +36,7 @@
"mapOffline": "El mapa está sin conexión. Sus registros siguen disponibles",
"mapPublicFallback": "Los mapas no se cargan en páginas publicadas ni en exportaciones",
"mapTooManyMarkers": "Esta página tiene más de ${limit} ubicaciones. Use filtros o reduzca el tamaño de página para mostrar el mapa",
- "locationPasteInEditor": "Introduce la longitud y la latitud por separado en el editor de ubicación y confirma el sistema de coordenadas",
+ "locationPasteInEditor": "Usa latitud, longitud en WGS84 (latitud de -90 a 90; longitud de -180 a 180), o Nombre; latitud, longitud [WGS84]",
"location": "Ubicación",
"locationName": "Nombre (opcional)",
"latitude": "Latitud",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 4b666e0f2d..fbb1b35010 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Choisir sur la carte",
+ "mapPickedPoint": "Lieu sélectionné",
+ "mapCreateAtPoint": "Créer une entrée ici",
"syncConfig": "Configuration du service de synchronisation",
"clearSyncConfig": "Effacer la configuration",
"clearSyncConfigConfirm": "Effacer l’adresse et les identifiants enregistrés pour ce service ? S’il s’agit du service de synchronisation actuel, la synchronisation sera aussi désactivée. Les notes locales et les données du cloud ne seront pas supprimées.",
@@ -33,7 +36,7 @@
"mapOffline": "La carte est hors ligne. Vos enregistrements restent disponibles",
"mapPublicFallback": "Les cartes ne sont pas chargées dans les pages publiées ni dans les exports",
"mapTooManyMarkers": "Cette page comporte plus de ${limit} localisations. Utilisez des filtres ou réduisez la taille des pages pour afficher la carte",
- "locationPasteInEditor": "Saisissez la longitude et la latitude séparément dans l’éditeur de lieu et vérifiez le système de coordonnées",
+ "locationPasteInEditor": "Utilisez latitude, longitude en WGS84 (latitude de -90 à 90 ; longitude de -180 à 180), ou Nom; latitude, longitude [WGS84]",
"location": "Lieu",
"locationName": "Nom (facultatif)",
"latitude": "Latitude",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index e8b70cfd2f..97ec9a16bd 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "בחירה במפה",
+ "mapPickedPoint": "המיקום שנבחר",
+ "mapCreateAtPoint": "יצירת רשומה כאן",
"syncConfig": "הגדרות שירות הסנכרון",
"clearSyncConfig": "ניקוי ההגדרות",
"clearSyncConfigConfirm": "לנקות את הכתובת ואת פרטי ההזדהות השמורים של שירות זה? אם זהו שירות הסנכרון הנוכחי, גם הסנכרון יושבת. פתקים מקומיים ונתוני ענן לא יימחקו.",
@@ -33,7 +36,7 @@
"mapOffline": "המפה אינה מחוברת לרשת. הרשומות שלך עדיין זמינות",
"mapPublicFallback": "מפות אינן נטענות בדפים שפורסמו או בתוכן שיוצא",
"mapTooManyMarkers": "בדף זה יש יותר מ-${limit} מיקומים. השתמש במסננים או הקטן את גודל הדף כדי להציג את המפה",
- "locationPasteInEditor": "יש להזין את קו האורך וקו הרוחב בנפרד בעורך המיקום ולוודא שמערכת הקואורדינטות נכונה",
+ "locationPasteInEditor": "יש להשתמש בקו רוחב, קו אורך לפי WGS84 (קו רוחב מ־-90 עד 90; קו אורך מ־-180 עד 180), או שם; קו רוחב, קו אורך [WGS84]",
"location": "מיקום",
"locationName": "שם (רשות)",
"latitude": "קו רוחב",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 79b050a196..d1c17f8db5 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "मानचित्र पर चुनें",
+ "mapPickedPoint": "चयनित स्थान",
+ "mapCreateAtPoint": "यहाँ प्रविष्टि बनाएँ",
"syncConfig": "सिंक सेवा कॉन्फ़िगरेशन",
"clearSyncConfig": "कॉन्फ़िगरेशन साफ़ करें",
"clearSyncConfigConfirm": "इस सेवा का सहेजा गया पता और क्रेडेंशियल साफ़ करें? यदि यह वर्तमान सिंक सेवा है, तो सिंक भी बंद हो जाएगा। स्थानीय नोट और क्लाउड डेटा नहीं मिटाए जाएँगे।",
@@ -33,7 +36,7 @@
"mapOffline": "मानचित्र ऑफ़लाइन है। आपके रिकॉर्ड अभी भी उपलब्ध हैं",
"mapPublicFallback": "प्रकाशित पृष्ठों या निर्यात में मानचित्र लोड नहीं किए जाते",
"mapTooManyMarkers": "इस पृष्ठ पर ${limit} से अधिक स्थान हैं। मानचित्र दिखाने के लिए फ़िल्टर उपयोग करें या पृष्ठ का आकार कम करें",
- "locationPasteInEditor": "स्थान संपादक में देशांतर और अक्षांश अलग-अलग दर्ज करें और निर्देशांक प्रणाली की पुष्टि करें",
+ "locationPasteInEditor": "WGS84 अक्षांश, देशांतर का उपयोग करें (अक्षांश -90 से 90; देशांतर -180 से 180), या नाम; अक्षांश, देशांतर [WGS84]",
"location": "स्थान",
"locationName": "नाम (वैकल्पिक)",
"latitude": "अक्षांश",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 8d25412d38..f33338cd67 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Pilih di peta",
+ "mapPickedPoint": "Lokasi terpilih",
+ "mapCreateAtPoint": "Buat entri di sini",
"syncConfig": "Konfigurasi layanan sinkronisasi",
"clearSyncConfig": "Hapus konfigurasi",
"clearSyncConfigConfirm": "Hapus alamat dan kredensial yang tersimpan untuk layanan ini? Jika ini layanan sinkronisasi saat ini, sinkronisasi juga akan dinonaktifkan. Catatan lokal dan data cloud tidak akan dihapus.",
@@ -33,7 +36,7 @@
"mapOffline": "Peta sedang luring. Rekaman Anda tetap tersedia",
"mapPublicFallback": "Peta tidak dimuat pada halaman yang dipublikasikan atau hasil ekspor",
"mapTooManyMarkers": "Halaman ini memiliki lebih dari ${limit} lokasi. Gunakan filter atau ukuran halaman yang lebih kecil untuk menampilkan peta",
- "locationPasteInEditor": "Masukkan bujur dan lintang secara terpisah di editor lokasi dan pastikan sistem koordinatnya benar",
+ "locationPasteInEditor": "Gunakan lintang, bujur WGS84 (lintang -90 hingga 90; bujur -180 hingga 180), atau Nama; lintang, bujur [WGS84]",
"location": "Lokasi",
"locationName": "Nama (opsional)",
"latitude": "Lintang",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index ef112fa9fb..89fe6d6bb5 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Scegli sulla mappa",
+ "mapPickedPoint": "Posizione selezionata",
+ "mapCreateAtPoint": "Crea voce qui",
"syncConfig": "Configurazione del servizio di sincronizzazione",
"clearSyncConfig": "Cancella configurazione",
"clearSyncConfigConfirm": "Cancellare l’indirizzo e le credenziali salvati per questo servizio? Se è il servizio di sincronizzazione attuale, verrà disattivata anche la sincronizzazione. Le note locali e i dati nel cloud non verranno eliminati.",
@@ -33,7 +36,7 @@
"mapOffline": "La mappa è offline. I tuoi record sono ancora disponibili",
"mapPublicFallback": "Le mappe non vengono caricate nelle pagine pubblicate o nelle esportazioni",
"mapTooManyMarkers": "Questa pagina contiene più di ${limit} posizioni. Usa i filtri o riduci la dimensione della pagina per visualizzare la mappa",
- "locationPasteInEditor": "Inserisci longitudine e latitudine separatamente nell’editor della posizione e verifica il sistema di coordinate",
+ "locationPasteInEditor": "Usa latitudine, longitudine WGS84 (latitudine da -90 a 90; longitudine da -180 a 180), oppure Nome; latitudine, longitudine [WGS84]",
"location": "Posizione",
"locationName": "Nome (facoltativo)",
"latitude": "Latitudine",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 1081248fda..58b8cc7b31 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "地図で選択",
+ "mapPickedPoint": "選択した位置",
+ "mapCreateAtPoint": "ここに項目を作成",
"syncConfig": "同期サービスの設定",
"clearSyncConfig": "設定を消去",
"clearSyncConfigConfirm": "このサービスの保存済みアドレスと認証情報を消去しますか?現在の同期サービスの場合は同期も無効になります。ローカルのノートとクラウドのデータは削除されません。",
@@ -33,7 +36,7 @@
"mapOffline": "地図はオフラインです。レコードは引き続き利用できます",
"mapPublicFallback": "公開ページやエクスポートでは地図を読み込みません",
"mapTooManyMarkers": "このページには ${limit} 件を超える位置があります。フィルターを使用するか、ページあたりの件数を減らして地図を表示してください",
- "locationPasteInEditor": "位置エディターで経度と緯度を別々に入力し、座標系を確認してください",
+ "locationPasteInEditor": "WGS84 の緯度, 経度(緯度は -90 から 90、経度は -180 から 180)、または 名前; 緯度, 経度 [WGS84] の形式で入力してください",
"location": "位置",
"locationName": "名前(任意)",
"latitude": "緯度",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 0bd456187a..78e59fb899 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "지도에서 선택",
+ "mapPickedPoint": "선택한 위치",
+ "mapCreateAtPoint": "여기에 항목 만들기",
"syncConfig": "동기화 서비스 설정",
"clearSyncConfig": "설정 지우기",
"clearSyncConfigConfirm": "이 서비스에 저장된 주소와 인증 정보를 지우시겠습니까? 현재 동기화 서비스인 경우 동기화도 비활성화됩니다. 로컬 노트와 클라우드 데이터는 삭제되지 않습니다.",
@@ -33,7 +36,7 @@
"mapOffline": "지도가 오프라인 상태입니다. 레코드는 계속 사용할 수 있습니다",
"mapPublicFallback": "게시된 페이지나 내보낸 콘텐츠에서는 지도를 불러오지 않습니다",
"mapTooManyMarkers": "이 페이지의 위치가 ${limit}개를 초과합니다. 지도를 표시하려면 필터를 사용하거나 페이지 크기를 줄이세요",
- "locationPasteInEditor": "위치 편집기에서 경도와 위도를 각각 입력하고 좌표계를 확인하세요",
+ "locationPasteInEditor": "WGS84 위도, 경도(위도 -90~90, 경도 -180~180) 또는 이름; 위도, 경도 [WGS84] 형식으로 입력하세요",
"location": "위치",
"locationName": "이름(선택 사항)",
"latitude": "위도",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 74a23b2654..db19a54b0e 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Op kaart kiezen",
+ "mapPickedPoint": "Geselecteerde locatie",
+ "mapCreateAtPoint": "Hier item maken",
"syncConfig": "Configuratie van synchronisatiedienst",
"clearSyncConfig": "Configuratie wissen",
"clearSyncConfigConfirm": "Het opgeslagen adres en de inloggegevens van deze dienst wissen? Als dit de huidige synchronisatiedienst is, wordt synchronisatie ook uitgeschakeld. Lokale notities en cloudgegevens worden niet verwijderd.",
@@ -33,7 +36,7 @@
"mapOffline": "De kaart is offline. Uw records zijn nog beschikbaar",
"mapPublicFallback": "Kaarten worden niet geladen in gepubliceerde pagina’s of exports",
"mapTooManyMarkers": "Deze pagina heeft meer dan ${limit} locaties. Gebruik filters of verklein de paginagrootte om de kaart weer te geven",
- "locationPasteInEditor": "Voer lengtegraad en breedtegraad afzonderlijk in de locatie-editor in en controleer het coördinatenstelsel",
+ "locationPasteInEditor": "Gebruik WGS84-breedtegraad, lengtegraad (breedtegraad -90 tot 90; lengtegraad -180 tot 180), of Naam; breedtegraad, lengtegraad [WGS84]",
"location": "Locatie",
"locationName": "Naam (optioneel)",
"latitude": "Breedtegraad",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 411e09f973..18ea0f6db7 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Wybierz na mapie",
+ "mapPickedPoint": "Wybrana lokalizacja",
+ "mapCreateAtPoint": "Utwórz wpis tutaj",
"syncConfig": "Konfiguracja usługi synchronizacji",
"clearSyncConfig": "Wyczyść konfigurację",
"clearSyncConfigConfirm": "Wyczyścić zapisany adres i dane uwierzytelniające tej usługi? Jeśli jest to bieżąca usługa synchronizacji, synchronizacja również zostanie wyłączona. Lokalne notatki i dane w chmurze nie zostaną usunięte.",
@@ -33,7 +36,7 @@
"mapOffline": "Mapa jest offline. Twoje rekordy są nadal dostępne",
"mapPublicFallback": "Mapy nie są wczytywane na opublikowanych stronach ani w eksportach",
"mapTooManyMarkers": "Ta strona zawiera więcej niż ${limit} lokalizacji. Użyj filtrów lub zmniejsz rozmiar strony, aby wyświetlić mapę",
- "locationPasteInEditor": "Wprowadź długość i szerokość geograficzną osobno w edytorze lokalizacji i sprawdź układ współrzędnych",
+ "locationPasteInEditor": "Użyj szerokości i długości geograficznej WGS84 (szerokość od -90 do 90; długość od -180 do 180) w formacie szerokość, długość lub Nazwa; szerokość, długość [WGS84]",
"location": "Lokalizacja",
"locationName": "Nazwa (opcjonalna)",
"latitude": "Szerokość geograficzna",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 41c775ded8..83972037ec 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Escolher no mapa",
+ "mapPickedPoint": "Localização selecionada",
+ "mapCreateAtPoint": "Criar registro aqui",
"syncConfig": "Configuração do serviço de sincronização",
"clearSyncConfig": "Limpar configuração",
"clearSyncConfigConfirm": "Limpar o endereço e as credenciais salvos deste serviço? Se ele for o serviço de sincronização atual, a sincronização também será desativada. As notas locais e os dados na nuvem não serão excluídos.",
@@ -33,7 +36,7 @@
"mapOffline": "O mapa está offline. Seus registros continuam disponíveis",
"mapPublicFallback": "Os mapas não são carregados em páginas publicadas nem em exportações",
"mapTooManyMarkers": "Esta página tem mais de ${limit} localizações. Use filtros ou reduza o tamanho da página para exibir o mapa",
- "locationPasteInEditor": "Insira a longitude e a latitude separadamente no editor de localização e confirme o sistema de coordenadas",
+ "locationPasteInEditor": "Use latitude, longitude WGS84 (latitude de -90 a 90; longitude de -180 a 180), ou Nome; latitude, longitude [WGS84]",
"location": "Localização",
"locationName": "Nome (opcional)",
"latitude": "Latitude",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 9e8ad56345..bf8c577a5b 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Выбрать на карте",
+ "mapPickedPoint": "Выбранное местоположение",
+ "mapCreateAtPoint": "Создать запись здесь",
"syncConfig": "Настройка службы синхронизации",
"clearSyncConfig": "Очистить настройки",
"clearSyncConfigConfirm": "Удалить сохранённый адрес и учётные данные этой службы? Если это текущая служба синхронизации, синхронизация также будет отключена. Локальные заметки и облачные данные не будут удалены.",
@@ -33,7 +36,7 @@
"mapOffline": "Карта недоступна без сети. Ваши записи по-прежнему доступны",
"mapPublicFallback": "Карты не загружаются на опубликованных страницах и в экспортированных материалах",
"mapTooManyMarkers": "На этой странице больше ${limit} местоположений. Используйте фильтры или уменьшите размер страницы, чтобы отобразить карту",
- "locationPasteInEditor": "Введите долготу и широту отдельно в редакторе местоположения и проверьте систему координат",
+ "locationPasteInEditor": "Используйте широту, долготу WGS84 (широта от -90 до 90; долгота от -180 до 180) или Название; широта, долгота [WGS84]",
"location": "Местоположение",
"locationName": "Название (необязательно)",
"latitude": "Широта",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 2cc6d515f0..0c2fadbff6 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Vybrať na mape",
+ "mapPickedPoint": "Vybraná poloha",
+ "mapCreateAtPoint": "Vytvoriť záznam tu",
"syncConfig": "Nastavenie služby synchronizácie",
"clearSyncConfig": "Vymazať nastavenie",
"clearSyncConfigConfirm": "Vymazať uloženú adresu a prihlasovacie údaje tejto služby? Ak ide o aktuálnu službu synchronizácie, synchronizácia sa tiež vypne. Lokálne poznámky a údaje v cloude sa neodstránia.",
@@ -33,7 +36,7 @@
"mapOffline": "Mapa je offline. Vaše záznamy sú naďalej dostupné",
"mapPublicFallback": "Mapy sa nenačítavajú na publikovaných stránkach ani v exportoch",
"mapTooManyMarkers": "Táto stránka obsahuje viac ako ${limit} polôh. Na zobrazenie mapy použite filtre alebo menšiu veľkosť stránky",
- "locationPasteInEditor": "Zemepisnú dĺžku a zemepisnú šírku zadajte v editore polohy samostatne a overte súradnicový systém",
+ "locationPasteInEditor": "Použite zemepisnú šírku, zemepisnú dĺžku WGS84 (šírka od -90 do 90; dĺžka od -180 do 180) alebo Názov; zemepisná šírka, zemepisná dĺžka [WGS84]",
"location": "Poloha",
"locationName": "Názov (voliteľný)",
"latitude": "Zemepisná šírka",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 03c39480e2..18fdb2bc71 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Изабери на мапи",
+ "mapPickedPoint": "Изабрана локација",
+ "mapCreateAtPoint": "Направи запис овде",
"syncConfig": "Подешавање услуге синхронизације",
"clearSyncConfig": "Обриши подешавања",
"clearSyncConfigConfirm": "Обрисати сачувану адресу и приступне податке ове услуге? Ако је ово тренутна услуга синхронизације, синхронизација ће такође бити искључена. Локалне белешке и подаци у облаку неће бити обрисани.",
@@ -33,7 +36,7 @@
"mapOffline": "Мапа је ван мреже. Ваши записи су и даље доступни",
"mapPublicFallback": "Мапе се не учитавају на објављеним страницама ни у извезеним садржајима",
"mapTooManyMarkers": "Ова страница има више од ${limit} локација. Користите филтере или смањите величину странице да бисте приказали мапу",
- "locationPasteInEditor": "Унесите географску дужину и географску ширину засебно у уређивачу локације и проверите координатни систем",
+ "locationPasteInEditor": "Користите географску ширину, географску дужину WGS84 (ширина од -90 до 90; дужина од -180 до 180) или Назив; географска ширина, географска дужина [WGS84]",
"location": "Локација",
"locationName": "Назив (опционо)",
"latitude": "Географска ширина",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 06c8a86b6b..f5496f4648 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "เลือกบนแผนที่",
+ "mapPickedPoint": "ตำแหน่งที่เลือก",
+ "mapCreateAtPoint": "สร้างรายการที่นี่",
"syncConfig": "การตั้งค่าบริการซิงค์",
"clearSyncConfig": "ล้างการตั้งค่า",
"clearSyncConfigConfirm": "ล้างที่อยู่และข้อมูลรับรองที่บันทึกไว้ของบริการนี้หรือไม่? หากเป็นบริการซิงค์ปัจจุบัน การซิงค์จะถูกปิดด้วย บันทึกในเครื่องและข้อมูลบนคลาวด์จะไม่ถูกลบ",
@@ -33,7 +36,7 @@
"mapOffline": "แผนที่ออฟไลน์ ระเบียนของคุณยังคงพร้อมใช้งาน",
"mapPublicFallback": "แผนที่จะไม่โหลดในหน้าที่เผยแพร่หรือเนื้อหาที่ส่งออก",
"mapTooManyMarkers": "หน้านี้มีตำแหน่งมากกว่า ${limit} รายการ ใช้ตัวกรองหรือลดขนาดหน้าเพื่อแสดงแผนที่",
- "locationPasteInEditor": "กรอกค่าลองจิจูดและละติจูดแยกกันในตัวแก้ไขตำแหน่ง และตรวจสอบระบบพิกัด",
+ "locationPasteInEditor": "ใช้รูปแบบละติจูด, ลองจิจูด WGS84 (ละติจูด -90 ถึง 90; ลองจิจูด -180 ถึง 180) หรือ ชื่อ; ละติจูด, ลองจิจูด [WGS84]",
"location": "ตำแหน่ง",
"locationName": "ชื่อ (ไม่บังคับ)",
"latitude": "ละติจูด",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 420e12f832..a8ec8dd509 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Haritada seç",
+ "mapPickedPoint": "Seçilen konum",
+ "mapCreateAtPoint": "Burada kayıt oluştur",
"syncConfig": "Eşitleme hizmeti yapılandırması",
"clearSyncConfig": "Yapılandırmayı temizle",
"clearSyncConfigConfirm": "Bu hizmetin kayıtlı adresi ve kimlik bilgileri temizlensin mi? Geçerli eşitleme hizmetiyse eşitleme de devre dışı bırakılır. Yerel notlar ve bulut verileri silinmez.",
@@ -33,7 +36,7 @@
"mapOffline": "Harita çevrimdışı. Kayıtlarınız hâlâ kullanılabilir",
"mapPublicFallback": "Yayımlanan sayfalarda veya dışa aktarılan içerikte haritalar yüklenmez",
"mapTooManyMarkers": "Bu sayfada ${limit} konumdan fazla konum var. Haritayı göstermek için filtreleri kullanın veya sayfa boyutunu küçültün",
- "locationPasteInEditor": "Konum düzenleyicisinde boylam ve enlemi ayrı ayrı girin ve koordinat sistemini doğrulayın",
+ "locationPasteInEditor": "WGS84 enlem, boylam biçimini (enlem -90 ile 90; boylam -180 ile 180) veya Ad; enlem, boylam [WGS84] biçimini kullanın",
"location": "Konum",
"locationName": "Ad (isteğe bağlı)",
"latitude": "Enlem",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 948ae38a1c..b2f7cd2228 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "Вибрати на мапі",
+ "mapPickedPoint": "Вибране розташування",
+ "mapCreateAtPoint": "Створити запис тут",
"syncConfig": "Налаштування служби синхронізації",
"clearSyncConfig": "Очистити налаштування",
"clearSyncConfigConfirm": "Видалити збережену адресу й облікові дані цієї служби? Якщо це поточна служба синхронізації, синхронізацію також буде вимкнено. Локальні нотатки та хмарні дані не буде видалено.",
@@ -33,7 +36,7 @@
"mapOffline": "Мапа недоступна без мережі. Ваші записи залишаються доступними",
"mapPublicFallback": "Мапи не завантажуються на опублікованих сторінках і в експортованих матеріалах",
"mapTooManyMarkers": "На цій сторінці понад ${limit} місцеположень. Використайте фільтри або зменште розмір сторінки, щоб показати мапу",
- "locationPasteInEditor": "Введіть довготу й широту окремо в редакторі розташування та перевірте систему координат",
+ "locationPasteInEditor": "Використовуйте широту, довготу WGS84 (широта від -90 до 90; довгота від -180 до 180) або Назва; широта, довгота [WGS84]",
"location": "Розташування",
"locationName": "Назва (необов’язково)",
"latitude": "Широта",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 05688a0173..6b2787c3ce 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "地图选点",
+ "mapPickedPoint": "已选位置",
+ "mapCreateAtPoint": "在此创建条目",
"syncConfig": "同步服务配置",
"clearSyncConfig": "清除配置",
"clearSyncConfigConfirm": "清除该服务保存的地址和凭据?如果它是当前同步服务,将同时关闭同步。本地笔记和云端数据不会被删除。",
@@ -33,7 +36,7 @@
"mapOffline": "地图处于离线状态,记录仍然可用",
"mapPublicFallback": "发布页面和导出内容不加载地图",
"mapTooManyMarkers": "当前页面的位置超过 ${limit} 个,请使用筛选或减小每页记录数以显示地图",
- "locationPasteInEditor": "请在位置编辑器中分别填写经度和纬度,并确认坐标系",
+ "locationPasteInEditor": "请使用 WGS84 纬度, 经度(纬度 -90 到 90;经度 -180 到 180),或 名称; 纬度, 经度 [WGS84] 格式",
"location": "位置",
"locationName": "名称(可选)",
"latitude": "纬度",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 8f944f90aa..4ded69d086 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "locationPickOnMap": "地圖選點",
+ "mapPickedPoint": "已選位置",
+ "mapCreateAtPoint": "在此建立項目",
"syncConfig": "同步服務設定",
"clearSyncConfig": "清除設定",
"clearSyncConfigConfirm": "清除這項服務儲存的位址和憑證?如果它是目前的同步服務,也會關閉同步。本機筆記和雲端資料不會被刪除。",
@@ -33,7 +36,7 @@
"mapOffline": "地圖處於離線狀態,記錄仍然可用",
"mapPublicFallback": "發佈頁面和匯出內容不載入地圖",
"mapTooManyMarkers": "目前頁面的位置超過 ${limit} 個,請使用篩選或減少每頁記錄數以顯示地圖",
- "locationPasteInEditor": "請在位置編輯器中分別填寫經度和緯度,並確認座標系",
+ "locationPasteInEditor": "請使用 WGS84 緯度, 經度(緯度 -90 到 90;經度 -180 到 180),或 名稱; 緯度, 經度 [WGS84] 格式",
"location": "位置",
"locationName": "名稱(選填)",
"latitude": "緯度",
diff --git a/app/electron/main.js b/app/electron/main.js
index efdc21d8a5..f8d1d781f7 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -82,6 +82,7 @@ const {captureWindowGeometry, normalizeWindowGeometry, restoreWindowGeometry} =
const {createSettingsWindows} = require("./settingsWindows");
const {createSettingsTaskBridge} = require("./settingsTasks");
const {createMapHostManager} = require("./mapHostManager");
+const {bindWebviewDevToolsShortcut} = require("./webviewDevTools");
const windowWorkspaces = new WindowWorkspaceRegistry();
const {createNotebookSystemLock, prepareNotebookSystemLock} = require("./notebookSystemLock");
const {
@@ -4645,6 +4646,7 @@ app.on("activate", () => {
});
app.on("web-contents-created", (webContentsCreatedEvent, contents) => {
+ bindWebviewDevToolsShortcut(contents, getWindowKernelTarget);
contents.setWindowOpenHandler((details) => {
const settings = settingsWindowPolicy(contents, details);
if (settings) {
diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.js
index 2bccf004a2..d4a3787fa5 100644
--- a/app/electron/mapHostManager.js
+++ b/app/electron/mapHostManager.js
@@ -237,7 +237,10 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChan
};
const setVisible = (host, visible) => {
host.visible = visible && host.ready && host.win.isVisible() && !host.win.isMinimized();
- if (!host.visible) host.attributionGestureUntil = 0;
+ if (!host.visible) {
+ host.attributionGestureUntil = 0;
+ host.pointGestureUntil = 0;
+ }
const visibility = host.visible ? host.visibility : {visible: false};
const key = JSON.stringify(visibility);
if (host.ready && key !== host.lastVisibility) {
@@ -419,7 +422,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChan
host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin, diagnostics: new Set(), report,
mode: owner.mode, kernelMode: owner.kernelMode, session: ses, partition, entryURL, router, listeners: [], ids: new Set(), revision: -1,
loaded: false, ready: false, bootstrapped: false, destroyed: false,
- visible: false, attributionGestureUntil: 0};
+ visible: false, attributionGestureUntil: 0, pointGestureUntil: 0};
hosts.set(key, host);
listen(host, event.sender, "destroyed", () => destroy(host));
listen(host, event.sender, "render-process-gone", () => destroy(host));
@@ -428,8 +431,8 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChan
if (details.isMainFrame && !details.isSameDocument) destroy(host);
});
for (const name of ["hide", "minimize"]) listen(host, owner.win, name, () => hide(host));
- // 失焦仅撤销署名外链手势,DOM 处理地图的裁剪和叠层。
- listen(host, owner.win, "blur", () => { host.attributionGestureUntil = 0; });
+ // 失焦撤销外链与选点手势,DOM 处理地图的裁剪和叠层。
+ listen(host, owner.win, "blur", () => { host.attributionGestureUntil = 0; host.pointGestureUntil = 0; });
for (const name of ["focus", "show", "restore"]) listen(host, owner.win, name, () => applyVisibility(host));
host.attachContents = contents => {
host.contents = contents;
@@ -447,7 +450,12 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChan
sendOwner(host, {version: 1, instanceID: host.init.instanceID, type: "dismissMenu"});
}
}
- if (input.type === "mouseUp" && input.button === "left") armAttributionClick();
+ if (input.type === "mouseUp" && input.button === "left") {
+ armAttributionClick();
+ if (host.init.picking && host.attributionGestureUntil > Date.now()) {
+ host.pointGestureUntil = Date.now() + 1000;
+ }
+ }
});
listen(host, contents, "before-input-event", (_event, input) => {
if (input.type === "keyDown" && input.key === "Enter" && !input.isAutoRepeat) armAttributionClick();
@@ -519,10 +527,17 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChan
sendOwner(host, reply);
} else if (reply.type === "markerClick" && host.ready && reply.revision === host.revision && host.ids.has(reply.id)) {
sendOwner(host, reply);
+ } else if (reply.type === "pointClick" && host.init.picking && host.ready && host.visible &&
+ reply.revision === host.revision && host.revision >= 0 && host.win.isFocused() &&
+ host.win.isVisible() && !host.win.isMinimized() && host.pointGestureUntil > Date.now()) {
+ host.pointGestureUntil = 0;
+ host.attributionGestureUntil = 0;
+ sendOwner(host, reply);
} else if (reply.type === "attributionClick" && host.ready && host.visible &&
host.win.isFocused() && host.win.isVisible() && !host.win.isMinimized() &&
host.attributionGestureUntil > Date.now()) {
host.attributionGestureUntil = 0;
+ host.pointGestureUntil = 0;
sendOwner(host, reply);
} else if (reply.type === "error") {
fail(host, reply.code === "hostUnavailable" ?
@@ -560,6 +575,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, MessageChan
if (command.type === "destroy") { destroy(host); return; }
if (command.type === "setPoints") {
if (command.revision <= host.revision) return;
+ host.pointGestureUntil = 0;
host.revision = command.revision;
host.points = command;
host.ids = new Set(command.points.map(point => point.id));
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.js
index 66a6571222..b867d9ec6e 100644
--- a/app/electron/mapHostManager.test.js
+++ b/app/electron/mapHostManager.test.js
@@ -321,6 +321,39 @@ managerTest("points and clicks are bounded by current revision and membership; r
s.manager.destroyAll();
});
+managerTest("picked coordinates require opt-in, a current revision and one recent visible pointer gesture", (t, mode) => {
+ let now = 100000;
+ t.mock.method(Date, "now", () => now);
+ for (const picking of [false, true]) {
+ const s = setup(undefined, mode); s.create({picking}); s.load();
+ s.reply({type: "bootstrapReady"}); s.reply({type: "ready"});
+ s.command({type: "setPoints", revision: 1, points: []});
+ s.command({type: "visibility", visible: true});
+ const contents = s.guests[0];
+ const click = () => contents.emit("before-mouse-event", {}, {type: "mouseUp", button: "left"});
+ const point = {type: "pointClick", revision: 1, longitude: 0, latitude: 0};
+ const replies = () => s.owner.sent.filter(entry => entry[1].type === "pointClick");
+ s.reply(point);
+ contents.emit("before-input-event", {}, {type: "keyDown", key: "Enter", isAutoRepeat: false});
+ s.reply(point);
+ assert.equal(replies().length, 0);
+ click(); s.reply({...point, revision: 0}); s.reply({...point, longitude: 181});
+ assert.equal(replies().length, 0);
+ s.reply({...point, name: "private"}); s.reply(point);
+ assert.equal(replies().length, picking ? 1 : 0);
+ if (picking) assert.deepEqual(replies()[0][1], {...envelope, ...point});
+ click(); s.win.emit("blur"); s.reply(point);
+ click(); s.command({type: "visibility", visible: false}); s.command({type: "visibility", visible: true}); s.reply(point);
+ click(); now += 1001; s.reply(point);
+ assert.equal(replies().length, picking ? 1 : 0);
+ click(); s.command({type: "setPoints", revision: 2, points: []}); s.reply(point);
+ s.reply({...point, revision: 2});
+ assert.equal(replies().length, picking ? 1 : 0);
+ s.manager.destroyAll();
+ assert.equal(contents.listenerCount("before-mouse-event"), 0);
+ }
+});
+
managerTest("attribution links require one recent trusted guest input in a ready visible focused map", (t, mode) => {
let now = 100000;
t.mock.method(Date, "now", () => now);
diff --git a/app/electron/mapHostPolicy.js b/app/electron/mapHostPolicy.js
index e85ea80d7d..302a7d3a98 100644
--- a/app/electron/mapHostPolicy.js
+++ b/app/electron/mapHostPolicy.js
@@ -56,8 +56,10 @@ const sanitizeMapPoints = value => {
};
const parseMapCreate = value => {
if (!isRecord(value) || value.version !== 1 || !isMapInstanceID(value.instanceID) ||
- value.provider !== "openfreemap" || !isMapTheme(value.theme)) return;
- return {version: 1, instanceID: value.instanceID, type: "init", provider: "openfreemap", theme: value.theme};
+ value.provider !== "openfreemap" || !isMapTheme(value.theme) ||
+ value.picking !== undefined && typeof value.picking !== "boolean") return;
+ return {version: 1, instanceID: value.instanceID, type: "init", provider: "openfreemap", theme: value.theme,
+ ...(value.picking === true && {picking: true})};
};
const parseMapCommand = (value, instanceID) => {
if (!isRecord(value) || value.version !== 1 || value.instanceID !== instanceID) return;
@@ -86,6 +88,11 @@ const parseMapReply = (value, instanceID) => {
if (value.type === "markerClick" && isMapIdentifier(value.id) && isMapRevision(value.revision)) {
return {...base, type: value.type, id: value.id, revision: value.revision};
}
+ if (value.type === "pointClick" && isMapRevision(value.revision) && !("coordinateSystem" in value) &&
+ Number.isFinite(value.longitude) && Math.abs(value.longitude) <= 180 &&
+ Number.isFinite(value.latitude) && Math.abs(value.latitude) <= 85.0511287798066) {
+ return {...base, type: value.type, revision: value.revision, longitude: value.longitude, latitude: value.latitude};
+ }
if (value.type === "attributionClick" && ["openfreemap", "openmaptiles", "openstreetmap", "maplibre"].includes(value.link)) {
return {...base, type: value.type, link: value.link};
}
diff --git a/app/electron/webviewDevTools.js b/app/electron/webviewDevTools.js
new file mode 100644
index 0000000000..2a5353dee4
--- /dev/null
+++ b/app/electron/webviewDevTools.js
@@ -0,0 +1,24 @@
+const bindWebviewDevToolsShortcut = (contents, getTarget, platform = process.platform) => {
+ if (contents.isDestroyed() || contents.getType() !== "webview") return;
+ const onInput = (event, input) => {
+ if (input.type !== "keyDown") return;
+ const modifiers = platform === "darwin" ? input.meta && input.alt && !input.control && !input.shift :
+ input.control && input.shift && !input.meta && !input.alt;
+ if (!modifiers || (input.key?.toLowerCase() !== "i" && input.code !== "KeyI")) return;
+ try {
+ // 每次按键都从 Electron 读取实际宿主,避免挂载前或销毁后的 guest 指向其他窗口。
+ if (contents.isDestroyed()) return;
+ const host = contents.hostWebContents;
+ if (!host || host.isDestroyed() || host.getType() !== "window" || !getTarget(host.id)) return;
+ // 主进程同步阻止 guest 和菜单处理同一按键;长按时仍拦截,但只切换一次。
+ event.preventDefault();
+ if (!input.isAutoRepeat) host.toggleDevTools();
+ } catch {
+ // guest 或宿主可能已在窗口关闭过程中销毁。
+ }
+ };
+ contents.on("before-input-event", onInput);
+ contents.once("destroyed", () => contents.removeListener("before-input-event", onInput));
+};
+
+module.exports = {bindWebviewDevToolsShortcut};
diff --git a/app/electron/webviewDevTools.test.js b/app/electron/webviewDevTools.test.js
new file mode 100644
index 0000000000..c4af59047e
--- /dev/null
+++ b/app/electron/webviewDevTools.test.js
@@ -0,0 +1,206 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const {EventEmitter} = require("node:events");
+const {readFileSync} = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+const {bindWebviewDevToolsShortcut} = require("./webviewDevTools");
+
+const createContents = (id, type = "window") => Object.assign(new EventEmitter(), {
+ id,
+ destroyed: false,
+ toggled: 0,
+ devToolsOpened: false,
+ getType() { return type; },
+ isDestroyed() { return this.destroyed; },
+ toggleDevTools() { this.toggled++; this.devToolsOpened = !this.devToolsOpened; },
+ destroy() { this.destroyed = true; this.emit("destroyed"); },
+ setWindowOpenHandler(handler) { this.windowOpenHandler = handler; },
+});
+
+const key = (platform = "linux") => ({
+ type: "keyDown", key: "I", code: "KeyI", isAutoRepeat: false,
+ control: platform !== "darwin", shift: platform !== "darwin",
+ meta: platform === "darwin", alt: platform === "darwin",
+});
+
+const press = (contents, input = key()) => {
+ let prevented = 0;
+ contents.emit("before-input-event", {preventDefault() { prevented++; }}, input);
+ return prevented;
+};
+
+const setup = (platform = "linux") => {
+ const host = createContents(1);
+ const guest = createContents(2, "webview");
+ const targets = new Map([[host.id, {mode: "local"}]]);
+ guest.hostWebContents = host;
+ bindWebviewDevToolsShortcut(guest, id => targets.get(id), platform);
+ return {host, guest, targets};
+};
+
+for (const platform of ["win32", "linux", "darwin"]) {
+ test(`webview shortcut toggles only its host on ${platform}`, () => {
+ const {host, guest} = setup(platform);
+ assert.equal(press(guest, key(platform)), 1);
+ assert.equal(host.devToolsOpened, true);
+ assert.equal(guest.toggled, 0);
+ assert.equal(press(guest, {...key(platform), key: "i"}), 1);
+ assert.equal(host.devToolsOpened, false);
+ assert.equal(host.toggled, 2);
+ assert.equal(guest.toggled, 0);
+ assert.equal(host.listenerCount("before-input-event"), 0);
+ });
+
+ test(`webview shortcut leaves unrelated inputs alone on ${platform}`, () => {
+ const {host, guest} = setup(platform);
+ const unrelated = [
+ {type: "keyUp"}, {key: "F12", code: "F12"}, {key: "j", code: "KeyJ"},
+ {key: undefined, code: undefined},
+ ...(platform === "darwin" ? [
+ {meta: false}, {alt: false}, {control: true}, {shift: true},
+ {control: true, shift: true, meta: false, alt: false},
+ ] : [
+ {control: false}, {shift: false}, {meta: true}, {alt: true},
+ {control: false, shift: false, meta: true, alt: true},
+ ]),
+ ];
+ for (const input of unrelated) assert.equal(press(guest, {...key(platform), ...input}), 0);
+ assert.equal(host.toggled, 0);
+ });
+
+ test(`holding the webview shortcut suppresses guest/menu repeats on ${platform}`, () => {
+ const {host, guest} = setup(platform);
+ assert.equal(press(guest, key(platform)), 1);
+ for (let repeat = 0; repeat < 3; repeat++) {
+ assert.equal(press(guest, {...key(platform), isAutoRepeat: true}), 1);
+ }
+ assert.equal(host.toggled, 1);
+ assert.equal(press(guest, key(platform)), 1);
+ assert.equal(host.toggled, 2);
+ });
+}
+
+test("macOS Option-modified characters still match the physical I key", () => {
+ const {host, guest} = setup("darwin");
+ assert.equal(press(guest, {...key("darwin"), key: "ˆ"}), 1);
+ assert.equal(host.toggled, 1);
+});
+
+test("map and plugin guests route to their own main, detached or settings window", () => {
+ const hosts = [1, 2, 3].map(id => createContents(id));
+ const targets = new Map(hosts.map(host => [host.id, {mode: "local"}]));
+ for (const mode of ["local", "remote"]) {
+ for (const host of hosts) {
+ targets.set(host.id, {mode});
+ for (const partition of ["siyuan-map-test", "plugin-test"]) {
+ const guest = createContents(10 + host.id, "webview");
+ guest.hostWebContents = host;
+ guest.partition = partition;
+ bindWebviewDevToolsShortcut(guest, id => targets.get(id), "linux");
+ const before = hosts.map(item => item.toggled);
+ assert.equal(press(guest), 1);
+ hosts.forEach((item, index) => assert.equal(item.toggled, before[index] + (item === host ? 1 : 0)));
+ assert.equal(guest.toggled, 0);
+ }
+ }
+ }
+});
+
+test("host is resolved after attachment and rechecked for each input", () => {
+ const {host, guest, targets} = setup();
+ guest.hostWebContents = null;
+ assert.equal(press(guest), 0);
+ guest.hostWebContents = host;
+ assert.equal(press(guest), 1);
+ const detachedHost = createContents(3);
+ targets.set(detachedHost.id, {mode: "local"});
+ guest.hostWebContents = detachedHost;
+ assert.equal(press(guest), 1);
+ assert.equal(host.toggled, 1);
+ assert.equal(detachedHost.toggled, 1);
+ targets.delete(detachedHost.id);
+ assert.equal(press(guest), 0);
+ assert.equal(detachedHost.toggled, 1);
+});
+
+test("missing, unregistered, non-window and destroyed hosts are ignored", () => {
+ const {host, guest, targets} = setup();
+ for (const invalid of [null, createContents(3), createContents(1, "webview"), createContents(1, "remote")]) {
+ guest.hostWebContents = invalid;
+ assert.equal(press(guest), 0);
+ }
+ guest.hostWebContents = host;
+ targets.delete(host.id);
+ assert.equal(press(guest), 0);
+ targets.set(host.id, {mode: "local"});
+ host.destroy();
+ assert.equal(press(guest), 0);
+ assert.equal(host.toggled, 0);
+});
+
+test("guest destruction removes only the shortcut listener", () => {
+ const {host, guest} = setup();
+ const otherInput = () => {};
+ guest.on("before-input-event", otherInput);
+ assert.equal(guest.listenerCount("before-input-event"), 2);
+ guest.destroy();
+ assert.deepEqual(guest.listeners("before-input-event"), [otherInput]);
+ assert.equal(press(guest), 0);
+ assert.equal(host.toggled, 0);
+});
+
+test("destroyed contents and non-webview contents keep their existing handling", () => {
+ for (const type of ["window", "remote", "browserView", "offscreen", "backgroundPage"]) {
+ const contents = createContents(1, type);
+ bindWebviewDevToolsShortcut(contents, () => ({mode: "local"}));
+ assert.equal(contents.listenerCount("before-input-event"), 0);
+ }
+ const guest = createContents(2, "webview");
+ guest.destroy();
+ bindWebviewDevToolsShortcut(guest, () => ({mode: "local"}));
+ assert.equal(guest.listenerCount("before-input-event"), 0);
+});
+
+test("native destruction races do not escape the input handler", () => {
+ const {host, guest} = setup();
+ Object.defineProperty(guest, "hostWebContents", {get() { throw new Error("Object has been destroyed"); }, configurable: true});
+ assert.equal(press(guest), 0);
+ Object.defineProperty(guest, "hostWebContents", {value: host});
+ host.toggleDevTools = () => { throw new Error("Object has been destroyed"); };
+ assert.equal(press(guest), 1);
+});
+
+test("guest DevTools APIs and other keys do not acquire host behavior", () => {
+ const {host, guest} = setup();
+ guest.toggleDevTools();
+ guest.emit("devtools-opened");
+ assert.equal(guest.devToolsOpened, true);
+ assert.equal(host.toggled, 0);
+ assert.equal(press(guest, {...key(), key: "F12", code: "F12"}), 0);
+ assert.equal(guest.devToolsOpened, true);
+});
+
+test("main installs the generic hook while retaining the window-open policy", () => {
+ const source = readFileSync(path.join(__dirname, "main.js"), "utf8");
+ const start = source.indexOf("app.on(\"web-contents-created\",");
+ const end = source.indexOf("\napp.on(\"before-quit\",", start);
+ assert.ok(start > 0 && end > start);
+ const app = new EventEmitter();
+ const host = createContents(1);
+ const guest = createContents(2, "webview");
+ guest.hostWebContents = host;
+ const opened = [];
+ vm.runInNewContext(source.slice(start, end), {
+ app,
+ bindWebviewDevToolsShortcut: (contents, getTarget) => bindWebviewDevToolsShortcut(contents, getTarget, "linux"),
+ getWindowKernelTarget: id => id === host.id ? {mode: "local"} : undefined,
+ settingsWindowPolicy: () => undefined,
+ shell: {openExternal: url => opened.push(url)},
+ });
+ app.emit("web-contents-created", {}, guest);
+ assert.equal(press(guest), 1);
+ assert.equal(host.toggled, 1);
+ assert.equal(guest.windowOpenHandler({url: "https://example.com"}).action, "deny");
+ assert.deepEqual(opened, ["https://example.com"]);
+});
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
index 0cf979f891..74d3a0f119 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
@@ -7,7 +7,7 @@
"id": "20240208172514-9dsv6na",
"title": "Database",
"type": "doc",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -74,7 +74,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009034010-6kd9rk5",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -102,12 +102,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-h9vridq",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Enter longitude and latitude in their separate fields, for example longitude 116.4074 and latitude 39.9042. Source text stays unchanged when you only edit the name. Manually changing the coordinates clears that source text."
+ "Data": "Enter longitude and latitude in their separate fields, for example longitude 116.4074 and latitude 39.9042. Or click "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Pick on map"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to open the embedded map in the location editor. Clicking the map fills the draft coordinates; click "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Save"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to apply them. Source text stays unchanged when you only edit the name. Changing the coordinates manually or by picking on the map clears that source text. If the map is unavailable, you can still enter coordinates manually."
}
]
},
@@ -116,12 +134,66 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-dub50kq",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Click Save to apply edits or Cancel to discard them. Clear removes the location value. Text filters and sorting use the combined name, coordinates, and fixed WGS84 label. This field does not contact external location services. The app displays longitude, latitude; plain-text copying and export use latitude, longitude. Structured database copying preserves the named latitude and longitude values."
+ "Data": "Click "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Save"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to apply edits or "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Cancel"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to discard them. "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Clear"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " removes the location value. Text filters and sorting use the combined name, coordinates, and fixed WGS84 label. The app displays longitude, latitude; plain-text copying and export use "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "Name; latitude, longitude [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ", omitting the name and semicolon when no name is set. You can paste this text or a WGS84 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "latitude, longitude"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " pair into a Location cell. For example, "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "Beijing; 39.9042, 116.4074 [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " includes both the name and coordinates. Structured database copying preserves the named latitude and longitude values."
}
]
},
@@ -3921,7 +3993,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009050034-byowtq3",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -3977,12 +4049,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-kpnifml",
- "updated": "20261009050034"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Filters and sorting also apply to the map. Markers represent only the loaded records, not the entire database. The displayed counts identify the loaded scope and skipped locations. If there are too many markers, use filters or a smaller page size. Click a marker to open its record; map clicks do not save coordinates"
+ "Data": "Filters and sorting also apply to the map. Markers represent only the loaded records, not the entire database. The displayed counts identify the loaded scope and skipped locations. If there are too many markers, use filters or a smaller page size. Click a marker to open its record. Click an empty area of the map to show a popup with the selected WGS84 coordinates. Use "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Copy"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to copy them, or in an editable view choose "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Create record here"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to create a record with that point in the view's selected Location field. Clicking the map alone does not change any record."
}
]
},
@@ -4005,12 +4095,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-wflckkb",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "The host follows the app theme; the basemap keeps its default style. Maps run in isolated Web pages. Desktop clients use a separate secure host; mobile clients require an app shell that restricts native bridges and navigation to trusted documents. Maps do not load if these boundaries cannot be established. Desktop maps follow page scrolling and clip areas covered by sticky tabs; menus or dialogs may hide them temporarily. When offline, incompatible with WebGL, unable to load the map, or using authentication bypass, switch to a Table view to access records. Address search, geocoding, routing, and clicking the map to save a location are not provided."
+ "Data": "The host follows the app theme; the basemap keeps its default style. Maps run in isolated Web pages. Desktop clients use a separate secure host; mobile clients require an app shell that restricts native bridges and navigation to trusted documents. Maps do not load if these boundaries cannot be established. Desktop maps follow page scrolling and clip areas covered by sticky tabs; menus or dialogs may hide them temporarily. When offline, incompatible with WebGL, unable to load the map, or using authentication bypass, switch to a Table view to access records. Address search, geocoding, routing, and coordinate conversion are not provided."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
index 9a1b0a9934..41fc8fa56f 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
@@ -7,7 +7,7 @@
"id": "20240208113259-nykkvaq",
"title": "数据库",
"type": "doc",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -74,7 +74,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009034010-m7nwg3o",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -102,12 +102,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-grvs8hv",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "请在经度和纬度输入框中分别填写坐标,例如经度 116.4074、纬度 39.9042。仅修改名称时,保留的来源文本保持不变;手动修改坐标会清除来源文本。"
+ "Data": "在经度和纬度输入框中分别填写坐标,例如经度 116.4074、纬度 39.9042。也可点击 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "地图选点"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 打开位置编辑器内嵌的地图。点击地图会填入草稿坐标,再点击 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 才会应用。仅修改名称时,保留的来源文本保持不变;手动修改坐标或地图选点会清除来源文本。地图不可用时,仍可手动填写坐标。"
}
]
},
@@ -116,12 +134,66 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-kag8uox",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "点击「保存」应用修改,点击「取消」放弃修改,「清空」会移除位置值。文本过滤和排序使用名称、坐标及固定 WGS84 标记组合后的文本。此字段不调用外部位置服务。应用内按经度、纬度顺序显示;纯文本复制和导出使用纬度、经度顺序。数据库内的结构化复制保留经纬度各自的命名字段值。"
+ "Data": "点击 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 应用修改,点击 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "取消"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 放弃修改,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "清空"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 会移除位置值。文本过滤和排序使用名称、坐标及固定 WGS84 标记组合后的文本。应用内按经度、纬度顺序显示;纯文本复制和导出使用 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "名称; 纬度, 经度 [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 格式,未填写名称时省略名称及分号。可将该文本或 WGS84 的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "纬度, 经度"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 坐标对粘贴到位置单元格。例如 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "北京; 39.9042, 116.4074 [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 同时包含名称和坐标。数据库内的结构化复制保留经纬度各自的命名字段值。"
}
]
},
@@ -3921,7 +3993,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009050034-dfwj4cb",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -3977,12 +4049,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-ughi4hh",
- "updated": "20261009050034"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "筛选和排序同样作用于地图。标记只代表已加载的记录,不代表整个数据库;界面会说明已加载范围及跳过的位置数量。标记过多时请缩小分页或使用筛选。点击标记打开对应记录,点击地图不会保存坐标"
+ "Data": "筛选和排序同样作用于地图。标记只代表已加载的记录,不代表整个数据库;界面会说明已加载范围及跳过的位置数量。标记过多时请缩小分页或使用筛选。点击标记打开对应记录。点击地图空白处会弹出所选点的 WGS84 坐标,可点击 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "复制"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 复制坐标;在可编辑视图中,还可选择 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "在此创建条目"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",创建条目并将该点写入视图选定的位置字段。仅点击地图不会更改任何记录。"
}
]
},
@@ -4005,12 +4095,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-wy69fcu",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "宿主配色跟随应用主题,底图保留默认样式。地图通过隔离的 Web 页面运行;桌面客户端使用独立的安全宿主,移动客户端需搭配限制原生桥和导航仅用于可信主文档的外壳。无法建立隔离边界时不加载地图。桌面地图随页面滚动并裁剪吸顶栏覆盖的区域,菜单或对话框遮挡时可能暂时隐藏。离线、WebGL 不兼容、地图加载失败或启用鉴权绕过模式时,可切换到表格视图访问记录。本功能不提供地址搜索、地理编码、路线规划或点击地图保存位置。"
+ "Data": "宿主配色跟随应用主题,底图保留默认样式。地图通过隔离的 Web 页面运行;桌面客户端使用独立的安全宿主,移动客户端需搭配限制原生桥和导航仅用于可信主文档的外壳。无法建立隔离边界时不加载地图。桌面地图随页面滚动并裁剪吸顶栏覆盖的区域,菜单或对话框遮挡时可能暂时隐藏。离线、WebGL 不兼容、地图加载失败或启用鉴权绕过模式时,可切换到表格视图访问记录。本功能不提供地址搜索、地理编码、路线规划或坐标转换。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
index 630e0153bc..6454a1a732 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
@@ -7,7 +7,7 @@
"id": "20240208171522-y7dxcno",
"title": "資料庫",
"type": "doc",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -74,7 +74,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009034010-5oq6h7a",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -102,12 +102,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-ue87c6m",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "請在經度和緯度輸入框中分別填寫座標,例如經度 116.4074、緯度 39.9042。僅修改名稱時,保留的來源文字維持不變;手動修改座標會清除來源文字。"
+ "Data": "在經度和緯度輸入框中分別填寫座標,例如經度 116.4074、緯度 39.9042。也可點擊 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "地圖選點"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 開啟位置編輯器內嵌的地圖。點擊地圖會填入草稿座標,再點擊 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 才會套用。僅修改名稱時,保留的來源文字維持不變;手動修改座標或地圖選點會清除來源文字。地圖無法使用時,仍可手動填寫座標。"
}
]
},
@@ -116,12 +134,66 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-g7jsd2p",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "點擊「保存」套用修改,點擊「取消」放棄修改,「清空」會移除位置值。文字過濾和排序使用名稱、座標及固定 WGS84 標記組合後的文字。此欄位不呼叫外部位置服務。應用程式內依經度、緯度順序顯示;純文字複製和匯出使用緯度、經度順序。資料庫內的結構化複製保留經緯度各自的具名欄位值。"
+ "Data": "點擊 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 套用修改,點擊 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "取消"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 放棄修改,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "清空"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 會移除位置值。文字過濾和排序使用名稱、座標及固定 WGS84 標記組合後的文字。應用程式內依經度、緯度順序顯示;純文字複製和匯出使用 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "名稱; 緯度, 經度 [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 格式,未填寫名稱時省略名稱及分號。可將該文字或 WGS84 的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "緯度, 經度"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 座標對貼上至位置儲存格。例如 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "北京; 39.9042, 116.4074 [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 同時包含名稱和座標。資料庫內的結構化複製保留經緯度各自的具名欄位值。"
}
]
},
@@ -3921,7 +3993,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009050034-7n1yzkx",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -3977,12 +4049,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-3r0lsdq",
- "updated": "20261009050034"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "篩選和排序同樣作用於地圖。標記只代表已載入的記錄,不代表整個資料庫;介面會說明已載入範圍及跳過的位置數量。標記過多時請縮小分頁或使用篩選。點擊標記開啟對應記錄,點擊地圖不會儲存座標"
+ "Data": "篩選和排序同樣作用於地圖。標記只代表已載入的記錄,不代表整個資料庫;介面會說明已載入範圍及跳過的位置數量。標記過多時請縮小分頁或使用篩選。點擊標記開啟對應記錄。點擊地圖空白處會彈出所選點的 WGS84 座標,可點擊 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "複製"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 複製座標;在可編輯檢視中,還可選擇 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "在此建立項目"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",建立項目並將該點寫入檢視選定的位置欄位。僅點擊地圖不會變更任何記錄。"
}
]
},
@@ -4005,12 +4095,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-8jfc6yh",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "宿主配色跟隨應用程式主題,底圖保留預設樣式。地圖透過隔離的 Web 頁面執行;桌面客戶端使用獨立的安全宿主,行動客戶端需搭配限制原生橋和導覽僅用於可信主文件的外殼。無法建立隔離邊界時不載入地圖。桌面地圖隨頁面捲動並裁剪置頂分頁列覆蓋的區域,選單或對話方塊遮擋時可能暫時隱藏。離線、WebGL 不相容、地圖載入失敗或啟用鑑權繞過模式時,可切換到表格檢視存取記錄。本功能不提供地址搜尋、地理編碼、路線規劃或點擊地圖儲存位置。"
+ "Data": "宿主配色跟隨應用程式主題,底圖保留預設樣式。地圖透過隔離的 Web 頁面執行;桌面客戶端使用獨立的安全宿主,行動客戶端需搭配限制原生橋和導覽僅用於可信主文件的外殼。無法建立隔離邊界時不載入地圖。桌面地圖隨頁面捲動並裁剪置頂分頁列覆蓋的區域,選單或對話方塊遮擋時可能暫時隱藏。離線、WebGL 不相容、地圖載入失敗或啟用鑑權繞過模式時,可切換到表格檢視存取記錄。本功能不提供地址搜尋、地理編碼、路線規劃或座標轉換。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
index cde1f896c4..f858852db1 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-3eaevtp",
"title": "データベース",
"type": "doc",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -75,7 +75,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009034010-6j4iniw",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -103,12 +103,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-1609sdo",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "経度と緯度は、それぞれの入力欄に入力してください。例えば、経度には 116.4074、緯度には 39.9042 を入力します。名前だけを変更すると出典テキストは保持されます。座標を手動で変更すると、出典テキストは消去されます。"
+ "Data": "経度と緯度は、それぞれの入力欄に入力します。例えば、経度には 116.4074、緯度には 39.9042 を入力します。または "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "地図で選択"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " をクリックすると、位置エディター内に埋め込み地図が開きます。地図をクリックすると下書きに座標が入力され、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " をクリックすると適用されます。名前だけを変更すると出典テキストは保持されます。座標を手動で変更したり、地図で選択したりすると、出典テキストは消去されます。地図を利用できない場合も、座標を手動で入力できます。"
}
]
},
@@ -117,12 +135,62 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009034010-fry67po",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で変更を適用し、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "キャンセル"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で破棄します。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "消去"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " は位置の値を削除します。テキストのフィルターとソートには、名前、座標、固定の WGS84 ラベルを組み合わせたテキストを使用します。アプリ内では経度、緯度の順に表示し、プレーンテキストのコピーとエクスポートでは "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "名前; 緯度, 経度 [WGS84]"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " の形式で出力します。名前がない場合は名前とセミコロンを省略します。このテキスト、または WGS84 の "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "緯度, 経度"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " の組を位置セルに貼り付けられます。例えば "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "北京; 39.9042, 116.4074 [WGS84]"
+ },
{
"Type": "NodeText",
- "Data": "「保存」で変更を適用し、「キャンセル」で破棄します。「消去」は位置の値を削除します。テキストのフィルターとソートには、名前、座標、固定の WGS84 ラベルを組み合わせたテキストを使用します。このフィールドは外部の位置情報サービスに接続しません。アプリ内では経度、緯度の順に表示し、プレーンテキストのコピーとエクスポートでは緯度、経度の順に出力します。データベース内の構造化コピーは、経度と緯度それぞれの名前付きフィールドの値を保持します。"
+ "Data": " には名前と座標が含まれます。データベース内の構造化コピーは、経度と緯度それぞれの名前付きフィールドの値を保持します。"
}
]
},
@@ -3931,7 +3999,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261009050034-lzsqdz2",
- "updated": "20261010233500"
+ "updated": "20261011093258"
},
"Children": [
{
@@ -3987,12 +4055,30 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-e6lcmxa",
- "updated": "20261009050034"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "フィルターと並べ替えは地図にも適用されます。マーカーは読み込み済みのレコードだけを表し、データベース全体ではありません。読み込み範囲と除外件数を画面に表示します。マーカーが多すぎる場合はフィルターや小さいページサイズを使用してください。マーカーをクリックするとレコードを開きます。地図のクリックでは座標を保存しません"
+ "Data": "フィルターと並べ替えは地図にも適用されます。マーカーは読み込み済みのレコードだけを表し、データベース全体ではありません。読み込み範囲と除外件数を画面に表示します。マーカーが多すぎる場合はフィルターや小さいページサイズを使用してください。マーカーをクリックするとレコードを開きます。地図の何もない場所をクリックすると、選択した地点の WGS84 座標がポップアップに表示されます。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "コピー"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で座標をコピーできます。編集可能なビューでは "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "ここに項目を作成"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を選ぶと、ビューで選択中の位置フィールドにその地点を設定した項目を作成できます。地図をクリックするだけではレコードは変更されません。"
}
]
},
@@ -4015,12 +4101,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261009050034-5qz3tt7",
- "updated": "20261010064719"
+ "updated": "20261011093258"
},
"Children": [
{
"Type": "NodeText",
- "Data": "ホストの配色はアプリのテーマに従い、ベースマップは既定のスタイルを維持します。地図は隔離された Web ページで動作します。デスクトップ版は独立した安全なホストを使用し、モバイル版はネイティブブリッジと画面遷移を信頼された主文書に制限するアプリが必要です。隔離を確立できない場合は地図を読み込みません。デスクトップでは地図がスクロールに追従し、固定タブに重なる部分を切り取ります。メニューやダイアログが重なる間は一時的に非表示になる場合があります。オフライン、WebGL 非対応、地図の読み込み失敗、認証バイパスの有効時には、テーブルビューでレコードを利用できます。住所検索、ジオコーディング、経路案内、地図クリックによる位置の保存は提供しません。"
+ "Data": "ホストの配色はアプリのテーマに従い、ベースマップは既定のスタイルを維持します。地図は隔離された Web ページで動作します。デスクトップ版は独立した安全なホストを使用し、モバイル版はネイティブブリッジと画面遷移を信頼された主文書に制限するアプリが必要です。隔離を確立できない場合は地図を読み込みません。デスクトップでは地図がスクロールに追従し、固定タブに重なる部分を切り取ります。メニューやダイアログが重なる間は一時的に非表示になる場合があります。オフライン、WebGL 非対応、地図の読み込み失敗、認証バイパスの有効時には、テーブルビューでレコードを利用できます。住所検索、ジオコーディング、経路案内、座標変換は提供しません。"
}
]
},
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index 3ad13996c1..58781eae3b 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -1,5 +1,15 @@
@use "../component/record-inbox";
+.av__location-picker {
+ margin-top: 8px;
+}
+
+.av__location-picker-canvas {
+ height: clamp(180px, 35vh, 280px);
+ position: relative;
+ overflow: hidden;
+}
+
.av__map {
width: 100%;
min-width: 0;
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index efce44904b..2332fa4570 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -64,7 +64,7 @@ import {getAVData, getAVPrimaryCell} from "./virtualScroll";
import {AV_CELL_EDITOR_CLOSE_EVENT, getAVCellEditorOwner} from "./cellEditor";
import {getAVBlockIconHTML, renderAVBlockIcon} from "./blockIcon";
import {bindAnchoredInputPosition} from "../../../dialog/anchoredInputPosition";
-import {createAVLocationFromText, createAVLocationReplacement, getAVLocationDisplayText, getAVLocationText, isAVLocationCoordinateInput, isAVLocationEmpty} from "./locationValue";
+import {createAVLocationFromText, createAVLocationReplacement, getAVLocationDisplayText, getAVLocationText, isAVLocationEmpty} from "./locationValue";
import {openAVLocationEditor} from "./locationEditor";
import {showMessage} from "../../../dialog/message";
@@ -1156,7 +1156,9 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
if (type === "location" && (typeof newValue === "string" ||
(newValue?.type && newValue.type !== "location" && !cellValueIsEmpty(newValue)))) {
const content = typeof newValue === "string" ? newValue : getCellValueContent(newValue) || "";
- if (isAVLocationCoordinateInput(content)) {
+ try {
+ createAVLocationFromText(content);
+ } catch {
showMessage(window.siyuan.languages.locationPasteInEditor, 6000, "error");
continue;
}
diff --git a/app/src/protyle/render/av/locationEditor.test.ts b/app/src/protyle/render/av/locationEditor.test.ts
index 132f3d23a3..b09db168a9 100644
--- a/app/src/protyle/render/av/locationEditor.test.ts
+++ b/app/src/protyle/render/av/locationEditor.test.ts
@@ -19,6 +19,8 @@ class Control {
classes = new Set<string>();
classList = {
toggle: (name: string, enabled: boolean) => enabled ? this.classes.add(name) : this.classes.delete(name),
+ add: (name: string) => this.classes.add(name),
+ remove: (name: string) => this.classes.delete(name),
};
focused = false;
focus() {
@@ -29,7 +31,7 @@ class Control {
this.listeners.set(name, handler);
}
dispatch(name: string, event = {}) {
- this.listeners.get(name)?.(event);
+ this.listeners.get(name)?.({currentTarget: this, ...event});
}
}
@@ -42,9 +44,13 @@ const createEditor = (options: {
} = {}) => {
const fields = Object.fromEntries(["name", "latitude", "longitude"]
.map(name => [name, new Control()]));
- const buttons = Object.fromEntries(["save", "clear", "cancel"].map(name => [name, new Control()]));
+ const buttons = Object.fromEntries(["save", "clear", "cancel", "pick"].map(name => [name, new Control()]));
const container = new Control();
const error = new Control();
+ const mapCanvas = new Control();
+ const mapStatus = new Control();
+ const pickers: Array<{options: Parameters<typeof import("./map/locationPicker").createAVLocationPicker>[0];
+ points: unknown[]; destroyed: boolean}> = [];
const lifecycle: string[] = [];
const saved: IAVCellLocationValue[] = [];
const owner = {isConnected: true};
@@ -57,6 +63,8 @@ const createEditor = (options: {
if (selector === '[data-role="error"]') {
return error;
}
+ if (selector === '[data-role="map-canvas"]') return mapCanvas;
+ if (selector === '[data-role="map-status"]') return mapStatus;
const field = selector.match(/data-field="(\w+)"/);
const action = selector.match(/data-action="(\w+)"/);
return field ? fields[field[1]] : buttons[action[1]];
@@ -95,6 +103,17 @@ const createEditor = (options: {
}},
"./locationValue": locationValue,
"./cellEditor": {AV_CELL_EDITOR_CLOSE_EVENT: "siyuan-av-cell-editor-close"},
+ "./map/locationPicker": {createAVLocationPicker: (options: typeof pickers[number]["options"]) => {
+ const picker = {options, points: [] as unknown[], destroyed: false};
+ pickers.push(picker);
+ return {
+ setPoint: (point: unknown) => picker.points.push(point),
+ destroy: () => {
+ picker.destroyed = true;
+ lifecycle.push("destroy-picker");
+ },
+ };
+ }},
};
runInNewContext(compiled, {
exports: methods,
@@ -128,7 +147,7 @@ const createEditor = (options: {
onDestroy: () => lifecycle.push("on-destroy"),
});
return {
- fields, buttons, error, root, lifecycle, saved, owner, dialog, markup,
+ fields, buttons, error, root, lifecycle, saved, owner, dialog, markup, pickers, mapCanvas, mapStatus,
ownerChanged: () => ownerChanged(),
closeSheet: () => closeSheet(),
settle: () => new Promise<void>(resolve => setImmediate(resolve)),
@@ -377,4 +396,116 @@ describe("database location editor", () => {
assert.equal(editor.lifecycle.includes("blur"), true);
});
+ it("opens one lazy embedded picker and commits its latest draft only on Save on desktop and mobile", async () => {
+ for (const mobile of [false, true]) {
+ const editor = createEditor({mobile, value: {name: "Office", latitude: 20, longitude: 30,
+ originalInput: "Legacy source"}});
+ assert.equal(editor.pickers.length, 0);
+ editor.buttons.pick.dispatch("click");
+ editor.buttons.pick.dispatch("click");
+ assert.equal(editor.pickers.length, 1);
+ const picker = editor.pickers[0];
+ assert.equal(picker.options.canvas, editor.mapCanvas);
+ assert.deepEqual(JSON.parse(JSON.stringify(picker.options.point)), {longitude: 30, latitude: 20});
+ assert.equal(picker.options.onPick({longitude: 110, latitude: 40}), true);
+ assert.equal(picker.options.onPick({longitude: -0.0000001, latitude: 0}), true);
+ assert.equal(editor.fields.longitude.value, "-0.0000001");
+ assert.equal(editor.fields.latitude.value, "0");
+ assert.equal(editor.fields.name.value, "Office");
+ assert.equal(editor.saved.length, 0);
+ editor.buttons.save.dispatch("click");
+ await editor.settle();
+ assert.deepEqual(editor.saved, [{name: "Office", longitude: -0.0000001, latitude: 0, originalInput: ""}]);
+ assert.equal(picker.destroyed, true);
+ assert.equal(editor.lifecycle.filter(item => item === "destroy-picker").length, 1);
+ }
+ });
+
+ it("updates the same picker with manual coordinate drafts without committing", () => {
+ const editor = createEditor();
+ editor.buttons.pick.dispatch("click");
+ editor.fields.longitude.value = "102.42";
+ editor.fields.latitude.value = "25.04";
+ editor.fields.latitude.dispatch("input");
+ assert.deepEqual(JSON.parse(JSON.stringify(editor.pickers[0].points)), [{longitude: 102.42, latitude: 25.04}]);
+ assert.equal(editor.saved.length, 0);
+ editor.fields.latitude.value = "invalid";
+ editor.fields.latitude.dispatch("input");
+ assert.equal(editor.pickers[0].points.length, 2);
+ assert.equal(editor.fields.latitude.value, "invalid");
+ });
+
+ it("does not change the saved value or provenance merely by opening the map", async () => {
+ const editor = createEditor({value: {name: "Office", longitude: 30, latitude: 20, originalInput: "Legacy source"}});
+ editor.buttons.pick.dispatch("click");
+ editor.buttons.save.dispatch("click");
+ await editor.settle();
+ assert.equal(editor.saved.length, 0);
+ assert.equal(editor.pickers[0].destroyed, true);
+ });
+
+ it("keeps manual fields and Save available while an opened picker is loading or unavailable", async () => {
+ const editor = createEditor();
+ editor.buttons.pick.dispatch("click");
+ editor.mapStatus.textContent = "mapLoadError";
+ assert.equal(editor.buttons.save.disabled, false);
+ assert.equal(editor.fields.latitude.disabled, false);
+ assert.equal(editor.fields.longitude.disabled, false);
+ editor.fields.latitude.value = "20";
+ editor.fields.longitude.value = "30";
+ editor.fields.latitude.dispatch("input");
+ editor.buttons.save.dispatch("click");
+ await editor.settle();
+ assert.deepEqual(editor.saved, [{name: "", longitude: 30, latitude: 20, originalInput: ""}]);
+ });
+
+ it("discards picked coordinates and disposes the picker on Cancel, Escape, navigation and mobile dismissal", async () => {
+ for (const action of ["cancel", "escape", "navigation", "sheet", "disconnect"]) {
+ const editor = createEditor({mobile: action === "sheet"});
+ editor.buttons.pick.dispatch("click");
+ const picker = editor.pickers[0];
+ picker.options.onPick({longitude: 110, latitude: 40});
+ if (action === "escape") editor.key("Escape");
+ else if (action === "navigation") editor.root.dispatch("siyuan-av-cell-editor-close");
+ else if (action === "sheet") await editor.closeSheet();
+ else if (action === "disconnect") {
+ editor.owner.isConnected = false;
+ editor.ownerChanged();
+ } else editor.buttons.cancel.dispatch("click");
+ assert.equal(picker.options.isCurrent(), false);
+ assert.equal(picker.options.onPick({longitude: 111, latitude: 41}), false);
+ editor.buttons.save.dispatch("click");
+ await editor.settle();
+ assert.equal(editor.saved.length, 0);
+ assert.equal(editor.fields.longitude.value, "110");
+ assert.equal(editor.lifecycle.filter(item => item === "destroy-picker").length, 1);
+ }
+ });
+
+ it("rejects stale owner identity during map callbacks and does not open a picker for a stale owner", () => {
+ let valid = true;
+ const editor = createEditor({isValid: () => valid});
+ editor.buttons.pick.dispatch("click");
+ valid = false;
+ assert.equal(editor.pickers[0].options.isCurrent(), false);
+ assert.equal(editor.pickers[0].destroyed, true);
+ assert.equal(editor.saved.length, 0);
+ const stale = createEditor({isValid: () => false});
+ stale.buttons.pick.dispatch("click");
+ assert.equal(stale.pickers.length, 0);
+ });
+
+ it("ignores map clicks while saving and preserves the committed draft", async () => {
+ let complete: () => void;
+ const editor = createEditor({save: () => new Promise<void>(resolve => complete = resolve)});
+ editor.buttons.pick.dispatch("click");
+ editor.pickers[0].options.onPick({longitude: 110, latitude: 40});
+ editor.buttons.save.dispatch("click");
+ assert.equal(editor.pickers[0].options.onPick({longitude: 111, latitude: 41}), false);
+ assert.equal(editor.fields.longitude.value, "110");
+ assert.deepEqual(editor.saved, [{name: "", longitude: 110, latitude: 40, originalInput: ""}]);
+ complete();
+ await editor.settle();
+ });
+
});
diff --git a/app/src/protyle/render/av/locationEditor.ts b/app/src/protyle/render/av/locationEditor.ts
index 03d848fe9c..a1c930e4a8 100644
--- a/app/src/protyle/render/av/locationEditor.ts
+++ b/app/src/protyle/render/av/locationEditor.ts
@@ -7,6 +7,7 @@ import {activeBlur} from "../../../mobile/util/keyboardToolbar";
/// #endif
import {beginAVEditorSession} from "./editorSession";
import {AV_CELL_EDITOR_CLOSE_EVENT} from "./cellEditor";
+import {createAVLocationPicker} from "./map/locationPicker";
import {
areAVLocationsEqual,
createAVLocationReplacement,
@@ -38,6 +39,7 @@ export const openAVLocationEditor = (options: AVLocationEditorOptions) => {
let composing = false;
let disposeSheet: (() => void) | undefined;
let ownerObserver: MutationObserver | undefined;
+ let mapPicker: ReturnType<typeof createAVLocationPicker> | undefined;
const endEditorSession = options.ownerElement ? beginAVEditorSession(options.ownerElement) : undefined;
const dialog = new Dialog({
title: escapeHtml(languages.location),
@@ -57,6 +59,11 @@ export const openAVLocationEditor = (options: AVLocationEditorOptions) => {
<span class="fn__hr"></span><input class="b3-text-field fn__block" data-field="latitude" type="text" inputmode="decimal" spellcheck="false">
</label>
</div>
+ <div class="av__location-picker">
+ <button type="button" class="b3-button b3-button--outline" data-action="pick">${escapeHtml(languages.locationPickOnMap)}</button>
+ <div class="ft__on-surface" data-role="map-status" role="status" aria-live="polite"></div>
+ <div class="av__location-picker-canvas fn__none" data-role="map-canvas"></div>
+ </div>
<div class="ft__error fn__none" style="margin-top:8px" data-role="error" role="alert" aria-live="polite"></div>
</div>
<div class="b3-dialog__action">
@@ -96,6 +103,7 @@ export const openAVLocationEditor = (options: AVLocationEditorOptions) => {
}
closing = true;
ownerObserver?.disconnect();
+ mapPicker?.destroy();
disposeSheet?.();
/// #if MOBILE
if (mobile && root.contains(document.activeElement)) {
@@ -108,6 +116,40 @@ export const openAVLocationEditor = (options: AVLocationEditorOptions) => {
const isOwnerConnected = () => (!options.ownerElement || options.ownerElement.isConnected) &&
(!options.isValid || options.isValid());
+ const currentPoint = () => ({
+ longitude: parseAVLocationCoordinate(longitudeInput.value),
+ latitude: parseAVLocationCoordinate(latitudeInput.value),
+ });
+ root.querySelector<HTMLButtonElement>('[data-action="pick"]').addEventListener("click", event => {
+ if (mapPicker || saving || closing || composing) return;
+ if (!isOwnerConnected()) {
+ dialog.destroy();
+ return;
+ }
+ (event.currentTarget as HTMLElement).classList.add("fn__none");
+ /// #if MOBILE
+ if (mobile) activeBlur(true);
+ /// #endif
+ mapPicker = createAVLocationPicker({
+ canvas: root.querySelector<HTMLElement>('[data-role="map-canvas"]'),
+ status: root.querySelector<HTMLElement>('[data-role="map-status"]'),
+ point: currentPoint(),
+ isCurrent: () => {
+ if (closing) return false;
+ if (isOwnerConnected()) return true;
+ dialog.destroy();
+ return false;
+ },
+ onPick: point => {
+ if (saving || closing || composing) return false;
+ longitudeInput.value = formatAVLocationCoordinate(point.longitude);
+ latitudeInput.value = formatAVLocationCoordinate(point.latitude);
+ originalInput = undefined;
+ setError();
+ return true;
+ },
+ });
+ });
const submit = async (clear = false) => {
if (saving || closing || composing) {
return;
@@ -164,6 +206,7 @@ export const openAVLocationEditor = (options: AVLocationEditorOptions) => {
const clearProvenance = () => {
originalInput = undefined;
setError();
+ mapPicker?.setPoint(currentPoint());
};
[latitudeInput, longitudeInput].forEach(input => input.addEventListener("input", clearProvenance));
root.addEventListener("compositionstart", () => composing = true);
diff --git a/app/src/protyle/render/av/locationIntegration.test.ts b/app/src/protyle/render/av/locationIntegration.test.ts
index 7c09230be2..bffde69c41 100644
--- a/app/src/protyle/render/av/locationIntegration.test.ts
+++ b/app/src/protyle/render/av/locationIntegration.test.ts
@@ -106,7 +106,8 @@ test("location copies preserve canonical text for cells, nested leaves and templ
assert.equal(cell.getCellText(attributeTemplate), "Custom display");
assert.equal(cell.getCellText(attributeTemplate, "display"), "Custom display");
assert.equal(cell.getCellValueText(first), "20, 30 [WGS84]");
- assert.throws(() => cell.genCellValue("location", cell.getCellValueText(first)));
+ assert.deepEqual(cell.genCellValue("location", cell.getCellValueText(first)).location,
+ locationValue.createAVLocationReplacement({...first.location, originalInput: "20, 30 [WGS84]"}));
});
test("location hover text explicitly uses display order instead of clipboard order", () => {
@@ -129,7 +130,7 @@ test("selected location copies keep structured values and latitude-first TSV ind
assert.deepEqual(cell.genCellValue("location", copied.json[0][0].location).location, value.location);
});
-test("location generic paste keeps place names and rejects coordinates without guessing", () => {
+test("location generic paste keeps place names and accepts only latitude-first WGS84 coordinates", () => {
for (const coordinateSystem of ["wgs84", "gcj02", "bd09", "unknown"]) {
const tagged = {latitude: 20, longitude: 30, coordinateSystem};
assert.throws(() => cell.genCellValue("location", tagged), /Invalid WGS84 location/);
@@ -142,7 +143,10 @@ test("location generic paste keeps place names and rejects coordinates without g
assert.equal("coordinateSystem" in value.location, false);
assert.equal(value.location.latitude, null);
assert.equal(value.location.longitude, null);
- for (const text of ["31.20, 121.40", "91, 0", "Home; 0, 0 [WGS84]"]) {
+ for (const text of ["31.20, 121.40", "Home; 0, 0 [WGS84]"]) {
+ assert.deepEqual(cell.genCellValue("location", text).location, locationValue.createAVLocationFromText(text));
+ }
+ for (const text of ["91, 0", "121.40, 31.20", "Home; 0, 0 [GCJ-02]"]) {
assert.throws(() => cell.genCellValue("location", text));
}
assert.equal(inferAVPasteColumnType(["31.20, 121.40", "0, 0"]), "text");
@@ -226,11 +230,24 @@ test("location update, clear, structured paste and undo send full replacement pa
if (undo.action === "updateAttrViewCell") {
assert.deepEqual(JSON.parse(JSON.stringify(undo.data.location)), locationValue.createAVLocationReplacement());
}
- for (const input of ["91, 0", "31,", "Home; 0, 0 [WGS84]"]) {
+ for (const input of ["91, 0", "31,", "Home; 0, 0 [GCJ-02]"]) {
const result = await update(input);
assert.equal(result.doOperations.length, 0);
}
assert.equal(warnings.length, 3);
+ for (const input of ["31.20, 121.40", "Home; 0, 0 [WGS84]",
+ {type: "text", text: {content: "Office; Campus; -90, 180 [WGS84]"}}]) {
+ const result = await update(input);
+ const operation = result.doOperations[0];
+ const undo = result.undoOperations[0];
+ if (operation.action !== "updateAttrViewCell" || undo.action !== "updateAttrViewCell") {
+ assert.fail("expected text location paste and undo");
+ }
+ const text = typeof input === "string" ? input : input.text.content;
+ assert.deepEqual(JSON.parse(JSON.stringify(operation.data.location)), locationValue.createAVLocationFromText(text));
+ assert.deepEqual(JSON.parse(JSON.stringify(undo.data.location)), oldLocation);
+ }
+ assert.equal(warnings.length, 3);
});
test("template and automation value buttons preserve the structured location until explicitly edited", () => {
diff --git a/app/src/protyle/render/av/locationValue.test.ts b/app/src/protyle/render/av/locationValue.test.ts
index cf149a3aba..261744e8f7 100644
--- a/app/src/protyle/render/av/locationValue.test.ts
+++ b/app/src/protyle/render/av/locationValue.test.ts
@@ -24,24 +24,64 @@ describe("database location values", () => {
}
});
it("keeps ordinary text as names without inference and replaces stale coordinates", () => {
- for (const text of [" Office ", "https://maps.example.com/?lat=31&lon=121", "geo:31,121"]) {
+ for (const text of [" Office ", "https://maps.example.com/?lat=31&lon=121", "geo:31,121",
+ "Cafe, 12 Main Street", "Paris, France", "Office; Cafe", "123, Main Street", "Office [WGS84]"]) {
assert.deepEqual(createAVLocationFromText(text), {
name: text.trim(), latitude: null, longitude: null, originalInput: text,
});
}
});
- it("requires the location editor for coordinate-looking or canonical pasted text", () => {
- for (const source of ["31.2,121.5", "(102.42,25.04)", " (20,30) ", "31,", ",121", "31,121,0", "181,91", "1e-7,-1e-7", "NaN,Infinity", "0,0 [WGS84]",
- "Office; 0, 0 [GCJ-02]", "Office; 0, 0 [BD-09]"]) {
+ it("accepts latitude-first WGS84 decimal text without swapping coordinates or discarding provenance", () => {
+ for (const [source, name, latitude, longitude] of [
+ ["31.20, 121.40", "", 31.2, 121.4],
+ [" +31.20, +121.40 [WGS84] ", "", 31.2, 121.4],
+ ["Home; 0, 0 [WGS84]", "Home", 0, 0],
+ [" Office; Campus; -90, 180 [WGS84] ", "Office; Campus", -90, 180],
+ ["90,-180", "", 90, -180],
+ ["+.5,-.25", "", .5, -.25],
+ ["1.,-0", "", 1, -0],
+ ["0.0000001, -0.00000001 [WGS84]", "", 1e-7, -1e-8],
+ ["20,30", "", 20, 30],
+ ] as const) {
assert.equal(isAVLocationCoordinateInput(source), true, source);
- assert.throws(() => createAVLocationFromText(source));
+ assert.deepEqual(createAVLocationFromText(source), {name, latitude, longitude, originalInput: source}, source);
+ }
+ });
+
+ it("rejects malformed, ambiguous, nondecimal, out-of-range and non-WGS84 coordinate candidates", () => {
+ for (const source of ["(102.42,25.04)", " (20,30) ", "[20,30]", "(20,30", "20,30)",
+ "31,", ",121", ",", "31,+", "-,121", "31,121,0", "181,91", "91,0", "-90.01,0", "0,180.01", "0,-181",
+ "121.40,31.20", "1e-7,-1e-7", "NaN,Infinity", "0x10,0x20", "31..2,121", "--31,121", "1e,0",
+ "Office; 0, 0", "Office; 31,", "Office; 91, 0 [WGS84]", "; 0, 0 [WGS84]",
+ "Office; 0, 0 [GCJ-02]", "Office; 0, 0 [BD-09]", "0,0 [unknown]", "0,0 [wgs84]",
+ "0,0 [WGS84", "0,0 [WGS84] extra", "0,0 []", "0,0 [GCJ-02; BD-09]",
+ "Office; 0,0 [GCJ-02, BD-09]", "(0,0) [GCJ-02]", `${"9".repeat(400)}, 0`]) {
+ assert.equal(isAVLocationCoordinateInput(source), true, source);
+ assert.throws(() => createAVLocationFromText(source), /Invalid WGS84 location/, source);
}
assert.equal(isAVLocationCoordinateInput("Cafe, 12 Main Street"), false);
assert.equal(isAVLocationCoordinateInput("Paris, France"), false);
assert.equal(isAVLocationCoordinateInput("Office; Cafe"), false);
});
+ it("round-trips canonical coordinates with delimiter-containing and coordinate-like names", () => {
+ for (const name of ["", ";", "Office;", "Office; Campus", "20, 30", "Origin; 0, 0 [GCJ-02]", "[WGS84]", "Office\nCampus"]) {
+ const value = {name, latitude: 31.2, longitude: 121.4};
+ const text = getAVLocationText(value);
+ assert.deepEqual(createAVLocationFromText(text), {...value, originalInput: text});
+ }
+ });
+
+ it("preserves long ordinary names with whitespace after a semicolon", () => {
+ for (const separator of [";", ""]) {
+ const name = "Office" + separator + " ".repeat(10000) + "Campus";
+ assert.deepEqual(createAVLocationFromText(name), {
+ name, latitude: null, longitude: null, originalInput: name,
+ });
+ }
+ });
+
it("produces complete replacement payloads for clearing merged backend values", () => {
assert.deepEqual(createAVLocationReplacement(), {
name: "", latitude: null, longitude: null, originalInput: "",
@@ -106,7 +146,9 @@ describe("database location values", () => {
assert.equal(getAVLocationDisplayText(location), "Office 30, 20");
assert.equal(getAVLocationText(location), `Office; 20, 30 [${label}]`);
assert.deepEqual(location, before);
- assert.throws(() => createAVLocationFromText(getAVLocationText(location)));
+ assert.deepEqual(createAVLocationFromText(getAVLocationText(location)), {
+ ...location, originalInput: getAVLocationText(location),
+ });
assert.equal(getAVLocationDisplayText({latitude: 1e-7, longitude: -1e-8}), "-0.00000001, 0.0000001");
assert.equal(getAVLocationDisplayText({name: " 昆明 ", latitude: 25.04, longitude: 102.71}), "昆明 102.71, 25.04");
assert.equal(getAVLocationDisplayText({latitude: 0, longitude: 0}), "0, 0");
diff --git a/app/src/protyle/render/av/locationValue.ts b/app/src/protyle/render/av/locationValue.ts
index ff11c2ae53..3e8691d8a8 100644
--- a/app/src/protyle/render/av/locationValue.ts
+++ b/app/src/protyle/render/av/locationValue.ts
@@ -1,7 +1,7 @@
-const decimalCoordinate = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
-const coordinateInputNumber = "[+-]?(?:(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|Infinity|NaN)";
-const coordinateInput = new RegExp(`^${coordinateInputNumber}$`, "i");
-const canonicalInput = new RegExp(`(?:^|;\\s*)${coordinateInputNumber}\\s*,\\s*${coordinateInputNumber}\\s*\\[[^\\]]+\\]\\s*$`, "i");
+const decimalCoordinateNumber = "[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)";
+const decimalCoordinate = new RegExp(`^${decimalCoordinateNumber}$`);
+const coordinateInput = /^[+-]*(?:[\d.]+(?:e[+-]*\d*)?|Infinity|NaN|0[xob][\da-f]*)?$/i;
+const canonicalInput = new RegExp(`^(?:([\\s\\S]+);\\s*)?(${decimalCoordinateNumber})\\s*,\\s*(${decimalCoordinateNumber})(\\s*\\[WGS84\\])?$`);
const locationFields = new Set(["name", "latitude", "longitude", "originalInput"]);
const isLocationObject = (location: unknown): location is IAVCellLocationValue =>
@@ -80,17 +80,31 @@ export const createAVLocationReplacement = (location?: IAVCellLocationValue): IA
};
export const isAVLocationCoordinateInput = (text: string) => {
- const trimmed = text.trim();
- const unwrapped = trimmed.startsWith("(") && trimmed.endsWith(")") ? trimmed.slice(1, -1) : trimmed;
- const parts = unwrapped.split(",").map(part => part.trim());
- return (parts.length > 1 && parts.some(part => part !== "") &&
- parts.every(part => part === "" || coordinateInput.test(part))) || canonicalInput.test(text);
+ // 名称可以包含分号;坐标候选采用更宽的语法,避免将格式错误或其他坐标系保存成名称。
+ const isCoordinateSuffix = (value: string) => {
+ const suffix = value.slice(value.lastIndexOf(";") + 1).trim();
+ const unwrapped = suffix.replace(/^[([]/, "");
+ const coordinates = unwrapped.replace(/\[[\s\S]*$/, "").trim().replace(/[)\]]$/, "");
+ const parts = coordinates.split(",").map(part => part.trim());
+ return parts.length > 1 && parts.every(part => coordinateInput.test(part));
+ };
+ // 无效坐标系标签中的分号、逗号也不应被识别为名称或另一组坐标。
+ return isCoordinateSuffix(text) || isCoordinateSuffix(text.replace(/\[[^\]]*(?:\]|$)/g, "["));
};
-// 普通粘贴只记录地点名称;坐标必须在编辑器中按具名字段输入。
+// 文本交换固定为纬度、经度;只接受十进制 WGS84,不推断顺序或转换坐标系。
export const createAVLocationFromText = (text: string): IAVCellLocationValue => {
+ const coordinates = canonicalInput.exec(text.trim());
+ if (coordinates && (coordinates[1] === undefined || (coordinates[1].trim() && coordinates[4]))) {
+ return createAVLocationReplacement({
+ name: coordinates[1]?.trim() || "",
+ latitude: Number(coordinates[2]),
+ longitude: Number(coordinates[3]),
+ originalInput: text,
+ });
+ }
if (isAVLocationCoordinateInput(text)) {
- throw new Error("Location coordinates require explicit latitude, longitude input");
+ throw new Error("Invalid WGS84 location coordinate text");
}
return createAVLocationReplacement({name: text.trim(), originalInput: text});
};
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index e147365e34..41ea297ed0 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -32,7 +32,7 @@ const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {
return result;
};
-const fixture = (warnings: unknown[][] = [], origin = "http://127.0.0.1:6806") => {
+const fixture = (warnings: unknown[][] = [], origin = "http://127.0.0.1:6806", picking = false) => {
const calls: Array<[string, any]> = [];
const listeners = new Map<string, (...args: any[]) => void>();
const domListeners = new Map<string, () => void>();
@@ -85,15 +85,16 @@ const fixture = (warnings: unknown[][] = [], origin = "http://127.0.0.1:6806") =
const container: any = {ownerDocument: doc, isConnected: true, parentElement: null, closest: (): HTMLElement | null => null,
clientWidth: 400, clientHeight: 300, append: (guest: unknown) => attachments.push(guest),
getClientRects: () => [rect], getBoundingClientRect: () => rect, contains: (target: unknown) => target === container || attachments.includes(target)};
- const errors: string[] = [], clicks: unknown[] = [], attributionClicks: string[] = [];
+ const errors: string[] = [], clicks: unknown[] = [], attributionClicks: string[] = [], pointClicks: unknown[] = [];
let ready = 0;
const api = load(ipc, false, warnings);
const host = api.createDesktopAVMapHost(container, {provider: "openfreemap", theme: "light",
onError: (value: string) => errors.push(value),
onAttributionClick: (link: string) => attributionClicks.push(link),
+ ...(picking && {onPointClick: (...args: unknown[]) => pointClicks.push(args)}),
onMarkerClick: (...args: unknown[]) => clicks.push(args), onReady: () => ready++});
const instanceID = calls[0][1].instanceID;
- return {host, calls, listeners, domListeners, frames, timers, errors, clicks, attributionClicks, doc, container, rect, guests, attachments,
+ return {host, calls, listeners, domListeners, frames, timers, errors, clicks, attributionClicks, pointClicks, doc, container, rect, guests, attachments,
api, instanceID,
ready: () => ready,
reply: (value: object) => listeners.get("siyuan-map-reply")?.({}, {version: 1, instanceID, ...value}),
@@ -115,6 +116,36 @@ const fixture = (warnings: unknown[][] = [], origin = "http://127.0.0.1:6806") =
};
describe("desktop map transport", () => {
+ it("opts in once and passes only current visible coordinate selections to the parent", async () => {
+ const oldResize = globalThis.ResizeObserver;
+ globalThis.ResizeObserver = class { observe() {} disconnect() {} } as any;
+ try {
+ for (const picking of [false, true]) {
+ const f = fixture([], "http://127.0.0.1:6806", picking);
+ assert.equal(f.calls[0][1].picking, picking ? true : undefined);
+ f.host.setPoints([], 1);
+ await f.created();
+ const point = {type: "pointClick", longitude: 121.4, latitude: 31.2, revision: 1};
+ f.reply(point);
+ assert.deepEqual(f.pointClicks, []);
+ f.reply({type: "ready"});
+ f.reply({...point, revision: 0});
+ f.reply({...point, latitude: 90});
+ f.doc.hidden = true; f.reply(point); f.doc.hidden = false;
+ f.container.isConnected = false; f.reply(point); f.container.isConnected = true;
+ assert.deepEqual(f.pointClicks, []);
+ f.reply({...point, name: "private"});
+ assert.deepEqual(f.pointClicks, picking ? [[{longitude: 121.4, latitude: 31.2}, 1]] : []);
+ f.host.setPoints([], 2);
+ f.reply(point);
+ f.host.destroy();
+ f.reply({...point, revision: 2});
+ assert.equal(f.pointClicks.length, picking ? 1 : 0);
+ }
+ } finally {
+ globalThis.ResizeObserver = oldResize;
+ }
+ });
it("accepts only the fixed owner-origin map document and ephemeral webview partition", () => {
const api = load({});
const instanceID = "a".repeat(48);
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index 6ac4973df6..a50409fc61 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -198,6 +198,9 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
options.onReady?.();
} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {
options.onMarkerClick(reply.id, reply.revision);
+ } else if (reply?.type === "pointClick" && ready && reply.revision === revision && revision >= 0 &&
+ getAVMapVisibility(container).visible) {
+ options.onPointClick?.({longitude: reply.longitude, latitude: reply.latitude}, reply.revision);
} else if (reply?.type === "attributionClick" && ready) {
// 主进程已校验 guest 可见区域,并消费一次可信用户输入。
options.onAttributionClick?.(reply.link);
@@ -241,7 +244,8 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
timeout = scope.setTimeout(() => fail("hostReadyTimeout"), AV_MAP_OWNER_TIMEOUT);
let reply: {version?: number; instanceID?: string; error?: unknown; diagnostic?: unknown};
try {
- reply = await ipc.invoke("siyuan-map-create", {...envelope(), provider: options.provider, theme});
+ reply = await ipc.invoke("siyuan-map-create", {...envelope(), provider: options.provider, theme,
+ ...(options.onPointClick && {picking: true})});
} catch (_error) {
fail("hostCreateRejected");
return;
diff --git a/app/src/protyle/render/av/map/host.test.ts b/app/src/protyle/render/av/map/host.test.ts
index e7bb46543a..5ba0cc0ee5 100644
--- a/app/src/protyle/render/av/map/host.test.ts
+++ b/app/src/protyle/render/av/map/host.test.ts
@@ -113,11 +113,13 @@ describe("map host boundary", () => {
getBoundingClientRect: () => rect, contains: (element: unknown) => element === iframe};
let ready = 0;
const clicked: any[] = [];
+ const pointsClicked: any[] = [];
const links: string[] = [];
const host = createAVMapHost(container as unknown as HTMLElement, {
provider: "openfreemap", theme: "light",
onReady: () => ready++, onMarkerClick: (...args) => clicked.push(args), onError: () => assert.fail("unexpected error"),
onAttributionClick: link => links.push(link),
+ onPointClick: (...args) => pointsClicked.push(args),
});
cleanups.push(host.destroy);
await new Promise<void>((resolve) => setImmediate(resolve));
@@ -150,7 +152,7 @@ describe("map host boundary", () => {
assert.equal(transfers.length, 2);
const port = channels[0].port1 as Port;
assert.deepEqual(port.messages[0], {version: 1, instanceID, type: "init", provider: "openfreemap",
- theme: "light"});
+ theme: "light", picking: true});
const reply = (data: Record<string, unknown>) => port.onmessage({data: {version: 1, instanceID, ...data}});
reply({type: "attributionClick", link: "maplibre"});
assert.equal(links.length, 0);
@@ -176,7 +178,19 @@ describe("map host boundary", () => {
reply({type: "markerClick", id: "missing", revision: 1});
reply({type: "markerClick", id: "row-1", revision: 1});
assert.deepEqual(clicked, [["row-1", 1]]);
+ reply({type: "pointClick", longitude: 0, latitude: 0, revision: 0});
+ scope.navigator.userActivation.isActive = false;
+ reply({type: "pointClick", longitude: 0, latitude: 0, revision: 1});
+ scope.navigator.userActivation.isActive = true;
+ doc.hidden = true;
+ reply({type: "pointClick", longitude: 0, latitude: 0, revision: 1});
+ doc.hidden = false;
+ assert.equal(pointsClicked.length, 0);
+ reply({type: "pointClick", longitude: 0, latitude: 0, revision: 1, name: "private"});
+ assert.deepEqual(pointsClicked, [[{longitude: 0, latitude: 0}, 1]]);
host.setPoints([], 2);
+ reply({type: "pointClick", longitude: 0, latitude: 0, revision: 1});
+ assert.equal(pointsClicked.length, 1);
reply({type: "markerClick", id: "row-1", revision: 1});
reply({type: "markerClick", id: "row-1", revision: 2});
assert.equal(clicked.length, 1);
diff --git a/app/src/protyle/render/av/map/host.ts b/app/src/protyle/render/av/map/host.ts
index 75b5fefaee..a7ef39a79e 100644
--- a/app/src/protyle/render/av/map/host.ts
+++ b/app/src/protyle/render/av/map/host.ts
@@ -1,5 +1,5 @@
import {
- AV_MAP_PROTOCOL_VERSION, AVMapAttributionLink, AVMapCommand, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapVisibility,
+ AV_MAP_PROTOCOL_VERSION, AVMapAttributionLink, AVMapCommand, AVMapCoordinate, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapVisibility,
isAVMapBootstrapMessage, isAVMapLoadErrorCode, isAVMapProvider, isAVMapRevision, isAVMapTheme, parseAVMapReply,
sanitizeAVMapPoints,
} from "./protocol";
@@ -12,6 +12,7 @@ export interface AVMapHostOptions {
title?: string;
onReady?: () => void;
onMarkerClick: (id: string, revision: number) => void;
+ onPointClick?: (point: AVMapCoordinate, revision: number) => void;
onError: (code: AVMapErrorCode) => void;
onAttributionClick?: (link: AVMapAttributionLink) => void;
}
@@ -189,6 +190,10 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
tickVisibility();
} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {
options.onMarkerClick(reply.id, reply.revision);
+ } else if (reply?.type === "pointClick" && ready && reply.revision === revision && revision >= 0 &&
+ options.onPointClick && visible && getAVMapVisibility(container).visible &&
+ (scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) {
+ options.onPointClick({longitude: reply.longitude, latitude: reply.latitude}, reply.revision);
} else if (reply?.type === "attributionClick" && ready && visible &&
getAVMapVisibility(container).visible &&
(scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) {
@@ -200,7 +205,8 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
port.start();
iframe.contentWindow.postMessage({...envelope(), type: "connect", nonce}, scope.location.origin, [channel.port2]);
// 端口建立后清除全局监听;地图初始化期间不再接受窗口消息。
- send({...envelope(), type: "init", provider: options.provider, theme});
+ send({...envelope(), type: "init", provider: options.provider, theme,
+ ...(options.onPointClick && {picking: true})});
};
const host: AVMapHost = {
diff --git a/app/src/protyle/render/av/map/hostRuntime.test.ts b/app/src/protyle/render/av/map/hostRuntime.test.ts
index 23db419788..5507eb2f64 100644
--- a/app/src/protyle/render/av/map/hostRuntime.test.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.test.ts
@@ -21,6 +21,31 @@ const fixture = () => {
};
describe("isolated map runtime lifecycle", () => {
+ it("keeps picking opt-in and gates sanitized coordinate replies by the latest snapshot and lifetime", async () => {
+ for (const picking of [false, true]) {
+ const f = fixture();
+ let callbacks: AVMapAdapterCallbacks;
+ const stop = startAVMapRuntime(f.port as unknown as MessagePort, "one", "openfreemap", {} as HTMLElement,
+ async (_init, _container, value) => { callbacks = value; return f.adapter; });
+ await f.send({type: "init", provider: "openfreemap", theme: "light", picking});
+ assert.equal(typeof callbacks.onPointClick, picking ? "function" : "undefined");
+ if (picking) {
+ const point = {longitude: 0, latitude: 0};
+ callbacks.onPointClick(point, -1);
+ await f.send({type: "setPoints", points: [], revision: 2});
+ callbacks.onPointClick(point, 1);
+ callbacks.onPointClick({...point, latitude: 90}, 2);
+ callbacks.onPointClick({...point, name: "private"} as any, 2);
+ assert.deepEqual(f.replies.filter(reply => reply.type === "pointClick"), [
+ {version: 1, instanceID: "one", type: "pointClick", longitude: 0, latitude: 0, revision: 2},
+ ]);
+ stop();
+ callbacks.onPointClick(point, 2);
+ assert.equal(f.replies.length, 2);
+ }
+ stop();
+ }
+ });
it("rejects duplicate init, other providers, old revisions and nonmember marker clicks", async () => {
const {port, adapter, replies, calls, send} = fixture();
let callbacks: AVMapAdapterCallbacks;
diff --git a/app/src/protyle/render/av/map/hostRuntime.ts b/app/src/protyle/render/av/map/hostRuntime.ts
index 3b4bedcd81..65e4af258a 100644
--- a/app/src/protyle/render/av/map/hostRuntime.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.ts
@@ -1,6 +1,6 @@
import {
AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, getAVMapLoadErrorCode, isAVMapAttributionLink, isAVMapBootstrapMessage, isAVMapProvider,
- parseAVMapCommand,
+ parseAVMapCommand, parseAVMapCoordinate,
} from "./protocol";
import {AVMapAdapter, AVMapAdapterCallbacks} from "./providers";
import {loadAVMapAdapter} from "./providersLoader";
@@ -80,6 +80,12 @@ export const startAVMapRuntime = (port: MessagePort, instanceID: string, provide
send({...envelope, type: "markerClick", id, revision});
}
},
+ ...(command.picking && {onPointClick: (input, clickedRevision) => {
+ const point = parseAVMapCoordinate(input);
+ if (adapter && point && clickedRevision === revision && revision >= 0) {
+ send({...envelope, type: "pointClick", ...point, revision});
+ }
+ }}),
onError: fail,
onAttributionClick: link => {
if (adapter && isAVMapAttributionLink(link)) {
diff --git a/app/src/protyle/render/av/map/locationPicker.test.ts b/app/src/protyle/render/av/map/locationPicker.test.ts
new file mode 100644
index 0000000000..e198902939
--- /dev/null
+++ b/app/src/protyle/render/av/map/locationPicker.test.ts
@@ -0,0 +1,268 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {describe, it} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import type {AVMapHostOptions} from "./host";
+import * as protocol from "./protocol";
+import {canLoadMapHost} from "./state";
+import {DOMFixture, requireFixture} from "./testDOM";
+
+const compiled = transpileModule(readFileSync("src/protyle/render/av/map/locationPicker.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+}).outputText;
+
+const setup = (options: {point?: {longitude: number; latitude: number}; desktop?: boolean; published?: boolean;
+ online?: boolean; protocol?: string; supported?: boolean | Promise<boolean>; acceptPick?: boolean;
+ failDuringCreate?: boolean; runtime?: () => Promise<unknown>} = {}) => {
+ const document = new DOMFixture();
+ const canvas = document.createElement("div");
+ canvas.classList.add("fn__none");
+ document.body.append(canvas);
+ const status = document.createElement("div");
+ const calls: string[] = [];
+ const events = new Map<string, () => void>();
+ const observers: Array<{callback: () => void; disconnects: number}> = [];
+ const hosts: Array<{options: AVMapHostOptions; points: Array<{points: protocol.AVMapPoint[]; revision: number}>;
+ destroys: number; themes: string[]}> = [];
+ const selected: Array<{longitude: number; latitude: number}> = [];
+ const links: unknown[][] = [];
+ const navigator = {onLine: options.online !== false};
+ let ownerCurrent = true;
+ const createHost = (_canvas: unknown, configuration: AVMapHostOptions) => {
+ assert.equal(_canvas, canvas);
+ const host = {options: configuration, points: [] as typeof hosts[number]["points"], destroys: 0, themes: [] as string[]};
+ hosts.push(host);
+ if (options.failDuringCreate) configuration.onError("hostUnavailable");
+ return {
+ destroy: () => host.destroys++,
+ setPoints: (points: protocol.AVMapPoint[], revision: number) =>
+ host.points.push({points: JSON.parse(JSON.stringify(points)), revision}),
+ resize() {},
+ setTheme: (theme: string) => host.themes.push(theme),
+ };
+ };
+ const methods = {} as typeof import("./locationPicker");
+ runInNewContext(compiled, {
+ exports: methods,
+ require: requireFixture({
+ "../../../../util/fetch": {fetchSyncPost: async (url: string, payload: unknown) => {
+ assert.equal(JSON.stringify(payload), "{}");
+ calls.push(url);
+ return options.runtime ? options.runtime() : {code: 0, data: {provider: "openfreemap"}};
+ }},
+ "./host": {
+ isAVMapHostEnvironmentSupported: () => { calls.push("browser-capability"); return options.supported ?? true; },
+ createAVMapHost: createHost,
+ },
+ "./desktopTransport": {
+ isDesktopAVMapHostSupported: async () => { calls.push("desktop-capability"); return !!options.desktop; },
+ createDesktopAVMapHost: (...args: Parameters<typeof createHost>) => {
+ calls.push("desktop-host");
+ return createHost(...args);
+ },
+ },
+ "./protocol": protocol,
+ "./state": {canLoadMapHost},
+ }),
+ window: {
+ siyuan: {languages: new Proxy({}, {get: (_target, key) => String(key)}), isPublish: !!options.published},
+ location: {protocol: options.protocol || "https:"},
+ addEventListener: (type: string, callback: () => void) => events.set(type, callback),
+ removeEventListener: (type: string) => events.delete(type),
+ open: (...args: unknown[]) => links.push(args),
+ },
+ document,
+ navigator,
+ MutationObserver: class {
+ record: typeof observers[number];
+ constructor(callback: () => void) {
+ this.record = {callback, disconnects: 0};
+ observers.push(this.record);
+ }
+ observe() {}
+ disconnect() { this.record.disconnects++; }
+ },
+ });
+ const picker = methods.createAVLocationPicker({
+ canvas: canvas as unknown as HTMLElement,
+ status: status as unknown as HTMLElement,
+ point: options.point,
+ isCurrent: () => ownerCurrent,
+ onPick: point => {
+ selected.push(JSON.parse(JSON.stringify(point)));
+ return options.acceptPick !== false;
+ },
+ });
+ return {picker, hosts, calls, events, observers, selected, links, navigator, canvas, status, document,
+ detach: () => { ownerCurrent = false; },
+ settle: () => new Promise<void>(resolve => setImmediate(resolve)),
+ click: (point: {longitude: number; latitude: number}, revision?: number) => {
+ const host = hosts[0];
+ host.options.onPointClick(point, revision ?? host.points[host.points.length - 1].revision);
+ }};
+};
+
+describe("embedded database location picker", () => {
+ it("loads an empty picker without requiring an existing location, on browser and desktop hosts", async () => {
+ for (const desktop of [false, true]) {
+ const scenario = setup({desktop});
+ await scenario.settle();
+ assert.equal(scenario.hosts.length, 1);
+ assert.deepEqual(scenario.hosts[0].points, [{points: [], revision: 1}]);
+ assert.equal(scenario.calls.includes("desktop-host"), desktop);
+ assert.equal(scenario.calls.includes("browser-capability"), !desktop);
+ assert.equal(scenario.status.textContent, "mapLoading");
+ assert.equal(scenario.canvas.classList.contains("fn__none"), false);
+ scenario.hosts[0].options.onReady();
+ assert.equal(scenario.status.textContent, "");
+ }
+ });
+
+ it("sends only the coordinate draft and updates its marker with strictly increasing revisions", async () => {
+ const scenario = setup({point: {longitude: 30, latitude: 20, name: "Private name",
+ originalInput: "Private source"} as {longitude: number; latitude: number}});
+ await scenario.settle();
+ const host = scenario.hosts[0];
+ assert.deepEqual(host.points[0], {points: [{id: "location-draft", longitude: 30, latitude: 20}], revision: 1});
+ scenario.click({longitude: 40, latitude: 10});
+ scenario.click({longitude: 0, latitude: 0});
+ assert.deepEqual(scenario.selected, [{longitude: 40, latitude: 10}, {longitude: 0, latitude: 0}]);
+ assert.deepEqual(host.points[2], {points: [{id: "location-draft", longitude: 0, latitude: 0}], revision: 3});
+ assert.equal(scenario.hosts.length, 1);
+ scenario.picker.setPoint({longitude: 50, latitude: 25});
+ assert.deepEqual(host.points[3], {points: [{id: "location-draft", longitude: 50, latitude: 25}], revision: 4});
+ assert.equal(JSON.stringify(host.points).includes("Private"), false);
+ });
+
+ it("ignores stale or invalid point clicks and leaves a rejected draft unchanged", async () => {
+ const scenario = setup();
+ await scenario.settle();
+ for (const point of [{longitude: 181, latitude: 0}, {longitude: 0, latitude: 86},
+ {longitude: NaN, latitude: 0}, {longitude: 0, latitude: Infinity}]) scenario.click(point);
+ scenario.click({longitude: 40, latitude: 10}, 0);
+ scenario.click({longitude: 40, latitude: 10}, 2);
+ assert.equal(scenario.selected.length, 0);
+ assert.equal(scenario.hosts[0].points.length, 1);
+ const rejected = setup({acceptPick: false});
+ await rejected.settle();
+ rejected.click({longitude: 40, latitude: 10});
+ assert.equal(rejected.hosts[0].points.length, 1);
+ });
+
+ it("removes the selected marker for invalid manual coordinates without changing the form draft", async () => {
+ const scenario = setup({point: {longitude: 30, latitude: 20}});
+ await scenario.settle();
+ scenario.picker.setPoint({longitude: 30, latitude: 90});
+ scenario.picker.setPoint();
+ assert.deepEqual(scenario.hosts[0].points.slice(1), [{points: [], revision: 2}, {points: [], revision: 3}]);
+ assert.equal(scenario.selected.length, 0);
+ });
+
+ it("shows a local fallback and makes no runtime request for unsupported, published or offline clients", async () => {
+ for (const [options, message] of [
+ [{protocol: "file:"}, "mapUnsupportedClient"], [{published: true}, "mapPublicFallback"],
+ [{online: false}, "mapOffline"], [{supported: false}, "mapUnsupportedClient"],
+ ] as const) {
+ const scenario = setup(options);
+ await scenario.settle();
+ assert.equal(scenario.calls.includes("/api/map/getRuntime"), false);
+ assert.equal(scenario.hosts.length, 0);
+ assert.equal(scenario.status.textContent, message);
+ assert.equal(scenario.events.size, 0);
+ assert.equal(scenario.canvas.classList.contains("fn__none"), true);
+ }
+ });
+
+ it("retains the newest manual draft while capability and runtime checks are pending", async () => {
+ let resolveCapability: (value: boolean) => void;
+ const scenario = setup({supported: new Promise(resolve => resolveCapability = resolve)});
+ scenario.picker.setPoint({longitude: 40, latitude: 10});
+ resolveCapability(true);
+ await scenario.settle();
+ assert.deepEqual(scenario.hosts[0].points[0].points, [{id: "location-draft", longitude: 40, latitude: 10}]);
+ });
+
+ it("does not create a late host after disposal, owner invalidation or going offline during runtime loading", async () => {
+ for (const action of ["destroy", "detach", "offline"]) {
+ let complete: (value: unknown) => void;
+ const scenario = setup({runtime: () => new Promise(resolve => complete = resolve)});
+ await scenario.settle();
+ if (action === "destroy") scenario.picker.destroy();
+ else if (action === "detach") scenario.detach();
+ else {
+ scenario.navigator.onLine = false;
+ scenario.events.get("offline")();
+ }
+ complete({code: 0, data: {provider: "openfreemap"}});
+ await scenario.settle();
+ assert.equal(scenario.hosts.length, 0);
+ assert.equal(scenario.events.size, 0);
+ }
+ });
+
+ it("does not fetch runtime after a capability result returns to a disposed picker", async () => {
+ let complete: (value: boolean) => void;
+ const scenario = setup({supported: new Promise(resolve => complete = resolve)});
+ await scenario.settle();
+ scenario.picker.destroy();
+ complete(true);
+ await scenario.settle();
+ assert.equal(scenario.calls.includes("/api/map/getRuntime"), false);
+ });
+
+ it("handles authentication, provider, request and synchronous host failures without exposing errors", async () => {
+ for (const [options, message] of [
+ [{runtime: async () => ({code: -1, msg: "mapAuthenticationBypass"})}, "mapAuthenticationBypass"],
+ [{runtime: async () => ({code: 0, data: {provider: "untrusted"}})}, "mapLoadError"],
+ [{runtime: async () => { throw new Error("Private runtime detail"); }}, "mapLoadError"],
+ [{failDuringCreate: true}, "mapLoadError"],
+ ] as const) {
+ const scenario = setup(options);
+ await scenario.settle();
+ assert.equal(scenario.status.textContent, message);
+ assert.equal(scenario.canvas.classList.contains("fn__none"), true);
+ assert.equal(scenario.events.size, 0);
+ assert.equal(scenario.observers.length, 0);
+ if (scenario.hosts.length) assert.equal(scenario.hosts[0].destroys, 1);
+ }
+ });
+
+ it("disposes the host and all listeners once and ignores late events after close, error or owner loss", async () => {
+ for (const action of ["destroy", "detach", "offline", "error"]) {
+ const scenario = setup();
+ await scenario.settle();
+ const host = scenario.hosts[0];
+ if (action === "destroy") scenario.picker.destroy();
+ else if (action === "detach") {
+ scenario.detach();
+ scenario.click({longitude: 40, latitude: 10});
+ } else if (action === "offline") {
+ scenario.navigator.onLine = false;
+ scenario.events.get("offline")();
+ } else host.options.onError("hostUnavailable");
+ scenario.click({longitude: 40, latitude: 10});
+ host.options.onReady();
+ scenario.observers[0].callback();
+ scenario.picker.destroy();
+ assert.equal(host.destroys, 1);
+ assert.equal(scenario.selected.length, 0);
+ assert.equal(scenario.observers[0].disconnects, 1);
+ assert.equal(scenario.events.size, 0);
+ }
+ });
+
+ it("updates theme and opens only fixed attribution destinations while active", async () => {
+ const scenario = setup();
+ await scenario.settle();
+ scenario.document.documentElement.setAttribute("data-theme-mode", "dark");
+ scenario.observers[0].callback();
+ assert.deepEqual(scenario.hosts[0].themes, ["dark"]);
+ const link = protocol.AV_MAP_ATTRIBUTION_LINKS.openfreemap[0];
+ scenario.hosts[0].options.onAttributionClick(link.id);
+ assert.deepEqual(scenario.links, [[link.href, "_blank", "noopener,noreferrer"]]);
+ scenario.picker.destroy();
+ scenario.hosts[0].options.onAttributionClick(link.id);
+ assert.equal(scenario.links.length, 1);
+ });
+});
diff --git a/app/src/protyle/render/av/map/locationPicker.ts b/app/src/protyle/render/av/map/locationPicker.ts
new file mode 100644
index 0000000000..886527558e
--- /dev/null
+++ b/app/src/protyle/render/av/map/locationPicker.ts
@@ -0,0 +1,134 @@
+import {fetchSyncPost} from "../../../../util/fetch";
+import {createAVMapHost, isAVMapHostEnvironmentSupported} from "./host";
+import type {AVMapHost} from "./host";
+import {createDesktopAVMapHost, isDesktopAVMapHostSupported} from "./desktopTransport";
+import {AV_MAP_ATTRIBUTION_LINKS, sanitizeAVMapPoints} from "./protocol";
+import type {AVMapCoordinate} from "./protocol";
+import {canLoadMapHost} from "./state";
+
+interface AVLocationPickerOptions {
+ canvas: HTMLElement;
+ status: HTMLElement;
+ point?: AVMapCoordinate;
+ isCurrent: () => boolean;
+ onPick: (point: AVMapCoordinate) => boolean;
+}
+
+// 地图仅接收固定草稿标识和坐标,不传递地点名称、来源或数据库内容。
+const getPoints = (point?: AVMapCoordinate) => point ? sanitizeAVMapPoints([
+ {id: "location-draft", longitude: point.longitude, latitude: point.latitude},
+]) : [];
+
+export const createAVLocationPicker = (options: AVLocationPickerOptions) => {
+ const languages = window.siyuan.languages;
+ const getTheme = () => document.documentElement.getAttribute("data-theme-mode") === "dark" ? "dark" : "light";
+ let host: AVMapHost;
+ let themeObserver: MutationObserver;
+ let disposed = false;
+ let failed = false;
+ let revision = 0;
+ let points = getPoints(options.point);
+ const offline = () => fallback(languages.mapOffline);
+ const releaseHost = () => {
+ revision++;
+ const previous = host;
+ host = undefined;
+ themeObserver?.disconnect();
+ themeObserver = undefined;
+ window.removeEventListener("offline", offline);
+ previous?.destroy();
+ };
+ const destroy = () => {
+ if (disposed) return;
+ disposed = true;
+ releaseHost();
+ };
+ const current = () => {
+ if (disposed || failed) return false;
+ if (options.isCurrent()) return true;
+ destroy();
+ return false;
+ };
+ const fallback = (message: string) => {
+ if (!current()) return;
+ failed = true;
+ releaseHost();
+ options.status.textContent = message;
+ options.canvas.classList.add("fn__none");
+ };
+ const setPoint = (point?: AVMapCoordinate) => {
+ if (!current()) return;
+ points = getPoints(point);
+ host?.setPoints(points, ++revision);
+ };
+ const start = async () => {
+ if (!current()) return;
+ if (window.siyuan.isPublish) {
+ fallback(languages.mapPublicFallback);
+ return;
+ }
+ if (!canLoadMapHost(window.location.protocol)) {
+ fallback(languages.mapUnsupportedClient);
+ return;
+ }
+ if (!navigator.onLine) {
+ fallback(languages.mapOffline);
+ return;
+ }
+ options.status.textContent = languages.mapLoading;
+ window.addEventListener("offline", offline);
+ const desktop = await isDesktopAVMapHostSupported();
+ if (!current()) return;
+ const supported = desktop || await isAVMapHostEnvironmentSupported();
+ if (!current()) return;
+ if (!supported) {
+ fallback(languages.mapUnsupportedClient);
+ return;
+ }
+ if (!navigator.onLine) {
+ fallback(languages.mapOffline);
+ return;
+ }
+ const response = await fetchSyncPost("/api/map/getRuntime", {});
+ if (!current()) return;
+ if (response.code !== 0 || response.data?.provider !== "openfreemap") {
+ fallback(response.msg === "mapAuthenticationBypass" ? languages.mapAuthenticationBypass : languages.mapLoadError);
+ return;
+ }
+ options.canvas.classList.remove("fn__none");
+ const nextHost = (desktop ? createDesktopAVMapHost : createAVMapHost)(options.canvas, {
+ provider: "openfreemap",
+ theme: getTheme(),
+ title: languages.locationPickOnMap,
+ onReady: () => {
+ if (current()) options.status.textContent = "";
+ },
+ onMarkerClick: () => {},
+ onPointClick: (point, pointRevision) => {
+ if (!current() || pointRevision !== revision) return;
+ const selected = getPoints(point)[0];
+ if (!selected) return;
+ const coordinates = {longitude: selected.longitude, latitude: selected.latitude};
+ if (options.onPick(coordinates)) setPoint(coordinates);
+ },
+ onAttributionClick: id => {
+ if (!current()) return;
+ const link = AV_MAP_ATTRIBUTION_LINKS.openfreemap.find(item => item.id === id);
+ if (link) window.open(link.href, "_blank", "noopener,noreferrer");
+ },
+ onError: () => fallback(navigator.onLine ? languages.mapLoadError : languages.mapOffline),
+ });
+ if (!current()) {
+ nextHost.destroy();
+ return;
+ }
+ host = nextHost;
+ host.setPoints(points, ++revision);
+ themeObserver = new MutationObserver(() => {
+ if (current()) host?.setTheme(getTheme());
+ });
+ themeObserver.observe(document.documentElement, {attributes: true, attributeFilter: ["data-theme-mode"]});
+ };
+ void start().catch(() => fallback(navigator.onLine ? languages.mapLoadError : languages.mapOffline));
+ return {setPoint, destroy};
+};
diff --git a/app/src/protyle/render/av/map/pointPicking.test.ts b/app/src/protyle/render/av/map/pointPicking.test.ts
new file mode 100644
index 0000000000..c36b57eb3e
--- /dev/null
+++ b/app/src/protyle/render/av/map/pointPicking.test.ts
@@ -0,0 +1,400 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {describe, it} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import * as escape from "../../../../util/escape";
+import * as locationValue from "../locationValue";
+import * as protocol from "./protocol";
+import {getMapSettings} from "./state";
+import {DOMElement, DOMFixture, requireFixture} from "./testDOM";
+
+const compile = (file: string) => transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+}).outputText;
+
+const setup = () => {
+ const document = new DOMFixture();
+ const editor = document.createElement("div");
+ editor.className = "protyle-wysiwyg";
+ document.body.append(editor);
+ const otherEditor = document.createElement("div");
+ otherEditor.className = "protyle-wysiwyg";
+ document.body.append(otherEditor);
+ const block = document.createElement("div");
+ block.dataset.nodeId = "carrier";
+ block.dataset.avId = "database";
+ block.setAttribute("custom-sy-av-view", "map-view");
+ block.setAttribute("updated", "20261010120000");
+ block.setAttribute("data-render", "true");
+ editor.append(block);
+ const canvas = document.createElement("div");
+ block.append(canvas);
+ const protyle = {options: {}, notebookId: "notebook"} as IProtyle;
+ const data = {id: "database", viewID: "map-view", viewType: "map", view: {
+ columns: [{id: "location", name: "Location", type: "location"}], map: {locationKeyID: "location"}, rows: [],
+ }} as IAV;
+ const view = data.view as IAVTable;
+ const sharedMenu = {data: undefined as Element, element: document.createElement("div"), remove: () => {}};
+ sharedMenu.element.classList.add("fn__none");
+ const context = {siyuan: {
+ menus: {menu: sharedMenu},
+ isPublish: false,
+ config: {readonly: false},
+ notebooks: [{id: "notebook", encrypted: true, closed: false}],
+ languages: new Proxy<Record<string, string>>({}, {get: (_target, key: string) => key}),
+ }};
+ const copied: string[] = [];
+ const opened: Array<Parameters<typeof import("../openDatabaseRow").openDatabaseRowByData>[1]> = [];
+ const transactions: Array<{perform: IOperation[]; undo: IOperation[]; callback: () => void; resolve: () => void}> = [];
+ const menus: MenuStub[] = [];
+ let current = true;
+ let pending = Promise.resolve();
+ let nextID = 0;
+ let renders = 0;
+ let throwTransaction = false;
+ class MenuStub {
+ items: Array<{option: IMenu; element: DOMElement}> = [];
+ closes = 0;
+ position: IPosition;
+ constructor(_id?: string, private onClose?: () => void) { sharedMenu.remove(); menus.push(this); }
+ addItem(option: IMenu) {
+ const element = document.createElement("button");
+ element.innerHTML = option.label || "";
+ document.body.append(element);
+ this.items.push({option, element});
+ return element;
+ }
+ open(position: IPosition) { this.position = position; sharedMenu.element.classList.remove("fn__none"); }
+ close() {
+ if (this.closes) return;
+ this.closes++;
+ sharedMenu.data = undefined;
+ sharedMenu.element.classList.add("fn__none");
+ this.items.forEach(item => item.element.remove());
+ this.onClose?.();
+ }
+ item(label: string) { return this.items.find(item => item.option.label === label); }
+ click(label: string) {
+ const item = this.item(label);
+ assert.ok(item, `Missing point menu item: ${label}`);
+ return item.option.click?.(item.element as unknown as HTMLElement, {} as MouseEvent);
+ }
+ }
+ sharedMenu.remove = () => {
+ menus[menus.length - 1]?.close();
+ sharedMenu.data = undefined;
+ sharedMenu.element.classList.add("fn__none");
+ };
+ const menuToggle = {} as typeof import("../../../../menus/menuToggle");
+ runInNewContext(compile("src/menus/menuToggle.ts"), {exports: menuToggle, window: context});
+ const modules: Record<string, unknown> = {
+ dayjs: () => ({format: () => "20261011090000"}),
+ "../../../../plugin/Menu": {Menu: MenuStub},
+ "../../../../menus/menuToggle": menuToggle,
+ "../../../../menus/Menu": {MenuItem: class {}},
+ "../../../../util/escape": escape,
+ "../../../../util/functions": {isMobile: () => false},
+ "../../../util/compatibility": {writeText: (text: string) => copied.push(text)},
+ "../../../util/transactionQueue": {waitForPendingTransactions: () => pending},
+ "../../../wysiwyg/transaction": {transaction: (_protyle: IProtyle, perform: IOperation[], undo: IOperation[],
+ options: {callback: () => void}) => {
+ if (throwTransaction) throw new Error("Transaction rejected");
+ pending = new Promise(resolve => transactions.push({perform, undo, callback: options.callback, resolve}));
+ }},
+ "../filteredTip": {
+ getAVFilteredTipContext: (scope: string, owner: IProtyle) => {
+ assert.equal(scope, "target");
+ assert.equal(owner, protyle);
+ return {filteredTipScope: "target", filteredTipToken: "filtered-token"};
+ },
+ getAVViewID: (element: DOMElement) => element.getAttribute("custom-sy-av-view"),
+ },
+ "../locationValue": locationValue,
+ "../openDatabaseRow": {openDatabaseRowByData: (_protyle: IProtyle, value: typeof opened[number]) => opened.push(value)},
+ "../render": {avRender: () => { renders++; }},
+ "./protocol": protocol,
+ "./state": {getMapSettings},
+ };
+ const settings = {} as typeof import("./settings");
+ runInNewContext(compile("src/protyle/render/av/map/settings.ts"), {
+ exports: settings, require: requireFixture(modules), window: context,
+ });
+ modules["./settings"] = settings;
+ const methods = {} as typeof import("./pointPicking");
+ runInNewContext(compile("src/protyle/render/av/map/pointPicking.ts"), {
+ exports: methods, require: requireFixture(modules), window: context, Lute: {NewNodeID: () => `generated-${++nextID}`},
+ });
+ const binding = methods.bindMapPointPicking({canvas: canvas as unknown as HTMLElement,
+ blockElement: block as unknown as HTMLElement, protyle, data, current: () => current});
+ return {binding, methods, block, canvas, data, view, context, protyle, copied, opened, transactions, menus,
+ stale: () => { current = false; },
+ reparent: () => otherEditor.append(block),
+ setTransactionFailure: (fail: boolean) => { throwTransaction = fail; },
+ renders: () => renders,
+ menu: () => menus[menus.length - 1],
+ settle: () => new Promise<void>(resolve => setImmediate(resolve)),
+ complete: async (success = true) => {
+ const batch = transactions[transactions.length - 1];
+ if (success) batch.callback();
+ batch.resolve();
+ await new Promise<void>(resolve => setImmediate(resolve));
+ },
+ create: (location: IAVCellLocationValue = {longitude: 120.5, latitude: 30.25}) =>
+ methods.createMapRecordAtPoint({protyle, blockElement: block as unknown as HTMLElement,
+ avID: "database", viewID: "map-view", locationKeyID: "location", location, current: () => current}),
+ };
+};
+
+describe("map point actions", () => {
+ it("copies canonical WGS84 text and only uses escaped names already held in the parent view", () => {
+ const scenario = setup();
+ const location = {name: ' <img src=x onerror="alert(1)"> & Office ', longitude: 120.5, latitude: 30.25,
+ originalInput: "Private source"};
+ scenario.view.rows.push({id: "row", cells: [{value: {type: "location", keyID: "location", location}}]} as IAVRow);
+ scenario.binding.show({longitude: 120.5, latitude: 30.25, name: "Untrusted supplier name"} as protocol.AVMapCoordinate);
+ const menu = scenario.menu();
+ const canonical = locationValue.getAVLocationText(location);
+ assert.equal(menu.items[1].option.label, escape.escapeHtml(canonical));
+ assert.equal(menu.items[1].element.children.length, 0);
+ assert.equal(menu.position.target, scenario.canvas);
+ menu.click("copy");
+ assert.deepEqual(scenario.copied, [canonical]);
+ assert.match(canonical, /30\.25, 120\.5 \[WGS84\]$/);
+ assert.doesNotMatch(canonical, /Private source|Untrusted supplier/);
+ assert.equal(scenario.transactions.length, 0);
+ });
+
+ it("offers copying without creation in readonly, published and history contexts", () => {
+ for (const mode of ["readonly", "global-readonly", "published", "created", "snapshot"]) {
+ const scenario = setup();
+ if (mode === "readonly") scenario.protyle.disabled = true;
+ else if (mode === "global-readonly") scenario.context.siyuan.config.readonly = true;
+ else if (mode === "published") scenario.context.siyuan.isPublish = true;
+ else scenario.protyle.options.history = {[mode]: "history"};
+ scenario.binding.show({longitude: 0, latitude: 0});
+ assert.equal(scenario.menu().item("mapCreateAtPoint"), undefined);
+ scenario.menu().click("copy");
+ assert.deepEqual(scenario.copied, ["0, 0 [WGS84]"]);
+ assert.equal(scenario.transactions.length, 0);
+ }
+ });
+
+ it("never exposes actions for invalid points or a stale, detached, reidentified, switched or locked owner", () => {
+ for (const point of [{longitude: 181, latitude: 0}, {longitude: NaN, latitude: 0},
+ {longitude: 0, latitude: 86}, {longitude: 0, latitude: Infinity},
+ {longitude: 0, latitude: 0, coordinateSystem: "GCJ02"}]) {
+ const scenario = setup();
+ scenario.binding.show(point);
+ assert.equal(scenario.menus.length, 0);
+ }
+ for (const mode of ["stale", "detached", "carrier", "database", "view", "field", "editor", "notebook", "locked"]) {
+ const scenario = setup();
+ if (mode === "stale") scenario.stale();
+ else if (mode === "detached") scenario.block.remove();
+ else if (mode === "carrier") scenario.block.dataset.nodeId = "other-carrier";
+ else if (mode === "database") scenario.block.dataset.avId = "other-database";
+ else if (mode === "view") scenario.block.setAttribute("custom-sy-av-view", "other-view");
+ else if (mode === "field") scenario.view.map.locationKeyID = "other-field";
+ else if (mode === "editor") scenario.reparent();
+ else if (mode === "notebook") scenario.protyle.notebookId = "other-notebook";
+ else scenario.context.siyuan.notebooks[0].closed = true;
+ scenario.binding.show({longitude: 0, latitude: 0});
+ assert.equal(scenario.menus.length, 0, mode);
+ }
+ });
+
+ it("revalidates owner and editability before actions from an already open menu", () => {
+ for (const mode of ["stale", "view", "editor", "notebook", "locked", "readonly", "global-readonly", "published", "history"]) {
+ const scenario = setup();
+ scenario.binding.show({longitude: 0, latitude: 0});
+ if (mode === "stale") scenario.stale();
+ else if (mode === "view") scenario.block.setAttribute("custom-sy-av-view", "other-view");
+ else if (mode === "editor") scenario.reparent();
+ else if (mode === "notebook") scenario.protyle.notebookId = "other-notebook";
+ else if (mode === "locked") scenario.context.siyuan.notebooks[0].closed = true;
+ else if (mode === "readonly") scenario.protyle.disabled = true;
+ else if (mode === "global-readonly") scenario.context.siyuan.config.readonly = true;
+ else if (mode === "published") scenario.context.siyuan.isPublish = true;
+ else scenario.protyle.options.history = {created: "history"};
+ scenario.menu().click("mapCreateAtPoint");
+ assert.equal(scenario.transactions.length, 0, mode);
+ if (["stale", "view", "editor", "notebook", "locked"].includes(mode)) {
+ scenario.menu().click("copy");
+ assert.equal(scenario.copied.length, 0, mode);
+ }
+ }
+ });
+
+ it("creates the detached row and full coordinate replacement in one transaction and one remove undo", async () => {
+ const scenario = setup();
+ scenario.binding.show({longitude: 120.5, latitude: 30.25});
+ scenario.menu().click("mapCreateAtPoint");
+ assert.equal(scenario.transactions.length, 1);
+ const batch = scenario.transactions[0];
+ assert.deepEqual(Array.from(batch.perform, operation => operation.action),
+ ["insertAttrViewBlock", "updateAttrViewCell", "doUpdateUpdated"]);
+ const [insert, update] = batch.perform;
+ assert.equal(insert.avID, "database");
+ assert.equal(insert.blockID, "carrier");
+ assert.equal(insert.viewID, "map-view");
+ assert.equal(insert.srcs.length, 1);
+ assert.equal(insert.srcs[0].isDetached, true);
+ assert.equal(insert.srcs[0].content, "");
+ assert.equal(update.rowID, insert.srcs[0].itemID);
+ assert.equal(update.keyID, "location");
+ assert.deepEqual(JSON.parse(JSON.stringify(update.data)), {id: update.id, keyID: "location",
+ blockID: insert.srcs[0].itemID, type: "location", location: {
+ longitude: 120.5, latitude: 30.25, name: "", originalInput: "",
+ }});
+ assert.deepEqual(JSON.parse(JSON.stringify(batch.undo)), [
+ {action: "removeAttrViewBlock", avID: "database", blockID: "carrier", srcIDs: [insert.srcs[0].itemID]},
+ {action: "doUpdateUpdated", id: "carrier", data: "20261010120000"},
+ ]);
+ assert.equal(scenario.opened.length, 0);
+ await scenario.complete();
+ assert.equal(scenario.renders(), 1);
+ assert.equal(scenario.block.getAttribute("updated"), "20261011090000");
+ assert.equal(scenario.block.hasAttribute("data-render"), false);
+ assert.equal(scenario.opened.length, 1);
+ assert.equal(scenario.opened[0].itemID, insert.srcs[0].itemID);
+ assert.equal(scenario.opened[0].focusPrimary, true);
+ assert.equal(scenario.opened[0].isDetached, true);
+ });
+
+ it("prevents duplicate creation until the transaction settles and permits retry after failure", async () => {
+ const scenario = setup();
+ scenario.binding.show({longitude: 0, latitude: 0});
+ const menu = scenario.menu();
+ menu.click("mapCreateAtPoint");
+ menu.click("mapCreateAtPoint");
+ scenario.binding.show({longitude: 1, latitude: 1});
+ assert.equal(scenario.menu().item("mapCreateAtPoint"), undefined);
+ assert.equal(scenario.transactions.length, 1);
+ await scenario.complete(false);
+ assert.equal(scenario.opened.length, 0);
+ assert.equal(scenario.renders(), 0);
+ scenario.binding.show({longitude: 1, latitude: 1});
+ scenario.menu().click("mapCreateAtPoint");
+ assert.equal(scenario.transactions.length, 2);
+ await scenario.complete();
+ assert.equal(scenario.opened.length, 1);
+ });
+
+ it("catches immediate transaction errors and restores the creation action", async () => {
+ const scenario = setup();
+ scenario.setTransactionFailure(true);
+ scenario.binding.show({longitude: 0, latitude: 0});
+ scenario.menu().click("mapCreateAtPoint");
+ await scenario.settle();
+ assert.equal(scenario.transactions.length, 0);
+ assert.equal(scenario.opened.length, 0);
+ scenario.setTransactionFailure(false);
+ scenario.binding.show({longitude: 1, latitude: 1});
+ scenario.menu().click("mapCreateAtPoint");
+ assert.equal(scenario.transactions.length, 1);
+ await scenario.complete();
+ });
+
+ it("does not reopen a row after success when its carrier, view, editability or notebook access changed", async () => {
+ for (const mode of ["detached", "carrier", "database", "view", "editor", "notebook", "readonly", "global-readonly", "history", "locked"]) {
+ const scenario = setup();
+ const result = scenario.create();
+ assert.equal(scenario.transactions.length, 1);
+ if (mode === "detached") scenario.block.remove();
+ else if (mode === "carrier") scenario.block.dataset.nodeId = "other-carrier";
+ else if (mode === "database") scenario.block.dataset.avId = "other-database";
+ else if (mode === "view") scenario.block.setAttribute("custom-sy-av-view", "other-view");
+ else if (mode === "editor") scenario.reparent();
+ else if (mode === "notebook") scenario.protyle.notebookId = "other-notebook";
+ else if (mode === "readonly") scenario.protyle.disabled = true;
+ else if (mode === "global-readonly") scenario.context.siyuan.config.readonly = true;
+ else if (mode === "history") scenario.protyle.options.history = {snapshot: "history"};
+ else scenario.context.siyuan.notebooks[0].closed = true;
+ await scenario.complete();
+ assert.equal(await result, true);
+ assert.equal(scenario.opened.length, 0, mode);
+ assert.equal(scenario.renders(), 0, mode);
+ }
+ });
+
+ it("still opens a successful new row when only its old map lifecycle was replaced", async () => {
+ const scenario = setup();
+ const result = scenario.create();
+ scenario.stale();
+ await scenario.complete();
+ assert.equal(await result, true);
+ assert.equal(scenario.opened.length, 1);
+ });
+
+ it("rejects invalid locations and unavailable owners when record creation is invoked directly", async () => {
+ for (const location of [{longitude: 181, latitude: 0}, {longitude: 0}, {longitude: 0, latitude: 90},
+ {longitude: 0, latitude: 0, name: 42}]) {
+ const scenario = setup();
+ assert.equal(await scenario.create(location as IAVCellLocationValue), false);
+ assert.equal(scenario.transactions.length, 0);
+ }
+ for (const mode of ["stale", "detached", "database", "view", "locked", "readonly", "published", "history"]) {
+ const scenario = setup();
+ if (mode === "stale") scenario.stale();
+ else if (mode === "detached") scenario.block.remove();
+ else if (mode === "database") scenario.block.dataset.avId = "other-database";
+ else if (mode === "view") scenario.block.setAttribute("custom-sy-av-view", "other-view");
+ else if (mode === "locked") scenario.context.siyuan.notebooks[0].closed = true;
+ else if (mode === "readonly") scenario.protyle.disabled = true;
+ else if (mode === "published") scenario.context.siyuan.isPublish = true;
+ else scenario.protyle.options.history = {created: "history"};
+ const result = scenario.create();
+ assert.equal(scenario.transactions.length, 0, mode);
+ assert.equal(await result, false, mode);
+ }
+ const failed = setup();
+ const result = failed.create();
+ await failed.complete(false);
+ assert.equal(await result, false);
+ assert.equal(failed.opened.length, 0);
+ });
+
+ it("replaces the existing menu and closes it once on disposal, disabling old callbacks", () => {
+ const scenario = setup();
+ scenario.binding.show({longitude: 0, latitude: 0});
+ const first = scenario.menu();
+ scenario.binding.show({longitude: 1, latitude: 1});
+ const second = scenario.menu();
+ assert.equal(first.closes, 1);
+ assert.equal(second.closes, 0);
+ assert.equal(scenario.context.siyuan.menus.menu.data, scenario.canvas);
+ assert.equal(scenario.canvas.hasAttribute("data-menu"), false);
+ first.click("copy");
+ first.click("mapCreateAtPoint");
+ assert.equal(scenario.copied.length, 0);
+ assert.equal(scenario.transactions.length, 0);
+ scenario.binding.destroy();
+ scenario.binding.destroy();
+ assert.equal(second.closes, 1);
+ assert.equal(scenario.context.siyuan.menus.menu.data, undefined);
+ second.click("copy");
+ second.click("mapCreateAtPoint");
+ scenario.binding.show({longitude: 2, latitude: 2});
+ assert.equal(scenario.menus.length, 2);
+ assert.equal(scenario.copied.length, 0);
+ assert.equal(scenario.transactions.length, 0);
+ });
+
+ it("dismissal clears shared ownership and cannot revive actions from the retired menu", () => {
+ const scenario = setup();
+ scenario.binding.show({longitude: 0, latitude: 0});
+ const menu = scenario.menu();
+ scenario.context.siyuan.menus.menu.remove();
+ assert.equal(scenario.context.siyuan.menus.menu.data, undefined);
+ menu.click("copy");
+ menu.click("mapCreateAtPoint");
+ assert.equal(scenario.copied.length, 0);
+ assert.equal(scenario.transactions.length, 0);
+ scenario.binding.show({longitude: 1, latitude: 1});
+ assert.equal(scenario.menu().closes, 0);
+ scenario.menu().click("copy");
+ assert.deepEqual(scenario.copied, ["1, 1 [WGS84]"]);
+ scenario.binding.destroy();
+ });
+});
diff --git a/app/src/protyle/render/av/map/pointPicking.ts b/app/src/protyle/render/av/map/pointPicking.ts
new file mode 100644
index 0000000000..04f1421e75
--- /dev/null
+++ b/app/src/protyle/render/av/map/pointPicking.ts
@@ -0,0 +1,130 @@
+import * as dayjs from "dayjs";
+import {Menu} from "../../../../plugin/Menu";
+import {toggleMenu} from "../../../../menus/menuToggle";
+import {escapeHtml} from "../../../../util/escape";
+import {writeText} from "../../../util/compatibility";
+import {waitForPendingTransactions} from "../../../util/transactionQueue";
+import {transaction} from "../../../wysiwyg/transaction";
+import {getAVFilteredTipContext, getAVViewID} from "../filteredTip";
+import {createAVLocationReplacement, getAVLocationText, validateAVLocation} from "../locationValue";
+import {openDatabaseRowByData} from "../openDatabaseRow";
+import {avRender} from "../render";
+import {AVMapCoordinate, parseAVMapCoordinate} from "./protocol";
+import {canEditMapSettings} from "./settings";
+import {getMapSettings} from "./state";
+
+const isNotebookLocked = (protyle: IProtyle) => window.siyuan.notebooks?.some(notebook =>
+ notebook.id === protyle.notebookId && notebook.encrypted && notebook.closed);
+const editable = (protyle: IProtyle) => canEditMapSettings(protyle) && !window.siyuan.config?.readonly;
+
+// 使用既有插入与单元格事务一次写入坐标,撤销时完整移除新建游离条目。
+export const createMapRecordAtPoint = async (options: {
+ protyle: IProtyle;
+ blockElement: HTMLElement;
+ avID: string;
+ viewID: string;
+ locationKeyID: string;
+ location: IAVCellLocationValue;
+ current: () => boolean;
+}) => {
+ const {protyle, blockElement, avID, viewID, locationKeyID, current} = options;
+ if (!current() || !blockElement.isConnected || blockElement.dataset.avId !== avID ||
+ getAVViewID(blockElement) !== viewID || !editable(protyle) || isNotebookLocked(protyle) ||
+ !parseAVMapCoordinate(options.location) ||
+ !validateAVLocation(options.location)) return false;
+ const location = createAVLocationReplacement(options.location);
+ const itemID = Lute.NewNodeID();
+ const valueID = Lute.NewNodeID();
+ const blockID = blockElement.dataset.nodeId;
+ const editorElement = blockElement.closest(".protyle-wysiwyg");
+ const notebookID = protyle.notebookId;
+ const updated = dayjs().format("YYYYMMDDHHmmss");
+ let committed = false;
+ transaction(protyle, [{
+ action: "insertAttrViewBlock", avID, blockID, viewID, previousID: "",
+ srcs: [{itemID, id: Lute.NewNodeID(), isDetached: true, content: ""}],
+ context: getAVFilteredTipContext("target", protyle),
+ }, {
+ action: "updateAttrViewCell", avID, blockID, rowID: itemID, keyID: locationKeyID, id: valueID,
+ data: {id: valueID, keyID: locationKeyID, blockID: itemID, type: "location", location},
+ }, {action: "doUpdateUpdated", id: blockID, data: updated}], [
+ {action: "removeAttrViewBlock", avID, blockID, srcIDs: [itemID]},
+ {action: "doUpdateUpdated", id: blockID, data: blockElement.getAttribute("updated")},
+ ], {callback: () => {
+ committed = true;
+ // 写入已成功时不依赖旧地图实例仍存在;导航到其他数据库或历史后不再打开条目。
+ if (!blockElement.isConnected || blockElement.dataset.avId !== avID || blockElement.dataset.nodeId !== blockID ||
+ blockElement.closest(".protyle-wysiwyg") !== editorElement || protyle.notebookId !== notebookID ||
+ getAVViewID(blockElement) !== viewID || !editable(protyle) || isNotebookLocked(protyle)) return;
+ blockElement.setAttribute("updated", updated);
+ blockElement.removeAttribute("data-render");
+ avRender(blockElement, protyle);
+ void openDatabaseRowByData(protyle, {avID, databaseBlockID: blockID, notebookID,
+ itemID, valueID: "", title: window.siyuan.languages.untitled, isDetached: true, focusPrimary: true});
+ }});
+ await waitForPendingTransactions(protyle);
+ return committed;
+};
+
+export const bindMapPointPicking = (options: {
+ canvas: HTMLElement;
+ blockElement: HTMLElement;
+ protyle: IProtyle;
+ data: IAV;
+ current: () => boolean;
+}) => {
+ const {canvas, blockElement, protyle, data, current} = options;
+ const view = data.view as IAVTable;
+ const locationKeyID = getMapSettings(view).locationKeyID;
+ const avID = data.id, viewID = data.viewID, blockID = blockElement.dataset.nodeId;
+ const editorElement = blockElement.closest(".protyle-wysiwyg");
+ const notebookID = protyle.notebookId;
+ let destroyed = false, pending = false;
+ let menu: Menu;
+ const available = () => !destroyed && current() && blockElement.isConnected &&
+ blockElement.dataset.avId === avID && blockElement.dataset.nodeId === blockID &&
+ blockElement.closest(".protyle-wysiwyg") === editorElement && protyle.notebookId === notebookID &&
+ getAVViewID(blockElement) === viewID &&
+ data.view === view && data.viewID === viewID && getMapSettings(view).locationKeyID === locationKeyID &&
+ view.columns.some(column => column.id === locationKeyID && column.type === "location") &&
+ !isNotebookLocked(protyle);
+ return {
+ show: (input: AVMapCoordinate) => {
+ const point = parseAVMapCoordinate(input);
+ if (!point || !available()) return;
+ menu?.close();
+ // 既有地点名称只在父页面查找,不读取或转发供应商返回的要素属性。
+ const location = view.rows.map(row => row.cells.find(cell => cell.value?.keyID === locationKeyID)?.value?.location)
+ .find(value => validateAVLocation(value) && value?.longitude === point.longitude &&
+ value.latitude === point.latitude && value.name?.trim());
+ const selected = {...point, name: location?.name || ""};
+ const text = getAVLocationText(selected);
+ // 地图的每次选点替换坐标菜单,不将整个画布当作重复点击关闭按钮。
+ toggleMenu({target: canvas, toggle: false, build: (_shared, session) => {
+ menu = new Menu(undefined, () => { menu = undefined; });
+ menu.addItem({type: "readonly", iconHTML: "", label: escapeHtml(window.siyuan.languages.mapPickedPoint)});
+ menu.addItem({type: "readonly", iconHTML: "", label: escapeHtml(text)});
+ menu.addItem({icon: "iconCopy", label: window.siyuan.languages.copy, click: () => {
+ if (session.isCurrent() && available()) writeText(text);
+ }});
+ if (editable(protyle) && !pending) {
+ menu.addItem({icon: "iconAdd", label: window.siyuan.languages.mapCreateAtPoint, click: () => {
+ if (!session.isCurrent() || !available() || !editable(protyle) || pending) return;
+ pending = true;
+ void createMapRecordAtPoint({protyle, blockElement, avID, viewID, locationKeyID,
+ location: selected, current: available}).catch(() => {
+ // 事务层负责失败提示,保留地图供用户重新选择或重试。
+ }).finally(() => { pending = false; });
+ }});
+ }
+ }, show: () => {
+ const rect = canvas.getBoundingClientRect();
+ menu.open({x: rect.left + rect.width / 2, y: rect.top + rect.height / 2, target: canvas});
+ }});
+ },
+ destroy: () => {
+ destroyed = true;
+ menu?.close();
+ },
+ };
+};
diff --git a/app/src/protyle/render/av/map/protocol.test.ts b/app/src/protyle/render/av/map/protocol.test.ts
index fe479234bc..02a914a098 100644
--- a/app/src/protyle/render/av/map/protocol.test.ts
+++ b/app/src/protyle/render/av/map/protocol.test.ts
@@ -10,6 +10,29 @@ import {getAVMapLockedPolicy} from "./bootstrap";
describe("isolated map protocol", () => {
const point = {id: "row-1", longitude: 0, latitude: 0};
+ it("enables picking explicitly and shares a bounded coordinate reply whitelist with Electron", () => {
+ const {parseMapCreate, parseMapReply} = require("../../../../../electron/mapHostPolicy");
+ const init = {version: 1, instanceID: "a".repeat(48), type: "init", provider: "openfreemap", theme: "light"};
+ for (const picking of [undefined, false, true]) {
+ const expected = {...init, ...(picking && {picking: true})};
+ assert.deepEqual(parseAVMapCommand({...init, picking}, init.instanceID), expected);
+ assert.deepEqual(parseMapCreate({...init, picking}), expected);
+ }
+ for (const picking of ["true", 1, null, {}]) {
+ assert.equal(parseAVMapCommand({...init, picking}, init.instanceID), undefined);
+ assert.equal(parseMapCreate({...init, picking}), undefined);
+ }
+ const reply = {version: 1, instanceID: init.instanceID, type: "pointClick", revision: 0,
+ longitude: 180, latitude: AV_MAP_MERCATOR_MAX_LATITUDE};
+ for (const parse of [parseAVMapReply, parseMapReply]) {
+ assert.deepEqual(parse({...reply, name: "private", url: "https://private.invalid"}, init.instanceID), reply);
+ for (const invalid of [{longitude: 181}, {latitude: 90}, {latitude: Infinity}, {longitude: NaN},
+ {longitude: "0"}, {latitude: null}, {revision: -1}, {revision: 1.5}, {coordinateSystem: "wgs84"},
+ {coordinateSystem: undefined}, {version: 2}, {instanceID: "foreign"}]) {
+ assert.equal(parse({...reply, ...invalid}, init.instanceID), undefined);
+ }
+ }
+ });
it("keeps attribution destinations in a fixed official allowlist", () => {
assert.deepEqual(AV_MAP_ATTRIBUTION_LINKS.openfreemap.map((link) => link.href), [
"https://openfreemap.org", "https://www.openmaptiles.org/", "https://www.openstreetmap.org/copyright", "https://maplibre.org/",
diff --git a/app/src/protyle/render/av/map/protocol.ts b/app/src/protyle/render/av/map/protocol.ts
index 77076153d5..01333be63d 100644
--- a/app/src/protyle/render/av/map/protocol.ts
+++ b/app/src/protyle/render/av/map/protocol.ts
@@ -57,12 +57,15 @@ export const AV_MAP_ATTRIBUTION_LINKS: Readonly<Record<AVMapProvider,
export const isAVMapAttributionLink = (value: unknown): value is AVMapAttributionLink =>
AV_MAP_ATTRIBUTION_LINKS.openfreemap.some(link => link.id === value);
-export interface AVMapPoint {
- id: string;
+export interface AVMapCoordinate {
longitude: number;
latitude: number;
}
+export interface AVMapPoint extends AVMapCoordinate {
+ id: string;
+}
+
interface AVMapEnvelope {
version: 1;
instanceID: string;
@@ -72,6 +75,7 @@ export interface AVMapInit extends AVMapEnvelope {
type: "init";
provider: AVMapProvider;
theme: AVMapTheme;
+ picking?: true;
}
export type AVMapCommand = AVMapInit |
@@ -83,6 +87,7 @@ export type AVMapCommand = AVMapInit |
export type AVMapReply = (AVMapEnvelope & {type: "ready"}) |
(AVMapEnvelope & {type: "attributionClick"; link: AVMapAttributionLink}) |
(AVMapEnvelope & {type: "markerClick"; id: string; revision: number}) |
+ (AVMapEnvelope & {type: "pointClick"; revision: number} & AVMapCoordinate) |
(AVMapEnvelope & {type: "error"; code: AVMapErrorCode});
export const isAVMapProvider = (value: unknown): value is AVMapProvider =>
@@ -124,6 +129,14 @@ export const sanitizeAVMapPoints = (input: unknown): AVMapPoint[] => {
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
+export const parseAVMapCoordinate = (value: unknown): AVMapCoordinate | undefined => {
+ const point = asRecord(value);
+ if (!point || "coordinateSystem" in point || typeof point.longitude !== "number" ||
+ !Number.isFinite(point.longitude) || Math.abs(point.longitude) > 180 ||
+ typeof point.latitude !== "number" || !isAVMapProjectionSupported(point.latitude)) return;
+ return {longitude: point.longitude, latitude: point.latitude};
+};
+
const parseAVMapViewport = (value: unknown): AVMapViewport | undefined => {
const rect = asRecord(value);
if (!rect || ![rect.x, rect.y, rect.width, rect.height].every(number =>
@@ -140,10 +153,12 @@ export const parseAVMapCommand = (value: unknown, instanceID: string, provider?:
const envelope = {version: AV_MAP_PROTOCOL_VERSION, instanceID} as const;
switch (input.type) {
case "init":
- if (!isAVMapProvider(input.provider) || !isAVMapTheme(input.theme)) {
+ if (!isAVMapProvider(input.provider) || !isAVMapTheme(input.theme) ||
+ input.picking !== undefined && typeof input.picking !== "boolean") {
return;
}
- return {...envelope, type: "init", provider: input.provider, theme: input.theme};
+ return {...envelope, type: "init", provider: input.provider, theme: input.theme,
+ ...(input.picking === true && {picking: true})};
case "setPoints":
if (!provider || !isAVMapRevision(input.revision) || !Array.isArray(input.points)) {
return;
@@ -177,6 +192,10 @@ export const parseAVMapReply = (value: unknown, instanceID: string): AVMapReply
if (input.type === "markerClick" && isAVMapIdentifier(input.id) && isAVMapRevision(input.revision)) {
return {...envelope, type: "markerClick", id: input.id, revision: input.revision};
}
+ if (input.type === "pointClick" && isAVMapRevision(input.revision)) {
+ const point = parseAVMapCoordinate(input);
+ return point ? {...envelope, type: "pointClick", revision: input.revision, ...point} : undefined;
+ }
if (input.type === "attributionClick" && isAVMapAttributionLink(input.link)) {
return {...envelope, type: "attributionClick", link: input.link};
}
diff --git a/app/src/protyle/render/av/map/providers.test.ts b/app/src/protyle/render/av/map/providers.test.ts
index 2f68b8db61..14f38fb109 100644
--- a/app/src/protyle/render/av/map/providers.test.ts
+++ b/app/src/protyle/render/av/map/providers.test.ts
@@ -146,6 +146,33 @@ test("OpenFreeMap preserves longitude/latitude, attribution and cleans stale cal
assert.equal(calls.filter(call => call[0] === "clear").length, 1);
});
+test("point picking accepts only genuine current map clicks and normalizes world copies without forwarding metadata", () => {
+ const f = fixture();
+ const clicked: unknown[] = [];
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {
+ onMarkerClick() {}, onError() {}, onPointClick: (...args) => clicked.push(args),
+ });
+ const click = f.instances[0].callbacks.get("click");
+ const event = {originalEvent: {isTrusted: true, button: 0}, lngLat: {lng: 121.4, lat: 31.2}, features: [{name: "private"}]};
+ click(event);
+ f.ready();
+ click(event);
+ assert.deepEqual(clicked, []);
+ adapter.setPoints([], 1);
+ click({...event, originalEvent: {isTrusted: false, button: 0}});
+ click({...event, originalEvent: {isTrusted: true, button: 1}});
+ click({...event, lngLat: {lng: 0, lat: 90}});
+ click({...event, lngLat: {lng: Infinity, lat: 0}});
+ assert.deepEqual(clicked, []);
+ click(event);
+ click({...event, lngLat: {lng: 540, lat: 0}, originalEvent: {isTrusted: true}});
+ assert.deepEqual(clicked, [[{longitude: 121.4, latitude: 31.2}, 1], [{longitude: -180, latitude: 0}, 1]]);
+ adapter.destroy();
+ click(event);
+ assert.equal(clicked.length, 2);
+ assert.equal(f.instances[0].callbacks.has("click"), false);
+});
+
test("attribution waits for five continuously visible seconds after load and stays expandable", () => {
const f = fixture();
const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
diff --git a/app/src/protyle/render/av/map/providers.ts b/app/src/protyle/render/av/map/providers.ts
index cde775240d..253314ba80 100644
--- a/app/src/protyle/render/av/map/providers.ts
+++ b/app/src/protyle/render/av/map/providers.ts
@@ -1,6 +1,6 @@
import {
- AVMapAttributionLink, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapViewport,
- sanitizeAVMapPoints,
+ AVMapAttributionLink, AVMapCoordinate, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapViewport,
+ parseAVMapCoordinate, sanitizeAVMapPoints,
} from "./protocol";
import {AVMapAttributionController, createAVMapAttribution} from "./attribution";
@@ -30,6 +30,7 @@ export interface AVMapAdapter {
export interface AVMapAdapterCallbacks {
onMarkerClick: (id: string, revision: number) => void;
+ onPointClick?: (point: AVMapCoordinate, revision: number) => void;
onError: (code: AVMapErrorCode) => void;
onReady?: () => void;
onAttributionClick?: (link: AVMapAttributionLink) => void;
@@ -54,6 +55,17 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
attributionControl: false, trackResize: false});
let attribution: AVMapAttributionController;
let ready = false, loaded = false;
+ const onPointClick = (event: any) => {
+ if (destroyed || !ready || revision < 0 || !event?.originalEvent?.isTrusted ||
+ event.originalEvent.button !== undefined && event.originalEvent.button !== 0) return;
+ // 世界副本仅归一化经度,不转换坐标系;名称和供应商要素属性不离开隔离页面。
+ const longitude = event.lngLat?.lng;
+ if (typeof longitude !== "number" || !Number.isFinite(longitude)) return;
+ const point = parseAVMapCoordinate({longitude: Math.abs(longitude) <= 180 ? longitude :
+ ((longitude + 180) % 360 + 360) % 360 - 180,
+ latitude: event.lngLat?.lat});
+ if (point) callbacks.onPointClick?.(point, revision);
+ };
const onReady = () => {
if (!destroyed && !ready) {
ready = true;
@@ -75,6 +87,7 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
map.off("style.load", onReady);
map.off("load", onLoad);
map.off("error", error);
+ if (callbacks.onPointClick) map.off("click", onPointClick);
cleanMarkers();
points = [];
} finally {
@@ -90,6 +103,7 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
map.on("error", error);
map.on("style.load", onReady);
map.on("load", onLoad);
+ if (callbacks.onPointClick) map.on("click", onPointClick);
} catch (error) {
destroy();
throw error;
@@ -102,7 +116,8 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
cleanMarkers();
points = sanitizeAVMapPoints(input);
points.forEach(point => {
- const onClick = () => {
+ const onClick = (event?: Event) => {
+ event?.stopPropagation();
if (!destroyed && nextRevision === revision && points.some(item => item.id === point.id)) {
callbacks.onMarkerClick(point.id, nextRevision);
}
diff --git a/app/src/protyle/render/av/map/render.test.ts b/app/src/protyle/render/av/map/render.test.ts
index 5f36fecaf3..ec66d727bd 100644
--- a/app/src/protyle/render/av/map/render.test.ts
+++ b/app/src/protyle/render/av/map/render.test.ts
@@ -12,15 +12,18 @@ import {DOMElement, DOMFixture, requireFixture} from "./testDOM";
const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?: boolean | Promise<boolean>;
online?: boolean; protocol?: string; source?: string; failDuringCreate?: boolean; runtime?: () => Promise<unknown>} = {}) => {
const document = new DOMFixture();
+ const editor = document.createElement("div");
+ editor.className = "protyle-wysiwyg";
+ document.body.append(editor);
const roots: DOMElement[] = [];
const block = document.createElement("div");
block.dataset.avId = "database";
block.dataset.nodeId = "carrier";
block.innerHTML = '<div class="av__container"><div class="av__scroll"></div></div>';
- document.body.append(block);
+ editor.append(block);
const records = block.querySelector(".av__scroll");
let root: DOMElement;
- let lifecycle: {root: DOMElement; destroy: () => void};
+ let lifecycle: {root: DOMElement; destroy: () => void; remount: () => void};
const languages = new Proxy<Record<string, string>>({mapPageScope: "Map covers ${shown} loaded records of ${total} filtered records",
mapLoadedCount: "Loaded ${shown}/${total}", mapSkippedCount: "Skipped ${count}",
mapSkippedLocations: "Skipped locations: ${empty} missing, ${invalid} invalid, ${projection} unsupported projection"},
@@ -41,6 +44,7 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
const calls: string[] = [];
const transactions: Array<{perform: IOperation[]; undo: IOperation[]; callback: () => void}> = [];
const unplaced: Array<{options: Parameters<typeof import("./unplaced").bindMapUnplaced>[0]; destroyed: boolean}> = [];
+ const picking: Array<{points: protocol.AVMapCoordinate[]; destroyed: boolean}> = [];
let settleTransaction: () => void;
let transactionPromise = Promise.resolve();
let refreshes = 0;
@@ -53,7 +57,7 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
{id: "primary-value", valueType: "block", value: {type: "block", isDetached: true,
block: {content: "Private title"}}}]}],
}} as IAV;
- const protyle = {options: {}, app: {}, notebookId: "notebook"} as IProtyle;
+ const protyle = {options: {}, app: {}, notebookId: "notebook", wysiwyg: {element: editor}} as unknown as IProtyle;
const destroyMap = () => {
lifecycle?.destroy();
lifecycle = undefined;
@@ -87,6 +91,12 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
unplaced.push(binding);
return () => { binding.destroyed = true; };
}},
+ "./pointPicking": {bindMapPointPicking: () => {
+ const binding = {points: [] as protocol.AVMapCoordinate[], destroyed: false};
+ picking.push(binding);
+ return {show: (point: protocol.AVMapCoordinate) => binding.points.push(point),
+ destroy: () => { binding.destroyed = true; }};
+ }},
"../openDatabaseRow": {openDatabaseRowByData: (_protyle: unknown, row: unknown) => opened.push(row)},
"./host": {isAVMapHostEnvironmentSupported: () => options.hostSupported ?? true,
createAVMapHost: (container: DOMElement, configuration: AVMapHostOptions) => {
@@ -132,7 +142,14 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
documentElement: document.documentElement},
MutationObserver: Observer, ResizeObserver: class {constructor() { assert.fail("Map hosts own their resize observers"); }},
Lute: {NewNodeID: () => "new-location"}});
- return {data, protyle, calls, hosts, roots, records, block, opened, openedLinks, events, observers, destroyMap, transactions, context, unplaced,
+ return {data, protyle, calls, hosts, roots, records, block, opened, openedLinks, events, observers, destroyMap, transactions, context, unplaced, picking,
+ remount: () => lifecycle.remount(),
+ moveToOtherEditor: () => {
+ const destination = document.createElement("div");
+ destination.className = "protyle-wysiwyg";
+ document.body.append(destination);
+ destination.append(block);
+ },
refreshes: () => refreshes,
completeTransaction: async (success = true) => {
if (success) transactions[transactions.length - 1].callback();
@@ -224,11 +241,13 @@ test("map summary retains skipped counts when every loaded row lacks a compatibl
const view = scenario.data.view as IAVTable;
view.rows[0].cells[0].value.location.latitude = 90;
await scenario.render();
+ scenario.hosts[0].options.onReady();
assert.equal(scenario.status(), "mapNoMarkers");
assert.equal(scenario.control(".av__map-skipped").textContent, "Skipped 1");
assert.equal(scenario.control(".av__map-summary").getAttribute("aria-label"),
"Map covers 1 loaded records of 12 filtered records\nSkipped locations: 0 missing, 0 invalid, 1 unsupported projection");
- assert.deepEqual(scenario.calls, []);
+ assert.deepEqual(scenario.calls, ["/api/map/getRuntime"]);
+ assert.deepEqual(scenario.hosts[0].points, []);
});
test("map attribution stays inside the control and parent opens only fixed current destinations", async () => {
@@ -253,7 +272,7 @@ test("published maps render a status without inline settings, runtime admission,
assert.doesNotMatch(scenario.roots[0].innerHTML, /av__map-settings|data-map-setting|data-map-configure|av__map-actions|data-map-fit|data-map-retry/);
});
-test("missing field, unavailable host, offline and unsupported projection maps never request runtime admission", async () => {
+test("missing field, unavailable host, offline and empty readonly maps never request runtime admission", async () => {
for (const option of [{hostSupported: false}, {online: false}, {}]) {
const scenario = setup(option);
if (!Object.keys(option).length) (scenario.data.view as IAVTable).columns = [];
@@ -262,12 +281,34 @@ test("missing field, unavailable host, offline and unsupported projection maps n
assert.equal(scenario.hosts.length, 0);
}
const incompatible = setup();
+ incompatible.protyle.disabled = true;
(incompatible.data.view as IAVTable).rows[0].cells[0].value.location.latitude = 90;
await incompatible.render();
assert.deepEqual(incompatible.calls, []);
assert.equal(incompatible.status(), "mapNoMarkers");
});
+test("empty editable maps permit first-point picking and stale or disposed callbacks cannot open popovers", async () => {
+ const scenario = setup();
+ (scenario.data.view as IAVTable).rows = [];
+ await scenario.render();
+ const host = scenario.hosts[0];
+ const point = {longitude: 0, latitude: 0};
+ assert.deepEqual(host.points, []);
+ host.options.onPointClick(point, host.revision - 1);
+ host.options.onPointClick(point, host.revision);
+ assert.deepEqual(scenario.picking[0].points, [point]);
+ await scenario.render();
+ host.options.onPointClick(point, host.revision);
+ assert.equal(scenario.picking[0].destroyed, true);
+ assert.equal(scenario.picking[0].points.length, 1);
+ scenario.events.get("offline")();
+ const next = scenario.hosts[1];
+ next.options.onPointClick(point, next.revision);
+ assert.equal(scenario.picking[1].destroyed, true);
+ assert.equal(scenario.picking[1].points.length, 0);
+});
+
test("deleted and changed-type map fields show a repairable location setup", async () => {
for (const locationKeyID of ["deleted", "text"]) {
const scenario = setup();
@@ -603,6 +644,54 @@ test("a host that fails synchronously during creation never acquires view observ
assert.equal(scenario.hosts[0].destroys, 1);
});
+test("moving a live map remounts its host and ignores replies from the old host", async () => {
+ const scenario = setup();
+ await scenario.render();
+ const original = scenario.hosts[0];
+ scenario.remount();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(original.destroys, 1);
+ assert.equal(scenario.hosts.length, 2);
+ original.options.onMarkerClick("row", original.revision);
+ original.options.onError("hostUnavailable");
+ assert.equal(scenario.opened.length, 0);
+ assert.equal(scenario.hosts[1].destroyed, false);
+ assert.equal(scenario.unplaced[0].destroyed, true);
+});
+
+test("a moved guest can recover when its disconnect error arrives before the DOM observer", async () => {
+ const scenario = setup();
+ await scenario.render();
+ scenario.hosts[0].options.onError("hostUnavailable");
+ assert.equal(scenario.hosts[0].destroys, 1);
+ scenario.remount();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(scenario.hosts.length, 2);
+ assert.equal(scenario.hosts[1].destroyed, false);
+});
+
+test("cross-editor moves invalidate active and hostless maps before destination transactions rehydrate them", async () => {
+ for (const mode of ["live", "setup", "offline", "pending"]) {
+ let finish: (response: unknown) => void;
+ const scenario = setup({online: mode !== "offline", runtime: mode === "pending" ?
+ () => new Promise(resolve => { finish = resolve; }) : undefined});
+ if (mode === "setup") (scenario.data.view as IAVTable).columns = [];
+ scenario.block.setAttribute("data-render", "true");
+ const rendering = scenario.render();
+ await new Promise(resolve => setImmediate(resolve));
+ scenario.moveToOtherEditor();
+ scenario.remount();
+ if (finish) finish({code: 0, data: {provider: "openfreemap"}});
+ await rendering;
+ assert.equal(scenario.block.getAttribute("data-render"), null);
+ assert.equal(scenario.block.querySelector(".av__map"), null);
+ assert.equal(scenario.hosts.length, mode === "live" ? 1 : 0);
+ assert.ok(scenario.hosts.every(host => host.destroyed));
+ assert.ok(scenario.unplaced.every(binding => binding.destroyed));
+ assert.ok(scenario.picking.every(binding => binding.destroyed));
+ }
+});
+
test("non-HTTP, both history modes and published views retain their own safe fallbacks", async () => {
for (const mode of ["protocol", "created", "snapshot", "published"]) {
const scenario = setup({protocol: mode === "protocol" ? "file:" : "https:", published: mode === "published"});
diff --git a/app/src/protyle/render/av/map/render.ts b/app/src/protyle/render/av/map/render.ts
index 2e91f343bc..427d860223 100644
--- a/app/src/protyle/render/av/map/render.ts
+++ b/app/src/protyle/render/av/map/render.ts
@@ -12,6 +12,7 @@ import {createDesktopAVMapHost, isDesktopAVMapHostSupported} from "./desktopTran
import type {AVMapHost} from "./host";
import {AV_MAP_ATTRIBUTION_LINKS, AV_MAP_MAX_POINTS} from "./protocol";
import {bindMapUnplaced} from "./unplaced";
+import {bindMapPointPicking} from "./pointPicking";
const getTheme = () => document.documentElement.getAttribute("data-theme-mode") === "dark" ? "dark" : "light";
@@ -119,8 +120,10 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
const status = root.querySelector<HTMLElement>(".av__map-status");
const canvas = root.querySelector<HTMLElement>(".av__map-canvas");
let host: AVMapHost;
+ let hostMounted = false;
let themeObserver: MutationObserver;
let destroyUnplaced: () => void;
+ let picking: ReturnType<typeof bindMapPointPicking>;
let revision = 0;
const offline = () => fallback(window.siyuan.languages.mapOffline);
const releaseHost = () => {
@@ -130,12 +133,26 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
themeObserver?.disconnect();
themeObserver = undefined;
window.removeEventListener("offline", offline);
+ picking?.destroy();
+ picking = undefined;
previousHost?.destroy();
};
- const current = registerMap(blockElement, {root, destroy: () => {
+ const current = registerMap(blockElement, {root, remount: () => {
+ const ownerElement = blockElement.closest(".protyle-wysiwyg");
+ if (ownerElement !== protyle.wysiwyg.element) {
+ // 跨编辑器移动后由目标事务重新读取上下文,旧请求和菜单不得沿用源笔记本。
+ destroyMap(blockElement);
+ root.remove();
+ blockElement.removeAttribute("data-render");
+ } else if (hostMounted) {
+ void renderMap(blockElement, protyle, data);
+ }
+ }, destroy: () => {
releaseHost();
destroyUnplaced?.();
destroyUnplaced = undefined;
+ picking?.destroy();
+ picking = undefined;
}});
const fallback = (message: string) => {
if (!current()) {
@@ -181,7 +198,7 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
fallback(window.siyuan.languages.mapUnsupportedClient);
return;
}
- if (!points.length) {
+ if (!points.length && !canEditMapSettings(protyle)) {
fallback(window.siyuan.languages.mapNoMarkers);
return;
}
@@ -206,7 +223,9 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
const rowByID = new Map(view.rows.map(row => [row.id, row]));
const pointIDs = new Set(points.map(point => point.id));
const activeRevision = ++revision;
+ picking = bindMapPointPicking({canvas, blockElement, protyle, data, current});
canvas.classList.remove("fn__none");
+ hostMounted = true;
const nextHost = (desktopHost ? createDesktopAVMapHost : createAVMapHost)(canvas, {
provider: "openfreemap",
theme: getTheme(),
@@ -215,7 +234,7 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
if (!current() || revision !== activeRevision) {
return;
}
- status.textContent = "";
+ status.textContent = points.length ? "" : window.siyuan.languages.mapNoMarkers;
},
onAttributionClick: id => {
if (!current() || revision !== activeRevision) return;
@@ -233,6 +252,11 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
void openMapRecord(protyle, blockElement, rowByID.get(id));
}
},
+ onPointClick: (point, pointRevision) => {
+ if (current() && pointRevision === activeRevision && revision === activeRevision) {
+ picking?.show(point);
+ }
+ },
});
if (!current() || revision !== activeRevision) {
nextHost.destroy();
diff --git a/app/src/protyle/render/av/map/state.test.ts b/app/src/protyle/render/av/map/state.test.ts
index b60bec4c38..ae3f78f494 100644
--- a/app/src/protyle/render/av/map/state.test.ts
+++ b/app/src/protyle/render/av/map/state.test.ts
@@ -2,6 +2,7 @@ import * as assert from "node:assert/strict";
import {test} from "node:test";
import {canLoadMapHost, destroyMap, getMapPoints, getMapSettings, registerMap} from "./state";
import {AV_MAP_MAX_POINTS} from "./protocol";
+import {DOMFixture} from "./testDOM";
const table = (locations: IAVCellLocationValue[]) => ({
rowCount: locations.length,
@@ -99,10 +100,10 @@ test("map host requires an HTTP document protocol", () => {
test("map lifecycle is independent per editor and releases removed or replaced hosts", () => {
const previousObserver = Object.getOwnPropertyDescriptor(globalThis, "MutationObserver");
const previousDocument = Object.getOwnPropertyDescriptor(globalThis, "document");
- let removal: () => void;
+ let removal: (records: MutationRecord[]) => void;
let disconnected = 0;
Object.assign(globalThis, {document: {body: {}}, MutationObserver: class {
- constructor(callback: () => void) { removal = callback; }
+ constructor(callback: typeof removal) { removal = callback; }
observe() {}
disconnect() { disconnected++; }
}});
@@ -122,7 +123,7 @@ test("map lifecycle is independent per editor and releases removed or replaced h
assert.equal(first(), false);
assert.equal(replacement(), true);
Object.assign(rootA, {isConnected: false});
- removal();
+ removal([]);
assert.equal(disposedA, 2);
assert.equal(second(), true);
assert.equal(disposedB, 0);
@@ -138,3 +139,57 @@ test("map lifecycle is independent per editor and releases removed or replaced h
else Reflect.deleteProperty(globalThis, "document");
}
});
+
+test("map moves remount once per mutation batch without revisiting newly registered hosts", () => {
+ const previousObserver = Object.getOwnPropertyDescriptor(globalThis, "MutationObserver");
+ const previousDocument = Object.getOwnPropertyDescriptor(globalThis, "document");
+ const document = new DOMFixture();
+ let observe: (records: MutationRecord[]) => void;
+ Object.assign(globalThis, {document, MutationObserver: class {
+ constructor(callback: typeof observe) { observe = callback; }
+ observe() {}
+ disconnect() {}
+ }});
+ const parent = document.createElement("div");
+ const block = document.createElement("div");
+ const root = document.createElement("div");
+ const mirror = document.createElement("div");
+ const mirrorRoot = document.createElement("div");
+ document.body.append(parent);
+ parent.append(block);
+ block.append(root);
+ document.body.append(mirror);
+ mirror.append(mirrorRoot);
+ let remounts = 0;
+ let destroyed = 0;
+ let mirrorRemounts = 0;
+ const element = block as unknown as HTMLElement;
+ const register = () => registerMap(element, {root: root as unknown as HTMLElement,
+ destroy: () => { destroyed++; }, remount: () => { remounts++; register(); }});
+ const removed = (node: unknown) => ({removedNodes: [node]}) as unknown as MutationRecord;
+ try {
+ const initial = register();
+ registerMap(mirror as unknown as HTMLElement, {root: mirrorRoot as unknown as HTMLElement,
+ destroy() {}, remount: () => { mirrorRemounts++; }});
+ observe([removed(parent), removed(block)]);
+ assert.equal(remounts, 1);
+ assert.equal(destroyed, 1);
+ assert.equal(initial(), false);
+ assert.equal(mirrorRemounts, 0);
+ observe([removed(document.createElement("div"))]);
+ assert.equal(remounts, 1);
+ observe([removed(block)]);
+ assert.equal(remounts, 2);
+ block.remove();
+ observe([removed(block)]);
+ assert.equal(remounts, 2);
+ assert.equal(destroyed, 3);
+ } finally {
+ destroyMap(element);
+ destroyMap(mirror as unknown as HTMLElement);
+ if (previousObserver) Object.defineProperty(globalThis, "MutationObserver", previousObserver);
+ else Reflect.deleteProperty(globalThis, "MutationObserver");
+ if (previousDocument) Object.defineProperty(globalThis, "document", previousDocument);
+ else Reflect.deleteProperty(globalThis, "document");
+ }
+});
diff --git a/app/src/protyle/render/av/map/state.ts b/app/src/protyle/render/av/map/state.ts
index 9b40dd341c..36ada026dd 100644
--- a/app/src/protyle/render/av/map/state.ts
+++ b/app/src/protyle/render/av/map/state.ts
@@ -42,6 +42,7 @@ export const canLoadMapHost = (protocol: string) => ["http:", "https:"].includes
interface IMapLifecycle {
root: HTMLElement;
destroy: () => void;
+ remount?: () => void;
}
const lifecycles = new WeakMap<HTMLElement, IMapLifecycle>();
@@ -64,11 +65,15 @@ export const registerMap = (blockElement: HTMLElement, state: IMapLifecycle) =>
lifecycles.set(blockElement, state);
mountedBlocks.add(blockElement);
if (!removalObserver) {
- removalObserver = new MutationObserver(() => {
- mountedBlocks.forEach(block => {
- const current = lifecycles.get(block);
+ removalObserver = new MutationObserver(records => {
+ // 移动节点也会重置 iframe/webview;先快照,避免重建时修改集合导致重复遍历。
+ Array.from(mountedBlocks, block => ({block, current: lifecycles.get(block)})).forEach(({block, current}) => {
+ if (lifecycles.get(block) !== current) return;
if (!block.isConnected || !current?.root.isConnected || !block.contains(current.root)) {
destroyMap(block);
+ } else if (records.some(record => Array.from(record.removedNodes).some(node =>
+ node.contains(current.root)))) {
+ current.remount?.();
}
});
});
diff --git a/app/src/protyle/render/av/refreshView.test.ts b/app/src/protyle/render/av/refreshView.test.ts
new file mode 100644
index 0000000000..1536adedbc
--- /dev/null
+++ b/app/src/protyle/render/av/refreshView.test.ts
@@ -0,0 +1,39 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {DOMFixture} from "./map/testDOM";
+
+const compiled = transpileModule(readFileSync("src/protyle/render/av/render.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+test("switching one database carrier refreshes only its copies and preserves other map hosts", () => {
+ const document = new DOMFixture();
+ const root = document.createElement("div");
+ document.body.append(root);
+ root.innerHTML = ["carrier", "mirror", "carrier"].map(id =>
+ `<div class="av" data-av-id="database" data-node-id="${id}" data-render="true"><div class="av__header" data-view-pages="pages"></div><div class="av__body" data-page-size="100"></div><div class="av__map"></div></div>`).join("");
+ const blocks = root.children;
+ const rendered: unknown[] = [];
+ const exports: any = {};
+ runInNewContext(compiled, {exports, require: () => ({
+ getAVViewPageSize: (_pages: string, id: string) => id === "limited" ? "50" : undefined,
+ }), window: {setTimeout: () => assert.fail("Carrier-only view changes must not schedule a database-wide refresh")}});
+ exports.avRender = (block: unknown) => { rendered.push(block); };
+ const protyle = {wysiwyg: {element: root}};
+ exports.refreshAV(protyle, {action: "setAttrViewBlockView", avID: "database", blockID: "carrier", id: "limited"});
+ assert.deepEqual(rendered, [blocks[0], blocks[2]]);
+ assert.equal(blocks[1].getAttribute("data-render"), "true");
+ assert.equal(blocks[1].querySelector(".av__body").dataset.pageSize, "100");
+ for (const block of [blocks[0], blocks[2]]) {
+ assert.equal(block.getAttribute("data-render"), null);
+ assert.equal(block.querySelector(".av__body").dataset.pageSize, "50");
+ }
+ rendered.length = 0;
+ exports.refreshAV(protyle, {action: "setAttrViewBlockView", avID: "database", blockID: "carrier", id: "unlimited"});
+ assert.deepEqual(rendered, [blocks[0], blocks[2]]);
+ assert.equal(blocks[0].querySelector(".av__body").hasAttribute("data-page-size"), false);
+ assert.equal(blocks[1].querySelector(".av__body").dataset.pageSize, "100");
+});
diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.ts
index 051babbe4d..68499755ba 100644
--- a/app/src/protyle/render/av/render.ts
+++ b/app/src/protyle/render/av/render.ts
@@ -892,6 +892,21 @@ const waitForAddingCellPosition = async (options: {
};
export const refreshAV = (protyle: IProtyle, operation: IOperation) => {
+ if (operation.action === "setAttrViewBlockView" && operation.blockID) {
+ getAVElements(protyle, operation.avID).forEach(item => {
+ if (item.dataset.nodeId !== operation.blockID) return;
+ const pageSize = getAVViewPageSize(
+ item.querySelector(".av__header")?.getAttribute("data-view-pages"), operation.id
+ );
+ item.querySelectorAll<HTMLElement>(".av__body").forEach(body => {
+ if (pageSize) body.dataset.pageSize = pageSize;
+ else body.removeAttribute("data-page-size");
+ });
+ item.removeAttribute("data-render");
+ void avRender(item, protyle);
+ });
+ return;
+ }
if (operation.action === "insertAttrViewBlock") {
inspectAVInsertedItem(protyle, operation);
}
diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.ts
index 7a109ab159..c015b30ea0 100644
--- a/app/src/protyle/util/insertHTML.ts
+++ b/app/src/protyle/util/insertHTML.ts
@@ -27,7 +27,7 @@ import {
import {focusByRange, getSelectionOffset, setLastNodeRange} from "./selectionOffsets";
import {Constants} from "../../constants";
import {showMessage} from "../../dialog/message";
-import {createAVLocationReplacement, isAVLocationCoordinateInput} from "../render/av/locationValue";
+import {createAVLocationFromText, createAVLocationReplacement} from "../render/av/locationValue";
import {highlightRender} from "../render/highlightRender";
import {scrollCenter} from "../../util/highlightById";
import {updateAttrViewCellAnimation, updateAVName} from "../render/av/action";
@@ -360,7 +360,7 @@ const pasteAVMatrix = async (options: {
return;
}
const availableColumns = visibleColumns.slice(startColumnIndex);
- const requiresLocationEditor = availableColumns.some((column, index) => column.type === "location" &&
+ const invalidLocationInput = availableColumns.some((column, index) => column.type === "location" &&
!(options.header && inferableKeyIDs.has(column.id)) && options.values.some(row => {
const value = row[index];
if (typeof value === "undefined") {
@@ -368,9 +368,14 @@ const pasteAVMatrix = async (options: {
}
const pasteValue = getAVPasteValueForType(value, "location");
const text = typeof pasteValue === "string" ? pasteValue : pasteValue.type === "text" ? pasteValue.text?.content : "";
- return isAVLocationCoordinateInput(text || "");
+ try {
+ createAVLocationFromText(text || "");
+ return false;
+ } catch {
+ return true;
+ }
}));
- if (requiresLocationEditor) {
+ if (invalidLocationInput) {
showMessage(window.siyuan.languages.locationPasteInEditor, 6000, "error");
return;
}
diff --git a/app/src/protyle/util/locationPaste.test.ts b/app/src/protyle/util/locationPaste.test.ts
new file mode 100644
index 0000000000..6c742cd0e2
--- /dev/null
+++ b/app/src/protyle/util/locationPaste.test.ts
@@ -0,0 +1,139 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {isAVReadonlyType} from "../render/av/capabilities";
+import {cloneAVCellValueSnapshot} from "../render/av/cellValue";
+import {createAVLocationFromText, createAVLocationReplacement} from "../render/av/locationValue";
+import {
+ compactAVCellOperations,
+ getAVPasteMatrixWidth,
+ getAVPasteValueForType,
+ inferAVPasteColumnType,
+} from "../render/av/paste";
+
+// 执行完整矩阵粘贴流程,校验位置文本预检先于列、行及单元格的修改。
+const source = readFileSync("src/protyle/util/insertHTML.ts", "utf8");
+const start = source.indexOf("const pasteAVMatrix =");
+const end = source.indexOf("const pasteAVMatrixWithSkeleton =", start);
+const compiled = transpileModule(source.slice(start, end) + "\nexports.pasteAVMatrix = pasteAVMatrix;", {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+}).outputText;
+
+const createHarness = (inferable = false) => {
+ const oldValue: IAVCellValue = {id: "value", type: "location", location: {
+ name: "Old", latitude: 20, longitude: 30, originalInput: "old input",
+ }};
+ const column = {id: "location", type: "location", name: "Location", width: "200px"} as IAVColumn;
+ const view = {columns: [column], rows: [{id: "row", cells: [{value: oldValue}]}]};
+ const warnings: string[] = [];
+ const pasted: Array<string | IAVCellValue> = [];
+ const transactions: Array<{doOperations: IOperation[], undoOperations: IOperation[]}> = [];
+ const cellElement = {dataset: {id: "value"}};
+ const rowElement = {querySelector: () => cellElement};
+ const body = {dataset: {groupId: ""}, querySelector: () => rowElement};
+ const blockElement = {
+ dataset: {avId: "av", nodeId: "block"},
+ querySelectorAll: () => [body], querySelector: (): null => null,
+ getAttribute: () => "view",
+ };
+ let measured = 0;
+ let restored = 0;
+ const methods: {pasteAVMatrix?: (options: unknown) => Promise<boolean>} = {};
+ runInNewContext(compiled, {
+ exports: methods,
+ Constants: {CUSTOM_SY_AV_VIEW: "custom-sy-av-view"},
+ getAVPasteMatrixWidth, getAVPasteValueForType, inferAVPasteColumnType,
+ compactAVCellOperations, cloneAVCellValueSnapshot,
+ createAVLocationFromText, createAVLocationReplacement, isAVReadonlyType,
+ fetchSyncPost: async () => ({code: 0, data: {view, inferableKeyIDs: inferable ? [column.id] : []}}),
+ showMessage: (message: string) => warnings.push(message),
+ window: {siyuan: {languages: {locationPasteInEditor: "Invalid WGS84 coordinates"}}},
+ getAVColumnTextMeasurer: () => measured++,
+ getAVColumnFitWidth: () => "200px",
+ genEmptyAVCell: (column: IAVColumn) => ({value: {type: column.type}}),
+ syncAVPasteRowCells: () => {},
+ updateCellsValue: async (_protyle: unknown, _block: unknown, value: string | IAVCellValue): Promise<{
+ doOperations: IOperation[], undoOperations: IOperation[],
+ }> => {
+ pasted.push(value);
+ const data: IAVCellValue = column.type === "location" ? {type: "location", location:
+ typeof value === "string" ? createAVLocationFromText(value) : value.type === "location" ?
+ createAVLocationReplacement(value.location) : createAVLocationFromText(value.text.content)} :
+ {type: "text", text: {content: value as string}};
+ return {doOperations: [{action: "updateAttrViewCell", id: "value", avID: "av",
+ keyID: "location", rowID: "row", data}], undoOperations: []};
+ },
+ restoreAVPasteCellPlaceholders: () => restored++,
+ removePlaceholderRows: () => {},
+ dayjs: () => ({format: () => "20261011000000"}),
+ transaction: (_protyle: unknown, doOperations: IOperation[], undoOperations: IOperation[]) =>
+ transactions.push({doOperations, undoOperations}),
+ });
+ return {
+ oldValue, column, warnings, pasted, transactions,
+ getMeasured: () => measured, getRestored: () => restored,
+ paste: (values: Array<Array<string | IAVCellValue>>, header?: string[]) => methods.pasteAVMatrix({
+ values, header, columns: [column], protyle: {}, blockElement, html: "",
+ start: {rowID: "row", colID: column.id, rowIndex: 0, groupID: ""},
+ }),
+ };
+};
+
+test("matrix paste accepts decimal and canonical location text and restores the original structured value on undo", async () => {
+ for (const value of ["31.20, 121.40", "Home; 0, 0 [WGS84]",
+ {type: "text", text: {content: "Office; Campus; -90, 180 [WGS84]"}} as IAVCellValue]) {
+ const harness = createHarness();
+ assert.equal(await harness.paste([[value]]), true);
+ assert.deepEqual(harness.warnings, []);
+ assert.equal(harness.transactions.length, 1);
+ const {doOperations, undoOperations} = harness.transactions[0];
+ const update = doOperations[0];
+ const undo = undoOperations[0];
+ if (update.action !== "updateAttrViewCell" || undo.action !== "updateAttrViewCell") {
+ assert.fail("expected location paste and undo operations");
+ }
+ const text = typeof value === "string" ? value : value.text.content;
+ assert.deepEqual(update.data.location, createAVLocationFromText(text));
+ assert.deepEqual(undo.data.location, createAVLocationReplacement(harness.oldValue.location));
+ assert.equal(harness.getRestored(), 1);
+ }
+});
+
+test("matrix paste rejects invalid location text before changing headers, adding rows or updating any cells", async () => {
+ for (const text of ["91, 0", "31,", "Home; 0, 0 [GCJ-02]", "0, 0 [WGS84] trailing"]) {
+ const harness = createHarness();
+ assert.equal(await harness.paste([["31, 121"], [text]], ["Renamed"]), undefined);
+ assert.deepEqual(harness.warnings, ["Invalid WGS84 coordinates"]);
+ assert.equal(harness.column.name, "Location");
+ assert.equal(harness.getMeasured(), 0);
+ assert.equal(harness.getRestored(), 0);
+ assert.deepEqual(harness.pasted, []);
+ assert.deepEqual(harness.transactions, []);
+ }
+});
+
+test("matrix paste keeps structured locations authoritative even when names resemble unsupported coordinates", async () => {
+ const harness = createHarness();
+ const location = {name: "91, 0 [GCJ-02]", latitude: 0, longitude: 0, originalInput: "legacy source"};
+ const value: IAVCellValue = {type: "location", location};
+ assert.equal(await harness.paste([[value]]), true);
+ assert.deepEqual(harness.warnings, []);
+ assert.deepEqual(harness.pasted, [value]);
+ const update = harness.transactions[0].doOperations[0];
+ if (update.action !== "updateAttrViewCell") {
+ assert.fail("expected structured location paste");
+ }
+ assert.deepEqual(update.data.location, location);
+ assert.notEqual(update.data.location, location);
+});
+
+test("matrix paste does not infer a location field from coordinate text when the column type is inferable", async () => {
+ const harness = createHarness(true);
+ assert.equal(await harness.paste([["91, 0"]], ["Text field"]), true);
+ assert.deepEqual(harness.warnings, []);
+ assert.equal(harness.column.type, "text");
+ assert.equal(harness.column.name, "Text field");
+ assert.deepEqual(harness.pasted, ["91, 0"]);
+});
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 9d69416f8b..e408026f35 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -385,21 +385,21 @@ const promiseTransaction = (options: {
if (operation.nextID && updateElements.length > 0) {
protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`).forEach(item => {
if (!isInEmbedBlock(item) && !item.contains(range.startContainer)) {
- item.before(...cloneMoveElements(primaryMoveElements));
+ item.before(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
}
});
} else if (operation.previousID && updateElements.length > 0) {
Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => {
if (!isInEmbedBlock(item) && !getNextBlockSibling(item)?.contains(range.startContainer)) {
- item.after(...cloneMoveElements(primaryMoveElements));
+ item.after(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
}
});
} else if (updateElements.length > 0) {
Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => {
if (!isInEmbedBlock(item) && !getFirstBlock(item).contains(range.startContainer)) {
- const cloneElements = cloneMoveElements(primaryMoveElements);
+ const cloneElements = cloneMoveElements(primaryMoveElements, pendingAVElements);
// 列表特殊处理
if (item.firstElementChild?.classList.contains("protyle-action")) {
item.firstElementChild.after(...cloneElements);
@@ -617,9 +617,18 @@ const promiseTransaction = (options: {
callback: (responseTransaction: {doOperations: IOperation[]}) => {
// 新增和更新的数据库载体必须在事务成功后渲染,确保内核已登记块及其笔记本归属。
responseTransaction.doOperations.forEach(operation => {
- if (operation.action === "insert" || operation.action === "update") {
- protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {
- pendingAVElements.add(item);
+ if (operation.action === "insert" || operation.action === "update" || operation.action === "move") {
+ const ids = operation.action === "move" ? [operation.id, ...(operation.blockIDs || [])] : [operation.id];
+ ids.forEach(id => {
+ protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${id}"]`).forEach(item => {
+ if (operation.action !== "move" || item.getAttribute("data-av-type") === "map") {
+ pendingAVElements.add(item);
+ } else {
+ item.querySelectorAll('[data-type="NodeAttributeView"][data-av-type="map"]').forEach(map => {
+ pendingAVElements.add(map);
+ });
+ }
+ });
});
}
});
@@ -1179,6 +1188,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
return;
}
if (operation.action === "move") {
+ const pendingAVElements = new Set<Element>();
if (operation.context?.ignoreProcess === "true") {
return;
}
@@ -1213,9 +1223,15 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
notebook: protyle.notebookId,
}, (response) => {
document.querySelectorAll(`.protyle-wysiwyg [data-node-id="${response.data.id}"]`).forEach(item => {
- if (item.getAttribute("data-protyle-id")) {
- item.outerHTML = getVisibleFoldHeadingHTML(response.data.dom);
- item.removeAttribute("data-protyle-id");
+ if (item.getAttribute("data-protyle-id") === protyle.element.getAttribute("data-id") &&
+ item.closest(".protyle-wysiwyg") === protyle.wysiwyg.element) {
+ const template = document.createElement("template");
+ template.innerHTML = getVisibleFoldHeadingHTML(response.data.dom);
+ const replacements = Array.from(template.content.children);
+ if (replacements.length) {
+ item.replaceWith(template.content);
+ replacements.forEach(replacement => { void avRender(replacement, protyle); });
+ }
}
});
});
@@ -1248,7 +1264,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
if (operation.nextID && updateElements.length > 0) {
protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.nextID}"]`).forEach(item => {
if (!isInEmbedBlock(item)) {
- item.before(...cloneMoveElements(primaryMoveElements));
+ item.before(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
}
});
@@ -1258,13 +1274,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
// 反链面板删除超级块中的最后一个段落块后撤销重做
const blockElement = hasTopClosestByAttribute(range.startContainer, "data-node-id", null);
if (blockElement) {
- blockElement.before(...cloneMoveElements(primaryMoveElements));
+ blockElement.before(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
}
} else {
previousElement.forEach(item => {
if (!isInEmbedBlock(item)) {
- item.after(...cloneMoveElements(primaryMoveElements));
+ item.after(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
}
});
@@ -1272,19 +1288,19 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
} else if (updateElements.length > 0) {
const parentElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`);
if (!protyle.options.backlinkData && operation.parentID === protyle.block.parentID && !protyle.block.showAll) {
- protyle.wysiwyg.element.prepend(...cloneMoveElements(primaryMoveElements));
+ protyle.wysiwyg.element.prepend(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
} else if (parentElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {
// 反链面板删除超级块中的段落块后撤销再重做 https://github.com/siyuan-note/siyuan/issues/14496#issuecomment-2771372486
const topBlockElement = hasTopClosestByAttribute(getSelection().getRangeAt(0).startContainer, "data-node-id", null);
if (topBlockElement) {
- topBlockElement.before(...cloneMoveElements(primaryMoveElements));
+ topBlockElement.before(...cloneMoveElements(primaryMoveElements, pendingAVElements));
hasFind = true;
}
} else {
parentElement.forEach(item => {
if (!isInEmbedBlock(item)) {
- const cloneElements = cloneMoveElements(primaryMoveElements);
+ const cloneElements = cloneMoveElements(primaryMoveElements, pendingAVElements);
// 列表特殊处理
if (item.firstElementChild?.classList.contains("protyle-action")) {
item.firstElementChild.after(...cloneElements);
@@ -1342,6 +1358,9 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
// 块移出后刷新源超级块的手柄(originSb 在元素被移除前捕获,仅含移出侧的超级块)
// https://github.com/siyuan-note/siyuan/issues/9521
refreshSbs(...originSbs);
+ pendingAVElements.forEach(item => {
+ if (item.isConnected) void avRender(item, protyle);
+ });
return;
}
if (operation.action === "insert") {
diff --git a/app/src/protyle/wysiwyg/transactionAV.test.ts b/app/src/protyle/wysiwyg/transactionAV.test.ts
index 480ab1408c..55d5a52e37 100644
--- a/app/src/protyle/wysiwyg/transactionAV.test.ts
+++ b/app/src/protyle/wysiwyg/transactionAV.test.ts
@@ -13,8 +13,8 @@ const compiled = transpileModule(readFileSync("src/protyle/wysiwyg/transaction.t
const fixture = () => {
const rendered: Element[] = [];
const carriers = [
- {isConnected: true, closest: (): Element => null, getAttribute: () => "NodeAttributeView"},
- {isConnected: true, closest: (): Element => null, getAttribute: () => "NodeAttributeView"},
+ {isConnected: true, closest: (): Element => null, getAttribute: (name: string) => name === "data-av-type" ? "map" : "NodeAttributeView"},
+ {isConnected: true, closest: (): Element => null, getAttribute: (name: string) => name === "data-av-type" ? "map" : "NodeAttributeView"},
];
let finish: (success: boolean) => void;
const exports: any = {};
@@ -69,7 +69,9 @@ const fixture = () => {
const insert = () => exports.transaction(protyle, [{
action: "insert", id: "carrier", previousID: "paragraph", data: '<div data-type="NodeAttributeView"></div>',
}]);
- return {protyle, carriers, rendered, insert, finish: (success: boolean) => finish(success)};
+ const move = () => exports.transaction(protyle, [{action: "move", id: "carrier", previousID: "paragraph"}], undefined,
+ {skipSync: true});
+ return {protyle, carriers, rendered, insert, move, finish: (success: boolean) => finish(success)};
};
test("本地模板数据库及其副本在插入事务成功后才渲染", async () => {
@@ -92,6 +94,18 @@ test("插入事务失败时不渲染尚未保存的数据库", async () => {
assert.equal(f.rendered.length, 0);
});
+test("moved database carriers rehydrate in the destination only after a successful transaction", async () => {
+ for (const success of [true, false]) {
+ const f = fixture();
+ f.move();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(f.rendered.length, 0);
+ f.finish(success);
+ await waitForPendingTransactions(f.protyle);
+ assert.deepEqual(f.rendered, success ? f.carriers : []);
+ }
+});
+
test("等待插入事务期间移除的数据库副本不再渲染", async () => {
const f = fixture();
f.insert();
diff --git a/app/src/protyle/wysiwyg/transactionMapMove.test.ts b/app/src/protyle/wysiwyg/transactionMapMove.test.ts
new file mode 100644
index 0000000000..1c5c047a92
--- /dev/null
+++ b/app/src/protyle/wysiwyg/transactionMapMove.test.ts
@@ -0,0 +1,259 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {DOMElement, DOMFixture} from "../render/av/map/testDOM";
+import {cloneMoveElements, getVisibleMoveElements} from "./transactionMove";
+import {getMoveAffectedEmbedElements} from "./transactionEmbed";
+
+const compiled = transpileModule(readFileSync("src/protyle/wysiwyg/transaction.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const wrappers = new WeakMap<DOMFixture, WeakMap<object, MoveElement>>();
+
+class MoveDocument extends DOMFixture {
+ wrap(node: object): MoveElement {
+ let elements = wrappers.get(this);
+ if (!elements) {
+ elements = new WeakMap();
+ wrappers.set(this, elements);
+ }
+ if (!elements.has(node)) elements.set(node, new MoveElement(node, this));
+ return elements.get(node);
+ }
+
+ querySelectorAll(selector: string) { return this.documentElement.querySelectorAll(selector); }
+}
+
+// 仅补齐移动回放需要的克隆、兄弟插入、模板和后代选择器,不修改共享地图 DOM 测试夹具。
+class MoveElement extends DOMElement {
+ get content() {
+ assert.equal(this.tagName, "TEMPLATE");
+ this.node.content ||= {nodeName: "#document-fragment", attrs: [], childNodes: []};
+ return this.ownerDocument.wrap(this.node.content);
+ }
+
+ get innerHTML(): string { return this.node.tagName === "template" ? this.content.innerHTML : super.innerHTML; }
+ set innerHTML(value: string) {
+ if (this.node.tagName === "template") this.content.innerHTML = value;
+ else super.innerHTML = value;
+ }
+
+ cloneNode(deep = false) {
+ const clone = this.ownerDocument.createElement(this.node.tagName);
+ this.node.attrs.forEach(({name, value}: {name: string; value: string}) => clone.setAttribute(name, value));
+ if (deep) clone.innerHTML = this.innerHTML;
+ return clone;
+ }
+
+ before(...children: DOMElement[]) { children.forEach(child => super.before(child)); }
+
+ replaceWith(child: DOMElement) {
+ if (child.node.nodeName === "#document-fragment") {
+ this.before(...child.node.childNodes.map((node: object) => this.ownerDocument.wrap(node)));
+ this.remove();
+ } else {
+ super.replaceWith(child);
+ }
+ }
+
+ after(...children: DOMElement[]) {
+ assert.ok(this.parentElement);
+ const next = this.nextElementSibling;
+ children.forEach(child => next ? next.before(child) : this.parentElement.append(child));
+ }
+
+ prepend(...children: DOMElement[]) {
+ [...children].reverse().forEach(child => this.firstElementChild ? this.firstElementChild.before(child) : this.append(child));
+ }
+
+ querySelectorAll(selector: string): DOMElement[] {
+ if (!selector.startsWith(":scope > ") && selector.includes(" ")) {
+ const parts = selector.split(" ");
+ assert.equal(parts.length, 2, `Unsupported move fixture selector: ${selector}`);
+ return super.querySelectorAll(parts[1]).filter(item => item.parentElement?.closest(parts[0]));
+ }
+ return super.querySelectorAll(selector);
+ }
+}
+
+const mapHTML = (id: string, runtime = true) => `<div class="av" data-node-id="${id}" data-type="NodeAttributeView" data-av-type="map"${runtime ? ' data-render="true"' : ""}>
+<div class="av__container">${runtime ? '<div class="av__map"><webview partition="siyuan-map-old"></webview></div>' : ""}<div class="av__scroll"></div></div></div>`;
+
+const fixture = () => {
+ const document = new MoveDocument();
+ const rendered: Array<{element: DOMElement; protyle: IProtyle}> = [];
+ const requests: Array<{id: string; notebook: string; reply: (response: unknown) => void}> = [];
+ const models: Array<{editor: {protyle: IProtyle}}> = [];
+ const exports: typeof import("./transaction") = {} as typeof import("./transaction");
+ const dependencies = {
+ cloneMoveElements,
+ getVisibleMoveElements,
+ getMoveAffectedEmbedElements,
+ Constants: {},
+ invalidateTrackedRangesByOperations() {},
+ invalidateViewFoldRequests() {},
+ handleViewFoldSourceOperation: () => false,
+ isInEmbedBlock: () => false,
+ getAllModels: () => ({editor: models}),
+ normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,
+ refreshSbResize() {},
+ applyViewFoldStates() {},
+ queueHeadingNumberRefresh() {},
+ refreshHeadingFoldIndicators() {},
+ shouldReloadForHeadingBatch: () => false,
+ avRender: (element: DOMElement, protyle: IProtyle) => {
+ assert.equal(element.isConnected, true, "Hydration must follow insertion into the document");
+ assert.equal(element.closest(".protyle-wysiwyg"), protyle.wysiwyg.element);
+ rendered.push({element, protyle});
+ },
+ fetchPost: (url: string, data: {id: string; notebook: string}, reply: (response: unknown) => void) => {
+ assert.equal(url, "/api/block/getBlockDOM");
+ requests.push({...data, reply});
+ },
+ };
+ runInNewContext(compiled, {
+ exports, document, require: () => dependencies,
+ window: {siyuan: {blockPanels: []}},
+ getSelection: () => ({rangeCount: 0}),
+ });
+ const editor = (id: string, html: string) => {
+ const element = document.createElement("div");
+ element.setAttribute("data-id", id);
+ const wysiwyg = document.createElement("div");
+ wysiwyg.className = "protyle-wysiwyg";
+ wysiwyg.innerHTML = html;
+ element.append(wysiwyg);
+ document.body.append(element);
+ const protyle = {element, wysiwyg: {element: wysiwyg}, notebookId: "notebook-" + id,
+ block: {rootID: "document-" + id, showAll: true}, options: {}} as unknown as IProtyle;
+ return {protyle, root: wysiwyg};
+ };
+ const replay = (protyle: IProtyle, operation: Partial<IOperation>) =>
+ exports.onTransaction(protyle, [{action: "move", ...operation} as IOperation], false);
+ const reply = (index: number, html = mapHTML("moved", false)) => requests[index].reply({
+ code: 0, data: {id: requests[index].id, dom: html},
+ });
+ return {document, editor, replay, rendered, requests, reply, models};
+};
+
+for (const anchor of ["nextID", "previousID", "parentID"] as const) {
+ test(`move replay hydrates a cleaned root map after ${anchor} placement`, () => {
+ const f = fixture();
+ const {protyle, root} = f.editor("destination", '<div data-node-id="target"></div>' + mapHTML("moved") + mapHTML("untouched"));
+ const original = root.querySelector('[data-node-id="moved"]');
+ const originalRuntime = original.querySelector(".av__map");
+ const untouched = root.querySelector('[data-node-id="untouched"]');
+ f.replay(protyle, {id: "moved", [anchor]: "target"});
+ const moved = root.querySelector('[data-node-id="moved"]');
+ assert.notEqual(moved, original);
+ assert.equal(original.isConnected, false);
+ assert.equal(original.querySelector(".av__map"), originalRuntime);
+ assert.equal(moved.querySelector(".av__map"), null);
+ assert.equal(moved.hasAttribute("data-render"), false);
+ assert.deepEqual(f.rendered, [{element: moved, protyle}]);
+ assert.equal(untouched.hasAttribute("data-render"), true);
+ assert.ok(untouched.querySelector(".av__map"));
+ const target = root.querySelector('[data-node-id="target"]');
+ if (anchor === "nextID") assert.equal(moved.nextElementSibling, target);
+ if (anchor === "previousID") assert.equal(moved.previousElementSibling, target);
+ if (anchor === "parentID") assert.equal(moved.parentElement, target);
+ assert.equal(f.requests.length, 0);
+ });
+}
+
+test("move replay rehydrates maps nested in a moved container and a moved heading group", () => {
+ const f = fixture();
+ const {protyle, root} = f.editor("destination", '<div data-node-id="target"></div>' +
+ '<div data-node-id="heading" data-type="NodeHeading"></div>' +
+ '<div data-node-id="container" data-type="NodeSuperBlock">' + mapHTML("nested") + "</div>" + mapHTML("sibling"));
+ f.replay(protyle, {id: "heading", blockIDs: ["container", "sibling"], nextID: "target"});
+ assert.deepEqual(root.children.map(item => item.dataset.nodeId), ["heading", "container", "sibling", "target"]);
+ const nested = root.querySelector('[data-node-id="nested"]');
+ const sibling = root.querySelector('[data-node-id="sibling"]');
+ assert.deepEqual(f.rendered, [{element: nested, protyle}, {element: sibling, protyle}]);
+ assert.equal(nested.hasAttribute("data-render"), false);
+ assert.equal(sibling.hasAttribute("data-render"), false);
+ assert.equal(root.querySelector("webview"), null);
+});
+
+test("replay using another editor's map copy preserves that source and hydrates the destination", () => {
+ const f = fixture();
+ const source = f.editor("source", mapHTML("moved"));
+ const destination = f.editor("destination", '<div data-node-id="target"></div>');
+ const original = source.root.firstElementChild;
+ f.models.push({editor: {protyle: source.protyle}});
+ f.replay(destination.protyle, {id: "moved", previousID: "target"});
+ const moved = destination.root.querySelector('[data-node-id="moved"]');
+ assert.ok(original.isConnected);
+ assert.ok(original.querySelector("webview"));
+ assert.equal(original.getAttribute("data-render"), "true");
+ assert.equal(moved.querySelector("webview"), null);
+ assert.deepEqual(f.rendered, [{element: moved, protyle: destination.protyle}]);
+ assert.equal(f.requests.length, 0);
+});
+
+test("async fallback hydrates concurrent same-block placeholders only in their requesting editor", () => {
+ const f = fixture();
+ const first = f.editor("first", '<div data-node-id="target"></div>');
+ const second = f.editor("second", '<div data-node-id="target"></div>');
+ for (const editor of [first, second]) f.replay(editor.protyle, {id: "moved", nextID: "target"});
+ const firstPlaceholder = first.root.querySelector('[data-node-id="moved"]');
+ const secondPlaceholder = second.root.querySelector('[data-node-id="moved"]');
+ assert.equal(firstPlaceholder.getAttribute("data-protyle-id"), "first");
+ assert.equal(secondPlaceholder.getAttribute("data-protyle-id"), "second");
+ assert.deepEqual(f.requests.map(request => request.notebook), ["notebook-first", "notebook-second"]);
+ assert.equal(f.rendered.length, 0);
+ f.reply(1);
+ assert.equal(first.root.querySelector('[data-node-id="moved"]'), firstPlaceholder);
+ assert.equal(secondPlaceholder.isConnected, false);
+ assert.deepEqual(f.rendered, [{element: second.root.querySelector('[data-node-id="moved"]'), protyle: second.protyle}]);
+ f.reply(0);
+ assert.equal(firstPlaceholder.isConnected, false);
+ assert.deepEqual(f.rendered.map(item => item.protyle), [second.protyle, first.protyle]);
+ assert.equal(first.root.querySelector('[data-protyle-id="first"]'), null);
+ assert.equal(second.root.querySelector('[data-protyle-id="second"]'), null);
+});
+
+test("fallback does not hydrate a matching owner ID after its placeholder moves to another editor", () => {
+ const f = fixture();
+ const first = f.editor("first", '<div data-node-id="target"></div>');
+ const second = f.editor("second", "");
+ f.replay(first.protyle, {id: "moved", nextID: "target"});
+ const placeholder = first.root.querySelector('[data-node-id="moved"]');
+ second.root.append(placeholder);
+ f.reply(0);
+ assert.equal(second.root.firstElementChild, placeholder);
+ assert.equal(placeholder.getAttribute("data-protyle-id"), "first");
+ assert.equal(f.rendered.length, 0);
+});
+
+test("fallback preserves every returned sibling and hydrates a trailing map after fragment insertion", () => {
+ const f = fixture();
+ const {protyle, root} = f.editor("destination", '<div data-node-id="target"></div>');
+ f.replay(protyle, {id: "moved", nextID: "target"});
+ f.reply(0, '<div data-node-id="moved" data-type="NodeHeading">Heading</div>\n' +
+ '<div data-node-id="paragraph">Paragraph</div>\n' + mapHTML("trailing-map", false));
+ assert.deepEqual(root.children.map(item => item.dataset.nodeId), ["moved", "paragraph", "trailing-map", "target"]);
+ assert.deepEqual(f.rendered.map(item => item.element.dataset.nodeId), ["moved", "paragraph", "trailing-map"]);
+ assert.ok(f.rendered.every(item => item.protyle === protyle));
+ assert.equal(root.querySelector("template"), null);
+ assert.equal(root.querySelector('[data-node-id="paragraph"]').textContent, "Paragraph");
+ assert.equal(root.querySelector('[data-protyle-id="destination"]'), null);
+});
+
+test("fallback ignores removed placeholders and mismatched owner IDs in the original editor", () => {
+ for (const change of ["removed", "different-owner"]) {
+ const f = fixture();
+ const {protyle, root} = f.editor("destination", '<div data-node-id="target"></div>');
+ f.replay(protyle, {id: "moved", nextID: "target"});
+ const placeholder = root.querySelector('[data-node-id="moved"]');
+ if (change === "removed") placeholder.remove();
+ else placeholder.setAttribute("data-protyle-id", "other");
+ f.reply(0);
+ assert.equal(root.querySelector(".av"), null);
+ assert.equal(f.rendered.length, 0);
+ }
+});
diff --git a/app/src/protyle/wysiwyg/transactionMove.test.ts b/app/src/protyle/wysiwyg/transactionMove.test.ts
index 8d71b02044..fa51ec62bb 100644
--- a/app/src/protyle/wysiwyg/transactionMove.test.ts
+++ b/app/src/protyle/wysiwyg/transactionMove.test.ts
@@ -1,6 +1,7 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {getVisibleMoveElements} from "./transactionMove";
+import {cloneMoveElements, getVisibleMoveElements} from "./transactionMove";
+import {DOMElement, DOMFixture} from "../render/av/map/testDOM";
class TestMoveElement {
nextElementSibling?: TestMoveElement;
@@ -57,3 +58,33 @@ describe("getVisibleMoveElements", () => {
assert.deepEqual(getVisibleMoveElements(asElement(heading), []), [heading]);
});
});
+
+it("move clones rebuild only map hosts and preserve database configuration and other layouts", () => {
+ const document = new DOMFixture();
+ const create = (html: string) => {
+ const wrapper = document.createElement("div");
+ wrapper.innerHTML = html;
+ return wrapper.firstElementChild;
+ };
+ const mapHTML = '<div data-type="NodeAttributeView" data-node-id="carrier" data-av-id="database" data-av-type="map" custom-sy-av-view="view" data-render="true"><div class="av__container"><div class="av__map"><webview partition="temporary"></webview></div><div class="av__scroll"></div></div></div>';
+ const tableHTML = '<div data-type="NodeAttributeView" data-av-type="table" data-render="true"><div class="av__container">table</div></div>';
+ for (const html of [mapHTML, `<div data-type="NodeSuperBlock">${mapHTML}${tableHTML}</div>`]) {
+ const source = create(html);
+ Object.assign(source, {cloneNode: () => create(html)});
+ const pending = new Set<Element>();
+ const [clone] = cloneMoveElements([source as unknown as Element], pending);
+ assert.equal(pending.size, 1);
+ const map = [...pending][0] as unknown as DOMElement;
+ assert.equal(map.getAttribute("data-render"), null);
+ assert.equal(map.querySelector(".av__map"), null);
+ assert.equal(map.getAttribute("custom-sy-av-view"), "view");
+ assert.equal(map.getAttribute("data-av-id"), "database");
+ assert.ok(map.querySelector(".av__scroll"));
+ assert.ok(source.querySelector("webview"));
+ const table = clone.querySelector('[data-av-type="table"]');
+ if (table) {
+ assert.equal(table.getAttribute("data-render"), "true");
+ assert.equal(table.textContent, "table");
+ }
+ }
+});
diff --git a/app/src/protyle/wysiwyg/transactionMove.ts b/app/src/protyle/wysiwyg/transactionMove.ts
index af849829c6..4f9abb02f3 100644
--- a/app/src/protyle/wysiwyg/transactionMove.ts
+++ b/app/src/protyle/wysiwyg/transactionMove.ts
@@ -33,5 +33,16 @@ export const getVisibleMoveElements = (sourceElement: Element, blockIDs?: string
return elements;
};
-export const cloneMoveElements = (elements: Element[]) =>
- elements.map(item => item.cloneNode(true) as Element);
+export const cloneMoveElements = (elements: Element[], pendingMapElements?: Set<Element>) =>
+ elements.map(item => {
+ const clone = item.cloneNode(true) as Element;
+ const maps = Array.from(clone.querySelectorAll('[data-type="NodeAttributeView"][data-av-type="map"]'));
+ if (clone.matches('[data-type="NodeAttributeView"][data-av-type="map"]')) maps.unshift(clone);
+ maps.forEach(map => {
+ // 宿主连接和临时分区不能随块 DOM 复制,插入完成后重新创建地图。
+ map.querySelector(":scope > .av__container > .av__map")?.remove();
+ map.removeAttribute("data-render");
+ pendingMapElements?.add(map);
+ });
+ return clone;
+ });