16 Commits

Author SHA1 Message Date
4ce73343ac Update dependency eslint to v10.0.2
All checks were successful
continuous-integration/drone/pr Build is passing
2026-02-24 22:08:36 +00:00
2ec7705b4b update thresholds
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-24 12:10:45 +01:00
5877d90f07 fix eslint ver
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-24 11:23:55 +01:00
2b96277bec fix yml
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-24 11:21:37 +01:00
063d1073de add code analysis step
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-24 11:19:44 +01:00
d7e144620e add unit tests
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-24 11:14:24 +01:00
7e938138ff fix sidebar width, v0.1.5
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2026-02-24 11:02:17 +01:00
62590c34d1 fix ci
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2026-02-24 10:55:39 +01:00
01bbaebe5b expose sidebars sizing, v0.1.4
Some checks failed
continuous-integration/drone/push Build encountered an error
2026-02-24 10:53:29 +01:00
83d9bc78f0 update ci
Some checks failed
continuous-integration/drone/push Build encountered an error
2026-02-24 10:16:31 +01:00
ef084b893b fix ci
Some checks failed
continuous-integration/drone/push Build encountered an error
2026-02-23 23:51:24 +01:00
a382bfee01 update drone
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-23 23:34:16 +01:00
6e4f529446 update eslint
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-23 15:17:51 +01:00
cbabf43584 update prettier
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-23 14:23:46 +01:00
33d1425fbb add eslint / prettier
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-23 14:18:51 +01:00
4d1d2e6ed8 add renovate
All checks were successful
continuous-integration/drone/push Build is passing
2026-02-23 11:32:38 +01:00
46 changed files with 4947 additions and 1323 deletions

View File

@@ -4,27 +4,55 @@ type: docker
name: web-core-ci name: web-core-ci
trigger: trigger:
branch: branch:
- main - main
- develop - develop
event: event:
- push - push
- pull_request - pull_request
steps: steps:
- name: install - name: install
image: node:22 image: node:25
commands: commands:
- corepack enable - yarn install --frozen-lockfile
- corepack prepare yarn@1.22.22 --activate
- yarn install --frozen-lockfile
- name: build - name: lint
image: node:22 image: node:25
commands: commands:
- corepack enable - yarn lint
- corepack prepare yarn@1.22.22 --activate
- yarn build - name: build
image: node:25
commands:
- yarn build
- name: unit-tests
image: node:25
environment:
NODE_OPTIONS: --no-webstorage
commands:
- yarn test:coverage
- test -f coverage/lcov.info
- name: code-analysis
when:
event:
- push
image: sonarsource/sonar-scanner-cli:latest
commands:
- |
test -f coverage/lcov.info
SONAR_ARGS="-Dsonar.projectKey=$SONAR_PROJECT_KEY -Dsonar.host.url=$SONAR_INSTANCE_URL -Dsonar.token=$SONAR_LOGIN_KEY -Dsonar.sources=src -Dsonar.tests=tests -Dsonar.test.inclusions=tests/**/*.{test,spec}.{ts,tsx,js,jsx} -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info -Dsonar.working.directory=/tmp/.scannerwork"
sonar-scanner $SONAR_ARGS
environment:
SONAR_USER_HOME: /tmp/.sonar
SONAR_PROJECT_KEY:
from_secret: sonar_project_key
SONAR_INSTANCE_URL:
from_secret: sonar_instance_url
SONAR_LOGIN_KEY:
from_secret: sonar_login_key
--- ---
kind: pipeline kind: pipeline
@@ -32,22 +60,18 @@ type: docker
name: web-core-publish name: web-core-publish
trigger: trigger:
branch: event:
- main - tag
event: ref:
- promote - refs/tags/v*
target:
- production
steps: steps:
- name: publish-npm - name: publish-npm
image: node:22 image: node:25
environment: environment:
NEXUS_NPM_TOKEN: NEXUS_NPM_TOKEN:
from_secret: nexus_npm_token from_secret: nexus_npm_token
commands: commands:
- corepack enable - yarn install --frozen-lockfile
- corepack prepare yarn@1.22.22 --activate - npm config set //nexus.beatrice.wtf/repository/npm-hosted/:_authToken "$NEXUS_NPM_TOKEN"
- yarn install --frozen-lockfile - yarn publish:nexus
- npm config set //nexus.beatrice.wtf/repository/npm-hosted/:_authToken "$NEXUS_NPM_TOKEN"
- yarn publish:nexus

4
.prettierignore Normal file
View File

@@ -0,0 +1,4 @@
dist
coverage
node_modules
yarn.lock

7
.prettierrc Normal file
View File

@@ -0,0 +1,7 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"singleQuote": true,
"semi": true,
"printWidth": 100,
"tabWidth": 4
}

61
eslint.config.mjs Normal file
View File

@@ -0,0 +1,61 @@
import js from '@eslint/js';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: [
'dist',
'coverage',
'node_modules',
'*.config.cjs',
'vite.config.js',
'vite.config.d.ts',
],
},
js.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
...globals.browser,
...globals.node,
},
},
rules: {
'no-empty': ['error', { allowEmptyCatch: true }],
},
},
{
files: ['src/**/*.{ts,tsx}'],
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
},
{
files: ['src/contexts/**/*.{ts,tsx}'],
rules: {
'react-refresh/only-export-components': 'off',
},
},
{
files: ['tests/**/*.{ts,tsx}'],
languageOptions: {
globals: {
...globals.browser,
...globals.node,
...globals.vitest,
},
},
},
);

View File

@@ -1,5 +1,4 @@
GNU Affero General Public License # GNU Affero General Public License
=================================
_Version 3, 19 November 2007_ _Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_ _Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
@@ -14,13 +13,13 @@ software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software. cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast, to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free share and change all versions of a program--to make sure it remains free
software for all its users. software for all its users.
When we speak of free software, we are referring to freedom, not When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for 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 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 want it, that you can change the software or use pieces of it in new
@@ -34,8 +33,8 @@ and/or modify the software.
A secondary benefit of defending all users' freedom is that A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about. software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its letting the public access it on a server without ever releasing its
@@ -43,14 +42,14 @@ source code to the public.
The GNU Affero General Public License is designed specifically to The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source a publicly accessible server, gives the public access to the source
code of the modified version. code of the modified version.
An older license, called the Affero General Public License and An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under released a new version of the Affero GPL which permits relicensing under
this license. this license.
@@ -68,12 +67,12 @@ modification follow.
works, such as semiconductor masks. works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this “The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations. “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work 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 in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a “modified version” of the exact copy. The resulting work is called a “modified version” of the
earlier work or a work “based on” the earlier work. earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based A “covered work” means either the unmodified Program or a work based
@@ -82,12 +81,12 @@ on the Program.
To “propagate” a work means to do anything with it that, without To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying, computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the distribution (with or without modification), making available to the
public, and in some countries other activities as well. public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying. a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” An interactive user interface displays “Appropriate Legal Notices”
@@ -95,14 +94,14 @@ to the extent that it includes a convenient and prominently visible
feature that **(1)** displays an appropriate copyright notice, and **(2)** feature that **(1)** displays an appropriate copyright notice, and **(2)**
tells the user that there is no warranty for the work (except to the tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey 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 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 the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion. menu, a prominent item in the list meets this criterion.
### 1. Source Code ### 1. Source Code
The “source code” for a work means the preferred form of the work The “source code” for a work means the preferred form of the work
for making modifications to it. “Object code” means any non-source for making modifications to it. “Object code” means any non-source
form of a work. form of a work.
A “Standard Interface” means an interface that either is an official A “Standard Interface” means an interface that either is an official
@@ -115,7 +114,7 @@ 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 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 Component, and **(b)** serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A implementation is available to the public in source code form. A
“Major Component”, in this context, means a major essential component “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to (if any) on which the executable work runs, or a compiler used to
@@ -124,10 +123,10 @@ 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 “Corresponding Source” for a work in object code form means all
the source code needed to generate, install, and (for an executable the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require, linked subprograms that the work is specifically designed to require,
@@ -145,25 +144,25 @@ same work.
All rights granted under this License are granted for the term of All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law. rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you. your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10 the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary. makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
@@ -201,20 +200,20 @@ 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 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: terms of section 4, provided that you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified - **a)** The work must carry prominent notices stating that you modified
it, and giving a relevant date. it, and giving a relevant date.
* **b)** The work must carry prominent notices stating that it is - **b)** The work must carry prominent notices stating that it is
released under this License and any conditions added under section 7. released under this License and any conditions added under section 7.
This requirement modifies the requirement in section 4 to This requirement modifies the requirement in section 4 to
“keep intact all notices”. “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this - **c)** You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7 License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts, additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it. invalidate such permission if you have separately received it.
* **d)** If the work has interactive user interfaces, each must display - **d)** If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your interfaces that do not display Appropriate Legal Notices, your
work need not make them do so. work need not make them do so.
@@ -225,7 +224,7 @@ 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 in or on a volume of a storage or distribution medium, is called an
“aggregate” if the compilation and its resulting copyright are not “aggregate” if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other in an aggregate does not cause this License to apply to the other
parts of the aggregate. parts of the aggregate.
@@ -236,11 +235,11 @@ of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License, machine-readable Corresponding Source under the terms of this License,
in one of these ways: in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product - **a)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the (including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium Corresponding Source fixed on a durable physical medium
customarily used for software interchange. customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product - **b)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a (including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product long as you offer spare parts or customer support for that product
@@ -251,24 +250,24 @@ in one of these ways:
more than your reasonable cost of physically performing this more than your reasonable cost of physically performing this
conveying of source, or **(2)** access to copy the conveying of source, or **(2)** access to copy the
Corresponding Source from a network server at no charge. Corresponding Source from a network server at no charge.
* **c)** Convey individual copies of the object code with a copy of the - **c)** Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord only if you received the object code with such an offer, in accord
with subsection 6b. with subsection 6b.
* **d)** Convey the object code by offering access from a designated - **d)** Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party) may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements. available for as long as needed to satisfy these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided - **e)** Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no Source of the work are being offered to the general public at no
charge under subsection 6d. charge under subsection 6d.
@@ -280,12 +279,12 @@ included in conveying the object code work.
A “User Product” is either **(1)** a “consumer product”, which means any A “User Product” is either **(1)** a “consumer product”, which means any
tangible personal property which is normally used for personal, family, tangible personal property which is normally used for personal, family,
or household purposes, or **(2)** anything designed or sold for incorporation or household purposes, or **(2)** anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product, into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, “normally used” refers to a product received by a particular user, “normally used” refers to a
typical or common use of that class of product, regardless of the status 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 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 actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product. the only significant mode of use of the product.
@@ -293,7 +292,7 @@ the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, “Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because code is in no case prevented or interfered with solely because
modification has been made. modification has been made.
@@ -304,7 +303,7 @@ 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 User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has modified object code on the User Product (for example, the work has
been installed in ROM). been installed in ROM).
@@ -312,7 +311,7 @@ been installed in ROM).
The requirement to provide Installation Information does not include a The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for 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 the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and adversely affects the operation of the network or violates the rules and
protocols for communication across the network. protocols for communication across the network.
@@ -329,15 +328,15 @@ unpacking, reading or copying.
License by making exceptions from one or more of its conditions. License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions. this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option 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 remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work, additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission. for which you have or can give appropriate copyright permission.
@@ -345,29 +344,29 @@ Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms: that material) supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the - **a)** Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or terms of sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or - **b)** Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or Notices displayed by works containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or - **c)** Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or reasonable ways as different from the original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or - **d)** Limiting the use for publicity purposes of names of licensors or
authors of the material; or authors of the material; or
* **e)** Declining to grant rights under trademark law for use of some - **e)** Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or trade names, trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that - **f)** Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on any liability that these contractual assumptions directly impose on
those licensors and authors. those licensors and authors.
All other non-permissive additional terms are considered “further All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you 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 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 governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does of that license document, provided that the further restriction does
@@ -385,7 +384,7 @@ the above requirements apply either way.
### 8. Termination ### 8. Termination
You may not propagate or modify a covered work except as expressly You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third this License (including any patent licenses granted under the third
paragraph of section 11). paragraph of section 11).
@@ -406,31 +405,31 @@ your receipt of the notice.
Termination of your rights under this section does not terminate the Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same reinstated, you do not qualify to receive new licenses for the same
material under section 10. material under section 10.
### 9. Acceptance Not Required for Having Copies ### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or 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 run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However, to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so. covered work, you indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients ### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License. for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could licenses to the work the party's predecessor in interest had or could
@@ -439,7 +438,7 @@ Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts. the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that (including a cross-claim or counterclaim in a lawsuit) alleging that
@@ -449,7 +448,7 @@ sale, or importing the Program or any portion of it.
### 11. Patents ### 11. Patents
A “contributor” is a copyright holder who authorizes use under this 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 License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's “contributor version”. work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims A contributor's “essential patent claims” are all patent claims
@@ -457,7 +456,7 @@ owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version, by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant purposes of this definition, “control” includes the right to grant
patent sublicenses in a manner consistent with the requirements of patent sublicenses in a manner consistent with the requirements of
this License. this License.
@@ -470,7 +469,7 @@ propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to (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 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 party means to make such an agreement or commitment not to enforce a
patent against the party. patent against the party.
@@ -482,7 +481,7 @@ then you must either **(1)** cause the Corresponding Source to be so
available, or **(2)** arrange to deprive yourself of the benefit of the available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner patent license for this particular work, or **(3)** arrange, in a manner
consistent with the requirements of this License, to extend the patent consistent with the requirements of this License, to extend the patent
license to downstream recipients. “Knowingly relying” means you have license to downstream recipients. “Knowingly relying” means you have
actual knowledge that, but for the patent license, your conveying the 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 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 in a country, would infringe one or more identifiable patents in that
@@ -499,7 +498,7 @@ work and works based on it.
A patent license is “discriminatory” if it does not include within A patent license is “discriminatory” if it does not include within
the scope of its coverage, prohibits the exercise of, or is 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 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 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 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 in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying to the third party based on the extent of your activity of conveying
@@ -519,10 +518,10 @@ otherwise be available to you under applicable patent law.
If conditions are imposed on you (whether by court order, agreement or If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may 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 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 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 the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program. License would be to refrain entirely from conveying the Program.
@@ -535,7 +534,7 @@ interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3 shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the of the GNU General Public License that is incorporated pursuant to the
following paragraph. following paragraph.
@@ -543,7 +542,7 @@ following paragraph.
Notwithstanding any other provision of this License, you have Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this 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, License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version but the work with which it is combined will remain governed by version
3 of the GNU General Public License. 3 of the GNU General Public License.
@@ -551,16 +550,16 @@ but the work with which it is combined will remain governed by version
### 14. Revised Versions of this License ### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions the GNU Affero 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 will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns. address new problems or concerns.
Each version is given a distinguishing version number. If the Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General Program specifies that a certain numbered version of the GNU Affero General
Public License “or any later version” applies to it, you have the Public License “or any later version” applies to it, you have the
option of following the terms and conditions either of that numbered option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation. by the Free Software Foundation.
@@ -570,19 +569,19 @@ public statement of acceptance of a version permanently authorizes you
to choose that version for the Program. to choose that version for the Program.
Later license versions may give you additional or different Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a author or copyright holder as a result of your choosing to follow a
later version. later version.
### 15. Disclaimer of Warranty ### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 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 IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION. ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability ### 16. Limitation of Liability
@@ -614,7 +613,7 @@ 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 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. 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 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 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 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. the “copyright” line and a pointer to where the full notice is found.
@@ -639,9 +638,9 @@ Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its get its source. For example, if your program is a web application, its
interface could display a “Source” link that leads users to an archive interface could display a “Source” link that leads users to an archive
of the code. There are many ways you could offer source, and different of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the solutions will be better for different programs; see section 13 for the
specific requirements. specific requirements.

View File

@@ -1,40 +1,61 @@
{ {
"name": "@panic/web-core", "name": "@panic/web-core",
"version": "0.1.3", "version": "0.1.5",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"description": "Core auth and utilities for panic.haus web applications", "description": "Core auth and utilities for panic.haus web applications",
"type": "module", "type": "module",
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.js", "module": "./dist/index.js",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"import": "./dist/index.js" "import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"clean": "rm -rf dist",
"build": "yarn clean && vite build && tsc -p tsconfig.build.json",
"test": "vitest run",
"test:coverage": "vitest run --coverage --coverage.reporter=lcov --coverage.reporter=text-summary",
"test:watch": "vitest",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier . --write",
"format:check": "prettier . --check",
"prepublishOnly": "yarn build",
"publish:nexus": "npm publish --registry ${NEXUS_NPM_REGISTRY:-https://nexus.beatrice.wtf/repository/npm-hosted/}"
},
"publishConfig": {
"registry": "https://nexus.beatrice.wtf/repository/npm-hosted/",
"access": "restricted"
},
"peerDependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"@eslint/js": "^10",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.0.0",
"@vitest/coverage-v8": "^4.0.18",
"eslint": "^10",
"eslint-plugin-react-hooks": "^7.1.0-canary-ab18f33d-20260220",
"eslint-plugin-react-refresh": "^0.5.1",
"globals": "^17.3.0",
"jsdom": "^28.1.0",
"prettier": "^3.8.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"typescript": "^5.6.2",
"typescript-eslint": "^8.56.0",
"vite": "^7.0.0",
"vitest": "^4.0.18"
} }
},
"files": [
"dist"
],
"scripts": {
"clean": "rm -rf dist",
"build": "yarn clean && vite build && tsc -p tsconfig.build.json",
"prepublishOnly": "yarn build",
"publish:nexus": "npm publish --registry ${NEXUS_NPM_REGISTRY:-https://nexus.beatrice.wtf/repository/npm-hosted/}"
},
"publishConfig": {
"registry": "https://nexus.beatrice.wtf/repository/npm-hosted/",
"access": "restricted"
},
"peerDependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@vitejs/plugin-react": "^5.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"typescript": "^5.6.2",
"vite": "^7.0.0"
}
} }

3
renovate.json Normal file
View File

@@ -0,0 +1,3 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
}

View File

