Полезная информация

В мире Mozilla происходит много интересных событий. Но вам не нужно постоянно посещать новостные сайты, чтобы быть в курсе всех изменений. Зайдите на ленту новостей Mozilla Россия.

№123-05-2014 18:40:33

2k1dmg
Участник
 
Группа: Members
Зарегистрирован: 06-04-2011
Сообщений: 190
UA: Firefox 29.0

[CB] Конвертировать текст в переменную JavaScript

Конвертировать текст в переменную JavaScript 2014-05-23 v24
Совместимость: [firefox] Firefox 24+
Автор: 2k1dmg
Описание: Конвертирует текст (CSS) для вставки в код JavaScript.
Приоритет:

  1. Выделенный текст
  2. Открытый во вкладке текстовый или CSS файл
  3. Текст из буфера обмена

пример
исходный текст:

Выделить код

Код:

#navigator-toolbox {
  -moz-appearance: none;
  background-color: transparent;
  border-top: none;
}

options.cssStringType = 0:

Выделить код

Код:

'#navigator-toolbox {\n' +
'  -moz-appearance: none;\n' +
'  background-color: transparent;\n' +
'  border-top: none;\n' +
'}'

options.cssStringType = 1:

Выделить код

Код:

'\
#navigator-toolbox {\n\
  -moz-appearance: none;\n\
  background-color: transparent;\n\
  border-top: none;\n\
}'


в секцию Код:

Выделить код

Код:

// CSS to JS string - 2014-05-23 v24
// CB code

// icon - http://www.iconsearch.ru/detailed/46532/1/

'use strict';

var options = {
    quotes: 0,
    // 0 - ' - одинарные
    // 1 - " - двойные
    forceQuotes: false,
    // true - если в тексте встречаются
    // выбранные кавычки то заменить их на \' или \"
    new_line: '\\n',
    // \\n
    // \\r\\n
    editor_new_line: 'auto',
    // auto
    // \n
    // \r\n
    converter: 0,
    // 0 - js
    // 1 - regexp
    
    cssStringType: 0, 
    // только если converter = 0
    
    // 0 -
    // = '#navigator-toolbox {\n' +
    // '  -moz-appearance: none;\n' +
    // '}\n';
    
    // 1 -
    // = '\    
    // #navigator-toolbox {\n\
    //   -moz-appearance: none;\n\
    // }\n\';
    // (при значении "1" oneLine игнорируется)
    
    oneLine: false
    // true - результат в одну строку
};

var oneLine = options.oneLine;
if (event.shiftKey) {
    oneLine = !oneLine;
}

function convertCode(str) {
    if (!str) {
        return;
    }
    var quote = (options.quotes === 0) ? '\'' : '"';
    var forceQuotes = function() {
        var re = new RegExp('(' + quote + ')', 'g');
        str = str.replace(re, '\\$1');
    };
    var doforceQuotes;
    if (str.indexOf(quote) != -1) {
        if (options.forceQuotes) {
            forceQuotes();
        }
        else {
            doforceQuotes = confirm('В тексте найдены ' +
                                    ((options.quotes === 0) ? 'одинарные' : 'двойные') +
                                    ' кавычки. Продолжить?');
            if (doforceQuotes) {
                forceQuotes();
            }
            else {
                return;
            }
        }
    }
    var type;
    if (str.indexOf('\r\n') != -1) {
        type = 'win';
    }
    else if (str.indexOf('\r') != -1) {
        type = 'mac';
    }
    else {
        type = 'nix';
    }
    var lastNewLine = (type == 'win') ? '\r\n' :
                        (type == 'mac') ? '\r' : '\n';
    var editor_new_line;
    if (options.editor_new_line == 'auto') {
        editor_new_line = lastNewLine;
    }
    else {
        editor_new_line = options.editor_new_line;
    }

    var converterJS = function() {
        var arr = str.split(lastNewLine);
        if (oneLine) {
            output += quote;
            output += arr.reduce(function(prevStr, curItem) {
                return prevStr + curItem + options.new_line;
            }, '');
            output += quote;
        }
        else {
            output = arr.reduce(function(prevStr, curItem, index, array) {
                return prevStr + quote + curItem +
                        ((index != array.length - 1) ? (options.new_line + quote + ' +') : quote) +
                                editor_new_line;
            }, '');
        }
    };
    
    var converterJS_secondType = function() {
        var arr = str.split(lastNewLine);
        output += arr.reduce(function(prevStr, curItem, index, array) {
            return prevStr + curItem + ((index != array.length - 1) ? '\\n\\' + editor_new_line : '\'');
        }, quote + '\\' + editor_new_line);

    };

    var converterRegExp = function() {
        var pat = (type == 'win') ? '\\r\\n' :
                        (type == 'mac') ? '\\r' : '\\n';
        var re = new RegExp('^([^' + pat + ']*)(' + pat + '|$)', 'gm');
        if (oneLine) {
            output += quote;
            output += str.replace(re, '$1' + options.new_line)
                                .replace(/(\s+$)/g, '');
            output += quote;
        }
        else {
            output = str.replace(re, quote + '$1' + options.new_line + quote + ' +' + editor_new_line)
                                .replace(/(\s+$)/g, '')
                                .replace(/(\s\+$)/g, '');
        }
    };

    var output = '';
    if (options.converter === 0) {
        if (options.cssStringType === 0) {
            converterJS();
        }
        else {
            converterJS_secondType();
        }
        
    }
    else {
        converterRegExp();
    }

    openTab(output);
}

