489 lines
32 KiB
JavaScript
489 lines
32 KiB
JavaScript
// The Bootstrap editor (the editor's "Bootstrap" mode of an .html / .twig file that uses Bootstrap): the code on the left; on the
|
||
// right the page (drawn with Bootstrap's CSS, click an element to select it, drop a component on it) and, under it, the palette of
|
||
// components, the utilities inspector for the selected element, the problems with their quick fixes, and "Ask the AI". Every
|
||
// change is one edit of the code (undo brings it back); the page is drawn again after it.
|
||
import { backend } from './backend.js';
|
||
import { HtmlPreview } from './html-preview.js';
|
||
import { twigPreviewText } from './twig-preview.js';
|
||
import { el, clear, notify, dialog, prefs, debounce, t } from './ui.js';
|
||
import { parseMarkup, elementAt, classesOf, setClasses, markElements, insertSnippet, insertAtOffset, pathOf, elementByPath, attrValue } from './bootstrap-model.js';
|
||
import { componentGroups, snippetFor } from './bootstrap-components.js';
|
||
import { GROUPS, SECTIONS, groupValue, groupValues, setGroup, valuesAt } from './bootstrap-utilities.js';
|
||
import { BREAKPOINTS, classSet } from './bootstrap-catalog.js';
|
||
import { lintBootstrap, convertAllEdits } from './bootstrap-lint.js';
|
||
import { describe, fixLabel } from './bootstrap-support.js';
|
||
import { AI_ACTIONS, buildRequest, runAi } from './bootstrap-ai.js';
|
||
|
||
const STYLE = `
|
||
.bse { position: absolute; inset: 0; display: flex; flex-direction: column; background: var(--bg, #1e1f22); color: var(--text, #dfe1e5); font-size: 12px; }
|
||
.bse-prev { flex: 1 1 50%; min-height: 120px; position: relative; }
|
||
.bse-panel { flex: 0 0 46%; display: flex; flex-direction: column; border-top: 1px solid var(--border-2, #393b40); min-height: 0; }
|
||
.bse-tabs { display: flex; gap: 2px; padding: 3px 6px; border-bottom: 1px solid var(--border-2, #393b40); align-items: center; flex: none; }
|
||
.bse-tabs button { white-space: nowrap; font: inherit; color: inherit; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 2px 10px; cursor: pointer; }
|
||
.bse-tabs button.on { background: var(--accent, #3574f0); color: #fff; }
|
||
.bse-tabs .sel { flex: 1; min-width: 0; color: var(--text-2, #8c8f96); font-family: var(--mono, monospace); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin: 0 6px; }
|
||
.bse-tabs label { white-space: nowrap; display: flex; align-items: center; gap: 3px; }
|
||
.bse-body { flex: 1; overflow: auto; padding: 8px 10px; min-height: 0; }
|
||
.bse-groupname { font-weight: 600; margin: 8px 0 4px; color: var(--text-2, #8c8f96); text-transform: uppercase; font-size: 10px; letter-spacing: .05em; }
|
||
.bse-items { display: flex; flex-wrap: wrap; gap: 4px; }
|
||
.bse-item { font: inherit; color: inherit; background: var(--bg-2, #2b2d30); border: 1px solid var(--border-2, #393b40); border-radius: 4px; padding: 3px 9px; cursor: grab; }
|
||
.bse-item:hover { border-color: var(--accent, #3574f0); }
|
||
.bse-row { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; flex-wrap: wrap; }
|
||
.bse select, .bse input[type=text], .bse textarea { font: inherit; color: inherit; background: var(--bg, #1e1f22); border: 1px solid var(--border-2, #393b40); border-radius: 4px; padding: 2px 4px; }
|
||
.bse textarea { width: 100%; box-sizing: border-box; }
|
||
.bse-bp { display: flex; gap: 2px; }
|
||
.bse-bp button, .bse-btn { font: inherit; color: inherit; background: transparent; border: 1px solid var(--border-2, #393b40); border-radius: 4px; padding: 1px 8px; cursor: pointer; }
|
||
.bse-bp button.on { background: var(--accent, #3574f0); border-color: var(--accent, #3574f0); color: #fff; }
|
||
.bse-bp button.set::after { content: '•'; margin-left: 3px; color: #ffaa00; }
|
||
.bse-btn.primary { background: var(--accent, #3574f0); color: #fff; border-color: var(--accent, #3574f0); }
|
||
.bse-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 4px 14px; }
|
||
.bse-field { display: flex; align-items: center; justify-content: space-between; gap: 6px; }
|
||
.bse-field.set span { color: var(--accent, #3574f0); font-weight: 600; }
|
||
.bse-box { display: inline-grid; grid-template-columns: auto auto auto; gap: 3px; align-items: center; justify-items: center; padding: 6px; border: 1px dashed #d99a4e; border-radius: 4px; background: rgba(217,154,78,.08); margin-right: 10px; }
|
||
.bse-box.pad { border: 1px dashed #6aa84f; background: rgba(106,168,79,.08); }
|
||
.bse-box .mid { grid-column: 1 / -1; justify-self: start; }
|
||
.bse-box select { width: 58px; }
|
||
.bse-box label { font-size: 10px; color: var(--text-2, #8c8f96); }
|
||
.bse-chips { display: flex; flex-wrap: wrap; gap: 3px; margin-bottom: 6px; }
|
||
.bse-chip { background: var(--bg-2, #2b2d30); border: 1px solid var(--border-2, #393b40); border-radius: 10px; padding: 0 4px 0 8px; font-family: var(--mono, monospace); }
|
||
.bse-chip b { cursor: pointer; margin-left: 4px; color: var(--text-2, #8c8f96); font-weight: normal; }
|
||
.bse-crumbs { display: flex; gap: 2px; flex-wrap: wrap; margin-bottom: 6px; }
|
||
.bse-crumbs button { font: inherit; font-family: var(--mono, monospace); color: inherit; background: transparent; border: 0; cursor: pointer; padding: 0 3px; }
|
||
.bse-crumbs button:hover, .bse-crumbs button.on { color: var(--accent, #3574f0); }
|
||
.bse-prob { display: flex; gap: 6px; align-items: baseline; padding: 2px 0; cursor: pointer; }
|
||
.bse-prob:hover { background: rgba(127,127,127,.12); }
|
||
.bse-prob .sev { width: 14px; flex: none; }
|
||
.bse-prob .msg { flex: 1; }
|
||
.bse-prob .where { color: var(--text-2, #8c8f96); flex: none; }
|
||
.bse-note { color: var(--text-2, #8c8f96); }
|
||
.bse-drop { position: absolute; inset: 0; z-index: 5; display: none; }
|
||
.bse-diff { height: 52vh; min-width: min(900px, 80vw); }
|
||
`;
|
||
const addStyle = () => {
|
||
if (document.getElementById('bse-style')) return;
|
||
document.head.append(el('style', { id: 'bse-style' }, STYLE));
|
||
};
|
||
|
||
// runs in the preview's page: marks the selected element, tells which one was clicked, answers where a dragged component would go
|
||
const PAGE_SCRIPT = `(() => {
|
||
const st = document.createElement('style');
|
||
st.textContent = '[data-jb-sel]{outline:2px solid #3574f0!important;outline-offset:-2px;background-image:linear-gradient(rgba(53,116,240,.10),rgba(53,116,240,.10))}[data-jb-hover]{outline:1px dashed #3574f0!important;outline-offset:-1px}#jb-drop{position:fixed;pointer-events:none;z-index:2147483647;background:rgba(53,116,240,.25);border:2px solid #3574f0;box-sizing:border-box}';
|
||
document.head.append(st);
|
||
const mark = (n) => { while (n && !(n.getAttribute && n.getAttribute('data-jb'))) n = n.parentElement; return n; };
|
||
let sel = null, hov = null, drop = null;
|
||
const send = (m) => parent.postMessage(m, '*');
|
||
document.addEventListener('mouseover', (e) => { hov && hov.removeAttribute('data-jb-hover'); hov = mark(e.target); hov && hov.setAttribute('data-jb-hover', ''); }, true);
|
||
document.addEventListener('mouseout', () => { hov && hov.removeAttribute('data-jb-hover'); hov = null; }, true);
|
||
document.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); const n = mark(e.target); if (n) send({ jumphpBs: 'pick', id: n.getAttribute('data-jb') }); }, true);
|
||
addEventListener('message', (e) => {
|
||
const d = e.data;
|
||
if (e.source !== parent || !d || !d.jumphpBs) return;
|
||
if (d.jumphpBs === 'select') {
|
||
sel && sel.removeAttribute('data-jb-sel');
|
||
sel = document.querySelector('[data-jb="' + d.id + '"]');
|
||
if (sel) { sel.setAttribute('data-jb-sel', ''); const r = sel.getBoundingClientRect(); if (r.top < 0 || r.bottom > innerHeight) sel.scrollIntoView({ block: 'center' }); }
|
||
} else if (d.jumphpBs === 'hit') {
|
||
const n = mark(document.elementFromPoint(d.x, d.y));
|
||
drop && drop.remove(); drop = null;
|
||
if (!n) return send({ jumphpBs: 'hit', id: null });
|
||
const r = n.getBoundingClientRect();
|
||
const rel = d.y < r.top + r.height * .25 ? 'before' : d.y > r.bottom - r.height * .25 ? 'after' : 'inside';
|
||
drop = document.createElement('div'); drop.id = 'jb-drop';
|
||
const top = rel === 'before' ? r.top - 2 : rel === 'after' ? r.bottom - 2 : r.top;
|
||
drop.style.cssText = 'left:' + r.left + 'px;width:' + r.width + 'px;top:' + top + 'px;height:' + (rel === 'inside' ? r.height : 4) + 'px;' + (rel === 'inside' ? 'background:rgba(53,116,240,.12)' : '');
|
||
document.body.append(drop);
|
||
send({ jumphpBs: 'hit', id: n.getAttribute('data-jb'), rel });
|
||
} else if (d.jumphpBs === 'clear') { drop && drop.remove(); drop = null; }
|
||
});
|
||
send({ jumphpBs: 'ready' });
|
||
})();`;
|
||
|
||
const HIDDEN_CSS = `<style>.modal{position:relative!important;display:block!important;opacity:1!important;z-index:auto!important}.modal-backdrop{display:none!important}.offcanvas{position:relative!important;visibility:visible!important;transform:none!important;display:flex!important}.offcanvas-backdrop{display:none}.dropdown-menu{display:block!important;position:static!important}.toast,.toast-container{position:static!important}.toast{opacity:1!important;display:block!important}.collapse:not(.show){display:block!important}.tab-pane{display:block!important;opacity:1!important}.fade:not(.show){opacity:1!important}.carousel-item{display:block!important;position:static!important}.carousel-inner{display:flex;flex-direction:column;gap:6px}</style>`;
|
||
|
||
const LABELS = () => ({
|
||
col: t('Column'), offset: t('Offset'), order: t('Order'), g: t('Gutter'), display: t('Display'), float: t('Float'), visibility: t('Visibility'), overflow: t('Overflow'),
|
||
direction: t('Direction'), justify: t('Justify'), items: t('Align items'), self: t('Align self'), wrap: t('Wrap'), grow: t('Grow'), gap: t('Gap'), align: t('Text align'),
|
||
weight: t('Weight'), size: t('Size'), style: t('Style'), transform: t('Transform'), textColor: t('Text colour'), bg: t('Background'), textBg: t('Text on background'),
|
||
border: t('Border'), bordertop: t('Border top'), borderend: t('Border end'), borderbottom: t('Border bottom'), borderstart: t('Border start'), borderColor: t('Border colour'),
|
||
borderWidth: t('Border width'), rounded: t('Rounded'), shadow: t('Shadow'), position: t('Position'), width: t('Width'), height: t('Height'),
|
||
});
|
||
const SECTION_LABELS = () => ({ grid: t('Grid'), spacing: t('Spacing'), display: t('Display'), flex: t('Flex'), text: t('Text'), colors: t('Colours'), borders: t('Borders'), position: t('Position and size') });
|
||
|
||
export class BootstrapEditor {
|
||
/**
|
||
* @param {HTMLElement} host
|
||
* @param {{model: object, monaco: object, editor: object, path: string, twig: boolean, info: {version: string}, support: object,
|
||
* readText: Function, readDataUrl: Function, htmlFiles: Function, projectClasses?: () => Promise<Set<string>>, ask?: Function}} o
|
||
*/
|
||
constructor(host, o) {
|
||
addStyle();
|
||
this.o = o;
|
||
this.model = o.model;
|
||
this.version = o.info?.version === '4' ? '4' : '5';
|
||
this.tab = prefs.get('bsTab', 'components');
|
||
this.bp = '';
|
||
this.where = prefs.get('bsInsert', 'after');
|
||
this.showHidden = prefs.get('bsHidden', true) !== false;
|
||
this.path = null; // the selected element, as its path in the document
|
||
this.parsedFor = -1;
|
||
this.node = el('div.bse');
|
||
this.previewHost = el('div.bse-prev');
|
||
this.dropLayer = el('div.bse-drop');
|
||
this.body = el('div.bse-body');
|
||
this.tabsBar = el('div.bse-tabs');
|
||
this.node.append(this.previewHost, el('div.bse-panel', {}, this.tabsBar, this.body));
|
||
host.append(this.node);
|
||
this.previewHost.append(this.dropLayer);
|
||
this.preview = new HtmlPreview(this.previewHost, {
|
||
path: o.path, kind: 'html', twig: o.twig, prefix: 'bsPreview',
|
||
text: async (p) => {
|
||
this.renderedVersion = this.model.getVersionId();
|
||
const marked = markElements(this.model.getValue());
|
||
return o.twig ? twigPreviewText(o.path, marked, o.readText, p?.layout !== false) : marked;
|
||
},
|
||
readText: o.readText, readDataUrl: o.readDataUrl, htmlFiles: o.htmlFiles, script: PAGE_SCRIPT,
|
||
head: (doc) => this.head(doc),
|
||
onFrameMessage: (d) => this.fromPage(d),
|
||
});
|
||
this.previewHost.append(this.dropLayer);
|
||
this.setupDrop();
|
||
const refresh = debounce(() => { this.preview.update(); this.refreshPanel(); }, 400);
|
||
this.sub = this.model.onDidChangeContent(refresh);
|
||
this.cursorSub = o.editor?.onDidChangeCursorPosition((e) => { if (e.source !== 'bse') this.followCursor(); });
|
||
this.render();
|
||
this.followCursor();
|
||
}
|
||
|
||
destroy() {
|
||
this.sub?.dispose();
|
||
this.cursorSub?.dispose();
|
||
this.preview.destroy();
|
||
this.node.remove();
|
||
}
|
||
|
||
// the document ----------------------------------------------------------------------------------------------------
|
||
doc() {
|
||
const v = this.model.getVersionId();
|
||
if (this.parsedFor !== v) { this.parsed = parseMarkup(this.model.getValue()); this.parsedFor = v; }
|
||
return this.parsed;
|
||
}
|
||
|
||
selected() { return this.path ? elementByPath(this.doc(), this.path) : null; }
|
||
|
||
apply(edits, { select = true } = {}) {
|
||
const list = (Array.isArray(edits) ? edits : [edits]).filter(Boolean);
|
||
if (!list.length) return;
|
||
const { monaco, editor } = this.o;
|
||
const ops = list.map((e) => {
|
||
const a = this.model.getPositionAt(e.start);
|
||
const b = this.model.getPositionAt(e.end);
|
||
return { range: new monaco.Range(a.lineNumber, a.column, b.lineNumber, b.column), text: e.text, forceMoveMarkers: true };
|
||
});
|
||
this.model.pushStackElement();
|
||
this.model.pushEditOperations(editor?.getSelections?.() || [], ops, () => null); // one undo step
|
||
this.model.pushStackElement();
|
||
void select;
|
||
this.refreshPanel();
|
||
}
|
||
|
||
// the preview ----------------------------------------------------------------------------------------------------
|
||
async head(doc) {
|
||
const links = [...doc.querySelectorAll('link[rel~="stylesheet" i]')].map((l) => l.getAttribute('href') || '');
|
||
let css = '';
|
||
if (!links.some((h) => /bootstrap/i.test(h)) && !(await this.pageHasBootstrapStyle(doc))) {
|
||
let found = null;
|
||
for (const p of ['assets/vendor/bootstrap/dist/css/bootstrap.min.css', 'assets/vendor/bootstrap/css/bootstrap.min.css', 'public/vendor/bootstrap/dist/css/bootstrap.min.css',
|
||
'public/css/bootstrap.min.css', 'node_modules/bootstrap/dist/css/bootstrap.min.css', 'assets/css/bootstrap.min.css', 'css/bootstrap.min.css']) {
|
||
if (typeof (await this.o.readText(p).catch(() => null)) === 'string') { found = '/' + p; break; }
|
||
}
|
||
css = `<link rel="stylesheet" href="${found || `https://cdn.jsdelivr.net/npm/bootstrap@${this.version === '4' ? '4.6.2' : '5.3.3'}/dist/css/bootstrap.min.css`}">`;
|
||
}
|
||
return css + (this.showHidden ? HIDDEN_CSS : '');
|
||
}
|
||
|
||
async pageHasBootstrapStyle(doc) { return [...doc.querySelectorAll('style')].some((s) => /\.navbar-expand|\.btn-primary/.test(s.textContent)); }
|
||
|
||
fromPage(d) {
|
||
if (d.jumphpBs === 'ready') this.postSelect();
|
||
else if (d.jumphpBs === 'pick') {
|
||
if (this.renderedVersion !== this.model.getVersionId()) { this.preview.update(); return; } // the code changed since the page was drawn
|
||
const target = this.doc().elements.find((e) => e.start === Number(d.id));
|
||
if (target) this.select(target, true);
|
||
} else if (d.jumphpBs === 'hit') this.hit = d.id === null ? null : { id: Number(d.id), rel: d.rel };
|
||
}
|
||
|
||
postSelect() {
|
||
const el = this.selected();
|
||
this.preview.post(el ? { jumphpBs: 'select', id: String(el.start) } : { jumphpBs: 'select', id: '-1' });
|
||
}
|
||
|
||
// selection ------------------------------------------------------------------------------------------------------
|
||
select(element, reveal = false) {
|
||
this.path = element ? pathOf(element) : null;
|
||
if (reveal && element && this.o.editor) {
|
||
const pos = this.model.getPositionAt(element.start);
|
||
this.o.editor.setPosition(pos, 'bse');
|
||
this.o.editor.revealPositionInCenterIfOutsideViewport?.(pos);
|
||
}
|
||
this.postSelect();
|
||
this.renderTabs();
|
||
if (this.tab === 'utilities') this.render();
|
||
}
|
||
|
||
followCursor() {
|
||
const pos = this.o.editor?.getPosition();
|
||
if (!pos) return;
|
||
const found = elementAt(this.doc(), this.model.getOffsetAt(pos));
|
||
const now = this.selected();
|
||
if (found && found !== now && (!now || pathOf(found).join() !== pathOf(now).join())) this.select(found);
|
||
}
|
||
|
||
// drag and drop from the palette ----------------------------------------------------------------------------------
|
||
setupDrop() {
|
||
const layer = this.dropLayer;
|
||
const point = (e) => {
|
||
const frame = this.preview.frame.getBoundingClientRect();
|
||
const scale = frame.width / (this.preview.frame.offsetWidth || frame.width);
|
||
return { x: (e.clientX - frame.left) / scale, y: (e.clientY - frame.top) / scale };
|
||
};
|
||
this.dropLayer.addEventListener('dragover', (e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; this.preview.post({ jumphpBs: 'hit', ...point(e) }); });
|
||
this.dropLayer.addEventListener('dragleave', () => this.preview.post({ jumphpBs: 'clear' }));
|
||
this.dropLayer.addEventListener('drop', (e) => {
|
||
e.preventDefault();
|
||
const id = (e.dataTransfer.getData('text/plain') || '').replace(/^jumphp-bs:/, '');
|
||
layer.style.display = 'none';
|
||
this.preview.post({ jumphpBs: 'clear' });
|
||
const target = this.hit && this.doc().elements.find((x) => x.start === this.hit.id);
|
||
const item = this.component(id);
|
||
if (item && target) this.insert(item, target, this.hit.rel === 'inside' ? 'end' : this.hit.rel);
|
||
});
|
||
this.dragEnd = () => { layer.style.display = 'none'; };
|
||
document.addEventListener('dragend', this.dragEnd);
|
||
}
|
||
|
||
component(id) { for (const [, items] of componentGroups(this.version)) { const c = items.find((x) => x.id === id); if (c) return c; } return null; }
|
||
|
||
/** a component into the code: before / after / inside the element (where: before, after, end), or at the cursor */
|
||
insert(item, target, where) {
|
||
const text = this.model.getValue();
|
||
const snippet = snippetFor(item, text, this.version);
|
||
const unit = this.model.getOptions().insertSpaces ? ' '.repeat(this.model.getOptions().tabSize) : '\t';
|
||
let edit;
|
||
if (target && where !== 'cursor') edit = insertSnippet({ text }, target, where, snippet, unit);
|
||
else {
|
||
const pos = this.o.editor?.getPosition();
|
||
edit = insertAtOffset({ text }, pos ? this.model.getOffsetAt(pos) : text.length, snippet, unit);
|
||
}
|
||
this.apply(edit);
|
||
this.o.editor?.focus();
|
||
}
|
||
|
||
// the panel ------------------------------------------------------------------------------------------------------
|
||
render() {
|
||
this.renderTabs();
|
||
clear(this.body);
|
||
({ components: () => this.renderComponents(), utilities: () => this.renderUtilities(), problems: () => this.renderProblems(), ai: () => this.renderAi() })[this.tab]();
|
||
}
|
||
|
||
refreshPanel() { if (this.tab !== 'ai' && !this.body.contains(document.activeElement)) this.render(); else this.renderTabs(); }
|
||
|
||
problems() { return lintBootstrap(this.model.getValue(), { version: this.version, projectClasses: this.o.classes, model: this.doc() }); }
|
||
|
||
renderTabs() {
|
||
clear(this.tabsBar);
|
||
const count = this.problems().length;
|
||
for (const [id, label] of [['components', t('Components')], ['utilities', t('Utilities')], ['problems', count ? t('Problems ({n})', { n: count }) : t('Problems')], ['ai', t('Ask the AI')]]) {
|
||
this.tabsBar.append(el(`button${id === this.tab ? '.on' : ''}`, { onclick: () => { this.tab = id; prefs.set('bsTab', id); this.render(); } }, label));
|
||
}
|
||
const sel = this.selected();
|
||
this.tabsBar.append(el('span.sel', { title: t('The selected element (click the page or move the cursor)') }, sel ? this.label(sel) : ''));
|
||
const hidden = el('label', { title: t('Show modals, offcanvas, dropdowns, tabs and collapsed parts as if they were open') }, el('input', { type: 'checkbox', checked: this.showHidden,
|
||
onchange: (e) => { this.showHidden = e.target.checked; prefs.set('bsHidden', this.showHidden); this.preview.update(); } }), ' ', t('Show hidden parts'));
|
||
this.tabsBar.append(hidden);
|
||
}
|
||
|
||
label(element) {
|
||
return `<${element.tag}${attrValue(element, 'id') ? '#' + attrValue(element, 'id') : ''}${classesOf(element).slice(0, 3).map((c) => '.' + c).join('')}>`;
|
||
}
|
||
|
||
renderComponents() {
|
||
const sel = this.selected();
|
||
const where = el('select', { onchange: (e) => { this.where = e.target.value; prefs.set('bsInsert', this.where); } },
|
||
...[['after', t('after the selected element')], ['end', t('inside the selected element')], ['before', t('before the selected element')], ['cursor', t('at the cursor')]]
|
||
.map(([v, label]) => el('option', { value: v, selected: v === this.where }, label)));
|
||
this.body.append(el('div.bse-row', {}, t('Insert'), where, el('span.bse-note', {}, t('Click a component, or drag it onto the page'))));
|
||
for (const [group, items] of componentGroups(this.version)) {
|
||
this.body.append(el('div.bse-groupname', {}, group), el('div.bse-items', {}, items.map((c) => el('button.bse-item', {
|
||
draggable: true, title: c.name,
|
||
onclick: () => this.insert(c, this.selected(), this.selected() ? this.where : 'cursor'),
|
||
ondragstart: (e) => { e.dataTransfer.setData('text/plain', 'jumphp-bs:' + c.id); e.dataTransfer.effectAllowed = 'copy'; this.dropLayer.style.display = 'block'; },
|
||
ondragend: () => { this.dropLayer.style.display = 'none'; },
|
||
}, c.name))));
|
||
}
|
||
void sel;
|
||
}
|
||
|
||
renderUtilities() {
|
||
const element = this.selected();
|
||
if (!element) { this.body.append(el('div.bse-note', {}, t('Click an element of the page, or put the cursor in a tag of the code.'))); return; }
|
||
const classes = classesOf(element);
|
||
// the ancestors
|
||
const chain = [];
|
||
for (let n = element; n; n = n.parent) chain.unshift(n);
|
||
this.body.append(el('div.bse-crumbs', {}, chain.map((n) => el(`button${n === element ? '.on' : ''}`, { onclick: () => this.select(n, true) }, this.label(n)))));
|
||
// the classes, and a field to add one
|
||
const input = el('input', { type: 'text', placeholder: t('Add a class…'), list: 'bse-classes', size: 18, onkeydown: (e) => {
|
||
if (e.key !== 'Enter' || !input.value.trim()) return;
|
||
this.setClasses([...classes, ...input.value.trim().split(/\s+/)]);
|
||
input.value = '';
|
||
} });
|
||
this.body.append(el('div.bse-chips', {}, classes.map((c) => el('span.bse-chip', {}, c, el('b', { title: t('Remove'), onclick: () => this.setClasses(classes.filter((x) => x !== c)) }, '×'))), input,
|
||
el('datalist', { id: 'bse-classes' }, [...classSet(this.version)].slice(0, 3000).map((c) => el('option', { value: c })))));
|
||
// the breakpoint every control below sets
|
||
const values = (g) => groupValues(g, classes);
|
||
const used = new Set(Object.values(GROUPS).flatMap((g) => Object.keys(values(g))));
|
||
this.body.append(el('div.bse-row', {}, t('Screen size'), el('div.bse-bp', {}, ['', ...BREAKPOINTS].map((bp) => el(`button${bp === this.bp ? '.on' : ''}${used.has(bp) && bp ? '.set' : ''}`, {
|
||
title: bp ? t('{bp} and wider', { bp }) : t('Every width'), onclick: () => { this.bp = bp; this.render(); },
|
||
}, bp || 'xs')))));
|
||
const labels = LABELS();
|
||
const sections = SECTION_LABELS();
|
||
const spacing = (prop, title) => {
|
||
const cell = (side) => this.groupSelect(GROUPS[prop + side], classes);
|
||
return el('div.bse-box' + (prop === 'p' ? '.pad' : ''), {}, el('label.mid', {}, title), el('span'), cell('t'), el('span'), cell('s'), cell(''), cell('e'), el('span'), cell('b'), el('span'));
|
||
};
|
||
const spacingNode = el('div', {}, spacing('m', t('Margin')), spacing('p', t('Padding')),
|
||
el('div.bse-row', {}, ['x', 'y'].flatMap((s) => [`m${s}`, `p${s}`]).map((id) => el('span', {}, id, ' ', this.groupSelect(GROUPS[id], classes)))));
|
||
for (const section of SECTIONS) {
|
||
const open = prefs.get('bsSec:' + section.id, section.id === 'spacing' || section.id === 'grid');
|
||
const details = el('details', { open, ontoggle: (e) => prefs.set('bsSec:' + section.id, e.target.open) }, el('summary.bse-groupname', {}, sections[section.id]));
|
||
if (section.id === 'spacing') details.append(spacingNode);
|
||
else details.append(el('div.bse-grid', {}, section.groups.map((id) => this.field(GROUPS[id], labels[id] || id, classes))));
|
||
this.body.append(details);
|
||
}
|
||
}
|
||
|
||
/** a select that sets a group's value at the current breakpoint */
|
||
groupSelect(g, classes) {
|
||
const bp = g.bpAware ? this.bp : '';
|
||
const current = groupValue(g, classes, bp);
|
||
const options = valuesAt(g, bp);
|
||
const node = el('select', { title: g.make('…', bp).replace('…', ''), onchange: (e) => this.setGroup(g, e.target.value === '\u0000' ? null : e.target.value) },
|
||
el('option', { value: '\u0000' }, '—'), ...options.map((v) => el('option', { value: v, selected: v === current }, v === '' ? t('default') : v)));
|
||
if (current === null) node.value = '\u0000';
|
||
return node;
|
||
}
|
||
|
||
field(g, label, classes) {
|
||
const bp = g.bpAware ? this.bp : '';
|
||
const current = groupValue(g, classes, bp);
|
||
const other = Object.keys(groupValues(g, classes)).length > (current === null ? 0 : 1);
|
||
if (g.values.length === 1 && g.values[0] === 'on') {
|
||
return el(`label.bse-field${current !== null ? '.set' : ''}`, {}, el('span', {}, label), el('input', { type: 'checkbox', checked: current !== null, onchange: (e) => this.setGroup(g, e.target.checked ? 'on' : null) }));
|
||
}
|
||
return el(`div.bse-field${current !== null ? '.set' : ''}`, {}, el('span', { title: other ? t('Also set at other screen sizes') : '' }, label + (other ? ' •' : '')), this.groupSelect(g, classes));
|
||
}
|
||
|
||
setGroup(g, value) {
|
||
const element = this.selected();
|
||
if (!element) return;
|
||
this.setClasses(setGroup(g, classesOf(element), value, g.bpAware ? this.bp : ''));
|
||
}
|
||
|
||
setClasses(list) {
|
||
const element = this.selected();
|
||
if (!element) return;
|
||
const edit = setClasses(this.doc(), element, list);
|
||
if (edit) this.apply(edit);
|
||
else this.render();
|
||
this.o.editor?.focus?.();
|
||
}
|
||
|
||
renderProblems() {
|
||
const list = this.problems();
|
||
const converts = convertAllEdits(list);
|
||
this.body.append(el('div.bse-row', {}, el('span.bse-note', {}, list.length ? t('{n} problems in this file', { n: list.length }) : t('No Bootstrap problem in this file.')),
|
||
converts.length ? el('button.bse-btn.primary', { onclick: () => this.apply(converts) }, t('Convert the whole page to Bootstrap 5')) : null));
|
||
for (const f of list) {
|
||
const a = this.model.getPositionAt(f.start);
|
||
this.body.append(el('div.bse-prob', { onclick: () => { this.o.editor?.setPosition(a); this.o.editor?.revealPositionInCenter(a); this.o.editor?.focus(); } },
|
||
el('span.sev', { style: { color: f.severity === 'error' ? 'var(--red, #e55)' : f.severity === 'info' ? 'var(--accent, #3574f0)' : 'var(--yellow, #e5a50a)' } }, f.severity === 'error' ? '●' : f.severity === 'info' ? '○' : '▲'),
|
||
el('span.msg', {}, describe(f)), f.fixes[0] ? el('button.bse-btn', { onclick: (e) => { e.stopPropagation(); this.apply(f.fixes[0].edits); } }, fixLabel(f, f.fixes[0])) : null,
|
||
el('span.where', {}, `${a.lineNumber}:${a.column}`)));
|
||
}
|
||
}
|
||
|
||
// Ask the AI -------------------------------------------------------------------------------------------------------
|
||
renderAi() {
|
||
const status = el('div.bse-note', {});
|
||
const instruction = el('textarea', { rows: 2, placeholder: t('Describe what you want (optional for the buttons above)…') }, prefs.get('bsAiText', ''));
|
||
const scope = el('select', {}, ...[['selection', t('the selection')], ['element', t('the selected element')], ['file', t('the whole file')]].map(([v, l]) => el('option', { value: v }, l)));
|
||
const sel = this.o.editor?.getSelection();
|
||
scope.value = sel && !sel.isEmpty() ? 'selection' : 'element';
|
||
const provider = el('select', {});
|
||
const model = el('input', { type: 'text', size: 14, placeholder: t('model name') });
|
||
this.providers().then((list) => {
|
||
for (const p of list) provider.append(el('option', { value: p.id }, p.name.replace(/ \(.*/, '')));
|
||
provider.value = prefs.get('bsAiProvider', 'claude');
|
||
if (!provider.value) provider.value = 'claude';
|
||
const sync = () => { const p = list.find((x) => x.id === provider.value); model.value = prefs.get('bsAiModel:' + provider.value, p?.kind === 'claude' ? 'sonnet' : p?.model || ''); };
|
||
provider.onchange = () => { prefs.set('bsAiProvider', provider.value); sync(); };
|
||
sync();
|
||
this.aiList = list;
|
||
});
|
||
const run = async (action) => {
|
||
prefs.set('bsAiText', instruction.value);
|
||
prefs.set('bsAiModel:' + provider.value, model.value);
|
||
const p = (this.aiList || []).find((x) => x.id === provider.value);
|
||
const pos = this.o.editor?.getPosition();
|
||
const s = this.o.editor?.getSelection();
|
||
const request = buildRequest({ action, instruction: instruction.value, version: this.version, text: this.model.getValue(), path: this.o.path, scope: scope.value,
|
||
cursor: pos ? this.model.getOffsetAt(pos) : 0, selection: s && !s.isEmpty() ? { start: this.model.getOffsetAt(s.getStartPosition()), end: this.model.getOffsetAt(s.getEndPosition()) } : null });
|
||
if (action === 'custom' && !instruction.value.trim()) { status.textContent = t('Describe what you want first.'); return; }
|
||
status.textContent = t('Asking… (up to a minute)');
|
||
const version = this.model.getVersionId();
|
||
try {
|
||
const ask = this.o.ask || ((prompt) => backend.invoke('bootstrap.ai', { prompt, provider: provider.value, model: model.value.trim(),
|
||
key: p?.needsKey ? prefs.get('aiKey:' + p.id, '') : '', baseUrl: p?.kind === 'chat' ? prefs.get('aiBase:' + p.id, p.baseUrl) : '' }));
|
||
const result = await runAi(request, this.model.getValue(), ask, { projectClasses: this.o.classes });
|
||
status.textContent = '';
|
||
if (this.model.getVersionId() !== version) { notify(t('The file changed while the AI was working: ask again.'), 'warning'); return; }
|
||
this.review(result);
|
||
} catch (e) {
|
||
status.textContent = '';
|
||
notify(e.message === 'no-markup' ? t('The AI answered with no markup.') : e.message === 'script' ? t('The AI\'s markup holds a script: it was refused.') : String(e.message || e), 'error', { title: t('Ask the AI') });
|
||
}
|
||
};
|
||
this.body.append(el('div.bse-row', {}, ...Object.keys(AI_ACTIONS).filter((a) => a !== 'custom').map((a) => el('button.bse-btn', { onclick: () => run(a) },
|
||
{ hero: t('Make a hero section'), contact: t('Make a contact page'), convert: t('Convert to Bootstrap'), responsive: t('Make it responsive') }[a]))),
|
||
instruction, el('div.bse-row', {}, t('Work on'), scope, t('With'), provider, model, el('button.bse-btn.primary', { onclick: () => run('custom') }, t('Ask'))), status,
|
||
el('div.bse-note', {}, t('The answer is shown as a difference you accept or refuse: nothing is written before.')));
|
||
}
|
||
|
||
async providers() {
|
||
try { return (await backend.invoke('ai.providers')).filter((p) => ['claude', 'opencode', 'chat'].includes(p.kind)); } catch { return [{ id: 'claude', name: 'Claude', kind: 'claude' }]; }
|
||
}
|
||
|
||
/** the AI's result as a diff (the file now / the file with it): Accept applies one edit */
|
||
review(result) {
|
||
const { monaco } = this.o;
|
||
const holder = el('div.bse-diff');
|
||
const original = monaco.editor.createModel(this.model.getValue(), 'html');
|
||
const modified = monaco.editor.createModel(result.next, 'html');
|
||
let diff = null;
|
||
const note = result.findings.length ? t('{n} Bootstrap problems in the result', { n: result.findings.length }) : t('No Bootstrap problem in the result');
|
||
const d = dialog({
|
||
title: 'Ask the AI', wide: true,
|
||
body: el('div', {}, el('p.bse-note', {}, note), holder),
|
||
onClose: () => { diff?.dispose(); original.dispose(); modified.dispose(); },
|
||
buttons: [{ label: 'Refuse' }, { label: 'Accept', primary: true, action: () => {
|
||
const edit = { start: result.range.start, end: result.range.end, text: result.replacement };
|
||
this.apply(edit);
|
||
} }],
|
||
});
|
||
void d;
|
||
setTimeout(() => {
|
||
diff = monaco.editor.createDiffEditor(holder, { readOnly: true, renderSideBySide: false, automaticLayout: true, minimap: { enabled: false } });
|
||
diff.setModel({ original, modified });
|
||
}, 0);
|
||
}
|
||
}
|