Compare commits

...

237 Commits

Author SHA1 Message Date
filipriec
20f9fae141 buffer working 2025-04-14 22:34:22 +02:00
filipriec
ec062bbf24 its on the top of the screen now 2025-04-14 22:17:24 +02:00
filipriec
8745c9ea2f sidebar fixed bugs and buffer implementation 1 2025-04-14 22:14:01 +02:00
filipriec
0917654361 admin panel now distinguish admin and other roles of the user 2025-04-14 21:04:55 +02:00
filipriec
d892d1cfa0 role restricted admin panel 2025-04-14 20:50:02 +02:00
filipriec
e31138c250 DONE we have now intro state separate from others completely 2025-04-14 20:00:02 +02:00
filipriec
7cbe5ce8be intro movement fixed 2025-04-14 16:25:54 +02:00
filipriec
1c31d4cd1c moved introstate into the state folder 2025-04-14 16:24:21 +02:00
filipriec
990ec9317f admin panel tiny improvement. STARTING OF ADMIN PANEL BUILDING 2025-04-14 15:27:26 +02:00
filipriec
718ceac17e cargo fix 2025-04-14 15:04:24 +02:00
filipriec
d154ba6b89 we compiled for now 2025-04-14 14:28:36 +02:00
filipriec
f2a63476b3 continuation of the fixes 2025-04-14 14:05:20 +02:00
filipriec
adcd3b37fa fixing this 2025-04-14 13:23:09 +02:00
filipriec
71dabc1e37 very bald changes, still destroyed 2025-04-14 12:07:15 +02:00
filipriec
2d724876eb going directly into adminstate from appstate for the admin page. DESTROYED 2025-04-14 11:24:56 +02:00
filipriec
1927d1fa4d appstate moved to its folder also 2025-04-13 22:52:15 +02:00
filipriec
d995fab0e4 moved canvasstate to the pages folder 2025-04-13 22:45:26 +02:00
filipriec
b4135c1626 attempt for dropdown generalization, minor change really 2025-04-13 22:14:34 +02:00
filipriec
3d0a9f2082 we successfully compiled and wen from auth state to login state and auth state 2025-04-13 17:47:00 +02:00
filipriec
1dd5f685a6 authstate splitting into login state and auth state, quite before maddness 2025-04-13 17:06:59 +02:00
filipriec
c1c4394f94 ... at the end of the dialog truncation 2025-04-13 14:58:41 +02:00
filipriec
16d9fcdadc only important stuff in the response of the login 2025-04-13 14:09:57 +02:00
filipriec
5b1db01fe6 displaying username and username contained in the jwt now 2025-04-13 14:04:30 +02:00
filipriec
e856e9d6c7 response contains username but jwt is holding username also 2025-04-13 13:45:22 +02:00
filipriec
ad2c783870 improvements on the register.rs 2025-04-13 00:09:12 +02:00
filipriec
5e101bef14 tab is triggering the suggestion dropdown menu, but ctrl+n and ctrl+p only cycle through it 2025-04-12 23:56:14 +02:00
filipriec
149949ad99 better dropdown gui 2025-04-12 22:42:06 +02:00
filipriec
741cc952fa fixed more dropdown menu 2025-04-12 18:06:19 +02:00
filipriec
d2bb7a0bf4 forgotten cargo lock 2025-04-12 17:48:35 +02:00
filipriec
d4d5bcec9e width for the dropdown fixed 2025-04-12 17:41:37 +02:00
filipriec
b4053a7b94 working perfectly well 2025-04-12 17:34:17 +02:00
filipriec
7b27d00972 working suggestions but position is wrong 2025-04-12 16:22:07 +02:00
filipriec
f4d234089f much better, still not it 2025-04-12 15:52:12 +02:00
filipriec
50a329fc0d suggestions on tab, still not working yet 2025-04-12 15:31:29 +02:00
filipriec
6d6df7ca5c still not working autocomplete 2025-04-12 00:13:28 +02:00
filipriec
6b16068706 moved to auth_e functions for dropdown from edit mode file 2025-04-11 23:42:18 +02:00
filipriec
024a0de4af completion not working yet 2025-04-11 22:54:44 +02:00
filipriec
e145d63ba6 fixing autocomplete, bombarded code, nothing in here 2025-04-11 22:39:09 +02:00
filipriec
e7e8b0b3f6 reg proper movement 2025-04-11 21:42:59 +02:00
filipriec
a7389db674 trigger dropdown, not working at all, needs proper implementation, ready for debug 2025-04-11 15:40:50 +02:00
filipriec
cf1aa4fd2a register form now has optional field role 2025-04-11 13:51:05 +02:00
filipriec
0fd2a589eb register with optional role in the post request 2025-04-11 13:37:57 +02:00
filipriec
944131d5a6 from 4e01740a61 till now, fully integrated working register 2025-04-11 08:52:01 +02:00
filipriec
eff46ac9bf working read only mode in login and register properly workig now 2025-04-11 08:50:54 +02:00
filipriec
14f9b254b2 read only mode needs adjustement to 4 fields from 2 2025-04-10 23:04:25 +02:00
filipriec
337d6050ff common mode register fix 2025-04-10 22:18:01 +02:00
filipriec
d36348b84f gRPC implementation of a registration working 2025-04-10 21:14:32 +02:00
filipriec
dfb6f5b375 registration auth services added 2025-04-10 21:00:41 +02:00
filipriec
a9089bc2ff displaying register 2025-04-10 20:01:03 +02:00
filipriec
5f5d690ff3 compiled time to render register properly well 2025-04-10 19:32:49 +02:00
filipriec
431882ece9 register 2 2025-04-10 19:27:04 +02:00
filipriec
b51e76e366 register on the way 2025-04-10 18:50:54 +02:00
filipriec
4e01740a61 fixed exit in the login dialog 2025-04-10 16:34:29 +02:00
filipriec
e729ed9df3 compiled 2025-04-10 16:05:06 +02:00
filipriec
6b241304fb dialog login functionality 2025-04-10 15:36:43 +02:00
filipriec
3ed8764087 cargo fix 2025-04-10 14:45:16 +02:00
filipriec
df61b245ab back to main 2025-04-10 14:42:11 +02:00
filipriec
7a364d654c repaired 2025-04-10 14:22:30 +02:00
filipriec
0d1a0be1a0 dialog movement fixed 2025-04-10 14:13:39 +02:00
filipriec
5da9f5aaf4 better, but more dialog logic is needed 2025-04-10 13:45:36 +02:00
filipriec
2bec0f5850 dialog 2 2025-04-10 13:40:24 +02:00
filipriec
5bc28ec38b dialog 2025-04-10 13:37:15 +02:00
filipriec
8c7a0a1ec0 we compiled centralized system for select 2025-04-10 12:13:04 +02:00
filipriec
a8eef8107b cursor fixed 2025-04-07 23:39:27 +02:00
filipriec
75cd942f39 fixed and now fully functional 2025-04-07 23:06:58 +02:00
filipriec
fc04af148d minor error fix 2025-04-07 22:55:07 +02:00
filipriec
d7d7fd614b fixing more errors, last to go 2025-04-07 22:46:00 +02:00
filipriec
10e9c3ead0 minor changes 2025-04-07 21:32:02 +02:00
filipriec
70678432c6 BREAKING CHANGES updating gRPC based on the enum now 2025-04-07 21:27:01 +02:00
filipriec
bb103fac6c minor changes 2025-04-07 17:36:59 +02:00
filipriec
0e1fc3f5fa cursor is disabled instead of hidden now 2025-04-07 17:23:42 +02:00
filipriec
7830ebdb3b cursor hidden if not active 2025-04-07 17:16:36 +02:00
filipriec
b061dd3395 BREAKING UPDATE COUNT REMOVED FROM THE MAIN LOOP 2025-04-07 16:27:40 +02:00
filipriec
a6f2fa8a88 button highlight now working perfectly well 2025-04-07 14:05:28 +02:00
filipriec
37f12ea6f0 working needs a small fix 2025-04-07 13:24:22 +02:00
filipriec
e29b576102 removed unused imports 2025-04-07 12:19:35 +02:00
filipriec
b1b3cf6136 changes for revert save in the readonly mode and not only the edit mode finished. 2025-04-07 12:18:03 +02:00
filipriec
173c4c98b8 feat: Prevent form navigation with unsaved changes 2025-04-07 12:03:17 +02:00
filipriec
5a3067c8e5 edit to read_only mode without save 2025-04-07 10:13:39 +02:00
filipriec
803c748738 only to the top and to the bottom in the canvas, cant jump around anymore 2025-04-06 23:16:15 +02:00
filipriec
5879b40e8c exit menu buttons upon success 2025-04-05 19:42:29 +02:00
filipriec
c3decdac13 working dialog now better 2025-04-05 19:37:51 +02:00
filipriec
1baf89dde6 login with dialog menu 2025-04-05 17:52:37 +02:00
filipriec
0219dc0ede border fixed 2025-04-05 17:34:26 +02:00
filipriec
1c662888c6 minor changes 2025-04-05 17:21:07 +02:00
filipriec
7fd1c1e41d working inputting characters 2025-04-05 13:34:38 +02:00
filipriec
1eaa716f42 working now, able to switch between form_e and auth_e 2025-04-05 00:42:56 +02:00
filipriec
704bb7401a copied form_e to auth_e 2025-04-04 23:37:19 +02:00
filipriec
b0c3fdbdc6 added in here src/functions/modes/read_only/auth_ro.rs missing functions, not working tho 2025-04-04 23:34:56 +02:00
filipriec
1d0ceb7045 minor changes 2025-04-04 23:28:30 +02:00
filipriec
ce85a050d3 command mode handler moved 2025-04-04 22:34:04 +02:00
filipriec
94ecbcd639 moved common to common_mode 2025-04-04 20:49:12 +02:00
filipriec
ef1d8bcc9c fully moved now 2025-04-04 20:39:23 +02:00
filipriec
1a7bbdc541 moving back to tui nonmode functions for now 2025-04-04 20:37:02 +02:00
filipriec
3dc5a89459 splitting modes into functions and how it works vs logic to handle it all 2025-04-03 23:23:25 +02:00
filipriec
9f6268dbc9 minor change 2025-04-03 23:00:34 +02:00
filipriec
2e912dd261 moved to form_ro 2025-04-03 22:12:20 +02:00
filipriec
6d6fff474f switching now execute action functions left to right 2025-04-03 20:04:01 +02:00
filipriec
e725c70570 splitting read_only mode 2025-04-03 19:50:35 +02:00
filipriec
07aeecbbfc functions created and now working, lets move modes functions here now 2025-04-03 19:43:59 +02:00
filipriec
9bfac04c44 modes functions dir 2025-04-03 12:34:37 +02:00
filipriec
6acf0d6378 new function dir for functions 2025-04-03 12:32:53 +02:00
filipriec
1a09624242 e fixed 2025-04-02 22:26:35 +02:00
filipriec
9e36385e63 decimated edit mode also 2025-04-02 21:13:18 +02:00
filipriec
43edadde0c trying restoring functionality we are not in there correctly yet 2025-04-02 21:06:49 +02:00
filipriec
d577ff6715 edit mode is like a readonly mode 2025-03-31 23:56:58 +02:00
filipriec
ca75c90ee9 changed read_only mode also 2025-03-31 23:37:02 +02:00
filipriec
8e0fae26ee we compiled 2025-03-31 22:08:39 +02:00
filipriec
bee95c3755 fixes, still 2 errors remaining 2025-03-31 20:10:53 +02:00
filipriec
306f4de14f smart way, but introduced many errors 2025-03-31 17:55:53 +02:00
filipriec
b2fc681e73 cargo fix 2025-03-31 17:16:10 +02:00
filipriec
060cff3f0f compiled 2025-03-31 17:10:51 +02:00
filipriec
07c48985e4 proper pass of the arguments 2025-03-31 16:25:11 +02:00
filipriec
3d266c2ad0 switching of the views done 2025-03-31 16:23:25 +02:00
filipriec
e2c326bf1e login gRPC 2025-03-31 16:16:07 +02:00
filipriec
7f5b671084 switch between login or form in the save request 2025-03-31 15:55:54 +02:00
filipriec
3ccf71ed0f switcher, have bugs 2025-03-31 15:42:48 +02:00
filipriec
efb59c5571 split config in modes/canvas is fixed and working properly well 2025-03-31 15:12:50 +02:00
filipriec
26cf06df14 needs fixes of the errors 2025-03-31 14:58:10 +02:00
filipriec
c82b62f72b moving modes/canvas/common.rs into the functions 2025-03-31 13:22:08 +02:00
filipriec
87cdb8048d we compiled fully, time to move grpc calls now 2025-03-31 12:07:01 +02:00
filipriec
f71498703a implementation of login 2025-03-31 10:40:34 +02:00
filipriec
94eea47b76 cargo fix 2025-03-31 10:24:20 +02:00
filipriec
ac833294c4 moved login from grpc_client 2025-03-31 10:23:23 +02:00
filipriec
81f0527085 ui.rs gRPC code removed 2025-03-31 09:54:16 +02:00
filipriec
dd4d9e88c6 ready to move gRPC into a single services folder, time to do the changes now 2025-03-31 09:39:47 +02:00
filipriec
f66d67c238 grpc_service moved 2025-03-31 07:13:24 +02:00
filipriec
9cf25afa52 moving grpc_client, needs import fixes 2025-03-31 07:08:51 +02:00
filipriec
2ed2419f9e Add auth service client and auth state fields 2025-03-30 21:44:45 +02:00
filipriec
e19b30f4f4 auth dialog implemented 2025-03-30 20:38:09 +02:00
filipriec
f6e21b6a61 is edit mode passing properly 2025-03-30 19:03:58 +02:00
filipriec
2180d8decf step2 compiled 2025-03-30 18:41:27 +02:00
filipriec
12aec72141 added fields to the traits 2025-03-30 18:33:21 +02:00
filipriec
0568441e46 minor ui stuff 2025-03-30 18:29:33 +02:00
filipriec
301189bd85 login is not dependent on form/form.rs and only on canvas now 2025-03-30 17:00:51 +02:00
filipriec
81767f376f button sizes 2025-03-30 16:35:38 +02:00
filipriec
e36b1817bc working, split config where functions for each page are defined for this page, if the functions are not general for each page. Huge update, works for tui/functions/form and fui/functions/login. Working, time to move to other things 2025-03-30 15:46:49 +02:00
filipriec
13d4db6bdc properly handling up and down in the form and login, login needs logic implementation 2025-03-30 15:11:02 +02:00
filipriec
b5a5ebd7c0 working exactly as i want, now making the login up and down to work properly well 2025-03-30 15:03:12 +02:00
filipriec
6e04c1f267 original form fully working in the tui functions is the logic for the form 2025-03-30 14:24:12 +02:00
filipriec
a0d96cb87a moving to tui/functions/form.rs read_only functions 2025-03-30 14:13:07 +02:00
filipriec
4052a5b81b fixed unused imports 2025-03-30 14:01:08 +02:00
filipriec
ed99ebf541 compiled if statement in the read_only mode 2025-03-30 13:57:22 +02:00
filipriec
0a4f59cf8e reverting back fully 2025-03-30 13:15:51 +02:00
filipriec
fd6a9b73be reverting back 2025-03-30 13:11:04 +02:00
filipriec
dc994f6ee1 login in the functions 2025-03-30 13:04:48 +02:00
filipriec
e234dd1785 down and up now added to work in the original form 2025-03-30 12:09:20 +02:00
filipriec
6e0943f0cc compiled 2025-03-30 00:51:11 +01:00
filipriec
9622e0bd3c moving read_only functions for the form specific 2025-03-29 22:36:03 +01:00
filipriec
ee666e91ed adjusted login not working yet, wrong changes 2025-03-29 00:09:06 +01:00
filipriec
4f8f2f4a40 step4 2025-03-28 20:48:06 +01:00
filipriec
f21953147b step 3 compiled 2025-03-28 14:35:16 +01:00
filipriec
48b2658b55 step2 2025-03-28 14:29:36 +01:00
filipriec
37b08fdd10 implementation of canvas for multiple pages step 1 2025-03-28 14:26:18 +01:00
filipriec
d4efdf4833 login improvements 2025-03-27 12:27:43 +01:00
filipriec
b408abe8c6 quick prod check .sqlx 2025-03-26 00:50:25 +01:00
filipriec
722c63af54 fixed the navigation previous function, therefore we are now moving into the login properly, lets implement the auth now 2025-03-26 00:46:59 +01:00
filipriec
4601ba4094 unused stuff removed 2025-03-26 00:43:42 +01:00
filipriec
3e2b8a36df fixing warnings 2025-03-26 00:39:27 +01:00
filipriec
11214734ae functions are now in the file dedicated to the functions belonging to the page 2025-03-26 00:26:36 +01:00
filipriec
92045a4e67 unused stuff 2025-03-26 00:16:38 +01:00
filipriec
9564bd8524 login page is now being properly displayed 2025-03-26 00:04:30 +01:00
filipriec
ad64df2ec3 nothing is fixed, it doesnt work, i cant see a login page 2025-03-25 23:23:47 +01:00
filipriec
aab11c1cba login logic in the components 2025-03-25 22:56:24 +01:00
filipriec
1fe139e0c5 we compiled 2025-03-25 22:01:09 +01:00
filipriec
4ced1a36d4 moved form.rs into the state where it really belongs to 2025-03-25 21:23:52 +01:00
filipriec
45fff34c4c login page being implemented slowly 2025-03-25 16:02:23 +01:00
filipriec
c84fa4a692 frontend implementing login 2025-03-25 15:57:45 +01:00
filipriec
eba3f56ba3 indefinite jwt expiration set 2025-03-25 13:17:13 +01:00
filipriec
71ab588c16 tonic rbac to tower 2025-03-25 12:36:31 +01:00
filipriec
195375c083 temp disable of the rbac 2025-03-25 12:35:10 +01:00
filipriec
34dafcc23e rbac using tonic 2025-03-25 11:33:14 +01:00
filipriec
507f86fcf1 docs 2025-03-25 10:35:22 +01:00
filipriec
f40654d2c4 it compiled 2025-03-25 10:28:29 +01:00
filipriec
cd32c175a4 jwt implementation and login, not working yet 2025-03-25 10:15:17 +01:00
filipriec
9393294af8 docs, auth starting officially 0.2.0 version 2025-03-24 22:17:02 +01:00
filipriec
24c426229c registration works perfectly well 2025-03-24 22:15:17 +01:00
filipriec
3ed6fd4ee8 we compiled 2025-03-24 22:03:04 +01:00
filipriec
70d83c284a broken only push user data 2025-03-24 21:46:04 +01:00
filipriec
8a248cab58 working finally 2025-03-24 18:57:59 +01:00
filipriec
e6851e1fe4 small error to fix 2025-03-24 17:14:12 +01:00
filipriec
65ff1256aa canvas common needs redesign, sidebar displaying even when no profile selected 2025-03-24 16:46:02 +01:00
filipriec
36dc4302a0 sidebar if there is no profile selected 2025-03-24 16:15:55 +01:00
filipriec
938a1f16f1 form component is now in the separate component 2025-03-24 15:57:41 +01:00
filipriec
355aff3032 working perfectly well right now 2025-03-24 15:13:57 +01:00
filipriec
3bb771187a admin bug fixed, time for intro also 2025-03-24 15:09:35 +01:00
filipriec
aa3ff18f9c now for common in canvas 2025-03-24 14:54:02 +01:00
filipriec
1fc9a0e1ff reorganization, preserved functionality 2025-03-24 14:29:28 +01:00
filipriec
cdac78c1bc needs to reset the render but it finally works 2025-03-24 14:17:44 +01:00
filipriec
bdb6cd4069 modes needs more progress 2025-03-24 11:46:33 +01:00
filipriec
ec5802b3a2 works 2025-03-24 11:17:59 +01:00
filipriec
1eb2edc1df mode manager finally 2025-03-24 11:03:52 +01:00
filipriec
2da009eede marked bloat 2025-03-24 00:06:44 +01:00
filipriec
b2fd44df49 working select setting the form to true in state state.rs 2025-03-23 22:41:18 +01:00
filipriec
78e8cce08b moved to common modes 2025-03-23 22:14:24 +01:00
filipriec
2cf4cd6748 appstate for form 2025-03-23 22:08:33 +01:00
filipriec
7caa4d8c3c general mode 2025-03-23 21:00:53 +01:00
filipriec
9917195fc4 disabling modes where they shouldnt be enabled BIG UPDATE 2025-03-23 20:07:47 +01:00
filipriec
fbcea1b270 trying to make the intro and admin with general keybindings 2025-03-23 19:17:42 +01:00
filipriec
87b07db26a completely broken intro or admin 2025-03-23 15:35:57 +01:00
filipriec
4481560025 HUGE CHANGES TO MODESA 2025-03-23 15:11:43 +01:00
filipriec
d1d33b5752 project redesign 2025-03-23 13:50:47 +01:00
filipriec
c6c6c5ed81 restored rendering 2025-03-23 12:59:36 +01:00
filipriec
4ddcb34205 nothing 2025-03-23 12:56:27 +01:00
filipriec
83393a20e2 fix of the error 2025-03-23 12:44:33 +01:00
filipriec
13d501e6d7 not working 2025-03-23 12:30:00 +01:00
filipriec
993febd204 admin panel keyindings 2025-03-23 11:28:39 +01:00
filipriec
49fe2aa793 edit mode is now perfectly working 2025-03-23 10:55:05 +01:00
filipriec
87a572783a i think its a step in the right direction, needs to export other functions now 2025-03-23 10:03:59 +01:00
filipriec
ca8dea53fd VERY SUSPICIOUS BREAKING FUNCTIONALITY CHECK LATER 2025-03-23 00:49:19 +01:00
filipriec
fef2f12c9a :disabled in the edit mode, cant type it tho, needs fix 2025-03-23 00:28:51 +01:00
filipriec
1a529a70bf gamechanging, commands works only on their windows properly well 2025-03-22 23:32:33 +01:00
filipriec
8da29376ab moved key sequences also 2025-03-22 23:03:13 +01:00
filipriec
8ad5fedcea config was moved successfully 2025-03-22 22:58:58 +01:00
filipriec
16a7fa0bcc working change of the themes 2025-03-22 22:55:43 +01:00
filipriec
5f6858251c moved themes out of the config 2025-03-22 22:51:53 +01:00
filipriec
73567ae5cf moved everything up 2025-03-22 22:40:38 +01:00
filipriec
fe2d1e4684 working perfectly well, needs bug fixes to proper shortcuts to proper windows 2025-03-22 20:10:39 +01:00
filipriec
7d4b043d63 still one error missing 2025-03-22 20:05:13 +01:00
filipriec
04b4220c76 needs bug fixing 2025-03-22 19:37:41 +01:00
filipriec
841418759b last changes 2025-03-22 16:26:38 +01:00
filipriec
ccd76eabdd components are redesigned 2025-03-22 15:45:55 +01:00
filipriec
fabe1e0ca7 changing components infrastructure 2025-03-22 15:36:49 +01:00
filipriec
9bf1d065d5 restored functionality 2025-03-22 15:11:08 +01:00
filipriec
62aed812b6 displaying admin panel properly well 2025-03-22 13:18:50 +01:00
filipriec
a58e976227 admin panel is working, needs to clear the terminal tho from the other things 2025-03-22 10:33:09 +01:00
filipriec
c198297a5c admin panel compiled 2025-03-22 10:27:21 +01:00
filipriec
c592dfc7f5 intro page working properly well 2025-03-21 23:07:10 +01:00
filipriec
1b0aaa55c9 switched stuff in the state.rs 2025-03-21 22:46:50 +01:00
filipriec
44c5963c71 removed unused stuff 2025-03-21 22:22:35 +01:00
filipriec
911dba9bce working profiler tree 2025-03-21 22:20:43 +01:00
filipriec
d55dff8a3e deprecation fixed 2025-03-21 21:26:06 +01:00
filipriec
8b2120bdc8 working perfectly well 2025-03-21 19:56:07 +01:00
filipriec
8ce90f3c42 sidebar behaviour is now amazing 2025-03-21 18:55:50 +01:00
filipriec
62d7fb6bda centered form 2025-03-21 18:46:17 +01:00
filipriec
27cca8763b removed preview card 2025-03-21 18:21:40 +01:00
filipriec
74054f2724 removed nonsense 2025-03-21 16:23:47 +01:00
127 changed files with 7271 additions and 1693 deletions

View File

@@ -4,3 +4,5 @@ RUST_DB_USER=multi_psql_dev
RUST_DB_PASSWORD=3
RUST_DB_HOST=localhost
RUST_DB_PORT=5432
JWT_SECRET=<YOUR-JWT-HERE>

197
Cargo.lock generated
View File