@@ -1,134 +1,134 @@
export type RequestOptions = { export type RequestOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
token?: string | null; token?: string | null;
body?: unknown; body?: unknown;
}; };
export type ResolveErrorInput = { export type ResolveErrorInput = {
code?: string; code?: string;
status?: number; status?: number;
fallbackMessage?: string; fallbackMessage?: string;
}; };
export type CreateApiClientConfig = { export type CreateApiClientConfig = {
baseUrl: string; baseUrl: string;
resolveError?: (input: ResolveErrorInput) => string; resolveError?: (input: ResolveErrorInput) => string;
inferErrorCodeFromStatus?: (status?: number | null) => string | undefined; inferErrorCodeFromStatus?: (status?: number | null) => string | undefined;
fetchImpl?: typeof fetch; fetchImpl?: typeof fetch;
}; };
export class ApiError extends Error { export class ApiError extends Error {
status: number;
code?: string;
requestId?: string;
details?: unknown;
rawMessage?: string;
constructor({
message,
status,
code,
requestId,
details,
rawMessage
}: {
message: string;
status: number; status: number;
code?: string; code?: string;
requestId?: string; requestId?: string;
details?: unknown; details?: unknown;
rawMessage?: string; rawMessage?: string;
}) {
super(message); constructor({
this.name = 'ApiError'; message,
this.status = status; status,
this.code = code; code,
this.requestId = requestId; requestId,
this.details = details; details,
this.rawMessage = rawMessage; rawMessage,
} }: {
message: string;
status: number;
code?: string;
requestId?: string;
details?: unknown;
rawMessage?: string;
}) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
this.requestId = requestId;
this.details = details;
this.rawMessage = rawMessage;
}
} }
function isRecord(value: unknown): value is Record<string, unknown> { function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value != null; return typeof value === 'object' && value != null;
} }
function parseErrorPayload(data: unknown) { function parseErrorPayload(data: unknown) {
if (!isRecord(data)) { if (!isRecord(data)) {
return { return {
code: undefined as string | undefined, code: undefined as string | undefined,
rawMessage: undefined as string | undefined, rawMessage: undefined as string | undefined,
requestId: undefined as string | undefined, requestId: undefined as string | undefined,
details: undefined as unknown details: undefined as unknown,
}; };
} }
const code = typeof data.code === 'string' ? data.code : undefined; const code = typeof data.code === 'string' ? data.code : undefined;
const rawMessage = typeof data.error === 'string' ? data.error : undefined; const rawMessage = typeof data.error === 'string' ? data.error : undefined;
const requestId = typeof data.requestId === 'string' ? data.requestId : undefined; const requestId = typeof data.requestId === 'string' ? data.requestId : undefined;
const details = data.details; const details = data.details;
return { code, rawMessage, requestId, details }; return { code, rawMessage, requestId, details };
} }
function defaultResolveError({ status, fallbackMessage }: ResolveErrorInput): string { function defaultResolveError({ status, fallbackMessage }: ResolveErrorInput): string {
if (fallbackMessage) { if (fallbackMessage) {
return fallbackMessage; return fallbackMessage;
} }
if (status != null) { if (status != null) {
return `Request failed (${status}).`; return `Request failed (${status}).`;
} }
return 'Request failed. Please try again.'; return 'Request failed. Please try again.';
} }
export function createApiClient(config: CreateApiClientConfig) { export function createApiClient(config: CreateApiClientConfig) {
const { const {
baseUrl, baseUrl,
resolveError = defaultResolveError, resolveError = defaultResolveError,
inferErrorCodeFromStatus, inferErrorCodeFromStatus,
fetchImpl fetchImpl,
} = config; } = config;
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> { async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { method = 'GET', token, body } = options; const { method = 'GET', token, body } = options;
const runFetch = fetchImpl ?? fetch; const runFetch = fetchImpl ?? fetch;
const response = await runFetch(`${baseUrl}${path}`, { const response = await runFetch(`${baseUrl}${path}`, {
method, method,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}) ...(token ? { Authorization: `Bearer ${token}` } : {}),
}, },
body: body ? JSON.stringify(body) : undefined body: body ? JSON.stringify(body) : undefined,
}); });
const data = await response.json().catch(() => null); const data = await response.json().catch(() => null);
if (!response.ok) { if (!response.ok) {
const parsed = parseErrorPayload(data); const parsed = parseErrorPayload(data);
const code = parsed.code ?? inferErrorCodeFromStatus?.(response.status); const code = parsed.code ?? inferErrorCodeFromStatus?.(response.status);
const message = resolveError({ const message = resolveError({
code, code,
status: response.status, status: response.status,
fallbackMessage: parsed.rawMessage fallbackMessage: parsed.rawMessage,
}); });
throw new ApiError({ throw new ApiError({
message, message,
status: response.status, status: response.status,
code, code,
requestId: parsed.requestId, requestId: parsed.requestId,
details: parsed.details, details: parsed.details,
rawMessage: parsed.rawMessage rawMessage: parsed.rawMessage,
}); });
}
return data as T;
} }
return data as T; return {
} request,
};
return {
request
};
} }

View File

@@ -1,29 +1,29 @@
type BuildListQueryOptions = { type BuildListQueryOptions = {
q?: string; q?: string;
page?: number; page?: number;
pageSize?: number; pageSize?: number;
sort?: string; sort?: string;
defaultSort: string; defaultSort: string;
}; };
export function buildListQuery({ export function buildListQuery({
q, q,
page = 1, page = 1,
pageSize = 10, pageSize = 10,
sort, sort,
defaultSort defaultSort,
}: BuildListQueryOptions): string { }: BuildListQueryOptions): string {
const query = new URLSearchParams(); const query = new URLSearchParams();
const normalizedQuery = q?.trim(); const normalizedQuery = q?.trim();
const normalizedSort = sort?.trim(); const normalizedSort = sort?.trim();
if (normalizedQuery) { if (normalizedQuery) {
query.set('q', normalizedQuery); query.set('q', normalizedQuery);
} }
query.set('page', String(page)); query.set('page', String(page));
query.set('pageSize', String(pageSize)); query.set('pageSize', String(pageSize));
query.set('sort', normalizedSort || defaultSort); query.set('sort', normalizedSort || defaultSort);
return query.toString(); return query.toString();
} }

View File

@@ -6,85 +6,91 @@ const DEFAULT_REFRESH_TOKEN_KEY = 'refreshToken';
const DEFAULT_LEGACY_KEYS = ['auth_token', 'auth_user', 'token']; const DEFAULT_LEGACY_KEYS = ['auth_token', 'auth_user', 'token'];
export type AuthState<TUser> = { export type AuthState<TUser> = {
authToken: string | null; authToken: string | null;
refreshToken: string | null; refreshToken: string | null;
currentUser: TUser | null; currentUser: TUser | null;
}; };
export type AuthContextValue<TUser> = AuthState<TUser> & { export type AuthContextValue<TUser> = AuthState<TUser> & {
setSession: (authToken: string, refreshToken: string, currentUser: TUser) => void; setSession: (authToken: string, refreshToken: string, currentUser: TUser) => void;
setCurrentUser: (currentUser: TUser | null) => void; setCurrentUser: (currentUser: TUser | null) => void;
clearSession: () => void; clearSession: () => void;
}; };
export type CreateAuthContextOptions = { export type CreateAuthContextOptions = {
authTokenKey?: string; authTokenKey?: string;
refreshTokenKey?: string; refreshTokenKey?: string;
legacyKeys?: string[]; legacyKeys?: string[];
}; };
export function createAuthContext<TUser>(options: CreateAuthContextOptions = {}) { export function createAuthContext<TUser>(options: CreateAuthContextOptions = {}) {
const authTokenKey = options.authTokenKey ?? DEFAULT_AUTH_TOKEN_KEY; const authTokenKey = options.authTokenKey ?? DEFAULT_AUTH_TOKEN_KEY;
const refreshTokenKey = options.refreshTokenKey ?? DEFAULT_REFRESH_TOKEN_KEY; const refreshTokenKey = options.refreshTokenKey ?? DEFAULT_REFRESH_TOKEN_KEY;
const legacyKeys = options.legacyKeys ?? DEFAULT_LEGACY_KEYS; const legacyKeys = options.legacyKeys ?? DEFAULT_LEGACY_KEYS;
const AuthContext = createContext<AuthContextValue<TUser> | undefined>(undefined); const AuthContext = createContext<AuthContextValue<TUser> | undefined>(undefined);
function readStoredSession(): AuthState<TUser> { function readStoredSession(): AuthState<TUser> {
for (const key of legacyKeys) { for (const key of legacyKeys) {
localStorage.removeItem(key); localStorage.removeItem(key);
}
const authToken = localStorage.getItem(authTokenKey);
const refreshToken = localStorage.getItem(refreshTokenKey);
return {
authToken,
refreshToken,
currentUser: null,
};
} }
const authToken = localStorage.getItem(authTokenKey); function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
const refreshToken = localStorage.getItem(refreshTokenKey); const [state, setState] = useState<AuthState<TUser>>(readStoredSession);
const setSession = useCallback(
(authToken: string, refreshToken: string, currentUser: TUser) => {
localStorage.setItem(authTokenKey, authToken);
localStorage.setItem(refreshTokenKey, refreshToken);
setState({ authToken, refreshToken, currentUser });
},
[],
);
const clearSession = useCallback(() => {
localStorage.removeItem(authTokenKey);
localStorage.removeItem(refreshTokenKey);
setState({ authToken: null, refreshToken: null, currentUser: null });
}, []);
const setCurrentUser = useCallback((currentUser: TUser | null) => {
setState((prev) => ({ ...prev, currentUser }));
}, []);
const value = useMemo<AuthContextValue<TUser>>(
() => ({
...state,
setSession,
setCurrentUser,
clearSession,
}),
[state, setSession, setCurrentUser, clearSession],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error('useAuth must be used within AuthProvider');
}
return ctx;
}
return { return {
authToken, AuthProvider,
refreshToken, useAuth,
currentUser: null AuthContext,
}; };
}
function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
const [state, setState] = useState<AuthState<TUser>>(readStoredSession);
const setSession = useCallback((authToken: string, refreshToken: string, currentUser: TUser) => {
localStorage.setItem(authTokenKey, authToken);
localStorage.setItem(refreshTokenKey, refreshToken);
setState({ authToken, refreshToken, currentUser });
}, []);
const clearSession = useCallback(() => {
localStorage.removeItem(authTokenKey);
localStorage.removeItem(refreshTokenKey);
setState({ authToken: null, refreshToken: null, currentUser: null });
}, []);
const setCurrentUser = useCallback((currentUser: TUser | null) => {
setState((prev) => ({ ...prev, currentUser }));
}, []);
const value = useMemo<AuthContextValue<TUser>>(() => ({
...state,
setSession,
setCurrentUser,
clearSession
}), [state, setSession, setCurrentUser, clearSession]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error('useAuth must be used within AuthProvider');
}
return ctx;
}
return {
AuthProvider,
useAuth,
AuthContext
};
} }

View File

@@ -1,35 +1,35 @@
const MILLISECONDS_PER_SECOND = 1000; const MILLISECONDS_PER_SECOND = 1000;
export function decodeJwtPayload(token: string): Record<string, unknown> | null { export function decodeJwtPayload(token: string): Record<string, unknown> | null {
const parts = token.split('.'); const parts = token.split('.');
if (parts.length !== 3) { if (parts.length !== 3) {
return null; return null;
}
const base64Url = parts[1];
const base64 = base64Url.replaceAll('-', '+').replaceAll('_', '/');
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
try {
const payload = JSON.parse(atob(padded));
if (payload && typeof payload === 'object') {
return payload as Record<string, unknown>;
} }
} catch {
return null;
}
return null; const base64Url = parts[1];
const base64 = base64Url.replaceAll('-', '+').replaceAll('_', '/');
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
try {
const payload = JSON.parse(atob(padded));
if (payload && typeof payload === 'object') {
return payload as Record<string, unknown>;
}
} catch {
return null;
}
return null;
} }
export function isJwtExpired(token: string, skewSeconds = 0) { export function isJwtExpired(token: string, skewSeconds = 0) {
const payload = decodeJwtPayload(token); const payload = decodeJwtPayload(token);
const exp = payload?.exp; const exp = payload?.exp;
if (typeof exp !== 'number' || !Number.isFinite(exp)) { if (typeof exp !== 'number' || !Number.isFinite(exp)) {
return false; return false;
} }
const expiresAt = exp * MILLISECONDS_PER_SECOND; const expiresAt = exp * MILLISECONDS_PER_SECOND;
const now = Date.now(); const now = Date.now();
return expiresAt <= now + skewSeconds * MILLISECONDS_PER_SECOND; return expiresAt <= now + skewSeconds * MILLISECONDS_PER_SECOND;
} }

View File

@@ -1,13 +1,13 @@
import { import {
createContext, createContext,
useCallback, useCallback,
useContext, useContext,
useEffect, useEffect,
useMemo, useMemo,
useRef, useRef,
useState, useState,
type CSSProperties, type CSSProperties,
type ReactNode type ReactNode,
} from 'react'; } from 'react';
import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine'; import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine';
@@ -18,200 +18,247 @@ const SIDEBAR_MIN_WIDTH = 220;
const SIDEBAR_MAX_WIDTH = 420; const SIDEBAR_MAX_WIDTH = 420;
const SIDEBAR_COLLAPSED_WIDTH = 56; const SIDEBAR_COLLAPSED_WIDTH = 56;
export type LeftMenuSizing = {
defaultWidth?: number;
minWidth?: number;
maxWidth?: number;
collapsedWidth?: number;
};
export type LeftMenuRenderState = { export type LeftMenuRenderState = {
collapsed: boolean; collapsed: boolean;
mobileOpen: boolean; mobileOpen: boolean;
isDesktop: boolean; isDesktop: boolean;
closeMenu: () => void; closeMenu: () => void;
}; };
export type LeftMenuContent = { export type LeftMenuContent = {
ariaLabel?: string; ariaLabel?: string;
render: (state: LeftMenuRenderState) => ReactNode; render: (state: LeftMenuRenderState) => ReactNode;
}; };
export type LeftMenuStyle = CSSProperties & { export type LeftMenuStyle = CSSProperties & {
'--auth-sidebar-width': string; '--auth-sidebar-width': string;
}; };
type LeftMenuContextValue = { type LeftMenuContextValue = {
collapsed: boolean; collapsed: boolean;
mobileOpen: boolean; mobileOpen: boolean;
content: LeftMenuContent; content: LeftMenuContent;
desktopMenuStyle: LeftMenuStyle; desktopMenuStyle: LeftMenuStyle;
openMenu: (content?: LeftMenuContent) => void; openMenu: (content?: LeftMenuContent) => void;
closeMenu: () => void; closeMenu: () => void;
toggleMenu: (content?: LeftMenuContent) => void; toggleMenu: (content?: LeftMenuContent) => void;
expandMenu: () => void; expandMenu: () => void;
collapseMenu: () => void; collapseMenu: () => void;
toggleCollapsed: () => void; toggleCollapsed: () => void;
setMenuContent: (content: LeftMenuContent | null) => void; setMenuContent: (content: LeftMenuContent | null) => void;
startResize: ReturnType<typeof useSidePanelMachine>['startResize']; startResize: ReturnType<typeof useSidePanelMachine>['startResize'];
}; };
type LeftMenuProviderProps = { type LeftMenuProviderProps = {
children: ReactNode; children: ReactNode;
defaultContent: LeftMenuContent; defaultContent: LeftMenuContent;
closeOnPathname?: string; closeOnPathname?: string;
sizing?: LeftMenuSizing;
}; };
const LeftMenuContext = createContext<LeftMenuContextValue | undefined>(undefined); const LeftMenuContext = createContext<LeftMenuContextValue | undefined>(undefined);
function readStoredCollapsed(): boolean { function readSizingValue(value: number | undefined, fallback: number): number {
if (!globalThis.window) { if (!Number.isFinite(value) || value == null || value <= 0) {
return false; return fallback;
} }
return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1'; return value;
}
function resolveLeftMenuSizing(sizing: LeftMenuSizing | undefined) {
const requestedMinWidth = readSizingValue(sizing?.minWidth, SIDEBAR_MIN_WIDTH);
const requestedMaxWidth = readSizingValue(sizing?.maxWidth, SIDEBAR_MAX_WIDTH);
const minWidth = Math.min(requestedMinWidth, requestedMaxWidth);
const maxWidth = Math.max(requestedMinWidth, requestedMaxWidth);
const requestedDefaultWidth = readSizingValue(sizing?.defaultWidth, SIDEBAR_DEFAULT_WIDTH);
const defaultWidth = Math.min(maxWidth, Math.max(minWidth, requestedDefaultWidth));
const requestedCollapsedWidth = readSizingValue(
sizing?.collapsedWidth,
SIDEBAR_COLLAPSED_WIDTH,
);
const collapsedWidth = Math.min(minWidth, requestedCollapsedWidth);
return {
defaultWidth,
minWidth,
maxWidth,
collapsedWidth,
};
}
function readStoredCollapsed(): boolean {
if (!globalThis.window) {
return false;
}
return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1';
} }
export function LeftMenuProvider({ export function LeftMenuProvider({
children, children,
defaultContent, defaultContent,
closeOnPathname
}: Readonly<LeftMenuProviderProps>) {
const [collapsed, setCollapsed] = useState<boolean>(() => readStoredCollapsed());
const [mobileOpen, setMobileOpen] = useState(false);
const [content, setContent] = useState<LeftMenuContent>(defaultContent);
const defaultContentRef = useRef(defaultContent);
useEffect(() => {
const previousDefaultContent = defaultContentRef.current;
defaultContentRef.current = defaultContent;
setContent((currentContent) => {
if (currentContent === previousDefaultContent) {
return defaultContent;
}
return currentContent;
});
}, [defaultContent]);
useEffect(() => {
if (!globalThis.window) {
return;
}
localStorage.setItem(SIDEBAR_COLLAPSED_KEY, collapsed ? '1' : '0');
}, [collapsed]);
const expandMenu = useCallback(() => {
setCollapsed(false);
}, []);
const collapseMenu = useCallback(() => {
setCollapsed(true);
}, []);
const toggleCollapsed = useCallback(() => {
setCollapsed((previous) => !previous);
}, []);
const closeMobile = useCallback(() => {
setMobileOpen(false);
}, []);
const setMenuContent = useCallback((nextContent: LeftMenuContent | null) => {
setContent(nextContent ?? defaultContentRef.current);
}, []);
const closeMenu = useCallback(() => {
if (isDesktopViewport()) {
collapseMenu();
return;
}
closeMobile();
}, [collapseMenu, closeMobile]);
const openMenu = useCallback((nextContent?: LeftMenuContent) => {
if (nextContent) {
setContent(nextContent);
}
if (isDesktopViewport()) {
expandMenu();
return;
}
setMobileOpen(true);
}, [expandMenu]);
const toggleMenu = useCallback((nextContent?: LeftMenuContent) => {
if (nextContent) {
setContent(nextContent);
}
if (isDesktopViewport()) {
toggleCollapsed();
return;
}
setMobileOpen((previous) => !previous);
}, [toggleCollapsed]);
const handleCloseOnPathname = useCallback(() => {
setMobileOpen(false);
setContent(defaultContentRef.current);
}, []);
const { width, startResize } = useSidePanelMachine({
storageKey: SIDEBAR_WIDTH_KEY,
defaultWidth: SIDEBAR_DEFAULT_WIDTH,
minWidth: SIDEBAR_MIN_WIDTH,
maxWidth: SIDEBAR_MAX_WIDTH,
resizeAxis: 'from-left',
resizingBodyClass: 'auth-sidebar-resizing',
isOpen: mobileOpen,
canResize: !collapsed,
shouldPersistWidth: !collapsed,
closeOnPathname, closeOnPathname,
onCloseOnPathname: handleCloseOnPathname, sizing,
onEscape: closeMobile }: Readonly<LeftMenuProviderProps>) {
}); const { defaultWidth, minWidth, maxWidth, collapsedWidth } = resolveLeftMenuSizing(sizing);
const [collapsed, setCollapsed] = useState<boolean>(() => readStoredCollapsed());
const [mobileOpen, setMobileOpen] = useState(false);
const [content, setContent] = useState<LeftMenuContent>(defaultContent);
const defaultContentRef = useRef(defaultContent);
const desktopMenuStyle = useMemo<LeftMenuStyle>(() => ({ useEffect(() => {
'--auth-sidebar-width': `${collapsed ? SIDEBAR_COLLAPSED_WIDTH : width}px` const previousDefaultContent = defaultContentRef.current;
}), [collapsed, width]); defaultContentRef.current = defaultContent;
setContent((currentContent) => {
if (currentContent === previousDefaultContent) {
return defaultContent;
}
return currentContent;
});
}, [defaultContent]);
const value = useMemo<LeftMenuContextValue>(() => ({ useEffect(() => {
collapsed, if (!globalThis.window) {
mobileOpen, return;
content, }
desktopMenuStyle,
openMenu,
closeMenu,
toggleMenu,
expandMenu,
collapseMenu,
toggleCollapsed,
setMenuContent,
startResize
}), [
collapsed,
mobileOpen,
content,
desktopMenuStyle,
openMenu,
closeMenu,
toggleMenu,
expandMenu,
collapseMenu,
toggleCollapsed,
setMenuContent,
startResize
]);
return ( localStorage.setItem(SIDEBAR_COLLAPSED_KEY, collapsed ? '1' : '0');
<LeftMenuContext.Provider value={value}> }, [collapsed]);
{children}
</LeftMenuContext.Provider> const expandMenu = useCallback(() => {
); setCollapsed(false);
}, []);
const collapseMenu = useCallback(() => {
setCollapsed(true);
}, []);
const toggleCollapsed = useCallback(() => {
setCollapsed((previous) => !previous);
}, []);
const closeMobile = useCallback(() => {
setMobileOpen(false);
}, []);
const setMenuContent = useCallback((nextContent: LeftMenuContent | null) => {
setContent(nextContent ?? defaultContentRef.current);
}, []);
const closeMenu = useCallback(() => {
if (isDesktopViewport()) {
collapseMenu();
return;
}
closeMobile();
}, [collapseMenu, closeMobile]);
const openMenu = useCallback(
(nextContent?: LeftMenuContent) => {
if (nextContent) {
setContent(nextContent);
}
if (isDesktopViewport()) {
expandMenu();
return;
}
setMobileOpen(true);
},
[expandMenu],
);
const toggleMenu = useCallback(
(nextContent?: LeftMenuContent) => {
if (nextContent) {
setContent(nextContent);
}
if (isDesktopViewport()) {
toggleCollapsed();
return;
}
setMobileOpen((previous) => !previous);
},
[toggleCollapsed],
);
const handleCloseOnPathname = useCallback(() => {
setMobileOpen(false);
setContent(defaultContentRef.current);
}, []);
const { width, startResize } = useSidePanelMachine({
storageKey: SIDEBAR_WIDTH_KEY,
defaultWidth,
minWidth,
maxWidth,
resizeAxis: 'from-left',
resizingBodyClass: 'auth-sidebar-resizing',
isOpen: mobileOpen,
canResize: !collapsed,
shouldPersistWidth: !collapsed,
closeOnPathname,
onCloseOnPathname: handleCloseOnPathname,
onEscape: closeMobile,
});
const desktopMenuStyle = useMemo<LeftMenuStyle>(
() => ({
'--auth-sidebar-width': `${collapsed ? collapsedWidth : width}px`,
}),
[collapsed, collapsedWidth, width],
);
const value = useMemo<LeftMenuContextValue>(
() => ({
collapsed,
mobileOpen,
content,
desktopMenuStyle,
openMenu,
closeMenu,
toggleMenu,
expandMenu,
collapseMenu,
toggleCollapsed,
setMenuContent,
startResize,
}),
[
collapsed,
mobileOpen,
content,
desktopMenuStyle,
openMenu,
closeMenu,
toggleMenu,
expandMenu,
collapseMenu,
toggleCollapsed,
setMenuContent,
startResize,
],
);
return <LeftMenuContext.Provider value={value}>{children}</LeftMenuContext.Provider>;
} }
export function useLeftMenu() { export function useLeftMenu() {
const ctx = useContext(LeftMenuContext); const ctx = useContext(LeftMenuContext);
if (!ctx) { if (!ctx) {
throw new Error('useLeftMenu must be used within LeftMenuProvider'); throw new Error('useLeftMenu must be used within LeftMenuProvider');
} }
return ctx; return ctx;
} }

