stylus/edit/lint.js

433 lines
14 KiB
JavaScript
Raw Normal View History

2017-08-26 14:49:14 +00:00
/* global CodeMirror messageBox */
/* global editors makeSectionVisible showCodeMirrorPopup showHelp */
/* global stylelintDefaultConfig csslintDefaultRuleConfig onDOMscripted injectCSS require */
2017-08-16 21:01:45 +00:00
'use strict';
2017-08-17 19:08:48 +00:00
function initLint() {
2017-08-20 18:32:41 +00:00
$('#lint-help').addEventListener('click', showLintHelp);
$('#lint').addEventListener('click', gotoLintIssue);
2017-08-16 21:01:45 +00:00
window.addEventListener('resize', resizeLintReport);
2017-08-23 22:13:55 +00:00
$('#linter-settings').addEventListener('click', openStylelintSettings);
2017-08-16 21:01:45 +00:00
// touch devices don't have onHover events so the element we'll be toggled via clicking (touching)
if ('ontouchstart' in document.body) {
2017-08-20 18:32:41 +00:00
$('#lint h2').addEventListener('click', toggleLintReport);
2017-08-16 21:01:45 +00:00
}
2017-08-23 22:13:55 +00:00
// initialize storage of rules
BG.chromeSync.getValue('editorStylelintRules').then(rules => setStylelintRules(rules));
BG.chromeSync.getValue('editorCSSLintRules').then(ruleset => setCSSLintRules(ruleset));
2017-08-17 19:08:48 +00:00
}
function setStylelintRules(rules) {
// can't use default parameters, because rules may be null
if (Object.keys(rules || []).length === 0 && typeof stylelintDefaultConfig !== 'undefined') {
2017-08-17 19:08:48 +00:00
rules = deepCopy(stylelintDefaultConfig.rules);
}
BG.chromeSync.setValue('editorStylelintRules', rules);
return rules;
2017-08-16 21:01:45 +00:00
}
function setCSSLintRules(ruleset) {
if (Object.keys(ruleset || []).length === 0 && typeof csslintDefaultRuleConfig !== 'undefined') {
ruleset = Object.assign({}, csslintDefaultRuleConfig);
2017-08-23 22:13:55 +00:00
}
BG.chromeSync.setValue('editorCSSLintRules', ruleset);
2017-08-23 22:13:55 +00:00
return ruleset;
}
2017-08-18 15:39:39 +00:00
function getLinterConfigForCodeMirror(name) {
2017-08-20 14:06:17 +00:00
return CodeMirror.lint && CodeMirror.lint[name] ? {
2017-08-16 21:01:45 +00:00
getAnnotations: CodeMirror.lint[name],
delay: prefs.get('editor.lintDelay')
2017-08-20 14:06:17 +00:00
} : false;
2017-08-16 21:01:45 +00:00
}
2017-08-23 22:13:55 +00:00
function updateLinter(linter) {
2017-08-20 14:06:17 +00:00
function updateEditors() {
2017-08-23 22:13:55 +00:00
const options = getLinterConfigForCodeMirror(linter);
2017-08-20 14:06:17 +00:00
CodeMirror.defaults.lint = options === 'null' ? false : options;
editors.forEach(cm => {
// set lint to "null" to disable
cm.setOption('lint', options);
2017-08-20 18:56:18 +00:00
// enabling/disabling linting changes the gutter width
cm.refresh();
2017-08-20 14:06:17 +00:00
updateLintReport(cm, 200);
});
}
// load scripts
2017-08-23 22:13:55 +00:00
loadSelectedLinter(linter).then(() => {
2017-08-20 14:06:17 +00:00
updateEditors();
2017-08-17 19:08:48 +00:00
});
$('#linter-settings').style.display = linter === 'null' ? 'none' : 'inline-block';
2017-08-17 19:08:48 +00:00
}
2017-08-16 21:01:45 +00:00
function updateLintReport(cm, delay) {
if (delay === 0) {
// immediately show pending csslint/stylelint messages in onbeforeunload and save
update(cm);
return;
}
if (delay > 0) {
setTimeout(cm => {
cm.performLint();
update(cm);
}, delay, cm);
2017-08-16 21:01:45 +00:00
return;
}
// eslint-disable-next-line no-var
var state = cm.state.lint;
if (!state) {
return;
}
// user is editing right now: postpone updating the report for the new issues (default: 500ms lint + 4500ms)
// or update it as soon as possible (default: 500ms lint + 100ms) in case an existing issue was just fixed
clearTimeout(state.reportTimeout);
state.reportTimeout = setTimeout(update, state.options.delay + 100, cm);
state.postponeNewIssues = delay === undefined || delay === null;
function update(cm) {
const scope = cm ? [cm] : editors;
let changed = false;
let fixedOldIssues = false;
scope.forEach(cm => {
const scopedState = cm.state.lint || {};
const oldMarkers = scopedState.markedLast || {};
const newMarkers = {};
const html = !scopedState.marked || scopedState.marked.length === 0 ? '' : '<tbody>' +
scopedState.marked.map(mark => {
const info = mark.__annotation;
const isActiveLine = info.from.line === cm.getCursor().line;
const pos = isActiveLine ? 'cursor' : (info.from.line + ',' + info.from.ch);
// stylelint rule added in parentheses at the end; extract it out for the stylelint info popup
2017-08-23 22:13:55 +00:00
const lintRuleName = info.message
.substring(info.message.lastIndexOf('('), info.message.length)
.replace(/[()]/g, '');
const title = escapeHtml(info.message);
const message = title.length > 100 ? title.substr(0, 100) + '...' : title;
2017-08-16 21:01:45 +00:00
if (isActiveLine || oldMarkers[pos] === message) {
delete oldMarkers[pos];
}
newMarkers[pos] = message;
return `<tr class="${info.severity}">
2017-08-23 22:13:55 +00:00
<td role="severity" data-rule="${lintRuleName}">
<div class="CodeMirror-lint-marker-${info.severity}">${info.severity}</div>
2017-08-16 21:01:45 +00:00
</td>
<td role="line">${info.from.line + 1}</td>
<td role="sep">:</td>
<td role="col">${info.from.ch + 1}</td>
<td role="message" title="${title}">${message}</td>
2017-08-16 21:01:45 +00:00
</tr>`;
}).join('') + '</tbody>';
scopedState.markedLast = newMarkers;
fixedOldIssues |= scopedState.reportDisplayed && Object.keys(oldMarkers).length > 0;
if (scopedState.html !== html) {
scopedState.html = html;
changed = true;
}
});
if (changed) {
clearTimeout(state ? state.renderTimeout : undefined);
if (!state || !state.postponeNewIssues || fixedOldIssues) {
renderLintReport(true);
} else {
state.renderTimeout = setTimeout(() => {
renderLintReport(true);
}, CodeMirror.defaults.lintReportDelay);
}
}
}
function escapeHtml(html) {
const chars = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;'};
return html.replace(/[&<>"'/]/g, char => chars[char]);
}
}
function renderLintReport(someBlockChanged) {
2017-08-20 18:32:41 +00:00
const container = $('#lint');
2017-08-16 21:01:45 +00:00
const content = container.children[1];
const label = t('sectionCode');
const newContent = content.cloneNode(false);
let issueCount = 0;
editors.forEach((cm, index) => {
if (cm.state.lint && cm.state.lint.html) {
const html = '<caption>' + label + ' ' + (index + 1) + '</caption>' + cm.state.lint.html;
const newBlock = newContent.appendChild(tHTML(html, 'table'));
newBlock.cm = cm;
issueCount += newBlock.rows.length;
const block = content.children[newContent.children.length - 1];
const blockChanged = !block || cm !== block.cm || html !== block.innerHTML;
someBlockChanged |= blockChanged;
cm.state.lint.reportDisplayed = blockChanged;
}
});
if (someBlockChanged || newContent.children.length !== content.children.length) {
2017-08-20 18:32:41 +00:00
$('#issue-count').textContent = issueCount;
2017-08-16 21:01:45 +00:00
container.replaceChild(newContent, content);
container.style.display = newContent.children.length ? 'block' : 'none';
2017-08-17 19:47:45 +00:00
resizeLintReport();
2017-08-16 21:01:45 +00:00
}
}
2017-08-17 19:47:45 +00:00
function resizeLintReport() {
2017-08-20 18:56:18 +00:00
// subtracted value to prevent scrollbar
const magicBuffer = 20;
2017-08-17 19:47:45 +00:00
const content = $('#lint table');
if (content) {
2017-08-16 21:01:45 +00:00
const bounds = content.getBoundingClientRect();
2017-08-17 19:47:45 +00:00
const newMaxHeight = bounds.bottom <= window.innerHeight ? '' :
// subtract out a bit of padding or the vertical scrollbar extends beyond the viewport
(window.innerHeight - bounds.top - magicBuffer) + 'px';
2017-08-16 21:01:45 +00:00
if (newMaxHeight !== content.style.maxHeight) {
2017-08-17 19:47:45 +00:00
content.parentNode.style.maxHeight = newMaxHeight;
2017-08-16 21:01:45 +00:00
}
}
}
function gotoLintIssue(event) {
const issue = event.target.closest('tr');
if (!issue) {
return;
}
const block = issue.closest('table');
makeSectionVisible(block.cm);
block.cm.focus();
block.cm.setSelection({
2017-08-20 18:32:41 +00:00
line: parseInt($('td[role="line"]', issue).textContent) - 1,
ch: parseInt($('td[role="col"]', issue).textContent) - 1
2017-08-16 21:01:45 +00:00
});
}
function toggleLintReport() {
2017-08-20 18:32:41 +00:00
$('#lint').classList.toggle('collapsed');
2017-08-16 21:01:45 +00:00
}
function showLintHelp() {
2017-08-23 22:13:55 +00:00
const makeLink = (url, txt) => `<a target="_blank" href="${url}">${txt}</a>`;
const linter = prefs.get('editor.linter');
const url = linter === 'stylelint'
? 'https://stylelint.io/user-guide/rules/'
// some CSSLint rules do not have a url
: 'https://github.com/CSSLint/csslint/issues/535';
const rules = [];
let template;
2017-08-16 21:01:45 +00:00
let list = '<ul class="rules">';
let header = '';
2017-08-23 22:13:55 +00:00
if (linter === 'csslint') {
2017-08-26 14:49:14 +00:00
const CSSLintRules = window.CSSLint.getRules();
2017-08-25 23:54:37 +00:00
const findCSSLintRule = id => CSSLintRules.find(rule => rule.id === id);
2017-08-26 16:48:32 +00:00
header = t('linterIssuesHelp', makeLink('https://github.com/CSSLint/csslint/wiki/Rules-by-ID', 'CSSLint'));
2017-08-23 22:13:55 +00:00
template = ruleID => {
const rule = findCSSLintRule(ruleID);
return rule ? `<li><b>${makeLink(rule.url || url, rule.name)}</b><br>${rule.desc}</li>` : '';
};
2017-08-16 21:01:45 +00:00
} else {
2017-08-26 16:48:32 +00:00
header = t('linterIssuesHelp', makeLink(url, 'stylelint'));
2017-08-23 22:13:55 +00:00
template = rule => `<li>${makeLink(url + rule, rule)}</li>`;
2017-08-16 21:01:45 +00:00
}
2017-08-23 22:13:55 +00:00
// to-do: change this to a generator
$$('#lint td[role="severity"]').forEach(el => {
const rule = el.dataset.rule;
if (!rules.includes(rule)) {
list += template(rule);
rules.push(rule);
}
});
2017-08-26 16:48:32 +00:00
return showHelp(t('linterIssues'), header + list + '</ul>');
2017-08-16 21:01:45 +00:00
}
2017-08-17 19:08:48 +00:00
function showLinterErrorMessage(title, contents) {
messageBox({
title,
contents,
className: 'danger center lint-config',
buttons: [t('confirmOK')],
});
}
function showSavedMessage() {
$('#help-popup .saved-message').classList.add('show');
clearTimeout($('#help-popup .contents').timer);
$('#help-popup .contents').timer = setTimeout(() => {
// popup may be closed at this point
const msg = $('#help-popup .saved-message');
if (msg) {
msg.classList.remove('show');
}
}, 2000);
}
2017-08-23 22:13:55 +00:00
function checkLinter(linter = prefs.get('editor.linter')) {
linter = linter.toLowerCase();
if (prefs.get('editor.linter') !== linter) {
prefs.set('editor.linter', linter);
}
return linter;
}
function checkRules(linter, rules) {
const invalid = [];
const linterRules = linter === 'stylelint'
? Object.keys(window.stylelint.rules)
2017-08-26 14:49:14 +00:00
: window.CSSLint.getRules().map(rule => rule.id);
Object.keys(rules).forEach(rule => {
if (!linterRules.includes(rule)) {
invalid.push(rule);
}
});
return invalid;
}
2017-08-26 14:30:33 +00:00
function stringifyRules(rules) {
2017-08-26 14:37:32 +00:00
return JSON.stringify(rules, null, 2)
.replace(/,\n\s+\{\n\s+("severity":\s"\w+")\n\s+\}/g, ', {$1}');
2017-08-26 14:30:33 +00:00
}
2017-08-23 22:13:55 +00:00
function setupLinterSettingsEvents(popup) {
2017-08-20 18:32:41 +00:00
$('.save', popup).addEventListener('click', event => {
2017-08-18 15:46:09 +00:00
event.preventDefault();
2017-08-23 22:13:55 +00:00
const linter = checkLinter(event.target.dataset.linter);
const json = tryJSONparse(popup.codebox.getValue());
2017-08-26 14:30:33 +00:00
if (json) {
const invalid = checkRules(linter, json);
if (invalid.length) {
return showLinterErrorMessage(
linter,
2017-08-26 16:48:32 +00:00
t('linterInvalidRuleError') + `<ul><li>${invalid.join('</li><li>')}</li></ul>`
);
}
2017-08-23 22:13:55 +00:00
if (linter === 'stylelint') {
2017-08-26 14:30:33 +00:00
setStylelintRules(json);
2017-08-23 22:13:55 +00:00
} else {
2017-08-26 14:30:33 +00:00
setCSSLintRules(json);
2017-08-17 19:08:48 +00:00
}
2017-08-23 22:13:55 +00:00
updateLinter(linter);
showSavedMessage();
2017-08-18 15:44:19 +00:00
} else {
2017-08-26 16:48:32 +00:00
showLinterErrorMessage(linter, t('linterJSONError'));
2017-08-17 19:08:48 +00:00
}
2017-08-26 15:46:04 +00:00
popup.codebox.focus();
2017-08-17 19:08:48 +00:00
});
2017-08-20 18:32:41 +00:00
$('.reset', popup).addEventListener('click', event => {
2017-08-18 15:46:09 +00:00
event.preventDefault();
2017-08-23 22:13:55 +00:00
const linter = checkLinter(event.target.dataset.linter);
let rules;
if (linter === 'stylelint') {
setStylelintRules();
2017-08-26 14:30:33 +00:00
rules = stylelintDefaultConfig.rules;
2017-08-23 22:13:55 +00:00
} else {
setCSSLintRules();
rules = csslintDefaultRuleConfig;
2017-08-17 19:08:48 +00:00
}
2017-08-26 14:30:33 +00:00
popup.codebox.setValue(stringifyRules(rules));
2017-08-26 15:46:04 +00:00
popup.codebox.focus();
2017-08-17 19:08:48 +00:00
});
2017-08-26 15:03:28 +00:00
$('.cancel', popup).addEventListener('click', event => {
event.preventDefault();
$('.dismiss').dispatchEvent(new Event('click'));
});
2017-08-17 19:08:48 +00:00
}
function openStylelintSettings() {
2017-08-23 22:13:55 +00:00
const linter = prefs.get('editor.linter');
BG.chromeSync.getValue(
2017-08-23 22:13:55 +00:00
linter === 'stylelint'
? 'editorStylelintRules'
: 'editorCSSLintRules'
2017-08-25 12:44:19 +00:00
).then(rules => {
if (!rules || rules.length === 0) {
2017-08-23 22:13:55 +00:00
rules = linter === 'stylelint'
? setStylelintRules(rules)
: setCSSLintRules(rules);
}
2017-08-26 14:30:33 +00:00
const rulesString = stringifyRules(rules);
2017-08-23 22:13:55 +00:00
setupLinterPopup(rulesString);
2017-08-17 19:08:48 +00:00
});
}
2017-08-23 22:13:55 +00:00
function setupLinterPopup(rules) {
const linter = prefs.get('editor.linter');
const linterTitle = linter === 'stylelint' ? 'Stylelint' : 'CSSLint';
2017-08-26 16:03:51 +00:00
function makeButton(className, text, options = {}) {
return $element(Object.assign(options, {
tag: 'button',
className,
type: 'button',
textContent: t(text),
dataset: {linter}
}));
}
function makeLink(url, textContent) {
return $element({tag: 'a', target: '_blank', href: url, textContent});
}
function setJSONMode(cm) {
cm.setOption('mode', 'application/json');
2017-08-20 14:06:17 +00:00
cm.setOption('lint', 'json');
}
2017-08-26 16:48:32 +00:00
const popup = showCodeMirrorPopup(t('linterRulesTitle', linterTitle), $element({
appendChild: [
$element({
tag: 'p',
appendChild: [
2017-08-26 16:48:32 +00:00
t('linterRulesLink') + ' ',
2017-08-23 22:13:55 +00:00
makeLink(
linter === 'stylelint'
? 'https://stylelint.io/demo/'
: 'https://github.com/CSSLint/csslint/wiki/Rules-by-ID',
linterTitle
),
2017-08-26 16:48:32 +00:00
linter === 'csslint' ? ' ' + t('linterCSSLintSettings') : ''
]
}),
makeButton('save', 'styleSaveLabel'),
2017-08-26 15:03:28 +00:00
makeButton('cancel', 'confirmCancel'),
2017-08-26 16:48:32 +00:00
makeButton('reset', 'genericResetLabel', {title: t('linterResetMessage')}),
$element({
tag: 'span',
className: 'saved-message',
textContent: t('genericSavedMessage')
})
]
}));
2017-08-20 18:32:41 +00:00
const contents = $('.contents', popup);
2017-08-20 14:50:18 +00:00
const loadJSON = window.jsonlint ? [] : [
2017-08-20 15:15:26 +00:00
'vendor/codemirror/mode/javascript/javascript.js',
'vendor/codemirror/addon/lint/json-lint.js',
2017-08-20 14:50:18 +00:00
'vendor/jsonlint/jsonlint.js'
];
contents.insertBefore(popup.codebox.display.wrapper, contents.firstElementChild);
popup.codebox.focus();
popup.codebox.setValue(rules);
2017-08-26 15:29:33 +00:00
popup.codebox.clearHistory();
2017-08-20 19:05:54 +00:00
onDOMscripted(loadJSON).then(() => setJSONMode(popup.codebox));
2017-08-23 22:13:55 +00:00
setupLinterSettingsEvents(popup);
}
2017-08-20 14:06:17 +00:00
function loadSelectedLinter(name) {
2017-08-20 20:03:42 +00:00
const scripts = [];
2017-08-20 14:06:17 +00:00
if (name !== 'null' && !$('script[src*="css-lint.js"]')) {
// inject css
injectCSS('vendor/codemirror/addon/lint/lint.css');
injectCSS('msgbox/msgbox.css');
2017-08-20 14:06:17 +00:00
// load CodeMirror lint code
2017-08-20 19:07:14 +00:00
scripts.push(
2017-08-20 14:06:17 +00:00
'vendor/codemirror/addon/lint/lint.js',
'vendor-overwrites/codemirror/addon/lint/css-lint.js',
'msgbox/msgbox.js'
2017-08-20 19:07:14 +00:00
);
2017-08-20 14:06:17 +00:00
}
if (name === 'csslint' && !window.CSSLint) {
2017-08-23 22:13:55 +00:00
scripts.push(
'edit/csslint-config.js',
2017-08-23 22:13:55 +00:00
'vendor-overwrites/csslint/csslint-worker.js'
);
2017-08-20 14:06:17 +00:00
} else if (name === 'stylelint' && !window.stylelint) {
2017-08-20 19:07:14 +00:00
scripts.push(
2017-08-20 14:06:17 +00:00
'vendor-overwrites/stylelint/stylelint-bundle.min.js',
2017-08-20 19:43:24 +00:00
'edit/stylelint-config.js'
2017-08-20 19:07:14 +00:00
);
2017-08-20 14:06:17 +00:00
}
return onDOMscripted(scripts);
}