UNPKG

@wordpress/editor

Version:
104 lines (103 loc) 3.02 kB
// packages/editor/src/components/provider/use-entity-contains-snapshot.js import { useEffect, useLayoutEffect, useRef, useState } from "@wordpress/element"; import { useRegistry, useSelect } from "@wordpress/data"; import { store as coreStore, privateApis as coreDataPrivateApis } from "@wordpress/core-data"; import { store as editorStore } from "../../store/index.mjs"; import { unlock } from "../../lock-unlock.mjs"; var { entityContainsSnapshot } = unlock(coreDataPrivateApis); var SNAPSHOT_STATUS_SYNC_WAIT_MS = 3e3; function useEntityContainsSnapshot({ postType, postId, snapshot }) { const registry = useRegistry(); const [snapshotStatus, setSnapshotStatus] = useState("pending"); const isPendingRef = useRef(false); const [hasWaitExpired, setHasWaitExpired] = useState(false); const { syncStatus, isCollaborationEnabledForPost } = useSelect( (select) => { if (!snapshot) { return { syncStatus: void 0, isCollaborationEnabledForPost: false }; } const connectionStatus = unlock( select(coreStore) ).getEntitySyncConnectionStatus("postType", postType, postId); return { syncStatus: connectionStatus?.status, isCollaborationEnabledForPost: unlock( select(editorStore) ).isCollaborationEnabledForCurrentPost() }; }, [postType, postId, snapshot] ); useLayoutEffect(() => { const canDefer = snapshot && unlock( registry.select(editorStore) ).isCollaborationEnabledForCurrentPost(); if (!canDefer) { setSnapshotStatus("missing"); return; } isPendingRef.current = true; const timeoutId = setTimeout(() => { setHasWaitExpired(true); }, SNAPSHOT_STATUS_SYNC_WAIT_MS); return () => clearTimeout(timeoutId); }, []); useEffect(() => { if (!isPendingRef.current) { return; } const containsSnapshot = entityContainsSnapshot( "postType", postType, postId, snapshot ); const isCollaborationEnabled = unlock( registry.select(editorStore) ).isCollaborationEnabledForCurrentPost(); const connectionStatus = unlock( registry.select(coreStore) ).getEntitySyncConnectionStatus("postType", postType, postId); let nextSnapshotStatus; if (containsSnapshot) { nextSnapshotStatus = "present"; } else if (!isCollaborationEnabled) { nextSnapshotStatus = "missing"; } else if ("disconnected" === connectionStatus?.status) { nextSnapshotStatus = "missing"; } else if (hasWaitExpired) { nextSnapshotStatus = "missing"; } else { return; } isPendingRef.current = false; setSnapshotStatus(nextSnapshotStatus); }, [ syncStatus, hasWaitExpired, isCollaborationEnabledForPost, postType, postId ]); return snapshotStatus; } export { SNAPSHOT_STATUS_SYNC_WAIT_MS, useEntityContainsSnapshot as default }; //# sourceMappingURL=use-entity-contains-snapshot.mjs.map