rob-revisited/ide/ui/js/bootstrap-lint.js

203 lines
13 KiB
JavaScript

// The Bootstrap checks of a page (no DOM: node --test runs it): structure (col in row, row in container, parts of components),
// class names (unknown, misspelled, Bootstrap 4's), data attributes, ids that must exist, accessibility, nesting that browsers
// refuse. A finding is {code, severity, start, end, params, fixes: [{id, edits: [{start, end, text}]}]}: its text is made by the
// interface (bootstrap-support.js), where the translations are.
import { parseMarkup, classTokens, attr, attrValue, idsOf, hasTwigClass } from './bootstrap-model.js';
import { unknownClass, renameClass, MANUAL_HINT, DATA_RENAMED, classSet } from './bootstrap-catalog.js';
const COL = /^col(?:-(?:(?:sm|md|lg|xl|xxl)-)?(?:\d{1,2}|auto))?$/;
const CONTAINER = /^container(?:-(?:sm|md|lg|xl|xxl|fluid))?$/;
// a part of a component must be inside its parent (within `depth` levels)
const PARTS = [
['modal-dialog', 'modal', 1], ['modal-content', 'modal-dialog', 1], ['modal-header', 'modal-content', 1], ['modal-body', 'modal-content', 1], ['modal-footer', 'modal-content', 1],
['dropdown-item', 'dropdown-menu', 3], ['list-group-item', 'list-group', 3], ['breadcrumb-item', 'breadcrumb', 1], ['page-item', 'pagination', 1],
['accordion-item', 'accordion', 1], ['accordion-body', 'accordion-collapse', 1], ['card-body', 'card', 3], ['card-header', 'card', 2], ['card-footer', 'card', 2],
['toast-body', 'toast', 1], ['toast-header', 'toast', 1], ['offcanvas-body', 'offcanvas', 1], ['offcanvas-header', 'offcanvas', 1], ['carousel-item', 'carousel-inner', 1],
['carousel-inner', 'carousel', 1], ['navbar-brand', 'navbar', 4], ['navbar-nav', 'navbar', 4], ['tab-pane', 'tab-content', 1], ['input-group-text', 'input-group', 1],
];
const TOGGLES_NEEDING_TARGET = new Set(['collapse', 'modal', 'offcanvas', 'tab', 'pill', 'toast']);
const classesOf = (el) => (attr(el, 'class')?.value === null || !attr(el, 'class') ? [] : classTokens(attr(el, 'class').value).filter((t) => !t.twig).map((t) => t.text));
const has = (el, cls) => classesOf(el).includes(cls);
const ancestors = (el) => { const out = []; for (let n = el.parent; n; n = n.parent) out.push(n); return out; };
const tagSpan = (el) => ({ start: el.start, end: el.end });
const insertAfterName = (el, text) => ({ start: el.start + 1 + el.tag.length, end: el.start + 1 + el.tag.length, text });
const attrSpan = (a) => ({ start: a.start, end: a.end });
/** the edit that removes a class token (and one space beside it) from a class attribute value */
function tokenEdit(el, token, replacement) {
const a = attr(el, 'class');
const base = a.valueStart;
let start = base + token.start;
let end = base + token.end;
if (replacement === '') {
const raw = a.value;
if (raw[token.end] === ' ') end++; else if (token.start > 0 && raw[token.start - 1] === ' ') start--;
}
return { start, end, text: replacement };
}
/**
* @param {string} text the page (HTML or Twig)
* @param {{version?: string, projectClasses?: Set<string>|null, model?: object}} [options] version: '5' (default) or '4'
*/
export function lintBootstrap(text, options = {}) {
const version = String(options.version) === '4' ? '4' : '5';
const model = options.model || parseMarkup(text);
const out = [];
const add = (code, severity, span, params = {}, fixes = []) => out.push({ code, severity, start: span.start, end: span.end, params, fixes });
const ids = idsOf(model);
const labelFor = new Set();
for (const el of model.elements) if (el.tag === 'label') { const f = attrValue(el, 'for'); if (f) labelFor.add(f); }
const structural = (el) => !el.unclosed && !ancestors(el).some((a) => a.unclosed);
for (const el of model.elements) {
const cls = attr(el, 'class');
const tokens = cls && cls.value !== null ? classTokens(cls.value) : [];
const plain = tokens.filter((t) => !t.twig);
const classNames = plain.map((t) => t.text);
// class names -----------------------------------------------------------------------------------------------
for (const tok of plain) {
const rename = renameClass(tok.text);
const known5 = classSet('5').has(tok.text);
if (rename && !known5) {
if (version === '4' && !options.hintBs4) continue;
const severity = version === '5' ? 'warning' : 'info';
const fix = rename.to !== null ? [{ id: 'convert', edits: [tokenEdit(el, tok, rename.to.join(' '))] }] : [];
add('bs4-class', severity, { start: cls.valueStart + tok.start, end: cls.valueStart + tok.end },
{ cls: tok.text, to: rename.to ? rename.to.join(' ') : '', hint: rename.to === null ? MANUAL_HINT[tok.text] || '' : '' }, fix);
continue;
}
const bad = unknownClass(tok.text, version, options.projectClasses);
if (bad) {
add('unknown-class', 'warning', { start: cls.valueStart + tok.start, end: cls.valueStart + tok.end }, { cls: tok.text, suggest: bad.suggest || '' },
bad.suggest ? [{ id: 'suggest', edits: [tokenEdit(el, tok, bad.suggest)] }] : []);
}
}
if (hasTwigClass(el)) { /* a class built by Twig: the structure checks below still look at the plain ones */ }
// data attributes of Bootstrap 4 -----------------------------------------------------------------------------
for (const a of el.attrs) {
const m = /^data-(.+)$/.exec(a.name);
if (version === '4' && !options.hintBs4) break;
if (m && DATA_RENAMED.includes(m[1]) && (a.name === 'data-toggle' || a.name === 'data-target' || a.name === 'data-dismiss' || a.name === 'data-ride' || a.name === 'data-slide' || a.name === 'data-slide-to' || a.name === 'data-parent' || a.name === 'data-spy' || a.name === 'data-backdrop' || a.name === 'data-keyboard' || a.name === 'data-interval' || a.name === 'data-autohide' || (/^data-(content|placement|trigger|offset|delay|animation|boundary|pause|wrap|touch|focus|reference)$/.test(a.name) && (attrValue(el, 'data-toggle') !== null || attrValue(el, 'data-bs-toggle') !== null)))) {
add('bs4-attr', version === '5' ? 'warning' : 'info', attrSpan({ start: a.start, end: a.start + a.name.length }), { name: a.name, to: `data-bs-${m[1]}` },
[{ id: 'convert', edits: [{ start: a.start, end: a.start + a.name.length, text: `data-bs-${m[1]}` }] }]);
}
}
// structure ---------------------------------------------------------------------------------------------------
if (structural(el) && version === '5') {
if (classNames.some((c) => COL.test(c)) && el.parent && !classNames.includes('placeholder')) {
const pc = classesOf(el.parent);
if (!pc.some((c) => c === 'row' || c.startsWith('row-cols') || c === 'd-flex' || c === 'd-grid' || c === 'form-row' || c.startsWith('d-flex')) && !el.parent.hasTwig) {
add('col-outside-row', 'warning', tagSpan(el), { cls: classNames.find((c) => COL.test(c)) });
}
}
if (classNames.includes('row') && el.parent) {
const up = ancestors(el);
if (!up.some((a) => classesOf(a).some((c) => CONTAINER.test(c) || COL.test(c) || c === 'row' || c === 'modal-body' || c === 'card-body' || c === 'offcanvas-body' || c === 'card' || c === 'list-group-item' || c === 'accordion-body' || c === 'toast-body'))) {
add('row-outside-container', 'warning', tagSpan(el));
}
}
}
if (structural(el)) {
for (const [part, parent, depth] of PARTS) {
if (!classNames.includes(part) || !el.parent) continue;
const up = ancestors(el).slice(0, depth);
if (!up.some((a) => has(a, parent)) && !up.some((a) => a.hasTwig)) { add('orphan-part', 'warning', tagSpan(el), { part, parent }); break; }
}
if (classNames.includes('dropdown-menu') && el.parent && !['dropdown', 'dropup', 'dropend', 'dropstart', 'btn-group', 'nav-item', 'input-group', 'dropdown-center', 'dropup-center'].some((c) => has(el.parent, c))
&& !el.parent.hasTwig) add('orphan-part', 'warning', tagSpan(el), { part: 'dropdown-menu', parent: 'dropdown' });
}
const tag = el.tag;
const bsToggle = attrValue(el, 'data-bs-toggle') ?? attrValue(el, 'data-toggle');
const dismiss = attrValue(el, 'data-bs-dismiss') ?? attrValue(el, 'data-dismiss');
// ids that must exist ---------------------------------------------------------------------------------------------
const target = attrValue(el, 'data-bs-target') ?? attrValue(el, 'data-target');
const href = tag === 'a' ? attrValue(el, 'href') : null;
const ref = target ?? (href && href.startsWith('#') && href.length > 1 ? href : null);
if (bsToggle !== null && TOGGLES_NEEDING_TARGET.has(bsToggle) && ref === null && !el.hasTwig) {
add('toggle-without-target', 'warning', tagSpan(el), { toggle: bsToggle });
}
for (const spec of [['data-bs-target', target], ['data-target', null]]) {
void spec;
}
if (ref !== null && !/\{[{%]/.test(ref) && (bsToggle !== null || attrValue(el, 'data-bs-slide') !== null || attrValue(el, 'data-slide') !== null)) {
const first = ref.split(',')[0].trim();
const id = /^#([A-Za-z_][\w:.-]*)$/.exec(first)?.[1];
if (id && !ids.has(id)) {
const a = attr(el, 'data-bs-target') || attr(el, 'data-target') || attr(el, 'href');
add('target-missing', 'warning', a ? { start: a.valueStart, end: a.valueEnd } : tagSpan(el), { id });
}
}
for (const name of ['aria-controls', 'aria-labelledby', 'aria-describedby']) {
const v = attrValue(el, name);
if (v && !/\{[{%]/.test(v) && v.split(/\s+/).some((i) => !ids.has(i)) && structural(el)) {
const a = attr(el, name);
add('aria-ref-missing', 'warning', { start: a.valueStart, end: a.valueEnd }, { id: v.split(/\s+/).find((i) => !ids.has(i)), name });
}
}
if (classNames.includes('dropdown-toggle') && bsToggle === null && !el.hasTwig) {
add('dropdown-toggle-attr', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, version === '5' ? ' data-bs-toggle="dropdown"' : ' data-toggle="dropdown"')] }]);
}
// accessibility ---------------------------------------------------------------------------------------------------
const inner = el.closeStart >= el.end ? text.slice(el.end, el.closeStart) : '';
if (tag === 'button' && attr(el, 'type') === undefined && !el.hasTwig) {
add('button-type', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' type="button"')] }]);
}
if (tag === 'img' && !attr(el, 'alt') && !el.hasTwig) {
add('img-alt', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' alt=""')] }]);
}
if (['input', 'select', 'textarea'].includes(tag) && !el.hasTwig) {
const type = (attrValue(el, 'type') || 'text').toLowerCase();
if (!['hidden', 'submit', 'button', 'reset', 'image'].includes(type)) {
const id = attrValue(el, 'id');
const labelled = attr(el, 'aria-label') || attr(el, 'aria-labelledby') || attr(el, 'title') || ancestors(el).some((a) => a.tag === 'label') || (id && (labelFor.has(id) || /\{[{%]/.test(id)));
if (!labelled) add('control-label', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' aria-label=""')] }]);
}
}
if (classNames.includes('modal') && !attr(el, 'aria-labelledby') && !attr(el, 'aria-label') && !el.hasTwig) {
add('modal-label', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' aria-labelledby=""')] }]);
}
if (classNames.includes('btn-close') && !attr(el, 'aria-label') && !attr(el, 'aria-labelledby') && !el.hasTwig && version === '5') {
add('close-label', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' aria-label="Close"')] }]);
}
if ((tag === 'button' || (tag === 'a' && classNames.includes('btn'))) && !classNames.includes('btn-close') && !el.hasTwig && el.closeStart >= el.end
&& !attr(el, 'aria-label') && !attr(el, 'aria-labelledby') && !attr(el, 'title')) {
const textual = inner.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/g, ' ').trim();
if (!textual && /<(i|svg|span|img)\b/i.test(inner) && !/\balt="[^"]+"/.test(inner)) {
add('icon-button-label', 'warning', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' aria-label=""')] }]);
}
}
if (classNames.includes('alert') && !attr(el, 'role') && !classNames.includes('alert-link') && !el.hasTwig) {
add('alert-role', 'info', tagSpan(el), {}, [{ id: 'add', edits: [insertAfterName(el, ' role="alert"')] }]);
}
void dismiss;
// nesting browsers refuse -------------------------------------------------------------------------------------------
const interactive = (n) => n.tag === 'button' || (n.tag === 'a' && attr(n, 'href') !== undefined);
if (interactive(el) || ['input', 'select', 'textarea'].includes(tag)) {
const outer = ancestors(el).find((a) => interactive(a));
if (outer && !(tag === 'input' && attrValue(el, 'type') === 'hidden') && structural(el)) add('nested-interactive', 'error', tagSpan(el), { tag, outer: outer.tag });
}
}
// ids used twice
for (const [id, list] of ids) {
if (list.length > 1) for (const el of list.slice(1)) { const a = attr(el, 'id'); add('duplicate-id', 'warning', { start: a.valueStart, end: a.valueEnd }, { id }); }
}
out.sort((a, b) => a.start - b.start || a.end - b.end);
return out;
}
/** every fix of a kind, as one list of edits (no two overlap): "convert the page to Bootstrap 5" */
export function convertAllEdits(findings) {
const edits = [];
for (const f of findings) if ((f.code === 'bs4-class' || f.code === 'bs4-attr') && f.fixes[0]) edits.push(...f.fixes[0].edits);
return edits;
}