@wordpress/editor
Version:
Enhanced block editor for WordPress posts.
286 lines (285 loc) • 9.56 kB
JavaScript
// packages/editor/src/components/collaborators-overlay/use-block-highlighting.ts
import {
privateApis as coreDataPrivateApis
} from "@wordpress/core-data";
import { privateApis as blockEditorPrivateApis } from "@wordpress/block-editor";
import { useEffect, useRef, useState } from "@wordpress/element";
import { unlock } from "../../lock-unlock.mjs";
import { getAvatarBorderColor } from "../collab-sidebar/utils.mjs";
import { getAvatarUrl } from "./get-avatar-url.mjs";
import {
useDebouncedRecompute,
useRequestAnimationFrameRecompute
} from "./use-debounced-recompute.mjs";
import {
getNearestVisibleBlockAncestor,
getOrderedBlockRange
} from "./cursor-dom-utils.mjs";
import { resolveTargetElement } from "./compute-selection.mjs";
import { resolveStartPosition } from "./resolve-start-position.mjs";
import { getCollaboratorDisplayName } from "../../utils/get-collaborator-display-name.mjs";
var { useActiveCollaborators, useResolvedSelection } = unlock(coreDataPrivateApis);
var { isElementVisible } = unlock(blockEditorPrivateApis);
var { SelectionType } = unlock(coreDataPrivateApis);
function useBlockHighlighting(overlayElement, blockEditorDocument, postId, postType, delayMs) {
const highlightedBlockIds = useRef(/* @__PURE__ */ new Set());
const userStates = useActiveCollaborators(
postId ?? null,
postType ?? null
);
const resolveSelection = useResolvedSelection(
postId ?? null,
postType ?? null
);
const [highlights, setHighlights] = useState(
[]
);
const [recomputeToken, rerenderHighlightsAfterDelay] = useDebouncedRecompute(delayMs);
const [resizeToken, rerenderHighlightsOnResize] = useRequestAnimationFrameRecompute();
useEffect(() => {
if (!blockEditorDocument) {
setHighlights([]);
return;
}
const currentHighlightedIds = highlightedBlockIds.current;
const seen = /* @__PURE__ */ new Set();
const blocksToHighlight = userStates.filter((userState) => {
if (userState.isMe) {
return false;
}
const selType = userState.editorState?.selection?.type;
return selType === SelectionType.WholeBlock || selType === SelectionType.SelectionInMultipleBlocks || selType === SelectionType.Cursor || selType === SelectionType.SelectionInOneBlock;
}).flatMap((userState) => {
const selection = userState.editorState?.selection;
if (selection.type === SelectionType.WholeBlock) {
let localClientId;
try {
({ localClientId } = resolveSelection(selection));
} catch {
return [];
}
if (!localClientId) {
return [];
}
let blockId = localClientId;
const blockElement = getBlockElementById(
blockEditorDocument,
localClientId
);
if (blockElement && !isElementVisible(blockElement)) {
const container = getNearestVisibleBlockAncestor(blockElement);
const containerId = container?.getAttribute("data-block");
if (!containerId) {
return [];
}
blockId = containerId;
}
return [
{
blockId,
clientId: userState.clientId,
userId: userState.collaboratorInfo.id ?? userState.clientId,
color: getAvatarBorderColor(
userState.collaboratorInfo.id ?? userState.clientId
),
userName: getCollaboratorDisplayName(
userState.collaboratorInfo
),
avatarUrl: getAvatarUrl(
userState.collaboratorInfo.avatar_urls
),
alwaysOutline: true
}
];
}
if (selection.type === SelectionType.Cursor || selection.type === SelectionType.SelectionInOneBlock) {
const resolved = resolveStartPosition(
selection,
resolveSelection
);
if (!resolved?.localClientId) {
return [];
}
const targetElement = resolveTargetElement(
blockEditorDocument,
resolved
);
if (!targetElement || isElementVisible(targetElement)) {
return [];
}
const container = getNearestVisibleBlockAncestor(targetElement);
const containerId = container?.getAttribute("data-block");
if (!containerId) {
return [];
}
return [
{
blockId: containerId,
clientId: userState.clientId,
userId: userState.collaboratorInfo.id ?? userState.clientId,
color: getAvatarBorderColor(
userState.collaboratorInfo.id ?? userState.clientId
),
userName: getCollaboratorDisplayName(
userState.collaboratorInfo
),
avatarUrl: getAvatarUrl(
userState.collaboratorInfo.avatar_urls
),
alwaysOutline: true
}
];
}
const resolveEndpointId = (endpoint) => {
try {
return resolveSelection(endpoint).localClientId;
} catch {
return null;
}
};
const startId = resolveEndpointId(selection.startEndpoint);
const endId = resolveEndpointId(selection.endEndpoint);
if (!startId || !endId) {
return [];
}
const range = getOrderedBlockRange(
startId,
endId,
blockEditorDocument
);
if (!range) {
return [];
}
const { firstId, lastId, middleEls, sameContainer } = range;
const color = getAvatarBorderColor(
userState.collaboratorInfo.id ?? userState.clientId
);
const userName = getCollaboratorDisplayName(
userState.collaboratorInfo
);
const avatarUrl = getAvatarUrl(
userState.collaboratorInfo.avatar_urls
);
if (sameContainer) {
return [
{
blockId: firstId,
clientId: userState.clientId,
userId: userState.collaboratorInfo.id ?? userState.clientId,
color,
userName,
avatarUrl,
alwaysOutline: false
}
];
}
const intermediateIds = middleEls.map((el) => el.getAttribute("data-block")).filter((id) => Boolean(id));
return [firstId, ...intermediateIds, lastId].map(
(blockId) => ({
blockId,
clientId: userState.clientId,
userId: userState.collaboratorInfo.id ?? userState.clientId,
color,
userName,
avatarUrl,
alwaysOutline: false
})
);
}).filter((block) => {
if (seen.has(block.blockId)) {
return false;
}
seen.add(block.blockId);
return true;
});
const selectedBlockIds = new Set(
blocksToHighlight.map((block) => block.blockId)
);
for (const blockId of currentHighlightedIds) {
if (!selectedBlockIds.has(blockId)) {
const blockElement = getBlockElementById(
blockEditorDocument,
blockId
);
if (blockElement) {
blockElement.classList.remove("is-collaborator-selected");
blockElement.style.removeProperty(
"--collaborator-outline-color"
);
}
currentHighlightedIds.delete(blockId);
}
}
const results = [];
const overlayRect = overlayElement?.getBoundingClientRect() ?? null;
const usersWithAvatar = /* @__PURE__ */ new Set();
blocksToHighlight.forEach((block) => {
const { color, blockId, userName, avatarUrl } = block;
const blockElement = getBlockElementById(
blockEditorDocument,
blockId
);
if (!blockElement) {
return;
}
blockElement.classList.remove("is-collaborator-selected");
blockElement.style.removeProperty("--collaborator-outline-color");
currentHighlightedIds.delete(blockId);
if (!isElementVisible(blockElement)) {
return;
}
const isNonTextBlock = !blockElement.innerText?.trim();
if (block.alwaysOutline || isNonTextBlock) {
blockElement.classList.add("is-collaborator-selected");
blockElement.style.setProperty(
"--collaborator-outline-color",
color
);
currentHighlightedIds.add(blockId);
}
if (overlayRect && !usersWithAvatar.has(block.userId)) {
usersWithAvatar.add(block.userId);
const blockRect = blockElement.getBoundingClientRect();
results.push({
blockId,
clientId: block.clientId,
userName,
avatarUrl,
color,
x: blockRect.left - overlayRect.left,
y: blockRect.top - overlayRect.top
});
}
});
setHighlights(results);
return () => {
for (const blockId of currentHighlightedIds) {
const el = getBlockElementById(blockEditorDocument, blockId);
if (el) {
el.classList.remove("is-collaborator-selected");
el.style.removeProperty("--collaborator-outline-color");
}
}
currentHighlightedIds.clear();
};
}, [
userStates,
blockEditorDocument,
overlayElement,
recomputeToken,
resizeToken,
resolveSelection
]);
return {
highlights,
rerenderHighlightsAfterDelay,
rerenderHighlightsOnResize
};
}
var getBlockElementById = (blockEditorDocument, blockId) => {
return blockEditorDocument.querySelector(`[data-block="${blockId}"]`);
};
export {
useBlockHighlighting
};
//# sourceMappingURL=use-block-highlighting.mjs.map