Compare commits

..

No commits in common. "master" and "multi-layers" have entirely different histories.

434 changed files with 5045 additions and 25793 deletions

41
.gitignore vendored
View File

@ -1,6 +1,35 @@
node_modules/
dist/
android/
ios/
vite.config.ts.timestamp-*.mjs
$*$/
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
package-lock.json
# testing
/coverage
# production
/build
# wtf ?
/android
# doc
/doc
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.vscode
.idea
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Optional eslint cache
.eslintcache

View File

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

View File

@ -1,9 +0,0 @@
{
"cSpell.words": [
"datatyping",
"docuri",
"Dyomedea",
"stackoverflow"
],
"workbench.colorTheme": "Default Light Modern"
}

View File

@ -1,152 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dyomedea.dyomedea"
>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:isGame="false"
android:appCategory="maps"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
>
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
android:name="com.dyomedea.dyomedea.MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<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>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<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
android:name="com.darryncampbell.cordova.plugin.intent.ACTION"
/>
<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>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"
/>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission
android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"
/>
<uses-permission
android:name="android.permission.ACCESS_BACKGROUND_LOCATION"
/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
</manifest>

View File

@ -1,675 +0,0 @@
### 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>.

380
README.md
View File

@ -1,16 +1,5 @@
# 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
@ -95,374 +84,5 @@ vdv@nuc:~/projects/tea/dyomedea/dyomedea$ echo $ANDROID_SDK_ROOT
```
### To (re)generate android/
```bash
$ rm capacitor.config.ts
$ rm -rf android
$ npx cap init dyomedea com.dyomedea.dyomedea # assets in dist/
$ npx cap add android
$ cp AndroidManifest.xml ./android/app/src/main/AndroidManifest.xml
$ npx cap run --target RFCN20NEZ4R android
```
### To generate style filters
```bash
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ esrun helper.ts
{
caller: 'overlay-definitions',
legacyOverlayDefinitions: {
amenity: {
bar: [Object],
fast_food: [Object],
food_court: [Object],
pub: [Object],
restaurant: [Object],
cafe: [Object],
atm: [Object],
bank: [Object],
doctors: [Object],
hospital: [Object],
pharmacy: [Object],
police: [Object],
fire_station: [Object],
drinking_water: [Object],
water_point: [Object],
waste_basket: [Object],
waste_disposal: [Object],
vending_machine: [Object]
},
shop: {
bakery: [Object],
butcher: [Object],
cheese: [Object],
chocolate: [Object],
convenience: [Object],
dairy: [Object],
farm: [Object],
greengrocer: [Object],
health_food: [Object],
pasta: [Object],
pastry: [Object],
seafood: [Object],
water: [Object],
department_store: [Object],
general: [Object],
mall: [Object],
supermarket: [Object],
wholesale: [Object],
outdoor: [Object],
laundry: [Object]
},
tourism: {
hotel: [Object],
alpine_hut: [Object],
apartment: [Object],
camp_site: [Object],
chalet: [Object],
guest_house: [Object],
hostel: [Object],
motel: [Object],
wilderness_hut: [Object],
viewpoint: [Object]
},
waterway: { waterfall: [Object] },
natural: {
peak: [Object],
cave_entrance: [Object],
volcano: [Object],
arch: [Object],
arete: [Object],
fumarole: [Object],
rock: [Object],
saddle: [Object],
sinkhole: [Object],
stone: [Object],
glacier: [Object],
spring: [Object],
hot_spring: [Object],
geyser: [Object]
}
},
_flat: [
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] },
{ hiking: [Object] }, { hiking: [Object] }, { hiking: [Object] }
],
overlayCategories: {
hiking: Set(9) {
'drinking',
'eating',
'money',
'dayToDay',
'health',
'security',
'material',
'sleeping',
'naturalSites'
}
}
}
{
legacyOverlayDefinitions: {
amenity: {
bar: [Object],
fast_food: [Object],
food_court: [Object],
pub: [Object],
restaurant: [Object],
cafe: [Object],
atm: [Object],
bank: [Object],
doctors: [Object],
hospital: [Object],
pharmacy: [Object],
police: [Object],
fire_station: [Object],
drinking_water: [Object],
water_point: [Object],
waste_basket: [Object],
waste_disposal: [Object],
vending_machine: [Object]
},
shop: {
bakery: [Object],
butcher: [Object],
cheese: [Object],
chocolate: [Object],
convenience: [Object],
dairy: [Object],
farm: [Object],
greengrocer: [Object],
health_food: [Object],
pasta: [Object],
pastry: [Object],
seafood: [Object],
water: [Object],
department_store: [Object],
general: [Object],
mall: [Object],
supermarket: [Object],
wholesale: [Object],
outdoor: [Object],
laundry: [Object]
},
tourism: {
hotel: [Object],
alpine_hut: [Object],
apartment: [Object],
camp_site: [Object],
chalet: [Object],
guest_house: [Object],
hostel: [Object],
motel: [Object],
wilderness_hut: [Object],
viewpoint: [Object]
},
waterway: { waterfall: [Object] },
natural: {
peak: [Object],
cave_entrance: [Object],
volcano: [Object],
arch: [Object],
arete: [Object],
fumarole: [Object],
rock: [Object],
saddle: [Object],
sinkhole: [Object],
stone: [Object],
glacier: [Object],
spring: [Object],
hot_spring: [Object],
geyser: [Object]
}
},
filters: [
'any',
[
'in', 'amenity',
'bar', 'fast_food',
'food_court', 'pub',
'restaurant', 'cafe',
'atm', 'bank',
'doctors', 'hospital',
'pharmacy', 'police',
'fire_station', 'drinking_water',
'water_point', 'waste_basket',
'waste_disposal', 'vending_machine'
],
[
'in', 'shop',
'bakery', 'butcher',
'cheese', 'chocolate',
'convenience', 'dairy',
'farm', 'greengrocer',
'health_food', 'pasta',
'pastry', 'seafood',
'water', 'department_store',
'general', 'mall',
'supermarket', 'wholesale',
'outdoor', 'laundry'
],
[
'in', 'tourism',
'hotel', 'alpine_hut',
'apartment', 'camp_site',
'chalet', 'guest_house',
'hostel', 'motel',
'wilderness_hut', 'viewpoint'
],
[ 'in', 'waterway', 'waterfall' ],
[
'in', 'natural',
'peak', 'cave_entrance',
'volcano', 'arch',
'arete', 'fumarole',
'rock', 'saddle',
'sinkhole', 'stone',
'glacier', 'spring',
'hot_spring', 'geyser'
]
],
json: '["any",["in","amenity","bar","fast_food","food_court","pub","restaurant","cafe","atm","bank","doctors","hospital","pharmacy","police","fire_station","drinking_water","water_point","waste_basket","waste_disposal","vending_machine"],["in","shop","bakery","butcher","cheese","chocolate","convenience","dairy","farm","greengrocer","health_food","pasta","pastry","seafood","water","department_store","general","mall","supermarket","wholesale","outdoor","laundry"],["in","tourism","hotel","alpine_hut","apartment","camp_site","chalet","guest_house","hostel","motel","wilderness_hut","viewpoint"],["in","waterway","waterfall"],["in","natural","peak","cave_entrance","volcano","arch","arete","fumarole","rock","saddle","sinkhole","stone","glacier","spring","hot_spring","geyser"]]'
}
```
(Just copy the filters as json)
Requires esrun (`sudo npm i -g @digitak/esrun`)
### Patches
* suid: https://github.com/swordev/suid/issues/89
### NPM updates: use npm-check-updates !
```
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ npm outdated
Package Current Wanted Latest Location Depended by
@capacitor/android 4.6.1 4.6.3 4.6.3 node_modules/@capacitor/android dyomedea
@capacitor/browser 4.1.0 4.1.1 4.1.1 node_modules/@capacitor/browser dyomedea
@capacitor/cli 4.6.1 4.6.3 4.6.3 node_modules/@capacitor/cli dyomedea
@capacitor/core 4.6.1 4.6.3 4.6.3 node_modules/@capacitor/core dyomedea
@capacitor/ios 4.6.1 4.6.3 4.6.3 node_modules/@capacitor/ios dyomedea
@esbuild-plugins/node-globals-polyfill 0.1.1 0.1.1 0.2.3 node_modules/@esbuild-plugins/node-globals-polyfill dyomedea
@esbuild-plugins/node-modules-polyfill 0.1.4 0.1.4 0.2.2 node_modules/@esbuild-plugins/node-modules-polyfill dyomedea
@solid-primitives/i18n 1.1.2 1.1.3 1.1.3 node_modules/@solid-primitives/i18n dyomedea
@solidjs/router 0.6.0 0.6.0 0.7.0 node_modules/@solidjs/router dyomedea
@suid/icons-material 0.5.5 0.5.8 0.5.8 node_modules/@suid/icons-material dyomedea
@suid/material 0.9.1 0.9.2 0.10.1 node_modules/@suid/material dyomedea
jsdom 21.0.0 21.1.0 21.1.0 node_modules/jsdom dyomedea
solid-js 1.6.9 1.6.10 1.6.10 node_modules/solid-js dyomedea
solid-testing-library 0.5.0 0.5.1 0.5.1 node_modules/solid-testing-library dyomedea
typescript 4.9.4 4.9.5 4.9.5 node_modules/typescript dyomedea
vite 4.0.4 4.1.1 4.1.1 node_modules/vite dyomedea
vitest 0.27.1 0.28.4 0.28.4 node_modules/vitest dyomedea
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ npm-check
npm-check npm-check-updates
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ npm-check-updates
Checking /home/vdv/projects/tea/dyomedea/dyomedea/package.json
[====================] 40/40 100%
@capacitor/android ^4.6.1 → ^4.6.3
@capacitor/browser ^4.1.0 → ^4.1.1
@capacitor/cli ^4.6.1 → ^4.6.3
@capacitor/core ^4.6.1 → ^4.6.3
@capacitor/ios ^4.6.1 → ^4.6.3
@esbuild-plugins/node-globals-polyfill ^0.1.1 → ^0.2.3
@esbuild-plugins/node-modules-polyfill ^0.1.4 → ^0.2.2
@solid-primitives/i18n ^1.1.2 → ^1.1.3
@solidjs/router ^0.6.0 → ^0.7.0
@suid/icons-material ^0.5.5 → ^0.5.8
@suid/material ^0.9.1 → ^0.10.1
jsdom >=21.0.0 → >=21.1.0
solid-js ^1.6.9 → ^1.6.10
typescript ^4.9.4 → ^4.9.5
vite >=4.0.4 → >=4.1.1
vitest >=0.27.1 → >=0.28.4
Run ncu -u to upgrade package.json
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ npm-check-updates -u
╭─────────────────────────────────────────────────────────────────────────────────╮
│ │
│ Update available 16.4.1 → 16.6.3 │
│ Run npm i -g npm-check-updates to update │
│ https://github.com/raineorshine/npm-check-updates/compare/v16.4.1...v16.6.3 │
│ │
╰─────────────────────────────────────────────────────────────────────────────────╯
Upgrading /home/vdv/projects/tea/dyomedea/dyomedea/package.json
[====================] 40/40 100%
@capacitor/android ^4.6.1 → ^4.6.3
@capacitor/browser ^4.1.0 → ^4.1.1
@capacitor/cli ^4.6.1 → ^4.6.3
@capacitor/core ^4.6.1 → ^4.6.3
@capacitor/ios ^4.6.1 → ^4.6.3
@esbuild-plugins/node-globals-polyfill ^0.1.1 → ^0.2.3
@esbuild-plugins/node-modules-polyfill ^0.1.4 → ^0.2.2
@solid-primitives/i18n ^1.1.2 → ^1.1.3
@solidjs/router ^0.6.0 → ^0.7.0
@suid/icons-material ^0.5.5 → ^0.5.8
@suid/material ^0.9.1 → ^0.10.1
jsdom >=21.0.0 → >=21.1.0
solid-js ^1.6.9 → ^1.6.10
typescript ^4.9.4 → ^4.9.5
vite >=4.0.4 → >=4.1.1
vitest >=0.27.1 → >=0.28.4
Run pnpm install to install new versions.
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ sudo npm i -g npm-check-updates
[sudo] Mot de passe de vdv :
npm WARN deprecated @npmcli/move-file@2.0.1: This functionality has been moved to @npmcli/fs
added 11 packages, and changed 285 packages in 17s
56 packages are looking for funding
run `npm fund` for details
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ npm install
> dyomedea-solid@0.0.0 postinstall
> node ./fix-jest-dom.mjs
added 20 packages, removed 2 packages, changed 21 packages, and audited 625 packages in 25s
91 packages are looking for funding
run `npm fund` for details
2 critical severity vulnerabilities
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
vdv@nuc:~/projects/tea/dyomedea/dyomedea$ npm outdated
Package Current Wanted Latest Location Depended by
solid-testing-library 0.5.0 0.5.1 0.5.1 node_modules/solid-testing-library dyomedea
vdv@nuc:~/projects/tea/dyomedea/dyomedea$
```

View File

@ -1,11 +0,0 @@
{
"overrides": [
{
"filename": "**/fr.*",
"language": "fr"
}
],
"words": [
"Clusterable"
]
}

View File

@ -1,12 +1,10 @@
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.dyomedea.dyomedea',
appName: 'dyomedea',
webDir: 'dist',
server: {
androidScheme: 'https'
}
appId: 'com.dyomedea.dyomedea2',
appName: 'dyomedea2',
webDir: 'build',
bundledWebRuntime: false
};
export default config;

View File

@ -1,63 +0,0 @@
import {
overlayDefinitions,
osmTags,
} from './src/components/overlays/overlay-definitions';
// One timer
// let tags = {};
// let overlays = {};
// 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) });
}

View File

@ -1,16 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="shortcut icon" type="image/ico" href="/src/assets/favicon.ico" />
<title>Solid App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="/src/index.tsx" type="module"></script>
</body>
</html>

7
ionic.config.json Normal file
View File

@ -0,0 +1,7 @@
{
"name": "dyomedea",
"integrations": {
"capacitor": {}
},
"type": "react"
}

8702
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,70 +1,85 @@
{
"name": "dyomedea-solid",
"version": "0.0.0",
"description": "",
"type": "module",
"scripts": {
"start": "vite",
"dev": "vite",
"build": "vite build",
"serve": "vite preview --host",
"test": "vitest",
"postinstall": "patch-package"
},
"license": "GPL-3.0-only",
"devDependencies": {
"@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.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"
},
"name": "dyomedea",
"version": "0.0.2",
"private": true,
"dependencies": {
"@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": "^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",
"@awesome-cordova-plugins/geolocation": "^6.2.0",
"@capacitor/android": "^4.5.0",
"@capacitor/app": "^4.1.1",
"@capacitor/core": "^4.5.0",
"@capacitor/haptics": "^4.1.0",
"@capacitor/keyboard": "^4.1.0",
"@capacitor/status-bar": "^4.1.0",
"@ionic/react": "^6.3.7",
"@ionic/react-router": "^6.3.7",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.4.3",
"@types/jest": "^29.2.3",
"@types/node": "^18.11.9",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"@types/react-router": "^5.1.19",
"@types/react-router-dom": "^5.3.3",
"ionicons": "^6.0.4",
"isomorphic-xml2js": "^0.1.3",
"jotai": "^1.10.0",
"jotai-location": "^0.2.0",
"lodash": "^4.17.21",
"memoizee": "^0.4.15",
"ol": "^8.1.0",
"osmtogeojson": "^3.0.0-beta.5",
"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"
}
"pouchdb": "^7.3.1",
"pouchdb-browser": "^7.3.1",
"pouchdb-find": "^7.3.1",
"react": "^18.2.0",
"react-cool-dimensions": "^2.0.7",
"react-dom": "^18.2.0",
"react-localization": "^1.0.19",
"react-router": "^6.4.3",
"react-router-dom": "^6.4.3",
"react-scripts": "^5.0.1",
"typedoc": "^0.23.21",
"typescript": "^4.9.3",
"web-vitals": "^3.1.0",
"workbox-background-sync": "^6.5.4",
"workbox-broadcast-update": "^6.5.4",
"workbox-cacheable-response": "^6.5.4",
"workbox-core": "^6.5.4",
"workbox-expiration": "^6.5.4",
"workbox-navigation-preload": "^6.5.4",
"workbox-precaching": "^6.5.4",
"workbox-range-requests": "^6.5.4",
"workbox-routing": "^6.5.4",
"workbox-strategies": "^6.5.4",
"workbox-streams": "^6.5.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(@ionic/react|@ionic/react-router|@ionic/core|@stencil/core|ionicons)/)'",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@capacitor/cli": "^4.5.0",
"@ionic/cli": "^6.20.4",
"@types/lodash": "^4.14.189",
"@types/pouchdb": "^6.4.0"
},
"description": "An Ionic project"
}

View File

@ -1,13 +0,0 @@
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

@ -1,33 +0,0 @@
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,

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 930 B

BIN
public/assets/icon/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

1
public/assets/shapes.svg Normal file
View File

@ -0,0 +1 @@
<svg width="350" height="140" xmlns="http://www.w3.org/2000/svg" style="background:#f6f7f9"><g fill="none" fill-rule="evenodd"><path fill="#F04141" style="mix-blend-mode:multiply" d="M61.905-34.23l96.194 54.51-66.982 54.512L22 34.887z"/><circle fill="#10DC60" style="mix-blend-mode:multiply" cx="155.5" cy="135.5" r="57.5"/><path fill="#3880FF" style="mix-blend-mode:multiply" d="M208.538 9.513l84.417 15.392L223.93 93.93z"/><path fill="#FFCE00" style="mix-blend-mode:multiply" d="M268.625 106.557l46.332-26.75 46.332 26.75v53.5l-46.332 26.75-46.332-26.75z"/><circle fill="#7044FF" style="mix-blend-mode:multiply" cx="299.5" cy="9.5" r="38.5"/><rect fill="#11D3EA" style="mix-blend-mode:multiply" transform="rotate(-60 148.47 37.886)" x="143.372" y="-7.056" width="10.196" height="89.884" rx="5.098"/><path d="M-25.389 74.253l84.86 8.107c5.498.525 9.53 5.407 9.004 10.905a10 10 0 0 1-.057.477l-12.36 85.671a10.002 10.002 0 0 1-11.634 8.42l-86.351-15.226c-5.44-.959-9.07-6.145-8.112-11.584l13.851-78.551a10 10 0 0 1 10.799-8.219z" fill="#7044FF" style="mix-blend-mode:multiply"/><circle fill="#0CD1E8" style="mix-blend-mode:multiply" cx="273.5" cy="106.5" r="20.5"/></g></svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

18
public/assets/test.svg Normal file
View File

@ -0,0 +1,18 @@
<svg width="1000" height="1000" xmlns="http://www.w3.org/2000/svg">
<g transform="scale(256) translate(-110000, -110000) ">
<path d=" M 110000,110000 L 111000, 111000" pointer-events="none" style="
vector-effect: non-scaling-stroke;
stroke-width: 2px
fill: transparent;
stroke: black;
"/>
</g>
</svg>
<!--
vector-effect: non-scaling-stroke;
stroke-width: 2
-->
<!--
stroke-width: 0.00781211;
-->

After

Width:  |  Height:  |  Size: 428 B

31
public/index.html Normal file
View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Ionic App</title>
<base href="/" />
<meta name="color-scheme" content="light dark" />
<meta
name="viewport"
content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="shortcut icon" type="image/png" href="%PUBLIC_URL%/assets/icon/favicon.png" />
<!-- add to homescreen for ios -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Ionic App" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
</head>
<body>
<div id="root"></div>
</body>
</html>

21
public/manifest.json Normal file
View File

@ -0,0 +1,21 @@
{
"short_name": "Ionic App",
"name": "My Ionic App",
"icons": [
{
"src": "assets/icon/favicon.png",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "assets/icon/icon.png",
"type": "image/png",
"sizes": "512x512",
"purpose": "maskable"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#ffffff",
"background_color": "#ffffff"
}

View File

@ -1 +0,0 @@
import '@testing-library/jest-dom';

View File

@ -1,33 +0,0 @@
.App {
text-align: center;
}
.logo {
animation: logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
.header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.link {
color: #b318f0;
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

8
src/App.test.tsx Normal file
View File

@ -0,0 +1,8 @@
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders without crashing', () => {
// const { baseElement } = render(<App />);
// expect(baseElement).toBeDefined();
});

View File

@ -1,13 +1,161 @@
import type { Component } from 'solid-js';
import { Routes, Route, Navigate } from '@solidjs/router';
import Map from './components/map';
import {
IonApp,
IonButtons,
IonContent,
IonFooter,
IonHeader,
IonToolbar,
setupIonicReact,
} from '@ionic/react';
const App: Component = () => {
/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';
/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';
/* Optional CSS utils that can be commented out */
import '@ionic/react/css/padding.css';
import '@ionic/react/css/float-elements.css';
import '@ionic/react/css/text-alignment.css';
import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';
/* Theme variables */
import './theme/variables.css';
import dispatch from './workers/dispatcher-main';
import LiveMap from './components/map/LiveMap';
import { atom, useAtom } from 'jotai';
import { atomWithHash } from 'jotai-location';
import { MapScope } from './components/map/types';
import { debounce } from 'lodash';
import GetLocation from './components/buttons/GetLocation';
import { geoPoint } from './components/map/types';
import Back from './components/buttons/Back';
import Forward from './components/buttons/Forward';
import CurrentLocation from './components/map/CurrentLocation';
import GpxImport from './components/dialogs/GpxImport';
import Gpxes from './components/map/Gpxes';
import MapChooser from './components/dialogs/MapChooser';
import Explorer from './components/dialogs/Explorer';
// import { initDb } from './db';
// import PouchDB from 'pouchdb';
// import PouchDBFind from 'pouchdb-find';
// PouchDB.plugin(PouchDBFind);
setupIonicReact();
// See https://stackoverflow.com/questions/71538643/property-wakelock-does-not-exist-on-type-navigator
const requestWakeLock = async () => {
const anyNav: any = navigator;
if ('wakeLock' in navigator) {
try {
const wakeLock = await anyNav['wakeLock'].request('screen');
} catch (err: any) {
// The wake lock request fails - usually system-related, such as low battery.
console.log(`Wake lock request failed: ${err.name}, ${err.message}`);
}
} else {
console.log('No wake lock support here...');
}
};
const handleVisibilityChange = () => {
if (document.hidden) {
console.log('Application hidden');
} else {
console.log('Application visible');
requestWakeLock();
}
};
// See https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
document.addEventListener('visibilitychange', handleVisibilityChange, false);
requestWakeLock();
const initialScope: MapScope = {
center: { lat: -37.8403508, lon: 77.5539501 },
zoom: 13,
tileProvider: 'osm',
};
const scopeAtom = atomWithHash('scope', initialScope);
export const setCenterAtom = atom(null, (get, set, center: geoPoint) => {
const previousScope = get(scopeAtom);
const newScope: MapScope = {
...previousScope,
center: center,
};
set(scopeAtom, newScope);
});
export const tileProviderAtom = atom(
(get) => get(scopeAtom).tileProvider,
(get, set, tileProvider: string) => {
const previousScope = get(scopeAtom);
const newScope: MapScope = {
...previousScope,
tileProvider,
};
set(scopeAtom, newScope);
}
);
// const db = new PouchDB('dyomedea', { auto_compaction: true, revs_limit: 10 });
// initDb(db);
dispatch({ action: 'initDb' });
//dispatch({ action: 'getGpxesForViewport', params: { type: 'tech' } });
/**
*
* @returns The root app component
*/
const App: React.FC = () => {
const [scope, setScope] = useAtom(scopeAtom);
console.log(`App, scope: ${JSON.stringify(scope)}`);
return (
<Routes>
<Route path='/map/:provider/:lon/:lat/:zoom/:rotation' component={Map} />
<Route path='/*' element={<Navigate href='/map/osm/0/0/2/0' />} />
</Routes>
<IonApp>
<IonContent fullscreen={true}>
<IonApp>
<LiveMap
scope={scope}
setScope={debounce(setScope, 1000)}
numberOfTiledLayers={5}
slippyGraphics={[
<CurrentLocation key='currentLocation' />,
<Gpxes key='gpxes' />,
]}
/>
</IonApp>
</IonContent>
<Explorer/>
<IonHeader className='ion-no-border' translucent={true}>
<IonToolbar>
<IonButtons slot='start'>
<Back />
<Forward />
</IonButtons>
<IonButtons slot='end'>
<GpxImport />
<MapChooser />
</IonButtons>
</IonToolbar>
</IonHeader>
<IonFooter className='ion-no-border'>
<IonToolbar>
<IonButtons>
<GetLocation />
</IonButtons>
</IonToolbar>
</IonFooter>
</IonApp>
);
};

View File

@ -1,222 +0,0 @@
import { Component, createSignal, For } from 'solid-js';
import PersonIcon from '@suid/icons-material/Person';
import {
Box,
Button,
DialogActions,
InputLabel,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
NativeSelect,
TextField,
} from '@suid/material';
import { useI18n } from '@solid-primitives/i18n';
import Dialog from '../dialog';
import dispatch from '../../workers/dispatcher-main';
import { cloneDeep } from 'lodash';
import { getAccountById } from '../../db/account';
const Account: Component<{}> = (props) => {
const [t] = useI18n();
const [open, setOpen] = createSignal(false);
const [settings, setSettings] = createSignal<any>();
const [accounts, setAccounts] = createSignal<any>();
const [account, setAccount] = createSignal<any>({});
const handleClickOpen = async () => {
setOpen(true);
const newSettings: any = await dispatch({
action: 'getSettings',
});
setSettings(newSettings || {});
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))
);
console.log({
caller: 'Account / handleClickOpen',
settings: settings(),
accounts: accounts(),
});
};
const handleClose = (event: any, reason?: string) => {
console.log({
caller: 'Account / handleClose',
event,
reason,
});
if (reason === undefined) {
setOpen(false);
}
};
const changeAccountHandler = (event: any) => {
const selectedAccountId = event.target.value;
setAccount(cloneDeep(getAccountById(accounts(), selectedAccountId)));
console.log({
caller: 'Account / changeAccountHandler',
event,
selectedAccountId: selectedAccountId,
account: account(),
});
};
const changeHandlerFactory = (path: string) => (event: any) => {
const value = event.target.value;
const newAccount = cloneDeep(account());
newAccount[path] = value;
setAccount(newAccount);
console.log({
caller: 'Account / changeHandlerFactory / ' + path,
event,
value,
account: account(),
});
};
const saveHandler = async () => {
const updatedAccount = account();
if (updatedAccount.id === '--new--') {
updatedAccount.id = updatedAccount.name;
}
await dispatch({
action: 'putAccount',
params: { id: updatedAccount.id, account: updatedAccount },
});
const updatedSettings = {
...settings(),
currentAccountId: updatedAccount.id,
};
await dispatch({
action: 'putSettings',
params: { settings: updatedSettings },
});
console.log({
caller: 'Account / saveHandler',
account: account(),
updatedAccount,
settings: settings(),
updatedSettings,
});
handleClose();
location.reload();
};
const isValid = () => {
if (!account().localDb) {
return false;
}
//TODO: add more tests
return true;
};
return (
<>
<ListItem>
<ListItemButton onClick={handleClickOpen}>
<ListItemIcon>
<PersonIcon />
</ListItemIcon>
<ListItemText>Account</ListItemText>
</ListItemButton>
</ListItem>
<Dialog
open={open()}
title={t('account')}
closeHandler={handleClose}
fullScreen={true}
>
<Box
component='form'
sx={{
width: '100%',
'& .MuiTextField-root': { m: 1, width: '100%' },
paddingTop: '5px',
}}
noValidate
autoComplete='off'
>
<InputLabel variant='normal' htmlFor='account-chooser'>
{t('accountChooser')}
</InputLabel>
<NativeSelect
inputProps={{
name: 'account-chooser',
id: 'account-chooser',
}}
onChange={changeAccountHandler}
>
<For each={accounts()}>
{(account: any) => (
<option
value={account.id}
selected={account.id === settings().currentAccountId}
>
{account.name}
</option>
)}
</For>
</NativeSelect>
<TextField
label={t('accountName')}
value={account().name || ''}
onChange={changeHandlerFactory('name')}
/>
<TextField
label={t('localDb')}
value={account().localDb || ''}
onChange={changeHandlerFactory('localDb')}
/>
<TextField
label={t('remoteDbServer')}
value={account().remoteDbServer || ''}
onChange={changeHandlerFactory('remoteDbServer')}
/>
<TextField
label={t('remoteDbUser')}
value={account().remoteDbUser || ''}
onChange={changeHandlerFactory('remoteDbUser')}
/>
<TextField
label={t('remoteDbPassword')}
value={account().remoteDbPassword || ''}
onChange={changeHandlerFactory('remoteDbPassword')}
/>
</Box>
<DialogActions>
<Button
variant='contained'
disabled={!isValid()}
onClick={saveHandler}
>
{t('accountSave')}
</Button>
<Button variant='outlined' color='secondary' onClick={handleClose}>
{t('accountCancel')}
</Button>
</DialogActions>
</Dialog>
</>
);
};
export default Account;

View File

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

View File

@ -1,33 +0,0 @@
import { Component, JSXElement } from 'solid-js';
import { Alert as MuiAlert } from '@suid/material';
import { AlertColor } from '@suid/material/Alert';
import Dialog from '../dialog';
interface Props {
open: boolean;
closeHandler: (event: any, reason?: string) => void;
severity?: AlertColor;
icon?: JSXElement;
action?: JSXElement;
children?: JSXElement;
}
const Alert: Component<Props> = ({
open,
closeHandler,
severity,
icon,
action,
children,
}) => {
return (
<Dialog open={open()} closeHandler={closeHandler} maxWidth={false}>
<MuiAlert severity={severity} icon={icon} action={action}>
{children}
</MuiAlert>
</Dialog>
);
};
export default Alert;

View File

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

View File

@ -1,45 +0,0 @@
import { Component, createEffect, For, onCleanup, Suspense } from 'solid-js';
import OlMap from 'ol/Map';
import Gpx from '../gpx';
import {
createCachedSignal,
destroyCachedSignal,
} from '../../workers/cached-signals';
interface Props {
map: () => OlMap | null;
}
export const AllGpxes: Component<Props> = ({ map }) => {
const params = {
id: 'gpx',
method: 'getAllGpxes',
};
const allGpxIds = createCachedSignal(params);
onCleanup(() => {
destroyCachedSignal(params);
});
createEffect(() => {
console.log({ caller: 'AllGpxes', allGpxes: allGpxIds(), map: map() });
});
return (
// @ts-ignore
<For each={allGpxIds()}>
{(gpxId: string) => {
console.log({ caller: 'AllGpxes / loop', gpxId });
return (
<Suspense>
<Gpx map={map} gpxId={gpxId} />
</Suspense>
);
}}
</For>
);
};
export default AllGpxes;

View File

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

View File

@ -1,16 +0,0 @@
.common {
opacity: 1;
position: fixed !important;
top: 6px;
z-index: 1;
}
.back {
composes: common;
margin-left: 6px !important;
}
.forward {
composes: common;
margin-left: 40px !important;
}

View File

@ -1,30 +0,0 @@
import { Component, createEffect, createSignal } from 'solid-js';
import { IconButton } from '@suid/material';
import ArrowBackIcon from '@suid/icons-material/ArrowBack';
import ArrowForwardIcon from '@suid/icons-material/ArrowForward';
import styles from './BackForward.module.css';
export const Back: Component = () => {
const onClickHandler = (event: any) => {
window.history.back();
};
return (
<IconButton onClick={onClickHandler} class={styles.back}>
<ArrowBackIcon />
</IconButton>
);
};
export const Forward: Component = () => {
const onClickHandler = (event: any) => {
window.history.forward();
};
return (
<IconButton onClick={onClickHandler} class={styles.forward}>
<ArrowForwardIcon />
</IconButton>
);
};

View File

@ -1 +0,0 @@
export { Back, Forward } from './BackForward';

View File

@ -0,0 +1,26 @@
import react from 'react';
import { IonButton, IonIcon } from '@ionic/react';
import { arrowBackCircleOutline } from 'ionicons/icons';
import './BackForward.css';
export interface BackProperties {}
export const Back: react.FC<BackProperties> = (props: BackProperties) => {
const onClickHandler = (event: any) => {
window.history.back();
};
return (
<IonButton
onClick={onClickHandler}
size='large'
className='back-forward'
shape='round'
fill='solid'
>
<IonIcon slot='icon-only' icon={arrowBackCircleOutline} />
</IonButton>
);
};
export default Back;

View File

@ -0,0 +1,5 @@
ion-button.back-forward {
--opacity: 0.6;
--ion-background-color: white;
--ionicon-stroke-width: 48px;
}

View File

@ -0,0 +1,26 @@
import react from 'react';
import { IonButton, IonIcon } from '@ionic/react';
import { arrowForwardCircleOutline } from 'ionicons/icons';
import './BackForward.css';
export interface ForwardProperties {}
export const Forward: react.FC<ForwardProperties> = (props: ForwardProperties) => {
const onClickHandler = (event: any) => {
window.history.forward();
};
return (
<IonButton
onClick={onClickHandler}
size='large'
className='back-forward'
shape='round'
fill='solid'
>
<IonIcon slot='icon-only' icon={arrowForwardCircleOutline} />
</IonButton>
);
};
export default Forward;

View File

@ -0,0 +1,6 @@
ion-button.get-location {
--opacity: 0.6;
--ion-background-color: white;
margin-left: calc(50% - 20px);
}

View File

@ -0,0 +1,46 @@
import React from 'react';
import { Geolocation } from '@awesome-cordova-plugins/geolocation';
import './GetLocation.css';
import { IonButton, IonIcon } from '@ionic/react';
import { locateOutline } from 'ionicons/icons';
import { useAtom } from 'jotai';
import { setCenterAtom } from '../../App';
import { locationAtom } from '../map/CurrentLocation';
const GetLocation: React.FC<{}> = () => {
const [, setCenter] = useAtom(setCenterAtom);
const [, setLocation] = useAtom(locationAtom);
const onClickHandler = (event: any) => {
console.log('Click handler');
Geolocation.getCurrentPosition().then((position) => {
console.log(
`Click handler, position: ${position.coords.latitude}, ${position.coords.longitude}`
);
setCenter({
lat: position.coords.latitude,
lon: position.coords.longitude,
});
setLocation({
lat: position.coords.latitude,
lon: position.coords.longitude,
});
});
};
return (
<IonButton
onClick={onClickHandler}
className='get-location get-position'
shape='round'
size='small'
fill='solid'
>
<IonIcon slot='icon-only' icon={locateOutline} color='white' />
</IonButton>
);
};
export default GetLocation;

View File

@ -1,54 +0,0 @@
import { Component, JSXElement, Show } from 'solid-js';
import {
Dialog as MuiDialog,
DialogContent,
DialogTitle,
IconButton,
} from '@suid/material';
import CloseIcon from '@suid/icons-material/Close';
const Dialog: Component<{
open: boolean;
fullScreen?: boolean;
maxWidth?: boolean;
title?: JSXElement;
closeHandler: (event: any, reason?: string) => void;
children: JSXElement;
}> = (props) => {
return (
<MuiDialog
onClose={props.closeHandler}
open={props.open}
PaperProps={{ sx: { minWidth: '300px' } }}
fullScreen={props.fullScreen}
>
<Show when={props.title}>
<DialogTitle
sx={{
backgroundColor: 'rgba(14, 116, 144, 0.7)',
color: 'white',
clear: 'both',
margin: '0',
paddingLeft: '0',
}}
>
<IconButton onClick={props.closeHandler}>
<CloseIcon />
</IconButton>
{props.title}
</DialogTitle>
</Show>
<DialogContent
sx={{
width: 'calc(100% - 60px)',
paddingBottom:
props.maxWidth === undefined || props.maxWidth ? '2000px' : '2px',
}}
>
{props.children}
</DialogContent>
</MuiDialog>
);
};
export default Dialog;

View File

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

View File

@ -0,0 +1,50 @@
import {
IonModal,
IonToolbar,
IonTitle,
IonButtons,
IonButton,
IonContent,
IonList,
} from '@ionic/react';
import react, { useRef, useState } from 'react';
import { atom, useAtom } from 'jotai';
import i18n from '../../i18n';
import cssDialog from './dialogs.module.css';
export interface ExplorerProperties {}
export const isOpenAtom = atom(false);
export const Explorer: react.FC<ExplorerProperties> = (
props: ExplorerProperties
) => {
const modal = useRef<HTMLIonModalElement>(null);
const [isOpen, setIsOpen] = useAtom(isOpenAtom);
const dismiss = () => {
setIsOpen(false);
};
return (
<IonModal
ref={modal}
className={cssDialog.modal}
isOpen={isOpen}
onDidDismiss={dismiss}
>
<IonToolbar>
<IonTitle>{i18n.explorer.nearBy}</IonTitle>
<IonButtons slot='end'>
<IonButton onClick={dismiss}>{i18n.common.close}</IonButton>
</IonButtons>
</IonToolbar>
<IonContent>
<IonList></IonList>
</IonContent>
</IonModal>
);
};
export default Explorer;

View File

@ -0,0 +1,8 @@
.inputFile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}

View File

@ -0,0 +1,72 @@
import React from 'react';
import GPX from '../../lib/gpx-parser-builder/src/gpx';
import css from './GpxImport.module.css';
import { IonIcon, IonItem } from '@ionic/react';
import { cloudUpload } from 'ionicons/icons';
import { findStartTime } from '../../lib/gpx';
import dispatch from '../../workers/dispatcher-main';
import { intToGpxId } from '../../lib/ids';
const GpxImport: React.FC<{}> = () => {
const onChangeHandler = (event: any) => {
console.log('On change handler');
const file: File = event.target.files[0];
const fileReader = new FileReader();
fileReader.readAsText(file);
fileReader.addEventListener(
'load',
() => {
// this will then display a text file
console.log(fileReader.result);
const gpx = GPX.parse(fileReader.result);
console.log(`gpx: ${JSON.stringify(gpx)}`);
const startTime = new Date(findStartTime(gpx)!);
dispatch({
action: 'pruneAndSaveImportedGpx',
params: {
id: { gpx: intToGpxId(startTime.valueOf()) },
gpx: gpx,
tech: {
lastModified: new Date(file.lastModified).toISOString(),
importDate: new Date().toISOString(),
name: file.name,
size: file.size,
type: file.type,
},
},
});
// pushGpx(db, {
// gpx,
// metadata: {
// lastModified: new Date(file.lastModified).toISOString(),
// importDate: new Date().toISOString(),
// name: file.name,
// size: file.size,
// type: file.type,
// },
// });
},
false
);
};
return (
<IonItem>
<input
type='file'
id='gpx-import'
className={css.inputFile}
accept='.gpx'
onChange={onChangeHandler}
/>
<label htmlFor='gpx-import'>
<IonIcon slot='icon-only' icon={cloudUpload} title='import' />
</label>
</IonItem>
);
};
export default GpxImport;

View File

@ -0,0 +1,78 @@
import react, { useRef } from 'react';
import {
IonButton,
IonButtons,
IonContent,
IonIcon,
IonItem,
IonLabel,
IonList,
IonModal,
IonRadio,
IonRadioGroup,
IonTitle,
IonToolbar,
} from '@ionic/react';
import { layersOutline } from 'ionicons/icons';
import { nonFakeTileProviders } from '../map/tile-providers';
import { tileProviderAtom } from '../../App';
import i18n from '../../i18n/index';
import { useAtom } from 'jotai';
import cssDialog from './dialogs.module.css';
export interface MapChooserProperties {}
export const MapChooser: react.FC<MapChooserProperties> = (
props: MapChooserProperties
) => {
const modal = useRef<HTMLIonModalElement>(null);
const dismiss = () => {
modal.current?.dismiss();
};
const [tileProvider, setTileProvider] = useAtom(tileProviderAtom);
const changeHandler = (event: any) => {
setTileProvider(event.detail.value);
dismiss();
};
return (
<>
<IonButton id='open-TileServerChooser'>
<IonIcon slot='icon-only' icon={layersOutline} />
</IonButton>
<IonModal
trigger='open-TileServerChooser'
ref={modal}
className={cssDialog.modal}
>
<IonToolbar>
<IonTitle>{i18n.mapChooser.chooseYourMap}</IonTitle>
<IonButtons slot='end'>
<IonButton onClick={() => dismiss()}>{i18n.common.close}</IonButton>
</IonButtons>
</IonToolbar>
<IonContent>
<IonList>
<IonRadioGroup value={tileProvider} onIonChange={changeHandler}>
{Object.keys(nonFakeTileProviders).map((provider) => {
return (
<IonItem key={provider}>
<IonLabel> {nonFakeTileProviders[provider].name}</IonLabel>
<IonRadio slot='start' value={provider} />
</IonItem>
);
})}
</IonRadioGroup>
</IonList>
</IonContent>
</IonModal>
</>
);
};
export default MapChooser;

View File

@ -0,0 +1,15 @@
.modal {
--height: 100%;
--border-radius: 16px;
--box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1),
0 4px 6px -4px rgb(0 0 0 / 0.1);
}
.modal ion-toolbar {
--background: rgba(14, 116, 144, 0.7);
--color: white;
}
.modal ion-content {
background-color: rgba(255, 255, 255, 0.7);
}

View File

@ -1,43 +0,0 @@
import { IconButton } from '@suid/material';
import SearchIcon from '@suid/icons-material/Search';
import { Component, Show } from 'solid-js';
import { findAddress, getVillageOrTown } from '../../lib/osm';
import { cloneDeep } from 'lodash';
import { useI18n } from '@solid-primitives/i18n';
import dispatch from '../../workers/dispatcher-main';
interface Props {
wpt: () => Wpt;
dispatchParams: (wpt: Wpt) => { action: string; params: any };
}
const DisplayOrGetAddress: Component<Props> = ({ wpt, dispatchParams }) => {
const [t, { add, locale, dict }] = useI18n();
const findClickHandler = async () => {
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;
dispatch(dispatchParams(updatedTarget));
};
return (
<Show
when={wpt()?.extensions?.address}
fallback={
<IconButton color='primary' onClick={findClickHandler}>
<SearchIcon />
</IconButton>
}
>
<>{getVillageOrTown(wpt()?.extensions?.address)}</>
</Show>
);
};
export default DisplayOrGetAddress;

View File

@ -1,36 +0,0 @@
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,2 +0,0 @@
export { default } from './DisplayOrGetAddress';
export { default as DisplayOrGetStartEndAddresses } from './DisplayOrGetStartEndAddresses';

View File

@ -1,222 +0,0 @@
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

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

View File

@ -1,56 +0,0 @@
.control {
opacity: 1;
position: fixed !important;
top: 0px;
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;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
padding: 15px;
border-radius: 10px;
border: 1px solid #cccccc;
bottom: 12px;
left: -50px;
min-width: 280px;
}
.ol_popup:after,
.ol_popup:before {
top: 100%;
border: solid transparent;
content: ' ';
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.ol_popup:after {
border-top-color: white;
border-width: 10px;
left: 48px;
margin-left: -10px;
}
.ol_popup:before {
border-top-color: #cccccc;
border-width: 11px;
left: 48px;
margin-left: -11px;
}
.ol_popup_closer {
text-decoration: none;
position: absolute;
top: 2px;
right: 8px;
}
.ol_popup_closer:after {
content: '✖';
}

View File

@ -1,216 +0,0 @@
import { Coordinate } from 'ol/coordinate';
import { Component, createEffect, createSignal } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import SearchIcon from '@suid/icons-material/Search';
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);
const [coordinate, setCoordinate] = createSignal<Coordinate>();
let popupElement: HTMLElement;
export const findLocation = (
navigate: (url: string) => void,
coordinate: Coordinate
) => {
setOpen(false);
if (popup() === undefined) {
setPopup(
new Overlay({
element: popupElement,
positioning: 'center-center',
})
);
}
console.log({
caller: 'Finder / submitHandler / popup',
coordinate,
popup: popup(),
popupElement,
});
setCoordinate(coordinate);
popup().setMap(getMap());
popup().setPosition(fromLonLat(coordinate));
getMap()?.addOverlay(popup());
navigate(
`/map/${getState().provider}/${coordinate[0]}/${coordinate[1]}/16/${
getState().rotation
}`
);
};
interface Props {}
const Finder: Component<Props> = (props) => {
const [searchString, setSearchString] = createSignal('');
const [popupContent, setPopupContent] = createSignal(<></>);
const [t, { add, locale, dict }] = useI18n();
const searchStringChangeHandler = (event: any) => {
setSearchString(event.target.value);
};
const navigate = useNavigate();
const popupCloseHandler = () => {
popup()?.setMap(null);
};
const submitHandler = () => {
setCoordinate(undefined);
const latLonRegExp = /(-?[0-9]+.[0-9]+)\s*,\s*(-?[0-9]+.[0-9]+)/;
const latLonMatch = searchString().match(latLonRegExp);
if (!!latLonMatch) {
setCoordinate([+latLonMatch[2], +latLonMatch[1]]);
setPopupContent(<>{latLonMatch[0]}</>);
console.log({
caller: 'Finder / submitHandler',
searchString: searchString(),
latLonMatch,
coordinate: coordinate(),
});
} else {
const utmRegExp = /([0-6]?[0-9])\s*([C-X])\s*([0-9]+)\s*([0-9]+)/;
const utmMatch = searchString().match(utmRegExp);
if (!!utmMatch) {
const utm = `+proj=utm +zone=${utmMatch[1]}`;
setCoordinate(proj4(utm, 'EPSG:4326', [+utmMatch[3], +utmMatch[4]]));
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(),
});
}
}
}
if (!!coordinate()) {
findLocation(navigate, coordinate());
}
};
const [openCreateWptDialog, setOpenCreateWptDialog] = createSignal(false);
const createWptCloseHandler = () => {
setOpenCreateWptDialog(false);
popupCloseHandler();
};
return (
<>
<div
class={
window.Capacitor.platform === 'web'
? style.control_web
: style.control
}
>
<IconButton
onClick={() => {
setOpen(true);
}}
>
<SearchIcon />
</IconButton>
</div>
<Dialog
closeHandler={() => {
setOpen(false);
}}
open={open()}
title={t('search')}
>
<Box
component='form'
sx={{
width: '100%',
'& .MuiTextField-root': { m: 1, width: '100%' },
paddingTop: '5px',
}}
noValidate
autoComplete='off'
onSubmit={submitHandler}
method='dialog'
>
<TextField onChange={searchStringChangeHandler} />
<Button variant='contained' onClick={submitHandler}>
Search
</Button>
</Box>
</Dialog>
<div class={style.ol_popup + ' ol_popup'} ref={popupElement}>
<a
href='#'
onclick={popupCloseHandler}
class={style.ol_popup_closer}
></a>
<div>
<div>{popupContent()}</div>
<div>
<Button
onClick={() => {
setOpenCreateWptDialog(true);
}}
>
New waypoint
</Button>
</div>
<WptEditDialog
open={openCreateWptDialog}
closeHandler={createWptCloseHandler}
coordinate={coordinate}
/>
</div>
</div>
</>
);
};
export default Finder;

View File

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

View File

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

View File

@ -1,7 +0,0 @@
.getLocation {
opacity: 1;
margin-left: calc(50% - 20px) !important;
position: fixed !important;
z-index: 1;
bottom: 6px;
}

View File

@ -1,41 +0,0 @@
import { Component, createEffect, createSignal } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { Geolocation } from '@awesome-cordova-plugins/geolocation';
import style from './GetLocation.module.css';
import LocationSearchingIcon from '@suid/icons-material/LocationSearching';
import { IconButton } from '@suid/material';
import { getState } from '../map';
export const [getCurrentLocation, setCurrentLocation] = createSignal<{
lon: number;
lat: number;
} | null>(null);
const GetLocation: Component = () => {
const navigate = useNavigate();
const onClickHandler = (event: any) => {
console.log('Click handler');
Geolocation.getCurrentPosition().then((position) => {
console.log({ caller: 'GetLocation/onClickHandler', position });
const state = getState();
navigate(
`/map/${state.provider}/${position.coords.longitude}/${position.coords.latitude}/${state.zoom}/${state.rotation}`
);
setCurrentLocation({
lon: position.coords.longitude,
lat: position.coords.latitude,
});
});
};
//
return (
<IconButton class={style.getLocation} onClick={onClickHandler}>
<LocationSearchingIcon />
</IconButton>
);
};
export default GetLocation;

View File

@ -1,12 +0,0 @@
<svg height="24" width="24" xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle
cx="12"
cy="12"
r="6"
fill='blue'
opacity='90%'
stroke='white'
stroke-width="4"
stroke-opacity='100%'
/>
</svg>

Before

Width:  |  Height:  |  Size: 240 B

View File

@ -1 +0,0 @@
export { default, getCurrentLocation, setCurrentLocation } from './GetLocation';

View File

@ -1,68 +0,0 @@
import { useI18n } from '@solid-primitives/i18n';
import { FormControl, InputLabel, NativeSelect } from '@suid/material';
import { Component, createSignal, For } from 'solid-js';
import dispatch from '../../workers/dispatcher-main';
interface Props {
gpxId: () => string;
setGpxId: (id: string) => void;
disabled?: boolean;
}
const GpxChooser: Component<Props> = (props: Props) => {
const { gpxId, setGpxId, disabled } = props;
const [t] = useI18n();
const [allGpxes, setAllGpxes] = createSignal<any[]>([
{ id: 'new', name: t('newGpx'), creator: 'dyomedea' },
]);
dispatch(
{
action: 'getAllGpxesWithSummary',
},
(error, result) => {
console.log({
caller: 'GpxChooser / getAllGpxesWithSummary',
error,
result,
});
if (!error) {
setAllGpxes([
{ id: 'new', name: t('newGpx'), creator: 'dyomedea' },
...result,
]);
}
}
);
const gpxChangeHandler = async (event: any) => {
setGpxId(event.target.value);
};
return (
<FormControl disabled={disabled}>
<InputLabel variant='normal' htmlFor='gpx-chooser'>
{t('gpxChooser')}
</InputLabel>
<NativeSelect
inputProps={{
name: 'gpx-chooser',
id: 'gpx-chooser',
}}
onChange={gpxChangeHandler}
>
<For each={allGpxes()}>
{(gpx) => (
<option value={gpx.id} selected={gpx.id === gpxId()}>
{gpx.name || `${t('gpxNoName')} (${gpx.creator})`}
</option>
)}
</For>
</NativeSelect>
</FormControl>
);
};
export default GpxChooser;

View File

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

View File

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

View File

@ -1,253 +0,0 @@
import { useI18n } from '@solid-primitives/i18n';
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';
import dispatch from '../../workers/dispatcher-main';
import Dialog from '../dialog';
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');
const GpxDialog: Component<{}> = (props) => {
const [t] = useI18n();
const [open, setOpen] = createSignal(false);
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' || !gpxId) {
return newEmptyGpx();
}
const newGpx = peekCachedSignal({
id: gpxId,
action: 'getGpx',
});
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);
setGpx(fetchGpx(currentGpxId()) as Gpx);
console.log({
caller: 'GpxDialog / handleClickOpen',
currentGpxId: currentGpxId(),
gpx: gpx(),
});
};
const handleClose = (event: any, reason?: string) => {
console.log({
caller: 'GpxDialog / handleClose',
event,
reason,
});
if (reason === undefined) {
setOpen(false);
}
};
const gpxChangeHandler = async (gpxId: string) => {
setSelectedGpxId(gpxId);
setGpx(fetchGpx(gpxId) as Gpx);
console.log({
caller: 'GpxDialog / gpxChangeHandler',
gpxId,
gpx: gpx(),
});
};
const gpxNameChangeHandler = (event: any) => {
const newGpx: Gpx = cloneDeep(gpx()) as Gpx;
if (newGpx.metadata === undefined) {
newGpx.metadata = {};
}
newGpx.metadata.name = event.target.value;
setGpx(newGpx);
console.log({
caller: 'GpxDialog / gpxNameChangeHandler',
value: event.target.value,
gpx: gpx(),
});
};
const gpxDescChangeHandler = (event: any) => {
const newGpx: Gpx = cloneDeep(gpx()) as Gpx;
if (newGpx.metadata === undefined) {
newGpx.metadata = {};
}
newGpx.metadata.desc = event.target.value;
setGpx(newGpx);
console.log({
caller: 'GpxDialog / gpxDescChangeHandler',
value: event.target.value,
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) {
newGpx.metadata = {};
}
newGpx.metadata.time = new Date(event.target.value).toISOString();
setGpx(newGpx);
console.log({
caller: 'GpxDialog / gpxTimeChangeHandler',
value: event.target.value,
gpx: gpx(),
});
};
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',
params: {
id: selectedGpxId(),
gpx: gpx(),
},
})) as string;
setCurrentGpxId(id);
setOpen(false);
await dispatch({
action: 'putCurrentAccount',
params: {
account: { ...currentAccount(), currentGpxId: currentGpxId() },
},
});
};
return (
<>
<div class={style.control}>
<IconButton onClick={handleClickOpen}>
<GpxIcon />
</IconButton>
</div>
<Dialog
open={open()}
title={t('gpxDialog')}
closeHandler={handleClose}
fullScreen={true}
>
<Box
component='form'
sx={{
width: '100%',
'& .MuiTextField-root': { m: 1, width: '100%' },
paddingTop: '5px',
}}
noValidate
autoComplete='off'
>
<GpxChooser gpxId={selectedGpxId} setGpxId={gpxChangeHandler} />
<Show when={gpx() != undefined}>
<TextField
label={t('gpxName')}
value={gpx()?.metadata?.name || ''}
onChange={gpxNameChangeHandler}
/>
<TextField
label={t('gpxTime')}
type='datetime-local'
value={(gpx()?.metadata?.time || '').replace('Z', '')}
onChange={gpxTimeChangeHandler}
/>
<TextField
label={t('gpxDesc')}
multiline={true}
rows={5}
value={gpx()?.metadata?.desc || ''}
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>
</Show>
</Box>
</Dialog>
</>
);
};
export default GpxDialog;

View File

@ -1 +0,0 @@
export { default, currentGpxId, setCurrentGpxId } from './GpxDialog';

View File

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

View File

@ -1,215 +0,0 @@
import {
Box,
Button,
DialogActions,
IconButton,
Typography,
} from '@suid/material';
import FiberManualRecordIcon from '@suid/icons-material/FiberManualRecord';
import { Component, createEffect, createSignal, Show } from 'solid-js';
import style from './GpxRecord.module.css';
import Dialog from '../dialog';
import { useI18n } from '@solid-primitives/i18n';
import GpxChooser from '../gpx-chooser';
import { currentGpxId } from '../gpx-dialog';
import {
startBackgroundGeolocation,
stopBackgroundGeolocation,
} from '../../lib/background-geolocation';
import dispatch from '../../workers/dispatcher-main';
import { emptyTrk } from '../../db/trk';
import getUri from '../../lib/ids';
import { setCurrentLocation } from '../get-location/GetLocation';
import { getState } from '../map';
import { useNavigate } from '@solidjs/router';
declare global {
var $lastValidLocationTime: number;
}
const GpxRecord: Component<{}> = (props) => {
const [t] = useI18n();
const navigate = useNavigate();
const [state, setState] = createSignal('stopped');
const [open, setOpen] = createSignal(false);
const [watcherId, setWatcherId] = createSignal();
const [gpxId, setGpxId] = createSignal<string>('');
const [trksegId, setTrksegId] = createSignal<IdTrkseg>();
const newLocationHandler = async (location: any) => {
console.log(
`Location filtering, elapsed time: ${
location.time - globalThis.$lastValidLocationTime
}`
);
if (
location.accuracy < 10 &&
location.time - globalThis.$lastValidLocationTime > 15000
) {
globalThis.$lastValidLocationTime = location.time;
await dispatch({
action: 'appendTrkpt',
params: {
trksegIdObj: trksegId(),
trkpt: {
$: {
lat: location.latitude,
lon: location.longitude,
},
ele: location.altitude,
time: new Date(location.time).toISOString(),
extensions: {
speed: location.speed,
accuracy: location.accuracy,
},
},
},
});
setCurrentLocation({ lon: location.longitude, lat: location.latitude });
const state = getState();
navigate(
`/map/${state.provider}/${location.longitude}/${location.latitude}/${state.zoom}/${state.rotation}`
);
}
};
const handleClickOpen = () => {
if (state() === 'stopped') {
setGpxId(currentGpxId());
}
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const startRecordingHandler = async () => {
const trkId = await dispatch({
action: 'appendTrk',
params: { gpxId: gpxId(), trk: emptyTrk },
});
const trkIdObj = getUri('trk', trkId);
setTrksegId({ ...trkIdObj, trkseg: 0 });
globalThis.$lastValidLocationTime = 0;
const id = await startBackgroundGeolocation(newLocationHandler, 10);
setWatcherId(id);
setState('recording');
setOpen(false);
};
const pauseRecordingHandler = () => {
stopBackgroundGeolocation(watcherId());
setState('paused');
setOpen(false);
};
const resumeRecordingHandler = async () => {
setTrksegId({ ...trksegId()!, trkseg: trksegId()!.trkseg + 1 });
const id = await startBackgroundGeolocation(newLocationHandler, 10);
setWatcherId(id);
setState('recording');
setOpen(false);
};
const stopRecordingHandler = () => {
stopBackgroundGeolocation(watcherId());
setState('stopped');
setOpen(false);
};
return (
<>
<div class={style.control}>
<IconButton onClick={handleClickOpen}>
<FiberManualRecordIcon
color={
state() === 'recording'
? 'error'
: state() === 'paused'
? 'primary'
: 'inherit'
}
/>
</IconButton>
</div>
<Dialog open={open()} title={t('gpxRecord')} closeHandler={handleClose}>
<Box
sx={{
width: '100%',
paddingTop: '10px',
paddingBottom: '10px',
}}
>
<GpxChooser
gpxId={gpxId}
setGpxId={setGpxId}
disabled={state() !== 'stopped'}
/>
<Typography sx={{ paddingTop: '20px' }} variant='h6'>
{t(`gpx_${state()}`)}
</Typography>
<Show when={state() === 'stopped'}>
<Button
color='primary'
variant='contained'
onClick={startRecordingHandler}
disabled={gpxId() === 'new'}
sx={{
width: '100%',
margin: '10px',
}}
>
{t('gpxStartRecording')}
</Button>
</Show>
<Show when={state() === 'recording'}>
<Button
color='primary'
variant='contained'
onClick={pauseRecordingHandler}
sx={{
width: '100%',
margin: '10px',
}}
>
{t('gpxPauseRecording')}
</Button>
<Button
color='warning'
variant='contained'
onClick={stopRecordingHandler}
sx={{
width: '100%',
margin: '10px',
}}
>
{t('gpxStopRecording')}
</Button>
</Show>
<Show when={state() === 'paused'}>
<Button
color='primary'
variant='contained'
onClick={resumeRecordingHandler}
sx={{
width: '100%',
margin: '10px',
}}
>
{t('gpxResumeRecording')}
</Button>
<Button
color='warning'
variant='contained'
onClick={stopRecordingHandler}
sx={{
width: '100%',
margin: '10px',
}}
>
{t('gpxStopRecording')}
</Button>
</Show>
</Box>
</Dialog>
</>
);
};
export default GpxRecord;

View File

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

View File

@ -1,114 +0,0 @@
import { Component, createEffect, For, onCleanup, Suspense } from 'solid-js';
import OlMap from 'ol/Map';
import Trk from '../trk';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import style from './styles';
import Wpt from '../wpt';
import Rte from '../rte';
import {
createCachedSignal,
destroyCachedSignal,
} from '../../workers/cached-signals';
import { getTagsFromObj } from '../../lib/tags/tags';
interface Props {
gpxId: string;
map: () => OlMap | null;
}
export const Gpx: Component<Props> = ({ map, gpxId }) => {
const params = {
id: gpxId,
method: 'getGpx',
};
const gpx = createCachedSignal(params);
onCleanup(() => {
console.log({
caller: 'Gpx / onCleanup',
gpxId,
gpx: gpx(),
params,
});
destroyCachedSignal(params);
});
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(() => {
console.log({ caller: 'Gpx', map: map(), gpxId, gpx: gpx(), vectorLayers });
});
return (
<>
<For each={gpx() ? gpx().trk || [] : []}>
{(trkId: string) => {
console.log({ caller: 'Gpx / loop', trkId });
return (
<Suspense>
<Trk
vectorSources={vectorSources}
trkId={trkId}
context={{ gpx, gpxId }}
tags={getTagsFromObj(gpx())}
/>
</Suspense>
);
}}
</For>
<For each={gpx() ? gpx().rte || [] : []}>
{(rteId: string) => {
console.log({ caller: 'Gpx / loop', rteId });
return (
<Suspense>
<Rte
vectorSources={vectorSources}
rteId={rteId}
context={{ gpx, gpxId }}
/>
</Suspense>
);
}}
</For>
<For each={gpx() ? gpx().wpt || [] : []}>
{(wptId: string) => {
console.log({ caller: 'Gpx / loop', wptId });
return (
<Suspense>
<Wpt
vectorSources={vectorSources}
wptId={wptId}
context={{ gpx, gpxId }}
/>
</Suspense>
);
}}
</For>
</>
);
};
export default Gpx;

View File

@ -1,32 +0,0 @@
import { SvgIcon } from '@suid/material';
import { Component } from 'solid-js';
const GpxIcon: Component<{}> = (props) => {
return (
<SvgIcon>
<svg
viewBox='0 0 170 170'
width='64px'
height='64px'
version='1.1'
style='stroke-width: 1%; stroke:black'
xml:space='preserve'
xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'
>
<g>
<path d='M63.5,16c-0.3-0.2-0.7-0.3-1-0.1l-20.4,7.3l-14.3-5.2c0.8-2,1.2-3.8,1.2-5.3c0-2.7-1-5.1-2.9-7c-1.9-1.9-4.4-2.9-7-2.9 c-5.5,0-9.9,4.4-9.9,9.9c0,1.9,0.7,4.2,1.9,7L0.7,23.2c-0.4,0.2-0.7,0.6-0.7,1v36c0,0.4,0.2,0.7,0.5,0.9c0.2,0.1,0.4,0.2,0.6,0.2 c0.1,0,0.3,0,0.4-0.1L21.9,54l19.8,7.3c0.2,0.1,0.5,0.1,0.7,0l20.8-7.4c0.4-0.2,0.7-0.6,0.7-1v-36C64,16.5,63.8,16.2,63.5,16z M19.1,4.8c2.1,0,4,0.8,5.4,2.3c0,0,0,0,0,0c1.5,1.4,2.3,3.4,2.3,5.4c0,1.4-0.5,3.3-1.5,5.5c-1.8,4-4.8,8.2-6.2,10.1 c-0.2-0.2-0.3-0.4-0.5-0.7c-1.3-1.8-3.4-4.8-4.9-7.9c-1.5-2.9-2.2-5.3-2.2-7.1C11.4,8.3,14.9,4.8,19.1,4.8z M61.8,52.1l-19.7,7 l-19.8-7.3c-0.1,0-0.3-0.1-0.4-0.1c-0.1,0-0.3,0-0.4,0.1L2.2,58.7V25l10-3.5c0,0,0,0,0,0.1c0.1,0.1,0.1,0.2,0.2,0.3 c0.1,0.2,0.2,0.4,0.3,0.6c0.1,0.1,0.1,0.2,0.2,0.3c0.1,0.2,0.2,0.4,0.3,0.6c0.1,0.1,0.1,0.2,0.2,0.3c0.1,0.2,0.2,0.4,0.3,0.5 c0.1,0.1,0.1,0.2,0.2,0.3c0.1,0.2,0.2,0.3,0.3,0.5c0.1,0.1,0.1,0.2,0.2,0.3c0.1,0.2,0.2,0.3,0.3,0.5c0.1,0.1,0.1,0.2,0.2,0.3 c0.1,0.2,0.2,0.3,0.3,0.5c0.1,0.1,0.1,0.2,0.2,0.3c0.1,0.2,0.2,0.3,0.3,0.5c0.1,0.1,0.1,0.2,0.2,0.2c0.1,0.2,0.2,0.3,0.3,0.4 c0,0.1,0.1,0.1,0.1,0.2c0.1,0.2,0.2,0.3,0.3,0.4c0,0,0.1,0.1,0.1,0.1c0.1,0.1,0.2,0.3,0.3,0.4c0,0,0.1,0.1,0.1,0.1 c0.1,0.1,0.2,0.3,0.3,0.4c0,0,0,0,0,0c0.1,0.1,0.2,0.2,0.3,0.3c0,0,0,0,0,0c0.2,0.3,0.4,0.5,0.4,0.6c0.2,0.3,0.5,0.4,0.9,0.4 c0.3,0,0.6-0.2,0.9-0.4c0,0,0.1-0.1,0.3-0.3c0,0,0.1-0.1,0.1-0.1c0.1-0.1,0.1-0.1,0.2-0.2c0,0,0.1-0.1,0.1-0.1 c0.1-0.1,0.1-0.2,0.2-0.3c0-0.1,0.1-0.1,0.1-0.2c0.1-0.1,0.2-0.2,0.2-0.3c0.1-0.1,0.1-0.2,0.2-0.3c0.1-0.1,0.2-0.2,0.3-0.4 c0.1-0.1,0.1-0.2,0.2-0.3c0.1-0.1,0.2-0.2,0.3-0.4c0.1-0.1,0.2-0.2,0.2-0.3c0.1-0.1,0.2-0.3,0.3-0.4c0.1-0.1,0.2-0.3,0.3-0.4 c0.1-0.1,0.2-0.3,0.3-0.4c0.1-0.1,0.2-0.3,0.3-0.4c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.1,0.2-0.3,0.3-0.4c0.1-0.2,0.2-0.3,0.3-0.5 c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.2,0.2-0.3,0.3-0.5 c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.2,0.2-0.3,0.3-0.5c0.1-0.2,0.2-0.4,0.3-0.5c0.1-0.2,0.2-0.3,0.2-0.5c0,0,0,0,0-0.1l14.8,5.4 c0.2,0.1,0.5,0.1,0.7,0l19.3-6.9V52.1z' />
<path d='M52.5,42.4c0.2,0.1,0.5,0.1,0.7,0.1c0.6,0,1.2-0.2,1.7-0.5c0.7-0.5,1.2-1.2,1.4-2c0.2-0.8,0-1.7-0.4-2.4 c-0.5-0.7-1.2-1.2-2-1.4c-1.7-0.4-3.5,0.7-3.9,2.4v0c-0.2,0.8,0,1.7,0.4,2.4C51,41.7,51.7,42.2,52.5,42.4z M52.2,39 c0.1-0.6,0.7-0.9,1.2-0.8c0.3,0.1,0.5,0.2,0.6,0.5c0.1,0.2,0.2,0.5,0.1,0.8c-0.1,0.3-0.2,0.5-0.5,0.6c-0.2,0.1-0.5,0.2-0.8,0.1 c-0.3-0.1-0.5-0.2-0.6-0.5C52.2,39.5,52.2,39.3,52.2,39z' />
<path d='M11,39.1l-0.7,0.4l-0.4-0.7c-0.3-0.5-1-0.7-1.5-0.3c-0.5,0.3-0.7,1-0.3,1.5l0.4,0.7l-0.7,0.4c-0.5,0.3-0.7,1-0.3,1.5 C7.6,43,8,43.1,8.3,43.1c0.2,0,0.4-0.1,0.6-0.2l0.7-0.4l0.4,0.7c0.2,0.3,0.6,0.5,0.9,0.5c0.2,0,0.4-0.1,0.6-0.2 c0.5-0.3,0.7-1,0.3-1.5l-0.4-0.7l0.7-0.4c0.5-0.3,0.7-1,0.3-1.5C12.2,38.9,11.5,38.8,11,39.1z' />
<path d='M21.3,42.1c-1.3,0-3-0.2-4.1-0.5c-0.6-0.1-1.2,0.3-1.3,0.9c-0.1,0.6,0.3,1.2,0.9,1.3c1.1,0.2,2.9,0.5,4.5,0.5c0,0,0,0,0,0 c0.6,0,1.1-0.5,1.1-1.1C22.4,42.6,21.9,42.1,21.3,42.1z' />
<path d='M29.5,38.3c-0.7,1-1.5,1.8-2.5,2.4c-0.3,0.2-0.7,0.4-1.1,0.6c-0.6,0.2-0.8,0.9-0.6,1.5c0.2,0.4,0.6,0.7,1,0.7 c0.1,0,0.3,0,0.4-0.1c0.5-0.2,0.9-0.4,1.3-0.7c1.2-0.8,2.2-1.7,3.1-2.9c0.4-0.5,0.3-1.2-0.2-1.5C30.6,37.7,29.9,37.8,29.5,38.3z' />
<path d='M37.5,31.1c-1.1,0-1.7,0.3-2.3,0.5c-1.4,0.6-2.6,1.9-2.9,2.3c-0.4,0.5-0.3,1.2,0.1,1.6c0.2,0.2,0.5,0.3,0.7,0.3 c0.3,0,0.6-0.1,0.8-0.4c0.5-0.6,1.3-1.3,2.1-1.7c0.6-0.2,0.8-0.3,1.5-0.4c0.6,0,1.1-0.5,1.1-1.1C38.6,31.6,38.1,31.1,37.5,31.1z' />
<path d='M41.6,32.8c-0.2,0.6,0,1.2,0.6,1.5c1.1,0.5,2.7,1.3,3.9,2.2c0.2,0.1,0.4,0.2,0.6,0.2c0.4,0,0.7-0.2,0.9-0.5 c0.3-0.5,0.2-1.2-0.3-1.5c-1.4-0.9-3-1.8-4.3-2.3C42.5,32,41.9,32.3,41.6,32.8z' />
<path d='M19.1,15.2c1.9,0,3.4-1.5,3.4-3.4S21,8.4,19.1,8.4c-1.9,0-3.4,1.5-3.4,3.4S17.3,15.2,19.1,15.2z M19.1,10.6 c0.6,0,1.2,0.5,1.2,1.2c0,0.6-0.5,1.2-1.2,1.2c-0.6,0-1.2-0.5-1.2-1.2C18,11.2,18.5,10.6,19.1,10.6z' />
</g>
</svg>
</SvgIcon>
);
};
export default GpxIcon;

View File

@ -1,61 +0,0 @@
import { Component, For } from 'solid-js';
import { peekCachedSignal } from '../../workers/cached-signals';
import { RteViewer } from '../rte';
import Tree from '../tree';
import { TrkViewer } from '../trk';
import { WptViewer } from '../wpt';
import GpxIcon from './GpxIcon';
interface Props {
gpxId: string;
restrictToHierarchy?: any;
}
const GpxViewer: Component<Props> = ({ gpxId, restrictToHierarchy }) => {
const gpx = peekCachedSignal({ id: gpxId, action: 'getGpx' });
console.log({ caller: 'GpxViewer', gpxId, restrictToHierarchy, gpx: gpx() });
const title = () => {
return gpx().metadata.name;
};
return (
<Tree
title={
<>
<span>
{' '}
<GpxIcon /> {title()}
</span>
</>
}
content={undefined}
subTree={
<For
each={Object.keys(restrictToHierarchy).filter(
(key: string) =>
key.startsWith('gpx/') &&
(gpx().trk?.includes(key) ||
gpx().wpt?.includes(key) ||
gpx().rte?.includes(key))
)}
>
{(key: string) => {
const child = restrictToHierarchy[key];
if (child.type === 'wpt') {
return <WptViewer wptId={key} />;
}
if (child.type === 'rte') {
return <RteViewer rteId={key} />;
}
if (child.type === 'trk') {
return <TrkViewer trkId={key} restrictToHierarchy={child} />;
}
return <></>;
}}
</For>
}
/>
);
};
export default GpxViewer;

View File

@ -1,5 +0,0 @@
export { default } from './Gpx';
export { default as GpxViewer } from './GpxViewer';
export { default as GpxIcon } from './GpxIcon';

View File

@ -1,146 +0,0 @@
import atm from '../../icons/osm/atm_euro.svg';
import bar from '../../icons/osm/bar.svg';
import cafe from '../../icons/osm/cafe.svg';
import fast_food from '../../icons/osm/fastfood.svg';
import pub from '../../icons/osm/pub.svg';
import restaurant from '../../icons/osm/restaurant.svg';
import bank from '../../icons/osm/bank_euro.svg';
import doctors from '../../icons/osm/doctors.svg';
import hospital from '../../icons/osm/hospital.svg';
import pharmacy from '../../icons/osm/pharmacie.svg';
import police from '../../icons/osm/police2.svg';
import fire_station from '../../icons/osm/firestation.svg';
import drinking_water from '../../icons/osm/drinking_water.svg';
import waste_basket from '../../icons/osm/waste_basket.svg';
import waste_disposal from '../../icons/osm/waste_disposal.svg';
import vending_machine from '../../icons/osm/vending_machine.svg';
import bakery from '../../icons/osm/bakery.svg';
import butcher from '../../icons/osm/butcher2.svg';
//import cheese from '../../icons/osm/cheese.svg';
//import chocolate from '../../icons/osm/chocolate.svg';
import dairy from '../../icons/osm/dairy.svg';
//import farm from '../../icons/osm/farm.svg';
import greengrocer from '../../icons/osm/greengrocer.svg';
//import health_food from '../../icons/osm/health_food.svg';
//import pasta from '../../icons/osm/pasta.svg';
//import pastry from '../../icons/osm/pastry.svg';
import seafood from '../../icons/osm/seafood.svg';
//import water from '../../icons/osm/water.svg';
import department_store from '../../icons/osm/department_store.svg';
//import general from '../../icons/osm/general.svg';
//import mall from '../../icons/osm/mall.svg';
import supermarket from '../../icons/osm/supermarket.svg';
//import wholesale from '../../icons/osm/wholesale.svg';
import outdoor from '../../icons/osm/outdoor.svg';
import laundry from '../../icons/osm/laundry.svg';
import convenience from '../../icons/osm/convenience.svg';
import hotel from '../../icons/osm/hotel2.svg';
import alpine_hut from '../../icons/osm/alpinehut.svg';
import apartment from '../../icons/osm/apartment.svg';
import camp_site from '../../icons/osm/camping.svg';
import chalet from '../../icons/osm/chalet.svg';
import guest_house from '../../icons/osm/guest_house.svg';
import hostel from '../../icons/osm/hostel.svg';
import motel from '../../icons/osm/motel.svg';
import wilderness_hut from '../../icons/osm/wilderness_hut.svg';
import viewpoint from '../../icons/osm/view_point.svg';
import waterfall from '../../icons/osm/waterfall.svg';
import cave_entrance from '../../icons/osm/cave.svg';
import volcano from '../../icons/osm/volcano.png';
import glacier from '../../icons/osm/glacier.png';
import peak from '../../icons/osm/peak.svg';
import arete from '../../icons/osm/arete2.svg';
import rock from '../../icons/osm/rock.svg';
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,
pub,
restaurant,
cafe,
atm,
bank,
doctors,
hospital,
pharmacy,
police,
fire_station,
drinking_water,
water_point: drinking_water,
waste_basket,
waste_disposal,
vending_machine: convenience,
bakery,
butcher,
cheese: dairy,
chocolate: bakery,
convenience,
dairy,
farm: convenience,
greengrocer,
health_food: convenience,
pasta: dairy,
pastry: bakery,
seafood,
water: drinking_water,
department_store,
general: department_store,
mall: department_store,
supermarket,
wholesale: supermarket,
outdoor,
laundry,
hotel,
alpine_hut,
apartment,
camp_site,
chalet,
guest_house,
hostel,
motel,
wilderness_hut,
viewpoint,
waterfall,
peak,
cave_entrance,
volcano,
arete,
rock,
saddle,
stone,
glacier,
spring,
fumarole,
hot_spring: fumarole,
geyser: fumarole,
arch: cave_entrance,
sinkhole: cave_entrance,
};
export const highlight = {
hotel,
alpine_hut,
apartment,
camp_site,
chalet,
guest_house,
hostel,
motel,
wilderness_hut,
};
export default osmIcons;

View File

@ -1,703 +0,0 @@
import { Fill, Text, Icon, Stroke, Style, Circle } from 'ol/style';
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';
import campingIcon from '../../icons/camping-14-svgrepo-com.svg';
import farmPigIcon from '../../icons/farm-pig-svgrepo-com.svg';
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 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 noteIcon from '../../icons/note-svgrepo-com.svg';
import { Feature } from 'ol';
import memoize from 'memoizee';
import { getMap } from '../map';
import { Point } from 'ol/geom';
import { Coordinate } from 'ol/coordinate';
import { createDefaultStyle } from 'ol/style/Style';
import osmIcons from './osm-icons';
import { getZoomInteger } from '../map/Map';
import { isHighlightedTagType } from '../map-tile-provider/MapTileProvider';
import { getCenter } from 'ol/extent';
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;
}
const icons = {
note: {
src: noteIcon,
scale: 1 / 20,
opacity: 0.9,
anchor: [0.5, 1],
},
house: {
src: houseIcon,
scale: 1 / 15,
opacity: 0.9,
anchor: [0.5, 1],
},
houseFlat: {
src: houseFlatIcon,
scale: 1 / 15,
opacity: 0.9,
anchor: [0.5, 1],
},
camping: {
src: campingIcon,
scale: 2,
opacity: 0.9,
anchor: [0.5, 1],
},
farmPig: {
src: farmPigIcon,
scale: 1 / 12,
opacity: 0.9,
anchor: [0.5, 1],
},
cheese: {
src: cheeseIcon,
scale: 3 / 4,
opacity: 0.9,
anchor: [0.5, 1],
},
train: {
src: trainIcon,
scale: 1 / 10,
opacity: 0.9,
anchor: [0.5, 1],
},
picnic: {
src: picnicIcon,
scale: 1 / 15,
opacity: 0.9,
anchor: [0.5, 1],
},
cave: {
src: caveIcon,
scale: 1 / 7,
opacity: 0.9,
anchor: [0.5, 1],
},
};
const wptIconObj = {
src: wptIcon,
scale: 0.1,
opacity: 0.9,
anchor: [0.5, 1],
};
const textStroke = new Stroke({
color: '#fff',
width: 3,
});
const textStrokeSel = new Stroke({
color: 'blue',
width: 2,
});
const textFill = new Fill({
color: '#000',
});
const textFillSel = new Fill({
color: 'red',
});
const rteStroke = new Stroke({
color: [18, 71, 11, 0.8],
width: 3,
});
const rteStrokeSel = new Stroke({
color: 'red',
width: 3,
});
const circleFill = new Fill({
color: 'rgba(255,255,255,0.4)',
});
const circleStroke = new Stroke({
color: '#3399CC',
width: 1.25,
});
const poiTextFill = new Fill({
color: 'white',
});
const circle = new Circle({
fill: circleFill,
stroke: circleStroke,
radius: 5,
});
const replacer = (key: string, value: any) => {
if (key === 'feature' && typeof value === 'object') {
return { id: value.get('id'), rev: value.getRevision() };
}
return value;
};
const normalizer = (params: any) => {
const key = JSON.stringify(params, replacer);
// console.log({ caller: 'getStyle / normalizer', key });
return key;
};
const memoizeOptions = {
length: 1,
normalizer,
max: 1024000,
};
const styles = {
wpt: {
getParameters: (feature: Feature) => {
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] ||
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, thumbnailUrl } = params;
if (hidden) {
return null;
}
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({
font: '16px Calibri,sans-serif',
text: text,
fill: isSelected ? textFillSel : textFill,
stroke: isSelected ? textStrokeSel : textStroke,
offsetY: -40,
}),
});
}, memoizeOptions),
},
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;
let currentStyles: any = isSelected
? styles.trkseg.ownStyles.selected
: styles.trkseg.ownStyles.normal;
if (feature) {
const map = getMap();
const geometry = feature.getGeometry();
const coordinates = geometry.getCoordinates();
let start = coordinates[0];
let startPixels = map?.getPixelFromCoordinate(start);
coordinates.slice(1).forEach((end: Coordinate) => {
const endPixels = map?.getPixelFromCoordinate(end);
if (
startPixels !== undefined &&
endPixels !== undefined &&
Math.sqrt(
(startPixels[0] - endPixels[0]) ** 2 +
(startPixels[1] - endPixels[1]) ** 2
) > 80
) {
const dx = end[0] - start[0];
const dy = end[1] - start[1];
const rotation = Math.atan2(dy, dx) - Math.PI / 2;
currentStyles.push(
new Style({
geometry: new Point(end),
image: new Icon({
src: blackArrowheadPointingUp,
scale: 1 / 20,
anchor: [0.5, 0.5],
rotateWithView: true,
rotation: -rotation,
}),
})
);
startPixels = endPixels;
start = end;
}
});
}
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,
};
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'getStyle', params });
const { isSelected } = params;
return new Style({ stroke: isSelected ? rteStrokeSel : rteStroke });
}, memoizeOptions),
},
way: {
strokes: {
veryLowZoom: {
iwn: [
new Style({
stroke: new Stroke({
color: [255, 0, 0, 1],
width: 1,
}),
}),
],
nwn: [
new Style({
stroke: new Stroke({
color: [255, 0, 0, 1],
width: 1,
}),
}),
],
rwn: [
new Style({
stroke: new Stroke({
color: [255, 128, 0, 1],
width: 1,
}),
}),
],
lwn: [
new Style({
stroke: new Stroke({
color: [255, 255, 0, 1],
width: 1,
}),
}),
],
default: [
new Style({
stroke: new Stroke({
color: [255, 255, 0, 1],
width: 1,
lineDash: [10, 10],
}),
}),
],
},
lowZoom: {
iwn: [
new Style({
stroke: new Stroke({
color: [255, 0, 0, 0.6],
width: 3,
}),
}),
],
nwn: [
new Style({
stroke: new Stroke({
color: [255, 0, 0, 0.6],
width: 3,
}),
}),
],
rwn: [
new Style({
stroke: new Stroke({
color: [255, 128, 0, 0.6],
width: 3,
}),
}),
],
lwn: [
new Style({
stroke: new Stroke({
color: [255, 255, 0, 0.6],
width: 3,
lineDash: [10, 10],
}),
}),
],
default: [
new Style({
stroke: new Stroke({
color: [255, 255, 0, 0.6],
width: 1,
lineDash: [10, 10],
}),
}),
],
},
highZoom: {
iwn: [
new Style({
stroke: new Stroke({
color: [255, 0, 0, 0.6],
width: 7,
// lineDash: [10, 10],
// lineDashOffset: 10,
}),
}),
new Style({
stroke: new Stroke({
color: [255, 255, 255, 0.6],
width: 3,
// lineDash: [10, 10],
// lineDashOffset: 0,
}),
}),
],
nwn: [
new Style({
stroke: new Stroke({
color: [255, 0, 0, 0.6],
width: 7,
// lineDash: [10, 10],
// lineDashOffset: 10,
}),
}),
new Style({
stroke: new Stroke({
color: [255, 255, 255, 0.6],
width: 3,
// lineDash: [10, 10],
// lineDashOffset: 0,
}),
}),
],
rwn: [
new Style({
stroke: new Stroke({
color: [255, 255, 0, 0.6],
width: 7,
// lineDash: [10, 10],
// lineDashOffset: 10,
}),
}),
new Style({
stroke: new Stroke({
color: [255, 0, 0, 0.6],
width: 3,
// lineDash: [10, 10],
// lineDashOffset: 0,
}),
}),
],
lwn: [
new Style({
stroke: new Stroke({
color: [0, 0, 255, 0.6],
width: 3,
}),
}),
new Style({
stroke: new Stroke({
color: [255, 255, 0, 0.6],
width: 1,
}),
}),
],
default: [
new Style({
stroke: new Stroke({
color: [0, 0, 255, 0.6],
lineDash: [10, 10],
width: 3,
}),
}),
new Style({
stroke: new Stroke({
color: [255, 255, 0, 0.6],
lineDash: [10, 10],
width: 1,
}),
}),
],
},
},
getParameters: (feature: Feature) => {
// let tags = feature.get('tags');
// try {
// tags = JSON.parse(feature.get('tags'));
// } catch (error) {
// tags = { error };
// console.error({
// caller: 'style / JSON.parse',
// tags: feature.get('tags'),
// error,
// feature,
// });
// }
const network = feature.get('network');
if (getZoomInteger() < 7 && !['iwn'].includes(network)) {
return null;
}
if (getZoomInteger() < 11 && !['iwn', 'nwn'].includes(network)) {
return null;
}
if (getZoomInteger() < 13 && !['iwn', 'nwn', 'lwn'].includes(network)) {
return null;
}
const name =
getZoomInteger() < 15
? feature.get('ref')
: feature.get('name') || feature.get('ref');
return {
// isSelected: feature.get('isSelected') ?? false,
name: !!name ? name : undefined,
network,
zoom:
getZoomInteger() >= 12
? 'highZoom'
: getZoomInteger() >= 8
? 'lowZoom'
: 'veryLowZoom',
};
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'getStyle', params });
const { name, network, zoom } = params;
return [
...(styles.way.strokes[zoom][network] ??
styles.way.strokes[zoom].default),
new Style({
text: new Text({
text: name,
font: 'bold 14px "Open Sans", "Arial Unicode MS", "sans-serif"',
placement: 'line',
overflow: false,
maxAngle: Math.PI / 16,
textBaseline: ['iwn', 'nwn'].includes(network) ? 'top' : 'bottom',
padding: [2, 2, 2, 2],
fill: new Fill({
color: 'black',
}),
}),
}),
];
}, memoizeOptions),
},
poi: {
getParameters: (feature: Feature) => {
if (feature.getGeometryName() !== 'Point') {
feature.setGeometry(
new Point(getCenter(feature.getGeometry().getExtent()))
);
}
if (getZoomInteger() < 16) {
return null;
}
const tagType = getTagType(feature);
const isHighlightedFeature = isHighlightedTagType(tagType);
if (
(isHighlightedFeature && getZoomInteger() < 16) ||
(!isHighlightedFeature && getZoomInteger() < 18)
) {
return null;
}
return {
name: feature.get('name'),
poiType: tagType,
isHighlighted: isHighlightedFeature,
isTextHidden: getZoomInteger() < 19,
};
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'getStyle', params });
const { name, poiType, isTextHidden, isHighlighted } = params;
const icon = osmIcons[poiType];
if (icon === undefined) {
return undefined;
}
return [
new Style({
image: new Circle({
radius: 28,
fill: new Fill({
color: isHighlighted ? [174, 33, 219, 0.7] : [255, 255, 255, 0.3],
}),
displacement: isHighlighted ? [0, +0] : [0, +3],
}),
}),
new Style({
image: new Icon({
src: icon,
scale: isHighlighted ? 2 : 1,
opacity: 1,
color: isHighlighted ? 'red' : 'black',
// anchor: [0, 0],
}),
text:
name && !isTextHidden
? new Text({
text: name,
font: 'bold 14px "Open Sans", "Arial Unicode MS", "sans-serif"',
offsetY: +40,
padding: [0, 0, 0, 0],
fill: new Fill({
color: 'black',
}),
backgroundFill: poiTextFill,
})
: undefined,
}),
];
}, memoizeOptions),
},
cluster: {
getParameters: (feature: Feature) => {
const nbFeatures = feature.get('features').length;
// console.log({ caller: 'cluster / getParameters', feature, nbFeatures });
return {
nbFeatures,
};
},
getStyle: memoize((params: any) => {
// console.log({ caller: 'cluster / getStyle', params });
const { nbFeatures } = params;
return new Style({
image: new Circle({
radius: 12,
fill: new Fill({ color: [174, 33, 219, 0.7] }),
}),
text: new Text({
text: `${nbFeatures}`,
font: 'bold 18px "Open Sans", "Arial Unicode MS", "sans-serif"',
offsetY: +2,
padding: [0, 0, 0, 0],
fill: new Fill({
color: 'black',
}),
}),
});
}, memoizeOptions),
},
};
export const style = (feature: Feature, resolution: number) => {
// console.log({ caller: 'style', feature, values: feature.values_ });
const type = (
feature.get('type') !== undefined
? feature.get('type')
: getVectorTileFeatureType(feature)
) as keyof typeof styles;
const styleForType = styles[type];
if (!styleForType) {
console.log({ caller: 'style / default', type, feature, resolution });
// return createDefaultStyle(feature, resolution)[0];
return null;
}
const params = styles[type].getParameters(feature);
// console.log({
// caller: 'style',
// type,
// styleForType,
// params,
// feature,
// resolution,
// });
if (params === null || params?.isHidden) {
return null;
}
// if (params.subFeature) {
// return style(params.subFeature, resolution);
// }
const getStyle = styles[type].getStyle;
const result = getStyle(params);
// console.log({ caller: 'style', feature, type, params, style });
if (result === undefined) {
// console.log({ caller: 'style / unknown', feature });
return createDefaultStyle(feature, resolution)[0];
}
return result;
};
export default style;

View File

@ -1,18 +0,0 @@
.container {
position: fixed !important;
top: 6px;
margin-left: calc(100% - 100px) !important;
z-index: 1;
}
.label {
opacity: 0.8;
}
.inputFile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
/* position: absolute; */
z-index: -1;
}

View File

@ -1,81 +0,0 @@
import { Component, createSignal, For } from 'solid-js';
import CloudUploadIcon from '@suid/icons-material/CloudUpload';
// @ts-ignore
import css from './Import.module.css';
import Dialog from '../dialog';
import { useI18n } from '@solid-primitives/i18n';
import { Box } from '@suid/material';
import ImportSingleFile from './ImportSingleFile';
const [filesToImport, setFilesToImport] = createSignal<FileList | string[]>();
export const importUrls = (urls: string[]) => {
setFilesToImport(urls);
};
const GpxImport: Component = () => {
const [t] = useI18n();
const onChangeHandler = (event: any) => {
console.log({
caller: 'GpxImport / On change handler',
files: event.target.files,
});
setFilesToImport(event.target.files);
};
const handleClose = (event: any, reason?: string) => {
console.log({
caller: 'GpxImport / handleClose',
event,
reason,
});
if (reason === undefined) {
setFilesToImport(undefined);
}
};
const accept =
window.Capacitor.platform === 'android'
? ''
: '.gpx,.jpg,image/jpeg,application/gpx+xml';
return (
<>
<div class={css.container}>
<label for='gpx-import' class={css.label}>
<CloudUploadIcon />
</label>
<input
type='file'
id='gpx-import'
class={css.inputFile}
accept={accept}
multiple={true}
onChange={onChangeHandler}
/>
</div>
<Dialog
open={filesToImport() !== undefined}
title={t('gpxImport')}
closeHandler={handleClose}
fullScreen
>
<Box
sx={{
width: '100%',
}}
>
<For each={filesToImport()}>
{(file) => <ImportSingleFile file={file} />}
</For>
</Box>
</Dialog>
</>
);
};
export default GpxImport;

View File

@ -1,355 +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';
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

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

View File

@ -1,301 +0,0 @@
import { Button, IconButton } from '@suid/material';
import { Feature } from 'ol';
import { Geometry } from 'ol/geom';
import { Component, createSignal, For, Match, Show, Switch } from 'solid-js';
import { useI18n } from '@solid-primitives/i18n';
import TravelExploreIcon from '@suid/icons-material/TravelExplore';
import AddLocationAltIcon from '@suid/icons-material/AddLocationAlt';
import OpenInNewIcon from '@suid/icons-material/OpenInNew';
import CallIcon from '@suid/icons-material/Call';
import { Paper, Stack } from '@suid/material';
import styled from '@suid/material/styles/styled';
import Dialog from '../dialog';
import Tree from '../tree';
import { GpxViewer } from '../gpx';
import { Browser } from '@capacitor/browser';
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,
padding: theme.spacing(1),
textAlign: 'center',
color: theme.palette.text.secondary,
}));
const [open, setOpen] = createSignal(false);
const [location, setLocation] = createSignal();
let selectedFeatures: Feature[] = [];
let vectorLayerFeatures: Feature[] = [];
let hierarchy: any = {};
const level2Key = (feature: Feature) =>
feature.get('context').wptId ||
feature.get('context').rteId ||
feature.get('context').trkId;
export const clickHandler = (event: any) => {
hierarchy = {};
const map = event.map;
const pixel = [event.originalEvent.x, event.originalEvent.y];
const features = map.getFeaturesAtPixel(pixel, { hitTolerance: 30 });
setLocation(toLonLat(map.getCoordinateFromPixel(pixel)));
console.log({ caller: 'Infos.tsx / clickHandler', features, event });
selectedFeatures.map((feature) => {
if (feature.set) {
feature.set('isSelected', false);
}
});
selectedFeatures = features.filter((feature: any) => feature.get('context'));
let osmIds = new Set<string>();
vectorLayerFeatures = features.filter((feature: any) => {
if (feature.get('context')) {
return false;
}
const osmId = feature.get('osm_id');
if (osmIds.has(osmId)) {
return false;
}
osmIds.add(osmId);
return true;
});
selectedFeatures.sort((f1: Feature, f2: Feature) => {
const ctx1 = f1.get('context');
const ctx2 = f2.get('context');
if (ctx1.gpxId < ctx2.gpxId) {
return 1;
} else if (ctx1.gpxId > ctx2.gpxId) {
return -1;
}
const level2Key1 = level2Key(f1);
const level2Key2 = level2Key(f2);
if (level2Key1 < level2Key2) {
return -1;
}
if (level2Key1 > level2Key2) {
return 1;
}
if (ctx1.trksegId < ctx2.trksegId) {
return -1;
}
if (ctx1.trksegId > ctx2.trksegId) {
return 1;
}
return 0;
});
selectedFeatures.map((feature: Feature<Geometry>) => {
const gpxId = feature.get('context').gpxId;
if (!hierarchy.hasOwnProperty(gpxId)) {
hierarchy[gpxId] = { type: 'gpx' };
}
const l2key = level2Key(feature);
if (!hierarchy[gpxId].hasOwnProperty(l2key)) {
hierarchy[gpxId][l2key] = {};
if (feature.get('type') === 'trkseg') {
hierarchy[gpxId][l2key].type = 'trk';
} else {
hierarchy[gpxId][l2key].type = feature.get('type');
hierarchy[gpxId][l2key].feature = feature;
}
}
if (feature.get('type') === 'trkseg') {
const trksegId = feature.get('context').trksegId;
if (!hierarchy[gpxId][l2key].hasOwnProperty(trksegId)) {
hierarchy[gpxId][l2key][trksegId] = {
type: 'trkseg',
feature,
};
}
}
});
console.log({
caller: '<Infos/> / clickHandler',
event,
features,
hierarchy,
vectorLayerFeatures,
location: location(),
});
selectedFeatures.map((feature: Feature<Geometry>) => {
const id = feature.get('id');
feature.set('isSelected', true);
// const geometry = feature.getGeometry();
// const length = getLength(geometry, { projection: "EPSG:4326" });
console.log({
caller: '<Infos/> / clickHandler / feature',
event,
feature,
id,
// geometry,
// length,
});
});
setOpen(true);
};
const FeaturesTree: Component<{ featuresHierarchy: any }> = ({
featuresHierarchy,
}) => {
return (
<Tree
title={featuresHierarchy.type || 'voyages'}
content={undefined}
subTree={Object.keys(featuresHierarchy)
.filter((key: string) => key.startsWith('gpx/'))
.map((key: string) => (
<GpxViewer gpxId={key} restrictToHierarchy={featuresHierarchy[key]} />
))}
/>
);
};
const Infos: Component<{}> = (props) => {
const [t, { add, locale, dict }] = useI18n();
const handleClick = () => {
setOpen(false);
};
return (
<Dialog closeHandler={handleClick} open={open()} title={t('nearby')}>
<Stack
spacing={1}
direction='column'
alignItems='center'
sx={{ width: 'calc(100% - 5px)' }}
>
<Tree
title='everything'
content={undefined}
subTree={
<>
<Tree
title={
<>
<div>osm</div>
<OsmFindAll location={location()} />
</>
}
content={undefined}
subTree={
<>
<For each={vectorLayerFeatures}>
{(feature) => (
<Tree
title={
<>
<div>{feature.get('name') || ''}</div>
<div>
<IconButton>
<AddLocationAltIcon />
</IconButton>
<IconButton
onClick={async () => {
await Browser.open({
url: `https://www.qwant.com/?q=${encodeURIComponent(
feature.get('name') || ''
)}&t=web`,
});
}}
>
<TravelExploreIcon />
</IconButton>
</div>
</>
}
content={
<>
<>
{console.log({
caller: 'Infos / vector layer feature',
isHighlighted: isHighlightedTagType(
getTagType(feature)
),
tagValue: getTagType(feature),
properties: feature.getProperties(),
style: style(feature),
})}
</>
<For each={Object.keys(feature.getProperties())}>
{(key: string) => (
<div>
<Switch
fallback={`${key}: ${
feature.getProperties()[key]
}`}
>
<Match when={key === 'website'}>
<Button
size='small'
startIcon={<OpenInNewIcon />}
onClick={async () => {
await Browser.open({
url: feature.getProperties()[key],
});
}}
>
{feature.getProperties()[key]}
</Button>
</Match>
<Match when={key === 'phone'}>
<Button
size='small'
startIcon={<CallIcon />}
href={
'tel:' +
feature.getProperties()[key]
}
>
{feature.getProperties()[key]}
</Button>
</Match>
<Match when={key === 'tags'}>
tags:
<ul>
<For
each={Object.keys(
feature.getProperties()[key]
)}
>
{(tagKey) => (
<li>
{tagKey}:
{
feature.getProperties()[key][
tagKey
]
}
</li>
)}
</For>
</ul>
</Match>
</Switch>
</div>
)}
</For>
</>
}
subTree={undefined}
/>
)}
</For>
</>
}
/>
<FeaturesTree featuresHierarchy={hierarchy} />
</>
}
/>
</Stack>
</Dialog>
);
};
export default Infos;

View File

@ -1,99 +0,0 @@
import { IconButton } from '@suid/material';
import { Coordinate } from 'ol/coordinate';
import { Point } from 'ol/geom';
import { Component, createSignal, For, Show } from 'solid-js';
import OsmIcon from '../../icons/OpenStreetMap-logo.svg?component-solid';
import Dialog from '../dialog';
import Tree from '../tree';
interface Props {
location: Coordinate;
}
const OsmFindAll: Component<Props> = (props) => {
const { location } = props;
const [osmResult, setOsmResult] = createSignal(false);
const handleClick = async () => {
const query = `[out:json][timeout:25];
(
nwr(if:count_tags()>0)(around:50,${location[1]},${location[0]});
);
out body;
`;
const response = await fetch(
'https://overpass-api.de/api/interpreter?contact=vdv@dyomedea.com',
{
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'text/plain',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: query, // body data type must match "Content-Type" header
}
);
const osmJson = await response.json(); // parses JSON response into native JavaScript objects
console.log({
caller: 'OsmFindAll / handleClick',
query,
osmJson,
});
setOsmResult(osmJson);
};
const closeHandler = () => {
setOsmResult(false);
};
return (
<>
<IconButton onClick={handleClick}>
<OsmIcon width={24} height={24} viewBox='0 0 240 240' />
</IconButton>
<Dialog
open={!!osmResult()}
title='OsmObjects'
closeHandler={closeHandler}
>
<Tree
title='OSMData'
content={undefined}
subTree={
<For each={osmResult().elements}>
{(element) => (
<Tree
title={element.id}
content={
<>
<div>type: {element.type}</div>
<Show when={element.type === 'node'}>
<div>
Coordinates: {element.lat}, {element.lon}
</div>
</Show>
<For each={Object.keys(element.tags)}>
{(tag) => (
<div>
{tag}: {element.tags[tag]}
</div>
)}
</For>
</>
}
subTree={undefined}
></Tree>
)}
</For>
}
></Tree>
</Dialog>
</>
);
};
export default OsmFindAll;

View File

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

View File

@ -1,247 +0,0 @@
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

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

View File

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

View File

@ -1,307 +0,0 @@
import OSM from 'ol/source/OSM';
import XYZ from 'ol/source/XYZ';
import { Component, createEffect, createSignal, For, Show } from 'solid-js';
import { useI18n } from '@solid-primitives/i18n';
import style from './MapTileProvider.module.css';
import LayersIcon from '@suid/icons-material/Layers';
import {
FormControlLabel,
IconButton,
Radio,
RadioGroup,
} from '@suid/material';
import { useNavigate, useParams } from '@solidjs/router';
import Dialog from '../dialog';
import Tree from '../tree';
import { createCachedSignal } from '../../workers/cached-signals';
import dispatch from '../../workers/dispatcher-main';
import getUri from '../../lib/ids';
import { Feature } from 'ol';
import {
overlayDefinitions,
osmTags,
OsmTag,
getTagType,
} from '../overlays/overlay-definitions';
import { cloneDeep } from 'lodash';
import DrawingSelector from '../drawing-selector/DrawingSelector';
const id = getUri('overlays', undefined);
interface TileProvider {
name: string;
language: string;
source: XYZ;
}
type TileProviders = {
[key: string]: TileProvider;
};
export const mapTileProviders: TileProviders = {
osm: {
name: 'Open Street Map',
language: 'int',
source: new OSM(),
},
osmfr: {
name: 'Open Street Map France',
language: 'fr',
source: new XYZ({
minZoom: 0,
maxZoom: 20,
url: 'https://{a-c}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png',
}),
},
otm: {
name: 'Open Topo Map',
language: 'int',
source: new XYZ({
minZoom: 0,
maxZoom: 16,
url: 'https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png',
}),
},
cyclosm: {
name: 'CyclOSM',
language: 'int',
source: new XYZ({
minZoom: 0,
maxZoom: 19,
url: 'https://{a-c}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
}),
},
//https://b.tile.openstreetmap.fr/openriverboatmap/20/535762/382966.png
openriverboatmap: {
name: 'Open River Boat Map',
language: 'int',
source: new XYZ({
minZoom: 0,
maxZoom: 19,
url: 'https://{a-c}.tile.openstreetmap.fr/openriverboatmap/{z}/{x}/{y}.png',
}),
},
rasterIgnEs: {
name: 'Cartografía Ráster de España del IGN',
language: 'es',
source: new XYZ({
minZoom: 0,
maxZoom: 19,
url: 'http://www.ign.es/wmts/mapa-raster?request=getTile&layer=MTN&TileMatrixSet=GoogleMapsCompatible&TileMatrix={z}&TileCol={x}&TileRow={y}&format=image/jpeg',
}),
},
pnoaMaEs: {
name: 'Ortoimágenes de España',
language: 'es',
source: new XYZ({
minZoom: 0,
maxZoom: 19,
url: 'http://www.ign.es/wmts/pnoa-ma?request=getTile&layer=MTN&TileMatrixSet=GoogleMapsCompatible&TileMatrix={z}&TileCol={x}&TileRow={y}&format=image/jpeg',
}),
},
};
type FeatureSubTypes = Array<string> | '*';
type FeatureTypes = Record<string, FeatureSubTypes>;
type Overlay = {
selected: boolean;
highlighted: FeatureTypes;
hidden: FeatureTypes;
};
type Overlays = Record<string, Overlay>;
const defaultOverlayContent = {
selected: false,
highlighted: {
none: [],
},
hidden: { none: [] },
};
const defaultOverlays: Overlays = {
none: { selected: true, highlighted: { none: [] }, hidden: {} },
};
const getOverlays = createCachedSignal({
id,
method: 'getOverlays',
defaultOverlays,
}) as () => Overlays;
const currentOverlayKey = () =>
getOverlays()
? Object.keys(getOverlays()).filter((key) => getOverlays()[key].selected)[0]
: 'none';
const currentOverlay = () =>
getOverlays() ? getOverlays()[currentOverlayKey()] : {};
const overlayDefinitionsPlusNone = { none: {}, ...overlayDefinitions };
export const currentCategory = () =>
Object.keys(
currentOverlayKey() === 'none'
? {}
: { none: [], ...overlayDefinitionsPlusNone[currentOverlayKey()] }
);
const currentOverlayHighlightedKey = () =>
currentOverlay() && currentOverlay().highlighted
? currentOverlay().highlighted
: 'none';
export const isHighlightedTagType = (tagType: string) => {
const currentOverlayHighlightedDefinition: string[] =
overlayDefinitions[currentOverlayKey()][currentOverlayHighlightedKey()];
return currentOverlayHighlightedDefinition.includes(tagType);
};
const MapTilesProvider: Component<{}> = (props) => {
const [open, setOpen] = createSignal(false);
const navigate = useNavigate();
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const params = useParams();
const [t] = useI18n();
const handleChange = (ev: any) => {
navigate(
`/map/${ev.target.value}/${params.lon}/${params.lat}/${params.zoom}/${params.rotation}`
);
setOpen(false);
};
createEffect(() => {
console.log({
caller: 'MapTilesProvider',
overlays: getOverlays(),
currentOverlayKey: currentOverlayKey(),
currentOverlay: currentOverlay(),
currentOverlayDefinition: currentCategory(),
currentOverlayHighlightedKey: currentOverlayHighlightedKey(),
});
});
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({
caller: 'MapTilesProvider / handleOverlayChange',
ev,
value,
});
const newOverlays = getOverlaysAddingSelectedIfMissing(value);
Object.keys(newOverlays).forEach((key) => {
newOverlays[key].selected = key === value;
});
dispatch({
action: 'putOverlays',
params: { id, overlays: newOverlays },
});
};
const handleOverlayHighlightChange = (ev: any) => {
const value = ev.target.value;
console.log({
caller: 'MapTilesProvider / handleOverlayHighlightChange',
ev,
value,
});
const newOverlays = getOverlays();
newOverlays[currentOverlayKey()].highlighted = value;
dispatch({
action: 'putOverlays',
params: { id, overlays: newOverlays },
});
};
return (
<>
<div class={style.control}>
<IconButton onClick={handleClickOpen}>
<LayersIcon />
</IconButton>
</div>
<Dialog
closeHandler={handleClose}
open={open()}
title={t('chooseYourMap')}
>
<DrawingSelector/>
<Tree
title={t('overlay')}
content={
<>
<RadioGroup
defaultValue={currentOverlayKey()}
onChange={handleOverlayChange}
>
<For each={Object.keys(overlayDefinitionsPlusNone)}>
{(p: string) => (
<FormControlLabel value={p} control={<Radio />} label={p} />
)}
</For>
</RadioGroup>
<Show when={currentCategory().length > 0}>
<div>---</div>
<div>Highlight</div>
<RadioGroup
defaultValue={currentOverlayHighlightedKey()}
onChange={handleOverlayHighlightChange}
>
<For each={currentCategory()}>
{(p: string) => (
<FormControlLabel
value={p}
control={<Radio />}
label={p}
/>
)}
</For>
</RadioGroup>
</Show>
</>
}
subTree={undefined}
></Tree>
<Tree
title={t('baseLayer')}
content={
<RadioGroup defaultValue={params.provider} onChange={handleChange}>
<For each={Object.keys(mapTileProviders)}>
{(p: string) => (
<FormControlLabel
value={p}
control={<Radio />}
label={mapTileProviders[p].name}
/>
)}
</For>
</RadioGroup>
}
subTree={undefined}
></Tree>
</Dialog>
</>
);
};
export default MapTilesProvider;

View File

@ -1,6 +0,0 @@
export {
default,
mapTileProviders,
currentCategory as currentOverlayDefinition,
isHighlightedTagType,
} from './MapTileProvider';

View File

@ -0,0 +1,47 @@
import { atom, useAtom } from 'jotai';
import react from 'react';
import Marker from './Marker';
import { geoPoint, Rectangle, TileKeyObject } from './types';
export interface CurrentLocationProperties {
keyObject?: TileKeyObject;
zoom?: number;
viewPort?: Rectangle;
}
const initialLocation: geoPoint | null = null;
export const locationAtom = atom<geoPoint | null>(initialLocation);
export const CurrentLocation: react.FC<CurrentLocationProperties> = (
props: CurrentLocationProperties
) => {
const [location] = useAtom(locationAtom);
console.log(
`Rendering CurrentLocation, location:${JSON.stringify(location)}`
);
return location !== null ? (
<Marker
key='currentLocation'
id='currentLocation'
coordinates={location}
icon={
<circle
cx={0}
cy={0}
r={8}
fill='blue'
opacity='90%'
stroke='white'
strokeWidth={3}
strokeOpacity='100%'
/>
}
keyObject={props.keyObject}
zoom={props.zoom}
viewPort={props.viewPort}
/>
) : null;
};
export default CurrentLocation;

View File

@ -0,0 +1,47 @@
import react, { startTransition, useEffect, useState } from 'react';
import dispatch from '../../workers/dispatcher-main';
import Trk from './Trk';
import { TileKeyObject, Rectangle } from './types';
import getUri from '../../lib/ids';
export interface GpxProperties {
id: string;
keyObject: TileKeyObject;
zoom: number;
viewPort: Rectangle;
}
export const Gpx: react.FC<GpxProperties> = (props: GpxProperties) => {
const [gpx, setGpx] = useState<any>([]);
useEffect(() => {
const getGpx = async () => {
const gpx = await dispatch({
action: 'getGpx',
params: {
id: props.id,
},
});
console.log(`<Gpx>, gpx: ${JSON.stringify(gpx)}`);
startTransition(() => setGpx(gpx));
};
getGpx();
}, [props.id]);
return (
<g>
{gpx
.filter((row: any) => row.doc.type === 'trk')
.map((row: any) => (
<Trk
key={row.id}
id={row.id}
keyObject={props.keyObject}
zoom={props.zoom}
viewPort={props.viewPort}
/>
))}
</g>
);
};
export default Gpx;

View File

@ -0,0 +1,51 @@
import react, { startTransition, useEffect, useState } from 'react';
import dispatch from '../../workers/dispatcher-main';
import Gpx from './Gpx';
import { TileKeyObject, Rectangle } from './types';
export interface GpxesProperties {
keyObject?: TileKeyObject;
zoom?: number;
viewPort?: Rectangle;
}
export const Gpxes: react.FC<GpxesProperties> = (props: GpxesProperties) => {
const [visibleGpxes, setVisibleGpxes] = useState<any>([]);
useEffect(() => {
const getVisibleGpxes = async () => {
const gpxes = await dispatch({
action: 'getGpxesForViewport',
params: {
viewport: props.viewPort,
zoomLevel: props.keyObject?.zoomLevel,
},
});
console.log(`Gpxes, visibles: ${JSON.stringify(gpxes)}`);
startTransition(() => setVisibleGpxes(gpxes));
};
if (props.viewPort !== undefined) {
getVisibleGpxes();
}
}, [
props.viewPort?.bottomRight.x,
props.viewPort?.bottomRight.y,
props.viewPort?.topLeft.x,
props.viewPort?.topLeft.y,
props.keyObject?.zoomLevel,
]);
return (
<>
{visibleGpxes.map((id: string) => (
<Gpx
key={id}
id={id}
keyObject={props.keyObject!}
zoom={props.zoom!}
viewPort={props.viewPort!}
/>
))}
</>
);
};
export default Gpxes;

View File

@ -0,0 +1,5 @@
.handler {
position: fixed;
height: 100%;
width: 100%;
}

View File

@ -0,0 +1,243 @@
import { createEvent, fireEvent, render, screen } from '@testing-library/react';
import { Handlers } from './Handlers';
import { Transformation } from './LiveMap';
import { Point } from './types';
describe('The Handlers component ', () => {
test('is just an empty div', () => {
const transformMap = (t: Transformation) => {};
render(<Handlers transformMap={transformMap} />);
// screen.debug();
const handlers = screen.getByRole('presentation');
// screen.debug();
expect(handlers).toMatchInlineSnapshot(`
<div
class="handler"
role="presentation"
/>
`);
});
/* test('handle mouseDown / mouseMove events', () => {
var transformMapParams: any;
function transformMap(
deltaShift: Point | null,
deltaZoom: number | null,
zoomCenter: Point | null
) {
console.log(`transformMap${JSON.stringify(arguments)}`);
transformMapParams = arguments;
}
render(<Handlers transformMap={transformMap} />);
const handlers = screen.getByRole('presentation');
fireEvent(
handlers,
createEvent.mouseDown(handlers, {
clientX: 10,
clientY: 20,
})
);
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 20,
clientY: 50,
})
);
// screen.debug();
expect(transformMapParams).toMatchInlineSnapshot(`
Arguments [
Object {
"x": 10,
"y": 30,
},
null,
null,
]
`);
});
test('does *not* handle mouseMove events not preceded by a mouseDown', () => {
var transformMapParams: any;
function transformMap(
deltaShift: Point | null,
deltaZoom: number | null,
zoomCenter: Point | null
) {
console.log(`transformMap${JSON.stringify(arguments)}`);
transformMapParams = arguments;
}
render(<Handlers transformMap={transformMap} />);
const handlers = screen.getByRole('presentation');
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 20,
clientY: 50,
})
);
// screen.debug();
expect(transformMapParams).toBeUndefined();
});
test('A mouseUp event disable further mouseMove events', () => {
var transformMapParams: any;
function transformMap(
deltaShift: Point | null,
deltaZoom: number | null,
zoomCenter: Point | null
) {
console.log(`transformMap${JSON.stringify(arguments)}`);
transformMapParams = arguments;
}
render(<Handlers transformMap={transformMap} />);
const handlers = screen.getByRole('presentation');
fireEvent(
handlers,
createEvent.mouseDown(handlers, {
clientX: 10,
clientY: 20,
})
);
fireEvent(
handlers,
createEvent.mouseUp(handlers, {
clientX: 20,
clientY: 50,
})
);
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 20,
clientY: 50,
})
);
// screen.debug();
expect(transformMapParams).toBeUndefined();
});
test('A mouseLeave event disable further mouseMove events', () => {
var transformMapParams: any;
function transformMap(
deltaShift: Point | null,
deltaZoom: number | null,
zoomCenter: Point | null
) {
console.log(`transformMap${JSON.stringify(arguments)}`);
transformMapParams = arguments;
}
render(<Handlers transformMap={transformMap} />);
const handlers = screen.getByRole('presentation');
fireEvent(handlers, createEvent.mouseOver(handlers));
fireEvent(handlers, createEvent.mouseEnter(handlers));
fireEvent(
handlers,
createEvent.mouseDown(handlers, {
clientX: 10,
clientY: 20,
})
);
fireEvent(handlers, createEvent.mouseOut(handlers));
fireEvent(handlers, createEvent.mouseLeave(handlers));
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 20,
clientY: 50,
})
);
// screen.debug();
expect(transformMapParams).toBeUndefined();
});
test('throttle mouseMove events', () => {
var transformMapParams: any;
function transformMap(
deltaShift: Point | null,
deltaZoom: number | null,
zoomCenter: Point | null
) {
console.log(`transformMap${JSON.stringify(arguments)}`);
transformMapParams = arguments;
}
render(<Handlers transformMap={transformMap} />);
const handlers = screen.getByRole('presentation');
fireEvent(
handlers,
createEvent.mouseDown(handlers, {
clientX: 10,
clientY: 20,
})
);
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 20,
clientY: 50,
})
);
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 30,
clientY: 60,
})
);
// screen.debug();
expect(transformMapParams).toMatchInlineSnapshot(`
Arguments [
Object {
"x": 10,
"y": 30,
},
null,
null,
]
`);
});
test('throttle mouseMove events', async () => {
var transformMapParams: any;
function transformMap(
deltaShift: Point | null,
deltaZoom: number | null,
zoomCenter: Point | null
) {
console.log(`transformMap${JSON.stringify(arguments)}`);
transformMapParams = arguments;
}
render(<Handlers transformMap={transformMap} />);
const handlers = screen.getByRole('presentation');
fireEvent(
handlers,
createEvent.mouseDown(handlers, {
clientX: 10,
clientY: 20,
})
);
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 20,
clientY: 50,
})
);
await new Promise((r) => setTimeout(r, 500));
fireEvent(
handlers,
createEvent.mouseMove(handlers, {
clientX: 5,
clientY: 5,
})
);
// screen.debug();
expect(transformMapParams).toMatchInlineSnapshot(`
Arguments [
Object {
"x": -15,
"y": -45,
},
null,
null,
]
`);
}); */
});

View File

@ -0,0 +1,327 @@
import react, { useRef } from 'react';
import { Point } from './types';
import './Handler.css';
import { handlersConfig } from './config';
import { Transformation } from './LiveMap';
import { isOpenAtom } from '../dialogs/Explorer';
import cache from '../../lib/cache';
import { useAtom } from 'jotai';
/**
*
*
*
*/
export interface HandlersProperties {
/** The transformation to apply on the `<LiveMap>` parent */
transformMap: (t: Transformation) => void;
}
/**
*
* @param props
* @returns A div with the following handlers
* * mouseLeave, mouseDown and mouseUp to track the mouse state
* * mouseMove to shift the map if the mouse is down
* * doubleClick to zoom in
* * wheel to zoom in and out
* * touchStart, touchEnd and touchCancel to track touch state
* * touchMove to shift the map (single finger) or shift and zoom (two fingers).
*
* Communication with the parent `<LiveMap>` is done through the transformMap {@link components/map/LiveMap!Transformation} property.
*/
export const Handlers: react.FC<HandlersProperties> = (
props: HandlersProperties
) => {
const genericHandler = (event: any) => {
// console.log(`Log - Event: ${event.type}`);
// if (event.clientX !== undefined) {
// console.log(
// `Mouse : ${event.clientX}, ${event.clientY}, target: ${event.target}`
// );
// console.log(
// `mouseState: ' ${JSON.stringify(mouseState)} (+${
// Date.now() - mouseState.timestamp
// }ms) `
// );
// return;
//}
};
/**
*
* Mouse handlers
*
*/
const initialMouseState = {
down: false,
starting: { x: -1, y: -1 },
timestamp: 0,
};
const mouseState = useRef(initialMouseState);
const mouseLeaveHandler = (event: any) => {
genericHandler(event);
mouseState.current = initialMouseState;
};
const mouseDownHandler = (event: any) => {
genericHandler(event);
mouseState.current = {
down: true,
starting: { x: event.clientX, y: event.clientY },
timestamp: 0,
};
};
const mouseUpHandler = (event: any) => {
genericHandler(event);
mouseState.current = initialMouseState;
};
const mouseMoveHandler = (event: any) => {
if (
mouseState.current.down &&
Date.now() - mouseState.current.timestamp >
handlersConfig.mouseMoveThrottleDelay /* &&
(event.clientX - mouseState.current.starting.x) ** 2 +
(event.clientY - mouseState.current.starting.y) ** 2 >
100 */
) {
genericHandler(event);
if (mouseState.current.down) {
props.transformMap({
deltaShift: {
x: event.clientX - mouseState.current.starting.x,
y: event.clientY - mouseState.current.starting.y,
},
deltaZoom: null,
zoomCenter: null,
});
mouseState.current = {
down: true,
starting: {
x: event.clientX,
y: event.clientY,
},
timestamp: Date.now(),
};
}
}
};
/**
*
* Double click
*
*/
const doubleClickHandler = (event: any) => {
genericHandler(event);
props.transformMap({
deltaShift: null,
deltaZoom: Math.SQRT2,
zoomCenter: {
x: event.clientX,
y: event.clientY,
},
});
};
/**
*
* Wheel handler
*
*/
const initialWheelState = {
timestamp: 0,
};
const wheelState = useRef(initialWheelState);
const wheelEventHandler = (event: any) => {
genericHandler(event);
if (
event.deltaMode === WheelEvent.DOM_DELTA_PIXEL &&
Date.now() - wheelState.current.timestamp >
handlersConfig.wheelThrottleDelay
) {
props.transformMap({
deltaShift: null,
deltaZoom: event.deltaY < 0 ? Math.SQRT2 : Math.SQRT1_2,
zoomCenter: {
x: event.clientX,
y: event.clientY,
},
});
wheelState.current = {
timestamp: Date.now(),
};
}
};
/**
*
* Touch handlers
*
*/
interface TouchState {
state: 'up' | 'pointer' | 'double';
touches: Point[];
distance: number;
timestamp: number;
}
const initialTouchState: TouchState = {
state: 'up',
touches: [],
distance: -1,
timestamp: 0,
};
const touchState = useRef<TouchState>(initialTouchState);
const touchCancelHandler = (event: any) => {
genericHandler(event);
touchState.current = initialTouchState;
};
const touchEndHandler = touchCancelHandler;
const touchStartHandler = (event: any) => {
genericHandler(event);
if (event.touches.length === 2) {
touchState.current = {
state: 'double',
touches: [
{ x: event.touches[0].screenX, y: event.touches[0].screenY },
{ x: event.touches[1].screenX, y: event.touches[1].screenY },
],
distance: Math.sqrt(
(event.touches[0].screenX - event.touches[1].screenX) ** 2 +
(event.touches[0].screenY - event.touches[1].screenY) ** 2
),
timestamp: Date.now(),
};
} else if (event.touches.length === 1) {
touchState.current = {
state: 'pointer',
touches: [{ x: event.touches[0].screenX, y: event.touches[0].screenY }],
timestamp: Date.now(),
distance: -1,
};
}
};
const touchMoveHandler = (event: any) => {
if (
touchState.current.state === 'double' &&
Date.now() - touchState.current.timestamp >
handlersConfig.doubleTouchMoveThrottleDelay
) {
if (event.touches.length === 2) {
genericHandler(event);
const newDistance = Math.sqrt(
(event.touches[0].screenX - event.touches[1].screenX) ** 2 +
(event.touches[0].screenY - event.touches[1].screenY) ** 2
);
const factor = newDistance / touchState.current.distance;
// console.log(`+++++++++ ZOOM Factor is ${factor} ++++++++++`);
const previousCenter = {
x:
(touchState.current.touches[0].x +
touchState.current.touches[1].x) /
2,
y:
(touchState.current.touches[0].y +
touchState.current.touches[1].y) /
2,
};
const currentCenter = {
x: (event.touches[0].screenX + event.touches[1].screenX) / 2,
y: (event.touches[0].screenY + event.touches[1].screenY) / 2,
};
props.transformMap({
deltaShift: {
x: currentCenter.x - previousCenter.x,
y: currentCenter.y - previousCenter.y,
},
deltaZoom: factor,
zoomCenter: {
x: (currentCenter.x + previousCenter.x) / 2,
y: (currentCenter.y + previousCenter.y) / 2,
},
});
touchState.current = {
state: 'double',
touches: [
{ x: event.touches[0].screenX, y: event.touches[0].screenY },
{ x: event.touches[1].screenX, y: event.touches[1].screenY },
],
distance: newDistance,
timestamp: Date.now(),
};
}
} else if (
touchState.current.state === 'pointer' &&
Date.now() - touchState.current.timestamp >
handlersConfig.singleTouchMoveThrottleDelay
) {
if (event.touches.length === 1) {
genericHandler(event);
props.transformMap({
deltaShift: {
x: event.touches[0].screenX - touchState.current.touches[0].x,
y: event.touches[0].screenY - touchState.current.touches[0].y,
},
deltaZoom: null,
zoomCenter: null,
});
touchState.current = {
state: 'pointer',
touches: [
{
x: event.touches[0].screenX,
y: event.touches[0].screenY,
},
],
timestamp: Date.now(),
distance: -1,
};
}
}
};
const [, setIsOpen] = useAtom(isOpenAtom);
const contextMenuHandler = (event: any) => {
console.log(event);
event.preventDefault();
console.log(cache.map({ cacheId: 'points' }));
setIsOpen(true);
};
return (
<div
className='handler'
role='presentation'
onMouseDown={mouseDownHandler}
onMouseMove={mouseMoveHandler}
onMouseUp={mouseUpHandler}
onMouseLeave={mouseLeaveHandler}
onDoubleClick={doubleClickHandler}
onWheel={wheelEventHandler}
onTouchEnd={touchEndHandler}
onTouchCancel={touchCancelHandler}
onTouchStart={touchStartHandler}
onTouchMove={touchMoveHandler}
onContextMenu={contextMenuHandler}
/>
);
};
export default Handlers;

