editor-switch.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { ChangeEvent, FC, memo, useCallback } from 'react'
  2. import useScopeValue from '../../../shared/hooks/use-scope-value'
  3. import Tooltip from '../../../shared/components/tooltip'
  4. import { sendMB } from '../../../infrastructure/event-tracking'
  5. import isValidTeXFile from '../../../main/is-valid-tex-file'
  6. import { useTranslation } from 'react-i18next'
  7. function EditorSwitch() {
  8. const { t } = useTranslation()
  9. const [visual, setVisual] = useScopeValue('editor.showVisual')
  10. const [docName] = useScopeValue('editor.open_doc_name')
  11. const richTextAvailable = isValidTeXFile(docName)
  12. const handleChange = useCallback(
  13. event => {
  14. const editorType = event.target.value
  15. switch (editorType) {
  16. case 'cm6':
  17. setVisual(false)
  18. break
  19. case 'rich-text':
  20. setVisual(true)
  21. break
  22. }
  23. sendMB('editor-switch-change', { editorType })
  24. },
  25. [setVisual]
  26. )
  27. return (
  28. <div className="editor-toggle-switch">
  29. <fieldset className="toggle-switch">
  30. <legend className="sr-only">Editor mode.</legend>
  31. <input
  32. type="radio"
  33. name="editor"
  34. value="cm6"
  35. id="editor-switch-cm6"
  36. className="toggle-switch-input"
  37. checked={!richTextAvailable || !visual}
  38. onChange={handleChange}
  39. />
  40. <label htmlFor="editor-switch-cm6" className="toggle-switch-label">
  41. <span>{t('code_editor')}</span>
  42. </label>
  43. <RichTextToggle
  44. checked={richTextAvailable && visual}
  45. disabled={!richTextAvailable}
  46. handleChange={handleChange}
  47. />
  48. </fieldset>
  49. </div>
  50. )
  51. }
  52. const RichTextToggle: FC<{
  53. checked: boolean
  54. disabled: boolean
  55. handleChange: (event: ChangeEvent<HTMLInputElement>) => void
  56. }> = ({ checked, disabled, handleChange }) => {
  57. const { t } = useTranslation()
  58. const toggle = (
  59. <span>
  60. <input
  61. type="radio"
  62. name="editor"
  63. value="rich-text"
  64. id="editor-switch-rich-text"
  65. className="toggle-switch-input"
  66. checked={checked}
  67. onChange={handleChange}
  68. disabled={disabled}
  69. />
  70. <label htmlFor="editor-switch-rich-text" className="toggle-switch-label">
  71. <span>{t('visual_editor')}</span>
  72. </label>
  73. </span>
  74. )
  75. if (disabled) {
  76. return (
  77. <Tooltip
  78. description={t('visual_editor_is_only_available_for_tex_files')}
  79. id="rich-text-toggle-tooltip"
  80. overlayProps={{ placement: 'bottom' }}
  81. tooltipProps={{ className: 'tooltip-wide' }}
  82. >
  83. {toggle}
  84. </Tooltip>
  85. )
  86. }
  87. return toggle
  88. }
  89. export default memo(EditorSwitch)