-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodal.component.ts
More file actions
107 lines (83 loc) · 2.41 KB
/
Copy pathmodal.component.ts
File metadata and controls
107 lines (83 loc) · 2.41 KB
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
import { Component, ElementRef, inject, ViewChild } from '@angular/core';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { setDoc, uploadFile, User } from '@junobuild/core';
import { nanoid } from 'nanoid';
import { AuthService } from '../../services/auth.service';
import { DocsService } from '../../services/docs.service';
import { BackdropComponent } from '../backdrop/backdrop.component';
import { ButtonComponent } from '../button/button.component';
@Component({
selector: 'app-modal',
imports: [BackdropComponent, ReactiveFormsModule, ButtonComponent],
templateUrl: './modal.component.html',
})
export class ModalComponent {
private readonly authService = inject(AuthService);
private readonly docsServices = inject(DocsService);
@ViewChild('inputFile') inputFile: ElementRef<HTMLInputElement> | undefined;
#formBuilder = inject(FormBuilder);
diaryForm = this.#formBuilder.group({
entry: '',
});
showModal = false;
file: File | undefined;
resetInputFile(): void {
if (this.inputFile !== undefined) {
this.inputFile.nativeElement.value = '';
}
this.file = undefined;
}
openModal() {
this.resetInputFile();
this.showModal = true;
}
closeModal() {
this.showModal = false;
}
async onSubmit() {
const user = this.authService.user();
// It's a demo, irl we would handle errors properly...
if (user !== null && user !== undefined) {
try {
this.diaryForm.disable();
await this.save(user);
await this.docsServices.reload();
this.closeModal();
} catch (err) {
console.error(err);
} finally {
this.diaryForm.enable();
}
}
}
private async save(user: User) {
let url;
if (this.file !== undefined) {
const filename = `${user.key}-${this.file.name}`;
const { downloadUrl } = await uploadFile({
collection: 'images',
data: this.file,
filename,
});
url = downloadUrl;
}
const key = nanoid();
await setDoc({
collection: 'notes',
doc: {
key,
data: {
text: this.diaryForm.value.entry,
...(url !== undefined && { url }),
},
},
});
}
onFileChanged($event: Event) {
const target = $event.target as HTMLInputElement;
this.file = target.files?.[0];
}
openSelectFile() {
this.inputFile?.nativeElement.click();
}
}