SelectionMenuItem.node constructor

SelectionMenuItem.node({
  1. required String getName(),
  2. required IconData iconData,
  3. required List<String> keywords,
  4. required Node nodeBuilder(
    1. EditorState editorState,
    2. BuildContext context
    ),
  5. bool insertBefore(
    1. EditorState editorState,
    2. Node node
    )?,
  6. bool replace(
    1. EditorState editorState,
    2. Node node
    )?,
  7. Selection? updateSelection(
    1. EditorState editorState,
    2. Path insertPath,
    3. bool replaced,
    4. bool insertedBefore,
    )?,
})

Creates a selection menu entry for inserting a Node. getName and iconData define the appearance within the selection menu.

The insert position is determined by the result of replace and insertBefore If no values are provided for replace and insertBefore the node is inserted after the current selection. replace takes precedence over insertBefore

updateSelection can be used to update the selection after the node has been inserted.

Implementation

factory SelectionMenuItem.node({
  required String Function() getName,
  required IconData iconData,
  required List<String> keywords,
  required Node Function(EditorState editorState, BuildContext context)
      nodeBuilder,
  bool Function(EditorState editorState, Node node)? insertBefore,
  bool Function(EditorState editorState, Node node)? replace,
  Selection? Function(
    EditorState editorState,
    Path insertPath,
    bool replaced,
    bool insertedBefore,
  )? updateSelection,
}) {
  return SelectionMenuItem(
    getName: getName,
    icon: (editorState, onSelected, style) => Icon(
      iconData,
      color: onSelected
          ? style.selectionMenuItemSelectedIconColor
          : style.selectionMenuItemIconColor,
      size: 18.0,
    ),
    keywords: keywords,
    handler: (editorState, _, context) {
      final selection = editorState.selection;
      if (selection == null || !selection.isCollapsed) {
        return;
      }
      final node = editorState.getNodeAtPath(selection.end.path);
      final delta = node?.delta;
      if (node == null || delta == null) {
        return;
      }
      final newNode = nodeBuilder(editorState, context);
      final transaction = editorState.transaction;
      final bReplace = replace?.call(editorState, node) ?? false;
      final bInsertBefore = insertBefore?.call(editorState, node) ?? false;

      //default insert after
      var path = node.path.next;
      if (bReplace) {
        path = node.path;
      } else if (bInsertBefore) {
        path = node.path;
      }

      transaction
        ..insertNode(path, newNode)
        ..afterSelection = updateSelection?.call(
              editorState,
              path,
              bReplace,
              bInsertBefore,
            ) ??
            selection;

      if (bReplace) {
        transaction.deleteNode(node);
      }

      editorState.apply(transaction);
    },
  );
}