example_library.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. from taipy.gui.extension import Element, ElementLibrary, ElementProperty, PropertyType
  12. class ExampleLibrary(ElementLibrary):
  13. def __init__(self) -> None:
  14. # Initialize the set of visual elements for this extension library
  15. self.elements = {
  16. # A static element that displays its properties in a fraction
  17. "fraction": Element(
  18. "numerator",
  19. {
  20. "numerator": ElementProperty(PropertyType.number),
  21. "denominator": ElementProperty(PropertyType.number),
  22. },
  23. render_xhtml=ExampleLibrary._fraction_render,
  24. ),
  25. # A dynamic element that decorates its value
  26. "label": Element(
  27. "value",
  28. {"value": ElementProperty(PropertyType.dynamic_string)},
  29. # The name of the React component (ColoredLabel) that implements this custom
  30. # element, exported as ExampleLabel in front-end/src/index.ts
  31. react_component="ExampleLabel",
  32. ),
  33. "game_table": Element(
  34. "data",
  35. {
  36. "data": ElementProperty(PropertyType.data),
  37. },
  38. # The name of the React component (GameTable) that implements this custom
  39. # element, exported as GameTable in front-end/src/index.ts
  40. # react_component="GameTable",
  41. ),
  42. }
  43. # The implementation of the rendering for the "fraction" static element
  44. @staticmethod
  45. def _fraction_render(props: dict) -> str:
  46. # Get the property values
  47. numerator = props.get("numerator")
  48. denominator = props.get("denominator")
  49. # No denominator or numerator is 0: display the numerator
  50. if denominator is None or int(numerator) == 0: # type: ignore[arg-type]
  51. return f"<span>{numerator}</span>"
  52. # Denominator is zero: display infinity
  53. if int(denominator) == 0:
  54. return '<span style="font-size: 1.6em">&#8734;</span>'
  55. # 'Normal' case
  56. return f"<span><sup>{numerator}</sup>/<sub>{denominator}</sub></span>"
  57. def get_name(self) -> str:
  58. return "example"
  59. def get_elements(self) -> dict:
  60. return self.elements
  61. def get_scripts(self) -> list[str]:
  62. # Only one JavaScript bundle for this library.
  63. return ["front-end/dist/exampleLibrary.js"]