Compare commits

...
40 Commits
Author SHA1 Message Date
c3bfae866b chore: bump version 0.7.7 (#6951)
* feat: add same delete design in database (#6620)

* add same delete design in database

* fix: remove padding when widget is null or function is null

* fix(desktop): resize sidebar menu regression (#6897)

* fix: initial ai chat load (#6920)

* fix: unable to open local file using afLaunchUrl function (#6927)

* fix: unable to open local file using afLaunchUrl function

* chore: use the latest api to open the local file

* chore: use the latest api to open the local file

* chore: use the latest api to open the local file

* test: add local paht regex test

* fix(flutter): implement mention date transaction handler (#6933)

* fix: implement mention date transaction handler

* test: add integration tests

* chore: code cleanup

* chore: early return if null delta

* fix(flutter_desktop): clicking on empty space when editing a cell sho… (#6949)

* fix(flutter_desktop): clicking on empty space when editing a cell shouldn't close event card

* test: fix integration tests

* chore: bump version 0.7.7

* fix: hotfix issues for v0.7.7 (#6948)

* fix: include link preview block and file block in exported markdown

* test: include link preview block and file block in exported markdown

* chore: remove unused logs

* chore: update editor version

* fix: "+" menu should be close after pressing space

* test: cancel inline page reference menu by space

* chore: update editor version

* chore: remove unused logs

---------

Co-authored-by: Ahad Patel <69256193+Ahad-patel@users.noreply.github.com>
Co-authored-by: Richard Shiue <71320345+richardshiue@users.noreply.github.com>
2024-12-09 17:50:45 +08:00
Lucas.Xu d3c7d4b1d2 Revert "fix: hotfix issues for v0.7.7 (#6948)"
This reverts commit 8726df703e.
2024-12-09 16:21:12 +08:00
Lucas 8726df703e fix: hotfix issues for v0.7.7 (#6948)
* fix: include link preview block and file block in exported markdown

* test: include link preview block and file block in exported markdown

* chore: remove unused logs

* chore: update editor version

* fix: "+" menu should be close after pressing space

* test: cancel inline page reference menu by space

* chore: update editor version

* chore: remove unused logs
2024-12-09 16:20:36 +08:00
nathan 3fdd19f7a2 chore: do not pull object when object ids is empty 2024-12-09 15:17:11 +08:00
Lucas.Xu fb132cb4b8 chore: upgrade rust version to 1.80.1 2024-12-03 21:06:51 +08:00
Lucas e32c584b3b fix: remove extra padding in table on mobile (#6915) 2024-12-03 20:41:52 +08:00
Lucas 64e4416f54 chore: release version 0.7.6 (#6910)
* chore: update changelog

* feat: support displaying text color, background color and font item in table cell

* fix: integration test and unit test
2024-12-03 17:27:59 +08:00
Nathan.fooo ca195887e0 chore: bump collab (#6914)
* chore: bump collab

* chore: bump collab
2024-12-03 17:05:40 +08:00
Kilu.He f9a5458b94 feat: support simple table (#6911) 2024-12-03 15:33:51 +08:00
Lucas 244d072a65 fix: pressing enter on a collapsible list toggle adds an additional new line (#6909)
* fix: pressing Enter on a closed toggle list adds an additional new line

* test: pressing Enter on a closed toggle list adds an additional new line

* chore: upgrade appflowy_editor

* chore: rename table align
2024-12-03 13:56:15 +08:00
Lucas d9bc97e012 chore: remove rename dialog logic (#6906) 2024-12-02 20:01:40 +08:00
LucasandRichard Shiue e7491e5182 feat: simple table issues (#6871)
* fix: disable cut command in table cell

* feat: only keep the table cell content when coping text from table

* fix: focus on the first cell after inserting table

* test: focus on the first cell after inserting table

* feat: highlight the cell when editing

* test: highlight the cell when editing

* fix: creating a new row makes a cursor appear for a fraction of a second

* fix: add 4px between scroll bar and add row button

* chore: rename simple table components

* fix: select all in table cell block

* test: select all in table cell block

* feat: disable two-fingers resize in table cell

* feat: includ table when exporting markdown

* test: include table when exporting markdown

* feat: optimize add row button render logic

* chore: optimize hover button render logic

* fix: column button is not clickable

* fix: theme assertion

* feat: improve hovering logic

* fix: selection issue in table

* fix(flutter_desktop): popover conflicts on simple table

* feat: support table markdown import

* test: table cell isEditing test

* test: select all in table test

* fix: popover conflict in table action menu

* test: insert row, column, row/column in table

* test: delete row, column, row/column in table

* test: enable header column and header row in table

* test: duplicate/insert left/right/above/below in table

* chore: duplicate table in optin menu

* fix: integraion test

---------

Co-authored-by: Richard Shiue <71320345+richardshiue@users.noreply.github.com>
2024-12-02 17:50:32 +08:00
promto-c 550b8835c6 chore: update th-TH translations (#6898) 2024-12-02 14:42:40 +08:00
Mathias Mogensen 1851721d9a fix: tabs lr 0.7.6 (#6899)
* fix: tabs improvements launch review

* test: add tests for pin/unpin feature

* fix: failing test + cleanup
2024-12-02 00:52:36 +01:00
Mathias Mogensen 603d65a790 fix: mobile camera android permission (#6900) 2024-12-02 00:49:54 +01:00
Richard Shiue 0cba3f9e3f fix(mobile): lost initial scroll position on empty ai chat page (#6895) 2024-12-01 13:18:20 +08:00
promto-c 81960a7f05 chore(i18n): add th-TH translations (#6891)
* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦
2024-11-30 21:17:30 +08:00
Lucas 62c4a8c541 fix: unable to render code block in ai writer block (#6883)
* fix: unable to render code block in ai writer block

* feat: enter to generate ai result
2024-11-29 18:49:47 +08:00
Richard Shiueandnathan 510d8357ee fix: RwLock race condition during group controller instantiation (#6860)
* chore: code cleanup

* fix: view editor used during initialization

* fix: quick and dirty hack job

* test: add test

* chore: don't create separate mut var

* chore: docs

* fix: uninitialized group controllers

* chore: remove group

* chore: fix test

---------

Co-authored-by: nathan <nathan@appflowy.io>
2024-11-28 17:26:13 +08:00
Mathias Mogensen 4c6f6f14f3 fix: add camera permission for iOS (#6872) 2024-11-28 10:17:24 +01:00
Lucas 27af57289f chore: update version to 0.7.6 (#6870) 2024-11-28 14:04:22 +08:00
Lucas 17aa8c9036 feat: simple table redesign (#6831)
* feat: define the simple table block data strucuture

* fix: close keyboard when uploading file

* feat: integrate a simple table

* feat: support selectable mixin for table

* feat: render border for table

* feat: support add column/row

* feat: support add column and row

* feat: support add column and row button

* feat: support table border and cell border

* feat: use context to manage hovering status

* feat: add hover status for cell

* feat: add hover row action

* feat: support row/column hover action

* feat: support table more actions

* feat: support insert left/right/above/below actions

* feat: add reorder button

* feat: clear content in table

* feat: support header column and header row

* chore: refactor the table more actions

* feat: render border in cell

* feat: add align button

* feat: add align menu

* fix: unable to delete last column

* feat: support drag to resize

* feat: support resizing column and set limitation

* fix: unable to resize

* feat: support table cell align

* fix: type error

* feat: support table cell background color

* fix: enable header column/row bug

* feat: support table background color

* feat: support duplicate table without background color

* feat: support duplicate with column color

* feat: update column width

* feat: move insert operations to a new file

* fix: row more action position is not correct

* fix: delete row error

* feat: support highlight the border after selecting a column/row

* feat: support mapping the insertion color/align

* feat: support mapping the duplication color/align

* fix: delete column error

* feat: support duplication map

* feat: support duplicating column with color and align

* feat: support duplicating row with color and align

* chore: optimize the table_map_operations

* feat: support clear content / header / style operations

* chore: remove null value in table attributes

* fix: delete row issues

* fix: delete column issues

* fix: unable to clear content

* feat: support arrow key shortcuts

* feat: support tab shortcuts

* feat: support backspace key shortcuts

* feat: support table block selection

* feat: set text in header column / row to bold

* fix: flutter analyze

* chore: enable debug log in table

* test: simple table insert operation

* test: simple table delete operation

* test: simple table header operation

* test: simple table style operation - column width

* test: simple table style operation - background color and align

* test: simple table content operation - clear content

* test: simple table operations - insertion, deletion and duplication

* test: simple table operations - duplicate with background and align

* fix: hide the delete button if there is only one column or one row

* test: add integration test and i18n

* chore: update translations

* fix: drag visual issue

* fix: exclude the popup menu in table more actions

* feat: only show the add button when hovering on the edge
2024-11-28 13:58:00 +08:00
Mathias Mogensen c910bda534 fix: minor improvements to media interactions (#6867)
* fix: minor improvements to media interactions

* test: remove redundant test
2024-11-28 02:13:06 +01:00
Mathias Mogensen 8d01b96281 feat: pin tabs (#6869) 2024-11-28 01:20:47 +01:00
Mathias Mogensen 55f12d5358 feat: attachment mobile toolbar item (#6868) 2024-11-28 01:20:30 +01:00
Mathias Mogensen 018c146d72 fix: built in database height issue (#6866)
* fix: built in database height issue

* fix: use shrinkWrap to decide height

* fix: pageview for lazy rendering
2024-11-27 15:37:45 +01:00
Lucas 068ac0e992 feat: support markdown syntax in ai writer block (#6864)
* feat: support markdown syntax in ai writer block

* feat: support nested list

* test: add markdown text robot tests

* feat: support in-memory update in ai-writer block

* feat: support markdown in ask ai block

* feat: render ai result with appflowy_editor

* feat: support markdown syntax in ask ai block

* fix: selection after replace
2024-11-27 21:19:24 +08:00
Lucas b036129efb fix: multiple select menu display issue (#6861)
* chore: set the minimum windows size to 640

* feat: optimize text insertion

* fix: unable to scroll down in multiple select options
2024-11-27 09:56:28 +08:00
Richard Shiue b3c8eb151a chore: improve ai chat errors (#6851)
* chore: move margins to layout define

* chore: related question alignment

* chore: adjust vertical spacing around sources

* chore: scroll to bottom animation improvement

* chore: improve ai chat error handling
2024-11-25 18:45:59 +08:00
Lucas e86d584ea7 feat: support skipping in-memory update transaction (#6856)
* feat: support skipping in-memory update transaction

* fix: flutter analyze

* feat: add sentence mode

* test: support skipping in-memory update transaction

* test: add sentence mode

* test: add sentence mode (2)

* chore: set enableDocumentInternalLog to false

* fix: integration test

* fix: integration test
2024-11-25 17:55:15 +08:00
Richard Shiue e0226e54a5 chore: minor ai chat improvements (#6855)
* chore: animation alignment improvement

* fix: missing context in drop zone

* chore: increase minimum padding between chat and edge of screen

* chore: unify padding for ai message loading
2024-11-25 10:43:08 +08:00
Lucas bde1457524 feat: support click to create content inside empty toggle list (#6854)
* feat: support click to create content inside empty toggle list

* test: support click to create content inside empty toggle list

* fix: toggle list rtl issue

* chore: optimize cover title request node logic
2024-11-25 10:39:23 +08:00
Lucas 2ad2a79bd0 fix: macOS error 50 on uploading files (#6853) 2024-11-25 10:39:15 +08:00
Richard Shiue f013bb9d6e chore: re-add chat message animations (#6850)
* chore: re-add chat message animation

* chore: bump up message vertical padding
2024-11-24 22:43:45 +08:00
Nathan.fooo 1b4a723500 chore: only fetch billing info when current user is the workspace owner (#6847) 2024-11-23 13:25:42 +08:00
Nathan.fooo b5d2af3371 chore: parse chat response (#6843)
* chore: parse chat response

* chore: remove unrelated message

* chore: update readme
2024-11-23 09:48:24 +08:00
Nathan.fooo 4205a34f04 chore: delete upload task when upload size exceed limit (#6841)
* chore: delete upload tasks

* test: update

* chore: bump client api

* chore: fix test
2024-11-22 18:18:24 +08:00
Richard Shiue e86a9d697c chore: simplify chat user message bloc and widgets (#6836) 2024-11-20 13:13:38 +03:00
Richard Shiue f82dabcc75 chore: bump flutter chat ui version (#6835) 2024-11-20 15:47:35 +08:00
Mathias Mogensen 09717d92c5 chore: inno setup ignore version on .exe (#6745) 2024-11-20 10:03:57 +08:00
299 changed files with 16336 additions and 3585 deletions

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ on:
env:
FLUTTER_VERSION: "3.22.0"
RUST_TOOLCHAIN: "1.77.2"
RUST_TOOLCHAIN: "1.80.1"
jobs:
create-release:
+1 -1
View File
@@ -19,7 +19,7 @@ on:
env:
CARGO_TERM_COLOR: always
CLOUD_VERSION: 0.7.6-amd64
RUST_TOOLCHAIN: "1.77.2"
RUST_TOOLCHAIN: "1.80.1"
jobs:
self-hosted-job:
+1 -1
View File
@@ -11,7 +11,7 @@ on:
env:
CARGO_TERM_COLOR: always
FLUTTER_VERSION: "3.22.0"
RUST_TOOLCHAIN: "1.77.2"
RUST_TOOLCHAIN: "1.80.1"
jobs:
tests:
+2 -2
View File
@@ -11,7 +11,7 @@ on:
env:
NODE_VERSION: "18.16.0"
PNPM_VERSION: "8.5.0"
RUST_TOOLCHAIN: "1.77.2"
RUST_TOOLCHAIN: "1.80.1"
CARGO_MAKE_VERSION: "0.36.6"
CI: true
@@ -121,4 +121,4 @@ jobs:
with:
tauriScript: pnpm tauri
projectPath: frontend/appflowy_web_app
args: "--debug"
args: "--debug"
+3 -3
View File
@@ -7,7 +7,7 @@ on:
env:
NODE_VERSION: "18.16.0"
PNPM_VERSION: "8.5.0"
RUST_TOOLCHAIN: "1.77.2"
RUST_TOOLCHAIN: "1.80.1"
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
@@ -19,7 +19,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ ubuntu-20.04 ]
platform: [ubuntu-20.04]
runs-on: ${{ matrix.platform }}
@@ -108,4 +108,4 @@ jobs:
with:
tauriScript: pnpm tauri
projectPath: frontend/appflowy_tauri
args: "--debug"
args: "--debug"
+5 -6
View File
@@ -4,20 +4,19 @@ on:
workflow_dispatch:
inputs:
branch:
description: 'The branch to release'
description: "The branch to release"
required: true
default: 'main'
default: "main"
version:
description: 'The version to release'
description: "The version to release"
required: true
default: '0.0.0'
default: "0.0.0"
env:
NODE_VERSION: "18.16.0"
PNPM_VERSION: "8.5.0"
RUST_TOOLCHAIN: "1.77.2"
RUST_TOOLCHAIN: "1.80.1"
jobs:
publish-tauri:
permissions:
contents: write
+22 -1
View File
@@ -1,5 +1,26 @@
# Release Notes
# Release Notes
## Version 0.7.6 - 03/12/2024
### Bug Fixes
## Version 0.7.6 - 03/12/2024
### New Features
- Revamped the simple table UI
- Added support for capturing images from camera on mobile
### Bug Fixes
- Improved markdown rendering capabilities in AI writer
- Fixed an issue where pressing Enter on a collapsed toggle list would add an unnecessary new line
- Fixed an issue where creating a document from slash menu could insert content at incorrect position
## Version 0.7.5 - 25/11/2024
### Bug Fixes
- Improved chat response parsing
- Fixed toggle list icon direction for RTL mode
- Fixed cross blocks formatting not reflecting in float toolbar
- Fixed unable to click inside the toggle list to create a new paragraph
- Fixed open file error 50 on macOS
- Fixed upload file exceed limit error
## Version 0.7.4 - 19/11/2024
### New Features
- Support uploading WebP and BMP images
+48 -17
View File
@@ -42,10 +42,12 @@ AppFlowy is the AI workspace where you achieve more without losing control of yo
## User Installation
- [Download AppFlowy Desktop (macOS, Windows, and Linux)](https://github.com/AppFlowy-IO/AppFlowy/releases)
- Other channels: [FlatHub](https://flathub.org/apps/io.appflowy.AppFlowy), [Snapcraft](https://snapcraft.io/appflowy), [Sourceforge](https://sourceforge.net/projects/appflowy/)
- Other
channels: [FlatHub](https://flathub.org/apps/io.appflowy.AppFlowy), [Snapcraft](https://snapcraft.io/appflowy), [Sourceforge](https://sourceforge.net/projects/appflowy/)
- Available on
- [App Store](https://apps.apple.com/app/appflowy/id6457261352): iPhone
- [Play Store](https://play.google.com/store/apps/details?id=io.appflowy.appflowy): Android 10 or above; ARMv7 is not supported
- [App Store](https://apps.apple.com/app/appflowy/id6457261352): iPhone
- [Play Store](https://play.google.com/store/apps/details?id=io.appflowy.appflowy): Android 10 or above; ARMv7 is
not supported
- [Self-hosting AppFlowy](https://docs.appflowy.io/docs/guides/appflowy/self-hosting-appflowy)
- [Source](https://docs.appflowy.io/docs/documentation/appflowy/from-source)
@@ -61,15 +63,18 @@ AppFlowy is the AI workspace where you achieve more without losing control of yo
## Getting Started with development
Please view the [documentation](https://docs.appflowy.io/docs/documentation/appflowy/from-source) for OS specific development instructions
Please view the [documentation](https://docs.appflowy.io/docs/documentation/appflowy/from-source) for OS specific
development instructions
## Roadmap
- [AppFlowy Roadmap ReadMe](https://docs.appflowy.io/docs/appflowy/roadmap)
- [AppFlowy Public Roadmap](https://github.com/orgs/AppFlowy-IO/projects/5/views/12)
If you'd like to propose a feature, submit a feature request [here](https://github.com/AppFlowy-IO/AppFlowy/issues/new?assignees=&labels=&template=feature_request.yaml&title=%5BFR%5D+) <br/>
If you'd like to report a bug, submit a bug report [here](https://github.com/AppFlowy-IO/AppFlowy/issues/new?assignees=&labels=&template=bug_report.yaml&title=%5BBug%5D+)
If you'd like to propose a feature, submit a feature
request [here](https://github.com/AppFlowy-IO/AppFlowy/issues/new?assignees=&labels=&template=feature_request.yaml&title=%5BFR%5D+) <br/>
If you'd like to report a bug, submit a bug
report [here](https://github.com/AppFlowy-IO/AppFlowy/issues/new?assignees=&labels=&template=bug_report.yaml&title=%5BBug%5D+)
## **Releases**
@@ -77,16 +82,24 @@ Please see the [changelog](https://www.appflowy.io/whatsnew) for more details ab
## Contributing
Contributions make the open-source community a fantastic place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. Please look at [Contributing to AppFlowy](https://docs.appflowy.io/docs/documentation/software-contributions/contributing-to-appflowy) for details.
Contributions make the open-source community a fantastic place to learn, inspire, and create. Any contributions you make
are **greatly appreciated**. Please look
at [Contributing to AppFlowy](https://docs.appflowy.io/docs/documentation/software-contributions/contributing-to-appflowy)
for details.
If your Pull Request is accepted as it fixes a bug, adds functionality, or makes AppFlowy's codebase significantly easier to use or understand, **Congratulations!** If your administrative and managerial work behind the scenes sustains the community, **Congratulations!** You are now an official contributor to AppFlowy. Get in touch with us ([link](https://tally.so/r/mKP5z3)) to receive the very special Contributor T-shirt!
If your Pull Request is accepted as it fixes a bug, adds functionality, or makes AppFlowy's codebase significantly
easier to use or understand, **Congratulations!** If your administrative and managerial work behind the scenes sustains
the community, **Congratulations!** You are now an official contributor to AppFlowy. Get in touch with
us ([link](https://tally.so/r/mKP5z3)) to receive the very special Contributor T-shirt!
Proudly wear your T-shirt and show it to us by tagging [@appflowy](https://twitter.com/appflowy) on Twitter.
## Translations 🌎🗺
[![translation badge](https://inlang.com/badge?url=github.com/AppFlowy-IO/AppFlowy)](https://inlang.com/editor/github.com/AppFlowy-IO/AppFlowy?ref=badge)
To add translations, you can manually edit the JSON translation files in `/frontend/resources/translations`, use the [inlang online editor](https://inlang.com/editor/github.com/AppFlowy-IO/AppFlowy), or run `npx inlang machine translate` to add missing translations.
To add translations, you can manually edit the JSON translation files in `/frontend/resources/translations`, use
the [inlang online editor](https://inlang.com/editor/github.com/AppFlowy-IO/AppFlowy), or
run `npx inlang machine translate` to add missing translations.
## Join the community to build AppFlowy together
@@ -96,16 +109,30 @@ To add translations, you can manually edit the JSON translation files in `/front
## Why Are We Building This?
Notion has been our favourite project and knowledge management tool in recent years because of its aesthetic appeal and functionality. Our team uses it daily, and we are on its paid plan. However, as we all know, Notion has its limitations. These include weak data security and poor compatibility with mobile devices. Likewise, alternative collaborative workplace management tools also have their constraints.
Notion has been our favourite project and knowledge management tool in recent years because of its aesthetic appeal and
functionality. Our team uses it daily, and we are on its paid plan. However, as we all know, Notion has its limitations.
These include weak data security and poor compatibility with mobile devices. Likewise, alternative collaborative
workplace management tools also have their constraints.
The limitations we encountered using these tools and our past work experience with collaborative productivity tools have led to our firm belief that there is a glass ceiling on what's possible for these tools in the future. This emanates from the fact that these tools will probably struggle to scale horizontally at some point and be forced to prioritize a proportion of customers whose needs differ from the rest. While decision-makers want a workplace OS, it is impossible to come up with a one-size fits all solution in such a fragmented market.
The limitations we encountered using these tools and our past work experience with collaborative productivity tools have
led to our firm belief that there is a glass ceiling on what's possible for these tools in the future. This emanates
from the fact that these tools will probably struggle to scale horizontally at some point and be forced to prioritize a
proportion of customers whose needs differ from the rest. While decision-makers want a workplace OS, it is impossible to
come up with a one-size fits all solution in such a fragmented market.
When a customer's evolving core needs are not satisfied, they either switch to another or build one from the ground up, in-house. Consequently, they either go under another ceiling or buy an expensive ticket to learn a hard lesson. This is a requirement for many resources and expertise, building a reliable and easy-to-use collaborative tool, not to mention the speed and native experience. The same may apply to individual users as well.
When a customer's evolving core needs are not satisfied, they either switch to another or build one from the ground up,
in-house. Consequently, they either go under another ceiling or buy an expensive ticket to learn a hard lesson. This is
a requirement for many resources and expertise, building a reliable and easy-to-use collaborative tool, not to mention
the speed and native experience. The same may apply to individual users as well.
All these restrictions necessitate our mission - to make it possible for anyone to create apps that suit their needs well.
All these restrictions necessitate our mission - to make it possible for anyone to create apps that suit their needs
well.
- To individuals, we would like to offer Notion's functionality, data security, and cross-platform native experience.
- To enterprises and hackers, AppFlowy is dedicated to offering building blocks and collaboration infra services to enable you to make apps on your own. Moreover, you have 100% control of your data. You can design and modify AppFlowy your way, with a single codebase written in Flutter and Rust supporting multiple platforms armed with long-term maintainability.
- To enterprises and hackers, AppFlowy is dedicated to offering building blocks and collaboration infra services to
enable you to make apps on your own. Moreover, you have 100% control of your data. You can design and modify AppFlowy
your way, with a single codebase written in Flutter and Rust supporting multiple platforms armed with long-term
maintainability.
We decided to achieve this mission by upholding the three most fundamental values:
@@ -113,16 +140,20 @@ We decided to achieve this mission by upholding the three most fundamental value
- Reliable native experience
- Community-driven extensibility
We do not claim to outperform Notion in terms of functionality and design, at least for now. Besides, our priority doesn't lie in more functionality at the moment. Instead, we would like to cultivate a community to democratize the knowledge and wheels of making complex workplace management tools while enabling people and businesses to create beautiful things on their own by equipping them with a versatile toolbox of building blocks.
We do not claim to outperform Notion in terms of functionality and design, at least for now. Besides, our priority
doesn't lie in more functionality at the moment. Instead, we would like to cultivate a community to democratize the
knowledge and wheels of making complex workplace management tools while enabling people and businesses to create
beautiful things on their own by equipping them with a versatile toolbox of building blocks.
## License
Distributed under the AGPLv3 License. See [`LICENSE.md`](https://github.com/AppFlowy-IO/AppFlowy/blob/main/LICENSE) for more information.
Distributed under the AGPLv3 License. See [`LICENSE.md`](https://github.com/AppFlowy-IO/AppFlowy/blob/main/LICENSE) for
more information.
## Acknowledgments
Special thanks to these amazing projects which help power AppFlowy.IO:
- [flutter-quill](https://github.com/singerdmx/flutter-quill)
- [cargo-make](https://github.com/sagiegurari/cargo-make)
- [contrib.rocks](https://contrib.rocks)
- [flutter_chat_ui](https://pub.dev/packages/flutter_chat_ui)
+1 -1
View File
@@ -26,7 +26,7 @@ CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true
CARGO_MAKE_CRATE_FS_NAME = "dart_ffi"
CARGO_MAKE_CRATE_NAME = "dart-ffi"
LIB_NAME = "dart_ffi"
APPFLOWY_VERSION = "0.7.4"
APPFLOWY_VERSION = "0.7.7"
FLUTTER_DESKTOP_FEATURES = "dart"
PRODUCT_NAME = "AppFlowy"
MACOSX_DEPLOYMENT_TARGET = "11.0"
@@ -65,4 +65,5 @@
-->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.CAMERA" />
</manifest>
@@ -0,0 +1,47 @@
import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import '../../../shared/constants.dart';
import '../../../shared/util.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('AI Writer:', () {
testWidgets('the ai writer transaction should only apply in memory',
(tester) async {
await tester.initializeAppFlowy(
cloudType: AuthenticatorType.appflowyCloudSelfHost,
);
await tester.tapGoogleLoginInButton();
await tester.expectToSeeHomePageWithGetStartedPage();
const pageName = 'Document';
await tester.createNewPageInSpace(
spaceName: Constants.generalSpaceName,
layout: ViewLayoutPB.Document,
pageName: pageName,
);
await tester.editor.tapLineOfEditorAt(0);
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_aiWriter.tr(),
);
expect(find.byType(AIWriterBlockComponent), findsOneWidget);
// switch to another page
await tester.openPage(Constants.gettingStartedPageName);
// switch back to the page
await tester.openPage(pageName);
// expect the ai writer block is not in the document
expect(find.byType(AIWriterBlockComponent), findsNothing);
});
});
}
@@ -1,5 +1,6 @@
import 'package:integration_test/integration_test.dart';
import 'document_ai_writer_test.dart' as document_ai_writer_test;
import 'document_copy_link_to_block_test.dart'
as document_copy_link_to_block_test;
import 'document_option_actions_test.dart' as document_option_actions_test;
@@ -11,4 +12,5 @@ void main() {
document_option_actions_test.main();
document_copy_link_to_block_test.main();
document_publish_test.main();
document_ai_writer_test.main();
}
@@ -301,6 +301,7 @@ void main() {
await tester.createOption(name: "qwer");
await tester.selectOption(name: "asdf");
await tester.dismissCellEditor();
await tester.dismissCellEditor();
await tester.tapDatabaseFilterButton();
await tester.tapCreateFilterByFieldType(FieldType.MultiSelect, "Tags");
@@ -332,6 +333,7 @@ void main() {
await tester.tapButton(finderForFieldType(FieldType.MultiSelect));
await tester.selectOption(name: "asdf");
await tester.dismissCellEditor();
await tester.dismissCellEditor();
tester.assertNumberOfEventsInCalendar(0);
@@ -4,12 +4,10 @@ import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/widgets/card/card.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/media_cell_editor.dart';
import 'package:appflowy/plugins/database/widgets/row/row_banner.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/af_image.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pbenum.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
@@ -26,61 +24,6 @@ void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('database row cover', () {
testWidgets('add image to media field and check if cover is set (grid)',
(tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(layout: ViewLayoutPB.Grid);
// Invoke the field editor
await tester.tapGridFieldWithName('Type');
await tester.tapEditFieldButton();
// Change to media type
await tester.tapSwitchFieldTypeButton();
await tester.selectFieldType(FieldType.Media);
await tester.dismissFieldEditor();
// Prepare file for upload from local
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final tempDirectory = await getTemporaryDirectory();
final imagePath = p.join(tempDirectory.path, 'sample.jpeg');
final file = File(imagePath)
..writeAsBytesSync(image.buffer.asUint8List());
mockPickFilePaths(paths: [imagePath]);
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, '0');
// Open media cell editor
await tester.tapCellInGrid(rowIndex: 0, fieldType: FieldType.Media);
await tester.findMediaCellEditor(findsOneWidget);
// Click on add file button in the Media Cell Editor
await tester.tap(find.text(LocaleKeys.grid_media_addFileOrImage.tr()));
await tester.pumpAndSettle();
// Tap on the upload interaction
await tester.tapFileUploadHint();
// Expect one file
expect(find.byType(RenderMedia), findsOneWidget);
// Close cell editor
await tester.dismissCellEditor();
// Open first row in row detail view
await tester.openFirstRowDetailPage();
await tester.pumpAndSettle();
// Expect a cover to be shown
expect(find.byType(RowCover), findsOneWidget);
// Remove the temp file
await Future.wait([file.delete()]);
});
testWidgets('add and remove cover from Row Detail Card', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
@@ -2,12 +2,12 @@ import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart';
import 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart';
import 'package:appflowy/workspace/presentation/home/menu/view/view_action_type.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
@@ -330,6 +330,23 @@ void main() {
expect(find.text("$_createdPageName (copy)"), findsNWidgets(2));
expect(find.text("$_createdPageName (copy) (copy)"), findsOneWidget);
});
testWidgets('Cancel inline page reference menu by space', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createOpenRenameDocumentUnderParent(name: _firstDocName);
await tester.editor.tapLineOfEditorAt(0);
await tester.editor.showPlusMenu();
// Cancel by space
await tester.simulateKeyEvent(
LogicalKeyboardKey.space,
);
await tester.pumpAndSettle();
expect(find.byType(InlineActionsMenu), findsNothing);
});
});
}
@@ -11,6 +11,8 @@ import 'document_with_file_test.dart' as document_with_file_test;
import 'document_with_image_block_test.dart' as document_with_image_block_test;
import 'document_with_multi_image_block_test.dart'
as document_with_multi_image_block_test;
import 'document_with_simple_table_test.dart'
as document_with_simple_table_test;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
@@ -25,4 +27,5 @@ void main() {
document_block_option_test.main();
document_find_menu_test.main();
document_toolbar_test.main();
document_with_simple_table_test.main();
}
@@ -1,14 +1,21 @@
import 'dart:io';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/reminder/reminder_bloc.dart';
import 'package:appflowy/workspace/application/settings/date_time/date_format_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/desktop_date_picker.dart';
import 'package:appflowy/workspace/presentation/widgets/toggle/toggle.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:table_calendar/table_calendar.dart';
import '../../shared/util.dart';
@@ -18,7 +25,7 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized();
});
group('date or reminder block in document', () {
group('date or reminder block in document:', () {
testWidgets("insert date with time block", (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
@@ -121,5 +128,339 @@ void main() {
expect(find.text('@$formattedDate'), findsOneWidget);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsOneWidget);
});
testWidgets("copy, cut and paste a date mention", (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
// create a new document
await tester.createNewPageWithNameUnderParent(
name: 'copy, cut and paste a date mention',
);
// tap the first line of the document
await tester.editor.tapLineOfEditorAt(0);
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_dateOrReminder.tr(),
);
final dateTimeSettings = DateTimeSettingsPB(
dateFormat: UserDateFormatPB.Friendly,
timeFormat: UserTimeFormatPB.TwentyFourHour,
);
final DateTime currentDateTime = DateTime.now();
final String formattedDate =
dateTimeSettings.dateFormat.formatDate(currentDateTime, false);
// get current date in editor
expect(find.byType(MentionDateBlock), findsOneWidget);
expect(find.text('@$formattedDate'), findsOneWidget);
// update selection and copy
await tester.editor.updateSelection(
Selection(
start: Position(path: [0]),
end: Position(path: [0], offset: 1),
),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyC,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
// update selection and paste
await tester.editor.updateSelection(
Selection.collapsed(Position(path: [0], offset: 1)),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsNWidgets(2));
expect(find.text('@$formattedDate'), findsNWidgets(2));
// update selection and cut
await tester.editor.updateSelection(
Selection(
start: Position(path: [0], offset: 1),
end: Position(path: [0], offset: 2),
),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyX,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsOneWidget);
expect(find.text('@$formattedDate'), findsOneWidget);
// update selection and paste
await tester.editor.updateSelection(
Selection.collapsed(Position(path: [0], offset: 1)),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsNWidgets(2));
expect(find.text('@$formattedDate'), findsNWidgets(2));
});
testWidgets("copy, cut and paste a reminder mention", (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
// create a new document
await tester.createNewPageWithNameUnderParent(
name: 'copy, cut and paste a reminder mention',
);
// tap the first line of the document
await tester.editor.tapLineOfEditorAt(0);
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_dateOrReminder.tr(),
);
// trigger popup
await tester.tapButton(find.byType(MentionDateBlock));
await tester.pumpAndSettle();
// set date to be fifteenth of the next month
await tester.tap(
find.descendant(
of: find.byType(DesktopAppFlowyDatePicker),
matching: find.byFlowySvg(FlowySvgs.arrow_right_s),
),
);
await tester.pumpAndSettle();
await tester.tap(
find.descendant(
of: find.byType(TableCalendar),
matching: find.text(15.toString()),
),
);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
// add a reminder
await tester.tap(find.byType(MentionDateBlock));
await tester.pumpAndSettle();
await tester.tap(find.text(LocaleKeys.datePicker_reminderLabel.tr()));
await tester.pumpAndSettle();
await tester.tap(
find.textContaining(
LocaleKeys.datePicker_reminderOptions_oneDayBefore.tr(),
),
);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
// verify
final dateTimeSettings = DateTimeSettingsPB(
dateFormat: UserDateFormatPB.Friendly,
timeFormat: UserTimeFormatPB.TwentyFourHour,
);
final now = DateTime.now();
final fifteenthOfNextMonth = DateTime(now.year, now.month + 1, 15);
final formattedDate =
dateTimeSettings.dateFormat.formatDate(fifteenthOfNextMonth, false);
expect(find.byType(MentionDateBlock), findsOneWidget);
expect(find.text('@$formattedDate'), findsOneWidget);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsOneWidget);
expect(getIt<ReminderBloc>().state.reminders.map((e) => e.id).length, 1);
// update selection and copy
await tester.editor.updateSelection(
Selection(
start: Position(path: [0]),
end: Position(path: [0], offset: 1),
),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyC,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
// update selection and paste
await tester.editor.updateSelection(
Selection.collapsed(Position(path: [0], offset: 1)),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsNWidgets(2));
expect(find.text('@$formattedDate'), findsNWidgets(2));
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsNWidgets(2));
expect(
getIt<ReminderBloc>().state.reminders.map((e) => e.id).toSet().length,
2,
);
// update selection and cut
await tester.editor.updateSelection(
Selection(
start: Position(path: [0], offset: 1),
end: Position(path: [0], offset: 2),
),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyX,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsOneWidget);
expect(find.text('@$formattedDate'), findsOneWidget);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsOneWidget);
expect(getIt<ReminderBloc>().state.reminders.map((e) => e.id).length, 1);
// update selection and paste
await tester.editor.updateSelection(
Selection.collapsed(Position(path: [0], offset: 1)),
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsNWidgets(2));
expect(find.text('@$formattedDate'), findsNWidgets(2));
expect(find.byType(MentionDateBlock), findsNWidgets(2));
expect(find.text('@$formattedDate'), findsNWidgets(2));
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsNWidgets(2));
expect(
getIt<ReminderBloc>().state.reminders.map((e) => e.id).toSet().length,
2,
);
});
testWidgets("delete, undo and redo a reminder mention", (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
// create a new document
await tester.createNewPageWithNameUnderParent(
name: 'delete, undo and redo a reminder mention',
);
// tap the first line of the document
await tester.editor.tapLineOfEditorAt(0);
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_dateOrReminder.tr(),
);
// trigger popup
await tester.tapButton(find.byType(MentionDateBlock));
await tester.pumpAndSettle();
// set date to be fifteenth of the next month
await tester.tap(
find.descendant(
of: find.byType(DesktopAppFlowyDatePicker),
matching: find.byFlowySvg(FlowySvgs.arrow_right_s),
),
);
await tester.pumpAndSettle();
await tester.tap(
find.descendant(
of: find.byType(TableCalendar),
matching: find.text(15.toString()),
),
);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
// add a reminder
await tester.tap(find.byType(MentionDateBlock));
await tester.pumpAndSettle();
await tester.tap(find.text(LocaleKeys.datePicker_reminderLabel.tr()));
await tester.pumpAndSettle();
await tester.tap(
find.textContaining(
LocaleKeys.datePicker_reminderOptions_oneDayBefore.tr(),
),
);
await tester.pumpAndSettle();
await tester.simulateKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
// verify
final dateTimeSettings = DateTimeSettingsPB(
dateFormat: UserDateFormatPB.Friendly,
timeFormat: UserTimeFormatPB.TwentyFourHour,
);
final now = DateTime.now();
final fifteenthOfNextMonth = DateTime(now.year, now.month + 1, 15);
final formattedDate =
dateTimeSettings.dateFormat.formatDate(fifteenthOfNextMonth, false);
expect(find.byType(MentionDateBlock), findsOneWidget);
expect(find.text('@$formattedDate'), findsOneWidget);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsOneWidget);
expect(getIt<ReminderBloc>().state.reminders.map((e) => e.id).length, 1);
// update selection and backspace to delete the mention
await tester.editor.updateSelection(
Selection.collapsed(Position(path: [0], offset: 1)),
);
await tester.simulateKeyEvent(LogicalKeyboardKey.backspace);
await tester.pumpAndSettle();
expect(find.byType(MentionDateBlock), findsNothing);
expect(find.text('@$formattedDate'), findsNothing);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsNothing);
expect(getIt<ReminderBloc>().state.reminders.isEmpty, isTrue);
// undo
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyZ,
isControlPressed: Platform.isWindows || Platform.isLinux,
isMetaPressed: Platform.isMacOS,
);
expect(find.byType(MentionDateBlock), findsOneWidget);
expect(find.text('@$formattedDate'), findsOneWidget);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsOneWidget);
expect(getIt<ReminderBloc>().state.reminders.map((e) => e.id).length, 1);
// redo
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyZ,
isControlPressed: Platform.isWindows || Platform.isLinux,
isMetaPressed: Platform.isMacOS,
isShiftPressed: true,
);
expect(find.byType(MentionDateBlock), findsNothing);
expect(find.text('@$formattedDate'), findsNothing);
expect(find.byFlowySvg(FlowySvgs.reminder_clock_s), findsNothing);
expect(getIt<ReminderBloc>().state.reminders.isEmpty, isTrue);
});
});
}
@@ -26,7 +26,6 @@ import '../../shared/util.dart';
const _testImageUrls = [
'https://images.unsplash.com/photo-1469474968028-56623f02e42e?ixlib=rb-4.0.3&q=85&fm=jpg&crop=entropy&cs=srgb&dl=david-marcu-78A265wPiO4-unsplash.jpg&w=640',
'https://mathiasbynens.be/demo/animated-webp-supported.webp',
'https://www.easygifanimator.net/images/samples/eglite.gif',
'https://people.math.sc.edu/Burkardt/data/bmp/snail.bmp',
'https://file-examples.com/storage/fe9566cb7d67345489a5a97/2017/10/file_example_JPG_100kB.jpg',
@@ -48,7 +48,7 @@ void main() {
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_photoGallery.tr(),
offset: 100,
offset: 80,
);
expect(find.byType(MultiImageBlockComponent), findsOneWidget);
expect(find.byType(MultiImagePlaceholder), findsOneWidget);
@@ -146,7 +146,7 @@ void main() {
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_photoGallery.tr(),
offset: 100,
offset: 80,
);
expect(find.byType(MultiImageBlockComponent), findsOneWidget);
expect(find.byType(MultiImagePlaceholder), findsOneWidget);
@@ -0,0 +1,392 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/_shared_widget.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:universal_platform/universal_platform.dart';
import '../../shared/util.dart';
const String heading1 = "Heading 1";
const String heading2 = "Heading 2";
const String heading3 = "Heading 3";
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('simple table block test:', () {
testWidgets('insert a simple table block', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
await tester.editor.tapLineOfEditorAt(0);
await tester.insertTableInDocument();
// validate the table is inserted
expect(find.byType(SimpleTableBlockWidget), findsOneWidget);
final editorState = tester.editor.getCurrentEditorState();
expect(
editorState.selection,
// table -> row -> cell -> paragraph
Selection.collapsed(Position(path: [0, 0, 0, 0])),
);
final firstCell = find.byType(SimpleTableCellBlockWidget).first;
expect(
tester
.state<SimpleTableCellBlockWidgetState>(firstCell)
.isEditingCellNotifier
.value,
isTrue,
);
});
testWidgets('select all in table cell', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
const cell1Content = 'Cell 1';
await tester.editor.tapLineOfEditorAt(0);
await tester.ime.insertText('New Table');
await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
await tester.editor.tapLineOfEditorAt(1);
await tester.insertTableInDocument();
await tester.ime.insertText(cell1Content);
await tester.pumpAndSettle();
// Select all in the cell
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyA,
isControlPressed: !UniversalPlatform.isMacOS,
isMetaPressed: UniversalPlatform.isMacOS,
);
expect(
tester.editor.getCurrentEditorState().selection,
Selection(
start: Position(path: [1, 0, 0, 0]),
end: Position(path: [1, 0, 0, 0], offset: cell1Content.length),
),
);
// Press select all again, the selection should be the entire document
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyA,
isControlPressed: !UniversalPlatform.isMacOS,
isMetaPressed: UniversalPlatform.isMacOS,
);
expect(
tester.editor.getCurrentEditorState().selection,
Selection(
start: Position(path: [0]),
end: Position(path: [1, 1, 1, 0]),
),
);
});
testWidgets('''
1. hover on the table
1.1 click the add row button
1.2 click the add column button
1.3 click the add row and column button
2. validate the table is updated
3. delete the last column
4. delete the last row
5. validate the table is updated
''', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
await tester.editor.tapLineOfEditorAt(0);
await tester.insertTableInDocument();
// add a new row
final row = find.byWidgetPredicate((w) {
return w is SimpleTableRowBlockWidget && w.node.rowIndex == 1;
});
await tester.hoverOnWidget(
row,
onHover: () async {
final addRowButton = find.byType(SimpleTableAddRowButton).first;
await tester.tap(addRowButton);
},
);
await tester.pumpAndSettle();
// add a new column
final column = find.byWidgetPredicate((w) {
return w is SimpleTableCellBlockWidget && w.node.columnIndex == 1;
}).first;
await tester.hoverOnWidget(
column,
onHover: () async {
final addColumnButton = find.byType(SimpleTableAddColumnButton).first;
await tester.tap(addColumnButton);
},
);
await tester.pumpAndSettle();
// add a new row and a new column
final row2 = find.byWidgetPredicate((w) {
return w is SimpleTableCellBlockWidget &&
w.node.rowIndex == 2 &&
w.node.columnIndex == 2;
}).first;
await tester.hoverOnWidget(
row2,
onHover: () async {
// click the add row and column button
final addRowAndColumnButton =
find.byType(SimpleTableAddColumnAndRowButton).first;
await tester.tap(addRowAndColumnButton);
},
);
await tester.pumpAndSettle();
final tableNode =
tester.editor.getCurrentEditorState().document.nodeAtPath([0])!;
expect(tableNode.columnLength, 4);
expect(tableNode.rowLength, 4);
// delete the last row
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.row,
index: tableNode.rowLength - 1,
action: SimpleTableMoreAction.delete,
);
await tester.pumpAndSettle();
expect(tableNode.rowLength, 3);
expect(tableNode.columnLength, 4);
// delete the last column
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.column,
index: tableNode.columnLength - 1,
action: SimpleTableMoreAction.delete,
);
await tester.pumpAndSettle();
expect(tableNode.columnLength, 3);
expect(tableNode.rowLength, 3);
});
testWidgets('enable header column and header row', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
await tester.editor.tapLineOfEditorAt(0);
await tester.insertTableInDocument();
// enable the header row
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.row,
index: 0,
action: SimpleTableMoreAction.enableHeaderRow,
);
await tester.pumpAndSettle();
// enable the header column
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.column,
index: 0,
action: SimpleTableMoreAction.enableHeaderColumn,
);
await tester.pumpAndSettle();
final tableNode =
tester.editor.getCurrentEditorState().document.nodeAtPath([0])!;
expect(tableNode.isHeaderColumnEnabled, isTrue);
expect(tableNode.isHeaderRowEnabled, isTrue);
// disable the header row
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.row,
index: 0,
action: SimpleTableMoreAction.enableHeaderRow,
);
await tester.pumpAndSettle();
expect(tableNode.isHeaderColumnEnabled, isTrue);
expect(tableNode.isHeaderRowEnabled, isFalse);
// disable the header column
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.column,
index: 0,
action: SimpleTableMoreAction.enableHeaderColumn,
);
await tester.pumpAndSettle();
expect(tableNode.isHeaderColumnEnabled, isFalse);
expect(tableNode.isHeaderRowEnabled, isFalse);
});
testWidgets('duplicate a column / row', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
await tester.editor.tapLineOfEditorAt(0);
await tester.insertTableInDocument();
// duplicate the row
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.row,
index: 0,
action: SimpleTableMoreAction.duplicate,
);
await tester.pumpAndSettle();
// duplicate the column
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.column,
index: 0,
action: SimpleTableMoreAction.duplicate,
);
await tester.pumpAndSettle();
final tableNode =
tester.editor.getCurrentEditorState().document.nodeAtPath([0])!;
expect(tableNode.columnLength, 3);
expect(tableNode.rowLength, 3);
});
testWidgets('insert left / insert right', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
await tester.editor.tapLineOfEditorAt(0);
await tester.insertTableInDocument();
// insert left
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.column,
index: 0,
action: SimpleTableMoreAction.insertLeft,
);
await tester.pumpAndSettle();
// insert right
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.column,
index: 0,
action: SimpleTableMoreAction.insertRight,
);
await tester.pumpAndSettle();
final tableNode =
tester.editor.getCurrentEditorState().document.nodeAtPath([0])!;
expect(tableNode.columnLength, 4);
expect(tableNode.rowLength, 2);
});
testWidgets('insert above / insert below', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(
name: 'simple_table_test',
);
await tester.editor.tapLineOfEditorAt(0);
await tester.insertTableInDocument();
// insert above
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.row,
index: 0,
action: SimpleTableMoreAction.insertAbove,
);
await tester.pumpAndSettle();
// insert below
await tester.clickMoreActionItemInTableMenu(
type: SimpleTableMoreActionType.row,
index: 0,
action: SimpleTableMoreAction.insertBelow,
);
await tester.pumpAndSettle();
final tableNode =
tester.editor.getCurrentEditorState().document.nodeAtPath([0])!;
expect(tableNode.rowLength, 4);
expect(tableNode.columnLength, 2);
});
});
}
extension on WidgetTester {
/// Insert a table in the document
Future<void> insertTableInDocument() async {
// open the actions menu and insert the outline block
await editor.showSlashMenu();
await editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_table.tr(),
);
await pumpAndSettle();
}
Future<void> clickMoreActionItemInTableMenu({
required SimpleTableMoreActionType type,
required int index,
required SimpleTableMoreAction action,
}) async {
if (type == SimpleTableMoreActionType.row) {
final row = find.byWidgetPredicate((w) {
return w is SimpleTableRowBlockWidget && w.node.rowIndex == index;
});
await hoverOnWidget(
row,
onHover: () async {
final moreActionButton = find.byWidgetPredicate((w) {
return w is SimpleTableMoreActionMenu &&
w.type == SimpleTableMoreActionType.row &&
w.index == index;
});
await tapButton(moreActionButton);
await tapButton(find.text(action.name));
},
);
await pumpAndSettle();
} else if (type == SimpleTableMoreActionType.column) {
final column = find.byWidgetPredicate((w) {
return w is SimpleTableCellBlockWidget && w.node.columnIndex == index;
}).first;
await hoverOnWidget(
column,
onHover: () async {
final moreActionButton = find.byWidgetPredicate((w) {
return w is SimpleTableMoreActionMenu &&
w.type == SimpleTableMoreActionType.column &&
w.index == index;
});
await tapButton(moreActionButton);
await tapButton(find.text(action.name));
},
);
await pumpAndSettle();
}
await tapAt(Offset.zero);
}
}
@@ -1,7 +1,9 @@
import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -263,5 +265,24 @@ void main() {
expect(node.attributes[ToggleListBlockKeys.level], 3);
expect(node.delta!.toPlainText(), 'Hello');
});
testWidgets('click the toggle list to create a new paragraph',
(tester) async {
await prepareToggleHeadingBlock(tester, '> # Hello');
final emptyHintText = find.text(
LocaleKeys.document_plugins_emptyToggleHeading.tr(
args: ['1'],
),
);
expect(emptyHintText, findsOneWidget);
await tester.tapButton(emptyHintText);
await tester.pumpAndSettle();
// check the new paragraph is created
final editorState = tester.editor.getCurrentEditorState();
final node = editorState.getNodeAtPath([0, 0])!;
expect(node.type, ParagraphBlockKeys.type);
});
});
}
@@ -1,5 +1,6 @@
import 'dart:io';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -87,7 +88,7 @@ void main() {
);
expect(
importedPageEditorState.getNodeAtPath([2])!.type,
TableBlockKeys.type,
SimpleTableBlockKeys.type,
);
});
});
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/home/tabs/flowy_tab.dart';
import 'package:appflowy/workspace/presentation/home/tabs/tabs_manager.dart';
import 'package:appflowy/workspace/presentation/widgets/tab_bar_item.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/gestures.dart';
@@ -145,5 +146,189 @@ void main() {
// and in this case view name in sidebar)
expect(find.text(gettingStarted), findsNWidgets(3));
});
testWidgets('cannot close pinned tabs', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
expect(
find.descendant(
of: find.byType(TabsManager),
matching: find.byType(TabBar),
),
findsNothing,
);
await tester.createNewPageWithNameUnderParent(name: _documentName);
await tester.createNewPageWithNameUnderParent(name: _documentTwoName);
// Open second menu item in a new tab
await tester.openAppInNewTab(gettingStarted, ViewLayoutPB.Document);
// Open third menu item in a new tab
await tester.openAppInNewTab(_documentName, ViewLayoutPB.Document);
expect(
find.descendant(
of: find.byType(TabsManager),
matching: find.byType(FlowyTab),
),
findsNWidgets(3),
);
const firstTab = _documentTwoName;
const secondTab = gettingStarted;
const thirdTab = _documentName;
expect(tester.isTabAtIndex(firstTab, 0), isTrue);
expect(tester.isTabAtIndex(secondTab, 1), isTrue);
expect(tester.isTabAtIndex(thirdTab, 2), isTrue);
expect(tester.isTabPinned(gettingStarted), isFalse);
// Right click on second tab
await tester.openTabMenu(gettingStarted);
expect(find.byType(TabMenu), findsOneWidget);
// Pin second tab
await tester.tap(find.text(LocaleKeys.tabMenu_pinTab.tr()));
await tester.pumpAndSettle();
expect(tester.isTabPinned(gettingStarted), isTrue);
/// Right click on first unpinned tab (second tab)
await tester.openTabMenu(_documentTwoName);
// Close others
await tester.tap(find.text(LocaleKeys.tabMenu_closeOthers.tr()));
await tester.pumpAndSettle();
// We expect to find 2 tabs, the first pinned tab and the second tab
expect(find.byType(FlowyTab), findsNWidgets(2));
expect(tester.isTabAtIndex(gettingStarted, 0), isTrue);
expect(tester.isTabAtIndex(_documentTwoName, 1), isTrue);
});
testWidgets('pin/unpin tabs proper order', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
expect(
find.descendant(
of: find.byType(TabsManager),
matching: find.byType(TabBar),
),
findsNothing,
);
await tester.createNewPageWithNameUnderParent(name: _documentName);
await tester.createNewPageWithNameUnderParent(name: _documentTwoName);
// Open second menu item in a new tab
await tester.openAppInNewTab(gettingStarted, ViewLayoutPB.Document);
// Open third menu item in a new tab
await tester.openAppInNewTab(_documentName, ViewLayoutPB.Document);
expect(
find.descendant(
of: find.byType(TabsManager),
matching: find.byType(FlowyTab),
),
findsNWidgets(3),
);
const firstTabName = _documentTwoName;
const secondTabName = gettingStarted;
const thirdTabName = _documentName;
// Expect correct order
expect(tester.isTabAtIndex(firstTabName, 0), isTrue);
expect(tester.isTabAtIndex(secondTabName, 1), isTrue);
expect(tester.isTabAtIndex(thirdTabName, 2), isTrue);
// Pin second tab
await tester.openTabMenu(secondTabName);
await tester.tap(find.text(LocaleKeys.tabMenu_pinTab.tr()));
await tester.pumpAndSettle();
expect(tester.isTabPinned(secondTabName), isTrue);
// Expect correct order
expect(tester.isTabAtIndex(secondTabName, 0), isTrue);
expect(tester.isTabAtIndex(firstTabName, 1), isTrue);
expect(tester.isTabAtIndex(thirdTabName, 2), isTrue);
// Pin new second tab (first tab)
await tester.openTabMenu(firstTabName);
await tester.tap(find.text(LocaleKeys.tabMenu_pinTab.tr()));
await tester.pumpAndSettle();
expect(tester.isTabPinned(firstTabName), isTrue);
expect(tester.isTabPinned(secondTabName), isTrue);
expect(tester.isTabPinned(thirdTabName), isFalse);
expect(tester.isTabAtIndex(secondTabName, 0), isTrue);
expect(tester.isTabAtIndex(firstTabName, 1), isTrue);
expect(tester.isTabAtIndex(thirdTabName, 2), isTrue);
// Unpin second tab
await tester.openTabMenu(secondTabName);
await tester.tap(find.text(LocaleKeys.tabMenu_unpinTab.tr()));
await tester.pumpAndSettle();
expect(tester.isTabPinned(firstTabName), isTrue);
expect(tester.isTabPinned(secondTabName), isFalse);
expect(tester.isTabPinned(thirdTabName), isFalse);
expect(tester.isTabAtIndex(firstTabName, 0), isTrue);
expect(tester.isTabAtIndex(secondTabName, 1), isTrue);
expect(tester.isTabAtIndex(thirdTabName, 2), isTrue);
});
});
}
extension _TabsTester on WidgetTester {
bool isTabPinned(String tabName) {
final tabFinder = find.ancestor(
of: find.byWidgetPredicate(
(w) => w is ViewTabBarItem && w.view.name == tabName,
),
matching: find.byType(FlowyTab),
);
final FlowyTab tabWidget = widget(tabFinder);
return tabWidget.pageManager.isPinned;
}
bool isTabAtIndex(String tabName, int index) {
final tabFinder = find.ancestor(
of: find.byWidgetPredicate(
(w) => w is ViewTabBarItem && w.view.name == tabName,
),
matching: find.byType(FlowyTab),
);
final pluginId = (widget(tabFinder) as FlowyTab).pageManager.plugin.id;
final pluginIds = find
.byType(FlowyTab)
.evaluate()
.map((e) => (e.widget as FlowyTab).pageManager.plugin.id);
return pluginIds.elementAt(index) == pluginId;
}
Future<void> openTabMenu(String tabName) async {
await tap(
buttons: kSecondaryButton,
find.ancestor(
of: find.byWidgetPredicate(
(w) => w is ViewTabBarItem && w.view.name == tabName,
),
matching: find.byType(FlowyTab),
),
);
await pumpAndSettle();
}
}
@@ -50,6 +50,8 @@
<string>AppFlowy needs access to your photos to let you add images to your documents</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>AppFlowy needs access to your camera to let you add images to your documents from camera</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
@@ -65,9 +67,9 @@
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>UISupportsDocumentBrowser</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
@@ -49,6 +49,7 @@ class KVKeys {
/// {'SidebarFolderCategoryType.value': true}
static const String expandedFolders = 'expandedFolders';
/// @deprecated in version 0.7.6
/// The key for saving if showing the rename dialog when creating a new file
///
/// The value is a boolean string.
@@ -1,16 +1,24 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/shared/patterns/common_patterns.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/log.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:open_filex/open_filex.dart';
import 'package:string_validator/string_validator.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
typedef OnFailureCallback = void Function(Uri uri);
Future<bool> afLaunchUrl(
/// Launch the uri
///
/// If the uri is a local file path, it will be opened with the OpenFilex.
/// Otherwise, it will be launched with the url_launcher.
Future<bool> afLaunchUri(
Uri uri, {
BuildContext? context,
OnFailureCallback? onFailure,
@@ -18,6 +26,18 @@ Future<bool> afLaunchUrl(
String? webOnlyWindowName,
bool addingHttpSchemeWhenFailed = false,
}) async {
final url = uri.toString();
final decodedUrl = Uri.decodeComponent(url);
// check if the uri is the local file path
if (localPathRegex.hasMatch(decodedUrl)) {
return _afLaunchLocalUri(
uri,
context: context,
onFailure: onFailure,
);
}
// try to launch the uri directly
bool result;
try {
@@ -32,7 +52,7 @@ Future<bool> afLaunchUrl(
}
// if the uri is not a valid url, try to launch it with http scheme
final url = uri.toString();
if (addingHttpSchemeWhenFailed &&
!result &&
!isURL(url, {'require_protocol': true})) {
@@ -54,9 +74,14 @@ Future<bool> afLaunchUrl(
return result;
}
/// Launch the url string
///
/// See [afLaunchUri] for more details.
Future<bool> afLaunchUrlString(
String url, {
bool addingHttpSchemeWhenFailed = false,
BuildContext? context,
OnFailureCallback? onFailure,
}) async {
final Uri uri;
try {
@@ -67,12 +92,56 @@ Future<bool> afLaunchUrlString(
}
// try to launch the uri directly
return afLaunchUrl(
return afLaunchUri(
uri,
addingHttpSchemeWhenFailed: addingHttpSchemeWhenFailed,
context: context,
onFailure: onFailure,
);
}
/// Launch the local uri
///
/// See [afLaunchUri] for more details.
Future<bool> _afLaunchLocalUri(
Uri uri, {
BuildContext? context,
OnFailureCallback? onFailure,
}) async {
final decodedUrl = Uri.decodeComponent(uri.toString());
// open the file with the OpenfileX
var result = await OpenFilex.open(decodedUrl);
if (result.type != ResultType.done) {
// For the file cant be opened, fallback to open the folder
final parentFolder = Directory(decodedUrl).parent.path;
result = await OpenFilex.open(parentFolder);
}
// show the toast if the file is not found
final message = switch (result.type) {
ResultType.done => LocaleKeys.openFileMessage_success.tr(),
ResultType.fileNotFound => LocaleKeys.openFileMessage_fileNotFound.tr(),
ResultType.noAppToOpen => LocaleKeys.openFileMessage_noAppToOpenFile.tr(),
ResultType.permissionDenied =>
LocaleKeys.openFileMessage_permissionDenied.tr(),
ResultType.error => LocaleKeys.failedToOpenUrl.tr(),
};
if (context != null && context.mounted) {
showToastNotification(
context,
message: message,
type: result.type == ResultType.done
? ToastificationType.success
: ToastificationType.error,
);
}
final openFileSuccess = result.type == ResultType.done;
if (!openFileSuccess && onFailure != null) {
onFailure(uri);
Log.error('Failed to open file: $result.message');
}
return openFileSuccess;
}
void _errorHandler(
Uri uri, {
BuildContext? context,
@@ -189,7 +189,7 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
final url = context.read<ShareBloc>().state.url;
if (url.isNotEmpty) {
unawaited(
afLaunchUrl(
afLaunchUri(
Uri.parse(url),
mode: LaunchMode.externalApplication,
),
@@ -9,10 +9,10 @@ import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/database/card/card_detail/widgets/widgets.dart';
import 'package:appflowy/mobile/presentation/widgets/widgets.dart';
import 'package:appflowy/plugins/base/drag_handler.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/application/field/type_option/number_format_bloc.dart';
import 'package:appflowy/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/extension.dart';
import 'package:appflowy/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:collection/collection.dart';
@@ -863,6 +863,8 @@ class _SelectOptionListState extends State<_SelectOptionList> {
return ListView(
shrinkWrap: true,
padding: EdgeInsets.zero,
// disable the inner scroll physics, so the outer ListView can scroll
physics: const NeverScrollableScrollPhysics(),
children: widget.selectOptions
.mapIndexed(
(index, option) => _SelectOptionTile(
@@ -1,5 +1,3 @@
import 'dart:async';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
@@ -22,42 +20,26 @@ class ChatAIMessageBloc extends Bloc<ChatAIMessageEvent, ChatAIMessageState> {
}) : super(
ChatAIMessageState.initial(
message,
messageReferenceSource(refSourceJsonString),
parseMetadata(refSourceJsonString),
),
) {
if (state.stream != null) {
state.stream!.listen(
onData: (text) {
if (!isClosed) {
add(ChatAIMessageEvent.updateText(text));
}
},
onError: (error) {
if (!isClosed) {
add(ChatAIMessageEvent.receiveError(error.toString()));
}
},
onAIResponseLimit: () {
if (!isClosed) {
add(const ChatAIMessageEvent.onAIResponseLimit());
}
},
onMetadata: (sources) {
if (!isClosed) {
add(ChatAIMessageEvent.receiveSources(sources));
}
},
);
_dispatch();
if (state.stream!.error != null) {
Future.delayed(const Duration(milliseconds: 300), () {
if (!isClosed) {
add(ChatAIMessageEvent.receiveError(state.stream!.error!));
}
});
if (state.stream != null) {
_startListening();
if (state.stream!.aiLimitReached) {
add(const ChatAIMessageEvent.onAIResponseLimit());
} else if (state.stream!.error != null) {
add(ChatAIMessageEvent.receiveError(state.stream!.error!));
}
}
}
final String chatId;
final Int64? questionId;
void _dispatch() {
on<ChatAIMessageEvent>(
(event, emit) {
event.when(
@@ -116,10 +98,12 @@ class ChatAIMessageBloc extends Bloc<ChatAIMessageEvent, ChatAIMessageState> {
),
);
},
receiveSources: (List<ChatMessageRefSource> sources) {
receiveMetadata: (metadata) {
Log.debug("AI Steps: ${metadata.progress?.step}");
emit(
state.copyWith(
sources: sources,
sources: metadata.sources,
progress: metadata.progress,
),
);
},
@@ -128,8 +112,30 @@ class ChatAIMessageBloc extends Bloc<ChatAIMessageEvent, ChatAIMessageState> {
);
}
final String chatId;
final Int64? questionId;
void _startListening() {
state.stream!.listen(
onData: (text) {
if (!isClosed) {
add(ChatAIMessageEvent.updateText(text));
}
},
onError: (error) {
if (!isClosed) {
add(ChatAIMessageEvent.receiveError(error.toString()));
}
},
onAIResponseLimit: () {
if (!isClosed) {
add(const ChatAIMessageEvent.onAIResponseLimit());
}
},
onMetadata: (metadata) {
if (!isClosed) {
add(ChatAIMessageEvent.receiveMetadata(metadata));
}
},
);
}
}
@freezed
@@ -139,8 +145,8 @@ class ChatAIMessageEvent with _$ChatAIMessageEvent {
const factory ChatAIMessageEvent.retry() = _Retry;
const factory ChatAIMessageEvent.retryResult(String text) = _RetryResult;
const factory ChatAIMessageEvent.onAIResponseLimit() = _OnAIResponseLimit;
const factory ChatAIMessageEvent.receiveSources(
List<ChatMessageRefSource> sources,
const factory ChatAIMessageEvent.receiveMetadata(
MetadataCollection metadata,
) = _ReceiveMetadata;
}
@@ -151,17 +157,19 @@ class ChatAIMessageState with _$ChatAIMessageState {
required String text,
required MessageState messageState,
required List<ChatMessageRefSource> sources,
required AIChatProgress? progress,
}) = _ChatAIMessageState;
factory ChatAIMessageState.initial(
dynamic text,
List<ChatMessageRefSource> sources,
MetadataCollection metadata,
) {
return ChatAIMessageState(
text: text is String ? text : "",
stream: text is AnswerStream ? text : null,
messageState: const MessageState.ready(),
sources: sources,
sources: metadata.sources,
progress: metadata.progress,
);
}
}
@@ -1,47 +1,50 @@
import 'dart:async';
import 'dart:collection';
import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
import 'package:appflowy/util/int64_extension.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:nanoid/nanoid.dart';
import 'chat_entity.dart';
import 'chat_message_listener.dart';
import 'chat_message_service.dart';
import 'chat_message_stream.dart';
part 'chat_bloc.freezed.dart';
class ChatBloc extends Bloc<ChatEvent, ChatState> {
ChatBloc({
required ViewPB view,
required UserProfilePB userProfile,
}) : listener = ChatMessageListener(chatId: view.id),
chatId = view.id,
super(
ChatState.initial(view, userProfile),
) {
required this.chatId,
required this.userId,
}) : chatController = InMemoryChatController(),
listener = ChatMessageListener(chatId: chatId),
super(ChatState.initial()) {
_startListening();
_dispatch();
_init();
}
final ChatMessageListener listener;
final String chatId;
final String userId;
final ChatMessageListener listener;
final ChatController chatController;
/// The last streaming message id
String answerStreamMessageId = '';
String questionStreamMessageId = '';
ChatMessagePB? lastSentMessage;
/// Using a temporary map to associate the real message ID with the last streaming message ID.
///
/// When a message is streaming, it does not have a real message ID. To maintain the relationship
@@ -51,11 +54,24 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
/// is 3 (AI response).
final HashMap<String, String> temporaryMessageIDMap = HashMap();
bool isLoadingPreviousMessages = false;
bool hasMorePreviousMessages = true;
AnswerStream? answerStream;
int numSendMessage = 0;
/// a counter used to determine whether the initial loading state should be
/// set to finish. It should hit two before we emit: one for the local fetch
/// and another for the server fetch.
///
/// This is to work around a bug where if an ai chat that is not yet on the
/// user local storage is opened but has messages in the server, it will
/// remain stuck on the welcome screen until the user switches to another page
/// then come back.
int initialFetchCounter = 0;
@override
Future<void> close() async {
if (state.answerStream != null) {
await state.answerStream?.dispose();
}
await answerStream?.dispose();
await listener.stop();
return super.close();
}
@@ -64,195 +80,170 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
on<ChatEvent>(
(event, emit) async {
await event.when(
initialLoad: () {
final payload = LoadNextChatMessagePB(
chatId: state.view.id,
limit: Int64(10),
);
AIEventLoadNextMessage(payload).send().then(
(result) {
result.fold((list) {
if (!isClosed) {
final messages =
list.messages.map(_createTextMessage).toList();
add(ChatEvent.didLoadLatestMessages(messages));
}
}, (err) {
Log.error("Failed to load messages: $err");
});
},
);
},
// Loading messages
startLoadingPrevMessage: () async {
Int64? beforeMessageId;
final oldestMessage = _getOldestMessage();
if (oldestMessage != null) {
try {
beforeMessageId = Int64.parseInt(oldestMessage.id);
} catch (e) {
Log.error(
"Failed to parse message id: $e, messaeg_id: ${oldestMessage.id}",
);
}
}
_loadPrevMessage(beforeMessageId);
emit(
state.copyWith(
loadingPreviousStatus: const ChatLoadingState.loading(),
),
);
},
didLoadPreviousMessages: (List<Message> messages, bool hasMore) {
Log.debug("did load previous messages: ${messages.length}");
final onetimeMessages = _getOnetimeMessages();
final allMessages = _permanentMessages();
final uniqueMessages = {...allMessages, ...messages}.toList();
uniqueMessages.insertAll(0, onetimeMessages);
emit(
state.copyWith(
messages: uniqueMessages,
loadingPreviousStatus: const ChatLoadingState.finish(),
hasMorePrevMessage: hasMore,
),
);
},
didLoadLatestMessages: (List<Message> messages) {
final onetimeMessages = _getOnetimeMessages();
final allMessages = _permanentMessages();
final uniqueMessages = {...allMessages, ...messages}.toList();
uniqueMessages.insertAll(0, onetimeMessages);
emit(
state.copyWith(
messages: uniqueMessages,
initialLoadingStatus: const ChatLoadingState.finish(),
),
);
},
// streaming message
finishAnswerStreaming: () {
emit(
state.copyWith(
streamingState: const StreamingState.done(),
acceptRelatedQuestion: true,
canSendMessage:
state.sendingState == const SendMessageState.done(),
),
);
},
didUpdateAnswerStream: (AnswerStream stream) {
emit(state.copyWith(answerStream: stream));
},
stopStream: () async {
if (state.answerStream == null) {
return;
didLoadLatestMessages: (List<Message> messages) async {
for (final message in messages) {
await chatController.insert(message, index: 0);
}
final payload = StopStreamPB(chatId: chatId);
await AIEventStopStream(payload).send();
final allMessages = _permanentMessages();
if (state.streamingState != const StreamingState.done()) {
// If the streaming is not started, remove the message from the list
if (!state.answerStream!.hasStarted) {
allMessages.removeWhere(
(element) => element.id == answerStreamMessageId,
);
answerStreamMessageId = "";
}
if (initialFetchCounter < 2) {
initialFetchCounter++;
}
// when stop stream, we will set the answer stream to null. Which means the streaming
// is finished or canceled.
if (state.loadingState.isLoading && initialFetchCounter >= 2) {
emit(
state.copyWith(
messages: allMessages,
answerStream: null,
streamingState: const StreamingState.done(),
),
state.copyWith(loadingState: const ChatLoadingState.finish()),
);
}
},
receiveMessage: (Message message) {
final allMessages = _permanentMessages();
// remove message with the same id
allMessages.removeWhere((element) => element.id == message.id);
allMessages.insert(0, message);
loadPreviousMessages: () {
if (isLoadingPreviousMessages) {
return;
}
final oldestMessage = _getOldestMessage();
if (oldestMessage != null) {
final oldestMessageId = Int64.tryParseInt(oldestMessage.id);
if (oldestMessageId == null) {
Log.error("Failed to parse message_id: ${oldestMessage.id}");
return;
}
isLoadingPreviousMessages = true;
_loadPreviousMessages(oldestMessageId);
}
},
didLoadPreviousMessages: (messages, hasMore) {
Log.debug("did load previous messages: ${messages.length}");
for (final message in messages) {
chatController.insert(message, index: 0);
}
isLoadingPreviousMessages = false;
hasMorePreviousMessages = hasMore;
},
didFinishAnswerStream: () {
emit(
state.copyWith(
messages: allMessages,
),
state.copyWith(promptResponseState: PromptResponseState.ready),
);
},
startAnswerStreaming: (Message message) {
final allMessages = _permanentMessages();
allMessages.insert(0, message);
emit(
state.copyWith(
messages: allMessages,
streamingState: const StreamingState.streaming(),
canSendMessage: false,
),
);
},
sendMessage: (String message, Map<String, dynamic>? metadata) async {
unawaited(_startStreamingMessage(message, metadata, emit));
final allMessages = _permanentMessages();
emit(
state.copyWith(
lastSentMessage: null,
messages: allMessages,
relatedQuestions: [],
acceptRelatedQuestion: false,
sendingState: const SendMessageState.sending(),
canSendMessage: false,
),
);
},
finishSending: (ChatMessagePB message) {
emit(
state.copyWith(
lastSentMessage: message,
sendingState: const SendMessageState.done(),
canSendMessage:
state.streamingState == const StreamingState.done(),
),
);
},
failedSending: () {
emit(
state.copyWith(
messages: _permanentMessages()..removeAt(0),
sendingState: const SendMessageState.done(),
canSendMessage: true,
),
);
},
// related question
didReceiveRelatedQuestion: (List<RelatedQuestionPB> questions) {
didReceiveRelatedQuestions: (List<String> questions) {
if (questions.isEmpty) {
return;
}
final allMessages = _permanentMessages();
final message = CustomMessage(
metadata: OnetimeShotType.relatedQuestion.toMap(),
final metadata = {
onetimeShotType: OnetimeShotType.relatedQuestion,
'questions': questions,
};
final createdAt = DateTime.now();
final message = TextMessage(
id: "related_question_$createdAt",
text: '',
metadata: metadata,
author: const User(id: systemUserId),
showStatus: false,
id: systemUserId,
createdAt: createdAt,
);
allMessages.insert(0, message);
chatController.insert(message);
},
receiveMessage: (Message message) {
final oldMessage = chatController.messages
.firstWhereOrNull((m) => m.id == message.id);
if (oldMessage == null) {
chatController.insert(message);
} else {
chatController.update(oldMessage, message);
}
},
sendMessage: (
String message,
Map<String, dynamic>? metadata,
) {
numSendMessage += 1;
final relatedQuestionMessages = chatController.messages
.where(
(message) =>
onetimeMessageTypeFromMeta(message.metadata) ==
OnetimeShotType.relatedQuestion,
)
.toList();
for (final message in relatedQuestionMessages) {
chatController.remove(message);
}
_startStreamingMessage(message, metadata);
lastSentMessage = null;
emit(
state.copyWith(
messages: allMessages,
relatedQuestions: questions,
promptResponseState: PromptResponseState.sendingQuestion,
),
);
},
clearRelatedQuestions: () {
finishSending: (ChatMessagePB message) {
lastSentMessage = message;
emit(
state.copyWith(
relatedQuestions: [],
promptResponseState: PromptResponseState.awaitingAnswer,
),
);
},
stopStream: () async {
if (answerStream == null) {
return;
}
// tell backend to stop
final payload = StopStreamPB(chatId: chatId);
await AIEventStopStream(payload).send();
// allow user input
emit(
state.copyWith(
promptResponseState: PromptResponseState.ready,
),
);
// no need to remove old message if stream has started already
if (answerStream!.hasStarted) {
return;
}
// remove the non-started message from the list
final message = chatController.messages.lastWhereOrNull(
(e) => e.id == answerStreamMessageId,
);
if (message != null) {
await chatController.remove(message);
}
// set answer stream to null
await answerStream?.dispose();
answerStream = null;
answerStreamMessageId = '';
},
startAnswerStreaming: (Message message) {
chatController.insert(message);
emit(
state.copyWith(
promptResponseState: PromptResponseState.streamingAnswer,
),
);
},
failedSending: () {
final lastMessage = chatController.messages.lastOrNull;
if (lastMessage != null) {
chatController.remove(lastMessage);
}
emit(
state.copyWith(
promptResponseState: PromptResponseState.ready,
),
);
},
@@ -264,29 +255,31 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
void _startListening() {
listener.start(
chatMessageCallback: (pb) {
if (!isClosed) {
// 3 mean message response from AI
if (pb.authorType == 3 && answerStreamMessageId.isNotEmpty) {
temporaryMessageIDMap[pb.messageId.toString()] =
answerStreamMessageId;
answerStreamMessageId = "";
}
// 1 mean message response from User
if (pb.authorType == 1 && questionStreamMessageId.isNotEmpty) {
temporaryMessageIDMap[pb.messageId.toString()] =
questionStreamMessageId;
questionStreamMessageId = "";
}
final message = _createTextMessage(pb);
add(ChatEvent.receiveMessage(message));
if (isClosed) {
return;
}
// 3 mean message response from AI
if (pb.authorType == 3 && answerStreamMessageId.isNotEmpty) {
temporaryMessageIDMap[pb.messageId.toString()] =
answerStreamMessageId;
answerStreamMessageId = '';
}
// 1 mean message response from User
if (pb.authorType == 1 && questionStreamMessageId.isNotEmpty) {
temporaryMessageIDMap[pb.messageId.toString()] =
questionStreamMessageId;
questionStreamMessageId = '';
}
final message = _createTextMessage(pb);
add(ChatEvent.receiveMessage(message));
},
chatErrorMessageCallback: (err) {
if (!isClosed) {
Log.error("chat error: ${err.errorMessage}");
add(const ChatEvent.finishAnswerStreaming());
add(const ChatEvent.didFinishAnswerStream());
}
},
latestMessageCallback: (list) {
@@ -301,65 +294,74 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
add(ChatEvent.didLoadPreviousMessages(messages, list.hasMore));
}
},
finishStreamingCallback: () {
if (!isClosed) {
add(const ChatEvent.finishAnswerStreaming());
// The answer strema will bet set to null after the streaming is finished or canceled.
// so if the answer stream is null, we will not get related question.
if (state.lastSentMessage != null && state.answerStream != null) {
final payload = ChatMessageIdPB(
chatId: chatId,
messageId: state.lastSentMessage!.messageId,
);
// When user message was sent to the server, we start gettting related question
AIEventGetRelatedQuestion(payload).send().then((result) {
if (!isClosed) {
result.fold(
(list) {
if (state.acceptRelatedQuestion) {
add(ChatEvent.didReceiveRelatedQuestion(list.items));
}
},
(err) {
Log.error("Failed to get related question: $err");
},
);
}
});
}
finishStreamingCallback: () async {
if (isClosed) {
return;
}
add(const ChatEvent.didFinishAnswerStream());
// The answer stream will bet set to null after the streaming has
// finished, got cancelled, or errored. In this case, don't retrieve
// related questions.
if (answerStream == null || lastSentMessage == null) {
return;
}
final payload = ChatMessageIdPB(
chatId: chatId,
messageId: lastSentMessage!.messageId,
);
// when previous numSendMessage is not equal to current numSendMessage, it means that the user
// has sent a new message. So we don't need to get related questions.
final preNumSendMessage = numSendMessage;
await AIEventGetRelatedQuestion(payload).send().fold(
(list) {
if (!isClosed && preNumSendMessage == numSendMessage) {
add(
ChatEvent.didReceiveRelatedQuestions(
list.items.map((e) => e.content).toList(),
),
);
}
},
(err) => Log.error("Failed to get related questions: $err"),
);
},
);
}
// Returns the list of messages that are not include one-time messages.
List<Message> _permanentMessages() {
final allMessages = state.messages.where((element) {
return !(element.metadata?.containsKey(onetimeShotType) == true);
}).toList();
return allMessages;
void _init() async {
final payload = LoadNextChatMessagePB(
chatId: chatId,
limit: Int64(10),
);
await AIEventLoadNextMessage(payload).send().fold(
(list) {
if (!isClosed) {
final messages = list.messages.map(_createTextMessage).toList();
add(ChatEvent.didLoadLatestMessages(messages));
}
},
(err) => Log.error("Failed to load messages: $err"),
);
}
List<Message> _getOnetimeMessages() {
final messages = state.messages.where((element) {
return (element.metadata?.containsKey(onetimeShotType) == true);
}).toList();
return messages;
bool _isOneTimeMessage(Message message) {
return message.metadata != null &&
message.metadata!.containsKey(onetimeShotType);
}
/// get the last message that is not a one-time message
Message? _getOldestMessage() {
// get the last message that is not a one-time message
final message = state.messages.lastWhereOrNull((element) {
return !(element.metadata?.containsKey(onetimeShotType) == true);
});
return message;
return chatController.messages
.firstWhereOrNull((message) => !_isOneTimeMessage(message));
}
void _loadPrevMessage(Int64? beforeMessageId) {
void _loadPreviousMessages(Int64? beforeMessageId) {
final payload = LoadPrevChatMessagePB(
chatId: state.view.id,
chatId: chatId,
limit: Int64(10),
beforeMessageId: beforeMessageId,
);
@@ -369,59 +371,56 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
Future<void> _startStreamingMessage(
String message,
Map<String, dynamic>? metadata,
Emitter<ChatState> emit,
) async {
if (state.answerStream != null) {
await state.answerStream?.dispose();
}
await answerStream?.dispose();
final answerStream = AnswerStream();
answerStream = AnswerStream();
final questionStream = QuestionStream();
add(ChatEvent.didUpdateAnswerStream(answerStream));
final payload = StreamChatPayloadPB(
chatId: state.view.id,
message: message,
messageType: ChatMessageTypePB.User,
questionStreamPort: Int64(questionStream.nativePort),
answerStreamPort: Int64(answerStream.nativePort),
metadata: await metadataPBFromMetadata(metadata),
);
// add a streaming question message
final questionStreamMessage = _createQuestionStreamMessage(
questionStream,
metadata,
);
add(ChatEvent.receiveMessage(questionStreamMessage));
// Stream message to the server
final result = await AIEventStreamMessage(payload).send();
result.fold(
(ChatMessagePB question) {
final payload = StreamChatPayloadPB(
chatId: chatId,
message: message,
messageType: ChatMessageTypePB.User,
questionStreamPort: Int64(questionStream.nativePort),
answerStreamPort: Int64(answerStream!.nativePort),
metadata: await metadataPBFromMetadata(metadata),
);
// stream the question to the server
await AIEventStreamMessage(payload).send().fold(
(question) {
if (!isClosed) {
final streamAnswer = _createAnswerStreamMessage(
answerStream!,
question.messageId,
);
add(ChatEvent.finishSending(question));
// final message = _createTextMessage(question);
// add(ChatEvent.receiveMessage(message));
final streamAnswer =
_createAnswerStreamMessage(answerStream, question.messageId);
add(ChatEvent.startAnswerStreaming(streamAnswer));
}
},
(err) {
if (!isClosed) {
Log.error("Failed to send message: ${err.msg}");
final metadata = OnetimeShotType.invalidSendMesssage.toMap();
if (err.code != ErrorCode.Internal) {
metadata[sendMessageErrorKey] = err.msg;
}
final error = CustomMessage(
final metadata = {
onetimeShotType: OnetimeShotType.error,
if (err.code != ErrorCode.Internal) errorMessageTextKey: err.msg,
};
final error = TextMessage(
text: '',
metadata: metadata,
author: const User(id: systemUserId),
showStatus: false,
id: systemUserId,
createdAt: DateTime.now(),
);
add(const ChatEvent.failedSending());
@@ -435,20 +434,18 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
AnswerStream stream,
Int64 questionMessageId,
) {
final streamMessageId = (questionMessageId + 1).toString();
answerStreamMessageId = streamMessageId;
answerStreamMessageId = (questionMessageId + 1).toString();
return TextMessage(
id: answerStreamMessageId,
text: '',
author: User(id: "streamId:${nanoid()}"),
metadata: {
"$AnswerStream": stream,
messageQuestionIdKey: questionMessageId,
"chatId": chatId,
},
id: streamMessageId,
showStatus: false,
createdAt: DateTime.now().millisecondsSinceEpoch,
text: '',
createdAt: DateTime.now(),
);
}
@@ -457,24 +454,18 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
Map<String, dynamic>? sentMetadata,
) {
final now = DateTime.now();
final timestamp = now.millisecondsSinceEpoch;
questionStreamMessageId = timestamp.toString();
final Map<String, dynamic> metadata = {};
// if (sentMetadata != null) {
// metadata[messageMetadataJsonStringKey] = sentMetadata;
// }
questionStreamMessageId = (now.millisecondsSinceEpoch ~/ 1000).toString();
metadata["$QuestionStream"] = stream;
metadata["chatId"] = chatId;
metadata[messageChatFileListKey] =
chatFilesFromMessageMetadata(sentMetadata);
return TextMessage(
author: User(id: state.userProfile.id.toString()),
metadata: metadata,
author: User(id: userId),
metadata: {
"$QuestionStream": stream,
"chatId": chatId,
messageChatFileListKey: chatFilesFromMessageMetadata(sentMetadata),
},
id: questionStreamMessageId,
showStatus: false,
createdAt: DateTime.now().millisecondsSinceEpoch,
createdAt: now,
text: '',
);
}
@@ -491,8 +482,7 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
author: User(id: message.authorId),
id: messageId,
text: message.content,
createdAt: message.createdAt.toInt() * 1000,
showStatus: false,
createdAt: message.createdAt.toDateTime(),
metadata: {
messageRefSourceJsonStringKey: message.metadata,
},
@@ -502,8 +492,6 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
@freezed
class ChatEvent with _$ChatEvent {
const factory ChatEvent.initialLoad() = _InitialLoadMessage;
// send message
const factory ChatEvent.sendMessage({
required String message,
@@ -513,71 +501,40 @@ class ChatEvent with _$ChatEvent {
_FinishSendMessage;
const factory ChatEvent.failedSending() = _FailSendMessage;
// receive message
// streaming answer
const factory ChatEvent.startAnswerStreaming(Message message) =
_StartAnswerStreaming;
const factory ChatEvent.receiveMessage(Message message) = _ReceiveMessage;
const factory ChatEvent.finishAnswerStreaming() = _FinishAnswerStreaming;
const factory ChatEvent.stopStream() = _StopStream;
const factory ChatEvent.didFinishAnswerStream() = _DidFinishAnswerStream;
// loading messages
const factory ChatEvent.startLoadingPrevMessage() = _StartLoadPrevMessage;
// receive message
const factory ChatEvent.receiveMessage(Message message) = _ReceiveMessage;
// loading messages
const factory ChatEvent.didLoadLatestMessages(List<Message> messages) =
_DidLoadMessages;
const factory ChatEvent.loadPreviousMessages() = _LoadPreviousMessages;
const factory ChatEvent.didLoadPreviousMessages(
List<Message> messages,
bool hasMore,
) = _DidLoadPreviousMessages;
const factory ChatEvent.didLoadLatestMessages(List<Message> messages) =
_DidLoadMessages;
// related questions
const factory ChatEvent.didReceiveRelatedQuestion(
List<RelatedQuestionPB> questions,
// related questions
const factory ChatEvent.didReceiveRelatedQuestions(
List<String> questions,
) = _DidReceiveRelatedQueston;
const factory ChatEvent.clearRelatedQuestions() = _ClearRelatedQuestions;
const factory ChatEvent.didUpdateAnswerStream(
AnswerStream stream,
) = _DidUpdateAnswerStream;
const factory ChatEvent.stopStream() = _StopStream;
}
@freezed
class ChatState with _$ChatState {
const factory ChatState({
required ViewPB view,
required List<Message> messages,
required UserProfilePB userProfile,
// When opening the chat, the initial loading status will be set as loading.
//After the initial loading is done, the status will be set as finished.
required ChatLoadingState initialLoadingStatus,
// When loading previous messages, the status will be set as loading.
// After the loading is done, the status will be set as finished.
required ChatLoadingState loadingPreviousStatus,
// When sending a user message, the status will be set as loading.
// After the message is sent, the status will be set as finished.
required StreamingState streamingState,
required SendMessageState sendingState,
// Indicate whether there are more previous messages to load.
required bool hasMorePrevMessage,
// The related questions that are received after the user message is sent.
required List<RelatedQuestionPB> relatedQuestions,
@Default(false) bool acceptRelatedQuestion,
// The last user message that is sent to the server.
ChatMessagePB? lastSentMessage,
AnswerStream? answerStream,
@Default(true) bool canSendMessage,
required ChatLoadingState loadingState,
required PromptResponseState promptResponseState,
}) = _ChatState;
factory ChatState.initial(ViewPB view, UserProfilePB userProfile) =>
ChatState(
view: view,
messages: [],
userProfile: userProfile,
initialLoadingStatus: const ChatLoadingState.finish(),
loadingPreviousStatus: const ChatLoadingState.finish(),
streamingState: const StreamingState.done(),
sendingState: const SendMessageState.done(),
hasMorePrevMessage: true,
relatedQuestions: [],
factory ChatState.initial() => const ChatState(
loadingState: ChatLoadingState.loading(),
promptResponseState: PromptResponseState.ready,
);
}
@@ -1,6 +1,5 @@
import 'dart:io';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:equatable/equatable.dart';
@@ -10,7 +9,7 @@ import 'package:path/path.dart' as path;
part 'chat_entity.g.dart';
part 'chat_entity.freezed.dart';
const sendMessageErrorKey = "sendMessageError";
const errorMessageTextKey = "errorMessageText";
const systemUserId = "system";
const aiResponseUserId = "0";
@@ -40,16 +39,25 @@ class ChatMessageRefSource {
Map<String, dynamic> toJson() => _$ChatMessageRefSourceToJson(this);
}
@freezed
class StreamingState with _$StreamingState {
const factory StreamingState.streaming() = _Streaming;
const factory StreamingState.done({FlowyError? error}) = _StreamDone;
@JsonSerializable()
class AIChatProgress {
AIChatProgress({
required this.step,
});
factory AIChatProgress.fromJson(Map<String, dynamic> json) =>
_$AIChatProgressFromJson(json);
final String step;
Map<String, dynamic> toJson() => _$AIChatProgressToJson(this);
}
@freezed
class SendMessageState with _$SendMessageState {
const factory SendMessageState.sending() = _Sending;
const factory SendMessageState.done({FlowyError? error}) = _SendDone;
enum PromptResponseState {
ready,
sendingQuestion,
awaitingAnswer,
streamingAnswer,
}
class ChatFile extends Equatable {
@@ -112,45 +120,13 @@ extension ChatLoadingStateExtension on ChatLoadingState {
}
enum OnetimeShotType {
unknown,
sendingMessage,
relatedQuestion,
invalidSendMesssage,
error,
}
const onetimeShotType = "OnetimeShotType";
extension OnetimeMessageTypeExtension on OnetimeShotType {
static OnetimeShotType fromString(String value) {
switch (value) {
case 'OnetimeShotType.sendingMessage':
return OnetimeShotType.sendingMessage;
case 'OnetimeShotType.relatedQuestion':
return OnetimeShotType.relatedQuestion;
case 'OnetimeShotType.invalidSendMesssage':
return OnetimeShotType.invalidSendMesssage;
default:
Log.error('Unknown OnetimeShotType: $value');
return OnetimeShotType.unknown;
}
}
Map<String, dynamic> toMap() {
return {
onetimeShotType: toString(),
};
}
}
OnetimeShotType? onetimeMessageTypeFromMeta(Map<String, dynamic>? metadata) {
if (metadata == null) {
return null;
}
for (final entry in metadata.entries) {
if (entry.key == onetimeShotType) {
return OnetimeMessageTypeExtension.fromString(entry.value as String);
}
}
return null;
return metadata?[onetimeShotType];
}
@@ -7,7 +7,7 @@ import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:nanoid/nanoid.dart';
/// Indicate file source from appflowy document
@@ -66,78 +66,101 @@ ChatFile? chatFileFromMap(Map<String, dynamic>? map) {
return ChatFile.fromFilePath(filePath);
}
List<ChatMessageRefSource> messageReferenceSource(String? s) {
if (s == null || s.isEmpty || s == "null") {
return [];
class MetadataCollection {
MetadataCollection({
required this.sources,
this.progress,
});
final List<ChatMessageRefSource> sources;
final AIChatProgress? progress;
}
MetadataCollection parseMetadata(String? s) {
if (s == null || s.trim().isEmpty || s.toLowerCase() == "null") {
return MetadataCollection(sources: []);
}
final List<ChatMessageRefSource> metadata = [];
try {
final metadataJson = jsonDecode(s);
if (metadataJson == null) {
Log.warn("metadata is null");
return [];
}
// [{"id":null,"name":"The Five Dysfunctions of a Team.pdf","source":"/Users/weidongfu/Desktop/The Five Dysfunctions of a Team.pdf"}]
AIChatProgress? progress;
if (metadataJson is Map<String, dynamic>) {
if (metadataJson.isNotEmpty) {
metadata.add(ChatMessageRefSource.fromJson(metadataJson));
}
} else if (metadataJson is List) {
metadata.addAll(
metadataJson.map(
(e) => ChatMessageRefSource.fromJson(e as Map<String, dynamic>),
),
);
} else {
Log.error("Invalid metadata: $metadataJson");
try {
final dynamic decodedJson = jsonDecode(s);
if (decodedJson == null) {
return MetadataCollection(sources: []);
}
} catch (e) {
Log.error("Failed to parse metadata: $e");
void processMap(Map<String, dynamic> map) {
if (map.containsKey("step") && map["step"] != null) {
progress = AIChatProgress.fromJson(map);
} else if (map.containsKey("id") && map["id"] != null) {
metadata.add(ChatMessageRefSource.fromJson(map));
} else {
Log.info("Unsupported metadata format: $map");
}
}
if (decodedJson is Map<String, dynamic>) {
processMap(decodedJson);
} else if (decodedJson is List) {
for (final element in decodedJson) {
if (element is Map<String, dynamic>) {
processMap(element);
} else {
Log.error("Invalid metadata element: $element");
}
}
} else {
Log.error("Invalid metadata format: $decodedJson");
}
} catch (e, stacktrace) {
Log.error("Failed to parse metadata: $e, input: $s");
Log.debug(stacktrace.toString());
}
return metadata;
return MetadataCollection(sources: metadata, progress: progress);
}
Future<List<ChatMessageMetaPB>> metadataPBFromMetadata(
Map<String, dynamic>? map,
) async {
if (map == null) return [];
final List<ChatMessageMetaPB> metadata = [];
if (map != null) {
for (final entry in map.entries) {
if (entry.value is ViewActionPage) {
if (entry.value.page is ViewPB) {
final view = entry.value.page as ViewPB;
if (view.layout.isDocumentView) {
final payload = OpenDocumentPayloadPB(documentId: view.id);
final result = await DocumentEventGetDocumentText(payload).send();
result.fold((pb) {
metadata.add(
ChatMessageMetaPB(
id: view.id,
name: view.name,
data: pb.text,
dataType: ChatMessageMetaTypePB.Txt,
source: appflowySource,
),
);
}, (err) {
Log.error('Failed to get document text: $err');
});
}
}
} else if (entry.value is ChatFile) {
for (final value in map.values) {
switch (value) {
case ViewActionPage(view: final view) when view.layout.isDocumentView:
final payload = OpenDocumentPayloadPB(documentId: view.id);
await DocumentEventGetDocumentText(payload).send().fold(
(pb) {
metadata.add(
ChatMessageMetaPB(
id: view.id,
name: view.name,
data: pb.text,
dataType: ChatMessageMetaTypePB.Txt,
source: appflowySource,
),
);
},
(err) => Log.error('Failed to get document text: $err'),
);
break;
case ChatFile(
filePath: final filePath,
fileName: final fileName,
fileType: final fileType,
):
metadata.add(
ChatMessageMetaPB(
id: nanoid(8),
name: entry.value.fileName,
data: entry.value.filePath,
dataType: entry.value.fileType,
source: entry.value.filePath,
name: fileName,
data: filePath,
dataType: fileType,
source: filePath,
),
);
}
break;
}
}
@@ -2,7 +2,6 @@ import 'dart:async';
import 'dart:ffi';
import 'dart:isolate';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_service.dart';
class AnswerStream {
@@ -14,34 +13,25 @@ class AnswerStream {
_hasStarted = true;
final newText = event.substring(5);
_text += newText;
if (_onData != null) {
_onData!(_text);
}
_onData?.call(_text);
} else if (event.startsWith("error:")) {
_error = event.substring(5);
if (_onError != null) {
_onError!(_error!);
}
_onError?.call(_error!);
} else if (event.startsWith("metadata:")) {
if (_onMetadata != null) {
final s = event.substring(9);
_onMetadata!(messageReferenceSource(s));
_onMetadata!(parseMetadata(s));
}
} else if (event == "AI_RESPONSE_LIMIT") {
if (_onAIResponseLimit != null) {
_onAIResponseLimit!();
}
_aiLimitReached = true;
_onAIResponseLimit?.call();
}
},
onDone: () {
if (_onEnd != null) {
_onEnd!();
}
_onEnd?.call();
},
onError: (error) {
if (_onError != null) {
_onError!(error.toString());
}
_onError?.call(error.toString());
},
);
}
@@ -50,6 +40,7 @@ class AnswerStream {
final StreamController<String> _controller = StreamController.broadcast();
late StreamSubscription<String> _subscription;
bool _hasStarted = false;
bool _aiLimitReached = false;
String? _error;
String _text = "";
@@ -59,10 +50,11 @@ class AnswerStream {
void Function()? _onEnd;
void Function(String error)? _onError;
void Function()? _onAIResponseLimit;
void Function(List<ChatMessageRefSource> metadata)? _onMetadata;
void Function(MetadataCollection metadataCollection)? _onMetadata;
int get nativePort => _port.sendPort.nativePort;
bool get hasStarted => _hasStarted;
bool get aiLimitReached => _aiLimitReached;
String? get error => _error;
String get text => _text;
@@ -78,7 +70,7 @@ class AnswerStream {
void Function()? onEnd,
void Function(String error)? onError,
void Function()? onAIResponseLimit,
void Function(List<ChatMessageRefSource> metadata)? onMetadata,
void Function(MetadataCollection metadata)? onMetadata,
}) {
_onData = onData;
_onStart = onStart;
@@ -87,9 +79,7 @@ class AnswerStream {
_onAIResponseLimit = onAIResponseLimit;
_onMetadata = onMetadata;
if (_onStart != null) {
_onStart!();
}
_onStart?.call();
}
}
@@ -8,76 +8,19 @@ part 'chat_user_message_bloc.freezed.dart';
class ChatUserMessageBloc
extends Bloc<ChatUserMessageEvent, ChatUserMessageState> {
ChatUserMessageBloc({
required dynamic message,
}) : super(
ChatUserMessageState.initial(
message,
),
) {
required this.questionStream,
required String text,
}) : super(ChatUserMessageState.initial(text)) {
_dispatch();
_startListening();
}
final QuestionStream? questionStream;
void _dispatch() {
on<ChatUserMessageEvent>(
(event, emit) {
event.when(
initial: () {
if (state.stream != null) {
if (!isClosed) {
add(ChatUserMessageEvent.updateText(state.stream!.text));
}
}
state.stream?.listen(
onData: (text) {
if (!isClosed) {
add(ChatUserMessageEvent.updateText(text));
}
},
onMessageId: (messageId) {
if (!isClosed) {
add(ChatUserMessageEvent.updateMessageId(messageId));
}
},
onError: (error) {
if (!isClosed) {
add(ChatUserMessageEvent.receiveError(error.toString()));
}
},
onFileIndexStart: (indexName) {
Log.debug("index start: $indexName");
},
onFileIndexEnd: (indexName) {
Log.info("index end: $indexName");
},
onFileIndexFail: (indexName) {
Log.debug("index fail: $indexName");
},
onIndexStart: () {
if (!isClosed) {
add(
const ChatUserMessageEvent.updateQuestionState(
QuestionMessageState.indexStart(),
),
);
}
},
onIndexEnd: () {
if (!isClosed) {
add(
const ChatUserMessageEvent.updateQuestionState(
QuestionMessageState.indexEnd(),
),
);
}
},
onDone: () {
if (!isClosed) {
add(
const ChatUserMessageEvent.updateQuestionState(
QuestionMessageState.finish(),
),
);
}
},
);
},
updateText: (String text) {
emit(state.copyWith(text: text));
},
@@ -92,11 +35,66 @@ class ChatUserMessageBloc
},
);
}
void _startListening() {
questionStream?.listen(
onData: (text) {
if (!isClosed) {
add(ChatUserMessageEvent.updateText(text));
}
},
onMessageId: (messageId) {
if (!isClosed) {
add(ChatUserMessageEvent.updateMessageId(messageId));
}
},
onError: (error) {
if (!isClosed) {
add(ChatUserMessageEvent.receiveError(error.toString()));
}
},
onFileIndexStart: (indexName) {
Log.debug("index start: $indexName");
},
onFileIndexEnd: (indexName) {
Log.info("index end: $indexName");
},
onFileIndexFail: (indexName) {
Log.debug("index fail: $indexName");
},
onIndexStart: () {
if (!isClosed) {
add(
const ChatUserMessageEvent.updateQuestionState(
QuestionMessageState.indexStart(),
),
);
}
},
onIndexEnd: () {
if (!isClosed) {
add(
const ChatUserMessageEvent.updateQuestionState(
QuestionMessageState.indexEnd(),
),
);
}
},
onDone: () {
if (!isClosed) {
add(
const ChatUserMessageEvent.updateQuestionState(
QuestionMessageState.finish(),
),
);
}
},
);
}
}
@freezed
class ChatUserMessageEvent with _$ChatUserMessageEvent {
const factory ChatUserMessageEvent.initial() = Initial;
const factory ChatUserMessageEvent.updateText(String text) = _UpdateText;
const factory ChatUserMessageEvent.updateQuestionState(
QuestionMessageState newState,
@@ -110,17 +108,14 @@ class ChatUserMessageEvent with _$ChatUserMessageEvent {
class ChatUserMessageState with _$ChatUserMessageState {
const factory ChatUserMessageState({
required String text,
QuestionStream? stream,
String? messageId,
@Default(QuestionMessageState.finish()) QuestionMessageState messageState,
required String? messageId,
required QuestionMessageState messageState,
}) = _ChatUserMessageState;
factory ChatUserMessageState.initial(
dynamic message,
) =>
ChatUserMessageState(
text: message is String ? message : "",
stream: message is QuestionStream ? message : null,
factory ChatUserMessageState.initial(String message) => ChatUserMessageState(
text: message,
messageId: null,
messageState: const QuestionMessageState.finish(),
);
}
@@ -1,60 +0,0 @@
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'chat_message_service.dart';
part 'chat_user_message_bubble_bloc.freezed.dart';
class ChatUserMessageBubbleBloc
extends Bloc<ChatUserMessageBubbleEvent, ChatUserMessageBubbleState> {
ChatUserMessageBubbleBloc({
required Message message,
}) : super(
ChatUserMessageBubbleState.initial(
message,
_getFiles(message.metadata),
),
) {
on<ChatUserMessageBubbleEvent>(
(event, emit) async {
event.when(
initial: () {},
);
},
);
}
}
List<ChatFile> _getFiles(Map<String, dynamic>? metadata) {
if (metadata == null) {
return [];
}
final refSourceMetadata = metadata[messageRefSourceJsonStringKey] as String?;
final files = metadata[messageChatFileListKey] as List<ChatFile>?;
if (refSourceMetadata != null) {
return chatFilesFromMetadataString(refSourceMetadata);
}
return files ?? [];
}
@freezed
class ChatUserMessageBubbleEvent with _$ChatUserMessageBubbleEvent {
const factory ChatUserMessageBubbleEvent.initial() = Initial;
}
@freezed
class ChatUserMessageBubbleState with _$ChatUserMessageBubbleState {
const factory ChatUserMessageBubbleState({
required Message message,
required List<ChatFile> files,
}) = _ChatUserMessageBubbleState;
factory ChatUserMessageBubbleState.initial(
Message message,
List<ChatFile> files,
) =>
ChatUserMessageBubbleState(message: message, files: files);
}
@@ -2,6 +2,7 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/ai_chat/chat_page.dart';
import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view_info/view_info_bloc.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart';
import 'package:appflowy/workspace/presentation/widgets/tab_bar_item.dart';
@@ -85,12 +86,16 @@ class AIChatPagePluginWidgetBuilder extends PluginWidgetBuilder
final ViewPluginNotifier notifier;
int? deletedViewIndex;
@override
String? get viewName => notifier.view.nameOrDefault;
@override
Widget get leftBarItem =>
ViewTitleBar(key: ValueKey(notifier.view.id), view: notifier.view);
@override
Widget tabBarItem(String pluginId) => ViewTabBarItem(view: notifier.view);
Widget tabBarItem(String pluginId, [bool shortForm = false]) =>
ViewTabBarItem(view: notifier.view, shortForm: shortForm);
@override
Widget buildWidget({
@@ -4,32 +4,31 @@ import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
import 'package:appflowy/plugins/ai_chat/presentation/chat_related_question.dart';
import 'package:appflowy/plugins/ai_chat/presentation/message/user_message_bubble.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:flutter_chat_ui/flutter_chat_ui.dart' show Chat;
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'package:flutter_chat_ui/flutter_chat_ui.dart'
hide ChatAnimatedListReversed;
import 'package:styled_widget/styled_widget.dart';
import 'package:universal_platform/universal_platform.dart';
import 'application/chat_member_bloc.dart';
import 'application/chat_side_panel_bloc.dart';
import 'presentation/animated_chat_list.dart';
import 'presentation/chat_input/desktop_ai_prompt_input.dart';
import 'presentation/chat_input/mobile_ai_prompt_input.dart';
import 'presentation/chat_side_panel.dart';
import 'presentation/chat_theme.dart';
import 'presentation/chat_user_invalid_message.dart';
import 'presentation/chat_welcome_page.dart';
import 'presentation/layout_define.dart';
import 'presentation/message/ai_text_message.dart';
import 'presentation/message/error_text_message.dart';
import 'presentation/message/user_text_message.dart';
import 'presentation/scroll_to_bottom.dart';
class AIChatPage extends StatelessWidget {
const AIChatPage({
@@ -59,9 +58,9 @@ class AIChatPage extends StatelessWidget {
/// [ChatBloc] is used to handle chat messages including send/receive message
BlocProvider(
create: (_) => ChatBloc(
view: view,
userProfile: userProfile,
)..add(const ChatEvent.initialLoad()),
chatId: view.id,
userId: userProfile.id.toString(),
),
),
/// [AIPromptInputBloc] is used to handle the user prompt
@@ -69,20 +68,24 @@ class AIChatPage extends StatelessWidget {
BlocProvider(create: (_) => ChatSidePanelBloc(chatId: view.id)),
BlocProvider(create: (_) => ChatMemberBloc()),
],
child: DropTarget(
onDragDone: (DropDoneDetails detail) async {
if (context.read<AIPromptInputBloc>().state.supportChatWithFile) {
for (final file in detail.files) {
context
.read<AIPromptInputBloc>()
.add(AIPromptInputEvent.newFile(file.path, file.name));
}
}
child: Builder(
builder: (context) {
return DropTarget(
onDragDone: (DropDoneDetails detail) async {
if (context.read<AIPromptInputBloc>().state.supportChatWithFile) {
for (final file in detail.files) {
context
.read<AIPromptInputBloc>()
.add(AIPromptInputEvent.newFile(file.path, file.name));
}
}
},
child: _ChatContentPage(
view: view,
userProfile: userProfile,
),
);
},
child: _ChatContentPage(
view: view,
userProfile: userProfile,
),
),
);
}
@@ -113,11 +116,11 @@ class _ChatContentPage extends StatelessWidget {
return Row(
children: [
Center(
child: buildChatWidget()
child: buildChatWidget(context)
.constrained(
maxWidth: 784,
)
.padding(horizontal: 32)
.padding(horizontal: 60)
.animate(
const Duration(milliseconds: 200),
Curves.easeOut,
@@ -148,7 +151,7 @@ class _ChatContentPage extends StatelessWidget {
Flexible(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 784),
child: buildChatWidget(),
child: buildChatWidget(context),
),
),
],
@@ -167,187 +170,187 @@ class _ChatContentPage extends StatelessWidget {
);
}
Widget buildChatWidget() {
return BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
return ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: BlocBuilder<ChatBloc, ChatState>(
builder: (_, state) => state.initialLoadingStatus.isFinish
? Chat(
messages: state.messages,
dateHeaderBuilder: (_) => const SizedBox.shrink(),
onSendPressed: (_) {
// We use custom bottom widget for chat input, so
// do not need to handle this event.
},
customBottomWidget: _buildBottom(context),
user: types.User(id: userProfile.id.toString()),
theme: _buildTheme(context),
onEndReached: () async {
if (state.hasMorePrevMessage &&
state.loadingPreviousStatus.isFinish) {
context
.read<ChatBloc>()
.add(const ChatEvent.startLoadingPrevMessage());
}
},
emptyState: TextFieldTapRegion(
child: ChatWelcomePage(
userProfile: userProfile,
onSelectedQuestion: (question) => context
.read<ChatBloc>()
.add(ChatEvent.sendMessage(message: question)),
Widget buildChatWidget(BuildContext context) {
return ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
return state.loadingState.when(
loading: () {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
},
finish: (_) {
final chatController = context.read<ChatBloc>().chatController;
return Column(
children: [
Expanded(
child: Chat(
chatController: chatController,
user: User(id: userProfile.id.toString()),
darkTheme: ChatTheme.fromThemeData(Theme.of(context)),
theme: ChatTheme.fromThemeData(Theme.of(context)),
builders: Builders(
inputBuilder: (_) => const SizedBox.shrink(),
textMessageBuilder: _buildTextMessage,
chatMessageBuilder: _buildChatMessage,
scrollToBottomBuilder: _buildScrollToBottom,
chatAnimatedListBuilder: _buildChatAnimatedList,
),
),
messageWidthRatio: AIChatUILayout.messageWidthRatio,
textMessageBuilder: (
textMessage, {
required messageWidth,
required showName,
}) =>
_buildTextMessage(context, textMessage, state),
customMessageBuilder: (message, {required messageWidth}) {
final messageType = onetimeMessageTypeFromMeta(
message.metadata,
);
if (messageType == OnetimeShotType.invalidSendMesssage) {
return ChatInvalidUserMessage(
message: message,
);
}
if (messageType == OnetimeShotType.relatedQuestion) {
return RelatedQuestionList(
relatedQuestions: state.relatedQuestions,
onQuestionSelected: (question) {
final bloc = context.read<ChatBloc>();
bloc
..add(ChatEvent.sendMessage(message: question))
..add(const ChatEvent.clearRelatedQuestions());
},
);
}
return const SizedBox.shrink();
},
bubbleBuilder: (
child, {
required message,
required nextMessageInGroup,
}) =>
_buildBubble(context, message, child),
)
: const Center(
child: CircularProgressIndicator.adaptive(),
),
),
);
},
_buildInput(context),
],
);
},
);
},
),
);
}
Widget _buildTextMessage(
BuildContext context,
TextMessage message,
ChatState state,
) {
if (message.author.id == userProfile.id.toString()) {
final stream = message.metadata?["$QuestionStream"];
return ChatUserMessageWidget(
key: ValueKey(message.id),
user: message.author,
message: stream is QuestionStream ? stream : message.text,
);
} else if (isOtherUserMessage(message)) {
final stream = message.metadata?["$QuestionStream"];
return ChatUserMessageWidget(
key: ValueKey(message.id),
user: message.author,
message: stream is QuestionStream ? stream : message.text,
);
} else {
final stream = message.metadata?["$AnswerStream"];
final questionId = message.metadata?[messageQuestionIdKey];
final refSourceJsonString =
message.metadata?[messageRefSourceJsonStringKey] as String?;
final messageType = onetimeMessageTypeFromMeta(
message.metadata,
);
return BlocSelector<ChatBloc, ChatState, bool>(
key: ValueKey(message.id),
selector: (state) {
final messages = state.messages.where((e) {
final oneTimeMessageType = onetimeMessageTypeFromMeta(e.metadata);
if (oneTimeMessageType == null) {
return true;
}
if (oneTimeMessageType
case OnetimeShotType.relatedQuestion ||
OnetimeShotType.sendingMessage ||
OnetimeShotType.invalidSendMesssage) {
return false;
}
return true;
});
return messages.isEmpty ? false : messages.first.id == message.id;
},
builder: (context, isLastMessage) {
return ChatAIMessageWidget(
user: message.author,
messageUserId: message.id,
message: message,
stream: stream is AnswerStream ? stream : null,
questionId: questionId,
chatId: view.id,
refSourceJsonString: refSourceJsonString,
isLastMessage: isLastMessage,
onSelectedMetadata: (metadata) {
context
.read<ChatSidePanelBloc>()
.add(ChatSidePanelEvent.selectedMetadata(metadata));
},
);
if (messageType == OnetimeShotType.error) {
return ChatErrorMessageWidget(
errorMessage: message.metadata?[errorMessageTextKey] ?? "",
);
}
if (messageType == OnetimeShotType.relatedQuestion) {
return RelatedQuestionList(
relatedQuestions: message.metadata!['questions'],
onQuestionSelected: (question) {
context
.read<ChatBloc>()
.add(ChatEvent.sendMessage(message: question));
},
);
}
}
Widget _buildBubble(
BuildContext context,
Message message,
Widget child,
) {
if (message.author.id == userProfile.id.toString()) {
return ChatUserMessageBubble(
return ChatUserMessageWidget(
user: message.author,
message: message,
child: child,
isCurrentUser: true,
);
} else if (isOtherUserMessage(message)) {
return ChatUserMessageBubble(
}
if (isOtherUserMessage(message)) {
return ChatUserMessageWidget(
user: message.author,
message: message,
isCurrentUser: false,
child: child,
);
} else {
// The bubble is rendered in the child already
return child;
}
final stream = message.metadata?["$AnswerStream"];
final questionId = message.metadata?[messageQuestionIdKey];
final refSourceJsonString =
message.metadata?[messageRefSourceJsonStringKey] as String?;
return BlocSelector<ChatBloc, ChatState, bool>(
selector: (state) {
final chatController = context.read<ChatBloc>().chatController;
final messages = chatController.messages
.where((e) => onetimeMessageTypeFromMeta(e.metadata) == null);
return messages.isEmpty ? false : messages.last.id == message.id;
},
builder: (context, isLastMessage) {
return ChatAIMessageWidget(
user: message.author,
messageUserId: message.id,
message: message,
stream: stream is AnswerStream ? stream : null,
questionId: questionId,
chatId: view.id,
refSourceJsonString: refSourceJsonString,
isLastMessage: isLastMessage,
onSelectedMetadata: (metadata) {
context
.read<ChatSidePanelBloc>()
.add(ChatSidePanelEvent.selectedMetadata(metadata));
},
);
},
);
}
Widget _buildBottom(BuildContext context) {
Widget _buildChatMessage(
BuildContext context,
Message message,
Animation<double> animation,
Widget child,
) {
return ChatMessage(
message: message,
animation: animation,
padding: const EdgeInsets.symmetric(vertical: 12.0),
receivedMessageScaleAnimationAlignment: Alignment.center,
child: child,
);
}
Widget _buildScrollToBottom(
BuildContext context,
Animation<double> animation,
VoidCallback onPressed,
) {
return CustomScrollToBottom(
animation: animation,
onPressed: onPressed,
);
}
Widget _buildChatAnimatedList(
BuildContext context,
ScrollController scrollController,
ChatItem itemBuilder,
) {
final bloc = context.read<ChatBloc>();
if (bloc.chatController.messages.isEmpty) {
return ChatWelcomePage(
userProfile: userProfile,
onSelectedQuestion: (question) {
bloc.add(ChatEvent.sendMessage(message: question));
},
);
}
return ChatAnimatedListReversed(
scrollController: scrollController,
itemBuilder: itemBuilder,
onLoadPreviousMessages: () {
bloc.add(const ChatEvent.loadPreviousMessages());
},
);
}
Widget _buildInput(BuildContext context) {
return Padding(
padding: AIChatUILayout.safeAreaInsets(context),
child: BlocSelector<ChatBloc, ChatState, bool>(
selector: (state) => state.canSendMessage,
selector: (state) {
return state.promptResponseState == PromptResponseState.ready;
},
builder: (context, canSendMessage) {
return UniversalPlatform.isDesktop
? DesktopAIPromptInput(
chatId: view.id,
indicateFocus: true,
onSubmitted: (message) {
onSubmitted: (text, metadata) {
context.read<ChatBloc>().add(
ChatEvent.sendMessage(
message: message.text,
metadata: message.metadata,
message: text,
metadata: metadata,
),
);
},
@@ -358,11 +361,11 @@ class _ChatContentPage extends StatelessWidget {
)
: MobileAIPromptInput(
chatId: view.id,
onSubmitted: (message) {
onSubmitted: (text, metadata) {
context.read<ChatBloc>().add(
ChatEvent.sendMessage(
message: message.text,
metadata: message.metadata,
message: text,
metadata: metadata,
),
);
},
@@ -375,11 +378,4 @@ class _ChatContentPage extends StatelessWidget {
),
);
}
AFDefaultChatTheme _buildTheme(BuildContext context) {
return AFDefaultChatTheme(
primaryColor: Theme.of(context).colorScheme.primary,
secondaryColor: AFThemeExtension.of(context).tint1,
);
}
}
@@ -0,0 +1,370 @@
// ignore_for_file: implementation_imports
import 'dart:async';
import 'dart:math';
import 'package:diffutil_dart/diffutil.dart' as diffutil;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'package:provider/provider.dart';
import 'package:flutter_chat_ui/src/scroll_to_bottom.dart';
import 'package:flutter_chat_ui/src/utils/message_list_diff.dart';
class ChatAnimatedListReversed extends StatefulWidget {
const ChatAnimatedListReversed({
super.key,
required this.scrollController,
required this.itemBuilder,
this.insertAnimationDuration = const Duration(milliseconds: 250),
this.removeAnimationDuration = const Duration(milliseconds: 250),
this.scrollToEndAnimationDuration = const Duration(milliseconds: 250),
this.scrollToBottomAppearanceDelay = const Duration(milliseconds: 250),
this.bottomPadding = 8,
this.onLoadPreviousMessages,
});
final ScrollController scrollController;
final ChatItem itemBuilder;
final Duration insertAnimationDuration;
final Duration removeAnimationDuration;
final Duration scrollToEndAnimationDuration;
final Duration scrollToBottomAppearanceDelay;
final double? bottomPadding;
final VoidCallback? onLoadPreviousMessages;
@override
ChatAnimatedListReversedState createState() =>
ChatAnimatedListReversedState();
}
class ChatAnimatedListReversedState extends State<ChatAnimatedListReversed>
with SingleTickerProviderStateMixin {
final GlobalKey<SliverAnimatedListState> _listKey = GlobalKey();
late ChatController _chatController;
late List<Message> _oldList;
late StreamSubscription<ChatOperation> _operationsSubscription;
late final AnimationController _scrollToBottomController;
late final Animation<double> _scrollToBottomAnimation;
Timer? _scrollToBottomShowTimer;
bool _userHasScrolled = false;
bool _isScrollingToBottom = false;
String _lastInsertedMessageId = '';
@override
void initState() {
super.initState();
_chatController = Provider.of<ChatController>(context, listen: false);
// TODO: Add assert for messages having same id
_oldList = List.from(_chatController.messages);
_operationsSubscription = _chatController.operationsStream.listen((event) {
switch (event.type) {
case ChatOperationType.insert:
assert(
event.index != null,
'Index must be provided when inserting a message.',
);
assert(
event.message != null,
'Message must be provided when inserting a message.',
);
_onInserted(0, event.message!);
_oldList = List.from(_chatController.messages);
break;
case ChatOperationType.remove:
assert(
event.index != null,
'Index must be provided when removing a message.',
);
assert(
event.message != null,
'Message must be provided when removing a message.',
);
_onRemoved(event.index!, event.message!);
_oldList = List.from(_chatController.messages);
break;
case ChatOperationType.set:
final newList = _chatController.messages;
final updates = diffutil
.calculateDiff<Message>(
MessageListDiff(_oldList, newList),
)
.getUpdatesWithData();
for (var i = updates.length - 1; i >= 0; i--) {
_onDiffUpdate(updates.elementAt(i));
}
_oldList = List.from(newList);
break;
default:
break;
}
});
_scrollToBottomController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
_scrollToBottomAnimation = CurvedAnimation(
parent: _scrollToBottomController,
curve: Curves.easeInOut,
);
widget.scrollController.addListener(_handleLoadPreviousMessages);
WidgetsBinding.instance.addPostFrameCallback((_) {
_handleLoadPreviousMessages();
});
}
@override
void dispose() {
super.dispose();
_scrollToBottomShowTimer?.cancel();
_scrollToBottomController.dispose();
_operationsSubscription.cancel();
widget.scrollController.removeListener(_handleLoadPreviousMessages);
}
@override
Widget build(BuildContext context) {
final builders = context.watch<Builders>();
return NotificationListener<Notification>(
onNotification: (notification) {
if (notification is UserScrollNotification) {
// When user scrolls up, save it to `_userHasScrolled`
if (notification.direction == ScrollDirection.reverse) {
_userHasScrolled = true;
} else {
// When user overscolls to the bottom or stays idle at the bottom, set `_userHasScrolled` to false
if (notification.metrics.pixels ==
notification.metrics.minScrollExtent) {
_userHasScrolled = false;
}
}
}
if (notification is ScrollUpdateNotification) {
_handleToggleScrollToBottom();
}
// Allow other listeners to get the notification
return false;
},
child: Stack(
children: [
CustomScrollView(
reverse: true,
controller: widget.scrollController,
slivers: <Widget>[
SliverPadding(
padding: EdgeInsets.only(
top: widget.bottomPadding ?? 0,
),
),
SliverAnimatedList(
key: _listKey,
initialItemCount: _chatController.messages.length,
itemBuilder: (
BuildContext context,
int index,
Animation<double> animation,
) {
final message = _chatController.messages[
max(_chatController.messages.length - 1 - index, 0)];
return widget.itemBuilder(
context,
animation,
message,
);
},
),
],
),
builders.scrollToBottomBuilder?.call(
context,
_scrollToBottomAnimation,
_handleScrollToBottom,
) ??
ScrollToBottom(
animation: _scrollToBottomAnimation,
onPressed: _handleScrollToBottom,
),
],
),
);
}
void _subsequentScrollToEnd(Message data) async {
final user = Provider.of<User>(context, listen: false);
// We only want to scroll to the bottom if user has not scrolled up
// or if the message is sent by the current user.
if (data.id == _lastInsertedMessageId &&
widget.scrollController.offset >
widget.scrollController.position.minScrollExtent &&
(user.id == data.author.id || !_userHasScrolled)) {
if (widget.scrollToEndAnimationDuration == Duration.zero) {
widget.scrollController
.jumpTo(widget.scrollController.position.minScrollExtent);
} else {
await widget.scrollController.animateTo(
widget.scrollController.position.minScrollExtent,
duration: widget.scrollToEndAnimationDuration,
curve: Curves.linearToEaseOut,
);
}
if (!widget.scrollController.hasClients || !mounted) return;
// Because of the issue I have opened here https://github.com/flutter/flutter/issues/129768
// we need an additional jump to the end. Sometimes Flutter
// will not scroll to the very end. Sometimes it will not scroll to the
// very end even with this, so this is something that needs to be
// addressed by the Flutter team.
//
// Additionally here we have a check for the message id, because
// if new message arrives in the meantime it will trigger another
// scroll to the end animation, making this logic redundant.
if (data.id == _lastInsertedMessageId &&
widget.scrollController.offset >
widget.scrollController.position.minScrollExtent &&
(user.id == data.author.id || !_userHasScrolled)) {
widget.scrollController
.jumpTo(widget.scrollController.position.minScrollExtent);
}
}
}
void _scrollToEnd(Message data) {
WidgetsBinding.instance.addPostFrameCallback(
(_) {
if (!widget.scrollController.hasClients || !mounted) return;
_subsequentScrollToEnd(data);
},
);
}
void _handleScrollToBottom() {
_isScrollingToBottom = true;
_scrollToBottomController.reverse();
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!widget.scrollController.hasClients || !mounted) return;
if (widget.scrollToEndAnimationDuration == Duration.zero) {
widget.scrollController
.jumpTo(widget.scrollController.position.minScrollExtent);
} else {
await widget.scrollController.animateTo(
widget.scrollController.position.minScrollExtent,
duration: widget.scrollToEndAnimationDuration,
curve: Curves.linearToEaseOut,
);
}
if (!widget.scrollController.hasClients || !mounted) return;
if (widget.scrollController.offset <
widget.scrollController.position.minScrollExtent) {
widget.scrollController.jumpTo(
widget.scrollController.position.minScrollExtent,
);
}
_isScrollingToBottom = false;
});
}
void _handleToggleScrollToBottom() {
if (_isScrollingToBottom) {
return;
}
_scrollToBottomShowTimer?.cancel();
if (widget.scrollController.offset >
widget.scrollController.position.minScrollExtent) {
_scrollToBottomShowTimer =
Timer(widget.scrollToBottomAppearanceDelay, () {
if (mounted) {
_scrollToBottomController.forward();
}
});
} else {
if (_scrollToBottomController.status != AnimationStatus.completed) {
_scrollToBottomController.stop();
}
_scrollToBottomController.reverse();
}
}
void _onInserted(final int position, final Message data) {
// There is a scroll notification listener the controls the
// `_userHasScrolled` variable.
//
// If for some reason `_userHasScrolled` is true and the user is not at the
// bottom of the list, set `_userHasScrolled` to false so that the scroll
// animation is triggered.
if (_userHasScrolled &&
widget.scrollController.offset >=
widget.scrollController.position.minScrollExtent) {
_userHasScrolled = false;
}
_listKey.currentState!.insertItem(
position,
duration: widget.insertAnimationDuration,
);
// Used later to trigger scroll to end only for the last inserted message.
_lastInsertedMessageId = data.id;
if (position == _oldList.length) {
_scrollToEnd(data);
}
}
void _onRemoved(final int position, final Message data) {
final visualPosition = max(_oldList.length - position - 1, 0);
_listKey.currentState!.removeItem(
visualPosition,
(context, animation) => widget.itemBuilder(
context,
animation,
data,
isRemoved: true,
),
duration: widget.removeAnimationDuration,
);
}
void _onChanged(int position, Message oldData, Message newData) {
_onRemoved(position, oldData);
_listKey.currentState!.insertItem(
max(_oldList.length - position - 1, 0),
duration: widget.insertAnimationDuration,
);
}
void _onDiffUpdate(diffutil.DataDiffUpdate<Message> update) {
update.when<void>(
insert: (pos, data) => _onInserted(max(_oldList.length - pos, 0), data),
remove: (pos, data) => _onRemoved(pos, data),
change: (pos, oldData, newData) => _onChanged(pos, oldData, newData),
move: (_, __, ___) => throw UnimplementedError('unused'),
);
}
void _handleLoadPreviousMessages() {
if (widget.scrollController.offset >=
widget.scrollController.position.maxScrollExtent) {
widget.onLoadPreviousMessages?.call();
}
}
}
@@ -12,8 +12,6 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'package:universal_platform/universal_platform.dart';
import 'ai_prompt_buttons.dart';
@@ -25,7 +23,6 @@ class DesktopAIPromptInput extends StatefulWidget {
super.key,
required this.chatId,
required this.indicateFocus,
this.options = const InputOptions(),
required this.isStreaming,
required this.onStopStreaming,
required this.onSubmitted,
@@ -33,10 +30,9 @@ class DesktopAIPromptInput extends StatefulWidget {
final String chatId;
final bool indicateFocus;
final InputOptions options;
final bool isStreaming;
final void Function() onStopStreaming;
final void Function(types.PartialText) onSubmitted;
final void Function(String, Map<String, dynamic>) onSubmitted;
@override
State<DesktopAIPromptInput> createState() => _DesktopAIPromptInputState();
@@ -56,7 +52,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
void initState() {
super.initState();
_textController = InputTextFieldController()
_textController = TextEditingController()
..addListener(_handleTextControllerChange);
_inputFocusNode = FocusNode(
@@ -118,6 +114,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
borderRadius: DesktopAIPromptSizes.promptFrameRadius,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ConstrainedBox(
constraints: BoxConstraints(
@@ -209,11 +206,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
..addAll(mentionPageMetadata)
..addAll(fileMetadata);
final partialText = types.PartialText(
text: trimmedText,
metadata: metadata,
);
widget.onSubmitted(partialText);
widget.onSubmitted(trimmedText, metadata);
}
void _handleTextControllerChange() {
@@ -12,8 +12,6 @@ import 'package:extended_text_field/extended_text_field.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'ai_prompt_buttons.dart';
import 'chat_input_span.dart';
@@ -23,17 +21,15 @@ class MobileAIPromptInput extends StatefulWidget {
const MobileAIPromptInput({
super.key,
required this.chatId,
this.options = const InputOptions(),
required this.isStreaming,
required this.onStopStreaming,
required this.onSubmitted,
});
final String chatId;
final InputOptions options;
final bool isStreaming;
final void Function() onStopStreaming;
final void Function(types.PartialText) onSubmitted;
final void Function(String, Map<String, dynamic>) onSubmitted;
@override
State<MobileAIPromptInput> createState() => _MobileAIPromptInputState();
@@ -50,7 +46,7 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
void initState() {
super.initState();
_textController = InputTextFieldController()
_textController = TextEditingController()
..addListener(_handleTextControllerChange);
_inputFocusNode = FocusNode();
@@ -166,11 +162,7 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
..addAll(mentionPageMetadata)
..addAll(fileMetadata);
final partialText = types.PartialText(
text: trimmedText,
metadata: metadata,
);
widget.onSubmitted(partialText);
widget.onSubmitted(trimmedText, metadata);
}
void _handleTextControllerChange() {
@@ -1,8 +1,10 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
/// An animated generating indicator for an AI response
class ChatAILoading extends StatelessWidget {
@@ -16,48 +18,56 @@ class ChatAILoading extends StatelessWidget {
@override
Widget build(BuildContext context) {
final slice = Duration(milliseconds: duration.inMilliseconds ~/ 5);
return SizedBox(
height: 20,
child: SeparatedRow(
separatorBuilder: () => const HSpace(4),
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 4.0),
child: FlowyText(
LocaleKeys.chat_generatingResponse.tr(),
color: Theme.of(context).hintColor,
return Padding(
padding: const EdgeInsets.only(top: 8.0),
child: SizedBox(
height: 20,
child: SeparatedRow(
separatorBuilder: () => const HSpace(4),
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 4.0),
child: BlocBuilder<ChatAIMessageBloc, ChatAIMessageState>(
builder: (context, state) {
return FlowyText(
state.progress?.step ??
LocaleKeys.chat_generatingResponse.tr(),
color: Theme.of(context).hintColor,
);
},
),
),
),
buildDot(const Color(0xFF9327FF))
.animate(onPlay: (controller) => controller.repeat())
.slideY(duration: slice, begin: 0, end: -1)
.then()
.slideY(begin: -1, end: 1)
.then()
.slideY(begin: 1, end: 0)
.then()
.slideY(duration: slice * 2, begin: 0, end: 0),
buildDot(const Color(0xFFFB006D))
.animate(onPlay: (controller) => controller.repeat())
.slideY(duration: slice, begin: 0, end: 0)
.then()
.slideY(begin: 0, end: -1)
.then()
.slideY(begin: -1, end: 1)
.then()
.slideY(begin: 1, end: 0)
.then()
.slideY(begin: 0, end: 0),
buildDot(const Color(0xFFFFCE00))
.animate(onPlay: (controller) => controller.repeat())
.slideY(duration: slice * 2, begin: 0, end: 0)
.then()
.slideY(duration: slice, begin: 0, end: -1)
.then()
.slideY(begin: -1, end: 1)
.then()
.slideY(begin: 1, end: 0),
],
buildDot(const Color(0xFF9327FF))
.animate(onPlay: (controller) => controller.repeat())
.slideY(duration: slice, begin: 0, end: -1)
.then()
.slideY(begin: -1, end: 1)
.then()
.slideY(begin: 1, end: 0)
.then()
.slideY(duration: slice * 2, begin: 0, end: 0),
buildDot(const Color(0xFFFB006D))
.animate(onPlay: (controller) => controller.repeat())
.slideY(duration: slice, begin: 0, end: 0)
.then()
.slideY(begin: 0, end: -1)
.then()
.slideY(begin: -1, end: 1)
.then()
.slideY(begin: 1, end: 0)
.then()
.slideY(begin: 0, end: 0),
buildDot(const Color(0xFFFFCE00))
.animate(onPlay: (controller) => controller.repeat())
.slideY(duration: slice * 2, begin: 0, end: 0)
.then()
.slideY(duration: slice, begin: 0, end: -1)
.then()
.slideY(begin: -1, end: 1)
.then()
.slideY(begin: 1, end: 0),
],
),
),
);
}
@@ -1,6 +1,5 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
@@ -8,6 +7,8 @@ import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
import 'layout_define.dart';
class RelatedQuestionList extends StatelessWidget {
const RelatedQuestionList({
super.key,
@@ -16,7 +17,7 @@ class RelatedQuestionList extends StatelessWidget {
});
final Function(String) onQuestionSelected;
final List<RelatedQuestionPB> relatedQuestions;
final List<String> relatedQuestions;
@override
Widget build(BuildContext context) {
@@ -24,10 +25,8 @@ class RelatedQuestionList extends StatelessWidget {
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: relatedQuestions.length + 1,
padding: const EdgeInsets.only(bottom: 8.0) +
(UniversalPlatform.isMobile
? const EdgeInsets.symmetric(horizontal: 16)
: EdgeInsets.zero),
padding:
const EdgeInsets.only(bottom: 8.0) + AIChatUILayout.messageMargin,
separatorBuilder: (context, index) => const VSpace(4.0),
itemBuilder: (context, index) {
if (index == 0) {
@@ -40,9 +39,12 @@ class RelatedQuestionList extends StatelessWidget {
),
);
} else {
return RelatedQuestionItem(
question: relatedQuestions[index - 1],
onQuestionSelected: onQuestionSelected,
return Align(
alignment: AlignmentDirectional.centerStart,
child: RelatedQuestionItem(
question: relatedQuestions[index - 1],
onQuestionSelected: onQuestionSelected,
),
);
}
},
@@ -57,17 +59,21 @@ class RelatedQuestionItem extends StatelessWidget {
super.key,
});
final RelatedQuestionPB question;
final String question;
final Function(String) onQuestionSelected;
@override
Widget build(BuildContext context) {
return FlowyButton(
text: FlowyText(
question.content,
lineHeight: 1.4,
overflow: TextOverflow.ellipsis,
mainAxisAlignment: MainAxisAlignment.start,
text: Flexible(
child: FlowyText(
question,
lineHeight: 1.4,
overflow: TextOverflow.ellipsis,
),
),
expandText: false,
margin: UniversalPlatform.isMobile
? const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0)
: const EdgeInsets.all(8.0),
@@ -76,7 +82,7 @@ class RelatedQuestionItem extends StatelessWidget {
color: Theme.of(context).colorScheme.primary,
size: const Size.square(16.0),
),
onTap: () => onQuestionSelected(question.content),
onTap: () => onQuestionSelected(question),
);
}
}
@@ -1,85 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
/// Default chat theme which extends [ChatTheme].
@immutable
class AFDefaultChatTheme extends ChatTheme {
const AFDefaultChatTheme({
required super.primaryColor,
required super.secondaryColor,
}) : super(
backgroundColor: Colors.transparent,
// TODO: think how to offset the default 12 pixels set by chat package
bubbleMargin: const EdgeInsets.symmetric(vertical: 4.0),
messageMaxWidth: double.infinity,
// unused
dateDividerMargin: EdgeInsets.zero,
dateDividerTextStyle: const TextStyle(),
attachmentButtonIcon: null,
attachmentButtonMargin: null,
deliveredIcon: null,
documentIcon: null,
emptyChatPlaceholderTextStyle: const TextStyle(),
errorColor: error,
errorIcon: null,
inputBackgroundColor: neutral0,
inputSurfaceTintColor: neutral0,
inputElevation: 0,
inputBorderRadius: BorderRadius.zero,
inputContainerDecoration: null,
inputMargin: EdgeInsets.zero,
inputPadding: EdgeInsets.zero,
inputTextColor: neutral7,
inputTextCursorColor: null,
inputTextDecoration: const InputDecoration(),
inputTextStyle: const TextStyle(),
messageBorderRadius: 0,
messageInsetsHorizontal: 0,
messageInsetsVertical: 0,
receivedEmojiMessageTextStyle: const TextStyle(),
receivedMessageBodyBoldTextStyle: null,
receivedMessageBodyCodeTextStyle: null,
receivedMessageBodyLinkTextStyle: null,
receivedMessageBodyTextStyle: const TextStyle(),
receivedMessageDocumentIconColor: primary,
receivedMessageCaptionTextStyle: const TextStyle(),
receivedMessageLinkDescriptionTextStyle: const TextStyle(),
receivedMessageLinkTitleTextStyle: const TextStyle(),
seenIcon: null,
sendButtonIcon: null,
sendButtonMargin: null,
sendingIcon: null,
sentEmojiMessageTextStyle: const TextStyle(),
sentMessageBodyBoldTextStyle: null,
sentMessageBodyCodeTextStyle: null,
sentMessageBodyLinkTextStyle: null,
sentMessageBodyTextStyle: const TextStyle(),
sentMessageCaptionTextStyle: const TextStyle(),
sentMessageDocumentIconColor: neutral7,
sentMessageLinkDescriptionTextStyle: const TextStyle(),
sentMessageLinkTitleTextStyle: const TextStyle(),
statusIconPadding: EdgeInsets.zero,
systemMessageTheme: const SystemMessageTheme(
margin: EdgeInsets.zero,
textStyle: TextStyle(),
),
typingIndicatorTheme: const TypingIndicatorTheme(
animatedCirclesColor: neutral1,
animatedCircleSize: 0.0,
bubbleBorder: BorderRadius.zero,
bubbleColor: neutral7,
countAvatarColor: primary,
countTextColor: secondary,
multipleUserTextStyle: TextStyle(),
),
unreadHeaderTheme: const UnreadHeaderTheme(
color: secondary,
textStyle: TextStyle(),
),
userAvatarImageBackgroundColor: Colors.transparent,
userAvatarNameColors: colors,
userAvatarTextStyle: const TextStyle(),
userNameTextStyle: const TextStyle(),
highlightMessageColor: null,
);
}
@@ -1,52 +0,0 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:universal_platform/universal_platform.dart';
class ChatInvalidUserMessage extends StatelessWidget {
const ChatInvalidUserMessage({
required this.message,
super.key,
});
final Message message;
@override
Widget build(BuildContext context) {
final errorMessage = message.metadata?[sendMessageErrorKey] ?? "";
return Center(
child: Container(
margin: const EdgeInsets.only(top: 16.0, bottom: 24.0),
constraints: UniversalPlatform.isDesktop
? const BoxConstraints(maxWidth: 480)
: const BoxConstraints(),
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Theme.of(context).isLightMode
? const Color(0x80FFE7EE)
: const Color(0x80591734),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const FlowySvg(
FlowySvgs.warning_filled_s,
blendMode: null,
),
const HSpace(8.0),
Flexible(
child: FlowyText(
errorMessage,
lineHeight: 1.4,
maxLines: null,
),
),
],
),
),
);
}
}
@@ -180,7 +180,7 @@ class WelcomeSampleQuestion extends StatelessWidget {
}
}
class _AutoScrollingSampleQuestions extends StatelessWidget {
class _AutoScrollingSampleQuestions extends StatefulWidget {
const _AutoScrollingSampleQuestions({
super.key,
required this.questions,
@@ -194,17 +194,29 @@ class _AutoScrollingSampleQuestions extends StatelessWidget {
final double offset;
final bool reverse;
@override
State<_AutoScrollingSampleQuestions> createState() =>
_AutoScrollingSampleQuestionsState();
}
class _AutoScrollingSampleQuestionsState
extends State<_AutoScrollingSampleQuestions> {
late final scrollController = ScrollController(
initialScrollOffset: widget.offset,
);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 36,
child: InfiniteScrollView(
scrollController: scrollController,
centerKey: UniqueKey(),
itemCount: questions.length,
itemCount: widget.questions.length,
itemBuilder: (context, index) {
return WelcomeSampleQuestion(
question: questions[index],
onSelected: onSelected,
question: widget.questions[index],
onSelected: widget.onSelected,
);
},
separatorBuilder: (context, index) => const HSpace(8),
@@ -2,8 +2,6 @@ import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
class AIChatUILayout {
static double get messageWidthRatio => 0.94; // Chat adds extra 0.06
static EdgeInsets safeAreaInsets(BuildContext context) {
final query = MediaQuery.of(context);
return UniversalPlatform.isMobile
@@ -15,6 +13,10 @@ class AIChatUILayout {
)
: const EdgeInsets.only(bottom: 16);
}
static EdgeInsets get messageMargin => UniversalPlatform.isMobile
? const EdgeInsets.symmetric(horizontal: 16)
: EdgeInsets.zero;
}
class DesktopAIPromptSizes {
@@ -4,7 +4,6 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_quick_action_button.dart';
import 'package:appflowy/plugins/ai_chat/presentation/chat_avatar.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/startup/startup.dart';
@@ -14,16 +13,16 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'package:universal_platform/universal_platform.dart';
import '../chat_avatar.dart';
import '../layout_define.dart';
/// Wraps an AI response message with the avatar and actions. On desktop,
/// the actions will be displayed below the response if the response is the
/// last message in the chat. For other AI responses, the actions will be shown
/// on hover. On mobile, the actions will be displayed in a bottom sheet on
/// long press.
/// last message in the chat. For the others, the actions will be shown on hover
/// On mobile, the actions will be displayed in a bottom sheet on long press.
class ChatAIMessageBubble extends StatelessWidget {
const ChatAIMessageBubble({
super.key,
@@ -293,7 +292,11 @@ class AIResponseActionBar extends StatelessWidget {
padding: const EdgeInsets.all(2.0),
decoration: BoxDecoration(
borderRadius: DesktopAIConvoSizes.actionBarIconRadius,
border: Border.all(color: Theme.of(context).dividerColor),
border: Border.all(
color: isLightMode
? const Color(0x1F1F2329)
: Theme.of(context).dividerColor,
),
color: Theme.of(context).cardColor,
boxShadow: [
BoxShadow(
@@ -341,7 +344,6 @@ class CopyButton extends StatelessWidget {
child: FlowyIconButton(
width: DesktopAIConvoSizes.actionBarIconSize,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
fillColor: Theme.of(context).cardColor,
radius: DesktopAIConvoSizes.actionBarIconRadius,
icon: FlowySvg(
FlowySvgs.copy_s,
@@ -17,7 +17,7 @@ class AIMessageMetadata extends StatefulWidget {
});
final List<ChatMessageRefSource> sources;
final void Function(ChatMessageRefSource metadata) onSelectedMetadata;
final void Function(ChatMessageRefSource metadata)? onSelectedMetadata;
@override
State<AIMessageMetadata> createState() => _AIMessageMetadataState();
@@ -92,7 +92,7 @@ class _AIMessageMetadataState extends State<AIMessageMetadata> {
if (m.source != appflowySource) {
return;
}
widget.onSelectedMetadata(m);
widget.onSelectedMetadata?.call(m);
},
),
);
@@ -1,23 +1,20 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
import 'package:appflowy/plugins/ai_chat/presentation/chat_loading.dart';
import 'package:appflowy/plugins/ai_chat/presentation/message/ai_markdown_text.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/gestures.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:universal_platform/universal_platform.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import '../chat_loading.dart';
import '../layout_define.dart';
import 'ai_markdown_text.dart';
import 'ai_message_bubble.dart';
import 'ai_metadata.dart';
import 'error_text_message.dart';
/// [ChatAIMessageWidget] includes both the text of the AI response as well as
/// the avatar, decorations and hover effects that are also rendered. This is
@@ -34,7 +31,7 @@ class ChatAIMessageWidget extends StatelessWidget {
required this.questionId,
required this.chatId,
required this.refSourceJsonString,
required this.onSelectedMetadata,
this.onSelectedMetadata,
this.isLastMessage = false,
});
@@ -46,7 +43,7 @@ class ChatAIMessageWidget extends StatelessWidget {
final Int64? questionId;
final String chatId;
final String? refSourceJsonString;
final void Function(ChatMessageRefSource metadata) onSelectedMetadata;
final void Function(ChatMessageRefSource metadata)? onSelectedMetadata;
final bool isLastMessage;
@override
@@ -61,23 +58,20 @@ class ChatAIMessageWidget extends StatelessWidget {
child: BlocBuilder<ChatAIMessageBloc, ChatAIMessageState>(
builder: (context, state) {
return Padding(
padding: UniversalPlatform.isMobile
? const EdgeInsets.symmetric(horizontal: 16)
: EdgeInsets.zero,
padding: AIChatUILayout.messageMargin,
child: state.messageState.when(
loading: () {
return ChatAIMessageBubble(
message: message,
showActions: false,
child: const Padding(
padding: EdgeInsets.only(top: 8.0),
child: ChatAILoading(),
),
);
},
loading: () => ChatAIMessageBubble(
message: message,
showActions: false,
child: const ChatAILoading(),
),
ready: () {
return state.text.isEmpty
? const SizedBox.shrink()
? ChatAIMessageBubble(
message: message,
showActions: false,
child: const ChatAILoading(),
)
: ChatAIMessageBubble(
message: message,
isLastMessage: isLastMessage,
@@ -91,12 +85,15 @@ class ChatAIMessageWidget extends StatelessWidget {
sources: state.sources,
onSelectedMetadata: onSelectedMetadata,
),
if (state.sources.isNotEmpty && !isLastMessage)
const VSpace(16.0),
],
),
);
},
onError: (err) {
return StreamingError(
onError: (error) {
return ChatErrorMessageWidget(
errorMessage: LocaleKeys.chat_aiServerUnavailable.tr(),
onRetry: () {
context
.read<ChatAIMessageBloc>()
@@ -105,7 +102,10 @@ class ChatAIMessageWidget extends StatelessWidget {
);
},
onAIResponseLimit: () {
return const AIResponseLimitReachedError();
return ChatErrorMessageWidget(
errorMessage:
LocaleKeys.sideBar_askOwnerToUpgradeToAIMax.tr(),
);
},
),
);
@@ -114,129 +114,3 @@ class ChatAIMessageWidget extends StatelessWidget {
);
}
}
class StreamingError extends StatefulWidget {
const StreamingError({
required this.onRetry,
super.key,
});
final VoidCallback onRetry;
@override
State<StreamingError> createState() => _StreamingErrorState();
}
class _StreamingErrorState extends State<StreamingError> {
late final TapGestureRecognizer recognizer;
@override
void initState() {
super.initState();
recognizer = TapGestureRecognizer()..onTap = widget.onRetry;
}
@override
void dispose() {
recognizer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
margin: const EdgeInsets.only(top: 16.0, bottom: 24.0),
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Theme.of(context).isLightMode
? const Color(0x80FFE7EE)
: const Color(0x80591734),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
),
constraints: _errorConstraints(),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const FlowySvg(
FlowySvgs.warning_filled_s,
blendMode: null,
),
const HSpace(8.0),
Flexible(
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: LocaleKeys.chat_aiServerUnavailable.tr(),
style: Theme.of(context).textTheme.bodyMedium,
),
TextSpan(
text: " ",
style: Theme.of(context).textTheme.bodyMedium,
),
TextSpan(
text: LocaleKeys.chat_retry.tr(),
recognizer: recognizer,
mouseCursor: SystemMouseCursors.click,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
decoration: TextDecoration.underline,
),
),
],
),
),
),
],
),
),
);
}
}
class AIResponseLimitReachedError extends StatelessWidget {
const AIResponseLimitReachedError({
super.key,
});
@override
Widget build(BuildContext context) {
return Center(
child: Container(
margin: const EdgeInsets.only(top: 16.0, bottom: 24.0),
constraints: _errorConstraints(),
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Theme.of(context).isLightMode
? const Color(0x80FFE7EE)
: const Color(0x80591734),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const FlowySvg(
FlowySvgs.warning_filled_s,
blendMode: null,
),
const HSpace(8.0),
Flexible(
child: FlowyText(
LocaleKeys.sideBar_askOwnerToUpgradeToAIMax.tr(),
lineHeight: 1.4,
maxLines: null,
),
),
],
),
),
);
}
}
BoxConstraints _errorConstraints() {
return UniversalPlatform.isDesktop
? const BoxConstraints(maxWidth: 480)
: const BoxConstraints();
}
@@ -0,0 +1,107 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
class ChatErrorMessageWidget extends StatefulWidget {
const ChatErrorMessageWidget({
super.key,
required this.errorMessage,
this.onRetry,
});
final String errorMessage;
final VoidCallback? onRetry;
@override
State<ChatErrorMessageWidget> createState() => _ChatErrorMessageWidgetState();
}
class _ChatErrorMessageWidgetState extends State<ChatErrorMessageWidget> {
late final TapGestureRecognizer recognizer;
@override
void initState() {
super.initState();
recognizer = TapGestureRecognizer()..onTap = widget.onRetry;
}
@override
void dispose() {
recognizer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
margin: const EdgeInsets.only(top: 16.0, bottom: 24.0) +
(UniversalPlatform.isMobile
? const EdgeInsets.symmetric(horizontal: 16)
: EdgeInsets.zero),
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Theme.of(context).isLightMode
? const Color(0x80FFE7EE)
: const Color(0x80591734),
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
),
constraints: UniversalPlatform.isDesktop
? const BoxConstraints(maxWidth: 480)
: null,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const FlowySvg(
FlowySvgs.warning_filled_s,
blendMode: null,
),
const HSpace(8.0),
Flexible(
child: _buildText(),
),
],
),
),
);
}
Widget _buildText() {
final errorMessage = widget.errorMessage;
return widget.onRetry != null
? RichText(
text: TextSpan(
children: [
TextSpan(
text: errorMessage,
style: Theme.of(context).textTheme.bodyMedium,
),
TextSpan(
text: ' ',
style: Theme.of(context).textTheme.bodyMedium,
),
TextSpan(
text: LocaleKeys.chat_retry.tr(),
recognizer: recognizer,
mouseCursor: SystemMouseCursors.click,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
decoration: TextDecoration.underline,
),
),
],
),
)
: FlowyText(
errorMessage,
lineHeight: 1.4,
maxLines: null,
);
}
}
@@ -1,67 +1,54 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_member_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_user_message_bubble_bloc.dart';
import 'package:appflowy/plugins/ai_chat/presentation/chat_avatar.dart';
import 'package:appflowy/plugins/ai_chat/presentation/layout_define.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:universal_platform/universal_platform.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import '../chat_avatar.dart';
import '../layout_define.dart';
class ChatUserMessageBubble extends StatelessWidget {
const ChatUserMessageBubble({
super.key,
required this.message,
required this.child,
this.isCurrentUser = true,
required this.isCurrentUser,
this.files = const [],
});
final Message message;
final Widget child;
final bool isCurrentUser;
final List<ChatFile> files;
@override
Widget build(BuildContext context) {
if (context.read<ChatMemberBloc>().state.members[message.author.id] ==
null) {
context
.read<ChatMemberBloc>()
.add(ChatMemberEvent.getMemberInfo(message.author.id));
}
context
.read<ChatMemberBloc>()
.add(ChatMemberEvent.getMemberInfo(message.author.id));
return BlocProvider(
create: (context) => ChatUserMessageBubbleBloc(
message: message,
),
child: BlocBuilder<ChatUserMessageBubbleBloc, ChatUserMessageBubbleState>(
builder: (context, state) {
return Padding(
padding: UniversalPlatform.isMobile
? const EdgeInsets.symmetric(horizontal: 16)
: EdgeInsets.zero,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (state.files.isNotEmpty) ...[
Padding(
padding: const EdgeInsets.only(right: 32),
child: _MessageFileList(files: state.files),
),
const VSpace(6),
],
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: getChildren(context),
),
],
return Padding(
padding: AIChatUILayout.messageMargin,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (files.isNotEmpty) ...[
Padding(
padding: const EdgeInsets.only(right: 32),
child: _MessageFileList(files: files),
),
);
},
const VSpace(6),
],
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: getChildren(context),
),
],
),
);
}
@@ -1,46 +1,70 @@
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_service.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_user_message_bloc.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'user_message_bubble.dart';
class ChatUserMessageWidget extends StatelessWidget {
const ChatUserMessageWidget({
super.key,
required this.user,
required this.message,
required this.isCurrentUser,
});
final User user;
final dynamic message;
final TextMessage message;
final bool isCurrentUser;
@override
Widget build(BuildContext context) {
final stream = message.metadata?["$QuestionStream"];
final messageText = stream is QuestionStream ? stream.text : message.text;
return BlocProvider(
create: (context) => ChatUserMessageBloc(message: message)
..add(const ChatUserMessageEvent.initial()),
child: BlocBuilder<ChatUserMessageBloc, ChatUserMessageState>(
builder: (context, state) {
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
child: TextMessageText(
text: state.text,
),
create: (context) => ChatUserMessageBloc(
text: messageText,
questionStream: stream,
),
child: ChatUserMessageBubble(
message: message,
isCurrentUser: isCurrentUser,
files: _getFiles(),
child: BlocBuilder<ChatUserMessageBloc, ChatUserMessageState>(
builder: (context, state) {
return Opacity(
opacity: state.messageState.isFinish ? 1.0 : 0.8,
child: TextMessageText(
text: state.text,
),
if (!state.messageState.isFinish) ...[
const HSpace(6),
const CircularProgressIndicator.adaptive(),
],
],
);
},
);
},
),
),
);
}
List<ChatFile> _getFiles() {
if (message.metadata == null) {
return const [];
}
final refSourceMetadata =
message.metadata?[messageRefSourceJsonStringKey] as String?;
if (refSourceMetadata != null) {
return chatFilesFromMetadataString(refSourceMetadata);
}
final chatFileList =
message.metadata![messageChatFileListKey] as List<ChatFile>?;
return chatFileList ?? [];
}
}
/// Widget to reuse the markdown capabilities, e.g., for previews.
@@ -0,0 +1,88 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flutter/material.dart';
const BorderRadius _borderRadius = BorderRadius.all(Radius.circular(16));
class CustomScrollToBottom extends StatelessWidget {
const CustomScrollToBottom({
super.key,
required this.animation,
required this.onPressed,
});
final Animation<double> animation;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final isLightMode = Theme.of(context).isLightMode;
return Positioned(
bottom: 24,
left: 0,
right: 0,
child: Center(
child: ScaleTransition(
scale: animation,
child: DecoratedBox(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
border: Border.all(
color: Theme.of(context).dividerColor,
strokeAlign: BorderSide.strokeAlignOutside,
),
borderRadius: _borderRadius,
boxShadow: [
BoxShadow(
offset: const Offset(0, 8),
blurRadius: 16,
spreadRadius: 8,
color: isLightMode
? const Color(0x0F1F2329)
: Theme.of(context).shadowColor.withOpacity(0.06),
),
BoxShadow(
offset: const Offset(0, 4),
blurRadius: 8,
color: isLightMode
? const Color(0x141F2329)
: Theme.of(context).shadowColor.withOpacity(0.08),
),
BoxShadow(
offset: const Offset(0, 2),
blurRadius: 4,
color: isLightMode
? const Color(0x1F1F2329)
: Theme.of(context).shadowColor.withOpacity(0.12),
),
],
),
child: Material(
borderRadius: _borderRadius,
color: Colors.transparent,
borderOnForeground: false,
child: InkWell(
overlayColor: WidgetStateProperty.all(
AFThemeExtension.of(context).lightGreyHover,
),
borderRadius: _borderRadius,
onTap: onPressed,
child: const SizedBox.square(
dimension: 32,
child: Center(
child: FlowySvg(
FlowySvgs.ai_scroll_to_bottom_s,
size: Size.square(20),
),
),
),
),
),
),
),
),
);
}
}
@@ -44,11 +44,14 @@ class BlankPagePlugin extends Plugin {
class BlankPagePluginWidgetBuilder extends PluginWidgetBuilder
with NavigationItem {
@override
String? get viewName => LocaleKeys.blankPageTitle.tr();
@override
Widget get leftBarItem => FlowyText.medium(LocaleKeys.blankPageTitle.tr());
@override
Widget tabBarItem(String pluginId) => leftBarItem;
Widget tabBarItem(String pluginId, [bool shortForm = false]) => leftBarItem;
@override
Widget buildWidget({
@@ -293,7 +293,6 @@ class DatabaseTabBarController {
OnViewChildViewChanged? onViewChildViewChanged;
Future<void> dispose() async {
await viewListener.stop();
await controller.dispose();
await Future.wait([viewListener.stop(), controller.dispose()]);
}
}
@@ -179,9 +179,7 @@ class _DesktopBoardPageState extends State<DesktopBoardPage> {
_focusScope.dispose();
_boardBloc.close();
_boardActionsCubit.close();
_didCreateRow
..removeListener(_handleDidCreateRow)
..dispose();
_didCreateRow.dispose();
super.dispose();
}
@@ -189,7 +187,7 @@ class _DesktopBoardPageState extends State<DesktopBoardPage> {
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<BoardBloc>.value(
BlocProvider.value(
value: _boardBloc,
),
BlocProvider.value(
@@ -5,6 +5,7 @@ import 'package:appflowy/plugins/shared/share/share_button.dart';
import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view_info/view_info_bloc.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart';
import 'package:appflowy/workspace/presentation/widgets/favorite_button.dart';
@@ -88,11 +89,11 @@ class _DatabaseTabBarViewState extends State<DatabaseTabBarView> {
return MultiBlocProvider(
providers: [
BlocProvider<DatabaseTabBarBloc>(
create: (context) => DatabaseTabBarBloc(view: widget.view)
create: (_) => DatabaseTabBarBloc(view: widget.view)
..add(const DatabaseTabBarEvent.initial()),
),
BlocProvider<ViewBloc>(
create: (context) =>
create: (_) =>
ViewBloc(view: widget.view)..add(const ViewEvent.initial()),
),
],
@@ -100,7 +101,7 @@ class _DatabaseTabBarViewState extends State<DatabaseTabBarView> {
listeners: [
BlocListener<DatabaseTabBarBloc, DatabaseTabBarState>(
listenWhen: (p, c) => p.selectedIndex != c.selectedIndex,
listener: (context, state) {
listener: (_, state) {
_initialRowId = null;
_pageController.jumpToPage(state.selectedIndex);
},
@@ -132,15 +133,22 @@ class _DatabaseTabBarViewState extends State<DatabaseTabBarView> {
builder: (context, state) =>
pageSettingBarExtensionFromState(state),
),
Expanded(
child: BlocBuilder<DatabaseTabBarBloc, DatabaseTabBarState>(
builder: (context, state) => PageView(
BlocBuilder<DatabaseTabBarBloc, DatabaseTabBarState>(
builder: (context, state) {
final content = PageView(
controller: _pageController,
pageSnapping: false,
physics: const NeverScrollableScrollPhysics(),
controller: _pageController,
children: pageContentFromState(state),
),
),
);
if (widget.shrinkWrap) {
final layout = state.tabBars[state.selectedIndex].layout;
return SizedBox(height: layout.pluginHeight, child: content);
}
return Expanded(child: content);
},
),
],
),
@@ -249,12 +257,16 @@ class DatabasePluginWidgetBuilder extends PluginWidgetBuilder {
///
final String? initialRowId;
@override
String? get viewName => notifier.view.nameOrDefault;
@override
Widget get leftBarItem =>
ViewTitleBar(key: ValueKey(notifier.view.id), view: notifier.view);
@override
Widget tabBarItem(String pluginId) => ViewTabBarItem(view: notifier.view);
Widget tabBarItem(String pluginId, [bool shortForm = false]) =>
ViewTabBarItem(view: notifier.view, shortForm: shortForm);
@override
Widget buildWidget({
@@ -1,24 +1,23 @@
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet_media_upload.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/common.dart';
import 'package:appflowy/workspace/presentation/widgets/image_viewer/image_provider.dart';
import 'package:appflowy/workspace/presentation/widgets/image_viewer/interactive_image_viewer.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet_media_upload.dart';
import 'package:appflowy/plugins/database/application/cell/bloc/media_cell_bloc.dart';
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/media.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/media_cell_editor.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/mobile_media_cell_editor.dart';
import 'package:appflowy/plugins/database/widgets/media_file_type_ext.dart';
import 'package:appflowy/plugins/database/widgets/row/cells/cell_container.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/common.dart';
import 'package:appflowy/shared/af_image.dart';
import 'package:appflowy/workspace/presentation/widgets/image_viewer/image_provider.dart';
import 'package:appflowy/workspace/presentation/widgets/image_viewer/interactive_image_viewer.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/media_entities.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:universal_platform/universal_platform.dart';
@@ -159,7 +158,7 @@ class GridMediaCellSkin extends IEditableMediaCellSkin {
List<MediaFilePB> files,
) {
if (file.fileType != MediaFileTypePB.Image) {
afLaunchUrlString(file.url);
afLaunchUrlString(file.url, context: context);
return;
}
@@ -31,6 +31,7 @@ class DesktopRowDetailDateCellSkin extends IEditableDateCellSkin {
direction: PopoverDirection.bottomWithLeftAligned,
constraints: BoxConstraints.loose(const Size(260, 620)),
margin: EdgeInsets.zero,
asBarrier: true,
child: Container(
alignment: AlignmentDirectional.centerStart,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
@@ -151,9 +151,10 @@ class DekstopRowDetailMediaCellSkin extends IEditableMediaCellSkin {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const FlowySvg(
FlowySvg(
FlowySvgs.add_thin_s,
size: Size.square(12),
size: const Size.square(12),
color: Theme.of(context).hintColor,
),
const HSpace(6),
FlowyText.medium(
@@ -219,7 +220,9 @@ class _FilePreviewFeedback extends StatelessWidget {
}
}
class _AddFileButton extends StatelessWidget {
const _menuWidth = 350.0;
class _AddFileButton extends StatefulWidget {
const _AddFileButton({
this.mutex,
required this.controller,
@@ -232,16 +235,24 @@ class _AddFileButton extends StatelessWidget {
final PopoverDirection direction;
final Widget child;
@override
State<_AddFileButton> createState() => _AddFileButtonState();
}
class _AddFileButtonState extends State<_AddFileButton> {
Offset? position;
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
triggerActions: PopoverTriggerFlags.none,
controller: controller,
mutex: mutex,
controller: widget.controller,
mutex: widget.mutex,
offset: const Offset(0, 10),
direction: direction,
constraints: const BoxConstraints(maxWidth: 350),
direction: widget.direction,
constraints: const BoxConstraints(maxWidth: _menuWidth),
margin: EdgeInsets.zero,
asBarrier: true,
onClose: () =>
context.read<EditorDropManagerState>().remove(_dropFileKey),
popupBuilder: (_) {
@@ -273,7 +284,7 @@ class _AddFileButton extends StatelessWidget {
),
);
controller.close();
widget.controller.close();
},
),
onInsertNetworkFile: (url) {
@@ -306,14 +317,25 @@ class _AddFileButton extends StatelessWidget {
),
);
controller.close();
widget.controller.close();
},
);
},
child: GestureDetector(
onTap: controller.show,
behavior: HitTestBehavior.translucent,
child: FlowyHover(resetHoverOnRebuild: false, child: child),
child: MouseRegion(
onEnter: (event) => position = event.position,
onExit: (_) => position = null,
onHover: (event) => position = event.position,
child: GestureDetector(
onTap: () {
if (position != null) {
widget.controller.showAt(
position! - const Offset(_menuWidth / 2, 0),
);
}
},
behavior: HitTestBehavior.translucent,
child: FlowyHover(resetHoverOnRebuild: false, child: widget.child),
),
),
);
}
@@ -437,6 +459,7 @@ class _FilePreviewRenderState extends State<_FilePreviewRender> {
offset: const Offset(0, 5),
triggerActions: PopoverTriggerFlags.none,
onClose: () => setState(() => isSelected = false),
asBarrier: true,
popupBuilder: (popoverContext) => MultiBlocProvider(
providers: [
BlocProvider.value(value: context.read<RowDetailBloc>()),
@@ -456,6 +479,11 @@ class _FilePreviewRenderState extends State<_FilePreviewRender> {
onTap: widget.foregroundText != null
? null
: () {
if (file.uploadType == FileUploadTypePB.LocalFile) {
afLaunchUrlString(file.url);
return;
}
if (file.fileType != MediaFileTypePB.Image) {
afLaunchUrlString(widget.file.url);
return;
@@ -24,6 +24,7 @@ class DesktopRowDetailRelationCellSkin extends IEditableRelationCellSkin {
direction: PopoverDirection.bottomWithLeftAligned,
constraints: const BoxConstraints(maxWidth: 400, maxHeight: 400),
margin: EdgeInsets.zero,
asBarrier: true,
onClose: () => cellContainerNotifier.isFocus = false,
popupBuilder: (context) {
return BlocProvider.value(
@@ -25,6 +25,7 @@ class DesktopRowDetailSelectOptionCellSkin
controller: popoverController,
constraints: const BoxConstraints.tightFor(width: 300),
margin: EdgeInsets.zero,
asBarrier: true,
triggerActions: PopoverTriggerFlags.none,
direction: PopoverDirection.bottomWithLeftAligned,
onClose: () => cellContainerNotifier.isFocus = false,
@@ -199,22 +199,30 @@ class FieldActionCell extends StatelessWidget {
(action == FieldAction.duplicate || action == FieldAction.delete)) {
enable = false;
}
return FlowyButton(
return FlowyIconTextButton(
resetHoverOnRebuild: false,
disable: !enable,
text: FlowyText(
action.title(fieldInfo),
lineHeight: 1.0,
color: enable ? null : Theme.of(context).disabledColor,
),
onHover: (_) => popoverMutex?.close(),
onTap: () => action.run(context, viewId, fieldInfo),
leftIcon: action.leading(
fieldInfo,
enable ? null : Theme.of(context).disabledColor,
// show the error color when delete is hovered
textBuilder: (onHover) => FlowyText(
action.title(fieldInfo),
lineHeight: 1.0,
color: enable
? action == FieldAction.delete && onHover
? Theme.of(context).colorScheme.error
: null
: Theme.of(context).disabledColor,
),
rightIcon: action.trailing(context, fieldInfo),
leftIconBuilder: (onHover) => action.leading(
fieldInfo,
enable
? action == FieldAction.delete && onHover
? Theme.of(context).colorScheme.error
: null
: Theme.of(context).disabledColor,
),
rightIconBuilder: (_) => action.trailing(context, fieldInfo),
);
}
}
@@ -4,6 +4,7 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -97,6 +98,9 @@ class DatabaseDocumentPluginWidgetBuilder extends PluginWidgetBuilder
final String documentId;
final Selection? initialSelection;
@override
String? get viewName => view.nameOrDefault;
@override
EdgeInsets get contentPadding => EdgeInsets.zero;
@@ -123,7 +127,8 @@ class DatabaseDocumentPluginWidgetBuilder extends PluginWidgetBuilder
ViewTitleBarWithRow(view: view, databaseId: databaseId, rowId: rowId);
@override
Widget tabBarItem(String pluginId) => const SizedBox.shrink();
Widget tabBarItem(String pluginId, [bool shortForm = false]) =>
const SizedBox.shrink();
@override
Widget? get rightBarItem => const SizedBox.shrink();
@@ -246,10 +246,16 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
(event) async {
final time = event.$1;
final transaction = event.$2;
final options = event.$3;
if (time != TransactionTime.before) {
return;
}
if (options.inMemoryUpdate) {
Log.info('skip transaction for in-memory update');
return;
}
if (enableDocumentInternalLog) {
Log.debug(
'[TransactionAdapter] 1. transaction before apply: ${transaction.hashCode}',
@@ -204,6 +204,19 @@ extension NodeToBlock on Node {
}
String _dataAdapter(String type, Attributes attributes) {
return jsonEncode(attributes);
try {
return jsonEncode(
attributes,
toEncodable: (value) {
if (value is Map) {
return jsonEncode(value);
}
return value;
},
);
} catch (e) {
Log.error('encode attributes error: $e');
return '{}';
}
}
}
@@ -4,7 +4,7 @@ import 'dart:convert';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/application/document_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
@@ -176,7 +176,7 @@ extension on InsertOperation {
Path currentPath = path;
final List<BlockActionWrapper> actions = [];
for (final node in nodes) {
if (node.type == SmartEditBlockKeys.type) {
if (node.type == AskAIBlockKeys.type) {
continue;
}
@@ -10,6 +10,7 @@ import 'package:appflowy/plugins/shared/share/share_button.dart';
import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view_info/view_info_bloc.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart';
import 'package:appflowy/workspace/presentation/widgets/favorite_button.dart';
@@ -145,11 +146,15 @@ class DocumentPluginWidgetBuilder extends PluginWidgetBuilder
);
}
@override
String? get viewName => notifier.view.nameOrDefault;
@override
Widget get leftBarItem => ViewTitleBar(key: ValueKey(view.id), view: view);
@override
Widget tabBarItem(String pluginId) => ViewTabBarItem(view: notifier.view);
Widget tabBarItem(String pluginId, [bool shortForm = false]) =>
ViewTabBarItem(view: notifier.view, shortForm: shortForm);
@override
Widget? get rightBarItem {
@@ -163,7 +163,11 @@ class _DocumentPageState extends State<DocumentPage>
return Provider(
create: (_) {
final context = SharedEditorContext();
if (widget.view.name.isEmpty) {
final children = editorState.document.root.children;
final firstDelta = children.firstOrNull?.delta;
final isEmptyDocument =
children.length == 1 && (firstDelta == null || firstDelta.isEmpty);
if (widget.view.name.isEmpty && isEmptyDocument) {
context.requestCoverTitleFocus = true;
}
return context;
@@ -125,8 +125,9 @@ void _customBlockOptionActions(
final actions = _buildOptionActions(context, entry.key);
if (UniversalPlatform.isDesktop) {
builder.showActions =
(node) => node.parent?.type != TableCellBlockKeys.type;
builder.showActions = (node) =>
node.parent?.type != TableCellBlockKeys.type &&
node.parent?.type != SimpleTableCellBlockKeys.type;
builder.configuration = builder.configuration.copyWith(
blockSelectionAreaMargin: (_) => const EdgeInsets.symmetric(
vertical: 1,
@@ -142,6 +143,8 @@ void _customBlockOptionActions(
level > 0) {
final offset = [14.0, 11.0, 8.0, 6.0, 4.0, 2.0];
top += offset[level - 1];
} else if (type == SimpleTableBlockKeys.type) {
top += 8.0;
} else {
top += 2.0;
}
@@ -157,6 +160,7 @@ void _customBlockOptionActions(
? () => customSlashCommand(
slashMenuItems,
shouldInsertSlash: false,
deleteKeywordsByDefault: true,
style: styleCustomizer.selectionMenuStyleBuilder(),
).handler.call(editorState)
: () {},
@@ -252,11 +256,11 @@ Map<String, BlockComponentBuilder> _buildBlockComponentBuilderMap(
configuration,
styleCustomizer,
),
AutoCompletionBlockKeys.type: _buildAutoCompletionBlockComponentBuilder(
AIWriterBlockKeys.type: _buildAIWriterBlockComponentBuilder(
context,
configuration,
),
SmartEditBlockKeys.type: _buildSmartEditBlockComponentBuilder(
AskAIBlockKeys.type: _buildAskAIBlockComponentBuilder(
context,
configuration,
),
@@ -286,6 +290,18 @@ Map<String, BlockComponentBuilder> _buildBlockComponentBuilderMap(
errorBlockComponentBuilderKey: ErrorBlockComponentBuilder(
configuration: configuration,
),
SimpleTableBlockKeys.type: _buildSimpleTableBlockComponentBuilder(
context,
configuration,
),
SimpleTableRowBlockKeys.type: _buildSimpleTableRowBlockComponentBuilder(
context,
configuration,
),
SimpleTableCellBlockKeys.type: _buildSimpleTableCellBlockComponentBuilder(
context,
configuration,
),
};
final builders = {
@@ -296,6 +312,37 @@ Map<String, BlockComponentBuilder> _buildBlockComponentBuilderMap(
return builders;
}
SimpleTableBlockComponentBuilder _buildSimpleTableBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
final copiedConfiguration = configuration.copyWith(
padding: (node) {
final padding = configuration.padding(node);
if (UniversalPlatform.isDesktop) {
return padding;
} else {
return padding.copyWith(right: padding.left);
}
},
);
return SimpleTableBlockComponentBuilder(configuration: copiedConfiguration);
}
SimpleTableRowBlockComponentBuilder _buildSimpleTableRowBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
return SimpleTableRowBlockComponentBuilder(configuration: configuration);
}
SimpleTableCellBlockComponentBuilder _buildSimpleTableCellBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
return SimpleTableCellBlockComponentBuilder(configuration: configuration);
}
ParagraphBlockComponentBuilder _buildParagraphBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
@@ -303,7 +350,17 @@ ParagraphBlockComponentBuilder _buildParagraphBlockComponentBuilder(
String Function(Node)? placeholderText,
) {
return ParagraphBlockComponentBuilder(
configuration: configuration.copyWith(placeholderText: placeholderText),
configuration: configuration.copyWith(
placeholderText: placeholderText,
textStyle: (node) {
if (node.isInHeaderColumn || node.isInHeaderRow) {
return configuration.textStyle(node).copyWith(
fontWeight: FontWeight.bold,
);
}
return configuration.textStyle(node);
},
),
showPlaceholder: showParagraphPlaceholder,
);
}
@@ -315,6 +372,14 @@ TodoListBlockComponentBuilder _buildTodoListBlockComponentBuilder(
return TodoListBlockComponentBuilder(
configuration: configuration.copyWith(
placeholderText: (_) => LocaleKeys.blockPlaceholders_todoList.tr(),
textStyle: (node) {
if (node.isInHeaderColumn || node.isInHeaderRow) {
return configuration.textStyle(node).copyWith(
fontWeight: FontWeight.bold,
);
}
return configuration.textStyle(node);
},
),
iconBuilder: (_, node, onCheck) => TodoListIcon(
node: node,
@@ -335,6 +400,14 @@ BulletedListBlockComponentBuilder _buildBulletedListBlockComponentBuilder(
return BulletedListBlockComponentBuilder(
configuration: configuration.copyWith(
placeholderText: (_) => LocaleKeys.blockPlaceholders_bulletList.tr(),
textStyle: (node) {
if (node.isInHeaderColumn || node.isInHeaderRow) {
return configuration.textStyle(node).copyWith(
fontWeight: FontWeight.bold,
);
}
return configuration.textStyle(node);
},
),
iconBuilder: (_, node) => BulletedListIcon(node: node),
);
@@ -347,6 +420,14 @@ NumberedListBlockComponentBuilder _buildNumberedListBlockComponentBuilder(
return NumberedListBlockComponentBuilder(
configuration: configuration.copyWith(
placeholderText: (_) => LocaleKeys.blockPlaceholders_numberList.tr(),
textStyle: (node) {
if (node.isInHeaderColumn || node.isInHeaderRow) {
return configuration.textStyle(node).copyWith(
fontWeight: FontWeight.bold,
);
}
return configuration.textStyle(node);
},
),
iconBuilder: (_, node, textDirection) => NumberedListIcon(
node: node,
@@ -362,6 +443,14 @@ QuoteBlockComponentBuilder _buildQuoteBlockComponentBuilder(
return QuoteBlockComponentBuilder(
configuration: configuration.copyWith(
placeholderText: (_) => LocaleKeys.blockPlaceholders_quote.tr(),
textStyle: (node) {
if (node.isInHeaderColumn || node.isInHeaderRow) {
return configuration.textStyle(node).copyWith(
fontWeight: FontWeight.bold,
);
}
return configuration.textStyle(node);
},
),
);
}
@@ -553,18 +642,18 @@ CodeBlockComponentBuilder _buildCodeBlockComponentBuilder(
);
}
AutoCompletionBlockComponentBuilder _buildAutoCompletionBlockComponentBuilder(
AIWriterBlockComponentBuilder _buildAIWriterBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
return AutoCompletionBlockComponentBuilder();
return AIWriterBlockComponentBuilder();
}
SmartEditBlockComponentBuilder _buildSmartEditBlockComponentBuilder(
AskAIBlockComponentBuilder _buildAskAIBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
return SmartEditBlockComponentBuilder();
return AskAIBlockComponentBuilder();
}
ToggleListBlockComponentBuilder _buildToggleListBlockComponentBuilder(
@@ -79,7 +79,7 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
];
final List<ToolbarItem> toolbarItems = [
smartEditItem..isActive = onlyShowInTextType,
askAIItem..isActive = onlyShowInTextType,
paragraphItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
headingsToolbarItem
..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
@@ -92,9 +92,9 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
inlineMathEquationItem,
linkItem,
alignToolbarItem,
buildTextColorItem(),
buildHighlightColorItem(),
customizeFontToolbarItem,
buildTextColorItem()..isActive = showInAnyTextType,
buildHighlightColorItem()..isActive = showInAnyTextType,
customizeFontToolbarItem..isActive = showInAnyTextType,
];
late List<SelectionMenuItem> slashMenuItems;
@@ -164,6 +164,9 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
ToggleListBlockKeys.type,
CalloutBlockKeys.type,
TableBlockKeys.type,
SimpleTableBlockKeys.type,
SimpleTableCellBlockKeys.type,
SimpleTableRowBlockKeys.type,
]);
AppFlowyRichTextKeys.supportSliced.add(AppFlowyRichTextKeys.fontFamily);
@@ -404,8 +407,9 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
}
List<SelectionMenuItem> _customSlashMenuItems() {
final isLocalMode = context.read<DocumentBloc>().isLocalMode;
return [
aiWriterSlashMenuItem,
if (!isLocalMode) aiWriterSlashMenuItem,
textSlashMenuItem,
heading1SlashMenuItem,
heading2SlashMenuItem,
@@ -34,7 +34,7 @@ class BlockActionList extends StatelessWidget {
editorState: editorState,
showSlashMenu: showSlashMenu,
),
const HSpace(4.0),
const HSpace(2.0),
BlockOptionButton(
blockComponentContext: blockComponentContext,
blockComponentState: blockComponentState,
@@ -42,7 +42,7 @@ class BlockActionList extends StatelessWidget {
editorState: editorState,
blockComponentBuilder: blockComponentBuilder,
),
const HSpace(4.0),
const HSpace(8.0),
],
);
}
@@ -86,6 +86,11 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
Log.error('Block type $type is not valid');
if (node.type == TableBlockKeys.type) {
copiedNode = _fixTableBlock(node);
copiedNode = _convertTableToSimpleTable(copiedNode);
}
} else {
if (node.type == TableBlockKeys.type) {
copiedNode = _convertTableToSimpleTable(node);
}
}
}
@@ -138,6 +143,44 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
);
}
Node _convertTableToSimpleTable(Node node) {
if (node.type != TableBlockKeys.type) {
return node;
}
// the table node should contains colsLen and rowsLen
final colsLen = node.attributes[TableBlockKeys.colsLen];
final rowsLen = node.attributes[TableBlockKeys.rowsLen];
if (colsLen == null || rowsLen == null) {
return node;
}
final rows = <List<Node>>[];
final children = node.children;
for (var i = 0; i < rowsLen; i++) {
final row = <Node>[];
for (var j = 0; j < colsLen; j++) {
final cell = children
.where(
(n) =>
n.attributes[TableCellBlockKeys.rowPosition] == i &&
n.attributes[TableCellBlockKeys.colPosition] == j,
)
.firstOrNull;
row.add(
simpleTableCellBlockNode(
children: [cell?.children.first.copyWith() ?? paragraphNode()],
),
);
}
rows.add(row);
}
return simpleTableBlockNode(
children: rows.map((e) => simpleTableRowBlockNode(children: e)).toList(),
);
}
Future<void> _copyLinkToBlock(Node node) async {
final context = editorState.document.root.context;
final viewId = context?.read<DocumentBloc>().documentId;
@@ -447,7 +490,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
// We move views after applying transaction to avoid performing side-effects on the views
final viewIdsToMove = _extractChildViewIds(selectedNodes);
for (final viewId in viewIdsToMove) {
// Attempt to put back from trash if neccessary
// Attempt to put back from trash if necessary
await TrashService.putback(viewId);
await ViewBackendService.moveViewV2(
@@ -2,7 +2,6 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_button.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@@ -111,9 +110,7 @@ class _OptionButtonState extends State<OptionButton> {
widget.blockComponentContext.node,
beforeSelection,
);
Log.info(
'update block selection, beforeSelection: $beforeSelection, afterSelection: $selection',
);
widget.editorState.updateSelectionWithReason(
selection,
customSelectionType: SelectionType.block,
@@ -1,3 +1,5 @@
import 'dart:math';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
@@ -46,7 +48,7 @@ class VisualDragArea extends StatelessWidget {
Widget child = Container(
height: 2,
width: width,
width: max(width, 0.0),
color: Theme.of(context).colorScheme.primary,
);
@@ -1,7 +1,6 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
@@ -62,41 +61,35 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
if (snapshot.hasData && page != null) {
return _build(context, page);
}
if (snapshot.connectionState == ConnectionState.done) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
// just delete the page if it is not found
_deletePage();
});
return const Center(
child: FlowyText('Cannot load the page'),
);
// Delete the page if not found
WidgetsBinding.instance.addPostFrameCallback((_) => _deletePage());
return const Center(child: FlowyText('Cannot load the page'));
}
return const Center(
child: CircularProgressIndicator(),
);
return const Center(child: CircularProgressIndicator());
},
future: future,
);
}
Widget _build(BuildContext context, ViewPB viewPB) {
Widget _build(BuildContext context, ViewPB view) {
return MouseRegion(
onEnter: (_) => widget.editorState.service.scrollService?.disable(),
onExit: (_) => widget.editorState.service.scrollService?.enable(),
child: SizedBox(
height: viewPB.pluginType == PluginType.calendar ? 700 : 400,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildMenu(context, viewPB),
Expanded(child: _buildPage(context, viewPB)),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildMenu(context, view),
_buildPage(context, view),
],
),
);
}
Widget _buildPage(BuildContext context, ViewPB viewPB) {
Widget _buildPage(BuildContext context, ViewPB view) {
return Focus(
focusNode: focusNode,
onFocusChange: (value) {
@@ -104,11 +97,11 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
widget.editorState.service.selectionService.clearSelection();
}
},
child: widget.builder(viewPB),
child: widget.builder(view),
);
}
Widget _buildMenu(BuildContext context, ViewPB viewPB) {
Widget _buildMenu(BuildContext context, ViewPB view) {
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
@@ -116,7 +109,7 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
// information
FlowyIconButton(
tooltipText: LocaleKeys.tooltip_referencePage.tr(
namedArgs: {'name': viewPB.layout.name},
namedArgs: {'name': view.layout.name},
),
width: 24,
height: 24,
@@ -147,8 +140,8 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
case _ActionType.viewDatabase:
getIt<TabsBloc>().add(
TabsEvent.openPlugin(
plugin: viewPB.plugin(),
view: viewPB,
plugin: view.plugin(),
view: view,
),
);
break;
@@ -172,10 +165,7 @@ class _BuiltInPageWidgetState extends State<BuiltInPageWidget> {
}
}
enum _ActionType {
viewDatabase,
delete,
}
enum _ActionType { viewDatabase, delete }
class _ActionWrapper extends ActionCell {
_ActionWrapper(this.inner);
@@ -0,0 +1,137 @@
import 'dart:convert';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/foundation.dart';
import 'package:synchronized/synchronized.dart';
class MarkdownTextRobot {
MarkdownTextRobot({
required this.editorState,
this.enableDebug = true,
});
final EditorState editorState;
final bool enableDebug;
final Lock lock = Lock();
// The selection before the text robot is ready.
Selection? _startSelection;
// The markdown text to be inserted.
String _markdownText = '';
// Only for debug. Enable by [enableDebug].
@visibleForTesting
final List<String> debugMarkdownTexts = [];
// The nodes inserted in the previous refresh.
Iterable<Node> _previousInsertedNodes = [];
/// Start the text robot.
///
/// Must call this function before using the text robot.
void start() {
_startSelection = editorState.selection;
if (enableDebug) {
Log.info(
'MarkdownTextRobot prepare, current selection: $_startSelection',
);
}
}
/// Append the markdown text to the text robot.
///
/// The text will be inserted into document but not persisted until the text
/// robot is stopped.
Future<void> appendMarkdownText(String text) async {
_markdownText += text;
await lock.synchronized(() async {
await _refresh();
});
if (enableDebug) {
debugMarkdownTexts.add(text);
Log.info('debug markdown texts: ${jsonEncode(debugMarkdownTexts)}');
}
}
/// Stop the text robot.
///
/// The text will be persisted into document.
Future<void> stop() async {
// persist the markdown text
await lock.synchronized(() async {
await _refresh(inMemoryUpdate: false);
});
_markdownText = '';
if (enableDebug) {
Log.info(
'debug markdown texts: ${jsonEncode(debugMarkdownTexts)}',
);
debugMarkdownTexts.clear();
}
}
/// Refreshes the editor state with the current markdown text by:
///
/// 1. Converting markdown to document nodes
/// 2. Replacing previously inserted nodes with new nodes
/// 3. Updating selection position
Future<void> _refresh({bool inMemoryUpdate = true}) async {
final start = _startSelection?.start;
if (start == null) {
return;
}
final transaction = editorState.transaction;
// Convert markdown and deep copy nodes
final nodes = customMarkdownToDocument(_markdownText).root.children.map(
(node) => node.copyWith(),
); // deep copy the nodes to avoid the linked entities being changed.
// Insert new nodes at selection start
transaction.insertNodes(start.path, nodes);
// Remove previously inserted nodes if they exist
if (_previousInsertedNodes.isNotEmpty) {
// fallback to the calculated position if the selection is null.
final end = editorState.selection?.end ??
Position(
path: start.path.nextNPath(_previousInsertedNodes.length - 1),
);
final deletedNodes = editorState.getNodesInSelection(
Selection(start: start, end: end),
);
transaction.deleteNodes(deletedNodes);
}
// Update selection to end of inserted content if it contains text
final lastDelta = nodes.lastOrNull?.delta;
if (lastDelta != null) {
transaction.afterSelection = Selection.collapsed(
Position(
path: start.path.nextNPath(nodes.length - 1),
offset: lastDelta.length,
),
);
}
await editorState.apply(
transaction,
options: ApplyOptions(
inMemoryUpdate: inMemoryUpdate,
recordUndo: false,
),
);
_previousInsertedNodes = nodes;
}
}
@@ -117,6 +117,22 @@ Future<bool> inlinePageReferenceCommandHandler(
initialResults: initialResults,
style: style,
startCharAmount: previousChar != null ? 2 : 1,
cancelBySpaceHandler: () {
if (character == _plusChar) {
final currentSelection = editorState.selection;
if (currentSelection == null) {
return false;
}
// check if the space is after the character
if (currentSelection.isCollapsed &&
currentSelection.start.offset ==
selection.start.offset + character.length) {
_cancelInlinePageReferenceMenu(editorState);
return true;
}
}
return false;
},
);
selectionMenuService?.show();
@@ -124,3 +140,17 @@ Future<bool> inlinePageReferenceCommandHandler(
return true;
}
void _cancelInlinePageReferenceMenu(EditorState editorState) {
selectionMenuService?.dismiss();
selectionMenuService = null;
// re-focus the selection
final selection = editorState.selection;
if (selection != null) {
editorState.updateSelectionWithReason(
selection,
reason: SelectionUpdateReason.uiEvent,
);
}
}
@@ -1,59 +1,154 @@
import 'dart:async';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:synchronized/synchronized.dart';
enum TextRobotInputType {
character,
word,
sentence,
}
class TextRobot {
const TextRobot({
TextRobot({
required this.editorState,
});
final EditorState editorState;
final Lock lock = Lock();
/// This function is used to insert text in a synchronized way
///
/// It is suitable for inserting text in a loop.
Future<void> autoInsertTextSync(
String text, {
TextRobotInputType inputType = TextRobotInputType.word,
Duration delay = const Duration(milliseconds: 10),
String separator = '\n',
}) async {
await lock.synchronized(() async {
await autoInsertText(
text,
inputType: inputType,
delay: delay,
separator: separator,
);
});
}
/// This function is used to insert text in an asynchronous way
///
/// It is suitable for inserting a long paragraph or a long sentence.
Future<void> autoInsertText(
String text, {
TextRobotInputType inputType = TextRobotInputType.word,
Duration delay = const Duration(milliseconds: 10),
String separator = '\n',
}) async {
if (text == '\n') {
return editorState.insertNewLine();
if (text == separator) {
await insertNewParagraph(delay);
return;
}
final lines = text.split('\n');
final lines = _splitText(text, separator);
for (final line in lines) {
if (line.isEmpty) {
await editorState.insertNewLine();
await insertNewParagraph(delay);
continue;
}
switch (inputType) {
case TextRobotInputType.character:
final iterator = line.runes.iterator;
while (iterator.moveNext()) {
await editorState.insertTextAtCurrentSelection(
iterator.currentAsString,
);
await Future.delayed(delay);
}
await insertCharacter(line, delay);
break;
case TextRobotInputType.word:
final words = line.split(' ');
if (words.length == 1 ||
(words.length == 2 &&
(words.first.isEmpty || words.last.isEmpty))) {
await editorState.insertTextAtCurrentSelection(
line,
);
} else {
for (final word in words.map((e) => '$e ')) {
await editorState.insertTextAtCurrentSelection(
word,
);
}
}
await Future.delayed(delay);
await insertWord(line, delay);
break;
case TextRobotInputType.sentence:
await insertSentence(line, delay);
break;
}
}
}
Future<void> insertCharacter(String line, Duration delay) async {
final iterator = line.runes.iterator;
while (iterator.moveNext()) {
await insertText(iterator.currentAsString, delay);
}
}
Future<void> insertWord(String line, Duration delay) async {
final words = line.split(' ');
if (words.length == 1 ||
(words.length == 2 && (words.first.isEmpty || words.last.isEmpty))) {
await insertText(line, delay);
} else {
for (final word in words.map((e) => '$e ')) {
await insertText(word, delay);
}
}
await Future.delayed(delay);
}
Future<void> insertSentence(String line, Duration delay) async {
await insertText(line, delay);
}
Future<void> insertNewParagraph(Duration delay) async {
final selection = editorState.selection;
if (selection == null || !selection.isCollapsed) {
return;
}
final next = selection.end.path.next;
final transaction = editorState.transaction;
transaction.insertNode(
next,
paragraphNode(),
);
transaction.afterSelection = Selection.collapsed(
Position(path: next),
);
await editorState.apply(transaction);
debugPrint(
'AI insertNewParagraph: path: ${editorState.selection!.end.path}, index: ${editorState.selection!.endIndex}',
);
await Future.delayed(const Duration(milliseconds: 10));
}
Future<void> insertText(String text, Duration delay) async {
final selection = editorState.selection;
debugPrint(
'AI insertText: get selection, path: ${selection!.end.path}, index: ${selection.endIndex}',
);
if (!selection.isCollapsed) {
return;
}
final node = editorState.getNodeAtPath(selection.end.path);
if (node == null) {
return;
}
final transaction = editorState.transaction;
transaction.insertText(node, selection.endIndex, text);
await editorState.apply(transaction);
await Future.delayed(delay);
debugPrint(
'AI insertText: path: ${selection.end.path}, index: ${selection.endIndex}, text: "$text"',
);
}
}
List<String> _splitText(String text, String separator) {
final parts = text.split(RegExp(separator));
final result = <String>[];
for (int i = 0; i < parts.length; i++) {
result.add(parts[i]);
// Only add empty string if it's not the last part and the next part is not empty
if (i < parts.length - 1 && parts[i + 1].isNotEmpty) {
result.add('');
}
}
return result;
}
@@ -1,11 +1,11 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/sub_page/sub_page_block_component.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table.dart';
/// Copy.
///
@@ -59,11 +59,12 @@ KeyEventResult handleCopyCommand(
// plain text.
text = editorState.getTextInSelection(selection).join('\n');
final selectedNodes = editorState.getSelectedNodes(selection: selection);
final nodes = _handleSubPageNodes(selectedNodes, isCut);
final document = Document.blank()..insert([0], nodes);
final document = _buildCopiedDocument(
editorState,
selection,
isCut: isCut,
);
// in app json
inAppJson = jsonEncode(document.toJson());
// html
@@ -83,6 +84,34 @@ KeyEventResult handleCopyCommand(
return KeyEventResult.handled;
}
Document _buildCopiedDocument(
EditorState editorState,
Selection selection, {
bool isCut = false,
}) {
// filter the table nodes
final filteredNodes = <Node>[];
final selectedNodes = editorState.getSelectedNodes(selection: selection);
final nodes = _handleSubPageNodes(selectedNodes, isCut);
for (final node in nodes) {
if (node.type == SimpleTableCellBlockKeys.type) {
// if the node is a table cell, we will fetch its children instead.
filteredNodes.addAll(node.children);
} else if (node.type == SimpleTableRowBlockKeys.type) {
// if the node is a table row, we will fetch its children instead.
filteredNodes.addAll(node.children.expand((e) => e.children));
} else {
filteredNodes.add(node);
}
}
final document = Document.blank()
..insert(
[0],
filteredNodes.map((e) => e.copyWith()),
);
return document;
}
List<Node> _handleSubPageNodes(List<Node> nodes, [bool isCut = false]) {
final handled = <Node>[];
for (final node in nodes) {
@@ -1,8 +1,7 @@
import 'package:flutter/material.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/clipboard_state.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
/// cut.
@@ -42,6 +41,11 @@ CommandShortcutEventHandler _cutCommandHandler = (editorState) {
if (node == null) {
return KeyEventResult.handled;
}
// prevent to cut the node that is selecting the table.
if (node.parentTableNode != null) {
return KeyEventResult.skipRemainingHandlers;
}
final transaction = editorState.transaction;
transaction.deleteNode(node);
final nextNode = node.next;
@@ -10,7 +10,6 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_p
import 'package:appflowy/plugins/document/presentation/editor_plugins/file/file_util.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:cross_file/cross_file.dart';
import 'package:desktop_drop/desktop_drop.dart';
@@ -19,7 +18,6 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:open_filex/open_filex.dart';
import 'package:provider/provider.dart';
import 'package:string_validator/string_validator.dart';
import 'package:universal_platform/universal_platform.dart';
@@ -323,23 +321,7 @@ class FileBlockComponentState extends State<FileBlockComponent>
FileUrlType urlType,
String url,
) async {
if ([FileUrlType.cloud, FileUrlType.network].contains(urlType) ||
UniversalPlatform.isDesktopOrWeb) {
await afLaunchUrlString(url);
} else {
final result = await OpenFilex.open(url);
if (result.type == ResultType.done) {
return;
}
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.document_plugins_file_failedToOpenMsg.tr(),
type: ToastificationType.error,
);
}
}
await afLaunchUrlString(url, context: context);
}
void _openMenu() {
@@ -347,6 +329,7 @@ class FileBlockComponentState extends State<FileBlockComponent>
controller.show();
dropManagerState?.add(FileBlockKeys.type);
} else {
editorState.updateSelectionWithReason(null, extraInfo: {});
showUploadFileMobileMenu();
}
}
@@ -1,8 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_service.dart';
@@ -22,6 +20,7 @@ import 'package:cross_file/cross_file.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/file_picker/file_picker_impl.dart';
import 'package:flowy_infra/uuid.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:universal_platform/universal_platform.dart';
@@ -102,7 +101,7 @@ Future<void> downloadMediaFile(
FileUploadTypePB.LocalFile,
].contains(file.uploadType)) {
/// When the file is a network file or a local file, we can directly open the file.
await afLaunchUrl(Uri.parse(file.url));
await afLaunchUrlString(file.url);
} else {
if (userProfile == null) {
return showToastNotification(
@@ -163,6 +163,10 @@ class _InnerCoverTitleState extends State<_InnerCoverTitle> {
bool _shouldFocus(ViewPB view, ViewState? state) {
final name = state?.view.name ?? view.name;
if (editorState.document.root.children.isNotEmpty) {
return false;
}
// if the view's name is empty, focus on the title
if (name.isEmpty) {
return true;
@@ -180,6 +184,15 @@ class _InnerCoverTitleState extends State<_InnerCoverTitle> {
void _onFocusChanged() {
if (titleFocusNode.hasFocus) {
// if the document is empty, disable the keyboard service
final children = editorState.document.root.children;
final firstDelta = children.firstOrNull?.delta;
final isEmptyDocument =
children.length == 1 && (firstDelta == null || firstDelta.isEmpty);
if (!isEmptyDocument) {
return;
}
if (editorState.selection != null) {
Log.info('cover title got focus, clear the editor selection');
editorState.selection = null;
@@ -1,3 +1,4 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/simple_table/simple_table_shortcuts/simple_table_command_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:flutter/services.dart';
@@ -15,6 +16,34 @@ class EditorKeyboardInterceptor extends AppFlowyKeyboardServiceInterceptor {
);
}
@override
Future<bool> interceptDelete(
TextEditingDeltaDeletion deletion,
EditorState editorState,
) async {
// check if the current selection is in a code block
final (isInTableCell, selection, tableCellNode, node) =
editorState.isCurrentSelectionInTableCell();
if (!isInTableCell ||
selection == null ||
tableCellNode == null ||
node == null) {
return false;
}
final onlyContainsOneChild = tableCellNode.children.length == 1;
final isParagraphNode =
tableCellNode.children.first.type == ParagraphBlockKeys.type;
if (onlyContainsOneChild &&
selection.isCollapsed &&
selection.end.offset == 0 &&
isParagraphNode) {
return true;
}
return false;
}
/// Check if the backtick pressed event should be handled
Future<bool> _checkIfBacktickPressed(
EditorState editorState,
@@ -16,11 +16,12 @@ import '../transaction_handler/mention_transaction_handler.dart';
const _pasteIdentifier = 'child_page_transaction';
class ChildPageTransactionHandler extends MentionTransactionHandler {
ChildPageTransactionHandler() : super(subType: MentionType.childPage.name);
ChildPageTransactionHandler();
@override
Future<void> onTransaction(
BuildContext context,
String viewId,
EditorState editorState,
List<MentionBlockData> added,
List<MentionBlockData> removed, {
@@ -0,0 +1,263 @@
import 'package:appflowy/shared/clipboard_state.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/reminder/reminder_bloc.dart';
import 'package:appflowy/user/application/reminder/reminder_extension.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:collection/collection.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import 'package:nanoid/nanoid.dart';
import 'package:provider/provider.dart';
import '../plugins.dart';
import '../transaction_handler/mention_transaction_handler.dart';
const _pasteIdentifier = 'date_transaction';
class DateTransactionHandler extends MentionTransactionHandler {
DateTransactionHandler();
@override
Future<void> onTransaction(
BuildContext context,
String viewId,
EditorState editorState,
List<MentionBlockData> added,
List<MentionBlockData> removed, {
bool isCut = false,
bool isUndoRedo = false,
bool isPaste = false,
bool isDraggingNode = false,
bool isTurnInto = false,
String? parentViewId,
}) async {
if (isDraggingNode || isTurnInto) {
return;
}
// Remove the mentions that were both added and removed in the same transaction.
// These were just moved around.
final moved = <MentionBlockData>[];
for (final mention in added) {
if (removed.any((r) => r.$2 == mention.$2)) {
moved.add(mention);
}
}
for (final mention in removed) {
if (!context.mounted || moved.any((m) => m.$2 == mention.$2)) {
return;
}
if (mention.$2[MentionBlockKeys.type] != MentionType.date.name) {
continue;
}
_handleDeletion(context, mention);
}
if (isPaste || isUndoRedo) {
if (context.mounted) {
context.read<ClipboardState>().startHandlingPaste(_pasteIdentifier);
}
for (final mention in added) {
if (!context.mounted || moved.any((m) => m.$2 == mention.$2)) {
return;
}
if (mention.$2[MentionBlockKeys.type] != MentionType.date.name) {
continue;
}
_handleAddition(
context,
viewId,
editorState,
mention,
isPaste,
isCut,
);
}
if (context.mounted) {
context.read<ClipboardState>().endHandlingPaste(_pasteIdentifier);
}
}
}
void _handleDeletion(
BuildContext context,
MentionBlockData data,
) {
final reminderId = data.$2[MentionBlockKeys.reminderId];
if (reminderId case String _ when reminderId.isNotEmpty) {
getIt<ReminderBloc>().add(ReminderEvent.remove(reminderId: reminderId));
}
}
void _handleAddition(
BuildContext context,
String viewId,
EditorState editorState,
MentionBlockData data,
bool isPaste,
bool isCut,
) {
final dateData = _MentionDateBlockData.fromData(data.$2);
if (dateData.dateString.isEmpty) {
Log.error("mention date block doesn't have a valid date string");
return;
}
if (isPaste && !isCut) {
_handlePasteFromCopy(
context,
viewId,
editorState,
data.$1,
data.$3,
dateData,
);
} else {
_handlePasteFromCut(viewId, data.$1, dateData);
}
}
void _handlePasteFromCut(
String viewId,
Node node,
_MentionDateBlockData data,
) {
final dateTime = DateTime.tryParse(data.dateString);
if (data.reminderId == null || dateTime == null) {
return;
}
getIt<ReminderBloc>().add(
ReminderEvent.addById(
reminderId: data.reminderId!,
objectId: viewId,
scheduledAt: Int64(
data.reminderOption
.getNotificationDateTime(dateTime)
.millisecondsSinceEpoch ~/
1000,
),
meta: {
ReminderMetaKeys.includeTime: data.includeTime.toString(),
ReminderMetaKeys.blockId: node.id,
},
),
);
}
void _handlePasteFromCopy(
BuildContext context,
String viewId,
EditorState editorState,
Node node,
int index,
_MentionDateBlockData data,
) async {
final dateTime = DateTime.tryParse(data.dateString);
if (node.delta == null) {
return;
}
if (data.reminderId == null || dateTime == null) {
return;
}
final reminderId = nanoid();
getIt<ReminderBloc>().add(
ReminderEvent.addById(
reminderId: reminderId,
objectId: viewId,
scheduledAt: Int64(
data.reminderOption
.getNotificationDateTime(dateTime)
.millisecondsSinceEpoch ~/
1000,
),
meta: {
ReminderMetaKeys.includeTime: data.includeTime.toString(),
ReminderMetaKeys.blockId: node.id,
},
),
);
final newMentionAttributes = {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: dateTime.toIso8601String(),
MentionBlockKeys.reminderId: reminderId,
MentionBlockKeys.includeTime: data.includeTime,
MentionBlockKeys.reminderOption: data.reminderOption.name,
},
};
// The index is the index of the delta, to get the index of the mention character
// in all the text, we need to calculate it based on the deltas before the current delta.
int mentionIndex = 0;
for (final (i, delta) in node.delta!.indexed) {
if (i >= index) {
break;
}
mentionIndex += delta.length;
}
// Required to prevent editing the same spot at the same time
await Future.delayed(const Duration(milliseconds: 100));
final transaction = editorState.transaction
..formatText(
node,
mentionIndex,
MentionBlockKeys.mentionChar.length,
newMentionAttributes,
);
await editorState.apply(
transaction,
options: const ApplyOptions(recordUndo: false),
);
}
}
/// A helper class to parse and store the mention date block data
class _MentionDateBlockData {
_MentionDateBlockData.fromData(Map<String, dynamic> data) {
dateString = switch (data[MentionBlockKeys.date]) {
final String string when DateTime.tryParse(string) != null => string,
_ => "",
};
includeTime = switch (data[MentionBlockKeys.includeTime]) {
final bool flag => flag,
_ => false,
};
reminderOption = switch (data[MentionBlockKeys.reminderOption]) {
final String name =>
ReminderOption.values.firstWhereOrNull((o) => o.name == name) ??
ReminderOption.none,
_ => ReminderOption.none,
};
reminderId = switch (data[MentionBlockKeys.reminderId]) {
final String id
when id.isNotEmpty && reminderOption != ReminderOption.none =>
id,
_ => null,
};
}
late final String dateString;
late final bool includeTime;
late final String? reminderId;
late final ReminderOption reminderOption;
}
@@ -8,7 +8,6 @@ import 'package:provider/provider.dart';
enum MentionType {
page,
reminder,
date,
childPage;
@@ -0,0 +1,238 @@
import 'dart:async';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/show_mobile_bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_quick_action_button.dart';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/file/file_util.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/common.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_util.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mobile_toolbar_v3/aa_menu/_toolbar_theme.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/permission/permission_checker.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/startup/tasks/app_widget.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
@visibleForTesting
const addAttachmentToolbarItemKey = ValueKey('add_attachment_toolbar_item');
final addAttachmentItem = AppFlowyMobileToolbarItem(
itemBuilder: (context, editorState, service, _, onAction) {
return AppFlowyMobileToolbarIconItem(
key: addAttachmentToolbarItemKey,
editorState: editorState,
icon: FlowySvgs.media_s,
onTap: () {
final documentId = context.read<DocumentBloc>().documentId;
final isLocalMode = context.read<DocumentBloc>().isLocalMode;
final selection = editorState.selection;
service.closeKeyboard();
// delay to wait the keyboard closed.
Future.delayed(const Duration(milliseconds: 100), () async {
unawaited(
editorState.updateSelectionWithReason(
selection,
extraInfo: {
selectionExtraInfoDisableMobileToolbarKey: true,
selectionExtraInfoDisableFloatingToolbar: true,
selectionExtraInfoDoNotAttachTextService: true,
},
),
);
keepEditorFocusNotifier.increase();
final didAddAttachment = await showAddAttachmentMenu(
AppGlobals.rootNavKey.currentContext!,
documentId: documentId,
isLocalMode: isLocalMode,
editorState: editorState,
selection: selection!,
);
if (didAddAttachment != true) {
unawaited(editorState.updateSelectionWithReason(selection));
}
});
},
);
},
);
Future<bool?> showAddAttachmentMenu(
BuildContext context, {
required String documentId,
required bool isLocalMode,
required EditorState editorState,
required Selection selection,
}) async =>
showMobileBottomSheet<bool>(
context,
showDragHandle: true,
barrierColor: Colors.transparent,
backgroundColor:
ToolbarColorExtension.of(context).toolbarMenuBackgroundColor,
elevation: 20,
isScrollControlled: false,
enableDraggableScrollable: true,
builder: (_) => _AddAttachmentMenu(
documentId: documentId,
isLocalMode: isLocalMode,
editorState: editorState,
selection: selection,
),
);
class _AddAttachmentMenu extends StatelessWidget {
const _AddAttachmentMenu({
required this.documentId,
required this.isLocalMode,
required this.editorState,
required this.selection,
});
final String documentId;
final bool isLocalMode;
final EditorState editorState;
final Selection selection;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
MobileQuickActionButton(
text: LocaleKeys.document_attachmentMenu_choosePhoto.tr(),
icon: FlowySvgs.image_rounded_s,
iconSize: const Size.square(20),
onTap: () async => selectPhoto(context),
),
const Divider(height: 8.5, thickness: 0.5),
MobileQuickActionButton(
text: LocaleKeys.document_attachmentMenu_takePicture.tr(),
icon: FlowySvgs.camera_s,
iconSize: const Size.square(20),
onTap: () async => selectCamera(context),
),
const Divider(height: 8.5, thickness: 0.5),
MobileQuickActionButton(
text: LocaleKeys.document_attachmentMenu_chooseFile.tr(),
icon: FlowySvgs.file_s,
iconSize: const Size.square(20),
onTap: () async => selectFile(context),
),
const Divider(height: 8.5, thickness: 0.5),
],
),
);
}
Future<void> _insertNode(Node node) async {
Future.delayed(
const Duration(milliseconds: 100),
() async {
// if current selected block is a empty paragraph block, replace it with the new block.
if (selection.isCollapsed) {
final path = selection.end.path;
final currentNode = editorState.getNodeAtPath(path);
final text = currentNode?.delta?.toPlainText();
if (currentNode != null &&
currentNode.type == ParagraphBlockKeys.type &&
text != null &&
text.isEmpty) {
final transaction = editorState.transaction;
transaction.insertNode(path.next, node);
transaction.deleteNode(currentNode);
transaction.afterSelection =
Selection.collapsed(Position(path: path));
transaction.selectionExtraInfo = {};
return editorState.apply(transaction);
}
}
await editorState.insertBlockAfterCurrentSelection(selection, node);
},
);
}
Future<void> insertImage(BuildContext context, XFile image) async {
CustomImageType type = CustomImageType.local;
String? path;
if (isLocalMode) {
path = await saveImageToLocalStorage(image.path);
} else {
(path, _) = await saveImageToCloudStorage(image.path, documentId);
type = CustomImageType.internal;
}
if (path != null) {
final node = customImageNode(url: path, type: type);
await _insertNode(node);
}
}
Future<void> selectPhoto(BuildContext context) async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image != null && context.mounted) {
await insertImage(context, image);
}
if (context.mounted) {
Navigator.pop(context);
}
}
Future<void> selectCamera(BuildContext context) async {
final cameraPermission =
await PermissionChecker.checkCameraPermission(context);
if (!cameraPermission) {
Log.error('Has no permission to access the camera');
return;
}
final image = await ImagePicker().pickImage(source: ImageSource.camera);
if (image != null && context.mounted) {
await insertImage(context, image);
}
if (context.mounted) {
Navigator.pop(context);
}
}
Future<void> selectFile(BuildContext context) async {
final result = await getIt<FilePickerService>().pickFiles();
final file = result?.files.first.xFile;
if (file != null) {
FileUrlType type = FileUrlType.local;
String? path;
if (isLocalMode) {
path = await saveFileToLocalStorage(file.path);
} else {
(path, _) = await saveFileToCloudStorage(file.path, documentId);
type = FileUrlType.cloud;
}
if (path != null) {
final node = fileNode(url: path, type: type, name: file.name);
await _insertNode(node);
}
}
if (context.mounted) {
Navigator.pop(context);
}
}
}
@@ -392,22 +392,3 @@ class AddBlockMenu extends StatelessWidget {
};
}
}
extension on EditorState {
Future<void> insertBlockAfterCurrentSelection(
Selection selection,
Node node,
) async {
final path = selection.end.path.next;
final transaction = this.transaction;
transaction.insertNode(
path,
node,
);
transaction.afterSelection = Selection.collapsed(
Position(path: path),
);
transaction.selectionExtraInfo = {};
await apply(transaction);
}
}
@@ -12,6 +12,7 @@ final _defaultToolbarItems = [
aaToolbarItem,
todoListToolbarItem,
bulletedListToolbarItem,
addAttachmentItem,
numberedListToolbarItem,
boldToolbarItem,
italicToolbarItem,
@@ -35,6 +36,7 @@ final _listToolbarItems = [
underlineToolbarItem,
strikethroughToolbarItem,
colorToolbarItem,
addAttachmentItem,
undoToolbarItem,
redoToolbarItem,
];
@@ -339,4 +339,21 @@ extension MobileToolbarEditorState on EditorState {
await apply(transaction);
}
Future<void> insertBlockAfterCurrentSelection(
Selection selection,
Node node,
) async {
final path = selection.end.path.next;
final transaction = this.transaction;
transaction.insertNode(
path,
node,
);
transaction.afterSelection = Selection.collapsed(
Position(path: path),
);
transaction.selectionExtraInfo = {};
await apply(transaction);
}
}
@@ -0,0 +1,68 @@
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
extension AskAINodeExtension on EditorState {
String getMarkdownInSelection(Selection? selection) {
selection ??= this.selection?.normalized;
if (selection == null || selection.isCollapsed) {
return '';
}
// if the selected nodes are not entirely selected, slice the nodes
final slicedNodes = <Node>[];
final nodes = getNodesInSelection(selection);
for (final node in nodes) {
final delta = node.delta;
if (delta == null) {
continue;
}
final slicedDelta = delta.slice(
node == nodes.first ? selection.startIndex : 0,
node == nodes.last ? selection.endIndex : delta.length,
);
final copiedNode = node.copyWith(
attributes: {
...node.attributes,
blockComponentDelta: slicedDelta.toJson(),
},
);
slicedNodes.add(copiedNode);
}
final markdown = customDocumentToMarkdown(
Document.blank()..insert([0], slicedNodes),
);
return markdown;
}
List<String> getPlainTextInSelection(Selection? selection) {
selection ??= this.selection?.normalized;
if (selection == null || selection.isCollapsed) {
return [];
}
final res = <String>[];
if (selection.isCollapsed) {
return res;
}
final nodes = getNodesInSelection(selection);
for (final node in nodes) {
final delta = node.delta;
if (delta == null) {
continue;
}
final startIndex = node == nodes.first ? selection.startIndex : 0;
final endIndex = node == nodes.last ? selection.endIndex : delta.length;
res.add(delta.slice(startIndex, endIndex).toPlainText());
}
return res;
}
}
@@ -0,0 +1,404 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/build_context_extension.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_operations.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_widgets.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/discard_dialog.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart';
import 'package:appflowy/user/application/ai_service.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:universal_platform/universal_platform.dart';
import 'ai_limit_dialog.dart';
class AIWriterBlockKeys {
const AIWriterBlockKeys._();
static const String type = 'ai_writer';
static const String prompt = 'prompt';
static const String startSelection = 'start_selection';
static const String generationCount = 'generation_count';
static String getRewritePrompt(String previousOutput, String prompt) {
return 'I am not satisfied with your previous response ($previousOutput) to the query ($prompt). Please provide an alternative response.';
}
}
Node aiWriterNode({
String prompt = '',
required Selection start,
}) {
return Node(
type: AIWriterBlockKeys.type,
attributes: {
AIWriterBlockKeys.prompt: prompt,
AIWriterBlockKeys.startSelection: start.toJson(),
AIWriterBlockKeys.generationCount: 0,
},
);
}
class AIWriterBlockComponentBuilder extends BlockComponentBuilder {
AIWriterBlockComponentBuilder();
@override
BlockComponentWidget build(BlockComponentContext blockComponentContext) {
final node = blockComponentContext.node;
return AIWriterBlockComponent(
key: node.key,
node: node,
showActions: showActions(node),
actionBuilder: (context, state) => actionBuilder(
blockComponentContext,
state,
),
);
}
@override
BlockComponentValidate get validate => (node) =>
node.children.isEmpty &&
node.attributes[AIWriterBlockKeys.prompt] is String &&
node.attributes[AIWriterBlockKeys.startSelection] is Map;
}
class AIWriterBlockComponent extends BlockComponentStatefulWidget {
const AIWriterBlockComponent({
super.key,
required super.node,
super.showActions,
super.actionBuilder,
super.configuration = const BlockComponentConfiguration(),
});
@override
State<AIWriterBlockComponent> createState() => _AIWriterBlockComponentState();
}
class _AIWriterBlockComponentState extends State<AIWriterBlockComponent> {
final controller = TextEditingController();
final textFieldFocusNode = FocusNode();
late final editorState = context.read<EditorState>();
late final SelectionGestureInterceptor interceptor;
late final AIWriterBlockOperations aiWriterOperations =
AIWriterBlockOperations(
editorState: editorState,
aiWriterNode: widget.node,
);
String get prompt => widget.node.attributes[AIWriterBlockKeys.prompt];
int get generationCount =>
widget.node.attributes[AIWriterBlockKeys.generationCount] ?? 0;
Selection? get startSelection {
final selection = widget.node.attributes[AIWriterBlockKeys.startSelection];
if (selection != null) {
return Selection.fromJson(selection);
}
return null;
}
bool isGenerating = false;
@override
void initState() {
super.initState();
_subscribeSelectionGesture();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
editorState.selection = null;
textFieldFocusNode.requestFocus();
});
}
@override
void dispose() {
_onExit();
_unsubscribeSelectionGesture();
controller.dispose();
textFieldFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (UniversalPlatform.isMobile) {
return const SizedBox.shrink();
}
final child = Focus(
onKeyEvent: (node, event) {
if (event is! KeyDownEvent) {
return KeyEventResult.ignored;
}
if (event.logicalKey == LogicalKeyboardKey.enter) {
if (!isGenerating) {
_onGenerate();
}
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Theme.of(context).colorScheme.surface,
child: Container(
margin: const EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const AIWriterBlockHeader(),
const Space(0, 10),
if (prompt.isEmpty && generationCount < 1) ...[
_buildInputWidget(context),
const Space(0, 10),
AIWriterBlockInputField(
onGenerate: _onGenerate,
onExit: _onExit,
),
] else ...[
AIWriterBlockFooter(
onKeep: _onExit,
onRewrite: _onRewrite,
onDiscard: _onDiscard,
),
],
],
),
),
),
);
return Padding(
padding: const EdgeInsets.only(left: 40),
child: child,
);
}
Widget _buildInputWidget(BuildContext context) {
return FlowyTextField(
hintText: LocaleKeys.document_plugins_autoGeneratorHintText.tr(),
controller: controller,
maxLines: 5,
focusNode: textFieldFocusNode,
autoFocus: false,
hintTextConstraints: const BoxConstraints(),
);
}
Future<void> _onExit() async {
await aiWriterOperations.removeAIWriterNode(widget.node);
}
Future<void> _onGenerate() async {
if (isGenerating) {
return;
}
isGenerating = true;
await aiWriterOperations.updatePromptText(controller.text);
if (!_isAIWriterEnabled) {
Log.error('AI Writer is not enabled');
return;
}
final markdownTextRobot = MarkdownTextRobot(
editorState: editorState,
);
BarrierDialog? barrierDialog;
final aiRepository = AppFlowyAIService();
await aiRepository.streamCompletion(
text: controller.text,
completionType: CompletionTypePB.ContinueWriting,
onStart: () async {
if (mounted) {
barrierDialog = BarrierDialog(context);
barrierDialog?.show();
await aiWriterOperations.ensurePreviousNodeIsEmptyParagraphNode();
markdownTextRobot.start();
}
},
onProcess: (text) async {
await markdownTextRobot.appendMarkdownText(text);
},
onEnd: () async {
barrierDialog?.dismiss();
await markdownTextRobot.stop();
editorState.service.keyboardService?.enable();
},
onError: (error) async {
barrierDialog?.dismiss();
_showAIWriterError(error);
},
);
await aiWriterOperations.updateGenerationCount(generationCount + 1);
isGenerating = false;
}
Future<void> _onDiscard() async {
await aiWriterOperations.discardCurrentResponse(
aiWriterNode: widget.node,
selection: startSelection,
);
return _onExit();
}
Future<void> _onRewrite() async {
if (isGenerating) {
return;
}
isGenerating = true;
final previousOutput = _getPreviousOutput();
if (previousOutput == null) {
return;
}
// discard the current response
await aiWriterOperations.discardCurrentResponse(
aiWriterNode: widget.node,
selection: startSelection,
);
if (!_isAIWriterEnabled) {
return;
}
final markdownTextRobot = MarkdownTextRobot(
editorState: editorState,
);
final aiService = AppFlowyAIService();
await aiService.streamCompletion(
text: AIWriterBlockKeys.getRewritePrompt(previousOutput, prompt),
completionType: CompletionTypePB.ContinueWriting,
onStart: () async {
await aiWriterOperations.ensurePreviousNodeIsEmptyParagraphNode();
markdownTextRobot.start();
},
onProcess: (text) async {
await markdownTextRobot.appendMarkdownText(text);
},
onEnd: () async {
await markdownTextRobot.stop();
},
onError: (error) {
_showAIWriterError(error);
},
);
await aiWriterOperations.updateGenerationCount(generationCount + 1);
isGenerating = false;
}
String? _getPreviousOutput() {
final startSelection = this.startSelection;
if (startSelection != null) {
final end = widget.node.previous?.path;
if (end != null) {
final result = editorState
.getNodesInSelection(
startSelection.copyWith(end: Position(path: end)),
)
.fold(
'',
(previousValue, element) {
final delta = element.delta;
if (delta != null) {
return "$previousValue\n${delta.toPlainText()}";
} else {
return previousValue;
}
},
);
return result.trim();
}
}
return null;
}
void _subscribeSelectionGesture() {
interceptor = SelectionGestureInterceptor(
key: AIWriterBlockKeys.type,
canTap: (details) {
if (!context.isOffsetInside(details.globalPosition)) {
if (prompt.isNotEmpty || controller.text.isNotEmpty) {
// show dialog
showDialog(
context: context,
builder: (_) => DiscardDialog(
onConfirm: _onDiscard,
onCancel: () {},
),
);
} else if (controller.text.isEmpty) {
_onExit();
}
}
editorState.service.keyboardService?.disable();
return false;
},
);
editorState.service.selectionService.registerGestureInterceptor(
interceptor,
);
}
void _unsubscribeSelectionGesture() {
editorState.service.selectionService.unregisterGestureInterceptor(
AIWriterBlockKeys.type,
);
}
void _showAIWriterError(AIError error) {
if (mounted) {
if (error.isLimitExceeded) {
showAILimitDialog(context, error.message);
} else {
showToastNotification(
context,
message: error.message,
type: ToastificationType.error,
);
}
}
}
bool get _isAIWriterEnabled {
final userProfile = context.read<DocumentBloc>().state.userProfilePB;
final isAIWriterEnabled = userProfile != null;
if (!isAIWriterEnabled) {
showToastNotification(
context,
message: LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(),
type: ToastificationType.error,
);
}
return isAIWriterEnabled;
}
}
@@ -0,0 +1,112 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_component.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
/// Notes: All the operation related to the AI writer block will be applied
/// in memory.
class AIWriterBlockOperations {
AIWriterBlockOperations({
required this.editorState,
required this.aiWriterNode,
}) : assert(aiWriterNode.type == AIWriterBlockKeys.type);
final EditorState editorState;
final Node aiWriterNode;
/// Update the prompt text in the node.
Future<void> updatePromptText(String prompt) async {
final transaction = editorState.transaction;
transaction.updateNode(
aiWriterNode,
{AIWriterBlockKeys.prompt: prompt},
);
await editorState.apply(
transaction,
options: const ApplyOptions(
inMemoryUpdate: true,
recordUndo: false,
),
);
}
/// Update the generation count in the node.
Future<void> updateGenerationCount(int count) async {
final transaction = editorState.transaction;
transaction.updateNode(
aiWriterNode,
{AIWriterBlockKeys.generationCount: count},
);
await editorState.apply(
transaction,
options: const ApplyOptions(inMemoryUpdate: true),
);
}
/// Ensure the previous node is a empty paragraph node without any styles.
Future<void> ensurePreviousNodeIsEmptyParagraphNode() async {
final previous = aiWriterNode.previous;
final Selection selection;
// 1. previous node is null or
// 2. previous node is not a paragraph node or
// 3. previous node is a paragraph node but not empty
final isNotEmptyParagraphNode = previous == null ||
previous.type != ParagraphBlockKeys.type ||
(previous.delta?.toPlainText().isNotEmpty ?? false);
if (isNotEmptyParagraphNode) {
final path = aiWriterNode.path;
final transaction = editorState.transaction;
selection = Selection.collapsed(Position(path: path));
transaction
..insertNode(
path,
paragraphNode(),
)
..afterSelection = selection;
await editorState.apply(transaction);
} else {
selection = Selection.collapsed(Position(path: previous.path));
}
final transaction = editorState.transaction;
transaction.updateNode(aiWriterNode, {
AIWriterBlockKeys.startSelection: selection.toJson(),
});
transaction.afterSelection = selection;
await editorState.apply(
transaction,
options: const ApplyOptions(inMemoryUpdate: true),
);
}
/// Discard the current response and delete the previous node.
Future<void> discardCurrentResponse({
required Node aiWriterNode,
Selection? selection,
}) async {
if (selection != null) {
final start = selection.start.path;
final end = aiWriterNode.previous?.path;
if (end != null) {
final transaction = editorState.transaction;
transaction.deleteNodesAtPath(
start,
end.last - start.last + 1,
);
await editorState.apply(transaction);
await ensurePreviousNodeIsEmptyParagraphNode();
}
}
}
/// Remove the ai writer node from the editor.
Future<void> removeAIWriterNode(Node aiWriterNode) async {
final transaction = editorState.transaction;
transaction.deleteNode(aiWriterNode);
await editorState.apply(
transaction,
options: const ApplyOptions(inMemoryUpdate: true, recordUndo: false),
withUpdateSelection: false,
);
}
}
@@ -0,0 +1,104 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class AIWriterBlockHeader extends StatelessWidget {
const AIWriterBlockHeader({super.key});
@override
Widget build(BuildContext context) {
return FlowyText.medium(
LocaleKeys.document_plugins_autoGeneratorTitleName.tr(),
fontSize: 14,
);
}
}
class AIWriterBlockInputField extends StatelessWidget {
const AIWriterBlockInputField({
super.key,
required this.onGenerate,
required this.onExit,
});
final VoidCallback onGenerate;
final VoidCallback onExit;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
PrimaryRoundedButton(
text: LocaleKeys.button_generate.tr(),
margin: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 10.0,
),
radius: 8.0,
onTap: onGenerate,
),
const Space(10, 0),
OutlinedRoundedButton(
text: LocaleKeys.button_cancel.tr(),
margin: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 10.0,
),
onTap: onExit,
),
Flexible(
child: Container(
alignment: Alignment.centerRight,
child: FlowyText.regular(
LocaleKeys.document_plugins_warning.tr(),
color: Theme.of(context).hintColor,
overflow: TextOverflow.ellipsis,
fontSize: 12,
),
),
),
],
);
}
}
class AIWriterBlockFooter extends StatelessWidget {
const AIWriterBlockFooter({
super.key,
required this.onKeep,
required this.onRewrite,
required this.onDiscard,
});
final VoidCallback onKeep;
final VoidCallback onRewrite;
final VoidCallback onDiscard;
@override
Widget build(BuildContext context) {
return Row(
children: [
PrimaryRoundedButton(
text: LocaleKeys.button_keep.tr(),
margin: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 9.0,
),
onTap: onKeep,
),
const HSpace(10),
OutlinedRoundedButton(
text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),
onTap: onRewrite,
),
const HSpace(10),
OutlinedRoundedButton(
text: LocaleKeys.button_discard.tr(),
onTap: onDiscard,
),
],
);
}
}
@@ -1,9 +1,9 @@
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
enum SmartEditAction {
enum AskAIAction {
summarize,
fixSpelling,
improveWriting,
@@ -11,62 +11,62 @@ enum SmartEditAction {
String get toInstruction {
switch (this) {
case SmartEditAction.summarize:
case AskAIAction.summarize:
return 'Tl;dr';
case SmartEditAction.fixSpelling:
case AskAIAction.fixSpelling:
return 'Correct this to standard English:';
case SmartEditAction.improveWriting:
case AskAIAction.improveWriting:
return 'Rewrite this in your own words:';
case SmartEditAction.makeItLonger:
case AskAIAction.makeItLonger:
return 'Make this text longer:';
}
}
String prompt(String input) {
switch (this) {
case SmartEditAction.summarize:
case AskAIAction.summarize:
return '$input\n\nTl;dr';
case SmartEditAction.fixSpelling:
case AskAIAction.fixSpelling:
return 'Correct this to standard English:\n\n$input';
case SmartEditAction.improveWriting:
case AskAIAction.improveWriting:
return 'Rewrite this:\n\n$input';
case SmartEditAction.makeItLonger:
case AskAIAction.makeItLonger:
return 'Make this text longer:\n\n$input';
}
}
static SmartEditAction from(int index) {
static AskAIAction from(int index) {
switch (index) {
case 0:
return SmartEditAction.summarize;
return AskAIAction.summarize;
case 1:
return SmartEditAction.fixSpelling;
return AskAIAction.fixSpelling;
case 2:
return SmartEditAction.improveWriting;
return AskAIAction.improveWriting;
case 3:
return SmartEditAction.makeItLonger;
return AskAIAction.makeItLonger;
}
return SmartEditAction.fixSpelling;
return AskAIAction.fixSpelling;
}
String get name {
switch (this) {
case SmartEditAction.summarize:
case AskAIAction.summarize:
return LocaleKeys.document_plugins_smartEditSummarize.tr();
case SmartEditAction.fixSpelling:
case AskAIAction.fixSpelling:
return LocaleKeys.document_plugins_smartEditFixSpelling.tr();
case SmartEditAction.improveWriting:
case AskAIAction.improveWriting:
return LocaleKeys.document_plugins_smartEditImproveWriting.tr();
case SmartEditAction.makeItLonger:
case AskAIAction.makeItLonger:
return LocaleKeys.document_plugins_smartEditMakeLonger.tr();
}
}
}
class SmartEditActionWrapper extends ActionCell {
SmartEditActionWrapper(this.inner);
class AskAIActionWrapper extends ActionCell {
AskAIActionWrapper(this.inner);
final SmartEditAction inner;
final AskAIAction inner;
Widget? icon(Color iconColor) => null;
@@ -2,27 +2,34 @@ import 'dart:async';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/user/application/ai_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'smart_edit_bloc.freezed.dart';
part 'ask_ai_action_bloc.freezed.dart';
class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
SmartEditBloc({
enum AskAIReplacementType {
markdown,
plainText,
}
const _defaultReplacementType = AskAIReplacementType.markdown;
class AskAIActionBloc extends Bloc<AskAIEvent, AskAIState> {
AskAIActionBloc({
required this.node,
required this.editorState,
required this.action,
this.enableLogging = true,
}) : super(
SmartEditState.initial(action),
AskAIState.initial(action),
) {
on<SmartEditEvent>((event, emit) async {
on<AskAIEvent>((event, emit) async {
await event.when(
initial: (aiRepositoryProvider) async {
aiRepository = await aiRepositoryProvider;
@@ -61,7 +68,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
final Node node;
final EditorState editorState;
final SmartEditAction action;
final AskAIAction action;
final bool enableLogging;
// used to wait for the aiRepository to be initialized
final aiRepositoryCompleter = Completer();
@@ -75,14 +82,14 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
await aiRepositoryCompleter.future;
if (rewrite) {
add(const SmartEditEvent.update('', true, null));
add(const AskAIEvent.update('', true, null));
}
if (enableLogging) {
Log.info('[smart_edit] request completions');
}
final content = node.attributes[SmartEditBlockKeys.content] as String;
final content = node.attributes[AskAIBlockKeys.content] as String;
await aiRepository.streamCompletion(
text: content,
completionType: completionTypeFromInt(state.action),
@@ -93,7 +100,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (enableLogging) {
Log.info('[smart_edit] start generating');
}
add(const SmartEditEvent.update('', true, null));
add(const AskAIEvent.update('', true, null));
},
onProcess: (text) async {
if (isCanceled) {
@@ -104,7 +111,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
Log.debug('[smart_edit] onProcess: $text');
}
final newResult = state.result + text;
add(SmartEditEvent.update(newResult, false, null));
add(AskAIEvent.update(newResult, false, null));
},
onEnd: () async {
if (isCanceled) {
@@ -113,7 +120,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (enableLogging) {
Log.info('[smart_edit] end generating');
}
add(SmartEditEvent.update('${state.result}\n', false, null));
add(AskAIEvent.update('${state.result}\n', false, null));
},
onError: (error) async {
if (isCanceled) {
@@ -122,7 +129,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (enableLogging) {
Log.info('[smart_edit] onError: $error');
}
add(SmartEditEvent.update('', false, error));
add(AskAIEvent.update('', false, error));
await _exit();
await _clearSelection();
},
@@ -135,35 +142,70 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
if (selection == null) {
return;
}
// return if the result is empty
final result = state.result.trim();
if (result.isEmpty) {
return;
}
final insertedText = result.split('\n')
..removeWhere((element) => element.isEmpty);
final nodes = customMarkdownToDocument(state.result)
.root
.children
.map((e) => e.copyWith())
.toList();
final insertedPath = selection.end.path.next;
final transaction = editorState.transaction;
// todo: keep the style of the current node
transaction.insertNodes(
selection.end.path.next,
insertedText.map(
(e) => paragraphNode(
text: e,
),
),
);
final start = Position(path: selection.end.path.next);
final end = Position(
path: [selection.end.path.next.first + insertedText.length],
insertedPath,
nodes,
);
final lastDeltaLength = nodes.lastOrNull?.delta?.length ?? 0;
transaction.afterSelection = Selection(
start: start,
end: end,
start: Position(path: insertedPath),
end: Position(
path: insertedPath.nextNPath(nodes.length - 1),
offset: lastDeltaLength,
),
);
await editorState.apply(transaction);
}
Future<void> _replace() async {
switch (_defaultReplacementType) {
case AskAIReplacementType.markdown:
await _replaceWithMarkdown();
case AskAIReplacementType.plainText:
await _replaceWithPlainText();
}
}
Future<void> _replaceWithMarkdown() async {
final selection = editorState.selection?.normalized;
if (selection == null) {
return;
}
final nodes = customMarkdownToDocument(state.result)
.root
.children
.map((e) => e.copyWith())
.toList();
if (nodes.isEmpty) {
return;
}
final nodesInSelection = editorState.getNodesInSelection(selection);
final transaction = editorState.transaction;
transaction.insertNodes(
selection.start.path,
nodes,
);
transaction.deleteNodes(nodesInSelection);
transaction.afterSelection = Selection(
start: selection.start,
end: Position(
path: selection.start.path.nextNPath(nodes.length - 1),
offset: nodes.lastOrNull?.delta?.length ?? 0,
),
);
await editorState.apply(transaction);
}
Future<void> _replaceWithPlainText() async {
final result = state.result.trim();
if (result.isEmpty) {
return;
@@ -222,16 +264,16 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {
}
@freezed
class SmartEditEvent with _$SmartEditEvent {
const factory SmartEditEvent.initial(
class AskAIEvent with _$AskAIEvent {
const factory AskAIEvent.initial(
Future<AIRepository> aiRepositoryProvider,
) = _Initial;
const factory SmartEditEvent.started() = _Started;
const factory SmartEditEvent.rewrite() = _Rewrite;
const factory SmartEditEvent.replace() = _Replace;
const factory SmartEditEvent.insertBelow() = _InsertBelow;
const factory SmartEditEvent.cancel() = _Cancel;
const factory SmartEditEvent.update(
const factory AskAIEvent.started() = _Started;
const factory AskAIEvent.rewrite() = _Rewrite;
const factory AskAIEvent.replace() = _Replace;
const factory AskAIEvent.insertBelow() = _InsertBelow;
const factory AskAIEvent.cancel() = _Cancel;
const factory AskAIEvent.update(
String result,
bool isLoading,
AIError? error,
@@ -239,15 +281,15 @@ class SmartEditEvent with _$SmartEditEvent {
}
@freezed
class SmartEditState with _$SmartEditState {
const factory SmartEditState({
class AskAIState with _$AskAIState {
const factory AskAIState({
required bool loading,
required String result,
required SmartEditAction action,
required AskAIAction action,
@Default(null) AIError? requestError,
}) = _SmartEditState;
}) = _AskAIState;
factory SmartEditState.initial(SmartEditAction action) => SmartEditState(
factory AskAIState.initial(AskAIAction action) => AskAIState(
loading: true,
action: action,
result: '',
@@ -4,8 +4,9 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_limit_dialog.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_widgets.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -15,14 +16,14 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:universal_platform/universal_platform.dart';
class SmartEditBlockKeys {
const SmartEditBlockKeys._();
class AskAIBlockKeys {
const AskAIBlockKeys._();
static const type = 'smart_edit';
static const type = 'ask_ai';
/// The instruction of the smart edit.
///
/// It is a [SmartEditAction] value.
/// It is a [AskAIAction] value.
static const action = 'action';
/// The input of the smart edit.
@@ -31,26 +32,26 @@ class SmartEditBlockKeys {
static const content = 'content';
}
Node smartEditNode({
required SmartEditAction action,
Node askAINode({
required AskAIAction action,
required String content,
}) {
return Node(
type: SmartEditBlockKeys.type,
type: AskAIBlockKeys.type,
attributes: {
SmartEditBlockKeys.action: action.index,
SmartEditBlockKeys.content: content,
AskAIBlockKeys.action: action.index,
AskAIBlockKeys.content: content,
},
);
}
class SmartEditBlockComponentBuilder extends BlockComponentBuilder {
SmartEditBlockComponentBuilder();
class AskAIBlockComponentBuilder extends BlockComponentBuilder {
AskAIBlockComponentBuilder();
@override
BlockComponentWidget build(BlockComponentContext blockComponentContext) {
final node = blockComponentContext.node;
return SmartEditBlockComponentWidget(
return AskAIBlockComponentWidget(
key: node.key,
node: node,
showActions: showActions(node),
@@ -63,12 +64,12 @@ class SmartEditBlockComponentBuilder extends BlockComponentBuilder {
@override
BlockComponentValidate get validate => (node) =>
node.attributes[SmartEditBlockKeys.action] is int &&
node.attributes[SmartEditBlockKeys.content] is String;
node.attributes[AskAIBlockKeys.action] is int &&
node.attributes[AskAIBlockKeys.content] is String;
}
class SmartEditBlockComponentWidget extends BlockComponentStatefulWidget {
const SmartEditBlockComponentWidget({
class AskAIBlockComponentWidget extends BlockComponentStatefulWidget {
const AskAIBlockComponentWidget({
super.key,
required super.node,
super.showActions,
@@ -77,18 +78,17 @@ class SmartEditBlockComponentWidget extends BlockComponentStatefulWidget {
});
@override
State<SmartEditBlockComponentWidget> createState() =>
_SmartEditBlockComponentWidgetState();
State<AskAIBlockComponentWidget> createState() =>
_AskAIBlockComponentWidgetState();
}
class _SmartEditBlockComponentWidgetState
extends State<SmartEditBlockComponentWidget> {
class _AskAIBlockComponentWidgetState extends State<AskAIBlockComponentWidget> {
final popoverController = PopoverController();
late final editorState = context.read<EditorState>();
late final action = SmartEditAction
.values[widget.node.attributes[SmartEditBlockKeys.action] as int];
late SmartEditBloc smartEditBloc;
late final action =
AskAIAction.values[widget.node.attributes[AskAIBlockKeys.action] as int];
late AskAIActionBloc askAIBloc;
@override
void initState() {
@@ -98,16 +98,16 @@ class _SmartEditBlockComponentWidgetState
popoverController.show();
});
smartEditBloc = SmartEditBloc(
askAIBloc = AskAIActionBloc(
node: widget.node,
editorState: editorState,
action: action,
)..add(SmartEditEvent.initial(getIt.getAsync<AIRepository>()));
)..add(AskAIEvent.initial(getIt.getAsync<AIRepository>()));
}
@override
void dispose() {
smartEditBloc.close();
askAIBloc.close();
super.dispose();
}
@@ -128,8 +128,8 @@ class _SmartEditBlockComponentWidgetState
final width = _getEditorWidth();
return BlocProvider.value(
value: smartEditBloc,
child: BlocListener<SmartEditBloc, SmartEditState>(
value: askAIBloc,
child: BlocListener<AskAIActionBloc, AskAIState>(
listener: _onListen,
child: AppFlowyPopover(
controller: popoverController,
@@ -141,7 +141,7 @@ class _SmartEditBlockComponentWidgetState
constraints: BoxConstraints(maxWidth: width),
canClose: () async {
final completer = Completer<bool>();
final state = smartEditBloc.state;
final state = askAIBloc.state;
if (state.result.isEmpty) {
completer.complete(true);
} else {
@@ -160,8 +160,8 @@ class _SmartEditBlockComponentWidgetState
popupBuilder: (BuildContext popoverContext) {
return BlocProvider.value(
// request the result when opening the popover
value: smartEditBloc..add(const SmartEditEvent.started()),
child: const SmartEditInputContent(),
value: askAIBloc..add(const AskAIEvent.started()),
child: const AskAiInputContent(),
);
},
child: const SizedBox(
@@ -191,7 +191,7 @@ class _SmartEditBlockComponentWidgetState
editorState.apply(transaction);
}
void _onListen(BuildContext context, SmartEditState state) {
void _onListen(BuildContext context, AskAIState state) {
final error = state.requestError;
if (error != null) {
if (error.isLimitExceeded) {
@@ -206,110 +206,3 @@ class _SmartEditBlockComponentWidgetState
}
}
}
class SmartEditInputContent extends StatelessWidget {
const SmartEditInputContent({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<SmartEditBloc, SmartEditState>(
builder: (context, state) {
return Card(
elevation: 5,
color: Theme.of(context).colorScheme.surface,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Container(
margin: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.medium(
state.action.name,
fontSize: 14,
),
const VSpace(16),
state.loading
? _buildLoadingWidget(context)
: _buildResultWidget(context, state),
const VSpace(16),
const _SmartEditFooterWidget(),
],
),
),
);
},
);
}
Widget _buildResultWidget(BuildContext context, SmartEditState state) {
// todo: replace it with appflowy_editor
return Flexible(
child: FlowyText.regular(
state.result,
maxLines: null,
),
);
}
Widget _buildLoadingWidget(BuildContext context) {
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 4.0),
child: SizedBox.square(
dimension: 14,
child: CircularProgressIndicator(
strokeWidth: 2.0,
),
),
);
}
}
class _SmartEditFooterWidget extends StatelessWidget {
const _SmartEditFooterWidget();
@override
Widget build(BuildContext context) {
return Row(
children: [
OutlinedRoundedButton(
text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),
onTap: () =>
context.read<SmartEditBloc>().add(const SmartEditEvent.rewrite()),
),
const HSpace(10),
OutlinedRoundedButton(
text: LocaleKeys.button_replace.tr(),
onTap: () =>
context.read<SmartEditBloc>().add(const SmartEditEvent.replace()),
),
const HSpace(10),
OutlinedRoundedButton(
text: LocaleKeys.button_insertBelow.tr(),
onTap: () => context
.read<SmartEditBloc>()
.add(const SmartEditEvent.insertBelow()),
),
const HSpace(10),
OutlinedRoundedButton(
text: LocaleKeys.button_cancel.tr(),
onTap: () =>
context.read<SmartEditBloc>().add(const SmartEditEvent.cancel()),
),
Expanded(
child: Container(
alignment: Alignment.centerRight,
child: Text(
LocaleKeys.document_plugins_warning.tr(),
style: TextStyle(color: Theme.of(context).hintColor),
overflow: TextOverflow.ellipsis,
),
),
),
],
);
}
}
Loaded 100 of 299 files, more files were not shown because too many files have changed in this diff. Show more