link function

ToolbarItem link({
  1. String uriHintText = 'google.com',
  2. String processInput(
    1. String
    )?,
  3. FormFieldValidator<String>? validator,
})

Toolbar item that applies a LinkAttribute. Shows a dialog with a text field for the url.

You can provide a custom processor to fix user input and a custom validator to control accepted (processed) user input.

The default processInput prepends http:// to the input if a protocol is missing. The default validator validates that the input is a valid URI.

Implementation

ToolbarItem link({
  String uriHintText = 'google.com',
  String Function(String)? processInput,
  FormFieldValidator<String>? validator,
}) {
  return ToolbarItem(
    title: const Icon(Icons.link),
    tooltip: 'Link',
    onPressed: (context, controller) async {
      final line = controller.focusedLine;
      if (line != null) {
        final c = line.controller;
        if (c.selection.isValid) {
          final canApply = !c.selection.isCollapsed ||
              c.getAppliedSpansWithType<LinkAttribute>().isNotEmpty;

          if (canApply) {
            final attrs = c.getAppliedSpansWithType<LinkAttribute>();
            final initialSpan = attrs.firstOrNull;
            final initialUri =
                (initialSpan?.attribute as LinkAttribute?)?.uri ?? '';
            final range = initialSpan?.range ?? c.selectionRange;
            // Show the dialog. Null means do nothing, empty string means remove.
            var link = await showDialog<String>(
              context: context,
              builder: (context) {
                return _LinkDialog(
                  text: initialUri,
                  hintText: uriHintText,
                  validator: validator,
                );
              },
            );

            if (link != null) {
              if (processInput != null) {
                link = processInput(link);
              } else if (!link.contains('://')) {
                link = 'http://$link';
              }

              var spans = c.spans;

              spans = spans.removeTypeFrom<LinkAttribute>(range);
              if (link.isNotEmpty) {
                final uri = Uri.parse(link);
                final attr = LinkAttribute(uri.toString());
                final span = AttributeSpan(attr, range.start, range.end);
                spans = spans.merge(span);
              }

              c.spans = spans;
            }
          }
        }
      }
    },
    builder: (context, controller, item) =>
        _LinkToolbarItem(controller: controller, toolbarItem: item),
  );
}