Field.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright 2021-2024 Avaiga Private Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5. * the License. You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10. * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11. * specific language governing permissions and limitations under the License.
  12. */
  13. import React, { lazy, useMemo } from "react";
  14. import Typography from "@mui/material/Typography";
  15. import Tooltip from "@mui/material/Tooltip";
  16. import { formatWSValue } from "../../utils";
  17. import { useClassNames, useDynamicProperty, useFormatConfig } from "../../utils/hooks";
  18. import { TaipyBaseProps, TaipyHoverProps } from "./utils";
  19. interface TaipyFieldProps extends TaipyBaseProps, TaipyHoverProps {
  20. dataType?: string;
  21. value: string | number;
  22. defaultValue?: string;
  23. format?: string;
  24. raw?: boolean;
  25. mode?: string;
  26. }
  27. const unsetWeightSx = { fontWeight: "unset" };
  28. const Markdown = lazy(() => import("react-markdown"));
  29. const Field = (props: TaipyFieldProps) => {
  30. const { id, dataType, format, defaultValue, raw } = props;
  31. const formatConfig = useFormatConfig();
  32. const className = useClassNames(props.libClassName, props.dynamicClassName, props.className);
  33. const hover = useDynamicProperty(props.hoverText, props.defaultHoverText, undefined);
  34. const mode = typeof props.mode === "string" ? props.mode.toLowerCase() : undefined;
  35. const value = useMemo(() => {
  36. return formatWSValue(
  37. props.value !== undefined ? props.value : defaultValue || "",
  38. dataType,
  39. format,
  40. formatConfig
  41. );
  42. }, [defaultValue, props.value, dataType, format, formatConfig]);
  43. return (
  44. <Tooltip title={hover || ""}>
  45. {mode == "pre" ? (
  46. <pre className={className} id={id}>{value}</pre>
  47. ) : mode == "markdown" || mode == "md" ? (
  48. <Markdown className={className}>{value}</Markdown>
  49. ) : raw || mode == "raw" ? (
  50. <span className={className} id={id}>
  51. {value}
  52. </span>
  53. ) : (
  54. <Typography className={className} id={id} component="span" sx={unsetWeightSx}>
  55. {value}
  56. </Typography>
  57. )}
  58. </Tooltip>
  59. );
  60. };
  61. export default Field;