theme.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. fontVariantNumeric: 'slashed-zero',
  172. },
  173. // remove the outline from the focused editor
  174. '&.cm-editor.cm-focused:not(:focus-visible)': {
  175. outline: 'none',
  176. },
  177. // override default styles for the search panel
  178. '.cm-panel.cm-search label': {
  179. display: 'inline-flex',
  180. alignItems: 'center',
  181. fontWeight: 'normal',
  182. },
  183. '.cm-selectionLayer': {
  184. zIndex: -10,
  185. },
  186. // remove the right-hand border from the gutter
  187. // ensure the gutter doesn't shrink
  188. '.cm-gutters': {
  189. borderRight: 'none',
  190. flexShrink: 0,
  191. },
  192. // style the gutter fold button
  193. // TODO: add a class to this element for easier theming
  194. '.cm-foldGutter .cm-gutterElement > span': {
  195. border: '1px solid transparent',
  196. borderRadius: '3px',
  197. display: 'inline-flex',
  198. flexDirection: 'column',
  199. justifyContent: 'center',
  200. color: 'rgba(109, 109, 109, 0.7)',
  201. },
  202. // reduce the padding around line numbers
  203. '.cm-lineNumbers .cm-gutterElement': {
  204. padding: '0',
  205. userSelect: 'none',
  206. },
  207. // make cursor visible with reduced opacity when the editor is not focused
  208. '&:not(.cm-focused) > .cm-scroller > .cm-cursorLayer .cm-cursor': {
  209. display: 'block',
  210. opacity: 0.2,
  211. },
  212. // make the cursor wider, and use the themed color
  213. '.cm-cursor, .cm-dropCursor': {
  214. borderWidth: '2px',
  215. marginLeft: '-1px', // half the border width
  216. borderLeftColor: 'inherit',
  217. },
  218. // remove border from hover tooltips (e.g. cursor highlights)
  219. '.cm-tooltip-hover': {
  220. border: 'none',
  221. },
  222. // use the same style as Ace for snippet fields
  223. '.cm-snippetField': {
  224. background: 'rgba(194, 193, 208, 0.09)',
  225. border: '1px dotted rgba(211, 208, 235, 0.62)',
  226. },
  227. // style the fold placeholder
  228. '.cm-foldPlaceholder': {
  229. boxSizing: 'border-box',
  230. display: 'inline-block',
  231. height: '11px',
  232. width: '1.8em',
  233. marginTop: '-2px',
  234. verticalAlign: 'middle',
  235. backgroundImage:
  236. 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=")',
  237. backgroundRepeat: 'no-repeat, repeat-x',
  238. backgroundPosition: 'center center, top left',
  239. color: 'transparent',
  240. border: '1px solid black',
  241. borderRadius: '2px',
  242. },
  243. // align the lint icons with the line numbers
  244. '.cm-gutter-lint .cm-gutterElement': {
  245. padding: '0.3em',
  246. },
  247. // reset the default style for the lint gutter error marker, which uses :before
  248. '.cm-lint-marker-error:before': {
  249. content: 'normal',
  250. },
  251. // set a new icon for the lint gutter error marker
  252. '.cm-lint-marker-error': {
  253. content: svgUrl(
  254. `<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`
  255. ),
  256. },
  257. // set a new icon for the lint gutter warning marker
  258. '.cm-lint-marker-warning': {
  259. content: svgUrl(
  260. `<path fill="#FCC483" stroke="#DE8014" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`
  261. ),
  262. },
  263. })
  264. const themeCache = new Map<string, any>()
  265. const loadSelectedTheme = async (editorTheme: string) => {
  266. if (!editorTheme) {
  267. editorTheme = 'textmate' // use the default theme if unset
  268. }
  269. if (!themeCache.has(editorTheme)) {
  270. const { theme, highlightStyle, dark } = await import(
  271. /* webpackChunkName: "cm6-theme" */ `../themes/cm6/${editorTheme}.json`
  272. )
  273. const extension = [
  274. EditorView.theme(theme, { dark }),
  275. EditorView.theme(highlightStyle, { dark }),
  276. ]
  277. themeCache.set(editorTheme, extension)
  278. }
  279. return themeCache.get(editorTheme)
  280. }