@ai-stack/payloadcms
Version:
<p align="center"> <img alt="Payload AI Plugin" src="assets/payload-ai-intro.gif" width="100%" /> </p>
76 lines (75 loc) • 2.19 kB
JavaScript
const normalizeRoot = (root)=>{
if (!Array.isArray(root.children)) {
return null;
}
return {
...root,
type: 'root',
children: root.children,
direction: root.direction ?? null,
format: typeof root.format === 'string' ? root.format : '',
indent: typeof root.indent === 'number' ? root.indent : 0,
version: typeof root.version === 'number' ? root.version : 1
};
};
export const normalizeLexicalState = (state)=>{
const parsedState = typeof state === 'string' ? (()=>{
try {
return JSON.parse(state);
} catch {
return null;
}
})() : state;
if (!parsedState || typeof parsedState !== 'object' || !('root' in parsedState)) {
return null;
}
const root = parsedState.root;
if (!root || typeof root !== 'object') {
return null;
}
const normalizedRoot = normalizeRoot(root);
if (!normalizedRoot) {
return null;
}
return {
...parsedState,
root: normalizedRoot
};
};
export const setSafeLexicalState = (state, editorInstance, options = {})=>{
const { logErrors = true } = options;
if (!editorInstance) {
if (logErrors) {
console.error('Error setting editor state: missing Lexical editor instance', {
state
});
}
return false;
}
const normalizedState = normalizeLexicalState(state);
if (!normalizedState) {
if (logErrors) {
console.error('Error setting editor state: invalid Lexical state shape', {
state
});
}
return false;
}
try {
const editorState = editorInstance.parseEditorState(normalizedState);
if (editorState.isEmpty()) {
return false;
}
editorInstance.setEditorState(editorState);
return true;
} catch (error) {
if (logErrors) {
console.error('Error setting editor state: ', {
error,
state: normalizedState
});
}
return false;
}
};
//# sourceMappingURL=setSafeLexicalState.js.map