@@ -170,9 +170,9 @@ dependencies = [
[[package]]
name = "async-trait"
version = "0.1.87"
version = "0.1.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97"
checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5"
dependencies = [
"proc-macro2",
"quote",
@@ -274,6 +274,19 @@ version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
[[package]]
name = "bcrypt"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92758ad6077e4c76a6cadbce5005f666df70d4f13b19976b1a8062eef880040f"
dependencies = [
"base64",
"blowfish",
"getrandom 0.3.1",
"subtle",
"zeroize",
]
[[package]]
name = "bigdecimal"
version = "0.4.7"
@@ -323,6 +336,16 @@ dependencies = [
"generic-array",
]
[[package]]
name = "blowfish"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"
dependencies = [
"byteorder",
"cipher",
]
[[package]]
name = "bumpalo"
version = "3.17.0"
@@ -387,13 +410,25 @@ dependencies = [
]
[[package]]
name = "client"
version = "0.1.0"
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "client"
version = "0.3.5"
dependencies = [
"async-trait",
"common",
"crossterm",
"dirs 6.0.0",
"dotenvy",
"lazy_static",
"prost",
"ratatui",
"serde",
@@ -401,6 +436,8 @@ dependencies = [
"toml",
"tonic",
"tracing",
"unicode-segmentation",
"unicode-width 0.2.0",
]
[[package]]
@@ -424,7 +461,7 @@ dependencies = [
[[package]]
name = "common"
version = "0.1.0"
version = "0.3.5"
dependencies = [
"prost",
"serde",
@@ -782,7 +819,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -991,8 +1028,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
"wasm-bindgen",
]
[[package]]
@@ -1452,6 +1491,15 @@ version = "2.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c7245a08504955605670dbf141fceab975f15ca21570696aebe9d2e71576bd"
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "instability"
version = "0.3.7"
@@ -1499,6 +1547,21 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jsonwebtoken"
version = "9.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
dependencies = [
"base64",
"js-sys",
"pem",
"ring",
"serde",
"serde_json",
"simple_asn1",
]
[[package]]
name = "lasso"
version = "0.7.3"
@@ -1886,6 +1949,16 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pem"
version = "3.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3"
dependencies = [
"base64",
"serde",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@@ -2030,6 +2103,28 @@ dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro-error-attr2"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "proc-macro-error2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"
dependencies = [
"proc-macro-error-attr2",
"proc-macro2",
"quote",
"syn 2.0.99",
]
[[package]]
name = "proc-macro2"
version = "1.0.94"
@@ -2281,6 +2376,20 @@ dependencies = [
"tstr",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.15",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rsa"
version = "0.9.7"
@@ -2356,7 +2465,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.4.15",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2369,7 +2478,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.9.2",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2483,12 +2592,14 @@ dependencies = [
[[package]]
name = "server"
version = "0.1.0"
version = "0.3.5"
dependencies = [
"bcrypt",
"chrono",
"common",
"dashmap",
"dotenvy",
"jsonwebtoken",
"lazy_static",
"prost",
"regex",
@@ -2504,6 +2615,8 @@ dependencies = [
"tonic",
"tonic-reflection",
"tracing",
"uuid",
"validator",
]
[[package]]
@@ -2574,6 +2687,18 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "simple_asn1"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
dependencies = [
"num-bigint",
"num-traits",
"thiserror 2.0.12",
"time",
]
[[package]]
name = "sized-chunks"
version = "0.6.5"
@@ -2678,6 +2803,7 @@ dependencies = [
"tokio-stream",
"tracing",
"url",
"uuid",
]
[[package]]
@@ -2760,6 +2886,7 @@ dependencies = [
"thiserror 2.0.12",
"time",
"tracing",
"uuid",
"whoami",
]
@@ -2799,6 +2926,7 @@ dependencies = [
"thiserror 2.0.12",
"time",
"tracing",
"uuid",
"whoami",
]
@@ -2825,6 +2953,7 @@ dependencies = [
"time",
"tracing",
"url",
"uuid",
]
[[package]]
@@ -3029,7 +3158,7 @@ dependencies = [
"getrandom 0.3.1",
"once_cell",
"rustix 1.0.1",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -3450,6 +3579,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.4"
@@ -3473,6 +3608,46 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "uuid"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
dependencies = [
"getrandom 0.3.1",
"serde",
]
[[package]]
name = "validator"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43fb22e1a008ece370ce08a3e9e4447a910e92621bb49b85d6e48a45397e7cfa"
dependencies = [
"idna",
"once_cell",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_derive",
]
[[package]]
name = "validator_derive"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7df16e474ef958526d1205f6dda359fdfab79d9aa6d54bafcb92dcd07673dca"
dependencies = [
"darling",
"once_cell",
"proc-macro-error2",
"proc-macro2",
"quote",
"syn 2.0.99",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
@@ -3623,7 +3798,7 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]

View File

@@ -5,7 +5,7 @@ resolver = "2"
[workspace.package]
# TODO: idk how to do the name, fix later
# name = "Multieko2"
version = "0.1.0"
version = "0.3.5"
edition = "2021"
license = "GPL-3.0-or-later"
authors = ["Filip Priečinský <filippriec@gmail.com>"]

View File

@@ -5,11 +5,13 @@ edition.workspace = true
license.workspace = true
[dependencies]
async-trait = "0.1.88"
common = { path = "../common" }
crossterm = "0.28.1"
dirs = "6.0.0"
dotenvy = "0.15.7"
lazy_static = "1.5.0"
prost = "0.13.5"
ratatui = "0.29.0"
serde = { version = "1.0.218", features = ["derive"] }
@@ -17,3 +19,5 @@ tokio = { version = "1.43.0", features = ["full", "macros"] }
toml = "0.8.20"
tonic = "0.12.3"
tracing = "0.1.41"
unicode-segmentation = "1.12.0"
unicode-width = "0.2.0"

View File

@@ -1,6 +1,19 @@
# config.toml
[keybindings]
enter_command_mode = [":", "ctrl+;"]
[keybindings.general]
move_up = ["k", "Up"]
move_down = ["j", "Down"]
next_option = ["l", "Right"]
previous_option = ["h", "Left"]
select = ["Enter"]
toggle_sidebar = ["ctrl+t"]
toggle_buffer_list = ["ctrl+b"]
next_field = ["Tab"]
prev_field = ["Shift+Tab"]
[keybindings.common]
save = ["ctrl+s"]
quit = ["ctrl+q"]
@@ -12,6 +25,7 @@ save_and_quit = ["ctrl+shift+s"]
move_up = ["Up"]
move_down = ["Down"]
toggle_sidebar = ["ctrl+t"]
toggle_buffer_list = ["ctrl+b"]
# MODE SPECIFIC
# READ ONLY MODE
@@ -33,16 +47,19 @@ move_line_start = ["0"]
move_line_end = ["$"]
move_first_line = ["gg"]
move_last_line = ["x"]
enter_command_mode = [":", "ctrl+;"]
[keybindings.edit]
exit_edit_mode = ["esc","ctrl+e"]
delete_char_forward = ["delete"]
delete_char_backward = ["backspace"]
next_field = ["tab", "enter"]
prev_field = ["shift+tab", "backtab"]
next_field = ["enter"]
prev_field = ["shift+enter"]
move_left = ["left"]
move_right = ["right"]
suggestion_down = ["ctrl+n", "tab"]
suggestion_up = ["ctrl+p", "shift+tab"]
select_suggestion = ["enter"]
exit_suggestion_mode = ["esc"]
[keybindings.command]
exit_command_mode = ["ctrl+g", "esc"]

View File

@@ -0,0 +1,4 @@
// src/components/admin.rs
pub mod admin_panel;
pub use admin_panel::*;

View File

@@ -0,0 +1,137 @@
// src/components/admin/admin_panel.rs
use crate::config::colors::themes::Theme;
use crate::state::pages::auth::AuthState;
use crate::state::pages::admin::AdminState;
use common::proto::multieko2::table_definition::ProfileTreeResponse;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::Style,
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, List, ListItem, Paragraph, Wrap},
Frame,
};
/// Renders the view specific to admin users.
fn render_admin_panel_admin(f: &mut Frame, content_chunks: &[Rect], theme: &Theme) {
// Admin-specific view placeholder
let admin_message = Paragraph::new("Admin-specific view. Profile selection not applicable.")
.style(Style::default().fg(theme.fg))
.alignment(Alignment::Center);
// Render only in the right pane for now, leaving left empty
f.render_widget(admin_message, content_chunks[1]);
}
pub fn render_admin_panel(
f: &mut Frame,
auth_state: &AuthState,
admin_state: &AdminState,
area: Rect,
theme: &Theme,
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>,
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent))
.style(Style::default().bg(theme.bg));
let inner_area = block.inner(area);
f.render_widget(block, area);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(1)])
.split(inner_area);
// Title
let title = Line::from(Span::styled("Admin Panel", Style::default().fg(theme.highlight)));
let title_widget = Paragraph::new(title).alignment(Alignment::Center);
f.render_widget(title_widget, chunks[0]);
// Content
let content_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
.split(chunks[1]);
if auth_state.role.as_deref() != Some("admin") {
render_admin_panel_non_admin(
f,
admin_state,
&content_chunks,
theme,
profile_tree,
selected_profile,
);
} else {
render_admin_panel_admin(f, &content_chunks, theme);
}
}
/// Renders the view for non-admin users (profile list and details).
fn render_admin_panel_non_admin(
f: &mut Frame,
admin_state: &AdminState,
content_chunks: &[Rect],
theme: &Theme,
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>,
) {
// Profile list - Use data from admin_state
let items: Vec<ListItem> = admin_state
.profiles
.iter()
.map(|p| {
ListItem::new(Line::from(vec![
Span::styled(
if Some(p) == selected_profile.as_ref() { "" } else { " " },
Style::default().fg(theme.accent),
),
Span::styled(p, Style::default().fg(theme.fg)),
]))
})
.collect();
let list = List::new(items)
.block(Block::default().title("Profiles"))
.highlight_style(Style::default().bg(theme.highlight).fg(theme.bg));
let mut list_state_clone = admin_state.list_state.clone();
f.render_stateful_widget(list, content_chunks[0], &mut list_state_clone);
// Profile details - Use selection info from admin_state
if let Some(profile) = admin_state
.get_selected_index()
.and_then(|i| profile_tree.profiles.get(i))
{
let mut text = Text::default();
text.lines.push(Line::from(vec![
Span::styled("Profile: ", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
]));
text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
"Tables:",
Style::default().fg(theme.accent),
)));
for table in &profile.tables {
let mut line = vec![Span::styled(format!("├─ {}", table.name), theme.fg)];
if !table.depends_on.is_empty() {
line.push(Span::styled(
format!("{}", table.depends_on.join(", ")),
Style::default().fg(theme.secondary),
));
}
text.lines.push(Line::from(line));
}
let details_widget = Paragraph::new(text)
.block(Block::default().title("Details"))
.wrap(Wrap { trim: true });
f.render_widget(details_widget, content_chunks[1]);
}
}

View File

@@ -0,0 +1,6 @@
// src/components/form.rs
pub mod login;
pub mod register;
pub use login::*;
pub use register::*;

View File

@@ -0,0 +1,145 @@
// src/components/auth/login.rs
use crate::{
config::colors::themes::Theme,
state::pages::auth::LoginState,
components::common::dialog,
state::app::state::AppState,
};
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color},
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
};
pub fn render_login(
f: &mut Frame,
area: Rect,
theme: &Theme,
login_state: &LoginState,
app_state: &AppState,
is_edit_mode: bool,
) {
// Main container
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(Style::default().fg(theme.border))
.title(" Login ")
.style(Style::default().bg(theme.bg));
f.render_widget(block, area);
let inner_area = area.inner(Margin {
horizontal: 1,
vertical: 1,
});
// Layout chunks
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(4), // Form (2 fields + padding)
Constraint::Length(1), // Error message
Constraint::Length(3), // Buttons
])
.split(inner_area);
// --- FORM RENDERING ---
crate::components::handlers::canvas::render_canvas(
f,
chunks[0],
login_state,
&["Username/Email", "Password"],
&login_state.current_field,
&[&login_state.username, &login_state.password],
theme,
is_edit_mode,
);
// --- ERROR MESSAGE ---
if let Some(err) = &login_state.error_message {
f.render_widget(
Paragraph::new(err.as_str())
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Center),
chunks[1],
);
}
// --- BUTTONS ---
let button_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(chunks[2]);
// Login Button
let login_button_index = 0;
let login_active = if app_state.ui.focus_outside_canvas {
app_state.focused_button_index== login_button_index
} else {
false
};
let mut login_style = Style::default().fg(theme.fg);
let mut login_border = Style::default().fg(theme.border);
if login_active {
login_style = login_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
login_border = login_border.fg(theme.accent);
}
f.render_widget(
Paragraph::new("Login")
.style(login_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(login_border),
),
button_chunks[0],
);
// Return Button
let return_button_index = 1; // Assuming Return is the second general element
let return_active = if app_state.ui.focus_outside_canvas {
app_state.focused_button_index== return_button_index
} else {
false // Not active if focus is in canvas or other modes
};
let mut return_style = Style::default().fg(theme.fg);
let mut return_border = Style::default().fg(theme.border);
if return_active {
return_style = return_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
return_border = return_border.fg(theme.accent);
}
f.render_widget(
Paragraph::new("Return")
.style(return_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(return_border),
),
button_chunks[1],
);
// --- DIALOG ---
// Check the correct field name for showing the dialog
if app_state.ui.dialog.dialog_show {
// Pass all 7 arguments correctly
dialog::render_dialog(
f,
f.area(),
theme,
&app_state.ui.dialog.dialog_title,
&app_state.ui.dialog.dialog_message,
&app_state.ui.dialog.dialog_buttons, // Pass buttons slice
app_state.ui.dialog.dialog_active_button_index, // Pass active index
);
}
}

View File

@@ -0,0 +1,170 @@
// src/components/auth/register.rs
use crate::{
config::colors::themes::Theme,
state::pages::auth::RegisterState, // Use RegisterState
components::common::{dialog, autocomplete},
state::app::state::AppState,
state::pages::canvas_state::CanvasState,
modes::handlers::mode_manager::AppMode,
};
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
style::{Style, Modifier, Color},
widgets::{Block, BorderType, Borders, Paragraph},
Frame,
};
pub fn render_register(
f: &mut Frame,
area: Rect,
theme: &Theme,
state: &RegisterState, // Use RegisterState
app_state: &AppState,
is_edit_mode: bool,
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(Style::default().fg(theme.border))
.title(" Register ") // Update title
.style(Style::default().bg(theme.bg));
f.render_widget(block, area);
let inner_area = area.inner(Margin {
horizontal: 1,
vertical: 1,
});
// Adjust constraints for 4 fields + error + buttons
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(7), // Form (5 fields + padding)
Constraint::Length(1), // Help text line
Constraint::Length(1), // Error message
Constraint::Length(3), // Buttons
])
.split(inner_area);
// --- FORM RENDERING (Using render_canvas) ---
let active_field_rect = crate::components::handlers::canvas::render_canvas(
f,
chunks[0], // Area for the canvas
state, // The state object (RegisterState)
&[ // Field labels
"Username",
"Email*",
"Password*",
"Confirm Password",
"Role* (Tab)",
],
&state.current_field(), // Pass current field index
&state.inputs().iter().map(|s| *s).collect::<Vec<&String>>(), // Pass inputs directly
theme,
is_edit_mode,
);
// --- HELP TEXT ---
let help_text = Paragraph::new("* are optional fields")
.style(Style::default().fg(theme.fg))
.alignment(Alignment::Center);
f.render_widget(help_text, chunks[1]);
// --- ERROR MESSAGE ---
if let Some(err) = &state.error_message {
f.render_widget(
Paragraph::new(err.as_str())
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Center),
chunks[2],
);
}
// --- BUTTONS ---
let button_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(chunks[3]);
// Register Button
let register_button_index = 0;
let register_active = if app_state.ui.focus_outside_canvas {
app_state.focused_button_index== register_button_index
} else {
false
};
let mut register_style = Style::default().fg(theme.fg);
let mut register_border = Style::default().fg(theme.border);
if register_active {
register_style = register_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
register_border = register_border.fg(theme.accent);
}
f.render_widget(
Paragraph::new("Register") // Update button text
.style(register_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(register_border),
),
button_chunks[0],
);
// Return Button (logic remains similar)
let return_button_index = 1;
let return_active = if app_state.ui.focus_outside_canvas {
app_state.focused_button_index== return_button_index
} else {
false
};
let mut return_style = Style::default().fg(theme.fg);
let mut return_border = Style::default().fg(theme.border);
if return_active {
return_style = return_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
return_border = return_border.fg(theme.accent);
}
f.render_widget(
Paragraph::new("Return")
.style(return_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(return_border),
),
button_chunks[1],
);
// --- Render Autocomplete Dropdown (Draw AFTER buttons) ---
if app_state.current_mode == AppMode::Edit {
if let Some(suggestions) = state.get_suggestions() {
let selected = state.get_selected_suggestion_index();
if !suggestions.is_empty() {
if let Some(input_rect) = active_field_rect {
autocomplete::render_autocomplete_dropdown(f, input_rect, f.size(), theme, suggestions, selected);
}
}
}
}
// --- DIALOG --- (Keep dialog logic)
if app_state.ui.dialog.dialog_show {
dialog::render_dialog(
f,
f.area(),
theme,
&app_state.ui.dialog.dialog_title,
&app_state.ui.dialog.dialog_message,
&app_state.ui.dialog.dialog_buttons,
app_state.ui.dialog.dialog_active_button_index,
);
}
}

View File

@@ -0,0 +1,12 @@
// src/components/common.rs
pub mod command_line;
pub mod status_line;
pub mod background;
pub mod dialog;
pub mod autocomplete;
pub use command_line::*;
pub use status_line::*;
pub use background::*;
pub use dialog::*;
pub use autocomplete::*;

View File

@@ -0,0 +1,90 @@
// src/components/common/autocomplete.rs
use crate::config::colors::themes::Theme;
use ratatui::{
layout::Rect,
style::{Color, Modifier, Style},
widgets::{Block, List, ListItem, ListState},
Frame,
};
use unicode_width::UnicodeWidthStr;
/// Renders an opaque dropdown list for autocomplete suggestions.
pub fn render_autocomplete_dropdown(
f: &mut Frame,
input_rect: Rect,
frame_area: Rect,
theme: &Theme,
suggestions: &[String],
selected_index: Option<usize>,
) {
if suggestions.is_empty() {
return;
}
// --- Calculate Dropdown Size & Position ---
let max_suggestion_width = suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
let horizontal_padding: u16 = 2;
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
let dropdown_height = (suggestions.len() as u16).min(5);
let mut dropdown_area = Rect {
x: input_rect.x, // Align horizontally with input
y: input_rect.y + 1, // Position directly below input
width: dropdown_width,
height: dropdown_height,
};
// --- Clamping Logic (prevent rendering off-screen) ---
// Clamp vertically (if it goes below the frame)
if dropdown_area.bottom() > frame_area.height {
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height); // Try rendering above
}
// Clamp horizontally (if it goes past the right edge)
if dropdown_area.right() > frame_area.width {
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
}
// Ensure x is not negative (if clamping pushes it left)
dropdown_area.x = dropdown_area.x.max(0);
// Ensure y is not negative (if clamping pushes it up)
dropdown_area.y = dropdown_area.y.max(0);
// --- End Clamping ---
// Render a solid background block first to ensure opacity
let background_block = Block::default().style(Style::default().bg(Color::DarkGray));
f.render_widget(background_block, dropdown_area);
// Create list items, ensuring each has a defined background
let items: Vec<ListItem> = suggestions
.iter()
.enumerate()
.map(|(i, s)| {
let is_selected = selected_index == Some(i);
let s_width = s.width() as u16;
let padding_needed = dropdown_width.saturating_sub(s_width);
let padded_s = format!("{}{}", s, " ".repeat(padding_needed as usize));
ListItem::new(padded_s).style(if is_selected {
Style::default()
.fg(theme.bg) // Text color on highlight
.bg(theme.highlight) // Highlight background
.add_modifier(Modifier::BOLD)
} else {
// Style for non-selected items (matching background block)
Style::default()
.fg(theme.fg) // Text color on gray
.bg(Color::DarkGray) // Explicit gray background
})
})
.collect();
// Create the list widget (without its own block)
let list = List::new(items);
// State for managing selection highlight (still needed for logic)
let mut list_state = ListState::default();
list_state.select(selected_index);
// Render the list statefully *over* the background block
f.render_stateful_widget(list, dropdown_area, &mut list_state);
}

View File

@@ -0,0 +1,15 @@
// src/components/handlers/background.rs
use ratatui::{
widgets::{Block},
layout::Rect,
style::Style,
Frame,
};
use crate::config::colors::themes::Theme;
pub fn render_background(f: &mut Frame, area: Rect, theme: &Theme) {
let background = Block::default()
.style(Style::default().bg(theme.bg));
f.render_widget(background, area);
}

View File

@@ -5,7 +5,7 @@ use ratatui::{
layout::Rect,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
pub fn render_command_line(f: &mut Frame, area: Rect, input: &str, active: bool, theme: &Theme, message: &str) {
let prompt = if active {

View File

@@ -0,0 +1,171 @@
use crate::config::colors::themes::Theme;
use ratatui::{
layout::{Constraint, Direction, Layout, Margin, Rect},
prelude::Alignment,
style::{Modifier, Style},
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, Paragraph, Clear},
Frame,
};
use unicode_segmentation::UnicodeSegmentation; // For grapheme clusters
use unicode_width::UnicodeWidthStr; // For accurate width calculation
pub fn render_dialog(
f: &mut Frame,
area: Rect,
theme: &Theme,
dialog_title: &str,
dialog_message: &str,
dialog_buttons: &[String],
dialog_active_button_index: usize,
) {
// Calculate required height based on the actual number of lines in the message
let message_lines: Vec<_> = dialog_message.lines().collect();
let message_height = message_lines.len() as u16;
let button_row_height = if dialog_buttons.is_empty() { 0 } else { 3 };
let vertical_padding = 2; // Block borders (top/bottom)
let inner_vertical_margin = 2; // Margin inside block (top/bottom)
// Calculate required height based on actual message lines
let required_inner_height =
message_height + button_row_height + inner_vertical_margin;
let required_total_height = required_inner_height + vertical_padding;
// Use a fixed percentage width, clamped to min/max
let width_percentage: u16 = 60;
let dialog_width = (area.width * width_percentage / 100)
.max(20) // Minimum width
.min(area.width); // Maximum width
// Ensure height doesn't exceed available area
let dialog_height = required_total_height.min(area.height);
// Calculate centered area manually
let dialog_x = area.x + (area.width.saturating_sub(dialog_width)) / 2;
let dialog_y = area.y + (area.height.saturating_sub(dialog_height)) / 2;
let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);
// Clear the area first before drawing the dialog
f.render_widget(Clear, dialog_area);
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent))
.title(format!(" {} ", dialog_title)) // Add padding to title
.style(Style::default().bg(theme.bg));
f.render_widget(block, dialog_area);
// Calculate inner area *after* defining the block
let inner_area = dialog_area.inner(Margin {
horizontal: 2, // Left/Right padding inside border
vertical: 1, // Top/Bottom padding inside border
});
// Layout for Message and Buttons based on actual message height
let mut constraints = vec![
// Allocate space for message, ensuring at least 1 line height
Constraint::Length(message_height.max(1)), // Use actual calculated height
];
if button_row_height > 0 {
constraints.push(Constraint::Length(button_row_height));
}
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints)
.split(inner_area);
// Render Message
let available_width = inner_area.width as usize;
let ellipsis = "...";
let ellipsis_width = UnicodeWidthStr::width(ellipsis);
let processed_lines: Vec<Line> =
message_lines
.into_iter()
.map(|line| {
let line_width = UnicodeWidthStr::width(line);
if line_width > available_width {
// Truncate with ellipsis
let mut truncated_len = 0;
let mut current_width = 0;
// Iterate over graphemes to handle multi-byte characters correctly
for (idx, grapheme) in line.grapheme_indices(true) {
let grapheme_width = UnicodeWidthStr::width(grapheme);
if current_width + grapheme_width > available_width.saturating_sub(ellipsis_width) {
break; // Stop before exceeding width needed for text + ellipsis
}
current_width += grapheme_width;
truncated_len = idx + grapheme.len(); // Store the byte index of the end of the last fitting grapheme
}
let truncated_line = format!("{}{}", &line[..truncated_len], ellipsis);
Line::from(Span::styled(truncated_line, Style::default().fg(theme.fg)))
} else {
// Line fits, use it as is
Line::from(Span::styled(line, Style::default().fg(theme.fg)))
}
})
.collect();
let message_paragraph =
Paragraph::new(Text::from(processed_lines)).alignment(Alignment::Center);
// Render message in the first chunk
f.render_widget(message_paragraph, chunks[0]);
// Render Buttons if they exist and there's a chunk for them
if !dialog_buttons.is_empty() && chunks.len() > 1 {
let button_area = chunks[1];
let button_count = dialog_buttons.len();
// Use Ratio for potentially more even distribution with few buttons
let button_constraints = std::iter::repeat(Constraint::Ratio(
1,
button_count as u32,
))
.take(button_count)
.collect::<Vec<_>>();
let button_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(button_constraints)
.horizontal_margin(1) // Add space between buttons
.split(button_area);
for (i, button_label) in dialog_buttons.iter().enumerate() {
// Ensure we don't try to render into a non-existent chunk
if i >= button_chunks.len() {
break;
}
let is_active = i == dialog_active_button_index;
let (button_style, border_style) = if is_active {
(
Style::default()
.fg(theme.highlight)
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.accent), // Highlight border
)
} else {
(
Style::default().fg(theme.fg),
Style::default().fg(theme.border), // Normal border
)
};
let button_block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Plain)
.border_style(border_style);
f.render_widget(
Paragraph::new(button_label.as_str())
.block(button_block)
.style(button_style)
.alignment(Alignment::Center),
button_chunks[i],
);
}
}
}

