editor.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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.utils.imports import ImportVar
  10. from reflex.vars 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. class Editor(NoSSRComponent):
  58. """A Rich Text Editor component based on SunEditor.
  59. Not every JS prop is listed here (some are not easily usable from python),
  60. refer to the library docs for a complete list.
  61. """
  62. library = "suneditor-react"
  63. tag: str = "SunEditor"
  64. is_default: bool = True
  65. lib_dependencies: List[str] = ["suneditor"]
  66. # Language of the editor.
  67. # Alternatively to a string, a dict of your language can be passed to this prop.
  68. # Please refer to the library docs for this.
  69. # options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |
  70. # "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"
  71. # default : "en"
  72. lang: Var[
  73. Union[
  74. Literal[
  75. "en",
  76. "da",
  77. "de",
  78. "es",
  79. "fr",
  80. "ja",
  81. "ko",
  82. "pt_br",
  83. "ru",
  84. "zh_cn",
  85. "ro",
  86. "pl",
  87. "ckb",
  88. "lv",
  89. "se",
  90. "ua",
  91. "he",
  92. "it",
  93. ],
  94. dict,
  95. ]
  96. ]
  97. # This is used to set the HTML form name of the editor.
  98. # This means on HTML form submission,
  99. # it will be submitted together with contents of the editor by the name provided.
  100. name: Optional[Var[str]] = None
  101. # Sets the default value of the editor.
  102. # This is useful if you don't want the on_change method to be called on render.
  103. # If you want the on_change method to be called on render please use the set_contents prop
  104. default_value: Optional[Var[str]] = None
  105. # Sets the width of the editor.
  106. # px and percentage values are accepted, eg width="100%" or width="500px"
  107. # default: 100%
  108. width: Optional[Var[str]] = None
  109. # Sets the height of the editor.
  110. # px and percentage values are accepted, eg height="100%" or height="100px"
  111. height: Optional[Var[str]] = None
  112. # Sets the placeholder of the editor.
  113. placeholder: Optional[Var[str]] = None
  114. # Should the editor receive focus when initialized?
  115. auto_focus: Optional[Var[bool]] = None
  116. # Pass an EditorOptions instance to modify the behaviour of Editor even more.
  117. set_options: Optional[Var[Dict]] = None
  118. # Whether all SunEditor plugins should be loaded.
  119. # default: True
  120. set_all_plugins: Optional[Var[bool]] = None
  121. # Set the content of the editor.
  122. # Note: To set the initial contents of the editor
  123. # without calling the on_change event,
  124. # please use the default_value prop.
  125. # set_contents is used to set the contents of the editor programmatically.
  126. # You must be aware that, when the set_contents's prop changes,
  127. # the on_change event is triggered.
  128. set_contents: Optional[Var[str]] = None
  129. # Append editor content
  130. append_contents: Optional[Var[str]] = None
  131. # Sets the default style of the editor's edit area
  132. set_default_style: Optional[Var[str]] = None
  133. # Disable the editor
  134. # default: False
  135. disable: Optional[Var[bool]] = None
  136. # Hide the editor
  137. # default: False
  138. hide: Optional[Var[bool]] = None
  139. # Hide the editor toolbar
  140. # default: False
  141. hide_toolbar: Optional[Var[bool]] = None
  142. # Disable the editor toolbar
  143. # default: False
  144. disable_toolbar: Optional[Var[bool]] = None
  145. def _get_imports(self):
  146. imports = super()._get_imports()
  147. imports[""] = [
  148. ImportVar(tag="suneditor/dist/css/suneditor.min.css", install=False)
  149. ]
  150. return imports
  151. def get_event_triggers(self) -> Dict[str, Any]:
  152. """Get the event triggers that pass the component's value to the handler.
  153. Returns:
  154. A dict mapping the event trigger to the var that is passed to the handler.
  155. """
  156. return {
  157. **super().get_event_triggers(),
  158. EventTriggers.ON_CHANGE: lambda content: [content],
  159. "on_input": lambda _e: [_e],
  160. EventTriggers.ON_BLUR: lambda _e, content: [content],
  161. "on_load": lambda reload: [reload],
  162. "on_resize_editor": lambda height, prev_height: [height, prev_height],
  163. "on_copy": lambda _e, clipboard_data: [clipboard_data],
  164. "on_cut": lambda _e, clipboard_data: [clipboard_data],
  165. "on_paste": lambda _e, clean_data, max_char_count: [
  166. clean_data,
  167. max_char_count,
  168. ],
  169. "toggle_code_view": lambda is_code_view: [is_code_view],
  170. "toggle_full_screen": lambda is_full_screen: [is_full_screen],
  171. }
  172. @classmethod
  173. def create(cls, set_options: Optional[EditorOptions] = None, **props) -> Component:
  174. """Create an instance of Editor. No children allowed.
  175. Args:
  176. set_options(Optional[EditorOptions]): Configuration object to further configure the instance.
  177. **props: Any properties to be passed to the Editor
  178. Returns:
  179. An Editor instance.
  180. Raises:
  181. ValueError: If set_options is a state Var.
  182. """
  183. if set_options is not None:
  184. if isinstance(set_options, Var):
  185. raise ValueError("EditorOptions cannot be a state Var")
  186. props["set_options"] = {
  187. to_camel_case(k): v
  188. for k, v in set_options.model_dump().items()
  189. if v is not None
  190. }
  191. return super().create(*[], **props)