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.0KB

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