View File

@@ -6,7 +6,7 @@ use ratatui::{
Frame,
text::{Line, Span},
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use std::path::Path;
pub fn render_status_line(

View File

@@ -0,0 +1,4 @@
// src/components/form.rs
pub mod form;
pub use form::*;

View File

@@ -1,18 +1,18 @@
// src/components/handlers/form.rs
// src/components/form/form.rs
use ratatui::{
widgets::{Paragraph, Block, Borders},
layout::{Layout, Constraint, Direction, Rect, Margin, Alignment},
style::Style,
Frame,
};
use crate::config::colors::Theme;
use crate::ui::form::FormState;
use super::canvas::render_canvas; // Changed to canvas
use crate::config::colors::themes::Theme;
use crate::state::pages::canvas_state::CanvasState;
use crate::components::handlers::canvas::render_canvas;
pub fn render_form(
f: &mut Frame,
area: Rect,
form_state: &FormState,
form_state: &impl CanvasState,
fields: &[&str],
current_field: &usize,
inputs: &[&String],

View File

@@ -1,14 +1,8 @@
// src/components/handlers.rs
pub mod form;
pub mod preview_card;
pub mod command_line;
pub mod status_line;
pub mod canvas;
pub mod sidebar;
pub mod buffer_list;
pub use command_line::render_command_line;
pub use form::*;
pub use preview_card::render_preview_card;
pub use status_line::render_status_line;
pub use canvas::*;
pub use sidebar::*;
pub use buffer_list::*;

View File

@@ -0,0 +1,61 @@
// src/components/handlers/buffer_list.rs
use crate::config::colors::themes::Theme;
use crate::state::app::state::AppState;
use ratatui::{
layout::{Alignment, Rect}, // Added Alignment
style::{Style, Stylize},
text::{Line, Span}, // Added Span
widgets::{Block, Borders, Paragraph}, // Changed widgets
Frame,
};
pub fn render_buffer_list(
f: &mut Frame,
area: Rect,
theme: &Theme,
app_state: &AppState,
) {
let mut current_buffer_name = "*scratch*"; // Default
// Determine the active buffer name based on UI state
if app_state.ui.show_intro {
current_buffer_name = "Intro";
} else if app_state.ui.show_register {
current_buffer_name = "Register";
} else if app_state.ui.show_login {
current_buffer_name = "Login";
} else if app_state.ui.show_admin {
current_buffer_name = "Admin Panel";
} else if app_state.ui.show_form {
// Potentially make this more specific later (e.g., show table name)
current_buffer_name = "Data Form";
}
// Add more conditions if other views exist
// Create the text line for the buffer name with padding
let buffer_text = Line::from(vec![
Span::raw(" "), // Left padding
Span::styled(
current_buffer_name,
Style::default().fg(theme.bg).bg(theme.highlight), // Style active tab
),
Span::raw(" "), // Right padding
]);
// Create the paragraph centered within the block
let paragraph = Paragraph::new(buffer_text)
.alignment(Alignment::Left) // Align text left, padding handles spacing
.block(
Block::default()
// Keep only the bottom border to act as a separator
.borders(Borders::BOTTOM)
.border_style(Style::default().fg(theme.secondary)),
)
// Set the background for the entire area (behind the text/block)
.style(Style::default().bg(theme.bg));
// Render the paragraph widget
f.render_widget(paragraph, area);
}

View File

@@ -7,19 +7,19 @@ use ratatui::{
Frame,
prelude::Alignment,
};
use crate::config::colors::Theme;
use crate::ui::form::FormState;
use crate::config::colors::themes::Theme;
use crate::state::pages::canvas_state::CanvasState;
pub fn render_canvas(
f: &mut Frame,
area: Rect,
form_state: &FormState,
form_state: &impl CanvasState,
fields: &[&str],
current_field: &usize,
inputs: &[&String],
theme: &Theme,
is_edit_mode: bool,
) {
) -> Option<Rect> {
// Split area into columns
let columns = Layout::default()
.direction(Direction::Horizontal)
@@ -27,13 +27,16 @@ pub fn render_canvas(
.split(area);
// Input container styling
let border_style = if form_state.has_unsaved_changes() {
Style::default().fg(theme.warning)
} else if is_edit_mode {
Style::default().fg(theme.accent)
} else {
Style::default().fg(theme.secondary)
};
let input_container = Block::default()
.borders(Borders::ALL)
.border_style(if is_edit_mode {
form_state.has_unsaved_changes.then(|| theme.warning).unwrap_or(theme.accent)
} else {
theme.secondary
})
.border_style(border_style)
.style(Style::default().bg(theme.bg));
// Input block dimensions
@@ -53,6 +56,8 @@ pub fn render_canvas(
.constraints(vec![Constraint::Length(1); fields.len()])
.split(input_area);
let mut active_field_input_rect = None;
// Render labels
for (i, field) in fields.iter().enumerate() {
let label = Paragraph::new(Line::from(Span::styled(
@@ -81,9 +86,12 @@ pub fn render_canvas(
f.render_widget(input_display, input_rows[i]);
if is_active {
let cursor_x = input_rows[i].x + form_state.current_cursor_pos as u16;
active_field_input_rect = Some(input_rows[i]);
let cursor_x = input_rows[i].x + form_state.current_cursor_pos() as u16;
let cursor_y = input_rows[i].y;
f.set_cursor_position((cursor_x, cursor_y));
}
}
active_field_input_rect
}

View File

@@ -1,33 +0,0 @@
// src/client/components/preview_card.rs
use ratatui::{
widgets::{Block, Borders, List, ListItem},
layout::Rect,
style::Style,
text::Text,
Frame,
};
use crate::config::colors::Theme;
pub fn render_preview_card(f: &mut Frame, area: Rect, fields: &[&String], theme: &Theme) {
let card = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(theme.border))
.title(" Preview Card ")
.style(Style::default().bg(theme.bg).fg(theme.fg));
let items = vec![
ListItem::new(Text::from(format!("Firma: {}", fields[0]))),
ListItem::new(Text::from(format!("Ulica: {}", fields[1]))),
ListItem::new(Text::from(format!("Mesto: {}", fields[2]))),
ListItem::new(Text::from(format!("PSC: {}", fields[3]))),
ListItem::new(Text::from(format!("ICO: {}", fields[4]))),
ListItem::new(Text::from(format!("Kontakt: {}", fields[5]))),
ListItem::new(Text::from(format!("Telefon: {}", fields[6]))),
];
let list = List::new(items)
.block(card)
.style(Style::default().bg(theme.bg).fg(theme.fg));
f.render_widget(list, area);
}

View File

@@ -1,27 +1,109 @@
// src/components/handlers/sidebar.rs
use ratatui::{
widgets::{Block, List, ListItem},
layout::Rect,
layout::{Rect, Direction, Layout, Constraint},
style::Style,
text::Text,
Frame,
};
use crate::config::colors::Theme;
use crate::config::colors::themes::Theme;
use common::proto::multieko2::table_definition::{ProfileTreeResponse};
use ratatui::text::{Span, Line};
pub fn render_sidebar(f: &mut Frame, area: Rect, theme: &Theme) {
let sidebar_block = Block::default()
.style(Style::default().bg(theme.bg));
// Reduced sidebar width
const SIDEBAR_WIDTH: u16 = 12;
let items = vec![
ListItem::new(Text::from(" Navigation ")),
ListItem::new(Text::from(" Search ")),
ListItem::new(Text::from(" Settings ")),
];
pub fn calculate_sidebar_layout(show_sidebar: bool, main_content_area: Rect) -> (Option<Rect>, Rect) {
if show_sidebar {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(SIDEBAR_WIDTH),
Constraint::Min(0),
])
.split(main_content_area);
(Some(chunks[0]), chunks[1])
} else {
(None, main_content_area)
}
}
pub fn render_sidebar(
f: &mut Frame,
area: Rect,
theme: &Theme,
profile_tree: &ProfileTreeResponse,
selected_profile: &Option<String>,
) {
let sidebar_block = Block::default().style(Style::default().bg(theme.bg));
let mut items = Vec::new();
if let Some(profile_name) = selected_profile {
// Existing code for when a profile is selected...
} else {
// Show full profile tree when no profile is selected (compact version)
for (profile_idx, profile) in profile_tree.profiles.iter().enumerate() {
// Profile header - more compact
items.push(ListItem::new(Line::from(vec![
Span::styled("", Style::default().fg(theme.accent)),
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
])));
// Tables with compact prefixes
for (table_idx, table) in profile.tables.iter().enumerate() {
let is_last_table = table_idx == profile.tables.len() - 1;
let is_last_profile = profile_idx == profile_tree.profiles.len() - 1;
// Shorter prefix characters
let prefix = match (is_last_profile, is_last_table) {
(true, true) => "",
(true, false) => "",
(false, true) => "│└",
(false, false) => "│├",
};
// Get table name without year prefix to save space
let display_name = if table.name.starts_with("2025_") {
&table.name[5..] // Skip "2025_" prefix
} else {
&table.name
};
let mut line = vec![
Span::styled(prefix, Style::default().fg(theme.fg)),
Span::styled(display_name, Style::default().fg(theme.fg)),
];
// Show a simple indicator for dependencies instead of listing them
if !table.depends_on.is_empty() {
line.push(Span::styled(
"",
Style::default().fg(theme.secondary)
));
}
items.push(ListItem::new(Line::from(line)));
}
// Compact separator between profiles
if profile_idx < profile_tree.profiles.len() - 1 {
items.push(ListItem::new(Line::from(
Span::styled("", Style::default().fg(theme.secondary))
)));
}
}
if profile_tree.profiles.is_empty() {
items.push(ListItem::new(Span::styled(
"No profiles",
Style::default().fg(theme.secondary)
)));
}
}
let list = List::new(items)
.block(sidebar_block)
.highlight_style(Style::default().fg(theme.highlight))
.highlight_symbol(">>");
.highlight_symbol(">");
f.render_widget(list, area);
}

View File

@@ -0,0 +1,4 @@
// src/components/intro.rs
pub mod intro;
pub use intro::*;

View File

@@ -0,0 +1,87 @@
// src/components/intro/intro.rs
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::Style,
text::{Line, Span},
widgets::{Block, BorderType, Borders, Paragraph},
prelude::Margin,
Frame,
};
use crate::config::colors::themes::Theme;
use crate::state::pages::intro::IntroState;
pub fn render_intro(f: &mut Frame, intro_state: &IntroState, area: Rect, theme: &Theme) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent))
.style(Style::default().bg(theme.bg));
let inner_area = block.inner(area);
f.render_widget(block, area);
// Center layout
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(40),
Constraint::Length(5),
Constraint::Percentage(40),
])
.split(inner_area);
// Title
let title = Line::from(vec![
Span::styled("multieko2", Style::default().fg(theme.highlight)),
Span::styled(" v", Style::default().fg(theme.fg)),
Span::styled(env!("CARGO_PKG_VERSION"), Style::default().fg(theme.secondary)),
]);
let title_para = Paragraph::new(title)
.alignment(Alignment::Center);
f.render_widget(title_para, chunks[1]);
// Buttons - now with 4 options
let button_area = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
])
.split(chunks[1].inner(Margin {
horizontal: 1,
vertical: 1
}));
let buttons = ["Continue", "Admin", "Login", "Register"];
for (i, &text) in buttons.iter().enumerate() {
render_button(f, button_area[i], text, intro_state.selected_option == i, theme);
}
}
fn render_button(f: &mut Frame, area: Rect, text: &str, selected: bool, theme: &Theme) {
let button_style = Style::default()
.fg(if selected { theme.highlight } else { theme.fg })
.bg(theme.bg)
.add_modifier(if selected {
ratatui::style::Modifier::BOLD
} else {
ratatui::style::Modifier::empty()
});
let border_style = Style::default()
.fg(if selected { theme.accent } else { theme.border });
let button = Paragraph::new(text)
.style(button_style)
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Double)
.border_style(border_style),
);
f.render_widget(button, area);
}

View File

@@ -1,5 +1,14 @@
// src/components/mod.rs
pub mod models;
pub mod handlers;
pub mod intro;
pub mod admin;
pub mod common;
pub mod form;
pub mod auth;
pub use handlers::*;
pub use intro::*;
pub use admin::*;
pub use common::*;
pub use form::*;
pub use auth::*;

View File

@@ -0,0 +1,7 @@
// src/config/binds.rs
pub mod config;
pub mod key_sequences;
pub use config::*;
pub use key_sequences::*;

View File

@@ -1,4 +1,4 @@
// client/src/config/config.rs
// src/config/binds/config.rs
use serde::Deserialize;
use std::collections::HashMap;
@@ -25,6 +25,8 @@ pub struct Config {
#[derive(Debug, Deserialize)]
pub struct ModeKeybindings {
#[serde(default)]
pub general: HashMap<String, Vec<String>>,
#[serde(default)]
pub read_only: HashMap<String, Vec<String>>,
#[serde(default)]
@@ -33,7 +35,6 @@ pub struct ModeKeybindings {
pub command: HashMap<String, Vec<String>>,
#[serde(default)]
pub common: HashMap<String, Vec<String>>,
// Store top-level keybindings that aren't in a specific mode section
#[serde(flatten)]
pub global: HashMap<String, Vec<String>>,
}
@@ -49,6 +50,17 @@ impl Config {
Ok(config)
}
pub fn get_general_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.general, key, modifiers)
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
}
/// Common actions for Edit/Read-only modes
pub fn get_common_action(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.common, key, modifiers)
}
/// Gets an action for a key in Read-Only mode, also checking common keybindings.
pub fn get_read_only_action_for_key(&self, key: KeyCode, modifiers: KeyModifiers) -> Option<&str> {
self.get_action_for_key_in_mode(&self.keybindings.read_only, key, modifiers)
@@ -70,6 +82,25 @@ impl Config {
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers))
}
/// Context-aware keybinding resolution
pub fn get_action_for_current_context(
&self,
is_edit_mode: bool,
command_mode: bool,
key: KeyCode,
modifiers: KeyModifiers
) -> Option<&str> {
match (command_mode, is_edit_mode) {
(true, _) => self.get_command_action_for_key(key, modifiers),
(_, true) => self.get_edit_action_for_key(key, modifiers)
.or_else(|| self.get_common_action(key, modifiers)),
_ => self.get_read_only_action_for_key(key, modifiers)
.or_else(|| self.get_common_action(key, modifiers))
// Add global bindings check for read-only mode
.or_else(|| self.get_action_for_key_in_mode(&self.keybindings.global, key, modifiers)),
}
}
/// Helper function to get an action for a key in a specific mode.
pub fn get_action_for_key_in_mode<'a>(
&self,
@@ -355,13 +386,13 @@ impl Config {
// Get string representations of the sequence
let sequence_str = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>()
.join("");
// Add the missing sequence_plus definition
let sequence_plus = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>()
.join("+");
@@ -414,7 +445,7 @@ impl Config {
// Special case for + format in bindings
if binding.contains('+') {
let normalized_sequence = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>();
let binding_parts: Vec<&str> = binding.split('+').collect();
@@ -442,7 +473,7 @@ impl Config {
// Get string representation of the sequence
let sequence_str = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>()
.join("");
@@ -491,7 +522,7 @@ impl Config {
if binding.contains('+') {
let binding_parts: Vec<&str> = binding.split('+').collect();
let sequence_parts = sequence.iter()
.map(|k| crate::config::key_sequences::key_to_string(k))
.map(|k| crate::config::binds::key_sequences::key_to_string(k))
.collect::<Vec<String>>();
if binding_parts.len() > sequence_parts.len() {

View File

@@ -1,68 +1,4 @@
// src/client/colors.rs
use ratatui::style::Color;
// src/config/colors.rs
pub mod themes;
#[derive(Debug, Clone)]
pub struct Theme {
pub bg: Color,
pub fg: Color,
pub accent: Color,
pub secondary: Color,
pub highlight: Color,
pub warning: Color,
pub border: Color,
}
impl Theme {
pub fn from_str(theme_name: &str) -> Self {
match theme_name.to_lowercase().as_str() {
"dark" => Self::dark(),
"high_contrast" => Self::high_contrast(),
_ => Self::light(),
}
}
// Default light theme
pub fn light() -> Self {
Self {
bg: Color::Rgb(245, 245, 245), // Light gray
fg: Color::Rgb(64, 64, 64), // Dark gray
accent: Color::Rgb(173, 216, 230), // Pastel blue
secondary: Color::Rgb(255, 165, 0), // Orange for secondary
highlight: Color::Rgb(152, 251, 152), // Pastel green
warning: Color::Rgb(255, 182, 193), // Pastel pink
border: Color::Rgb(220, 220, 220), // Light gray border
}
}
// High-contrast dark theme
pub fn dark() -> Self {
Self {
bg: Color::Rgb(30, 30, 30), // Dark background
fg: Color::Rgb(255, 255, 255), // White text
accent: Color::Rgb(0, 191, 255), // Bright blue
secondary: Color::Rgb(255, 215, 0), // Gold for secondary
highlight: Color::Rgb(50, 205, 50), // Bright green
warning: Color::Rgb(255, 99, 71), // Bright red
border: Color::Rgb(100, 100, 100), // Medium gray border
}
}
// High-contrast light theme
pub fn high_contrast() -> Self {
Self {
bg: Color::Rgb(255, 255, 255), // White background
fg: Color::Rgb(0, 0, 0), // Black text
accent: Color::Rgb(0, 0, 255), // Blue
secondary: Color::Rgb(255, 140, 0), // Dark orange for secondary
highlight: Color::Rgb(0, 128, 0), // Green
warning: Color::Rgb(255, 0, 0), // Red
border: Color::Rgb(0, 0, 0), // Black border
}
}
}
impl Default for Theme {
fn default() -> Self {
Self::light() // Default to light theme
}
}
pub use themes::*;

View File

@@ -0,0 +1,68 @@
// src/client/themes/colors.rs
use ratatui::style::Color;
#[derive(Debug, Clone)]
pub struct Theme {
pub bg: Color,
pub fg: Color,
pub accent: Color,
pub secondary: Color,
pub highlight: Color,
pub warning: Color,
pub border: Color,
}
impl Theme {
pub fn from_str(theme_name: &str) -> Self {
match theme_name.to_lowercase().as_str() {
"dark" => Self::dark(),
"high_contrast" => Self::high_contrast(),
_ => Self::light(),
}
}
// Default light theme
pub fn light() -> Self {
Self {
bg: Color::Rgb(245, 245, 245), // Light gray
fg: Color::Rgb(64, 64, 64), // Dark gray
accent: Color::Rgb(173, 216, 230), // Pastel blue
secondary: Color::Rgb(255, 165, 0), // Orange for secondary
highlight: Color::Rgb(152, 251, 152), // Pastel green
warning: Color::Rgb(255, 182, 193), // Pastel pink
border: Color::Rgb(220, 220, 220), // Light gray border
}
}
// High-contrast dark theme
pub fn dark() -> Self {
Self {
bg: Color::Rgb(30, 30, 30), // Dark background
fg: Color::Rgb(255, 255, 255), // White text
accent: Color::Rgb(0, 191, 255), // Bright blue
secondary: Color::Rgb(255, 215, 0), // Gold for secondary
highlight: Color::Rgb(50, 205, 50), // Bright green
warning: Color::Rgb(255, 99, 71), // Bright red
border: Color::Rgb(100, 100, 100), // Medium gray border
}
}
// High-contrast light theme
pub fn high_contrast() -> Self {
Self {
bg: Color::Rgb(255, 255, 255), // White background
fg: Color::Rgb(0, 0, 0), // Black text
accent: Color::Rgb(0, 0, 255), // Blue
secondary: Color::Rgb(255, 140, 0), // Dark orange for secondary
highlight: Color::Rgb(0, 128, 0), // Green
warning: Color::Rgb(255, 0, 0), // Red
border: Color::Rgb(0, 0, 0), // Black border
}
}
}
impl Default for Theme {
fn default() -> Self {
Self::light() // Default to light theme
}
}

View File

@@ -1,4 +1,4 @@
// src/config/mod.rs
pub mod binds;
pub mod colors;
pub mod config;
pub mod key_sequences;

View File

@@ -0,0 +1,2 @@
// src/functions/common.rs

View File

@@ -0,0 +1,6 @@
// src/functions/mod.rs
pub mod common;
pub mod modes;
pub use modes::*;

View File

@@ -0,0 +1,8 @@
// src/functions/modes.rs
pub mod read_only;
pub mod edit;
pub mod navigation;
pub use read_only::*;
pub use edit::*;

View File

@@ -0,0 +1,4 @@
// src/functions/modes/edit.rs
pub mod form_e;
pub mod auth_e;

View File

@@ -0,0 +1,483 @@
// src/functions/modes/edit/auth_e.rs
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::RegisterState;
use crate::tui::functions::common::form::{revert, save};
use crossterm::event::{KeyCode, KeyEvent};
use std::any::Any;
pub async fn execute_common_action<S: CanvasState + Any>(
action: &str,
state: &mut S,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" | "revert" => {
if !state.has_unsaved_changes() {
return Ok("No changes to save or revert.".to_string());
}
if let Some(form_state) =
(state as &mut dyn Any).downcast_mut::<FormState>()
{
match action {
"save" => {
let outcome = save(
form_state,
grpc_client,
current_position,
total_count,
)
.await?;
let message = format!("Save successful: {:?}", outcome); // Simple message for now
Ok(message)
}
"revert" => {
revert(
form_state,
grpc_client,
current_position,
total_count,
)
.await
}
_ => unreachable!(),
}
} else {
Ok(format!(
"Action '{}' not implemented for this state type.",
action
))
}
}
_ => Ok(format!("Common action '{}' not handled here.", action)),
}
}
pub async fn execute_edit_action<S: CanvasState + Any + Send>(
action: &str,
key: KeyEvent,
state: &mut S,
ideal_cursor_column: &mut usize,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"insert_char" => {
if let KeyCode::Char(c) = key.code {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
state.set_current_cursor_pos(cursor_pos + 1);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = state.current_cursor_pos();
}
} else {
return Ok("Error: insert_char called without a char key."
.to_string());
}
Ok("working?".to_string())
}
"delete_char_backward" => {
if state.current_cursor_pos() > 0 {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
let new_pos = cursor_pos - 1;
state.set_current_cursor_pos(new_pos);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = new_pos;
}
}
Ok("".to_string())
}
"delete_char_forward" => {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
chars.remove(cursor_pos);
*field_value = chars.into_iter().collect();
state.set_has_unsaved_changes(true);
*ideal_cursor_column = cursor_pos;
}
Ok("".to_string())
}
"next_field" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = (current_field + 1) % num_fields;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"prev_field" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = if current_field == 0 {
num_fields - 1
} else {
current_field - 1
};
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_left" => {
let new_pos = state.current_cursor_pos().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
if current_pos < current_input.len() {
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_up" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = current_field.saturating_sub(1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_down" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.current_field() + 1).min(num_fields - 1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
let new_pos = current_input.len();
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_first_line" => {
let num_fields = state.fields().len();
if num_fields > 0 {
state.set_current_field(0);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("Moved to first field".to_string())
}
"move_last_line" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = num_fields - 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("Moved to last field".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(
current_input,
state.current_cursor_pos(),
);
let final_pos = new_pos.min(current_input.len());
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
let final_pos = if new_pos == current_pos {
find_word_end(current_input, new_pos + 1)
} else {
new_pos
};
let max_valid_index = current_input.len().saturating_sub(1);
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("Moved to previous word end".to_string())
}
// --- Autocomplete Actions ---
"suggestion_down" | "suggestion_up" | "select_suggestion" | "exit_suggestion_mode" => {
// Attempt to downcast to RegisterState to handle suggestion logic here
if let Some(register_state) = (state as &mut dyn Any).downcast_mut::<RegisterState>() {
// Only handle if it's the role field (index 4)
if register_state.current_field() == 4 {
match action {
"suggestion_down" if register_state.in_suggestion_mode => {
let max_index = register_state.role_suggestions.len().saturating_sub(1);
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
register_state.selected_suggestion_index = Some(if current_index >= max_index { 0 } else { current_index + 1 });
Ok("Suggestion changed down".to_string())
}
"suggestion_up" if register_state.in_suggestion_mode => {
let max_index = register_state.role_suggestions.len().saturating_sub(1);
let current_index = register_state.selected_suggestion_index.unwrap_or(0);
register_state.selected_suggestion_index = Some(if current_index == 0 { max_index } else { current_index.saturating_sub(1) });
Ok("Suggestion changed up".to_string())
}
"select_suggestion" if register_state.in_suggestion_mode => {
if let Some(index) = register_state.selected_suggestion_index {
if let Some(selected_role) = register_state.role_suggestions.get(index).cloned() {
register_state.role = selected_role.clone(); // Update the role field
register_state.in_suggestion_mode = false; // Exit suggestion mode
register_state.show_role_suggestions = false; // Hide suggestions
register_state.selected_suggestion_index = None; // Clear selection
Ok(format!("Selected role: {}", selected_role)) // Return success message
} else {
Ok("Selected suggestion index out of bounds.".to_string()) // Error case
}
} else {
Ok("No suggestion selected".to_string())
}
}
"exit_suggestion_mode" => { // Handle Esc or other conditions
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
register_state.in_suggestion_mode = false;
Ok("Suggestions hidden".to_string())
}
_ => {
// Action is suggestion-related but state doesn't match (e.g., not in suggestion mode)
Ok("Suggestion action ignored: State mismatch.".to_string())
}
}
} else {
// It's RegisterState, but not the role field
Ok("Suggestion action ignored: Not on role field.".to_string())
}
} else {
// Downcast failed - this action is only for RegisterState
Ok(format!("Action '{}' not applicable for this state type.", action))
}
}
// --- End Autocomplete Actions ---
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
}
}
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos >= len {
return len;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
if get_char_type(chars[pos]) == CharType::Whitespace {
pos = find_next_word_start(text, pos);
}
if pos >= len {
return len.saturating_sub(1);
}
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos - 1
} else {
0
}
}

View File

@@ -0,0 +1,440 @@
// src/functions/modes/edit/form_e.rs
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::tui::functions::common::form::{revert, save};
use crate::tui::functions::common::form::SaveOutcome;
use crate::modes::handlers::event::EventOutcome;
use crossterm::event::{KeyCode, KeyEvent};
use std::any::Any;
pub async fn execute_common_action<S: CanvasState + Any>(
action: &str,
state: &mut S,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
match action {
"save" | "revert" => {
if !state.has_unsaved_changes() {
return Ok(EventOutcome::Ok("No changes to save or revert.".to_string()));
}
if let Some(form_state) =
(state as &mut dyn Any).downcast_mut::<FormState>()
{
match action {
"save" => {
let save_result = save(
form_state,
grpc_client,
current_position,
total_count,
).await;
match save_result {
Ok(save_outcome) => {
let message = match save_outcome {
SaveOutcome::NoChange => "No changes to save.".to_string(),
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
};
Ok(EventOutcome::DataSaved(save_outcome, message))
}
Err(e) => Err(e),
}
}
"revert" => {
let revert_result = revert(
form_state,
grpc_client,
current_position,
total_count,
).await;
match revert_result {
Ok(message) => Ok(EventOutcome::Ok(message)),
Err(e) => Err(e),
}
}
_ => unreachable!(),
}
} else {
Ok(EventOutcome::Ok(format!(
"Action '{}' not implemented for this state type.",
action
)))
}
}
_ => Ok(EventOutcome::Ok(format!("Common action '{}' not handled here.", action))),
}
}
pub async fn execute_edit_action<S: CanvasState>(
action: &str,
key: KeyEvent,
state: &mut S,
ideal_cursor_column: &mut usize,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"insert_char" => {
if let KeyCode::Char(c) = key.code {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
state.set_current_cursor_pos(cursor_pos + 1);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = state.current_cursor_pos();
}
} else {
return Ok("Error: insert_char called without a char key."
.to_string());
}
Ok("".to_string())
}
"delete_char_backward" => {
if state.current_cursor_pos() > 0 {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
let new_pos = cursor_pos - 1;
state.set_current_cursor_pos(new_pos);
state.set_has_unsaved_changes(true);
*ideal_cursor_column = new_pos;
}
}
Ok("".to_string())
}
"delete_char_forward" => {
let cursor_pos = state.current_cursor_pos();
let field_value = state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
chars.remove(cursor_pos);
*field_value = chars.into_iter().collect();
state.set_has_unsaved_changes(true);
*ideal_cursor_column = cursor_pos;
}
Ok("".to_string())
}
"next_field" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = (current_field + 1) % num_fields;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"prev_field" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = if current_field == 0 {
num_fields - 1
} else {
current_field - 1
};
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_left" => {
let new_pos = state.current_cursor_pos().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
if current_pos < current_input.len() {
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_up" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let current_field = state.current_field();
let new_field = current_field.saturating_sub(1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_down" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = (state.current_field() + 1).min(num_fields - 1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
let new_pos = current_input.len();
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_first_line" => {
let num_fields = state.fields().len();
if num_fields > 0 {
state.set_current_field(0);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("Moved to first field".to_string())
}
"move_last_line" => {
let num_fields = state.fields().len();
if num_fields > 0 {
let new_field = num_fields - 1;
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_pos = current_input.len();
state.set_current_cursor_pos(
(*ideal_cursor_column).min(max_pos),
);
}
Ok("Moved to last field".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(
current_input,
state.current_cursor_pos(),
);
let final_pos = new_pos.min(current_input.len());
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
let final_pos = if new_pos == current_pos {
find_word_end(current_input, new_pos + 1)
} else {
new_pos
};
let max_valid_index = current_input.len().saturating_sub(1);
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("Moved to previous word end".to_string())
}
_ => Ok(format!("Unknown or unhandled edit action: {}", action)),
}
}
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos >= len {
return len;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < len && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
if get_char_type(chars[pos]) == CharType::Whitespace {
pos = find_next_word_start(text, pos);
}
if pos >= len {
return len.saturating_sub(1);
}
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[pos]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[pos]) != CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos - 1
} else {
0
}
}

