@iobroker/adapter-react-v5 6.1.3 → 6.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +6 -0
  2. package/craco-module-federation.js +1 -1
  3. package/package.json +1 -1
  4. package/src/AdminConnection.tsx +3 -0
  5. package/src/Components/404.tsx +121 -0
  6. package/src/Components/ColorPicker.tsx +315 -0
  7. package/src/Components/ComplexCron.tsx +507 -0
  8. package/src/Components/CopyToClipboard.tsx +165 -0
  9. package/src/Components/CustomModal.tsx +163 -0
  10. package/src/Components/FileBrowser.tsx +2394 -0
  11. package/src/Components/FileViewer.tsx +384 -0
  12. package/src/Components/Icon.tsx +210 -0
  13. package/src/Components/IconPicker.tsx +149 -0
  14. package/src/Components/IconSelector.tsx +2202 -0
  15. package/src/Components/Image.tsx +176 -0
  16. package/src/Components/Loader.tsx +304 -0
  17. package/src/Components/Logo.tsx +166 -0
  18. package/src/Components/MDUtils.tsx +100 -0
  19. package/src/Components/ObjectBrowser.tsx +7915 -0
  20. package/src/Components/Router.tsx +90 -0
  21. package/src/Components/SaveCloseButtons.tsx +113 -0
  22. package/src/Components/Schedule.tsx +1724 -0
  23. package/src/Components/SelectWithIcon.tsx +197 -0
  24. package/src/Components/TabContainer.tsx +55 -0
  25. package/src/Components/TabContent.tsx +37 -0
  26. package/src/Components/TabHeader.tsx +19 -0
  27. package/src/Components/TableResize.tsx +259 -0
  28. package/src/Components/TextWithIcon.tsx +148 -0
  29. package/src/Components/ToggleThemeMenu.tsx +34 -0
  30. package/src/Components/TreeTable.tsx +919 -0
  31. package/src/Components/UploadImage.tsx +599 -0
  32. package/src/Components/Utils.tsx +1794 -0
  33. package/src/Components/loader.css +222 -0
  34. package/src/Components/withWidth.tsx +21 -0
  35. package/src/Connection.tsx +7 -0
  36. package/src/Dialogs/ComplexCron.tsx +129 -0
  37. package/src/Dialogs/Confirm.tsx +162 -0
  38. package/src/Dialogs/Cron.tsx +182 -0
  39. package/src/Dialogs/Error.tsx +72 -0
  40. package/src/Dialogs/Message.tsx +71 -0
  41. package/src/Dialogs/SelectFile.tsx +270 -0
  42. package/src/Dialogs/SelectID.tsx +298 -0
  43. package/src/Dialogs/SimpleCron.tsx +100 -0
  44. package/src/Dialogs/TextInput.tsx +107 -0
  45. package/src/GenericApp.tsx +976 -0
  46. package/src/LegacyConnection.tsx +3589 -0
  47. package/src/Prompt.tsx +20 -0
  48. package/src/Theme.tsx +479 -0
  49. package/src/icons/IconAdapter.tsx +20 -0
  50. package/src/icons/IconAlias.tsx +20 -0
  51. package/src/icons/IconChannel.tsx +21 -0
  52. package/src/icons/IconClearFilter.tsx +22 -0
  53. package/src/icons/IconClosed.tsx +17 -0
  54. package/src/icons/IconCopy.tsx +16 -0
  55. package/src/icons/IconDevice.tsx +27 -0
  56. package/src/icons/IconDocument.tsx +17 -0
  57. package/src/icons/IconDocumentReadOnly.tsx +18 -0
  58. package/src/icons/IconExpert.tsx +18 -0
  59. package/src/icons/IconFx.tsx +36 -0
  60. package/src/icons/IconInstance.tsx +20 -0
  61. package/src/icons/IconLogout.tsx +30 -0
  62. package/src/icons/IconNoIcon.tsx +19 -0
  63. package/src/icons/IconOpen.tsx +17 -0
  64. package/src/icons/IconProps.tsx +15 -0
  65. package/src/icons/IconState.tsx +17 -0
  66. package/src/index.css +55 -0
  67. package/assets/devices/list.json +0 -994
  68. package/assets/devices/names.txt +0 -63
  69. package/assets/devices/parseNames.d.ts +0 -0
  70. package/assets/devices/parseNames.js +0 -34
  71. package/assets/rooms/list.json +0 -946
  72. package/assets/rooms/names.txt +0 -60
  73. package/assets/rooms/parseNames.d.ts +0 -0
  74. package/assets/rooms/parseNames.js +0 -34
