Compare commits

...

198 Commits

Author SHA1 Message Date
Eric van der Vlist c1d070c504 npm-check-updates 2023-10-07 18:21:58 +02:00
Eric van der Vlist 2b19746bb2 Displaying a cycle icon when GPX locomotion tag is cycling 2023-08-07 18:56:28 +02:00
Eric van der Vlist f3ae5cfcf4 Saving edited tags in GpxDialog 2023-08-07 18:13:43 +02:00
Eric van der Vlist 70b431a1c5 npm updates 2023-08-07 17:59:56 +02:00
Eric van der Vlist 2d73315a9a Adding GPX tags extension 2023-08-06 18:06:54 +02:00
Eric van der Vlist a9e2855e3f npm updates 2023-08-05 18:08:14 +02:00
Eric van der Vlist 2793db6f1e Filtering out tracks, routes and waypoints 2023-08-05 18:05:41 +02:00
Eric van der Vlist b025c74d99 Displaying only the current GPX if required 2023-08-05 17:38:08 +02:00
Eric van der Vlist a297c1ec29 typo 2023-08-04 18:50:47 +02:00
Eric van der Vlist 877b0f892d Implementing a selection mechanism to define what should be drawn: GPX all/none 2023-08-03 22:09:25 +02:00
Eric van der Vlist 68d1f8140a Starting to implement a selection mechanism to define what should be drawn 2023-08-03 18:46:08 +02:00
Eric van der Vlist b9c2cf3448 regression 2023-08-03 16:16:24 +02:00
Eric van der Vlist 15e52d39d9 npm updates 2023-08-03 15:04:56 +02:00
Eric van der Vlist 132455c33a npm updates 2023-07-12 15:21:51 +02:00
Eric van der Vlist 3638103034 npm updates 2023-07-08 10:54:18 +02:00
Eric van der Vlist 435149d718 Activities and categories, WIP 2023-07-08 10:52:02 +02:00
Eric van der Vlist 03666ff605 Cosmetics (typescript) 2023-06-13 11:13:08 +02:00
Eric van der Vlist 1d9d38c437 Cosmetics (typescript) 2023-06-13 11:04:45 +02:00
Eric van der Vlist 7caf088a7e Cosmetics (typescript) 2023-06-13 11:03:02 +02:00
Eric van der Vlist 787323bcac Cosmetics 2023-06-13 10:52:52 +02:00
Eric van der Vlist 0ae8b68255 Adding a level in tag definitions to support routes (in addition to POIs) 2023-06-12 18:26:53 +02:00
Eric van der Vlist db85c8ff69 File rename 2023-06-12 16:35:50 +02:00
Eric van der Vlist 3fba5b0529 Implementing the OSM tag format definitions library 2023-06-12 16:29:17 +02:00
Eric van der Vlist 3f56cf9c23 Starting to implement a proper library for OSM tags 2023-06-12 15:51:05 +02:00
Eric van der Vlist a4e975dbeb npm updates 2023-06-12 11:57:25 +02:00
Eric van der Vlist 28271da640 Moving stuff around so that helper.ts works again 2023-06-09 18:15:02 +02:00
Eric van der Vlist ba09d5ef50 Cleanup (unused imports) 2023-06-09 17:03:35 +02:00
Eric van der Vlist 861717ee18 Cleanup 2023-06-09 16:59:53 +02:00
Eric van der Vlist 64b01bd7a5 Regression fix 2023-06-09 15:56:12 +02:00
Eric van der Vlist c2705def86 Refactoring osm tags (wip) 2023-06-09 15:49:50 +02:00
Eric van der Vlist 29f92dca10 Refactoring osm tags (wip) 2023-06-09 15:23:08 +02:00
Eric van der Vlist 92fb5f7bac Redesigning overlay definitions 2023-06-09 12:21:11 +02:00
Eric van der Vlist fc09fdf358 npm updates 2023-06-09 11:05:07 +02:00
Eric van der Vlist 6943424d34 Cleanup (removing getAllPoiTypes which was used only once) 2023-06-07 10:23:02 +02:00
Eric van der Vlist 7cb02012c0 Preparing a refactoring for overlay definitions 2023-06-06 16:03:14 +02:00
Eric van der Vlist 00fdc5577c Minor update in overlay-definitions 2023-06-06 15:15:10 +02:00
Eric van der Vlist 2bd23ac785 One timer helper to change the structure ofoverlay definitions 2023-06-05 11:17:01 +02:00
Eric van der Vlist ce6a112d77 npm updates 2023-06-02 15:34:48 +02:00
Eric van der Vlist f8ef752d09 npm updates 2023-05-31 17:12:31 +02:00
Eric van der Vlist 4b4901743b Adding new icons 2023-05-26 18:32:57 +02:00
Eric van der Vlist 988e3df1ee Require POST_NOTIFICATIONS permission (Android 13) 2023-05-26 18:04:08 +02:00
Eric van der Vlist ed5fbd7e13 npm updates 2023-05-26 17:20:45 +02:00
Eric van der Vlist 716013d605 Adding overlay definitions 2023-05-16 21:46:00 +02:00
Eric van der Vlist 2295991f23 Bug fix to support more overlay definitions 2023-05-16 19:29:00 +02:00
Eric van der Vlist c8367450d6 npm updates 2023-05-16 18:34:41 +02:00
Eric van der Vlist 713080a73b npm updates 2023-05-13 11:38:06 +02:00
Eric van der Vlist bce59f9781 npm updates 2023-05-12 18:18:20 +02:00
Eric van der Vlist cde6012227 npm updates 2023-05-09 10:10:55 +02:00
Eric van der Vlist 790a692529 Averaging heights 2023-05-09 09:59:10 +02:00
Eric van der Vlist 99daeefa98 Display delta heigth stats for trkseg 2023-05-09 09:40:42 +02:00
Eric van der Vlist 73172812f5 npm updates 2023-05-03 18:40:43 +02:00
Eric van der Vlist 4397dfc9f8 npm update 2023-04-24 16:30:11 +02:00
Eric van der Vlist dd32763895 npm install blob-util 2023-04-24 16:27:55 +02:00
Eric van der Vlist 9beb1eb1a3 Displaying thumbnails on the map 2023-04-24 15:26:03 +02:00
Eric van der Vlist e08d6993c1 Displaying WPT thumbnails 2023-04-24 15:03:34 +02:00
Eric van der Vlist 014e58a31b Calling WptEditDialog to import pictures as wpts 2023-04-23 18:06:10 +02:00
Eric van der Vlist a84b813066 npm update 2023-04-23 16:59:53 +02:00
Eric van der Vlist 65abffb5d9 Adding more properties to picture imports 2023-04-22 21:17:43 +02:00
Eric van der Vlist 06b2c60a4a Resize refactoring to create downsized image and thumbnails in one run 2023-04-22 18:04:20 +02:00
Eric van der Vlist 3ca64ad7eb Avoiding raising errors when there is no elevation in exif data 2023-04-21 21:28:09 +02:00
Eric van der Vlist e634d13ee5 Imageresizing using a canvas 2023-04-21 21:23:32 +02:00
Eric van der Vlist a91230f614 Attempt to scale using a canvas element 2023-04-21 18:53:38 +02:00
Eric van der Vlist 4df529abb7 Extracting GPS coordinates from exif 2023-04-20 17:50:30 +02:00
Eric van der Vlist d44f9a257e Using piexifjs to support exif (it(s yhe only one that can write exif data) and nothing to reisze images (WIP) 2023-04-20 15:18:32 +02:00
Eric van der Vlist 99410d7ebd npm updates 2023-04-20 10:52:55 +02:00
Eric van der Vlist ee980f219b Using image-js to generate images thumbnails (doesn't work well because of the lack of advanced interpolation methods in the current version) 2023-04-18 17:45:48 +02:00
Eric van der Vlist 15984a0d5d Adding a dragenter handler 2023-04-18 17:44:35 +02:00
Eric van der Vlist 35a03dcfc9 npm i image-js 2023-04-18 10:41:58 +02:00
Eric van der Vlist d3c0cfd393 Refactoring intent receivers for gmap links 2023-04-17 15:09:08 +02:00
Eric van der Vlist f9517b07b4 Refactoring intent receivers for web links 2023-04-17 15:02:46 +02:00
Eric van der Vlist c3c93139ed Refactoring intent receivers for geo: locations 2023-04-17 14:57:08 +02:00
Eric van der Vlist d5a8118c2a Refactoring intent receivers for invitations 2023-04-17 14:45:04 +02:00
Eric van der Vlist f82181347c Begining to refactor intent receivers to support GPX imports from more sources 2023-04-17 10:41:30 +02:00
Eric van der Vlist 8242680137 Accepting mimeType file/* (sic) to support wikiloc exports 2023-04-17 09:30:02 +02:00
Eric van der Vlist f17cc2e073 Adding a button to force importing tracks as routes 2023-04-15 20:24:35 +02:00
Eric van der Vlist 856cd7637e Making sure gpx id is 'new' when importing a GPX as a new journey 2023-04-15 18:25:27 +02:00
Eric van der Vlist b38fdf49ad Check db url before attempting to get a user id. 2023-04-15 17:29:50 +02:00
Eric van der Vlist 09e82600aa Do not restrict import file types on Android since it just doesn't work :( ... 2023-04-15 17:29:09 +02:00
Eric van der Vlist 5640cf8755 Bug regression caused by suid updates 2023-04-15 12:18:46 +02:00
Eric van der Vlist 91ef0239c9 npm updates 2023-04-15 11:55:52 +02:00
Eric van der Vlist 59f266de37 Displaying thumbnails 2023-04-04 19:33:22 +02:00
Eric van der Vlist 5333e8053b Extracting interesting stuff from exif 2023-04-04 19:17:44 +02:00
Eric van der Vlist f52191966c Reading exif tags 2023-04-04 15:25:53 +02:00
Eric van der Vlist 854a9d701a Fixing css issue with updater's alert 2023-04-04 15:03:44 +02:00
Eric van der Vlist f5e9657842 Refactoring to prepare jpg imports 2023-04-03 14:46:41 +02:00
Eric van der Vlist 9863efc26a Refactoring to prepare jpg imports 2023-04-03 14:39:55 +02:00
Eric van der Vlist 20bb1387fc Intent to receive Google maps share actions 2023-04-02 20:23:18 +02:00
Eric van der Vlist 60ca62bf09 Support for searching pluscodes (extended when required relative to the map center) 2023-04-02 16:06:38 +02:00
Eric van der Vlist b547e203a6 Pluscode npm package plus a utility function to test if a string may be a pluscode 2023-04-02 12:35:53 +02:00
Eric van der Vlist 519d671761 npm updates 2023-04-02 11:36:59 +02:00
Eric van der Vlist f6b5b97063 npm updates 2023-03-21 18:46:59 +01:00
Eric van der Vlist 41c81fca1b Adding file drop capability to import GPX files. 2023-03-17 19:57:22 +01:00
Eric van der Vlist 9b9bba1609 Trying to improve trkseg styles 2023-03-16 22:16:16 +01:00
Eric van der Vlist c9d231251f Looking how to import images 2023-03-16 21:41:51 +01:00
Eric van der Vlist 39876031e4 Setting a higher z-index for GPX layers 2023-03-16 21:41:29 +01:00
Eric van der Vlist e406590c59 Installing exifreader 2023-03-13 19:52:50 +01:00
Eric van der Vlist 7a2752e286 Declutter all wpt types (including notes) 2023-03-13 17:35:49 +01:00
Eric van der Vlist 9588ca7749 Regression that prevented initial configuration 2023-03-13 13:19:43 +01:00
Eric van der Vlist 95cfa8c8d7 Adding a click to copy feature in SystemInfo 2023-03-11 19:08:52 +01:00
Eric van der Vlist ef909b475b Adding a self test to check that web workers are supported 2023-03-11 18:35:14 +01:00
Eric van der Vlist ba14181bdd Adding a test for undefined addresses 2023-03-10 23:36:45 +01:00
Eric van der Vlist 229bc14f72 Adding a <SystemInfo> component to display basic system info 2023-03-10 23:27:03 +01:00
Eric van der Vlist 9e08a70002 Update check frequency 2023-03-10 22:26:24 +01:00
Eric van der Vlist 3aa96c7afc Moving the Account icon in a drawer 2023-03-10 20:01:40 +01:00
Eric van der Vlist 4ff760a0ff Making sure that notes default dates are the current date 2023-03-09 22:21:18 +01:00
Eric van der Vlist 06daffbd1c Add an update link for android 2023-03-09 21:51:52 +01:00
Eric van der Vlist 677ac02835 Checking if app needs update 2023-03-09 21:00:56 +01:00
Eric van der Vlist 7997138c5e Defining vite env vars with git info 2023-03-07 20:04:06 +01:00
Eric van der Vlist da76e30fc4 Use double click rather than single click to query the map 2023-03-07 19:01:25 +01:00
Eric van der Vlist bb763435ef Don't compact trksegs if you don't own them 2023-03-07 18:41:05 +01:00
Eric van der Vlist c1f1c8afb0 Displaying Wpts description and start date 2023-03-06 21:54:36 +01:00
Eric van der Vlist e620db5c7b Change origin format in put() 2023-03-06 21:38:50 +01:00
Eric van der Vlist df3039a04b Specific icon for notes 2023-03-06 21:16:19 +01:00
Eric van der Vlist adbbb3e356 First version of notes, also allowing to delete wpts 2023-03-06 16:45:20 +01:00
Eric van der Vlist bf179a4b6d Filtering out GPX positions when accuracy is less than 10 m 2023-03-06 14:36:15 +01:00
Eric van der Vlist 5404a6e5ad Implementing notes (WIP) 2023-03-06 09:24:39 +01:00
Eric van der Vlist 07cd0d04c5 Supporting invitations through geo URLs 2023-03-05 09:53:26 +01:00
Eric van der Vlist aba2ddd907 Handling deep links to web.dyomedea.add, thus supporting invitations in the app too 2023-03-04 20:52:11 +01:00
Eric van der Vlist c9be4dcc28 Typo 2023-03-04 20:09:59 +01:00
Eric van der Vlist c8644c8817 Replacing URLs by user ids in origins 2023-03-04 16:07:22 +01:00
Eric van der Vlist f07bf07c3f Replacing shared by to 2023-03-04 15:13:27 +01:00
Eric van der Vlist acb6156ed2 Replacing Shared by To... 2023-03-04 13:09:11 +01:00
Eric van der Vlist 2358c7d8fb Saving settings and reloading the page to select the invitation account 2023-03-04 12:27:27 +01:00
Eric van der Vlist 51eb54954f Adding a check for existing accounts 2023-03-04 12:10:09 +01:00
Eric van der Vlist a32faaa837 Saving the new account 2023-03-04 11:59:34 +01:00
Eric van der Vlist 87b6e1710d Cosmetics 2023-03-04 11:08:14 +01:00
Eric van der Vlist 24fb46c0fb Validation flow seems OK. 2023-03-04 10:54:32 +01:00
Eric van der Vlist 04cd163906 Moving on implementing invitations 2023-03-04 10:30:09 +01:00
Eric van der Vlist 5ad98a860e Moving invitation check in its own module 2023-03-04 09:23:28 +01:00
Eric van der Vlist bedcaa209a Checking if location's hash contains an invitation 2023-03-03 21:39:26 +01:00
Eric van der Vlist 5753245dad npm update 2023-03-03 21:38:49 +01:00
Eric van der Vlist 909949657e Adding a second vector source (and layer) per GPX to display uncluttered features. 2023-02-23 11:59:51 +01:00
Eric van der Vlist 99374520a5 npm-check-updates 2023-02-23 10:58:35 +01:00
Eric van der Vlist 0be074bbfb npm-check-updates 2023-02-21 20:36:08 +01:00
Eric van der Vlist ccd4e22934 vscode recommendations 2023-02-20 09:56:31 +01:00
Eric van der Vlist 543b7cd259 Remove decluttering which doesn't work nicely 2023-02-16 16:08:54 +01:00
Eric van der Vlist 3fd108177b Starting to implement a node component 2023-02-15 15:42:02 +01:00
Eric van der Vlist 951deb5fef Removing a condition that doesn't seem necessary before deleting docs.x 2023-02-15 15:37:45 +01:00
Eric van der Vlist 937fd885fa Sligthly bigger iconx 2023-02-15 12:34:54 +01:00
Eric van der Vlist ddf0590dcd Hiker icon for last GPX position.x 2023-02-15 12:25:12 +01:00
Eric van der Vlist 597cb8629a Displaying last position of each gpx 2023-02-15 12:02:56 +01:00
Eric van der Vlist 1406e88ad6 console.log's 2023-02-15 10:43:29 +01:00
Eric van der Vlist c4b2fa175d Bug fix (trkpts were deleted during compaction) 2023-02-14 20:55:20 +01:00
Eric van der Vlist 1d5d158f8c Bug fix when creating the first gpx. 2023-02-13 20:57:30 +01:00
Eric van der Vlist 51ab7c38e0 Store the current gpx id in account docs 2023-02-13 18:30:01 +01:00
Eric van der Vlist 8d32fa253a Bug fix 2023-02-13 15:59:41 +01:00
Eric van der Vlist 6dfe98b655 Refactoring the worker / db init flow. 2023-02-13 15:44:02 +01:00
Eric van der Vlist cfaf7ad72f Removing call to solid-worker. 2023-02-13 11:38:07 +01:00
Eric van der Vlist df42a684c3 Updating GPX import to use parent's shared. 2023-02-13 11:23:17 +01:00
Eric van der Vlist e445a7e1af db put should take parent's shared by default. 2023-02-13 10:56:48 +01:00
Eric van der Vlist 9ea29b368f 1000 ! 2023-02-13 10:14:34 +01:00
Eric van der Vlist 05532a2a5f ... 2023-02-13 10:12:59 +01:00
Eric van der Vlist 01554e3383 Breaking after 1000 purges. 2023-02-13 10:11:46 +01:00
Eric van der Vlist 19aaaba3f8 Breaking after 10000 purges to give a chance to delete _local/purges. 2023-02-13 10:02:28 +01:00
Eric van der Vlist e1d6fea35c Removing _local/purges 2023-02-13 09:59:41 +01:00
Eric van der Vlist cbd5eb1e04 Adding documents origin. 2023-02-12 21:23:30 +01:00
Eric van der Vlist 9dacad9af3 Adding a "shared" property to gpxes and family. 2023-02-12 18:14:14 +01:00
Eric van der Vlist 8853ea4670 Decreasing delay between purges. 2023-02-12 15:20:41 +01:00
Eric van der Vlist c992782ab7 Firefox issue. 2023-02-12 14:47:03 +01:00
Eric van der Vlist 8a63cc07f4 Bug fix (forEech and promises...) 2023-02-12 14:41:19 +01:00
Eric van der Vlist 4502162a36 Removing a few console.log... 2023-02-12 14:10:56 +01:00
Eric van der Vlist 5a5931dbcd Implementing a mechanism to purge deleted docs. 2023-02-12 12:19:00 +01:00
Eric van der Vlist 534ec32312 Signals are very handy in web workers ! 2023-02-12 11:12:53 +01:00
Eric van der Vlist 89689c5ed6 Porting db health to single worker mode. 2023-02-12 10:46:26 +01:00
Eric van der Vlist 0d86b789c1 Moving sync back in the first worker (sync doesn't see updates done in other workers!) 2023-02-11 20:23:18 +01:00
Eric van der Vlist 51250c1880 Bug fix (bad promise magic!) 2023-02-11 18:21:25 +01:00
Eric van der Vlist 853b158dcf Bug fix 2023-02-11 17:52:11 +01:00
Eric van der Vlist 79fed3cc28 Simplification 2023-02-11 16:08:07 +01:00
Eric van der Vlist 0e714ac361 Searching a new balance between the two web workers... 2023-02-11 15:55:49 +01:00
Eric van der Vlist 71bd820da9 Implementing a machanism to purge databases. 2023-02-11 12:02:22 +01:00
Eric van der Vlist 4a4ebdff50 Upgrading to the PouchDb indexedDb adapter while testing signals in web workers... 2023-02-11 11:31:32 +01:00
Eric van der Vlist e73497265f Updating TrksegViewer as well. 2023-02-10 15:38:18 +01:00
Eric van der Vlist b30af4c3ac Applying the same update to trkpt 2023-02-10 15:30:45 +01:00
Eric van der Vlist d8d15d9d83 More tests 2023-02-10 08:09:13 +01:00
Eric van der Vlist 31669d8aac Adapting the address fetcher for rtes. 2023-02-10 06:35:10 +01:00
Eric van der Vlist 796147e4a9 One more test (and bug fix). 2023-02-09 21:11:17 +01:00
Eric van der Vlist c30ceecbb1 More tests and debugging putRtept 2023-02-09 21:07:09 +01:00
Eric van der Vlist 3f5bb1633c More tests 2023-02-09 16:37:46 +01:00
Eric van der Vlist a04fcab25d Adding more tests. 2023-02-09 14:36:14 +01:00
Eric van der Vlist e8a3d8c62e Re implementing a basic test for db/gpx.ts 2023-02-09 14:25:13 +01:00
Eric van der Vlist 2387b1a4e9 Stting up vitest. 2023-02-09 13:57:14 +01:00
Eric van der Vlist 4b952001c3 Restoring previous version of vite.config.ts 2023-02-09 11:42:11 +01:00
Eric van der Vlist e2ef46b612 More updates related to the previous changes. 2023-02-08 22:39:04 +01:00
Eric van der Vlist 92ffe42ab9 Major update: storing trkpt and rtept inside trkseg and rte instead of independent documents. 2023-02-08 20:44:28 +01:00
Eric van der Vlist ecae9b4037 Adding the text of the license 2023-02-07 21:42:57 +01:00
Eric van der Vlist 9ca25222f5 Updating the license. 2023-02-07 21:32:40 +01:00
Eric van der Vlist aa91262de0 Adding license-report 2023-02-07 16:54:07 +01:00
Eric van der Vlist 03c0476f46 Removing tests which hadn't been updated since React (shame on me). 2023-02-07 16:47:26 +01:00
Eric van der Vlist 57010f89f4 Adding licenses checkers 2023-02-07 16:47:10 +01:00
Eric van der Vlist 994956f58d npm update 2023-02-07 09:32:26 +01:00
Eric van der Vlist 8355ee4c1e Differentiating between web and non web platforms. 2023-02-06 18:52:14 +01:00
Eric van der Vlist a458b82dc1 Second attempt to better hide the popup overlay when not shown... 2023-02-06 14:56:39 +01:00
Eric van der Vlist 0c6e497648 Adding patch-package 2023-02-06 10:04:17 +01:00
Eric van der Vlist 16d97c009f Patch for @suid/material 2023-02-06 09:56:09 +01:00
Eric van der Vlist 86427d5ff9 Hiding (through CSS) overlay popups when not shown (otherwise they are just located under the map and show up when the map is moved before tiles are loaded. 2023-02-06 09:24:57 +01:00
Eric van der Vlist e528db9fad Bug fix (was raising an error when no rows were returned) 2023-02-05 17:41:33 +01:00
Eric van der Vlist b821748fec Basic branches history in Readme.md 2023-02-05 15:32:14 +01:00
Eric van der Vlist 038e1fb9de Exposing preview to network 2023-02-05 15:25:32 +01:00
130 changed files with 9578 additions and 4452 deletions

3
.gitignore vendored
View File

@ -2,4 +2,5 @@ node_modules/
dist/
android/
ios/
vite.config.ts.timestamp-*.mjs
vite.config.ts.timestamp-*.mjs
$*$/

View File

@ -1,5 +1,8 @@
{
"recommendations": [
"ionic.ionic"
]
"recommendations": [
"esbenp.prettier-vscode",
"streetsidesoftware.code-spell-checker",
"streetsidesoftware.code-spell-checker-french",
"solidjs-community.solid-snippets"
]
}

View File

@ -4,5 +4,6 @@
"docuri",
"Dyomedea",
"stackoverflow"
]
],
"workbench.colorTheme": "Default Light Modern"
}

View File

@ -34,7 +34,9 @@
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="geo" />
<data android:scheme="" />
</intent-filter>
<intent-filter>
@ -43,18 +45,70 @@
<data android:mimeType="application/gpx+xml" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/gpx+xml" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/xml" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/xml" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/xml" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/xml" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="file/*" />
</intent-filter>
<intent-filter>
<action
<action
android:name="com.darryncampbell.cordova.plugin.intent.ACTION"
/>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" />
<data android:host="web.dyomedea.app" />
</intent-filter>
</activity>
@ -92,4 +146,7 @@
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
</manifest>

675
LICENSE.md Normal file
View File

@ -0,0 +1,675 @@
### GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program--to make sure it remains
free software for all its users. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,5 +1,16 @@
# Dyomedea
## License
GPL 3.0.
## Branches
* master: dev (and only active) branch (started as a React project, now using solidjs)
* multi-layers: (deprecated) attempt to create a native React map components. Went pretty far but there was still so many things to implement that I switched to:
* openlayers: (deprecated) an attempt to use React with Openlayers. Wasn't that easy because Openlayers is heavily based on the DOM while React uses a "pseudo-dom". That has been one of the reasons why I switched (again) to:
* solid: (merged into master and deprecated) a SolidJS / Openlayers implementation that has replaced the master branch on Feb 5th, 2023.
## Hiking app.
## Documentation
@ -102,7 +113,7 @@ $ npx cap run --target RFCN20NEZ4R android
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ esrun helper.ts
{
caller: 'overlay-definitions',
overlayDefinitions: {
legacyOverlayDefinitions: {
amenity: {
bar: [Object],
fast_food: [Object],
@ -213,7 +224,7 @@ vdv@nuc:~/projects/tea/dyomedea/dyomedea$ esrun helper.ts
}
}
{
overlayDefinitions: {
legacyOverlayDefinitions: {
amenity: {
bar: [Object],
fast_food: [Object],
@ -343,6 +354,9 @@ Requires esrun (`sudo npm i -g @digitak/esrun`)
### Patches
* suid: https://github.com/swordev/suid/issues/89
### NPM updates: use npm-check-updates !

View File

@ -4,7 +4,9 @@ const config: CapacitorConfig = {
appId: 'com.dyomedea.dyomedea',
appName: 'dyomedea',
webDir: 'dist',
bundledWebRuntime: false
server: {
androidScheme: 'https'
}
};
export default config;

View File

@ -1,18 +0,0 @@
import fs from 'fs';
import path from 'path';
const typesPath = path.resolve('node_modules', '@types', 'testing-library__jest-dom', 'index.d.ts');
fs.readFile(typesPath, 'utf8', (err, data) => {
if (err) throw err;
let lines = data.split('\n');
if (lines[8] === '/// <reference types="jest" />') {
lines = lines.slice(0, 8).concat(lines.slice(9));
}
fs.writeFile(typesPath, lines.join('\n'), 'utf8', function(err) {
if (err) throw err;
});
});

View File

@ -1,14 +1,63 @@
import { overlayDefinitions } from './src/components/overlays/overlay-definitions';
import {
overlayDefinitions,
osmTags,
} from './src/components/overlays/overlay-definitions';
let filters: any[] = ['any'];
// One timer
Object.keys(overlayDefinitions).forEach((key) => {
const definition = overlayDefinitions[key];
let filter: any[] = ['in', key];
Object.keys(definition).forEach((subKey) => {
filter = [...filter, subKey];
});
filters = [...filters, filter];
});
// let tags = {};
// let overlays = {};
console.log({ overlayDefinitions, filters, json: JSON.stringify(filters) });
// for (const tagName of Object.keys(legacyOverlayDefinitions)) {
// for (const tagValue of Object.keys(legacyOverlayDefinitions[tagName])) {
// tags[tagValue] = { name: tagName, value: tagValue };
// for (const activity of Object.keys(
// legacyOverlayDefinitions[tagName][tagValue]
// )) {
// if (!overlays[activity]) {
// overlays[activity] = {};
// }
// for (const category of Object.keys(
// legacyOverlayDefinitions[tagName][tagValue][activity]
// )) {
// if (!overlays[activity][category]) {
// overlays[activity][category] = [];
// }
// overlays[activity][category].push(tagValue);
// }
// }
// }
// }
// console.log({
// caller: 'onetimer / result',
// tags: JSON.stringify(tags),
// overlays: JSON.stringify(overlays),
// });
// End of one timer
for (const overlayCategory of Object.keys(overlayDefinitions)) {
let filters: any[] = ['any'];
const definitions = overlayDefinitions[overlayCategory];
let tags = {};
for (const category of Object.keys(definitions)) {
//console.log({ category });
for (const tagId of definitions[category]) {
//console.log({ tagId });
const tag = osmTags[tagId];
if (!tags[tag.name]) {
tags[tag.name] = [];
}
tags[tag.name].push(tag.value);
}
}
for (const tagName of Object.keys(tags)) {
let filter = ['in', tagName];
for (const tagValue of tags[tagName]) {
filter.push(tagValue);
}
filters.push(filter);
}
console.log({ overlayCategory, filters: JSON.stringify(filters) });
}

5605
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -7,53 +7,64 @@
"start": "vite",
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"serve": "vite preview --host",
"test": "vitest",
"postinstall": "node ./fix-jest-dom.mjs"
"postinstall": "patch-package"
},
"license": "MIT",
"license": "GPL-3.0-only",
"devDependencies": {
"@capacitor/cli": "^4.6.3",
"@testing-library/jest-dom": "^5.16.5",
"@types/lodash": "^4.14.191",
"@types/memoizee": "^0.4.8",
"@capacitor/cli": "^5.4.2",
"@solidjs/testing-library": "^0.8.4",
"@testing-library/jest-dom": "^6.1.3",
"@types/lodash": "^4.14.199",
"@types/memoizee": "^0.4.9",
"@types/pouchdb": "^6.4.0",
"@types/proj4": "^2.5.2",
"jsdom": ">=21.1.0",
"solid-testing-library": ">=0.5.0",
"typescript": "^4.9.5",
"vite": ">=4.1.1",
"vite-plugin-solid": "^2.5.0",
"vitest": ">=0.28.4"
"@types/proj4": "^2.5.3",
"@types/shelljs": "^0.8.13",
"@vitest/ui": "^0.34.6",
"jsdom": "^22.1.0",
"license-checker": "^25.0.1",
"license-compatibility-checker": "^0.3.5",
"license-report": "^6.4.0",
"shelljs": "^0.8.5",
"typescript": "^5.2.2",
"vite": ">=4.4.11",
"vite-plugin-solid": "^2.7.0",
"vitest": "^0.34.6"
},
"dependencies": {
"@awesome-cordova-plugins/android-full-screen": "^6.3.0",
"@awesome-cordova-plugins/geolocation": "^6.3.0",
"@awesome-cordova-plugins/web-intent": "^6.3.0",
"@capacitor-community/background-geolocation": "^1.2.7",
"@capacitor/android": "^4.6.3",
"@capacitor/browser": "^4.1.1",
"@capacitor/core": "^4.6.3",
"@capacitor/filesystem": "^4.1.4",
"@capacitor/ios": "^4.6.3",
"@awesome-cordova-plugins/android-full-screen": "^6.4.0",
"@awesome-cordova-plugins/geolocation": "^6.4.0",
"@awesome-cordova-plugins/web-intent": "^6.4.0",
"@capacitor-community/background-geolocation": "^1.2.15",
"@capacitor/android": "^5.4.2",
"@capacitor/browser": "^5.1.0",
"@capacitor/core": "^5.4.2",
"@capacitor/filesystem": "^5.1.4",
"@capacitor/ios": "^5.4.2",
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
"@solid-primitives/i18n": "^1.1.3",
"@solidjs/router": "^0.7.0",
"@suid/icons-material": "^0.5.8",
"@suid/material": "^0.10.1",
"@suid/vite-plugin": "^0.1.2",
"@solid-primitives/i18n": "^2.0.0",
"@solidjs/router": "^0.8.3",
"@suid/icons-material": "^0.6.11",
"@suid/material": "^0.15.1",
"@suid/vite-plugin": "^0.1.5",
"blob-util": "^2.0.2",
"com-darryncampbell-cordova-plugin-intent": "^2.2.0",
"cordova-plugin-fullscreen": "^1.3.0",
"isomorphic-xml2js": "^0.1.3",
"lodash": "^4.17.21",
"memoizee": "^0.4.15",
"ol": "^7.2.2",
"ol": "^8.1.0",
"osmtogeojson": "^3.0.0-beta.5",
"pouchdb": "^8.0.0",
"pouchdb-browser": "^8.0.0",
"proj4": "^2.8.1",
"solid-js": "^1.6.10",
"vite-plugin-solid-svg": "^0.6.0"
"patch-package": "^8.0.0",
"piexifjs": "^1.0.6",
"pluscodes": "^2.6.0",
"pouchdb": "^8.0.1",
"pouchdb-adapter-indexeddb": "^8.0.1",
"pouchdb-browser": "^8.0.1",
"proj4": "^2.9.0",
"solid-js": "^1.7.12",
"vite-plugin-solid-svg": "^0.6.4"
}
}

View File

@ -0,0 +1,13 @@
diff --git a/node_modules/@suid/material/InputBase/InputBase.jsx b/node_modules/@suid/material/InputBase/InputBase.jsx
index 4d9a4b9..e465053 100644
--- a/node_modules/@suid/material/InputBase/InputBase.jsx
+++ b/node_modules/@suid/material/InputBase/InputBase.jsx
@@ -239,7 +239,7 @@ const inputGlobalStyles = () => (<>
"@keyframes mui-auto-fill-cancel": { from: { display: "block" } },
}}/>}
</>);
-const selectionTypes = new Set(["text", "search", "password", "tel", "url"]);
+const selectionTypes = new Set(["text", "textarea", "search", "password", "tel", "url"]);
/**
* `InputBase` contains as few styles as possible.
* It aims to be a simple building block for creating an input.

View File

@ -0,0 +1,33 @@
diff --git a/node_modules/piexifjs/piexif.js b/node_modules/piexifjs/piexif.js
index 3d0bd12..a920f5e 100644
--- a/node_modules/piexifjs/piexif.js
+++ b/node_modules/piexifjs/piexif.js
@@ -1781,6 +1781,18 @@ SOFTWARE.
'name': 'DateTimeDigitized',
'type': 'Ascii'
},
+ 36880: {
+ 'name': 'OffsetTime',
+ 'type': 'Ascii'
+ },
+ 36881: {
+ 'name': 'OffsetTimeOriginal',
+ 'type': 'Ascii'
+ },
+ 36882: {
+ 'name': 'OffsetTimeDigitized',
+ 'type': 'Ascii'
+ },
37121: {
'name': 'ComponentsConfiguration',
'type': 'Undefined'
@@ -2349,6 +2361,9 @@ SOFTWARE.
ExifVersion:36864,
DateTimeOriginal:36867,
DateTimeDigitized:36868,
+ OffsetTime:36880,
+ OffsetTimeOriginal:36881,
+ OffsetTimeDigitized:36882,
ComponentsConfiguration:37121,
CompressedBitsPerPixel:37122,
ShutterSpeedValue:37377,

View File

@ -2,13 +2,15 @@ import { Component, createSignal, For } from 'solid-js';
import PersonIcon from '@suid/icons-material/Person';
import style from './Account.module.css';
import {
Box,
Button,
DialogActions,
IconButton,
InputLabel,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
NativeSelect,
TextField,
} from '@suid/material';
@ -34,6 +36,10 @@ const Account: Component<{}> = (props) => {
const newAccounts: any = await dispatch({
action: 'getAccounts',
});
console.log({
caller: 'Account / handleClickOpen',
newAccounts,
});
setAccounts([{ id: '--new--', name: t('newAccount') }, ...newAccounts]);
setAccount(
cloneDeep(getAccountById(accounts(), settings().currentAccountId))
@ -119,11 +125,15 @@ const Account: Component<{}> = (props) => {
return (
<>
<div class={style.control}>
<IconButton onClick={handleClickOpen}>
<PersonIcon />
</IconButton>
</div>
<ListItem>
<ListItemButton onClick={handleClickOpen}>
<ListItemIcon>
<PersonIcon />
</ListItemIcon>
<ListItemText>Account</ListItemText>
</ListItemButton>
</ListItem>
<Dialog
open={open()}
title={t('account')}

View File

@ -8,43 +8,34 @@ import { useI18n } from '@solid-primitives/i18n';
import dispatch from '../../workers/dispatcher-main';
interface Props {
target: () => any;
putAction: string;
putParamName: string;
wpt: () => Wpt;
dispatchParams: (wpt: Wpt) => { action: string; params: any };
}
const DisplayOrGetAddress: Component<Props> = ({
target,
putAction,
putParamName,
}) => {
const DisplayOrGetAddress: Component<Props> = ({ wpt, dispatchParams }) => {
const [t, { add, locale, dict }] = useI18n();
const findClickHandler = async () => {
const address = await findAddress(target().$.lon, target().$.lat, locale);
const updatedTarget = cloneDeep(target());
console.log({ caller: 'findClickHandler', wpt: wpt() });
const address = await findAddress(wpt().$.lon, wpt().$.lat, locale);
const updatedTarget = cloneDeep(wpt());
if (updatedTarget.extensions === undefined) {
updatedTarget.extensions = {};
}
updatedTarget.extensions.address = address;
const params: any = { id: target().id };
params[putParamName] = updatedTarget;
dispatch({
action: putAction,
params,
});
dispatch(dispatchParams(updatedTarget));
};
return (
<Show
when={target().extensions?.address}
when={wpt()?.extensions?.address}
fallback={
<IconButton color='primary' onClick={findClickHandler}>
<SearchIcon />
</IconButton>
}
>
<>{getVillageOrTown(target().extensions?.address)}</>
<>{getVillageOrTown(wpt()?.extensions?.address)}</>
</Show>
);
};

View File

@ -0,0 +1,36 @@
import { Component } from 'solid-js';
import { useI18n } from '@solid-primitives/i18n';
import DisplayOrGetAddress from '.';
interface Props {
id: string;
wpts: () => Wpt[];
putAction: string;
}
const DisplayOrGetStartEndAddresses: Component<Props> = (props) => {
const { id, wpts, putAction } = props;
const [t, { add, locale, dict }] = useI18n();
const dispatchParamsFactory = (index: number) => (wpt: Wpt) => ({
action: putAction,
params: { id, index, wpt },
});
return (
<>
{t('from')}{' '}
<DisplayOrGetAddress
wpt={() => wpts()?.at(0)}
dispatchParams={dispatchParamsFactory(0)}
/>{' '}
{t('to')}{' '}
<DisplayOrGetAddress
wpt={() => wpts()?.at(-1)}
dispatchParams={dispatchParamsFactory(-1)}
/>
</>
);
};
export default DisplayOrGetStartEndAddresses;

View File

@ -1 +1,2 @@
export { default } from './DisplayOrGetAddress';
export { default as DisplayOrGetStartEndAddresses } from './DisplayOrGetStartEndAddresses';

View File

@ -0,0 +1,222 @@
import { Component, createEffect } from 'solid-js';
import style from './index.module.css';
import Tree from '../tree/Tree';
import getUri from '../../lib/ids';
import { createCachedSignal } from '../../workers/cached-signals';
import { FormControlLabel, Radio, RadioGroup } from '@suid/material';
import { getDrawingSelections } from '../../db/drawing-selections';
import dispatch from '../../workers/dispatcher-main';
import { Feature } from 'ol';
import uri from '../../lib/ids';
import { currentGpxId } from '../gpx-dialog';
const id = getUri('drawingSelections', undefined);
type CompleteSelectionType = 'ALL' | 'NONE' | 'CURRENT';
type RestrictedSelectionType = 'ALL' | 'NONE';
type DrawingSelections = {
gpxSelection: CompleteSelectionType;
trkSelection: RestrictedSelectionType;
rteSelection: RestrictedSelectionType;
wptSelection: RestrictedSelectionType;
};
const defaultDrawingSelections: DrawingSelections = {
gpxSelection: 'ALL',
trkSelection: 'ALL',
rteSelection: 'ALL',
wptSelection: 'ALL',
};
const drawingSelections = createCachedSignal({
id,
method: 'getDrawingSelections',
defaultDrawingSelections,
}) as () => DrawingSelections;
createEffect(() => {
console.log({
caller: 'DrawingSelections',
drawingSelections: drawingSelections(),
});
});
const AllNoneCurrent: Component<{}> = (props) => {
return (
<>
<FormControlLabel
value='ALL'
control={<Radio />}
label='All'
></FormControlLabel>
<FormControlLabel
value='NONE'
control={<Radio />}
label='None'
></FormControlLabel>
<FormControlLabel
value='CURRENT'
control={<Radio />}
label='Current'
></FormControlLabel>
</>
);
};
const AllNone: Component<{}> = (props) => {
return (
<>
<FormControlLabel
value='ALL'
control={<Radio />}
label='All'
></FormControlLabel>
<FormControlLabel
value='NONE'
control={<Radio />}
label='None'
></FormControlLabel>
</>
);
};
const gpxSelection = () => drawingSelections().gpxSelection;
const gpxMustBeDrawn = (feature: Feature) => {
const id = feature.getId() as String;
if (gpxSelection() === 'ALL') {
return true;
}
if (gpxSelection() === 'CURRENT') {
return id.startsWith(currentGpxId());
}
return false;
};
const typeMustBeDrawn = (feature: Feature) => {
const type = feature.get('type') as String;
if (type.startsWith('trk')) {
return drawingSelections().trkSelection !== 'NONE';
}
if (type === 'wpt') {
return drawingSelections().wptSelection !== 'NONE';
}
if (type === 'rte') {
return drawingSelections().rteSelection !== 'NONE';
}
return true;
};
export const mustBeDrawn = (feature: Feature) => {
console.log({
caller: 'DrawingSelector / mustBeDrawn',
feature,
});
return gpxMustBeDrawn(feature) && typeMustBeDrawn(feature);
};
const handleGpxSelectionChange = (ev: any) => {
const value = ev.target.value;
console.log({
caller: 'DrawingSelector / handleGpxSelectionChange',
ev,
value,
});
const newDrawingSelections = drawingSelections();
newDrawingSelections.gpxSelection = value;
dispatch({
action: 'putDrawingSelections',
params: { id, drawingSelections: newDrawingSelections },
});
};
const handleTrkSelectionChange = (ev: any) => {
const value = ev.target.value;
console.log({
caller: 'DrawingSelector / handleTrkSelectionChange',
ev,
value,
});
const newDrawingSelections = drawingSelections();
newDrawingSelections.trkSelection = value;
dispatch({
action: 'putDrawingSelections',
params: { id, drawingSelections: newDrawingSelections },
});
};
const handleRteSelectionChange = (ev: any) => {
const value = ev.target.value;
console.log({
caller: 'DrawingSelector / handleRteSelectionChange',
ev,
value,
});
const newDrawingSelections = drawingSelections();
newDrawingSelections.rteSelection = value;
dispatch({
action: 'putDrawingSelections',
params: { id, drawingSelections: newDrawingSelections },
});
};
const handleWptSelectionChange = (ev: any) => {
const value = ev.target.value;
console.log({
caller: 'DrawingSelector / handleWptSelectionChange',
ev,
value,
});
const newDrawingSelections = drawingSelections();
newDrawingSelections.wptSelection = value;
dispatch({
action: 'putDrawingSelections',
params: { id, drawingSelections: newDrawingSelections },
});
};
const DrawingSelector: Component<{}> = (props) => {
return (
<Tree
title='Show'
content={
<>
<div>Trips</div>
<RadioGroup
defaultValue={drawingSelections()?.gpxSelection}
onChange={handleGpxSelectionChange}
>
<AllNoneCurrent />
</RadioGroup>
<div>Tracks</div>
<RadioGroup
defaultValue={drawingSelections()?.trkSelection}
onChange={handleTrkSelectionChange}
>
<AllNone />
</RadioGroup>
<div>Routes</div>
<RadioGroup
defaultValue={drawingSelections()?.rteSelection}
onChange={handleRteSelectionChange}
>
<AllNone />
</RadioGroup>{' '}
<div>Waypoints</div>
<RadioGroup
defaultValue={drawingSelections()?.wptSelection}
onChange={handleWptSelectionChange}
>
<AllNone />
</RadioGroup>
</>
}
subTree={undefined}
/>
);
};
export default DrawingSelector;

View File

@ -0,0 +1,3 @@
import { mustBeDrawn } from './DrawingSelector';
export { default, mustBeDrawn } from './DrawingSelector';

View File

@ -5,6 +5,13 @@
margin-left: calc(100% - 230px) !important;
z-index: 1;
}
.control_web {
opacity: 1;
position: fixed !important;
top: 0px;
margin-left: calc(100% - 190px) !important;
z-index: 1;
}
.ol_popup {
position: absolute;
background-color: white;

View File

@ -7,12 +7,16 @@ import { useI18n } from '@solid-primitives/i18n';
import proj4 from 'proj4';
import style from './Finder.module.css';
import './finder.css';
import { Box, Button, IconButton, TextField } from '@suid/material';
import Dialog from '../dialog';
import { getMap, getState } from '../map';
import { Overlay } from 'ol';
import { fromLonLat } from 'ol/proj';
import WptEditDialog from '../wpt/WptEditDialog';
import maybePlusCode from '../../lib/check-pluscodes';
import { decode, expand } from 'pluscodes';
const [popup, setPopup] = createSignal<Overlay>();
const [open, setOpen] = createSignal(false);
@ -66,6 +70,7 @@ const Finder: Component<Props> = (props) => {
};
const submitHandler = () => {
setCoordinate(undefined);
const latLonRegExp = /(-?[0-9]+.[0-9]+)\s*,\s*(-?[0-9]+.[0-9]+)/;
const latLonMatch = searchString().match(latLonRegExp);
@ -87,15 +92,46 @@ const Finder: Component<Props> = (props) => {
setPopupContent(
<>{`${coordinate()[0]}, ${coordinate()[1]} (UTM ${utmMatch[0]})`}</>
);
console.log({
caller: 'Finder / submitHandler',
searchString: searchString(),
utmMatch,
coordinate: coordinate(),
});
} else {
const potentialPlusCode = maybePlusCode(searchString());
if (!!potentialPlusCode) {
let plusCode = potentialPlusCode.code;
if (potentialPlusCode.isShort) {
plusCode = expand(potentialPlusCode.code, {
longitude: getState().lon,
latitude: getState().lat,
});
}
const plusCodeCoordinates = decode(plusCode);
if (plusCodeCoordinates) {
setCoordinate([
plusCodeCoordinates.longitude,
plusCodeCoordinates.latitude,
]);
}
console.log({
caller: 'Finder / submitHandler',
searchString: searchString(),
potentialPlusCode,
plusCode,
plusCodeCoordinates,
state: getState(),
coordinate: coordinate(),
});
} else {
console.log({
caller: 'Finder / submitHandler / no match found',
searchString: searchString(),
});
}
}
console.log({
caller: 'Finder / submitHandler',
searchString: searchString(),
utmMatch,
coordinate: coordinate(),
});
}
if (!!coordinate()) {
findLocation(navigate, coordinate());
}
@ -110,7 +146,13 @@ const Finder: Component<Props> = (props) => {
return (
<>
<div class={style.control}>
<div
class={
window.Capacitor.platform === 'web'
? style.control_web
: style.control
}
>
<IconButton
onClick={() => {
setOpen(true);
@ -139,9 +181,12 @@ const Finder: Component<Props> = (props) => {
method='dialog'
>
<TextField onChange={searchStringChangeHandler} />
<Button variant='contained' onClick={submitHandler}>
Search
</Button>
</Box>
</Dialog>
<div class={style.ol_popup} ref={popupElement}>
<div class={style.ol_popup + ' ol_popup'} ref={popupElement}>
<a
href='#'
onclick={popupCloseHandler}
@ -168,5 +213,4 @@ const Finder: Component<Props> = (props) => {
</>
);
};
export default Finder;

View File

@ -0,0 +1,3 @@
.ol-map > .ol_popup {
visibility: hidden;
}

View File

@ -23,6 +23,11 @@ const GpxChooser: Component<Props> = (props: Props) => {
action: 'getAllGpxesWithSummary',
},
(error, result) => {
console.log({
caller: 'GpxChooser / getAllGpxesWithSummary',
error,
result,
});
if (!error) {
setAllGpxes([
{ id: 'new', name: t('newGpx'), creator: 'dyomedea' },

View File

@ -1,6 +1,15 @@
import { useI18n } from '@solid-primitives/i18n';
import { Box, Button, IconButton, SvgIcon, TextField } from '@suid/material';
import { cloneDeep } from 'lodash';
import {
Box,
Button,
FormControlLabel,
IconButton,
Radio,
RadioGroup,
SvgIcon,
TextField,
} from '@suid/material';
import { cloneDeep, isPlainObject } from 'lodash';
import { Component, createSignal, Show } from 'solid-js';
import { newEmptyGpx } from '../../db/gpx';
import { peekCachedSignal } from '../../workers/cached-signals';
@ -10,6 +19,12 @@ import GpxChooser from '../gpx-chooser';
import GpxIcon from '../gpx/GpxIcon';
//import GpxesIcon from '../../icons/adventure-journey-location-svgrepo-com.svg';
import style from './GpxDialog.module.css';
import {
getTagValue,
getTagsFromObj,
setTagValue,
setTagsIntoObj,
} from '../../lib/tags/tags';
export const [currentGpxId, setCurrentGpxId] = createSignal<string>('new');
@ -19,11 +34,12 @@ const GpxDialog: Component<{}> = (props) => {
const [selectedGpxId, setSelectedGpxId] = createSignal<string>('');
const [gpx, setGpx] = createSignal<Gpx>();
const [currentAccount, setCurrentAccount] = createSignal<any>();
console.log({ caller: 'GpxDialog', currentGpxId: currentGpxId() });
const fetchGpx = (gpxId: string) => {
if (gpxId === 'new') {
if (gpxId === 'new' || !gpxId) {
return newEmptyGpx();
}
const newGpx = peekCachedSignal({
@ -33,12 +49,16 @@ const GpxDialog: Component<{}> = (props) => {
return newGpx();
};
dispatch({ action: 'getCurrentAccount' }).then((currentAccount: any) => {
console.log({ caller: 'GpxDialog / currentAccount', currentAccount });
setCurrentAccount(currentAccount);
setCurrentGpxId(currentAccount.currentGpxId || 'new');
setSelectedGpxId(currentAccount.currentGpxId || 'new');
});
const handleClickOpen = async () => {
setOpen(true);
setSelectedGpxId(currentGpxId());
if (currentGpxId() !== '') {
setGpx(fetchGpx(currentGpxId()) as Gpx);
}
setGpx(fetchGpx(currentGpxId()) as Gpx);
console.log({
caller: 'GpxDialog / handleClickOpen',
currentGpxId: currentGpxId(),
@ -93,6 +113,20 @@ const GpxDialog: Component<{}> = (props) => {
gpx: gpx(),
});
};
const gpxToChangeHandler = (event: any) => {
const newGpx: Gpx = cloneDeep(gpx()) as Gpx;
if (!isPlainObject(newGpx.extensions)) {
newGpx.extensions = {};
}
newGpx.extensions.to = event.target.value;
setGpx(newGpx);
console.log({
caller: 'GpxDialog / gpxToChangeHandler',
value: event.target.value,
gpx: gpx(),
newGpx,
});
};
const gpxTimeChangeHandler = (event: any) => {
const newGpx: Gpx = cloneDeep(gpx()) as Gpx;
if (newGpx.metadata === undefined) {
@ -107,6 +141,18 @@ const GpxDialog: Component<{}> = (props) => {
});
};
const getGpxTagValue = (tagName: string, defaultValue: string) => {
return getTagValue(getTagsFromObj(gpx()), tagName) || defaultValue;
};
const gpxLocomotionChangeHandler = (event: any) => {
const newGpx: Gpx = cloneDeep(gpx()) as Gpx;
const tags = getTagsFromObj(newGpx);
setTagValue(tags, 'locomotion', event.target.value);
setTagsIntoObj(newGpx, tags);
setGpx(newGpx);
};
const saveHandler = async (event: any) => {
const id = (await dispatch({
action: 'putGpx',
@ -117,6 +163,12 @@ const GpxDialog: Component<{}> = (props) => {
})) as string;
setCurrentGpxId(id);
setOpen(false);
await dispatch({
action: 'putCurrentAccount',
params: {
account: { ...currentAccount(), currentGpxId: currentGpxId() },
},
});
};
return (
@ -164,6 +216,30 @@ const GpxDialog: Component<{}> = (props) => {
onChange={gpxDescChangeHandler}
InputProps={{ inputComponent: 'textarea' }}
/>
<div>Locomotion</div>
<RadioGroup
value={getGpxTagValue('locomotion', 'hiking')}
onChange={gpxLocomotionChangeHandler}
>
<FormControlLabel
value='hiking'
control={<Radio />}
label='Hiking'
></FormControlLabel>
<FormControlLabel
value='cycling'
control={<Radio />}
label='Cycling'
></FormControlLabel>
</RadioGroup>
<TextField
label={t('gpxTo')}
multiline={true}
rows={5}
value={gpx()?.extensions?.to || ''}
onChange={gpxToChangeHandler}
InputProps={{ inputComponent: 'textarea' }}
/>
<Button variant='contained' onClick={saveHandler}>
{t('gpxSave')}
</Button>

View File

@ -1,208 +0,0 @@
import { useI18n } from '@solid-primitives/i18n';
import {
Typography,
Card,
CardContent,
CardActions,
Button,
Box,
LinearProgress,
CircularProgress,
} from '@suid/material';
import { Component, createEffect, createSignal, Show } from 'solid-js';
import { findStartTime } from '../../lib/gpx';
import GPX from '../../lib/gpx-parser-builder/src/gpx';
import dispatch from '../../workers/dispatcher-main';
import GpxChooser from '../gpx-chooser';
import { currentGpxId } from '../gpx-dialog';
import {
Filesystem as CapacitorFileSystem,
Encoding,
} from '@capacitor/filesystem';
interface Props {
gpxFile: File;
}
interface StatsAndGpx {
gpx: Gpx;
stats: any;
}
const analyzeGpx = (gpx: Gpx | undefined) => {
if (gpx === undefined) {
return {};
}
const stats = {
creator: gpx.$.creator,
nbWpts: gpx.wpt ? gpx.wpt?.length : 0,
nbRtes: gpx.rte ? gpx.rte?.length : 0,
nbTrks: gpx.trk ? gpx.trk?.length : 0,
trkMaybeRte:
gpx.trk &&
gpx.trk[0].trkseg &&
gpx.trk[0].trkseg[0] &&
gpx.trk[0].trkseg[0].trkpt &&
!gpx.trk[0].trkseg[0].trkpt[0].time,
startTime: findStartTime(gpx),
};
return stats;
};
const GpxImportSingleFile: Component<Props> = ({ gpxFile }) => {
const [t] = useI18n();
const [statsAndGpx, setStatsAndGpx] = createSignal<StatsAndGpx>();
const [state, setState] = createSignal('init');
const [gpxId, setGpxId] = createSignal<string>('');
createEffect(() => {
setGpxId(currentGpxId());
});
const parseGpx = (content: string) => {
const gpx = GPX.parse(content);
console.log({ caller: 'GpxImportSingleFile / JSON', gpxFile, gpx });
setStatsAndGpx({ gpx, stats: analyzeGpx(gpx) });
};
if (typeof gpxFile === 'string') {
CapacitorFileSystem.requestPermissions().then((permissionStatus) => {
console.log({
caller: 'GpxImportSingleFile / content',
permissionStatus,
});
});
CapacitorFileSystem.readFile({
path: gpxFile,
encoding: Encoding.UTF8,
}).then((content) => {
console.log({
caller: 'GpxImportSingleFile / content',
gpxFile,
content,
});
parseGpx(content.data);
});
} else {
const gpxReader = new FileReader();
gpxReader.readAsText(gpxFile);
gpxReader.addEventListener(
'load',
async () => {
// this will then display a text gpxfile
console.log({
caller: 'GpxImportSingleFile / XML',
gpxFile,
result: gpxReader.result,
});
parseGpx(gpxReader.result);
},
false
);
}
const doImport = async () => {
setState('importing');
// console.log({ caller: 'GpxImport / JSON', file, gpx });
// if (gpx) {
// const startTime = new Date(findStartTime(gpx)!);
await dispatch({
action: 'pruneAndSaveImportedGpx',
params: {
id: gpxId(),
gpx: statsAndGpx()?.gpx,
tech:
typeof gpxFile === 'string'
? {
importDate: new Date().toISOString(),
uri: gpxFile,
}
: {
lastModified: new Date(gpxFile.lastModified).toISOString(),
importDate: new Date().toISOString(),
name: gpxFile.name,
size: gpxFile.size,
type: gpxFile.type,
},
},
});
console.log({
caller: 'GpxImport / JSON / done',
gpxFile,
gpx: statsAndGpx()?.gpx,
});
setState('done');
// } else {
// console.error({
// message: "can't parse GPX file",
// file,
// xml: fileReader.result,
// });
// }
// // TODO: error handling
// },
// false
// );
// }
};
const [selectedTrkTransform, setSelectedTrkTransform] = createSignal(
'importNonTimedTrksAsRtes'
);
const handleTrkTransformChange = (event: any) => {
setSelectedTrkTransform(event.target.value);
};
const controlTrkTransformProps = (item: string) => ({
checked: selectedTrkTransform() === item,
onChange: handleTrkTransformChange,
value: item,
name: 'trkTransform',
label: t(item),
inputProps: { 'aria-label': item },
});
return (
<Card raised>
<CardContent>
<Typography variant='h6'>
{t('file')}
{gpxFile.name}
</Typography>
</CardContent>
<CardContent>
<Show when={statsAndGpx() !== undefined}>
<Typography variant='body1'>
{t('gpxStats', statsAndGpx().stats)}{' '}
{statsAndGpx()?.stats.startTime
? t('gpxStartTime', statsAndGpx().stats)
: t('gpxNoStartTime')}
</Typography>
<Show when={statsAndGpx().stats.trkMaybeRte}>
<Typography variant='body1'>{t('trkMaybeRte')}</Typography>
</Show>
<Show when={state() === 'importing'}>
<LinearProgress />
</Show>
<CardActions>
<GpxChooser
gpxId={gpxId}
setGpxId={setGpxId}
disabled={state() != 'init'}
/>
<Button
variant='contained'
disabled={state() != 'init'}
onClick={doImport}
>
{t('import')}
</Button>
</CardActions>
</Show>
</CardContent>
</Card>
);
};
export default GpxImportSingleFile;

View File

@ -1 +0,0 @@
export { default, importUrls } from './GpxImport';

View File

@ -42,7 +42,10 @@ const GpxRecord: Component<{}> = (props) => {
location.time - globalThis.$lastValidLocationTime
}`
);
if (location.time - globalThis.$lastValidLocationTime > 15000) {
if (
location.accuracy < 10 &&
location.time - globalThis.$lastValidLocationTime > 15000
) {
globalThis.$lastValidLocationTime = location.time;
await dispatch({
action: 'appendTrkpt',
@ -62,7 +65,7 @@ const GpxRecord: Component<{}> = (props) => {
},
},
});
setCurrentLocation({lon:location.longitude, lat:location.latitude});
setCurrentLocation({ lon: location.longitude, lat: location.latitude });
const state = getState();
navigate(
`/map/${state.provider}/${location.longitude}/${location.latitude}/${state.zoom}/${state.rotation}`
@ -87,7 +90,7 @@ const GpxRecord: Component<{}> = (props) => {
const trkIdObj = getUri('trk', trkId);
setTrksegId({ ...trkIdObj, trkseg: 0 });
globalThis.$lastValidLocationTime = 0;
const id = await startBackgroundGeolocation(newLocationHandler, 20);
const id = await startBackgroundGeolocation(newLocationHandler, 10);
setWatcherId(id);
setState('recording');
setOpen(false);
@ -99,7 +102,7 @@ const GpxRecord: Component<{}> = (props) => {
};
const resumeRecordingHandler = async () => {
setTrksegId({ ...trksegId()!, trkseg: trksegId()!.trkseg + 1 });
const id = await startBackgroundGeolocation(newLocationHandler, 20);
const id = await startBackgroundGeolocation(newLocationHandler, 10);
setWatcherId(id);
setState('recording');
setOpen(false);

View File

@ -13,6 +13,7 @@ import {
createCachedSignal,
destroyCachedSignal,
} from '../../workers/cached-signals';
import { getTagsFromObj } from '../../lib/tags/tags';
interface Props {
gpxId: string;
@ -37,16 +38,28 @@ export const Gpx: Component<Props> = ({ map, gpxId }) => {
destroyCachedSignal(params);
});
const vectorSource = new VectorSource();
const vectorLayer = new VectorLayer({
source: vectorSource,
style,
declutter: true,
const vectorSources = [new VectorSource(), new VectorSource()];
const vectorLayers = [
new VectorLayer({
source: vectorSources[0],
style,
declutter: true,
zIndex: 1,
}),
new VectorLayer({
source: vectorSources[1],
style,
declutter: false,
zIndex: 2,
}),
];
createEffect(() => {
map()?.addLayer(vectorLayers[0]);
map()?.addLayer(vectorLayers[1]);
});
createEffect(() => map()?.addLayer(vectorLayer));
createEffect(() => {
console.log({ caller: 'Gpx', map: map(), gpxId, gpx: gpx(), vectorLayer });
console.log({ caller: 'Gpx', map: map(), gpxId, gpx: gpx(), vectorLayers });
});
return (
@ -57,9 +70,10 @@ export const Gpx: Component<Props> = ({ map, gpxId }) => {
return (
<Suspense>
<Trk
vectorSource={vectorSource}
vectorSources={vectorSources}
trkId={trkId}
context={{ gpx, gpxId }}
tags={getTagsFromObj(gpx())}
/>
</Suspense>
);
@ -71,7 +85,7 @@ export const Gpx: Component<Props> = ({ map, gpxId }) => {
return (
<Suspense>
<Rte
vectorSource={vectorSource}
vectorSources={vectorSources}
rteId={rteId}
context={{ gpx, gpxId }}
/>
@ -85,7 +99,7 @@ export const Gpx: Component<Props> = ({ map, gpxId }) => {
return (
<Suspense>
<Wpt
vectorSource={vectorSource}
vectorSources={vectorSources}
wptId={wptId}
context={{ gpx, gpxId }}
/>

View File

@ -57,8 +57,12 @@ import saddle from '../../icons/osm/saddle.svg';
import stone from '../../icons/osm/stone.svg';
import spring from '../../icons/osm/spring.svg';
import fumarole from '../../icons/osm/eruption-svgrepo-com.svg';
import parking from '../../icons/osm/parking.svg';
import bicycle_parking from '../../icons/osm/parking_bicycle.svg';
export const osmIcons = {
parking,
bicycle_parking,
bar,
fast_food,
food_court: fast_food,

View File

@ -1,6 +1,4 @@
import { Fill, Text, Icon, Stroke, Style, Circle } from 'ol/style';
import startIcon from '../../icons/flag-start-b-svgrepo-com-green.svg';
import finishIcon from '../../icons/flag-finish-b-o-svgrepo-com-red.svg';
import wptIcon from '../../icons/location-pin-svgrepo-com-green.svg';
import houseIcon from '../../icons/house-svgrepo-com.svg';
import houseFlatIcon from '../../icons/houseFlat-svgrepo-com.svg';
@ -10,40 +8,41 @@ import cheeseIcon from '../../icons/cheese-svgrepo-com.svg';
import trainIcon from '../../icons/train-svgrepo-com.svg';
import picnicIcon from '../../icons/picnic-svgrepo-com.svg';
import caveIcon from '../../icons/cave-entrance-svgrepo-com.svg';
import leftArrowIcon from '../../icons/right-arrow-svgrepo-com.svg';
import hikerIcon from '../../icons/hiker-svgrepo-com.svg';
import cycleIcon from '../../icons/bicycle-man-svgrepo-com.svg';
import blackArrowheadPointingUp from '../../icons/black-arrowhead-pointing-up-svgrepo-com.svg';
import wptIconSel from '../../icons/location-pin-svgrepo-com-red.svg';
import noteIcon from '../../icons/note-svgrepo-com.svg';
import { Feature } from 'ol';
import memoize from 'memoizee';
import { getMap, getState } from '../map';
import { getMap } from '../map';
import { Point } from 'ol/geom';
import { Coordinate } from 'ol/coordinate';
import { createDefaultStyle } from 'ol/style/Style';
import osmIcons, { highlight } from './osm-icons';
import { indexOf } from 'lodash';
import osmIcons from './osm-icons';
import { getZoomInteger } from '../map/Map';
import { isHighlighted } from '../map-tile-provider';
import {
getAllPoiTypes,
getHighlightedTagValue,
getTagValue,
} from '../map-tile-provider/MapTileProvider';
import { isHighlightedTagType } from '../map-tile-provider/MapTileProvider';
import { getCenter } from 'ol/extent';
import { getVectorTileFeatureType } from '../overlays/overlay-definitions';
import {
getVectorTileFeatureType,
getTagType,
} from '../overlays/overlay-definitions';
import { Category } from '../wpt/WptEditDialog';
import { mustBeDrawn } from '../drawing-selector';
import { getTagValue } from '../../lib/tags/tags';
interface StyleParameters {
type: string;
isSelected: boolean;
}
getAllPoiTypes().forEach((type) => {
if (!Object.keys(osmIcons).includes(type)) {
console.warn({ caller: 'styles', message: 'missing icon', type });
}
});
const icons = {
note: {
src: noteIcon,
scale: 1 / 20,
opacity: 0.9,
anchor: [0.5, 1],
},
house: {
src: houseIcon,
scale: 1 / 15,
@ -116,16 +115,6 @@ const textFillSel = new Fill({
color: 'red',
});
const trksegStroke = new Stroke({
color: [11, 16, 71, 0.8],
width: 3,
});
const trksegStrokeSel = new Stroke({
color: 'red',
width: 3,
});
const rteStroke = new Stroke({
color: [18, 71, 11, 0.8],
width: 3,
@ -177,21 +166,31 @@ const memoizeOptions = {
const styles = {
wpt: {
getParameters: (feature: Feature) => {
const minZoom = feature.get('extensions')?.['dyo:minZoom'];
if (!mustBeDrawn(feature)) return null;
const extensions = feature.get('extensions');
const minZoom = extensions?.['dyo:minZoom'];
const category = extensions?.category;
return {
isSelected: feature.get('isSelected') ?? false,
text: feature.get('name'),
customIcon: icons[feature.get('sym') as keyof typeof icons],
customIcon:
icons[feature.get('sym') as keyof typeof icons] ||
icons[category as keyof typeof icons],
thumbnailUrl:
category === Category.PICTURE ? extensions?.thumbnailUrl : undefined,
hidden: minZoom && getZoominteger() < minZoom,
};
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'getStyle', params });
const { isSelected, text, customIcon, hidden } = params;
// console.log({ caller: 'getStyle', params });
const { isSelected, text, customIcon, hidden, thumbnailUrl } = params;
if (hidden) {
return null;
}
const icon = customIcon ?? wptIconObj;
const thumbnailIcon = !!thumbnailUrl
? { src: thumbnailUrl, scale: 1 / 2, anchor: [0.5, 0.5] }
: undefined;
const icon = customIcon ?? thumbnailIcon ?? wptIconObj;
return new Style({
image: new Icon(icon),
text: new Text({
@ -206,18 +205,50 @@ const styles = {
},
trkseg: {
getParameters: (feature: Feature) => {
if (!mustBeDrawn(feature)) return null;
return {
isSelected: feature.get('isSelected') ?? false,
feature: getZoomInteger() >= 7 ? feature : undefined,
zoom: getZoomInteger() >= 7 ? Math.floor(getZoomInteger()) : undefined,
};
},
ownStyles: {
normal: [
new Style({
stroke: new Stroke({
color: [44, 64, 255, 0.8],
width: 2,
}),
}),
new Style({
stroke: new Stroke({
color: [44, 64, 255, 0.2],
width: 7,
}),
}),
],
selected: [
new Style({
stroke: new Stroke({
color: [44, 64, 255, 0.8],
width: 2,
}),
}),
new Style({
stroke: new Stroke({
color: [255, 0, 0, 0.4],
width: 7,
}),
}),
],
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'getStyle', params });
const { isSelected, feature, zoom } = params;
const styles = [
new Style({ stroke: isSelected ? trksegStrokeSel : trksegStroke }),
];
let currentStyles: any = isSelected
? styles.trkseg.ownStyles.selected
: styles.trkseg.ownStyles.normal;
if (feature) {
const map = getMap();
const geometry = feature.getGeometry();
@ -237,7 +268,7 @@ const styles = {
const dx = end[0] - start[0];
const dy = end[1] - start[1];
const rotation = Math.atan2(dy, dx) - Math.PI / 2;
styles.push(
currentStyles.push(
new Style({
geometry: new Point(end),
image: new Icon({
@ -254,11 +285,38 @@ const styles = {
}
});
}
return styles;
return currentStyles;
}, memoizeOptions),
},
'trkseg-finish': {
getParameters: (feature: Feature) => {
if (!mustBeDrawn(feature)) return null;
const positions: Set<string> = feature.get('positions');
const tags: any = feature.get('tags') || {};
return {
isLast: positions.has('gpx-end') && positions.has('trk-end'),
locomotion: getTagValue(tags, 'locomotion') || 'hiking',
};
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'getStyle', params });
const { isLast, locomotion } = params;
if (isLast) {
return new Style({
image: new Icon({
src: locomotion === 'cycling' ? cycleIcon : hikerIcon,
scale: 1 / 20,
opacity: 0.9,
anchor: [0.5, 0.5],
}),
});
}
return null;
}, memoizeOptions),
},
rte: {
getParameters: (feature: Feature) => {
if (!mustBeDrawn(feature)) return null;
return {
isSelected: feature.get('isSelected') ?? false,
};
@ -517,8 +575,8 @@ const styles = {
if (getZoomInteger() < 16) {
return null;
}
const highlightedTagValue = getHighlightedTagValue(feature);
const isHighlightedFeature = !!highlightedTagValue;
const tagType = getTagType(feature);
const isHighlightedFeature = isHighlightedTagType(tagType);
if (
(isHighlightedFeature && getZoomInteger() < 16) ||
(!isHighlightedFeature && getZoomInteger() < 18)
@ -527,9 +585,7 @@ const styles = {
}
return {
name: feature.get('name'),
poiType: isHighlightedFeature
? highlightedTagValue
: getTagValue(feature),
poiType: tagType,
isHighlighted: isHighlightedFeature,
isTextHidden: getZoomInteger() < 19,
};

View File

@ -4,11 +4,11 @@ import CloudUploadIcon from '@suid/icons-material/CloudUpload';
// @ts-ignore
import css from './GpxImport.module.css';
import css from './Import.module.css';
import Dialog from '../dialog';
import { useI18n } from '@solid-primitives/i18n';
import { Box } from '@suid/material';
import GpxImportSingleFile from './GpxImportSingleFile';
import ImportSingleFile from './ImportSingleFile';
const [filesToImport, setFilesToImport] = createSignal<FileList | string[]>();
@ -38,6 +38,11 @@ const GpxImport: Component = () => {
}
};
const accept =
window.Capacitor.platform === 'android'
? ''
: '.gpx,.jpg,image/jpeg,application/gpx+xml';
return (
<>
<div class={css.container}>
@ -48,7 +53,7 @@ const GpxImport: Component = () => {
type='file'
id='gpx-import'
class={css.inputFile}
accept='.gpx'
accept={accept}
multiple={true}
onChange={onChangeHandler}
/>
@ -65,7 +70,7 @@ const GpxImport: Component = () => {
}}
>
<For each={filesToImport()}>
{(gpxFile) => <GpxImportSingleFile gpxFile={gpxFile} />}
{(file) => <ImportSingleFile file={file} />}
</For>
</Box>
</Dialog>

View File

@ -0,0 +1,355 @@
import { useI18n } from '@solid-primitives/i18n';
import {
Typography,
Card,
CardContent,
CardActions,
Button,
Box,
LinearProgress,
CircularProgress,
} from '@suid/material';
import { Component, createEffect, createSignal, Show } from 'solid-js';
import { findStartTime } from '../../lib/gpx';
import GPX from '../../lib/gpx-parser-builder/src/gpx';
import dispatch from '../../workers/dispatcher-main';
import GpxChooser from '../gpx-chooser';
import { currentGpxId } from '../gpx-dialog';
import {
Filesystem as CapacitorFileSystem,
Encoding,
} from '@capacitor/filesystem';
import piexif from 'piexifjs';
import { getDate, getGps } from '../../lib/exif';
import { downsize } from '../../lib/image';
import { Coordinate } from 'ol/coordinate';
import WptEditDialog, { Category } from '../wpt/WptEditDialog';
interface Props {
file: File;
}
interface StatsAndGpx {
gpx: Gpx;
stats: any;
}
interface Picture {
id: string;
date: string;
gpx: { Latitude: number; Longitude: number; Altitude: number };
thumbnailUrl: string;
}
const analyzeGpx = (gpx: Gpx | undefined) => {
if (gpx === undefined) {
return {};
}
const stats = {
creator: gpx.$.creator,
nbWpts: gpx.wpt ? gpx.wpt?.length : 0,
nbRtes: gpx.rte ? gpx.rte?.length : 0,
nbTrks: gpx.trk ? gpx.trk?.length : 0,
trkMaybeRte:
gpx.trk &&
gpx.trk[0].trkseg &&
gpx.trk[0].trkseg[0] &&
gpx.trk[0].trkseg[0].trkpt &&
!gpx.trk[0].trkseg[0].trkpt[0].time,
startTime: findStartTime(gpx),
};
return stats;
};
const ImportSingleFile: Component<Props> = ({ file: file }) => {
const [t] = useI18n();
const [statsAndGpx, setStatsAndGpx] = createSignal<StatsAndGpx>();
const [picture, setPicture] = createSignal<Picture>();
const [state, setState] = createSignal('init');
const [gpxId, setGpxId] = createSignal<string>('new');
const [open, setOpen] = createSignal<boolean>(false);
const [coordinate, setCoordinate] = createSignal<Coordinate>();
const [initialWpt, setInitialWpt] = createSignal({
$: { lat: 0, lon: 0 },
ele: undefined,
time: undefined,
magvar: undefined,
geoidheight: undefined,
name: undefined,
cmt: undefined,
desc: undefined,
src: undefined,
link: undefined,
sym: undefined,
type: undefined,
fix: undefined,
sat: undefined,
hdop: undefined,
vdop: undefined,
pdop: undefined,
ageofdgpsdata: undefined,
dgpsid: undefined,
extensions: {
address: undefined,
startTime: undefined,
endTime: undefined,
category: Category.PICTURE,
subCategory: undefined,
pictureId: '',
thumbnailUrl: '',
},
});
createEffect(() => {
setGpxId(currentGpxId());
});
const parseGpx = (content: string) => {
const gpx = GPX.parse(content);
console.log({
caller: 'ImportSingleFile / JSON',
gpxFile: file,
gpx,
gpxId: gpxId(),
});
setStatsAndGpx({ gpx, stats: analyzeGpx(gpx) });
};
if (typeof file === 'string') {
CapacitorFileSystem.requestPermissions().then((permissionStatus) => {
console.log({
caller: 'ImportSingleFile / content',
permissionStatus,
});
});
CapacitorFileSystem.readFile({
path: file,
encoding: Encoding.UTF8,
}).then((content) => {
console.log({
caller: 'ImportSingleFile / content',
file,
content,
});
parseGpx(content.data);
});
} else {
const reader = new FileReader();
if (file.type === 'image/jpeg') {
reader.readAsDataURL(file);
reader.addEventListener(
'load',
async () => {
const imageUrl = reader.result;
const exifObj = piexif.load(imageUrl);
console.log({
caller: 'ImportSingleFile / Jpeg',
file,
type: file.type,
result: reader.result,
exifObj,
});
const id = exifObj.Exif[piexif.ExifIFD.ImageUniqueID];
const gps = getGps(exifObj);
const date = getDate(exifObj);
const [downsizedUrl, bigThumbnailUrl, thumbnailUrl] = await downsize(
reader.result,
[1024, 512, 128]
);
console.log({
caller: 'ImportSingleFile / Jpeg',
file,
id,
gps,
date,
type: file.type,
result: reader.result,
exifObj,
});
setPicture({
id,
gps,
date,
thumbnailUrl,
bigThumbnailUrl,
downsizedUrl,
});
setCoordinate([gps.longitude, gps.latitude]);
setInitialWpt({
...initialWpt(),
extensions: {
...initialWpt().extensions,
category: Category.PICTURE,
startTime: date.toISOString(),
endTime: date.toISOString(),
pictureId: id,
thumbnailUrl: thumbnailUrl,
},
});
},
false
);
} else {
// GPX
reader.readAsText(file);
reader.addEventListener(
'load',
async () => {
// this will then display a text gpxfile
console.log({
caller: 'ImportSingleFile / XML',
file,
type: file.type,
result: reader.result,
});
parseGpx(reader.result);
},
false
);
}
}
const doImport = async (forceImportAsRoutes: boolean = false) => {
setState('importing');
// console.log({ caller: 'GpxImport / JSON', file, gpx });
// if (gpx) {
// const startTime = new Date(findStartTime(gpx)!);
await dispatch({
action: 'pruneAndSaveImportedGpx',
params: {
id: gpxId(),
forceImportAsRoutes,
gpx: statsAndGpx()?.gpx,
tech:
typeof file === 'string'
? {
importDate: new Date().toISOString(),
uri: file,
}
: {
lastModified: new Date(file.lastModified).toISOString(),
importDate: new Date().toISOString(),
name: file.name,
size: file.size,
type: file.type,
},
},
});
console.log({
caller: 'GpxImport / JSON / done',
gpxFile: file,
gpx: statsAndGpx()?.gpx,
});
setState('done');
// } else {
// console.error({
// message: "can't parse GPX file",
// file,
// xml: fileReader.result,
// });
// }
// // TODO: error handling
// },
// false
// );
// }
};
const [selectedTrkTransform, setSelectedTrkTransform] = createSignal(
'importNonTimedTrksAsRtes'
);
const handleTrkTransformChange = (event: any) => {
setSelectedTrkTransform(event.target.value);
};
const controlTrkTransformProps = (item: string) => ({
checked: selectedTrkTransform() === item,
onChange: handleTrkTransformChange,
value: item,
name: 'trkTransform',
label: t(item),
inputProps: { 'aria-label': item },
});
return (
<Card raised>
<CardContent>
<Typography variant='h6'>
{t('file')}
{file.name}
</Typography>
</CardContent>
<CardContent>
<Show when={statsAndGpx() !== undefined}>
<Typography variant='body1'>
{t('gpxStats', statsAndGpx().stats)}{' '}
{statsAndGpx()?.stats.startTime
? t('gpxStartTime', statsAndGpx().stats)
: t('gpxNoStartTime')}
</Typography>
<Show when={statsAndGpx().stats.trkMaybeRte}>
<Typography variant='body1'>{t('trkMaybeRte')}</Typography>
</Show>
<Show when={state() === 'importing'}>
<LinearProgress />
</Show>
<CardActions>
<GpxChooser
gpxId={gpxId}
setGpxId={setGpxId}
disabled={state() != 'init'}
/>
<Button
variant='contained'
disabled={state() != 'init'}
onClick={() => doImport(false)}
>
{t('import')}
</Button>
<Button
variant='contained'
disabled={state() != 'init'}
onClick={() => doImport(true)}
>
{t('importAllTrksAsRtes')}
</Button>
</CardActions>
</Show>
<Show when={picture() !== undefined}>
<img src={picture()?.bigThumbnailUrl} />
<p>Id: {picture()?.id}</p>
<p>Date: {picture()?.date.toString()}</p>
<p>
Coordinates: {picture()?.gps.latitude}, {picture()?.gps.longitude}
</p>
<CardActions>
<Button
variant='contained'
disabled={state() != 'init'}
onClick={() => setOpen(true)}
>
{t('import')}
</Button>
</CardActions>
<Show when={open()}>
<WptEditDialog
open={open}
closeHandler={() => {
setOpen(false);
setState('imported');
}}
coordinate={coordinate}
initialWpt={initialWpt}
imageUrl={picture()?.downsizedUrl}
/>
</Show>
</Show>
</CardContent>
</Card>
);
};
export default ImportSingleFile;

View File

@ -0,0 +1 @@
export { default, importUrls } from './Import';

View File

@ -13,14 +13,11 @@ import Dialog from '../dialog';
import Tree from '../tree';
import { GpxViewer } from '../gpx';
import { Browser } from '@capacitor/browser';
import { isHighlighted } from '../map-tile-provider';
import {
getHighlightedTagValue,
getTagValue,
} from '../map-tile-provider/MapTileProvider';
import { isHighlightedTagType } from '../map-tile-provider/MapTileProvider';
import style from '../gpx/styles';
import OsmFindAll from './OsmFindAll';
import { toLonLat } from 'ol/proj';
import { getTagType } from '../overlays/overlay-definitions';
const Item = styled(Paper)(({ theme }) => ({
...theme.typography.body2,
@ -216,10 +213,11 @@ const Infos: Component<{}> = (props) => {
<>
{console.log({
caller: 'Infos / vector layer feature',
highlightedTagValue:
getHighlightedTagValue(feature),
isHighlighted: isHighlighted(feature),
tagValue: getTagValue(feature),
isHighlighted: isHighlightedTagType(
getTagType(feature)
),
tagValue: getTagType(feature),
properties: feature.getProperties(),
style: style(feature),
})}

View File

@ -0,0 +1,247 @@
import {
Alert,
Box,
Button,
Modal,
TextField,
Typography,
} from '@suid/material';
import { Component, createEffect, createSignal, Show } from 'solid-js';
import { parseUserId } from '../../lib/user-id';
import dispatch from '../../workers/dispatcher-main';
import Dialog from '../dialog';
interface props {}
const [invitation, setInvitation] = createSignal<any>(false);
const fetchInvitation = () => {
fetch(invitation().url)
.then((response) => response.json())
.then((data) => {
setInvitation({ ...invitation(), data });
return invitation();
})
.then(() => {
dispatch({
action: 'getAccount',
params: { id: invitation().data.id },
}).then((account) => {
console.log({ caller: 'Invitation / fetchInvitation', account });
setInvitation({ ...invitation(), existing: true });
});
})
.catch((error) => {
console.error({ caller: 'Invitation / fetchInvitation', error });
});
};
export const openInvitation = (payload: string) => {
try {
const decoded = atob(payload);
const url = new URL(decoded);
setInvitation({ url });
fetchInvitation();
} catch {
console.warn({
caller: 'Invitation / searchInvitationInIntent',
payload,
message: 'Query is not a base64 encoded URL',
});
}
return true;
};
export const searchInvitation = () => {
const hash = location.hash;
console.log({ caller: 'Invitation / searchInvitation', hash });
if (hash.length > 1) {
try {
const payload = hash.slice(1);
const decoded = atob(payload);
const url = new URL(decoded);
setInvitation({ url });
fetchInvitation();
} catch {
console.warn({
caller: 'Invitation / searchInvitation',
hash,
message: 'Hash is not a base64 encoded URL',
});
}
}
};
const Invitation: Component<props> = (props) => {
createEffect(() => {
console.log({
caller: 'Invitation / createEffect',
invitation: invitation(),
});
});
const closeHandler = () => {};
const submitHandler = async () => {
try {
const response = await fetch(
`${invitation().url.href}/${invitation().code}`
);
const codeData = await response.json();
setInvitation({
...invitation(),
codeData,
failure: codeData.response !== 'OK',
success: codeData.response === 'OK',
});
const user = invitation().codeData.user;
const id = user._id;
const account = {
id,
localDb: id,
name: id,
remoteDbServer: user.database,
remoteDbUser: user.username,
remoteDbPassword: user.password,
mail: user.mail,
};
dispatch({ action: 'putAccount', params: { id, account } });
const settings: any = await dispatch({ action: 'getSettings' });
dispatch({
action: 'putSettings',
params: { settings: { ...settings, currentAccountId: id } },
});
} catch (error) {
setInvitation({
...invitation(),
failure: true,
});
}
};
const codeChangeHandler = (event: any) => {
setInvitation({ ...invitation(), code: event.target.value });
};
const handleModalFailureClose = () => {
setInvitation({ ...invitation(), failure: undefined, existing: undefined });
};
const handleCloseSuccess = () => {
setInvitation(false);
location.reload();
};
return (
<Show when={!!invitation() && !!invitation().data}>
<Dialog
open={!!invitation() && !!invitation().data}
fullScreen={false}
closeHandler={closeHandler}
title='Invitation'
>
<Box
component='form'
sx={{
width: '100%',
'& .MuiTextField-root': { m: 1, width: '100%' },
paddingTop: '5px',
}}
noValidate
autoComplete='off'
>
<p>
Pour configurer cette application en tant que "
{invitation().data.id}
", copier le code qui vous a été envoyé par mail à l'adresse "
{invitation().data.mail}" :{' '}
</p>
<TextField
required
label='Code'
type='number'
onChange={codeChangeHandler}
/>
<Button variant='contained' onClick={submitHandler}>
OK
</Button>
<Button variant='outlined' onClick={fetchInvitation}>
Renvoyer le code
</Button>
<Button variant='outlined' color='error' onClick={handleCloseSuccess}>
Annuler
</Button>
</Box>
</Dialog>
<Modal
open={!!invitation().failure}
onClose={handleModalFailureClose}
aria-labelledby='modal-modal-title'
aria-describedby='modal-modal-description'
>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
border: '2px solid #000',
boxShadow: '24px',
p: 4,
}}
>
<Alert severity='error'>Le code est erroné !</Alert>
</Box>
</Modal>
<Modal
open={!!invitation().success}
onClose={handleCloseSuccess}
aria-labelledby='modal-modal-title'
aria-describedby='modal-modal-description'
>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
border: '2px solid #000',
boxShadow: '24px',
p: 4,
}}
>
<Alert severity='success'>C'est tout bon !</Alert>
</Box>
</Modal>
<Modal
open={!!invitation().existing}
onClose={handleModalFailureClose}
aria-labelledby='modal-modal-title'
aria-describedby='modal-modal-description'
>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
border: '2px solid #000',
boxShadow: '24px',
p: 4,
}}
>
<Alert severity='info'>
Ce compte est déjà configuré, vous pouvez soit continuer et le
reconfigurer soit abandonner cette action et ne pas tenir compte du
message qui vous a é envoyé.
</Alert>
</Box>
</Modal>
</Show>
);
};
export default Invitation;

View File

@ -0,0 +1 @@
export { default, searchInvitation } from './Invitation';

View File

@ -1,15 +1,10 @@
import OSM from 'ol/source/OSM';
import XYZ from 'ol/source/XYZ';
import { Component, createEffect, createSignal, For, Show } from 'solid-js';
import {
I18nContext,
createI18nContext,
useI18n,
} from '@solid-primitives/i18n';
import { useI18n } from '@solid-primitives/i18n';
import style from './MapTileProvider.module.css';
import LayersIcon from '@suid/icons-material/Layers';
import CloseIcon from '@suid/icons-material/Close';
import {
FormControlLabel,
IconButton,
@ -25,9 +20,13 @@ import getUri from '../../lib/ids';
import { Feature } from 'ol';
import {
overlayCategories,
overlayDefinitions,
osmTags,
OsmTag,
getTagType,
} from '../overlays/overlay-definitions';
import { cloneDeep } from 'lodash';
import DrawingSelector from '../drawing-selector/DrawingSelector';
const id = getUri('overlays', undefined);
@ -113,75 +112,17 @@ type Overlay = {
};
type Overlays = Record<string, Overlay>;
const defaultOverlays: Overlays = {
none: { selected: true, highlighted: { none: [] }, hidden: {} },
hiking: {
selected: false,
highlighted: {
none: [],
},
hidden: { none: [] },
const defaultOverlayContent = {
selected: false,
highlighted: {
none: [],
},
hidden: { none: [] },
};
// type OverlayDefinition = Record<string, FeatureTypes>;
// type OverlayDefinitions = Record<string, OverlayDefinition>;
// export const overlayDefinitions: OverlayDefinitions = {
// none: {},
// hiking: {
// none: {},
// sleeping: {
// tourism: [
// 'hotel',
// 'alpine_hut',
// 'apartment',
// 'camp_site',
// 'chalet',
// 'guest_house',
// 'hostel',
// 'motel',
// 'wilderness_hut',
// ],
// },
// drinking: {
// amenity: ['bar', 'cafe', 'pub', 'drinking_water', 'water_point'],
// natural: ['spring'],
// },
// eating: {
// amenity: ['fast_food', 'pub', 'restaurant'],
// shop: [
// 'bakery',
// 'butcher',
// 'cheese',
// 'chocolate',
// 'convenience',
// 'dairy',
// 'farm',
// 'greengrocer',
// 'health_food',
// 'pastry',
// 'seafood',
// 'department_store',
// 'supermarket',
// ],
// },
// health: {
// amenity: ['doctors', 'hospital', 'pharmacy'],
// },
// security: {
// amenity: ['police', 'fire_station'],
// },
// dayToday: {
// amenity: ['waste_basket', 'waste_disposal'],
// shop: ['laundry'],
// },
// naturalSites: {
// tourism: ['viewpoint'],
// natural: '*',
// },
// },
// };
const defaultOverlays: Overlays = {
none: { selected: true, highlighted: { none: [] }, hidden: {} },
};
const getOverlays = createCachedSignal({
id,
@ -197,153 +138,24 @@ const currentOverlayKey = () =>
const currentOverlay = () =>
getOverlays() ? getOverlays()[currentOverlayKey()] : {};
const overlayCategoriesPlusNone = { none: [], ...overlayCategories };
const overlayDefinitionsPlusNone = { none: {}, ...overlayDefinitions };
export const currentCategory = () =>
currentOverlayKey() === 'none'
? []
: ['none', ...overlayCategoriesPlusNone[currentOverlayKey()]];
Object.keys(
currentOverlayKey() === 'none'
? {}
: { none: [], ...overlayDefinitionsPlusNone[currentOverlayKey()] }
);
const currentOverlayHighlightedKey = () =>
currentOverlay() && currentOverlay().highlighted
? currentOverlay().highlighted
: 'none';
export const currentOverlayHighlightedDefinition = () =>
currentCategory()[currentOverlayHighlightedKey()];
export const getAllPoiTypes = () => {
let result = new Set();
Object.keys(overlayDefinitions).forEach((tagName) => {
const tag = overlayDefinitions[tagName];
result = new Set([...result, ...Object.keys(tag)]);
});
return [...result];
};
export const highlightedTags = () => {
let result = {};
Object.keys(overlayDefinitions).forEach((tagName) => {
let tagValues = [];
const tag = overlayDefinitions[tagName];
Object.keys(tag).forEach((tagValue) => {
const catDef = tag[tagValue];
Object.keys(catDef).forEach((catName) => {
if (catName === currentOverlayKey()) {
const catValue = catDef[catName];
if (catValue[currentOverlay()?.highlighted]) {
tagValues = [...tagValues, tagValue];
}
}
});
});
if (tagValues.length > 0) {
result[tagName] = tagValues;
}
});
// console.log({
// caller: 'MapTileProviders / highlightedTags',
// result,
// currentOverlayKey: currentOverlayKey(),
// currentOverlay: currentOverlay(),
// });
return result;
};
// createEffect(() => {
// highlightedTags = {};
// Object.keys(overlayDefinitions).forEach((tagName) => {
// let tagValues = [];
// const tag = overlayDefinitions[tagName];
// Object.keys(tag).forEach((tagValue) => {
// const catDef = tag[tagValue];
// Object.keys(catDef).forEach((catName) => {
// if (catName === currentOverlayKey()) {
// const catValue = catDef[catName];
// if (catValue[currentOverlay()?.highlighted]) {
// tagValues = [...tagValues, tagValue];
// }
// }
// });
// });
// if (tagValues.length > 0) {
// highlightedTags[tagName] = tagValues;
// }
// });
// console.log({
// caller: 'MapTileProviders / createEffect',
// highlightedTags,
// currentOverlayKey: currentOverlayKey(),
// currentOverlay: currentOverlay(),
// });
// });
export const getHighlightedTagValue = (feature: Feature) => {
let result = false;
Object.keys(highlightedTags()).every((tagName) => {
const value = feature.get(tagName);
const highlightedValues = highlightedTags()[tagName];
// console.log({
// caller: 'MapTileProviders / highlightedTag / found',
// feature,
// feature_values: feature.values_,
// highlightedTags,
// tagName,
// tag_value: value,
// highlightedValues,
// });
if (value !== undefined && highlightedValues.includes(value)) {
result = value;
return false;
}
return true;
});
// console.log({
// caller: 'MapTileProviders / highlightedTag / result',
// feature,
// feature_values: feature.values_,
// highlightedTags,
// result,
// });
return result;
};
export const isHighlighted = (feature: Feature) => {
return !!getHighlightedTagValue(feature);
};
export const getTagValue = (feature: Feature) => {
let result = false;
Object.keys(overlayDefinitions).every((tagName) => {
const value = feature.get(tagName);
const tagValues = overlayDefinitions[tagName];
if (value !== undefined && Object.keys(tagValues).includes(value)) {
// console.log({
// caller: 'MapTileProviders / tagValue / found',
// feature,
// feature_values: feature.values_,
// highlightedTags,
// tagName,
// tag_value: value,
// highlightedValues,
// });
result = value;
return false;
}
return true;
});
// console.log({
// caller: 'MapTileProviders / isHighlighted / false',
// feature,
// feature_values: feature.values_,
// highlightedTags,
// });
return result;
export const isHighlightedTagType = (tagType: string) => {
const currentOverlayHighlightedDefinition: string[] =
overlayDefinitions[currentOverlayKey()][currentOverlayHighlightedKey()];
return currentOverlayHighlightedDefinition.includes(tagType);
};
const MapTilesProvider: Component<{}> = (props) => {
@ -380,6 +192,14 @@ const MapTilesProvider: Component<{}> = (props) => {
});
});
const getOverlaysAddingSelectedIfMissing = (key: string) => {
const overlays = getOverlays();
if (!Object.keys(overlays).includes(key)) {
overlays[key] = cloneDeep(defaultOverlayContent);
}
return overlays;
};
const handleOverlayChange = (ev: any) => {
const value = ev.target.value;
console.log({
@ -387,7 +207,7 @@ const MapTilesProvider: Component<{}> = (props) => {
ev,
value,
});
const newOverlays = getOverlays();
const newOverlays = getOverlaysAddingSelectedIfMissing(value);
Object.keys(newOverlays).forEach((key) => {
newOverlays[key].selected = key === value;
});
@ -424,6 +244,7 @@ const MapTilesProvider: Component<{}> = (props) => {
open={open()}
title={t('chooseYourMap')}
>
<DrawingSelector/>
<Tree
title={t('overlay')}
content={
@ -432,7 +253,7 @@ const MapTilesProvider: Component<{}> = (props) => {
defaultValue={currentOverlayKey()}
onChange={handleOverlayChange}
>
<For each={Object.keys(overlayCategoriesPlusNone)}>
<For each={Object.keys(overlayDefinitionsPlusNone)}>
{(p: string) => (
<FormControlLabel value={p} control={<Radio />} label={p} />
)}

View File

@ -2,6 +2,5 @@ export {
default,
mapTileProviders,
currentCategory as currentOverlayDefinition,
currentOverlayHighlightedDefinition,
isHighlighted,
isHighlightedTagType,
} from './MapTileProvider';

View File

@ -1,5 +1,5 @@
import { Component, createEffect, createSignal, onMount } from 'solid-js';
import { useParams, useNavigate, useLocation } from '@solidjs/router';
import { useParams, useNavigate } from '@solidjs/router';
import OlMap from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
@ -10,22 +10,22 @@ import Attribution from 'ol/control/Attribution';
import Rotate from 'ol/control/Rotate';
import ScaleLine from 'ol/control/ScaleLine';
import Control from 'ol/control/Control';
import Zoom from 'ol/control/Zoom';
import { fromLonLat, toLonLat } from 'ol/proj';
import DragRotate from 'ol/interaction/DragRotate';
import 'ol/ol.css';
import './Map.css';
import { Collection, Overlay } from 'ol';
import { Collection } from 'ol';
import { Point } from 'ol/geom';
import { Style, Icon } from 'ol/style';
import GetLocation, { getCurrentLocation } from '../get-location';
import ShowLocationIcon from '../get-location/ShowLocationIcon.svg';
import { Back, Forward } from '../back-forward';
import GpxImport, { importUrls } from '../gpx-import';
import GpxImport, { importUrls } from '../import';
import AllGpxes from '../all-gpxes';
import MapTileProvider, { mapTileProviders } from '../map-tile-provider';
import Interaction from 'ol/interaction/Interaction';
import DoubleClickZoom from 'ol/interaction/DoubleClickZoom';
import DragPan from 'ol/interaction/DragPan';
import PinchRotate from 'ol/interaction/PinchRotate';
import PinchZoom from 'ol/interaction/PinchZoom';
@ -40,9 +40,13 @@ import dispatch from '../../workers/dispatcher-main';
import { debounce } from 'lodash';
import { AndroidFullScreen } from '@awesome-cordova-plugins/android-full-screen';
import Account from '../account';
import { Overlays } from '../overlays/Overlays';
import Finder, { findLocation } from '../finder';
import Note from '../note';
import Invitation, { searchInvitation } from '../invitation';
import Updater from '../updater';
import SystemDrawer from '../system-drawer';
import { receiveIntent } from '../../lib/intent-receivers';
const [getState, setState] = createSignal({
lon: 0,
@ -60,15 +64,11 @@ const [getMap, setMap] = createSignal<OlMap | null>(null);
export { getMap };
const useHash = () => useLocation().hash;
const Map: Component = () => {
const navigate = useNavigate();
const params = useParams();
createEffect(() => {
console.log({ caller: 'Map / createEffect', hash: useHash() });
});
searchInvitation();
// See https://stackoverflow.com/questions/71288670/how-to-make-fullscreen-ionic-capacitor-app
AndroidFullScreen.isImmersiveModeSupported()
@ -92,15 +92,8 @@ const Map: Component = () => {
);
window.plugins.intentShim.onIntent(function (intent: any) {
console.log({ caller: 'Intent receiver', intent });
if (intent.action === 'android.intent.action.VIEW') {
const url = new URL(intent.data);
const q = url.search;
const [, lat, lon] = q.match(/q=([0-9.-]+),([0-9.-]+)/);
console.log({ caller: 'Intent receiver', intent, url, lat, lon });
findLocation(navigate, [lon, lat]);
} else if (intent.action === 'android.intent.action.SEND') {
const uri = intent.extras['android.intent.extra.STREAM'];
importUrls([uri]);
if (receiveIntent(intent, navigate)) {
return;
}
});
} else {
@ -111,6 +104,33 @@ const Map: Component = () => {
});
}
const dropHandler = (event: any) => {
event.preventDefault();
console.log({
caller: 'Map / dropHandler',
event,
files: event.dataTransfer.files,
});
importUrls(event.dataTransfer.files);
};
const dragEnterHandler = (event: any) => {
event.preventDefault();
console.log({ caller: 'Map / dragEnterHandler', event });
};
const dragOverHandler = (event: any) => {
event.preventDefault();
console.log({ caller: 'Map / dragOverHandler', event });
};
// const dragStartHandler = (event: any) => {
// event.preventDefault();
// event.dataTransfer.effectAllowed = 'all';
// event.dataTransfer.dropEffect = 'move';
// console.log({ caller: 'Map / dragStartHandler', event });
// };
if (
params.lat === '0' &&
params.lon === '0' &&
@ -141,6 +161,7 @@ const Map: Component = () => {
params: {
...params,
},
lastCommit: import.meta.env.VITE_GIT_COMMIT_HASH,
});
setState({
provider: params.provider,
@ -252,6 +273,16 @@ const Map: Component = () => {
// vectorTile: clusterableVectorTileSource.getProjection(),
// });
let controls = [
new Attribution({ collapsible: true }),
new Rotate(),
new ScaleLine({ bar: true }),
];
if (window.Capacitor.platform === 'web') {
controls.push(new Zoom());
}
const olMap = new OlMap({
view: new View({
center: fromLonLat([+getState().lon, +getState().lat]),
@ -260,15 +291,11 @@ const Map: Component = () => {
}),
layers: [tileLayer, vectorLayer],
target: target,
controls: new Collection<Control>([
new Attribution({ collapsible: true }),
new Rotate(),
new ScaleLine({ bar: true }),
]),
controls: new Collection<Control>(controls),
moveTolerance: 10,
interactions: new Collection<Interaction>([
new DragRotate(),
new DoubleClickZoom(),
// new DoubleClickZoom(),
new DragPan(),
new PinchRotate(),
new PinchZoom(),
@ -279,7 +306,7 @@ const Map: Component = () => {
]),
});
olMap.on(['moveend'], changeListener);
olMap.on(['singleclick'], clickHandler);
olMap.on(['dblclick'], clickHandler);
setMap(olMap);
});
@ -287,17 +314,28 @@ const Map: Component = () => {
return (
//<OsmFetch map={getMap} />
// @ts-ignore
<div class='ol-map' ref={target}>
<div
class='ol-map'
ref={target}
ondrop={dropHandler}
ondragover={dragOverHandler}
ondragenter={dragEnterHandler}
>
<Updater />
<Invitation />
<Overlays map={getMap} />
<Note />
<Finder />
<GetLocation />
<Forward />
<Back />
<GpxRecord />
<Show when={window.Capacitor.platform !== 'web'}>
<Forward />
<Back />
<GpxRecord />
</Show>
<GpxImport />
<MapTileProvider />
<GpxDialog />
<Account />
<SystemDrawer />
<AllGpxes map={getMap} />
<Infos />
</div>

View File

@ -0,0 +1,15 @@
.control {
opacity: 1;
position: fixed !important;
top: 0px;
margin-left: calc(100% - 260px) !important;
z-index: 1;
}
.control_web {
opacity: 1;
position: fixed !important;
top: 0px;
margin-left: calc(100% - 220px) !important;
z-index: 1;
}

View File

@ -0,0 +1,81 @@
import { IconButton } from '@suid/material';
import { Component, createSignal, Show } from 'solid-js';
import { Geolocation } from '@awesome-cordova-plugins/geolocation';
import NoteIcon from '@suid/icons-material/Note';
import style from './Note.module.css';
import WptEditDialog, { Category } from '../wpt/WptEditDialog';
import { Coordinate } from 'ol/coordinate';
interface Props {}
const Note: Component<Props> = (props) => {
const [open, setOpen] = createSignal<boolean>(false);
const [coordinate, setCoordinate] = createSignal<Coordinate>();
const openWptEditDialogWithCurrentLocation = async () => {
const position = await Geolocation.getCurrentPosition();
setCoordinate([position.coords.longitude, position.coords.latitude]);
setOpen(true);
};
const initialWpt = () => {
const time = new Date().toISOString();
return {
$: { lat: 0, lon: 0 },
ele: undefined,
time: undefined,
magvar: undefined,
geoidheight: undefined,
name: undefined,
cmt: undefined,
desc: undefined,
src: undefined,
link: undefined,
sym: undefined,
type: undefined,
fix: undefined,
sat: undefined,
hdop: undefined,
vdop: undefined,
pdop: undefined,
ageofdgpsdata: undefined,
dgpsid: undefined,
extensions: {
address: undefined,
startTime: time,
endTime: time,
category: Category.NOTE,
subCategory: undefined,
},
};
};
return (
<>
<div
class={
window.Capacitor.platform === 'web'
? style.control_web
: style.control
}
>
{' '}
<IconButton onClick={openWptEditDialogWithCurrentLocation}>
<NoteIcon />
</IconButton>
</div>
<Show when={open()}>
<WptEditDialog
open={open}
closeHandler={() => setOpen(false)}
coordinate={coordinate}
initialWpt={initialWpt}
/>
</Show>
</>
);
};
export default Note;

View File

@ -0,0 +1 @@
export { default } from './Note';

View File

@ -3,25 +3,20 @@ import OlMap from 'ol/Map';
import {
currentOverlayDefinition,
currentOverlayHighlightedDefinition,
isHighlighted,
isHighlightedTagType,
} from '../map-tile-provider';
import { Feature } from 'ol';
import MVT from 'ol/format/MVT';
import { Point } from 'ol/geom';
import VectorLayer from 'ol/layer/Vector';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile.js';
import WMTSTileGrid from 'ol/tilegrid/WMTS.js';
import Cluster from 'ol/source/Cluster';
import { style } from '../gpx/styles';
import ClusterableVectorTileSourceProxy from '../../lib/ClusterableVectorTileSourceProxy';
import { getMap, getZoomInteger } from '../map/Map';
import { getCenter } from 'ol/extent';
import { Projection } from 'ol/proj';
import { getVectorTileFeatureType } from './overlay-definitions';
import { getTagType, getVectorTileFeatureType } from './overlay-definitions';
import GeoJSON from 'ol/format/GeoJSON.js';
import TopoJSON from 'ol/format/TopoJSON.js';
interface Props {
map: () => OlMap | null;
@ -144,7 +139,7 @@ export const Overlays: Component<Props> = ({ map }) => {
if (
getZoomInteger() < 16 &&
getVectorTileFeatureType(feature) === 'poi' &&
isHighlighted(feature)
isHighlightedTagType(getTagType(feature))
) {
return new Point(getCenter(feature.getGeometry().getExtent()));
}
@ -174,7 +169,6 @@ export const Overlays: Component<Props> = ({ map }) => {
createEffect(() => {
const overlayDefinition = currentOverlayDefinition();
const overlayHighlightedDefinition = currentOverlayHighlightedDefinition();
const olMap = getMap();
if (olMap) {
olMap.removeLayer(clusterLayer);

View File

@ -1 +1,6 @@
import { overlayDefinitions, overlayCategories } from './overlay-definitions';
import {
overlayDefinitions,
OsmTag,
osmTags,
getTagType,
} from './overlay-definitions';

View File

@ -1,104 +1,284 @@
import { indexOf } from 'lodash';
import { Feature } from 'ol';
export interface OsmTag {
name: string;
value: string;
}
export const osmTags = {
bar: { name: 'amenity', value: 'bar' },
fast_food: { name: 'amenity', value: 'fast_food' },
food_court: { name: 'amenity', value: 'food_court' },
pub: { name: 'amenity', value: 'pub' },
restaurant: { name: 'amenity', value: 'restaurant' },
cafe: { name: 'amenity', value: 'cafe' },
atm: { name: 'amenity', value: 'atm' },
bank: { name: 'amenity', value: 'bank' },
doctors: { name: 'amenity', value: 'doctors' },
hospital: { name: 'amenity', value: 'hospital' },
pharmacy: { name: 'amenity', value: 'pharmacy' },
police: { name: 'amenity', value: 'police' },
fire_station: { name: 'amenity', value: 'fire_station' },
drinking_water: { name: 'amenity', value: 'drinking_water' },
water_point: { name: 'amenity', value: 'water_point' },
waste_basket: { name: 'amenity', value: 'waste_basket' },
waste_disposal: { name: 'amenity', value: 'waste_disposal' },
vending_machine: { name: 'amenity', value: 'vending_machine' },
bicycle_parking: { name: 'amenity', value: 'bicycle_parking' },
parking: { name: 'amenity', value: 'parking' },
bakery: { name: 'shop', value: 'bakery' },
butcher: { name: 'shop', value: 'butcher' },
cheese: { name: 'shop', value: 'cheese' },
chocolate: { name: 'shop', value: 'chocolate' },
convenience: { name: 'shop', value: 'convenience' },
dairy: { name: 'shop', value: 'dairy' },
farm: { name: 'shop', value: 'farm' },
greengrocer: { name: 'shop', value: 'greengrocer' },
health_food: { name: 'shop', value: 'health_food' },
pasta: { name: 'shop', value: 'pasta' },
pastry: { name: 'shop', value: 'pastry' },
seafood: { name: 'shop', value: 'seafood' },
water: { name: 'shop', value: 'water' },
department_store: { name: 'shop', value: 'department_store' },
general: { name: 'shop', value: 'general' },
mall: { name: 'shop', value: 'mall' },
supermarket: { name: 'shop', value: 'supermarket' },
wholesale: { name: 'shop', value: 'wholesale' },
outdoor: { name: 'shop', value: 'outdoor' },
laundry: { name: 'shop', value: 'laundry' },
hotel: { name: 'tourism', value: 'hotel' },
alpine_hut: { name: 'tourism', value: 'alpine_hut' },
apartment: { name: 'tourism', value: 'apartment' },
camp_site: { name: 'tourism', value: 'camp_site' },
chalet: { name: 'tourism', value: 'chalet' },
guest_house: { name: 'tourism', value: 'guest_house' },
hostel: { name: 'tourism', value: 'hostel' },
motel: { name: 'tourism', value: 'motel' },
wilderness_hut: { name: 'tourism', value: 'wilderness_hut' },
viewpoint: { name: 'tourism', value: 'viewpoint' },
waterfall: { name: 'waterway', value: 'waterfall' },
peak: { name: 'natural', value: 'peak' },
cave_entrance: { name: 'natural', value: 'cave_entrance' },
volcano: { name: 'natural', value: 'volcano' },
arch: { name: 'natural', value: 'arch' },
arete: { name: 'natural', value: 'arete' },
fumarole: { name: 'natural', value: 'fumarole' },
rock: { name: 'natural', value: 'rock' },
saddle: { name: 'natural', value: 'saddle' },
sinkhole: { name: 'natural', value: 'sinkhole' },
stone: { name: 'natural', value: 'stone' },
glacier: { name: 'natural', value: 'glacier' },
spring: { name: 'natural', value: 'spring' },
hot_spring: { name: 'natural', value: 'hot_spring' },
geyser: { name: 'natural', value: 'geyser' },
};
export const overlayDefinitions = {
amenity: {
bar: { hiking: { drinking: true } },
fast_food: { hiking: { eating: true } },
food_court: { hiking: { eating: true } },
pub: { hiking: { eating: true } },
restaurant: { hiking: { eating: true } },
cafe: { hiking: { drinking: true } },
atm: { hiking: { money: true, dayToDay: true } },
bank: { hiking: { money: true, dayToDay: true } },
doctors: { hiking: { health: true } },
hospital: { hiking: { health: true } },
pharmacy: { hiking: { health: true } },
police: { hiking: { security: true } },
fire_station: { hiking: { security: true } },
drinking_water: { hiking: { drinking: true } },
water_point: { hiking: { drinking: true } },
waste_basket: { hiking: { dayToDay: true } },
waste_disposal: { hiking: { dayToDay: true } },
vending_machine: { hiking: { dayToDay: true } },
hiking: {
drinking: ['bar', 'pub', 'cafe', 'drinking_water', 'water_point', 'water'],
eating: [
'fast_food',
'food_court',
'pub',
'restaurant',
'bakery',
'butcher',
'cheese',
'chocolate',
'convenience',
'dairy',
'farm',
'greengrocer',
'health_food',
'pasta',
'pastry',
'seafood',
'supermarket',
'wholesale',
'outdoor',
],
money: ['atm', 'bank'],
dayToDay: [
'atm',
'bank',
'waste_basket',
'waste_disposal',
'vending_machine',
'department_store',
'general',
'mall',
'laundry',
],
health: ['doctors', 'hospital', 'pharmacy'],
security: ['police', 'fire_station'],
sleeping: [
'hotel',
'alpine_hut',
'apartment',
'camp_site',
'chalet',
'guest_house',
'hostel',
'motel',
'wilderness_hut',
],
naturalSites: [
'viewpoint',
'waterfall',
'peak',
'cave_entrance',
'volcano',
'arch',
'arete',
'fumarole',
'rock',
'saddle',
'sinkhole',
'stone',
'glacier',
'spring',
'hot_spring',
'geyser',
],
},
shop: {
bakery: { hiking: { eating: true } },
butcher: { hiking: { eating: true } },
cheese: { hiking: { eating: true } },
chocolate: { hiking: { eating: true } },
convenience: { hiking: { eating: true } },
dairy: { hiking: { eating: true } },
farm: { hiking: { eating: true } },
greengrocer: { hiking: { eating: true } },
health_food: { hiking: { eating: true } },
pasta: { hiking: { eating: true } },
pastry: { hiking: { eating: true } },
seafood: { hiking: { eating: true } },
water: { hiking: { drinking: true } },
department_store: { hiking: { dayToDay: true } },
general: { hiking: { dayToDay: true } },
mall: { hiking: { dayToDay: true } },
supermarket: { hiking: { eating: true } },
wholesale: { hiking: { eating: true } },
outdoor: { hiking: { material: true } },
laundry: { hiking: { dayToDay: true } },
cycling: {
drinking: ['bar', 'pub', 'cafe', 'drinking_water', 'water_point', 'water'],
eating: [
'fast_food',
'food_court',
'pub',
'restaurant',
'bakery',
'butcher',
'cheese',
'chocolate',
'convenience',
'dairy',
'farm',
'greengrocer',
'health_food',
'pasta',
'pastry',
'seafood',
'supermarket',
'wholesale',
'outdoor',
],
money: ['atm', 'bank'],
dayToDay: [
'atm',
'bank',
'waste_basket',
'waste_disposal',
'vending_machine',
'department_store',
'general',
'mall',
'laundry',
],
health: ['doctors', 'hospital', 'pharmacy'],
security: ['police', 'fire_station'],
parking: ['bicycle_parking'],
sleeping: [
'hotel',
'alpine_hut',
'apartment',
'camp_site',
'chalet',
'guest_house',
'hostel',
'motel',
'wilderness_hut',
],
naturalSites: [
'viewpoint',
'waterfall',
'peak',
'cave_entrance',
'volcano',
'arch',
'arete',
'fumarole',
'rock',
'saddle',
'sinkhole',
'stone',
'glacier',
'spring',
'hot_spring',
'geyser',
],
},
tourism: {
hotel: { hiking: { sleeping: true } },
alpine_hut: { hiking: { sleeping: true } },
apartment: { hiking: { sleeping: true } },
camp_site: { hiking: { sleeping: true } },
chalet: { hiking: { sleeping: true } },
guest_house: { hiking: { sleeping: true } },
hostel: { hiking: { sleeping: true } },
motel: { hiking: { sleeping: true } },
wilderness_hut: { hiking: { sleeping: true } },
viewpoint: { hiking: { naturalSites: true } },
},
waterway: { waterfall: { hiking: { naturalSites: true } } },
natural: {
peak: { hiking: { naturalSites: true } },
cave_entrance: { hiking: { naturalSites: true } },
volcano: { hiking: { naturalSites: true } },
arch: { hiking: { naturalSites: true } },
arete: { hiking: { naturalSites: true } },
fumarole: { hiking: { naturalSites: true } },
rock: { hiking: { naturalSites: true } },
saddle: { hiking: { naturalSites: true } },
sinkhole: { hiking: { naturalSites: true } },
stone: { hiking: { naturalSites: true } },
glacier: { hiking: { naturalSites: true } },
spring: { hiking: { naturalSites: true } },
hot_spring: { hiking: { naturalSites: true } },
geyser: { hiking: { naturalSites: true } },
vanlife: {
drinking: ['bar', 'pub', 'cafe', 'drinking_water', 'water_point', 'water'],
eating: [
'fast_food',
'food_court',
'pub',
'restaurant',
'bakery',
'butcher',
'cheese',
'chocolate',
'convenience',
'dairy',
'farm',
'greengrocer',
'health_food',
'pasta',
'pastry',
'seafood',
'supermarket',
'wholesale',
'outdoor',
],
money: ['atm', 'bank'],
dayToDay: [
'atm',
'bank',
'waste_basket',
'waste_disposal',
'vending_machine',
'department_store',
'general',
'mall',
'laundry',
],
health: ['doctors', 'hospital', 'pharmacy'],
security: ['police', 'fire_station'],
parking: ['parking'],
sleeping: ['parking', 'camp_site'],
naturalSites: [
'viewpoint',
'waterfall',
'peak',
'cave_entrance',
'volcano',
'arch',
'arete',
'fumarole',
'rock',
'saddle',
'sinkhole',
'stone',
'glacier',
'spring',
'hot_spring',
'geyser',
],
},
};
let _flat: any = [];
Object.values(overlayDefinitions).forEach((category) => {
Object.values(category).forEach((subCategory) => {
_flat = [..._flat, subCategory];
});
});
type Categories = { string: Set<string> };
export let overlayCategories: Categories = {};
_flat.forEach((obj: any) => {
Object.keys(obj).forEach((catName: string) => {
const catValue = obj[catName];
const previous =
overlayCategories[catName] === undefined
? []
: overlayCategories[catName];
overlayCategories[catName] = new Set([
...previous,
...Object.keys(catValue),
]);
});
});
export const getTagType = (feature: Feature) => {
for (const tagType of Object.keys(osmTags)) {
const tag: OsmTag = osmTags[tagType];
const tagValue = feature.get(tag.name);
if (tagValue === tag.value) {
return tagType;
}
}
return false;
};
export const getVectorTileFeatureType = (feature: Feature) => {
if (
@ -107,12 +287,7 @@ export const getVectorTileFeatureType = (feature: Feature) => {
) {
return 'way';
}
if (
Object.keys(overlayDefinitions).some((tagName) => {
const tagValue = feature.get(tagName);
return Object.keys(overlayDefinitions[tagName]).includes(tagValue);
})
) {
if (getTagType(feature)) {
return 'poi';
}
};
@ -120,6 +295,4 @@ export const getVectorTileFeatureType = (feature: Feature) => {
console.log({
caller: 'overlay-definitions',
overlayDefinitions,
_flat,
overlayCategories,
});

View File

@ -1,6 +1,5 @@
import { Component, createEffect, createSignal, onCleanup } from 'solid-js';
import dispatch, { cancelDispatch } from '../../workers/dispatcher-main';
import VectorSource from 'ol/source/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import {
@ -11,11 +10,11 @@ import { fromLonLat } from 'ol/proj';
interface Props {
rteId: string;
vectorSource: VectorSource;
vectorSources: VectorSource[];
context: any;
}
export const Rte: Component<Props> = ({ vectorSource, rteId, context }) => {
export const Rte: Component<Props> = ({ vectorSources, rteId, context }) => {
const params = {
id: rteId,
method: 'getRte',
@ -34,9 +33,9 @@ export const Rte: Component<Props> = ({ vectorSource, rteId, context }) => {
});
createEffect(() => {
console.log({ caller: 'Rte', vectorSource, rteId, rte: rte() });
console.log({ caller: 'Rte', vectorSources, rteId, rte: rte() });
if (rte()) {
if (rte() && rte().rtept && rte().rtept.length > 0) {
let geo: any = {
type: 'FeatureCollection',
features: [
@ -93,12 +92,12 @@ export const Rte: Component<Props> = ({ vectorSource, rteId, context }) => {
const features = new GeoJSON().readFeatures(geo);
console.log({ caller: 'Rte', features });
[`${rteId}/start`, rteId, `${rteId}/end`].forEach((id) => {
const feature = vectorSource.getFeatureById(id);
const feature = vectorSources[0].getFeatureById(id);
if (feature) {
vectorSource.removeFeature(feature);
vectorSources[0].removeFeature(feature);
}
});
vectorSource.addFeatures(features);
vectorSources[0].addFeatures(features);
}
});

View File

@ -7,8 +7,8 @@ import DeleteIcon from '@suid/icons-material/Delete';
import QuestionMarkIcon from '@suid/icons-material/QuestionMark';
import Tree from '../tree';
import { LineString } from 'ol/geom';
import DisplayOrGetAddress from '../display-or-get-address';
import { getFormatedLength } from '../../lib/ol';
import { DisplayOrGetStartEndAddresses } from '../display-or-get-address';
import { getFormattedLength } from '../../lib/ol';
import Alert from '../alert';
import dispatch from '../../workers/dispatcher-main';
@ -73,17 +73,11 @@ const RteViewer: Component<Props> = ({ rteId }) => {
content={
<>
<div>
{getFormatedLength(lineString)} {t('from')}{' '}
<DisplayOrGetAddress
target={() => rte().rtept.at(0)}
{getFormattedLength(lineString)}
<DisplayOrGetStartEndAddresses
id={rteId}
wpts={() => rte().rtept}
putAction='putRtept'
putParamName='rtept'
/>{' '}
{t('to')}{' '}
<DisplayOrGetAddress
target={() => rte().rtept.at(-1)}
putAction='putRtept'
putParamName='rtept'
/>
</div>
</>

View File

@ -0,0 +1,42 @@
import { Component, createSignal } from 'solid-js';
import SettingsIcon from '@suid/icons-material/Settings';
import style from './SystemDrawer.module.css';
import {
Box,
Drawer,
IconButton,
List,
ListItem,
ListItemButton,
} from '@suid/material';
import Account from '../account';
import SystemInfo from '../system-info/SystemInfo';
interface Props {}
const SystemDrawer: Component<Props> = (props) => {
const [open, setOpen] = createSignal(false);
return (
<>
<div class={style.control}>
<IconButton onClick={() => setOpen(true)}>
<SettingsIcon />
</IconButton>
<Drawer open={open()} onClose={() => setOpen(false)} anchor='right'>
<Box
sx={{ width: '100%', maxWidth: 200, bgcolor: 'background.paper' }}
>
<List>
<Account />
<SystemInfo />
</List>
</Box>
</Drawer>
</div>
</>
);
};
export default SystemDrawer;

View File

@ -0,0 +1 @@
export { default } from './SystemDrawer';

View File

@ -0,0 +1,3 @@
.clickPrompt {
font-style: italic;
}

View File

@ -0,0 +1,146 @@
import {
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
} from '@suid/material';
import {
Component,
createEffect,
createSignal,
For,
onMount,
Show,
} from 'solid-js';
import SystemSecurityUpdateWarningIcon from '@suid/icons-material/SystemSecurityUpdateWarning';
import Dialog from '../dialog';
import dispatch from '../../workers/dispatcher-main';
import { sleep } from '../../lib/async-wait';
import style from './SystemInfo.module.css';
const [error, setError] = createSignal<any[]>([]);
export const reportError = (err: any) => {
setError([...error(), err]);
};
interface Props {}
const SystemInfo: Component<Props> = (props) => {
const [open, setOpen] = createSignal(false);
const [settings, setSettings] = createSignal<any>();
const [account, setAccount] = createSignal<any>();
createEffect(() => {
if (error().length > 0 && !open()) {
openDialog();
}
});
const selfTest = async () => {
try {
const pong = await dispatch({
action: 'ping',
params: { what: 'ping' },
});
if (pong !== 'ping pong') {
throw new Error(
`web worker test error, received "${pong}" instead of expected "ping pong"`
);
}
} catch (err) {
reportError(err);
}
};
selfTest();
const openDialog = async () => {
setOpen(true);
try {
const sets: any = await dispatch({
action: 'getSettings',
});
setSettings(sets);
const acc: any = await dispatch({
action: 'getAccount',
params: { id: settings().currentAccountId },
});
setAccount(acc);
} catch (err) {
reportError(err);
}
};
let content: any;
onMount(() => {
if (!!content) {
content.onclick = function () {
document.execCommand('copy');
};
content.addEventListener('copy', function (event: any) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData('text/plain', content.textContent);
console.log(event.clipboardData.getData('text'));
}
});
}
});
const clickHandler = async (event: any) => {
const range = document.createRange();
range.selectNode(content);
window.getSelection()?.removeAllRanges();
window.getSelection()?.addRange(range);
document.execCommand('copy');
await sleep(300);
window.getSelection()?.removeAllRanges();
console.log({ caller: 'SystemInfo / clickHandler', event, range });
};
return (
<>
<ListItem>
<ListItemButton onClick={openDialog}>
<ListItemIcon>
<SystemSecurityUpdateWarningIcon />
</ListItemIcon>
<ListItemText>System Info</ListItemText>
</ListItemButton>
</ListItem>
<Show when={open()}>
<Dialog
open={open()}
closeHandler={() => setOpen(false)}
title='System info'
>
<div onclick={clickHandler}>
<div class={style.clickPrompt}>Click to copy to clipboard</div>
<div ref={content}>
<p>Platform: {window.Capacitor.platform}</p>
<p>User agent: {navigator.userAgent}</p>
<p>App release: {import.meta.env.VITE_GIT_COMMIT_HASH}</p>
<p>Account id: {settings()?.currentAccountId}</p>
<p>Account name: {account()?.name}</p>
<p>Remote DB user: {account()?.remoteDbUser}</p>
<p>Remote DB server: {account()?.remoteDbServer}</p>
</div>
<Show when={error().length > 0}>
<div>
<p>Errors:</p>
<ul>
<For each={error()}>{(item) => <li>{item.message}</li>}</For>
</ul>
</div>
</Show>
</div>
</Dialog>
</Show>
</>
);
};
export default SystemInfo;

View File

@ -0,0 +1 @@
export { default, reportError } from './SystemInfo';

View File

@ -1,17 +1,4 @@
import {
Component,
createEffect,
createResource,
createSignal,
For,
onCleanup,
Suspense,
} from 'solid-js';
import OlMap from 'ol/Map';
import dispatch, { cancelDispatch } from '../../workers/dispatcher-main';
import getUri from '../../lib/ids';
import { Component, createEffect, For, onCleanup, Suspense } from 'solid-js';
import Trkseg from '../trkseg';
import VectorSource from 'ol/source/Vector';
@ -22,10 +9,16 @@ import {
interface Props {
trkId: string;
vectorSource: VectorSource;
vectorSources: VectorSource[];
context: any;
tags: any;
}
export const Trk: Component<Props> = ({ vectorSource, trkId, context }) => {
export const Trk: Component<Props> = ({
vectorSources,
trkId,
context,
tags,
}) => {
const params = {
id: trkId,
method: 'getTrk',
@ -38,7 +31,7 @@ export const Trk: Component<Props> = ({ vectorSource, trkId, context }) => {
});
createEffect(() => {
console.log({ caller: 'Trk', vectorSource, trkId, trk: trk() });
console.log({ caller: 'Trk', vectorSources, trkId, trk: trk() });
});
return (
@ -49,9 +42,10 @@ export const Trk: Component<Props> = ({ vectorSource, trkId, context }) => {
return (
<Suspense>
<Trkseg
vectorSource={vectorSource}
vectorSources={vectorSources}
trksegId={trksegId}
context={{ ...context, trk, trkId }}
tags={tags}
/>
</Suspense>
);

View File

@ -11,14 +11,16 @@ import { fromLonLat } from 'ol/proj';
interface Props {
trksegId: string;
vectorSource: VectorSource;
vectorSources: VectorSource[];
context: any;
tags: any;
}
export const Trkseg: Component<Props> = ({
vectorSource,
vectorSources,
trksegId,
context,
tags,
}) => {
const params = {
id: trksegId,
@ -28,29 +30,61 @@ export const Trkseg: Component<Props> = ({
const clearFeatures = () => {
[`${trksegId}/start`, trksegId, `${trksegId}/end`].forEach((id) => {
const feature = vectorSource.getFeatureById(id);
if (feature) {
vectorSource.removeFeature(feature);
}
vectorSources.forEach((vectorSource) => {
const feature = vectorSource.getFeatureById(id);
if (feature) {
vectorSource.removeFeature(feature);
}
});
});
};
const positions = () => {
let result = new Set<string>();
if (context.trk && context.gpx) {
const trkId = context.trkId;
if (trkId === context.gpx().trk.at(0)) {
result.add('gpx-start');
}
if (trkId === context.gpx().trk.at(-1)) {
result.add('gpx-end');
}
if (trksegId === context.trk().trkseg.at(0)) {
result.add('trk-start');
}
if (trksegId === context.trk().trkseg.at(-1)) {
result.add('trk-end');
}
}
return result;
};
onCleanup(() => {
console.log({
caller: 'Trkseg / onCleanup',
trksegId,
trkseg: trkseg(),
params,
context,
});
destroyCachedSignal(params);
clearFeatures();
});
createEffect(() => {
console.log({ caller: 'Trkseg', vectorSource, trksegId, trkseg: trkseg() });
console.log({
caller: 'Trkseg',
vectorSources,
trksegId,
trkseg: trkseg(),
context,
trk: context.trk(),
});
if (trkseg()) {
let geo: any = {
clearFeatures();
if (trkseg() && trkseg().trkpt && trkseg().trkpt.length > 0) {
let geoCluttered: any = {
type: 'FeatureCollection',
features: [
{
@ -66,6 +100,8 @@ export const Trkseg: Component<Props> = ({
type: 'trkseg-start',
id: trksegId,
context: { ...context, trkseg, trksegId },
positions: positions(),
tags,
},
id: `${trksegId}/start`,
},
@ -81,9 +117,17 @@ export const Trkseg: Component<Props> = ({
type: 'trkseg',
id: trksegId,
context: { ...context, trkseg, trksegId },
positions: positions(),
tags,
},
id: trksegId,
},
],
};
let geoUnCluttered: any = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
@ -97,16 +141,16 @@ export const Trkseg: Component<Props> = ({
type: 'trkseg-finish',
id: trksegId,
context: { ...context, trkseg, trksegId },
positions: positions(),
tags,
},
id: `${trksegId}/end`,
},
],
};
const features = new GeoJSON().readFeatures(geo);
console.log({ caller: 'Trkseg', features });
clearFeatures();
vectorSource.addFeatures(features);
vectorSources[0].addFeatures(new GeoJSON().readFeatures(geoCluttered));
vectorSources[1].addFeatures(new GeoJSON().readFeatures(geoUnCluttered));
}
});

View File

@ -3,9 +3,10 @@ import { peekCachedSignal } from '../../workers/cached-signals';
import Tree from '../tree';
import TrkIcon from '../../icons/human-footprints-svgrepo-com.svg?component-solid';
import { useI18n } from '@solid-primitives/i18n';
import { getFormatedLength } from '../../lib/ol';
import DisplayOrGetAddress from '../display-or-get-address';
import { getFormattedLength } from '../../lib/ol';
import { DisplayOrGetStartEndAddresses } from '../display-or-get-address';
import { LineString } from 'ol/geom';
import { getFormattedHeightStats } from '../../lib/height';
interface Props {
trksegId: string;
@ -40,18 +41,13 @@ const TrksegViewer: Component<Props> = ({ trksegId }) => {
content={
<>
<div>
{getFormatedLength(lineString)} {t('from')}{' '}
<DisplayOrGetAddress
target={firstTrkpt}
{getFormattedLength(lineString)}{' '}
<DisplayOrGetStartEndAddresses
id={trksegId}
wpts={() => trkseg().trkpt}
putAction='putTrkpt'
putParamName='trkpt'
/>{' '}
{t('to')}{' '}
<DisplayOrGetAddress
target={lastTrkpt}
putAction='putTrkpt'
putParamName='trkpt'
/>
/>{', '}
{getFormattedHeightStats(trkseg().trkpt)}
</div>
</>
}

View File

@ -0,0 +1,12 @@
.mobile {
position: fixed;
z-index: 1;
padding-top: 20px;
}
.web {
position: fixed;
z-index: 1;
left: 40px;
padding-top: 20px;
}

View File

@ -0,0 +1,66 @@
import { Alert, Button } from '@suid/material';
import { Component, createSignal, onCleanup, Show } from 'solid-js';
import { Browser } from '@capacitor/browser';
import style from './Updater.module.css';
interface Props {}
const Updater: Component<Props> = (props) => {
const [updateNeeded, setUpdateNeeded] = createSignal(false);
const checkUpdate = async () => {
const response = await fetch(
'https://dyomedea.app/assets/release/dyomedea.rel',
{
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin',
}
);
const latestRelease = (await response.text()).replace('\n', '');
const currentRelease = import.meta.env.VITE_GIT_COMMIT_HASH;
console.log({ caller: 'checkUpdate', currentRelease, latestRelease });
setUpdateNeeded(latestRelease !== currentRelease);
};
const intervalId = setInterval(checkUpdate, 10 * 60 * 1000);
checkUpdate();
onCleanup(() => {
clearInterval(intervalId);
});
return (
<>
<Show when={updateNeeded()}>
<Show when={window.Capacitor.platform === 'android'}>
<div class={style.mobile}>
<Alert severity='warning'>
The app needs to be updated
<Button
variant='outlined'
onclick={() => {
Browser.open({
url: 'https://dyomedea.app/assets/release/dyomedea.apk',
});
}}
>
Update
</Button>
</Alert>
</div>
</Show>
<Show when={window.Capacitor.platform === 'web'}>
<div class={style.web}>
<Alert severity='warning' class={style.mobile}>
Please reload this page to update the application.
</Alert>
</div>
</Show>
</Show>
</>
);
};
export default Updater;

View File

@ -0,0 +1 @@
export { default } from './Updater';

View File

@ -12,12 +12,12 @@ import { fromLonLat } from 'ol/proj';
interface Props {
wptId: string;
vectorSource: VectorSource;
vectorSources: VectorSource[];
context: any;
}
export const Wpt: Component<Props> = ({
vectorSource,
vectorSources,
wptId: wptId,
context,
}) => {
@ -48,12 +48,12 @@ export const Wpt: Component<Props> = ({
};
createEffect(() => {
console.log({ caller: 'Wpt', vectorSource, wptId, wpt: cloneDeep(wpt()) });
console.log({ caller: 'Wpt', vectorSources, wptId, wpt: cloneDeep(wpt()) });
if (wpt()) {
const existingFeature = vectorSource.getFeatureById(wptId);
const existingFeature = vectorSources[0].getFeatureById(wptId);
if (existingFeature) {
vectorSource.removeFeature(existingFeature);
vectorSources[0].removeFeature(existingFeature);
}
let geo: any = {
type: 'FeatureCollection',
@ -78,11 +78,19 @@ export const Wpt: Component<Props> = ({
const features = new GeoJSON().readFeatures(geo);
console.log({ caller: 'Wpt', features });
const feature = vectorSource.getFeatureById(wptId);
if (feature) {
vectorSource.removeFeature(feature);
const feature0 = vectorSources[0].getFeatureById(wptId);
if (feature0) {
vectorSources[0].removeFeature(feature0);
}
const feature1 = vectorSources[1].getFeatureById(wptId);
if (feature1) {
vectorSources[1].removeFeature(feature1);
}
if (false && wpt()?.extensions?.category === 'note') {
vectorSources[1].addFeatures(features);
} else {
vectorSources[0].addFeatures(features);
}
vectorSource.addFeatures(features);
}
});

View File

@ -1,4 +1,12 @@
import { Box, Button, Stack, TextField } from '@suid/material';
import {
Box,
Button,
FormControl,
InputLabel,
NativeSelect,
Stack,
TextField,
} from '@suid/material';
import { Component, createEffect, createSignal, Show } from 'solid-js';
import { useI18n } from '@solid-primitives/i18n';
@ -15,20 +23,41 @@ import { emptyGpx } from '../../db/gpx';
import getUri from '../../lib/ids';
import { Coordinate } from 'ol/coordinate';
export enum Category {
NOTE = 'note',
POI = 'poi',
PICTURE = 'picture',
UNKNOWN = '',
}
export enum SubCategory {
ACCOMMODATION = 'accommodation',
UNKNOWN = '',
}
interface Props {
wptId?: string;
coordinate?: () => Coordinate | undefined;
open: () => boolean;
closeHandler?: () => vpod;
closeHandler?: () => void;
initialWpt: () => Wpt;
imageUrl?: string | undefined;
}
const WptEditDialog: Component<Props> = (props) => {
const { wptId, closeHandler, open, coordinate } = props;
const {
wptId,
closeHandler,
open,
coordinate,
initialWpt = () => emptyWpt,
imageUrl,
} = props;
const [t, { add, locale, dict }] = useI18n();
const wpt = !!wptId
? peekCachedSignal({ id: wptId, method: 'getWpt' })
: () => emptyWpt;
: initialWpt;
const [gpxId, setGpxId] = !wptId
? createSignal<string>(currentGpxId())
@ -107,7 +136,7 @@ const WptEditDialog: Component<Props> = (props) => {
action: 'putWpt',
params: { id: newWptId, wpt: editedWpt() },
});
setEditedWpt(undefined);
_closeHandler();
};
@ -118,6 +147,25 @@ const WptEditDialog: Component<Props> = (props) => {
return t('wpt');
};
// <TextField
// label={t('sym')}
// defaultValue={wpt()?.sym}
// onChange={(event: any, value: string) => {
// setEditedWpt({ ...editedWpt(), sym: value });
// }}
// />
// <TextField
// label={t('minZoom')}
// defaultValue={wpt()?.extensions?.['dyo:minZoom']?.toString()}
// onChange={(event: any, value: string) => {
// const extensions = {
// ...editedWpt()?.extensions,
// 'dyo:minZoom': parseFloat(value),
// };
// setEditedWpt({ ...editedWpt(), extensions });
// }}
// />
return (
<Dialog
open={open() && !!wpt()}
@ -147,24 +195,50 @@ const WptEditDialog: Component<Props> = (props) => {
setEditedWpt({ ...editedWpt(), name: value });
}}
/>
<TextField
label={t('sym')}
defaultValue={wpt()?.sym}
onChange={(event: any, value: string) => {
setEditedWpt({ ...editedWpt(), sym: value });
}}
/>
<TextField
label={t('minZoom')}
defaultValue={wpt()?.extensions?.['dyo:minZoom']?.toString()}
onChange={(event: any, value: string) => {
const extensions = {
...editedWpt()?.extensions,
'dyo:minZoom': parseFloat(value),
};
setEditedWpt({ ...editedWpt(), extensions });
}}
/>
<FormControl>
<InputLabel variant='normal' htmlFor='category'>
Type
</InputLabel>
<NativeSelect
inputProps={{
name: 'category',
id: 'category',
}}
onChange={(event: any, value: string) => {
setEditedWpt({
...editedWpt(),
extensions: { ...editedWpt().extensions, category: value },
});
}}
>
<option
value={Category.POI}
selected={editedWpt()?.extensions?.category === Category.POI}
>
Point d'intérêt
</option>
<option
value={Category.NOTE}
selected={editedWpt()?.extensions?.category === Category.NOTE}
>
Note
</option>
<option
value={Category.PICTURE}
selected={
editedWpt()?.extensions?.category === Category.PICTURE
}
>
Picture
</option>
<option
value={undefined}
selected={!editedWpt()?.extensions?.category}
>
Autre
</option>
</NativeSelect>
</FormControl>
<TextField
label={t('gpxDesc')}
type='text'
@ -176,6 +250,34 @@ const WptEditDialog: Component<Props> = (props) => {
}}
InputProps={{ inputComponent: 'textarea' }}
/>
<TextField
label='Début'
type='datetime-local'
value={(editedWpt()?.extensions?.startTime || '').replace('Z', '')}
onChange={(event: any) => {
setEditedWpt({
...editedWpt(),
extensions: {
...editedWpt().extensions,
startTime: new Date(event.target.value).toISOString(),
},
});
}}
/>
<TextField
label='Fin'
type='datetime-local'
value={(editedWpt()?.extensions?.endTime || '').replace('Z', '')}
onChange={(event: any) => {
setEditedWpt({
...editedWpt(),
extensions: {
...editedWpt().extensions,
endTime: new Date(event.target.value).toISOString(),
},
});
}}
/>
<Stack spacing={2} direction='row' sx={{ marginTop: '20px' }}>
<Button variant='outlined' color='secondary' onClick={closeHandler}>
{t('cancel')}

View File

@ -0,0 +1,13 @@
.description {
white-space: pre-wrap;
}
.date {
padding-top: 10px;
font-style: italic;
}
.thumbnail {
padding-top: 10px;
text-align: center;
}

View File

@ -1,32 +1,121 @@
import { Component } from 'solid-js';
import { Button, IconButton } from '@suid/material';
import { Component, createSignal, Show } from 'solid-js';
import WptIcon from '../../icons/location-pin-svgrepo-com.svg?component-solid';
import { peekCachedSignal } from '../../workers/cached-signals';
import dispatch from '../../workers/dispatcher-main';
import { useI18n } from '@solid-primitives/i18n';
import Tree from '../tree';
import WptEditButtonAndDialog from './WptEditButtonAndDialog';
import DeleteIcon from '@suid/icons-material/Delete';
import QuestionMarkIcon from '@suid/icons-material/QuestionMark';
import Alert from '../alert';
import style from './WptViewer.module.css';
interface Props {
wptId: string;
}
const WptViewer: Component<Props> = ({ wptId }) => {
const [t, { add, locale, dict }] = useI18n();
const wpt = peekCachedSignal({ id: wptId, method: 'getWpt' });
console.log({ caller: 'WptViewer', wptId, wpt: wpt() });
const title = () => {
return wpt().name;
};
const [confirmDelete, setConfirmDelete] = createSignal(false);
const confirmDeleteHandler = () => {
console.log({
caller: 'WptViewer / confirmDeleteHandler',
wptId,
});
setConfirmDelete(true);
};
const deleteHandler = () => {
console.log({
caller: 'WptViewer / deleteHandler',
wptId,
});
dispatch({ action: 'deleteWpt', params: { id: wptId } });
setConfirmDelete(false);
};
const cancelDeleteHandler = () => {
console.log({
caller: 'WptViewer / cancelDeleteHandler',
wptId,
});
setConfirmDelete(false);
};
return (
<Tree
title={
<>
<WptIcon fill='black' width='24' height='24' viewBox='0 0 300 300' />
{title()}
<WptEditButtonAndDialog wptId={wptId} />
</>
}
content={undefined}
subTree={undefined}
/>
<>
<Tree
title={
<>
<WptIcon
fill='black'
width='24'
height='24'
viewBox='0 0 300 300'
/>
{title()}
<WptEditButtonAndDialog wptId={wptId} />
<div>
<IconButton onClick={confirmDeleteHandler}>
<DeleteIcon fill='white' />
</IconButton>
</div>
</>
}
content={
<div>
<div class={style.description}>{wpt().desc}</div>
<Show when={wpt().extensions?.thumbnailUrl}>
<div class={style.thumbnail}>
<img src={wpt().extensions?.thumbnailUrl}></img>
</div>
</Show>
<Show when={wpt().extensions?.startTime}>
<div class={style.date}>
{new Date(wpt().extensions?.startTime).toLocaleDateString()}
</div>
</Show>
</div>
}
subTree={undefined}
/>
<Alert
open={confirmDelete}
closeHandler={cancelDeleteHandler}
severity='warning'
icon={<QuestionMarkIcon />}
action={
<>
<Button
color='error'
variant='contained'
size='small'
onClick={deleteHandler}
>
{t('yes')}
</Button>
<Button
color='primary'
variant='outlined'
size='small'
onclick={cancelDeleteHandler}
>
{t('no')}
</Button>
</>
}
>
{t('deleteTrack')}
</Alert>
</>
);
};

View File

@ -0,0 +1,299 @@
import { createEffect, createRoot, createSignal } from 'solid-js';
import PouchDB from 'pouchdb';
import indexeddb from 'pouchdb-adapter-indexeddb';
import { sleep, until } from '../lib/async-wait';
import { isEqual } from 'lodash';
import { dbUrlToUserId } from '../lib/user-id';
PouchDB.plugin(indexeddb);
declare global {
var localDb: any;
var db: any;
var remoteDb: any;
var currentAccount: any;
var sync: any;
}
const [state, setState] = createSignal<any>({});
export { state };
export const watchDbLegacy = async () => {
createRoot(async (dispose) => {
console.log({ caller: 'watchDbLegacy / start' });
const { db, localDb, remoteDb, sync, currentAccount } = globalThis;
const [status, setStatus] = createSignal<any>({});
const [syncState, setSyncState] = createSignal<any>({});
const [remoteUrl, setRemoteUrl] = createSignal<string>();
const updateStatus = async () => {
const dbInfo = await db.info();
const localDbInfo = await localDb.info();
const remoteDbInfo = remoteDb ? await remoteDb.info() : undefined;
const tasks = PouchDB.activeTasks.list();
const newStatus = {
...status(),
tasks,
dbInfo,
localDbInfo,
remoteDbInfo,
// date: new Date(),
};
if (!isEqual(status(), newStatus)) {
setStatus(newStatus);
}
};
createEffect(() => {
console.log({
caller: 'watchDbLegacy',
state: state(),
status: status(),
syncState: syncState(),
sync,
});
});
createEffect(() => {
const newState = {
...state(),
dbName: status()?.dbInfo?.db_name,
userId: dbUrlToUserId(status()?.remoteDbInfo?.host),
localUpdateSeq: status()?.dbInfo?.update_seq,
remoteUrl: status()?.remoteDbInfo?.host,
sync: syncState(),
};
if (!isEqual(newState, state())) {
setState(newState);
}
});
updateStatus();
if (sync) {
sync
.on('change', function (info) {
// handle change
// console.log({ caller: 'Sync / change', info });
if (info.direction === 'push') {
setSyncState({ ...syncState(), lastSeq: info.change.last_seq });
}
})
.on('paused', function (err) {
// replication paused (e.g. replication up to date, user went offline)
setSyncState({ ...syncState(), paused: true });
// console.log({ caller: 'Sync / paused', err });
})
.on('active', function () {
// replicate resumed (e.g. new changes replicating, user went back online)
setSyncState({ ...syncState(), paused: false });
// console.log({ caller: 'Sync / active' });
})
.on('denied', function (err) {
// a document failed to replicate (e.g. due to permissions)
console.error({ caller: 'Sync / denied', err });
})
.on('complete', function (info) {
// handle complete
console.log({ caller: 'Sync / complete', info });
})
.on('error', function (err) {
// handle error
console.error({ caller: 'Sync / error', err });
});
}
const timerId = setInterval(updateStatus, 15000);
const findDocumentsWithoutOrigin = async () => {
const allDocs = await db.allDocs({ include_docs: true });
return allDocs.rows
.filter(
(row: any) =>
!row.doc.origin || !row.doc.origin.match(/^@([^>]+)>(.+)$/)
)
.map((row: any) => row.doc._id);
};
const updateDocumentsWithoutOrigin = async () => {
const documentsWithoutOrigin = await findDocumentsWithoutOrigin();
console.log({
caller: 'watchDbLegacy / addOrigin',
remoteUrl: state().remoteUrl,
nbDocumentsWithoutOrigin: documentsWithoutOrigin.length,
});
for (const docId of documentsWithoutOrigin) {
while (true) {
await sleep(100);
const doc = await db.get(docId);
console.log({
caller: 'watchDbLegacy / addOrigin',
remoteUrl: state().remoteUrl,
docId,
doc,
});
try {
db.put({ ...doc, origin: dbUrlToUserId(state().remoteUrl) });
break;
} catch (error) {
if (error.name === 'conflict') {
console.log({
caller: 'watchDbLegacy / addOrigin',
docId,
doc,
error,
});
} else {
console.error({
caller: 'watchDbLegacy / addOrigin',
docId,
doc,
error,
});
break;
}
}
}
}
};
if (!!state().remoteUrl) {
await updateDocumentsWithoutOrigin();
}
createEffect(async () => {
if (!!state().remoteUrl && remoteUrl() !== state().remoteUrl) {
setRemoteUrl(state().remoteUrl);
// Check documents and update without origin
await updateDocumentsWithoutOrigin();
}
});
// db.compact();
const openIDb = (name: string) =>
new Promise((resolve, reject) => {
const iDb = indexedDB.open(name);
iDb.onerror = (event: any) => {
console.error({
caller: 'watchDbLegacy',
message: 'open db error',
target: event.target,
});
reject(event.target.errorCode);
};
iDb.onsuccess = (event: any) => {
resolve(event.target.result);
};
});
const getAll = (store: any) =>
new Promise((resolve, reject) => {
const request = store.getAll();
request.onerror = (event: any) => {
console.error({
caller: 'watchDbLegacy',
message: 'getAll error',
target: event.target,
});
reject(event.target.errorCode);
};
request.onsuccess = (event: any) => {
resolve(event.target.result as any[]);
};
});
const getDeletedDocs = async () => {
const iDb = (await openIDb(`_pouch_${state().dbName}`)) as IDBDatabase;
const bySequence = iDb.transaction('docs', 'readonly');
const store = bySequence.objectStore('docs');
const allDocs = (await getAll(store)) as any[];
iDb.close();
const docs = allDocs
.filter(
(doc) =>
!doc.id.startsWith('_local') &&
doc.deleted === 1 &&
doc.seq <= state()?.sync?.lastSeq
)
.map((doc) => ({ id: doc.id, rev: doc.rev }));
// console.log({
// caller: 'watchDbLegacy / getDeletedDocs',
// // bySequence,
// // store,
// // allDocs,
// docs,
// state: state(),gi
// });
return docs;
};
while (true) {
await until(
() => state()?.sync?.paused, //&&
//state()?.sync?.lastSeq >= state()?.localUpdateSeq - 1, // I wonder why this can happen !
1000
);
console.log({ caller: 'watchDbLegacy / ready to purge after sync ' });
try {
const localPurges = await db.get('_local/purges');
localPurges._deleted = true;
await db.put(localPurges);
} catch (error) {
// console.warn({ caller: 'watchDbLegacy / _local/purges', error });
}
const deletedDocs = await getDeletedDocs();
let i = 0;
if (deletedDocs.length > 0) {
console.log({
caller: 'watchDbLegacy / purge',
// bySequence,
// store,
// allDocs,
deletedDocs,
state: state(),
});
for (const doc of deletedDocs) {
await sleep(10);
try {
await db.purge(doc.id, doc.rev);
} catch (err) {
console.log({
caller: 'watchDbLegacy / purge',
doc,
err,
});
}
i = i + 1;
if (i % 10 === 0) {
console.log({
caller: 'watchDbLegacy / purge',
nbDeletedDocs: i,
nbDocsToDelete: deletedDocs.length,
doc,
});
}
if (i === 1000) {
break;
}
}
}
console.log({
caller: 'watchDbLegacy / purge',
nbDeletedDocs: i,
nbDocsToDelete: deletedDocs.length,
});
if (i === deletedDocs.length) {
await sleep(60000);
}
}
});
};

181
src/db-admin/health.ts Normal file
View File

@ -0,0 +1,181 @@
import { Signal } from 'solid-js';
import PouchDB from 'pouchdb';
import indexeddb from 'pouchdb-adapter-indexeddb';
import { sleep } from '../lib/async-wait';
import { openDatabases } from './open';
import { toHex } from '../lib/to-hex';
import { isEqual } from 'lodash';
PouchDB.plugin(indexeddb);
declare global {
var localDb: any;
var db: any;
var remoteDb: any;
var currentAccount: any;
var sync: any;
}
const initDb = async () => {
if (globalThis.localDb === undefined) {
globalThis.currentAccount = await openDatabases();
const currentAccount = globalThis.currentAccount;
// if (currentAccount.remoteDbServer) {
// const url = `${currentAccount.remoteDbServer}/userdb-${toHex(
// currentAccount.remoteDbUser
// )}`;
// const remoteDb = new PouchDB(url, {
// auth: {
// username: currentAccount.remoteDbUser,
// password: currentAccount.remoteDbPassword,
// },
// skip_setup: true,
// });
// globalThis.remoteDb = remoteDb;
// globalThis.sync = PouchDB.sync(db, remoteDb, {
// live: true,
// retry: true,
// });
// }
}
};
export const watchDb = async (p: { signal: Signal<any>; params: any }) => {
const { signal } = p;
const [status, setStatus] = signal;
console.log({ caller: 'watchDb', p });
await initDb();
db = globalThis.db;
localDb = globalThis.localDb;
setStatus({ opened: true });
// if (globalThis.sync) {
// globalThis.sync
// .on('change', function (info) {
// // handle change
// console.log({ caller: 'Sync / change', info });
// })
// .on('paused', function (err) {
// // replication paused (e.g. replication up to date, user went offline)
// console.log({ caller: 'Sync / paused', err });
// })
// .on('active', function () {
// // replicate resumed (e.g. new changes replicating, user went back online)
// console.log({ caller: 'Sync / active' });
// })
// .on('denied', function (err) {
// // a document failed to replicate (e.g. due to permissions)
// console.error({ caller: 'Sync / denied', err });
// })
// .on('complete', function (info) {
// // handle complete
// console.log({ caller: 'Sync / complete', info });
// })
// .on('error', function (err) {
// // handle error
// console.error({ caller: 'Sync / error', err });
// });
// }
const timerId = setInterval(async () => {
const dbInfo = await db.info();
const localDbInfo = await localDb.info();
const remoteDbInfo = globalThis.remoteDb
? await remoteDb.info()
: undefined;
const tasks = PouchDB.activeTasks.list();
const newStatus = {
...status(),
tasks,
dbInfo,
localDbInfo,
remoteDbInfo,
// date: new Date(),
};
if (!isEqual(status(), newStatus)) {
setStatus(newStatus);
}
}, 10000);
// db.compact();
await sleep(10000);
const openIDb = (name: string) =>
new Promise((resolve, reject) => {
const iDb = indexedDB.open(name);
iDb.onerror = (event: any) => {
console.error({
caller: 'watchDb',
message: 'open db error',
target: event.target,
});
reject(event.target.errorCode);
};
iDb.onsuccess = (event: any) => {
console.log({
caller: 'watchDb',
message: 'open db',
target: event.target,
});
resolve(event.target.result);
};
});
const getAll = (store: any) =>
new Promise((resolve, reject) => {
const request = store.getAll();
request.onerror = (event: any) => {
console.error({
caller: 'watchDb',
message: 'getAll error',
target: event.target,
});
reject(event.target.errorCode);
};
request.onsuccess = (event: any) => {
console.log({
caller: 'watchDb',
message: 'getAll',
target: event.target,
});
resolve(event.target.result as any[]);
};
});
// const iDb = (await openIDb('_pouch__dyomedea_')) as IDBDatabase;
// const bySequence = iDb.transaction('docs', 'readonly');
// const store = bySequence.objectStore('docs');
// console.log({
// caller: 'watchDb',
// message: 'transaction opened',
// bySequence,
// store,
// });
// const docs = (await getAll(store)) as any[];
// docs.forEach(async (doc) => {
// const { id, rev, deleted } = doc;
// if (deleted !== 0) {
// // const purge = await db.purge(id, rev);
// console.log({
// caller: 'watchDb',
// message: 'purging',
// id,
// rev,
// doc,
// // purge,
// });
// await sleep(1000);
// }
// });
};

48
src/db-admin/open.ts Normal file
View File

@ -0,0 +1,48 @@
import PouchDB from 'pouchdb';
import indexeddb from 'pouchdb-adapter-indexeddb';
import {
getAccounts,
initialAccount,
putAccount,
getAccountById,
} from '../db/account';
import { getSettings, putSettings } from '../db/settings';
PouchDB.plugin(indexeddb);
declare global {
var localDb: any;
var db: any;
}
export const openDatabases = async () => {
globalThis.localDb = new PouchDB('_local_dyomedea_', {
adapter: 'indexeddb',
auto_compaction: true,
});
const accounts = await getAccounts();
if (accounts.length === 0) {
accounts[0] = initialAccount;
await putAccount({ id: initialAccount.id, account: initialAccount });
}
const settings = await getSettings();
let currentAccount = getAccountById(accounts, settings.currentAccountId);
if (currentAccount === undefined) {
settings.currentAccountId = accounts[0].id;
await putSettings({ settings });
currentAccount = accounts[0];
}
console.log({ caller: 'open', accounts, settings });
if (globalThis.db === undefined) {
globalThis.db = new PouchDB(currentAccount.localDb, {
adapter: 'indexeddb',
auto_compaction: true,
});
}
return currentAccount;
};

View File

@ -1,10 +1,11 @@
import { getFamily, put } from './lib';
import { get, getFamily, put } from './lib';
import getUri from '../lib/ids';
import { getSettings, putSettings } from './settings';
export const initialAccount = {
id: 'initial',
name: '???',
localDb: 'dyomedea',
localDb: '_dyomedea_',
};
export const getAccounts = async () => {
@ -12,6 +13,13 @@ export const getAccounts = async () => {
return accountDocs.rows.map((row: any) => row.doc.doc);
};
export const getAccount = async (params: any) => {
const { id } = params;
console.log({ caller: 'getAccount', params });
const uri = getUri('account', { account: id });
return (await get(uri, true)).doc;
};
export const putAccount = async (params: any) => {
const { id, account } = params;
const uri = getUri('account', { account: id });
@ -22,3 +30,14 @@ export const getAccountById = (accounts: any, id: string) => {
const targetAccounts: any[] = accounts.filter((acc: any) => acc.id === id);
return targetAccounts[0];
};
export const getCurrentAccount = async (params: any) => {
const settings = await getSettings();
return await getAccount({ id: settings.currentAccountId });
};
export const putCurrentAccount = async (params: any) => {
const { account } = params;
const settings = await getSettings();
await putAccount({ id: settings.currentAccountId, account });
};

View File

@ -1,5 +1,6 @@
import { debounce, slice } from 'lodash';
import { getWpt } from '../db/wpt';
import { getParentId } from '../lib/docuri';
import { returnAgain } from '../workers/dispatcher-worker';
import { getAllGpxes, getGpx } from './gpx';
import { put } from './lib';
@ -7,6 +8,7 @@ import { getOverlays } from './overlays';
import { getRte } from './rte';
import { getTrk } from './trk';
import { getTrkseg } from './trkseg';
import { getDrawingSelections } from './drawing-selections';
declare global {
var watches: Map<string, any>;
@ -20,15 +22,20 @@ const methods = {
getWpt,
getRte,
getOverlays,
getDrawingSelections,
};
const sendUpdate = async (params: any) => {
if (params) {
console.log({ caller: 'ChangeHandler / sendUpdate', params });
const { method, _dispatchId, id, ...otherParams } = params;
const returnValue = await methods[<keyof typeof methods>method](params);
if (returnValue) {
returnAgain(_dispatchId, returnValue);
try {
const { method, _dispatchId, id, ...otherParams } = params;
const returnValue = await methods[<keyof typeof methods>method](params);
if (returnValue) {
returnAgain(_dispatchId, returnValue);
}
} catch (error) {
console.error({ caller: 'ChangeHandler / sendUpdate', params, error });
}
}
};
@ -43,34 +50,24 @@ for (const property in methods) {
}
const changeHandler = async (change: any) => {
console.log({ caller: 'ChangeHandler', change, watches: globalThis.watches });
// console.log({ caller: 'ChangeHandler', change, watches: globalThis.watches });
const { id } = change;
if (!globalThis.watches) {
globalThis.watches = new Map();
}
sendUpdate(globalThis.watches.get(id));
const tokens = id.split('/').slice(0, -1);
if (['1wpt', '2rte', '3trk'].includes(tokens.at(-1))) {
tokens.splice(-1);
}
const parentId = tokens.join('/');
console.log({
caller: 'ChangeHandler',
change,
watches: globalThis.watches,
parentId,
});
const parentId = getParentId(id);
if (parentId === 'gpx') {
const gpxes = await getAllGpxes();
console.log({ caller: 'changeHandler / gpxes', gpxes, id });
// console.log({ caller: 'changeHandler / gpxes', gpxes, id });
if (!gpxes.includes(id)) {
await put(
parentId,
`idx-${parentId}`,
(doc) => {
console.log({ caller: 'changeHandler / gpxes', doc });
// console.log({ caller: 'changeHandler / gpxes', doc });
doc.push(id);
doc.reverse().sort().reverse();
return doc;
@ -89,23 +86,23 @@ const changeHandler = async (change: any) => {
export default changeHandler;
export const getAndWatch = async (params: any) => {
console.log({
caller: 'ChangeHandler / getAndWatch',
params,
watches: globalThis.watches,
});
// console.log({
// caller: 'ChangeHandler / getAndWatch',
// params,
// watches: globalThis.watches,
// });
const { method, _dispatchId, id, ...otherParams } = params;
if (!globalThis.watches) {
globalThis.watches = new Map();
}
globalThis.watches.set(id, params);
const returnValue = await methods[<keyof typeof methods>method](params);
console.log({
caller: 'ChangeHandler / getAndWatch',
params,
returnValue,
watches: globalThis.watches,
});
// console.log({
// caller: 'ChangeHandler / getAndWatch',
// params,
// returnValue,
// watches: globalThis.watches,
// });
return returnValue;
};

View File

@ -0,0 +1,18 @@
import { get, put } from './lib';
export const getDrawingSelections = async (params: any) => {
const { id, defaultDrawingSelections } = params;
try {
const drawingSelections = await get(id, true);
return drawingSelections.doc;
} catch (error: any) {
console.error({ caller: 'defaultDrawingSelections', error });
return defaultDrawingSelections;
}
};
export const putDrawingSelections = async (params: any) => {
const { id, drawingSelections } = params;
await put(id, 'drawingSelections', (doc) => drawingSelections, {}, true);
return drawingSelections;
};

View File

@ -1,5 +1,12 @@
import { initDb } from '.';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import shell from 'shelljs';
import PouchDB from 'pouchdb';
import { existsGpx, putNewGpx } from './gpx';
const test = it;
declare global {
var db: any;
var dbReady: boolean;
@ -8,16 +15,17 @@ declare global {
const originalDb = globalThis.db;
const originalDateNow = globalThis.Date.now;
describe('The gpx module', () => {
describe('putNewGpx', () => {
beforeEach(() => {
globalThis.db = { put: jest.fn() };
globalThis.db = { put: vi.fn() };
globalThis.Date.now = () => 0;
});
afterEach(() => {
globalThis.db = originalDb;
globalThis.Date.now = originalDateNow;
});
test('db.put() a new Gpx when required', async () => {
it('db.put() a new Gpx when required', async () => {
await putNewGpx({ gpx: 0 });
expect(globalThis.db.put).toBeCalledWith({
_id: 'gpx/0000000000000000',
@ -56,20 +64,24 @@ describe('The gpx module', () => {
type: 'gpx',
});
});
test('db.put() generates an id if needed', async () => {
const id = await putNewGpx();
expect(id).toEqual({ gpx: 4320000000000000 });
});
});
describe('The gpx module with a real db', () => {
beforeEach(async () => {
await initDb({});
globalThis.db = new PouchDB('dyomedea', {
auto_compaction: false,
});
globalThis.Date.now = () => 0;
});
afterEach(async () => {
await db.destroy();
db = undefined;
try {
await db.destroy();
} catch (err) {
// console.error(err);
await shell.exec('rm -rf $*$');
}
globalThis.db = undefined;
globalThis.dbReady = false;
globalThis.Date.now = originalDateNow;
});

View File

@ -1,10 +1,13 @@
import { Rowing } from '@suid/icons-material';
import { cloneDeep, isEmpty } from 'lodash';
import { PureComponent } from 'react';
import { $DEVCOMP } from 'solid-js';
import { Point, Rectangle } from '../components/map/types';
import { state } from '../db-admin/health-legacy';
import { lat2tile, lon2tile, rectanglesIntersect } from '../lib/geo';
import { findStartTime } from '../lib/gpx';
import getUri, { intToGpxId, intToTrkptId } from '../lib/ids';
import { dbUrlToUserId } from '../lib/user-id';
import { get, getDocsByType, getFamily, put, putAll } from './lib';
export const emptyGpx: Gpx = {
@ -77,22 +80,23 @@ const prune = (
trkpt: number;
},
extensions: any,
docs: any[]
docs: any[],
to: string[]
) => {
if (typeof object === 'object') {
for (const key in object) {
if (
key === 'wpt' ||
key === 'rte' ||
key === 'rtept' ||
// key === 'rtept' ||
key === 'trk' ||
key === 'trkseg' ||
key === 'trkpt'
key === 'trkseg'
// key === 'trkpt'
) {
const subObjects = object[key];
for (const index in subObjects) {
const subId = { ...id };
if (key === 'trkpt') {
/* if (key === 'trkpt') {
// fix buggy times in GPX tracks
const normalId = intToTrkptId(
new Date(object[key][index].time).valueOf()
@ -101,10 +105,10 @@ const prune = (
normalId > previousIds.trk ? normalId : previousIds.trk + 1;
subId[key] = id;
previousIds.trk = id;
} else {
previousIds[key] = previousIds[key] + 1;
subId[key] = previousIds[key];
}
} else { */
previousIds[key] = previousIds[key] + 1;
subId[key] = previousIds[key];
/* } */
// console.log({
// caller: 'prune',
// id,
@ -123,94 +127,18 @@ const prune = (
docs.push({
_id: getUri(key, subId),
type: key,
to,
origin: dbUrlToUserId(state().remoteUrl),
doc: subObjects[index],
});
prune(subId, subObjects[index], previousIds, {}, docs);
prune(subId, subObjects[index], previousIds, {}, docs, to);
}
object[key] = undefined;
} else prune(id, object[key], previousIds, extensions, docs);
} else prune(id, object[key], previousIds, extensions, docs, to);
}
}
};
// const extensionsFromObject = (
// object: any,
// extensions = {
// viewport: { topLeft: <Point>{}, bottomRight: <Point>{} },
// bbox: {
// minLon: <number | undefined>undefined,
// minLat: <number | undefined>undefined,
// maxLon: <number | undefined>undefined,
// maxLat: <number | undefined>undefined,
// },
// }
// ) => {
// if (typeof object === 'object') {
// if ('$' in object) {
// const attributes = object.$;
// if ('lat' in attributes) {
// const lat = +attributes.lat;
// if (
// extensions.bbox.minLat === undefined ||
// lat < extensions.bbox.minLat
// ) {
// extensions.bbox.minLat = lat;
// }
// if (
// extensions.bbox.maxLat === undefined ||
// lat > extensions.bbox.maxLat
// ) {
// extensions.bbox.maxLat = lat;
// }
// }
// if ('lon' in attributes) {
// const lon = +attributes.lon;
// if (
// extensions.bbox.minLon === undefined ||
// lon < extensions.bbox.minLon
// ) {
// extensions.bbox.minLon = lon;
// }
// if (
// extensions.bbox.maxLon === undefined ||
// lon > extensions.bbox.maxLon
// ) {
// extensions.bbox.maxLon = lon;
// }
// }
// }
// for (const key in object) {
// extensionsFromObject(object[key], extensions);
// }
// }
// return extensions;
// };
// const extensionsFromGpx = (gpx: Gpx) => {
// const extensions = { ...gpx.extensions, ...extensionsFromObject(gpx) };
// gpx.extensions = undefined;
// if (
// extensions.bbox.maxLat !== undefined &&
// extensions.bbox.minLon !== undefined
// ) {
// extensions.viewport.topLeft = {
// x: lon2tile(extensions.bbox.minLon, 0),
// y: lat2tile(extensions.bbox.maxLat, 0),
// };
// }
// if (
// extensions.bbox.minLat !== undefined &&
// extensions.bbox.maxLon !== undefined
// ) {
// extensions.viewport.bottomRight = {
// x: lon2tile(extensions.bbox.maxLon, 0),
// y: lat2tile(extensions.bbox.minLat, 0),
// };
// }
// return extensions;
// };
const hasMissingTimestamps = (trk: Trk) => {
for (const trkseg of trk.trkseg!) {
for (const trkpt of trkseg.trkpt!) {
@ -222,13 +150,13 @@ const hasMissingTimestamps = (trk: Trk) => {
return false;
};
const convertTrkToRteWhenNeeded = (gpx: Gpx) => {
const convertTrkToRteWhenNeeded = (gpx: Gpx, forceImportAsRoutes: boolean) => {
if (gpx.trk === undefined) {
return;
}
const newTrks: Trk[] = [];
for (const trk of gpx.trk) {
if (hasMissingTimestamps(trk)) {
if (forceImportAsRoutes || hasMissingTimestamps(trk)) {
const rte = { ...trk, trkseg: undefined, rtept: [] };
for (const trkseg of trk.trkseg!) {
rte.rtept = rte.rtept.concat(trkseg.trkpt);
@ -246,7 +174,7 @@ const convertTrkToRteWhenNeeded = (gpx: Gpx) => {
export const pruneAndSaveImportedGpx = async (params: any) => {
console.log({ caller: 'pruneAndSaveImportedGpx', params });
const { id, gpx, tech } = params;
const { id, gpx, tech, forceImportAsRoutes } = params;
let gpxId: IdGpx;
let docs: any[] = [];
const extensions = {
@ -258,8 +186,9 @@ export const pruneAndSaveImportedGpx = async (params: any) => {
extensions: gpx.extensions,
},
};
convertTrkToRteWhenNeeded(gpx);
convertTrkToRteWhenNeeded(gpx, forceImportAsRoutes);
let previousGpx: Gpx | null = null;
let to: string[];
if (id === 'new') {
const currentDateTime = new Date().toISOString();
const startTime = new Date(findStartTime(gpx, currentDateTime));
@ -271,16 +200,26 @@ export const pruneAndSaveImportedGpx = async (params: any) => {
}
gpxId = { gpx: intToGpxId(startTime.valueOf()) };
docs = [
{ _id: getUri('gpx', gpxId), type: 'gpx', doc: gpx },
{
_id: getUri('gpx', gpxId),
type: 'gpx',
origin: dbUrlToUserId(state().remoteUrl),
doc: gpx,
// a new GPX isn't to...
},
{
_id: getUri('extensions', gpxId),
type: 'extensions',
origin: dbUrlToUserId(state().remoteUrl),
doc: {},
},
];
} else {
gpxId = getUri('gpx', id);
previousGpx = (await getGpx({ id })) ?? null;
if (previousGpx?.extensions?.to) {
to = previousGpx?.extensions?.to.split(/\s*,\s*/);
}
console.log({
caller: 'pruneAndSaveImportedGpx / previousGpx',
id,
@ -311,7 +250,7 @@ export const pruneAndSaveImportedGpx = async (params: any) => {
const trkId = getUri('trk', trkUri);
previousIds.trk = trkId.trk;
}
prune(gpxId, gpx, previousIds, extensions, docs);
prune(gpxId, gpx, previousIds, extensions, docs, to);
console.log({ caller: 'pruneAndSaveImportedGpx / pruned', docs });
try {
const result = await putAll(docs);
@ -423,9 +362,20 @@ export const getGpx = async (params: any) => {
}
//level 1 (extensions)
if (target !== undefined && row.doc.type === 'extensions') {
target.splice(1);
appendToArray(target.at(-1), row.doc.type, row.doc.doc);
target.push(row.doc.doc);
console.log({
caller: 'getGpx / extensions',
gpx,
row,
doc: row.doc.doc,
gpx_extensions: gpx?.extensions,
target,
});
gpx.extensions = row.doc.doc;
// target.splice(1);
// appendToArray(target.at(-1), row.doc.type, row.doc.doc);
// target.push(row.doc.doc);
}
//level 1 (others)
if (
@ -471,28 +421,72 @@ export const appendTrk = async (params: any) => {
export const putGpx = async (params: any) => {
let { id, gpx } = params;
if (id === 'new') {
const date = !!gpx.metadata.time ? new Date(gpx.metadata.time) : new Date();
id = getUri('gpx', {
gpx: intToGpxId(date.valueOf()),
try {
if (id === 'new' || !id) {
const date = !!gpx.metadata.time
? new Date(gpx.metadata.time)
: new Date();
id = getUri('gpx', {
gpx: intToGpxId(date.valueOf()),
});
}
let previousTo;
try {
previousTo = (await get(`${id}/4extensions`)).doc?.to;
} catch (error) {}
console.log({ caller: 'putGpx', params, id, gpx, previousTo });
const extensions = gpx?.extensions;
gpx.extensions = undefined;
gpx.wpt = undefined;
gpx.trk = undefined;
gpx.rte = undefined;
await put(id, 'gpx', (doc) => gpx, gpx);
if (extensions !== undefined) {
try {
await put(
`${id}/4extensions`,
'extensions',
(doc) => extensions,
extensions
);
} catch (error) {
console.error({
caller: 'putGpx / extensions',
error,
});
}
}
if (previousTo !== extensions?.to) {
const to = extensions?.to.split(/\s*,\s*/);
const family = (await getFamily(id, { include_docs: true })).rows.map(
(row: any) => {
return { ...row.doc, to };
}
);
console.log({
caller: 'putGpx / updateTo',
params,
id,
gpx,
previousTo,
family,
});
await db.bulkDocs(family);
}
} catch (error) {
console.error({
caller: 'putGpx',
params,
id,
gpx,
error,
});
}
console.log({ caller: 'putGpx', params, id, gpx });
const extensions = gpx?.extensions;
gpx.extensions = undefined;
gpx.wpt = undefined;
gpx.trk = undefined;
gpx.rte = undefined;
await put(id, 'gpx', (doc) => gpx, gpx);
if (extensions !== undefined) {
await put(
`${id}/4extensions`,
'extensions',
(doc) => extensions,
extensions
);
}
return id;
};

View File

@ -1,154 +1,105 @@
import _ from 'lodash';
import PouchDB from 'pouchdb';
import uri from '../lib/ids';
import { watchDbLegacy } from '../db-admin/health-legacy';
import { openDatabases } from '../db-admin/open';
import { toHex } from '../lib/to-hex';
import {
getAccountById,
getAccounts,
initialAccount,
putAccount,
} from './account';
import changeHandler from './change-handler';
import { getSettings, putSettings } from './settings';
const dbDefinitionId = uri('dbdef', {});
const currentDbDefinition = {
_id: dbDefinitionId,
type: dbDefinitionId,
def: { version: '0.000001' },
};
declare global {
var localDb: any;
var db: any;
var dbReady: boolean;
var currentAccount: any;
var sync: any;
}
export const initDb = async (params: any) => {
export const initDb = async () => {
console.log({ caller: 'initDb' });
if (globalThis.localDb === undefined) {
globalThis.localDb = new PouchDB('$local_dyomedea$', {
auto_compaction: true,
revs_limit: 10,
});
}
globalThis.dbReady = false;
const accounts = await getAccounts();
console.log({ caller: 'initDb', accounts });
await openDatabases();
if (accounts.length === 0) {
accounts[0] = initialAccount;
await putAccount({ id: initialAccount.id, account: initialAccount });
}
globalThis.currentAccount = await openDatabases();
const currentAccount = globalThis.currentAccount;
const settings = await getSettings();
let currentAccount = getAccountById(accounts, settings.currentAccountId);
if (currentAccount === undefined) {
settings.currentAccountId = accounts[0].id;
await putSettings({ settings });
currentAccount = accounts[0];
}
if (currentAccount.remoteDbServer) {
const url = `${currentAccount.remoteDbServer}/userdb-${toHex(
currentAccount.remoteDbUser
)}`;
console.log({ caller: 'initDb', settings, currentAccount });
if (globalThis.db === undefined) {
globalThis.db = new PouchDB(currentAccount.localDb, {
auto_compaction: false,
});
}
const db = globalThis.db;
var previousDbDefinition = {
_id: dbDefinitionId,
type: dbDefinitionId,
def: { version: '0' },
};
try {
previousDbDefinition = await db.get(dbDefinitionId);
} catch (error: any) {
if (error.status !== 404) {
console.log(
`Unexpected error fetching db definition: ${JSON.stringify(error)}`
);
return;
}
}
if (previousDbDefinition.def.version < currentDbDefinition.def.version) {
previousDbDefinition.def = currentDbDefinition.def;
db.put(previousDbDefinition);
// TODO: support migrations
}
//await await db.compact();
if (currentAccount.remoteDbServer) {
const url = `${currentAccount.remoteDbServer}/userdb-${toHex(
currentAccount.remoteDbUser
)}`;
const remoteDb = new PouchDB(url, {
auth: {
username: currentAccount.remoteDbUser,
password: currentAccount.remoteDbPassword,
},
skip_setup: true,
});
const sync = PouchDB.sync(db, remoteDb, {
live: true,
retry: true,
})
.on('change', function (info) {
// handle change
console.log({ caller: 'Sync / change', info });
})
.on('paused', function (err) {
// replication paused (e.g. replication up to date, user went offline)
console.log({ caller: 'Sync / paused', err });
})
.on('active', function () {
// replicate resumed (e.g. new changes replicating, user went back online)
console.log({ caller: 'Sync / active' });
})
.on('denied', function (err) {
// a document failed to replicate (e.g. due to permissions)
console.error({ caller: 'Sync / denied', err });
})
.on('complete', function (info) {
// handle complete
console.log({ caller: 'Sync / complete', info });
})
.on('error', function (err) {
// handle error
console.error({ caller: 'Sync / error', err });
const remoteDb = new PouchDB(url, {
auth: {
username: currentAccount.remoteDbUser,
password: currentAccount.remoteDbPassword,
},
skip_setup: true,
});
globalThis.remoteDb = remoteDb;
globalThis.sync = PouchDB.sync(db, remoteDb, {
live: true,
retry: true,
});
}
// if (globalThis.sync) {
// globalThis.sync
// .on('change', function (info) {
// // handle change
// console.log({ caller: 'Sync / change', info });
// })
// .on('paused', function (err) {
// // replication paused (e.g. replication up to date, user went offline)
// console.log({ caller: 'Sync / paused', err });
// })
// .on('active', function () {
// // replicate resumed (e.g. new changes replicating, user went back online)
// console.log({ caller: 'Sync / active' });
// })
// .on('denied', function (err) {
// // a document failed to replicate (e.g. due to permissions)
// console.error({ caller: 'Sync / denied', err });
// })
// .on('complete', function (info) {
// // handle complete
// console.log({ caller: 'Sync / complete', info });
// })
// .on('error', function (err) {
// // handle error
// console.error({ caller: 'Sync / error', err });
// });
// }
// console.log({ caller: 'initDb / before db.changes' });
const changes = db
.changes({ since: 'now', live: true, include_docs: false })
.on('change', changeHandler)
.on('complete', (info: any) => {
console.log({ caller: 'changes / complete', info });
})
.on('error', (error: any) => {
console.log({ caller: 'changes / complete', error });
});
const localDbChanges = localDb
.changes({ since: 'now', live: true, include_docs: false })
.on('change', changeHandler)
.on('complete', (info: any) => {
console.log({ caller: 'localDb changes / complete', info });
})
.on('error', (error: any) => {
console.log({ caller: 'localDb changes / complete', error });
});
// console.log({ caller: 'initDb / back from db.changes', changes });
// changes.cancel();
globalThis.dbReady = true;
watchDbLegacy();
console.log({ caller: 'initDb / done' });
return;
}
// console.log({ caller: 'initDb / before db.changes' });
const changes = db
.changes({ since: 'now', live: true, include_docs: false })
.on('change', changeHandler)
.on('complete', (info: any) => {
console.log({ caller: 'changes / complete', info });
})
.on('error', (error: any) => {
console.log({ caller: 'changes / complete', error });
});
const localDbChanges = localDb
.changes({ since: 'now', live: true, include_docs: false })
.on('change', changeHandler)
.on('complete', (info: any) => {
console.log({ caller: 'localDb changes / complete', info });
})
.on('error', (error: any) => {
console.log({ caller: 'localDb changes / complete', error });
});
// console.log({ caller: 'initDb / back from db.changes', changes });
// changes.cancel();
globalThis.dbReady = true;
};

View File

@ -1,299 +0,0 @@
import { initDb } from '.';
import uri from '../lib/ids';
import { getDocsByType, getFamily } from './lib';
import { putNewRte } from './rte';
import { putNewRtept } from './rtept';
import { putNewTrk } from './trk';
import { putNewTrkpt } from './trkpt';
import { putNewTrkseg } from './trkseg';
import { putNewWpt } from './wpt';
declare global {
var db: any;
}
const originalDateNow = globalThis.Date.now;
describe('getFamily', () => {
beforeEach(async () => {
await initDb({});
globalThis.Date.now = () => 0;
});
afterEach(async () => {
await db.destroy();
db = undefined;
globalThis.Date.now = originalDateNow;
});
test('returns two rows after a gpx and a track have been inserted.', async () => {
await putNewTrk();
const allDocs: any = await getFamily('gpx/');
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"id": "gpx/4320000000000000/3trk/000000",
"key": "gpx/4320000000000000/3trk/000000",
"value": Object {
"rev": "1-4c114f3ae0073151e4082ff1d220c2a4",
},
},
],
"total_rows": 4,
}
`);
});
test('also returns the docs if required.', async () => {
await putNewTrk();
const allDocs: any = await getFamily('gpx/', {
include_docs: true,
});
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"doc": Object {
"_id": "gpx/4320000000000000",
"_rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
"doc": Object {
"$": Object {
"creator": "dyomedea version 0.000002",
"version": "1.1",
"xmlns": "http://www.topografix.com/GPX/1/1",
"xmlns:dyo": "http://xmlns.dyomedea.com/",
"xmlns:gpxtpx": "http://www.garmin.com/xmlschemas/TrackPointExtension/v1",
"xmlns:gpxx": "http://www.garmin.com/xmlschemas/GpxExtensions/v3",
"xmlns:wptx1": "http://www.garmin.com/xmlschemas/WaypointExtension/v1",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/WaypointExtension/v1 http://www8.garmin.com/xmlschemas/WaypointExtensionv1.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd",
},
"metadata": Object {
"time": "1970-01-01T00:00:00.000Z",
},
},
"type": "gpx",
},
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"doc": Object {
"_id": "gpx/4320000000000000/3trk/000000",
"_rev": "1-4c114f3ae0073151e4082ff1d220c2a4",
"doc": Object {
"number": 0,
},
"type": "trk",
},
"id": "gpx/4320000000000000/3trk/000000",
"key": "gpx/4320000000000000/3trk/000000",
"value": Object {
"rev": "1-4c114f3ae0073151e4082ff1d220c2a4",
},
},
],
"total_rows": 4,
}
`);
});
test('returns three rows after a gpx and a track segment have been inserted.', async () => {
await putNewTrkseg();
const allDocs: any = await getFamily('gpx/');
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"id": "gpx/4320000000000000/3trk/000000",
"key": "gpx/4320000000000000/3trk/000000",
"value": Object {
"rev": "1-4c114f3ae0073151e4082ff1d220c2a4",
},
},
Object {
"id": "gpx/4320000000000000/3trk/000000/000000",
"key": "gpx/4320000000000000/3trk/000000/000000",
"value": Object {
"rev": "1-68d7de0569de570229ea9f9e1a0b13cb",
},
},
],
"total_rows": 5,
}
`);
});
test('returns four rows after a gpx and a track point have been inserted.', async () => {
await putNewTrkpt();
const allDocs: any = await getFamily('gpx/');
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"id": "gpx/4320000000000000/3trk/000000",
"key": "gpx/4320000000000000/3trk/000000",
"value": Object {
"rev": "1-4c114f3ae0073151e4082ff1d220c2a4",
},
},
Object {
"id": "gpx/4320000000000000/3trk/000000/000000",
"key": "gpx/4320000000000000/3trk/000000/000000",
"value": Object {
"rev": "1-68d7de0569de570229ea9f9e1a0b13cb",
},
},
Object {
"id": "gpx/4320000000000000/3trk/000000/000000/000000",
"key": "gpx/4320000000000000/3trk/000000/000000/000000",
"value": Object {
"rev": "1-7d917d1f3505fe0e3092161694904b53",
},
},
],
"total_rows": 6,
}
`);
});
test('returns two rows after a gpx and a waypoint have been inserted.', async () => {
await putNewWpt();
const allDocs: any = await getFamily('gpx/');
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"id": "gpx/4320000000000000/1wpt/000000",
"key": "gpx/4320000000000000/1wpt/000000",
"value": Object {
"rev": "1-c6793365fd0dd56236ab8734a41c7ae7",
},
},
],
"total_rows": 4,
}
`);
});
test('returns two rows after a gpx and a route have been inserted.', async () => {
await putNewRte();
const allDocs: any = await getFamily('gpx/');
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"id": "gpx/4320000000000000/2rte/000000",
"key": "gpx/4320000000000000/2rte/000000",
"value": Object {
"rev": "1-2ca14f512a9c83f5a239389e580befce",
},
},
],
"total_rows": 4,
}
`);
});
test('returns three rows after a gpx and a route point have been inserted.', async () => {
await putNewRtept();
const allDocs: any = await getFamily('gpx/');
expect(allDocs).toMatchInlineSnapshot(`
Object {
"offset": 0,
"rows": Array [
Object {
"id": "gpx/4320000000000000",
"key": "gpx/4320000000000000",
"value": Object {
"rev": "1-49baa096ec0c89962f2cafd3ff50b80b",
},
},
Object {
"id": "gpx/4320000000000000/2rte/000000",
"key": "gpx/4320000000000000/2rte/000000",
"value": Object {
"rev": "1-2ca14f512a9c83f5a239389e580befce",
},
},
Object {
"id": "gpx/4320000000000000/2rte/000000/000000",
"key": "gpx/4320000000000000/2rte/000000/000000",
"value": Object {
"rev": "1-0f4064d20f6bfac3888a7758851fbac5",
},
},
],
"total_rows": 5,
}
`);
});
});
describe('getDocsByType', () => {
beforeEach(async () => {
await initDb({});
globalThis.Date.now = () => 0;
});
afterEach(async () => {
await db.destroy();
db = undefined;
globalThis.Date.now = originalDateNow;
});
test('gets the rte amongst other docs', async () => {
await putNewRtept();
const rtes = await getDocsByType('rte');
expect(rtes).toMatchInlineSnapshot(`
Array [
Object {
"_id": "gpx/4320000000000000/2rte/000000",
"_rev": "1-2ca14f512a9c83f5a239389e580befce",
"doc": Object {
"number": 0,
},
"type": "rte",
},
]
`);
});
});

View File

@ -1,4 +1,7 @@
import { cloneDeep } from 'lodash';
import { state } from '../db-admin/health-legacy';
import { getParentId } from '../lib/docuri';
import { dbUrlToUserId } from '../lib/user-id';
declare global {
var localDb: any;
@ -18,13 +21,24 @@ export const put = async (
try {
current = await targetDb.get(_id);
} catch {
current = { _rev: undefined, doc: cloneDeep(defaultDoc) };
const parentId = getParentId(_id);
let to;
try {
const parent = await db.get(parentId);
// console.log({ caller: 'put', parent });
to = parent.to;
} catch {}
current = { _rev: undefined, to, doc: cloneDeep(defaultDoc) };
}
try {
putDoc = {
_id,
_rev: current._rev,
type,
to: current.to,
origin:
current.origin ??
(state().remoteUrl ? dbUrlToUserId(state().remoteUrl) : undefined),
doc: update(current.doc),
};
await targetDb.put(putDoc);
@ -50,16 +64,6 @@ export const getFamily = async (
endkey,
...options,
});
if (allDocs.rows.at(-1).id > endkey) {
console.error({
caller: 'getFamilly',
key,
endkey,
options,
local,
allDocs,
});
}
return allDocs;
};

View File

@ -1,4 +1,17 @@
import { putNewRte } from './rte';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import shell from 'shelljs';
import PouchDB from 'pouchdb';
import { getRte, putNewRte, putRte } from './rte';
import { put } from './lib';
import { emptyWpt } from './wpt';
import { sleep } from '../lib/async-wait';
import { debounce, memoize, property, wrap } from 'lodash';
import memoizee from 'memoizee';
const test = it;
const jest = vi;
declare global {
var db: any;
@ -45,3 +58,112 @@ describe('The rte module', () => {
expect(id).toEqual({ gpx: 4320000000000000, rte: 0 });
});
});
describe('The rte module with a real db', () => {
beforeEach(async () => {
globalThis.db = new PouchDB('dyomedea', {
auto_compaction: false,
});
globalThis.Date.now = () => 0;
});
afterEach(async () => {
try {
await db.destroy();
} catch (err) {
// console.error(err);
await shell.exec('rm -rf $*$');
}
globalThis.db = undefined;
globalThis.dbReady = false;
globalThis.Date.now = originalDateNow;
});
it('can write and read a rte', async () => {
const id = 'whatever';
const rte: Rte = {
name: 'A new route',
};
const rtePut = await putRte({ id, rte });
expect(rtePut).toEqual(rte);
const rteGet = await getRte({ id });
expect(rteGet).toEqual(rte);
});
it('can write and read a rte with rtepts', async () => {
const id = 'whatever';
const rte: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 0, lon: 0 },
},
{
$: { lat: 1, lon: 1 },
},
],
};
const rtePut = await putRte({ id, rte });
expect(rtePut).toEqual(rte);
const rteGet = await getRte({ id });
expect(rteGet).toEqual(rte);
});
it('can read external rtepts ', async () => {
const idRte = 'gpx/4320836410265485/2rte/000034';
const idRtept = 'gpx/4320836410265485/2rte/000034/000035';
const rtept3: Wpt = {
$: { lat: 3, lon: 3 },
};
const rte0: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const rte1: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
rtept3,
],
};
const rtePut = await putRte({ id: idRte, rte: rte0 });
expect(rtePut).toEqual(rte0);
await put(idRtept, 'rtept', () => rtept3, emptyWpt);
expect(await getRte({ id: idRte })).toEqual(rte1);
});
// it('debounces correctly by param ', async () => {
// let values = [0, 1, 2, 3, 4, 5];
// const decrement = (params: any) => {
// const { id } = params;
// //await sleep(1);
// values[2] = values[2] - 1;
// };
// const debounceByParam = (targetFunc, resolver, ...debounceParams) =>
// wrap(
// memoize(() => debounce(targetFunc, ...debounceParams), resolver),
// (getMemoizedFunc, ...params) => getMemoizedFunc(...params)(...params)
// );
// const debouncedDecrement = debounce(decrement, 100);
// debouncedDecrement({ id: 2 });
// debouncedDecrement({ id: 2 });
// debouncedDecrement({ id: 5 });
// debouncedDecrement({ id: 2 });
// debouncedDecrement({ id: 5 });
// debouncedDecrement({ id: 2 });
// debouncedDecrement({ id: 2 });
// debouncedDecrement({ id: 2 });
// await sleep(2000);
// expect(values).toEqual([0, 1, 1, 3, 4, 4]);
// });
});

View File

@ -1,5 +1,6 @@
import { cloneDeep, debounce, memoize, property, wrap } from 'lodash';
import getUri from '../lib/ids';
import { appendToArray, putNewGpx } from './gpx';
import { putNewGpx } from './gpx';
import { getFamily, put } from './lib';
export const emptyRte: Rte = {
@ -32,42 +33,90 @@ export const putNewRte = async (id?: IdRte | IdGpx) => {
return finalId as IdRte;
};
export const getRte = async (params: any) => {
// See https://stackoverflow.com/questions/28787436/debounce-a-function-with-argument
export const debounceByParam = (
targetFunc: (params: any) => any,
resolver: (params: any) => any,
...debounceParams: any
) =>
wrap(
memoize(() => debounce(targetFunc, ...debounceParams), resolver),
(getMemoizedFunc, ...params) => getMemoizedFunc(...params)(...params)
);
export const compactRteOrTrkseg = async (params: any) => {
const { getDocs } = params;
const { docs, rte, trkseg } = await getDocs(params);
if (docs.rows.length > 1) {
const compactedDocs = docs.rows.map((row: any) => {
if (['rte', 'trkseg'].includes(row.doc.type)) {
return { ...row.doc, doc: rte || trkseg };
}
return { ...row.doc, doc: undefined, _deleted: true };
});
console.log({
caller: 'compactRteOrTrkseg',
params,
compactedDocs,
firstDoc: compactedDocs[0].doc,
firstDocWpt: compactedDocs[0].doc.trkpt[0],
date: new Date().toISOString(),
});
await db.bulkDocs(compactedDocs);
}
};
export const compactRteOrTrksegDebounced = debounceByParam(
compactRteOrTrkseg,
property('id'),
60 * 60 * 1000 * (1 + Math.random())
);
export const getRteDocs: ({
id,
}: {
id: string;
}) => Promise<{ docs: any; rte: Rte }> = async (params) => {
const { id } = params;
const docs = await getFamily(id, { include_docs: true });
let target: any[];
let rte: Rte | undefined = undefined;
docs.rows.every((row: any) => {
// level 0
if (row.doc.type === 'rte') {
if (!!rte) {
console.error({
caller: 'getRte',
id,
row,
target,
rte,
});
return false; // Hack to stop if getFamily fails
}
target = [row.doc.doc];
rte = row.doc.doc;
let rte: Rte;
if (docs.rows.length === 1) {
rte = docs.rows[0].doc.doc;
} else {
rte = cloneDeep(docs.rows[0].doc.doc);
if (!rte.rtept) {
rte.rtept = [];
}
//level 1
if (row.doc.type === 'rtept') {
target.splice(1);
row.doc.doc.id = row.doc._id;
appendToArray(target.at(-1), row.doc.type, row.doc.doc);
target.push(row.doc.doc);
}
return true;
});
docs.rows.slice(1).forEach((row: any) => {
rte.rtept.push(row.doc.doc);
});
}
// console.log({
// caller: 'getRteDocs',
// id,
// docs,
// nbRteptIn: docs.rows[0].doc.doc.rtept?.length,
// nbRteptTotal: rte?.rtept?.length,
// });
return { docs, rte };
};
export const getRte = async (params: any) => {
const { id } = params;
const { docs, rte } = await getRteDocs(params);
if (docs.rows.length > 1) {
console.log({
caller: 'getRte compactRteOrTrksegDebounced required',
id,
});
compactRteOrTrksegDebounced({ id, getDocs: getRteDocs });
}
return rte;
};
export const putRte = async (params: any) => {
const { id, rte } = params;
rte.rtept = undefined;
await put(id, 'rte', (doc) => rte, rte);
return rte;
};

View File

@ -1,4 +1,14 @@
import { putNewRtept } from './rtept';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import shell from 'shelljs';
import PouchDB from 'pouchdb';
import { getRte, compactRteOrTrksegDebounced, putRte } from './rte';
import { putRtept } from './rtept';
import { get, getFamily, put } from './lib';
import { emptyWpt } from './wpt';
const test = it;
const jest = vi;
declare global {
var db: any;
@ -8,51 +18,172 @@ declare global {
const originalDb = globalThis.db;
const originalDateNow = globalThis.Date.now;
describe('The rtept module', () => {
beforeEach(() => {
globalThis.db = { put: jest.fn() };
describe('The rtept module with a real db', () => {
beforeEach(async () => {
globalThis.db = new PouchDB('dyomedea', {
auto_compaction: false,
});
globalThis.Date.now = () => 0;
});
afterEach(() => {
globalThis.db = originalDb;
globalThis.Date.now = originalDateNow;
});
test('db.put() a new rtept when required', async () => {
putNewRtept({ gpx: 0, rte: 0, rtept: 0 });
await expect(globalThis.db.put).toBeCalledWith({
_id: 'gpx/0000000000000000/2rte/000000/000000',
_rev: undefined,
doc: {
$: { lat: 0, lon: 0 },
ageofdgpsdata: undefined,
cmt: undefined,
desc: undefined,
dgpsid: undefined,
ele: undefined,
extensions: undefined,
fix: undefined,
geoidheight: undefined,
hdop: undefined,
link: undefined,
magvar: undefined,
name: undefined,
pdop: undefined,
sat: undefined,
src: undefined,
sym: undefined,
time: undefined,
type: undefined,
vdop: undefined,
},
type: 'rtept',
vi.mock('compactRteOrTrksegDebounced', () => {
console.log({ caller: 'mocked compactRteOrTrksegDebounced' });
});
});
test('db.put() generates an id for the rtept if needed', async () => {
const id = await putNewRtept({ gpx: 0 });
expect(id).toEqual({ gpx: 0, rte: 0, rtept: 0 });
afterEach(async () => {
try {
await db.destroy();
} catch (err) {
// console.error(err);
await shell.exec('rm -rf $*$');
}
globalThis.db = undefined;
globalThis.dbReady = false;
globalThis.Date.now = originalDateNow;
});
test('db.put() generates ids for both gpx and rte if needed', async () => {
const id = await putNewRtept();
expect(id).toEqual({ gpx: 4320000000000000, rte: 0, rtept: 0 });
it('can write a rtept inside a rte', async () => {
const idRte = 'whatever';
const rtept: Wpt = {
$: { lat: 2, lon: 2 },
};
const rte0: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 0, lon: 0 },
},
{
$: { lat: 1, lon: 1 },
},
],
};
const rte1: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 0, lon: 0 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const rtePut = await putRte({ id: idRte, rte: rte0 });
expect(rtePut).toEqual(rte0);
const rtePutRtept = await putRtept({ id: idRte, index: 1, wpt: rtept });
const rteGetRtept = await getRte({ id: idRte });
expect(rteGetRtept).toEqual(rte1);
});
it('can write a rtept outside a rte', async () => {
const idRte = 'gpx/4320836410265485/2rte/000034';
const idRtept = 'gpx/4320836410265485/2rte/000034/000035';
const rtept3: Wpt = {
$: { lat: 3, lon: 3 },
};
const rtept4: Wpt = {
$: { lat: 4, lon: 4 },
};
const rte0: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const rte1: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
rtept3,
],
};
const rte2: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
rtept4,
],
};
const rtePut = await putRte({ id: idRte, rte: rte0 });
expect(rtePut).toEqual(rte0);
await put(idRtept, 'rtept', () => rtept3, emptyWpt);
expect(await getRte({ id: idRte })).toEqual(rte1);
await putRtept({
id: idRte,
index: 2,
wpt: rtept4,
});
expect((await getFamily(idRte)).rows.length).toEqual(2);
expect(await getRte({ id: idRte })).toEqual(rte2);
expect((await get(idRtept)).doc).toEqual(rtept4);
});
it('can write a rtept outside a rte with a negative index', async () => {
const idRte = 'gpx/4320836410265485/2rte/000034';
const idRtept = 'gpx/4320836410265485/2rte/000034/000035';
const rtept3: Wpt = {
$: { lat: 3, lon: 3 },
};
const rtept4: Wpt = {
$: { lat: 4, lon: 4 },
};
const rte0: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const rte1: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
rtept3,
],
};
const rte2: Rte = {
name: 'A new route',
rtept: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
rtept4,
],
};
const rtePut = await putRte({ id: idRte, rte: rte0 });
await put(idRtept, 'rtept', () => rtept3, emptyWpt);
await putRtept({
id: idRte,
index: -1,
wpt: rtept4,
});
expect(await getRte({ id: idRte })).toEqual(rte2);
expect((await get(idRtept)).doc).toEqual(rtept4);
});
});

View File

@ -1,6 +1,6 @@
import { getRteDocs, putRte } from './rte';
import getUri from '../lib/ids';
import { put } from './lib';
import { putNewRte } from './rte';
export const emptyRtept: Wpt = {
$: { lat: 0, lon: 0 },
@ -25,27 +25,27 @@ export const emptyRtept: Wpt = {
extensions: undefined,
};
export const putNewRtept = async (id?: IdGpx | IdRte | IdRtept) => {
let finalId = { ...id };
if (!('rtept' in finalId)) {
const rteId = await putNewRte(id);
finalId = { ...rteId, rtept: 0 };
}
const uri = getUri('rtept', finalId);
await put(
uri,
'rtept',
(rtept) => {
return rtept;
},
emptyRtept
);
return finalId as IdRtept;
};
export const putRtept = async (params: any) => {
const { id, rtept } = params;
rtept.id = undefined;
await put(id, 'rtept', (doc) => rtept, rtept);
return rtept;
const { id, index, wpt } = params;
const { docs } = await getRteDocs({ id: id });
const rte = docs.rows[0].doc.doc;
const nbRteptInRte = rte && rte.rtept ? rte.rtept.length : 0;
const nbRteptOutRte = docs.rows.length - 1;
const nbRtept = nbRteptInRte + nbRteptOutRte;
const positiveIndex = index >= 0 ? index : nbRtept + index;
// console.log({
// caller: 'putRtept',
// nbRteptInRte,
// nbRteptOutRte,
// nbRtept,
// positiveIndex,
// });
if (positiveIndex < nbRteptInRte) {
rte.rtept[positiveIndex] = wpt;
await putRte({ id, rte });
} else {
const reptId = docs.rows[1 + positiveIndex - nbRteptInRte].doc._id;
await put(reptId, 'rtept', () => wpt, emptyRtept);
}
return wpt;
};

View File

@ -1,47 +0,0 @@
import { putNewTrk } from './trk';
declare global {
var db: any;
var dbReady: boolean;
}
const originalDb = globalThis.db;
const originalDateNow = globalThis.Date.now;
describe('The trk module', () => {
beforeEach(() => {
globalThis.db = { put: jest.fn() };
globalThis.Date.now = () => 0;
});
afterEach(() => {
globalThis.db = originalDb;
globalThis.Date.now = originalDateNow;
});
test('db.put() a new trk when required', async () => {
putNewTrk({ gpx: 1, trk: 2 });
await expect(globalThis.db.put).toBeCalledWith({
_id: 'gpx/0000000000000001/3trk/000002',
_rev: undefined,
doc: {
cmt: undefined,
desc: undefined,
extensions: undefined,
link: undefined,
name: undefined,
number: 0,
src: undefined,
trkseg: undefined,
type: undefined,
},
type: 'trk',
});
});
test('db.put() generates an id for the trk if needed', async () => {
const id = await putNewTrk({ gpx: 2 });
expect(id).toEqual({ gpx: 2, trk: 0});
});
test('db.put() generates ids for both gpx and trk if needed', async () => {
const id = await putNewTrk();
expect(id).toEqual({ gpx: 4320000000000000, trk: 0});
});
});

View File

@ -1,4 +1,14 @@
import { putNewTrkpt } from './trkpt';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import shell from 'shelljs';
import PouchDB from 'pouchdb';
import { getTrkseg, getTrksegDocs, putTrkseg } from './trkseg';
import { putTrkpt } from './trkpt';
import { get, getFamily, put } from './lib';
import { emptyWpt } from './wpt';
const test = it;
const jest = vi;
declare global {
var db: any;
@ -8,72 +18,180 @@ declare global {
const originalDb = globalThis.db;
const originalDateNow = globalThis.Date.now;
describe('The trkpt module', () => {
beforeEach(() => {
globalThis.db = { put: jest.fn() };
describe('The trkpt module with a real db', () => {
beforeEach(async () => {
globalThis.db = new PouchDB('dyomedea', {
auto_compaction: false,
});
globalThis.Date.now = () => 0;
// vi.mock('./rte', async () => {
// const originalModule = await vi.importActual('./rte');
// return {
// ...originalModule,
// compactTrksegOrTrksegDebounced: () => {
// console.log('mocked compactTrksegOrTrksegDebounced');
// },
// };
// });
});
afterEach(() => {
globalThis.db = originalDb;
afterEach(async () => {
try {
await db.destroy();
} catch (err) {
// console.error(err);
await shell.exec('rm -rf $*$');
}
globalThis.db = undefined;
globalThis.dbReady = false;
globalThis.Date.now = originalDateNow;
});
test('db.put() a new trkpt when required', async () => {
putNewTrkpt({
gpx: 1,
trk: 2,
trkseg: 3,
trkpt: 4,
});
await expect(globalThis.db.put).toBeCalledWith({
_id: 'gpx/0000000000000001/3trk/000002/000003/000004',
_rev: undefined,
doc: {
$: { lat: 0, lon: 0 },
ageofdgpsdata: undefined,
cmt: undefined,
desc: undefined,
dgpsid: undefined,
ele: undefined,
extensions: {
'dyo:accuracy': undefined,
'dyo:batterylevel': undefined,
'dyo:course': undefined,
'dyo:speed': undefined,
'dyo:useragent': undefined,
it('can write a trkpt inside a trkseg', async () => {
const idTrkseg = 'gpx/4320836410265485/2trkseg/000034';
const trkpt: Wpt = {
$: { lat: 2, lon: 2 },
};
const trkseg0: Trkseg = {
trkpt: [
{
$: { lat: 0, lon: 0 },
},
fix: undefined,
geoidheight: undefined,
hdop: undefined,
link: undefined,
magvar: undefined,
name: undefined,
pdop: undefined,
sat: undefined,
src: undefined,
sym: undefined,
time: undefined,
type: undefined,
vdop: undefined,
},
type: 'trkpt',
{
$: { lat: 1, lon: 1 },
},
],
};
const trkseg1: Trkseg = {
trkpt: [
{
$: { lat: 0, lon: 0 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const trksegPut = await putTrkseg(idTrkseg, trkseg0);
expect(trksegPut).toEqual(idTrkseg);
const trksegPutTrksegpt = await putTrkpt({
id: idTrkseg,
index: 1,
wpt: trkpt,
});
const trksegGetTrksegpt = await getTrkseg({ id: idTrkseg });
expect(trksegGetTrksegpt).toEqual(trkseg1);
});
test('db.put() generates an id for the trk if needed', async () => {
const id = await putNewTrkpt({ gpx: 5 });
expect(id).toEqual({
gpx: 5,
trk: 0,
trkseg: 0,
trkpt: 0,
it('can write a trkpt outside a trkseg', async () => {
const idTrkseg = 'gpx/4320836410265485/2trkseg/000034';
const idTrksegpt = 'gpx/4320836410265485/2trkseg/000034/000035';
const trkpt3: Wpt = {
$: { lat: 3, lon: 3 },
};
const trkpt4: Wpt = {
$: { lat: 4, lon: 4 },
};
const trkseg0: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const trkseg1: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt3,
],
};
const trkseg2: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt4,
],
};
const trksegPut = await putTrkseg(idTrkseg, trkseg0);
expect(trksegPut).toEqual(idTrkseg);
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg0);
await put(idTrksegpt, 'trkpt', () => trkpt3, emptyWpt);
const { trkseg, docs } = await getTrksegDocs({ id: idTrkseg });
console.log({
caller: 'test',
trkptIn: JSON.stringify(docs.rows[0].doc.doc.trkpt),
});
});
test('db.put() generates ids for both gpx and trk if needed', async () => {
const id = await putNewTrkpt();
expect(id).toEqual({
gpx: 4320000000000000,
trk: 0,
trkseg: 0,
trkpt: 0,
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg1);
await putTrkpt({
id: idTrkseg,
index: 2,
wpt: trkpt4,
});
expect((await getFamily(idTrkseg)).rows.length).toEqual(2);
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg2);
expect((await get(idTrksegpt)).doc).toEqual(trkpt4);
});
it('can write a trkpt outside a trkseg with a negative index', async () => {
const idTrkseg = 'gpx/4320836410265485/2trkseg/000034';
const idTrksegpt = 'gpx/4320836410265485/2trkseg/000034/000035';
const trkpt3: Wpt = {
$: { lat: 3, lon: 3 },
};
const trkpt4: Wpt = {
$: { lat: 4, lon: 4 },
};
const trkseg0: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const trkseg1: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt3,
],
};
const trkseg2: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt4,
],
};
const trksegPut = await putTrkseg(idTrkseg, trkseg0);
await put(idTrksegpt, 'trkpt', () => trkpt3, emptyWpt);
await putTrkpt({
id: idTrkseg,
index: -1,
wpt: trkpt4,
});
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg2);
expect((await get(idTrksegpt)).doc).toEqual(trkpt4);
});
});

View File

@ -1,6 +1,7 @@
import getUri, { intToTrkptId } from '../lib/ids';
import { put } from './lib';
import { putNewTrkseg } from './trkseg';
import { getTrksegDocs, putTrkseg } from './trkseg';
import { emptyWpt } from './wpt';
const emptyTrkpt: Wpt = {
$: { lat: 0, lon: 0 },
@ -31,28 +32,28 @@ const emptyTrkpt: Wpt = {
},
};
export const putNewTrkpt = async (id?: IdTrk | IdGpx | IdTrkseg | IdTrkpt) => {
let finalId = { ...id };
if (!('trkpt' in finalId)) {
const trksegId = await putNewTrkseg(id);
finalId = { ...trksegId, trkpt: intToTrkptId(Date.now()) };
}
const uri = getUri('trkpt', finalId);
await put(
uri,
'trkpt',
(trkpt) => {
return trkpt;
},
emptyTrkpt
);
return finalId;
};
export const putTrkpt = async (params: any) => {
const { id, trkpt } = params;
trkpt.id = undefined;
await put(id, 'trkpt', (doc) => trkpt, trkpt);
return trkpt;
};
const { id, index, wpt } = params;
const { docs } = await getTrksegDocs({ id: id });
const trkseg = docs.rows[0].doc.doc;
const nbWptInTrkseg = trkseg && trkseg.trkpt ? trkseg.trkpt.length : 0;
const nbWptOutTrkseg = docs.rows.length - 1;
const nbWpt = nbWptInTrkseg + nbWptOutTrkseg;
const positiveIndex = index >= 0 ? index : nbWpt + index;
console.log({
caller: 'putTrkpt',
nbWptInTrkseg,
nbWptOutTrkseg,
nbWpt,
positiveIndex,
trkpt: JSON.stringify(trkseg.trkpt),
});
if (positiveIndex < nbWptInTrkseg) {
trkseg.trkpt[positiveIndex] = wpt;
await putTrkseg(id, trkseg);
} else {
const trkptId = docs.rows[1 + positiveIndex - nbWptInTrkseg].doc._id;
await put(trkptId, 'trkpt', () => wpt, emptyWpt);
}
return wpt;
};

View File

@ -1,4 +1,18 @@
import { putNewTrkseg } from './trkseg';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import shell from 'shelljs';
import PouchDB from 'pouchdb';
import { appendTrkpt, getTrkseg, getTrksegDocs, putTrkseg } from './trkseg';
import getUri from '../lib/ids';
import { put } from './lib';
import { emptyWpt } from './wpt';
import { compactRteOrTrkseg } from './rte';
import { sleep } from '../lib/async-wait';
const test = it;
const jest = vi;
declare global {
var db: any;
@ -8,33 +22,171 @@ declare global {
const originalDb = globalThis.db;
const originalDateNow = globalThis.Date.now;
describe('The trkseg module', () => {
beforeEach(() => {
globalThis.db = { put: jest.fn() };
describe('The trkseg module with a real db', () => {
beforeEach(async () => {
globalThis.db = new PouchDB('dyomedea', {
auto_compaction: false,
});
globalThis.Date.now = () => 0;
});
afterEach(() => {
globalThis.db = originalDb;
afterEach(async () => {
try {
await db.destroy();
} catch (err) {
// console.error(err);
await shell.exec('rm -rf $*$');
}
globalThis.db = undefined;
globalThis.dbReady = false;
globalThis.Date.now = originalDateNow;
});
test('db.put() a new trk when required', async () => {
putNewTrkseg({ gpx: 1234567890123456, trk: 123456, trkseg: 5 });
await expect(globalThis.db.put).toBeCalledWith({
_id: 'gpx/1234567890123456/3trk/123456/000005',
_rev: undefined,
doc: {
trkpt: undefined,
extensions: undefined,
},
type: 'trkseg',
it('can write and read a trkseg', async () => {
const id = 'gpx/4320836036089189/3trk/000000/000000';
const trkseg: Trkseg = {};
const trksegPut = await putTrkseg(id, trkseg);
const trksegGet = await getTrkseg({ id });
expect(trksegGet).toEqual(trkseg);
});
it('can write and read a trkseg with trkpts', async () => {
const id = 'whatever';
const trkseg: Trkseg = {
trkpt: [
{
$: { lat: 0, lon: 0 },
},
{
$: { lat: 1, lon: 1 },
},
],
};
const trksegPut = await putTrkseg(id, trkseg);
const trksegGet = await getTrkseg({ id });
expect(trksegGet).toEqual(trkseg);
});
it('can read external trkpts ', async () => {
const idTrkseg = 'gpx/4320836036089189/3trk/000000/000000';
const idTrksegpt = 'gpx/4320836036089189/3trk/000000/000000/000035';
const trkpt3: Wpt = {
$: { lat: 3, lon: 3 },
};
const trkseg0: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const trkseg1: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt3,
],
};
const trksegPut = await putTrkseg(idTrkseg, trkseg0);
await put(idTrksegpt, 'trkpt', () => trkpt3, emptyWpt);
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg1);
});
it('can can append a new trkpt ', async () => {
const idTrkseg = 'gpx/4320836036089189/3trk/000000/000000';
const trkpt3: Wpt = {
$: { lat: 3, lon: 3 },
};
const trkseg0: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const trkseg1: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt3,
],
};
await putTrkseg(idTrkseg, trkseg0);
await appendTrkpt({
trksegIdObj: getUri('trkseg', idTrkseg),
trkpt: trkpt3,
});
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg1);
});
test('db.put() generates an id for the trk if needed', async () => {
const id = await putNewTrkseg({ gpx: 1 });
expect(id).toEqual({ gpx: 1, trk: 0, trkseg: 0 });
it('can compact external trkpts after existing internal trkpts', async () => {
const idTrkseg = 'gpx/4320836036089189/3trk/000000/000000';
const idTrksegpt = 'gpx/4320836036089189/3trk/000000/000000/000035';
const trkpt3: Wpt = {
$: { lat: 3, lon: 3 },
};
const trkseg0: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
],
};
const trkseg1: Trkseg = {
trkpt: [
{
$: { lat: 1, lon: 1 },
},
{
$: { lat: 2, lon: 2 },
},
trkpt3,
],
};
const trksegPut = await putTrkseg(idTrkseg, trkseg0);
await put(idTrksegpt, 'trkpt', () => trkpt3, emptyWpt);
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg1);
compactRteOrTrkseg({ id: idTrkseg, getDocs: getTrksegDocs });
expect(await getTrkseg({ id: idTrkseg })).toEqual(trkseg1);
});
test('db.put() generates ids for both gpx and trk if needed', async () => {
const id = await putNewTrkseg();
expect(id).toEqual({ gpx: 4320000000000000, trk: 0, trkseg: 0 });
it('can compact external trkpts without existing internal trkpts', async () => {
const idTrkseg = 'gpx/4320836036089189/3trk/000000/000000';
const idTrksegpt1 = 'gpx/4320836036089189/3trk/000000/000000/000035';
const idTrksegpt2 = 'gpx/4320836036089189/3trk/000000/000000/000036';
const trkpt1 = {
$: { lat: 1, lon: 1 },
};
const trkpt2 = {
$: { lat: 2, lon: 2 },
};
const trkseg0: Trkseg = {};
const trkseg1: Trkseg = {
trkpt: [trkpt1, trkpt2],
};
const trksegPut = await putTrkseg(idTrkseg, trkseg0);
await put(idTrksegpt1, 'trkpt', () => trkpt1, emptyWpt);
await put(idTrksegpt2, 'trkpt', () => trkpt2, emptyWpt);
const { trkseg, docs } = await getTrksegDocs({ id: idTrkseg });
expect(trkseg).toEqual(trkseg1);
expect(docs.rows.length).toEqual(3);
await compactRteOrTrkseg({ id: idTrkseg, getDocs: getTrksegDocs });
//await sleep(5000);
const { trkseg: trksegx, docs: docsx } = await getTrksegDocs({
id: idTrkseg,
});
expect(trksegx).toEqual(trkseg1);
expect(docsx.rows.length).toEqual(1);
});
});

View File

@ -1,6 +1,9 @@
import { cloneDeep } from 'lodash';
import { state } from '../db-admin/health-legacy';
import getUri, { intToTrkptId } from '../lib/ids';
import { appendToArray } from './gpx';
import { getFamily, put } from './lib';
import { compactRteOrTrksegDebounced } from './rte';
import { putNewTrk } from './trk';
import { emptyWpt } from './wpt';
@ -9,55 +12,45 @@ const emptyTrkseg: Trkseg = {
extensions: undefined,
};
export const putNewTrkseg = async (id?: IdTrk | IdGpx | IdTrkseg) => {
let finalId = { ...id };
if (!('trkseg' in finalId)) {
const trkId = await putNewTrk(id);
finalId = { ...trkId, trkseg: 0 };
export const getTrksegDocs: ({
id,
}: {
id: string;
}) => Promise<{ docs: any; trkseg: Trkseg }> = async (params) => {
const { id } = params;
const docs = await getFamily(id, { include_docs: true });
let trkseg: Trkseg;
if (docs.rows.length === 1) {
trkseg = docs.rows[0].doc.doc;
} else {
trkseg = cloneDeep(docs.rows[0].doc.doc);
if (!trkseg.trkpt) {
trkseg.trkpt = [];
}
docs.rows.slice(1).forEach((row: any) => {
trkseg.trkpt.push(row.doc.doc);
});
}
const uri = getUri('trkseg', finalId);
await put(
uri,
'trkseg',
(trkseg) => {
return trkseg;
},
emptyTrkseg
);
return finalId as IdTrkseg;
console.log({
caller: 'getTrksegDocs',
id,
docs,
nbWptIn: docs.rows[0].doc.doc.trkpt?.length,
nbWptTotal: trkseg?.trkpt?.length,
});
return { docs, trkseg };
};
export const getTrkseg = async (params: any) => {
const { id } = params;
const docs = await getFamily(id, { include_docs: true });
let target: any[];
let trkseg: Trkseg | undefined = undefined;
docs.rows.every((row: any) => {
// level 0
if (row.doc.type === 'trkseg') {
if (!!trkseg) {
console.error({
caller: 'getTrkseg',
id,
row,
target,
trkseg,
});
return false; // Hack to stop if getFamily fails
}
target = [row.doc.doc];
trkseg = row.doc.doc;
}
//level 1
if (row.doc.type === 'trkpt') {
target.splice(1);
row.doc.doc.id = row.doc._id;
appendToArray(target.at(-1), row.doc.type, row.doc.doc);
target.push(row.doc.doc);
}
return true;
});
const { docs, trkseg } = await getTrksegDocs(params);
if (docs.rows.length > 1 && docs.rows[0].doc.origin === state().userId) {
// console.log({
// caller: 'getTrkseg compactRteOrTrksegDebounced required',
// id,
// });
compactRteOrTrksegDebounced({ id, getDocs: getTrksegDocs });
}
return trkseg;
};

8
src/db/types.d.ts vendored
View File

@ -49,7 +49,13 @@ interface Extensions {
'dyo:batterylevel'?: number;
'dyo:useragent'?: string;
'dyo:minZoom'?: number;
address: any;
address?: any;
to?: string;
startTime?: string;
endTime?: string;
category?: Category;
subCategory?: SubCategory;
tags?: any;
}
interface Trk {

View File

@ -1,58 +0,0 @@
import { putNewWpt } from './wpt';
declare global {
var db: any;
var dbReady: boolean;
}
const originalDb = globalThis.db;
const originalDateNow = globalThis.Date.now;
describe('The wpt module', () => {
beforeEach(() => {
globalThis.db = { put: jest.fn() };
globalThis.Date.now = () => 0;
});
afterEach(() => {
globalThis.db = originalDb;
globalThis.Date.now = originalDateNow;
});
test('db.put() a new wpt when required', async () => {
putNewWpt({ gpx: 1, wpt: 2 });
await expect(globalThis.db.put).toBeCalledWith({
_id: 'gpx/0000000000000001/1wpt/000002',
_rev: undefined,
doc: {
$: { lat: 0, lon: 0 },
ageofdgpsdata: undefined,
cmt: undefined,
desc: undefined,
dgpsid: undefined,
ele: undefined,
extensions: undefined,
fix: undefined,
geoidheight: undefined,
hdop: undefined,
link: undefined,
magvar: undefined,
name: undefined,
pdop: undefined,
sat: undefined,
src: undefined,
sym: undefined,
time: undefined,
type: undefined,
vdop: undefined,
},
type: 'wpt',
});
});
test('db.put() generates an id for the wpt if needed', async () => {
const id = await putNewWpt({ gpx: 1 });
expect(id).toEqual({ gpx: 1, wpt: 0 });
});
test('db.put() generates ids for both gpx and trk if needed', async () => {
const id = await putNewWpt();
expect(id).toEqual({ gpx: 4320000000000000, wpt: 0 });
});
});

View File

@ -1,6 +1,6 @@
import getUri from '../lib/ids';
import { putNewGpx } from './gpx';
import { get, put } from './lib';
import { get, getFamily, put } from './lib';
export const emptyWpt: Wpt = {
$: { lat: 0, lon: 0 },
@ -62,3 +62,17 @@ export const getWpt = async (params: any) => {
const doc = await get(id);
return doc.doc;
};
export const deleteWpt = async (params: any) => {
const { id } = params;
const docs = await getFamily(id, { include_docs: false });
console.log({ caller: 'deleteWpt' }, id, docs);
const deletedDocs = docs.rows.reverse().map((doc: any) => ({
_deleted: true,
_id: doc.id,
_rev: doc.value.rev,
}));
console.log({ caller: 'deleteWpt' }, id, docs, deletedDocs);
await db.bulkDocs(deletedDocs);
return id;
};

View File

@ -44,6 +44,7 @@ const dict = {
gpxNoName: 'No name',
gpxDesc: 'Description',
gpxTime: 'Start date',
gpxTo: 'To',
gpxSave: 'Save',
newGpx: '-- new journey --',

View File

@ -49,6 +49,7 @@ const dict = {
gpxNoName: 'Pas de nom',
gpxDesc: 'Description',
gpxTime: 'Date de début',
gpxTo: 'Destinataires',
gpxSave: 'Sauvegarder',
newGpx: '-- nouveau voyage --',

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 17 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="si-glyph si-glyph-bicycle-man">
<title>1102</title>
<defs>
</defs>
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(1.000000, 2.000000)" fill="#434343">
<path d="M8.5,12.969 C8.141,12.967 8.005,12.68 8.006,12.316 L8.021,9.532 L5.153,6.44 C4.934,6.151 4.99,5.737 5.274,5.515 L8.836,2.582 C8.972,2.477 9.147,2.428 9.316,2.451 C9.486,2.473 9.641,2.564 9.746,2.703 L11.29,4.508 L13.579,5.605 C13.914,5.735 14.083,6.116 13.956,6.457 C13.828,6.798 13.453,6.97 13.117,6.84 L10.656,5.677 C10.543,5.633 10.445,5.56 10.371,5.462 L9.111,4.033 L6.687,6.16 L8.878,8.698 C8.964,8.814 8.968,8.912 8.968,9.058 L8.985,12.312 C8.984,12.676 8.859,12.97 8.5,12.969 L8.5,12.969 L8.5,12.969 Z" class="si-glyph-fill">
</path>
<g transform="translate(0.000000, 8.000000)">
<path d="M12.98,-0.018 C11.335,-0.018 10.003,1.326 10.003,2.983 C10.003,4.64 11.335,5.984 12.98,5.984 C14.625,5.984 15.958,4.64 15.958,2.983 C15.958,1.326 14.625,-0.018 12.98,-0.018 L12.98,-0.018 Z M12.975,5.046 C11.83,5.046 10.903,4.123 10.903,2.984 C10.903,1.845 11.831,0.922 12.975,0.922 C14.116,0.922 15.044,1.845 15.044,2.984 C15.044,4.123 14.115,5.046 12.975,5.046 L12.975,5.046 Z" class="si-glyph-fill">
</path>
<path d="M2.991,0.023 C1.349,0.023 0.02,1.353 0.02,2.994 C0.02,4.636 1.349,5.965 2.991,5.965 C4.631,5.965 5.962,4.636 5.962,2.994 C5.962,1.354 4.631,0.023 2.991,0.023 L2.991,0.023 Z M2.991,5.063 C1.847,5.063 0.922,4.137 0.922,2.994 C0.922,1.851 1.848,0.925 2.991,0.925 C4.133,0.925 5.06,1.851 5.06,2.994 C5.06,4.137 4.133,5.063 2.991,5.063 L2.991,5.063 Z" class="si-glyph-fill">
</path>
</g>
<ellipse cx="11.469" cy="1.486" rx="1.469" ry="1.486" class="si-glyph-fill">
</ellipse>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--gis" preserveAspectRatio="xMidYMid meet"><path d="M46.43 7.5c4.055 0 7.337 3.379 7.337 7.434c0 4.054-3.282 7.433-7.337 7.433s-7.434-3.379-7.434-7.433c0-4.055 3.38-7.434 7.434-7.434zm.483 15.543c2.79-.087 4.947 1.649 6.082 3.476l7.723 12.84l13.516 5.696c3.861 1.64 2.027 6.757-2.317 5.599a5.015 5.015 0 0 0-.483-.29l-9.075 20.08s2.896 6.662 6.565 14.193c3.572 7.626-5.117 10.909-8.303 3.861l-3.185-7.144l-4.634 10.137l-1.931-.869l5.406-11.778l-9.075-19.79c-.386.096-.772 0-1.255 0c0 0-10.523 23.941-13.42 30.217c-2.799 6.275-11.101 2.51-8.302-3.67c2.8-6.178 16.123-36.202 16.123-36.202l-9.903.162c-1.5.013-1.859-.226-1.954-1.35c-.153-2.97-.415-9.958.272-13.197c.886-4.175 1.415-8.77 4.344-10.137c2.93-1.367 8.013 2.414 8.013 2.414c.772-2.51 3.186-4.248 5.793-4.248zm5.985 15.06V49.69l8.303 18.15l8.302-18.247l-12.067-5.02c-.58-.29-1.062-.676-1.449-1.255z" fill="#000000" fill-rule="evenodd"></path></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20 14V7C20 5.34315 18.6569 4 17 4H7C5.34315 4 4 5.34315 4 7V17C4 18.6569 5.34315 20 7 20H13.5M20 14L13.5 20M20 14H15.5C14.3954 14 13.5 14.8954 13.5 16V20" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 8H16" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 12H12" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 683 B

168
src/icons/osm/bike.svg Normal file
View File

@ -0,0 +1,168 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://web.resource.org/cc/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.0"
width="480"
height="480"
id="svg2"
sodipodi:version="0.32"
inkscape:version="0.45.1"
sodipodi:docname="bike.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape"
sodipodi:docbase="C:\Dokumente und Einstellungen\ulfl\Eigene Dateien\svn.openstreetmap.org\applications\share\map-icons\svg\vehicle\parking">
<metadata
id="metadata8">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<cc:license
rdf:resource="http://web.resource.org/cc/PublicDomain" />
</cc:Work>
<cc:License
rdf:about="http://web.resource.org/cc/PublicDomain">
<cc:permits
rdf:resource="http://web.resource.org/cc/Reproduction" />
<cc:permits
rdf:resource="http://web.resource.org/cc/Distribution" />
<cc:permits
rdf:resource="http://web.resource.org/cc/DerivativeWorks" />
</cc:License>
</rdf:RDF>
</metadata>
<sodipodi:namedview
inkscape:window-height="573"
inkscape:window-width="797"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
guidetolerance="10.0"
gridtolerance="10.0"
objecttolerance="10.0"
borderopacity="1.0"
bordercolor="#666666"
pagecolor="#ffffff"
id="base"
inkscape:zoom="0.78541667"
inkscape:cx="240"
inkscape:cy="240"
inkscape:window-x="154"
inkscape:window-y="203"
inkscape:current-layer="svg2" />
<defs
id="defs4">
<marker
viewBox="0 0 10 10"
refY="5"
refX="10"
orient="auto"
markerWidth="4"
markerUnits="strokeWidth"
markerHeight="3"
id="ArrowStart">
<path
id="path2295"
d="M 10,0 L 0,5 L 10,10 L 10,0 z " />
</marker>
<marker
viewBox="0 0 10 10"
refY="5"
refX="0"
orient="auto"
markerWidth="4"
markerUnits="strokeWidth"
markerHeight="3"
id="ArrowEnd">
<path
id="path2292"
d="M 0,0 L 10,5 L 0,10 L 0,0 z " />
</marker>
</defs>
<path
d="M 30.856274,5.7720243 L 450.86109,5.7720243 C 461.67691,6.5627045 473.93298,17.615789 474.52755,30.636789 L 474.52755,449.4433 C 474.57722,459.76184 462.73404,473.63554 449.36321,474.30807 L 29.957547,474.30807 C 20.433732,473.72489 5.5262338,458.92955 5.0927831,449.14373 L 5.691934,30.936364 C 4.6103723,24.633922 19.978002,5.6381226 30.856274,5.7720243 z "
style="fill:white;fill-opacity:1;fill-rule:evenodd;stroke:black;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path3669" />
<path
d="M 35.1875,16.78125 C 23.426887,16.266334 16.714331,24.30046 17.15625,37.15625 L 17.15625,443.5625 C 17.202803,452.2297 20.884421,462.63293 32.84375,462.84375 L 447.28125,462.8125 C 459.24058,462.6017 462.95345,452.19845 463,443.53125 L 463,37.09375 C 463.44191,24.237959 456.72937,16.20383 444.96875,16.71875 L 35.1875,16.78125 z "
style="fill:#039;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.94117647"
id="path3661" />
<path
d="M 100.82515,91.817251 L 100.82515,197.08323 L 174.28737,197.08323 C 192.65275,197.0834 206.35224,191.55881 215.3859,180.50943 C 224.41915,169.46044 228.93588,157.44072 228.93609,144.45024 C 228.93588,124.74111 221.8435,110.25772 207.65893,101.00002 C 198.55062,94.878451 186.82953,91.817521 172.49561,91.817251 L 100.82515,91.817251 z M 51.327737,371.33202 L 51.327737,45.00748 L 169.80797,45.00748 C 182.49944,45.007806 194.70581,46.351626 206.42709,49.038943 C 218.148,51.726905 230.35436,57.998063 243.04621,67.852438 C 252.90067,75.467721 261.26221,85.956981 268.13087,99.320251 C 274.99903,112.68406 278.43324,128.17531 278.4335,145.79406 C 278.43324,169.08716 269.73574,191.26018 252.34098,212.3132 C 234.94574,233.36653 209.52515,243.89312 176.07913,243.89299 L 100.82515,243.89299 L 100.82515,371.33202 L 51.327737,371.33202 z "
style="font-size:458.69091797px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;line-height:100%;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:DIN 1451 Mittelschrift"
id="text5426" />
<g
transform="matrix(0.7929425,0,0,0.7755778,-372.35858,292.1436)"
id="g2297">
<path
d="M 278.91286 461.96271 A 78.380615 78.380615 0 1 1 122.15163,461.96271 A 78.380615 78.380615 0 1 1 278.91286 461.96271 z"
id="path596"
sodipodi:cx="200.53224"
sodipodi:cy="461.96271"
sodipodi:rx="78.380615"
sodipodi:ry="78.380615"
sodipodi:type="arc"
style="font-size:12px;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:26;stroke-opacity:1"
transform="matrix(-0.7941975,0,0,0.7941975,844.6956,-247.27632)" />
<path
d="M 278.91286 461.96271 A 78.380615 78.380615 0 1 1 122.15163,461.96271 A 78.380615 78.380615 0 1 1 278.91286 461.96271 z"
id="path595"
sodipodi:cx="200.53224"
sodipodi:cy="461.96271"
sodipodi:rx="78.380615"
sodipodi:ry="78.380615"
sodipodi:type="arc"
style="font-size:12px;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:#feffff;stroke-width:25.99983025;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
transform="matrix(-0.7941975,0,0,0.7941975,1111.4801,-248.48899)" />
<path
d="M 902.90325,12.49531 L 742.83259,13.303766 L 686.24197,118.40065 L 794.57261,118.40065 L 907.75387,41.599088"
id="path594"
sodipodi:nodetypes="ccccc"
style="font-size:12px;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:16.57887268;stroke-linejoin:round;stroke-opacity:1" />
<path
d="M 896.75233,-50.489179 C 905.44709,-50.489179 912.01918,-50.683176 918.75551,-40.392067 C 920.69453,-36.961461 921.58106,-32.77272 920.86509,-28.603196 C 920.00619,-23.862035 917.19925,-19.203901 913.89022,-16.4464 C 909.5085,-12.79494 905.35013,-13.076632 906.02217,-9.7941826 C 906.88446,-5.5824266 909.51604,0.27036544 912.35992,9.7741226 C 915.24666,19.42106 918.67449,31.227993 922.03921,42.857413 C 925.40393,54.486808 928.70687,65.944962 931.32138,74.873497 C 932.62866,79.337753 933.77035,83.171066 934.6471,86.041895 C 935.5013,88.83894 936.25548,91.011621 936.18584,90.856721 C 938.90979,95.649288 939.28057,98.772121 943.84948,102.85126 C 948.97222,107.33462 953.14308,110.64668 954.59062,111.65843 C 958.26729,114.32927 959.97652,119.96578 958.03499,122.75082 C 955.58819,126.54638 950.53489,127.12861 946.8416,125.99309 C 943.33471,124.87986 937.78337,122.96765 931.34621,117.63605 L 931.29657,117.56161 L 931.22211,117.51197 C 922.26513,109.82917 918.95144,100.50467 918.61424,99.965175 L 918.14268,99.245428 L 917.82003,98.451238 C 917.0439,96.540701 916.57901,94.856088 915.66081,91.849459 C 914.74261,88.842831 913.57861,84.958513 912.26065,80.457684 C 909.62473,71.456073 906.33855,59.980493 902.97847,48.367156 C 899.61837,36.753819 896.19895,25.006992 893.34882,15.482413 C 890.4987,5.9578348 888.69807,-1.8646344 888.03246,-3.528685 C 886.41239,-7.578844 885.58474,-11.951325 886.69224,-16.335124 C 887.79972,-20.718923 891.10922,-24.257008 894.08003,-25.079472 C 900.86114,-26.976615 899.06187,-31.854189 895.59257,-31.861264 L 866.5202,-31.920451 L 866.44854,-50.488779 C 866.44873,-50.489179 885.31934,-50.489179 896.75233,-50.489179 z "
id="path593"
sodipodi:nodetypes="ccccscccccsscsccccccccccccssccc"
style="font-size:12px;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke-width:25;stroke-linecap:round" />
<path
d="M 792.49843,115.11004 L 737.61984,-19.228118"
id="path599"
style="font-size:12px;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:19.85493851;stroke-opacity:1" />
<path
d="M 817.07944,72.236162 L 772.49063,166.5587"
id="path600"
style="font-size:12px;fill:#fffffd;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:7.24705219;stroke-linecap:round;stroke-opacity:1" />
<path
d="M 278.91286 461.96271 A 78.380615 78.380615 0 1 1 122.15163,461.96271 A 78.380615 78.380615 0 1 1 278.91286 461.96271 z"
id="path597"
sodipodi:cx="200.53224"
sodipodi:cy="461.96271"
sodipodi:rx="78.380615"
sodipodi:ry="78.380615"
sodipodi:type="arc"
style="font-size:12px;fill:#fffeff;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:31.30500031;stroke-opacity:1"
transform="matrix(-0.3120051,0,0,0.3223192,856.53347,-30.297359)" />
<path
d="M 828.98308,75.129086 L 799.69311,75.397573"
id="path601"
sodipodi:nodetypes="cc"
style="font-size:12px;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:10.12601757;stroke-opacity:1" />
<path
d="M 787.42188,162.59237 L 758.13191,162.86086"
id="path602"
sodipodi:nodetypes="cc"
style="font-size:12px;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:10.12601757;stroke-opacity:1" />
<path
d="M 710.75194,-31.233245 L 779.63603,-31.233245 C 782.20847,-31.233245 785.5287,-26.682779 782.20847,-23.658842 C 778.6175,-20.24123 746.33729,-13.226203 746.33729,-13.226203 C 746.33729,-13.226203 737.47669,-10.796683 732.76054,-11.368321 C 728.04443,-11.939982 711.75234,-13.369101 710.75194,-31.233245 z "
id="path603"
sodipodi:nodetypes="cssccc"
style="font-size:12px;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.79419751pt;stroke-opacity:1" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

111
src/icons/osm/hiking.svg Normal file
View File

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://web.resource.org/cc/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.0"
width="480"
height="720"
id="svg2"
sodipodi:version="0.32"
inkscape:version="0.45.1"
sodipodi:docname="hiking.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape"
sodipodi:docbase="G:\Documents\map-icons\svg\vehicle\parking">
<metadata
id="metadata2495">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<cc:license
rdf:resource="http://web.resource.org/cc/PublicDomain" />
</cc:Work>
<cc:License
rdf:about="http://web.resource.org/cc/PublicDomain">
<cc:permits
rdf:resource="http://web.resource.org/cc/Reproduction" />
<cc:permits
rdf:resource="http://web.resource.org/cc/Distribution" />
<cc:permits
rdf:resource="http://web.resource.org/cc/DerivativeWorks" />
</cc:License>
</rdf:RDF>
</metadata>
<sodipodi:namedview
inkscape:window-height="573"
inkscape:window-width="797"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
guidetolerance="10.0"
gridtolerance="10.0"
objecttolerance="10.0"
borderopacity="1.0"
bordercolor="#666666"
pagecolor="#ffffff"
id="base"
inkscape:zoom="0.52361111"
inkscape:cx="240"
inkscape:cy="360"
inkscape:window-x="198"
inkscape:window-y="261"
inkscape:current-layer="svg2" />
<defs
id="defs4" />
<path
d="M 30.856274,5.7720243 L 450.86109,5.7720243 C 461.67691,6.5627045 473.93298,17.615789 474.52755,30.636789 L 474.52755,686.44619 C 474.57722,696.76473 462.73404,710.63843 449.36321,711.31096 L 29.957547,711.31096 C 20.433732,710.72778 5.5262338,695.93244 5.0927831,686.14662 L 5.691934,30.936364 C 5.4925171,19.341053 19.978002,5.6381226 30.856274,5.7720243 z "
style="fill:white;fill-opacity:1;fill-rule:evenodd;stroke:black;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path3669" />
<path
d="M 35.1875,16.78125 C 23.426887,16.266334 16.714331,24.30046 17.15625,37.15625 L 17.15625,680 C 17.202803,688.6672 20.884421,699.07046 32.84375,699.28125 L 447.28125,699.8125 C 459.24058,699.60169 462.95345,689.19845 463,680.53125 L 463,37.09375 C 463.44191,24.237959 456.72937,16.20383 444.96875,16.71875 L 35.1875,16.78125 z "
style="fill:#039;fill-opacity:1;fill-rule:evenodd;stroke:#00339f;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.94117647"
id="path2774" />
<path
d="M 97.67666,336.42028 L 97.626101,619.68454 L 382.40713,619.63398 L 382.40713,336.31916 L 97.67666,336.42028 z "
style="fill:white;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path1886" />
<path
d="M 136.54347,86.246749 L 136.54347,169.00552 L 194.29853,169.00552 C 208.73716,169.00566 219.50752,164.66229 226.60967,155.97541 C 233.7115,147.28884 237.26249,137.83909 237.26266,127.62613 C 237.26249,112.13107 231.68655,100.74441 220.53482,93.466129 C 213.37399,88.653429 204.15902,86.246969 192.88987,86.246749 L 136.54347,86.246749 z M 97.629241,305.9977 L 97.629241,49.445505 L 190.77688,49.445505 C 200.75476,49.445762 210.35124,50.502256 219.56637,52.61499 C 228.78119,54.728231 238.37768,59.658536 248.35585,67.40592 C 256.1033,73.392957 262.67704,81.639479 268.07709,92.145509 C 273.47675,102.65197 276.17668,114.831 276.17689,128.68263 C 276.17668,146.99537 269.33882,164.42752 255.66328,180.97913 C 241.98737,197.53099 222.00202,205.80686 195.70719,205.80676 L 136.54347,205.80676 L 136.54347,305.9977 L 97.629241,305.9977 z "
style="font-size:360.61694336px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;line-height:100%;writing-mode:lr-tb;text-anchor:middle;fill:white;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:DIN 1451 Mittelschrift"
id="text1885" />
<g
style="fill:black"
id="g1967">
<path
d="M 305.47137,379.90744 C 305.47137,390.6016 296.80202,399.27096 286.10786,399.27096 C 275.41368,399.27096 266.74434,390.6016 266.74434,379.90744 C 266.74434,369.21326 275.41368,360.54391 286.10786,360.54391 C 296.80202,360.54391 305.47137,369.21326 305.47137,379.90744 L 305.47137,379.90744 z "
style="fill:black;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:7;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="path5663" />
<path
d="M 276.52373,494.9308 L 315.00347,494.9308 L 315.18137,498.39434 L 356.02613,574.90167 C 356.82547,587.40818 351.13058,592.20279 345.42581,596.98566 L 295.95765,505.99959 L 248.25621,591.24383 C 234.77599,599.77637 229.81923,596.19662 223.96382,593.8939 L 276.15963,499.07994 L 276.52373,494.9308 z "
style="fill:black;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path5659" />
<path
d="M 252.0663,477.51136 L 275.68305,454.10216 L 275.27572,414.41829 C 281.15774,406.61054 291.33339,402.78549 305.93992,406.61042 L 347.85266,471.57304 C 347.21135,479.98392 346.89804,489.73908 338.19975,489.68581 L 314.56004,450.92359 L 314.06048,490.37335 L 275.89608,490.40536 L 275.66622,478.0085 C 276.07919,479.79802 259.01884,488.86597 252.0663,477.51136 z "
style="opacity:1;fill:black;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path5661" />
<g
transform="translate(525.4094,-19.18652)"
style="fill:black"
id="g1954">
<path
d="M -315.45043,399.09396 C -315.45043,409.78812 -324.11978,418.45748 -334.81394,418.45748 C -345.50812,418.45748 -354.17746,409.78812 -354.17746,399.09396 C -354.17746,388.39978 -345.50812,379.73043 -334.81394,379.73043 C -324.11978,379.73043 -315.45043,388.39978 -315.45043,399.09396 L -315.45043,399.09396 z "
style="fill:black;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:7;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="path1956" />
<path
d="M -344.39807,514.11732 L -305.91833,514.11732 L -305.74043,517.58086 L -264.89567,594.08819 C -264.09633,606.5947 -269.79122,611.38931 -275.49599,616.17218 L -324.96415,525.18611 L -372.66559,610.43035 C -386.14581,618.96289 -391.10257,615.38314 -396.95798,613.08042 L -344.76217,518.26646 L -344.39807,514.11732 z "
style="fill:black;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path1958" />
<path
d="M -399.83568,473.09124 L -345.08881,430.74432 C -337.89231,423.54782 -329.58841,421.97201 -314.98188,425.79694 L -281.12568,452.53244 L -277.06558,460.028 L -277.06558,487.76223 C -280.75825,495.60098 -286.03713,500.92821 -294.71137,500.87945 L -294.71137,464.55657 L -305.61243,455.62301 L -305.61243,509.80965 L -344.80795,509.80965 L -344.80795,452.21584 L -381.34993,482.27214 L -311.98699,611.13555 L -320.37358,616.2234 L -392.05517,486.92262 C -397.14454,490.55788 -404.80356,477.35337 -399.83568,473.09124 z "
style="fill:black;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path1960" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.0 KiB

View File

@ -1 +1,74 @@
<svg xmlns="http://www.w3.org/2000/svg" width="580" height="580" xml:space="preserve"><path fill="#0071BC" stroke="#0071BC" stroke-width=".5" d="M500.742 278.013v-12.462h4.701c.829 0 1.459.04 1.896.119.611.102 1.124.296 1.537.583.414.286.748.687 1 1.202a3.85 3.85 0 0 1 .378 1.7c0 1.061-.337 1.957-1.012 2.691-.674.734-1.895 1.101-3.656 1.101h-3.196v5.066h-1.648zm1.651-6.537h3.222c1.064 0 1.821-.198 2.271-.595.445-.397.669-.955.669-1.675 0-.521-.131-.968-.393-1.338a1.846 1.846 0 0 0-1.042-.735c-.278-.074-.79-.11-1.538-.11h-3.188v4.453h-.001z"/></svg>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://web.resource.org/cc/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.0"
width="480"
height="480"
id="svg2"
sodipodi:version="0.32"
inkscape:version="0.45.1"
sodipodi:docname="parking.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape"
sodipodi:docbase="C:\Dokumente und Einstellungen\ulfl\Eigene Dateien\svn.openstreetmap.org\applications\share\map-icons\svg\vehicle">
<metadata
id="metadata8">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<cc:license
rdf:resource="http://web.resource.org/cc/PublicDomain" />
</cc:Work>
<cc:License
rdf:about="http://web.resource.org/cc/PublicDomain">
<cc:permits
rdf:resource="http://web.resource.org/cc/Reproduction" />
<cc:permits
rdf:resource="http://web.resource.org/cc/Distribution" />
<cc:permits
rdf:resource="http://web.resource.org/cc/DerivativeWorks" />
</cc:License>
</rdf:RDF>
</metadata>
<sodipodi:namedview
inkscape:window-height="573"
inkscape:window-width="797"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
guidetolerance="10.0"
gridtolerance="10.0"
objecttolerance="10.0"
borderopacity="1.0"
bordercolor="#666666"
pagecolor="#ffffff"
id="base"
inkscape:zoom="0.78541667"
inkscape:cx="240"
inkscape:cy="240"
inkscape:window-x="154"
inkscape:window-y="203"
inkscape:current-layer="svg2" />
<defs
id="defs4" />
<path
d="M 30.856274,5.7720243 L 450.86109,5.7720243 C 461.67691,6.5627045 473.93298,17.615789 474.52755,30.636789 L 474.52755,449.4433 C 474.57722,459.76184 462.73404,473.63554 449.36321,474.30807 L 29.957547,474.30807 C 20.433732,473.72489 5.5262338,458.92955 5.0927831,449.14373 L 5.691934,30.936364 C 4.6103723,24.633922 19.978002,5.6381226 30.856274,5.7720243 z "
style="fill:white;fill-opacity:1;fill-rule:evenodd;stroke:black;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path3669" />
<path
d="M 35.1875,16.78125 C 23.426887,16.266334 16.714331,24.30046 17.15625,37.15625 L 17.15625,443.5625 C 17.202803,452.2297 20.884421,462.63293 32.84375,462.84375 L 447.28125,462.8125 C 459.24058,462.6017 462.95345,452.19845 463,443.53125 L 463,37.09375 C 463.44191,24.237959 456.72937,16.20383 444.96875,16.71875 L 35.1875,16.78125 z "
style="fill:#039;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.94117647"
id="path3661" />
<path
d="M 175.94451,123.64749 L 175.94451,228.91347 L 249.40673,228.91347 C 267.77211,228.91364 281.4716,223.38905 290.50526,212.33967 C 299.53851,201.29068 304.05524,189.27096 304.05545,176.28048 C 304.05524,156.57135 296.96286,142.08796 282.77829,132.83026 C 273.66998,126.70869 261.94889,123.64776 247.61497,123.64749 L 175.94451,123.64749 z M 126.4471,403.16226 L 126.4471,76.837719 L 244.92733,76.837719 C 257.6188,76.838045 269.82517,78.181865 281.54645,80.869182 C 293.26736,83.557144 305.47372,89.828302 318.16557,99.682677 C 328.02003,107.29796 336.38157,117.78722 343.25023,131.15049 C 350.11839,144.5143 353.5526,160.00555 353.55286,177.6243 C 353.5526,200.9174 344.8551,223.09042 327.46034,244.14344 C 310.0651,265.19677 284.64451,275.72336 251.19849,275.72323 L 175.94451,275.72323 L 175.94451,403.16226 L 126.4471,403.16226 z "
style="font-size:458.69091797px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;line-height:100%;writing-mode:lr-tb;text-anchor:middle;fill:white;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:DIN 1451 Mittelschrift"
id="text5426" />
</svg>

Before

Width:  |  Height:  |  Size: 554 B

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

@ -1,15 +1,13 @@
/* @refresh reload */
import { render } from 'solid-js/web';
import { Router, hashIntegration } from '@solidjs/router';
import { Router } from '@solidjs/router';
import {
I18nContext,
createI18nContext,
useI18n,
} from '@solid-primitives/i18n';
import dict from './i18n';
import App from './App';
import { Language } from '@suid/icons-material';
// See https://stackoverflow.com/questions/71538643/property-wakelock-does-not-exist-on-type-navigator
const requestWakeLock = async () => {
@ -55,6 +53,13 @@ const getLanguage = () => {
const i18nDict = createI18nContext(dict, getLanguage());
// const [watchDbStatus] = createWorkerSignal({
// provider: 'watchDb',
// });
// createEffect(() => {
// console.log({ caller: 'createEffect', watchDbStatus: watchDbStatus() });
// });
render(
() => (
<Router>

View File

@ -0,0 +1,38 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import maybePlusCode from './check-pluscodes';
describe('The maybePlusCode method', () => {
it('detects a valid short pluscode without qualifier', () => {
const code = '9G8F+6W';
expect(maybePlusCode(code)).toEqual({ code, isShort: true });
});
it('detects a valid short pluscode with qualifier', () => {
const code = '948G+V4 Oviedo';
expect(maybePlusCode(code)).toEqual({
code: '948G+V4',
qualifier: 'Oviedo',
isShort: true,
});
});
it('detects a valid long pluscode with 10 digits', () => {
const code = '9FFW84J9+XG';
expect(maybePlusCode(code)).toEqual({
code,
isShort: false,
});
});
it('detects a valid long pluscode with 8 digits', () => {
const code = '9FFW84J9+';
expect(maybePlusCode(code)).toEqual({
code,
isShort: false,
});
});
it('detects a valid long pluscode with 4 digits', () => {
const code = '9FFW0000+';
expect(maybePlusCode(code)).toEqual({
code,
isShort: false,
});
});
});

View File

@ -0,0 +1,16 @@
const maybePlusRegexp =
/^([23456789CFGHJMPQRVWX]+0*\+[23456789CFGHJMPQRVWX]*)(\s+(.*))?$/;
const maybePlusCode = (code: string) => {
const matches = code.match(maybePlusRegexp);
if (!matches) {
return false;
}
return {
code: matches[1],
isShort: matches[1].length < 9,
qualifier: matches[3] || undefined,
};
};
export default maybePlusCode;

View File

@ -130,4 +130,13 @@ export const route = (route, coding = {}) => {
};
};
export const getParentId = (id) => {
const tokens = id.split('/').slice(0, -1);
if (['1wpt', '2rte', '3trk'].includes(tokens.at(-1))) {
tokens.splice(-1);
}
const parentId = tokens.join('/');
return parentId;
};
export default route;

Some files were not shown because too many files have changed in this diff Show More