View File

@@ -0,0 +1,3 @@
// src/functions/modes/navigation.rs
// pub mod admin_nav;

View File

@@ -0,0 +1 @@
// src/functions/modes/navigation/admin_nav.rs

View File

@@ -0,0 +1,4 @@
// src/functions/modes/read_only.rs
pub mod auth_ro;
pub mod form_ro;

View File

@@ -0,0 +1,367 @@
// src/functions/modes/read_only/auth_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::pages::canvas_state::CanvasState;
use crate::state::app::state::AppState;
use std::error::Error;
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
pub async fn execute_action<S: CanvasState>(
action: &str,
app_state: &mut AppState,
state: &mut S,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
) -> Result<String, Box<dyn Error>> {
match action {
"previous_entry" | "next_entry" => {
key_sequence_tracker.reset();
Ok(format!(
"Action '{}' should be handled by context-specific logic",
action
))
}
"move_up" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate.".to_string());
}
let current_field = state.current_field();
let new_field = current_field.saturating_sub(1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
Ok("move up from functions/modes/read_only/auth_ro.rs".to_string())
}
"move_down" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate.".to_string());
}
let current_field = state.current_field();
let last_field_index = num_fields - 1;
if current_field == last_field_index {
// Already on the last field, move focus outside
app_state.ui.focus_outside_canvas = true;
app_state.focused_button_index= 0;
key_sequence_tracker.reset();
Ok("Focus moved below canvas".to_string())
} else {
// Move to the next field within the canvas
let new_field = (current_field + 1).min(last_field_index);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
Ok("".to_string()) // Clear previous debug message
}
}
"move_first_line" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate to.".to_string());
}
state.set_current_field(0);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_last_line" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate to.".to_string());
}
let last_field_index = num_fields - 1;
state.set_current_field(last_field_index);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = state.current_cursor_pos();
let new_pos = current_pos.saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
if !current_input.is_empty()
&& current_pos < current_input.len().saturating_sub(1)
{
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos =
find_next_word_start(current_input, state.current_cursor_pos());
let final_pos = new_pos.min(current_input.len().saturating_sub(1));
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
let final_pos = if new_pos != current_pos {
new_pos
} else {
find_word_end(current_input, new_pos + 1)
};
let max_valid_index = current_input.len().saturating_sub(1);
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("Moved to previous word end".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = current_input.len().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
} else {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
}
Ok("".to_string())
}
_ => {
key_sequence_tracker.reset();
Ok(format!("Unknown read-only action: {}", action))
},
}
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
let current_pos = current_pos.min(chars.len());
if current_pos == chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
let next_start = find_next_word_start(text, current_pos);
if next_start >= chars.len() {
return chars.len().saturating_sub(1);
}
let mut pos = next_start;
let word_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
let original_pos = pos;
let current_type = get_char_type(chars[pos]);
if current_type != CharType::Whitespace {
while pos < len && get_char_type(chars[pos]) == current_type {
pos += 1;
}
return pos.saturating_sub(1);
}
pos = find_next_word_start(text, pos);
if pos >= len {
return len.saturating_sub(1);
}
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
0
} else {
pos
}
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[0]) != CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos - 1
} else {
0
}
}

View File

@@ -0,0 +1,353 @@
// src/functions/modes/read_only/form_ro.rs
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::state::pages::canvas_state::CanvasState;
use std::error::Error;
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
pub async fn execute_action<S: CanvasState>(
action: &str,
state: &mut S,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
) -> Result<String, Box<dyn Error>> {
match action {
"previous_entry" | "next_entry" => {
key_sequence_tracker.reset();
Ok(format!(
"Action '{}' should be handled by context-specific logic",
action
))
}
"move_up" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate.".to_string());
}
let current_field = state.current_field();
let new_field = current_field.saturating_sub(1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
Ok("".to_string())
}
"move_down" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate.".to_string());
}
let current_field = state.current_field();
let new_field = (current_field + 1).min(num_fields - 1);
state.set_current_field(new_field);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
Ok("".to_string())
}
"move_first_line" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate to.".to_string());
}
state.set_current_field(0);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_last_line" => {
key_sequence_tracker.reset();
let num_fields = state.fields().len();
if num_fields == 0 {
return Ok("No fields to navigate to.".to_string());
}
let last_field_index = num_fields - 1;
state.set_current_field(last_field_index);
let current_input = state.get_current_input();
let max_cursor_pos = if current_input.is_empty() {
0
} else {
current_input.len().saturating_sub(1)
};
let new_pos = (*ideal_cursor_column).min(max_cursor_pos);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = state.current_cursor_pos();
let new_pos = current_pos.saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = state.get_current_input();
let current_pos = state.current_cursor_pos();
if !current_input.is_empty()
&& current_pos < current_input.len().saturating_sub(1)
{
let new_pos = current_pos + 1;
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_next" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos =
find_next_word_start(current_input, state.current_cursor_pos());
let final_pos = new_pos.min(current_input.len().saturating_sub(1));
state.set_current_cursor_pos(final_pos);
*ideal_cursor_column = final_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let current_pos = state.current_cursor_pos();
let new_pos = find_word_end(current_input, current_pos);
let final_pos = if new_pos != current_pos {
new_pos
} else {
find_word_end(current_input, new_pos + 1)
};
let max_valid_index = current_input.len().saturating_sub(1);
let clamped_pos = final_pos.min(max_valid_index);
state.set_current_cursor_pos(clamped_pos);
*ideal_cursor_column = clamped_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(
current_input,
state.current_cursor_pos(),
);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
}
Ok("Moved to previous word end".to_string())
}
"move_line_start" => {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
Ok("".to_string())
}
"move_line_end" => {
let current_input = state.get_current_input();
if !current_input.is_empty() {
let new_pos = current_input.len().saturating_sub(1);
state.set_current_cursor_pos(new_pos);
*ideal_cursor_column = new_pos;
} else {
state.set_current_cursor_pos(0);
*ideal_cursor_column = 0;
}
Ok("".to_string())
}
_ => {
key_sequence_tracker.reset();
Ok(format!("Unknown read-only action: {}", action))
},
}
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
let current_pos = current_pos.min(chars.len());
if current_pos == chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_next_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
let next_start = find_next_word_start(text, current_pos);
if next_start >= chars.len() {
return chars.len().saturating_sub(1);
}
let mut pos = next_start;
let word_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(chars.len().saturating_sub(1))
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
let len = chars.len();
if len == 0 {
return 0;
}
let mut pos = current_pos.min(len - 1);
let original_pos = pos;
let current_type = get_char_type(chars[pos]);
if current_type != CharType::Whitespace {
while pos < len && get_char_type(chars[pos]) == current_type {
pos += 1;
}
return pos.saturating_sub(1);
}
pos = find_next_word_start(text, pos);
if pos >= len {
return len.saturating_sub(1);
}
let word_type = get_char_type(chars[pos]);
while pos < len && get_char_type(chars[pos]) == word_type {
pos += 1;
}
pos.saturating_sub(1).min(len.saturating_sub(1))
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
0
} else {
pos
}
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos == 0 && get_char_type(chars[0]) == CharType::Whitespace {
return 0;
}
if pos == 0 && get_char_type(chars[0]) != CharType::Whitespace {
return 0;
}
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos - 1
} else {
0
}
}

View File

@@ -5,6 +5,8 @@ pub mod config;
pub mod state;
pub mod components;
pub mod modes;
pub mod functions;
pub mod services;
pub use ui::run_ui;

View File

@@ -0,0 +1,4 @@
// src/client/modes/canvas.rs
pub mod edit;
pub mod common_mode;
pub mod read_only;

View File

@@ -0,0 +1,96 @@
// src/modes/canvas/common_mode.rs
use crate::tui::terminal::core::TerminalCore;
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState, auth::AuthState};
use crate::state::app::state::AppState;
use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::form::SaveOutcome;
use crate::tui::functions::common::{
form::{save as form_save, revert as form_revert},
login::{save as login_save, revert as login_revert},
register::{save as register_save, revert as register_revert},
};
pub async fn handle_core_action(
action: &str,
form_state: &mut FormState,
auth_state: &mut AuthState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
grpc_client: &mut GrpcClient,
auth_client: &mut AuthClient,
terminal: &mut TerminalCore,
app_state: &mut AppState,
current_position: &mut u64,
total_count: u64,
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
match action {
"save" => {
if app_state.ui.show_login {
let message = login_save(auth_state, login_state, auth_client, app_state).await?;
Ok(EventOutcome::Ok(message))
} else if app_state.ui.show_register {
let message = register_save(register_state, auth_client, app_state).await?;
Ok(EventOutcome::Ok(message))
} else {
let save_outcome = form_save(
form_state,
grpc_client,
current_position,
total_count,
).await?;
let message = match save_outcome {
SaveOutcome::NoChange => "No changes to save.".to_string(),
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
};
Ok(EventOutcome::DataSaved(save_outcome, message))
}
},
"force_quit" => {
terminal.cleanup()?;
Ok(EventOutcome::Exit("Force exiting without saving.".to_string()))
},
"save_and_quit" => {
let message = if app_state.ui.show_login {
login_save(auth_state, login_state, auth_client, app_state).await?
} else if app_state.ui.show_register {
register_save(register_state, auth_client, app_state).await?
} else {
let save_outcome = form_save(
form_state,
grpc_client,
current_position,
total_count,
).await?;
match save_outcome {
SaveOutcome::NoChange => "No changes to save.".to_string(),
SaveOutcome::UpdatedExisting => "Entry updated.".to_string(),
SaveOutcome::CreatedNew(_) => "New entry created.".to_string(),
}
};
terminal.cleanup()?;
Ok(EventOutcome::Exit(format!("{}. Exiting application.", message)))
},
"revert" => {
if app_state.ui.show_login {
let message = login_revert(login_state, app_state).await;
Ok(EventOutcome::Ok(message))
} else if app_state.ui.show_register {
let message = register_revert(register_state, app_state).await;
Ok(EventOutcome::Ok(message))
} else {
let message = form_revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
Ok(EventOutcome::Ok(message))
}
},
_ => Ok(EventOutcome::Ok(format!("Core action not handled: {}", action))),
}
}

View File

