all files / htmlcs/lib/rules/ title-required.js

100% Statements 21/21
100% Branches 21/21
100% Functions 2/2
100% Lines 21/21
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                      103× 103× 94×                 39× 39× 33×                        
/**
 * @file rule: title-required
 * @author nighca<nighca@live.cn>
 */
 
module.exports = {
 
    name: 'title-required',
 
    desc: '<title> required.',
 
    lint: function (getCfg, document, reporter) {
        var head = document.querySelector('head');
        if (!head || !getCfg(head)) {
            return;
        }
 
        var title = head.querySelector('title');
        var charsetMeta = head.querySelector('meta[charset]');
 
        if (!title) {
            reporter.warn(head.startIndex, '024', '<title> required.');
        }
        else if (!charsetMeta || title.previousElementSibling !== charsetMeta) {
            reporter.warn(title.startIndex, '025', '<title> should be just after <meta> charset.');
        }
    },
 
    format: function (getCfg, document, options) {
        var head = document.querySelector('head');
        if (!head || !getCfg(head)) {
            return;
        }
 
        var title = head.querySelector('title');
        var charsetMeta = head.querySelector('meta[charset]');
 
        if (!title) {
            title = document.createElement('title');
        }
 
        var firstChild = charsetMeta && charsetMeta.nextSibling || head.firstChild;
        if (firstChild) {
            head.insertBefore(title, firstChild);
        }
        else {
            head.appendChild(title);
        }
    }
 
};