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

167 lines
13 KiB
JavaScript

// What the Bootstrap editor knows about Bootstrap's classes (no DOM: node --test runs it): the real class lists of 5.3 and 4.6
// (bootstrap-classes.js, generated from their stylesheets), the BS4 -> BS5 renames, near-miss suggestions, and where a class is
// documented. Versions are the strings '5' and '4'.
import { BOOTSTRAP_CLASSES } from './bootstrap-classes.js';
export const BREAKPOINTS = ['sm', 'md', 'lg', 'xl', 'xxl'];
export const BREAKPOINT_WIDTH = { '': 0, sm: 576, md: 768, lg: 992, xl: 1200, xxl: 1400 };
export const COLORS = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'];
const sets = {};
export function classSet(version) {
const v = String(version) === '4' ? '4' : '5';
return (sets[v] ||= new Set(BOOTSTRAP_CLASSES[v].split(' ')));
}
/** the classes of Bootstrap 5 that Bootstrap 4 had under another name (value: what to write in 5), or no equivalent (null) */
export function renameClass(cls) {
let m;
if ((m = /^([mp])([lr])-(.+)$/.exec(cls)) && /^((sm|md|lg|xl)-)?(\d|auto|n\d)$/.test(m[3])) return { to: [`${m[1]}${m[2] === 'l' ? 's' : 'e'}-${m[3]}`] };
if ((m = /^float-((?:sm-|md-|lg-|xl-)?)(left|right)$/.exec(cls))) return { to: [`float-${m[1]}${m[2] === 'left' ? 'start' : 'end'}`] };
if ((m = /^text-((?:sm-|md-|lg-|xl-)?)(left|right)$/.exec(cls))) return { to: [`text-${m[1]}${m[2] === 'left' ? 'start' : 'end'}`] };
if ((m = /^border-(left|right)(-0)?$/.exec(cls))) return { to: [`border-${m[1] === 'left' ? 'start' : 'end'}${m[2] || ''}`] };
if ((m = /^rounded-(left|right)$/.exec(cls))) return { to: [`rounded-${m[1] === 'left' ? 'start' : 'end'}`] };
if ((m = /^font-weight-(bold|bolder|normal|light|lighter)$/.exec(cls))) return { to: [`fw-${m[1]}`] };
if ((m = /^badge-(primary|secondary|success|danger|warning|info|light|dark)$/.exec(cls))) return { to: [`text-bg-${m[1]}`] };
if ((m = /^dropdown-menu-((?:sm-|md-|lg-|xl-)?)(left|right)$/.exec(cls))) return { to: [`dropdown-menu-${m[1]}${m[2] === 'left' ? 'start' : 'end'}`] };
if ((m = /^col-xs-(\d+|auto)$/.exec(cls))) return { to: [`col-${m[1]}`] };
if ((m = /^thead-(light|dark)$/.exec(cls))) return { to: [`table-${m[1]}`] };
const table = {
'font-italic': ['fst-italic'], 'text-monospace': ['font-monospace'], 'sr-only': ['visually-hidden'], 'sr-only-focusable': ['visually-hidden-focusable'],
'badge-pill': ['rounded-pill'], 'custom-select': ['form-select'], 'custom-range': ['form-range'], 'custom-control': ['form-check'],
'custom-checkbox': [], 'custom-radio': [], 'custom-switch': ['form-switch'], 'custom-control-input': ['form-check-input'],
'custom-control-label': ['form-check-label'], 'custom-control-inline': ['form-check-inline'], 'custom-file': [],
'form-group': ['mb-3'], 'form-row': ['row', 'g-2'], 'form-control-file': ['form-control'], 'form-control-range': ['form-range'],
'no-gutters': ['g-0'], media: ['d-flex'], 'media-body': ['flex-grow-1'], close: ['btn-close'], dropleft: ['dropstart'], dropright: ['dropend'],
};
if (cls in table) return { to: table[cls] };
// no equivalent: the page has to be reworked by hand
const manual = ['jumbotron', 'card-deck', 'card-columns', 'btn-block', 'input-group-append', 'input-group-prepend', 'form-inline', 'text-justify', 'text-hide', 'embed-responsive',
'embed-responsive-item', 'embed-responsive-16by9', 'embed-responsive-4by3', 'embed-responsive-1by1', 'embed-responsive-21by9', 'custom-file-input', 'custom-file-label', 'pre-scrollable'];
if (manual.includes(cls)) return { to: null };
return null;
}
/** what to do by hand for a class without an equivalent: a key of the language files (bootstrap-lint.js turns it into text) */
export const MANUAL_HINT = {
jumbotron: 'p-5 mb-4 bg-body-tertiary rounded-3', 'card-deck': 'row row-cols-1 row-cols-md-3 g-4', 'card-columns': 'row (masonry needs a library)',
'btn-block': 'd-grid gap-2 on the parent (or w-100)', 'input-group-append': 'put the button directly in the .input-group', 'input-group-prepend': 'put the text directly in the .input-group',
'form-inline': 'row row-cols-lg-auto g-3 align-items-center', 'text-justify': 'a style of your own', 'text-hide': 'a style of your own',
'embed-responsive': 'ratio ratio-16x9', 'embed-responsive-item': 'ratio ratio-16x9 on the parent', 'embed-responsive-16by9': 'ratio ratio-16x9', 'embed-responsive-4by3': 'ratio ratio-4x3',
'embed-responsive-1by1': 'ratio ratio-1x1', 'embed-responsive-21by9': 'ratio ratio-21x9', 'custom-file-input': 'form-control type="file"', 'custom-file-label': 'form-control type="file"',
'pre-scrollable': 'overflow-auto and a max-height of your own',
};
/** Bootstrap 4's data attributes that have the bs- infix in 5 */
export const DATA_RENAMED = ['toggle', 'target', 'dismiss', 'ride', 'slide', 'slide-to', 'parent', 'content', 'placement', 'trigger', 'spy', 'offset', 'backdrop', 'keyboard',
'interval', 'autohide', 'delay', 'animation', 'boundary', 'pause', 'wrap', 'touch', 'focus', 'reference'];
/** Bootstrap 5 classes -> 4 (the palette's snippets for a Bootstrap 4 page) */
export function toBootstrap4Class(cls) {
let m;
// Bootstrap 5 only: gutters, font sizes, the grid display, gap helpers, the 5th and 6th display heading (no class in 4)
if (/^g[xy]?-\d$|^fs-\d$|^d-grid$|^gap-\d$/.test(cls)) return null;
if (/^display-[56]$/.test(cls)) return 'display-4';
if ((m = /^([mp])([se])-(.+)$/.exec(cls))) return `${m[1]}${m[2] === 's' ? 'l' : 'r'}-${m[3]}`;
if ((m = /^float-((?:sm-|md-|lg-|xl-)?)(start|end)$/.exec(cls))) return `float-${m[1]}${m[2] === 'start' ? 'left' : 'right'}`;
if ((m = /^text-((?:sm-|md-|lg-|xl-)?)(start|end)$/.exec(cls))) return `text-${m[1]}${m[2] === 'start' ? 'left' : 'right'}`;
if ((m = /^fw-(bold|bolder|normal|light|lighter)$/.exec(cls))) return `font-weight-${m[1]}`;
if ((m = /^dropdown-menu-((?:sm-|md-|lg-|xl-)?)(start|end)$/.exec(cls))) return `dropdown-menu-${m[1]}${m[2] === 'start' ? 'left' : 'right'}`;
if ((m = /^text-bg-(.+)$/.exec(cls))) return `badge-${m[1]}`;
const table = { 'form-select': 'custom-select', 'form-range': 'custom-range', 'visually-hidden': 'sr-only', 'rounded-pill': 'badge-pill', 'bg-body-tertiary': 'bg-light',
'fst-italic': 'font-italic', 'font-monospace': 'text-monospace', dropstart: 'dropleft', dropend: 'dropright', 'text-body-secondary': 'text-muted' };
return cls in table ? table[cls] : cls;
}
// Bootstrap's families a class with a dash can not leave: a made-up member of them is a typo (col-13, mt-6, d-md-flexx), not a project class
const STRICT = new RegExp('^(?:(?:col|offset|row-cols|d|order|justify-content|align-items|align-self|align-content|flex|fw|fst|fs|lh|shadow|position|float|z|opacity|overflow|visually)-.+'
+ '|[mp][tbsexy]?-(?:(?:sm|md|lg|xl|xxl)-)?(?:\\d+|auto)|g[xy]?-(?:(?:sm|md|lg|xl|xxl)-)?\\d+|gap-(?:(?:sm|md|lg|xl|xxl)-)?\\d+|[wh]-\\d+)$');
const spacing = /^[mp][tbsexy]?-(?:(?:sm|md|lg|xl|xxl)-)?n\d$/; // negative margins: off by default, a project may turn them on
/** distance between two class names (small ones: a typo) */
function distance(a, b) {
if (Math.abs(a.length - b.length) > 2) return 9;
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let prev = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const keep = row[j];
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
prev = keep;
}
}
return row[b.length];
}
/** the known class a typo is closest to (distance <= 2, <= 1 for a short one), or null */
export function nearestClass(cls, version, extra = null) {
const limit = cls.length < 7 ? 1 : 2;
let best = null;
let bestD = limit + 1;
const pool = [classSet(version), extra || []];
for (const set of pool) {
for (const c of set) {
if (Math.abs(c.length - cls.length) > limit) continue;
const d = distance(cls, c);
if (d < bestD) { best = c; bestD = d; if (d === 1) { return best; } }
}
}
return best;
}
/**
* What to say about a class that is not in Bootstrap's list: null (it may be the project's own), or {suggest} (a typo of a
* Bootstrap class, or a made-up member of a family Bootstrap fully lists: suggest may be null).
*/
export function unknownClass(cls, version, projectClasses = null) {
if (classSet(version).has(cls) || projectClasses?.has(cls) || spacing.test(cls)) return null;
const near = nearestClass(cls, version, projectClasses);
// a project class that is only a typo of another project class is not Bootstrap's business
if (near && projectClasses?.has(near) && !classSet(version).has(near)) return null;
if (near && cls.length >= 4 && cls.includes('-') === near.includes('-')) return { suggest: near };
if (STRICT.test(cls)) return { suggest: null };
return null;
}
/** every class that is known in 4 and not in 5 (for the "this is Bootstrap 4" hint) */
export const isBootstrap4Only = (cls) => classSet('4').has(cls) && !classSet('5').has(cls);
const SPACERS = ['0', '.25rem', '.5rem', '1rem', '1.5rem', '3rem'];
const DOCS = [
[/^[mp][tbsexy]?-/, 'utilities/spacing'], [/^(?:d|float|visible|invisible|visually)-?/, 'utilities/display'], [/^(?:container|row|col|offset|g|gx|gy|row-cols)(?:-|$)/, 'layout/grid'],
[/^(?:flex|justify-content|align-items|align-self|align-content|order|gap)-/, 'utilities/flex'], [/^(?:text|fw|fst|fs|lh|font|display|lead|small|mark|h[1-6])(?:-|$)/, 'utilities/text'],
[/^bg-/, 'utilities/background'], [/^(?:border|rounded)(?:-|$)/, 'utilities/borders'], [/^shadow/, 'utilities/shadows'], [/^(?:position|top|bottom|start|end|translate|fixed|sticky)(?:-|$)/, 'utilities/position'],
[/^(?:w|h|mw|mh|vw|vh|min-vw|min-vh)-/, 'utilities/sizing'], [/^btn(?:-|$)/, 'components/buttons'], [/^navbar/, 'components/navbar'], [/^nav(?:-|$)/, 'components/navs-tabs'], [/^card/, 'components/card'],
[/^(?:form|input-group)/, 'forms/overview'], [/^alert/, 'components/alerts'], [/^badge/, 'components/badge'], [/^list-group/, 'components/list-group'], [/^table/, 'content/tables'],
[/^modal/, 'components/modal'], [/^offcanvas/, 'components/offcanvas'], [/^dropdown/, 'components/dropdowns'], [/^accordion/, 'components/accordion'], [/^carousel/, 'components/carousel'],
[/^(?:pagination|page-)/, 'components/pagination'], [/^breadcrumb/, 'components/breadcrumb'], [/^toast/, 'components/toasts'], [/^spinner/, 'components/spinners'], [/^progress/, 'components/progress'],
[/^placeholder/, 'components/placeholders'], [/^(?:collapse|collapsing)/, 'components/collapse'], [/^(?:tooltip|popover)/, 'components/' + 'popovers'],
];
const bpName = (bp) => (bp ? `from ${bp} (>= ${BREAKPOINT_WIDTH[bp]}px) up` : 'on every width');
/** a short, language-free description of a class: its CSS in one line, and its page in Bootstrap's docs. null for a class that is not Bootstrap's */
export function describeClass(cls, version = '5') {
if (!classSet(version).has(cls)) return null;
const v = String(version) === '4' ? '4.6' : '5.3';
let m;
let css = '';
if ((m = /^([mp])([tbsexy]?)-(?:(sm|md|lg|xl|xxl)-)?(\d|auto)$/.exec(cls))) {
const prop = m[1] === 'm' ? 'margin' : 'padding';
const side = m[2] ? { t: '-top', b: '-bottom', s: '-inline-start', e: '-inline-end', x: '-inline', y: '-block' }[m[2]] : '';
css = `${prop}${side}: ${m[4] === 'auto' ? 'auto' : SPACERS[Number(m[4])]} ${bpName(m[3] || '')}`;
} else if ((m = /^col(?:-(?:(sm|md|lg|xl|xxl)-)?(\d+|auto))?$/.exec(cls))) {
css = `width: ${m[2] === 'auto' || (!m[2]) ? (m[2] ? 'auto (content)' : 'equal share of the row') : `${m[2]}/12 of the row`} ${bpName(m[1] || '')}`;
} else if ((m = /^d-(?:(sm|md|lg|xl|xxl)-)?([a-z-]+)$/.exec(cls))) css = `display: ${m[2]} ${bpName(m[1] || '')}`;
else if ((m = /^g([xy]?)-(?:(sm|md|lg|xl|xxl)-)?(\d)$/.exec(cls))) css = `gutter${m[1] ? ' ' + m[1] : ''}: ${SPACERS[Number(m[3])]} ${bpName(m[2] || '')}`;
else if ((m = /^gap-(?:(sm|md|lg|xl|xxl)-)?(\d)$/.exec(cls))) css = `gap: ${SPACERS[Number(m[2])]} ${bpName(m[1] || '')}`;
else if ((m = /^fs-(\d)$/.exec(cls))) css = `font-size: ${['2.5rem', '2rem', '1.75rem', '1.5rem', '1.25rem', '1rem'][Number(m[1]) - 1]}`;
else if ((m = /^w-(\d+|auto)$/.exec(cls))) css = `width: ${m[1] === 'auto' ? 'auto' : m[1] + '%'}`;
else if ((m = /^h-(\d+|auto)$/.exec(cls))) css = `height: ${m[1] === 'auto' ? 'auto' : m[1] + '%'}`;
else if ((m = /^text-(start|center|end)$/.exec(cls))) css = `text-align: ${{ start: 'left', center: 'center', end: 'right' }[m[1]]}`;
const doc = DOCS.find(([re]) => re.test(cls));
return { css, doc: doc ? `https://getbootstrap.com/docs/${v}/${doc[1]}/` : `https://getbootstrap.com/docs/${v}/` };
}
/** the side letters of the spacing helpers, for the inspector */
export const SPACING_SIDES = ['t', 'b', 's', 'e', 'x', 'y'];