@@ -0,0 +1,206 @@
// src/modes/canvas/edit.rs
use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::{auth::{LoginState, RegisterState}};
use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::functions::modes::edit::{auth_e, form_e};
use crate::modes::handlers::event::EventOutcome;
use crate::state::app::state::AppState;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
pub async fn handle_edit_event(
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
ideal_cursor_column: &mut usize,
command_message: &mut String,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
app_state: &AppState,
) -> Result<String, Box<dyn std::error::Error>> {
// Global command mode check
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
&config.keybindings.global,
key.code,
key.modifiers
) {
*command_message = "Switching to Command Mode...".to_string();
return Ok(command_message.clone());
}
// Common actions (save/revert)
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key.code,
key.modifiers
) {
if matches!(action, "save" | "revert") {
let message = if app_state.ui.show_login {
auth_e::execute_common_action(
action,
login_state,
grpc_client,
current_position,
total_count
).await
} else if app_state.ui.show_register {
auth_e::execute_common_action(
action,
register_state,
grpc_client,
current_position,
total_count
).await
} else {
form_e::execute_common_action(
action,
form_state, // Concrete FormState
grpc_client,
current_position,
total_count
).await
.map(|outcome| match outcome {
EventOutcome::Ok(msg) => msg,
EventOutcome::Exit(msg) => format!("Exit requested: {}", msg),
EventOutcome::DataSaved(save_outcome, msg) => format!("Data saved ({:?}): {}", save_outcome, msg),
EventOutcome::ButtonSelected { context, index } => {
"Unexpected action in edit mode".to_string()
}
})
}?;
return Ok(message);
}
}
// Edit-specific actions
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
// --- Special Handling for Tab/Shift+Tab in Role Field ---
if app_state.ui.show_register && register_state.current_field() == 4 {
if !register_state.in_suggestion_mode && key.code == KeyCode::Tab && key.modifiers == KeyModifiers::NONE {
register_state.update_role_suggestions();
if !register_state.role_suggestions.is_empty() {
register_state.in_suggestion_mode = true;
register_state.selected_suggestion_index = Some(0); // Select first suggestion
return Ok("Suggestions shown".to_string());
} else {
return Ok("No suggestions available".to_string());
}
}
}
// --- End Special Handling ---
return if app_state.ui.show_login {
auth_e::execute_edit_action(
action,
key,
login_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else if app_state.ui.show_register {
auth_e::execute_edit_action(
action,
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else {
form_e::execute_edit_action(
action,
key,
form_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
};
}
// Character insertion
if let KeyCode::Char(_) = key.code {
// If in suggestion mode, exit it before inserting char
if app_state.ui.show_register && register_state.in_suggestion_mode {
register_state.in_suggestion_mode = false;
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
}
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
// --- End Autocomplete Trigger ---
return if app_state.ui.show_login {
auth_e::execute_edit_action(
"insert_char",
key,
login_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else if app_state.ui.show_register {
auth_e::execute_edit_action(
"insert_char",
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else {
form_e::execute_edit_action(
"insert_char",
key,
form_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
};
}
// Handle Backspace/Delete for Autocomplete Trigger
if matches!(key.code, KeyCode::Backspace | KeyCode::Delete) {
// If in suggestion mode, exit it before deleting char
if app_state.ui.show_register && register_state.in_suggestion_mode {
register_state.in_suggestion_mode = false;
register_state.show_role_suggestions = false;
register_state.selected_suggestion_index = None;
}
let is_role_field = app_state.ui.show_register && register_state.current_field() == 4;
let action_str = if key.code == KeyCode::Backspace { "backspace" } else { "delete_char" };
// Execute the action first
let result = if app_state.ui.show_register {
auth_e::execute_edit_action(
action_str,
key,
register_state,
ideal_cursor_column,
grpc_client,
current_position,
total_count
).await
} else {
// Handle for login/form if needed, assuming auth_e covers RegisterState
Ok("Action not applicable here".to_string()) // Placeholder
}?;
return Ok(result);
}
Ok(command_message.clone())
}

View File

@@ -0,0 +1,248 @@
// src/modes/canvas/read_only.rs
use crate::config::binds::config::Config;
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::{canvas_state::CanvasState, auth::RegisterState};
use crate::state::pages::auth::LoginState;
use crate::state::pages::form::FormState;
use crate::state::app::state::AppState;
use crate::functions::modes::read_only::{auth_ro, form_ro};
use crossterm::event::KeyEvent;
pub async fn handle_read_only_event(
app_state: &mut AppState,
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
command_message: &mut String,
edit_mode_cooldown: &mut bool,
ideal_cursor_column: &mut usize,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
*edit_mode_cooldown = true;
*command_message = "Entering Edit mode".to_string();
return Ok((false, command_message.clone()));
}
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
let (current_input, current_pos) = if app_state.ui.show_login { // Check Login first
(
login_state.get_current_input(),
login_state.current_cursor_pos(),
)
} else if app_state.ui.show_register { // Then check Register
(
register_state.get_current_input(),
register_state.current_cursor_pos(),
)
} else {
(
form_state.get_current_input(),
form_state.current_cursor_pos(),
) // Default to Form
};
if !current_input.is_empty() && current_pos < current_input.len() {
if app_state.ui.show_login {
login_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = login_state.current_cursor_pos();
} else if app_state.ui.show_register {
register_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = register_state.current_cursor_pos();
} else { // Default to Form
form_state.set_current_cursor_pos(current_pos + 1);
*ideal_cursor_column = form_state.current_cursor_pos();
}
}
*edit_mode_cooldown = true;
*command_message = "Entering Edit mode (after cursor)".to_string();
return Ok((false, command_message.clone()));
}
const CONTEXT_ACTIONS_FORM: &[&str] = &[
"previous_entry",
"next_entry",
];
const CONTEXT_ACTIONS_LOGIN: &[&str] = &[
"previous_entry",
"next_entry",
];
// Add context actions specific to register if needed, otherwise reuse login/form ones
const CONTEXT_ACTIONS_REGISTER: &[&str] = &[
// Add actions like "next_field", "prev_field" if handled differently than general read-only
];
if key.modifiers.is_empty() {
key_sequence_tracker.add_key(key.code);
let sequence = key_sequence_tracker.get_sequence();
if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action(
action,
form_state,
grpc_client,
current_position,
total_count,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
crate::tui::functions::login::handle_action(action).await?
} else if app_state.ui.show_register{
auth_ro::execute_action(
action,
app_state,
register_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
).await?
} else if app_state.ui.show_login {
auth_ro::execute_action(
action,
app_state,
login_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else {
form_ro::execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
};
key_sequence_tracker.reset();
return Ok((false, result));
}
if config.is_key_sequence_prefix(&sequence) {
return Ok((false, command_message.clone()));
}
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action(
action,
form_state,
grpc_client,
current_position,
total_count,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
crate::tui::functions::login::handle_action(action).await?
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
auth_ro::execute_action(
action,
app_state,
register_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
).await?
} else if app_state.ui.show_login { // Handle login general actions
auth_ro::execute_action(
action,
app_state,
login_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else {
form_ro::execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
};
key_sequence_tracker.reset();
return Ok((false, result));
}
}
key_sequence_tracker.reset();
} else {
key_sequence_tracker.reset();
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = if app_state.ui.show_form && CONTEXT_ACTIONS_FORM.contains(&action) {
crate::tui::functions::form::handle_action(
action,
form_state,
grpc_client,
current_position,
total_count,
ideal_cursor_column,
)
.await?
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
crate::tui::functions::login::handle_action(action).await?
} else if app_state.ui.show_register /* && CONTEXT_ACTIONS_REGISTER.contains(&action) */ { // Handle register general actions
auth_ro::execute_action(
action,
app_state,
register_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
).await?
} else if app_state.ui.show_login { // Handle login general actions
auth_ro::execute_action(
action,
app_state,
login_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
} else {
form_ro::execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
)
.await?
};
return Ok((false, result));
}
}
if !*edit_mode_cooldown {
let default_key = "i".to_string();
let edit_key = config
.keybindings
.read_only
.get("enter_edit_mode_before")
.and_then(|keys| keys.first())
.map(|k| k.to_string())
.unwrap_or(default_key);
*command_message = format!("Read-only mode - press {} to edit", edit_key);
}
*edit_mode_cooldown = false;
Ok((false, command_message.clone()))
}

View File

@@ -0,0 +1,6 @@
// src/client/modes/common.rs
pub mod command_mode;
pub mod highlight;
pub mod commands;
pub use commands::*;

View File

@@ -1,30 +1,37 @@
// src/modes/handlers/command_mode.rs
// src/modes/common/command_mode.rs
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::grpc_client::GrpcClient;
use crate::config::config::Config;
use crate::ui::handlers::form::FormState;
use super::common;
use crate::config::binds::config::Config;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
use crate::state::{app::state::AppState, pages::auth::LoginState, pages::auth::RegisterState};
use crate::modes::common::commands::CommandHandler;
use crate::tui::terminal::core::TerminalCore;
use crate::tui::functions::common::form::{save, revert};
use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::form::SaveOutcome;
use std::error::Error;
pub async fn handle_command_event(
key: KeyEvent,
config: &Config,
app_state: &AppState,
login_state: &LoginState,
register_state: &RegisterState,
form_state: &mut FormState,
command_input: &mut String,
command_message: &mut String,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
command_handler: &mut CommandHandler,
terminal: &mut TerminalCore,
current_position: &mut u64,
total_count: u64,
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
// Return value: (should_exit, message, should_exit_command_mode)
) -> Result<EventOutcome, Box<dyn Error>> {
// Exit command mode (via configurable keybinding)
if config.is_exit_command_mode(key.code, key.modifiers) {
command_input.clear();
*command_message = "".to_string();
return Ok((false, "".to_string(), true));
return Ok(EventOutcome::Ok("Exited command mode".to_string()));
}
// Execute command (via configurable keybinding, defaults to Enter)
@@ -32,10 +39,14 @@ pub async fn handle_command_event(
return process_command(
config,
form_state,
app_state,
login_state,
register_state,
command_input,
command_message,
grpc_client,
is_saved,
command_handler,
terminal,
current_position,
total_count,
).await;
@@ -44,7 +55,7 @@ pub async fn handle_command_event(
// Backspace (via configurable keybinding, defaults to Backspace)
if config.is_command_backspace(key.code, key.modifiers) {
command_input.pop();
return Ok((false, "".to_string(), false));
return Ok(EventOutcome::Ok("".to_string()));
}
// Regular character input - accept any character in command mode
@@ -52,29 +63,33 @@ pub async fn handle_command_event(
// Accept regular or shifted characters (e.g., 'a' or 'A')
if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT {
command_input.push(c);
return Ok((false, "".to_string(), false));
return Ok(EventOutcome::Ok("".to_string()));
}
}
// Ignore all other keys
Ok((false, "".to_string(), false))
Ok(EventOutcome::Ok("".to_string()))
}
async fn process_command(
config: &Config,
form_state: &mut FormState,
app_state: &AppState,
login_state: &LoginState,
register_state: &RegisterState,
command_input: &mut String,
command_message: &mut String,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
command_handler: &mut CommandHandler,
terminal: &mut TerminalCore,
current_position: &mut u64,
total_count: u64,
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
) -> Result<EventOutcome, Box<dyn Error>> {
// Clone the trimmed command to avoid borrow issues
let command = command_input.trim().to_string();
if command.is_empty() {
*command_message = "Empty command".to_string();
return Ok((false, command_message.clone(), false));
return Ok(EventOutcome::Ok(command_message.clone()));
}
// Get the action for the command (now checks global and common bindings too)
@@ -82,51 +97,53 @@ async fn process_command(
.unwrap_or("unknown");
match action {
"force_quit" | "save_and_quit" | "quit" => {
let (should_exit, message) = command_handler
.handle_command(
action,
terminal,
app_state,
form_state,
login_state,
register_state,
)
.await?;
command_input.clear();
if should_exit {
Ok(EventOutcome::Exit(message))
} else {
Ok(EventOutcome::Ok(message))
}
},
"save" => {
let message = common::save(
form_state,
grpc_client,
is_saved,
current_position,
total_count,
).await?;
command_input.clear();
return Ok((false, message, true));
},
"force_quit" => {
let (should_exit, message) = common::force_quit();
command_input.clear();
return Ok((should_exit, message, true));
},
"save_and_quit" => {
let (should_exit, message) = common::save_and_quit(
let outcome = save(
form_state,
grpc_client,
current_position,
total_count,
).await?;
let message = match outcome {
SaveOutcome::CreatedNew(_) => "New entry created".to_string(),
SaveOutcome::UpdatedExisting => "Entry updated".to_string(),
SaveOutcome::NoChange => "No changes to save".to_string(),
};
command_input.clear();
return Ok((should_exit, message, true));
Ok(EventOutcome::DataSaved(outcome, message))
},
"revert" => {
let message = common::revert(
let message = revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
command_input.clear();
return Ok((false, message, true));
},
"unknown" => {
let message = format!("Unknown command: {}", command);
command_input.clear();
return Ok((false, message, true));
Ok(EventOutcome::Ok(message))
},
_ => {
let message = format!("Unhandled action: {}", action);
command_input.clear();
return Ok((false, message, true));
Ok(EventOutcome::Ok(message))
}
}
}

View File

@@ -0,0 +1,71 @@
// src/modes/common/commands.rs
use crate::tui::terminal::core::TerminalCore;
use crate::state::app::state::AppState;
use crate::state::pages::{form::FormState, auth::LoginState, auth::RegisterState};
use crate::state::pages::canvas_state::CanvasState;
pub struct CommandHandler;
impl CommandHandler {
pub fn new() -> Self {
Self
}
pub async fn handle_command(
&mut self,
action: &str,
terminal: &mut TerminalCore,
app_state: &AppState,
form_state: &FormState,
login_state: &LoginState,
register_state: &RegisterState,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"quit" => self.handle_quit(terminal, app_state, form_state, login_state, register_state).await,
"force_quit" => self.handle_force_quit(terminal).await,
"save_and_quit" => self.handle_save_quit(terminal).await,
_ => Ok((false, format!("Unknown command: {}", action))),
}
}
async fn handle_quit(
&self,
terminal: &mut TerminalCore,
app_state: &AppState,
form_state: &FormState,
login_state: &LoginState,
register_state: &RegisterState,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
// Use actual unsaved changes state instead of is_saved flag
let has_unsaved = if app_state.ui.show_login {
login_state.has_unsaved_changes()
} else if app_state.ui.show_register {
register_state.has_unsaved_changes()
} else {
form_state.has_unsaved_changes
};
if !has_unsaved {
terminal.cleanup()?;
Ok((true, "Exiting.".into()))
} else {
Ok((false, "No changes saved. Use :q! to force quit.".into()))
}
}
async fn handle_force_quit(
&self,
terminal: &mut TerminalCore,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
terminal.cleanup()?;
Ok((true, "Force exiting without saving.".into()))
}
async fn handle_save_quit(
&mut self,
terminal: &mut TerminalCore,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
terminal.cleanup()?;
Ok((true, "State saved. Exiting.".into()))
}
}

View File

@@ -0,0 +1,3 @@
// src/client/modes/general.rs
pub mod navigation;
pub mod dialog;

View File

@@ -0,0 +1,127 @@
// src/modes/general/dialog.rs
use crossterm::event::{Event, KeyCode};
use crate::config::binds::config::Config;
use crate::ui::handlers::context::DialogPurpose;
use crate::state::app::state::AppState;
use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::modes::handlers::event::EventOutcome;
use crate::tui::functions::common::{login, register};
/// Handles key events specifically when a dialog is active.
/// Returns Some(Result<EventOutcome, Error>) if the event was handled (consumed),
/// otherwise returns None.
pub async fn handle_dialog_event(
event: &Event,
config: &Config,
app_state: &mut AppState,
auth_state: &mut AuthState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
) -> Option<Result<EventOutcome, Box<dyn std::error::Error>>> {
if let Event::Key(key) = event {
// Always allow Esc to dismiss
if key.code == KeyCode::Esc {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Dialog dismissed".to_string())));
}
// Check general bindings for dialog actions
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
match action {
"move_down" | "next_option" => {
let current_index = app_state.ui.dialog.dialog_active_button_index;
let num_buttons = app_state.ui.dialog.dialog_buttons.len();
if num_buttons > 0 && current_index < num_buttons - 1 {
app_state.ui.dialog.dialog_active_button_index += 1;
}
return Some(Ok(EventOutcome::Ok(String::new())));
}
"move_up" | "previous_option" => {
let current_index = app_state.ui.dialog.dialog_active_button_index;
if current_index > 0 {
app_state.ui.dialog.dialog_active_button_index -= 1;
}
return Some(Ok(EventOutcome::Ok(String::new())));
}
"select" => {
let selected_index = app_state.ui.dialog.dialog_active_button_index;
let purpose = match app_state.ui.dialog.purpose {
Some(p) => p,
None => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Internal Error: Dialog context lost".to_string())));
}
};
// Handle Dialog Actions Directly Here
match purpose {
DialogPurpose::LoginSuccess => {
match selected_index {
0 => { // "Menu" button selected
app_state.hide_dialog();
let message = login::back_to_main(login_state, app_state).await;
return Some(Ok(EventOutcome::Ok(message)));
}
1 => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Exiting dialog".to_string())));
}
_ => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
DialogPurpose::LoginFailed => {
match selected_index {
0 => { // "OK" button selected
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Login failed dialog dismissed".to_string())));
}
_ => {
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
DialogPurpose::RegisterSuccess => { // Add this arm
match selected_index {
0 => { // "OK" button for RegisterSuccess
app_state.hide_dialog();
// Go back to intro after successful registration dialog
let message = register::back_to_main(register_state, app_state).await;
return Some(Ok(EventOutcome::Ok(message)));
}
_ => { // Default for RegisterSuccess
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
DialogPurpose::RegisterFailed => { // Add this arm
match selected_index {
0 => { // "OK" button for RegisterFailed
app_state.hide_dialog(); // Just dismiss
return Some(Ok(EventOutcome::Ok("Register failed dialog dismissed".to_string())));
}
_ => { // Default for RegisterFailed
app_state.hide_dialog();
return Some(Ok(EventOutcome::Ok("Unknown dialog button selected".to_string())));
}
}
}
}
}
_ => {} // Ignore other general actions when dialog is shown
}
}
// If it was a key event but not handled above, consume it
Some(Ok(EventOutcome::Ok(String::new())))
} else {
// If it wasn't a key event, consume it too while dialog is active
Some(Ok(EventOutcome::Ok(String::new())))
}
}

View File

@@ -0,0 +1,161 @@
// src/modes/general/navigation.rs
use crossterm::event::KeyEvent;
use crate::config::binds::config::Config;
use crate::state::app::state::AppState;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::pages::intro::IntroState;
use crate::state::pages::admin::AdminState;
use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::context::UiContext;
use crate::modes::handlers::event::EventOutcome;
pub async fn handle_navigation_event(
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
app_state: &mut AppState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
intro_state: &mut IntroState,
admin_state: &mut AdminState,
command_mode: &mut bool,
command_input: &mut String,
command_message: &mut String,
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
match action {
"move_up" => {
move_up(app_state, login_state, register_state, intro_state, admin_state);
return Ok(EventOutcome::Ok(String::new()));
}
"move_down" => {
move_down(app_state, intro_state, admin_state);
return Ok(EventOutcome::Ok(String::new()));
}
"next_option" => {
next_option(app_state, intro_state);
return Ok(EventOutcome::Ok(String::new()));
}
"previous_option" => {
previous_option(app_state, intro_state);
return Ok(EventOutcome::Ok(String::new()));
}
"next_field" => {
next_field(form_state);
return Ok(EventOutcome::Ok(String::new()));
}
"prev_field" => {
prev_field(form_state);
return Ok(EventOutcome::Ok(String::new()));
}
"enter_command_mode" => {
handle_enter_command_mode(command_mode, command_input, command_message);
return Ok(EventOutcome::Ok(String::new()));
}
"select" => {
let (context, index) = if app_state.ui.show_intro {
(UiContext::Intro, intro_state.selected_option)
} else if app_state.ui.show_login && app_state.ui.focus_outside_canvas {
(UiContext::Login, app_state.focused_button_index)
} else if app_state.ui.show_register && app_state.ui.focus_outside_canvas {
(UiContext::Register, app_state.focused_button_index)
} else if app_state.ui.show_admin {
(UiContext::Admin, admin_state.get_selected_index().unwrap_or(0))
} else if app_state.ui.dialog.dialog_show {
(UiContext::Dialog, app_state.ui.dialog.dialog_active_button_index)
} else {
return Ok(EventOutcome::Ok("Select (No Action)".to_string()));
};
return Ok(EventOutcome::ButtonSelected { context, index });
}
_ => {}
}
}
Ok(EventOutcome::Ok(String::new()))
}
pub fn move_up(app_state: &mut AppState, login_state: &mut LoginState, register_state: &mut RegisterState, intro_state: &mut IntroState, admin_state: &mut AdminState) {
if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register{
if app_state.focused_button_index == 0 {
app_state.ui.focus_outside_canvas = false;
if app_state.ui.show_login {
let last_field_index = login_state.fields().len().saturating_sub(1);
login_state.set_current_field(last_field_index);
} else {
let last_field_index = register_state.fields().len().saturating_sub(1);
register_state.set_current_field(last_field_index);
}
} else {
app_state.focused_button_index = app_state.focused_button_index.saturating_sub(1);
}
} else if app_state.ui.show_intro {
intro_state.previous_option();
} else if app_state.ui.show_admin {
admin_state.previous();
}
}
pub fn move_down(app_state: &mut AppState, intro_state: &mut IntroState, admin_state: &mut AdminState) {
if app_state.ui.focus_outside_canvas && app_state.ui.show_login || app_state.ui.show_register {
let num_general_elements = 2;
if app_state.focused_button_index < num_general_elements - 1 {
app_state.focused_button_index += 1;
}
} else if app_state.ui.show_intro {
intro_state.next_option();
} else if app_state.ui.show_admin {
admin_state.next();
}
}
pub fn next_option(app_state: &mut AppState, intro_state: &mut IntroState) {
if app_state.ui.show_intro {
intro_state.next_option();
} else {
// Get option count from state instead of parameter
let option_count = app_state.profile_tree.profiles.len();
app_state.focused_button_index = (app_state.focused_button_index + 1) % option_count;
}
}
pub fn previous_option(app_state: &mut AppState, intro_state: &mut IntroState) {
if app_state.ui.show_intro {
intro_state.previous_option();
} else {
let option_count = app_state.profile_tree.profiles.len();
app_state.focused_button_index = if app_state.focused_button_index == 0 {
option_count.saturating_sub(1)
} else {
app_state.focused_button_index - 1
};
}
}
pub fn next_field(form_state: &mut FormState) {
if !form_state.fields.is_empty() {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
}
}
pub fn prev_field(form_state: &mut FormState) {
if !form_state.fields.is_empty() {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field -= 1;
}
}
}
pub fn handle_enter_command_mode(
command_mode: &mut bool,
command_input: &mut String,
command_message: &mut String
) {
*command_mode = true;
command_input.clear();
command_message.clear();
}

View File

@@ -1,6 +1,3 @@
// src/client/modes/handlers.rs
pub mod event;
pub mod edit;
pub mod common;
pub mod command_mode;
pub mod read_only;
pub mod mode_manager;

View File

@@ -1,413 +0,0 @@
// src/modes/handlers/edit.rs
use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
use crate::tui::terminal::{
grpc_client::GrpcClient,
};
use crate::config::config::Config;
use crate::ui::handlers::form::FormState;
use super::common;
pub async fn handle_edit_event_internal(
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
command_message: &mut String,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
) -> Result<String, Box<dyn std::error::Error>> {
if let Some(action) = config.get_edit_action_for_key(key.code, key.modifiers) {
return execute_edit_action(
action,
form_state,
ideal_cursor_column,
grpc_client, // Changed from AppTerminal
is_saved,
current_position,
total_count,
).await;
}
handle_edit_specific_input(
key,
form_state,
ideal_cursor_column,
);
Ok(command_message.clone())
}
fn handle_edit_specific_input(
key: KeyEvent,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
) {
match key.code {
KeyCode::Char(c) => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() {
chars.insert(cursor_pos, c);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos + 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
}
}
KeyCode::Backspace => {
if form_state.current_cursor_pos > 0 {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() && cursor_pos > 0 {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
}
}
}
KeyCode::Delete => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
let mut new_chars = chars.clone();
new_chars.remove(cursor_pos);
*field_value = new_chars.into_iter().collect();
form_state.has_unsaved_changes = true;
}
}
KeyCode::Tab => {
if key.modifiers.contains(KeyModifiers::SHIFT) {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
} else {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
KeyCode::Enter => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
}
_ => {}
}
}
async fn execute_edit_action(
action: &str,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
grpc_client: &mut GrpcClient, // Changed from AppTerminal
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"save" => {
common::save(
form_state,
grpc_client, // Changed from AppTerminal
is_saved,
current_position,
total_count,
).await
},
"move_left" => {
form_state.current_cursor_pos = form_state.current_cursor_pos.saturating_sub(1);
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = form_state.get_current_input();
if form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_up" => {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_down" => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_line_start" => {
form_state.current_cursor_pos = 0;
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_line_end" => {
let current_input = form_state.get_current_input();
form_state.current_cursor_pos = current_input.len();
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_first_line" => {
form_state.current_field = 0;
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to first line".to_string())
}
"move_last_line" => {
form_state.current_field = form_state.fields.len() - 1;
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to last line".to_string())
}
// Word movement actions
"move_word_next" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len());
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len());
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
// Edit-specific actions that can be bound to keys
"delete_char_forward" => {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let chars: Vec<char> = field_value.chars().collect();
if cursor_pos < chars.len() {
let mut new_chars = chars.clone();
new_chars.remove(cursor_pos);
*field_value = new_chars.into_iter().collect();
form_state.has_unsaved_changes = true;
}
Ok("".to_string())
}
"delete_char_backward" => {
if form_state.current_cursor_pos > 0 {
let cursor_pos = form_state.current_cursor_pos;
let field_value = form_state.get_current_input_mut();
let mut chars: Vec<char> = field_value.chars().collect();
if cursor_pos <= chars.len() && cursor_pos > 0 {
chars.remove(cursor_pos - 1);
*field_value = chars.into_iter().collect();
form_state.current_cursor_pos = cursor_pos - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
form_state.has_unsaved_changes = true;
}
}
Ok("".to_string())
}
"insert_char" => {
// This could be expanded to allow configurable character insertion
// For now, it's a placeholder that would need additional parameters
Ok("Character insertion requires configuration".to_string())
}
"next_field" => {
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"prev_field" => {
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
let current_input = form_state.get_current_input();
let max_cursor_pos = current_input.len();
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
// Fallback for unrecognized actions
_ => Ok(format!("Unknown action: {}", action)),
}
}
// Reuse these character and word navigation helper functions
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos >= chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
if current_pos >= chars.len() - 1 {
return chars.len() - 1;
}
let mut pos = current_pos;
if get_char_type(chars[pos]) == CharType::Whitespace {
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
} else {
let current_type = get_char_type(chars[pos]);
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
pos += 1;
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
}
}
if pos >= chars.len() {
return chars.len() - 1;
}
let word_type = get_char_type(chars[pos]);
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
pos += 1;
}
pos
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos <= 1 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 && get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos -= 1;
let prev_word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
pos -= 1;
}
while pos < chars.len() - 1 &&
get_char_type(chars[pos + 1]) == prev_word_type {
pos += 1;
}
}
}
pos
}

View File

@@ -1,18 +1,39 @@
// src/modes/handlers/event.rs
use crossterm::event::Event;
use crossterm::cursor::SetCursorStyle;
use crate::tui::terminal::{
core::TerminalCore,
grpc_client::GrpcClient,
commands::CommandHandler,
};
use crate::config::config::Config;
use crate::ui::handlers::form::FormState;
use crate::tui::terminal::core::TerminalCore;
use crate::services::grpc_client::GrpcClient;
use crate::services::auth::AuthClient;
use crate::modes::common::commands::CommandHandler;
use crate::config::binds::config::Config;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::pages::intro::IntroState;
use crate::state::pages::admin::AdminState;
use crate::state::app::state::AppState;
use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::rat_state::UiStateHandler;
use crate::modes::handlers::{edit, command_mode, read_only};
use crate::config::key_sequences::KeySequenceTracker;
use super::common;
use crate::ui::handlers::context::UiContext;
use crate::tui::functions::{intro, admin};
use crate::tui::functions::common::{login, register};
use crate::modes::{
common::command_mode,
canvas::{edit, read_only, common_mode},
general::{navigation, dialog},
};
use crate::config::binds::key_sequences::KeySequenceTracker;
use crate::modes::handlers::mode_manager::{ModeManager, AppMode};
use crate::tui::functions::common::form::SaveOutcome;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventOutcome {
Ok(String),
Exit(String),
DataSaved(SaveOutcome, String),
ButtonSelected { context: UiContext, index: usize },
}
pub struct EventHandler {
pub command_mode: bool,
@@ -22,11 +43,12 @@ pub struct EventHandler {
pub edit_mode_cooldown: bool,
pub ideal_cursor_column: usize,
pub key_sequence_tracker: KeySequenceTracker,
pub auth_client: AuthClient,
}
impl EventHandler {
pub fn new() -> Self {
EventHandler {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
Ok(EventHandler {
command_mode: false,
command_input: String::new(),
command_message: String::new(),
@@ -34,7 +56,8 @@ impl EventHandler {
edit_mode_cooldown: false,
ideal_cursor_column: 0,
key_sequence_tracker: KeySequenceTracker::new(800),
}
auth_client: AuthClient::new().await?,
})
}
pub async fn handle_event(
@@ -45,162 +68,310 @@ impl EventHandler {
grpc_client: &mut GrpcClient,
command_handler: &mut CommandHandler,
form_state: &mut FormState,
app_state: &mut crate::state::state::AppState,
auth_state: &mut AuthState,
login_state: &mut LoginState,
register_state: &mut RegisterState,
intro_state: &mut IntroState,
admin_state: &mut AdminState,
app_state: &mut AppState,
total_count: u64,
current_position: &mut u64,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
) -> Result<EventOutcome, Box<dyn std::error::Error>> {
let current_mode = ModeManager::derive_mode(app_state, self);
app_state.update_mode(current_mode);
// --- DIALOG MODALITY ---
if app_state.ui.dialog.dialog_show {
if let Some(dialog_result) = dialog::handle_dialog_event(
&event, config, app_state, auth_state, login_state, register_state
).await {
return dialog_result;
}
return Ok(EventOutcome::Ok(String::new()));
}
// --- END DIALOG MODALITY CHECK ---
if let Event::Key(key) = event {
let key_code = key.code;
let modifiers = key.modifiers;
if UiStateHandler::toggle_sidebar(
&mut app_state.ui,
config,
key_code,
modifiers,
) {
return Ok((false, format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
)));
}
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" => {
let message = common::save(
form_state,
grpc_client,
&mut app_state.is_saved,
current_position,
total_count,
).await?;
return Ok((false, message));
},
"force_quit" => {
let (should_exit, message) = command_handler.handle_command("force_quit", terminal).await?;
return Ok((should_exit, message));
},
"save_and_quit" => {
let (should_exit, message) = command_handler.handle_command("save_and_quit", terminal).await?;
return Ok((should_exit, message));
},
"revert" => {
let message = common::revert(
form_state,
grpc_client,
current_position,
total_count,
).await?;
return Ok((false, message));
},
_ => {}
}
if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) {
let message = format!("Sidebar {}",
if app_state.ui.show_sidebar { "shown" } else { "hidden" }
);
return Ok(EventOutcome::Ok(message));
}
if self.command_mode {
let (should_exit, message, exit_command_mode) = command_mode::handle_command_event(
key,
config,
form_state,
&mut self.command_input,
&mut self.command_message,
grpc_client,
&mut app_state.is_saved,
current_position,
total_count,
).await?;
if exit_command_mode {
self.command_mode = false;
}
return Ok((should_exit, message));
if UiStateHandler::toggle_buffer_list(&mut app_state.ui, config, key_code, modifiers) {
let message = format!("Buffer {}",
if app_state.ui.show_buffer_list { "shown" } else { "hidden" }
);
return Ok(EventOutcome::Ok(message));
}
// --- End Global UI Toggles ---
if self.is_edit_mode {
if config.is_exit_edit_mode(key_code, modifiers) {
if form_state.has_unsaved_changes {
self.command_message = "Unsaved changes! Use :w to save or :q! to discard".to_string();
return Ok((false, self.command_message.clone()));
match current_mode {
AppMode::General => {
let nav_outcome = navigation::handle_navigation_event(
key,
config,
form_state,
app_state,
login_state,
register_state,
intro_state,
admin_state,
&mut self.command_mode,
&mut self.command_input,
&mut self.command_message,
).await;
match nav_outcome {
Ok(EventOutcome::ButtonSelected { context, index }) => {
let mut message = String::from("Selected"); // Default message
match context {
UiContext::Intro => {
intro::handle_intro_selection(app_state, index);
if app_state.ui.show_admin {
let profile_names = app_state.profile_tree.profiles.iter()
.map(|p| p.name.clone())
.collect();
admin_state.set_profiles(profile_names);
}
message = format!("Intro Option {} selected", index);
}
UiContext::Login => {
message = match index {
0 => login::save(auth_state, login_state, &mut self.auth_client, app_state).await?,
1 => login::back_to_main(login_state, app_state).await,
_ => "Invalid Login Option".to_string(),
};
}
UiContext::Register => {
message = match index {
0 => register::save(register_state, &mut self.auth_client, app_state).await?,
1 => register::back_to_main(register_state, app_state).await,
_ => "Invalid Login Option".to_string(),
};
}
UiContext::Admin => {
admin::handle_admin_selection(app_state, admin_state);
message = format!("Admin Option {} selected", index);
}
UiContext::Dialog => {
message = "Internal error: Unexpected dialog state".to_string();
}
}
return Ok(EventOutcome::Ok(message)); // Return Ok with message
}
other => return other, // Pass through Ok, Err, DataSaved directly
}
self.is_edit_mode = false;
self.edit_mode_cooldown = true;
self.command_message = "Read-only mode".to_string();
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
},
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos >= current_input.len() {
form_state.current_cursor_pos = current_input.len() - 1;
self.ideal_cursor_column = form_state.current_cursor_pos;
AppMode::ReadOnly => {
if config.is_enter_edit_mode_before(key_code, modifiers) &&
ModeManager::can_enter_edit_mode(current_mode) {
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
return Ok((false, self.command_message.clone()));
}
let result = edit::handle_edit_event_internal(
key,
config,
form_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
&mut app_state.is_saved,
current_position,
total_count,
grpc_client,
).await?;
if config.is_enter_edit_mode_after(key_code, modifiers) &&
ModeManager::can_enter_edit_mode(current_mode) {
let current_input = if app_state.ui.show_login || app_state.ui.show_register{
login_state.get_current_input()
} else {
form_state.get_current_input()
};
let current_cursor_pos = if app_state.ui.show_login || app_state.ui.show_register{
login_state.current_cursor_pos()
} else {
form_state.current_cursor_pos()
};
self.key_sequence_tracker.reset();
return Ok((false, result));
} else {
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) {
if action == "enter_command_mode" {
self.command_mode = true;
self.command_input.clear();
self.command_message.clear();
return Ok((false, String::new()));
if !current_input.is_empty() && current_cursor_pos < current_input.len() {
if app_state.ui.show_login || app_state.ui.show_register{
login_state.set_current_cursor_pos(current_cursor_pos + 1);
self.ideal_cursor_column = login_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(current_cursor_pos + 1);
self.ideal_cursor_column = form_state.current_cursor_pos();
}
}
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode (after cursor)".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
}
if config.is_enter_edit_mode_before(key_code, modifiers) {
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok((false, self.command_message.clone()));
}
if config.is_enter_edit_mode_after(key_code, modifiers) {
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
self.ideal_cursor_column = form_state.current_cursor_pos;
if let Some(action) = config.get_read_only_action_for_key(key_code, modifiers) {
if action == "enter_command_mode" && ModeManager::can_enter_command_mode(current_mode) {
self.command_mode = true;
self.command_input.clear();
self.command_message.clear();
return Ok(EventOutcome::Ok(String::new()));
}
}
self.is_edit_mode = true;
self.edit_mode_cooldown = true;
self.command_message = "Edit mode (after cursor)".to_string();
terminal.set_cursor_style(SetCursorStyle::BlinkingBar)?;
return Ok((false, self.command_message.clone()));
}
return read_only::handle_read_only_event(
key,
config,
form_state,
&mut self.key_sequence_tracker,
current_position,
total_count,
grpc_client,
&mut self.command_message,
&mut self.edit_mode_cooldown,
&mut self.ideal_cursor_column,
).await;
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" | "force_quit" | "save_and_quit" | "revert" => {
return common_mode::handle_core_action(
action,
form_state,
auth_state,
login_state,
register_state,
grpc_client,
&mut self.auth_client,
terminal,
app_state,
current_position,
total_count,
).await;
},
_ => {}
}
}
let (_should_exit, message) = read_only::handle_read_only_event(
app_state,
key,
config,
form_state,
login_state,
register_state,
&mut self.key_sequence_tracker,
current_position,
total_count,
grpc_client,
&mut self.command_message,
&mut self.edit_mode_cooldown,
&mut self.ideal_cursor_column,
).await?;
return Ok(EventOutcome::Ok(message));
},
AppMode::Edit => {
if config.is_exit_edit_mode(key_code, modifiers) {
self.is_edit_mode = false;
self.edit_mode_cooldown = true;
let has_changes = if app_state.ui.show_login || app_state.ui.show_register{
login_state.has_unsaved_changes()
} else {
form_state.has_unsaved_changes()
};
self.command_message = if has_changes {
"Exited edit mode (unsaved changes remain)".to_string()
} else {
"Read-only mode".to_string()
};
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
let current_input = if app_state.ui.show_login || app_state.ui.show_register{
login_state.get_current_input()
} else {
form_state.get_current_input()
};
let current_cursor_pos = if app_state.ui.show_login || app_state.ui.show_register{
login_state.current_cursor_pos()
} else {
form_state.current_cursor_pos()
};
if !current_input.is_empty() && current_cursor_pos >= current_input.len() {
let new_pos = current_input.len() - 1;
if app_state.ui.show_login || app_state.ui.show_register{
login_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = login_state.current_cursor_pos();
} else {
form_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = form_state.current_cursor_pos();
}
}
return Ok(EventOutcome::Ok(self.command_message.clone()));
}
if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.common,
key_code,
modifiers
) {
match action {
"save" | "force_quit" | "save_and_quit" | "revert" => {
return common_mode::handle_core_action(
action,
form_state,
auth_state,
login_state,
register_state,
grpc_client,
&mut self.auth_client,
terminal,
app_state,
current_position,
total_count,
).await;
},
_ => {}
}
}
let message = edit::handle_edit_event(
key,
config,
form_state,
login_state,
register_state,
&mut self.ideal_cursor_column,
&mut self.command_message,
current_position,
total_count,
grpc_client,
app_state,
).await?;
self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok(message));
},
AppMode::Command => {
let outcome = command_mode::handle_command_event(
key,
config,
app_state,
login_state,
register_state,
form_state,
&mut self.command_input,
&mut self.command_message,
grpc_client,
command_handler,
terminal,
current_position,
total_count,
).await?;
if let EventOutcome::Ok(msg) = &outcome {
if msg == "Exited command mode" {
self.command_mode = false;
}
}
return Ok(outcome);
}
}
}
self.edit_mode_cooldown = false;
Ok((false, self.command_message.clone()))
Ok(EventOutcome::Ok(self.command_message.clone()))
}
}

View File

@@ -0,0 +1,55 @@
// src/modes/handlers/mode_manager.rs
use crate::state::app::state::AppState;
use crate::modes::handlers::event::EventHandler;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
General, // For intro and admin screens
ReadOnly, // Canvas read-only mode
Edit, // Canvas edit mode
Command, // Command mode overlay
}
pub struct ModeManager;
impl ModeManager {
// Determine current mode based on app state
pub fn derive_mode(app_state: &AppState, event_handler: &EventHandler) -> AppMode {
if event_handler.command_mode {
return AppMode::Command;
}
if app_state.ui.focus_outside_canvas {
return AppMode::General;
}
if app_state.ui.show_login || app_state.ui.show_register {
if event_handler.is_edit_mode {
AppMode::Edit
} else {
AppMode::ReadOnly
}
} else if app_state.ui.show_form {
if event_handler.is_edit_mode {
AppMode::Edit
} else {
AppMode::ReadOnly
}
} else {
AppMode::General
}
}
// Mode transition rules
pub fn can_enter_command_mode(current_mode: AppMode) -> bool {
!matches!(current_mode, AppMode::Edit) // Can't enter from Edit mode
}
pub fn can_enter_edit_mode(current_mode: AppMode) -> bool {
matches!(current_mode, AppMode::ReadOnly) // Only from ReadOnly
}
pub fn can_enter_read_only_mode(current_mode: AppMode) -> bool {
matches!(current_mode, AppMode::Edit | AppMode::Command)
}
}

View File

@@ -1,458 +0,0 @@
// src/modes/handlers/read_only.rs
use crossterm::event::{KeyEvent};
use crate::config::config::Config;
use crate::ui::handlers::form::FormState;
use crate::config::key_sequences::KeySequenceTracker;
use crate::tui::terminal::grpc_client::GrpcClient;
#[derive(PartialEq)]
enum CharType {
Whitespace,
Alphanumeric,
Punctuation,
}
pub async fn handle_read_only_event(
key: KeyEvent,
config: &Config,
form_state: &mut FormState,
key_sequence_tracker: &mut KeySequenceTracker,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
command_message: &mut String,
edit_mode_cooldown: &mut bool,
ideal_cursor_column: &mut usize,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
// Check for entering Edit mode from Read-Only mode
if config.is_enter_edit_mode_before(key.code, key.modifiers) {
*edit_mode_cooldown = true;
*command_message = "Entering Edit mode".to_string();
return Ok((false, command_message.clone()));
}
if config.is_enter_edit_mode_after(key.code, key.modifiers) {
let current_input = form_state.get_current_input();
if !current_input.is_empty() && form_state.current_cursor_pos < current_input.len() {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
*edit_mode_cooldown = true;
*command_message = "Entering Edit mode (after cursor)".to_string();
return Ok((false, command_message.clone()));
}
// Handle Read-Only mode keybindings
if key.modifiers.is_empty() {
key_sequence_tracker.add_key(key.code);
let sequence = key_sequence_tracker.get_sequence();
// Try to match the current sequence against Read-Only mode bindings
if let Some(action) = config.matches_key_sequence_generalized(&sequence) {
let result = execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
current_position,
total_count,
grpc_client,
).await?;
key_sequence_tracker.reset();
return Ok((false, result));
}
// Check if this might be a prefix of a longer sequence
if config.is_key_sequence_prefix(&sequence) {
return Ok((false, command_message.clone()));
}
// Since it's not part of a multi-key sequence, check for a direct action
if sequence.len() == 1 && !config.is_key_sequence_prefix(&sequence) {
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
current_position,
total_count,
grpc_client,
).await?;
key_sequence_tracker.reset();
return Ok((false, result));
}
}
} else {
// If modifiers are pressed, check for direct key bindings
key_sequence_tracker.reset();
if let Some(action) = config.get_read_only_action_for_key(key.code, key.modifiers) {
let result = execute_action(
action,
form_state,
ideal_cursor_column,
key_sequence_tracker,
command_message,
current_position,
total_count,
grpc_client,
).await?;
return Ok((false, result));
}
}
// Show a helpful message when no binding was found
if !*edit_mode_cooldown {
let default_key = "i".to_string();
let edit_key = config.keybindings.read_only.get("enter_edit_mode_before")
.and_then(|keys| keys.first())
.unwrap_or(&default_key);
*command_message = format!("Read-only mode - press {} to edit", edit_key);
}
Ok((false, command_message.clone()))
}
async fn execute_action(
action: &str,
form_state: &mut FormState,
ideal_cursor_column: &mut usize,
key_sequence_tracker: &mut KeySequenceTracker,
command_message: &mut String,
current_position: &mut u64,
total_count: u64,
grpc_client: &mut GrpcClient,
) -> Result<String, Box<dyn std::error::Error>> {
match action {
"previous_entry" => {
let new_position = current_position.saturating_sub(1);
if new_position >= 1 {
*current_position = new_position;
match grpc_client.get_adresar_by_position(*current_position).await {
Ok(response) => {
form_state.id = response.id;
form_state.values = vec![
response.firma, response.kz, response.drc,
response.ulica, response.psc, response.mesto,
response.stat, response.banka, response.ucet,
response.skladm, response.ico, response.kontakt,
response.telefon, response.skladu, response.fax,
];
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else { 0 };
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
form_state.has_unsaved_changes = false;
*command_message = format!("Loaded entry {}", *current_position);
}
Err(e) => {
*command_message = format!("Error loading entry: {}", e);
}
}
key_sequence_tracker.reset();
}
Ok(command_message.clone())
}
"next_entry" => {
if *current_position <= total_count {
*current_position += 1;
if *current_position <= total_count {
match grpc_client.get_adresar_by_position(*current_position).await {
Ok(response) => {
form_state.id = response.id;
form_state.values = vec![
response.firma, response.kz, response.drc,
response.ulica, response.psc, response.mesto,
response.stat, response.banka, response.ucet,
response.skladm, response.ico, response.kontakt,
response.telefon, response.skladu, response.fax,
];
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else { 0 };
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
form_state.has_unsaved_changes = false;
*command_message = format!("Loaded entry {}", *current_position);
}
Err(e) => {
*command_message = format!("Error loading entry: {}", e);
}
}
} else {
form_state.reset_to_empty();
form_state.current_field = 0;
form_state.current_cursor_pos = 0;
*ideal_cursor_column = 0;
*command_message = "New entry mode".to_string();
}
key_sequence_tracker.reset();
}
Ok(command_message.clone())
}
"exit_edit_mode" => {
key_sequence_tracker.reset();
command_message.clear();
Ok("".to_string())
}
"move_left" => {
let current_pos = form_state.current_cursor_pos;
form_state.current_cursor_pos = current_pos.saturating_sub(1);
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_right" => {
let current_input = form_state.get_current_input();
let current_pos = form_state.current_cursor_pos;
if !current_input.is_empty() && current_pos < current_input.len() - 1 {
form_state.current_cursor_pos += 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_up" => {
// Change field first
if form_state.current_field == 0 {
form_state.current_field = form_state.fields.len() - 1;
} else {
form_state.current_field = form_state.current_field.saturating_sub(1);
}
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_down" => {
// Change field first
form_state.current_field = (form_state.current_field + 1) % form_state.fields.len();
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("".to_string())
}
"move_word_next" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_next_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos.min(current_input.len().saturating_sub(1));
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_start(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_word_end_prev" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
let new_pos = find_prev_word_end(current_input, form_state.current_cursor_pos);
form_state.current_cursor_pos = new_pos;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("Moved to previous word end".to_string())
}
"move_line_start" => {
form_state.current_cursor_pos = 0;
*ideal_cursor_column = form_state.current_cursor_pos;
Ok("".to_string())
}
"move_line_end" => {
let current_input = form_state.get_current_input();
if !current_input.is_empty() {
form_state.current_cursor_pos = current_input.len() - 1;
*ideal_cursor_column = form_state.current_cursor_pos;
}
Ok("".to_string())
}
"move_first_line" => {
// Change field first
form_state.current_field = 0;
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
current_input.len()
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to first line".to_string())
}
"move_last_line" => {
// Change field first
form_state.current_field = form_state.fields.len() - 1;
// Get current input AFTER changing field
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
current_input.len()
};
form_state.current_cursor_pos = (*ideal_cursor_column).min(max_cursor_pos);
Ok("Moved to last line".to_string())
}
_ => Ok(format!("Unknown action: {}", action)),
}
}
fn get_char_type(c: char) -> CharType {
if c.is_whitespace() {
CharType::Whitespace
} else if c.is_alphanumeric() {
CharType::Alphanumeric
} else {
CharType::Punctuation
}
}
fn find_next_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos >= chars.len() {
return current_pos;
}
let mut pos = current_pos;
let initial_type = get_char_type(chars[pos]);
while pos < chars.len() && get_char_type(chars[pos]) == initial_type {
pos += 1;
}
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
pos
}
fn find_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return 0;
}
if current_pos >= chars.len() - 1 {
return chars.len() - 1;
}
let mut pos = current_pos;
if get_char_type(chars[pos]) == CharType::Whitespace {
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
} else {
let current_type = get_char_type(chars[pos]);
if pos + 1 < chars.len() && get_char_type(chars[pos + 1]) != current_type {
pos += 1;
while pos < chars.len() && get_char_type(chars[pos]) == CharType::Whitespace {
pos += 1;
}
}
}
if pos >= chars.len() {
return chars.len() - 1;
}
let word_type = get_char_type(chars[pos]);
while pos + 1 < chars.len() && get_char_type(chars[pos + 1]) == word_type {
pos += 1;
}
pos
}
fn find_prev_word_start(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos == 0 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
}
pos
}
fn find_prev_word_end(text: &str, current_pos: usize) -> usize {
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() || current_pos <= 1 {
return 0;
}
let mut pos = current_pos.saturating_sub(1);
while pos > 0 && get_char_type(chars[pos]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 && get_char_type(chars[pos]) != CharType::Whitespace {
let word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == word_type {
pos -= 1;
}
while pos > 0 && get_char_type(chars[pos - 1]) == CharType::Whitespace {
pos -= 1;
}
if pos > 0 {
pos -= 1;
let prev_word_type = get_char_type(chars[pos]);
while pos > 0 && get_char_type(chars[pos - 1]) == prev_word_type {
pos -= 1;
}
while pos < chars.len() - 1 &&
get_char_type(chars[pos + 1]) == prev_word_type {
pos += 1;
}
}
}
pos
}

View File

@@ -1,4 +1,10 @@
// src/client/modes/mod.rs
pub mod handlers;
pub mod canvas;
pub mod general;
pub mod common;
pub use handlers::*;
pub use canvas::*;
pub use general::*;
pub use common::*;

View File

@@ -0,0 +1,45 @@
// src/services/auth.rs
use tonic::transport::Channel;
use common::proto::multieko2::auth::{
auth_service_client::AuthServiceClient,
LoginRequest, LoginResponse,
RegisterRequest, AuthResponse,
};
pub struct AuthClient {
client: AuthServiceClient<Channel>,
}
impl AuthClient {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
let client = AuthServiceClient::connect("http://[::1]:50051").await?;
Ok(Self { client })
}
/// Login user via gRPC.
pub async fn login(&mut self, identifier: String, password: String) -> Result<LoginResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(LoginRequest { identifier, password });
let response = self.client.login(request).await?.into_inner();
Ok(response)
}
/// Registers a new user via gRPC.
pub async fn register(
&mut self,
username: String,
email: String,
password: Option<String>,
password_confirmation: Option<String>,
role: Option<String>,
) -> Result<AuthResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(RegisterRequest {
username,
email,
password: password.unwrap_or_default(),
password_confirmation: password_confirmation.unwrap_or_default(),
role: role.unwrap_or_default(),
});
let response = self.client.register(request).await?.into_inner();
Ok(response)
}
}

