Compare commits

...
61 Commits
Author SHA1 Message Date
Lucas.Xu 247a19b0c6 Merge pull request #1553 from AppFlowy-IO/update_version_num_0.0.8.1
chore: update changelog
2022-12-09 11:32:04 +08:00
Lucas.Xu 8494e0f0a6 Merge pull request #1554 from LucasXu0/rules
feat: add rules for editorstate.apply
2022-12-09 11:31:51 +08:00
Lucas.Xu e94eb20388 chore: disable rules for test cases 2022-12-09 11:06:28 +08:00
Lucas.Xu 8bbae46a7c feat: add rules for editorstate.apply 2022-12-09 10:36:01 +08:00
nathan 8521cc0897 chore: update changelog 2022-12-09 10:18:38 +08:00
Nathan.foooandnathan 12441f1183 fix: auto size filter menu (#1552)
Co-authored-by: nathan <nathan@appflowy.io>
2022-12-09 10:12:45 +08:00
Lucas.Xu 53b7595de8 Merge pull request #1548 from ramanverma2k/fix_1503
Refactor linux workflow & fix 1503
2022-12-09 09:42:59 +08:00
Nathan.foooandnathan 8c225fe547 Feat/restore revision (#1549)
* chore: write snapshot

* chore: add tests

* chore: sync close

* chore: restore from snapshot

* chore: delete invalid revisions after restored from snapshot

* chore: create default view if it fail to deserialize view's revisions when there is no snapshot

* chore: auto generate snapshot

Co-authored-by: nathan <nathan@appflowy.io>
2022-12-09 09:19:47 +08:00
Lucas.Xu a507fb8ec6 Merge pull request #1550 from LucasXu0/fix_windows_copy_paste
fix: Clipboard does not work in Windows #1406
2022-12-08 16:13:01 +08:00
Lucas.Xu 4db5b7a544 chore: typo 2022-12-08 15:50:43 +08:00
Lucas.Xu 1de5b274c3 chore: fix flutter analyze 2022-12-08 15:29:59 +08:00
Lucas.Xu 12b549bad2 fix: Clipboard does not work in Windows #1406 2022-12-08 15:19:21 +08:00
ramanverma2k 6dbb08c2ae fix: move deb control file to linux_installer 2022-12-08 12:04:43 +05:30
Rasyid Miftahul Ihsan 9711d670ca feat: add hover effect when trash icon is selected or hovered. (#1513) 2022-12-08 14:22:27 +08:00
Richard Shiue 442dfe7ef8 feat: switch between light and dark theme based on system settings (#1523)
* feat: allow listening to system for light/dark theme

* chore: implement UI for theme mode setting

* chore: fix translations
2022-12-08 14:21:11 +08:00
Richard Shiue f81d5eb23e fix: location of popover wrt the cell (#1545) 2022-12-08 14:18:57 +08:00
ramanverma2k 32be754eb7 fix: add libkeybinder as a dependency in deb pkg 2022-12-08 10:25:27 +05:30
ramanverma2k 0643e93e94 ci: refactor linux workflow & build an alternative linux package for older distributions. 2022-12-08 10:11:40 +05:30
Lucas.Xu 681d9028e3 Merge pull request #1544 from LucasXu0/fix_1542
fix: [Bug] Text formatting toolbar disappear under layout
2022-12-07 17:09:06 +08:00
Lucas.Xu 49574d3ff0 fix: [Bug] Text formatting toolbar disappear under layout #1542 2022-12-07 10:59:28 +08:00
Lucas.Xu c64b83c2d6 Merge pull request #1541 from LucasXu0/refactor_font_size
chore: refactor font size design
2022-12-06 19:14:14 +08:00
Lucas.Xu 52d65c4c4f Merge pull request #1540 from LucasXu0/missing_code_block_markdown
fix: add missing markdown converter for code block and divider
2022-12-06 18:36:40 +08:00
Lucas.Xu 4da786a439 chore: refactor font size design 2022-12-06 18:36:22 +08:00
Lucas.Xu 114968f2ee fix: markdown decoder and encoder test error 2022-12-06 17:48:00 +08:00
Lucas.Xu 29952bc7fd fix: add missing markdown converter for code block and divider 2022-12-06 17:24:10 +08:00
Nathan.foooandnathan 64ee3140a3 fix: click enter to submit the text content (#1537)
Co-authored-by: nathan <nathan@appflowy.io>
2022-12-05 17:17:33 +08:00
Nathan.foooandnathan a2f9ca2f28 fix: options don't refresh after moving the card (#1536)
Co-authored-by: nathan <nathan@appflowy.io>
2022-12-05 15:23:59 +08:00
Nathan.foooandnathan 72dc0b8f67 fix: filter orders (#1535)
Co-authored-by: nathan <nathan@appflowy.io>
2022-12-05 15:23:48 +08:00
Nathan.foooandnathan 721781f0ae chore: refresh the grid rows after typing text in the text filter (#1533)
Co-authored-by: nathan <nathan@appflowy.io>
2022-12-05 09:55:37 +08:00
Nathan.foooandnathan 0d879a6091 Fix/select option filter (#1530)
* fix: multi select filter bugs

* fix: single select bugs

Co-authored-by: nathan <nathan@appflowy.io>
2022-12-05 09:54:47 +08:00
Nathan.fooo 806a924fff Merge pull request #1528 from AppFlowy-IO/feat/folder_node
Feat/folder node
2022-12-05 09:53:59 +08:00
nathan 9488f42749 chore: macro node 2022-12-04 19:52:24 +08:00
ENsu a2161216d8 feat: can transform options from single & multi select (#1493)
* feat: can transform options from single & multi select

* test: add single-multi switch test
2022-12-04 16:32:37 +08:00
nathan aca9b81c79 chore: implement folder 2022-12-04 09:54:25 +08:00
nathan 81dd353d12 chore: add Node macro 2022-12-03 21:12:45 +08:00
nathan eb1659fd3e chore: add node ast parser 2022-12-03 12:03:52 +08:00
nathan c89277d507 feat: create folder node & add tests 2022-12-02 22:31:03 +08:00
nathan fa01dbb572 chore: rename 2022-12-02 10:44:46 +08:00
Lucas.Xu 63613689cd Merge pull request #1522 from LucasXu0/checklist_typo
chore: checklist.panelTitle typo
2022-12-02 09:43:36 +08:00
Lucas.Xu 89f89e8822 Merge pull request #1519 from LucasXu0/plugin
Separate AppFlowy Editor Plugins
2022-12-02 09:43:20 +08:00
Lucas.Xu a801fa627c chore: checklist.panelTitle typo 2022-12-01 19:42:49 +08:00
Lucas.Xu c6c164d347 feat: integrate divider, code block, and math equation into appflowy 2022-12-01 19:26:00 +08:00
Nathan.fooo be4222a62f Merge pull request #1518 from richardshiue/deprecate-textstyle-getters
chore: remove unused getters for TextStyles
2022-12-01 19:05:49 +08:00
Lucas.Xu 4fa2d6dc2e feat: overwrite paste logic in code block 2022-12-01 18:54:48 +08:00
Lucas.Xu e476337a6a feat: move code block plugin to appflowy editor plugins directory 2022-12-01 18:35:27 +08:00
nathan 44f9254c0a chore: add codegen crate 2022-12-01 15:17:55 +08:00
Lucas.Xu 89becbfe71 feat: add hint text for math equation plugin 2022-12-01 15:08:16 +08:00
Richard Shiue cf42d8cd43 chore: remove unused getters for TextStyles 2022-12-01 14:45:59 +08:00
Lucas.Xu 2b27fe85aa feat: move math equation plugin to appflowy editor plugins directory 2022-12-01 14:44:06 +08:00
nathan 30e7323cf7 chore: delete flowy-tool 2022-12-01 14:42:09 +08:00
Nathan.fooo 39a97499de Merge pull request #1516 from AppFlowy-IO/refactor/backend_event_system 2022-12-01 11:49:48 +08:00
Lucas.Xu 157f929ff9 feat: move divider plugin to appflowy editor plugins directory 2022-12-01 11:14:35 +08:00
nathan bf36ef7fd9 chore: update documentation 2022-12-01 10:59:22 +08:00
Lucas.Xu 7ba638268b feat: init appflowy editor plugins 2022-12-01 09:47:28 +08:00
nathan 96c427e869 refactor: rename flowy-dispatch structs 2022-12-01 09:26:16 +08:00
Nathan.fooo fff4af53e2 Merge pull request #1510 from LucasXu0/fix_1488
fix: [Bug] Inconsistent font weights #1488
2022-11-30 20:31:39 +08:00
Nathan.fooo 6910004003 Merge pull request #1512 from richardshiue/fix-flowytextfield-bugs
fix: flowy text field bugs
2022-11-30 20:30:42 +08:00
Nathan.fooo 7cb964c7a2 Merge pull request #1511 from AppFlowy-IO/feat/checklist_filter
chore: support checklist filter
2022-11-30 20:24:15 +08:00
Richard Shiue eaa1cb5a67 fix: flowy text field bugs 2022-11-30 18:28:51 +08:00
nathan 553cfb3f5e chore: support checklist filter 2022-11-30 16:43:57 +08:00
Lucas.Xu 086195d2cf fix: inconsistent font weight in Chinese #1488 2022-11-30 16:36:53 +08:00
312 changed files with 5767 additions and 4493 deletions

No files matched your search

+87 -29
View File
@@ -71,45 +71,29 @@ jobs:
flutter config --enable-linux-desktop
cargo make --env APP_VERSION=${{ github.ref_name }} --profile production-linux-x86_64 appflowy
- name: Configuring Linux Package
working-directory: frontend
run: |
mkdir -p ../${{ env.LINUX_APP_RELEASE_PATH }}/package/opt
mkdir -p ../${{ env.LINUX_APP_RELEASE_PATH }}/package/usr/share/applications
cp -r ./scripts/linux_installer ../${{ env.LINUX_APP_RELEASE_PATH }}/package/DEBIAN
cd ../${{ env.LINUX_APP_RELEASE_PATH }}/package/DEBIAN
grep -rl "\[CHANGE_THIS\]" ./control | xargs sed -i "s/\[CHANGE_THIS\]/${{ github.ref_name }}/"
chmod 0755 {postinst,postrm}
- name: Build Linux package
working-directory: ${{ env.LINUX_APP_RELEASE_PATH }}
run: |
mkdir -p package/opt && mv AppFlowy package/opt/
cd package && mkdir DEBIAN
# Create control file
printf 'Package: AppFlowy
Version: %s
Architecture: amd64
Essential: no
Priority: optional
Maintainer: AppFlowy
Description: An Open Source Alternative to Notion\n' "${{ github.ref_name }}" > DEBIAN/control
mv AppFlowy package/opt/
cd package
# postinst script for creating symlink
printf '#!/bin/bash
if [ -e /usr/local/bin/appflowy ]; then
echo "Symlink already exists, skipping."
else
echo "Creating Symlink in /usr/local/bin/appflowy"
ln -s /opt/AppFlowy/app_flowy /usr/local/bin/appflowy
fi' > DEBIAN/postinst
chmod 0755 DEBIAN/postinst
# postrm script for cleaning up residuals
printf '#!/bin/bash
if [ -e /usr/local/bin/appflowy ]; then
rm /usr/local/bin/appflowy
fi' > DEBIAN/postrm
chmod 0755 DEBIAN/postrm
mkdir -p usr/share/applications
# Update Exec & icon path in desktop entry
grep -rl "\[CHANGE_THIS\]" ./opt/AppFlowy/appflowy.desktop.temp | xargs sed -i "s/\[CHANGE_THIS\]/\/opt/"
# Add desktop entry in package
mv ./opt/AppFlowy/appflowy.desktop.temp ./usr/share/applications/appflowy.desktop
# Build
cd ../ && dpkg-deb --build --root-owner-group package ${{ env.LINUX_PACKAGE_NAME }}
cd ../ && dpkg-deb --build --root-owner-group -Z xz package ${{ env.LINUX_PACKAGE_NAME }}
- name: Upload Release Asset
id: upload-release-asset
@@ -133,6 +117,80 @@ jobs:
asset_name: ${{ env.LINUX_PACKAGE_NAME }}
asset_content_type: application/octet-stream
build-linux-x86-alt:
runs-on: ubuntu-18.04
needs: create-release
env:
LINUX_APP_RELEASE_PATH: frontend/app_flowy/product/${{ github.ref_name }}/linux/Release
LINUX_PACKAGE_NAME: AppFlowy_${{ github.ref_name }}_linux-amd64-alt.deb
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup environment - Rust and Cargo
uses: actions-rs/toolchain@v1
with:
toolchain: 'stable-2022-04-07'
- name: Setup environment - Flutter
uses: subosito/flutter-action@v2
with:
channel: 'stable'
flutter-version: '3.0.5'
- name: Pre build
working-directory: frontend
run: |
sudo wget -qO /etc/apt/trusted.gpg.d/dart_linux_signing_key.asc https://dl-ssl.google.com/linux/linux_signing_key.pub
sudo apt-get update
sudo apt-get install -y build-essential libsqlite3-dev libssl-dev clang cmake ninja-build pkg-config libgtk-3-dev
sudo apt-get install keybinder-3.0
source $HOME/.cargo/env
cargo install --force cargo-make
cargo install --force duckscript_cli
cargo make appflowy-deps-tools
- name: Build Linux app
working-directory: frontend
run: |
flutter config --enable-linux-desktop
cargo make --env APP_VERSION=${{ github.ref_name }} --profile production-linux-x86_64 appflowy
- name: Configuring Linux Package
working-directory: frontend
run: |
mkdir -p ../${{ env.LINUX_APP_RELEASE_PATH }}/package/opt
mkdir -p ../${{ env.LINUX_APP_RELEASE_PATH }}/package/usr/share/applications
cp -r ./scripts/linux_installer ../${{ env.LINUX_APP_RELEASE_PATH }}/package/DEBIAN
cd ../${{ env.LINUX_APP_RELEASE_PATH }}/package/DEBIAN
grep -rl "\[CHANGE_THIS\]" ./control | xargs sed -i "s/\[CHANGE_THIS\]/${{ github.ref_name }}/"
chmod 0755 {postinst,postrm}
- name: Build Linux package
working-directory: ${{ env.LINUX_APP_RELEASE_PATH }}
run: |
mv AppFlowy package/opt/
cd package
# Update Exec & icon path in desktop entry
grep -rl "\[CHANGE_THIS\]" ./opt/AppFlowy/appflowy.desktop.temp | xargs sed -i "s/\[CHANGE_THIS\]/\/opt/"
# Add desktop entry in package
mv ./opt/AppFlowy/appflowy.desktop.temp ./usr/share/applications/appflowy.desktop
# Build
cd ../ && dpkg-deb --build --root-owner-group -Z xz package ${{ env.LINUX_PACKAGE_NAME }}
- name: Upload Alternative Release Asset Install Package
id: upload-release-asset-install-package
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ${{ env.LINUX_APP_RELEASE_PATH }}/${{ env.LINUX_PACKAGE_NAME }}
asset_name: ${{ env.LINUX_PACKAGE_NAME }}
asset_content_type: application/octet-stream
build-macos-x86_64:
runs-on: macos-latest
needs: create-release
+7
View File
@@ -1,4 +1,11 @@
# Release Notes
## Version 0.0.8.1 - 12/09/2022
### New features
- Support following your default system theme
- Improve the filter in Grid
### Bug Fixes
- Copy/Paste
## Version 0.0.8 - 11/30/2022
### New features
- Table-view database
+1 -1
View File
@@ -22,7 +22,7 @@ CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true
CARGO_MAKE_CRATE_FS_NAME = "dart_ffi"
CARGO_MAKE_CRATE_NAME = "dart-ffi"
LIB_NAME = "dart_ffi"
CURRENT_APP_VERSION = "0.0.8"
CURRENT_APP_VERSION = "0.0.8.1"
FEATURES = "flutter"
PRODUCT_NAME = "AppFlowy"
# CRATE_TYPE: https://doc.rust-lang.org/reference/linkage.html
@@ -138,12 +138,16 @@
"open": "Obrir la configuració"
},
"appearance": {
"lightLabel": "Mode Clar",
"darkLabel": "Mode Fosc"
"themeMode": {
"label": "Theme Mode",
"light": "Mode Clar",
"dark": "Mode Fosc",
"system": "Adapt to System"
}
}
},
"sideBar": {
"openSidebar": "Open sidebar",
"closeSidebar": "Close sidebar"
}
}
}
+11 -3
View File
@@ -158,8 +158,12 @@
"open": "Open Settings"
},
"appearance": {
"lightLabel": "Light Mode",
"darkLabel": "Dark Mode"
"themeMode": {
"label": "Theme Mode",
"light": "Light Mode",
"dark": "Dark Mode",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -197,6 +201,10 @@
"is": "is"
}
},
"checklistFilter": {
"isComplete": "is complete",
"isIncomplted": "is incomplete"
},
"singleSelectOptionFilter": {
"is": "Is",
"isNot": "Is not",
@@ -266,7 +274,7 @@
"searchOption": "Search for an option"
},
"checklist": {
"panelTitle": "Search an option or create one"
"panelTitle": "Add an item"
},
"menuName": "Grid"
},
@@ -144,8 +144,12 @@
"open": "Abrir ajustes"
},
"appearance": {
"lightLabel": "Modo Claro",
"darkLabel": "Modo Oscuro"
"themeMode": {
"label": "Theme Mode",
"light": "Modo Claro",
"dark": "Modo Oscuro",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -218,9 +222,9 @@
"openSidebar": "Abrir panel lateral",
"closeSidebar": "Cerrar panel lateral"
},
"board": {
"board": {
"column": {
"create_new_card": "Nuevo"
}
}
}
}
@@ -138,12 +138,16 @@
"open": "Ouvrir les paramètres"
},
"appearance": {
"lightLabel": "Mode clair",
"darkLabel": "Mode sombre"
"themeMode": {
"label": "Theme Mode",
"light": "Mode clair",
"dark": "Mode sombre",
"system": "Adapt to System"
}
}
},
"sideBar": {
"openSidebar": "Open sidebar",
"closeSidebar": "Close sidebar"
}
}
}
@@ -152,8 +152,12 @@
"open": "Ouvrir les paramètres"
},
"appearance": {
"lightLabel": "Mode clair",
"darkLabel": "Mode sombre"
"themeMode": {
"label": "Theme Mode",
"light": "Mode clair",
"dark": "Mode sombre",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -138,12 +138,16 @@
"open": "Beállítások megnyitása"
},
"appearance": {
"lightLabel": "Világos mód",
"darkLabel": "Éjjeli mód"
"themeMode": {
"label": "Theme Mode",
"light": "Világos mód",
"dark": "Éjjeli mód",
"system": "Adapt to System"
}
}
},
"sideBar": {
"openSidebar": "Open sidebar",
"closeSidebar": "Close sidebar"
}
}
}
@@ -145,8 +145,12 @@
"open": "Buka Pengaturan"
},
"appearance": {
"lightLabel": "Mode Terang",
"darkLabel": "Mode Gelap"
"themeMode": {
"label": "Theme Mode",
"light": "Mode Terang",
"dark": "Mode Gelap",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -138,18 +138,22 @@
"open": "aprire le impostazioni"
},
"appearance": {
"lightLabel": "Modalità Chiara",
"darkLabel": "Modalità Scura"
"themeMode": {
"label": "Theme Mode",
"light": "Modalità Chiara",
"dark": "Modalità Scura",
"system": "Adapt to System"
}
}
},
"grid": {
"menuName":"Griglia"
"menuName": "Griglia"
},
"document":{
"menuName":"Documento"
"document": {
"menuName": "Documento"
},
"sideBar": {
"openSidebar": "Open sidebar",
"closeSidebar": "Close sidebar"
}
}
}
@@ -138,8 +138,12 @@
"open": "設定"
},
"appearance": {
"lightLabel": "ライトモード",
"darkLabel": "ダークモード"
"themeMode": {
"label": "Theme Mode",
"light": "ライトモード",
"dark": "ダークモード",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -138,12 +138,16 @@
"open": "Otwórz Ustawienia"
},
"appearance": {
"lightLabel": "Tryb Jasny",
"darkLabel": "Tryb Ciemny"
"themeMode": {
"label": "Theme Mode",
"light": "Tryb Jasny",
"dark": "Tryb Ciemny",
"system": "Adapt to System"
}
}
},
"sideBar": {
"openSidebar": "Open sidebar",
"closeSidebar": "Close sidebar"
}
}
}
@@ -152,8 +152,12 @@
"open": "Abrir as Configurações"
},
"appearance": {
"lightLabel": "Modo Claro",
"darkLabel": "Modo Escuro"
"themeMode": {
"label": "Theme Mode",
"light": "Modo Claro",
"dark": "Modo Escuro",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -151,8 +151,12 @@
"open": "Открыть настройки"
},
"appearance": {
"lightLabel": "Светлая",
"darkLabel": "Тёмная"
"themeMode": {
"label": "Theme Mode",
"light": "Светлая",
"dark": "Тёмная",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -152,8 +152,12 @@
"open": "Öppna inställningarna"
},
"appearance": {
"lightLabel": "Ljust läge",
"darkLabel": "Mörkt läge"
"themeMode": {
"label": "Theme Mode",
"light": "Ljust läge",
"dark": "Mörkt läge",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -232,4 +236,4 @@
"create_new_card": "Nytt"
}
}
}
}
@@ -138,12 +138,16 @@
"open": "Ayarları Aç"
},
"appearance": {
"lightLabel": "Aydınlık Mod",
"darkLabel": "Karanlık Mod"
"themeMode": {
"label": "Theme Mode",
"light": "Aydınlık Mod",
"dark": "Karanlık Mod",
"system": "Adapt to System"
}
}
},
"sideBar": {
"openSidebar": "Open sidebar",
"closeSidebar": "Close sidebar"
}
}
}
@@ -152,8 +152,12 @@
"open": "打开设置"
},
"appearance": {
"lightLabel": "日间模式",
"darkLabel": "夜间模式"
"themeMode": {
"label": "Theme Mode",
"light": "日间模式",
"dark": "夜间模式",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -145,8 +145,12 @@
"open": "開啟設定"
},
"appearance": {
"lightLabel": "亮色模式",
"darkLabel": "暗色模式"
"themeMode": {
"label": "Theme Mode",
"light": "亮色模式",
"dark": "暗色模式",
"system": "Adapt to System"
}
}
},
"grid": {
@@ -1,5 +1,4 @@
import 'package:app_flowy/plugins/grid/application/cell/cell_service/cell_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:async';
@@ -1,8 +1,8 @@
import 'package:app_flowy/plugins/document/editor_styles.dart';
import 'package:app_flowy/plugins/document/presentation/plugins/horizontal_rule_node_widget.dart';
import 'package:app_flowy/startup/startup.dart';
import 'package:app_flowy/plugins/document/presentation/banner.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:flowy_infra_ui/widget/error_page.dart';
import 'package:flowy_sdk/protobuf/flowy-folder/view.pb.dart';
import 'package:flutter/material.dart';
@@ -101,10 +101,28 @@ class _DocumentPageState extends State<DocumentPage> {
editorState: editorState,
autoFocus: editorState.document.isEmpty,
customBuilders: {
'horizontal_rule': HorizontalRuleWidgetBuilder(),
// Divider
kDividerType: DividerWidgetBuilder(),
// Math Equation
kMathEquationType: MathEquationNodeWidgetBuidler(),
// Code Block
kCodeBlockType: CodeBlockNodeWidgetBuilder(),
},
shortcutEvents: [
insertHorizontalRule,
// Divider
insertDividerEvent,
// Code Block
enterInCodeBlock,
ignoreKeysInCodeBlock,
pasteInCodeBlock,
],
selectionMenuItems: [
// Divider
dividerMenuItem,
// Math Equation
mathEquationMenuItem,
// Code Block
codeBlockMenuItem,
],
themeData: theme.copyWith(extensions: [
...theme.extensions.values,
@@ -4,8 +4,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
EditorStyle customEditorTheme(BuildContext context) {
final documentStyle =
context.watch<DocumentAppearanceCubit>().documentAppearance;
final documentStyle = context.watch<DocumentAppearanceCubit>().state;
var editorStyle = Theme.of(context).brightness == Brightness.dark
? EditorStyle.dark
: EditorStyle.light;
@@ -29,8 +28,7 @@ EditorStyle customEditorTheme(BuildContext context) {
}
Iterable<ThemeExtension<dynamic>> customPluginTheme(BuildContext context) {
final documentStyle =
context.watch<DocumentAppearanceCubit>().documentAppearance;
final documentStyle = context.watch<DocumentAppearanceCubit>().state;
final baseFontSize = documentStyle.fontSize;
const basePadding = 12.0;
var headingPluginStyle = Theme.of(context).brightness == Brightness.dark
@@ -22,19 +22,19 @@ class DocumentAppearance {
class DocumentAppearanceCubit extends Cubit<DocumentAppearance> {
DocumentAppearanceCubit() : super(const DocumentAppearance(fontSize: 14.0));
late DocumentAppearance documentAppearance;
void fetch() async {
final prefs = await SharedPreferences.getInstance();
final fontSize = prefs.getDouble(_kDocumentAppearenceFontSize) ?? 14.0;
documentAppearance = DocumentAppearance(fontSize: fontSize);
emit(documentAppearance);
emit(state.copyWith(
fontSize: fontSize,
));
}
void sync(DocumentAppearance documentAppearance) async {
void syncFontSize(double fontSize) async {
final prefs = await SharedPreferences.getInstance();
prefs.setDouble(_kDocumentAppearenceFontSize, documentAppearance.fontSize);
this.documentAppearance = documentAppearance;
emit(documentAppearance);
prefs.setDouble(_kDocumentAppearenceFontSize, fontSize);
emit(state.copyWith(
fontSize: fontSize,
));
}
}
@@ -2,7 +2,7 @@ import 'package:app_flowy/plugins/document/presentation/more/cubit/document_appe
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
import 'package:app_flowy/generated/locale_keys.g.dart';
import 'package:provider/provider.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:tuple/tuple.dart';
import 'package:easy_localization/easy_localization.dart';
@@ -16,74 +16,54 @@ class FontSizeSwitcher extends StatefulWidget {
}
class _FontSizeSwitcherState extends State<FontSizeSwitcher> {
final List<bool> _selectedFontSizes = [false, true, false];
final List<Tuple2<String, double>> _fontSizes = [
Tuple2(LocaleKeys.moreAction_small.tr(), 12.0),
Tuple2(LocaleKeys.moreAction_medium.tr(), 14.0),
Tuple2(LocaleKeys.moreAction_large.tr(), 18.0),
final List<Tuple3<String, double, bool>> _fontSizes = [
Tuple3(LocaleKeys.moreAction_small.tr(), 12.0, false),
Tuple3(LocaleKeys.moreAction_medium.tr(), 14.0, true),
Tuple3(LocaleKeys.moreAction_large.tr(), 18.0, false),
];
@override
void initState() {
super.initState();
final fontSize =
context.read<DocumentAppearanceCubit>().documentAppearance.fontSize;
final index = _fontSizes.indexWhere((element) => element.item2 == fontSize);
_updateSelectedFontSize(index);
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.semibold(
LocaleKeys.moreAction_fontSize.tr(),
fontSize: 12,
),
const SizedBox(
height: 5,
),
ToggleButtons(
isSelected: _selectedFontSizes,
onPressed: (int index) {
_updateSelectedFontSize(index);
_sync(index);
},
borderRadius: const BorderRadius.all(Radius.circular(5)),
selectedBorderColor: Theme.of(context).colorScheme.primaryContainer,
selectedColor: Theme.of(context).colorScheme.onSurface,
fillColor: Theme.of(context).colorScheme.primaryContainer,
color: Theme.of(context).hintColor,
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 80.0,
return BlocBuilder<DocumentAppearanceCubit, DocumentAppearance>(
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.semibold(
LocaleKeys.moreAction_fontSize.tr(),
fontSize: 12,
),
children: _fontSizes
.map((e) => Text(
e.item1,
style: TextStyle(fontSize: e.item2),
))
.toList(),
),
],
);
}
void _updateSelectedFontSize(int index) {
setState(() {
for (int i = 0; i < _selectedFontSizes.length; i++) {
_selectedFontSizes[i] = i == index;
}
const SizedBox(
height: 5,
),
ToggleButtons(
isSelected:
_fontSizes.map((e) => e.item2 == state.fontSize).toList(),
onPressed: (int index) {
_updateSelectedFontSize(_fontSizes[index].item2);
},
borderRadius: const BorderRadius.all(Radius.circular(5)),
selectedBorderColor: Theme.of(context).colorScheme.primaryContainer,
selectedColor: Theme.of(context).colorScheme.onSurface,
fillColor: Theme.of(context).colorScheme.primaryContainer,
color: Theme.of(context).hintColor,
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 80.0,
),
children: _fontSizes
.map((e) => Text(
e.item1,
style: TextStyle(fontSize: e.item2),
))
.toList(),
),
],
);
});
}
void _sync(int index) {
if (index < 0 || index >= _fontSizes.length) return;
final fontSize = _fontSizes[index].item2;
final cubit = context.read<DocumentAppearanceCubit>();
final documentAppearance = cubit.documentAppearance;
cubit.sync(documentAppearance.copyWith(fontSize: fontSize));
void _updateSelectedFontSize(double fontSize) {
context.read<DocumentAppearanceCubit>().syncFontSize(fontSize);
}
}
@@ -18,8 +18,10 @@ class TextCellBloc extends Bloc<TextCellEvent, TextCellState> {
_startListening();
},
updateText: (text) {
cellController.saveCellData(text);
emit(state.copyWith(content: text));
if (state.content != text) {
cellController.saveCellData(text);
emit(state.copyWith(content: text));
}
},
didReceiveCellUpdate: (content) {
emit(state.copyWith(content: content));
@@ -522,7 +522,7 @@ class FieldInfo {
case FieldType.MultiSelect:
case FieldType.RichText:
case FieldType.SingleSelect:
// case FieldType.Checklist:
case FieldType.Checklist:
return true;
default:
return false;
@@ -3,7 +3,6 @@ import 'package:flowy_sdk/dispatch/dispatch.dart';
import 'package:flowy_sdk/protobuf/flowy-error/errors.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/grid_entities.pb.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'field_service.freezed.dart';
@@ -0,0 +1,107 @@
import 'package:app_flowy/plugins/grid/presentation/widgets/filter/filter_info.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/checklist_filter.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/util.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:async';
import 'filter_listener.dart';
import 'filter_service.dart';
part 'checklist_filter_bloc.freezed.dart';
class ChecklistFilterEditorBloc
extends Bloc<ChecklistFilterEditorEvent, ChecklistFilterEditorState> {
final FilterInfo filterInfo;
final FilterFFIService _ffiService;
// final SelectOptionFFIService _selectOptionService;
final FilterListener _listener;
ChecklistFilterEditorBloc({
required this.filterInfo,
}) : _ffiService = FilterFFIService(viewId: filterInfo.viewId),
// _selectOptionService =
// SelectOptionFFIService(cellId: cellController.cellId)
_listener = FilterListener(
viewId: filterInfo.viewId,
filterId: filterInfo.filter.id,
),
super(ChecklistFilterEditorState.initial(filterInfo)) {
on<ChecklistFilterEditorEvent>(
(event, emit) async {
event.when(
initial: () async {
_startListening();
},
updateCondition: (ChecklistFilterCondition condition) {
_ffiService.insertChecklistFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
);
},
delete: () {
_ffiService.deleteFilter(
fieldId: filterInfo.fieldInfo.id,
filterId: filterInfo.filter.id,
fieldType: filterInfo.fieldInfo.fieldType,
);
},
didReceiveFilter: (FilterPB filter) {
final filterInfo = state.filterInfo.copyWith(filter: filter);
final checklistFilter = filterInfo.checklistFilter()!;
emit(state.copyWith(
filterInfo: filterInfo,
filter: checklistFilter,
));
},
);
},
);
}
void _startListening() {
_listener.start(
onDeleted: () {
if (!isClosed) add(const ChecklistFilterEditorEvent.delete());
},
onUpdated: (filter) {
if (!isClosed) {
add(ChecklistFilterEditorEvent.didReceiveFilter(filter));
}
},
);
}
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
}
@freezed
class ChecklistFilterEditorEvent with _$ChecklistFilterEditorEvent {
const factory ChecklistFilterEditorEvent.initial() = _Initial;
const factory ChecklistFilterEditorEvent.didReceiveFilter(FilterPB filter) =
_DidReceiveFilter;
const factory ChecklistFilterEditorEvent.updateCondition(
ChecklistFilterCondition condition) = _UpdateCondition;
const factory ChecklistFilterEditorEvent.delete() = _Delete;
}
@freezed
class ChecklistFilterEditorState with _$ChecklistFilterEditorState {
const factory ChecklistFilterEditorState({
required FilterInfo filterInfo,
required ChecklistFilterPB filter,
required String filterDesc,
}) = _GridFilterState;
factory ChecklistFilterEditorState.initial(FilterInfo filterInfo) {
return ChecklistFilterEditorState(
filterInfo: filterInfo,
filter: filterInfo.checklistFilter()!,
filterDesc: '',
);
}
}
@@ -62,7 +62,7 @@ class GridCreateFilterBloc
final List<FieldInfo> allFields = List.from(fields);
final keyword = filterText.toLowerCase();
allFields.retainWhere((field) {
if (field.canCreateFilter) {
if (!field.canCreateFilter) {
return false;
}
@@ -97,11 +97,22 @@ class GridRowCache {
}
}
void _updateRows(List<RowPB> updatedRows) {
void _updateRows(List<UpdatedRowPB> updatedRows) {
if (updatedRows.isEmpty) return;
List<RowPB> rowPBs = [];
for (final updatedRow in updatedRows) {
for (final fieldId in updatedRow.fieldIds) {
final key = GridCellCacheKey(
fieldId: fieldId,
rowId: updatedRow.row.id,
);
_cellCache.remove(key);
}
rowPBs.add(updatedRow.row);
}
final updatedIndexs =
_rowList.updateRows(updatedRows, (rowPB) => buildGridRow(rowPB));
_rowList.updateRows(rowPBs, (rowPB) => buildGridRow(rowPB));
if (updatedIndexs.isNotEmpty) {
_rowChangeReasonNotifier.receive(RowsChangedReason.update(updatedIndexs));
}
@@ -40,10 +40,7 @@ class GridChecklistCellState extends State<GridChecklistCell> {
alignment: AlignmentDirectional.center,
fit: StackFit.expand,
children: [
Padding(
padding: GridSize.cellContentInsets,
child: _wrapPopover(const ChecklistProgressBar()),
),
_wrapPopover(const ChecklistProgressBar()),
InkWell(onTap: () => _popover.show()),
],
),
@@ -66,7 +63,10 @@ class GridChecklistCellState extends State<GridChecklistCell> {
);
},
onClose: () => widget.onCellEditing.value = false,
child: child,
child: Padding(
padding: GridSize.cellContentInsets,
child: child,
),
);
}
}
@@ -168,10 +168,7 @@ class _SelectOptionWrapState extends State<SelectOptionWrap> {
alignment: AlignmentDirectional.center,
fit: StackFit.expand,
children: [
Padding(
padding: GridSize.cellContentInsets,
child: _wrapPopover(child),
),
_wrapPopover(child),
InkWell(onTap: () => _popover.show()),
],
);
@@ -196,7 +193,10 @@ class _SelectOptionWrapState extends State<SelectOptionWrap> {
);
},
onClose: () => widget.onFocus?.call(false),
child: child,
child: Padding(
padding: GridSize.cellContentInsets,
child: child,
),
);
}
@@ -37,7 +37,6 @@ class GridTextCell extends GridCellWidget {
class _GridTextCellState extends GridFocusNodeCellState<GridTextCell> {
late TextCellBloc _cellBloc;
late TextEditingController _controller;
Timer? _delayOperation;
@override
void initState() {
@@ -66,8 +65,6 @@ class _GridTextCellState extends GridFocusNodeCellState<GridTextCell> {
child: TextField(
controller: _controller,
focusNode: focusNode,
onChanged: (value) => focusChanged(),
onEditingComplete: () => focusNode.unfocus(),
maxLines: null,
style: Theme.of(context).textTheme.bodyMedium,
decoration: InputDecoration(
@@ -87,24 +84,10 @@ class _GridTextCellState extends GridFocusNodeCellState<GridTextCell> {
@override
Future<void> dispose() async {
_delayOperation = null;
_cellBloc.close();
super.dispose();
}
@override
Future<void> focusChanged() async {
if (mounted) {
_delayOperation?.cancel();
_delayOperation = Timer(const Duration(milliseconds: 30), () {
if (_cellBloc.isClosed == false &&
_controller.text != _cellBloc.state.content) {
_cellBloc.add(TextCellEvent.updateText(_controller.text));
}
});
}
}
@override
String? onCopy() => _cellBloc.state.content;
@@ -112,4 +95,12 @@ class _GridTextCellState extends GridFocusNodeCellState<GridTextCell> {
void onInsert(String value) {
_cellBloc.add(TextCellEvent.updateText(value));
}
@override
Future<void> focusChanged() {
_cellBloc.add(
TextCellEvent.updateText(_controller.text),
);
return super.focusChanged();
}
}
@@ -1,14 +0,0 @@
import 'package:app_flowy/plugins/grid/presentation/widgets/filter/filter_info.dart';
import 'package:flutter/material.dart';
import 'choicechip.dart';
class ChecklistFilterChoicechip extends StatelessWidget {
final FilterInfo filterInfo;
const ChecklistFilterChoicechip({required this.filterInfo, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return ChoiceChipButton(filterInfo: filterInfo);
}
}
@@ -0,0 +1,172 @@
import 'package:app_flowy/generated/locale_keys.g.dart';
import 'package:app_flowy/plugins/grid/application/filter/checklist_filter_bloc.dart';
import 'package:app_flowy/plugins/grid/presentation/widgets/filter/condition_button.dart';
import 'package:app_flowy/plugins/grid/presentation/widgets/filter/disclosure_button.dart';
import 'package:app_flowy/plugins/grid/presentation/widgets/filter/filter_info.dart';
import 'package:app_flowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/checklist_filter.pbenum.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../choicechip.dart';
class ChecklistFilterChoicechip extends StatefulWidget {
final FilterInfo filterInfo;
const ChecklistFilterChoicechip({required this.filterInfo, Key? key})
: super(key: key);
@override
State<ChecklistFilterChoicechip> createState() =>
_ChecklistFilterChoicechipState();
}
class _ChecklistFilterChoicechipState extends State<ChecklistFilterChoicechip> {
late ChecklistFilterEditorBloc bloc;
late PopoverMutex popoverMutex;
@override
void initState() {
popoverMutex = PopoverMutex();
bloc = ChecklistFilterEditorBloc(filterInfo: widget.filterInfo);
bloc.add(const ChecklistFilterEditorEvent.initial());
super.initState();
}
@override
void dispose() {
bloc.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider.value(
value: bloc,
child: BlocBuilder<ChecklistFilterEditorBloc, ChecklistFilterEditorState>(
builder: (blocContext, state) {
return AppFlowyPopover(
controller: PopoverController(),
constraints: BoxConstraints.loose(const Size(200, 160)),
direction: PopoverDirection.bottomWithCenterAligned,
popupBuilder: (BuildContext context) {
return ChecklistFilterEditor(
bloc: bloc,
popoverMutex: popoverMutex,
);
},
child: ChoiceChipButton(
filterInfo: widget.filterInfo,
filterDesc: state.filterDesc,
),
);
},
),
);
}
}
class ChecklistFilterEditor extends StatefulWidget {
final ChecklistFilterEditorBloc bloc;
final PopoverMutex popoverMutex;
const ChecklistFilterEditor(
{required this.bloc, required this.popoverMutex, Key? key})
: super(key: key);
@override
ChecklistState createState() => ChecklistState();
}
class ChecklistState extends State<ChecklistFilterEditor> {
@override
Widget build(BuildContext context) {
return BlocProvider.value(
value: widget.bloc,
child: BlocBuilder<ChecklistFilterEditorBloc, ChecklistFilterEditorState>(
builder: (context, state) {
return SizedBox(
height: 20,
child: Row(
children: [
FlowyText(state.filterInfo.fieldInfo.name),
const HSpace(4),
ChecklistFilterConditionList(
filterInfo: state.filterInfo,
),
const Spacer(),
DisclosureButton(
popoverMutex: widget.popoverMutex,
onAction: (action) {
switch (action) {
case FilterDisclosureAction.delete:
context
.read<ChecklistFilterEditorBloc>()
.add(const ChecklistFilterEditorEvent.delete());
break;
}
},
),
],
),
);
},
),
);
}
}
class ChecklistFilterConditionList extends StatelessWidget {
final FilterInfo filterInfo;
const ChecklistFilterConditionList({
required this.filterInfo,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final checklistFilter = filterInfo.checklistFilter()!;
return PopoverActionList<ConditionWrapper>(
asBarrier: true,
direction: PopoverDirection.bottomWithCenterAligned,
actions: ChecklistFilterCondition.values
.map((action) => ConditionWrapper(action))
.toList(),
buildChild: (controller) {
return ConditionButton(
conditionName: checklistFilter.condition.filterName,
onTap: () => controller.show(),
);
},
onSelected: (action, controller) async {
context
.read<ChecklistFilterEditorBloc>()
.add(ChecklistFilterEditorEvent.updateCondition(action.inner));
controller.close();
},
);
}
}
class ConditionWrapper extends ActionCell {
final ChecklistFilterCondition inner;
ConditionWrapper(this.inner);
@override
String get name => inner.filterName;
}
extension ChecklistFilterConditionExtension on ChecklistFilterCondition {
String get filterName {
switch (this) {
case ChecklistFilterCondition.IsComplete:
return LocaleKeys.grid_checklistFilter_isComplete.tr();
case ChecklistFilterCondition.IsIncomplete:
return LocaleKeys.grid_checklistFilter_isIncomplted.tr();
default:
return "";
}
}
}
@@ -61,7 +61,7 @@ class _SelectOptionFilterChoicechipState
builder: (blocContext, state) {
return AppFlowyPopover(
controller: PopoverController(),
constraints: BoxConstraints.loose(const Size(200, 160)),
constraints: BoxConstraints.loose(const Size(240, 160)),
direction: PopoverDirection.bottomWithCenterAligned,
popupBuilder: (BuildContext context) {
return SelectOptionFilterEditor(bloc: bloc);
@@ -152,8 +152,9 @@ class _TextFilterEditorState extends State<TextFilterEditor> {
return FlowyTextField(
text: state.filter.content,
hintText: LocaleKeys.grid_settings_typeAValue.tr(),
autoFucous: false,
onSubmitted: (text) {
debounceDuration: const Duration(milliseconds: 300),
autoFocus: false,
onChanged: (text) {
context
.read<TextFilterEditorBloc>()
.add(TextFilterEditorEvent.updateContent(text));
@@ -1,5 +1,6 @@
import 'package:app_flowy/plugins/grid/application/field/field_controller.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/checkbox_filter.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/checklist_filter.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/date_filter.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pb.dart';
import 'package:flowy_sdk/protobuf/flowy-grid/select_option_filter.pbserver.dart';
@@ -50,4 +51,12 @@ class FilterInfo {
return null;
}
}
ChecklistFilterPB? checklistFilter() {
if (filter.fieldType == FieldType.Checklist) {
return ChecklistFilterPB.fromBuffer(filter.data);
} else {
return null;
}
}
}
@@ -54,21 +54,26 @@ class GridFilterMenu extends StatelessWidget {
}
Widget buildFilterItems(String viewId, GridFilterMenuState state) {
final List<Widget> children = state.filters
.map((filterInfo) => FilterMenuItem(filterInfo: filterInfo))
.toList();
final List<Widget> children = [];
children.addAll(
state.filters
.map((filterInfo) => FilterMenuItem(filterInfo: filterInfo))
.toList(),
);
if (state.creatableFields.isNotEmpty) {
children.add(AddFilterButton(viewId: viewId));
}
return Row(
children: [
SingleChildScrollView(
controller: ScrollController(),
scrollDirection: Axis.horizontal,
Expanded(
child: Wrap(
spacing: 4,
spacing: 6,
runSpacing: 4,
children: children,
),
),
const HSpace(4),
if (state.creatableFields.isNotEmpty) AddFilterButton(viewId: viewId),
],
);
}
@@ -2,7 +2,7 @@ import 'package:flowy_sdk/protobuf/flowy-grid/field_entities.pbenum.dart';
import 'package:flutter/material.dart';
import 'choicechip/checkbox.dart';
import 'choicechip/checklist.dart';
import 'choicechip/checklist/checklist.dart';
import 'choicechip/date.dart';
import 'choicechip/number.dart';
import 'choicechip/select_option/select_option.dart';
@@ -123,8 +123,9 @@ class _OptionNameTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FlowyTextField(
autoFucous: autoFocus,
autoFocus: autoFocus,
text: name,
maxLength: 30,
onSubmitted: (newName) {
if (name != newName) {
context
@@ -114,7 +114,7 @@ class _PropertyList extends StatelessWidget {
builder: (context, state) {
return Column(
children: [
Expanded(child: _wrapScrollbar(buildList(state))),
Expanded(child: _wrapScrollbar(buildRowCells(state))),
const VSpace(10),
_CreateFieldButton(
viewId: viewId,
@@ -126,7 +126,7 @@ class _PropertyList extends StatelessWidget {
);
}
Widget buildList(RowDetailState state) {
Widget buildRowCells(RowDetailState state) {
return ListView.separated(
controller: _scrollController,
itemCount: state.gridCells.length,
@@ -3,7 +3,6 @@ import 'package:app_flowy/plugins/grid/application/filter/filter_menu_bloc.dart'
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/color_extension.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flutter/material.dart';
@@ -35,7 +34,7 @@ class _FilterButtonState extends State<FilterButton> {
height: 26,
child: FlowyTextButton(
LocaleKeys.grid_settings_filter.tr(),
fontSize: FontSizes.s14,
fontSize: 13,
fontColor: textColor,
fillColor: Colors.transparent,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
@@ -4,7 +4,6 @@ import 'package:app_flowy/plugins/grid/application/setting/setting_bloc.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/color_extension.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flutter/material.dart';
@@ -50,7 +49,7 @@ class _SettingButtonState extends State<SettingButton> {
triggerActions: PopoverTriggerFlags.none,
child: FlowyTextButton(
LocaleKeys.settings_title.tr(),
fontSize: FontSizes.s14,
fontSize: 13,
fillColor: Colors.transparent,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 6),
+26 -11
View File
@@ -3,7 +3,11 @@ import 'package:app_flowy/startup/startup.dart';
import 'package:app_flowy/workspace/presentation/home/home_stack.dart';
import 'package:app_flowy/workspace/presentation/home/menu/menu.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/color_extension.dart';
import 'package:flowy_infra/image.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/extension.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
@@ -14,16 +18,27 @@ class MenuTrash extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(
height: 26,
child: InkWell(
onTap: () {
getIt<MenuSharedState>().latestOpenView = null;
getIt<HomeStackManager>()
.setPlugin(makePlugin(pluginType: PluginType.trash));
},
child: _render(context),
),
return ValueListenableBuilder(
valueListenable: getIt<MenuSharedState>().notifier,
builder: (context, value, child) {
return FlowyHover(
style: HoverStyle(
hoverColor: AFThemeExtension.of(context).greySelect,
),
isSelected: () => getIt<MenuSharedState>().latestOpenView == null,
child: SizedBox(
height: 26,
child: InkWell(
onTap: () {
getIt<MenuSharedState>().latestOpenView = null;
getIt<HomeStackManager>()
.setPlugin(makePlugin(pluginType: PluginType.trash));
},
child: _render(context),
),
).padding(horizontal: Insets.l),
).padding(horizontal: 8);
},
);
}
@@ -43,4 +58,4 @@ class MenuTrash extends StatelessWidget {
],
);
}
}
}
@@ -82,7 +82,9 @@ class ApplicationWidget extends StatelessWidget {
builder: (context, state) => MaterialApp(
builder: overlayManagerBuilder(),
debugShowCheckedModeBanner: false,
theme: state.theme.themeData,
theme: state.theme.getThemeData(state.locale),
darkTheme: state.darkTheme.getThemeData(state.locale),
themeMode: state.themeMode,
localizationsDelegates: context.localizationDelegates +
[AppFlowyEditorLocalizations.delegate],
supportedLocales: context.supportedLocales,
@@ -19,6 +19,7 @@ class AppearanceSettingsCubit extends Cubit<AppearanceSettingsState> {
: _setting = setting,
super(AppearanceSettingsState.initial(
setting.theme,
setting.themeMode,
setting.font,
setting.monospaceFont,
setting.locale,
@@ -26,21 +27,34 @@ class AppearanceSettingsCubit extends Cubit<AppearanceSettingsState> {
/// Updates the current theme and notify the listeners the theme was changed.
/// Do nothing if the passed in themeType equal to the current theme type.
void setTheme(Brightness brightness) {
if (state.theme.brightness == brightness) {
// void setTheme(Brightness brightness) {
// if (state.theme.brightness == brightness) {
// return;
// }
// _setting.theme = themeTypeToString(brightness);
// _saveAppearanceSettings();
// emit(state.copyWith(
// theme: AppTheme.fromBrightness(
// brightness: _setting.themeMode,
// font: state.theme.font,
// monospaceFont: state.theme.monospaceFont,
// ),
// ));
// }
/// Updates the current theme and notify the listeners the theme was changed.
/// Do nothing if the passed in themeType equal to the current theme type.
void setThemeMode(ThemeMode themeMode) {
if (state.themeMode == themeMode) {
return;
}
_setting.theme = themeTypeToString(brightness);
_setting.themeMode = _themeModeToPB(themeMode);
_saveAppearanceSettings();
emit(state.copyWith(
theme: AppTheme.fromName(
themeName: _setting.theme,
font: state.theme.font,
monospaceFont: state.theme.monospaceFont,
),
));
emit(state.copyWith(themeMode: themeMode));
}
/// Updates the current locale and notify the listeners the locale was changed
@@ -115,25 +129,58 @@ class AppearanceSettingsCubit extends Cubit<AppearanceSettingsState> {
}
}
ThemeMode _themeModeFromPB(ThemeModePB themeModePB) {
switch (themeModePB) {
case ThemeModePB.Light:
return ThemeMode.light;
case ThemeModePB.Dark:
return ThemeMode.dark;
case ThemeModePB.System:
default:
return ThemeMode.system;
}
}
ThemeModePB _themeModeToPB(ThemeMode themeMode) {
switch (themeMode) {
case ThemeMode.light:
return ThemeModePB.Light;
case ThemeMode.dark:
return ThemeModePB.Dark;
case ThemeMode.system:
default:
return ThemeModePB.System;
}
}
@freezed
class AppearanceSettingsState with _$AppearanceSettingsState {
const factory AppearanceSettingsState({
required AppTheme theme,
required AppTheme darkTheme,
required ThemeMode themeMode,
required Locale locale,
}) = _AppearanceSettingsState;
factory AppearanceSettingsState.initial(
String themeName,
ThemeModePB themeMode,
String font,
String monospaceFont,
LocaleSettingsPB locale,
) =>
AppearanceSettingsState(
theme: AppTheme.fromName(
themeName: themeName,
theme: AppTheme.fromBrightness(
brightness: Brightness.light,
font: font,
monospaceFont: monospaceFont,
),
darkTheme: AppTheme.fromBrightness(
brightness: Brightness.dark,
font: font,
monospaceFont: monospaceFont,
),
themeMode: _themeModeFromPB(themeMode),
locale: Locale(locale.languageCode, locale.countryCode),
);
}
@@ -104,7 +104,7 @@ class HomeMenu extends StatelessWidget {
).padding(horizontal: Insets.l),
),
const VSpace(20),
const MenuTrash().padding(horizontal: Insets.l),
const MenuTrash(),
const VSpace(20),
_renderNewAppButton(context),
],
@@ -178,6 +178,7 @@ class MenuSharedState {
}
ViewPB? get latestOpenView => _latestOpenView.value;
ValueNotifier<ViewPB?> get notifier => _latestOpenView;
set latestOpenView(ViewPB? view) {
if (_latestOpenView.value != view) {
@@ -1,43 +1,99 @@
import 'package:app_flowy/generated/locale_keys.g.dart';
import 'package:app_flowy/workspace/application/appearance.dart';
import 'package:app_flowy/workspace/presentation/widgets/toggle/toggle_style.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra/image.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../widgets/toggle/toggle.dart';
class SettingsAppearanceView extends StatelessWidget {
const SettingsAppearanceView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>(
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.medium(LocaleKeys.settings_appearance_lightLabel.tr()),
Toggle(
value: Theme.of(context).brightness == Brightness.dark,
onChanged: (_) => setTheme(context),
style: ToggleStyle.big,
),
FlowyText.medium(LocaleKeys.settings_appearance_darkLabel.tr())
ThemeModeSetting(currentThemeMode: state.themeMode),
],
);
},
),
);
}
}
class ThemeModeSetting extends StatelessWidget {
final ThemeMode currentThemeMode;
const ThemeModeSetting({required this.currentThemeMode, super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: FlowyText.medium(
LocaleKeys.settings_appearance_themeMode_label.tr(),
overflow: TextOverflow.ellipsis,
),
],
),
AppFlowyPopover(
direction: PopoverDirection.bottomWithRightAligned,
child: FlowyTextButton(
_themeModeLabelText(currentThemeMode),
fillColor: Colors.transparent,
hoverColor: Theme.of(context).colorScheme.secondary,
onPressed: () {},
),
popupBuilder: (BuildContext context) {
return IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_themeModeItemButton(context, ThemeMode.light),
_themeModeItemButton(context, ThemeMode.dark),
_themeModeItemButton(context, ThemeMode.system),
],
),
);
},
),
],
);
}
Widget _themeModeItemButton(BuildContext context, ThemeMode themeMode) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(_themeModeLabelText(themeMode)),
rightIcon: currentThemeMode == themeMode
? svgWidget("grid/checkmark")
: const SizedBox(),
onTap: () {
if (currentThemeMode != themeMode) {
context.read<AppearanceSettingsCubit>().setThemeMode(themeMode);
}
},
),
);
}
void setTheme(BuildContext context) {
if (Theme.of(context).brightness == Brightness.dark) {
context.read<AppearanceSettingsCubit>().setTheme(Brightness.light);
} else {
context.read<AppearanceSettingsCubit>().setTheme(Brightness.dark);
String _themeModeLabelText(ThemeMode themeMode) {
switch (themeMode) {
case (ThemeMode.light):
return LocaleKeys.settings_appearance_themeMode_light.tr();
case (ThemeMode.dark):
return LocaleKeys.settings_appearance_themeMode_dark.tr();
case (ThemeMode.system):
return LocaleKeys.settings_appearance_themeMode_system.tr();
default:
return "";
}
}
}
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:flutter/material.dart';
class SimpleEditor extends StatelessWidget {
@@ -30,10 +31,35 @@ class SimpleEditor extends StatelessWidget {
),
);
onEditorStateChange(editorState);
return AppFlowyEditor(
editorState: editorState,
themeData: themeData,
autoFocus: editorState.document.isEmpty,
customBuilders: {
// Divider
kDividerType: DividerWidgetBuilder(),
// Math Equation
kMathEquationType: MathEquationNodeWidgetBuidler(),
// Code Block
kCodeBlockType: CodeBlockNodeWidgetBuilder(),
},
shortcutEvents: [
// Divider
insertDividerEvent,
// Code Block
enterInCodeBlock,
ignoreKeysInCodeBlock,
pasteInCodeBlock,
],
selectionMenuItems: [
// Divider
dividerMenuItem,
// Math Equation
mathEquationMenuItem,
// Code Block
codeBlockMenuItem,
],
);
} else {
return const Center(
@@ -1,166 +0,0 @@
import 'dart:collection';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
ShortcutEvent insertHorizontalRule = ShortcutEvent(
key: 'Horizontal rule',
command: 'Minus',
handler: _insertHorzaontalRule,
);
ShortcutEventHandler _insertHorzaontalRule = (editorState, event) {
final selection = editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (textNodes.length != 1 || selection == null) {
return KeyEventResult.ignored;
}
final textNode = textNodes.first;
if (textNode.toPlainText() == '--') {
final transaction = editorState.transaction
..deleteText(textNode, 0, 2)
..insertNode(
textNode.path,
Node(
type: 'horizontal_rule',
children: LinkedList(),
attributes: {},
),
)
..afterSelection =
Selection.single(path: textNode.path.next, startOffset: 0);
editorState.apply(transaction);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
};
SelectionMenuItem horizontalRuleMenuItem = SelectionMenuItem(
name: () => 'Horizontal rule',
icon: (_, __) => const Icon(
Icons.horizontal_rule,
color: Colors.black,
size: 18.0,
),
keywords: ['horizontal rule'],
handler: (editorState, _, __) {
final selection =
editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (selection == null || textNodes.isEmpty) {
return;
}
final textNode = textNodes.first;
if (textNode.toPlainText().isEmpty) {
final transaction = editorState.transaction
..insertNode(
textNode.path,
Node(
type: 'horizontal_rule',
children: LinkedList(),
attributes: {},
),
)
..afterSelection =
Selection.single(path: textNode.path.next, startOffset: 0);
editorState.apply(transaction);
} else {
final transaction = editorState.transaction
..insertNode(
selection.end.path.next,
TextNode(
children: LinkedList(),
attributes: {
'subtype': 'horizontal_rule',
},
delta: Delta()..insert('---'),
),
)
..afterSelection = selection;
editorState.apply(transaction);
}
},
);
class HorizontalRuleWidgetBuilder extends NodeWidgetBuilder<Node> {
@override
Widget build(NodeWidgetContext<Node> context) {
return _HorizontalRuleWidget(
key: context.node.key,
node: context.node,
editorState: context.editorState,
);
}
@override
NodeValidator<Node> get nodeValidator => (node) {
return true;
};
}
class _HorizontalRuleWidget extends StatefulWidget {
const _HorizontalRuleWidget({
Key? key,
required this.node,
required this.editorState,
}) : super(key: key);
final Node node;
final EditorState editorState;
@override
State<_HorizontalRuleWidget> createState() => __HorizontalRuleWidgetState();
}
class __HorizontalRuleWidgetState extends State<_HorizontalRuleWidget>
with SelectableMixin {
RenderBox get _renderBox => context.findRenderObject() as RenderBox;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Container(
height: 1,
color: Colors.grey,
),
);
}
@override
Position start() => Position(path: widget.node.path, offset: 0);
@override
Position end() => Position(path: widget.node.path, offset: 1);
@override
Position getPositionInOffset(Offset start) => end();
@override
bool get shouldCursorBlink => false;
@override
CursorStyle get cursorStyle => CursorStyle.borderLine;
@override
Rect? getCursorRectInPosition(Position position) {
final size = _renderBox.size;
return Rect.fromLTWH(-size.width / 2.0, 0, size.width, size.height);
}
@override
List<Rect> getRectsInSelection(Selection selection) =>
[Offset.zero & _renderBox.size];
@override
Selection getSelectionInRange(Offset start, Offset end) => Selection.single(
path: widget.node.path,
startOffset: 0,
endOffset: 1,
);
@override
Offset localToGlobal(Offset offset) => _renderBox.localToGlobal(offset);
}
@@ -1,193 +0,0 @@
import 'dart:collection';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_math_fork/flutter_math.dart';
SelectionMenuItem teXBlockMenuItem = SelectionMenuItem(
name: () => 'Tex',
icon: (_, __) => const Icon(
Icons.text_fields_rounded,
color: Colors.black,
size: 18.0,
),
keywords: ['tex, latex, katex'],
handler: (editorState, _, __) {
final selection =
editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (selection == null || !selection.isCollapsed || textNodes.isEmpty) {
return;
}
final Path texNodePath;
if (textNodes.first.toPlainText().isEmpty) {
texNodePath = selection.end.path;
final transaction = editorState.transaction
..insertNode(
selection.end.path,
Node(
type: 'tex',
children: LinkedList(),
attributes: {'tex': ''},
),
)
..deleteNode(textNodes.first)
..afterSelection = selection;
editorState.apply(transaction);
} else {
texNodePath = selection.end.path.next;
final transaction = editorState.transaction
..insertNode(
selection.end.path.next,
Node(
type: 'tex',
children: LinkedList(),
attributes: {'tex': ''},
),
)
..afterSelection = selection;
editorState.apply(transaction);
}
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
final texState =
editorState.document.nodeAtPath(texNodePath)?.key?.currentState;
if (texState != null && texState is __TeXBlockNodeWidgetState) {
texState.showEditingDialog();
}
});
},
);
class TeXBlockNodeWidgetBuidler extends NodeWidgetBuilder<Node> {
@override
Widget build(NodeWidgetContext<Node> context) {
return _TeXBlockNodeWidget(
key: context.node.key,
node: context.node,
editorState: context.editorState,
);
}
@override
NodeValidator<Node> get nodeValidator => (node) {
return node.attributes['tex'] is String;
};
}
class _TeXBlockNodeWidget extends StatefulWidget {
const _TeXBlockNodeWidget({
Key? key,
required this.node,
required this.editorState,
}) : super(key: key);
final Node node;
final EditorState editorState;
@override
State<_TeXBlockNodeWidget> createState() => __TeXBlockNodeWidgetState();
}
class __TeXBlockNodeWidgetState extends State<_TeXBlockNodeWidget> {
String get _tex => widget.node.attributes['tex'] as String;
bool _isHover = false;
@override
Widget build(BuildContext context) {
return InkWell(
onHover: (value) {
setState(() {
_isHover = value;
});
},
onTap: () {
showEditingDialog();
},
child: Stack(
children: [
_buildTex(context),
if (_isHover) _buildDeleteButton(context),
],
),
);
}
Widget _buildTex(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
padding: const EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
color: _isHover ? Colors.grey[200] : Colors.transparent,
),
child: Center(
child: Math.tex(
_tex,
textStyle: const TextStyle(fontSize: 20),
mathStyle: MathStyle.display,
),
),
);
}
Widget _buildDeleteButton(BuildContext context) {
return Positioned(
top: -5,
right: -5,
child: IconButton(
icon: Icon(
Icons.delete_outline,
color: Colors.blue[400],
size: 16,
),
onPressed: () {
final transaction = widget.editorState.transaction
..deleteNode(widget.node);
widget.editorState.apply(transaction);
},
),
);
}
void showEditingDialog() {
showDialog(
context: context,
builder: (context) {
final controller = TextEditingController(text: _tex);
return AlertDialog(
title: const Text('Edit Katex'),
content: TextField(
controller: controller,
maxLines: null,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
if (controller.text != _tex) {
final transaction = widget.editorState.transaction
..updateNode(
widget.node,
{'tex': controller.text},
);
widget.editorState.apply(transaction);
}
},
child: const Text('OK'),
),
],
);
},
);
}
}
@@ -45,6 +45,8 @@ dependencies:
universal_html: ^2.0.8
highlight: ^0.7.0
flutter_math_fork: ^0.6.3+1
appflowy_editor_plugins:
path: ../../../packages/appflowy_editor_plugins
dev_dependencies:
flutter_test:
@@ -1,4 +1,5 @@
import 'dart:async';
import 'package:appflowy_editor/src/core/document/node.dart';
import 'package:appflowy_editor/src/infra/log.dart';
import 'package:appflowy_editor/src/render/selection_menu/selection_menu_widget.dart';
import 'package:appflowy_editor/src/render/style/editor_style.dart';
@@ -72,6 +73,7 @@ class EditorState {
// TODO: only for testing.
bool disableSealTimer = false;
bool disbaleRules = false;
bool editable = true;
@@ -119,8 +121,12 @@ class EditorState {
///
/// The options can be used to determine whether the editor
/// should record the transaction in undo/redo stack.
apply(Transaction transaction,
[ApplyOptions options = const ApplyOptions(recordUndo: true)]) {
void apply(
Transaction transaction, {
ApplyOptions options = const ApplyOptions(recordUndo: true),
ruleCount = 0,
withUpdateCursor = true,
}) {
if (!editable) {
return;
}
@@ -132,7 +138,10 @@ class EditorState {
_observer.add(transaction);
WidgetsBinding.instance.addPostFrameCallback((_) {
updateCursorSelection(transaction.afterSelection);
_applyRules(ruleCount);
if (withUpdateCursor) {
updateCursorSelection(transaction.afterSelection);
}
});
if (options.recordUndo) {
@@ -153,7 +162,7 @@ class EditorState {
}
}
_debouncedSealHistoryItem() {
void _debouncedSealHistoryItem() {
if (disableSealTimer) {
return;
}
@@ -168,7 +177,7 @@ class EditorState {
});
}
_applyOperation(Operation op) {
void _applyOperation(Operation op) {
if (op is InsertOperation) {
document.insert(op.path, op.nodes);
} else if (op is UpdateOperation) {
@@ -179,4 +188,27 @@ class EditorState {
document.updateText(op.path, op.delta);
}
}
void _applyRules(int ruleCount) {
// Set a maximum count to prevent a dead loop.
if (ruleCount >= 5 || disbaleRules) {
return;
}
final tr = transaction;
// Rules
_insureLastNodeEditable(tr);
if (tr.operations.isNotEmpty) {
apply(tr, ruleCount: ruleCount + 1, withUpdateCursor: false);
}
}
void _insureLastNodeEditable(Transaction tr) {
if (document.root.children.isEmpty ||
document.root.children.last.id != 'text') {
tr.insertNode([document.root.children.length], TextNode.empty());
}
}
}
@@ -123,7 +123,7 @@ class UndoManager {
final transaction = historyItem.toTransaction(s);
s.apply(
transaction,
const ApplyOptions(
options: const ApplyOptions(
recordUndo: false,
recordRedo: true,
),
@@ -143,7 +143,7 @@ class UndoManager {
final transaction = historyItem.toTransaction(s);
s.apply(
transaction,
const ApplyOptions(
options: const ApplyOptions(
recordUndo: true,
recordRedo: false,
),
@@ -0,0 +1,54 @@
import 'dart:io' show Platform;
import 'package:rich_clipboard/rich_clipboard.dart';
class AppFlowyClipboardData {
const AppFlowyClipboardData({
required this.text,
required this.html,
});
final String? text;
final String? html;
}
class AppFlowyClipboard {
static Future<void> setData({
String? text,
String? html,
}) async {
// https://github.com/BringingFire/rich_clipboard/issues/13
// Wrapping a `<html><body>` tag for html in Windows,
// otherwise it will raise an exception
if (Platform.isWindows && html != null) {
if (!html.startsWith('<html><body>')) {
html = '<html><body>$html</body></html>';
}
}
return RichClipboard.setData(
RichClipboardData(
text: text,
html: html,
),
);
}
static Future<AppFlowyClipboardData> getData() async {
final data = await RichClipboard.getData();
final text = data.text;
var html = data.html;
// https://github.com/BringingFire/rich_clipboard/issues/13
// Remove all the fragment symbol in Windows.
if (Platform.isWindows && html != null) {
html = html
.replaceAll('<!--StartFragment-->', '')
.replaceAll('<!--EndFragment-->', '');
}
return AppFlowyClipboardData(
text: text,
html: html,
);
}
}
@@ -80,6 +80,8 @@ class DocumentMarkdownDecoder extends Converter<String, Document> {
BuiltInAttributeKey.subtype: BuiltInAttributeKey.quote,
},
);
} else if (text.isNotEmpty && RegExp(r'^-*').stringMatch(text) == text) {
return Node(type: 'divider');
}
if (text.isNotEmpty) {
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:appflowy_editor/src/core/document/document.dart';
import 'package:appflowy_editor/src/plugins/markdown/encoder/parser/divider_node_parser.dart';
import 'package:appflowy_editor/src/plugins/markdown/encoder/parser/image_node_parser.dart';
import 'package:appflowy_editor/src/plugins/markdown/encoder/parser/node_parser.dart';
import 'package:appflowy_editor/src/plugins/markdown/encoder/parser/text_node_parser.dart';
@@ -10,6 +11,7 @@ class DocumentMarkdownEncoder extends Converter<Document, String> {
this.parsers = const [
TextNodeParser(),
ImageNodeParser(),
DividerNodeParser(),
],
});
@@ -0,0 +1,14 @@
import 'package:appflowy_editor/src/core/document/node.dart';
import 'package:appflowy_editor/src/plugins/markdown/encoder/parser/node_parser.dart';
class DividerNodeParser extends NodeParser {
const DividerNodeParser();
@override
String get id => 'divider';
@override
String transform(Node node) {
return '---\n';
}
}
@@ -40,7 +40,7 @@ class TextNodeParser extends NodeParser {
}
} else if (subtype == 'quote') {
result = '> $markdown';
} else if (subtype == 'code-block') {
} else if (subtype == 'code_block') {
result = '```\n$markdown\n```';
} else if (subtype == 'bulleted-list') {
result = '* $markdown';
@@ -1,7 +1,7 @@
import 'package:appflowy_editor/src/core/document/node.dart';
import 'package:appflowy_editor/src/infra/clipboard.dart';
import 'package:appflowy_editor/src/service/render_plugin_service.dart';
import 'package:flutter/material.dart';
import 'package:rich_clipboard/rich_clipboard.dart';
import 'image_node_widget.dart';
@@ -21,7 +21,7 @@ class ImageNodeBuilder extends NodeWidgetBuilder<Node> {
width: width,
alignment: _textToAlignment(align),
onCopy: () {
RichClipboard.setData(RichClipboardData(text: src));
AppFlowyClipboard.setData(text: src);
},
onDelete: () {
final transaction = context.editorState.transaction
@@ -2,6 +2,7 @@ import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor/src/commands/text/text_commands.dart';
import 'package:appflowy_editor/src/extensions/url_launcher_extension.dart';
import 'package:appflowy_editor/src/flutter/overlay.dart';
import 'package:appflowy_editor/src/infra/clipboard.dart';
import 'package:appflowy_editor/src/infra/flowy_svg.dart';
import 'package:appflowy_editor/src/render/link_menu/link_menu.dart';
import 'package:appflowy_editor/src/extensions/text_node_extensions.dart';
@@ -9,7 +10,6 @@ import 'package:appflowy_editor/src/extensions/editor_state_extensions.dart';
import 'package:appflowy_editor/src/service/default_text_operations/format_rich_text_style.dart';
import 'package:flutter/material.dart' hide Overlay, OverlayEntry;
import 'package:rich_clipboard/rich_clipboard.dart';
typedef ToolbarItemEventHandler = void Function(
EditorState editorState, BuildContext context);
@@ -363,7 +363,7 @@ void showLinkMenu(
_dismissLinkMenu();
},
onCopyLink: () {
RichClipboard.setData(RichClipboardData(text: linkText));
AppFlowyClipboard.setData(text: linkText);
_dismissLinkMenu();
},
onRemoveLink: () {
@@ -16,12 +16,14 @@ class ToolbarWidget extends StatefulWidget {
required this.layerLink,
required this.offset,
required this.items,
this.aligment = Alignment.topLeft,
}) : super(key: key);
final EditorState editorState;
final LayerLink layerLink;
final Offset offset;
final List<ToolbarItem> items;
final Alignment aligment;
@override
State<ToolbarWidget> createState() => _ToolbarWidgetState();
@@ -39,6 +41,7 @@ class _ToolbarWidgetState extends State<ToolbarWidget> with ToolbarMixin {
link: widget.layerLink,
showWhenUnlinked: true,
offset: widget.offset,
followerAnchor: widget.aligment,
child: _buildToolbar(context),
),
);
@@ -1,9 +1,9 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor/src/infra/clipboard.dart';
import 'package:appflowy_editor/src/infra/html_converter.dart';
import 'package:appflowy_editor/src/core/document/node_iterator.dart';
import 'package:appflowy_editor/src/service/internal_key_event_handlers/number_list_helper.dart';
import 'package:flutter/material.dart';
import 'package:rich_clipboard/rich_clipboard.dart';
int _textLengthOfNode(Node node) {
if (node is TextNode) {
@@ -38,14 +38,15 @@ void _handleCopy(EditorState editorState) async {
startOffset: selection.start.offset,
endOffset: selection.end.offset)
.toHTMLString();
final textString = textNode.toPlainText().substring(
selection.startIndex,
selection.endIndex,
);
Log.keyboard.debug('copy html: $htmlString');
RichClipboard.setData(RichClipboardData(
AppFlowyClipboard.setData(
text: textString,
html: htmlString,
text: textNode.toPlainText().substring(
selection.startIndex,
selection.endIndex,
),
));
);
} else {
Log.keyboard.debug('unimplemented: copy non-text');
}
@@ -79,7 +80,10 @@ void _handleCopy(EditorState editorState) async {
}
text += '\n';
}
RichClipboard.setData(RichClipboardData(html: html, text: text));
AppFlowyClipboard.setData(
text: text,
html: html,
);
}
void _pasteHTML(EditorState editorState, String html) {
@@ -186,7 +190,7 @@ void _pasteMultipleLinesInText(
}
void _handlePaste(EditorState editorState) async {
final data = await RichClipboard.getData();
final data = await AppFlowyClipboard.getData();
if (editorState.cursorSelection?.isCollapsed ?? false) {
_pastRichClipboard(editorState, data);
@@ -200,7 +204,7 @@ void _handlePaste(EditorState editorState) async {
});
}
void _pastRichClipboard(EditorState editorState, RichClipboardData data) {
void _pastRichClipboard(EditorState editorState, AppFlowyClipboardData data) {
if (data.html != null) {
_pasteHTML(editorState, data.html!);
return;
@@ -388,9 +388,11 @@ class _AppFlowySelectionState extends State<AppFlowySelection>
// TODO: need to be refactored.
Offset? toolbarOffset;
Alignment? alignment;
LayerLink? layerLink;
final editorOffset =
editorState.renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final editorSize = editorState.renderBox?.size ?? Size.zero;
final backwardNodes =
selection.isBackward ? nodes : nodes.reversed.toList(growable: false);
@@ -438,10 +440,33 @@ class _AppFlowySelectionState extends State<AppFlowySelection>
// TODO: Need to compute more precise location.
if ((selectionRect.topLeft.dy - editorOffset.dy) <=
baseToolbarOffset.dy) {
toolbarOffset ??= rect.bottomLeft;
if (selectionRect.topLeft.dx <=
editorSize.width / 3.0 + editorOffset.dx) {
toolbarOffset ??= rect.bottomLeft;
alignment ??= Alignment.topLeft;
} else if (selectionRect.topRight.dx >=
editorSize.width * 2.0 / 3.0 + editorOffset.dx) {
toolbarOffset ??= rect.bottomRight;
alignment ??= Alignment.topRight;
} else {
toolbarOffset ??= rect.bottomCenter;
alignment ??= Alignment.topCenter;
}
} else {
toolbarOffset ??= rect.topLeft - baseToolbarOffset;
if (selectionRect.topLeft.dx <=
editorSize.width / 3.0 + editorOffset.dx) {
toolbarOffset ??= rect.topLeft - baseToolbarOffset;
alignment ??= Alignment.topLeft;
} else if (selectionRect.topRight.dx >=
editorSize.width * 2.0 / 3.0 + editorOffset.dx) {
toolbarOffset ??= rect.topRight - baseToolbarOffset;
alignment ??= Alignment.topRight;
} else {
toolbarOffset ??= rect.topCenter - baseToolbarOffset;
alignment ??= Alignment.topCenter;
}
}
layerLink ??= node.layerLink;
final overlay = OverlayEntry(
@@ -460,6 +485,7 @@ class _AppFlowySelectionState extends State<AppFlowySelection>
if (toolbarOffset != null && layerLink != null) {
editorState.service.toolbarService?.showInOffset(
toolbarOffset,
alignment!,
layerLink,
);
}
@@ -8,7 +8,7 @@ import 'package:appflowy_editor/src/extensions/object_extensions.dart';
abstract class AppFlowyToolbarService {
/// Show the toolbar widget beside the offset.
void showInOffset(Offset offset, LayerLink layerLink);
void showInOffset(Offset offset, Alignment alignment, LayerLink layerLink);
/// Hide the toolbar widget.
void hide();
@@ -37,7 +37,7 @@ class _FlowyToolbarState extends State<FlowyToolbar>
final _toolbarWidgetKey = GlobalKey(debugLabel: '_toolbar_widget');
@override
void showInOffset(Offset offset, LayerLink layerLink) {
void showInOffset(Offset offset, Alignment alignment, LayerLink layerLink) {
hide();
final items = _filterItems(defaultToolbarItems);
if (items.isEmpty) {
@@ -50,6 +50,7 @@ class _FlowyToolbarState extends State<FlowyToolbar>
layerLink: layerLink,
offset: offset,
items: items,
aligment: alignment,
),
);
Overlay.of(context)?.insert(_toolbarOverlay!);
@@ -157,7 +157,9 @@ class EditorWidgetTester {
document: Document(
root: _createEmptyEditorRoot(),
),
)..disableSealTimer = true;
)
..disableSealTimer = true
..disbaleRules = true;
}
}
@@ -0,0 +1,15 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor/src/plugins/markdown/encoder/parser/divider_node_parser.dart';
import 'package:flutter_test/flutter_test.dart';
void main() async {
group('divider_node_parser.dart', () {
test('parser divider node', () {
final node = Node(
type: 'divider',
);
final result = const DividerNodeParser().transform(node);
expect(result, '---\n');
});
});
}
@@ -86,7 +86,7 @@ void main() async {
final node = TextNode(
delta: Delta(operations: [TextInsert(text)]),
attributes: {
BuiltInAttributeKey.subtype: 'code-block',
BuiltInAttributeKey.subtype: 'code_block',
},
);
expect(const TextNodeParser().transform(node), '```\n$text\n```');
@@ -0,0 +1,30 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.packages
build/
@@ -0,0 +1,10 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: f1875d570e39de09040c8f79aa13cc56baab8db1
channel: unknown
project_type: package
@@ -0,0 +1,3 @@
## 0.0.1
* TODO: Describe initial release.
@@ -0,0 +1 @@
TODO: Add your license here.
@@ -0,0 +1,39 @@
<!--
This README describes the package. If you publish this package to pub.dev,
this README's contents appear on the landing page for your package.
For information about how to write a good package README, see the guide for
[writing package pages](https://dart.dev/guides/libraries/writing-package-pages).
For general information about developing packages, see the Dart guide for
[creating packages](https://dart.dev/guides/libraries/create-library-packages)
and the Flutter guide for
[developing packages and plugins](https://flutter.dev/developing-packages).
-->
TODO: Put a short description of the package here that helps potential users
know whether this package might be useful for them.
## Features
TODO: List what your package can do. Maybe include images, gifs, or videos.
## Getting started
TODO: List prerequisites and provide or point to information on how to
start using the package.
## Usage
TODO: Include short and useful examples for package users. Add longer examples
to `/example` folder.
```dart
const like = 'sample';
```
## Additional information
TODO: Tell users more about the package: where to find more information, how to
contribute to the package, how to file issues, what response they can expect
from the package authors, and more.
@@ -0,0 +1,4 @@
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
@@ -0,0 +1,12 @@
library appflowy_editor_plugins;
// Divider
export 'src/divider/divider_node_widget.dart';
export 'src/divider/divider_shortcut_event.dart';
// Math Equation
export 'src/math_ equation/math_equation_node_widget.dart';
// Code Block
export 'src/code_block/code_block_node_widget.dart';
export 'src/code_block/code_block_shortcut_event.dart';
@@ -1,93 +1,12 @@
import 'dart:collection';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:highlight/highlight.dart' as highlight;
import 'package:highlight/languages/all.dart';
ShortcutEvent enterInCodeBlock = ShortcutEvent(
key: 'Enter in code block',
command: 'enter',
handler: _enterInCodeBlockHandler,
);
ShortcutEvent ignoreKeysInCodeBlock = ShortcutEvent(
key: 'White space in code block',
command: 'space,slash,shift+underscore',
handler: _ignorekHandler,
);
ShortcutEventHandler _enterInCodeBlockHandler = (editorState, event) {
final selection = editorState.service.selectionService.currentSelection.value;
final nodes = editorState.service.selectionService.currentSelectedNodes;
final codeBlockNode =
nodes.whereType<TextNode>().where((node) => node.id == 'text/code_block');
if (codeBlockNode.length != 1 || selection == null) {
return KeyEventResult.ignored;
}
if (selection.isCollapsed) {
final transaction = editorState.transaction
..insertText(codeBlockNode.first, selection.end.offset, '\n');
editorState.apply(transaction);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
};
ShortcutEventHandler _ignorekHandler = (editorState, event) {
final nodes = editorState.service.selectionService.currentSelectedNodes;
final codeBlockNodes =
nodes.whereType<TextNode>().where((node) => node.id == 'text/code_block');
if (codeBlockNodes.length == 1) {
return KeyEventResult.skipRemainingHandlers;
}
return KeyEventResult.ignored;
};
SelectionMenuItem codeBlockMenuItem = SelectionMenuItem(
name: () => 'Code Block',
icon: (_, __) => const Icon(
Icons.abc,
color: Colors.black,
size: 18.0,
),
keywords: ['code block'],
handler: (editorState, _, __) {
final selection =
editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (selection == null || textNodes.isEmpty) {
return;
}
if (textNodes.first.toPlainText().isEmpty) {
final transaction = editorState.transaction
..updateNode(textNodes.first, {
'subtype': 'code_block',
'theme': 'vs',
'language': null,
})
..afterSelection = selection;
editorState.apply(transaction);
} else {
final transaction = editorState.transaction
..insertNode(
selection.end.path.next,
TextNode(
children: LinkedList(),
attributes: {
'subtype': 'code_block',
'theme': 'vs',
'language': null,
},
delta: Delta()..insert('\n'),
),
)
..afterSelection = selection;
editorState.apply(transaction);
}
},
);
const String kCodeBlockType = 'text/$kCodeBlockSubType';
const String kCodeBlockSubType = 'code_block';
const String kCodeBlockAttrTheme = 'theme';
const String kCodeBlockAttrLanguage = 'language';
class CodeBlockNodeWidgetBuilder extends NodeWidgetBuilder<TextNode> {
@override
@@ -101,7 +20,8 @@ class CodeBlockNodeWidgetBuilder extends NodeWidgetBuilder<TextNode> {
@override
NodeValidator<Node> get nodeValidator => (node) {
return node is TextNode && node.attributes['theme'] is String;
return node is TextNode &&
node.attributes[kCodeBlockAttrTheme] is String;
};
}
@@ -121,9 +41,11 @@ class _CodeBlockNodeWidge extends StatefulWidget {
class __CodeBlockNodeWidgeState extends State<_CodeBlockNodeWidge>
with SelectableMixin, DefaultSelectable {
final _richTextKey = GlobalKey(debugLabel: 'code_block_text');
final _padding = const EdgeInsets.only(left: 20, top: 20, bottom: 20);
String? get _language => widget.textNode.attributes['language'] as String?;
final _richTextKey = GlobalKey(debugLabel: kCodeBlockType);
final _padding = const EdgeInsets.only(left: 20, top: 30, bottom: 30);
bool _isHover = false;
String? get _language =>
widget.textNode.attributes[kCodeBlockAttrLanguage] as String?;
String? _detectLanguage;
@override
@@ -138,11 +60,20 @@ class __CodeBlockNodeWidgeState extends State<_CodeBlockNodeWidge>
@override
Widget build(BuildContext context) {
return Stack(
children: [
_buildCodeBlock(context),
_buildSwitchCodeButton(context),
],
return InkWell(
onHover: (value) {
setState(() {
_isHover = value;
});
},
onTap: () {},
child: Stack(
children: [
_buildCodeBlock(context),
_buildSwitchCodeButton(context),
if (_isHover) _buildDeleteButton(context),
],
),
);
}
@@ -177,25 +108,49 @@ class __CodeBlockNodeWidgeState extends State<_CodeBlockNodeWidge>
Widget _buildSwitchCodeButton(BuildContext context) {
return Positioned(
top: -5,
right: 0,
child: DropdownButton<String>(
value: _detectLanguage,
onChanged: (value) {
left: 10,
child: SizedBox(
height: 35,
child: DropdownButton<String>(
value: _detectLanguage,
iconSize: 14.0,
onChanged: (value) {
final transaction = widget.editorState.transaction
..updateNode(widget.textNode, {
kCodeBlockAttrLanguage: value,
});
widget.editorState.apply(transaction);
},
items:
allLanguages.keys.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(fontSize: 12.0),
),
);
}).toList(growable: false),
),
),
);
}
Widget _buildDeleteButton(BuildContext context) {
return Positioned(
top: -5,
right: -5,
child: IconButton(
icon: Icon(
Icons.delete_forever_outlined,
color: widget.editorState.editorStyle.selectionMenuItemIconColor,
size: 16,
),
onPressed: () {
final transaction = widget.editorState.transaction
..updateNode(widget.textNode, {
'language': value,
});
..deleteNode(widget.textNode);
widget.editorState.apply(transaction);
},
items: allLanguages.keys.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(fontSize: 12.0),
),
);
}).toList(growable: false),
),
);
}
@@ -0,0 +1,125 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/src/code_block/code_block_node_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
ShortcutEvent enterInCodeBlock = ShortcutEvent(
key: 'Press Enter In Code Block',
command: 'enter',
handler: _enterInCodeBlockHandler,
);
ShortcutEvent ignoreKeysInCodeBlock = ShortcutEvent(
key: 'White space in code block',
command: 'space, slash, shift+underscore',
handler: _ignorekHandler,
);
ShortcutEvent pasteInCodeBlock = ShortcutEvent(
key: 'Paste in code block',
command: 'meta+v',
windowsCommand: 'ctrl+v',
linuxCommand: 'ctrl+v',
handler: _pasteHandler,
);
ShortcutEventHandler _enterInCodeBlockHandler = (editorState, event) {
final selection = editorState.service.selectionService.currentSelection.value;
final nodes = editorState.service.selectionService.currentSelectedNodes;
final codeBlockNode =
nodes.whereType<TextNode>().where((node) => node.id == kCodeBlockType);
if (codeBlockNode.length != 1 ||
selection == null ||
!selection.isCollapsed) {
return KeyEventResult.ignored;
}
final transaction = editorState.transaction
..insertText(
codeBlockNode.first,
selection.end.offset,
'\n',
);
editorState.apply(transaction);
return KeyEventResult.handled;
};
ShortcutEventHandler _ignorekHandler = (editorState, event) {
final nodes = editorState.service.selectionService.currentSelectedNodes;
final codeBlockNodes =
nodes.whereType<TextNode>().where((node) => node.id == kCodeBlockType);
if (codeBlockNodes.length == 1) {
return KeyEventResult.skipRemainingHandlers;
}
return KeyEventResult.ignored;
};
ShortcutEventHandler _pasteHandler = (editorState, event) {
final selection = editorState.service.selectionService.currentSelection.value;
final nodes = editorState.service.selectionService.currentSelectedNodes;
final codeBlockNodes =
nodes.whereType<TextNode>().where((node) => node.id == kCodeBlockType);
if (selection != null &&
selection.isCollapsed &&
codeBlockNodes.length == 1) {
Clipboard.getData(Clipboard.kTextPlain).then((value) {
final text = value?.text;
if (text == null) return;
final transaction = editorState.transaction;
transaction.insertText(
codeBlockNodes.first,
selection.startIndex,
text,
);
editorState.apply(transaction);
});
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
};
SelectionMenuItem codeBlockMenuItem = SelectionMenuItem(
name: () => 'Code Block',
icon: (editorState, onSelected) => Icon(
Icons.abc,
color: onSelected
? editorState.editorStyle.selectionMenuItemSelectedIconColor
: editorState.editorStyle.selectionMenuItemIconColor,
size: 18.0,
),
keywords: ['code block', 'code snippet'],
handler: (editorState, _, __) {
final selection =
editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (selection == null || textNodes.isEmpty) {
return;
}
final transaction = editorState.transaction;
final textNode = textNodes.first;
if (textNode.toPlainText().isEmpty && textNode.next is TextNode) {
transaction.updateNode(textNodes.first, {
BuiltInAttributeKey.subtype: kCodeBlockSubType,
kCodeBlockAttrTheme: 'vs',
kCodeBlockAttrLanguage: null,
});
transaction.afterSelection = selection;
editorState.apply(transaction);
} else {
transaction.insertNode(
selection.end.path,
TextNode(
attributes: {
BuiltInAttributeKey.subtype: kCodeBlockSubType,
kCodeBlockAttrTheme: 'vs',
kCodeBlockAttrLanguage: null,
},
delta: Delta()..insert('\n'),
),
);
transaction.afterSelection = selection;
}
editorState.apply(transaction);
},
);
@@ -0,0 +1,84 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
const String kDividerType = 'divider';
class DividerWidgetBuilder extends NodeWidgetBuilder<Node> {
@override
Widget build(NodeWidgetContext<Node> context) {
return _DividerWidget(
key: context.node.key,
node: context.node,
editorState: context.editorState,
);
}
@override
NodeValidator<Node> get nodeValidator => (node) {
return true;
};
}
class _DividerWidget extends StatefulWidget {
const _DividerWidget({
Key? key,
required this.node,
required this.editorState,
}) : super(key: key);
final Node node;
final EditorState editorState;
@override
State<_DividerWidget> createState() => _DividerWidgetState();
}
class _DividerWidgetState extends State<_DividerWidget> with SelectableMixin {
RenderBox get _renderBox => context.findRenderObject() as RenderBox;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Container(
height: 1,
color: Colors.grey,
),
);
}
@override
Position start() => Position(path: widget.node.path, offset: 0);
@override
Position end() => Position(path: widget.node.path, offset: 1);
@override
Position getPositionInOffset(Offset start) => end();
@override
bool get shouldCursorBlink => false;
@override
CursorStyle get cursorStyle => CursorStyle.borderLine;
@override
Rect? getCursorRectInPosition(Position position) {
final size = _renderBox.size;
return Rect.fromLTWH(-size.width / 2.0, 0, size.width, size.height);
}
@override
List<Rect> getRectsInSelection(Selection selection) =>
[Offset.zero & _renderBox.size];
@override
Selection getSelectionInRange(Offset start, Offset end) => Selection.single(
path: widget.node.path,
startOffset: 0,
endOffset: 1,
);
@override
Offset localToGlobal(Offset offset) => _renderBox.localToGlobal(offset);
}
@@ -0,0 +1,72 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/src/divider/divider_node_widget.dart';
import 'package:flutter/material.dart';
// insert divider into a document by typing three minuses.
// ---
ShortcutEvent insertDividerEvent = ShortcutEvent(
key: 'Divider',
command: 'Minus',
handler: _insertDividerHandler,
);
ShortcutEventHandler _insertDividerHandler = (editorState, event) {
final selection = editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (textNodes.length != 1 || selection == null) {
return KeyEventResult.ignored;
}
final textNode = textNodes.first;
if (textNode.toPlainText() != '--') {
return KeyEventResult.ignored;
}
final transaction = editorState.transaction
..deleteText(textNode, 0, 2) // remove the existing minuses.
..insertNode(textNode.path, Node(type: kDividerType)) // insert the divder
..afterSelection = Selection.single(
// update selection to the next text node.
path: textNode.path.next,
startOffset: 0,
);
editorState.apply(transaction);
return KeyEventResult.handled;
};
SelectionMenuItem dividerMenuItem = SelectionMenuItem(
name: () => 'Divider',
icon: (editorState, onSelected) => Icon(
Icons.horizontal_rule,
color: onSelected
? editorState.editorStyle.selectionMenuItemSelectedIconColor
: editorState.editorStyle.selectionMenuItemIconColor,
size: 18.0,
),
keywords: ['horizontal rule', 'divider'],
handler: (editorState, _, __) {
final selection =
editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (textNodes.length != 1 || selection == null) {
return;
}
final textNode = textNodes.first;
// insert the divider at current path if the text node is empty.
if (textNode.toPlainText().isEmpty) {
final transaction = editorState.transaction
..insertNode(textNode.path, Node(type: kDividerType))
..afterSelection = Selection.single(
path: textNode.path.next,
startOffset: 0,
);
editorState.apply(transaction);
} else {
// insert the divider at the path next to current path if the text node is not empty.
final transaction = editorState.transaction
..insertNode(selection.end.path.next, Node(type: kDividerType))
..afterSelection = selection;
editorState.apply(transaction);
}
},
);
@@ -0,0 +1,220 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_math_fork/flutter_math.dart';
const String kMathEquationType = 'math_equation';
const String kMathEquationAttr = 'math_equation';
// TODO: l10n
SelectionMenuItem mathEquationMenuItem = SelectionMenuItem(
name: () => 'Math Equation',
icon: (editorState, onSelected) => Icon(
Icons.text_fields_rounded,
color: onSelected
? editorState.editorStyle.selectionMenuItemSelectedIconColor
: editorState.editorStyle.selectionMenuItemIconColor,
size: 18.0,
),
keywords: ['tex, latex, katex', 'math equation'],
handler: (editorState, _, __) {
final selection =
editorState.service.selectionService.currentSelection.value;
final textNodes = editorState.service.selectionService.currentSelectedNodes
.whereType<TextNode>();
if (selection == null || textNodes.isEmpty) {
return;
}
final textNode = textNodes.first;
final Path mathEquationNodePath;
if (textNode.toPlainText().isEmpty) {
mathEquationNodePath = selection.end.path;
} else {
mathEquationNodePath = selection.end.path.next;
}
// insert the math equation node
final transaction = editorState.transaction
..insertNode(
mathEquationNodePath,
Node(type: kMathEquationType, attributes: {kMathEquationAttr: ''}),
)
..afterSelection = selection;
editorState.apply(transaction);
// tricy to show the editing dialog.
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
final mathEquationState = editorState.document
.nodeAtPath(mathEquationNodePath)
?.key
?.currentState;
if (mathEquationState != null &&
mathEquationState is _MathEquationNodeWidgetState) {
mathEquationState.showEditingDialog();
}
});
},
);
class MathEquationNodeWidgetBuidler extends NodeWidgetBuilder<Node> {
@override
Widget build(NodeWidgetContext<Node> context) {
return _MathEquationNodeWidget(
key: context.node.key,
node: context.node,
editorState: context.editorState,
);
}
@override
NodeValidator<Node> get nodeValidator =>
(node) => node.attributes[kMathEquationAttr] is String;
}
class _MathEquationNodeWidget extends StatefulWidget {
const _MathEquationNodeWidget({
Key? key,
required this.node,
required this.editorState,
}) : super(key: key);
final Node node;
final EditorState editorState;
@override
State<_MathEquationNodeWidget> createState() =>
_MathEquationNodeWidgetState();
}
class _MathEquationNodeWidgetState extends State<_MathEquationNodeWidget> {
String get _mathEquation =>
widget.node.attributes[kMathEquationAttr] as String;
bool _isHover = false;
@override
Widget build(BuildContext context) {
return InkWell(
onHover: (value) {
setState(() {
_isHover = value;
});
},
onTap: () {
showEditingDialog();
},
child: Stack(
children: [
_buildMathEquation(context),
if (_isHover) _buildDeleteButton(context),
],
),
);
}
Widget _buildMathEquation(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
constraints: const BoxConstraints(minHeight: 50),
padding: const EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
color: _isHover || _mathEquation.isEmpty
? Colors.grey[200]
: Colors.transparent,
),
child: Center(
child: _mathEquation.isEmpty
? Text(
'Add a Math Equation',
style: widget.editorState.editorStyle.placeholderTextStyle,
)
: Math.tex(
_mathEquation,
textStyle: const TextStyle(fontSize: 20),
mathStyle: MathStyle.display,
),
),
);
}
Widget _buildDeleteButton(BuildContext context) {
return Positioned(
top: -5,
right: -5,
child: IconButton(
icon: Icon(
Icons.delete_forever_outlined,
color: widget.editorState.editorStyle.selectionMenuItemIconColor,
size: 16,
),
onPressed: () {
final transaction = widget.editorState.transaction
..deleteNode(widget.node);
widget.editorState.apply(transaction);
},
),
);
}
void showEditingDialog() {
showDialog(
context: context,
builder: (context) {
final controller = TextEditingController(text: _mathEquation);
return AlertDialog(
title: const Text('Edit Math Equation'),
content: RawKeyboardListener(
focusNode: FocusNode(),
onKey: (key) {
if (key is! RawKeyDownEvent) return;
if (key.logicalKey == LogicalKeyboardKey.enter &&
!key.isShiftPressed) {
_updateMathEquation(controller.text, context);
} else if (key.logicalKey == LogicalKeyboardKey.escape) {
_dismiss(context);
}
},
child: TextField(
autofocus: true,
controller: controller,
maxLines: null,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'E = MC^2',
),
),
),
actions: [
TextButton(
onPressed: () => _dismiss(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => _updateMathEquation(controller.text, context),
child: const Text('Done'),
),
],
);
},
);
}
void _updateMathEquation(String mathEquation, BuildContext context) {
if (mathEquation == _mathEquation) {
_dismiss(context);
return;
}
final transaction = widget.editorState.transaction;
transaction.updateNode(
widget.node,
{
kMathEquationAttr: mathEquation,
},
);
widget.editorState.apply(transaction);
_dismiss(context);
}
void _dismiss(BuildContext context) {
Navigator.of(context).pop();
}
}
@@ -0,0 +1,60 @@
name: appflowy_editor_plugins
description: A new Flutter package project.
version: 0.0.1
homepage: https://github.com/AppFlowy-IO/AppFlowy
publish_to: none
environment:
sdk: ">=2.17.6 <3.0.0"
flutter: ">=1.17.0"
dependencies:
flutter:
sdk: flutter
appflowy_editor:
path: ../appflowy_editor
flutter_math_fork: ^0.6.3+1
highlight: ^0.7.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# To add assets to your package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# To add custom fonts to your package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
@@ -1,78 +1,7 @@
import 'package:flowy_infra/size.dart';
import 'package:flutter/material.dart';
// preserved until deprecation
class Fonts {
static String general = "Poppins";
static String monospace = "SF Mono";
static String emoji = "Noto Color Emoji";
}
class TextStyles {
// preserved until deprecation
static TextStyle general({
double? fontSize,
FontWeight fontWeight = FontWeight.w500,
Color? color,
}) =>
TextStyle(
fontFamily: Fonts.general,
fontSize: fontSize ?? FontSizes.s12,
color: color,
fontWeight: fontWeight,
fontFamilyFallback: [Fonts.emoji],
letterSpacing: (fontSize ?? FontSizes.s12) * 0.005,
);
static TextStyle monospace({
String? fontFamily,
double? fontSize,
FontWeight fontWeight = FontWeight.w400,
}) =>
TextStyle(
fontFamily: fontFamily ?? Fonts.monospace,
fontSize: fontSize ?? FontSizes.s12,
fontWeight: fontWeight,
fontFamilyFallback: [Fonts.emoji],
);
static TextStyle get title => general(
fontSize: FontSizes.s18,
fontWeight: FontWeight.w600,
);
static TextStyle get subheading => general(
fontSize: FontSizes.s16,
fontWeight: FontWeight.w600,
);
static TextStyle get subtitle => general(
fontSize: FontSizes.s16,
fontWeight: FontWeight.w600,
);
static TextStyle get body1 => general(
fontSize: FontSizes.s12,
fontWeight: FontWeight.w500,
);
static TextStyle get body2 => general(
fontSize: FontSizes.s12,
fontWeight: FontWeight.w400,
);
static TextStyle get callout => general(
fontSize: FontSizes.s11,
fontWeight: FontWeight.w600,
);
static TextStyle get caption => general(
fontSize: FontSizes.s11,
fontWeight: FontWeight.w400,
);
final String font;
final Color color;
@@ -73,12 +73,12 @@ class AppTheme {
/// Default constructor
AppTheme({this.brightness = Brightness.light});
factory AppTheme.fromName({
required String themeName,
factory AppTheme.fromBrightness({
required Brightness brightness,
required String font,
required String monospaceFont,
}) {
switch (themeTypeFromString(themeName)) {
switch (brightness) {
case Brightness.light:
return AppTheme(brightness: Brightness.light)
..surface = Colors.white
@@ -155,13 +155,26 @@ class AppTheme {
}
}
ThemeData get themeData {
final textTheme = TextStyles(font: font, color: shader1);
ThemeData getThemeData(Locale locale) {
// Poppins and SF Mono are not well supported in some languages, so use the
// built-in font for the following languages.
final useBuiltInFontLanguages = [
const Locale('zh', 'CN'),
const Locale('zh', 'TW'),
];
TextStyles textTheme;
if (useBuiltInFontLanguages.contains(locale)) {
textTheme = TextStyles(font: '', color: shader1);
} else {
textTheme = TextStyles(font: font, color: shader1);
}
return ThemeData(
brightness: brightness,
textTheme: textTheme.generateTextTheme(),
textSelectionTheme: TextSelectionThemeData(
cursorColor: main2, selectionHandleColor: main2),
cursorColor: main2,
selectionHandleColor: main2,
),
primaryIconTheme: IconThemeData(color: hover),
iconTheme: IconThemeData(color: shader1),
scrollbarTheme: ScrollbarThemeData(
@@ -24,7 +24,7 @@ class FlowyButton extends StatelessWidget {
required this.text,
this.onTap,
this.onHover,
this.margin = const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
this.margin = const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
this.leftIcon,
this.rightIcon,
this.hoverColor,
@@ -63,6 +63,8 @@ class FlowyButton extends StatelessWidget {
children.add(Expanded(child: text));
if (rightIcon != null) {
children.add(const HSpace(10));
// No need to define the size of rightIcon. Just use its intrinsic width
children.add(rightIcon!);
}
@@ -1,6 +1,9 @@
import 'dart:async';
import 'package:flowy_infra/size.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:textstyle_extensions/textstyle_extensions.dart';
class FlowyTextField extends StatefulWidget {
final String hintText;
@@ -8,20 +11,23 @@ class FlowyTextField extends StatefulWidget {
final void Function(String)? onChanged;
final void Function(String)? onSubmitted;
final void Function()? onCanceled;
final bool autoFucous;
final bool autoFocus;
final int? maxLength;
final TextEditingController? controller;
final bool autoClearWhenDone;
final Duration? debounceDuration;
const FlowyTextField({
this.hintText = "",
this.text = "",
this.onChanged,
this.onSubmitted,
this.onCanceled,
this.autoFucous = true,
this.autoFocus = true,
this.maxLength,
this.controller,
this.autoClearWhenDone = false,
this.debounceDuration,
Key? key,
}) : super(key: key);
@@ -32,7 +38,7 @@ class FlowyTextField extends StatefulWidget {
class FlowyTextFieldState extends State<FlowyTextField> {
late FocusNode focusNode;
late TextEditingController controller;
var textLength = 0;
Timer? _debounceOnChanged;
@override
void initState() {
@@ -45,7 +51,7 @@ class FlowyTextFieldState extends State<FlowyTextField> {
controller = TextEditingController();
controller.text = widget.text;
}
if (widget.autoFucous) {
if (widget.autoFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
focusNode.requestFocus();
});
@@ -53,27 +59,47 @@ class FlowyTextFieldState extends State<FlowyTextField> {
super.initState();
}
void _debounceOnChangedText(Duration duration, String text) {
_debounceOnChanged?.cancel();
_debounceOnChanged = Timer(duration, () async {
if (mounted) {
_onChanged(text);
}
});
}
void _onChanged(String text) {
widget.onChanged?.call(text);
setState(() {});
}
void _onSubmitted(String text) {
widget.onSubmitted?.call(text);
if (widget.autoClearWhenDone) {
controller.text = "";
}
}
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
focusNode: focusNode,
onChanged: (text) {
widget.onChanged?.call(text);
},
onSubmitted: (text) {
widget.onSubmitted?.call(text);
if (widget.autoClearWhenDone) {
controller.text = "";
if (widget.debounceDuration != null) {
_debounceOnChangedText(widget.debounceDuration!, text);
} else {
_onChanged(text);
}
},
onSubmitted: (text) => _onSubmitted(text),
maxLines: 1,
maxLength: widget.maxLength,
maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds,
style: Theme.of(context).textTheme.bodySmall,
style: Theme.of(context).textTheme.bodyMedium,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
@@ -83,6 +109,10 @@ class FlowyTextFieldState extends State<FlowyTextField> {
),
isDense: true,
hintText: widget.hintText,
hintStyle: Theme.of(context)
.textTheme
.bodySmall!
.textColor(Theme.of(context).hintColor),
suffixText: _suffixText(),
counterText: "",
focusedBorder: OutlineInputBorder(
@@ -115,7 +145,7 @@ class FlowyTextFieldState extends State<FlowyTextField> {
String? _suffixText() {
if (widget.maxLength != null) {
return '${textLength.toString()}/${widget.maxLength.toString()}';
return ' ${controller.text.length}/${widget.maxLength}';
} else {
return null;
}
+22 -1
View File
@@ -36,6 +36,13 @@ packages:
relative: true
source: path
version: "0.0.7"
appflowy_editor_plugins:
dependency: "direct main"
description:
path: "packages/appflowy_editor_plugins"
relative: true
source: path
version: "0.0.1"
appflowy_popover:
dependency: "direct main"
description:
@@ -471,6 +478,13 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_math_fork:
dependency: transitive
description:
name: flutter_math_fork
url: "https://pub.dartlang.org"
source: hosted
version: "0.6.3+1"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
@@ -556,6 +570,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
highlight:
dependency: transitive
description:
name: highlight
url: "https://pub.dartlang.org"
source: hosted
version: "0.7.0"
hotkey_manager:
dependency: "direct main"
description:
@@ -1402,5 +1423,5 @@ packages:
source: hosted
version: "3.1.1"
sdks:
dart: ">=2.17.0 <3.0.0"
dart: ">=2.17.6 <3.0.0"
flutter: ">=3.0.0"
+2
View File
@@ -91,6 +91,8 @@ dependencies:
google_fonts: ^3.0.1
file_picker: <=5.0.0
percent_indicator: ^4.0.1
appflowy_editor_plugins:
path: packages/appflowy_editor_plugins
dev_dependencies:
flutter_lints: ^2.0.1
@@ -133,35 +133,35 @@ void main() {
workspaceSetting.latestView.id == document1.id;
});
test('open latest grid test', () async {
test('open latest document test', () async {
final app = await testContext.createTestApp();
final bloc = AppBloc(app: app)..add(const AppEvent.initial());
await blocResponseFuture();
bloc.add(AppEvent.createView("grid 1", GridPluginBuilder()));
bloc.add(AppEvent.createView("document 1", DocumentPluginBuilder()));
await blocResponseFuture();
final grid1 = bloc.state.latestCreatedView;
assert(grid1!.name == "grid 1");
final document = bloc.state.latestCreatedView;
assert(document!.name == "document 1");
bloc.add(AppEvent.createView("grid 2", GridPluginBuilder()));
await blocResponseFuture();
final grid2 = bloc.state.latestCreatedView;
assert(grid2!.name == "grid 2");
final grid = bloc.state.latestCreatedView;
assert(grid!.name == "grid 2");
var workspaceSetting = await FolderEventReadCurrentWorkspace()
.send()
.then((result) => result.fold((l) => l, (r) => throw Exception()));
workspaceSetting.latestView.id == grid1!.id;
workspaceSetting.latestView.id == grid!.id;
// Open grid 1
// ignore: unused_local_variable
final documentBloc = DocumentBloc(view: grid1)
final documentBloc = DocumentBloc(view: document!)
..add(const DocumentEvent.initial());
await blocResponseFuture();
workspaceSetting = await FolderEventReadCurrentWorkspace()
.send()
.then((result) => result.fold((l) => l, (r) => throw Exception()));
workspaceSetting.latestView.id == grid1.id;
workspaceSetting.latestView.id == document.id;
});
}
+61 -34
View File
@@ -84,6 +84,17 @@ dependencies = [
"syn",
]
[[package]]
name = "async-trait"
version = "0.1.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31e6e93155431f3931513b243d371981bb2770112b370c82745a1d19d2f99364"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "atomic"
version = "0.5.1"
@@ -570,10 +581,10 @@ dependencies = [
"crossbeam-utils",
"dart-notify",
"ffi-support",
"flowy-codegen",
"flowy-derive",
"flowy-sdk",
"lib-dispatch",
"lib-infra",
"log",
"once_cell",
"protobuf",
@@ -588,10 +599,10 @@ version = "0.1.0"
dependencies = [
"allo-isolate",
"bytes",
"flowy-codegen",
"flowy-derive",
"lazy_static",
"lib-dispatch",
"lib-infra",
"log",
"protobuf",
]
@@ -816,6 +827,30 @@ dependencies = [
"syn",
]
[[package]]
name = "flowy-codegen"
version = "0.1.0"
dependencies = [
"cmd_lib",
"console",
"fancy-regex",
"flowy-ast",
"itertools",
"lazy_static",
"log",
"phf 0.8.0",
"protoc-bin-vendored",
"protoc-rust",
"quote",
"serde",
"serde_json",
"similar",
"syn",
"tera",
"toml",
"walkdir",
]
[[package]]
name = "flowy-database"
version = "0.1.0"
@@ -834,8 +869,8 @@ version = "0.1.0"
dependencies = [
"dashmap",
"flowy-ast",
"flowy-codegen",
"lazy_static",
"lib-infra",
"proc-macro2",
"quote",
"serde_json",
@@ -857,6 +892,7 @@ dependencies = [
"derive_more",
"diesel",
"diesel_derives",
"flowy-codegen",
"flowy-database",
"flowy-derive",
"flowy-document",
@@ -891,13 +927,13 @@ name = "flowy-error"
version = "0.1.0"
dependencies = [
"bytes",
"flowy-codegen",
"flowy-database",
"flowy-derive",
"flowy-error-code",
"flowy-sync",
"http-flowy",
"lib-dispatch",
"lib-infra",
"lib-ot",
"lib-sqlite",
"protobuf",
@@ -910,8 +946,8 @@ name = "flowy-error-code"
version = "0.1.0"
dependencies = [
"derive_more",
"flowy-codegen",
"flowy-derive",
"lib-infra",
"protobuf",
]
@@ -923,6 +959,7 @@ dependencies = [
"dart-notify",
"diesel",
"diesel_derives",
"flowy-codegen",
"flowy-database",
"flowy-derive",
"flowy-document",
@@ -965,6 +1002,7 @@ dependencies = [
"dashmap",
"diesel",
"fancy-regex",
"flowy-codegen",
"flowy-database",
"flowy-derive",
"flowy-error",
@@ -1002,6 +1040,7 @@ name = "flowy-http-model"
version = "0.1.0"
dependencies = [
"bytes",
"flowy-codegen",
"flowy-derive",
"lib-infra",
"md5",
@@ -1017,6 +1056,7 @@ dependencies = [
"bytes",
"config",
"dashmap",
"flowy-codegen",
"flowy-derive",
"flowy-document",
"flowy-error",
@@ -1056,6 +1096,7 @@ dependencies = [
"flowy-error",
"flowy-http-model",
"flowy-revision",
"futures",
"futures-util",
"lib-infra",
"lib-ws",
@@ -1178,6 +1219,7 @@ dependencies = [
"diesel_derives",
"fake",
"fancy-regex",
"flowy-codegen",
"flowy-database",
"flowy-derive",
"flowy-error",
@@ -1738,29 +1780,13 @@ dependencies = [
name = "lib-infra"
version = "0.1.0"
dependencies = [
"async-trait",
"bytes",
"chrono",
"cmd_lib",
"console",
"fancy-regex",
"flowy-ast",
"futures-core",
"itertools",
"lazy_static",
"log",
"phf 0.8.0",
"pin-project",
"protoc-bin-vendored",
"protoc-rust",
"rand 0.8.5",
"serde",
"serde_json",
"similar",
"syn",
"tera",
"tokio",
"toml",
"walkdir",
]
[[package]]
@@ -1827,6 +1853,7 @@ version = "0.1.0"
dependencies = [
"bytes",
"dashmap",
"flowy-codegen",
"flowy-derive",
"futures",
"futures-channel",
@@ -2455,11 +2482,11 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]]
name = "proc-macro2"
version = "1.0.36"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
dependencies = [
"unicode-xid",
"unicode-ident",
]
[[package]]
@@ -3141,13 +3168,13 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.85"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a684ac3dcd8913827e18cd09a68384ee66c1de24157e3c556c9ab16d85695fb7"
checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
"unicode-ident",
]
[[package]]
@@ -3588,6 +3615,12 @@ version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a01404663e3db436ed2746d9fefef640d868edae3cceb81c3b8d5732fda678f"
[[package]]
name = "unicode-ident"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]]
name = "unicode-normalization"
version = "0.1.19"
@@ -3609,12 +3642,6 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"
[[package]]
name = "unicode-xid"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "url"
version = "2.2.2"
+3 -2
View File
@@ -37,6 +37,7 @@ http_sync = ["flowy-sdk/http_sync", "flowy-sdk/use_bunyan"]
openssl_vendored = ["flowy-sdk/openssl_vendored"]
[build-dependencies]
lib-infra = { path = "../../../shared-lib/lib-infra", features = [
flowy-codegen= { path = "../../../shared-lib/flowy-codegen", features = [
"dart",
] }
]}
+1 -3
View File
@@ -1,5 +1,3 @@
use lib_infra::code_gen;
fn main() {
code_gen::protobuf_file::gen(env!("CARGO_PKG_NAME"));
flowy_codegen::protobuf_file::gen(env!("CARGO_PKG_NAME"));
}
+5 -5
View File
@@ -31,7 +31,7 @@ pub extern "C" fn init_sdk(path: *mut c_char) -> i64 {
#[no_mangle]
pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
let request: ModuleRequest = FFIRequest::from_u8_pointer(input, len).into();
let request: AFPluginRequest = FFIRequest::from_u8_pointer(input, len).into();
log::trace!(
"[FFI]: {} Async Event: {:?} with {} port",
&request.id,
@@ -46,7 +46,7 @@ pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
}
Some(e) => e.event_dispatcher.clone(),
};
let _ = EventDispatcher::async_send_with_callback(dispatcher, request, move |resp: EventResponse| {
let _ = AFPluginDispatcher::async_send_with_callback(dispatcher, request, move |resp: AFPluginEventResponse| {
log::trace!("[FFI]: Post data to dart through {} port", port);
Box::pin(post_to_flutter(resp, port))
});
@@ -54,7 +54,7 @@ pub extern "C" fn async_event(port: i64, input: *const u8, len: usize) {
#[no_mangle]
pub extern "C" fn sync_event(input: *const u8, len: usize) -> *const u8 {
let request: ModuleRequest = FFIRequest::from_u8_pointer(input, len).into();
let request: AFPluginRequest = FFIRequest::from_u8_pointer(input, len).into();
log::trace!("[FFI]: {} Sync Event: {:?}", &request.id, &request.event,);
let dispatcher = match FLOWY_SDK.get() {
@@ -64,7 +64,7 @@ pub extern "C" fn sync_event(input: *const u8, len: usize) -> *const u8 {
}
Some(e) => e.event_dispatcher.clone(),
};
let _response = EventDispatcher::sync_send(dispatcher, request);
let _response = AFPluginDispatcher::sync_send(dispatcher, request);
// FFIResponse { }
let response_bytes = vec![];
@@ -83,7 +83,7 @@ pub extern "C" fn set_stream_port(port: i64) -> i32 {
pub extern "C" fn link_me_please() {}
#[inline(always)]
async fn post_to_flutter(response: EventResponse, port: i64) {
async fn post_to_flutter(response: AFPluginEventResponse, port: i64) {
let isolate = allo_isolate::Isolate::new(port);
match isolate
.catch_unwind(async {
@@ -1,6 +1,6 @@
use bytes::Bytes;
use flowy_derive::ProtoBuf;
use lib_dispatch::prelude::ModuleRequest;
use lib_dispatch::prelude::AFPluginRequest;
use std::convert::TryFrom;
#[derive(Default, ProtoBuf)]
@@ -21,8 +21,8 @@ impl FFIRequest {
}
}
impl std::convert::From<FFIRequest> for ModuleRequest {
impl std::convert::From<FFIRequest> for AFPluginRequest {
fn from(ffi_request: FFIRequest) -> Self {
ModuleRequest::new(ffi_request.event).payload(ffi_request.payload)
AFPluginRequest::new(ffi_request.event).payload(ffi_request.payload)
}
}
@@ -1,5 +1,5 @@
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use lib_dispatch::prelude::{EventResponse, Payload, StatusCode};
use lib_dispatch::prelude::{AFPluginEventResponse, Payload, StatusCode};
#[derive(ProtoBuf_Enum, Clone, Copy)]
pub enum FFIStatusCode {
@@ -23,8 +23,8 @@ pub struct FFIResponse {
code: FFIStatusCode,
}
impl std::convert::From<EventResponse> for FFIResponse {
fn from(resp: EventResponse) -> Self {
impl std::convert::From<AFPluginEventResponse> for FFIResponse {
fn from(resp: AFPluginEventResponse) -> Self {
let payload = match resp.payload {
Payload::Bytes(bytes) => bytes.to_vec(),
Payload::None => vec![],
+2 -2
View File
@@ -16,7 +16,7 @@ flowy-derive = {path = "../../../shared-lib/flowy-derive" }
lib-dispatch = {path = "../lib-dispatch" }
[features]
dart = ["lib-infra/dart"]
dart = ["flowy-codegen/dart"]
[build-dependencies]
lib-infra = { path = "../../../shared-lib/lib-infra", features = ["proto_gen"] }
flowy-codegen= { path = "../../../shared-lib/flowy-codegen"}
+1 -3
View File
@@ -1,5 +1,3 @@
use lib_infra::code_gen;
fn main() {
code_gen::protobuf_file::gen(env!("CARGO_PKG_NAME"));
flowy_codegen::protobuf_file::gen(env!("CARGO_PKG_NAME"));
}
@@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE grid_rev_snapshot;
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff. Show more