View File

@ -0,0 +1,241 @@
import { render, screen } from '@testing-library/react';
import LayerStack from './LayerStack';
import { CoordinateSystem } from './LiveMap';
describe('The LayerStack component', () => {
const coordinateSystem:CoordinateSystem= {
shift:{x:0,y:0},
zoom:1,
}
test('generates four empty layers and a populated one', () => {
// const { result } = renderHook(() => useAtom(tiledLayersAtom));
render(
<LayerStack
numberOfTiledLayers={5}
keyObject={{ provider: 'fake', zoomLevel: 9, x: 777, y: 333 }}
coordinateSystem= {coordinateSystem}
/>
);
const svg = screen.getByTestId('layer-stack');
expect(svg).toMatchInlineSnapshot(`
<svg
data-testid="layer-stack"
height="100%"
width="100%"
>
<g
transform="translate(0, 0) scale(1)"
>
<g
transform="scale(1024) translate(-194.25, -83.25)"
/>
<g
transform="scale(512) translate(-388.5, -166.5)"
/>
<g
transform="scale(64) translate(-3108, -1332)"
/>
<g
transform="scale(128) translate(-1554, -666)"
/>
<g
transform="scale(256) translate(-777, -333)"
/>
</g>
</svg>
`);
});
test('generates two empty layers and a populated one', () => {
// const { result } = renderHook(() => useAtom(tiledLayersAtom));
render(
<LayerStack
numberOfTiledLayers={3}
keyObject={{ provider: 'fake', zoomLevel: 9, x: 777, y: 333 }}
coordinateSystem= {coordinateSystem}
/>
);
const svg = screen.getByTestId('layer-stack');
expect(svg).toMatchInlineSnapshot(`
<svg
data-testid="layer-stack"
height="100%"
width="100%"
>
<g
transform="translate(0, 0) scale(1)"
>
<g
transform="scale(512) translate(-388.5, -166.5)"
/>
<g
transform="scale(128) translate(-1554, -666)"
/>
<g
transform="scale(256) translate(-777, -333)"
/>
</g>
</svg>
`);
});
/* test('populates a new layer when zoomed in', () => {
// const { result } = renderHook(() => useAtom(tiledLayersAtom));
render(
<LayerStack
numberOfTiledLayers={3}
keyObject={{ provider: 'fake', zoomLevel: 9, x: 777, y: 333 }}
coordinateSystem= {coordinateSystem}
/>
);
const { result } = renderHook(() => [
useAtom(coordinateSystemAtom),
useAtom(relativeCoordinateSystemAtom),
]);
act(() => {
result.current[0][1]({
shift: {
x: 0,
y: 0,
},
zoom: 1,
} as any);
result.current[1][1]({
deltaShift: null,
zoomCenter: { x: 0, y: 0 },
deltaZoom: 2,
} as any);
});
const svg = screen.getByTestId('layer-stack');
expect(svg).toMatchInlineSnapshot(`
<svg
data-testid="layer-stack"
height="768"
width="1024"
>
<g
transform="translate(0, 0) scale(2)"
>
<g
transform="scale(128) translate(-388.5, -166.5)"
/>
<g
transform="scale(512) translate(-1554, -666)"
/>
<g
transform="scale(256) translate(-777, -333)"
>
<g
transform="translate(777, 333)"
>
<image
height="1"
href="https://fakeurl/9/265/333.png"
width="1"
/>
</g>
<g
transform="translate(778, 333)"
>
<image
height="1"
href="https://fakeurl/9/266/333.png"
width="1"
/>
</g>
<g
transform="translate(779, 333)"
>
<image
height="1"
href="https://fakeurl/9/267/333.png"
width="1"
/>
</g>
<g
transform="translate(780, 333)"
>
<image
height="1"
href="https://fakeurl/9/268/333.png"
width="1"
/>
</g>
<g
transform="translate(777, 334)"
>
<image
height="1"
href="https://fakeurl/9/265/334.png"
width="1"
/>
</g>
<g
transform="translate(778, 334)"
>
<image
height="1"
href="https://fakeurl/9/266/334.png"
width="1"
/>
</g>
<g
transform="translate(779, 334)"
>
<image
height="1"
href="https://fakeurl/9/267/334.png"
width="1"
/>
</g>
<g
transform="translate(780, 334)"
>
<image
height="1"
href="https://fakeurl/9/268/334.png"
width="1"
/>
</g>
<g
transform="translate(777, 335)"
>
<image
height="1"
href="https://fakeurl/9/265/335.png"
width="1"
/>
</g>
<g
transform="translate(778, 335)"
>
<image
height="1"
href="https://fakeurl/9/266/335.png"
width="1"
/>
</g>
<g
transform="translate(779, 335)"
>
<image
height="1"
href="https://fakeurl/9/267/335.png"
width="1"
/>
</g>
<g
transform="translate(780, 335)"
>
<image
height="1"
href="https://fakeurl/9/268/335.png"
width="1"
/>
</g>
</g>
</g>
</svg>
`);
}); */
});