View File

@@ -1,11 +1,11 @@
import { import {
createContext, createContext,
useCallback, useCallback,
useContext, useContext,
useMemo, useMemo,
useState, useState,
type CSSProperties, type CSSProperties,
type ReactNode type ReactNode,
} from 'react'; } from 'react';
import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine'; import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine';
@@ -14,126 +14,169 @@ const RIGHT_SIDEBAR_DEFAULT_WIDTH = 320;
const RIGHT_SIDEBAR_MIN_WIDTH = 260; const RIGHT_SIDEBAR_MIN_WIDTH = 260;
const RIGHT_SIDEBAR_MAX_WIDTH = 480; const RIGHT_SIDEBAR_MAX_WIDTH = 480;
export type RightSidebarSizing = {
defaultWidth?: number;
minWidth?: number;
maxWidth?: number;
};
export type RightSidebarContent = { export type RightSidebarContent = {
title: string; title: string;
content: ReactNode; content: ReactNode;
ariaLabel?: string; ariaLabel?: string;
}; };
export type RightSidebarStyle = CSSProperties & { export type RightSidebarStyle = CSSProperties & {
'--auth-right-sidebar-width': string; '--auth-right-sidebar-width': string;
}; };
type RightSidebarContextValue = { type RightSidebarContextValue = {
isOpen: boolean; isOpen: boolean;
content: RightSidebarContent | null; content: RightSidebarContent | null;
openSidebar: (content?: RightSidebarContent) => void; openSidebar: (content?: RightSidebarContent) => void;
closeSidebar: () => void; closeSidebar: () => void;
toggleSidebar: (content?: RightSidebarContent) => void; toggleSidebar: (content?: RightSidebarContent) => void;
setSidebarContent: (content: RightSidebarContent | null) => void; setSidebarContent: (content: RightSidebarContent | null) => void;
desktopSidebarStyle: RightSidebarStyle; desktopSidebarStyle: RightSidebarStyle;
startResize: ReturnType<typeof useSidePanelMachine>['startResize']; startResize: ReturnType<typeof useSidePanelMachine>['startResize'];
}; };
type RightSidebarProviderProps = { type RightSidebarProviderProps = {
children: ReactNode; children: ReactNode;
closeOnPathname?: string; closeOnPathname?: string;
onMobileOpenRequest?: () => void; onMobileOpenRequest?: () => void;
sizing?: RightSidebarSizing;
}; };
const RightSidebarContext = createContext<RightSidebarContextValue | undefined>(undefined); const RightSidebarContext = createContext<RightSidebarContextValue | undefined>(undefined);
function readSizingValue(value: number | undefined, fallback: number): number {
if (!Number.isFinite(value) || value == null || value <= 0) {
return fallback;
}
return value;
}
function resolveRightSidebarSizing(sizing: RightSidebarSizing | undefined) {
const requestedMinWidth = readSizingValue(sizing?.minWidth, RIGHT_SIDEBAR_MIN_WIDTH);
const requestedMaxWidth = readSizingValue(sizing?.maxWidth, RIGHT_SIDEBAR_MAX_WIDTH);
const minWidth = Math.min(requestedMinWidth, requestedMaxWidth);
const maxWidth = Math.max(requestedMinWidth, requestedMaxWidth);
const requestedDefaultWidth = readSizingValue(
sizing?.defaultWidth,
RIGHT_SIDEBAR_DEFAULT_WIDTH,
);
const defaultWidth = Math.min(maxWidth, Math.max(minWidth, requestedDefaultWidth));
return {
defaultWidth,
minWidth,
maxWidth,
};
}
export function RightSidebarProvider({ export function RightSidebarProvider({
children, children,
closeOnPathname,
onMobileOpenRequest
}: Readonly<RightSidebarProviderProps>) {
const [isOpen, setIsOpen] = useState(false);
const [content, setContent] = useState<RightSidebarContent | null>(null);
const closeSidebar = useCallback(() => {
setIsOpen(false);
setContent(null);
}, []);
const setSidebarContent = useCallback((nextContent: RightSidebarContent | null) => {
setContent(nextContent);
}, []);
const openSidebar = useCallback((nextContent?: RightSidebarContent) => {
const resolvedContent = nextContent ?? content;
if (!resolvedContent) {
return;
}
if (nextContent) {
setContent(nextContent);
}
if (!isDesktopViewport()) {
onMobileOpenRequest?.();
}
setIsOpen(true);
}, [content, onMobileOpenRequest]);
const toggleSidebar = useCallback((nextContent?: RightSidebarContent) => {
if (isOpen) {
closeSidebar();
return;
}
openSidebar(nextContent);
}, [isOpen, closeSidebar, openSidebar]);
const { width, startResize } = useSidePanelMachine({
storageKey: RIGHT_SIDEBAR_WIDTH_KEY,
defaultWidth: RIGHT_SIDEBAR_DEFAULT_WIDTH,
minWidth: RIGHT_SIDEBAR_MIN_WIDTH,
maxWidth: RIGHT_SIDEBAR_MAX_WIDTH,
resizeAxis: 'from-right',
resizingBodyClass: 'auth-right-sidebar-resizing',
isOpen,
canResize: isOpen,
shouldPersistWidth: true,
closeOnPathname, closeOnPathname,
onCloseOnPathname: closeSidebar, onMobileOpenRequest,
onEscape: closeSidebar sizing,
}); }: Readonly<RightSidebarProviderProps>) {
const { defaultWidth, minWidth, maxWidth } = resolveRightSidebarSizing(sizing);
const [isOpen, setIsOpen] = useState(false);
const [content, setContent] = useState<RightSidebarContent | null>(null);
const desktopSidebarStyle = useMemo<RightSidebarStyle>(() => ({ const closeSidebar = useCallback(() => {
'--auth-right-sidebar-width': `${width}px` setIsOpen(false);
}), [width]); setContent(null);
}, []);
const value = useMemo<RightSidebarContextValue>(() => ({ const setSidebarContent = useCallback((nextContent: RightSidebarContent | null) => {
isOpen, setContent(nextContent);
content, }, []);
openSidebar,
closeSidebar,
toggleSidebar,
setSidebarContent,
desktopSidebarStyle,
startResize
}), [
isOpen,
content,
openSidebar,
closeSidebar,
toggleSidebar,
setSidebarContent,
desktopSidebarStyle,
startResize
]);
return ( const openSidebar = useCallback(
<RightSidebarContext.Provider value={value}> (nextContent?: RightSidebarContent) => {
{children} const resolvedContent = nextContent ?? content;
</RightSidebarContext.Provider> if (!resolvedContent) {
); return;
}
if (nextContent) {
setContent(nextContent);
}
if (!isDesktopViewport()) {
onMobileOpenRequest?.();
}
setIsOpen(true);
},
[content, onMobileOpenRequest],
);
const toggleSidebar = useCallback(
(nextContent?: RightSidebarContent) => {
if (isOpen) {
closeSidebar();
return;
}
openSidebar(nextContent);
},
[isOpen, closeSidebar, openSidebar],
);
const { width, startResize } = useSidePanelMachine({
storageKey: RIGHT_SIDEBAR_WIDTH_KEY,
defaultWidth,
minWidth,
maxWidth,
resizeAxis: 'from-right',
resizingBodyClass: 'auth-right-sidebar-resizing',
isOpen,
canResize: isOpen,
shouldPersistWidth: true,
closeOnPathname,
onCloseOnPathname: closeSidebar,
onEscape: closeSidebar,
});
const desktopSidebarStyle = useMemo<RightSidebarStyle>(
() => ({
'--auth-right-sidebar-width': `${width}px`,
}),
[width],
);
const value = useMemo<RightSidebarContextValue>(
() => ({
isOpen,
content,
openSidebar,
closeSidebar,
toggleSidebar,
setSidebarContent,
desktopSidebarStyle,
startResize,
}),
[
isOpen,
content,
openSidebar,
closeSidebar,
toggleSidebar,
setSidebarContent,
desktopSidebarStyle,
startResize,
],
);
return <RightSidebarContext.Provider value={value}>{children}</RightSidebarContext.Provider>;
} }
export function useRightSidebar() { export function useRightSidebar() {
const ctx = useContext(RightSidebarContext); const ctx = useContext(RightSidebarContext);
if (!ctx) { if (!ctx) {
throw new Error('useRightSidebar must be used within RightSidebarProvider'); throw new Error('useRightSidebar must be used within RightSidebarProvider');
} }
return ctx; return ctx;
} }

View File

@@ -1,132 +1,132 @@
export type ErrorCatalog = Record<string, string>; export type ErrorCatalog = Record<string, string>;
type ErrorLike = { type ErrorLike = {
code?: unknown; code?: unknown;
status?: unknown; status?: unknown;
message?: unknown; message?: unknown;
rawMessage?: unknown; rawMessage?: unknown;
}; };
export type ResolveErrorMessageOptions = { export type ResolveErrorMessageOptions = {
code?: string | null; code?: string | null;
status?: number | null; status?: number | null;
context?: string; context?: string;
fallbackMessage?: string | null; fallbackMessage?: string | null;
}; };
export type CreateErrorResolverConfig = { export type CreateErrorResolverConfig = {
catalog: ErrorCatalog; catalog: ErrorCatalog;
fallbackCode?: string; fallbackCode?: string;
defaultContext?: string; defaultContext?: string;
contextOverrides?: Record<string, Partial<Record<string, string>>>; contextOverrides?: Record<string, Partial<Record<string, string>>>;
inferCodeFromStatus?: (status?: number | null) => string | undefined; inferCodeFromStatus?: (status?: number | null) => string | undefined;
inferCodeFromLegacyMessage?: (message?: string | null) => string | undefined; inferCodeFromLegacyMessage?: (message?: string | null) => string | undefined;
}; };
export function createErrorResolver(config: CreateErrorResolverConfig) { export function createErrorResolver(config: CreateErrorResolverConfig) {
const {
catalog,
fallbackCode,
defaultContext = 'default',
contextOverrides = {},
inferCodeFromStatus,
inferCodeFromLegacyMessage
} = config;
const knownCodes = new Set(Object.keys(catalog));
function isKnownErrorCode(value: string): boolean {
return knownCodes.has(value);
}
function normalizeErrorCode(code?: string | null): string | undefined {
if (!code) {
return undefined;
}
return isKnownErrorCode(code) ? code : undefined;
}
function inferErrorCodeFromStatus(status?: number | null): string | undefined {
return inferCodeFromStatus?.(status);
}
function resolveErrorMessage(options: ResolveErrorMessageOptions): string {
const { const {
code, catalog,
status, fallbackCode,
context = defaultContext, defaultContext = 'default',
fallbackMessage contextOverrides = {},
} = options; inferCodeFromStatus,
inferCodeFromLegacyMessage,
} = config;
const resolvedCode = normalizeErrorCode(code) const knownCodes = new Set(Object.keys(catalog));
?? inferCodeFromLegacyMessage?.(fallbackMessage)
?? inferErrorCodeFromStatus(status);
if (resolvedCode) { function isKnownErrorCode(value: string): boolean {
const contextMessage = contextOverrides[context]?.[resolvedCode]; return knownCodes.has(value);
if (contextMessage) {
return contextMessage;
}
const catalogMessage = catalog[resolvedCode];
if (catalogMessage) {
return catalogMessage;
}
} }
const statusCode = inferErrorCodeFromStatus(status); function normalizeErrorCode(code?: string | null): string | undefined {
if (statusCode) { if (!code) {
const contextMessage = contextOverrides[context]?.[statusCode]; return undefined;
if (contextMessage) { }
return contextMessage; return isKnownErrorCode(code) ? code : undefined;
}
const catalogMessage = catalog[statusCode];
if (catalogMessage) {
return catalogMessage;
}
} }
if (fallbackCode && catalog[fallbackCode]) { function inferErrorCodeFromStatus(status?: number | null): string | undefined {
return catalog[fallbackCode]; return inferCodeFromStatus?.(status);
} }
if (fallbackMessage) { function resolveErrorMessage(options: ResolveErrorMessageOptions): string {
return fallbackMessage; const { code, status, context = defaultContext, fallbackMessage } = options;
const resolvedCode =
normalizeErrorCode(code) ??
inferCodeFromLegacyMessage?.(fallbackMessage) ??
inferErrorCodeFromStatus(status);
if (resolvedCode) {
const contextMessage = contextOverrides[context]?.[resolvedCode];
if (contextMessage) {
return contextMessage;
}
const catalogMessage = catalog[resolvedCode];
if (catalogMessage) {
return catalogMessage;
}
}
const statusCode = inferErrorCodeFromStatus(status);
if (statusCode) {
const contextMessage = contextOverrides[context]?.[statusCode];
if (contextMessage) {
return contextMessage;
}
const catalogMessage = catalog[statusCode];
if (catalogMessage) {
return catalogMessage;
}
}
if (fallbackCode && catalog[fallbackCode]) {
return catalog[fallbackCode];
}
if (fallbackMessage) {
return fallbackMessage;
}
return 'Request failed. Please try again.';
} }
return 'Request failed. Please try again.'; function resolveOptionalErrorMessage(
} code?: string | null,
context: string = defaultContext,
function resolveOptionalErrorMessage(code?: string | null, context: string = defaultContext): string | undefined { ): string | undefined {
if (!code) { if (!code) {
return undefined; return undefined;
} }
return resolveErrorMessage({ code, context }); return resolveErrorMessage({ code, context });
}
function toErrorMessage(err: unknown, context: string = defaultContext): string {
if (err && typeof err === 'object') {
const errorLike = err as ErrorLike;
const code = typeof errorLike.code === 'string' ? errorLike.code : undefined;
const status = typeof errorLike.status === 'number' ? errorLike.status : undefined;
const rawMessage = typeof errorLike.rawMessage === 'string' ? errorLike.rawMessage : undefined;
const message = typeof errorLike.message === 'string' ? errorLike.message : undefined;
return resolveErrorMessage({
code,
status,
context,
fallbackMessage: rawMessage ?? message
});
} }
return resolveErrorMessage({ context }); function toErrorMessage(err: unknown, context: string = defaultContext): string {
} if (err && typeof err === 'object') {
const errorLike = err as ErrorLike;
const code = typeof errorLike.code === 'string' ? errorLike.code : undefined;
const status = typeof errorLike.status === 'number' ? errorLike.status : undefined;
const rawMessage =
typeof errorLike.rawMessage === 'string' ? errorLike.rawMessage : undefined;
const message = typeof errorLike.message === 'string' ? errorLike.message : undefined;
return { return resolveErrorMessage({
isKnownErrorCode, code,
inferErrorCodeFromStatus, status,
resolveErrorMessage, context,
resolveOptionalErrorMessage, fallbackMessage: rawMessage ?? message,
toErrorMessage });
}; }
return resolveErrorMessage({ context });
}
return {
isKnownErrorCode,
inferErrorCodeFromStatus,
resolveErrorMessage,
resolveOptionalErrorMessage,
toErrorMessage,
};
} }

