theme.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { EditorView } from '@codemirror/view'
  2. import { Annotation, Compartment, TransactionSpec } from '@codemirror/state'
  3. import { syntaxHighlighting } from '@codemirror/language'
  4. import { classHighlighter } from './class-highlighter'
  5. import classNames from 'classnames'
  6. import {
  7. FontFamily,
  8. LineHeight,
  9. OverallTheme,
  10. userStyles,
  11. } from '@/shared/utils/styles'
  12. const optionsThemeConf = new Compartment()
  13. const selectedThemeConf = new Compartment()
  14. export const themeOptionsChange = Annotation.define<boolean>()
  15. type Options = {
  16. fontSize: number
  17. fontFamily: FontFamily
  18. lineHeight: LineHeight
  19. overallTheme: OverallTheme
  20. bootstrapVersion: 3 | 5
  21. }
  22. export const theme = (options: Options) => [
  23. baseTheme,
  24. staticTheme,
  25. /**
  26. * Syntax highlighting, using a highlighter which maps tags to class names.
  27. */
  28. syntaxHighlighting(classHighlighter),
  29. optionsThemeConf.of(createThemeFromOptions(options)),
  30. selectedThemeConf.of([]),
  31. ]
  32. export const setOptionsTheme = (options: Options): TransactionSpec => {
  33. return {
  34. effects: optionsThemeConf.reconfigure(createThemeFromOptions(options)),
  35. annotations: themeOptionsChange.of(true),
  36. }
  37. }
  38. export const setEditorTheme = async (
  39. editorTheme: string
  40. ): Promise<TransactionSpec> => {
  41. const theme = await loadSelectedTheme(editorTheme)
  42. return {
  43. effects: selectedThemeConf.reconfigure(theme),
  44. }
  45. }
  46. const svgUrl = (content: string) =>
  47. `url('data:image/svg+xml,${encodeURIComponent(
  48. `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">${content}</svg>`
  49. )}')`
  50. const createThemeFromOptions = ({
  51. fontSize = 12,
  52. fontFamily = 'monaco',
  53. lineHeight = 'normal',
  54. overallTheme = '',
  55. bootstrapVersion = 3,
  56. }: Options) => {
  57. // Theme styles that depend on settings.
  58. const styles = userStyles({ fontSize, fontFamily, lineHeight })
  59. return [
  60. EditorView.editorAttributes.of({
  61. class: classNames(
  62. overallTheme === '' ? 'overall-theme-dark' : 'overall-theme-light',
  63. 'bootstrap-' + bootstrapVersion
  64. ),
  65. style: Object.entries({
  66. '--font-size': styles.fontSize,
  67. '--source-font-family': styles.fontFamily,
  68. '--line-height': styles.lineHeight,
  69. })
  70. .map(([key, value]) => `${key}: ${value}`)
  71. .join(';'),
  72. }),
  73. // set variables for tooltips, which are outside the editor
  74. // TODO: set these on document.body, or a new container element for the tooltips, without using a style mod
  75. EditorView.theme({
  76. '.cm-tooltip': {
  77. '--font-size': styles.fontSize,
  78. '--source-font-family': styles.fontFamily,
  79. '--line-height': styles.lineHeight,
  80. },
  81. }),
  82. ]
  83. }
  84. /**
  85. * Base styles that can have &dark and &light variants
  86. */
  87. const baseTheme = EditorView.baseTheme({
  88. '.cm-content': {
  89. fontSize: 'var(--font-size)',
  90. fontFamily: 'var(--source-font-family)',
  91. lineHeight: 'var(--line-height)',
  92. },
  93. '.cm-cursor-primary': {
  94. fontSize: 'var(--font-size)',
  95. fontFamily: 'var(--source-font-family)',
  96. lineHeight: 'var(--line-height)',
  97. },
  98. '.cm-gutters': {
  99. fontSize: 'var(--font-size)',
  100. lineHeight: 'var(--line-height)',
  101. },
  102. '.cm-tooltip': {
  103. // NOTE: fontFamily is not set here, as most tooltips use the UI font
  104. fontSize: 'var(--font-size)',
  105. },
  106. '.cm-panel': {
  107. fontSize: 'var(--font-size)',
  108. },
  109. '.cm-foldGutter .cm-gutterElement > span': {
  110. height: 'calc(var(--font-size) * var(--line-height))',
  111. },
  112. '.cm-lineNumbers': {
  113. fontFamily: 'var(--source-font-family)',
  114. },
  115. // double the specificity to override the underline squiggle
  116. '.cm-lintRange.cm-lintRange': {
  117. backgroundImage: 'none',
  118. },
  119. // use a background color for lint error ranges
  120. '.cm-lintRange-error': {
  121. padding: 'var(--half-leading, 0) 0',
  122. background: 'rgba(255, 0, 0, 0.2)',
  123. // avoid highlighting nested error ranges
  124. '& .cm-lintRange-error': {
  125. background: 'none',
  126. },
  127. },
  128. '.cm-specialChar': {
  129. color: 'red',
  130. backgroundColor: 'rgba(255, 0, 0, 0.1)',
  131. },
  132. '.cm-widgetBuffer': {
  133. height: '1.3em',
  134. },
  135. '.cm-snippetFieldPosition': {
  136. display: 'inline-block',
  137. height: '1.3em',
  138. },
  139. // style the gutter fold button on hover
  140. '&dark .cm-foldGutter .cm-gutterElement > span:hover': {
  141. boxShadow: '0 1px 1px rgba(255, 255, 255, 0.2)',
  142. backgroundColor: 'rgba(255, 255, 255, 0.1)',
  143. },
  144. '&light .cm-foldGutter .cm-gutterElement > span:hover': {
  145. borderColor: 'rgba(0, 0, 0, 0.3)',
  146. boxShadow: '0 1px 1px rgba(255, 255, 255, 0.7)',
  147. backgroundColor: 'rgba(255, 255, 255, 0.2)',
  148. },
  149. '.cm-diagnosticSource': {
  150. display: 'none',
  151. },
  152. '.ol-cm-diagnostic-actions': {
  153. marginTop: '4px',
  154. },
  155. '.cm-diagnostic:last-of-type .ol-cm-diagnostic-actions': {
  156. marginBottom: '4px',
  157. },
  158. '.cm-vim-panel input': {
  159. color: 'inherit',
  160. },
  161. })
  162. /**
  163. * Theme styles that don't depend on settings.
  164. */
  165. // TODO: move some/all of these into baseTheme?
  166. const staticTheme = EditorView.theme({
  167. // make the editor fill the available height
  168. '&': {
  169. height: '100%',
  170. textRendering: 'optimizeSpeed',
  171. },
  172. // remove the outline from the focused editor
  173. '&.cm-editor.cm-focused:not(:focus-visible)': {
  174. outline: 'none',
  175. },
  176. // override default styles for the search panel
  177. '.cm-panel.cm-search label': {
  178. display: 'inline-flex',
  179. alignItems: 'center',
  180. fontWeight: 'normal',
  181. },
  182. '.cm-selectionLayer': {
  183. zIndex: -10,
  184. },
  185. // remove the right-hand border from the gutter
  186. // ensure the gutter doesn't shrink
  187. '.cm-gutters': {
  188. borderRight: 'none',
  189. flexShrink: 0,
  190. },
  191. // style the gutter fold button
  192. // TODO: add a class to this element for easier theming
  193. '.cm-foldGutter .cm-gutterElement > span': {
  194. border: '1px solid transparent',
  195. borderRadius: '3px',
  196. display: 'inline-flex',
  197. flexDirection: 'column',
  198. justifyContent: 'center',
  199. color: 'rgba(109, 109, 109, 0.7)',
  200. },
  201. // reduce the padding around line numbers
  202. '.cm-lineNumbers .cm-gutterElement': {
  203. padding: '0',
  204. userSelect: 'none',
  205. },
  206. // make cursor visible with reduced opacity when the editor is not focused
  207. '&:not(.cm-focused) > .cm-scroller > .cm-cursorLayer .cm-cursor': {
  208. display: 'block',
  209. opacity: 0.2,
  210. },
  211. // make the cursor wider, and use the themed color
  212. '.cm-cursor, .cm-dropCursor': {
  213. borderWidth: '2px',
  214. marginLeft: '-1px', // half the border width
  215. borderLeftColor: 'inherit',
  216. },
  217. // remove border from hover tooltips (e.g. cursor highlights)
  218. '.cm-tooltip-hover': {
  219. border: 'none',
  220. },
  221. // use the same style as Ace for snippet fields
  222. '.cm-snippetField': {
  223. background: 'rgba(194, 193, 208, 0.09)',
  224. border: '1px dotted rgba(211, 208, 235, 0.62)',
  225. },
  226. // style the fold placeholder
  227. '.cm-foldPlaceholder': {
  228. boxSizing: 'border-box',
  229. display: 'inline-block',
  230. height: '11px',
  231. width: '1.8em',
  232. marginTop: '-2px',
  233. verticalAlign: 'middle',
  234. backgroundImage:
  235. 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=")',
  236. backgroundRepeat: 'no-repeat, repeat-x',
  237. backgroundPosition: 'center center, top left',
  238. color: 'transparent',
  239. border: '1px solid black',
  240. borderRadius: '2px',
  241. },
  242. // align the lint icons with the line numbers
  243. '.cm-gutter-lint .cm-gutterElement': {
  244. padding: '0.3em',
  245. },
  246. // reset the default style for the lint gutter error marker, which uses :before
  247. '.cm-lint-marker-error:before': {
  248. content: 'normal',
  249. },
  250. // set a new icon for the lint gutter error marker
  251. '.cm-lint-marker-error': {
  252. content: svgUrl(
  253. `<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`
  254. ),
  255. },
  256. // set a new icon for the lint gutter warning marker
  257. '.cm-lint-marker-warning': {
  258. content: svgUrl(
  259. `<path fill="#FCC483" stroke="#DE8014" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`
  260. ),
  261. },
  262. })
  263. const themeCache = new Map<string, any>()
  264. const loadSelectedTheme = async (editorTheme: string) => {
  265. if (!editorTheme) {
  266. editorTheme = 'textmate' // use the default theme if unset
  267. }
  268. if (!themeCache.has(editorTheme)) {
  269. const { theme, highlightStyle, dark } = await import(
  270. /* webpackChunkName: "cm6-theme" */ `../themes/cm6/${editorTheme}.json`
  271. )
  272. const extension = [
  273. EditorView.theme(theme, { dark }),
  274. EditorView.theme(highlightStyle, { dark }),
  275. ]
  276. themeCache.set(editorTheme, extension)
  277. }
  278. return themeCache.get(editorTheme)
  279. }