View File

@ -0,0 +1,146 @@
import react, {
cloneElement,
JSXElementConstructor,
ReactComponentElement,
ReactElement,
ReactNode,
useRef,
} from 'react';
import { Rectangle, TileKeyObject } from './types';
import { CoordinateSystem } from './LiveMap';
import { range } from 'lodash';
import tileUri from './uris';
import TiledLayer from './TiledLayer';
import { ReactComponentOrElement } from '@ionic/react';
import { KeyObject } from 'crypto';
import useViewport from './use-viewport';
export interface LayerStackProperties {
/**
* A key identifying the top left tile
*/
keyObject: TileKeyObject;
/**
* Number of {@link components/map/TiledLayer!TiledLayer}.
*/
numberOfTiledLayers?: number;
/**
* The coordinates system
*/
coordinateSystem: CoordinateSystem;
/** Slippy graphics are non scalable SVG snippets defined by geo locations */
slippyGraphics?: ReactElement<any, string | JSXElementConstructor<any>>[];
}
/**
*
* @param props
* @returns A stack of layers embedded in an SVG element
*
* This component does the conversion between the {@link components/map/LiveMap!CoordinateSystem} and
* the `<`{@link components/map/TiledLayer!TiledLayer}`>`
* components which units are in tiles.
*
* When more then one {@link components/map/TiledLayer!TiledLayer} is required, the tiled layer identified by the keyObject is considered active and new tiles are added
* as needed and the other layers are used as backups while the tiles are loading.
*
*/
export const LayerStack: react.FC<LayerStackProperties> = (
props: LayerStackProperties
) => {
console.log(
`LayerStack rendering, coordinateSystem: ${JSON.stringify(
props.coordinateSystem
)}, slippyGraphics: ${props.slippyGraphics}`
);
const g = useRef<SVGGElement>(null);
const viewPort = useViewport({
coordinateSystem: props.coordinateSystem,
keyObject: props.keyObject,
svgElement: g,
});
const numberOfTiledLayers =
props.numberOfTiledLayers === undefined ? 1 : props.numberOfTiledLayers;
const activeTiledLayer = Math.floor(numberOfTiledLayers / 2);
const getTiledLayer = (i: number, viewPort?: Rectangle) => {
const relativeZoomLevel = i - activeTiledLayer;
const zoom = 2 ** relativeZoomLevel;
const origin = {
x: props.keyObject.x * zoom,
y: props.keyObject.y * zoom,
};
const keyObject = {
provider: props.keyObject.provider,
zoomLevel: props.keyObject.zoomLevel + relativeZoomLevel,
x: Math.floor(origin.x),
y: Math.floor(origin.y),
};
const shift = {
x: -origin.x,
y: -origin.y,
};
const key = tileUri({
provider: keyObject.provider,
zoomLevel: keyObject.zoomLevel,
});
return (
<TiledLayer
key={key}
keyObject={keyObject}
shift={shift}
zoom={256 / zoom}
coordinateSystem={props.coordinateSystem}
viewPort={viewPort}
/>
);
};
// console.log(`tiledLayers: ${JSON.stringify(tiledLayers)}`);
return (
<svg width='100%' height='100%' data-testid='layer-stack'>
<g
transform={`translate(${props.coordinateSystem.shift.x}, ${props.coordinateSystem.shift.y}) scale(${props.coordinateSystem.zoom})`}
key='tiles'
ref={g}
>
{
// Tiled layers with less detail
range(0, activeTiledLayer).map((index) => getTiledLayer(index))
}
{
// Tiled layers with more details
range(numberOfTiledLayers - 1, activeTiledLayer, -1).map((index) =>
getTiledLayer(index)
)
}
{
// And the active one
getTiledLayer(activeTiledLayer, viewPort)
}
{props.slippyGraphics !== undefined ? (
// Slippy graphics (if needed)
<>
{props.slippyGraphics.map((slippyGraphic) =>
cloneElement(slippyGraphic, {
keyObject: props.keyObject,
zoom: props.coordinateSystem.zoom,
viewPort: viewPort,
})
)}
{console.log('LayerStack: adding slippyGraphics')},
</>
) : null}
</g>
</svg>
);
};
export default LayerStack;