View File

@@ -1,28 +1,28 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
export function useCooldownTimer(seconds = 0, enabled = true) { export function useCooldownTimer(seconds = 0, enabled = true) {
const [cooldown, setCooldown] = useState(seconds); const [cooldown, setCooldown] = useState(seconds);
useEffect(() => { useEffect(() => {
if (!enabled || cooldown <= 0) { if (!enabled || cooldown <= 0) {
return; return;
} }
const timer = globalThis.setInterval(() => { const timer = globalThis.setInterval(() => {
setCooldown((prev) => (prev > 0 ? prev - 1 : 0)); setCooldown((prev) => (prev > 0 ? prev - 1 : 0));
}, 1000); }, 1000);
return () => { return () => {
globalThis.clearInterval(timer); globalThis.clearInterval(timer);
};
}, [enabled, cooldown]);
const startCooldown = useCallback((seconds: number) => {
setCooldown(Math.max(0, Math.floor(seconds)));
}, []);
return {
cooldown,
startCooldown,
}; };
}, [enabled, cooldown]);
const startCooldown = useCallback((seconds: number) => {
setCooldown(Math.max(0, Math.floor(seconds)));
}, []);
return {
cooldown,
startCooldown
};
} }

View File

@@ -4,65 +4,77 @@ import { useValidatedFields } from './useValidatedFields';
type FieldErrors<TValues> = Partial<Record<keyof TValues, string | undefined>>; type FieldErrors<TValues> = Partial<Record<keyof TValues, string | undefined>>;
type UseEditableFormOptions<TValues> = { type UseEditableFormOptions<TValues> = {
initialValues: TValues; initialValues: TValues;
validate: (values: TValues) => FieldErrors<TValues>; validate: (values: TValues) => FieldErrors<TValues>;
}; };
export function useEditableForm<TValues extends Record<string, string>>({ export function useEditableForm<TValues extends Record<string, string>>({
initialValues,
validate
}: UseEditableFormOptions<TValues>) {
const [isEditing, setIsEditing] = useState(false);
const {
values,
errors,
isValid,
setValues,
setFieldValue,
validateAll,
setFieldError,
setErrors,
clearErrors
} = useValidatedFields({
initialValues, initialValues,
validate validate,
}); }: UseEditableFormOptions<TValues>) {
const [isEditing, setIsEditing] = useState(false);
const startEditing = useCallback((sourceValues: TValues) => { const {
setValues(sourceValues, { validate: true }); values,
setIsEditing(true); errors,
}, [setValues]); isValid,
setValues,
setFieldValue,
validateAll,
setFieldError,
setErrors,
clearErrors,
} = useValidatedFields({
initialValues,
validate,
});
const discardChanges = useCallback((sourceValues: TValues) => { const startEditing = useCallback(
setValues(sourceValues, { clearErrors: true }); (sourceValues: TValues) => {
setIsEditing(false); setValues(sourceValues, { validate: true });
}, [setValues]); setIsEditing(true);
},
[setValues],
);
const loadFromSource = useCallback((sourceValues: TValues) => { const discardChanges = useCallback(
setValues(sourceValues, { clearErrors: true }); (sourceValues: TValues) => {
}, [setValues]); setValues(sourceValues, { clearErrors: true });
setIsEditing(false);
},
[setValues],
);
const commitSaved = useCallback((sourceValues: TValues) => { const loadFromSource = useCallback(
setValues(sourceValues, { clearErrors: true }); (sourceValues: TValues) => {
setIsEditing(false); setValues(sourceValues, { clearErrors: true });
}, [setValues]); },
[setValues],
);
return { const commitSaved = useCallback(
values, (sourceValues: TValues) => {
errors, setValues(sourceValues, { clearErrors: true });
isValid, setIsEditing(false);
setValues, },
setFieldValue, [setValues],
validateAll, );
setFieldError,
setErrors, return {
clearErrors, values,
isEditing, errors,
startEditing, isValid,
discardChanges, setValues,
loadFromSource, setFieldValue,
commitSaved, validateAll,
setIsEditing setFieldError,
}; setErrors,
clearErrors,
isEditing,
startEditing,
discardChanges,
loadFromSource,
commitSaved,
setIsEditing,
};
} }

View File

@@ -1,102 +1,111 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
type PaginatedResourceResponse<TItem> = { type PaginatedResourceResponse<TItem> = {
items: TItem[]; items: TItem[];
page: number; page: number;
pageSize: number; pageSize: number;
total: number; total: number;
totalPages: number; totalPages: number;
}; };
type UsePaginatedResourceOptions<TItem> = { type UsePaginatedResourceOptions<TItem> = {
load: (params: { q: string; page: number; pageSize: number; sort?: string }) => Promise<PaginatedResourceResponse<TItem>>; load: (params: {
sort?: string; q: string;
debounceMs?: number; page: number;
initialQuery?: string; pageSize: number;
initialPage?: number; sort?: string;
initialPageSize?: number; }) => Promise<PaginatedResourceResponse<TItem>>;
sort?: string;
debounceMs?: number;
initialQuery?: string;
initialPage?: number;
initialPageSize?: number;
}; };
export function usePaginatedResource<TItem>({ export function usePaginatedResource<TItem>({
load, load,
sort, sort,
debounceMs = 250, debounceMs = 250,
initialQuery = '', initialQuery = '',
initialPage = 1, initialPage = 1,
initialPageSize = 10 initialPageSize = 10,
}: UsePaginatedResourceOptions<TItem>) { }: UsePaginatedResourceOptions<TItem>) {
const [items, setItems] = useState<TItem[]>([]); const [items, setItems] = useState<TItem[]>([]);
const [q, setQ] = useState(initialQuery); const [q, setQ] = useState(initialQuery);
const [page, setPage] = useState(initialPage); const [page, setPage] = useState(initialPage);
const [pageSize, setPageSize] = useState(initialPageSize); const [pageSize, setPageSize] = useState(initialPageSize);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const [totalPages, setTotalPages] = useState(0); const [totalPages, setTotalPages] = useState(0);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
setIsLoading(true); setIsLoading(true);
setError(null); setError(null);
const timer = setTimeout(() => { const timer = setTimeout(() => {
void (async () => { void (async () => {
try { try {
const response = await load({ const response = await load({
q, q,
page, page,
pageSize, pageSize,
sort sort,
}); });
if (cancelled) { if (cancelled) {
return; return;
} }
setItems(response.items); setItems(response.items);
setTotal(response.total); setTotal(response.total);
setTotalPages(response.totalPages); setTotalPages(response.totalPages);
setPage(response.page); setPage(response.page);
setPageSize(response.pageSize); setPageSize(response.pageSize);
} catch (err) { } catch (err) {
if (!cancelled) { if (!cancelled) {
setError(err instanceof Error ? err.message : 'Request failed. Please try again.'); setError(
} err instanceof Error
} finally { ? err.message
if (!cancelled) { : 'Request failed. Please try again.',
setIsLoading(false); );
} }
} } finally {
})(); if (!cancelled) {
}, debounceMs); setIsLoading(false);
}
}
})();
}, debounceMs);
return () => { return () => {
cancelled = true; cancelled = true;
clearTimeout(timer); clearTimeout(timer);
};
}, [q, page, pageSize, sort, load, debounceMs]);
const setQuery = useCallback((value: string) => {
setQ(value);
setPage(1);
}, []);
const setPageSizeAndResetPage = useCallback((value: number) => {
setPageSize(value);
setPage(1);
}, []);
return {
items,
q,
page,
pageSize,
total,
totalPages,
error,
isLoading,
setQuery,
setPage,
setPageSize: setPageSizeAndResetPage,
}; };
}, [q, page, pageSize, sort, load, debounceMs]);
const setQuery = useCallback((value: string) => {
setQ(value);
setPage(1);
}, []);
const setPageSizeAndResetPage = useCallback((value: number) => {
setPageSize(value);
setPage(1);
}, []);
return {
items,
q,
page,
pageSize,
total,
totalPages,
error,
isLoading,
setQuery,
setPage,
setPageSize: setPageSizeAndResetPage
};
} }

View File

@@ -3,76 +3,79 @@ import { useCallback, useMemo, useState } from 'react';
export type SortDirection = 'asc' | 'desc'; export type SortDirection = 'asc' | 'desc';
export type SortState = { export type SortState = {
field: string; field: string;
direction: SortDirection; direction: SortDirection;
}; };
function invertDirection(direction: SortDirection): SortDirection { function invertDirection(direction: SortDirection): SortDirection {
return direction === 'asc' ? 'desc' : 'asc'; return direction === 'asc' ? 'desc' : 'asc';
} }
export function formatSortParam(sort: SortState | null | undefined): string | undefined { export function formatSortParam(sort: SortState | null | undefined): string | undefined {
if (!sort) { if (!sort) {
return undefined; return undefined;
} }
return sort.direction === 'desc' ? `-${sort.field}` : sort.field; return sort.direction === 'desc' ? `-${sort.field}` : sort.field;
} }
type UseSortingResult = { type UseSortingResult = {
activeSort: SortState | null; activeSort: SortState | null;
sortParam: string | undefined; sortParam: string | undefined;
toggleSort: (field: string) => void; toggleSort: (field: string) => void;
setSort: (next: SortState | null) => void; setSort: (next: SortState | null) => void;
resetSort: () => void; resetSort: () => void;
}; };
export function useSorting(defaultSort?: SortState | null): UseSortingResult { export function useSorting(defaultSort?: SortState | null): UseSortingResult {
const [overrideSort, setOverrideSort] = useState<SortState | null>(null); const [overrideSort, setOverrideSort] = useState<SortState | null>(null);
const activeSort = overrideSort ?? defaultSort ?? null; const activeSort = overrideSort ?? defaultSort ?? null;
const toggleSort = useCallback((field: string) => { const toggleSort = useCallback(
setOverrideSort((previousOverride) => { (field: string) => {
const baselineSort = defaultSort ?? null; setOverrideSort((previousOverride) => {
const currentSort = previousOverride ?? baselineSort; const baselineSort = defaultSort ?? null;
const currentSort = previousOverride ?? baselineSort;
if (!currentSort || currentSort.field !== field) { if (!currentSort || currentSort.field !== field) {
return { field, direction: 'asc' }; return { field, direction: 'asc' };
} }
if (baselineSort && baselineSort.field === field) { if (baselineSort && baselineSort.field === field) {
if (previousOverride == null) { if (previousOverride == null) {
return { field, direction: invertDirection(baselineSort.direction) }; return { field, direction: invertDirection(baselineSort.direction) };
} }
if (previousOverride.direction === baselineSort.direction) { if (previousOverride.direction === baselineSort.direction) {
return { field, direction: invertDirection(baselineSort.direction) }; return { field, direction: invertDirection(baselineSort.direction) };
} }
return null; return null;
} }
if (previousOverride == null || previousOverride.direction === 'desc') { if (previousOverride == null || previousOverride.direction === 'desc') {
return null; return null;
} }
return { field, direction: 'desc' }; return { field, direction: 'desc' };
}); });
}, [defaultSort]); },
[defaultSort],
);
const setSort = useCallback((next: SortState | null) => { const setSort = useCallback((next: SortState | null) => {
setOverrideSort(next); setOverrideSort(next);
}, []); }, []);
const resetSort = useCallback(() => { const resetSort = useCallback(() => {
setOverrideSort(null); setOverrideSort(null);
}, []); }, []);
const sortParam = useMemo(() => formatSortParam(activeSort), [activeSort]); const sortParam = useMemo(() => formatSortParam(activeSort), [activeSort]);
return { return {
activeSort, activeSort,
sortParam, sortParam,
toggleSort, toggleSort,
setSort, setSort,
resetSort resetSort,
}; };
} }

View File

@@ -1,31 +1,31 @@
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
export function useSubmitState<TStatus = string | null>(initialStatus: TStatus) { export function useSubmitState<TStatus = string | null>(initialStatus: TStatus) {
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null); const [submitError, setSubmitError] = useState<string | null>(null);
const [status, setStatus] = useState<TStatus>(initialStatus); const [status, setStatus] = useState<TStatus>(initialStatus);
const startSubmitting = useCallback(() => { const startSubmitting = useCallback(() => {
setIsSubmitting(true); setIsSubmitting(true);
}, []); }, []);
const finishSubmitting = useCallback(() => { const finishSubmitting = useCallback(() => {
setIsSubmitting(false); setIsSubmitting(false);
}, []); }, []);
const clearFeedback = useCallback(() => { const clearFeedback = useCallback(() => {
setSubmitError(null); setSubmitError(null);
setStatus(initialStatus); setStatus(initialStatus);
}, [initialStatus]); }, [initialStatus]);
return { return {
isSubmitting, isSubmitting,
submitError, submitError,
status, status,
startSubmitting, startSubmitting,
finishSubmitting, finishSubmitting,
setSubmitError, setSubmitError,
setStatus, setStatus,
clearFeedback clearFeedback,
}; };
} }

View File

@@ -4,163 +4,172 @@ type FieldErrors<TValues> = Partial<Record<keyof TValues, string | undefined>>;
type TouchedFields<TValues> = Partial<Record<keyof TValues, boolean>>; type TouchedFields<TValues> = Partial<Record<keyof TValues, boolean>>;
type SetValuesOptions = { type SetValuesOptions = {
validate?: boolean; validate?: boolean;
clearErrors?: boolean; clearErrors?: boolean;
}; };
type SetFieldValueOptions = { type SetFieldValueOptions = {
validate?: boolean; validate?: boolean;
touch?: boolean; touch?: boolean;
}; };
type ValidateAllOptions = { type ValidateAllOptions = {
touchAll?: boolean; touchAll?: boolean;
}; };
type UseValidatedFieldsOptions<TValues> = { type UseValidatedFieldsOptions<TValues> = {
initialValues: TValues; initialValues: TValues;
validate: (values: TValues) => FieldErrors<TValues>; validate: (values: TValues) => FieldErrors<TValues>;
}; };
function hasErrors<TValues>(errors: FieldErrors<TValues>): boolean { function hasErrors<TValues>(errors: FieldErrors<TValues>): boolean {
return Object.values(errors).some(Boolean); return Object.values(errors).some(Boolean);
} }
function pickTouchedErrors<TValues>( function pickTouchedErrors<TValues>(
errors: FieldErrors<TValues>, errors: FieldErrors<TValues>,
touched: TouchedFields<TValues> touched: TouchedFields<TValues>,
): FieldErrors<TValues> { ): FieldErrors<TValues> {
const next: FieldErrors<TValues> = {}; const next: FieldErrors<TValues> = {};
for (const key of Object.keys(errors) as Array<keyof TValues>) { for (const key of Object.keys(errors) as Array<keyof TValues>) {
if (touched[key]) { if (touched[key]) {
next[key] = errors[key]; next[key] = errors[key];
}
} }
}
return next; return next;
} }
function touchAll<TValues extends Record<string, string>>(values: TValues): TouchedFields<TValues> { function touchAll<TValues extends Record<string, string>>(values: TValues): TouchedFields<TValues> {
const touched: TouchedFields<TValues> = {}; const touched: TouchedFields<TValues> = {};
for (const key of Object.keys(values) as Array<keyof TValues>) { for (const key of Object.keys(values) as Array<keyof TValues>) {
touched[key] = true; touched[key] = true;
} }
return touched; return touched;
} }
export function useValidatedFields<TValues extends Record<string, string>>({ export function useValidatedFields<TValues extends Record<string, string>>({
initialValues, initialValues,
validate validate,
}: UseValidatedFieldsOptions<TValues>) { }: UseValidatedFieldsOptions<TValues>) {
const [values, setValues] = useState<TValues>(initialValues); const [values, setValues] = useState<TValues>(initialValues);
const [allErrors, setAllErrors] = useState<FieldErrors<TValues>>(() => validate(initialValues)); const [allErrors, setAllErrors] = useState<FieldErrors<TValues>>(() => validate(initialValues));
const [touched, setTouched] = useState<TouchedFields<TValues>>({}); const [touched, setTouched] = useState<TouchedFields<TValues>>({});
const updateValues = useCallback((nextValues: TValues, options: SetValuesOptions = {}) => { const updateValues = useCallback(
const { validate: shouldValidate = false, clearErrors = false } = options; (nextValues: TValues, options: SetValuesOptions = {}) => {
setValues(nextValues); const { validate: shouldValidate = false, clearErrors = false } = options;
setValues(nextValues);
if (shouldValidate || clearErrors) { if (shouldValidate || clearErrors) {
setAllErrors(validate(nextValues)); setAllErrors(validate(nextValues));
} }
if (clearErrors) { if (clearErrors) {
setTouched({}); setTouched({});
} }
}, [validate]); },
[validate],
);
const setFieldValue = useCallback(<K extends keyof TValues>( const setFieldValue = useCallback(
key: K, <K extends keyof TValues>(
value: TValues[K], key: K,
options: SetFieldValueOptions = {} value: TValues[K],
) => { options: SetFieldValueOptions = {},
const { validate: shouldValidate = true, touch = true } = options; ) => {
const { validate: shouldValidate = true, touch = true } = options;
if (touch) { if (touch) {
setTouched((current) => ({ setTouched((current) => ({
...current, ...current,
[key]: true [key]: true,
})); }));
} }
setValues((current) => { setValues((current) => {
const nextValues = { const nextValues = {
...current, ...current,
[key]: value [key]: value,
}; };
if (shouldValidate) { if (shouldValidate) {
setAllErrors(validate(nextValues)); setAllErrors(validate(nextValues));
} }
return nextValues; return nextValues;
}); });
}, [validate]); },
[validate],
);
const validateAll = useCallback((options: ValidateAllOptions = {}) => { const validateAll = useCallback(
const { touchAll: shouldTouchAll = true } = options; (options: ValidateAllOptions = {}) => {
const nextErrors = validate(values); const { touchAll: shouldTouchAll = true } = options;
const nextErrors = validate(values);
setAllErrors(nextErrors); setAllErrors(nextErrors);
if (shouldTouchAll) { if (shouldTouchAll) {
setTouched(touchAll(values)); setTouched(touchAll(values));
} }
return nextErrors; return nextErrors;
}, [validate, values]); },
[validate, values],
);
const setFieldError = useCallback(<K extends keyof TValues>(key: K, message?: string) => { const setFieldError = useCallback(<K extends keyof TValues>(key: K, message?: string) => {
setTouched((current) => ({ setTouched((current) => ({
...current, ...current,
[key]: true [key]: true,
})); }));
setAllErrors((current) => ({ setAllErrors((current) => ({
...current, ...current,
[key]: message [key]: message,
})); }));
}, []); }, []);
const updateErrors = useCallback((nextErrors: FieldErrors<TValues>) => { const updateErrors = useCallback((nextErrors: FieldErrors<TValues>) => {
const nextTouched: TouchedFields<TValues> = {}; const nextTouched: TouchedFields<TValues> = {};
for (const key of Object.keys(nextErrors) as Array<keyof TValues>) { for (const key of Object.keys(nextErrors) as Array<keyof TValues>) {
if (nextErrors[key]) { if (nextErrors[key]) {
nextTouched[key] = true; nextTouched[key] = true;
} }
} }
setTouched((current) => ({ setTouched((current) => ({
...current, ...current,
...nextTouched ...nextTouched,
})); }));
setAllErrors(nextErrors); setAllErrors(nextErrors);
}, []); }, []);
const clearErrors = useCallback(() => { const clearErrors = useCallback(() => {
setAllErrors(validate(values)); setAllErrors(validate(values));
setTouched({}); setTouched({});
}, [validate, values]); }, [validate, values]);
const errors = useMemo(() => pickTouchedErrors(allErrors, touched), [allErrors, touched]); const errors = useMemo(() => pickTouchedErrors(allErrors, touched), [allErrors, touched]);
const isValid = useMemo(() => { const isValid = useMemo(() => {
return !hasErrors(validate(values)); return !hasErrors(validate(values));
}, [validate, values]); }, [validate, values]);
return { return {
values, values,
errors, errors,
isValid, isValid,
setValues: updateValues, setValues: updateValues,
setFieldValue, setFieldValue,
validateAll, validateAll,
setFieldError, setFieldError,
setErrors: updateErrors, setErrors: updateErrors,
clearErrors clearErrors,
}; };
} }

