Skip to content

Commit

Permalink
Fix Multiline paste with attributes and embeds (#2074)
Browse files Browse the repository at this point in the history
  • Loading branch information
AtlasAutocode authored Jul 27, 2024
1 parent 1c3ccf7 commit 6f8fa24
Show file tree
Hide file tree
Showing 8 changed files with 285 additions and 86 deletions.
85 changes: 52 additions & 33 deletions lib/src/controller/quill_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import '../document/nodes/embeddable.dart';
import '../document/nodes/leaf.dart';
import '../document/structs/doc_change.dart';
import '../document/style.dart';
import '../editor/config/editor_configurations.dart';
import '../editor_toolbar_controller_shared/clipboard/clipboard_service_provider.dart';
import 'quill_controller_configurations.dart';

Expand All @@ -39,19 +40,25 @@ class QuillController extends ChangeNotifier {
_selection = selection;

factory QuillController.basic(
{QuillControllerConfigurations configurations =
const QuillControllerConfigurations(),
FocusNode? editorFocusNode}) {
return QuillController(
configurations: configurations,
editorFocusNode: editorFocusNode,
document: Document(),
selection: const TextSelection.collapsed(offset: 0),
);
}
{QuillControllerConfigurations configurations =
const QuillControllerConfigurations(),
FocusNode? editorFocusNode}) =>
QuillController(
configurations: configurations,
editorFocusNode: editorFocusNode,
document: Document(),
selection: const TextSelection.collapsed(offset: 0),
);

final QuillControllerConfigurations configurations;

/// Local copy of editor configurations enables fail-safe setting from editor _initState method
QuillEditorConfigurations? _editorConfigurations;
QuillEditorConfigurations? get editorConfigurations =>
configurations.editorConfigurations ?? _editorConfigurations;
set editorConfigurations(QuillEditorConfigurations? value) =>
_editorConfigurations = value;

/// Document managed by this controller.
Document _document;

Expand Down Expand Up @@ -476,10 +483,13 @@ class QuillController extends ChangeNotifier {

/// Clipboard caches last copy to allow paste with styles. Static to allow paste between multiple instances of editor.
static String _pastePlainText = '';
static Delta _pasteDelta = Delta();
static List<OffsetValue> _pasteStyleAndEmbed = <OffsetValue>[];

String get pastePlainText => _pastePlainText;
Delta get pasteDelta => _pasteDelta;
List<OffsetValue> get pasteStyleAndEmbed => _pasteStyleAndEmbed;

bool readOnly;

/// Used to give focus to the editor following a toolbar action
Expand All @@ -495,9 +505,17 @@ class QuillController extends ChangeNotifier {

bool clipboardSelection(bool copy) {
copiedImageUrl = null;
_pastePlainText = getPlainText();

/// Get the text for the selected region and expand the content of Embedded objects.
_pastePlainText = document.getPlainText(
selection.start, selection.end - selection.start, editorConfigurations);

/// Get the internal representation so it can be pasted into a QuillEditor with style retained.
_pasteStyleAndEmbed = getAllIndividualSelectionStylesAndEmbed();

/// Get the deltas for the selection so they can be pasted into a QuillEditor with styles and embeds retained.
_pasteDelta = document.toDelta().slice(selection.start, selection.end);

if (!selection.isCollapsed) {
Clipboard.setData(ClipboardData(text: _pastePlainText));
if (!copy) {
Expand Down Expand Up @@ -538,28 +556,7 @@ class QuillController extends ChangeNotifier {
// See https://github.com/flutter/flutter/issues/11427
final plainTextClipboardData =
await Clipboard.getData(Clipboard.kTextPlain);
if (plainTextClipboardData != null) {
final lines = plainTextClipboardData.text!.split('\n');
for (var i = 0; i < lines.length; ++i) {
final line = lines[i];
if (line.isNotEmpty) {
replaceTextWithEmbeds(
selection.start,
selection.end - selection.start,
line,
TextSelection.collapsed(offset: selection.start + line.length),
);
}
if (i != lines.length - 1) {
document.insert(selection.extentOffset, '\n');
_updateSelection(
TextSelection.collapsed(
offset: selection.extentOffset + 1,
),
insertNewline: true,
);
}
}
if (pasteUsingPlainOrDelta(plainTextClipboardData?.text)) {
updateEditor?.call();
return true;
}
Expand All @@ -572,6 +569,28 @@ class QuillController extends ChangeNotifier {
return false;
}

/// Internal method to allow unit testing
bool pasteUsingPlainOrDelta(String? clipboardText) {
if (clipboardText != null) {
/// Internal copy-paste preserves styles and embeds
if (clipboardText == _pastePlainText &&
_pastePlainText.isNotEmpty &&
_pasteDelta.isNotEmpty) {
replaceText(selection.start, selection.end - selection.start,
_pasteDelta, TextSelection.collapsed(offset: selection.end));
} else {
replaceText(
selection.start,
selection.end - selection.start,
clipboardText,
TextSelection.collapsed(
offset: selection.end + clipboardText.length));
}
return true;
}
return false;
}

void _pasteUsingDelta(Delta deltaFromClipboard) {
replaceText(
selection.start,
Expand Down
11 changes: 10 additions & 1 deletion lib/src/controller/quill_controller_configurations.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import '../editor/config/editor_configurations.dart';

class QuillControllerConfigurations {
const QuillControllerConfigurations(
{this.onClipboardPaste, this.requireScriptFontFeatures = false});
{this.editorConfigurations,
this.onClipboardPaste,
this.requireScriptFontFeatures = false});

/// Provides central access to editor configurations required for controller actions
///
/// Future: will be changed to 'required final'
final QuillEditorConfigurations? editorConfigurations;

/// Callback when the user pastes and data has not already been processed
///
Expand Down
13 changes: 6 additions & 7 deletions lib/src/delta/delta_diff.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,18 @@ int getPositionDelta(Delta user, Delta actual) {
);
}
if (userOperation.key == actualOperation.key) {
/// Insertions must update diff allowing for type mismatch of Operation
if (userOperation.key == Operation.insertKey) {
if (userOperation.data is Delta && actualOperation.data is String) {
diff += actualOperation.length!;
}
}
continue;
} else if (userOperation.isInsert && actualOperation.isRetain) {
diff -= userOperation.length!;
} else if (userOperation.isDelete && actualOperation.isRetain) {
diff += userOperation.length!;
} else if (userOperation.isRetain && actualOperation.isInsert) {
String? operationTxt = '';
if (actualOperation.data is String) {
operationTxt = actualOperation.data as String?;
}
if (operationTxt!.startsWith('\n')) {
continue;
}
diff += actualOperation.length!;
}
}
Expand Down
5 changes: 3 additions & 2 deletions lib/src/document/document.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import '../../quill_delta.dart';
import '../common/structs/offset_value.dart';
import '../common/structs/segment_leaf_node.dart';
import '../delta/delta_x.dart';
import '../editor/config/editor_configurations.dart';
import '../editor/embed/embed_editor_builder.dart';
import '../rules/rule.dart';
import 'attribute.dart';
Expand Down Expand Up @@ -239,9 +240,9 @@ class Document {
}

/// Returns plain text within the specified text range.
String getPlainText(int index, int len) {
String getPlainText(int index, int len, [QuillEditorConfigurations? config]) {
final res = queryChild(index);
return (res.node as Line).getPlainText(res.offset, len);
return (res.node as Line).getPlainText(res.offset, len, config);
}

/// Returns [Line] located at specified character [offset].
Expand Down
28 changes: 20 additions & 8 deletions lib/src/document/nodes/line.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:collection/collection.dart';

import '../../../../quill_delta.dart';
import '../../common/structs/offset_value.dart';
import '../../editor/config/editor_configurations.dart';
import '../../editor/embed/embed_editor_builder.dart';
import '../../editor_toolbar_controller_shared/copy_cut_service/copy_cut_service_provider.dart';
import '../attribute.dart';
Expand Down Expand Up @@ -512,14 +513,17 @@ base class Line extends QuillContainer<Leaf?> {
}

/// Returns plain text within the specified text range.
String getPlainText(int offset, int len) {
String getPlainText(int offset, int len,
[QuillEditorConfigurations? config]) {
final plainText = StringBuffer();
_getPlainText(offset, len, plainText);
_getPlainText(offset, len, plainText, config);
return plainText.toString();
}

int _getNodeText(Leaf node, StringBuffer buffer, int offset, int remaining) {
final text = node.toPlainText();
int _getNodeText(Leaf node, StringBuffer buffer, int offset, int remaining,
QuillEditorConfigurations? config) {
final text =
node.toPlainText(config?.embedBuilders, config?.unknownEmbedBuilder);
if (text == Embed.kObjectReplacementCharacter) {
final embed = node.value as Embeddable;
final provider = CopyCutServiceProvider.instance;
Expand All @@ -539,12 +543,19 @@ base class Line extends QuillContainer<Leaf?> {
return remaining - node.length;
}

/// Text for clipboard will expand the content of Embed nodes
if (node is Embed && config != null) {
buffer.write(text);
return remaining - 1;
}

final end = math.min(offset + remaining, text.length);
buffer.write(text.substring(offset, end));
return remaining - (end - offset);
}

int _getPlainText(int offset, int len, StringBuffer plainText) {
int _getPlainText(int offset, int len, StringBuffer plainText,
QuillEditorConfigurations? config) {
var len0 = len;
final data = queryChild(offset, false);
var node = data.node as Leaf?;
Expand All @@ -555,11 +566,12 @@ base class Line extends QuillContainer<Leaf?> {
plainText.write('\n');
len0 -= 1;
} else {
len0 = _getNodeText(node, plainText, offset - node.offset, len0);
len0 =
_getNodeText(node, plainText, offset - node.offset, len0, config);

while (!node!.isLast && len0 > 0) {
node = node.next as Leaf;
len0 = _getNodeText(node, plainText, 0, len0);
len0 = _getNodeText(node, plainText, 0, len0, config);
}

if (len0 > 0) {
Expand All @@ -570,7 +582,7 @@ base class Line extends QuillContainer<Leaf?> {
}

if (len0 > 0 && nextLine != null) {
len0 = nextLine!._getPlainText(0, len0, plainText);
len0 = nextLine!._getPlainText(0, len0, plainText, config);
}
}

Expand Down
7 changes: 4 additions & 3 deletions lib/src/editor/editor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,18 @@ class QuillEditorState extends State<QuillEditor>
@override
void initState() {
super.initState();

_editorKey = configurations.editorKey ?? GlobalKey<EditorState>();
_selectionGestureDetectorBuilder =
_QuillEditorSelectionGestureDetectorBuilder(
this,
configurations.detectWordBoundary,
);

widget.configurations.controller.editorConfigurations ??=
widget.configurations;

final focusNode =
widget.configurations.controller.editorFocusNode ?? widget.focusNode;
widget.configurations.controller.editorFocusNode = focusNode;
widget.configurations.controller.editorFocusNode ??= widget.focusNode;

if (configurations.autoFocus) {
focusNode.requestFocus();
Expand Down
Loading

0 comments on commit 6f8fa24

Please sign in to comment.