editor.py 7.2 KB

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