View File

@@ -1,15 +1,27 @@
export { createAuthContext } from './auth/createAuthContext'; export { createAuthContext } from './auth/createAuthContext';
export type { AuthContextValue, AuthState, CreateAuthContextOptions } from './auth/createAuthContext'; export type {
AuthContextValue,
AuthState,
CreateAuthContextOptions,
} from './auth/createAuthContext';
export { decodeJwtPayload, isJwtExpired } from './auth/jwt'; export { decodeJwtPayload, isJwtExpired } from './auth/jwt';
export { createApiClient, ApiError } from './api/createApiClient'; export { createApiClient, ApiError } from './api/createApiClient';
export type { CreateApiClientConfig, RequestOptions, ResolveErrorInput } from './api/createApiClient'; export type {
CreateApiClientConfig,
RequestOptions,
ResolveErrorInput,
} from './api/createApiClient';
export { buildListQuery } from './api/query'; export { buildListQuery } from './api/query';
export { createErrorResolver } from './errors/createErrorResolver'; export { createErrorResolver } from './errors/createErrorResolver';
export type { CreateErrorResolverConfig, ErrorCatalog, ResolveErrorMessageOptions } from './errors/createErrorResolver'; export type {
CreateErrorResolverConfig,
ErrorCatalog,
ResolveErrorMessageOptions,
} from './errors/createErrorResolver';
export { useValidatedFields } from './hooks/useValidatedFields'; export { useValidatedFields } from './hooks/useValidatedFields';
export { useEditableForm } from './hooks/useEditableForm'; export { useEditableForm } from './hooks/useEditableForm';
@@ -20,9 +32,18 @@ export type { SortDirection, SortState } from './hooks/useSorting';
export { useCooldownTimer } from './hooks/useCooldownTimer'; export { useCooldownTimer } from './hooks/useCooldownTimer';
export { LeftMenuProvider, useLeftMenu } from './contexts/LeftMenuContext'; export { LeftMenuProvider, useLeftMenu } from './contexts/LeftMenuContext';
export type { LeftMenuContent, LeftMenuRenderState, LeftMenuStyle } from './contexts/LeftMenuContext'; export type {
LeftMenuContent,
LeftMenuRenderState,
LeftMenuSizing,
LeftMenuStyle,
} from './contexts/LeftMenuContext';
export { RightSidebarProvider, useRightSidebar } from './contexts/RightSidebarContext'; export { RightSidebarProvider, useRightSidebar } from './contexts/RightSidebarContext';
export type { RightSidebarContent, RightSidebarStyle } from './contexts/RightSidebarContext'; export type {
RightSidebarContent,
RightSidebarSizing,
RightSidebarStyle,
} from './contexts/RightSidebarContext';
export { formatDate, capitalize, splitAndCapitalize } from './utils/formatting'; export { formatDate, capitalize, splitAndCapitalize } from './utils/formatting';
export type { SplitMode } from './utils/formatting'; export type { SplitMode } from './utils/formatting';

View File

@@ -1,174 +1,190 @@
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'; import {
useCallback,
useEffect,
useRef,
useState,
type PointerEvent as ReactPointerEvent,
} from 'react';
const DEFAULT_DESKTOP_BREAKPOINT = 1024; const DEFAULT_DESKTOP_BREAKPOINT = 1024;
type ResizeAxis = 'from-left' | 'from-right'; type ResizeAxis = 'from-left' | 'from-right';
export type SidePanelMachineOptions = { export type SidePanelMachineOptions = {
storageKey: string; storageKey: string;
defaultWidth: number; defaultWidth: number;
minWidth: number; minWidth: number;
maxWidth: number; maxWidth: number;
resizeAxis: ResizeAxis; resizeAxis: ResizeAxis;
resizingBodyClass: string; resizingBodyClass: string;
isOpen: boolean; isOpen: boolean;
canResize: boolean; canResize: boolean;
shouldPersistWidth: boolean; shouldPersistWidth: boolean;
closeOnPathname?: string; closeOnPathname?: string;
onCloseOnPathname?: () => void; onCloseOnPathname?: () => void;
onEscape?: () => void; onEscape?: () => void;
desktopBreakpoint?: number; desktopBreakpoint?: number;
}; };
export type SidePanelMachineResult = { export type SidePanelMachineResult = {
width: number; width: number;
isDesktop: boolean; isDesktop: boolean;
startResize: (event: ReactPointerEvent<HTMLDivElement>) => void; startResize: (event: ReactPointerEvent<HTMLDivElement>) => void;
}; };
export function isDesktopViewport(breakpoint = DEFAULT_DESKTOP_BREAKPOINT): boolean { export function isDesktopViewport(breakpoint = DEFAULT_DESKTOP_BREAKPOINT): boolean {
if (!globalThis.window) { if (!globalThis.window) {
return true; return true;
} }
if (typeof globalThis.window.matchMedia === 'function') { if (typeof globalThis.window.matchMedia === 'function') {
return globalThis.window.matchMedia(`(min-width: ${breakpoint}px)`).matches; return globalThis.window.matchMedia(`(min-width: ${breakpoint}px)`).matches;
} }
return window.innerWidth >= breakpoint; return window.innerWidth >= breakpoint;
} }
export function useSidePanelMachine({ export function useSidePanelMachine({
storageKey, storageKey,
defaultWidth, defaultWidth,
minWidth, minWidth,
maxWidth, maxWidth,
resizeAxis, resizeAxis,
resizingBodyClass, resizingBodyClass,
isOpen, isOpen,
canResize, canResize,
shouldPersistWidth, shouldPersistWidth,
closeOnPathname, closeOnPathname,
onCloseOnPathname, onCloseOnPathname,
onEscape, onEscape,
desktopBreakpoint = DEFAULT_DESKTOP_BREAKPOINT desktopBreakpoint = DEFAULT_DESKTOP_BREAKPOINT,
}: SidePanelMachineOptions): SidePanelMachineResult { }: SidePanelMachineOptions): SidePanelMachineResult {
const isResizingRef = useRef(false); const isResizingRef = useRef(false);
const resizeStartXRef = useRef(0); const resizeStartXRef = useRef(0);
const resizeStartWidthRef = useRef(0); const resizeStartWidthRef = useRef(0);
const clampWidth = useCallback((value: number) => { const clampWidth = useCallback(
return Math.min(maxWidth, Math.max(minWidth, value)); (value: number) => {
}, [maxWidth, minWidth]); return Math.min(maxWidth, Math.max(minWidth, value));
},
[maxWidth, minWidth],
);
const readStoredWidth = useCallback(() => { const readStoredWidth = useCallback(() => {
if (!globalThis.window) { if (!globalThis.window) {
return defaultWidth; return defaultWidth;
} }
const storedValue = localStorage.getItem(storageKey); const storedValue = localStorage.getItem(storageKey);
const parsed = Number(storedValue); if (storedValue == null || storedValue.trim() === '') {
if (!Number.isFinite(parsed)) { return defaultWidth;
return defaultWidth; }
}
return clampWidth(parsed); const parsed = Number(storedValue);
}, [defaultWidth, storageKey, clampWidth]); if (!Number.isFinite(parsed)) {
return defaultWidth;
}
const [width, setWidth] = useState<number>(() => readStoredWidth()); return clampWidth(parsed);
}, [defaultWidth, storageKey, clampWidth]);
useEffect(() => { const [width, setWidth] = useState<number>(() => readStoredWidth());
if (closeOnPathname == null || !onCloseOnPathname) {
return;
}
onCloseOnPathname(); useEffect(() => {
}, [closeOnPathname, onCloseOnPathname]); if (closeOnPathname == null || !onCloseOnPathname) {
return;
}
useEffect(() => { onCloseOnPathname();
if (!shouldPersistWidth || !globalThis.window) { }, [closeOnPathname, onCloseOnPathname]);
return;
}
localStorage.setItem(storageKey, String(width)); useEffect(() => {
}, [shouldPersistWidth, storageKey, width]); if (!shouldPersistWidth || !globalThis.window) {
return;
}
useEffect(() => { localStorage.setItem(storageKey, String(width));
function handlePointerMove(event: PointerEvent) { }, [shouldPersistWidth, storageKey, width]);
if (!isResizingRef.current || !canResize) {
return;
}
const deltaX = event.clientX - resizeStartXRef.current; useEffect(() => {
const delta = resizeAxis === 'from-left' ? deltaX : -deltaX; function handlePointerMove(event: PointerEvent) {
const nextWidth = clampWidth(resizeStartWidthRef.current + delta); if (!isResizingRef.current || !canResize) {
setWidth(nextWidth); return;
} }
function stopResizing() { const deltaX = event.clientX - resizeStartXRef.current;
if (!isResizingRef.current) { const delta = resizeAxis === 'from-left' ? deltaX : -deltaX;
return; const nextWidth = clampWidth(resizeStartWidthRef.current + delta);
} setWidth(nextWidth);
}
isResizingRef.current = false; function stopResizing() {
document.body.classList.remove(resizingBodyClass); if (!isResizingRef.current) {
} return;
}
globalThis.addEventListener('pointermove', handlePointerMove); isResizingRef.current = false;
globalThis.addEventListener('pointerup', stopResizing); document.body.classList.remove(resizingBodyClass);
}
return () => { globalThis.addEventListener('pointermove', handlePointerMove);
globalThis.removeEventListener('pointermove', handlePointerMove); globalThis.addEventListener('pointerup', stopResizing);
globalThis.removeEventListener('pointerup', stopResizing);
document.body.classList.remove(resizingBodyClass); return () => {
globalThis.removeEventListener('pointermove', handlePointerMove);
globalThis.removeEventListener('pointerup', stopResizing);
document.body.classList.remove(resizingBodyClass);
};
}, [canResize, clampWidth, resizeAxis, resizingBodyClass]);
useEffect(() => {
if (!isOpen || isDesktopViewport(desktopBreakpoint)) {
return;
}
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = previousOverflow;
};
}, [isOpen, desktopBreakpoint]);
useEffect(() => {
if (!isOpen || !onEscape) {
return;
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onEscape();
}
};
globalThis.addEventListener('keydown', handleEscape);
return () => {
globalThis.removeEventListener('keydown', handleEscape);
};
}, [isOpen, onEscape]);
const startResize = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (!canResize || !isDesktopViewport(desktopBreakpoint)) {
return;
}
isResizingRef.current = true;
resizeStartXRef.current = event.clientX;
resizeStartWidthRef.current = width;
document.body.classList.add(resizingBodyClass);
event.preventDefault();
},
[canResize, desktopBreakpoint, resizingBodyClass, width],
);
return {
width,
isDesktop: isDesktopViewport(desktopBreakpoint),
startResize,
}; };
}, [canResize, clampWidth, resizeAxis, resizingBodyClass]);
useEffect(() => {
if (!isOpen || isDesktopViewport(desktopBreakpoint)) {
return;
}
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = previousOverflow;
};
}, [isOpen, desktopBreakpoint]);
useEffect(() => {
if (!isOpen || !onEscape) {
return;
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onEscape();
}
};
globalThis.addEventListener('keydown', handleEscape);
return () => {
globalThis.removeEventListener('keydown', handleEscape);
};
}, [isOpen, onEscape]);
const startResize = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
if (!canResize || !isDesktopViewport(desktopBreakpoint)) {
return;
}
isResizingRef.current = true;
resizeStartXRef.current = event.clientX;
resizeStartWidthRef.current = width;
document.body.classList.add(resizingBodyClass);
event.preventDefault();
}, [canResize, desktopBreakpoint, resizingBodyClass, width]);
return {
width,
isDesktop: isDesktopViewport(desktopBreakpoint),
startResize
};
} }

View File

@@ -1,21 +1,24 @@
export function formatDate(value: string, seconds = false): string { export function formatDate(value: string, seconds = false): string {
const options: Intl.DateTimeFormatOptions = { const options: Intl.DateTimeFormatOptions = {
year: "numeric", year: 'numeric',
month: "2-digit", month: '2-digit',
day: "2-digit", day: '2-digit',
hour: "2-digit", hour: '2-digit',
minute: "2-digit", minute: '2-digit',
...(seconds ? { second: "2-digit" } : {}), ...(seconds ? { second: '2-digit' } : {}),
}; };
return new Date(value).toLocaleString("it-IT", options); return new Date(value).toLocaleString('it-IT', options);
} }
export const capitalize = (str: string) => export const capitalize = (str: string) =>
str.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' '); str
.toLowerCase()
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
export type SplitMode = "underscore" | "camel" | "auto"; export type SplitMode = 'underscore' | 'camel' | 'auto';
/** Title-case a string while preserving short all-caps acronyms (e.g., XML) */ /** Title-case a string while preserving short all-caps acronyms (e.g., XML) */
const toTitleCase = (s: string) => const toTitleCase = (s: string) =>
@@ -23,23 +26,23 @@ const toTitleCase = (s: string) =>
.trim() .trim()
.toLowerCase() .toLowerCase()
.split(/\s+/) .split(/\s+/)
.map(w => .map((w) =>
/^[A-Z]{2,4}$/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase() /^[A-Z]{2,4}$/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase(),
) )
.join(" "); .join(' ');
const splitUnderscoreHyphen = (s: string) => s.replaceAll(/[_-]+/g, " "); const splitUnderscoreHyphen = (s: string) => s.replaceAll(/[_-]+/g, ' ');
/** Insert spaces at camelCase boundaries and around digit/letter edges */ /** Insert spaces at camelCase boundaries and around digit/letter edges */
const splitCamel = (s: string) => const splitCamel = (s: string) =>
s s
// fooBar -> foo Bar ; foo2D -> foo 2D // fooBar -> foo Bar ; foo2D -> foo 2D
.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2") .replaceAll(/([a-z0-9])([A-Z])/g, '$1 $2')
// XMLHttp -> XML Http (acronym + word) // XMLHttp -> XML Http (acronym + word)
.replaceAll(/([A-Z])([A-Z][a-z])/g, "$1 $2") .replaceAll(/([A-Z])([A-Z][a-z])/g, '$1 $2')
// letter<->digit boundaries // letter<->digit boundaries
.replaceAll(/([a-zA-Z])([0-9])/g, "$1 $2") .replaceAll(/([a-zA-Z])([0-9])/g, '$1 $2')
.replaceAll(/([0-9])([a-zA-Z])/g, "$1 $2"); .replaceAll(/([0-9])([a-zA-Z])/g, '$1 $2');
/** /**
* Split and capitalize either by underscores/hyphens or camelCase. * Split and capitalize either by underscores/hyphens or camelCase.
@@ -48,17 +51,15 @@ const splitCamel = (s: string) =>
* - "camel": split on camelCase boundaries * - "camel": split on camelCase boundaries
* - "auto": pick underscore if present, otherwise camel * - "auto": pick underscore if present, otherwise camel
*/ */
export function splitAndCapitalize(str?: string, mode: SplitMode = "auto"): string { export function splitAndCapitalize(str?: string, mode: SplitMode = 'auto'): string {
if (!str) return ""; if (!str) return '';
// normalize underscores/hyphens first for auto decision // normalize underscores/hyphens first for auto decision
const hasUnderscoreLike = /[_-]/.test(str); const hasUnderscoreLike = /[_-]/.test(str);
const chosen: SplitMode = const chosen: SplitMode = mode === 'auto' ? (hasUnderscoreLike ? 'underscore' : 'camel') : mode;
mode === "auto" ? (hasUnderscoreLike ? "underscore" : "camel") : mode;
const spaced = const spaced = chosen === 'underscore' ? splitUnderscoreHyphen(str) : splitCamel(str);
chosen === "underscore" ? splitUnderscoreHyphen(str) : splitCamel(str);
// collapse extra spaces, then title-case // collapse extra spaces, then title-case
return toTitleCase(spaced.replaceAll(/\s+/g, " ").trim()); return toTitleCase(spaced.replaceAll(/\s+/g, ' ').trim());
} }

