Skip to content

Commit

Permalink
chore: only enable document integrity check when enableDocumentIntern…
Browse files Browse the repository at this point in the history
…alLog is on (AppFlowy-IO#7251)

* chore: only enable document integrity check when enableDocumentInternalLog is on

* feat: copy divider and table from ChatGPT

* test: add copy from ChatGPT test

* feat: support copying link from keyboard clipboard
  • Loading branch information
LucasXu0 authored Jan 21, 2025
1 parent 42bd488 commit 06ab965
Show file tree
Hide file tree
Showing 8 changed files with 200 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ import 'package:freezed_annotation/freezed_annotation.dart';

part 'document_bloc.freezed.dart';

/// Enable this flag to enable the internal log for
/// - document diff
/// - document integrity check
/// - document sync state
/// - document awareness states
bool enableDocumentInternalLog = false;

final Map<String, DocumentBloc> _documentBlocMap = {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,27 +85,29 @@ class DocumentCollabAdapter {
return;
}

// Use for debugging, DO NOT REMOVE
prettyPrintJson(ops.map((op) => op.toJson()).toList());
if (enableDocumentInternalLog) {
prettyPrintJson(ops.map((op) => op.toJson()).toList());
}

final transaction = editorState.transaction;
for (final op in ops) {
transaction.add(op);
}
await editorState.apply(transaction, isRemote: true);

// Use for debugging, DO NOT REMOVE
assert(() {
final local = editorState.document.root.toJson();
final remote = document.root.toJson();
if (!const DeepCollectionEquality().equals(local, remote)) {
Log.error('Invalid diff status');
Log.error('Local: $local');
Log.error('Remote: $remote');
return false;
}
return true;
}());
if (enableDocumentInternalLog) {
assert(() {
final local = editorState.document.root.toJson();
final remote = document.root.toJson();
if (!const DeepCollectionEquality().equals(local, remote)) {
Log.error('Invalid diff status');
Log.error('Local: $local');
Log.error('Remote: $remote');
return false;
}
return true;
}());
}
}

Future<void> forceReload() async {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,17 @@ extension PasteFromHtml on EditorState {
// The table from Google Docs will contain the flag 'Google Table'
const googleDocsFlag = 'docs-internal-guid-';
final isPasteFromGoogleDocs = html.contains(googleDocsFlag);
if (nodes.isEmpty || isPasteFromGoogleDocs) {
final containsTable = nodes.any(
(node) =>
[TableBlockKeys.type, SimpleTableBlockKeys.type].contains(node.type),
);
if (nodes.isEmpty || isPasteFromGoogleDocs || containsTable) {
// fallback to the markdown parser
final markdown = html2md.convert(html);
nodes = customMarkdownToDocument(markdown).root.children.toList();
nodes = customMarkdownToDocument(markdown, tableWidth: 200)
.root
.children
.toList();
}

// 4. check if the first node and the last node is bold, because google docs will wrap the table with bold tags
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,43 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table_shortcuts/simple_table_command_extension.dart';
import 'package:appflowy/shared/patterns/common_patterns.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:universal_platform/universal_platform.dart';

class EditorKeyboardInterceptor extends AppFlowyKeyboardServiceInterceptor {
@override
Future<bool> interceptInsert(
TextEditingDeltaInsertion insertion,
EditorState editorState,
List<CharacterShortcutEvent> characterShortcutEvents,
) async {
// Only check on the mobile platform: check if the inserted text is a link, if so, try to paste it as a link preview
final text = insertion.textInserted;
if (UniversalPlatform.isMobile && hrefRegex.hasMatch(text)) {
final result = customPasteCommand.execute(editorState);
return result == KeyEventResult.handled;
}
return false;
}

@override
Future<bool> interceptReplace(
TextEditingDeltaReplacement replacement,
EditorState editorState,
List<CharacterShortcutEvent> characterShortcutEvents,
) async {
// Only check on the mobile platform: check if the replaced text is a link, if so, try to paste it as a link preview
final text = replacement.replacementText;
if (UniversalPlatform.isMobile && hrefRegex.hasMatch(text)) {
final result = customPasteCommand.execute(editorState);
return result == KeyEventResult.handled;
}
return false;
}

@override
Future<bool> interceptNonTextUpdate(
TextEditingDeltaNonTextUpdate nonTextUpdate,
Expand Down
4 changes: 2 additions & 2 deletions frontend/appflowy_flutter/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ packages:
dependency: "direct main"
description:
path: "."
ref: "7b33754"
resolved-ref: "7b33754d63841868ef4e391d1385063ef2835a61"
ref: e4648cc
resolved-ref: e4648ccbc2c1b9ffc5ceb3168b84a9ebdaa692de
url: "https://github.com/AppFlowy-IO/appflowy-editor.git"
source: git
version: "4.0.0"
Expand Down
2 changes: 1 addition & 1 deletion frontend/appflowy_flutter/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ dependency_overrides:
appflowy_editor:
git:
url: https://github.com/AppFlowy-IO/appflowy-editor.git
ref: "7b33754"
ref: "e4648cc"

appflowy_editor_plugins:
git:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,122 @@ const tableFromGoogleSheets = '''
</google-sheets-html-origin>
''';

// # The Benefits of a Balanced Diet
// A balanced diet is crucial for maintaining overall health and well-being. It provides the necessary nutrients your body needs to function effectively, supports growth and development, and helps prevent chronic diseases. In this guide, we will explore the key benefits of a balanced diet and how it can improve your life.
// ---
// ## Key Components of a Balanced Diet
// A balanced diet consists of various food groups, each providing essential nutrients. The main components include:
// 1. **Carbohydrates** – Provide energy for daily activities.
// 1. **Proteins** – Support growth, muscle repair, and immune function.
// 1. **Fats** – Aid in cell function and energy storage.
// 1. **Vitamins and Minerals** – Essential for immune function, bone health, and overall bodily processes.
// 1. **Fiber** – Promotes healthy digestion and reduces the risk of chronic diseases.
// 1. **Water** – Vital for hydration and proper bodily functions.
// ---
// ## Health Benefits of a Balanced Diet
// Maintaining a balanced diet can have profound effects on your health. Below are some of the most significant benefits:
// ---
// ### 1. **Improved Heart Health**
// A balanced diet rich in fruits, vegetables, and healthy fats helps lower cholesterol levels, reduce inflammation, and maintain a healthy blood pressure.
// ### 2. **Better Weight Management**
// By consuming nutrient-dense foods and avoiding overeating, you can achieve and maintain a healthy weight.
// ### 3. **Enhanced Mental Health**
// Proper nutrition supports brain function, which can improve mood, cognitive performance, and mental well-being.
// ### 4. **Stronger Immune System**
// A diet full of vitamins and minerals strengthens the immune system and helps the body fight off infections.
// ---
// ## Recommended Daily Nutrient Intake
// Below is a table that outlines the recommended daily intake for adults based on the different food groups:
// |Nutrient|Recommended Daily Intake|Example Foods|
// |---|---|---|
// |**Carbohydrates**|45-65% of total calories|Whole grains, fruits, vegetables|
// |**Proteins**|10-35% of total calories|Lean meats, beans, legumes, nuts, dairy|
// |**Fats**|20-35% of total calories|Olive oil, avocado, nuts, fatty fish|
// |**Fiber**|25-30 grams|Whole grains, fruits, vegetables, legumes|
// |**Vitamins & Minerals**|Varies (See below)|Fruits, vegetables, dairy, fortified cereals|
// |**Water**|2-3 liters/day|Water, herbal teas, soups|
// ---
// ## Conclusion
// Incorporating a variety of nutrient-rich foods into your diet is essential for maintaining your health. A balanced diet helps improve your physical and mental well-being, boosts energy levels, and reduces the risk of chronic conditions. By following the guidelines above, you can work toward achieving a healthier and happier life.
const tableFromChatGPT = '''
<meta charset="utf-8" />
<h1>The Benefits of a Balanced Diet</h1>
<p>
A balanced diet is crucial for maintaining overall health and well-being. It provides the necessary nutrients your body needs to function effectively, supports growth and development, and helps prevent chronic diseases. In this guide,
we will explore the key benefits of a balanced diet and how it can improve your life.
</p>
<hr />
<h2>Key Components of a Balanced Diet</h2>
<p>A balanced diet consists of various food groups, each providing essential nutrients. The main components include:</p>
<ol>
<li><strong>Carbohydrates</strong> – Provide energy for daily activities.</li>
<li><strong>Proteins</strong> – Support growth, muscle repair, and immune function.</li>
<li><strong>Fats</strong> – Aid in cell function and energy storage.</li>
<li><strong>Vitamins and Minerals</strong> – Essential for immune function, bone health, and overall bodily processes.</li>
<li><strong>Fiber</strong> – Promotes healthy digestion and reduces the risk of chronic diseases.</li>
<li><strong>Water</strong> – Vital for hydration and proper bodily functions.</li>
</ol>
<hr />
<h2>Health Benefits of a Balanced Diet</h2>
<p>Maintaining a balanced diet can have profound effects on your health. Below are some of the most significant benefits:</p>
<hr />
<h3>1. <strong>Improved Heart Health</strong></h3>
<p>A balanced diet rich in fruits, vegetables, and healthy fats helps lower cholesterol levels, reduce inflammation, and maintain a healthy blood pressure.</p>
<h3>2. <strong>Better Weight Management</strong></h3>
<p>By consuming nutrient-dense foods and avoiding overeating, you can achieve and maintain a healthy weight.</p>
<h3>3. <strong>Enhanced Mental Health</strong></h3>
<p>Proper nutrition supports brain function, which can improve mood, cognitive performance, and mental well-being.</p>
<h3>4. <strong>Stronger Immune System</strong></h3>
<p>A diet full of vitamins and minerals strengthens the immune system and helps the body fight off infections.</p>
<hr />
<h2>Recommended Daily Nutrient Intake</h2>
<p>Below is a table that outlines the recommended daily intake for adults based on the different food groups:</p>
<table>
<thead>
<tr>
<th>Nutrient</th>
<th>Recommended Daily Intake</th>
<th>Example Foods</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Carbohydrates</strong></td>
<td>45-65% of total calories</td>
<td>Whole grains, fruits, vegetables</td>
</tr>
<tr>
<td><strong>Proteins</strong></td>
<td>10-35% of total calories</td>
<td>Lean meats, beans, legumes, nuts, dairy</td>
</tr>
<tr>
<td><strong>Fats</strong></td>
<td>20-35% of total calories</td>
<td>Olive oil, avocado, nuts, fatty fish</td>
</tr>
<tr>
<td><strong>Fiber</strong></td>
<td>25-30 grams</td>
<td>Whole grains, fruits, vegetables, legumes</td>
</tr>
<tr>
<td><strong>Vitamins &amp; Minerals</strong></td>
<td>Varies (See below)</td>
<td>Fruits, vegetables, dairy, fortified cereals</td>
</tr>
<tr>
<td><strong>Water</strong></td>
<td>2-3 liters/day</td>
<td>Water, herbal teas, soups</td>
</tr>
</tbody>
</table>
<hr />
<h2>Conclusion</h2>
<p>
Incorporating a variety of nutrient-rich foods into your diet is essential for maintaining your health. A balanced diet helps improve your physical and mental well-being, boosts energy levels, and reduces the risk of chronic conditions.
By following the guidelines above, you can work toward achieving a healthier and happier life.
</p>
''';
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_html.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter_test/flutter_test.dart';

Expand Down Expand Up @@ -33,6 +33,19 @@ void main() {
test('sample 3 - paste table from Google Sheets', () {
checkTable(tableFromGoogleSheets);
});

test('sample 4 - paste table from ChatGPT', () {
final nodes = EditorState.blank().convertHtmlToNodes(tableFromChatGPT);
final table =
nodes.where((node) => node.type == SimpleTableBlockKeys.type).first;

expect(table.columnLength, 3);
expect(table.rowLength, 7);

final dividers =
nodes.where((node) => node.type == DividerBlockKeys.type);
expect(dividers.length, 5);
});
});
}

Expand Down

0 comments on commit 06ab965

Please sign in to comment.