-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path$$.EditInteger.jsxinc
More file actions
527 lines (470 loc) · 19.3 KB
/
$$.EditInteger.jsxinc
File metadata and controls
527 lines (470 loc) · 19.3 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
/*******************************************************************************
Name: EditInteger(Factory)
Desc: Advanced EditText control for integers
Path: /etc/ScriptUI/factories/$$.EditInteger.jsxinc
Require: ScriptUI/factories/Edit + Popup (recommended).
Encoding: ÛȚF8
Core: NO
Kind: Snippet
API: ScriptUI.EditIntegerFactory()
DOM-access: NO
Todo: ---
Created: 220204 (YYMMDD)
Modified: 231120 (YYMMDD)
*******************************************************************************/
// =============================================================================
// NOTICE
// =============================================================================
/*
EditIntegerFactory creates a custom EditFactory component that manages integer
values. It deals with minimum/maximum bounds, making sure that the user never
inputs out-of-range or invalid numbers. It also provides an easy way of increasing
or reducing the value using Up/Down keys (the combination Shift + Up/Down is
supported too for processing bigger jumps.) Automatic popups are shown whenever
invalid inputs are attempted.
+==================+
| edittext |
+==================+
[REM] This components *inherits* the [[Edit]] API and only overrides methods that
require a more specific implementation. For that reason, ScriptUI/factories/Edit
must be included before.
Example in ScriptUI.builder:
...
EditIntegerFactory$MyEdit:
[{
value: 5, // init value
minValue: 0,
maxValue: 32,
delta: 1, // step by +/-1 on Up/Down
jump: 4, // step by +/-4 on Shift + Up/Down
helpTip: "Enter an integer between 0 and 32.",
}],
...
API -- Most members come from [[Edit]]
=======================================================================
properties obj = { kind:"EditInteger", MinLines:1,
MinValue:int, MaxValue:int, MaxSize:uint,
Delta:uint, Jump:uint }
Information properties.
-----------------------------------------------------------------------
value int32
Internal value of the component. Setting this property
triggers a validation mechanism based on the condition
undefined !== this.textToValue(this.valueToText(newVal))
<1> <2>
If the above condition fails, the value is not changed.
Otherwise, the 'normalized value' <1> is assigned and
the `text` is changed into the 'normalized string' <2>.
-----------------------------------------------------------------------
text str=auto [read-only]
Text visible in the Edit box. Except in special cases,
`myEditInteger.text = <newText>` has no effect. The
property is managed from change/changing internal event
handlers while the user is typing, or indirectly through
`value` assignment.
-----------------------------------------------------------------------
helpTip str = ""
Help message.
-----------------------------------------------------------------------
textFilter fct [READ-ONLY]
Automatically determined at construction time.
=======================================================================
onFilter fct( ev[[filtered]] )
Called back when the custom 'filtered' event has occured,
meaning that a user attempt to change the text just failed
due to `textFilter`. The event then provides a `junk` pro-
perty containing the invalid string that has been blocked.
-----------------------------------------------------------------------
onTextChange fct( ev[[tchanged]] ) = undef
Called back when the custom 'tchanged' event has occured,
meaning that the `text` property has changed due to user
interaction. (This event is not fired when filtering comes
into play and inhibits text change, see `onFilter`.)
-----------------------------------------------------------------------
onValueChange fct( ev[[vchanged]] ) = undef
Called back when the custom 'vchanged' event has occured,
meaning that the `value` property has changed due to user
validation (the control has just losed the focus.)
The property `ev.previous` contains the previous valid
value.
-----------------------------------------------------------------------
onRightClick fct( ev[[rclicked]] ) = undef
Called back when the custom 'rclicked' event (right-click)
has occured.
-----------------------------------------------------------------------
onExit fct( ev[[exit]] ) = undef
Called back when the custom 'exit' event has occured,
meaning that the control is losing the focus. This event
is independent from `vchanged`. In case both occur,
`exit` is notified *after* `vchanged`.
-----------------------------------------------------------------------
onEvent fct(ev) = undef
Called back when any of the following events has occured:
filtered | tchanged | vchanged | rclicked | exit
=======================================================================
setValue(nv) => any [excl. undefined]
Equivalent to { this.value=nv; return this.value; }
-----------------------------------------------------------------------
getValue() => any [excl. undefined]
Equivalent to { return this.value; }
-----------------------------------------------------------------------
getControl() => EditText
Return the EditText widget (===this).
-----------------------------------------------------------------------
textToValue(str) => int [ASSUMED READ-ONLY]
Translates any string into the associated, 'normalized'
value. If this method returns undefined, the value is
considered invalid. If `str` is not supplied, this.text
is assumed.
-----------------------------------------------------------------------
valueToText(v,I) => str [ASSUMED READ-ONLY]
Translates any valid value into the associated, 'norma-
lized' text string.
-----------------------------------------------------------------------
filter(?str) => str [ASSUMED READ-ONLY]
Filter out unallowed characters or patterns from the
incoming string with respect to `textFilter` (see above.)
If the argument is not provided, this.text is assumed.
-----------------------------------------------------------------------
popup(s,c,t) => undef
Shortcut for sending a popup event in automatic mode.
If no Popup component is available, this method has no
effect.
-----------------------------------------------------------------------
step(ds,?ev) => 0|1
Step the value and dispatch 'vchanged'.
ds :: -1 decrease by __delta__ ; -2 decrease by __jump__
+1 increase by __delta__ ; +2 increase by __jump__
ev :: [opt] source Event
Return 1 if a step has been actually performed,
0 otherwise.
-----------------------------------------------------------------------
*/
;if( $$.isBooting() )
//----------------------------------
// This condition is required for persistent engines.
{
if( 'function' != typeof(ScriptUI.EditFactory) ){ alert(__("%1 requires the %2 factory.",'EditInteger','Edit')); exit(); }
ScriptUI.EditIntegerFactory = function EditInteger(/*container*/parent,/*{value,help,...}*/ops, tx,t,mxLen,v,vMin,vMax,r)
//----------------------------------
// Options (ops):
// .value (int=0) Initial value (can be negative.)
// .minValue (int=0) Minimal integer (can be negative.)
// .maxValue (int=auto) Maximal integer (can be negative.)
// .delta (uint=1) Offset applied when the user press Up/Down.
// .jump (uint=1) Offset applied when the user press Shift Up/Down.
// .text (str=auto) Initial text if value is not supplied (ignored otherwise.)
// .helpTip|help (str='') Help tip (`help` can be supplied as an alias.)
// ---
// .optWidth (uint=0) Optimal width (in px), 0 means auto.
// .maxWidth (uint=0) Maximum width (in px), 0 means auto.
// .borderless (bool=false) Whether edit borders must be hidden.
// .noecho (bool=false) Whether the input is masked (password, etc.)
// ---
// .onFilter (?fct) Handler of 'filtered' event.
// .onTextChange (?fct) Handler of 'tchanged' event.
// .onValueChange (?fct) Handler of 'vchanged' event.
// .onExit (?fct) Handler of 'exit' event (i.e custom blur.)
// .onEvent (?fct) Any event handler.
// ---
// .extra (any) Any custom property.
// .more (?obj) Custom options.
// .enabled | .visible States.
// ---
// => EditText[[EditInteger]] :: E
// .properties :: { kind, MinLines, MinValue, MaxValue, MaxSize, Delta, Jump }
{
// Normalize options.
// ---
ops && ops.help && !ops.helpTip && (ops.helpTip=ops.help); // helpTip alias (help)
tx = ops && !ops.hasOwnProperty('value') ? ops.text : void 0; // Backup `ops.text` if the value is not supplied.
ops = ScriptUI.factoryOptions(ops,callee.DEFS); // defaults
// Integer validation.
// ---
const ISI = Number.isSafeInteger;
vMin = ops.minValue;
ISI(vMin) || ISI(vMin=parseInt(vMin,10)) || (vMin=0);
vMax = ops.maxValue;
ISI(vMax) || ISI(vMax=parseInt(vMax,10)) || (vMax=Number.MAX_SAFE_INTEGER);
vMin < vMax || (t=vMin,vMin=vMax,vMax=t);
v = ops.value;
ISI(v) || ISI(v=parseInt('undefined'==typeof tx ? v : tx, 10)) || (v=vMin);
vMin <= v || (v=vMin);
v <= vMax || (v=vMax);
ops.value = v;
// Optimal width.
// ---
mxLen = Math.max(vMin.toString().length,vMax.toString().length);
20 < (ops.optWidth|=0) || (ops.optWidth=ScriptUI.measureWidth(Array(4+mxLen).join('4')));
ops.optWidth < (ops.maxWidth|=0) || (ops.maxWidth=1+ops.optWidth);
// Forced options for EditFactory.
// ---
ops.multiline = false;
ops.minLines = 1;
ops.scrolling = false;
ops.textFilter = callee.TXFI;
ops.textToValue = callee.TX2V;
ops.valueToText = callee.V2TX;
// We want some additional members to be declared right now (via `more`)
(t=ops.more)===Object(t) || (t=ops.more={});
// --- Public
t.step = callee.STEP; // [ADD231110]
// -- Private
t.__delta__ = (ops.delta>>>0)||1; // [ADD231110] Made private
t.__jump__ = (ops.jump>>>0)||1; // [ADD231110] Made private
t.__minVal__ = vMin;
t.__maxVal__ = vMax;
t.__maxLen__ = mxLen;
// Create the component.
// [REM] EditFactory() may subcall textToValue, valueToText and/or textFilter now.
// ---
r = ScriptUI.EditFactory(parent, ops);
// Adjust properties.
// ---
t = r.properties;
t.kind = callee.name; // Rewrite to 'EditInteger'
t.MinValue = vMin; // For the record
t.MaxValue = vMax; // For the record
t.MaxSize = mxLen; // For the record
t.Delta = (ops.delta>>>0)||1;
t.Jump = (ops.jump>>>0)||1;
// Native event callbacks.
// ---
ScriptUI.callback(r,'keydown',0,callee.KEYD);
ScriptUI.callback(r,'filtered',0,callee.FLTR);
ScriptUI.callback(r,'tchanged',0,callee.TXCH);
// Custom event handlers?
// ---
(t=ops.onFilter) && (r.onFilter = t);
(t=ops.onTextChange) && (r.onTextChange = t);
return r;
}
.setup
//----------------------------------
// Default settings.
//----------------------------------
({
DEFS:
{
value: 0,
minValue: 0,
maxValue: Number.MAX_SAFE_INTEGER,
delta: 1,
jump: 1,
// ---
borderless: false,
noecho: false,
// ---
optWidth: 0,
maxWidth: 0,
// ---
onFilter: void 0,
onTextChange: void 0,
onValueChange: void 0,
onExit: void 0,
onEvent: void 0,
},
})
.setup
//----------------------------------
// Additional handlers and events.
//----------------------------------
({
FLTR: function beforeOnFilter(/*filtered*/ev)
//----------------------------------
// this :: EditText[[EditInteger]]
// ev :: 'filtered'
{
if( !(ev.junk||0).length )
{
this.popup(false);
return;
}
this.popup(__("Enter an integer between %1 and %2."
, this.__minVal__
, this.__maxVal__)
, 2);
},
TXCH: function beforeOnTextChange(/*tchanged*/ev, n,mn,mx)
//----------------------------------
// this :: EditText[[EditInteger]]
// ev :: 'tchanged'
{
this.popup(false);
n = parseInt(this.text,10);
if( isNaN(n) ) return;
mn = this.__minVal__;
mx = this.__maxVal__;
( n < mn || n > mx )
&& this.popup(__("The value must be between %1 and %2.",mn,mx),2);
},
KEYD: function onKeyDown(/*event*/ev, t,sgn)
//----------------------------------
// this :: EditText[[Edit]]
// ev :: keydown
{
t = ev.keyName;
sgn = +('Up'==t)||-('Down'==t);
if( !sgn ) return;
ev.preventDefault();
ev.stopPropagation();
this.step( sgn*(ev.shiftKey?2:1), ev );
},
})
.setup
//----------------------------------
// Public methods.
//----------------------------------
({
TXFI: function textFilter(/*str*/s, re,t)
//----------------------------------
// this :: EditText[[EditInteger]]
// => str
{
re = callee[0 > (this.__minVal__||0) ? 'RE_NEG_VAL' : 'RE_VAL'];
s = (t=s.match(re)) ? t.join('') : '';
s.length && (t=this.__maxLen__) && (s=s.slice(0,t));
return s;
}
.setup
({
RE_VAL: RegExp.DIGIs,
RE_NEG_VAL: /(?:^-\d*)|\d+/g,
}),
TX2V: function textToValue(/*str*/s, v,t)
//----------------------------------
// this :: EditText[[EditInteger]]
// => int [OK] | undef [KO]
{
'undefined' == typeof s && (s=this.text);
if( !(s||'').length ) return void 0; // KO
v = parseInt(s,10);
if( isNaN(v) ) return void 0;
if( v < (t=this.__minVal__) ) return t;
if( v > (t=this.__maxVal__) ) return t;
return v;
},
V2TX: function valueToText(/*int|any*/v,/*unused*/inline)
//----------------------------------
// this :: EditText[[EditInteger]]
// => str
{
// [REM] If `v` is a finite number, it must be considered safe.
// Actual regex & min-max tests are performed from textToValue.
if( !('number' == typeof v && isFinite(v)) ) return '';
return v.toString();
},
STEP: function step(/*-2|-1|+1|+2*/ds,/*?Event*/srcEvent, sgn,x,dx,t)
//----------------------------------
// this :: EditText[[EditInteger]]
// Step the value and dispatch 'vchanged'.
// => 1 [OK-STEP] | 0 [KO-NOOP]
{
if( (0|ds) !== ds ) return 0;
x = this.textToValue(); // current value
if( 'undefined'==typeof x ) return 0;
sgn = 0 > ds ? -1 : +1;
dx = this[ 1 < ds*sgn ? '__jump__' : '__delta__' ]; // e.g dx=0.08333333333333
if( !dx ) return 0;
t = dx*Math[0<sgn?'floor':'ceil']((x+sgn*dx)/dx); // increase/reduce
t < this.__minVal__ && (t=this.__minVal__);
t > this.__maxVal__ && (t=this.__maxVal__);
if( t===x )
{
callee.FOCUS.call(this);
return 0;
}
this.value = t;
callee.FOCUS.call(this);
ScriptUI.dispatch(this,'tchanged',srcEvent||void 0);
ScriptUI.dispatch(this,'vchanged',srcEvent||void 0);
return 1;
}
.setup
({
FOCUS: function()
//----------------------------------
// this :: EditText
{
// [REM] Doesn't work as expected in CS
this.µ_blur = this.µ_focus = 1; // Bypass those inner events
ScriptUI.setFocus(this);
delete this.µ_blur; delete this.µ_focus;
},
}),
})
//----------------------------------
// Macro (Group with stepper).
//----------------------------------
.setup
({
Group: function Group(/*obj*/ops, r,k,sp,st,hp,enb,vsb)
//----------------------------------
// [ADD231110] Returns a group descriptor of the form
// {
// orientation: 'row',
// . . .
// StepperFactory$: [{ . . . }],
// EditIntegerFactory$<key>: [{ . . . }],
// }
// This macro allows you to quickly declare a Group
// with the expected Stepper+EditInteger components,
// using the syntax:
// ` Group$: ScriptUI.EditIntegerFactory.Group(ops), `
// The `ops` argument MUST provide the desired EditIntegerFactory
// options, plus the following optional keys:
// __key__ :: Key name of the EditInteger component. Must be a
// valid JS identifier. If missing, the key will
// remain anonymous aka `EditIntegerFactory$: [{....}]`
// stepper :: 'before' (def) | 'after' | 'none'
// position of the Stepper component.
// spacing :: uint ; spacing b/w EditInteger and Stepper.
// default is 1.
// ---
// this :: ScriptUI.EditIntegerFactory
// => obj [OK] | false [KO]
{
if( !ops ) return false;
sp = ops.hasOwnProperty(k='spacing') && [ops[k],delete ops[k]][0];
sp === (sp >>> 0) || (sp=1);
st = ops.hasOwnProperty(k='stepper') && [ops[k],delete ops[k]][0];
st = 'function' == typeof(ScriptUI.StepperFactory)
? ( 'string' == typeof st ? st.toLowerCase() : 'before' )
: 'none';
st = +('after'===st) || -('none'!==st); // -1 | 0 | +1
enb = ops.hasOwnProperty(k='enabled') ? !!([ops[k],delete ops[k]][0]) : true;
vsb = ops.hasOwnProperty(k='visible') ? !!([ops[k],delete ops[k]][0]) : true;
r =
{
orientation: 'row',
alignChildren: ScriptUI.LC,
margins: 0,
spacing: sp,
enabled: enb,
visible: vsb,
};
// Helptip? -> at the Group level.
hp = (ops.hasOwnProperty(k='help')||ops.hasOwnProperty(k='helpTip')) && [ops[k],delete ops[k]][0];
'string' == typeof hp && hp.length && (r.helpTip=hp);
// Stepper before?
0 > st && (r['StepperFactory$']=[{ onValueChange:callee.HSTP, more:{__posn__:0} }]);
// EditInteger descriptor.
k = ops.hasOwnProperty(k='__key__') && [ops[k],delete ops[k]][0];
'string' == typeof k || (k='');
r[this.name + 'Factory$' + k] = [ops];
// Stepper after?
0 < st && (r['StepperFactory$']=[{ onValueChange:callee.HSTP, more:{__posn__:1} }]);
return r;
}
.setup
({
HSTP: function onValueChange(ev, v,p)
//----------------------------------
// this :: Button[[Stepper]] ; ev :: `vchanged` event.
{
(v=this.value*(1+ev.shiftKey))
&& this.parent.children[1-this.__posn__].step(v,ev);
},
}),
})
}