View File

@ -0,0 +1,155 @@
import react, {
JSXElementConstructor,
ReactElement,
useEffect,
useState,
} from 'react';
import useDimensions from 'react-cool-dimensions';
import { MapScope, Point } from './types';
import Map from './Map';
import Handlers from './Handlers';
import { tileProviders } from './tile-providers';
import { lon2tile, lat2tile, tile2lat, tile2long } from '../../lib/geo';
/**
* Definition of a coordinate system
*
* The coordinate system is shifted and zoomed (from the viewport origin)
*
*/
export interface CoordinateSystem {
/** Zoom relative to the origin */
zoom: number;
/** Origin's shift (in pixels) */
shift: Point;
}
/**
* Description of coordinates system transformation
*/
export interface Transformation {
/** New translation to apply */
deltaShift: Point | null;
/** Zoom factor to apply */
deltaZoom: number | null;
/** Center of the new zoom to apply */
zoomCenter: Point | null;
}
export interface LiveMapProperties {
/** The initial map's scope */
scope: MapScope;
/** The number of tiled layers (default to 1) */
numberOfTiledLayers?: number;
/** If provided, a function to call when the scope is updated. */
setScope?: (scope: MapScope) => void;
/** Slippy graphics are non scalable SVG snippets defined by geo locations */
slippyGraphics?: ReactElement<any, string | JSXElementConstructor<any>>[];
}
/**
*
* @param props
* @returns A `<LiveMap>` component.
*
* A `<LiveMap>` is a wrapper around a {@link components/map/Map!Map} component which updates the `<Map>`'s scope according to user's mouse, wheel and touch events.
*
* To do so, `<LiveMap>` embeds a `<Map>` component together with a {@link components/map/Handlers!Handlers} component which listens to user's event.
*
* The main task of `<LiveMap>` components is thus to translate {@link Transformation}s delivered by `<Handler>` in pixels into geographical coordinates.
*/
export const LiveMap: react.FC<LiveMapProperties> = (
props: LiveMapProperties
) => {
const [scope, setScope] = useState(props.scope);
useEffect(() => {
setScope(props.scope);
}, [props.scope]);
console.log(
`LiveMap rendering, scope: ${JSON.stringify(scope)}, slippyGraphics: ${
props.slippyGraphics
}`
);
const { observe, width, height } = useDimensions<HTMLDivElement>();
const transform = (t: Transformation) => {
const deltaZoom = t.deltaZoom === null ? 1 : t.deltaZoom;
const deltaZoomLevel = Math.log2(deltaZoom);
const tileProvider = tileProviders[scope.tileProvider];
const tilesZoom = Math.min(
Math.max(Math.round(scope.zoom), tileProvider.minZoom),
tileProvider.maxZoom
);
const softZoom = scope.zoom - tilesZoom;
const relativeScale = 2 ** softZoom;
const visibleTileSize = tileProvider.tileSize * relativeScale;
// Values in pixels
const actualDeltaShift =
t.deltaShift === null ? { x: 0, y: 0 } : t.deltaShift;
const actualZoomCenter =
t.zoomCenter === null ? { x: 0, y: 0 } : t.zoomCenter;
// Values in tiles (for the current zoom level)
const actualDeltaShiftTiles = {
x: actualDeltaShift.x / visibleTileSize,
y: actualDeltaShift.y / visibleTileSize,
};
const actualZoomCenterTiles = {
x: actualZoomCenter.x / visibleTileSize,
y: actualZoomCenter.y / visibleTileSize,
};
const tilesCenter: Point = {
x: lon2tile(scope.center.lon, tilesZoom),
y: lat2tile(scope.center.lat, tilesZoom),
};
const newTilesCenter = {
x:
tilesCenter.x -
actualDeltaShiftTiles.x -
(width / 2 / visibleTileSize - actualZoomCenterTiles.x) *
(deltaZoom - 1),
y:
tilesCenter.y -
actualDeltaShiftTiles.y -
(height / 2 / visibleTileSize - actualZoomCenterTiles.y) *
(deltaZoom - 1),
};
const newScope: MapScope = {
center: {
lat: tile2lat(newTilesCenter.y, tilesZoom),
lon: tile2long(newTilesCenter.x, tilesZoom),
},
zoom: deltaZoomLevel + scope.zoom,
tileProvider: scope.tileProvider,
};
// console.log(
// `LiveMap transform: ${JSON.stringify(t)}, ${JSON.stringify(
// scope
// )} -> ${JSON.stringify(newScope)}, delta lat: ${
// newScope.center.lat - scope.center.lat
// }, delta lon: ${newScope.center.lon - scope.center.lon}`
// );
setScope(newScope);
if (props.setScope !== undefined) {
props.setScope(newScope);
}
};
return (
<div style={{ width: '100%', height: '100%' }} ref={observe}>
<Handlers transformMap={transform} />
<Map
scope={scope}
numberOfTiledLayers={props.numberOfTiledLayers}
slippyGraphics={props.slippyGraphics}
/>
</div>
);
};
export default LiveMap;

