Source

molecules/date/updated/date-updated.tsx

  1. import React from "react";
  2. import get from "lodash.get";
  3. import { DateTime } from "../../../atoms";
  4. import { withStoryAndConfig } from "../../../context";
  5. import formatDistanceToNow from "date-fns/formatDistanceToNow";
  6. import { utcToZonedTime } from "date-fns-tz";
  7. import { DateUpdatedTypes } from "./types";
  8. export const DateUpdatedBase = ({ story, prepend, config }: DateUpdatedTypes) => {
  9. const updatedAt = story["last-published-at"];
  10. if (!updatedAt) return null;
  11. const timeZonedTime = utcToZonedTime(updatedAt, "Asia/Kolkata");
  12. let humanizedString = formatDistanceToNow(timeZonedTime, { addSuffix: true });
  13. const languageCode = get(config, ["publisherConfig", "language", "ietf-code"]);
  14. const localizationOpts = get(config, ["opts", "featureConfig", "localization"], {});
  15. const timeZone = get(config, ["additionalConfig", "general", "timeZone"], "Asia/Kolkata");
  16. if ("useLocaleDateStampOnGenericStory" in localizationOpts) {
  17. const useLocale =
  18. typeof localizationOpts.useLocaleDateStampOnGenericStory === "function"
  19. ? localizationOpts.useLocaleDateStampOnGenericStory(config)
  20. : localizationOpts.useLocaleDateStampOnGenericStory;
  21. if (useLocale) {
  22. humanizedString = new Date(updatedAt).toLocaleDateString(languageCode, {
  23. year: "numeric",
  24. month: "long",
  25. day: "numeric",
  26. hour: "numeric",
  27. minute: "numeric",
  28. hour12: true,
  29. timeZone: timeZone
  30. });
  31. }
  32. }
  33. return <DateTime formattedDate={humanizedString} prepend={prepend} />;
  34. };
  35. /**
  36. * DateUpdated Component - uses library "date-fns-tz" to format the story updated date. Uses the "DateTime" atomic component internally
  37. *
  38. * ```js
  39. * <DateUpdated prepend="Updated: " />
  40. * ```
  41. *
  42. * @param {Object} props Object containing parameters passed to the render prop
  43. * @param {String} props.prepend Optional. String that is prepended to the date
  44. *
  45. * @category Molecules
  46. * @component
  47. */
  48. export const DateUpdated = withStoryAndConfig(DateUpdatedBase);