240 lines
13 KiB
JavaScript
240 lines
13 KiB
JavaScript
// Bootstrap in the code editor (every .html / .twig file of a project that uses Bootstrap, whatever the editor's mode): the checks as
|
|
// markers and in the Problems window, quick fixes (one, or the whole page to Bootstrap 5), class completion in class="…" with
|
|
// short docs, hover on a class. Detection: the page, then the project (package.json, importmap.php, the base template). The pure
|
|
// parts (reader, checks, catalogue) are bootstrap-model / -lint / -catalog / -detect; this file is the glue with Monaco.
|
|
import { t, debounce } from './ui.js';
|
|
import { parseMarkup } from './bootstrap-model.js';
|
|
import { lintBootstrap, convertAllEdits } from './bootstrap-lint.js';
|
|
import { classSet, describeClass, renameClass, MANUAL_HINT } from './bootstrap-catalog.js';
|
|
import { detectInText, detectInProject, mergeDetection, cssClasses } from './bootstrap-detect.js';
|
|
|
|
/** the text of a finding (English keys of the language files; placeholders filled) */
|
|
export function describe(f) {
|
|
const p = f.params || {};
|
|
switch (f.code) {
|
|
case 'col-outside-row': return t('{cls} must be a direct child of a .row (or of a flex / grid container)', p);
|
|
case 'row-outside-container': return t('A .row belongs in a .container (or in a column, card or modal body)');
|
|
case 'unknown-class': return p.suggest ? t('Unknown Bootstrap class "{cls}": did you mean "{suggest}"?', p) : t('"{cls}" is not a Bootstrap class', p);
|
|
case 'bs4-class': return p.to ? t('"{cls}" is Bootstrap 4: in Bootstrap 5 it is "{to}"', p) : t('"{cls}" is Bootstrap 4 and has no equivalent in Bootstrap 5{hint}', { cls: p.cls, hint: p.hint ? ` (${p.hint})` : '' });
|
|
case 'bs4-attr': return t('"{name}" is Bootstrap 4: in Bootstrap 5 it is "{to}"', p);
|
|
case 'toggle-without-target': return t('data-bs-toggle="{toggle}" needs a data-bs-target (or an href="#id") that names the element to open', p);
|
|
case 'target-missing': return t('No element has the id "{id}"', p);
|
|
case 'aria-ref-missing': return t('{name} points to "{id}": no element has this id', p);
|
|
case 'orphan-part': return t('.{part} must be inside a .{parent}', p);
|
|
case 'dropdown-toggle-attr': return t('A .dropdown-toggle needs data-bs-toggle="dropdown"');
|
|
case 'duplicate-id': return t('The id "{id}" is used more than once', p);
|
|
case 'button-type': return t('A <button> needs a type (type="button", or "submit" in a form)');
|
|
case 'img-alt': return t('An image needs an alt text (alt="" if it is only decoration)');
|
|
case 'control-label': return t('A form control needs a label: a <label for>, a wrapping <label>, or aria-label');
|
|
case 'modal-label': return t('A modal needs aria-labelledby (the id of its title)');
|
|
case 'close-label': return t('A .btn-close needs aria-label="Close"');
|
|
case 'icon-button-label': return t('A button with only an icon needs aria-label');
|
|
case 'alert-role': return t('An alert should have role="alert"');
|
|
case 'nested-interactive': return t('A <{tag}> inside a <{outer}>: interactive elements cannot be nested', p);
|
|
default: return f.code;
|
|
}
|
|
}
|
|
|
|
/** the label of a finding's quick fix */
|
|
export function fixLabel(f, fix) {
|
|
const p = f.params || {};
|
|
if (f.code === 'unknown-class') return t('Change to "{suggest}"', p);
|
|
if (f.code === 'bs4-class') return p.to ? t('Convert to "{to}"', p) : t('Remove "{cls}"', p);
|
|
if (f.code === 'bs4-attr') return t('Convert to "{to}"', p);
|
|
void fix;
|
|
return t('Add the missing attribute');
|
|
}
|
|
|
|
const CONVERT_ALL = () => t('Convert the whole page to Bootstrap 5');
|
|
|
|
let providersRegistered = false;
|
|
const registry = new Map(); // model uri -> its BootstrapSupport entry {version, findings, parsed, versionId}
|
|
|
|
/** `before` ends inside a class="…" value: the value so far, or null */
|
|
export function classValueBefore(before) {
|
|
const m = /\bclass\s*=\s*(["'])((?:(?!\1)[\s\S])*)$/.exec(before.slice(-800));
|
|
if (!m || /\{\{[^}]*$|\{%[^%]*$/.test(m[2])) return null;
|
|
return m[2];
|
|
}
|
|
|
|
export class BootstrapSupport {
|
|
/**
|
|
* @param {{monaco: object, readText: (path: string) => Promise<?string>, files: () => string[], onProblems?: (path: string, list: object[]) => void}} o
|
|
*/
|
|
constructor(o) {
|
|
this.o = o;
|
|
this.monaco = o.monaco;
|
|
this.project = null; // the project's detection (once)
|
|
this.projectClasses = null;
|
|
this.attached = new Map(); // path -> {model, sub, info, timer}
|
|
this.register();
|
|
}
|
|
|
|
async projectInfo() {
|
|
this.project ??= await detectInProject(this.o.readText).catch(() => ({ used: false }));
|
|
return this.project;
|
|
}
|
|
|
|
/** the project's own CSS classes: not typos (read once; the CSS files of the project outside vendor / node_modules / Bootstrap's own) */
|
|
async classes() {
|
|
if (this.projectClasses) return this.projectClasses;
|
|
const out = new Set();
|
|
const files = (this.o.files() || []).filter((p) => /\.s?css$/i.test(p) && !/(^|\/)(vendor|node_modules|var|dist|build)\//.test(p) && !/bootstrap/i.test(p)).slice(0, 40);
|
|
for (const p of files) { const css = await this.o.readText(p).catch(() => null); if (typeof css === 'string' && css.length < 400000) for (const c of cssClasses(css)) out.add(c); }
|
|
this.projectClasses = out;
|
|
return out;
|
|
}
|
|
|
|
forgetClasses() { this.projectClasses = null; }
|
|
|
|
/** Whether (and for which version) this page uses Bootstrap: null when it does not */
|
|
async detect(text) {
|
|
const file = detectInText(text);
|
|
if (file.used && file.reason === 'link' && file.version) return mergeDetection(file, null);
|
|
return mergeDetection(file, await this.projectInfo());
|
|
}
|
|
|
|
/** the file's model is followed: checks as one types, markers, the Problems window */
|
|
async attach(path, model) {
|
|
if (this.attached.has(path)) return this.attached.get(path).info;
|
|
const info = await this.detect(model.getValue());
|
|
const entry = { model, info, timer: null, sub: null, path };
|
|
this.attached.set(path, entry);
|
|
registry.set(model.uri.toString(), entry);
|
|
entry.sub = model.onDidChangeContent(() => { clearTimeout(entry.timer); entry.timer = setTimeout(() => this.check(entry), 350); });
|
|
await this.check(entry);
|
|
return info;
|
|
}
|
|
|
|
detach(path) {
|
|
const e = this.attached.get(path);
|
|
if (!e) return;
|
|
clearTimeout(e.timer);
|
|
e.sub?.dispose();
|
|
registry.delete(e.model.uri.toString());
|
|
this.attached.delete(path);
|
|
if (!e.model.isDisposed()) this.monaco.editor.setModelMarkers(e.model, 'bootstrap', []);
|
|
this.o.onProblems?.(path, []);
|
|
}
|
|
|
|
/** the findings of an entry's text, again (the detection too: a page may start to use Bootstrap while one types) */
|
|
async check(entry) {
|
|
const { model } = entry;
|
|
if (model.isDisposed()) return;
|
|
const text = model.getValue();
|
|
if (!entry.info?.used) {
|
|
const d = await this.detect(text);
|
|
if (d) entry.info = d;
|
|
}
|
|
if (!entry.info?.used) { this.monaco.editor.setModelMarkers(model, 'bootstrap', []); this.o.onProblems?.(entry.path, []); return; }
|
|
entry.parsed = parseMarkup(text);
|
|
entry.versionId = model.getVersionId();
|
|
entry.findings = lintBootstrap(text, { version: entry.info.version, projectClasses: await this.classes(), model: entry.parsed });
|
|
if (model.isDisposed() || model.getVersionId() !== entry.versionId) return;
|
|
const sev = { error: this.monaco.MarkerSeverity.Error, warning: this.monaco.MarkerSeverity.Warning, info: this.monaco.MarkerSeverity.Info };
|
|
const markers = entry.findings.map((f) => {
|
|
const a = model.getPositionAt(f.start);
|
|
const b = model.getPositionAt(Math.max(f.end, f.start + 1));
|
|
return { startLineNumber: a.lineNumber, startColumn: a.column, endLineNumber: b.lineNumber, endColumn: b.column, message: describe(f), severity: sev[f.severity] || sev.warning, source: 'Bootstrap', code: f.code };
|
|
});
|
|
this.monaco.editor.setModelMarkers(model, 'bootstrap', markers);
|
|
this.o.onProblems?.(entry.path, markers.map((m) => ({ startLine: m.startLineNumber, startColumn: m.startColumn, endLine: m.endLineNumber, endColumn: m.endColumn,
|
|
message: m.message, severity: m.severity === sev.error ? 'error' : 'warning', source: 'Bootstrap' })));
|
|
}
|
|
|
|
/** the entry of a model */
|
|
entryOf(model) { return registry.get(model.uri.toString()) || null; }
|
|
|
|
/** the monaco edits of a fix (one workspace edit: one undo) */
|
|
editsOf(model, edits) {
|
|
return edits.map((e) => {
|
|
const a = model.getPositionAt(e.start);
|
|
const b = model.getPositionAt(e.end);
|
|
return { resource: model.uri, versionId: undefined, textEdit: { range: new this.monaco.Range(a.lineNumber, a.column, b.lineNumber, b.column), text: e.text } };
|
|
});
|
|
}
|
|
|
|
register() {
|
|
if (providersRegistered) return;
|
|
providersRegistered = true;
|
|
const monaco = this.monaco;
|
|
const self = this;
|
|
let items = { '5': null, '4': null };
|
|
const itemsFor = (version, extra) => {
|
|
const key = version + (extra?.size || 0);
|
|
if (items[key]) return items[key];
|
|
const list = [...classSet(version)].map((c) => ({ c, project: false }));
|
|
for (const c of extra || []) if (!classSet(version).has(c)) list.push({ c, project: true });
|
|
return (items[key] = list);
|
|
};
|
|
for (const language of ['html', 'twig']) {
|
|
monaco.languages.registerCompletionItemProvider(language, {
|
|
triggerCharacters: ['"', "'", ' ', '-'],
|
|
provideCompletionItems: async (model, position) => {
|
|
const entry = self.entryOf(model);
|
|
if (!entry?.info?.used) return { suggestions: [] };
|
|
const before = model.getValueInRange({ startLineNumber: Math.max(1, position.lineNumber - 6), startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column });
|
|
const value = classValueBefore(before);
|
|
if (value === null) return { suggestions: [] };
|
|
const word = /[\w:./-]*$/.exec(value)[0];
|
|
const range = new monaco.Range(position.lineNumber, position.column - word.length, position.lineNumber, position.column);
|
|
const used = new Set(value.split(/\s+/));
|
|
const extra = await self.classes();
|
|
return { suggestions: itemsFor(entry.info.version, extra).map(({ c, project }) => ({
|
|
label: c, kind: project ? monaco.languages.CompletionItemKind.Reference : monaco.languages.CompletionItemKind.Value, insertText: c, range,
|
|
sortText: (used.has(c) ? '9' : project ? '1' : '0') + c, detail: project ? t('your CSS') : 'Bootstrap ' + entry.info.version,
|
|
})) };
|
|
},
|
|
resolveCompletionItem: (item) => {
|
|
const info = describeClass(item.label, '5');
|
|
if (info) item.documentation = { value: `${info.css ? '`' + info.css + '`\n\n' : ''}[${info.doc.replace('https://', '')}](${info.doc})` };
|
|
return item;
|
|
},
|
|
});
|
|
monaco.languages.registerHoverProvider(language, {
|
|
provideHover: (model, position) => {
|
|
const entry = self.entryOf(model);
|
|
if (!entry?.info?.used) return null;
|
|
const text = model.getValue();
|
|
if (entry.versionId !== model.getVersionId()) { entry.parsed = parseMarkup(text); entry.versionId = model.getVersionId(); }
|
|
const offset = model.getOffsetAt(position);
|
|
for (const el of entry.parsed.elements) {
|
|
if (el.start > offset) break;
|
|
const a = el.attrs.find((x) => x.name === 'class' && x.value !== null);
|
|
if (!a || offset < a.valueStart || offset > a.valueEnd) continue;
|
|
const at = offset - a.valueStart;
|
|
const tok = [...a.value.matchAll(/[^\s{]+/g)].find((m) => at >= m.index && at <= m.index + m[0].length);
|
|
if (!tok) return null;
|
|
const cls = tok[0];
|
|
const version = entry.info.version;
|
|
const info = describeClass(cls, version);
|
|
const start = model.getPositionAt(a.valueStart + tok.index);
|
|
const end = model.getPositionAt(a.valueStart + tok.index + cls.length);
|
|
const range = new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column);
|
|
if (info) return { range, contents: [{ value: `**${cls}**${info.css ? ' \n`' + info.css + '`' : ''}` }, { value: `[Bootstrap docs](${info.doc})` }] };
|
|
const rename = version === '5' ? renameClass(cls) : null;
|
|
if (rename) return { range, contents: [{ value: rename.to ? t('"{cls}" is Bootstrap 4: in Bootstrap 5 it is "{to}"', { cls, to: rename.to.join(' ') }) : t('"{cls}" is Bootstrap 4 and has no equivalent in Bootstrap 5{hint}', { cls, hint: MANUAL_HINT[cls] ? ` (${MANUAL_HINT[cls]})` : '' }) }] };
|
|
return null;
|
|
}
|
|
return null;
|
|
},
|
|
});
|
|
monaco.languages.registerCodeActionProvider(language, {
|
|
provideCodeActions: (model, range) => {
|
|
const entry = self.entryOf(model);
|
|
if (!entry?.findings?.length || entry.versionId !== model.getVersionId()) return { actions: [], dispose() {} };
|
|
const from = model.getOffsetAt({ lineNumber: range.startLineNumber, column: range.startColumn });
|
|
const to = model.getOffsetAt({ lineNumber: range.endLineNumber, column: range.endColumn });
|
|
const actions = [];
|
|
for (const f of entry.findings) {
|
|
if (f.end < from || f.start > to || !f.fixes.length) continue;
|
|
for (const fix of f.fixes) actions.push({ title: fixLabel(f, fix), kind: 'quickfix', isPreferred: true, edit: { edits: self.editsOf(model, fix.edits) } });
|
|
}
|
|
const all = convertAllEdits(entry.findings);
|
|
if (all.length > 1) actions.push({ title: CONVERT_ALL(), kind: 'quickfix', edit: { edits: self.editsOf(model, all) } });
|
|
return { actions, dispose() {} };
|
|
},
|
|
}, { providedCodeActionKinds: ['quickfix'] });
|
|
}
|
|
}
|
|
}
|