2020-03-13 15:44:24 +05:30
|
|
|
import { editor as monacoEditor, languages as monacoLanguages, Uri } from 'monaco-editor';
|
2020-04-08 14:13:33 +05:30
|
|
|
import { DEFAULT_THEME, themes } from '~/ide/lib/themes';
|
2020-05-24 23:13:21 +05:30
|
|
|
import languages from '~/ide/lib/languages';
|
2020-03-13 15:44:24 +05:30
|
|
|
import { defaultEditorOptions } from '~/ide/lib/editor_options';
|
2020-05-24 23:13:21 +05:30
|
|
|
import { registerLanguages } from '~/ide/utils';
|
2020-03-13 15:44:24 +05:30
|
|
|
import { clearDomElement } from './utils';
|
|
|
|
|
|
|
|
export default class Editor {
|
|
|
|
constructor(options = {}) {
|
|
|
|
this.editorEl = null;
|
|
|
|
this.blobContent = '';
|
|
|
|
this.blobPath = '';
|
|
|
|
this.instance = null;
|
|
|
|
this.model = null;
|
|
|
|
this.options = {
|
2020-04-08 14:13:33 +05:30
|
|
|
extraEditorClassName: 'gl-editor-lite',
|
2020-03-13 15:44:24 +05:30
|
|
|
...defaultEditorOptions,
|
|
|
|
...options,
|
|
|
|
};
|
|
|
|
|
|
|
|
Editor.setupMonacoTheme();
|
2020-05-24 23:13:21 +05:30
|
|
|
|
|
|
|
registerLanguages(...languages);
|
2020-03-13 15:44:24 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
static setupMonacoTheme() {
|
2020-04-08 14:13:33 +05:30
|
|
|
const themeName = window.gon?.user_color_scheme || DEFAULT_THEME;
|
|
|
|
const theme = themes.find(t => t.name === themeName);
|
|
|
|
if (theme) monacoEditor.defineTheme(themeName, theme.data);
|
|
|
|
monacoEditor.setTheme(theme ? themeName : DEFAULT_THEME);
|
2020-03-13 15:44:24 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
createInstance({ el = undefined, blobPath = '', blobContent = '' } = {}) {
|
|
|
|
if (!el) return;
|
|
|
|
this.editorEl = el;
|
|
|
|
this.blobContent = blobContent;
|
|
|
|
this.blobPath = blobPath;
|
|
|
|
|
|
|
|
clearDomElement(this.editorEl);
|
|
|
|
|
|
|
|
this.model = monacoEditor.createModel(
|
|
|
|
this.blobContent,
|
|
|
|
undefined,
|
|
|
|
new Uri('gitlab', false, this.blobPath),
|
|
|
|
);
|
|
|
|
|
|
|
|
monacoEditor.onDidCreateEditor(this.renderEditor.bind(this));
|
|
|
|
|
|
|
|
this.instance = monacoEditor.create(this.editorEl, this.options);
|
|
|
|
this.instance.setModel(this.model);
|
|
|
|
}
|
|
|
|
|
|
|
|
dispose() {
|
|
|
|
return this.instance && this.instance.dispose();
|
|
|
|
}
|
|
|
|
|
|
|
|
renderEditor() {
|
|
|
|
delete this.editorEl.dataset.editorLoading;
|
|
|
|
}
|
|
|
|
|
|
|
|
updateModelLanguage(path) {
|
|
|
|
if (path === this.blobPath) return;
|
|
|
|
this.blobPath = path;
|
|
|
|
const ext = `.${path.split('.').pop()}`;
|
|
|
|
const language = monacoLanguages
|
|
|
|
.getLanguages()
|
|
|
|
.find(lang => lang.extensions.indexOf(ext) !== -1);
|
|
|
|
const id = language ? language.id : 'plaintext';
|
|
|
|
monacoEditor.setModelLanguage(this.model, id);
|
|
|
|
}
|
|
|
|
|
|
|
|
getValue() {
|
|
|
|
return this.model.getValue();
|
|
|
|
}
|
|
|
|
}
|