custom_components.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. """CLI for creating custom components."""
  2. from __future__ import annotations
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. from collections import namedtuple
  8. from contextlib import contextmanager
  9. from pathlib import Path
  10. from typing import Any
  11. import click
  12. import httpx
  13. from reflex import constants
  14. from reflex.constants import CustomComponents
  15. from reflex.utils import console
  16. def set_loglevel(ctx: Any, self: Any, value: str | None):
  17. """Set the log level.
  18. Args:
  19. ctx: The click context.
  20. self: The click command.
  21. value: The log level to set.
  22. """
  23. if value is not None:
  24. loglevel = constants.LogLevel.from_string(value)
  25. console.set_log_level(loglevel)
  26. @click.group
  27. def custom_components_cli():
  28. """CLI for creating custom components."""
  29. pass
  30. loglevel_option = click.option(
  31. "--loglevel",
  32. type=click.Choice(
  33. [loglevel.value for loglevel in constants.LogLevel],
  34. case_sensitive=False,
  35. ),
  36. callback=set_loglevel,
  37. is_eager=True,
  38. expose_value=False,
  39. help="The log level to use.",
  40. )
  41. POST_CUSTOM_COMPONENTS_GALLERY_TIMEOUT = 15
  42. @contextmanager
  43. def set_directory(working_directory: str | Path):
  44. """Context manager that sets the working directory.
  45. Args:
  46. working_directory: The working directory to change to.
  47. Yields:
  48. Yield to the caller to perform operations in the working directory.
  49. """
  50. current_directory = Path.cwd()
  51. working_directory = Path(working_directory)
  52. try:
  53. os.chdir(working_directory)
  54. yield
  55. finally:
  56. os.chdir(current_directory)
  57. def _create_package_config(module_name: str, package_name: str):
  58. """Create a package config pyproject.toml file.
  59. Args:
  60. module_name: The name of the module.
  61. package_name: The name of the package typically constructed with `reflex-` prefix and a meaningful library name.
  62. """
  63. from reflex.compiler import templates
  64. pyproject = Path(CustomComponents.PYPROJECT_TOML)
  65. pyproject.write_text(
  66. templates.CUSTOM_COMPONENTS_PYPROJECT_TOML.render(
  67. module_name=module_name,
  68. package_name=package_name,
  69. reflex_version=constants.Reflex.VERSION,
  70. )
  71. )
  72. def _create_readme(module_name: str, package_name: str):
  73. """Create a package README file.
  74. Args:
  75. module_name: The name of the module.
  76. package_name: The name of the python package to be published.
  77. """
  78. from reflex.compiler import templates
  79. readme = Path(CustomComponents.PACKAGE_README)
  80. readme.write_text(
  81. templates.CUSTOM_COMPONENTS_README.render(
  82. module_name=module_name,
  83. package_name=package_name,
  84. )
  85. )
  86. def _write_source_and_init_py(
  87. custom_component_src_dir: Path,
  88. component_class_name: str,
  89. module_name: str,
  90. ):
  91. """Write the source code and init file from templates for the custom component.
  92. Args:
  93. custom_component_src_dir: The name of the custom component source directory.
  94. component_class_name: The name of the component class.
  95. module_name: The name of the module.
  96. """
  97. from reflex.compiler import templates
  98. module_path = custom_component_src_dir / f"{module_name}.py"
  99. module_path.write_text(
  100. templates.CUSTOM_COMPONENTS_SOURCE.render(
  101. component_class_name=component_class_name, module_name=module_name
  102. )
  103. )
  104. init_path = custom_component_src_dir / CustomComponents.INIT_FILE
  105. init_path.write_text(
  106. templates.CUSTOM_COMPONENTS_INIT_FILE.render(module_name=module_name)
  107. )
  108. def _populate_demo_app(name_variants: NameVariants):
  109. """Populate the demo app that imports the custom components.
  110. Args:
  111. name_variants: the tuple including various names such as package name, class name needed for the project.
  112. """
  113. from reflex import constants
  114. from reflex.compiler import templates
  115. from reflex.reflex import _init
  116. demo_app_dir = Path(name_variants.demo_app_dir)
  117. demo_app_name = name_variants.demo_app_name
  118. console.info(f"Creating app for testing: {demo_app_dir!s}")
  119. demo_app_dir.mkdir(exist_ok=True)
  120. with set_directory(demo_app_dir):
  121. # We start with the blank template as basis.
  122. _init(name=demo_app_name, template=constants.Templates.DEFAULT)
  123. # Then overwrite the app source file with the one we want for testing custom components.
  124. # This source file is rendered using jinja template file.
  125. demo_file = Path(f"{demo_app_name}/{demo_app_name}.py")
  126. demo_file.write_text(
  127. templates.CUSTOM_COMPONENTS_DEMO_APP.render(
  128. custom_component_module_dir=name_variants.custom_component_module_dir,
  129. module_name=name_variants.module_name,
  130. )
  131. )
  132. # Append the custom component package to the requirements.txt file.
  133. with Path(f"{constants.RequirementsTxt.FILE}").open(mode="a") as f:
  134. f.write(f"{name_variants.package_name}\n")
  135. def _get_default_library_name_parts() -> list[str]:
  136. """Get the default library name. Based on the current directory name, remove any non-alphanumeric characters.
  137. Raises:
  138. Exit: If the current directory name is not suitable for python projects, and we cannot find a valid library name based off it.
  139. Returns:
  140. The parts of default library name.
  141. """
  142. current_dir_name = Path.cwd().name
  143. cleaned_dir_name = re.sub("[^0-9a-zA-Z-_]+", "", current_dir_name).lower()
  144. parts = [part for part in re.split("-|_", cleaned_dir_name) if part]
  145. if parts and parts[0] == constants.Reflex.MODULE_NAME:
  146. # If the directory name already starts with "reflex", remove it from the parts.
  147. parts = parts[1:]
  148. # If no parts left, cannot find a valid library name, exit.
  149. if not parts:
  150. # The folder likely has a name not suitable for python paths.
  151. console.error(
  152. f"Based on current directory name {current_dir_name}, the library name is {constants.Reflex.MODULE_NAME}. This package already exists. Please use --library-name to specify a different name."
  153. )
  154. raise click.exceptions.Exit(code=1)
  155. if not parts:
  156. # The folder likely has a name not suitable for python paths.
  157. console.error(
  158. f"Could not find a valid library name based on the current directory: got {current_dir_name}."
  159. )
  160. raise click.exceptions.Exit(code=1)
  161. return parts
  162. NameVariants = namedtuple(
  163. "NameVariants",
  164. [
  165. "library_name",
  166. "component_class_name",
  167. "package_name",
  168. "module_name",
  169. "custom_component_module_dir",
  170. "demo_app_dir",
  171. "demo_app_name",
  172. ],
  173. )
  174. def _validate_library_name(library_name: str | None) -> NameVariants:
  175. """Validate the library name.
  176. Args:
  177. library_name: The name of the library if picked otherwise None.
  178. Raises:
  179. Exit: If the library name is not suitable for python projects.
  180. Returns:
  181. A tuple containing the various names such as package name, class name, etc., needed for the project.
  182. """
  183. if library_name is not None and not re.match(
  184. r"^[a-zA-Z-]+[a-zA-Z0-9-]*$", library_name
  185. ):
  186. console.error(
  187. f"Please use only alphanumeric characters or dashes: got {library_name}"
  188. )
  189. raise click.exceptions.Exit(code=1)
  190. # If not specified, use the current directory name to form the module name.
  191. name_parts = (
  192. [part.lower() for part in library_name.split("-")]
  193. if library_name
  194. else _get_default_library_name_parts()
  195. )
  196. if not library_name:
  197. library_name = "-".join(name_parts)
  198. # Component class name is the camel case.
  199. component_class_name = "".join([part.capitalize() for part in name_parts])
  200. console.debug(f"Component class name: {component_class_name}")
  201. # Package name is commonly kebab case.
  202. package_name = f"reflex-{library_name}"
  203. console.debug(f"Package name: {package_name}")
  204. # Module name is the snake case.
  205. module_name = "_".join(name_parts)
  206. custom_component_module_dir = Path(f"reflex_{module_name}")
  207. console.debug(f"Custom component source directory: {custom_component_module_dir}")
  208. # Use the same name for the directory and the app.
  209. demo_app_dir = demo_app_name = f"{module_name}_demo"
  210. console.debug(f"Demo app directory: {demo_app_dir}")
  211. return NameVariants(
  212. library_name=library_name,
  213. component_class_name=component_class_name,
  214. package_name=package_name,
  215. module_name=module_name,
  216. custom_component_module_dir=custom_component_module_dir,
  217. demo_app_dir=demo_app_dir,
  218. demo_app_name=demo_app_name,
  219. )
  220. def _populate_custom_component_project(name_variants: NameVariants):
  221. """Populate the custom component source directory. This includes the pyproject.toml, README.md, and the code template for the custom component.
  222. Args:
  223. name_variants: the tuple including various names such as package name, class name needed for the project.
  224. """
  225. console.info(
  226. f"Populating pyproject.toml with package name: {name_variants.package_name}"
  227. )
  228. # write pyproject.toml, README.md, etc.
  229. _create_package_config(
  230. module_name=name_variants.library_name, package_name=name_variants.package_name
  231. )
  232. _create_readme(
  233. module_name=name_variants.library_name, package_name=name_variants.package_name
  234. )
  235. console.info(
  236. f"Initializing the component directory: {CustomComponents.SRC_DIR / name_variants.custom_component_module_dir}"
  237. )
  238. CustomComponents.SRC_DIR.mkdir(exist_ok=True)
  239. with set_directory(CustomComponents.SRC_DIR):
  240. module_dir = Path(name_variants.custom_component_module_dir)
  241. module_dir.mkdir(exist_ok=True, parents=True)
  242. _write_source_and_init_py(
  243. custom_component_src_dir=module_dir,
  244. component_class_name=name_variants.component_class_name,
  245. module_name=name_variants.module_name,
  246. )
  247. @custom_components_cli.command(name="init")
  248. @click.option(
  249. "--library-name",
  250. default=None,
  251. help="The name of your library. On PyPI, package will be published as `reflex-{library-name}`.",
  252. )
  253. @click.option(
  254. "--install/--no-install",
  255. default=True,
  256. help="Whether to install package from this local custom component in editable mode.",
  257. )
  258. @loglevel_option
  259. def init(
  260. library_name: str | None,
  261. install: bool,
  262. ):
  263. """Initialize a custom component.
  264. Args:
  265. library_name: The name of the library.
  266. install: Whether to install package from this local custom component in editable mode.
  267. Raises:
  268. Exit: If the pyproject.toml already exists.
  269. """
  270. from reflex.utils import exec, prerequisites
  271. if CustomComponents.PYPROJECT_TOML.exists():
  272. console.error(f"A {CustomComponents.PYPROJECT_TOML} already exists. Aborting.")
  273. click.exceptions.Exit(code=1)
  274. # Show system info.
  275. exec.output_system_info()
  276. # Check the name follows the convention if picked.
  277. name_variants = _validate_library_name(library_name)
  278. console.rule(f"[bold]Initializing {name_variants.package_name} project")
  279. _populate_custom_component_project(name_variants)
  280. _populate_demo_app(name_variants)
  281. # Initialize the .gitignore.
  282. prerequisites.initialize_gitignore(
  283. gitignore_file=CustomComponents.FILE, files_to_ignore=CustomComponents.DEFAULTS
  284. )
  285. if install:
  286. package_name = name_variants.package_name
  287. console.rule(f"[bold]Installing {package_name} in editable mode.")
  288. if _pip_install_on_demand(package_name=".", install_args=["-e"]):
  289. console.info(f"Package {package_name} installed!")
  290. else:
  291. raise click.exceptions.Exit(code=1)
  292. console.print("[bold]Custom component initialized successfully!")
  293. console.rule("[bold]Project Summary")
  294. console.print(
  295. f"[ {CustomComponents.PACKAGE_README} ]: Package description. Please add usage examples."
  296. )
  297. console.print(
  298. f"[ {CustomComponents.PYPROJECT_TOML} ]: Project configuration file. Please fill in details such as your name, email, homepage URL."
  299. )
  300. console.print(
  301. f"[ {CustomComponents.SRC_DIR}/ ]: Custom component code template. Start by editing it with your component implementation."
  302. )
  303. console.print(
  304. f"[ {name_variants.demo_app_dir}/ ]: Demo App. Add more code to this app and test."
  305. )
  306. def _pip_install_on_demand(
  307. package_name: str,
  308. install_args: list[str] | None = None,
  309. ) -> bool:
  310. """Install a package on demand.
  311. Args:
  312. package_name: The name of the package.
  313. install_args: The additional arguments for the pip install command.
  314. Returns:
  315. True if the package is installed successfully, False otherwise.
  316. """
  317. install_args = install_args or []
  318. install_cmds = [
  319. sys.executable,
  320. "-m",
  321. "pip",
  322. "install",
  323. *install_args,
  324. package_name,
  325. ]
  326. console.debug(f"Install package: {' '.join(install_cmds)}")
  327. return _run_commands_in_subprocess(install_cmds)
  328. def _run_commands_in_subprocess(cmds: list[str]) -> bool:
  329. """Run commands in a subprocess.
  330. Args:
  331. cmds: The commands to run.
  332. Returns:
  333. True if the command runs successfully, False otherwise.
  334. """
  335. console.debug(f"Running command: {' '.join(cmds)}")
  336. try:
  337. result = subprocess.run(cmds, capture_output=True, text=True, check=True)
  338. except subprocess.CalledProcessError as cpe:
  339. console.error(cpe.stdout)
  340. console.error(cpe.stderr)
  341. return False
  342. else:
  343. console.debug(result.stdout)
  344. return True
  345. def _make_pyi_files():
  346. """Create pyi files for the custom component."""
  347. from reflex.utils.pyi_generator import PyiGenerator
  348. for top_level_dir in Path.cwd().iterdir():
  349. if not top_level_dir.is_dir() or top_level_dir.name.startswith("."):
  350. continue
  351. for dir, _, _ in top_level_dir.walk():
  352. if "__pycache__" in dir.name:
  353. continue
  354. PyiGenerator().scan_all([dir])
  355. def _run_build():
  356. """Run the build command.
  357. Raises:
  358. Exit: If the build fails.
  359. """
  360. console.print("Building custom component...")
  361. _make_pyi_files()
  362. cmds = [sys.executable, "-m", "build", "."]
  363. if _run_commands_in_subprocess(cmds):
  364. console.info("Custom component built successfully!")
  365. else:
  366. raise click.exceptions.Exit(code=1)
  367. @custom_components_cli.command(name="build")
  368. @loglevel_option
  369. def build():
  370. """Build a custom component. Must be run from the project root directory where the pyproject.toml is."""
  371. _run_build()
  372. @custom_components_cli.command(name="publish", deprecated=True)
  373. def publish():
  374. """Publish a custom component. This command is deprecated and will be removed in future releases.
  375. Raises:
  376. Exit: If the publish command fails.
  377. """
  378. console.error(
  379. "The publish command is deprecated. You can use `reflex component build` followed by `twine upload` or a similar publishing command to publish your custom component."
  380. "\nIf you want to share your custom component with the Reflex community, please use `reflex component share`."
  381. )
  382. raise click.exceptions.Exit(code=1)
  383. def _collect_details_for_gallery():
  384. """Helper to collect details on the custom component to be included in the gallery.
  385. Raises:
  386. Exit: If pyproject.toml file is ill-formed or the request to the backend services fails.
  387. """
  388. from reflex_cli.utils import hosting
  389. console.rule("[bold]Authentication with Reflex Services")
  390. console.print("First let's log in to Reflex backend services.")
  391. access_token, _ = hosting.authenticated_token()
  392. if not access_token:
  393. console.error(
  394. "Unable to authenticate with Reflex backend services. Make sure you are logged in."
  395. )
  396. raise click.exceptions.Exit(code=1)
  397. console.rule("[bold]Custom Component Information")
  398. params = {}
  399. package_name = console.ask("[ Published python package name ]")
  400. console.print(f"[ Custom component package name ] : {package_name}")
  401. params["package_name"] = package_name
  402. post_custom_components_gallery_endpoint = (
  403. "https://gallery-backend.reflex.dev/custom-components/gallery"
  404. )
  405. # Check the backend services if the user is allowed to update information of this package is already shared.
  406. try:
  407. console.debug(
  408. f"Checking if user has permission to upsert information for {package_name} by POST."
  409. )
  410. # Send a POST request to achieve two things at once:
  411. # 1. Check if the package is already shared by the user. If not, the backend will return 403.
  412. # 2. If this package is not shared before, this request records the package name in the backend.
  413. response = httpx.post(
  414. post_custom_components_gallery_endpoint,
  415. headers={"Authorization": f"Bearer {access_token}"},
  416. data=params,
  417. )
  418. if response.status_code == httpx.codes.FORBIDDEN:
  419. console.error(
  420. f"{package_name} is owned by another user. Unable to update the information for it."
  421. )
  422. raise click.exceptions.Exit(code=1)
  423. response.raise_for_status()
  424. except httpx.HTTPError as he:
  425. console.error(f"Unable to complete request due to {he}.")
  426. raise click.exceptions.Exit(code=1) from he
  427. files = []
  428. if (image_file_and_extension := _get_file_from_prompt_in_loop()) is not None:
  429. files.append(
  430. ("files", (image_file_and_extension[1], image_file_and_extension[0]))
  431. )
  432. demo_url = None
  433. while True:
  434. demo_url = (
  435. console.ask(
  436. "[ Full URL of deployed demo app, e.g. `https://my-app.reflex.run` ] (enter to skip)"
  437. )
  438. or None
  439. )
  440. if _validate_url_with_protocol_prefix(demo_url):
  441. break
  442. if demo_url:
  443. params["demo_url"] = demo_url
  444. # Now send the post request to Reflex backend services.
  445. try:
  446. console.debug(f"Sending custom component data: {params}")
  447. response = httpx.post(
  448. post_custom_components_gallery_endpoint,
  449. headers={"Authorization": f"Bearer {access_token}"},
  450. data=params,
  451. files=files,
  452. timeout=POST_CUSTOM_COMPONENTS_GALLERY_TIMEOUT,
  453. )
  454. response.raise_for_status()
  455. except httpx.HTTPError as he:
  456. console.error(f"Unable to complete request due to {he}.")
  457. raise click.exceptions.Exit(code=1) from he
  458. console.info("Custom component information successfully shared!")
  459. def _validate_url_with_protocol_prefix(url: str | None) -> bool:
  460. """Validate the URL with protocol prefix. Empty string is acceptable.
  461. Args:
  462. url: the URL string to check.
  463. Returns:
  464. Whether the entered URL is acceptable.
  465. """
  466. return not url or (url.startswith("http://") or url.startswith("https://"))
  467. def _get_file_from_prompt_in_loop() -> tuple[bytes, str] | None:
  468. image_file = file_extension = None
  469. while image_file is None:
  470. image_path_str = console.ask(
  471. "Upload a preview image of your demo app (enter to skip)"
  472. )
  473. if not image_path_str:
  474. break
  475. image_file_path = Path(image_path_str)
  476. if not image_file_path:
  477. break
  478. if not image_file_path.exists():
  479. console.error(f"File {image_file_path} does not exist.")
  480. continue
  481. file_extension = image_file_path.suffix
  482. try:
  483. image_file = image_file_path.read_bytes()
  484. except OSError as ose:
  485. console.error(f"Unable to read the {file_extension} file due to {ose}")
  486. raise click.exceptions.Exit(code=1) from ose
  487. else:
  488. return image_file, file_extension
  489. console.debug(f"File extension detected: {file_extension}")
  490. return None
  491. @custom_components_cli.command(name="share")
  492. @loglevel_option
  493. def share_more_detail():
  494. """Collect more details on the published package for gallery."""
  495. _collect_details_for_gallery()
  496. @custom_components_cli.command(name="install")
  497. @loglevel_option
  498. def install():
  499. """Install package from this local custom component in editable mode.
  500. Raises:
  501. Exit: If unable to install the current directory in editable mode.
  502. """
  503. if _pip_install_on_demand(package_name=".", install_args=["-e"]):
  504. console.info("Package installed successfully!")
  505. else:
  506. raise click.exceptions.Exit(code=1)