function openTab(output) {
    var uri = 'data:text/plain;charset=utf-8,' + encodeURIComponent(output);
    gBrowser.selectedTab = gBrowser.addTab(uri, makeURI('about:blank'));
}

function isPRE(sourceText) {
    try {
        if (sourceText.anchorNode.parentNode.nodeName.toLowerCase() == 'pre')
            return true;
    }
    catch (ex) {};
    return false;
}

function sourceTextIsPRE(sourceText) {
    var range = sourceText.getRangeAt(0);
    return range.toString();
}

var sourceText = content.getSelection();

if (typeof sourceText == 'object') {
    if (isPRE(sourceText)) {
        sourceText = sourceTextIsPRE(sourceText);
    }
    else {
        sourceText = sourceText.toString();
    }
}

if (sourceText) {
    convertCode(sourceText);
}
else if (content.document &&
            /^(text\/(css|plain))$/.test(content.document.contentType)) {
    sourceText = [content.document.body.textContent];
    if (sourceText) {
        sourceText.forEach(convertCode);
    }
}
else {
    sourceText = gClipboard.read();
    if (sourceText) {
        convertCode(sourceText);
    }
}

Отредактировано 2k1dmg (23-05-2014 18:41:03)

Отсутствует

 

№223-05-2014 23:23:53

2k1dmg
Участник
 
Группа: Members
Зарегистрирован: 06-04-2011
Сообщений: 190
UA: Firefox 29.0

Re: [CB] Конвертировать текст в переменную JavaScript

2014-05-24 v25
+ options.cssStringType = 2:

Выделить код

Код:

[
'#navigator-toolbox {',
'  -moz-appearance: none;',
'  background-color: transparent;',
'  border-top: none;',
'}'
].join('\n')
Выделить код

Код:

// CSS to JS string - 2014-05-24 v25
// CB code

// icon - http://www.iconsearch.ru/detailed/46532/1/

'use strict';

var options = {
    quotes: 0,
    // 0 - ' - одинарные
    // 1 - " - двойные
    forceQuotes: false,
    // true - если в тексте встречаются
    // выбранные кавычки то заменить их на \' или \"
    new_line: '\\n',
    // \\n
    // \\r\\n
    editor_new_line: 'auto',
    // auto
    // \n
    // \r\n
    converter: 0,
    // 0 - js
    // 1 - regexp
    
    cssStringType: 0, 
    // только если converter = 0
    
    // 0 -
    // = '#navigator-toolbox {\n' +
    // '  -moz-appearance: none;\n' +
    // '}\n';
    
    // 1 -
    // = '\    
    // #navigator-toolbox {\n\
    //   -moz-appearance: none;\n\
    // }\n\';

    // 2 -
    // [
    // '#navigator-toolbox {',
    // '  -moz-appearance: none;',
    // '}'
    // ].join('\n')
    
    // (при значениях "1" и "2" oneLine игнорируется)
    
    oneLine: false
    // true - результат в одну строку
};

var oneLine = options.oneLine;
if (event.shiftKey) {
    oneLine = !oneLine;
}

