rob-revisited/ide/ui/js/path-links.js

168 lines
8.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Paths named in a file, without the DOM nor Monaco (node --test: path-links.test.mjs): where each quoted path / template
// name / import / url() of a line is (the WHOLE path, so the editor underlines it as one link and Ctrl+click opens it), and
// what path is being typed before the cursor (path completion). The backend (path.resolve, path.complete) knows the files.
//
// kinds (JumPHP\Ide\Links\ProjectPaths): template (Twig names: templates/), relative (pages, styles, Markdown: next to the
// file, '/x' = public/x), module (JS imports: relative or a package of importmap.php / node_modules), asset (Twig asset()),
// any (a PHP string naming a file), url (an http(s) image: previewed / opened from the web).
export const IMAGE = /\.(png|jpe?g|gif|webp|svg|avif|ico|bmp)$/i;
/** The languages the editor gives path links / completion to (YAML has its own: yaml-lang.js). */
export const PATH_LANGUAGES = ['javascript', 'typescript', 'css', 'scss', 'less', 'html', 'twig', 'markdown', 'php'];
const TWIG_TAG = /\{%-?\s*(?:extends|include|embed|import|from|use|sandbox)\s+(?:\[\s*)?$|\{%-?\s*form_theme\s+[\w.]+\s+(?:with\s+)?(?:\[\s*)?$|\{%-?\s*include\s+\[(?:\s*['"][^'"]*['"]\s*,)*\s*$/;
const TWIG_FN = /\b(include|source|asset|template_from_string)\s*\(\s*$/;
const HTML_ATTR = /\b(src|href|srcset|poster|data-src|action|data|content)\s*=\s*$/i;
const JS_FROM = /(?:\bfrom\s*|\bimport\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bexport\s+\*\s+from\s*)$/;
const JS_URL = /\bnew\s+URL\s*\(\s*$/;
const CSS_IMPORT = /@import\s+(?:url\(\s*)?$/;
const CSS_URL = /\burl\(\s*$/;
/** What kind of path an opening quote at the end of `before` starts (null: not a path place). */
export function kindBefore(language, before) {
if (language === 'twig') {
if (TWIG_TAG.test(before)) return 'template';
const fn = TWIG_FN.exec(before);
if (fn) return fn[1] === 'asset' ? 'asset' : 'template';
if (HTML_ATTR.test(before)) return 'relative';
return null;
}
if (language === 'html') return HTML_ATTR.test(before) ? 'relative' : null;
if (language === 'javascript' || language === 'typescript') {
if (JS_URL.test(before)) return 'relative';
return JS_FROM.test(before) ? 'module' : null;
}
if (language === 'css' || language === 'scss' || language === 'less') return CSS_IMPORT.test(before) || CSS_URL.test(before) ? 'relative' : null;
if (language === 'php') {
if (/\b(?:render|renderView|renderBlock|stream|include|require|include_once|require_once)\s*\(?\s*(?:__DIR__\s*\.\s*)?$/.test(before)) return 'any';
return HTML_ATTR.test(before) ? 'relative' : 'any';
}
return null;
}
const looksLikePath = (s) => s.length > 0 && s.length < 400 && !/[\s{}<>|`$\\]/.test(s) && !/^(?:#|mailto:|tel:|javascript:|data:)/i.test(s);
const isUrl = (s) => /^https?:\/\/[^\s'"]+$/i.test(s);
/**
* The paths of a line: [{start, end, ref, kind}], start / end = 0-based columns of the path itself (without its quotes), end exclusive.
* PHP: only strings that look like a file name (an extension), as Ctrl+click on them always did.
*/
export function refsInLine(language, line) {
const out = [];
const push = (start, ref, kind) => {
const trimmed = ref.replace(/\s+$/, '');
if (!looksLikePath(trimmed)) return;
if (isUrl(trimmed)) { if (IMAGE.test(trimmed.replace(/[?#].*$/, ''))) out.push({ start, end: start + trimmed.length, ref: trimmed, kind: 'url' }); return; }
if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) || trimmed.startsWith('//')) return;
out.push({ start, end: start + trimmed.length, ref: trimmed, kind });
};
if (line.length > 2000) return out;
if (language === 'markdown') {
for (const m of line.matchAll(/!?\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)) push(m.index + m[0].indexOf(m[1], m[0].indexOf('](')), m[1], 'relative');
for (const m of line.matchAll(/<img\b[^>]*\bsrc\s*=\s*(["'])([^"']+)\1/gi)) push(m.index + m[0].lastIndexOf(m[2]), m[2], 'relative');
return out;
}
if (language === 'css' || language === 'scss' || language === 'less') {
for (const m of line.matchAll(/\burl\(\s*(["']?)([^"')\s]+)\1\s*\)/g)) push(m.index + m[0].indexOf(m[2], 4), m[2], 'relative');
for (const m of line.matchAll(/@import\s+(["'])([^"']+)\1/g)) push(m.index + m[0].indexOf(m[2]), m[2], 'relative');
return out;
}
// a quoted string: what comes before its opening quote says what it is. Every quote is tried as an opening one, so the 'x' of
// src="{{ asset('x') }}" is found inside the attribute's string
for (let i = 0; i < line.length; i++) {
const q = line[i];
if (q !== '"' && q !== "'") continue;
let j = i + 1;
while (j < line.length && line[j] !== q) j += line[j] === '\\' ? 2 : 1;
if (j >= line.length) break;
const before = line.slice(0, i);
const start = i + 1;
const ref = line.slice(start, j);
if (isUrl(ref)) { push(start, ref, 'url'); i = j; continue; }
let kind = kindBefore(language, before);
if (language === 'twig' && kind === null && /\{%-?\s*(?:extends|include|embed|import|from|use)\b[^%]*$/.test(before) && /\.twig$/.test(ref)) kind = 'template';
if (language === 'twig' && kind === null && /\{%-?\s*form_theme\b[^%]*$/.test(before) && /\.twig$/.test(ref)) kind = 'template';
if (language === 'php') {
if (!/^@?[\w./-]+\.\w+$/.test(ref) || (ref.includes('..') && !ref.startsWith('.'))) continue;
if (/\.twig$/.test(ref)) kind = 'template';
}
if (kind === null || !looksLikePath(ref)) continue;
push(start, ref, kind);
i = j;
}
return out;
}
/** The path link of a line under a 0-based column (or null). */
export function refAt(language, line, column) {
return refsInLine(language, line).find((r) => column >= r.start && column <= r.end) || null;
}
/**
* The path being typed when the cursor is at the end of `before` (the line up to the cursor), inside an open quote / url( of a
* path place: {typed, kind} (typed = the path's text so far), else null.
*/
export function pathTypedAt(language, before) {
if (!PATH_LANGUAGES.includes(language)) return null;
if (language === 'css' || language === 'scss' || language === 'less') {
const m = /(?:\burl\(\s*|@import\s+)(["']?)([^"'()\s]*)$/.exec(before);
if (!m) return null;
return { typed: m[2], kind: 'relative' };
}
if (language === 'markdown') {
const m = /!?\[[^\]]*\]\(\s*([^)\s]*)$/.exec(before);
return m ? { typed: m[1], kind: 'relative' } : null;
}
// inside an open quote: the last quote of the line not closed
const m = /(["'])([^"'\n]*)$/.exec(before);
if (!m) return null;
const quoteAt = m.index;
// the quote opens a string (an even number of that quote before it)
const prefix = before.slice(0, quoteAt);
if (((prefix.match(new RegExp(m[1], 'g')) || []).length) % 2 === 1) return null;
const typed = m[2];
if (/^[a-z][a-z0-9+.-]*:/i.test(typed) || /\s/.test(typed) || typed.includes('{')) return null;
let kind = kindBefore(language, prefix);
if (language === 'php') {
// a PHP string only completes once it looks like a path (a / or a dot), or right after render( / include
if (kind === 'any' && !/[/.]/.test(typed) && !/(?:render\w*|stream|include\w*|require\w*)\s*\(?\s*$/.test(prefix)) return null;
if (/\.twig$|^@/.test(typed) || /render\w*\s*\(\s*$/.test(prefix)) kind = 'template';
}
return kind ? { typed, kind } : null;
}
/** The completion items filtered and ranked for what is typed after the last '/' (a prefix first, then a part of the name). */
export function rankEntries(items, word) {
const w = word.toLowerCase();
const scored = [];
for (const item of items) {
const name = item.label.toLowerCase().replace(/\/$/, '');
const at = w ? name.indexOf(w) : 0;
if (w && at < 0) continue;
scored.push({ item, score: (item.kind === 'folder' ? 0 : item.kind === 'package' ? 1 : 2) * 10 + (at === 0 ? 0 : 5) });
}
scored.sort((a, b) => a.score - b.score || a.item.label.localeCompare(b.item.label));
return scored.map((s) => s.item);
}
/** '12.3 KB' */
export function formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1048576).toFixed(1)} MB`;
}
/** A thumbnail's size: the image fit in max × max (never larger than it is). */
export function fitIn(width, height, max) {
if (!width || !height) return { width: max, height: max };
const scale = Math.min(1, max / Math.max(width, height));
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
}
/** The import specifiers of a JS / TS text (to know when to ask the backend again for the project's modules). */
export function importsOf(text) {
const out = new Set();
for (const m of text.matchAll(/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)(["'])([^"'\n]+)\1/g)) out.add(m[2]);
return [...out].sort();
}