View File

@@ -1,20 +1,20 @@
type VerifiedEmailVisibilityOptions = { type VerifiedEmailVisibilityOptions = {
verifiedAt: string | null; verifiedAt: string | null;
persistedEmail: string; persistedEmail: string;
currentEmail: string; currentEmail: string;
isEditing: boolean; isEditing: boolean;
}; };
export function shouldShowVerifiedEmailBadge(options: VerifiedEmailVisibilityOptions): boolean { export function shouldShowVerifiedEmailBadge(options: VerifiedEmailVisibilityOptions): boolean {
const { verifiedAt, persistedEmail, currentEmail, isEditing } = options; const { verifiedAt, persistedEmail, currentEmail, isEditing } = options;
if (!verifiedAt) { if (!verifiedAt) {
return false; return false;
} }
if (!isEditing) { if (!isEditing) {
return true; return true;
} }
return persistedEmail.trim() === currentEmail.trim(); return persistedEmail.trim() === currentEmail.trim();
} }

View File

@@ -0,0 +1,154 @@
import { describe, expect, it, vi } from 'vitest';
import { ApiError, createApiClient } from '../../src/api/createApiClient';
describe('createApiClient', () => {
it('sends json requests and returns parsed payload', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: vi.fn().mockResolvedValue({ ok: true }),
} as unknown as Response);
const client = createApiClient({
baseUrl: 'https://api.example.com',
fetchImpl: fetchMock as typeof fetch,
});
const result = await client.request<{ ok: boolean }>('/users', {
method: 'POST',
token: 'token-123',
body: { hello: 'world' },
});
expect(result).toEqual({ ok: true });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer token-123',
},
body: JSON.stringify({ hello: 'world' }),
});
});
it('maps api error payload through custom resolver', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 401,
json: vi.fn().mockResolvedValue({
code: 'AUTH_UNAUTHORIZED',
error: 'unauthorized',
requestId: 'req-1',
details: { reason: 'expired' },
}),
} as unknown as Response);
const resolveError = vi.fn(() => 'Unauthorized access. Please sign in again.');
const client = createApiClient({
baseUrl: 'https://api.example.com',
fetchImpl: fetchMock as typeof fetch,
resolveError,
});
await expect(client.request('/users')).rejects.toMatchObject({
name: 'ApiError',
status: 401,
code: 'AUTH_UNAUTHORIZED',
requestId: 'req-1',
details: { reason: 'expired' },
rawMessage: 'unauthorized',
message: 'Unauthorized access. Please sign in again.',
});
expect(resolveError).toHaveBeenCalledWith({
code: 'AUTH_UNAUTHORIZED',
status: 401,
fallbackMessage: 'unauthorized',
});
});
it('infers an error code from status when payload has no code', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 404,
json: vi.fn().mockResolvedValue({ error: 'missing resource' }),
} as unknown as Response);
const inferErrorCodeFromStatus = vi.fn((status?: number | null) =>
status === 404 ? 'USER_NOT_FOUND' : undefined,
);
const client = createApiClient({
baseUrl: 'https://api.example.com',
fetchImpl: fetchMock as typeof fetch,
inferErrorCodeFromStatus,
resolveError: ({ code }) => (code === 'USER_NOT_FOUND' ? 'User not found.' : 'Unknown'),
});
await expect(client.request('/users/missing')).rejects.toMatchObject({
code: 'USER_NOT_FOUND',
message: 'User not found.',
});
});
it('falls back to default messages when response is not valid json', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: vi.fn().mockRejectedValue(new Error('invalid json')),
} as unknown as Response);
const client = createApiClient({
baseUrl: 'https://api.example.com',
fetchImpl: fetchMock as typeof fetch,
});
await expect(client.request('/users')).rejects.toMatchObject({
code: undefined,
rawMessage: undefined,
message: 'Request failed (500).',
});
});
it('uses generic default message when status is unavailable', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: undefined,
json: vi.fn().mockResolvedValue(null),
} as unknown as Response);
const client = createApiClient({
baseUrl: 'https://api.example.com',
fetchImpl: fetchMock as typeof fetch,
});
let thrown: unknown;
try {
await client.request('/users');
} catch (err) {
thrown = err;
}
expect(thrown).toBeInstanceOf(ApiError);
expect((thrown as ApiError).message).toBe('Request failed. Please try again.');
});
it('uses raw fallback error text with the default resolver when present', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 400,
json: vi.fn().mockResolvedValue({
error: 'Validation failed in backend.',
}),
} as unknown as Response);
const client = createApiClient({
baseUrl: 'https://api.example.com',
fetchImpl: fetchMock as typeof fetch,
});
await expect(client.request('/users')).rejects.toMatchObject({
message: 'Validation failed in backend.',
rawMessage: 'Validation failed in backend.',
});
});
});

25
tests/api/query.test.ts Normal file
View File

@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { buildListQuery } from '../../src/api/query';
describe('buildListQuery', () => {
it('builds query with trimmed search and explicit sort', () => {
const result = buildListQuery({
q: ' jane ',
page: 3,
pageSize: 20,
sort: ' createdAt ',
defaultSort: '-createdAt',
});
expect(result).toBe('q=jane&page=3&pageSize=20&sort=createdAt');
});
it('falls back to defaults when query is blank and sort missing', () => {
const result = buildListQuery({
q: ' ',
defaultSort: '-createdAt',
});
expect(result).toBe('page=1&pageSize=10&sort=-createdAt');
});
});

View File

@@ -0,0 +1,143 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { createAuthContext } from '../../src/auth/createAuthContext';
type User = {
id: string;
username: string;
};
const defaultAuth = createAuthContext<User>();
function createUser(username: string): User {
return {
id: `id-${username}`,
username,
};
}
function AuthHarness() {
const { authToken, refreshToken, currentUser, setSession, setCurrentUser, clearSession } =
defaultAuth.useAuth();
return (
<div>
<span data-testid="auth-token">{authToken ?? 'none'}</span>
<span data-testid="refresh-token">{refreshToken ?? 'none'}</span>
<span data-testid="username">{currentUser?.username ?? 'none'}</span>
<button
type="button"
onClick={() => setSession('auth-next', 'refresh-next', createUser('after-set'))}
>
set-session
</button>
<button type="button" onClick={() => setCurrentUser(createUser('patched'))}>
set-user
</button>
<button type="button" onClick={clearSession}>
clear
</button>
</div>
);
}
describe('createAuthContext', () => {
it('throws when hook is used outside the provider', () => {
function Invalid() {
defaultAuth.useAuth();
return null;
}
expect(() => render(<Invalid />)).toThrow('useAuth must be used within AuthProvider');
});
it('reads persisted tokens and cleans default legacy keys', () => {
localStorage.setItem('authToken', 'auth-1');
localStorage.setItem('refreshToken', 'refresh-1');
localStorage.setItem('auth_token', 'legacy');
localStorage.setItem('auth_user', 'legacy');
localStorage.setItem('token', 'legacy');
render(
<defaultAuth.AuthProvider>
<AuthHarness />
</defaultAuth.AuthProvider>,
);
expect(screen.getByTestId('auth-token')).toHaveTextContent('auth-1');
expect(screen.getByTestId('refresh-token')).toHaveTextContent('refresh-1');
expect(localStorage.getItem('auth_token')).toBeNull();
expect(localStorage.getItem('auth_user')).toBeNull();
expect(localStorage.getItem('token')).toBeNull();
});
it('supports session lifecycle updates', () => {
render(
<defaultAuth.AuthProvider>
<AuthHarness />
</defaultAuth.AuthProvider>,
);
fireEvent.click(screen.getByRole('button', { name: 'set-session' }));
expect(screen.getByTestId('auth-token')).toHaveTextContent('auth-next');
expect(screen.getByTestId('refresh-token')).toHaveTextContent('refresh-next');
expect(screen.getByTestId('username')).toHaveTextContent('after-set');
expect(localStorage.getItem('authToken')).toBe('auth-next');
expect(localStorage.getItem('refreshToken')).toBe('refresh-next');
fireEvent.click(screen.getByRole('button', { name: 'set-user' }));
expect(screen.getByTestId('username')).toHaveTextContent('patched');
fireEvent.click(screen.getByRole('button', { name: 'clear' }));
expect(screen.getByTestId('auth-token')).toHaveTextContent('none');
expect(screen.getByTestId('refresh-token')).toHaveTextContent('none');
expect(screen.getByTestId('username')).toHaveTextContent('none');
expect(localStorage.getItem('authToken')).toBeNull();
expect(localStorage.getItem('refreshToken')).toBeNull();
});
it('supports custom token keys and legacy cleanup keys', () => {
const customAuth = createAuthContext<User>({
authTokenKey: 'custom-auth',
refreshTokenKey: 'custom-refresh',
legacyKeys: ['legacy-a', 'legacy-b'],
});
function CustomHarness() {
const { authToken, refreshToken, setSession } = customAuth.useAuth();
return (
<div>
<span data-testid="custom-auth-token">{authToken ?? 'none'}</span>
<span data-testid="custom-refresh-token">{refreshToken ?? 'none'}</span>
<button
type="button"
onClick={() => setSession('next-auth', 'next-refresh', createUser('custom'))}
>
set-custom-session
</button>
</div>
);
}
localStorage.setItem('custom-auth', 'auth-1');
localStorage.setItem('custom-refresh', 'refresh-1');
localStorage.setItem('legacy-a', 'legacy');
localStorage.setItem('legacy-b', 'legacy');
render(
<customAuth.AuthProvider>
<CustomHarness />
</customAuth.AuthProvider>,
);
expect(screen.getByTestId('custom-auth-token')).toHaveTextContent('auth-1');
expect(screen.getByTestId('custom-refresh-token')).toHaveTextContent('refresh-1');
expect(localStorage.getItem('legacy-a')).toBeNull();
expect(localStorage.getItem('legacy-b')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'set-custom-session' }));
expect(localStorage.getItem('custom-auth')).toBe('next-auth');
expect(localStorage.getItem('custom-refresh')).toBe('next-refresh');
});
});

60
tests/auth/jwt.test.ts Normal file
View File

@@ -0,0 +1,60 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { decodeJwtPayload, isJwtExpired } from '../../src/auth/jwt';
function createJwt(payload: Record<string, unknown>) {
const header = { alg: 'HS256', typ: 'JWT' };
const encode = (value: object) =>
btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
return `${encode(header)}.${encode(payload)}.signature`;
}
describe('decodeJwtPayload', () => {
it('returns null for malformed tokens or invalid payloads', () => {
expect(decodeJwtPayload('not-a-jwt')).toBeNull();
expect(decodeJwtPayload('a.b')).toBeNull();
expect(decodeJwtPayload('a.b.c.d')).toBeNull();
const nonJson = 'header.' + btoa('nope') + '.sig';
expect(decodeJwtPayload(nonJson)).toBeNull();
const nonObjectPayload = createJwt({ value: 1 }).replace(
/\.[^.]+\./,
`.${btoa('1').replace(/=+$/g, '')}.`,
);
expect(decodeJwtPayload(nonObjectPayload)).toBeNull();
});
it('decodes valid base64url payloads', () => {
const payload = { sub: 'user-1', role: 'ADMIN', exp: 1735689600 };
expect(decodeJwtPayload(createJwt(payload))).toEqual(payload);
});
});
describe('isJwtExpired', () => {
beforeEach(() => {
vi.useFakeTimers();
});
it('returns false for malformed tokens and invalid exp claim', () => {
expect(isJwtExpired('not-a-jwt')).toBe(false);
expect(isJwtExpired(createJwt({}))).toBe(false);
expect(isJwtExpired(createJwt({ exp: 'nope' }))).toBe(false);
expect(isJwtExpired(createJwt({ exp: Number.POSITIVE_INFINITY }))).toBe(false);
});
it('returns true when token is expired', () => {
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
const exp = Math.floor(new Date('2025-12-31T23:59:00Z').getTime() / 1000);
expect(isJwtExpired(createJwt({ exp }))).toBe(true);
});
it('applies skew seconds when evaluating expiration', () => {
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
const exp = Math.floor(new Date('2026-01-01T00:00:10Z').getTime() / 1000);
expect(isJwtExpired(createJwt({ exp }), 15)).toBe(true);
expect(isJwtExpired(createJwt({ exp }), 5)).toBe(false);
});
});

View File

@@ -0,0 +1,246 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { act } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
LeftMenuProvider,
type LeftMenuContent,
useLeftMenu,
} from '../../src/contexts/LeftMenuContext';
function buildDefaultContent(label = 'Default menu'): LeftMenuContent {
return {
ariaLabel: label,
render: ({ collapsed }) => <div>{collapsed ? `${label} (collapsed)` : `${label} (expanded)`}</div>,
};
}
function setViewportWidth(width: number) {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
writable: true,
value: width,
});
Object.defineProperty(window, 'matchMedia', {
configurable: true,
writable: true,
value: undefined,
});
}
function renderLeftMenuHarness(initialPathname = '/users') {
let currentPathname = initialPathname;
let currentValue: ReturnType<typeof useLeftMenu> | null = null;
const defaultContent = buildDefaultContent();
function Probe() {
currentValue = useLeftMenu();
const renderState = {
collapsed: currentValue.collapsed,
mobileOpen: currentValue.mobileOpen,
isDesktop: window.innerWidth >= 1024,
closeMenu: currentValue.closeMenu,
};
return <div data-testid="left-menu-content">{currentValue.content.render(renderState)}</div>;
}
function Wrapper({ pathname }: Readonly<{ pathname: string }>) {
return (
<LeftMenuProvider defaultContent={defaultContent} closeOnPathname={pathname}>
<Probe />
</LeftMenuProvider>
);
}
const rendered = render(<Wrapper pathname={currentPathname} />);
return {
getCurrent() {
if (!currentValue) {
throw new Error('Left menu context value not initialized');
}
return currentValue;
},
reroute(nextPathname: string) {
currentPathname = nextPathname;
rendered.rerender(<Wrapper pathname={currentPathname} />);
},
};
}
describe('LeftMenuContext', () => {
beforeEach(() => {
localStorage.removeItem('authSidebarWidth');
localStorage.removeItem('authSidebarCollapsed');
setViewportWidth(1024);
});
it('throws when useLeftMenu is used outside provider', () => {
function Invalid() {
useLeftMenu();
return null;
}
expect(() => render(<Invalid />)).toThrow('useLeftMenu must be used within LeftMenuProvider');
});
it('supports desktop collapse/expand/toggle semantics', () => {
const harness = renderLeftMenuHarness('/users');
expect(harness.getCurrent().collapsed).toBe(false);
act(() => {
harness.getCurrent().closeMenu();
});
expect(harness.getCurrent().collapsed).toBe(true);
act(() => {
harness.getCurrent().openMenu();
});
expect(harness.getCurrent().collapsed).toBe(false);
act(() => {
harness.getCurrent().toggleMenu();
});
expect(harness.getCurrent().collapsed).toBe(true);
});
it('restores collapsed state from storage and clamps persisted width', () => {
localStorage.setItem('authSidebarCollapsed', '1');
localStorage.setItem('authSidebarWidth', '999');
const harness = renderLeftMenuHarness('/users');
expect(harness.getCurrent().collapsed).toBe(true);
expect(harness.getCurrent().desktopMenuStyle['--auth-sidebar-width']).toBe('56px');
});
it('locks body scroll on mobile open and unlocks on close', () => {
setViewportWidth(768);
const harness = renderLeftMenuHarness('/users');
act(() => {
harness.getCurrent().openMenu();
});
expect(harness.getCurrent().mobileOpen).toBe(true);
expect(document.body.style.overflow).toBe('hidden');
act(() => {
harness.getCurrent().closeMenu();
});
expect(harness.getCurrent().mobileOpen).toBe(false);
expect(document.body.style.overflow).toBe('');
});
it('reads, clamps, and persists sidebar width through pointer resize', async () => {
localStorage.setItem('authSidebarWidth', '999');
const harness = renderLeftMenuHarness('/users');
expect(harness.getCurrent().desktopMenuStyle['--auth-sidebar-width']).toBe('420px');
const preventDefault = vi.fn();
act(() => {
harness.getCurrent().startResize({
clientX: 420,
preventDefault,
} as never);
});
act(() => {
fireEvent.pointerMove(window, { clientX: -1000 });
fireEvent.pointerUp(window);
});
await act(async () => {
await Promise.resolve();
});
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(localStorage.getItem('authSidebarWidth')).toBe('220');
expect(harness.getCurrent().desktopMenuStyle['--auth-sidebar-width']).toBe('220px');
});
it('accepts custom content and resets to default on route changes', () => {
setViewportWidth(768);
const harness = renderLeftMenuHarness('/users');
act(() => {
harness.getCurrent().openMenu();
harness.getCurrent().setMenuContent({
ariaLabel: 'Custom menu',
render: () => <div>Custom menu content</div>,
});
});
expect(harness.getCurrent().mobileOpen).toBe(true);
expect(screen.getByText('Custom menu content')).toBeInTheDocument();
harness.reroute('/posts');
expect(harness.getCurrent().mobileOpen).toBe(false);
expect(screen.queryByText('Custom menu content')).not.toBeInTheDocument();
expect(screen.getByText('Default menu (expanded)')).toBeInTheDocument();
});
it('applies provided content in openMenu/toggleMenu and toggles mobile open state', () => {
setViewportWidth(768);
const harness = renderLeftMenuHarness('/users');
act(() => {
harness.getCurrent().openMenu({
render: () => <div>Open payload</div>,
});
});
expect(screen.getByText('Open payload')).toBeInTheDocument();
expect(harness.getCurrent().mobileOpen).toBe(true);
act(() => {
harness.getCurrent().toggleMenu({
render: () => <div>Toggle payload</div>,
});
});
expect(screen.getByText('Toggle payload')).toBeInTheDocument();
expect(harness.getCurrent().mobileOpen).toBe(false);
});
it('updates default content only when current content is still default', () => {
function Harness() {
const menu = useLeftMenu();
const state = {
collapsed: menu.collapsed,
mobileOpen: menu.mobileOpen,
isDesktop: true,
closeMenu: menu.closeMenu,
};
return (
<div>
<button type="button" onClick={() => menu.setMenuContent({ render: () => <div>Custom</div> })}>
custom
</button>
<div data-testid="content">{menu.content.render(state)}</div>
</div>
);
}
function Wrapper({ label }: Readonly<{ label: string }>) {
return (
<LeftMenuProvider defaultContent={buildDefaultContent(label)}>
<Harness />
</LeftMenuProvider>
);
}
const rendered = render(<Wrapper label="Menu A" />);
expect(screen.getByTestId('content')).toHaveTextContent('Menu A (expanded)');
rendered.rerender(<Wrapper label="Menu B" />);
expect(screen.getByTestId('content')).toHaveTextContent('Menu B (expanded)');
fireEvent.click(screen.getByRole('button', { name: 'custom' }));
expect(screen.getByTestId('content')).toHaveTextContent('Custom');
rendered.rerender(<Wrapper label="Menu C" />);
expect(screen.getByTestId('content')).toHaveTextContent('Custom');
});
});