View File

@ -1,22 +0,0 @@
.ol-map {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.ol-control {
position: absolute;
background-color: rgba(255, 255, 255, 0.4);
border-radius: 4px;
padding: 2px;
}
.ol-full-screen {
top: 0.5em;
right: 0.5em;
}
.ol-rotate {
top: auto;
bottom: 0.5em;
right: 3em;
}

View File

@ -1,343 +1,75 @@
import { Component, createEffect, createSignal, onMount } from 'solid-js';
import { useParams, useNavigate } from '@solidjs/router';
import OlMap from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
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 react, { JSXElementConstructor, ReactElement, ReactNode } from 'react';
import useDimensions from 'react-cool-dimensions';
import 'ol/ol.css';
import './Map.css';
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 '../import';
import AllGpxes from '../all-gpxes';
import MapTileProvider, { mapTileProviders } from '../map-tile-provider';
import Interaction from 'ol/interaction/Interaction';
import DragPan from 'ol/interaction/DragPan';
import PinchRotate from 'ol/interaction/PinchRotate';
import PinchZoom from 'ol/interaction/PinchZoom';
import KeyboardPan from 'ol/interaction/KeyboardPan';
import KeyboardZoom from 'ol/interaction/KeyboardZoom';
import MouseWheelZoom from 'ol/interaction/MouseWheelZoom';
import DragZoom from 'ol/interaction/DragZoom';
import Infos, { clickHandler } from '../infos';
import GpxDialog from '../gpx-dialog';
import GpxRecord from '../gpx-record';
import dispatch from '../../workers/dispatcher-main';
import { debounce } from 'lodash';
import { Point, MapScope } from './types';
import Marker from './Marker';
import { AndroidFullScreen } from '@awesome-cordova-plugins/android-full-screen';
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';
import LayerStack from './LayerStack';
import { tileProviders } from './tile-providers';
import { lon2tile, lat2tile } from '../../lib/geo';
const [getState, setState] = createSignal({
lon: 0,
lat: 0,
rotation: 0,
zoom: 0,
provider: 'osm',
});
const getZoomInteger = () => Math.floor(getState().zoom);
export { getState, getZoomInteger };
const [getMap, setMap] = createSignal<OlMap | null>(null);
export { getMap };
const Map: Component = () => {
const navigate = useNavigate();
const params = useParams();
searchInvitation();
// See https://stackoverflow.com/questions/71288670/how-to-make-fullscreen-ionic-capacitor-app
AndroidFullScreen.isImmersiveModeSupported()
.then(() => AndroidFullScreen.immersiveMode())
.catch(console.warn);
if (window.plugins) {
window.plugins.intentShim.registerBroadcastReceiver(
{
filterActions: [
'android.intent.action.VIEW',
'android.intent.action.SEND',
],
},
function (intent: any) {
console.log({
caller: 'Intent broadcast receiver',
intent,
});
export interface MapProperties {
scope: MapScope;
numberOfTiledLayers?: number;
/** Slippy graphics are non scalable SVG snippets defined by geo locations */
slippyGraphics?: ReactElement<any, string | JSXElementConstructor<any>>[];
}
/**
*
* @returns A `<Map>` component
*
* `<Map>` components display the map specified by their {@link MapProperties}'s scope.
*
* They can be driven by {@link components/map/LiveMap!LiveMap} component to react to user's event.
*
*/
export const Map: react.FC<MapProperties> = (props: MapProperties) => {
console.log(
`Map rendering, scope: ${JSON.stringify(props.scope)}, slippyGraphics: ${
props.slippyGraphics
}`
);
window.plugins.intentShim.onIntent(function (intent: any) {
console.log({ caller: 'Intent receiver', intent });
if (receiveIntent(intent, navigate)) {
return;
}
});
} else {
console.log({
caller: 'Intent',
message: "window.plugins doesn't exist",
window,
});
}
const dropHandler = (event: any) => {
event.preventDefault();
console.log({
caller: 'Map / dropHandler',
event,
files: event.dataTransfer.files,
});
importUrls(event.dataTransfer.files);
};
const { observe, width, height } = useDimensions<HTMLDivElement>();
const dragEnterHandler = (event: any) => {
event.preventDefault();
console.log({ caller: 'Map / dragEnterHandler', event });
};
const tileProvider = tileProviders[props.scope.tileProvider];
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' &&
params.provider === 'osm' &&
params.rotation === '0' &&
params.zoom === '2'
) {
dispatch({ action: 'getState' }, (error, state) => {
if (state !== null) {
console;
navigate(
`/map/${state.provider}/${state.lon}/${state.lat}/${state.zoom}/${state.rotation}`
const tilesZoom = Math.min(
Math.max(Math.round(props.scope.zoom), tileProvider.minZoom),
tileProvider.maxZoom
);
}
});
}
let target: HTMLDivElement;
const debouncedDbSetState = debounce((state: any) => {
console.log({ caller: 'Map / debouncedDbSetState', state });
dispatch({ action: 'setState', params: state });
}, 60000);
createEffect(async () => {
console.log({
caller: 'Map / setState',
params: {
...params,
},
lastCommit: import.meta.env.VITE_GIT_COMMIT_HASH,
});
setState({
provider: params.provider,
lon: +params.lon,
lat: +params.lat,
rotation: +params.rotation,
zoom: +params.zoom,
});
debouncedDbSetState(getState());
const map = getMap();
const layers = map?.getLayers();
const tileLayer = layers?.item(0) as TileLayer<any> | undefined;
if (tileLayer?.get('provider') !== params.provider) {
tileLayer?.set('provider', params.provider, true);
tileLayer?.setSource(mapTileProviders[params.provider].source);
}
const view = map?.getView();
view?.animate({
center: fromLonLat([getState().lon, getState().lat]),
rotation: getState().rotation,
zoom: getState().zoom,
duration: 1000,
});
});
createEffect(() => {
const location = getCurrentLocation();
if (location) {
console.log({
caller: 'Map / updateLocation',
location,
});
const source = getMap()
?.getAllLayers()
.at(1)
?.getSource() as VectorSource;
source!.clear(true);
const point = new Point(fromLonLat([location.lon, location.lat]));
const style = new Style({
image: new Icon({
// size: [20, 20],
imgSize: [24, 24],
declutterMode: 'obstacle',
// @ts-ignore
src: ShowLocationIcon,
}),
});
const feature = new Feature({
geometry: point,
// labelPoint: point,
// name: 'current location',
style: style,
});
feature.set('type', 'current-location');
feature.setStyle(style);
source.addFeature(feature);
// source.changed();
console.log({
caller: 'Map / updateLocation',
location,
source,
style,
feature,
});
}
});
onMount(async () => {
// olUseGeographic();
const changeListener = (event: any) => {
const map = getMap();
const view = map?.getView();
const center = view?.getCenter();
if (center) {
const centerLonLat = toLonLat(center);
navigate(
`/map/${getState().provider}/${centerLonLat[0]}/${
centerLonLat[1]
}/${view?.getZoom()}/${view?.getRotation()}`
);
}
console.log({
caller: 'Map / changeListener',
event,
params: {
...params,
},
map,
center,
});
const tilesCenter: Point = {
x: lon2tile(props.scope.center.lon, tilesZoom),
y: lat2tile(props.scope.center.lat, tilesZoom),
};
const tileLayer = new TileLayer({
source: mapTileProviders[params.provider].source,
});
tileLayer.set('provider', params.provider, true);
const vectorLayer = new VectorLayer({
source: new VectorSource(),
zIndex: Infinity,
});
// console.log({
// caller: 'Map / projections',
// vector: vectorLayer.getSource()?.getProjection(),
// 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]),
zoom: +getState().zoom,
rotation: +getState().rotation,
}),
layers: [tileLayer, vectorLayer],
target: target,
controls: new Collection<Control>(controls),
moveTolerance: 10,
interactions: new Collection<Interaction>([
new DragRotate(),
// new DoubleClickZoom(),
new DragPan(),
new PinchRotate(),
new PinchZoom(),
new KeyboardPan(),
new KeyboardZoom(),
new MouseWheelZoom(),
new DragZoom(),
]),
});
olMap.on(['moveend'], changeListener);
olMap.on(['dblclick'], clickHandler);
setMap(olMap);
});
const softZoom = props.scope.zoom - tilesZoom;
const relativeScale = 2 ** softZoom;
const visibleTileSize = tileProvider.tileSize * relativeScale;
const nbTilesLeft = width / 2 / visibleTileSize;
const nbTilesTop = height / 2 / visibleTileSize;
const firstTileLeft = Math.floor(tilesCenter.x - nbTilesLeft);
const firstTileTop = Math.floor(tilesCenter.y - nbTilesTop);
return (
//<OsmFetch map={getMap} />
// @ts-ignore
<div
class='ol-map'
ref={target}
ondrop={dropHandler}
ondragover={dragOverHandler}
ondragenter={dragEnterHandler}
>
<Updater />
<Invitation />
<Overlays map={getMap} />
<Note />
<Finder />
<GetLocation />
<Show when={window.Capacitor.platform !== 'web'}>
<Forward />
<Back />
<GpxRecord />
</Show>
<GpxImport />
<MapTileProvider />
<GpxDialog />
<SystemDrawer />
<AllGpxes map={getMap} />
<Infos />
<div style={{ width: '100%', height: '100%' }} ref={observe}>
<LayerStack
numberOfTiledLayers={props.numberOfTiledLayers}
keyObject={{
provider: props.scope.tileProvider,
zoomLevel: tilesZoom,
x: firstTileLeft,
y: firstTileTop,
}}
coordinateSystem={{
shift: {
x: -((tilesCenter.x - nbTilesLeft) % 1) * visibleTileSize,
y: -((tilesCenter.y - nbTilesTop) % 1) * visibleTileSize,
},
zoom: relativeScale,
}}
slippyGraphics={props.slippyGraphics}
/>
</div>
);
};

View File

@ -0,0 +1,72 @@
import react, { ReactNode, useEffect } from 'react';
import { lat2tile, lon2tile } from '../../lib/geo';
import cache from '../../lib/cache';
import { geoPoint, Rectangle, TileKeyObject } from './types';
export interface MarkerProperties {
id: string;
coordinates: geoPoint;
icon: ReactNode;
keyObject?: TileKeyObject;
zoom?: number;
viewPort?: Rectangle;
className?: string;
}
export const Marker: react.FC<MarkerProperties> = (props: MarkerProperties) => {
console.log(`Rendering Marker`);
useEffect(() => {
console.log(`Marker onMount, id:${props.id}`);
return () => {
console.log(`Marker onUnmount, id:${props.id}`);
cache.delete({ cacheId: 'points', key: props.id });
};
}, []);
if (
props.keyObject === undefined ||
props.zoom === undefined ||
props.viewPort === undefined
) {
console.log(`Marker props undefined: ${JSON.stringify(props)} `);
return null;
}
const x0 = lon2tile(props.coordinates.lon, 0);
const y0 = lat2tile(props.coordinates.lat, 0);
const x = x0 * 2 ** props.keyObject.zoomLevel;
const y = y0 * 2 ** props.keyObject.zoomLevel;
if (
x < props.viewPort.topLeft.x ||
x > props.viewPort.bottomRight.x + 1 ||
y < props.viewPort.topLeft.y ||
y > props.viewPort.bottomRight.y + 1
) {
cache.delete({ cacheId: 'points', key: props.id });
console.log(
`Marker ${x}, ${y} out of viewport: ${JSON.stringify(props.viewPort)} `
);
return null;
}
cache.set({
cacheId: 'points',
key: props.id,
value: {
coordinates: props.coordinates,
point: { x: x0, y: y0 },
},
});
return (
<g
transform={`translate(${(x - props.keyObject.x) * 256}, ${
(y - props.keyObject.y) * 256
}) scale(${1 / props.zoom})`}
className={props.className}
>
{props.icon}
</g>
);
};
export default Marker;

View File

@ -0,0 +1,56 @@
import { render, screen } from '@testing-library/react';
import Tile from './Tile';
import { TileKeyObject } from './types';
describe('The Tile component ', () => {
const keyObject: TileKeyObject = {
provider: 'fake',
zoomLevel: 10,
x: 1,
y: 2,
};
test('Is initially empty', () => {
const { baseElement } = render(
<svg>
<Tile keyObject={keyObject} delay={10000} />
</svg>
);
// screen.debug();
expect(baseElement).toMatchInlineSnapshot(`
<body>
<div>
<svg>
<g
transform="translate(1, 2)"
/>
</svg>
</div>
</body>
`);
});
test('Gets its image immediately with a fake URL', () => {
const { baseElement } = render(
<svg>
<Tile keyObject={keyObject} />
</svg>
);
// screen.debug();
expect(baseElement).toMatchInlineSnapshot(`
<body>
<div>
<svg>
<g
transform="translate(1, 2)"
>
<image
height="1"
href="https://fakeurl/10/1/2.png"
width="1"
/>
</g>
</svg>
</div>
</body>
`);
});
});

View File

@ -0,0 +1,68 @@
import react, { memo, useEffect, useRef } from 'react';
import { isEqual } from 'lodash';
import { TileKeyObject } from './types';
import { getTileUrl } from './tile-providers';
export interface TileProperties {
/** The image's source URL */
keyObject: TileKeyObject;
/** A delay to add (for test/debug purposes) */
delay?: number;
}
/**
*
* @param props
* @returns A tile
*
* Tile components are containers for images.
*
* They return an empty `<g/>` element immediately so that the rendering can proceed
* and append an `<image/>` element whenever the image is loaded.
*
* They are designed to be part of {@link components/map/TiledLayer!TiledLayer} components in SVG `<g/>` elements
* in which the unit is the tile size. In this coordinate system their size is thus always equal to 1.
*/
export const Tile: react.FC<TileProperties> = memo((props: TileProperties) => {
const g = useRef<SVGGElement>(null);
const timeout = (ms: number) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
// console.log(`Rendering tile: ${JSON.stringify(props)}`);
useEffect(() => {
const loadImage = async () => {
// console.log(`Pre loading: ${props.href}`);
const href = getTileUrl(props.keyObject);
const image = new Image(1, 1);
image.loading = 'eager';
// @ts-ignore
image.setAttribute('href', href);
if (!image.complete) {
await image.decode();
}
if (props.delay !== undefined) {
await timeout(props.delay);
}
const svgImage = document.createElementNS(
'http://www.w3.org/2000/svg',
'image'
) as unknown as SVGImageElement;
svgImage.setAttribute('width', '1');
svgImage.setAttribute('height', '1');
// @ts-ignore
svgImage.setAttribute('href', href);
g.current?.replaceChildren(svgImage);
};
loadImage();
}, [props.keyObject]);
return (
<g
ref={g}
transform={`translate(${props.keyObject.x}, ${props.keyObject.y})`}
/>
);
}, isEqual);
export default Tile;

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