code.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. """A code component."""
  2. import re
  3. from typing import Dict, Literal, Optional, Union
  4. from reflex.components.chakra.forms import Button
  5. from reflex.components.chakra.layout import Box
  6. from reflex.components.chakra.media import Icon
  7. from reflex.components.component import Component
  8. from reflex.components.core.cond import color_mode_cond
  9. from reflex.event import set_clipboard
  10. from reflex.style import Style
  11. from reflex.utils import format, imports
  12. from reflex.utils.imports import ImportVar
  13. from reflex.vars import 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. # The code to display.
  352. code: Var[str]
  353. # If this is enabled line numbers will be shown next to the code block.
  354. show_line_numbers: Var[bool]
  355. # The starting line number to use.
  356. starting_line_number: Var[int]
  357. # Whether to wrap long lines.
  358. wrap_long_lines: Var[bool]
  359. # A custom style for the code block.
  360. custom_style: Dict[str, str] = {}
  361. # Props passed down to the code tag.
  362. code_tag_props: Var[Dict[str, str]]
  363. def _get_imports(self) -> imports.ImportDict:
  364. merged_imports = super()._get_imports()
  365. # Get all themes from a cond literal
  366. themes = re.findall(r"`(.*?)`", self.theme._var_name)
  367. if not themes:
  368. themes = [self.theme._var_name]
  369. merged_imports = imports.merge_imports(
  370. merged_imports,
  371. {
  372. f"react-syntax-highlighter/dist/cjs/styles/prism/{theme}": {
  373. ImportVar(
  374. tag=format.to_camel_case(theme),
  375. is_default=True,
  376. install=False,
  377. )
  378. }
  379. for theme in themes
  380. },
  381. )
  382. if (
  383. self.language is not None
  384. and self.language._var_name in LiteralCodeLanguage.__args__ # type: ignore
  385. ):
  386. merged_imports = imports.merge_imports(
  387. merged_imports,
  388. {
  389. f"react-syntax-highlighter/dist/cjs/languages/prism/{self.language._var_name}": {
  390. ImportVar(
  391. tag=format.to_camel_case(self.language._var_name),
  392. is_default=True,
  393. install=False,
  394. )
  395. }
  396. },
  397. )
  398. return merged_imports
  399. def _get_custom_code(self) -> Optional[str]:
  400. if (
  401. self.language is not None
  402. and self.language._var_name in LiteralCodeLanguage.__args__ # type: ignore
  403. ):
  404. return f"{self.alias}.registerLanguage('{self.language._var_name}', {format.to_camel_case(self.language._var_name)})"
  405. @classmethod
  406. def create(
  407. cls,
  408. *children,
  409. can_copy: Optional[bool] = False,
  410. copy_button: Optional[Union[bool, Component]] = None,
  411. **props,
  412. ):
  413. """Create a text component.
  414. Args:
  415. *children: The children of the component.
  416. can_copy: Whether a copy button should appears.
  417. copy_button: A custom copy button to override the default one.
  418. **props: The props to pass to the component.
  419. Returns:
  420. The text component.
  421. """
  422. # This component handles style in a special prop.
  423. custom_style = props.pop("custom_style", {})
  424. if "theme" not in props:
  425. # Default color scheme responds to global color mode.
  426. props["theme"] = color_mode_cond(light="one-light", dark="one-dark")
  427. # react-syntax-highlighter doesnt have an explicit "light" or "dark" theme so we use one-light and one-dark
  428. # themes respectively to ensure code compatibility.
  429. if "theme" in props and not isinstance(props["theme"], Var):
  430. props["theme"] = (
  431. "one-light"
  432. if props["theme"] == "light"
  433. else "one-dark"
  434. if props["theme"] == "dark"
  435. else props["theme"]
  436. )
  437. if can_copy:
  438. code = children[0]
  439. copy_button = ( # type: ignore
  440. copy_button
  441. if copy_button is not None
  442. else Button.create(
  443. Icon.create(tag="copy"),
  444. on_click=set_clipboard(code),
  445. style=Style({"position": "absolute", "top": "0.5em", "right": "0"}),
  446. )
  447. )
  448. custom_style.update({"padding": "1em 3.2em 1em 1em"})
  449. else:
  450. copy_button = None
  451. # Transfer style props to the custom style prop.
  452. for key, value in props.items():
  453. if key not in cls.get_fields():
  454. custom_style[key] = value
  455. # Carry the children (code) via props
  456. if children:
  457. props["code"] = children[0]
  458. if not isinstance(props["code"], Var):
  459. props["code"] = Var.create(props["code"], _var_is_string=True)
  460. # Create the component.
  461. code_block = super().create(
  462. **props,
  463. custom_style=Style(custom_style),
  464. )
  465. if copy_button:
  466. return Box.create(code_block, copy_button, position="relative")
  467. else:
  468. return code_block
  469. def _add_style(self, style):
  470. self.custom_style.update(style) # type: ignore
  471. def _render(self):
  472. out = super()._render()
  473. predicate, qmark, value = self.theme._var_name.partition("?")
  474. out.add_props(
  475. style=Var.create(
  476. format.to_camel_case(f"{predicate}{qmark}{value.replace('`', '')}"),
  477. _var_is_local=False,
  478. )
  479. ).remove_props("theme", "code")
  480. if self.code is not None:
  481. out.special_props.add(Var.create_safe(f"children={str(self.code)}"))
  482. return out