imports.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """Import operations."""
  2. from __future__ import annotations
  3. from collections import defaultdict
  4. from typing import Dict, List, Optional
  5. from reflex.base import Base
  6. def merge_imports(*imports) -> ImportDict:
  7. """Merge multiple import dicts together.
  8. Args:
  9. *imports: The list of import dicts to merge.
  10. Returns:
  11. The merged import dicts.
  12. """
  13. all_imports = defaultdict(list)
  14. for import_dict in imports:
  15. for lib, fields in import_dict.items():
  16. all_imports[lib].extend(fields)
  17. return all_imports
  18. def collapse_imports(imports: ImportDict) -> ImportDict:
  19. """Remove all duplicate ImportVar within an ImportDict.
  20. Args:
  21. imports: The import dict to collapse.
  22. Returns:
  23. The collapsed import dict.
  24. """
  25. return {lib: list(set(import_vars)) for lib, import_vars in imports.items()}
  26. class ImportVar(Base):
  27. """An import var."""
  28. # The name of the import tag.
  29. tag: Optional[str]
  30. # whether the import is default or named.
  31. is_default: Optional[bool] = False
  32. # The tag alias.
  33. alias: Optional[str] = None
  34. # Whether this import need to install the associated lib
  35. install: Optional[bool] = True
  36. # whether this import should be rendered or not
  37. render: Optional[bool] = True
  38. # whether this import package should be added to transpilePackages in next.config.js
  39. # https://nextjs.org/docs/app/api-reference/next-config-js/transpilePackages
  40. transpile: Optional[bool] = False
  41. @property
  42. def name(self) -> str:
  43. """The name of the import.
  44. Returns:
  45. The name(tag name with alias) of tag.
  46. """
  47. if self.alias:
  48. return (
  49. self.alias if self.is_default else " as ".join([self.tag, self.alias]) # type: ignore
  50. )
  51. else:
  52. return self.tag or ""
  53. def __hash__(self) -> int:
  54. """Define a hash function for the import var.
  55. Returns:
  56. The hash of the var.
  57. """
  58. return hash(
  59. (
  60. self.tag,
  61. self.is_default,
  62. self.alias,
  63. self.install,
  64. self.render,
  65. self.transpile,
  66. )
  67. )
  68. ImportDict = Dict[str, List[ImportVar]]