Merge pull request #1397 from LucasXu0/auto_focus

feat: implement auto focus
This commit is contained in:
Lucas.Xu 2022-10-30 17:07:35 +08:00 committed by GitHub
commit fa4e3d0d2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 90 additions and 0 deletions

View File

@ -96,6 +96,7 @@ class _DocumentPageState extends State<DocumentPage> {
final theme = Theme.of(context);
final editor = AppFlowyEditor(
editorState: editorState,
autoFocus: editorState.document.isEmpty,
customBuilders: {
'horizontal_rule': HorizontalRuleWidgetBuilder(),
},

View File

@ -117,6 +117,7 @@ class _MyHomePageState extends State<MyHomePage> {
child: AppFlowyEditor(
editorState: _editorState!,
editable: true,
autoFocus: _editorState!.document.isEmpty,
themeData: _editorThemeData,
customBuilders: {
'text/code_block': CodeBlockNodeWidgetBuilder(),

View File

@ -110,6 +110,20 @@ class Document {
return true;
}
bool get isEmpty {
if (root.children.isEmpty) {
return true;
}
final node = root.children.first;
if (node is TextNode &&
(node.delta.isEmpty || node.delta.toPlainText().isEmpty)) {
return true;
}
return false;
}
Map<String, Object> toJson() {
return {
'document': root.toJson(),

View File

@ -31,6 +31,7 @@ class AppFlowyEditor extends StatefulWidget {
this.shortcutEvents = const [],
this.selectionMenuItems = const [],
this.editable = true,
this.autoFocus = false,
ThemeData? themeData,
}) : super(key: key) {
this.themeData = themeData ??
@ -54,6 +55,9 @@ class AppFlowyEditor extends StatefulWidget {
final bool editable;
/// Set the value to true to focus the editor on the start of the document.
final bool autoFocus;
@override
State<AppFlowyEditor> createState() => _AppFlowyEditorState();
}
@ -73,6 +77,15 @@ class _AppFlowyEditorState extends State<AppFlowyEditor> {
editorState.themeData = widget.themeData;
editorState.service.renderPluginService = _createRenderPlugin();
editorState.editable = widget.editable;
// auto focus
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (widget.editable && widget.autoFocus) {
editorState.service.selectionService.updateSelection(
Selection.single(path: [0], startOffset: 0),
);
}
});
}
@override

View File

@ -73,5 +73,66 @@ void main() async {
final document = Document.fromJson(json);
expect(document.toJson(), json);
});
test('isEmpty', () {
expect(
true,
Document.fromJson({
'document': {
'type': 'editor',
'children': [
{
'type': 'text',
'delta': [],
}
],
}
}).isEmpty,
);
expect(
true,
Document.fromJson({
'document': {
'type': 'editor',
'children': [],
}
}).isEmpty,
);
expect(
true,
Document.fromJson({
'document': {
'type': 'editor',
'children': [
{
'type': 'text',
'delta': [
{'insert': ''}
],
}
],
}
}).isEmpty,
);
expect(
false,
Document.fromJson({
'document': {
'type': 'editor',
'children': [
{
'type': 'text',
'delta': [
{'insert': 'Welcome to AppFlowy!'}
],
}
],
}
}).isEmpty,
);
});
});
}