code.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. """A code component."""
  2. from typing import Dict, Literal, Optional, Union
  3. from reflex.components.component import Component
  4. from reflex.components.forms import Button
  5. from reflex.components.layout import Box
  6. from reflex.components.libs.chakra import (
  7. ChakraComponent,
  8. )
  9. from reflex.components.media import Icon
  10. from reflex.event import set_clipboard
  11. from reflex.style import Style
  12. from reflex.utils import format, imports
  13. from reflex.vars import ImportVar, Var
  14. LiteralCodeBlockTheme = Literal[
  15. "a11y-dark",
  16. "atom-dark",
  17. "cb",
  18. "coldark-cold",
  19. "coldark-dark",
  20. "coy",
  21. "coy-without-shadows",
  22. "darcula",
  23. "dark",
  24. "dracula",
  25. "duotone-dark",
  26. "duotone-earth",
  27. "duotone-forest",
  28. "duotone-light",
  29. "duotone-sea",
  30. "duotone-space",
  31. "funky",
  32. "ghcolors",
  33. "gruvbox-dark",
  34. "gruvbox-light",
  35. "holi-theme",
  36. "hopscotch",
  37. "light", # not present in react-syntax-highlighter styles
  38. "lucario",
  39. "material-dark",
  40. "material-light",
  41. "material-oceanic",
  42. "night-owl",
  43. "nord",
  44. "okaidia",
  45. "one-dark",
  46. "one-light",
  47. "pojoaque",
  48. "prism",
  49. "shades-of-purple",
  50. "solarized-dark-atom",
  51. "solarizedlight",
  52. "synthwave84",
  53. "tomorrow",
  54. "twilight",
  55. "vs",
  56. "vs-dark",
  57. "vsc-dark-plus",
  58. "xonokai",
  59. "z-touch",
  60. ]
  61. LiteralCodeLanguage = Literal[
  62. "abap",
  63. "abnf",
  64. "actionscript",
  65. "ada",
  66. "agda",
  67. "al",
  68. "antlr4",
  69. "apacheconf",
  70. "apex",
  71. "apl",
  72. "applescript",
  73. "aql",
  74. "arduino",
  75. "arff",
  76. "asciidoc",
  77. "asm6502",
  78. "asmatmel",
  79. "aspnet",
  80. "autohotkey",
  81. "autoit",
  82. "avisynth",
  83. "avro-idl",
  84. "bash",
  85. "basic",
  86. "batch",
  87. "bbcode",
  88. "bicep",
  89. "birb",
  90. "bison",
  91. "bnf",
  92. "brainfuck",
  93. "brightscript",
  94. "bro",
  95. "bsl",
  96. "c",
  97. "cfscript",
  98. "chaiscript",
  99. "cil",
  100. "clike",
  101. "clojure",
  102. "cmake",
  103. "cobol",
  104. "coffeescript",
  105. "concurnas",
  106. "coq",
  107. "core",
  108. "cpp",
  109. "crystal",
  110. "csharp",
  111. "cshtml",
  112. "csp",
  113. "css",
  114. "css-extras",
  115. "csv",
  116. "cypher",
  117. "d",
  118. "dart",
  119. "dataweave",
  120. "dax",
  121. "dhall",
  122. "diff",
  123. "django",
  124. "dns-zone-file",
  125. "docker",
  126. "dot",
  127. "ebnf",
  128. "editorconfig",
  129. "eiffel",
  130. "ejs",
  131. "elixir",
  132. "elm",
  133. "erb",
  134. "erlang",
  135. "etlua",
  136. "excel-formula",
  137. "factor",
  138. "false",
  139. "firestore-security-rules",
  140. "flow",
  141. "fortran",
  142. "fsharp",
  143. "ftl",
  144. "gap",
  145. "gcode",
  146. "gdscript",
  147. "gedcom",
  148. "gherkin",
  149. "git",
  150. "glsl",
  151. "gml",
  152. "gn",
  153. "go",
  154. "go-module",
  155. "graphql",
  156. "groovy",
  157. "haml",
  158. "handlebars",
  159. "haskell",
  160. "haxe",
  161. "hcl",
  162. "hlsl",
  163. "hoon",
  164. "hpkp",
  165. "hsts",
  166. "http",
  167. "ichigojam",
  168. "icon",
  169. "icu-message-format",
  170. "idris",
  171. "iecst",
  172. "ignore",
  173. "index",
  174. "inform7",
  175. "ini",
  176. "io",
  177. "j",
  178. "java",
  179. "javadoc",
  180. "javadoclike",
  181. "javascript",
  182. "javastacktrace",
  183. "jexl",
  184. "jolie",
  185. "jq",
  186. "js-extras",
  187. "js-templates",
  188. "jsdoc",
  189. "json",
  190. "json5",
  191. "jsonp",
  192. "jsstacktrace",
  193. "jsx",
  194. "julia",
  195. "keepalived",
  196. "keyman",
  197. "kotlin",
  198. "kumir",
  199. "kusto",
  200. "latex",
  201. "latte",
  202. "less",
  203. "lilypond",
  204. "liquid",
  205. "lisp",
  206. "livescript",
  207. "llvm",
  208. "log",
  209. "lolcode",
  210. "lua",
  211. "magma",
  212. "makefile",
  213. "markdown",
  214. "markup",
  215. "markup-templating",
  216. "matlab",
  217. "maxscript",
  218. "mel",
  219. "mermaid",
  220. "mizar",
  221. "mongodb",
  222. "monkey",
  223. "moonscript",
  224. "n1ql",
  225. "n4js",
  226. "nand2tetris-hdl",
  227. "naniscript",
  228. "nasm",
  229. "neon",
  230. "nevod",
  231. "nginx",
  232. "nim",
  233. "nix",
  234. "nsis",
  235. "objectivec",
  236. "ocaml",
  237. "opencl",
  238. "openqasm",
  239. "oz",
  240. "parigp",
  241. "parser",
  242. "pascal",
  243. "pascaligo",
  244. "pcaxis",
  245. "peoplecode",
  246. "perl",
  247. "php",
  248. "php-extras",
  249. "phpdoc",
  250. "plsql",
  251. "powerquery",
  252. "powershell",
  253. "processing",
  254. "prolog",
  255. "promql",
  256. "properties",
  257. "protobuf",
  258. "psl",
  259. "pug",
  260. "puppet",
  261. "pure",
  262. "purebasic",
  263. "purescript",
  264. "python",
  265. "q",
  266. "qml",
  267. "qore",
  268. "qsharp",
  269. "r",
  270. "racket",
  271. "reason",
  272. "regex",
  273. "rego",
  274. "renpy",
  275. "rest",
  276. "rip",
  277. "roboconf",
  278. "robotframework",
  279. "ruby",
  280. "rust",
  281. "sas",
  282. "sass",
  283. "scala",
  284. "scheme",
  285. "scss",
  286. "shell-session",
  287. "smali",
  288. "smalltalk",
  289. "smarty",
  290. "sml",
  291. "solidity",
  292. "solution-file",
  293. "soy",
  294. "sparql",
  295. "splunk-spl",
  296. "sqf",
  297. "sql",
  298. "squirrel",
  299. "stan",
  300. "stylus",
  301. "swift",
  302. "systemd",
  303. "t4-cs",
  304. "t4-templating",
  305. "t4-vb",
  306. "tap",
  307. "tcl",
  308. "textile",
  309. "toml",
  310. "tremor",
  311. "tsx",
  312. "tt2",
  313. "turtle",
  314. "twig",
  315. "typescript",
  316. "typoscript",
  317. "unrealscript",
  318. "uorazor",
  319. "uri",
  320. "v",
  321. "vala",
  322. "vbnet",
  323. "velocity",
  324. "verilog",
  325. "vhdl",
  326. "vim",
  327. "visual-basic",
  328. "warpscript",
  329. "wasm",
  330. "web-idl",
  331. "wiki",
  332. "wolfram",
  333. "wren",
  334. "xeora",
  335. "xml-doc",
  336. "xojo",
  337. "xquery",
  338. "yaml",
  339. "yang",
  340. "zig",
  341. ]
  342. class CodeBlock(Component):
  343. """A code block."""
  344. library = "react-syntax-highlighter@15.5.0"
  345. tag = "PrismAsyncLight"
  346. alias = "SyntaxHighlighter"
  347. # The theme to use ("light" or "dark").
  348. theme: Var[LiteralCodeBlockTheme] = "one-light" # type: ignore
  349. # The language to use.
  350. language: Var[LiteralCodeLanguage] = "python" # type: ignore
  351. # If this is enabled line numbers will be shown next to the code block.
  352. show_line_numbers: Var[bool]
  353. # The starting line number to use.
  354. starting_line_number: Var[int]
  355. # Whether to wrap long lines.
  356. wrap_long_lines: Var[bool]
  357. # A custom style for the code block.
  358. custom_style: Dict[str, str] = {}
  359. # Props passed down to the code tag.
  360. code_tag_props: Var[Dict[str, str]]
  361. def _get_imports(self) -> imports.ImportDict:
  362. merged_imports = super()._get_imports()
  363. merged_imports = imports.merge_imports(
  364. merged_imports,
  365. {
  366. f"react-syntax-highlighter/dist/cjs/styles/prism/{self.theme._var_name}": {
  367. ImportVar(
  368. tag=format.to_camel_case(self.theme._var_name),
  369. is_default=True,
  370. install=False,
  371. )
  372. }
  373. },
  374. )
  375. if (
  376. self.language is not None
  377. and self.language._var_name in LiteralCodeLanguage.__args__ # type: ignore
  378. ):
  379. merged_imports = imports.merge_imports(
  380. merged_imports,
  381. {
  382. f"react-syntax-highlighter/dist/cjs/languages/prism/{self.language._var_name}": {
  383. ImportVar(
  384. tag=format.to_camel_case(self.language._var_name),
  385. is_default=True,
  386. install=False,
  387. )
  388. }
  389. },
  390. )
  391. return merged_imports
  392. def _get_custom_code(self) -> Optional[str]:
  393. if (
  394. self.language is not None
  395. and self.language._var_name in LiteralCodeLanguage.__args__ # type: ignore
  396. ):
  397. return f"{self.alias}.registerLanguage('{self.language._var_name}', {format.to_camel_case(self.language._var_name)})"
  398. @classmethod
  399. def create(
  400. cls,
  401. *children,
  402. can_copy: Optional[bool] = False,
  403. copy_button: Optional[Union[bool, Component]] = None,
  404. **props,
  405. ):
  406. """Create a text component.
  407. Args:
  408. *children: The children of the component.
  409. can_copy: Whether a copy button should appears.
  410. copy_button: A custom copy button to override the default one.
  411. **props: The props to pass to the component.
  412. Returns:
  413. The text component.
  414. """
  415. # This component handles style in a special prop.
  416. custom_style = props.pop("custom_style", {})
  417. # react-syntax-highlighter doesnt have an explicit "light" or "dark" theme so we use one-light and one-dark
  418. # themes respectively to ensure code compatibility.
  419. if "theme" in props:
  420. props["theme"] = (
  421. "one-light"
  422. if props["theme"] == "light"
  423. else "one-dark"
  424. if props["theme"] == "dark"
  425. else props["theme"]
  426. )
  427. if can_copy:
  428. code = children[0]
  429. copy_button = ( # type: ignore
  430. copy_button
  431. if copy_button is not None
  432. else Button.create(
  433. Icon.create(tag="copy"),
  434. on_click=set_clipboard(code),
  435. style={"position": "absolute", "top": "0.5em", "right": "0"},
  436. )
  437. )
  438. custom_style.update({"padding": "1em 3.2em 1em 1em"})
  439. else:
  440. copy_button = None
  441. # Transfer style props to the custom style prop.
  442. for key, value in props.items():
  443. if key not in cls.get_fields():
  444. custom_style[key] = value
  445. # Create the component.
  446. code_block = super().create(
  447. *children,
  448. **props,
  449. custom_style=Style(custom_style),
  450. )
  451. if copy_button:
  452. return Box.create(code_block, copy_button, position="relative")
  453. else:
  454. return code_block
  455. def _add_style(self, style):
  456. self.custom_style.update(style) # type: ignore
  457. def _render(self):
  458. out = super()._render()
  459. out.add_props(
  460. style=Var.create(
  461. format.to_camel_case(self.theme._var_name), _var_is_local=False
  462. )
  463. ).remove_props("theme")
  464. return out
  465. class Code(ChakraComponent):
  466. """Used to display inline code."""
  467. tag = "Code"