forked from wikimedia-gadgets/twinkle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
morebits.js
6097 lines (5538 loc) · 197 KB
/
morebits.js
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
// <nowiki>
/**
* A library full of lots of goodness for user scripts on MediaWiki wikis, including Wikipedia.
*
* The highlights include:
* - {@link Morebits.wiki.api} - make calls to the MediaWiki API
* - {@link Morebits.wiki.page} - modify pages on the wiki (edit, revert, delete, etc.)
* - {@link Morebits.date} - enhanced date object processing, sort of a light moment.js
* - {@link Morebits.quickForm} - generate quick HTML forms on the fly
* - {@link Morebits.simpleWindow} - a wrapper for jQuery UI Dialog with a custom look and extra features
* - {@link Morebits.status} - a rough-and-ready status message displayer, used by the Morebits.wiki classes
* - {@link Morebits.wikitext} - utilities for dealing with wikitext
* - {@link Morebits.string} - utilities for manipulating strings
* - {@link Morebits.array} - utilities for manipulating arrays
* - {@link Morebits.ip} - utilities to help process IP addresses
*
* Dependencies:
* - The whole thing relies on jQuery. But most wikis should provide this by default.
* - {@link Morebits.quickForm}, {@link Morebits.simpleWindow}, and {@link Morebits.status} rely on the "morebits.css" file for their styling.
* - {@link Morebits.simpleWindow} and {@link Morebits.quickForm} tooltips rely on jQuery UI Dialog (from ResourceLoader module name 'jquery.ui').
* - To create a gadget based on morebits.js, use this syntax in MediaWiki:Gadgets-definition:
* - `*GadgetName[ResourceLoader|dependencies=mediawiki.user,mediawiki.util,mediawiki.Title,jquery.ui]|morebits.js|morebits.css|GadgetName.js`
* - Alternatively, you can configure morebits.js as a hidden gadget in MediaWiki:Gadgets-definition:
* - `*morebits[ResourceLoader|dependencies=mediawiki.user,mediawiki.util,mediawiki.Title,jquery.ui|hidden]|morebits.js|morebits.css`
* and then load ext.gadget.morebits as one of the dependencies for the new gadget.
*
* All the stuff here works on all browsers for which MediaWiki provides JavaScript support.
*
* This library is maintained by the maintainers of Twinkle.
* For queries, suggestions, help, etc., head to [Wikipedia talk:Twinkle on English Wikipedia](http://en.wikipedia.org/wiki/WT:TW).
* The latest development source is available at {@link https://github.com/wikimedia-gadgets/twinkle/blob/master/morebits.js|GitHub}.
*
* @namespace Morebits
*/
(function (window, document, $) { // Wrap entire file with anonymous function
/** @lends Morebits */
const Morebits = {};
window.Morebits = Morebits; // allow global access
/**
* i18n support for strings in Morebits
*/
Morebits.i18n = {
parser: null,
/**
* Set an i18n library to use with Morebits.
* Examples:
* Use jquery-i18n:
* Morebits.i18n.setParser({ get: $.i18n });
* Use banana-i18n or orange-i18n:
* var banana = new Banana('en');
* Morebits.i18n.setParser({ get: banana.i18n });
* @param {Object} parser
*/
setParser: function(parser) {
if (!parser || typeof parser.get !== 'function') {
throw new Error('Morebits.i18n: parser must implement get()');
}
Morebits.i18n.parser = parser;
},
/**
* @private
* @returns {string}
*/
getMessage: function () {
const args = Array.prototype.slice.call(arguments); // array of size `n`
// 1st arg: message name
// 2nd to (n-1)th arg: message parameters
// nth arg: legacy English fallback
const msgName = args[0];
const fallback = args[args.length - 1];
if (!Morebits.i18n.parser) {
return fallback;
}
// i18n libraries are generally invoked with variable number of arguments
// as msg(msgName, ...parameters)
const i18nMessage = Morebits.i18n.parser.get.apply(null, args.slice(0, -1));
// if no i18n message exists, i18n libraries generally give back the message name
if (i18nMessage === msgName) {
return fallback;
}
return i18nMessage;
}
};
// shortcut
const msg = Morebits.i18n.getMessage;
/**
* Wiki-specific configurations for Morebits
*/
Morebits.l10n = {
/**
* Local aliases for "redirect" magic word.
* Check using api.php?action=query&format=json&meta=siteinfo&formatversion=2&siprop=magicwords
*/
redirectTagAliases: ['#REDIRECT'],
/**
* Takes a string as argument and checks if it is a timestamp or not
* If not, it returns null. If yes, it returns an array of integers
* in the format [year, month, date, hour, minute, second]
* which can be passed to Date.UTC()
* @param {string} str
* @returns {number[] | null}
*/
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
const rgx = /(\d{2}):(\d{2}), (\d{1,2}) (\w+) (\d{4}) \(UTC\)/;
const match = rgx.exec(str);
if (!match) {
return null;
}
const month = Morebits.date.localeData.months.indexOf(match[4]);
if (month === -1) {
return null;
}
// ..... year ... month .. date ... hour .... minute
return [match[5], month, match[3], match[1], match[2]];
}
};
/**
* Simple helper function to see what groups a user might belong.
*
* @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc.
* @returns {boolean}
*/
Morebits.userIsInGroup = function (group) {
return mw.config.get('wgUserGroups').indexOf(group) !== -1;
};
/** Hardcodes whether the user is a sysop, used a lot.
*
* @type {boolean}
*/
Morebits.userIsSysop = Morebits.userIsInGroup('sysop');
/**
* Deprecated as of February 2021, use {@link Morebits.ip.sanitizeIPv6}.
*
* @deprecated Use {@link Morebits.ip.sanitizeIPv6}.
* Converts an IPv6 address to the canonical form stored and used by MediaWiki.
* JavaScript translation of the {@link https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/8eb6ac3e84ea3312d391ca96c12c49e3ad0753bb/includes/utils/IP.php#131|`IP::sanitizeIP()`}
* function from the IPUtils library. Addresses are verbose, uppercase,
* normalized, and expanded to 8 words.
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @returns {string}
*/
Morebits.sanitizeIPv6 = function (address) {
console.warn('NOTE: Morebits.sanitizeIPv6 was renamed to Morebits.ip.sanitizeIPv6 in February 2021, please use that instead'); // eslint-disable-line no-console
return Morebits.ip.sanitizeIPv6(address);
};
/**
* Determines whether the current page is a redirect or soft redirect. Fails
* to detect soft redirects on edit, history, etc. pages. Will attempt to
* detect Module:RfD, with the same failure points.
*
* @returns {boolean}
*/
Morebits.isPageRedirect = function() {
return !!(mw.config.get('wgIsRedirect') || document.getElementById('softredirect') || $('.box-RfD').length);
};
/**
* Stores a normalized (underscores converted to spaces) version of the
* `wgPageName` variable.
*
* @type {string}
*/
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' ');
/**
* Create a string for use in regex matching a page name. Accounts for
* leading character's capitalization, underscores as spaces, and special
* characters being escaped. See also {@link Morebits.namespaceRegex}.
*
* @param {string} pageName - Page name without namespace.
* @returns {string} - For a page name `Foo bar`, returns the string `[Ff]oo[_ ]bar`.
*/
Morebits.pageNameRegex = function(pageName) {
if (pageName === '') {
return '';
}
const firstChar = pageName[0],
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
return '[' + mw.Title.phpCharToUpper(firstChar) + firstChar.toLowerCase() + ']' + remainder;
}
return Morebits.string.escapeRegExp(firstChar) + remainder;
};
/**
* Converts string or array of DOM nodes into an HTML fragment.
* Wikilink syntax (`[[...]]`) is transformed into HTML anchor.
* Used in Morebits.quickForm and Morebits.status
* @internal
* @param {string|Node|(string|Node)[]} input
* @returns {DocumentFragment}
*/
Morebits.createHtml = function(input) {
const fragment = document.createDocumentFragment();
if (!input) {
return fragment;
}
if (!Array.isArray(input)) {
input = [ input ];
}
for (let i = 0; i < input.length; ++i) {
if (input[i] instanceof Node) {
fragment.appendChild(input[i]);
} else {
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach((node) => {
fragment.appendChild(node);
});
}
}
return fragment;
};
/**
* Converts wikilinks to HTML anchor tags.
* @param text
* @returns {*}
*/
Morebits.createHtml.renderWikilinks = function (text) {
const ub = new Morebits.unbinder(text);
// Don't convert wikilinks within code tags as they're used for displaying wiki-code
ub.unbind('<code>', '</code>');
ub.content = ub.content.replace(
/\[\[:?(?:([^|\]]+?)\|)?([^\]|]+?)\]\]/g,
(_, target, text) => {
if (!target) {
target = text;
}
return '<a target="_blank" href="' + mw.util.getUrl(target) +
'" title="' + target.replace(/"/g, '"') + '">' + text + '</a>';
});
return ub.rebind();
};
/**
* Create a string for use in regex matching all namespace aliases, regardless
* of the capitalization and underscores/spaces. Doesn't include the optional
* leading `:`, but if there's more than one item, wraps the list in a
* non-capturing group. This means you can do `Morebits.namespaceRegex([4]) +
* ':' + Morebits.pageNameRegex('Twinkle')` to match a full page. Uses
* {@link Morebits.pageNameRegex}.
*
* @param {number[]} namespaces - Array of namespace numbers. Unused/invalid
* namespace numbers are silently discarded.
* @example
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
* Morebits.namespaceRegex([6])
* @returns {string} - Regex-suitable string of all namespace aliases.
*/
Morebits.namespaceRegex = function(namespaces) {
if (!Array.isArray(namespaces)) {
namespaces = [namespaces];
}
let aliases = [], regex;
$.each(mw.config.get('wgNamespaceIds'), (name, number) => {
if (namespaces.indexOf(number) !== -1) {
// Namespaces are completely agnostic as to case,
// and a regex string is more useful/compatible than a RegExp object,
// so we accept any casing for any letter.
aliases.push(name.split('').map((char) => Morebits.pageNameRegex(char)).join(''));
}
});
switch (aliases.length) {
case 0:
regex = '';
break;
case 1:
regex = aliases[0];
break;
default:
regex = '(?:' + aliases.join('|') + ')';
break;
}
return regex;
};
/* **************** Morebits.quickForm **************** */
/**
* Creation of simple and standard forms without much specific coding.
*
* @namespace Morebits.quickForm
* @memberof Morebits
* @class
* @param {event} event - Function to execute when form is submitted.
* @param {string} [eventType=submit] - Type of the event.
*/
Morebits.quickForm = function QuickForm(event, eventType) {
this.root = new Morebits.quickForm.element({ type: 'form', event: event, eventType: eventType });
};
/**
* Renders the HTML output of the quickForm.
*
* @memberof Morebits.quickForm
* @returns {HTMLElement}
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
const ret = this.root.render();
ret.names = {};
return ret;
};
/**
* Append element to the form.
*
* @memberof Morebits.quickForm
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which
* a quickform element is constructed.
* @returns {Morebits.quickForm.element} - Same as what is passed to the function.
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
return this.root.append(data);
};
/**
* Create a new element for the the form.
*
* Index to Morebits.quickForm.element types:
* - Global attributes: id, className, style, tooltip, extra, $data, adminonly
* - `select`: A combo box (aka drop-down).
* - Attributes: name, label, multiple, size, list, event, disabled
* - `option`: An element for a combo box.
* - Attributes: value, label, selected, disabled
* - `optgroup`: A group of "option"s.
* - Attributes: label, list
* - `field`: A fieldset (aka group box).
* - Attributes: name, label, disabled
* - `checkbox`: A checkbox. Must use "list" parameter.
* - Attributes: name, list, event
* - Attributes (within list): name, label, value, checked, disabled, event, subgroup
* - `radio`: A radio button. Must use "list" parameter.
* - Attributes: name, list, event
* - Attributes (within list): name, label, value, checked, disabled, event, subgroup
* - `input`: A text input box.
* - Attributes: name, label, value, size, placeholder, maxlength, disabled, required, readonly, event
* - `number`: A number input box.
* - Attributes: Everything the text `input` has, as well as: min, max, step, list
* - `dyninput`: A set of text boxes with "Remove" buttons and an "Add" button.
* - Attributes: name, label, min, max, inputs, sublabel, value, size, maxlength, event
* - `hidden`: An invisible form field.
* - Attributes: name, value
* - `header`: A level 5 header.
* - Attributes: label
* - `div`: A generic placeholder element or label.
* - Attributes: name, label
* - `submit`: A submit button. Morebits.simpleWindow moves these to the footer of the dialog.
* - Attributes: name, label, disabled
* - `button`: A generic button.
* - Attributes: name, label, disabled, event
* - `textarea`: A big, multi-line text box.
* - Attributes: name, label, value, cols, rows, disabled, required, readonly
* - `fragment`: A DocumentFragment object.
* - No attributes, and no global attributes except adminonly.
* There is some difference on how types handle the `label` attribute:
* - `div`, `select`, `field`, `checkbox`/`radio`, `input`, `textarea`, `header`, and `dyninput` can accept an array of items,
* and the label item(s) can be `Element`s.
* - `option`, `optgroup`, `_dyninput_cell`, `submit`, and `button` accept only a single string.
*
* @memberof Morebits.quickForm
* @class
* @param {object} data - Object representing the quickform element. Should
* specify one of the available types from the index above, as well as any
* relevant and available attributes.
* @example new Morebits.quickForm.element({
* name: 'target',
* type: 'input',
* label: 'Your target:',
* tooltip: 'Enter your target. Required.',
* required: true
* });
*/
Morebits.quickForm.element = function QuickFormElement(data) {
this.data = data;
this.childs = [];
};
/**
* @memberof Morebits.quickForm.element
* @type {number}
*/
Morebits.quickForm.element.id = 0;
/**
* Appends an element to current element.
*
* @memberof Morebits.quickForm.element
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to
* create the quickForm element.
* @returns {Morebits.quickForm.element} The same element passed in.
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
let child;
if (data instanceof Morebits.quickForm.element) {
child = data;
} else {
child = new Morebits.quickForm.element(data);
}
this.childs.push(child);
return child;
};
/**
* Renders the HTML output for the quickForm element. This should be called
* without parameters: `form.render()`.
*
* @memberof Morebits.quickForm.element
* @returns {HTMLElement}
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) {
const currentNode = this.compute(this.data, internal_subgroup_id);
for (let i = 0; i < this.childs.length; ++i) {
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild(this.childs[i].render());
}
return currentNode[0];
};
/** @memberof Morebits.quickForm.element */
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) {
let node;
let childContainer = null;
let label;
const id = (in_id ? in_id + '_' : '') + 'node_' + Morebits.quickForm.element.id++;
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
data.type = 'hidden';
}
let i, current, subnode;
switch (data.type) {
case 'form':
node = document.createElement('form');
node.className = 'quickform';
node.setAttribute('action', 'javascript:void(0);');
if (data.event) {
node.addEventListener(data.eventType || 'submit', data.event, false);
}
break;
case 'fragment':
node = document.createDocumentFragment();
// fragments can't have any attributes, so just return it straight away
return [ node, node ];
// Sometimes Twinkle uses fancy searchable "select" elements. This is powered by the third party library "select2". Activate it by creating a Morebits "select" element, then call `$('select[name=sub_group]').select2({});` or similar towards the end of your main code.
case 'select':
node = document.createElement('div');
node.setAttribute('id', 'div_' + id);
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.setAttribute('for', id);
label.appendChild(Morebits.createHtml(data.label));
label.style.marginRight = '3px';
}
var select = node.appendChild(document.createElement('select'));
if (data.event) {
select.addEventListener('change', data.event, false);
}
if (data.multiple) {
select.setAttribute('multiple', 'multiple');
}
if (data.size) {
select.setAttribute('size', data.size);
}
if (data.disabled) {
select.setAttribute('disabled', 'disabled');
}
select.setAttribute('name', data.name);
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
current = data.list[i];
if (current.list) {
current.type = 'optgroup';
} else {
current.type = 'option';
}
subnode = this.compute(current);
select.appendChild(subnode[0]);
}
}
childContainer = select;
break;
case 'option':
node = document.createElement('option');
node.values = data.value;
node.setAttribute('value', data.value);
if (data.selected) {
node.setAttribute('selected', 'selected');
}
if (data.disabled) {
node.setAttribute('disabled', 'disabled');
}
node.setAttribute('label', data.label);
node.appendChild(document.createTextNode(data.label));
break;
case 'optgroup':
node = document.createElement('optgroup');
node.setAttribute('label', data.label);
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
current = data.list[i];
current.type = 'option'; // must be options here
subnode = this.compute(current);
node.appendChild(subnode[0]);
}
}
break;
case 'field':
node = document.createElement('fieldset');
label = node.appendChild(document.createElement('legend'));
label.appendChild(Morebits.createHtml(data.label));
if (data.name) {
node.setAttribute('name', data.name);
}
if (data.disabled) {
node.setAttribute('disabled', 'disabled');
}
break;
case 'checkbox':
case 'radio':
node = document.createElement('div');
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
const cur_id = id + '_' + i;
current = data.list[i];
var cur_div;
if (current.type === 'header') {
// inline hack
cur_div = node.appendChild(document.createElement('h6'));
cur_div.appendChild(document.createTextNode(current.label));
if (current.tooltip) {
Morebits.quickForm.element.generateTooltip(cur_div, current);
}
continue;
}
cur_div = node.appendChild(document.createElement('div'));
subnode = cur_div.appendChild(document.createElement('input'));
subnode.values = current.value;
subnode.setAttribute('value', current.value);
subnode.setAttribute('type', data.type);
subnode.setAttribute('id', cur_id);
subnode.setAttribute('name', current.name || data.name);
// If name is provided on the individual checkbox, add a data-single
// attribute which indicates it isn't part of a list of checkboxes with
// same name. Used in getInputData()
if (current.name) {
subnode.setAttribute('data-single', 'data-single');
}
if (current.checked) {
subnode.setAttribute('checked', 'checked');
}
if (current.disabled) {
subnode.setAttribute('disabled', 'disabled');
}
label = cur_div.appendChild(document.createElement('label'));
label.appendChild(Morebits.createHtml(current.label));
label.setAttribute('for', cur_id);
if (current.tooltip) {
Morebits.quickForm.element.generateTooltip(label, current);
}
// styles go on the label, doesn't make sense to style a checkbox/radio
if (current.style) {
label.setAttribute('style', current.style);
}
var event;
if (current.subgroup) {
let tmpgroup = current.subgroup;
if (!Array.isArray(tmpgroup)) {
tmpgroup = [ tmpgroup ];
}
var subgroupRaw = new Morebits.quickForm.element({
type: 'div',
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup, (idx, el) => {
const newEl = $.extend({}, el);
if (!newEl.type) {
newEl.type = data.type;
}
newEl.name = (current.name || data.name) + '.' + newEl.name;
subgroupRaw.append(newEl);
});
const subgroup = subgroupRaw.render(cur_id);
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
subnode.shown = false;
event = function(e) {
if (e.target.checked) {
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
const name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
}
e.target.form.names[name] = e.target;
}
} else {
e.target.parentNode.removeChild(e.target.subgroup);
}
};
subnode.addEventListener('change', event, true);
if (current.checked) {
subnode.parentNode.appendChild(subgroup);
}
} else if (data.type === 'radio') {
event = function(e) {
if (e.target.checked) {
const name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
}
delete e.target.form.names[name];
}
};
subnode.addEventListener('change', event, true);
}
// add users' event last, so it can interact with the subgroup
if (data.event) {
subnode.addEventListener('change', data.event, false);
} else if (current.event) {
subnode.addEventListener('change', current.event, true);
}
}
}
if (data.shiftClickSupport && data.type === 'checkbox') {
Morebits.checkboxShiftClickSupport(Morebits.quickForm.getElements(node, data.name));
}
break;
// input is actually a text-type, so number here inherits the same stuff
case 'number':
case 'input':
node = document.createElement('div');
node.setAttribute('id', 'div_' + id);
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(Morebits.createHtml(data.label));
label.setAttribute('for', data.id || id);
label.style.marginRight = '3px';
}
subnode = node.appendChild(document.createElement('input'));
subnode.setAttribute('name', data.name);
if (data.type === 'input') {
subnode.setAttribute('type', 'text');
} else {
subnode.setAttribute('type', 'number');
['min', 'max', 'step', 'list'].forEach((att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
}
['value', 'size', 'placeholder', 'maxlength'].forEach((att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
['disabled', 'required', 'readonly'].forEach((att) => {
if (data[att]) {
subnode.setAttribute(att, att);
}
});
if (data.event) {
subnode.addEventListener('keyup', data.event, false);
}
childContainer = subnode;
break;
case 'dyninput':
var min = data.min || 1;
var max = data.max || Infinity;
node = document.createElement('div');
label = node.appendChild(document.createElement('h5'));
label.appendChild(Morebits.createHtml(data.label));
var listNode = node.appendChild(document.createElement('div'));
var more = this.compute({
type: 'button',
label: 'more',
disabled: min >= max,
event: function(e) {
const new_node = new Morebits.quickForm.element(e.target.sublist);
e.target.area.appendChild(new_node.render());
if (++e.target.counter >= e.target.max) {
e.target.setAttribute('disabled', 'disabled');
}
e.stopPropagation();
}
});
node.appendChild(more[0]);
var moreButton = more[1];
var sublist = {
type: '_dyninput_row',
remove: false,
maxlength: data.maxlength,
event: data.event,
inputs: data.inputs || [{
// compatibility
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size
}]
};
for (i = 0; i < min; ++i) {
const elem = new Morebits.quickForm.element(sublist);
listNode.appendChild(elem.render());
}
sublist.remove = true;
sublist.morebutton = moreButton;
sublist.listnode = listNode;
moreButton.sublist = sublist;
moreButton.area = listNode;
moreButton.max = max - min;
moreButton.counter = 0;
break;
case '_dyninput_row': // Private
node = document.createElement('div');
data.inputs.forEach((subdata) => {
const cell = new Morebits.quickForm.element($.extend(subdata, { type: '_dyninput_cell' }));
node.appendChild(cell.render());
});
if (data.remove) {
const remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
const list = e.target.listnode;
const node = e.target.inputnode;
const more = e.target.morebutton;
list.removeChild(node);
--more.counter;
more.removeAttribute('disabled');
e.stopPropagation();
}
});
node.appendChild(remove[0]);
const removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
removeButton.morebutton = data.morebutton;
}
break;
case '_dyninput_cell': // Private, similar to normal input
node = document.createElement('span');
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(document.createTextNode(data.label));
label.setAttribute('for', id + '_input');
label.style.marginRight = '3px';
}
subnode = node.appendChild(document.createElement('input'));
subnode.setAttribute('id', id + '_input');
if (data.value) {
subnode.setAttribute('value', data.value);
}
subnode.setAttribute('name', data.name);
subnode.setAttribute('type', 'text');
subnode.setAttribute('data-dyninput', 'data-dyninput');
if (data.size) {
subnode.setAttribute('size', data.size);
}
if (data.maxlength) {
subnode.setAttribute('maxlength', data.maxlength);
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.disabled) {
subnode.setAttribute('required', 'disabled');
}
if (data.event) {
subnode.addEventListener('keyup', data.event, false);
}
node.style.marginRight = '3px';
break;
case 'hidden':
node = document.createElement('input');
node.setAttribute('type', 'hidden');
node.values = data.value;
node.setAttribute('value', data.value);
node.setAttribute('name', data.name);
break;
case 'header':
node = document.createElement('h5');
node.appendChild(Morebits.createHtml(data.label));
break;
case 'div':
node = document.createElement('div');
if (data.name) {
node.setAttribute('name', data.name);
}
if (data.label) {
const result = document.createElement('span');
result.className = 'quickformDescription';
result.appendChild(Morebits.createHtml(data.label));
node.appendChild(result);
}
break;
case 'submit':
node = document.createElement('span');
childContainer = node.appendChild(document.createElement('input'));
childContainer.setAttribute('type', 'submit');
if (data.label) {
childContainer.setAttribute('value', data.label);
}
childContainer.setAttribute('name', data.name || 'submit');
if (data.disabled) {
childContainer.setAttribute('disabled', 'disabled');
}
break;
case 'button':
node = document.createElement('span');
childContainer = node.appendChild(document.createElement('input'));
childContainer.setAttribute('type', 'button');
if (data.label) {
childContainer.setAttribute('value', data.label);
}
childContainer.setAttribute('name', data.name);
if (data.disabled) {
childContainer.setAttribute('disabled', 'disabled');
}
if (data.event) {
childContainer.addEventListener('click', data.event, false);
}
break;
case 'textarea':
node = document.createElement('div');
node.setAttribute('id', 'div_' + id);
if (data.label) {
label = node.appendChild(document.createElement('h5'));
const labelElement = document.createElement('label');
labelElement.appendChild(Morebits.createHtml(data.label));
labelElement.setAttribute('for', data.id || id);
label.appendChild(labelElement);
}
subnode = node.appendChild(document.createElement('textarea'));
subnode.setAttribute('name', data.name);
if (data.cols) {
subnode.setAttribute('cols', data.cols);
}
if (data.rows) {
subnode.setAttribute('rows', data.rows);
}
if (data.disabled) {
subnode.setAttribute('disabled', 'disabled');
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.readonly) {
subnode.setAttribute('readonly', 'readonly');
}
if (data.value) {
subnode.value = data.value;
}
childContainer = subnode;
break;
default:
throw new Error('Morebits.quickForm: unknown element type ' + data.type.toString());
}
if (!childContainer) {
childContainer = node;
}
if (data.tooltip) {
Morebits.quickForm.element.generateTooltip(label || node, data);
}
if (data.extra) {
childContainer.extra = data.extra;
}
if (data.$data) {
$(childContainer).data(data.$data);
}
if (data.style) {
childContainer.setAttribute('style', data.style);
}
if (data.className) {
childContainer.className = childContainer.className ?
childContainer.className + ' ' + data.className :
data.className;
}
childContainer.setAttribute('id', data.id || id);
return [ node, childContainer ];
};
/**
* Create a jQuery UI-based tooltip.
*
* @memberof Morebits.quickForm.element
* @requires jquery.ui
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated.
* @param {object} data - Tooltip-related configuration data.
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
const tooltipButton = node.appendChild(document.createElement('span'));
tooltipButton.className = 'morebits-tooltipButton';
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI
tooltipButton.appendChild(document.createTextNode(msg('tooltip-mark', '?')));
$(tooltipButton).tooltip({
position: { my: 'left top', at: 'center bottom', collision: 'flipfit' },
// Deprecated in UI 1.12, but MW stuck on 1.9.2 indefinitely; see #398 and T71386
tooltipClass: 'morebits-ui-tooltip'
});
};
// Some utility methods for manipulating quickForms after their creation:
// (None of these work for "dyninput" type fields at present)
/**
* Returns an object containing all filled form data entered by the user, with the object
* keys being the form element names. Disabled fields will be ignored, but not hidden fields.
*
* @memberof Morebits.quickForm
* @param {HTMLFormElement} form
* @returns {object} With field names as keys, input data as values.
*/
Morebits.quickForm.getInputData = function(form) {
const result = {};
for (let i = 0; i < form.elements.length; i++) {
const field = form.elements[i];
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
continue;
}
// For elements in subgroups, quickform prepends element names with
// name of the parent group followed by a period, get rid of that.
const fieldNameNorm = field.name.slice(field.name.indexOf('.') + 1);
switch (field.type) {
case 'radio':
if (field.checked) {
result[fieldNameNorm] = field.value;
}
break;
case 'checkbox':
if (field.dataset.single) {
result[fieldNameNorm] = field.checked; // boolean
} else {
result[fieldNameNorm] = result[fieldNameNorm] || [];
if (field.checked) {
result[fieldNameNorm].push(field.value);
}
}
break;
case 'select-multiple':
result[fieldNameNorm] = $(field).val(); // field.value doesn't work
break;
case 'text': // falls through
case 'textarea':
if (field.dataset.dyninput) {
result[fieldNameNorm] = result[fieldNameNorm] || [];
result[fieldNameNorm].push(field.value.trim());
} else {
result[fieldNameNorm] = field.value.trim();
}
break;