all files / htmlcs/lib/rules/ doctype.js

100% Statements 27/27
95.45% Branches 21/22
100% Functions 4/4
100% Lines 27/27
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                            103× 95×                                     39× 39×   39× 37×                  
/**
 * @file rule: doctype
 * @author nighca<nighca@live.cn>
 */
 
module.exports = {
 
    name: 'doctype',
 
    desc: 'DOCTYPE needed.',
 
    target: 'parser',
 
    lint: function (getCfg, parser, reporter) {
 
        if (!getCfg()) {
            return;
        }
 
        var doctype = false;
        var html = false;
 
        parser.on('processinginstruction', function (name, data) {
 
            Eif (name === '!doctype') {
 
                var index = this.startIndex;
 
                data = data.split(/\s/);
                doctype = (data[0]).trim();
                html = (data[1]).trim().toLowerCase();
 
                if (getCfg('doctype') === 'upper' && doctype !== '!DOCTYPE') {
                    reporter.warn(index, '041', 'DOCTYPE must be uppercase.');
                }
 
                if (data.length !== 2 || html !== 'html') {
                    reporter.warn(index, '041', 'DOCTYPE must be html5.');
                }
            }
        });
 
        parser.on('end', function () {
            if (!doctype) {
                reporter.warn(0, '009', 'DOCTYPE needed.');
            }
        });
    },
 
    format: function (getCfg, document, options) {
        var doctype = document.doctype;
        var html = document.querySelector('html');
 
        if (!html || !getCfg(html) || doctype && doctype.name === 'html') {
            return;
        }
 
        if (doctype) {
            doctype.name = 'html';
        }
        else {
            doctype = document.implementation.createDocumentType('html', '', '');
            document.insertBefore(doctype, document.firstElementChild);
            document.doctype = doctype;
        }
    }
 
};