import { Editor, Transforms } from 'slate';
import { CUSTOM_ELEMENT_TYPES } from './constants';
export function isMentionElement(type) {
  return type === CUSTOM_ELEMENT_TYPES.mention;
}
export function getMentionsCount(nodes) {
  return nodes.reduce((total, {
    children
  }) => {
    return total + children.reduce((subTotal, {
      type
    }) => {
      return isMentionElement(type) ? subTotal + 1 : subTotal;
    }, 0);
  }, 0);
}

/** This function synchronises slate editor chidren with value prop.
 * Setting value directly (editor.children = value) breaks UI when keyboard is used
 * https://docs.slatejs.org/walkthroughs/06-saving-to-a-database
 */
export function resetNodes(editor, nodes) {
  const children = [...editor.children];
  children.forEach(node => editor.apply({
    type: 'remove_node',
    path: [0],
    node
  }));
  nodes.forEach((node, i) => editor.apply({
    type: 'insert_node',
    path: [i],
    node
  }));
  const point = Editor.end(editor, []);
  Transforms.select(editor, point);
}