editor.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. """A Rich Text Editor based on SunEditor."""
  2. from __future__ import annotations
  3. import enum
  4. from typing import Any, Dict, List, Literal, Optional, Tuple, Union
  5. from reflex.base import Base
  6. from reflex.components.component import Component, NoSSRComponent
  7. from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec
  8. from reflex.utils.format import to_camel_case
  9. from reflex.utils.imports import ImportDict, ImportVar
  10. from reflex.vars.base import Var
  11. class EditorButtonList(list, enum.Enum):
  12. """List enum that provides three predefined button lists."""
  13. BASIC = [
  14. ["font", "fontSize"],
  15. ["fontColor"],
  16. ["horizontalRule"],
  17. ["link", "image"],
  18. ]
  19. FORMATTING = [
  20. ["undo", "redo"],
  21. ["bold", "underline", "italic", "strike", "subscript", "superscript"],
  22. ["removeFormat"],
  23. ["outdent", "indent"],
  24. ["fullScreen", "showBlocks", "codeView"],
  25. ["preview", "print"],
  26. ]
  27. COMPLEX = [
  28. ["undo", "redo"],
  29. ["font", "fontSize", "formatBlock"],
  30. ["bold", "underline", "italic", "strike", "subscript", "superscript"],
  31. ["removeFormat"],
  32. "/",
  33. ["fontColor", "hiliteColor"],
  34. ["outdent", "indent"],
  35. ["align", "horizontalRule", "list", "table"],
  36. ["link", "image", "video"],
  37. ["fullScreen", "showBlocks", "codeView"],
  38. ["preview", "print"],
  39. ["save", "template"],
  40. ]
  41. class EditorOptions(Base):
  42. """Some of the additional options to configure the Editor.
  43. Complete list of options found here:
  44. https://github.com/JiHong88/SunEditor/blob/master/README.md#options.
  45. """
  46. # Specifies default tag name of the editor.
  47. # default: 'p' {String}
  48. default_tag: Optional[str] = None
  49. # The mode of the editor ('classic', 'inline', 'balloon', 'balloon-always').
  50. # default: 'classic' {String}
  51. mode: Optional[str] = None
  52. # If true, the editor is set to RTL(Right To Left) mode.
  53. # default: false {Boolean}
  54. rtl: Optional[bool] = None
  55. # List of buttons to use in the toolbar.
  56. button_list: Optional[List[Union[List[str], str]]]
  57. def on_blur_spec(e: Var, content: Var[str]) -> Tuple[Var[str]]:
  58. """A helper function to specify the on_blur event handler.
  59. Args:
  60. e: The event.
  61. content: The content of the editor.
  62. Returns:
  63. A tuple containing the content of the editor.
  64. """
  65. return (content,)
  66. def on_paste_spec(
  67. e: Var, clean_data: Var[str], max_char_count: Var[bool]
  68. ) -> Tuple[Var[str], Var[bool]]:
  69. """A helper function to specify the on_paste event handler.
  70. Args:
  71. e: The event.
  72. clean_data: The clean data.
  73. max_char_count: The maximum character count.
  74. Returns:
  75. A tuple containing the clean data and the maximum character count.
  76. """
  77. return (clean_data, max_char_count)
  78. class Editor(NoSSRComponent):
  79. """A Rich Text Editor component based on SunEditor.
  80. Not every JS prop is listed here (some are not easily usable from python),
  81. refer to the library docs for a complete list.
  82. """
  83. library = "suneditor-react"
  84. tag = "SunEditor"
  85. is_default = True
  86. lib_dependencies: List[str] = ["suneditor"]
  87. # Language of the editor.
  88. # Alternatively to a string, a dict of your language can be passed to this prop.
  89. # Please refer to the library docs for this.
  90. # options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |
  91. # "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"
  92. # default: "en".
  93. lang: Var[
  94. Union[
  95. Literal[
  96. "en",
  97. "da",
  98. "de",
  99. "es",
  100. "fr",
  101. "ja",
  102. "ko",
  103. "pt_br",
  104. "ru",
  105. "zh_cn",
  106. "ro",
  107. "pl",
  108. "ckb",
  109. "lv",
  110. "se",
  111. "ua",
  112. "he",
  113. "it",
  114. ],
  115. dict,
  116. ]
  117. ]
  118. # This is used to set the HTML form name of the editor.
  119. # This means on HTML form submission,
  120. # it will be submitted together with contents of the editor by the name provided.
  121. name: Var[str]
  122. # Sets the default value of the editor.
  123. # This is useful if you don't want the on_change method to be called on render.
  124. # If you want the on_change method to be called on render please use the set_contents prop
  125. default_value: Var[str]
  126. # Sets the width of the editor.
  127. # px and percentage values are accepted, eg width="100%" or width="500px"
  128. # default: 100%
  129. width: Var[str]
  130. # Sets the height of the editor.
  131. # px and percentage values are accepted, eg height="100%" or height="100px"
  132. height: Var[str]
  133. # Sets the placeholder of the editor.
  134. placeholder: Var[str]
  135. # Should the editor receive focus when initialized?
  136. auto_focus: Var[bool]
  137. # Pass an EditorOptions instance to modify the behaviour of Editor even more.
  138. set_options: Var[Dict]
  139. # Whether all SunEditor plugins should be loaded.
  140. # default: True.
  141. set_all_plugins: Var[bool]
  142. # Set the content of the editor.
  143. # Note: To set the initial contents of the editor
  144. # without calling the on_change event,
  145. # please use the default_value prop.
  146. # set_contents is used to set the contents of the editor programmatically.
  147. # You must be aware that, when the set_contents's prop changes,
  148. # the on_change event is triggered.
  149. set_contents: Var[str]
  150. # Append editor content
  151. append_contents: Var[str]
  152. # Sets the default style of the editor's edit area
  153. set_default_style: Var[str]
  154. # Disable the editor
  155. # default: False.
  156. disable: Var[bool]
  157. # Hide the editor
  158. # default: False.
  159. hide: Var[bool]
  160. # Hide the editor toolbar
  161. # default: False.
  162. hide_toolbar: Var[bool]
  163. # Disable the editor toolbar
  164. # default: False.
  165. disable_toolbar: Var[bool]
  166. # Fired when the editor content changes.
  167. on_change: EventHandler[passthrough_event_spec(str)]
  168. # Fired when the something is inputted in the editor.
  169. on_input: EventHandler[no_args_event_spec]
  170. # Fired when the editor loses focus.
  171. on_blur: EventHandler[on_blur_spec]
  172. # Fired when the editor is loaded.
  173. on_load: EventHandler[passthrough_event_spec(bool)]
  174. # Fired when the editor content is copied.
  175. on_copy: EventHandler[no_args_event_spec]
  176. # Fired when the editor content is cut.
  177. on_cut: EventHandler[no_args_event_spec]
  178. # Fired when the editor content is pasted.
  179. on_paste: EventHandler[on_paste_spec]
  180. # Fired when the code view is toggled.
  181. toggle_code_view: EventHandler[passthrough_event_spec(bool)]
  182. # Fired when the full screen mode is toggled.
  183. toggle_full_screen: EventHandler[passthrough_event_spec(bool)]
  184. def add_imports(self) -> ImportDict:
  185. """Add imports for the Editor component.
  186. Returns:
  187. The import dict.
  188. """
  189. return {
  190. "": ImportVar(tag="suneditor/dist/css/suneditor.min.css", install=False)
  191. }
  192. @classmethod
  193. def create(
  194. cls, set_options: Optional[EditorOptions] = None, **props: Any
  195. ) -> Component:
  196. """Create an instance of Editor. No children allowed.
  197. Args:
  198. set_options: Configuration object to further configure the instance.
  199. **props: Any properties to be passed to the Editor
  200. Returns:
  201. An Editor instance.
  202. Raises:
  203. ValueError: If set_options is a state Var.
  204. """
  205. if set_options is not None:
  206. if isinstance(set_options, Var):
  207. raise ValueError("EditorOptions cannot be a state Var")
  208. props["set_options"] = {
  209. to_camel_case(k): v
  210. for k, v in set_options.dict().items()
  211. if v is not None
  212. }
  213. return super().create(*[], **props)