function convertCode(str) {
    if (!str) {
        return;
    }
    var quote = (options.quotes === 0) ? '\'' : '"';
    var forceQuotes = function() {
        var re = new RegExp('(' + quote + ')', 'g');
        str = str.replace(re, '\\$1');
    };
    var doforceQuotes;
    if (str.indexOf(quote) != -1) {
        if (options.forceQuotes) {
            forceQuotes();
        }
        else {
            doforceQuotes = confirm('В тексте найдены ' +
                                    ((options.quotes === 0) ? 'одинарные' : 'двойные') +
                                    ' кавычки. Продолжить?');
            if (doforceQuotes) {
                forceQuotes();
            }
            else {
                return;
            }
        }
    }
    var type;
    if (str.indexOf('\r\n') != -1) {
        type = 'win';
    }
    else if (str.indexOf('\r') != -1) {
        type = 'mac';
    }
    else {
        type = 'nix';
    }
    var lastNewLine = (type == 'win') ? '\r\n' :
                        (type == 'mac') ? '\r' : '\n';
    var editor_new_line;
    if (options.editor_new_line == 'auto') {
        editor_new_line = lastNewLine;
    }
    else {
        editor_new_line = options.editor_new_line;
    }

    var converterJS = function() {
        var arr = str.split(lastNewLine);
        if (oneLine) {
            output += quote;
            output += arr.reduce(function(prevStr, curItem) {
                return prevStr + curItem + options.new_line;
            }, '');
            output += quote;
        }
        else {
            output = arr.reduce(function(prevStr, curItem, index, array) {
                return prevStr + quote + curItem +
                        ((index != array.length - 1) ? (options.new_line + quote + ' +') : quote) +
                                editor_new_line;
            }, '');
        }
    };
    
    var converterJS_Type1 = function() {
        var arr = str.split(lastNewLine);
        output += arr.reduce(function(prevStr, curItem, index, array) {
            return prevStr + curItem + ((index != array.length - 1) ? '\\n\\' + editor_new_line : '\'');
        }, quote + '\\' + editor_new_line);

    };
    
    var converterJS_Type2 = function() {
        var arr = str.split(lastNewLine);
        output += arr.reduce(function(prevStr, curItem, index, array) {
            return prevStr + quote + curItem + ((index != array.length - 1) ? quote + ',' + editor_new_line : 
                        quote + editor_new_line + '].join(\'' + options.new_line + '\')');
        }, '[' + editor_new_line);

    };

    var converterRegExp = function() {
        var pat = (type == 'win') ? '\\r\\n' :
                        (type == 'mac') ? '\\r' : '\\n';
        var re = new RegExp('^([^' + pat + ']*)(' + pat + '|$)', 'gm');
        if (oneLine) {
            output += quote;
            output += str.replace(re, '$1' + options.new_line)
                                .replace(/(\s+$)/g, '');
            output += quote;
        }
        else {
            output = str.replace(re, quote + '$1' + options.new_line + quote + ' +' + editor_new_line)
                                .replace(/(\s+$)/g, '')
                                .replace(/(\s\+$)/g, '');
        }
    };

    var output = '';
    if (options.converter === 0) {
        if (options.cssStringType === 0) {
            converterJS();
        }
        else if (options.cssStringType === 1) {
            converterJS_Type1();
        }
        else {
            converterJS_Type2();
        }
        
    }
    else {
        converterRegExp();
    }

    openTab(output);
}

function openTab(output) {
    var uri = 'data:text/plain;charset=utf-8,' + encodeURIComponent(output);
    gBrowser.selectedTab = gBrowser.addTab(uri, makeURI('about:blank'));
}

function isPRE(sourceText) {
    try {
        if (sourceText.anchorNode.parentNode.nodeName.toLowerCase() == 'pre')
            return true;
    }
    catch (ex) {};
    return false;
}

function sourceTextIsPRE(sourceText) {
    var range = sourceText.getRangeAt(0);
    return range.toString();
}

var sourceText = content.getSelection();

if (typeof sourceText == 'object') {
    if (isPRE(sourceText)) {
        sourceText = sourceTextIsPRE(sourceText);
    }
    else {
        sourceText = sourceText.toString();
    }
}

if (sourceText) {
    convertCode(sourceText);
}
else if (content.document &&
            /^(text\/(css|plain))$/.test(content.document.contentType)) {
    sourceText = [content.document.body.textContent];
    if (sourceText) {
        sourceText.forEach(convertCode);
    }
}
else {
    sourceText = gClipboard.read();
    if (sourceText) {
        convertCode(sourceText);
    }
}


