theme.ts 8.7 KB

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