All files / src/hooks useMomentContent.ts

100% Statements 13/13
100% Branches 5/5
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 433x     3x 3x                                     3x     9x   9x 3x     9x 9x 9x   9x 1x     9x    
import { useMomentContext } from '../MomentContext';
import type moment from 'moment';
import type { MomentContent, MomentProps } from '../types';
import { getContent, getDatetime, getTitle } from '../utils';
import { useMomentUpdate } from './useMomentUpdate';
 
/**
 * Props accepted by `useMomentContent` (same as `<Moment>` minus DOM `element`).
 */
export type UseMomentContentProps = Omit<MomentProps, 'element'>;
 
/**
 * Value returned by `useMomentContent`.
 */
export interface UseMomentContentResult {
  content: MomentContent;
  datetime: moment.Moment;
  title?: string;
}
 
/**
 * Formats a date using the same pipeline as `<Moment>`, with optional auto-updates.
 */
export function useMomentContent(
  props: UseMomentContentProps
): UseMomentContentResult {
  const { settings } = useMomentContext();
 
  useMomentUpdate(props, (currentProps) => {
    currentProps.onChange?.(getContent(currentProps, settings));
  });
 
  const datetime = getDatetime(props, settings);
  const content = getContent(props, settings);
  const result: UseMomentContentResult = { content, datetime };
 
  if (props.withTitle) {
    result.title = getTitle(props, settings);
  }
 
  return result;
}