theme.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { EditorView } from '@codemirror/view'
  2. import { Compartment, TransactionSpec } from '@codemirror/state'
  3. export type FontFamily = 'monaco' | 'lucida' | 'opendyslexicmono'
  4. export type LineHeight = 'compact' | 'normal' | 'wide'
  5. export type Options = {
  6. fontSize: number
  7. fontFamily: FontFamily
  8. lineHeight: LineHeight
  9. }
  10. const optionsThemeConf = new Compartment()
  11. export const theme = (options: Options) => [
  12. baseTheme,
  13. optionsThemeConf.of(createThemeFromOptions(options)),
  14. ]
  15. export const lineHeights: Record<LineHeight, number> = {
  16. compact: 1.33,
  17. normal: 1.6,
  18. wide: 2,
  19. }
  20. const fontFamilies: Record<FontFamily, string[]> = {
  21. monaco: ['Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'monospace'],
  22. lucida: ['Lucida Console', 'Source Code Pro', 'monospace'],
  23. opendyslexicmono: ['OpenDyslexic Mono', 'monospace'],
  24. }
  25. const createThemeFromOptions = ({
  26. fontSize = 12,
  27. fontFamily = 'monaco',
  28. lineHeight = 'normal',
  29. }: Options) => {
  30. // Theme styles that depend on settings
  31. const fontFamilyValue = fontFamilies[fontFamily]?.join(', ')
  32. return [
  33. EditorView.editorAttributes.of({
  34. style: Object.entries({
  35. '--font-size': `${fontSize}px`,
  36. '--source-font-family': fontFamilyValue,
  37. '--line-height': lineHeights[lineHeight],
  38. })
  39. .map(([key, value]) => `${key}: ${value}`)
  40. .join(';'),
  41. }),
  42. // Set variables for tooltips, which are outside the editor
  43. // TODO: set these on document.body, or a new container element for the tooltips, without using a style mod
  44. EditorView.theme({
  45. '.cm-tooltip': {
  46. '--font-size': `${fontSize}px`,
  47. '--source-font-family': fontFamilyValue,
  48. },
  49. }),
  50. ]
  51. }
  52. const baseTheme = EditorView.theme({
  53. '.cm-content': {
  54. fontSize: 'var(--font-size)',
  55. fontFamily: 'var(--source-font-family)',
  56. lineHeight: 'var(--line-height)',
  57. color: '#000',
  58. },
  59. '.cm-gutters': {
  60. fontSize: 'var(--font-size)',
  61. lineHeight: 'var(--line-height)',
  62. },
  63. '.cm-lineNumbers': {
  64. fontFamily: 'var(--source-font-family)',
  65. },
  66. '.cm-tooltip': {
  67. // NOTE: fontFamily is not set here, as most tooltips use the UI font
  68. fontSize: 'var(--font-size)',
  69. },
  70. })
  71. export const setOptionsTheme = (options: Options): TransactionSpec => {
  72. return {
  73. effects: optionsThemeConf.reconfigure(createThemeFromOptions(options)),
  74. }
  75. }