Compare commits

...

10 Commits

Author SHA1 Message Date
808c805cde Fix dockerfile
Some checks failed
parsley/pipeline/head There was a failure building this commit
2024-10-18 10:18:16 -05:00
7ead02ad7e progress and autosize 2024-10-02 16:20:07 -05:00
67c23015ab Continue converting to composition api 2024-10-02 14:34:50 -05:00
0d35f50dbf Continue converting to composition api 2024-10-01 09:32:09 -05:00
a071e6b21e Begin converting to composition api 2024-09-29 13:35:49 -05:00
b957d44aed style cleanup 2024-09-29 09:44:40 -05:00
f246f71aa9 Upgrade shakapacker, vue; switch to pinia 2024-09-28 20:58:25 -05:00
bb2e29f25c upgrade ruby/rails 2024-09-28 11:50:07 -05:00
552524e78b upgrade to shakapacker 2022-12-01 20:13:53 -06:00
2b77bc9fb8 rails 7/ruby 3 2022-12-01 18:02:26 -06:00
145 changed files with 10712 additions and 11479 deletions

View File

@ -1 +0,0 @@
> 1%, not ie <= 12

View File

@ -5,3 +5,5 @@ tmp/*.*
public/assets public/assets
public/packs public/packs
node_modules/ node_modules/
.yarn
.pnp.*

11
.gitignore vendored
View File

@ -9,7 +9,7 @@
# Ignore the default SQLite database. # Ignore the default SQLite database.
/db/*.sqlite3 /db/*.sqlite3
/db/*.sqlite3-journal /db/*.sqlite3*
# Ignore all logfiles and tempfiles. # Ignore all logfiles and tempfiles.
/log/* /log/*
@ -28,3 +28,12 @@
yarn-debug.log* yarn-debug.log*
.yarn-integrity .yarn-integrity
/dist /dist
/public/packs
/public/packs-test
/node_modules
/yarn-error.log
yarn-debug.log*
.yarn-integrity
.yarn
.pnp.*

View File

@ -1 +1 @@
3.1.2 3.3.5

View File

@ -1,4 +1,4 @@
FROM ruby:3.1.2-bullseye FROM ruby:3.3.5-bookworm
RUN curl -sL https://deb.nodesource.com/setup_lts.x | bash - && \ RUN curl -sL https://deb.nodesource.com/setup_lts.x | bash - && \
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \

24
Gemfile
View File

@ -1,30 +1,30 @@
source 'https://rubygems.org' source 'https://rubygems.org'
gem 'rails', '6.1.7' gem 'rails', '7.2.1'
gem 'pg', '~> 1.4.5' gem 'pg', '~> 1.5.8'
gem 'webpacker', '5.4.3' gem 'shakapacker', '8.0.2'
gem 'bootsnap', '>= 1.1.0', require: false gem 'bootsnap', '>= 1.1.0', require: false
gem 'net-smtp'
gem 'oj', '~> 3.13.23' gem 'oj', '~> 3.16.6'
gem 'csv', '~> 3.3'
gem 'kaminari', '~> 1.2.2' gem 'kaminari', '~> 1.2.2'
gem 'unitwise', '~> 2.3.0' gem 'unitwise', '~> 2.3.0'
gem 'redcarpet', '~> 3.5.1' gem 'redcarpet', '~> 3.6.0'
gem 'dalli', '~> 3.2.3' gem 'dalli', '~> 3.2.8'
gem 'puma', '~> 5.6' gem 'puma', '~> 6.4'
gem 'bcrypt', '~> 3.1.18' gem 'bcrypt', '~> 3.1.18'
gem 'tzinfo-data' gem 'tzinfo-data'
group :development, :test do group :development, :test do
gem 'sqlite3', '~> 1.5.4' gem 'sqlite3', '~> 2.1.0'
gem 'guard', '~> 2.18.0' gem 'guard', '~> 2.18.0'
gem 'guard-rspec', require: false gem 'guard-rspec', require: false
gem 'rspec-rails', '~> 6.0.1' gem 'rspec-rails', '~> 7.0.1'
gem 'rails-controller-testing' gem 'rails-controller-testing'
gem 'factory_bot_rails', '~> 6.2.0' gem 'factory_bot_rails', '~> 6.4.3'
gem 'database_cleaner', '~> 2.0.1' gem 'database_cleaner', '~> 2.0.2'
end end

View File

@ -1,91 +1,108 @@
GEM GEM
remote: https://rubygems.org/ remote: https://rubygems.org/
specs: specs:
actioncable (6.1.7) actioncable (7.2.1)
actionpack (= 6.1.7) actionpack (= 7.2.1)
activesupport (= 6.1.7) activesupport (= 7.2.1)
nio4r (~> 2.0) nio4r (~> 2.0)
websocket-driver (>= 0.6.1) websocket-driver (>= 0.6.1)
actionmailbox (6.1.7) zeitwerk (~> 2.6)
actionpack (= 6.1.7) actionmailbox (7.2.1)
activejob (= 6.1.7) actionpack (= 7.2.1)
activerecord (= 6.1.7) activejob (= 7.2.1)
activestorage (= 6.1.7) activerecord (= 7.2.1)
activesupport (= 6.1.7) activestorage (= 7.2.1)
mail (>= 2.7.1) activesupport (= 7.2.1)
actionmailer (6.1.7) mail (>= 2.8.0)
actionpack (= 6.1.7) actionmailer (7.2.1)
actionview (= 6.1.7) actionpack (= 7.2.1)
activejob (= 6.1.7) actionview (= 7.2.1)
activesupport (= 6.1.7) activejob (= 7.2.1)
mail (~> 2.5, >= 2.5.4) activesupport (= 7.2.1)
rails-dom-testing (~> 2.0) mail (>= 2.8.0)
actionpack (6.1.7) rails-dom-testing (~> 2.2)
actionview (= 6.1.7) actionpack (7.2.1)
activesupport (= 6.1.7) actionview (= 7.2.1)
rack (~> 2.0, >= 2.0.9) activesupport (= 7.2.1)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.2.0)
actiontext (6.1.7)
actionpack (= 6.1.7)
activerecord (= 6.1.7)
activestorage (= 6.1.7)
activesupport (= 6.1.7)
nokogiri (>= 1.8.5) nokogiri (>= 1.8.5)
actionview (6.1.7) racc
activesupport (= 6.1.7) rack (>= 2.2.4, < 3.2)
rack-session (>= 1.0.1)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.2)
rails-html-sanitizer (~> 1.6)
useragent (~> 0.16)
actiontext (7.2.1)
actionpack (= 7.2.1)
activerecord (= 7.2.1)
activestorage (= 7.2.1)
activesupport (= 7.2.1)
globalid (>= 0.6.0)
nokogiri (>= 1.8.5)
actionview (7.2.1)
activesupport (= 7.2.1)
builder (~> 3.1) builder (~> 3.1)
erubi (~> 1.4) erubi (~> 1.11)
rails-dom-testing (~> 2.0) rails-dom-testing (~> 2.2)
rails-html-sanitizer (~> 1.1, >= 1.2.0) rails-html-sanitizer (~> 1.6)
activejob (6.1.7) activejob (7.2.1)
activesupport (= 6.1.7) activesupport (= 7.2.1)
globalid (>= 0.3.6) globalid (>= 0.3.6)
activemodel (6.1.7) activemodel (7.2.1)
activesupport (= 6.1.7) activesupport (= 7.2.1)
activerecord (6.1.7) activerecord (7.2.1)
activemodel (= 6.1.7) activemodel (= 7.2.1)
activesupport (= 6.1.7) activesupport (= 7.2.1)
activestorage (6.1.7) timeout (>= 0.4.0)
actionpack (= 6.1.7) activestorage (7.2.1)
activejob (= 6.1.7) actionpack (= 7.2.1)
activerecord (= 6.1.7) activejob (= 7.2.1)
activesupport (= 6.1.7) activerecord (= 7.2.1)
activesupport (= 7.2.1)
marcel (~> 1.0) marcel (~> 1.0)
mini_mime (>= 1.1.0) activesupport (7.2.1)
activesupport (6.1.7) base64
concurrent-ruby (~> 1.0, >= 1.0.2) bigdecimal
concurrent-ruby (~> 1.0, >= 1.3.1)
connection_pool (>= 2.2.5)
drb
i18n (>= 1.6, < 2) i18n (>= 1.6, < 2)
logger (>= 1.4.2)
minitest (>= 5.1) minitest (>= 5.1)
tzinfo (~> 2.0) securerandom (>= 0.3)
zeitwerk (~> 2.3) tzinfo (~> 2.0, >= 2.0.5)
bcrypt (3.1.18) base64 (0.2.0)
bootsnap (1.14.0) bcrypt (3.1.20)
bigdecimal (3.1.8)
bootsnap (1.18.4)
msgpack (~> 1.2) msgpack (~> 1.2)
builder (3.2.4) builder (3.3.0)
coderay (1.1.3) coderay (1.1.3)
concurrent-ruby (1.1.10) concurrent-ruby (1.3.4)
connection_pool (2.4.1)
crass (1.0.6) crass (1.0.6)
dalli (3.2.3) csv (3.3.0)
database_cleaner (2.0.1) dalli (3.2.8)
database_cleaner-active_record (~> 2.0.0) database_cleaner (2.0.2)
database_cleaner-active_record (2.0.1) database_cleaner-active_record (>= 2, < 3)
database_cleaner-active_record (2.2.0)
activerecord (>= 5.a) activerecord (>= 5.a)
database_cleaner-core (~> 2.0.0) database_cleaner-core (~> 2.0.0)
database_cleaner-core (2.0.1) database_cleaner-core (2.0.1)
diff-lcs (1.5.0) date (3.3.4)
erubi (1.11.0) diff-lcs (1.5.1)
factory_bot (6.2.1) drb (2.2.1)
erubi (1.13.0)
factory_bot (6.5.0)
activesupport (>= 5.0.0) activesupport (>= 5.0.0)
factory_bot_rails (6.2.0) factory_bot_rails (6.4.3)
factory_bot (~> 6.2.0) factory_bot (~> 6.4)
railties (>= 5.0.0) railties (>= 5.0.0)
ffi (1.15.5) ffi (1.17.0)
formatador (1.1.0) formatador (1.1.0)
globalid (1.0.0) globalid (1.2.1)
activesupport (>= 5.0) activesupport (>= 6.1)
guard (2.18.0) guard (2.18.1)
formatador (>= 0.2.4) formatador (>= 0.2.4)
listen (>= 2.7, < 4.0) listen (>= 2.7, < 4.0)
lumberjack (>= 1.0.12, < 2.0) lumberjack (>= 1.0.12, < 2.0)
@ -99,8 +116,12 @@ GEM
guard (~> 2.1) guard (~> 2.1)
guard-compat (~> 1.1) guard-compat (~> 1.1)
rspec (>= 2.99.0, < 4.0) rspec (>= 2.99.0, < 4.0)
i18n (1.12.0) i18n (1.14.6)
concurrent-ruby (~> 1.0) concurrent-ruby (~> 1.0)
io-console (0.7.2)
irb (1.14.1)
rdoc (>= 4.0.0)
reline (>= 0.4.2)
kaminari (1.2.2) kaminari (1.2.2)
activesupport (>= 4.1.0) activesupport (>= 4.1.0)
kaminari-actionview (= 1.2.2) kaminari-actionview (= 1.2.2)
@ -114,138 +135,163 @@ GEM
kaminari-core (= 1.2.2) kaminari-core (= 1.2.2)
kaminari-core (1.2.2) kaminari-core (1.2.2)
liner (0.2.4) liner (0.2.4)
listen (3.7.1) listen (3.9.0)
rb-fsevent (~> 0.10, >= 0.10.3) rb-fsevent (~> 0.10, >= 0.10.3)
rb-inotify (~> 0.9, >= 0.9.10) rb-inotify (~> 0.9, >= 0.9.10)
loofah (2.19.0) logger (1.6.1)
loofah (2.22.0)
crass (~> 1.0.2) crass (~> 1.0.2)
nokogiri (>= 1.5.9) nokogiri (>= 1.12.0)
lumberjack (1.2.8) lumberjack (1.2.10)
mail (2.7.1) mail (2.8.1)
mini_mime (>= 0.1.1) mini_mime (>= 0.1.1)
marcel (1.0.2) net-imap
net-pop
net-smtp
marcel (1.0.4)
memoizable (0.4.2) memoizable (0.4.2)
thread_safe (~> 0.3, >= 0.3.1) thread_safe (~> 0.3, >= 0.3.1)
method_source (1.0.0) method_source (1.1.0)
mini_mime (1.1.2) mini_mime (1.1.5)
mini_portile2 (2.8.0) mini_portile2 (2.8.7)
minitest (5.16.3) minitest (5.25.1)
msgpack (1.6.0) msgpack (1.7.2)
nenv (0.3.0) nenv (0.3.0)
net-protocol (0.1.3) net-imap (0.4.16)
timeout date
net-smtp (0.3.3)
net-protocol net-protocol
nio4r (2.5.8) net-pop (0.1.2)
nokogiri (1.13.9) net-protocol
mini_portile2 (~> 2.8.0) net-protocol (0.2.2)
timeout
net-smtp (0.5.0)
net-protocol
nio4r (2.7.3)
nokogiri (1.16.7)
mini_portile2 (~> 2.8.2)
racc (~> 1.4) racc (~> 1.4)
notiffany (0.1.3) notiffany (0.1.3)
nenv (~> 0.1) nenv (~> 0.1)
shellany (~> 0.0) shellany (~> 0.0)
oj (3.13.23) oj (3.16.6)
bigdecimal (>= 3.0)
ostruct (>= 0.2)
ostruct (0.6.0)
package_json (0.1.0)
parslet (2.0.0) parslet (2.0.0)
pg (1.4.5) pg (1.5.8)
pry (0.14.1) pry (0.14.2)
coderay (~> 1.1) coderay (~> 1.1)
method_source (~> 1.0) method_source (~> 1.0)
puma (5.6.5) psych (5.1.2)
stringio
puma (6.4.3)
nio4r (~> 2.0) nio4r (~> 2.0)
racc (1.6.0) racc (1.8.1)
rack (2.2.4) rack (3.1.7)
rack-proxy (0.7.4) rack-proxy (0.7.7)
rack rack
rack-test (2.0.2) rack-session (2.0.0)
rack (>= 3.0.0)
rack-test (2.1.0)
rack (>= 1.3) rack (>= 1.3)
rails (6.1.7) rackup (2.1.0)
actioncable (= 6.1.7) rack (>= 3)
actionmailbox (= 6.1.7) webrick (~> 1.8)
actionmailer (= 6.1.7) rails (7.2.1)
actionpack (= 6.1.7) actioncable (= 7.2.1)
actiontext (= 6.1.7) actionmailbox (= 7.2.1)
actionview (= 6.1.7) actionmailer (= 7.2.1)
activejob (= 6.1.7) actionpack (= 7.2.1)
activemodel (= 6.1.7) actiontext (= 7.2.1)
activerecord (= 6.1.7) actionview (= 7.2.1)
activestorage (= 6.1.7) activejob (= 7.2.1)
activesupport (= 6.1.7) activemodel (= 7.2.1)
activerecord (= 7.2.1)
activestorage (= 7.2.1)
activesupport (= 7.2.1)
bundler (>= 1.15.0) bundler (>= 1.15.0)
railties (= 6.1.7) railties (= 7.2.1)
sprockets-rails (>= 2.0.0)
rails-controller-testing (1.0.5) rails-controller-testing (1.0.5)
actionpack (>= 5.0.1.rc1) actionpack (>= 5.0.1.rc1)
actionview (>= 5.0.1.rc1) actionview (>= 5.0.1.rc1)
activesupport (>= 5.0.1.rc1) activesupport (>= 5.0.1.rc1)
rails-dom-testing (2.0.3) rails-dom-testing (2.2.0)
activesupport (>= 4.2.0) activesupport (>= 5.0.0)
minitest
nokogiri (>= 1.6) nokogiri (>= 1.6)
rails-html-sanitizer (1.4.3) rails-html-sanitizer (1.6.0)
loofah (~> 2.3) loofah (~> 2.21)
railties (6.1.7) nokogiri (~> 1.14)
actionpack (= 6.1.7) railties (7.2.1)
activesupport (= 6.1.7) actionpack (= 7.2.1)
method_source activesupport (= 7.2.1)
irb (~> 1.13)
rackup (>= 1.0.0)
rake (>= 12.2) rake (>= 12.2)
thor (~> 1.0) thor (~> 1.0, >= 1.2.2)
rake (13.0.6) zeitwerk (~> 2.6)
rake (13.2.1)
rb-fsevent (0.11.2) rb-fsevent (0.11.2)
rb-inotify (0.10.1) rb-inotify (0.11.1)
ffi (~> 1.0) ffi (~> 1.0)
redcarpet (3.5.1) rdoc (6.7.0)
rspec (3.12.0) psych (>= 4.0.0)
rspec-core (~> 3.12.0) redcarpet (3.6.0)
rspec-expectations (~> 3.12.0) reline (0.5.10)
rspec-mocks (~> 3.12.0) io-console (~> 0.5)
rspec-core (3.12.0) rspec (3.13.0)
rspec-support (~> 3.12.0) rspec-core (~> 3.13.0)
rspec-expectations (3.12.0) rspec-expectations (~> 3.13.0)
rspec-mocks (~> 3.13.0)
rspec-core (3.13.1)
rspec-support (~> 3.13.0)
rspec-expectations (3.13.3)
diff-lcs (>= 1.2.0, < 2.0) diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.12.0) rspec-support (~> 3.13.0)
rspec-mocks (3.12.0) rspec-mocks (3.13.1)
diff-lcs (>= 1.2.0, < 2.0) diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.12.0) rspec-support (~> 3.13.0)
rspec-rails (6.0.1) rspec-rails (7.0.1)
actionpack (>= 6.1) actionpack (>= 7.0)
activesupport (>= 6.1) activesupport (>= 7.0)
railties (>= 6.1) railties (>= 7.0)
rspec-core (~> 3.11) rspec-core (~> 3.13)
rspec-expectations (~> 3.11) rspec-expectations (~> 3.13)
rspec-mocks (~> 3.11) rspec-mocks (~> 3.13)
rspec-support (~> 3.11) rspec-support (~> 3.13)
rspec-support (3.12.0) rspec-support (3.13.1)
securerandom (0.3.1)
semantic_range (3.0.0) semantic_range (3.0.0)
shakapacker (8.0.2)
activesupport (>= 5.2)
package_json
rack-proxy (>= 0.6.1)
railties (>= 5.2)
semantic_range (>= 2.3.0)
shellany (0.0.1) shellany (0.0.1)
signed_multiset (0.2.1) signed_multiset (0.2.1)
sprockets (4.1.1) sqlite3 (2.1.0)
concurrent-ruby (~> 1.0)
rack (> 1, < 3)
sprockets-rails (3.4.2)
actionpack (>= 5.2)
activesupport (>= 5.2)
sprockets (>= 3.0.0)
sqlite3 (1.5.4)
mini_portile2 (~> 2.8.0) mini_portile2 (~> 2.8.0)
thor (1.2.1) stringio (3.1.1)
thor (1.3.2)
thread_safe (0.3.6) thread_safe (0.3.6)
timeout (0.3.0) timeout (0.4.1)
tzinfo (2.0.5) tzinfo (2.0.6)
concurrent-ruby (~> 1.0) concurrent-ruby (~> 1.0)
tzinfo-data (1.2022.6) tzinfo-data (1.2024.2)
tzinfo (>= 1.0.0) tzinfo (>= 1.0.0)
unitwise (2.3.0) unitwise (2.3.0)
liner (~> 0.2) liner (~> 0.2)
memoizable (~> 0.4) memoizable (~> 0.4)
parslet (~> 2.0) parslet (~> 2.0)
signed_multiset (~> 0.2) signed_multiset (~> 0.2)
webpacker (5.4.3) useragent (0.16.10)
activesupport (>= 5.2) webrick (1.8.2)
rack-proxy (>= 0.6.1) websocket-driver (0.7.6)
railties (>= 5.2)
semantic_range (>= 2.3.0)
websocket-driver (0.7.5)
websocket-extensions (>= 0.1.0) websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.5) websocket-extensions (0.1.5)
zeitwerk (2.6.6) zeitwerk (2.6.18)
PLATFORMS PLATFORMS
ruby ruby
@ -253,24 +299,24 @@ PLATFORMS
DEPENDENCIES DEPENDENCIES
bcrypt (~> 3.1.18) bcrypt (~> 3.1.18)
bootsnap (>= 1.1.0) bootsnap (>= 1.1.0)
dalli (~> 3.2.3) csv (~> 3.3)
database_cleaner (~> 2.0.1) dalli (~> 3.2.8)
factory_bot_rails (~> 6.2.0) database_cleaner (~> 2.0.2)
factory_bot_rails (~> 6.4.3)
guard (~> 2.18.0) guard (~> 2.18.0)
guard-rspec guard-rspec
kaminari (~> 1.2.2) kaminari (~> 1.2.2)
net-smtp oj (~> 3.16.6)
oj (~> 3.13.23) pg (~> 1.5.8)
pg (~> 1.4.5) puma (~> 6.4)
puma (~> 5.6) rails (= 7.2.1)
rails (= 6.1.7)
rails-controller-testing rails-controller-testing
redcarpet (~> 3.5.1) redcarpet (~> 3.6.0)
rspec-rails (~> 6.0.1) rspec-rails (~> 7.0.1)
sqlite3 (~> 1.5.4) shakapacker (= 8.0.2)
sqlite3 (~> 2.1.0)
tzinfo-data tzinfo-data
unitwise (~> 2.3.0) unitwise (~> 2.3.0)
webpacker (= 5.4.3)
BUNDLED WITH BUNDLED WITH
2.3.22 2.5.20

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2020 Dan Elbert Copyright (c) 2024 Dan Elbert
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,2 +1,2 @@
rails: bundle exec rails s -b 0.0.0.0 rails: bundle exec rails s -b 0.0.0.0
webpacker: bin/webpack-dev-server shakapacker: bin/shakapacker-dev-server

View File

@ -5,7 +5,7 @@ A self hosted cookbook
Parsley is released under the MIT License. Parsley is released under the MIT License.
Copyright (C) 2020 Dan Elbert Copyright (C) 2024 Dan Elbert
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -4,7 +4,7 @@ class ApplicationController < ActionController::Base
protect_from_forgery with: :exception protect_from_forgery with: :exception
def verified_request? def verified_request?
if request.content_type == "application/json" if request.media_type == "application/json"
true true
else else
super() super()
@ -42,9 +42,19 @@ class ApplicationController < ActionController::Base
if owner if owner
yield if block_given? yield if block_given?
else else
respond_to do |format|
format.html do
flash[:warning] = "Operation Not Permitted" flash[:warning] = "Operation Not Permitted"
redirect_to root_path redirect_to root_path
end end
format.json do
render json: { error: "Operation Not Permitted" }, status: current_user.nil? ? :unauthorized : :forbidden
end
end
end
end end
def current_user def current_user

View File

@ -34,8 +34,10 @@ class CalculatorController < ApplicationController
begin begin
input_unit = UnitConversion.parse(input) input_unit = UnitConversion.parse(input)
input_unit.unitwise
rescue UnitConversion::UnparseableUnitError => e rescue UnitConversion::UnparseableUnitError => e
data[:errors][:input] << 'invalid string' data[:errors][:input] << e.message
input_unit = nil
end end
if !input_unit.nil? if !input_unit.nil?

View File

@ -1,5 +1,5 @@
class NotesController < ApplicationController class NotesController < ApplicationController
before_action :set_note, only: [:show, :edit, :update, :destroy] before_action :set_note, only: [:show, :update, :destroy]
before_action :ensure_valid_user before_action :ensure_valid_user
# GET /notes # GET /notes

View File

@ -50,7 +50,7 @@ class UsersController < ApplicationController
if @user.save if @user.save
set_current_user(@user) set_current_user(@user)
format.html { redirect_to root_path, notice: 'User created.' } format.html { redirect_to root_path, notice: 'User created.' }
format.json { render :show, status: :created, location: @user } format.json { render json: UserSerializer.for(@user), status: :created, location: @user }
else else
format.html { render :new } format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity } format.json { render json: @user.errors, status: :unprocessable_entity }
@ -68,7 +68,7 @@ class UsersController < ApplicationController
respond_to do |format| respond_to do |format|
if @user.update(user_params) if @user.update(user_params)
format.html { redirect_to root_path, notice: 'User updated.' } format.html { redirect_to root_path, notice: 'User updated.' }
format.json { render :show, status: :created, location: @user } format.json { render json: UserSerializer.for(@user) , status: :created, location: @user }
else else
format.html { render :edit } format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity } format.json { render json: @user.errors, status: :unprocessable_entity }

View File

@ -1,83 +1,67 @@
<template> <template>
<div id="app"> <div id="app">
<vue-progress-bar></vue-progress-bar> <app-progress-bar></app-progress-bar>
<app-navbar></app-navbar> <app-navbar></app-navbar>
<section id="main" class=""> <section id="main" class="">
<div class="container"> <div class="container">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in"> <transition name="fade" mode="out-in">
<router-view v-if="!hasError"></router-view> <component v-if="!hasError" :is="Component" />
<div v-else> <div v-else>
<h1>Error!</h1> <h1>Error!</h1>
<p>{{error}}</p> <p>{{ appConfig.error }}</p>
</div> </div>
</transition> </transition>
</router-view>
</div> </div>
</section> </section>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useGlobalTweenGroup } from "../lib/useGlobalTweenGroup";
import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
import { useCheckAuthentication } from "../lib/useCheckAuthentication";
import AppProgressBar from "./AppProgressBar.vue";
import { mapMutations, mapState } from "vuex"; const globalTweenGroup = useGlobalTweenGroup();
import api from "../lib/Api"; let animationLoop = true;
import TWEEN from '@tweenjs/tween.js';
export default { const appConfig = useAppConfigStore();
data() { const hasError = computed(() => appConfig.error !== null);
return {
api: api
};
},
computed: {
...mapState({
hasError: state => state.error !== null,
error: state => state.error,
authChecked: state => state.authChecked,
initialLoad: state => state.initialLoad
})
},
watch: { const { loadResource } = useLoadResource();
isLoading(val) { const { checkAuthentication } = useCheckAuthentication(loadResource);
watch(
() => appConfig.initialLoad,
(val) => {
if (val) { if (val) {
this.$Progress.start(); nextTick(() => document.body.classList.remove("loading"));
} else {
this.$Progress.finish();
} }
}, },
{ immediate: true }
);
initialLoad(val) { onMounted(() => {
if (val) {
this.$nextTick(() => {
document.body.classList.remove("loading");
});
}
}
},
created() {
// Setup global animation loop // Setup global animation loop
function animate() { function animate() {
TWEEN.update(); if (animationLoop) {
globalTweenGroup.update();
requestAnimationFrame(animate); requestAnimationFrame(animate);
} }
}
animate(); animate();
if (this.user === null && this.authChecked === false) { if (appConfig.user === null && appConfig.authChecked === false) {
this.checkAuthentication(); checkAuthentication();
} }
},
mounted() {
if (this.initialLoad) {
this.$nextTick(() => {
document.body.classList.remove("loading");
}); });
}
},
components: { onUnmounted(() => {
} animationLoop = false;
} });
</script> </script>

View File

@ -27,13 +27,15 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, ref, watch } from "vue";
import debounce from 'lodash/debounce'; import debounce from 'lodash/debounce';
export default { const emit = defineEmits(["update:modelValue", "inputClick", "optionSelected"]);
props: {
value: String, const props = defineProps({
modelValue: String,
id: String, id: String,
placeholder: String, placeholder: String,
name: String, name: String,
@ -58,175 +60,157 @@
onGetOptions: Function, onGetOptions: Function,
searchOptions: Array searchOptions: Array
}, });
data() { const options = ref([]);
return { const rawValue = ref("");
options: [], const isListOpen = ref(false);
rawValue: "", const activeListIndex = ref(0);
isListOpen: false,
activeListIndex: 0
}
},
created() { const finalInputClass = computed(() => {
this.rawValue = this.value;
},
watch: {
value(newValue) {
this.rawValue = newValue;
}
},
computed: {
finalInputClass() {
let cls = ['input']; let cls = ['input'];
if (this.inputClass === null) { if (props.inputClass === null) {
return cls; return cls;
} else if (Array.isArray(this.inputClass)) { } else if (Array.isArray(props.inputClass)) {
return cls.concat(this.inputClass); return cls.concat(props.inputClass);
} else { } else {
cls.push(this.inputClass); cls.push(props.inputClass);
return cls; return cls;
} }
}, });
debouncedUpdateOptions() { watch(
return debounce(this.updateOptions, this.debounce); () => props.modelValue,
(newValue) => { rawValue.value = newValue; },
{ immediate: true }
);
function optionClass(idx) {
return activeListIndex.value === idx ? 'option active' : 'option';
} }
},
methods: { function optionClick(opt) {
optionClass(idx) { selectOption(opt);
return this.activeListIndex === idx ? 'option active' : 'option'; }
},
optionClick(opt) { function optionKey(opt) {
this.selectOption(opt); if (props.keyAttribute) {
}, return opt[props.keyAttribute]
} else if (props.valueAttribute) {
optionKey(opt) { return opt[props.valueAttribute];
if (this.keyAttribute) {
return opt[this.keyAttribute]
} else if (this.valueAttribute) {
return opt[this.valueAttribute];
} else { } else {
return opt.toString(); return opt.toString();
} }
}, }
optionValue(opt) { function optionValue(opt) {
if (this.valueAttribute) { if (props.valueAttribute) {
return opt[this.valueAttribute]; return opt[props.valueAttribute];
} else { } else {
return opt.toString(); return opt.toString();
} }
}, }
optionLabel(opt) { function optionLabel(opt) {
if (this.labelAttribute) { if (props.labelAttribute) {
return opt[this.labelAttribute]; return opt[props.labelAttribute];
} else { } else {
return null; return null;
} }
}, }
optionMousemove(idx) { function optionMousemove(idx) {
this.activeListIndex = idx; activeListIndex.value = idx;
}, }
clickHandler(evt) { function clickHandler(evt) {
this.$emit("inputClick", evt); emit('inputClick', evt);
}, }
blurHandler(evt) { function blurHandler(evt) {
// blur fires before click. If the blur was fired because the user clicked a list item, immediately hiding the list here // blur fires before click. If the blur was fired because the user clicked a list item, immediately hiding the list here
// would prevent the click event from firing // would prevent the click event from firing
setTimeout(() => { setTimeout(() => {
this.isListOpen = false; isListOpen.value = false;
},250); },250);
}, }
inputHandler(evt) { function inputHandler(evt) {
const newValue = evt.target.value; const newValue = evt.target.value;
if (this.rawValue !== newValue) { if (rawValue.value !== newValue) {
this.rawValue = newValue; rawValue.value = newValue;
this.$emit("input", newValue); emit("update:modelValue", newValue);
if (newValue.length >= Math.max(1, this.minLength)) { if (newValue.length >= Math.max(1, props.minLength)) {
this.debouncedUpdateOptions(newValue); updateOptions(newValue);
} else { } else {
this.isListOpen = false; isListOpen.value = false;
}
} }
} }
},
keydownHandler(evt) { function keydownHandler(evt) {
if (this.isListOpen === false) if (isListOpen.value === false)
return; return;
switch (evt.key) { switch (evt.key) {
case "ArrowUp": case "ArrowUp":
evt.preventDefault(); evt.preventDefault();
this.activeListIndex = Math.max(0, this.activeListIndex - 1); activeListIndex.value = Math.max(0, activeListIndex.value - 1);
break; break;
case "ArrowDown": case "ArrowDown":
evt.preventDefault(); evt.preventDefault();
this.activeListIndex = Math.min(this.options.length - 1, this.activeListIndex + 1); activeListIndex.value = Math.min(options.value.length - 1, activeListIndex.value + 1);
break; break;
case "Enter": case "Enter":
evt.preventDefault(); evt.preventDefault();
this.selectOption(this.options[this.activeListIndex]); selectOption(options.value[activeListIndex.value]);
break; break;
case "Escape": case "Escape":
evt.preventDefault(); evt.preventDefault();
this.isListOpen = false; isListOpen.value = false;
break; break;
} }
}, }
selectOption(opt) { function selectOption(opt) {
this.rawValue = this.optionValue(opt); rawValue.value = optionValue(opt);
this.$emit("input", this.rawValue); emit("update:modelValue", rawValue.value);
this.$emit("optionSelected", opt); emit("optionSelected", opt);
this.isListOpen = false; isListOpen.value = false;
}, }
updateOptions(value) { const updateOptions = debounce(function(value) {
let p = null; let p = null;
if (this.searchOptions) { if (props.searchOptions) {
const reg = new RegExp("^" + value, "i"); const reg = new RegExp("^" + value, "i");
const matcher = o => reg.test(this.optionValue(o)); const matcher = o => reg.test(optionValue(o));
p = Promise.resolve(this.searchOptions.filter(matcher)); p = Promise.resolve(props.searchOptions.filter(matcher));
} else { } else {
p = this.onGetOptions(value) p = props.onGetOptions(value)
} }
p.then(opts => { p.then(opts => {
this.options = opts; options.value = opts;
this.isListOpen = opts.length > 0; isListOpen.value = opts.length > 0;
this.activeListIndex = 0; activeListIndex.value = 0;
}) })
} }, props.debounce);
}
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "../styles/variables"; @use "bulma/sass/utilities" as bulma;
$labelLineHeight: 0.8rem; $labelLineHeight: 0.8rem;
input.input { input.input {
&::placeholder { &::placeholder {
color: $grey-darker; color: bulma.$grey-darker;
} }
} }
@ -251,7 +235,7 @@
&.active { &.active {
color: white; color: white;
background-color: $turquoise; background-color: bulma.$turquoise;
} }
.opt_value { .opt_value {

View File

@ -1,47 +1,45 @@
<template> <template>
<app-modal :open="open" :title="message" @dismiss="runCancel"> <app-modal :open="open" :title="title" @dismiss="runCancel">
<p class="is-size-5">{{ message }}</p>
<template #footer>
<div class="buttons"> <div class="buttons">
<button type="button" class="button is-primary" @click="runConfirm">OK</button> <button type="button" class="button is-primary" @click="runConfirm">OK</button>
<button type="button" class="button" @click="runCancel">Cancel</button> <button type="button" class="button" @click="runCancel">Cancel</button>
</div> </div>
</template>
</app-modal> </app-modal>
</template> </template>
<script> <script setup>
export default { const emit = defineEmits(["cancel", "confirm"]);
props: {
cancel: {
type: Function,
required: true
},
confirm: {
type: Function,
required: true
},
const props = defineProps({
message: { message: {
type: String, type: String,
required: false, required: false,
default: 'Are you sure?' default: 'Are you sure?'
}, },
title: {
type: String,
required: false,
default: "Confirm"
},
open: { open: {
type: Boolean, type: Boolean,
required: true required: true
} }
}, });
methods: { function runConfirm() {
runConfirm() { emit("confirm");
this.confirm(); }
},
runCancel() { function runCancel() {
this.cancel(); emit("cancel");
}
}
} }
</script> </script>

View File

@ -1,14 +1,15 @@
<template> <template>
<app-text-field :value="stringValue" @input="input" :label="label" type="date"></app-text-field> <app-text-field :value="stringValue" @update:modelValue="input" :label="label" type="date"></app-text-field>
</template> </template>
<script> <script setup>
import { computed } from "vue";
import DateTimeUtils from "../lib/DateTimeUtils"; import DateTimeUtils from "../lib/DateTimeUtils";
export default { const emit = defineEmits(["update:modelValue"]);
props: { const props = defineProps({
value: { modelValue: {
required: false, required: false,
type: [Date, String] type: [Date, String]
}, },
@ -18,21 +19,16 @@
type: String, type: String,
default: null default: null
} }
}, });
computed: { const stringValue = computed(() => {
stringValue() { const d = DateTimeUtils.toDate(props.modelValue);
const d = DateTimeUtils.toDate(this.value);
return DateTimeUtils.formatDateForEdit(d); return DateTimeUtils.formatDateForEdit(d);
} });
},
methods: { function input(val) {
input(val) {
let d = DateTimeUtils.toDate(val + " 00:00"); let d = DateTimeUtils.toDate(val + " 00:00");
this.$emit("input", d); emit("update:modelValue", d);
}
}
} }
</script> </script>

View File

@ -5,12 +5,12 @@
</span> </span>
</template> </template>
<script> <script setup>
import { computed } from "vue";
import DateTimeUtils from "../lib/DateTimeUtils"; import DateTimeUtils from "../lib/DateTimeUtils";
export default { const props = defineProps({
props: {
dateTime: { dateTime: {
required: true, required: true,
type: [Date, String] type: [Date, String]
@ -33,29 +33,21 @@
type: Boolean, type: Boolean,
default: false default: false
} }
}, });
computed: { const dateObj = computed(() => DateTimeUtils.toDate(props.dateTime));
dateObj() { const fullString = computed(() => DateTimeUtils.formatTimestamp(dateObj.value));
return DateTimeUtils.toDate(this.dateTime);
},
friendlyString() { const friendlyString = computed(() => {
const parts = []; const parts = [];
if (this.showDate) { if (props.showDate) {
parts.push(DateTimeUtils.formatDate(this.dateObj)); parts.push(DateTimeUtils.formatDate(dateObj.value));
} }
if (this.showTime) { if (props.showTime) {
parts.push(DateTimeUtils.formatTime(this.dateObj, true)); parts.push(DateTimeUtils.formatTime(dateObj.value, true));
} }
return parts.join(" "); return parts.join(" ");
}, });
fullString() {
return DateTimeUtils.formatTimestamp(this.dateObj);
}
}
}
</script> </script>

View File

@ -1,5 +1,5 @@
<template> <template>
<div class="dropdown" :class="{'is-active': open, 'is-hoverable': hover}"> <div ref="dropdown" class="dropdown" :class="{'is-active': open, 'is-hoverable': hover}">
<div class="dropdown-trigger"> <div class="dropdown-trigger">
<slot name="button"> <slot name="button">
<button type="button" class="button" :class="buttonClass" @click="toggle"> <button type="button" class="button" :class="buttonClass" @click="toggle">
@ -19,10 +19,13 @@
</div> </div>
</template> </template>
<script> <script setup>
export default { import { useTemplateRef } from "vue";
props: { import { onClickOutside } from '@vueuse/core'
const emit = defineEmits(["close", "open"]);
const props = defineProps({
open: { open: {
required: false, required: false,
type: Boolean, type: Boolean,
@ -45,40 +48,33 @@
required: false, required: false,
default: "" default: ""
} }
}, });
methods: { const dropdownElement = useTemplateRef("dropdown");
toggle() {
if (this.open) { onClickOutside(dropdownElement, event => handleOutsideClick(event))
this.triggerClose();
function toggle() {
if (props.open) {
triggerClose();
} else { } else {
this.triggerOpen(); triggerOpen();
}
},
triggerOpen() {
this.$emit("open");
},
triggerClose() {
this.$emit("close");
},
handleOutsideClick(evt) {
if (this.open) {
if (!this.$el.contains(evt.target)) {
this.triggerClose();
} }
} }
function triggerOpen() {
emit("open");
} }
},
mounted() { function triggerClose() {
document.addEventListener("click", this.handleOutsideClick); emit("close");
}, }
beforeDestroy() { function handleOutsideClick(evt) {
document.removeEventListener("click", this.handleOutsideClick); if (props.open) {
if (!dropdownElement.value.contains(evt.target)) {
triggerClose();
}
} }
} }

View File

@ -9,33 +9,28 @@
</transition> </transition>
</template> </template>
<script> <script setup>
import TWEEN from '@tweenjs/tween.js'; import TWEEN from '@tweenjs/tween.js';
import { useGlobalTweenGroup } from "../lib/useGlobalTweenGroup";
export default { const props = defineProps({
props: {
expandTime: { expandTime: {
type: Number, type: Number,
default: 250 default: 250
} }
}, });
data() { let animation = null;
return {
animation: null function cancel () {
if (animation) {
animation.stop();
animation = null;
} }
},
methods: {
cancel () {
if (this.animation) {
this.animation.stop();
this.animation = null;
} }
},
enter(element, done) { function enter(element, done) {
const width = parseInt(getComputedStyle(element).width); const width = parseInt(getComputedStyle(element).width);
const paddingTop = parseInt(getComputedStyle(element).paddingTop); const paddingTop = parseInt(getComputedStyle(element).paddingTop);
const paddingBottom = parseInt(getComputedStyle(element).paddingBottom); const paddingBottom = parseInt(getComputedStyle(element).paddingBottom);
@ -53,15 +48,15 @@
element.style.overflow = 'hidden'; element.style.overflow = 'hidden';
element.style.height = 0; element.style.height = 0;
this.animation = new TWEEN.Tween({height: 0, paddingTop: 0, paddingBottom: 0}) animation = new TWEEN.Tween({height: 0, paddingTop: 0, paddingBottom: 0})
.to({height: height, paddingTop: paddingTop, paddingBottom: paddingBottom}, this.expandTime) .to({height: height, paddingTop: paddingTop, paddingBottom: paddingBottom}, props.expandTime)
.onUpdate(obj => { .onUpdate(obj => {
element.style.height = obj.height + "px"; element.style.height = obj.height + "px";
element.style.paddingBottom = obj.paddingBottom + "px"; element.style.paddingBottom = obj.paddingBottom + "px";
element.style.paddingTop = obj.paddingTop + "px"; element.style.paddingTop = obj.paddingTop + "px";
}) })
.onComplete(() => { .onComplete(() => {
this.animation = null; animation = null;
element.removeAttribute('style'); element.removeAttribute('style');
element.style.opacity = 0.99; element.style.opacity = 0.99;
setTimeout(() => { setTimeout(() => {
@ -70,32 +65,32 @@
}, 1000); }, 1000);
done(); done();
}) })
.group(useGlobalTweenGroup())
.start(); .start();
}, }
leave(element, done) { function leave(element, done) {
const height = parseInt(getComputedStyle(element).height); const height = parseInt(getComputedStyle(element).height);
const paddingTop = parseInt(getComputedStyle(element).paddingTop); const paddingTop = parseInt(getComputedStyle(element).paddingTop);
const paddingBottom = parseInt(getComputedStyle(element).paddingBottom); const paddingBottom = parseInt(getComputedStyle(element).paddingBottom);
element.style.overflow = 'hidden'; element.style.overflow = 'hidden';
this.animation = new TWEEN.Tween({height: height, paddingTop: paddingTop, paddingBottom: paddingBottom}) animation = new TWEEN.Tween({height: height, paddingTop: paddingTop, paddingBottom: paddingBottom})
.to({height: 0, paddingTop: 0, paddingBottom: 0}, this.expandTime) .to({height: 0, paddingTop: 0, paddingBottom: 0}, props.expandTime)
.onUpdate(obj => { .onUpdate(obj => {
element.style.height = obj.height + "px"; element.style.height = obj.height + "px";
element.style.paddingBottom = obj.paddingBottom + "px"; element.style.paddingBottom = obj.paddingBottom + "px";
element.style.paddingTop = obj.paddingTop + "px"; element.style.paddingTop = obj.paddingTop + "px";
}) })
.onComplete(() => { .onComplete(() => {
this.animation = null; animation = null;
element.removeAttribute('style'); element.removeAttribute('style');
done(); done();
}) })
.group(useGlobalTweenGroup())
.start(); .start();
} }
}
}
</script> </script>

View File

@ -6,6 +6,8 @@
<script> <script>
import { computed } from "vue";
class IconData { class IconData {
constructor(iconicIcon, dataAttributes) { constructor(iconicIcon, dataAttributes) {
this.iconicIcon = iconicIcon; this.iconicIcon = iconicIcon;
@ -49,6 +51,7 @@
}; };
export default { export default {
emits: ["click"],
props: { props: {
icon: { icon: {
validator: (i) => iconMap[i] !== undefined validator: (i) => iconMap[i] !== undefined
@ -66,38 +69,21 @@
} }
}, },
data() { setup(props) {
const iconData = computed(() => iconMap[props.icon]);
const sizeData = computed(() => sizeMap[props.size]);
const iconClasses = computed(() => [sizeData.value.bulmaIconClass, sizeData.value.customIconClass]);
const iconicSize = computed(() => sizeData.value.iconicSize);
const iconicIcon = computed(() => iconData.value.iconicIcon);
const iconicAttributes = computed(() => iconData.value.dataAttributes);
return { return {
injectedSvg: null iconClasses,
} iconData,
}, sizeData,
iconicAttributes,
computed: { iconicIcon,
iconData() { iconicSize
return iconMap[this.icon];
},
sizeData() {
return sizeMap[this.size];
},
iconClasses() {
return [
this.sizeData.bulmaIconClass,
this.sizeData.customIconClass
]
},
iconicSize() {
return this.sizeData.iconicSize;
},
iconicIcon() {
return this.iconData.iconicIcon;
},
iconicAttributes() {
return this.iconData.dataAttributes;
} }
} }
} }

View File

@ -1,9 +1,11 @@
<template> <template>
<svg v-bind="svgAttributes" v-html="svgContent" :class="calculatedClasses"></svg> <svg ref="svg" v-bind="svgAttributes" v-html="svgContent" :class="calculatedClasses"></svg>
</template> </template>
<script> <script>
import { computed, nextTick, onMounted, onUpdated, useTemplateRef } from "vue";
import Caret from "../iconic/svg/smart/caret"; import Caret from "../iconic/svg/smart/caret";
import Check from "../iconic/svg/smart/check"; import Check from "../iconic/svg/smart/check";
import CircleCheck from "../iconic/svg/smart/circle-check"; import CircleCheck from "../iconic/svg/smart/circle-check";
@ -68,29 +70,15 @@
} }
}, },
data() { setup(props) {
return { const svgElement = useTemplateRef("svg");
calculatedClasses: [] const svgData = computed(() => iconMap[props.icon]);
} const svgAttributes = computed(() => svgData.value.attributes);
}, const svgName = computed(() => svgAttributes.value['data-icon']);
const svgContent = computed(() => {
let content = String(svgData.value.content);
computed: { for (let idRep of svgData.value.idReplacements) {
svgData() {
return iconMap[this.icon];
},
svgAttributes() {
return this.svgData.attributes;
},
svgName() {
return this.svgAttributes['data-icon'];
},
svgContent() {
let content = String(this.svgData.content);
for (let idRep of this.svgData.idReplacements) {
let newId = `__new_id_${globalIdCounter}`; let newId = `__new_id_${globalIdCounter}`;
globalIdCounter += 1; globalIdCounter += 1;
@ -98,57 +86,70 @@
} }
return content; return content;
} });
},
methods: { const calculatedClasses = computed(() => {
const classes = (svgAttributes.value.class || "").split(" ");
rebind() { classes.push(`iconic-${props.size}`);
const apis = APIS;
if (apis && this.svgName && apis[this.svgName]) { if (props.iconSizeOverride) {
const iconApi = apis[this.svgName](this.$el); classes.push(`iconic-icon-${props.iconSizeOverride}`);
for (let func in iconApi) this.$el[func] = iconApi[func]
} else {
this.$el.update = function() {}
} }
this.calculatedClasses = (this.svgAttributes.class || "").split(" "); if (props.displaySizeOverride) {
classes.push(`iconic-size-${props.displaySizeOverride}`);
this.calculatedClasses.push(`iconic-${this.size}`);
if (this.iconSizeOverride) {
this.calculatedClasses.push(`iconic-icon-${this.iconSizeOverride}`);
} }
if (this.displaySizeOverride) { return classes;
this.calculatedClasses.push(`iconic-size-${this.displaySizeOverride}`); });
}
this.$el.update(); function ensureSvgApi(name, scripts) {
} if (!name) { return; }
}, if (LOADED_APIS[name] !== true) {
for (let sb of scripts) {
created() { try {
if (LOADED_APIS[this.svgName] !== true) {
for (let sb of this.svgData.scriptBlocks) {
new Function(sb)(window); new Function(sb)(window);
} catch (e) {
console.log(sb);
console.log(e);
}
}
LOADED_APIS[name] = true;
} }
LOADED_APIS[this.svgName] = true;
} }
},
mounted() { function setupSvgApi(name) {
const apis = APIS;
this.$watch( if (apis && apis[name]) {
function() { return [this.$attrs, this.icon, this.fluid] }, const iconApi = apis[name](svgElement.value);
function() { for (let func in iconApi) svgElement.value[func] = iconApi[func]
this.rebind() } else {
}, svgElement.value.update = function() {}
{
immediate: true
} }
); svgElement.value.update();
}
function updateScripts() {
ensureSvgApi(svgName.value, svgData.value.scriptBlocks);
setupSvgApi(svgName.value);
}
onMounted(() => {
updateScripts();
});
onUpdated(() => {
updateScripts();
});
return {
svgData,
svgAttributes,
svgName,
svgContent,
calculatedClasses
};
} }
} }

View File

@ -4,10 +4,7 @@
</div> </div>
</template> </template>
<script> <script setup>
export default {
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -1,6 +1,6 @@
<template> <template>
<div ref="container"> <Teleport to="body">
<div ref="modal" :class="['popup', 'modal', { 'is-wide': wide, 'is-active': open && error === null }]"> <div :class="['modal', { 'is-wide': wide, 'is-active': open && error === null }]">
<div class="modal-background" @click="close"></div> <div class="modal-background" @click="close"></div>
<div class="modal-card"> <div class="modal-card">
<header class="modal-card-head"> <header class="modal-card-head">
@ -13,17 +13,24 @@
<section class="modal-card-body"> <section class="modal-card-body">
<slot></slot> <slot></slot>
</section> </section>
<footer class="modal-card-foot">
<slot name="footer">
</slot>
</footer>
</div> </div>
</div> </div>
</div> </Teleport>
</template> </template>
<script> <script setup>
import { mapState } from "vuex"; import { computed } from "vue";
import { useAppConfigStore } from "../stores/appConfig";
export default { const emit = defineEmits(["dismiss"]);
props: {
const props = defineProps({
open: { open: {
type: Boolean, type: Boolean,
default: false default: false
@ -33,30 +40,13 @@
type: Boolean, type: Boolean,
default: false default: false
} }
}, });
mounted() { const appConfig = useAppConfigStore();
this.$root.$el.appendChild(this.$refs.modal); const error = computed(() => appConfig.error);
},
beforeDestroy() { function close() {
this.$refs.container.appendChild(this.$refs.modal); emit("dismiss");
},
computed: {
...mapState([
'error'
])
},
methods: {
close() {
this.$emit("dismiss");
}
},
components: {
}
} }
</script> </script>

View File

@ -51,46 +51,27 @@
</nav> </nav>
</template> </template>
<script> <script setup>
import { ref, watch } from "vue";
import UserLogin from "./UserLogin"; import UserLogin from "./UserLogin";
import { mapState } from "vuex"; import { storeToRefs } from "pinia";
import { useAppConfigStore } from "../stores/appConfig";
import { swUpdate } from "../lib/ServiceWorker"; import { swUpdate } from "../lib/ServiceWorker";
import { useRoute } from "vue-router";
export default { const appConfig = useAppConfigStore();
data() { const menuActive = ref(false);
return { const route = useRoute();
menuActive: false const { isAdmin, isLoggedIn, updateAvailable, user } = storeToRefs(appConfig);
};
},
computed: { function updateApp() {
...mapState([
'route',
'user',
'updateAvailable'
])
},
methods: {
updateApp() {
swUpdate(); swUpdate();
} }
},
watch: { watch(
route() { () => [route, appConfig.user],
this.menuActive = false; () => menuActive.value = false
}, );
user() {
this.menuActive = false;
}
},
components: {
UserLogin
}
}
</script> </script>

View File

@ -1,7 +1,7 @@
<template> <template>
<nav v-show="totalPages > 1 || showWithSinglePage" class="pagination" role="navigation" :aria-label="pagedItemName + ' page navigation'"> <nav v-show="totalPages > 1 || showWithSinglePage" class="pagination" role="navigation" :aria-label="pagedItemName + ' page navigation'">
<a class="pagination-previous" :title="isFirstPage ? 'This is the first page' : ''" :disabled="isFirstPage" @click.prevent="changePage(currentPage - 1)">Previous</a> <a :class="{'pagination-previous': true, 'is-disabled': isFirstPage}" :title="isFirstPage ? 'This is the first page' : ''" @click.prevent="changePage(currentPage - 1)">Previous</a>
<a class="pagination-next" :title="isLastPage ? 'This is the last page' : ''" :disabled="isLastPage" @click.prevent="changePage(currentPage + 1)">Next page</a> <a :class="{'pagination-next': true, 'is-disabled': isLastPage}" :title="isLastPage ? 'This is the last page' : ''" @click.prevent="changePage(currentPage + 1)">Next page</a>
<ul class="pagination-list"> <ul class="pagination-list">
<li v-for="page in pageItems" :key="page"> <li v-for="page in pageItems" :key="page">
<a v-if="page > 0" class="pagination-link" :class="{'is-current': page === currentPage}" href="#" @click.prevent="changePage(page)">{{page}}</a> <a v-if="page > 0" class="pagination-link" :class="{'is-current': page === currentPage}" href="#" @click.prevent="changePage(page)">{{page}}</a>
@ -11,10 +11,13 @@
</nav> </nav>
</template> </template>
<script> <script setup>
export default { import { computed } from "vue";
props: {
const emit = defineEmits(["changePage"]);
const props = defineProps({
pagedItemName: { pagedItemName: {
required: false, required: false,
type: String, type: String,
@ -48,19 +51,18 @@
type: Boolean, type: Boolean,
default: false default: false
} }
}, });
computed: { const pageItems = computed(() => {
pageItems() {
const items = new Set(); const items = new Set();
for (let x = 0; x < this.pageOuterWindow; x++) { for (let x = 0; x < props.pageOuterWindow; x++) {
items.add(x + 1); items.add(x + 1);
items.add(this.totalPages - x); items.add(props.totalPages - x);
} }
const start = this.currentPage - Math.ceil(this.pageWindow / 2); const start = props.currentPage - Math.ceil(props.pageWindow / 2);
const end = this.currentPage + Math.floor(this.pageWindow / 2); const end = props.currentPage + Math.floor(props.pageWindow / 2);
for (let x = start; x <= end; x++) { for (let x = start; x <= end; x++) {
items.add(x); items.add(x);
@ -69,7 +71,7 @@
let emptySpace = -1; let emptySpace = -1;
const finalList = []; const finalList = [];
[...items.values()].filter(p => p > 0 && p <= this.totalPages).sort((a, b) => a - b).forEach((p, idx, list) => { [...items.values()].filter(p => p > 0 && p <= props.totalPages).sort((a, b) => a - b).forEach((p, idx, list) => {
finalList.push(p); finalList.push(p);
if (list[idx + 1] && list[idx + 1] !== p + 1) { if (list[idx + 1] && list[idx + 1] !== p + 1) {
finalList.push(emptySpace--); finalList.push(emptySpace--);
@ -77,30 +79,13 @@
}); });
return finalList; return finalList;
}, });
isLastPage() { const isLastPage = computed(() => props.currentPage === props.totalPages);
return this.currentPage === this.totalPages; const isFirstPage = computed(() => props.currentPage === 1);
},
isFirstPage() { function changePage(idx) {
return this.currentPage === 1; emit("changePage", idx);
}
},
methods: {
changePage(idx) {
this.$emit("changePage", idx);
}
}
} }
</script> </script>
<style lang="scss" scoped>
ul.pagination {
}
</style>

View File

@ -0,0 +1,69 @@
<template>
<div class="progress-bar" :style="progressStyle"></div>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { useAppConfigStore } from "../stores/appConfig";
import TWEEN from '@tweenjs/tween.js';
import { useGlobalTweenGroup } from "../lib/useGlobalTweenGroup";
const appConfig = useAppConfigStore();
const showProgress = ref(false);
const loadingPercent = ref(0);
let animation = null;
const progressStyle = computed(() => {
return {
opacity: showProgress.value ? "1" : "0",
width: `${loadingPercent.value}%`,
height: "4px"
};
});
watch(() => appConfig.isLoading, val => {
if (val) {
start();
} else {
stop();
}
});
function start() {
if (!animation) {
showProgress.value = true;
animation = new TWEEN.Tween({ percent: 0 }, useGlobalTweenGroup())
.to({ percent: 90 })
.easing(TWEEN.Easing.Quartic.Out)
.duration(3000)
.onUpdate(({ percent }) => { loadingPercent.value = percent; })
.onComplete(({ percent }) => {})
.start();
}
}
function stop() {
if (animation) {
showProgress.value = false;
animation.stop();
animation = null;
}
}
</script>
<style lang="scss" scoped>
@use "bulma/sass/utilities" as bulma;
.progress-bar {
position: fixed;
top: 0;
left: 0;
z-index: 999999;
background-color: bulma.$blue;
transition: width 0.1s, opacity 0.3s;
}
</style>

View File

@ -9,11 +9,13 @@
</span> </span>
</template> </template>
<script> <script setup>
import { computed, ref, useTemplateRef } from "vue";
export default { const emit = defineEmits(["update:modelValue"]);
props: {
const props = defineProps({
starCount: { starCount: {
required: false, required: false,
type: Number, type: Number,
@ -32,80 +34,66 @@
default: 0.5 default: 0.5
}, },
value: { modelValue: {
required: false, required: false,
type: Number, type: Number,
default: 0 default: 0
} }
}, });
data() { const temporaryValue = ref(null);
return { const ratingPercent = computed(() => ((props.modelValue || 0) / props.starCount) * 100.0);
temporaryValue: null const wrapperEl = useTemplateRef("wrapper");
};
},
computed: { const temporaryPercent = computed(() => {
ratingPercent() { if (temporaryValue.value !== null) {
return ((this.value || 0) / this.starCount) * 100.0; return (temporaryValue.value / props.starCount) * 100.0;
},
temporaryPercent() {
if (this.temporaryValue !== null) {
return (this.temporaryValue / this.starCount) * 100.0;
} else { } else {
return null; return null;
} }
}, });
filledStyle() { const filledStyle = computed(() => {
const width = this.temporaryPercent || this.ratingPercent; const width = temporaryPercent.value || ratingPercent.value;
return { return {
width: width + "%" width: width + "%"
}; };
} });
},
methods: { function handleClick(evt) {
handleClick(evt) { if (temporaryValue.value !== null) {
if (this.temporaryValue !== null) { emit("update:modelValue", temporaryValue.value);
this.$emit("input", this.temporaryValue); }
} }
},
handleMousemove(evt) { function handleMousemove(evt) {
if (this.readonly) { if (props.readonly) {
return; return;
} }
const wrapperBox = this.$refs.wrapper.getBoundingClientRect(); const wrapperBox = wrapperEl.value.getBoundingClientRect();
const wrapperWidth = wrapperBox.right - wrapperBox.left; const wrapperWidth = wrapperBox.right - wrapperBox.left;
const mousePosition = evt.clientX; const mousePosition = evt.clientX;
if (mousePosition > wrapperBox.left && mousePosition < wrapperBox.right) { if (mousePosition > wrapperBox.left && mousePosition < wrapperBox.right) {
const filledRatio = ((mousePosition - wrapperBox.left) / wrapperWidth); const filledRatio = ((mousePosition - wrapperBox.left) / wrapperWidth);
const totalSteps = this.starCount / this.step; const totalSteps = props.starCount / props.step;
const filledSteps = Math.round(totalSteps * filledRatio); const filledSteps = Math.round(totalSteps * filledRatio);
this.temporaryValue = filledSteps * this.step; temporaryValue.value = filledSteps * props.step;
}
} }
},
handleMouseleave(evt) { function handleMouseleave(evt) {
this.temporaryValue = null; temporaryValue.value = null;
}
},
components: {
}
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "../styles/variables"; @use "bulma/sass/utilities" as bulma;
span.rating { span.rating {
position: relative; position: relative;
@ -125,7 +113,7 @@
} }
.filled-set { .filled-set {
color: $yellow; color: bulma.$yellow;
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;

View File

@ -6,61 +6,45 @@
</div> </div>
</template> </template>
<script> <script setup>
import { ref } from "vue";
import debounce from "lodash/debounce"; import debounce from "lodash/debounce";
export default { const emit = defineEmits(["update:modelValue"]);
props: {
const props = defineProps({
placeholder: { placeholder: {
required: false, required: false,
type: String, type: String,
default: "" default: ""
}, },
value: { modelValue: {
required: false, required: false,
type: String, type: String,
default: "" default: ""
} }
});
const text = ref(null);
const triggerInput = debounce(function() {
emit("update:modelValue", text.value);
}, },
250,
{ leading: false, trailing: true })
data() { function userUpdateText(newText) {
return { if (text.value !== newText) {
text: null text.value = newText;
}; triggerInput();
},
computed: {
},
methods: {
triggerInput: debounce(function() {
this.$emit("input", this.text);
}, 250, {leading: false, trailing: true}),
userUpdateText(text) {
if (this.text !== text) {
this.text = text;
this.triggerInput();
}
},
propUpdateText(text) {
if (this.text === null && this.text !== text) {
this.text = text;
} }
} }
},
created() { function propUpdateText(newText) {
this.$watch("value", if (text.value === null && text.value !== newText) {
val => this.propUpdateText(val), text.value = newText;
{
immediate: true
}
);
} }
} }

View File

@ -2,47 +2,38 @@
<div class="tag-editor control"> <div class="tag-editor control">
<input ref="input" type="text" class="input" :value="tagText" @input="inputHandler" @focus="getFocus" @blur="loseFocus"> <input ref="input" type="text" class="input" :value="tagText" @input="inputHandler" @focus="getFocus" @blur="loseFocus">
<div class="tags"> <div class="tags">
<span v-for="t in value" :key="t" class="tag">{{t}}</span> <span v-for="t in modelValue" :key="t" class="tag">{{t}}</span>
</div> </div>
</div> </div>
</template> </template>
<script> <script setup>
export default { import {computed, nextTick, ref, useTemplateRef} from "vue";
props: {
value: { const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
modelValue: {
required: true, required: true,
type: Array type: Array
} }
}, });
data() { const hasFocus = ref(false);
return { const tagText = computed(() => props.modelValue.join(" "));
hasFocus: false const inputElement = useTemplateRef("input");
};
},
computed: { function inputHandler(el) {
tagText() {
return this.value.join(" ");
}
},
watch: {
},
methods: {
inputHandler(el) {
let str = el.target.value; let str = el.target.value;
this.checkInput(str); checkInput(str);
this.$nextTick(() => { nextTick(() => {
el.target.value = str; el.target.value = str;
}); });
}, }
checkInput(str) { function checkInput(str) {
if (this.hasFocus) { if (hasFocus.value) {
const m = str.match(/\S\s+\S*$/); const m = str.match(/\S\s+\S*$/);
if (m !== null) { if (m !== null) {
@ -54,22 +45,21 @@
const newTags = [...new Set(str.toString().split(/\s+/).filter(t => t.length > 0))]; const newTags = [...new Set(str.toString().split(/\s+/).filter(t => t.length > 0))];
if (!this.arraysEqual(newTags, this.value)) { if (!arraysEqual(newTags, props.modelValue)) {
this.$emit("input", newTags); emit("update:modelValue", newTags);
}
} }
},
getFocus() { function getFocus() {
this.hasFocus = true; hasFocus.value = true;
}, }
loseFocus() { function loseFocus() {
this.hasFocus = false; hasFocus.value = false;
this.checkInput(this.$refs.input.value); checkInput(inputElement.value.value);
}
}, function arraysEqual(arr1, arr2) {
arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length) if(arr1.length !== arr2.length)
return false; return false;
for(let i = arr1.length; i--;) { for(let i = arr1.length; i--;) {
@ -79,7 +69,4 @@
return true; return true;
} }
}
}
</script> </script>

View File

@ -2,8 +2,8 @@
<div class="field"> <div class="field">
<label v-if="label.length" class="label is-small-mobile">{{ label }}</label> <label v-if="label.length" class="label is-small-mobile">{{ label }}</label>
<div :class="controlClasses"> <div :class="controlClasses">
<textarea v-if="isTextarea" :class="inputClasses" :value="value" @input="input" :disabled="disabled"></textarea> <textarea v-if="isTextarea" :class="inputClasses" v-model="model" :disabled="disabled"></textarea>
<input v-else :type="type" :class="inputClasses" :value="value" @input="input" :disabled="disabled"> <input v-else :type="type" :class="inputClasses" v-model="model" :disabled="disabled">
<app-icon class="is-right" icon="warning" v-if="validationError !== null"></app-icon> <app-icon class="is-right" icon="warning" v-if="validationError !== null"></app-icon>
</div> </div>
<p v-if="helpMessage !== null" :class="helpClasses"> <p v-if="helpMessage !== null" :class="helpClasses">
@ -12,16 +12,17 @@
</div> </div>
</template> </template>
<script> <script setup>
export default { import { computed } from "vue";
props: {
const props = defineProps({
label: { label: {
required: false, required: false,
type: String, type: String,
default: "" default: ""
}, },
value: { modelValue: {
required: false, required: false,
type: [String, Number], type: [String, Number],
default: "" default: ""
@ -40,53 +41,38 @@
type: String, type: String,
default: null default: null
} }
}, });
computed: { const model = defineModel({
isTextarea() { type: [String, Number],
return this.type === "textarea"; default: ""
}, });
controlClasses() { const isTextarea = computed(() => props.type === "textarea");
return [ const controlClasses = computed(() => [
"control", "control",
{ {
"has-icons-right": this.validationError !== null "has-icons-right": props.validationError !== null
} }
] ]);
},
inputClasses() { const inputClasses = computed(() =>[
return [
"is-small-mobile", "is-small-mobile",
{ {
"textarea": this.isTextarea, "textarea": isTextarea.value,
"input": !this.isTextarea, "input": !isTextarea.value,
"is-danger": this.validationError !== null "is-danger": props.validationError !== null
} }
] ]);
},
helpMessage() { const helpMessage = computed(() => props.validationError);
return this.validationError; const helpClasses = computed(() => [
},
helpClasses() {
return [
"help", "help",
{ {
"is-danger": this.validationError !== null "is-danger": props.validationError !== null
} }
]; ]);
}
},
methods: {
input(evt) {
this.$emit("input", evt.target.value);
}
}
}
</script> </script>

View File

@ -6,16 +6,14 @@
</div> </div>
</template> </template>
<script> <script setup>
export default { const props = defineProps({
props: {
errors: { errors: {
required: false, required: false,
type: Object, type: Object,
default: {} default: {}
} }
} });
}
</script> </script>

View File

@ -62,11 +62,14 @@
<button class="button" type="button" @click="addUnit">Add Unit</button> <button class="button" type="button" @click="addUnit">Add Unit</button>
<table class="table"> <table class="table">
<thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Grams</th> <th>Grams</th>
<th></th> <th></th>
</tr> </tr>
</thead>
<tbody>
<tr v-for="unit in visibleFoodUnits" :key="unit.id"> <tr v-for="unit in visibleFoodUnits" :key="unit.id">
<td> <td>
<div class="control"> <div class="control">
@ -82,6 +85,7 @@
<button type="button" class="button is-danger" @click="removeUnit(unit)">X</button> <button type="button" class="button is-danger" @click="removeUnit(unit)">X</button>
</td> </td>
</tr> </tr>
</tbody>
</table> </table>
</div> </div>
</div> </div>
@ -96,14 +100,18 @@
<div class="message-body"> <div class="message-body">
<table class="table"> <table class="table">
<thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Grams</th> <th>Grams</th>
</tr> </tr>
</thead>
<tbody>
<tr v-for="unit in food.ndbn_units"> <tr v-for="unit in food.ndbn_units">
<td>{{unit.description}}</td> <td>{{unit.description}}</td>
<td>{{unit.gram_weight}}</td> <td>{{unit.gram_weight}}</td>
</tr> </tr>
</tbody>
</table> </table>
</div> </div>
@ -136,13 +144,19 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed } from "vue";
import api from "../lib/Api"; import api from "../lib/Api";
import { mapState } from "vuex"; import { mapState } from "pinia";
import { useNutrientStore } from "../stores/nutrient";
import { useLoadResource } from "../lib/useLoadResource";
export default { const nutrientStore = useNutrientStore();
props: { const nutrients = computed(() => nutrientStore.nutrientList);
const { loadResource } = useLoadResource();
const props = defineProps({
food: { food: {
required: true, required: true,
type: Object type: Object
@ -157,53 +171,35 @@
type: String, type: String,
default: "Editing" default: "Editing"
} }
}, });
data() { const visibleFoodUnits = computed(() => props.food.food_units.filter(iu => iu._destroy !== true));
return { const hasNdbn = computed(() => props.food.ndbn !== null);
}; function addUnit() {
}, props.food.food_units.push({
computed: {
...mapState({
nutrients: 'nutrientList'
}),
visibleFoodUnits() {
return this.food.food_units.filter(iu => iu._destroy !== true);
},
hasNdbn() {
return this.food.ndbn !== null;
}
},
methods: {
addUnit() {
this.food.food_units.push({
id: null, id: null,
name: null, name: null,
gram_weight: null gram_weight: null
}); });
}, }
removeUnit(unit) { function removeUnit(unit) {
if (unit.id) { if (unit.id) {
unit._destroy = true; unit._destroy = true;
} else { } else {
const idx = this.food.food_units.findIndex(i => i === unit); const idx = props.food.food_units.findIndex(i => i === unit);
this.food.food_units.splice(idx, 1); props.food.food_units.splice(idx, 1);
}
} }
},
removeNdbn() { function removeNdbn() {
this.food.ndbn = null; props.food.ndbn = null;
this.food.usda_food_name = null; props.food.usda_food_name = null;
this.food.ndbn_units = []; props.food.ndbn_units = [];
}, }
updateSearchItems(text) { function updateSearchItems(text) {
return api.getUsdaFoodSearch(text) return api.getUsdaFoodSearch(text)
.then(data => data.map(f => { .then(data => data.map(f => {
return { return {
@ -212,23 +208,18 @@
description: ["#", f.ndbn, ", Cal:", f.kcal, ", Carbs:", f.carbohydrates, ", Fat:", f.lipid, ", Protein:", f.protein].join("") description: ["#", f.ndbn, ", Cal:", f.kcal, ", Carbs:", f.carbohydrates, ", Fat:", f.lipid, ", Protein:", f.protein].join("")
} }
})); }));
}, }
searchItemSelected(food) { function searchItemSelected(food) {
this.food.ndbn = food.ndbn; props.food.ndbn = food.ndbn;
this.food.usda_food_name = food.name; props.food.usda_food_name = food.name;
this.food.ndbn_units = []; props.food.ndbn_units = [];
this.loadResource( loadResource(
api.postIngredientSelectNdbn(this.food) api.postIngredientSelectNdbn(props.food)
.then(i => Object.assign(this.food, i)) .then(i => Object.assign(props.food, i))
); );
},
},
components: {
}
} }
</script> </script>

View File

@ -53,24 +53,20 @@
</div> </div>
</template> </template>
<script> <script setup>
import { mapState } from "vuex"; import { computed } from "vue";
import { useNutrientStore } from "../stores/nutrient";
export default { const props = defineProps({
props: {
food: { food: {
required: true, required: true,
type: Object type: Object
} }
}, });
computed: { const nutrientStore = useNutrientStore();
...mapState({ const nutrients = computed(() => nutrientStore.nutrientList);
nutrients: 'nutrientList'
}),
}
}
</script> </script>

View File

@ -31,12 +31,11 @@
</template> </template>
<script> <script setup>
import RecipeEdit from "./RecipeEdit"; import RecipeEdit from "./RecipeEdit";
export default { const props = defineProps({
props: {
log: { log: {
required: true, required: true,
type: Object type: Object
@ -46,12 +45,7 @@
type: Object, type: Object,
default: {} default: {}
}, },
}, });
components: {
RecipeEdit
}
}
</script> </script>

View File

@ -21,7 +21,7 @@
</div> </div>
<div class="field-body"> <div class="field-body">
<div class="field"> <div class="field">
<app-rating readonly :value="log.rating"></app-rating> <app-rating readonly :model-value="log.rating"></app-rating>
</div> </div>
</div> </div>
</div> </div>
@ -44,22 +44,16 @@
</div> </div>
</template> </template>
<script> <script setup>
import RecipeShow from "./RecipeShow"; import RecipeShow from "./RecipeShow";
export default { const props = defineProps({
props: {
log: { log: {
required: true, required: true,
type: Object type: Object
} }
}, });
components: {
RecipeShow
}
}
</script> </script>

View File

@ -19,36 +19,26 @@
</div> </div>
</template> </template>
<script> <script setup>
export default { import { computed } from "vue";
props: {
const emit = defineEmits(["save", "cancel"]);
const props = defineProps({
note: { note: {
required: true, required: true,
type: Object type: Object
} }
}, });
data() { const canSave = computed(() => props.note?.content?.length);
return {
};
},
computed: { function save() {
canSave() { emit("save", props.note);
return this.note && this.note.content && this.note.content.length;
} }
},
methods: { function cancel() {
save() { emit("cancel");
this.$emit("save", this.note);
},
cancel() {
this.$emit("cancel");
}
}
} }
</script> </script>

View File

@ -71,6 +71,7 @@
<th>Result</th> <th>Result</th>
</tr> </tr>
</thead> </thead>
<tbody>
<tr> <tr>
<td>Heading</td> <td>Heading</td>
<td> <td>
@ -155,6 +156,7 @@ _underline_
</p> </p>
</td> </td>
</tr> </tr>
</tbody>
</table> </table>
<h3 class="title is-3">Basic Example</h3> <h3 class="title is-3">Basic Example</h3>
@ -204,16 +206,15 @@ _underline_
</div> </div>
</template> </template>
<script> <script setup>
import autosize from "autosize"; import { computed, ref, useTemplateRef, watch } from "vue";
import { useAutosize } from "../lib/useAutosize";
import debounce from "lodash/debounce"; import debounce from "lodash/debounce";
import api from "../lib/Api"; import api from "../lib/Api";
import RecipeEditIngredientEditor from "./RecipeEditIngredientEditor"; import RecipeEditIngredientEditor from "./RecipeEditIngredientEditor";
export default { const props = defineProps({
props: {
recipe: { recipe: {
required: true, required: true,
type: Object type: Object
@ -223,48 +224,32 @@ _underline_
type: Boolean, type: Boolean,
default: false default: false
} }
}, });
data() { const stepTextArea = useTemplateRef("step_text_area");
return { const stepPreviewCache = ref(null);
stepPreviewCache: null, const isDescriptionHelpOpen = ref(false);
isDescriptionHelpOpen: false
};
},
computed: { useAutosize(stepTextArea);
stepPreview() {
if (this.stepPreviewCache === null) { const stepPreview = computed(() => {
return this.recipe.rendered_steps; if (stepPreviewCache.value === null) {
return props.recipe.rendered_steps;
} else { } else {
return this.stepPreviewCache; return stepPreviewCache.value;
} }
} });
},
methods: { const updatePreview = debounce(function() {
api.postPreviewSteps(props.recipe.step_text)
.then(data => stepPreviewCache.value = data.rendered_steps)
.catch(err => stepPreviewCache.value = "?? Error ??");
}, 750);
updatePreview: debounce(function() { watch(
api.postPreviewSteps(this.recipe.step_text) () => props.recipe.step_text,
.then(data => this.stepPreviewCache = data.rendered_steps) () => updatePreview()
.catch(err => this.stepPreviewCache = "?? Error ??"); );
}, 750)
},
watch: {
'recipe.step_text': function() {
this.updatePreview();
}
},
mounted() {
//autosize(this.$refs.step_text_area);
},
components: {
RecipeEditIngredientEditor
}
}
</script> </script>

View File

@ -12,18 +12,22 @@
</div> </div>
<div class="column is-half"> <div class="column is-half">
<table class="table is-bordered is-narrow is-size-7"> <table class="table is-bordered is-narrow is-size-7">
<thead>
<tr> <tr>
<th>#</th> <th>#</th>
<th>Unit</th> <th>Unit</th>
<th>Name</th> <th>Name</th>
<th>Prep</th> <th>Prep</th>
</tr> </tr>
</thead>
<tbody>
<tr v-for="i in bulkIngredientPreview"> <tr v-for="i in bulkIngredientPreview">
<td>{{i.quantity}}</td> <td>{{i.quantity}}</td>
<td>{{i.units}}</td> <td>{{i.units}}</td>
<td>{{i.name}}</td> <td>{{i.name}}</td>
<td>{{i.preparation}}</td> <td>{{i.preparation}}</td>
</tr> </tr>
</tbody>
</table> </table>
</div> </div>
</div> </div>
@ -39,33 +43,28 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, ref } from "vue";
import { useMediaQueryStore } from "../stores/mediaQuery";
import RecipeEditIngredientItem from "./RecipeEditIngredientItem"; import RecipeEditIngredientItem from "./RecipeEditIngredientItem";
import { mapState } from "vuex"; const mediaQueryStore = useMediaQueryStore();
export default { const props = defineProps({
props: {
ingredients: { ingredients: {
required: true, required: true,
type: Array type: Array
} }
}, });
data() { const isBulkEditing = ref(false);
return { const bulkEditText = ref(null);
isBulkEditing: false, const isMobile = computed(() => mediaQueryStore.mobile);
bulkEditText: null const visibleIngredients = computed(() => props.ingredients.filter(i => i._destroy !== true));
};
},
computed: { const bulkIngredientPreview = computed(() => {
...mapState({ if (bulkEditText.value === null || bulkEditText.value === "") {
isMobile: state => state.mediaQueries.mobile
}),
bulkIngredientPreview() {
if (this.bulkEditText === null) {
return []; return [];
} }
@ -80,7 +79,7 @@
}; };
const parsed = []; const parsed = [];
const lines = this.bulkEditText.replace("\r", "").split("\n"); const lines = bulkEditText.value.replace("\r", "").split("\n");
for (let line of lines) { for (let line of lines) {
if (line.length === 0) { continue; } if (line.length === 0) { continue; }
@ -97,16 +96,10 @@
} }
return parsed; return parsed;
}, });
visibleIngredients() { function createIngredient() {
return this.ingredients.filter(i => i._destroy !== true); const sort_orders = props.ingredients.map(i => i.sort_order);
}
},
methods: {
createIngredient() {
const sort_orders = this.ingredients.map(i => i.sort_order);
sort_orders.push(0); sort_orders.push(0);
const next_sort_order = Math.max(...sort_orders) + 5; const next_sort_order = Math.max(...sort_orders) + 5;
@ -119,27 +112,27 @@
ingredient_id: null, ingredient_id: null,
sort_order: next_sort_order sort_order: next_sort_order
}; };
}, }
addIngredient() { function addIngredient() {
this.ingredients.push(this.createIngredient()); props.ingredients.push(createIngredient());
}, }
deleteFood(food) { function deleteFood(food) {
if (food.id) { if (food.id) {
food._destroy = true; food._destroy = true;
} else { } else {
const idx = this.ingredients.findIndex(i => i === food); const idx = props.ingredients.findIndex(i => i === food);
this.ingredients.splice(idx, 1); props.ingredients.splice(idx, 1);
}
} }
},
bulkEditIngredients() { function bulkEditIngredients() {
this.isBulkEditing = true; isBulkEditing.value = true;
let text = []; let text = [];
for (let item of this.visibleIngredients) { for (let item of visibleIngredients.value) {
text.push( text.push(
item.quantity + " " + item.quantity + " " +
(item.units || "-") + " " + (item.units || "-") + " " +
@ -149,16 +142,16 @@
); );
} }
this.bulkEditText = text.join("\n"); bulkEditText.value = text.join("\n");
}, }
cancelBulkEditing() { function cancelBulkEditing() {
this.isBulkEditing = false; isBulkEditing.value = false;
}, }
saveBulkEditing() { function saveBulkEditing() {
const parsed = this.bulkIngredientPreview.filter(i => i !== null); const parsed = bulkIngredientPreview.value.filter(i => i !== null);
const existing = [...this.ingredients]; const existing = [...props.ingredients];
const newList = []; const newList = [];
for (let parsedIngredient of parsed) { for (let parsedIngredient of parsed) {
@ -177,7 +170,7 @@
} }
if (newIngredient === null) { if (newIngredient === null) {
newIngredient = this.createIngredient(); newIngredient = createIngredient();
} }
newIngredient.quantity = parsedIngredient.quantity; newIngredient.quantity = parsedIngredient.quantity;
@ -191,20 +184,14 @@
newList.push({id: oldExisting.id, _destroy: true}); newList.push({id: oldExisting.id, _destroy: true});
} }
this.ingredients.splice(0); props.ingredients.splice(0);
let sortIdx = 0; let sortIdx = 0;
for (let n of newList) { for (let n of newList) {
n.sort_order = sortIdx++; n.sort_order = sortIdx++;
this.ingredients.push(n); props.ingredients.push(n);
} }
this.isBulkEditing = false; isBulkEditing.value = false;
}
},
components: {
RecipeEditIngredientItem
}
} }
</script> </script>

View File

@ -44,12 +44,13 @@
</div> </div>
</template> </template>
<script> <script setup>
import { useTemplateRef, watch } from "vue";
import api from "../lib/Api"; import api from "../lib/Api";
export default { const emit = defineEmits(["deleteFood"]);
props: { const props = defineProps({
ingredient: { ingredient: {
required: true, required: true,
type: Object type: Object
@ -59,40 +60,34 @@
type: Boolean, type: Boolean,
default: false default: false
} }
}, });
methods: { const autocompleteElement = useTemplateRef("autocomplete");
deleteFood(ingredient) {
this.$emit("deleteFood", ingredient);
},
updateSearchItems(text) { watch(props.ingredient, (val) => {
if (props.ingredient.ingredient && props.ingredient.ingredient.name !== val) {
props.ingredient.ingredient_id = null;
props.ingredient.ingredient = null;
}
});
function deleteFood(ingredient) {
emit("deleteFood", ingredient);
}
function updateSearchItems(text) {
return api.getSearchIngredients(text); return api.getSearchIngredients(text);
},
searchItemSelected(ingredient) {
this.ingredient.ingredient_id = ingredient.id;
this.ingredient.ingredient = ingredient;
this.ingredient.name = ingredient.name;
},
nameClick() {
if (this.ingredient.ingredient_id === null && this.ingredient.name !== null && this.ingredient.name.length > 2) {
this.$refs.autocomplete.updateOptions(this.ingredient.name);
} }
}
},
watch: { function searchItemSelected(ingredient) {
'ingredient.name': function(val) { props.ingredient.ingredient_id = ingredient.id;
if (this.ingredient.ingredient && this.ingredient.ingredient.name !== val) { props.ingredient.ingredient = ingredient;
this.ingredient.ingredient_id = null; props.ingredient.name = ingredient.name;
this.ingredient.ingredient = null;
} }
}
},
components: { function nameClick() {
if (props.ingredient.ingredient_id === null && props.ingredient.name !== null && props.ingredient.name.length > 2) {
autocompleteElement.updateOptions(props.ingredient.name);
} }
} }
@ -100,10 +95,10 @@
<style lang="scss" scoped> <style lang="scss" scoped>
@import "../styles/variables"; @use "bulma/sass/utilities" as bulma;
.edit-ingredient-item { .edit-ingredient-item {
border-bottom: solid 1px $grey-light; border-bottom: solid 1px bulma.$grey-light;
margin-bottom: 1.25rem; margin-bottom: 1.25rem;
&:last-child { &:last-child {

View File

@ -38,7 +38,7 @@
Ingredients Ingredients
<button class="button is-small is-primary" type="button" @click="showConvertDialog = true">Convert</button> <button class="button is-small is-primary" type="button" @click="showConvertDialog = true">Convert</button>
<app-dropdown :open="addToTasksMenuOpen" label="Add to list" button-class="is-small is-primary" @open="addToTasksMenuOpen = true" @close="addToTasksMenuOpen = false"> <app-dropdown :open="addToTasksMenuOpen" label="Add to list" button-class="is-small is-primary" @open="addToTasksMenuOpen = true" @close="addToTasksMenuOpen = false">
<button class="button primary" v-for="tl in taskLists" :key="tl.id" @click="addRecipeToList(tl)"> <button class="button primary" v-for="tl in taskStore.taskLists" :key="tl.id" @click="addRecipeToList(tl)">
{{tl.name}} {{tl.name}}
</button> </button>
</app-dropdown> </app-dropdown>
@ -65,14 +65,18 @@
<div class="message-header" @click="showNutrition = !showNutrition">Nutrition Data</div> <div class="message-header" @click="showNutrition = !showNutrition">Nutrition Data</div>
<div class="message-body" v-show="showNutrition"> <div class="message-body" v-show="showNutrition">
<table class="table"> <table class="table">
<thead>
<tr> <tr>
<th>Item</th> <th>Item</th>
<th>Value</th> <th>Value</th>
</tr> </tr>
</thead>
<tbody>
<tr v-for="nutrient in recipe.nutrition_data.nutrients" :key="nutrient.name"> <tr v-for="nutrient in recipe.nutrition_data.nutrients" :key="nutrient.name">
<td>{{nutrient.label}}</td> <td>{{nutrient.label}}</td>
<td>{{ roundValue(nutrient.value) }}</td> <td>{{ roundValue(nutrient.value) }}</td>
</tr> </tr>
</tbody>
</table> </table>
<h3 class="title is-5">Nutrition Calculation Warnings</h3> <h3 class="title is-5">Nutrition Calculation Warnings</h3>
@ -146,30 +150,32 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import api from "../lib/Api"; import api from "../lib/Api";
import { mapActions, mapMutations, mapState } from "vuex"; import { useTaskStore } from "../stores/task";
export default { const taskStore = useTaskStore();
props: { const router = useRouter();
const props = defineProps({
recipe: { recipe: {
required: true, required: true,
type: Object type: Object
} }
}, });
data() { const showNutrition = ref(false);
return { const showConvertDialog = ref(false);
showNutrition: false, const addToTasksMenuOpen = ref(false);
showConvertDialog: false,
addToTasksMenuOpen: false,
scaleValue: '1', const scaleValue = ref('1');
systemConvertValue: "", const systemConvertValue = ref('');
unitConvertValue: "", const unitConvertValue = ref('');
scaleOptions: [ const scaleOptions = [
'1/4', '1/4',
'1/3', '1/3',
'1/2', '1/2',
@ -180,87 +186,60 @@
'2', '2',
'3', '3',
'4' '4'
] ];
};
},
computed: { const timeDisplay = computed(() => {
...mapState([ let a = formatMinutes(props.recipe.active_time);
'taskLists' const t = formatMinutes(props.recipe.total_time);
]),
timeDisplay() {
let a = this.formatMinutes(this.recipe.active_time);
const t = this.formatMinutes(this.recipe.total_time);
if (a) { if (a) {
a = ` (${a} active)`; a = ` (${a} active)`;
} }
return t + a; return t + a;
}, });
sourceUrl() { const sourceUrl = computed(() => {
try { try {
return new URL(this.recipe.source); return new URL(props.recipe.source);
} catch(err) { } catch(err) {
return null; return null;
} }
},
isSourceUrl() {
return this.sourceUrl !== null;
},
sourceText() {
if (this.isSourceUrl) {
return this.sourceUrl.host;
} else {
return this.recipe.source;
}
}
},
watch: {
recipe: {
handler: function(r) {
if (r) {
this.scaleValue = r.converted_scale || '1';
this.systemConvertValue = r.converted_system;
this.unitConvertValue = r.converted_unit;
}
},
immediate: true
}
},
methods: {
...mapActions([
'ensureTaskLists'
]),
...mapMutations([
'setCurrentTaskList'
]),
addRecipeToList(list) {
api.addRecipeToTaskList(list.id, this.recipe.id)
.then(() => {
this.setCurrentTaskList(list);
this.$router.push({name: 'task_lists'})
}); });
},
convert() { const isSourceUrl = computed(() => sourceUrl.value !== null);
this.showConvertDialog = false; const sourceText = computed(() => isSourceUrl.value ? sourceUrl.value.host : props.recipe.source);
this.$router.push({name: 'recipe', query: { scale: this.scaleValue, system: this.systemConvertValue, unit: this.unitConvertValue }});
},
roundValue(v) { watch(props.recipe, (r) => {
if (r) {
scaleValue.value = r.converted_scale || '1';
systemConvertValue.value = r.converted_system;
unitConvertValue.value = r.converted_unit;
}
}, { immediate: true });
onMounted(() => {
taskStore.ensureTaskLists();
});
function addRecipeToList(list) {
api.addRecipeToTaskList(list.id, props.recipe.id)
.then(() => {
taskStore.setCurrentTaskList(list);
router.push({name: 'task_lists'})
});
}
function convert() {
showConvertDialog.value = false;
router.push({name: 'recipe', query: { scale: scaleValue.value, system: systemConvertValue.value, unit: unitConvertValue.value }});
}
function roundValue(v) {
return parseFloat(v).toFixed(2); return parseFloat(v).toFixed(2);
}, }
formatMinutes(min) { function formatMinutes(min) {
if (min) { if (min) {
const partUnits = [ const partUnits = [
{unit: "d", minutes: 60 * 24}, {unit: "d", minutes: 60 * 24},
@ -285,12 +264,6 @@
return ""; return "";
} }
} }
},
mounted() {
this.ensureTaskLists();
}
}
</script> </script>

View File

@ -24,38 +24,41 @@
</div> </div>
</template> </template>
<script> <script setup>
export default { import { onMounted, useTemplateRef } from "vue";
props: {
const emit = defineEmits(["save"]);
const props = defineProps({
taskItem: { taskItem: {
required: true, required: true,
type: Object type: Object
} }
}, });
methods: { const nameElement = useTemplateRef("nameInput");
inputKeydown(evt) {
onMounted(() => focus());
function inputKeydown(evt) {
switch (evt.key) { switch (evt.key) {
case "Enter": case "Enter":
evt.preventDefault(); evt.preventDefault();
this.save(); save();
}
} }
},
save() { function save() {
this.$emit("save", this.taskItem); emit("save", props.taskItem);
}, }
focus() { function focus() {
this.$refs.nameInput.focus(); nameElement.value.focus();
} }
},
mounted() { defineExpose({
this.focus(); focus
} });
}
</script> </script>

View File

@ -60,138 +60,106 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, ref, useTemplateRef } from "vue";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { mapActions } from "vuex"; import { useTaskStore } from "../stores/task";
import cloneDeep from "lodash/cloneDeep"; import { useLoadResource } from "../lib/useLoadResource";
import TaskItemEdit from "./TaskItemEdit"; import TaskItemEdit from "./TaskItemEdit";
const newItemTemplate = function(listId) { const { loadResource } = useLoadResource();
return { const taskStore = useTaskStore();
task_list_id: listId, const itemEditElement = useTemplateRef("itemEdit");
name: '',
quantity: '',
completed: false
};
};
export default { const props = defineProps({
props: {
taskList: { taskList: {
required: true, required: true,
type: Object type: Object
} }
}, });
data() { const showAddItem = ref(false);
const newItem = ref(null);
const newItemValidationErrors = ref({});
const completedTaskItems = computed(() => (props.taskList ? props.taskList.task_items : []).filter(i => i.completed));
const uncompletedTaskItems = computed(() => (props.taskList ? props.taskList.task_items : []).filter(i => !i.completed));
const completedItemCount = computed(() => completedTaskItems.value.length);
const uncompletedItemCount = computed(() => uncompletedTaskItems.value.length);
const taskItems = computed(() => uncompletedTaskItems.value.concat(completedTaskItems.value));
function newItemTemplate() {
return { return {
showAddItem: false, task_list_id: null,
newItem: null, name: '',
newItemValidationErrors: {} quantity: '',
completed: false
}; };
},
computed: {
completedItemCount() {
return this.taskList === null ? 0 : this.taskList.task_items.filter(i => i.completed).length;
},
uncompletedItemCount() {
return this.taskList === null ? 0 : this.taskList.task_items.filter(i => !i.completed).length;
},
completedTaskItems() {
return (this.taskList ? this.taskList.task_items : []).filter(i => i.completed);
},
uncompletedTaskItems() {
return (this.taskList ? this.taskList.task_items : []).filter(i => !i.completed);
},
taskItems() {
return this.uncompletedTaskItems.concat(this.completedTaskItems);
} }
},
methods: { function save() {
...mapActions([ newItem.value.task_list_id = props.taskList.id;
'createTaskItem', loadResource(
'updateTaskItem', taskStore.createTaskItem(newItem.value)
'deleteTaskItems',
'completeTaskItems'
]),
save() {
this.loadResource(
this.createTaskItem(this.newItem)
.then(() => { .then(() => {
this.newItem = newItemTemplate(this.taskList.id); newItem.value = newItemTemplate();
this.$refs.itemEdit.focus(); itemEditElement.value.focus();
}) })
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.newItemValidationErrors = err.validationErrors())) .catch(Errors.onlyFor(Errors.ApiValidationError, err => newItemValidationErrors.value = err.validationErrors()))
) )
}, }
toggleItem(i) { function toggleItem(i) {
this.loadResource( loadResource(
this.completeTaskItems({ taskStore.completeTaskItems({
taskList: this.taskList, taskList: props.taskList,
taskItems: [i], taskItems: [i],
completed: !i.completed completed: !i.completed
}) })
); );
}, }
toggleShowAddItem() { function toggleShowAddItem() {
this.newItem = newItemTemplate(this.taskList.id); newItem.value = newItemTemplate();
this.showAddItem = !this.showAddItem; showAddItem.value = !showAddItem.value;
}, }
completeAllItems() { function completeAllItems() {
const toComplete = this.taskList.task_items.filter(i => !i.completed); const toComplete = props.taskList.task_items.filter(i => !i.completed);
this.loadResource( loadResource(
this.completeTaskItems({ taskStore.completeTaskItems({
taskList: this.taskList, taskList: props.taskList,
taskItems: toComplete, taskItems: toComplete,
completed: true completed: true
}) })
) )
}, }
unCompleteAllItems() { function unCompleteAllItems() {
const toUnComplete = this.taskList.task_items.filter(i => i.completed); const toUnComplete = props.taskList.task_items.filter(i => i.completed);
this.loadResource( loadResource(
this.completeTaskItems({ taskStore.completeTaskItems({
taskList: this.taskList, taskList: props.taskList,
taskItems: toUnComplete, taskItems: toUnComplete,
completed: false completed: false
}) })
) )
}, }
deleteCompletedItems() { function deleteCompletedItems() {
this.loadResource( loadResource(
this.deleteTaskItems({ taskStore.deleteTaskItems({
taskList: this.taskList, taskList: props.taskList,
taskItems: this.taskList.task_items.filter(i => i.completed) taskItems: props.taskList.task_items.filter(i => i.completed)
}) })
); );
},
},
components: {
TaskItemEdit
}
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "../styles/variables";
.columns { .columns {
margin-top: 0; margin-top: 0;
margin-bottom: 0; margin-bottom: 0;

View File

@ -14,10 +14,13 @@
</template> </template>
<script> <script setup>
export default { import { ref } from "vue";
props: {
const emit = defineEmits(["select", "delete"]);
const props = defineProps({
taskList: { taskList: {
type: Object, type: Object,
required: true required: true
@ -28,44 +31,38 @@
required: false, required: false,
default: false default: false
} }
}, });
data() { const hovering = ref(false);
return { const confirmingDelete = ref(false);
hovering: false,
confirmingDelete: false
};
},
methods: { function selectList() {
selectList() { emit("select", props.taskList);
this.$emit("select", this.taskList);
},
deleteList() {
this.confirmingDelete = false;
this.$emit("delete", this.taskList);
}
} }
function deleteList() {
confirmingDelete.value = false;
emit("delete", props.taskList);
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "~styles/variables"; @use "bulma/sass/utilities" as bulma;
@use 'sass:color';
div.dropdown-item { div.dropdown-item {
cursor: pointer; cursor: pointer;
&.hovered { &.hovered {
color: $black; color: bulma.$black;
background-color: $background; background-color: bulma.$background;
} }
&.is-active { &.is-active {
color: $link-invert; color: color.invert(bulma.$link);
background-color: $link; background-color: bulma.$link;
} }
} }

View File

@ -14,10 +14,11 @@
</div> </div>
</template> </template>
<script> <script setup>
export default { const emit = defineEmits(["save"]);
props: {
const props = defineProps({
taskList: { taskList: {
required: true, required: true,
type: Object type: Object
@ -28,20 +29,17 @@
type: Object, type: Object,
default: function() { return {}; } default: function() { return {}; }
} }
}, });
methods: { function save() {
save() { emit("save");
this.$emit("save"); }
},
nameKeydownHandler(evt) { function nameKeydownHandler(evt) {
switch (evt.key) { switch (evt.key) {
case "Enter": case "Enter":
evt.preventDefault(); evt.preventDefault();
this.save(); save();
}
}
} }
} }

View File

@ -5,10 +5,7 @@
</div> </div>
</template> </template>
<script> <script setup>
export default {
}
</script> </script>

View File

@ -7,7 +7,7 @@
</p> </p>
<p> <p>
Parsley is released under the MIT License. All code &copy; Dan Elbert 2020. Parsley is released under the MIT License. All code &copy; Dan Elbert 2024.
</p> </p>
<p> <p>
@ -19,11 +19,7 @@
</div> </div>
</template> </template>
<script> <script setup>
export default {
}
</script> </script>

View File

@ -2,11 +2,8 @@
</template> </template>
<script> <script setup>
export default {
}
</script> </script>

View File

@ -29,24 +29,21 @@
</template> </template>
<script> <script setup>
import { onBeforeMount, ref } from "vue";
import { useLoadResource } from "../lib/useLoadResource";
import api from "../lib/Api"; import api from "../lib/Api";
export default { const { loadResource } = useLoadResource();
data() { const userList = ref([]);
return {
userList: []
};
},
created() { onBeforeMount(() => {
this.loadResource( loadResource(
api.getAdminUserList() api.getAdminUserList()
.then(list => this.userList = list) .then(list => userList.value = list)
); );
} });
}
</script> </script>

View File

@ -40,93 +40,64 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, ref, watch } from "vue";
import api from "../lib/Api"; import api from "../lib/Api";
import debounce from "lodash/debounce"; import debounce from "lodash/debounce";
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data() {
return {
input: '',
outputUnit: '',
ingredient_name: '',
ingredient: null,
density: '',
output: '',
errors: {}
};
},
computed: { const input = ref("");
inputErrors() { const outputUnit = ref("");
if (this.errors.input && this.errors.input.length > 0) { const ingredient_name = ref("");
return this.errors.input.join(", "); const ingredient = ref(null);
} else { const density = ref("");
return null; const output = ref("");
} const errors = ref({});
},
outputUnitErrors() { const inputErrors = computed(() => getErrors("input"));
if (this.errors.output_unit && this.errors.output_unit.length > 0) { const outputUnitErrors = computed(() => getErrors("output_unit"));
return this.errors.output_unit.join(", "); const densityErrors = computed(() => getErrors("density"));
} else {
return null;
}
},
densityErrors() { const updateOutput = debounce(function() {
if (this.errors.density && this.errors.density.length > 0) { if (input.value && input.value.length > 0) {
return this.errors.density.join(", "); loadResource(api.getCalculate(input.value, outputUnit.value, ingredient.value ? ingredient.value.ingredient_id : null, density.value)
} else {
return null;
}
}
},
methods: {
updateSearchItems(text) {
return api.getSearchIngredients(text);
},
searchItemSelected(ingredient) {
this.ingredient = ingredient || null;
this.ingredient_name = ingredient.name || null;
this.density = ingredient.density || null;
},
updateOutput: debounce(function() {
if (this.input && this.input.length > 0) {
this.loadResource(api.getCalculate(this.input, this.outputUnit, this.ingredient ? this.ingredient.ingredient_id : null, this.density)
.then(data => { .then(data => {
this.output = data.output; output.value = data.output;
this.errors = data.errors; errors.value = data.errors;
}) })
); );
} }
}, 500) }, 500);
},
watch: { watch(ingredient_name, function(val) {
'ingredient_name': function(val) { if (ingredient.value && ingredient.value.name !== val) {
if (this.ingredient && this.ingredient.name !== val) { ingredient.value = null;
this.ingredient = null;
} }
} });
},
created() { watch(
this.$watch( [input, outputUnit, density, ingredient],
function() { () => updateOutput()
return [this.input, this.outputUnit, this.density, this.ingredient]; );
},
function() {
this.updateOutput();
}
)
},
components: { function updateSearchItems(text) {
return api.getSearchIngredients(text);
}
function searchItemSelected(ingredient) {
ingredient.value = ingredient || null;
ingredient_name.value = ingredient.name || null;
density.value = ingredient.density || null;
}
function getErrors(type) {
if (errors.value[type] && errors.value[type].length > 0) {
return errors.value[type].join(", ");
} else {
return null;
} }
} }

View File

@ -7,41 +7,33 @@
<food-show :food="food"></food-show> <food-show :food="food"></food-show>
</div> </div>
<router-link v-if="isLoggedIn" class="button" :to="{name: 'edit_food', params: { id: foodId }}">Edit</router-link> <router-link v-if="appConfig.isLoggedIn" class="button" :to="{name: 'edit_food', params: { id: foodId }}">Edit</router-link>
<router-link class="button" to="/foods">Back</router-link> <router-link class="button" to="/foods">Back</router-link>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute } from "vue-router";
import FoodShow from "./FoodShow"; import FoodShow from "./FoodShow";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import { useLoadResource } from "../lib/useLoadResource";
import { useAppConfigStore } from "../stores/appConfig";
export default { const { loadResource } = useLoadResource();
data: function () { const appConfig = useAppConfigStore();
return { const route = useRoute();
food: null
}
},
computed: { const food = ref(null);
...mapState({ const foodId = computed(() => route.params.id);
foodId: state => state.route.params.id,
})
},
created() { onBeforeMount(() => {
this.loadResource( loadResource(
api.getFood(this.foodId) api.getFood(foodId.value)
.then(data => { this.food = data; return data; }) .then(data => { food.value = data; return data; })
); );
}, });
components: {
FoodShow
}
}
</script> </script>

View File

@ -9,17 +9,20 @@
</div> </div>
</template> </template>
<script> <script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import FoodEdit from "./FoodEdit"; import FoodEdit from "./FoodEdit";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data() { const router = useRouter();
return {
food: { const validationErrors = ref({});
const food = reactive({
name: null, name: null,
notes: null, notes: null,
ndbn: null, ndbn: null,
@ -50,26 +53,16 @@
cholesterol: null, cholesterol: null,
lipids: null, lipids: null,
food_units: [] food_units: []
}, });
validationErrors: {}
}
},
methods: { function save() {
save() { validationErrors.value = {}
this.validationErrors = {} loadResource(
this.loadResource( api.postFood(food)
api.postFood(this.food) .then(() => router.push('/foods'))
.then(() => this.$router.push('/foods')) .catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
); );
} }
},
components: {
FoodEdit
}
}
</script> </script>

View File

@ -14,48 +14,37 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import FoodEdit from "./FoodEdit"; import FoodEdit from "./FoodEdit";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data: function () { const router = useRouter();
return { const route = useRoute();
food: null,
validationErrors: {}
};
},
computed: { const food = ref(null);
...mapState({ const validationErrors = ref({});
foodId: state => state.route.params.id, const foodId = computed(() => route.params.id);
})
},
methods: { onBeforeMount(() => {
save() { loadResource(
this.validationErrors = {}; api.getFood(foodId.value)
this.loadResource( .then(data => { food.value = data; return data; })
api.patchFood(this.food)
.then(() => this.$router.push({name: 'food', params: {id: this.foodId }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
); );
} });
},
created() { function save() {
this.loadResource( validationErrors.value = {};
api.getFood(this.foodId) loadResource(
.then(data => { this.food = data; return data; }) api.patchFood(food.value)
.then(() => router.push({name: 'food', params: {id: foodId.value }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
); );
},
components: {
FoodEdit
}
} }
</script> </script>

View File

@ -3,7 +3,7 @@
<h1 class="title">Ingredients</h1> <h1 class="title">Ingredients</h1>
<div class="buttons"> <div class="buttons">
<router-link v-if="isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link> <router-link v-if="appConfig.isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link>
</div> </div>
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="food" @changePage="changePage"></app-pager> <app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="food" @changePage="changePage"></app-pager>
@ -35,12 +35,14 @@
<td>{{i.kcal}}</td> <td>{{i.kcal}}</td>
<td>{{i.density}}</td> <td>{{i.density}}</td>
<td> <td>
<router-link v-if="isLoggedIn" class="button" :to="{name: 'edit_food', params: { id: i.id } }"> <template v-if="appConfig.isLoggedIn">
<router-link class="button" :to="{name: 'edit_food', params: { id: i.id } }">
<app-icon icon="pencil"></app-icon> <app-icon icon="pencil"></app-icon>
</router-link> </router-link>
<button v-if="isLoggedIn" type="button" class="button is-danger" @click="deleteFood(i)"> <button type="button" class="button is-danger" @click="deleteFood(i)">
<app-icon icon="x"></app-icon> <app-icon icon="x"></app-icon>
</button> </button>
</template>
</td> </td>
</tr> </tr>
</transition-group> </transition-group>
@ -49,114 +51,80 @@
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="food" @changePage="changePage"></app-pager> <app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="food" @changePage="changePage"></app-pager>
<div class="buttons"> <div class="buttons">
<router-link v-if="isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link> <router-link v-if="appConfig.isLoggedIn" :to="{name: 'new_food'}" class="button is-primary">Create Ingredient</router-link>
</div> </div>
<app-confirm :open="showConfirmFoodDelete" :message="confirmFoodDeleteMessage" :cancel="foodDeleteCancel" :confirm="foodDeleteConfirm"></app-confirm> <app-confirm :open="showConfirmFoodDelete" title="Delete Ingredient?" :message="confirmFoodDeleteMessage" @cancel="foodDeleteCancel" @confirm="foodDeleteConfirm"></app-confirm>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, reactive, ref, watch } from "vue";
import api from "../lib/Api"; import api from "../lib/Api";
import debounce from "lodash/debounce"; import debounce from "lodash/debounce";
import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
export default { const appConfig = useAppConfigStore();
data() { const { loadResource } = useLoadResource();
return {
foodData: null, const foodData = ref(null);
foodForDeletion: null, const foodForDeletion = ref(null);
search: { const search = reactive({
page: 1, page: 1,
per: 25, per: 25,
name: null name: null
} });
};
},
computed: { const foods = computed(() => foodData.value?.foods || []);
foods() { const totalPages = computed(() => foodData.value?.total_pages || 0);
if (this.foodData) { const currentPage = computed(() => foodData.value?.current_page || 0);
return this.foodData.foods; const showConfirmFoodDelete = computed(() => foodForDeletion.value !== null);
} else { const confirmFoodDeleteMessage = computed(() => {
return []; if (foodForDeletion.value !== null) {
} return `Are you sure you want to delete ${foodForDeletion.value.name}?`;
},
totalPages() {
if (this.foodData) {
return this.foodData.total_pages
}
return 0;
},
currentPage() {
if (this.foodData) {
return this.foodData.current_page
}
return 0;
},
showConfirmFoodDelete() {
return this.foodForDeletion !== null;
},
confirmFoodDeleteMessage() {
if (this.foodForDeletion !== null) {
return `Are you sure you want to delete ${this.foodForDeletion.name}?`;
} else { } else {
return "??"; return "??";
} }
} });
},
methods: { const getList = debounce(function() {
changePage(idx) { return loadResource(
this.search.page = idx; api.getFoodList(search.page, search.per, search.name)
}, .then(data => foodData.value = data)
getList: debounce(function() {
return this.loadResource(
api.getFoodList(this.search.page, this.search.per, this.search.name)
.then(data => this.foodData = data)
); );
}, 500, {leading: true, trailing: true}), }, 500, {leading: true, trailing: true});
deleteFood(food) { watch(search,
this.foodForDeletion = food; () => getList(),
},
foodDeleteCancel() {
this.foodForDeletion = null;
},
foodDeleteConfirm() {
if (this.foodForDeletion !== null) {
this.loadResource(
api.deleteFood(this.foodForDeletion.id).then(res => {
this.foodForDeletion = null;
return this.getList();
})
);
console.log("This is where the thing happens!!");
this.foodForDeletion = null;
}
}
},
created() {
this.$watch("search",
() => this.getList(),
{ {
deep: true, deep: true,
immediate: true immediate: true
} }
); );
},
components: { function changePage(idx) {
search.page = idx;
}
function deleteFood(food) {
foodForDeletion.value = food;
}
function foodDeleteCancel() {
foodForDeletion.value = null;
}
function foodDeleteConfirm() {
if (foodForDeletion.value !== null) {
loadResource(
api.deleteFood(foodForDeletion.value.id).then(res => {
foodForDeletion.value = null;
return getList();
})
);
} }
} }

View File

@ -8,42 +8,34 @@
</div> </div>
<div class="buttons"> <div class="buttons">
<router-link v-if="isLoggedIn" class="button" :to="{name: 'edit_log', params: { id: logId }}">Edit</router-link> <router-link v-if="appConfig.isLoggedIn" class="button" :to="{name: 'edit_log', params: { id: logId }}">Edit</router-link>
<router-link class="button" to="/logs">Back</router-link> <router-link class="button" to="/logs">Back</router-link>
</div> </div>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute } from "vue-router";
import LogShow from "./LogShow"; import LogShow from "./LogShow";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import { useLoadResource } from "../lib/useLoadResource";
import { useAppConfigStore } from "../stores/appConfig";
export default { const { loadResource } = useLoadResource();
data: function () { const route = useRoute();
return { const appConfig = useAppConfigStore();
log: null
}
},
computed: { const log = ref(null);
...mapState({ const logId = computed(() => route.params.id);
logId: state => state.route.params.id,
})
},
created() { onBeforeMount(() => {
this.loadResource( loadResource(
api.getLog(this.logId) api.getLog(logId.value)
.then(data => { this.log = data; return data; }) .then(data => { log.value = data; return data; })
); );
}, });
components: {
LogShow
}
}
</script> </script>

View File

@ -16,54 +16,44 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, onBeforeMount, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import LogEdit from "./LogEdit"; import LogEdit from "./LogEdit";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data() { const route = useRoute();
return { const router = useRouter();
validationErrors: {},
log: { const validationErrors = ref({});
const log = reactive({
date: null, date: null,
rating: null, rating: null,
notes: null, notes: null,
recipe: null recipe: null
} });
}
},
computed: { const recipeId = computed(() => route.params.recipeId);
...mapState({
recipeId: state => state.route.params.recipeId,
})
},
methods: { onBeforeMount(() => {
save() { loadResource(
this.log.original_recipe_id = this.recipeId; api.getRecipe(recipeId.value, null, null, null, data => log.recipe = data)
this.validationErrors = {};
this.loadResource(
api.postLog(this.log)
.then(() => this.$router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
); );
} });
},
created() { function save() {
this.loadResource( log.original_recipe_id = recipeId.value;
api.getRecipe(this.recipeId, null, null, null, data => this.log.recipe = data) validationErrors.value = {};
loadResource(
api.postLog(log)
.then(() => router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
); );
},
components: {
LogEdit
}
} }
</script> </script>

View File

@ -16,48 +16,38 @@
</div> </div>
</template> </template>
<script> <script setup>
import { mapState } from "vuex"; import { computed, onBeforeMount, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from "../lib/Errors"; import * as Errors from "../lib/Errors";
import LogEdit from "./LogEdit"; import LogEdit from "./LogEdit";
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data() { const route = useRoute();
return { const router = useRouter();
validationErrors: {},
log: null
}
},
computed: { const validationErrors = ref({});
...mapState({ const log = ref(null);
logId: state => state.route.params.id,
})
},
methods: { const logId = computed(() => route.params.id);
save() {
this.validationErrors = {}; onBeforeMount(() => {
this.loadResource( loadResource(
api.patchLog(this.log) api.getLog(logId.value)
.then(() => this.$router.push('/')) .then(data => { log.value = data; return data; })
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
); );
} });
},
created() { function save() {
this.loadResource( validationErrors.value = {};
api.getLog(this.logId) loadResource(
.then(data => { this.log = data; return data; }) api.patchLog(log.value)
.then(() => router.push('/'))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
); );
},
components: {
LogEdit
}
} }
</script> </script>

View File

@ -5,86 +5,64 @@
</h1> </h1>
<table class="table"> <table class="table">
<thead>
<tr> <tr>
<th>Recipe</th> <th>Recipe</th>
<th>Date</th> <th>Date</th>
<th>Rating</th> <th>Rating</th>
<th>Notes</th> <th>Notes</th>
</tr> </tr>
</thead>
<tbody>
<tr v-for="l in logs" :key="l.id"> <tr v-for="l in logs" :key="l.id">
<td> <router-link :to="{name: 'log', params: {id: l.id}}">{{l.recipe.name}}</router-link></td> <td> <router-link :to="{name: 'log', params: {id: l.id}}">{{l.recipe.name}}</router-link></td>
<td><app-date-time :date-time="l.date" :show-time="false"></app-date-time> </td> <td><app-date-time :date-time="l.date" :show-time="false"></app-date-time> </td>
<td><app-rating :value="l.rating" readonly></app-rating></td> <td><app-rating :model-value="l.rating" readonly></app-rating></td>
<td>{{l.notes}}</td> <td>{{l.notes}}</td>
</tr> </tr>
</tbody>
</table> </table>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, reactive, ref, watch } from "vue";
import api from "../lib/Api"; import api from "../lib/Api";
import debounce from "lodash/debounce"; import debounce from "lodash/debounce";
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data() {
return { const logData = ref(null);
logData: null, const search = reactive({
search: {
page: 1, page: 1,
per: 25 per: 25
} });
};
},
computed: { const logs = computed(() => logData.value?.logs || []);
logs() { const totalPages = computed(() => logData.value?.total_pages || 0);
if (this.logData) { const currentPage = computed(() => logData.value?.current_page || 0);
return this.logData.logs;
} else {
return [];
}
},
totalPages() { const getList = debounce(function() {
if (this.logData) { loadResource(
return this.logData.total_pages api.getLogList(search.page, search.per)
} .then(data => logData.value = data)
return 0;
},
currentPage() {
if (this.logData) {
return this.logData.current_page
}
return 0;
}
},
methods: {
changePage(idx) {
this.search.page = idx;
},
getList: debounce(function() {
this.loadResource(
api.getLogList(this.search.page, this.search.per)
.then(data => this.logData = data)
); );
}, 500, {leading: true, trailing: true}) }, 500, {leading: true, trailing: true});
},
created() { watch(search,
this.$watch("search", () => getList(),
() => this.getList(),
{ {
deep: true, deep: true,
immediate: true immediate: true
} }
); );
}
function changePage(idx) {
search.page = idx;
} }
</script> </script>

View File

@ -9,12 +9,15 @@
</app-modal> </app-modal>
<table class="table"> <table class="table">
<thead>
<tr> <tr>
<th>Note</th> <th>Note</th>
<th>Date</th> <th>Date</th>
<th></th> <th></th>
</tr> </tr>
</thead>
<tbody>
<tr v-for="n in notes" :key="n.id"> <tr v-for="n in notes" :key="n.id">
<td> <td>
{{ n.content }} {{ n.content }}
@ -28,69 +31,61 @@
</button> </button>
</td> </td>
</tr> </tr>
</tbody>
</table> </table>
</div> </div>
</template> </template>
<script> <script setup>
import { onBeforeMount, ref } from "vue";
import api from "../lib/Api"; import api from "../lib/Api";
import NoteEdit from "./NoteEdit"; import NoteEdit from "./NoteEdit";
import { useLoadResource } from "../lib/useLoadResource";
export default { const { loadResource } = useLoadResource();
data() { const notes = ref([]);
return { const editNote = ref(null);
notes: [],
editNote: null
};
},
methods: { onBeforeMount(() => {
refreshList() { refreshList();
this.loadResource( });
function refreshList() {
loadResource(
api.getNoteList() api.getNoteList()
.then(data => this.notes = data) .then(data => notes.value = data)
); );
}, }
addNote() { function addNote() {
this.editNote = { id: null, content: "" }; editNote.value = { id: null, content: "" };
}, }
saveNote() { function saveNote() {
this.loadResource( loadResource(
api.postNote(this.editNote) api.postNote(editNote.value)
.then(() => { .then(() => {
this.editNote = null; editNote.value = null;
return this.refreshList(); return refreshList();
}) })
); );
}, }
cancelNote() { function cancelNote() {
this.editNote = null; editNote.value = null;
}, }
deleteNote(n) { function deleteNote(n) {
this.loadResource( loadResource(
api.deleteNote(n) api.deleteNote(n)
.then(() => { .then(() => {
return this.refreshList(); return refreshList();
}) })
); );
} }
},
created() {
this.refreshList();
},
components: {
NoteEdit
}
}
</script> </script>

View File

@ -17,67 +17,51 @@
<recipe-show :recipe="recipe"></recipe-show> <recipe-show :recipe="recipe"></recipe-show>
</div> </div>
<router-link v-if="isLoggedIn" class="button" :to="{name: 'edit_recipe', params: { id: recipeId }}">Edit</router-link> <router-link v-if="appConfig.isLoggedIn" class="button" :to="{name: 'edit_recipe', params: { id: recipeId }}">Edit</router-link>
<router-link class="button" to="/">Back</router-link> <router-link class="button" to="/">Back</router-link>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";
import RecipeShow from "./RecipeShow"; import RecipeShow from "./RecipeShow";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import { useLoadResource } from "../lib/useLoadResource";
import { useAppConfigStore } from "../stores/appConfig";
export default { const appConfig = useAppConfigStore();
data: function () { const route = useRoute();
return { const { loadResource } = useLoadResource();
recipe: null, const recipe = ref(null);
showNutrition: false
}
},
computed: { const recipeId = computed(() => route.params.id);
...mapState({ const scale = computed(() => route.query.scale || null);
recipeId: state => state.route.params.id, const system = computed(() => route.query.system || null);
routeQuery: state => state.route.query, const unit = computed(() => route.query.unit || null);
scale: state => state.route.query.scale || null, const isScaled = computed(() => recipe.value?.converted_scale?.length !== undefined && recipe.value.converted_scale.length > 0 && recipe.value.converted_scale !== "1");
system: state => state.route.query.system || null,
unit: state => state.route.query.unit || null
}),
isScaled() { watch(
return this.recipe.converted_scale !== null && this.recipe.converted_scale.length > 0 && this.recipe.converted_scale !== "1"; () => route.query,
} () => refreshData(),
}, { immediate: true }
);
watch: { watch(
routeQuery() { () => recipe.value?.name,
this.refreshData(); (newRecipe) => {
},
recipe(newRecipe) {
if (newRecipe) { if (newRecipe) {
document.title = `${newRecipe.name}`; document.title = `${newRecipe.name}`;
} }
} }
}, )
methods: { function refreshData() {
refreshData() { loadResource(
this.loadResource( api.getRecipe(recipeId.value, scale.value, system.value, unit.value, data => recipe.value = data)
api.getRecipe(this.recipeId, this.scale, this.system, this.unit, data => this.recipe = data)
); );
} }
},
created() {
this.refreshData();
},
components: {
RecipeShow
}
}
</script> </script>

View File

@ -13,17 +13,20 @@
</div> </div>
</template> </template>
<script> <script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import RecipeEdit from "./RecipeEdit"; import RecipeEdit from "./RecipeEdit";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
export default { const router = useRouter();
data() { const { loadResource } = useLoadResource();
return {
validationErrors: {}, const validationErrors = ref({});
recipe: { const recipe = ref({
name: null, name: null,
source: null, source: null,
description: null, description: null,
@ -33,25 +36,16 @@
step_text: null, step_text: null,
tags: [], tags: [],
ingredients: [] ingredients: []
} });
}
},
methods: { function save() {
save() { validationErrors.value = {};
this.validationErrors = {}; loadResource(
this.loadResource( api.postRecipe(recipe.value)
api.postRecipe(this.recipe) .then(() => router.push('/'))
.then(() => this.$router.push('/')) .catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
); );
} }
},
components: {
RecipeEdit
}
}
</script> </script>

View File

@ -18,48 +18,38 @@
</div> </div>
</template> </template>
<script> <script setup>
import { computed, onBeforeMount, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useLoadResource } from "../lib/useLoadResource";
import RecipeEdit from "./RecipeEdit"; import RecipeEdit from "./RecipeEdit";
import { mapState } from "vuex";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
export default { const { loadResource } = useLoadResource();
data: function () { const route = useRoute();
return { const router = useRouter();
recipe: null, const recipe = ref(null);
validationErrors: {} const validationErrors = ref({});
}
},
computed: { const recipeId = computed(() => route.params.id);
...mapState({
recipeId: state => state.route.params.id,
})
},
methods: { onBeforeMount(() => {
save() { loadResource(
this.validationErrors = {}; api.getRecipe(recipeId.value, null, null, null, data => { recipe.value = data; return data; })
this.loadResource( );
api.patchRecipe(this.recipe) });
.then(() => this.$router.push({name: 'recipe', params: {id: this.recipeId }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors())) function save() {
validationErrors.value = {};
loadResource(
api.patchRecipe(recipe.value)
.then(() => router.push({name: 'recipe', params: {id: recipeId.value }}))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
); );
} }
},
created() {
this.loadResource(
api.getRecipe(this.recipeId, null, null, null, data => { this.recipe = data; return data; })
);
},
components: {
RecipeEdit
}
}
</script> </script>

View File

@ -2,7 +2,7 @@
<div> <div>
<h1 class="title">Recipes</h1> <h1 class="title">Recipes</h1>
<router-link v-if="isLoggedIn" :to="{name: 'new_recipe'}" class="button is-primary">Create Recipe</router-link> <router-link v-if="appConfig.isLoggedIn" :to="{name: 'new_recipe'}" class="button is-primary">Create Recipe</router-link>
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager> <app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager>
@ -11,7 +11,7 @@
<table class="table is-fullwidth" :class="{ small: mediaQueries.touch }"> <table class="table is-fullwidth" :class="{ small: isTouch }">
<thead> <thead>
<tr> <tr>
<th v-for="h in tableHeader" :key="h.name"> <th v-for="h in tableHeader" :key="h.name">
@ -25,10 +25,10 @@
</tr> </tr>
<tr> <tr>
<td> <td>
<app-search-text placeholder="search names" :value="search.name" @input="setSearchName($event)"></app-search-text> <app-search-text placeholder="search names" :value="search.name" @update:modelValue="setSearchName($event)"></app-search-text>
</td> </td>
<td> <td>
<app-search-text placeholder="search tags" :value="search.tags" @input="setSearchTags($event)"></app-search-text> <app-search-text placeholder="search tags" :value="search.tags" @update:modelValue="setSearchTags($event)"></app-search-text>
</td> </td>
<td colspan="5"></td> <td colspan="5"></td>
</tr> </tr>
@ -42,17 +42,19 @@
</div> </div>
</td> </td>
<td> <td>
<app-rating v-if="r.rating !== null" :value="r.rating" readonly></app-rating> <app-rating v-if="r.rating !== null" :model-value="r.rating" readonly></app-rating>
<span v-else>--</span> <span v-else>--</span>
</td> </td>
<td>{{ r.yields }}</td> <td>{{ r.yields }}</td>
<td class="recipe-time">{{ formatRecipeTime(r.total_time, r.active_time) }}</td> <td class="recipe-time">{{ formatRecipeTime(r.total_time, r.active_time) }}</td>
<td><app-date-time :date-time="r.created_at" :show-time="false"></app-date-time></td> <td><app-date-time :date-time="r.created_at" :show-time="false"></app-date-time></td>
<td> <td>
<app-dropdown hover v-if="isLoggedIn" class="is-right"> <app-dropdown hover v-if="appConfig.isLoggedIn" class="is-right">
<button slot="button" class="button is-small"> <template #button>
<button class="button is-small">
<app-icon icon="menu"></app-icon> <app-icon icon="menu"></app-icon>
</button> </button>
</template>
<div class="dropdown-item"> <div class="dropdown-item">
<router-link :to="{name: 'new_log', params: { recipeId: r.id } }" class="button is-primary is-fullwidth"> <router-link :to="{name: 'new_log', params: { recipeId: r.id } }" class="button is-primary is-fullwidth">
@ -83,113 +85,114 @@
</div> </div>
<app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager> <app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager>
<app-confirm :open="showConfirmRecipeDelete" :message="confirmRecipeDeleteMessage" :cancel="recipeDeleteCancel" :confirm="recipeDeleteConfirm"></app-confirm> <app-confirm :open="showConfirmRecipeDelete" title="Delete Recipe?" :message="confirmRecipeDeleteMessage" @cancel="recipeDeleteCancel" @confirm="recipeDeleteConfirm"></app-confirm>
</div> </div>
</template> </template>
<script> <script setup>
import { computed, reactive, ref, watch } from "vue";
import { useRouter } from 'vue-router'
import api from "../lib/Api"; import api from "../lib/Api";
import debounce from "lodash/debounce";
import { mapMutations, mapState } from "vuex";
import AppLoading from "./AppLoading"; import AppLoading from "./AppLoading";
import { useAppConfigStore } from "../stores/appConfig";
import { useMediaQueryStore } from "../stores/mediaQuery";
import { useLoadResource } from "../lib/useLoadResource";
export default { const appConfig = useAppConfigStore();
props: { const mediaQueries = useMediaQueryStore();
const { loadResource, localLoading } = useLoadResource();
const router = useRouter();
const props = defineProps({
searchQuery: { searchQuery: {
type: Object, type: Object,
required: false, required: false,
default: {} default: {}
} }
}, });
data() { const tableHeader = [
return {
recipeData: null,
recipeForDeletion: null
};
},
computed: {
...mapState([
"mediaQueries"
]),
search() {
return {
name: this.searchQuery.name || null,
tags: this.searchQuery.tags || null,
column: this.searchQuery.column || "created_at",
direction: this.searchQuery.direction || "desc",
page: this.searchQuery.page || 1,
per: this.searchQuery.per || 25
}
},
recipes() {
if (this.recipeData) {
return this.recipeData.recipes;
} else {
return [];
}
},
tableHeader() {
return [
{name: 'name', label: 'Name', sort: true}, {name: 'name', label: 'Name', sort: true},
{name: 'tags', label: 'Tags', sort: false}, {name: 'tags', label: 'Tags', sort: false},
{name: 'rating', label: 'Rating', sort: true}, {name: 'rating', label: 'Rating', sort: true},
{name: 'yields', label: 'Yields', sort: false}, {name: 'yields', label: 'Yields', sort: false},
{name: 'total_time', label: 'Time', sort: true}, {name: 'total_time', label: 'Time', sort: true},
{name: 'created_at', label: 'Created', sort: true} {name: 'created_at', label: 'Created', sort: true}
] ];
},
totalPages() { const recipeData = ref(null);
if (this.recipeData) { const recipeForDeletion = ref(null);
return this.recipeData.total_pages; const isTouch = computed(() => mediaQueries.touch);
const search = computed(() => ({
name: props.searchQuery.name || null,
tags: props.searchQuery.tags || null,
column: props.searchQuery.column || "created_at",
direction: props.searchQuery.direction || "desc",
page: props.searchQuery.page || 1,
per: props.searchQuery.per || 25
}));
const recipes = computed(() => {
if (recipeData.value) {
return recipeData.value.recipes;
} else {
return [];
}
});
const totalPages = computed(() => {
if (recipeData.value) {
return recipeData.value.total_pages;
} }
return 0; return 0;
}, });
currentPage() { const currentPage = computed(() => {
if (this.recipeData) { if (recipeData.value) {
return this.recipeData.current_page; return recipeData.value.current_page;
} }
return 0; return 0;
}, });
showConfirmRecipeDelete() { const showConfirmRecipeDelete = computed(() => recipeForDeletion.value !== null);
return this.recipeForDeletion !== null;
},
confirmRecipeDeleteMessage() { const confirmRecipeDeleteMessage = computed(() => {
if (this.showConfirmRecipeDelete) { if (showConfirmRecipeDelete.value) {
return `Are you sure you want to delete ${this.recipeForDeletion.name}?`; return `Are you sure you want to delete ${recipeForDeletion.value.name}?`;
} else { } else {
return "??"; return "??";
} }
});
watch(search, () => {
getList().then(() => appConfig.initialLoad = true);
}, {
deep: true,
immediate: true
});
function getList() {
return loadResource(
api.getRecipeList(search.value.page, search.value.per, search.value.column, search.value.direction, search.value.name, search.value.tags, data => recipeData.value = data)
);
} }
},
methods: {
...mapMutations([
"setInitialLoad"
]),
buildQueryParams() { function buildQueryParams() {
return { return {
name: this.searchQuery.name, name: props.searchQuery.name,
tags: this.searchQuery.tags, tags: props.searchQuery.tags,
column: this.searchQuery.column, column: props.searchQuery.column,
direction: this.searchQuery.direction, direction: props.searchQuery.direction,
page: this.searchQuery.page, page: props.searchQuery.page,
per: this.searchQuery.per per: props.searchQuery.per
}
} }
},
redirectToParams(params) { function redirectToParams(params) {
const rParams = {}; const rParams = {};
if (params.name) { if (params.name) {
@ -216,17 +219,17 @@
rParams.per = params.per; rParams.per = params.per;
} }
this.$router.push({name: 'recipeList', query: rParams}); router.push({name: 'recipeList', query: rParams});
}, }
changePage(idx) { function changePage(idx) {
const p = this.buildQueryParams(); const p = buildQueryParams();
p.page = idx; p.page = idx;
this.redirectToParams(p); redirectToParams(p);
}, }
setSort(col) { function setSort(col) {
const p = this.buildQueryParams(); const p = buildQueryParams();
if (p.column === col) { if (p.column === col) {
p.direction = p.direction === "desc" ? "asc" : "desc"; p.direction = p.direction === "desc" ? "asc" : "desc";
@ -234,53 +237,47 @@
p.column = col; p.column = col;
p.direction = "asc"; p.direction = "asc";
} }
this.redirectToParams(p); redirectToParams(p);
}, }
setSearchName(name) { function setSearchName(name) {
const p = this.buildQueryParams(); const p = buildQueryParams();
if (name !== p.name) { if (name !== p.name) {
p.name = name; p.name = name;
p.page = null; p.page = null;
this.redirectToParams(p); redirectToParams(p);
}
} }
},
setSearchTags(tags) { function setSearchTags(tags) {
const p = this.buildQueryParams(); const p = buildQueryParams();
if (tags !== p.tags) { if (tags !== p.tags) {
p.tags = tags; p.tags = tags;
p.page = null; p.page = null;
this.redirectToParams(p); redirectToParams(p);
}
} }
},
deleteRecipe(recipe) { function deleteRecipe(recipe) {
this.recipeForDeletion = recipe; recipeForDeletion.value = recipe;
}, }
recipeDeleteConfirm() { function recipeDeleteConfirm() {
if (this.recipeForDeletion !== null) { if (recipeForDeletion.value !== null) {
this.loadResource( loadResource(
api.deleteRecipe(this.recipeForDeletion.id).then(() => { api.deleteRecipe(recipeForDeletion.value.id).then(() => {
this.recipeForDeletion = null; recipeForDeletion.value = null;
return this.getList(); return getList();
}) })
); );
} }
}, }
recipeDeleteCancel() { function recipeDeleteCancel() {
this.recipeForDeletion = null; recipeForDeletion.value = null;
}, }
getList() { function formatRecipeTime(total, active) {
return this.loadResource(
api.getRecipeList(this.search.page, this.search.per, this.search.column, this.search.direction, this.search.name, this.search.tags, data => this.recipeData = data)
);
},
formatRecipeTime(total, active) {
let str = ""; let str = "";
if (total && total > 0) { if (total && total > 0) {
@ -297,24 +294,7 @@
return str; return str;
} }
},
created() {
this.$watch("search",
() => {
this.getList().then(() => this.setInitialLoad(true));
},
{
deep: true,
immediate: true
}
);
},
components: {
AppLoading
}
}
</script> </script>

View File

@ -22,15 +22,16 @@
</div> </div>
</template> </template>
<script> <script setup>
import api from "../lib/Api"; import { computed, onBeforeMount, ref } from "vue";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { mapActions, mapMutations, mapState } from "vuex"; import { useTaskStore } from "../stores/task";
import TaskListMiniForm from "./TaskListMiniForm"; import TaskListMiniForm from "./TaskListMiniForm";
import TaskListDropdownItem from "./TaskListDropdownItem"; import TaskListDropdownItem from "./TaskListDropdownItem";
import TaskItemList from "./TaskItemList"; import TaskItemList from "./TaskItemList";
import { useLoadResource } from "../lib/useLoadResource";
const newListTemplate = function() { const newListTemplate = function() {
return { return {
@ -38,85 +39,53 @@
}; };
}; };
export default { const { loadResource } = useLoadResource();
data() { const taskStore = useTaskStore();
return {
showListDropdown: false,
newList: newListTemplate(),
newListValidationErrors: {}
}
},
computed: { const showListDropdown = ref(false);
...mapState([ const newList = ref(newListTemplate());
'taskLists', const newListValidationErrors = ref({});
'currentTaskList'
]), const taskLists = computed(() => taskStore.taskLists);
listSelectLabel() { const currentTaskList = computed(() => taskStore.currentTaskList);
if (this.currentTaskList === null) { const listSelectLabel = computed(() => {
if (currentTaskList.value === null) {
return "Select or Create a List"; return "Select or Create a List";
} else { } else {
return this.currentTaskList.name; return currentTaskList.value.name;
} }
});
onBeforeMount(() => {
loadResource(taskStore.refreshTaskLists());
});
function selectList(list) {
taskStore.setCurrentTaskList(list);
showListDropdown.value = false;
} }
},
methods: { function saveNewList() {
...mapActions([ loadResource(
'refreshTaskLists', taskStore.createTaskList(newList.value)
'createTaskList', .then(() => showListDropdown.value = false)
'deleteTaskList', .then(() => { newList.value = newListTemplate(); newListValidationErrors.value = {}; } )
'deleteTaskItems', .catch(Errors.onlyFor(Errors.ApiValidationError, err => newListValidationErrors.value = err.validationErrors()))
'completeTaskItems'
]),
...mapMutations([
'setCurrentTaskList'
]),
selectList(list) {
this.setCurrentTaskList(list);
this.showListDropdown = false;
},
saveNewList() {
this.loadResource(
this.createTaskList(this.newList)
.then(() => this.showListDropdown = false)
.then(() => { this.newList = newListTemplate(); this.newListValidationErrors = {}; } )
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.newListValidationErrors = err.validationErrors()))
); );
}, }
deleteList(list) { function deleteList(list) {
this.loadResource( loadResource(taskStore.deleteTaskList(list));
this.deleteTaskList(list) }
);
},
function deleteAllItems() {
loadResource(
deleteAllItems() { taskStore.deleteTaskItems({
this.loadResource( taskList: currentTaskList.value,
this.deleteTaskItems({ taskItems: currentTaskList.value.task_items
taskList: this.currentTaskList,
taskItems: this.currentTaskList.task_items
}) })
); );
} }
},
created() {
this.loadResource(
this.refreshTaskLists()
);
},
components: {
TaskListMiniForm,
TaskListDropdownItem,
TaskItemList
}
}
</script> </script>

View File

@ -13,42 +13,38 @@
</div> </div>
</template> </template>
<script> <script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import UserEdit from "./UserEdit"; import UserEdit from "./UserEdit";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { useLoadResource } from "../lib/useLoadResource";
import { useCheckAuthentication } from "../lib/useCheckAuthentication";
export default { const { loadResource } = useLoadResource();
data() { const { checkAuthentication } = useCheckAuthentication(loadResource);
return { const router = useRouter();
validationErrors: {},
userObj: { const validationErrors = ref({});
const userObj = ref({
username: '', username: '',
full_name: '', full_name: '',
email: '', email: '',
password: '', password: '',
password_confirmation: '' password_confirmation: ''
} });
}
},
methods: { function save() {
save() { validationErrors.value = {};
this.validationErrors = {}; loadResource(
this.loadResource( api.postUser(userObj.value)
api.postUser(this.userObj) .then(() => checkAuthentication())
.then(() => this.checkAuthentication()) .then(() => router.push('/'))
.then(() => this.$router.push('/')) .catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
); );
} }
},
components: {
UserEdit
}
}
</script> </script>

View File

@ -13,62 +13,55 @@
</div> </div>
</template> </template>
<script> <script setup>
import { ref, watch } from "vue";
import { useRouter } from "vue-router";
import UserEdit from "./UserEdit"; import UserEdit from "./UserEdit";
import api from "../lib/Api"; import api from "../lib/Api";
import * as Errors from '../lib/Errors'; import * as Errors from '../lib/Errors';
import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
import { useCheckAuthentication } from "../lib/useCheckAuthentication";
export default { const appConfig = useAppConfigStore();
data() { const { loadResource } = useLoadResource();
return { const { checkAuthentication } = useCheckAuthentication(loadResource);
validationErrors: {}, const router = useRouter();
userObj: null
}
},
created() { const validationErrors = ref({});
this.refreshUser(); const userObj = ref(null);
},
watch: { watch(
user() { () => appConfig.user,
this.refreshUser(); () => refreshUser(),
} { immediate: true });
},
methods: { function refreshUser() {
refreshUser() { if (appConfig.user) {
if (this.user) { userObj.value = {
this.userObj = { username: appConfig.user.username,
username: this.user.username, full_name: appConfig.user.full_name,
full_name: this.user.full_name, email: appConfig.user.email,
email: this.user.email,
password: '', password: '',
password_confirmation: '' password_confirmation: ''
}; };
} else { } else {
this.userObj = null; userObj.value = null;
}
} }
},
save() { function save() {
this.validationErrors = {}; validationErrors.value = {};
this.loadResource( loadResource(
api.patchUser(this.userObj) api.patchUser(userObj.value)
.then(() => this.checkAuthentication()) .then(() => checkAuthentication())
.then(() => { .then(() => {
this.$router.push('/'); router.push('/');
}) })
.catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors())) .catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
); );
} }
},
components: {
UserEdit
}
}
</script> </script>

View File

@ -3,21 +3,19 @@
<app-text-field label="Username" v-model="userObj.username"></app-text-field> <app-text-field label="Username" v-model="userObj.username"></app-text-field>
<app-text-field label="Name" v-model="userObj.full_name"></app-text-field> <app-text-field label="Name" v-model="userObj.full_name"></app-text-field>
<app-text-field label="Email" v-model="userObj.email"></app-text-field> <app-text-field label="Email" v-model="userObj.email"></app-text-field>
<app-text-field label="Password" v-model="userObj.password"></app-text-field> <app-text-field type="password" label="Password" v-model="userObj.password"></app-text-field>
<app-text-field label="Password Confirmation" v-model="userObj.password_confirmation"></app-text-field> <app-text-field type="password" label="Password Confirmation" v-model="userObj.password_confirmation"></app-text-field>
</div> </div>
</template> </template>
<script> <script setup>
export default { const props = defineProps({
props: {
userObj: { userObj: {
required: true, required: true,
type: Object type: Object
} }
} });
}
</script> </script>

View File

@ -34,7 +34,7 @@
<button type="submit" class="button is-primary" :disabled="!enableSubmit">Login</button> <button type="submit" class="button is-primary" :disabled="!enableSubmit">Login</button>
</div> </div>
<div class="control"> <div class="control">
<button class="button is-secondary" @click="showLogin = false">Cancel</button> <button type="button" class="button is-secondary" @click="showLogin = false">Cancel</button>
</div> </div>
</div> </div>
@ -45,59 +45,46 @@
</div> </div>
</template> </template>
<script> <script setup>
import api from "../lib/Api"; import { computed, nextTick, ref, useTemplateRef } from "vue";
import { mapActions, mapState } from "vuex"; import { useAppConfigStore } from "../stores/appConfig";
import { useLoadResource } from "../lib/useLoadResource";
export default { const appConfig = useAppConfigStore();
data() { const { loadResource } = useLoadResource();
return {
showLogin: false,
error: '',
username: '',
password: ''
};
},
computed: { const userNameElement = useTemplateRef("usernameInput");
...mapState([
'loginMessage' const showLogin = ref(false);
]), const error = ref('');
enableSubmit() { const username = ref("");
return this.username !== '' && this.password !== '' && !this.isLoading; const password = ref("");
const loginMessage = computed(() => appConfig.loginMessage);
const enableSubmit = computed(() => username.value !== "" && password.value !== "" && !appConfig.isLoading);
function openDialog() {
showLogin.value = true;
nextTick(() => {
userNameElement.value.focus();
})
} }
},
methods: { function performLogin() {
...mapActions([ if (username.value !== '' && password.value !== '') {
'login' const params = {username: username.value, password: password.value};
]),
openDialog() { loadResource(
this.showLogin = true; appConfig.login(params)
this.$nextTick(() => this.$refs.usernameInput.focus());
},
performLogin() {
if (this.username !== '' && this.password !== '') {
const params = {username: this.username, password: this.password};
this.loadResource(
this.login(params)
.then(data => { .then(data => {
if (data.success) { if (data.success) {
this.showLogin = false; showLogin.value = false;
} }
}) })
); );
} }
} }
},
components: {
}
}
</script> </script>

View File

@ -1,4 +1,4 @@
import config from '../config'; import config from './config';
import * as Errors from './Errors'; import * as Errors from './Errors';
class Api { class Api {

View File

@ -0,0 +1,35 @@
function clickStrikeClick(evt) {
const isStrikable = el => el && el.tagName === "LI";
const strikeClass = "is-strikethrough";
let t = evt.target;
while (t !== null && t !== this && !isStrikable(t)) {
t = t.parentElement;
}
if (isStrikable(t)) {
const classList = t.className.split(" ");
const strIdx = classList.findIndex(c => c === strikeClass);
if (strIdx >= 0) {
classList.splice(strIdx, 1);
} else {
classList.push(strikeClass);
}
t.className = classList.join(" ");
}
}
export function installClickStrike(app) {
app.directive('click-strike', {
beforeMount(el) {
el.addEventListener("click", clickStrikeClick);
},
unmounted(el) {
el.removeEventListener("click", clickStrikeClick);
}
});
}

View File

@ -1,84 +0,0 @@
import Vue from 'vue';
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex';
import api from "../lib/Api";
Vue.mixin({
data() {
return {
localLoadingCount: 0
};
},
computed: {
...mapGetters([
"isLoading",
"isLoggedIn",
"isAdmin"
]),
...mapState([
"user"
]),
localLoading() {
return this.localLoadingCount > 0;
}
},
methods: {
...mapActions([
'updateCurrentUser'
]),
...mapMutations([
'setError',
'setLoading'
]),
loadResource(promise) {
this.setLoading(true);
this.localLoadingCount = this.localLoadingCount + 1;
return promise
.catch(err => this.setError(err))
.then(res => {
this.setLoading(false);
this.localLoadingCount = this.localLoadingCount - 1;
return res;
});
},
checkAuthentication() {
return this.loadResource(this.updateCurrentUser());
}
}
});
function clickStrikeClick(evt) {
const isStrikable = el => el && el.tagName === "LI";
const strikeClass = "is-strikethrough";
let t = evt.target;
while (t !== null && t !== this && !isStrikable(t)) {
t = t.parentElement;
}
if (isStrikable(t)) {
const classList = t.className.split(" ");
const strIdx = classList.findIndex(c => c === strikeClass);
if (strIdx >= 0) {
classList.splice(strIdx, 1);
} else {
classList.push(strikeClass);
}
t.className = classList.join(" ");
}
}
Vue.directive('click-strike', {
bind(el) {
el.addEventListener("click", clickStrikeClick);
},
unbind(el) {
el.removeEventListener("click", clickStrikeClick);
}
});

View File

@ -1,4 +1,6 @@
import { useAppConfigStore } from '../stores/appConfig';
function trackInstall(worker, cb) { function trackInstall(worker, cb) {
worker.addEventListener('statechange', function() { worker.addEventListener('statechange', function() {
if (worker.state == 'installed') { if (worker.state == 'installed') {
@ -18,7 +20,9 @@ function trackActive(worker, cb) {
export function swUpdate() { export function swUpdate() {
navigator.serviceWorker.getRegistration().then(reg => { navigator.serviceWorker.getRegistration().then(reg => {
if (reg && reg.waiting) { if (reg && reg.waiting) {
trackActive(reg.waiting, () => window.location.reload(true)); trackActive(reg.waiting, () => {
window.location.reload(true)
});
reg.waiting.postMessage("skipWaiting"); reg.waiting.postMessage("skipWaiting");
} else { } else {
window.location.reload(true); window.location.reload(true);
@ -27,10 +31,17 @@ export function swUpdate() {
} }
export function swInit(store) { export function swInit() {
const updateReady = () => store.commit("setUpdateAvailable", true); const updateReady = () => {
const clearUpdateReady = () => store.commit("setUpdateAvailable", false); const store = useAppConfigStore();
store.updateAvailable = true;
};
const clearUpdateReady = () => {
const store = useAppConfigStore();
store.updateAvailable = false;
}
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js') navigator.serviceWorker.register('/sw.js')
@ -53,6 +64,4 @@ export function swInit(store) {
console.log('Registration failed with ' + error); console.log('Registration failed with ' + error);
}); });
} }
} }

View File

@ -1,49 +0,0 @@
// Adds a module to a vuex store with a set of media query states
const defaultOptions = {
module: "mediaQueries"
};
// Hard coded values taken directly from Bulma css
const mobileBp = 768;
const desktopBp = 1024;
const widscreenBp = 1216;
const fullHdBp = 1408;
const mediaQueries = {
mobile: `screen and (max-width: ${mobileBp}px)`,
tablet: `screen and (min-width: ${mobileBp + 1}px)`,
tabletOnly: `screen and (min-width: ${mobileBp + 1}px) and (max-width: ${desktopBp - 1}px)`,
touch: `screen and (max-width: ${desktopBp - 1}px)`,
desktop: `screen and (min-width: ${desktopBp}px)`,
desktopOnly: `screen and (min-width: ${desktopBp}px) and (max-width: ${widscreenBp - 1}px)`,
widescreen: `screen and (min-width: ${widscreenBp}px)`,
widescreenOnly: `screen and (min-width: ${widscreenBp}px) and (max-width: ${fullHdBp - 1}px)`,
fullhd: `screen and (min-width: ${fullHdBp}px)`
};
export default function(store, options) {
let opts = Object.assign({}, defaultOptions, options || {});
const moduleName = opts.module;
const initialState = {};
for (let device in mediaQueries) {
const query = window.matchMedia(mediaQueries[device]);
query.onchange = (q) => {
store.commit(moduleName + "/MEDIA_QUERY_CHANGED", {mediaName: device, value: q.matches});
};
initialState[device] = query.matches;
}
store.registerModule(moduleName, {
namespaced: true,
state: initialState,
mutations: {
"MEDIA_QUERY_CHANGED" (state, data) {
state[data.mediaName] = data.value;
}
}
});
}

View File

@ -0,0 +1,9 @@
import { onBeforeUnmount } from "vue";
import autosize from 'autosize';
export function useAutosize(elementRef) {
autosize(elementRef.value);
onBeforeUnmount(() => {
autosize.destroy(elementRef.value);
});
}

View File

@ -0,0 +1,12 @@
import { useAppConfigStore } from "../stores/appConfig";
export function useCheckAuthentication(loadResource) {
const appConfig = useAppConfigStore();
const checkAuthentication = function() {
return loadResource(appConfig.updateCurrentUser());
}
return {
checkAuthentication
}
}

View File

@ -0,0 +1,10 @@
import { Group } from '@tweenjs/tween.js'
let group = null;
export function useGlobalTweenGroup() {
if (group === null) {
group = new Group();
}
return group;
}

View File

@ -0,0 +1,27 @@
import { computed, ref } from "vue";
import { useAppConfigStore } from "../stores/appConfig";
export function useLoadResource() {
const appConfig = useAppConfigStore();
const localLoadingCount = ref(0);
const localLoading = computed(() => localLoadingCount.value > 0);
const loadResource = async (promise) => {
appConfig.setLoading(true);
localLoadingCount.value = localLoadingCount.value + 1;
try {
return await promise;
} catch (error) {
appConfig.setError(error);
} finally {
appConfig.setLoading(false);
localLoadingCount.value = localLoadingCount.value - 1;
}
};
return {
loadResource,
localLoading,
localLoadingCount
};
}

View File

@ -1,18 +1,10 @@
import '../styles'; import '../styles';
import "vue-resize/dist/vue-resize"; import { createApp } from 'vue';
import { createPinia } from 'pinia';
import Vue from 'vue'
import { sync } from 'vuex-router-sync';
import { swInit } from "../lib/ServiceWorker"; import { swInit } from "../lib/ServiceWorker";
import responsiveSync from "../lib/VuexResponsiveSync"; import config from '../lib/config';
import { createChannel } from "../lib/ActionCable"; import { installClickStrike } from "../lib/ClickStrike";
import VueProgressBar from "vue-progressbar";
import VueResize from "vue-resize";
import config from '../config';
import store from '../store';
import router from '../router'; import router from '../router';
import '../lib/GlobalMixins';
import App from '../components/App';
import AppAutocomplete from "../components/AppAutocomplete"; import AppAutocomplete from "../components/AppAutocomplete";
import AppConfirm from "../components/AppConfirm"; import AppConfirm from "../components/AppConfirm";
@ -31,61 +23,40 @@ import AppTagEditor from "../components/AppTagEditor";
import AppTextField from "../components/AppTextField"; import AppTextField from "../components/AppTextField";
import AppValidationErrors from "../components/AppValidationErrors"; import AppValidationErrors from "../components/AppValidationErrors";
Vue.component("AppAutocomplete", AppAutocomplete); import App from '../components/App.vue'
Vue.component("AppConfirm", AppConfirm);
Vue.component("AppDateTime", AppDateTime);
Vue.component("AppDatePicker", AppDatePicker);
Vue.component("AppDropdown", AppDropdown);
Vue.component("AppExpandTransition", AppExpandTransition);
Vue.component("AppIcon", AppIcon);
Vue.component("AppIconicIcon", AppIconicIcon);
Vue.component("AppModal", AppModal);
Vue.component("AppNavbar", AppNavbar);
Vue.component("AppPager", AppPager);
Vue.component("AppRating", AppRating);
Vue.component("AppSearchText", AppSearchText);
Vue.component("AppTagEditor", AppTagEditor);
Vue.component("AppTextField", AppTextField);
Vue.component("AppValidationErrors", AppValidationErrors);
// Resize?
Vue.use(VueProgressBar, { // Progressbar?
// color: '#bffaf3',
// failedColor: '#874b4b',
// thickness: '5px',
// transition: {
// speed: '0.2s',
// opacity: '0.6s',
// termination: 300
// },
// autoRevert: true,
// location: 'left',
// inverse: false
});
Vue.use(VueResize);
sync(store, router);
responsiveSync(store);
Vue.prototype.$createChannel = function(...args) {
createChannel(null, ...args);
}
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const appElement = document.getElementById('app');
if (!appElement) { return; }
const app = document.getElementById('app'); config.baseApiUrl = appElement.dataset.url;
config.baseApiUrl = app.dataset.url;
window.$vm = new Vue({
el: '#app',
store,
router,
render: createElement => createElement('App'),
mounted() {
this.$nextTick(() => swInit(store));
},
components: { App }
});
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.use(router);
swInit();
installClickStrike(app);
app.component("AppAutocomplete", AppAutocomplete);
app.component("AppConfirm", AppConfirm);
app.component("AppDateTime", AppDateTime);
app.component("AppDatePicker", AppDatePicker);
app.component("AppDropdown", AppDropdown);
app.component("AppExpandTransition", AppExpandTransition);
app.component("AppIcon", AppIcon);
app.component("AppIconicIcon", AppIconicIcon);
app.component("AppModal", AppModal);
app.component("AppNavbar", AppNavbar);
app.component("AppPager", AppPager);
app.component("AppRating", AppRating);
app.component("AppSearchText", AppSearchText);
app.component("AppTagEditor", AppTagEditor);
app.component("AppTextField", AppTextField);
app.component("AppValidationErrors", AppValidationErrors);
app.mount(appElement);
}); });

View File

@ -1,53 +1,39 @@
import Vue from 'vue'; import { createRouter, createWebHashHistory } from "vue-router";
import Router from 'vue-router'; import { nextTick } from "vue";
import The404Page from './components/The404Page'; import The404Page from '../components/The404Page';
import TheAboutPage from './components/TheAboutPage'; import TheAboutPage from '../components/TheAboutPage';
import TheCalculator from './components/TheCalculator'; import TheCalculator from '../components/TheCalculator';
import TheLog from './components/TheLog'; import TheLog from '../components/TheLog';
import TheLogList from './components/TheLogList'; import TheLogList from '../components/TheLogList';
import TheLogCreator from './components/TheLogCreator'; import TheLogCreator from '../components/TheLogCreator';
import TheLogEditor from './components/TheLogEditor'; import TheLogEditor from '../components/TheLogEditor';
import TheFoodList from './components/TheFoodList'; import TheFoodList from '../components/TheFoodList';
import TheFood from "./components/TheFood"; import TheFood from "../components/TheFood";
import TheFoodEditor from "./components/TheFoodEditor"; import TheFoodEditor from "../components/TheFoodEditor";
import TheFoodCreator from "./components/TheFoodCreator"; import TheFoodCreator from "../components/TheFoodCreator";
import TheNotesList from './components/TheNotesList'; import TheNotesList from '../components/TheNotesList';
import TheRecipe from './components/TheRecipe'; import TheRecipe from '../components/TheRecipe';
import TheRecipeEditor from './components/TheRecipeEditor'; import TheRecipeEditor from '../components/TheRecipeEditor';
import TheRecipeCreator from './components/TheRecipeCreator'; import TheRecipeCreator from '../components/TheRecipeCreator';
import TheRecipeList from './components/TheRecipeList'; import TheRecipeList from '../components/TheRecipeList';
import TheTaskListList from './components/TheTaskListList'; import TheTaskListList from '../components/TheTaskListList';
import TheUserCreator from './components/TheUserCreator'; import TheUserCreator from '../components/TheUserCreator';
import TheUserEditor from './components/TheUserEditor'; import TheUserEditor from '../components/TheUserEditor';
import TheAdminUserList from './components/TheAdminUserList'; import TheAdminUserList from '../components/TheAdminUserList';
import TheAdminUserEditor from './components/TheAdminUserEditor'; import TheAdminUserEditor from '../components/TheAdminUserEditor';
import $store from './store'; import { useAppConfigStore } from "../stores/appConfig";
Vue.use(Router);
const router = new Router({ const router = createRouter({
routes: [] history: createWebHashHistory(),
}); routes: [
router.afterEach((to, from) => {
if (to.meta.handleInitialLoad !== true && $store.state.initialLoad === false) {
$store.commit("setInitialLoad", true);
}
Vue.nextTick(() => {
document.title = to.meta.title || 'Parsley';
});
});
router.addRoutes(
[
{ {
path: '/', path: '/',
redirect: '/recipes' redirect: '/recipes'
@ -148,10 +134,10 @@ router.addRoutes(
{ {
path: "/logout", path: "/logout",
name: "logout", name: "logout",
beforeEnter: (to, from, next) => { beforeEnter: async (to, from, next) => {
const $store = router.app.$store; const appConfig = useAppConfigStore();
$store.dispatch("logout") await appConfig.logout();
.then(() => next("/")); return next("/");
} }
}, },
@ -179,10 +165,22 @@ router.addRoutes(
}, },
{ {
path: '*', path: '/:pathMatch(.*)*',
name: 'NotFound',
component: The404Page component: The404Page
} }
] ]
); });
router.afterEach((to, from) => {
const appConfigStore = useAppConfigStore();
if (to.meta.handleInitialLoad !== true && appConfigStore.initialLoad === false) {
appConfigStore.initialLoad = true;
}
nextTick(() => {
document.title = to.meta.title || 'Parsley';
});
});
export default router; export default router;

View File

@ -1,218 +0,0 @@
import Vue from 'vue'
import Vuex from 'vuex'
import api from '../lib/Api';
import { createChannel } from '../lib/ActionCable';
Vue.use(Vuex);
let taskChannel = null;
export default new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: {
initialLoad: false,
updateAvailable: false,
loadingCount: 0,
error: null,
authChecked: false,
user: null,
loginMessage: null,
taskLists: [],
currentTaskList: null,
nutrientList: {
kcal: { label: "Calories", unit: "kcal" },
protein: { label: "Protein", unit: "g" },
lipids: { label: "Fat", unit: "g" },
carbohydrates: { label: "Carbohydrates", unit: "g" },
water: { label: "Water", unit: "g" },
sugar: { label: "Sugar", unit: "g" },
fiber: { label: "Fiber", unit: "g" },
cholesterol: { label: "Cholesterol", unit: "mg" },
sodium: { label: "Sodium", unit: "mg" },
calcium: { label: "Calcium", unit: "mg" },
iron: { label: "Iron", unit: "mg" },
magnesium: { label: "Magnesium", unit: "mg" },
phosphorus: { label: "Phosphorus", unit: "mg" },
potassium: { label: "Potassium", unit: "mg" },
zinc: { label: "Zinc", unit: "mg" },
copper: { label: "Copper", unit: "mg" },
manganese: { label: "Manganese", unit: "mg" },
vit_a: { label: "Vitamin A", unit: "μg" },
vit_b6: { label: "Vitamin B6", unit: "mg" },
vit_b12: { label: "Vitamin B12", unit: "μg" },
vit_c: { label: "Vitamin C", unit: "mg" },
vit_d: { label: "Vitamin D", unit: "μg" },
vit_e: { label: "Vitamin E", unit: "mg" },
vit_k: { label: "Vitamin K", unit: "μg" },
ash: { label: "ash", unit: "g" }
}
},
getters: {
isLoading(state) {
return state.loadingCount > 0;
},
isLoggedIn(state) {
return state.user !== null;
},
isAdmin(state) {
return state.user !== null && state.user.admin === true;
}
},
mutations: {
setUpdateAvailable(state, value) {
state.updateAvailable = value;
},
setInitialLoad(state, value) {
state.initialLoad = value;
},
setLoading(state, value) {
if (value) {
state.loadingCount = state.loadingCount + 1;
} else {
state.loadingCount = state.loadingCount - 1;
}
state.loading = state.loadingCount !== 0;
},
setError(state, value) {
console.log(value);
state.error = value;
},
setUser(state, user) {
state.authChecked = true;
state.user = user;
},
setLoginMessage(state, msg) {
state.loginMessage = msg;
},
setTaskLists(state, lists) {
state.taskLists = lists || [];
},
setCurrentTaskList(state, list) {
state.currentTaskList = list || null;
},
replaceTaskList(state, list) {
if (state.taskLists) {
const listIdx = state.taskLists.findIndex(l => l.id === list.id);
if (listIdx >= 0) {
state.taskLists.splice(listIdx, 1, list);
}
if (state.currentTaskList && state.currentTaskList.id === list.id) {
state.currentTaskList = list;
}
}
}
},
actions: {
updateCurrentUser({commit}) {
return api.getCurrentUser()
.then(user => {
commit("setUser", user);
return user;
});
},
login({commit}, authData) {
return api.postLogin(authData.username, authData.password)
.then(data => {
if (data.success) {
commit("setUser", data.user);
commit("setLoginMessage", null);
} else {
commit("setUser", null);
commit("setLoginMessage", data.message);
}
return data;
});
},
logout({commit}) {
return api.getLogout()
.then(() => {
commit("setUser", null);
});
},
refreshTaskLists({commit, dispatch, state}) {
const cb = function(data) {
commit("setTaskLists", data);
let ctl = null;
if (state.currentTaskList) {
ctl = data.find(l => l.id === state.currentTaskList.id);
}
ctl = ctl || data[0] || null;
commit("setCurrentTaskList", ctl);
dispatch('ensureTaskListChannel');
};
return api.getTaskLists(cb)
},
ensureTaskLists({dispatch, state}) {
if (state.user && state.taskLists.length === 0) {
return dispatch("refreshTaskLists");
} else {
return Promise.resolve();
}
},
ensureTaskListChannel({ commit }) {
if (taskChannel === null) {
taskChannel = createChannel(null, "TaskChannel", {
received(data) {
if (data && data.action === 'updated') {
commit('replaceTaskList', data.task_list);
}
}
});
}
},
createTaskList({commit, dispatch}, newList) {
return api.postTaskList(newList)
.then(data => commit("setCurrentTaskList", data))
.then(() => dispatch("refreshTaskLists"))
},
deleteTaskList({dispatch}, taskList) {
return api.deleteTaskList(taskList)
.then(() => dispatch("refreshTaskLists"));
},
createTaskItem({commit, dispatch}, taskItem) {
return api.postTaskItem(taskItem.task_list_id, taskItem)
.then(data => {
return data;
});
},
updateTaskItem({commit}, taskItem) {
return api.patchTaskItem(taskItem.task_list_id, taskItem)
.then(data => {
return data;
});
},
deleteTaskItems({commit}, payload) {
return api.deleteTaskItems(payload.taskList.id, payload.taskItems);
},
completeTaskItems({commit}, payload) {
return api.completeTaskItems(payload.taskList.id, payload.taskItems, !payload.completed);
}
}
});

View File

@ -0,0 +1,102 @@
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { useRoute } from "vue-router";
import api from "../lib/Api";
export const useAppConfigStore = defineStore('appConfig', () => {
const authChecked = ref(false);
const errorObject = ref(null);
const initialLoad = ref(false);
const loadingCount = ref(0);
const loginMessage = ref(null);
const updateAvailable = ref(false);
const userObject = ref(null);
const route = useRoute();
const isLoading = computed(() => {
return loadingCount.value > 0;
});
const isLoggedIn = computed(() => {
return userObject.value !== null;
});
const isAdmin = computed(() => {
return userObject.value?.admin === true;
});
const error = computed({
get: () => errorObject.value,
set: (val) => {
console.log(val);
errorObject.value = val;
}
});
const user = computed({
get: () => userObject.value,
set: (val) => {
userObject.value = val;
authChecked.value = true;
}
});
function setError(value) {
error.value = value;
}
function setLoading(value) {
if (value) {
loadingCount.value = loadingCount.value + 1;
} else {
loadingCount.value = loadingCount.value - 1;
}
}
async function updateCurrentUser() {
user.value = await api.getCurrentUser();
return user.value;
}
function login(authData) {
return api.postLogin(authData.username, authData.password)
.then(data => {
if (data.success) {
user.value = data.user;
loginMessage.value = null;
} else {
user.value = null;
loginMessage.value = data.message;
}
return data;
});
}
function logout() {
return api.getLogout()
.then(() => {
user.value = null;
});
}
return {
authChecked,
error,
initialLoad,
loadingCount,
loginMessage,
updateAvailable,
user,
route,
isAdmin,
isLoading,
isLoggedIn,
login,
logout,
setError,
setLoading,
updateCurrentUser
};
});

View File

@ -0,0 +1,35 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useMediaQueryStore = defineStore('mediaQuery', () => {
// Hard coded values taken directly from Bulma css
const mobileBp = 768;
const desktopBp = 1024;
const widscreenBp = 1216;
const fullHdBp = 1408;
const mediaQueries = {
mobile: `screen and (max-width: ${mobileBp}px)`,
tablet: `screen and (min-width: ${mobileBp + 1}px)`,
tabletOnly: `screen and (min-width: ${mobileBp + 1}px) and (max-width: ${desktopBp - 1}px)`,
touch: `screen and (max-width: ${desktopBp - 1}px)`,
desktop: `screen and (min-width: ${desktopBp}px)`,
desktopOnly: `screen and (min-width: ${desktopBp}px) and (max-width: ${widscreenBp - 1}px)`,
widescreen: `screen and (min-width: ${widscreenBp}px)`,
widescreenOnly: `screen and (min-width: ${widscreenBp}px) and (max-width: ${fullHdBp - 1}px)`,
fullhd: `screen and (min-width: ${fullHdBp}px)`
};
const store = {};
for (let device in mediaQueries) {
const query = window.matchMedia(mediaQueries[device]);
store[device] = ref(query.matches);
query.onchange = (q) => {
store[device].value = q.matches;
};
}
return store;
});

View File

@ -0,0 +1,36 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useNutrientStore = defineStore('nutrient', () => {
const nutrientList = ref({
kcal: { label: "Calories", unit: "kcal" },
protein: { label: "Protein", unit: "g" },
lipids: { label: "Fat", unit: "g" },
carbohydrates: { label: "Carbohydrates", unit: "g" },
water: { label: "Water", unit: "g" },
sugar: { label: "Sugar", unit: "g" },
fiber: { label: "Fiber", unit: "g" },
cholesterol: { label: "Cholesterol", unit: "mg" },
sodium: { label: "Sodium", unit: "mg" },
calcium: { label: "Calcium", unit: "mg" },
iron: { label: "Iron", unit: "mg" },
magnesium: { label: "Magnesium", unit: "mg" },
phosphorus: { label: "Phosphorus", unit: "mg" },
potassium: { label: "Potassium", unit: "mg" },
zinc: { label: "Zinc", unit: "mg" },
copper: { label: "Copper", unit: "mg" },
manganese: { label: "Manganese", unit: "mg" },
vit_a: { label: "Vitamin A", unit: "μg" },
vit_b6: { label: "Vitamin B6", unit: "mg" },
vit_b12: { label: "Vitamin B12", unit: "μg" },
vit_c: { label: "Vitamin C", unit: "mg" },
vit_d: { label: "Vitamin D", unit: "μg" },
vit_e: { label: "Vitamin E", unit: "mg" },
vit_k: { label: "Vitamin K", unit: "μg" },
ash: { label: "ash", unit: "g" }
});
return {
nutrientList
};
});

View File

@ -0,0 +1,114 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useAppConfigStore } from "./appConfig";
import api from "../lib/Api";
import { createChannel } from "../lib/ActionCable";
export const useTaskStore = defineStore('task', () => {
const taskLists = ref([]);
const currentTaskList = ref(null);
let taskChannel = null;
function replaceTaskList(list) {
if (taskLists.value) {
const listIdx = taskLists.value.findIndex(l => l.id === list.id);
if (listIdx >= 0) {
taskLists.value.splice(listIdx, 1, list);
}
if (currentTaskList.value && currentTaskList.value.id === list.id) {
currentTaskList.value = list;
}
}
}
function ensureTaskListChannel() {
if (taskChannel === null) {
taskChannel = createChannel(null, "TaskChannel", {
received(data) {
if (data && data.action === 'updated') {
replaceTaskList(data.task_list);
}
}
});
}
}
function refreshTaskLists() {
const cb = function(data) {
taskLists.value = data || [];
let ctl = null;
if (currentTaskList.value) {
ctl = data.find(l => l.id === currentTaskList.value.id);
}
ctl = ctl || data[0] || null;
setCurrentTaskList(ctl);
ensureTaskListChannel();
};
return api.getTaskLists(cb)
}
function ensureTaskLists() {
const appConfig = useAppConfigStore();
if (appConfig.user && taskLists.value.length === 0) {
return refreshTaskLists();
} else {
return Promise.resolve();
}
}
function setCurrentTaskList(taskList) {
currentTaskList.value = taskList || null;
}
async function createTaskList(newList) {
currentTaskList.value = await api.postTaskList(newList);
return refreshTaskLists();
}
async function deleteTaskList(taskList) {
await api.deleteTaskList(taskList);
return refreshTaskLists();
}
function createTaskItem(taskItem) {
return api.postTaskItem(taskItem.task_list_id, taskItem)
.then(data => {
return data;
});
}
function updateTaskItem(taskItem) {
return api.patchTaskItem(taskItem.task_list_id, taskItem)
.then(data => {
return data;
});
}
function deleteTaskItems(payload) {
return api.deleteTaskItems(payload.taskList.id, payload.taskItems);
}
function completeTaskItems(payload) {
return api.completeTaskItems(payload.taskList.id, payload.taskItems, !payload.completed);
}
return {
currentTaskList,
taskLists,
createTaskList,
deleteTaskList,
ensureTaskLists,
refreshTaskLists,
setCurrentTaskList,
createTaskItem,
updateTaskItem,
deleteTaskItems,
completeTaskItems
};
});

View File

@ -1,107 +1,97 @@
@mixin responsive-button-size($size) { @use "bulma/sass/utilities" as bulma;
&.is-small-#{$size} { @use "bulma/sass/utilities/controls";
@include button-small; @use "bulma/sass/utilities/mixins";
}
&.is-medium-#{$size} {
@include button-medium;
}
&.is-large-#{$size} {
@include button-large;
}
}
@mixin responsive-label-size($size) { @mixin responsive-label-size($size) {
&.is-small-#{$size} { &.is-small-#{$size} {
font-size: $size-small; font-size: bulma.$size-small;
} }
&.is-medium-#{$size} { &.is-medium-#{$size} {
font-size: $size-medium; font-size: bulma.$size-medium;
} }
&.is-large-#{$size} { &.is-large-#{$size} {
font-size: $size-large; font-size: bulma.$size-large;
} }
} }
@mixin responsive-control-size($size) { @mixin responsive-control-size($size) {
&.is-small-#{$size} { &.is-small-#{$size} {
@include control-small; @include controls.control-small;
} }
&.is-medium-#{$size} { &.is-medium-#{$size} {
@include control-medium; @include controls.control-medium;
} }
&.is-large-#{$size} { &.is-large-#{$size} {
@include control-large; @include controls.control-large;
} }
} }
.button { .button {
@include mobile { @include mixins.mobile {
@include responsive-button-size("mobile"); @include responsive-control-size("mobile");
} }
@include tablet { @include mixins.tablet {
@include responsive-button-size("tablet"); @include responsive-control-size("tablet");
} }
@include desktop { @include mixins.desktop {
@include responsive-button-size("desktop"); @include responsive-control-size("desktop");
} }
@include widescreen { @include mixins.widescreen {
@include responsive-button-size("widescreen"); @include responsive-control-size("widescreen");
} }
@include fullhd { @include mixins.fullhd {
@include responsive-button-size("fullhd"); @include responsive-control-size("fullhd");
} }
} }
.label { .label {
@include mobile { @include mixins.mobile {
@include responsive-label-size("mobile"); @include responsive-label-size("mobile");
} }
@include tablet { @include mixins.tablet {
@include responsive-label-size("tablet"); @include responsive-label-size("tablet");
} }
@include desktop { @include mixins.desktop {
@include responsive-label-size("desktop"); @include responsive-label-size("desktop");
} }
@include widescreen { @include mixins.widescreen {
@include responsive-label-size("widescreen"); @include responsive-label-size("widescreen");
} }
@include fullhd { @include mixins.fullhd {
@include responsive-label-size("fullhd"); @include responsive-label-size("fullhd");
} }
} }
.input, .textarea { .input, .textarea {
@include mobile { @include mixins.mobile {
@include responsive-control-size("mobile"); @include responsive-control-size("mobile");
} }
@include tablet { @include mixins.tablet {
@include responsive-control-size("tablet"); @include responsive-control-size("tablet");
} }
@include desktop { @include mixins.desktop {
@include responsive-control-size("desktop"); @include responsive-control-size("desktop");
} }
@include widescreen { @include mixins.widescreen {
@include responsive-control-size("widescreen"); @include responsive-control-size("widescreen");
} }
@include fullhd { @include mixins.fullhd {
@include responsive-control-size("fullhd"); @include responsive-control-size("fullhd");
} }
} }

View File

@ -1,35 +0,0 @@
// coolors.co pallet
$coolors-dark: rgba(29, 30, 24, 1);
$coolors-blue: rgba(67, 127, 151, 1);
$coolors-green: rgba(121, 167, 54, 1);
$coolors-red: #ab4c34;
$coolors-yellow: rgba(240, 162, 2, 1);
//$family-sans-serif: "Verdana", "Helvetica Neue", "Helvetica", "Arial", sans-serif !default
$family-serif: Georgia, "Times New Roman", Times, serif;
// Bluma default overrides
//$green: #79A736;
//$red: #d4424e;
//$blue: #9c36a7;
$green: $coolors-green;
$blue: $coolors-blue;
$red: $coolors-red;
$yellow: $coolors-yellow;
$dark: $coolors-dark;
$primary: $green;
$family-primary: $family-serif;
$modal-content-width: 750px;
// Make all Bulma variables and functions available
@import "~bulma/sass/utilities/initial-variables";
@import "~bulma/sass/utilities/functions";
@import "~bulma/sass/utilities/derived-variables";
//$dropdown-item-hover-background-color: $white-ter;

View File

@ -1,5 +1,9 @@
@include until($desktop) { @use "bulma/sass/utilities" as bulma;
@use "bulma/sass/utilities/mixins";
@include mixins.until(bulma.$desktop) {
.modal.is-wide { .modal.is-wide {
.modal-content, .modal-card { .modal-content, .modal-card {
margin: 0 20px; margin: 0 20px;
@ -8,7 +12,7 @@
} }
} }
@include from($desktop) { @include mixins.from(bulma.$desktop) {
.modal.is-wide { .modal.is-wide {
.modal-content, .modal-card { .modal-content, .modal-card {
margin: 0 auto; margin: 0 auto;

View File

@ -1,18 +1,22 @@
@import "./variables"; // coolors.co pallet
$coolors-dark: rgba(29, 30, 24, 1);
$coolors-blue: rgba(67, 127, 151, 1);
$coolors-green: rgba(121, 167, 54, 1);
$coolors-red: #ab4c34;
$coolors-yellow: rgba(240, 162, 2, 1);
@import "~bulma/sass/utilities/_all"; $family-serif: Georgia, "Times New Roman", Times, serif;
@import "~bulma/sass/base/_all";
@import "~bulma/sass/components/dropdown"; @use "bulma/sass" as bulma with (
@import "~bulma/sass/components/navbar"; $family-primary: $family-serif,
@import "~bulma/sass/components/level"; $green: $coolors-green,
@import "~bulma/sass/components/message"; $blue: $coolors-blue,
@import "~bulma/sass/components/modal"; $red: $coolors-red,
@import "~bulma/sass/components/pagination"; $yellow: $coolors-yellow,
@import "~bulma/sass/components/panel"; $dark: $coolors-dark,
@import "~bulma/sass/elements/_all"; $primary: $coolors-green,
@import "~bulma/sass/form/_all"; $modal-content-width: 750px
@import "~bulma/sass/grid/columns"; );
@import "~bulma/sass/layout/section";
@import "./responsive_controls"; @import "./responsive_controls";
@import "./wide_modal"; @import "./wide_modal";
@ -28,7 +32,7 @@ body {
} }
body { body {
background-color: $grey-dark; background-color: bulma.$grey-dark;
padding-bottom: 2rem; padding-bottom: 2rem;
} }
@ -37,13 +41,13 @@ body {
.container { .container {
padding: 1rem; padding: 1rem;
background-color: $white; background-color: bulma.$white;
min-height: 75vh; min-height: 75vh;
} }
} }
.title, .subtitle, .navbar, .button, .pagination, .modal-card-title, th { .title, .subtitle, .navbar, .button, .pagination, .modal-card-title, th {
font-family: $family-sans-serif; font-family: bulma.$family-sans-serif;
} }
.pagination:not(:last-child) { .pagination:not(:last-child) {

View File

@ -91,15 +91,15 @@ class Food < Ingredient
:vit_e, :vit_e,
:vit_d, :vit_d,
:vit_k, :vit_k,
:cholesterol :cholesterol,
[:lipids, :lipid],
[:density, :density_best_guess]
] ]
copy_fields.each do |f| copy_fields.each do |f|
self.send("#{f}=".to_sym, food.send(f.to_sym)) to, from = f.is_a?(Array) ? f : [f, f]
self.send("#{to}=".to_sym, food.send(from.to_sym))
end end
self.lipids = food.lipid
self.density = food.density_best_guess
end end
end end

View File

@ -1,7 +1,7 @@
<% <%
manifest_data = Webpacker::manifest.refresh manifest_data = Shakapacker::manifest.refresh
manifest_timestamp = File.mtime(Webpacker::config.public_manifest_path).to_i manifest_timestamp = File.mtime(Shakapacker::config.public_manifest_path).to_i
pack_assets = manifest_data.select { |name, asset| name !~ /\.map$/ && name != 'entrypoints' }.values pack_assets = manifest_data.select { |name, asset| name !~ /\.map$/ && name != 'entrypoints' }.values
%> %>

View File

@ -11,6 +11,7 @@
<%= csrf_meta_tags %> <%= csrf_meta_tags %>
<%= javascript_pack_tag "application" %>
</head> </head>
<body> <body>

View File

@ -1,79 +0,0 @@
module.exports = function(api) {
var validEnv = ['development', 'test', 'production']
var currentEnv = api.env()
var isDevelopmentEnv = api.env('development')
var isProductionEnv = api.env('production')
var isTestEnv = api.env('test')
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
)
}
return {
presets: [
isTestEnv && [
'@babel/preset-env',
{
targets: {
node: 'current'
}
}
],
(isProductionEnv || isDevelopmentEnv) && [
'@babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: 3,
modules: false,
exclude: ['transform-typeof-symbol']
}
]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'@babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'@babel/plugin-transform-destructuring',
[
'@babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'@babel/plugin-proposal-private-methods',
{
"loose": true
}
],
["@babel/plugin-proposal-private-property-in-object", { "loose": true }],
[
'@babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'@babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
corejs: false
}
],
[
'@babel/plugin-transform-regenerator',
{
async: false
}
]
].filter(Boolean)
}
}

View File

@ -1,4 +1,4 @@
#!/usr/bin/env ruby #!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__) APP_PATH = File.expand_path("../config/application", __dir__)
require_relative '../config/boot' require_relative "../config/boot"
require 'rails/commands' require "rails/commands"

View File

@ -1,4 +1,4 @@
#!/usr/bin/env ruby #!/usr/bin/env ruby
require_relative '../config/boot' require_relative "../config/boot"
require 'rake' require "rake"
Rake.application.run Rake.application.run

View File

@ -1,11 +1,11 @@
#!/usr/bin/env ruby #!/usr/bin/env ruby
require 'fileutils' require "fileutils"
# path to your application root. APP_ROOT = File.expand_path("..", __dir__)
APP_ROOT = File.expand_path('..', __dir__) APP_NAME = "parsley"
def system!(*args) def system!(*args)
system(*args) || abort("\n== Command #{args} failed ==") system(*args, exception: true)
end end
FileUtils.chdir APP_ROOT do FileUtils.chdir APP_ROOT do
@ -13,21 +13,28 @@ FileUtils.chdir APP_ROOT do
# This script is idempotent, so that you can run it at any time and get an expectable outcome. # This script is idempotent, so that you can run it at any time and get an expectable outcome.
# Add necessary setup steps to this file. # Add necessary setup steps to this file.
puts '== Installing dependencies ==' puts "== Installing dependencies =="
system! 'gem install bundler --conservative' system! "gem install bundler --conservative"
system('bundle check') || system!('bundle install') system("bundle check") || system!("bundle install")
# Install JavaScript dependencies
system!("yarn install --no-immutable")
# puts "\n== Copying sample files ==" # puts "\n== Copying sample files =="
# unless File.exist?('config/database.yml') # unless File.exist?("config/database.yml")
# FileUtils.cp 'config/database.yml.sample', 'config/database.yml' # FileUtils.cp "config/database.yml.sample", "config/database.yml"
# end # end
puts "\n== Preparing database ==" puts "\n== Preparing database =="
system! 'bin/rails db:prepare' system! "bin/rails db:prepare"
puts "\n== Removing old logs and tempfiles ==" puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear' system! "bin/rails log:clear tmp:clear"
puts "\n== Restarting application server ==" puts "\n== Restarting application server =="
system! 'bin/rails restart' system! "bin/rails restart"
# puts "\n== Configuring puma-dev =="
# system "ln -nfs #{APP_ROOT} ~/.puma-dev/#{APP_NAME}"
# system "curl -Is https://#{APP_NAME}.test/up | head -n 1"
end end

13
bin/shakapacker Executable file
View File

@ -0,0 +1,13 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= "development"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", __FILE__)
require "bundler/setup"
require "shakapacker"
require "shakapacker/webpack_runner"
APP_ROOT = File.expand_path("..", __dir__)
Dir.chdir(APP_ROOT) do
Shakapacker::WebpackRunner.run(ARGV)
end

13
bin/shakapacker-dev-server Executable file
View File

@ -0,0 +1,13 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= "development"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", __FILE__)
require "bundler/setup"
require "shakapacker"
require "shakapacker/dev_server_runner"
APP_ROOT = File.expand_path("..", __dir__)
Dir.chdir(APP_ROOT) do
Shakapacker::DevServerRunner.run(ARGV)
end

View File

@ -1,19 +0,0 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"] ||= "development"
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
require "rubygems"
require "bundler/setup"
require "webpacker"
require "webpacker/webpack_runner"
APP_ROOT = File.expand_path("..", __dir__)
Dir.chdir(APP_ROOT) do
Webpacker::WebpackRunner.run(ARGV)
end

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