Đăng Nhập

Vui lòng khai báo chính xác tên truy cập và mật khẩu!

Quên mật khẩu?

Đăng Ký

Bạn phải điền đầy đủ thông tin đăng ký!

  


Search found 3 matches for highlight

[TUTs] Zzhljs - Làm đẹp khung code với highlightjs và clipboardjs - 09.08.16 14:10

Trong forum về code như Devs forumvi thì vấn đề màu mè cho khung code luôn được đặt lên hàng đầu. :D

Trước đây, mình đã có hướng dẫn vài cách ứng dụng các plugin syntax highlighter cho forum, mỗi cái có ưu và nhược điểm riêng, tạm kể ra vài tội như:
- Google Code Prettify: Tự nhận diện ngôn ngữ nhưng không chính xác lắm, xử lý rất chậm khi gặp code dài, kích thước file js lớn.
- Prismjs: Lỗi ở một số mã Regexp phức tạp, không tự nhận diện ngôn ngữ.
- CodeMirror: Không tự nhận diện ngôn ngữ, kích thước file js khá lớn.

Hôm nay mình sẽ hướng dẫn cách dùng highlightjs, một plugin syntax highlighter khắc phục được các nhược điểm trên.


Demo


Topics tagged under highlight on Zzbaivong forumvi 2xpXfbr
Ảnh minh họa highlight code với ngôn ngữ PHP


Tính năng


  1. Hỗ trợ 146 ngôn ngữ và 66 giao diện (Xem ví dụ).
  2. Tự động nhận diện ngôn ngữ.
  3. Kích thước file js nhỏ ~17Kb.
  4. Sao chép nhanh dùng Clipboard.


Hạn chế


  1. Không hỗ trợ phpBB2. Do cấu trúc phpBB2 khác biệt với 3 mã nguồn còn lại, và ít người dùng nên mình không làm.
  2. Làm nổi bật cú pháp không chi tiết bằng 3 plugin mình giới thiệu trước đây.
  3. Không có các tính năng phụ như: số dòng, tìm dòng, chọn giao diện, chọn toàn bộ (đã thay bằng nút copy). Mình thấy các tính năng này ít dùng, lại làm chậm xử lý nên bỏ bớt cho nó nuột.



Hướng dẫn


ACP >> Display >> QLTT >> overall_header

Tìm:
Code:
<script src="{JQUERY_PATH}" type="text/javascript"></script>
<script src="{JS_DIR}{L_LANG}.js" type="text/javascript"></script>


