94 lines
6.8 KiB
JavaScript
94 lines
6.8 KiB
JavaScript
// "Ask the AI" in the Bootstrap editor, without the interface (no DOM: node --test runs it with a fake AI): the request (what to
|
|
// ask, about which part of the file), the answer read back as markup, and the check of that markup. The asking itself is the
|
|
// IDE's own path (backend 'bootstrap.ai': Claude, OpenCode or a chat model); the result is shown as a diff, never written.
|
|
import { parseMarkup, elementAt } from './bootstrap-model.js';
|
|
import { lintBootstrap } from './bootstrap-lint.js';
|
|
|
|
export const AI_ACTIONS = {
|
|
hero: { make: true, task: 'Make a hero section: a headline, a short lead text and two call-to-action buttons, centred, with generous spacing.' },
|
|
contact: { make: true, task: 'Make a contact page section: a responsive two-column layout with a contact form (name, e-mail, subject, message, submit; labels, floating or plain) and a column with the address, phone and e-mail.' },
|
|
convert: { make: false, task: 'Convert this markup to Bootstrap components and utilities (keep the content, the Twig tags and the data attributes; use Bootstrap classes instead of custom CSS or inline styles).' },
|
|
responsive: { make: false, task: 'Make this markup responsive with Bootstrap: grid columns with breakpoints (col-12 col-md-6...), responsive spacing and display utilities, stacked on phones.' },
|
|
custom: { make: null, task: '' },
|
|
};
|
|
|
|
const RULES = (version) => [
|
|
`The site uses Bootstrap ${version === '4' ? '4.6' : '5.3'}${version === '4' ? ' (data-toggle, ml-/mr-, float-left...)' : ' (data-bs-*, ms-/me-, text-start...)'}: use only its classes and its JavaScript data attributes.`,
|
|
'Answer with the markup only: no explanation, no code fence, no <html>, <head> or <body> unless the region you were given has them.',
|
|
'Keep every Twig tag ({{ }}, {% %}, {# #}) as it is, and the text the region already has (unless asked to rewrite it).',
|
|
'No <script>, no inline event handler, no inline style when a utility does the job.',
|
|
'Give every form control a label, every image an alt, every button a type, every modal an aria-labelledby, and wire ids, aria-controls and data-bs-target together.',
|
|
].map((r, i) => `${i + 1}. ${r}`).join('\n');
|
|
|
|
/**
|
|
* What to ask: the prompt, and the range of the file the answer replaces (an empty range: the answer is inserted there).
|
|
* scope: 'selection' (the selected text), 'element' (the element at the cursor), 'file' (all of it)
|
|
* @param {{action: string, instruction?: string, version?: string, text: string, selection?: {start: number, end: number}, cursor?: number, scope?: string, path?: string}} o
|
|
*/
|
|
export function buildRequest(o) {
|
|
const action = AI_ACTIONS[o.action] || AI_ACTIONS.custom;
|
|
const version = String(o.version) === '4' ? '4' : '5';
|
|
const text = o.text;
|
|
const sel = o.selection && o.selection.end > o.selection.start ? o.selection : null;
|
|
const cursor = o.cursor ?? sel?.end ?? 0;
|
|
let scope = o.scope || (sel ? 'selection' : 'element');
|
|
if (scope === 'selection' && !sel) scope = 'element';
|
|
let range;
|
|
if (action.make) {
|
|
// new markup: after the selection, else after the element at the cursor, else at the cursor
|
|
const el = elementAt(parseMarkup(text), cursor);
|
|
const after = el && (cursor < el.end || !el.children.length) ? (el.closeEnd >= 0 ? el.closeEnd : el.end) : cursor; // on a tag or a leaf: after it; between children: there
|
|
range = sel ? { start: sel.end, end: sel.end } : { start: after, end: after };
|
|
if (scope === 'file') range = { start: text.length, end: text.length };
|
|
} else if (scope === 'file') range = { start: 0, end: text.length };
|
|
else if (scope === 'selection') range = { start: sel.start, end: sel.end };
|
|
else {
|
|
const el = elementAt(parseMarkup(text), cursor);
|
|
range = el ? { start: el.start, end: el.closeEnd >= 0 ? el.closeEnd : el.end } : { start: 0, end: text.length };
|
|
}
|
|
const task = [action.task, (o.instruction || '').trim()].filter(Boolean).join('\n');
|
|
const region = text.slice(range.start, range.end);
|
|
const indent = /^[ \t]*/.exec(text.slice(text.lastIndexOf('\n', range.start - 1) + 1, range.start))[0];
|
|
// the region as the AI sees it: the indentation of its first line taken off the others (its answer is indented back)
|
|
const shown = region.split('\n').map((l, i) => (i > 0 && indent && l.startsWith(indent) ? l.slice(indent.length) : l)).join('\n');
|
|
const context = text.length <= 6000 ? text : text.slice(0, 3000) + '\n…\n' + text.slice(-2500);
|
|
const prompt = [
|
|
`Task: ${task || 'Improve this markup.'}`,
|
|
'',
|
|
'Rules:', RULES(version),
|
|
'',
|
|
o.path ? `File: ${o.path}${/\.twig$/i.test(o.path) ? ' (a Twig template)' : ''}` : '',
|
|
action.make ? 'Make new markup that will be inserted into the page at the place shown below (marked <<HERE>>).' : 'The region to rewrite (your answer replaces it):',
|
|
action.make ? '```html\n' + text.slice(Math.max(0, range.start - 600), range.start) + '<<HERE>>' + text.slice(range.end, range.end + 400) + '\n```'
|
|
: '```html\n' + shown + '\n```',
|
|
scope === 'file' || action.make ? '' : `The whole file, for context only (do not repeat it):\n\`\`\`html\n${context}\n\`\`\``,
|
|
].filter((l) => l !== '').join('\n');
|
|
return { prompt, range, original: region, make: !!action.make, scope, version };
|
|
}
|
|
|
|
/** the markup of an answer: a code fence's content, or the text; null when it holds no markup */
|
|
export function extractMarkup(answer) {
|
|
let s = String(answer ?? '').trim();
|
|
const fence = /```[a-z]*\n([\s\S]*?)```/i.exec(s);
|
|
if (fence) s = fence[1].trim();
|
|
else s = s.replace(/^```[a-z]*\n?|```$/gi, '').trim();
|
|
if (!s || !/<[a-z]|\{%|\{\{/i.test(s)) return null;
|
|
return s;
|
|
}
|
|
|
|
/**
|
|
* Ask and check: ask(prompt) is the AI (a promise of text). Resolves {range, original, replacement, findings} (findings: the
|
|
* Bootstrap checks of the whole page once the answer is in), or rejects: no markup, a <script>.
|
|
*/
|
|
export async function runAi(request, text, ask, options = {}) {
|
|
const answer = await ask(request.prompt);
|
|
const markup = extractMarkup(answer);
|
|
if (!markup) throw new Error('no-markup');
|
|
if (/<script\b|\son[a-z]+\s*=/i.test(markup) && !/<script\b|\son[a-z]+\s*=/i.test(request.original)) throw new Error('script');
|
|
// the original's indentation: lines after the first take the indentation of the line the region starts on
|
|
const lineStart = text.lastIndexOf('\n', request.range.start - 1) + 1;
|
|
const indent = /^[ \t]*/.exec(text.slice(lineStart, request.range.start))[0];
|
|
const body = request.make ? '\n' + indent + markup.split('\n').join('\n' + indent) : markup.split('\n').map((l, i) => (i === 0 || !l ? l : indent + l)).join('\n');
|
|
const next = text.slice(0, request.range.start) + body + text.slice(request.range.end);
|
|
return { range: request.range, original: request.original, replacement: body, next, findings: lintBootstrap(next, { version: request.version, projectClasses: options.projectClasses }) };
|
|
}
|