UNPKG

use-monaco

Version:

[![npm](https://img.shields.io/npm/v/use-monaco)](https://npm.im/use-monaco)

1,403 lines (1,245 loc) 196 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var scopeEval = require('scope-eval'); var useDebounce = require('use-debounce'); var React = require('react'); var dequal = require('dequal'); var createHookContext = require('create-hook-context'); var deepmerge = require('deepmerge'); var Color = require('color'); var dot = require('dot-object'); var onigasm = require('onigasm'); var monacoTextmate = require('monaco-textmate'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var scopeEval__default = /*#__PURE__*/_interopDefaultLegacy(scopeEval); var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var deepmerge__default = /*#__PURE__*/_interopDefaultLegacy(deepmerge); var Color__default = /*#__PURE__*/_interopDefaultLegacy(Color); var dot__default = /*#__PURE__*/_interopDefaultLegacy(dot); function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); } // A type of promise-like that resolves synchronously and supports only one observer const _Pact = /*#__PURE__*/(function() { function _Pact() {} _Pact.prototype.then = function(onFulfilled, onRejected) { const result = new _Pact(); const state = this.s; if (state) { const callback = state & 1 ? onFulfilled : onRejected; if (callback) { try { _settle(result, 1, callback(this.v)); } catch (e) { _settle(result, 2, e); } return result; } else { return this; } } this.o = function(_this) { try { const value = _this.v; if (_this.s & 1) { _settle(result, 1, onFulfilled ? onFulfilled(value) : value); } else if (onRejected) { _settle(result, 1, onRejected(value)); } else { _settle(result, 2, value); } } catch (e) { _settle(result, 2, e); } }; return result; }; return _Pact; })(); // Settles a pact synchronously function _settle(pact, state, value) { if (!pact.s) { if (value instanceof _Pact) { if (value.s) { if (state & 1) { state = value.s; } value = value.v; } else { value.o = _settle.bind(null, pact, state); return; } } if (value && value.then) { value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); return; } pact.s = state; pact.v = value; const observer = pact.o; if (observer) { observer(pact); } } } function _isSettledPact(thenable) { return thenable instanceof _Pact && thenable.s & 1; } // Asynchronously iterate through an object that has a length property, passing the index as the first argument to the callback (even as the length property changes) function _forTo(array, body, check) { var i = -1, pact, reject; function _cycle(result) { try { while (++i < array.length && (!check || !check())) { result = body(i); if (result && result.then) { if (_isSettledPact(result)) { result = result.v; } else { result.then(_cycle, reject || (reject = _settle.bind(null, pact = new _Pact(), 2))); return; } } } if (pact) { _settle(pact, 1, result); } else { pact = result; } } catch (e) { _settle(pact || (pact = new _Pact()), 2, e); } } _cycle(); return pact; } // Asynchronously iterate through an object's properties (including properties inherited from the prototype) // Uses a snapshot of the object's properties function _forIn(target, body, check) { var keys = []; for (var key in target) { keys.push(key); } return _forTo(keys, function(i) { return body(keys[i]); }, check); } const _iteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator"))) : "@@iterator"; const _asyncIteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.asyncIterator || (Symbol.asyncIterator = Symbol("Symbol.asyncIterator"))) : "@@asyncIterator"; // Asynchronously call a function and send errors to recovery continuation function _catch(body, recover) { try { var result = body(); } catch(e) { return recover(e); } if (result && result.then) { return result.then(void 0, recover); } return result; } function parseJSONWithComments(json) { var tokenizer = /"|(\/\*)|(\*\/)|(\/\/)|\n|\r/g, in_string = false, in_multiline_comment = false, in_singleline_comment = false, tmp, tmp2, new_str = [], ns = 0, from = 0, lc, rc; tokenizer.lastIndex = 0; while (tmp = tokenizer.exec(json)) { // @ts-ignore lc = RegExp.leftContext; // @ts-ignore rc = RegExp.rightContext; if (!in_multiline_comment && !in_singleline_comment) { tmp2 = lc.substring(from); if (!in_string) { tmp2 = tmp2.replace(/(\n|\r|\s)*/g, ''); } new_str[ns++] = tmp2; } from = tokenizer.lastIndex; if (tmp[0] == '"' && !in_multiline_comment && !in_singleline_comment) { tmp2 = lc.match(/(\\)*$/); if (!in_string || !tmp2 || tmp2[0].length % 2 == 0) { // start of string with ", or unescaped " character found to end string in_string = !in_string; } from--; // include " character in next catch rc = json.substring(from); } else if (tmp[0] == '/*' && !in_string && !in_multiline_comment && !in_singleline_comment) { in_multiline_comment = true; } else if (tmp[0] == '*/' && !in_string && in_multiline_comment && !in_singleline_comment) { in_multiline_comment = false; } else if (tmp[0] == '//' && !in_string && !in_multiline_comment && !in_singleline_comment) { in_singleline_comment = true; } else if ((tmp[0] == '\n' || tmp[0] == '\r') && !in_string && !in_multiline_comment && in_singleline_comment) { in_singleline_comment = false; } else if (!in_multiline_comment && !in_singleline_comment && !/\n|\r|\s/.test(tmp[0])) { new_str[ns++] = tmp[0]; } } new_str[ns++] = rc; return new_str.join('').replace(/,}/, '}'); } var fixPath = function fixPath(path) { return path.startsWith('/') ? path : "/" + path; }; var endingSlash = function endingSlash(path) { return path.endsWith('/') ? path : path + "/"; }; var noEndingSlash = function noEndingSlash(path) { return !path.endsWith('/') ? path : path.substr(0, path.length - 1); }; function asDisposable(disposables) { return { dispose: function dispose() { var _disposables$dispose; return Array.isArray(disposables) ? disposeAll(disposables.filter(Boolean)) : typeof (disposables === null || disposables === void 0 ? void 0 : disposables.dispose) === 'function' ? disposables === null || disposables === void 0 ? void 0 : (_disposables$dispose = disposables.dispose) === null || _disposables$dispose === void 0 ? void 0 : _disposables$dispose.call(disposables) : {}; } }; } function disposeAll(disposables) { while (disposables.length) { var _disposables$pop, _disposables$pop$disp; (_disposables$pop = disposables.pop()) === null || _disposables$pop === void 0 ? void 0 : (_disposables$pop$disp = _disposables$pop.dispose) === null || _disposables$pop$disp === void 0 ? void 0 : _disposables$pop$disp.call(_disposables$pop); } } var version = '0.0.40'; function processSize(size) { size = String(size); return !/^\d+$/.test(size) ? size : size + "px"; } function processDimensions(width, height) { var fixedWidth = processSize(width); var fixedHeight = processSize(height); return { width: fixedWidth, height: fixedHeight }; } function noop() { return undefined; } var fetchPlugin = function fetchPlugin(_ref3) { var url = _ref3.url, _ref3$fetchOptions = _ref3.fetchOptions, fetchOptions = _ref3$fetchOptions === void 0 ? {} : _ref3$fetchOptions; try { return Promise.resolve(fetch(url, Object.assign({}, fetchOptions))).then(function (response) { return Promise.resolve(response.text()).then(function (text) { var code = text; var plugin = function plugin(monaco) { try { modularize(code, { monaco: monaco }, { 'monaco-editor-core': monaco, 'monaco-editor': monaco, 'use-monaco': monaco }); } catch (e) { console.log('[monaco] Error installing plugin from', url); } return { dispose: function dispose() {} }; }; return plugin; }); }); } catch (e) { return Promise.reject(e); } }; var createPlugin = function createPlugin(_ref, plugin) { var dependencies = _ref.dependencies, name = _ref.name, other = _objectWithoutPropertiesLoose(_ref, ["dependencies", "name", "format"]); plugin.dependencies = dependencies; plugin.label = name; // plugin.format = format; return plugin; }; var compose = function compose() { for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) { plugins[_key] = arguments[_key]; } return function (obj) { for (var _iterator = _createForOfIteratorHelperLoose(plugins), _step; !(_step = _iterator()).done;) { var plugin = _step.value; plugin(obj); } }; }; function modularize(text, globals, dependencies) { var require = function require(path) { return dependencies[path]; }; var exports = {}; var module = { exports: exports }; scopeEval__default['default'](text, Object.assign({ module: module, exports: exports, require: require }, globals)); return { module: module, exports: exports }; } var createRemotePlugin = function createRemotePlugin(_ref2) { var dependencies = _ref2.dependencies, name = _ref2.name, url = _ref2.url, _ref2$fetchOptions = _ref2.fetchOptions, fetchOptions = _ref2$fetchOptions === void 0 ? {} : _ref2$fetchOptions; return createPlugin({ name: name, dependencies: dependencies }, function (monaco) { try { console.log('[monaco] fetching plugin from', url); return Promise.resolve(fetchPlugin({ url: url, fetchOptions: fetchOptions })).then(function (remotePlugin) { return remotePlugin(monaco); }); } catch (e) { return Promise.reject(e); } }); }; var withPlugins = (function (monaco) { // returns whether to continue to install (true), or not install and wait (false) var checkDependencies = function checkDependencies(plugin) { try { var _plugin$dependencies; var waiting; (_plugin$dependencies = plugin.dependencies) === null || _plugin$dependencies === void 0 ? void 0 : _plugin$dependencies.forEach(function (dep) { if (installed[dep]) {} else { if (!waitingFor[dep]) { waitingFor[dep] = []; } waitingFor[dep].push(plugin); waiting = true; } }); if (waiting) { return Promise.resolve(false); } return Promise.resolve(true); } catch (e) { return Promise.reject(e); } }; var installPlugin = function installPlugin(plugin) { try { var _plugin$label2; console.log("[monaco] installing plugin: " + ((_plugin$label2 = plugin.label) !== null && _plugin$label2 !== void 0 ? _plugin$label2 : plugin.name)); return Promise.resolve(plugin(monaco)).then(function (d1) { var _plugin$label3; installed[(_plugin$label3 = plugin.label) !== null && _plugin$label3 !== void 0 ? _plugin$label3 : plugin.name] = plugin; if (plugin.label) { var d2 = release(plugin.label); return asDisposable([d1, d2].filter(Boolean)); } return d1; }); } catch (e) { return Promise.reject(e); } }; var installed = {}; // monaco.loader.includeBasicLanguages // ? Object.fromEntries( // basicLanguages.map((lang) => [`language.${lang}`, true as any]) // ) // : {}; var waitingFor = {}; function release(done) { if (waitingFor[done]) { var disposables = waitingFor[done].map(function (plugin) { var keepWaiting; plugin.dependencies.forEach(function (dep) { if (!installed[dep]) { keepWaiting = true; } }); if (!keepWaiting) { return installPlugin(plugin); } else { return null; } }); delete waitingFor[done]; return asDisposable(disposables.filter(Boolean)); } } Object.assign(monaco, { plugin: { isInstalled: function isInstalled(name) { return !!installed[name]; }, install: function () { for (var _len2 = arguments.length, plugins = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { plugins[_key2] = arguments[_key2]; } try { var _exit2 = false; var _temp5 = function _temp5(_result) { return _exit2 ? _result : asDisposable(disposables.filter(Boolean)); }; var disposables = []; var _temp6 = _forIn(plugins, function (i) { function _temp2(_fetchPlugin) { var _plugin$label; plugin = _temp ? _fetchPlugin : _fetchPlugin; if (!plugin) { throw new Error("Could'nt resolve plugin, " + plugin); } plugin.label = (_plugin$label = plugin.label) !== null && _plugin$label !== void 0 ? _plugin$label : plugin.name; if (installed[plugin.label]) { console.log("[monaco] skipped installing " + plugin.label + " (already installed)"); _exit2 = true; return; } return Promise.resolve(checkDependencies(plugin)).then(function (_checkDependencies) { if (!_checkDependencies) { return; } var _push = disposables.push; return Promise.resolve(installPlugin(plugin)).then(function (_installPlugin) { _push.call(disposables, _installPlugin); }); }); } var plugin = plugins[i]; var _temp = typeof plugin === 'function', _plugin$url = _temp || plugin.url; return _temp || !_plugin$url ? _temp2(_temp ? plugin : _plugin$url ? fetchPlugin(plugin) : null) : Promise.resolve(_temp ? plugin : _plugin$url ? fetchPlugin(plugin) : null).then(_temp2); }, function () { return _exit2; }); return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(_temp5) : _temp5(_temp6)); } catch (e) { return Promise.reject(e); } } } }); return monaco; }); var languageDefinitions = {}; var lazyLanguageLoaders = {}; var LazyLanguageLoader = /*#__PURE__*/function () { LazyLanguageLoader.getOrCreate = function getOrCreate(languageId) { if (!lazyLanguageLoaders[languageId]) { lazyLanguageLoaders[languageId] = new LazyLanguageLoader(languageId); } return lazyLanguageLoaders[languageId]; }; function LazyLanguageLoader(languageId) { var _this = this; this._languageId = void 0; this._loadingTriggered = void 0; this._lazyLoadPromise = void 0; this._lazyLoadPromiseResolve = void 0; this._lazyLoadPromiseReject = void 0; this._languageId = languageId; this._loadingTriggered = false; this._lazyLoadPromise = new Promise(function (resolve, reject) { _this._lazyLoadPromiseResolve = resolve; _this._lazyLoadPromiseReject = reject; }); } var _proto = LazyLanguageLoader.prototype; _proto.whenLoaded = function whenLoaded() { return this._lazyLoadPromise; }; _proto.load = function load() { var _this2 = this; if (!this._loadingTriggered) { var _languageDefinitions$, _languageDefinitions$2; this._loadingTriggered = true; (_languageDefinitions$ = languageDefinitions[this._languageId]) === null || _languageDefinitions$ === void 0 ? void 0 : (_languageDefinitions$2 = _languageDefinitions$.loader) === null || _languageDefinitions$2 === void 0 ? void 0 : _languageDefinitions$2.call(_languageDefinitions$).then(function (mod) { return _this2._lazyLoadPromiseResolve(mod); }, function (err) { return _this2._lazyLoadPromiseReject(err); }); } return this._lazyLoadPromise; }; return LazyLanguageLoader; }(); var languagesPlugin = createPlugin({ name: 'core.languages', dependencies: ['core.workers'] }, function (monaco) { var monacoLanguageRegister = monaco.languages.register; monaco.languages.register = function (languageDefintion) { var languageId = languageDefintion.id; var lang = monaco.languages.getLanguages().find(function (l) { return l.id === languageId; }); if (lang) { console.log('[monaco] replacing language:', languageId); Object.assign(lang, languageDefintion); languageDefinitions[languageId] = languageDefintion; } else { languageDefinitions[languageId] = languageDefintion; console.log('[monaco] registering language:', languageId); } monacoLanguageRegister(languageDefintion); if (languageDefintion.loader) { var lazyLanguageLoader = LazyLanguageLoader.getOrCreate(languageId); monaco.languages.setMonarchTokensProvider(languageId, lazyLanguageLoader.whenLoaded().then(function (mod) { return mod.language; })["catch"](function (e) { console.error(e); return; })); monaco.languages.onLanguage(languageId, function () { lazyLanguageLoader.load().then(function (mod) { if (mod && mod.conf) { monaco.languages.setLanguageConfiguration(languageId, mod.conf); } })["catch"](function (err) { console.error(err); return; }); }); } if (languageDefintion.worker) { var config = typeof languageDefintion.worker === 'object' ? languageDefintion.worker : {}; monaco.worker.register(Object.assign({ languageId: languageId }, config)); } }; }); var themes = createPlugin({ name: 'core.themes', dependencies: ['core.editors'] }, function (monaco) { var setTheme = monaco.editor.setTheme; var definedThemes = {}; var _onDidChangeTheme = new monaco.Emitter(); monaco.editor.onDidChangeTheme = _onDidChangeTheme.event; var defineTheme = monaco.editor.defineTheme; monaco.editor.defineTheme = function (name, theme) { defineTheme(name, theme); definedThemes[name] = theme; }; monaco.editor.setTheme = function (theme) { if (typeof theme === 'string') { try { var resolvedTheme = JSON.parse(parseJSONWithComments(theme)); if (typeof resolvedTheme === 'object' && (resolvedTheme === null || resolvedTheme === void 0 ? void 0 : resolvedTheme.colors)) { monaco.editor.setTheme(resolvedTheme); return; } else { console.log('[monaco] setting theme:', theme); setTheme(theme); _onDidChangeTheme.fire({ name: theme, theme: definedThemes[theme] }); } } catch (e) { console.log('[monaco] setting theme:', theme); setTheme(theme); _onDidChangeTheme.fire({ name: theme, theme: definedThemes[theme] }); } } else if (typeof theme === 'object') { try { monaco.editor.defineTheme('custom', theme); console.log('[monaco] setting theme:', theme); setTheme('custom'); _onDidChangeTheme.fire({ name: 'custom', theme: theme }); } catch (e) { console.warn("[monaco] error setting theme: " + e); } } }; monaco.editor.getDefinedThemes = function () { return definedThemes; }; monaco.editor.defineThemes = function (themes) { Object.keys(themes).forEach(function (themeName) { monaco.editor.defineTheme(themeName, themes[themeName]); }); }; monaco.editor.getTheme = function (themeName) { var _monaco$editor$getFoc; return (_monaco$editor$getFoc = monaco.editor.getFocusedEditor()) === null || _monaco$editor$getFoc === void 0 ? void 0 : _monaco$editor$getFoc['_themeService']; }; }); // function setupThemes( // monaco: typeof monacoApi, // // editor: monacoApi.editor.IStandaloneCodeEditor, // themes: any // ) { // // const allThemes = { // // // ...defaultThemes, // // ...themes, // // }; // // Object.keys(allThemes).forEach((themeName) => { // // monaco.editor.defineTheme( // // themeName, // // allThemes[themeName as keyof typeof allThemes] // // ); // // }); // // editor.addSelectAction({ // // id: 'editor.action.selectTheme', // // label: 'Preferences: Color Theme', // // choices: () => Object.keys(themeNames), // // runChoice: (choice, mode, ctx, api) => { // // if (mode === 0) { // // api.editor.setTheme(themeNames[choice]); // // } else if (mode === 1) { // // api.editor.setTheme(themeNames[choice]); // // } // // }, // // runAction: function (editor: any, api: any) { // // const _this: any = this; // // const currentTheme = editor._themeService._theme.themeName; // // console.log(currentTheme); // // const controller = _this.getController(editor); // // const oldDestroy = controller.widget.quickOpenWidget.callbacks.onCancel; // // controller.widget.quickOpenWidget.callbacks.onCancel = function () { // // debugger; // // monaco.editor.setTheme(currentTheme); // // oldDestroy(); // // }; // // console.log( // // controller, // // controller.widget.quickOpenWidget.callbacks.onCancel, // // this // // ); // // _this.show(editor); // // return Promise.resolve(); // // }, // // }); // } // // A list of color names: // 'foreground' // Overall foreground color. This color is only used if not overridden by a component. // 'errorForeground' // Overall foreground color for error messages. This color is only used if not overridden by a component. // 'descriptionForeground' // Foreground color for description text providing additional information, for example for a label. // 'focusBorder' // Overall border color for focused elements. This color is only used if not overridden by a component. // 'contrastBorder' // An extra border around elements to separate them from others for greater contrast. // 'contrastActiveBorder' // An extra border around active elements to separate them from others for greater contrast. // 'selection.background' // The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor. // 'textSeparator.foreground' // Color for text separators. // 'textLink.foreground' // Foreground color for links in text. // 'textLink.activeForeground' // Foreground color for active links in text. // 'textPreformat.foreground' // Foreground color for preformatted text segments. // 'textBlockQuote.background' // Background color for block quotes in text. // 'textBlockQuote.border' // Border color for block quotes in text. // 'textCodeBlock.background' // Background color for code blocks in text. // 'widget.shadow' // Shadow color of widgets such as find/replace inside the editor. // 'input.background' // Input box background. // 'input.foreground' // Input box foreground. // 'input.border' // Input box border. // 'inputOption.activeBorder' // Border color of activated options in input fields. // 'input.placeholderForeground' // Input box foreground color for placeholder text. // 'inputValidation.infoBackground' // Input validation background color for information severity. // 'inputValidation.infoBorder' // Input validation border color for information severity. // 'inputValidation.warningBackground' // Input validation background color for information warning. // 'inputValidation.warningBorder' // Input validation border color for warning severity. // 'inputValidation.errorBackground' // Input validation background color for error severity. // 'inputValidation.errorBorder' // Input validation border color for error severity. // 'dropdown.background' // Dropdown background. // 'dropdown.foreground' // Dropdown foreground. // 'dropdown.border' // Dropdown border. // 'list.focusBackground' // List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not. // 'list.focusForeground' // List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not. // 'list.activeSelectionBackground' // List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not. // 'list.activeSelectionForeground' // List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not. // 'list.inactiveSelectionBackground' // List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not. // 'list.inactiveSelectionForeground' // List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not. // 'list.hoverBackground' // List/Tree background when hovering over items using the mouse. // 'list.hoverForeground' // List/Tree foreground when hovering over items using the mouse. // 'list.dropBackground' // List/Tree drag and drop background when moving items around using the mouse. // 'list.highlightForeground' // List/Tree foreground color of the match highlights when searching inside the list/tree. // 'pickerGroup.foreground' // Quick picker color for grouping labels. // 'pickerGroup.border' // Quick picker color for grouping borders. // 'button.foreground' // Button foreground color. // 'button.background' // Button background color. // 'button.hoverBackground' // Button background color when hovering. // 'badge.background' // Badge background color. Badges are small information labels, e.g. for search results count. // 'badge.foreground' // Badge foreground color. Badges are small information labels, e.g. for search results count. // 'scrollbar.shadow' // Scrollbar shadow to indicate that the view is scrolled. // 'scrollbarSlider.background' // Slider background color. // 'scrollbarSlider.hoverBackground' // Slider background color when hovering. // 'scrollbarSlider.activeBackground' // Slider background color when active. // 'progressBar.background' // Background color of the progress bar that can show for long running operations. // 'editor.background' // Editor background color. // 'editor.foreground' // Editor default foreground color. // 'editorWidget.background' // Background color of editor widgets, such as find/replace. // 'editorWidget.border' // Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget. // 'editor.selectionBackground' // Color of the editor selection. // 'editor.selectionForeground' // Color of the selected text for high contrast. // 'editor.inactiveSelectionBackground' // Color of the selection in an inactive editor. // 'editor.selectionHighlightBackground' // Color for regions with the same content as the selection. // 'editor.findMatchBackground' // Color of the current search match. // 'editor.findMatchHighlightBackground' // Color of the other search matches. // 'editor.findRangeHighlightBackground' // Color the range limiting the search. // 'editor.hoverHighlightBackground' // Highlight below the word for which a hover is shown. // 'editorHoverWidget.background' // Background color of the editor hover. // 'editorHoverWidget.border' // Border color of the editor hover. // 'editorLink.activeForeground' // Color of active links. // 'diffEditor.insertedTextBackground' // Background color for text that got inserted. // 'diffEditor.removedTextBackground' // Background color for text that got removed. // 'diffEditor.insertedTextBorder' // Outline color for the text that got inserted. // 'diffEditor.removedTextBorder' // Outline color for text that got removed. // 'editorOverviewRuler.currentContentForeground' // Current overview ruler foreground for inline merge-conflicts. // 'editorOverviewRuler.incomingContentForeground' // Incoming overview ruler foreground for inline merge-conflicts. // 'editorOverviewRuler.commonContentForeground' // Common ancestor overview ruler foreground for inline merge-conflicts. // 'editor.lineHighlightBackground' // Background color for the highlight of line at the cursor position. // 'editor.lineHighlightBorder' // Background color for the border around the line at the cursor position. // 'editor.rangeHighlightBackground' // Background color of highlighted ranges, like by quick open and find features. // 'editorCursor.foreground' // Color of the editor cursor. // 'editorWhitespace.foreground' // Color of whitespace characters in the editor. // 'editorIndentGuide.background' // Color of the editor indentation guides. // 'editorLineNumber.foreground' // Color of editor line numbers. // 'editorRuler.foreground' // Color of the editor rulers. // 'editorCodeLens.foreground' // Foreground color of editor code lenses // 'editorBracketMatch.background' // Background color behind matching brackets // 'editorBracketMatch.border' // Color for matching brackets boxes // 'editorOverviewRuler.border' // Color of the overview ruler border. // 'editorGutter.background' // Background color of the editor gutter. The gutter contains the glyph margins and the line numbers. // 'editorError.foreground' // Foreground color of error squigglies in the editor. // 'editorError.border' // Border color of error squigglies in the editor. // 'editorWarning.foreground' // Foreground color of warning squigglies in the editor. // 'editorWarning.border' // Border color of warning squigglies in the editor. // 'editorMarkerNavigationError.background' // Editor marker navigation widget error color. // 'editorMarkerNavigationWarning.background' // Editor marker navigation widget warning color. // 'editorMarkerNavigation.background' // Editor marker navigation widget background. // 'editorSuggestWidget.background' // Background color of the suggest widget. // 'editorSuggestWidget.border' // Border color of the suggest widget. // 'editorSuggestWidget.foreground' // Foreground color of the suggest widget. // 'editorSuggestWidget.selectedBackground' // Background color of the selected entry in the suggest widget. // 'editorSuggestWidget.highlightForeground' // Color of the match highlights in the suggest widget. // 'editor.wordHighlightBackground' // Background color of a symbol during read-access, like reading a variable. // 'editor.wordHighlightStrongBackground' // Background color of a symbol during write-access, like writing to a variable. // 'peekViewTitle.background' // Background color of the peek view title area. // 'peekViewTitleLabel.foreground' // Color of the peek view title. // 'peekViewTitleDescription.foreground' // Color of the peek view title info. // 'peekView.border' // Color of the peek view borders and arrow. // 'peekViewResult.background' // Background color of the peek view result list. // 'peekViewResult.lineForeground' // Foreground color for line nodes in the peek view result list. // 'peekViewResult.fileForeground' // Foreground color for file nodes in the peek view result list. // 'peekViewResult.selectionBackground' // Background color of the selected entry in the peek view result list. // 'peekViewResult.selectionForeground' // Foreground color of the selected entry in the peek view result list. // 'peekViewEditor.background' // Background color of the peek view editor. // 'peekViewEditorGutter.background' // Background color of the gutter in the peek view editor. // 'peekViewResult.matchHighlightBackground' // Match highlight color in the peek view result list. // 'peekViewEditor.matchHighlightBackground' // Match highlight color in the peek view editor. var editors = createPlugin({ name: 'core.editors', dependencies: [] }, function (monaco) { var createMonacoEditor = monaco.editor.create; var _onCreatedEditor = new monaco.Emitter(); // const onDidCreateEditor = monaco.editor.onDidCreateEditor; monaco.editor.onDidCreateEditor = _onCreatedEditor.event; // let _defaultEditorOptions = {}; // monaco.editor.getDefaultEditorOptions = () => { // let editorOptions = _defaultEditorOptions; // console.log(editorOptions); // return editorOptions; // }; // monaco.editor.setDefaultEditorOptions = (opts) => { // console.log(opts); // Object.keys(opts).forEach((k) => { // _defaultEditorOptions[k] = opts[k]; // }); // }; monaco.editor.create = function (domElement, options, override) { var editor = createMonacoEditor(domElement, options, override); _onCreatedEditor.fire(editor); return editor; }; var editors = []; var focusedEditor = null; monaco.editor.getFocusedEditor = function () { return focusedEditor; }; monaco.editor.getEditors = function () { return editors; }; return monaco.editor.onDidCreateEditor(function (editor) { editors.push(editor); if (!focusedEditor) { focusedEditor = editor; } editor.onDidFocusEditorText(function () { focusedEditor = editor; }); editor.onDidDispose(function () { editors = editors.filter(function (ed) { return ed !== editor; }); }); }); }); // editor.addSelectAction = function (descriptor) { // return editor.addAction(new QuickSelectAction(descriptor, monaco) as any); // }; // function setupCommandPaletteShortcuts( // editor: monacoApi.editor.IStandaloneCodeEditor // ) { // // for firefox support (wasn't able to intercept key) // editor.addCommand( // monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_C, // () => { // editor.trigger('ctrl-shift-c', 'editor.action.quickCommand', null); // } // ); // editor.addCommand( // monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_P, // () => { // editor.trigger('ctrl-shift-p', 'editor.action.quickCommand', null); // } // ); // window.addEventListener('keydown', (event: any) => { // if (event.metaKey && event.shiftKey && event.code === 'KeyP') { // editor.trigger('ctrl-shift-p', 'editor.action.quickCommand', null); // event.stopPropagation(); // } // }); // } // @ts-ignore // import { BaseEditorQuickOpenAction } from '../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickOpen/editorQuickOpen'; // @ts-ignore // import { // QuickOpenModel, // QuickOpenEntry, // // @ts-ignore // } from '../../node_modules/monaco-editor/esm/vs/base/parts/quickopen/browser/quickOpenModel'; // @ts-ignore // import { matchesFuzzy } from '../../node_modules/monaco-editor/esm/vs/base/common/filters'; // export type IQuickSelectAction = Omit< // monacoApi.editor.IActionDescriptor, // 'run' // > & { // choices?: () => Promise<string[]> | string[]; // runChoice?: ( // choice: string, // mode: number, // context: any, // api: typeof monacoApi // ) => Promise<boolean | void> | boolean | void; // runAction?: ( // editor: monacoApi.editor.IStandaloneCodeEditor, // api: typeof monacoApi // ) => Promise<void>; // }; // export class QuickSelectAction extends BaseEditorQuickOpenAction { // choices?: IQuickSelectAction['choices']; // runChoice: IQuickSelectAction['runChoice']; // id?: string; // label?: string; // precondition?: string; // keybindings?: number[]; // keybindingContext?: string; // contextMenuGroupId?: string; // contextMenuOrder?: number; // runAction?: IQuickSelectAction['runAction']; // api: typeof monacoApi; // constructor(descriptor: IQuickSelectAction, api: typeof monacoApi) { // super(descriptor.label, descriptor); // Object.assign(this, descriptor); // const _this: any = this; // this.runAction = // descriptor?.runAction ?? // (async function (editor: any, api: any, payload: any) { // await _this.show(editor, payload); // return; // } as any); // this.api = api; // } // getOptions( // editor: monaco.editor.IStandaloneCodeEditor, // choices: string[], // searchValue: string // ) { // const _this = this; // const entries: QuickOpenEntry[] = []; // choices.forEach((name) => { // var highlights = matchesFuzzy(searchValue, name); // if (highlights) { // const entry = new QuickOpenEntry(); // entry.getLabel = () => name; // entry.setHighlights(highlights); // entry.run = function (mode: number, context: any) { // if (mode === 0) { // _this.runChoice?.(name, mode, context, _this.api); // return false; // } else if (mode === 1 /* OPEN */) { // // Use a timeout to give the quick open widget a chance to close itself first // setTimeout(function () { // // Some actions are enabled only when editor has focus // editor.focus(); // _this.runChoice?.(name, mode, context, _this.api); // }, 50); // return true; // } // return false; // }; // entries.push(entry); // } // }); // return entries; // } // async show(editor: monacoApi.editor.IStandaloneCodeEditor) { // const _this: any = this; // const choices = await _this.choices(); // _this._show(_this.getController(editor), { // getModel: function (value: string) { // // return new QuickOpenModel( // // _this.getOptions(editor, choices, value) // // // _this._editorActionsToEntries(keybindingService, editor, value) // // ); // }, // getAutoFocus: function (searchValue: string) { // return { // autoFocusFirstEntry: true, // autoFocusPrefixMatch: searchValue, // }; // }, // }); // } // run() { // const editor = arguments[0]; // const _this = this; // _this.runAction?.apply(_this, [editor, monacoApi]); // return Promise.resolve(); // } // } // export class SetThemeAction extends QuickSelectAction { // constructor() { // super(); // } // _getThemeEntries(editor, searchValue) { // const _this = this; // const entries = []; // Object.keys(themeNames).forEach((name) => { // var highlights = matchesFuzzy(searchValue, name); // if (highlights) { // const entry = new QuickOpenEntry(); // entry.getLabel = () => name; // entry.setHighlights(highlights); // entry.run = function (mode, context) { // if (mode === 0) { // _this.api.editor.setTheme(themeNames[name]); // return false; // } else if (mode === 1 /* OPEN */) { // // Use a timeout to give the quick open widget a chance to close itself first // setTimeout(function () { // // Some actions are enabled only when editor has focus // editor.focus(); // _this.api.editor.setTheme(themeNames[name]); // localStorage.setItem('theme', themeNames[name]); // }, 50); // return true; // } // }; // entries.push(entry); // } // }); // return entries; // } // run() { // const editor: monacoApi.editor.IStandaloneCodeEditor = arguments[0]; // const currentTheme = editor._themeService._theme.themeName; // this.show(editor); // const _this = this; // const controller = _this.getController(editor); // const oldDestroy = controller.widget.quickOpenWidget.callbacks.onCancel; // controller.widget.quickOpenWidget.callbacks.onCancel = function () { // monaco.editor.setTheme(currentTheme); // oldDestroy(); // }; // return Promise.resolve(); // } // } var shortcuts = createPlugin({ name: 'core.shortcuts', dependencies: ['core.editors'] }, function (monaco) { return monaco.editor.onDidCreateEditor(function (editor) { var _editor$getRawOptions; if ((_editor$getRawOptions = editor.getRawOptions()) === null || _editor$getRawOptions === void 0 ? void 0 : _editor$getRawOptions.formatOnSave) { editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function () { editor === null || editor === void 0 ? void 0 : editor.trigger('ctrl-s', 'editor.action.formatDocument', null); }); } // } // for firefox support (wasn't able to intercept key) // editor.addCommand( // monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_C, // () => { // editor.trigger('ctrl-shift-c', 'editor.action.quickCommand', null); // } // ); // editor.addCommand( // monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_P, // () => { // editor.trigger('ctrl-shift-p', 'editor.action.quickCommand', null); // } // ); // window.addEventListener('keydown', (event: any) => { // if (event.metaKey && event.shiftKey && event.code === 'KeyP') { // editor.trigger('ctrl-shift-p', 'editor.action.quickCommand', null); // event.stopPropagation(); // } // }); }); }); var defaultProviderConfig = { reference: true, rename: true, signatureHelp: true, hover: true, documentSymbol: true, documentHighlight: true, definition: true, implementation: true, typeDefinition: true, codeLens: true, codeAction: true, documentFormattingEdit: true, documentRangeFormattingEdit: true, onTypeFormattingEdit: true, link: true, completionItem: true, color: true, foldingRange: true, declaration: true, selectionRange: true, diagnostics: true, documentSemanticTokens: true, documentRangeSemanticTokens: true }; var getProvider = function getProvider(getWorker, provider) { return function (model) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } try { var resource = model.uri; return Promise.resolve(_catch(function () { return Promise.resolve(getWorker(resource)).then(function (worker) { return Promise.resolve(worker.provide.apply(worker, [provider, resource.toString()].concat(args.slice(0, args.length - 1)))); }); }, function (e) { console.error(e); return null; })); } catch (e) { return Promise.reject(e); } }; }; var getSignatureHelpProvider = function getSignatureHelpProvider(getWorker) { return function (model, position, token, context) { try { var resource = model.uri; return Promise.resolve(_catch(function () { return Promise.resolve(getWorker(resource)).then(function (worker) { return Promise.resolve(worker.provide('signatureHelp', resource.toString(), position, context)); }); }, function (e) { console.error(e); return null; })); } catch (e) { return Promise.reject(e); } }; }; var getResolver = function getResolver(getWorker, resolver) { return function (model) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } try { var resource = model.uri; return Promise.resolve(_catch(function () { return Promise.resolve(getWorker(resource)).then(function (worker) { return Promise.resolve(worker.resolve.apply(worker, [resolver, resource.toString()].concat(args.slice(0, args.length - 1)))); }); }, function (e) { console.error(e); return null; })); } catch (e) { return Promise.reject(e); } }; }; var getCompletionItemResolver = function getCompletionItemResolver(getWorker) { return function (item, token) { try { return Promise.resolve(_catch(function () { return Promise.resolve(getWorker()).then(function (worker) { return Promise.resolve(worker.resolve('completionItem', item, token)); }); }, function (e) { console.error(e); return null; })); } catch (e) { return Promise.reject(e); } }; }; var DiagnosticsProvider = /*#__PURE__*/function () { var _proto = DiagnosticsProvider.prototype; _proto.isActiveModel = function isActiveModel(model) { if (this._editor) { var currentModel = this._editor.getModel(); if (currentModel && currentModel.uri.toString() === model.uri.toString()) { return true; } } return false; }; function DiagnosticsProvider(client, monaco) { var _this = this; this.client = client; this._disposables = []; this._listener = Object.create(null); this._editor = void 0; this._client = void 0; this.monaco = void 0; this._client = client; this.monaco = monaco; this._disposables.push(monaco.editor.onDidCreateEditor(function (editor) { _this._editor = editor; })); var onModelAdd = function onModelAdd(model) { var modeId = model.getModeId(); if (modeId !== client.config.languageId) { return; } // console.log( // 'model added', // model.uri.toString(), // client.config.languageId, // model.getModeId() // ); var handle; // console.log(handle, this._listener, this._client, model); _this._listener[model.uri.toString()] = model.onDidChangeContent(function () { clearTimeout(handle); // @ts-ignore handle = setTimeout(function () { // if (this.isActiveModel(model)) { _this._doValidate(model.uri, modeId); // } }, 500); }); // if (this.isActiveModel(model)) { _this._doValidate(model.uri, modeId); // } }; var onModelRemoved = function onModelRemoved(model) { var _client$config$langua; // console.log( // 'model removed', // model.uri.toString(), // client.config.languageId // ); monaco.editor.setModelMarkers(model, (_client$config$langua = client.config.languageId) !== null && _client$config$langua !== void 0 ? _client$config$langua : '', []); var uriStr = model.uri.toString(); var listener = _this._listener[uriStr]; if (listener) { listener.dispose(); delete _this._listener[uriStr]; } }; this._disposables.push(monaco.editor.onDidCreateModel(onModelAdd)); this._disposables.push(monaco.editor.onWillDisposeModel(function (model) { // console.log( // 'model disposed', // model.uri.toString(), // client.config.languageId // ); onModelRemoved(model); })); this._disposables.push(monaco.editor.onDidChangeModelLanguage(function (event) { // console.log( // 'model changed language', // event.model.uri.toStri