insertLink method

void insertLink(
  1. String url,
  2. String displayText, {
  3. int? blockIndex,
  4. TextSelection? selection,
})

Inserts or applies a hyperlink. If selection is a non-empty range, applies the link to the selection, or replaces the selected text if displayText was modified. If selection is collapsed, inserts a new link span at the cursor.

Implementation

void insertLink(
  String url,
  String displayText, {
  int? blockIndex,
  TextSelection? selection,
}) {
  if (displayText.isEmpty) return;

  final effectiveBlockIndex =
      blockIndex ?? _editorWidgetState?.focusedBlockIndex ?? 0;
  final effectiveSelection =
      selection ?? _editorWidgetState?.selectionForToolbar;
  final info = focusedTableInfo;

  final isRange = effectiveSelection != null &&
      effectiveSelection.isValid &&
      !effectiveSelection.isCollapsed;

  if (info != null) {
    final start = isRange
        ? effectiveSelection.start
        : (effectiveSelection?.start ??
            _editorWidgetState?.cursorOffset ??
            0);
    final end = isRange ? effectiveSelection.end : start;

    final targetCursorOffset = _documentController.setCellLink(
      blockIndex: info.blockIndex,
      row: info.row,
      col: info.col,
      start: start,
      end: end,
      text: displayText,
      url: url,
    );

    _editorWidgetState?.setCursorPosition(
      info.blockIndex,
      targetCursorOffset,
      row: info.row,
      col: info.col,
    );
  } else {
    final start = isRange
        ? effectiveSelection.start
        : (effectiveSelection?.start ??
            _editorWidgetState?.cursorOffset ??
            0);
    final end = isRange ? effectiveSelection.end : start;

    final targetCursorOffset = _documentController.setLink(
      blockIndex: effectiveBlockIndex,
      start: start,
      end: end,
      text: displayText,
      url: url,
    );

    _editorWidgetState?.setCursorPosition(
      effectiveBlockIndex,
      targetCursorOffset,
    );
  }
  _editorWidgetState?.rebuild();
}