/
web.ts
295 lines (263 loc) · 8.71 KB
/
web.ts
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
import { WebPlugin, CapacitorException } from '@capacitor/core';
import { CameraSource, CameraDirection } from './definitions';
import type {
CameraPlugin,
GalleryImageOptions,
GalleryPhotos,
ImageOptions,
PermissionStatus,
Photo,
} from './definitions';
export class CameraWeb extends WebPlugin implements CameraPlugin {
async getPhoto(options: ImageOptions): Promise<Photo> {
// eslint-disable-next-line no-async-promise-executor
return new Promise<Photo>(async (resolve, reject) => {
if (options.webUseInput || options.source === CameraSource.Photos) {
this.fileInputExperience(options, resolve, reject);
} else if (options.source === CameraSource.Prompt) {
let actionSheet: any = document.querySelector('pwa-action-sheet');
if (!actionSheet) {
actionSheet = document.createElement('pwa-action-sheet');
document.body.appendChild(actionSheet);
}
actionSheet.header = options.promptLabelHeader || 'Photo';
actionSheet.cancelable = false;
actionSheet.options = [
{ title: options.promptLabelPhoto || 'From Photos' },
{ title: options.promptLabelPicture || 'Take Picture' },
];
actionSheet.addEventListener('onSelection', async (e: any) => {
const selection = e.detail;
if (selection === 0) {
this.fileInputExperience(options, resolve, reject);
} else {
this.cameraExperience(options, resolve, reject);
}
});
} else {
this.cameraExperience(options, resolve, reject);
}
});
}
async pickImages(_options: GalleryImageOptions): Promise<GalleryPhotos> {
// eslint-disable-next-line no-async-promise-executor
return new Promise<GalleryPhotos>(async (resolve, reject) => {
this.multipleFileInputExperience(resolve, reject);
});
}
private async cameraExperience(
options: ImageOptions,
resolve: any,
reject: any,
) {
if (customElements.get('pwa-camera-modal')) {
const cameraModal: any = document.createElement('pwa-camera-modal');
cameraModal.facingMode =
options.direction === CameraDirection.Front ? 'user' : 'environment';
document.body.appendChild(cameraModal);
try {
await cameraModal.componentOnReady();
cameraModal.addEventListener('onPhoto', async (e: any) => {
const photo = e.detail;
if (photo === null) {
reject(new CapacitorException('User cancelled photos app'));
} else if (photo instanceof Error) {
reject(photo);
} else {
resolve(await this._getCameraPhoto(photo, options));
}
cameraModal.dismiss();
document.body.removeChild(cameraModal);
});
cameraModal.present();
} catch (e) {
this.fileInputExperience(options, resolve, reject);
}
} else {
console.error(
`Unable to load PWA Element 'pwa-camera-modal'. See the docs: https://capacitorjs.com/docs/web/pwa-elements.`,
);
this.fileInputExperience(options, resolve, reject);
}
}
private fileInputExperience(
options: ImageOptions,
resolve: any,
reject: any,
) {
let input = document.querySelector(
'#_capacitor-camera-input',
) as HTMLInputElement;
const cleanup = () => {
input.parentNode?.removeChild(input);
};
if (!input) {
input = document.createElement('input') as HTMLInputElement;
input.id = '_capacitor-camera-input';
input.type = 'file';
input.hidden = true;
document.body.appendChild(input);
input.addEventListener('change', (_e: any) => {
const file = input.files![0];
let format = 'jpeg';
if (file.type === 'image/png') {
format = 'png';
} else if (file.type === 'image/gif') {
format = 'gif';
}
if (
options.resultType === 'dataUrl' ||
options.resultType === 'base64'
) {
const reader = new FileReader();
reader.addEventListener('load', () => {
if (options.resultType === 'dataUrl') {
resolve({
dataUrl: reader.result,
format,
} as Photo);
} else if (options.resultType === 'base64') {
const b64 = (reader.result as string).split(',')[1];
resolve({
base64String: b64,
format,
} as Photo);
}
cleanup();
});
reader.readAsDataURL(file);
} else {
resolve({
webPath: URL.createObjectURL(file),
format: format,
});
cleanup();
}
});
input.addEventListener('cancel', (_e: any) => {
reject(new CapacitorException('User cancelled photos app'));
cleanup();
});
}
input.accept = 'image/*';
(input as any).capture = true;
if (
options.source === CameraSource.Photos ||
options.source === CameraSource.Prompt
) {
input.removeAttribute('capture');
} else if (options.direction === CameraDirection.Front) {
(input as any).capture = 'user';
} else if (options.direction === CameraDirection.Rear) {
(input as any).capture = 'environment';
}
input.click();
}
private multipleFileInputExperience(resolve: any, reject: any) {
let input = document.querySelector(
'#_capacitor-camera-input-multiple',
) as HTMLInputElement;
const cleanup = () => {
input.parentNode?.removeChild(input);
};
if (!input) {
input = document.createElement('input') as HTMLInputElement;
input.id = '_capacitor-camera-input-multiple';
input.type = 'file';
input.hidden = true;
input.multiple = true;
document.body.appendChild(input);
input.addEventListener('change', (_e: any) => {
const photos = [];
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < input.files!.length; i++) {
const file = input.files![i];
let format = 'jpeg';
if (file.type === 'image/png') {
format = 'png';
} else if (file.type === 'image/gif') {
format = 'gif';
}
photos.push({
webPath: URL.createObjectURL(file),
format: format,
});
}
resolve({ photos });
cleanup();
});
input.addEventListener('cancel', (_e: any) => {
reject(new CapacitorException('User cancelled photos app'));
cleanup();
});
}
input.accept = 'image/*';
input.click();
}
private _getCameraPhoto(photo: Blob, options: ImageOptions) {
return new Promise<Photo>((resolve, reject) => {
const reader = new FileReader();
const format = photo.type.split('/')[1];
if (options.resultType === 'uri') {
resolve({
webPath: URL.createObjectURL(photo),
format: format,
saved: false,
});
} else {
reader.readAsDataURL(photo);
reader.onloadend = () => {
const r = reader.result as string;
if (options.resultType === 'dataUrl') {
resolve({
dataUrl: r,
format: format,
saved: false,
});
} else {
resolve({
base64String: r.split(',')[1],
format: format,
saved: false,
});
}
};
reader.onerror = e => {
reject(e);
};
}
});
}
async checkPermissions(): Promise<PermissionStatus> {
if (typeof navigator === 'undefined' || !navigator.permissions) {
throw this.unavailable('Permissions API not available in this browser');
}
try {
// https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
// the specific permissions that are supported varies among browsers that implement the
// permissions API, so we need a try/catch in case 'camera' is invalid
const permission = await window.navigator.permissions.query({
name: 'camera',
});
return {
camera: permission.state,
photos: 'granted',
};
} catch {
throw this.unavailable(
'Camera permissions are not available in this browser',
);
}
}
async requestPermissions(): Promise<PermissionStatus> {
throw this.unimplemented('Not implemented on web.');
}
async pickLimitedLibraryPhotos(): Promise<GalleryPhotos> {
throw this.unavailable('Not implemented on web.');
}
async getLimitedLibraryPhotos(): Promise<GalleryPhotos> {
throw this.unavailable('Not implemented on web.');
}
}
const Camera = new CameraWeb();
export { Camera };