forked from indiscripts/IdExtenso
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path$$.CheckList.jsxinc
1242 lines (1109 loc) · 43 KB
/
$$.CheckList.jsxinc
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
Name: CheckList(Factory)
Desc: Listbox representing hierarchical, checkable items.
Path: /etc/ScriptUI/factories/$$.CheckList.jsxinc
Require: ScriptUI/factories ; ScriptUI/events ; ScriptUI/layout
Encoding: ÛȚF8
Core: NO
Kind: Snippet
API: ScriptUI.CheckListFactory()
DOM-access: NO
Todo: ---
Created: 201231 (YYMMDD)
Modified: 230311 (YYMMDD)
*******************************************************************************/
// =============================================================================
// NOTICE
// =============================================================================
/*
CheckListFactory provides a customized Listbox representing a tree of checkable
items. The user can quickly select/deselect individual items as well as entire
branches. Checks have three possible visual states:
◼ (U+25FC) The item or branch is fully selected.
◻ (U+25FB) The item or branch is fully unselected.
⬓ (U+2B13) The branch is partially selected.
[ADD211207] In addition, some *terminal* nodes can be declared
'locked' and have then a special state:
※ (U+203B) This item is locked, meaning that its
state cannot be unchecked.
+----------------------+
¦ +==================+ ¦
¦ |-⬓ BranchA--------| ¦
¦ |---◼ ItemA1-------| ¦
¦ |---⬓ BranchAA-----| ¦
¦ |-----◻ ItemAA1----| ¦
¦ |-----◼ ItemAA2----| ¦
¦ |-◼ BranchB--------| ¦
¦ |---※ ItemB1---<---|-¦---- locked node
¦ |---◼ ItemB2-------| ¦
¦ +==================+ ¦
+----------------------+
[REM] The ScriptUI/layout and /events extensions SHOULD be included.
Example in ScriptUI.builder:
CheckListFactory$MyCheckList:
[{
data: ["+ Adobe", "++ InDesign","-- Illustrator","++ Photoshop",
"+ Other", "++ IndyFont", "-- Wordalizer"],
help: "This is a help message.", // help tip.
maxLines: 15, // Number of rows to display
}],
The `data` (alias `value`) parameter can be seen as a tree:
+ Adobe // 1st branch (can use '+ ' or '- ' indifferently)
++ InDesign // checked node
-- Illustrator // unchecked node
++ Photoshop // checked node
+ Other // 2nd branch (can use '+ ' or '- ' indifferently)
++ IndyFont // checked node
-- Wordalizer // unchecked node
etc // Subbranches can be declared at any level
[REM] The `+` or `-` sequences MUST be followed by a space.
[ADD211206] Use `#` instead of `+` to specify a LOCKED node.
Important: Locked items cannot have children, they must be terminal nodes
in the tree. Also, do not declare branches entirely formed of locked items.
The point of using locked items is to visually inform the user that some
elements are required in a branch *beside* other items that s/he can select
or deselect. Hence the current implementation does not support behaviors
that would imply a "locked branch."
API
=======================================================================
properties obj = { kind: "CheckList", RootNode: str,
MinLines:uint>0, MaxLines:uint>0 }
Information properties.
-----------------------------------------------------------------------
helpTip str = ""
Help message (getter and setter).
-----------------------------------------------------------------------
length uint [READ-ONLY]
Total number of items in the list (incl. branches,
checked or unchecked elements.) Use `countNodes(bool)`
to get the number of terminal nodes.
=======================================================================
onValueChange fct( ev[[vchanged]] ) = undef
Called back when the custom 'vchanged' event has occured,
indicating that the check state of some item(s) has changed.
[REM] The 'vchanged' event usually reflects a click.
The extra property `itemIndex` is added to this event:
- uint >=0 -> clicked item index
- true -> select all
- false -> unselect all
-----------------------------------------------------------------------
onRightClick fct( ev[[rclicked]] ) = undef
Called back when the custom 'rclicked' event (right-click)
has occured in the CheckList area.
-----------------------------------------------------------------------
onEvent fct(ev) = undef
Called back when any of the following events has occured:
vchanged | rclicked
=======================================================================
setValue(nv) => seq
Reset the checklist with new items/states and return
this.getValue().
`nv` :: str[] | seq
Array of branches and nodes with +/-/# prefixes, or
equivalent <X1>-separated strings (see getValue.)
-----------------------------------------------------------------------
getValue() => seq
Return the FULL item/state sequence in the form
"<state> <name><X1><state> <name><X1>..."
<state> being either `-`, `--`, `---`, etc
or `+`, `++`, `+++`, etc
or `#`, `##`, `###`, etc
-----------------------------------------------------------------------
getString(?CK,?PM) => seq
(a1) If CK *undefined*, return this.getValue() [CHG211212]
(a2) If CK is false or 0, return all branch and node
names as <X1> seq, e.g "A<X1>nodeA1<X1>nodeA2<X1>B..."
(without state prefixes.)
(b) If CK is truthy, return only the *checked terminal*
nodes as a <X1> seq, e.g "nodeA3<X1>nodeB7<X1>..."
If PM::'brackets'|'slashed'|'x2' is supplied in case (a) or
(b), format each element of the sequence in full path mode:
'brackets' -> "[parent] [parent] ... <nodeOrParent>"
ending in `[xyz]` form if elem is a parent
'slashed' -> "parent/parent/.../<nodeOrParent>"
ending in `xyz/` form if elem is a parent.
'x2' -> "parent\x02parent\x02...\x02<nodeOrParent>"
ending in `xyz\x02` form if elem is a parent.
-----------------------------------------------------------------------
getControl() => Listbox
Return the inner listbox.
-----------------------------------------------------------------------
notify(?idx) => undef
Notify a `vchanged` event.
idx (false|true|uint) itemIndex property.
-----------------------------------------------------------------------
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.
-----------------------------------------------------------------------
getItems() => ListItem[]& (actual type is Collection)
Get the current `items` collection.
-----------------------------------------------------------------------
getItemAt(idx) => ListItem&|false
Get the ListItem at index idx.
-----------------------------------------------------------------------
getData() => str[{}]&
Get the *internal* rich array of strings, structured
as follows:
index => <itemName> (without state prefix)
$index => CHR(state) + CHR(depth) + CHR(1+parentIdx)
where state :: 0|1|2|3 and depth :: 0|1|2|3|...
[ADD211206] The state 3 represents a locked node.
=======================================================================
preCheck(CN,PM) => uint [ADD220115]
Pre-check a set of terminal nodes. This method is
useful when you need to rebuild the previous state
of a CheckList from a backup that only provides the
terminal nodes that were selected -- as typically
returned by `this.getString(true)`.
CN (str[]|seq) Array or <X1>-sequence of paths, each
path being formatted in brackets, slashed, or x2
form (see getString.)
PM (str) One of 'brackets'|'slashed'|'x2'. If not
supplied, the function tries to guess the format
based on CN strings.
-----------------------------------------------------------------------
countNodes(ALL_NODES) => uint
Return the number of *terminal nodes* presently checked
(including locked nodes.)
If ALL_NODES is truthy, return the number of terminal
nodes whatever their state.
-----------------------------------------------------------------------
checkAll() => uint
Check all terminal nodes and return countNodes().
-----------------------------------------------------------------------
uncheckAll() => uint
Uncheck all terminal nodes (excl. locked nodes)
and return the number of locked nodes.
-----------------------------------------------------------------------
matches(?req) => uint[]
Return the array of item indices that match `req`
(disregarding check prefixes.) `req` can be:
- null|undef|-1 -> empty array
- uint|ListItem|str -> singleton array, or empty
- (uint|ListItem|str)[] -> array of corresponding indices
- RegExp -> regular expression on `text`.
[REM] If exact strings are searched using a `req` of
type string, the 1st match is returned.
-----------------------------------------------------------------------
revealItem(what) => undef
Make an item visible. If `what` is a string, it is
searched disregarding check prefix.
(Consistent CS/CC behavior.)
=======================================================================
*/
;if( $$.isBooting() )
//----------------------------------
// This condition is required for persistent engines.
{
ScriptUI.CheckListFactory = function CheckList(/*container*/parent,/*{value,help...}*/ops, q,r,z)
//----------------------------------
// Options (ops):
// .value (seq|str[]) Strings of the form `<state> <name>`, where <state> is
// (or .data) either '-', '--', '---' etc or '+', '++', '+++' or
// '#', '##', '###' etc
// `-` means NOT-CHECKED ; `+` means CHECKED ;
// `#` means LOCKED [211206]
// E.g ["+ item1","-- subitem11","- item2","# item3",...]
// Can be supplied as a <X1> sequence as well.
// `data` is an alias of `value`
// .root (str='') Opt. append a root node. [220115]
// .helpTip (str='') Help tip (`help` can be supplied as an alias.)
// ---
// .optWidth (uint=200) Optimal width (in px.)
// .minLines (uint=1) Minimal number of lines (>=1)
// .maxLines (uint=0) Maximal number of lines, 0 means <auto>
// <auto> takes max(minLines,data.length||5)
// .maxWidth (uint=400) Maximum width (in px.)
// .maxHeight (uint=600) Maximum height (in px.)
// .margins (uint=0) Margins around the list control.
// ---
// .onValueChange (?fct) 'vchanged' handler.
// .onRightClick (?fct) 'rclicked' handler.
// .onEvent (?fct) Any event handler.
// ---
// .enabled | .visible States.
// .more (?obj) Custom options.
// ---
// => Group[[CheckList]] :: G( L|D )
// .properties :: { kind, MinLines, MaxLines }
{
// Normalize options.
// ---
ops && ops.help && !ops.helpTip && (ops.helpTip=ops.help); // helpTip alias (help)
ops = ScriptUI.factoryOptions(ops,callee.DEFS); // defaults
q = callee.FRMT(ops.hasOwnProperty('value') ? ops.value : ops.data, ops.root);
// Absolute minimal is 1 ; absolute maximal is 50.
// If the list is originally empty and has no definite maxLines, use max(min,5).
// ---
const ABS_MAX = 50;
const EMP_MAX = 5;
z = q.length;
ABS_MAX < (ops.minLines=ops.minLines>>>0||1) && (ops.minLines=ABS_MAX); // min :: [1..50]
ABS_MAX < (ops.maxLines=ops.maxLines>>>0||z||EMP_MAX) && (ops.maxLines=ABS_MAX); // max :: [1..50]
ops.maxLines < ops.minLines && (ops.maxLines=ops.minLines); // min <= max
z < ops.minLines ? (z=ops.minLines) : (z > ops.maxLines && z=ops.maxLines); // Final number of lines.
r =
{
margins: ops.hasOwnProperty('margins') ? ops.margins : 0,
orientation: 'stack', // single control
// --- Watched.
helpTip: ops.helpTip||'',
onValueChange: void 0, // pending
onRightClick: void 0, // pending
onEvent: void 0, // pending
// --- Inner events and private.
_layout: 'function' == typeof ScriptUI.layoutDeclare && callee.HLAY,
__kbStrings__: callee.KBST,
__updateChecks__: callee.UPDT,
__toggle__: callee.TOGL,
__clear__: callee.CLEA,
// --- Regular public methods.
popup: ScriptUI.POPU, // noop if Popup unavailable.
getControl: callee.CTRL,
getItems: callee.ITMS,
getItemAt: callee.GETI,
getData: callee.DATA,
notify: callee.NTFY,
// ---
setValue: callee.SETV,
getValue: callee.GETV,
getString: callee.GETS,
// --- Special public methods
preCheck: callee.PCHK,
countNodes: callee.COUN,
matches: callee.MTCH,
revealItem: callee.RVLI,
checkAll: callee.CKAL,
uncheckAll: callee.UNAL,
List$1:
{
properties: { items:q, multiselect:false },
alignment: ScriptUI.CT,
optimalSize:
{
width: ops.optWidth,
height: callee.OPTH(z),
},
maximumSize:
{
width: ops.maxWidth,
height: ops.maxHeight,
},
selection: null,
// --- Inner events.
_change_mousedown_keydown: callee.HINN, // Inhibits select on change; manage right-click; manage keyevents.
_blur: callee.HBLU_FIX, // Blur fixer on CC.
},
};
r = ScriptUI.builder
(
ScriptUI.moreOptions(r, ops.more), // [ADD220807]
parent.add( 'group', void 0, callee.CREA(ops) )
);
r.length = r.getControl().items.length;
r.__updateChecks__();
// Watcher.
// ---
ScriptUI.setWatcher
(
r,
['length', 'helpTip', 'onValueChange', 'onRightClick', 'onEvent'],
callee.WTCH,
ops
);
// [ADD210821] States.
// ---
( false===ops.enabled || 0===ops.enabled ) && (r.enabled=false);
( false===ops.visible || 0===ops.visible ) && (r.visible=false);
return r;
}
.setup
//----------------------------------
// Parameters, tools, private.
//----------------------------------
({
DEFS:
{
helpTip: '',
root: '', // [ADD220115]
// ---
optWidth: 200,
minLines: 1,
maxLines: 0,
maxWidth: 400,
maxHeight: 800,
// ---
onValueChange: void 0,
onRightClick: void 0,
onEvent: void 0,
// ---
more: {},
},
CREA: function(/*{}*/ops)
//----------------------------------
// this :: ScriptUI.CheckListFactory
// => new {} ; properties object
{
return {
kind: this.name,
// ---
MinLines: ops.minLines,
MaxLines: ops.maxLines,
RootNode: ops.root,
};
},
OPTH: function(/*uint*/n)
//----------------------------------
// (Optimal-Height.) Get the optimal height of a
// listbox, given the number of rows to display.
{
return callee.INCR + ((n>>>0)||1)*callee.BASE;
}
.setup
({
INCR: $$.inMac ? 1 : ($$.inCS ? 4 : 1),
BASE: $$.inMac ? 20 : ($$.inCS ? 18 : 21),
}),
FRMT: function(/*any|str[]|seq*/tree,/*?str*/root, r,n,re,dp,pi,p,i,s,m,c,v,t,x)
//----------------------------------
// Parse and reformat the array `tree` (whose elements have the
// form `<state> <name>`) into a rich array:
// - idx => name
// - $idx => CHR(state::0|1|2|3) + CHR(depth::0|1|2|3...) + CHR(1+parentIdx)
// `tree`can be supplied as a <X1>-separated sequence as well.
// [ADD211206] Added state value 3 (locked.)
// [ADD220115] Added `root` arg.
// ---
// => new str[{}]
{
(tree && (tree instanceof Array))
|| (tree=String(tree||'').split('\x01'));
// [ADD220115] Optionally append a root node.
// ---
if( 'string'==typeof root && root.length )
{
tree = ['- '.concat(root)].concat(tree);
for( i=tree.length ; --i ; tree[i]='-'.concat(tree[i]) );
}
const CHR = String.fromCharCode;
r = Array(n=tree.length);
for( re=callee.RE_STATE, dp=0, pi=-1, i=-1 ; ++i < n ; r[i]=s )
{
s = tree[i].toString();
t = v = 0; // default (depth,state) == (0,0)
if( m=s.match(re) )
{
m = m[0]; // m :: prefix + ' ' ; e.g "+++ ", "- ", etc
s = s.slice(t=m.length);
0 > (t-=2) && (t=0); // t :: 0|1|2... ; current depth
c = m.charAt(t);
v = 1*('+'==c)||3*('#'==c); // v :: 0|1|3 ; current state, incl. locked [211206]
}
m = i && ((t>dp) - (t<dp)); // -1 | 0 | +1
switch( m )
{
case +1: // Go DOWN by +1 (unless i==0.)
pi = i-1;
++dp;
break;
case -1: // Go UP until dp==t
do{ pi=r['$'+pi].charCodeAt(2)-1 }while( t < --dp );
break;
default: // Same depth.
;
}
// Update parents?
// r['$'+p] = CHR(state_p)+CHR(depth_p)+CHR(1+parent_p_idx)
// ---
for
(
p=pi, x=1&v ; // [CHG211206] positive v can be 1 or 3 (locked)
0 <= p && x != (t=r['$'+p]).charCodeAt(0) ;
(1==m||(x=2)), (r['$'+p]=CHR(x)+t.slice(1)), (p=t.charCodeAt(2)-1)
);
r['$'+i] = CHR(v,dp,1+pi);
}
return r;
}
.setup
({
RE_STATE: /^[+\#-]+ /,
}),
KBST: function __kbStrings__(/*char|undef*/c, t,p,x)
//----------------------------------
// [PRIVATE METH.] Manage keyboard event char through keystring indices.
// Use `undef` to clear up.
// `c`:: [A-Z0-9] or undef
// ---
// this :: Group[[CheckList]]
// => uint [OK] | false [KO]
{
// The key __KB_STR__ (str) must be privately stored
// in the instance.
// ---
const K = '__KB_STR__';
if( 'string' != typeof c || !c.length )
{
delete this[K];
return false;
}
if( (t=this[K]) && t.charCodeAt(0)===c.charCodeAt(0) )
{
p = 1 + t.charCodeAt(1);
t.length <= p && (p=2);
x = t.charCodeAt(p);
this[K] = c + String.fromCharCode(p) + t.slice(2);
}
else
{
(t=String.prototype.unaccent.B2AC) && t.hasOwnProperty(c)
? ( t = '[' + RegExp.escape(c+t[c]) + ']' )
: ( t = RegExp.escape(c) );
t = this.matches(RegExp('^(?' + t + '|[ \\(\\[\\{<"\'/:\\.@>\\}\\]\\)_+-]+' + t + ')', 'i'));
false !== (x = 0 < t.length && t[0])
? ( this[K] = c + '\x02' + String.fromCharCode.apply(0,t) )
: ( delete this[K] );
}
return x;
},
UPDT: function __updateChecks__( q,wg,HID,REA,CK,SP,a,i,t,k)
//----------------------------------
// Refresh the CheckList w/ respect to current states.
// [CHG211206] Manage state value 3 (locked.)
// ---
// this :: Group[[CheckList]]
// => undef
{
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
wg = this.getControl();
HID = !ScriptUI.isHidden(wg);
REA = HID && (this.active||wg.active);
HID && this.hide();
a = wg.items; // Collection of ListItem instances.
for( CK=callee.CHKS, SP=callee.SPCE, i=a.length ; i-- ; )
{
if( 'item' != (t=a[i]).type ) continue; // Shouldn't happen.
k = '$'+i;
if( !q.hasOwnProperty(k) ) continue; // Shouldn't happen.
k = q[k];
t.text = Array(1+k.charCodeAt(1)).join(SP) + CK[k.charCodeAt(0)] + q[i];
}
HID && this.show();
REA && ScriptUI.setFocus(wg);
}
.setup
({
// [CHG220808] Changed LOCKED symbol for better cross-platform rendering. Old: \u23FA
// EMPTY FULL PARTIAL LOCKED
// [ '\u25FB ','\u25FC ', '\u2B13 ', '\u203B '],
CHKS: ScriptUI.NoCharWidth !== ScriptUI.measureWidth('\u2B13')
? [ '\u25FB ','\u25FC ', '\u2B13 ', '\u203B ' ] // Normal glyphs
: [ '[ ] ','[\u2022] ', '[~] ', '[#] '], // [FIX230311] Fallback
SPCE: ' ', // Indent by 3 spaces
}),
TOGL: function __toggle__(/*uint*/idx,/*bool=0*/UPD, q,n,sdp,cc,ns,lv,a,s,p,i,t,x,tt)
//----------------------------------
// Toggle the state of a node or branch at index idx (if possible)
// then update its dependencies accordingly:
// - Toggling a partially checked branch will get it fully checked;
// - Toggling a fully checked branch will get it either fully unchecked
// (if no locked nodes inside it) or partially checked (if locked nodes
// are present, only the free nodes are unchecked.)
// - Locked nodes cannot be unchecked.
// By default, data are just updated internally (without visible
// effect.) Send a truthy `UPD` arg to force refresh.
// [CHG211206] Manage LOCKED nodes.
// ---
// this :: Group[[CheckList]]
// => 1 [OK-CHANGED] | 0 [NOOP]
{
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
n = q.length;
idx >>>= 0; // Item index.
sdp = q['$'+idx]; // sdp :: CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
cc = sdp.charCodeAt(0);
if( 3===cc ) return 0; // Locked -> NOOP.
ns = 1==cc ? '\0' : '\x01'; // ns :: <X0>|<X1> ; new state at index `idx` (unless locked children present.)
// Children.
// ---
for
(
a=[], lv=1+sdp.charCodeAt(1), i=idx ;
++i < n && lv <= (t=q['$'+i]).charCodeAt(1) ;
// [CHG211206] Preserve locked nodes
3==t.charCodeAt(0) ? (a[a.length]=i) : (q['$'+i] = ns + t.slice(1))
);
if( 0===ns.charCodeAt(0) && (i=a.length) ) // ns==='\0' AND locked child(ren) => ns := <X2>
{
while( i-- ) // [FIX211207] Needed to update intermediate parents.
for
(
s=q['$'+a[i]] ;
idx != (p=-1+s.charCodeAt(2)) && 2 != (s=q['$'+p]).charCodeAt(0) ;
q['$'+p] = '\x02'+s.slice(1)
);
ns = '\x02';
}
q['$'+idx] = ns + sdp.slice(1); // Rewrite the target element at idx.
// Parent chain.
// ---
const CHR = String.fromCharCode;
while( idx=sdp.charCodeAt(2) ) // Go up.
{
sdp = q['$'+(--idx)]; // Parent branch data.
lv = 1+sdp.charCodeAt(1); // Max level for children (used for looping.)
for
( // Recalculate state by scanning children:
i=idx, x=ns.charCodeAt(0); // x :: 0|1|2 ; status of the elem we come from.
2!==x && ++i < n && lv <= (tt=(t=q['$'+i]).charCodeAt(1));
tt > lv || x===(t=t.charCodeAt(0)) || (x&t) // x :: 0|1 vs. t.cc :: 0|1|2|3
|| (x=2) // Mismatch -> x := 2
);
if( x===sdp.charCodeAt(0) ) break;
q['$'+idx] = (ns=CHR(x)) + sdp.slice(1);
}
UPD && this.__updateChecks__();
return 1;
},
CLEA: function __clear__( q,a,i,s,p)
//----------------------------------
// [ADD220115] Uncheck all non-locked terminal nodes.
// this :: Group[[CheckList]]
// => undef
{
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
for
(
a=[], i=q.length ; i-- ;
3 == (s=q['$'+i]).charCodeAt(0)
? ( a[a.length]=i ) // Register indices of locked elems
: ( q['$'+i]='\x00'+s.slice(1) )
);
// [ADD211207] Manage the parents of locked nodes.
// ---
for( i=a.length ; i-- ; )
for
(
s=q['$'+a[i]] ;
0 <= (p=-1+s.charCodeAt(2)) && 2 != (s=q['$'+p]).charCodeAt(0) ;
q['$'+p] = '\x02'+s.slice(1)
);
},
})
.setup
//----------------------------------
// Inner events
//----------------------------------
({
HLAY: $$.inCC ?
function onLayout( t,o,w)
//----------------------------------
// Temporarily set <listbox>.columns.preferredWidth[0]
// (this will improve *line selection* in CC.)
// ---
// this :: Group[[List]]
// => undef
{
t = this.getControl();
if( !(o=t.columns) ) return;
w = (t.preferredSize || this.preferredSize || [0])[0];
// [CHG210103] Changed the delta (-10) into -15. This value helps
// inhibit horizontal scrollbar--based on vertical scrollbar width.
// ---
25 < w && ((o.preferredWidths[0]=w-15),(o.preferredWidths[0]=void 0));
}
:
function onLayout( t)
//----------------------------------
// Forcibly set <listbox>.colums.preferredWidths[0] to undef.
// ---
// this :: Group[[List]]
// => undef
{
// Needed in CS6, harmless in CS4/CS5
// ---
(t=this.getControl()) && (t=t.columns) && (t.preferredWidths[0]=void 0);
},
// [FIX210108] In CC, list widgets have an obscure focus/blur
// sequence that may keep 'active' a widget which is losing
// the focus. Forcing this.active to false seems to solve the pb.
// ---
HBLU_FIX: $$.inCC ? function onBlur(){ this.active=false } : void 0,
HINN: function onInnerEvent(/*event*/ev, k,me,item,c,idx,x)
//----------------------------------
// Dispatch or inhibit ListBox events.
// ---
// this :: ListBox
// ev.type :: change | mousedown | keydown
// target :: this
{
k = ev ? ev.type : 'noevent';
me = this.parent;
// Temporary transparent event type.
// [FIX210903] `me` -> `this`
// ---
if( this.hasOwnProperty('µ_'+k) ) return;
switch( k )
{
case 'change':
// Interpret any inner 'change' as a click:
// inhibits the selection and switches the state.
ev.stopPropagation();
if( !(item=this.selection) ) return;
// While unselecting, make sure we don't fire an extra
// change event towards handler(s.)
// ---
this.µ_change = 1;
this.selection=null; // [REM] This fires an extra 'change' event :-(
delete this.µ_change;
// [CHG211207] No need to fire any event if cannot toggle.
me.__toggle__(idx=item.index, 1)
&& ( ev.itemIndex=idx, ScriptUI.dispatch(me,'vchanged',ev) );
break;
case 'mousedown':
if( 2!==ev.button ) break;
// --- Makes CS behave as CC on right-clicking a list.
ev.preventDefault();
ev.stopPropagation();
ScriptUI.dispatch(me,'rclicked',ev);
break;
case 'keydown':
if( 'Escape' == ev.keyName || 'Tab' == ev.keyName ) break; // Preserve regular Esc/Tab events.
ev.preventDefault();
ev.stopPropagation();
if( ev.ctrlKey && 'A' == ev.keyName )
{
ev.altKey ? me.uncheckAll() : me.checkAll();
ScriptUI.dispatch(me,'vchanged',{itemIndex:!ev.altKey}); // itemIndex :: false|true
break;
}
if( !ev.ctrlKey && 'string' == typeof(c=ev.keyName) && 1==c.length )
{
false !== (x=me.__kbStrings__(c)) && me.revealItem(x);
}
// ScriptUI.dispatch(me,'keypress',ev); // could be added?
break;
default:;
}
},
})
.setup
//----------------------------------
// Watcher.
//----------------------------------
({
WTCH: function watcher(/*value*/k,/*any*/ov,/*any*/nv)
//----------------------------------
// this :: Group[[CheckList]]
// k :: length | helpTip |
// onValueChange | onRightClick | onEvent
{
if( this.hasOwnProperty('µ_'+k) ) return nv; // Temporary transparent key.
switch( k )
{
case 'length': // READ-ONLY
nv = ov;
break;
case 'helpTip': // str
nv = String(nv||'');
this.getControl().helpTip = nv;
break;
case 'onRightClick': // fct
ScriptUI.callback(this,'rclicked',ov,nv);
break;
case 'onValueChange': // fct
ScriptUI.callback(this,'vchanged',ov,nv);
break;
case 'onEvent': // fct
ScriptUI.callback(this,['rclicked','vchanged'],ov,nv);
break;
default:;
}
return nv;
},
})
.setup
//----------------------------------
// Public methods.
//----------------------------------
({
CTRL: function getControl(){ return this.children[0] },
DATA: function getData(){ return this.getControl().properties.items },
ITMS: function getItems(){ return this.getControl().items },
GETI: function getItemAt(/*uint*/idx, t){ return idx === idx >>> 0 && x < (t=this.getItems()).length && t[idx] },
NTFY: function notify(/*?uint|true|false*/idx){ ScriptUI.dispatch(this,'vchanged',{itemIndex:idx}) },
GETV: function getValue( q,RN,inc,r,n,i,t,cc)
//----------------------------------
// Return the full item/state sequence in the form
// "<state> <name><X1><state> <name><X1>..."
// <state> being either `-`, `--`, `---`, etc
// or `+`, `++`, `+++`, etc, or `#`, `##`, `###`, etc
// [ADD211206] Support of state value 3 (locked.)
// [CHG220115] Ignore RootNode (if set.)
// ---
// this :: Group[[CheckList]]
// => seq aka <X1>-separated string
{
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
// [CHG220115] Ignore RootNode.
// ---
RN = 0 < (this.properties.RootNode||'').length;
inc = 2-RN; // 2 [NO-ROOT] | 1 [HAS-ROOT]
for
(
r=[], n=q.length, i=-1 ;
++i < n ;
(t=q['$'+i]), r[r.length]=Array(inc+t.charCodeAt(1)).join((cc=t.charCodeAt(0))?(3==cc?'#':'+'):'-')+' '+q[i]
);
RN && r.shift();
return r.join('\x01');
},
SETV: function setValue(/*str[]|seq*/tree, q,n,i,HID,REA,wg)
//----------------------------------
// Reset the checklist with new items/states and return this.getValue().
// tree :: str[] | "str1<X1>str2<X1>..."
// where each elem is in `<state> <name>` form
// <state> being either `-`, `--`, `---`, etc
// or `+`, `++`, `+++`, etc, or `#`, `##`, `###`, etc
// `+` means checked, `-` means non-checked, `#` means locked
// E.g [ "+ item1", "-- subitem11", "- item2", "# item3", ...]
// [REM] The internal getData() structure is updated accordingly.
// This method does not fire `vchanged`.
// ---
// this :: Group[[CheckList]]
// => seq aka <X1>-separated string [see getValue.]
{
tree = ScriptUI.CheckListFactory.FRMT(tree, this.properties.RootNode||'');
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
n = q.length = tree.length;
for( i = n ; i-- ; q[i]=tree[i], q['$'+i]=tree['$'+i] );
// Update listbox.
// ---
this.µ_change = 1;
HID = !ScriptUI.isHidden(wg=this.getControl()); // [FIX211206]
REA = HID && (this.active||wg.active);
HID && this.hide();
// ---
wg.removeAll();
for( i=-1 ; ++i < n ; wg.add('item',q[i]) );
this.µ_length = 1;
this.length = n;
delete this.µ_length;
// ---
HID && this.show();
REA && ScriptUI.setFocus(wg);
delete this.µ_change;
this.__updateChecks__();
return this.getValue();
},
PCHK: function preCheck(/*str[]|seq*/checkedNodes,/*'brackets'|'slashed'|'x2'=auto*/pathMode, q,a,k,t,F,i,RN,p,j)
//----------------------------------
// Given an array (or <X1> sequence) of terminal node paths formatted as
// specified by `pathMode`, check every matched node in the present CheckList
// and uncheck every other nodes. If no match is found, all nodes are unchecked.
// Return the final number of checked nodes.
// E.g myCheckList.preCheck(["someNode1","path/to/node"]);
// => uint
{
this.__clear__();
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
a = (checkedNodes && (checkedNodes instanceof Array))
? checkedNodes.slice()
: String(checkedNodes||'').split('\x01');
if( !a.length ) return this.countNodes();
k = 'string'==typeof pathMode ? pathMode.toUpperCase() : '';
while( 'BRACKETS'!=k && 'SLASHED'!=k && 'X2'!=k )
{
t = a.join('\x01');
if( 0 <= t.indexOf('\x02') ){ k='X2'; break; }
if( 0 <= ('\x01'.concat(t)).indexOf('\x01[') ){ k='BRACKETS'; break; }
k = 'SLASHED';
break;
}
// --> a :: { #name => [path1,path2,...] }
for
(
F=callee[k.slice(0,2)], i=-1 ;
++i < a.length ;
t=F(a[i]), k='#'.concat(t.pop()),
(a[k]||(a[k]=[])).push(t.join('\x02'))
);
RN = +(0 < (this.properties.RootNode||'').length); // 0|1
for( i=-1 ; ++i < q.length ; )
{
k = '#'.concat(q[i]);
if( !a.hasOwnProperty(k) ) continue;
for( j=i, p='' ; RN <= (j=-1+q['$'+j].charCodeAt(2)) ; p='\x02'.concat(q[j],p) );
p.length && (p=p.slice(1));
t = a[k];
for( j=t.length ; j-- && t[j]!==p ; );
0 <= j && (this.__toggle__(i));
}
this.__updateChecks__();
return this.countNodes();
}
.setup
({
X2: function(/*aaa<X2>bbb<X2>...*/path)
//----------------------------------
// => str[]
{
return path.split('\x02');
},
BR: function(/*[aaa][bbb]...*/path, p,m,i,t)
//----------------------------------
// => str[]
{
if( -1 == (p=path.lastIndexOf(']')) ) return [path];
if( !(m=path.match(/\[[^\]]+\]/g)) ) return [path];
for( i=m.length ; i-- ; m[i]=m[i].slice(1,-1) );
0x20===(t=path.slice(1+p)).charCodeAt(0) && (t=t.slice(1));
m[m.length] = t;
return m;
},
SL: function(/*aaa/bbb/...*/path)
//----------------------------------
// => str[]
{
return path.split('/');
},
}),
COUN: function countNodes(/*bool=0*/ALL_NODES, q,z,p,i,t)
//----------------------------------
// Return the number of *terminal* nodes that are now checked.
// If ALL_NODES is truthy, return the number of terminal nodes
// whatever their state.
// [CHG211206] Support of state value 3 (locked.)
// ---
// this :: Group[[CheckList]]
// => uint
{
q = this.getData(); // idx=>name ; $idx=>CHR(state::0|1|2|3) + CHR(depth::0|1|2|3|4...) + CHR(1+parentIdx)
for( z=0, p=-1, i=q.length ; i-- ; (t=q['$'+i]), (i!=p && (ALL_NODES||(1&t.charCodeAt(0))) && ++z), p=-1+t.charCodeAt(2) );
return z;
},
CKAL: function checkAll( q,i,s)
//----------------------------------
// Check all terminal nodes and return this.countNodes().
// [REM] This method does not fire `vchanged`.
// [CHG211206] Support of state value 3 (locked.)