@@ -0,0 +1,507 @@
1
+ import React, { Component } from 'react';
2
+
3
+ import {
4
+ Checkbox,
5
+ Button,
6
+ MenuItem,
7
+ Select,
8
+ FormControlLabel,
9
+ AppBar,
10
+ Tabs,
11
+ Tab,
12
+ TextField, Box,
13
+ } from '@mui/material';
14
+
15
+ import I18n from '../i18n';
16
+ import convertCronToText from './SimpleCron/cronText';
17
+
18
+ const styles: Record<string, React.CSSProperties> = {
19
+ mainDiv: {
20
+ width: '100%',
21
+ height: '100%',
22
+ },
23
+ periodSelect: {
24
+ // margin: '0 10px 60px 10px',
25
+ display: 'block',
26
+ width: 200,
27
+ },
28
+ slider: {
29
+ marginTop: 20,
30
+ display: 'block',
31
+ width: '100%',
32
+ },
33
+ tabContent: {
34
+ padding: 20,
35
+ height: 'calc(100% - 240px)',
36
+ overflow: 'auto',
37
+ },
38
+ numberButton: {
39
+ padding: 4,
40
+ minWidth: 40,
41
+ margin: 5,
42
+ },
43
+ numberButtonBreak: {
44
+ display: 'block',
45
+ },
46
+ appBar: {
47
+ color: 'white',
48
+ },
49
+ };
50
+
51
+ const WEEKDAYS = [
52
+ 'Sunday',
53
+ 'Monday',
54
+ 'Tuesday',
55
+ 'Wednesday',
56
+ 'Thursday',
57
+ 'Friday',
58
+ 'Saturday',
59
+ 'Sunday',
60
+ ];
61
+ const MONTHS = [
62
+ 'January',
63
+ 'February',
64
+ 'March',
65
+ 'April',
66
+ 'May',
67
+ 'June',
68
+ 'July',
69
+ 'August',
70
+ 'September',
71
+ 'October',
72
+ 'November',
73
+ 'December',
74
+ ];
75
+
76
+ // 5-7,9-11 => [5,6,7,9,10,11]
77
+ function convertMinusIntoArray(value: string | false | undefined, max: number): number[] {
78
+ const result: number[] = [];
79
+
80
+ if (value === '*') {
81
+ if (max === 24 || max === 60 || max === 7) {
82
+ for (let i = 0; i < max; i++) {
83
+ result.push(i);
84
+ }
85
+ } else {
86
+ for (let i = 1; i <= max; i++) {
87
+ result.push(i);
88
+ }
89
+ }
90
+ return result; // array with entries max
91
+ }
92
+
93
+ const parts = (value || '').toString().split(',');
94
+
95
+ for (let p = 0; p < parts.length; p++) {
96
+ if (!parts[p].trim().length) {
97
+ continue;
98
+ }
99
+ const items = parts[p].trim().split('-');
100
+ if (items.length > 1) {
101
+ const iMax = parseInt(items[1], 10);
102
+ for (let i = parseInt(items[0], 10); i <= iMax; i++) {
103
+ result.push(i);
104
+ }
105
+ } else {
106
+ result.push(parseInt(parts[p], 10));
107
+ }
108
+ }
109
+
110
+ result.sort();
111
+
112
+ // remove double entries
113
+ for (let p = result.length - 1; p >= 0; p--) {
114
+ if (result[p] === result[p + 1]) {
115
+ result.splice(p + 1, 1);
116
+ }
117
+ }
118
+
119
+ return result;
120
+ }
121
+
122
+ // [5,6,7,9,10,11] => 5-7,9-11
123
+ function convertArrayIntoMinus(value: number | number [], max: number): string {
124
+ if (typeof value !== 'object') {
125
+ value = [value];
126
+ }
127
+ if (value.length === max) {
128
+ return '*';
129
+ }
130
+ const newParts = [];
131
+ if (!value.length) {
132
+ return '-';
133
+ }
134
+ value = value.map(a => parseInt(a as any as string, 10));
135
+
136
+ value.sort((a, b) => a - b);
137
+
138
+ let start = value[0];
139
+ let end = value[0];
140
+ for (let p = 1; p < value.length; p++) {
141
+ if (value[p] - 1 !== parseInt(value[p - 1] as any as string, 10)) {
142
+ if (start === end) {
143
+ newParts.push(start);
144
+ } else if (end - 1 === start) {
145
+ newParts.push(`${start},${end}`);
146
+ } else {
147
+ newParts.push(`${start}-${end}`);
148
+ }
149
+ start = value[p];
150
+ }
151
+ end = value[p];
152
+ }
153
+
154
+ if (start === end) {
155
+ newParts.push(start);
156
+ } else if (end - 1 === start) {
157
+ newParts.push(`${start},${end}`);
158
+ } else {
159
+ newParts.push(`${start}-${end}`);
160
+ }
161
+
162
+ return newParts.join(',');
163
+ }
164
+
165
+ type CronNames = 'seconds' | 'minutes' | 'hours' | 'dates' | 'months' | 'dow';
166
+
167
+ interface CronProps {
168
+ seconds: string | false | null;
169
+ minutes: string | null;
170
+ hours: string | null;
171
+ dates: string | null;
172
+ months: string | null;
173
+ dow: string | null;
174
+ }
175
+
176
+ interface ComplexCronProps {
177
+ cronExpression: string;
178
+ onChange: (cron: string) => void;
179
+ language: ioBroker.Languages;
180
+ }
181
+
182
+ // type CronModes = 'every' | 'everyN' | 'specific';
183
+
184
+ interface ComplexCronState {
185
+ extended: boolean;
186
+ tab: number;
187
+ cron: string;
188
+ seconds?: string | false;
189
+ minutes?: string;
190
+ hours?: string;
191
+ dates?: string;
192
+ months?: string;
193
+ dow?: string;
194
+ modes: CronProps;
195
+ }
196
+
197
+ class ComplexCron extends Component<ComplexCronProps, ComplexCronState> {
198
+ constructor(props: ComplexCronProps) {
199
+ super(props);
200
+ let cron = typeof this.props.cronExpression === 'string' ?
201
+ this.props.cronExpression.replace(/^["']/, '').replace(/["']\n?$/, '') : '';
202
+ if (cron[0] === '{') {
203
+ cron = '';
204
+ }
205
+ const state = ComplexCron.cron2state(cron || '* * * * *');
206
+
207
+ this.state = {
208
+ extended: false,
209
+ tab: state.seconds !== false ? 1 : 0,
210
+ cron: ComplexCron.state2cron(state),
211
+ modes: {
212
+ seconds: null,
213
+ minutes: null,
214
+ hours: null,
215
+ dates: null,
216
+ months: null,
217
+ dow: null,
218
+ },
219
+ };
220
+ Object.assign(this.state, state);
221
+ if (this.state.cron !== this.props.cronExpression) {
222
+ setTimeout(() => this.props.onChange && this.props.onChange(this.state.cron), 100);
223
+ }
224
+ }
225
+
226
+ static cron2state(cron: string): CronProps {
227
+ cron = cron.replace(/['"]/g, '').trim();
228
+ const cronParts = cron.split(' ').map(p => p.trim());
229
+ let options: CronProps;
230
+
231
+ if (cronParts.length === 6) {
232
+ options = {
233
+ seconds: cronParts[0] || '*',
234
+ minutes: cronParts[1] || '*',
235
+ hours: cronParts[2] || '*',
236
+ dates: cronParts[3] || '*',
237
+ months: cronParts[4] || '*',
238
+ dow: cronParts[5] || '*',
239
+ };
240
+ } else {
241
+ options = {
242
+ seconds: false,
243
+ minutes: cronParts[0] || '*',
244
+ hours: cronParts[1] || '*',
245
+ dates: cronParts[2] || '*',
246
+ months: cronParts[3] || '*',
247
+ dow: cronParts[4] || '*',
248
+ };
249
+ }
250
+ return options;
251
+ }
252
+
253
+ static state2cron(state: ComplexCronState | CronProps): string {
254
+ let text = `${state.minutes} ${state.hours} ${state.dates} ${state.months} ${state.dow}`;
255
+ if (state.seconds !== false) {
256
+ text = `${state.seconds} ${text}`;
257
+ }
258
+ return text;
259
+ }
260
+
261
+ recalcCron() {
262
+ const cron = ComplexCron.state2cron(this.state);
263
+ if (cron !== this.state.cron) {
264
+ this.setState({ cron }, () =>
265
+ this.props.onChange && this.props.onChange(this.state.cron));
266
+ }
267
+ }
268
+
269
+ onToggle(i: boolean | number, type: CronNames, max: number) {
270
+ if (i === true) {
271
+ this.setCronAttr(type, '*');
272
+ } else if (i === false) {
273
+ if (max === 60 || max === 24) {
274
+ this.setCronAttr(type, '0');
275
+ } else {
276
+ this.setCronAttr(type, '1');
277
+ }
278
+ } else {
279
+ const nums = convertMinusIntoArray(this.state[type], max);
280
+ const pos = nums.indexOf(i);
281
+ if (pos !== -1) {
282
+ nums.splice(pos, 1);
283
+ } else {
284
+ nums.push(i);
285
+ nums.sort();
286
+ }
287
+ this.setCronAttr(type, convertArrayIntoMinus(nums, max));
288
+ }
289
+ }
290
+
291
+ getDigitsSelector(type: CronNames, max: number) {
292
+ let values = [];
293
+ if (max === 7) {
294
+ values = [1, 2, 3, 4, 5, 6, 0];
295
+ } else if (max === 60 || max === 24) {
296
+ for (let i = 0; i < max; i++) {
297
+ values.push(i);
298
+ }
299
+ } else {
300
+ for (let i = 1; i <= max; i++) {
301
+ values.push(i);
302
+ }
303
+ }
304
+
305
+ const parts = convertMinusIntoArray(this.state[type], max);
306
+
307
+ return [
308
+ <Button
309
+ key="removeall"
310
+ variant="outlined"
311
+ style={styles.numberButton}
312
+ // style={{paddingBottom: 20}}
313
+ color="primary"
314
+ onClick={() => this.onToggle(false, type, max)}
315
+ >
316
+ {I18n.t('ra_Deselect all')}
317
+ </Button>,
318
+ <Button
319
+ key="addall"
320
+ variant="contained"
321
+ // style={{paddingBottom: 20}}
322
+ style={styles.numberButton}
323
+ color="secondary"
324
+ onClick={() => this.onToggle(true, type, max)}
325
+ >
326
+ {I18n.t('ra_Select all')}
327
+ </Button>,
328
+ <div key="all">
329
+ {values.map(i =>
330
+ [((max === 7 && i === 4) ||
331
+ (max === 12 && i === 7) ||
332
+ (max === 31 && !((i - 1) % 10)) ||
333
+ (max === 60 && i && !(i % 10)) ||
334
+ (max === 24 && i && !(i % 6))) ?
335
+ <div key={`allInner${i}`} style={{ width: '100%' }} /> : null,
336
+ <Button
337
+ key={`_${i}`}
338
+ variant={parts.indexOf(i) !== -1 ? 'contained' : 'outlined'}
339
+ style={styles.numberButton}
340
+ color={parts.indexOf(i) !== -1 ? 'secondary' : 'primary'}
341
+ onClick={() => this.onToggle(i, type, max)}
342
+ >
343
+ {max === 7 ? I18n.t(WEEKDAYS[i]) : (max === 12 ? MONTHS[i - 1] : i)}
344
+ </Button>,
345
+ ])}
346
+ </div>,
347
+ ];
348
+ }
349
+
350
+ getPeriodsTab(type: CronNames, max: number): React.JSX.Element | null {
351
+ const value = this.state[type];
352
+ let every = value === '*';
353
+ let everyN = value === undefined || value === null ? false : value.toString().includes('/');
354
+ let select;
355
+ if (this.state.modes[type] === null) {
356
+ select = every ? 'every' : (everyN ? 'everyN' : 'specific');
357
+ const modes = JSON.parse(JSON.stringify(this.state.modes));
358
+ modes[type] = select;
359
+ setTimeout(() => this.setState({ modes }, () => this.recalcCron()), 100);
360
+ return null;
361
+ }
362
+
363
+ every = this.state.modes[type] === 'every';
364
+ everyN = this.state.modes[type] === 'everyN';
365
+ select = this.state.modes[type];
366
+
367
+ let valueNumber = 1;
368
+ if (everyN && value) {
369
+ valueNumber = parseInt(value.replace('*/', ''), 10) || 1;
370
+ }
371
+
372
+ return <div>
373
+ <Select
374
+ variant="standard"
375
+ style={{ ...styles.periodSelect, verticalAlign: 'bottom' }}
376
+ value={select}
377
+ onChange={e => {
378
+ const modes = JSON.parse(JSON.stringify(this.state.modes));
379
+ modes[type] = e.target.value;
380
+ if (e.target.value === 'every') {
381
+ this.setCronAttr(type, '*', modes);
382
+ } else if (e.target.value === 'everyN') {
383
+ const num = parseInt((this.state[type] || '').toString().replace('*/', ''), 10) || 1;
384
+ this.setCronAttr(type, `*/${num}`, modes);
385
+ } else if (e.target.value === 'specific') {
386
+ let num = parseInt((this.state[type] || '').toString().split(',')[0], 10) || 0;
387
+ if (!num && (type === 'months' || type === 'dates')) {
388
+ num = 1;
389
+ }
390
+ this.setCronAttr(type, convertArrayIntoMinus(num, max), modes);
391
+ }
392
+ }}
393
+ >
394
+ <MenuItem key="every" value="every">{I18n.t(`sc_every_${type}`)}</MenuItem>
395
+ <MenuItem key="everyN" value="everyN">{I18n.t(`sc_everyN_${type}`)}</MenuItem>
396
+ <MenuItem key="specific" value="specific">{I18n.t(`sc_specific_${type}`)}</MenuItem>
397
+ </Select>
398
+ {everyN && false && <span>{value}</span>}
399
+ {everyN && <TextField
400
+ variant="standard"
401
+ key="interval"
402
+ label={I18n.t(`sc_${type}`)}
403
+ value={valueNumber}
404
+ inputProps={{ min: 1, max }}
405
+ onChange={e => {
406
+ // @ts-expect-error is allowed
407
+ this.setState({ [type]: `*/${e.target.value}` }, () => this.recalcCron());
408
+ }}
409
+ InputLabelProps={{ shrink: true }}
410
+ type="number"
411
+ margin="normal"
412
+ />}
413
+ {!every && !everyN && this.getDigitsSelector(type, max)}
414
+ </div>;
415
+ }
416
+
417
+ static convertCronToText(cron: string, lang: ioBroker.Languages): string {
418
+ if (cron.split(' ').includes('-')) {
419
+ return I18n.t('ra_Invalid CRON');
420
+ }
421
+ return convertCronToText(cron, lang);
422
+ }
423
+
424
+ setCronAttr(attr: CronNames, value: string, modes?: CronProps) {
425
+ if (modes) {
426
+ if (attr === 'seconds') {
427
+ this.setState({ seconds: value, modes }, () =>
428
+ this.recalcCron());
429
+ } else if (attr === 'minutes') {
430
+ this.setState({ minutes: value, modes }, () =>
431
+ this.recalcCron());
432
+ } else if (attr === 'hours') {
433
+ this.setState({ hours: value, modes }, () =>
434
+ this.recalcCron());
435
+ } else if (attr === 'dates') {
436
+ this.setState({ dates: value, modes }, () =>
437
+ this.recalcCron());
438
+ } else if (attr === 'months') {
439
+ this.setState({ months: value, modes }, () =>
440
+ this.recalcCron());
441
+ } else if (attr === 'dow') {
442
+ this.setState({ dow: value, modes }, () =>
443
+ this.recalcCron());
444
+ } else {
445
+ this.setState({ modes }, () =>
446
+ this.recalcCron());
447
+ }
448
+ } else if (attr === 'seconds') {
449
+ this.setState({ seconds: value }, () =>
450
+ this.recalcCron());
451
+ } else if (attr === 'minutes') {
452
+ this.setState({ minutes: value }, () =>
453
+ this.recalcCron());
454
+ } else if (attr === 'hours') {
455
+ this.setState({ hours: value }, () =>
456
+ this.recalcCron());
457
+ } else if (attr === 'dates') {
458
+ this.setState({ dates: value }, () =>
459
+ this.recalcCron());
460
+ } else if (attr === 'months') {
461
+ this.setState({ months: value }, () =>
462
+ this.recalcCron());
463
+ } else if (attr === 'dow') {
464
+ this.setState({ dow: value }, () =>
465
+ this.recalcCron());
466
+ }
467
+ }
468
+
469
+ render() {
470
+ const tab = this.state.seconds !== false ? this.state.tab : this.state.tab + 1;
471
+ return <div style={styles.mainDiv}>
472
+ <div style={{ paddingLeft: 8, width: '100%' }}><TextField variant="standard" style={{ width: '100%' }} value={this.state.cron} disabled /></div>
473
+ <div style={{ paddingLeft: 8, width: '100%', height: 60 }}>{ComplexCron.convertCronToText(this.state.cron, this.props.language || 'en')}</div>
474
+ <FormControlLabel
475
+ control={<Checkbox
476
+ checked={!!this.state.seconds}
477
+ onChange={e => this.setState({ seconds: e.target.checked ? '*' : false }, () => this.recalcCron())}
478
+ />}
479
+ label={I18n.t('ra_use seconds')}
480
+ />
481
+ <AppBar position="static" sx={{ '&.MuiAppBar-root': styles.appBar }} color="secondary">
482
+ <Tabs
483
+ value={this.state.tab}
484
+ style={styles.appBar}
485
+ color="secondary"
486
+ onChange={(active, _tab) =>
487
+ this.setState({ tab: _tab })}
488
+ >
489
+ {this.state.seconds !== false && <Tab id="sc_seconds" label={I18n.t('sc_seconds')} />}
490
+ <Tab id="minutes" label={I18n.t('sc_minutes')} />
491
+ <Tab id="hours" label={I18n.t('sc_hours')} />
492
+ <Tab id="dates" label={I18n.t('sc_dates')} />
493
+ <Tab id="months" label={I18n.t('sc_months')} />
494
+ <Tab id="dow" label={I18n.t('sc_dows')} />
495
+ </Tabs>
496
+ </AppBar>
497
+ {tab === 0 && <div style={styles.tabContent}>{this.getPeriodsTab('seconds', 60)}</div>}
498
+ {tab === 1 && <div style={styles.tabContent}>{this.getPeriodsTab('minutes', 60)}</div>}
499
+ {tab === 2 && <div style={styles.tabContent}>{this.getPeriodsTab('hours', 24)}</div>}
500
+ {tab === 3 && <div style={styles.tabContent}>{this.getPeriodsTab('dates', 31)}</div>}
501
+ {tab === 4 && <div style={styles.tabContent}>{this.getPeriodsTab('months', 12)}</div>}
502
+ {tab === 5 && <div style={styles.tabContent}>{this.getPeriodsTab('dow', 7)}</div>}
503
+ </div>;
504
+ }
505
+ }
506
+
507
+ export default ComplexCron;
@@ -0,0 +1,165 @@
1
+ /*
2
+ MIT License
3
+
4
+ Copyright (c) 2017 sudodoki <smd.deluzion@gmail.com>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+ // https://github.com/sudodoki/toggle-selection/blob/gh-pages/index.js
25
+ function deselectCurrent() {
26
+ const selection = document.getSelection();
27
+ if (!selection?.rangeCount) {
28
+ return () => {};
29
+ }
30
+ let active = document.activeElement as HTMLElement | null;
31
+
32
+ const ranges: Range[] = [];
33
+ for (let i = 0; i < selection.rangeCount; i++) {
34
+ ranges.push(selection.getRangeAt(i));
35
+ }
36
+
37
+ switch (active?.tagName.toUpperCase()) { // .toUpperCase handles XHTML
38
+ case 'INPUT':
39
+ case 'TEXTAREA':
40
+ active.blur();
41
+ break;
42
+
43
+ default:
44
+ active = null;
45
+ break;
46
+ }
47
+
48
+ selection.removeAllRanges();
49
+ return () => {
50
+ selection.type === 'Caret' &&
51
+ selection.removeAllRanges();
52
+
53
+ if (!selection.rangeCount) {
54
+ ranges.forEach(range => selection.addRange(range));
55
+ }
56
+
57
+ active && active.focus();
58
+ };
59
+ }
60
+
61
+ // https://github.com/sudodoki/copy-to-clipboard/blob/master/index.js
62
+
63
+ const clipboardToIE11Formatting = {
64
+ 'text/plain': 'Text',
65
+ 'text/html': 'Url',
66
+ default: 'Text',
67
+ };
68
+
69
+ const defaultMessage = 'Copy to clipboard: #{key}, Enter';
70
+
71
+ function format(message: string): string {
72
+ const copyKey = `${/mac os x/i.test(navigator.userAgent) ? '⌘' : 'Ctrl'}+C`;
73
+ return message.replace(/#{\s*key\s*}/g, copyKey);
74
+ }
75
+
76
+ function copy(text: string, options?: { debug?: boolean; format?: string; message?: string }) {
77
+ let reselectPrevious;
78
+ let range;
79
+ let selection;
80
+ let mark;
81
+ let success = false;
82
+ options = options || {};
83
+ const debug = options.debug || false;
84
+ try {
85
+ reselectPrevious = deselectCurrent();
86
+
87
+ range = document.createRange();
88
+ selection = document.getSelection();
89
+
90
+ mark = document.createElement('span');
91
+ mark.textContent = text;
92
+ // avoid screen readers from reading out loud the text
93
+ mark.ariaHidden = 'true';
94
+ // reset user styles for span element
95
+ mark.style.all = 'unset';
96
+ // prevents scrolling to the end of the page
97
+ mark.style.position = 'fixed';
98
+ mark.style.top = '0px';
99
+ mark.style.clip = 'rect(0, 0, 0, 0)';
100
+ // used to preserve spaces and line breaks
101
+ mark.style.whiteSpace = 'pre';
102
+ // do not inherit user-select (it may be `none`)
103
+ mark.style.webkitUserSelect = 'text';
104
+ mark.style.MozUserSelect = 'text';
105
+ mark.style.msUserSelect = 'text';
106
+ mark.style.userSelect = 'text';
107
+ mark.addEventListener('copy', e => {
108
+ e.stopPropagation();
109
+ if (options?.format) {
110
+ e.preventDefault();
111
+ if (typeof e.clipboardData === 'undefined') { // IE 11
112
+ debug && console.warn('unable to use e.clipboardData');
113
+ debug && console.warn('trying IE specific stuff');
114
+ (window as any).clipboardData?.clearData();
115
+ const _format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting.default;
116
+ (window as any).clipboardData?.setData(_format, text);
117
+ } else { // all other browsers
118
+ e.clipboardData?.clearData();
119
+ e.clipboardData?.setData(options.format, text);
120
+ }
121
+ }
122
+ });
123
+
124
+ document.body.appendChild(mark);
125
+
126
+ range.selectNodeContents(mark);
127
+ selection?.addRange(range);
128
+
129
+ const successful = document.execCommand('copy');
130
+ if (!successful) {
131
+ throw new Error('copy command was unsuccessful');
132
+ }
133
+ success = true;
134
+ } catch (err) {
135
+ debug && console.error('unable to copy using execCommand: ', err);
136
+ debug && console.warn('trying IE specific stuff');
137
+ try {
138
+ (window as any).clipboardData.setData(options.format || 'text', text);
139
+ // options.onCopy && options.onCopy((window as any).clipboardData);
140
+ success = true;
141
+ } catch (error) {
142
+ debug && console.error('unable to copy using clipboardData: ', error);
143
+ debug && console.error('falling back to prompt');
144
+ const message = format('message' in options ? options.message || '' : defaultMessage);
145
+ window.prompt(message, text);
146
+ }
147
+ } finally {
148
+ if (selection) {
149
+ if (range && typeof selection.removeRange === 'function') {
150
+ selection.removeRange(range);
151
+ } else {
152
+ selection.removeAllRanges();
153
+ }
154
+ }
155
+
156
+ if (mark) {
157
+ document.body.removeChild(mark);
158
+ }
159
+ reselectPrevious && reselectPrevious();
160
+ }
161
+
162
+ return success;
163
+ }
164
+
165
+ export default copy;