visual-editor.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import importOverleafModules from '../../../../macros/import-overleaf-module.macro'
  2. import { isValidTeXFile } from '../../../main/is-valid-tex-file'
  3. import { getFileExtension } from './file'
  4. const visualEditorProviders = importOverleafModules('visualEditorProviders')
  5. const cmVisualEditorProviders: Array<{
  6. import: { getExtensions: (ext: string) => unknown }
  7. }> = importOverleafModules('sourceEditorVisualExtensions')
  8. /**
  9. * This currently covers LaTeX and Markdown. Other file
  10. * types (e.g. .bib) use module-provided visual editors that render their own
  11. * component instead, so they must NOT enable the CodeMirror visual extensions.
  12. */
  13. export function isCmVisualEditorAvailable(filename: string): boolean {
  14. if (isValidTeXFile(filename)) {
  15. return true
  16. }
  17. const extension = getFileExtension(filename)
  18. if (extension === null) {
  19. return false
  20. }
  21. for (const provider of cmVisualEditorProviders) {
  22. const extensions = provider.import.getExtensions(extension)
  23. if (
  24. Array.isArray(extensions) ? extensions.length > 0 : extensions != null
  25. ) {
  26. return true
  27. }
  28. }
  29. return false
  30. }
  31. /**
  32. * Whether any visual editor exists for the file, including module-provided
  33. * ones. Drives the editor toggle UI and the default editor mode for a file.
  34. */
  35. export function isVisualEditorAvailable(filename: string): boolean {
  36. if (isCmVisualEditorAvailable(filename)) {
  37. return true
  38. }
  39. // Visual editors provided by modules
  40. for (const provider of visualEditorProviders) {
  41. if (provider.import.isVisualEditorAvailable(filename)) {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. export function getVisualEditorComponent(filename: string) {
  48. for (const provider of visualEditorProviders) {
  49. const component = provider.import.getVisualEditorComponent(filename)
  50. if (component != null) {
  51. return component
  52. }
  53. }
  54. return null
  55. }
  56. export function getVisualEditorStorageKey(filename: string): string {
  57. for (const provider of visualEditorProviders) {
  58. if (provider.import.isVisualEditorAvailable(filename)) {
  59. const id = provider.import.id
  60. return id != null ? `editor.lastUsedMode.${id}` : 'editor.lastUsedMode'
  61. }
  62. }
  63. return 'editor.lastUsedMode'
  64. }