2014-05-24 v27
в секцию Инициализация:

Выделить код

Код:

// CSS to JS string - 2014-05-24 v27
// CB init

// icon - http://www.iconsearch.ru/detailed/46532/1/

'use strict';

var options = {
    quotes: 0,
    // 0 - ' - одинарные
    // 1 - " - двойные
    forceQuotes: false,
    // true - если в тексте встречаются
    // выбранные кавычки то заменить их на \' или \"
    new_line: '\\n',
    // \\n
    // \\r\\n
    editor_new_line: 'auto'
    // auto
    // \n
    // \r\n
};

function convertCode(str, value) {
    if (!str) {
        return;
    }
    var quote = (options.quotes === 0) ? '\'' : '"';
    var forceQuotes = function() {
        var re = new RegExp('(' + quote + ')', 'g');
        str = str.replace(re, '\\$1');
    };
    var doforceQuotes;
    if (str.indexOf(quote) != -1) {
        if (options.forceQuotes) {
            forceQuotes();
        }
        else {
            doforceQuotes = confirm('В тексте найдены ' +
                                    ((options.quotes === 0) ? 'одинарные' : 'двойные') +
                                    ' кавычки. Продолжить?');
            if (doforceQuotes) {
                forceQuotes();
            }
            else {
                return;
            }
        }
    }
    var type;
    if (str.indexOf('\r\n') != -1) {
        type = 'win';
    }
    else if (str.indexOf('\r') != -1) {
        type = 'mac';
    }
    else {
        type = 'nix';
    }
    var lastNewLine = (type == 'win') ? '\r\n' :
                        (type == 'mac') ? '\r' : '\n';
    var editor_new_line;
    if (options.editor_new_line == 'auto') {
        editor_new_line = lastNewLine;
    }
    else {
        editor_new_line = options.editor_new_line;
    }

    var converterJS = function(oneLine) {
        var arr = str.split(lastNewLine);
        if (oneLine) {
            output += quote;
            output += arr.reduce(function(prevStr, curItem) {
                return prevStr + curItem + options.new_line;
            }, '');
            output += quote;
        }
        else {
            output = arr.reduce(function(prevStr, curItem, index, array) {
                return prevStr + quote + curItem +
                        ((index != array.length - 1) ? (options.new_line + quote + ' +') : quote) +
                                editor_new_line;
            }, '');
        }
    };
    
    var converterJS_Type1 = function() {
        var arr = str.split(lastNewLine);
        output += arr.reduce(function(prevStr, curItem, index, array) {
            return prevStr + curItem + ((index != array.length - 1) ? '\\n\\' + editor_new_line : '\'');
        }, quote + '\\' + editor_new_line);

    };
    
    var converterJS_Type2 = function() {
        var arr = str.split(lastNewLine);
        output += arr.reduce(function(prevStr, curItem, index, array) {
            return prevStr + quote + curItem + ((index != array.length - 1) ? quote + ',' + editor_new_line : 
                        quote + editor_new_line + '].join(\'' + options.new_line + '\')');
        }, '[' + editor_new_line);

    };
    
    var converterJS_Type3 = function(oneLine) {
        var arr = str.split(lastNewLine);
        if (oneLine) {
            output += quote;
            output += arr.reduce(function(prevStr, curItem) {
                return prevStr + curItem.replace(/(^\s*)/g, '');
            }, '');
            output += quote;
        }
        else {
            output = arr.reduce(function(prevStr, curItem, index, array) {
                return prevStr + quote + curItem.replace(/(^\s*)/g, '') + 
                    ((index != array.length - 1) ? (quote + ' +') : quote) +
                    editor_new_line;
            }, '');
        }
    };

    var converterRegExp = function(oneLine) {
        var pat = (type == 'win') ? '\\r\\n' :
                        (type == 'mac') ? '\\r' : '\\n';
        var re = new RegExp('^([^' + pat + ']*)(' + pat + '|$)', 'gm');
        if (oneLine) {
            output += quote;
            output += str.replace(re, '$1' + options.new_line)
                                .replace(/(\s+$)/g, '');
            output += quote;
        }
        else {
            output = str.replace(re, quote + '$1' + options.new_line + quote + ' +' + editor_new_line)
                                .replace(/(\s+$)/g, '')
                                .replace(/(\s\+$)/g, '');
        }
    };

    var output = '';

    switch (value) {
        case 'plus':
            converterJS(false);
            break;
        case 'backslash':
            converterJS_Type1();
            break;
        case 'array':
            converterJS_Type2();
            break;
        case 'html':
            converterJS_Type3(false);
            break;
        case 'plus-oneline':
            converterJS(true);
            break;
        case 'html-oneline':
            converterJS_Type3(true);
            break;
        case 'plus-re':
            converterRegExp(false);
            break;
        case 'plus-re-oneline':
            converterRegExp(true);
            break;
    };
    
    openTab(output);
}

