@atlaskit/editor-common
Version:
A package that contains common classes and components for editor and renderer
48 lines (44 loc) • 2.19 kB
JavaScript
/* eslint-disable @atlaskit/platform/ensure-feature-flag-prefix */
export const defaultWordWrapState = false;
export const codeBlockWrappedStates = new WeakMap();
export const isCodeBlockWordWrapEnabled = codeBlockNode => {
const currentNodeWordWrapState = codeBlockWrappedStates.get(codeBlockNode);
return currentNodeWordWrapState !== undefined ? currentNodeWordWrapState : defaultWordWrapState;
};
/**
* Swap the old node key with the new node key in the wrapped states WeakMap.
*/
export const transferCodeBlockWrappedValue = (oldCodeBlockNode, newCodeBlockNode) => {
// Don't overwrite the value for the new node if it already exists.
// This can happen when a drag&drop is swapping nodes.
if (codeBlockWrappedStates.has(newCodeBlockNode)) {
return;
}
const previousValue = isCodeBlockWordWrapEnabled(oldCodeBlockNode);
codeBlockWrappedStates.set(newCodeBlockNode, previousValue);
codeBlockWrappedStates.delete(oldCodeBlockNode);
};
/**
* As the code block node is used as the wrapped state key, there is instances where the node will be destroyed & recreated and is no longer a valid key.
* In these instances, we must get the value from that old node and set it to the value of the new node.
* This function takes all the given nodes, finds their old nodes from the old state and updates these old node keys.
*/
export const updateCodeBlockWrappedStateNodeKeys = (newCodeBlockNodes, oldState) => {
newCodeBlockNodes.forEach(newCodeBlockNode => {
// Don't overwrite the value for the new node if it already exists.
// This can happen when a drag&drop is swapping nodes.
if (codeBlockWrappedStates.has(newCodeBlockNode.node)) {
return;
}
// Do not go out of range on the oldState doc. Happens on initial load.
if (oldState.doc.content.size <= newCodeBlockNode.pos) {
return;
}
const oldCodeBlockNode = oldState.doc.nodeAt(newCodeBlockNode.pos);
if (!oldCodeBlockNode || oldCodeBlockNode.type !== oldState.schema.nodes.codeBlock) {
return;
}
const previousValue = isCodeBlockWordWrapEnabled(oldCodeBlockNode);
codeBlockWrappedStates.set(newCodeBlockNode.node, previousValue);
});
};