@wordpress/core-data
Version:
Access to and manipulation of core WordPress entities.
70 lines (69 loc) • 2.28 kB
JavaScript
// packages/core-data/src/hooks/use-post-editor-awareness-state.ts
import { useEffect, useState } from "@wordpress/element";
import { getSyncManager } from "../sync.mjs";
var defaultState = {
activeCollaborators: [],
getAbsolutePositionIndex: () => null,
getDebugData: () => ({
doc: {},
clients: {},
collaboratorMap: {}
}),
isCurrentCollaboratorDisconnected: false
};
function getAwarenessState(awareness, newState) {
const activeCollaborators = newState ?? awareness.getCurrentState();
return {
activeCollaborators,
getAbsolutePositionIndex: (selection) => awareness.getAbsolutePositionIndex(selection),
getDebugData: () => awareness.getDebugData(),
isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false
};
}
function usePostEditorAwarenessState(postId, postType) {
const [state, setState] = useState(defaultState);
useEffect(() => {
if (null === postId || null === postType) {
setState(defaultState);
return;
}
const objectType = `postType/${postType}`;
const objectId = postId.toString();
const awareness = getSyncManager()?.getAwareness(
objectType,
objectId
);
if (!awareness) {
setState(defaultState);
return;
}
awareness.setUp();
setState(getAwarenessState(awareness));
const unsubscribe = awareness?.onStateChange(
(newState) => {
setState(getAwarenessState(awareness, newState));
}
);
return unsubscribe;
}, [postId, postType]);
return state;
}
function useActiveCollaborators(postId, postType) {
return usePostEditorAwarenessState(postId, postType).activeCollaborators;
}
function useGetAbsolutePositionIndex(postId, postType) {
return usePostEditorAwarenessState(postId, postType).getAbsolutePositionIndex;
}
function useGetDebugData(postId, postType) {
return usePostEditorAwarenessState(postId, postType).getDebugData();
}
function useIsDisconnected(postId, postType) {
return usePostEditorAwarenessState(postId, postType).isCurrentCollaboratorDisconnected;
}
export {
useActiveCollaborators,
useGetAbsolutePositionIndex,
useGetDebugData,
useIsDisconnected
};
//# sourceMappingURL=use-post-editor-awareness-state.mjs.map