defaultContextMenuBuilder static method

Widget defaultContextMenuBuilder(
  1. BuildContext context,
  2. EditableTextState editableTextState
)

Implementation

static Widget defaultContextMenuBuilder(
  BuildContext context,
  EditableTextState editableTextState,
) {
  final l = ShadLocalizations.of(context);
  final textValue = editableTextState.textEditingValue;
  final selection = textValue.selection;
  final hasSelection = selection.isValid && !selection.isCollapsed;
  final buttonItems = editableTextState.contextMenuButtonItems.where(
    (item) {
      if (item.type == ContextMenuButtonType.cut ||
          item.type == ContextMenuButtonType.copy) {
        return hasSelection;
      }
      if (item.type == ContextMenuButtonType.selectAll) {
        return !(hasSelection &&
            selection.start == 0 &&
            selection.end == textValue.text.length);
      }
      return (_localizedLabel(item.type, l) ?? item.label ?? '').isNotEmpty;
    },
  ).toList();
  if (buttonItems.isEmpty) return const SizedBox.shrink();
  return FocusScope(
    // Prevent the context menu from stealing focus from the
    // EditableText, which would cause Flutter to dismiss the overlay
    // before the menu renders.
    canRequestFocus: false,
    child: ShadContextMenu(
      visible: true,
      anchor: ShadGlobalAnchor(
        editableTextState.contextMenuAnchors.primaryAnchor,
      ),
      items: [
        for (final item in buttonItems)
          ShadContextMenuItem(
            onTapDown: item.onPressed != null
                ? (_) {
                    item.onPressed!();
                    // After Select All, re-show the toolbar so the
                    // user can tap Copy/Cut on the updated selection.
                    if (item.type == ContextMenuButtonType.selectAll) {
                      editableTextState.showToolbar();
                    }
                  }
                : null,
            child: Text(
              _localizedLabel(item.type, l) ?? item.label ?? '',
            ),
          ),
      ],
      child: const SizedBox.shrink(),
    ),
  );
}