You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

codeeditor.js 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import tinycolor from 'tinycolor2';
  2. import {basename, extname, isObject, isDarkTheme} from '../utils.js';
  3. import {onInputDebounce} from '../utils/dom.js';
  4. const languagesByFilename = {};
  5. const languagesByExt = {};
  6. const baseOptions = {
  7. fontFamily: 'var(--fonts-monospace)',
  8. fontSize: 14, // https://github.com/microsoft/monaco-editor/issues/2242
  9. guides: {bracketPairs: false, indentation: false},
  10. links: false,
  11. minimap: {enabled: false},
  12. occurrencesHighlight: 'off',
  13. overviewRulerLanes: 0,
  14. renderLineHighlight: 'all',
  15. renderLineHighlightOnlyWhenFocus: true,
  16. rulers: false,
  17. scrollbar: {horizontalScrollbarSize: 6, verticalScrollbarSize: 6},
  18. scrollBeyondLastLine: false,
  19. automaticLayout: true,
  20. };
  21. function getEditorconfig(input) {
  22. try {
  23. return JSON.parse(input.getAttribute('data-editorconfig'));
  24. } catch {
  25. return null;
  26. }
  27. }
  28. function initLanguages(monaco) {
  29. for (const {filenames, extensions, id} of monaco.languages.getLanguages()) {
  30. for (const filename of filenames || []) {
  31. languagesByFilename[filename] = id;
  32. }
  33. for (const extension of extensions || []) {
  34. languagesByExt[extension] = id;
  35. }
  36. }
  37. }
  38. function getLanguage(filename) {
  39. return languagesByFilename[filename] || languagesByExt[extname(filename)] || 'plaintext';
  40. }
  41. function updateEditor(monaco, editor, filename, lineWrapExts) {
  42. editor.updateOptions(getFileBasedOptions(filename, lineWrapExts));
  43. const model = editor.getModel();
  44. const language = model.getLanguageId();
  45. const newLanguage = getLanguage(filename);
  46. if (language !== newLanguage) monaco.editor.setModelLanguage(model, newLanguage);
  47. }
  48. // export editor for customization - https://github.com/go-gitea/gitea/issues/10409
  49. function exportEditor(editor) {
  50. if (!window.codeEditors) window.codeEditors = [];
  51. if (!window.codeEditors.includes(editor)) window.codeEditors.push(editor);
  52. }
  53. export async function createMonaco(textarea, filename, editorOpts) {
  54. const monaco = await import(/* webpackChunkName: "monaco" */'monaco-editor');
  55. initLanguages(monaco);
  56. let {language, ...other} = editorOpts;
  57. if (!language) language = getLanguage(filename);
  58. const container = document.createElement('div');
  59. container.className = 'monaco-editor-container';
  60. textarea.parentNode.append(container);
  61. // https://github.com/microsoft/monaco-editor/issues/2427
  62. // also, monaco can only parse 6-digit hex colors, so we convert the colors to that format
  63. const styles = window.getComputedStyle(document.documentElement);
  64. const getColor = (name) => tinycolor(styles.getPropertyValue(name).trim()).toString('hex6');
  65. monaco.editor.defineTheme('gitea', {
  66. base: isDarkTheme() ? 'vs-dark' : 'vs',
  67. inherit: true,
  68. rules: [
  69. {
  70. background: getColor('--color-code-bg'),
  71. },
  72. ],
  73. colors: {
  74. 'editor.background': getColor('--color-code-bg'),
  75. 'editor.foreground': getColor('--color-text'),
  76. 'editor.inactiveSelectionBackground': getColor('--color-primary-light-4'),
  77. 'editor.lineHighlightBackground': getColor('--color-editor-line-highlight'),
  78. 'editor.selectionBackground': getColor('--color-primary-light-3'),
  79. 'editor.selectionForeground': getColor('--color-primary-light-3'),
  80. 'editorLineNumber.background': getColor('--color-code-bg'),
  81. 'editorLineNumber.foreground': getColor('--color-secondary-dark-6'),
  82. 'editorWidget.background': getColor('--color-body'),
  83. 'editorWidget.border': getColor('--color-secondary'),
  84. 'input.background': getColor('--color-input-background'),
  85. 'input.border': getColor('--color-input-border'),
  86. 'input.foreground': getColor('--color-input-text'),
  87. 'scrollbar.shadow': getColor('--color-shadow'),
  88. 'progressBar.background': getColor('--color-primary'),
  89. },
  90. });
  91. // Quick fix: https://github.com/microsoft/monaco-editor/issues/2962
  92. monaco.languages.register({id: 'vs.editor.nullLanguage'});
  93. monaco.languages.setLanguageConfiguration('vs.editor.nullLanguage', {});
  94. const editor = monaco.editor.create(container, {
  95. value: textarea.value,
  96. theme: 'gitea',
  97. language,
  98. ...other,
  99. });
  100. const model = editor.getModel();
  101. model.onDidChangeContent(() => {
  102. textarea.value = editor.getValue({preserveBOM: true});
  103. textarea.dispatchEvent(new Event('change')); // seems to be needed for jquery-are-you-sure
  104. });
  105. exportEditor(editor);
  106. const loading = document.querySelector('.editor-loading');
  107. if (loading) loading.remove();
  108. return {monaco, editor};
  109. }
  110. function getFileBasedOptions(filename, lineWrapExts) {
  111. return {
  112. wordWrap: (lineWrapExts || []).includes(extname(filename)) ? 'on' : 'off',
  113. };
  114. }
  115. function togglePreviewDisplay(previewable) {
  116. const previewTab = document.querySelector('a[data-tab="preview"]');
  117. if (!previewTab) return;
  118. if (previewable) {
  119. const newUrl = (previewTab.getAttribute('data-url') || '').replace(/(.*)\/.*/, `$1/markup`);
  120. previewTab.setAttribute('data-url', newUrl);
  121. previewTab.style.display = '';
  122. } else {
  123. previewTab.style.display = 'none';
  124. // If the "preview" tab was active, user changes the filename to a non-previewable one,
  125. // then the "preview" tab becomes inactive (hidden), so the "write" tab should become active
  126. if (previewTab.classList.contains('active')) {
  127. const writeTab = document.querySelector('a[data-tab="write"]');
  128. writeTab.click();
  129. }
  130. }
  131. }
  132. export async function createCodeEditor(textarea, filenameInput) {
  133. const filename = basename(filenameInput.value);
  134. const previewableExts = new Set((textarea.getAttribute('data-previewable-extensions') || '').split(','));
  135. const lineWrapExts = (textarea.getAttribute('data-line-wrap-extensions') || '').split(',');
  136. const previewable = previewableExts.has(extname(filename));
  137. const editorConfig = getEditorconfig(filenameInput);
  138. togglePreviewDisplay(previewable);
  139. const {monaco, editor} = await createMonaco(textarea, filename, {
  140. ...baseOptions,
  141. ...getFileBasedOptions(filenameInput.value, lineWrapExts),
  142. ...getEditorConfigOptions(editorConfig),
  143. });
  144. filenameInput.addEventListener('input', onInputDebounce(() => {
  145. const filename = filenameInput.value;
  146. const previewable = previewableExts.has(extname(filename));
  147. togglePreviewDisplay(previewable);
  148. updateEditor(monaco, editor, filename, lineWrapExts);
  149. }));
  150. return editor;
  151. }
  152. function getEditorConfigOptions(ec) {
  153. if (!isObject(ec)) return {};
  154. const opts = {};
  155. opts.detectIndentation = !('indent_style' in ec) || !('indent_size' in ec);
  156. if ('indent_size' in ec) opts.indentSize = Number(ec.indent_size);
  157. if ('tab_width' in ec) opts.tabSize = Number(ec.tab_width) || opts.indentSize;
  158. if ('max_line_length' in ec) opts.rulers = [Number(ec.max_line_length)];
  159. opts.trimAutoWhitespace = ec.trim_trailing_whitespace === true;
  160. opts.insertSpaces = ec.indent_style === 'space';
  161. opts.useTabStops = ec.indent_style === 'tab';
  162. return opts;
  163. }