464 lines
31 KiB
JavaScript
464 lines
31 KiB
JavaScript
// The Bootstrap editor's pure parts: the markup reader, the code edits, the class catalogue, the checks, the palette, the utilities,
|
|
// the AI request. Run: docker run --rm -v $PWD:/w -w /w node:22-alpine node --test ide/ui/js/bootstrap.test.mjs
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { parseMarkup, elementAt, classesOf, setClasses, changeClasses, setAttribute, applyEdits, insertSnippet, insertAtOffset, markElements, idsOf, classTokens, pathOf, elementByPath, attrValue } from './bootstrap-model.js';
|
|
import { isBootstrap4Only, classSet, renameClass, unknownClass, nearestClass, describeClass, toBootstrap4Class } from './bootstrap-catalog.js';
|
|
import { lintBootstrap, convertAllEdits } from './bootstrap-lint.js';
|
|
import { GROUPS, groupValue, groupValues, setGroup, valuesAt } from './bootstrap-utilities.js';
|
|
import { COMPONENTS, componentGroups, snippetFor, snippetContext, forVersion } from './bootstrap-components.js';
|
|
import { buildRequest, extractMarkup, runAi } from './bootstrap-ai.js';
|
|
|
|
const codes = (text, o) => lintBootstrap(text, o).map((f) => f.code);
|
|
const apply = (text, f, i = 0) => applyEdits(text, f.fixes[i].edits);
|
|
|
|
// ---- the reader ---------------------------------------------------------------------------------------------------------
|
|
test('elements, nesting, void tags, comments and Twig are read with their offsets', () => {
|
|
const t = '<div class="a b"><!-- <p> --><img src="x"><ul><li>1<li>2</ul>{% if x %}<span>s</span>{% endif %}</div>';
|
|
const m = parseMarkup(t);
|
|
assert.deepEqual(m.elements.map((e) => e.tag), ['div', 'img', 'ul', 'li', 'li', 'span']);
|
|
const [div, img, ul, li1, li2, span] = m.elements;
|
|
assert.equal(img.parent, div);
|
|
assert.deepEqual(ul.children, [li1, li2]); // the second <li> closed the first
|
|
assert.equal(span.parent, div);
|
|
assert.equal(t.slice(div.start, div.end), '<div class="a b">');
|
|
assert.equal(t.slice(div.closeStart, div.closeEnd), '</div>');
|
|
});
|
|
|
|
test('Twig inside tags and attribute values does not break the reader', () => {
|
|
const t = '<a {% if x %}class="btn {{ c ? "x" : \'y\' }}"{% endif %} href="{{ path(\'a\') }}">go</a><p>after</p>';
|
|
const m = parseMarkup(t);
|
|
assert.deepEqual(m.elements.map((e) => e.tag), ['a', 'p']);
|
|
assert.equal(attrValue(m.elements[0], 'href'), "{{ path('a') }}");
|
|
assert.equal(m.elements[0].hasTwig, true);
|
|
});
|
|
|
|
test('script and style content is not read as tags; unquoted and valueless attributes work', () => {
|
|
const m = parseMarkup('<script>if (a<b) { x = "<div>" }</script><input disabled value=3 class=big><style>a>b{}</style>');
|
|
assert.deepEqual(m.elements.map((e) => e.tag), ['script', 'input', 'style']);
|
|
assert.equal(attrValue(m.elements[1], 'disabled'), '');
|
|
assert.equal(attrValue(m.elements[1], 'class'), 'big');
|
|
});
|
|
|
|
test('elementAt gives the innermost element, in a tag or between tags', () => {
|
|
const t = '<div><p class="x">hi <b>there</b></p><hr></div>';
|
|
const m = parseMarkup(t);
|
|
assert.equal(elementAt(m, t.indexOf('there') + 2).tag, 'b');
|
|
assert.equal(elementAt(m, t.indexOf('hi')).tag, 'p');
|
|
assert.equal(elementAt(m, t.indexOf('class')).tag, 'p');
|
|
assert.equal(elementAt(m, t.indexOf('<hr>') + 2).tag, 'hr');
|
|
assert.equal(elementAt(m, 1).tag, 'div');
|
|
assert.equal(elementAt(parseMarkup(''), 0), null);
|
|
});
|
|
|
|
test('an element is found again by its path after an edit', () => {
|
|
const t = '<div><p>1</p><p class="y">2</p></div>';
|
|
const m = parseMarkup(t);
|
|
const path = pathOf(m.elements[2]);
|
|
const t2 = applyEdits(t, [setClasses(m, m.elements[2], ['y', 'z'])]);
|
|
assert.equal(attrValue(elementByPath(parseMarkup(t2), path), 'class'), 'y z');
|
|
});
|
|
|
|
// ---- the edits ----------------------------------------------------------------------------------------------------------
|
|
const only = (before, after, edit) => { // the edit touches nothing outside its range
|
|
assert.equal(applyEdits(before, [edit]), after);
|
|
assert.equal(before.slice(0, edit.start), after.slice(0, edit.start));
|
|
assert.equal(before.slice(edit.end), after.slice(after.length - (before.length - edit.end)));
|
|
};
|
|
|
|
test('a class attribute is rewritten in place: only its value changes', () => {
|
|
const t = '<div id="a" class="p-2 mt-3 x" data-k="1">\n <p>x</p>\n</div>';
|
|
const m = parseMarkup(t);
|
|
const edit = setClasses(m, m.elements[0], ['p-2', 'mt-2', 'x']);
|
|
only(t, '<div id="a" class="p-2 mt-2 x" data-k="1">\n <p>x</p>\n</div>', edit);
|
|
assert.equal(edit.start, t.indexOf('p-2'));
|
|
});
|
|
|
|
test('an element without class gets one after its tag name; no class left removes the attribute', () => {
|
|
let t = '<p id="a">x</p>';
|
|
let m = parseMarkup(t);
|
|
assert.equal(applyEdits(t, [setClasses(m, m.elements[0], ['lead'])]), '<p class="lead" id="a">x</p>');
|
|
t = '<p class="lead" id="a">x</p>';
|
|
m = parseMarkup(t);
|
|
assert.equal(applyEdits(t, [changeClasses(m, m.elements[0], { remove: ['lead'] })]), '<p id="a">x</p>');
|
|
assert.equal(setClasses(m, m.elements[0], ['lead']), null); // nothing to change: no edit
|
|
});
|
|
|
|
test('Twig in a class attribute stays where it is; new classes go at the end', () => {
|
|
const t = '<a class="btn {{ cls }} {% if on %}active{% endif %} p-1">x</a>';
|
|
const m = parseMarkup(t);
|
|
assert.deepEqual(classTokens(m.elements[0].attrs[0].value).map((x) => x.twig), [false, true, true, false]);
|
|
assert.deepEqual(classesOf(m.elements[0]), ['btn', 'p-1']);
|
|
const out = applyEdits(t, [changeClasses(m, m.elements[0], { add: ['mt-2'], remove: ['p-1'] })]);
|
|
assert.equal(out, '<a class="btn {{ cls }} {% if on %}active{% endif %} mt-2">x</a>');
|
|
});
|
|
|
|
test('mt-3 -> mt-2 keeps mt-md-4 (the inspector sets a value at one breakpoint)', () => {
|
|
const t = '<div class="mt-3 mt-md-4 d-flex">';
|
|
const m = parseMarkup(t);
|
|
const g = GROUPS.mt;
|
|
const next = setGroup(g, classesOf(m.elements[0]), '2', '');
|
|
assert.deepEqual([...next].sort(), ['d-flex', 'mt-2', 'mt-md-4']);
|
|
assert.equal(applyEdits(t, [setClasses(m, m.elements[0], next)]), '<div class="mt-2 mt-md-4 d-flex">');
|
|
assert.deepEqual(setGroup(g, ['mt-3', 'mt-md-4'], null, 'md'), ['mt-3']);
|
|
});
|
|
|
|
test('one edit is one undo: applying it and its inverse gives the text back, whatever the rest of the file is', () => {
|
|
const t = '<ul>\n <li class="a">1</li>\n <li>2</li>\n</ul>\n';
|
|
const m = parseMarkup(t);
|
|
const e = changeClasses(m, m.elements[1], { add: ['b'] });
|
|
const done = applyEdits(t, [e]);
|
|
const inverse = { start: e.start, end: e.start + e.text.length, text: t.slice(e.start, e.end) };
|
|
assert.equal(applyEdits(done, [inverse]), t);
|
|
});
|
|
|
|
test('attributes are added, replaced and removed with one edit', () => {
|
|
const t = '<button class="btn">x</button>';
|
|
const m = parseMarkup(t);
|
|
assert.equal(applyEdits(t, [setAttribute(m, m.elements[0], 'type', 'button')]), '<button type="button" class="btn">x</button>');
|
|
const t2 = '<button type="submit" class="btn">x</button>';
|
|
assert.equal(applyEdits(t2, [setAttribute(parseMarkup(t2), parseMarkup(t2).elements[0], 'type', 'button')]), '<button type="button" class="btn">x</button>');
|
|
assert.equal(applyEdits(t2, [setAttribute(parseMarkup(t2), parseMarkup(t2).elements[0], 'type', null)]), '<button class="btn">x</button>');
|
|
});
|
|
|
|
test('snippets go before, after and inside an element with the right indentation', () => {
|
|
const t = '<main>\n <section>\n <p>x</p>\n </section>\n</main>\n';
|
|
const m = parseMarkup(t);
|
|
const section = m.elements[1];
|
|
const snippet = '<div class="row">\n <div class="col"></div>\n</div>';
|
|
assert.equal(applyEdits(t, [insertSnippet(m, section, 'after', snippet)]),
|
|
'<main>\n <section>\n <p>x</p>\n </section>\n <div class="row">\n <div class="col"></div>\n </div>\n</main>\n');
|
|
assert.equal(applyEdits(t, [insertSnippet(m, section, 'before', snippet)]),
|
|
'<main>\n <div class="row">\n <div class="col"></div>\n </div>\n <section>\n <p>x</p>\n </section>\n</main>\n');
|
|
assert.equal(applyEdits(t, [insertSnippet(m, section, 'end', '<hr>')]), '<main>\n <section>\n <p>x</p>\n <hr>\n </section>\n</main>\n');
|
|
assert.equal(applyEdits('<div></div>', [insertSnippet(parseMarkup('<div></div>'), parseMarkup('<div></div>').elements[0], 'end', '<p>x</p>')]), '<div>\n <p>x</p>\n</div>');
|
|
assert.equal(applyEdits(' <i></i>', [insertAtOffset({ text: ' <i></i>' }, 2, 'a\nb')]), ' a\n b<i></i>');
|
|
});
|
|
|
|
test('the tags of a template are marked with their offset (what a click in the preview gives back)', () => {
|
|
const t = '<!doctype html><html><head><title>x</title></head><body><div class="a"><p>x</p></div></body></html>';
|
|
const marked = markElements(t);
|
|
const m = parseMarkup(t);
|
|
const div = m.elements.find((e) => e.tag === 'div');
|
|
assert.ok(marked.includes(`<div data-jb="${div.start}" class="a">`));
|
|
assert.ok(!marked.includes('<html data-jb') && !marked.includes('<title data-jb'));
|
|
assert.equal(marked.replace(/ data-jb="\d+"/g, ''), t);
|
|
});
|
|
|
|
test('ids are listed; duplicates and Twig-built ids are told apart', () => {
|
|
const ids = idsOf(parseMarkup('<i id="a"></i><i id="a"></i><i id="b{{ n }}"></i>'));
|
|
assert.equal(ids.get('a').length, 2);
|
|
assert.equal(ids.size, 1);
|
|
});
|
|
|
|
// ---- the catalogue ------------------------------------------------------------------------------------------------------
|
|
test('the catalogue comes from the real stylesheets', () => {
|
|
const five = classSet('5');
|
|
for (const c of ['btn', 'col-md-6', 'ms-3', 'mt-md-4', 'g-3', 'offcanvas', 'form-select', 'text-bg-primary', 'navbar-expand-lg', 'row-cols-md-3', 'placeholder-glow', 'dropdown-menu-end']) assert.ok(five.has(c), c);
|
|
for (const c of ['ml-3', 'custom-select', 'badge-primary', 'form-group', 'float-left', 'sr-only', 'btn-block']) assert.ok(!five.has(c) && classSet('4').has(c), c);
|
|
assert.ok(isBootstrap4Only('ml-3'));
|
|
});
|
|
|
|
test('BS4 classes map to their BS5 names', () => {
|
|
const to = (c) => renameClass(c)?.to;
|
|
assert.deepEqual(to('ml-3'), ['ms-3']);
|
|
assert.deepEqual(to('mr-md-auto'), ['me-md-auto']);
|
|
assert.deepEqual(to('pl-lg-5'), ['ps-lg-5']);
|
|
assert.deepEqual(to('pr-0'), ['pe-0']);
|
|
assert.deepEqual(to('float-md-left'), ['float-md-start']);
|
|
assert.deepEqual(to('text-right'), ['text-end']);
|
|
assert.deepEqual(to('border-left-0'), ['border-start-0']);
|
|
assert.deepEqual(to('rounded-right'), ['rounded-end']);
|
|
assert.deepEqual(to('font-weight-bold'), ['fw-bold']);
|
|
assert.deepEqual(to('badge-danger'), ['text-bg-danger']);
|
|
assert.deepEqual(to('custom-select'), ['form-select']);
|
|
assert.deepEqual(to('form-group'), ['mb-3']);
|
|
assert.deepEqual(to('sr-only'), ['visually-hidden']);
|
|
assert.deepEqual(to('no-gutters'), ['g-0']);
|
|
assert.deepEqual(to('dropdown-menu-right'), ['dropdown-menu-end']);
|
|
assert.deepEqual(to('col-xs-6'), ['col-6']);
|
|
assert.equal(to('jumbotron'), null); // no equivalent
|
|
assert.equal(renameClass('mt-3'), null);
|
|
assert.equal(renameClass('ms-3'), null);
|
|
assert.equal(toBootstrap4Class('ms-3'), 'ml-3');
|
|
});
|
|
|
|
test('typos are found; the project\'s own classes and Twig are left alone', () => {
|
|
assert.deepEqual(unknownClass('card-bodyy', '5'), { suggest: 'card-body' });
|
|
assert.deepEqual(unknownClass('btn-primry', '5'), { suggest: 'btn-primary' });
|
|
assert.deepEqual(unknownClass('col-13', '5'), { suggest: 'col-1' });
|
|
assert.deepEqual(unknownClass('mt-9', '5'), { suggest: 'mt-0' });
|
|
assert.deepEqual(unknownClass('d-md-flexx', '5'), { suggest: 'd-md-flex' });
|
|
assert.equal(unknownClass('hero-banner', '5'), null);
|
|
assert.equal(unknownClass('site-nav', '5'), null);
|
|
assert.equal(unknownClass('btn-brand', '5'), null);
|
|
assert.equal(unknownClass('text-gradient', '5'), null);
|
|
assert.equal(unknownClass('mt-n2', '5'), null); // negative margins may be switched on
|
|
assert.equal(unknownClass('card-bodyy', '5', new Set(['card-bodyy'])), null); // the project's own CSS has it
|
|
assert.equal(nearestClass('zzzzzzzz', '5'), null);
|
|
});
|
|
|
|
test('hover documentation: the CSS in a line and the page of the docs', () => {
|
|
assert.equal(describeClass('mt-md-3', '5').css, 'margin-top: 1rem from md (>= 768px) up');
|
|
assert.equal(describeClass('col-lg-4', '5').css, 'width: 4/12 of the row from lg (>= 992px) up');
|
|
assert.equal(describeClass('d-none', '5').css, 'display: none on every width');
|
|
assert.match(describeClass('card', '5').doc, /5\.3\/components\/card/);
|
|
assert.equal(describeClass('my-class', '5'), null);
|
|
});
|
|
|
|
// ---- the checks ---------------------------------------------------------------------------------------------------------
|
|
test('a col must be in a row, a row in a container', () => {
|
|
assert.deepEqual(codes('<div class="container"><div class="row"><div class="col-md-6">a</div></div></div>'), []);
|
|
assert.ok(codes('<div class="container"><div class="col-md-6">a</div></div>').includes('col-outside-row'));
|
|
assert.ok(codes('<body><div class="row"><div class="col">a</div></div></body>').includes('row-outside-container'));
|
|
assert.deepEqual(codes('<div class="row"><div class="col">a</div></div>'), []); // a fragment (a Twig block): its container is elsewhere
|
|
assert.deepEqual(codes('<div class="card"><div class="card-body"><div class="row"><div class="col">a</div></div></div></div>'), []);
|
|
assert.deepEqual(codes('<div class="d-flex"><div class="col-6">a</div></div>'), []);
|
|
assert.deepEqual(codes('<div class="row"><div class="col-6 {{ x }}">a</div></div>'), []);
|
|
assert.deepEqual(codes('<div class="wrap"><div class="col-6">a</div>', {}), []); // an unclosed wrapper: the structure is not trusted
|
|
});
|
|
|
|
test('unknown classes, with a quick fix to the nearest one', () => {
|
|
const t = '<div class="container hero-banner card-bodyy"></div>';
|
|
const [f] = lintBootstrap(t);
|
|
assert.equal(f.code, 'unknown-class');
|
|
assert.equal(t.slice(f.start, f.end), 'card-bodyy');
|
|
assert.equal(apply(t, f), '<div class="container hero-banner card-body"></div>');
|
|
assert.deepEqual(codes('<div class="container my-custom {{ x }}"></div>'), []);
|
|
assert.deepEqual(codes('<div class="mylib-thing"></div>', { projectClasses: new Set(['mylib-thing']) }), []);
|
|
});
|
|
|
|
test('Bootstrap 4 classes and attributes in a Bootstrap 5 page, with a fix each and "convert all"', () => {
|
|
const t = '<div class="ml-3 pr-2 float-left text-left badge badge-primary mt-2" data-toggle="collapse" data-target="#c"></div><div id="c"></div>';
|
|
const found = lintBootstrap(t);
|
|
assert.deepEqual(found.map((f) => f.code), ['bs4-class', 'bs4-class', 'bs4-class', 'bs4-class', 'bs4-class', 'bs4-attr', 'bs4-attr']);
|
|
assert.equal(apply(t, found[0]), t.replace('ml-3', 'ms-3'));
|
|
const converted = applyEdits(t, convertAllEdits(found));
|
|
assert.equal(converted, '<div class="ms-3 pe-2 float-start text-start badge text-bg-primary mt-2" data-bs-toggle="collapse" data-bs-target="#c"></div><div id="c"></div>');
|
|
assert.deepEqual(codes(converted), []); // nothing left to convert
|
|
});
|
|
|
|
test('a class without equivalent says what to do by hand; removing a class leaves no double space', () => {
|
|
const [f] = lintBootstrap('<div class="jumbotron"></div>');
|
|
assert.equal(f.code, 'bs4-class');
|
|
assert.equal(f.fixes.length, 0);
|
|
assert.match(f.params.hint, /bg-body-tertiary/);
|
|
const t = '<div class="custom-control custom-checkbox x"></div>';
|
|
assert.equal(applyEdits(t, convertAllEdits(lintBootstrap(t))), '<div class="form-check x"></div>');
|
|
});
|
|
|
|
test('on a Bootstrap 4 page the same classes are not reported', () => {
|
|
assert.deepEqual(codes('<div class="ml-3 badge badge-primary" data-toggle="modal"></div>', { version: '4' }).filter((c) => c.startsWith('bs4')), []);
|
|
assert.ok(codes('<div class="ml-3" data-toggle="x"></div>', { version: '4', hintBs4: true }).includes('bs4-class'));
|
|
});
|
|
|
|
test('data-bs-target and href="#id" must point to an id of the page', () => {
|
|
assert.ok(codes('<button data-bs-toggle="collapse" data-bs-target="#nope"></button>').includes('target-missing'));
|
|
assert.deepEqual(codes('<button type="button" data-bs-toggle="collapse" data-bs-target="#yes"></button><div id="yes"></div>'), []);
|
|
assert.ok(codes('<a data-bs-toggle="tab" href="#gone">x</a>').includes('target-missing'));
|
|
assert.ok(codes('<button type="button" data-bs-toggle="modal">x</button>').includes('toggle-without-target'));
|
|
assert.deepEqual(codes('<button type="button" data-bs-toggle="dropdown">x</button>'), []);
|
|
assert.ok(codes('<button type="button" aria-controls="ghost">x</button>').includes('aria-ref-missing'));
|
|
assert.deepEqual(codes('<button type="button" data-bs-toggle="collapse" data-bs-target="#{{ id }}"></button>'), []);
|
|
});
|
|
|
|
test('parts of components outside their parent, dropdown wiring, duplicate ids', () => {
|
|
assert.ok(codes('<div class="modal-content"></div>').length === 0); // a fragment root: unknown parent
|
|
assert.ok(codes('<div><div class="modal-dialog"></div></div>').includes('orphan-part'));
|
|
assert.deepEqual(codes('<div class="modal" aria-labelledby="t"><div class="modal-dialog"><div class="modal-content"><h1 id="t">x</h1></div></div></div>'), []);
|
|
assert.ok(codes('<div><ul class="dropdown-menu"><li><a class="dropdown-item" href="#">a</a></li></ul></div>').includes('orphan-part'));
|
|
assert.deepEqual(codes('<div class="dropdown"><button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown">x</button><ul class="dropdown-menu"><li><a class="dropdown-item" href="#">a</a></li></ul></div>'), []);
|
|
const t = '<button type="button" class="btn dropdown-toggle">x</button>';
|
|
const [f] = lintBootstrap(t);
|
|
assert.equal(f.code, 'dropdown-toggle-attr');
|
|
assert.equal(apply(t, f), '<button data-bs-toggle="dropdown" type="button" class="btn dropdown-toggle">x</button>');
|
|
assert.ok(codes('<i id="a"></i><i id="a"></i>').includes('duplicate-id'));
|
|
});
|
|
|
|
test('accessibility: button type, image alt, labels, modal title, icon buttons, close buttons', () => {
|
|
let t = '<button class="btn">Save</button>';
|
|
assert.equal(apply(t, lintBootstrap(t)[0]), '<button type="button" class="btn">Save</button>');
|
|
t = '<img src="a.png">';
|
|
assert.equal(apply(t, lintBootstrap(t)[0]), '<img alt="" src="a.png">');
|
|
assert.ok(codes('<input type="text" class="form-control" id="n">').includes('control-label'));
|
|
assert.deepEqual(codes('<label for="n">N</label><input type="text" id="n">'), []);
|
|
assert.deepEqual(codes('<label>N <input type="text"></label>'), []);
|
|
assert.deepEqual(codes('<input type="text" aria-label="Search"><input type="hidden"><input type="submit">'), []);
|
|
assert.ok(codes('<div class="modal" tabindex="-1"><div class="modal-dialog"></div></div>').includes('modal-label'));
|
|
assert.ok(codes('<button type="button" class="btn btn-light"><i class="bi bi-x"></i></button>').includes('icon-button-label'));
|
|
assert.deepEqual(codes('<button type="button" class="btn"><i class="bi bi-x"></i> Close</button>'), []);
|
|
assert.deepEqual(codes('<button type="button" class="btn"><i class="bi bi-x"></i><span class="visually-hidden">Close</span></button>'), []);
|
|
assert.deepEqual(codes('<button type="button" class="btn" aria-label="Close"><svg></svg></button>'), []);
|
|
t = '<button type="button" class="btn-close" data-bs-dismiss="modal"></button>';
|
|
assert.equal(apply(t, lintBootstrap(t)[0]), '<button aria-label="Close" type="button" class="btn-close" data-bs-dismiss="modal"></button>');
|
|
assert.ok(codes('<div class="alert alert-info">x</div>').includes('alert-role'));
|
|
});
|
|
|
|
test('an interactive element inside an interactive one is an error', () => {
|
|
const found = lintBootstrap('<a href="#"><button type="button">x</button></a><button type="button"><a href="#">y</a></button><button type="button"><span>z</span></button>');
|
|
assert.deepEqual(found.filter((f) => f.code === 'nested-interactive').map((f) => f.params.tag), ['button', 'a']);
|
|
assert.ok(found.every((f) => f.code !== 'nested-interactive' || f.severity === 'error'));
|
|
});
|
|
|
|
test('Twig templates: blocks and conditionals do not make false findings', () => {
|
|
const t = `{% extends 'base.html.twig' %}
|
|
{% block body %}
|
|
<div class="row g-3">
|
|
{% for p in posts %}
|
|
<div class="col-12 col-md-6"><a class="btn btn-{{ p.kind }}" href="{{ path('post', {id: p.id}) }}">{{ p.title }}</a></div>
|
|
{% endfor %}
|
|
<img src="{{ asset('a.png') }}" alt="{{ p.alt }}">
|
|
</div>
|
|
{% endblock %}`;
|
|
assert.deepEqual(codes(t), []);
|
|
});
|
|
|
|
// ---- the palette --------------------------------------------------------------------------------------------------------
|
|
test('every palette snippet is clean in its Bootstrap version (ids, aria and data attributes wired)', () => {
|
|
for (const version of ['5', '4']) {
|
|
for (const [, items] of componentGroups(version)) {
|
|
for (const c of items) {
|
|
const text = snippetFor(c, '', version);
|
|
const found = lintBootstrap(text, { version }).filter((f) => !(f.code === 'alert-role' && f.severity === 'info'));
|
|
assert.deepEqual(found.map((f) => `${f.code}: ${text.slice(f.start, f.end)}`), [], `${c.id} in ${version}`);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
test('Bootstrap 4 gets no component that does not exist there, and the 4 markup of the others', () => {
|
|
const ids4 = componentGroups('4').flatMap(([, i]) => i.map((c) => c.id));
|
|
assert.ok(!ids4.includes('offcanvas') && !ids4.includes('floating') && ids4.includes('modal'));
|
|
const modal = snippetFor(COMPONENTS.find((c) => c.id === 'modal'), '', '4');
|
|
assert.ok(modal.includes('data-toggle="modal"') && modal.includes('class="close"') && !modal.includes('data-bs-'));
|
|
assert.ok(forVersion('<div class="ms-2 text-start">', '4').includes('ml-2 text-left'));
|
|
});
|
|
|
|
test('inserting a component twice gives unique ids, each wired to itself', () => {
|
|
const modal = COMPONENTS.find((c) => c.id === 'modal');
|
|
let page = '<body>\n</body>';
|
|
for (let i = 0; i < 3; i++) page = page.replace('</body>', snippetFor(modal, page, '5') + '\n</body>');
|
|
const ids = idsOf(parseMarkup(page));
|
|
assert.deepEqual([...ids.keys()].sort(), ['exampleModal', 'exampleModal2', 'exampleModal2Label', 'exampleModal3', 'exampleModal3Label', 'exampleModalLabel']);
|
|
assert.ok([...ids.values()].every((l) => l.length === 1));
|
|
assert.deepEqual(codes(page), []);
|
|
const ctx = snippetContext('<i id="x"></i>');
|
|
assert.deepEqual([ctx.id('x'), ctx.id('x'), ctx.id('y')], ['x2', 'x3', 'y']);
|
|
});
|
|
|
|
test('the palette covers what was asked', () => {
|
|
const ids = new Set(COMPONENTS.map((c) => c.id));
|
|
for (const id of ['navbar', 'container', 'grid', 'card', 'button', 'buttongroup', 'form', 'select', 'check', 'inputgroup', 'floating', 'validation', 'alert', 'badge', 'listgroup', 'table', 'modal', 'offcanvas', 'dropdown', 'accordion', 'carousel', 'tabs', 'pills', 'pagination', 'breadcrumb', 'toast', 'spinner', 'progress', 'placeholder']) assert.ok(ids.has(id), id);
|
|
});
|
|
|
|
// ---- the utilities --------------------------------------------------------------------------------------------------------
|
|
test('utility groups read and set a value per breakpoint', () => {
|
|
const classes = ['d-none', 'd-md-flex', 'col-12', 'col-md-6', 'p-3', 'text-center', 'text-primary', 'rounded', 'shadow-sm', 'btn'];
|
|
assert.equal(groupValue(GROUPS.display, classes, ''), 'none');
|
|
assert.equal(groupValue(GROUPS.display, classes, 'md'), 'flex');
|
|
assert.deepEqual(groupValues(GROUPS.col, classes), { '': '12', md: '6' });
|
|
assert.equal(groupValue(GROUPS.align, classes), 'center');
|
|
assert.equal(groupValue(GROUPS.textColor, classes), 'primary');
|
|
assert.equal(groupValue(GROUPS.p, classes), '3');
|
|
assert.equal(groupValue(GROUPS.shadow, classes), 'sm');
|
|
assert.equal(groupValue(GROUPS.rounded, classes), '');
|
|
assert.deepEqual(setGroup(GROUPS.col, classes, '4', 'lg').filter((c) => c.startsWith('col')), ['col-12', 'col-md-6', 'col-lg-4']);
|
|
assert.deepEqual(setGroup(GROUPS.col, ['col-md'], '', 'md'), ['col-md']);
|
|
assert.deepEqual(setGroup(GROUPS.col, ['col-md-6'], 'auto', 'md'), ['col-md-auto']);
|
|
assert.deepEqual(setGroup(GROUPS.align, ['text-center', 'text-primary'], 'end', '').sort(), ['text-end', 'text-primary']);
|
|
assert.deepEqual(setGroup(GROUPS.border, ['border'], null), []);
|
|
assert.deepEqual(setGroup(GROUPS.width, ['w-25', 'x'], '100'), ['w-100', 'x']);
|
|
});
|
|
|
|
test('every class a group makes exists in Bootstrap 5, and every group has values', () => {
|
|
const known = classSet('5');
|
|
for (const g of Object.values(GROUPS)) {
|
|
assert.ok(valuesAt(g, '').length > 0 || valuesAt(g, 'md').length > 0, g.id);
|
|
for (const c of g.lookup.keys()) assert.ok(known.has(c), c);
|
|
}
|
|
assert.ok(!valuesAt(GROUPS.offset, '').includes('0') && valuesAt(GROUPS.offset, 'md').includes('0'));
|
|
assert.deepEqual(valuesAt(GROUPS.grow, 'md'), []);
|
|
});
|
|
|
|
// ---- the AI --------------------------------------------------------------------------------------------------------------
|
|
test('the AI request names the region, the version and the rules', () => {
|
|
const page = '<main>\n <div class="row"><div class="col">a</div></div>\n <p>x</p>\n</main>';
|
|
const sel = { start: page.indexOf('<div class="row">'), end: page.indexOf('</div></div>') + 12 };
|
|
const r = buildRequest({ action: 'responsive', version: '5', text: page, selection: sel, path: 'templates/home.html.twig' });
|
|
assert.equal(r.scope, 'selection');
|
|
assert.equal(page.slice(r.range.start, r.range.end), '<div class="row"><div class="col">a</div></div>');
|
|
assert.match(r.prompt, /Bootstrap 5\.3/);
|
|
assert.match(r.prompt, /a Twig template/);
|
|
assert.match(r.prompt, /Keep every Twig tag/);
|
|
assert.match(r.prompt, /col-12 col-md-6/);
|
|
const el = buildRequest({ action: 'convert', version: '4', text: page, cursor: page.indexOf('<p>') + 4 });
|
|
assert.equal(page.slice(el.range.start, el.range.end), '<p>x</p>');
|
|
assert.match(el.prompt, /Bootstrap 4\.6/);
|
|
const file = buildRequest({ action: 'custom', instruction: 'Add a footer', text: page, scope: 'file' });
|
|
assert.deepEqual(file.range, { start: 0, end: page.length });
|
|
assert.match(file.prompt, /Add a footer/);
|
|
const hero = buildRequest({ action: 'hero', text: page, cursor: page.indexOf('<p>') + 4 });
|
|
assert.equal(hero.make, true);
|
|
assert.equal(hero.range.start, page.indexOf('</p>') + 4);
|
|
assert.match(hero.prompt, /<<HERE>>/);
|
|
});
|
|
|
|
test('with a fake AI: the answer becomes a replacement with the findings of the new page; refusals', async () => {
|
|
const page = '<div class="container">\n <div class="row">\n <div class="col">a</div>\n </div>\n</div>';
|
|
const ask = async (prompt) => { assert.match(prompt, /Task:/); return 'Here you go:\n```html\n<div class="row g-3">\n <div class="col-12 col-md-6">a</div>\n</div>\n```'; };
|
|
const req = buildRequest({ action: 'responsive', text: page, cursor: page.indexOf('<div class="row">') + 3 });
|
|
const out = await runAi(req, page, ask);
|
|
assert.equal(out.original, '<div class="row">\n <div class="col">a</div>\n </div>');
|
|
assert.equal(out.next, '<div class="container">\n <div class="row g-3">\n <div class="col-12 col-md-6">a</div>\n </div>\n</div>');
|
|
assert.deepEqual(out.findings, []);
|
|
const bad = async () => '<div class="rowx"><script>alert(1)</script></div>';
|
|
await assert.rejects(runAi(req, page, bad), /script/);
|
|
await assert.rejects(runAi(req, page, async () => 'Sorry, I cannot do that.'), /no-markup/);
|
|
const made = await runAi(buildRequest({ action: 'hero', text: page, cursor: 5 }), page, async () => '<section class="py-5"><h1 class="display-5">x</h1></section>');
|
|
assert.ok(made.next.startsWith('<div class="container">') && made.next.endsWith('</div>\n<section class="py-5"><h1 class="display-5">x</h1></section>'));
|
|
assert.equal(extractMarkup('```\n<p>x</p>\n```'), '<p>x</p>');
|
|
assert.equal(extractMarkup('no markup here'), null);
|
|
});
|
|
|
|
test('a Twig answer is accepted and its own findings are shown', async () => {
|
|
const page = '<div class="container"><p>x</p></div>';
|
|
const req = buildRequest({ action: 'custom', instruction: 'a form', text: page, cursor: 30, scope: 'selection', selection: { start: 23, end: 35 } });
|
|
const out = await runAi(req, page, async () => '<input class="form-control" type="text">');
|
|
assert.deepEqual(out.findings.map((f) => f.code), ['control-label']);
|
|
});
|
|
|
|
// ---- detection ------------------------------------------------------------------------------------------------------------
|
|
import { detectInText, detectInProject, mergeDetection, cssClasses } from './bootstrap-detect.js';
|
|
|
|
test('a page says it uses Bootstrap, and which one', async () => {
|
|
assert.deepEqual(detectInText('<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">'), { used: true, version: '5', reason: 'link' });
|
|
assert.equal(detectInText('<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.6.2/css/bootstrap.min.css">').version, '4');
|
|
assert.equal(detectInText('<button data-bs-toggle="modal">').version, '5');
|
|
assert.equal(detectInText('<button data-toggle="modal">').version, '4');
|
|
assert.equal(detectInText('<div class="ms-3">').version, '5');
|
|
assert.equal(detectInText('<div class="ml-3">').version, '4');
|
|
assert.deepEqual(detectInText('<div class="container"><div class="row"><div class="col-md-6">'), { used: true, version: null, reason: 'classes' });
|
|
assert.equal(detectInText('<div class="container"><p>x</p>').used, false);
|
|
assert.equal(detectInText('{% extends "base.html.twig" %}<p>plain</p>').used, false);
|
|
});
|
|
|
|
test('the project says it when the page does not (package.json, importmap, base template)', async () => {
|
|
const files = (map) => async (p) => map[p] ?? null;
|
|
assert.deepEqual(await detectInProject(files({ 'package.json': '{"dependencies":{"bootstrap":"^5.3.3"}}' })), { used: true, version: '5', reason: 'package.json' });
|
|
assert.equal((await detectInProject(files({ 'package.json': '{"devDependencies":{"bootstrap":"~4.6.0"}}' }))).version, '4');
|
|
assert.equal((await detectInProject(files({ 'importmap.php': "<?php return ['bootstrap' => ['version' => '5.3.3']];" }))).reason, 'importmap');
|
|
const viaBase = await detectInProject(files({ 'templates/base.html.twig': '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">' }));
|
|
assert.deepEqual([viaBase.used, viaBase.version, viaBase.reason], [true, '5', 'templates/base.html.twig']);
|
|
assert.equal((await detectInProject(files({}))).used, false);
|
|
assert.equal(mergeDetection({ used: false }, { used: true, version: '4', reason: 'x' }).version, '4');
|
|
assert.equal(mergeDetection({ used: true, version: '5', reason: 'link' }, { used: true, version: '4' }).version, '5');
|
|
assert.equal(mergeDetection({ used: true, version: '4', reason: 'data-toggle' }, { used: true, version: '5' }).version, '5'); // an old page of a Bootstrap 5 project
|
|
assert.equal(mergeDetection({ used: true, version: null, reason: 'classes' }, null).version, '5');
|
|
assert.equal(mergeDetection({ used: true, version: '4', reason: 'classes' }, null).version, '4');
|
|
assert.equal(mergeDetection({ used: false }, { used: false }), null);
|
|
});
|
|
|
|
test('the project\'s own CSS classes are collected', () => {
|
|
const s = cssClasses('/* .no */ .hero-banner { margin: .5rem } .a:hover, .b > .c-d { x: 1 } @media (min-width: 1px) { .e { y: 2 } } a.link { z: 3 }');
|
|
assert.deepEqual([...s].sort(), ['a', 'b', 'c-d', 'e', 'hero-banner', 'link'].filter((c) => c !== 'a' || true).sort());
|
|
});
|