function openTab(output) {
    var uri = 'data:text/plain;charset=utf-8,' + encodeURIComponent(output);
    gBrowser.selectedTab = gBrowser.addTab(uri, makeURI('about:blank'));
}

function isPRE(sourceText) {
    try {
        if (sourceText.anchorNode.parentNode.nodeName.toLowerCase() == 'pre')
            return true;
    }
    catch (ex) {};
    return false;
}

function sourceTextIsPRE(sourceText) {
    var range = sourceText.getRangeAt(0);
    return range.toString();
}

function getText(value) {
    var sourceText = content.getSelection();

    if (typeof sourceText == 'object') {
        if (isPRE(sourceText)) {
            sourceText = sourceTextIsPRE(sourceText);
        }
        else {
            sourceText = sourceText.toString();
        }
    }

    if (sourceText) {
        convertCode(sourceText, value);
    }
    else if (content.document &&
                /^(text\/(css|plain))$/.test(content.document.contentType)) {
        sourceText = [content.document.body.textContent];
        if (sourceText) {
            sourceText.forEach(function(str) {
                convertCode(str, value);
            });
        }
    }
    else {
        sourceText = gClipboard.read();
        if (sourceText) {
            convertCode(sourceText, value);
        }
    }
}

// -----------------------------------------------------------------------------

this.type = 'menu';

var btn = this;

this.onclick = function(event) {
    if ( event.button == 0 ) {
        var menuPopup = btn.menuPopup;
        menuPopup.showPopup(this, -1, -1, 'popup', 'bottomleft', 'topleft');
    }
};

(function init() {
    if (document.getElementById(btn.id + '-menuPopup'))
        return;
    var menuPopup = btn.menuPopup = document.getElementById('mainPopupSet')
        .appendChild(document.createElement('menupopup'));
    menuPopup.id = btn.id + '-menuPopup';
}());

function destroy() {
    var menuPopup = btn.menuPopup;
    if (menuPopup && menuPopup.parentNode) {
        menuPopup.parentNode.removeChild(menuPopup);
    }
}

addDestructor(function(reason) {
    destroy();
}, this);

var menuItems = [
    { 
        label: '"+"',
        value: 'plus'
    },
    {
        label: '"\\"',
        value: 'backslash'
    },
    {
        label :'"[].join"',
        value: 'array'
    },
    {
        label :'"html"',
        value: 'html'
    },
    {
        separator: ''
    },
    { 
        label: '"+" oneline',
        value: 'plus-oneline'
    },
    {
        label :'"html" oneline',
        value: 'html-oneline'
    },
    {
        separator: ''
    },
    { 
        label: '"+" regexp',
        value: 'plus-re'
    },
    { 
        label: '"+" regexp oneline',
        value: 'plus-re-oneline'
    }
]; 
menuItems.forEach(function(item) {
    var menuPopup = document.getElementById(btn.id + '-menuPopup');
    
    if ('separator' in item) {
        menuPopup.appendChild( document.createElement('menuseparator') );
        return;
    };
    var menuItem = document.createElement('menuitem');
    menuItem.setAttribute('label', item.label);
    menuItem.value = item.value;    
    menuItem.setAttribute('class', 'menuitem-iconic');    
    
    menuPopup.btn = btn;
    menuPopup.setAttribute('onclick', 'this.btn.textConverter(event, event.target.value);');
    
    menuPopup.appendChild( menuItem );
});

this.textConverter = function(event, value) {
    getText(value);
}

Отредактировано 2k1dmg (24-05-2014 18:40:40)

Отсутствует

 

Board footer

Powered by PunBB
Modified by Mozilla Russia
Copyright © 2004–2020 Mozilla Russia GitHub mark
Язык отображения форума: [Русский] [English]