Копипаста:Лурк:Участник:Asq13/summaryBytesLeft.js

Материал из Неолурк, народный Lurkmore
Перейти к навигации Перейти к поиску

/**

* summaryBytesLeft.js — 13.07.2016
* By Jack who built the house
* 
* Чтобы сделать количество байт видимым, только когда их остаётся немного, добавьте в свой common.js строчку
*   var summaryBytesLeft_margin = 50;
* (50 — количество оставшихся байт; счётчик плавно появится на подходе к этой цифре).
*/

(function() { function byteLength(str) {

   return str.replace(/[\u0080-\u07FF\uD800-\uDFFF]/g, '**').replace(/[\u0800-\uD7FF\uE000-\uFFFF]/g, '***').length;

}

function updateCounter(maxLength) { if (!maxLength) maxLength = $wpSummary.attr('maxlength'); summary = $wpSummary.val(); bytesLeft = maxLength - byteLength(summary); $summaryBytesLeft.text(bytesLeft);

if (summaryBytesLeft_margin < maxLength) { var grayShade = 153; // rgb(153, 153, 153) = #999999 var darkenRange = 31; // Better to end with 1 in order that the first round number will not be the color of background. var bgColor = $('.editOptions').css('background-color').match(/\d+/)[0] || 240; var colorDifference = bgColor - grayShade; var startDarkenAt = summaryBytesLeft_margin + darkenRange; var colorCode = Math.round( bgColor - ( ( (startDarkenAt - Math.min( Math.max(bytesLeft, summaryBytesLeft_margin), startDarkenAt ) ) / darkenRange) * colorDifference) ); $summaryBytesLeft.css('color', 'rgb(' + colorCode + ', ' + colorCode + ', ' + colorCode + ')'); } }

if ($.inArray(mw.config.get('wgAction'), ['edit', 'submit']) != -1 && location.search.indexOf('section=new') == -1) {

   if (typeof summaryBytesLeft_margin == 'undefined')
   	window.summaryBytesLeft_margin = 1000; // Set to >=255 to make the counter be apparent regardless of the number of bytes left.

var $wpSummary = $('#wpSummary'); $('#wpSummaryLabel label').append(''); var $summaryBytesLeft = $('#summaryBytesLeft');

updateCounter(255); // Turns out the summary input maxlength is changed dynamically. // On load, it is 200, then 255, so we better use 255 explicitly // here instead of $wpSummary.attr('maxlength'). $wpSummary.on('input keyup keydown change mouseup cut paste focus blur', function() { updateCounter(); });

$(document).ready(function() { $('#userSummaryButtonsA').on('click', function(event) { $wpSummary.trigger('change'); }); }); } })();