View File

@@ -1,4 +1,4 @@
// src/tui/terminal/grpc_client.rs
// src/services/grpc_client.rs
use tonic::transport::Channel;
use common::proto::multieko2::adresar::adresar_client::AdresarClient;
@@ -6,17 +6,29 @@ use common::proto::multieko2::adresar::{AdresarResponse, PostAdresarRequest, Put
use common::proto::multieko2::common::{CountResponse, PositionRequest, Empty};
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
use common::proto::multieko2::table_structure::TableStructureResponse;
use common::proto::multieko2::table_definition::{
table_definition_client::TableDefinitionClient,
ProfileTreeResponse
};
#[derive(Clone)]
pub struct GrpcClient {
adresar_client: AdresarClient<Channel>,
table_structure_client: TableStructureServiceClient<Channel>,
table_definition_client: TableDefinitionClient<Channel>,
}
impl GrpcClient {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
Ok(Self { adresar_client, table_structure_client })
let table_definition_client = TableDefinitionClient::connect("http://[::1]:50051").await?;
Ok(Self {
adresar_client,
table_structure_client,
table_definition_client,
})
}
pub async fn get_adresar_count(&mut self) -> Result<u64, Box<dyn std::error::Error>> {
@@ -48,4 +60,10 @@ impl GrpcClient {
let response = self.table_structure_client.get_adresar_table_structure(request).await?;
Ok(response.into_inner())
}
pub async fn get_profile_tree(&mut self) -> Result<ProfileTreeResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(Empty::default());
let response = self.table_definition_client.get_profile_tree(request).await?;
Ok(response.into_inner())
}
}

View File

@@ -0,0 +1,9 @@
// services/mod.rs
pub mod grpc_client;
pub mod auth;
pub mod ui_service;
pub use grpc_client::*;
pub use ui_service::*;
pub use auth::*;

View File

@@ -0,0 +1,112 @@
// src/services/ui_service.rs
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
use crate::tui::functions::common::form::SaveOutcome;
use crate::state::app::state::AppState;
pub struct UiService;
impl UiService {
pub async fn initialize_app_state(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
// Fetch profile tree
let profile_tree = grpc_client.get_profile_tree().await?;
app_state.profile_tree = profile_tree;
// Fetch table structure
let table_structure = grpc_client.get_table_structure().await?;
// Extract the column names from the response
let column_names: Vec<String> = table_structure
.columns
.iter()
.map(|col| col.name.clone())
.collect();
Ok(column_names)
}
pub async fn initialize_adresar_count(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
) -> Result<(), Box<dyn std::error::Error>> {
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
Ok(())
}
pub async fn update_adresar_count(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
) -> Result<(), Box<dyn std::error::Error>> {
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
Ok(())
}
pub async fn load_adresar_by_position(
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
form_state: &mut FormState,
position: u64,
) -> Result<String, Box<dyn std::error::Error>> {
match grpc_client.get_adresar_by_position(position).await {
Ok(response) => {
// Set the ID properly
form_state.id = response.id;
// Update form values dynamically
form_state.values = vec![
response.firma,
response.kz,
response.drc,
response.ulica,
response.psc,
response.mesto,
response.stat,
response.banka,
response.ucet,
response.skladm,
response.ico,
response.kontakt,
response.telefon,
response.skladu,
response.fax,
];
form_state.has_unsaved_changes = false;
Ok(format!("Loaded entry {}", position))
}
Err(e) => {
Ok(format!("Error loading entry: {}", e))
}
}
}
/// Handles the consequences of a save operation, like updating counts.
pub async fn handle_save_outcome(
save_outcome: SaveOutcome,
grpc_client: &mut GrpcClient,
app_state: &mut AppState,
form_state: &mut FormState, // Needed to potentially update position/ID
) -> Result<(), Box<dyn std::error::Error>> {
match save_outcome {
SaveOutcome::CreatedNew(new_id) => {
// A new record was created, update the count!
UiService::update_adresar_count(grpc_client, app_state).await?;
// Navigate to the new record (now that count is updated)
app_state.update_current_position(app_state.total_count);
form_state.id = new_id; // Ensure ID is set (might be redundant if save already did it)
}
SaveOutcome::UpdatedExisting | SaveOutcome::NoChange => {
// No count update needed for these outcomes
}
}
Ok(())
}
}

3
client/src/state/app.rs Normal file
View File

@@ -0,0 +1,3 @@
// src/state/app.rs
pub mod state;

View File

@@ -0,0 +1,159 @@
// src/state/state.rs
use std::env;
use common::proto::multieko2::table_definition::ProfileTreeResponse;
use crate::modes::handlers::mode_manager::AppMode;
use crate::ui::handlers::context::DialogPurpose;
pub struct DialogState {
pub dialog_show: bool,
pub dialog_title: String,
pub dialog_message: String,
pub dialog_buttons: Vec<String>,
pub dialog_active_button_index: usize,
pub purpose: Option<DialogPurpose>,
}
pub struct UiState {
pub show_sidebar: bool,
pub show_buffer_list: bool,
pub show_intro: bool,
pub show_admin: bool,
pub show_form: bool,
pub show_login: bool,
pub show_register: bool,
pub focus_outside_canvas: bool,
pub dialog: DialogState,
}
pub struct AppState {
// Core editor state
pub current_dir: String,
pub total_count: u64,
pub current_position: u64,
pub profile_tree: ProfileTreeResponse,
pub selected_profile: Option<String>,
pub current_mode: AppMode,
pub focused_button_index: usize,
// UI preferences
pub ui: UiState,
}
impl AppState {
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
let current_dir = env::current_dir()?
.to_string_lossy()
.to_string();
Ok(AppState {
current_dir,
total_count: 0,
current_position: 0,
profile_tree: ProfileTreeResponse::default(),
selected_profile: None,
current_mode: AppMode::General,
focused_button_index: 0,
ui: UiState::default(),
})
}
// Existing methods remain unchanged
pub fn update_total_count(&mut self, total_count: u64) {
self.total_count = total_count;
}
pub fn update_current_position(&mut self, current_position: u64) {
self.current_position = current_position;
}
pub fn update_mode(&mut self, mode: AppMode) {
self.current_mode = mode;
}
// Add dialog helper methods
/// Shows a dialog with the given title, message, and buttons.
/// The first button (index 0) is active by default.
pub fn show_dialog(
&mut self,
title: &str,
message: &str,
buttons: Vec<String>,
purpose: DialogPurpose,
) {
self.ui.dialog.dialog_title = title.to_string();
self.ui.dialog.dialog_message = message.to_string();
self.ui.dialog.dialog_buttons = buttons;
self.ui.dialog.dialog_active_button_index = 0;
self.ui.dialog.purpose = Some(purpose);
self.ui.dialog.dialog_show = true;
self.ui.focus_outside_canvas = true;
}
/// Hides the dialog and clears its content.
pub fn hide_dialog(&mut self) {
self.ui.dialog.dialog_show = false;
self.ui.dialog.dialog_title.clear();
self.ui.dialog.dialog_message.clear();
self.ui.dialog.dialog_buttons.clear();
self.ui.dialog.dialog_active_button_index = 0;
self.ui.dialog.purpose = None;
self.ui.focus_outside_canvas = false;
}
/// Sets the active button index, wrapping around if necessary.
pub fn next_dialog_button(&mut self) {
if !self.ui.dialog.dialog_buttons.is_empty() {
let next_index = (self.ui.dialog.dialog_active_button_index + 1)
% self.ui.dialog.dialog_buttons.len();
self.ui.dialog.dialog_active_button_index = next_index; // Use new name
}
}
/// Sets the active button index, wrapping around if necessary.
pub fn previous_dialog_button(&mut self) {
if !self.ui.dialog.dialog_buttons.is_empty() {
let len = self.ui.dialog.dialog_buttons.len();
let prev_index =
(self.ui.dialog.dialog_active_button_index + len - 1) % len;
self.ui.dialog.dialog_active_button_index = prev_index; // Use new name
}
}
/// Gets the label of the currently active button, if any.
pub fn get_active_dialog_button_label(&self) -> Option<&str> {
self.ui.dialog
.dialog_buttons // Use new name
.get(self.ui.dialog.dialog_active_button_index) // Use new name
.map(|s| s.as_str())
}
}
impl Default for UiState {
fn default() -> Self {
Self {
show_sidebar: true,
show_intro: true,
show_admin: false,
show_form: false,
show_login: false,
show_register: false,
show_buffer_list: false,
focus_outside_canvas: false,
dialog: DialogState::default(),
}
}
}
// Update the Default implementation for DialogState itself
impl Default for DialogState {
fn default() -> Self {
Self {
dialog_show: false,
dialog_title: String::new(),
dialog_message: String::new(),
dialog_buttons: Vec::new(),
dialog_active_button_index: 0,
purpose: None,
}
}
}

View File

@@ -1,2 +1,3 @@
// src/state/mod.rs
pub mod state;
pub mod app;
pub mod pages;

View File

@@ -0,0 +1,7 @@
// src/state/pages.rs
pub mod form;
pub mod auth;
pub mod admin;
pub mod intro;
pub mod canvas_state;

