Skip to content

Commit 249152f

Browse files
committed
feat: allow inserting raw bbcode text
1 parent d5634f2 commit 249152f

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

lib/src/editor.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'dart:convert';
22
import 'dart:io';
33

4+
import 'package:dart_bbcode_parser/dart_bbcode_parser.dart';
45
import 'package:dart_bbcode_web_colors/dart_bbcode_web_colors.dart';
56
import 'package:flutter/material.dart';
67
import 'package:flutter_bbcode_editor/src/constants.dart';

lib/src/editor_controller.dart

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,28 @@ extension BBCodeExt on BBCodeEditorController {
134134
..replaceText(position, length, embed, null)
135135
..moveCursorToPosition(position + 1);
136136
}
137+
138+
/// Insert bbcode text in the cursor position.
139+
void insertBBCode(String bbcode) {
140+
final position = selection.baseOffset;
141+
final length = selection.extentOffset - position;
142+
var delta = parseBBCodeTextToDelta(bbcode);
143+
final lastOp = delta.operations.lastOrNull;
144+
if (lastOp == null) {
145+
// Do noting if operation is empty.
146+
return;
147+
}
148+
// Remove the trailing space because the space may be added by editor not user.
149+
// Note that if user manually ends the text with '\n', we can not tell if the trailing '\n' is inserted by editor
150+
// or not, this issue occurs everywhere we process text content.
151+
if (lastOp.data != null && lastOp.data is String) {
152+
final lastOpStr = lastOp.data! as String;
153+
if (lastOpStr.length == 1 && lastOpStr.endsWith('\n')) {
154+
delta = Delta.fromOperations(List.from(delta.operations)..removeLast());
155+
}
156+
}
157+
158+
replaceText(position, length, delta, null);
159+
moveCursorToPosition(position);
160+
}
137161
}

0 commit comments

Comments
 (0)