-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
560 lines (526 loc) · 14.6 KB
/
Copy pathmain.js
File metadata and controls
560 lines (526 loc) · 14.6 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
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
const { InstanceBase, runEntrypoint, InstanceStatus } = require('@companion-module/base')
const UpgradeScripts = require('./upgrades')
const UpdateActions = require('./actions')
const UpdateFeedbacks = require('./feedbacks')
const UpdateVariableDefinitions = require('./variables')
const UpdatePresetDefinitions = require('./presets')
const { format } = require('string-kit')
const numfmt = require('numfmt')
class DataEntryInstance extends InstanceBase {
constructor(internal) {
super(internal)
}
/**
* Initialization of module
* @param {*} config config provided from core
*/
async init(config) {
this.config = config
this.updateStatus(InstanceStatus.Ok)
this.modifier = [
{
effective: false,
onetime: false,
controls: new Set(),
},
{
effective: false,
onetime: false,
controls: new Set(),
},
{
effective: false,
onetime: false,
controls: new Set(),
},
]
this.timeout = undefined
this.variables = [
{ variableId: 'entry_raw', name: 'Current entry', initial: '' },
{ variableId: 'entry_last', name: 'Last entry', initial: '' },
{ variableId: 'entry_second_last', name: 'Second last entry', initial: '' },
{ variableId: 'entry_raw_length', name: 'Length of current entry', initial: 0 },
{ variableId: 'entry_last_length', name: 'Length of last entry', initial: 0 },
{ variableId: 'entry_formatted', name: 'Current entry formatted', initial: '' },
{ variableId: 'entry_cursor', name: 'Current entry with cursor shown', initial: this.config.cursor },
{ variableId: 'entry_cursor_position', name: 'Position of cursor', initial: 0 },
{ variableId: 'entrycounter', name: 'Counter of entries', initial: 0 },
]
this.updateVariableDefinitions()
this.initVariables()
this.updateActions()
this.updateFeedbacks()
this.updatePresetDefinitions()
}
/**
* Cleanup stuff, get's called when module is destroyed
*/
async destroy() {
if (this.timeout) clearTimeout(this.timeout)
this.log('debug', 'destroy')
}
async configUpdated(config) {
this.cancelTimeout()
this.config = config
this.updateActions()
}
/**
* Sets all variables to their initial values
*/
async initVariables() {
this.variables.forEach((vari) => {
this[vari.variableId] = vari.initial ?? undefined
})
const initObj = {}
this.setVariableValues(
this.variables
.filter((vari) => vari.initial != undefined)
.reduce((obj, vari) => {
return {
...obj,
[vari.variableId]: vari.initial,
}
}, initObj),
)
}
/**
* Return config fields for web config
*/
getConfigFields() {
return [
{
id: 'hint',
type: 'static-text',
label: 'This is a complex module, please read the help page for an explanation of all options.',
width: 12,
},
{
id: 'autolengthraw',
label: 'Automatic enter when raw length is reached',
type: 'checkbox',
default: false,
width: 9,
},
{
type: 'number',
id: 'enterlengthraw',
label: 'Length',
width: 3,
min: 1,
max: 65536,
step: 1,
default: 4,
isVisibleExpression: `$(options:autolengthraw) == true`,
},
{
id: 'autolengthformatted',
label: 'Automatic enter when formatted length is reached',
type: 'checkbox',
default: false,
width: 9,
},
{
type: 'number',
id: 'enterlengthformatted',
label: 'Length',
width: 3,
min: 1,
max: 65536,
step: 1,
default: 4,
isVisibleExpression: `$(options:autolengthformatted) == true`,
},
{
id: 'autoregex',
label: 'Automatic enter when regular expression matches',
type: 'checkbox',
default: false,
width: 9,
},
{
id: 'enterregex',
label: 'Regular expression',
type: 'textinput',
width: 12,
default: '/.*/i',
regex: '/^/(.+)\\/([gmiyusvd]?)$/',
isVisibleExpression: `$(options:autoregex) == true`,
},
{
id: 'autotime',
label: 'Automatic enter after inactivity timeout',
type: 'checkbox',
default: false,
width: 9,
},
{
type: 'number',
id: 'timeout',
label: 'Timeout (s)',
width: 3,
min: 0.1,
max: 30,
step: 0.1,
default: 2.5,
isVisibleExpression: `$(options:autotime) == true`,
},
{
type: 'dropdown',
id: 'criterialogic',
label: 'Enter Criteria',
width: 12,
choices: [
{ id: 'or', label: 'Any checked criterion is met (OR)' },
{ id: 'and', label: 'All checked cruteria are met (AND)' },
],
default: 'or',
},
{
type: 'dropdown',
id: 'copydata',
label: 'When entering...',
width: 6,
choices: [
{ id: 'raw', label: '...copy raw entry' },
{ id: 'formatted', label: '...copy formatted entry' },
],
default: 'raw',
},
{
type: 'dropdown',
id: 'after',
label: 'After entering...',
width: 6,
choices: [
{ id: 'clear', label: '...clear raw entry' },
{ id: 'keep', label: '...keep raw entry' },
],
default: 'clear',
},
{
type: 'dropdown',
id: 'formattype',
label: 'Format Type',
width: 6,
choices: [
{ id: 'none', label: 'None' },
{ id: 'ecmaauto', label: 'ECMA-376 automatic' },
{ id: 'ecmastring', label: 'ECMA-376 text' },
{ id: 'ecmanumber', label: 'ECMA-376 number' },
{ id: 'ecmadate', label: 'ECMA-376 date' },
{ id: 'ecmatime', label: 'ECMA-376 time' },
{ id: 'ecmabool', label: 'ECMA-376 boolean' },
{ id: 'printf', label: 'Printf format' },
{ id: 'regex', label: 'Regular Expression' },
],
default: 'none',
},
{
type: 'static-text',
id: 'placeholder',
label: '',
value: '',
width: 6,
isVisibleExpression: `$(options:formattype) == 'none'`,
},
{
type: 'textinput',
id: 'formatecma',
label: 'ECMA-376 format expression',
width: 6,
default: '*',
useVariables: true,
isVisibleExpression: `includes($(options:formattype), "ecma")`,
},
{
type: 'textinput',
id: 'formatprintf',
label: 'printf format expression',
width: 6,
default: '%s',
useVariables: true,
isVisibleExpression: `$(options:formattype) == 'printf'`,
},
{
type: 'textinput',
id: 'formatregex',
label: 'Regular replacement expression',
width: 6,
default: '/(.)/$1/g',
useVariables: true,
isVisibleExpression: `$(options:formattype) == 'regex'`,
},
{
type: 'number',
id: 'maxlength',
label: 'Maximum entry length before truncation',
width: 6,
min: 1,
max: 65536,
step: 1,
default: 1024,
},
{
type: 'textinput',
id: 'cursor',
label: 'Cursor Character',
width: 6,
default: '|',
regex: '/^.$/',
},
]
}
/**
* Makes a regular expression from a string
* @param {string} string String representating the regular expression including slashes and optional modifiers
* @returns {RegExp}
*/
buildRegex(string) {
const parts = string.match(/^\/(.+)\/([gmiyusvd]?)$/)
if (parts === null) {
return /(?!)/ // if input is not a valid regexp, return valid regexp which never matches
} else {
try {
return new RegExp(parts[1], parts[2])
} catch (error) {
this.log('error', `Cannot compile regular expression from "${string}", ${error.message}`)
return /(?!)/
}
}
}
/**
* Checks if an automatic enter should be done
* @param {*} timer set to truthy value if this check is performed from a timer event
* @returns void
*/
checkEnter(timer) {
// with 'or' any configured automation will enter
if (this.config.criterialogic === 'or') {
if (
(this.config.autotime && timer) ||
(this.config.autolengthraw && this.entry_raw.length >= this.config.enterlengthraw) ||
(this.config.autolengthformatted && this.entry_formatted.length >= this.config.enterlengthformatted) ||
(this.config.autoregex && this.buildRegex(this.config.enterregex).test(this.entry_raw))
) {
this.enter()
return
}
} else if (this.config.criterialogic === 'and') {
// with 'and' any configured but unmet automation will abort
if (this.config.autotime && !timer) {
return
}
if (this.config.autolengthraw && this.entry_raw.length < this.config.enterlengthraw) {
return
}
if (this.config.autolengthformatted && this.entry_formatted.length < this.config.enterlengthformatted) {
return
}
if (this.config.autoregex && !this.buildRegex(this.config.enterregex).test(this.entry_raw)) {
return
}
this.enter()
}
}
/**
* Cancels the timeout if there is one
*/
cancelTimeout() {
if (this.timeout) {
clearTimeout(this.timeout)
this.timeout = undefined
}
}
/**
* Restarts the timer for the timeout
*/
restartTimeout() {
this.cancelTimeout()
this.timeout = setTimeout(this.fireTimeout.bind(this), this.config.timeout * 1000)
}
/**
* Gets called when the timeout runs out
*/
fireTimeout() {
this.checkEnter(true)
}
/**
* Enter data
* Handles all variables needed when data is entered
* @param {'raw'|'formatted'|undefined} copy if unset use the copy preference from configuration, if set copy this
*/
async enter(copy) {
this.cancelTimeout()
if (copy === undefined) copy = this.config.copydata
if (copy === 'raw') {
this.entry_second_last = this.entry_last
this.entry_last = this.entry_raw
} else if (copy === 'formatted') {
this.entry_second_last = this.entry_last
this.entry_last = this.entry_formatted
} else {
this.log('error', 'copy data unknown: ' + copy)
}
this.setVariableValues({
entry_second_last: this.entry_second_last,
entry_last: this.entry_last,
})
this.entrycounter += 1
this.setVariableValues({
entrycounter: this.entrycounter,
})
if (copy !== 'none' && this.config.after === 'clear') {
await this.clearRaw()
}
this.checkFeedbacks('valid')
}
/**
* gets the locale(s) from a string like "some text{locale1}{locale2}" and sets the internal variables to them
* @param {*} str
*/
getlocale(str) {
let from = 'en-US'
let to = 'en-US'
let locale = str.match(
/(\{(zh(?:-\w\w)?|cs(?:-\w\w)?|da(?:-\w\w)?|nl(?:-\w\w)?|en(?:-\w\w)?|fi(?:-\w\w)?|fr(?:-\w\w)?|de(?:-\w\w)?|el(?:-\w\w)?|hu(?:-\w\w)?|is(?:-\w\w)?|id(?:-\w\w)?|it(?:-\w\w)?|ja(?:-\w\w)?|ko(?:-\w\w)?|nb(?:-\w\w)?|pl(?:-\w\w)?|pt(?:-\w\w)?|ru(?:-\w\w)?|sk(?:-\w\w)?|es(?:-\w\w)?|sv(?:-\w\w)?|th(?:-\w\w)?|tr(?:-\w\w)?)\}){1,2}$/i,
)
if (locale === null) {
return {
apendix: '',
from,
to,
}
} else {
let locstr = locale[0]
locstr = locstr.replaceAll('}{', '|')
locstr = locstr.replaceAll(/[{}]/g, '')
let locales = locstr.split('|')
if (locales.length === 1) {
from = locales[0]
to = locales[0]
} else if (locales.length === 2) {
from = locales[0]
to = locales[1]
}
}
return {
apendix: locale[0],
from,
to,
}
}
/**
* Farmats a string according to preference in configuration and returns the formatted result
* @param {string} string the string to format
* @returns {string} the formatted string, if format is invalid it returns the original string
*/
async formatData(string) {
const getEcmaParts = async () => {
const formatstr = await this.parseVariablesInString(this.config.formatecma)
const loc = this.getlocale(formatstr)
return {
format: loc.apendix.length ? formatstr.slice(0, -1 * loc.apendix.length) : formatstr,
from: { locale: loc.from },
to: { locale: loc.to },
}
}
let formatted = ''
if (this.config.formattype === 'none') {
formatted = string
} else if (this.config.formattype === 'ecmastring') {
const fmt = await getEcmaParts()
formatted = numfmt.format(fmt.format, string, fmt.to)
} else if (this.config.formattype === 'ecmanumber') {
const fmt = await getEcmaParts()
let value = numfmt.parseNumber(string, fmt.from) ?? { v: '' }
formatted = numfmt.format(fmt.format, value.v, fmt.to)
} else if (this.config.formattype === 'ecmadate') {
const fmt = await getEcmaParts()
let value = numfmt.parseDate(string, fmt.from) ?? { v: '' }
formatted = numfmt.format(fmt.format, value.v, fmt.to)
} else if (this.config.formattype === 'ecmatime') {
const fmt = await getEcmaParts()
let value = numfmt.parseTime(string, fmt.from) ?? { v: '' }
formatted = numfmt.format(fmt.format, value.v, fmt.to)
} else if (this.config.formattype === 'ecmabool') {
const fmt = await getEcmaParts()
let value = numfmt.parseBool(string, fmt.from) ?? { v: false }
formatted = numfmt.format(fmt.format, value.v, fmt.to)
} else if (this.config.formattype === 'ecmaauto') {
const fmt = await getEcmaParts()
let value = numfmt.parseValue(string, fmt.from) ?? { v: '' }
formatted = numfmt.format(fmt.format, value.v, fmt.to)
} else if (this.config.formattype === 'printf') {
let formatstr = await this.parseVariablesInString(this.config.formatprintf)
formatted = format(formatstr, string)
} else if (this.config.formattype === 'regex') {
let formatstr = await this.parseVariablesInString(this.config.formatregex)
let formatregex = formatstr.match(/^\/(.+)(?<!\\)\/(.*)\/([gmiyusvd]?)$/)
if (Array.isArray(formatregex)) {
try {
formatted = string.replace(new RegExp(formatregex[1], formatregex[3]), formatregex[2].replaceAll('\\/', '/'))
} catch (error) {
formatted = string
this.log('error', `Regex formatting failed: ${error.message}`)
}
} else {
formatted = string
this.log('error', `Regex formatting failed: input is no valid regular expression`)
}
} else {
formatted = string
}
return formatted
}
/**
* Clears the data in entry_raw and updates variables
*/
async clearRaw() {
this.entry_raw = ''
this.entry_cursor = this.config.cursor
this.entry_cursor_position = 0
this.entry_raw_length = 0
this.entry_formatted = await this.formatData(this.entry_raw)
this.setVariableValues({
entry_raw: this.entry_raw,
entry_cursor: this.entry_cursor,
entry_cursor_position: this.entry_cursor_position,
entry_raw_length: this.entry_raw_length,
entry_formatted: this.entry_formatted,
})
}
/**
* Releases a modifier
* @param {number} modifier which modifier to release
*/
releaseModifier(modifier) {
this.modifier[modifier].controls.clear()
this.modifier[modifier].effective = false
this.modifier[modifier].onetime = false
}
/**
* Update the action definitions to core
*/
updateActions() {
UpdateActions(this)
}
/**
* Update the feedback definitions to core
*/
updateFeedbacks() {
UpdateFeedbacks(this)
}
/**
* Update the variable definitions to core
*/
updateVariableDefinitions() {
UpdateVariableDefinitions(this)
}
/**
* Update the preset definitions to core
*/
updatePresetDefinitions() {
UpdatePresetDefinitions(this)
}
}
runEntrypoint(DataEntryInstance, UpgradeScripts)