View File

@@ -0,0 +1,65 @@
// src/state/pages/admin.rs
use ratatui::widgets::ListState;
#[derive(Default, Clone, Debug)]
pub struct AdminState {
pub profiles: Vec<String>,
pub list_state: ListState,
}
impl AdminState {
/// Gets the index of the currently selected item.
pub fn get_selected_index(&self) -> Option<usize> {
self.list_state.selected()
}
/// Gets the name of the currently selected profile.
pub fn get_selected_profile_name(&self) -> Option<&String> {
self.list_state.selected().and_then(|i| self.profiles.get(i))
}
/// Populates the profile list and updates/resets the selection.
pub fn set_profiles(&mut self, new_profiles: Vec<String>) {
let current_selection_index = self.list_state.selected();
self.profiles = new_profiles;
if self.profiles.is_empty() {
self.list_state.select(None);
} else {
let new_selection = match current_selection_index {
Some(index) => Some(index.min(self.profiles.len() - 1)),
None => Some(0),
};
self.list_state.select(new_selection);
}
}
/// Selects the next profile in the list, wrapping around.
pub fn next(&mut self) {
if self.profiles.is_empty() {
self.list_state.select(None);
return;
}
let i = match self.list_state.selected() {
Some(i) => if i >= self.profiles.len() - 1 { 0 } else { i + 1 },
None => 0,
};
self.list_state.select(Some(i));
}
/// Selects the previous profile in the list, wrapping around.
pub fn previous(&mut self) {
if self.profiles.is_empty() {
self.list_state.select(None);
return;
}
let i = match self.list_state.selected() {
Some(i) => if i == 0 { self.profiles.len() - 1 } else { i - 1 },
None => self.profiles.len() - 1,
};
self.list_state.select(Some(i));
}
}

View File

@@ -0,0 +1,295 @@
// src/state/pages/auth.rs
use crate::state::pages::canvas_state::CanvasState;
use lazy_static::lazy_static;
lazy_static! {
pub static ref AVAILABLE_ROLES: Vec<String> = vec![
"admin".to_string(),
"moderator".to_string(),
"accountant".to_string(),
"viewer".to_string(),
];
}
/// Represents the authenticated session state
#[derive(Default)]
pub struct AuthState {
pub auth_token: Option<String>,
pub user_id: Option<String>,
pub role: Option<String>,
pub decoded_username: Option<String>,
}
/// Represents the state of the Login form UI
#[derive(Default)]
pub struct LoginState {
pub username: String,
pub password: String,
pub error_message: Option<String>,
pub current_field: usize,
pub current_cursor_pos: usize,
pub has_unsaved_changes: bool,
}
/// Represents the state of the Registration form UI
#[derive(Default, Clone)]
pub struct RegisterState {
pub username: String,
pub email: String,
pub password: String,
pub password_confirmation: String,
pub role: String,
pub error_message: Option<String>,
pub current_field: usize,
pub current_cursor_pos: usize,
pub has_unsaved_changes: bool,
pub show_role_suggestions: bool,
pub role_suggestions: Vec<String>,
pub selected_suggestion_index: Option<usize>,
pub in_suggestion_mode: bool,
}
impl AuthState {
/// Creates a new empty AuthState (unauthenticated)
pub fn new() -> Self {
Self {
auth_token: None,
user_id: None,
role: None,
decoded_username: None,
}
}
}
impl LoginState {
/// Creates a new empty LoginState
pub fn new() -> Self {
Self {
username: String::new(),
password: String::new(),
error_message: None,
current_field: 0,
current_cursor_pos: 0,
has_unsaved_changes: false,
}
}
}
impl RegisterState {
/// Creates a new empty RegisterState
pub fn new() -> Self {
Self {
username: String::new(),
email: String::new(),
password: String::new(),
password_confirmation: String::new(),
role: String::new(),
error_message: None,
current_field: 0,
current_cursor_pos: 0,
has_unsaved_changes: false,
show_role_suggestions: false,
role_suggestions: Vec::new(),
selected_suggestion_index: None,
in_suggestion_mode: false,
}
}
/// Updates role suggestions based on current input
pub fn update_role_suggestions(&mut self) {
let current_input = self.role.to_lowercase();
self.role_suggestions = AVAILABLE_ROLES
.iter()
.filter(|role| role.to_lowercase().contains(&current_input))
.cloned()
.collect();
self.show_role_suggestions = !self.role_suggestions.is_empty();
}
}
impl CanvasState for LoginState {
fn current_field(&self) -> usize {
self.current_field
}
fn current_cursor_pos(&self) -> usize {
let len = match self.current_field {
0 => self.username.len(),
1 => self.password.len(),
_ => 0,
};
self.current_cursor_pos.min(len)
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
vec![&self.username, &self.password]
}
fn get_current_input(&self) -> &str {
match self.current_field {
0 => &self.username,
1 => &self.password,
_ => "",
}
}
fn get_current_input_mut(&mut self) -> &mut String {
match self.current_field {
0 => &mut self.username,
1 => &mut self.password,
_ => panic!("Invalid current_field index in LoginState"),
}
}
fn fields(&self) -> Vec<&str> {
vec!["Username/Email", "Password"]
}
fn set_current_field(&mut self, index: usize) {
if index < 2 {
self.current_field = index;
let len = match self.current_field {
0 => self.username.len(),
1 => self.password.len(),
_ => 0,
};
self.current_cursor_pos = self.current_cursor_pos.min(len);
}
}
fn set_current_cursor_pos(&mut self, pos: usize) {
let len = match self.current_field {
0 => self.username.len(),
1 => self.password.len(),
_ => 0,
};
self.current_cursor_pos = pos.min(len);
}
fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed;
}
fn get_suggestions(&self) -> Option<&[String]> {
None
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
None
}
}
impl CanvasState for RegisterState {
fn current_field(&self) -> usize {
self.current_field
}
fn current_cursor_pos(&self) -> usize {
let len = match self.current_field {
0 => self.username.len(),
1 => self.email.len(),
2 => self.password.len(),
3 => self.password_confirmation.len(),
4 => self.role.len(),
_ => 0,
};
self.current_cursor_pos.min(len)
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
vec![
&self.username,
&self.email,
&self.password,
&self.password_confirmation,
&self.role,
]
}
fn get_current_input(&self) -> &str {
match self.current_field {
0 => &self.username,
1 => &self.email,
2 => &self.password,
3 => &self.password_confirmation,
4 => &self.role,
_ => "",
}
}
fn get_current_input_mut(&mut self) -> &mut String {
match self.current_field {
0 => &mut self.username,
1 => &mut self.email,
2 => &mut self.password,
3 => &mut self.password_confirmation,
4 => &mut self.role,
_ => panic!("Invalid current_field index in RegisterState"),
}
}
fn fields(&self) -> Vec<&str> {
vec![
"Username",
"Email (Optional)",
"Password (Optional)",
"Confirm Password",
"Role (Optional)"
]
}
fn set_current_field(&mut self, index: usize) {
if index < 5 {
self.current_field = index;
let len = match self.current_field {
0 => self.username.len(),
1 => self.email.len(),
2 => self.password.len(),
3 => self.password_confirmation.len(),
4 => self.role.len(),
_ => 0,
};
self.current_cursor_pos = self.current_cursor_pos.min(len);
}
}
fn set_current_cursor_pos(&mut self, pos: usize) {
let len = match self.current_field {
0 => self.username.len(),
1 => self.email.len(),
2 => self.password.len(),
3 => self.password_confirmation.len(),
4 => self.role.len(),
_ => 0,
};
self.current_cursor_pos = pos.min(len);
}
fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed;
}
fn get_suggestions(&self) -> Option<&[String]> {
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
Some(&self.role_suggestions)
} else {
None
}
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
if self.current_field == 4 && self.in_suggestion_mode && self.show_role_suggestions {
self.selected_suggestion_index
} else {
None
}
}
}

View File

@@ -0,0 +1,20 @@
// src/state/canvas_state.rs
pub trait CanvasState {
fn current_field(&self) -> usize;
fn current_cursor_pos(&self) -> usize;
fn has_unsaved_changes(&self) -> bool;
fn inputs(&self) -> Vec<&String>;
fn get_current_input(&self) -> &str;
fn get_current_input_mut(&mut self) -> &mut String;
fn fields(&self) -> Vec<&str>;
fn set_current_field(&mut self, index: usize);
fn set_current_cursor_pos(&mut self, pos: usize);
fn set_has_unsaved_changes(&mut self, changed: bool);
// --- Autocomplete Support ---
fn get_suggestions(&self) -> Option<&[String]>;
fn get_selected_suggestion_index(&self) -> Option<usize>;
}

View File

@@ -0,0 +1,145 @@
// src/state/pages/form.rs
use crate::config::colors::themes::Theme;
use ratatui::layout::Rect;
use ratatui::Frame;
use crate::state::pages::canvas_state::CanvasState;
pub struct FormState {
pub id: i64,
pub fields: Vec<String>, // Use Vec<String> for dynamic field names
pub values: Vec<String>, // Store field values dynamically
pub current_field: usize,
pub has_unsaved_changes: bool,
pub current_cursor_pos: usize,
}
impl FormState {
/// Create a new FormState with dynamic fields.
pub fn new(fields: Vec<String>) -> Self {
let values = vec![String::new(); fields.len()]; // Initialize values for each field
FormState {
id: 0,
fields,
values,
current_field: 0,
has_unsaved_changes: false,
current_cursor_pos: 0,
}
}
pub fn render(
&self,
f: &mut Frame,
area: Rect,
theme: &Theme,
is_edit_mode: bool,
total_count: u64,
current_position: u64,
) {
let fields: Vec<&str> = self.fields.iter().map(|s| s.as_str()).collect();
let values: Vec<&String> = self.values.iter().collect();
crate::components::form::form::render_form(
f,
area,
self,
&fields,
&self.current_field,
&values,
theme,
is_edit_mode,
total_count,
current_position,
);
}
pub fn reset_to_empty(&mut self) {
self.id = 0; // Reset ID to 0 for new entries
self.values.iter_mut().for_each(|v| v.clear()); // Clear all values
self.has_unsaved_changes = false;
}
pub fn get_current_input(&self) -> &str {
self.values
.get(self.current_field)
.map(|s| s.as_str())
.unwrap_or("")
}
pub fn get_current_input_mut(&mut self) -> &mut String {
self.values
.get_mut(self.current_field)
.expect("Invalid current_field index")
}
pub fn update_from_response(&mut self, response: common::proto::multieko2::adresar::AdresarResponse) {
self.id = response.id;
self.values = vec![
response.firma, response.kz, response.drc,
response.ulica, response.psc, response.mesto,
response.stat, response.banka, response.ucet,
response.skladm, response.ico, response.kontakt,
response.telefon, response.skladu, response.fax,
];
}
}
impl CanvasState for FormState {
fn current_field(&self) -> usize {
self.current_field
}
fn current_cursor_pos(&self) -> usize {
self.current_cursor_pos
}
fn has_unsaved_changes(&self) -> bool {
self.has_unsaved_changes
}
fn inputs(&self) -> Vec<&String> {
self.values.iter().collect()
}
fn get_current_input(&self) -> &str {
self.values
.get(self.current_field)
.map(|s| s.as_str())
.unwrap_or("")
}
fn get_current_input_mut(&mut self) -> &mut String {
self.values
.get_mut(self.current_field)
.expect("Invalid current_field index")
}
fn fields(&self) -> Vec<&str> {
self.fields.iter().map(|s| s.as_str()).collect()
}
// --- Implement the setter methods ---
fn set_current_field(&mut self, index: usize) {
if index < self.fields.len() { // Basic bounds check
self.current_field = index;
}
}
fn set_current_cursor_pos(&mut self, pos: usize) {
// Optional: Add validation based on current input length if needed
self.current_cursor_pos = pos;
}
fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed;
}
// --- Autocomplete Support (Not Used for FormState) ---
fn get_suggestions(&self) -> Option<&[String]> {
None // FormState doesn't provide suggestions
}
fn get_selected_suggestion_index(&self) -> Option<usize> {
None // FormState doesn't have selected suggestions
}
}

View File

@@ -0,0 +1,25 @@
// src/state/pages/intro.rs
#[derive(Default, Clone, Debug)]
pub struct IntroState {
pub selected_option: usize,
}
impl IntroState {
pub fn new() -> Self {
Self::default()
}
pub fn next_option(&mut self) {
if self.selected_option < 3 {
self.selected_option += 1;
}
}
pub fn previous_option(&mut self) {
if self.selected_option > 0 {
self.selected_option -= 1
}
}
}

View File

@@ -1,44 +0,0 @@
// src/client/ui/handlers/state.rs
use std::env;
#[derive(Default)]
pub struct UiState {
pub show_sidebar: bool,
// Add other UI-related states here
}
pub struct AppState {
// Core editor state
pub is_saved: bool,
pub current_dir: String,
pub total_count: u64,
pub current_position: u64,
// UI preferences
pub ui: UiState,
}
impl AppState {
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
let current_dir = env::current_dir()?
.to_string_lossy()
.to_string();
Ok(AppState {
is_saved: false,
current_dir,
total_count: 0,
current_position: 0,
ui: UiState::default(),
})
}
// Existing methods remain unchanged
pub fn update_total_count(&mut self, total_count: u64) {
self.total_count = total_count;
}
pub fn update_current_position(&mut self, current_position: u64) {
self.current_position = current_position;
}
}

View File

@@ -1 +0,0 @@
cat src/modes/handlers/event.rs src/state/state.rs src/ui/handlers.rs src/ui/handlers/render.rs src/ui/handlers/ui.rs src/components/handlers.rs

View File

@@ -0,0 +1,11 @@
// src/tui/functions.rs
pub mod admin;
pub mod intro;
pub mod login;
pub mod form;
pub mod common;
pub use admin::*;
pub use intro::*;
pub use form::*;

View File

@@ -0,0 +1,11 @@
use crate::state::app::state::AppState;
use crate::state::pages::admin::AdminState;
pub fn handle_admin_selection(app_state: &mut AppState, admin_state: &AdminState) {
let profiles = &app_state.profile_tree.profiles;
if let Some(selected_index) = admin_state.get_selected_index() {
if let Some(profile) = profiles.get(selected_index) {
app_state.selected_profile = Some(profile.name.clone());
}
}
}

View File

@@ -0,0 +1,5 @@
// src/tui/functions/common.rs
pub mod form;
pub mod login;
pub mod register;

View File

@@ -1,20 +1,29 @@
// src/modes/handlers/common.rs
// src/tui/functions/common/form.rs
use crate::tui::terminal::grpc_client::GrpcClient;
use crate::ui::handlers::form::FormState;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::form::FormState;
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SaveOutcome {
NoChange, // Nothing needed saving
UpdatedExisting, // An existing record was updated
CreatedNew(i64), // A new record was created (include its new ID)
}
/// Shared logic for saving the current form state
pub async fn save(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
is_saved: &mut bool,
current_position: &mut u64,
total_count: u64,
) -> Result<String, Box<dyn std::error::Error>> {
) -> Result<SaveOutcome, Box<dyn std::error::Error>> { // <-- Return SaveOutcome
if !form_state.has_unsaved_changes {
return Ok(SaveOutcome::NoChange); // Early exit if no changes
}
let is_new = *current_position == total_count + 1;
let message = if is_new {
let outcome = if is_new {
let post_request = PostAdresarRequest {
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
@@ -33,10 +42,9 @@ pub async fn save(
fax: form_state.values[14].clone(),
};
let response = grpc_client.post_adresar(post_request).await?;
let new_total = grpc_client.get_adresar_count().await?;
*current_position = new_total;
form_state.id = response.into_inner().id;
"New entry created".to_string()
let new_id = response.into_inner().id;
form_state.id = new_id;
SaveOutcome::CreatedNew(new_id) // <-- Return CreatedNew with ID
} else {
let put_request = PutAdresarRequest {
id: form_state.id,
@@ -57,70 +65,11 @@ pub async fn save(
fax: form_state.values[14].clone(),
};
let _ = grpc_client.put_adresar(put_request).await?;
"Entry updated".to_string()
SaveOutcome::UpdatedExisting
};
*is_saved = true;
form_state.has_unsaved_changes = false;
Ok(message)
}
/// Shared logic for force quitting the application
pub fn force_quit() -> (bool, String) {
(true, "Force quitting application".to_string())
}
/// Shared logic for saving and quitting
pub async fn save_and_quit(
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
let is_new = *current_position == total_count + 1;
if is_new {
let post_request = PostAdresarRequest {
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
drc: form_state.values[2].clone(),
ulica: form_state.values[3].clone(),
psc: form_state.values[4].clone(),
mesto: form_state.values[5].clone(),
stat: form_state.values[6].clone(),
banka: form_state.values[7].clone(),
ucet: form_state.values[8].clone(),
skladm: form_state.values[9].clone(),
ico: form_state.values[10].clone(),
kontakt: form_state.values[11].clone(),
telefon: form_state.values[12].clone(),
skladu: form_state.values[13].clone(),
fax: form_state.values[14].clone(),
};
let _ = grpc_client.post_adresar(post_request).await?;
} else {
let put_request = PutAdresarRequest {
id: form_state.id,
firma: form_state.values[0].clone(),
kz: form_state.values[1].clone(),
drc: form_state.values[2].clone(),
ulica: form_state.values[3].clone(),
psc: form_state.values[4].clone(),
mesto: form_state.values[5].clone(),
stat: form_state.values[6].clone(),
banka: form_state.values[7].clone(),
ucet: form_state.values[8].clone(),
skladm: form_state.values[9].clone(),
ico: form_state.values[10].clone(),
kontakt: form_state.values[11].clone(),
telefon: form_state.values[12].clone(),
skladu: form_state.values[13].clone(),
fax: form_state.values[14].clone(),
};
let _ = grpc_client.put_adresar(put_request).await?;
}
Ok((true, "Saved and exiting application".to_string()))
Ok(outcome)
}
/// Discard changes since last save

View File

@@ -0,0 +1,109 @@
// src/tui/functions/common/login.rs
use crate::services::auth::AuthClient;
use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::app::state::AppState;
use crate::state::pages::canvas_state::CanvasState;
use crate::ui::handlers::context::DialogPurpose;
/// Attempts to log the user in using the provided credentials via gRPC.
/// Updates AuthState and AppState on success or failure.
pub async fn save(
auth_state: &mut AuthState,
login_state: &mut LoginState,
auth_client: &mut AuthClient,
app_state: &mut AppState,
) -> Result<String, Box<dyn std::error::Error>> {
let identifier = login_state.username.clone();
let password = login_state.password.clone();
// Clear previous error/dialog state before attempting
login_state.error_message = None;
// Use the helper to ensure dialog is hidden and cleared properly
app_state.hide_dialog();
// Call the gRPC login method
match auth_client.login(identifier, password).await {
Ok(response) => {
// Store authentication details on success
auth_state.auth_token = Some(response.access_token.clone());
auth_state.user_id = Some(response.user_id.clone());
auth_state.role = Some(response.role.clone());
auth_state.decoded_username = Some(response.username.clone());
login_state.set_has_unsaved_changes(false);
let success_message = format!(
"Login Successful!\n\n\
Username: {}\n\
User ID: {}\n\
Role: {}",
response.username,
response.user_id,
response.role
);
app_state.show_dialog(
"Login Success",
&success_message,
vec!["Menu".to_string(), "Exit".to_string()],
DialogPurpose::LoginSuccess,
);
Ok("Login successful, details shown in dialog.".to_string())
}
Err(e) => {
let error_message = format!("{}", e);
// Use the helper method to configure and show the dialog
app_state.show_dialog(
"Login Failed",
&error_message,
vec!["OK".to_string()],
DialogPurpose::LoginFailed,
);
login_state.set_has_unsaved_changes(true);
Ok(format!("Login failed: {}", error_message))
}
}
}
/// Reverts the login form fields to empty and returns to the previous screen (Intro).
pub async fn revert(
login_state: &mut LoginState,
app_state: &mut AppState,
) -> String {
// Clear the input fields
login_state.username.clear();
login_state.password.clear();
login_state.error_message = None;
login_state.set_has_unsaved_changes(false);
"Login reverted".to_string()
}
pub async fn back_to_main(
login_state: &mut LoginState,
app_state: &mut AppState,
) -> String {
// Clear the input fields
login_state.username.clear();
login_state.password.clear();
login_state.error_message = None;
login_state.set_has_unsaved_changes(false);
// Ensure dialog is hidden if revert is called
app_state.hide_dialog(); // Uncomment if needed
// Navigation logic (currently disabled in original code)
app_state.ui.show_login = false;
app_state.ui.show_intro = true;
// Reset focus state
app_state.ui.focus_outside_canvas = false;
app_state.focused_button_index= 0;
"Returned to main menu".to_string()
}

View File

@@ -0,0 +1,154 @@
// src/tui/functions/common/register.rs
use crate::{
services::auth::AuthClient,
state::{
pages::auth::RegisterState,
app::state::AppState,
pages::canvas_state::CanvasState,
},
ui::handlers::context::DialogPurpose,
};
/// Attempts to register the user using the provided details via gRPC.
/// Updates RegisterState and AppState on success or failure.
pub async fn save(
register_state: &mut RegisterState,
auth_client: &mut AuthClient,
app_state: &mut AppState,
) -> Result<String, Box<dyn std::error::Error>> {
let username = register_state.username.clone();
let email = register_state.email.clone();
// Handle optional passwords: send None if empty, Some(value) otherwise
let password = if register_state.password.is_empty() {
None
} else {
Some(register_state.password.clone())
};
let password_confirmation = if register_state.password_confirmation.is_empty() {
None
} else {
Some(register_state.password_confirmation.clone())
};
let role = if register_state.role.is_empty() {
None
} else {
Some(register_state.role.clone())
};
// Basic client-side validation (example)
if username.is_empty() {
app_state.show_dialog(
"Registration Failed",
"Username cannot be empty.",
vec!["OK".to_string()],
DialogPurpose::RegisterFailed,
);
register_state.error_message = Some("Username cannot be empty.".to_string());
return Ok("Registration failed: Username cannot be empty.".to_string());
}
if password.is_some() && password != password_confirmation {
app_state.show_dialog(
"Registration Failed",
"Passwords do not match.",
vec!["OK".to_string()],
DialogPurpose::RegisterFailed,
);
register_state.error_message = Some("Passwords do not match.".to_string());
return Ok("Registration failed: Passwords do not match.".to_string());
}
// Clear previous error/dialog state before attempting
register_state.error_message = None;
app_state.hide_dialog();
// Call the gRPC register method
match auth_client.register(username, email, password, password_confirmation, role).await {
Ok(response) => {
// Clear fields on success? Optional, maybe wait for dialog confirmation.
// register_state.username.clear();
// register_state.email.clear();
// register_state.password.clear();
// register_state.password_confirmation.clear();
register_state.set_has_unsaved_changes(false);
let success_message = format!(
"Registration Successful!\n\n\
User ID: {}\n\
Username: {}\n\
Email: {}\n\
Role: {}",
response.id,
response.username,
response.email,
response.role
);
// Show success dialog
app_state.show_dialog(
"Registration Success",
&success_message,
vec!["OK".to_string()], // Simple OK for now
DialogPurpose::RegisterSuccess,
);
Ok("Registration successful, details shown in dialog.".to_string())
}
Err(e) => {
let error_message = format!("{}", e);
register_state.error_message = Some(error_message.clone());
register_state.set_has_unsaved_changes(true); // Keep changes on error
// Show error dialog
app_state.show_dialog(
"Registration Failed",
&error_message,
vec!["OK".to_string()],
DialogPurpose::RegisterFailed,
);
Ok(format!("Registration failed: {}", error_message))
}
}
}
/// Clears the registration form fields.
pub async fn revert(
register_state: &mut RegisterState,
_app_state: &mut AppState, // Keep signature consistent if needed elsewhere
) -> String {
register_state.username.clear();
register_state.email.clear();
register_state.password.clear();
register_state.password_confirmation.clear();
register_state.role.clear();
register_state.error_message = None;
register_state.set_has_unsaved_changes(false);
register_state.current_field = 0; // Reset focus to first field
register_state.current_cursor_pos = 0;
"Registration form cleared".to_string()
}
/// Clears the form and returns to the intro screen.
pub async fn back_to_main(
register_state: &mut RegisterState,
app_state: &mut AppState,
) -> String {
// Clear fields first
let _ = revert(register_state, app_state).await;
// Ensure dialog is hidden
app_state.hide_dialog();
// Navigation logic
app_state.ui.show_register = false;
app_state.ui.show_intro = true;
// Reset focus state
app_state.ui.focus_outside_canvas = false;
app_state.focused_button_index = 0;
"Returned to main menu".to_string()
}

View File

@@ -0,0 +1,89 @@
// src/tui/functions/form.rs
use crate::state::pages::form::FormState;
use crate::services::grpc_client::GrpcClient;
use crate::state::pages::canvas_state::CanvasState;
pub async fn handle_action(
action: &str,
form_state: &mut FormState,
grpc_client: &mut GrpcClient,
current_position: &mut u64,
total_count: u64,
ideal_cursor_column: &mut usize,
) -> Result<String, Box<dyn std::error::Error>> {
// TODO store unsaved changes without deleting form state values
// First check for unsaved changes in both cases
if form_state.has_unsaved_changes() {
return Ok(
"Unsaved changes. Save (Ctrl+S) or Revert (Ctrl+R) before navigating."
.to_string(),
);
}
match action {
"previous_entry" => {
let new_position = current_position.saturating_sub(1);
if new_position >= 1 {
*current_position = new_position;
let response = grpc_client.get_adresar_by_position(*current_position).await?;
// Direct field assignments
form_state.id = response.id;
form_state.values = vec![
response.firma, response.kz, response.drc,
response.ulica, response.psc, response.mesto,
response.stat, response.banka, response.ucet,
response.skladm, response.ico, response.kontakt,
response.telefon, response.skladu, response.fax,
];
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else { 0 };
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
form_state.has_unsaved_changes = false;
Ok(format!("Loaded form entry {}", *current_position))
} else {
Ok("Already at first form entry".into())
}
}
"next_entry" => {
if *current_position <= total_count {
*current_position += 1;
if *current_position <= total_count {
let response = grpc_client.get_adresar_by_position(*current_position).await?;
// Direct field assignments
form_state.id = response.id;
form_state.values = vec![
response.firma, response.kz, response.drc,
response.ulica, response.psc, response.mesto,
response.stat, response.banka, response.ucet,
response.skladm, response.ico, response.kontakt,
response.telefon, response.skladu, response.fax,
];
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else { 0 };
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
form_state.has_unsaved_changes = false;
Ok(format!("Loaded form entry {}", *current_position))
} else {
form_state.reset_to_empty();
form_state.current_field = 0;
form_state.current_cursor_pos = 0;
*ideal_cursor_column = 0;
Ok("New form entry mode".into())
}
} else {
Ok("Already at last entry".into())
}
}
_ => Err("Unknown form action".into())
}
}

View File

@@ -0,0 +1,31 @@
// src/tui/functions/intro.rs
use crate::state::app::state::AppState;
pub fn handle_intro_selection(app_state: &mut AppState, index: usize) {
match index { // Use index directly
0 => { // Continue
app_state.ui.show_form = true;
app_state.ui.show_admin = false;
app_state.ui.show_login = false;
}
1 => { // Admin
app_state.ui.show_form = false;
app_state.ui.show_admin = true;
app_state.ui.show_login = false;
}
2 => { // Login
app_state.ui.show_form = false;
app_state.ui.show_admin = false;
app_state.ui.show_login = true;
}
3 => { // Register
app_state.ui.show_intro = false;
app_state.ui.show_register = true;
app_state.ui.focus_outside_canvas = false;
app_state.focused_button_index = 0;
}
_ => {}
}
app_state.ui.show_intro = false;
}

View File

@@ -0,0 +1,13 @@
// src/tui/functions/login.rs
pub async fn handle_action(action: &str,) -> Result<String, Box<dyn std::error::Error>> {
match action {
"previous_entry" => {
Ok("Previous entry at tui/functions/login.rs not implemented".into())
}
"next_entry" => {
Ok("Next entry at tui/functions/login.rs not implemented".into())
}
_ => Err("Unknown login action".into())
}
}

View File

@@ -1,2 +1,5 @@
// src/tui/mod.rs
pub mod terminal;
pub mod functions;
pub use functions::*;

View File

@@ -1,11 +1,7 @@
// src/tui/terminal.rs
pub mod core;
pub mod grpc_client;
pub mod commands;
pub mod event_reader;
pub use core::TerminalCore;
pub use grpc_client::GrpcClient;
pub use commands::CommandHandler;
pub use event_reader::EventReader;

View File

@@ -1,46 +0,0 @@
// src/tui/terminal/commands.rs
use crate::tui::terminal::core::TerminalCore;
pub struct CommandHandler {
is_saved: bool,
}
impl CommandHandler {
pub fn new() -> Self {
Self { is_saved: false }
}
pub async fn handle_command(
&mut self,
action: &str,
terminal: &mut TerminalCore,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"quit" => self.handle_quit(terminal).await,
"force_quit" => self.handle_force_quit(terminal).await,
"save_and_quit" => self.handle_save_quit(terminal).await,
_ => Ok((false, format!("Unknown command: {}", action))),
}
}
async fn handle_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
if self.is_saved {
terminal.cleanup()?;
Ok((true, "Exiting.".into()))
} else {
Ok((false, "No changes saved. Use :q! to force quit.".into()))
}
}
async fn handle_force_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
terminal.cleanup()?;
Ok((true, "Force exiting without saving.".into()))
}
async fn handle_save_quit(&mut self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
self.is_saved = true;
terminal.cleanup()?;
Ok((true, "State saved. Exiting.".into()))
}
}

