rob-revisited/ide/ui/js/yaml-nav.js

162 lines
7.7 KiB
JavaScript

// Navigation in YAML files, answered by the PHP side (JumPHP\Ide\Yaml\YamlNavigation): Ctrl+click / F12 (an alias to its
// anchor, a service, a parameter, %env()%, a class or Class::method, a compose service / network / volume, a path...),
// Shift+F12 / Alt+F7 (usages), hover (the anchor's merged keys, the definition), document links (the values that lead to a
// file: underlined, Ctrl+click), rename (anchors and their aliases, compose names). In PHP and Twig, a string that is a
// translation / lang key, an input action or a parameter leads back to its YAML.
const SCHEME = 'jumphp-yaml';
/** Whether a 1-based column of a line is inside a quoted string (PHP / Twig: only then the YAML side is asked). */
export function inString(line, column) {
let quote = null;
let start = 0;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (quote) {
if (c === '\\') { i++; continue; }
if (c === quote) {
if (column - 1 >= start && column - 1 <= i) return true;
quote = null;
}
} else if (c === '"' || c === "'") {
quote = c;
start = i;
}
}
return false;
}
/** The link's URI (opened by the opener below, not by Monaco's own file opener) and back. */
export function linkTarget(path, line, col) {
return { scheme: SCHEME, path: '/', query: JSON.stringify({ path, line, col }) };
}
export function parseTarget(query) {
try {
const t = JSON.parse(query);
return typeof t.path === 'string' ? { path: t.path, line: t.line | 0 || 1, col: t.col | 0 || 1 } : null;
} catch { return null; }
}
/**
* @param monaco Monaco
* @param editors the Editors (open, ensureModels, pushNavigation, saveAll, files, app)
* @param io {backend, uriOf, pathOf}
*/
export function registerYamlNavigation(monaco, editors, { backend, uriOf, pathOf }) {
const args = (model, position) => ({ path: pathOf(model.uri), text: model.getValue(), line: position.lineNumber, column: position.column });
const location = (l) => ({ uri: uriOf(l.path), range: new monaco.Range(l.line, l.col, l.line, l.col + (l.length || 0)) });
const range = (r) => new monaco.Range(r.startLine, r.startColumn, r.endLine, r.endColumn);
const stringAt = (model, position) => inString(model.getLineContent(position.lineNumber), position.column);
monaco.editor.registerLinkOpener({
open(uri) {
if (uri.scheme !== SCHEME) return false;
const target = parseTarget(uri.query);
if (!target) return false;
editors.pushNavigation?.();
editors.open(target.path, { line: target.line, col: target.col });
return true;
},
});
monaco.languages.registerDefinitionProvider('yaml', {
provideDefinition: async (model, position) => {
const list = await backend.invoke('yaml.definition', args(model, position)).catch(() => []);
if (!list.length) {
// on a declaration (an anchor, a service, an action...): its usages, as for PHP
const refs = await backend.invoke('yaml.references', { ...args(model, position), declarations: false }).catch(() => []);
if (refs.length) editors.app?.showUsages?.(refs, model.getWordAtPosition(position)?.word);
return [];
}
await editors.ensureModels(list.map((l) => l.path));
editors.pushNavigation?.();
return list.map((l) => ({ uri: uriOf(l.path), range: new monaco.Range(l.line, l.col, l.line, l.col) }));
},
});
monaco.languages.registerReferenceProvider('yaml', {
provideReferences: async (model, position, context) => {
const refs = await backend.invoke('yaml.references', { ...args(model, position), declarations: context.includeDeclaration }).catch(() => []);
await editors.ensureModels(refs.map((r) => r.path));
return refs.map(location);
},
});
monaco.languages.registerDocumentHighlightProvider('yaml', {
provideDocumentHighlights: async (model, position) => {
const word = model.getWordAtPosition(position);
if (!word) return [];
const refs = await backend.invoke('yaml.references', args(model, position)).catch(() => []);
const path = pathOf(model.uri);
return refs.filter((r) => r.path === path).map((r) => ({ range: new monaco.Range(r.line, r.col, r.line, r.col + r.length),
kind: r.declaration ? monaco.languages.DocumentHighlightKind.Write : monaco.languages.DocumentHighlightKind.Read }));
},
});
monaco.languages.registerHoverProvider('yaml', {
provideHover: async (model, position) => {
const hover = await backend.invoke('yaml.hover', args(model, position)).catch(() => null);
return hover ? { contents: [{ value: hover.contents }], range: range(hover.range) } : null;
},
});
monaco.languages.registerLinkProvider('yaml', {
provideLinks: async (model) => {
if (model.getLineCount() > 5000) return { links: [] };
const list = await backend.invoke('yaml.links', { path: pathOf(model.uri), text: model.getValue() }).catch(() => []);
return {
links: list.map((l) => ({ range: new monaco.Range(l.line, l.col, l.line, l.endCol), url: monaco.Uri.from(linkTarget(l.path, l.targetLine, l.targetCol)),
tooltip: l.targetLine > 1 ? `${l.path}:${l.targetLine}` : l.path })),
};
},
});
monaco.languages.registerRenameProvider('yaml', {
resolveRenameLocation: async (model, position) => {
const target = await backend.invoke('yaml.renameTarget', args(model, position)).catch(() => null);
if (!target) return { rejectReason: 'This element cannot be renamed.', range: undefined, text: '' };
return { range: range(target.range), text: target.text };
},
provideRenameEdits: async (model, position, newName) => {
await editors.saveAll?.(true);
const result = await backend.invoke('yaml.rename', { ...args(model, position), newName });
const edits = [];
const closed = {};
for (const [path, list] of Object.entries(result.edits || {})) {
const open = monaco.editor.getModel(uriOf(path));
if (open && editors.files?.has(path)) {
for (const e of list) edits.push({ resource: open.uri, versionId: undefined, textEdit: { range: new monaco.Range(e.line, e.col, e.line, e.col + e.length), text: e.text } });
} else closed[path] = list;
}
if (Object.keys(closed).length) await backend.invoke('edits.apply', { edits: closed });
return { edits };
},
});
// PHP and Twig: 'key'|trans, ->trans('key'), Lang::t('KEY'), isPressed('jump'), getParameter('x') -> the YAML that defines it
for (const language of ['php', 'twig']) {
monaco.languages.registerDefinitionProvider(language, {
provideDefinition: async (model, position) => {
if (!stringAt(model, position)) return [];
const list = await backend.invoke('yaml.definition', args(model, position)).catch(() => []);
await editors.ensureModels(list.map((l) => l.path));
return list.map((l) => ({ uri: uriOf(l.path), range: new monaco.Range(l.line, l.col, l.line, l.col) }));
},
});
monaco.languages.registerReferenceProvider(language, {
provideReferences: async (model, position, context) => {
if (!stringAt(model, position)) return [];
const refs = await backend.invoke('yaml.references', { ...args(model, position), declarations: context.includeDeclaration }).catch(() => []);
await editors.ensureModels(refs.map((r) => r.path));
return refs.map(location);
},
});
monaco.languages.registerHoverProvider(language, {
provideHover: async (model, position) => {
if (!stringAt(model, position)) return null;
const hover = await backend.invoke('yaml.hover', args(model, position)).catch(() => null);
return hover ? { contents: [{ value: hover.contents }], range: range(hover.range) } : null;
},
});
}
}