All files / src MomentContext.tsx

100% Statements 36/36
100% Branches 7/7
100% Functions 12/12
100% Lines 36/36

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 17717x                                                               17x                       17x         17x         17x 102x     17x                                         16x 16x 144x 11x     16x           17x                           16x 16x   16x 16x                                                 16x 16x 10x   6x   6x     1x         16x 15x 9x   6x 5x 5x 4x       6x 1x 1x       16x 16x       16x            
import React, {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useRef
} from 'react';
import type {
  MomentProviderProps,
  MomentSettings,
  PoolEntry
} from './types';
 
/**
 * Controls registration of mounted `<Moment>` instances with a pooled timer.
 */
export interface PoolController {
  add: (entry: PoolEntry) => void;
  remove: (entry: PoolEntry) => void;
}
 
/**
 * Value exposed by `MomentContext`.
 */
export interface MomentContextValue {
  settings: MomentSettings;
  pool: PoolController | null;
}
 
/**
 * Built-in defaults used when no `<MomentProvider>` is mounted.
 */
export const defaultSettings: MomentSettings = {
  moment: null,
  locale: null,
  local: null,
  format: null,
  parse: null,
  filters: null,
  renderers: null,
  element: 'time',
  timezone: null
};
 
const defaultContextValue: MomentContextValue = {
  settings: defaultSettings,
  pool: null
};
 
export const MomentContext = createContext<MomentContextValue>(defaultContextValue);
 
/**
 * Returns the nearest `MomentContext` value.
 */
export function useMomentContext(): MomentContextValue {
  return useContext(MomentContext);
}
 
const settingKeys: (keyof MomentSettings)[] = [
  'moment',
  'locale',
  'local',
  'format',
  'parse',
  'filters',
  'renderers',
  'element',
  'timezone'
];
 
type MomentSettingsInput = Partial<Omit<MomentProviderProps, 'children' | 'pool' | 'interval'>>;
 
/**
 * Shallow-merges provider props onto parent settings.
 */
function mergeSettings(
  parent: MomentSettings,
  props: MomentSettingsInput
): MomentSettings {
  const merged = { ...parent };
  for (const key of settingKeys) {
    if (key in props && props[key] !== undefined) {
      (merged as Record<string, unknown>)[key] = props[key];
    }
  }
  return merged;
}
 
/**
 * Supplies default settings and optional pooled timing to descendant `<Moment>` instances.
 */
export function MomentProvider({
  children,
  pool: enablePool,
  interval = 60000,
  moment: momentProp,
  locale,
  local,
  format,
  parse,
  filters,
  renderers,
  element,
  timezone
}: MomentProviderProps): React.ReactElement {
  const parent = useMomentContext();
  const entriesRef = useRef<Set<PoolEntry>>(new Set());
 
  const settings = useMemo(
    () => mergeSettings(parent.settings, {
      moment: momentProp,
      locale,
      local,
      format,
      parse,
      filters,
      renderers,
      element,
      timezone
    }),
    [
      parent.settings,
      momentProp,
      locale,
      local,
      format,
      parse,
      filters,
      renderers,
      element,
      timezone
    ]
  );
 
  const pool = useMemo<PoolController | null>(() => {
    if (!enablePool) {
      return null;
    }
    return {
      add: (entry: PoolEntry) => {
        entriesRef.current.add(entry);
      },
      remove: (entry: PoolEntry) => {
        entriesRef.current.delete(entry);
      }
    };
  }, [enablePool]);
 
  useEffect(() => {
    if (!enablePool) {
      return undefined;
    }
    const timer = setInterval(() => {
      entriesRef.current.forEach((entry) => {
        if (entry.getProps().interval !== 0) {
          entry.update();
        }
      });
    }, interval);
    return () => {
      clearInterval(timer);
      entriesRef.current.clear();
    };
  }, [enablePool, interval]);
 
  const value = useMemo(
    () => ({ settings, pool }),
    [settings, pool]
  );
 
  return (
    <MomentContext.Provider value={value}>
      {children}
    </MomentContext.Provider>
  );
}