View File

@@ -3,7 +3,7 @@
use crossterm::{
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
cursor::{SetCursorStyle, EnableBlinking, Show, MoveTo},
cursor::{SetCursorStyle, EnableBlinking, Show, Hide, MoveTo},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io::{self, stdout, Write};
@@ -64,6 +64,22 @@ impl TerminalCore {
)?;
Ok(())
}
pub fn show_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
execute!(
self.terminal.backend_mut(),
Show
)?;
Ok(())
}
pub fn hide_cursor(&mut self) -> Result<(), Box<dyn std::error::Error>> {
execute!(
self.terminal.backend_mut(),
Hide
)?;
Ok(())
}
}
impl Drop for TerminalCore {

View File

@@ -1,9 +1,10 @@
// src/client/ui/handlers.rs
pub mod ui;
pub mod form;
pub mod render;
pub mod rat_state;
pub mod context;
pub use ui::run_ui;
pub use rat_state::*;
pub use context::*;

View File

@@ -0,0 +1,21 @@
// src/ui/handlers/context.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UiContext {
Intro,
Login,
Register,
Admin,
Dialog,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DialogPurpose {
LoginSuccess,
LoginFailed,
RegisterSuccess,
RegisterFailed,
// TODO in the future:
// ConfirmQuit,
}

View File

@@ -1,73 +0,0 @@
// src/client/ui/handlers/form.rs
use crate::config::colors::Theme;
use ratatui::layout::Rect;
use ratatui::Frame;
pub struct FormState {
pub id: i64,
pub fields: Vec<String>, // Use Vec<String> for dynamic field names
pub values: Vec<String>, // Store field values dynamically
pub current_field: usize,
pub has_unsaved_changes: bool,
pub current_cursor_pos: usize,
}
impl FormState {
/// Create a new FormState with dynamic fields.
pub fn new(fields: Vec<String>) -> Self {
let values = vec![String::new(); fields.len()]; // Initialize values for each field
FormState {
id: 0,
fields,
values,
current_field: 0,
has_unsaved_changes: false,
current_cursor_pos: 0,
}
}
pub fn render(
&self,
f: &mut Frame,
area: Rect,
theme: &Theme,
is_edit_mode: bool,
total_count: u64,
current_position: u64,
) {
let fields: Vec<&str> = self.fields.iter().map(|s| s.as_str()).collect();
let values: Vec<&String> = self.values.iter().collect();
crate::components::handlers::form::render_form(
f,
area,
self,
&fields,
&self.current_field,
&values,
theme,
is_edit_mode,
total_count,
current_position,
);
}
pub fn reset_to_empty(&mut self) {
self.id = 0; // Reset ID to 0 for new entries
self.values.iter_mut().for_each(|v| v.clear()); // Clear all values
self.has_unsaved_changes = false;
}
pub fn get_current_input(&self) -> &str {
self.values
.get(self.current_field)
.map(|s| s.as_str())
.unwrap_or("")
}
pub fn get_current_input_mut(&mut self) -> &mut String {
self.values
.get_mut(self.current_field)
.expect("Invalid current_field index")
}
}

View File

@@ -1,7 +1,7 @@
// src/ui/handlers/rat_state.rs
use crossterm::event::{KeyCode, KeyModifiers};
use crate::config::config::Config;
use crate::state::state::UiState;
use crate::config::binds::config::Config;
use crate::state::app::state::UiState;
pub struct UiStateHandler;
@@ -21,4 +21,18 @@ impl UiStateHandler {
false
}
pub fn toggle_buffer_list(
ui_state: &mut UiState,
config: &Config,
key: KeyCode,
modifiers: KeyModifiers,
) -> bool {
if let Some(action) = config.get_common_action(key, modifiers) {
if action == "toggle_buffer_list" {
ui_state.show_buffer_list = !ui_state.show_buffer_list;
return true;
}
}
false
}
}

View File

@@ -1,15 +1,34 @@
// src/ui/handlers/render.rs
use crate::components::{render_command_line, render_preview_card, render_status_line};
use crate::config::colors::Theme;
use crate::components::{
render_background,
render_buffer_list,
render_command_line,
render_status_line,
intro::intro::render_intro,
handlers::sidebar::{self, calculate_sidebar_layout},
form::form::render_form,
auth::{login::render_login, register::render_register},
};
use crate::config::colors::themes::Theme;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::Frame;
use super::form::FormState;
use crate::state::state::UiState;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::pages::intro::IntroState;
use crate::state::app::state::AppState;
use crate::state::pages::admin::AdminState;
pub fn render_ui(
f: &mut Frame,
form_state: &mut FormState,
auth_state: &mut AuthState,
login_state: &LoginState,
register_state: &RegisterState,
intro_state: &IntroState,
admin_state: &mut AdminState,
theme: &Theme,
is_edit_mode: bool,
total_count: u64,
@@ -18,84 +37,142 @@ pub fn render_ui(
command_input: &str,
command_mode: bool,
command_message: &str,
ui_state: &UiState,
app_state: &AppState,
) {
// Root layout - vertical split for main content, status, and command line
let root = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(10), // Main content area
Constraint::Length(1), // Status line
Constraint::Length(1), // Command line
])
.split(f.area());
render_background(f, f.area(), theme);
// Main content area layout
let main_content_area = root[0];
// Split into sidebar + content or just content
let (sidebar_area, content_area) = if ui_state.show_sidebar {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(16), // Fixed sidebar width
Constraint::Fill(1), // Remaining space for form/preview
])
.split(main_content_area);
(Some(chunks[0]), chunks[1])
// Adjust layout based on whether buffer list is shown
let constraints = if app_state.ui.show_buffer_list {
vec![
Constraint::Length(2), // Buffer list
Constraint::Min(1), // Main content
Constraint::Length(1), // Status line
Constraint::Length(1), // Command line
]
} else {
(None, main_content_area)
vec![
Constraint::Min(1), // Main content
Constraint::Length(1), // Status line (no buffer list)
Constraint::Length(1), // Command line
]
};
// Split content area into form and preview
let content_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(60),
Constraint::Percentage(40),
])
.split(content_area);
let root = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints)
.split(f.area());
// Render form in the left content area
form_state.render(
f,
content_chunks[0],
theme,
is_edit_mode,
total_count,
current_position,
);
let mut buffer_list_area = None;
let main_content_area;
let status_line_area;
let command_line_area;
// Render preview card in the right content area
let preview_values: Vec<&String> = form_state.values.iter().collect();
render_preview_card(
f,
content_chunks[1],
&preview_values,
theme,
);
// Render sidebar if enabled
if let Some(sidebar_rect) = sidebar_area {
crate::components::handlers::sidebar::render_sidebar(f, sidebar_rect, theme);
// Assign areas based on layout
if app_state.ui.show_buffer_list {
buffer_list_area = Some(root[0]);
main_content_area = root[1];
status_line_area = root[2];
command_line_area = root[3];
} else {
main_content_area = root[0];
status_line_area = root[1];
command_line_area = root[2];
}
// Status line
render_status_line(
f,
root[1],
current_dir,
theme,
is_edit_mode,
);
if app_state.ui.show_intro {
render_intro(f, intro_state, main_content_area, theme);
} else if app_state.ui.show_register {
render_register(
f,
main_content_area,
theme,
register_state,
app_state,
register_state.current_field < 4
);
} else if app_state.ui.show_login {
render_login(
f,
main_content_area,
theme,
login_state,
app_state,
login_state.current_field < 2
);
} else if app_state.ui.show_admin {
crate::components::admin::admin_panel::render_admin_panel(
f,
auth_state,
admin_state,
main_content_area,
theme,
&app_state.profile_tree,
&app_state.selected_profile,
);
} else if app_state.ui.show_form {
let (sidebar_area, form_area) = calculate_sidebar_layout(
app_state.ui.show_sidebar,
main_content_area
);
// Command line
render_command_line(
f,
root[2],
command_input,
command_mode,
theme,
command_message,
);
if let Some(sidebar_rect) = sidebar_area {
sidebar::render_sidebar(
f,
sidebar_rect,
theme,
&app_state.profile_tree,
&app_state.selected_profile
);
}
// This change makes the form stay stationary when toggling sidebar
let available_width = form_area.width;
let form_constraint = if available_width >= 80 {
// Use main_content_area for centering when enough space
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Min(0),
Constraint::Length(80),
Constraint::Min(0),
])
.split(main_content_area)[1]
} else {
// Use form_area (post sidebar) when limited space
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Min(0),
Constraint::Length(80.min(available_width)),
Constraint::Min(0),
])
.split(form_area)[1]
};
// Convert fields to &[&str] and values to &[&String]
let fields: Vec<&str> = form_state.fields.iter().map(|s| s.as_str()).collect();
let values: Vec<&String> = form_state.values.iter().collect();
render_form(
f,
form_constraint,
form_state,
&fields,
&form_state.current_field,
&values,
theme,
is_edit_mode,
total_count,
current_position,
);
}
// Render buffer list if enabled and area is available
if let Some(area) = buffer_list_area {
if app_state.ui.show_buffer_list {
render_buffer_list(f, area, theme, app_state);
}
}
render_status_line(f, status_line_area, current_dir, theme, is_edit_mode);
render_command_line(f, command_line_area, command_input, command_mode, theme, command_message);
}

View File

@@ -1,154 +1,283 @@
// src/client/ui/handlers/ui.rs
use crate::tui::terminal::TerminalCore;
use crate::tui::terminal::GrpcClient;
use crate::tui::terminal::CommandHandler;
use crate::tui::terminal::EventReader;
use crate::config::colors::Theme;
use crate::config::config::Config;
use crate::ui::handlers::{form::FormState, render::render_ui};
use crate::modes::handlers::event::EventHandler;
use crate::state::state::AppState;
// src/ui/handlers/ui.rs
use crate::config::binds::config::Config;
use crate::config::colors::themes::Theme;
use crate::modes::common::commands::CommandHandler;
use crate::modes::handlers::event::{EventHandler, EventOutcome}; // Import EventOutcome
use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
use crate::services::grpc_client::GrpcClient;
use crate::services::ui_service::UiService;
use crate::state::pages::canvas_state::CanvasState;
use crate::state::pages::form::FormState;
use crate::state::pages::auth::AuthState;
use crate::state::pages::auth::LoginState;
use crate::state::pages::auth::RegisterState;
use crate::state::pages::admin::AdminState;
use crate::state::pages::intro::IntroState;
use crate::state::app::state::AppState;
// Import SaveOutcome
use crate::tui::terminal::{EventReader, TerminalCore};
use crate::ui::handlers::render::render_ui;
use crossterm::cursor::SetCursorStyle;
pub async fn run_ui() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?;
let mut terminal = TerminalCore::new()?; // Remove .await
let theme = Theme::from_str(&config.colors.theme);
let mut terminal = TerminalCore::new()?;
let mut grpc_client = GrpcClient::new().await?;
let mut command_handler = CommandHandler::new();
let theme = Theme::from_str(&config.colors.theme);
// Fetch table structure at startup (one-time)
// TODO: Later, consider implementing a live update for table structure changes.
let table_structure = grpc_client.get_table_structure().await?; // Changed
// Extract the column names from the response
let column_names: Vec<String> = table_structure
.columns
.iter()
.map(|col| col.name.clone())
.collect();
// Initialize FormState with dynamic fields
let mut form_state = FormState::new(column_names);
// The rest of your UI initialization remains the same
let mut event_handler = EventHandler::new();
let mut event_handler = EventHandler::new().await?;
let event_reader = EventReader::new();
let mut auth_state = AuthState::default();
let mut login_state = LoginState::default();
let mut register_state = RegisterState::default();
let mut intro_state = IntroState::default();
let mut admin_state = AdminState::default();
let mut app_state = AppState::new()?;
// Initialize app state with profile tree and table structure
let column_names =
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
.await?;
let mut form_state = FormState::new(column_names);
// Fetch the total count of Adresar entries
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state)
.await?;
form_state.reset_to_empty();
loop {
let total_count = grpc_client.get_adresar_count().await?;
app_state.update_total_count(total_count);
// Determine edit mode based on EventHandler state
let is_edit_mode = event_handler.is_edit_mode;
terminal.draw(|f| {
render_ui(
f,
&mut form_state,
&mut auth_state,
&login_state,
&register_state,
&intro_state,
&mut admin_state,
&theme,
event_handler.is_edit_mode,
is_edit_mode,
app_state.total_count,
app_state.current_position,
&app_state.current_dir,
&event_handler.command_input,
event_handler.command_mode,
&event_handler.command_message,
&app_state.ui,
&app_state,
);
})?;
let total_count = app_state.total_count;
// --- Cursor Visibility Logic ---
let current_mode = ModeManager::derive_mode(&app_state, &event_handler);
match current_mode {
AppMode::Edit => {
terminal.show_cursor()?;
}
AppMode::ReadOnly => {
if !app_state.ui.focus_outside_canvas {
terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?;
} else {
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
}
terminal.show_cursor()?;
}
AppMode::General => {
if app_state.ui.focus_outside_canvas {
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
terminal.show_cursor()?;
} else {
terminal.hide_cursor()?;
}
}
AppMode::Command => {
terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?;
terminal.show_cursor()?;
}
}
// --- End Cursor Visibility Logic ---
let total_count = app_state.total_count; // Keep track for save logic
let mut current_position = app_state.current_position;
let position_before_event = current_position;
let event = event_reader.read_event()?;
let (should_exit, message) = event_handler.handle_event(
event,
&config,
&mut terminal,
&mut grpc_client,
&mut command_handler,
&mut form_state,
&mut app_state,
total_count,
&mut current_position,
).await?;
// Get the outcome from the event handler
let event_outcome_result = event_handler
.handle_event(
event,
&config,
&mut terminal,
&mut grpc_client,
&mut command_handler,
&mut form_state,
&mut auth_state,
&mut login_state,
&mut register_state,
&mut intro_state,
&mut admin_state,
&mut app_state,
total_count,
&mut current_position,
)
.await;
// Update position based on handler's modification
app_state.current_position = current_position;
// Handle position changes and update form state
if !event_handler.is_edit_mode {
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1 // Limit to last character in readonly mode
} else {
0
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
// Ensure position never exceeds total_count + 1
if app_state.current_position > total_count + 1 {
app_state.current_position = total_count + 1;
}
if app_state.current_position > total_count {
// New entry - reset form
form_state.reset_to_empty();
form_state.current_field = 0;
} else if app_state.current_position >= 1 && app_state.current_position <= total_count {
// Existing entry - load data
match grpc_client.get_adresar_by_position(app_state.current_position).await {
Ok(response) => {
// Set the ID properly
form_state.id = response.id;
// Update form values dynamically
form_state.values = vec![
response.firma,
response.kz,
response.drc,
response.ulica,
response.psc,
response.mesto,
response.stat,
response.banka,
response.ucet,
response.skladm,
response.ico,
response.kontakt,
response.telefon,
response.skladu,
response.fax,
];
let current_input = form_state.get_current_input();
let max_cursor_pos = if !event_handler.is_edit_mode && !current_input.is_empty() {
current_input.len() - 1 // In readonly mode, limit to last character
} else {
current_input.len()
};
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
form_state.has_unsaved_changes = false;
event_handler.command_message = format!("Loaded entry {}", app_state.current_position);
}
Err(e) => {
event_handler.command_message = format!("Error loading entry: {}", e);
// --- Centralized Consequence Handling ---
let mut should_exit = false;
match event_outcome_result {
// Handle the Result first
Ok(outcome) => match outcome {
// Handle the Ok variant containing EventOutcome
EventOutcome::Ok(message) => {
if !message.is_empty() {
event_handler.command_message = message;
}
}
} else {
// Invalid position - reset to first entry
app_state.current_position = 1;
EventOutcome::Exit(message) => {
event_handler.command_message = message;
should_exit = true;
}
EventOutcome::DataSaved(save_outcome, message) => {
event_handler.command_message = message; // Show save status
// *** Delegate outcome handling to UiService ***
if let Err(e) = UiService::handle_save_outcome(
save_outcome,
&mut grpc_client,
&mut app_state,
&mut form_state,
)
.await
{
// Handle potential errors from the outcome handler itself
event_handler.command_message =
format!("Error handling save outcome: {}", e);
}
// No count update needed for UpdatedExisting or NoChange
}
EventOutcome::ButtonSelected { context, index } => {
event_handler.command_message = "Internal error: Unexpected button state".to_string();
}
},
Err(e) => {
// Handle errors from handle_event, e.g., log or display
event_handler.command_message = format!("Error: {}", e);
// Decide if the error is fatal, maybe set should_exit = true;
}
}
event_handler.command_message = message;
// --- Position Change Handling (after outcome processing) ---
let position_changed =
app_state.current_position != position_before_event; // Calculate after potential update
// Recalculate total_count *after* potential update
let current_total_count = app_state.total_count;
// Handle position changes and update form state (Only when form is shown)
if app_state.ui.show_form {
if position_changed && !event_handler.is_edit_mode {
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1 // Limit to last character in readonly mode
} else {
0
};
form_state.current_cursor_pos =
event_handler.ideal_cursor_column.min(max_cursor_pos);
// Ensure position never exceeds total_count + 1
if app_state.current_position > current_total_count + 1 {
app_state.current_position = current_total_count + 1;
}
if app_state.current_position > current_total_count {
// New entry - reset form
form_state.reset_to_empty();
form_state.current_field = 0;
} else if app_state.current_position >= 1
&& app_state.current_position <= current_total_count
{
// Existing entry - load data
let current_position_to_load = app_state.current_position; // Use a copy
let load_message = UiService::load_adresar_by_position(
&mut grpc_client,
&mut app_state, // Pass app_state mutably if needed by the service
&mut form_state,
current_position_to_load,
)
.await?;
let current_input = form_state.get_current_input();
let max_cursor_pos = if !event_handler.is_edit_mode
&& !current_input.is_empty()
{
current_input.len() - 1 // In readonly mode, limit to last character
} else {
current_input.len()
};
form_state.current_cursor_pos = event_handler
.ideal_cursor_column
.min(max_cursor_pos);
// Don't overwrite message from handle_event if load_message is simple success
if !load_message.starts_with("Loaded entry")
|| event_handler.command_message.is_empty()
{
event_handler.command_message = load_message;
}
} else {
// Invalid position (e.g., 0) - reset to first entry or new entry mode
app_state.current_position =
1.min(current_total_count + 1); // Go to 1 or new entry if empty
if app_state.current_position > total_count {
form_state.reset_to_empty();
form_state.current_field = 0;
}
}
} else if !position_changed && !event_handler.is_edit_mode {
// If position didn't change but we are in read-only, just adjust cursor
let current_input = form_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
form_state.current_cursor_pos =
event_handler.ideal_cursor_column.min(max_cursor_pos);
}
} else if app_state.ui.show_register {
if !event_handler.is_edit_mode {
let current_input = register_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
register_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
}
} else if app_state.ui.show_login {
if !event_handler.is_edit_mode {
let current_input = login_state.get_current_input();
let max_cursor_pos = if !current_input.is_empty() {
current_input.len() - 1
} else {
0
};
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
}
}
// Check exit condition *after* processing outcome
if should_exit {
// terminal.cleanup()?; // Optional: Drop handles this
return Ok(());
}
}
}

View File

@@ -8,6 +8,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
&[
"proto/common.proto",
"proto/adresar.proto",
"proto/auth.proto",
"proto/uctovnictvo.proto",
"proto/table_structure.proto",
"proto/table_definition.proto",

39
common/proto/auth.proto Normal file
View File

@@ -0,0 +1,39 @@
// proto/auth.proto
syntax = "proto3";
package multieko2.auth;
import "common.proto";
service AuthService {
rpc Register(RegisterRequest) returns (AuthResponse);
rpc Login(LoginRequest) returns (LoginResponse);
}
message RegisterRequest {
string username = 1;
string email = 2;
string password = 3;
string password_confirmation = 4;
string role = 5;
}
message AuthResponse {
string id = 1; // UUID in string format
string username = 2; // Registered username
string email = 3; // Registered email (if provided)
string role = 4; // Default role: 'accountant'
}
message LoginRequest {
string identifier = 1; // Can be username or email
string password = 2;
}
message LoginResponse {
string access_token = 1; // JWT token
string token_type = 2; // Usually "Bearer"
int32 expires_in = 3; // Expiration in seconds (86400 for 24 hours)
string user_id = 4; // User's UUID in string format
string role = 5; // User's role
string username = 6;
}

View File

@@ -4,6 +4,9 @@ pub mod proto {
pub mod adresar {
include!("proto/multieko2.adresar.rs");
}
pub mod auth {
include!("proto/multieko2.auth.rs");
}
pub mod common {
include!("proto/multieko2.common.rs");
}

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