]>
Commit | Line | Data |
---|---|---|
1 | import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core' | |
2 | import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms' | |
3 | import { Notifier } from '@app/core' | |
4 | import { GlobalIconName } from '@app/shared/shared-icons' | |
5 | ||
6 | @Component({ | |
7 | selector: 'my-reactive-file', | |
8 | styleUrls: [ './reactive-file.component.scss' ], | |
9 | templateUrl: './reactive-file.component.html', | |
10 | providers: [ | |
11 | { | |
12 | provide: NG_VALUE_ACCESSOR, | |
13 | useExisting: forwardRef(() => ReactiveFileComponent), | |
14 | multi: true | |
15 | } | |
16 | ] | |
17 | }) | |
18 | export class ReactiveFileComponent implements OnInit, ControlValueAccessor { | |
19 | @Input() inputLabel: string | |
20 | @Input() inputName: string | |
21 | @Input() extensions: string[] = [] | |
22 | @Input() maxFileSize: number | |
23 | ||
24 | @Input() displayFilename = false | |
25 | @Input() displayReset = false | |
26 | ||
27 | @Input() icon: GlobalIconName | |
28 | @Input() buttonTooltip: string | |
29 | ||
30 | @Output() fileChanged = new EventEmitter<Blob>() | |
31 | ||
32 | allowedExtensionsMessage = '' | |
33 | fileInputValue: any | |
34 | ||
35 | private file: File | |
36 | ||
37 | constructor (private notifier: Notifier) { } | |
38 | ||
39 | get filename () { | |
40 | if (!this.file) return '' | |
41 | ||
42 | return this.file.name | |
43 | } | |
44 | ||
45 | ngOnInit () { | |
46 | this.allowedExtensionsMessage = this.extensions.join(', ') | |
47 | } | |
48 | ||
49 | fileChange (event: any) { | |
50 | if (event.target.files?.length) { | |
51 | const [ file ] = event.target.files | |
52 | ||
53 | if (file.size > this.maxFileSize) { | |
54 | this.notifier.error($localize`This file is too large.`) | |
55 | return | |
56 | } | |
57 | ||
58 | const extension = '.' + file.name.split('.').pop() | |
59 | if (this.extensions.includes(extension.toLowerCase()) === false) { | |
60 | const message = $localize`PeerTube cannot handle this kind of file. Accepted extensions are ${this.allowedExtensionsMessage}.` | |
61 | this.notifier.error(message) | |
62 | ||
63 | return | |
64 | } | |
65 | ||
66 | this.file = file | |
67 | ||
68 | this.propagateChange(this.file) | |
69 | } | |
70 | this.fileChanged.emit(this.file) | |
71 | } | |
72 | ||
73 | reset () { | |
74 | this.writeValue(undefined) | |
75 | this.propagateChange(undefined) | |
76 | this.fileChanged.emit(undefined) | |
77 | } | |
78 | ||
79 | propagateChange = (_: any) => { /* empty */ } | |
80 | ||
81 | writeValue (file: any) { | |
82 | this.file = file | |
83 | ||
84 | if (!this.file) this.fileInputValue = null | |
85 | } | |
86 | ||
87 | registerOnChange (fn: (_: any) => void) { | |
88 | this.propagateChange = fn | |
89 | } | |
90 | ||
91 | registerOnTouched () { | |
92 | // Unused | |
93 | } | |
94 | } |