View File

@@ -0,0 +1,249 @@
import { fireEvent, render } from '@testing-library/react';
import { act } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
RightSidebarProvider,
useRightSidebar,
} from '../../src/contexts/RightSidebarContext';
type RightSidebarHarnessOptions = {
pathname?: string;
onMobileOpenRequest?: () => void;
};
function setViewportWidth(width: number) {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
writable: true,
value: width,
});
Object.defineProperty(window, 'matchMedia', {
configurable: true,
writable: true,
value: undefined,
});
}
function renderRightSidebarHarness(options: RightSidebarHarnessOptions = {}) {
const { pathname = '/users', onMobileOpenRequest } = options;
let currentPathname = pathname;
let currentValue: ReturnType<typeof useRightSidebar> | null = null;
function Probe() {
currentValue = useRightSidebar();
return null;
}
function Wrapper({ pathname }: Readonly<{ pathname: string }>) {
return (
<RightSidebarProvider
closeOnPathname={pathname}
onMobileOpenRequest={onMobileOpenRequest}
>
<Probe />
</RightSidebarProvider>
);
}
const rendered = render(<Wrapper pathname={currentPathname} />);
return {
getCurrent() {
if (!currentValue) {
throw new Error('Right sidebar context value not initialized');
}
return currentValue;
},
reroute(nextPathname: string) {
currentPathname = nextPathname;
rendered.rerender(<Wrapper pathname={currentPathname} />);
},
unmount: rendered.unmount,
};
}
describe('RightSidebarContext', () => {
beforeEach(() => {
localStorage.removeItem('authRightSidebarWidth');
setViewportWidth(1024);
});
it('throws when useRightSidebar is used outside provider', () => {
function Invalid() {
useRightSidebar();
return null;
}
expect(() => render(<Invalid />)).toThrow('useRightSidebar must be used within RightSidebarProvider');
});
it('opens and closes with content', () => {
const harness = renderRightSidebarHarness({ pathname: '/users' });
act(() => {
harness.getCurrent().openSidebar({
title: 'Meta',
content: <div>Body</div>,
});
});
expect(harness.getCurrent().isOpen).toBe(true);
expect(harness.getCurrent().content?.title).toBe('Meta');
act(() => {
harness.getCurrent().closeSidebar();
});
expect(harness.getCurrent().isOpen).toBe(false);
expect(harness.getCurrent().content).toBeNull();
});
it('does not open without current or next content', () => {
const harness = renderRightSidebarHarness({ pathname: '/users' });
act(() => {
harness.getCurrent().openSidebar();
});
expect(harness.getCurrent().isOpen).toBe(false);
expect(harness.getCurrent().content).toBeNull();
});
it('updates content live and supports toggle semantics', () => {
const harness = renderRightSidebarHarness({ pathname: '/users' });
act(() => {
harness.getCurrent().openSidebar({
title: 'Meta',
content: <div>Body</div>,
});
});
act(() => {
harness.getCurrent().setSidebarContent({
title: 'Meta Updated',
content: <div>Updated</div>,
});
});
expect(harness.getCurrent().isOpen).toBe(true);
expect(harness.getCurrent().content?.title).toBe('Meta Updated');
act(() => {
harness.getCurrent().toggleSidebar();
});
expect(harness.getCurrent().isOpen).toBe(false);
expect(harness.getCurrent().content).toBeNull();
});
it('toggleSidebar opens with provided content when closed', () => {
const harness = renderRightSidebarHarness({ pathname: '/users' });
act(() => {
harness.getCurrent().toggleSidebar({
title: 'Toggle open',
content: <div>Toggle body</div>,
});
});
expect(harness.getCurrent().isOpen).toBe(true);
expect(harness.getCurrent().content?.title).toBe('Toggle open');
});
it('closes on pathname changes', () => {
const harness = renderRightSidebarHarness({ pathname: '/users' });
act(() => {
harness.getCurrent().openSidebar({
title: 'Meta',
content: <div>Body</div>,
});
});
expect(harness.getCurrent().isOpen).toBe(true);
harness.reroute('/posts');
expect(harness.getCurrent().isOpen).toBe(false);
expect(harness.getCurrent().content).toBeNull();
});
it('reads/clamps persisted width, persists resized widths, and reacts to escape', async () => {
localStorage.setItem('authRightSidebarWidth', '999');
const harness = renderRightSidebarHarness({ pathname: '/users' });
expect(harness.getCurrent().desktopSidebarStyle['--auth-right-sidebar-width']).toBe(
'480px',
);
act(() => {
harness.getCurrent().openSidebar({
title: 'Meta',
content: <div>Body</div>,
});
});
const preventDefault = vi.fn();
act(() => {
harness.getCurrent().startResize({
clientX: 480,
preventDefault,
} as never);
});
act(() => {
fireEvent.pointerMove(window, { clientX: -400 });
fireEvent.pointerUp(window);
});
await act(async () => {
await Promise.resolve();
});
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(localStorage.getItem('authRightSidebarWidth')).toBe('480');
act(() => {
fireEvent.keyDown(window, { key: 'Escape' });
});
expect(harness.getCurrent().isOpen).toBe(false);
});
it('notifies mobile open requests when opening on mobile', () => {
setViewportWidth(768);
const onMobileOpenRequest = vi.fn();
const harness = renderRightSidebarHarness({
pathname: '/users',
onMobileOpenRequest,
});
act(() => {
harness.getCurrent().openSidebar({
title: 'Meta',
content: <div>Body</div>,
});
});
expect(harness.getCurrent().isOpen).toBe(true);
expect(onMobileOpenRequest).toHaveBeenCalledTimes(1);
});
it('normalizes custom sizing values', () => {
function Probe() {
const sidebar = useRightSidebar();
return <div data-testid="width">{sidebar.desktopSidebarStyle['--auth-right-sidebar-width']}</div>;
}
const { getByTestId } = render(
<RightSidebarProvider
sizing={{
defaultWidth: 1000,
minWidth: 500,
maxWidth: 300,
}}
>
<Probe />
</RightSidebarProvider>,
);
expect(getByTestId('width').textContent).toBe('500px');
});
});

View File

@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import { createErrorResolver } from '../../src/errors/createErrorResolver';
const CATALOG = {
AUTH_UNAUTHORIZED: 'Unauthorized access. Please sign in again.',
FORBIDDEN: 'You do not have permission to perform this action.',
USER_NOT_FOUND: 'User not found.',
INTERNAL_ERROR: 'Unexpected request error.',
REQUEST_FAILED: 'Request failed. Please try again.',
};
const resolver = createErrorResolver({
catalog: CATALOG,
fallbackCode: 'REQUEST_FAILED',
defaultContext: 'default',
contextOverrides: {
session: {
AUTH_UNAUTHORIZED: 'Session expired. Please sign in again.',
},
},
inferCodeFromStatus: (status?: number | null) => {
switch (status) {
case 401:
return 'AUTH_UNAUTHORIZED';
case 403:
return 'FORBIDDEN';
case 404:
return 'USER_NOT_FOUND';
default:
if (status != null && status >= 500) {
return 'INTERNAL_ERROR';
}
return undefined;
}
},
inferCodeFromLegacyMessage: (message?: string | null) => {
if (message?.toLowerCase() === 'unauthorized') {
return 'AUTH_UNAUTHORIZED';
}
return undefined;
},
});
describe('createErrorResolver', () => {
it('recognizes known error codes', () => {
expect(resolver.isKnownErrorCode('AUTH_UNAUTHORIZED')).toBe(true);
expect(resolver.isKnownErrorCode('NOPE')).toBe(false);
});
it('returns context override for known code', () => {
expect(
resolver.resolveErrorMessage({
code: 'AUTH_UNAUTHORIZED',
context: 'session',
}),
).toBe('Session expired. Please sign in again.');
});
it('falls back from unknown code to legacy message inference', () => {
expect(
resolver.resolveErrorMessage({
code: 'UNKNOWN_CODE',
fallbackMessage: 'unauthorized',
}),
).toBe('Unauthorized access. Please sign in again.');
});
it('falls back to status mapping when code is missing', () => {
expect(resolver.resolveErrorMessage({ status: 404 })).toBe('User not found.');
});
it('falls back to status mapping when legacy inference returns an unmapped code', () => {
const resolverWithUnmappedLegacyCode = createErrorResolver({
catalog: CATALOG,
inferCodeFromStatus: resolver.inferErrorCodeFromStatus,
inferCodeFromLegacyMessage: () => 'LEGACY_ONLY_CODE',
});
expect(
resolverWithUnmappedLegacyCode.resolveErrorMessage({
status: 403,
fallbackMessage: 'legacy message',
}),
).toBe('You do not have permission to perform this action.');
});
it('uses fallbackCode when no code/status resolve and fallback message is missing', () => {
expect(resolver.resolveErrorMessage({ status: 418 })).toBe('Request failed. Please try again.');
});
it('uses fallback message when no mapping exists and fallback code is unavailable', () => {
const noFallbackCodeResolver = createErrorResolver({
catalog: CATALOG,
inferCodeFromStatus: () => undefined,
});
expect(
noFallbackCodeResolver.resolveErrorMessage({
code: 'UNKNOWN',
fallbackMessage: 'raw backend message',
}),
).toBe('raw backend message');
});
it('returns default request failure message when no signal is available', () => {
const emptyResolver = createErrorResolver({
catalog: {},
});
expect(emptyResolver.resolveErrorMessage({})).toBe('Request failed. Please try again.');
});
it('resolveOptionalErrorMessage returns undefined for empty inputs', () => {
expect(resolver.resolveOptionalErrorMessage(undefined)).toBeUndefined();
expect(resolver.resolveOptionalErrorMessage(null)).toBeUndefined();
});
it('resolveOptionalErrorMessage resolves known codes', () => {
expect(resolver.resolveOptionalErrorMessage('FORBIDDEN')).toBe(
'You do not have permission to perform this action.',
);
});
it('toErrorMessage prefers rawMessage over message and handles unknown values', () => {
expect(
resolver.toErrorMessage({
status: 403,
rawMessage: 'unauthorized',
message: 'ignored message',
}),
).toBe('Unauthorized access. Please sign in again.');
expect(resolver.toErrorMessage('boom')).toBe('Request failed. Please try again.');
expect(resolver.toErrorMessage(null)).toBe('Request failed. Please try again.');
});
it('exposes inferErrorCodeFromStatus', () => {
expect(resolver.inferErrorCodeFromStatus(401)).toBe('AUTH_UNAUTHORIZED');
expect(resolver.inferErrorCodeFromStatus(500)).toBe('INTERNAL_ERROR');
expect(resolver.inferErrorCodeFromStatus(418)).toBeUndefined();
expect(resolver.inferErrorCodeFromStatus(null)).toBeUndefined();
});
});

View File

@@ -0,0 +1,36 @@
import { act } from 'react';
import { createRoot } from 'react-dom/client';
export function renderHook<T>(useHook: () => T) {
let currentValue: T;
function TestComponent() {
currentValue = useHook();
return null;
}
const container = document.createElement('div');
const root = createRoot(container);
act(() => {
root.render(<TestComponent />);
});
return {
result: {
get current() {
return currentValue;
},
},
rerender() {
act(() => {
root.render(<TestComponent />);
});
},
unmount() {
act(() => {
root.unmount();
});
},
};
}

View File

@@ -0,0 +1,64 @@
import { act } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useCooldownTimer } from '../../src/hooks/useCooldownTimer';
import { renderHook } from '../helpers/renderHook';
describe('useCooldownTimer', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('decrements cooldown every second while enabled', () => {
const { result } = renderHook(() => useCooldownTimer(2, true));
expect(result.current.cooldown).toBe(2);
act(() => {
vi.advanceTimersByTime(1000);
});
expect(result.current.cooldown).toBe(1);
act(() => {
vi.advanceTimersByTime(1000);
});
expect(result.current.cooldown).toBe(0);
});
it('does not decrement when disabled', () => {
const { result } = renderHook(() => useCooldownTimer(2, false));
act(() => {
vi.advanceTimersByTime(3000);
});
expect(result.current.cooldown).toBe(2);
});
it('startCooldown floors values and clamps negatives', () => {
const { result } = renderHook(() => useCooldownTimer(0, true));
act(() => {
result.current.startCooldown(2.8);
});
expect(result.current.cooldown).toBe(2);
act(() => {
result.current.startCooldown(-4);
});
expect(result.current.cooldown).toBe(0);
});
it('stays at zero when already expired', () => {
const { result } = renderHook(() => useCooldownTimer(0, true));
act(() => {
vi.advanceTimersByTime(2000);
});
expect(result.current.cooldown).toBe(0);
});
});

View File

@@ -0,0 +1,81 @@
import { act } from 'react';
import { describe, expect, it } from 'vitest';
import { useEditableForm } from '../../src/hooks/useEditableForm';
import { renderHook } from '../helpers/renderHook';
type FormValues = {
username: string;
email: string;
};
const INITIAL_VALUES: FormValues = {
username: '',
email: '',
};
function validate(values: FormValues) {
return {
username: values.username.trim().length < 3 ? 'Username too short' : undefined,
email: values.email.includes('@') ? undefined : 'Invalid email',
};
}
describe('useEditableForm', () => {
it('supports load/start/discard/commit edit lifecycle', () => {
const { result } = renderHook(() =>
useEditableForm({
initialValues: INITIAL_VALUES,
validate,
}),
);
expect(result.current.isEditing).toBe(false);
act(() => {
result.current.loadFromSource({ username: 'alice', email: 'alice@example.com' });
});
expect(result.current.values).toEqual({ username: 'alice', email: 'alice@example.com' });
expect(result.current.errors).toEqual({});
act(() => {
result.current.startEditing({ username: 'al', email: 'aliceexample.com' });
});
expect(result.current.isEditing).toBe(true);
act(() => {
result.current.setFieldValue('username', 'a');
});
expect(result.current.errors.username).toBe('Username too short');
act(() => {
result.current.discardChanges({ username: 'alice', email: 'alice@example.com' });
});
expect(result.current.isEditing).toBe(false);
expect(result.current.values).toEqual({ username: 'alice', email: 'alice@example.com' });
act(() => {
result.current.startEditing({ username: 'alice', email: 'alice@example.com' });
result.current.setFieldValue('username', 'alice_2');
result.current.commitSaved({ username: 'alice_2', email: 'alice@example.com' });
});
expect(result.current.isEditing).toBe(false);
expect(result.current.values.username).toBe('alice_2');
});
it('exposes direct editing toggles and field error injection', () => {
const { result } = renderHook(() =>
useEditableForm({
initialValues: INITIAL_VALUES,
validate,
}),
);
act(() => {
result.current.setIsEditing(true);
result.current.setFieldError('username', 'Username already taken');
});
expect(result.current.isEditing).toBe(true);
expect(result.current.errors.username).toBe('Username already taken');
});
});

View File

@@ -0,0 +1,170 @@
import { act } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { usePaginatedResource } from '../../src/hooks/usePaginatedResource';
import { renderHook } from '../helpers/renderHook';
type Item = {
id: string;
};
async function flushDebounce(delay = 250) {
await act(async () => {
vi.advanceTimersByTime(delay);
await Promise.resolve();
});
}
describe('usePaginatedResource', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('loads first page after debounce and stores response fields', async () => {
const loadMock = vi.fn(async () => ({
items: [{ id: '1' }] as Item[],
page: 1,
pageSize: 10,
total: 25,
totalPages: 3,
}));
const { result } = renderHook(() =>
usePaginatedResource<Item>({
load: loadMock,
sort: '-createdAt',
}),
);
await flushDebounce();
expect(loadMock).toHaveBeenCalledWith({
q: '',
page: 1,
pageSize: 10,
sort: '-createdAt',
});
expect(result.current.items).toEqual([{ id: '1' }]);
expect(result.current.total).toBe(25);
expect(result.current.totalPages).toBe(3);
expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBeNull();
});
it('resets page to 1 when query or page size changes', async () => {
const loadMock = vi.fn(
async ({ q, page, pageSize }: { q: string; page: number; pageSize: number }) => ({
items: [{ id: `${q}:${page}:${pageSize}` }] as Item[],
page,
pageSize,
total: 1,
totalPages: 1,
}),
);
const { result } = renderHook(() =>
usePaginatedResource<Item>({
load: loadMock,
}),
);
await flushDebounce();
act(() => {
result.current.setPage(2);
});
await flushDebounce();
expect(loadMock).toHaveBeenLastCalledWith({
q: '',
page: 2,
pageSize: 10,
sort: undefined,
});
act(() => {
result.current.setQuery('search');
});
await flushDebounce();
expect(loadMock).toHaveBeenLastCalledWith({
q: 'search',
page: 1,
pageSize: 10,
sort: undefined,
});
act(() => {
result.current.setPage(3);
});
await flushDebounce();
act(() => {
result.current.setPageSize(20);
});
await flushDebounce();
expect(loadMock).toHaveBeenLastCalledWith({
q: 'search',
page: 1,
pageSize: 20,
sort: undefined,
});
});
it('cancels stale debounce timers when inputs change quickly', async () => {
const loadMock = vi.fn(async () => ({
items: [] as Item[],
page: 1,
pageSize: 10,
total: 0,
totalPages: 0,
}));
const { result } = renderHook(() =>
usePaginatedResource<Item>({
load: loadMock,
debounceMs: 100,
}),
);
act(() => {
result.current.setQuery('latest');
});
await flushDebounce(100);
expect(loadMock).toHaveBeenCalledTimes(1);
expect(loadMock).toHaveBeenCalledWith({
q: 'latest',
page: 1,
pageSize: 10,
sort: undefined,
});
});
it('maps thrown errors into string error state', async () => {
const loadMock = vi
.fn()
.mockRejectedValueOnce(new Error('Load failed'))
.mockRejectedValueOnce('unknown');
const { result } = renderHook(() =>
usePaginatedResource<Item>({
load: loadMock,
}),
);
await flushDebounce();
expect(result.current.error).toBe('Load failed');
expect(result.current.isLoading).toBe(false);
act(() => {
result.current.setPage(2);
});
await flushDebounce();
expect(result.current.error).toBe('Request failed. Please try again.');
expect(result.current.isLoading).toBe(false);
});
});

