/
acdc.js
1268 lines (1172 loc) · 45.4 KB
/
acdc.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
( function ( mw, $ ) {
/* eslint-disable indent */
( async function () {
'use strict';
const require = await mw.loader.using( [
'oojs',
'oojs-ui-core',
'oojs-ui-widgets',
'oojs-ui-windows',
'oojs-ui.styles.icons-interactions',
'oojs-ui.styles.icons-content',
'oojs-ui.styles.icons-editing-list',
'wikibase.mediainfo.statements',
'wikibase.utilities.ClaimGuidGenerator',
'wikibase.datamodel',
'wikibase.serialization',
'wikibase.common',
'mediawiki.api',
'mediawiki.util',
'mediawiki.Title',
'jquery.i18n',
'web2017-polyfills',
] ),
ClaimGuidGenerator = wikibase.utilities.ClaimGuidGenerator,
{ Statement, Claim, PropertyNoValueSnak } = require( 'wikibase.datamodel' ),
{ StatementListDeserializer, StatementSerializer, StatementDeserializer } = require( 'wikibase.serialization' ),
{ StatementWidget, AddPropertyWidget } = require( 'wikibase.mediainfo.statements' );
await $.i18n().load( {
en: {
'gadget-acdc-load-category': 'Load category',
'gadget-acdc-load-pagepile': 'Load PagePile',
'gadget-acdc-load-category-title': 'Category title:',
'gadget-acdc-load-category-placeholder': 'Category:Example',
'gadget-acdc-load-pagepile-id': 'PagePile ID:',
'gadget-acdc-load-pagepile-error-wrong-wiki': 'That PagePile does not belong to this wiki!',
'gadget-acdc-load-pagepile-warning-large-pagepile':
'This PagePile contains {{PLURAL:$1|$1 file|$1 files}}, ' +
'using it will take a while. Are you sure?',
'gadget-acdc-button-stop-edit': 'Stop',
'gadget-acdc-field-files': 'Files to edit',
'gadget-acdc-field-statements-to-add': 'Statements to add',
'gadget-acdc-field-statements-to-remove': 'Statements to remove',
'gadget-acdc-file-placeholder': 'File:Example.png',
'gadget-acdc-files-placeholder': 'File:Example.png | File:Example.jpg',
'gadget-acdc-error-duplicate-statements-to-add':
'You specified multiple statements with the same main value, ' +
'which is not supported. ' +
'If you need to make multiple changes to one statement, merge them. ' +
'If you really need to add multiple statements with the same value, ' +
'you’ll have to find another way (sorry).',
'gadget-acdc-error-duplicate-statements-to-remove':
'You specified multiple statements to remove with the same main value, ' +
'which is not supported.',
'gadget-acdc-error-statement-with-qualifiers-to-remove':
'You specified a statement with qualifiers ' +
'in the “{{int:gadget-acdc-field-statements-to-remove}}” section. ' +
'The meaning of this is not clear ' +
'(remove only qualifiers, or remove whole statement only if it has these qualifiers?), ' +
'so this is currenty not supported.',
// TODO implement the following error
'gadget-acdc-error-statement-to-add-and-remove':
'You specified statements with the same property and value ' +
'in the “{{int:gadget-acdc-field-statements-to-add}}” and ' +
'“{{int:gadget-acdc-field-statements-to-remove}}” sections. ' +
'The meaning of this is not clear, so it is currently not supported.',
},
} );
await $.i18n().load(
new mw.Title( 'MediaWiki:Gadget-ACDC-i18n.json' ).getUrl() +
'?action=raw&ctype=application/json',
// note: we can’t pass the parameters into getUrl() –
// we need a URL that ends in .json (otherwise $.i18n thinks it’s a directory),
// so it has to be /wiki/….json?action=…, not /w/index.php?title=….json&action=…
// (and yes, this means the i18n only works on wikis with nice URLs)
);
// implement {{int:}}, see https://github.com/wikimedia/jquery.i18n/issues/211
$.extend( $.i18n.parser.emitter, {
int( nodes ) {
return $.i18n( ...nodes );
},
} );
/**
* Maps titles to entity IDs.
*
* @param {string[]} titles
* @return {Promise<Object.<string,string>>} map from title to entity ID
*/
async function titlesToEntityIds( titles ) {
const api = new mw.Api(),
allTitles = titles.slice(), // copy that we can splice without affecting the original
entityIds = {};
let someTitles;
while ( ( someTitles = allTitles.splice( 0, 50 ) ).length > 0 ) {
const response = await api.post( { // POST because titles list may be too long for GET URL
action: 'query',
titles: someTitles,
formatversion: 2,
} );
for ( const page of response.query.pages ) {
entityIds[ page.title ] = `M${ page.pageid }`;
}
}
return entityIds;
}
/**
* Maps entity IDs to entity data.
*
* @param {string[]} entityIds
* @param {string[]} props
* @return {Promise<Object.<string,Object>>} map from entity ID to entity data
*/
async function entityIdsToData( entityIds, props ) {
const api = new mw.Api(),
allEntityIds = entityIds.slice(), // copy that we can splice without affecting the original
entityData = {};
let someEntityIds;
while ( ( someEntityIds = allEntityIds.splice( 0, 50 ) ).length > 0 ) {
const response = await api.get( { action: 'wbgetentities', ids: someEntityIds, props, formatversion: 2 } );
Object.assign( entityData, response.entities );
}
for ( const data of Object.values( entityData ) ) {
if ( 'missing' in data ) {
// treat missing entities (i. e. no structured data yet) as having empty statements
data.statements = {};
}
}
return entityData;
}
async function* categoryFiles( categoryTitle ) {
const api = new mw.Api(),
originalParams = {
action: 'query',
list: 'categorymembers',
cmtitle: categoryTitle,
cmprop: [ 'title' ],
cmtype: [ 'file' ],
cmlimit: 'max',
formatversion: 2,
};
let response = {};
do {
response = await api.get( Object.assign( {}, originalParams, response.continue ) );
yield* response.query.categorymembers.map( member => member.title );
} while ( 'continue' in response );
}
/**
* Return the datatypes of the properties with the given IDs.
*
* @param {Array.<string>} propertyIds
* @return {Promise<Object.<string,string>>}
*/
async function propertyDatatypes( propertyIds ) {
if ( !propertyIds.length ) {
return {};
}
const api = new mw.Api(),
response = await api.get( {
action: 'wbgetentities',
ids: propertyIds,
props: [ 'datatype' ],
formatversion: 2,
} );
return Object.fromEntries(
Object.entries( response.entities )
.map( ( [ propertyId, { datatype } ] ) => [ propertyId, datatype ] ) );
}
/**
* Sleep for a tiny bit, to give the browser time to update the UI.
* Usually called in busy loops that would otherwise block for a while, freezing the browser.
* Calling this may slow down the process a bit, but is much more responsive.
*
* @return {Promise}
*/
function microsleep() {
return new Promise( resolve => setTimeout( resolve, 1 ) );
}
function failSanityCheck( component ) {
throw new Error( `${ component } seems to have changed incompatibly, AC/DC must be updated before it can be safely used!` );
}
function sanityCheckStatementWidgetPropertyId() {
const statementWidget = new StatementWidget( {
entityId: '',
propertyId: 'P12345',
isDefaultProperty: false,
propertyType: 'wikibase-item',
} );
if ( !( 'state' in statementWidget &&
statementWidget.state.propertyId === 'P12345' ) ) {
// if the property ID is not available, we can’t detect existing statements
failSanityCheck( 'StatementWidget.state.propertyId' );
}
}
function sanityCheckStatementEquals() {
const snak = new PropertyNoValueSnak( 'P1' ),
claim1 = new Claim( snak, null, 'guid 1' ),
statement1 = new Statement( claim1 ),
claim2 = new Claim( snak, null, 'guid 2' ),
statement2 = new Statement( claim2 );
if ( !statement1.equals( statement2 ) ) {
// if different GUIDs break Statement.equals, we can’t detect duplicate statements
failSanityCheck( 'Statement.equals' );
}
}
sanityCheckStatementWidgetPropertyId();
sanityCheckStatementEquals();
let installedStyles = false;
function installStyles() {
if ( installedStyles ) {
return;
}
const style = document.createElement( 'style' );
// TODO better way to indicate errors
style.innerHTML = `
.acdc-statementsDialog__statementWidget--duplicate-statement,
.acdc-statementsDialog__statementWidget--statement-with-qualifiers-to-remove,
.acdc-statementsDialog__statementWidget--statement-to-add-and-remove {
border-left: 2px solid red;
}
.acdc-statementsDialog .wbmi-statement-footer {
display: none;
}
body.acdc-active .uls-menu {
z-index: 102; /* Vector @z-index-overlay (101) + 1 */
--source-of-this-z-index: '[[c:Help:Gadget-ACDC|AC/DC gadget]]';
}
`;
const now = new Date();
if ( ( now.getMonth() + 1 ) === 9 && now.getDate() === 23 ) {
style.innerHTML += `
.acdc-statementsDialog .oo-ui-processDialog-actions-primary .oo-ui-widget-enabled .oo-ui-buttonElement-button {
background: linear-gradient( #D60270 40%, #9B4F96 40%, 60%, #0038A8 60% );
}
`;
}
document.head.appendChild( style );
installedStyles = true;
}
/**
* Parse a URL on the local wiki into just a title.
*
* @param {string|URL} url
* @return {string|null} The title, if the URL can be parsed,
* otherwise null (invalid URL, not on the local wiki, …)
*/
function parseLocalTitle( url ) {
if ( !( url instanceof URL ) ) {
try {
url = new URL( url );
} catch ( e ) {
return null;
}
}
if ( !(
`//${ url.host }` === mw.config.get( 'wgServer' ) ||
`${ url.protocol }//${ url.host }` === mw.config.get( 'wgServer' )
) ) {
return null;
}
const articlePath = mw.config.get( 'wgArticlePath' ); // like /wiki/$1
if ( articlePath.endsWith( '$1' ) && !articlePath.includes( '?' ) ) {
const articlePathPrefix = articlePath.slice( 0, -2 );
if ( url.pathname.startsWith( articlePathPrefix ) ) {
return decodeURIComponent(
url.pathname.slice( articlePathPrefix.length ),
).replace( /_/g, ' ' );
}
}
const script = mw.config.get( 'wgScript' ); // like /w/index.php
if ( url.pathname === script ) {
const params = url.searchParams;
if ( params.has( 'title' ) ) {
return decodeURIComponent(
params.get( 'title' ),
).replace( /_/g, ' ' );
}
}
return null;
}
/**
* Ensure that a title begins with the File: namespace.
*
* @param {string} title
* @return {string}
*/
function ensureFileNamespace( title ) {
if ( title.startsWith( 'File:' ) ) {
return title;
} else {
return `File:${ title }`;
}
}
/**
* Try to intelligently parse some input for a file.
* The input can be a title with or without the File: namespace,
* or a URL to the file on the local wiki.
*
* @param {string} input
* @return {string}
*/
function parseFileInput( input ) {
if ( input.includes( '/' ) ) {
// file names can never contain a slash, so try to parse as URL
// (subpages in the File: namespace exist but they’re not files)
const title = parseLocalTitle( input );
if ( title !== null && title.startsWith( 'File:' ) ) {
return title;
}
}
return ensureFileNamespace( input );
}
/**
* FileInputWidget is an input widget for files on the local wiki.
* File names are looked up as soon as the user begins typing,
* and suggested accordingly.
* When text is pasted into the input,
* newline and tab characters are replaced with pipe characters,
* for integration with FilesWidget.
*
* @class
* @extends OO.ui.TextInputWidget
* @mixins OO.ui.mixin.LookupElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]} [skippedFiles] Don’t suggest these files in the lookup.
*/
function FileInputWidget( config ) {
FileInputWidget.super.call( this, $.extend( {
placeholder: $.i18n( 'gadget-acdc-file-placeholder' ),
}, config ) );
OO.ui.mixin.LookupElement.call( this, $.extend( {
showPendingRequest: false,
$container: this.$input, // the default is this.$element, which in a non-'outline' TagMultiselectWidget is never attached to the DOM, so the lookup can’t position itself relative to it
}, config ) );
this.skippedFiles = config.skippedFiles || [];
this.$element.addClass( 'acdc-fileInputWidget' );
this.$input.addClass( 'acdc-fileInputWidget-input' );
this.lookupMenu.connect( this, { choose: [ 'emit', 'select' ] } );
this.$input.on( 'paste', ( { originalEvent: clipboardEvent } ) => {
const value = clipboardEvent.clipboardData.getData( 'text' )
.trim()
.replace( /[\n\t]/g, ' | ' ),
inputElement = this.$input[ 0 ];
if ( typeof inputElement.setRangeText === 'function' ) {
inputElement.setRangeText( value );
inputElement.selectionStart += value.length;
inputElement.selectionEnd = inputElement.selectionStart;
} else {
// fallback for incompatible browsers
inputElement.value = value;
}
clipboardEvent.preventDefault();
} );
}
OO.inheritClass( FileInputWidget, OO.ui.TextInputWidget );
OO.mixinClass( FileInputWidget, OO.ui.mixin.LookupElement );
FileInputWidget.prototype.setSkippedFiles = function ( skippedFiles ) {
this.skippedFiles = skippedFiles;
};
FileInputWidget.prototype.getLookupRequest = function () {
const prefix = this.getValue();
if ( !prefix || prefix.includes( '|' ) ) {
const response = {
query: {
search: [],
},
notice: 'This is a fake API response generated by FileInputWidget.prototype.getLookupRequest.',
};
return $.Deferred().resolve( response ).promise();
}
const api = new mw.Api();
return api.get( {
action: 'query',
list: 'search',
srsearch: `prefix:${ ensureFileNamespace( prefix ) }`,
srinfo: [ /* no metadata */ ],
srprop: [ /* no properties (we only need title, which is always returned) */ ],
formatversion: 2,
} );
};
FileInputWidget.prototype.getLookupCacheDataFromResponse = function ( response ) {
return response.query.search.map( result => result.title );
};
FileInputWidget.prototype.getLookupMenuOptionsFromData = function ( titles ) {
return titles
.filter( title => !this.skippedFiles.includes( title ) )
.map( title => {
return new OO.ui.MenuOptionWidget( {
data: title,
label: title,
} );
} );
};
/**
* FilesWidget is an input widget for a collection of files on the local wiki.
* A FileInputWidget is used for the input,
* and the input is split on pipe characters
* to allow adding multiple files at once.
* The File: namespace is automatically added where missing.
* The TagMultiselectWidget’s icon is turned into an icon,
* which opens a menu with a button to load files from a PagePile.
* Inputs may also be file or PagePile URLs.
*
* @class
* @extends OO.ui.TagMultiselectWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
function FilesWidget( config ) {
FilesWidget.super.call( this, $.extend( {
allowArbitrary: true,
inputWidget: new FileInputWidget( $.extend( {
placeholder: $.i18n( 'gadget-acdc-files-placeholder' ),
}, config ) ),
icon: 'ellipsis',
}, config ) );
this.input.connect( this, { select: 'addTagFromInput' } );
this.on( 'change', () => {
this.input.setSkippedFiles( this.getTitles() );
} );
this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
this.$element.addClass( 'acdc-filesWidget' );
// we turn the ellipsis icon into a “button” opening a popup menu with currently one button
this.categoryButton = new OO.ui.ButtonWidget( {
icon: 'tag',
label: $.i18n( 'gadget-acdc-load-category' ),
} );
this.pagePileButton = new OO.ui.ButtonWidget( {
icon: 'listBullet',
label: $.i18n( 'gadget-acdc-load-pagepile' ),
} );
this.menuPopup = new OO.ui.PopupWidget( {
$content: new OO.ui.StackLayout( {
items: [
new OO.ui.PanelLayout( {
$content: this.categoryButton.$element,
expanded: false,
} ),
new OO.ui.PanelLayout( {
$content: this.pagePileButton.$element,
expanded: false,
} ),
],
continuous: true,
expanded: false,
} ).$element,
$floatableContainer: this.$icon,
align: 'forwards',
autoClose: true,
$autoCloseIgnore: this.$icon, // click on $icon closes via toggle() below instead
$overlay: this.$overlay,
width: null, // use automatic width
padded: true,
} );
this.$overlay.append( this.menuPopup.$element );
this.$icon.css( { cursor: 'pointer' } );
this.$icon.on( 'click', () => this.menuPopup.toggle() );
// TODO this is not very accessible :/
// but we don’t have many options – we can’t add other elements around the $icon,
// or the TagMultiselectWidget’s layout breaks
this.suggestedCurrentCategory = false;
this.categoryButton.on( 'click', async () => {
this.menuPopup.toggle( false );
let defaultCategory = mw.config.get( 'wgPageName' )
.replace( /_/g, ' ' );
if ( defaultCategory.startsWith( 'Category:' ) && !this.suggestedCurrentCategory ) {
this.suggestedCurrentCategory = true;
} else {
defaultCategory = null;
}
let categoryTitle = await OO.ui.prompt( $.i18n( 'gadget-acdc-load-category-title' ), {
size: 'medium',
textInput: {
placeholder: $.i18n( 'gadget-acdc-load-category-placeholder' ),
value: defaultCategory,
},
} );
if ( !categoryTitle ) {
// user clicked “cancel”, nothing to do
return;
}
if ( !categoryTitle.startsWith( 'Category:' ) ) {
categoryTitle = `Category:${ categoryTitle }`;
}
try {
await this.loadCategory( categoryTitle );
} catch ( e ) {
await OO.ui.alert( `Error: ${ e }` );
}
} );
this.pagePileButton.on( 'click', async () => {
this.menuPopup.toggle( false );
const pagePileId = await OO.ui.prompt( $.i18n( 'gadget-acdc-load-pagepile-id' ), {
textInput: {
placeholder: '12345',
type: 'number',
},
} );
if ( !pagePileId ) {
// user clicked “cancel”, nothing to do
return;
}
await this.loadPagePile( pagePileId );
} );
}
OO.inheritClass( FilesWidget, OO.ui.TagMultiselectWidget );
FilesWidget.prototype.addTagFromInput = function () {
const titles = this.input.getValue().split( '|' )
.map( s => s.trim() )
.filter( s => s )
.filter( input => {
// try parsing as well-known URL, skip in that case
let url;
try {
url = new URL( input );
} catch ( e ) {
// not a URL
return true;
}
if (
url.host === 'pagepile.toolforge.org' && url.pathname === '/api.php' ||
url.host === 'tools.wmflabs.org' && url.pathname === '/pagepile/api.php'
) {
// PagePile URL
const pagePileId = url.searchParams.get( 'id' );
if ( pagePileId === null || !/^[1-9][0-9]*$/.test( pagePileId ) ) {
// no valid ID
return true;
}
// load it (asynchronously) and skip input as a file in the meantime
this.loadPagePile( pagePileId );
return false;
}
const title = parseLocalTitle( url );
if ( title !== null && title.startsWith( 'Category:' ) ) {
// Category URL – load (async) and skip input in the meantime
this.loadCategory( title );
return false;
}
return true;
} )
.map( input => parseFileInput( input ) );
this.clearInput();
for ( const title of titles ) {
if ( this.isAllowedData( title ) || this.allowDisplayInvalidTags ) {
this.addTag( title );
} else {
let inputValue = this.input.getValue();
if ( inputValue ) {
inputValue += ' | ';
}
inputValue += title;
this.input.setValue( inputValue );
}
}
};
FilesWidget.prototype.loadCategory = async function ( categoryTitle ) {
for await ( const file of categoryFiles( categoryTitle ) ) {
this.addTag( file );
await microsleep();
}
};
FilesWidget.prototype.loadPagePile = async function ( pagePileId ) {
const pileJson = await fetch(
`https://pagepile.toolforge.org/api.php?action=get_data&id=${ pagePileId }&format=json`,
).then( r => r.json() );
if ( pileJson.wiki !== mw.config.get( 'wgDBname' ) ) {
await OO.ui.alert( $.i18n( 'gadget-acdc-load-pagepile-error-wrong-wiki' ) );
return false;
}
const files = pileJson.pages
.filter( page => page.startsWith( 'File:' ) );
if ( files.length >= 100 ) {
const confirmation = await OO.ui.confirm(
$.i18n( 'gadget-acdc-load-pagepile-warning-large-pagepile', files.length ),
);
if ( !confirmation ) {
return false;
}
}
for ( const file of files ) {
this.addTag( file );
await microsleep();
}
return true;
};
FilesWidget.prototype.loadCatALot = async function () {
for ( const [ file ] of mw.libs.catALot.getMarkedLabels() ) {
if ( file.startsWith( 'File:' ) ) {
this.addTag( file );
await microsleep();
}
}
};
FilesWidget.prototype.getTitles = function () {
return this.getItems().map( item => item.getData() );
};
/**
* StatementsProgressBarWidget is a progress bar widget for AC/DC.
* It is initialized with the number of files
* and number of statements to edit on each file,
* and updated whenever progress has been made,
* and then calculates the progress itself each time.
*
* @class
* @extends OO.ui.ProgressBarWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
function StatementsProgressBarWidget( config ) {
StatementsProgressBarWidget.super.call( this, $.extend( {
progress: 0,
}, config ) );
this.toggle( false );
this.$element.addClass( 'acdc-statementsProgressBarWidget' );
}
OO.inheritClass( StatementsProgressBarWidget, OO.ui.ProgressBarWidget );
StatementsProgressBarWidget.prototype.enable = function ( numberEntities, numberStatementsPerEntity ) {
this.numberEntities = numberEntities;
this.numberStatementsPerEntity = numberStatementsPerEntity;
this.totalQueryCalls = Math.ceil( numberEntities / 50 );
this.totalGetEntitiesCalls = Math.ceil( numberEntities / 50 );
this.totalApiCalls = this.totalQueryCalls + this.totalGetEntitiesCalls + this.numberEntities * this.numberStatementsPerEntity;
this.loadedEntityIds = false;
this.loadedEntityData = false;
this.indexEntity = 0;
this.indexStatement = 0;
this.toggle( true );
};
StatementsProgressBarWidget.prototype.disable = function () {
this.toggle( false );
this.setProgress( 0 );
};
StatementsProgressBarWidget.prototype.updateProgress = function () {
this.setProgress(
100 * ( ( this.loadedEntityIds ? this.totalQueryCalls : 0 ) +
( this.loadedEntityData ? this.totalGetEntitiesCalls : 0 ) +
this.indexEntity * this.numberStatementsPerEntity +
this.indexStatement ) /
this.totalApiCalls,
);
};
StatementsProgressBarWidget.prototype.finishedLoadingEntityIds = function () {
this.loadedEntityIds = true;
this.updateProgress();
};
StatementsProgressBarWidget.prototype.finishedLoadingEntityData = function () {
this.loadedEntityData = true;
this.updateProgress();
};
StatementsProgressBarWidget.prototype.finishedStatements = function ( numberStatements ) {
this.indexStatement += numberStatements;
this.updateProgress();
};
StatementsProgressBarWidget.prototype.finishedEntity = function () {
this.indexEntity++;
this.indexStatement = 0;
this.updateProgress();
};
StatementsProgressBarWidget.prototype.finished = function () {
this.setProgress( 100 );
};
/**
* StatementsDialog is the main dialog of AC/DC.
* It initializes and arranges the other UI elements,
* and performs the edits on publish.
*
* Adding multiple statements for the same property with the same value is disallowed –
* attempting to do so marks the erroneous statements and disables the publish button.
* This is because otherwise, AC/DC updates existing statements with the same value
* (i. e. to add qualifiers),
* so trying to add more than one such statement does not make sense.
*
* Likewise, an error is reported if two statements in the “remove” section have the same value,
* or if any of them have qualifiers, because the meaning of either would be unclear.
*
* @class
* @extends OO.ui.ProcessDialog
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string[]} [tags] Change tags to apply to edits.
*/
function StatementsDialog( config ) {
StatementsDialog.super.call( this, $.extend( {
size: 'large',
}, config ) );
this.tags = ( config || {} ).tags || [];
this.$element.addClass( 'acdc-statementsDialog' );
}
OO.inheritClass( StatementsDialog, OO.ui.ProcessDialog );
StatementsDialog.static.name = 'statements';
StatementsDialog.static.title = 'Add to Commons / Descriptive Claims';
StatementsDialog.static.actions = [
{
action: 'save',
label: mw.message( 'wikibasemediainfo-filepage-publish' ).text(),
flags: [ 'primary', 'progressive' ],
modes: [ 'edit' ],
disabled: true, // see updateCanSave
},
{
label: mw.message( 'wikibasemediainfo-filepage-cancel' ).text(),
flags: [ 'safe', 'close' ],
modes: [ 'edit', 'save' ],
},
{
action: 'stop',
label: $.i18n( 'gadget-acdc-button-stop-edit' ),
flags: [ 'primary', 'destructive' ],
modes: [ 'save' ],
},
];
StatementsDialog.prototype.initialize = function () {
StatementsDialog.super.prototype.initialize.call( this );
installStyles();
this.stopped = false;
this.filesWidget = new FilesWidget( {
indicator: 'required',
$overlay: this.$overlay,
} );
this.filesWidget.connect( this, { change: 'updateCanSave' } );
this.filesWidget.connect( this, { change: 'updateSize' } );
this.hasDuplicateStatementsToAddPerProperty = {};
this.statementToAddWidgets = [];
this.addPropertyToAddWidget = new AddPropertyWidget( {
$overlay: this.$overlay,
} );
this.addPropertyToAddWidget.on( 'choose', ( _widget, { id, datatype } ) => this.addStatementToAddWidget( id, datatype ) );
this.addPropertyToAddWidget.connect( this, { choose: 'updateSize' } );
// TODO we should also updateSize when the AddPropertyWidget enters/leaves editing mode, but it doesn’t emit an event for that yet
this.hasDuplicateStatementsToRemovePerProperty = {};
this.hasStatementWithQualifiersToRemovePerProperty = {};
this.statementToRemoveWidgets = [];
this.addPropertyToRemoveWidget = new AddPropertyWidget( {
$overlay: this.$overlay,
} );
this.addPropertyToRemoveWidget.on( 'choose', ( _widget, { id, datatype } ) => this.addStatementToRemoveWidget( id, datatype ) );
this.addPropertyToRemoveWidget.connect( this, { choose: 'updateSize' } );
// TODO we should also updateSize when the AddPropertyWidget enters/leaves editing mode, but it doesn’t emit an event for that yet
const filesField = new OO.ui.FieldLayout( this.filesWidget, {
label: $.i18n( 'gadget-acdc-field-files' ),
align: 'top',
classes: [ 'acdc-statementsDialog-filesField' ],
} );
filesField.$header.wrap( '<h3>' );
const statementsToAddField = new OO.ui.FieldLayout( this.addPropertyToAddWidget, {
label: $.i18n( 'gadget-acdc-field-statements-to-add' ),
align: 'top',
classes: [ 'acdc-statementsDialog-statementsToAddField' ],
} );
statementsToAddField.$header.wrap( '<h3>' );
const statementsToRemoveField = new OO.ui.FieldLayout( this.addPropertyToRemoveWidget, {
label: $.i18n( 'gadget-acdc-field-statements-to-remove' ),
align: 'top',
classes: [ 'acdc-statementsDialog-statementsToRemoveField' ],
} );
statementsToRemoveField.$header.wrap( '<h3>' );
this.content = new OO.ui.PanelLayout( {
content: [ new OO.ui.FieldsetLayout( {
items: window.acdcEnableRemoveFeature ? [ // TODO remove this magic global
filesField,
statementsToAddField,
statementsToRemoveField,
] : [
filesField,
statementsToAddField,
],
} ) ],
padded: true,
expanded: false,
} );
this.$body.append( this.content.$element );
this.statementsProgressBarWidget = new StatementsProgressBarWidget( {} );
this.$head.append( this.statementsProgressBarWidget.$element );
this.duplicateStatementsToAddError = new OO.ui.MessageWidget( {
type: 'error',
label: $.i18n( 'gadget-acdc-error-duplicate-statements-to-add' ),
} );
this.duplicateStatementsToAddError.toggle( false ); // see updateShowDuplicateStatementsToAddError
this.$foot.append( this.duplicateStatementsToAddError.$element );
this.duplicateStatementsToRemoveError = new OO.ui.MessageWidget( {
type: 'error',
label: $.i18n( 'gadget-acdc-error-duplicate-statements-to-remove' ),
} );
this.duplicateStatementsToRemoveError.toggle( false ); // see updateShowDuplicateStatementsToRemoveError
this.$foot.append( this.duplicateStatementsToRemoveError.$element );
this.statementWithQualifiersToRemoveError = new OO.ui.MessageWidget( {
type: 'error',
label: $.i18n( 'gadget-acdc-error-statement-with-qualifiers-to-remove' ),
} );
this.statementWithQualifiersToRemoveError.toggle( false ); // see updateShowStatementWithQualifiersToRemoveError
this.$foot.append( this.statementWithQualifiersToRemoveError.$element );
const favoritePropertiesToAdd = window.acdcFavoritePropertiesToAdd ||
window.acdcFavoriteProperties ||
mw.config.get( 'wbmiDefaultProperties', [] );
const favoritePropertiesToRemove = window.acdcFavoritePropertiesToRemove ||
window.acdcFavoriteProperties ||
[];
propertyDatatypes( Array.from( new Set( [ ...favoritePropertiesToAdd, ...favoritePropertiesToRemove ] ) ) ).then( datatypes => {
for ( const favoritePropertyToAdd of favoritePropertiesToAdd ) {
this.addStatementToAddWidget( favoritePropertyToAdd, datatypes[ favoritePropertyToAdd ] );
}
for ( const favoritePropertyToRemove of favoritePropertiesToRemove ) {
this.addStatementToRemoveWidget( favoritePropertyToRemove, datatypes[ favoritePropertyToRemove ] );
}
} );
this.filesWidget.loadCatALot().catch( () => {
// ignore any error (Cat-a-lot not loaded, not active, changed its API…)
} );
};
StatementsDialog.prototype.getSetupProcess = function ( data ) {
$( document.body ).toggleClass( 'acdc-active', true );
return StatementsDialog.super.prototype.getSetupProcess.call( this, data ).next( async () => {
this.title.setLabel( 'AC/DC' );
this.actions.setMode( 'edit' );
if ( 'tags' in data ) {
this.tags = data.tags;
}
} );
};
StatementsDialog.prototype.getTeardownProcess = function ( data ) {
$( document.body ).toggleClass( 'acdc-active', false );
return StatementsDialog.super.prototype.getTeardownProcess.call( this, data );
};
StatementsDialog.prototype.getReadyProcess = function ( data ) {
return StatementsDialog.super.prototype.getReadyProcess.call( this, data ).next( async () => {
this.filesWidget.updateInputSize();
this.filesWidget.focus();
} );
};
StatementsDialog.prototype.getActionProcess = function ( action ) {
switch ( action ) {
case 'save':
return new OO.ui.Process( async () => {
this.actions.setMode( 'save' );
const finished = await this.save().catch( error => {
console.error( 'AC/DC: error while saving', error );
throw new OO.ui.Error( error, { recoverable: false } );
} );
if ( finished ) {
this.actions.setMode( 'edit' );
this.close();
}
} ).next( async () => {
// regardless whether we finished or stopped, remove the progress bar again
this.statementsProgressBarWidget.disable();
} );
case 'stop':
return new OO.ui.Process( async () => {
this.stopped = true;
this.actions.setMode( 'edit' );
} );
default:
return StatementsDialog.super.prototype.getActionProcess.call( this, action );
}
};
StatementsDialog.prototype.addStatementToAddWidget = function ( id, datatype ) {
const statementToAddWidget = new StatementWidget( {
entityId: '', // this widget is reused for multiple entities, we inject the entity IDs on publish
propertyId: id,
isDefaultProperty: false,
propertyType: datatype,
$overlay: this.$overlay,
tags: this.tags,
showControls: true,
} );
statementToAddWidget.connect( this, { change: 'updateCanSave' } );
statementToAddWidget.connect( this, { change: 'updateSize' } );
statementToAddWidget.on( 'change', () => {
// check if there are any duplicate statements for this property
this.hasDuplicateStatementsToAddPerProperty[ id ] = false;
const itemWidgets = statementToAddWidget.getItems();
for ( const itemWidget of itemWidgets ) {
itemWidget.$element.removeClass( 'acdc-statementsDialog__statementWidget--duplicate-statement' );
}
// this is O(n²) but for small n
for ( let i = 0; i < itemWidgets.length; i++ ) {
const itemWidget1 = itemWidgets[ i ];
for ( let j = i + 1; j < itemWidgets.length; j++ ) {
const itemWidget2 = itemWidgets[ j ];
if ( itemWidget1.getData().getClaim().getMainSnak().equals( itemWidget2.getData().getClaim().getMainSnak() ) ) {
this.hasDuplicateStatementsToAddPerProperty[ id ] = true;
itemWidget1.$element.addClass( 'acdc-statementsDialog__statementWidget--duplicate-statement' );
itemWidget2.$element.addClass( 'acdc-statementsDialog__statementWidget--duplicate-statement' );
}
}
}
this.updateShowDuplicateStatementsToAddError();
this.updateCanSave();
} );
this.statementToAddWidgets.push( statementToAddWidget );
statementToAddWidget.$element.insertBefore( this.addPropertyToAddWidget.$element );
};
StatementsDialog.prototype.addStatementToRemoveWidget = function ( id, datatype ) {
const statementToRemoveWidget = new StatementWidget( {
entityId: '', // this widget is reused for multiple entities, we inject the entity IDs on publish
propertyId: id,
isDefaultProperty: false,
propertyType: datatype,
$overlay: this.$overlay,
tags: this.tags,
showControls: true,
} );
statementToRemoveWidget.connect( this, { change: 'updateCanSave' } );
statementToRemoveWidget.connect( this, { change: 'updateSize' } );
statementToRemoveWidget.on( 'change', () => {
// check if there are any duplicate statements or statements with qualifiers for this property
this.hasDuplicateStatementsToRemovePerProperty[ id ] = false;
this.hasStatementWithQualifiersToRemovePerProperty[ id ] = false;
const itemWidgets = statementToRemoveWidget.getItems();
for ( const itemWidget of itemWidgets ) {
itemWidget.$element.removeClass( 'acdc-statementsDialog__statementWidget--duplicate-statement' );
itemWidget.$element.removeClass( 'acdc-statementsDialog__statementWidget--statement-with-qualifiers-to-remove' );
}
// this is O(n²) but for small n
for ( let i = 0; i < itemWidgets.length; i++ ) {
const itemWidget1 = itemWidgets[ i ];
for ( let j = i + 1; j < itemWidgets.length; j++ ) {
const itemWidget2 = itemWidgets[ j ];
if ( itemWidget1.getData().getClaim().getMainSnak().equals( itemWidget2.getData().getClaim().getMainSnak() ) ) {
this.hasDuplicateStatementsToRemovePerProperty[ id ] = true;
itemWidget1.$element.addClass( 'acdc-statementsDialog__statementWidget--duplicate-statement' );
itemWidget2.$element.addClass( 'acdc-statementsDialog__statementWidget--duplicate-statement' );
}
}
}
for ( const itemWidget of itemWidgets ) {
// TODO we don’t check for references here (but WikibaseMediaInfo doesn’t support them yet as of writing this)
if ( !itemWidget.getData().getClaim().getQualifiers().isEmpty() ) {