selectandother.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * HTMLForm enhancements:
  3. * Add a dynamic max length to the reason field of SelectAndOther.
  4. */
  5. ( function () {
  6. // cache the separator to avoid object creation on each keypress
  7. var colonSeparator = mw.message( 'colon-separator' ).text();
  8. mw.hook( 'htmlform.enhance' ).add( function ( $root ) {
  9. // This checks the length together with the value from the select field
  10. // When the reason list is changed and the bytelimit is longer than the allowed,
  11. // nothing is done
  12. $root
  13. .find( '.mw-htmlform-select-and-other-field' )
  14. .each( function () {
  15. var $reasonList, currentValReasonList, maxlengthUnit, lengthLimiter, widget,
  16. $this = $( this ),
  17. $widget = $this.closest( '.oo-ui-widget[data-ooui]' );
  18. if ( $widget ) {
  19. mw.loader.using( 'mediawiki.widgets.SelectWithInputWidget', function () {
  20. widget = OO.ui.Widget.static.infuse( $widget );
  21. maxlengthUnit = widget.getData().maxlengthUnit;
  22. lengthLimiter = maxlengthUnit === 'codepoints' ? 'codePointLimit' : 'byteLimit';
  23. widget.textinput.$input[ lengthLimiter ]( function ( input ) {
  24. // Should be built the same as in HTMLSelectAndOtherField::loadDataFromRequest
  25. var comment = widget.dropdowninput.getValue();
  26. if ( comment === 'other' ) {
  27. comment = input;
  28. } else if ( input !== '' ) {
  29. // Entry from drop down menu + additional comment
  30. comment += colonSeparator + input;
  31. }
  32. return comment;
  33. } );
  34. } );
  35. } else {
  36. // find the reason list
  37. $reasonList = $root.find( '#' + $this.data( 'id-select' ) );
  38. // cache the current selection to avoid expensive lookup
  39. currentValReasonList = $reasonList.val();
  40. $reasonList.change( function () {
  41. currentValReasonList = $reasonList.val();
  42. } );
  43. // Select the function for the length limit
  44. maxlengthUnit = $this.data( 'mw-maxlength-unit' );
  45. lengthLimiter = maxlengthUnit === 'codepoints' ? 'codePointLimit' : 'byteLimit';
  46. $this[ lengthLimiter ]( function ( input ) {
  47. // Should be built the same as in HTMLSelectAndOtherField::loadDataFromRequest
  48. var comment = currentValReasonList;
  49. if ( comment === 'other' ) {
  50. comment = input;
  51. } else if ( input !== '' ) {
  52. // Entry from drop down menu + additional comment
  53. comment += colonSeparator + input;
  54. }
  55. return comment;
  56. } );
  57. }
  58. } );
  59. } );
  60. }() );