@grafana/ui
Version:
Grafana Components Library
65 lines (60 loc) • 2.82 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactUse = require('react-use');
var TimeRangeContext = require('../TimeRangeContext.cjs');
var TimeSyncButton = require('../TimeSyncButton.cjs');
;
function useTimeSync(options) {
const { value, onChangeProp, isSyncedProp, initialIsSynced, timeSyncButtonProp } = options;
const timeRangeContext = 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 = React.useCallback(
(timeRange) => {
onChangeProp(timeRange);
if (usingTimeRangeContext && timeRangeContextSynced) {
timeRangeContextSyncFunc == null ? void 0 : timeRangeContextSyncFunc(timeRange);
}
},
[onChangeProp, usingTimeRangeContext, timeRangeContextSyncFunc, timeRangeContextSynced]
);
const prevValue = reactUse.usePrevious(value);
const prevSyncedValue = reactUse.usePrevious(timeRangeContext == null ? void 0 : timeRangeContext.syncedValue);
React.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__ */ jsxRuntime.jsx(
TimeSyncButton.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
};
}
exports.useTimeSync = useTimeSync;
//# sourceMappingURL=useTimeSync.cjs.map