-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui.sh
1562 lines (1365 loc) · 45.4 KB
/
ui.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
printf "Bash version: %s\n" "$BASH_VERSION"
export NG_CLI_ANALYTICS=false
# Get the current working directory
CURRENT_DIRECTORY=$(pwd)
SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
pushd "${SCRIPT_PATH}" >/dev/null
trap cleanup EXIT
function success() {
echo -e "\x1B[32m$1\x1B[0m"
}
function warning() {
echo -e "\x1B[33m$1\x1B[0m"
}
function error() {
echo -e "\x1B[31m$1\x1B[0m"
}
function info() {
echo -e "\x1B[34m$1\x1B[0m"
}
function titleCase() {
# Read input from stdin
while read -r line; do
local string="$line"
local result=""
local word=""
# Convert each word to title case
for word in $string; do
# Convert hyphens to spaces and capitalize each word
result="$result $(echo "${word//-/ }" | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2));}1')"
done
# Remove leading whitespace
result="${result## }"
echo "$result"
done
}
function should_continue() {
# echo the first parameter in yellow color
echo -e "\x1B[33m$1\x1B[0m"
read -r CONTINUE
if [[ "$CONTINUE" =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "Continuing..."
else:
echo "Exiting..."
exit 1
fi
}
function cleanup() {
popd >/dev/null
}
function destroy() {
local DIRECTORY=$1
rm -rf "$DIRECTORY"
}
function create_dockerfile() {
local PROJECT_NAME=$1
local AUTHOR=$(git config user.name)
echo -e "FROM cimg/node:lts-browsers
LABEL author=\"$AUTHOR\"
WORKDIR ./${PROJECT_NAME}
USER root
RUN sudo apt-get update && sudo apt-get install curl jq -y
EXPOSE 4200
RUN npm ci
#RUN [\"ng\", \"serve\", \"-H\", \"0.0.0.0\"]
" > Dockerfile
}
function save_exact() {
echo "save-exact=true" > .npmrc
}
function create_fake_json_server() {
local PROJECT_PATH=$1
local SERVER_DIR="$PROJECT_PATH/fake-json-server"
info "Creating fake JSON server at $SERVER_DIR"
mkdir -p "$SERVER_DIR"
pushd "$SERVER_DIR" >/dev/null
# Initialize package.json
npm init -y
# # Install json-server
# npm install --save-exact json-server
# Create initial db.json with todo-app data
local DB_JSON_CONTENT=$(cat <<'EOF'
{
"todos": [
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"userId": "TEST_USER",
"title": "Learn Angular",
"description": "Complete the Angular tutorial",
"dueDate": "2026-02-01",
"status": "pending",
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
},
{
"id": "123e4567-e89c-12d3-a456-426614174000",
"userId": "TEST_USER",
"title": "Learn NgZorro",
"description": "Complete the NgZorro tutorial",
"dueDate": "2026-02-01",
"status": "pending",
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
},
{
"id": "123e4567-e89d-12d3-a456-426614174000",
"userId": "TEST_USER",
"title": "Build an awesome app",
"description": "Build an awesome app using Angular and NgZorro",
"dueDate": "2026-02-01",
"status": "pending",
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
}
],
"users": [
{ "id": "TEST_USER", "name": "Test User", "email": "[email protected]" },
{ "id": 2, "name": "Jane Smith", "email": "[email protected]" }
],
"profile": {
"name": "Demo User",
"email": "[email protected]",
"avatar": "https://placekitten.com/200/200"
}
}
EOF
)
echo "$DB_JSON_CONTENT" > db.json
popd >/dev/null
}
function create_todo_model() {
local TODO_COMPONENTS_DIRECTORY=$1
local TODO_MODEL_CONTENT=$(cat <<'EOF'
export interface Todo {
id: string;
userId: string;
title: string;
description: string;
dueDate: Date | string;
status: 'pending' | 'completed';
createdAt: string;
updatedAt: string;
ttl?: number;
editingTitle?: boolean;
editingDescription?: boolean;
}
export type CreateTodoDto = Omit<Todo, 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'ttl'>;
export type UpdateTodoDto = Partial<Todo>;
EOF
)
echo "$TODO_MODEL_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/state/todo.model.ts"
}
function create_todo_service() {
local TODO_COMPONENTS_DIRECTORY=$1
local TODO_SERVICE_CONTENT=$(cat <<'EOF'
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { Todo, CreateTodoDto, UpdateTodoDto } from './todo.model';
import { AppConfigService } from '../../../app.config.service';
@Injectable({
providedIn: 'root'
})
export class TodoService {
private http = inject(HttpClient);
private config = inject(AppConfigService);
private baseUrl = `${this.config.getConfig().restApiEndpoint}/todos`
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl);
}
getTodoById(id: string): Observable<Todo> {
return this.http.get<Todo>(`${this.baseUrl}/${id}`);
}
createTodo(todo: CreateTodoDto): Observable<Todo> {
return this.http.post<Todo>(this.baseUrl, todo);
}
updateTodo(id: string, updates: UpdateTodoDto): Observable<Todo> {
return this.http.patch<Todo>(`${this.baseUrl}/${id}`, updates).pipe(
tap(updatedTodo => {
// Now service is also publishing the updated todo after successful update
// so component can update in list and no need to recall list.
})
);
}
deleteTodo(id: string): Observable<void> {
return this.http.delete<void>(`${this.baseUrl}/${id}`);
}
}
EOF
)
echo "$TODO_SERVICE_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/state/todo.service.ts"
}
function create_todo_routes() {
local TODO_COMPONENTS_DIRECTORY=$1
# Create Todo routes
local TODO_ROUTES_CONTENT=$(cat <<'EOF'
import { Routes } from '@angular/router';
import { TodoListComponent } from './todo-list.component';
import { TodoService } from './state/todo.service';
import { TodoFormComponent } from './todo-form.component';
export const TODO_ROUTES: Routes = [
{
path: '',
providers: [TodoService],
component: TodoListComponent,
children: [
{
path: 'add',
component: TodoFormComponent,
data: { mode: 'create' }
},
{
path: 'edit/:id',
component: TodoFormComponent,
data: { mode: 'update' }
}
]
}
];
EOF
)
echo "$TODO_ROUTES_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/todo.routes.ts"
}
function create_todo_list_component() {
local TODO_COMPONENTS_DIRECTORY=$1
local TODO_LIST_COMPONENT_CONTENT=$(cat <<'EOF'
import { Component, inject, signal, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzListModule } from 'ng-zorro-antd/list';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { TodoService } from './state/todo.service';
import { Todo, UpdateTodoDto } from './state/todo.model';
import { Router, RouterModule } from '@angular/router';
import { NzModalService, NzModalModule } from 'ng-zorro-antd/modal';
import { TodoModalComponent } from './todo-modal.component';
import { TodoCommunicationService } from '../../core/services/todo-communication.service'; // Import
import { Subscription } from 'rxjs'; // Import Subscription
import { NzTagModule } from 'ng-zorro-antd/tag'; // Import for the status tags
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm'; // Import pop confirm module
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { NzFormModule } from 'ng-zorro-antd/form';
@Component({
selector: 'todo-list',
standalone: true,
imports: [
CommonModule,
FormsModule,
NzButtonModule,
NzInputModule,
NzIconModule,
NzListModule,
NzCheckboxModule,
RouterModule,
NzModalModule,
NzTagModule,
NzPopconfirmModule,
DatePipe,
ReactiveFormsModule,
NzDatePickerModule,
NzFormModule
],
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.less'],
})
export class TodoListComponent implements OnInit, OnDestroy {
private todoService = inject(TodoService);
private router = inject(Router);
private modalService = inject(NzModalService);
private todoCommunicationService = inject(TodoCommunicationService);
private fb = inject(FormBuilder);
todos = signal<Todo[]>([]);
newTodoTitle = '';
private todoCreatedSubscription: Subscription | undefined;
private todoUpdatedSubscription: Subscription | undefined;
addTodoForm: FormGroup = this.fb.group({
title: ['', Validators.required],
description: [''],
dueDate: [null] // Add dueDate control
});
constructor() {
}
ngOnInit() {
this.loadTodos();
this.todoCreatedSubscription = this.todoCommunicationService.todoCreated$.subscribe(todo => {
this.addTodoToList(todo);
});
this.todoUpdatedSubscription = this.todoCommunicationService.todoUpdated$.subscribe(updatedTodo => {
this.updateTodoInList(updatedTodo);
});
this.addTodoForm = this.fb.group({
title: ['', Validators.required],
description: [''],
dueDate: [null] // Add dueDate control
});
}
ngOnDestroy() {
// Unsubscribe to prevent memory leaks
this.todoCreatedSubscription?.unsubscribe();
this.todoUpdatedSubscription?.unsubscribe();
}
private loadTodos() {
this.todoService.getTodos().subscribe(todos => {
todos.forEach(todo => {
todo.dueDate = new Date(todo.dueDate);
todo.editingTitle = false;
todo.editingDescription = false;
});
this.todos.set(todos);
});
}
submitNewTodo(): void {
if (this.addTodoForm.valid) {
const title = this.addTodoForm.get('title')?.value;
const description = this.addTodoForm.get('description')?.value;
const dueDate = this.addTodoForm.get('dueDate')?.value;
this.todoService.createTodo({ title: title, description: description, dueDate: dueDate, status: 'pending' }).subscribe(
(newTodo) => {
this.todos.update(todos => [...todos, newTodo]);
this.addTodoForm.reset();
},
(error) => {
console.error('Error creating todo:', error);
}
);
} else {
console.log('Form is invalid');
}
}
addTodo() {
this.router.navigate(['todos', 'add']);
}
toggleTodo(todo: Todo) {
const newStatus = todo.status === 'completed' ? 'pending' : 'completed';
this.todoService.updateTodo(todo.id, { status: newStatus } as any)
.subscribe(() => this.loadTodos());
}
confirmDelete(id: string): void {
this.todoService.deleteTodo(id).subscribe(() => this.loadTodos());
}
cancelDelete(): void {
console.log('Delete canceled');
}
editTodo(todo: Todo) {
this.modalService.create({
nzTitle: 'Edit Todo',
nzContent: TodoModalComponent,
nzData: { todo: todo },
nzOnOk: (componentInstance: TodoModalComponent) => {
return componentInstance.onSubmit();
},
});
}
addTodoToList(todo: Todo) {
this.todos.update(todos => [...todos, todo]);
}
updateTodoInList(updatedTodo: Todo) {
this.todos.update(todos => {
return todos.map(todo => {
if (todo.id === updatedTodo.id) {
return updatedTodo; // replace with updated todo
}
return todo; // otherwise return the original todo
});
});
}
trackByTodoId(_index: number, todo: Todo): string {
return todo.id;
}
startEditTitle(todo: Todo) {
todo.editingTitle = true;
setTimeout(() => {
const element = document.querySelector(`.todo-title[data-todo-id="${todo.id}"]`);
if (element) {
(element as HTMLElement).focus();
}
}, 0);
}
endEditTitle(todo: Todo) {
todo.editingTitle = false;
const element = document.querySelector(`.todo-title[data-todo-id="${todo.id}"]`) as HTMLElement;
if (element) {
const newTitle = element.innerText;
if (newTitle !== todo.title) {
this.updateTodo(todo, { title: newTitle });
}
}
}
startEditDescription(todo: Todo) {
todo.editingDescription = true;
}
endEditDescription(todo: Todo) {
todo.editingDescription = false;
const element = document.querySelector(`.todo-description[data-todo-id="${todo.id}"]`) as HTMLElement;
if (element) {
const newDescription = element.innerText;
if (newDescription !== todo.description) {
this.updateTodo(todo, { description: newDescription });
}
}
}
private updateTodo(todo: Todo, updates: UpdateTodoDto) {
this.todoService.updateTodo(todo.id, updates)
.subscribe(updatedTodo => {
this.todoCommunicationService.todoUpdated(updatedTodo); // Now publish updated todo itself
});
}
}
EOF
)
echo "$TODO_LIST_COMPONENT_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/todo-list.component.ts"
# Create template file - ADDED HERE
local TODO_LIST_TEMPLATE_CONTENT=$(cat <<'EOF'
<div class="container">
<div class="todo-header">
<h1>My Todos</h1>
<button nz-button nzType="primary" (click)="addTodo()">
<span nz-icon nzType="plus" nzTheme="outline"></span> Add Todo
</button>
</div>
<div class="todo-form">
<h2>Add New Todo</h2>
<form nz-form [formGroup]="addTodoForm" (ngSubmit)="submitNewTodo()">
<nz-form-item>
<nz-form-control>
<input nz-input formControlName="title" placeholder="Title" />
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control>
<textarea nz-input formControlName="description" rows="2" placeholder="Description"></textarea>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control>
<nz-date-picker formControlName="dueDate" nzPlaceHolder="Due Date"></nz-date-picker>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control>
<button nz-button nzType="primary" [disabled]="!addTodoForm.valid">Add Todo</button>
</nz-form-control>
</nz-form-item>
</form>
</div>
<nz-list nzItemLayout="vertical">
<nz-list-item *ngFor="let todo of todos(); trackBy: trackByTodoId" class="todo-item">
<div nz-list-item-extra>
<a nz-button nzType="primary" nzShape="circle" (click)="editTodo(todo)">
<span nz-icon nzType="edit" nzTheme="outline"></span>
</a>
<nz-popconfirm
nzTitle="Are you sure delete this task?"
(nzOnConfirm)="confirmDelete(todo.id)"
(nzOnCancel)="cancelDelete()"
>
<a nz-button nzType="primary" nzDanger nzShape="circle" nzPopconfirm>
<span nz-icon nzType="delete" nzTheme="outline"></span>
</a>
</nz-popconfirm>
</div>
<div nz-list-item-content>
<div class='todo-item-content' [class.todo-item-completed]="todo.status === 'completed'">
<label nz-checkbox [ngModel]="todo.status === 'completed'" (ngModelChange)="toggleTodo(todo)"></label>
<div class="todo-text-content" >
<div class="todo-title-status">
<span class="todo-title"
(click)="startEditTitle(todo)"
[contentEditable]="!!todo.editingTitle"
(blur)="endEditTitle(todo)"
(keydown.enter)="endEditTitle(todo)"
[attr.data-todo-id]="todo.id"
>{{ todo.title }}</span>
<nz-tag *ngIf="todo.status === 'completed'" nzColor="success">Completed</nz-tag>
<nz-tag *ngIf="todo.status === 'pending'" nzColor="warning">Pending</nz-tag>
</div>
<div class="todo-description-date">
<span class="todo-description"
(click)="startEditDescription(todo)"
[contentEditable]="!!todo.editingDescription"
(blur)="endEditDescription(todo)"
(keydown.enter)="endEditDescription(todo)"
[attr.data-todo-id]="todo.id"
>{{ todo.description }}</span>
<small class="todo-due-date">Due Date: {{ todo.dueDate | date }}</small>
</div>
</div>
</div>
</div>
</nz-list-item>
</nz-list>
</div>
EOF
)
echo "$TODO_LIST_TEMPLATE_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/todo-list.component.html"
}
function create_todo_form_component() {
local TODO_COMPONENTS_DIRECTORY=$1
# Create template file
local TODO_FORM_TEMPLATE=$(cat <<EOF
<form [formGroup]="form" (ngSubmit)="onSubmit()" nz-form>
<formly-form [form]="form" [fields]="fields" [model]="model"></formly-form>
<div class="flex gap-2 justify-end">
<button nz-button (click)="onCancel()">Cancel</button>
<button nz-button nzType="primary" type="submit" [disabled]="!form.valid">Save</button>
</div>
</form>
EOF
)
echo "$TODO_FORM_TEMPLATE" > "$TODO_COMPONENTS_DIRECTORY/todo-form.component.html"
local TODO_FORM_COMPONENT_CONTENT=$(cat <<'EOF'
import { Component, OnInit, inject } from '@angular/core';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { NzFormModule } from 'ng-zorro-antd/form';
import { TodoService } from './state/todo.service';
import { ActivatedRoute, Router } from '@angular/router';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { CommonModule } from '@angular/common';
import { todoFormlyFields } from './todo.formly';
import { Todo } from './state/todo.model';
import { firstValueFrom } from 'rxjs';
import { TodoCommunicationService } from '../../core/services/todo-communication.service'; // Import
@Component({
selector: 'todo-form',
standalone: true,
imports: [
ReactiveFormsModule,
FormlyModule,
NzFormModule,
NzButtonModule,
CommonModule
],
templateUrl: './todo-form.component.html'
})
export class TodoFormComponent implements OnInit {
form = new FormGroup({});
model: Partial<Todo> = {};
fields: FormlyFieldConfig[] = todoFormlyFields;
mode: 'create' | 'update' = 'create';
private todoService = inject(TodoService);
private router = inject(Router);
private route = inject(ActivatedRoute);
private todoCommunicationService = inject(TodoCommunicationService); // Import
ngOnInit() {
this.route.data.subscribe(data => {
this.mode = data['mode'];
if (this.mode === 'update') {
this.loadTodoForUpdate();
}
});
}
async loadTodoForUpdate() {
const id = this.route.snapshot.paramMap.get('id');
if (id) {
const todo = await firstValueFrom(this.todoService.getTodoById(id));
if (todo) {
this.model = { ...todo, dueDate: new Date(todo.dueDate) };
}
}
}
async onSubmit() {
if (this.form.valid) {
try {
let newTodo: Todo;
if (this.mode === 'create') {
const In1Year = new Date();
In1Year.setFullYear(In1Year.getFullYear() + 1);
const dueDate = this.model.dueDate ? new Date(this.model.dueDate).toISOString() : In1Year.toISOString();
// Await creation
newTodo = await firstValueFrom(this.todoService.createTodo(
{
title: this.model.title || '',
description: this.model.description || '',
dueDate: dueDate, // send as string to api
status: this.model.status || 'pending'
}
));
this.todoCommunicationService.todoCreated(newTodo); // after create todo created will update the ui.
} else {
newTodo = await firstValueFrom(this.todoService.updateTodo(this.model.id!, this.model));
this.todoCommunicationService.todoUpdated(newTodo); // after create todo created will update the ui.
}
// After successful creation or update, navigate back
this.router.navigate(['/todos']);
} catch (error) {
console.error('Error saving todo:', error);
}
}
}
onCancel() {
this.router.navigate(['/todos']);
}
}
EOF
)
echo "$TODO_FORM_COMPONENT_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/todo-form.component.ts"
}
function create_todo_formly_file() {
local TODO_COMPONENTS_DIRECTORY=$1
local TODO_FORMLY_CONTENT=$(cat <<'EOF'
import { FormlyFieldConfig } from '@ngx-formly/core';
export const todoFormlyFields: FormlyFieldConfig[] = [
{
key: 'title',
type: 'input',
props: {
label: 'Title',
placeholder: 'Enter title',
required: true,
},
},
{
key: 'description',
type: 'textarea',
props: {
label: 'Description',
placeholder: 'Enter description',
},
},
{
key: 'dueDate',
type: 'datepicker',
props: {
label: 'Due Date',
placeholder: 'Select due date',
required: false
},
},
{
key: 'status',
type: 'select',
defaultValue: 'pending',
props: {
label: 'Status',
placeholder: 'Select Status',
required: true,
options: [
{ label: 'Pending', value: 'pending' },
{ label: 'Completed', value: 'completed' },
],
},
},
];
EOF
)
echo "$TODO_FORMLY_CONTENT" > "$TODO_COMPONENTS_DIRECTORY/todo.formly.ts"
}
function create_todo_setup() {
local PROJECT_PATH=$1
info "Creating Todo related files..."
# Create Todo directory and its state subdirectory
local TODO_COMPONENTS_DIRECTORY="$PROJECT_PATH/src/app/pages/todo"
mkdir -p "$TODO_COMPONENTS_DIRECTORY/state"
create_todo_model "$TODO_COMPONENTS_DIRECTORY"
create_todo_service "$TODO_COMPONENTS_DIRECTORY"
create_todo_routes "$TODO_COMPONENTS_DIRECTORY"
create_todo_list_component "$TODO_COMPONENTS_DIRECTORY"
create_todo_form_component "$TODO_COMPONENTS_DIRECTORY"
create_todo_formly_file "$TODO_COMPONENTS_DIRECTORY"
}
function create_navigation_service() {
local CORE_NAV_DIR=$1
# Create navigation service
local NAV_SERVICE_CONTENT=$(cat <<EOF
import { Injectable } from '@angular/core';
import { Route, Routes } from '@angular/router';
export interface NavItem {
path: string;
title: string;
icon: string;
children?: NavItem[];
}
@Injectable({
providedIn: 'root'
})
export class NavigationService {
private iconMap: { [key: string]: string } = {
welcome: 'dashboard',
todos: 'unordered-list',
};
generateNavItems(routes: Routes): NavItem[] {
// .filter(route => !route.path?.includes('**')) Filter out wildcard routes
return routes
.filter(route => !route.path?.includes('**'))
.map(route => this.createNavItem(route))
.filter(item => item !== null) as NavItem[];
}
private createNavItem(route: Route): NavItem | null {
if (!route.path) return null;
if (route.data?.['hideInNav']) return null;
const title = route.data?.['title'] || this.capitalizeFirstLetter(route.path);
const icon = this.iconMap[route.path] || 'default';
const navItem: NavItem = {
path: route.path,
title: title,
icon: icon,
};
if (route.children) {
const children = route.children
.map(child => this.createNavItem(child))
.filter(child => child !== null) as NavItem[];
if (children.length) {
navItem.children = children;
}
}
return navItem;
}
private capitalizeFirstLetter(string: string): string {
return string.charAt(0).toUpperCase() + string.slice(1);
}
}
EOF
)
echo "$NAV_SERVICE_CONTENT" > "$CORE_NAV_DIR/navigation.service.ts"
}
function create_app_component() {
local PROJECT_PATH=$1
local PROJECT_NAME_TITLE=$2
local APP_COMPONENT_TEMPLATE=$(cat <<EOF
<nz-layout class="app-layout">
<nz-sider
class="menu-sidebar"
nzCollapsible
nzWidth="256px"
nzBreakpoint="md"
[(nzCollapsed)]="isCollapsed"
>
<div class="sidebar-logo">
<a href="https://ng.ant.design/" target="_blank">
<img src="https://ng.ant.design/assets/img/logo.svg" alt="logo">
<h1>${PROJECT_NAME_TITLE}</h1>
</a>
</div>
<ul nz-menu nzTheme="dark" nzMode="inline" [nzInlineCollapsed]="isCollapsed">
<ng-container *ngFor="let item of navigationItems">
<li nz-menu-item *ngIf="!item.children?.length" [routerLink]="[item.path]">
<span nz-icon [nzType]="item.icon"></span>
<span>{{item.title}}</span>
</li>
<li nz-submenu *ngIf="item.children?.length" [nzTitle]="item.title" [nzIcon]="item.icon">
<ul>
<li nz-menu-item *ngFor="let child of item.children" [routerLink]="[item.path, child.path]">
{{child.title}}
</li>
</ul>
</li>
</ng-container>
</ul>
</nz-sider>
<nz-layout>
<nz-header>
<div class="app-header">
<span class="header-trigger" (click)="isCollapsed = !isCollapsed">
<span nz-icon [nzType]="isCollapsed ? 'menu-unfold' : 'menu-fold'"></span>
</span>
</div>
</nz-header>
<nz-content>
<div class="inner-content">
<router-outlet></router-outlet>
</div>
</nz-content>
</nz-layout>
</nz-layout>
EOF
)
echo "$APP_COMPONENT_TEMPLATE" > "$PROJECT_PATH/src/app/app.component.html"
# Update app.component.ts
local APP_COMPONENT_CONTENT=$(cat <<EOF
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NzLayoutModule } from 'ng-zorro-antd/layout';
import { NzMenuModule } from 'ng-zorro-antd/menu';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NavigationService, NavItem } from './core/navigation/navigation.service';
import { routes } from './app.routes';
@Component({
selector: 'app-root',
standalone: true,
imports: [
CommonModule,
RouterModule,
NzLayoutModule,
NzMenuModule,
NzIconModule
],
templateUrl: './app.component.html',
styleUrl: './app.component.less'
})
export class AppComponent implements OnInit {
isCollapsed = localStorage.getItem('isCollapsed') === 'true';
navigationItems: NavItem[] = [];
constructor(private navigationService: NavigationService) {}
ngOnInit() {
this.navigationItems = this.navigationService.generateNavItems(routes);
this.updateIsCollapsed();
}
updateIsCollapsed() {
localStorage.setItem('isCollapsed', this.isCollapsed.toString());
}
}
EOF
)
echo "$APP_COMPONENT_CONTENT" > "$PROJECT_PATH/src/app/app.component.ts"
}
function create_app_routes() {
local PROJECT_PATH=$1
# Update app.routes.ts
local ROUTES_CONTENT=$(cat <<EOF
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'welcome',
data: { hideInNav: true }
},
{
path: 'welcome',
loadChildren: () => import('./pages/welcome/welcome.routes').then(m => m.WELCOME_ROUTES),
data: {
title: 'Welcome',
icon: 'dashboard'
}
},
{
path: 'todos',
loadChildren: () => import('./pages/todo/todo.routes').then(m => m.TODO_ROUTES),
data: {
title: 'Todo List',
icon: 'unordered-list'
}
}
];
EOF
)
echo "$ROUTES_CONTENT" > "$PROJECT_PATH/src/app/app.routes.ts"
}
function create_navigation_setup() {
local PROJECT_PATH=$1
local PROJECT_NAME_TITLE=$2
info "Creating navigation files..."
local CORE_NAV_DIR="$PROJECT_PATH/src/app/core/navigation"
mkdir -p "$CORE_NAV_DIR"
create_navigation_service "$CORE_NAV_DIR"
create_app_component "$PROJECT_PATH" "$PROJECT_NAME_TITLE"
create_app_routes "$PROJECT_PATH"
}
function setup_project_directories() {
local UI_PATH="$1"
local COMPONENTS_DIRECTORY="$UI_PATH/src/app/components"
local TODO_COMPONENTS_DIRECTORY="$UI_PATH/src/app/pages/todo"
local CORE_SERVICE_DIRECTORY="$UI_PATH/src/app/core/services" # Add this line
info "Creating components directory: $COMPONENTS_DIRECTORY"
mkdir -p "$COMPONENTS_DIRECTORY"
if [ $? -ne 0 ]; then
error "Failed to create components directory: $COMPONENTS_DIRECTORY"
exit 1
fi
info "Creating core services directory: $CORE_SERVICE_DIRECTORY" # Add this line
mkdir -p "$CORE_SERVICE_DIRECTORY" # Add this line
if [ $? -ne 0 ]; then # Add this line
error "Failed to create components directory: $CORE_SERVICE_DIRECTORY" # Add this line
exit 1 # Add this line
fi # Add this line
info "Creating formly-datepicker directory: $COMPONENTS_DIRECTORY/formly-datepicker"
mkdir -p "$COMPONENTS_DIRECTORY/formly-datepicker"
if [ $? -ne 0 ]; then
error "Failed to create formly-datepicker directory: $COMPONENTS_DIRECTORY/formly-datepicker"
exit 1
fi
info "Creating todo components directory: $TODO_COMPONENTS_DIRECTORY"
mkdir -p "$TODO_COMPONENTS_DIRECTORY"
if [ $? -ne 0 ]; then
error "Failed to create todo components directory: $TODO_COMPONENTS_DIRECTORY"
exit 1
fi
}
function create_project_components() {
local COMPONENTS_DIRECTORY="$1"
local TODO_COMPONENTS_DIRECTORY="$2"