UNPKG

@zendesk/react-measure-timing-hooks

Version:

react hooks for measuring time to interactive and time to render of components

81 lines 3.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ActionLogCache = void 0; const ActionLog_1 = require("./ActionLog"); const debounce_1 = require("./debounce"); class ActionLogCache { options; cache = new Map(); garbageCollectUnusedIdLater; makeWrapperRef(actionLog, initialId) { let ref = { activeId: initialId, ids: new Set([initialId]), actionLog, getCurrent: (id) => { const cachedRef = this.cache.get(id); const cachedActionLog = cachedRef?.actionLog; const activeRef = cachedRef ?? ref; if (cachedActionLog !== ref.actionLog) { // when ID changes, we transfer the state from the old actionLog to the new one // because of the edge case when the child with the new ID // is re-rendered *before* the parent beacon gets the new ID if (cachedActionLog && !ref.actionLog.wasImported) { cachedActionLog.importState(ref.actionLog); } else { activeRef.actionLog = ref.actionLog; ref.ids.forEach((refId) => { activeRef.ids.add(refId); }); } } this.cache.set(id, activeRef); activeRef.activeId = id; activeRef.ids.add(id); this.garbageCollectUnusedIdLater(activeRef); ref = activeRef; return activeRef.actionLog; }, }; return ref; } get(id) { const existingRef = this.cache.get(id); if (existingRef) return existingRef.getCurrent(id); return undefined; } makeGetOrCreateFn(id) { const existingRef = this.cache.get(id); if (existingRef) return existingRef.getCurrent; const actionLog = new ActionLog_1.ActionLog(this.options); const ref = this.makeWrapperRef(actionLog, id); actionLog.onDispose('gc', () => { ref.ids.forEach((refId) => { if (this.cache.get(refId)?.actionLog === actionLog) { this.cache.delete(refId); } }); }); this.cache.set(id, ref); return ref.getCurrent; } constructor({ garbageCollectMs, ...actionLogOptions }) { this.options = actionLogOptions; this.garbageCollectUnusedIdLater = (0, debounce_1.debounce)({ fn: (ref) => { ref.ids.forEach((id) => { if (id !== ref.activeId && this.cache.get(id) === ref) { this.cache.delete(id); ref.ids.delete(id); } }); }, debounceMs: garbageCollectMs, }); } } exports.ActionLogCache = ActionLogCache; //# sourceMappingURL=ActionLogCache.js.map