Skip to content

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

:recycle: Simplify database map lifecycle and strengthen boundary tests https://github.com/siyuan-note/siyuan/issues/20129

Danielf3f14861ab51
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index b61c1fe03e..38c398d434 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "محرّك التعرّف",
"configGroupSignInTokens": "تسجيل الدخول والرموز",
"searchControlUnavailable": "هذا الخيار غير متاح لطريقة البحث الحالية",
- "coordinateOrder": "ترتيب الإحداثيات",
"mapAuthenticationBypass": "لا تتوفر الخرائط أثناء تفعيل تجاوز المصادقة. تظل السجلات متاحة",
"mapView": "الخريطة",
"mapLocationField": "حقل الموقع",
@@ -27,8 +26,6 @@
"locationName": "الاسم (اختياري)",
"latitude": "خط العرض",
"longitude": "خط الطول",
- "pasteCoordinates": "لصق الإحداثيات",
- "coordinateOrderTip": "تُقرأ الإحداثيات بالترتيب المحدد؛ الترتيب الافتراضي هو خط الطول ثم خط العرض",
"invalidCoordinates": "أدخل خط عرض محدودًا من -90 إلى 90 وخط طول من -180 إلى 180، أو اترك كليهما فارغًا",
"pageScrollUp": "الشاشة السابقة",
"pageScrollDown": "الشاشة التالية",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index cd84c97e58..73cc8527e7 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Erkennungs-Engine",
"configGroupSignInTokens": "Anmeldung und Token",
"searchControlUnavailable": "Für die aktuelle Suchmethode nicht verfügbar",
- "coordinateOrder": "Koordinatenreihenfolge",
"mapAuthenticationBypass": "Karten sind bei aktivierter Umgehung der Authentifizierung nicht verfügbar. Datensätze bleiben verfügbar",
"mapView": "Karte",
"mapLocationField": "Standortfeld",
@@ -27,8 +26,6 @@
"locationName": "Name (optional)",
"latitude": "Breitengrad",
"longitude": "Längengrad",
- "pasteCoordinates": "Koordinaten einfügen",
- "coordinateOrderTip": "Koordinaten werden in der ausgewählten Reihenfolge gelesen; standardmäßig gilt Längengrad, Breitengrad",
"invalidCoordinates": "Endlichen Breitengrad von -90 bis 90 und Längengrad von -180 bis 180 eingeben oder beide leer lassen",
"pageScrollUp": "Vorheriger Bildschirm",
"pageScrollDown": "Nächster Bildschirm",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 3c33e1daac..58f0e42c53 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Recognition engine",
"configGroupSignInTokens": "Login and tokens",
"searchControlUnavailable": "Unavailable for the current search method",
- "coordinateOrder": "Coordinate order",
"mapAuthenticationBypass": "Maps are unavailable while authentication bypass is enabled. Records remain available",
"mapView": "Map",
"mapLocationField": "Location field",
@@ -27,8 +26,6 @@
"locationName": "Name (optional)",
"latitude": "Latitude",
"longitude": "Longitude",
- "pasteCoordinates": "Paste coordinates",
- "coordinateOrderTip": "Coordinates are read in the selected order; longitude, latitude is the default",
"invalidCoordinates": "Enter a finite latitude from -90 to 90 and longitude from -180 to 180, or leave both empty",
"pageScrollUp": "Previous screen",
"pageScrollDown": "Next screen",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 7fba37b09e..0f432ff237 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Motor de reconocimiento",
"configGroupSignInTokens": "Inicio de sesión y tokens",
"searchControlUnavailable": "No disponible para el método de búsqueda actual",
- "coordinateOrder": "Orden de las coordenadas",
"mapAuthenticationBypass": "Los mapas no están disponibles mientras esté activada la omisión de autenticación. Los registros siguen disponibles",
"mapView": "Mapa",
"mapLocationField": "Campo de ubicación",
@@ -27,8 +26,6 @@
"locationName": "Nombre (opcional)",
"latitude": "Latitud",
"longitude": "Longitud",
- "pasteCoordinates": "Pegar coordenadas",
- "coordinateOrderTip": "Las coordenadas se leen en el orden seleccionado; el predeterminado es longitud, latitud",
"invalidCoordinates": "Introduce una latitud finita entre -90 y 90 y una longitud entre -180 y 180, o deja ambas vacías",
"pageScrollUp": "Pantalla anterior",
"pageScrollDown": "Pantalla siguiente",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 84027ffbef..a077a6eb4d 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Moteur de reconnaissance",
"configGroupSignInTokens": "Connexion et jetons",
"searchControlUnavailable": "Indisponible pour la méthode de recherche actuelle",
- "coordinateOrder": "Ordre des coordonnées",
"mapAuthenticationBypass": "Les cartes sont indisponibles lorsque le contournement de l’authentification est activé. Les enregistrements restent disponibles",
"mapView": "Carte",
"mapLocationField": "Champ de localisation",
@@ -27,8 +26,6 @@
"locationName": "Nom (facultatif)",
"latitude": "Latitude",
"longitude": "Longitude",
- "pasteCoordinates": "Coller les coordonnées",
- "coordinateOrderTip": "Les coordonnées sont lues dans l’ordre sélectionné ; longitude, latitude est l’ordre par défaut",
"invalidCoordinates": "Saisissez une latitude finie entre -90 et 90 et une longitude entre -180 et 180, ou laissez les deux vides",
"pageScrollUp": "Écran précédent",
"pageScrollDown": "Écran suivant",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 62433e8212..a12e6ade1d 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "מנוע זיהוי",
"configGroupSignInTokens": "כניסה ואסימונים",
"searchControlUnavailable": "האפשרות אינה זמינה בשיטת החיפוש הנוכחית",
- "coordinateOrder": "סדר הקואורדינטות",
"mapAuthenticationBypass": "מפות אינן זמינות כאשר עקיפת האימות מופעלת. הרשומות נשארות זמינות",
"mapView": "מפה",
"mapLocationField": "שדה מיקום",
@@ -27,8 +26,6 @@
"locationName": "שם (רשות)",
"latitude": "קו רוחב",
"longitude": "קו אורך",
- "pasteCoordinates": "הדבקת קואורדינטות",
- "coordinateOrderTip": "הקואורדינטות נקראות לפי הסדר שנבחר; סדר ברירת המחדל הוא קו אורך, קו רוחב",
"invalidCoordinates": "יש להזין קו רוחב סופי בין ‎-90 ל-90 וקו אורך בין ‎-180 ל-180, או להשאיר את שניהם ריקים",
"pageScrollUp": "המסך הקודם",
"pageScrollDown": "המסך הבא",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d13f431da6..40c02a1872 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "पहचान इंजन",
"configGroupSignInTokens": "लॉगिन और टोकन",
"searchControlUnavailable": "वर्तमान खोज विधि में यह विकल्प उपलब्ध नहीं है",
- "coordinateOrder": "निर्देशांक क्रम",
"mapAuthenticationBypass": "प्रमाणीकरण बायपास सक्षम होने पर मानचित्र उपलब्ध नहीं हैं। रिकॉर्ड उपलब्ध रहते हैं",
"mapView": "मानचित्र",
"mapLocationField": "स्थान फ़ील्ड",
@@ -27,8 +26,6 @@
"locationName": "नाम (वैकल्पिक)",
"latitude": "अक्षांश",
"longitude": "देशांतर",
- "pasteCoordinates": "निर्देशांक पेस्ट करें",
- "coordinateOrderTip": "निर्देशांक चुने गए क्रम में पढ़े जाते हैं; डिफ़ॉल्ट क्रम देशांतर, अक्षांश है",
"invalidCoordinates": "-90 से 90 तक सीमित अक्षांश और -180 से 180 तक सीमित देशांतर दर्ज करें, या दोनों खाली छोड़ें",
"pageScrollUp": "पिछली स्क्रीन",
"pageScrollDown": "अगली स्क्रीन",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index a614037604..aeb3cf5f7c 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Mesin pengenalan",
"configGroupSignInTokens": "Login dan token",
"searchControlUnavailable": "Tidak tersedia untuk metode pencarian saat ini",
- "coordinateOrder": "Urutan koordinat",
"mapAuthenticationBypass": "Peta tidak tersedia saat fitur melewati autentikasi diaktifkan. Rekaman tetap tersedia",
"mapView": "Peta",
"mapLocationField": "Kolom lokasi",
@@ -27,8 +26,6 @@
"locationName": "Nama (opsional)",
"latitude": "Lintang",
"longitude": "Bujur",
- "pasteCoordinates": "Tempel koordinat",
- "coordinateOrderTip": "Koordinat dibaca sesuai urutan yang dipilih; urutan bawaan adalah bujur, lintang",
"invalidCoordinates": "Masukkan lintang terhingga dari -90 hingga 90 dan bujur dari -180 hingga 180, atau kosongkan keduanya",
"pageScrollUp": "Layar sebelumnya",
"pageScrollDown": "Layar berikutnya",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 6f5557efa1..6549073b16 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Motore di riconoscimento",
"configGroupSignInTokens": "Accesso e token",
"searchControlUnavailable": "Non disponibile per il metodo di ricerca corrente",
- "coordinateOrder": "Ordine delle coordinate",
"mapAuthenticationBypass": "Le mappe non sono disponibili quando è attivo il bypass dell’autenticazione. I record restano disponibili",
"mapView": "Mappa",
"mapLocationField": "Campo posizione",
@@ -27,8 +26,6 @@
"locationName": "Nome (facoltativo)",
"latitude": "Latitudine",
"longitude": "Longitudine",
- "pasteCoordinates": "Incolla coordinate",
- "coordinateOrderTip": "Le coordinate vengono lette nell’ordine selezionato; quello predefinito è longitudine, latitudine",
"invalidCoordinates": "Inserisci una latitudine finita da -90 a 90 e una longitudine da -180 a 180, oppure lascia entrambe vuote",
"pageScrollUp": "Schermata precedente",
"pageScrollDown": "Schermata successiva",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 0a70c1bfdc..eb2fce581a 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "認識エンジン",
"configGroupSignInTokens": "ログインとトークン",
"searchControlUnavailable": "現在の検索方法ではこの項目を利用できません",
- "coordinateOrder": "座標の順序",
"mapAuthenticationBypass": "認証のバイパスが有効な間は地図を利用できません。レコードは引き続き利用できます",
"mapView": "地図",
"mapLocationField": "位置フィールド",
@@ -27,8 +26,6 @@
"locationName": "名前(任意)",
"latitude": "緯度",
"longitude": "経度",
- "pasteCoordinates": "座標を貼り付け",
- "coordinateOrderTip": "座標は選択した順序で読み取られます。既定の順序は経度、緯度です",
"invalidCoordinates": "緯度は -90 から 90、経度は -180 から 180 の有限値を入力するか、両方を空欄にしてください",
"pageScrollUp": "前の画面",
"pageScrollDown": "次の画面",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 8a5c6e06d2..d9dff9a1a3 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "인식 엔진",
"configGroupSignInTokens": "로그인과 토큰",
"searchControlUnavailable": "현재 검색 방식에서는 이 옵션을 사용할 수 없습니다",
- "coordinateOrder": "좌표 순서",
"mapAuthenticationBypass": "인증 우회가 활성화된 동안에는 지도를 사용할 수 없습니다. 레코드는 계속 사용할 수 있습니다",
"mapView": "지도",
"mapLocationField": "위치 필드",
@@ -27,8 +26,6 @@
"locationName": "이름(선택 사항)",
"latitude": "위도",
"longitude": "경도",
- "pasteCoordinates": "좌표 붙여넣기",
- "coordinateOrderTip": "좌표는 선택한 순서로 읽으며 기본 순서는 경도, 위도입니다",
"invalidCoordinates": "위도는 -90~90, 경도는 -180~180 사이의 유한한 값을 입력하거나 둘 다 비워 두세요",
"pageScrollUp": "이전 화면",
"pageScrollDown": "다음 화면",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 459d4822ed..cda25b9c5d 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Herkenning-engine",
"configGroupSignInTokens": "Inloggen en tokens",
"searchControlUnavailable": "Niet beschikbaar voor de huidige zoekmethode",
- "coordinateOrder": "Coördinatenvolgorde",
"mapAuthenticationBypass": "Kaarten zijn niet beschikbaar wanneer het omzeilen van authenticatie is ingeschakeld. Records blijven beschikbaar",
"mapView": "Kaart",
"mapLocationField": "Locatieveld",
@@ -27,8 +26,6 @@
"locationName": "Naam (optioneel)",
"latitude": "Breedtegraad",
"longitude": "Lengtegraad",
- "pasteCoordinates": "Coördinaten plakken",
- "coordinateOrderTip": "Coördinaten worden in de gekozen volgorde gelezen; de standaardvolgorde is lengtegraad, breedtegraad",
"invalidCoordinates": "Voer een eindige breedtegraad van -90 tot 90 en lengtegraad van -180 tot 180 in, of laat beide leeg",
"pageScrollUp": "Vorig scherm",
"pageScrollDown": "Volgend scherm",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index f1dd0b783e..dd65bd1919 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Silnik rozpoznawania",
"configGroupSignInTokens": "Logowanie i tokeny",
"searchControlUnavailable": "Niedostępne dla bieżącej metody wyszukiwania",
- "coordinateOrder": "Kolejność współrzędnych",
"mapAuthenticationBypass": "Mapy są niedostępne, gdy pomijanie uwierzytelniania jest włączone. Rekordy pozostają dostępne",
"mapView": "Mapa",
"mapLocationField": "Pole lokalizacji",
@@ -27,8 +26,6 @@
"locationName": "Nazwa (opcjonalna)",
"latitude": "Szerokość geograficzna",
"longitude": "Długość geograficzna",
- "pasteCoordinates": "Wklej współrzędne",
- "coordinateOrderTip": "Współrzędne są odczytywane w wybranej kolejności; domyślna to długość, szerokość geograficzna",
"invalidCoordinates": "Podaj skończoną szerokość od -90 do 90 i długość od -180 do 180 lub pozostaw oba pola puste",
"pageScrollUp": "Poprzedni ekran",
"pageScrollDown": "Następny ekran",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 70b7ede6c9..41cc20ade0 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Mecanismo de reconhecimento",
"configGroupSignInTokens": "Login e tokens",
"searchControlUnavailable": "Indisponível para o método de pesquisa atual",
- "coordinateOrder": "Ordem das coordenadas",
"mapAuthenticationBypass": "Os mapas ficam indisponíveis enquanto a opção de ignorar a autenticação está ativada. Os registros continuam disponíveis",
"mapView": "Mapa",
"mapLocationField": "Campo de localização",
@@ -27,8 +26,6 @@
"locationName": "Nome (opcional)",
"latitude": "Latitude",
"longitude": "Longitude",
- "pasteCoordinates": "Colar coordenadas",
- "coordinateOrderTip": "As coordenadas são lidas na ordem selecionada; longitude, latitude é a ordem padrão",
"invalidCoordinates": "Insira uma latitude finita de -90 a 90 e uma longitude de -180 a 180, ou deixe ambas vazias",
"pageScrollUp": "Tela anterior",
"pageScrollDown": "Próxima tela",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 352e3ecf76..6d4b54051d 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Движок распознавания",
"configGroupSignInTokens": "Вход и токены",
"searchControlUnavailable": "Недоступно для текущего метода поиска",
- "coordinateOrder": "Порядок координат",
"mapAuthenticationBypass": "Карты недоступны, пока включён обход аутентификации. Записи остаются доступными",
"mapView": "Карта",
"mapLocationField": "Поле местоположения",
@@ -27,8 +26,6 @@
"locationName": "Название (необязательно)",
"latitude": "Широта",
"longitude": "Долгота",
- "pasteCoordinates": "Вставить координаты",
- "coordinateOrderTip": "Координаты считываются в выбранном порядке; по умолчанию — долгота, широта",
"invalidCoordinates": "Введите конечную широту от -90 до 90 и долготу от -180 до 180 или оставьте оба поля пустыми",
"pageScrollUp": "Предыдущий экран",
"pageScrollDown": "Следующий экран",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 613ff819a7..641bc552e5 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Mechanizmus rozpoznávania",
"configGroupSignInTokens": "Prihlásenie a tokeny",
"searchControlUnavailable": "Nie je dostupné pre aktuálnu metódu vyhľadávania",
- "coordinateOrder": "Poradie súradníc",
"mapAuthenticationBypass": "Mapy nie sú dostupné, keď je zapnuté obchádzanie overenia totožnosti. Záznamy zostávajú dostupné",
"mapView": "Mapa",
"mapLocationField": "Pole polohy",
@@ -27,8 +26,6 @@
"locationName": "Názov (voliteľný)",
"latitude": "Zemepisná šírka",
"longitude": "Zemepisná dĺžka",
- "pasteCoordinates": "Vložiť súradnice",
- "coordinateOrderTip": "Súradnice sa čítajú vo vybranom poradí; predvolené poradie je dĺžka, šírka",
"invalidCoordinates": "Zadajte konečnú šírku od -90 do 90 a dĺžku od -180 do 180 alebo nechajte obe polia prázdne",
"pageScrollUp": "Predchádzajúca obrazovka",
"pageScrollDown": "Nasledujúca obrazovka",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index efc5ae4af6..ed3bcf5f35 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Mehanizam prepoznavanja",
"configGroupSignInTokens": "Prijava i tokeni",
"searchControlUnavailable": "Није доступно за тренутни начин претраге",
- "coordinateOrder": "Редослед координата",
"mapAuthenticationBypass": "Мапе нису доступне док је укључено заобилажење аутентификације. Записи остају доступни",
"mapView": "Мапа",
"mapLocationField": "Поље локације",
@@ -27,8 +26,6 @@
"locationName": "Назив (опционо)",
"latitude": "Географска ширина",
"longitude": "Географска дужина",
- "pasteCoordinates": "Налепи координате",
- "coordinateOrderTip": "Координате се читају изабраним редоследом; подразумевани редослед је дужина, ширина",
"invalidCoordinates": "Унесите коначну ширину од -90 до 90 и дужину од -180 до 180 или оставите оба поља празна",
"pageScrollUp": "Претходни екран",
"pageScrollDown": "Следећи екран",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 51c7d38928..a0f2449745 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "กลไกการรู้จำ",
"configGroupSignInTokens": "เข้าสู่ระบบและโทเค็น",
"searchControlUnavailable": "ตัวเลือกนี้ไม่พร้อมใช้งานสำหรับวิธีค้นหาปัจจุบัน",
- "coordinateOrder": "ลำดับพิกัด",
"mapAuthenticationBypass": "แผนที่ไม่พร้อมใช้งานขณะเปิดใช้การข้ามการยืนยันตัวตน ระเบียนยังคงพร้อมใช้งาน",
"mapView": "แผนที่",
"mapLocationField": "ฟิลด์ตำแหน่ง",
@@ -27,8 +26,6 @@
"locationName": "ชื่อ (ไม่บังคับ)",
"latitude": "ละติจูด",
"longitude": "ลองจิจูด",
- "pasteCoordinates": "วางพิกัด",
- "coordinateOrderTip": "อ่านพิกัดตามลำดับที่เลือก โดยลำดับเริ่มต้นคือลองจิจูด ละติจูด",
"invalidCoordinates": "ป้อนละติจูดที่เป็นจำนวนจำกัดตั้งแต่ -90 ถึง 90 และลองจิจูดตั้งแต่ -180 ถึง 180 หรือเว้นว่างทั้งคู่",
"pageScrollUp": "หน้าจอก่อนหน้า",
"pageScrollDown": "หน้าจอถัดไป",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index e1bbaabc47..cdf99eaa26 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Tanıma motoru",
"configGroupSignInTokens": "Giriş ve tokenlar",
"searchControlUnavailable": "Geçerli arama yöntemi için kullanılamaz",
- "coordinateOrder": "Koordinat sırası",
"mapAuthenticationBypass": "Kimlik doğrulamayı atlama etkinken haritalar kullanılamaz. Kayıtlar kullanılabilir durumda kalır",
"mapView": "Harita",
"mapLocationField": "Konum alanı",
@@ -27,8 +26,6 @@
"locationName": "Ad (isteğe bağlı)",
"latitude": "Enlem",
"longitude": "Boylam",
- "pasteCoordinates": "Koordinatları yapıştır",
- "coordinateOrderTip": "Koordinatlar seçilen sırayla okunur; varsayılan sıra boylam, enlemdir",
"invalidCoordinates": "-90 ile 90 arasında sonlu bir enlem ve -180 ile 180 arasında bir boylam girin veya ikisini de boş bırakın",
"pageScrollUp": "Önceki ekran",
"pageScrollDown": "Sonraki ekran",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index d164c8250f..14d2dbbf2c 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "Рушій розпізнавання",
"configGroupSignInTokens": "Вхід і токени",
"searchControlUnavailable": "Недоступно для поточного методу пошуку",
- "coordinateOrder": "Порядок координат",
"mapAuthenticationBypass": "Мапи недоступні, доки ввімкнено обхід автентифікації. Записи залишаються доступними",
"mapView": "Мапа",
"mapLocationField": "Поле місцеположення",
@@ -27,8 +26,6 @@
"locationName": "Назва (необов’язково)",
"latitude": "Широта",
"longitude": "Довгота",
- "pasteCoordinates": "Вставити координати",
- "coordinateOrderTip": "Координати зчитуються у вибраному порядку; типовий порядок — довгота, широта",
"invalidCoordinates": "Введіть скінченну широту від -90 до 90 і довготу від -180 до 180 або залиште обидва поля порожніми",
"pageScrollUp": "Попередній екран",
"pageScrollDown": "Наступний екран",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 61ecc0bbe6..7cf165db36 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "识别引擎",
"configGroupSignInTokens": "登录与令牌",
"searchControlUnavailable": "当前搜索方式不支持此选项",
- "coordinateOrder": "坐标顺序",
"mapAuthenticationBypass": "启用鉴权绕过时无法使用地图,记录仍可访问",
"mapView": "地图",
"mapLocationField": "位置字段",
@@ -27,8 +26,6 @@
"locationName": "名称(可选)",
"latitude": "纬度",
"longitude": "经度",
- "pasteCoordinates": "粘贴坐标",
- "coordinateOrderTip": "按所选顺序读取坐标,默认为经度、纬度",
"invalidCoordinates": "请输入 -90 至 90 的有限纬度和 -180 至 180 的有限经度,或同时留空",
"pageScrollUp": "上一屏",
"pageScrollDown": "下一屏",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 006993061a..3a0f21e5d8 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -7,7 +7,6 @@
"configGroupOCREngine": "辨識引擎",
"configGroupSignInTokens": "登入與權杖",
"searchControlUnavailable": "目前的搜尋方式不支援此選項",
- "coordinateOrder": "座標順序",
"mapAuthenticationBypass": "啟用驗證繞過時無法使用地圖,記錄仍可存取",
"mapView": "地圖",
"mapLocationField": "位置欄位",
@@ -27,8 +26,6 @@
"locationName": "名稱(選填)",
"latitude": "緯度",
"longitude": "經度",
- "pasteCoordinates": "貼上座標",
- "coordinateOrderTip": "依所選順序讀取座標,預設為經度、緯度",
"invalidCoordinates": "請輸入 -90 至 90 的有限緯度和 -180 至 180 的有限經度,或同時留空",
"pageScrollUp": "上一屏",
"pageScrollDown": "下一屏",
diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.js
index 0423a1dde1..fa198c4b4d 100644
--- a/app/electron/mapHostManager.js
+++ b/app/electron/mapHostManager.js
@@ -12,6 +12,10 @@ const {
isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy,
} = require("./mapHostPolicy");
+// 资源准备包含文档、打包资源和 CSP 锁定;地图就绪从 bootstrapReady 起另计有限预算。
+const MAP_HOST_BOOTSTRAP_TIMEOUT = 30000;
+const MAP_HOST_READY_TIMEOUT = 45000;
+
const deniedResponse = () => new Response("Forbidden", {status: 403,
headers: {"Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store"}});
const withoutCredentials = (headers) => Object.fromEntries(Object.entries(headers || {})
@@ -414,15 +418,14 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
try {
if (reply.type === "bootstrapReady" && !host.bootstrapped) {
host.bootstrapped = true;
- // SDK 脚本和地图完成分别最多等待 20 秒,启动耗时不占用这两个阶段的预算。
- setDeadline(host, 45000);
+ // 打包资源和 CSP 已准备完成,此后只等待地图创建与 load 就绪。
+ setDeadline(host, MAP_HOST_READY_TIMEOUT);
post(host, init);
} else if (reply.type === "ready" && host.bootstrapped && !host.ready) {
host.ready = true;
clearTimeout(host.timer);
if (host.points) post(host, host.points);
post(host, {version: 1, instanceID: init.instanceID, type: "theme", theme: init.theme});
- if (host.pendingFit) post(host, {version: 1, instanceID: init.instanceID, type: "fit"});
if (host.destroyed) return;
applyGeometry(host);
if (host.destroyed) return;
@@ -446,7 +449,7 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
contents.postMessage("siyuan-map-port", {version: 1, instanceID: init.instanceID, nonce, provider: init.provider}, [port2]);
} catch (_error) { fail(host, "hostPortSetupFailed"); }
});
- setDeadline(host, 30000);
+ setDeadline(host, MAP_HOST_BOOTSTRAP_TIMEOUT);
creationFailure = "hostAttachFailed";
view.setVisible(false);
// DOM 暂时不可见时也能完成初始化;此占位视图始终隐藏,不会覆盖编辑器。
@@ -473,7 +476,6 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
host.points = command;
host.ids = new Set(command.points.map(point => point.id));
} else if (command.type === "theme") host.init.theme = command.theme;
- else if (command.type === "fit") host.pendingFit = true;
if (host.ready) post(host, command);
});
ipcMain.on("siyuan-map-geometry", (event, value) => {
@@ -491,4 +493,4 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
return {destroyAll: () => [...hosts.values()].forEach(destroy)};
};
-module.exports = {createMapSessionRouter, createMapHostManager};
+module.exports = {createMapSessionRouter, createMapHostManager, MAP_HOST_BOOTSTRAP_TIMEOUT, MAP_HOST_READY_TIMEOUT};
diff --git a/app/electron/mapHostPolicy.js b/app/electron/mapHostPolicy.js
index 2a83918b80..9c32761527 100644
--- a/app/electron/mapHostPolicy.js
+++ b/app/electron/mapHostPolicy.js
@@ -66,7 +66,7 @@ const parseMapCommand = (value, instanceID) => {
return {...base, type: value.type, revision: value.revision, points: sanitizeMapPoints(value.points)};
}
if (value.type === "theme" && isMapTheme(value.theme)) return {...base, type: value.type, theme: value.theme};
- if (["fit", "resize", "destroy"].includes(value.type)) return {...base, type: value.type};
+ if (["resize", "destroy"].includes(value.type)) return {...base, type: value.type};
};
const parseMapReply = (value, instanceID) => {
if (!isRecord(value) || value.version !== 1 || value.instanceID !== instanceID) return;
diff --git a/app/src/protyle/render/av/locationEditor.test.ts b/app/src/protyle/render/av/locationEditor.test.ts
index 91ca08ef53..132f3d23a3 100644
--- a/app/src/protyle/render/av/locationEditor.test.ts
+++ b/app/src/protyle/render/av/locationEditor.test.ts
@@ -98,7 +98,10 @@ const createEditor = (options: {
};
runInNewContext(compiled, {
exports: methods,
- require: (name: string) => modules[name],
+ require: (name: string) => {
+ assert.ok(Object.prototype.hasOwnProperty.call(modules, name), `Unexpected location editor dependency: ${name}`);
+ return modules[name];
+ },
Error,
window: {siyuan: {languages: new Proxy({}, {get: (_target, property) => String(property)})}},
document: {body: {}, activeElement: null, createElement: () => new Control(),
@@ -143,7 +146,7 @@ describe("database location editor", () => {
assert.doesNotMatch(editor.markup, /<label class="b3-label/);
assert.match(editor.markup, /<div class="b3-label b3-label--inner fn__flex">\s*<label class="fn__flex-1">longitude/);
assert.match(editor.markup, /<label class="fn__flex-1">latitude/);
- assert.doesNotMatch(editor.markup, /coordinateSystem|coordinateOrder|pasteCoordinates|textarea|data-action="parse"/);
+ assert.doesNotMatch(editor.markup, /coordinateSystem|select|textarea|data-action="parse"/);
assert.match(editor.markup, /data-action="save"/);
}
});
diff --git a/app/src/protyle/render/av/locationIntegration.test.ts b/app/src/protyle/render/av/locationIntegration.test.ts
index 47077f6f8c..220c12f65d 100644
--- a/app/src/protyle/render/av/locationIntegration.test.ts
+++ b/app/src/protyle/render/av/locationIntegration.test.ts
@@ -12,23 +12,45 @@ import * as escape from "../../../util/escape";
import {genAVDragFillValue} from "./dragFillValue";
import {inferAVPasteColumnType} from "./paste";
+// 位置用例不调用这些依赖;新增依赖或意外调用都应立即使测试失败。
+const unusedDependencies = [
+ "./viewType", "./renderData", "../../wysiwyg/transaction", "../../util/hasClosest", "./openMenuPanel",
+ "./action", "../../util/compatibility", "../../../util/fetch", "../../util/selection", "../../util/selectionOffsets",
+ "dayjs", "../../../emoji", "./col", "./attributeValue", "../../../constants", "../../hint/extend",
+ "../../../util/pathName", "./select", "../../undo", "./dateFormat", "./row", "./view", "../../../util/image",
+ "../../../util/imageURL", "../../../mobile/util/mobileAppUtil", "../../../mobile/util/keyboardToolbar",
+ "../../../util/setPosition", "./selectionState", "./color", "./richText", "./richTextEditor", "./virtualScroll",
+ "./cellEditor", "./blockIcon", "./cellInputPosition", "./locationEditor", "../../../dialog/message",
+ "../../../util/hostCapabilities", "../../../plugin/Menu", "../../../util/upDownHint", "./richTextValue",
+ "../../../emoji/fileTreeIcon", "./lunarDate",
+];
+
const loadModule = <T>(file: string, extra: Record<string, unknown> = {}) => {
const methods = {} as T;
+ const modules: Record<string, unknown> = {
+ ...Object.fromEntries(unusedDependencies.map(name => [name, new Proxy({}, {
+ get: (_target, member) => {
+ throw new Error(`Unexpected dependency use in ${file}: ${name}.${String(member)}`);
+ },
+ })])),
+ "./capabilities": capabilities,
+ "./cellValue": cellValue,
+ "./locationValue": locationValue,
+ "./batchValue": batchValue,
+ "./dragFillValue": dragFillValue,
+ "../../../util/functions": {objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right)},
+ "../../../util/escape": escape,
+ ...extra,
+ };
runInNewContext(transpileModule(readFileSync(`src/protyle/render/av/${file}.ts`, "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
}).outputText, {
exports: methods,
window: {siyuan: {languages: {empty: "Empty", copy: "Copy", locationPasteInEditor: "Use the location editor"}}},
- require: (name: string) => ({
- "./capabilities": capabilities,
- "./cellValue": cellValue,
- "./locationValue": locationValue,
- "./batchValue": batchValue,
- "./dragFillValue": dragFillValue,
- "../../../util/functions": {objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right)},
- "../../../util/escape": escape,
- ...extra,
- })[name] || {},
+ require: (name: string) => {
+ assert.ok(Object.prototype.hasOwnProperty.call(modules, name), `Unexpected dependency in ${file}: ${name}`);
+ return modules[name];
+ },
});
return methods;
};
@@ -84,7 +106,6 @@ 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.equal(locationValue.parseAVLocationCoordinates(cell.getCellValueText(first), "longitudeLatitude"), undefined);
assert.throws(() => cell.genCellValue("location", cell.getCellValueText(first)));
});
diff --git a/app/src/protyle/render/av/locationValue.test.ts b/app/src/protyle/render/av/locationValue.test.ts
index 80fda2d169..cf149a3aba 100644
--- a/app/src/protyle/render/av/locationValue.test.ts
+++ b/app/src/protyle/render/av/locationValue.test.ts
@@ -9,7 +9,7 @@ import {
getAVLocationText,
isAVLocationCoordinateInput,
isAVLocationEmpty,
- parseAVLocationCoordinates,
+ parseAVLocationCoordinate,
validateAVLocation,
} from "./locationValue";
@@ -23,18 +23,6 @@ describe("database location values", () => {
assert.deepEqual(value, {latitude: 20, longitude: 30, coordinateSystem});
}
});
- it("supports paired parentheses and explicit longitude-first order without guessing", () => {
- const source = " (102.42,25.04) ";
- assert.equal(parseAVLocationCoordinates(source), undefined);
- assert.deepEqual(parseAVLocationCoordinates(source, "longitudeLatitude"), {
- latitude: 25.04, longitude: 102.42, originalInput: source,
- });
- assert.equal(parseAVLocationCoordinates("(20,30)")?.latitude, 20);
- assert.equal(parseAVLocationCoordinates("(20,30)", "longitudeLatitude")?.latitude, 30);
- for (const text of ["(20,30", "20,30)", "((20,30))", "(20),30", "[20,30]"]) {
- assert.equal(parseAVLocationCoordinates(text), undefined, text);
- }
- });
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"]) {
assert.deepEqual(createAVLocationFromText(text), {
@@ -43,7 +31,7 @@ describe("database location values", () => {
}
});
- it("requires the explicit import flow for coordinate-looking or canonical pasted 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]"]) {
assert.equal(isAVLocationCoordinateInput(source), true, source);
@@ -79,23 +67,21 @@ describe("database location values", () => {
}
});
- it("imports only the explicitly specified latitude, longitude order and exact source", () => {
- const source = " +31.23040, 121.47370\n";
- assert.deepEqual(parseAVLocationCoordinates(source), {
- latitude: 31.2304, longitude: 121.4737, originalInput: source,
- });
- assert.deepEqual(parseAVLocationCoordinates("0, -0"), {
- latitude: 0, longitude: -0, originalInput: "0, -0",
- });
- assert.equal(parseAVLocationCoordinates("121.4737,31.2304"), undefined);
- assert.equal(parseAVLocationCoordinates(".5,-.25")?.latitude, .5);
+ it("parses each named coordinate field as a signed decimal including zero and boundaries", () => {
+ for (const [source, expected] of [
+ [" +31.23040\n", 31.2304], ["121.47370", 121.4737],
+ ["0", 0], ["+0.0", 0], ["-0", -0], [".5", .5], ["-.25", -.25], ["1.", 1],
+ ["-90", -90], ["90", 90], ["-180", -180], ["180", 180], ["0.0000001", 1e-7],
+ ] as const) {
+ assert.equal(parseAVLocationCoordinate(source), expected, source);
+ }
});
- it("rejects malformed, out-of-range, partial, nondecimal, and service-link imports", () => {
- for (const source of ["", "31", "31,", ",121", "31,121,0", "90.1,0", "0,-180.1",
- "1e1,2e1", "0x10,20", "NaN,0", "Infinity,0", "31 121", "31;121", "31\u00b0N,121\u00b0E",
- "geo:31,121", "https://example.com/?lat=31&lon=121"]) {
- assert.equal(parseAVLocationCoordinates(source), undefined, source);
+ it("rejects pairs, malformed, nondecimal, nonfinite, and service-link coordinate fields", () => {
+ for (const source of ["", " ", "+", "-", ".", "--1", "31,", ",121", "31,121", "31,121,0",
+ "(20)", "[20]", "(20,30)", "1e1", "0x10", "0b10", "0o10", "NaN", "Infinity", "-Infinity",
+ "9".repeat(400), "31 121", "31;121", "31\u00b0N", "geo:31,121", "https://example.com/?lat=31&lon=121"]) {
+ assert.equal(parseAVLocationCoordinate(source), undefined, source);
}
});
@@ -120,7 +106,7 @@ describe("database location values", () => {
assert.equal(getAVLocationDisplayText(location), "Office 30, 20");
assert.equal(getAVLocationText(location), `Office; 20, 30 [${label}]`);
assert.deepEqual(location, before);
- assert.equal(parseAVLocationCoordinates(getAVLocationText(location), "longitudeLatitude"), undefined);
+ assert.throws(() => createAVLocationFromText(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 80086b2bfb..ff11c2ae53 100644
--- a/app/src/protyle/render/av/locationValue.ts
+++ b/app/src/protyle/render/av/locationValue.ts
@@ -87,7 +87,7 @@ export const isAVLocationCoordinateInput = (text: string) => {
parts.every(part => part === "" || coordinateInput.test(part))) || canonicalInput.test(text);
};
-// 普通粘贴只记录地点名称;坐标文本必须使用明确标注顺序的导入入口。
+// 普通粘贴只记录地点名称;坐标必须在编辑器中按具名字段输入。
export const createAVLocationFromText = (text: string): IAVCellLocationValue => {
if (isAVLocationCoordinateInput(text)) {
throw new Error("Location coordinates require explicit latitude, longitude input");
@@ -104,22 +104,6 @@ export const parseAVLocationCoordinate = (text: string) => {
return Number.isFinite(number) ? number : undefined;
};
-// 只按用户明确选择的顺序解析,不根据范围猜测顺序或解析地图服务链接。
-export const parseAVLocationCoordinates = (text: string,
- order: "latitudeLongitude" | "longitudeLatitude" = "latitudeLongitude"):
- IAVCellLocationValue | undefined => {
- const trimmed = text.trim();
- const unwrapped = trimmed.startsWith("(") && trimmed.endsWith(")") ? trimmed.slice(1, -1) : trimmed;
- const parts = unwrapped.split(",");
- if (parts.length !== 2) {
- return undefined;
- }
- const latitude = parseAVLocationCoordinate(parts[order === "longitudeLatitude" ? 1 : 0]);
- const longitude = parseAVLocationCoordinate(parts[order === "longitudeLatitude" ? 0 : 1]);
- const value = {latitude, longitude, originalInput: text};
- return hasAVLocationCoordinates(value) ? value : undefined;
-};
-
// 原始输入仅为来源记录,不参与值的语义比较。
export const areAVLocationsEqual = (left?: IAVCellLocationValue, right?: IAVCellLocationValue) => {
return (left?.name?.trim() || "") === (right?.name?.trim() || "") &&
diff --git a/app/src/protyle/render/av/map/attribution.ts b/app/src/protyle/render/av/map/attribution.ts
new file mode 100644
index 0000000000..efbba6fb5a
--- /dev/null
+++ b/app/src/protyle/render/av/map/attribution.ts
@@ -0,0 +1,145 @@
+import {AV_MAP_ATTRIBUTION_LINKS, AVMapAttributionLink, AVMapProvider, AVMapViewport} from "./protocol";
+
+export interface AVMapAttributionController {
+ onReady: () => void;
+ setVisible: (visible: boolean, viewport?: AVMapViewport) => void;
+ destroy: () => void;
+}
+
+export const createAVMapAttribution = (provider: AVMapProvider, sdk: any, map: any, container: HTMLElement,
+ onClick?: (link: AVMapAttributionLink) => void): AVMapAttributionController => {
+ const doc = container.ownerDocument;
+ const scope = doc.defaultView;
+ const maplibre = AV_MAP_ATTRIBUTION_LINKS[provider].find(link => link.id === "maplibre");
+ const control = new sdk.AttributionControl({compact: true,
+ customAttribution: `<a href="${maplibre.href}" target="_blank">${maplibre.label}</a>`});
+ let attribution: HTMLDetailsElement;
+ let attributionText: HTMLElement;
+ let destroyed = false, loaded = false, visible = false, expanded = true, automatic = true;
+ let viewport: AVMapViewport;
+ let frame = 0, visibleSince: number;
+ const syncAttribution = () => {
+ if (destroyed) return;
+ // MapLibre 的紧凑控件同时使用 details 状态和此 CSS 类。
+ attribution.open = expanded;
+ attribution.classList.toggle("maplibregl-compact-show", expanded);
+ };
+ const cancelFrame = () => {
+ scope.cancelAnimationFrame(frame);
+ frame = 0;
+ };
+ const attributionVisible = () => {
+ if (!viewport || doc.hidden || !attributionText.getClientRects().length || !attributionText.textContent?.trim()) return false;
+ const rect = attribution.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0 || rect.left < 0 || rect.top < 0 ||
+ rect.right > scope.innerWidth || rect.bottom > scope.innerHeight ||
+ rect.left < viewport.x || rect.top < viewport.y || rect.right > viewport.x + viewport.width ||
+ rect.bottom > viewport.y + viewport.height) return false;
+ // 紧凑控件的圆角属于透明区域,遮挡检查应命中实际展示的版权文字。
+ const textRect = attributionText.getBoundingClientRect();
+ if (textRect.width <= 0 || textRect.height <= 0) return false;
+ return [textRect.left + 1, textRect.right - 1].every(x => [textRect.top + 1, textRect.bottom - 1].every(y =>
+ attribution.contains(doc.elementFromPoint(x, y))));
+ };
+ const tickAttribution = (now: number) => {
+ frame = 0;
+ if (destroyed || !automatic || !loaded || !visible || doc.hidden) return;
+ if (attributionVisible()) {
+ if (visibleSince === undefined) visibleSince = now;
+ if (now - visibleSince >= 5000) {
+ automatic = false;
+ expanded = false;
+ syncAttribution();
+ return;
+ }
+ } else {
+ visibleSince = undefined;
+ }
+ frame = scope.requestAnimationFrame(tickAttribution);
+ };
+ const updateVisibility = () => {
+ cancelFrame();
+ if (destroyed || !automatic || !loaded || !visible || doc.hidden) {
+ visibleSince = undefined;
+ return;
+ }
+ // 尺寸变化后仍完整可见时延续计时;裁剪或遮挡立即中断连续展示。
+ if (!attributionVisible()) visibleSince = undefined;
+ frame = scope.requestAnimationFrame(tickAttribution);
+ };
+ const onInteraction = (event: Event) => {
+ if (destroyed || !event.isTrusted) return;
+ automatic = false;
+ cancelFrame();
+ visibleSince = undefined;
+ };
+ const onAttributionClick = (event: MouseEvent) => {
+ const target = event.target as Element;
+ const anchor = target.closest<HTMLAnchorElement>("a");
+ const summary = target.closest("summary");
+ if (!anchor && !summary) return;
+ // 不向供应商文档授予导航或弹窗权限。
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ if (destroyed || !event.isTrusted || event.button !== 0) return;
+ if (summary) {
+ // 本地展开不依赖跨宿主可见性消息或外链所需的瞬时激活状态。
+ onInteraction(event);
+ expanded = !expanded;
+ syncAttribution();
+ } else if (visible && attribution.contains(anchor) &&
+ (scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) {
+ onInteraction(event);
+ const link = AV_MAP_ATTRIBUTION_LINKS[provider].find(item => item.href === anchor.getAttribute("href"));
+ if (link) onClick?.(link.id);
+ }
+ };
+ const controller: AVMapAttributionController = {
+ onReady: () => {
+ if (destroyed || loaded) return;
+ loaded = true;
+ syncAttribution();
+ updateVisibility();
+ },
+ setVisible: (nextVisible, nextViewport) => {
+ if (destroyed || visible === nextVisible && viewport?.x === nextViewport?.x && viewport?.y === nextViewport?.y &&
+ viewport?.width === nextViewport?.width && viewport?.height === nextViewport?.height) return;
+ visible = nextVisible;
+ viewport = nextViewport;
+ updateVisibility();
+ },
+ destroy: () => {
+ if (destroyed) return;
+ destroyed = true;
+ cancelFrame();
+ visibleSince = undefined;
+ attribution?.removeEventListener("click", onAttributionClick, true);
+ attribution?.removeEventListener("auxclick", onAttributionClick, true);
+ attribution?.removeEventListener("pointerdown", onInteraction, true);
+ attribution?.removeEventListener("keydown", onInteraction, true);
+ doc.removeEventListener("visibilitychange", updateVisibility);
+ map.off("drag", syncAttribution);
+ map.off("resize", syncAttribution);
+ },
+ };
+ try {
+ map.addControl(control);
+ attribution = container.querySelector<HTMLDetailsElement>(".maplibregl-ctrl-attrib");
+ attributionText = attribution?.querySelector<HTMLElement>(".maplibregl-ctrl-attrib-inner");
+ if (!attribution || !attributionText) throw new Error("mapUnavailable");
+ attribution.addEventListener("click", onAttributionClick, true);
+ attribution.addEventListener("auxclick", onAttributionClick, true);
+ attribution.addEventListener("pointerdown", onInteraction, true);
+ attribution.addEventListener("keydown", onInteraction, true);
+ doc.addEventListener("visibilitychange", updateVisibility);
+ // SDK 控件先处理拖动和尺寸事件,再恢复首次展示或用户主动选择的状态。
+ map.on("drag", syncAttribution);
+ map.on("resize", syncAttribution);
+ syncAttribution();
+ return controller;
+ } catch (error) {
+ controller.destroy();
+ if (!map.hasControl?.(control)) control.onRemove?.();
+ throw error;
+ }
+};
diff --git a/app/src/protyle/render/av/map/bootstrap.ts b/app/src/protyle/render/av/map/bootstrap.ts
index 751af17334..efd890ed94 100644
--- a/app/src/protyle/render/av/map/bootstrap.ts
+++ b/app/src/protyle/render/av/map/bootstrap.ts
@@ -1,7 +1,7 @@
import {AVMapProvider, isAVMapProvider} from "./protocol";
import {prepareAVMapAssets} from "./providersLoader";
-// This intersects the response policy. Local origins are removed before creating any Worker.
+// 此策略与响应策略共同生效,在创建 Worker 前移除本地来源权限。
export const getAVMapLockedPolicy = (provider: AVMapProvider): string => {
if (!isAVMapProvider(provider)) throw new Error("invalidConfiguration");
return "default-src 'none'; script-src 'none'; connect-src https://tiles.openfreemap.org; " +
diff --git a/app/src/protyle/render/av/map/createRecord.test.ts b/app/src/protyle/render/av/map/createRecord.test.ts
index c34b6764be..39b390193f 100644
--- a/app/src/protyle/render/av/map/createRecord.test.ts
+++ b/app/src/protyle/render/av/map/createRecord.test.ts
@@ -2,74 +2,133 @@ import * as assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
-import * as ts from "typescript";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import * as closest from "../../../util/hasClosest";
+import * as escape from "../../../../util/escape";
+import {DOMFixture, requireFixture} from "./testDOM";
-const action = ts.createSourceFile("action.ts", readFileSync("src/protyle/render/av/action.ts", "utf8"),
- ts.ScriptTarget.Latest, true);
-const template = ts.createSourceFile("newItemTemplate.ts", readFileSync("src/protyle/render/av/newItemTemplate.ts", "utf8"),
- ts.ScriptTarget.Latest, true);
-const create = template.statements.find(statement => ts.isVariableStatement(statement) &&
- statement.declarationList.declarations.some(declaration => declaration.name.getText(template) === "createAttributeViewItem"));
+const compile = (path: string) => transpileModule(readFileSync(path, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+}).outputText;
+const actionSource = compile("src/protyle/render/av/action.ts");
+const templateSource = compile("src/protyle/render/av/newItemTemplate.ts");
+
+const setup = (type: string, layout: string, templateID = "") => {
+ const document = new DOMFixture();
+ const block = document.createElement("div");
+ block.dataset.type = "NodeAttributeView";
+ block.dataset.avId = "database";
+ block.dataset.nodeId = "carrier";
+ block.dataset.avType = layout;
+ block.setAttribute("custom-sy-av-view", "view");
+ block.innerHTML = `<div class="av__header" data-default-template-id="${templateID}"></div>
+ <div class="av__body" data-group-id=""><button data-type="${type}"><span>Create</span></button></div>`;
+ document.body.append(block);
+ const requests: Array<{templateID: string; previousID: string; groupID: string; avID: string; blockID: string; viewID: string}> = [];
+ const opened: Array<{itemID: string; focusPrimary: boolean}> = [];
+ const insertions: Array<{previousID: string; groupID: string}> = [];
+ const messages: string[] = [];
+ let callback: (response: unknown) => void;
+ let rendered = 0;
+ const modules: Record<string, unknown> = {};
+ // 只允许已知但本入口不应调用的依赖;新增依赖或意外走入其他业务路径均立即失败。
+ for (const id of ["./viewType", "../../../plugin/Menu", "../../wysiwyg/transaction", "../../../menus/util",
+ "../../../menus/commonMenuItem", "./cell", "./col", "../../../plugin/EventBus", "./openMenuPanel",
+ "../../hint/extend", "../../util/selection", "../../util/selectionOffsets", "../../preview/image",
+ "../../../emoji", "dayjs", "./calc", "./view", "./rangeSelect", "./relation", "../../ui/hideElements",
+ "../../../util/highlightById", "./gallery/util", "../../util/clear", "../../../util/image",
+ "../../../mobile/util/mobileAppUtil", "./kanban/groupMenu", "./groupFold", "./publishState",
+ "./readonlyState", "./batchEdit", "../../../util/functions", "./viewVisibility",
+ "./cellValue", "./blockIcon", "./itemLink", "../../../editor/openLink", "./richText", "../../../search/util",
+ "../../../mobile/menu/search", "../../../mobile/util/keyboardToolbar", "./capabilities", "./fieldValueEditor",
+ "./locationValue", "../../../dialog", "../../../menus/Menu", "../../../util/upDownHint",
+ "../../../mobile/util/bindBottomSheetDialog"]) {
+ modules[id] = new Proxy({}, {get: (_target, name: string) => assert.fail(`Unexpected dependency call: ${id}.${name}`)});
+ }
+ Object.assign(modules, {
+ "../../util/hasClosest": closest,
+ "../../util/compatibility": {isOnlyMeta: () => false},
+ "./attributeValue": {getAVTemplateInteractiveElement: () => null},
+ "./coverPosition": {isCardCoverPositioning: () => false},
+ "./row": {insertRows: (position: typeof insertions[number]) => insertions.push(position)},
+ "./virtualScroll": {getAvBodyData: () => ({rows: [{id: "previous-row"}]})},
+ "./calendar/state": {getCalendarCreationDate: () => undefined},
+ "../../../constants": {Constants: {CUSTOM_SY_AV_VIEW: "custom-sy-av-view"}},
+ "../../../util/escape": escape,
+ "../../../dialog/message": {showMessage: (message: string) => messages.push(message)},
+ "../../../util/fetch": {fetchPost: (url: string, payload: typeof requests[number], response: typeof callback) => {
+ assert.equal(url, "/api/av/createAttributeViewItem");
+ requests.push(payload);
+ callback = response;
+ }},
+ "./render": {avRender: () => { rendered++; }},
+ "./openDatabaseRow": {openDatabaseRowByData: (_protyle: unknown, record: typeof opened[number]) => opened.push(record)},
+ });
+ const context = {document, require: requireFixture(modules), window: {siyuan: {languages: {
+ newItemTemplateUnavailableNotebookTip: "Unavailable notebook", untitled: "Untitled",
+ }}}};
+ const template = {} as typeof import("../newItemTemplate");
+ runInNewContext(templateSource, {...context, exports: template});
+ modules["./newItemTemplate"] = template;
+ const action = {} as typeof import("../action");
+ runInNewContext(actionSource, {...context, exports: action});
+ const protyle = {app: {appId: "app"}, id: "editor", notebookId: "notebook", options: {}} as IProtyle;
+ return {requests, opened, insertions, messages, protyle, block, rendered: () => rendered,
+ click: () => action.avClick(protyle, {target: block.querySelector("span"), preventDefault() {}, stopPropagation() {}} as unknown as MouseEvent & {target: HTMLElement}),
+ respond: (response: unknown = {code: 0, data: {itemID: "new-record", content: "New record", isDetached: true}}) => callback(response)};
+};
for (const type of ["av-add-more", "av-add-bottom"]) {
- test(`map ${type} creates and opens records with optional templates and preserves insertion position`, () => {
- let branch: ts.Statement;
- const visit = (node: ts.Node) => {
- if (ts.isIfStatement(node) && node.expression.getText(action) === `type === "${type}" && !protyle.disabled`) {
- branch = node.thenStatement;
- }
- ts.forEachChild(node, visit);
- };
- visit(action);
- assert.ok(branch);
- const compiled = ts.transpileModule(create.getText(template).replace(/^export /, "") +
- `\n(() => ${branch.getText(action)})();`, {compilerOptions: {target: ts.ScriptTarget.ES2022}}).outputText;
+ test(`map ${type} dispatches through avClick and opens created records with optional templates`, () => {
for (const layout of ["map", "table"]) {
for (const templateID of ["", "template-id"]) {
- const requests: Array<{templateID: string; previousID: string; groupID: string}> = [];
- const opened: Array<{itemID: string; focusPrimary: boolean}> = [];
- let inserted = 0;
- let rendered = 0;
- const blockElement = {
- dataset: {avId: "database", nodeId: "carrier", avType: layout},
- getAttribute: (name: string) => name === "data-av-type" ? layout : "view",
- querySelector: () => ({dataset: {defaultTemplateId: templateID}}),
- removeAttribute() {},
- };
- runInNewContext(compiled, {
- blockElement, viewType: layout, target: {},
- Constants: {CUSTOM_SY_AV_VIEW: "custom-sy-av-view"},
- protyle: {app: {appId: "app"}, id: "editor", notebookId: "notebook"},
- event: {preventDefault() {}, stopPropagation() {}},
- hasClosestByClassName: () => ({getAttribute: () => ""}),
- getAvBodyData: () => ({rows: [{id: "previous-row"}]}),
- getCalendarCreationDate: (): number | undefined => undefined,
- fetchPost: (url: string, payload: typeof requests[number], callback: (response: unknown) => void) => {
- assert.equal(url, "/api/av/createAttributeViewItem");
- requests.push(payload);
- callback({code: 0, data: {itemID: "new-record", content: "New record", isDetached: true}});
- },
- insertRows: () => inserted++,
- avRender: () => rendered++,
- openDatabaseRowByData: (_protyle: unknown, record: typeof opened[number]) => opened.push(record),
- });
+ const scenario = setup(type, layout, templateID);
+ assert.equal(scenario.click(), true);
+ assert.equal(scenario.opened.length, 0);
if (layout === "table" && !templateID) {
- assert.equal(inserted, 1);
- assert.equal(requests.length, 0);
+ assert.equal(scenario.insertions.length, 1);
+ assert.equal(scenario.requests.length, 0);
+ assert.equal(scenario.insertions[0].previousID, type === "av-add-bottom" ? "previous-row" : "");
} else {
- assert.equal(inserted, 0);
- assert.equal(requests.length, 1);
- assert.equal(requests[0].templateID, templateID);
- assert.equal(requests[0].previousID, type === "av-add-bottom" ? "previous-row" : "");
- assert.equal(requests[0].groupID, "");
- assert.equal(rendered, 1);
+ assert.equal(scenario.insertions.length, 0);
+ assert.equal(scenario.requests.length, 1);
+ const request = scenario.requests[0];
+ assert.equal(request.templateID, templateID);
+ assert.equal(request.previousID, type === "av-add-bottom" ? "previous-row" : "");
+ assert.equal(request.groupID, "");
+ assert.equal(request.avID, "database");
+ assert.equal(request.blockID, "carrier");
+ assert.equal(request.viewID, "view");
+ scenario.respond();
+ assert.equal(scenario.rendered(), 1);
}
- assert.equal(opened.length, layout === "map" ? 1 : 0);
+ assert.equal(scenario.opened.length, layout === "map" ? 1 : 0);
if (layout === "map") {
- assert.equal(opened[0].itemID, "new-record");
- assert.equal(opened[0].focusPrimary, true);
+ assert.equal(scenario.opened[0].itemID, "new-record");
+ assert.equal(scenario.opened[0].focusPrimary, true);
}
}
}
});
}
+
+test("disabled map creation actions cannot issue requests or insert records", () => {
+ for (const type of ["av-add-more", "av-add-bottom"]) {
+ const scenario = setup(type, "map");
+ scenario.protyle.disabled = true;
+ assert.equal(scenario.click(), false);
+ assert.equal(scenario.requests.length, 0);
+ assert.equal(scenario.insertions.length, 0);
+ }
+});
+
+test("failed map record creation cannot open a detail and preserves unavailable-notebook feedback", () => {
+ for (const unavailableNotebook of [false, true]) {
+ const scenario = setup("av-add-more", "map", "template-id");
+ scenario.click();
+ scenario.respond({code: 1, data: {unavailableNotebook}});
+ assert.equal(scenario.opened.length, 0);
+ assert.deepEqual(scenario.messages, unavailableNotebook ? ["Unavailable notebook"] : []);
+ assert.equal(scenario.rendered(), unavailableNotebook ? 0 : 1);
+ }
+});
diff --git a/app/src/protyle/render/av/map/desktopGeometry.ts b/app/src/protyle/render/av/map/desktopGeometry.ts
new file mode 100644
index 0000000000..456109057f
--- /dev/null
+++ b/app/src/protyle/render/av/map/desktopGeometry.ts
@@ -0,0 +1,63 @@
+export interface MapRect { x: number; y: number; width: number; height: number; }
+export type MapGeometry = {visible: false} | {
+ visible: true; bounds: MapRect; logicalSize: {width: number; height: number}; crop: {x: number; y: number};
+};
+
+export const intersects = (a: MapRect, b: MapRect) => a.x < b.x + b.width && b.x < a.x + a.width &&
+ a.y < b.y + b.height && b.y < a.y + a.height;
+
+// 菜单打开时不展示难以操作的狭窄残片。
+const MIN_MENU_MAP_EDGE = 32;
+const MIN_MENU_MAP_AREA = 4096;
+
+// 坐标始终使用主文档 CSS 像素,只由主进程应用文档缩放系数。
+export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occluders: MapRect[] = [],
+ menus: MapRect[] = []): MapGeometry => {
+ if (![rect, ...clips, ...occluders, ...menus].every((item) => [item.x, item.y, item.width, item.height].every(Number.isFinite) &&
+ item.width >= 0 && item.height >= 0)) {
+ return {visible: false};
+ }
+ if (rect.width < 1 || rect.height < 1) {
+ return {visible: false};
+ }
+ let left = rect.x, top = rect.y, right = rect.x + rect.width, bottom = rect.y + rect.height;
+ clips.forEach((clip) => {
+ left = Math.max(left, clip.x);
+ top = Math.max(top, clip.y);
+ right = Math.min(right, clip.x + clip.width);
+ bottom = Math.min(bottom, clip.y + clip.height);
+ });
+ // 裁剪边缘内收一个 CSS 像素,避免半像素命中相邻控件;原生绘制区域与命中检测同步收窄。
+ if (left > rect.x) left += 1;
+ if (top > rect.y) top += 1;
+ if (right < rect.x + rect.width) right -= 1;
+ if (bottom < rect.y + rect.height) bottom -= 1;
+ // 裁剪差值的浮点舍入不能使可见尺寸超过原始尺寸。
+ let bounds = {x: left, y: top, width: Math.min(rect.width, right - left), height: Math.min(rect.height, bottom - top)};
+ if (left < 0 || top < 0 || bounds.width < 1 || bounds.height < 1) {
+ return {visible: false};
+ }
+ if (occluders.some((item) => item.width > 0 && item.height > 0 && intersects(bounds, item))) {
+ return {visible: false};
+ }
+ const overlapping = menus.filter(item => item.width > 0 && item.height > 0 && intersects(bounds, item));
+ if (overlapping.length > 1) return {visible: false};
+ if (overlapping.length) {
+ const menu = overlapping[0];
+ const rightEdge = bounds.x + bounds.width, bottomEdge = bounds.y + bounds.height;
+ // 只处理当前地图唯一的未定位菜单,在四个连续矩形中选择面积最大的安全区域。
+ const candidates = [
+ [bounds.x, bounds.y, Math.min(rightEdge, menu.x - 1), bottomEdge],
+ [Math.max(bounds.x, menu.x + menu.width + 1), bounds.y, rightEdge, bottomEdge],
+ [bounds.x, bounds.y, rightEdge, Math.min(bottomEdge, menu.y - 1)],
+ [bounds.x, Math.max(bounds.y, menu.y + menu.height + 1), rightEdge, bottomEdge],
+ ].map(([x, y, right, bottom]) => ({x: Math.ceil(x), y: Math.ceil(y),
+ width: Math.floor(right) - Math.ceil(x), height: Math.floor(bottom) - Math.ceil(y)}))
+ .filter(item => item.width >= MIN_MENU_MAP_EDGE && item.height >= MIN_MENU_MAP_EDGE &&
+ item.width * item.height >= MIN_MENU_MAP_AREA);
+ if (!candidates.length) return {visible: false};
+ bounds = candidates.reduce((largest, item) => item.width * item.height > largest.width * largest.height ? item : largest);
+ }
+ return {visible: true, bounds, logicalSize: {width: rect.width, height: rect.height},
+ crop: {x: bounds.x - rect.x, y: bounds.y - rect.y}};
+};
diff --git a/app/src/protyle/render/av/map/desktopGeometryDOM.ts b/app/src/protyle/render/av/map/desktopGeometryDOM.ts
new file mode 100644
index 0000000000..eaf2f3ca8a
--- /dev/null
+++ b/app/src/protyle/render/av/map/desktopGeometryDOM.ts
@@ -0,0 +1,130 @@
+import {computeDesktopAVMapGeometry, intersects, MapGeometry, MapRect} from "./desktopGeometry";
+import {isMapUnplacedMenu} from "./unplacedMenu";
+
+const readMenuRect = (element: HTMLElement, style: CSSStyleDeclaration, scope: Window): MapRect | undefined => {
+ // 无法用单个矩形可靠界定的主题效果仍走全隐藏路径。
+ const measurable = (value: CSSStyleDeclaration) => value.transform === "none" && value.filter === "none" &&
+ ["", "normal", "1"].includes(value.getPropertyValue("zoom")) &&
+ [value.translate, value.rotate, value.scale].every(item => !item || item === "none");
+ if (!measurable(style)) return;
+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {
+ if (!measurable(scope.getComputedStyle(parent))) return;
+ }
+ const rect = element.getBoundingClientRect();
+ let left = 0, right = 0, top = 0, bottom = 0;
+ const shadows = style.boxShadow === "none" ? [] : style.boxShadow.split(/,(?![^()]*\))/);
+ for (const shadow of shadows) {
+ const parts = shadow.replace(/(?:rgba?|hsla?)\([\d\s.,%/+\-]+\)/, "").trim().split(/\s+/);
+ const inset = parts[0] === "inset" || parts[parts.length - 1] === "inset";
+ if (inset) parts.splice(parts[0] === "inset" ? 0 : parts.length - 1, 1);
+ if (parts.length < 2 || parts.length > 4 || parts.some(value => !/^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;
+ const [x, y, blur = 0, spread = 0] = parts.map(parseFloat);
+ if (blur < 0) return;
+ if (inset) continue;
+ // 模糊阴影按两倍半径保守外扩,包含多层阴影、负偏移和边框外侧的描边。
+ const extent = Math.max(0, blur * 2 + spread);
+ left = Math.max(left, extent - x);
+ right = Math.max(right, extent + x);
+ top = Math.max(top, extent - y);
+ bottom = Math.max(bottom, extent + y);
+ }
+ if (style.outlineStyle !== "none") {
+ if (![style.outlineWidth, style.outlineOffset].every(value => /^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;
+ const outline = Math.max(0, parseFloat(style.outlineWidth) + parseFloat(style.outlineOffset));
+ left = Math.max(left, outline);
+ right = Math.max(right, outline);
+ top = Math.max(top, outline);
+ bottom = Math.max(bottom, outline);
+ }
+ return {x: rect.x - left, y: rect.y - top, width: rect.width + left + right, height: rect.height + top + bottom};
+};
+
+export const readDesktopAVMapGeometry = (container: HTMLElement): MapGeometry => {
+ const doc = container.ownerDocument;
+ const scope = doc.defaultView;
+ if (!scope) {
+ return {visible: false};
+ }
+ if (doc.hidden) {
+ return {visible: false};
+ }
+ if (!container.isConnected) {
+ return {visible: false};
+ }
+ if (!container.getClientRects().length) {
+ return {visible: false};
+ }
+ const rect = container.getBoundingClientRect();
+ const clips: MapRect[] = [{x: 0, y: 0, width: scope.innerWidth, height: scope.innerHeight}];
+ for (let element: HTMLElement = container; element; element = element.parentElement) {
+ const style = scope.getComputedStyle(element);
+ if (style.display === "none" || style.visibility !== "visible" || Number(style.opacity) === 0 ||
+ style.getPropertyValue("content-visibility") === "hidden") {
+ return {visible: false};
+ }
+ if (element !== container && /hidden|clip|scroll|auto/.test(style.overflowX + style.overflowY)) {
+ const bounds = element.getBoundingClientRect();
+ const clipX = /hidden|clip|scroll|auto/.test(style.overflowX);
+ const clipY = /hidden|clip|scroll|auto/.test(style.overflowY);
+ const scaleX = element.offsetWidth ? bounds.width / element.offsetWidth : 1;
+ const scaleY = element.offsetHeight ? bounds.height / element.offsetHeight : 1;
+ clips.push({x: clipX ? bounds.x + element.clientLeft * scaleX : 0,
+ y: clipY ? bounds.y + element.clientTop * scaleY : 0,
+ width: clipX ? element.clientWidth * scaleX : scope.innerWidth,
+ height: clipY ? element.clientHeight * scaleY : scope.innerHeight});
+ }
+ }
+ const views = container.closest(".av[data-type='NodeAttributeView']")
+ ?.querySelector<HTMLElement>(":scope > .av__container > .av__header > .av__views--fixed");
+ if (views?.getClientRects().length) {
+ const style = scope.getComputedStyle(views);
+ const bounds = views.getBoundingClientRect();
+ if (["fixed", "sticky"].includes(style.position) && style.display !== "none" &&
+ style.visibility === "visible" && Number(style.opacity) !== 0 && intersects(rect, bounds)) {
+ // 本数据库的固定页签栏遮住地图顶部时,只展示栏底部以下的区域。
+ const top = Math.max(0, bounds.y + bounds.height);
+ clips.push({x: 0, y: top, width: scope.innerWidth, height: Math.max(0, scope.innerHeight - top)});
+ }
+ }
+ const occluders: MapRect[] = [];
+ const menus: MapRect[] = [];
+ let unsupportedMenu = false;
+ // 只检查应用实际浮层根节点,不根据任意 z-index 猜测遮挡。
+ doc.querySelectorAll<HTMLElement>(".b3-menu, .b3-dialog, .av__panel, .protyle-util, .protyle-toolbar, .block__popover, [popover]")
+ .forEach((element) => {
+ if (element.contains(container) || !element.getClientRects().length) {
+ return;
+ }
+ const style = scope.getComputedStyle(element);
+ if (style.display !== "none" && style.visibility === "visible" && Number(style.opacity) !== 0) {
+ if (isMapUnplacedMenu(element, container)) {
+ const bounds = readMenuRect(element, style, scope);
+ const hasSubmenu = Array.from(element.querySelectorAll<HTMLElement>(".b3-menu__submenu"))
+ .some(submenu => {
+ const submenuStyle = scope.getComputedStyle(submenu);
+ return submenu.getClientRects().length && submenuStyle.display !== "none" &&
+ submenuStyle.visibility === "visible" && Number(submenuStyle.opacity) !== 0;
+ });
+ if (!bounds || hasSubmenu) unsupportedMenu = true;
+ else menus.push(bounds);
+ } else {
+ occluders.push(element.getBoundingClientRect());
+ }
+ }
+ });
+ if (unsupportedMenu) return {visible: false};
+ const geometry = computeDesktopAVMapGeometry(rect, clips, occluders, menus);
+ if (geometry.visible) {
+ const bounds = geometry.bounds;
+ // 在主文档中命中检测,包括固定工具栏;原生子视图不属于此 DOM 树。
+ for (const x of [bounds.x + 0.5, bounds.x + bounds.width / 2, bounds.x + bounds.width - 0.5]) {
+ for (const y of [bounds.y + 0.5, bounds.y + bounds.height / 2, bounds.y + bounds.height - 0.5]) {
+ const top = doc.elementFromPoint(x, y);
+ if (!top || !container.contains(top)) {
+ return {visible: false};
+ }
+ }
+ }
+ }
+ return geometry;
+};
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index 4d9bf896f7..2486d0df1f 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -5,6 +5,14 @@ import {describe, it} from "node:test";
import * as ts from "typescript";
import * as protocol from "./protocol";
import * as unplacedMenu from "./unplacedMenu";
+import {computeDesktopAVMapGeometry, MapGeometry} from "./desktopGeometry";
+import * as desktopGeometryDOM from "./desktopGeometryDOM";
+import * as loadingBudget from "./loadingBudget";
+
+const visibleGeometry = (geometry: MapGeometry) => {
+ assert.ok(geometry.visible === true, "the fixture must produce visible geometry");
+ return geometry;
+};
const source = readFileSync(__dirname + "/desktopTransport.ts", "utf8");
const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {
@@ -19,7 +27,8 @@ const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {
const result: any = {};
const requireModule = (name: string) => {
if (name === "./protocol") { return protocol; }
- if (name === "./unplacedMenu") { return unplacedMenu; }
+ if (name === "./desktopGeometryDOM") { return desktopGeometryDOM; }
+ if (name === "./loadingBudget") { return loadingBudget; }
assert.equal(name, "electron");
assert.equal(browser, false, "browser must not import Electron");
return {ipcRenderer: ipc};
@@ -229,7 +238,7 @@ describe("desktop map transport", () => {
assert.deepEqual(browserWarnings, []);
});
it("clips CSS rectangles, preserves full logical size and never multiplies by display scale", () => {
- const compute = load({}).computeDesktopAVMapGeometry;
+ const compute = computeDesktopAVMapGeometry;
assert.deepEqual(compute({x: -20.5, y: 30, width: 200, height: 100},
[{x: 0, y: 0, width: 1000, height: 800}, {x: 10, y: 40, width: 100, height: 60}]),
{visible: true, bounds: {x: 11, y: 41, width: 98, height: 58},
@@ -283,16 +292,16 @@ describe("desktop map transport", () => {
globalThis.MutationObserver = oldMutation;
globalThis.ResizeObserver = oldResize;
}
- const compute = load({}).computeDesktopAVMapGeometry;
+ const compute = computeDesktopAVMapGeometry;
const rect = {x: 0, y: 0, width: 100, height: 100};
assert.equal(compute(rect, [{...rect, height: 1.5}]).visible, false);
- assert.equal(compute(rect, [{...rect, height: 2}]).bounds.height, 1);
+ assert.equal(visibleGeometry(compute(rect, [{...rect, height: 2}])).bounds.height, 1);
assert.equal(compute(rect, [{...rect, y: 20, height: 2.5}]).visible, false);
- assert.equal(compute(rect, [{...rect, y: 20, height: 3}]).bounds.height, 1);
- assert.deepEqual(compute(rect, [rect]).bounds, rect, "uncropped maps retain their complete bounds");
- assert.deepEqual(compute(rect, [{x: -10, y: -10, width: 120, height: 120}]).bounds, rect);
+ assert.equal(visibleGeometry(compute(rect, [{...rect, y: 20, height: 3}])).bounds.height, 1);
+ assert.deepEqual(visibleGeometry(compute(rect, [rect])).bounds, rect, "uncropped maps retain their complete bounds");
+ assert.deepEqual(visibleGeometry(compute(rect, [{x: -10, y: -10, width: 120, height: 120}])).bounds, rect);
const clip = {...rect, height: 50};
- assert.equal(compute(rect, [clip, clip, clip]).bounds.height, 49, "nested clips inset only once");
+ assert.equal(visibleGeometry(compute(rect, [clip, clip, clip])).bounds.height, 49, "nested clips inset only once");
const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");
assert.equal(parseMapGeometry(compute(rect, [{...rect, height: 2}]), 0.8, {width: 1000, height: 800}).visible, false);
});
@@ -303,7 +312,7 @@ describe("desktop map transport", () => {
assert.equal(await load({invoke: async () => { throw new Error("old main"); }}).isDesktopAVMapHostSupported(), false);
});
it("selects the largest safe rectangle around one owned menu and retains the full logical map", () => {
- const compute = load({}).computeDesktopAVMapGeometry;
+ const compute = computeDesktopAVMapGeometry;
const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");
const rect = {x: 10, y: 20, width: 400, height: 300};
const cases = [
@@ -314,8 +323,7 @@ describe("desktop map transport", () => {
{menu: {x: 160, y: 120, width: 100, height: 100}, bounds: {x: 10, y: 20, width: 149, height: 300}},
];
for (const {menu, bounds} of cases) {
- const geometry = compute(rect, [], [], [menu]);
- assert.equal(geometry.visible, true);
+ const geometry = visibleGeometry(compute(rect, [], [], [menu]));
assert.deepEqual(geometry.bounds, bounds);
assert.deepEqual(geometry.logicalSize, {width: rect.width, height: rect.height});
assert.deepEqual(geometry.crop, {x: bounds.x - rect.x, y: bounds.y - rect.y});
@@ -341,8 +349,8 @@ describe("desktop map transport", () => {
assert.deepEqual(compute({...rect, height: 100}, [], [], [{...rect, width: 360}]), {visible: false});
assert.deepEqual(compute(rect, [], [], [{...menu, x: NaN}]), {visible: false});
const fractional = {x: 10.25, y: 20.75, width: 400.5, height: 300.5};
- const geometry = compute(fractional, [{x: 30.5, y: 50.25, width: 340, height: 220}], [],
- [{x: 290.5, y: 30, width: 100, height: 290}]);
+ const geometry = visibleGeometry(compute(fractional, [{x: 30.5, y: 50.25, width: 340, height: 220}], [],
+ [{x: 290.5, y: 30, width: 100, height: 290}]));
assert.deepEqual(geometry.bounds, {x: 32, y: 52, width: 257, height: 217});
assert.deepEqual(geometry.crop, {x: 21.75, y: 31.25});
assert.deepEqual(geometry.logicalSize, {width: 400.5, height: 300.5});
@@ -471,7 +479,7 @@ describe("desktop map transport", () => {
assert.equal(unplacedMenu.isMapUnplacedMenu(menu, second), false);
});
it("preserves fractional geometry through native validation at every clipped edge and zoom", () => {
- const compute = load({}).computeDesktopAVMapGeometry;
+ const compute = computeDesktopAVMapGeometry;
const {parseMapGeometry} = require("../../../../../electron/mapHostPolicy");
const rect = {x: 155.55555555555554, y: 555.5555555555555, width: 1433.3333333333333, height: 480};
assert.ok(rect.y + rect.height - rect.y > rect.height, "the fixture must reproduce floating-point expansion");
@@ -489,8 +497,7 @@ describe("desktop map transport", () => {
width: rect.width - 32, height: rect.height - 72, cropX: 11, cropY: 31},
];
for (const entry of cases) {
- const geometry = compute(rect, entry.clips);
- assert.equal(geometry.visible, true);
+ const geometry = visibleGeometry(compute(rect, entry.clips));
assert.ok(geometry.bounds.width <= rect.width);
assert.ok(geometry.bounds.height <= rect.height);
assert.ok(Math.abs(geometry.bounds.width - entry.width) < 1e-9);
@@ -508,7 +515,7 @@ describe("desktop map transport", () => {
}
const widthRect = {...rect, x: rect.y, width: rect.height};
assert.ok(widthRect.x + widthRect.width - widthRect.x > widthRect.width);
- const geometry = compute(widthRect, []);
+ const geometry = visibleGeometry(compute(widthRect, []));
assert.equal(geometry.bounds.width, widthRect.width);
assert.equal(parseMapGeometry(geometry, 1.25, {width: 4000, height: 3000})?.visible, true);
});
@@ -604,7 +611,6 @@ describe("desktop map transport", () => {
const point = {id: "row", longitude: 1, latitude: 2, name: "private"};
f.host.setPoints([point], 1);
f.host.setTheme("dark");
- f.host.fit();
assert.equal(f.calls[0][1].credentials, undefined);
assert.match(f.calls[0][1].instanceID, /^[a-f0-9]{48}$/);
await f.created();
@@ -614,7 +620,7 @@ describe("desktop map transport", () => {
f.reply({type: "ready"});
assert.equal(f.ready(), 1);
const commands = f.calls.filter(([name]) => name === "siyuan-map-command").map(([, value]) => value);
- assert.deepEqual(commands.map((value) => value.type), ["setPoints", "theme", "fit"]);
+ assert.deepEqual(commands.map((value) => value.type), ["setPoints", "theme"]);
assert.equal(commands[0].points[0].name, undefined);
assert.equal(commands[1].theme, "dark");
f.reply({type: "markerClick", id: "row", revision: 0});
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index c81692dce1..7b2b62412b 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -2,114 +2,14 @@
import {ipcRenderer} from "electron";
/// #endif
import type {AVMapHost, AVMapHostOptions} from "./host";
-import {isMapUnplacedMenu} from "./unplacedMenu";
+import {MapGeometry} from "./desktopGeometry";
+import {readDesktopAVMapGeometry} from "./desktopGeometryDOM";
+import {AV_MAP_OWNER_TIMEOUT} from "./loadingBudget";
import {
AV_MAP_PROTOCOL_VERSION, AVMapCommand, AVMapErrorCode, AVMapPoint, isAVMapHostErrorCode, isAVMapProvider, isAVMapRevision,
isAVMapTheme, parseAVMapReply, sanitizeAVMapPoints,
} from "./protocol";
-interface MapRect { x: number; y: number; width: number; height: number; }
-type MapGeometry = {visible: false} | {
- visible: true; bounds: MapRect; logicalSize: {width: number; height: number}; crop: {x: number; y: number};
-};
-
-const intersects = (a: MapRect, b: MapRect) => a.x < b.x + b.width && b.x < a.x + a.width &&
- a.y < b.y + b.height && b.y < a.y + a.height;
-
-// 菜单打开时不展示难以操作的狭窄残片。
-const MIN_MENU_MAP_EDGE = 32;
-const MIN_MENU_MAP_AREA = 4096;
-
-// All coordinates stay in owner CSS pixels. Only the main process applies the owner zoom factor.
-export const computeDesktopAVMapGeometry = (rect: MapRect, clips: MapRect[], occluders: MapRect[] = [],
- menus: MapRect[] = []): MapGeometry => {
- if (![rect, ...clips, ...occluders, ...menus].every((item) => [item.x, item.y, item.width, item.height].every(Number.isFinite) &&
- item.width >= 0 && item.height >= 0)) {
- return {visible: false};
- }
- if (rect.width < 1 || rect.height < 1) {
- return {visible: false};
- }
- let left = rect.x, top = rect.y, right = rect.x + rect.width, bottom = rect.y + rect.height;
- clips.forEach((clip) => {
- left = Math.max(left, clip.x);
- top = Math.max(top, clip.y);
- right = Math.min(right, clip.x + clip.width);
- bottom = Math.min(bottom, clip.y + clip.height);
- });
- // 裁剪边缘内收一个 CSS 像素,避免半像素命中相邻控件;原生绘制区域与命中检测同步收窄。
- if (left > rect.x) left += 1;
- if (top > rect.y) top += 1;
- if (right < rect.x + rect.width) right -= 1;
- if (bottom < rect.y + rect.height) bottom -= 1;
- // 裁剪差值的浮点舍入不能使可见尺寸超过原始尺寸。
- let bounds = {x: left, y: top, width: Math.min(rect.width, right - left), height: Math.min(rect.height, bottom - top)};
- if (left < 0 || top < 0 || bounds.width < 1 || bounds.height < 1) {
- return {visible: false};
- }
- if (occluders.some((item) => item.width > 0 && item.height > 0 && intersects(bounds, item))) {
- return {visible: false};
- }
- const overlapping = menus.filter(item => item.width > 0 && item.height > 0 && intersects(bounds, item));
- if (overlapping.length > 1) return {visible: false};
- if (overlapping.length) {
- const menu = overlapping[0];
- const rightEdge = bounds.x + bounds.width, bottomEdge = bounds.y + bounds.height;
- // 只处理当前地图唯一的未定位菜单,在四个连续矩形中选择面积最大的安全区域。
- const candidates = [
- [bounds.x, bounds.y, Math.min(rightEdge, menu.x - 1), bottomEdge],
- [Math.max(bounds.x, menu.x + menu.width + 1), bounds.y, rightEdge, bottomEdge],
- [bounds.x, bounds.y, rightEdge, Math.min(bottomEdge, menu.y - 1)],
- [bounds.x, Math.max(bounds.y, menu.y + menu.height + 1), rightEdge, bottomEdge],
- ].map(([x, y, right, bottom]) => ({x: Math.ceil(x), y: Math.ceil(y),
- width: Math.floor(right) - Math.ceil(x), height: Math.floor(bottom) - Math.ceil(y)}))
- .filter(item => item.width >= MIN_MENU_MAP_EDGE && item.height >= MIN_MENU_MAP_EDGE &&
- item.width * item.height >= MIN_MENU_MAP_AREA);
- if (!candidates.length) return {visible: false};
- bounds = candidates.reduce((largest, item) => item.width * item.height > largest.width * largest.height ? item : largest);
- }
- return {visible: true, bounds, logicalSize: {width: rect.width, height: rect.height},
- crop: {x: bounds.x - rect.x, y: bounds.y - rect.y}};
-};
-
-const readMenuRect = (element: HTMLElement, style: CSSStyleDeclaration, scope: Window): MapRect | undefined => {
- // 无法用单个矩形可靠界定的主题效果仍走全隐藏路径。
- const measurable = (value: CSSStyleDeclaration) => value.transform === "none" && value.filter === "none" &&
- ["", "normal", "1"].includes(value.getPropertyValue("zoom")) &&
- [value.translate, value.rotate, value.scale].every(item => !item || item === "none");
- if (!measurable(style)) return;
- for (let parent = element.parentElement; parent; parent = parent.parentElement) {
- if (!measurable(scope.getComputedStyle(parent))) return;
- }
- const rect = element.getBoundingClientRect();
- let left = 0, right = 0, top = 0, bottom = 0;
- const shadows = style.boxShadow === "none" ? [] : style.boxShadow.split(/,(?![^()]*\))/);
- for (const shadow of shadows) {
- const parts = shadow.replace(/(?:rgba?|hsla?)\([\d\s.,%/+\-]+\)/, "").trim().split(/\s+/);
- const inset = parts[0] === "inset" || parts[parts.length - 1] === "inset";
- if (inset) parts.splice(parts[0] === "inset" ? 0 : parts.length - 1, 1);
- if (parts.length < 2 || parts.length > 4 || parts.some(value => !/^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;
- const [x, y, blur = 0, spread = 0] = parts.map(parseFloat);
- if (blur < 0) return;
- if (inset) continue;
- // 模糊阴影按两倍半径保守外扩,包含多层阴影、负偏移和边框外侧的描边。
- const extent = Math.max(0, blur * 2 + spread);
- left = Math.max(left, extent - x);
- right = Math.max(right, extent + x);
- top = Math.max(top, extent - y);
- bottom = Math.max(bottom, extent + y);
- }
- if (style.outlineStyle !== "none") {
- if (![style.outlineWidth, style.outlineOffset].every(value => /^-?(?:\d+\.?\d*|\.\d+)px$/.test(value))) return;
- const outline = Math.max(0, parseFloat(style.outlineWidth) + parseFloat(style.outlineOffset));
- left = Math.max(left, outline);
- right = Math.max(right, outline);
- top = Math.max(top, outline);
- bottom = Math.max(bottom, outline);
- }
- return {x: rect.x - left, y: rect.y - top, width: rect.width + left + right, height: rect.height + top + bottom};
-};
-
const getIPC = () => {
/// #if !BROWSER
return ipcRenderer;
@@ -170,100 +70,10 @@ export const isDesktopAVMapHostSupported = async (): Promise<boolean> => {
return false;
};
-const readGeometry = (container: HTMLElement): MapGeometry => {
- const doc = container.ownerDocument;
- const scope = doc.defaultView;
- if (!scope) {
- return {visible: false};
- }
- if (doc.hidden) {
- return {visible: false};
- }
- if (!container.isConnected) {
- return {visible: false};
- }
- if (!container.getClientRects().length) {
- return {visible: false};
- }
- const rect = container.getBoundingClientRect();
- const clips: MapRect[] = [{x: 0, y: 0, width: scope.innerWidth, height: scope.innerHeight}];
- for (let element: HTMLElement = container; element; element = element.parentElement) {
- const style = scope.getComputedStyle(element);
- if (style.display === "none" || style.visibility !== "visible" || Number(style.opacity) === 0 ||
- style.getPropertyValue("content-visibility") === "hidden") {
- return {visible: false};
- }
- if (element !== container && /hidden|clip|scroll|auto/.test(style.overflowX + style.overflowY)) {
- const bounds = element.getBoundingClientRect();
- const clipX = /hidden|clip|scroll|auto/.test(style.overflowX);
- const clipY = /hidden|clip|scroll|auto/.test(style.overflowY);
- const scaleX = element.offsetWidth ? bounds.width / element.offsetWidth : 1;
- const scaleY = element.offsetHeight ? bounds.height / element.offsetHeight : 1;
- clips.push({x: clipX ? bounds.x + element.clientLeft * scaleX : 0,
- y: clipY ? bounds.y + element.clientTop * scaleY : 0,
- width: clipX ? element.clientWidth * scaleX : scope.innerWidth,
- height: clipY ? element.clientHeight * scaleY : scope.innerHeight});
- }
- }
- const views = container.closest(".av[data-type='NodeAttributeView']")
- ?.querySelector<HTMLElement>(":scope > .av__container > .av__header > .av__views--fixed");
- if (views?.getClientRects().length) {
- const style = scope.getComputedStyle(views);
- const bounds = views.getBoundingClientRect();
- if (["fixed", "sticky"].includes(style.position) && style.display !== "none" &&
- style.visibility === "visible" && Number(style.opacity) !== 0 && intersects(rect, bounds)) {
- // 本数据库的固定页签栏遮住地图顶部时,只展示栏底部以下的区域。
- const top = Math.max(0, bounds.y + bounds.height);
- clips.push({x: 0, y: top, width: scope.innerWidth, height: Math.max(0, scope.innerHeight - top)});
- }
- }
- const occluders: MapRect[] = [];
- const menus: MapRect[] = [];
- let unsupportedMenu = false;
- // These are actual application overlay roots, not guesses based on arbitrary z-index values.
- doc.querySelectorAll<HTMLElement>(".b3-menu, .b3-dialog, .av__panel, .protyle-util, .protyle-toolbar, .block__popover, [popover]")
- .forEach((element) => {
- if (element.contains(container) || !element.getClientRects().length) {
- return;
- }
- const style = scope.getComputedStyle(element);
- if (style.display !== "none" && style.visibility === "visible" && Number(style.opacity) !== 0) {
- if (isMapUnplacedMenu(element, container)) {
- const bounds = readMenuRect(element, style, scope);
- const hasSubmenu = Array.from(element.querySelectorAll<HTMLElement>(".b3-menu__submenu"))
- .some(submenu => {
- const submenuStyle = scope.getComputedStyle(submenu);
- return submenu.getClientRects().length && submenuStyle.display !== "none" &&
- submenuStyle.visibility === "visible" && Number(submenuStyle.opacity) !== 0;
- });
- if (!bounds || hasSubmenu) unsupportedMenu = true;
- else menus.push(bounds);
- } else {
- occluders.push(element.getBoundingClientRect());
- }
- }
- });
- if (unsupportedMenu) return {visible: false};
- const geometry = computeDesktopAVMapGeometry(rect, clips, occluders, menus);
- if (geometry.visible) {
- const bounds = geometry.bounds;
- // Hit-test the owner's DOM (native child views are not in this tree), including sticky toolbars.
- for (const x of [bounds.x + 0.5, bounds.x + bounds.width / 2, bounds.x + bounds.width - 0.5]) {
- for (const y of [bounds.y + 0.5, bounds.y + bounds.height / 2, bounds.y + bounds.height - 0.5]) {
- const top = doc.elementFromPoint(x, y);
- if (!top || !container.contains(top)) {
- return {visible: false};
- }
- }
- }
- }
- return geometry;
-};
-
export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHostOptions): AVMapHost => {
const scope = container.ownerDocument.defaultView;
const ipc = getIPC();
- let destroyed = false, ready = false, created = false, pendingFit = false;
+ let destroyed = false, ready = false, created = false;
let instanceID = "", revision = -1, theme = options.theme;
let points: AVMapPoint[] = [];
let ids = new Set<string>();
@@ -292,7 +102,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
}
};
const checkGeometry = () => {
- const next = readGeometry(container);
+ const next = readDesktopAVMapGeometry(container);
const key = JSON.stringify(next);
if (key !== lastGeometry) {
lastGeometry = key;
@@ -388,10 +198,6 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
scope.clearTimeout(timeout);
postPoints();
send({...envelope(), type: "theme", theme});
- if (pendingFit) {
- send({...envelope(), type: "fit"});
- pendingFit = false;
- }
options.onReady?.();
} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {
options.onMarkerClick(reply.id, reply.revision);
@@ -411,11 +217,6 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
postPoints();
}
},
- fit: () => {
- if (!destroyed) {
- if (ready) { send({...envelope(), type: "fit"}); } else { pendingFit = true; }
- }
- },
resize: invalidate,
setTheme: (nextTheme) => {
if (!destroyed && isAVMapTheme(nextTheme)) {
@@ -439,8 +240,8 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
instanceID = Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
ipc.on("siyuan-map-reply", onReply);
scope.addEventListener("pagehide", destroy, {once: true});
- // 主进程先等待引导 30 秒,再为 SDK 两个 20 秒阶段保留 45 秒;这里只做更晚的失联兜底。
- timeout = scope.setTimeout(() => fail("hostReadyTimeout"), 90000);
+ // 主进程分别限制资源准备与地图就绪;此预算只处理主进程或 IPC 未能返回结果的情况。
+ 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});
@@ -448,7 +249,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
fail("hostCreateRejected");
return;
}
- // Creation can finish after disposal. Tell main again, even if the first destroy arrived too early.
+ // 创建可能在销毁后才完成;再次通知主进程,覆盖第一次销毁早于创建的情况。
if (destroyed) {
ipc.send("siyuan-map-destroy", envelope());
return;
diff --git a/app/src/protyle/render/av/map/host.test.ts b/app/src/protyle/render/av/map/host.test.ts
index e8b101ba66..e7bb46543a 100644
--- a/app/src/protyle/render/av/map/host.test.ts
+++ b/app/src/protyle/render/av/map/host.test.ts
@@ -7,6 +7,37 @@ import {isAVMapRuntimeIsolated} from "./hostRuntime";
describe("map host boundary", () => {
const cleanups: Array<() => void> = [];
afterEach(() => { cleanups.splice(0).reverse().forEach((cleanup) => cleanup()); });
+ it("preserves fixed preparation failures through the wrapper and strips unknown codes", async () => {
+ for (const input of ["sdkScriptLoadFailed", "sdkGlobalMissing", "https://private.invalid/?token=secret"]) {
+ const listeners = new Map<string, (event?: any) => void>();
+ const failures: string[] = [];
+ let removed = 0;
+ const iframe = {src: "", style: {}, contentWindow: {postMessage() {}}, setAttribute() {},
+ addEventListener() {}, remove() { removed++; }};
+ const scope = {location: {protocol: "https:", origin: "https://fixture.invalid"},
+ navigator: {userAgent: "Chromium"}, HTMLIFrameElement: {prototype: {}}, crypto: webcrypto,
+ setTimeout: () => 1, clearTimeout() {}, cancelAnimationFrame() {},
+ addEventListener: (name: string, listener: (event?: any) => void) => listeners.set(name, listener),
+ removeEventListener: (name: string) => listeners.delete(name)};
+ const container = {ownerDocument: {defaultView: scope, createElement: () => iframe,
+ addEventListener() {}, removeEventListener() {}}, appendChild() {}};
+ const host = createAVMapHost(container as unknown as HTMLElement, {provider: "openfreemap", theme: "light",
+ onMarkerClick() {}, onError: code => failures.push(code)});
+ cleanups.push(host.destroy);
+ await new Promise<void>(resolve => setImmediate(resolve));
+ const [instanceID, nonce] = iframe.src.split("#")[1].split(":");
+ const receive = listeners.get("message");
+ const data = {version: 1, instanceID, nonce, type: "wrapperHello"};
+ const event = {source: iframe.contentWindow, origin: scope.location.origin, ports: [] as MessagePort[], data};
+ receive({...event, data: Object.assign([], data)});
+ receive(event);
+ receive({...event, data: {...data, type: "bootstrapError", code: input, message: "secret"}});
+ assert.deepEqual(failures, [input.startsWith("sdk") ? input : "hostBootstrapFailed"]);
+ assert.equal(removed, 1);
+ receive({...event, data: {...data, type: "bootstrapError", code: input}});
+ assert.equal(failures.length, 1);
+ }
+ });
it("fails closed for Electron and unguarded native bridges but does not require credentialless", async () => {
const browser = {location: {protocol: "http:"}, navigator: {userAgent: "Chromium"},
HTMLIFrameElement: {prototype: {credentialless: false}}};
@@ -100,7 +131,6 @@ describe("map host boundary", () => {
data: {version: 1, type: "wrapperHello", instanceID, nonce}};
const point = {id: "row-1", longitude: 0, latitude: 0};
host.setPoints([{...point, title: "private"} as any], 1);
- host.fit();
onMessage({...handshake, source: {}});
onMessage({...handshake, origin: "https://attacker.invalid"});
onMessage({...handshake, data: {...handshake.data, nonce: "old"}});
@@ -113,7 +143,7 @@ describe("map host boundary", () => {
onMessage({...handshake, data: {...handshake.data, type: "bootstrapReady"}});
assert.equal(channels.length, 1);
assert.deepEqual([...timers.values()].map((timer) => timer.delay), [45000],
- "bootstrap completion starts a fresh budget covering both 20-second SDK phases");
+ "locked assets start a separate finite budget for map creation and readiness");
assert.equal(listeners.has("message"), false);
onMessage(handshake);
assert.equal(channels.length, 1);
@@ -141,7 +171,7 @@ describe("map host boundary", () => {
reply({type: "attributionClick", link: "maplibre"});
assert.deepEqual(links, ["maplibre"], "visible attribution remains clickable when the map top is cropped");
assert.deepEqual(port.messages.find((message) => message.type === "setPoints").points, [point]);
- assert.equal(port.messages.filter((message) => message.type === "fit").length, 1);
+ assert.equal(port.messages.some((message) => message.type === "fit"), false);
reply({type: "markerClick", id: "row-1", revision: 0});
reply({type: "markerClick", id: "missing", revision: 1});
reply({type: "markerClick", id: "row-1", revision: 1});
diff --git a/app/src/protyle/render/av/map/host.ts b/app/src/protyle/render/av/map/host.ts
index 530744bc2f..75b5fefaee 100644
--- a/app/src/protyle/render/av/map/host.ts
+++ b/app/src/protyle/render/av/map/host.ts
@@ -1,9 +1,10 @@
import {
AV_MAP_PROTOCOL_VERSION, AVMapAttributionLink, AVMapCommand, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapVisibility,
- isAVMapProvider, isAVMapRevision, isAVMapTheme, parseAVMapReply,
+ isAVMapBootstrapMessage, isAVMapLoadErrorCode, isAVMapProvider, isAVMapRevision, isAVMapTheme, parseAVMapReply,
sanitizeAVMapPoints,
} from "./protocol";
-import {getAVMapHostCapabilities, isAVMapBootstrapMessage} from "./hostCapabilities";
+import {getAVMapHostCapabilities} from "./hostCapabilities";
+import {AV_MAP_BOOTSTRAP_TIMEOUT, AV_MAP_HOST_READY_TIMEOUT} from "./loadingBudget";
export interface AVMapHostOptions {
provider: AVMapProvider;
@@ -17,7 +18,6 @@ export interface AVMapHostOptions {
export interface AVMapHost {
setPoints: (points: AVMapPoint[], revision: number) => void;
- fit: () => void;
resize: () => void;
setTheme: (theme: AVMapTheme) => void;
destroy: () => void;
@@ -93,7 +93,6 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
let points: AVMapPoint[] = [];
let ids = new Set<string>();
let theme = options.theme;
- let pendingFit = false;
let instanceID = "";
let nonce = "";
let nativeBoundary = false;
@@ -164,16 +163,16 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
return;
}
if (preparing && isAVMapBootstrapMessage(event.data, "bootstrapError", instanceID, nonce)) {
- fail("hostBootstrapFailed");
+ fail(isAVMapLoadErrorCode(event.data.code) ? event.data.code : "hostBootstrapFailed");
return;
}
if (!preparing || !isAVMapBootstrapMessage(event.data, "bootstrapReady", instanceID, nonce)) {
return;
}
scope.removeEventListener("message", onMessage);
- // SDK 脚本和地图初始化各有 20 秒预算,不能被之前的引导计时提前截断。
+ // 打包资源和 CSP 已准备完成;此预算仅保护后续地图创建与 load 就绪。
scope.clearTimeout(timeout);
- timeout = scope.setTimeout(() => fail("hostSDKTimeout"), 45000);
+ timeout = scope.setTimeout(() => fail("hostSDKTimeout"), AV_MAP_HOST_READY_TIMEOUT);
const channel = new MessageChannel();
port = channel.port1;
port.onmessage = (replyEvent) => {
@@ -186,10 +185,6 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
scope.clearTimeout(timeout);
postPoints();
send({...envelope(), type: "theme", theme});
- if (pendingFit) {
- send({...envelope(), type: "fit"});
- pendingFit = false;
- }
options.onReady?.();
tickVisibility();
} else if (reply?.type === "markerClick" && ready && reply.revision === revision && ids.has(reply.id)) {
@@ -204,7 +199,7 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
};
port.start();
iframe.contentWindow.postMessage({...envelope(), type: "connect", nonce}, scope.location.origin, [channel.port2]);
- // 端口建立后清除全局监听;外部 SDK 加载期间不再接受窗口消息。
+ // 端口建立后清除全局监听;地图初始化期间不再接受窗口消息。
send({...envelope(), type: "init", provider: options.provider, theme});
};
@@ -218,13 +213,6 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
ids = new Set(points.map((point) => point.id));
postPoints();
},
- fit: () => {
- if (ready) {
- send({...envelope(), type: "fit"});
- } else {
- pendingFit = true;
- }
- },
resize: () => {
if (ready) {
send({...envelope(), type: "resize"});
@@ -276,7 +264,7 @@ export const createAVMapHost = (container: HTMLElement, options: AVMapHostOption
scope.addEventListener("message", onMessage);
scope.addEventListener("pagehide", destroy, {once: true});
container.ownerDocument.addEventListener("visibilitychange", updateVisibility);
- timeout = scope.setTimeout(() => fail("hostBootstrapTimeout"), 30000);
+ timeout = scope.setTimeout(() => fail("hostBootstrapTimeout"), AV_MAP_BOOTSTRAP_TIMEOUT);
container.appendChild(iframe);
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(host.resize);
diff --git a/app/src/protyle/render/av/map/hostCapabilities.ts b/app/src/protyle/render/av/map/hostCapabilities.ts
index e5ad476608..cbec5a85c2 100644
--- a/app/src/protyle/render/av/map/hostCapabilities.ts
+++ b/app/src/protyle/render/av/map/hostCapabilities.ts
@@ -36,9 +36,3 @@ export const getAVMapHostCapabilities = async (scope: Window): Promise<AVMapHost
scope.clearTimeout(timer);
}
};
-
-export const isAVMapBootstrapMessage = (value: unknown, type: string, instanceID: string, nonce: string): boolean => {
- const input = value as Record<string, unknown>;
- return !!input && typeof input === "object" && input.version === 1 && input.type === type &&
- input.instanceID === instanceID && input.nonce === nonce;
-};
diff --git a/app/src/protyle/render/av/map/hostRuntime.test.ts b/app/src/protyle/render/av/map/hostRuntime.test.ts
index f38da8260b..23db419788 100644
--- a/app/src/protyle/render/av/map/hostRuntime.test.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.test.ts
@@ -76,6 +76,25 @@ describe("isolated map runtime lifecycle", () => {
assert.equal(replies.length, 0);
assert.equal(calls.filter((call) => call[0] === "destroy").length, 1);
});
+ it("fits only the first nonempty snapshot and rejects the removed external fit command", async () => {
+ const {port, adapter, calls, send} = fixture();
+ const stop = startAVMapRuntime(port as unknown as MessagePort, "one", "openfreemap", {} as HTMLElement,
+ async () => adapter);
+ await send({type: "init", provider: "openfreemap", theme: "light"});
+ await send({type: "fit"});
+ await send({type: "setPoints", revision: 0, points: []});
+ assert.equal(calls.some(call => call[0] === "fit"), false);
+ await send({type: "setPoints", revision: 1, points: [{id: "row-1", longitude: 0, latitude: 0}]});
+ assert.equal(calls.filter(call => call[0] === "fit").length, 1);
+ await send({type: "fit"});
+ await send({type: "visibility", visible: false});
+ await send({type: "resize"});
+ await send({type: "visibility", visible: true});
+ await send({type: "setPoints", revision: 2, points: []});
+ await send({type: "setPoints", revision: 3, points: [{id: "row-2", longitude: 20, latitude: 20}]});
+ assert.equal(calls.filter(call => call[0] === "fit").length, 1);
+ stop();
+ });
it("passes only fixed attribution identifiers and visibility booleans through the runtime", async () => {
const {port, adapter, replies, calls, send} = fixture();
let callbacks: AVMapAdapterCallbacks;
@@ -143,7 +162,7 @@ describe("isolated map runtime lifecycle", () => {
});
describe("isolated map bootstrap ordering", () => {
- const bootstrapFixture = (desktop = false, native = false) => {
+ const bootstrapFixture = (desktop = false, native = false, timing = {setTimeout, clearTimeout}) => {
const instanceID = "a".repeat(48);
const nonce = "b".repeat(48);
const events: any[] = [];
@@ -152,7 +171,7 @@ describe("isolated map bootstrap ordering", () => {
"document", {get() { throw new Error("opaque sandbox"); }});
const scope: any = {
origin: "null", location: {hash: `#${instanceID}:${nonce}`, search: "?provider=openfreemap"},
- parent, setTimeout, clearTimeout, maplibregl: {},
+ parent, ...timing, maplibregl: {Map() {}, AttributionControl() {}, setWorkerUrl() {}},
fetch: async () => ({ok: true, text: async () => "worker"}),
addEventListener: (name: string, callback: (event?: any) => void) => listeners.set(name, callback),
removeEventListener: (name: string) => listeners.delete(name),
@@ -170,7 +189,8 @@ describe("isolated map bootstrap ordering", () => {
if (native) {
scope.JSAndroid = {};
}
- const port = {onmessage: null as any, start() {}, close() {}, postMessage: (message: unknown) => events.push(message)};
+ const port = {onmessage: null as any, closed: 0, start() {}, close() { this.closed++; },
+ postMessage: (message: unknown) => events.push(message)};
connectAVMapRuntime(scope);
const message = (type: string, values: Record<string, unknown> = {}, ports: unknown[] = []) => ({
source: desktop ? scope : parent, origin: "https://fixture.invalid", ports,
@@ -225,4 +245,73 @@ describe("isolated map bootstrap ordering", () => {
assert.equal(listeners.has("message"), false);
listeners.get("pagehide")();
});
+ it("reports preparation failures once with fixed codes and closes a transferred desktop port", async () => {
+ for (const desktop of [false, true]) {
+ for (const failure of ["script", "global", "policy"]) {
+ const {scope, events, listeners, port, message} = bootstrapFixture(desktop);
+ if (failure === "global" || failure === "script") scope.maplibregl = undefined;
+ const append = scope.document.head.appendChild;
+ scope.document.head.appendChild = (element: any) => {
+ if (failure === "script" && element.tag === "script") {
+ queueMicrotask(() => element.onerror?.(new Error("https://private.invalid/?token=secret")));
+ } else if (failure === "policy" && element.tag === "meta") {
+ throw new Error("https://private.invalid/?token=secret");
+ } else append(element);
+ };
+ const receive = listeners.get("message");
+ const request = desktop ? message("siyuan-map-desktop-connect", {provider: "openfreemap"}, [port]) : message("prepare");
+ receive(request);
+ await tick();
+ const code = failure === "script" ? "sdkScriptLoadFailed" : failure === "global" ? "sdkGlobalMissing" : "hostUnavailable";
+ const replies = events.filter(event => event.type === "error" || event.type === "bootstrapError");
+ assert.equal(replies.length, 1);
+ assert.equal(replies[0].code, code);
+ assert.equal(JSON.stringify(events).includes("secret"), false);
+ assert.equal(events.some(event => event.type === "bootstrapReady"), false);
+ assert.equal(listeners.has("message"), false);
+ assert.equal(port.closed, desktop ? 1 : 0);
+ receive(request);
+ listeners.get("pagehide")();
+ assert.equal(events.filter(event => event.type === "error" || event.type === "bootstrapError").length, 1);
+ }
+ }
+ });
+ it("keeps slow CSS and script loading inside one bootstrap deadline and ignores late completion", async () => {
+ for (const desktop of [false, true]) {
+ let now = 0, nextTimer = 0, removed = 0;
+ const timers = new Map<number, {at: number; callback: () => void}>();
+ const timing = {
+ setTimeout: (callback: () => void, delay: number) => {
+ timers.set(++nextTimer, {at: now + delay, callback});
+ return nextTimer;
+ }, clearTimeout: (id: number) => timers.delete(id),
+ } as unknown as {setTimeout: typeof setTimeout; clearTimeout: typeof clearTimeout};
+ const {scope, events, listeners, port, message} = bootstrapFixture(desktop, false, timing);
+ const assets: any[] = [];
+ scope.document.createElement = (tag: string) => ({tag, remove() { removed++; }});
+ scope.document.head.appendChild = (element: any) => assets.push(element);
+ listeners.get("message")(desktop ? message("siyuan-map-desktop-connect", {provider: "openfreemap"}, [port]) : message("prepare"));
+ assert.equal(assets[0].tag, "link");
+ now = 19000;
+ assets[0].onload();
+ await tick();
+ assert.equal(assets[1].tag, "script");
+ const lateLoad = assets[1].onload;
+ now = 30000;
+ for (const [id, timer] of Array.from(timers)) {
+ if (timer.at <= now) { timers.delete(id); timer.callback(); }
+ }
+ await tick();
+ assert.equal(assets[1].onload, null);
+ assert.equal(assets[1].onerror, null);
+ assert.equal(removed, 1);
+ assert.equal(timers.size, 0);
+ assert.equal(port.closed, desktop ? 1 : 0);
+ lateLoad();
+ await tick();
+ assert.equal(events.some(event => event.type === "bootstrapReady" || event.type === "error"), false);
+ assert.equal(assets.some(element => element.tag === "meta"), false);
+ assert.equal(listeners.has("message"), false);
+ }
+ });
});
diff --git a/app/src/protyle/render/av/map/hostRuntime.ts b/app/src/protyle/render/av/map/hostRuntime.ts
index 76319d0778..3b4bedcd81 100644
--- a/app/src/protyle/render/av/map/hostRuntime.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.ts
@@ -1,11 +1,11 @@
import {
- AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, getAVMapLoadErrorCode, isAVMapAttributionLink, isAVMapHandshake, isAVMapProvider,
+ AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, getAVMapLoadErrorCode, isAVMapAttributionLink, isAVMapBootstrapMessage, isAVMapProvider,
parseAVMapCommand,
} from "./protocol";
import {AVMapAdapter, AVMapAdapterCallbacks} from "./providers";
import {loadAVMapAdapter} from "./providersLoader";
import {prepareAVMapBootstrap} from "./bootstrap";
-import {isAVMapBootstrapMessage} from "./hostCapabilities";
+import {AV_MAP_BOOTSTRAP_TIMEOUT} from "./loadingBudget";
export type AVMapAdapterFactory = (init: AVMapInit, container: HTMLElement,
callbacks: AVMapAdapterCallbacks, signal: AbortSignal) => Promise<AVMapAdapter>;
@@ -104,8 +104,6 @@ export const startAVMapRuntime = (port: MessagePort, instanceID: string, provide
}
} else if (adapter && command.type === "theme") {
adapter.setTheme(command.theme);
- } else if (adapter && command.type === "fit") {
- adapter.fit();
} else if (adapter && command.type === "resize") {
adapter.resize();
} else if (adapter && command.type === "visibility") {
@@ -172,12 +170,13 @@ export const connectAVMapRuntime = (scope: Window) => {
} else {
scope.parent.postMessage({...envelope, type: "bootstrapReady"}, "*");
}
- } catch (_error) {
+ } catch (error) {
if (!closed) {
+ const code = getAVMapLoadErrorCode(error) || "hostUnavailable";
if (desktop) {
- desktopPort?.postMessage({version: AV_MAP_PROTOCOL_VERSION, type: "error", instanceID, code: "hostUnavailable"});
+ desktopPort?.postMessage({version: AV_MAP_PROTOCOL_VERSION, type: "error", instanceID, code});
} else {
- scope.parent.postMessage({...envelope, type: "bootstrapError"}, "*");
+ scope.parent.postMessage({...envelope, type: "bootstrapError", code}, "*");
}
}
cleanup();
@@ -209,7 +208,7 @@ export const connectAVMapRuntime = (scope: Window) => {
void prepare();
return;
}
- if (!locked || event.ports.length !== 1 || !isAVMapHandshake(event.data, "connect", instanceID, nonce)) {
+ if (!locked || event.ports.length !== 1 || !isAVMapBootstrapMessage(event.data, "connect", instanceID, nonce)) {
return;
}
connected = true;
@@ -217,7 +216,7 @@ export const connectAVMapRuntime = (scope: Window) => {
scope.clearTimeout(timer);
destroy = startAVMapRuntime(event.ports[0], instanceID, provider, scope.document.getElementById("map"));
};
- const timer = scope.setTimeout(cleanup, 30000);
+ const timer = scope.setTimeout(cleanup, AV_MAP_BOOTSTRAP_TIMEOUT);
scope.addEventListener("message", onConnect);
scope.addEventListener("pagehide", cleanup, {once: true});
if (!desktop) {
diff --git a/app/src/protyle/render/av/map/loadingBudget.ts b/app/src/protyle/render/av/map/loadingBudget.ts
new file mode 100644
index 0000000000..c210ae2e7a
--- /dev/null
+++ b/app/src/protyle/render/av/map/loadingBudget.ts
@@ -0,0 +1,8 @@
+// CSS、脚本和 worker 各阶段受限,同时受宿主准备总期限约束。
+export const AV_MAP_ASSET_TIMEOUT = 20000;
+export const AV_MAP_READY_TIMEOUT = 20000;
+// 文档、资源准备和 CSP 锁定共用此预算;bootstrapReady 后仅等待地图就绪。
+export const AV_MAP_BOOTSTRAP_TIMEOUT = 30000;
+export const AV_MAP_HOST_READY_TIMEOUT = 45000;
+// 桌面创建请求与 IPC 失联的最外层兜底,不延长各阶段的独立期限。
+export const AV_MAP_OWNER_TIMEOUT = 90000;
diff --git a/app/src/protyle/render/av/map/locate.test.ts b/app/src/protyle/render/av/map/locate.test.ts
index 2f84e3c3b0..712bf3dc0a 100644
--- a/app/src/protyle/render/av/map/locate.test.ts
+++ b/app/src/protyle/render/av/map/locate.test.ts
@@ -5,6 +5,7 @@ import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
import * as locateState from "../locateState";
import {isTableLikeView} from "../viewType";
+import {requireFixture} from "./testDOM";
const setup = (open: () => Promise<boolean> = () => Promise.resolve(true)) => {
const opened: unknown[] = [];
@@ -22,6 +23,9 @@ const setup = (open: () => Promise<boolean> = () => Promise.resolve(true)) => {
"../../../dialog/message": {showMessage: (message: string) => messages.push(message)},
"../../../util/highlightById": {scrollCenter: (_protyle: unknown, element: unknown) => scrolled.push(element)},
"./backlinkScroll": {scrollBacklinkTarget: () => false},
+ "../../../constants": {}, "./publishState": {}, "./readonlyState": {}, "./gallery/style": {},
+ "../../wysiwyg/transaction": {}, "../../util/clear": {}, "./rangeSelect": {}, "./virtualScroll": {},
+ "./locateView": {}, "./color": {},
"../openDatabaseRow": {openDatabaseRowByData: (_protyle: unknown, record: unknown) => {
opened.push(record);
return open();
@@ -31,7 +35,7 @@ const setup = (open: () => Promise<boolean> = () => Promise.resolve(true)) => {
const exports = {};
runInNewContext(transpileModule(readFileSync(path, "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
- }).outputText, {exports, require: (id: string) => modules[id] || {}, window: {siyuan: {languages}}});
+ }).outputText, {exports, require: requireFixture(modules), window: {siyuan: {languages}}});
return exports;
};
modules["./map/openRecord"] = load("src/protyle/render/av/map/openRecord.ts");
diff --git a/app/src/protyle/render/av/map/protocol.test.ts b/app/src/protyle/render/av/map/protocol.test.ts
index fc2779e272..59d1cc0bb1 100644
--- a/app/src/protyle/render/av/map/protocol.test.ts
+++ b/app/src/protyle/render/av/map/protocol.test.ts
@@ -2,9 +2,11 @@ import * as assert from "node:assert/strict";
import {describe, it} from "node:test";
import {
AV_MAP_ATTRIBUTION_LINKS, AV_MAP_MERCATOR_MAX_LATITUDE, AVMapLoadError, getAVMapLoadErrorCode,
- isAVMapHandshake, isAVMapHostErrorCode, isAVMapProjectionSupported,
+ isAVMapBootstrapMessage, isAVMapHostErrorCode, isAVMapProjectionSupported,
parseAVMapCommand, parseAVMapReply, sanitizeAVMapPoints,
} from "./protocol";
+import {AV_MAP_BOOTSTRAP_TIMEOUT, AV_MAP_HOST_READY_TIMEOUT, AV_MAP_OWNER_TIMEOUT, AV_MAP_READY_TIMEOUT} from "./loadingBudget";
+import {getAVMapLockedPolicy} from "./bootstrap";
describe("isolated map protocol", () => {
const point = {id: "row-1", longitude: 0, latitude: 0};
@@ -99,10 +101,11 @@ describe("isolated map protocol", () => {
});
it("requires the exact nonce and instance during its one-time handshake", () => {
const handshake = {version: 1, type: "hello", instanceID: "instance", nonce: "nonce"};
- assert.equal(isAVMapHandshake(handshake, "hello", "instance", "nonce"), true);
+ assert.equal(isAVMapBootstrapMessage(handshake, "hello", "instance", "nonce"), true);
for (const invalid of [{nonce: "old"}, {instanceID: "other"}, {version: 0}, {type: "connect"}]) {
- assert.equal(isAVMapHandshake({...handshake, ...invalid}, "hello", "instance", "nonce"), false);
+ assert.equal(isAVMapBootstrapMessage({...handshake, ...invalid}, "hello", "instance", "nonce"), false);
}
+ assert.equal(isAVMapBootstrapMessage(structuredClone(Object.assign([], handshake)), "hello", "instance", "nonce"), false);
});
it("admits only fixed loading stages and never treats arbitrary SDK exceptions as controlled errors", () => {
for (const code of ["sdkScriptLoadFailed", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout"] as const) {
@@ -135,3 +138,111 @@ describe("isolated map protocol", () => {
}
});
});
+
+describe("shared owner and runtime protocol corpus", () => {
+ const {parseMapCommand, parseMapReply} = require("../../../../../electron/mapHostPolicy");
+ const envelope = {version: 1, instanceID: "one"};
+ const point = {id: "row-1", longitude: 0, latitude: 0};
+ const commands = [
+ (value: unknown) => parseAVMapCommand(value, "one", "openfreemap"),
+ (value: unknown) => parseMapCommand(value, "one"),
+ ];
+ const replies = [(value: unknown) => parseAVMapReply(value, "one"), (value: unknown) => parseMapReply(value, "one")];
+ it("keeps desktop and web preparation and readiness budgets aligned and finite", () => {
+ const {MAP_HOST_BOOTSTRAP_TIMEOUT, MAP_HOST_READY_TIMEOUT} = require("../../../../../electron/mapHostManager");
+ assert.equal(MAP_HOST_BOOTSTRAP_TIMEOUT, AV_MAP_BOOTSTRAP_TIMEOUT);
+ assert.equal(MAP_HOST_READY_TIMEOUT, AV_MAP_HOST_READY_TIMEOUT);
+ assert.ok(AV_MAP_READY_TIMEOUT < AV_MAP_HOST_READY_TIMEOUT);
+ assert.ok(AV_MAP_BOOTSTRAP_TIMEOUT + AV_MAP_HOST_READY_TIMEOUT < AV_MAP_OWNER_TIMEOUT);
+ assert.ok(Number.isFinite(AV_MAP_OWNER_TIMEOUT));
+ });
+ it("only removes resource permissions when the initial desktop policy is locked", () => {
+ const {createMapContentSecurityPolicy, mapHostFiles} = require("../../../../../electron/mapHostPolicy");
+ const origin = "https://fixture.invalid";
+ const directives = (policy: string) => new Map(policy.split(";").map(value => value.trim().split(/\s+/))
+ .filter(([name]) => name).map(([name, ...values]) => [name, values]));
+ const initial = directives(createMapContentSecurityPolicy(origin));
+ const locked = directives(getAVMapLockedPolicy("openfreemap"));
+ assert.deepEqual(initial.get("sandbox"), ["allow-scripts"]);
+ assert.deepEqual(initial.get("frame-ancestors"), ["'none'"]);
+ assert.deepEqual(locked.get("script-src"), ["'none'"]);
+ assert.deepEqual(locked.get("connect-src"), ["https://tiles.openfreemap.org"]);
+ for (const directive of ["script-src", "connect-src", "img-src", "style-src", "font-src", "worker-src",
+ "frame-src", "object-src", "base-uri", "form-action"]) {
+ const before = initial.get(directive), after = locked.get(directive);
+ assert.ok(before && after);
+ for (const source of after) assert.ok(source === "'none'" || before.includes(source), `${directive}: ${source}`);
+ }
+ for (const sources of locked.values()) assert.equal(sources.some(source => source.includes("fixture.invalid")), false);
+ const localSources = [...initial.values()].flat().filter(source => source.startsWith(origin));
+ assert.equal(localSources.length, 5);
+ for (const source of localSources) assert.ok(Object.prototype.hasOwnProperty.call(mapHostFiles, new URL(source).pathname));
+ assert.deepEqual(locked.get("frame-src"), ["'none'"], "child-src must not permit subframe navigation");
+ assert.deepEqual(locked.get("worker-src"), ["blob:"], "only prepared blob workers remain available");
+ });
+ it("uses the same cloned command corpus while copying only allowed fields", () => {
+ const setPoints = {...envelope, type: "setPoints", revision: 1, points: [point]};
+ const valid = [setPoints, {...envelope, type: "theme", theme: "light"}, {...envelope, type: "theme", theme: "dark"},
+ {...envelope, type: "resize"}, {...envelope, type: "destroy"}];
+ for (const command of valid) {
+ for (const parse of commands) {
+ assert.deepEqual(parse(structuredClone({...command, secret: "private"})), command);
+ for (const malformed of [null, 1, "command", Object.assign([], command), {...command, version: 2},
+ {...command, instanceID: "other"}, {...command, type: "fit"}, {...command, type: "unknown"}]) {
+ assert.equal(parse(structuredClone(malformed)), undefined);
+ }
+ }
+ }
+ for (const revision of [-1, 1.5, NaN, Infinity, "1", null, Number.MAX_SAFE_INTEGER + 1]) {
+ for (const parse of commands) assert.equal(parse({...setPoints, revision}), undefined);
+ }
+ for (const points of [null, {}, "points"]) {
+ for (const parse of commands) assert.equal(parse({...setPoints, points}), undefined);
+ }
+ for (const theme of [null, {}, "auto", "LIGHT"]) {
+ for (const parse of commands) assert.equal(parse({...envelope, type: "theme", theme}), undefined);
+ }
+ });
+ it("rejects malformed point shapes, duplicates and nonprojectable values identically", () => {
+ const valid = [point,
+ {id: "west", longitude: -180, latitude: -AV_MAP_MERCATOR_MAX_LATITUDE},
+ {id: "east", longitude: 180, latitude: AV_MAP_MERCATOR_MAX_LATITUDE}];
+ const malformed = [null, 1, "point", Object.assign([], {...point, id: "array"}),
+ ...[{longitude: NaN}, {longitude: Infinity}, {longitude: "0"}, {longitude: 181}, {latitude: null},
+ {latitude: -86}, {latitude: 90}, {latitude: -Infinity}, {id: ""}, {id: "x".repeat(129)},
+ {id: "<script>"}, {coordinateSystem: undefined}].map(value => ({...point, ...value}))];
+ const command = {...envelope, type: "setPoints", revision: 0,
+ points: [...valid.map(value => ({...value, name: "private", originalInput: "secret"})), point, ...malformed]};
+ for (const parse of commands) {
+ assert.deepEqual(parse(structuredClone(command)), {...envelope, type: "setPoints", revision: 0, points: valid});
+ const points = Array.from({length: 10001}, (_, i) => ({...point, id: `row-${i}`}));
+ assert.deepEqual(parse({...command, points}).points, points.slice(0, 10000));
+ }
+ });
+ it("uses the same reply corpus and keeps privileged bootstrap and visibility directions explicit", () => {
+ const valid = [{...envelope, type: "ready"}, {...envelope, type: "markerClick", id: point.id, revision: 0},
+ ...AV_MAP_ATTRIBUTION_LINKS.openfreemap.map(({id: link}) => ({...envelope, type: "attributionClick", link})),
+ {...envelope, type: "error", code: "mapUnavailable"}];
+ for (const reply of valid) {
+ for (const parse of replies) {
+ assert.deepEqual(parse(structuredClone({...reply, url: "private", message: "secret"})), reply);
+ for (const malformed of [null, Object.assign([], reply), {...reply, version: 2}, {...reply, instanceID: "other"},
+ {...reply, type: "unknown"}]) assert.equal(parse(structuredClone(malformed)), undefined);
+ }
+ }
+ for (const parse of replies) {
+ assert.equal(parse({...envelope, type: "error", code: "unknown"}), undefined);
+ assert.equal(parse({...envelope, type: "markerClick", id: [], revision: 0}), undefined);
+ assert.equal(parse({...envelope, type: "markerClick", id: point.id, revision: NaN}), undefined);
+ }
+ const bootstrapped = {...envelope, type: "bootstrapReady"};
+ assert.deepEqual(parseMapReply(bootstrapped, "one"), bootstrapped);
+ assert.equal(parseAVMapReply(bootstrapped, "one"), undefined);
+ const visibility = {...envelope, type: "visibility", visible: true};
+ assert.deepEqual(parseAVMapCommand(visibility, "one"), visibility);
+ assert.equal(parseMapCommand(visibility, "one"), undefined);
+ const init = {...envelope, type: "init", provider: "openfreemap", theme: "light"};
+ assert.deepEqual(parseAVMapCommand(init, "one"), init);
+ assert.equal(parseMapCommand(init, "one"), undefined);
+ });
+});
diff --git a/app/src/protyle/render/av/map/protocol.ts b/app/src/protyle/render/av/map/protocol.ts
index d1269d1e0a..77076153d5 100644
--- a/app/src/protyle/render/av/map/protocol.ts
+++ b/app/src/protyle/render/av/map/protocol.ts
@@ -30,7 +30,7 @@ export const isAVMapHostErrorCode = (value: unknown): value is AVMapHostErrorCod
const mapLoadErrorCodes = new Set<AVMapLoadErrorCode>([
"sdkScriptLoadFailed", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout",
]);
-const isAVMapLoadErrorCode = (value: unknown): value is AVMapLoadErrorCode =>
+export const isAVMapLoadErrorCode = (value: unknown): value is AVMapLoadErrorCode =>
typeof value === "string" && mapLoadErrorCodes.has(value as AVMapLoadErrorCode);
// 内部加载阶段只保留固定错误码,不保存 SDK 原始异常、地址或凭据。
@@ -78,7 +78,7 @@ export type AVMapCommand = AVMapInit |
(AVMapEnvelope & {type: "setPoints"; revision: number; points: AVMapPoint[]}) |
(AVMapEnvelope & {type: "theme"; theme: AVMapTheme}) |
(AVMapEnvelope & {type: "visibility"} & AVMapVisibility) |
- (AVMapEnvelope & {type: "fit" | "resize" | "destroy"});
+ (AVMapEnvelope & {type: "resize" | "destroy"});
export type AVMapReply = (AVMapEnvelope & {type: "ready"}) |
(AVMapEnvelope & {type: "attributionClick"; link: AVMapAttributionLink}) |
@@ -107,7 +107,7 @@ export const sanitizeAVMapPoints = (input: unknown): AVMapPoint[] => {
const ids = new Set<string>();
const result: AVMapPoint[] = [];
input.slice(0, AV_MAP_MAX_POINTS).forEach((point) => {
- if (!point || typeof point !== "object" || "coordinateSystem" in point || !isAVMapIdentifier(point.id) || ids.has(point.id) ||
+ if (!point || typeof point !== "object" || Array.isArray(point) || "coordinateSystem" in point || !isAVMapIdentifier(point.id) || ids.has(point.id) ||
typeof point.longitude !== "number" || !Number.isFinite(point.longitude) ||
point.longitude < -180 || point.longitude > 180 ||
typeof point.latitude !== "number" || !Number.isFinite(point.latitude) ||
@@ -159,7 +159,6 @@ export const parseAVMapCommand = (value: unknown, instanceID: string, provider?:
const viewport = parseAVMapViewport(input.viewport);
return viewport ? {...envelope, type: "visibility", visible: true, viewport} : undefined;
}
- case "fit":
case "resize":
case "destroy":
return {...envelope, type: input.type};
@@ -188,7 +187,11 @@ export const parseAVMapReply = (value: unknown, instanceID: string): AVMapReply
}
};
-export const isAVMapHandshake = (value: unknown, type: "hello" | "connect", instanceID: string, nonce: string): boolean => {
+type AVMapBootstrapMessageType = "hello" | "wrapperHello" | "prepare" | "connect" |
+ "bootstrapReady" | "bootstrapError" | "siyuan-map-desktop-connect";
+
+export const isAVMapBootstrapMessage = (value: unknown, type: AVMapBootstrapMessageType,
+ instanceID: string, nonce: string): boolean => {
const input = asRecord(value);
return !!input && input.type === type && input.version === AV_MAP_PROTOCOL_VERSION &&
input.instanceID === instanceID && input.nonce === nonce;
diff --git a/app/src/protyle/render/av/map/providers.test.ts b/app/src/protyle/render/av/map/providers.test.ts
index 0d608c873a..6a097a7e17 100644
--- a/app/src/protyle/render/av/map/providers.test.ts
+++ b/app/src/protyle/render/av/map/providers.test.ts
@@ -3,6 +3,13 @@ import {test} from "node:test";
import {AV_MAP_OPENFREEMAP_STYLE, createAVMapAdapter} from "./providers";
import {AV_MAP_ATTRIBUTION_LINKS} from "./protocol";
+const {AJAXError, Evented} = require("maplibre-gl");
+
+// 瓦片数据形状依照 TileManager._loadTile;事件冒泡和 HTTP 异常使用实际 SDK 实现。
+const tileError = (status: number) => ({type: "error", sourceId: "fixture",
+ error: new AJAXError(status, "Fixture HTTP status", "https://fixture.invalid/tile", new Blob()),
+ tile: {state: "errored", tileID: {canonical: {z: 2, x: 1, y: 1}}}});
+
const fixture = () => {
const instances: any[] = [];
const calls: Array<[string, ...any[]]> = [];
@@ -51,7 +58,7 @@ const fixture = () => {
LngLatBounds: class LngLatBounds extends SDKObject {}, AttributionControl: class AttributionControl extends SDKObject {}};
const container = {ownerDocument: doc, querySelector: () => attribution,
replaceChildren() { calls.push(["clear"]); }};
- return {sdk, calls, instances, container: container as unknown as HTMLElement, attribution, frames, events, doc, scope, rect,
+ return {sdk, calls, instances, container: container as unknown as HTMLElement, attribution, frames, events, documentEvents, doc, scope, rect,
load: () => instances[0].callbacks.get("load")(),
advance: (milliseconds: number) => {
now += milliseconds;
@@ -248,3 +255,129 @@ test("removed providers cannot create a map", () => {
assert.equal(calls.length, 0);
}
});
+
+test("fully visible viewport changes preserve the continuous attribution display clock", () => {
+ const f = fixture();
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
+ f.load();
+ adapter.setVisible(true, visibleViewport);
+ f.advance(0);
+ f.advance(4000);
+ adapter.setVisible(true, {...visibleViewport, width: 790});
+ f.advance(1000);
+ assert.equal(f.attribution.open, false, "five uninterrupted visible seconds include a viewport resize");
+ adapter.destroy();
+});
+
+test("a simulated SDK tile 503 after load preserves the ready map", () => {
+ const f = fixture();
+ const errors: string[] = [];
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {
+ onMarkerClick() {}, onError: code => { errors.push(code); adapter.destroy(); },
+ });
+ f.load();
+ const source = new Evented();
+ const map = new Evented();
+ source.setEventedParent(map, {sourceId: "fixture"});
+ map.on("error", f.instances[0].callbacks.get("error"));
+ const event = tileError(503);
+ source.fire("error", {error: event.error, tile: event.tile});
+ assert.deepEqual(errors, []);
+ assert.equal(f.calls.filter(call => call[0] === "remove").length, 0);
+ adapter.destroy();
+});
+
+test("only recognized temporary tile HTTP errors after the first load preserve the map", () => {
+ for (const status of [408, 429, 500, 502, 503, 504]) {
+ const f = fixture();
+ const errors: string[] = [];
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {
+ onMarkerClick() {}, onError: code => errors.push(code),
+ });
+ const error = f.instances[0].callbacks.get("error");
+ error(tileError(status));
+ assert.deepEqual(errors, ["mapUnavailable"], "the same failure before load is fatal");
+ f.load();
+ error(tileError(status));
+ assert.deepEqual(errors, ["mapUnavailable"]);
+ adapter.destroy();
+ error(tileError(status));
+ assert.deepEqual(errors, ["mapUnavailable"], "late SDK errors cannot resurrect a destroyed map");
+ }
+});
+
+test("ready maps still report startup, source, worker, authorization and unknown errors safely", () => {
+ const variants = [undefined, {}, {error: new Error("private worker failure")},
+ ...[0, 401, 403, 404, 501, 505].map(tileError),
+ {...tileError(503), tile: undefined}, {...tileError(503), sourceId: ""},
+ {...tileError(503), error: {status: "503", message: "private URL"}},
+ {...tileError(503), tile: {state: "loaded", tileID: {canonical: {z: 2, x: 1, y: 1}}}},
+ ...[{z: -1, x: 0, y: 0}, {z: 26, x: 1, y: 1}, {z: 2.5, x: 1, y: 1},
+ {z: 2, x: 4, y: 1}, {z: 2, x: 1, y: Infinity}, {z: "2", x: 1, y: 1}]
+ .map(canonical => ({...tileError(503), tile: {state: "errored", tileID: {canonical}}})),
+ ];
+ for (const event of variants) {
+ const f = fixture();
+ const errors: string[] = [];
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {
+ onMarkerClick() {}, onError: code => { errors.push(code); adapter.destroy(); },
+ });
+ f.load();
+ f.instances[0].callbacks.get("error")(event);
+ assert.deepEqual(errors, ["mapUnavailable"]);
+ assert.equal(f.calls.filter(call => call[0] === "remove").length, 1);
+ }
+});
+
+test("viewport clipping and occlusion reset accumulated time, including between animation frames", () => {
+ const f = fixture();
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
+ f.load(); adapter.setVisible(true, visibleViewport); f.advance(0); f.advance(4000);
+ adapter.setVisible(true, {...visibleViewport, width: 290});
+ adapter.setVisible(true, visibleViewport);
+ f.advance(0); f.advance(1000);
+ assert.equal(f.attribution.open, true, "brief clipping interrupts continuous display");
+ f.doc.elementFromPoint = () => f.container;
+ f.advance(0);
+ f.doc.elementFromPoint = () => f.attribution;
+ f.advance(0); f.advance(4999);
+ assert.equal(f.attribution.open, true);
+ f.advance(1);
+ assert.equal(f.attribution.open, false);
+ adapter.destroy();
+});
+
+test("destruction cancels pending attribution time and late DOM or SDK callbacks", () => {
+ const f = fixture();
+ const adapter = createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}});
+ f.load(); adapter.setVisible(true, visibleViewport); f.advance(0); f.advance(4000);
+ const tick = [...f.frames.values()][0];
+ const click = f.events.get("click");
+ const drag = f.instances[0].callbacks.get("drag");
+ adapter.destroy();
+ assert.equal(f.frames.size, 0);
+ assert.equal(f.events.size, 0);
+ tick(10000);
+ click({target: {closest: (selector: string) => selector === "summary" ? {} : null}, isTrusted: true,
+ button: 0, preventDefault() {}, stopImmediatePropagation() {}});
+ drag();
+ assert.equal(f.attribution.open, true);
+ assert.equal(f.frames.size, 0);
+});
+
+test("attribution initialization failures clean the already created map and partial listeners", () => {
+ for (const stage of ["control", "missingDOM", "eventRegistration", "initialState"]) {
+ const f = fixture();
+ const failure = () => { throw new Error("fixture initialization failure"); };
+ if (stage === "control") f.sdk.Map.prototype.addControl = failure;
+ if (stage === "missingDOM") f.container.querySelector = (): null => null;
+ if (stage === "eventRegistration") f.sdk.Map.prototype.on = failure;
+ if (stage === "initialState") f.attribution.classList.toggle = failure;
+ assert.throws(() => createAVMapAdapter("openfreemap", f.sdk, f.container, {onMarkerClick() {}, onError() {}}));
+ assert.equal(f.calls.filter(call => call[0] === "remove").length, 1, stage);
+ assert.equal(f.calls.filter(call => call[0] === "clear").length, 1, stage);
+ assert.equal(f.events.size, 0, stage);
+ assert.equal(f.documentEvents.size, 0, stage);
+ assert.equal(f.frames.size, 0, stage);
+ }
+});
diff --git a/app/src/protyle/render/av/map/providers.ts b/app/src/protyle/render/av/map/providers.ts
index 2e2cdc45c3..258949acce 100644
--- a/app/src/protyle/render/av/map/providers.ts
+++ b/app/src/protyle/render/av/map/providers.ts
@@ -1,10 +1,24 @@
import {
- AV_MAP_ATTRIBUTION_LINKS, AVMapAttributionLink, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapViewport,
+ AVMapAttributionLink, AVMapErrorCode, AVMapPoint, AVMapProvider, AVMapTheme, AVMapViewport,
sanitizeAVMapPoints,
} from "./protocol";
+import {AVMapAttributionController, createAVMapAttribution} from "./attribution";
export const AV_MAP_OPENFREEMAP_STYLE = "https://tiles.openfreemap.org/styles/liberty";
+const retryableTileStatuses = new Set([408, 429, 500, 502, 503, 504]);
+const isRecoverableTileError = (event: any): boolean => {
+ const tile = event?.tile;
+ const canonical = tile?.tileID?.canonical;
+ // MapLibre 的瓦片错误带有源标识和失败瓦片;其他启动、样式或 worker 错误仍交给宿主处理。
+ return event?.type === "error" && typeof event.sourceId === "string" && event.sourceId.trim().length > 0 &&
+ tile?.state === "errored" && canonical && typeof canonical === "object" && !Array.isArray(canonical) &&
+ Number.isInteger(canonical.z) && canonical.z >= 0 && canonical.z <= 25 &&
+ Number.isInteger(canonical.x) && canonical.x >= 0 && canonical.x < 2 ** canonical.z &&
+ Number.isInteger(canonical.y) && canonical.y >= 0 && canonical.y < 2 ** canonical.z &&
+ retryableTileStatuses.has(event.error?.status);
+};
+
export interface AVMapAdapter {
setPoints: (points: AVMapPoint[], revision: number) => void;
fit: () => void;
@@ -21,7 +35,7 @@ export interface AVMapAdapterCallbacks {
onAttributionClick?: (link: AVMapAttributionLink) => void;
}
-// The SDK is loaded only in the isolated web entry, never in the main interface.
+// SDK 仅加载于隔离页面,不进入主界面。
export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container: HTMLElement,
callbacks: AVMapAdapterCallbacks): AVMapAdapter => {
if (provider !== "openfreemap") throw new Error("invalidConfiguration");
@@ -33,111 +47,45 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
removeMarkers.forEach(remove => remove());
removeMarkers = [];
};
- const error = () => {
- if (!destroyed) callbacks.onError("mapUnavailable");
+ const error = (event: unknown) => {
+ if (!destroyed && !(loaded && isRecoverableTileError(event))) callbacks.onError("mapUnavailable");
};
- const doc = container.ownerDocument;
- const scope = doc.defaultView;
const map = new sdk.Map({container, style: AV_MAP_OPENFREEMAP_STYLE, center: [0, 0], zoom: 1,
attributionControl: false, trackResize: false});
- const maplibre = AV_MAP_ATTRIBUTION_LINKS[provider].find(link => link.id === "maplibre");
- map.addControl(new sdk.AttributionControl({compact: true,
- customAttribution: `<a href="${maplibre.href}" target="_blank">${maplibre.label}</a>`}));
- const attribution = container.querySelector<HTMLDetailsElement>(".maplibregl-ctrl-attrib");
- const attributionText = attribution.querySelector<HTMLElement>(".maplibregl-ctrl-attrib-inner");
- let loaded = false, visible = false, expanded = true, automatic = true;
- let viewport: AVMapViewport;
- let frame = 0, visibleSince: number;
- const syncAttribution = () => {
- // MapLibre 的紧凑控件同时使用 details 状态和此 CSS 类。
- attribution.open = expanded;
- attribution.classList.toggle("maplibregl-compact-show", expanded);
- };
- const stopCollapse = () => {
- scope.cancelAnimationFrame(frame);
- frame = 0;
- visibleSince = undefined;
- };
- const attributionVisible = () => {
- if (!viewport || doc.hidden || !attributionText.getClientRects().length || !attributionText.textContent?.trim()) return false;
- const rect = attribution.getBoundingClientRect();
- if (rect.width <= 0 || rect.height <= 0 || rect.left < 0 || rect.top < 0 ||
- rect.right > scope.innerWidth || rect.bottom > scope.innerHeight ||
- rect.left < viewport.x || rect.top < viewport.y || rect.right > viewport.x + viewport.width ||
- rect.bottom > viewport.y + viewport.height) return false;
- // 紧凑控件的圆角属于透明区域,遮挡检查应命中实际展示的版权文字。
- const textRect = attributionText.getBoundingClientRect();
- if (textRect.width <= 0 || textRect.height <= 0) return false;
- return [textRect.left + 1, textRect.right - 1].every(x => [textRect.top + 1, textRect.bottom - 1].every(y =>
- attribution.contains(doc.elementFromPoint(x, y))));
- };
- const tickAttribution = (now: number) => {
- frame = 0;
- if (destroyed || !automatic || !loaded || !visible || doc.hidden) return;
- if (attributionVisible()) {
- if (visibleSince === undefined) visibleSince = now;
- if (now - visibleSince >= 5000) {
- automatic = false;
- expanded = false;
- syncAttribution();
- return;
- }
- } else {
- visibleSince = undefined;
- }
- frame = scope.requestAnimationFrame(tickAttribution);
- };
- const updateVisibility = () => {
- stopCollapse();
- if (!destroyed && automatic && loaded && visible && !doc.hidden) {
- frame = scope.requestAnimationFrame(tickAttribution);
- }
- };
- const onAttributionInteraction = (event: Event) => {
- if (!event.isTrusted) return;
- automatic = false;
- stopCollapse();
- };
- const onAttributionClick = (event: MouseEvent) => {
- const target = event.target as Element;
- const anchor = target.closest<HTMLAnchorElement>("a");
- const summary = target.closest("summary");
- if (!anchor && !summary) return;
- // 不向供应商文档授予导航或弹窗权限。
- event.preventDefault();
- event.stopImmediatePropagation();
- if (destroyed || !event.isTrusted || event.button !== 0) return;
- if (summary) {
- // 本地展开不依赖跨宿主可见性消息或外链所需的瞬时激活状态。
- onAttributionInteraction(event);
- expanded = !expanded;
- syncAttribution();
- } else if (visible && attribution.contains(anchor) &&
- (scope.navigator as Navigator & {userActivation?: {isActive: boolean}}).userActivation?.isActive) {
- onAttributionInteraction(event);
- const link = AV_MAP_ATTRIBUTION_LINKS[provider].find(item => item.href === anchor.getAttribute("href"));
- if (link) callbacks.onAttributionClick?.(link.id);
- }
- };
- attribution.addEventListener("click", onAttributionClick, true);
- attribution.addEventListener("auxclick", onAttributionClick, true);
- attribution.addEventListener("pointerdown", onAttributionInteraction, true);
- attribution.addEventListener("keydown", onAttributionInteraction, true);
- doc.addEventListener("visibilitychange", updateVisibility);
- // MapLibre 拖动时会收起署名,保留首次展示时间及用户主动选择的展开状态。
- map.on("drag", syncAttribution);
- map.on("resize", syncAttribution);
- syncAttribution();
+ let attribution: AVMapAttributionController;
+ let loaded = false;
const onReady = () => {
- if (!destroyed) {
+ if (!destroyed && !loaded) {
loaded = true;
- syncAttribution();
- updateVisibility();
+ attribution.onReady();
callbacks.onReady?.();
}
};
- map.on("error", error);
- map.on("load", onReady);
+ const destroy = () => {
+ if (destroyed) return;
+ destroyed = true;
+ try {
+ attribution?.destroy();
+ map.off("load", onReady);
+ map.off("error", error);
+ cleanMarkers();
+ points = [];
+ } finally {
+ try {
+ map.remove();
+ } finally {
+ container.replaceChildren();
+ }
+ }
+ };
+ try {
+ attribution = createAVMapAttribution(provider, sdk, map, container, callbacks.onAttributionClick);
+ map.on("error", error);
+ map.on("load", onReady);
+ } catch (error) {
+ destroy();
+ throw error;
+ }
return {
setPoints: (input, nextRevision) => {
@@ -172,30 +120,7 @@ export const createAVMapAdapter = (provider: AVMapProvider, sdk: any, container:
setTheme: theme => {
if (!destroyed) container.ownerDocument.documentElement.dataset.theme = theme;
},
- setVisible: (nextVisible, nextViewport) => {
- if (!destroyed && (visible !== nextVisible || JSON.stringify(viewport) !== JSON.stringify(nextViewport))) {
- visible = nextVisible;
- viewport = nextViewport;
- updateVisibility();
- }
- },
- destroy: () => {
- if (destroyed) return;
- destroyed = true;
- stopCollapse();
- attribution.removeEventListener("click", onAttributionClick, true);
- attribution.removeEventListener("auxclick", onAttributionClick, true);
- attribution.removeEventListener("pointerdown", onAttributionInteraction, true);
- attribution.removeEventListener("keydown", onAttributionInteraction, true);
- doc.removeEventListener("visibilitychange", updateVisibility);
- map.off("drag", syncAttribution);
- map.off("resize", syncAttribution);
- map.off("load", onReady);
- cleanMarkers();
- points = [];
- map.off("error", error);
- map.remove();
- container.replaceChildren();
- },
+ setVisible: attribution.setVisible,
+ destroy,
};
};
diff --git a/app/src/protyle/render/av/map/providersLoader.test.ts b/app/src/protyle/render/av/map/providersLoader.test.ts
index 581a2db6a3..e1a853ff96 100644
--- a/app/src/protyle/render/av/map/providersLoader.test.ts
+++ b/app/src/protyle/render/av/map/providersLoader.test.ts
@@ -3,9 +3,12 @@ import {test} from "node:test";
import {AVMapInit, AVMapLoadError} from "./protocol";
import {loadAVMapAdapter} from "./providersLoader";
import {getAVMapLockedPolicy, prepareAVMapBootstrap} from "./bootstrap";
+import {AV_MAP_ASSET_TIMEOUT, AV_MAP_READY_TIMEOUT} from "./loadingBudget";
-const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?: boolean; mapError?: boolean} = {}) => {
+const fixture = (options: {ready?: boolean; assetFailure?: boolean; scriptFailure?: boolean; missingSDK?: boolean;
+ mapError?: boolean; controlError?: boolean; manualAssets?: boolean; policyFailure?: boolean} = {}) => {
const requested: any[] = [];
+ const elements: any[] = [];
let destroyed = 0;
class FakeMap {
constructor() {
@@ -16,7 +19,7 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
if (options.ready !== false && type === "load") queueMicrotask(callback);
}
off() {}
- addControl() {}
+ addControl() { if (options.controlError) throw new Error("private control failure"); }
remove() { destroyed++; }
}
const scope: any = {
@@ -33,9 +36,12 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
addEventListener() {}, removeEventListener() {},
createElement: (tag: string) => ({tag, remove() {}}),
head: {appendChild: (element: any) => {
+ elements.push(element);
requested.push({tag: element.tag, src: element.src, href: element.href, referrerPolicy: element.referrerPolicy,
policy: element.content});
- if (element.tag !== "meta") queueMicrotask(() => options.assetFailure ? element.onerror?.() : element.onload?.());
+ if (element.tag === "meta" && options.policyFailure) throw new Error("private policy failure");
+ if (element.tag !== "meta" && !options.manualAssets) queueMicrotask(() =>
+ options.assetFailure || options.scriptFailure && element.tag === "script" ? element.onerror?.() : element.onload?.());
}},
};
scope.document = document;
@@ -43,7 +49,7 @@ const fixture = (options: {ready?: boolean; assetFailure?: boolean; missingSDK?:
classList: {toggle() {}}, addEventListener() {}, removeEventListener() {},
querySelector: () => ({}),
})} as unknown as HTMLElement;
- return {scope, requested, container, destroyed: () => destroyed};
+ return {scope, requested, elements, container, destroyed: () => destroyed};
};
const init: AVMapInit = {version: 1, instanceID: "fixture", type: "init", provider: "openfreemap", theme: "light"};
const callbacks = {onMarkerClick() {}, onError() {}};
@@ -93,12 +99,155 @@ test("locked policy removes local access and permits only the tile origin", () =
test("missing assets or SDK never create a map", async () => {
for (const options of [{assetFailure: true}, {missingSDK: true}]) {
const {scope, requested, destroyed} = fixture(options);
- await assert.rejects(prepareAVMapBootstrap(scope, "openfreemap", new AbortController().signal), /hostUnavailable/);
+ await assert.rejects(prepareAVMapBootstrap(scope, "openfreemap", new AbortController().signal), (error: any) => {
+ if (options.missingSDK) {
+ assert.ok(error instanceof AVMapLoadError);
+ assert.equal(error.code, "sdkGlobalMissing");
+ } else {
+ assert.equal(error.message, "hostUnavailable");
+ }
+ return true;
+ });
assert.equal(requested.some(request => request.mapCreated || request.worker), false);
assert.equal(destroyed(), 0);
}
});
+test("script failures and missing SDK globals expose only the controlled diagnostics", async () => {
+ for (const options of [{scriptFailure: true}, {missingSDK: true}]) {
+ const {scope, requested} = fixture(options);
+ await assert.rejects(prepareAVMapBootstrap(scope, "openfreemap", new AbortController().signal), (error: unknown) => {
+ assert.ok(error instanceof AVMapLoadError);
+ assert.equal(error.code, options.scriptFailure ? "sdkScriptLoadFailed" : "sdkGlobalMissing");
+ assert.equal(error.message, "Map loading failed");
+ return true;
+ });
+ assert.equal(requested.some(request => request.url || request.mapCreated || request.worker || request.tag === "meta"), false);
+ }
+});
+
+const flush = () => new Promise(resolve => setImmediate(resolve));
+const controlledTimers = (scope: any) => {
+ let serial = 0;
+ const pending = new Map<number, {callback: () => void; delay: number}>();
+ scope.setTimeout = (callback: () => void, delay: number) => {
+ pending.set(++serial, {callback, delay});
+ return serial;
+ };
+ scope.clearTimeout = (id: number) => pending.delete(id);
+ return pending;
+};
+
+test("each packaged asset is bounded and CSP cannot lock before the worker body finishes", async () => {
+ const f = fixture({manualAssets: true});
+ const timers = controlledTimers(f.scope);
+ let finishBody: (source: string) => void;
+ f.scope.fetch = async () => ({ok: true, text: () => new Promise<string>(resolve => { finishBody = resolve; })});
+ const pending = prepareAVMapBootstrap(f.scope, "openfreemap", new AbortController().signal);
+ assert.equal(timers.size, 1);
+ assert.equal([...timers.values()][0].delay, AV_MAP_ASSET_TIMEOUT);
+ assert.deepEqual(f.elements.map(element => element.tag), ["link"]);
+ f.elements[0].onload();
+ await flush();
+ assert.deepEqual(f.elements.map(element => element.tag), ["link", "script"]);
+ assert.equal(timers.size, 1);
+ f.elements[1].onload();
+ await flush();
+ assert.equal(timers.size, 1, "the worker response body remains inside the asset deadline");
+ assert.equal(f.requested.some(request => request.policy || request.mapCreated || request.worker), false);
+ finishBody("/* fixture worker */");
+ const dispose = await pending;
+ assert.equal(f.elements.at(-1).tag, "meta");
+ assert.equal(timers.size, 0);
+ dispose();
+});
+
+test("abort during slow CSS or script removes handlers and cannot lock CSP from a late load", async () => {
+ for (const stage of ["link", "script"]) {
+ const f = fixture({manualAssets: true});
+ const timers = controlledTimers(f.scope);
+ const abort = new AbortController();
+ const pending = prepareAVMapBootstrap(f.scope, "openfreemap", abort.signal);
+ if (stage === "script") {
+ f.elements[0].onload();
+ await flush();
+ }
+ const element = f.elements.at(-1);
+ const lateLoad = element.onload;
+ abort.abort();
+ await assert.rejects(pending, /hostUnavailable/);
+ lateLoad();
+ assert.equal(element.onload, null);
+ assert.equal(element.onerror, null);
+ assert.equal(timers.size, 0);
+ assert.equal(f.requested.some(request => request.policy || request.mapCreated || request.worker || request.url), false);
+ }
+});
+
+test("worker header/body timeout and abort settle immediately and ignore late results", async () => {
+ for (const stage of ["headers", "body"]) for (const cause of ["timeout", "abort"]) {
+ const f = fixture();
+ const timers = controlledTimers(f.scope);
+ const abort = new AbortController();
+ let finishWorker: () => void;
+ let requestSignal: AbortSignal;
+ f.scope.fetch = async (_url: string, options: RequestInit) => {
+ requestSignal = options.signal;
+ if (stage === "headers") {
+ return new Promise(resolve => { finishWorker = () => resolve({ok: true, text: async () => "/* too late */"}); });
+ }
+ return {ok: true, text: () => new Promise<string>(resolve => { finishWorker = () => resolve("/* too late */"); })};
+ };
+ const pending = prepareAVMapBootstrap(f.scope, "openfreemap", abort.signal);
+ await flush();
+ assert.equal(timers.size, 1);
+ if (cause === "timeout") [...timers.values()][0].callback();
+ else abort.abort();
+ await assert.rejects(pending, /hostUnavailable/);
+ assert.equal(requestSignal.aborted, true);
+ assert.equal(timers.size, 0);
+ finishWorker();
+ await flush();
+ assert.equal(f.requested.some(request => request.policy || request.mapCreated || request.worker), false);
+ await assert.rejects(loadAVMapAdapter(init, f.container, callbacks, new AbortController().signal), /hostUnavailable/);
+ }
+});
+
+test("control initialization failure disposes the map and revokes its prepared worker", async () => {
+ const f = fixture({controlError: true});
+ const signal = new AbortController().signal;
+ await prepareAVMapBootstrap(f.scope, "openfreemap", signal);
+ const revoked: string[] = [];
+ const original = URL.revokeObjectURL;
+ URL.revokeObjectURL = url => { revoked.push(url); original(url); };
+ try {
+ await assert.rejects(loadAVMapAdapter(init, f.container, callbacks, signal), (error: unknown) => {
+ assert.ok(error instanceof AVMapLoadError);
+ assert.equal(error.code, "mapCreationFailed");
+ return true;
+ });
+ assert.equal(f.destroyed(), 1);
+ assert.deepEqual(revoked, [f.requested.find(request => request.worker).worker]);
+ await assert.rejects(loadAVMapAdapter(init, f.container, callbacks, signal), /hostUnavailable/);
+ } finally {
+ URL.revokeObjectURL = original;
+ }
+});
+
+test("failed worker or CSP preparation cannot leave usable prepared assets", async () => {
+ for (const stage of ["workerResponse", "workerBody", "workerThrow", "policy"]) {
+ const f = fixture({policyFailure: stage === "policy"});
+ const timers = controlledTimers(f.scope);
+ if (stage === "workerResponse") f.scope.fetch = async () => ({ok: false});
+ if (stage === "workerBody") f.scope.fetch = async () => ({ok: true, text: async () => { throw new Error("private body"); }});
+ if (stage === "workerThrow") f.scope.fetch = () => { throw new Error("private request"); };
+ await assert.rejects(prepareAVMapBootstrap(f.scope, "openfreemap", new AbortController().signal), /hostUnavailable/);
+ assert.equal(timers.size, 0);
+ await assert.rejects(loadAVMapAdapter(init, f.container, callbacks, new AbortController().signal), /hostUnavailable/);
+ assert.equal(f.requested.some(request => request.mapCreated || request.worker), false);
+ }
+});
+
test("removed providers cannot load assets or initialize an adapter", async () => {
for (const provider of ["amap", "tencent", "baidu"]) {
const {scope, requested, container} = fixture();
@@ -126,7 +275,11 @@ test("construction and ready failures return controlled stages", async () => {
const signal = new AbortController().signal;
await prepareAVMapBootstrap(scope, "openfreemap", signal);
let timer: () => void;
- scope.setTimeout = (callback: () => void) => { timer = callback; return 1; };
+ scope.setTimeout = (callback: () => void, delay: number) => {
+ assert.equal(delay, AV_MAP_READY_TIMEOUT);
+ timer = callback;
+ return 1;
+ };
scope.clearTimeout = () => {};
const pending = loadAVMapAdapter(init, container, callbacks, signal);
const rejected = assert.rejects(pending, (error: unknown) => {
diff --git a/app/src/protyle/render/av/map/providersLoader.ts b/app/src/protyle/render/av/map/providersLoader.ts
index d2c64c2591..0f9ac53160 100644
--- a/app/src/protyle/render/av/map/providersLoader.ts
+++ b/app/src/protyle/render/av/map/providersLoader.ts
@@ -1,5 +1,6 @@
import {AVMapInit, AVMapLoadError, AVMapLoadErrorCode, AVMapProvider, getAVMapLoadErrorCode, isAVMapProvider} from "./protocol";
import {AVMapAdapter, AVMapAdapterCallbacks, createAVMapAdapter} from "./providers";
+import {AV_MAP_ASSET_TIMEOUT, AV_MAP_READY_TIMEOUT} from "./loadingBudget";
interface AVMapPreparedAssets {
locked: boolean;
@@ -11,7 +12,8 @@ interface AVMapPreparedAssets {
const preparedAssets = new WeakMap<Window, AVMapPreparedAssets>();
-const loadAsset = (scope: Window, element: HTMLScriptElement | HTMLLinkElement, signal: AbortSignal): Promise<void> =>
+const loadAsset = (scope: Window, element: HTMLScriptElement | HTMLLinkElement, signal: AbortSignal,
+ code?: AVMapLoadErrorCode): Promise<void> =>
new Promise((resolve, reject) => {
let settled = false;
const finish = (success: boolean) => {
@@ -25,11 +27,11 @@ const loadAsset = (scope: Window, element: HTMLScriptElement | HTMLLinkElement,
resolve();
} else {
element.remove();
- reject(new Error("hostUnavailable"));
+ reject(code && !signal.aborted ? new AVMapLoadError(code) : new Error("hostUnavailable"));
}
};
const abort = () => finish(false);
- const timer = scope.setTimeout(abort, 20000);
+ const timer = scope.setTimeout(abort, AV_MAP_ASSET_TIMEOUT);
signal.addEventListener("abort", abort, {once: true});
element.onload = () => finish(true);
element.onerror = abort;
@@ -41,7 +43,41 @@ const loadAsset = (scope: Window, element: HTMLScriptElement | HTMLLinkElement,
}
});
-// Only packaged assets are prepared here; no Map, Worker or blob exists before CSP is locked.
+const loadWorkerSource = (scope: Window, signal: AbortSignal): Promise<string> => new Promise((resolve, reject) => {
+ const request = new AbortController();
+ let settled = false;
+ const finish = (source?: string) => {
+ if (settled) return;
+ settled = true;
+ scope.clearTimeout(timer);
+ signal.removeEventListener("abort", abort);
+ if (source === undefined) {
+ request.abort();
+ reject(new Error("hostUnavailable"));
+ } else {
+ resolve(source);
+ }
+ };
+ const abort = () => finish();
+ const timer = scope.setTimeout(abort, AV_MAP_ASSET_TIMEOUT);
+ signal.addEventListener("abort", abort, {once: true});
+ if (signal.aborted) {
+ abort();
+ return;
+ }
+ void Promise.resolve().then(() => {
+ if (request.signal.aborted) throw new Error("hostUnavailable");
+ return scope.fetch("/stage/build/map/maplibre-gl-csp-worker.js", {
+ credentials: "omit", mode: "cors", cache: "no-store", referrerPolicy: "no-referrer", signal: request.signal,
+ });
+ }).then(async response => {
+ if (settled) return;
+ if (!response.ok) throw new Error("hostUnavailable");
+ finish(await response.text());
+ }).catch(abort);
+});
+
+// 此阶段仅准备随应用打包的资源;CSP 锁定前不创建 Map、Worker 或 blob。
export const prepareAVMapAssets = async (scope: Window, provider: AVMapProvider, signal: AbortSignal) => {
if (!isAVMapProvider(provider) || preparedAssets.has(scope) || signal.aborted) {
throw new Error("hostUnavailable");
@@ -64,17 +100,18 @@ export const prepareAVMapAssets = async (scope: Window, provider: AVMapProvider,
script.src = "/stage/build/map/maplibre-gl.js";
script.referrerPolicy = "no-referrer";
script.async = true;
- await loadAsset(scope, script, signal);
- const response = await scope.fetch("/stage/build/map/maplibre-gl-csp-worker.js", {
- credentials: "omit", mode: "cors", cache: "no-store", referrerPolicy: "no-referrer", signal,
- });
- if (!response.ok) throw new Error("hostUnavailable");
- assets.workerSource = await response.text();
+ await loadAsset(scope, script, signal, "sdkScriptLoadFailed");
assets.sdk = (scope as unknown as Record<string, any>).maplibregl;
- if (!assets.sdk || signal.aborted) throw new Error("hostUnavailable");
+ if (signal.aborted) throw new Error("hostUnavailable");
+ if (!assets.sdk || [assets.sdk.Map, assets.sdk.AttributionControl, assets.sdk.setWorkerUrl]
+ .some(value => typeof value !== "function")) throw new AVMapLoadError("sdkGlobalMissing");
+ assets.workerSource = await loadWorkerSource(scope, signal);
+ if (signal.aborted) throw new Error("hostUnavailable");
return {lock: () => { assets.locked = true; }, destroy: assets.destroy};
- } catch (_error) {
+ } catch (error) {
assets.destroy();
+ const code = getAVMapLoadErrorCode(error);
+ if (code) throw new AVMapLoadError(code);
throw new Error("hostUnavailable");
}
};
@@ -87,7 +124,7 @@ export const loadAVMapAdapter = async (init: AVMapInit, container: HTMLElement,
throw new Error("hostUnavailable");
}
try {
- // Worker and blob inherit the locked policy, with no local network authority.
+ // Worker 和 blob 继承已锁定的策略,不具有本地网络访问权限。
assets.workerURL = URL.createObjectURL(new Blob([assets.workerSource], {type: "text/javascript"}));
assets.workerSource = undefined;
const sdk = assets.sdk;
@@ -111,7 +148,7 @@ export const loadAVMapAdapter = async (init: AVMapInit, container: HTMLElement,
}
};
const abort = () => finish(false);
- const timer = scope.setTimeout(() => finish(false, "mapReadyTimeout"), 20000);
+ const timer = scope.setTimeout(() => finish(false, "mapReadyTimeout"), AV_MAP_READY_TIMEOUT);
signal.addEventListener("abort", abort, {once: true});
try {
adapter = createAVMapAdapter(init.provider, sdk, container, {...callbacks,
diff --git a/app/src/protyle/render/av/map/render.test.ts b/app/src/protyle/render/av/map/render.test.ts
index d97060e669..9d977fa612 100644
--- a/app/src/protyle/render/av/map/render.test.ts
+++ b/app/src/protyle/render/av/map/render.test.ts
@@ -7,53 +7,35 @@ import * as state from "./state";
import * as protocol from "./protocol";
import * as escape from "../../../../util/escape";
import type {AVMapHost, AVMapHostOptions} from "./host";
-
-class ElementStub {
- className = "";
- innerHTML = "";
- textContent = "";
- isConnected = true;
- disabled = false;
- value = "";
- readonly children = new Map<string, ElementStub>();
- readonly events = new Map<string, () => void>();
- readonly classes = new Set<string>();
- readonly attributes = new Map<string, string>();
- readonly classList = {add: (...names: string[]) => names.forEach(name => this.classes.add(name)),
- remove: (...names: string[]) => names.forEach(name => this.classes.delete(name)),
- toggle: (name: string, enabled: boolean) => enabled ? this.classes.add(name) : this.classes.delete(name)};
- setAttribute(name: string, value: string) { this.attributes.set(name, value); }
- remove() { this.isConnected = false; }
- addEventListener(type: string, callback: () => void) { this.events.set(type, callback); }
- querySelector(selector: string) {
- if (!this.children.has(selector)) this.children.set(selector, new ElementStub());
- return this.children.get(selector);
- }
-}
+import {DOMElement, DOMFixture, requireFixture} from "./testDOM";
const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?: boolean | Promise<boolean>;
- online?: boolean; runtime?: () => Promise<unknown>} = {}) => {
- const roots: ElementStub[] = [];
- const records = new ElementStub();
- let root: ElementStub;
- let lifecycle: {root: ElementStub; destroy: () => void};
- const block = {dataset: {avId: "database", nodeId: "carrier"}, removeAttribute() {}, querySelector: (selector: string) =>
- selector.endsWith(".av__map") ? root : records};
- Object.assign(records, {before: (element: ElementStub) => { root = element; roots.push(root); }});
+ online?: boolean; protocol?: string; source?: string; failDuringCreate?: boolean; runtime?: () => Promise<unknown>} = {}) => {
+ const document = new DOMFixture();
+ 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);
+ const records = block.querySelector(".av__scroll");
+ let root: DOMElement;
+ let lifecycle: {root: DOMElement; destroy: () => 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"},
{get: (target, key: string) => target[key] || key});
const events = new Map<string, () => void>();
- const observers: Array<{disconnected: boolean}> = [];
+ const observers: Array<{disconnected: boolean; disconnects: number}> = [];
class Observer {
disconnected = false;
+ disconnects = 0;
constructor() { observers.push(this); }
observe() {}
- disconnect() { this.disconnected = true; }
+ disconnect() { this.disconnected = true; this.disconnects++; }
}
const hosts: Array<{options: AVMapHostOptions; points: protocol.AVMapPoint[]; revision: number;
- destroyed: boolean; fitted: boolean}> = [];
+ container: DOMElement; destroyed: boolean; destroys: number}> = [];
const opened: unknown[] = [];
const openedLinks: unknown[] = [];
const calls: string[] = [];
@@ -90,12 +72,16 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
}},
"../../../util/transactionQueue": {waitForPendingTransactions: () => transactionPromise},
"../render": {avRender: () => { refreshes++; }},
+ "../virtualScroll": {getAVData: () => data},
"../../../../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"}};
}},
"./protocol": protocol,
+ "../../../../plugin/Menu": {Menu: class {}},
+ "../../../../menus/Menu": {MenuItem: class {}},
+ "../../../../util/functions": {isMobile: () => false},
"./unplaced": {bindMapUnplaced: (options: Parameters<typeof import("./unplaced").bindMapUnplaced>[0]) => {
const binding = {options, destroyed: false};
unplaced.push(binding);
@@ -103,13 +89,16 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
}},
"../openDatabaseRow": {openDatabaseRowByData: (_protyle: unknown, row: unknown) => opened.push(row)},
"./host": {isAVMapHostEnvironmentSupported: () => options.hostSupported ?? true,
- createAVMapHost: (_container: unknown, configuration: AVMapHostOptions) => {
+ createAVMapHost: (container: DOMElement, configuration: AVMapHostOptions) => {
+ assert.ok(container?.isConnected, "Map host needs its mounted canvas");
+ assert.ok(container.classList.contains("av__map-canvas"));
const host = {options: configuration, points: [] as protocol.AVMapPoint[], revision: -1,
- destroyed: false, fitted: false};
+ container, destroyed: false, destroys: 0};
hosts.push(host);
- return {destroy: () => { host.destroyed = true; },
+ if (options.failDuringCreate) configuration.onError("hostUnavailable");
+ return {destroy: () => { host.destroyed = true; host.destroys++; },
setPoints: (points: protocol.AVMapPoint[], revision: number) => { host.points = points; host.revision = revision; },
- fit: () => { host.fitted = true; }, resize() {}, setTheme() {}};
+ resize() {}, setTheme() {}};
}},
};
modules["./desktopTransport"] = {
@@ -123,25 +112,27 @@ const setup = (options: {published?: boolean; desktop?: boolean; hostSupported?:
const openRecord = {} as typeof import("./openRecord");
runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/openRecord.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
- }).outputText, {exports: openRecord, require: (id: string) => modules[id] || {}, window: {siyuan: {languages}}});
+ }).outputText, {exports: openRecord, require: requireFixture(modules), window: {siyuan: {languages}}});
modules["./openRecord"] = openRecord;
const settings = {} as typeof import("./settings");
const context = {siyuan: {languages, isPublish: options.published === true}};
runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/settings.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
- }).outputText, {exports: settings, require: (id: string) => modules[id] || {}, window: context});
+ }).outputText, {exports: settings, require: requireFixture(modules), window: context});
modules["./settings"] = settings;
- runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/render.ts", "utf8"), {
+ runInNewContext(transpileModule(options.source ?? readFileSync("src/protyle/render/av/map/render.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
- }).outputText, {exports: methods, require: (id: string) => modules[id] || {},
- window: {...context, location: {protocol: "https:"},
+ }).outputText, {exports: methods, require: requireFixture(modules),
+ window: {...context, location: {protocol: options.protocol || "https:"},
open: (...args: unknown[]) => openedLinks.push(args),
addEventListener: (type: string, callback: () => void) => events.set(type, callback),
removeEventListener: (type: string) => events.delete(type)},
navigator: {userAgent: "Mozilla/5.0", onLine: options.online !== false},
- document: {createElement: () => new ElementStub(), documentElement: {getAttribute: () => "light"}},
- MutationObserver: Observer, ResizeObserver: Observer, Lute: {NewNodeID: () => "new-location"}});
- return {data, protyle, calls, hosts, roots, records, opened, openedLinks, events, observers, destroyMap, transactions, context, unplaced,
+ document: {createElement: () => { root = document.createElement("div"); roots.push(root); return root; },
+ 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,
refreshes: () => refreshes,
completeTransaction: async (success = true) => {
if (success) transactions[transactions.length - 1].callback();
@@ -169,7 +160,10 @@ test("map toolbar places the unplaced inbox after the summary and disposes its r
await scenario.render();
const html = scenario.roots[0].innerHTML;
assert.match(html, /av__map-toolbar/);
- assert.match(html, /data-map-unplaced-toggle data-position="4north".*aria-expanded="false".*#iconInbox/s);
+ const toggle = scenario.control("[data-map-unplaced-toggle]");
+ assert.equal(toggle.getAttribute("data-position"), "4north");
+ assert.equal(toggle.getAttribute("aria-expanded"), "false");
+ assert.match(toggle.innerHTML, /#iconInbox/);
assert.ok(html.indexOf("av__map-summary") < html.indexOf("data-map-unplaced-toggle"));
assert.equal(scenario.unplaced.length, 1);
assert.equal(scenario.unplaced[0].options.data, scenario.data);
@@ -215,7 +209,7 @@ test("map summary counts all skipped locations and keeps their reasons in its to
await scenario.render();
assert.match(scenario.roots[0].innerHTML, /<span>Loaded 4\/12<\/span>/);
assert.equal(scenario.control(".av__map-skipped").textContent, "Skipped 3");
- assert.equal(scenario.control(".av__map-summary").attributes.get("aria-label"),
+ assert.equal(scenario.control(".av__map-summary").getAttribute("aria-label"),
"Map covers 4 loaded records of 12 filtered records\nSkipped locations: 1 missing, 1 invalid, 1 unsupported projection");
assert.equal(scenario.hosts[0].points.length, 1);
view.rows = [row];
@@ -232,7 +226,7 @@ test("map summary retains skipped counts when every loaded row lacks a compatibl
await scenario.render();
assert.equal(scenario.status(), "mapNoMarkers");
assert.equal(scenario.control(".av__map-skipped").textContent, "Skipped 1");
- assert.equal(scenario.control(".av__map-summary").attributes.get("aria-label"),
+ 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, []);
});
@@ -284,8 +278,10 @@ test("deleted and changed-type map fields show a repairable location setup", asy
assert.match(html, /#iconGlobe/);
assert.match(html, locationKeyID ? /mapMissingLocationField/ : /mapSelectLocationField/);
assert.match(html, /<label class="av__map-setting"><span>mapLocationField<\/span>/);
- assert.match(html, /<select class="b3-select" data-map-location-field aria-label="mapLocationField">/);
- assert.match(html, /<option value="location">&lt;Location><\/option>/);
+ const select = scenario.control("[data-map-location-field]");
+ assert.equal(select.tagName, "SELECT");
+ assert.equal(select.getAttribute("aria-label"), "mapLocationField");
+ assert.equal(select.querySelector('[value="location"]').textContent, "<Location>");
assert.match(html, /class="b3-button b3-button--outline" data-map-create-field/);
assert.doesNotMatch(html, /value="text"|<Location>|provider|CRS|serviceID/);
assert.deepEqual(scenario.calls, []);
@@ -298,6 +294,39 @@ test("deleted and changed-type map fields show a repairable location setup", asy
assert.match(empty.setupHTML(), /mapSelectLocationField/);
});
+test("parsed templates do not manufacture missing controls and reject a canvas class mutation", async () => {
+ const scenario = setup();
+ await scenario.render();
+ assert.equal(scenario.control("[data-map-create-field]"), null);
+ assert.equal(scenario.hosts[0].container, scenario.control(".av__map-canvas"));
+ assert.equal(scenario.hosts[0].container.classList.contains("fn__none"), false);
+ const source = readFileSync("src/protyle/render/av/map/render.ts", "utf8");
+ const mutated = source.replace('class="av__map-canvas fn__none"', 'class="av__wrong-canvas fn__none"');
+ assert.notEqual(mutated, source);
+ const broken = setup({source: mutated});
+ await assert.rejects(broken.render(), /classList/);
+ assert.equal(broken.hosts.length, 0);
+});
+
+test("render requires an existing records container and contains mounted map input events", async () => {
+ const absent = setup();
+ absent.records.remove();
+ await absent.render();
+ assert.equal(absent.roots.length, 0);
+ const scenario = setup();
+ await scenario.render();
+ let escaped = 0;
+ for (const type of ["click", "keydown", "pointerdown"]) {
+ scenario.block.addEventListener(type, () => escaped++);
+ scenario.control(".av__map-canvas").dispatch(type);
+ }
+ assert.equal(escaped, 0);
+});
+
+test("undeclared VM imports fail instead of silently returning an empty module", () => {
+ assert.throws(() => requireFixture({})("./unlisted"), /Unexpected require: \.\/unlisted/);
+});
+
test("unconfigured maps render existing location fields without submitting settings transactions", async () => {
for (const mode of ["editable", "readonly", "published", "history"]) {
const scenario = setup({published: mode === "published"});
@@ -322,14 +351,14 @@ test("selecting an existing location field submits one undoable transaction and
await scenario.render();
const select = scenario.control("[data-map-location-field]");
select.value = "text";
- select.events.get("change")();
+ select.dispatch("change");
select.value = "";
- select.events.get("change")();
+ select.dispatch("change");
assert.equal(scenario.transactions.length, 0);
select.value = "location";
- select.events.get("change")();
- select.events.get("change")();
- scenario.control("[data-map-create-field]").events.get("click")();
+ select.dispatch("change");
+ select.dispatch("change");
+ scenario.control("[data-map-create-field]").dispatch("click");
assert.equal(scenario.transactions.length, 1);
assert.equal(select.disabled, true);
assert.equal(scenario.control("[data-map-create-field]").disabled, true);
@@ -341,7 +370,7 @@ test("selecting an existing location field submits one undoable transaction and
assert.equal(scenario.refreshes(), 0);
await scenario.completeTransaction();
assert.equal(scenario.refreshes(), 1);
- select.events.get("change")();
+ select.dispatch("change");
assert.equal(scenario.transactions.length, 1);
});
@@ -351,8 +380,8 @@ test("adding a location field atomically creates, selects and hides it with an u
(scenario.data.view as IAVTable).columns = [];
await scenario.render();
const create = scenario.control("[data-map-create-field]");
- create.events.get("click")();
- create.events.get("click")();
+ create.dispatch("click");
+ create.dispatch("click");
assert.equal(scenario.transactions.length, 1);
const {perform, undo} = scenario.transactions[0];
assert.equal(JSON.stringify(perform), JSON.stringify([
@@ -397,8 +426,8 @@ test("stale setup controls and permissions changed after render cannot submit a
if (mode === "removed") scenario.roots[0].remove();
if (mode === "rerendered") await scenario.render();
select.value = "location";
- select.events.get("change")();
- create.events.get("click")();
+ select.dispatch("change");
+ create.dispatch("click");
assert.equal(scenario.transactions.length, 0, mode);
}
});
@@ -409,12 +438,12 @@ test("failed setup transactions reenable controls, while late completion cannot
(scenario.data.view as IAVTable).columns = [];
await scenario.render();
const create = scenario.control("[data-map-create-field]");
- create.events.get("click")();
+ create.dispatch("click");
assert.equal(create.disabled, true);
await scenario.completeTransaction(false);
assert.equal(create.disabled, false);
assert.equal(scenario.refreshes(), 0);
- create.events.get("click")();
+ create.dispatch("click");
assert.equal(scenario.transactions.length, 2);
scenario.destroyMap();
await scenario.completeTransaction();
@@ -426,7 +455,7 @@ test("late setup transaction completions cannot refresh a removed or superseded
const scenario = setup();
(scenario.data.view as IAVTable).map.locationKeyID = "deleted";
await scenario.render();
- scenario.control("[data-map-create-field]").events.get("click")();
+ scenario.control("[data-map-create-field]").dispatch("click");
if (mode === "removed") scenario.roots[0].remove();
else await scenario.render();
await scenario.completeTransaction();
@@ -509,6 +538,9 @@ test("rerendering a map destroys the old host and invalidates its callbacks", as
previous.options.onReady();
await scenario.render();
assert.equal(previous.destroyed, true);
+ previous.options.onError("hostUnavailable");
+ assert.equal(scenario.hosts[1].destroyed, false);
+ assert.equal(scenario.status(), "mapLoading");
previous.options.onMarkerClick("row", previous.revision);
assert.equal(scenario.opened.length, 0);
const next = scenario.hosts[1];
@@ -518,6 +550,55 @@ test("rerendering a map destroys the old host and invalidates its callbacks", as
scenario.destroyMap();
});
+test("host failure releases its observers once while preserving the unplaced inbox", async () => {
+ for (const mode of ["offline", "error"]) {
+ const scenario = setup();
+ await scenario.render();
+ const host = scenario.hosts[0];
+ if (mode === "offline") scenario.events.get("offline")();
+ else host.options.onError("hostUnavailable");
+ assert.equal(host.destroys, 1, mode);
+ assert.equal(scenario.observers.length, 1);
+ assert.equal(scenario.observers[0].disconnects, 1);
+ assert.equal(scenario.events.size, 0);
+ assert.equal(scenario.unplaced[0].destroyed, false);
+ assert.equal(scenario.control(".av__map-canvas").classList.contains("fn__none"), true);
+ const status = scenario.status();
+ host.options.onReady();
+ host.options.onError("hostUnavailable");
+ assert.equal(scenario.status(), status);
+ scenario.destroyMap();
+ scenario.destroyMap();
+ assert.equal(host.destroys, 1);
+ assert.equal(scenario.observers[0].disconnects, 1);
+ assert.equal(scenario.unplaced[0].destroyed, true);
+ }
+});
+
+test("a host that fails synchronously during creation never acquires view observers", async () => {
+ const scenario = setup({failDuringCreate: true});
+ await scenario.render();
+ assert.equal(scenario.status(), "mapLoadError");
+ assert.equal(scenario.hosts[0].destroys, 1);
+ assert.equal(scenario.hosts[0].points.length, 0);
+ assert.equal(scenario.observers.length, 0);
+ assert.equal(scenario.events.size, 0);
+ assert.equal(scenario.unplaced[0].destroyed, false);
+ scenario.destroyMap();
+ assert.equal(scenario.hosts[0].destroys, 1);
+});
+
+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"});
+ if (mode === "created" || mode === "snapshot") scenario.protyle.options.history = {[mode]: "version"};
+ await scenario.render();
+ assert.equal(scenario.status(), mode === "published" ? "mapPublicFallback" : "mapUnsupportedClient");
+ assert.deepEqual(scenario.calls, []);
+ assert.equal(scenario.hosts.length, 0);
+ }
+});
+
test("authentication bypass reports its specific safe fallback without mounting the host", async () => {
const scenario = setup({runtime: async () => ({code: -1, msg: "mapAuthenticationBypass", data: null})});
await scenario.render();
diff --git a/app/src/protyle/render/av/map/render.ts b/app/src/protyle/render/av/map/render.ts
index 7e6a484953..c831a25975 100644
--- a/app/src/protyle/render/av/map/render.ts
+++ b/app/src/protyle/render/av/map/render.ts
@@ -119,25 +119,28 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
const canvas = root.querySelector<HTMLElement>(".av__map-canvas");
let host: AVMapHost;
let themeObserver: MutationObserver;
- let resizeObserver: ResizeObserver;
let destroyUnplaced: () => void;
let revision = 0;
const offline = () => fallback(window.siyuan.languages.mapOffline);
- const current = registerMap(blockElement, {root, destroy: () => {
+ const releaseHost = () => {
revision++;
- host?.destroy();
+ const previousHost = host;
+ host = undefined;
themeObserver?.disconnect();
- resizeObserver?.disconnect();
- destroyUnplaced?.();
+ themeObserver = undefined;
window.removeEventListener("offline", offline);
+ previousHost?.destroy();
+ };
+ const current = registerMap(blockElement, {root, destroy: () => {
+ releaseHost();
+ destroyUnplaced?.();
+ destroyUnplaced = undefined;
}});
const fallback = (message: string) => {
if (!current()) {
return;
}
- revision++;
- host?.destroy();
- host = undefined;
+ releaseHost();
status.textContent = message;
canvas.classList.add("fn__none");
};
@@ -164,7 +167,7 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
text.replace("${" + key + "}", value.toString()), window.siyuan.languages.mapSkippedLocations);
root.querySelector(".av__map-summary").setAttribute("aria-label", `${pageText}\n${skippedText}`);
}
- if (!canLoadMapHost({published: false, history: false, protocol: window.location.protocol})) {
+ if (!canLoadMapHost(window.location.protocol)) {
fallback(window.siyuan.languages.mapUnsupportedClient);
return;
}
@@ -203,7 +206,7 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
const pointIDs = new Set(points.map(point => point.id));
const activeRevision = ++revision;
canvas.classList.remove("fn__none");
- host = (desktopHost ? createDesktopAVMapHost : createAVMapHost)(canvas, {
+ const nextHost = (desktopHost ? createDesktopAVMapHost : createAVMapHost)(canvas, {
provider: "openfreemap",
theme: getTheme(),
title: window.siyuan.languages.mapView,
@@ -219,18 +222,25 @@ ${hasLocationField && canEditMapSettings(protyle) ? `<button type="button" class
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 ? window.siyuan.languages.mapLoadError : window.siyuan.languages.mapOffline),
+ onError: () => {
+ if (current() && revision === activeRevision) {
+ fallback(navigator.onLine ? window.siyuan.languages.mapLoadError : window.siyuan.languages.mapOffline);
+ }
+ },
onMarkerClick: (id, markerRevision) => {
if (current() && markerRevision === activeRevision && revision === activeRevision && pointIDs.has(id)) {
void openMapRecord(protyle, blockElement, rowByID.get(id));
}
},
});
+ if (!current() || revision !== activeRevision) {
+ nextHost.destroy();
+ return;
+ }
+ host = nextHost;
host.setPoints(points, activeRevision);
themeObserver = new MutationObserver(() => host?.setTheme(getTheme()));
themeObserver.observe(document.documentElement, {attributes: true, attributeFilter: ["data-theme-mode"]});
- resizeObserver = new ResizeObserver(() => host?.resize());
- resizeObserver.observe(canvas);
window.addEventListener("offline", offline);
} catch (_error) {
fallback(window.siyuan.languages.mapLoadError);
diff --git a/app/src/protyle/render/av/map/settings.test.ts b/app/src/protyle/render/av/map/settings.test.ts
index 096add68eb..393834f27f 100644
--- a/app/src/protyle/render/av/map/settings.test.ts
+++ b/app/src/protyle/render/av/map/settings.test.ts
@@ -4,145 +4,229 @@ import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
import * as escape from "../../../../util/escape";
+import * as menuGroup from "../../../../menus/menuGroup";
import * as state from "./state";
+import {DOMElement, DOMFixture, requireFixture} from "./testDOM";
-const setup = () => {
- const operations: Array<{perform: IOperation[]; undo: IOperation[]}> = [];
- const menus: Array<Array<{label: string; checked: boolean; click: () => void}>> = [];
- const languages = {mapLocationField: "Location", mapSelectLocationField: "Select field", mapMissingLocationField: "Missing field"};
- const methods = {} as typeof import("./settings");
- const context = {siyuan: {isPublish: false, languages}};
- runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/settings.ts", "utf8"), {
- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
- }).outputText, {exports: methods, window: context, require: (id: string) => ({
- "./state": state,
- "../../../../util/escape": escape,
- "../../../wysiwyg/transaction": {transaction: (_protyle: IProtyle, perform: IOperation[], undo: IOperation[]) =>
- operations.push({perform, undo})},
- "../../../../util/fetch": {fetchSyncPost: () => assert.fail("settings must not fetch services")},
- "../viewSettingMenu": {openViewSettingMenu() {}},
- "../../../../plugin/Menu": {Menu: class {
- items: Array<{label: string; checked: boolean; click: () => void}> = [];
- constructor() { menus.push(this.items); }
- addItem(item: {label: string; checked: boolean; click: () => void}) { this.items.push(item); }
- }},
- })[id] || {}});
- return {methods, operations, menus, context};
-};
+const compile = (path: string) => transpileModule(readFileSync(path, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+}).outputText;
+const menuSource = compile("src/menus/Menu.ts");
+const settingsSource = compile("src/protyle/render/av/map/settings.ts");
const data = () => ({id: "database", viewID: "map-view", view: {
map: {locationKeyID: "missing-field"},
columns: [{id: "location", type: "location", name: "<Location>"}, {id: "text", type: "text", name: "Text"}],
}}) as IAV;
-const control = () => {
- const handlers: Record<string, (event?: {preventDefault: () => void; stopPropagation: () => void}) => void> = {};
- return {disabled: false, isConnected: true,
- addEventListener: (type: string, handler: typeof handlers[string]) => { handlers[type] = handler; }, handlers};
+const setup = (mobile = false) => {
+ const document = new DOMFixture();
+ const operations: Array<{perform: IOperation[]; undo: IOperation[]}> = [];
+ const shown: DOMElement[] = [];
+ const menus: Array<{items: IMenu[]; independent: boolean; position?: IPosition; element: DOMElement}> = [];
+ let closed = 0;
+ const context = {siyuan: {isPublish: false,
+ languages: {mapLocationField: "Location", mapSelectLocationField: "Select field", mapMissingLocationField: "Missing field"},
+ menus: {menu: {showSubMenu: (element: DOMElement) => shown.push(element), remove: () => { closed++; }}}}};
+ const sharedMenu = {} as typeof import("../../../../menus/Menu");
+ runInNewContext(menuSource, {exports: sharedMenu, document, window: context, require: requireFixture({
+ "../protyle/util/compatibility": {updateHotkeyTip: (value: string) => value.replace(/⌘/g, "Ctrl+").replace(/↩/g, "Enter")},
+ "../util/setPosition": {}, "../util/zIndex": {}, "./menuPosition": {}, "./menuGroup": menuGroup,
+ "./sheetOpen": {}, "../protyle/util/hasClosest": {}, "../util/functions": {isMobile: () => mobile},
+ "../constants": {}, "../layout/getTopBarHeight": {}, "../protyle/undo": {}, "../util/escape": escape,
+ "./menuKeyboard": {}, "../plugin/EventBusCore": {}, "../mobile/util/keyboardToolbar": {},
+ "../block/popoverLifecycle": {}, "../config/entryVisibility/runtime": {},
+ })});
+ const methods = {} as typeof import("./settings");
+ runInNewContext(settingsSource, {exports: methods, document, window: context, require: requireFixture({
+ "./state": state, "../../../../util/escape": escape,
+ "../../../../util/functions": {isMobile: () => mobile},
+ "../../../../menus/Menu": sharedMenu,
+ "../../../wysiwyg/transaction": {transaction: (_protyle: IProtyle, perform: IOperation[], undo: IOperation[]) =>
+ operations.push({perform, undo})},
+ "../../../../plugin/Menu": {Menu: class {
+ readonly entry: typeof menus[number];
+ constructor(_id?: string, _close?: () => void, independent = false) {
+ const element = document.createElement("div");
+ document.body.append(element);
+ this.entry = {items: [], independent, element};
+ menus.push(this.entry);
+ }
+ addItem(item: IMenu) {
+ this.entry.items.push(item);
+ this.entry.element.append(new sharedMenu.MenuItem(item).element as unknown as DOMElement);
+ }
+ open(position: IPosition) { this.entry.position = position; }
+ }},
+ })});
+ const mount = (database = data(), protyle = {options: {}} as IProtyle) => {
+ const menuElement = document.createElement("div");
+ menuElement.innerHTML = methods.getMapSettingsHTML(database.view as IAVTable) +
+ '<button class="b3-menu__item" data-other>Other setting</button>';
+ document.body.append(menuElement);
+ const blockElement = document.createElement("div");
+ blockElement.dataset.nodeId = "carrier";
+ let updated = 0;
+ methods.bindMapSettings({data: database, protyle, menuElement: menuElement as unknown as Element,
+ blockElement: blockElement as unknown as Element, onChange: () => { updated++; }});
+ const field = menuElement.querySelector('[data-map-setting="locationKeyID"]');
+ return {database, protyle, field, menuElement, updated: () => updated,
+ choices: () => field.querySelector(".b3-menu__submenu").querySelectorAll("button")};
+ };
+ return {methods, document, operations, shown, menus, context, mount, closed: () => closed};
};
-test("map settings expose only a field choice and preserve missing field IDs", () => {
- const {methods, operations} = setup();
- const view = data().view as IAVTable;
+test("map settings mount a shared submenu, preserve missing field IDs and escape field labels", () => {
+ const scenario = setup();
+ const database = data();
+ const view = database.view as IAVTable;
const before = JSON.stringify(view);
- const html = methods.getMapSettingsHTML(view);
- assert.match(html, /Missing field/);
- assert.doesNotMatch(html, /serviceID|missing-field|showRecordList|checkbox|<select/);
- assert.equal((html.match(/data-map-setting=/g) || []).length, 1);
+ const {field, choices} = scenario.mount(database);
+ assert.equal(field.querySelector(".av__map-setting-value").textContent, "Missing field");
+ assert.equal(choices().length, 2);
+ assert.equal(choices()[0].querySelector(".b3-menu__label").textContent, "<Location>");
+ assert.equal(choices()[0].querySelector("location"), null);
+ assert.equal(choices()[1].querySelectorAll(".b3-menu__checked").length, 1);
+ assert.equal(field.querySelectorAll("select").length, 0);
assert.equal(JSON.stringify(view), before);
- assert.equal(operations.length, 0);
- view.map.locationKeyID = "location";
- assert.match(methods.getMapSettingsHTML(view), /&lt;Location>/);
+ assert.equal(scenario.operations.length, 0);
+ assert.equal(scenario.menus.length, 0);
});
-test("map field selection uses an undoable transaction without changing cells", () => {
- const {methods, operations, menus} = setup();
- const field = control();
- let updated = 0;
- methods.bindMapSettings({data: data(), protyle: {options: {}} as IProtyle,
- blockElement: {getAttribute: () => "carrier"} as unknown as Element,
- menuElement: {querySelectorAll: () => [field]} as unknown as Element, onChange: () => updated++});
- field.handlers.click({preventDefault() {}, stopPropagation() {}});
- assert.equal(menus[0].filter(item => item.checked).length, 1);
- menus[0].find(item => item.checked).click();
- assert.equal(operations.length, 0);
- menus[0].find(item => item.label === "&lt;Location>").click();
- assert.equal(updated, 1);
- const perform = operations[0].perform[0];
- assert.equal(perform.action, "setAttrViewMap");
- assert.equal(perform.avID, "database");
- assert.equal(perform.viewID, "map-view");
- assert.equal(perform.blockID, "carrier");
- assert.equal(JSON.stringify(perform.data), JSON.stringify({locationKeyID: "location"}));
- assert.equal(JSON.stringify(operations[0].undo[0].data), JSON.stringify({locationKeyID: "missing-field"}));
+test("empty field labels and absent choices still produce a usable settings item", () => {
+ for (const mode of ["empty-label", "no-fields"]) {
+ const scenario = setup();
+ const database = data();
+ const view = database.view as IAVTable;
+ view.map.locationKeyID = "";
+ if (mode === "no-fields") view.columns = [];
+ else view.columns[0].name = "";
+ const {field, choices} = scenario.mount(database);
+ assert.equal(field.querySelector(".av__map-setting-value").getAttribute("title"), mode === "no-fields" ? "Select field" : "");
+ assert.equal(choices().length, 1);
+ field.dispatch("click");
+ assert.equal(scenario.shown.length, 1);
+ }
});
-test("the default field is displayed without writes and can be explicitly pinned with a raw-state undo", () => {
- const {methods, operations, menus} = setup();
+test("field names containing shortcut symbols remain literal labels", () => {
+ const scenario = setup();
const database = data();
const view = database.view as IAVTable;
- view.map.locationKeyID = "";
- const before = JSON.stringify(view);
- assert.match(methods.getMapSettingsHTML(view), /&lt;Location>/);
- const field = control();
- methods.bindMapSettings({data: database, protyle: {options: {}} as IProtyle,
- blockElement: {getAttribute: () => "carrier"} as unknown as Element,
- menuElement: {querySelectorAll: () => [field]} as unknown as Element});
- field.handlers.click({preventDefault() {}, stopPropagation() {}});
- assert.equal(operations.length, 0);
- assert.equal(JSON.stringify(view), before);
- assert.equal(menus[0].length, 1);
- assert.equal(menus[0][0].checked, true);
- menus[0][0].click();
- assert.equal(JSON.stringify(operations[0].perform[0].data), JSON.stringify({locationKeyID: "location"}));
- assert.equal(JSON.stringify(operations[0].undo[0].data), JSON.stringify({locationKeyID: ""}));
- assert.equal(view.map.locationKeyID, "location");
+ view.map.locationKeyID = "location";
+ view.columns[0].name = "⌘Office ↩ <Location>";
+ const {field, choices} = scenario.mount(database);
+ assert.equal(field.querySelector(".av__map-setting-value").textContent, view.columns[0].name);
+ assert.equal(field.querySelector(".av__map-setting-value").getAttribute("title"), view.columns[0].name);
+ assert.equal(choices()[0].querySelector(".b3-menu__label").textContent, view.columns[0].name);
});
-test("choosing another field from an automatic default keeps the empty binding in undo", () => {
- const {methods, operations, menus} = setup();
- const database = data();
- const view = database.view as IAVTable;
- view.map.locationKeyID = "";
- view.columns.push({id: "second", type: "location", name: "Second"});
- const field = control();
- methods.bindMapSettings({data: database, protyle: {options: {}} as IProtyle,
- blockElement: {getAttribute: () => "carrier"} as unknown as Element,
- menuElement: {querySelectorAll: () => [field]} as unknown as Element});
- field.handlers.click({preventDefault() {}, stopPropagation() {}});
- menus[0].find(item => item.label === "Second").click();
- assert.equal(view.map.locationKeyID, "second");
- assert.equal(JSON.stringify(operations[0].undo[0].data), JSON.stringify({locationKeyID: ""}));
- view.map = {locationKeyID: (operations[0].undo[0].data as IAVMapSettings).locationKeyID};
- assert.equal(state.getMapSettings(view).locationKeyID, "location");
+test("desktop hover, sibling hover, ArrowRight, ArrowLeft and Escape use the actual submenu", () => {
+ const scenario = setup();
+ const {field, choices, menuElement} = scenario.mount();
+ const submenu = field.querySelector(".b3-menu__submenu");
+ field.dispatch("mouseenter", {bubbles: false});
+ assert.equal(field.classList.contains("b3-menu__item--show"), true);
+ assert.equal(scenario.shown[0], submenu);
+ choices()[0].dispatch("mouseover");
+ assert.equal(field.classList.contains("b3-menu__item--show"), true);
+ menuElement.querySelector("[data-other]").dispatch("mouseover");
+ assert.equal(field.classList.contains("b3-menu__item--show"), false);
+ for (const key of ["ArrowLeft", "Escape"]) {
+ const right = field.dispatch("keydown", {key: "ArrowRight"});
+ assert.equal(right.defaultPrevented, true);
+ assert.equal(scenario.document.activeElement, choices()[0]);
+ assert.equal(field.classList.contains("b3-menu__item--show"), true);
+ const close = choices()[0].dispatch("keydown", {key});
+ assert.equal(close.defaultPrevented, true);
+ assert.equal(scenario.document.activeElement, field);
+ assert.equal(field.classList.contains("b3-menu__item--show"), false);
+ }
+ field.dispatch("click");
+ assert.equal(field.classList.contains("b3-menu__item--show"), true);
+ assert.equal(scenario.menus.length, 0);
+ assert.equal(scenario.operations.length, 0);
});
-test("readonly, history, and published maps cannot change settings", () => {
- for (const mode of ["disabled", "history", "published"]) {
- const {methods, operations, context} = setup();
- const field = control();
- context.siyuan.isPublish = mode === "published";
- methods.bindMapSettings({data: data(), protyle: {disabled: mode === "disabled",
- options: {history: mode === "history" ? {created: "version"} : undefined}} as IProtyle,
- blockElement: {} as Element, menuElement: {querySelectorAll: () => [field]} as unknown as Element});
+test("map field selection uses the shared item click and an undoable transaction", () => {
+ const scenario = setup();
+ const {choices, updated} = scenario.mount();
+ choices()[1].dispatch("click");
+ assert.equal(scenario.operations.length, 0);
+ choices()[0].dispatch("click");
+ assert.equal(updated(), 1);
+ assert.equal(scenario.closed(), 2);
+ assert.deepEqual(JSON.parse(JSON.stringify(scenario.operations[0])), {
+ perform: [{action: "setAttrViewMap", avID: "database", viewID: "map-view", blockID: "carrier", data: {locationKeyID: "location"}}],
+ undo: [{action: "setAttrViewMap", avID: "database", viewID: "map-view", blockID: "carrier", data: {locationKeyID: "missing-field"}}],
+ });
+});
+
+test("automatic defaults remain read only until selected and preserve raw-state undo", () => {
+ for (const selectSecond of [false, true]) {
+ const scenario = setup();
+ const database = data();
+ const view = database.view as IAVTable;
+ view.map.locationKeyID = "";
+ view.columns.push({id: "second", type: "location", name: "Second"});
+ const before = JSON.stringify(view);
+ const {field, choices} = scenario.mount(database);
+ assert.equal(field.querySelector(".av__map-setting-value").textContent, "<Location>");
+ assert.ok(choices()[0].querySelector(".b3-menu__checked"));
+ assert.equal(scenario.operations.length, 0);
+ assert.equal(JSON.stringify(view), before);
+ choices()[selectSecond ? 1 : 0].dispatch("click");
+ assert.equal(view.map.locationKeyID, selectSecond ? "second" : "location");
+ assert.equal((scenario.operations[0].undo[0].data as IAVMapSettings).locationKeyID, "");
+ view.map = {locationKeyID: ""};
+ assert.equal(state.getMapSettings(view).locationKeyID, "location");
+ }
+});
+
+test("mobile taps open an independent menu with checked choices and anchored ownership", () => {
+ const scenario = setup(true);
+ const {field, updated} = scenario.mount();
+ field.dispatch("mouseenter", {bubbles: false});
+ assert.equal(scenario.shown.length, 0);
+ field.dispatch("click");
+ assert.equal(scenario.menus.length, 1);
+ const menu = scenario.menus[0];
+ assert.equal(menu.independent, true);
+ assert.equal(menu.position.target, field);
+ assert.equal(menu.position.y, field.getBoundingClientRect().bottom);
+ assert.equal(menu.items.filter(item => item.checked).length, 1);
+ menu.element.querySelector("button").dispatch("click");
+ assert.equal(updated(), 1);
+ assert.equal(scenario.operations.length, 1);
+});
+
+test("readonly, both history modes and published maps cannot open field submenus", () => {
+ for (const mode of ["disabled", "created", "snapshot", "published"]) {
+ const scenario = setup();
+ scenario.context.siyuan.isPublish = mode === "published";
+ const {field} = scenario.mount(data(), {disabled: mode === "disabled",
+ options: {history: ["created", "snapshot"].includes(mode) ? {[mode]: "version"} : undefined}} as IProtyle);
assert.equal(field.disabled, true);
- assert.equal(Object.keys(field.handlers).length, 0);
- assert.equal(operations.length, 0);
+ assert.equal(field.querySelector(".b3-menu__submenu"), null);
+ field.dispatch("click");
+ assert.equal(scenario.operations.length, 0);
+ assert.equal(scenario.shown.length, 0);
}
});
-test("a dismissed menu and a later readonly transition cannot change map fields", () => {
- const {methods, operations, menus} = setup();
- const field = control();
- const protyle = {options: {}} as IProtyle;
- methods.bindMapSettings({data: data(), protyle, blockElement: {} as Element,
- menuElement: {querySelectorAll: () => [field]} as unknown as Element});
- field.isConnected = false;
- field.handlers.click({preventDefault() {}, stopPropagation() {}});
- assert.equal(menus.length, 0);
- field.isConnected = true;
- field.handlers.click({preventDefault() {}, stopPropagation() {}});
- protyle.disabled = true;
- menus[0].find(item => item.label === "&lt;Location>").click();
- assert.equal(operations.length, 0);
+test("dismissed controls and later readonly transitions cannot change fields", () => {
+ for (const mobile of [false, true]) {
+ for (const mode of ["dismissed", "readonly"]) {
+ const scenario = setup(mobile);
+ const {field, protyle, choices} = scenario.mount();
+ field.dispatch("click");
+ const choice = mobile ? scenario.menus[0].element.querySelector("button") : choices()[0];
+ if (mode === "dismissed") field.remove();
+ else protyle.disabled = true;
+ field.dispatch("click");
+ choice.dispatch("click");
+ assert.equal(scenario.operations.length, 0);
+ assert.equal(scenario.menus.length, mobile ? 1 : 0);
+ }
+ }
});
diff --git a/app/src/protyle/render/av/map/settings.ts b/app/src/protyle/render/av/map/settings.ts
index 08f99fca86..fc023825de 100644
--- a/app/src/protyle/render/av/map/settings.ts
+++ b/app/src/protyle/render/av/map/settings.ts
@@ -1,7 +1,8 @@
import {transaction} from "../../../wysiwyg/transaction";
import {escapeAttr, escapeHtml} from "../../../../util/escape";
import {Menu} from "../../../../plugin/Menu";
-import {openViewSettingMenu} from "../viewSettingMenu";
+import {MenuItem} from "../../../../menus/Menu";
+import {isMobile} from "../../../../util/functions";
import {getMapSettings} from "./state";
export const canEditMapSettings = (protyle: IProtyle) => !protyle.disabled && !window.siyuan.isPublish &&
@@ -54,14 +55,59 @@ export const bindMapSettings = (options: {
options.onChange?.();
};
controls.forEach(control => {
- control.addEventListener("click", event => {
+ const choices = getChoices(view);
+ const items: IMenu[] = choices.map(choice => ({iconHTML: "", label: escapeHtml(choice.label),
+ checked: getMapSettings(view).locationKeyID === choice.value, click: () => {
+ if (item.element.isConnected) update(choice.value);
+ }}));
+ const label = choices.find(choice => choice.value === getMapSettings(view).locationKeyID).label;
+ const item = new MenuItem({iconHTML: "", label: window.siyuan.languages.mapLocationField,
+ accelerator: " ", submenu: items});
+ item.element.dataset.mapSetting = "locationKeyID";
+ const valueElement = item.element.querySelector(".b3-menu__accelerator");
+ valueElement.textContent = label;
+ valueElement.classList.add("fn__ellipsis", "av__map-setting-value");
+ valueElement.setAttribute("title", label);
+ control.replaceWith(item.element);
+ const submenu = item.element.querySelector<HTMLElement>(".b3-menu__submenu");
+ const show = () => {
+ if (!item.element.isConnected || !canEditMapSettings(options.protyle)) return;
+ item.element.classList.add("b3-menu__item--show");
+ window.siyuan.menus.menu.showSubMenu(submenu);
+ };
+ if (!isMobile()) {
+ item.element.addEventListener("mouseenter", show);
+ options.menuElement.addEventListener("mouseover", event => {
+ const hovered = (event.target as Element).closest(".b3-menu__item");
+ if (hovered && !item.element.contains(hovered)) item.element.classList.remove("b3-menu__item--show");
+ });
+ item.element.addEventListener("keydown", event => {
+ if (!item.element.isConnected || !canEditMapSettings(options.protyle)) return;
+ if (event.key === "ArrowRight") {
+ event.preventDefault();
+ event.stopPropagation();
+ show();
+ submenu.querySelector<HTMLButtonElement>(".b3-menu__item").focus();
+ } else if (event.key === "ArrowLeft" || event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ item.element.classList.remove("b3-menu__item--show");
+ item.element.focus();
+ }
+ });
+ }
+ item.element.addEventListener("click", event => {
event.preventDefault();
event.stopPropagation();
- if (!control.isConnected || !canEditMapSettings(options.protyle)) return;
- const menu = new Menu();
- getChoices(view).forEach(choice => menu.addItem({iconHTML: "", label: escapeHtml(choice.label),
- checked: getMapSettings(view).locationKeyID === choice.value, click: () => update(choice.value)}));
- openViewSettingMenu(menu, control);
+ if (!item.element.isConnected || !canEditMapSettings(options.protyle)) return;
+ if (isMobile()) {
+ const menu = new Menu(undefined, undefined, true);
+ items.forEach(choice => menu.addItem(choice));
+ const rect = item.element.getBoundingClientRect();
+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, target: item.element});
+ } else {
+ show();
+ }
});
});
};
diff --git a/app/src/protyle/render/av/map/state.test.ts b/app/src/protyle/render/av/map/state.test.ts
index 8d12fbb9a8..8e2e7351c0 100644
--- a/app/src/protyle/render/av/map/state.test.ts
+++ b/app/src/protyle/render/av/map/state.test.ts
@@ -44,10 +44,10 @@ test("map preserves valid polar coordinates but counts unsupported projection se
test("missing or changed location fields retain their saved identifiers and do not fall back", () => {
const view = table([{latitude: 0, longitude: 0}]);
view.map.locationKeyID = "removed";
- assert.equal(getMapPoints(view).missingField, true);
+ assert.deepEqual(getMapPoints(view), {points: [], skipped: {empty: 0, invalid: 0, projection: 0}});
assert.equal(getMapSettings(view).locationKeyID, "removed");
view.map.locationKeyID = "primary";
- assert.equal(getMapPoints(view).missingField, true);
+ assert.deepEqual(getMapPoints(view), {points: [], skipped: {empty: 0, invalid: 0, projection: 0}});
assert.deepEqual(getMapSettings(view), {locationKeyID: "primary"});
assert.deepEqual(getMapSettings({} as IAVTable), {locationKeyID: ""});
});
@@ -78,12 +78,11 @@ test("map does not silently truncate the loaded page before the explicit renderi
assert.equal(getMapPoints(view).points.length, AV_MAP_MAX_POINTS + 1);
});
-test("map document eligibility excludes public, history and non-HTTP contexts before host capability checks", () => {
- const context = {published: false, history: false, protocol: "https:"};
- assert.equal(canLoadMapHost(context), true);
- assert.equal(canLoadMapHost({...context, protocol: "http:"}), true);
- for (const change of [{published: true}, {history: true}, {protocol: "file:"}]) {
- assert.equal(canLoadMapHost({...context, ...change}), false);
+test("map host requires an HTTP document protocol", () => {
+ assert.equal(canLoadMapHost("https:"), true);
+ assert.equal(canLoadMapHost("http:"), true);
+ for (const protocol of ["file:", "data:", "siyuan:", ""]) {
+ assert.equal(canLoadMapHost(protocol), false);
}
});
diff --git a/app/src/protyle/render/av/map/state.ts b/app/src/protyle/render/av/map/state.ts
index 1c408d9e2b..21035206da 100644
--- a/app/src/protyle/render/av/map/state.ts
+++ b/app/src/protyle/render/av/map/state.ts
@@ -14,7 +14,7 @@ export const getMapPoints = (view: IAVTable) => {
const fieldID = getMapSettings(view).locationKeyID;
const fieldIndex = view.columns.findIndex(column => column.id === fieldID && column.type === "location");
if (fieldIndex < 0) {
- return {points, skipped, missingField: true};
+ return {points, skipped};
}
const used = new Set<string>();
view.rows.forEach(row => {
@@ -31,14 +31,10 @@ export const getMapPoints = (view: IAVTable) => {
points.push({id: row.id, longitude: location.longitude, latitude: location.latitude});
}
});
- return {points, skipped, missingField: false};
+ return {points, skipped};
};
-export const canLoadMapHost = (context: {
- published: boolean;
- history: boolean;
- protocol: string;
-}) => !context.published && !context.history && ["http:", "https:"].includes(context.protocol);
+export const canLoadMapHost = (protocol: string) => ["http:", "https:"].includes(protocol);
interface IMapLifecycle {
root: HTMLElement;
diff --git a/app/src/protyle/render/av/map/testDOM.ts b/app/src/protyle/render/av/map/testDOM.ts
new file mode 100644
index 0000000000..8a9288035c
--- /dev/null
+++ b/app/src/protyle/render/av/map/testDOM.ts
@@ -0,0 +1,143 @@
+import * as assert from "node:assert/strict";
+import {createRequire} from "node:module";
+
+// 复用已安装的 HTML 解析器,只查询模板中实际存在的节点。
+// 仅实现测试需要的 DOM 接口;不支持的选择器直接失败,避免掩盖模板错误。
+const parse5 = createRequire(require.resolve("html-loader"))("parse5");
+
+export class DOMFixture {
+ activeElement: DOMElement;
+ private elements = new WeakMap<object, DOMElement>();
+ readonly body = this.createElement("body");
+ readonly documentElement = this.createElement("html");
+ constructor() { this.documentElement.append(this.body); }
+ wrap(node: any): DOMElement {
+ if (!this.elements.has(node)) this.elements.set(node, new DOMElement(node, this));
+ return this.elements.get(node);
+ }
+ createElement(name: string): DOMElement {
+ return this.wrap({nodeName: name, tagName: name, attrs: [], childNodes: [],
+ namespaceURI: "http://www.w3.org/1999/xhtml"});
+ }
+}
+
+export class DOMElement {
+ readonly events = new Map<string, Array<(event: any) => void>>();
+ private inputValue: string;
+ constructor(readonly node: any, readonly ownerDocument: DOMFixture) {}
+ get children(): DOMElement[] { return (this.node.childNodes || []).filter((node: any) => node.tagName).map((node: any) => this.ownerDocument.wrap(node)); }
+ get firstElementChild() { return this.children[0] || null; }
+ get lastElementChild() { return this.children[this.children.length - 1] || null; }
+ get parentElement(): DOMElement | null { return this.node.parentNode?.tagName ? this.ownerDocument.wrap(this.node.parentNode) : null; }
+ get previousElementSibling(): DOMElement | null { return this.parentElement?.children[this.parentElement.children.indexOf(this) - 1] || null; }
+ get nextElementSibling(): DOMElement | null { return this.parentElement?.children[this.parentElement.children.indexOf(this) + 1] || null; }
+ get isConnected(): boolean { return this === this.ownerDocument.documentElement || this.parentElement?.isConnected || false; }
+ get tagName(): string { return this.node.tagName.toUpperCase(); }
+ get className(): string { return this.getAttribute("class") || ""; }
+ set className(value: string) { this.setAttribute("class", value); }
+ get disabled() { return this.hasAttribute("disabled"); }
+ set disabled(value: boolean) { if (value) this.setAttribute("disabled", ""); else this.removeAttribute("disabled"); }
+ get value(): string { return this.inputValue ?? this.getAttribute("value") ?? ""; }
+ set value(value: string) { this.inputValue = value; }
+ get dataset(): Record<string, string> {
+ const attribute = (key: string) => "data-" + key.replace(/[A-Z]/g, char => "-" + char.toLowerCase());
+ return new Proxy({}, {get: (_target, key: string) => this.getAttribute(attribute(key)) ?? undefined,
+ set: (_target, key: string, value: string) => { this.setAttribute(attribute(key), value); return true; }});
+ }
+ get classList() {
+ const values = () => new Set(this.className.split(/\s+/).filter(Boolean));
+ const toggle = (name: string, force?: boolean) => {
+ const classes = values();
+ const enabled = force ?? !classes.has(name);
+ if (enabled) classes.add(name); else classes.delete(name);
+ this.className = [...classes].join(" ");
+ return enabled;
+ };
+ return {contains: (name: string) => values().has(name), toggle,
+ add: (...names: string[]) => names.forEach(name => toggle(name, true)),
+ remove: (...names: string[]) => names.forEach(name => toggle(name, false))};
+ }
+ getAttribute(name: string): string | null { return this.node.attrs.find((attr: any) => attr.name === name)?.value ?? null; }
+ hasAttribute(name: string) { return this.getAttribute(name) !== null; }
+ setAttribute(name: string, value: string) { this.removeAttribute(name); this.node.attrs.push({name, value}); }
+ removeAttribute(name: string) { this.node.attrs = this.node.attrs.filter((attr: any) => attr.name !== name); }
+ get innerHTML(): string { return parse5.serialize(this.node); }
+ set innerHTML(value: string) {
+ this.children.forEach(child => child.remove());
+ this.node.childNodes = parse5.parseFragment(value).childNodes;
+ this.node.childNodes.forEach((child: any) => { child.parentNode = this.node; });
+ }
+ get textContent(): string {
+ const read = (node: any): string => node.nodeName === "#text" ? node.value : (node.childNodes || []).map(read).join("");
+ return read(this.node);
+ }
+ set textContent(value: string) {
+ this.children.forEach(child => child.remove());
+ this.node.childNodes = [{nodeName: "#text", value, parentNode: this.node}];
+ }
+ remove() {
+ if (this.node.parentNode) {
+ this.node.parentNode.childNodes = this.node.parentNode.childNodes.filter((node: any) => node !== this.node);
+ this.node.parentNode = undefined;
+ }
+ }
+ append(child: DOMElement) { child.remove(); child.node.parentNode = this.node; this.node.childNodes.push(child.node); }
+ before(child: DOMElement) {
+ assert.ok(this.parentElement, "Cannot insert before an unmounted element");
+ child.remove();
+ const parent = this.node.parentNode;
+ parent.childNodes.splice(parent.childNodes.indexOf(this.node), 0, child.node);
+ child.node.parentNode = parent;
+ }
+ replaceWith(child: DOMElement) { this.before(child); this.remove(); }
+ insertAdjacentHTML(position: string, html: string) {
+ assert.equal(position, "beforeend");
+ parse5.parseFragment(html).childNodes.forEach((node: any) => { node.parentNode = this.node; this.node.childNodes.push(node); });
+ }
+ contains(other: DOMElement): boolean { return this === other || this.children.some(child => child.contains(other)); }
+ isEqualNode(other: DOMElement) { return this === other; }
+ matches(selector: string): boolean {
+ const tokens = selector.match(/^[a-z]+|\.[\w-]+|\[[\w-]+(?:="[^"]*")?\]/g);
+ assert.equal(tokens?.join(""), selector, `Unsupported fixture selector: ${selector}`);
+ return tokens.every(token => {
+ if (token.startsWith(".")) return this.classList.contains(token.slice(1));
+ if (!token.startsWith("[")) return this.node.tagName === token;
+ const [, name, value] = token.match(/^\[([\w-]+)(?:="([^"]*)")?\]$/);
+ return value === undefined ? this.hasAttribute(name) : this.getAttribute(name) === value;
+ });
+ }
+ closest(selector: string): DOMElement | null { return this.matches(selector) ? this : this.parentElement?.closest(selector) || null; }
+ querySelector(selector: string): DOMElement | null { return this.querySelectorAll(selector)[0] || null; }
+ querySelectorAll(selector: string): DOMElement[] {
+ if (selector.startsWith(":scope > ")) {
+ const [first, ...rest] = selector.slice(9).split(" > ");
+ return this.children.filter(child => child.matches(first)).flatMap(child => rest.length ? child.querySelectorAll(":scope > " + rest.join(" > ")) : [child]);
+ }
+ const descendants = (element: DOMElement): DOMElement[] => element.children.flatMap(child => [child, ...descendants(child)]);
+ return descendants(this).filter(child => child.matches(selector));
+ }
+ addEventListener(type: string, listener: (event: any) => void) {
+ if (!this.events.has(type)) this.events.set(type, []);
+ this.events.get(type).push(listener);
+ }
+ dispatch(type: string, options: {key?: string; bubbles?: boolean} = {}) {
+ let stopped = false;
+ let immediate = false;
+ const event = {target: this, key: options.key, defaultPrevented: false,
+ preventDefault() { this.defaultPrevented = true; },
+ stopPropagation() { stopped = true; }, stopImmediatePropagation() { stopped = true; immediate = true; }};
+ const dispatchTo = (element: DOMElement) => {
+ for (const listener of element.events.get(type) || []) { listener(event); if (immediate) break; }
+ if (options.bubbles !== false && !stopped && element.parentElement) dispatchTo(element.parentElement);
+ };
+ dispatchTo(this);
+ return event;
+ }
+ focus() { this.ownerDocument.activeElement = this; }
+ getBoundingClientRect() { return {left: 10, right: 110, top: 20, bottom: 50, width: 100, height: 30}; }
+}
+
+export const requireFixture = (modules: Record<string, unknown>) => (id: string) => {
+ assert.ok(Object.prototype.hasOwnProperty.call(modules, id), `Unexpected require: ${id}`);
+ return modules[id];
+};
diff --git a/app/src/protyle/render/av/map/unplaced.test.ts b/app/src/protyle/render/av/map/unplaced.test.ts
index 2dab931ff9..1811e05a77 100644
--- a/app/src/protyle/render/av/map/unplaced.test.ts
+++ b/app/src/protyle/render/av/map/unplaced.test.ts
@@ -8,6 +8,7 @@ import * as escape from "../../../../util/escape";
import * as locationValue from "../locationValue";
import {getMapSettings} from "./state";
import * as unplacedMenu from "./unplacedMenu";
+import {requireFixture} from "./testDOM";
class ElementStub {
isConnected = true;
@@ -94,7 +95,7 @@ const setup = (mobile = false) => {
runInNewContext(transpileModule(readFileSync("src/protyle/render/av/map/unplaced.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
}).outputText, {exports: methods, window: context, AbortController,
- clearTimeout: (id: number) => timers.delete(id), require: (id: string) => ({
+ clearTimeout: (id: number) => timers.delete(id), require: requireFixture({
"../../../../constants": {Constants: {TIMEOUT_INPUT: 256, ATTRIBUTE_MENU_KEYMAP: "data-keymap"}},
"../../../../plugin/Menu": {Menu: MenuStub},
"../../../../util/escape": escape,
@@ -111,7 +112,7 @@ const setup = (mobile = false) => {
!protyle.options.history?.created && !protyle.options.history?.snapshot},
"./openRecord": {openMapRecord: (_protyle: IProtyle, _block: HTMLElement, row: IAVRow, keyID: string) =>
opens.push({row, keyID})},
- })[id] || {}});
+ })});
const destroy = methods.bindMapUnplaced({root: root as unknown as HTMLElement, blockElement: block as unknown as HTMLElement,
protyle, data, current: () => current});
return {methods, requests, menus, toggle, count, input, canvas, data, protyle, context, opens, destroy,
@@ -135,10 +136,15 @@ const setup = (mobile = false) => {
const nativeMenu = {} as typeof import("../../../../menus/Menu");
runInNewContext(transpileModule(readFileSync("src/menus/Menu.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
- }).outputText, {exports: nativeMenu, window: context, CustomEvent: class {}, require: (id: string) => ({
+ }).outputText, {exports: nativeMenu, window: context, CustomEvent: class {}, require: requireFixture({
"../constants": {Constants: {KEYCODELIST: {13: "↩"}}},
"../protyle/util/compatibility": {getEventName: () => "click"},
- })[id] || {}});
+ "../util/setPosition": {}, "../util/zIndex": {}, "./menuPosition": {}, "./menuGroup": {},
+ "./sheetOpen": {}, "../protyle/util/hasClosest": {}, "../util/functions": {},
+ "../layout/getTopBarHeight": {}, "../protyle/undo": {}, "../util/escape": {},
+ "./menuKeyboard": {}, "../plugin/EventBusCore": {}, "../mobile/util/keyboardToolbar": {},
+ "../block/popoverLifecycle": {}, "../config/entryVisibility/runtime": {},
+ })});
assert.equal(nativeMenu.bindMenuKeydown({keyCode: 13, target: item.element} as unknown as KeyboardEvent), true);
},
runTimers: () => { const pending = [...timers.values()]; timers.clear(); pending.forEach(callback => callback()); },
diff --git a/app/src/protyle/render/av/map/wrapperEntry.test.ts b/app/src/protyle/render/av/map/wrapperEntry.test.ts
index 454c884a98..761e4e1337 100644
--- a/app/src/protyle/render/av/map/wrapperEntry.test.ts
+++ b/app/src/protyle/render/av/map/wrapperEntry.test.ts
@@ -3,6 +3,35 @@ import {describe, it} from "node:test";
import {connectAVMapWrapper} from "./wrapperEntry";
describe("trusted map navigation wrapper", () => {
+ it("forwards only fixed bootstrap error codes and rejects array-shaped handshakes", () => {
+ for (const input of ["sdkScriptLoadFailed", "sdkGlobalMissing", "https://private.invalid/?token=secret", {}]) {
+ const instanceID = "a".repeat(48), nonce = "b".repeat(48), origin = "https://fixture.invalid";
+ const messages: any[] = [], listeners = new Map<string, (event?: any) => void>();
+ let appended = 0, removed = 0;
+ const child = {style: {}, setAttribute() {}, contentWindow: {postMessage() {}}, remove() { removed++; }};
+ const scope = {
+ location: {hash: `#${instanceID}:${nonce}`, search: "?provider=openfreemap", protocol: "https:", origin},
+ parent: {postMessage: (value: unknown) => messages.push(value)},
+ document: {createElement: () => child, body: {appendChild() { appended++; }}},
+ setTimeout: () => 1, clearTimeout() {},
+ addEventListener: (type: string, callback: (event?: any) => void) => listeners.set(type, callback),
+ removeEventListener: (type: string) => listeners.delete(type),
+ };
+ connectAVMapWrapper(scope as unknown as Window);
+ const receive = listeners.get("message");
+ const prepare = {version: 1, type: "prepare", instanceID, nonce};
+ receive({source: scope.parent, origin, ports: [], data: Object.assign([], prepare)});
+ assert.equal(appended, 0);
+ receive({source: scope.parent, origin, ports: [], data: prepare});
+ receive({source: child.contentWindow, origin: "null", ports: [], data: {...prepare, type: "hello"}});
+ receive({source: child.contentWindow, origin: "null", ports: [],
+ data: {...prepare, type: "bootstrapError", code: input, message: "secret"}});
+ const code = typeof input === "string" && input.startsWith("sdk") ? input : "hostBootstrapFailed";
+ assert.deepEqual(messages[messages.length - 1], {version: 1, type: "bootstrapError", instanceID, nonce, code});
+ assert.equal(removed, 1);
+ assert.equal(listeners.has("message"), false);
+ }
+ });
it("authenticates both sides, preserves the opaque sandbox, and transfers only one port after bootstrap", () => {
const instanceID = "a".repeat(48);
const nonce = "b".repeat(48);
diff --git a/app/src/protyle/render/av/map/wrapperEntry.ts b/app/src/protyle/render/av/map/wrapperEntry.ts
index b3c1f16aa0..69bd355ffd 100644
--- a/app/src/protyle/render/av/map/wrapperEntry.ts
+++ b/app/src/protyle/render/av/map/wrapperEntry.ts
@@ -1,5 +1,5 @@
-import {isAVMapProvider} from "./protocol";
-import {isAVMapBootstrapMessage} from "./hostCapabilities";
+import {isAVMapBootstrapMessage, isAVMapLoadErrorCode, isAVMapProvider} from "./protocol";
+import {AV_MAP_BOOTSTRAP_TIMEOUT} from "./loadingBudget";
// 可信 wrapper 不加载 SDK、不处理记录或凭证,只把一次业务端口交给固定 opaque 子框架。
export const connectAVMapWrapper = (scope: Window) => {
@@ -58,11 +58,12 @@ export const connectAVMapWrapper = (scope: Window) => {
ready = true;
scope.parent.postMessage({...envelope, type: "bootstrapReady"}, scope.location.origin);
} else if (booted && isAVMapBootstrapMessage(event.data, "bootstrapError", instanceID, nonce)) {
- scope.parent.postMessage({...envelope, type: "bootstrapError"}, scope.location.origin);
+ const code = isAVMapLoadErrorCode(event.data.code) ? event.data.code : "hostBootstrapFailed";
+ scope.parent.postMessage({...envelope, type: "bootstrapError", code}, scope.location.origin);
cleanup();
}
};
- const timer = scope.setTimeout(cleanup, 30000);
+ const timer = scope.setTimeout(cleanup, AV_MAP_BOOTSTRAP_TIMEOUT);
scope.addEventListener("message", onMessage);
scope.addEventListener("pagehide", cleanup, {once: true});
scope.parent.postMessage({...envelope, type: "wrapperHello"}, scope.location.origin);
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index f9dcfe5dcc..013ef90da1 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -1523,7 +1523,7 @@ interface IAVCellValue {
}
/**
- * 坐标统一使用 WGS84,不自动转换;文本顺序为纬度、经度。
+ * 坐标统一使用 WGS84,不自动转换;界面按经度、纬度显示,规范复制与导出文本按纬度、经度排列。
* 位置字段的文本筛选条件使用 IAVCellValue.text.content,不把查询词解析成坐标。
*/
interface IAVCellLocationValue {
diff --git a/app/tests/fixtures/map-unplaced-overlay/README.md b/app/tests/fixtures/map-unplaced-overlay/README.md
new file mode 100644
index 0000000000..3bd5ca8a5e
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/README.md
@@ -0,0 +1,46 @@
+# 未定位菜单可信 overlay 独立原型
+
+本目录没有生产入口。它不修改现有 `unplaced.ts`、`desktopTransport.ts`、`unplacedMenu.ts` 或 `mapHostManager.js`,不替换当前裁剪方案。生产环境「点击菜单仍闪烁」尚未解决。原型中所有记录是合成数据,底图是独立 WebContentsView 占位页;它没有连接真实笔记、内核、加密笔记本或 OpenFreeMap。
+
+## 可运行入口
+
+在 `app/` 目录运行:
+
+```sh
+node --import tsx --test tests/mapUnplacedOverlay.test.js tests/mapUnplacedOverlayBoundary.test.js
+pnpm exec electron tests/fixtures/map-unplaced-overlay/harness.cjs
+```
+
+第一条命令同时收集纯 Node 测试和真实 Electron 测试。Linux 缺少 DISPLAY/WAYLAND_DISPLAY 时,真实 Electron 测试明确跳过;不允许添加 `--no-sandbox` 或安全绕过参数来令测试通过。第二条需要可用桌面,打开可手动测试的独立原型。自动与手动入口均在 app ready 前设置独立临时 userData,不使用用户原有 profile。手动入口在退出及启动失败时尽力清理自己生成的临时目录,显式传入的测试 profile 由调用者负责清理。运行入口只在内存编译已有 menu/text-field 共享 SCSS,不生成生产构建文件。
+
+当前环境无法运行真实 GUI。已执行的 Node 测试验证严格 schema、资源路由、owner/frame/session/revision/requestID、选择成员集合、权限撤销、导航和销毁、失败清理、几何去重,以及实际 preload/menu 脚本在模拟 IPC/DOM 下的行为。模拟 DOM 使用项目现有 parse5 fixture,不证明浏览器排版、真实键盘输入、中文输入法候选窗、CSP 的浏览器执行、原生层合成或真实 OFM 覆盖正确。真实 Electron 入口已经编写,但只有它实际通过后才可报告相应浏览器证据。
+
+## 最小安全边界
+
+- owner 是构造 manager 时固定登记的 WebContents、当前主 frame 和精确文档 URL。程序导航、销毁、窗口隐藏或失焦都会销毁旧 overlay;owner WebContents 失焦进入同一窗口 overlay 不会误关
+- 每次打开使用新随机内存 session,不复用 owner 或 OFM 会话。只有固定 synthetic HTTPS origin 上精确四个本地资源可通过 GET/HEAD 加载,额外 query、编码路径、凭证和其他地址全部拒绝。初始主文档只允许一次,子 frame、worker、WebSocket、下载和导航全部拒绝
+- overlay 禁用 Node、webview 和不安全内容,启用 contextIsolation、sandbox、webSecurity。CSP 不含 unsafe-inline/unsafe-eval,禁止网络、图片、字体、媒体、表单等能力;权限、设备、认证和新窗口拒绝。销毁后保留拒绝路由并清理 session
+- 可信 owner 只发送受限文本条目、计数、页码、加载状态、语言标签和主题枚举。所有标签用 textContent 渲染,不接受 HTML、URL、任意 CSS 或脚本。主题只支持静态浅色/深色与六档字体,使用本地 CSS 属性选择器,不动态注入样式
+- overlay 的桥只暴露 subscribe/editing/search/more/select/close。主进程校验发送者、主 frame、session、revision 和当前选择集合;编辑/组合开始立即撤销旧选择。主进程为请求签发递增 requestID,旧 A→B→A 回复即使 query 相同也不能复活旧成员
+- owner 保留查询取消和最终权限校验责任。这里的 owner 只用内存合成数据模拟,不从原型自行 fetch 内核。真实记录与权限/加密租约逻辑必须留在既有可信 owner
+- overlay 使用固定容量视口,owner 传 CSS 锚点与滚动容器/窗口的可见交集,完全裁掉时关闭且不恢复焦点;缩放从真实 owner WebContents 读取,按当前窗口 contentBounds 重验。滚动/缩放只更新且去重 bounds,不因菜单 DOM mutation 使用 hide/show 稳定延迟。未改变任何生产 observer/stabilize 行为
+- owner 的可信 DOM pointerdown 处理外部点击并排除 toggle;独立地图占位视图通过主进程 before-mouse-event 处理外部点击。Esc、选择和显式关闭恢复 owner 焦点;外部点击及窗口失焦不抢焦点。关闭取消 owner 定时器并清理 view、监听器、会话及条目集合
+
+## 实际 GUI 验收仍待完成
+
+1. 在 Windows、macOS 和 Linux 的真实桌面启动原型,运行 Electron 测试,再人工检查原生输入法候选窗和组合中的 Esc;合成 composition 事件不算真实中文输入法验证
+2. 搜索、防抖、清空搜索、重复搜索 A→B→A、分页、快速连续开关、加载中关闭、加载失败后重试、空列表、超长标签、键盘方向键和焦点恢复
+3. 浅色/深色、较大字体、不同窗口大小、125%/150% 缩放、滚动、锚点离开可视区、其他原生地图视图和窗口抢焦点;验证无残留透明点击层
+4. 使用真实 OFM 和生产 observer/stabilize,检查菜单打开、输入、分页、焦点变动时地图不闪烁或被压住。占位地图始终可见的测试不能替代此项
+5. 真实内核查询的搜索分页契约、只读和权限撤销、锁定加密笔记本、当前视图/位置字段切换、地图销毁、窗口导航,以及在请求途中关闭后的迟到回复
+6. 现有自定义主题的有限 token 映射、共享菜单快捷键与可访问性、菜单尺寸与定位策略。这些产品接线细节尚未完成,不应因原型通过而默认启用
+
+## 将来最小接线范围
+
+- `map/unplaced.ts`:保留现有 getAttributeViewMapUnplaced、toMapUnplacedRow、available/canEditMapSettings、AbortController 和 openMapRecord;只把渲染目标抽为 DOM Menu / desktop overlay adapter。仅向 overlay 发送所需标题与稳定选择 ID,收到选择时重新核对当前上下文、权限和条目映射。新增 requestID/session 校验不能取代最终权限检查
+- 独立可信菜单 manager、preload 和打包本地资源:登记真实 owner,复用现有 owner 信任判定,不给 OFM renderer 新通道、私有数据、菜单 DOM 或任何权限。资源必须纳入明确打包清单
+- `map/desktopTransport.ts` / `map/unplacedMenu.ts` 与 `electron/mapHostManager.js`:只在实际 overlay 成功就绪且安全绑定对应地图后,让该菜单退出 DOM 遮挡裁剪路径,并维护原生 sibling 层级与外部点击。不能全局忽略菜单遮挡或降低其他覆盖物的隔离
+- `electron/main.js` 及构建资源清单:仅负责可信 manager 的受限接线、销毁和本地资源打包。保留当前失败处理,准备好返回现有 DOM 菜单的路径;禁止把加载失败转为宽松 CSP 或共享 session
+- 浏览器/移动端继续使用现有 DOM Menu;此原型只研究 Electron 原生层级问题,未改变移动行为
+
+只有独立实现复核与实际 GUI/生产 OFM 验收完成,才可以决定是否接入和替换裁剪。此目录自身不授权或执行该替换。
diff --git a/app/tests/fixtures/map-unplaced-overlay/harness.cjs b/app/tests/fixtures/map-unplaced-overlay/harness.cjs
new file mode 100644
index 0000000000..1392a4d4c4
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/harness.cjs
@@ -0,0 +1,84 @@
+const path = require("node:path");
+const fs = require("node:fs");
+const os = require("node:os");
+const {pathToFileURL} = require("node:url");
+const {createManager} = require("./manager.cjs");
+const createTemporaryProfile = () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-unplaced-manual-"));
+ return {profile, cleanup() {
+ // 只清理本次入口自己生成的临时目录,不删除调用者传入的 profile。
+ if (path.dirname(path.resolve(profile)) !== path.resolve(os.tmpdir()) ||
+ !path.basename(profile).startsWith("siyuan-unplaced-manual-")) return;
+ try { fs.rmSync(profile, {recursive: true, force: true, maxRetries: 3, retryDelay: 100}); }
+ catch (_error) { /* 系统文件锁尚未释放时,在退出事件中再次清理。 */ }
+ }};
+};
+const createHarness = async ({profile, automate = false} = {}) => {
+ if (typeof profile !== "string" || !path.isAbsolute(profile)) throw new Error("An explicit isolated fixture profile is required");
+ const {app, BrowserWindow, WebContentsView, ipcMain, session} = require("electron");
+ const {hasUnsafeMapSwitches} = require("../../../electron/mapHostPolicy");
+ if (hasUnsafeMapSwitches(app.commandLine)) throw new Error("Unsafe process switches are not supported by this fixture");
+ app.setPath("userData", profile);
+ await app.whenReady();
+ // 样式只编译已有本地共享控件;该入口不生成或修改生产构建文件。
+ const sass = require("sass");
+ const component = path.resolve(__dirname, "../../../src/assets/scss/component");
+ const controls = sass.compileString('@use "menu"; @use "text-field";', {loadPaths: [component], logger: sass.Logger.silent}).css;
+ const ownerURL = pathToFileURL(path.join(__dirname, "owner.html")).href;
+ const win = new BrowserWindow({width: 980, height: 760, useContentSize: true, show: true,
+ webPreferences: {preload: path.join(__dirname, "owner-preload.cjs"), nodeIntegration: false,
+ contextIsolation: true, sandbox: true, webSecurity: true, webviewTag: false}});
+ const owner = win.webContents;
+ const map = new WebContentsView({webPreferences: {nodeIntegration: false, contextIsolation: true, sandbox: true,
+ webSecurity: true, webviewTag: false, partition: "unplaced-fixture-synthetic-map"}});
+ const mapVisible = [];
+ const setVisible = map.setVisible.bind(map);
+ map.setVisible = value => { mapVisible.push(value); setVisible(value); };
+ win.contentView.addChildView(map);
+ map.setBounds({x: 30, y: 380, width: 860, height: 250});
+ map.setVisible(true);
+ await map.webContents.loadURL("data:text/html," + encodeURIComponent('<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'"><body style="background:#cbd7df;font:24px system-ui;padding:30px">Synthetic map placeholder. No OFM or private data.</body>'));
+ let allowed = true;
+ const events = [];
+ const reply = value => { events.push(value); if (!owner.isDestroyed()) owner.send("unplaced-fixture-owner-event", value); };
+ const manager = createManager({ipcMain, session, WebContentsView, owner, win, ownerURL,
+ outsideContents: [map.webContents], assets: {controls}, mayUse: () => allowed,
+ onAction: reply, onClose: value => reply({type: "closed", ...value})});
+ const prefix = "unplaced-fixture-owner-";
+ const handlers = [];
+ ipcMain.handle(prefix + "open", (event, value) => manager.open(event, value));
+ for (const [name, fn] of [["update", manager.update], ["anchor", manager.setAnchor], ["close", manager.close]]) {
+ ipcMain.on(prefix + name, fn); handlers.push([prefix + name, fn]);
+ }
+ const trusted = event => event.sender === owner && event.senderFrame === owner.mainFrame && owner.mainFrame.url === ownerURL;
+ const zoom = event => { if (trusted(event)) owner.setZoomFactor(owner.getZoomFactor() === 1 ? 1.25 : 1); };
+ const permission = event => { if (trusted(event)) { allowed = !allowed; if (!allowed) manager.revoke(); } };
+ ipcMain.on(prefix + "zoom", zoom); handlers.push([prefix + "zoom", zoom]);
+ ipcMain.on(prefix + "permission", permission); handlers.push([prefix + "permission", permission]);
+ let cleaned = false;
+ const destroy = () => {
+ if (cleaned) return;
+ cleaned = true;
+ manager.destroy();
+ ipcMain.removeHandler(prefix + "open");
+ handlers.forEach(([channel, fn]) => ipcMain.removeListener(channel, fn));
+ if (!map.webContents.isDestroyed()) map.webContents.close({waitForBeforeUnload: false});
+ if (!win.isDestroyed()) win.destroy();
+ };
+ win.on("closed", () => { destroy(); if (!automate) app.quit(); });
+ await win.loadURL(ownerURL);
+ return {win, owner, manager, map, mapVisible, events, destroy};
+};
+module.exports = {createHarness, createTemporaryProfile};
+if (require.main === module) {
+ const {app, BrowserWindow} = require("electron");
+ const temporary = createTemporaryProfile();
+ app.once("will-quit", temporary.cleanup);
+ app.once("quit", temporary.cleanup);
+ createHarness({profile: temporary.profile}).catch(error => {
+ for (const win of BrowserWindow.getAllWindows()) { if (!win.isDestroyed()) win.destroy(); }
+ temporary.cleanup();
+ console.error(error);
+ app.exit(1);
+ });
+}
diff --git a/app/tests/fixtures/map-unplaced-overlay/manager.cjs b/app/tests/fixtures/map-unplaced-overlay/manager.cjs
new file mode 100644
index 0000000000..546083fb5f
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/manager.cjs
@@ -0,0 +1,220 @@
+const path = require("node:path");
+const fs = require("node:fs/promises");
+const {randomBytes} = require("node:crypto");
+const {ORIGIN, CHANNEL, CSP, keys, parseState, parseAction, parseAnchor, place, resource} = require("./policy.cjs");
+
+const deny = () => new Response("Forbidden", {status: 403});
+const clearSession = ses => {
+ for (const method of ["closeAllConnections", "clearStorageData", "clearAuthCache", "clearCache", "clearHostResolverCache"]) {
+ try { void Promise.resolve(ses[method]()).catch(() => {}); } catch (_error) { /* 继续清理其他状态。 */ }
+ }
+};
+const createRouter = (ses, assets, readFile = fs.readFile) => {
+ let destroyed = false, documentRequested = false;
+ ses.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
+ ses.setPermissionCheckHandler(() => false);
+ ses.setDevicePermissionHandler(() => false);
+ ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));
+ ses.setCertificateVerifyProc((_request, callback) => callback(-3));
+ ses.allowNTLMCredentialsForDomains("");
+ ses.on("will-download", event => event.preventDefault());
+ ses.webRequest.onBeforeRequest((request, callback) => {
+ const entry = resource(request.url, request.method);
+ let allowed = !destroyed && entry && entry[2] === request.resourceType;
+ if (request.resourceType === "mainFrame") {
+ allowed = allowed && !documentRequested;
+ if (allowed) documentRequested = true;
+ }
+ callback({cancel: !allowed});
+ });
+ ses.webRequest.onBeforeSendHeaders((_details, callback) => callback({cancel: destroyed, requestHeaders: {}}));
+ const handle = async request => {
+ const entry = resource(request.url, request.method);
+ if (destroyed || !entry || request.headers.get("service-worker")) return deny();
+ try {
+ const body = entry[0] === "controls.css" ? assets.controls : await readFile(path.join(__dirname, entry[0]));
+ if (destroyed) return deny();
+ return new Response(request.method === "HEAD" ? null : body, {headers: {
+ "Content-Type": entry[1], "Content-Security-Policy": CSP, "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer",
+ "Permissions-Policy": "geolocation=(), camera=(), microphone=(), payment=(), usb=(), serial=(), bluetooth=()",
+ }});
+ } catch (_error) { return new Response("Not Found", {status: 404}); }
+ };
+ ses.protocol.handle("https", handle);
+ ses.protocol.handle("http", deny);
+ ses.protocol.handle("file", deny);
+ return {destroy() {
+ if (destroyed) return;
+ destroyed = true;
+ clearSession(ses);
+ }};
+};
+
+// 此管理器只由独立测试入口构造;生产地图没有引用此模块。
+const createManager = ({ipcMain, session, WebContentsView, owner, win, ownerURL, outsideContents = [], assets,
+ onAction, onClose = () => {}, mayUse = () => true, randomID = () => randomBytes(24).toString("hex")}) => {
+ let host, disposed = false;
+ const listeners = [];
+ const listen = (emitter, name, fn, list = listeners) => { emitter.on(name, fn); list.push([emitter, name, fn]); };
+ const currentOwner = () => !disposed && !owner.isDestroyed() && !win.isDestroyed() && owner.mainFrame.url === ownerURL;
+ const trusted = event => currentOwner() && event?.sender === owner && event.senderFrame === owner.mainFrame;
+ const permitted = () => { try { return mayUse() === true; } catch (_error) { return false; } };
+ const close = (reason, restore = false) => {
+ const previous = host;
+ if (!previous) return;
+ host = undefined;
+ clearTimeout(previous.timer);
+ previous.ids.clear();
+ previous.state.rows = [];
+ for (const [emitter, name, fn] of previous.listeners) emitter.removeListener(name, fn);
+ previous.router.destroy();
+ try { if (!win.isDestroyed()) win.contentView.removeChildView(previous.view); } catch (_error) { /* 继续关闭渲染器。 */ }
+ const contents = previous.view.webContents;
+ if (!contents.isDestroyed()) {
+ try { contents.stop(); } catch (_error) { /* 继续关闭渲染器。 */ }
+ try { contents.close({waitForBeforeUnload: false}); } catch (_error) { /* 渲染器可能已关闭。 */ }
+ }
+ if (restore && !owner.isDestroyed() && !win.isDestroyed() && win.isFocused()) owner.focus();
+ onClose({sessionID: previous.sessionID, reason, restore});
+ };
+ const geometry = () => {
+ if (!host) return false;
+ if (!currentOwner()) { close("owner-unavailable"); return false; }
+ const zoom = owner.getZoomFactor();
+ const bounds = place(host.anchor, zoom, win.getContentBounds());
+ if (!permitted() || !win.isVisible() || !bounds) { close("unavailable"); return false; }
+ const key = JSON.stringify({bounds, zoom});
+ if (host.geometryKey !== key) {
+ host.view.webContents.setZoomFactor(zoom);
+ host.view.setBounds(bounds);
+ host.geometryKey = key;
+ }
+ return true;
+ };
+ const sendState = () => {
+ if (host?.ready) host.view.webContents.send(CHANNEL + "-state", {sessionID: host.sessionID, state: host.state});
+ };
+ const stateIDs = state => new Set(state.loading || state.error ? [] : state.rows.map(row => row.id));
+ const open = (event, value) => {
+ if (!trusted(event) || !permitted() || !keys(value, ["state", "anchor"])) return;
+ const state = parseState(value.state), anchor = parseAnchor(value.anchor);
+ if (!state || state.requestID !== 0 || !anchor || !place(anchor, owner.getZoomFactor(), win.getContentBounds())) return;
+ close("replace");
+ const sessionID = randomID();
+ let ses, router, view;
+ try {
+ ses = session.fromPartition("unplaced-fixture-" + sessionID, {cache: false});
+ router = createRouter(ses, assets);
+ view = new WebContentsView({webPreferences: {session: ses, preload: path.join(__dirname, "preload.cjs"),
+ additionalArguments: ["--unplaced-session=" + sessionID], nodeIntegration: false,
+ nodeIntegrationInWorker: false, nodeIntegrationInSubFrames: false, contextIsolation: true, sandbox: true,
+ webSecurity: true, webviewTag: false, allowRunningInsecureContent: false, devTools: false}});
+ host = {sessionID, view, router, state, anchor, ids: stateIDs(state), ready: false, listeners: [],
+ pending: state.loading, query: state.query, requestID: 0};
+ const active = host;
+ const contents = view.webContents;
+ contents.setWindowOpenHandler(() => ({action: "deny"}));
+ for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {
+ listen(contents, name, event => event.preventDefault(), host.listeners);
+ }
+ listen(contents, "login", (event, _details, _info, callback) => { event.preventDefault(); callback(); }, host.listeners);
+ listen(contents, "select-client-certificate", (event, _url, _certificates, callback) => { event.preventDefault(); callback(); }, host.listeners);
+ for (const name of ["render-process-gone", "destroyed", "did-fail-load"]) {
+ listen(contents, name, () => { if (host === active) close("renderer-failed"); }, host.listeners);
+ }
+ host.timer = setTimeout(() => { if (host === active) close("ready-timeout"); }, 10000);
+ host.timer.unref?.();
+ view.setVisible(false);
+ win.contentView.addChildView(view);
+ if (!geometry()) return;
+ void contents.loadURL(ORIGIN + "/menu.html").catch(() => { if (host === active) close("load-failed"); });
+ return sessionID;
+ } catch (_error) {
+ if (host?.sessionID === sessionID) close("setup-failed");
+ else {
+ if (router) router.destroy(); else if (ses) clearSession(ses);
+ try { if (view && !view.webContents.isDestroyed()) view.webContents.close({waitForBeforeUnload: false}); } catch (_failure) { /* 保留拒绝网络策略。 */ }
+ }
+ }
+ };
+ const update = (event, value) => {
+ if (!trusted(event) || !host || !keys(value, ["sessionID", "state"]) || value.sessionID !== host.sessionID) return false;
+ if (!permitted()) { close("permission-revoked"); return false; }
+ const state = parseState(value.state);
+ if (!state || state.revision <= host.state.revision || state.requestID !== host.requestID ||
+ host.pending && state.query !== host.query) return false;
+ host.state = state;
+ host.ids = stateIDs(state);
+ host.pending = state.loading;
+ sendState();
+ return true;
+ };
+ const setAnchor = (event, value) => {
+ if (!trusted(event) || !host || !keys(value, ["sessionID", "anchor"]) || value.sessionID !== host.sessionID) return false;
+ const anchor = parseAnchor(value.anchor);
+ if (!anchor) return false;
+ host.anchor = anchor;
+ return geometry();
+ };
+ const message = (event, value) => {
+ if (host && !currentOwner()) { close("owner-unavailable"); return; }
+ const action = parseAction(value);
+ if (!host || !action || event.sender !== host.view.webContents || event.senderFrame !== event.sender.mainFrame ||
+ event.senderFrame.url !== ORIGIN + "/menu.html" || action.sessionID !== host.sessionID) return;
+ if (!permitted()) { close("permission-revoked"); return; }
+ if (action.type === "ready") {
+ if (host.ready || action.revision !== 0) return;
+ host.ready = true;
+ clearTimeout(host.timer);
+ sendState();
+ if (geometry()) { host.view.setVisible(true); host.view.webContents.focus(); }
+ return;
+ }
+ if (!host.ready || action.revision !== host.state.revision) return;
+ if (action.type === "close") { close(action.reason, true); return; }
+ if (action.type === "editing") {
+ host.ids.clear();
+ host.pending = true;
+ host.query = undefined;
+ onAction({...action, requestID: ++host.requestID});
+ return;
+ }
+ if (action.type === "select") {
+ if (!host.ids.has(action.id)) return;
+ const sessionID = host.sessionID;
+ close("select", true);
+ onAction({...action, sessionID});
+ return;
+ }
+ if (action.type === "more" && (host.pending || host.state.error || host.state.page * 50 >= host.state.total || host.state.rows.length >= 500)) return;
+ host.ids.clear();
+ host.pending = true;
+ host.query = action.type === "search" ? action.query.trim() : host.state.query;
+ onAction({...action, query: host.query, requestID: ++host.requestID});
+ };
+ listen(ipcMain, CHANNEL + "-action", message);
+ const outside = (_event, input) => { if (input.type === "mouseDown") close("outside"); };
+ for (const contents of outsideContents) listen(contents, "before-mouse-event", outside);
+ for (const name of ["blur", "hide", "minimize", "closed"]) listen(win, name, () => close("window-" + name));
+ for (const name of ["resize", "move"]) listen(win, name, geometry);
+ listen(owner, "zoom-changed", geometry);
+ for (const name of ["will-navigate", "destroyed", "render-process-gone"]) listen(owner, name, () => close("owner-" + name));
+ listen(owner, "did-start-navigation", details => { if (details.isMainFrame) close("owner-navigation"); });
+ return {open, update, setAnchor,
+ close(event, value) {
+ if (trusted(event) && host && keys(value, ["sessionID", "reason"]) && value.sessionID === host.sessionID &&
+ ["outside", "button", "anchor-hidden"].includes(value.reason)) close(value.reason, value.reason === "button");
+ },
+ revoke() { close("permission-revoked"); },
+ destroy() {
+ if (disposed) return;
+ close("destroy");
+ disposed = true;
+ for (const [emitter, name, fn] of listeners) emitter.removeListener(name, fn);
+ },
+ // 仅供主进程测试读取,不通过 renderer 桥暴露。
+ inspect: () => host && {sessionID: host.sessionID, view: host.view, ready: host.ready},
+ };
+};
+module.exports = {createRouter, createManager};
diff --git a/app/tests/fixtures/map-unplaced-overlay/menu.css b/app/tests/fixtures/map-unplaced-overlay/menu.css
new file mode 100644
index 0000000000..5b84728580
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/menu.css
@@ -0,0 +1,44 @@
+:root {
+ --b3-menu-background: #ffffff;
+ --b3-theme-background: #ffffff;
+ --b3-theme-surface: #f6f6f6;
+ --b3-theme-surface-lighter: #dddddd;
+ --b3-theme-on-background: #222222;
+ --b3-theme-on-surface: #666666;
+ --b3-theme-primary: #3576d5;
+ --b3-theme-primary-light: #6d9fe7;
+ --b3-theme-primary-lighter: #bed4f3;
+ --b3-border-color: #cccccc;
+ --b3-list-hover: #eeeeee;
+ --b3-scroll-color: #aaaaaa;
+ --b3-border-radius: 4px;
+ --b3-border-radius-b: 6px;
+ --b3-dialog-shadow: none;
+ --b3-font-size: 16px;
+ color-scheme: light;
+}
+:root[data-theme="dark"] {
+ --b3-menu-background: #292929;
+ --b3-theme-background: #292929;
+ --b3-theme-surface: #222222;
+ --b3-theme-surface-lighter: #444444;
+ --b3-theme-on-background: #eeeeee;
+ --b3-theme-on-surface: #bbbbbb;
+ --b3-border-color: #666666;
+ --b3-list-hover: #444444;
+ color-scheme: dark;
+}
+:root[data-font-size="12"] { --b3-font-size: 12px; }
+:root[data-font-size="14"] { --b3-font-size: 14px; }
+:root[data-font-size="18"] { --b3-font-size: 18px; }
+:root[data-font-size="20"] { --b3-font-size: 20px; }
+:root[data-font-size="24"] { --b3-font-size: 24px; }
+html, body { height: 100%; margin: 0; overflow: hidden; }
+body { color: var(--b3-theme-on-background); font-family: system-ui, sans-serif; }
+.fixture-menu { inset: 0; display: flex; flex-direction: column; }
+.fixture-menu header, .fixture-search, #status { padding: 6px 12px; }
+.fixture-search input { width: 100%; }
+.fixture-menu #rows { flex: 1; min-height: 0; overflow: auto; }
+.fixture-menu footer { display: flex; }
+.fixture-menu #rows .b3-menu__item { width: calc(100% - 8px); }
+.fixture-menu [hidden] { display: none; }
diff --git a/app/tests/fixtures/map-unplaced-overlay/menu.html b/app/tests/fixtures/map-unplaced-overlay/menu.html
new file mode 100644
index 0000000000..0bcf1b0197
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/menu.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<html lang="zh-CN" data-theme="light" data-font-size="16">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <link rel="stylesheet" href="/controls.css">
+ <link rel="stylesheet" href="/menu.css">
+ <script defer src="/menu.js"></script>
+ <title></title>
+</head>
+<body>
+ <section class="b3-menu fixture-menu" role="dialog" aria-labelledby="title">
+ <header><span id="title"></span> <span id="count"></span></header>
+ <div class="fixture-search"><input id="search" class="b3-text-field" type="search" maxlength="256"></div>
+ <div id="rows" class="b3-menu__items" role="group"></div>
+ <div id="status" role="status" aria-live="polite"></div>
+ <footer><button id="more" class="b3-menu__item" type="button"></button><button id="close" class="b3-menu__item" type="button"></button></footer>
+ </section>
+</body>
+</html>
diff --git a/app/tests/fixtures/map-unplaced-overlay/menu.js b/app/tests/fixtures/map-unplaced-overlay/menu.js
new file mode 100644
index 0000000000..4a6e6edac5
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/menu.js
@@ -0,0 +1,91 @@
+(() => {
+ const bridge = window.unplacedMenu;
+ const input = document.getElementById("search");
+ const rows = document.getElementById("rows");
+ const status = document.getElementById("status");
+ const more = document.getElementById("more");
+ let composing = false, timer, first = true, lastQuery = "", state, pending = false, awaitingSearch = false, searchSent = false;
+ const disableRows = () => { for (const row of rows.children) row.disabled = true; };
+ const search = () => {
+ clearTimeout(timer);
+ pending = true;
+ awaitingSearch = true;
+ searchSent = false;
+ bridge.editing();
+ disableRows();
+ more.disabled = true;
+ timer = setTimeout(() => {
+ lastQuery = input.value.trim();
+ searchSent = true;
+ bridge.search(lastQuery);
+ }, 200);
+ };
+ input.addEventListener("compositionstart", () => {
+ composing = true;
+ pending = true;
+ awaitingSearch = true;
+ searchSent = false;
+ clearTimeout(timer);
+ disableRows();
+ more.disabled = true;
+ bridge.editing();
+ });
+ input.addEventListener("compositionend", () => { composing = false; search(); });
+ input.addEventListener("input", event => { if (!composing && !event.isComposing) search(); });
+ more.addEventListener("click", () => {
+ if (pending || !state || more.disabled) return;
+ pending = true;
+ disableRows();
+ more.disabled = true;
+ if (state.error) bridge.search(lastQuery); else bridge.more();
+ });
+ document.getElementById("close").addEventListener("click", () => bridge.close("button"));
+ document.addEventListener("keydown", event => {
+ if (event.isComposing || composing) return;
+ if (event.key === "Escape") { event.preventDefault(); bridge.close("escape"); return; }
+ if (!["ArrowDown", "ArrowUp"].includes(event.key)) return;
+ const buttons = Array.from(rows.children).filter(row => !row.disabled);
+ if (!buttons.length) return;
+ const index = buttons.indexOf(document.activeElement);
+ const next = event.key === "ArrowDown" ? (index + 1) % buttons.length : (index < 0 ? buttons.length - 1 : (index + buttons.length - 1) % buttons.length);
+ event.preventDefault();
+ buttons[next].focus();
+ });
+ window.addEventListener("pagehide", () => { clearTimeout(timer); state = undefined; });
+ bridge.subscribe(value => {
+ if (composing || awaitingSearch && (!searchSent || value.query !== lastQuery)) return;
+ state = value;
+ pending = value.loading;
+ if (!value.loading) awaitingSearch = false;
+ document.documentElement.dataset.theme = value.theme.mode;
+ document.documentElement.dataset.fontSize = String(value.theme.fontSize);
+ document.title = value.labels.title;
+ document.getElementById("title").textContent = value.labels.title;
+ document.getElementById("count").textContent = value.loading ? "" : String(value.total);
+ input.placeholder = value.labels.search;
+ input.setAttribute("aria-label", value.labels.search);
+ if (first) { input.value = value.query; lastQuery = value.query; }
+ const focusedID = document.activeElement?.dataset?.rowId;
+ rows.replaceChildren();
+ for (const row of value.rows) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "b3-menu__item";
+ button.dataset.rowId = row.id;
+ button.disabled = value.loading || value.error;
+ const label = document.createElement("span");
+ label.className = "b3-menu__label";
+ label.textContent = row.label;
+ button.append(label);
+ button.addEventListener("click", () => { if (!pending && !button.disabled) bridge.select(row.id); });
+ rows.append(button);
+ if (focusedID === row.id) button.focus();
+ }
+ status.textContent = value.loading ? value.labels.loading : value.error ? value.labels.retry : value.rows.length ? "" : value.labels.empty;
+ more.textContent = value.error ? value.labels.retry : value.labels.more;
+ more.hidden = !value.error && (value.page * 50 >= value.total || value.rows.length >= 500);
+ more.disabled = value.loading;
+ document.getElementById("close").textContent = value.labels.close;
+ if (first) { first = false; input.focus(); }
+ });
+})();
diff --git a/app/tests/fixtures/map-unplaced-overlay/owner-preload.cjs b/app/tests/fixtures/map-unplaced-overlay/owner-preload.cjs
new file mode 100644
index 0000000000..f40a2bf7dd
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/owner-preload.cjs
@@ -0,0 +1,13 @@
+const {contextBridge, ipcRenderer} = require("electron");
+const PREFIX = "unplaced-fixture-owner-";
+contextBridge.exposeInMainWorld("fixtureOwner", Object.freeze({
+ open(value) { return ipcRenderer.invoke(PREFIX + "open", value); },
+ update(value) { ipcRenderer.send(PREFIX + "update", value); },
+ anchor(value) { ipcRenderer.send(PREFIX + "anchor", value); },
+ close(value) { ipcRenderer.send(PREFIX + "close", value); },
+ zoom() { ipcRenderer.send(PREFIX + "zoom"); },
+ permission() { ipcRenderer.send(PREFIX + "permission"); },
+ subscribe(callback) {
+ if (typeof callback === "function") ipcRenderer.on(PREFIX + "event", (_event, value) => callback(value));
+ },
+}));
diff --git a/app/tests/fixtures/map-unplaced-overlay/owner.css b/app/tests/fixtures/map-unplaced-overlay/owner.css
new file mode 100644
index 0000000000..b1dde1aeda
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/owner.css
@@ -0,0 +1,6 @@
+body { margin: 20px; font: 16px system-ui, sans-serif; }
+button { margin: 4px; padding: 8px; }
+#scroll { height: 220px; overflow: auto; position: relative; }
+#space { height: 600px; }
+#open { margin-left: 240px; }
+#result { position: fixed; bottom: 12px; }
diff --git a/app/tests/fixtures/map-unplaced-overlay/owner.html b/app/tests/fixtures/map-unplaced-overlay/owner.html
new file mode 100644
index 0000000000..557ca851df
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/owner.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="zh-CN"><head><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
+<link rel="stylesheet" href="owner.css"><script defer src="owner.js"></script>
+<title>Unplaced overlay fixture</title></head><body>
+<h1>未定位菜单独立原型</h1>
+<p>下方仅为 synthetic 地图占位视图。全部记录是合成数据,没有 OFM、内核或真实笔记连接。</p>
+<div id="actions"><button id="theme">切换主题</button><button id="zoom">切换缩放</button><button id="permission">切换权限</button></div>
+<div id="scroll"><div id="space"><button id="open">未定位记录</button></div></div>
+<p id="result" role="status"></p>
+</body></html>
diff --git a/app/tests/fixtures/map-unplaced-overlay/owner.js b/app/tests/fixtures/map-unplaced-overlay/owner.js
new file mode 100644
index 0000000000..2de8acb4a9
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/owner.js
@@ -0,0 +1,78 @@
+(() => {
+ const bridge = window.fixtureOwner;
+ const toggle = document.getElementById("open");
+ const result = document.getElementById("result");
+ const records = Array.from({length: 123}, (_, index) => ({id: "row-" + index,
+ label: index === 0 ? "PRIVATE_FIXTURE <img src=x onerror=alert(1)>" : "合成记录 " + index}));
+ const labels = {title: "未定位记录", search: "搜索", empty: "没有记录", loading: "加载中...", more: "加载更多", retry: "重试", close: "关闭"};
+ let sessionID, revision = 0, requestID = 0, page = 1, query = "", timer, generation = 0, opening = false;
+ let theme = {mode: "light", fontSize: 16};
+ const anchor = () => {
+ const rect = toggle.getBoundingClientRect();
+ const viewport = document.getElementById("scroll").getBoundingClientRect();
+ const x = Math.max(0, rect.left, viewport.left), y = Math.max(0, rect.top, viewport.top);
+ const right = Math.min(window.innerWidth, rect.right, viewport.right);
+ const bottom = Math.min(window.innerHeight, rect.bottom, viewport.bottom);
+ if (right <= x || bottom <= y) return;
+ return {x, y, width: right - x, height: bottom - y};
+ };
+ const state = (loading = false) => {
+ const filtered = records.filter(row => row.label.includes(query));
+ return {revision: ++revision, requestID, query, page: loading ? 0 : page, total: filtered.length,
+ rows: loading ? [] : filtered.slice(0, page * 50), loading, error: false, theme, labels};
+ };
+ const update = loading => { if (sessionID) bridge.update({sessionID, state: state(loading)}); };
+ const geometry = () => {
+ if (!sessionID) return;
+ const next = anchor();
+ if (next) bridge.anchor({sessionID, anchor: next});
+ else bridge.close({sessionID, reason: "anchor-hidden"});
+ };
+ toggle.addEventListener("click", async () => {
+ if (opening) return;
+ if (sessionID) { bridge.close({sessionID, reason: "button"}); return; }
+ const position = anchor();
+ if (!position) return;
+ opening = true;
+ requestID = 0;
+ page = 1;
+ query = "";
+ try { sessionID = await bridge.open({state: state(), anchor: position}); }
+ finally { opening = false; }
+ toggle.setAttribute("aria-expanded", String(!!sessionID));
+ });
+ bridge.subscribe(message => {
+ if (message.type === "closed") {
+ if (message.sessionID !== sessionID) return;
+ sessionID = undefined;
+ clearTimeout(timer);
+ generation++;
+ toggle.setAttribute("aria-expanded", "false");
+ if (message.restore) toggle.focus();
+ result.textContent = "关闭:" + message.reason;
+ return;
+ }
+ if (message.type === "select") { result.textContent = "已选择合成记录:" + message.id; return; }
+ if (message.sessionID !== sessionID) return;
+ clearTimeout(timer);
+ const current = ++generation;
+ requestID = message.requestID;
+ if (message.type === "editing") return;
+ query = message.query;
+ page = message.type === "search" ? 1 : page + 1;
+ update(true);
+ timer = setTimeout(() => { if (current === generation && sessionID === message.sessionID) update(false); }, 150);
+ });
+ document.getElementById("theme").addEventListener("click", () => {
+ theme = {mode: theme.mode === "light" ? "dark" : "light", fontSize: theme.fontSize === 16 ? 24 : 16};
+ update(false);
+ });
+ document.getElementById("zoom").addEventListener("click", () => { bridge.zoom(); setTimeout(geometry, 50); });
+ document.getElementById("permission").addEventListener("click", () => bridge.permission());
+ window.addEventListener("scroll", geometry, true);
+ document.addEventListener("pointerdown", event => {
+ if (sessionID && !toggle.contains(event.target)) bridge.close({sessionID, reason: "outside"});
+ }, true);
+ window.addEventListener("resize", geometry);
+ window.addEventListener("pagehide", () => { clearTimeout(timer); generation++; });
+})();
diff --git a/app/tests/fixtures/map-unplaced-overlay/policy.cjs b/app/tests/fixtures/map-unplaced-overlay/policy.cjs
new file mode 100644
index 0000000000..39b7117f96
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/policy.cjs
@@ -0,0 +1,68 @@
+const ORIGIN = "https://siyuan-unplaced.invalid";
+const CHANNEL = "siyuan-unplaced-fixture";
+const RESOURCES = Object.freeze({
+ "/menu.html": ["menu.html", "text/html; charset=utf-8", "mainFrame"],
+ "/menu.js": ["menu.js", "text/javascript; charset=utf-8", "script"],
+ "/menu.css": ["menu.css", "text/css; charset=utf-8", "stylesheet"],
+ "/controls.css": ["controls.css", "text/css; charset=utf-8", "stylesheet"],
+});
+const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'none'; img-src 'none'; " +
+ "font-src 'none'; media-src 'none'; frame-src 'none'; object-src 'none'; worker-src 'none'; " +
+ "base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
+const keys = (value, names) => !!value && typeof value === "object" && !Array.isArray(value) &&
+ Object.keys(value).length === names.length && names.every(name => Object.hasOwn(value, name));
+const text = (value, max) => typeof value === "string" && value.length <= max && !value.includes("\0");
+const integer = (value, max) => Number.isSafeInteger(value) && value >= 0 && value <= max;
+const isSession = value => typeof value === "string" && /^[a-f0-9]{48}$/.test(value);
+const isRevision = value => integer(value, Number.MAX_SAFE_INTEGER);
+const parseState = value => {
+ if (!keys(value, ["revision", "requestID", "query", "rows", "total", "page", "loading", "error", "theme", "labels"]) ||
+ !isRevision(value.revision) || !isRevision(value.requestID) || !text(value.query, 256) || !integer(value.total, 1000000) ||
+ !integer(value.page, 20) || typeof value.loading !== "boolean" || typeof value.error !== "boolean" ||
+ !Array.isArray(value.rows) || value.rows.length > 500 || value.rows.length > value.total || value.rows.length > value.page * 50 ||
+ !keys(value.theme, ["mode", "fontSize"]) || !["light", "dark"].includes(value.theme.mode) ||
+ ![12, 14, 16, 18, 20, 24].includes(value.theme.fontSize)) return;
+ const names = ["title", "search", "empty", "loading", "more", "retry", "close"];
+ if (!keys(value.labels, names) || names.some(name => !text(value.labels[name], 120))) return;
+ const ids = new Set();
+ const rows = [];
+ for (const row of value.rows) {
+ if (!keys(row, ["id", "label"]) || !text(row.id, 128) || !row.id || !text(row.label, 2048) || ids.has(row.id)) return;
+ ids.add(row.id);
+ rows.push({id: row.id, label: row.label});
+ }
+ return {revision: value.revision, requestID: value.requestID, query: value.query, rows, total: value.total, page: value.page,
+ loading: value.loading, error: value.error, theme: {...value.theme}, labels: {...value.labels}};
+};
+const parseAction = value => {
+ if (!value || !isSession(value.sessionID) || !isRevision(value.revision)) return;
+ const base = ["sessionID", "revision", "type"];
+ if (["ready", "editing", "more"].includes(value.type) && keys(value, base)) return {...value};
+ if (value.type === "search" && keys(value, [...base, "query"]) && text(value.query, 256)) return {...value};
+ if (value.type === "select" && keys(value, [...base, "id"]) && text(value.id, 128) && value.id) return {...value};
+ if (value.type === "close" && keys(value, [...base, "reason"]) &&
+ ["escape", "button"].includes(value.reason)) return {...value};
+};
+const parseAnchor = value => {
+ if (!keys(value, ["x", "y", "width", "height"]) ||
+ Object.values(value).some(n => !Number.isFinite(n) || Math.abs(n) > 100000) ||
+ value.width <= 0 || value.height <= 0) return;
+ return {...value};
+};
+// 缩放取主进程的真实 WebContents 值,锚点以 owner 的 CSS 像素表示。
+const place = (anchor, zoom, bounds) => {
+ if (!parseAnchor(anchor) || !Number.isFinite(zoom) || zoom < 0.25 || zoom > 5 ||
+ bounds.width < 240 || bounds.height < 160) return;
+ const a = {x: anchor.x * zoom, y: anchor.y * zoom, width: anchor.width * zoom, height: anchor.height * zoom};
+ if (a.x < 0 || a.y < 0 || a.x + a.width > bounds.width || a.y + a.height > bounds.height) return;
+ const width = Math.min(Math.round(320 * zoom), bounds.width);
+ const height = Math.min(Math.round(360 * zoom), bounds.height);
+ return {x: Math.max(0, Math.min(Math.round(a.x + a.width - width), bounds.width - width)),
+ y: Math.max(0, Math.min(Math.round(a.y + a.height), bounds.height - height)), width, height};
+};
+const resource = (url, method) => {
+ if (!["GET", "HEAD"].includes(method) || typeof url !== "string") return;
+ const item = Object.entries(RESOURCES).find(([pathname]) => url === ORIGIN + pathname);
+ return item?.[1];
+};
+module.exports = {ORIGIN, CHANNEL, RESOURCES, CSP, keys, isSession, parseState, parseAction, parseAnchor, place, resource};
diff --git a/app/tests/fixtures/map-unplaced-overlay/preload.cjs b/app/tests/fixtures/map-unplaced-overlay/preload.cjs
new file mode 100644
index 0000000000..97e56fe9ad
--- /dev/null
+++ b/app/tests/fixtures/map-unplaced-overlay/preload.cjs
@@ -0,0 +1,25 @@
+const {contextBridge, ipcRenderer} = require("electron");
+const CHANNEL = "siyuan-unplaced-fixture";
+const sessionID = process.argv.find(value => value.startsWith("--unplaced-session="))?.slice(19);
+let revision = 0, subscribed = false, listener;
+const send = (type, data = {}) => {
+ if (/^[a-f0-9]{48}$/.test(sessionID)) ipcRenderer.send(CHANNEL + "-action", {sessionID, revision, type, ...data});
+};
+ipcRenderer.on(CHANNEL + "-state", (_event, value) => {
+ if (value?.sessionID !== sessionID || !Number.isSafeInteger(value.state?.revision) || value.state.revision < revision) return;
+ revision = value.state.revision;
+ listener?.(value.state);
+});
+contextBridge.exposeInMainWorld("unplacedMenu", Object.freeze({
+ subscribe(callback) {
+ if (subscribed || typeof callback !== "function") return;
+ subscribed = true;
+ listener = callback;
+ send("ready");
+ },
+ search(query) { if (typeof query === "string" && query.length <= 256) send("search", {query}); },
+ editing() { send("editing"); },
+ more() { send("more"); },
+ select(id) { if (typeof id === "string" && id.length <= 128) send("select", {id}); },
+ close(reason) { if (["escape", "button"].includes(reason)) send("close", {reason}); },
+}));
diff --git a/app/tests/mapAttribution.test.js b/app/tests/mapAttribution.test.js
index 19f9d121ba..dcf707125a 100644
--- a/app/tests/mapAttribution.test.js
+++ b/app/tests/mapAttribution.test.js
@@ -12,12 +12,16 @@ const install = (sources, css, controlledClock) => {
const modules = {};
for (const [name, source] of Object.entries(sources)) {
const exports = {};
- new Function("require", "exports", source)(name => modules[name.slice(2)], exports);
+ new Function("require", "exports", source)(name => {
+ assertModule(name, modules[name.slice(2)]);
+ return modules[name.slice(2)];
+ }, exports);
modules[name] = exports;
}
const container = document.getElementById("map");
class FakeMap {
callbacks = new Map();
+ controls = [];
style = {stylesheet: {}, tileManagers: {source: {used: true, getSource: () => ({attribution:
'<a href="https://openfreemap.org" target="_blank">OpenFreeMap</a> ' +
'<a href="https://www.openmaptiles.org/" target="_blank">&copy; OpenMapTiles</a> ' +
@@ -29,16 +33,17 @@ const install = (sources, css, controlledClock) => {
off(name, callback) {
this.callbacks.set(name, this.callbacks.get(name)?.filter(item => item !== callback) || []);
}
- remove() {}
+ remove() { this.controls.forEach(control => control.onRemove()); }
getCanvasContainer() { return container; }
_getUIString() { return "Toggle attribution"; }
addControl(control) {
+ this.controls.push(control);
const wrapper = document.createElement("div");
wrapper.className = "maplibregl-ctrl-bottom-right";
container.append(wrapper);
wrapper.append(control.onAdd(this));
}
- emit(name) { this.callbacks.get(name)?.forEach(callback => callback()); }
+ emit(name) { this.callbacks.get(name)?.slice().forEach(callback => callback()); }
constructor() { window.mapFixture = this; }
}
if (controlledClock) {
@@ -52,6 +57,7 @@ const install = (sources, css, controlledClock) => {
frames.clear();
pending.forEach(callback => callback(now));
};
+ window.pendingAttributionFrames = () => frames.size;
}
window.attributionLinks = [];
window.attributionAdapter = modules.providers.createAVMapAdapter("openfreemap", {
@@ -63,6 +69,111 @@ const install = (sources, css, controlledClock) => {
window.mapFixture.emit("load");
};
+const assertModule = (name, module) => {
+ if (!module) throw new Error(`Unknown fixture module: ${name}`);
+};
+
+const verifyTileHTTP = async (win, sources, css, sdk) => {
+ const http = require("node:http");
+ const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADUlEQVQImWOoWHDiPwAGVALgQhC29AAAAABJRU5ErkJggg==", "base64");
+ let failNextTile = false;
+ let failedTiles = 0;
+ const server = http.createServer((request, response) => {
+ if (request.url === "/") {
+ response.setHeader("Content-Type", "text/html");
+ response.end("<!doctype html><html><head></head><body style='margin:0'><div id='map' style='width:800px;height:600px'></div></body></html>");
+ } else if (request.url === "/worker.js") {
+ response.setHeader("Content-Type", "text/javascript");
+ response.end(fs.readFileSync(require.resolve("maplibre-gl/dist/maplibre-gl-csp-worker.js")));
+ } else if (/^\/tile\/\d+\/\d+\/\d+\.png$/.test(request.url)) {
+ if (failNextTile) {
+ failNextTile = false;
+ failedTiles++;
+ response.writeHead(503).end("Temporary fixture failure");
+ } else {
+ response.setHeader("Content-Type", "image/png");
+ response.end(png);
+ }
+ } else {
+ response.writeHead(404).end();
+ }
+ });
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ try {
+ await win.loadURL(origin);
+ await win.webContents.executeJavaScript(sdk);
+ const installRealMap = (sources, css, origin) => new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("Fixture map did not load")), 15000);
+ const style = document.createElement("style");
+ style.textContent = css;
+ document.head.append(style);
+ const modules = {};
+ for (const [name, source] of Object.entries(sources)) {
+ const exports = {};
+ new Function("require", "exports", source)(name => {
+ if (!modules[name.slice(2)]) throw new Error(`Unknown fixture module: ${name}`);
+ return modules[name.slice(2)];
+ }, exports);
+ modules[name] = exports;
+ }
+ const sdk = window.maplibregl;
+ sdk.setWorkerUrl(origin + "/worker.js");
+ window.tileHTTP = {errors: [], removed: 0, tileError: null};
+ class FixtureMap extends sdk.Map {
+ constructor(options) {
+ super({...options, style: {version: 8, sources: {fixture: {type: "raster", tileSize: 256,
+ tiles: [origin + "/tile/{z}/{x}/{y}.png"], minzoom: 0, maxzoom: 6, attribution: "Fixture data"}},
+ layers: [{id: "fixture", type: "raster", source: "fixture"}]}});
+ window.tileMap = this;
+ this.on("error", event => {
+ window.tileHTTP.tileError = {status: event.error?.status, sourceId: event.sourceId,
+ state: event.tile?.state, canonical: event.tile?.tileID?.canonical};
+ });
+ }
+ remove() { window.tileHTTP.removed++; super.remove(); }
+ }
+ window.tileAdapter = modules.providers.createAVMapAdapter("openfreemap", {...sdk, Map: FixtureMap},
+ document.getElementById("map"), {onMarkerClick() {}, onReady() { clearTimeout(timer); resolve(); },
+ onError(code) {
+ window.tileHTTP.errors.push(code);
+ window.tileAdapter?.destroy();
+ clearTimeout(timer);
+ reject(new Error("Fixture map failed: " + code));
+ }});
+ });
+ await win.webContents.executeJavaScript(`(${installRealMap.toString()})(${JSON.stringify(sources)},
+ ${JSON.stringify(css)}, ${JSON.stringify(origin)})`);
+ failNextTile = true;
+ await win.webContents.executeJavaScript("tileMap.setZoom(3); void 0");
+ const deadline = Date.now() + 10000;
+ let state;
+ do {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ state = await win.webContents.executeJavaScript("tileHTTP");
+ } while (!state.tileError && Date.now() < deadline);
+ assert.equal(failedTiles, 1);
+ assert.equal(state.tileError?.status, 503);
+ assert.equal(state.tileError.sourceId, "fixture");
+ assert.equal(state.tileError.state, "errored");
+ assert.ok(Number.isInteger(state.tileError.canonical.z));
+ assert.deepEqual(state.errors, []);
+ assert.equal(state.removed, 0, "a real HTTP tile 503 preserves the loaded SDK map");
+ await win.webContents.executeJavaScript("tileAdapter.setPoints([{id:'fixture', longitude:0, latitude:0}],1); void 0");
+ assert.equal(await win.webContents.executeJavaScript("document.querySelectorAll('.maplibregl-marker').length"), 1);
+ await win.webContents.executeJavaScript("tileMap.fire('error', {error: new Error('fixture fatal worker')}); void 0");
+ state = await win.webContents.executeJavaScript("tileHTTP");
+ assert.deepEqual(state.errors, ["mapUnavailable"]);
+ assert.equal(state.removed, 1, "unclassified SDK errors retain the fatal cleanup path");
+ } finally {
+ await win.webContents.executeJavaScript("window.tileAdapter?.destroy()");
+ await new Promise(resolve => server.close(resolve));
+ }
+};
+
const inspect = () => {
const attribution = document.querySelector(".maplibregl-ctrl-attrib");
const text = attribution.querySelector(".maplibregl-ctrl-attrib-inner");
@@ -88,7 +199,9 @@ if (process.versions.electron && process.type === "browser") {
path.join(__dirname, "../src/protyle/render/av/map", name + ".ts"), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
}).outputText;
- const sources = {protocol: compile("protocol"), providers: compile("providers")};
+ const sources = Object.fromEntries(["protocol", "attribution", "providers"]
+ .filter(name => fs.existsSync(path.join(__dirname, "../src/protyle/render/av/map", name + ".ts")))
+ .map(name => [name, compile(name)]));
const css = fs.readFileSync(require.resolve("maplibre-gl/dist/maplibre-gl.css"), "utf8");
const sdk = fs.readFileSync(require.resolve("maplibre-gl/dist/maplibre-gl-csp.js"), "utf8");
const evaluate = source => win.webContents.executeJavaScript(source);
@@ -96,7 +209,8 @@ if (process.versions.electron && process.type === "browser") {
const setup = async controlled => {
await win.loadURL("data:text/html,<html><head></head><body></body></html>");
await evaluate(sdk);
- await evaluate(`(${install.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(css)}, ${controlled})`);
+ await evaluate(`const assertModule = ${assertModule.toString()};
+ (${install.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(css)}, ${controlled})`);
};
await setup(false);
const initial = await state();
@@ -114,6 +228,12 @@ if (process.versions.electron && process.type === "browser") {
assert.equal((await state()).textVisible, false);
await evaluate("window.attributionAdapter.destroy()");
+ await setup(true);
+ await evaluate("document.getElementById('map').style.width = '780px'; advanceAttribution(0); advanceAttribution(4000)");
+ await evaluate("attributionAdapter.setVisible(true, {x: 0, y: 0, width: 790, height: 600}); advanceAttribution(1000)");
+ assert.equal((await state()).open, false, "an entirely visible viewport change preserves four elapsed seconds");
+ await evaluate("window.attributionAdapter.destroy()");
+
await setup(true);
win.webContents.debugger.attach("1.3");
await win.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {enabled: true});
@@ -154,6 +274,9 @@ if (process.versions.electron && process.type === "browser") {
await click("summary");
assert.equal((await state()).open, false);
await evaluate("window.attributionAdapter.destroy()");
+ assert.deepEqual(await evaluate("[pendingAttributionFrames(), [...mapFixture.callbacks.values()].flat().length]"), [0, 0],
+ "destroy releases application and real SDK control listeners");
+ await verifyTileHTTP(win, sources, css, sdk);
} catch (error) {
console.error(error);
code = 1;
@@ -174,7 +297,7 @@ if (process.versions.electron && process.type === "browser") {
const env = {...process.env};
delete env.ELECTRON_RUN_AS_NODE;
try {
- await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 30000});
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 60000});
} finally {
assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
diff --git a/app/tests/mapHostBoundary.test.js b/app/tests/mapHostBoundary.test.js
new file mode 100644
index 0000000000..04bfe7cec7
--- /dev/null
+++ b/app/tests/mapHostBoundary.test.js
@@ -0,0 +1,212 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+// 真实 owner、主进程、预载与原生子视图;固定 adapter 只隔离 OFM 网络和 WebGL。
+const runBoundaryFixture = async (profile) => {
+ const {app, BrowserWindow, WebContentsView, MessageChannelMain, ipcMain, session} = require("electron");
+ const {createMapHostManager} = require("../electron/mapHostManager");
+ const http = require("node:http");
+ const ts = require("typescript");
+ app.setPath("userData", profile);
+ await app.whenReady();
+ const mapDirectory = path.join(__dirname, "../src/protyle/render/av/map");
+ const compile = name => ts.transpileModule(fs.readFileSync(path.join(mapDirectory, name + ".ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ const bundle = (names, extra, entry, electron = false) => {
+ const modules = {...Object.fromEntries(names.map(name => ["./" + name, compile(name)])), ...extra};
+ return `(() => {
+ const modules = {${Object.entries(modules).map(([name, source]) =>
+ `${JSON.stringify(name)}: (require, exports) => {${source}\n}`).join(",")}};
+ const cache = {};
+ const load = name => {
+ ${electron ? 'if (name === "electron") return require("electron");' : ""}
+ if (!modules[name]) throw new Error("Unknown fixture module");
+ if (!cache[name]) { cache[name] = {}; modules[name](load, cache[name]); }
+ return cache[name];
+ };
+ ${entry}
+ })();`;
+ };
+ let owner, manager, server;
+ const views = [];
+ let privateRequests = 0;
+ try {
+ server = http.createServer((request, response) => {
+ if (request.url !== "/stage/build/app/") {
+ if (request.url.startsWith("/api/")) privateRequests++;
+ response.writeHead(403).end();
+ return;
+ }
+ response.setHeader("Content-Type", "text/html");
+ response.end('<!doctype html><html><body style="margin:0"><div id="map" ' +
+ 'style="position:fixed;left:10px;top:20px;width:400px;height:300px"></div></body></html>');
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ const runtime = bundle(["protocol", "loadingBudget", "bootstrap", "hostRuntime"], {
+ "./providersLoader": `
+ window.mapFixture = {fits: 0, revisions: [], destroyed: 0};
+ exports.prepareAVMapAssets = async () => {
+ await new Promise(resolve => { window.releaseFixtureBootstrap = resolve; });
+ return {lock() {}, destroy() { window.mapFixture.assetsDestroyed = true; }};
+ };
+ exports.loadAVMapAdapter = async (_init, _container, callbacks) => {
+ if (window.rejectFixtureMap) throw new Error("private-fixture-path?token=secret");
+ window.mapFixture.callbacks = callbacks;
+ return {
+ setPoints(points, revision) { window.mapFixture.revisions.push(revision); },
+ fit() { window.mapFixture.fits++; },
+ resize() {}, setTheme() {}, setVisible() {},
+ destroy() { window.mapFixture.destroyed++; }
+ };
+ };`,
+ }, 'load("./hostRuntime").connectAVMapRuntime(window);');
+ const fixtureFiles = new Map([
+ ["stage/map/index.html", Buffer.from("<!doctype html><html><head><script defer " +
+ 'src="/stage/build/map/host.js"></script></head><body style="margin:0"><div id="map"></div></body></html>')],
+ ["stage/build/map/host.js", Buffer.from(runtime)],
+ ]);
+ owner = new BrowserWindow({width: 800, height: 600, useContentSize: true, show: true,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false}});
+ manager = createMapHostManager({app, ipcMain, session, BrowserWindow, MessageChannelMain,
+ WebContentsView: function (options) {
+ const view = new WebContentsView(options);
+ views.push(view);
+ return view;
+ },
+ getTarget: id => id === owner.webContents.id ? {origin} : undefined,
+ isInitialized: id => id === owner.webContents.id, appDir: path.join(__dirname, ".."),
+ readFile: async filename => {
+ const key = path.relative(path.join(__dirname, ".."), filename).split(path.sep).join("/");
+ if (!fixtureFiles.has(key)) throw new Error("Unknown fixture asset");
+ return fixtureFiles.get(key);
+ }});
+ await owner.loadURL(origin + "/stage/build/app/");
+ const evaluate = script => owner.webContents.executeJavaScript(script);
+ const waitFor = async (predicate, label) => {
+ const deadline = Date.now() + 5000;
+ while (!await predicate()) {
+ assert.ok(Date.now() < deadline, label);
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ };
+ await evaluate(bundle(["protocol", "loadingBudget", "unplacedMenu", "desktopGeometry", "desktopGeometryDOM", "desktopTransport"], {}, `
+ window.ownerFixture = {ready: 0, errors: [], links: []};
+ window.mapContainer = document.getElementById("map");
+ window.startFixtureHost = () => load("./desktopTransport").createDesktopAVMapHost(window.mapContainer, {
+ provider: "openfreemap", theme: "light", onMarkerClick() {},
+ onReady() { window.ownerFixture.ready++; },
+ onError(code) { window.ownerFixture.errors.push(code); },
+ onAttributionClick(link) { window.ownerFixture.links.push(link); }
+ });
+ window.mapHost = window.startFixtureHost();
+ window.mapHost.setPoints([{id: "row-1", longitude: 0, latitude: 0}], 1);
+ window.openFixtureMenu = () => {
+ const menu = document.createElement("div");
+ menu.className = "b3-menu";
+ menu.style.cssText = "position:fixed;left:250px;top:20px;width:150px;height:200px;background:white;z-index:10";
+ document.body.appendChild(menu);
+ const release = load("./unplacedMenu").registerMapUnplacedMenu(menu, window.mapContainer);
+ window.closeFixtureMenu = () => { release(); menu.remove(); };
+ };
+ `, true));
+ await waitFor(() => views.length === 1, "one native view is created");
+ const view = views[0], map = view.webContents;
+ const inspectMap = script => map.executeJavaScript(script);
+ await waitFor(() => inspectMap("typeof window.releaseFixtureBootstrap === 'function'"), "the real preload transfers its port");
+ assert.equal(view.getVisible(), false);
+ assert.equal(await evaluate("window.ownerFixture.ready"), 0);
+ assert.deepEqual(await inspectMap("({origin: window.origin, node: typeof require, bridge: window.siyuanMapDesktop.version})"),
+ {origin: "null", node: "undefined", bridge: 1});
+ await inspectMap("window.releaseFixtureBootstrap()");
+ await waitFor(() => evaluate("window.ownerFixture.ready === 1"), "runtime ready crosses the main process");
+ await waitFor(() => view.getVisible(), "the stable native map becomes visible");
+ const fullBounds = view.getBounds();
+ assert.equal(fullBounds.width, 400);
+ assert.deepEqual(await inspectMap("({fits: window.mapFixture.fits, revisions: window.mapFixture.revisions})"),
+ {fits: 1, revisions: [1]});
+ await evaluate("window.openFixtureMenu()");
+ await waitFor(() => view.getVisible() && view.getBounds().width < fullBounds.width, "an owned menu crops the real native view");
+ assert.equal(await inspectMap("document.getElementById('map').style.width"), "400px");
+ await evaluate("window.closeFixtureMenu()");
+ await waitFor(() => view.getVisible() && view.getBounds().width === fullBounds.width, "menu closure restores the native view");
+ assert.equal(await inspectMap("window.mapFixture.fits"), 1);
+ owner.hide();
+ await waitFor(() => !view.getVisible(), "hiding the actual owner hides its native child view");
+ owner.show();
+ await waitFor(() => view.getVisible(), "showing the owner restores verified native geometry");
+ assert.deepEqual(view.getBounds(), fullBounds);
+ assert.equal(await inspectMap("window.mapFixture.fits"), 1);
+ owner.webContents.setZoomFactor(1.25);
+ await waitFor(() => view.getVisible() && view.getBounds().width > fullBounds.width, "owner zoom is applied once");
+ assert.equal(map.getZoomFactor(), 1.25);
+ await evaluate("window.mapContainer.style.top = '-20px'; window.dispatchEvent(new Event('scroll'));");
+ await waitFor(() => view.getVisible() && view.getBounds().y < 5, "scroll updates native cropping");
+ assert.ok(view.getBounds().y >= 0);
+ assert.match(await inspectMap("document.getElementById('map').style.transform"), /translate\(/);
+ const privateURL = origin + "/api/map-fixture-private";
+ assert.equal(await inspectMap(`fetch(${JSON.stringify(privateURL)}).then(() => false, () => true)`), true);
+ assert.equal(await inspectMap(`new Promise(resolve => {
+ const source = "fetch(" + ${JSON.stringify(JSON.stringify(privateURL))} + ").then(() => postMessage(false), () => postMessage(true))";
+ const url = URL.createObjectURL(new Blob([source], {type: "text/javascript"}));
+ const worker = new Worker(url);
+ worker.onmessage = event => { worker.terminate(); URL.revokeObjectURL(url); resolve(event.data); };
+ worker.onerror = () => { worker.terminate(); URL.revokeObjectURL(url); resolve(false); };
+ })`), true, "the locked worker cannot connect to the owner API");
+ const entryURL = map.getURL();
+ await inspectMap(`window.location.href = ${JSON.stringify(privateURL)}`);
+ await new Promise(resolve => setTimeout(resolve, 100));
+ assert.equal(map.getURL(), entryURL);
+ assert.equal(privateRequests, 0);
+ await inspectMap("window.mapFixture.callbacks.onAttributionClick('maplibre')");
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.deepEqual(await evaluate("window.ownerFixture"), {ready: 1, errors: [], links: []});
+ await evaluate("window.mapHost.destroy(); window.mapHost.destroy()");
+ await waitFor(() => map.isDestroyed(), "destroy closes the actual isolated renderer");
+ assert.equal(owner.contentView.children.includes(view), false);
+ await evaluate("window.mapHost = window.startFixtureHost()");
+ await waitFor(() => views.length === 2, "a replacement receives an independent native view");
+ const failedMap = views[1].webContents;
+ await waitFor(() => failedMap.executeJavaScript("typeof window.releaseFixtureBootstrap === 'function'"), "replacement bootstrap receives its port");
+ await failedMap.executeJavaScript("window.rejectFixtureMap = true; window.releaseFixtureBootstrap()");
+ await waitFor(() => failedMap.isDestroyed(), "a failed adapter closes its real native renderer");
+ assert.deepEqual(await evaluate("window.ownerFixture.errors"), ["sdkUnavailable"]);
+ assert.equal((await evaluate("JSON.stringify(window.ownerFixture)")).includes("secret"), false);
+ } finally {
+ manager?.destroyAll();
+ if (owner && !owner.isDestroyed()) owner.destroy();
+ if (server) {
+ server.closeAllConnections?.();
+ await new Promise(resolve => server.close(resolve));
+ }
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app} = require("electron");
+ runBoundaryFixture(process.argv[2]).then(() => app.exit(0), error => {
+ console.error(error);
+ app.exit(1);
+ });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("real Electron owner, main, preload and isolated map enforce native geometry, CSP and teardown", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY
+ ? "Real Electron boundary verification requires DISPLAY or WAYLAND_DISPLAY" : false,
+ }, async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-map-boundary-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 30000});
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}
diff --git a/app/tests/mapUnplacedOverlay.test.js b/app/tests/mapUnplacedOverlay.test.js
new file mode 100644
index 0000000000..1e7ab5decd
--- /dev/null
+++ b/app/tests/mapUnplacedOverlay.test.js
@@ -0,0 +1,392 @@
+const assert = require("node:assert/strict");
+const {test} = require("node:test");
+const {EventEmitter} = require("node:events");
+const fs = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+const vm = require("node:vm");
+const {ORIGIN, CHANNEL, CSP, parseState, parseAction, resource, place} = require("./fixtures/map-unplaced-overlay/policy.cjs");
+const {createRouter, createManager} = require("./fixtures/map-unplaced-overlay/manager.cjs");
+const fixtureDirectory = path.join(__dirname, "fixtures/map-unplaced-overlay");
+const ownerURL = "file:///fixture/owner.html";
+const state = (extra = {}) => ({revision: 1, requestID: 0, query: "", rows: [{id: "row-1", label: "Private <img src=x>"}],
+ total: 123, page: 1, loading: false, error: false, theme: {mode: "light", fontSize: 16},
+ labels: {title: "List", search: "Search", empty: "Empty", loading: "Loading", more: "More", retry: "Retry", close: "Close"}, ...extra});
+const anchor = {x: 100, y: 50, width: 160, height: 30};
+const createSession = () => {
+ const ses = Object.assign(new EventEmitter(), {handlers: {}, protocols: {}, cleanup: []});
+ for (const name of ["setPermissionRequestHandler", "setPermissionCheckHandler", "setDevicePermissionHandler",
+ "setDisplayMediaRequestHandler", "setCertificateVerifyProc", "allowNTLMCredentialsForDomains"]) {
+ ses[name] = fn => { ses.handlers[name] = fn; };
+ }
+ for (const name of ["closeAllConnections", "clearStorageData", "clearAuthCache", "clearCache", "clearHostResolverCache"]) {
+ ses[name] = async () => ses.cleanup.push(name);
+ }
+ ses.webRequest = {onBeforeRequest: fn => { ses.handlers.before = fn; },
+ onBeforeSendHeaders: fn => { ses.handlers.headers = fn; }};
+ ses.protocol = {handle: (scheme, fn) => { ses.protocols[scheme] = fn; }};
+ return ses;
+};
+const createContents = url => Object.assign(new EventEmitter(), {
+ mainFrame: {url}, dead: false, sent: [], focused: 0, zoom: 1,
+ isDestroyed() { return this.dead; },
+ getZoomFactor() { return this.zoom; },
+ setZoomFactor(value) { this.zoom = value; },
+ setWindowOpenHandler(fn) { this.popup = fn; },
+ loadURL(value) { this.mainFrame.url = value; return Promise.resolve(); },
+ focus() { this.focused++; },
+ stop() {},
+ close() { this.dead = true; this.emit("destroyed"); },
+ send(channel, value) { this.sent.push([channel, value]); },
+});
+const setup = (fail = "") => {
+ const ipcMain = new EventEmitter(), owner = createContents(ownerURL), map = createContents("data:synthetic");
+ const sessions = [], views = [], actions = [], closed = [], children = [];
+ let allowed = true, counter = 0;
+ const win = Object.assign(new EventEmitter(), {bounds: {width: 800, height: 600}, visible: true,
+ isDestroyed: () => false, isFocused: () => true, isVisible() { return this.visible; }, getContentBounds() { return this.bounds; },
+ contentView: {addChildView(view) { if (fail === "attach") throw new Error("attach"); children.push(view); },
+ removeChildView(view) { const index = children.indexOf(view); if (index >= 0) children.splice(index, 1); }}});
+ const manager = createManager({ipcMain, owner, win, ownerURL, outsideContents: [map], assets: {controls: ""},
+ session: {fromPartition(name) { const ses = createSession(); ses.partition = name; sessions.push(ses); return ses; }},
+ WebContentsView: function (options) {
+ if (fail === "constructor") throw new Error("constructor");
+ const webContents = createContents("");
+ if (fail === "load") webContents.loadURL = () => Promise.reject(new Error("load"));
+ const view = {options, webContents, bounds: [], visibility: [],
+ setBounds(value) { if (fail === "bounds") throw new Error("bounds"); this.bounds.push(value); },
+ setVisible(value) { this.visibility.push(value); }};
+ views.push(view);
+ return view;
+ }, mayUse: () => allowed, randomID: () => (++counter).toString(16).padStart(48, "0"),
+ onAction: value => actions.push(value), onClose: value => closed.push(value)});
+ const event = {sender: owner, senderFrame: owner.mainFrame};
+ const open = value => manager.open(event, {state: state(value), anchor});
+ const action = (type, extra = {}, eventOverride) => {
+ const current = manager.inspect();
+ const contents = current?.view.webContents || views.at(-1).webContents;
+ ipcMain.emit(CHANNEL + "-action", eventOverride || {sender: contents, senderFrame: contents.mainFrame},
+ {sessionID: current?.sessionID, revision: type === "ready" ? 0 : 1, type, ...extra});
+ };
+ return {manager, event, open, action, owner, map, win, sessions, views, actions, closed, children, ipcMain,
+ revoke() { allowed = false; }};
+};
+
+test("overlay strict schemas copy bounded plain text and reject URLs, HTML fields, duplicate IDs and CSS", () => {
+ const source = state(), result = parseState(source);
+ assert.deepEqual(result, source);
+ assert.notEqual(result.rows, source.rows);
+ for (const value of [state({url: "https://evil.invalid"}), state({rows: [{id: "a", label: "x", html: "<b>"}]}),
+ state({rows: [{id: "a", label: "x"}, {id: "a", label: "y"}]}), state({query: "x".repeat(257)}),
+ state({theme: {mode: "dark", fontSize: 17}}), state({theme: {mode: "dark", fontSize: 16, css: "url(https://evil)"}}),
+ state({revision: NaN}), state({total: -1}), state({page: 0}), state({rows: [{id: "x", label: "x".repeat(2049)}]})]) {
+ assert.equal(parseState(value), undefined);
+ }
+ const envelope = {sessionID: "a".repeat(48), revision: 1, type: "select", id: "row-1"};
+ assert.deepEqual(parseAction(envelope), envelope);
+ for (const value of [{...envelope, url: "https://evil"}, {...envelope, sessionID: "bad"},
+ {...envelope, revision: -1}, {...envelope, type: "execute"}]) assert.equal(parseAction(value), undefined);
+ assert.equal(resource(ORIGIN + "/menu.html", "GET")[0], "menu.html");
+ for (const url of [ORIGIN + "/%6denu.html", ORIGIN + "/x/../menu.html", ORIGIN + "/menu.html?x", ORIGIN + "/menu.html#x",
+ "https://[email protected]/menu.html", "https://evil.invalid/menu.html"]) assert.equal(resource(url, "GET"), undefined);
+ assert.equal(resource(ORIGIN + "/menu.html", "POST"), undefined);
+ assert.doesNotMatch(CSP, /unsafe-inline|unsafe-eval/);
+});
+
+test("overlay router denies all networking, permissions, credentials, frames, repeat navigation and destroyed requests", async () => {
+ const ses = createSession(), files = [];
+ const router = createRouter(ses, {controls: "shared"}, async filename => { files.push(filename); return "local"; });
+ const before = (url, resourceType, method = "GET") => {
+ let answer;
+ ses.handlers.before({url, resourceType, method}, value => { answer = value; });
+ return answer.cancel;
+ };
+ assert.equal(before(ORIGIN + "/menu.html", "mainFrame"), false);
+ assert.equal(before(ORIGIN + "/menu.html", "mainFrame"), true);
+ assert.equal(before(ORIGIN + "/menu.js", "script"), false);
+ for (const type of ["subFrame", "xhr", "webSocket", "other"]) assert.equal(before(ORIGIN + "/menu.js", type), true);
+ for (const url of ["https://tiles.openfreemap.org/private", "http://127.0.0.1:6806/api/sql", "file:///etc/passwd", "data:text/html,hi", "blob:x"]) {
+ assert.equal(before(url, "script"), true);
+ }
+ const response = await ses.protocols.https(new Request(ORIGIN + "/menu.html"));
+ assert.equal(await response.text(), "local");
+ assert.equal(response.headers.get("content-security-policy"), CSP);
+ assert.deepEqual(files, [path.join(fixtureDirectory, "menu.html")]);
+ assert.equal((await ses.protocols.https(new Request(ORIGIN + "/menu.js", {headers: {"service-worker": "script"}}))).status, 403);
+ assert.equal((await ses.protocols.http(new Request("http://127.0.0.1"))).status, 403);
+ assert.equal((await ses.protocols.file()).status, 403);
+ let value;
+ ses.handlers.setPermissionRequestHandler({}, "clipboard-read", answer => { value = answer; });
+ assert.equal(value, false);
+ assert.equal(ses.handlers.setPermissionCheckHandler(), false);
+ assert.equal(ses.handlers.setDevicePermissionHandler(), false);
+ ses.handlers.headers({requestHeaders: {Cookie: "secret"}}, answer => { value = answer; });
+ assert.deepEqual(value.requestHeaders, {});
+ router.destroy();
+ assert.equal(before(ORIGIN + "/menu.js", "script"), true);
+ assert.equal((await ses.protocols.https(new Request(ORIGIN + "/menu.js"))).status, 403);
+ assert.equal(ses.cleanup.length, 5);
+});
+
+test("overlay owner/frame/session binding, request invalidation and membership gate reject stale and foreign selections", () => {
+ const f = setup();
+ try {
+ assert.equal(f.manager.open({...f.event, senderFrame: {}}, {state: state(), anchor}), undefined);
+ const sessionID = f.open();
+ f.action("ready");
+ const options = f.views[0].options.webPreferences;
+ assert.equal(options.sandbox, true);
+ assert.equal(options.contextIsolation, true);
+ assert.equal(options.nodeIntegration, false);
+ assert.equal(options.webSecurity, true);
+ assert.equal(options.webviewTag, false);
+ assert.ok(!f.sessions[0].partition.startsWith("persist:"));
+ assert.deepEqual(f.views[0].visibility, [false, true]);
+ f.action("select", {id: "row-1"}, {sender: f.map, senderFrame: f.map.mainFrame});
+ f.action("select", {id: "missing"});
+ f.action("select", {id: "row-1", sessionID: "f".repeat(48)});
+ assert.equal(f.actions.length, 0);
+ f.action("editing");
+ f.action("select", {id: "row-1"});
+ assert.equal(f.actions.length, 1);
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2})}), false);
+ f.action("search", {query: "new"});
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, query: "old"})}), false);
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, requestID: 2, query: "new", loading: true})}), true);
+ f.action("select", {id: "row-1", revision: 2});
+ assert.equal(f.actions.length, 2);
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 3, requestID: 2, query: "new", rows: [{id: "new", label: "new"}]})}), true);
+ f.action("select", {id: "row-1", revision: 3});
+ f.action("select", {id: "new", revision: 2});
+ assert.equal(f.actions.length, 2);
+ f.action("select", {id: "new", revision: 3});
+ assert.equal(f.actions.at(-1).id, "new");
+ assert.equal(f.manager.inspect(), undefined);
+ assert.equal(f.owner.focused, 1);
+ const replacement = f.open();
+ assert.notEqual(replacement, sessionID);
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 99})}), false);
+ } finally { f.manager.destroy(); }
+});
+
+test("initial loading completes and main-issued request generations reject late A-to-B-to-A results", () => {
+ const f = setup();
+ try {
+ const sessionID = f.open({loading: true, rows: []});
+ f.action("ready");
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2, query: "wrong"})}), false);
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 2})}), true);
+ f.action("search", {revision: 2, query: "A"});
+ f.action("search", {revision: 2, query: "B"});
+ f.action("search", {revision: 2, query: "A"});
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 3, requestID: 1, query: "A"})}), false);
+ assert.equal(f.manager.update(f.event, {sessionID, state: state({revision: 4, requestID: 3, query: "A"})}), true);
+ } finally { f.manager.destroy(); }
+});
+
+test("overlay pagination gates, permission revocation and owner navigation destroy private state", () => {
+ const f = setup();
+ try {
+ f.open(); f.action("ready"); f.action("more"); f.action("more");
+ assert.equal(f.actions.length, 1);
+ f.revoke(); f.action("select", {id: "row-1"});
+ assert.equal(f.manager.inspect(), undefined);
+ assert.equal(f.closed.at(-1).reason, "permission-revoked");
+ } finally { f.manager.destroy(); }
+ for (const operation of [f => f.owner.emit("did-start-navigation", {isMainFrame: true}),
+ f => { f.owner.mainFrame.url = "file:///other.html"; f.action("select", {id: "row-1"}); },
+ f => f.owner.emit("destroyed"), f => f.win.emit("closed")]) {
+ const fixture = setup();
+ fixture.open(); fixture.action("ready"); operation(fixture);
+ assert.equal(fixture.manager.inspect(), undefined);
+ assert.equal(fixture.views[0].webContents.dead, true);
+ assert.equal(fixture.children.length, 0);
+ assert.equal(fixture.sessions[0].cleanup.length, 5);
+ fixture.manager.destroy();
+ assert.equal(fixture.ipcMain.listenerCount(CHANNEL + "-action"), 0);
+ }
+});
+
+test("overlay anchors use actual zoom/content bounds; geometry is deduplicated and focus transitions do not hide", () => {
+ const f = setup();
+ try {
+ const sessionID = f.open(); f.action("ready");
+ const view = f.views[0];
+ f.owner.emit("blur");
+ assert.ok(f.manager.inspect());
+ const count = view.bounds.length;
+ f.manager.setAnchor(f.event, {sessionID, anchor});
+ assert.equal(view.bounds.length, count);
+ f.owner.zoom = 1.25;
+ f.manager.setAnchor(f.event, {sessionID, anchor: {...anchor, y: 100}});
+ assert.deepEqual(view.bounds.at(-1), place({...anchor, y: 100}, 1.25, f.win.bounds));
+ assert.deepEqual(view.visibility, [false, true]);
+ f.map.emit("before-mouse-event", {}, {type: "mouseDown"});
+ assert.equal(f.manager.inspect(), undefined);
+ assert.equal(f.owner.focused, 0);
+ f.open(); f.action("ready");
+ f.win.bounds = {width: 100, height: 100}; f.win.emit("resize");
+ assert.equal(f.manager.inspect(), undefined);
+ } finally { f.manager.destroy(); }
+});
+
+test("overlay setup failures close sessions, views and listeners transactionally", async () => {
+ for (const failure of ["constructor", "attach", "bounds", "load"]) {
+ const f = setup(failure);
+ f.open();
+ await Promise.resolve();
+ assert.equal(f.manager.inspect(), undefined, failure);
+ assert.equal(f.children.length, 0, failure);
+ assert.equal(f.sessions[0].cleanup.length, 5, failure);
+ if (f.views[0]) assert.equal(f.views[0].webContents.dead, true, failure);
+ f.manager.destroy();
+ assert.equal(f.ipcMain.listenerCount(CHANNEL + "-action"), 0, failure);
+ }
+});
+
+test("manual harness requires an explicit profile and owns only its fresh temporary directory", async () => {
+ const {createHarness, createTemporaryProfile} = require("./fixtures/map-unplaced-overlay/harness.cjs");
+ await assert.rejects(createHarness(), /explicit isolated fixture profile/);
+ const temporary = createTemporaryProfile();
+ try {
+ assert.equal(path.dirname(temporary.profile), os.tmpdir());
+ assert.ok(path.basename(temporary.profile).startsWith("siyuan-unplaced-manual-"));
+ fs.writeFileSync(path.join(temporary.profile, "fixture-only"), "synthetic");
+ } finally { temporary.cleanup(); }
+ assert.equal(fs.existsSync(temporary.profile), false);
+ temporary.cleanup();
+});
+
+test("actual preload exposes only fixed operations, binds session/revision and never forwards IPC events", () => {
+ const ipc = new EventEmitter(), sent = [];
+ ipc.send = (channel, value) => sent.push({channel, value});
+ let bridge;
+ vm.runInNewContext(fs.readFileSync(path.join(fixtureDirectory, "preload.cjs"), "utf8"), {
+ require: name => { assert.equal(name, "electron"); return {ipcRenderer: ipc,
+ contextBridge: {exposeInMainWorld(name, value) { assert.equal(name, "unplacedMenu"); bridge = value; }}}; },
+ process: {argv: ["--unplaced-session=" + "a".repeat(48)]},
+ });
+ assert.deepEqual(Object.keys(bridge).sort(), ["close", "editing", "more", "search", "select", "subscribe"]);
+ const updates = [];
+ bridge.subscribe((...args) => updates.push(args));
+ assert.equal(sent[0].value.type, "ready");
+ const privateEvent = {sender: "must-not-pass"};
+ ipc.emit(CHANNEL + "-state", privateEvent, {sessionID: "b".repeat(48), state: state()});
+ assert.equal(updates.length, 0);
+ ipc.emit(CHANNEL + "-state", privateEvent, {sessionID: "a".repeat(48), state: state({revision: 3})});
+ assert.equal(updates[0].length, 1);
+ assert.equal(updates[0][0].revision, 3);
+ bridge.select("row-1");
+ assert.equal(sent.at(-1).value.revision, 3);
+ assert.equal(sent.at(-1).value.sessionID, "a".repeat(48));
+ const count = sent.length;
+ bridge.close("url"); bridge.search("x".repeat(257));
+ assert.equal(sent.length, count);
+});
+
+test("actual menu script uses text nodes, preserves pending edits against late states and suppresses composing search (simulated DOM)", () => {
+ const {DOMFixture} = require("../src/protyle/render/av/map/testDOM.ts");
+ const document = new DOMFixture();
+ document.body.innerHTML = fs.readFileSync(path.join(fixtureDirectory, "menu.html"), "utf8");
+ document.getElementById = id => document.body.querySelector('[id="' + id + '"]');
+ document.addEventListener = (...args) => document.documentElement.addEventListener(...args);
+ const rows = document.getElementById("rows");
+ rows.replaceChildren = () => { Array.from(rows.children).forEach(child => child.remove()); };
+ const actions = [], timers = new Map();
+ let update, nextTimer = 0;
+ const bridge = {subscribe(fn) { update = fn; }};
+ for (const name of ["search", "editing", "more", "select", "close"]) bridge[name] = value => actions.push([name, value]);
+ const window = {unplacedMenu: bridge, addEventListener() {}};
+ vm.runInNewContext(fs.readFileSync(path.join(fixtureDirectory, "menu.js"), "utf8"), {window, document,
+ setTimeout(fn) { timers.set(++nextTimer, fn); return nextTimer; }, clearTimeout(id) { timers.delete(id); }});
+ const flush = () => { const callbacks = [...timers.values()]; timers.clear(); callbacks.forEach(fn => fn()); };
+ const fire = (element, type, event = {}) => (element.events.get(type) || []).forEach(fn => fn({preventDefault() {}, ...event}));
+ update(state());
+ assert.equal(rows.children.length, 1);
+ assert.equal(rows.querySelectorAll("img").length, 0);
+ assert.equal(rows.children[0].textContent, "Private <img src=x>");
+ const input = document.getElementById("search");
+ input.value = "new"; fire(input, "input");
+ assert.equal(actions.at(-1)[0], "editing");
+ update(state({revision: 2}));
+ assert.equal(rows.children[0].disabled, true);
+ flush();
+ assert.deepEqual(actions.at(-1), ["search", "new"]);
+ update(state({revision: 3, query: "old"}));
+ assert.equal(rows.children[0].disabled, true);
+ update(state({revision: 4, query: "new"}));
+ assert.equal(rows.children[0].disabled, false);
+ fire(input, "compositionstart"); input.value = "中文"; fire(input, "input", {isComposing: true}); flush();
+ assert.equal(actions.at(-1)[0], "editing");
+ update(state({revision: 5, query: "new"}));
+ assert.equal(rows.children[0].disabled, true);
+ fire(input, "compositionend"); flush();
+ assert.deepEqual(actions.at(-1), ["search", "中文"]);
+ update(state({revision: 6, query: "中文", theme: {mode: "dark", fontSize: 24}}));
+ assert.equal(document.documentElement.dataset.theme, "dark");
+ assert.equal(document.documentElement.dataset.fontSize, "24");
+ fire(document.documentElement, "keydown", {key: "Escape"});
+ assert.deepEqual(actions.at(-1), ["close", "escape"]);
+});
+
+test("actual owner script keeps toggle/outside separate and cancels stale same-query work (simulated DOM)", async () => {
+ const {DOMFixture} = require("../src/protyle/render/av/map/testDOM.ts");
+ const document = new DOMFixture();
+ document.body.innerHTML = fs.readFileSync(path.join(fixtureDirectory, "owner.html"), "utf8");
+ document.getElementById = id => document.body.querySelector('[id="' + id + '"]');
+ document.addEventListener = (...args) => document.documentElement.addEventListener(...args);
+ const toggle = document.getElementById("open");
+ toggle.getBoundingClientRect = () => ({x: 100, y: 50, left: 100, top: 50, right: 260, bottom: 80, width: 160, height: 30});
+ const viewport = {left: 0, top: 20, right: 600, bottom: 420};
+ document.getElementById("scroll").getBoundingClientRect = () => viewport;
+ const sessionID = "a".repeat(48), updates = [], closes = [], anchors = [], timers = new Map(), listeners = new Map();
+ let reply, opens = 0, nextTimer = 0;
+ const bridge = {
+ async open(value) { opens++; assert.ok(parseState(value.state)); return sessionID; },
+ update(value) { assert.ok(parseState(value.state)); updates.push(value); },
+ close(value) { closes.push(value); },
+ subscribe(fn) { reply = fn; }, anchor(value) { anchors.push(value); }, zoom() {}, permission() {},
+ };
+ vm.runInNewContext(fs.readFileSync(path.join(fixtureDirectory, "owner.js"), "utf8"), {
+ window: {fixtureOwner: bridge, innerWidth: 800, innerHeight: 600,
+ addEventListener(name, fn) { listeners.set(name, fn); }}, document,
+ setTimeout(fn) { timers.set(++nextTimer, fn); return nextTimer; }, clearTimeout(id) { timers.delete(id); },
+ });
+ const click = () => toggle.events.get("click")[0]();
+ const pointer = target => document.documentElement.events.get("pointerdown")[0]({target});
+ await click();
+ assert.equal(opens, 1);
+ pointer(toggle);
+ assert.equal(closes.length, 0);
+ await click();
+ assert.equal(opens, 1);
+ assert.equal(closes.at(-1).reason, "button");
+ reply({type: "closed", sessionID, reason: "button", restore: true});
+ await click();
+ assert.equal(opens, 2);
+ viewport.top = 60;
+ listeners.get("scroll")();
+ assert.deepEqual(JSON.parse(JSON.stringify(anchors.at(-1).anchor)), {x: 100, y: 60, width: 160, height: 20});
+ viewport.top = 90;
+ listeners.get("scroll")();
+ assert.equal(closes.at(-1).reason, "anchor-hidden");
+ viewport.top = 20;
+ pointer(document.body);
+ assert.equal(closes.at(-1).reason, "outside");
+ const query = "合成记录 1";
+ reply({type: "search", sessionID, requestID: 1, query});
+ const lateA = [...timers.values()][0];
+ reply({type: "editing", sessionID, requestID: 2});
+ reply({type: "search", sessionID, requestID: 3, query: "合成记录 2"});
+ reply({type: "editing", sessionID, requestID: 4});
+ reply({type: "search", sessionID, requestID: 5, query});
+ const count = updates.length;
+ lateA();
+ assert.equal(updates.length, count);
+ [...timers.values()][0]();
+ assert.equal(updates.at(-1).state.requestID, 5);
+ assert.equal(updates.at(-1).state.loading, false);
+ assert.equal(updates.at(-1).state.total, 34);
+ reply({type: "closed", sessionID, reason: "outside", restore: false});
+ assert.equal(timers.size, 0);
+});
diff --git a/app/tests/mapUnplacedOverlayBoundary.test.js b/app/tests/mapUnplacedOverlayBoundary.test.js
new file mode 100644
index 0000000000..30aa184d0e
--- /dev/null
+++ b/app/tests/mapUnplacedOverlayBoundary.test.js
@@ -0,0 +1,112 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+// 使用真实 Electron owner、IPC、sandbox preload 和 DOM;底图及记录仍为合成测试资源。
+const run = async profile => {
+ const {createHarness} = require("./fixtures/map-unplaced-overlay/harness.cjs");
+ const f = await createHarness({profile, automate: true});
+ const owner = source => f.owner.executeJavaScript(source);
+ const waitFor = async (check, label) => {
+ const deadline = Date.now() + 5000;
+ while (!await check()) {
+ assert.ok(Date.now() < deadline, label);
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ };
+ const open = async () => {
+ await owner('document.getElementById("open").click()');
+ await waitFor(() => f.manager.inspect()?.ready, "overlay becomes ready");
+ const view = f.manager.inspect().view;
+ await waitFor(() => view.getVisible(), "overlay becomes visible");
+ return {view, contents: view.webContents, evaluate: source => view.webContents.executeJavaScript(source)};
+ };
+ try {
+ f.win.focus();
+ let overlay = await open();
+ assert.equal(f.win.contentView.children.at(-1), overlay.view);
+ assert.equal(await overlay.evaluate('document.getElementById("rows").children.length'), 50);
+ assert.equal(await overlay.evaluate('document.querySelectorAll("img").length'), 0);
+ assert.equal(await overlay.evaluate('document.getElementById("rows").textContent.includes("<img src=x")'), true);
+ assert.equal(await overlay.evaluate("typeof require"), "undefined");
+ assert.equal(await f.map.webContents.executeJavaScript('document.body.textContent.includes("PRIVATE_FIXTURE")'), false);
+ const security = overlay.contents.getLastWebPreferences();
+ assert.equal(security.sandbox, true);
+ assert.equal(security.contextIsolation, true);
+ assert.equal(security.nodeIntegration, false);
+ assert.equal(security.webSecurity, true);
+ assert.equal(await overlay.evaluate('fetch("http://127.0.0.1:6806/api/sql").then(() => false, () => true)'), true);
+ assert.equal(await overlay.evaluate('fetch("https://tiles.openfreemap.org/private").then(() => false, () => true)'), true);
+ await overlay.evaluate('document.getElementById("more").click()');
+ await waitFor(() => overlay.evaluate('document.getElementById("rows").children.length === 100'), "pagination appends rows");
+ await overlay.evaluate('const input = document.getElementById("search"); input.value = "合成记录 1"; input.dispatchEvent(new Event("input", {bubbles: true}));');
+ await waitFor(() => overlay.evaluate('document.getElementById("count").textContent === "34"'), "search result replaces rows");
+ await owner('document.getElementById("theme").click()');
+ await waitFor(() => overlay.evaluate('document.documentElement.dataset.theme === "dark"'), "theme reaches trusted view");
+ assert.equal(await overlay.evaluate('getComputedStyle(document.querySelector(".fixture-menu")).fontSize'), "24px");
+ assert.equal(await overlay.evaluate('getComputedStyle(document.querySelector(".fixture-menu")).backgroundColor'), "rgb(41, 41, 41)");
+ const before = overlay.view.getBounds();
+ await owner('document.getElementById("scroll").scrollTop = 30');
+ await waitFor(() => overlay.view.getBounds().y !== before.y, "anchor follows owner scroll");
+ await owner('document.getElementById("zoom").click()');
+ await waitFor(() => overlay.contents.getZoomFactor() === f.owner.getZoomFactor(), "overlay follows actual owner zoom");
+ assert.equal(overlay.view.getVisible(), true);
+ assert.deepEqual(f.mapVisible, [true]);
+ overlay.contents.sendInputEvent({type: "keyDown", keyCode: "Escape"});
+ await waitFor(() => !f.manager.inspect(), "escape destroys overlay");
+ await waitFor(() => owner('document.activeElement.id === "open"'), "escape restores owner focus");
+ assert.equal(overlay.contents.isDestroyed(), true);
+ overlay = await open();
+ await owner('document.getElementById("open").click()');
+ await waitFor(() => !f.manager.inspect(), "toggle closes once without reopening");
+ overlay = await open();
+ await owner('document.body.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}))');
+ await waitFor(() => !f.manager.inspect(), "owner DOM outside closes overlay");
+ assert.equal(f.events.at(-1).restore, false);
+ overlay = await open();
+ f.map.webContents.sendInputEvent({type: "mouseDown", x: 20, y: 20, button: "left", clickCount: 1});
+ f.map.webContents.sendInputEvent({type: "mouseUp", x: 20, y: 20, button: "left", clickCount: 1});
+ await waitFor(() => !f.manager.inspect(), "native map outside closes overlay");
+ assert.equal(f.events.at(-1).restore, false);
+ overlay = await open();
+ await owner('document.getElementById("scroll").scrollTop = 180');
+ await waitFor(() => !f.manager.inspect(), "fully clipped anchor destroys overlay");
+ assert.equal(f.events.at(-1).reason, "anchor-hidden");
+ assert.equal(f.events.at(-1).restore, false);
+ await owner('document.getElementById("scroll").scrollTop = 0');
+ overlay = await open();
+ await owner('document.getElementById("permission").click()');
+ await waitFor(() => !f.manager.inspect(), "permission revoke destroys overlay");
+ assert.equal(overlay.contents.isDestroyed(), true);
+ await owner('document.getElementById("permission").click()');
+ overlay = await open();
+ await f.owner.loadURL("about:blank");
+ await waitFor(() => !f.manager.inspect(), "programmatic owner navigation destroys overlay");
+ assert.equal(overlay.contents.isDestroyed(), true);
+ assert.deepEqual(f.mapVisible, [true]);
+ } finally { f.destroy(); }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ const {app} = require("electron");
+ run(process.argv[2]).then(() => app.exit(0), error => { console.error(error); app.exit(1); });
+} else {
+ const {test} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ test("real Electron trusted unplaced overlay DOM, IPC, CSP, theme, focus and native outside clicks", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY
+ ? "Requires a real display; synthetic Node tests do not validate IME, OFM overlap or production flicker" : false,
+ }, async () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-unplaced-overlay-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 45000});
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}
diff --git a/kernel/api/av.go b/kernel/api/av.go
index 74ab428d45..4dd5949d35 100644
--- a/kernel/api/av.go
+++ b/kernel/api/av.go
@@ -509,38 +509,14 @@ var getAttributeViewCalendarUndated = contractHandler(apicontract.GetAttributeVi
search := strings.ToLower(strings.TrimSpace(request.Search))
rows := make([]*av.TableRow, 0, len(calendar.UndatedRows))
for _, row := range calendar.UndatedRows {
- if search != "" {
- matched := false
- for _, cell := range row.Cells {
- if cell == nil || cell.Value == nil || cell.Value.Type != av.KeyTypeBlock || cell.Value.Block == nil {
- continue
- }
- matched = strings.Contains(strings.ToLower(cell.Value.Block.Content), search)
- break
- }
- if !matched {
- continue
- }
+ if attributeViewRowMatchesTitle(row, search) {
+ rows = append(rows, row)
}
- rows = append(rows, row)
}
total := len(rows)
- page, pageSize := avPage(request.Page, 1), avPage(request.PageSize, 50)
- if page < 1 {
- page = 1
- }
- if pageSize < 1 {
- pageSize = 50
- } else if pageSize > 100 {
- pageSize = 100
- }
- if page > (total+pageSize-1)/pageSize {
- return apicontract.Success(apicontract.AVCalendarUndatedData{Rows: []*apicontract.AVTableRow{}, Total: total})
- }
- start := (page - 1) * pageSize
- end := min(total, start+pageSize)
+ rows = paginateAttributeViewRows(rows, avPage(request.Page, 1), avPage(request.PageSize, 50))
return apicontract.Success(apicontract.AVCalendarUndatedData{
- Rows: avContractSlice(rows[start:end], toContractAVTableRow), Total: total,
+ Rows: avContractSlice(rows, toContractAVTableRow), Total: total,
})
})
diff --git a/kernel/api/av_map.go b/kernel/api/av_map.go
index e727242850..4dbec459e1 100644
--- a/kernel/api/av_map.go
+++ b/kernel/api/av_map.go
@@ -24,22 +24,9 @@ var getAttributeViewMapUnplaced = contractHandler(apicontract.GetAttributeViewMa
}
rows := attributeViewMapUnplacedRows(mapped, request.Search)
total := len(rows)
- page, pageSize := avPage(request.Page, 1), avPage(request.PageSize, 50)
- if page < 1 {
- page = 1
- }
- if pageSize < 1 {
- pageSize = 50
- } else if pageSize > 100 {
- pageSize = 100
- }
- if page > (total+pageSize-1)/pageSize {
- return apicontract.Success(apicontract.AVMapUnplacedData{Rows: []*apicontract.AVTableRow{}, Total: total})
- }
- start := (page - 1) * pageSize
- end := min(total, start+pageSize)
+ rows = paginateAttributeViewRows(rows, avPage(request.Page, 1), avPage(request.PageSize, 50))
return apicontract.Success(apicontract.AVMapUnplacedData{
- Rows: avContractSlice(rows[start:end], toContractAVTableRow), Total: total,
+ Rows: avContractSlice(rows, toContractAVTableRow), Total: total,
})
})
@@ -69,20 +56,9 @@ func attributeViewMapUnplacedRows(mapped *av.Map, search string) (rows []*av.Tab
if location != nil && (location.Normalize() != nil || location.Latitude != nil || location.Longitude != nil) {
continue
}
- if search != "" {
- matched := false
- for _, cell := range row.Cells {
- if cell == nil || cell.Value == nil || cell.Value.Type != av.KeyTypeBlock || cell.Value.Block == nil {
- continue
- }
- matched = strings.Contains(strings.ToLower(cell.Value.Block.Content), search)
- break
- }
- if !matched {
- continue
- }
+ if attributeViewRowMatchesTitle(row, search) {
+ rows = append(rows, row)
}
- rows = append(rows, row)
}
return
}
diff --git a/kernel/api/av_rows.go b/kernel/api/av_rows.go
new file mode 100644
index 0000000000..36ce996007
--- /dev/null
+++ b/kernel/api/av_rows.go
@@ -0,0 +1,39 @@
+package api
+
+import (
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+// attributeViewRowMatchesTitle 匹配主键标题,search 由调用方统一去除首尾空白并转为小写。
+func attributeViewRowMatchesTitle(row *av.TableRow, search string) bool {
+ if search == "" {
+ return true
+ }
+ for _, cell := range row.Cells {
+ if cell == nil || cell.Value == nil || cell.Value.Type != av.KeyTypeBlock || cell.Value.Block == nil {
+ continue
+ }
+ return strings.Contains(strings.ToLower(cell.Value.Block.Content), search)
+ }
+ return false
+}
+
+// paginateAttributeViewRows 为已筛选和排序的条目分页,空页保持非 nil 切片。
+func paginateAttributeViewRows(rows []*av.TableRow, page, pageSize int) []*av.TableRow {
+ if page < 1 {
+ page = 1
+ }
+ if pageSize < 1 {
+ pageSize = 50
+ } else if pageSize > 100 {
+ pageSize = 100
+ }
+ if page > (len(rows)+pageSize-1)/pageSize {
+ return []*av.TableRow{}
+ }
+ start := (page - 1) * pageSize
+ end := min(len(rows), start+pageSize)
+ return rows[start:end]
+}
diff --git a/kernel/api/av_rows_test.go b/kernel/api/av_rows_test.go
new file mode 100644
index 0000000000..8389eb0903
--- /dev/null
+++ b/kernel/api/av_rows_test.go
@@ -0,0 +1,28 @@
+package api
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+func TestAttributeViewRowTitleSearch(t *testing.T) {
+ row := &av.TableRow{Cells: []*av.TableCell{
+ nil, {BaseValue: &av.BaseValue{}},
+ {BaseValue: &av.BaseValue{Value: &av.Value{Type: av.KeyTypeBlock}}},
+ {BaseValue: &av.BaseValue{Value: &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "Other field"}}}},
+ {BaseValue: &av.BaseValue{Value: &av.Value{Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: "PLAN Alpha"}}}},
+ {BaseValue: &av.BaseValue{Value: &av.Value{Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: "Other block"}}}},
+ }}
+ for _, test := range []struct {
+ search string
+ want bool
+ }{{"", true}, {"plan alpha", true}, {"alpha", true}, {"other", false}, {"missing", false}} {
+ if got := attributeViewRowMatchesTitle(row, test.search); got != test.want {
+ t.Fatalf("title search %q: got %t, want %t", test.search, got, test.want)
+ }
+ }
+ if attributeViewRowMatchesTitle(&av.TableRow{}, "plan") {
+ t.Fatal("row without a primary cell matched a title search")
+ }
+}
diff --git a/kernel/api/contract_av_calendar_test.go b/kernel/api/contract_av_calendar_test.go
index b56bfc9228..e01e2ebe47 100644
--- a/kernel/api/contract_av_calendar_test.go
+++ b/kernel/api/contract_av_calendar_test.go
@@ -323,7 +323,7 @@ func TestAVContractCalendarUndated(t *testing.T) {
request map[string]any
wantID string
}{
- {map[string]any{"id": database.ID, "viewID": view.ID, "search": "beta"}, ids[1]},
+ {map[string]any{"id": database.ID, "viewID": view.ID, "search": " BETA "}, ids[1]},
{map[string]any{"id": database.ID, "viewID": view.ID, "query": "Plan", "search": "alpha"}, ids[0]},
} {
response = callAttributeViewContextFilterAPI(t, path, test.request, getAttributeViewCalendarUndated)
@@ -333,6 +333,32 @@ func TestAVContractCalendarUndated(t *testing.T) {
t.Fatalf("undated search returned the wrong rows: %s", response.Body.String())
}
}
+ for _, test := range []struct {
+ name string
+ options map[string]any
+ start int
+ count int
+ }{
+ {"null defaults", map[string]any{"page": nil, "pageSize": nil}, 0, 3},
+ {"fractional", map[string]any{"page": 2.9, "pageSize": 1.9}, 1, 1},
+ {"invalid bounds", map[string]any{"page": -1, "pageSize": 0}, 0, 3},
+ {"beyond", map[string]any{"page": 4, "pageSize": 1}, 0, 0},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ test.options["id"], test.options["viewID"] = database.ID, view.ID
+ response = callAttributeViewContextFilterAPI(t, path, test.options, getAttributeViewCalendarUndated)
+ requireAPIContract(t, http.MethodPost, path, response)
+ decodeAttributeViewContextFilterAPIResponse(t, response, &result)
+ if result.Code != 0 || result.Data.Total != 3 || result.Data.Rows == nil || len(result.Data.Rows) != test.count {
+ t.Fatalf("unexpected undated page: %s", response.Body.String())
+ }
+ for index, row := range result.Data.Rows {
+ if row.ID != ids[test.start+index] {
+ t.Fatalf("undated page skipped or repeated rows: %s", response.Body.String())
+ }
+ }
+ })
+ }
response = callAttributeViewContextFilterAPI(t, path, map[string]any{
"id": database.ID, "blockID": fixture.databaseID, "viewID": view.ID,
}, getAttributeViewCalendarUndated)
diff --git a/kernel/api/contract_av_map_unplaced_test.go b/kernel/api/contract_av_map_unplaced_test.go
index 123fd5bc95..437768e952 100644
--- a/kernel/api/contract_av_map_unplaced_test.go
+++ b/kernel/api/contract_av_map_unplaced_test.go
@@ -103,15 +103,17 @@ func TestAVContractMapUnplacedPagination(t *testing.T) {
{"second", map[string]any{"page": 2}, 50, 50},
{"last", map[string]any{"page": 3}, 100, 5},
{"beyond", map[string]any{"page": 4}, 0, 0},
+ {"large page", map[string]any{"page": 1e9}, 0, 0},
{"count", map[string]any{"pageSize": 1}, 0, 1},
{"invalid bounds", map[string]any{"page": -1, "pageSize": 0}, 0, 50},
{"maximum", map[string]any{"pageSize": 1000}, 0, 100},
{"fractional", map[string]any{"page": 2.9, "pageSize": 1.9}, 1, 1},
+ {"fractional bounds", map[string]any{"page": -0.9, "pageSize": 0.9}, 0, 50},
{"null", map[string]any{"page": nil, "pageSize": nil}, 0, 50},
} {
t.Run(test.name, func(t *testing.T) {
rows, total := callMapUnplacedContractTest(t, database, test.options)
- if total != len(ids) || len(rows) != test.count {
+ if total != len(ids) || rows == nil || len(rows) != test.count {
t.Fatalf("unexpected page: total %d, rows %d", total, len(rows))
}
for index, row := range rows {
diff --git a/kernel/apicontract/av_types.go b/kernel/apicontract/av_types.go
index f91a884582..7190803339 100644
--- a/kernel/apicontract/av_types.go
+++ b/kernel/apicontract/av_types.go
@@ -150,7 +150,7 @@ type AVValuePhone struct {
// AVValueLocation 保存单个位置的 WGS84 坐标,不执行坐标系转换。
// API 使用具名成员,不接受无标签的坐标数组。
-// 界面按经度、纬度显示,坐标对粘贴默认经度在前且可显式切换;规范文本复制与导出保留纬度、经度顺序。
+// 界面按经度、纬度显示并使用具名字段输入;规范文本复制与导出保留纬度、经度顺序。
// 纬度和经度必须同时为空或同时提供,范围分别为 [-90,90] 和 [-180,180],零是有效坐标。
// 更新时省略成员保留原值,显式 null 同时清空两个坐标;名称可以独立存在。
// 位置值拒绝坐标系及其他额外字段,字段不提供默认坐标系设置。
diff --git a/kernel/av/av.go b/kernel/av/av.go
index a75047b0c6..ce4f0c203b 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -956,7 +956,7 @@ func parseAttributeViewData(avID string, data []byte, normalizeRichText bool) (r
err = fmt.Errorf("unsupported database automation specification [%d]", ret.Automations.Spec)
}
if nil == err {
- err = ret.ValidateListLayouts()
+ err = ret.ValidateLayouts()
}
if nil == err && normalizeRichText {
err = ret.NormalizeRichText()
@@ -997,7 +997,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {
if err = av.NormalizeLocations(); nil != err {
return
}
- if err = av.ValidateListLayouts(); nil != err {
+ if err = av.ValidateLayouts(); nil != err {
return
}
if err = av.NormalizeRichText(); nil != err {
diff --git a/kernel/av/layout.go b/kernel/av/layout.go
index 566900fb7a..5fa1fa9720 100644
--- a/kernel/av/layout.go
+++ b/kernel/av/layout.go
@@ -16,6 +16,17 @@
package av
+// ValidateLayouts 统一校验地图、日历和列表布局,拒绝损坏数据并保留原始文件。
+func (attrView *AttributeView) ValidateLayouts() error {
+ if err := attrView.ValidateMapLayouts(); err != nil {
+ return err
+ }
+ if err := attrView.ValidateCalendarLayouts(); err != nil {
+ return err
+ }
+ return attrView.ValidateListLayouts()
+}
+
// BaseLayout 描述了布局的基础结构。
type BaseLayout struct {
Spec int `json:"spec"` // 布局格式版本
diff --git a/kernel/av/layout_list.go b/kernel/av/layout_list.go
index 65cd518600..278f942c30 100644
--- a/kernel/av/layout_list.go
+++ b/kernel/av/layout_list.go
@@ -62,12 +62,6 @@ func TableFromViewable(viewable Viewable) *Table {
// ValidateListLayouts 校验列表布局的结构,拒绝损坏数据并保留原始文件。
func (attrView *AttributeView) ValidateListLayouts() error {
- if err := attrView.ValidateMapLayouts(); nil != err {
- return err
- }
- if err := attrView.ValidateCalendarLayouts(); nil != err {
- return err
- }
var validate func(*View) error
validate = func(view *View) error {
if nil == view {
diff --git a/kernel/av/layout_test.go b/kernel/av/layout_test.go
new file mode 100644
index 0000000000..fc2281eae2
--- /dev/null
+++ b/kernel/av/layout_test.go
@@ -0,0 +1,34 @@
+package av
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestValidateLayoutsPreservesOrderAndNestedValidation(t *testing.T) {
+ for _, nested := range []bool{false, true} {
+ list := &View{ID: "list", LayoutType: LayoutTypeList}
+ calendar := &View{ID: "calendar", LayoutType: LayoutTypeCalendar}
+ mapped := &View{ID: "map", LayoutType: LayoutTypeMap}
+ database := &AttributeView{Views: []*View{nil, list, calendar, mapped}}
+ if nested {
+ database.Views = []*View{{Groups: database.Views}}
+ }
+ for _, layout := range []string{"map", "calendar", "list"} {
+ if err := database.ValidateLayouts(); err == nil || !strings.HasPrefix(err.Error(), layout+" layout missing") {
+ t.Fatalf("nested=%t expected %s validation first, got %v", nested, layout, err)
+ }
+ switch layout {
+ case "map":
+ mapped.Map = &LayoutMap{LayoutTable: NewLayoutTable()}
+ case "calendar":
+ calendar.Calendar = &LayoutCalendar{LayoutTable: NewLayoutTable()}
+ case "list":
+ list.List = NewLayoutList()
+ }
+ }
+ if err := database.ValidateLayouts(); err != nil {
+ t.Fatalf("valid layouts rejected: %v", err)
+ }
+ }
+}
diff --git a/kernel/model/attribute_view_location_import_empty_test.go b/kernel/model/attribute_view_location_import_empty_test.go
deleted file mode 100644
index 56edbe1653..0000000000
--- a/kernel/model/attribute_view_location_import_empty_test.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package model
-
-import (
- "bytes"
- "encoding/json"
- "github.com/88250/lute/ast"
- "github.com/siyuan-note/siyuan/kernel/av"
- "github.com/siyuan-note/siyuan/kernel/util"
- "testing"
-)
-
-func TestAttributeViewLocationImportOmittedValues(t *testing.T) {
- setupAttributeViewValidationTest(t)
- setAttributeViewListTestLangs()
- util.AttrViewLangs["en"]["calendar"] = "Calendar"
- for _, scenario := range []struct {
- name string
- layout av.LayoutType
- loc bool
- }{
- {"location", av.LayoutTypeTable, true},
- {"legacy table", av.LayoutTypeTable, false},
- {"legacy calendar", av.LayoutTypeCalendar, false},
- } {
- t.Run(scenario.name, func(t *testing.T) {
- database := newAttributeViewWithLayout(ast.NewNodeID(), scenario.layout)
- if scenario.loc {
- database.KeyValues = append(database.KeyValues, &av.KeyValues{Key: av.NewKey(ast.NewNodeID(), "Location", "", av.KeyTypeLocation)})
- }
- if err := av.SaveAttributeView(database); err != nil {
- t.Fatal(err)
- }
- data, err := json.Marshal(database)
- if err != nil {
- t.Fatal(err)
- }
- var root map[string]json.RawMessage
- if err = json.Unmarshal(data, &root); err != nil {
- t.Fatal(err)
- }
- var keyValues []map[string]json.RawMessage
- if err = json.Unmarshal(root["keyValues"], &keyValues); err != nil {
- t.Fatal(err)
- }
- for _, values := range []string{"", "null", "[]", "{}", `"invalid"`} {
- delete(keyValues[0], "values")
- if values != "" {
- keyValues[0]["values"] = json.RawMessage(values)
- }
- root["keyValues"], err = json.Marshal(keyValues)
- if err != nil {
- t.Fatal(err)
- }
- input, err := json.Marshal(root)
- if err != nil {
- t.Fatal(err)
- }
- for _, encrypted := range []bool{false, true} {
- got, importErr := isolateImportedAttributeViewBindings(input, nil, encrypted)
- wantSuccess := values == "null" || values == "[]" || values == ""
- if wantSuccess && (importErr != nil || !bytes.Equal(got, input)) {
- t.Fatalf("values=%q encrypted=%t rejected or rewrote valid empty data: %v", values, encrypted, importErr)
- }
- if !wantSuccess && importErr == nil {
- t.Fatalf("values=%q encrypted=%t accepted malformed data", values, encrypted)
- }
- }
- }
- })
- }
-}
diff --git a/kernel/model/attribute_view_map_test.go b/kernel/model/attribute_view_map_test.go
index 5abfe69c91..e66cdbc30f 100644
--- a/kernel/model/attribute_view_map_test.go
+++ b/kernel/model/attribute_view_map_test.go
@@ -306,14 +306,20 @@ func TestAttributeViewMapAndLocationImportOmittedValues(t *testing.T) {
t.Fatal(err)
}
for _, encrypted := range []bool{false, true} {
- got, importErr := isolateImportedAttributeViewBindings(input, nil, encrypted)
- wantSuccess := values == "null" || values == "[]" || values == ""
- if wantSuccess && (importErr != nil || !bytes.Equal(got, input)) {
- t.Fatalf("values=%q encrypted=%t rejected or rewrote valid empty data: %v", values, encrypted, importErr)
- }
- if !wantSuccess && importErr == nil {
- t.Fatalf("values=%q encrypted=%t accepted malformed data", values, encrypted)
- }
+ t.Run(fmt.Sprintf("values=%q/encrypted=%t", values, encrypted), func(t *testing.T) {
+ before := bytes.Clone(input)
+ got, importErr := isolateImportedAttributeViewBindings(input, nil, encrypted)
+ if !bytes.Equal(input, before) {
+ t.Fatal("import changed the source JSON")
+ }
+ wantSuccess := values == "null" || values == "[]" || values == ""
+ if wantSuccess && (importErr != nil || !bytes.Equal(got, input)) {
+ t.Fatalf("rejected or rewrote valid empty data: %v", importErr)
+ }
+ if !wantSuccess && importErr == nil {
+ t.Fatal("accepted malformed data")
+ }
+ })
}
}
})
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index 0e034ca5f5..3b40b1be7c 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -519,7 +519,7 @@ const (
)
func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierViewID, query string, page, pageSize int, groupPaging map[string]any, ignoreRows, writable bool, target *AttributeViewRenderTarget, targetGroupID string, calendarRanges ...*av.CalendarRange) (viewable av.Viewable, err error) {
- if err = attrView.ValidateListLayouts(); nil != err {
+ if err = attrView.ValidateLayouts(); nil != err {
return
}
// 获取待渲染的视图
diff --git a/kernel/model/import_attribute_view.go b/kernel/model/import_attribute_view.go
index 78059b7fcd..79fe8ab33d 100644
--- a/kernel/model/import_attribute_view.go
+++ b/kernel/model/import_attribute_view.go
@@ -18,7 +18,7 @@ func isolateImportedAttributeViewBindings(data []byte, importedBlockIDs map[stri
if err := av.CheckSpec(&attrView); err != nil {
return nil, err
}
- if err := attrView.ValidateListLayouts(); err != nil {
+ if err := attrView.ValidateLayouts(); err != nil {
return nil, err
}
if err := attrView.NormalizeLocations(); err != nil {