breakpoints.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Breakpoints utility."""
  2. from typing import Optional, Tuple
  3. breakpoints_values = ["30em", "48em", "62em", "80em", "96em"]
  4. def set_breakpoints(values: Tuple[str, str, str, str, str]):
  5. """Overwrite default breakpoint values.
  6. Args:
  7. values: CSS values in order defining the breakpoints of responsive layouts
  8. """
  9. breakpoints_values.clear()
  10. breakpoints_values.extend(values)
  11. class Breakpoints(dict):
  12. """A responsive styling helper."""
  13. @classmethod
  14. def create(
  15. cls,
  16. custom: Optional[dict] = None,
  17. initial=None,
  18. xs=None,
  19. sm=None,
  20. md=None,
  21. lg=None,
  22. xl=None,
  23. ):
  24. """Create a new instance of the helper. Only provide a custom component OR use named props.
  25. Args:
  26. custom: Custom mapping using CSS values or variables.
  27. initial: Styling when in the inital width
  28. xs: Styling when in the extra-small width
  29. sm: Styling when in the small width
  30. md: Styling when in the medium width
  31. lg: Styling when in the large width
  32. xl: Styling when in the extra-large width
  33. Raises:
  34. ValueError: If both custom and any other named parameters are provided.
  35. Returns:
  36. The responsive mapping.
  37. """
  38. thresholds = [initial, xs, sm, md, lg, xl]
  39. if custom is not None:
  40. if any((threshold is not None for threshold in thresholds)):
  41. raise ValueError("Named props cannot be used with custom thresholds")
  42. return Breakpoints(custom)
  43. else:
  44. return Breakpoints(
  45. {
  46. k: v
  47. for k, v in zip(["0px", *breakpoints_values], thresholds)
  48. if v is not None
  49. }
  50. )
  51. breakpoints = Breakpoints.create