Compare commits
1 Commits
chore/diox
...
test-andro
| Author | SHA1 | Date | |
|---|---|---|---|
|
3d8a2910cb
|
@@ -1,13 +1,12 @@
|
||||
/.git
|
||||
/.gitea
|
||||
/.github
|
||||
/bundle
|
||||
/node_modules
|
||||
/target
|
||||
|
||||
/.dockerignore
|
||||
/docker-compose-dev.yaml
|
||||
/docker-compose-prod.yaml
|
||||
/docker-compose.yaml
|
||||
/docker/dev/*/Dockerfile
|
||||
/docker/prod/*/Dockerfile
|
||||
/.dioxus/
|
||||
/.git/
|
||||
/.github/
|
||||
/debug/
|
||||
/node_modules/
|
||||
/static/
|
||||
/target/
|
||||
.dockerignore
|
||||
/docker-compose-dev.yml
|
||||
/docker-compose-prod.yml
|
||||
/docker/dev/app/Dockerfile
|
||||
/docker/prod/app/Dockerfile
|
||||
|
||||
2
.env.dev
2
.env.dev
@@ -1,2 +1,2 @@
|
||||
DATABASE_URL=postgres://app:app@localhost:5432/todo_baggins
|
||||
LANGUAGE_CODE=en-US
|
||||
MOBILE_SERVER_URL=
|
||||
|
||||
2
.github/workflows/checkov-check.yaml
vendored
2
.github/workflows/checkov-check.yaml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
with:
|
||||
python-version: "3.13.1"
|
||||
- name: Rust toolchain installation
|
||||
uses: dtolnay/rust-toolchain@8a40291d6a0a08b8fb98b13bad5a0305b42d5f9c # 1.92.0
|
||||
uses: dtolnay/rust-toolchain@0579bb9e1907e560c2f263f705f93655a44a07e5
|
||||
- name: code checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
|
||||
8
.github/workflows/rust-check.yaml
vendored
8
.github/workflows/rust-check.yaml
vendored
@@ -21,20 +21,18 @@ jobs:
|
||||
run: >
|
||||
apt-get update && apt-get install -y
|
||||
libgtk-3-dev=3.24.33-1ubuntu2.2
|
||||
libjavascriptcoregtk-4.1-dev=2.50.2-0ubuntu0.22.04.2
|
||||
libjavascriptcoregtk-4.1-dev=2.46.4-0ubuntu0.22.04.1
|
||||
libsoup-3.0-dev=3.0.7-0ubuntu1
|
||||
libwebkit2gtk-4.1-dev=2.50.2-0ubuntu0.22.04.2
|
||||
libwebkit2gtk-4.1-dev=2.46.4-0ubuntu0.22.04.1
|
||||
libxdo-dev=1:3.20160805.1-4
|
||||
- name: Rust toolchain installation
|
||||
uses: dtolnay/rust-toolchain@8a40291d6a0a08b8fb98b13bad5a0305b42d5f9c # 1.92.0
|
||||
uses: dtolnay/rust-toolchain@0579bb9e1907e560c2f263f705f93655a44a07e5
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
- name: code checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: .env symlink creation
|
||||
run: ln -s .env.example .env
|
||||
- name: npm build
|
||||
run: npm install && npm run build
|
||||
- name: rustfmt check
|
||||
|
||||
8
.github/workflows/shellcheck-check.yaml
vendored
8
.github/workflows/shellcheck-check.yaml
vendored
@@ -25,10 +25,4 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: ShellCheck check
|
||||
# https://www.shellcheck.net/wiki/Recursiveness
|
||||
run: |
|
||||
if find . -type f -name "*.sh" -print0 | grep -qz .; then
|
||||
find . -type f -name "*.sh" -print0 | xargs -0 shellcheck
|
||||
exit 0
|
||||
else
|
||||
echo "No shell scripts found. Skipping ShellCheck."
|
||||
fi
|
||||
run: find . -type f -name "*.sh" -print0 | xargs -0 shellcheck
|
||||
|
||||
16
.gitignore
vendored
16
.gitignore
vendored
@@ -1,10 +1,10 @@
|
||||
/.env
|
||||
/target/
|
||||
/dist/
|
||||
/static/
|
||||
/.dioxus/
|
||||
/node_modules/
|
||||
|
||||
/docker-compose.yaml
|
||||
**/*.rs.bk
|
||||
|
||||
/node_modules
|
||||
/target
|
||||
/bundle
|
||||
|
||||
/**/*.rs.bk
|
||||
/.DS_Store
|
||||
.env
|
||||
.env.prod
|
||||
|
||||
5
.idea/.gitignore
generated
vendored
Normal file
5
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
20
.idea/dataSources.local.xml
generated
Normal file
20
.idea/dataSources.local.xml
generated
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="dataSourceStorageLocal" created-in="RR-243.22562.230">
|
||||
<data-source name="todo_baggins@localhost" uuid="1658668c-c2b8-426d-a22f-16fbad9eff0b">
|
||||
<database-info product="PostgreSQL" version="16.4 (Debian 16.4-1.pgdg120+1)" jdbc-version="4.2" driver-name="PostgreSQL JDBC Driver" driver-version="42.6.0" dbms="POSTGRES" exact-version="16.4" exact-driver-version="42.6">
|
||||
<identifier-quote-string>"</identifier-quote-string>
|
||||
</database-info>
|
||||
<case-sensitivity plain-identifiers="lower" quoted-identifiers="exact" />
|
||||
<secret-storage>master_key</secret-storage>
|
||||
<user-name>app</user-name>
|
||||
<schema-mapping>
|
||||
<introspection-scope>
|
||||
<node kind="database" qname="@">
|
||||
<node kind="schema" qname="@" />
|
||||
</node>
|
||||
</introspection-scope>
|
||||
</schema-mapping>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
12
.idea/dataSources.xml
generated
Normal file
12
.idea/dataSources.xml
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="todo_baggins@localhost" uuid="1658668c-c2b8-426d-a22f-16fbad9eff0b">
|
||||
<driver-ref>postgresql</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
||||
<jdbc-url>jdbc:postgresql://localhost:5432/todo_baggins</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
5014
.idea/dataSources/1658668c-c2b8-426d-a22f-16fbad9eff0b.xml
generated
Normal file
5014
.idea/dataSources/1658668c-c2b8-426d-a22f-16fbad9eff0b.xml
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
#n:todo_baggins
|
||||
@@ -0,0 +1,2 @@
|
||||
#n:information_schema
|
||||
!<md> [null, 0, null, null, -2147483648, -2147483648]
|
||||
@@ -0,0 +1,2 @@
|
||||
#n:pg_catalog
|
||||
!<md> [null, 0, null, null, -2147483648, -2147483648]
|
||||
@@ -0,0 +1,2 @@
|
||||
#n:public
|
||||
!<md> [785, 0, null, null, -2147483648, -2147483648]
|
||||
Binary file not shown.
6
.idea/jsLibraryMappings.xml
generated
Normal file
6
.idea/jsLibraryMappings.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="JavaScriptLibraryMappings">
|
||||
<includedPredefinedLibrary name="Node.js Core" />
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/todo-baggins.iml" filepath="$PROJECT_DIR$/.idea/todo-baggins.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/prettier.xml
generated
Normal file
8
.idea/prettier.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="PrettierConfiguration">
|
||||
<option name="myConfigurationMode" value="AUTOMATIC" />
|
||||
<option name="myRunOnSave" value="true" />
|
||||
<option name="myFilesPattern" value="**/*.{html,css,scss,js,ts,cjs,cts,mjs,mts,json,yaml}" />
|
||||
</component>
|
||||
</project>
|
||||
11
.idea/runConfigurations/dev.xml
generated
Normal file
11
.idea/runConfigurations/dev.xml
generated
Normal file
@@ -0,0 +1,11 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="dev" type="docker-deploy" factoryName="docker-compose.yml" server-name="Docker">
|
||||
<deployment type="docker-compose.yml">
|
||||
<settings>
|
||||
<option name="envFilePath" value="" />
|
||||
<option name="sourceFilePath" value="docker-compose-dev.yaml" />
|
||||
</settings>
|
||||
</deployment>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
8
.idea/sqldialects.xml
generated
Normal file
8
.idea/sqldialects.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/migrations/00000000000000_diesel_initial_setup/down.sql" dialect="GenericSQL" />
|
||||
<file url="file://$PROJECT_DIR$/migrations/00000000000000_diesel_initial_setup/up.sql" dialect="PostgreSQL" />
|
||||
<file url="PROJECT" dialect="PostgreSQL" />
|
||||
</component>
|
||||
</project>
|
||||
11
.idea/todo-baggins.iml
generated
Normal file
11
.idea/todo-baggins.iml
generated
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="EMPTY_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
12
.idea/vcs.xml
generated
Normal file
12
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CommitMessageInspectionProfile">
|
||||
<profile version="1.0">
|
||||
<inspection_tool class="CommitFormat" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="CommitNamingConvention" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
14
.idea/webResources.xml
generated
Normal file
14
.idea/webResources.xml
generated
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="WebResourcesPaths">
|
||||
<contentEntries>
|
||||
<entry url="file://$PROJECT_DIR$">
|
||||
<entryData>
|
||||
<resourceRoots>
|
||||
<path value="file://$PROJECT_DIR$/assets" />
|
||||
</resourceRoots>
|
||||
</entryData>
|
||||
</entry>
|
||||
</contentEntries>
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"lsp": {
|
||||
"rust-analyzer": {
|
||||
"initialization_options": {
|
||||
"cargo": {
|
||||
"features": ["server", "web"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
4181
Cargo.lock
generated
4181
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
66
Cargo.toml
66
Cargo.toml
@@ -1,54 +1,50 @@
|
||||
[package]
|
||||
name = "todo_baggins"
|
||||
name = "todo-baggins"
|
||||
version = "0.1.0"
|
||||
authors = ["Matouš Volf <git@matousvolf.cz>"]
|
||||
edition = "2024"
|
||||
authors = ["Matouš Volf <66163112+matous-volf@users.noreply.github.com>"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.42", features = ["serde", "unstable-locales"] }
|
||||
dioxus = { version = "0.7.2", features = ["fullstack", "router"] }
|
||||
# TODO: Remove this once https://github.com/DioxusLabs/dioxus/issues/4765 is resolved.
|
||||
dioxus-html = { version = "0.7.2", features = ["serialize"] }
|
||||
feruca = { version = "0.11.5" }
|
||||
serde = { version = "1.0.228" }
|
||||
serde_json = { version = "1.0.145" }
|
||||
serde_with = { version = "3.16.1", features = ["chrono_0_4"] }
|
||||
tracing = "0.1.43"
|
||||
unic-langid-impl = { version = "0.9.6", features = ["serde"] }
|
||||
validator = { version = "0.20.0", features = ["derive"] }
|
||||
chrono = { version = "0.4.38", features = ["serde", "unstable-locales"] }
|
||||
dioxus = { version = "0.6.0", features = ["fullstack", "router"] }
|
||||
feruca = { version = "0.10.0" }
|
||||
serde = { version = "1.0.208" }
|
||||
serde_json = { version = "1.0.125" }
|
||||
serde_with = { version = "3.9.0", features = ["chrono_0_4"] }
|
||||
tracing = "0.1.40"
|
||||
unic-langid-impl = { version = "0.9.5", features = ["serde"] }
|
||||
validator = { version = "0.19.0", features = ["derive"] }
|
||||
|
||||
diesel = { version = "2.3.4", features = [
|
||||
"chrono",
|
||||
"postgres",
|
||||
"postgres_backend",
|
||||
"serde_json",
|
||||
], optional = true }
|
||||
diesel_migrations = { version = "2.3.1", features = [
|
||||
"postgres",
|
||||
], optional = true }
|
||||
rand = { version = "0.9.2", optional = true }
|
||||
time = { version = "0.3.44", optional = true }
|
||||
tokio = { version = "1.48.0", optional = true }
|
||||
diesel = { version = "2.2.2", features = ["chrono", "postgres", "postgres_backend", "serde_json"], optional = true }
|
||||
diesel_migrations = { version = "2.2.0", features = ["postgres"], optional = true }
|
||||
dotenvy = { version = "0.15.7", optional = true }
|
||||
time = { version = "0.3.36", optional = true }
|
||||
|
||||
async-std = { version = "1.13.2", optional = true }
|
||||
dioxus-i18n = "0.5.0"
|
||||
voca_rs = "1.15.2"
|
||||
load-dotenv = "0.1.2"
|
||||
async-std = { version = "1.12.0" }
|
||||
dioxus-i18n = { version = "0.3.0" }
|
||||
dioxus-query = { version = "0.6.0" }
|
||||
voca_rs = { version = "1.15.2" }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
openssl = { version = "0.10", features = ["vendored"] }
|
||||
|
||||
[features]
|
||||
default = ["web"]
|
||||
web = ["dioxus/web", "dep:async-std"]
|
||||
mobile = ["dioxus/mobile", "dep:async-std"]
|
||||
default = ["mobile"]
|
||||
desktop = ["dioxus/desktop"]
|
||||
mobile = [
|
||||
"dioxus/mobile",
|
||||
]
|
||||
web = [
|
||||
"dioxus/web",
|
||||
]
|
||||
server = [
|
||||
"dioxus/server",
|
||||
"dep:diesel",
|
||||
"dep:diesel_migrations",
|
||||
"dep:rand",
|
||||
"dep:dotenvy",
|
||||
"dep:time",
|
||||
"dep:tokio",
|
||||
]
|
||||
|
||||
[profile]
|
||||
|
||||
29
Dioxus.toml
29
Dioxus.toml
@@ -1,18 +1,39 @@
|
||||
[application]
|
||||
|
||||
# App (Project) Name
|
||||
name = "todo-baggins"
|
||||
|
||||
# Dioxus App Default Platform
|
||||
# web, desktop, fullstack
|
||||
default_platform = "fullstack"
|
||||
|
||||
# `build` & `serve` dist path
|
||||
out_dir = "dist"
|
||||
|
||||
# resource (assets) file folder
|
||||
asset_dir = "assets"
|
||||
|
||||
[web.app]
|
||||
|
||||
# HTML title tag content
|
||||
title = "todo_baggins"
|
||||
title = "Todo Baggins"
|
||||
|
||||
[web.watcher]
|
||||
|
||||
# when watcher trigger, regenerate the `index.html`
|
||||
reload_html = true
|
||||
|
||||
# which files or dirs will be watcher monitoring
|
||||
watch_path = ["src", "assets"]
|
||||
|
||||
# include `assets` in web platform
|
||||
[web.resource]
|
||||
|
||||
# Additional CSS style files
|
||||
# CSS style file
|
||||
style = []
|
||||
|
||||
# Additional JavaScript files
|
||||
script = []
|
||||
# Javascript code file
|
||||
script = ["https://kit.fontawesome.com/3c1b409f8f.js"]
|
||||
|
||||
[web.resource.dev]
|
||||
|
||||
|
||||
1
assets/.gitignore
vendored
1
assets/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
/tailwind.css
|
||||
@@ -7,9 +7,8 @@
|
||||
"theme_color": "#27272a",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/assets/images/icon.png",
|
||||
"src": "/images/icon.png",
|
||||
"sizes": "any",
|
||||
"purpose": "maskable",
|
||||
"type": "image/png"
|
||||
}
|
||||
]
|
||||
|
||||
1
assets/styles/.gitignore
vendored
Normal file
1
assets/styles/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/tailwind_output.css
|
||||
@@ -12,12 +12,14 @@ services:
|
||||
- ./Cargo.toml:/srv/app/Cargo.toml
|
||||
- ./diesel.toml:/srv/app/diesel.toml
|
||||
- ./Dioxus.toml:/srv/app/Dioxus.toml
|
||||
- ./package.json:/srv/app/package.json
|
||||
- ./package-lock.json:/srv/app/package-lock.json
|
||||
restart: always
|
||||
ports: ["8000:8000"]
|
||||
depends_on: ["db"]
|
||||
|
||||
db:
|
||||
image: postgres:16.11-alpine3.23@sha256:a5074487380d4e686036ce61ed6f2d363939ae9a0c40123d1a9e3bb3a5f344b4
|
||||
image: postgres:16.4-bookworm
|
||||
volumes: ["db_data:/var/lib/postgresql/data"]
|
||||
ports: ["5432:5432"]
|
||||
environment:
|
||||
|
||||
@@ -10,7 +10,7 @@ services:
|
||||
depends_on: ["db"]
|
||||
|
||||
db:
|
||||
image: postgres:16.11-alpine3.23@sha256:a5074487380d4e686036ce61ed6f2d363939ae9a0c40123d1a9e3bb3a5f344b4
|
||||
image: postgres:16.4-bookworm
|
||||
volumes: ["db_data:/var/lib/postgresql/data"]
|
||||
networks:
|
||||
- default
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
FROM rust:1.92.0-bookworm@sha256:9676d0547a259997add8f5924eb6b959c589ed39055338e23b99aba7958d6d31
|
||||
FROM rust@sha256:a45bf1f5d9af0a23b26703b3500d70af1abff7f984a7abef5a104b42c02a292b
|
||||
|
||||
RUN useradd -m -u 1000 -s /bin/bash app_user
|
||||
RUN cargo install dioxus-cli diesel_cli \
|
||||
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||
nodejs=18.19.0+dfsg-6~deb12u2 \
|
||||
npm=9.2.0~ds1-1 \
|
||||
supervisor=4.2.5-1 \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN rustup target add wasm32-unknown-unknown
|
||||
|
||||
USER app_user
|
||||
|
||||
RUN cargo install --locked dioxus-cli --version 0.7.2 \
|
||||
&& cargo install --locked diesel_cli --version 2.3.4
|
||||
|
||||
COPY --chown=app_user . /srv/app
|
||||
COPY . /srv/app
|
||||
WORKDIR /srv/app
|
||||
|
||||
RUN npm install
|
||||
|
||||
COPY docker/dev/app/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
|
||||
|
||||
RUN chown -R 1000:1000 /srv/app \
|
||||
&& chown -R 1000:1000 /usr/local/cargo \
|
||||
&& mkdir -p /.local/share/dioxus \
|
||||
&& chown -R 1000:1000 /.local/share/dioxus
|
||||
|
||||
HEALTHCHECK CMD curl --fail -H "Accept: text/html" http://localhost:8000 || exit 1
|
||||
|
||||
CMD ["sleep", "infinity"]
|
||||
USER 1000:1000
|
||||
|
||||
CMD ["sh", "docker/dev/app/entrypoint.sh"]
|
||||
|
||||
3
docker/dev/app/entrypoint.sh
Executable file
3
docker/dev/app/entrypoint.sh
Executable file
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
|
||||
supervisord -c /etc/supervisor/conf.d/supervisord.conf
|
||||
23
docker/dev/app/supervisord.conf
Normal file
23
docker/dev/app/supervisord.conf
Normal file
@@ -0,0 +1,23 @@
|
||||
[supervisord]
|
||||
nodaemon=true
|
||||
logfile=/dev/null
|
||||
logfile_maxbytes=0
|
||||
pidfile=/dev/null
|
||||
|
||||
[program:npm]
|
||||
command=npm run watch
|
||||
directory=/srv/app
|
||||
autostart=true
|
||||
autorestart=true
|
||||
stdout_logfile=/dev/fd/1
|
||||
stdout_logfile_maxbytes=0
|
||||
redirect_stderr=true
|
||||
|
||||
# [program:dx]
|
||||
# command=dx serve --addr 0.0.0.0 --port 8000
|
||||
# directory=/srv/app
|
||||
# autostart=true
|
||||
# autorestart=true
|
||||
# stdout_logfile=/dev/fd/1
|
||||
# stdout_logfile_maxbytes=0
|
||||
# redirect_stderr=true
|
||||
@@ -1,58 +1,32 @@
|
||||
FROM rust:1.92.0-bookworm@sha256:9676d0547a259997add8f5924eb6b959c589ed39055338e23b99aba7958d6d31 AS builder
|
||||
FROM rust@sha256:a45bf1f5d9af0a23b26703b3500d70af1abff7f984a7abef5a104b42c02a292b AS builder
|
||||
|
||||
ARG ANDROID_NDK_VERSION=26.2.11394342
|
||||
ARG ANDROID_COMMAND_LINE_TOOLS_VERSION=13114758
|
||||
ARG ANDROID_COMMAND_LINE_TOOLS_SHA256=7ec965280a073311c339e571cd5de778b9975026cfcbe79f2b1cdcb1e15317ee
|
||||
ARG ANDROID_VERSION=34
|
||||
ARG ANDROID_BUILD_TOOLS_VERSION=34.0.0
|
||||
ARG ANDROID_BUNDLETOOL_VERSION=1.18.3
|
||||
ARG ANDROID_BUNDLETOOL_SHA256=a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29
|
||||
ENV ANDROID_SDK_ROOT=/opt/android-sdk
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
openjdk-17-jdk-headless=17.0.17+10-1~deb12u1 \
|
||||
&& curl -fsSL -o /tmp/cmdline-tools.zip "https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_COMMAND_LINE_TOOLS_VERSION}_latest.zip" \
|
||||
RUN cargo install dioxus-cli diesel_cli \
|
||||
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||
nodejs=18.19.0+dfsg-6~deb12u2 \
|
||||
npm=9.2.0~ds1-1 \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& cargo install --git https://github.com/diesel-rs/diesel --rev 2e85ba060d3d70ea605ea58a79b8a435749a7adc diesel_cli \
|
||||
&& cargo install --git https://github.com/DioxusLabs/dioxus --rev 8f8b58ea80ba0ec8057807bcd58fb609f7a5f2b1 dioxus-cli --features disable-telemetry \
|
||||
&& rustup target add aarch64-linux-android \
|
||||
&& mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" \
|
||||
&& curl -fsSL -o /tmp/cmdline-tools.zip "https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_COMMAND_LINE_TOOLS_VERSION}_latest.zip" \
|
||||
&& unzip -q /tmp/cmdline-tools.zip -d "$ANDROID_SDK_ROOT/cmdline-tools" \
|
||||
&& export PATH="$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools:$PATH" \
|
||||
&& mv "$ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools" "$ANDROID_SDK_ROOT/cmdline-tools/latest" \
|
||||
&& rm /tmp/cmdline-tools.zip \
|
||||
&& yes | sdkmanager --sdk_root="$ANDROID_SDK_ROOT" --licenses > /dev/null \
|
||||
&& sdkmanager --sdk_root="$ANDROID_SDK_ROOT" "platform-tools" "platforms;android-$ANDROID_VERSION" "build-tools;$ANDROID_BUILD_TOOLS_VERSION" "ndk;$ANDROID_NDK_VERSION" \
|
||||
&& curl -fsSL -o /tmp/bundletool-all.jar "https://github.com/google/bundletool/releases/download/$ANDROID_BUNDLETOOL_VERSION/bundletool-all-${ANDROID_BUNDLETOOL_VERSION}.jar" \
|
||||
&& echo "$ANDROID_BUNDLETOOL_SHA256 /tmp/bundletool-all.jar" | sha256sum -c - \
|
||||
&& keytool -genkeypair -noprompt -keystore /tmp/android_keystore.jks -alias key -keyalg RSA -keysize 2048 -validity 3660 -dname "CN=" -storepass 123456 -keypass 123456
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY . /srv/app
|
||||
WORKDIR /srv/app
|
||||
|
||||
RUN export ANDROID_HOME="$ANDROID_SDK_ROOT" \
|
||||
&& export ANDROID_NDK_HOME="$ANDROID_SDK_ROOT/ndk/$ANDROID_NDK_VERSION" \
|
||||
&& dx bundle --release \
|
||||
&& dx bundle --platform android --target aarch64-linux-android --release \
|
||||
&& java -jar /tmp/bundletool-all.jar build-apks --bundle=/srv/app/target/dx/todo_baggins/release/android/app/app/build/outputs/bundle/release/TodoBaggins-aarch64-linux-android.aab --output=/tmp/todo_baggins.apks --mode=universal --ks=/tmp/android_keystore.jks --ks-key-alias=key --ks-pass=pass:123456 \
|
||||
&& mkdir -p /srv/app/bundle/android \
|
||||
&& unzip -qp /tmp/todo_baggins.apks universal.apk > /srv/app/bundle/android/todo_baggins.apk
|
||||
RUN npm install \
|
||||
&& npm run build \
|
||||
&& dx build --release
|
||||
|
||||
FROM debian:bookworm@sha256:b877a1a3fdf02469440f1768cf69c9771338a875b7add5e80c45b756c92ac20a AS runner
|
||||
FROM debian@sha256:b877a1a3fdf02469440f1768cf69c9771338a875b7add5e80c45b756c92ac20a AS runner
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libpq5=15.10-0+deb12u1 \
|
||||
&& apt-get install -y --no-install-recommends libpq5=15.8-0+deb12u1 \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /srv/app/target/dx/todo_baggins/release/web /srv/app/web
|
||||
COPY --from=builder /srv/app/bundle/android /srv/app/android
|
||||
COPY --from=builder /srv/app/target/dx/todo-baggins/release/web /srv/app
|
||||
COPY .env /srv/app/.env
|
||||
|
||||
RUN chown -R 1000:1000 /srv/app/web
|
||||
RUN chown -R 1000:1000 /srv/app
|
||||
|
||||
WORKDIR /srv/app/web
|
||||
WORKDIR /srv/app
|
||||
|
||||
HEALTHCHECK CMD curl --fail -H "Accept: text/html" http://localhost || exit 1
|
||||
|
||||
@@ -60,4 +34,4 @@ USER 1000:1000
|
||||
|
||||
ENV IP="0.0.0.0"
|
||||
ENV PORT="80"
|
||||
CMD ["./todo_baggins"]
|
||||
CMD ["./server"]
|
||||
|
||||
3013
package-lock.json
generated
Normal file
3013
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,11 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"tailwindcss": "3.4.10"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tailwindcss -c src/styles/tailwind.config.js -i src/styles/tailwind.css -o assets/styles/tailwind_output.css",
|
||||
"watch": "npm run build -- --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"htmlhint": "1.1.4",
|
||||
"markdownlint-cli": "0.43.0",
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
mkdir -p ../bundle \
|
||||
&& docker compose -f docker-compose-prod.yaml cp app:/srv/app/android bundle
|
||||
@@ -1,27 +1,28 @@
|
||||
use crate::internationalization::get_language_identifier;
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::route::Route;
|
||||
use crate::server::internationalization::get_language_identifier;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::prelude::*;
|
||||
use dioxus_i18n::unic_langid::langid;
|
||||
use dioxus_query::prelude::use_init_query_client;
|
||||
|
||||
const FAVICON: Asset = asset!("/assets/favicon.ico");
|
||||
const TAILWIND_CSS: Asset = asset!("/assets/tailwind.css");
|
||||
#[used]
|
||||
static FONTS_DIRECTORY: Asset = asset!(
|
||||
"/assets/fonts",
|
||||
AssetOptions::builder().with_hash_suffix(false)
|
||||
);
|
||||
const TAILWIND_CSS: Asset = asset!("/assets/styles/tailwind_output.css");
|
||||
const FONTS_CSS: Asset = asset!("/assets/styles/fonts.css");
|
||||
const INPUT_NUMBER_ARROWS_CSS: Asset = asset!("/assets/styles/input_number_arrows.css");
|
||||
const INPUT_RANGE_CSS: Asset = asset!("/assets/styles/input_range.css");
|
||||
const MANIFEST: Asset = asset!("/assets/manifest.json");
|
||||
|
||||
#[component]
|
||||
pub(crate) fn App() -> Element {
|
||||
use_init_query_client::<QueryValue, QueryErrors, QueryKey>();
|
||||
|
||||
let language_identifier = use_server_future(get_language_identifier)?
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
use_init_i18n(|| {
|
||||
I18nConfig::new(get_language_identifier())
|
||||
I18nConfig::new(language_identifier)
|
||||
.with_locale(Locale::new_static(
|
||||
langid!("cs-CZ"),
|
||||
include_str!("../internationalization/cs_cz.ftl"),
|
||||
@@ -34,15 +35,13 @@ pub(crate) fn App() -> Element {
|
||||
|
||||
rsx! {
|
||||
document::Link { rel: "icon", href: FAVICON }
|
||||
document::Stylesheet { href: TAILWIND_CSS }
|
||||
document::Stylesheet { href: FONTS_CSS }
|
||||
document::Stylesheet { href: INPUT_NUMBER_ARROWS_CSS }
|
||||
document::Stylesheet { href: INPUT_RANGE_CSS }
|
||||
document::Link { rel: "manifest", href: MANIFEST, crossorigin: "use-credentials" }
|
||||
document::Script { src: "https://kit.fontawesome.com/3c1b409f8f.js" }
|
||||
document::Link { rel: "stylesheet", href: TAILWIND_CSS }
|
||||
document::Link { rel: "stylesheet", href: FONTS_CSS }
|
||||
document::Link { rel: "stylesheet", href: INPUT_NUMBER_ARROWS_CSS }
|
||||
document::Link { rel: "stylesheet", href: INPUT_RANGE_CSS }
|
||||
|
||||
div {
|
||||
class: "min-h-screen pt-4 pb-36 flex flex-col text-zinc-200 bg-zinc-800",
|
||||
class: "min-h-screen text-zinc-200 bg-zinc-800 pt-4 pb-36",
|
||||
Router::<Route> {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::components::error_boundary_message::ErrorBoundaryMessage;
|
||||
use crate::components::navigation::Navigation;
|
||||
use crate::components::project_form::ProjectForm;
|
||||
use crate::components::task_form::TaskForm;
|
||||
@@ -24,7 +23,6 @@ pub(crate) fn BottomPanel(display_form: Signal<bool>) -> Element {
|
||||
} else {
|
||||
spawn(async move {
|
||||
// Necessary for a smooth – not instant – height transition.
|
||||
#[cfg(not(feature = "server"))]
|
||||
async_std::task::sleep(std::time::Duration::from_millis(500)).await;
|
||||
/* The check is necessary for the situation when the user expands the panel while
|
||||
it is being closed. */
|
||||
@@ -38,7 +36,7 @@ pub(crate) fn BottomPanel(display_form: Signal<bool>) -> Element {
|
||||
rsx! {
|
||||
div {
|
||||
class: format!(
|
||||
"flex flex-col pointer-events-auto bg-zinc-700/50 rounded-t-xl border-t-zinc-600 border-t backdrop-blur drop-shadow-[0_-5px_10px_rgba(0,0,0,0.2)] transition-[height] duration-[500ms] ease-[cubic-bezier(0.79,0.14,0.15,0.86)] overflow-y-scroll {}",
|
||||
"pointer-events-auto bg-zinc-700/50 rounded-t-xl border-t-zinc-600 border-t backdrop-blur drop-shadow-[0_-5px_10px_rgba(0,0,0,0.2)] transition-[height] duration-[500ms] ease-[cubic-bezier(0.79,0.14,0.15,0.86)] overflow-y-scroll {}",
|
||||
match (display_form(), current_route, navigation_expanded()) {
|
||||
(false, _, false) => "h-[66px]",
|
||||
(false, _, true) => "h-[130px]",
|
||||
@@ -47,24 +45,22 @@ pub(crate) fn BottomPanel(display_form: Signal<bool>) -> Element {
|
||||
}
|
||||
),
|
||||
if expanded() {
|
||||
ErrorBoundaryMessage {
|
||||
match current_route {
|
||||
Route::ProjectsPage => rsx! {
|
||||
ProjectForm {
|
||||
project: project_being_edited(),
|
||||
on_successful_submit: move |_| {
|
||||
display_form.set(false);
|
||||
project_being_edited.set(None);
|
||||
}
|
||||
match current_route {
|
||||
Route::ProjectsPage => rsx! {
|
||||
ProjectForm {
|
||||
project: project_being_edited(),
|
||||
on_successful_submit: move |_| {
|
||||
display_form.set(false);
|
||||
project_being_edited.set(None);
|
||||
}
|
||||
},
|
||||
_ => rsx! {
|
||||
TaskForm {
|
||||
task: task_being_edited(),
|
||||
on_successful_submit: move |_| {
|
||||
display_form.set(false);
|
||||
task_being_edited.set(None);
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => rsx! {
|
||||
TaskForm {
|
||||
task: task_being_edited(),
|
||||
on_successful_submit: move |_| {
|
||||
display_form.set(false);
|
||||
task_being_edited.set(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
use crate::components::task_list::TaskList;
|
||||
use crate::hooks::use_tasks_with_subtasks_in_category;
|
||||
use crate::internationalization::LocaleFromLanguageIdentifier;
|
||||
use crate::models::category::Category;
|
||||
use crate::models::task::TaskWithSubtasks;
|
||||
use chrono::{Datelike, Local};
|
||||
use dioxus::core_macro::{component, rsx};
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::prelude::i18n;
|
||||
use dioxus_i18n::t;
|
||||
|
||||
const CALENDAR_LENGTH_DAYS: usize = 366 * 3;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryCalendarTaskList() -> Element {
|
||||
let today_date = Local::now().date_naive();
|
||||
let tasks = use_tasks_with_subtasks_in_category(Category::Calendar {
|
||||
date: today_date,
|
||||
reoccurrence: None,
|
||||
time: None,
|
||||
})?();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "pt-4 flex flex-col gap-8",
|
||||
for date_current in today_date.iter_days().take(CALENDAR_LENGTH_DAYS) {
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
div {
|
||||
class: "pt-1",
|
||||
{
|
||||
date_current.format_localized(t!(
|
||||
if date_current.year() == Local::now().year() {
|
||||
"date-weekday-format"
|
||||
} else {
|
||||
"date-weekday-year-format"
|
||||
}
|
||||
).as_str(),
|
||||
LocaleFromLanguageIdentifier::from(
|
||||
&i18n().language()
|
||||
).into()
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
TaskList {
|
||||
tasks: tasks.iter().filter(|task| {
|
||||
if let Category::Calendar { date, .. }
|
||||
= task.task.category {
|
||||
date == date_current
|
||||
} else {
|
||||
panic!("Unexpected category.");
|
||||
}
|
||||
}).cloned().collect::<Vec<TaskWithSubtasks>>()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ pub(crate) fn CategoryInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg grow basis-0 {} cursor-pointer",
|
||||
"py-2 rounded-lg grow basis-0 {}",
|
||||
if selected_category() == Category::SomedayMaybe { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub(crate) fn CategoryInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg grow basis-0 {} cursor-pointer",
|
||||
"py-2 rounded-lg grow basis-0 {}",
|
||||
if selected_category() == Category::LongTerm { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub(crate) fn CategoryInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg grow basis-0 {} cursor-pointer",
|
||||
"py-2 rounded-lg grow basis-0 {}",
|
||||
if let Category::WaitingFor(_) = selected_category() { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
),
|
||||
@@ -56,7 +56,7 @@ pub(crate) fn CategoryInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg grow basis-0 {} cursor-pointer",
|
||||
"py-2 rounded-lg grow basis-0 {}",
|
||||
if selected_category() == Category::NextSteps { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub(crate) fn CategoryInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg grow basis-0 {} cursor-pointer",
|
||||
"py-2 rounded-lg grow basis-0 {}",
|
||||
if let Category::Calendar { .. } = selected_category() { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
),
|
||||
@@ -88,7 +88,7 @@ pub(crate) fn CategoryInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg grow basis-0 {} cursor-pointer",
|
||||
"py-2 rounded-lg grow basis-0 {}",
|
||||
if selected_category() == Category::Inbox { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
),
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
use crate::components::task_list::TaskList;
|
||||
use crate::components::task_list_item::TaskListItem;
|
||||
use crate::hooks::use_tasks_with_subtasks_in_category;
|
||||
use crate::internationalization::LocaleFromLanguageIdentifier;
|
||||
use crate::models::category::Category;
|
||||
use crate::models::task::TaskWithSubtasks;
|
||||
use chrono::Local;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::t;
|
||||
use dioxus_i18n::use_i18n::i18n;
|
||||
use voca_rs::Voca;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryTodayTaskList() -> Element {
|
||||
let today_date = Local::now().date_naive();
|
||||
let calendar_tasks = use_tasks_with_subtasks_in_category(Category::Calendar {
|
||||
date: today_date,
|
||||
reoccurrence: None,
|
||||
time: None,
|
||||
})?();
|
||||
let today_tasks = calendar_tasks
|
||||
.iter()
|
||||
.filter(|task| {
|
||||
if let Category::Calendar { date, .. } = task.task.category {
|
||||
date == today_date
|
||||
} else {
|
||||
panic!("Unexpected category.");
|
||||
}
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<TaskWithSubtasks>>();
|
||||
let overdue_tasks = calendar_tasks
|
||||
.iter()
|
||||
.filter(|task| {
|
||||
if let Category::Calendar { date, .. } = task.task.category {
|
||||
date < today_date
|
||||
} else {
|
||||
panic!("Unexpected category.");
|
||||
}
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<TaskWithSubtasks>>();
|
||||
let long_term_tasks = use_tasks_with_subtasks_in_category(Category::LongTerm)?();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "pt-4 flex flex-col gap-8",
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
i {
|
||||
class: "fa-solid fa-water text-xl w-6 text-center"
|
||||
}
|
||||
div {
|
||||
class: "mt-1",
|
||||
{t!("long-term")._upper_first()}
|
||||
}
|
||||
}
|
||||
div {
|
||||
for task in long_term_tasks {
|
||||
div {
|
||||
key: "{task.task.id}",
|
||||
class: format!(
|
||||
"px-8 pt-5 {} flex flex-row gap-4",
|
||||
if task.task.deadline.is_some() {
|
||||
"pb-0.5"
|
||||
} else {
|
||||
"pb-5"
|
||||
}
|
||||
),
|
||||
TaskListItem {
|
||||
task: task.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !overdue_tasks.is_empty() {
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
i {
|
||||
class: "fa-solid fa-calendar-xmark text-xl w-6 text-center"
|
||||
}
|
||||
div {
|
||||
class: "mt-1",
|
||||
{t!("overdue")._upper_first()}
|
||||
}
|
||||
}
|
||||
TaskList {
|
||||
tasks: overdue_tasks,
|
||||
class: "pb-3"
|
||||
}
|
||||
}
|
||||
}
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
i {
|
||||
class: "fa-solid fa-calendar-check text-xl w-6 text-center"
|
||||
}
|
||||
div {
|
||||
class: "mt-1",
|
||||
{
|
||||
let format = t!("date-weekday-format");
|
||||
let today_date = today_date.format_localized(
|
||||
format.as_str(),
|
||||
LocaleFromLanguageIdentifier::from(
|
||||
&i18n().language()
|
||||
).into()
|
||||
).to_string();
|
||||
format!(
|
||||
"{} – {}",
|
||||
t!("today")._upper_first(),
|
||||
if t!("weekday-lowercase-first").parse().unwrap() {
|
||||
today_date._lower_first()
|
||||
} else {
|
||||
today_date
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
TaskList {
|
||||
tasks: today_tasks
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn ErrorBoundaryMessage(children: Element, class: Option<String>) -> Element {
|
||||
rsx! {
|
||||
ErrorBoundary {
|
||||
handle_error: |_| {
|
||||
rsx! {
|
||||
div {
|
||||
class: "grow flex flex-col justify-center items-center",
|
||||
div {
|
||||
i {
|
||||
class: "text-3xl fa-solid fa-triangle-exclamation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
div {
|
||||
class,
|
||||
{children}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ pub(crate) fn FormOpenButton(opened: Signal<bool>) -> Element {
|
||||
|
||||
rsx! {
|
||||
button {
|
||||
class: "pointer-events-auto m-4 py-3 px-5 self-end text-center bg-zinc-300/50 rounded-xl border-t-zinc-200 border-t backdrop-blur drop-shadow-[0_-5px_10px_rgba(0,0,0,0.2)] text-2xl text-zinc-200 cursor-pointer",
|
||||
class: "pointer-events-auto m-4 py-3 px-5 self-end text-center bg-zinc-300/50 rounded-xl border-t-zinc-200 border-t backdrop-blur drop-shadow-[0_-5px_10px_rgba(0,0,0,0.2)] text-2xl text-zinc-200",
|
||||
onclick: move |_| {
|
||||
if opened() {
|
||||
project_being_edited.set(None);
|
||||
|
||||
8
src/components/home.rs
Normal file
8
src/components/home.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn Home() -> Element {
|
||||
rsx! {}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn Main() -> Element {
|
||||
pub(crate) fn Layout() -> Element {
|
||||
let mut display_form = use_signal(|| false);
|
||||
let project_being_edited =
|
||||
use_context_provider::<Signal<Option<Project>>>(|| Signal::new(None));
|
||||
@@ -20,21 +20,7 @@ pub(crate) fn Main() -> Element {
|
||||
});
|
||||
|
||||
rsx! {
|
||||
SuspenseBoundary {
|
||||
fallback: |_| {
|
||||
rsx! {
|
||||
div {
|
||||
class: "grow flex flex-col justify-center items-center",
|
||||
div {
|
||||
i {
|
||||
class: "text-3xl fa-solid fa-cog fa-spin"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Outlet::<Route> {}
|
||||
}
|
||||
Outlet::<Route> {}
|
||||
StickyBottom {
|
||||
FormOpenButton {
|
||||
opened: display_form,
|
||||
@@ -1,15 +1,13 @@
|
||||
pub(crate) mod app;
|
||||
pub(crate) mod bottom_panel;
|
||||
pub(crate) mod category_calendar_task_list;
|
||||
pub(crate) mod category_input;
|
||||
pub(crate) mod category_today_task_list;
|
||||
pub(crate) mod error_boundary_message;
|
||||
pub(crate) mod form_open_button;
|
||||
pub(crate) mod home;
|
||||
pub(crate) mod layout;
|
||||
pub(crate) mod navigation;
|
||||
pub(crate) mod navigation_item;
|
||||
pub(crate) mod pages;
|
||||
pub(crate) mod project_form;
|
||||
pub(crate) mod project_list;
|
||||
pub(crate) mod project_select;
|
||||
pub(crate) mod reoccurrence_input;
|
||||
pub(crate) mod sticky_bottom;
|
||||
pub(crate) mod subtasks_form;
|
||||
|
||||
@@ -9,7 +9,7 @@ pub(crate) fn Navigation(expanded: Signal<bool>) -> Element {
|
||||
class: "grid grid-cols-5 justify-stretch",
|
||||
button {
|
||||
class: format!(
|
||||
"py-4 text-center text-2xl {} cursor-pointer",
|
||||
"py-4 text-center text-2xl {}",
|
||||
if expanded() { "text-zinc-200" }
|
||||
else { "text-zinc-500" }
|
||||
),
|
||||
|
||||
84
src/components/pages/category_calendar_page.rs
Normal file
84
src/components/pages/category_calendar_page.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use crate::components::task_list::TaskList;
|
||||
use crate::internationalization::LocaleFromLanguageIdentifier;
|
||||
use crate::models::category::Category;
|
||||
use crate::models::task::TaskWithSubtasks;
|
||||
use crate::query::tasks::use_tasks_with_subtasks_in_category_query;
|
||||
use crate::query::QueryValue;
|
||||
use chrono::{Datelike, Local};
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::prelude::i18n;
|
||||
use dioxus_i18n::t;
|
||||
use dioxus_query::prelude::QueryResult;
|
||||
|
||||
const CALENDAR_LENGTH_DAYS: usize = 366 * 3;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryCalendarPage() -> Element {
|
||||
let tasks = use_tasks_with_subtasks_in_category_query(Category::Calendar {
|
||||
date: Local::now().date_naive(),
|
||||
reoccurrence: None,
|
||||
time: None,
|
||||
});
|
||||
let tasks_query_result = tasks.result();
|
||||
|
||||
rsx! {
|
||||
match tasks_query_result.value() {
|
||||
QueryResult::Ok(QueryValue::TasksWithSubtasks(tasks))
|
||||
| QueryResult::Loading(Some(QueryValue::TasksWithSubtasks(tasks))) => {
|
||||
let today_date = Local::now().date_naive();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "pt-4 flex flex-col gap-8",
|
||||
for date_current in today_date.iter_days().take(CALENDAR_LENGTH_DAYS) {
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
div {
|
||||
class: "pt-1",
|
||||
{
|
||||
date_current.format_localized(t!(
|
||||
if date_current.year() == Local::now().year() {
|
||||
"date-weekday-format"
|
||||
} else {
|
||||
"date-weekday-year-format"
|
||||
}
|
||||
).as_str(),
|
||||
LocaleFromLanguageIdentifier::from(
|
||||
&i18n().language()
|
||||
).into()
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
TaskList {
|
||||
tasks: tasks.iter().filter(|task| {
|
||||
if let Category::Calendar { date, .. }
|
||||
= task.task().category() {
|
||||
*date == date_current
|
||||
} else {
|
||||
panic!("Unexpected category.");
|
||||
}
|
||||
}).cloned().collect::<Vec<TaskWithSubtasks>>()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_done_page.rs
Normal file
14
src/components/pages/category_done_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryDonePage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::Done,
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_inbox_page.rs
Normal file
14
src/components/pages/category_inbox_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryInboxPage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::Inbox,
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_long_term_page.rs
Normal file
14
src/components/pages/category_long_term_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryLongTermPage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::LongTerm,
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_next_steps_page.rs
Normal file
14
src/components/pages/category_next_steps_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryNextStepsPage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::NextSteps,
|
||||
}
|
||||
}
|
||||
}
|
||||
33
src/components/pages/category_page.rs
Normal file
33
src/components/pages/category_page.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use crate::components::task_list::TaskList;
|
||||
use crate::models::category::Category;
|
||||
use crate::query::tasks::use_tasks_with_subtasks_in_category_query;
|
||||
use crate::query::QueryValue;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_query::prelude::QueryResult;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryPage(category: Category) -> Element {
|
||||
let tasks_query = use_tasks_with_subtasks_in_category_query(category);
|
||||
let tasks_query_result = tasks_query.result();
|
||||
|
||||
match tasks_query_result.value() {
|
||||
QueryResult::Ok(QueryValue::TasksWithSubtasks(tasks))
|
||||
| QueryResult::Loading(Some(QueryValue::TasksWithSubtasks(tasks))) => rsx! {
|
||||
TaskList {
|
||||
tasks: tasks.clone(),
|
||||
class: "pb-36"
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}"),
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_someday_maybe_page.rs
Normal file
14
src/components/pages/category_someday_maybe_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategorySomedayMaybePage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::SomedayMaybe,
|
||||
}
|
||||
}
|
||||
}
|
||||
166
src/components/pages/category_today_page.rs
Normal file
166
src/components/pages/category_today_page.rs
Normal file
@@ -0,0 +1,166 @@
|
||||
use crate::components::task_list::TaskList;
|
||||
use crate::components::task_list_item::TaskListItem;
|
||||
use crate::internationalization::LocaleFromLanguageIdentifier;
|
||||
use crate::models::category::Category;
|
||||
use crate::models::task::TaskWithSubtasks;
|
||||
use crate::query::tasks::use_tasks_with_subtasks_in_category_query;
|
||||
use crate::query::QueryValue;
|
||||
use chrono::Local;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::t;
|
||||
use dioxus_i18n::use_i18n::i18n;
|
||||
use dioxus_query::prelude::QueryResult;
|
||||
use voca_rs::Voca;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryTodayPage() -> Element {
|
||||
let today_date = Local::now().date_naive();
|
||||
|
||||
let calendar_tasks_query = use_tasks_with_subtasks_in_category_query(Category::Calendar {
|
||||
date: today_date,
|
||||
reoccurrence: None,
|
||||
time: None,
|
||||
});
|
||||
let calendar_tasks_query_result = calendar_tasks_query.result();
|
||||
|
||||
let long_term_tasks_query = use_tasks_with_subtasks_in_category_query(Category::LongTerm);
|
||||
let long_term_tasks_query_result = long_term_tasks_query.result();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "pt-4 flex flex-col gap-8",
|
||||
match long_term_tasks_query_result.value() {
|
||||
QueryResult::Ok(QueryValue::TasksWithSubtasks(tasks))
|
||||
| QueryResult::Loading(Some(QueryValue::TasksWithSubtasks(tasks))) => {
|
||||
let mut tasks = tasks.clone();
|
||||
tasks.sort();
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
i {
|
||||
class: "fa-solid fa-water text-xl w-6 text-center"
|
||||
}
|
||||
div {
|
||||
class: "mt-1",
|
||||
{t!("long-term")._upper_first()}
|
||||
}
|
||||
}
|
||||
div {
|
||||
for task in tasks {
|
||||
div {
|
||||
key: "{task.task().id()}",
|
||||
class: format!(
|
||||
"px-8 pt-5 {} flex flex-row gap-4",
|
||||
if task.task().deadline().is_some() {
|
||||
"pb-0.5"
|
||||
} else {
|
||||
"pb-5"
|
||||
}
|
||||
),
|
||||
TaskListItem {
|
||||
task: task.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}")
|
||||
}
|
||||
match calendar_tasks_query_result.value() {
|
||||
QueryResult::Ok(QueryValue::TasksWithSubtasks(tasks))
|
||||
| QueryResult::Loading(Some(QueryValue::TasksWithSubtasks(tasks))) => {
|
||||
let today_tasks = tasks.iter().filter(|task| {
|
||||
if let Category::Calendar { date, .. } = task.task().category() {
|
||||
*date == today_date
|
||||
} else {
|
||||
panic!("Unexpected category.");
|
||||
}
|
||||
}).cloned().collect::<Vec<TaskWithSubtasks>>();
|
||||
let overdue_tasks = tasks.iter().filter(|task| {
|
||||
if let Category::Calendar { date, .. } = task.task().category() {
|
||||
*date < today_date
|
||||
} else {
|
||||
panic!("Unexpected category.");
|
||||
}
|
||||
}).cloned().collect::<Vec<TaskWithSubtasks>>();
|
||||
|
||||
rsx! {
|
||||
if !overdue_tasks.is_empty() {
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
i {
|
||||
class: "fa-solid fa-calendar-xmark text-xl w-6 text-center"
|
||||
}
|
||||
div {
|
||||
class: "mt-1",
|
||||
{t!("overdue")._upper_first()}
|
||||
}
|
||||
}
|
||||
TaskList {
|
||||
tasks: overdue_tasks,
|
||||
class: "pb-3"
|
||||
}
|
||||
}
|
||||
}
|
||||
div {
|
||||
class: "flex flex-col gap-4",
|
||||
div {
|
||||
class: "px-8 flex flex-row items-center gap-2 font-bold",
|
||||
i {
|
||||
class: "fa-solid fa-calendar-check text-xl w-6 text-center"
|
||||
}
|
||||
div {
|
||||
class: "mt-1",
|
||||
{
|
||||
let format = t!("date-weekday-format");
|
||||
let today_date = today_date.format_localized(
|
||||
format.as_str(),
|
||||
LocaleFromLanguageIdentifier::from(
|
||||
&i18n().language()
|
||||
).into()
|
||||
).to_string();
|
||||
format!(
|
||||
"{} – {}",
|
||||
t!("today")._upper_first(),
|
||||
if t!("weekday-lowercase-first").parse().unwrap() {
|
||||
today_date._lower_first()
|
||||
} else {
|
||||
today_date
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
TaskList {
|
||||
tasks: today_tasks
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_trash_page.rs
Normal file
14
src/components/pages/category_trash_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryTrashPage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::Trash,
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/components/pages/category_waiting_for_page.rs
Normal file
14
src/components/pages/category_waiting_for_page.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::components::pages::category_page::CategoryPage;
|
||||
use crate::models::category::Category;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn CategoryWaitingForPage() -> Element {
|
||||
rsx! {
|
||||
CategoryPage {
|
||||
category: Category::WaitingFor(String::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,6 @@ use dioxus::prelude::*;
|
||||
#[component]
|
||||
pub(crate) fn NotFoundPage(route: Vec<String>) -> Element {
|
||||
rsx! {
|
||||
"404"
|
||||
{"404"}
|
||||
}
|
||||
}
|
||||
48
src/components/pages/projects_page.rs
Normal file
48
src/components/pages/projects_page.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use crate::models::project::Project;
|
||||
use crate::query::projects::use_projects_query;
|
||||
use crate::query::QueryValue;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_query::prelude::QueryResult;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn ProjectsPage() -> Element {
|
||||
let projects_query = use_projects_query();
|
||||
let mut project_being_edited = use_context::<Signal<Option<Project>>>();
|
||||
|
||||
rsx! {
|
||||
match projects_query.result().value() {
|
||||
QueryResult::Ok(QueryValue::Projects(projects))
|
||||
| QueryResult::Loading(Some(QueryValue::Projects(projects))) => {
|
||||
let mut projects = projects.clone();
|
||||
projects.sort();
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col",
|
||||
for project in projects {
|
||||
div {
|
||||
key: "{project.id()}",
|
||||
class: format!(
|
||||
"px-8 py-4 select-none {}",
|
||||
if project_being_edited().is_some_and(|p| p.id() == project.id()) {
|
||||
"bg-zinc-700"
|
||||
} else { "" }
|
||||
),
|
||||
onclick: move |_| project_being_edited.set(Some(project.clone())),
|
||||
{project.title()}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,33 @@
|
||||
use crate::models::project::Project;
|
||||
use crate::models::project::{NewProject, Project};
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::server::projects::{create_project, delete_project, edit_project};
|
||||
use dioxus::core_macro::{component, rsx};
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_query::prelude::use_query_client;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn ProjectForm(
|
||||
project: Option<Project>,
|
||||
on_successful_submit: EventHandler<()>,
|
||||
) -> Element {
|
||||
let query_client = use_query_client::<QueryValue, QueryErrors, QueryKey>();
|
||||
let project_for_submit = project.clone();
|
||||
|
||||
rsx! {
|
||||
form {
|
||||
onsubmit: move |event| {
|
||||
event.prevent_default();
|
||||
let project = project_for_submit.clone();
|
||||
async move {
|
||||
let new_project = event.parsed_values().unwrap();
|
||||
let new_project = NewProject::new(
|
||||
event.values().get("title").unwrap().as_value()
|
||||
);
|
||||
if let Some(project) = project {
|
||||
let _ = edit_project(project.id, new_project).await;
|
||||
let _ = edit_project(project.id(), new_project).await;
|
||||
} else {
|
||||
let _ = create_project(new_project).await;
|
||||
}
|
||||
query_client.invalidate_queries(&[QueryKey::Projects]);
|
||||
on_successful_submit.call(());
|
||||
}
|
||||
},
|
||||
@@ -38,7 +44,7 @@ pub(crate) fn ProjectForm(
|
||||
input {
|
||||
name: "title",
|
||||
required: true,
|
||||
initial_value: project.as_ref().map(|project| project.title.to_owned()),
|
||||
initial_value: project.as_ref().map(|project| project.title().to_owned()),
|
||||
r#type: "text",
|
||||
class: "py-2 px-3 grow bg-zinc-800/50 rounded-lg",
|
||||
id: "input_title"
|
||||
@@ -48,12 +54,13 @@ pub(crate) fn ProjectForm(
|
||||
class: "flex flex-row justify-between mt-auto",
|
||||
button {
|
||||
r#type: "button",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg cursor-pointer",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg",
|
||||
onclick: move |_| {
|
||||
let project = project.clone();
|
||||
async move {
|
||||
if let Some(project) = project {
|
||||
let _ = delete_project(project.id).await;
|
||||
let _ = delete_project(project.id()).await;
|
||||
query_client.invalidate_queries(&[QueryKey::Projects]);
|
||||
}
|
||||
on_successful_submit.call(());
|
||||
}
|
||||
@@ -64,7 +71,7 @@ pub(crate) fn ProjectForm(
|
||||
}
|
||||
button {
|
||||
r#type: "submit",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg cursor-pointer",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg",
|
||||
i {
|
||||
class: "fa-solid fa-floppy-disk"
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
use crate::{hooks::use_projects, models::project::Project};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn ProjectList() -> Element {
|
||||
let projects = use_projects()?();
|
||||
let mut project_being_edited = use_context::<Signal<Option<Project>>>();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col",
|
||||
for project in projects {
|
||||
div {
|
||||
key: "{project.id}",
|
||||
class: format!(
|
||||
"px-8 py-4 select-none {}",
|
||||
if project_being_edited().is_some_and(|p| p.id == project.id) {
|
||||
"bg-zinc-700"
|
||||
} else { "" }
|
||||
),
|
||||
onclick: move |_| project_being_edited.set(Some(project.clone())),
|
||||
{project.title.clone()}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use crate::hooks::use_projects;
|
||||
use dioxus::core_macro::{component, rsx};
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::t;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn ProjectSelect(initial_selected_id: Option<i32>) -> Element {
|
||||
let projects = use_projects()?();
|
||||
rsx! {
|
||||
select {
|
||||
name: "project_id",
|
||||
class: "px-3.5 py-2.5 bg-zinc-800/50 rounded-lg grow cursor-pointer",
|
||||
id: "input_project",
|
||||
option {
|
||||
value: 0,
|
||||
{t!("none")}
|
||||
},
|
||||
for project in projects {
|
||||
option {
|
||||
value: project.id.to_string(),
|
||||
initial_selected: initial_selected_id.is_some_and(
|
||||
|id| id == project.id
|
||||
),
|
||||
{project.title}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ pub(crate) fn ReoccurrenceIntervalInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg {} {} cursor-pointer",
|
||||
"py-2 rounded-lg {} {}",
|
||||
class_buttons.unwrap_or(""),
|
||||
if reoccurrence_interval().is_none() { "bg-zinc-500/50" }
|
||||
else { "bg-zinc-800/50" }
|
||||
@@ -27,7 +27,7 @@ pub(crate) fn ReoccurrenceIntervalInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg {} {} cursor-pointer",
|
||||
"py-2 rounded-lg {} {}",
|
||||
class_buttons.unwrap_or(""),
|
||||
if let Some(ReoccurrenceInterval::Day) = reoccurrence_interval()
|
||||
{ "bg-zinc-500/50" }
|
||||
@@ -43,7 +43,7 @@ pub(crate) fn ReoccurrenceIntervalInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg {} {} cursor-pointer",
|
||||
"py-2 rounded-lg {} {}",
|
||||
class_buttons.unwrap_or(""),
|
||||
if let Some(ReoccurrenceInterval::Month) = reoccurrence_interval()
|
||||
{ "bg-zinc-500/50" }
|
||||
@@ -59,7 +59,7 @@ pub(crate) fn ReoccurrenceIntervalInput(
|
||||
button {
|
||||
r#type: "button",
|
||||
class: format!(
|
||||
"py-2 rounded-lg {} {} cursor-pointer",
|
||||
"py-2 rounded-lg {} {}",
|
||||
class_buttons.unwrap_or(""),
|
||||
if let Some(ReoccurrenceInterval::Year) = reoccurrence_interval()
|
||||
{ "bg-zinc-500/50" }
|
||||
|
||||
@@ -1,31 +1,36 @@
|
||||
use crate::hooks::use_subtasks_of_task;
|
||||
use crate::models::subtask::NewSubtask;
|
||||
use crate::models::task::Task;
|
||||
use crate::query::subtasks::use_subtasks_of_task_query;
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::server::subtasks::{create_subtask, delete_subtask, edit_subtask};
|
||||
use dioxus::core_macro::{component, rsx};
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_query::prelude::{use_query_client, QueryResult};
|
||||
|
||||
#[component]
|
||||
pub(crate) fn SubtasksForm(task: Task) -> Element {
|
||||
let subtasks = use_subtasks_of_task(task.id)?();
|
||||
let query_client = use_query_client::<QueryValue, QueryErrors, QueryKey>();
|
||||
let subtasks_query = use_subtasks_of_task_query(task.id());
|
||||
|
||||
let mut new_title = use_signal(String::new);
|
||||
|
||||
rsx! {
|
||||
form {
|
||||
class: "flex flex-row items-center gap-3",
|
||||
onsubmit: move |event| {
|
||||
event.prevent_default();
|
||||
let task = task.clone();
|
||||
async move {
|
||||
let new_subtask = NewSubtask {
|
||||
task_id: task.id,
|
||||
title: event.get("title").first().cloned().and_then(|value| match value {
|
||||
FormValue::Text(value) => Some(value),
|
||||
FormValue::File(_) => None
|
||||
}).unwrap(),
|
||||
is_completed: false
|
||||
};
|
||||
let new_subtask = NewSubtask::new(
|
||||
task.id(),
|
||||
event.values().get("title").unwrap().as_value(),
|
||||
false
|
||||
);
|
||||
let _ = create_subtask(new_subtask).await;
|
||||
query_client.invalidate_queries(&[
|
||||
QueryKey::SubtasksOfTaskId(task.id()),
|
||||
QueryKey::TasksWithSubtasksInCategory(task.category().clone()),
|
||||
]);
|
||||
new_title.set(String::new());
|
||||
}
|
||||
},
|
||||
@@ -56,84 +61,126 @@ pub(crate) fn SubtasksForm(task: Task) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
for subtask in subtasks {
|
||||
div {
|
||||
key: "{subtask.id}",
|
||||
class: "flex flex-row items-center gap-3",
|
||||
i {
|
||||
class: format!(
|
||||
"{} min-w-6 text-center text-2xl text-zinc-400/50",
|
||||
if subtask.is_completed {
|
||||
"fa solid fa-square-check"
|
||||
} else {
|
||||
"fa-regular fa-square"
|
||||
}
|
||||
),
|
||||
onclick: {
|
||||
let subtask = subtask.clone();
|
||||
move |_| {
|
||||
let subtask = subtask.clone();
|
||||
async move {
|
||||
let new_subtask = NewSubtask {
|
||||
task_id: subtask.task_id,
|
||||
title: subtask.title.clone(),
|
||||
is_completed: !subtask.is_completed
|
||||
};
|
||||
let _ = edit_subtask(
|
||||
subtask.id,
|
||||
new_subtask
|
||||
).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div {
|
||||
class: "grow grid grid-cols-6 gap-2",
|
||||
input {
|
||||
r#type: "text",
|
||||
class: "grow py-2 px-3 col-span-5 bg-zinc-800/50 rounded-lg",
|
||||
id: "input_title_{subtask.id}",
|
||||
initial_value: subtask.title.clone(),
|
||||
onchange: {
|
||||
let subtask = subtask.clone();
|
||||
move |event: Event<FormData>| {
|
||||
let subtask = subtask.clone();
|
||||
async move {
|
||||
let new_subtask = NewSubtask {
|
||||
task_id: subtask.task_id,
|
||||
title: event.value(),
|
||||
is_completed: subtask.is_completed
|
||||
};
|
||||
if new_subtask.title.is_empty() {
|
||||
let _ = delete_subtask(subtask.id).await;
|
||||
match subtasks_query.result().value() {
|
||||
QueryResult::Ok(QueryValue::Subtasks(subtasks))
|
||||
| QueryResult::Loading(Some(QueryValue::Subtasks(subtasks))) => {
|
||||
let mut subtasks = subtasks.clone();
|
||||
subtasks.sort();
|
||||
rsx! {
|
||||
for subtask in subtasks {
|
||||
div {
|
||||
key: "{subtask.id()}",
|
||||
class: "flex flex-row items-center gap-3",
|
||||
i {
|
||||
class: format!(
|
||||
"{} min-w-6 text-center text-2xl text-zinc-400/50",
|
||||
if subtask.is_completed() {
|
||||
"fa solid fa-square-check"
|
||||
} else {
|
||||
let _ = edit_subtask(
|
||||
subtask.id,
|
||||
new_subtask
|
||||
).await;
|
||||
"fa-regular fa-square"
|
||||
}
|
||||
),
|
||||
onclick: {
|
||||
let subtask = subtask.clone();
|
||||
let task = task.clone();
|
||||
move |_| {
|
||||
let subtask = subtask.clone();
|
||||
let task = task.clone();
|
||||
async move {
|
||||
let new_subtask = NewSubtask::new(
|
||||
subtask.task_id(),
|
||||
subtask.title().to_owned(),
|
||||
!subtask.is_completed()
|
||||
);
|
||||
let _ = edit_subtask(
|
||||
subtask.id(),
|
||||
new_subtask
|
||||
).await;
|
||||
query_client.invalidate_queries(&[
|
||||
QueryKey::SubtasksOfTaskId(task.id()),
|
||||
QueryKey::TasksWithSubtasksInCategory(
|
||||
task.category().clone()
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div {
|
||||
class: "grow grid grid-cols-6 gap-2",
|
||||
input {
|
||||
r#type: "text",
|
||||
class: "grow py-2 px-3 col-span-5 bg-zinc-800/50 rounded-lg",
|
||||
id: "input_title_{subtask.id()}",
|
||||
initial_value: subtask.title(),
|
||||
onchange: {
|
||||
let subtask = subtask.clone();
|
||||
let task = task.clone();
|
||||
move |event: Event<FormData>| {
|
||||
let subtask = subtask.clone();
|
||||
let task = task.clone();
|
||||
async move {
|
||||
let new_subtask = NewSubtask::new(
|
||||
subtask.task_id(),
|
||||
event.value(),
|
||||
subtask.is_completed()
|
||||
);
|
||||
if new_subtask.title.is_empty() {
|
||||
let _ = delete_subtask(subtask.id()).await;
|
||||
} else {
|
||||
let _ = edit_subtask(
|
||||
subtask.id(),
|
||||
new_subtask
|
||||
).await;
|
||||
}
|
||||
query_client.invalidate_queries(&[
|
||||
QueryKey::SubtasksOfTaskId(task.id()),
|
||||
QueryKey::TasksWithSubtasksInCategory(
|
||||
task.category().clone()
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
button {
|
||||
r#type: "button",
|
||||
class: "py-2 col-span-1 bg-zinc-800/50 rounded-lg",
|
||||
onclick: {
|
||||
let subtask = subtask.clone();
|
||||
let task = task.clone();
|
||||
move |_| {
|
||||
let subtask = subtask.clone();
|
||||
let task = task.clone();
|
||||
async move {
|
||||
let _ = delete_subtask(subtask.id()).await;
|
||||
query_client.invalidate_queries(&[
|
||||
QueryKey::SubtasksOfTaskId(task.id()),
|
||||
QueryKey::TasksWithSubtasksInCategory(
|
||||
task.category().clone()
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
},
|
||||
i {
|
||||
class: "fa-solid fa-trash-can"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
button {
|
||||
r#type: "button",
|
||||
class: "py-2 col-span-1 bg-zinc-800/50 rounded-lg",
|
||||
onclick: {
|
||||
let subtask = subtask.clone();
|
||||
move |_| {
|
||||
let subtask = subtask.clone();
|
||||
async move {
|
||||
let _ = delete_subtask(subtask.id).await;
|
||||
}
|
||||
}
|
||||
},
|
||||
i {
|
||||
class: "fa-solid fa-trash-can"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use crate::components::category_input::CategoryInput;
|
||||
use crate::components::project_select::ProjectSelect;
|
||||
use crate::components::reoccurrence_input::ReoccurrenceIntervalInput;
|
||||
use crate::components::subtasks_form::SubtasksForm;
|
||||
use crate::models::category::{CalendarTime, Category, Reoccurrence};
|
||||
use crate::models::task::NewTask;
|
||||
use crate::models::task::Task;
|
||||
use crate::query::projects::use_projects_query;
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::route::Route;
|
||||
use crate::server::tasks::{create_task, delete_task, edit_task};
|
||||
use chrono::Duration;
|
||||
@@ -12,7 +13,7 @@ use dioxus::core_macro::{component, rsx};
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_i18n::t;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use dioxus_query::prelude::{use_query_client, QueryResult};
|
||||
|
||||
const REMINDER_OFFSETS: [Option<Duration>; 17] = [
|
||||
None,
|
||||
@@ -34,24 +35,14 @@ const REMINDER_OFFSETS: [Option<Duration>; 17] = [
|
||||
Some(Duration::zero()),
|
||||
];
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct InputData {
|
||||
title: String,
|
||||
deadline: Option<String>,
|
||||
category_waiting_for: Option<String>,
|
||||
category_calendar_date: Option<String>,
|
||||
category_calendar_reoccurrence_length: Option<String>,
|
||||
category_calendar_time: Option<String>,
|
||||
category_calendar_reminder_offset_index: Option<String>,
|
||||
project_id: Option<String>,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()>) -> Element {
|
||||
let projects_query = use_projects_query();
|
||||
|
||||
let route = use_route::<Route>();
|
||||
let selected_category = use_signal(|| {
|
||||
if let Some(task) = &task {
|
||||
task.category.clone()
|
||||
task.category().clone()
|
||||
} else {
|
||||
match route {
|
||||
Route::CategorySomedayMaybePage => Category::SomedayMaybe,
|
||||
@@ -72,34 +63,37 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
if let Category::Calendar {
|
||||
reoccurrence: Some(reoccurrence),
|
||||
..
|
||||
} = &task.category
|
||||
} = task.category()
|
||||
{
|
||||
Some(reoccurrence.interval.clone())
|
||||
Some(reoccurrence.interval().clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
});
|
||||
let mut category_calendar_has_time = use_signal(|| {
|
||||
task.as_ref()
|
||||
.is_some_and(|task| matches!(task.category, Category::Calendar { time: Some(_), .. }))
|
||||
task.as_ref().is_some_and(|task| {
|
||||
matches!(*task.category(), Category::Calendar { time: Some(_), .. })
|
||||
})
|
||||
});
|
||||
let mut category_calendar_reminder_offset_index = use_signal(|| {
|
||||
task.as_ref()
|
||||
.and_then(|task| {
|
||||
if let Category::Calendar {
|
||||
time: Some(time), ..
|
||||
} = &task.category
|
||||
} = task.category()
|
||||
{
|
||||
REMINDER_OFFSETS
|
||||
.iter()
|
||||
.position(|&reminder_offset| reminder_offset == time.reminder_offset)
|
||||
.position(|&reminder_offset| reminder_offset == time.reminder_offset())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or(REMINDER_OFFSETS.len() - 1)
|
||||
});
|
||||
|
||||
let query_client = use_query_client::<QueryValue, QueryErrors, QueryKey>();
|
||||
let task_for_submit = task.clone();
|
||||
|
||||
rsx! {
|
||||
@@ -109,50 +103,56 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
class: "flex flex-col gap-4",
|
||||
id: "form_task",
|
||||
onsubmit: move |event| {
|
||||
event.prevent_default();
|
||||
let task = task_for_submit.clone();
|
||||
async move {
|
||||
let input_data = event.parsed_values::<InputData>().unwrap();
|
||||
let new_task = NewTask {
|
||||
title: input_data.title,
|
||||
deadline: input_data.deadline
|
||||
.and_then(|deadline| deadline.parse().ok()),
|
||||
category: match &selected_category() {
|
||||
let new_task = NewTask::new(
|
||||
event.values().get("title").unwrap().as_value(),
|
||||
event.values().get("deadline").unwrap().as_value().parse().ok(),
|
||||
match &selected_category() {
|
||||
Category::WaitingFor(_) => Category::WaitingFor(
|
||||
input_data.category_waiting_for.unwrap()
|
||||
event.values().get("category_waiting_for").unwrap()
|
||||
.as_value()
|
||||
),
|
||||
Category::Calendar { .. } => Category::Calendar {
|
||||
date: input_data.category_calendar_date.clone().unwrap().parse()
|
||||
.unwrap(),
|
||||
date: event.values().get("category_calendar_date").unwrap()
|
||||
.as_value().parse().unwrap(),
|
||||
reoccurrence: category_calendar_reoccurrence_interval().map(
|
||||
|reoccurrence_interval| Reoccurrence {
|
||||
start_date: input_data.category_calendar_date.unwrap()
|
||||
.parse().unwrap(),
|
||||
interval: reoccurrence_interval,
|
||||
length: input_data.category_calendar_reoccurrence_length
|
||||
.unwrap().parse().unwrap()
|
||||
}
|
||||
|reoccurrence_interval| Reoccurrence::new(
|
||||
event.values().get("category_calendar_date").unwrap()
|
||||
.as_value().parse().unwrap(),
|
||||
reoccurrence_interval,
|
||||
event.values()
|
||||
.get("category_calendar_reoccurrence_length")
|
||||
.unwrap().as_value().parse().unwrap()
|
||||
)
|
||||
),
|
||||
time: input_data.category_calendar_time.unwrap().parse().ok()
|
||||
.map(|time| CalendarTime {
|
||||
time: event.values().get("category_calendar_time").unwrap()
|
||||
.as_value().parse().ok().map(|time|
|
||||
CalendarTime::new(
|
||||
time,
|
||||
reminder_offset: REMINDER_OFFSETS[
|
||||
input_data.category_calendar_reminder_offset_index
|
||||
.unwrap().parse::<usize>().unwrap()
|
||||
REMINDER_OFFSETS[
|
||||
event.values()
|
||||
.get("category_calendar_reminder_offset_index")
|
||||
.unwrap().as_value().parse::<usize>().unwrap()
|
||||
]
|
||||
}
|
||||
)
|
||||
)
|
||||
},
|
||||
category => category.clone()
|
||||
},
|
||||
project_id: input_data.project_id
|
||||
.and_then(|deadline| deadline.parse().ok()).filter(|&id| id > 0),
|
||||
};
|
||||
event.values().get("project_id").unwrap()
|
||||
.as_value().parse::<i32>().ok().filter(|&id| id > 0),
|
||||
);
|
||||
if let Some(task) = task {
|
||||
let _ = edit_task(task.id, new_task).await;
|
||||
let _ = edit_task(task.id(), new_task).await;
|
||||
} else {
|
||||
let _ = create_task(new_task).await;
|
||||
}
|
||||
query_client.invalidate_queries(&[
|
||||
QueryKey::Tasks,
|
||||
QueryKey::TasksInCategory(selected_category()),
|
||||
QueryKey::TasksWithSubtasksInCategory(selected_category()),
|
||||
]);
|
||||
on_successful_submit.call(());
|
||||
}
|
||||
},
|
||||
@@ -168,7 +168,7 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
input {
|
||||
name: "title",
|
||||
required: true,
|
||||
initial_value: task.as_ref().map(|task| task.title.clone()),
|
||||
initial_value: task.as_ref().map(|task| task.title().to_owned()),
|
||||
r#type: "text",
|
||||
class: "py-2 px-3 grow bg-zinc-800/50 rounded-lg",
|
||||
id: "input_title"
|
||||
@@ -183,22 +183,42 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
class: "fa-solid fa-list text-zinc-400/50"
|
||||
}
|
||||
},
|
||||
SuspenseBoundary {
|
||||
fallback: |_| {
|
||||
rsx ! {
|
||||
select {
|
||||
class: "px-3.5 py-2.5 bg-zinc-800/50 rounded-lg grow cursor-pointer",
|
||||
option {
|
||||
value: 0,
|
||||
{t!("none")}
|
||||
},
|
||||
}
|
||||
}
|
||||
select {
|
||||
name: "project_id",
|
||||
class: "px-3.5 py-2.5 bg-zinc-800/50 rounded-lg grow",
|
||||
id: "input_project",
|
||||
option {
|
||||
value: 0,
|
||||
{t!("none")}
|
||||
},
|
||||
ProjectSelect {
|
||||
initial_selected_id: task.clone().and_then(|task| task.project_id)
|
||||
match projects_query.result().value() {
|
||||
QueryResult::Ok(QueryValue::Projects(projects))
|
||||
| QueryResult::Loading(Some(QueryValue::Projects(projects))) => {
|
||||
let mut projects = projects.clone();
|
||||
projects.sort();
|
||||
rsx! {
|
||||
for project in projects {
|
||||
option {
|
||||
value: project.id().to_string(),
|
||||
initial_selected: task.as_ref().is_some_and(
|
||||
|task| task.project_id() == Some(project.id())
|
||||
),
|
||||
{project.title()}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
QueryResult::Loading(None) => rsx! {
|
||||
// TODO: Add a loading indicator.
|
||||
},
|
||||
QueryResult::Err(errors) => rsx! {
|
||||
div {
|
||||
"Errors occurred: {errors:?}"
|
||||
}
|
||||
},
|
||||
value => panic!("Unexpected query result: {value:?}")
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
div {
|
||||
class: "flex flex-row items-center gap-3",
|
||||
@@ -211,10 +231,10 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
},
|
||||
input {
|
||||
name: "deadline",
|
||||
initial_value: task.as_ref().and_then(|task| task.deadline)
|
||||
initial_value: task.as_ref().and_then(|task| task.deadline())
|
||||
.map(|deadline| deadline.format("%Y-%m-%d").to_string()),
|
||||
r#type: "date",
|
||||
class: "py-2 px-3 bg-zinc-800/50 rounded-lg grow basis-0 cursor-pointer",
|
||||
class: "py-2 px-3 bg-zinc-800/50 rounded-lg grow basis-0",
|
||||
id: "input_deadline"
|
||||
}
|
||||
},
|
||||
@@ -269,17 +289,16 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
name: "category_calendar_date",
|
||||
required: true,
|
||||
initial_value: date.format("%Y-%m-%d").to_string(),
|
||||
class:
|
||||
"py-2 px-3 bg-zinc-800/50 rounded-lg grow cursor-pointer",
|
||||
class: "py-2 px-3 bg-zinc-800/50 rounded-lg grow",
|
||||
id: "input_category_calendar_date"
|
||||
},
|
||||
input {
|
||||
r#type: "time",
|
||||
name: "category_calendar_time",
|
||||
initial_value: time.map(|calendar_time|
|
||||
calendar_time.time.format("%H:%M").to_string()
|
||||
calendar_time.time().format("%H:%M").to_string()
|
||||
),
|
||||
class: "py-2 px-3 bg-zinc-800/50 rounded-lg grow cursor-pointer",
|
||||
class: "py-2 px-3 bg-zinc-800/50 rounded-lg grow",
|
||||
id: "input_category_calendar_time",
|
||||
oninput: move |event| {
|
||||
category_calendar_has_time.set(!event.value().is_empty());
|
||||
@@ -311,7 +330,7 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
initial_value: category_calendar_reoccurrence_interval().map_or(
|
||||
String::new(),
|
||||
|_| reoccurrence.map_or(1, |reoccurrence|
|
||||
reoccurrence.length).to_string()
|
||||
reoccurrence.length()).to_string()
|
||||
),
|
||||
class: "py-2 px-3 bg-zinc-800/50 rounded-lg col-span-2 text-right",
|
||||
id: "category_calendar_reoccurrence_length"
|
||||
@@ -335,7 +354,7 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
max: REMINDER_OFFSETS.len() as i64 - 1,
|
||||
initial_value: category_calendar_reminder_offset_index()
|
||||
.to_string(),
|
||||
class: "grow input-range-reverse cursor-pointer",
|
||||
class: "grow input-range-reverse",
|
||||
id: "category_calendar_has_reminder",
|
||||
oninput: move |event| {
|
||||
category_calendar_reminder_offset_index.set(
|
||||
@@ -362,35 +381,37 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
}
|
||||
},
|
||||
if let Some(task) = task.as_ref() {
|
||||
SuspenseBoundary {
|
||||
fallback: |_| {
|
||||
VNode::empty()
|
||||
},
|
||||
SubtasksForm {
|
||||
task: task.clone()
|
||||
}
|
||||
SubtasksForm {
|
||||
task: task.clone()
|
||||
}
|
||||
}
|
||||
div {
|
||||
class: "flex flex-row justify-between mt-auto",
|
||||
button {
|
||||
r#type: "button",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg cursor-pointer",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg",
|
||||
onclick: move |_| {
|
||||
let task = task.clone();
|
||||
async move {
|
||||
if let Some(task) = task {
|
||||
if let Category::Trash = task.category {
|
||||
let _ = delete_task(task.id).await;
|
||||
if *(task.category()) == Category::Trash {
|
||||
let _ = delete_task(task.id()).await;
|
||||
} else {
|
||||
let new_task = NewTask {
|
||||
title: task.title.to_owned(),
|
||||
deadline: task.deadline,
|
||||
category: Category::Trash,
|
||||
project_id: task.project_id
|
||||
};
|
||||
let _ = edit_task(task.id, new_task).await;
|
||||
let new_task = NewTask::new(
|
||||
task.title().to_owned(),
|
||||
task.deadline(),
|
||||
Category::Trash,
|
||||
task.project_id()
|
||||
);
|
||||
|
||||
let _ = edit_task(task.id(), new_task).await;
|
||||
}
|
||||
|
||||
query_client.invalidate_queries(&[
|
||||
QueryKey::Tasks,
|
||||
QueryKey::TasksInCategory(task.category().clone()),
|
||||
QueryKey::TasksWithSubtasksInCategory(selected_category()),
|
||||
]);
|
||||
}
|
||||
on_successful_submit.call(());
|
||||
}
|
||||
@@ -402,7 +423,7 @@ pub(crate) fn TaskForm(task: Option<Task>, on_successful_submit: EventHandler<()
|
||||
button {
|
||||
form: "form_task",
|
||||
r#type: "submit",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg cursor-pointer",
|
||||
class: "py-2 px-4 bg-zinc-300/50 rounded-lg",
|
||||
i {
|
||||
class: "fa-solid fa-floppy-disk"
|
||||
}
|
||||
|
||||
@@ -1,24 +1,31 @@
|
||||
use crate::components::task_list_item::TaskListItem;
|
||||
use crate::models::category::Category;
|
||||
use crate::models::task::{Task, TaskWithSubtasks};
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::server::tasks::complete_task;
|
||||
use dioxus::core_macro::rsx;
|
||||
use dioxus::dioxus_core::Element;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_query::prelude::use_query_client;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn TaskList(tasks: Vec<TaskWithSubtasks>, class: Option<&'static str>) -> Element {
|
||||
let query_client = use_query_client::<QueryValue, QueryErrors, QueryKey>();
|
||||
let mut task_being_edited = use_context::<Signal<Option<Task>>>();
|
||||
|
||||
tasks.sort();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: format!("flex flex-col {}", class.unwrap_or("")),
|
||||
for task in tasks.clone() {
|
||||
div {
|
||||
key: "{task.task.id}",
|
||||
key: "{task.task().id()}",
|
||||
class: format!(
|
||||
"px-8 pt-4 {} flex flex-row gap-4 select-none {}",
|
||||
if task.task.deadline.is_some() || !task.subtasks.is_empty() {
|
||||
if task.task().deadline().is_some() || !task.subtasks().is_empty() {
|
||||
"pb-0.5"
|
||||
} else if let Category::Calendar { time, .. } = &task.task.category {
|
||||
} else if let Category::Calendar { time, .. } = task.task().category() {
|
||||
if time.is_some() {
|
||||
"pb-0.5"
|
||||
} else {
|
||||
@@ -27,27 +34,47 @@ pub(crate) fn TaskList(tasks: Vec<TaskWithSubtasks>, class: Option<&'static str>
|
||||
} else {
|
||||
"pb-4"
|
||||
},
|
||||
if task_being_edited().is_some_and(|t| t.id == task.task.id) {
|
||||
if task_being_edited().is_some_and(|t| t.id() == task.task().id()) {
|
||||
"bg-zinc-700"
|
||||
} else { "" }
|
||||
),
|
||||
onclick: {
|
||||
let task = task.clone();
|
||||
move |_| task_being_edited.set(Some(task.task.clone()))
|
||||
move |_| task_being_edited.set(Some(task.task().clone()))
|
||||
},
|
||||
i {
|
||||
class: format!(
|
||||
"{} text-3xl align-middle h-9 text-zinc-500",
|
||||
if let Category::Done = task.task.category {
|
||||
if *(task.task().category()) == Category::Done {
|
||||
"fa solid fa-square-check"
|
||||
} else {
|
||||
"fa-regular fa-square cursor-pointer"
|
||||
"fa-regular fa-square"
|
||||
}
|
||||
),
|
||||
onclick: {
|
||||
let task = task.clone();
|
||||
move |event: Event<MouseData>| {
|
||||
// To prevent editing the task.
|
||||
event.stop_propagation();
|
||||
let task = task.clone();
|
||||
async move {
|
||||
let completed_task = complete_task(task.task().id()).await
|
||||
.unwrap();
|
||||
let mut query_keys = vec![
|
||||
QueryKey::Tasks,
|
||||
QueryKey::TasksInCategory(
|
||||
completed_task.category().clone()
|
||||
),
|
||||
QueryKey::TasksWithSubtasksInCategory(completed_task.category().clone()),
|
||||
];
|
||||
if let Category::Calendar { reoccurrence: Some(_), .. }
|
||||
= task.task().category() {
|
||||
query_keys.push(
|
||||
QueryKey::SubtasksOfTaskId(task.task().id())
|
||||
);
|
||||
}
|
||||
query_client.invalidate_queries(&query_keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -11,23 +11,23 @@ use voca_rs::Voca;
|
||||
|
||||
#[component]
|
||||
pub(crate) fn TaskListItem(task: TaskWithSubtasks) -> Element {
|
||||
let today_date = Local::now().date_naive();
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col",
|
||||
div {
|
||||
class: "mt-1 grow font-medium",
|
||||
{task.task.title}
|
||||
class: "mt-2 grow font-medium",
|
||||
{task.task().title()}
|
||||
},
|
||||
div {
|
||||
class: "flex flex-row gap-4",
|
||||
if let Some(deadline) = task.task.deadline {
|
||||
if let Some(deadline) = task.task().deadline() {
|
||||
div {
|
||||
class: "text-sm text-zinc-400",
|
||||
i {
|
||||
class: "fa-solid fa-bomb"
|
||||
},
|
||||
{
|
||||
let today_date = Local::now().date_naive();
|
||||
format!(
|
||||
" {}",
|
||||
if deadline == today_date - chrono::Days::new(1) {
|
||||
@@ -69,7 +69,7 @@ pub(crate) fn TaskListItem(task: TaskWithSubtasks) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Category::Calendar { time, .. } = task.task.category {
|
||||
if let Category::Calendar { time, .. } = task.task().category() {
|
||||
if let Some(calendar_time) = time {
|
||||
div {
|
||||
class: "text-sm text-zinc-400",
|
||||
@@ -78,12 +78,12 @@ pub(crate) fn TaskListItem(task: TaskWithSubtasks) -> Element {
|
||||
},
|
||||
{
|
||||
let format = t!("time-format");
|
||||
format!(" {}", calendar_time.time.format(format.as_str()))
|
||||
format!(" {}", calendar_time.time().format(format.as_str()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !task.subtasks.is_empty() {
|
||||
if !task.subtasks().is_empty() {
|
||||
div {
|
||||
class: "text-sm text-zinc-400",
|
||||
i {
|
||||
@@ -91,10 +91,10 @@ pub(crate) fn TaskListItem(task: TaskWithSubtasks) -> Element {
|
||||
},
|
||||
{format!(
|
||||
" {}/{}",
|
||||
task.subtasks.iter()
|
||||
.filter(|subtask| subtask.is_completed)
|
||||
task.subtasks().iter()
|
||||
.filter(|subtask| subtask.is_completed())
|
||||
.count(),
|
||||
task.subtasks.len()
|
||||
task.subtasks().len()
|
||||
)}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
load_dotenv::load_dotenv!();
|
||||
|
||||
pub(crate) const LANGUAGE_CODE: &str = env!("LANGUAGE_CODE");
|
||||
#[cfg(feature = "mobile")]
|
||||
pub(crate) const MOBILE_SERVER_URL: &str = env!("MOBILE_SERVER_URL");
|
||||
36
src/errors/error.rs
Normal file
36
src/errors/error.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub enum Error {
|
||||
ServerInternal,
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
impl From<diesel::result::Error> for Error {
|
||||
fn from(_: diesel::result::Error) -> Self {
|
||||
Self::ServerInternal
|
||||
}
|
||||
}
|
||||
|
||||
// has to be implemented for Dioxus server functions
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::ServerInternal => write!(f, "internal server error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// has to be implemented for Dioxus server functions
|
||||
impl FromStr for Error {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(match s {
|
||||
"internal server error" => Self::ServerInternal,
|
||||
_ => return Err(()),
|
||||
})
|
||||
}
|
||||
}
|
||||
45
src/errors/error_vec.rs
Normal file
45
src/errors/error_vec.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use serde::Deserialize;
|
||||
use serde_with::serde_derive::Serialize;
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct ErrorVec<T> {
|
||||
errors: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> From<ErrorVec<T>> for Vec<T> {
|
||||
fn from(e: ErrorVec<T>) -> Self {
|
||||
e.errors
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Vec<T>> for ErrorVec<T> {
|
||||
fn from(e: Vec<T>) -> Self {
|
||||
ErrorVec { errors: e }
|
||||
}
|
||||
}
|
||||
|
||||
// has to be implemented for Dioxus server functions
|
||||
impl<T: Display> Display for ErrorVec<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
self.errors
|
||||
.iter()
|
||||
.map(|e| e.to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.join("\n")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// has to be implemented for Dioxus server functions
|
||||
impl<T> FromStr for ErrorVec<T> {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(_: &str) -> Result<Self, Self::Err> {
|
||||
Ok(ErrorVec { errors: Vec::new() })
|
||||
}
|
||||
}
|
||||
5
src/errors/mod.rs
Normal file
5
src/errors/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub(crate) mod error;
|
||||
pub(crate) mod error_vec;
|
||||
pub(crate) mod project_error;
|
||||
pub(crate) mod subtask_error;
|
||||
pub(crate) mod task_error;
|
||||
59
src/errors/project_error.rs
Normal file
59
src/errors/project_error.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
use validator::{ValidationErrors, ValidationErrorsKind};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum ProjectError {
|
||||
TitleLengthInvalid,
|
||||
Error(Error),
|
||||
}
|
||||
|
||||
impl From<ValidationErrors> for ErrorVec<ProjectError> {
|
||||
fn from(validation_errors: ValidationErrors) -> Self {
|
||||
validation_errors
|
||||
.errors()
|
||||
.iter()
|
||||
.flat_map(|(&field, error_kind)| match field {
|
||||
"title" => match error_kind {
|
||||
ValidationErrorsKind::Field(validation_errors) => validation_errors
|
||||
.iter()
|
||||
.map(|validation_error| validation_error.code.as_ref())
|
||||
.map(|code| match code {
|
||||
"title_length" => ProjectError::TitleLengthInvalid,
|
||||
_ => panic!("Unexpected validation error code: `{code}`."),
|
||||
})
|
||||
.collect::<Vec<ProjectError>>(),
|
||||
_ => panic!("Unexpected validation error kind."),
|
||||
},
|
||||
_ => panic!("Unexpected validation field name: `{field}`."),
|
||||
})
|
||||
.collect::<Vec<ProjectError>>()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
impl From<diesel::result::Error> for ProjectError {
|
||||
fn from(_: diesel::result::Error) -> Self {
|
||||
Self::Error(Error::ServerInternal)
|
||||
}
|
||||
}
|
||||
|
||||
// Has to be implemented for Dioxus server functions.
|
||||
impl Display for ProjectError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
|
||||
// Has to be implemented for Dioxus server functions.
|
||||
impl FromStr for ProjectError {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(_: &str) -> Result<Self, Self::Err> {
|
||||
Ok(Self::Error(Error::ServerInternal))
|
||||
}
|
||||
}
|
||||
79
src/errors/subtask_error.rs
Normal file
79
src/errors/subtask_error.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
use validator::{ValidationErrors, ValidationErrorsKind};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum SubtaskError {
|
||||
TitleLengthInvalid,
|
||||
TaskNotFound,
|
||||
Error(Error),
|
||||
}
|
||||
|
||||
impl From<ValidationErrors> for ErrorVec<SubtaskError> {
|
||||
fn from(validation_errors: ValidationErrors) -> Self {
|
||||
validation_errors
|
||||
.errors()
|
||||
.iter()
|
||||
.flat_map(|(&field, error_kind)| match field {
|
||||
"title" => match error_kind {
|
||||
ValidationErrorsKind::Field(validation_errors) => validation_errors
|
||||
.iter()
|
||||
.map(|validation_error| validation_error.code.as_ref())
|
||||
.map(|code| match code {
|
||||
"title_length" => SubtaskError::TitleLengthInvalid,
|
||||
_ => panic!("Unexpected validation error code: `{code}`."),
|
||||
})
|
||||
.collect::<Vec<SubtaskError>>(),
|
||||
_ => panic!("Unexpected validation error kind."),
|
||||
},
|
||||
_ => panic!("Unexpected validation field name: `{field}`."),
|
||||
})
|
||||
.collect::<Vec<SubtaskError>>()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
impl From<diesel::result::Error> for SubtaskError {
|
||||
fn from(diesel_error: diesel::result::Error) -> Self {
|
||||
match diesel_error {
|
||||
diesel::result::Error::DatabaseError(
|
||||
diesel::result::DatabaseErrorKind::ForeignKeyViolation,
|
||||
info,
|
||||
) => match info.constraint_name() {
|
||||
Some("subtasks_task_id_fkey") => Self::TaskNotFound,
|
||||
_ => Self::Error(Error::ServerInternal),
|
||||
},
|
||||
_ => Self::Error(Error::ServerInternal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ErrorVec<Error>> for ErrorVec<SubtaskError> {
|
||||
fn from(error_vec: ErrorVec<Error>) -> Self {
|
||||
Vec::from(error_vec)
|
||||
.into_iter()
|
||||
.map(SubtaskError::Error)
|
||||
.collect::<Vec<SubtaskError>>()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
// Has to be implemented for Dioxus server functions.
|
||||
impl Display for SubtaskError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
|
||||
// Has to be implemented for Dioxus server functions.
|
||||
impl FromStr for SubtaskError {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(_: &str) -> Result<Self, Self::Err> {
|
||||
Ok(Self::Error(Error::ServerInternal))
|
||||
}
|
||||
}
|
||||
69
src/errors/task_error.rs
Normal file
69
src/errors/task_error.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
use validator::{ValidationErrors, ValidationErrorsKind};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum TaskError {
|
||||
TitleLengthInvalid,
|
||||
ProjectNotFound,
|
||||
Error(Error),
|
||||
}
|
||||
|
||||
impl From<ValidationErrors> for ErrorVec<TaskError> {
|
||||
fn from(validation_errors: ValidationErrors) -> Self {
|
||||
validation_errors
|
||||
.errors()
|
||||
.iter()
|
||||
.flat_map(|(&field, error_kind)| match field {
|
||||
"title" => match error_kind {
|
||||
ValidationErrorsKind::Field(validation_errors) => validation_errors
|
||||
.iter()
|
||||
.map(|validation_error| validation_error.code.as_ref())
|
||||
.map(|code| match code {
|
||||
"title_length" => TaskError::TitleLengthInvalid,
|
||||
_ => panic!("Unexpected validation error code: `{code}`."),
|
||||
})
|
||||
.collect::<Vec<TaskError>>(),
|
||||
_ => panic!("Unexpected validation error kind."),
|
||||
},
|
||||
_ => panic!("Unexpected validation field name: `{field}`."),
|
||||
})
|
||||
.collect::<Vec<TaskError>>()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
impl From<diesel::result::Error> for TaskError {
|
||||
fn from(diesel_error: diesel::result::Error) -> Self {
|
||||
match diesel_error {
|
||||
diesel::result::Error::DatabaseError(
|
||||
diesel::result::DatabaseErrorKind::ForeignKeyViolation,
|
||||
info,
|
||||
) => match info.constraint_name() {
|
||||
Some("tasks_project_id_fkey") => Self::ProjectNotFound,
|
||||
_ => Self::Error(Error::ServerInternal),
|
||||
},
|
||||
_ => Self::Error(Error::ServerInternal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Has to be implemented for Dioxus server functions.
|
||||
impl Display for TaskError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
|
||||
// Has to be implemented for Dioxus server functions.
|
||||
impl FromStr for TaskError {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(_: &str) -> Result<Self, Self::Err> {
|
||||
Ok(Self::Error(Error::ServerInternal))
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
use dioxus::{
|
||||
CapturedError,
|
||||
fullstack::{Loader, Loading, WebSocketOptions, use_websocket},
|
||||
prelude::*,
|
||||
};
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
|
||||
use crate::{
|
||||
models::{category::Category, project::Project, subtask::Subtask, task::TaskWithSubtasks},
|
||||
server::{
|
||||
projects::get_projects, subtasks::get_subtasks_of_task,
|
||||
tasks::get_tasks_with_subtasks_in_category, updates::subscribe_to_updates,
|
||||
},
|
||||
};
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn use_loader_with_update_subscription<F, T, E>(
|
||||
mut future: impl FnMut() -> F + 'static,
|
||||
) -> Result<Loader<T>, Loading>
|
||||
where
|
||||
F: Future<Output = Result<T, E>> + 'static,
|
||||
T: 'static + PartialEq + Serialize + DeserializeOwned,
|
||||
E: Into<CapturedError> + 'static,
|
||||
{
|
||||
let mut refresh_tick = use_signal(|| 0u64);
|
||||
|
||||
let loader = use_loader(move || {
|
||||
let _ = refresh_tick(); // Read => dependency.
|
||||
future()
|
||||
});
|
||||
|
||||
let mut socket = use_websocket(|| subscribe_to_updates(WebSocketOptions::default()));
|
||||
use_future(move || async move {
|
||||
while socket.recv().await.is_ok() {
|
||||
refresh_tick += 1;
|
||||
}
|
||||
});
|
||||
|
||||
loader
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub(crate) fn use_projects() -> Result<Loader<Vec<Project>>, Loading> {
|
||||
use_loader_with_update_subscription(get_projects).inspect(|projects| projects().sort())
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub(crate) fn use_tasks_with_subtasks_in_category(
|
||||
filtered_category: Category,
|
||||
) -> Result<Loader<Vec<TaskWithSubtasks>>, Loading> {
|
||||
use_loader_with_update_subscription(move || {
|
||||
get_tasks_with_subtasks_in_category(filtered_category.clone())
|
||||
})
|
||||
.inspect(|tasks| tasks().sort())
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub(crate) fn use_subtasks_of_task(task_id: i32) -> Result<Loader<Vec<Subtask>>, Loading> {
|
||||
use_loader_with_update_subscription(move || get_subtasks_of_task(task_id))
|
||||
.inspect(|subtasks| subtasks().sort())
|
||||
}
|
||||
@@ -1,18 +1,11 @@
|
||||
use crate::dotenv;
|
||||
use chrono::Locale;
|
||||
use dioxus::fullstack::once_cell::sync::Lazy;
|
||||
use feruca::Collator;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::sync::Mutex;
|
||||
use unic_langid_impl::LanguageIdentifier;
|
||||
|
||||
pub(crate) fn get_language_identifier() -> LanguageIdentifier {
|
||||
dotenv::LANGUAGE_CODE
|
||||
.parse::<LanguageIdentifier>()
|
||||
.expect("The LANGUAGE_CODE environment variable is not a valid language code.")
|
||||
}
|
||||
|
||||
pub(crate) static COLLATOR: LazyLock<Mutex<Collator>> =
|
||||
LazyLock::new(|| Mutex::new(Collator::default()));
|
||||
pub(crate) static COLLATOR: Lazy<Mutex<Collator>> = Lazy::new(|| Mutex::new(Collator::default()));
|
||||
|
||||
pub(crate) struct LocaleFromLanguageIdentifier<'a>(&'a LanguageIdentifier);
|
||||
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
mod main;
|
||||
pub(crate) use main::Main;
|
||||
11
src/main.rs
11
src/main.rs
@@ -1,17 +1,15 @@
|
||||
mod components;
|
||||
mod dotenv;
|
||||
mod hooks;
|
||||
mod errors;
|
||||
mod internationalization;
|
||||
mod layouts;
|
||||
#[cfg(feature = "server")]
|
||||
mod migrations;
|
||||
mod models;
|
||||
mod query;
|
||||
mod route;
|
||||
#[cfg(feature = "server")]
|
||||
mod schema;
|
||||
mod server;
|
||||
mod utils;
|
||||
mod views;
|
||||
|
||||
use components::app::App;
|
||||
use dioxus::prelude::*;
|
||||
@@ -23,9 +21,6 @@ fn main() {
|
||||
migrations::run_migrations().expect("Failed to run migrations.");
|
||||
);
|
||||
|
||||
#[cfg(feature = "mobile")]
|
||||
dioxus::fullstack::set_server_url(crate::dotenv::MOBILE_SERVER_URL);
|
||||
|
||||
info!("Starting the app.");
|
||||
info!("Starting app.");
|
||||
launch(App);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
|
||||
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
||||
use std::error::Error;
|
||||
|
||||
const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
|
||||
|
||||
@@ -104,15 +104,54 @@ pub enum ReoccurrenceInterval {
|
||||
|
||||
#[derive(Serialize, Deserialize, Hash, Clone, Debug)]
|
||||
pub struct Reoccurrence {
|
||||
pub start_date: NaiveDate,
|
||||
pub interval: ReoccurrenceInterval,
|
||||
pub length: u32,
|
||||
start_date: NaiveDate,
|
||||
interval: ReoccurrenceInterval,
|
||||
length: u32,
|
||||
}
|
||||
|
||||
impl Reoccurrence {
|
||||
pub fn new(start_date: NaiveDate, interval: ReoccurrenceInterval, length: u32) -> Self {
|
||||
Self {
|
||||
start_date,
|
||||
interval,
|
||||
length,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_date(&self) -> NaiveDate {
|
||||
self.start_date
|
||||
}
|
||||
|
||||
pub fn interval(&self) -> &ReoccurrenceInterval {
|
||||
&self.interval
|
||||
}
|
||||
|
||||
pub fn length(&self) -> u32 {
|
||||
self.length
|
||||
}
|
||||
}
|
||||
|
||||
#[serde_with::serde_as]
|
||||
#[derive(Serialize, Deserialize, Hash, Clone, Debug)]
|
||||
pub struct CalendarTime {
|
||||
pub time: NaiveTime,
|
||||
time: NaiveTime,
|
||||
#[serde_as(as = "Option<DurationSeconds<i64>>")]
|
||||
pub reminder_offset: Option<Duration>,
|
||||
reminder_offset: Option<Duration>,
|
||||
}
|
||||
|
||||
impl CalendarTime {
|
||||
pub fn new(time: NaiveTime, reminder_offset: Option<Duration>) -> Self {
|
||||
Self {
|
||||
time,
|
||||
reminder_offset,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn time(&self) -> NaiveTime {
|
||||
self.time
|
||||
}
|
||||
|
||||
pub fn reminder_offset(&self) -> Option<Duration> {
|
||||
self.reminder_offset
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,29 @@ const TITLE_LENGTH_MAX: u64 = 255;
|
||||
diesel(table_name = crate::schema::projects, check_for_backend(diesel::pg::Pg))
|
||||
)]
|
||||
pub struct Project {
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: NaiveDateTime,
|
||||
id: i32,
|
||||
title: String,
|
||||
created_at: NaiveDateTime,
|
||||
updated_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Project {
|
||||
pub fn id(&self) -> i32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn title(&self) -> &str {
|
||||
&self.title
|
||||
}
|
||||
|
||||
pub fn created_at(&self) -> NaiveDateTime {
|
||||
self.created_at
|
||||
}
|
||||
|
||||
pub fn updated_at(&self) -> NaiveDateTime {
|
||||
self.updated_at
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Project {}
|
||||
@@ -37,7 +56,7 @@ impl Ord for Project {
|
||||
COLLATOR
|
||||
.lock()
|
||||
.unwrap()
|
||||
.collate(self.title.as_str(), other.title.as_str())
|
||||
.collate(self.title(), other.title())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,3 +71,9 @@ pub struct NewProject {
|
||||
))]
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
impl NewProject {
|
||||
pub fn new(title: String) -> Self {
|
||||
Self { title }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ const TITLE_LENGTH_MAX: u64 = 255;
|
||||
derive(Queryable, Selectable, Identifiable, Associations)
|
||||
)]
|
||||
#[cfg_attr(
|
||||
feature = "server",
|
||||
feature = "server",
|
||||
diesel(
|
||||
table_name = subtasks,
|
||||
belongs_to(Task, foreign_key = task_id),
|
||||
@@ -26,12 +26,38 @@ const TITLE_LENGTH_MAX: u64 = 255;
|
||||
)
|
||||
)]
|
||||
pub struct Subtask {
|
||||
pub id: i32,
|
||||
pub task_id: i32,
|
||||
pub title: String,
|
||||
pub is_completed: bool,
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: NaiveDateTime,
|
||||
id: i32,
|
||||
task_id: i32,
|
||||
title: String,
|
||||
is_completed: bool,
|
||||
created_at: NaiveDateTime,
|
||||
updated_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
impl Subtask {
|
||||
pub fn id(&self) -> i32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn task_id(&self) -> i32 {
|
||||
self.task_id
|
||||
}
|
||||
|
||||
pub fn title(&self) -> &str {
|
||||
&self.title
|
||||
}
|
||||
|
||||
pub fn is_completed(&self) -> bool {
|
||||
self.is_completed
|
||||
}
|
||||
|
||||
pub fn created_at(&self) -> NaiveDateTime {
|
||||
self.created_at
|
||||
}
|
||||
|
||||
pub fn updated_at(&self) -> NaiveDateTime {
|
||||
self.updated_at
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Subtask {}
|
||||
@@ -44,9 +70,9 @@ impl PartialOrd<Self> for Subtask {
|
||||
|
||||
impl Ord for Subtask {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.is_completed
|
||||
.cmp(&other.is_completed)
|
||||
.then(self.created_at.cmp(&other.created_at))
|
||||
self.is_completed()
|
||||
.cmp(&other.is_completed())
|
||||
.then(self.created_at().cmp(&other.created_at()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,12 +90,18 @@ pub struct NewSubtask {
|
||||
pub is_completed: bool,
|
||||
}
|
||||
|
||||
impl From<Subtask> for NewSubtask {
|
||||
fn from(subtask: Subtask) -> Self {
|
||||
impl NewSubtask {
|
||||
pub fn new(task_id: i32, title: String, is_completed: bool) -> Self {
|
||||
Self {
|
||||
task_id: subtask.task_id,
|
||||
title: subtask.title,
|
||||
is_completed: subtask.is_completed,
|
||||
task_id,
|
||||
title,
|
||||
is_completed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Subtask> for NewSubtask {
|
||||
fn from(subtask: Subtask) -> Self {
|
||||
Self::new(subtask.task_id, subtask.title, subtask.is_completed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,13 +17,43 @@ const TITLE_LENGTH_MAX: u64 = 255;
|
||||
#[cfg_attr(feature = "server", derive(Queryable, Selectable, Identifiable))]
|
||||
#[cfg_attr(feature = "server", diesel(table_name = tasks, check_for_backend(diesel::pg::Pg)))]
|
||||
pub struct Task {
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub deadline: Option<chrono::NaiveDate>,
|
||||
pub category: Category,
|
||||
pub project_id: Option<i32>,
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: NaiveDateTime,
|
||||
id: i32,
|
||||
title: String,
|
||||
deadline: Option<chrono::NaiveDate>,
|
||||
category: Category,
|
||||
project_id: Option<i32>,
|
||||
created_at: NaiveDateTime,
|
||||
updated_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
pub fn id(&self) -> i32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn title(&self) -> &str {
|
||||
&self.title
|
||||
}
|
||||
|
||||
pub fn deadline(&self) -> Option<chrono::NaiveDate> {
|
||||
self.deadline
|
||||
}
|
||||
|
||||
pub fn category(&self) -> &Category {
|
||||
&self.category
|
||||
}
|
||||
|
||||
pub fn project_id(&self) -> Option<i32> {
|
||||
self.project_id
|
||||
}
|
||||
|
||||
pub fn created_at(&self) -> NaiveDateTime {
|
||||
self.created_at
|
||||
}
|
||||
|
||||
pub fn updated_at(&self) -> NaiveDateTime {
|
||||
self.updated_at
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Task {}
|
||||
@@ -53,22 +83,24 @@ impl Ord for Task {
|
||||
.cmp(other_date)
|
||||
.then(
|
||||
ReverseOrdOption::from(
|
||||
&self_time.as_ref().map(|calendar_time| calendar_time.time),
|
||||
&self_time.as_ref().map(|calendar_time| calendar_time.time()),
|
||||
)
|
||||
.cmp(&ReverseOrdOption::from(
|
||||
&other_time.as_ref().map(|calendar_time| calendar_time.time),
|
||||
&other_time
|
||||
.as_ref()
|
||||
.map(|calendar_time| calendar_time.time()),
|
||||
)),
|
||||
)
|
||||
.then(
|
||||
ReverseOrdOption::from(&self.deadline)
|
||||
.cmp(&ReverseOrdOption::from(&other.deadline)),
|
||||
ReverseOrdOption::from(&self.deadline())
|
||||
.cmp(&ReverseOrdOption::from(&other.deadline())),
|
||||
)
|
||||
.then(self.created_at.cmp(&other.created_at)),
|
||||
(Category::Done, Category::Done) | (Category::Trash, Category::Trash) => {
|
||||
self.updated_at.cmp(&other.updated_at).reverse()
|
||||
}
|
||||
(_, _) => ReverseOrdOption::from(&self.deadline)
|
||||
.cmp(&ReverseOrdOption::from(&other.deadline))
|
||||
(_, _) => ReverseOrdOption::from(&self.deadline())
|
||||
.cmp(&ReverseOrdOption::from(&other.deadline()))
|
||||
.then(self.created_at.cmp(&other.created_at)),
|
||||
}
|
||||
}
|
||||
@@ -76,8 +108,22 @@ impl Ord for Task {
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
|
||||
pub struct TaskWithSubtasks {
|
||||
pub task: Task,
|
||||
pub subtasks: Vec<Subtask>,
|
||||
task: Task,
|
||||
subtasks: Vec<Subtask>,
|
||||
}
|
||||
|
||||
impl TaskWithSubtasks {
|
||||
pub fn new(task: Task, subtasks: Vec<Subtask>) -> Self {
|
||||
Self { task, subtasks }
|
||||
}
|
||||
|
||||
pub fn task(&self) -> &Task {
|
||||
&self.task
|
||||
}
|
||||
|
||||
pub fn subtasks(&self) -> &Vec<Subtask> {
|
||||
&self.subtasks
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for TaskWithSubtasks {}
|
||||
@@ -90,7 +136,7 @@ impl PartialOrd<Self> for TaskWithSubtasks {
|
||||
|
||||
impl Ord for TaskWithSubtasks {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.task.cmp(&other.task)
|
||||
self.task().cmp(other.task())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,13 +155,24 @@ pub struct NewTask {
|
||||
pub project_id: Option<i32>,
|
||||
}
|
||||
|
||||
impl From<Task> for NewTask {
|
||||
fn from(task: Task) -> Self {
|
||||
impl NewTask {
|
||||
pub fn new(
|
||||
title: String,
|
||||
deadline: Option<chrono::NaiveDate>,
|
||||
category: Category,
|
||||
project_id: Option<i32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
title: task.title,
|
||||
deadline: task.deadline,
|
||||
category: task.category,
|
||||
project_id: task.project_id,
|
||||
title,
|
||||
deadline,
|
||||
category,
|
||||
project_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Task> for NewTask {
|
||||
fn from(task: Task) -> Self {
|
||||
Self::new(task.title, task.deadline, task.category, task.project_id)
|
||||
}
|
||||
}
|
||||
|
||||
34
src/query/mod.rs
Normal file
34
src/query/mod.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use crate::models::category::Category;
|
||||
use crate::models::project::Project;
|
||||
use crate::models::subtask::Subtask;
|
||||
use crate::models::task::{Task, TaskWithSubtasks};
|
||||
|
||||
pub(crate) mod projects;
|
||||
pub(crate) mod subtasks;
|
||||
pub(crate) mod tasks;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub(crate) enum QueryValue {
|
||||
Projects(Vec<Project>),
|
||||
Tasks(Vec<Task>),
|
||||
TasksWithSubtasks(Vec<TaskWithSubtasks>),
|
||||
Subtasks(Vec<Subtask>),
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum QueryErrors {
|
||||
Error(ErrorVec<Error>),
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
|
||||
pub(crate) enum QueryKey {
|
||||
Projects,
|
||||
Tasks,
|
||||
TasksInCategory(Category),
|
||||
TasksWithSubtasksInCategory(Category),
|
||||
SubtasksOfTaskId(i32),
|
||||
}
|
||||
21
src/query/projects.rs
Normal file
21
src/query/projects.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::server::projects::get_projects;
|
||||
use dioxus::prelude::ServerFnError;
|
||||
use dioxus_query::prelude::{use_get_query, QueryResult, UseQuery};
|
||||
|
||||
pub(crate) fn use_projects_query() -> UseQuery<QueryValue, QueryErrors, QueryKey> {
|
||||
use_get_query([QueryKey::Projects, QueryKey::Tasks], fetch_projects)
|
||||
}
|
||||
|
||||
async fn fetch_projects(keys: Vec<QueryKey>) -> QueryResult<QueryValue, QueryErrors> {
|
||||
if let Some(QueryKey::Projects) = keys.first() {
|
||||
match get_projects().await {
|
||||
Ok(projects) => Ok(QueryValue::Projects(projects)),
|
||||
Err(ServerFnError::WrappedServerError(errors)) => Err(QueryErrors::Error(errors)),
|
||||
Err(error) => panic!("Unexpected error: {:?}", error),
|
||||
}
|
||||
.into()
|
||||
} else {
|
||||
panic!("Unexpected query keys: {:?}", keys);
|
||||
}
|
||||
}
|
||||
26
src/query/subtasks.rs
Normal file
26
src/query/subtasks.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::server::subtasks::get_subtasks_of_task;
|
||||
use dioxus::prelude::ServerFnError;
|
||||
use dioxus_query::prelude::{use_get_query, QueryResult, UseQuery};
|
||||
|
||||
pub(crate) fn use_subtasks_of_task_query(
|
||||
task_id: i32,
|
||||
) -> UseQuery<QueryValue, QueryErrors, QueryKey> {
|
||||
use_get_query(
|
||||
[QueryKey::SubtasksOfTaskId(task_id)],
|
||||
fetch_subtasks_of_task,
|
||||
)
|
||||
}
|
||||
|
||||
async fn fetch_subtasks_of_task(keys: Vec<QueryKey>) -> QueryResult<QueryValue, QueryErrors> {
|
||||
if let Some(QueryKey::SubtasksOfTaskId(task_id)) = keys.first() {
|
||||
match get_subtasks_of_task(*task_id).await {
|
||||
Ok(subtasks) => Ok(QueryValue::Subtasks(subtasks)),
|
||||
Err(ServerFnError::WrappedServerError(errors)) => Err(QueryErrors::Error(errors)),
|
||||
Err(error) => panic!("Unexpected error: {:?}", error),
|
||||
}
|
||||
.into()
|
||||
} else {
|
||||
panic!("Unexpected query keys: {:?}", keys);
|
||||
}
|
||||
}
|
||||
56
src/query/tasks.rs
Normal file
56
src/query/tasks.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
use crate::models::category::Category;
|
||||
use crate::query::{QueryErrors, QueryKey, QueryValue};
|
||||
use crate::server::tasks::{get_tasks_in_category, get_tasks_with_subtasks_in_category};
|
||||
use dioxus::prelude::ServerFnError;
|
||||
use dioxus_query::prelude::{use_get_query, QueryResult, UseQuery};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn use_tasks_in_category_query(
|
||||
category: Category,
|
||||
) -> UseQuery<QueryValue, QueryErrors, QueryKey> {
|
||||
use_get_query(
|
||||
[QueryKey::TasksInCategory(category), QueryKey::Tasks],
|
||||
fetch_tasks_in_category,
|
||||
)
|
||||
}
|
||||
|
||||
async fn fetch_tasks_in_category(keys: Vec<QueryKey>) -> QueryResult<QueryValue, QueryErrors> {
|
||||
if let Some(QueryKey::TasksInCategory(category)) = keys.first() {
|
||||
match get_tasks_in_category(category.clone()).await {
|
||||
Ok(tasks) => Ok(QueryValue::Tasks(tasks)),
|
||||
Err(ServerFnError::WrappedServerError(errors)) => Err(QueryErrors::Error(errors)),
|
||||
Err(error) => panic!("Unexpected error: {:?}", error),
|
||||
}
|
||||
.into()
|
||||
} else {
|
||||
panic!("Unexpected query keys: {:?}", keys);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn use_tasks_with_subtasks_in_category_query(
|
||||
category: Category,
|
||||
) -> UseQuery<QueryValue, QueryErrors, QueryKey> {
|
||||
use_get_query(
|
||||
[
|
||||
QueryKey::TasksWithSubtasksInCategory(category.clone()),
|
||||
QueryKey::TasksInCategory(category),
|
||||
QueryKey::Tasks,
|
||||
],
|
||||
fetch_tasks_with_subtasks_in_category,
|
||||
)
|
||||
}
|
||||
|
||||
async fn fetch_tasks_with_subtasks_in_category(
|
||||
keys: Vec<QueryKey>,
|
||||
) -> QueryResult<QueryValue, QueryErrors> {
|
||||
if let Some(QueryKey::TasksWithSubtasksInCategory(category)) = keys.first() {
|
||||
match get_tasks_with_subtasks_in_category(category.clone()).await {
|
||||
Ok(tasks) => Ok(QueryValue::TasksWithSubtasks(tasks)),
|
||||
Err(ServerFnError::WrappedServerError(errors)) => Err(QueryErrors::Error(errors)),
|
||||
Err(error) => panic!("Unexpected error: {:?}", error),
|
||||
}
|
||||
.into()
|
||||
} else {
|
||||
panic!("Unexpected query keys: {:?}", keys);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
use crate::layouts;
|
||||
use crate::views::category_calendar_page::CategoryCalendarPage;
|
||||
use crate::views::category_done_page::CategoryDonePage;
|
||||
use crate::views::category_inbox_page::CategoryInboxPage;
|
||||
use crate::views::category_long_term_page::CategoryLongTermPage;
|
||||
use crate::views::category_next_steps_page::CategoryNextStepsPage;
|
||||
use crate::views::category_someday_maybe_page::CategorySomedayMaybePage;
|
||||
use crate::views::category_today_page::CategoryTodayPage;
|
||||
use crate::views::category_trash_page::CategoryTrashPage;
|
||||
use crate::views::category_waiting_for_page::CategoryWaitingForPage;
|
||||
use crate::views::not_found_page::NotFoundPage;
|
||||
use crate::views::projects_page::ProjectsPage;
|
||||
use crate::components::layout::Layout;
|
||||
use crate::components::pages::category_calendar_page::CategoryCalendarPage;
|
||||
use crate::components::pages::category_done_page::CategoryDonePage;
|
||||
use crate::components::pages::category_inbox_page::CategoryInboxPage;
|
||||
use crate::components::pages::category_long_term_page::CategoryLongTermPage;
|
||||
use crate::components::pages::category_next_steps_page::CategoryNextStepsPage;
|
||||
use crate::components::pages::category_someday_maybe_page::CategorySomedayMaybePage;
|
||||
use crate::components::pages::category_today_page::CategoryTodayPage;
|
||||
use crate::components::pages::category_trash_page::CategoryTrashPage;
|
||||
use crate::components::pages::category_waiting_for_page::CategoryWaitingForPage;
|
||||
use crate::components::pages::not_found_page::NotFoundPage;
|
||||
use crate::components::pages::projects_page::ProjectsPage;
|
||||
use dioxus::prelude::*;
|
||||
|
||||
// All variants have the same postfix because they have to match the component names.
|
||||
@@ -17,7 +17,7 @@ use dioxus::prelude::*;
|
||||
#[derive(Clone, Routable, Debug, PartialEq)]
|
||||
#[rustfmt::skip]
|
||||
pub(crate) enum Route {
|
||||
#[layout(layouts::Main)]
|
||||
#[layout(Layout)]
|
||||
#[redirect("/", || Route::CategoryTodayPage {})]
|
||||
#[route("/today")]
|
||||
CategoryTodayPage,
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::prelude::*;
|
||||
|
||||
const DATABASE_URL: &str = "postgres://app:app@db/todo_baggins";
|
||||
use dotenvy::dotenv;
|
||||
use std::env;
|
||||
|
||||
pub(crate) fn establish_database_connection() -> ConnectionResult<PgConnection> {
|
||||
PgConnection::establish(DATABASE_URL)
|
||||
dotenv().expect("Could not load environment variables.");
|
||||
|
||||
let database_url =
|
||||
env::var("DATABASE_URL").expect("The environment variable DATABASE_URL has to be set.");
|
||||
PgConnection::establish(&database_url)
|
||||
}
|
||||
|
||||
15
src/server/internationalization.rs
Normal file
15
src/server/internationalization.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use dioxus::prelude::ServerFnError;
|
||||
use dioxus::prelude::*;
|
||||
#[cfg(feature = "server")]
|
||||
use dotenvy::dotenv;
|
||||
use std::env;
|
||||
use unic_langid_impl::LanguageIdentifier;
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn get_language_identifier() -> Result<LanguageIdentifier, ServerFnError> {
|
||||
dotenv().expect("Could not load environment variables from the .env file.");
|
||||
|
||||
Ok(env::var("LANGUAGE_CODE")
|
||||
.expect("The environment variable LANGUAGE_CODE must be set.")
|
||||
.parse::<LanguageIdentifier>()?)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#[cfg(feature = "server")]
|
||||
pub(crate) mod database_connection;
|
||||
pub(crate) mod internationalization;
|
||||
pub(crate) mod projects;
|
||||
pub(crate) mod subtasks;
|
||||
pub(crate) mod tasks;
|
||||
pub(crate) mod updates;
|
||||
|
||||
@@ -1,75 +1,100 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use crate::errors::project_error::ProjectError;
|
||||
use crate::models::project::{NewProject, Project};
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::database_connection::establish_database_connection;
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::updates::publish_update;
|
||||
#[cfg(feature = "server")]
|
||||
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl, SelectableHelper};
|
||||
use dioxus::prelude::*;
|
||||
#[cfg(feature = "server")]
|
||||
use validator::Validate;
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn create_project(new_project: NewProject) -> Result<Project> {
|
||||
pub(crate) async fn create_project(
|
||||
new_project: NewProject,
|
||||
) -> Result<Project, ServerFnError<ErrorVec<ProjectError>>> {
|
||||
use crate::schema::projects;
|
||||
|
||||
// TODO: replace with model sanitization (https://github.com/matous-volf/todo-baggins/issues/13)
|
||||
let mut new_project = new_project;
|
||||
new_project.title = new_project.title.trim().to_owned();
|
||||
|
||||
new_project.validate()?;
|
||||
new_project
|
||||
.validate()
|
||||
.map_err::<ErrorVec<ProjectError>, _>(|errors| errors.into())?;
|
||||
|
||||
let mut connection =
|
||||
establish_database_connection().map_err::<ErrorVec<ProjectError>, _>(|_| {
|
||||
vec![ProjectError::Error(Error::ServerInternal)].into()
|
||||
})?;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let new_project = diesel::insert_into(projects::table)
|
||||
.values(&new_project)
|
||||
.returning(Project::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
|
||||
publish_update().await;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<ProjectError>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
Ok(new_project)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn get_projects() -> Result<Vec<Project>> {
|
||||
pub(crate) async fn get_projects() -> Result<Vec<Project>, ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::projects::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let results = projects
|
||||
.select(Project::as_select())
|
||||
.load::<Project>(&mut connection)?;
|
||||
.load::<Project>(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn edit_project(project_id: i32, new_project: NewProject) -> Result<Project> {
|
||||
pub(crate) async fn edit_project(
|
||||
project_id: i32,
|
||||
new_project: NewProject,
|
||||
) -> Result<Project, ServerFnError<ErrorVec<ProjectError>>> {
|
||||
use crate::schema::projects::dsl::*;
|
||||
|
||||
// TODO: replace with model sanitization (https://github.com/matous-volf/todo-baggins/issues/13)
|
||||
let mut new_project = new_project;
|
||||
new_project.title = new_project.title.trim().to_owned();
|
||||
|
||||
new_project.validate()?;
|
||||
new_project
|
||||
.validate()
|
||||
.map_err::<ErrorVec<ProjectError>, _>(|errors| errors.into())?;
|
||||
|
||||
let mut connection =
|
||||
establish_database_connection().map_err::<ErrorVec<ProjectError>, _>(|_| {
|
||||
vec![ProjectError::Error(Error::ServerInternal)].into()
|
||||
})?;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let updated_project = diesel::update(projects)
|
||||
.filter(id.eq(project_id))
|
||||
.set(title.eq(new_project.title))
|
||||
.returning(Project::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<ProjectError>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(updated_project)
|
||||
}
|
||||
|
||||
// TODO: Get rid of this suppression.
|
||||
//noinspection DuplicatedCode
|
||||
#[server]
|
||||
pub(crate) async fn delete_project(project_id: i32) -> Result<()> {
|
||||
pub(crate) async fn delete_project(project_id: i32) -> Result<(), ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::projects::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
diesel::delete(projects.filter(id.eq(project_id))).execute(&mut connection)?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
diesel::delete(projects.filter(id.eq(project_id)))
|
||||
.execute(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,64 +1,86 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use crate::errors::subtask_error::SubtaskError;
|
||||
use crate::models::subtask::{NewSubtask, Subtask};
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::database_connection::establish_database_connection;
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::tasks::trigger_task_updated_at;
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::updates::publish_update;
|
||||
#[cfg(feature = "server")]
|
||||
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl, SelectableHelper};
|
||||
use dioxus::prelude::*;
|
||||
#[cfg(feature = "server")]
|
||||
use validator::Validate;
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn create_subtask(new_subtask: NewSubtask) -> Result<Subtask> {
|
||||
pub(crate) async fn create_subtask(
|
||||
new_subtask: NewSubtask,
|
||||
) -> Result<Subtask, ServerFnError<ErrorVec<SubtaskError>>> {
|
||||
use crate::schema::subtasks;
|
||||
|
||||
// TODO: replace with model sanitization (https://github.com/matous-volf/todo-baggins/issues/13)
|
||||
let mut new_subtask = new_subtask;
|
||||
new_subtask.title = new_subtask.title.trim().to_owned();
|
||||
|
||||
new_subtask.validate()?;
|
||||
new_subtask
|
||||
.validate()
|
||||
.map_err::<ErrorVec<SubtaskError>, _>(|errors| errors.into())?;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection =
|
||||
establish_database_connection().map_err::<ErrorVec<SubtaskError>, _>(|_| {
|
||||
vec![SubtaskError::Error(Error::ServerInternal)].into()
|
||||
})?;
|
||||
|
||||
let created_subtask = diesel::insert_into(subtasks::table)
|
||||
.values(&new_subtask)
|
||||
.returning(Subtask::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<SubtaskError>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
trigger_task_updated_at(new_subtask.task_id).await?;
|
||||
trigger_task_updated_at(new_subtask.task_id)
|
||||
.await
|
||||
.map_err::<ErrorVec<SubtaskError>, _>(|error_vec| error_vec.into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(created_subtask)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn get_subtasks_of_task(filtered_task_id: i32) -> Result<Vec<Subtask>> {
|
||||
pub(crate) async fn get_subtasks_of_task(
|
||||
filtered_task_id: i32,
|
||||
) -> Result<Vec<Subtask>, ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::subtasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let results = subtasks
|
||||
.select(Subtask::as_select())
|
||||
.filter(task_id.eq(filtered_task_id))
|
||||
.load::<Subtask>(&mut connection)?;
|
||||
.load::<Subtask>(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn edit_subtask(subtask_id: i32, new_subtask: NewSubtask) -> Result<Subtask> {
|
||||
pub(crate) async fn edit_subtask(
|
||||
subtask_id: i32,
|
||||
new_subtask: NewSubtask,
|
||||
) -> Result<Subtask, ServerFnError<ErrorVec<SubtaskError>>> {
|
||||
use crate::schema::subtasks::dsl::*;
|
||||
|
||||
// TODO: replace with model sanitization (https://github.com/matous-volf/todo-baggins/issues/13)
|
||||
let mut new_subtask = new_subtask;
|
||||
new_subtask.title = new_subtask.title.trim().to_owned();
|
||||
|
||||
new_subtask.validate()?;
|
||||
new_subtask
|
||||
.validate()
|
||||
.map_err::<ErrorVec<SubtaskError>, _>(|errors| errors.into())?;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection =
|
||||
establish_database_connection().map_err::<ErrorVec<SubtaskError>, _>(|_| {
|
||||
vec![SubtaskError::Error(Error::ServerInternal)].into()
|
||||
})?;
|
||||
|
||||
let updated_task = diesel::update(subtasks)
|
||||
.filter(id.eq(subtask_id))
|
||||
@@ -67,41 +89,50 @@ pub(crate) async fn edit_subtask(subtask_id: i32, new_subtask: NewSubtask) -> Re
|
||||
is_completed.eq(new_subtask.is_completed),
|
||||
))
|
||||
.returning(Subtask::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<SubtaskError>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
trigger_task_updated_at(new_subtask.task_id).await?;
|
||||
trigger_task_updated_at(new_subtask.task_id)
|
||||
.await
|
||||
.map_err::<ErrorVec<SubtaskError>, _>(|error_vec| error_vec.into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(updated_task)
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub(super) async fn restore_subtasks_of_task(filtered_task_id: i32) -> Result<Vec<Subtask>> {
|
||||
#[server]
|
||||
pub(crate) async fn restore_subtasks_of_task(
|
||||
filtered_task_id: i32,
|
||||
) -> Result<Vec<Subtask>, ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::subtasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let updated_subtasks = diesel::update(subtasks)
|
||||
.filter(task_id.eq(filtered_task_id))
|
||||
.set(is_completed.eq(false))
|
||||
.returning(Subtask::as_returning())
|
||||
.get_results(&mut connection)?;
|
||||
.get_results(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
Ok(updated_subtasks)
|
||||
}
|
||||
|
||||
// TODO: Get rid of this suppression.
|
||||
//noinspection DuplicatedCode
|
||||
#[server]
|
||||
pub(crate) async fn delete_subtask(subtask_id: i32) -> Result<()> {
|
||||
pub(crate) async fn delete_subtask(subtask_id: i32) -> Result<(), ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::subtasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let deleted_subtask = diesel::delete(subtasks.filter(id.eq(subtask_id)))
|
||||
.returning(Subtask::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
trigger_task_updated_at(deleted_subtask.task_id).await?;
|
||||
trigger_task_updated_at(deleted_subtask.task_id()).await?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use crate::errors::error::Error;
|
||||
use crate::errors::error_vec::ErrorVec;
|
||||
use crate::errors::task_error::TaskError;
|
||||
use crate::models::category::Category;
|
||||
#[cfg(feature = "server")]
|
||||
use crate::models::category::ReoccurrenceInterval;
|
||||
@@ -9,8 +12,6 @@ use crate::server::database_connection::establish_database_connection;
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::subtasks::restore_subtasks_of_task;
|
||||
#[cfg(feature = "server")]
|
||||
use crate::server::updates::publish_update;
|
||||
#[cfg(feature = "server")]
|
||||
use chrono::{Datelike, Days, Local, Months, NaiveDate};
|
||||
#[cfg(feature = "server")]
|
||||
use diesel::prelude::*;
|
||||
@@ -18,57 +19,70 @@ use diesel::prelude::*;
|
||||
use diesel::{ExpressionMethods, OptionalExtension, QueryDsl, RunQueryDsl, SelectableHelper};
|
||||
use dioxus::prelude::*;
|
||||
#[cfg(feature = "server")]
|
||||
use time::Month;
|
||||
use time::util::days_in_year_month;
|
||||
#[cfg(feature = "server")]
|
||||
use validator::Validate;
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn create_task(new_task: NewTask) -> Result<Task> {
|
||||
pub(crate) async fn create_task(
|
||||
new_task: NewTask,
|
||||
) -> Result<Task, ServerFnError<ErrorVec<TaskError>>> {
|
||||
use crate::schema::tasks;
|
||||
|
||||
// TODO: replace with model sanitization (https://github.com/matous-volf/todo-baggins/issues/13)
|
||||
let mut new_task = new_task;
|
||||
new_task.title = new_task.title.trim().to_owned();
|
||||
|
||||
new_task.validate()?;
|
||||
new_task
|
||||
.validate()
|
||||
.map_err::<ErrorVec<TaskError>, _>(|errors| errors.into())?;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection =
|
||||
establish_database_connection().map_err::<ErrorVec<TaskError>, _>(|_| {
|
||||
vec![TaskError::Error(Error::ServerInternal)].into()
|
||||
})?;
|
||||
|
||||
let new_task = diesel::insert_into(tasks::table)
|
||||
.values(&new_task)
|
||||
.returning(Task::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<TaskError>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(new_task)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn get_task(task_id: i32) -> Result<Task> {
|
||||
pub(crate) async fn get_task(task_id: i32) -> Result<Task, ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::tasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let task = tasks
|
||||
.find(task_id)
|
||||
.select(Task::as_select())
|
||||
.first(&mut connection)
|
||||
.optional()?;
|
||||
.optional()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
// TODO: Handle not finding the task.
|
||||
Ok(task.unwrap())
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn get_tasks_in_category(filtered_category: Category) -> Result<Vec<Task>> {
|
||||
pub(crate) async fn get_tasks_in_category(
|
||||
filtered_category: Category,
|
||||
) -> Result<Vec<Task>, ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::tasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let results = tasks
|
||||
.select(Task::as_select())
|
||||
.filter(filtered_category.eq_sql_predicate())
|
||||
.load::<Task>(&mut connection)?;
|
||||
.load::<Task>(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
@@ -76,40 +90,52 @@ pub(crate) async fn get_tasks_in_category(filtered_category: Category) -> Result
|
||||
#[server]
|
||||
pub(crate) async fn get_tasks_with_subtasks_in_category(
|
||||
filtered_category: Category,
|
||||
) -> Result<Vec<TaskWithSubtasks>> {
|
||||
) -> Result<Vec<TaskWithSubtasks>, ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::tasks;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let tasks_in_category = tasks::table
|
||||
.filter(filtered_category.eq_sql_predicate())
|
||||
.select(Task::as_select())
|
||||
.load(&mut connection)?;
|
||||
.load(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let subtasks = Subtask::belonging_to(&tasks_in_category)
|
||||
.select(Subtask::as_select())
|
||||
.load(&mut connection)?;
|
||||
.load(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let tasks_with_subtasks = subtasks
|
||||
.grouped_by(&tasks_in_category)
|
||||
.into_iter()
|
||||
.zip(tasks_in_category)
|
||||
.map(|(subtasks, task)| TaskWithSubtasks { task, subtasks })
|
||||
.map(|(pages, book)| TaskWithSubtasks::new(book, pages))
|
||||
.collect();
|
||||
|
||||
Ok(tasks_with_subtasks)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn edit_task(task_id: i32, mut new_task: NewTask) -> Result<Task> {
|
||||
pub(crate) async fn edit_task(
|
||||
task_id: i32,
|
||||
mut new_task: NewTask,
|
||||
) -> Result<Task, ServerFnError<ErrorVec<TaskError>>> {
|
||||
use crate::schema::tasks::dsl::*;
|
||||
|
||||
// TODO: replace with model sanitization (https://github.com/matous-volf/todo-baggins/issues/13)
|
||||
let mut new_task = new_task;
|
||||
new_task.title = new_task.title.trim().to_owned();
|
||||
|
||||
new_task.validate()?;
|
||||
new_task
|
||||
.validate()
|
||||
.map_err::<ErrorVec<TaskError>, _>(|errors| errors.into())?;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection =
|
||||
establish_database_connection().map_err::<ErrorVec<TaskError>, _>(|_| {
|
||||
vec![TaskError::Error(Error::ServerInternal)].into()
|
||||
})?;
|
||||
|
||||
let updated_task = diesel::update(tasks)
|
||||
.filter(id.eq(task_id))
|
||||
@@ -120,14 +146,14 @@ pub(crate) async fn edit_task(task_id: i32, mut new_task: NewTask) -> Result<Tas
|
||||
project_id.eq(new_task.project_id),
|
||||
))
|
||||
.returning(Task::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<TaskError>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(updated_task)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub(crate) async fn complete_task(task_id: i32) -> Result<Task> {
|
||||
pub(crate) async fn complete_task(task_id: i32) -> Result<Task, ServerFnError<ErrorVec<Error>>> {
|
||||
let task = get_task(task_id).await?;
|
||||
let mut new_task = NewTask::from(task);
|
||||
|
||||
@@ -137,13 +163,13 @@ pub(crate) async fn complete_task(task_id: i32) -> Result<Task> {
|
||||
..
|
||||
} = &mut new_task.category
|
||||
{
|
||||
match reoccurrence.interval {
|
||||
ReoccurrenceInterval::Day => *date = *date + Days::new(reoccurrence.length as u64),
|
||||
match reoccurrence.interval() {
|
||||
ReoccurrenceInterval::Day => *date = *date + Days::new(reoccurrence.length() as u64),
|
||||
ReoccurrenceInterval::Month | ReoccurrenceInterval::Year => {
|
||||
*date = *date
|
||||
+ Months::new(
|
||||
reoccurrence.length
|
||||
* if reoccurrence.interval == ReoccurrenceInterval::Year {
|
||||
reoccurrence.length()
|
||||
* if *(reoccurrence.interval()) == ReoccurrenceInterval::Year {
|
||||
12
|
||||
} else {
|
||||
1
|
||||
@@ -152,11 +178,10 @@ pub(crate) async fn complete_task(task_id: i32) -> Result<Task> {
|
||||
*date = NaiveDate::from_ymd_opt(
|
||||
date.year(),
|
||||
date.month(),
|
||||
reoccurrence.start_date.day().min(
|
||||
Month::try_from(date.month() as u8)
|
||||
.unwrap()
|
||||
.length(date.year()) as u32,
|
||||
),
|
||||
reoccurrence.start_date().day().min(days_in_year_month(
|
||||
date.year(),
|
||||
(date.month() as u8).try_into().unwrap(),
|
||||
) as u32),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -166,35 +191,42 @@ pub(crate) async fn complete_task(task_id: i32) -> Result<Task> {
|
||||
new_task.category = Category::Done;
|
||||
}
|
||||
|
||||
let updated_task = edit_task(task_id, new_task).await?;
|
||||
let updated_task = edit_task(task_id, new_task)
|
||||
.await
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(updated_task)
|
||||
}
|
||||
|
||||
// TODO: Get rid of this suppression.
|
||||
//noinspection DuplicatedCode
|
||||
#[server]
|
||||
pub(crate) async fn delete_task(task_id: i32) -> Result<()> {
|
||||
pub(crate) async fn delete_task(task_id: i32) -> Result<(), ServerFnError<ErrorVec<Error>>> {
|
||||
use crate::schema::tasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
diesel::delete(tasks.filter(id.eq(task_id))).execute(&mut connection)?;
|
||||
diesel::delete(tasks.filter(id.eq(task_id)))
|
||||
.execute(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
publish_update().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub(crate) async fn trigger_task_updated_at(task_id: i32) -> Result<Task> {
|
||||
pub(crate) async fn trigger_task_updated_at(task_id: i32) -> Result<Task, ErrorVec<Error>> {
|
||||
use crate::schema::tasks::dsl::*;
|
||||
|
||||
let mut connection = establish_database_connection()?;
|
||||
let mut connection = establish_database_connection()
|
||||
.map_err::<ErrorVec<Error>, _>(|_| vec![Error::ServerInternal].into())?;
|
||||
|
||||
let updated_task = diesel::update(tasks)
|
||||
.filter(id.eq(task_id))
|
||||
.set(updated_at.eq(Local::now().naive_local()))
|
||||
.returning(Task::as_returning())
|
||||
.get_result(&mut connection)?;
|
||||
.get_result(&mut connection)
|
||||
.map_err::<ErrorVec<Error>, _>(|error| vec![error.into()].into())?;
|
||||
|
||||
Ok(updated_task)
|
||||
}
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
use dioxus::{
|
||||
fullstack::{WebSocketOptions, Websocket},
|
||||
prelude::*,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
use rand::random;
|
||||
#[cfg(feature = "server")]
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct UpdateEvent;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
mod server_only {
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
ops::Deref,
|
||||
sync::LazyLock,
|
||||
};
|
||||
|
||||
use dioxus::fullstack::TypedWebsocket;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
use crate::server::updates::UpdateEvent;
|
||||
|
||||
pub(super) struct SubscribedClient {
|
||||
pub(super) websocket: Mutex<TypedWebsocket<UpdateEvent, UpdateEvent>>,
|
||||
}
|
||||
|
||||
pub(super) struct SubscribedClients(RwLock<HashMap<u64, SubscribedClient>>);
|
||||
|
||||
impl Deref for SubscribedClients {
|
||||
type Target = RwLock<HashMap<u64, SubscribedClient>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) static SUBSCRIBED_CLIENTS: LazyLock<SubscribedClients> =
|
||||
LazyLock::new(|| SubscribedClients(RwLock::new(HashMap::new())));
|
||||
|
||||
pub(crate) async fn publish_update() {
|
||||
let mut disconnected_client_ids = HashSet::new();
|
||||
let subscribed_clients = SUBSCRIBED_CLIENTS.read().await;
|
||||
for (id, client) in subscribed_clients.iter() {
|
||||
if let Err(_) = client.websocket.lock().await.send(UpdateEvent).await {
|
||||
disconnected_client_ids.insert(id.clone());
|
||||
}
|
||||
}
|
||||
drop(subscribed_clients);
|
||||
if !disconnected_client_ids.is_empty() {
|
||||
let mut subscribed_clients = SUBSCRIBED_CLIENTS.write().await;
|
||||
subscribed_clients.retain(|id, _| !disconnected_client_ids.contains(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub(super) use server_only::*;
|
||||
|
||||
#[get("/api/subscribe_to_updates")]
|
||||
pub(crate) async fn subscribe_to_updates(
|
||||
websocket_options: WebSocketOptions,
|
||||
) -> Result<Websocket<UpdateEvent, UpdateEvent>> {
|
||||
Ok(websocket_options.on_upgrade(move |socket| async move {
|
||||
SUBSCRIBED_CLIENTS.write().await.insert(
|
||||
random(),
|
||||
SubscribedClient {
|
||||
websocket: Mutex::new(socket),
|
||||
},
|
||||
);
|
||||
}))
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/** @type {import("tailwindcss").Config} */
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
mode: "all",
|
||||
content: ["./src/**/*.{rs,html,css}"],
|
||||
content: ["./src/**/*.{rs,html,css}", "./dist/**/*.html"],
|
||||
theme: {
|
||||
fontFamily: {
|
||||
sans: ["Inter", "sans-serif"],
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user