UNPKG

@grafana/ui

Version:
61 lines (58 loc) 2.68 kB
import { jsx } from 'react/jsx-runtime'; import { useCallback, useEffect } from 'react'; import { usePrevious } from 'react-use'; import { useTimeRangeContext } from '../TimeRangeContext.mjs'; import { TimeSyncButton } from '../TimeSyncButton.mjs'; "use strict"; function useTimeSync(options) { const { value, onChangeProp, isSyncedProp, initialIsSynced, timeSyncButtonProp } = options; const timeRangeContext = useTimeRangeContext(initialIsSynced && value ? value : void 0); const timeRangeContextSynced = timeRangeContext == null ? void 0 : timeRangeContext.synced; const timeRangeContextSyncedValue = timeRangeContext == null ? void 0 : timeRangeContext.syncedValue; const timeRangeContextSyncFunc = timeRangeContext == null ? void 0 : timeRangeContext.sync; const usingTimeRangeContext = Boolean(options.isSyncedProp === void 0 && timeRangeContext); const onChangeWithSync = useCallback( (timeRange) => { onChangeProp(timeRange); if (usingTimeRangeContext && timeRangeContextSynced) { timeRangeContextSyncFunc == null ? void 0 : timeRangeContextSyncFunc(timeRange); } }, [onChangeProp, usingTimeRangeContext, timeRangeContextSyncFunc, timeRangeContextSynced] ); const prevValue = usePrevious(value); const prevSyncedValue = usePrevious(timeRangeContext == null ? void 0 : timeRangeContext.syncedValue); useEffect(() => { if (usingTimeRangeContext && timeRangeContextSynced) { if (value !== prevValue && value !== timeRangeContextSyncedValue) { timeRangeContextSyncFunc == null ? void 0 : timeRangeContextSyncFunc(value); } else if (timeRangeContextSyncedValue && timeRangeContextSyncedValue !== prevSyncedValue && timeRangeContextSyncedValue !== value) { onChangeProp(timeRangeContextSyncedValue); } } }, [ usingTimeRangeContext, timeRangeContextSynced, timeRangeContextSyncedValue, timeRangeContextSyncFunc, prevSyncedValue, value, prevValue, onChangeProp ]); const isSynced = usingTimeRangeContext ? timeRangeContext == null ? void 0 : timeRangeContext.synced : isSyncedProp; const button = usingTimeRangeContext ? (timeRangeContext == null ? void 0 : timeRangeContext.syncPossible) && /* @__PURE__ */ jsx( TimeSyncButton, { isSynced: timeRangeContext == null ? void 0 : timeRangeContext.synced, onClick: () => (timeRangeContext == null ? void 0 : timeRangeContext.synced) ? timeRangeContext.unSync() : timeRangeContext.sync(value) } ) : timeSyncButtonProp; return { onChangeWithSync, isSynced, timeSyncButton: button }; } export { useTimeSync }; //# sourceMappingURL=useTimeSync.mjs.map