Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f831c35d5 | ||
|
|
2c3cc3449b | ||
|
|
820fd56fbc | ||
|
|
41f7dabbf0 | ||
|
|
5041ebeeff | ||
|
|
fa8c84bb38 | ||
|
|
c3115bc002 | ||
|
|
91e48f2cbb | ||
|
|
4217ea11c8 | ||
|
|
f41e34486a | ||
|
|
29812e8175 | ||
|
|
0444ad5a5d | ||
|
|
89eb15d714 | ||
|
|
08ed7c485e | ||
|
|
cf598c0971 | ||
|
|
e8833320d4 | ||
|
|
eb759a232d | ||
|
|
4e167f9a85 | ||
|
|
ee2fb62036 | ||
|
|
5eb9ee5ced | ||
|
|
2679cf61ac | ||
|
|
49baf4db77 | ||
|
|
c1db12be40 | ||
|
|
1eab863fca | ||
|
|
ed6738381a | ||
|
|
b423082b1f | ||
|
|
ab34a310c4 | ||
|
|
ee916d02b9 | ||
|
|
ee38fa256d | ||
|
|
1d7b10ec4d | ||
|
|
e4454f913f | ||
|
|
7ea127c4a9 | ||
|
|
7fffb163d1 | ||
|
|
bd3a6c6f18 | ||
|
|
111eb4686b | ||
|
|
da0432a734 | ||
|
|
d016d20850 | ||
|
|
332da7de94 | ||
|
|
6c92a5ca91 | ||
|
|
ed464bf719 | ||
|
|
b423e4141f | ||
|
|
a1fc1c1dfc | ||
|
|
cd26ea52b0 | ||
|
|
a305a95970 | ||
|
|
2e24cf06ed | ||
|
|
75e082d64b | ||
|
|
af2b37fae9 | ||
|
|
77eb28c1c3 | ||
|
|
f450b88a7b | ||
|
|
eb050bfa80 | ||
|
|
92cdb86f59 | ||
|
|
ab8757dba4 | ||
|
|
f016eeb2f2 | ||
|
|
3f95dba104 | ||
|
|
83ae707a6d | ||
|
|
c9380598cf | ||
|
|
7f95a9e274 | ||
|
|
bf2a83ad44 | ||
|
|
0c77393000 | ||
|
|
5f6cc58e36 | ||
|
|
2da0a9f113 | ||
|
|
caa0b8b9ea | ||
|
|
a653b3cb41 | ||
|
|
8d7f37c8a9 | ||
|
|
e52d1d9c23 | ||
|
|
d1a08a0d5c | ||
|
|
14b76a0a37 | ||
|
|
91de896ea7 | ||
|
|
4ecdb940e3 | ||
|
|
8144b9b2fe | ||
|
|
8d886ee3dc | ||
|
|
91f1e21c9e | ||
|
|
a0ed8a9c4c | ||
|
|
0ae08f4158 | ||
|
|
793e6fe85b | ||
|
|
dc5fac2f0d | ||
|
|
64048dd5d3 | ||
|
|
2c22b8e463 | ||
|
|
09e84aaf24 | ||
|
|
06390c4724 | ||
|
|
bbf0d5db3e | ||
|
|
2008533e91 | ||
|
|
dbb8e37d88 | ||
|
|
c6dd3dd9d5 | ||
|
|
570f5ebb14 | ||
|
|
bf1916e23a | ||
|
|
1e906a0f01 | ||
|
|
8fd9c05933 | ||
|
|
362a38539d | ||
|
|
9b9c7820ae | ||
|
|
3f10727fe8 | ||
|
|
6a20420835 | ||
|
|
80317e5453 | ||
|
|
afd9c4aaef | ||
|
|
45e92eb44c | ||
|
|
56c584b68b | ||
|
|
4c0328ac4d | ||
|
|
eda07943a2 | ||
|
|
d9c3dfe3c2 | ||
|
|
037cfaca08 | ||
|
|
279180d7b6 | ||
|
|
4ba705d6c4 | ||
|
|
9db1a189bd | ||
|
|
3a1c89d1dd | ||
|
|
4f96f32daf | ||
|
|
b992c879d7 | ||
|
|
e007baf298 | ||
|
|
b65445a042 | ||
|
|
5a15843295 | ||
|
|
97d87d3ff3 | ||
|
|
261df08b1e | ||
|
|
e5f3e339f6 | ||
|
|
c4972c2fbe | ||
|
|
70c38933f9 | ||
|
|
a65e55caae | ||
|
|
05beb6cabf | ||
|
|
0234c77538 | ||
|
|
4ba3d1962d | ||
|
|
494c77e0af | ||
|
|
410366adad | ||
|
|
32969dc861 | ||
|
|
255ce7c193 | ||
|
|
d1ebc96fde | ||
|
|
4538151871 | ||
|
|
4763c89f1a | ||
|
|
97b3110bb1 | ||
|
|
1027ee2a57 | ||
|
|
f8d07e87a7 | ||
|
|
dce2b04ecc | ||
|
|
d8b1319240 | ||
|
|
6bb6deeb08 | ||
|
|
d1307c2128 | ||
|
|
02cc7a7d74 | ||
|
|
77ca171214 | ||
|
|
67dee07835 | ||
|
|
9871b83e6f | ||
|
|
0b48a7d816 | ||
|
|
8fedf9a1ea | ||
|
|
b6d0ebef0a | ||
|
|
3da6e4900b | ||
|
|
0961c67e80 | ||
|
|
d843df9e26 | ||
|
|
8b3e8a5829 | ||
|
|
0af136088a | ||
|
|
df9a05c1d4 | ||
|
|
e198907546 | ||
|
|
bc5c9865da | ||
|
|
a958ef723d | ||
|
|
bcd5597fd1 | ||
|
|
502d1787d7 | ||
|
|
63e696b2b1 | ||
|
|
354c4c6851 | ||
|
|
eda5565e49 | ||
|
|
b4d01e1e1b | ||
|
|
642a09e855 | ||
|
|
44d3fb23aa | ||
|
|
787bcd1773 | ||
|
|
17897f2090 | ||
|
|
8faa8af456 | ||
|
|
fdc7f84907 | ||
|
|
8e7119e91f | ||
|
|
9e8eee3723 | ||
|
|
5affb6197f | ||
|
|
fcd40346ee | ||
|
|
ffc2247985 | ||
|
|
fc5f27a915 | ||
|
|
09a5064364 | ||
|
|
e87973788c | ||
|
|
3721d60b40 | ||
|
|
2c47eb7416 | ||
|
|
340ed324e5 | ||
|
|
b3bdf17597 | ||
|
|
f470bfae50 | ||
|
|
72407ba2e1 | ||
|
|
dfcd6b2171 | ||
|
|
1dd3311c8c | ||
|
|
e87e1aa557 | ||
|
|
b5d050eab8 | ||
|
|
d6a11a5e07 | ||
|
|
fd2db315cc | ||
|
|
a571501992 | ||
|
|
55a570a969 | ||
|
|
6fce3dd8db | ||
|
|
ad6d4fe07c | ||
|
|
d5632c1c4c | ||
|
|
0e73d48a30 | ||
|
|
27f49a9a89 | ||
|
|
647497af1a | ||
|
|
2899fd60c8 | ||
|
|
283d244c55 | ||
|
|
6959431bf9 | ||
|
|
8fc2df747f | ||
|
|
bd77b91a3c | ||
|
|
11f96bf047 | ||
|
|
1480cef8e2 | ||
|
|
a8a87d8d03 | ||
|
|
333cb423d0 | ||
|
|
fa9a710417 | ||
|
|
b1fe277063 | ||
|
|
30d1ceaf73 | ||
|
|
af9c3280f6 | ||
|
|
82748e4ac4 | ||
|
|
69c40419ea | ||
|
|
2aaa4e7543 | ||
|
|
b63be64788 | ||
|
|
0a18749dce | ||
|
|
dbc5f68d5e | ||
|
|
b1891277e9 | ||
|
|
73f8741013 | ||
|
|
6bcd1515c4 | ||
|
|
1f17af2a0d | ||
|
|
7089c653ff | ||
|
|
9d430b9e5a | ||
|
|
d03c9639e9 | ||
|
|
e8c82f411e | ||
|
|
98012bac24 | ||
|
|
9e603f8bb6 | ||
|
|
fc93ca4d0b | ||
|
|
d303d4050d | ||
|
|
e501e2b4a4 | ||
|
|
6e820c9104 | ||
|
|
9acd7afa1d | ||
|
|
c4da2a7b7f | ||
|
|
4925860410 | ||
|
|
43c7a539c7 | ||
|
|
5d53637e85 | ||
|
|
c96f864747 | ||
|
|
eda1b9f875 | ||
|
|
e98ce9c191 | ||
|
|
dae34004ff | ||
|
|
0ce71f7f1a | ||
|
|
036c8f3474 | ||
|
|
2218bf561a | ||
|
|
181fe28f55 | ||
|
|
6fe493a5a3 | ||
|
|
24530d30c1 | ||
|
|
2228181fff | ||
|
|
0301676c76 | ||
|
|
cb614bd092 | ||
|
|
c846a162be | ||
|
|
3eec5d2249 | ||
|
|
7a6b41245a | ||
|
|
8fa20a00f6 | ||
|
|
38a4c3961b | ||
|
|
161764a233 | ||
|
|
ce2d168fb7 | ||
|
|
8bca2025db | ||
|
|
cfc5e4e2f4 | ||
|
|
8489aabbbf | ||
|
|
6276131d9d | ||
|
|
6a06f0ace2 | ||
|
|
9df330b43f | ||
|
|
5cbcfc59ec | ||
|
|
7150a5b8f4 | ||
|
|
722c06597f | ||
|
|
29ae0bfa48 | ||
|
|
89963cb2b9 | ||
|
|
5c0c95b60d | ||
|
|
486e91610a | ||
|
|
1abfbe7586 | ||
|
|
498dfd8502 | ||
|
|
6334ab1812 | ||
|
|
b15bb3b631 | ||
|
|
e069a990d0 | ||
|
|
1f758e162f | ||
|
|
c8a511ac89 | ||
|
|
028392e338 | ||
|
|
c68c3a7c2e | ||
|
|
f076cdb784 | ||
|
|
501dfa2cd9 | ||
|
|
c195079b45 | ||
|
|
0d187ec587 | ||
|
|
24444a3ac3 | ||
|
|
327387db37 | ||
|
|
3344313557 | ||
|
|
cb15eee684 | ||
|
|
e79a56eb15 | ||
|
|
218478f208 | ||
|
|
b59cf5e0bb | ||
|
|
a89585f9f3 | ||
|
|
048d3c75c0 | ||
|
|
e657a4068d | ||
|
|
f67e0e97de | ||
|
|
f079792da3 | ||
|
|
c595df4d98 | ||
|
|
33ade8a9c7 | ||
|
|
a65fa76481 | ||
|
|
01f6cdb128 | ||
|
|
aa121260c0 | ||
|
|
cce0633a9f | ||
|
|
755166f099 | ||
|
|
3f3ca0c59b | ||
|
|
197818d927 | ||
|
|
594e168863 | ||
|
|
d94becd721 | ||
|
|
e065e3deb5 | ||
|
|
1295257d1a | ||
|
|
df287c4de0 | ||
|
|
004cbc29b7 | ||
|
|
8f5ca9bce4 | ||
|
|
0e6c3ffb70 | ||
|
|
7ec980e98f | ||
|
|
6f81382a8a | ||
|
|
bb4e13c3ca | ||
|
|
745f7c88b0 | ||
|
|
a7d1bb57d1 | ||
|
|
a1ef1103d9 | ||
|
|
4ffc27b9e6 | ||
|
|
8e52b07dc3 | ||
|
|
02d1f3878e | ||
|
|
e0b9e49b81 | ||
|
|
d267635c73 | ||
|
|
ea5c563b20 | ||
|
|
24f858e6a0 | ||
|
|
6020f8f6d5 | ||
|
|
ed2dfeaa0b | ||
|
|
af245fe975 | ||
|
|
8c7a66ea28 | ||
|
|
318a7f9f61 | ||
|
|
213a2f4673 | ||
|
|
0d1998a388 | ||
|
|
ccd282dc74 | ||
|
|
f4fa8f4208 | ||
|
|
b1efed7899 | ||
|
|
b5679ecc82 | ||
|
|
da860a440a | ||
|
|
36f41ebf17 | ||
|
|
bad1e4027d | ||
|
|
c09113fee9 | ||
|
|
27e415895f | ||
|
|
91f4740cbd | ||
|
|
ab7165adc8 | ||
|
|
d83fbfd70f | ||
|
|
a46a49c6cd | ||
|
|
0bba05a888 | ||
|
|
2c14b47358 | ||
|
|
1f855c78a8 | ||
|
|
b4ab20432c | ||
|
|
cf40438a14 | ||
|
|
63e563e551 | ||
|
|
0dbaaff644 | ||
|
|
93954728df | ||
|
|
e70b257286 | ||
|
|
90ea07fade | ||
|
|
992e35d6c4 | ||
|
|
372d270380 | ||
|
|
430ef17946 | ||
|
|
c56999858c | ||
|
|
37430639c6 | ||
|
|
0e22862ec1 | ||
|
|
33c8883607 | ||
|
|
c8b47db3d2 | ||
|
|
99c5735b65 | ||
|
|
4631d414a5 | ||
|
|
f07d73a8c7 | ||
|
|
35ce507ce8 | ||
|
|
f55418b9fa | ||
|
|
e943775fb7 | ||
|
|
3f509e9779 | ||
|
|
672b0c2d84 | ||
|
|
3f5016eadd | ||
|
|
fc3d3620b6 | ||
|
|
f7adb0e382 | ||
|
|
b1da996326 | ||
|
|
d9842d5a04 | ||
|
|
52f3ce23cc | ||
|
|
b906abc1c3 | ||
|
|
de2e28afee | ||
|
|
dc9a80f41b | ||
|
|
ce60197a92 | ||
|
|
7939137a80 | ||
|
|
713ba9ae27 | ||
|
|
1c22b6202f | ||
|
|
ccefa60e4b | ||
|
|
0226e3ee27 | ||
|
|
2af02b3f70 | ||
|
|
935cd66503 | ||
|
|
98223ee47e | ||
|
|
6047d01353 | ||
|
|
8cb719c2f9 | ||
|
|
0d377b05d1 | ||
|
|
5b7d16c459 | ||
|
|
6f22117c98 | ||
|
|
1ab7e7a0d7 | ||
|
|
28b2ec6439 | ||
|
|
0c64aad2f2 | ||
|
|
3b5dfb8674 | ||
|
|
548626864e | ||
|
|
ae8e5cdae8 | ||
|
|
b3d7d44903 | ||
|
|
b2e5aa16e8 | ||
|
|
68946ce5f7 | ||
|
|
4be5722f5b | ||
|
|
191950fdc8 | ||
|
|
1cb355f8da | ||
|
|
ea7c519963 | ||
|
|
b318cffcb7 | ||
|
|
a80232668c | ||
|
|
bc50c19f21 | ||
|
|
a2d06c8403 | ||
|
|
8217da31e5 | ||
|
|
380b542a78 | ||
|
|
089cdd8639 |
@@ -0,0 +1,51 @@
|
||||
name: React App CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
paths:
|
||||
- 'client/**/*.html'
|
||||
- 'client/**/*.png'
|
||||
- 'client/**/*.json'
|
||||
- 'client/**/*.txt'
|
||||
- 'client/**/*.ts'
|
||||
- 'client/**/*.tsx'
|
||||
- 'client/**/*.js'
|
||||
- 'client/Dockerfile'
|
||||
- 'client/Caddyfile'
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
working-directory: ./client
|
||||
|
||||
- name: Run lint
|
||||
run: npm run lint
|
||||
working-directory: ./client
|
||||
|
||||
- name: Run build
|
||||
run: npm run build
|
||||
working-directory: ./client
|
||||
|
||||
- name: Run tests
|
||||
run: npm run test:no-watch
|
||||
working-directory: ./client
|
||||
@@ -0,0 +1,77 @@
|
||||
name: Build and Push App Docker Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'client/**/*.html'
|
||||
- 'client/**/*.png'
|
||||
- 'client/**/*.json'
|
||||
- 'client/**/*.txt'
|
||||
- 'client/**/*.ts'
|
||||
- 'client/**/*.tsx'
|
||||
- 'client/**/*.js'
|
||||
- 'client/Dockerfile'
|
||||
- 'client/Caddyfile'
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Generate version tag
|
||||
id: version
|
||||
run: |
|
||||
DATE=$(date +'%Y.%m.%d')
|
||||
TAG="app-v${DATE}.${{ github.run_number }}"
|
||||
echo "tag=${TAG}" >> $GITHUB_OUTPUT
|
||||
echo "Generated tag: ${TAG}"
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}/app
|
||||
tags: |
|
||||
type=raw,value=${{ steps.version.outputs.tag }}
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./client
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
VITE_BUILD=v${{ steps.version.outputs.tag }}
|
||||
|
||||
- name: Create and push Git tag
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -a ${{ steps.version.outputs.tag }} -m "Release ${{ steps.version.outputs.tag }}"
|
||||
git push origin ${{ steps.version.outputs.tag }}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
name: Build and Push API Docker Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'server/**/*.java'
|
||||
- 'server/**/*.xml'
|
||||
- 'server/pom.xml'
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set lowercase repo name
|
||||
id: repo
|
||||
run: echo "name=${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set up Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '25'
|
||||
cache: 'maven'
|
||||
|
||||
- name: Increment version in pom.xml
|
||||
id: version
|
||||
working-directory: ./server
|
||||
run: |
|
||||
# Extract current version from pom.xml
|
||||
CURRENT_VERSION=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout)
|
||||
echo "Current version: ${CURRENT_VERSION}"
|
||||
|
||||
# Increment version
|
||||
NEW_VERSION=$((CURRENT_VERSION + 1))
|
||||
echo "New version: ${NEW_VERSION}"
|
||||
|
||||
# Update pom.xml with new version
|
||||
./mvnw versions:set -DnewVersion=${NEW_VERSION} -DgenerateBackupFiles=false -q
|
||||
|
||||
# Output for later steps
|
||||
echo "version=${NEW_VERSION}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Commit version bump
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add server/pom.xml
|
||||
git commit -m "chore: bump api version to ${{ steps.version.outputs.version }} [skip ci]"
|
||||
git push
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build Docker image with Spring Boot
|
||||
working-directory: ./server
|
||||
run: |
|
||||
./mvnw -Pnative -DskipTests spring-boot:build-image \
|
||||
-Dspring-boot.build-image.imageName=ghcr.io/${{ steps.repo.outputs.name }}/api:latest \
|
||||
-Dspring-boot.build-image.builder=paketobuildpacks/builder-jammy-tiny:latest
|
||||
|
||||
- name: Tag and push Docker image
|
||||
run: |
|
||||
docker tag ghcr.io/${{ steps.repo.outputs.name }}/api:latest ghcr.io/${{ steps.repo.outputs.name }}/api:${{ steps.version.outputs.version }}
|
||||
docker push ghcr.io/${{ steps.repo.outputs.name }}/api:latest
|
||||
docker push ghcr.io/${{ steps.repo.outputs.name }}/api:${{ steps.version.outputs.version }}
|
||||
|
||||
- name: Create and push Git tag
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -a api-v${{ steps.version.outputs.version }} -m "Release API v${{ steps.version.outputs.version }}"
|
||||
git push origin api-v${{ steps.version.outputs.version }}
|
||||
@@ -0,0 +1,43 @@
|
||||
name: Server API CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
# run for all pushes, not only main
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
paths:
|
||||
- 'server/**/*.java'
|
||||
- 'server/**/*.xml'
|
||||
- 'server/pom.xml'
|
||||
|
||||
jobs:
|
||||
run-checks:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '25'
|
||||
cache: 'maven'
|
||||
|
||||
- name: Run Check Style
|
||||
working-directory: ./server
|
||||
run: ./mvnw --no-transfer-progress checkstyle:check -Dcheckstyle.skip=false
|
||||
|
||||
- name: Run build
|
||||
working-directory: ./server
|
||||
run: ./mvnw --no-transfer-progress clean compile -DskipTests
|
||||
|
||||
- name: Run tests
|
||||
working-directory: ./server
|
||||
run: ./mvnw --no-transfer-progress clean verify -P tests --file pom.xml
|
||||
@@ -1,15 +1,16 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
client/node_modules
|
||||
client/.pnp
|
||||
client.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
client/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
client/build
|
||||
client/dist
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
@@ -21,3 +22,11 @@
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
.env
|
||||
|
||||
# Local PG data
|
||||
/localpgdata
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# 🤝 Contributing
|
||||
|
||||
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
|
||||
|
||||
This project is an opensource project, meaning you can contribute as many times as you want! We work with the **Fork & Merge** flow.
|
||||
|
||||
If you want to contribute, please create a fork and a Merge Request. Take a look [here to learn more.](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork)
|
||||
|
||||
## Steps to Contribute
|
||||
|
||||
1. Fork the Project
|
||||
2. Clone it on your local (`git clone https://github.com/ricardo-campos-org/react-typescript-todolist`)
|
||||
3. Develop your amazing feature/changes
|
||||
4. Make sure your name is set (`git config user.name 'YOUR NAME'; git config user.email 'YOUR EMAIL'`)
|
||||
5. Commit your changes (`git commit -m 'Add some amazing feature'`)
|
||||
6. Push to the Branch (`git push`)
|
||||
7. Open a Merge Request
|
||||
|
||||
## 🏃♀️ Running locally
|
||||
|
||||
> If your OS is Microsoft Windows, make sure to run this on a Linux VM over WSL2.
|
||||
|
||||
The easiest way of having the app up and running is using [Docker](https://www.docker.com/). Once you're all set, follow these steps to see it live locally:
|
||||
|
||||
1. Start the database engine (PostgreSQL)
|
||||
```sh
|
||||
bash tools/run-docker-db.sh
|
||||
```
|
||||
2. Start the back-end engine (Java & Spring Boot)
|
||||
```sh
|
||||
bash tools/run-docker-server.sh
|
||||
```
|
||||
3. Start the app server
|
||||
```sh
|
||||
bash tools/run-docker-client.sh
|
||||
```
|
||||
|
||||
> Remember to follow up logs with 'docker ps' and 'docker logs -f <name>'
|
||||
|
||||
If everything went well, you can head to [http://localhost:5000](http://localhost:5000) and create your user.
|
||||
|
||||
## 🦾 Automation
|
||||
|
||||
Once you finish your changes, just create a Merge Request to get started.
|
||||
|
||||
This project has workflows to ensure quality code, including linting, testing and security checks. Your changes will be merged only after all check passes.
|
||||
|
||||
You can check locally if changes are passing:
|
||||
|
||||
1. Back-end
|
||||
```sh
|
||||
bash tools/check-backend.sh
|
||||
```
|
||||
2. Front-end
|
||||
```sh
|
||||
bash tools/check-frontend.sh
|
||||
```
|
||||
|
||||
> Remember to follow up logs with 'docker ps' and 'docker logs -f <name>'
|
||||
|
||||
## Debugging Java
|
||||
|
||||
You might need to create a `launch.json` file. Here's a working one
|
||||
|
||||
```json
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Debug (Attach)",
|
||||
"request": "attach",
|
||||
"hostName": "localhost",
|
||||
"port": 5005
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,8 +1,295 @@
|
||||
## Simple React Project to Study
|
||||
# TaskNote
|
||||
|
||||
- React
|
||||
- TypeScript
|
||||
- Featuring
|
||||
- CSS as modules
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
[](https://github.com/RMCampos/tasknote/actions/workflows/client-ci.yml)
|
||||
[](https://github.com/RMCampos/tasknote/actions/workflows/server-ci.yml)
|
||||
[](https://github.com/RMCampos/tasknote/actions/workflows/main-client.yml)
|
||||
[](https://github.com/RMCampos/tasknote/actions/workflows/main-server.yml)
|
||||
|
||||
This project was based on a course from **Matheus Battisti** on Udemy (https://www.udemy.com/course/typescript-do-basico-ao-avancado-c-react-express/)
|
||||
## 📋 Table of Contents
|
||||
|
||||
- [📝 About the Project](#-about-the-project)
|
||||
- [✨ Features](#-features)
|
||||
- [🚀 Tech Stack](#-tech-stack)
|
||||
- [🏗️ Architecture](#️-architecture)
|
||||
- [🚀 Getting Started](#-getting-started)
|
||||
- [🛠️ Development](#️-development)
|
||||
- [🧪 Testing](#-testing)
|
||||
- [📦 Deployment](#-deployment)
|
||||
- [🤝 Contributing](#-contributing)
|
||||
- [👨💻 Developer](#-developer)
|
||||
- [📞 Contact](#-contact)
|
||||
- [📄 License](#-license)
|
||||
|
||||
## 📝 About the Project
|
||||
|
||||
TaskNote is a full-stack productivity application designed for managing tasks and notes with simplicity and effectiveness in mind. Originally created to address personal productivity needs, it has evolved into a comprehensive, open-source solution featuring a modern tech stack and enterprise-grade architecture.
|
||||
|
||||
The project was born from a month-long technical challenge and has since grown to include robust authentication, internationalization support, responsive design, and comprehensive testing coverage.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
### Current Features
|
||||
- **Task Management**: Create, edit, delete, and organize TODO items with due dates and priority levels
|
||||
- **Note Taking**: Rich text notes with Markdown support for better formatting
|
||||
- **Smart Search**: Full-text search across tasks and notes with real-time filtering
|
||||
- **User Authentication**: Secure JWT-based authentication with automatic token refresh
|
||||
- **Internationalization**: Multi-language support (English, Portuguese, Spanish, Russian)
|
||||
- **Responsive Design**: Mobile-first approach with Bootstrap 5 and dark/light theme support
|
||||
- **Data Visualization**: Task completion charts and productivity analytics
|
||||
- **File Attachments**: URL attachments for tasks and notes
|
||||
- **Tagging System**: `#tag` support for better organization
|
||||
- **Mobile App**: Native mobile applications for iOS and Android with PWA plugin
|
||||
- **Collaboration**: Share tasks and notes with other users
|
||||
|
||||
### Upcoming Features
|
||||
- **Advanced Filters**: Enhanced search with date ranges, priority levels, and status filters
|
||||
- **Notifications**: Email and push notifications for due dates and reminders
|
||||
|
||||
## 🚀 Tech Stack
|
||||
|
||||
### Frontend (React & TypeScript)
|
||||
- **Framework**: React 19 with TypeScript for type safety
|
||||
- **Build Tool**: Vite for fast development and optimized production builds
|
||||
- **Testing**: Vitest with React Testing Library and comprehensive coverage reporting
|
||||
- **Styling**: Bootstrap 5 with custom SCSS and theme support
|
||||
- **State Management**: React Context API for authentication and sidebar state
|
||||
- **Routing**: React Router 7 with dynamic route configuration
|
||||
- **Internationalization**: i18next with automatic language detection
|
||||
- **API Client**: Centralized API service with automatic authentication headers
|
||||
|
||||
### Backend (Java & Spring Boot)
|
||||
- **Framework**: Spring Boot 4.x.x with Java 25
|
||||
- **Security**: Spring Security with JWT authentication and refresh tokens
|
||||
- **Database**: PostgreSQL with JPA/Hibernate ORM
|
||||
- **Migration**: Flyway for database schema versioning
|
||||
- **Documentation**: OpenAPI/Swagger UI for API documentation
|
||||
- **Testing**: JUnit with separate unit and integration test suites
|
||||
- **Code Quality**: Checkstyle, JaCoCo coverage (75% minimum), Maven Enforcer
|
||||
- **Build Options**: Traditional JAR or GraalVM native image compilation
|
||||
|
||||
### Database & Infrastructure
|
||||
- **Database**: PostgreSQL with optimized indexes and constraints
|
||||
- **Containerization**: Docker and Docker Compose for development environment
|
||||
- **Web Server**: Caddy for reverse proxy and SSL termination
|
||||
- **CI/CD**: GitHub Actions with automated testing and quality gates
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
### Monorepo Structure
|
||||
```
|
||||
tasknote/
|
||||
├── client/ # React TypeScript frontend
|
||||
├── server/ # Java Spring Boot REST API
|
||||
├── tools/ # Development and deployment scripts
|
||||
└── docker-compose.yml
|
||||
```
|
||||
|
||||
### Frontend Architecture
|
||||
- **Component Structure**: Modular components with TypeScript interfaces
|
||||
- **Authentication Flow**: JWT tokens with 2-minute refresh intervals
|
||||
- **Theme System**: CSS custom properties for dark/light mode switching
|
||||
- **Responsive Layout**: Mobile-first design with sidebar navigation
|
||||
- **Error Handling**: Centralized error boundary and user feedback
|
||||
|
||||
### Backend Architecture
|
||||
- **RESTful API**: Clean REST endpoints with proper HTTP status codes
|
||||
- **Security Layer**: JWT validation, CORS configuration, and input validation
|
||||
- **Service Layer**: Business logic separation with transaction management
|
||||
- **Repository Pattern**: Data access abstraction with custom queries
|
||||
- **Email Service**: Template-based email notifications for user actions
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
### Prerequisites
|
||||
- **Docker & Docker Compose** (recommended for easy setup)
|
||||
- **Node.js 20+** and **npm** (for frontend development)
|
||||
- **Java 25+** and **Maven 3.6+** (for backend development)
|
||||
- **PostgreSQL 15+** (if running without Docker)
|
||||
|
||||
### Quick Start with Docker
|
||||
1. **Clone the repository**
|
||||
```bash
|
||||
git clone https://github.com/rmcampos/tasknote.git
|
||||
cd tasknote
|
||||
```
|
||||
|
||||
2. **Start the database**
|
||||
```bash
|
||||
bash tools/run-docker-db.sh
|
||||
```
|
||||
|
||||
3. **Start the backend server**
|
||||
```bash
|
||||
bash tools/run-docker-server.sh
|
||||
```
|
||||
|
||||
4. **Start the frontend application**
|
||||
```bash
|
||||
bash tools/run-docker-client.sh
|
||||
```
|
||||
|
||||
5. **Access the application**
|
||||
- Frontend: http://localhost:5000
|
||||
|
||||
## 🛠️ Development
|
||||
|
||||
### Frontend Development
|
||||
```bash
|
||||
cd client
|
||||
npm install # Install dependencies
|
||||
npm start # Start development server (port 5000)
|
||||
npm run build # Build for production
|
||||
npm run preview # Preview production build
|
||||
npm run lint # Run ESLint
|
||||
npm run lint:fix # Fix ESLint issues
|
||||
```
|
||||
|
||||
### Backend Development
|
||||
```bash
|
||||
cd server
|
||||
./mvnw spring-boot:run # Start development server
|
||||
./mvnw clean compile # Compile sources
|
||||
./mvnw spring-boot:build-image # Build Docker image
|
||||
./mvnw clean verify -Pnative # Build GraalVM native image
|
||||
```
|
||||
|
||||
### Quality Checks
|
||||
Run quality checks before submitting changes:
|
||||
```bash
|
||||
bash tools/check-frontend.sh # Frontend linting, testing, coverage
|
||||
bash tools/check-backend.sh # Backend compilation, tests, checkstyle
|
||||
```
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
### Frontend Testing
|
||||
- **Framework**: Vitest with React Testing Library
|
||||
- **Coverage**: Comprehensive test coverage with reports in `client/coverage/`
|
||||
- **Commands**:
|
||||
```bash
|
||||
npm test # Run tests in watch mode
|
||||
npm run test:coverage # Generate coverage report
|
||||
```
|
||||
|
||||
### Backend Testing
|
||||
- **Unit Tests**: Fast, isolated tests with mocked dependencies
|
||||
- **Integration Tests**: Full application context with test database
|
||||
- **Coverage**: JaCoCo reporting with 75% minimum requirement
|
||||
- **Commands**:
|
||||
```bash
|
||||
./mvnw test # Unit tests only
|
||||
./mvnw clean verify -Ptests # All tests with coverage
|
||||
```
|
||||
|
||||
## 📦 Deployment
|
||||
|
||||
### Production Deployment
|
||||
The application supports multiple deployment strategies:
|
||||
|
||||
1. **Docker Containers** (recommended)
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
2. **Traditional JAR Deployment**
|
||||
```bash
|
||||
cd server && ./mvnw clean package
|
||||
java -jar target/tasknote-api.jar
|
||||
```
|
||||
|
||||
3. **GraalVM Native Image** (for optimal performance)
|
||||
```bash
|
||||
cd server && ./mvnw clean verify -Pnative
|
||||
./target/tasknote-api
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
- Database connection via environment variables
|
||||
- JWT secret configuration for production
|
||||
- Email service configuration for notifications
|
||||
- CORS settings for frontend domain
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We welcome contributions from the community! This project follows the **Fork & Merge** workflow.
|
||||
|
||||
### How to Contribute
|
||||
|
||||
1. **Fork the Project** on GitHub
|
||||
2. **Clone your fork** locally
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/tasknote.git
|
||||
```
|
||||
3. **Create a feature branch**
|
||||
```bash
|
||||
git checkout -b feature/amazing-feature
|
||||
```
|
||||
4. **Make your changes** and ensure they follow the project standards
|
||||
5. **Run quality checks**
|
||||
```bash
|
||||
bash tools/check-frontend.sh
|
||||
bash tools/check-backend.sh
|
||||
```
|
||||
6. **Commit your changes**
|
||||
```bash
|
||||
git commit -m 'Add some amazing feature'
|
||||
```
|
||||
7. **Push to your fork**
|
||||
```bash
|
||||
git push origin feature/amazing-feature
|
||||
```
|
||||
8. **Open a Pull Request** with a detailed description
|
||||
|
||||
### Development Guidelines
|
||||
- Follow existing code conventions and patterns
|
||||
- Write tests for new functionality
|
||||
- Update documentation when necessary
|
||||
- Ensure all quality checks pass
|
||||
- Keep commits focused and descriptive
|
||||
|
||||
For detailed setup instructions and development workflows, see [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## 👨💻 Developer
|
||||
|
||||
**Ricardo Campos** - Full-Stack Developer & Project Maintainer
|
||||
|
||||
- **GitHub**: [@RMCampos](https://github.com/RMCampos)
|
||||
- **Twitter/X**: [@RMCamposs](https://x.com/RMCamposs)
|
||||
- **LinkedIn**: [Ricardo Campos](https://www.linkedin.com/in/ricardompcampos/)
|
||||
|
||||
### About the Developer
|
||||
Ricardo is a passionate full-stack developer with expertise in modern web technologies, cloud architecture, and agile development practices. This project showcases his skills in:
|
||||
|
||||
- **Frontend Development**: React, TypeScript, modern CSS, responsive design
|
||||
- **Backend Development**: Java, Spring Boot, RESTful APIs, microservices
|
||||
- **DevOps & Infrastructure**: Docker, CI/CD, cloud deployment, monitoring
|
||||
- **Software Quality**: Testing strategies, code coverage, static analysis
|
||||
- **Open Source**: Community engagement, documentation, maintainership
|
||||
|
||||
The TaskNote project represents a commitment to clean code, comprehensive testing, and user-centered design principles.
|
||||
|
||||
## 📞 Contact
|
||||
|
||||
For questions, suggestions, or collaboration opportunities:
|
||||
|
||||
- **Email**: Contact via GitHub issues or discussions
|
||||
- **Twitter/X**: [@RMCamposs](https://x.com/RMCamposs) for quick questions
|
||||
- **GitHub Issues**: [Create an issue](https://github.com/rmcampos/tasknote/issues) for bugs or feature requests
|
||||
- **GitHub Discussions**: [Join discussions](https://github.com/rmcampos/tasknote/discussions) for general questions
|
||||
|
||||
## 📄 License
|
||||
|
||||
This project is licensed under the **GNU General Public License v3.0** - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
### What this means:
|
||||
- ✅ **Freedom to use**: Use the software for any purpose
|
||||
- ✅ **Freedom to study**: Access and modify the source code
|
||||
- ✅ **Freedom to share**: Distribute copies of the software
|
||||
- ✅ **Freedom to improve**: Distribute modified versions
|
||||
|
||||
**Copyleft**: Any derivative work must also be open source under GPL v3.0
|
||||
|
||||
---
|
||||
|
||||
⭐ **Star this repository if you find it helpful!** ⭐
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
meta {
|
||||
name: 0-Signup new user
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
put {
|
||||
url: {{addr}}/auth/sign-up
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "{{testEmail}}",
|
||||
"password": "Teste@123.,",
|
||||
"passwordAgain": "Teste@123.,",
|
||||
"lang": "en"
|
||||
}
|
||||
}
|
||||
|
||||
script:pre-request {
|
||||
const testEmail = `test_${Date.now()}@example.com`;
|
||||
const testUsername = `test_user_${Date.now()}`;
|
||||
|
||||
bru.setVar("testEmail", testEmail);
|
||||
}
|
||||
|
||||
tests {
|
||||
test("Status code is 204", function() {
|
||||
expect(res.getStatus()).to.equal(204);
|
||||
});
|
||||
|
||||
test("Response time is acceptable", function() {
|
||||
expect(res.getResponseTime()).to.be.below(3000);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
meta {
|
||||
name: 1-Signup duplicate user
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
put {
|
||||
url: {{addr}}/auth/sign-up
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "{{testEmail}}",
|
||||
"password": "Teste@123.,",
|
||||
"passwordAgain": "Teste@123.,",
|
||||
"lang": "en"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("Status code is 409", function() {
|
||||
expect(res.getStatus()).to.equal(409);
|
||||
});
|
||||
|
||||
test("Response time is acceptable", function() {
|
||||
expect(res.getResponseTime()).to.be.below(3000);
|
||||
});
|
||||
|
||||
test("Content type is JSON", function() {
|
||||
expect(res.getHeader('content-type')).to.contain('application/json');
|
||||
});
|
||||
|
||||
test("Response has data property", function() {
|
||||
const body = res.getBody();
|
||||
expect(body).to.have.property('error');
|
||||
expect(body).to.have.property('message');
|
||||
expect(body.message).to.equal('Email already exists!');
|
||||
bru.setVar("authToken", body.token);
|
||||
});
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
meta {
|
||||
name: 2-Sign in user
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{addr}}/auth/sign-in
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "{{testEmail}}",
|
||||
"password": "Teste@123.,",
|
||||
"passwordAgain": "Teste@123.,",
|
||||
"lang": "en"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("Status code is 200", function() {
|
||||
expect(res.getStatus()).to.equal(200);
|
||||
});
|
||||
|
||||
test("Response time is acceptable", function() {
|
||||
expect(res.getResponseTime()).to.be.below(3000);
|
||||
});
|
||||
|
||||
test("Content type is JSON", function() {
|
||||
expect(res.getHeader('content-type')).to.contain('application/json');
|
||||
});
|
||||
|
||||
test("Response has all data well set and defined", function() {
|
||||
const body = res.getBody();
|
||||
|
||||
expect(body).to.have.property('userId');
|
||||
expect(body).to.have.property('name');
|
||||
expect(body).to.have.property('email');
|
||||
expect(body).to.have.property('admin');
|
||||
expect(body).to.have.property('createdAt');
|
||||
expect(body).to.have.property('inactivatedAt');
|
||||
expect(body).to.have.property('gravatarImageUrl');
|
||||
expect(body).to.have.property('token');
|
||||
expect(body).to.have.property('lang');
|
||||
|
||||
expect(body.userId).to.be.greaterThan(0);
|
||||
expect(body.name).to.be.null;
|
||||
expect(body.email).to.equal(bru.getVar("testEmail"));
|
||||
expect(body.admin).to.equal(false);
|
||||
expect(body.createdAt).to.not.be.null;
|
||||
expect(body.inactivatedAt).to.be.null;
|
||||
expect(body.gravatarImageUrl).to.not.be.null;
|
||||
expect(body.token).to.not.be.null;
|
||||
expect(body.lang).to.equal('en');
|
||||
bru.setVar("authToken", body.token);
|
||||
});
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
meta {
|
||||
name: 3-Sign in user wrong pw
|
||||
type: http
|
||||
seq: 4
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{addr}}/auth/sign-in
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "{{testEmail}}",
|
||||
"password": "Teste@123.,11",
|
||||
"lang": "en"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("Status code is 401", function() {
|
||||
expect(res.getStatus()).to.equal(401);
|
||||
});
|
||||
|
||||
test("Response time is acceptable", function() {
|
||||
expect(res.getResponseTime()).to.be.below(3000);
|
||||
});
|
||||
|
||||
test("Content type is JSON", function() {
|
||||
expect(res.getHeader('content-type')).to.contain('application/json');
|
||||
});
|
||||
|
||||
test("Response has all data well set and defined", function() {
|
||||
const body = res.getBody();
|
||||
|
||||
expect(body).to.have.property('timestamp');
|
||||
expect(body).to.have.property('status');
|
||||
expect(body).to.have.property('error');
|
||||
expect(body).to.have.property('message');
|
||||
expect(body).to.have.property('path');
|
||||
|
||||
expect(body.timestamp).to.not.be.null;
|
||||
expect(body.status).to.equal(401);
|
||||
expect(body.error).to.equal('Unauthorized');
|
||||
expect(body.message).to.equal('Invalid credentials');
|
||||
expect(body.path).to.equal('/auth/sign-in');
|
||||
});
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
meta {
|
||||
name: Confirm Password Reset
|
||||
type: http
|
||||
seq: 8
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{addr}}/auth/complete-password-reset
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"token": "string",
|
||||
"password": "string",
|
||||
"passwordAgain": "string"
|
||||
}
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
meta {
|
||||
name: Email Confirmation
|
||||
type: http
|
||||
seq: 7
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{addr}}/auth/email-confirmation
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "ricardompcampos@gmail.com"
|
||||
}
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
meta {
|
||||
name: ReSend Email
|
||||
type: http
|
||||
seq: 5
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{addr}}/auth/resend-email-confirmation
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "ricardompcampos@gmail.com"
|
||||
}
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
meta {
|
||||
name: Reset Password
|
||||
type: http
|
||||
seq: 6
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{addr}}/auth/password-reset
|
||||
body: json
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "ricardompcampos@gmail.com"
|
||||
}
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
meta {
|
||||
name: Authentication
|
||||
seq: 2
|
||||
}
|
||||
|
||||
auth {
|
||||
mode: inherit
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
meta {
|
||||
name: 5-Get tags empty
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{addr}}/rest/home/tasks/tags
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{authToken}}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("Response is an empty array", function() {
|
||||
const body = res.getBody();
|
||||
expect(body).to.be.an('array').that.is.empty;
|
||||
});
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
meta {
|
||||
name: Home
|
||||
seq: 4
|
||||
}
|
||||
|
||||
auth {
|
||||
mode: inherit
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
meta {
|
||||
name: Refresh
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{addr}}/rest/user-sessions/refresh
|
||||
body: none
|
||||
auth: inherit
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
meta {
|
||||
name: Session
|
||||
seq: 2
|
||||
}
|
||||
|
||||
auth {
|
||||
mode: inherit
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
meta {
|
||||
name: Task
|
||||
seq: 3
|
||||
}
|
||||
|
||||
auth {
|
||||
mode: inherit
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
meta {
|
||||
name: 999-Delete account
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
delete {
|
||||
url: {{addr}}/rest/user-sessions/delete-account
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{authToken}}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("Status code is 200", function() {
|
||||
expect(res.getStatus()).to.equal(200);
|
||||
});
|
||||
|
||||
test("Response time is acceptable", function() {
|
||||
expect(res.getResponseTime()).to.be.below(3000);
|
||||
});
|
||||
|
||||
test("User deletion response is valid", function() {
|
||||
const body = res.getBody();
|
||||
|
||||
// User ID assertions
|
||||
expect(body.userId).to.exist;
|
||||
expect(body.userId).to.be.a('number');
|
||||
expect(body.userId).to.be.greaterThan(0);
|
||||
|
||||
// Name should be null after deletion
|
||||
expect(body.name).to.be.null;
|
||||
|
||||
// Email assertions
|
||||
expect(body.email).to.exist;
|
||||
expect(body.email).to.be.a('string');
|
||||
expect(body.email).to.not.be.empty;
|
||||
expect(body.email).to.match(/^[\w\.-]+@[\w\.-]+\.\w+$/);
|
||||
|
||||
// Admin flag
|
||||
expect(body.admin).to.exist;
|
||||
expect(body.admin).to.be.a('boolean');
|
||||
|
||||
// CreatedAt assertions
|
||||
expect(body.createdAt).to.exist;
|
||||
expect(body.createdAt).to.be.a('string');
|
||||
expect(body.createdAt).to.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
|
||||
|
||||
// InactivatedAt should exist and not be null (user was deleted)
|
||||
expect(body.inactivatedAt).to.exist;
|
||||
expect(body.inactivatedAt).to.not.be.null;
|
||||
expect(body.inactivatedAt).to.be.a('string');
|
||||
expect(body.inactivatedAt).to.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
|
||||
|
||||
// Gravatar URL
|
||||
expect(body.gravatarImageUrl).to.exist;
|
||||
expect(body.gravatarImageUrl).to.be.a('string');
|
||||
expect(body.gravatarImageUrl).to.have.lengthOf(64); // SHA-256 hash length
|
||||
});
|
||||
|
||||
test("User was inactivated after creation", function() {
|
||||
const body = res.getBody();
|
||||
|
||||
const createdAt = new Date(body.createdAt);
|
||||
const inactivatedAt = new Date(body.inactivatedAt);
|
||||
|
||||
expect(inactivatedAt).to.be.greaterThan(createdAt);
|
||||
});
|
||||
|
||||
test("Email matches the test user", function() {
|
||||
const body = res.getBody();
|
||||
const expectedEmail = bru.getVar("testEmail");
|
||||
|
||||
expect(body.email).to.equal(expectedEmail);
|
||||
});
|
||||
}
|
||||
|
||||
settings {
|
||||
encodeUrl: true
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
meta {
|
||||
name: User Session
|
||||
seq: 5
|
||||
}
|
||||
|
||||
auth {
|
||||
mode: inherit
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"version": "1",
|
||||
"name": "TaskNoteBruno",
|
||||
"type": "collection",
|
||||
"ignore": [
|
||||
"node_modules",
|
||||
".git"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
auth {
|
||||
mode: bearer
|
||||
}
|
||||
|
||||
auth:bearer {
|
||||
token: eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJKYXZhLUFQSSIsInN1YiI6InJpY2FyZG9tcGNhbXBvc0BnbWFpbC5jb20iLCJpYXQiOjE3NTgzOTQ5NzEsImV4cCI6MTc1ODk5OTc3MSwicm9sZXMiOltdLCJ1c2VySWQiOjEsImVtYWlsIjoicmljYXJkb21wY2FtcG9zQGdtYWlsLmNvbSJ9.ZdlouCYWF_kIEwJ2d7Nl3ASA6xS9OeSke84KXa94ugo
|
||||
}
|
||||
|
||||
vars:pre-request {
|
||||
addr: http://localhost:8585
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
vars {
|
||||
addr: http://localhost:8585
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
vars {
|
||||
addr: https://api.tasknoteapp.dev.br
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
vars {
|
||||
addr: https://stageapi.tasknoteapp.dev.br
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
# https://taskfile.dev
|
||||
|
||||
version: '3'
|
||||
|
||||
vars:
|
||||
GREETING: Hello, World!
|
||||
|
||||
tasks:
|
||||
docker-build-web:
|
||||
desc: Build the tasknote-web prod-ready docker image, tagging it as candidate
|
||||
cmd: docker build --no-cache --build-arg VITE_BUILD="v999-$(date '+%Y-%m-%d-%H%M%S')" --build-arg SOURCE_PR="v999-123456789-$(date '+%Y-%m-%d-%H%M%S')" -t ghcr.io/rmcampos/tasknote/app:latest ./client
|
||||
|
||||
docker-build-api:
|
||||
desc: Build the tasknote-api prod-ready docker image, tagging it as candidate
|
||||
cmd: cd server && mvn -Pnative -DskipTests spring-boot:build-image -Dspring-boot.build-image.imageName=ghcr.io/rmcampos/tasknote/api:latest -Dspring-boot.build-image.builder=paketobuildpacks/builder-jammy-tiny:latest
|
||||
|
||||
prod-up-web:
|
||||
desc: Speed up the tasknote-web prod-like image, building it if required
|
||||
cmd: docker compose -f docker-compose.prod.yml up -d tasknote-web
|
||||
|
||||
prod-up-api:
|
||||
desc: Speed up the tasknote-api prod-like image, building it if required
|
||||
cmd: docker compose -f docker-compose.prod.yml up -d tasknote-api
|
||||
|
||||
prod-up-db:
|
||||
desc: Start the database container
|
||||
cmd: docker compose -f docker-compose.prod.yml up -d tasknote-db
|
||||
|
||||
prod-up:
|
||||
desc: Speed up the prod-like images for both tasknote-api and tasknote-web, building them if required
|
||||
cmd: docker compose -f docker-compose.prod.yml up -d
|
||||
|
||||
prod-stop:
|
||||
desc: Stop prod containers
|
||||
cmd: docker compose -f docker-compose.prod.yml stop
|
||||
|
||||
prod-tier-down:
|
||||
desc: Stop and remove prod containers
|
||||
cmd: docker compose -f docker-compose.prod.yml down --remove-orphans
|
||||
|
||||
dev-run-web:
|
||||
desc: Get the tasknote-web up and running locally inside docker ready for development
|
||||
cmd: docker compose -f docker-compose.dev.yml up -d tasknote-web
|
||||
|
||||
dev-run-api:
|
||||
desc: Get the tasknote-api up and running locally inside docker ready for development
|
||||
cmd: docker compose -f docker-compose.dev.yml up -d tasknote-api
|
||||
|
||||
dev-run-db:
|
||||
desc: Get the tasknote-db up and running locally inside docker ready for development
|
||||
cmd: docker compose -f docker-compose.dev.yml up -d tasknote-db
|
||||
|
||||
dev-run:
|
||||
desc: Get both tasknote-web and tasknote-api up and running locally inside docker ready for development
|
||||
cmd: docker compose -f docker-compose.dev.yml up -d
|
||||
|
||||
dev-stop:
|
||||
desc: Stop dev containers
|
||||
cmd: docker compose -f docker-compose.dev.yml stop
|
||||
|
||||
dev-tier-down:
|
||||
desc: Stop and remove dev containers
|
||||
cmd: docker compose -f docker-compose.dev.yml down --remove-orphans
|
||||
@@ -0,0 +1,11 @@
|
||||
module.exports = {
|
||||
arrowParens: 'avoid',
|
||||
bracketSameLine: true,
|
||||
bracketSpacing: false,
|
||||
singleQuote: false,
|
||||
trailingComma: 'all',
|
||||
tabWidth: 2,
|
||||
useTabs: false,
|
||||
semi: true,
|
||||
printWidth: 80
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
auto_https off
|
||||
admin off
|
||||
}
|
||||
|
||||
:5000 {
|
||||
root * /app/dist
|
||||
|
||||
encode gzip
|
||||
|
||||
log {
|
||||
output stdout
|
||||
format console {
|
||||
time_format iso8601
|
||||
level_format color
|
||||
}
|
||||
level "INFO"
|
||||
}
|
||||
|
||||
header {
|
||||
X-Frame-Options "SAMEORIGIN"
|
||||
X-XSS-Protection "1;mode=block"
|
||||
Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate"
|
||||
X-Content-Type-Options "nosniff"
|
||||
Strict-Transport-Security "max-age=31536000"
|
||||
Content-Security-Policy "
|
||||
base-uri 'self';
|
||||
connect-src 'self' {$VITE_BACKEND_SERVER};
|
||||
default-src 'self' data:;
|
||||
font-src 'self' https://fonts.gstatic.com/ https://cdn.jsdelivr.net/;
|
||||
frame-src 'self';
|
||||
img-src 'self' data: https://gravatar.com/;
|
||||
manifest-src 'self';
|
||||
media-src 'self';
|
||||
object-src 'none';
|
||||
script-src 'unsafe-inline' 'report-sample' 'self' https://*.cloudfront.net;
|
||||
style-src 'report-sample' 'self' https://cdn.jsdelivr.net/ https://fonts.googleapis.com;
|
||||
worker-src 'none';
|
||||
"
|
||||
Referrer-Policy "same-origin"
|
||||
}
|
||||
|
||||
handle /env.js {
|
||||
header Content-Type "text/javascript"
|
||||
respond `window.config = {"VITE_BACKEND_SERVER":"{$VITE_BACKEND_SERVER}","VITE_BUILD":"{$VITE_BUILD}"};`
|
||||
}
|
||||
|
||||
handle /favicon.ico {
|
||||
file_server
|
||||
}
|
||||
|
||||
file_server
|
||||
|
||||
handle_errors {
|
||||
@404 {
|
||||
expression {http.error.status_code} == 404
|
||||
}
|
||||
rewrite @404 /
|
||||
file_server
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# Build static files
|
||||
# Node Bullseye has npm
|
||||
FROM node:22.14-bookworm-slim AS build
|
||||
ENV NODE_OPTIONS="--max-old-space-size=3072"
|
||||
|
||||
# Build
|
||||
WORKDIR /app
|
||||
COPY *.html *.json *.ts ./
|
||||
COPY ./src ./src
|
||||
COPY ./public ./public
|
||||
RUN npm i --ignore-scripts --no-update-notifier --omit=dev && \
|
||||
npm run build && \
|
||||
rm -rf node_modules
|
||||
|
||||
# Deploy container
|
||||
# Caddy serves static files
|
||||
FROM caddy:2.10.2-alpine
|
||||
RUN apk add --no-cache ca-certificates curl
|
||||
|
||||
# Receive build number as argument, retain as environment variable
|
||||
ARG VITE_BUILD
|
||||
ARG SOURCE_PR
|
||||
ENV VITE_BUILD=${VITE_BUILD}
|
||||
ENV SOURCE_PR=${SOURCE_PR}
|
||||
|
||||
# Add metadata to the final image
|
||||
LABEL org.opencontainers.image.authors="Ricardo Campos <ricardompcampos@gmail.com>" \
|
||||
org.opencontainers.image.vendor="Ricardo Campos Org" \
|
||||
org.opencontainers.image.title="TaskNoteApp client" \
|
||||
org.opencontainers.image.description="React Web app application" \
|
||||
org.opencontainers.image.version="${SOURCE_PR}" \
|
||||
org.opencontainers.image.source="https://github.com/ricardo-campos-org/react-typescript-todolist"
|
||||
|
||||
# Copy files and run formatting
|
||||
COPY --from=build /app/dist/ /app/dist
|
||||
COPY Caddyfile /etc/caddy/Caddyfile
|
||||
RUN caddy fmt --overwrite /etc/caddy/Caddyfile
|
||||
|
||||
# User, port and healthcheck
|
||||
EXPOSE 5000
|
||||
HEALTHCHECK CMD curl -f http://localhost:5000
|
||||
USER 1001
|
||||
@@ -0,0 +1,4 @@
|
||||
FROM node:22.14-bookworm-slim
|
||||
WORKDIR /app
|
||||
HEALTHCHECK CMD timeout 10s bash -c 'true > /dev/tcp/127.0.0.1/5000'
|
||||
CMD ["sh", "run-from-docker.sh"]
|
||||
@@ -0,0 +1,62 @@
|
||||
import globals from 'globals';
|
||||
import { fixupConfigRules } from '@eslint/compat';
|
||||
import jsLint from '@eslint/js';
|
||||
import tsLint from 'typescript-eslint';
|
||||
import pluginReactConfig from 'eslint-plugin-react/configs/recommended.js';
|
||||
import stylistic from '@stylistic/eslint-plugin';
|
||||
|
||||
export default [
|
||||
{
|
||||
files: ['**/*.{ts,tsx}']
|
||||
},
|
||||
{
|
||||
languageOptions: {
|
||||
// common parser options, enable TypeScript and JSX
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
sourceType: 'module'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
ignores: [
|
||||
'**/__test__/*',
|
||||
'**/assets/*',
|
||||
'**/*.scss',
|
||||
'**/*.css',
|
||||
'**/*.svg'
|
||||
]
|
||||
},
|
||||
{
|
||||
languageOptions: {
|
||||
globals: { ...globals.browser, ...globals.node }
|
||||
}
|
||||
},
|
||||
{
|
||||
settings: {
|
||||
'import/resolver': {
|
||||
node: {
|
||||
extensions: ['.js', '.jsx', ',ts', '.tsx']
|
||||
}
|
||||
},
|
||||
'react': {
|
||||
pragma: 'React',
|
||||
fragment: 'Fragment',
|
||||
version: '18.3'
|
||||
}
|
||||
}
|
||||
},
|
||||
// syntax rules
|
||||
jsLint.configs.recommended,
|
||||
...tsLint.configs.recommended,
|
||||
...fixupConfigRules(pluginReactConfig),
|
||||
// code style rules
|
||||
stylistic.configs['disable-legacy'],
|
||||
stylistic.configs.customize({
|
||||
indent: 2,
|
||||
quotes: 'single',
|
||||
semi: true,
|
||||
commaDangle: 'never',
|
||||
jsx: true
|
||||
})
|
||||
];
|
||||
@@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#ffffff" />
|
||||
<meta name="description" content="This app provides you tools to get organized and stay on op of notes and TODOs." />
|
||||
<meta name="robots" content="noindex" />
|
||||
<meta name="robots" content="nofollow" />
|
||||
<meta name="googlebot-news" content="noindex" />
|
||||
<meta name="keywords" content="TODOs, organization, notes, tools" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
|
||||
<link rel="canonical" href="https://tasknoteapp.dev.br" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,200..800;1,200..800&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
|
||||
<title>TaskNote is your daily-basis friend to keep up with notes and tasks</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
server {
|
||||
root /var/www/example.com/html;
|
||||
index index.html;
|
||||
|
||||
server_name example.com www.example.com;
|
||||
|
||||
location / {
|
||||
try_files $uri /index.html
|
||||
}
|
||||
|
||||
listen [::]:443 ssl ipv6only=on;
|
||||
listen 443 ssl;
|
||||
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/texample.com/privkey.pem;
|
||||
|
||||
location /server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header Host $host;
|
||||
proxy_pass http://localhost:8585;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
if ($host = www.example.com) {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
if ($host = example.com) {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
|
||||
server_name example.com www.example.com;
|
||||
return 404;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "task-note",
|
||||
"version": "1.0.0",
|
||||
"license": "GPL-3.0-only",
|
||||
"description": "TaskNote App - Your daily-basis friend to help you with TODOs and Notes",
|
||||
"keywords": [
|
||||
"react",
|
||||
"typescript",
|
||||
"node",
|
||||
"nestjs"
|
||||
],
|
||||
"repository": "https://github.com/ricardo-campos-org/react-typescript-todolist",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@types/node": "^25.3.2",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"bootstrap": "^5.3.8",
|
||||
"dompurify": "^3.3.1",
|
||||
"i18next": "^25.8.13",
|
||||
"react": "^19.2.4",
|
||||
"react-bootstrap": "^2.10.10",
|
||||
"react-bootstrap-icons": "^1.11.6",
|
||||
"react-charts": "^3.0.0-beta.57",
|
||||
"react-datepicker": "^9.1.0",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-i18next": "^16.5.4",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router": "^7.13.1",
|
||||
"react-router-bootstrap": "^0.26.3",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.3.1"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "vite --host",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite build && vite preview",
|
||||
"test": "vitest",
|
||||
"test:no-watch": "vitest --watch=false",
|
||||
"test:coverage": "vitest run --coverage --watch=false",
|
||||
"lint": "./node_modules/.bin/eslint",
|
||||
"lint:fix": "./node_modules/.bin/eslint --fix"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^2.0.2",
|
||||
"@eslint/eslintrc": "^3.3.4",
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@stylistic/eslint-plugin": "^5.9.0",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-router-bootstrap": "^0.26.8",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-jsdoc": "^62.7.1",
|
||||
"eslint-plugin-n": "^17.24.0",
|
||||
"eslint-plugin-promise": "^7.2.1",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"globals": "^17.3.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"prettier": "^3.8.1",
|
||||
"sass": "^1.97.3",
|
||||
"source-map-support": "^0.5.21",
|
||||
"typescript-eslint": "^8.56.1",
|
||||
"vitest": "^4.0.18"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 182 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 831 B |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "TastNote",
|
||||
"short_name": "TastNote",
|
||||
"icons":[
|
||||
{
|
||||
"src":"/android-chrome-192x192.png",
|
||||
"sizes":"192x192",
|
||||
"type":"image/png"
|
||||
},
|
||||
{
|
||||
"src":"/android-chrome-512x512.png",
|
||||
"sizes":"512x512",
|
||||
"type":"image/png"
|
||||
}
|
||||
],
|
||||
"theme_color":"#ffffff",
|
||||
"background_color":"#ffffff",
|
||||
"display":"standalone",
|
||||
"start_url": "."
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Must be unique in a given SonarQube instance
|
||||
sonar.projectKey=ricardo-campos-org_react-typescript-todolist_client
|
||||
sonar.organization=ricardo-campos-org
|
||||
|
||||
# This is the name and version displayed in the SonarQube UI.
|
||||
# Was mandatory prior to SonarQube 6.1.
|
||||
sonar.projectName=tasknote-webapp
|
||||
#sonar.projectVersion=1.0
|
||||
|
||||
# Path is relative to the sonar-project.properties file.
|
||||
# Replace "\" by "/" on Windows.
|
||||
# This property is optional if sonar.modules is set.
|
||||
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
||||
sonar.typescript.tsconfigPaths=tsconfig.json
|
||||
sonar.sources=src/
|
||||
sonar.exclusions=src/__test__/**
|
||||
sonar.tests=src/__test__/
|
||||
sonar.verbose=false
|
||||
|
||||
# Encoding of the source code. Default is default system encoding
|
||||
sonar.sourceEncoding=UTF-8
|
||||
@@ -0,0 +1,146 @@
|
||||
import React, { useContext, useEffect, useState } from 'react';
|
||||
import {
|
||||
createBrowserRouter,
|
||||
Navigate,
|
||||
RouteObject,
|
||||
RouterProvider
|
||||
} from 'react-router';
|
||||
import AuthContext from './context/AuthContext';
|
||||
import BrowserRoutes from './routes';
|
||||
import ProtectedRoute from './routes/ProtectedRoute';
|
||||
import PrivateLayout from './layout/PrivateLayout';
|
||||
import Landing from './views/Landing';
|
||||
import Login from './views/Login';
|
||||
import NotFound from './views/NotFound';
|
||||
import Register from './views/Register';
|
||||
import EmailConfirmation from './views/EmailConfirmation';
|
||||
import ResetPassword from './views/ResetPassword';
|
||||
import CompleteResetPassword from './views/CompleteResetPassword';
|
||||
import SharedNote from './views/SharedNote';
|
||||
import './styles/custom.scss';
|
||||
|
||||
/**
|
||||
* The main application component that sets up routing based on the
|
||||
* user's authentication status.
|
||||
*
|
||||
* @component
|
||||
* @returns {React.ReactNode} The rendered component.
|
||||
*/
|
||||
function App(): React.ReactNode {
|
||||
const { signed, checkCurrentAuthUser } = useContext(AuthContext);
|
||||
const [theme, setTheme] = useState(() => {
|
||||
return localStorage.getItem('theme') ?? 'light';
|
||||
});
|
||||
|
||||
/**
|
||||
* Routes for the users who are not signed in.
|
||||
* @type {RouteObject[]}
|
||||
*/
|
||||
const notSignedRouter: RouteObject[] = [
|
||||
{
|
||||
path: '/',
|
||||
element: <Landing />
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
element: <Login />
|
||||
},
|
||||
{
|
||||
path: '/register',
|
||||
element: <Register />
|
||||
},
|
||||
{
|
||||
path: '/home',
|
||||
element: <Navigate to="/login" replace />
|
||||
},
|
||||
{
|
||||
path: '/email-confirmation',
|
||||
element: <EmailConfirmation />
|
||||
},
|
||||
{
|
||||
// The reset-password is where the password reset workflow starts
|
||||
path: '/reset-password',
|
||||
element: <ResetPassword />
|
||||
},
|
||||
{
|
||||
path: '/finish-reset-password',
|
||||
element: <CompleteResetPassword />
|
||||
},
|
||||
{
|
||||
path: '/public/notes/:token',
|
||||
element: <SharedNote />
|
||||
},
|
||||
{
|
||||
path: '*',
|
||||
element: <Navigate to="/" replace />
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* Routes for users who are signed in.
|
||||
* @type {RouteObject[]}
|
||||
*/
|
||||
const signedRouter: RouteObject[] = [
|
||||
{
|
||||
path: '/',
|
||||
element: <ProtectedRoute />,
|
||||
children: [
|
||||
{
|
||||
element: <PrivateLayout />,
|
||||
children: BrowserRoutes
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/public/notes/:token',
|
||||
element: <SharedNote />
|
||||
},
|
||||
{
|
||||
path: '*',
|
||||
element: <NotFound />
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* Determines the appropriate router based on the user's authentication status.
|
||||
* @returns {Router} The configured router.
|
||||
*/
|
||||
const getBrowserRouter = () => {
|
||||
if (signed) {
|
||||
return createBrowserRouter(signedRouter);
|
||||
}
|
||||
return createBrowserRouter(notSignedRouter);
|
||||
};
|
||||
|
||||
const browserRouter = getBrowserRouter();
|
||||
|
||||
useEffect(() => {
|
||||
checkCurrentAuthUser(window.location.pathname);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
document.body.setAttribute('data-bs-theme', theme);
|
||||
localStorage.setItem('theme', theme);
|
||||
}, [theme]);
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(prev => (prev === 'light' ? 'dark' : 'light'));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-dark"
|
||||
onClick={toggleTheme}
|
||||
>
|
||||
{theme === 'dark' ? '☀ Light Mode' : '🌙 Dark Mode'}
|
||||
</button>
|
||||
|
||||
{/* Your routes or content here */}
|
||||
<RouterProvider router={browserRouter} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,28 @@
|
||||
import React from 'react';
|
||||
import { test, vi } from 'vitest';
|
||||
import App from '../App';
|
||||
import { act, render } from '@testing-library/react';
|
||||
import AuthContext from '../context/AuthContext';
|
||||
import authContextMock from './__mocks__/authContextMock';
|
||||
import SidebarContext from '../context/SidebarContext';
|
||||
|
||||
const sidebarContextMock = {
|
||||
currentPage: '/home',
|
||||
setNewPage: vi.fn()
|
||||
};
|
||||
|
||||
vi.mock('react-charts', () => ({
|
||||
Chart: ({ options }) => <div data-testid="mocked-chart">Mocked Chart</div>
|
||||
}));
|
||||
|
||||
test('Renders the app', async () => {
|
||||
await act(async () => {
|
||||
render(
|
||||
<AuthContext.Provider value={authContextMock}>
|
||||
<SidebarContext.Provider value={sidebarContextMock}>
|
||||
<App />
|
||||
</SidebarContext.Provider>
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { vi } from "vitest";
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: undefined,
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn()
|
||||
};
|
||||
|
||||
export default authContextMock;
|
||||
@@ -0,0 +1,31 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import AlertError from '../../components/AlertError';
|
||||
|
||||
describe('AlertError Component tests', () => {
|
||||
const dataTestId: string = "alert-error-msg-tests";
|
||||
const renderAlert = (message?: string) => {
|
||||
return render(
|
||||
<AlertError errorMessage={message} dataTestid={dataTestId} />
|
||||
);
|
||||
};
|
||||
|
||||
it('should display the message if error', () => {
|
||||
const errorMessage = "Oops, something went wrong";
|
||||
const { getByTestId } = renderAlert(errorMessage);
|
||||
|
||||
expect(getByTestId(dataTestId)).toBeDefined();
|
||||
});
|
||||
|
||||
// Personal notes: queryByTestId should be used to find elements
|
||||
// that possibly aren't in the document. getByTestId expect always
|
||||
// to find the element.
|
||||
it('should not display the message if no error', () => {
|
||||
const errorMessage = "";
|
||||
const { queryByTestId } = renderAlert(errorMessage);
|
||||
(errorMessage);
|
||||
|
||||
expect(queryByTestId(dataTestId)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import ContentHeader from '../../components/ContentHeader';
|
||||
|
||||
const headerProps = {
|
||||
h1TextRegular: "Title part one",
|
||||
h1TextBold: "Title part two",
|
||||
subtitle: "This is the subtitle",
|
||||
h2BlackText: "Another text part one",
|
||||
h2GreenText: "Another green text",
|
||||
isHomeComponent: false
|
||||
};
|
||||
|
||||
describe('ContentHeader test cases', () => {
|
||||
it('should render all the text elements', () => {
|
||||
const { getByText } = render(<ContentHeader {...headerProps} />);
|
||||
|
||||
expect(getByText(headerProps.h1TextRegular)).toBeDefined();
|
||||
expect(getByText(headerProps.h1TextBold)).toBeDefined();
|
||||
expect(getByText(headerProps.subtitle)).toBeDefined();
|
||||
expect(getByText(headerProps.h2BlackText)).toBeDefined();
|
||||
expect(getByText(headerProps.h2GreenText)).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render all the text elements for home', () => {
|
||||
const { getByText } = render(
|
||||
<MemoryRouter>
|
||||
<ContentHeader
|
||||
{ ...headerProps }
|
||||
isHomeComponent={true}
|
||||
newTaskI18n="New task"
|
||||
newNoteI18n="New note"
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(getByText(headerProps.h1TextRegular)).toBeDefined();
|
||||
expect(getByText(headerProps.h1TextBold)).toBeDefined();
|
||||
expect(getByText(headerProps.subtitle)).toBeDefined();
|
||||
expect(getByText(headerProps.h2BlackText)).toBeDefined();
|
||||
expect(getByText(headerProps.h2GreenText)).toBeDefined();
|
||||
|
||||
// renders only if it's the home (dashboard)
|
||||
expect(getByText("New note")).toBeDefined();
|
||||
expect(getByText("New task")).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import Header from '../../components/Header';
|
||||
import '../../i18n';
|
||||
|
||||
describe('Header component test', () => {
|
||||
it('should renders the Header with all elements', () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Header />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
const logo = screen.getByAltText('TaskNote logo');
|
||||
const homeLink = screen.getByText('Home');
|
||||
const tasksLink = screen.getByText('Tasks');
|
||||
const notesLink = screen.getByText('Notes');
|
||||
const aboutLink = screen.getByText('About');
|
||||
|
||||
expect(logo).toBeDefined();
|
||||
expect(homeLink).toBeDefined();
|
||||
expect(tasksLink).toBeDefined();
|
||||
expect(notesLink).toBeDefined();
|
||||
expect(aboutLink).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import LoginForm from '../../components/LoginForm';
|
||||
import '../../i18n';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Ricardo',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://image.com'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn()
|
||||
};
|
||||
|
||||
describe('LoginForm Component test', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
const renderFn = (prefix: string) => {
|
||||
return render(
|
||||
<BrowserRouter>
|
||||
<AuthContext.Provider value={authContextMock}>
|
||||
<LoginForm prefix={prefix} />
|
||||
</AuthContext.Provider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('should render the Login Form component correctly', () => {
|
||||
renderFn("login");
|
||||
|
||||
const loginEmailInput: HTMLInputElement = screen.getByTestId('login_email_input');
|
||||
expect(loginEmailInput).toBeDefined();
|
||||
expect(loginEmailInput.required).toBe(true);
|
||||
});
|
||||
|
||||
it('should render the Register Form component correctly', () => {
|
||||
renderFn("register");
|
||||
|
||||
const loginEmailInput: HTMLInputElement = screen.getByTestId('register_email_input');
|
||||
expect(loginEmailInput).toBeDefined();
|
||||
expect(loginEmailInput.required).toBe(true);
|
||||
});
|
||||
|
||||
it('should render the Login Form correctly for "login" prefix', () => {
|
||||
renderFn("login");
|
||||
|
||||
const emailInput = screen.getByTestId('login_email_input');
|
||||
const passwordInput = screen.getByTestId('account-password-login');
|
||||
const submitButton = screen.getByRole('button', { name: /login/i });
|
||||
|
||||
expect(emailInput).toBeDefined();
|
||||
expect(passwordInput).toBeDefined();
|
||||
expect(submitButton).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render the Register Form correctly for "register" prefix', () => {
|
||||
renderFn("register");
|
||||
|
||||
const emailInput = screen.getByTestId('register_email_input');
|
||||
const passwordInput = screen.getByTestId('account-password-login');
|
||||
const repeatPasswordInput = screen.getByTestId('account-repeat-password-register');
|
||||
const submitButton = screen.getByRole('button', { name: /create account/i });
|
||||
|
||||
expect(emailInput).toBeDefined();
|
||||
expect(passwordInput).toBeDefined();
|
||||
expect(repeatPasswordInput).toBeDefined();
|
||||
expect(submitButton).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render the Reset Password Form correctly for "reset" prefix', () => {
|
||||
renderFn("reset");
|
||||
|
||||
const emailInput = screen.getByTestId('reset_email_input');
|
||||
const submitButton = screen.getByRole('button', { name: /Send confirmation email/i });
|
||||
|
||||
expect(emailInput).toBeDefined();
|
||||
expect(submitButton).toBeDefined();
|
||||
});
|
||||
|
||||
it('should display error message when form is invalid', () => {
|
||||
renderFn("login");
|
||||
|
||||
const submitButton = screen.getByRole('button', { name: /login/i });
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
const errorMessage = screen.getByText(/please fill in your username and password/i);
|
||||
expect(errorMessage).toBeDefined();
|
||||
});
|
||||
|
||||
it('should display success message for "register" prefix after successful submission', async () => {
|
||||
renderFn("register");
|
||||
|
||||
const emailInput = screen.getByTestId('register_email_input');
|
||||
const passwordInput = screen.getByTestId('account-password-login');
|
||||
const repeatPasswordInput = screen.getByTestId('account-repeat-password-register');
|
||||
const submitButton = screen.getByRole('button', { name: /create account/i });
|
||||
|
||||
fireEvent.change(emailInput, { target: { value: 'test@example.com' } });
|
||||
fireEvent.change(passwordInput, { target: { value: 'password123' } });
|
||||
fireEvent.change(repeatPasswordInput, { target: { value: 'password123' } });
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
const successMessage = await screen.findByText(/please confirm your email before proceeding/i);
|
||||
expect(successMessage).toBeDefined();
|
||||
});
|
||||
|
||||
it('should disable resend button and show countdown for "register" prefix', async () => {
|
||||
renderFn("register");
|
||||
|
||||
const emailInput = screen.getByTestId('register_email_input');
|
||||
const passwordInput = screen.getByTestId('account-password-login');
|
||||
const repeatPasswordInput = screen.getByTestId('account-repeat-password-register');
|
||||
const submitButton = screen.getByRole('button', { name: /create account/i });
|
||||
|
||||
fireEvent.change(emailInput, { target: { value: 'test@example.com' } });
|
||||
fireEvent.change(passwordInput, { target: { value: 'password123' } });
|
||||
fireEvent.change(repeatPasswordInput, { target: { value: 'password123' } });
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
const resendButton = screen.queryByRole('button', { name: /resend confirmation email/i }) as HTMLButtonElement;
|
||||
expect(resendButton).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import React from 'react';
|
||||
import { describe, vi, it, expect, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';
|
||||
import ModalMarkdown from '../../components/ModalMarkdown';
|
||||
|
||||
describe('ModalMarkdown Component', () => {
|
||||
const props = {
|
||||
show: true,
|
||||
title: 'Test Title',
|
||||
markdownText: '# Test Markdown',
|
||||
onHide: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
Object.assign(navigator, {
|
||||
clipboard: {
|
||||
writeText: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should render the modal with the correct title and markdown text', () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
expect(screen.getByTestId('modal-header-title').innerHTML).toBe('Test Title');
|
||||
expect(screen.getByText('Test Markdown')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call onHide when the close button is clicked', () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
fireEvent.click(screen.getByText('Close'));
|
||||
expect(props.onHide).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not render the modal when show is false', () => {
|
||||
render(<ModalMarkdown {...props} show={false} />);
|
||||
|
||||
expect(screen.queryByTestId('modal-header-title')).toBeNull();
|
||||
});
|
||||
|
||||
it('should render "No title" when title is an empty string', () => {
|
||||
render(<ModalMarkdown {...props} title="" />);
|
||||
|
||||
expect(screen.getByTestId('modal-header-title').innerHTML).toBe('No title');
|
||||
});
|
||||
|
||||
it('should show Source and Copy buttons', () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
expect(screen.getByTestId('modal-source-button')).toBeDefined();
|
||||
expect(screen.getByTestId('modal-copy-button')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should toggle to source view when Source button is clicked', () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
expect(screen.queryByTestId('markdown-source-view')).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByTestId('modal-source-button'));
|
||||
|
||||
expect(screen.getByTestId('markdown-source-view')).toBeDefined();
|
||||
expect(screen.getByTestId('markdown-source-view').textContent).toBe('# Test Markdown');
|
||||
});
|
||||
|
||||
it('should toggle back to rendered view when Source button is clicked again', () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('modal-source-button'));
|
||||
expect(screen.getByTestId('markdown-source-view')).toBeDefined();
|
||||
|
||||
fireEvent.click(screen.getByTestId('modal-source-button'));
|
||||
expect(screen.queryByTestId('markdown-source-view')).toBeNull();
|
||||
});
|
||||
|
||||
it('should call clipboard writeText with markdownText when Copy button is clicked', async () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByTestId('modal-copy-button'));
|
||||
});
|
||||
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('# Test Markdown');
|
||||
});
|
||||
|
||||
it('should show "Copied!" text after Copy button is clicked', async () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByTestId('modal-copy-button'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('modal-copy-button').textContent).toBe('Copied!');
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset source view state when modal is closed', () => {
|
||||
render(<ModalMarkdown {...props} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('modal-source-button'));
|
||||
expect(screen.getByTestId('markdown-source-view')).toBeDefined();
|
||||
|
||||
fireEvent.click(screen.getByText('Close'));
|
||||
expect(props.onHide).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import NoteTitle from '../../components/NoteTitle';
|
||||
|
||||
describe('NoteTitle test cases', () => {
|
||||
it('should render the note title', () => {
|
||||
const { getByText } = render(<NoteTitle title="Test Title" noteUrl={null} />)
|
||||
|
||||
expect(getByText('Test Title')).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
import { render, fireEvent } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import Sidebar from '../../components/Sidebar';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
import SidebarContext from '../../context/SidebarContext';
|
||||
import i18n from '../../i18n';
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Ricardo',
|
||||
email: 'ricardo@campos.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://url.com'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn(),
|
||||
};
|
||||
|
||||
const sidebarContextMock = {
|
||||
currentPage: '/home',
|
||||
setNewPage: vi.fn()
|
||||
};
|
||||
|
||||
describe('Sidebar Component', () => {
|
||||
const renderSidebar = () => {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<AuthContext.Provider value={authContextMock}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<SidebarContext.Provider value={sidebarContextMock}>
|
||||
<Sidebar isMobileOpen={false} setIsMobileOpen={vi.fn()} />
|
||||
</SidebarContext.Provider>
|
||||
</I18nextProvider>
|
||||
</AuthContext.Provider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('should render the Sidebar component', () => {
|
||||
const { getByText } = renderSidebar();
|
||||
expect(getByText('Ricardo')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call signOut when logout is clicked', () => {
|
||||
const { getByText } = renderSidebar();
|
||||
fireEvent.click(getByText('Logout'));
|
||||
expect(authContextMock.signOut).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should highlight the selected menu item', () => {
|
||||
const { getByText } = renderSidebar();
|
||||
fireEvent.click(getByText('Home'));
|
||||
const dashboardElement = getByText('Home').closest('.sidebar-nav');
|
||||
expect(dashboardElement).not.toBeNull();
|
||||
expect(dashboardElement!.classList.contains('selected')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import TaskTag from '../../components/TaskTag';
|
||||
|
||||
describe('TaskTag Component', () => {
|
||||
it('should render the TaskTag component with provided tag and last update', () => {
|
||||
const { getByText } = render(<TaskTag tag="important" lastUpdate="2025-02-20" />);
|
||||
expect(getByText('#important')).toBeDefined();
|
||||
expect(getByText('2025-02-20')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render the TaskTag component with default tag when no tag is provided', () => {
|
||||
const { getByText } = render(<TaskTag lastUpdate="2025-02-20" />);
|
||||
expect(getByText('#untagged')).toBeDefined();
|
||||
expect(getByText('2025-02-20')).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import TaskTimeLeft from '../../components/TaskTimeLeft';
|
||||
|
||||
describe('TaskTimeLeft Component', () => {
|
||||
const renderComponent = (done: boolean) => {
|
||||
return render(
|
||||
<TaskTimeLeft
|
||||
text="2 days left"
|
||||
done={done}
|
||||
tooltip="2025-03-20"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
it('should render the TaskTimeLeft component with text when task is not done', () => {
|
||||
const { getByText } = renderComponent(false);
|
||||
expect(getByText('2 days left')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should not render the TaskTimeLeft component when task is done', () => {
|
||||
const { queryByText } = renderComponent(true);
|
||||
expect(queryByText('2 days left')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import TaskTitle from '../../components/TaskTitle';
|
||||
|
||||
describe('TaskTitle Component', () => {
|
||||
it('should render the TaskTitle component with high priority and done', () => {
|
||||
const { getByText, container } = render(<TaskTitle title="Test Task" highPriority={true} done={true} />);
|
||||
expect(container.querySelector('.task-title-icon')).toBeDefined();
|
||||
expect(container.querySelector('.text-strike')).toBeDefined();
|
||||
expect(getByText('Test Task')).toBeDefined();
|
||||
expect(container.querySelector('svg')).toBeDefined(); // Check2Circle icon
|
||||
});
|
||||
|
||||
it('should render the TaskTitle component with high priority and not done', () => {
|
||||
const { getByText, container } = render(<TaskTitle title="Test Task" highPriority={true} done={false} />);
|
||||
expect(container.querySelector('.task-title-icon')).toBeDefined();
|
||||
expect(container.querySelector('.text-strike')).toBeNull();
|
||||
expect(getByText('Test Task')).toBeDefined();
|
||||
expect(container.querySelector('svg')).toBeDefined(); // Bell icon
|
||||
});
|
||||
|
||||
it('should render the TaskTitle component with not high priority and done', () => {
|
||||
const { getByText, container } = render(<TaskTitle title="Test Task" highPriority={false} done={true} />);
|
||||
expect(container.querySelector('.task-title-icon')).toBeDefined();
|
||||
expect(container.querySelector('.text-strike')).toBeDefined();
|
||||
expect(getByText('Test Task')).toBeDefined();
|
||||
expect(container.querySelector('svg')).toBeDefined(); // Check2Circle icon
|
||||
});
|
||||
|
||||
it('should render the TaskTitle component with not high priority and not done', () => {
|
||||
const { getByText, container } = render(<TaskTitle title="Test Task" highPriority={false} done={false} />);
|
||||
expect(container.querySelector('.task-title-icon')).toBeDefined();
|
||||
expect(container.querySelector('.text-strike')).toBeNull();
|
||||
expect(getByText('Test Task')).toBeDefined();
|
||||
expect(container.querySelector('svg')).toBeNull(); // No icon
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
// AuthProvider.test.tsx
|
||||
import React, { useContext } from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, act, waitFor, cleanup } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import AuthProvider from '../../context/AuthProvider';
|
||||
import AuthContext, { AuthContextData } from '../../context/AuthContext';
|
||||
import api from '../../api-service/api';
|
||||
import { API_TOKEN, USER_DATA } from '../../app-constants/app-constants';
|
||||
|
||||
// Mock the API service methods.
|
||||
vi.mock('../../api-service/api');
|
||||
|
||||
// Create a helper component to consume AuthContext for testing.
|
||||
const ConsumerComponent: React.FC = () => {
|
||||
const {
|
||||
signed,
|
||||
user,
|
||||
signIn,
|
||||
register,
|
||||
signOut,
|
||||
updateUser,
|
||||
checkCurrentAuthUser
|
||||
} = useContext<AuthContextData>(AuthContext);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="signed">{signed ? 'true' : 'false'}</div>
|
||||
<div data-testid="user">{user ? user.name : 'none'}</div>
|
||||
<button
|
||||
data-testid="signIn"
|
||||
onClick={async() => {
|
||||
await signIn('test@example.com', 'password123');
|
||||
}}
|
||||
>
|
||||
Sign In
|
||||
</button>
|
||||
<button
|
||||
data-testid="register"
|
||||
onClick={() => {
|
||||
register('new@example.com', 'password123', 'password123');
|
||||
}}
|
||||
>
|
||||
Register
|
||||
</button>
|
||||
<button
|
||||
data-testid="sign-out-btn"
|
||||
onClick={() => {
|
||||
signOut();
|
||||
}}
|
||||
>
|
||||
Sign Out
|
||||
</button>
|
||||
<button
|
||||
data-testid="updateUser"
|
||||
onClick={() => {
|
||||
updateUser({
|
||||
userId: 1,
|
||||
name: 'Updated User',
|
||||
email: 'updated@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://dummyimage.com'
|
||||
});
|
||||
}}
|
||||
>
|
||||
Update User
|
||||
</button>
|
||||
<button
|
||||
data-testid="checkCurrentAuthUser"
|
||||
onClick={() => {
|
||||
checkCurrentAuthUser('/some-path');
|
||||
}}
|
||||
>
|
||||
Check Current Auth User
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
describe('AuthProvider', () => {
|
||||
// Reset DOM and mocks for each test.
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('should render the default context values', () => {
|
||||
const { getByTestId } = render(
|
||||
<AuthProvider>
|
||||
<ConsumerComponent />
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
expect(getByTestId('signed').textContent).toBe('false');
|
||||
expect(getByTestId('user').textContent).toBe('none');
|
||||
});
|
||||
|
||||
it('should sign in a user successfully', async () => {
|
||||
// Create a fake sign-in response.
|
||||
const fakeResponse = {
|
||||
userId: '123',
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
token: 'dummy-token',
|
||||
gravatarImageUrl: 'http://dummyimage.com'
|
||||
};
|
||||
|
||||
vi.spyOn(api, 'postJSON').mockResolvedValue(fakeResponse);
|
||||
|
||||
const { getByTestId } = render(
|
||||
<AuthProvider>
|
||||
<ConsumerComponent />
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
userEvent.click(getByTestId('signIn'));
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getByTestId('signed').textContent).toBe('true')
|
||||
);
|
||||
expect(getByTestId('user').textContent).toBe('Test User');
|
||||
// LocalStorage should have API_TOKEN and USER_DATA set.
|
||||
expect(localStorage.getItem(API_TOKEN)).toBe('dummy-token');
|
||||
expect(localStorage.getItem(USER_DATA)).not.toBeNull();
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('should sign out a user', async () => {
|
||||
// Pre-populate localStorage to simulate a signed-in state.
|
||||
localStorage.setItem(API_TOKEN, 'dummy-token');
|
||||
localStorage.setItem(
|
||||
USER_DATA,
|
||||
JSON.stringify({
|
||||
userId: '123',
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://dummyimage.com'
|
||||
})
|
||||
);
|
||||
|
||||
const fakeResponse = {
|
||||
userId: '123',
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
token: 'dummy-token',
|
||||
gravatarImageUrl: 'http://dummyimage.com'
|
||||
};
|
||||
|
||||
vi.spyOn(api, 'postJSON').mockResolvedValue(fakeResponse);
|
||||
|
||||
const { getByTestId } = render(
|
||||
<AuthProvider>
|
||||
<ConsumerComponent />
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
// Make sure that the context initially renders with the signed user by triggering a signIn.
|
||||
await act(async () => {
|
||||
userEvent.click(getByTestId('signIn'));
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getByTestId('signed').textContent).toBe('true')
|
||||
);
|
||||
|
||||
// Now sign out
|
||||
await act(async () => {
|
||||
userEvent.click(getByTestId('sign-out-btn'));
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getByTestId('signed').textContent).toBe('false')
|
||||
);
|
||||
expect(getByTestId('user').textContent).toBe('none');
|
||||
// LocalStorage items should be removed.
|
||||
expect(localStorage.getItem(API_TOKEN)).toBeNull();
|
||||
expect(localStorage.getItem(USER_DATA)).toBeNull();
|
||||
});
|
||||
|
||||
it('should update user in context and localStorage', async () => {
|
||||
const { getByTestId } = render(
|
||||
<AuthProvider>
|
||||
<ConsumerComponent />
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
userEvent.click(getByTestId('updateUser'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
act(() => {
|
||||
expect(getByTestId('user').textContent).toBe('Updated User')
|
||||
})
|
||||
const savedUser = localStorage.getItem(USER_DATA);
|
||||
expect(savedUser).not.toBeNull();
|
||||
|
||||
if (savedUser) {
|
||||
const parsedUser = JSON.parse(savedUser);
|
||||
expect(parsedUser.name).toBe('Updated User');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should call fetchCurrentSession when checking current auth user', async () => {
|
||||
const fakeResponse = {
|
||||
token: 'refresh-token',
|
||||
userId: '789',
|
||||
name: 'Refreshed User',
|
||||
email: 'refreshed@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
gravatarImageUrl: 'http://dummyimage.com'
|
||||
};
|
||||
|
||||
vi.spyOn(api, 'getJSON').mockResolvedValue(fakeResponse);
|
||||
|
||||
// Store API_TOKEN so that fetchCurrentSession runs the refresh logic.
|
||||
localStorage.setItem(API_TOKEN, 'dummy');
|
||||
|
||||
const user = userEvent.setup();
|
||||
|
||||
let getByTestIdFunction;
|
||||
await act(async () => {
|
||||
const { getByTestId } = render(
|
||||
<AuthProvider>
|
||||
<ConsumerComponent />
|
||||
</AuthProvider>
|
||||
);
|
||||
getByTestIdFunction = getByTestId;
|
||||
});
|
||||
|
||||
// Wait for any initial renders to complete
|
||||
await waitFor(() => expect(getByTestIdFunction('checkCurrentAuthUser')).toBeDefined());
|
||||
|
||||
await user.click(getByTestIdFunction('checkCurrentAuthUser'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(localStorage.getItem(API_TOKEN)).toBe('refresh-token')
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// AuthProvider.test.tsx
|
||||
import React, { useContext } from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, act, waitFor, cleanup } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import SidebarProvider from '../../context/SidebarProvider';
|
||||
import SidebarContext, { SidebarContextData } from '../../context/SidebarContext';
|
||||
|
||||
// Create a helper component to consume AuthContext for testing.
|
||||
const ConsumerComponent: React.FC = () => {
|
||||
const {
|
||||
currentPage,
|
||||
setNewPage
|
||||
} = useContext<SidebarContextData>(SidebarContext);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="page">{currentPage}</div>
|
||||
<button
|
||||
data-testid="setPage"
|
||||
onClick={() => {
|
||||
setNewPage('/another');
|
||||
}}
|
||||
>
|
||||
Change page
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
describe('SidebarProvider', () => {
|
||||
// Reset DOM and mocks for each test.
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('should render the default context values', () => {
|
||||
const { getByTestId } = render(
|
||||
<SidebarProvider>
|
||||
<ConsumerComponent />
|
||||
</SidebarProvider>
|
||||
);
|
||||
|
||||
expect(getByTestId('page').textContent).toBe('/home');
|
||||
});
|
||||
|
||||
it('should set a new page after click', async () => {
|
||||
const { getByTestId } = render(
|
||||
<SidebarProvider>
|
||||
<ConsumerComponent />
|
||||
</SidebarProvider>
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
userEvent.click(getByTestId('setPage'));
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getByTestId('page').textContent).toBe('/another')
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, beforeEach } from 'vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
// runs a cleanup after each test case (e.g. clearing jsdom)
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
window.matchMedia = window.matchMedia || function() {
|
||||
return {
|
||||
matches: false,
|
||||
addListener: function() {},
|
||||
removeListener: function() {}
|
||||
};
|
||||
};
|
||||
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
window.ResizeObserver = window.ResizeObserver || ResizeObserver;
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([]),
|
||||
text: vi.fn().mockResolvedValue(''),
|
||||
blob: vi.fn().mockResolvedValue(new Blob()),
|
||||
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(0)),
|
||||
headers: new Headers(),
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
|
||||
// Reset the fetch mock with default successful response
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([]),
|
||||
text: vi.fn().mockResolvedValue(''),
|
||||
blob: vi.fn().mockResolvedValue(new Blob()),
|
||||
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(0)),
|
||||
headers: new Headers(),
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { translateTimeMessage, translateServerResponse } from '../../utils/TranslatorUtils';
|
||||
import { serverResponses } from '../../constants/serverResponses';
|
||||
|
||||
describe('Portuguese Utils unit tests', () => {
|
||||
it('should translate all time ago messages to pt_br', () => {
|
||||
expect(translateTimeMessage('2 years ago', 'pt_br')).toBe('2 anos atrás');
|
||||
expect(translateTimeMessage('1 year ago', 'pt_br')).toBe('1 ano atrás');
|
||||
expect(translateTimeMessage('2 months ago', 'pt_br')).toBe('2 meses atrás');
|
||||
expect(translateTimeMessage('1 month ago', 'pt_br')).toBe('1 mês atrás');
|
||||
expect(translateTimeMessage('2 days ago', 'pt_br')).toBe('2 dias atrás');
|
||||
expect(translateTimeMessage('1 day ago', 'pt_br')).toBe('1 dia atrás');
|
||||
expect(translateTimeMessage('2 hours ago', 'pt_br')).toBe('2 horas atrás');
|
||||
expect(translateTimeMessage('1 hour ago', 'pt_br')).toBe('1 hora atrás');
|
||||
expect(translateTimeMessage('2 minutes ago', 'pt_br')).toBe('2 minutos atrás');
|
||||
expect(translateTimeMessage('1 minute ago', 'pt_br')).toBe('1 minuto atrás');
|
||||
expect(translateTimeMessage('2 seconds ago', 'pt_br')).toBe('2 segundos atrás');
|
||||
expect(translateTimeMessage('1 second ago', 'pt_br')).toBe('1 segundo atrás');
|
||||
expect(translateTimeMessage('Moments ago', 'pt_br')).toBe('Momentos atrás');
|
||||
expect(translateTimeMessage('lala', 'pt_br')).toBe('lala');
|
||||
expect(translateTimeMessage('null', 'pt_br')).toBe('null');
|
||||
});
|
||||
|
||||
it('should translate all time left messages to pt_br', () => {
|
||||
expect(translateTimeMessage('2 years left', 'pt_br')).toBe('2 anos restantes');
|
||||
expect(translateTimeMessage('1 year left', 'pt_br')).toBe('1 ano restante');
|
||||
expect(translateTimeMessage('2 months left', 'pt_br')).toBe('2 meses restantes');
|
||||
expect(translateTimeMessage('1 month left', 'pt_br')).toBe('1 mês restante');
|
||||
expect(translateTimeMessage('2 days left', 'pt_br')).toBe('2 dias restantes');
|
||||
expect(translateTimeMessage('1 day left', 'pt_br')).toBe('1 dia restante');
|
||||
expect(translateTimeMessage('lala', 'pt_br')).toBe('lala');
|
||||
expect(translateTimeMessage('null', 'pt_br')).toBe('null');
|
||||
});
|
||||
|
||||
it('should translate all server responses to pt_br', () => {
|
||||
const keys: string[] = Object.keys(serverResponses);
|
||||
|
||||
expect(translateServerResponse(keys[0], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 8 letras');
|
||||
expect(translateServerResponse(keys[1], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 8 letras, 1 caracter especial');
|
||||
expect(translateServerResponse(keys[2], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 8 letras, 1 número, 1 caracter especial');
|
||||
expect(translateServerResponse(keys[3], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 8 letras, 1 maiúscula, 1 número, 1 caracter especial');
|
||||
expect(translateServerResponse(keys[4], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 8 letras, 1 maiúscula, 1 caracter especial');
|
||||
expect(translateServerResponse(keys[5], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 1 maiúscula, 1 caracter especial');
|
||||
expect(translateServerResponse(keys[6], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 1 caracter especial');
|
||||
expect(translateServerResponse(keys[7], 'pt_br')).toBe('Senha fraca: Senha deve possuir pelo menos 1 número');
|
||||
expect(translateServerResponse(keys[8], 'pt_br')).toBe('E-mail já cadastrado!');
|
||||
expect(translateServerResponse(keys[9], 'pt_br')).toBe('Proibido! Acesso negado');
|
||||
expect(translateServerResponse(keys[10], 'pt_br')).toBe('Se o endereço de e-mail informado estiver associado a uma conta, você receberá um link para resetar a senha em breve.');
|
||||
expect(translateServerResponse(keys[11], 'pt_br')).toBe('Erro Interno do Servidor!');
|
||||
expect(translateServerResponse(keys[12], 'pt_br')).toBe('Limite máximo de tentativas atingido. Por favor aguarde 30 minutos');
|
||||
expect(translateServerResponse(keys[13], 'pt_br')).toBe('Erro de rede ao tentar obter recursos.');
|
||||
expect(translateServerResponse(keys[14], 'pt_br')).toBe('Por favor, confirme seu e-mail antes de continuar');
|
||||
expect(translateServerResponse(keys[15], 'pt_br')).toBe('Por favor, preencha todos os campos');
|
||||
expect(translateServerResponse(keys[16], 'pt_br')).toBe('Por favor, informe seu e-mail');
|
||||
expect(translateServerResponse(keys[17], 'pt_br')).toBe('Por favor, informe seu e-mail e senha!');
|
||||
expect(translateServerResponse(keys[18], 'pt_br')).toBe('Por favor, informe a nova senha');
|
||||
expect(translateServerResponse(keys[19], 'pt_br')).toBe('Por favor, digite pelo menos 3 letras');
|
||||
expect(translateServerResponse(keys[20], 'pt_br')).toBe('O tamanho máximo do texto é 2000');
|
||||
expect(translateServerResponse(keys[21], 'pt_br')).toBe('Erro desconhecido');
|
||||
expect(translateServerResponse(keys[22], 'pt_br')).toBe('Identificação incorreta ou faltando');
|
||||
expect(translateServerResponse(keys[23], 'pt_br')).toBe('Informação errada ou incompleta!');
|
||||
expect(translateServerResponse(keys[24], 'pt_br')).toBe('E-mail ou senha inválidos!');
|
||||
expect(translateServerResponse(keys[25], 'pt_br')).toBe('Nada para atualizar!');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { translateTimeMessage, translateServerResponse } from '../../utils/TranslatorUtils';
|
||||
import { serverResponses } from '../../constants/serverResponses';
|
||||
|
||||
describe('Russian Utils unit tests', () => {
|
||||
it('should translate all time ago messages to ru', () => {
|
||||
expect(translateTimeMessage('2 years ago', 'ru')).toBe('2 года назад');
|
||||
expect(translateTimeMessage('1 year ago', 'ru')).toBe('1 год назад');
|
||||
expect(translateTimeMessage('2 months ago', 'ru')).toBe('2 месяца назад');
|
||||
expect(translateTimeMessage('1 month ago', 'ru')).toBe('1 месяц назад');
|
||||
expect(translateTimeMessage('2 days ago', 'ru')).toBe('2 дня назад');
|
||||
expect(translateTimeMessage('1 day ago', 'ru')).toBe('1 день назад');
|
||||
expect(translateTimeMessage('2 hours ago', 'ru')).toBe('2 часа назад');
|
||||
expect(translateTimeMessage('1 hour ago', 'ru')).toBe('1 час назад');
|
||||
expect(translateTimeMessage('2 minutes ago', 'ru')).toBe('2 минуты назад');
|
||||
expect(translateTimeMessage('1 minute ago', 'ru')).toBe('1 минуту назад');
|
||||
expect(translateTimeMessage('2 seconds ago', 'ru')).toBe('2 секунды назад');
|
||||
expect(translateTimeMessage('1 second ago', 'ru')).toBe('1 секунду назад');
|
||||
expect(translateTimeMessage('Moments ago', 'ru')).toBe('Несколько минут назад');
|
||||
expect(translateTimeMessage('lala', 'ru')).toBe('lala');
|
||||
expect(translateTimeMessage('null', 'ru')).toBe('null');
|
||||
});
|
||||
|
||||
it('should translate all time left messages to ru', () => {
|
||||
expect(translateTimeMessage('1 year left', 'ru')).toBe('Остался 1 год');
|
||||
expect(translateTimeMessage('2 years left', 'ru')).toBe('осталось 2 года');
|
||||
expect(translateTimeMessage('3 years left', 'ru')).toBe('осталось 3 года');
|
||||
expect(translateTimeMessage('4 years left', 'ru')).toBe('осталось 4 года');
|
||||
expect(translateTimeMessage('5 years left', 'ru')).toBe('осталось 5 лет');
|
||||
expect(translateTimeMessage('6 years left', 'ru')).toBe('осталось 6 лет');
|
||||
expect(translateTimeMessage('7 years left', 'ru')).toBe('осталось 7 лет');
|
||||
expect(translateTimeMessage('8 years left', 'ru')).toBe('осталось 8 лет');
|
||||
expect(translateTimeMessage('9 years left', 'ru')).toBe('осталось 9 лет');
|
||||
expect(translateTimeMessage('1 month left', 'ru')).toBe('Остался 1 месяц');
|
||||
expect(translateTimeMessage('2 months left', 'ru')).toBe('осталось 2 месяца');
|
||||
expect(translateTimeMessage('3 months left', 'ru')).toBe('осталось 3 месяца');
|
||||
expect(translateTimeMessage('4 months left', 'ru')).toBe('осталось 4 месяца');
|
||||
expect(translateTimeMessage('5 months left', 'ru')).toBe('осталось 5 месяцев');
|
||||
expect(translateTimeMessage('6 months left', 'ru')).toBe('осталось 6 месяцев');
|
||||
expect(translateTimeMessage('7 months left', 'ru')).toBe('осталось 7 месяцев');
|
||||
expect(translateTimeMessage('8 months left', 'ru')).toBe('осталось 8 месяцев');
|
||||
expect(translateTimeMessage('9 months left', 'ru')).toBe('осталось 9 месяцев');
|
||||
expect(translateTimeMessage('1 day left', 'ru')).toBe('Остался 1 день');
|
||||
expect(translateTimeMessage('2 days left', 'ru')).toBe('осталось 2 дня');
|
||||
expect(translateTimeMessage('3 days left', 'ru')).toBe('осталось 3 дня');
|
||||
expect(translateTimeMessage('4 days left', 'ru')).toBe('осталось 4 дня');
|
||||
expect(translateTimeMessage('5 days left', 'ru')).toBe('осталось 5 дней');
|
||||
expect(translateTimeMessage('6 days left', 'ru')).toBe('осталось 6 дней');
|
||||
expect(translateTimeMessage('7 days left', 'ru')).toBe('осталось 7 дней');
|
||||
expect(translateTimeMessage('8 days left', 'ru')).toBe('осталось 8 дней');
|
||||
expect(translateTimeMessage('9 days left', 'ru')).toBe('осталось 9 дней');
|
||||
expect(translateTimeMessage('lala', 'ru')).toBe('lala');
|
||||
expect(translateTimeMessage('null', 'ru')).toBe('null');
|
||||
});
|
||||
|
||||
it('should translate all server responses to ru', () => {
|
||||
const keys: string[] = Object.keys(serverResponses);
|
||||
|
||||
expect(translateServerResponse(keys[0], 'ru')).toBe('Неправильный пароль: Пароль должен содержать не менее 8 символов.');
|
||||
expect(translateServerResponse(keys[1], 'ru')).toBe('Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 специальный символ.');
|
||||
expect(translateServerResponse(keys[2], 'ru')).toBe('Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 цифру, 1 специальный символ.');
|
||||
expect(translateServerResponse(keys[3], 'ru')).toBe('Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 заглавную букву, 1 цифру, 1 специальный символ.');
|
||||
expect(translateServerResponse(keys[4], 'ru')).toBe('Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 заглавную букву, 1 специальный символ.');
|
||||
expect(translateServerResponse(keys[5], 'ru')).toBe('Неправильный пароль: Пароль должен содержать как минимум 1 заглавную букву и 1 специальный символ.');
|
||||
expect(translateServerResponse(keys[6], 'ru')).toBe('Неправильный пароль: Пароль должен содержать хотя бы 1 специальный символ.');
|
||||
expect(translateServerResponse(keys[7], 'ru')).toBe('Неправильный пароль: Пароль должен содержать не менее 1 цифры.');
|
||||
expect(translateServerResponse(keys[8], 'ru')).toBe('Электронная почта уже используется!');
|
||||
expect(translateServerResponse(keys[9], 'ru')).toBe('Доступ запрещен!');
|
||||
expect(translateServerResponse(keys[10], 'ru')).toBe('Если введенный вами адрес электронной почты связан с учетной записью, вы вскоре получите ссылку для сброса пароля.');
|
||||
expect(translateServerResponse(keys[11], 'ru')).toBe('Внутренняя ошибка сервера!');
|
||||
expect(translateServerResponse(keys[12], 'ru')).toBe('Достигнут максимальный лимит попыток входа. Пожалуйста, подождите 30 минут');
|
||||
expect(translateServerResponse(keys[13], 'ru')).toBe('Ошибка сети при попытке получить ресурс.');
|
||||
expect(translateServerResponse(keys[14], 'ru')).toBe('Пожалуйста, подтвердите свой адрес электронной почты, прежде чем продолжить');
|
||||
expect(translateServerResponse(keys[15], 'ru')).toBe('Пожалуйста, заполните все поля');
|
||||
expect(translateServerResponse(keys[16], 'ru')).toBe('Пожалуйста, введите свой адрес электронной почты');
|
||||
expect(translateServerResponse(keys[17], 'ru')).toBe('Пожалуйста, введите свое имя пользователя и пароль!');
|
||||
expect(translateServerResponse(keys[18], 'ru')).toBe('Пожалуйста, введите новый пароль');
|
||||
expect(translateServerResponse(keys[19], 'ru')).toBe('Пожалуйста, введите не менее 3 символов');
|
||||
expect(translateServerResponse(keys[20], 'ru')).toBe('Максимальная длина текста — 2000 символов.');
|
||||
expect(translateServerResponse(keys[21], 'ru')).toBe('Неизвестная ошибка');
|
||||
expect(translateServerResponse(keys[22], 'ru')).toBe('Неправильная или отсутствующая идентификация');
|
||||
expect(translateServerResponse(keys[23], 'ru')).toBe('Неверная или отсутствующая информация!');
|
||||
expect(translateServerResponse(keys[24], 'ru')).toBe('Неправильный пользователь или пароль');
|
||||
expect(translateServerResponse(keys[25], 'ru')).toBe('Нечего обновлять!');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { translateTimeMessage, translateServerResponse } from '../../utils/TranslatorUtils';
|
||||
import { serverResponses } from '../../constants/serverResponses';
|
||||
|
||||
describe('Spanish Utils unit tests', () => {
|
||||
it('should translate all time ago messages to es', () => {
|
||||
expect(translateTimeMessage('2 years ago', 'es')).toBe('Hace 2 años');
|
||||
expect(translateTimeMessage('1 year ago', 'es')).toBe('Hace 1 año');
|
||||
expect(translateTimeMessage('2 months ago', 'es')).toBe('Hace 2 meses');
|
||||
expect(translateTimeMessage('1 month ago', 'es')).toBe('Hace 1 mes');
|
||||
expect(translateTimeMessage('2 days ago', 'es')).toBe('Hace 2 días');
|
||||
expect(translateTimeMessage('1 day ago', 'es')).toBe('Hace 1 día');
|
||||
expect(translateTimeMessage('2 hours ago', 'es')).toBe('Hace 2 horas');
|
||||
expect(translateTimeMessage('1 hour ago', 'es')).toBe('Hace 1 hora');
|
||||
expect(translateTimeMessage('2 minutes ago', 'es')).toBe('Hace 2 minutos');
|
||||
expect(translateTimeMessage('1 minute ago', 'es')).toBe('Hace 1 minuto');
|
||||
expect(translateTimeMessage('2 seconds ago', 'es')).toBe('Hace 2 segundos');
|
||||
expect(translateTimeMessage('1 second ago', 'es')).toBe('Hace 1 segundo');
|
||||
expect(translateTimeMessage('Moments ago', 'es')).toBe('Hace momentos');
|
||||
expect(translateTimeMessage('lala', 'es')).toBe('lala');
|
||||
expect(translateTimeMessage('null', 'es')).toBe('null');
|
||||
});
|
||||
|
||||
it('should translate all time left messages to es', () => {
|
||||
expect(translateTimeMessage('2 years left', 'es')).toBe('Faltan 2 años');
|
||||
expect(translateTimeMessage('1 year left', 'es')).toBe('Falta 1 año');
|
||||
expect(translateTimeMessage('2 months left', 'es')).toBe('Faltan 2 meses');
|
||||
expect(translateTimeMessage('1 month left', 'es')).toBe('Falta 1 mes');
|
||||
expect(translateTimeMessage('2 days left', 'es')).toBe('Faltan 2 días');
|
||||
expect(translateTimeMessage('1 day left', 'es')).toBe('Falta 1 día');
|
||||
expect(translateTimeMessage('lala', 'es')).toBe('lala');
|
||||
expect(translateTimeMessage('null', 'es')).toBe('null');
|
||||
});
|
||||
|
||||
it('should translate all server responses to es', () => {
|
||||
const keys: string[] = Object.keys(serverResponses);
|
||||
|
||||
expect(translateServerResponse(keys[0], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 8 caracteres');
|
||||
expect(translateServerResponse(keys[1], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 carácter especial');
|
||||
expect(translateServerResponse(keys[2], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 número, 1 carácter especial');
|
||||
expect(translateServerResponse(keys[3], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 mayúscula, 1 número, 1 carácter especial');
|
||||
expect(translateServerResponse(keys[4], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 mayúscula y 1 carácter especial');
|
||||
expect(translateServerResponse(keys[5], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 1 mayúscula y 1 carácter especial');
|
||||
expect(translateServerResponse(keys[6], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 1 carácter especial');
|
||||
expect(translateServerResponse(keys[7], 'es')).toBe('Contraseña inválida: La contraseña debe tener al menos 1 número');
|
||||
expect(translateServerResponse(keys[8], 'es')).toBe('¡El correo ya está registrado!');
|
||||
expect(translateServerResponse(keys[9], 'es')).toBe('¡Prohibido! Acceso denegado');
|
||||
expect(translateServerResponse(keys[10], 'es')).toBe('Si la dirección de correo electrónico ingresada está asociada a una cuenta, recibirá un enlace para restablecer su contraseña en breve.');
|
||||
expect(translateServerResponse(keys[11], 'es')).toBe('¡Error interno del servidor!');
|
||||
expect(translateServerResponse(keys[12], 'es')).toBe('Has alcanzado el límite máximo de intentos de inicio de sesión. Por favor, espera 30 minutos');
|
||||
expect(translateServerResponse(keys[13], 'es')).toBe('Error de red al intentar obtener el recurso.');
|
||||
expect(translateServerResponse(keys[14], 'es')).toBe('Por favor, confirme su correo electrónico antes de continuar');
|
||||
expect(translateServerResponse(keys[15], 'es')).toBe('Por favor, completa todos los campos');
|
||||
expect(translateServerResponse(keys[16], 'es')).toBe('Por favor, ingresa tu correo electronico');
|
||||
expect(translateServerResponse(keys[17], 'es')).toBe('¡Por favor, ingresa tu correo electronico y contraseña!');
|
||||
expect(translateServerResponse(keys[18], 'es')).toBe('Por favor, rellene la nueva contraseña');
|
||||
expect(translateServerResponse(keys[19], 'es')).toBe('¡Por favor, escriba al menos 3 caracteres!');
|
||||
expect(translateServerResponse(keys[20], 'es')).toBe('La longitud máxima del texto es 2000');
|
||||
expect(translateServerResponse(keys[21], 'es')).toBe('Error desconocido');
|
||||
expect(translateServerResponse(keys[22], 'es')).toBe('Identificación incorrecta o faltante');
|
||||
expect(translateServerResponse(keys[23], 'es')).toBe('¡Información incorrecta o incompleta!');
|
||||
expect(translateServerResponse(keys[24], 'es')).toBe('¡Usuario o contraseña incorrectos!');
|
||||
expect(translateServerResponse(keys[25], 'es')).toBe('¡Nada que actualizar!');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { translateTaskResponse } from '../../utils/TranslatorUtils';
|
||||
import { TaskResponse } from '../../types/TaskResponse';
|
||||
|
||||
const tasks: TaskResponse[] = [
|
||||
{
|
||||
id: 1,
|
||||
description: 'description',
|
||||
done: false,
|
||||
highPriority: true,
|
||||
dueDate: '',
|
||||
dueDateFmt: '',
|
||||
lastUpdate: 'Moments ago',
|
||||
tag: 'test',
|
||||
urls: []
|
||||
}
|
||||
];
|
||||
|
||||
describe('Translator utils unit tests', () => {
|
||||
it('should translate all task responses to pt_br', () => {
|
||||
const newListPtBr = JSON.parse(JSON.stringify(tasks));
|
||||
const translatedPtBr = translateTaskResponse(newListPtBr, 'pt_br');
|
||||
expect(translatedPtBr.length).toBe(1);
|
||||
|
||||
translatedPtBr.forEach((task: TaskResponse) => {
|
||||
expect(task.lastUpdate).toBe('Momentos atrás');
|
||||
});
|
||||
});
|
||||
|
||||
it('should translate all task responses to es', () => {
|
||||
const newListEs = JSON.parse(JSON.stringify(tasks));
|
||||
const translatedEs = translateTaskResponse(newListEs, 'es');
|
||||
expect(translatedEs.length).toBe(1);
|
||||
|
||||
translatedEs.forEach((task: TaskResponse) => {
|
||||
expect(task.lastUpdate).toBe('Hace momentos');
|
||||
});
|
||||
});
|
||||
|
||||
it('should translate all task responses to ru', () => {
|
||||
const newListRu = JSON.parse(JSON.stringify(tasks));
|
||||
const translatedRu = translateTaskResponse(newListRu, 'ru');
|
||||
expect(translatedRu.length).toBe(1);
|
||||
|
||||
translatedRu.forEach((task: TaskResponse) => {
|
||||
expect(task.lastUpdate).toBe('Несколько минут назад');
|
||||
});
|
||||
});
|
||||
|
||||
it('should not translate a task responses from en', () => {
|
||||
const newListEn = JSON.parse(JSON.stringify(tasks));
|
||||
const translatedEn = translateTaskResponse(newListEn, 'en');
|
||||
expect(translatedEn.length).toBe(1);
|
||||
|
||||
translatedEn.forEach((task: TaskResponse) => {
|
||||
expect(task.lastUpdate).toBe('Moments ago');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import About from '../../views/About';
|
||||
import '../../i18n';
|
||||
|
||||
describe('Renders the about view', () => {
|
||||
it('should render the about view', async() => {
|
||||
render(
|
||||
<About />
|
||||
);
|
||||
|
||||
expect(document.querySelector('.justify-content-center')).toBeDefined();
|
||||
expect(document.querySelector('.poppins-medium')).toBeDefined();
|
||||
expect(document.querySelector('.poppins-light')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render text based on new contentHeader component', () => {
|
||||
const { getByText } = render(
|
||||
<About />
|
||||
);
|
||||
|
||||
expect(getByText('About the')).toBeDefined();
|
||||
expect(getByText('TaskNote App')).toBeDefined();
|
||||
expect(getByText('Find more information about us and the app')).toBeDefined();
|
||||
expect(getByText('Tasks and notes made')).toBeDefined();
|
||||
expect(getByText('Easy')).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import React from 'react';
|
||||
import { render, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import Account from '../../views/Account';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
import i18n from '../../i18n';
|
||||
import api from '../../api-service/api';
|
||||
import ApiConfig from '../../api-service/apiConfig';
|
||||
|
||||
vi.mock('../../api-service/api');
|
||||
|
||||
const changeLanguageMock = vi.fn();
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
i18n: {
|
||||
changeLanguage: changeLanguageMock,
|
||||
language: 'en'
|
||||
},
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
initReactI18next: {
|
||||
type: '3rdParty',
|
||||
init: vi.fn(),
|
||||
},
|
||||
I18nextProvider: ({ children }: any) => children,
|
||||
}));
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Ricardo',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://image.com',
|
||||
lang: 'en'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn()
|
||||
};
|
||||
|
||||
describe('Account Component', () => {
|
||||
const renderAccount = () => {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<AuthContext.Provider value={authContextMock}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<Account />
|
||||
</I18nextProvider>
|
||||
</AuthContext.Provider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('should render the Account component', () => {
|
||||
const { getByText } = renderAccount();
|
||||
expect(getByText('account_data_update_header')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should change language when a language button is clicked', () => {
|
||||
const { getByTestId } = renderAccount();
|
||||
const languageButton = getByTestId('language-button-pt_br');
|
||||
fireEvent.click(languageButton);
|
||||
expect(changeLanguageMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should show alert when delete button is clicked', () => {
|
||||
const { getByText } = renderAccount();
|
||||
const deleteButton = getByText('account_privacy_delete_btn');
|
||||
fireEvent.click(deleteButton);
|
||||
expect(getByText('account_delete_title')).toBeDefined();
|
||||
})
|
||||
|
||||
it('should call deleteAccount API and signOut when delete is confirmed', async () => {
|
||||
const { getByText } = renderAccount();
|
||||
const deleteButton = getByText('account_privacy_delete_btn');
|
||||
fireEvent.click(deleteButton);
|
||||
const confirmButton = getByText('account_delete_btn');
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.deleteNoContent).toHaveBeenCalledWith(ApiConfig.deleteAccountUrl);
|
||||
expect(authContextMock.signOut).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should submit the form with correct patchPayload', async () => {
|
||||
const mockPatchJSON = vi.spyOn(api, 'patchJSON').mockResolvedValue(authContextMock.user);
|
||||
|
||||
const { getByLabelText, getByText, getByTestId } = renderAccount();
|
||||
|
||||
fireEvent.change(getByLabelText('account_form_first_name_label'), { target: { value: 'Jane' } });
|
||||
fireEvent.change(getByLabelText('login_email_label'), { target: { value: 'jane.doe@example.com' } });
|
||||
fireEvent.change(getByTestId('account-password-one'), { target: { value: 'password123' } });
|
||||
fireEvent.change(getByLabelText(/register_password_repeat_label/i), { target: { value: 'password123' } });
|
||||
|
||||
fireEvent.click(getByText('account_form_save'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPatchJSON).toHaveBeenCalledWith(expect.any(String), {
|
||||
name: 'Jane',
|
||||
email: 'jane.doe@example.com',
|
||||
password: 'password123',
|
||||
passwordAgain: 'password123',
|
||||
lang: ''
|
||||
});
|
||||
});
|
||||
|
||||
mockPatchJSON.mockRestore();
|
||||
});
|
||||
|
||||
it('should render text based on new contentHeader component', () => {
|
||||
const { getByText } = renderAccount();
|
||||
|
||||
expect(getByText('account_header_my')).toBeDefined();
|
||||
expect(getByText('account_header_account')).toBeDefined();
|
||||
expect(getByText('account_my_account_hello')).toBeDefined();
|
||||
expect(getByText('account_header_update_manage')).toBeDefined();
|
||||
expect(getByText('account_header_data')).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi, Mock } from 'vitest';
|
||||
import { useNavigate } from 'react-router';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
import CompleteResetPassword from '../../views/CompleteResetPassword';
|
||||
|
||||
// Mock useNavigate
|
||||
vi.mock('react-router', () => ({
|
||||
useNavigate: vi.fn()
|
||||
}));
|
||||
|
||||
// Mock LoginForm
|
||||
vi.mock('../../components/LoginForm', () => ({
|
||||
__esModule: true,
|
||||
default: ({ prefix }: { prefix: string }) => (
|
||||
<div data-testid="login-form">LoginForm with prefix: {prefix}</div>
|
||||
)
|
||||
}));
|
||||
|
||||
vi.mock('react-router', () => {
|
||||
return {
|
||||
useNavigate: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const mockedUseNavigate = useNavigate as unknown as Mock;
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Ricardo',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://image.com'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn()
|
||||
};
|
||||
|
||||
describe('CompleteResetPassword Component', () => {
|
||||
const mockCheckCurrentAuthUser = vi.fn();
|
||||
const mockNavigate = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockedUseNavigate.mockReturnValue(mockNavigate);
|
||||
});
|
||||
|
||||
test('calls checkCurrentAuthUser with the correct pathname', () => {
|
||||
render(
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
...authContextMock,
|
||||
signed: false,
|
||||
checkCurrentAuthUser: mockCheckCurrentAuthUser,
|
||||
}}
|
||||
>
|
||||
<CompleteResetPassword />
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
expect(mockCheckCurrentAuthUser).toHaveBeenCalledWith(window.location.pathname);
|
||||
});
|
||||
|
||||
test('navigates to /home when signed is true', () => {
|
||||
render(
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
...authContextMock,
|
||||
signed: true,
|
||||
checkCurrentAuthUser: mockCheckCurrentAuthUser,
|
||||
}}
|
||||
>
|
||||
<CompleteResetPassword />
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/home');
|
||||
});
|
||||
|
||||
test('renders LoginForm with the correct prefix', () => {
|
||||
render(
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
...authContextMock,
|
||||
signed: false,
|
||||
checkCurrentAuthUser: mockCheckCurrentAuthUser,
|
||||
}}
|
||||
>
|
||||
<CompleteResetPassword />
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
const loginForm = screen.getByTestId('login-form');
|
||||
expect(loginForm.innerHTML.includes('LoginForm with prefix: complete_reset')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
// filepath: /home/ricardo/Projects/react-typescript-todolist/client/src/__test__/views/EmailConfirmation.test.tsx
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { vi, describe, test, expect, beforeEach } from 'vitest';
|
||||
import api from '../../api-service/api';
|
||||
import EmailConfirmation from '../../views/EmailConfirmation';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import ApiConfig from '../../api-service/apiConfig';
|
||||
|
||||
// Mock the entire api module
|
||||
vi.mock('../../api-service/api', () => ({
|
||||
default: {
|
||||
postJSON: vi.fn()
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock the translation hook
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => {
|
||||
const translations: Record<string, string> = {
|
||||
'email_confirmation_loading': 'Confirming your email address...',
|
||||
'email_confirmation_success': '✅ Email Confirmed!',
|
||||
'email_confirmation_success_text': 'Your email has been successfully confirmed.',
|
||||
'email_confirmation_btn': 'Login'
|
||||
};
|
||||
return translations[key] || key;
|
||||
},
|
||||
i18n: { language: 'en' }
|
||||
})
|
||||
}));
|
||||
|
||||
// Mock the lang handler
|
||||
vi.mock('../../lang-service/LangHandler', () => ({
|
||||
handleDefaultLang: vi.fn()
|
||||
}));
|
||||
|
||||
// Mock the translator utils
|
||||
vi.mock('../../utils/TranslatorUtils', () => ({
|
||||
translateServerResponse: (message: string) => message
|
||||
}));
|
||||
|
||||
const mockedApi = vi.mocked(api);
|
||||
|
||||
describe('EmailConfirmation Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
const renderWithRouter = (initialEntries: string[] = ['/?identification=test-id']) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={initialEntries}>
|
||||
<EmailConfirmation />
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
test('renders loading state initially', () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id'); // Default query param
|
||||
// Mock a pending promise to keep loading state
|
||||
mockedApi.postJSON.mockImplementation(() => new Promise(() => {}));
|
||||
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
expect(screen.getByText('Confirming your email address...')).toBeDefined();
|
||||
});
|
||||
|
||||
test('shows error when identification is missing', async () => {
|
||||
window.history.pushState({}, '', '/'); // No query param
|
||||
renderWithRouter();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('❌ Oops!')).toBeDefined();
|
||||
expect(screen.getByTestId('email-confirm-error-msg')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('shows success message when API call succeeds', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
vi.spyOn(api, 'postJSON').mockResolvedValue({});
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('email-confirm-success-msg')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('shows error message when API call fails', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockRejectedValue(new Error('API error occurred')); // Mock API failure
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('❌ Oops!')).toBeDefined();
|
||||
expect(screen.getByText('API error occurred')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('does not call API if identification is missing', async () => {
|
||||
window.history.pushState({}, '', '/'); // No query param
|
||||
renderWithRouter();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.postJSON).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test('calls API with correct payload when identification is present', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockResolvedValueOnce({}); // Mock successful API response
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.postJSON).toHaveBeenCalledWith(ApiConfig.confirmUrl, { identification: 'test-id' });
|
||||
});
|
||||
});
|
||||
|
||||
test('renders correct styles for success state', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockResolvedValueOnce({}); // Mock successful API response
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
const successMessage = screen.getByTestId('email-confirm-success-msg');
|
||||
expect(successMessage).toBeDefined();
|
||||
expect(successMessage.classList.contains('mb-4')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('renders correct styles for error state', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockRejectedValueOnce(new Error('API error occurred'));
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorMessage = screen.getByText('❌ Oops!');
|
||||
expect(errorMessage).toBeDefined();
|
||||
expect(errorMessage.classList.contains('mb-3')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('renders "Go to Login" button on success', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockResolvedValueOnce({}); // Mock successful API response
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
const loginButton = screen.getByText('Login');
|
||||
expect(loginButton).toBeDefined();
|
||||
expect(loginButton.classList.contains('btn-success')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('does not render "Go to Login" button on error', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockRejectedValueOnce(new Error('API error occurred')); // Mock API failure
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
const loginButton = screen.queryByText('Go to Login');
|
||||
expect(loginButton).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test('shows error message when API call fails', async () => {
|
||||
window.history.pushState({}, '', '/?identification=test-id');
|
||||
mockedApi.postJSON.mockRejectedValueOnce(new Error('API error occurred')); // Mock API failure
|
||||
renderWithRouter(['/?identification=test-id']);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('❌ Oops!')).toBeDefined();
|
||||
expect(screen.getByText('API error occurred')).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,560 @@
|
||||
import React from 'react';
|
||||
import { test, describe, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, act, fireEvent, waitFor } from '@testing-library/react';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
import FilterProvider from '../../context/FilterProvider';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import api from '../../api-service/api';
|
||||
import { TaskResponse } from '../../types/TaskResponse';
|
||||
import { NoteResponse } from '../../types/NoteResponse';
|
||||
import Home from '../../views/Home';
|
||||
|
||||
// filepath: client/src/views/Home/index.test.tsx
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => key,
|
||||
i18n: { language: 'en', changeLanguage: vi.fn() }
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock('../../api-service/api', () => ({
|
||||
default: {
|
||||
getJSON: vi.fn(),
|
||||
deleteNoContent: vi.fn()
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock('../../lang-service/LangHandler', () => ({
|
||||
handleDefaultLang: vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('../../utils/TranslatorUtils', () => ({
|
||||
translateServerResponse: (text: string) => text,
|
||||
translateTaskResponse: (tasks: any[]) => tasks
|
||||
}));
|
||||
|
||||
vi.mock('react-router', () => ({
|
||||
NavLink: ({ to, children }: { to: string, children: React.ReactNode }) => (
|
||||
<a href={to} data-testid={`navlink-${to}`}>{children}</a>
|
||||
)
|
||||
}));
|
||||
|
||||
vi.mock('react-bootstrap-icons', () => ({
|
||||
ThreeDotsVertical: () => <div data-testid="three-dots-icon">•••</div>
|
||||
}));
|
||||
|
||||
// Mock components
|
||||
vi.mock('../../components/ContentHeader', () => ({
|
||||
default: (props: any) => <div data-testid="content-header">{props.h1TextRegular} {props.h1TextBold}</div>
|
||||
}));
|
||||
|
||||
vi.mock('../../components/AlertError', () => ({
|
||||
default: (props: any) => <div data-testid="alert-error">{props.errorMessage}</div>
|
||||
}));
|
||||
|
||||
vi.mock('../../components/ModalMarkdown', () => ({
|
||||
default: (props: any) => <div data-testid="modal-markdown">{props.show ? 'Modal Open' : ''}</div>
|
||||
}));
|
||||
|
||||
vi.mock('../../components/TaskTitle', () => ({
|
||||
default: (props: any) => <div data-testid="task-title">{props.title}</div>
|
||||
}));
|
||||
|
||||
vi.mock('../../components/TaskTimeLeft', () => ({
|
||||
default: (props: any) => <div data-testid="task-time-left">{props.text}</div>
|
||||
}));
|
||||
|
||||
vi.mock('../../components/TaskTag', () => ({
|
||||
default: (props: any) => <div data-testid="task-tag">{props.tag}</div>
|
||||
}));
|
||||
|
||||
vi.mock('../../components/NoteTitle', () => ({
|
||||
default: (props: any) => <div data-testid="note-title">{props.title}</div>
|
||||
}));
|
||||
|
||||
// Test mock data
|
||||
const mockTasks: TaskResponse[] = [
|
||||
{
|
||||
id: 1,
|
||||
description: 'Task 1',
|
||||
done: false,
|
||||
urls: ['http://example.com'],
|
||||
tag: 'work',
|
||||
lastUpdate: '2023-10-10',
|
||||
highPriority: true,
|
||||
dueDateFmt: '2 days left',
|
||||
dueDate: '2023-10-12',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
description: 'Task 2',
|
||||
done: true,
|
||||
urls: [],
|
||||
tag: 'home',
|
||||
lastUpdate: '2023-10-09',
|
||||
highPriority: false,
|
||||
dueDateFmt: '',
|
||||
dueDate: '',
|
||||
}
|
||||
];
|
||||
|
||||
const mockNotes: NoteResponse[] = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Note 1',
|
||||
description: 'Line 1\nLine 2\nLine 3',
|
||||
tag: 'work',
|
||||
lastUpdate: '2023-10-10',
|
||||
url: 'http://example.com'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Note 2',
|
||||
description: 'This is a sample\nnote content',
|
||||
tag: 'personal',
|
||||
lastUpdate: '2023-10-09',
|
||||
url: null
|
||||
}
|
||||
];
|
||||
|
||||
const mockTags = ['work', 'home', 'personal', 'untagged'];
|
||||
|
||||
const authContextValue = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://image.com',
|
||||
lang: 'en'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn()
|
||||
};
|
||||
|
||||
describe('Home Component', () => {
|
||||
const renderHome = () => render(
|
||||
<AuthContext.Provider value={authContextValue}>
|
||||
<FilterProvider>
|
||||
<BrowserRouter>
|
||||
<Home />
|
||||
</BrowserRouter>
|
||||
</FilterProvider>
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mocks and setup default responses
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
(api.getJSON as any).mockImplementation((url: string) => {
|
||||
if (url.includes('tags')) {
|
||||
return Promise.resolve(mockTags);
|
||||
} else if (url.includes('tasks')) {
|
||||
return Promise.resolve(mockTasks);
|
||||
} else if (url.includes('notes')) {
|
||||
return Promise.resolve(mockNotes);
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
(api.deleteNoContent as any).mockResolvedValue(undefined);
|
||||
|
||||
// Mock window.innerWidth for the cleanText function
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: 1024
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
test('renders with initial data', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('content-header')).toBeDefined();
|
||||
expect(screen.getByPlaceholderText('home_input_filter')).toBeDefined();
|
||||
|
||||
// Check that API calls were made
|
||||
expect(api.getJSON).toHaveBeenCalledTimes(3);
|
||||
|
||||
// Wait for tasks and notes to render
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
test('filters tasks and notes when search text is entered', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('home_input_filter');
|
||||
|
||||
// Test filtering by entering text
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: 'Task 1' } });
|
||||
});
|
||||
|
||||
// Expect filtered results
|
||||
await waitFor(() => {
|
||||
const taskTitles = screen.getAllByTestId('task-title');
|
||||
expect(taskTitles.length).toBe(1);
|
||||
expect(taskTitles[0].textContent).toBe('Task 1');
|
||||
});
|
||||
});
|
||||
|
||||
test('filters by radio button selection', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
|
||||
const dropdownToggle = screen.getByTestId('main-label-selector');
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggle);
|
||||
});
|
||||
|
||||
// Select "Only Tasks" from dropdown
|
||||
const onlyTasksOption = screen.getByRole('button', { name: /home_radio_tasks/i });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(onlyTasksOption);
|
||||
});
|
||||
|
||||
// Should only show tasks
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
expect(screen.queryAllByTestId('note-title').length).toBe(0);
|
||||
});
|
||||
|
||||
// Select "Only Notes" radio button
|
||||
const onlyNotesOption = screen.getByRole('button', { name: /home_radio_notes/i });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(onlyNotesOption);
|
||||
});
|
||||
|
||||
// Should only show notes
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByTestId('task-title').length).toBe(0);
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
test('filters by tag selection', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
|
||||
const dropdownToggle = screen.getByTestId('main-label-selector');
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggle);
|
||||
});
|
||||
|
||||
// Select "work" tag radio button
|
||||
const workTagOption = screen.getByRole('button', { name: /#work/i });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(workTagOption);
|
||||
});
|
||||
|
||||
// Should only show items with "work" tag
|
||||
await waitFor(() => {
|
||||
const taskTitles = screen.getAllByTestId('task-title');
|
||||
const noteTitles = screen.getAllByTestId('note-title');
|
||||
|
||||
expect(taskTitles.length).toBe(1);
|
||||
expect(noteTitles.length).toBe(1);
|
||||
expect(taskTitles[0].textContent).toBe('Task 1');
|
||||
expect(noteTitles[0].textContent).toBe('Note 1');
|
||||
});
|
||||
});
|
||||
|
||||
test('marks task as done', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
});
|
||||
|
||||
// Find the dropdown toggle for the first task
|
||||
const dropdownToggles = screen.getAllByTestId('three-dots-icon');
|
||||
|
||||
// Click the dropdown toggle
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggles[0]);
|
||||
});
|
||||
|
||||
// Find and click the "Mark as Done" option
|
||||
// Since we mocked the components, we need to find it by aria role
|
||||
const dropdownItems = screen.getAllByRole('button');
|
||||
const markAsDoneButton = dropdownItems.find(
|
||||
item => item.textContent === 'task_table_action_done'
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(markAsDoneButton!);
|
||||
});
|
||||
|
||||
// Should call deleteNoContent API
|
||||
expect(api.deleteNoContent).toHaveBeenCalledWith(expect.stringContaining('/1'));
|
||||
|
||||
// Should reload tasks
|
||||
expect(api.getJSON).toHaveBeenCalledWith(expect.stringContaining('tasks'));
|
||||
});
|
||||
|
||||
test('deletes note', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
|
||||
// Find the dropdown toggle for the first note
|
||||
const noteDropdownToggles = screen.getAllByTestId('three-dots-icon');
|
||||
// Note dropdowns start after task dropdowns
|
||||
const firstNoteDropdown = noteDropdownToggles[mockTasks.length];
|
||||
|
||||
// Click the dropdown toggle
|
||||
await act(async () => {
|
||||
fireEvent.click(firstNoteDropdown);
|
||||
});
|
||||
|
||||
// Find and click the "Delete" option by testId
|
||||
const deleteButtons = screen.getAllByRole('button');
|
||||
const deleteButton = deleteButtons.find(
|
||||
button => button.textContent === 'task_table_action_delete'
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(deleteButton!);
|
||||
});
|
||||
|
||||
// Should call deleteNoContent API
|
||||
expect(api.deleteNoContent).toHaveBeenCalledWith(expect.stringContaining('/2'));
|
||||
|
||||
// Should reload notes
|
||||
expect(api.getJSON).toHaveBeenCalledWith(expect.stringContaining('notes'));
|
||||
});
|
||||
|
||||
test('opens markdown modal when clicking on note tag', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-tag').length).toBe(mockTasks.length + mockNotes.length);
|
||||
});
|
||||
|
||||
// Find the tags for notes (they start after task tags)
|
||||
const noteTags = screen.getAllByTestId('task-tag').slice(mockTasks.length);
|
||||
|
||||
// Click on the first note tag
|
||||
await act(async () => {
|
||||
// Simulate the onClick prop by finding the element and firing a click event
|
||||
fireEvent.click(noteTags[0]);
|
||||
});
|
||||
|
||||
// Modal should be opened
|
||||
const modal = screen.getByTestId('modal-markdown');
|
||||
expect(modal.textContent).toBe('');
|
||||
});
|
||||
|
||||
test('handles API errors gracefully', async () => {
|
||||
// Mock API to throw error
|
||||
(api.getJSON as any).mockImplementation(() => {
|
||||
throw new Error('API Error');
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
// Should show error message
|
||||
expect(screen.getByTestId('alert-error')).toBeDefined();
|
||||
expect(screen.getByTestId('alert-error').textContent).toBe('API Error');
|
||||
});
|
||||
|
||||
test('keeps filter selection after marking task as done', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
});
|
||||
|
||||
// Select "Only Tasks" filter
|
||||
const dropdownToggle = screen.getByTestId('main-label-selector');
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggle);
|
||||
});
|
||||
|
||||
const onlyTasksOption = screen.getByRole('button', { name: /home_radio_tasks/i });
|
||||
await act(async () => {
|
||||
fireEvent.click(onlyTasksOption);
|
||||
});
|
||||
|
||||
// Verify filter is applied - notes should be hidden
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByTestId('note-title').length).toBe(0);
|
||||
});
|
||||
|
||||
// Mark a task as done
|
||||
const dropdownToggles = screen.getAllByTestId('three-dots-icon');
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggles[0]);
|
||||
});
|
||||
|
||||
const dropdownItems = screen.getAllByRole('button');
|
||||
const markAsDoneButton = dropdownItems.find(
|
||||
item => item.textContent === 'task_table_action_done'
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(markAsDoneButton!);
|
||||
});
|
||||
|
||||
// After reload, filter should still be applied - notes should remain hidden
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByTestId('note-title').length).toBe(0);
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
test('keeps filter selection after deleting a note', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
|
||||
// Select "Only Notes" filter
|
||||
const dropdownToggle = screen.getByTestId('main-label-selector');
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggle);
|
||||
});
|
||||
|
||||
const onlyNotesOption = screen.getByRole('button', { name: /home_radio_notes/i });
|
||||
await act(async () => {
|
||||
fireEvent.click(onlyNotesOption);
|
||||
});
|
||||
|
||||
// Verify filter is applied - tasks should be hidden
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByTestId('task-title').length).toBe(0);
|
||||
});
|
||||
|
||||
// Delete a note
|
||||
const noteDropdownToggles = screen.getAllByTestId('three-dots-icon');
|
||||
await act(async () => {
|
||||
fireEvent.click(noteDropdownToggles[0]);
|
||||
});
|
||||
|
||||
const deleteButtons = screen.getAllByRole('button');
|
||||
const deleteButton = deleteButtons.find(
|
||||
button => button.textContent === 'task_table_action_delete'
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(deleteButton!);
|
||||
});
|
||||
|
||||
// After reload, filter should still be applied - tasks should remain hidden
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByTestId('task-title').length).toBe(0);
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
test('keeps text search after marking task as done', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(2);
|
||||
});
|
||||
|
||||
// Enter search text to filter to only 'Task 1'
|
||||
const searchInput = screen.getByPlaceholderText('home_input_filter');
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: 'Task 1' } });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(1);
|
||||
expect(screen.getAllByTestId('task-title')[0].textContent).toBe('Task 1');
|
||||
});
|
||||
|
||||
// Mark the task as done
|
||||
const dropdownToggles = screen.getAllByTestId('three-dots-icon');
|
||||
await act(async () => {
|
||||
fireEvent.click(dropdownToggles[0]);
|
||||
});
|
||||
|
||||
const dropdownItems = screen.getAllByRole('button');
|
||||
const markAsDoneButton = dropdownItems.find(
|
||||
item => item.textContent === 'task_table_action_done'
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(markAsDoneButton!);
|
||||
});
|
||||
|
||||
// After reload, text filter should still be applied
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('task-title').length).toBe(1);
|
||||
expect(screen.getAllByTestId('task-title')[0].textContent).toBe('Task 1');
|
||||
});
|
||||
});
|
||||
/*
|
||||
test('getFirstRows properly formats note preview', async () => {
|
||||
await act(async () => {
|
||||
renderHome();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByTestId('note-title').length).toBe(2);
|
||||
});
|
||||
|
||||
// Find rendered note previews
|
||||
const noteCards = screen.getAllByClassName('text-muted span-line-break font-size-14');
|
||||
|
||||
// First note should have preview with the first two lines
|
||||
expect(noteCards[0].textContent).toBe('Line 1\nLine 2');
|
||||
});*/
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import React from 'react';
|
||||
import { render, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import NoteAdd from '../../views/NoteAdd';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
import i18n from '../../i18n';
|
||||
import api from '../../api-service/api';
|
||||
import ApiConfig from '../../api-service/apiConfig';
|
||||
import { NoteResponse } from '../../types/NoteResponse';
|
||||
import SidebarContext from '../../context/SidebarContext';
|
||||
|
||||
// Mock the entire api module
|
||||
vi.mock('../../api-service/api', () => ({
|
||||
default: {
|
||||
postJSON: vi.fn(),
|
||||
getJSON: vi.fn(),
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
i18n: {
|
||||
changeLanguage: vi.fn(),
|
||||
language: 'en',
|
||||
},
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
initReactI18next: {
|
||||
type: '3rdParty',
|
||||
init: vi.fn(),
|
||||
},
|
||||
I18nextProvider: ({ children }: any) => children,
|
||||
}));
|
||||
|
||||
vi.mock('react-router', async () => {
|
||||
const actual = await vi.importActual<any>('react-router');
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useSearchParams: vi.fn(),
|
||||
useParams: vi.fn()
|
||||
};
|
||||
});
|
||||
|
||||
import { useSearchParams, useParams } from 'react-router';
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Ricardo',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://url.com',
|
||||
lang: 'en'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn(),
|
||||
};
|
||||
|
||||
const sidebarContextMock = {
|
||||
currentPage: '/home',
|
||||
setNewPage: vi.fn()
|
||||
};
|
||||
|
||||
// Mock the lang handler
|
||||
vi.mock('../../lang-service/LangHandler', () => ({
|
||||
handleDefaultLang: vi.fn()
|
||||
}));
|
||||
|
||||
// Mock the translator utils
|
||||
vi.mock('../../utils/TranslatorUtils', () => ({
|
||||
translateServerResponse: (message: string) => message
|
||||
}));
|
||||
|
||||
const mockedApi = vi.mocked(api);
|
||||
const mockedUseParams = vi.mocked(useParams);
|
||||
|
||||
describe('NoteAdd Component', () => {
|
||||
const renderNoteAdd = () => {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<AuthContext.Provider value={authContextMock}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<SidebarContext.Provider value={sidebarContextMock}>
|
||||
<NoteAdd />
|
||||
</SidebarContext.Provider>
|
||||
</I18nextProvider>
|
||||
</AuthContext.Provider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mock between tests
|
||||
(useSearchParams as unknown as ReturnType<typeof vi.fn>).mockReset();
|
||||
vi.clearAllMocks();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it('should render the NoteAdd component', () => {
|
||||
const { getByText } = renderNoteAdd();
|
||||
expect(getByText('note_form_title_label')).toBeDefined();
|
||||
expect(getByText('task_form_url_label')).toBeDefined();
|
||||
expect(getByText('note_form_content_label')).toBeDefined();
|
||||
expect(getByText('note_form_submit')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should show error message when form is invalid', async () => {
|
||||
const { getByText, getByRole } = renderNoteAdd();
|
||||
const submitButton = getByRole('button', { name: 'note_form_submit' });
|
||||
fireEvent.click(submitButton);
|
||||
await waitFor(() => {
|
||||
expect(getByText('Please fill in all the fields')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('should add a new note when form is valid', async () => {
|
||||
(useSearchParams as unknown as ReturnType<typeof vi.fn>).mockReturnValue([
|
||||
new URLSearchParams("backTo=home"),
|
||||
]);
|
||||
|
||||
const { getByLabelText, getByTestId, getByRole } = renderNoteAdd();
|
||||
const descriptionInput = getByLabelText('note_form_title_label') as HTMLInputElement;
|
||||
const noteContentInput = getByTestId('note-content-input-area') as HTMLAreaElement;
|
||||
const submitButton = getByRole('button', { name: 'note_form_submit' });
|
||||
|
||||
fireEvent.change(descriptionInput, { target: { value: 'New Note' } });
|
||||
fireEvent.change(noteContentInput, { target: { value: 'Note content' } });
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
const newNote: NoteResponse = {
|
||||
id: 0,
|
||||
title: 'New Note',
|
||||
description: 'Note content',
|
||||
url: '',
|
||||
tag: '',
|
||||
lastUpdate: '',
|
||||
shared: false,
|
||||
shareToken: null
|
||||
}
|
||||
expect(api.postJSON).toHaveBeenCalledWith(ApiConfig.notesUrl, newNote);
|
||||
});
|
||||
});
|
||||
|
||||
it('should render text based on new contentHeader component', () => {
|
||||
const { getByText } = renderNoteAdd();
|
||||
|
||||
expect(getByText('Add')).toBeDefined();
|
||||
expect(getByText('Note')).toBeDefined();
|
||||
expect(getByText('Save your notes in plain text or Markdown format')).toBeDefined();
|
||||
expect(getByText('Create, Filter, and Easily Find')).toBeDefined();
|
||||
expect(getByText('Them')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should render a note to edit', async () => {
|
||||
mockedUseParams.mockReturnValue({ id: '1' });
|
||||
|
||||
const toEdit: NoteResponse = {
|
||||
id: 1,
|
||||
title: 'Note one',
|
||||
description: 'Description of note one',
|
||||
url: 'http://notes.domain.com',
|
||||
tag: 'dev',
|
||||
lastUpdate: '3 minutes ago',
|
||||
};
|
||||
|
||||
vi.spyOn(api, 'getJSON').mockResolvedValue(toEdit);
|
||||
|
||||
const { getByLabelText, getByTestId } = renderNoteAdd();
|
||||
|
||||
await waitFor(() => {
|
||||
const noteTitle = getByLabelText('note_form_title_label') as HTMLInputElement;
|
||||
const noteUrl = getByLabelText('task_form_url_label') as HTMLInputElement;
|
||||
const noteContentInput = getByTestId('note-content-input-area') as HTMLAreaElement;
|
||||
expect(noteTitle.value).toBe(toEdit.title);
|
||||
expect(noteUrl.value).toBe(toEdit.url);
|
||||
expect(noteContentInput.innerHTML).toBe(toEdit.description);
|
||||
});
|
||||
});
|
||||
|
||||
it('should render a cloned note', async () => {
|
||||
window.history.pushState({}, '', '?cloneFrom=123');
|
||||
|
||||
const toClone: NoteResponse = {
|
||||
id: 11,
|
||||
title: 'Old title',
|
||||
description: 'Old description',
|
||||
url: 'http://notes.domain.com',
|
||||
tag: 'dev',
|
||||
lastUpdate: '1 minute ago',
|
||||
};
|
||||
|
||||
vi.spyOn(api, 'getJSON').mockResolvedValue(toClone);
|
||||
|
||||
const { getByLabelText, getByTestId } = renderNoteAdd();
|
||||
|
||||
await waitFor(() => {
|
||||
const noteTitle = getByLabelText('note_form_title_label') as HTMLInputElement;
|
||||
const noteUrl = getByLabelText('task_form_url_label') as HTMLInputElement;
|
||||
const noteContentInput = getByTestId('note-content-input-area') as HTMLAreaElement;
|
||||
expect(noteTitle.value).toBe(toClone.title);
|
||||
expect(noteUrl.value).toBe(toClone.url);
|
||||
expect(noteContentInput.innerHTML).toBe(toClone.description);
|
||||
});
|
||||
});
|
||||
|
||||
it('should not render a cloned note when user is trying to mess up', async () => {
|
||||
window.history.pushState({}, '', '?cloneFrom=12345');
|
||||
|
||||
const { getByLabelText, getByTestId } = renderNoteAdd();
|
||||
|
||||
await waitFor(() => {
|
||||
const noteTitle = getByLabelText('note_form_title_label') as HTMLInputElement;
|
||||
const noteUrl = getByLabelText('task_form_url_label') as HTMLInputElement;
|
||||
const noteContentInput = getByTestId('note-content-input-area') as HTMLAreaElement;
|
||||
expect(noteTitle.value).toBe('');
|
||||
expect(noteUrl.value).toBe('');
|
||||
expect(noteContentInput.innerHTML).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import React from 'react';
|
||||
import { render, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import TaskAdd from '../../views/TaskAdd';
|
||||
import AuthContext from '../../context/AuthContext';
|
||||
import i18n from '../../i18n';
|
||||
import api from '../../api-service/api';
|
||||
import ApiConfig from '../../api-service/apiConfig';
|
||||
import TaskNoteRequest from '../../types/TaskNoteRequest';
|
||||
import SidebarContext from '../../context/SidebarContext';
|
||||
|
||||
vi.mock('../../api-service/api');
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
i18n: {
|
||||
changeLanguage: vi.fn(),
|
||||
language: 'en',
|
||||
},
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
initReactI18next: {
|
||||
type: '3rdParty',
|
||||
init: vi.fn(),
|
||||
},
|
||||
I18nextProvider: ({ children }: any) => children,
|
||||
}));
|
||||
|
||||
vi.mock("react-router-dom", async () => {
|
||||
const actual = await vi.importActual<any>("react-router-dom");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useSearchParams: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
const authContextMock = {
|
||||
signed: true,
|
||||
user: {
|
||||
userId: 1,
|
||||
name: 'Ricardo',
|
||||
email: 'test@example.com',
|
||||
admin: false,
|
||||
createdAt: new Date(),
|
||||
gravatarImageUrl: 'http://url.com'
|
||||
},
|
||||
checkCurrentAuthUser: vi.fn(),
|
||||
signIn: vi.fn(),
|
||||
signOut: vi.fn(),
|
||||
register: vi.fn(),
|
||||
isAdmin: false,
|
||||
updateUser: vi.fn(),
|
||||
};
|
||||
|
||||
const sidebarContextMock = {
|
||||
currentPage: '/home',
|
||||
setNewPage: vi.fn()
|
||||
};
|
||||
|
||||
describe('TaskAdd Component', () => {
|
||||
const renderTaskAdd = () => {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<AuthContext.Provider value={authContextMock}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<SidebarContext.Provider value={sidebarContextMock}>
|
||||
<TaskAdd />
|
||||
</SidebarContext.Provider>
|
||||
</I18nextProvider>
|
||||
</AuthContext.Provider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mock between tests
|
||||
(useSearchParams as unknown as ReturnType<typeof vi.fn>).mockReset();
|
||||
});
|
||||
|
||||
it('should render the TaskAdd component', () => {
|
||||
const { getByText } = renderTaskAdd();
|
||||
expect(getByText('task_form_title')).toBeDefined();
|
||||
expect(getByText('task_form_desc_label')).toBeDefined();
|
||||
expect(getByText('task_form_url_label')).toBeDefined();
|
||||
expect(getByText('task_form_duedate_label')).toBeDefined();
|
||||
expect(getByText('task_form_submit')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should show error message when form is invalid', async () => {
|
||||
const { getByText, getByRole } = renderTaskAdd();
|
||||
const submitButton = getByRole('button', { name: 'task_form_submit' });
|
||||
fireEvent.click(submitButton);
|
||||
await waitFor(() => {
|
||||
expect(getByText('Please fill in all the fields')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('should add a new task when form is valid', async () => {
|
||||
(useSearchParams as unknown as ReturnType<typeof vi.fn>).mockReturnValue([
|
||||
new URLSearchParams("backTo=home"),
|
||||
]);
|
||||
|
||||
const { getByLabelText, getByRole } = renderTaskAdd();
|
||||
const descriptionInput = getByLabelText('task_form_desc_label') as HTMLInputElement;
|
||||
const submitButton = getByRole('button', { name: 'task_form_submit' });
|
||||
|
||||
fireEvent.change(descriptionInput, { target: { value: 'New Task' } });
|
||||
expect(descriptionInput.value).toBe('New Task');
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
const newTask: TaskNoteRequest = {
|
||||
description: 'New Task',
|
||||
dueDate: '',
|
||||
highPriority: false,
|
||||
tag: '',
|
||||
urls: []
|
||||
}
|
||||
expect(api.postJSON).toHaveBeenCalledWith(ApiConfig.tasksUrl, newTask);
|
||||
});
|
||||
});
|
||||
|
||||
it('should render text based on new contentHeader component', () => {
|
||||
(useSearchParams as unknown as ReturnType<typeof vi.fn>).mockReturnValue([
|
||||
new URLSearchParams("backTo=home"),
|
||||
]);
|
||||
|
||||
const { getByText } = renderTaskAdd();
|
||||
|
||||
expect(getByText('Add')).toBeDefined();
|
||||
expect(getByText('Task')).toBeDefined();
|
||||
expect(getByText('Be on top of your TODO list')).toBeDefined();
|
||||
expect(getByText('Create, Filter, and Easily Find')).toBeDefined();
|
||||
expect(getByText('Them')).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { API_TOKEN } from '../app-constants/app-constants';
|
||||
|
||||
/**
|
||||
* Retrieves the API token from local storage.
|
||||
*
|
||||
* @returns {string} The API token if it exists in local storage, otherwise an empty string.
|
||||
*/
|
||||
function getToken(): string {
|
||||
const tokenState = localStorage.getItem(API_TOKEN);
|
||||
return tokenState ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all the headers for the app.
|
||||
*
|
||||
* @returns {Headers} the headers.
|
||||
*/
|
||||
function getHeaders(addAuth: boolean = true): Headers {
|
||||
const headers = new Headers();
|
||||
headers.append('Content-Type', 'application/json');
|
||||
|
||||
if (addAuth) {
|
||||
headers.append('Authorization', `Bearer ${getToken()}`);
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
function getRequestInit(method: string, payload: object | undefined, addAuth: boolean = true): RequestInit {
|
||||
const body: string | undefined = method !== 'GET' ? JSON.stringify(payload) : undefined;
|
||||
|
||||
return {
|
||||
method: method,
|
||||
mode: 'cors',
|
||||
credentials: 'include',
|
||||
headers: getHeaders(addAuth),
|
||||
body
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle errors for the AJAX HTTPS requests.
|
||||
*
|
||||
* @param {number} httpStatusCode The HTTP response status code.
|
||||
*/
|
||||
function handleError(httpStatusCode: number) {
|
||||
if (httpStatusCode === 500) {
|
||||
throw new Error('Internal Server Error!');
|
||||
}
|
||||
throw new Error('Unknown error');
|
||||
}
|
||||
|
||||
async function handleResponse(response: Response) {
|
||||
// Successful responses
|
||||
if (response?.ok) {
|
||||
const codesToIgnore: number[] = [204];
|
||||
if (codesToIgnore.includes(response.status)) {
|
||||
return;
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
// Error responses
|
||||
if (response) {
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (contentType && contentType.includes('application/json')) {
|
||||
const data = await response.json();
|
||||
if ('message' in data && typeof data.message === 'string') {
|
||||
throw new Error(data.message);
|
||||
}
|
||||
if ('fields' in data && Array.isArray(data.fields)) {
|
||||
const firstError = data.fields[0].fieldMessage as string;
|
||||
throw new Error(firstError);
|
||||
}
|
||||
}
|
||||
handleError(response.status);
|
||||
}
|
||||
}
|
||||
|
||||
function isAddAuth(url: string): boolean {
|
||||
return !url.includes('sign-in') && !url.includes('sign-up');
|
||||
}
|
||||
|
||||
const api = {
|
||||
getJSON: async (url: string) => {
|
||||
const response = await fetch(url, getRequestInit('GET', {}));
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
getJSONNoAuth: async (url: string) => {
|
||||
const response = await fetch(url, getRequestInit('GET', {}, false));
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
postJSON: async (url: string, payload: object) => {
|
||||
const response = await fetch(url, getRequestInit('POST', payload, isAddAuth(url)));
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
patchJSON: async (url: string, payload: object) => {
|
||||
const response = await fetch(url, getRequestInit('PATCH', payload));
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
putJSON: async (url: string, payload: object) => {
|
||||
const response = await fetch(url, getRequestInit('PUT', payload, isAddAuth(url)));
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
deleteNoContent: async (url: string) => {
|
||||
const response = await fetch(url, getRequestInit('DELETE', {}));
|
||||
return handleResponse(response);
|
||||
}
|
||||
};
|
||||
|
||||
export default api;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { env } from '../env';
|
||||
|
||||
const server = env.VITE_BACKEND_SERVER;
|
||||
|
||||
const ApiConfig = {
|
||||
|
||||
signInUrl: `${server}/auth/sign-in`,
|
||||
|
||||
registerUrl: `${server}/auth/sign-up`,
|
||||
|
||||
confirmUrl: `${server}/auth/email-confirmation`,
|
||||
|
||||
resetPwdUrl: `${server}/auth/password-reset`,
|
||||
|
||||
completeResetPwdUrl: `${server}/auth/complete-password-reset`,
|
||||
|
||||
resendConfirmUrl: `${server}/auth/resend-email-confirmation`,
|
||||
|
||||
refreshTokenUrl: `${server}/rest/user-sessions/refresh`,
|
||||
|
||||
deleteAccountUrl: `${server}/rest/user-sessions/delete-account`,
|
||||
|
||||
tasksUrl: `${server}/rest/tasks`,
|
||||
|
||||
homeUrl: `${server}/rest/home`,
|
||||
|
||||
notesUrl: `${server}/rest/notes`,
|
||||
|
||||
publicNotesUrl: `${server}/public/notes`,
|
||||
|
||||
userUrl: `${server}/rest/users`
|
||||
};
|
||||
|
||||
export default ApiConfig;
|
||||
@@ -0,0 +1,3 @@
|
||||
export const REDIRECT_PATH = 'TASKNOTE-REDIRECT';
|
||||
export const API_TOKEN = 'TASKNOTE-TOKEN';
|
||||
export const USER_DATA = 'TASKNOTE-USER';
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,12 @@
|
||||
<svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect opacity="0.8" x="0.5" y="0.5" width="43" height="43" rx="7.5" stroke="#C3D4E9"/>
|
||||
<path d="M18 12V15" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M26 12V15" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13.5 19.09H30.5" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M32 29C32 29.75 31.79 30.46 31.42 31.06C30.73 32.22 29.46 33 28 33C26.99 33 26.07 32.63 25.37 32C25.06 31.74 24.79 31.42 24.58 31.06C24.21 30.46 24 29.75 24 29C24 26.79 25.79 25 28 25C29.2 25 30.27 25.53 31 26.36C31.62 27.07 32 27.99 32 29Z" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M26.44 29L27.43 29.99L29.56 28.02" stroke="#222222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M31 18.5V26.36C30.27 25.53 29.2 25 28 25C25.79 25 24 26.79 24 29C24 29.75 24.21 30.46 24.58 31.06C24.79 31.42 25.06 31.74 25.37 32H18C14.5 32 13 30 13 27V18.5C13 15.5 14.5 13.5 18 13.5H26C29.5 13.5 31 15.5 31 18.5Z" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M21.9955 23.7H22.0045" stroke="#222222" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M18.2943 23.7H18.3033" stroke="#222222" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M18.2943 26.7H18.3033" stroke="#222222" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,8 @@
|
||||
<svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect opacity="0.8" x="0.5" y="0.5" width="43" height="43" rx="7.5" fill="white" stroke="#C3D4E9"/>
|
||||
<path d="M15.9 27H28.09C29.99 27 30.99 26 30.99 24.1V12H12.99V24.1C13 26 14 27 15.9 27Z" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M12 12H32" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M18 32L22 30V27" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M26 32L22 30" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M17.5 21L20.65 18.37C20.9 18.16 21.23 18.22 21.4 18.5L22.6 20.5C22.77 20.78 23.1 20.83 23.35 20.63L26.5 18" stroke="#222222" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1018 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 443 B |
|
After Width: | Height: | Size: 324 KiB |
|
After Width: | Height: | Size: 355 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 235 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,8 @@
|
||||
<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="40" height="40" rx="8" fill="white" fill-opacity="0.2"/>
|
||||
<path d="M18 14H22C24 14 24 13 24 12C24 10 23 10 22 10H18C17 10 16 10 16 12C16 14 17 14 18 14Z" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M22 30H17C12 30 11 28 11 24V18C11 13.44 12.67 12.2 16 12.02" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M24 12.02C27.33 12.2 29 13.43 29 18V23" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M23 27V24H26" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M29 30L23.04 24.04" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 970 B |
@@ -0,0 +1,6 @@
|
||||
<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="40" height="40" rx="8" fill="white" fill-opacity="0.2"/>
|
||||
<path d="M17.31 22.7L18.81 24.2L22.81 20.2" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M18 14H22C24 14 24 13 24 12C24 10 23 10 22 10H18C17 10 16 10 16 12C16 14 17 14 18 14Z" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M24 12.02C27.33 12.2 29 13.43 29 18V24C29 28 28 30 23 30H17C12 30 11 28 11 24V18C11 13.44 12.67 12.2 16 12.02" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 728 B |
@@ -0,0 +1,7 @@
|
||||
<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="40" height="40" rx="8" fill="white" fill-opacity="0.2"/>
|
||||
<path d="M16 20.2H23" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16 24.2H20.38" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M18 14H22C24 14 24 13 24 12C24 10 23 10 22 10H18C17 10 16 10 16 12C16 14 17 14 18 14Z" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M24 12.02C27.33 12.2 29 13.43 29 18V24C29 28 28 30 23 30H17C12 30 11 28 11 24V18C11 13.44 12.67 12.2 16 12.02" stroke="white" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 860 B |
|
After Width: | Height: | Size: 915 B |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
import { Alert } from 'react-bootstrap';
|
||||
|
||||
type Props = {
|
||||
errorMessage?: string;
|
||||
dataTestid?: string;
|
||||
onClose?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders an AlertError message banner.
|
||||
*
|
||||
* @param {Props} props the AlertError props with the message to be displayed.
|
||||
* @param {string} [props.errorMessage] Optional error message.
|
||||
* @param {string} [props.dataTestid] Optional data-testid property.
|
||||
* @param {Function} [props.onClose] OnClose function to be called.
|
||||
* @returns {React.ReactNode} the AlertError rendered component.
|
||||
*/
|
||||
const AlertError: React.FC<Props> = (props: Props): React.ReactNode => {
|
||||
if (!props.errorMessage || props.errorMessage.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Alert
|
||||
variant="danger"
|
||||
dismissible
|
||||
data-testid={props.dataTestid}
|
||||
onClose={props.onClose}
|
||||
>
|
||||
{ props.errorMessage }
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
|
||||
export default AlertError;
|
||||
@@ -0,0 +1,77 @@
|
||||
import React, { useContext } from 'react';
|
||||
import { Col, Row } from 'react-bootstrap';
|
||||
import { NavLink } from 'react-router';
|
||||
import SidebarContext from '../../context/SidebarContext';
|
||||
|
||||
type Props = {
|
||||
h1TextRegular: string;
|
||||
h1TextBold: string;
|
||||
subtitle: string;
|
||||
h2BlackText: string;
|
||||
h2GreenText: string;
|
||||
isHomeComponent?: boolean;
|
||||
newTaskI18n?: string;
|
||||
newNoteI18n?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the content header component with the title, subtitle and another subtitle.
|
||||
*
|
||||
* @param {Props} props the ContentHeader props with text to the displayed.
|
||||
* @param {string} props.h1TextRegular The first part of the h1 text block.
|
||||
* @param {string} props.h1TextBold The second part of the h1 text block.
|
||||
* @param {string} props.subtitle The header subtitle, muted.
|
||||
* @param {string} props.h2BlackText The first part of the h2 text block, black.
|
||||
* @param {string} props.h2GreenText The second part of the h2 text block, green.
|
||||
* @returns {React.ReactNode} The rendered ContentHeader component.
|
||||
*/
|
||||
const ContentHeader: React.FC<Props> = (props: Props): React.ReactNode => {
|
||||
const { setNewPage } = useContext(SidebarContext);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="poppins-regular home-hello main-margin">
|
||||
{props.h1TextRegular}
|
||||
{' '}
|
||||
<b>{props.h1TextBold}</b>
|
||||
</h1>
|
||||
<p className="poppins-regular home-subtitle">
|
||||
{props.subtitle}
|
||||
</p>
|
||||
|
||||
<Row className="mb-3">
|
||||
{/* If it's not the home component, display full column */}
|
||||
<Col xs={12} sm={props.isHomeComponent ? 8 : 12}>
|
||||
<h2 className="poppins-regular">
|
||||
{props.h2BlackText}
|
||||
</h2>
|
||||
<h2 className="poppins-bold home-productive">
|
||||
{props.h2GreenText}
|
||||
</h2>
|
||||
</Col>
|
||||
{props.isHomeComponent && (
|
||||
<Col xs={12} sm={4} className="text-sm-end">
|
||||
<NavLink to="/tasks/new" onClick={() => setNewPage('/tasks/new')}>
|
||||
<button
|
||||
type="button"
|
||||
className="home-new-item w-45 mb-2"
|
||||
>
|
||||
{props.newTaskI18n}
|
||||
</button>
|
||||
</NavLink>
|
||||
<NavLink to="/notes/new" onClick={() => setNewPage('/notes/new')}>
|
||||
<button
|
||||
type="button"
|
||||
className="home-new-item w-45 ms-2"
|
||||
>
|
||||
{props.newNoteI18n}
|
||||
</button>
|
||||
</NavLink>
|
||||
</Col>
|
||||
)}
|
||||
</Row>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContentHeader;
|
||||