View File

@@ -0,0 +1,97 @@
import { act } from 'react';
import { describe, expect, it } from 'vitest';
import { formatSortParam, useSorting } from '../../src/hooks/useSorting';
import { renderHook } from '../helpers/renderHook';
describe('useSorting', () => {
it('starts from default sort and cycles asc/desc/default', () => {
const { result } = renderHook(() => useSorting({ field: 'createdAt', direction: 'asc' }));
expect(result.current.activeSort).toEqual({ field: 'createdAt', direction: 'asc' });
expect(result.current.sortParam).toBe('createdAt');
act(() => {
result.current.toggleSort('name');
});
expect(result.current.activeSort).toEqual({ field: 'name', direction: 'asc' });
expect(result.current.sortParam).toBe('name');
act(() => {
result.current.toggleSort('name');
});
expect(result.current.activeSort).toEqual({ field: 'name', direction: 'desc' });
expect(result.current.sortParam).toBe('-name');
act(() => {
result.current.toggleSort('name');
});
expect(result.current.activeSort).toEqual({ field: 'createdAt', direction: 'asc' });
expect(result.current.sortParam).toBe('createdAt');
});
it('cycles sort state without a baseline default', () => {
const { result } = renderHook(() => useSorting(null));
expect(result.current.activeSort).toBeNull();
expect(result.current.sortParam).toBeUndefined();
act(() => {
result.current.toggleSort('updatedAt');
});
expect(result.current.sortParam).toBe('updatedAt');
act(() => {
result.current.toggleSort('updatedAt');
});
expect(result.current.sortParam).toBe('-updatedAt');
act(() => {
result.current.toggleSort('updatedAt');
});
expect(result.current.sortParam).toBeUndefined();
});
it('supports manual setSort and resetSort', () => {
const { result } = renderHook(() => useSorting({ field: 'createdAt', direction: 'desc' }));
expect(result.current.sortParam).toBe('-createdAt');
act(() => {
result.current.setSort({ field: 'title', direction: 'asc' });
});
expect(result.current.sortParam).toBe('title');
act(() => {
result.current.resetSort();
});
expect(result.current.sortParam).toBe('-createdAt');
});
it('toggles baseline field directly between baseline and opposite direction', () => {
const { result } = renderHook(() => useSorting({ field: 'createdAt', direction: 'desc' }));
expect(result.current.sortParam).toBe('-createdAt');
act(() => {
result.current.toggleSort('createdAt');
});
expect(result.current.sortParam).toBe('createdAt');
act(() => {
result.current.toggleSort('createdAt');
});
expect(result.current.sortParam).toBe('-createdAt');
act(() => {
result.current.toggleSort('createdAt');
});
expect(result.current.sortParam).toBe('createdAt');
});
it('formats sort params safely', () => {
expect(formatSortParam(null)).toBeUndefined();
expect(formatSortParam(undefined)).toBeUndefined();
expect(formatSortParam({ field: 'updatedAt', direction: 'desc' })).toBe('-updatedAt');
expect(formatSortParam({ field: 'updatedAt', direction: 'asc' })).toBe('updatedAt');
});
});

View File

@@ -0,0 +1,44 @@
import { act } from 'react';
import { describe, expect, it } from 'vitest';
import { useSubmitState } from '../../src/hooks/useSubmitState';
import { renderHook } from '../helpers/renderHook';
describe('useSubmitState', () => {
it('tracks submit lifecycle and feedback state', () => {
const { result } = renderHook(() => useSubmitState<string | null>(null));
expect(result.current.isSubmitting).toBe(false);
expect(result.current.submitError).toBeNull();
expect(result.current.status).toBeNull();
act(() => {
result.current.startSubmitting();
result.current.setSubmitError('Oops');
result.current.setStatus('Done');
});
expect(result.current.isSubmitting).toBe(true);
expect(result.current.submitError).toBe('Oops');
expect(result.current.status).toBe('Done');
act(() => {
result.current.finishSubmitting();
result.current.clearFeedback();
});
expect(result.current.isSubmitting).toBe(false);
expect(result.current.submitError).toBeNull();
expect(result.current.status).toBeNull();
});
it('restores the typed initial status in clearFeedback', () => {
const { result } = renderHook(() => useSubmitState<'idle' | 'done'>('idle'));
act(() => {
result.current.setStatus('done');
result.current.clearFeedback();
});
expect(result.current.status).toBe('idle');
});
});

View File

@@ -0,0 +1,158 @@
import { act } from 'react';
import { describe, expect, it } from 'vitest';
import { useValidatedFields } from '../../src/hooks/useValidatedFields';
import { renderHook } from '../helpers/renderHook';
type FormValues = {
password: string;
confirmPassword: string;
};
function validate(values: FormValues) {
return {
password: values.password.length < 3 ? 'Password too short' : undefined,
confirmPassword:
values.confirmPassword !== values.password ? 'Passwords do not match' : undefined,
};
}
describe('useValidatedFields', () => {
it('initializes values and keeps errors hidden until fields are touched', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: '', confirmPassword: '' },
validate,
}),
);
expect(result.current.values).toEqual({ password: '', confirmPassword: '' });
expect(result.current.errors).toEqual({});
expect(result.current.isValid).toBe(false);
});
it('setFieldValue touches and validates by default', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: '', confirmPassword: '' },
validate,
}),
);
act(() => {
result.current.setFieldValue('password', 'ab');
});
expect(result.current.values.password).toBe('ab');
expect(result.current.errors.password).toBe('Password too short');
});
it('setFieldValue can skip touch and validation', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: '', confirmPassword: '' },
validate,
}),
);
act(() => {
result.current.setFieldValue('password', 'ab', { touch: false, validate: false });
});
expect(result.current.values.password).toBe('ab');
expect(result.current.errors).toEqual({});
});
it('validateAll can avoid touching fields when requested', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: 'abcd', confirmPassword: 'abce' },
validate,
}),
);
let validationErrors: ReturnType<typeof validate> | undefined;
act(() => {
validationErrors = result.current.validateAll({ touchAll: false });
});
expect(validationErrors).toEqual({
password: undefined,
confirmPassword: 'Passwords do not match',
});
expect(result.current.errors).toEqual({});
});
it('validateAll touches all fields by default', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: '', confirmPassword: '' },
validate,
}),
);
act(() => {
result.current.validateAll();
});
expect(result.current.errors.password).toBe('Password too short');
expect(result.current.errors.confirmPassword).toBeUndefined();
});
it('supports setFieldError, setErrors and clearErrors', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: 'abcd', confirmPassword: 'abcd' },
validate,
}),
);
act(() => {
result.current.setFieldError('password', 'Server-side password issue');
});
expect(result.current.errors.password).toBe('Server-side password issue');
act(() => {
result.current.setErrors({
password: undefined,
confirmPassword: 'Still invalid',
});
});
expect(result.current.errors.confirmPassword).toBe('Still invalid');
act(() => {
result.current.clearErrors();
});
expect(result.current.errors).toEqual({});
});
it('setValues with clearErrors resets touched state and revalidates', () => {
const { result } = renderHook(() =>
useValidatedFields({
initialValues: { password: '', confirmPassword: '' },
validate,
}),
);
act(() => {
result.current.setFieldValue('password', 'ab');
});
expect(result.current.errors.password).toBe('Password too short');
act(() => {
result.current.setValues(
{
password: 'abcd',
confirmPassword: 'abcd',
},
{ clearErrors: true },
);
});
expect(result.current.values).toEqual({
password: 'abcd',
confirmPassword: 'abcd',
});
expect(result.current.errors).toEqual({});
expect(result.current.isValid).toBe(true);
});
});

View File

@@ -0,0 +1,239 @@
import { fireEvent } from '@testing-library/react';
import { act } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { isDesktopViewport, useSidePanelMachine } from '../../src/panels/useSidePanelMachine';
import { renderHook } from '../helpers/renderHook';
function setViewportWidth(width: number) {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
writable: true,
value: width,
});
}
function resetMatchMedia() {
Object.defineProperty(window, 'matchMedia', {
configurable: true,
writable: true,
value: undefined,
});
}
describe('isDesktopViewport', () => {
it('uses matchMedia when available', () => {
const matchMedia = vi.fn(() => ({ matches: false }));
Object.defineProperty(window, 'matchMedia', {
configurable: true,
writable: true,
value: matchMedia,
});
expect(isDesktopViewport(1200)).toBe(false);
expect(matchMedia).toHaveBeenCalledWith('(min-width: 1200px)');
});
it('falls back to window.innerWidth when matchMedia is unavailable', () => {
resetMatchMedia();
setViewportWidth(1024);
expect(isDesktopViewport(1024)).toBe(true);
setViewportWidth(800);
expect(isDesktopViewport(1024)).toBe(false);
});
});
describe('useSidePanelMachine', () => {
it('reads stored width, clamps resize values, and persists final width', async () => {
resetMatchMedia();
setViewportWidth(1200);
localStorage.setItem('panel-width', '999');
const preventDefault = vi.fn();
const { result } = renderHook(() =>
useSidePanelMachine({
storageKey: 'panel-width',
defaultWidth: 300,
minWidth: 200,
maxWidth: 400,
resizeAxis: 'from-left',
resizingBodyClass: 'resizing',
isOpen: false,
canResize: true,
shouldPersistWidth: true,
closeOnPathname: undefined,
}),
);
expect(result.current.width).toBe(400);
expect(result.current.isDesktop).toBe(true);
expect(localStorage.getItem('panel-width')).toBe('400');
act(() => {
result.current.startResize({
clientX: 400,
preventDefault,
} as never);
});
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(document.body.classList.contains('resizing')).toBe(true);
act(() => {
fireEvent.pointerMove(window, { clientX: 100 });
fireEvent.pointerUp(window);
});
await act(async () => {
await Promise.resolve();
});
expect(result.current.width).toBe(200);
expect(localStorage.getItem('panel-width')).toBe('200');
expect(document.body.classList.contains('resizing')).toBe(false);
});
it('falls back to default width for empty or invalid stored values', () => {
resetMatchMedia();
setViewportWidth(1200);
localStorage.setItem('panel-width', '');
const invalid = renderHook(() =>
useSidePanelMachine({
storageKey: 'panel-width',
defaultWidth: 310,
minWidth: 200,
maxWidth: 400,
resizeAxis: 'from-left',
resizingBodyClass: 'resizing',
isOpen: false,
canResize: true,
shouldPersistWidth: false,
closeOnPathname: undefined,
}),
);
expect(invalid.result.current.width).toBe(310);
invalid.unmount();
localStorage.setItem('panel-width', 'NaN-value');
const nonFinite = renderHook(() =>
useSidePanelMachine({
storageKey: 'panel-width',
defaultWidth: 315,
minWidth: 200,
maxWidth: 400,
resizeAxis: 'from-left',
resizingBodyClass: 'resizing',
isOpen: false,
canResize: true,
shouldPersistWidth: false,
closeOnPathname: undefined,
}),
);
expect(nonFinite.result.current.width).toBe(315);
});
it('does not start resizing when viewport is mobile or resizing is disabled', () => {
resetMatchMedia();
setViewportWidth(700);
const preventDefault = vi.fn();
const { result } = renderHook(() =>
useSidePanelMachine({
storageKey: 'panel-width',
defaultWidth: 300,
minWidth: 200,
maxWidth: 400,
resizeAxis: 'from-left',
resizingBodyClass: 'resizing',
isOpen: false,
canResize: false,
shouldPersistWidth: false,
closeOnPathname: undefined,
}),
);
act(() => {
result.current.startResize({
clientX: 300,
preventDefault,
} as never);
});
expect(preventDefault).not.toHaveBeenCalled();
expect(document.body.classList.contains('resizing')).toBe(false);
expect(localStorage.getItem('panel-width')).toBeNull();
});
it('ignores pointer events when not currently resizing', () => {
resetMatchMedia();
setViewportWidth(1200);
renderHook(() =>
useSidePanelMachine({
storageKey: 'panel-width',
defaultWidth: 300,
minWidth: 200,
maxWidth: 400,
resizeAxis: 'from-left',
resizingBodyClass: 'resizing',
isOpen: false,
canResize: true,
shouldPersistWidth: true,
closeOnPathname: undefined,
}),
);
act(() => {
fireEvent.pointerMove(window, { clientX: 1000 });
fireEvent.pointerUp(window);
});
expect(document.body.classList.contains('resizing')).toBe(false);
});
it('handles closeOnPathname, escape key callbacks and body overflow lock', () => {
resetMatchMedia();
setViewportWidth(700);
const onCloseOnPathname = vi.fn();
const onEscape = vi.fn();
let options = {
storageKey: 'panel-width',
defaultWidth: 300,
minWidth: 200,
maxWidth: 400,
resizeAxis: 'from-right' as const,
resizingBodyClass: 'resizing',
isOpen: true,
canResize: true,
shouldPersistWidth: false,
closeOnPathname: '/users',
onCloseOnPathname,
onEscape,
};
const { rerender } = renderHook(() => useSidePanelMachine(options));
expect(onCloseOnPathname).toHaveBeenCalledTimes(1);
expect(document.body.style.overflow).toBe('hidden');
act(() => {
fireEvent.keyDown(window, { key: 'Escape' });
});
expect(onEscape).toHaveBeenCalledTimes(1);
options = {
...options,
closeOnPathname: '/posts',
};
rerender();
expect(onCloseOnPathname).toHaveBeenCalledTimes(2);
options = {
...options,
isOpen: false,
};
rerender();
expect(document.body.style.overflow).toBe('');
});
});

15
tests/setup.ts Normal file
View File

@@ -0,0 +1,15 @@
// Required by React to silence act(...) warnings in jsdom tests.
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach, vi } from 'vitest';
afterEach(() => {
cleanup();
localStorage.clear();
document.body.className = '';
document.body.style.overflow = '';
vi.restoreAllMocks();
vi.useRealTimers();
});

View File

@@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest';
import { capitalize, formatDate, splitAndCapitalize } from '../../src/utils/formatting';
describe('formatDate', () => {
it('formats date in it-IT locale and includes seconds when requested', () => {
const withoutSeconds = formatDate('2026-01-01T12:34:56.000Z');
const withSeconds = formatDate('2026-01-01T12:34:56.000Z', true);
expect(withoutSeconds).toContain('2026');
expect(withSeconds).toContain('56');
});
});
describe('capitalize', () => {
it('capitalizes every space-delimited word', () => {
expect(capitalize('hello WORLD')).toBe('Hello World');
expect(capitalize('mUlTi SPACES')).toBe('Multi Spaces');
});
});
describe('splitAndCapitalize', () => {
it('splits underscore and hyphen mode', () => {
expect(splitAndCapitalize('hello_world-test', 'underscore')).toBe('Hello World Test');
});
it('splits camel mode with acronym and number boundaries', () => {
expect(splitAndCapitalize('helloWorldXML2Http', 'camel')).toBe('Hello World Xml 2 Http');
});
it('auto mode prefers underscore splitting when underscore-like chars exist', () => {
expect(splitAndCapitalize('user_name')).toBe('User Name');
expect(splitAndCapitalize('kebab-case')).toBe('Kebab Case');
});
it('auto mode falls back to camel splitting when underscore-like chars are absent', () => {
expect(splitAndCapitalize('helloWorldTest')).toBe('Hello World Test');
});
it('returns empty string for empty or missing input', () => {
expect(splitAndCapitalize('')).toBe('');
expect(splitAndCapitalize(undefined)).toBe('');
});
});

View File

@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { shouldShowVerifiedEmailBadge } from '../../src/utils/verifiedEmail';
describe('shouldShowVerifiedEmailBadge', () => {
it('returns false when email has not been verified', () => {
expect(
shouldShowVerifiedEmailBadge({
verifiedAt: null,
persistedEmail: 'a@example.com',
currentEmail: 'a@example.com',
isEditing: false,
}),
).toBe(false);
});
it('returns true when verified and not editing', () => {
expect(
shouldShowVerifiedEmailBadge({
verifiedAt: '2025-01-01T10:00:00Z',
persistedEmail: 'a@example.com',
currentEmail: 'other@example.com',
isEditing: false,
}),
).toBe(true);
});
it('while editing, returns true only when trimmed current email matches persisted email', () => {
expect(
shouldShowVerifiedEmailBadge({
verifiedAt: '2025-01-01T10:00:00Z',
persistedEmail: 'a@example.com',
currentEmail: ' a@example.com ',
isEditing: true,
}),
).toBe(true);
expect(
shouldShowVerifiedEmailBadge({
verifiedAt: '2025-01-01T10:00:00Z',
persistedEmail: 'a@example.com',
currentEmail: 'other@example.com',
isEditing: true,
}),
).toBe(false);
});
});

View File

@@ -1,12 +1,12 @@
{ {
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"compilerOptions": { "compilerOptions": {
"noEmit": false, "noEmit": false,
"declaration": true, "declaration": true,
"emitDeclarationOnly": true, "emitDeclarationOnly": true,
"rootDir": "src", "rootDir": "src",
"outDir": "dist", "outDir": "dist",
"declarationMap": true "declarationMap": true
}, },
"include": ["src"] "include": ["src"]
} }

View File

@@ -1,17 +1,17 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2022", "target": "ES2022",
"module": "ESNext", "module": "ESNext",
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"], "lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx", "jsx": "react-jsx",
"strict": true, "strict": true,
"skipLibCheck": true, "skipLibCheck": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"allowImportingTsExtensions": false, "allowImportingTsExtensions": false,
"noEmit": true, "noEmit": true,
"types": ["react"] "types": ["react"]
}, },
"include": ["src"] "include": ["src"]
} }

View File

@@ -1,18 +1,32 @@
import { defineConfig } from 'vite'; import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
build: { build: {
lib: { lib: {
entry: resolve(__dirname, 'src/index.ts'), entry: resolve(__dirname, 'src/index.ts'),
name: 'PanicCore', name: 'PanicCore',
formats: ['es'], formats: ['es'],
fileName: () => 'index.js' fileName: () => 'index.js',
},
rollupOptions: {
external: ['react'],
},
},
test: {
environment: 'jsdom',
setupFiles: ['./tests/setup.ts'],
coverage: {
provider: 'v8',
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/index.ts'],
thresholds: {
lines: 80,
functions: 75,
branches: 70,
},
},
}, },
rollupOptions: {
external: ['react']
}
}
}); });

1337
yarn.lock

File diff suppressed because it is too large Load Diff