Compare commits

...

86 Commits

Author SHA1 Message Date
ca2c9130aa
Update system-react 2023-09-15 12:48:55 +01:00
37948d1579
Update docs 2023-09-15 12:42:39 +01:00
9a13888db8
Requset builder withBareFilter 2023-09-15 12:33:32 +01:00
f6d8e96ae3
Bump packages 2023-09-15 11:11:01 +01:00
5ce15a6c6b chore: Update translations 2023-09-15 10:04:41 +00:00
268d2e2c68
Change to MIT license 2023-09-15 11:03:38 +01:00
34cb12fc95 chore: Update translations 2023-09-14 18:56:40 +00:00
70bc41e063
fix: root tabs 2023-09-14 19:55:57 +01:00
9c05b6a101 chore: Update translations 2023-09-14 18:45:29 +00:00
a8f000d9d8 Merge pull request 'deck' (#632) from deck into main
Reviewed-on: Kieran/snort#632
2023-09-14 18:44:39 +00:00
063052b622
Fix logged out snort deck 2023-09-14 19:39:05 +01:00
a31e30979d
Init SnortDeck 2023-09-14 19:39:03 +01:00
5960a5bf5f chore: Update translations 2023-09-14 12:35:37 +00:00
0fa51dd7e5
Zap split goals 2023-09-14 13:34:45 +01:00
dd4d73e81c
Cleanup 2023-09-14 13:15:15 +01:00
24d3f43600 chore: Update translations 2023-09-14 11:32:33 +00:00
d2baf9bd5b
Zap splits 2023-09-14 12:31:29 +01:00
4864ef6831 chore: Update translations 2023-09-13 11:19:16 +00:00
84f6e810b0
Catch error for zap splits 2023-09-13 12:18:13 +01:00
7b7a6c7800
Update CSP 2023-09-12 23:03:05 +01:00
35b6261e12 chore: Update translations 2023-09-12 21:58:37 +00:00
3c88a228aa
Fix lockfile 2023-09-12 22:57:43 +01:00
6745786e9f
Setup usage metrics 2023-09-12 22:53:32 +01:00
377dfd5d30
Count polls by pubkey 2023-09-12 22:17:04 +01:00
4927e0c4f8
Add new langs 2023-09-12 16:02:10 +01:00
e8f412381a
Cleanup 2023-09-12 15:57:28 +01:00
3ffcd1b2c5
fix: DM's not decrypting
fixes #629
2023-09-12 15:56:08 +01:00
e77b9928d0 chore: Update translations 2023-09-12 14:15:07 +00:00
15ffa7d4b4 Merge pull request 'wasm' (#631) from wasm into main
Reviewed-on: Kieran/snort#631
2023-09-12 14:14:13 +00:00
9e2453444d
Prettier 2023-09-12 15:02:16 +01:00
f42096fa64
Benchmarks 2023-09-12 15:00:32 +01:00
3ed62d9f9a
Build benchmarks page 2023-09-12 15:00:32 +01:00
e2e1bb90ca
Make query optimizer pluggable 2023-09-12 15:00:32 +01:00
a4c1ba8450
Remove unused constraint 2023-09-12 15:00:31 +01:00
4dfc6525a1
flat_merge to rust 2023-09-12 15:00:31 +01:00
d67beb8dbf
Cache zap parser results 2023-09-12 15:00:31 +01:00
3e0fae2c33
Merger 2023-09-12 15:00:31 +01:00
08bc4cafa9
Optimize note reaction 2023-09-12 15:00:31 +01:00
28b98864a6
Remove build command 2023-09-12 15:00:31 +01:00
dc7ac061a5
Commit wasm build 2023-09-12 15:00:30 +01:00
3232a8679c
install wasm-pack 2023-09-12 15:00:30 +01:00
d672336ea1
Try build directly with wasm-pack command 2023-09-12 15:00:30 +01:00
a0f1031b85
Add system-query 2023-09-12 15:00:30 +01:00
4df6c19248 chore: Update translations 2023-09-08 16:32:30 +00:00
8f11effb67
Fixes #630 2023-09-08 17:31:09 +01:00
106ad437f1
Use isomorphic-ws 2023-09-06 19:39:15 +01:00
e81420d4a9
Bump packages 2023-09-06 15:08:28 +01:00
65861d30a2
Formatting 2023-09-05 15:26:39 +01:00
0f635ec877
Bugfix oldest 2023-09-05 15:26:39 +01:00
5fed053a73 chore: Update translations 2023-09-05 14:23:04 +00:00
e05cfeaba9
Run formatter 2023-09-05 15:22:03 +01:00
ab464bfae5
Fix formatting command 2023-09-05 15:21:39 +01:00
c72cdcc9a9 chore: Update translations 2023-09-05 14:18:25 +00:00
5ef3fb0337
Run prettier 2023-09-05 15:17:51 +01:00
e99f323cfa chore: Update translations 2023-09-05 14:17:02 +00:00
532ab8403d
Only backfill when cache has some values already 2023-09-05 15:15:39 +01:00
0eaf619721 chore: Update translations 2023-09-05 14:14:46 +00:00
ba1fdbc22d
Bugfix oldest 2023-09-05 15:13:30 +01:00
f9d2a22c74
Fix build 2023-09-05 15:07:18 +01:00
df7353a43c chore: Update translations 2023-09-05 13:59:44 +00:00
b1459d0f49
Cache all the things 2023-09-05 14:57:50 +01:00
5521f685fc
bugfixes 2023-08-30 10:05:34 +01:00
3bbad28c32 chore: Update translations 2023-08-29 15:43:42 +00:00
d7825e23a7 chore: Update translations 2023-08-29 15:42:20 +00:00
c6d41badab
Enable swahili 2023-08-29 16:41:33 +01:00
0f610257aa chore: Update translations 2023-08-29 15:38:38 +00:00
d4eaf247b0 Merge pull request 'feat: add pt-BR to languages menu' (#623) from fernandoporazzi/snort:pt_BR-translations into main
Reviewed-on: Kieran/snort#623
2023-08-29 15:35:57 +00:00
c7ae0e8319 chore: Update translations 2023-08-29 13:57:56 +00:00
3b11831723 chore: Update translations 2023-08-29 13:56:46 +00:00
ec2b11bd75
Nip7os interface
Light theme tweaks
2023-08-29 14:55:55 +01:00
Fernando Porazzi
a6cb5ddace feat: add pt-BR to languages menu 2023-08-29 11:16:25 +00:00
8a3133af70 chore: Update translations 2023-08-28 16:40:15 +00:00
0a60b22fb2
closes #580 2023-08-28 17:38:09 +01:00
a57951c0ed
fixes #569 2023-08-28 17:38:09 +01:00
99e4be0a23
fixes #620 2023-08-28 17:38:09 +01:00
a12c82c3d9
fixes #621 2023-08-28 17:38:08 +01:00
efdc57b8c4
Mobile settings layout 2023-08-28 17:38:08 +01:00
f0f009f4fd chore: Update translations 2023-08-26 21:55:21 +00:00
5cd1ad070a
Service worker precache
Yarn upgrades / cleanup
2023-08-26 22:48:52 +01:00
6fae5accde
Show note creator on profiles 2023-08-26 22:48:52 +01:00
0630aa3208
Embed Inter font in src 2023-08-26 22:48:52 +01:00
5b5747be81 chore: Update translations 2023-08-25 18:44:52 +00:00
86247207a4
Simple search 2023-08-25 17:52:59 +01:00
8973536e01
Enable Thai language 2023-08-25 17:09:52 +01:00
807b8207ba
Disable semisol suggested follows 2023-08-25 17:05:31 +01:00
01a2f1cd82
fix dm window 2023-08-25 17:05:31 +01:00
259 changed files with 18466 additions and 7752 deletions

View File

@ -58,7 +58,7 @@ steps:
- yarn build
- yarn test
- yarn workspace @snort/app eslint
- yarn workspace @snort/app prettier --check .
- yarn prettier --check .
volumes:
- name: cache
claim:
@ -93,7 +93,7 @@ steps:
- yarn install
- npx @crowdin/cli upload sources -b main -T $CTOKEN
- npx @crowdin/cli pull -b main -T $CTOKEN
- yarn workspace @snort/app format
- yarn prettier --write .
- git add .
- 'git commit -a -m "chore: Update translations"'
- git push -u origin main

1
.husky/.gitignore vendored
View File

@ -1 +0,0 @@
_

View File

@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn workspace @snort/app lint-staged

View File

@ -3,4 +3,5 @@ build/
.vscode/
.github/
transifex.yml
dist/
dist/
src-tauri/

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1 @@
yarnPath: .yarn/releases/yarn-3.6.1.cjs
npmScopes:
void-cat:
npmRegistryServer: https://git.v0l.io/api/packages/Kieran/npm/
yarnPath: .yarn/releases/yarn-3.6.3.cjs

695
LICENSE
View File

@ -1,674 +1,21 @@
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>.
MIT License
Copyright (c) 2023 Kieran (v0l)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -16,7 +16,7 @@ Snort supports the following NIP's:
- [x] NIP-10: Conventions for clients' use of `e` and `p` tags in text events
- [x] NIP-11: Relay Information Document
- [x] NIP-12: Generic Tag Queries
- [ ] NIP-13: Proof of Work
- [x] NIP-13: Proof of Work
- [ ] NIP-14: Subject tag in text events
- [x] NIP-15: End of Stored Events Notice
- [x] NIP-18: Reposts
@ -25,20 +25,25 @@ Snort supports the following NIP's:
- [x] NIP-21: `nostr:` Protocol handler (`web+nostr`)
- [x] NIP-25: Reactions
- [x] NIP-26: Delegated Event Signing (Display delegated signings only)
- [x] NIP-27: Text note references (Parsing only)
- [x] NIP-27: Text note references
- [ ] NIP-28: Public Chat
- [x] NIP-30: Custom Emoji
- [x] NIP-31: Alt tag for unknown events
- [x] NIP-36: Sensitive Content
- [ ] NIP-40: Expiration Timestamp
- [x] NIP-42: Authentication of clients to relays
- [x] NIP-44: Versioned encryption
- [x] NIP-46: Nostr connect (+bunker)
- [x] NIP-47: Nostr wallet connect
- [x] NIP-50: Search
- [x] NIP-51: Lists
- [x] NIP-53: Live Events
- [x] NIP-58: Badges
- [x] NIP-59: Gift Wrap
- [x] NIP-65: Relay List Metadata
- [ ] NIP-78: App specific data
- [x] NIP-102: Live Events
- [x] NIP-94: File header
- [x] NIP-98: HTTP Auth
### Running

View File

@ -18,9 +18,9 @@
"bracketSameLine": true,
"arrowParens": "avoid"
},
"packageManager": "yarn@3.6.1",
"packageManager": "yarn@3.6.3",
"dependencies": {
"eslint": "^8.44.0",
"typescript": "^5.1.6"
"eslint": "^8.48.0",
"typescript": "^5.2.2"
}
}

View File

@ -1,2 +1,2 @@
/*
Content-Security-Policy: default-src 'self'; manifest-src *; child-src 'none'; worker-src 'self'; frame-src youtube.com www.youtube.com https://platform.twitter.com https://embed.tidal.com https://w.soundcloud.com https://www.mixcloud.com https://open.spotify.com https://player.twitch.tv https://embed.music.apple.com https://nostrnests.com https://embed.wavlake.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; connect-src *; img-src * data: blob:; font-src https://fonts.gstatic.com; media-src * blob:; script-src 'self' 'wasm-unsafe-eval' https://static.cloudflareinsights.com https://platform.twitter.com https://embed.tidal.com;
Content-Security-Policy: default-src 'self'; manifest-src *; child-src 'none'; worker-src 'self'; frame-src youtube.com www.youtube.com https://platform.twitter.com https://embed.tidal.com https://w.soundcloud.com https://www.mixcloud.com https://open.spotify.com https://player.twitch.tv https://embed.music.apple.com https://nostrnests.com https://embed.wavlake.com; style-src 'self' 'unsafe-inline'; connect-src *; img-src * data: blob:; font-src 'self'; media-src * blob:; script-src 'self' 'wasm-unsafe-eval' https://analytics.v0l.io https://platform.twitter.com https://embed.tidal.com;

View File

@ -31,6 +31,6 @@ declare module "translations/*.json" {
}
declare module "emojilib" {
const value: Record<string, Array<string>>;
const value: Record<string, string>;
export default value;
}

View File

@ -12,6 +12,7 @@
"@scure/bip39": "^1.1.1",
"@snort/shared": "workspace:*",
"@snort/system": "workspace:*",
"@snort/system-query": "workspace:*",
"@snort/system-react": "workspace:*",
"@szhsin/react-menu": "^3.3.1",
"@void-cat/api": "^1.0.4",
@ -33,6 +34,7 @@
"use-long-press": "^2.0.3",
"uuid": "^9.0.0",
"workbox-core": "^6.4.2",
"workbox-precaching": "^7.0.0",
"workbox-routing": "^6.4.2",
"workbox-strategies": "^6.4.2"
},
@ -42,9 +44,7 @@
"test": "jest --runInBand",
"intl-extract": "formatjs extract 'src/**/*.ts*' --ignore='**/*.d.ts' --out-file src/lang.json --flatten true",
"intl-compile": "formatjs compile src/lang.json --out-file src/translations/en.json",
"format": "prettier --write .",
"eslint": "eslint .",
"prepare": "cd ../.. && husky install"
"eslint": "eslint ."
},
"eslintConfig": {
"extends": [
@ -70,9 +70,9 @@
"@babel/plugin-syntax-import-assertions": "^7.20.0",
"@babel/preset-env": "^7.21.5",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.22.5",
"@babel/runtime": "^7.22.6",
"@formatjs/cli": "^6.0.1",
"@formatjs/cli": "^6.1.3",
"@formatjs/ts-transformer": "^3.13.3",
"@jest/globals": "^29.6.1",
"@types/debug": "^4.1.8",
"@types/jest": "^29.5.1",
@ -87,34 +87,28 @@
"@webbtc/webln-types": "^1.0.10",
"@webpack-cli/generators": "^3.0.4",
"@webscopeio/react-textarea-autocomplete": "^4.9.2",
"babel-loader": "^9.1.2",
"babel-plugin-formatjs": "^10.5.1",
"babel-loader": "^9.1.3",
"copy-webpack-plugin": "^11.0.0",
"css-loader": "^6.7.3",
"css-minimizer-webpack-plugin": "^5.0.0",
"customize-cra": "^1.0.0",
"eslint": "^8.44.0",
"eslint-plugin-formatjs": "^4.10.1",
"eslint": "^8.48.0",
"eslint-webpack-plugin": "^4.0.1",
"html-webpack-plugin": "^5.5.1",
"husky": ">=6",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"lint-staged": ">=10",
"mini-css-extract-plugin": "^2.7.5",
"prettier": "2.8.3",
"prop-types": "^15.8.1",
"source-map-loader": "^4.0.1",
"terser-webpack-plugin": "^5.3.9",
"tinybench": "^2.5.0",
"ts-jest": "^29.1.0",
"typescript": "^5.1.6",
"webpack": "^5.82.1",
"ts-loader": "^9.4.4",
"typescript": "^5.2.2",
"webpack": "^5.88.2",
"webpack-bundle-analyzer": "^4.8.0",
"webpack-cli": "^5.1.1",
"webpack-dev-server": "^4.15.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"workbox-webpack-plugin": "^6.5.4"
},
"lint-staged": {
"*.{js,jsx,ts,tsx,css,md}": "prettier --write"
}
}

View File

@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Snort Benchmarks</title>
</head>
<body>
Check console
</body>
</html>

View File

@ -176,7 +176,7 @@
<path d="M22.1328 5.76872C22.3174 5.64092 22.4097 5.57702 22.4664 5.47424C22.5104 5.39443 22.5356 5.26804 22.5255 5.17745C22.5125 5.06079 22.463 4.98377 22.3638 4.82973C21.9839 4.23964 21.4373 3.75256 20.816 3.43598C20.3306 3.18868 19.8139 3.09012 19.2518 3.04419C18.7106 2.99998 18.0463 2.99999 17.2413 3H6.7587C5.95374 2.99999 5.28937 2.99998 4.74818 3.04419C4.18608 3.09012 3.66937 3.18868 3.18404 3.43598C2.62501 3.72082 2.1418 4.1326 1.77436 4.63335C1.65877 4.79089 1.60097 4.86966 1.58192 4.98921C1.56703 5.08269 1.58783 5.21257 1.63116 5.29674C1.68657 5.40436 1.78269 5.47302 1.97493 5.61033L10.75 11.8783C11.4773 12.3977 11.6316 12.4881 11.7681 12.5233C11.9272 12.5644 12.0939 12.5656 12.2535 12.5269C12.3906 12.4937 12.5463 12.4056 13.281 11.8969L22.1328 5.76872Z" fill="currentColor"/>
</g>
</symbol>
<symbol id="bell-v2" viewBox="0 0 24 24" fill="none">
<symbol id="bell-02" viewBox="0 0 24 24" fill="none">
<g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.99974 21C8.99974 20.4477 9.44745 20 9.99974 20H13.9997C14.552 20 14.9997 20.4477 14.9997 21C14.9997 21.5523 14.552 22 13.9997 22H9.99974C9.44745 22 8.99974 21.5523 8.99974 21Z" fill="currentColor"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.04999 3.05025C8.36275 1.7375 10.1432 1 11.9997 1C13.8563 1 15.6367 1.7375 16.9495 3.05025C18.2622 4.36301 18.9997 6.14349 18.9997 8C18.9997 10.9127 19.7317 12.8439 20.4991 14.0771L20.511 14.0962C20.8683 14.6704 21.1507 15.1243 21.3411 15.4547C21.4366 15.6202 21.5235 15.7797 21.5879 15.9215C21.62 15.9922 21.6559 16.079 21.684 16.1733C21.7073 16.2515 21.7517 16.4187 21.7351 16.6223C21.7239 16.7591 21.696 16.9928 21.5618 17.2343C21.4277 17.4758 21.244 17.623 21.1337 17.7047C20.8834 17.8904 20.596 17.9329 20.5001 17.947L20.4957 17.9477C20.3482 17.9695 20.181 17.9804 20.0122 17.9869C19.677 18 19.2128 18 18.6356 18H5.36388C4.78666 18 4.32252 18 3.98726 17.9869C3.81851 17.9804 3.65123 17.9695 3.50382 17.9477L3.49939 17.947C3.40347 17.9329 3.11604 17.8904 2.86574 17.7047C2.7555 17.623 2.57178 17.4758 2.43762 17.2343C2.30347 16.9928 2.27558 16.7591 2.26439 16.6223C2.24774 16.4187 2.29214 16.2515 2.31545 16.1733C2.34354 16.079 2.37948 15.9922 2.41161 15.9215C2.47598 15.7797 2.56291 15.6202 2.65833 15.4547C2.84876 15.1243 3.13124 14.6703 3.48856 14.0961L3.50035 14.0771C4.26773 12.8439 4.99974 10.9127 4.99974 8C4.99974 6.14348 5.73724 4.36301 7.04999 3.05025Z" fill="currentColor"/>
@ -296,6 +296,34 @@
<path d="M20 2C20 1.44772 19.5523 1 19 1C18.4477 1 18 1.44772 18 2V4H16C15.4477 4 15 4.44772 15 5C15 5.55228 15.4477 6 16 6H18V8C18 8.55228 18.4477 9 19 9C19.5523 9 20 8.55228 20 8V6H22C22.5523 6 23 5.55228 23 5C23 4.44772 22.5523 4 22 4H20V2Z" fill="currentColor"/>
</g>
</symbol>
<symbol id="grid-01" viewBox="0 0 24 24" fill="none">
<g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.56811 2C5.85605 2.00016 7.1465 2.00016 8.4319 2C8.68429 1.99997 8.93008 1.99994 9.13824 2.01695C9.36683 2.03563 9.63656 2.07969 9.90799 2.21799C10.2843 2.40974 10.5903 2.7157 10.782 3.09202C10.9203 3.36345 10.9644 3.63318 10.9831 3.86178C11.0001 4.06994 11 4.31574 11 4.56813V8.43189C11 8.68427 11.0001 8.93007 10.9831 9.13824C10.9644 9.36683 10.9203 9.63656 10.782 9.90799C10.5903 10.2843 10.2843 10.5903 9.90799 10.782C9.63656 10.9203 9.36683 10.9644 9.13824 10.9831C8.93007 11.0001 8.68427 11 8.43189 11H4.56812C4.31574 11 4.06994 11.0001 3.86178 10.9831C3.63318 10.9644 3.36345 10.9203 3.09202 10.782C2.7157 10.5903 2.40974 10.2843 2.21799 9.90799C2.07969 9.63656 2.03563 9.36683 2.01695 9.13824C1.99994 8.93008 1.99997 8.68429 2 8.4319C2 8.42128 2.00001 8.41065 2.00001 8.40001V4.60001C2.00001 4.58936 2 4.57873 2 4.56811C1.99997 4.31572 1.99994 4.06993 2.01695 3.86178C2.03563 3.63318 2.07969 3.36345 2.21799 3.09202C2.40974 2.7157 2.7157 2.40974 3.09202 2.21799C3.36345 2.07969 3.63318 2.03563 3.86178 2.01695C4.06993 1.99994 4.31572 1.99997 4.56811 2Z" fill="currentColor"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.56811 13C5.85605 13.0002 7.1465 13.0002 8.4319 13C8.68429 13 8.93008 12.9999 9.13824 13.017C9.36683 13.0356 9.63656 13.0797 9.90799 13.218C10.2843 13.4097 10.5903 13.7157 10.782 14.092C10.9203 14.3634 10.9644 14.6332 10.9831 14.8618C11.0001 15.0699 11 15.3157 11 15.5681V19.4319C11 19.6843 11.0001 19.9301 10.9831 20.1382C10.9644 20.3668 10.9203 20.6366 10.782 20.908C10.5903 21.2843 10.2843 21.5903 9.90799 21.782C9.63656 21.9203 9.36683 21.9644 9.13824 21.9831C8.93007 22.0001 8.68427 22 8.43189 22H4.56812C4.31574 22 4.06994 22.0001 3.86178 21.9831C3.63318 21.9644 3.36345 21.9203 3.09202 21.782C2.7157 21.5903 2.40974 21.2843 2.21799 20.908C2.07969 20.6366 2.03563 20.3668 2.01695 20.1382C1.99994 19.9301 1.99997 19.6843 2 19.4319C2 19.4213 2.00001 19.4106 2.00001 19.4V15.6C2.00001 15.5894 2 15.5787 2 15.5681C1.99997 15.3157 1.99994 15.0699 2.01695 14.8618C2.03563 14.6332 2.07969 14.3634 2.21799 14.092C2.40974 13.7157 2.7157 13.4097 3.09202 13.218C3.36345 13.0797 3.63318 13.0356 3.86178 13.017C4.06993 12.9999 4.31572 13 4.56811 13Z" fill="currentColor"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M15.5681 2C16.856 2.00016 18.1465 2.00016 19.4319 2C19.6843 1.99997 19.9301 1.99994 20.1382 2.01695C20.3668 2.03563 20.6366 2.07969 20.908 2.21799C21.2843 2.40974 21.5903 2.7157 21.782 3.09202C21.9203 3.36345 21.9644 3.63318 21.9831 3.86178C22.0001 4.06994 22 4.31574 22 4.56813V8.43189C22 8.68427 22.0001 8.93007 21.9831 9.13824C21.9644 9.36683 21.9203 9.63656 21.782 9.90799C21.5903 10.2843 21.2843 10.5903 20.908 10.782C20.6366 10.9203 20.3668 10.9644 20.1382 10.9831C19.9301 11.0001 19.6843 11 19.4319 11H15.5681C15.3157 11 15.0699 11.0001 14.8618 10.9831C14.6332 10.9644 14.3634 10.9203 14.092 10.782C13.7157 10.5903 13.4097 10.2843 13.218 9.90799C13.0797 9.63656 13.0356 9.36683 13.017 9.13824C12.9999 8.93008 13 8.68429 13 8.4319C13 8.42128 13 8.41065 13 8.40001V4.60001C13 4.58936 13 4.57873 13 4.56811C13 4.31572 12.9999 4.06993 13.017 3.86178C13.0356 3.63318 13.0797 3.36345 13.218 3.09202C13.4097 2.7157 13.7157 2.40974 14.092 2.21799C14.3634 2.07969 14.6332 2.03563 14.8618 2.01695C15.0699 1.99994 15.3157 1.99997 15.5681 2Z" fill="currentColor"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M15.5681 13C16.856 13.0002 18.1465 13.0002 19.4319 13C19.6843 13 19.9301 12.9999 20.1382 13.017C20.3668 13.0356 20.6366 13.0797 20.908 13.218C21.2843 13.4097 21.5903 13.7157 21.782 14.092C21.9203 14.3634 21.9644 14.6332 21.9831 14.8618C22.0001 15.0699 22 15.3157 22 15.5681V19.4319C22 19.6843 22.0001 19.9301 21.9831 20.1382C21.9644 20.3668 21.9203 20.6366 21.782 20.908C21.5903 21.2843 21.2843 21.5903 20.908 21.782C20.6366 21.9203 20.3668 21.9644 20.1382 21.9831C19.9301 22.0001 19.6843 22 19.4319 22H15.5681C15.3157 22 15.0699 22.0001 14.8618 21.9831C14.6332 21.9644 14.3634 21.9203 14.092 21.782C13.7157 21.5903 13.4097 21.2843 13.218 20.908C13.0797 20.6366 13.0356 20.3668 13.017 20.1382C12.9999 19.9301 13 19.6843 13 19.4319C13 19.4213 13 19.4106 13 19.4V15.6C13 15.5894 13 15.5787 13 15.5681C13 15.3157 12.9999 15.0699 13.017 14.8618C13.0356 14.6332 13.0797 14.3634 13.218 14.092C13.4097 13.7157 13.7157 13.4097 14.092 13.218C14.3634 13.0797 14.6332 13.0356 14.8618 13.017C15.0699 12.9999 15.3157 13 15.5681 13Z" fill="currentColor"/>
</g>
</symbol>
<symbol id="settings-02" viewBox="0 0 24 24" fill="none">
<g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.74225 21.5541L9.08973 20.1082C8.85724 19.5922 8.4646 19.1621 7.9683 18.8799C7.47171 18.5977 6.89723 18.4774 6.32708 18.5364L4.73053 18.7039C4.25532 18.7531 3.77581 18.6656 3.35002 18.4519C2.92423 18.2383 2.57041 17.9076 2.33135 17.5C2.09223 17.0924 1.97831 16.6252 2.00341 16.1551C2.02851 15.6849 2.19156 15.2321 2.47277 14.8514L3.41805 13.5718C3.75516 13.115 3.9367 12.5648 3.93659 12C3.9367 11.4352 3.75516 10.885 3.41805 10.4282L2.47277 9.14855C2.19156 8.76793 2.02851 8.31508 2.00341 7.84494C1.97831 7.3748 2.09223 6.90759 2.33135 6.5C2.57017 6.09216 2.92395 5.76134 3.3498 5.54765C3.77565 5.33396 4.25528 5.24658 4.73053 5.29611L6.33205 5.46356C6.90219 5.52255 7.47667 5.40233 7.97326 5.12011C8.46771 4.83708 8.85854 4.40709 9.08973 3.89178L9.74225 2.44589C9.93622 2.01549 10.2528 1.64979 10.6535 1.39314C11.0543 1.13649 11.522 0.999923 12 1C12.478 0.999923 12.9457 1.13649 13.3465 1.39314C13.7472 1.64979 14.0638 2.01549 14.2578 2.44589L14.9152 3.89178C15.1464 4.40709 15.5372 4.83708 16.0317 5.12011C16.5283 5.40233 17.1028 5.52255 17.6729 5.46356L19.2695 5.29611C19.7447 5.24658 20.2243 5.33396 20.6502 5.54765C21.076 5.76134 21.4298 6.09216 21.6686 6.5C21.9078 6.90759 22.0217 7.3748 21.9966 7.84494C21.9715 8.31508 21.8084 8.76793 21.5272 9.14855L20.5819 10.4282C20.2448 10.885 20.0633 11.4352 20.0634 12C20.0605 12.5663 20.2404 13.1188 20.577 13.5779L21.5223 14.8576C21.8035 15.2382 21.9665 15.691 21.9916 16.1612C22.0167 16.6313 21.9028 17.0985 21.6637 17.5061C21.4249 17.914 21.0711 18.2448 20.6452 18.4585C20.2194 18.6722 19.7398 18.7595 19.2645 18.71L17.668 18.5426C17.0978 18.4836 16.5233 18.6038 16.0267 18.886C15.5333 19.1674 15.1425 19.5952 14.9103 20.1082L14.2578 21.5541C14.0638 21.9845 13.7472 22.3502 13.3465 22.6069C12.9457 22.8635 12.478 23.0001 12 23C11.522 23.0001 11.0543 22.8635 10.6535 22.6069C10.2528 22.3502 9.93622 21.9845 9.74225 21.5541ZM15 12C15 13.6569 13.6569 15 12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12Z" fill="currentColor"/>
</g>
</symbol>
<symbol id="rows-01" viewBox="0 0 24 24" fill="none">
<g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M22 17.1615V17.8385C22 18.3657 22 18.8205 21.9694 19.195C21.9371 19.5904 21.8658 19.9836 21.673 20.362C21.3854 20.9265 20.9265 21.3854 20.362 21.673C19.9836 21.8658 19.5904 21.9371 19.195 21.9694C18.8205 22 18.3657 22 17.8385 22H6.16148C5.63432 22 5.17955 22 4.80497 21.9694C4.40963 21.9371 4.01641 21.8658 3.63803 21.673C3.07354 21.3854 2.6146 20.9265 2.32698 20.362C2.13419 19.9836 2.06287 19.5904 2.03057 19.195C1.99997 18.8205 1.99998 18.3657 2 17.8386L2 17.1614C1.99998 16.6343 1.99997 16.1795 2.03057 15.805C2.06287 15.4096 2.13419 15.0164 2.32698 14.638C2.6146 14.0735 3.07354 13.6146 3.63803 13.327C4.01641 13.1342 4.40963 13.0629 4.80497 13.0306C5.17955 13 5.63431 13 6.16146 13L17.8385 13C18.3657 13 18.8205 13 19.195 13.0306C19.5904 13.0629 19.9836 13.1342 20.362 13.327C20.9265 13.6146 21.3854 14.0735 21.673 14.638C21.8658 15.0164 21.9371 15.4096 21.9694 15.805C22 16.1795 22 16.6343 22 17.1615Z" fill="currentColor"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M22 6.16146V6.83855C22 7.36569 22 7.82046 21.9694 8.19503C21.9371 8.59038 21.8658 8.98359 21.673 9.36197C21.3854 9.92646 20.9265 10.3854 20.362 10.673C19.9836 10.8658 19.5904 10.9371 19.195 10.9694C18.8205 11 18.3657 11 17.8385 11L6.16148 11C5.63432 11 5.17955 11 4.80497 10.9694C4.40963 10.9371 4.01641 10.8658 3.63803 10.673C3.07354 10.3854 2.6146 9.92646 2.32698 9.36197C2.13419 8.98359 2.06287 8.59037 2.03057 8.19503C1.99997 7.82046 1.99998 7.36571 2 6.83857L2 6.16144C1.99998 5.6343 1.99997 5.17954 2.03057 4.80497C2.06287 4.40963 2.13419 4.01641 2.32698 3.63803C2.6146 3.07354 3.07354 2.6146 3.63803 2.32698C4.01641 2.13419 4.40963 2.06287 4.80497 2.03057C5.17955 1.99997 5.63431 1.99998 6.16146 2L17.8385 2C18.3657 1.99998 18.8205 1.99997 19.195 2.03057C19.5904 2.06287 19.9836 2.13419 20.362 2.32698C20.9265 2.6146 21.3854 3.07354 21.673 3.63803C21.8658 4.01641 21.9371 4.40963 21.9694 4.80497C22 5.17955 22 5.63431 22 6.16146Z" fill="currentColor"/>
</g>
</symbol>
<symbol id="camera-lens" viewBox="0 0 24 24" fill="none">
<g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.7782 4.22183C24.0739 8.5176 24.0739 15.4824 19.7782 19.7782C15.4824 24.0739 8.51757 24.0739 4.22183 19.7782C-0.073941 15.4824 -0.0739439 8.51757 4.22183 4.22183C8.5176 -0.0739412 15.4824 -0.0739441 19.7782 4.22183ZM18.3639 5.63604C16.9457 4.21783 15.172 3.37188 13.3296 3.09818C15.1903 4.84851 16.3469 7.26042 16.5131 9.84459C16.7413 10.3224 16.8892 10.8289 16.957 11.344C18.1231 9.82019 18.7436 7.89858 18.6289 5.91225C18.5429 5.81878 18.4546 5.72668 18.3639 5.63604ZM13.9108 7.37813C13.1743 5.60658 11.8204 4.10837 10.0429 3.21421C8.42788 3.57237 6.89244 4.37965 5.63604 5.63604C5.39169 5.88039 5.16433 6.13529 4.95396 6.39928C7.40123 5.66183 10.0699 5.86592 12.3924 7.01533C12.9104 7.05586 13.4233 7.17679 13.9108 7.37813ZM8.95317 8.03485C7.04977 7.78701 5.07457 8.21117 3.4111 9.30482C2.79889 11.2616 2.87046 13.3861 3.62582 15.3036C4.21048 12.8157 5.72136 10.6067 7.87702 9.16982C8.04787 8.92153 8.24369 8.68524 8.46446 8.46446C8.62007 8.30886 8.78338 8.16566 8.95317 8.03485ZM7.04296 12.656C5.87684 14.1797 5.25622 16.1012 5.37085 18.0874C5.4569 18.181 5.5453 18.2732 5.63604 18.3639C7.05418 19.7821 8.82785 20.628 10.6701 20.9018C8.80942 19.1513 7.65282 16.7393 7.48676 14.1551C7.25866 13.6774 7.11073 13.1709 7.04296 12.656ZM10.089 16.6218C10.8255 18.3934 12.1794 19.8916 13.9569 20.7858C15.572 20.4277 17.1075 19.6204 18.3639 18.3639C18.6084 18.1195 18.8358 17.8646 19.0462 17.6005C16.599 18.338 13.9303 18.134 11.6079 16.9847C11.0897 16.9442 10.5766 16.8232 10.089 16.6218ZM15.047 15.965C15.2167 15.8343 15.38 15.6911 15.5355 15.5355C15.7563 15.3148 15.952 15.0786 16.1228 14.8304C18.2786 13.3934 19.7895 11.1842 20.3741 8.69606C21.1295 10.6136 21.2011 12.7381 20.589 14.6949C18.9255 15.7886 16.9504 16.2128 15.047 15.965Z" fill="currentColor"/>
</g>
</symbol>
<symbol id="file-06" viewBox="0 0 24 24" fill="none">
<g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13 2.01558C13 1.98928 13 1.97612 12.9989 1.95227C12.9753 1.4585 12.541 1.02448 12.0473 1.00112C12.0234 0.999992 12.0156 0.999995 12 1H12H8.75866H8.75862C7.95369 0.99999 7.28935 0.999981 6.74818 1.0442C6.18608 1.09012 5.66938 1.18869 5.18404 1.43598C4.43139 1.81947 3.81947 2.43139 3.43598 3.18404C3.18869 3.66938 3.09012 4.18608 3.0442 4.74818C2.99998 5.28936 2.99999 5.95372 3 6.75867V6.75869V17.2413V17.2413C2.99999 18.0463 2.99998 18.7106 3.0442 19.2518C3.09012 19.8139 3.18869 20.3306 3.43598 20.816C3.81947 21.5686 4.43139 22.1805 5.18404 22.564C5.66938 22.8113 6.18608 22.9099 6.74818 22.9558C7.28937 23 7.95372 23 8.75868 23H15.2413C16.0463 23 16.7106 23 17.2518 22.9558C17.8139 22.9099 18.3306 22.8113 18.816 22.564C19.5686 22.1805 20.1805 21.5686 20.564 20.816C20.8113 20.3306 20.9099 19.8139 20.9558 19.2518C21 18.7106 21 18.0463 21 17.2413V9.99994C21 9.98441 21 9.97664 20.9989 9.95282C20.9756 9.45899 20.5415 9.02471 20.0477 9.00115C20.0238 9.00001 20.0107 9.00001 19.9845 9.00001L15.5681 9.00001C15.3157 9.00004 15.0699 9.00007 14.8618 8.98307C14.6332 8.96439 14.3634 8.92032 14.092 8.78202C13.7157 8.59028 13.4097 8.28432 13.218 7.90799C13.0797 7.63657 13.0356 7.36683 13.017 7.13824C12.9999 6.93008 13 6.68429 13 6.43191L13 2.01558ZM18.908 6.99999C19.2016 7 19.3484 7 19.4686 6.92627C19.6385 6.82215 19.74 6.57684 19.6935 6.38313C19.6605 6.24598 19.5648 6.15033 19.3733 5.95904L16.041 2.62672C15.8497 2.43523 15.754 2.33949 15.6169 2.30652C15.4232 2.25996 15.1779 2.3615 15.0737 2.53134C15 2.65161 15 2.79842 15 3.09204L15 6.19996C15 6.47998 15 6.61999 15.0545 6.72694C15.1024 6.82102 15.1789 6.89751 15.273 6.94545C15.38 6.99995 15.52 6.99995 15.8 6.99995L18.908 6.99999ZM8 9C7.44772 9 7 9.44772 7 10C7 10.5523 7.44772 11 8 11H10C10.5523 11 11 10.5523 11 10C11 9.44772 10.5523 9 10 9H8ZM7 14C7 13.4477 7.44772 13 8 13H16C16.5523 13 17 13.4477 17 14C17 14.5523 16.5523 15 16 15H8C7.44772 15 7 14.5523 7 14ZM7 18C7 17.4477 7.44772 17 8 17H16C16.5523 17 17 17.4477 17 18C17 18.5523 16.5523 19 16 19H8C7.44772 19 7 18.5523 7 18Z" fill="currentColor"/>
</g>
</symbol>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 88 KiB

View File

@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
@ -8,10 +8,7 @@
<meta
name="keywords"
content="nostr snort fast decentralized social media censorship resistant open source software" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://imgproxy.snort.social" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
<link rel="apple-touch-icon" href="/nostrich_512.png" />
<link rel="manifest" href="/manifest.json" />
<title>Snort - Nostr</title>

View File

@ -0,0 +1,126 @@
import debug from "debug";
import { EventKind, RequestBuilder, SystemInterface, TaggedNostrEvent } from "@snort/system";
import { unixNow, unixNowMs } from "@snort/shared";
import { db } from "Db";
import { RefreshFeedCache, TWithCreated } from "./RefreshFeedCache";
import { LoginSession } from "Login";
import { Day, Hour } from "Const";
const WindowSize = Hour * 6;
const MaxCacheWindow = Day * 7;
export class FollowsFeedCache extends RefreshFeedCache<TaggedNostrEvent> {
#kinds = [EventKind.TextNote, EventKind.Repost, EventKind.Polls];
#oldest?: number;
constructor() {
super("FollowsFeedCache", db.followsFeed);
}
key(of: TWithCreated<TaggedNostrEvent>): string {
return of.id;
}
takeSnapshot(): TWithCreated<TaggedNostrEvent>[] {
return [...this.cache.values()];
}
buildSub(session: LoginSession, rb: RequestBuilder): void {
const since = this.newest();
rb.withFilter()
.kinds(this.#kinds)
.authors(session.follows.item)
.since(since === 0 ? unixNow() - WindowSize : since);
}
async onEvent(evs: readonly TaggedNostrEvent[]): Promise<void> {
const filtered = evs.filter(a => this.#kinds.includes(a.kind));
if (filtered.length > 0) {
await this.bulkSet(filtered);
this.notifyChange(filtered.map(a => this.key(a)));
}
}
override async preload() {
const start = unixNowMs();
const keys = (await this.table?.toCollection().primaryKeys()) ?? [];
this.onTable = new Set<string>(keys.map(a => a as string));
// load only latest 10 posts, rest can be loaded on-demand
const latest = await this.table?.orderBy("created_at").reverse().limit(50).toArray();
latest?.forEach(v => this.cache.set(this.key(v), v));
// cleanup older than 7 days
await this.table
?.where("created_at")
.below(unixNow() - MaxCacheWindow)
.delete();
const oldest = await this.table?.orderBy("created_at").first();
this.#oldest = oldest?.created_at;
this.notifyChange(latest?.map(a => this.key(a)) ?? []);
debug(this.name)(`Loaded %d/%d in %d ms`, latest?.length ?? 0, keys.length, (unixNowMs() - start).toLocaleString());
}
async loadMore(system: SystemInterface, session: LoginSession, before: number) {
if (this.#oldest && before <= this.#oldest) {
const rb = new RequestBuilder(`${this.name}-loadmore`);
rb.withFilter()
.kinds(this.#kinds)
.authors(session.follows.item)
.until(before)
.since(before - WindowSize);
await system.Fetch(rb, async evs => {
await this.bulkSet(evs);
});
} else {
const latest = await this.table
?.where("created_at")
.between(before - WindowSize, before)
.reverse()
.sortBy("created_at");
latest?.forEach(v => {
const k = this.key(v);
this.cache.set(k, v);
this.onTable.add(k);
});
this.notifyChange(latest?.map(a => this.key(a)) ?? []);
}
}
/**
* Backfill cache with new follows
*/
async backFill(system: SystemInterface, keys: Array<string>) {
if (keys.length === 0) return;
const rb = new RequestBuilder(`${this.name}-backfill`);
rb.withFilter()
.kinds(this.#kinds)
.authors(keys)
.until(unixNow())
.since(this.#oldest ?? unixNow() - MaxCacheWindow);
await system.Fetch(rb, async evs => {
await this.bulkSet(evs);
});
}
/**
* Backfill cache based on follows list
*/
async backFillIfMissing(system: SystemInterface, keys: Array<string>) {
if (!this.#oldest) return;
const start = unixNowMs();
const everything = await this.table?.toArray();
if ((everything?.length ?? 0) > 0) {
const allKeys = new Set(everything?.map(a => a.pubkey));
const missingKeys = keys.filter(a => !allKeys.has(a));
await this.backFill(system, missingKeys);
debug(this.name)(`Backfilled %d keys in %d ms`, missingKeys.length, (unixNowMs() - start).toLocaleString());
}
}
}

View File

@ -1,9 +1,10 @@
import { FeedCache } from "@snort/shared";
import { EventKind, EventPublisher, TaggedNostrEvent } from "@snort/system";
import { EventKind, EventPublisher, RequestBuilder, TaggedNostrEvent } from "@snort/system";
import { UnwrappedGift, db } from "Db";
import { findTag, unwrap } from "SnortUtils";
import { RefreshFeedCache } from "./RefreshFeedCache";
import { LoginSession } from "Login";
export class GiftWrapCache extends FeedCache<UnwrappedGift> {
export class GiftWrapCache extends RefreshFeedCache<UnwrappedGift> {
constructor() {
super("GiftWrapCache", db.gifts);
}
@ -12,22 +13,18 @@ export class GiftWrapCache extends FeedCache<UnwrappedGift> {
return of.id;
}
override async preload(): Promise<void> {
await super.preload();
await this.buffer([...this.onTable]);
}
newest(): number {
let ret = 0;
this.cache.forEach(v => (ret = v.created_at > ret ? v.created_at : ret));
return ret;
buildSub(session: LoginSession, rb: RequestBuilder): void {
const pubkey = session.publicKey;
if (pubkey) {
rb.withFilter().kinds([EventKind.GiftWrap]).tag("p", [pubkey]).since(this.newest());
}
}
takeSnapshot(): Array<UnwrappedGift> {
return [...this.cache.values()];
}
async onEvent(evs: Array<TaggedNostrEvent>, pub: EventPublisher) {
override async onEvent(evs: Array<TaggedNostrEvent>, pub: EventPublisher) {
const unwrapped = (
await Promise.all(
evs.map(async v => {
@ -41,7 +38,7 @@ export class GiftWrapCache extends FeedCache<UnwrappedGift> {
} catch (e) {
console.debug(e, v);
}
})
}),
)
)
.filter(a => a !== undefined)

View File

@ -1,8 +1,9 @@
import { EventKind, NostrEvent, RequestBuilder, TaggedRawEvent } from "@snort/system";
import { EventKind, NostrEvent, RequestBuilder, TaggedNostrEvent } from "@snort/system";
import { RefreshFeedCache, TWithCreated } from "./RefreshFeedCache";
import { LoginSession } from "Login";
import { unixNow } from "SnortUtils";
import { db } from "Db";
import { Day } from "Const";
import { unixNow } from "@snort/shared";
export class NotificationsCache extends RefreshFeedCache<NostrEvent> {
#kinds = [EventKind.TextNote, EventKind.Reaction, EventKind.Repost, EventKind.ZapReceipt];
@ -17,11 +18,11 @@ export class NotificationsCache extends RefreshFeedCache<NostrEvent> {
rb.withFilter()
.kinds(this.#kinds)
.tag("p", [session.publicKey])
.since(newest === 0 ? unixNow() - 60 * 60 * 24 * 30 : newest);
.since(newest === 0 ? unixNow() - Day * 30 : newest);
}
}
async onEvent(evs: readonly TaggedRawEvent[]) {
async onEvent(evs: readonly TaggedNostrEvent[]) {
const filtered = evs.filter(a => this.#kinds.includes(a.kind) && a.tags.some(b => b[0] === "p"));
if (filtered.length > 0) {
await this.bulkSet(filtered);

View File

@ -1,12 +1,12 @@
import { FeedCache } from "@snort/shared";
import { RequestBuilder, TaggedRawEvent } from "@snort/system";
import { EventPublisher, RequestBuilder, TaggedNostrEvent } from "@snort/system";
import { LoginSession } from "Login";
export type TWithCreated<T> = T & { created_at: number };
export type TWithCreated<T> = (T | Readonly<T>) & { created_at: number };
export abstract class RefreshFeedCache<T> extends FeedCache<TWithCreated<T>> {
abstract buildSub(session: LoginSession, rb: RequestBuilder): void;
abstract onEvent(evs: Readonly<Array<TaggedRawEvent>>): void;
abstract onEvent(evs: Readonly<Array<TaggedNostrEvent>>, pub: EventPublisher): void;
/**
* Get latest event

View File

@ -4,6 +4,7 @@ import { ChatCache } from "./ChatCache";
import { Payments } from "./PaymentsCache";
import { GiftWrapCache } from "./GiftWrapCache";
import { NotificationsCache } from "./Notifications";
import { FollowsFeedCache } from "./FollowsFeed";
export const UserCache = new UserProfileCache();
export const UserRelays = new UserRelaysCache();
@ -13,6 +14,7 @@ export const PaymentsCache = new Payments();
export const InteractionCache = new EventInteractionCache();
export const GiftsCache = new GiftWrapCache();
export const Notifications = new NotificationsCache();
export const FollowsFeed = new FollowsFeedCache();
export async function preload(follows?: Array<string>) {
const preloads = [
@ -23,6 +25,7 @@ export async function preload(follows?: Array<string>) {
RelayMetrics.preload(),
GiftsCache.preload(),
Notifications.preload(),
FollowsFeed.preload(),
];
await Promise.all(preloads);
}

View File

@ -1,5 +1,15 @@
import { RelaySettings } from "@snort/system";
/**
* 1 Hour in seconds
*/
export const Hour = 60 * 60;
/**
* 1 Day in seconds
*/
export const Day = Hour * 24;
/**
* Add-on api for snort features
*/

View File

@ -1,8 +1,8 @@
import Dexie, { Table } from "dexie";
import { HexKey, NostrEvent, u256 } from "@snort/system";
import { HexKey, NostrEvent, TaggedNostrEvent, u256 } from "@snort/system";
export const NAME = "snortDB";
export const VERSION = 13;
export const VERSION = 14;
export interface SubCache {
id: string;
@ -41,6 +41,7 @@ const STORES = {
payments: "++url",
gifts: "++id",
notifications: "++id",
followsFeed: "++id, created_at, kind",
};
export class SnortDB extends Dexie {
@ -50,6 +51,7 @@ export class SnortDB extends Dexie {
payments!: Table<Payment>;
gifts!: Table<UnwrappedGift>;
notifications!: Table<NostrEvent>;
followsFeed!: Table<TaggedNostrEvent>;
constructor() {
super(NAME);

View File

@ -18,3 +18,14 @@
.avatar[data-domain="strike.army"] {
background-image: var(--img-url), var(--strike-army-gradient);
}
.avatar .overlay {
color: white;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.4);
}

View File

@ -1,6 +1,6 @@
import "./Avatar.css";
import { CSSProperties, useEffect, useState } from "react";
import { CSSProperties, ReactNode, useEffect, useState } from "react";
import type { UserMetadata } from "@snort/system";
import useImgProxy from "Hooks/useImgProxy";
@ -13,8 +13,9 @@ interface AvatarProps {
onClick?: () => void;
size?: number;
image?: string;
imageOverlay?: ReactNode;
}
const Avatar = ({ pubkey, user, size, onClick, image }: AvatarProps) => {
const Avatar = ({ pubkey, user, size, onClick, image, imageOverlay }: AvatarProps) => {
const [url, setUrl] = useState("");
const { proxy } = useImgProxy();
@ -35,9 +36,11 @@ const Avatar = ({ pubkey, user, size, onClick, image }: AvatarProps) => {
<div
onClick={onClick}
style={style}
className="avatar"
className={`avatar${imageOverlay ? " with-overlay" : ""}`}
data-domain={domain?.toLowerCase()}
title={getDisplayName(user, "")}></div>
title={getDisplayName(user, "")}>
{imageOverlay && <div className="overlay">{imageOverlay}</div>}
</div>
);
};

View File

@ -26,7 +26,7 @@ export default function CashuNuts({ token }: { token: string }) {
e.stopPropagation();
const lnurl = profile?.lud16 ?? "";
const url = `https://redeem.cashu.me?token=${encodeURIComponent(token)}&lightning=${encodeURIComponent(
lnurl
lnurl,
)}&autopay=yes`;
window.open(url, "_blank");
}

View File

@ -1,14 +1,5 @@
.copy {
cursor: pointer;
align-items: center;
}
.copy .body {
.copy .copy-body {
font-size: var(--font-size-small);
color: var(--font-color);
margin-right: 6px;
}
.copy .icon {
margin-bottom: -4px;
}

View File

@ -13,8 +13,8 @@ export default function Copy({ text, maxSize = 32, className }: CopyProps) {
const trimmed = text.length > maxSize ? `${text.slice(0, sliceLength)}...${text.slice(-sliceLength)}` : text;
return (
<div className={`flex flex-row copy ${className}`} onClick={() => copy(text)}>
<span className="body">{trimmed}</span>
<div className={`copy flex pointer g8${className ? ` ${className}` : ""}`} onClick={() => copy(text)}>
<span className="copy-body">{trimmed}</span>
<span className="icon" style={{ color: copied ? "var(--success)" : "var(--highlight)" }}>
{copied ? <Icon name="check" size={14} /> : <Icon name="copy-solid" size={14} />}
</span>

View File

@ -1,6 +1,6 @@
import "./DM.css";
import { useEffect, useState } from "react";
import { useIntl } from "react-intl";
import { FormattedMessage, useIntl } from "react-intl";
import { useInView } from "react-intersection-observer";
import useEventPublisher from "Feed/EventPublisher";
@ -8,9 +8,9 @@ import NoteTime from "Element/NoteTime";
import Text from "Element/Text";
import useLogin from "Hooks/useLogin";
import { Chat, ChatMessage, ChatType, setLastReadIn } from "chat";
import ProfileImage from "./ProfileImage";
import messages from "./messages";
import ProfileImage from "./ProfileImage";
export interface DMProps {
chat: Chat;
@ -21,9 +21,8 @@ export default function DM(props: DMProps) {
const pubKey = useLogin().publicKey;
const publisher = useEventPublisher();
const msg = props.data;
const [content, setContent] = useState(msg.needsDecryption ? "Loading..." : msg.content);
const [decrypted, setDecrypted] = useState(false);
const { ref, inView } = useInView();
const [content, setContent] = useState<string>();
const { ref, inView } = useInView({ triggerOnce: true });
const { formatMessage } = useIntl();
const isMe = msg.from === pubKey;
const otherPubkey = isMe ? pubKey : msg.from;
@ -46,17 +45,24 @@ export default function DM(props: DMProps) {
}
useEffect(() => {
if (!decrypted && inView && msg.needsDecryption) {
setDecrypted(true);
decrypt().catch(console.error);
if (inView) {
if (msg.needsDecryption) {
decrypt().catch(console.error);
} else {
setContent(msg.content);
}
}
}, [inView, msg]);
}, [inView]);
return (
<div className={isMe ? "dm me" : "dm other"} ref={ref}>
<div>
{sender()}
<Text content={content} tags={[]} creator={otherPubkey} />
{content ? (
<Text id={msg.id} content={content} tags={[]} creator={otherPubkey} />
) : (
<FormattedMessage defaultMessage="Loading..." />
)}
</div>
<div>
<NoteTime from={msg.created_at * 1000} fallback={formatMessage(messages.JustNow)} />

View File

@ -0,0 +1,14 @@
import { useArticles } from "Feed/ArticlesFeed";
import { orderDescending } from "SnortUtils";
import Note from "../Note";
export default function Articles() {
const data = useArticles();
return (
<>
{orderDescending(data.data ?? []).map(a => (
<Note data={a} key={a.id} related={[]} />
))}
</>
);
}

View File

@ -0,0 +1,12 @@
nav.deck {
width: 48px;
height: calc(100vh - 20px);
padding: 10px 8px;
border-right: 1px solid var(--border-color);
text-align: center;
}
nav.deck .avatar {
width: 40px;
height: 40px;
}

View File

@ -0,0 +1,41 @@
import { useUserProfile } from "@snort/system-react";
import Avatar from "Element/Avatar";
import useLogin from "Hooks/useLogin";
import "./Nav.css";
import Icon from "Icons/Icon";
import { Link } from "react-router-dom";
import { profileLink } from "SnortUtils";
export function DeckNav() {
const { publicKey } = useLogin();
const profile = useUserProfile(publicKey);
const unreadDms = 0;
const hasNotifications = false;
return (
<nav className="deck flex-column f-space">
<div className="flex-column f-center g24">
<Link className="btn" to="/messages">
<Icon name="mail" size={24} />
{unreadDms > 0 && <span className="has-unread"></span>}
</Link>
<Link className="btn" to="/notifications">
<Icon name="bell-02" size={24} />
{hasNotifications && <span className="has-unread"></span>}
</Link>
</div>
<div className="flex-column f-center g16">
<Link className="btn" to="/">
<Icon name="grid-01" size={24} />
</Link>
<Link className="btn" to="/settings">
<Icon name="settings-02" size={24} />
</Link>
<Link to={profileLink(publicKey ?? "")}>
<Avatar pubkey={publicKey ?? ""} user={profile} />
</Link>
</div>
</nav>
);
}

View File

@ -9,6 +9,7 @@ import AsyncButton from "Element/AsyncButton";
import { System } from "index";
import messages from "./messages";
import { FollowsFeed } from "Cache";
export interface FollowButtonProps {
pubkey: HexKey;
@ -24,6 +25,7 @@ export default function FollowButton(props: FollowButtonProps) {
async function follow(pubkey: HexKey) {
if (publisher) {
const ev = await publisher.contactList([pubkey, ...follows.item], relays.item);
await FollowsFeed.backFill(System, [pubkey]);
System.BroadcastEvent(ev);
}
}
@ -32,7 +34,7 @@ export default function FollowButton(props: FollowButtonProps) {
if (publisher) {
const ev = await publisher.contactList(
follows.item.filter(a => a !== pubkey),
relays.item
relays.item,
);
System.BroadcastEvent(ev);
}

View File

@ -8,6 +8,7 @@ import useLogin from "Hooks/useLogin";
import { System } from "index";
import messages from "./messages";
import { FollowsFeed } from "Cache";
export interface FollowListBaseProps {
pubkeys: HexKey[];
@ -34,6 +35,7 @@ export default function FollowListBase({
async function followAll() {
if (publisher) {
const ev = await publisher.contactList([...pubkeys, ...follows.item], relays.item);
await FollowsFeed.backFill(System, pubkeys);
System.BroadcastEvent(ev);
}
}

View File

@ -27,9 +27,10 @@ import MagnetLink from "Element/MagnetLink";
interface HypeTextProps {
link: string;
depth?: number;
showLinkPreview?: boolean;
}
export default function HyperText({ link, depth }: HypeTextProps) {
export default function HyperText({ link, depth, showLinkPreview }: HypeTextProps) {
const a = link;
try {
const url = new URL(a);
@ -91,7 +92,7 @@ export default function HyperText({ link, depth }: HypeTextProps) {
if (parsed) {
return <MagnetLink magnet={parsed} />;
}
} else {
} else if (showLinkPreview ?? true) {
return <LinkPreview url={a} />;
}
} catch {

View File

@ -75,7 +75,7 @@ export default function Invoice(props: InvoiceProps) {
{description && <p>{description}</p>}
{isPaid ? (
<div className="paid">
<FormattedMessage {...messages.Paid} />
<FormattedMessage defaultMessage="Paid" />
</div>
) : (
<button disabled={isExpired} type="button" onClick={payInvoice}>

View File

@ -1,19 +0,0 @@
import Hls from "hls.js";
import { HTMLProps, useEffect, useRef } from "react";
export function LiveVideoPlayer(props: HTMLProps<HTMLVideoElement> & { stream: string }) {
const video = useRef<HTMLVideoElement>(null);
useEffect(() => {
if (props.stream && video.current && !video.current.src && Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(props.stream);
hls.attachMedia(video.current);
return () => hls.destroy();
}
}, [video, props]);
return (
<div>
<video ref={video} {...props} controls={true} />
</div>
);
}

View File

@ -261,9 +261,7 @@ export default function Nip5Service(props: Nip05ServiceProps) {
/>
&nbsp;@&nbsp;
<select value={domain} onChange={onDomainChange}>
{serviceConfig?.domains.map(a => (
<option key={a.name}>{a.name}</option>
))}
{serviceConfig?.domains.map(a => <option key={a.name}>{a.name}</option>)}
</select>
</div>
)}

View File

@ -2,7 +2,7 @@ import { FormattedMessage } from "react-intl";
import { NostrEvent, NostrLink } from "@snort/system";
import { findTag } from "SnortUtils";
import useEventFeed from "Feed/EventFeed";
import { useEventFeed } from "Feed/EventFeed";
import PageSpinner from "Element/PageSpinner";
import Reveal from "Element/Reveal";
import { MediaElement } from "Element/MediaElement";

View File

@ -67,15 +67,6 @@
padding: 8px 16px 16px 16px;
}
.note > .body .text-frag {
text-overflow: ellipsis;
white-space: pre-wrap;
word-break: normal;
overflow-x: hidden;
overflow-y: visible;
display: inline;
}
.note .footer .footer-reactions {
display: flex;
flex-direction: row;

View File

@ -3,7 +3,17 @@ import React, { useMemo, useState, ReactNode } from "react";
import { useNavigate, Link } from "react-router-dom";
import { useInView } from "react-intersection-observer";
import { useIntl, FormattedMessage } from "react-intl";
import { TaggedNostrEvent, HexKey, EventKind, NostrPrefix, Lists, EventExt, parseZap } from "@snort/system";
import {
TaggedNostrEvent,
HexKey,
EventKind,
NostrPrefix,
Lists,
EventExt,
parseZap,
tagToNostrLink,
createNostrLinkToEvent,
} from "@snort/system";
import { System } from "index";
import useEventPublisher from "Feed/EventPublisher";
@ -11,7 +21,6 @@ import Icon from "Icons/Icon";
import ProfileImage from "Element/ProfileImage";
import Text from "Element/Text";
import {
eventLink,
getReactions,
dedupeByPubkey,
tagFilterOfTextRepost,
@ -19,6 +28,7 @@ import {
normalizeReaction,
Reaction,
profileLink,
findTag,
} from "SnortUtils";
import NoteFooter from "Element/NoteFooter";
import NoteTime from "Element/NoteTime";
@ -35,8 +45,11 @@ import { LiveEvent } from "Element/LiveEvent";
import { NoteContextMenu, NoteTranslation } from "Element/NoteContextMenu";
import Reactions from "Element/Reactions";
import { ZapGoal } from "Element/ZapGoal";
import NoteReaction from "Element/NoteReaction";
import ProfilePreview from "Element/ProfilePreview";
import messages from "./messages";
import { ProxyImg } from "./ProxyImg";
export interface NoteProps {
data: TaggedNostrEvent;
@ -80,8 +93,10 @@ const HiddenNote = ({ children }: { children: React.ReactNode }) => {
};
export default function Note(props: NoteProps) {
const { data: ev, related, highlight, options: opt, ignoreModeration = false, className } = props;
const { data: ev, className } = props;
if (ev.kind === EventKind.Repost) {
return <NoteReaction data={ev} key={ev.id} root={undefined} depth={(props.depth ?? 0) + 1} />;
}
if (ev.kind === EventKind.FileHeader) {
return <NostrFileElement ev={ev} />;
}
@ -94,10 +109,19 @@ export default function Note(props: NoteProps) {
if (ev.kind === EventKind.LiveEvent) {
return <LiveEvent ev={ev} />;
}
if (ev.kind === EventKind.SetMetadata) {
return <ProfilePreview actions={<></>} pubkey={ev.pubkey} className="card" />;
}
if (ev.kind === (9041 as EventKind)) {
return <ZapGoal ev={ev} />;
}
return <NoteInner {...props} />;
}
export function NoteInner(props: NoteProps) {
const { data: ev, related, highlight, options: opt, ignoreModeration = false, className } = props;
const baseClassName = `note card${className ? ` ${className}` : ""}`;
const navigate = useNavigate();
const [showReactions, setShowReactions] = useState(false);
@ -121,7 +145,7 @@ export default function Note(props: NoteProps) {
{
[Reaction.Positive]: [] as TaggedNostrEvent[],
[Reaction.Negative]: [] as TaggedNostrEvent[],
}
},
);
return {
[Reaction.Positive]: dedupeByPubkey(result[Reaction.Positive]),
@ -136,7 +160,7 @@ export default function Note(props: NoteProps) {
...getReactions(related, ev.id, EventKind.TextNote).filter(e => e.tags.some(tagFilterOfTextRepost(e, ev.id))),
...getReactions(related, ev.id, EventKind.Repost),
]),
[related, ev]
[related, ev],
);
const zaps = useMemo(() => {
const sortedZaps = getReactions(related, ev.id, EventKind.ZapReceipt)
@ -179,8 +203,45 @@ export default function Note(props: NoteProps) {
}
}
const innerContent = () => {
if (ev.kind === EventKind.LongFormTextNote) {
const title = findTag(ev, "title");
const summary = findTag(ev, "simmary");
const image = findTag(ev, "image");
return (
<div className="long-form-note">
<h3>{title}</h3>
<div className="text">
<p>{summary}</p>
<Text
id={ev.id}
content={ev.content}
tags={ev.tags}
creator={ev.pubkey}
depth={props.depth}
truncate={255}
disableLinkPreview={true}
/>
{image && <ProxyImg src={image} />}
</div>
</div>
);
} else {
const body = ev?.content ?? "";
return (
<Text
id={ev.id}
content={body}
tags={ev.tags}
creator={ev.pubkey}
depth={props.depth}
disableMedia={!(options.showMedia ?? true)}
/>
);
}
};
const transformBody = () => {
const body = ev?.content ?? "";
if (deletions?.length > 0) {
return (
<b className="error">
@ -208,25 +269,17 @@ export default function Note(props: NoteProps) {
)}
</>
}>
<Text content={body} tags={ev.tags} creator={ev.pubkey} />
{innerContent()}
</Reveal>
);
}
return (
<Text
content={body}
tags={ev.tags}
creator={ev.pubkey}
depth={props.depth}
disableMedia={!(options.showMedia ?? true)}
/>
);
return innerContent();
};
function goToEvent(
e: React.MouseEvent,
eTarget: TaggedNostrEvent,
isTargetAllowed: boolean = e.target === e.currentTarget
isTargetAllowed: boolean = e.target === e.currentTarget,
) {
if (!isTargetAllowed || opt?.canClick === false) {
return;
@ -238,13 +291,13 @@ export default function Note(props: NoteProps) {
return;
}
const link = eventLink(eTarget.id, eTarget.relays);
const link = createNostrLinkToEvent(eTarget);
// detect cmd key and open in new tab
if (e.metaKey) {
window.open(link, "_blank");
window.open(`/e/${link.encode()}`, "_blank");
} else {
navigate(link, {
state: ev,
navigate(`/e/${link.encode()}`, {
state: eTarget,
});
}
}
@ -256,8 +309,12 @@ export default function Note(props: NoteProps) {
}
const maxMentions = 2;
const replyId = thread?.replyTo?.value ?? thread?.root?.value;
const replyRelayHints = thread?.replyTo?.relay ?? thread.root?.relay;
const replyTo = thread?.replyTo ?? thread?.root;
const replyLink = replyTo
? tagToNostrLink(
[replyTo.key, replyTo.value ?? "", replyTo.relay ?? "", replyTo.marker ?? ""].filter(a => a.length > 0),
)
: undefined;
const mentions: { pk: string; name: string; link: ReactNode }[] = [];
for (const pk of thread?.pubKeys ?? []) {
const u = UserCache.getFromCache(pk);
@ -290,26 +347,31 @@ export default function Note(props: NoteProps) {
{pubMentions} {others}
</>
) : (
replyId && (
<Link to={eventLink(replyId, replyRelayHints)}>
{hexToBech32(NostrPrefix.Event, replyId)?.substring(0, 12)}
</Link>
)
replyLink && <Link to={`/e/${replyLink.encode()}`}>{replyLink.encode().substring(0, 12)}</Link>
)}
</div>
);
}
const canRenderAsTextNote = [EventKind.TextNote, EventKind.Polls];
const canRenderAsTextNote = [EventKind.TextNote, EventKind.Polls, EventKind.LongFormTextNote];
if (!canRenderAsTextNote.includes(ev.kind)) {
return (
<>
<h4>
<FormattedMessage {...messages.UnknownEventKind} values={{ kind: ev.kind }} />
</h4>
<pre>{JSON.stringify(ev, undefined, " ")}</pre>
</>
);
const alt = findTag(ev, "alt");
if (alt) {
return (
<div className="note-quote">
<Text id={ev.id} content={alt} tags={[]} creator={ev.pubkey} />
</div>
);
} else {
return (
<>
<h4>
<FormattedMessage {...messages.UnknownEventKind} values={{ kind: ev.kind }} />
</h4>
<pre>{JSON.stringify(ev, undefined, " ")}</pre>
</>
);
}
}
function translation() {

View File

@ -1,5 +1,5 @@
import { FormattedMessage, useIntl } from "react-intl";
import { HexKey, Lists, NostrPrefix, TaggedRawEvent, encodeTLV } from "@snort/system";
import { HexKey, Lists, NostrPrefix, TaggedNostrEvent, encodeTLV } from "@snort/system";
import { Menu, MenuItem } from "@szhsin/react-menu";
import { useDispatch, useSelector } from "react-redux";
@ -26,7 +26,7 @@ export interface NoteTranslation {
}
interface NosteContextMenuProps {
ev: TaggedRawEvent;
ev: TaggedNostrEvent;
setShowReactions(b: boolean): void;
react(content: string): Promise<void>;
onTranslated?: (t: NoteTranslation) => void;

View File

@ -2,7 +2,8 @@
border: 1px solid transparent;
border-radius: 12px;
box-shadow: 0px 0px 6px 1px rgba(182, 108, 156, 0.3);
background: linear-gradient(var(--gray-superdark), var(--gray-superdark)) padding-box,
background:
linear-gradient(var(--gray-superdark), var(--gray-superdark)) padding-box,
linear-gradient(90deg, #ef9644, #fd7c49, #ff5e58, #ff3b70, #ff088e, #eb00b1, #c31ed5, #7b41f6) border-box;
}

View File

@ -1,9 +1,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import "./NoteCreator.css";
import { FormattedMessage, useIntl } from "react-intl";
import { useDispatch, useSelector } from "react-redux";
import { encodeTLV, EventKind, NostrPrefix, TaggedNostrEvent, EventBuilder } from "@snort/system";
import { LNURL } from "@snort/shared";
import { encodeTLV, EventKind, NostrPrefix, TaggedNostrEvent, EventBuilder, tryParseNostrLink } from "@snort/system";
import Icon from "Icons/Icon";
import useEventPublisher from "Feed/EventPublisher";
@ -21,7 +19,7 @@ import {
setPreview,
setShowAdvanced,
setSelectedCustomRelays,
setZapForward,
setZapSplits,
setSensitive,
reset,
setPollOptions,
@ -29,16 +27,13 @@ import {
} from "State/NoteCreator";
import type { RootState } from "State/Store";
import messages from "./messages";
import { ClipboardEventHandler, useState } from "react";
import Spinner from "Icons/Spinner";
import { Menu, MenuItem } from "@szhsin/react-menu";
import { LoginStore } from "Login";
import { getCurrentSubscription } from "Subscription";
import { ClipboardEventHandler } from "react";
import useLogin from "Hooks/useLogin";
import { System } from "index";
import AsyncButton from "Element/AsyncButton";
import { AsyncIcon } from "Element/AsyncIcon";
import { fetchNip05Pubkey } from "@snort/shared";
import { ZapTarget } from "Zapper";
export function NoteCreator() {
const { formatMessage } = useIntl();
@ -46,7 +41,7 @@ export function NoteCreator() {
const uploader = useFileUpload();
const {
note,
zapForward,
zapSplits,
sensitive,
pollOptions,
replyTo,
@ -59,45 +54,95 @@ export function NoteCreator() {
error,
} = useSelector((s: RootState) => s.noteCreator);
const dispatch = useDispatch();
const sub = getCurrentSubscription(LoginStore.allSubscriptions());
const login = useLogin();
const relays = login.relays;
async function sendNote() {
if (note && publisher) {
let extraTags: Array<Array<string>> | undefined;
if (zapForward) {
try {
const svc = new LNURL(zapForward);
await svc.load();
extraTags = [svc.getZapTag()];
} catch {
dispatch(
setError(
formatMessage({
defaultMessage: "Invalid LNURL",
})
)
);
return;
async function buildNote() {
try {
dispatch(setError(""));
if (note && publisher) {
let extraTags: Array<Array<string>> | undefined;
if (zapSplits) {
const parsedSplits = [] as Array<ZapTarget>;
for (const s of zapSplits) {
if (s.value.startsWith(NostrPrefix.PublicKey) || s.value.startsWith(NostrPrefix.Profile)) {
const link = tryParseNostrLink(s.value);
if (link) {
parsedSplits.push({ ...s, value: link.id });
} else {
throw new Error(
formatMessage(
{
defaultMessage: "Failed to parse zap split: {input}",
},
{
input: s.value,
},
),
);
}
} else if (s.value.includes("@")) {
const [name, domain] = s.value.split("@");
const pubkey = await fetchNip05Pubkey(name, domain);
if (pubkey) {
parsedSplits.push({ ...s, value: pubkey });
} else {
throw new Error(
formatMessage(
{
defaultMessage: "Failed to parse zap split: {input}",
},
{
input: s.value,
},
),
);
}
} else {
throw new Error(
formatMessage(
{
defaultMessage: "Invalid zap split: {input}",
},
{
input: s.value,
},
),
);
}
}
extraTags = parsedSplits.map(v => ["zap", v.value, "", String(v.weight)]);
}
}
if (sensitive) {
extraTags ??= [];
extraTags.push(["content-warning", sensitive]);
if (sensitive) {
extraTags ??= [];
extraTags.push(["content-warning", sensitive]);
}
const kind = pollOptions ? EventKind.Polls : EventKind.TextNote;
if (pollOptions) {
extraTags ??= [];
extraTags.push(...pollOptions.map((a, i) => ["poll_option", i.toString(), a]));
}
const hk = (eb: EventBuilder) => {
extraTags?.forEach(t => eb.tag(t));
eb.kind(kind);
return eb;
};
const ev = replyTo ? await publisher.reply(replyTo, note, hk) : await publisher.note(note, hk);
return ev;
}
const kind = pollOptions ? EventKind.Polls : EventKind.TextNote;
if (pollOptions) {
extraTags ??= [];
extraTags.push(...pollOptions.map((a, i) => ["poll_option", i.toString(), a]));
} catch (e) {
if (e instanceof Error) {
dispatch(setError(e.message));
} else {
dispatch(setError(e as string));
}
const hk = (eb: EventBuilder) => {
extraTags?.forEach(t => eb.tag(t));
eb.kind(kind);
return eb;
};
const ev = replyTo ? await publisher.reply(replyTo, note, hk) : await publisher.note(note, hk);
}
}
async function sendNote() {
const ev = await buildNote();
if (ev) {
if (selectedCustomRelays) selectedCustomRelays.forEach(r => System.WriteOnceToRelay(r, ev));
else System.BroadcastEvent(ev);
dispatch(reset());
@ -166,7 +211,7 @@ export function NoteCreator() {
if (preview) {
dispatch(setPreview(undefined));
} else if (publisher) {
const tmpNote = await publisher.note(note);
const tmpNote = await buildNote();
if (tmpNote) {
dispatch(setPreview(tmpNote));
}
@ -256,9 +301,9 @@ export function NoteCreator() {
? false
: // otherwise return selectedCustomRelays with target relay added / removed
a.filter(el =>
el === r ? e.target.checked : !selectedCustomRelays || selectedCustomRelays.includes(el)
)
)
el === r ? e.target.checked : !selectedCustomRelays || selectedCustomRelays.includes(el),
),
),
)
}
/>
@ -269,7 +314,7 @@ export function NoteCreator() {
);
}
function listAccounts() {
/*function listAccounts() {
return LoginStore.getSessions().map(a => (
<MenuItem
onClick={ev => {
@ -279,7 +324,7 @@ export function NoteCreator() {
<ProfileImage pubkey={a} link={""} />
</MenuItem>
));
}
}*/
const handlePaste: ClipboardEventHandler<HTMLDivElement> = evt => {
if (evt.clipboardData) {
@ -374,20 +419,63 @@ export function NoteCreator() {
</div>
<div className="flex-column g8">
<h4>
<FormattedMessage defaultMessage="Forward Zaps" />
<FormattedMessage defaultMessage="Zap Splits" />
</h4>
<FormattedMessage defaultMessage="All zaps sent to this note will be received by the following LNURL" />
<input
type="text"
className="w-max"
placeholder={formatMessage({
defaultMessage: "LNURL to forward zaps to",
})}
value={zapForward}
onChange={e => dispatch(setZapForward(e.target.value))}
/>
<FormattedMessage defaultMessage="Zaps on this note will be split to the following users." />
<div className="flex-column g8">
{[...(zapSplits ?? [])].map((v, i, arr) => (
<div className="flex f-center g8">
<div className="flex-column f-4 g4">
<h4>
<FormattedMessage defaultMessage="Recipient" />
</h4>
<input
type="text"
value={v.value}
onChange={e =>
dispatch(
setZapSplits(arr.map((vv, ii) => (ii === i ? { ...vv, value: e.target.value } : vv))),
)
}
placeholder={formatMessage({ defaultMessage: "npub / nprofile / nostr address" })}
/>
</div>
<div className="flex-column f-1 g4">
<h4>
<FormattedMessage defaultMessage="Weight" />
</h4>
<input
type="number"
min={0}
value={v.weight}
onChange={e =>
dispatch(
setZapSplits(
arr.map((vv, ii) => (ii === i ? { ...vv, weight: Number(e.target.value) } : vv)),
),
)
}
/>
</div>
<div className="flex-column f-shrink g4">
<div>&nbsp;</div>
<Icon
name="close"
onClick={() => dispatch(setZapSplits((zapSplits ?? []).filter((_v, ii) => ii !== i)))}
/>
</div>
</div>
))}
<button
type="button"
onClick={() =>
dispatch(setZapSplits([...(zapSplits ?? []), { type: "pubkey", value: "", weight: 1 }]))
}>
<FormattedMessage defaultMessage="Add" />
</button>
</div>
<span className="warning">
<FormattedMessage defaultMessage="Not all clients support this yet" />
<FormattedMessage defaultMessage="Not all clients support this, you may still receive some zaps as if zap splits was not configured" />
</span>
</div>
<div className="flex-column g8">

View File

@ -1,14 +1,13 @@
import React, { HTMLProps, useEffect, useState } from "react";
import React, { HTMLProps, useContext, useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useIntl } from "react-intl";
import { useLongPress } from "use-long-press";
import { TaggedNostrEvent, HexKey, u256, ParsedZap, countLeadingZeros } from "@snort/system";
import { LNURL } from "@snort/shared";
import { useUserProfile } from "@snort/system-react";
import { TaggedNostrEvent, ParsedZap, countLeadingZeros, createNostrLinkToEvent } from "@snort/system";
import { SnortContext, useUserProfile } from "@snort/system-react";
import { formatShort } from "Number";
import useEventPublisher from "Feed/EventPublisher";
import { delay, findTag, normalizeReaction, unwrap } from "SnortUtils";
import { delay, findTag, normalizeReaction } from "SnortUtils";
import { NoteCreator } from "Element/NoteCreator";
import SendSats from "Element/SendSats";
import { ZapsSummary } from "Element/Zap";
@ -21,6 +20,8 @@ import useLogin from "Hooks/useLogin";
import { useInteractionCache } from "Hooks/useInteractionCache";
import { ZapPoolController } from "ZapPoolController";
import { System } from "index";
import { Zapper, ZapTarget } from "Zapper";
import { getDisplayName } from "./ProfileImage";
import messages from "./messages";
@ -47,9 +48,10 @@ export interface NoteFooterProps {
export default function NoteFooter(props: NoteFooterProps) {
const { ev, positive, reposts, zaps } = props;
const dispatch = useDispatch();
const system = useContext(SnortContext);
const { formatMessage } = useIntl();
const login = useLogin();
const { publicKey, preferences: prefs, relays } = login;
const { publicKey, preferences: prefs } = login;
const author = useUserProfile(ev.pubkey);
const interactionCache = useInteractionCache(publicKey, ev.id);
const publisher = useEventPublisher();
@ -71,7 +73,7 @@ export default function NoteFooter(props: NoteFooterProps) {
},
{
captureEvent: true,
}
},
);
function hasReacted(emoji: string) {
@ -103,27 +105,36 @@ export default function NoteFooter(props: NoteFooterProps) {
}
}
function getLNURL() {
return ev.tags.find(a => a[0] === "zap")?.[1] || author?.lud16 || author?.lud06;
}
function getZapTarget(): Array<ZapTarget> | undefined {
if (ev.tags.some(v => v[0] === "zap")) {
return Zapper.fromEvent(ev);
}
function getTargetName() {
const zapTarget = ev.tags.find(a => a[0] === "zap")?.[1];
if (zapTarget) {
return new LNURL(zapTarget).name;
} else {
return author?.display_name || author?.name;
const authorTarget = author?.lud16 || author?.lud06;
if (authorTarget) {
return [
{
type: "lnurl",
value: authorTarget,
weight: 1,
name: getDisplayName(author, ev.pubkey),
zap: {
pubkey: ev.pubkey,
event: createNostrLinkToEvent(ev),
},
} as ZapTarget,
];
}
}
async function fastZap(e?: React.MouseEvent) {
if (zapping || e?.isPropagationStopped()) return;
const lnurl = getLNURL();
const lnurl = getZapTarget();
if (wallet?.isReady() && lnurl) {
setZapping(true);
try {
await fastZapInner(lnurl, prefs.defaultZapAmount, ev.pubkey, ev.id);
await fastZapInner(lnurl, prefs.defaultZapAmount);
} catch (e) {
console.warn("Fast zap failed", e);
if (!(e instanceof Error) || e.message !== "User rejected") {
@ -137,30 +148,29 @@ export default function NoteFooter(props: NoteFooterProps) {
}
}
async function fastZapInner(lnurl: string, amount: number, key: HexKey, id?: u256) {
// only allow 1 invoice req/payment at a time to avoid hitting rate limits
await barrierZapper(async () => {
const handler = new LNURL(lnurl);
await handler.load();
const zr = Object.keys(relays.item);
const zap = handler.canZap && publisher ? await publisher.zap(amount * 1000, key, zr, id) : undefined;
const invoice = await handler.getInvoice(amount, undefined, zap);
await wallet?.payInvoice(unwrap(invoice.pr));
ZapPoolController.allocate(amount);
await interactionCache.zap();
});
async function fastZapInner(targets: Array<ZapTarget>, amount: number) {
if (wallet) {
// only allow 1 invoice req/payment at a time to avoid hitting rate limits
await barrierZapper(async () => {
const zapper = new Zapper(system, publisher);
const result = await zapper.send(wallet, targets, amount);
const totalSent = result.reduce((acc, v) => (acc += v.sent), 0);
if (totalSent > 0) {
ZapPoolController.allocate(totalSent);
await interactionCache.zap();
}
});
}
}
useEffect(() => {
if (prefs.autoZap && !didZap && !isMine && !zapping) {
const lnurl = getLNURL();
const lnurl = getZapTarget();
if (wallet?.isReady() && lnurl) {
setZapping(true);
queueMicrotask(async () => {
try {
await fastZapInner(lnurl, prefs.defaultZapAmount, ev.pubkey, ev.id);
await fastZapInner(lnurl, prefs.defaultZapAmount);
} catch {
// ignored
} finally {
@ -181,8 +191,8 @@ export default function NoteFooter(props: NoteFooterProps) {
}
function tipButton() {
const service = getLNURL();
if (service) {
const targets = getZapTarget();
if (targets) {
return (
<AsyncFooterIcon
className={didZap ? "reacted" : ""}
@ -257,15 +267,7 @@ export default function NoteFooter(props: NoteFooterProps) {
{powIcon()}
</div>
{willRenderNoteCreator && <NoteCreator />}
<SendSats
lnurl={getLNURL()}
onClose={() => setTip(false)}
show={tip}
author={author?.pubkey}
target={getTargetName()}
note={ev.id}
allocatePool={true}
/>
<SendSats targets={getZapTarget()} onClose={() => setTip(false)} show={tip} note={ev.id} allocatePool={true} />
</div>
<ZapsSummary zaps={zaps} />
</>

View File

@ -1,4 +1,4 @@
import useEventFeed from "Feed/EventFeed";
import { useEventFeed } from "Feed/EventFeed";
import { NostrLink } from "@snort/system";
import Note from "Element/Note";
import PageSpinner from "Element/PageSpinner";

View File

@ -1,7 +1,7 @@
import "./NoteReaction.css";
import { Link } from "react-router-dom";
import { useMemo } from "react";
import { EventKind, NostrEvent, TaggedNostrEvent, NostrPrefix } from "@snort/system";
import { EventKind, NostrEvent, TaggedNostrEvent, NostrPrefix, EventExt } from "@snort/system";
import Note from "Element/Note";
import { getDisplayName } from "Element/ProfileImage";
@ -10,15 +10,18 @@ import useModeration from "Hooks/useModeration";
import { FormattedMessage } from "react-intl";
import Icon from "Icons/Icon";
import { useUserProfile } from "@snort/system-react";
import { useInView } from "react-intersection-observer";
export interface NoteReactionProps {
data: TaggedNostrEvent;
root?: TaggedNostrEvent;
depth?: number;
}
export default function NoteReaction(props: NoteReactionProps) {
const { data: ev } = props;
const { isMuted } = useModeration();
const profile = useUserProfile(ev.pubkey);
const { inView, ref } = useInView({ triggerOnce: true });
const profile = useUserProfile(inView ? ev.pubkey : "");
const refEvent = useMemo(() => {
if (ev) {
@ -43,9 +46,15 @@ export default function NoteReaction(props: NoteReactionProps) {
* Some clients embed the reposted note in the content
*/
function extractRoot() {
if (!inView) return null;
if (ev?.kind === EventKind.Repost && ev.content.length > 0 && ev.content !== "#[0]") {
try {
const r: NostrEvent = JSON.parse(ev.content);
EventExt.fixupEvent(r);
if (!EventExt.verify(r)) {
console.debug("Event in repost is invalid");
return undefined;
}
return r as TaggedNostrEvent;
} catch (e) {
console.error("Could not load reposted content", e);
@ -54,7 +63,11 @@ export default function NoteReaction(props: NoteReactionProps) {
return props.root;
}
const root = extractRoot();
const root = useMemo(() => extractRoot(), [ev, props.root, inView]);
if (!inView) {
return <div className="card reaction" ref={ref}></div>;
}
const isOpMuted = root && isMuted(root.pubkey);
const shouldNotBeRendered = isOpMuted || root?.kind !== EventKind.TextNote;
const opt = {
@ -73,7 +86,7 @@ export default function NoteReaction(props: NoteReactionProps) {
}}
/>
</div>
{root ? <Note data={root} options={opt} related={[]} /> : null}
{root ? <Note data={root} options={opt} related={[]} depth={props.depth} /> : null}
{!root && refEvent ? (
<p>
<Link to={eventLink(refEvent[1] ?? "", refEvent[2])}>

View File

@ -4,7 +4,6 @@ import { useState } from "react";
import { FormattedMessage, FormattedNumber, useIntl } from "react-intl";
import { useUserProfile } from "@snort/system-react";
import Text from "Element/Text";
import useEventPublisher from "Feed/EventPublisher";
import { useWallet } from "Wallet";
import { unwrap } from "SnortUtils";
@ -18,12 +17,15 @@ interface PollProps {
zaps: Array<ParsedZap>;
}
type PollTally = "zaps" | "pubkeys";
export default function Poll(props: PollProps) {
const { formatMessage } = useIntl();
const publisher = useEventPublisher();
const { wallet } = useWallet();
const { preferences: prefs, publicKey: myPubKey, relays } = useLogin();
const pollerProfile = useUserProfile(props.ev.pubkey);
const [tallyBy, setTallyBy] = useState<PollTally>("pubkeys");
const [error, setError] = useState("");
const [invoice, setInvoice] = useState("");
const [voting, setVoting] = useState<number>();
@ -31,7 +33,10 @@ export default function Poll(props: PollProps) {
const isMyPoll = props.ev.pubkey === myPubKey;
const showResults = didVote || isMyPoll;
const options = props.ev.tags.filter(a => a[0] === "poll_option").sort((a, b) => Number(a[1]) - Number(b[1]));
const options = props.ev.tags
.filter(a => a[0] === "poll_option")
.sort((a, b) => (Number(a[1]) > Number(b[1]) ? 1 : -1));
async function zapVote(ev: React.MouseEvent, opt: number) {
ev.stopPropagation();
if (voting || !publisher) return;
@ -46,15 +51,15 @@ export default function Poll(props: PollProps) {
},
{
amount,
}
)
},
),
);
}
setVoting(opt);
const r = Object.keys(relays.item);
const zap = await publisher.zap(amount * 1000, props.ev.pubkey, r, props.ev.id, undefined, eb =>
eb.tag(["poll_option", opt.toString()])
eb.tag(["poll_option", opt.toString()]),
);
const lnurl = props.ev.tags.find(a => a[0] === "zap")?.[1] || pollerProfile?.lud16 || pollerProfile?.lud06;
@ -67,7 +72,7 @@ export default function Poll(props: PollProps) {
throw new Error(
formatMessage({
defaultMessage: "Can't vote because LNURL service does not support zaps",
})
}),
);
}
@ -84,7 +89,7 @@ export default function Poll(props: PollProps) {
setError(
formatMessage({
defaultMessage: "Failed to send vote",
})
}),
);
}
} finally {
@ -92,33 +97,57 @@ export default function Poll(props: PollProps) {
}
}
const allTotal = props.zaps.filter(a => a.pollOption !== undefined).reduce((acc, v) => (acc += v.amount), 0);
const totalVotes = (() => {
switch (tallyBy) {
case "zaps":
return props.zaps.filter(a => a.pollOption !== undefined).reduce((acc, v) => (acc += v.amount), 0);
case "pubkeys":
return new Set(props.zaps.filter(a => a.pollOption !== undefined).map(a => unwrap(a.sender))).size;
}
})();
return (
<>
<small>
<FormattedMessage
defaultMessage="You are voting with {amount} sats"
values={{
amount: formatShort(prefs.defaultZapAmount),
}}
/>
</small>
<div className="flex f-space p">
<small>
<FormattedMessage
defaultMessage="You are voting with {amount} sats"
values={{
amount: formatShort(prefs.defaultZapAmount),
}}
/>
</small>
<button type="button" onClick={() => setTallyBy(s => (s !== "zaps" ? "zaps" : "pubkeys"))}>
<FormattedMessage
defaultMessage="Votes by {type}"
values={{
type:
tallyBy === "zaps" ? (
<FormattedMessage defaultMessage="zap" />
) : (
<FormattedMessage defaultMessage="user" />
),
}}
/>
</button>
</div>
<div className="poll-body">
{options.map(a => {
const opt = Number(a[1]);
const desc = a[2];
const zapsOnOption = props.zaps.filter(b => b.pollOption === opt);
const total = zapsOnOption.reduce((acc, v) => (acc += v.amount), 0);
const weight = allTotal === 0 ? 0 : total / allTotal;
const total = (() => {
switch (tallyBy) {
case "zaps":
return zapsOnOption.reduce((acc, v) => (acc += v.amount), 0);
case "pubkeys":
return new Set(zapsOnOption.map(a => unwrap(a.sender))).size;
}
})();
const weight = totalVotes === 0 ? 0 : total / totalVotes;
return (
<div key={a[1]} className="flex" onClick={e => zapVote(e, opt)}>
<div className="f-grow">
{opt === voting ? (
<Spinner />
) : (
<Text content={desc} tags={props.ev.tags} creator={props.ev.pubkey} disableMediaSpotlight={true} />
)}
</div>
<div className="f-grow">{opt === voting ? <Spinner /> : <>{desc}</>}</div>
{showResults && (
<>
<div className="flex">

View File

@ -12,6 +12,8 @@
width: 48px;
height: 48px;
cursor: pointer;
position: relative;
z-index: 2;
}
a.pfp {

View File

@ -1,6 +1,6 @@
import "./ProfileImage.css";
import React, { useMemo } from "react";
import React, { ReactNode, useMemo } from "react";
import { Link } from "react-router-dom";
import { HexKey, NostrPrefix, UserMetadata } from "@snort/system";
import { useUserProfile } from "@snort/system-react";
@ -21,6 +21,7 @@ export interface ProfileImageProps {
profile?: UserMetadata;
size?: number;
onClick?: (e: React.MouseEvent) => void;
imageOverlay?: ReactNode;
}
export default function ProfileImage({
@ -34,6 +35,7 @@ export default function ProfileImage({
overrideUsername,
profile,
size,
imageOverlay,
onClick,
}: ProfileImageProps) {
const user = useUserProfile(profile ? "" : pubkey) ?? profile;
@ -54,7 +56,7 @@ export default function ProfileImage({
return (
<>
<div className="avatar-wrapper">
<Avatar pubkey={pubkey} user={user} size={size} />
<Avatar pubkey={pubkey} user={user} size={size} imageOverlay={imageOverlay} />
</div>
{showUsername && (
<div className="f-ellipsis">

View File

@ -36,6 +36,8 @@ export const ProxyImg = (props: ProxyImgProps) => {
<img
{...props}
src={props.src ? proxy(props.src, props.size) : ""}
width={props.size}
height={props.size}
onError={e => {
if (props.onError) {
props.onError(e);

View File

@ -34,7 +34,7 @@ export default function PubkeyList({ ev, className }: { ev: NostrEvent; classNam
pk,
Object.keys(login.relays.item),
undefined,
`Zap from ${hexToBech32("note", ev.id)}`
`Zap from ${hexToBech32("note", ev.id)}`,
);
const invoice = await svc.getInvoice(amtSend, undefined, zap);
if (invoice.pr) {

View File

@ -55,9 +55,9 @@ export function ReBroadcaster() {
? false
: // otherwise return selectedCustomRelays with target relay added / removed
a.filter(el =>
el === r ? e.target.checked : !selectedCustomRelays || selectedCustomRelays.includes(el)
)
)
el === r ? e.target.checked : !selectedCustomRelays || selectedCustomRelays.includes(el),
),
),
)
}
/>

View File

@ -60,7 +60,7 @@ const Reactions = ({ show, setShow, positive, negative, reposts, zaps }: Reactio
value: 3,
},
]
: []
: [],
);
const [tab, setTab] = useState(tabs[0]);

View File

@ -3,10 +3,11 @@ import { useMemo } from "react";
import { FormattedMessage } from "react-intl";
import { useNavigate } from "react-router-dom";
import { RelaySettings } from "@snort/system";
import { unixNowMs } from "@snort/shared";
import useRelayState from "Feed/RelayState";
import { System } from "index";
import { getRelayName, unixNowMs, unwrap } from "SnortUtils";
import { getRelayName, unwrap } from "SnortUtils";
import useLogin from "Hooks/useLogin";
import { setRelays } from "Login";
import Icon from "Icons/Icon";
@ -21,7 +22,7 @@ export default function Relay(props: RelayProps) {
const navigate = useNavigate();
const login = useLogin();
const relaySettings = unwrap(
login.relays.item[props.addr] ?? System.Sockets.find(a => a.address === props.addr)?.settings ?? {}
login.relays.item[props.addr] ?? System.Sockets.find(a => a.address === props.addr)?.settings ?? {},
);
const state = useRelayState(props.addr);
const name = useMemo(() => getRelayName(props.addr), [props.addr]);
@ -33,7 +34,7 @@ export default function Relay(props: RelayProps) {
...login.relays.item,
[props.addr]: o,
},
unixNowMs()
unixNowMs(),
);
}

View File

@ -0,0 +1,17 @@
.root-type {
display: flex;
align-items: center;
justify-content: center;
}
.root-type > button {
background: white;
color: black;
font-size: 16px;
padding: 10px 16px;
border-radius: 1000px;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}

View File

@ -0,0 +1,156 @@
import "./RootTabs.css";
import { useState, ReactNode, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Menu, MenuItem } from "@szhsin/react-menu";
import { FormattedMessage } from "react-intl";
import useLogin from "Hooks/useLogin";
import Icon from "Icons/Icon";
export type RootTab =
| "following"
| "conversations"
| "trending-notes"
| "trending-people"
| "suggested"
| "tags"
| "global";
export function RootTabs({ base }: { base?: string }) {
const navigate = useNavigate();
const location = useLocation();
const { publicKey: pubKey, tags } = useLogin();
const [rootType, setRootType] = useState<RootTab>("following");
const menuItems = [
{
tab: "following",
path: `${base}/notes`,
show: Boolean(pubKey),
element: (
<>
<Icon name="user-v2" />
<FormattedMessage defaultMessage="Following" />
</>
),
},
{
tab: "trending-notes",
path: `${base}/trending/notes`,
show: true,
element: (
<>
<Icon name="fire" />
<FormattedMessage defaultMessage="Trending Notes" />
</>
),
},
{
tab: "conversations",
path: `${base}/conversations`,
show: Boolean(pubKey),
element: (
<>
<Icon name="message-chat-circle" />
<FormattedMessage defaultMessage="Conversations" />
</>
),
},
{
tab: "trending-people",
path: `${base}/trending/people`,
show: true,
element: (
<>
<Icon name="user-up" />
<FormattedMessage defaultMessage="Trending People" />
</>
),
},
{
tab: "suggested",
path: `${base}/suggested`,
show: Boolean(pubKey),
element: (
<>
<Icon name="thumbs-up" />
<FormattedMessage defaultMessage="Suggested Follows" />
</>
),
},
{
tab: "global",
path: `${base}/global`,
show: true,
element: (
<>
<Icon name="globe" />
<FormattedMessage defaultMessage="Global" />
</>
),
},
] as Array<{
tab: RootTab;
path: string;
show: boolean;
element: ReactNode;
}>;
useEffect(() => {
const currentTab = menuItems.find(a => a.path === location.pathname)?.tab;
if (currentTab) {
setRootType(currentTab);
}
}, [location]);
function currentMenuItem() {
if (location.pathname.startsWith(`${base}/t/`)) {
return (
<>
<Icon name="hash" />
{location.pathname.split("/").slice(-1)}
</>
);
}
return menuItems.find(a => a.tab === rootType)?.element;
}
return (
<div className="root-type">
<Menu
menuButton={
<button type="button">
{currentMenuItem()}
<Icon name="chevronDown" />
</button>
}
align="center"
menuClassName={() => "ctx-menu"}>
<div className="close-menu-container">
<MenuItem>
<div className="close-menu" />
</MenuItem>
</div>
{menuItems
.filter(a => a.show)
.map(a => (
<MenuItem
onClick={() => {
navigate(a.path);
}}>
{a.element}
</MenuItem>
))}
{tags.item.map(v => (
<MenuItem
onClick={() => {
navigate(`${base}/t/${v}`);
}}>
<Icon name="hash" />
{v}
</MenuItem>
))}
</Menu>
</div>
);
}

View File

@ -1,31 +1,28 @@
.lnurl-modal .modal-body {
padding: 0;
max-width: 470px;
padding: 12px 24px;
max-width: 500px;
}
.lnurl-modal .lnurl-tip .pfp .avatar {
.lnurl-modal .pfp .avatar {
width: 48px;
height: 48px;
}
.lnurl-tip {
padding: 24px 32px;
background-color: #1b1b1b;
border-radius: 16px;
position: relative;
}
@media (max-width: 720px) {
.lnurl-tip {
.lnurl-modal {
padding: 12px 16px;
}
}
.light .lnurl-tip {
background-color: var(--gray-superdark);
.lnurl-modal h2 {
margin: 0;
font-weight: 600;
font-size: 16px;
line-height: 19px;
}
.lnurl-tip h3 {
.lnurl-modal h3 {
margin: 0;
color: var(--font-secondary-color);
font-size: 11px;
letter-spacing: 0.11em;
@ -34,43 +31,14 @@
text-transform: uppercase;
}
.lnurl-tip .close {
position: absolute;
top: 12px;
right: 16px;
color: var(--font-secondary-color);
cursor: pointer;
}
.lnurl-tip .close:hover {
color: var(--font-tertiary-color);
}
.lnurl-tip .lnurl-header {
display: flex;
flex-direction: row;
align-items: center;
margin-bottom: 32px;
}
.lnurl-tip .lnurl-header h2 {
margin: 0;
flex-grow: 1;
font-weight: 600;
font-size: 16px;
line-height: 19px;
}
.amounts {
display: flex;
width: 100%;
margin-bottom: 16px;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
.sat-amount {
flex: 1 1 auto;
text-align: center;
display: inline-block;
background-color: #2a2a2a;
color: var(--font-color);
padding: 12px 16px;
@ -79,83 +47,28 @@
font-weight: 600;
font-size: 14px;
line-height: 17px;
cursor: pointer;
}
.light .sat-amount {
background-color: var(--gray);
}
.sat-amount:not(:last-child) {
margin-right: 8px;
}
.sat-amount:hover {
cursor: pointer;
}
.sat-amount.active {
font-weight: bold;
color: var(--gray-superdark);
background-color: var(--font-color);
}
.lnurl-tip .invoice {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.lnurl-tip .invoice .actions {
display: flex;
flex-direction: column;
align-items: flex-start;
text-align: center;
}
.lnurl-tip .invoice .actions .copy-action {
margin: 10px auto;
}
.lnurl-tip .invoice .actions .wallet-action {
width: 100%;
height: 40px;
}
.lnurl-tip .zap-action {
margin-top: 16px;
width: 100%;
height: 40px;
}
.lnurl-tip .zap-action svg {
margin-right: 10px;
}
.lnurl-tip .zap-action-container {
display: flex;
align-items: center;
justify-content: center;
}
.lnurl-tip .custom-amount {
margin-bottom: 16px;
}
.lnurl-tip .custom-amount button {
padding: 12px 18px;
border-radius: 100px;
}
.lnurl-tip canvas {
.lnurl-modal canvas {
border-radius: 10px;
}
.lnurl-tip .success-action .paid {
.lnurl-modal .success-action .paid {
font-size: 19px;
}
.lnurl-tip .success-action a {
.lnurl-modal .success-action a {
color: var(--highlight);
font-size: 19px;
}

View File

@ -1,9 +1,10 @@
import "./SendSats.css";
import React, { useEffect, useMemo, useState } from "react";
import React, { ReactNode, useContext, useEffect, useState } from "react";
import { useIntl, FormattedMessage } from "react-intl";
import { HexKey, NostrEvent, EventPublisher } from "@snort/system";
import { LNURL, LNURLError, LNURLErrorCode, LNURLInvoice, LNURLSuccessAction } from "@snort/shared";
import { HexKey } from "@snort/system";
import { SnortContext } from "@snort/system-react";
import { LNURLSuccessAction } from "@snort/shared";
import { formatShort } from "Number";
import Icon from "Icons/Icon";
@ -12,12 +13,11 @@ import ProfileImage from "Element/ProfileImage";
import Modal from "Element/Modal";
import QrCode from "Element/QrCode";
import Copy from "Element/Copy";
import { chunks, debounce } from "SnortUtils";
import { useWallet } from "Wallet";
import { debounce } from "SnortUtils";
import { LNWallet, useWallet } from "Wallet";
import useLogin from "Hooks/useLogin";
import { generateRandomKey } from "Login";
import { ZapPoolController } from "ZapPoolController";
import AsyncButton from "Element/AsyncButton";
import { ZapTarget, ZapTargetResult, Zapper } from "Zapper";
import messages from "./messages";
@ -30,56 +30,45 @@ enum ZapType {
export interface SendSatsProps {
onClose?: () => void;
lnurl?: string;
targets?: Array<ZapTarget>;
show?: boolean;
invoice?: string; // shortcut to invoice qr tab
title?: string;
title?: ReactNode;
notice?: string;
target?: string;
note?: HexKey;
author?: HexKey;
allocatePool?: boolean;
}
export default function SendSats(props: SendSatsProps) {
const onClose = props.onClose || (() => undefined);
const { note, author, target } = props;
const login = useLogin();
const defaultZapAmount = login.preferences.defaultZapAmount;
const amounts = [defaultZapAmount, 1_000, 5_000, 10_000, 20_000, 50_000, 100_000, 1_000_000];
const emojis: Record<number, string> = {
1_000: "👍",
5_000: "💜",
10_000: "😍",
20_000: "🤩",
50_000: "🔥",
100_000: "🚀",
1_000_000: "🤯",
};
const [handler, setHandler] = useState<LNURL>();
const [invoice, setInvoice] = useState<string>();
const [amount, setAmount] = useState<number>(defaultZapAmount);
const [customAmount, setCustomAmount] = useState<number>();
const [comment, setComment] = useState<string>();
const [success, setSuccess] = useState<LNURLSuccessAction>();
const [zapper, setZapper] = useState<Zapper>();
const [invoice, setInvoice] = useState<Array<ZapTargetResult>>();
const [error, setError] = useState<string>();
const [zapType, setZapType] = useState(ZapType.PublicZap);
const [paying, setPaying] = useState<boolean>(false);
const [success, setSuccess] = useState<LNURLSuccessAction>();
const [amount, setAmount] = useState<SendSatsInputSelection>();
const { formatMessage } = useIntl();
const system = useContext(SnortContext);
const publisher = useEventPublisher();
const canComment = handler ? (handler.canZap && zapType !== ZapType.NonZap) || handler.maxCommentLength > 0 : false;
const walletState = useWallet();
const wallet = walletState.wallet;
useEffect(() => {
if (props.show) {
const invoiceTarget = {
target: {
type: "lnurl",
value: "",
weight: 1,
},
pr: props.invoice,
paid: false,
sent: 0,
fee: 0,
} as ZapTargetResult;
setError(undefined);
setAmount(defaultZapAmount);
setComment(undefined);
setZapType(ZapType.PublicZap);
setInvoice(props.invoice);
setInvoice(props.invoice ? [invoiceTarget] : undefined);
setSuccess(undefined);
}
}, [props.show]);
@ -94,247 +83,30 @@ export default function SendSats(props: SendSatsProps) {
}, [success]);
useEffect(() => {
if (props.lnurl && props.show) {
if (props.targets && props.show) {
try {
const h = new LNURL(props.lnurl);
setHandler(h);
h.load().catch(e => handleLNURLError(e, formatMessage(messages.InvoiceFail)));
console.debug("loading zapper");
const zapper = new Zapper(system, publisher);
zapper.load(props.targets).then(() => {
console.debug(zapper);
setZapper(zapper);
});
} catch (e) {
console.error(e);
if (e instanceof Error) {
setError(e.message);
}
}
}
}, [props.lnurl, props.show]);
const serviceAmounts = useMemo(() => {
if (handler) {
const min = handler.min / 1000;
const max = handler.max / 1000;
return amounts.filter(a => a >= min && a <= max);
}
return [];
}, [handler]);
const amountRows = useMemo(() => chunks(serviceAmounts, 3), [serviceAmounts]);
const selectAmount = (a: number) => {
setError(undefined);
setAmount(a);
};
async function loadInvoice(): Promise<void> {
if (!amount || !handler || !publisher) return;
let zap: NostrEvent | undefined;
if (author && zapType !== ZapType.NonZap) {
const relays = Object.keys(login.relays.item);
// use random key for anon zaps
if (zapType === ZapType.AnonZap) {
const randomKey = generateRandomKey();
console.debug("Generated new key for zap: ", randomKey);
const publisher = EventPublisher.privateKey(randomKey.privateKey);
zap = await publisher.zap(amount * 1000, author, relays, note, comment, eb => eb.tag(["anon", ""]));
} else {
zap = await publisher.zap(amount * 1000, author, relays, note, comment);
}
}
try {
const rsp = await handler.getInvoice(amount, comment, zap);
if (rsp.pr) {
setInvoice(rsp.pr);
await payWithWallet(rsp);
}
} catch (e) {
handleLNURLError(e, formatMessage(messages.InvoiceFail));
}
}
function handleLNURLError(e: unknown, fallback: string) {
if (e instanceof LNURLError) {
switch (e.code) {
case LNURLErrorCode.ServiceUnavailable: {
setError(formatMessage(messages.LNURLFail));
return;
}
case LNURLErrorCode.InvalidLNURL: {
setError(formatMessage(messages.InvalidLNURL));
return;
}
}
}
setError(fallback);
}
function custom() {
if (!handler) return null;
const min = handler.min / 1000;
const max = handler.max / 1000;
return (
<div className="custom-amount flex">
<input
type="number"
min={min}
max={max}
className="f-grow mr10"
placeholder={formatMessage(messages.Custom)}
value={customAmount}
onChange={e => setCustomAmount(parseInt(e.target.value))}
/>
<button
className="secondary"
type="button"
disabled={!customAmount}
onClick={() => selectAmount(customAmount ?? 0)}>
<FormattedMessage {...messages.Confirm} />
</button>
</div>
);
}
async function payWithWallet(invoice: LNURLInvoice) {
try {
if (wallet?.isReady()) {
setPaying(true);
const res = await wallet.payInvoice(invoice?.pr ?? "");
if (props.allocatePool) {
ZapPoolController.allocate(amount);
}
console.log(res);
setSuccess(invoice?.successAction ?? {});
}
} catch (e: unknown) {
console.warn(e);
if (e instanceof Error) {
setError(e.toString());
}
} finally {
setPaying(false);
}
}
function renderAmounts(amount: number, amounts: number[]) {
return (
<div className="amounts">
{amounts.map(a => (
<span className={`sat-amount ${amount === a ? "active" : ""}`} key={a} onClick={() => selectAmount(a)}>
{emojis[a] && <>{emojis[a]}&nbsp;</>}
{a === 1000 ? "1K" : formatShort(a)}
</span>
))}
</div>
);
}
function invoiceForm() {
if (!handler || invoice) return null;
return (
<>
<h3>
<FormattedMessage {...messages.ZapAmount} />
</h3>
{amountRows.map(amounts => renderAmounts(amount, amounts))}
{custom()}
<div className="flex">
{canComment && (
<input
type="text"
placeholder={formatMessage(messages.Comment)}
className="f-grow"
maxLength={handler.canZap && zapType !== ZapType.NonZap ? 250 : handler.maxCommentLength}
onChange={e => setComment(e.target.value)}
/>
)}
</div>
{zapTypeSelector()}
{(amount ?? 0) > 0 && (
<AsyncButton className="zap-action" onClick={() => loadInvoice()}>
<div className="zap-action-container">
<Icon name="zap" />
{target ? (
<FormattedMessage {...messages.ZapTarget} values={{ target, n: formatShort(amount) }} />
) : (
<FormattedMessage {...messages.ZapSats} values={{ n: formatShort(amount) }} />
)}
</div>
</AsyncButton>
)}
</>
);
}
function zapTypeSelector() {
if (!handler || !handler.canZap) return;
const makeTab = (t: ZapType, n: React.ReactNode) => (
<div className={`tab${zapType === t ? " active" : ""}`} onClick={() => setZapType(t)}>
{n}
</div>
);
return (
<>
<h3>
<FormattedMessage defaultMessage="Zap Type" />
</h3>
<div className="tabs mt10">
{makeTab(ZapType.PublicZap, <FormattedMessage defaultMessage="Public" description="Public Zap" />)}
{/*makeTab(ZapType.PrivateZap, "Private")*/}
{makeTab(ZapType.AnonZap, <FormattedMessage defaultMessage="Anon" description="Anonymous Zap" />)}
{makeTab(
ZapType.NonZap,
<FormattedMessage defaultMessage="Non-Zap" description="Non-Zap, Regular LN payment" />
)}
</div>
</>
);
}
function payInvoice() {
if (success || !invoice) return null;
return (
<>
<div className="invoice">
{props.notice && <b className="error">{props.notice}</b>}
{paying ? (
<h4>
<FormattedMessage
defaultMessage="Paying with {wallet}"
values={{
wallet: walletState.config?.info.alias,
}}
/>
...
</h4>
) : (
<QrCode data={invoice} link={`lightning:${invoice}`} />
)}
<div className="actions">
{invoice && (
<>
<div className="copy-action">
<Copy text={invoice} maxSize={26} />
</div>
<button className="wallet-action" type="button" onClick={() => window.open(`lightning:${invoice}`)}>
<FormattedMessage {...messages.OpenWallet} />
</button>
</>
)}
</div>
</div>
</>
);
}
}, [props.targets, props.show]);
function successAction() {
if (!success) return null;
return (
<div className="success-action">
<p className="paid">
<Icon name="check" className="success mr10" />
{success?.description ?? <FormattedMessage {...messages.Paid} />}
<div className="flex f-center">
<p className="flex g12">
<Icon name="check" className="success" />
{success?.description ?? <FormattedMessage defaultMessage="Paid" />}
</p>
{success.url && (
<p>
@ -347,29 +119,289 @@ export default function SendSats(props: SendSatsProps) {
);
}
const defaultTitle = handler?.canZap ? formatMessage(messages.SendZap) : formatMessage(messages.SendSats);
const title = target
? formatMessage(messages.ToTarget, {
action: defaultTitle,
target,
})
: defaultTitle;
function title() {
if (!props.targets) {
return (
<>
<h2>
{zapper?.canZap() ? (
<FormattedMessage defaultMessage="Send zap" />
) : (
<FormattedMessage defaultMessage="Send sats" />
)}
</h2>
</>
);
}
if (props.targets.length === 1 && props.targets[0].name) {
const t = props.targets[0];
const values = {
name: t.name,
};
return (
<>
{t.zap?.pubkey && <ProfileImage pubkey={t.zap.pubkey} showUsername={false} />}
<h2>
{zapper?.canZap() ? (
<FormattedMessage defaultMessage="Send zap to {name}" values={values} />
) : (
<FormattedMessage defaultMessage="Send sats to {name}" values={values} />
)}
</h2>
</>
);
}
if (props.targets.length > 1) {
const total = props.targets.reduce((acc, v) => (acc += v.weight), 0);
return (
<div className="flex-column g12">
<h2>
{zapper?.canZap() ? (
<FormattedMessage defaultMessage="Send zap splits to" />
) : (
<FormattedMessage defaultMessage="Send sats splits to" />
)}
</h2>
<div className="flex g4">
{props.targets.map(v => (
<ProfileImage
pubkey={v.value}
showUsername={false}
imageOverlay={formatShort(Math.floor((amount?.amount ?? 0) * (v.weight / total)))}
/>
))}
</div>
</div>
);
}
}
if (!(props.show ?? false)) return null;
return (
<Modal className="lnurl-modal" onClose={onClose}>
<div className="lnurl-tip" onClick={e => e.stopPropagation()}>
<div className="close" onClick={onClose}>
<Icon name="close" />
<div className="p flex-column g12">
<div className="flex g12">
<div className="flex f-grow">{props.title || title()}</div>
<div onClick={onClose}>
<Icon name="close" />
</div>
</div>
<div className="lnurl-header">
{author && <ProfileImage pubkey={author} showUsername={false} />}
<h2>{props.title || title}</h2>
</div>
{invoiceForm()}
{zapper && !invoice && (
<SendSatsInput
zapper={zapper}
onChange={v => setAmount(v)}
onNextStage={async p => {
const targetsWithComments = (props.targets ?? []).map(v => {
if (p.comment) {
v.memo = p.comment;
}
if (p.type === ZapType.AnonZap && v.zap) {
v.zap = {
...v.zap,
anon: true,
};
} else if (p.type === ZapType.NonZap) {
v.zap = undefined;
}
return v;
});
if (targetsWithComments.length > 0) {
const sends = await zapper.send(wallet, targetsWithComments, p.amount);
if (sends[0].error) {
setError(sends[0].error.message);
} else if (sends.every(a => a.paid)) {
setSuccess({});
} else {
setInvoice(sends);
}
}
}}
/>
)}
{error && <p className="error">{error}</p>}
{payInvoice()}
{invoice && !success && (
<SendSatsInvoice
invoice={invoice}
wallet={wallet}
notice={props.notice}
onInvoicePaid={() => {
setSuccess({});
}}
/>
)}
{successAction()}
</div>
</Modal>
);
}
interface SendSatsInputSelection {
amount: number;
comment?: string;
type: ZapType;
}
function SendSatsInput(props: {
zapper: Zapper;
onChange?: (v: SendSatsInputSelection) => void;
onNextStage: (v: SendSatsInputSelection) => Promise<void>;
}) {
const login = useLogin();
const { formatMessage } = useIntl();
const defaultZapAmount = login.preferences.defaultZapAmount;
const amounts: Record<string, string> = {
[defaultZapAmount.toString()]: "",
"1000": "👍",
"5000": "💜",
"10000": "😍",
"20000": "🤩",
"50000": "🔥",
"100000": "🚀",
"1000000": "🤯",
};
const [comment, setComment] = useState<string>();
const [amount, setAmount] = useState<number>(defaultZapAmount);
const [customAmount, setCustomAmount] = useState<number>(defaultZapAmount);
const [zapType, setZapType] = useState(ZapType.PublicZap);
function getValue() {
return {
amount,
comment,
type: zapType,
} as SendSatsInputSelection;
}
useEffect(() => {
if (props.onChange) {
props.onChange(getValue());
}
}, [amount, comment, zapType]);
function renderAmounts() {
const min = props.zapper.minAmount() / 1000;
const max = props.zapper.maxAmount() / 1000;
const filteredAmounts = Object.entries(amounts).filter(([k]) => Number(k) >= min && Number(k) <= max);
return (
<div className="amounts">
{filteredAmounts.map(([k, v]) => (
<span
className={`sat-amount ${amount === Number(k) ? "active" : ""}`}
key={k}
onClick={() => setAmount(Number(k))}>
{v}&nbsp;
{k === "1000" ? "1K" : formatShort(Number(k))}
</span>
))}
</div>
);
}
function custom() {
const min = props.zapper.minAmount() / 1000;
const max = props.zapper.maxAmount() / 1000;
return (
<div className="flex g8">
<input
type="number"
min={min}
max={max}
className="f-grow"
placeholder={formatMessage(messages.Custom)}
value={customAmount}
onChange={e => setCustomAmount(parseInt(e.target.value))}
/>
<button
className="secondary"
type="button"
disabled={!customAmount}
onClick={() => setAmount(customAmount ?? 0)}>
<FormattedMessage {...messages.Confirm} />
</button>
</div>
);
}
return (
<div className="flex-column g24">
<div className="flex-column g8">
<h3>
<FormattedMessage defaultMessage="Zap amount in sats" />
</h3>
{renderAmounts()}
{custom()}
{props.zapper.maxComment() > 0 && (
<input
type="text"
placeholder={formatMessage(messages.Comment)}
className="f-grow"
maxLength={props.zapper.maxComment()}
onChange={e => setComment(e.target.value)}
/>
)}
</div>
<SendSatsZapTypeSelector zapType={zapType} setZapType={setZapType} />
{(amount ?? 0) > 0 && (
<AsyncButton className="zap-action" onClick={() => props.onNextStage(getValue())}>
<div className="zap-action-container">
<Icon name="zap" />
<FormattedMessage defaultMessage="Zap {n} sats" values={{ n: formatShort(amount) }} />
</div>
</AsyncButton>
)}
</div>
);
}
function SendSatsZapTypeSelector({ zapType, setZapType }: { zapType: ZapType; setZapType: (t: ZapType) => void }) {
const makeTab = (t: ZapType, n: React.ReactNode) => (
<button type="button" className={zapType === t ? "" : "secondary"} onClick={() => setZapType(t)}>
{n}
</button>
);
return (
<div className="flex-column g8">
<h3>
<FormattedMessage defaultMessage="Zap Type" />
</h3>
<div className="flex g8">
{makeTab(ZapType.PublicZap, <FormattedMessage defaultMessage="Public" description="Public Zap" />)}
{/*makeTab(ZapType.PrivateZap, "Private")*/}
{makeTab(ZapType.AnonZap, <FormattedMessage defaultMessage="Anon" description="Anonymous Zap" />)}
{makeTab(
ZapType.NonZap,
<FormattedMessage defaultMessage="Non-Zap" description="Non-Zap, Regular LN payment" />,
)}
</div>
</div>
);
}
function SendSatsInvoice(props: {
invoice: Array<ZapTargetResult>;
wallet?: LNWallet;
notice?: ReactNode;
onInvoicePaid: () => void;
}) {
return (
<div className="flex-column g12 txt-center">
{props.notice && <b className="error">{props.notice}</b>}
{props.invoice.map(v => (
<>
<QrCode data={v.pr} link={`lightning:${v.pr}`} />
<div className="flex-column g12">
<Copy text={v.pr} maxSize={26} className="f-center" />
<a href={`lightning:${v.pr}`}>
<button type="button">
<FormattedMessage defaultMessage="Open Wallet" />
</button>
</a>
</div>
</>
))}
</div>
);
}

View File

@ -10,15 +10,15 @@
background: transparent;
}
.modal.spotlight img,
.modal.spotlight video {
.spotlight img,
.spotlight video {
max-width: 100vw;
max-height: 100vh;
max-height: 99vh;
aspect-ratio: unset;
width: unset;
}
.modal.spotlight .details {
.spotlight .details {
text-align: right;
position: absolute;
top: 28px;
@ -29,16 +29,17 @@
font-weight: 400;
line-height: 24px;
align-items: center;
user-select: none;
}
.modal.spotlight .left {
.spotlight .left {
position: absolute;
left: 24px;
top: 50vh;
transform: rotate(180deg);
}
.modal.spotlight .right {
.spotlight .right {
position: absolute;
right: 24px;
top: 50vh;

View File

@ -37,7 +37,7 @@ export function SpotlightMedia(props: SpotlightMediaProps) {
});
}
return (
<Modal onClose={props.onClose} className="spotlight">
<div className="spotlight">
<ProxyImg src={image} />
<div className="details">
{idx + 1}/{props.images.length}
@ -49,6 +49,14 @@ export function SpotlightMedia(props: SpotlightMediaProps) {
<Icon className="right" name="arrowFront" size={24} onClick={() => inc()} />
</>
)}
</div>
);
}
export function SpotlightMediaModal(props: SpotlightMediaProps) {
return (
<Modal onClose={props.onClose} className="spotlight">
<SpotlightMedia {...props} />
</Modal>
);
}

View File

@ -59,7 +59,7 @@ export default function SuggestedProfiles() {
<FormattedMessage defaultMessage="Provider" />
<select onChange={e => setProvider(Number(e.target.value))}>
<option value={Provider.NostrBand}>nostr.band</option>
<option value={Provider.SemisolDev}>semisol.dev</option>
{/*<option value={Provider.SemisolDev}>semisol.dev</option>*/}
</select>
</div>
{error && <b className="error">{error}</b>}

View File

@ -7,7 +7,6 @@
scrollbar-width: none; /* Firefox */
white-space: nowrap;
gap: 8px;
padding: 16px 12px;
}
.tabs::-webkit-scrollbar {

View File

@ -31,7 +31,7 @@ export const TabElement = ({ t, tab, setTab }: TabElementProps) => {
const Tabs = ({ tabs, tab, setTab }: TabsProps) => {
const horizontalScroll = useHorizontalScroll();
return (
<div className="tabs" ref={horizontalScroll}>
<div className="tabs p" ref={horizontalScroll}>
{tabs.map(t => (
<TabElement tab={tab} setTab={setTab} t={t} />
))}

View File

@ -3,6 +3,13 @@
line-height: 24px;
}
.text .text-frag {
text-overflow: ellipsis;
white-space: pre-wrap;
display: inline;
overflow-wrap: break-word;
}
.text .text-frag > a {
color: var(--highlight);
text-decoration: none;

View File

@ -1,6 +1,6 @@
import "./Text.css";
import { useMemo, useState } from "react";
import { HexKey, ParsedFragment, transformText } from "@snort/system";
import { useState } from "react";
import { HexKey, ParsedFragment } from "@snort/system";
import Invoice from "Element/Invoice";
import Hashtag from "Element/Hashtag";
@ -8,74 +8,106 @@ import HyperText from "Element/HyperText";
import CashuNuts from "Element/CashuNuts";
import RevealMedia from "./RevealMedia";
import { ProxyImg } from "./ProxyImg";
import { SpotlightMedia } from "./SpotlightMedia";
import { SpotlightMediaModal } from "./SpotlightMedia";
import { useTextTransformer } from "Hooks/useTextTransformCache";
export interface TextProps {
id: string;
content: string;
creator: HexKey;
tags: Array<Array<string>>;
disableMedia?: boolean;
disableMediaSpotlight?: boolean;
disableLinkPreview?: boolean;
depth?: number;
truncate?: number;
className?: string;
onClick?: (e: React.MouseEvent) => void;
}
export default function Text({ content, tags, creator, disableMedia, depth, disableMediaSpotlight }: TextProps) {
export default function Text({
id,
content,
tags,
creator,
disableMedia,
depth,
disableMediaSpotlight,
disableLinkPreview,
truncate,
className,
onClick,
}: TextProps) {
const [showSpotlight, setShowSpotlight] = useState(false);
const [imageIdx, setImageIdx] = useState(0);
const elements = useMemo(() => {
return transformText(content, tags);
}, [content]);
const elements = useTextTransformer(id, content, tags);
const images = elements.filter(a => a.type === "media" && a.mimeType?.startsWith("image")).map(a => a.content);
function renderChunk(a: ParsedFragment) {
if (a.type === "media" && !a.mimeType?.startsWith("unknown")) {
if (disableMedia ?? false) {
return (
<a href={a.content} onClick={e => e.stopPropagation()} target="_blank" rel="noreferrer" className="ext">
{a.content}
</a>
);
const renderContent = () => {
let lenCtr = 0;
function renderChunk(a: ParsedFragment) {
if (truncate) {
if (lenCtr > truncate) {
return null;
} else if (lenCtr + a.content.length > truncate) {
lenCtr += a.content.length;
return <div className="text-frag">{a.content.slice(0, truncate - lenCtr)}...</div>;
} else {
lenCtr += a.content.length;
}
}
return (
<RevealMedia
link={a.content}
creator={creator}
onMediaClick={e => {
if (!disableMediaSpotlight) {
e.stopPropagation();
e.preventDefault();
setShowSpotlight(true);
const selected = images.findIndex(b => b === a.content);
setImageIdx(selected === -1 ? 0 : selected);
}
}}
/>
);
} else {
switch (a.type) {
case "invoice":
return <Invoice invoice={a.content} />;
case "hashtag":
return <Hashtag tag={a.content} />;
case "cashu":
return <CashuNuts token={a.content} />;
case "media":
case "link":
return <HyperText link={a.content} depth={depth} />;
case "custom_emoji":
return <ProxyImg src={a.content} size={15} className="custom-emoji" />;
default:
return <div className="text-frag">{a.content}</div>;
if (a.type === "media" && !a.mimeType?.startsWith("unknown")) {
if (disableMedia ?? false) {
return (
<a href={a.content} onClick={e => e.stopPropagation()} target="_blank" rel="noreferrer" className="ext">
{a.content}
</a>
);
}
return (
<RevealMedia
link={a.content}
creator={creator}
onMediaClick={e => {
if (!disableMediaSpotlight) {
e.stopPropagation();
e.preventDefault();
setShowSpotlight(true);
const selected = images.findIndex(b => b === a.content);
setImageIdx(selected === -1 ? 0 : selected);
}
}}
/>
);
} else {
switch (a.type) {
case "invoice":
return <Invoice invoice={a.content} />;
case "hashtag":
return <Hashtag tag={a.content} />;
case "cashu":
return <CashuNuts token={a.content} />;
case "media":
case "link":
return <HyperText link={a.content} depth={depth} showLinkPreview={!(disableLinkPreview ?? false)} />;
case "custom_emoji":
return <ProxyImg src={a.content} size={15} className="custom-emoji" />;
default:
return <div className="text-frag">{a.content}</div>;
}
}
}
}
return elements.map(a => renderChunk(a));
};
return (
<div dir="auto" className="text">
{elements.map(a => renderChunk(a))}
{showSpotlight && <SpotlightMedia images={images} onClose={() => setShowSpotlight(false)} idx={imageIdx} />}
<div dir="auto" className={`text${className ? ` ${className}` : ""}`} onClick={onClick}>
{renderContent()}
{showSpotlight && <SpotlightMediaModal images={images} onClose={() => setShowSpotlight(false)} idx={imageIdx} />}
</div>
);
}

View File

@ -1,3 +1,7 @@
.rta__autocomplete {
z-index: 99;
}
.rta__list {
border: none;
}

View File

@ -33,7 +33,7 @@ const UserItem = (metadata: MetadataCache) => {
return (
<div key={pubkey} className="user-item">
<div className="user-picture">
<Avatar user={metadata} />
<Avatar pubkey={pubkey} user={metadata} />
</div>
<div className="user-details">
<strong>{display_name || rest.name}</strong>

View File

@ -55,54 +55,46 @@
position: absolute;
left: calc(48px / 2 + 16px);
top: 48px;
border-left: 1px solid var(--gray-superdark);
border-left: 1px solid var(--border-color);
height: 100%;
z-index: -1;
z-index: 1;
}
.subthread-container.subthread-mid:not(.subthread-last) .line-container:before {
content: "";
position: absolute;
border-left: 1px solid var(--gray-superdark);
border-left: 1px solid var(--border-color);
left: calc(48px / 2 + 16px);
top: 0;
height: 48px;
z-index: -1;
z-index: 1;
}
.subthread-container.subthread-last .line-container:before {
content: "";
position: absolute;
border-left: 1px solid var(--gray-superdark);
border-left: 1px solid var(--border-color);
left: calc(48px / 2 + 16px);
top: 0;
height: 48px;
z-index: -1;
}
.divider-container {
margin-right: 16px;
z-index: 1;
}
.divider {
height: 1px;
background: var(--gray-superdark);
background: var(--border-color);
}
.divider.divider-small {
margin-left: calc(16px + 61px);
margin-right: 16px;
}
.thread-container .collapsed,
.thread-container .show-more-container {
background: var(--gray-superdark);
min-height: 48px;
}
.thread-container .collapsed {
background-color: var(--gray-superdark);
}
.thread-container .hidden-note {
padding-left: 48px;
}

View File

@ -1,23 +1,15 @@
import "./Thread.css";
import { useMemo, useState, ReactNode } from "react";
import { useMemo, useState, ReactNode, useContext } from "react";
import { useIntl } from "react-intl";
import { useNavigate, useLocation, Link, useParams } from "react-router-dom";
import {
TaggedNostrEvent,
u256,
EventKind,
NostrPrefix,
EventExt,
Thread as ThreadInfo,
parseNostrLink,
} from "@snort/system";
import { useNavigate, Link, useParams } from "react-router-dom";
import { TaggedNostrEvent, u256, NostrPrefix, EventExt, parseNostrLink } from "@snort/system";
import { eventLink, unwrap, getReactions, getAllReactions, findTag } from "SnortUtils";
import { eventLink, getReactions, getAllReactions } from "SnortUtils";
import BackButton from "Element/BackButton";
import Note from "Element/Note";
import NoteGhost from "Element/NoteGhost";
import Collapsed from "Element/Collapsed";
import useThreadFeed from "Feed/ThreadFeed";
import { ThreadContext, ThreadContextWrapper } from "Hooks/useThreadContext";
import messages from "./messages";
@ -213,110 +205,41 @@ const TierThree = ({ active, isLastSubthread, notes, related, chains, onNavigate
);
};
export default function Thread() {
export function ThreadRoute() {
const params = useParams();
const location = useLocation();
const link = parseNostrLink(params.id ?? "", NostrPrefix.Note);
const thread = useThreadFeed(link);
const [currentId, setCurrentId] = useState(link.id);
return (
<ThreadContextWrapper link={link}>
<Thread />
</ThreadContextWrapper>
);
}
export function Thread() {
const thread = useContext(ThreadContext);
const navigate = useNavigate();
const isSingleNote = thread.data?.filter(a => a.kind === EventKind.TextNote).length === 1;
const isSingleNote = thread.chains?.size === 1 && [thread.chains.values].every(v => v.length === 0);
const { formatMessage } = useIntl();
function navigateThread(e: TaggedNostrEvent) {
setCurrentId(e.id);
thread.setCurrent(e.id);
//const link = encodeTLV(e.id, NostrPrefix.Event, e.relays);
}
const chains = useMemo(() => {
const chains = new Map<u256, Array<TaggedNostrEvent>>();
if (thread.data) {
thread.data
?.filter(a => a.kind === EventKind.TextNote)
.sort((a, b) => b.created_at - a.created_at)
.forEach(v => {
const t = EventExt.extractThread(v);
let replyTo = t?.replyTo?.value ?? t?.root?.value;
if (t?.root?.key === "a" && t?.root?.value) {
const parsed = t.root.value.split(":");
replyTo = thread.data?.find(
a => a.kind === Number(parsed[0]) && a.pubkey === parsed[1] && findTag(a, "d") === parsed[2]
)?.id;
}
if (replyTo) {
if (!chains.has(replyTo)) {
chains.set(replyTo, [v]);
} else {
unwrap(chains.get(replyTo)).push(v);
}
}
});
}
return chains;
}, [thread.data]);
// Root is the parent of the current note or the current note if its a root note or the root of the thread
const root = useMemo(() => {
const currentNote =
thread.data?.find(
ne =>
ne.id === currentId ||
(link.type === NostrPrefix.Address && findTag(ne, "d") === currentId && ne.pubkey === link.author)
) ?? (location.state && "sig" in location.state ? (location.state as TaggedNostrEvent) : undefined);
if (currentNote) {
const currentThread = EventExt.extractThread(currentNote);
const isRoot = (ne?: ThreadInfo) => ne === undefined;
if (isRoot(currentThread)) {
return currentNote;
}
const replyTo = currentThread?.replyTo ?? currentThread?.root;
// sometimes the root event ID is missing, and we can only take the happy path if the root event ID exists
if (replyTo) {
if (replyTo.key === "a" && replyTo.value) {
const parsed = replyTo.value.split(":");
return thread.data?.find(
a => a.kind === Number(parsed[0]) && a.pubkey === parsed[1] && findTag(a, "d") === parsed[2]
);
}
if (replyTo.value) {
return thread.data?.find(a => a.id === replyTo.value);
}
}
const possibleRoots = thread.data?.filter(a => {
const thread = EventExt.extractThread(a);
return isRoot(thread);
});
if (possibleRoots) {
// worst case we need to check every possible root to see which one contains the current note as a child
for (const ne of possibleRoots) {
const children = chains.get(ne.id) ?? [];
if (children.find(ne => ne.id === currentId)) {
return ne;
}
}
}
}
}, [thread.data, currentId, location]);
const parent = useMemo(() => {
if (root) {
const currentThread = EventExt.extractThread(root);
if (thread.root) {
const currentThread = EventExt.extractThread(thread.root);
return (
currentThread?.replyTo?.value ??
currentThread?.root?.value ??
(currentThread?.root?.key === "a" && currentThread.root?.value)
);
}
}, [root]);
}, [thread.root]);
const brokenChains = Array.from(chains?.keys()).filter(a => !thread.data?.some(b => b.id === a));
const brokenChains = Array.from(thread.chains?.keys()).filter(a => !thread.data?.some(b => b.id === a));
function renderRoot(note: TaggedNostrEvent) {
const className = `thread-root${isSingleNote ? " thread-root-single" : ""}`;
@ -337,20 +260,20 @@ export default function Thread() {
}
function renderChain(from: u256): ReactNode {
if (!from || !chains) {
if (!from || thread.chains.size === 0) {
return;
}
const replies = chains.get(from);
if (replies && currentId) {
const replies = thread.chains.get(from);
if (replies && thread.current) {
return (
<Subthread
active={currentId}
active={thread.current}
notes={replies}
related={getAllReactions(
thread.data,
replies.map(a => a.id)
replies.map(a => a.id),
)}
chains={chains}
chains={thread.chains}
onNavigate={navigateThread}
/>
);
@ -359,7 +282,7 @@ export default function Thread() {
function goBack() {
if (parent) {
setCurrentId(parent);
thread.setCurrent(parent);
} else {
navigate(-1);
}
@ -379,8 +302,8 @@ export default function Thread() {
<BackButton onClick={goBack} text={parent ? parentText : backText} />
</div>
<div className="main-content">
{root && renderRoot(root)}
{root && renderChain(root.id)}
{thread.root && renderRoot(thread.root)}
{thread.root && renderChain(thread.root.id)}
{brokenChains.length > 0 && <h3>Other replies</h3>}
{brokenChains.map(a => {

View File

@ -2,18 +2,14 @@ import "./Timeline.css";
import { FormattedMessage } from "react-intl";
import { useCallback, useMemo } from "react";
import { useInView } from "react-intersection-observer";
import { TaggedNostrEvent, EventKind, u256, parseZap } from "@snort/system";
import { TaggedNostrEvent, EventKind, u256 } from "@snort/system";
import Icon from "Icons/Icon";
import { dedupeByPubkey, findTag, tagFilterOfTextRepost } from "SnortUtils";
import { dedupeByPubkey, findTag } from "SnortUtils";
import ProfileImage from "Element/ProfileImage";
import useTimelineFeed, { TimelineFeed, TimelineSubject } from "Feed/TimelineFeed";
import Zap from "Element/Zap";
import Note from "Element/Note";
import NoteReaction from "Element/NoteReaction";
import useModeration from "Hooks/useModeration";
import ProfilePreview from "Element/ProfilePreview";
import { UserCache } from "Cache";
import { LiveStreams } from "Element/LiveStreams";
export interface TimelineProps {
@ -28,7 +24,7 @@ export interface TimelineProps {
}
/**
* A list of notes by pubkeys
* A list of notes by "subject"
*/
const Timeline = (props: TimelineProps) => {
const feedOptions = useMemo(() => {
@ -51,7 +47,7 @@ const Timeline = (props: TimelineProps) => {
?.filter(a => (props.postsOnly ? !a.tags.some(b => b[0] === "e") : true))
.filter(a => props.ignoreModeration || !isMuted(a.pubkey));
},
[props.postsOnly, muted, props.ignoreModeration]
[props.postsOnly, muted, props.ignoreModeration],
);
const mainFeed = useMemo(() => {
@ -64,50 +60,16 @@ const Timeline = (props: TimelineProps) => {
(id: u256) => {
return (feed.related ?? []).filter(a => findTag(a, "e") === id);
},
[feed.related]
[feed.related],
);
const liveStreams = useMemo(() => {
return (feed.main ?? []).filter(a => a.kind === EventKind.LiveEvent && findTag(a, "status") === "live");
}, [feed]);
const findRelated = useCallback(
(id?: u256) => {
if (!id) return undefined;
return (feed.related ?? []).find(a => a.id === id);
},
[feed.related]
);
const latestAuthors = useMemo(() => {
return dedupeByPubkey(latestFeed).map(e => e.pubkey);
}, [latestFeed]);
function eventElement(e: TaggedNostrEvent) {
switch (e.kind) {
case EventKind.SetMetadata: {
return <ProfilePreview actions={<></>} pubkey={e.pubkey} className="card" />;
}
case EventKind.Polls:
case EventKind.TextNote: {
const eRef = e.tags.find(tagFilterOfTextRepost(e))?.at(1);
if (eRef) {
return <NoteReaction data={e} key={e.id} root={findRelated(eRef)} />;
}
return (
<Note key={e.id} data={e} related={relatedFeed(e.id)} ignoreModeration={props.ignoreModeration} depth={0} />
);
}
case EventKind.ZapReceipt: {
const zap = parseZap(e, UserCache);
return zap.event ? null : <Zap zap={zap} key={e.id} />;
}
case EventKind.Reaction:
case EventKind.Repost: {
const eRef = findTag(e, "e");
return <NoteReaction data={e} key={e.id} root={findRelated(eRef)} />;
}
}
}
function onShowLatest(scrollToTop = false) {
feed.showLatest();
if (scrollToTop) {
@ -144,7 +106,9 @@ const Timeline = (props: TimelineProps) => {
)}
</>
)}
{mainFeed.map(eventElement)}
{mainFeed.map(e => (
<Note key={e.id} data={e} related={relatedFeed(e.id)} ignoreModeration={props.ignoreModeration} depth={0} />
))}
{(props.loadMore === undefined || props.loadMore === true) && (
<div className="flex f-center">
<button type="button" onClick={() => feed.loadMore()}>

View File

@ -0,0 +1,133 @@
import "./Timeline.css";
import { ReactNode, useCallback, useContext, useMemo, useState, useSyncExternalStore } from "react";
import { FormattedMessage } from "react-intl";
import { TaggedNostrEvent, EventKind, u256, NostrEvent } from "@snort/system";
import { unixNow } from "@snort/shared";
import { SnortContext } from "@snort/system-react";
import { useInView } from "react-intersection-observer";
import { dedupeByPubkey, findTag, orderDescending } from "SnortUtils";
import Note from "Element/Note";
import useModeration from "Hooks/useModeration";
import { FollowsFeed } from "Cache";
import { LiveStreams } from "Element/LiveStreams";
import { useReactions } from "Feed/FeedReactions";
import AsyncButton from "./AsyncButton";
import useLogin from "Hooks/useLogin";
import ProfileImage from "Element/ProfileImage";
import Icon from "Icons/Icon";
export interface TimelineFollowsProps {
postsOnly: boolean;
liveStreams?: boolean;
noteFilter?: (ev: NostrEvent) => boolean;
noteRenderer?: (ev: NostrEvent) => ReactNode;
}
/**
* A list of notes by "subject"
*/
const TimelineFollows = (props: TimelineFollowsProps) => {
const [latest, setLatest] = useState(unixNow());
const feed = useSyncExternalStore(
cb => FollowsFeed.hook(cb, "*"),
() => FollowsFeed.snapshot(),
);
const reactions = useReactions(
"follows-feed-reactions",
feed.map(a => a.id),
);
const system = useContext(SnortContext);
const login = useLogin();
const { muted, isMuted } = useModeration();
const { ref, inView } = useInView();
const sortedFeed = useMemo(() => orderDescending(feed), [feed]);
const filterPosts = useCallback(
function <T extends NostrEvent>(nts: Array<T>) {
const a = nts.filter(a => a.kind !== EventKind.LiveEvent);
return a
?.filter(a => (props.postsOnly ? !a.tags.some(b => b[0] === "e") : true))
.filter(a => !isMuted(a.pubkey) && login.follows.item.includes(a.pubkey) && (props.noteFilter?.(a) ?? true));
},
[props.postsOnly, muted, login.follows.timestamp],
);
const mainFeed = useMemo(() => {
return filterPosts((sortedFeed ?? []).filter(a => a.created_at <= latest));
}, [sortedFeed, filterPosts, latest, login.follows.timestamp]);
const latestFeed = useMemo(() => {
return filterPosts((sortedFeed ?? []).filter(a => a.created_at > latest));
}, [sortedFeed, latest]);
const relatedFeed = useCallback(
(id: u256) => {
return (reactions?.data ?? []).filter(a => findTag(a, "e") === id);
},
[reactions],
);
const liveStreams = useMemo(() => {
return (sortedFeed ?? []).filter(a => a.kind === EventKind.LiveEvent && findTag(a, "status") === "live");
}, [sortedFeed]);
const latestAuthors = useMemo(() => {
return dedupeByPubkey(latestFeed).map(e => e.pubkey);
}, [latestFeed]);
function onShowLatest(scrollToTop = false) {
setLatest(unixNow());
if (scrollToTop) {
window.scrollTo(0, 0);
}
}
return (
<>
{(props.liveStreams ?? true) && <LiveStreams evs={liveStreams} />}
{latestFeed.length > 0 && (
<>
<div className="card latest-notes" onClick={() => onShowLatest()} ref={ref}>
{latestAuthors.slice(0, 3).map(p => {
return <ProfileImage pubkey={p} showUsername={false} link={""} />;
})}
<FormattedMessage
defaultMessage="{n} new {n, plural, =1 {note} other {notes}}"
values={{ n: latestFeed.length }}
/>
<Icon name="arrowUp" />
</div>
{!inView && (
<div className="card latest-notes latest-notes-fixed pointer fade-in" onClick={() => onShowLatest(true)}>
{latestAuthors.slice(0, 3).map(p => {
return <ProfileImage pubkey={p} showUsername={false} link={""} />;
})}
<FormattedMessage
defaultMessage="{n} new {n, plural, =1 {note} other {notes}}"
values={{ n: latestFeed.length }}
/>
<Icon name="arrowUp" />
</div>
)}
</>
)}
{mainFeed.map(
a =>
props.noteRenderer?.(a) ?? (
<Note data={a as TaggedNostrEvent} related={relatedFeed(a.id)} key={a.id} depth={0} />
),
)}
<div className="flex f-center p">
<AsyncButton
onClick={async () => {
await FollowsFeed.loadMore(system, login, sortedFeed[sortedFeed.length - 1].created_at);
}}>
<FormattedMessage defaultMessage="Load more" />
</AsyncButton>
</div>
</>
);
};
export default TimelineFollows;

View File

@ -22,8 +22,8 @@ export default function TrendingUsers() {
if (!userList) return <PageSpinner />;
return (
<>
<div className="p">
<FollowListBase pubkeys={userList} showAbout={true} />
</>
</div>
);
}

View File

@ -28,7 +28,7 @@ const Zap = ({ zap, showZapped = true }: { zap: ParsedZap; showZapped?: boolean
</div>
{(content?.length ?? 0) > 0 && sender && (
<div className="body">
<Text creator={sender} content={unwrap(content)} tags={[]} />
<Text id={zap.id} creator={sender} content={unwrap(content)} tags={[]} />
</div>
)}
</div>

View File

@ -5,6 +5,7 @@ import { useUserProfile } from "@snort/system-react";
import SendSats from "Element/SendSats";
import Icon from "Icons/Icon";
import { ZapTarget } from "Zapper";
const ZapButton = ({
pubkey,
@ -29,11 +30,17 @@ const ZapButton = ({
{children}
</div>
<SendSats
target={profile?.display_name || profile?.name}
lnurl={service}
targets={[
{
type: "lnurl",
value: service,
weight: 1,
name: profile?.display_name || profile?.name,
zap: { pubkey: pubkey },
} as ZapTarget,
]}
show={zap}
onClose={() => setZap(false)}
author={pubkey}
note={event}
/>
</>

View File

@ -1,12 +1,15 @@
import "./ZapGoal.css";
import { CSSProperties, useState } from "react";
import { NostrEvent, NostrPrefix, createNostrLink } from "@snort/system";
import useZapsFeed from "Feed/ZapsFeed";
import { formatShort } from "Number";
import { findTag } from "SnortUtils";
import { CSSProperties } from "react";
import ZapButton from "./ZapButton";
import Icon from "Icons/Icon";
import SendSats from "./SendSats";
import { Zapper } from "Zapper";
export function ZapGoal({ ev }: { ev: NostrEvent }) {
const [zap, setZap] = useState(false);
const zaps = useZapsFeed(createNostrLink(NostrPrefix.Note, ev.id));
const target = Number(findTag(ev, "amount"));
const amount = zaps.reduce((acc, v) => (acc += v.amount * 1000), 0);
@ -16,7 +19,10 @@ export function ZapGoal({ ev }: { ev: NostrEvent }) {
<div className="zap-goal card">
<div className="flex f-space">
<h2>{ev.content}</h2>
<ZapButton pubkey={ev.pubkey} event={ev.id} />
<div className="zap-button flex" onClick={() => setZap(true)}>
<Icon name="zap" size={15} />
</div>
<SendSats targets={Zapper.fromEvent(ev)} show={zap} onClose={() => setZap(false)} />
</div>
<div className="flex f-space">

View File

@ -17,7 +17,7 @@ export default function ZapstrEmbed({ ev }: { ev: NostrEvent }) {
ev.tags.find(a => a[0] === "d")?.[1] ?? "",
undefined,
ev.kind,
ev.pubkey
ev.pubkey,
);
return (
<>

View File

@ -29,7 +29,6 @@ export default defineMessages({
PayInvoice: { defaultMessage: "Pay Invoice" },
Expired: { defaultMessage: "Expired" },
Pay: { defaultMessage: "Pay" },
Paid: { defaultMessage: "Paid" },
Loading: { defaultMessage: "Loading..." },
Logout: { defaultMessage: "Logout" },
ShowMore: { defaultMessage: "Show more" },
@ -64,14 +63,8 @@ export default defineMessages({
InvoiceFail: { defaultMessage: "Failed to load invoice" },
Custom: { defaultMessage: "Custom" },
Confirm: { defaultMessage: "Confirm" },
ZapAmount: { defaultMessage: "Zap amount in sats" },
Comment: { defaultMessage: "Comment" },
ZapTarget: { defaultMessage: "Zap {target} {n} sats" },
ZapSats: { defaultMessage: "Zap {n} sats" },
OpenWallet: { defaultMessage: "Open Wallet" },
SendZap: { defaultMessage: "Send zap" },
SendSats: { defaultMessage: "Send sats" },
ToTarget: { defaultMessage: "{action} to {target}" },
ShowReplies: { defaultMessage: "Show replies" },
TooShort: { defaultMessage: "name too short" },
TooLong: { defaultMessage: "name too long" },

View File

@ -0,0 +1,18 @@
import { EventKind, NoteCollection, RequestBuilder } from "@snort/system";
import { useRequestBuilder } from "@snort/system-react";
import useLogin from "Hooks/useLogin";
import { useMemo } from "react";
export function useArticles() {
const { publicKey, follows } = useLogin();
const sub = useMemo(() => {
if (!publicKey) return null;
const rb = new RequestBuilder(`articles:${publicKey}`);
rb.withFilter().kinds([EventKind.LongFormTextNote]).authors(follows.item).limit(20);
return rb;
}, [follows.timestamp]);
return useRequestBuilder(NoteCollection, sub);
}

View File

@ -23,7 +23,7 @@ export default function useProfileBadges(pubkey?: HexKey) {
if (profileBadges.data) {
return chunks(
profileBadges.data.tags.filter(t => t[0] === "a" || t[0] === "e"),
2
2,
).reduce((acc, [a, e]) => {
return {
...acc,
@ -44,7 +44,7 @@ export default function useProfileBadges(pubkey?: HexKey) {
}
return acc;
},
{ pubkeys: [], ds: [] } as BadgeAwards
{ pubkeys: [], ds: [] } as BadgeAwards,
) as BadgeAwards;
}, [profile]);
@ -77,7 +77,7 @@ export default function useProfileBadges(pubkey?: HexKey) {
})
.filter(
({ award, badge }) =>
badge && award.pubkey === badge.pubkey && award.tags.find(t => t[0] === "p" && t[1] === pubkey)
badge && award.pubkey === badge.pubkey && award.tags.find(t => t[0] === "p" && t[1] === pubkey),
)
.map(({ badge }) => unwrap(badge));
}

View File

@ -1,10 +1,10 @@
import { useMemo } from "react";
import { NostrPrefix, RequestBuilder, ReplaceableNoteStore, NostrLink } from "@snort/system";
import { NostrPrefix, RequestBuilder, ReplaceableNoteStore, NostrLink, NoteCollection } from "@snort/system";
import { useRequestBuilder } from "@snort/system-react";
import { unwrap } from "SnortUtils";
export default function useEventFeed(link: NostrLink) {
export function useEventFeed(link: NostrLink) {
const sub = useMemo(() => {
const b = new RequestBuilder(`event:${link.id.slice(0, 12)}`);
if (link.type === NostrPrefix.Address) {
@ -29,3 +29,31 @@ export default function useEventFeed(link: NostrLink) {
return useRequestBuilder(ReplaceableNoteStore, sub);
}
export function useEventsFeed(id: string, links: Array<NostrLink>) {
const sub = useMemo(() => {
const b = new RequestBuilder(`events:${id}`);
for (const l of links) {
if (l.type === NostrPrefix.Address) {
const f = b.withFilter().tag("d", [l.id]);
if (l.author) {
f.authors([unwrap(l.author)]);
}
if (l.kind) {
f.kinds([unwrap(l.kind)]);
}
} else {
const f = b.withFilter().ids([l.id]);
if (l.relays) {
l.relays.slice(0, 2).forEach(r => f.relay(r));
}
if (l.author) {
f.authors([l.author]);
}
}
}
return b;
}, [id, links]);
return useRequestBuilder(NoteCollection, sub);
}

View File

@ -13,7 +13,7 @@ export function useReactions(subId: string, ids: Array<string>, others?: (rb: Re
.kinds(
pref.enableReactions
? [EventKind.Reaction, EventKind.Repost, EventKind.ZapReceipt]
: [EventKind.ZapReceipt, EventKind.Repost]
: [EventKind.ZapReceipt, EventKind.Repost],
)
.tag("e", ids);
}

View File

@ -14,7 +14,7 @@ export default function useFollowersFeed(pubkey?: HexKey) {
const followers = useMemo(() => {
const contactLists = followersFeed.data?.filter(
a => a.kind === EventKind.ContactList && a.tags.some(b => b[0] === "p" && b[1] === pubkey)
a => a.kind === EventKind.ContactList && a.tags.some(b => b[0] === "p" && b[1] === pubkey),
);
return [...new Set(contactLists?.map(a => a.pubkey))];
}, [followersFeed, pubkey]);

View File

@ -12,9 +12,10 @@ import { addSubscription, setBlocked, setBookmarked, setFollows, setMuted, setPi
import { SnortPubKey } from "Const";
import { SubscriptionEvent } from "Subscription";
import useRelaysFeedFollows from "./RelaysFeedFollows";
import { GiftsCache, Notifications, UserRelays } from "Cache";
import { FollowsFeed, GiftsCache, Notifications, UserRelays } from "Cache";
import { System } from "index";
import { Nip29Chats, Nip4Chats } from "chat";
import { Nip4Chats } from "chat";
import { useRefreshFeedCache } from "Hooks/useRefreshFeedcache";
/**
* Managed loading data for the current logged in user
@ -25,6 +26,12 @@ export default function useLoginFeed() {
const { isMuted } = useModeration();
const publisher = useEventPublisher();
useRefreshFeedCache(Notifications, true);
useRefreshFeedCache(FollowsFeed, true);
if (publisher?.supports("nip44")) {
useRefreshFeedCache(GiftsCache, true);
}
const subLogin = useMemo(() => {
if (!pubKey) return null;
@ -38,10 +45,8 @@ export default function useLoginFeed() {
.authors([bech32ToHex(SnortPubKey)])
.tag("p", [pubKey])
.limit(1);
b.withFilter().kinds([EventKind.GiftWrap]).tag("p", [pubKey]).since(GiftsCache.newest());
b.add(Nip4Chats.subscription(pubKey));
Notifications.buildSub(login, b);
return b;
}, [pubKey]);
@ -73,17 +78,14 @@ export default function useLoginFeed() {
}
const pTags = contactList.tags.filter(a => a[0] === "p").map(a => a[1]);
setFollows(login, pTags, contactList.created_at * 1000);
FollowsFeed.backFillIfMissing(System, pTags);
}
Nip4Chats.onEvent(loginFeed.data);
Nip29Chats.onEvent(loginFeed.data);
Notifications.onEvent(loginFeed.data);
const giftWraps = loginFeed.data.filter(a => a.kind === EventKind.GiftWrap);
GiftsCache.onEvent(giftWraps, publisher);
const subs = loginFeed.data.filter(
a => a.kind === EventKind.SnortSubscriptions && a.pubkey === bech32ToHex(SnortPubKey)
a => a.kind === EventKind.SnortSubscriptions && a.pubkey === bech32ToHex(SnortPubKey),
);
Promise.all(
subs.map(async a => {
@ -95,7 +97,7 @@ export default function useLoginFeed() {
...ex,
} as SubscriptionEvent;
}
})
}),
).then(a => addSubscription(login, ...a.filter(a => a !== undefined).map(unwrap)));
}
}, [loginFeed, publisher]);
@ -104,7 +106,7 @@ export default function useLoginFeed() {
useEffect(() => {
if (loginFeed.data) {
const replies = loginFeed.data.filter(
a => a.kind === EventKind.TextNote && !isMuted(a.pubkey) && a.created_at > readNotifications
a => a.kind === EventKind.TextNote && !isMuted(a.pubkey) && a.created_at > readNotifications,
);
replies.forEach(async nx => {
const n = await makeNotification(nx);

View File

@ -35,11 +35,11 @@ export default function useThreadFeed(link: NostrLink) {
.kinds(
pref.enableReactions
? [EventKind.Reaction, EventKind.TextNote, EventKind.Repost, EventKind.ZapReceipt]
: [EventKind.TextNote, EventKind.ZapReceipt, EventKind.Repost]
: [EventKind.TextNote, EventKind.ZapReceipt, EventKind.Repost],
)
.tag(
"e",
allEvents.map(a => a.id)
allEvents.map(a => a.id),
);
}
if (trackingATags.length > 0) {
@ -50,7 +50,7 @@ export default function useThreadFeed(link: NostrLink) {
.authors(parsed.map(a => a[1]))
.tag(
"d",
parsed.map(a => a[2])
parsed.map(a => a[2]),
);
sub.withFilter().tag("a", trackingATags);
}
@ -85,7 +85,7 @@ export default function useThreadFeed(link: NostrLink) {
id: b[1],
relay: b[2],
};
})
}),
)
.flat();
const eTagsMissing = eTags.filter(a => !mainNotes.some(b => b.id === a.id));

View File

@ -1,8 +1,9 @@
import { useCallback, useEffect, useMemo } from "react";
import { EventKind, NoteCollection, RequestBuilder } from "@snort/system";
import { useRequestBuilder } from "@snort/system-react";
import { unixNow } from "@snort/shared";
import { unixNow, unwrap, tagFilterOfTextRepost } from "SnortUtils";
import { unwrap, tagFilterOfTextRepost } from "SnortUtils";
import useTimelineWindow from "Hooks/useTimelineWindow";
import useLogin from "Hooks/useLogin";
import { SearchRelays } from "Const";
@ -42,7 +43,7 @@ export default function useTimelineFeed(subject: TimelineSubject, options: Timel
.kinds(
subject.type === "profile_keyword"
? [EventKind.SetMetadata]
: [EventKind.TextNote, EventKind.Repost, EventKind.Polls]
: [EventKind.TextNote, EventKind.Repost, EventKind.Polls],
);
if (subject.relay) {
@ -148,7 +149,7 @@ export default function useTimelineFeed(subject: TimelineSubject, options: Timel
.map(a => unwrap(a)[1]);
const repostsByKind1 = main.data
.filter(
a => (a.kind === EventKind.Repost || a.kind === EventKind.TextNote) && a.tags.some(tagFilterOfTextRepost(a))
a => (a.kind === EventKind.Repost || a.kind === EventKind.TextNote) && a.tags.some(tagFilterOfTextRepost(a)),
)
.map(a => a.tags.find(tagFilterOfTextRepost(a)))
.filter(a => a)

View File

@ -21,7 +21,7 @@ export default function useImgProxy() {
const result = hmacSha256(
utils.hexToBytes(unwrap(settings).key),
utils.hexToBytes(unwrap(settings).salt),
te.encode(u)
te.encode(u),
);
return urlSafe(base64.encode(result));
}

View File

@ -15,7 +15,7 @@ export function useInteractionCache(pubkey?: HexKey, event?: u256) {
const data =
useSyncExternalStore(
c => InteractionCache.hook(c, id),
() => InteractionCache.snapshot().find(a => a.id === id)
() => InteractionCache.snapshot().find(a => a.id === id),
) || EmptyInteraction;
return {
data: data,

View File

@ -4,6 +4,6 @@ import { useSyncExternalStore } from "react";
export default function useLogin() {
return useSyncExternalStore(
s => LoginStore.hook(s),
() => LoginStore.snapshot()
() => LoginStore.snapshot(),
);
}

View File

@ -16,6 +16,7 @@ export default function useLoginHandler() {
defaultMessage:
"Can't login with private key on an insecure connection, please use a Nostr key manager extension instead",
});
// private key logins
if (key.startsWith("nsec")) {
if (!hasSubtleCrypto) {
throw new Error(insecureMsg);
@ -26,12 +27,6 @@ export default function useLoginHandler() {
} else {
throw new Error("INVALID PRIVATE KEY");
}
} else if (key.startsWith("npub")) {
const hexKey = bech32ToHex(key);
LoginStore.loginWithPubkey(hexKey, LoginSessionType.PublicKey);
} else if (key.match(EmailRegex)) {
const hexKey = await getNip05PubKey(key);
LoginStore.loginWithPubkey(hexKey, LoginSessionType.PublicKey);
} else if (key.match(MnemonicRegex)?.length === 24) {
if (!hasSubtleCrypto) {
throw new Error(insecureMsg);
@ -44,6 +39,15 @@ export default function useLoginHandler() {
throw new Error(insecureMsg);
}
LoginStore.loginWithPrivateKey(key);
}
// public key logins
if (key.startsWith("npub")) {
const hexKey = bech32ToHex(key);
LoginStore.loginWithPubkey(hexKey, LoginSessionType.PublicKey);
} else if (key.match(EmailRegex)) {
const hexKey = await getNip05PubKey(key);
LoginStore.loginWithPubkey(hexKey, LoginSessionType.PublicKey);
} else if (key.startsWith("bunker://")) {
const nip46 = new Nip46Signer(key);
await nip46.init();

View File

@ -0,0 +1,22 @@
import { System } from "index";
import { useEffect } from "react";
import useLogin from "./useLogin";
export function useLoginRelays() {
const { relays } = useLogin();
useEffect(() => {
if (relays) {
(async () => {
for (const [k, v] of Object.entries(relays.item)) {
await System.ConnectToRelay(k, v);
}
for (const v of System.Sockets) {
if (!relays.item[v.address] && !v.ephemeral) {
System.DisconnectRelay(v.address);
}
}
})();
}
}, [relays]);
}

View File

@ -0,0 +1,52 @@
import { SnortContext } from "@snort/system-react";
import { useContext, useEffect, useMemo } from "react";
import { NoopStore, RequestBuilder, TaggedNostrEvent } from "@snort/system";
import { unwrap } from "@snort/shared";
import { RefreshFeedCache } from "Cache/RefreshFeedCache";
import useLogin from "./useLogin";
export function useRefreshFeedCache<T>(c: RefreshFeedCache<T>, leaveOpen = false) {
const system = useContext(SnortContext);
const login = useLogin();
const sub = useMemo(() => {
if (login) {
const rb = new RequestBuilder(`using-${c.name}`);
rb.withOptions({
leaveOpen,
});
c.buildSub(login, rb);
return rb;
}
return undefined;
}, [login]);
useEffect(() => {
if (sub) {
const q = system.Query(NoopStore, sub);
let t: ReturnType<typeof setTimeout> | undefined;
let tBuf: Array<TaggedNostrEvent> = [];
const releaseOnEvent = q.feed.onEvent(evs => {
if (!t) {
tBuf = [...evs];
t = setTimeout(() => {
t = undefined;
c.onEvent(tBuf, unwrap(login.publisher));
}, 100);
} else {
tBuf.push(...evs);
}
});
q.uncancel();
return () => {
q.cancel();
q.sendClose();
releaseOnEvent();
};
}
return () => {
// noop
};
}, [sub]);
}

View File

@ -0,0 +1,15 @@
import { ParsedFragment, transformText } from "@snort/system";
const TextCache = new Map<string, Array<ParsedFragment>>();
export function transformTextCached(id: string, content: string, tags: Array<Array<string>>) {
const cached = TextCache.get(id);
if (cached) return cached;
const newCache = transformText(content, tags);
TextCache.set(id, newCache);
return newCache;
}
export function useTextTransformer(id: string, content: string, tags: Array<Array<string>>) {
return transformTextCached(id, content, tags);
}

View File

@ -0,0 +1,31 @@
import { useEffect } from "react";
import useLogin from "./useLogin";
export function useTheme() {
const { preferences } = useLogin();
function setTheme(theme: "light" | "dark") {
const elm = document.documentElement;
if (theme === "light" && !elm.classList.contains("light")) {
elm.classList.add("light");
} else if (theme === "dark" && elm.classList.contains("light")) {
elm.classList.remove("light");
}
}
useEffect(() => {
const osTheme = window.matchMedia("(prefers-color-scheme: light)");
setTheme(
preferences.theme === "system" && osTheme.matches ? "light" : preferences.theme === "light" ? "light" : "dark",
);
osTheme.onchange = e => {
if (preferences.theme === "system") {
setTheme(e.matches ? "light" : "dark");
}
};
return () => {
osTheme.onchange = null;
};
}, [preferences.theme]);
}

View File

@ -0,0 +1,116 @@
import { unwrap } from "@snort/shared";
import {
EventExt,
EventKind,
NostrLink,
NostrPrefix,
TaggedNostrEvent,
u256,
Thread as ThreadInfo,
} from "@snort/system";
import useThreadFeed from "Feed/ThreadFeed";
import { findTag } from "SnortUtils";
import { ReactNode, createContext, useMemo, useState } from "react";
import { useLocation } from "react-router-dom";
export interface ThreadContext {
current: string;
root?: TaggedNostrEvent;
chains: Map<string, Array<TaggedNostrEvent>>;
data: Array<TaggedNostrEvent>;
setCurrent: (i: string) => void;
}
export const ThreadContext = createContext({} as ThreadContext);
export function ThreadContextWrapper({ link, children }: { link: NostrLink; children?: ReactNode }) {
const location = useLocation();
const [currentId, setCurrentId] = useState(link.id);
const thread = useThreadFeed(link);
const chains = useMemo(() => {
const chains = new Map<u256, Array<TaggedNostrEvent>>();
if (thread.data) {
thread.data
?.filter(a => a.kind === EventKind.TextNote)
.sort((a, b) => b.created_at - a.created_at)
.forEach(v => {
const t = EventExt.extractThread(v);
let replyTo = t?.replyTo?.value ?? t?.root?.value;
if (t?.root?.key === "a" && t?.root?.value) {
const parsed = t.root.value.split(":");
replyTo = thread.data?.find(
a => a.kind === Number(parsed[0]) && a.pubkey === parsed[1] && findTag(a, "d") === parsed[2],
)?.id;
}
if (replyTo) {
if (!chains.has(replyTo)) {
chains.set(replyTo, [v]);
} else {
unwrap(chains.get(replyTo)).push(v);
}
}
});
}
return chains;
}, [thread.data]);
// Root is the parent of the current note or the current note if its a root note or the root of the thread
const root = useMemo(() => {
const currentNote =
thread.data?.find(
ne =>
ne.id === currentId ||
(link.type === NostrPrefix.Address && findTag(ne, "d") === currentId && ne.pubkey === link.author),
) ?? (location.state && "sig" in location.state ? (location.state as TaggedNostrEvent) : undefined);
if (currentNote) {
const currentThread = EventExt.extractThread(currentNote);
const isRoot = (ne?: ThreadInfo) => ne === undefined;
if (isRoot(currentThread)) {
return currentNote;
}
const replyTo = currentThread?.replyTo ?? currentThread?.root;
// sometimes the root event ID is missing, and we can only take the happy path if the root event ID exists
if (replyTo) {
if (replyTo.key === "a" && replyTo.value) {
const parsed = replyTo.value.split(":");
return thread.data?.find(
a => a.kind === Number(parsed[0]) && a.pubkey === parsed[1] && findTag(a, "d") === parsed[2],
);
}
if (replyTo.value) {
return thread.data?.find(a => a.id === replyTo.value);
}
}
const possibleRoots = thread.data?.filter(a => {
const thread = EventExt.extractThread(a);
return isRoot(thread);
});
if (possibleRoots) {
// worst case we need to check every possible root to see which one contains the current note as a child
for (const ne of possibleRoots) {
const children = chains.get(ne.id) ?? [];
if (children.find(ne => ne.id === currentId)) {
return ne;
}
}
}
}
}, [thread.data, currentId, location]);
const ctxValue = useMemo(() => {
return {
current: currentId,
root,
chains,
data: thread.data,
setCurrent: v => setCurrentId(v),
} as ThreadContext;
}, [root, chains]);
return <ThreadContext.Provider value={ctxValue}>{children}</ThreadContext.Provider>;
}

View File

@ -2,7 +2,13 @@ import IconProps from "./IconProps";
import "./Spinner.css";
const Spinner = (props: IconProps) => (
<svg width="20" height="20" stroke="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" {...props}>
<svg
width={props.width ?? 20}
height={props.height ?? 20}
stroke="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
{...props}>
<g className="spinner_V8m1">
<circle cx="10" cy="10" r="7.5" fill="none" strokeWidth="3"></circle>
</g>

View File

@ -56,6 +56,21 @@ const getMessages = (locale: string) => {
case "fa-IR":
case "fa":
return (await import("translations/fa_IR.json")).default;
case "th-TH":
case "th":
return (await import("translations/th_TH.json")).default;
case "pt-BR":
case "pt":
return (await import("translations/pt_BR.json")).default;
case "sw-KE":
case "sw":
return (await import("translations/sw_KE.json")).default;
case "nl-NL":
case "nl":
return (await import("translations/nl_NL.json")).default;
case "fi-FI":
case "fi":
return (await import("translations/fi_FI.json")).default;
case DefaultLocale:
case "en":
return enMessages;

View File

@ -1,13 +1,15 @@
import { HexKey, RelaySettings, EventPublisher } from "@snort/system";
import { unixNowMs } from "@snort/shared";
import * as secp from "@noble/curves/secp256k1";
import * as utils from "@noble/curves/abstract/utils";
import { DefaultRelays, SnortPubKey } from "Const";
import { LoginStore, UserPreferences, LoginSession } from "Login";
import { generateBip39Entropy, entropyToPrivateKey } from "nip6";
import { bech32ToHex, dedupeById, randomSample, sanitizeRelayUrl, unixNowMs, unwrap } from "SnortUtils";
import { bech32ToHex, dedupeById, randomSample, sanitizeRelayUrl, unwrap } from "SnortUtils";
import { SubscriptionEvent } from "Subscription";
import { System } from "index";
import { Chats, FollowsFeed, GiftsCache, Notifications } from "Cache";
export function setRelays(state: LoginSession, relays: Record<string, RelaySettings>, createdAt: number) {
if (state.relays.timestamp >= createdAt) {
@ -41,8 +43,10 @@ export function updatePreferences(state: LoginSession, p: UserPreferences) {
export function logout(k: HexKey) {
LoginStore.removeSession(k);
//TODO: delete giftwarps for:k
//TODO: delete notifications for:k
GiftsCache.clear();
Notifications.clear();
FollowsFeed.clear();
Chats.clear();
}
export function markNotificationsRead(state: LoginSession) {

View File

@ -15,6 +15,7 @@ export enum LoginSessionType {
PublicKey = "public_key",
Nip7 = "nip7",
Nip46 = "nip46",
Nip7os = "nip7_os",
}
export interface LoginSession {

View File

@ -7,6 +7,7 @@ import { deepClone, sanitizeRelayUrl, unwrap, ExternalStore } from "@snort/share
import { DefaultRelays } from "Const";
import { LoginSession, LoginSessionType } from "Login";
import { DefaultPreferences, UserPreferences } from "./Preferences";
import { Nip7OsSigner } from "./Nip7OsSigner";
const AccountStoreKey = "sessions";
const LoggedOut = {
@ -95,7 +96,7 @@ export class MultiAccountStore extends ExternalStore<LoginSession> {
type: LoginSessionType,
relays?: Record<string, RelaySettings>,
remoteSignerRelays?: Array<string>,
privateKey?: string
privateKey?: string,
) {
if (this.#accounts.has(key)) {
throw new Error("Already logged in with this pubkey");
@ -146,6 +147,12 @@ export class MultiAccountStore extends ExternalStore<LoginSession> {
},
preferences: deepClone(DefaultPreferences),
} as LoginSession;
if ("nostr_os" in window && window.nostr_os) {
window.nostr_os.saveKey(key);
newSession.type = LoginSessionType.Nip7os;
newSession.privateKey = undefined;
}
newSession.publisher = this.#createPublisher(newSession);
this.#accounts.set(pubKey, newSession);
@ -190,6 +197,9 @@ export class MultiAccountStore extends ExternalStore<LoginSession> {
const nip46 = new Nip46Signer(`bunker://${unwrap(l.publicKey)}?${[...relayArgs].join("&")}`, inner);
return new EventPublisher(nip46, unwrap(l.publicKey));
}
case LoginSessionType.Nip7os: {
return new EventPublisher(new Nip7OsSigner(), unwrap(l.publicKey));
}
default: {
if (l.publicKey) {
return new EventPublisher(new Nip7Signer(), l.publicKey);

View File

@ -0,0 +1,48 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { EventSigner, NostrEvent } from "@snort/system";
import { Nip7os } from "Login";
export class Nip7OsSigner implements EventSigner {
#interface: Nip7os;
constructor() {
if ("nostr_os" in window && window.nostr_os) {
this.#interface = window.nostr_os;
} else {
throw new Error("Nost OS extension not available");
}
}
get supports(): string[] {
return ["nip04"];
}
init(): Promise<void> {
return Promise.resolve();
}
getPubKey(): string | Promise<string> {
return this.#interface.getPublicKey();
}
nip4Encrypt(content: string, key: string): Promise<string> {
return Promise.resolve(this.#interface.nip04_encrypt(content, key));
}
nip4Decrypt(content: string, otherKey: string): Promise<string> {
return Promise.resolve(this.#interface.nip04_decrypt(content, otherKey));
}
nip44Encrypt(content: string, key: string): Promise<string> {
throw new Error("Method not implemented.");
}
nip44Decrypt(content: string, otherKey: string): Promise<string> {
throw new Error("Method not implemented.");
}
sign(ev: NostrEvent): Promise<NostrEvent> {
const ret = this.#interface.signEvent(JSON.stringify(ev));
return Promise.resolve(JSON.parse(ret) as NostrEvent);
}
}

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