Và thêm vào bên dưới nó, code sau:
Code:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/styles/github-gist.min.css">
<style>
/* Zzhljs - http://devs.forumvi.com */
dl.codebox:not(.spoiler) dt {
    display: none;
}
dl.codebox:not(.spoiler) dd {
    border: 0 none;
    background: #f8f8f8;
    position: relative;
    max-height: 100%;
}
.clipboard {
    display: block;
    color: #333;
    position: absolute;
    right: 4px;
    top: 4px;
    background: url(http://i.imgur.com/o9NOYtH.png) no-repeat center center #eee;
    border: 1px solid #D5D5D5;
    width: 30px;
    height: 30px;
    text-align: center;
    border-radius: 3px;
    transition: opacity 0.3s ease-in-out 0s;
    opacity: 0;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
    -webkit-appearance:none;
    cursor: pointer;
}
.clipboard.check-circle {
    background-image: url(http://i.imgur.com/CBEkyLH.png);
}
.clipboard.exclamation-triangle {
    background-image: url(http://i.imgur.com/QQkE9Wj.png);
}
dl.codebox:not(.spoiler) dd:hover .clipboard {
    opacity: 1;
}
.clipboard:hover {
    background-color:#ddd;
    border-color:#ccc;
}
.hljs {
    background: #f8f8f8;
}
dl.codebox:not(.spoiler) code,
.codebox:not(.spoiler) dd.cont_code {
    max-height: 100%;
    margin: 0;
}
.codebox:not(.spoiler) {
    background-color: transparent;
    border: 0 none;
    margin: 0;
}
</style>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/highlight.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.5/clipboard.min.js"></script>
<script>
/* Zzhljs - http://devs.forumvi.com */
jQuery(function($){
    var $code = $("code");
    if ($code.length) {
        hljs.configure({
            useBR: true
        });
        $code.each(function (i, block) {
            hljs.highlightBlock(block);
        });

        function fallbackMessage(action) {
            var actionMsg = '';
            var actionKey = (action === 'cut' ? 'X' : 'C');

            if (/iPhone|iPad/i.test(navigator.userAgent)) {
                actionMsg = 'No support!';
            } else if (/Mac/i.test(navigator.userAgent)) {
                actionMsg = 'Press ⌘-' + actionKey + ' to ' + action;
            } else {
                actionMsg = 'Press Ctrl-' + actionKey + ' to ' + action;
            }

            return actionMsg;
        }

        function afterClipboard(ele) {
            setTimeout(function(){
                ele.className = 'clipboard clipboard';
            }, 400);
        }

        var snippets = document.querySelectorAll('.codebox:not(.spoiler) > dd');

        [].forEach.call(snippets, function (snippet) {
            snippet.firstChild.insertAdjacentHTML('beforebegin', '<i class="clipboard clipboard" data-clipboard></i>');
        });

        var clipboardSnippets = new Clipboard('[data-clipboard]', {
            target: function (trigger) {
                return trigger.nextElementSibling;
            }
        });

        clipboardSnippets.on('success', function (e) {
            e.clearSelection();
            e.trigger.className = 'clipboard check-circle';
            afterClipboard(e.trigger);
        });

        clipboardSnippets.on('error', function (e) {
            e.trigger.className = 'clipboard exclamation-triangle';
            afterClipboard(e.trigger);
            alert(fallbackMessage(e.action));
        });
    }
});
</script>



Tài nguyên

Icon từ FlatIcon.
Javascript plugin HighlightJsClipboardJs.
Ứng dụng cho Forumotion viết bởi Zzbaivong.
Tags: #mod #template #tutorial #highlight #clipboard #hljs

[Userscript] View source kiểu Chromium cho Firefox - 21.08.15 13:49

View-source trong Firefox có điểm bất tiện là, mở trong cửa sổ mới, và các liên kết trong đó đều ở dạng view-source. Vì thế mình viết script này theo kiểu của Chromium, bổ sung thêm tính năng định dạng code.


Demo


Topics tagged under highlight on Zzbaivong forumvi G7PNESO
Source đã được format

Gợi ý: Nhấn Ctrl+Y hoặc chọn trên menu User script command.
Nên sử dụng chung với js-css beautify


Cài đặt


Dùng một trong các link sau:

  1. https://greasyfork.org/vi/scripts/16112-viewsource
  2. https://openuserjs.org/scripts/baivong/viewsource
  3. https://github.com/baivong/Userscript/raw/master/view_source/view_source.user.js


Mã nguồn


Code:
// ==UserScript==
// @id           view-source@devs.forumvi.com
// @name         viewsource
// @namespace    devs.forumvi.com
// @description  View and beauty website source code. Support to see the source code by holding the right mouse and drag. Shortcut: Alt+U.
// @version      2.3.6
// @icon         http://i.imgur.com/6yZMOeH.png
// @author       Zzbaivong
// @license      MIT
// @match        http://*/*
// @match        https://*/*
// @resource     light https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/github-gist.min.css
// @resource     dark https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/monokai-sublime.min.css
// @require      https://greasyfork.org/scripts/18530-beautify-html/code/beautify-html.js?version=117787
// @require      https://greasyfork.org/scripts/18531-beautify-js/code/beautify-js.js?version=117786
// @require      https://greasyfork.org/scripts/18528-beautify-css/code/beautify-css.js?version=117789
// @require      https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js
// @noframes
// @connect      self
// @supportURL   https://github.com/baivong/Userscript/issues
// @run-at       document-idle
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function () {

    'use strict';

    var theme = 'light', // light|dark

        win = window,
        urlpage = location.href,
        doc = document,
        wrapcontent = doc.documentElement,
        content = doc.body;

    function scrollByDragging(container, disableH, disableV) {

        function mouseUp(e) {
            if (e.which !== 3) return;

            window.removeEventListener('mousemove', mouseMove, true);
            container.style.cursor = 'default';
        }

        function mouseDown(e) {
            if (e.which !== 3) return;

            pos = {
                x: e.clientX,
                y: e.clientY
            };

            window.addEventListener('mousemove', mouseMove, true);
            container.style.cursor = 'move';
        }

        function mouseMove(e) {
            if (!disableH) container.scrollLeft -= (-pos.x + (pos.x = e.clientX));
            if (!disableV) container.scrollTop -= (-pos.y + (pos.y = e.clientY));
        }

        var pos = {
            x: 0,
            y: 0
        };

        container.oncontextmenu = function (e) {
            e.preventDefault();
        };

        container.addEventListener('mousedown', mouseDown, false);
        window.addEventListener('mouseup', mouseUp, false);

    }

    function removeEvents(ele, attr) {
        var events = 'onafterprint onbeforeprint onbeforeunload onerror onhashchange onload onmessage onoffline ononline onpagehide onpageshow onpopstate onresize  onstorage onunload onblur onchange oncontextmenu onfocus oninput oninvalid onreset onsearch onselect onsubmit onkeydown onkeypress onkeyup onclick ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onscroll onwheel oncopy oncut onpaste onerror onshow ontoggle'.split(' '),
            x;
        for (x in events) {
            var _event = events[x];
            ele[_event] = null;
            if (attr) {
                ele.removeAttribute(_event);
            }
        }
    }

    function viewsource() {
        GM_xmlhttpRequest({
            method: 'GET',
            url: urlpage,
            onload: function (response) {

                removeEvents(win);
                removeEvents(doc);
                removeEvents(wrapcontent, true);
                removeEvents(content, true);

                var txt = html_beautify(response.response);

                doc.head.innerHTML = '';
                content.innerHTML = '';
                content.removeAttribute('id');
                content.removeAttribute('class');
                content.removeAttribute('style');
                doc.title = 'view-source:' + urlpage;

                GM_addStyle(GM_getResourceText(theme) + 'html,body,pre{margin:0;padding:0}.hljs{word-wrap:normal!important;white-space:pre!important;padding-left:4em;line-height:100%}.hljs::before{content:attr(data-lines);position:absolute;color:#d2d2d2;text-align:right;width:3.5em;left:-.5em;border-right:1px solid rgba(221, 221, 221, 0.36);padding-right:.5em}');

                var output = doc.createElement('PRE');
                output.setAttribute('class', 'xml');
                output.textContent = txt;

                content.appendChild(output);

                hljs.highlightBlock(output);

                var lines = txt.split('\n'),
                    l = '';
                lines = lines ? lines.length : 0;
                for (var i = 0; i < lines; i++) {
                    l += (i + 1) + '\n';
                }

                output.setAttribute('data-lines', l);
                output.style.width = output.scrollWidth + 'px';

                scrollByDragging(content);
                scrollByDragging(wrapcontent);

                var attrUrl = doc.getElementsByClassName('hljs-attr');
                for (var j = 0; j < attrUrl.length; j++) {
                    if (/\b(src|href\b)/.test(attrUrl[j].textContent)) {
                        var link = attrUrl[j].nextSibling.nextSibling;
                        var url = link.textContent.slice(1, -1);
                        link.innerHTML = '<a href="' + url + '" target="_blank">' + url + '</a>';
                    }
                }

            }
        });
    }

    GM_registerMenuCommand('View source', viewsource, 'u');

    if (/^application\/(xhtml+xml|xml|rss+xml)|text\/(html|xml)$/.test(doc.contentType)) {
        doc.onkeydown = function (e) {

            // Alt+U
            if (e.which === 85 && e.altKey) {
                e.preventDefault();

                viewsource();
            }
        };
    }

}());

Chú ý: Bạn có thể chọn giao diện Dark hoặc Light bằng cách sửa tham số theme ở dòng 25.


Credits


  1. jsBeautifier
  2. highlightJs

Tags: #userscript #firefox #highlight #beautify

[Userscript] Javascript-css beautify - 21.08.15 13:47

Javascript-css beautify chỉ hoạt động với các URL file js/json/css. Tác dụng của nó là định dạng và làm nổi cú pháp trong code, giúp việc đọc code thuận tiện hơn.


Demo


Topics tagged under highlight on Zzbaivong forumvi Z2fhzSR
File CSS

Topics tagged under highlight on Zzbaivong forumvi Rt0HUaw
File Javascript


Cài đặt

Dùng một trong các link sau:

  1. https://greasyfork.org/vi/scripts/16111-javascript-css-beautify
  2. https://openuserjs.org/scripts/baivong/Javascript-css_beautify
  3. https://github.com/baivong/Userscript/raw/master/js-css_beautify/js-css_beautify.user.js


Mã nguồn


Code:
// ==UserScript==
// @id           javascript-css-beautify@devs.forumvi.com
// @name         Javascript-css beautify
// @namespace    http://devs.forumvi.com
// @description  Beautify and syntax highlighting for source code javascript, json, css. Support to see the source code by holding the right mouse and drag.
// @version      2.3.6
// @icon         http://i.imgur.com/kz8nqz1.png
// @author       Zzbaivong
// @license      MIT
// @match        http://*/*
// @match        https://*/*
// @resource     light https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/github-gist.min.css
// @resource     dark https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/monokai-sublime.min.css
// @require      https://greasyfork.org/scripts/18531-beautify-js/code/beautify-js.js?version=117786
// @require      https://greasyfork.org/scripts/18528-beautify-css/code/beautify-css.js?version=117789
// @require      https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js
// @noframes
// @supportURL   https://github.com/baivong/Userscript/issues
// @run-at       document-idle
// @grant        GM_addStyle
// @grant        GM_getResourceText
// ==/UserScript==

(function () {

    'use strict';

    var theme = 'light', // light|dark

        url = location.pathname,
        doc = document,
        contenttype = doc.contentType;

    function scrollByDragging(container, disableH, disableV) {

        function mouseUp(e) {
            if (e.which !== 3) return;

            window.removeEventListener('mousemove', mouseMove, true);
            container.style.cursor = 'default';
        }

        function mouseDown(e) {
            if (e.which !== 3) return;

            pos = {
                x: e.clientX,
                y: e.clientY
            };

            window.addEventListener('mousemove', mouseMove, true);
            container.style.cursor = 'move';
        }

        function mouseMove(e) {
            if (!disableH) container.scrollLeft -= (-pos.x + (pos.x = e.clientX));
            if (!disableV) container.scrollTop -= (-pos.y + (pos.y = e.clientY));
        }

        var pos = {
            x: 0,
            y: 0
        };

        container.oncontextmenu = function (e) {
            e.preventDefault();
        };

        container.addEventListener('mousedown', mouseDown, false);
        window.addEventListener('mouseup', mouseUp, false);

    }

    if (/^application\/(x-javascript|javascript|json)|text\/css$/.test(contenttype) || (/.+\.(js|json|css)$/.test(url) && !/^application\/(xhtml+xml|xml|rss+xml)|text\/(html|xml)$/.test(contenttype))) {

        var output = doc.getElementsByTagName('pre')[0],
            txt = output.textContent,
            lang = 'javascript',
            lines = 0,
            l = '';

        GM_addStyle(GM_getResourceText(theme) + 'html,body,pre{margin:0;padding:0}.hljs{word-wrap:normal!important;white-space:pre!important;padding-left:4em;line-height:100%}.hljs::before{content:attr(data-lines);position:absolute;color:#d2d2d2;text-align:right;width:3.5em;left:-.5em;border-right:1px solid rgba(221, 221, 221, 0.36);padding-right:.5em}');

        if (contenttype === 'text/css' || /.+\.css$/.test(url)) {
            lang = 'css';
            txt = css_beautify(txt);
        } else {
            txt = js_beautify(txt);
        }

        output.textContent = txt;
        output.setAttribute('class', lang);

        hljs.highlightBlock(output);

        lines = txt.split('\n');
        lines = lines ? lines.length : 0;
        for (var i = 0; i < lines; i++) {
            l += (i + 1) + '\n';
        }

        output.setAttribute('data-lines', l);
        output.style.width = output.scrollWidth + 'px';

        scrollByDragging(doc.body);
        scrollByDragging(doc.documentElement);

    }

}());

Chú ý: Bạn có thể chọn giao diện Dark hoặc Light bằng cách sửa tham số theme ở dòng 22.


Credits


  1. jsBeautifier
  2. highlightJs
  3. Devs forumvi

Tags: #Userscript #firefox #highlight #beautify #chromium


Back to top