fluffychat/lib/pages/chat/chat.dart
ggurdin 044726fed5
Merge main into production (#4437)
* 3871 activity session issues feedback (#3874)

* fix: add header when fetching image from CMS

* fix: only show activity start page is all roles have never been full

* chore: disable archive button until summary loads

* chore: still save activity analytics summary even if there's a choreo error when fetching summary

* chore: pass location image URL as topic image URL (#3876)

* feat: add local cache for activity session analytics (#3878)

* fix: in new courses, set course_user state event power level to 0 (#3882)

* fix: make activity summary request cache keys unique, use in-memory cache instead of local storage, remove items from cache on error or on state event sent successfully (#3885)

* chore: widen summary cards (#3888)

* Replaced references to spaces with courses in intl files and calls (#3884)

* Replaced references to spaces with courses in intl files and calls

* Change learning community reference to 'public course'

---------

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* chore: update delete course description (#3889)

* 3890 activity start page changes (#3901)

* comment out unreferenced files

* decouple courses, topics, and activities

* update start page

* disable 'join open session' button

* feat: activity dropdown menu

* fix: always initialize course info after fetching (#3907)

* chore: show role goal in text abut button on activity launch page and in tooltip above input bar (#3910)

* chore: go to course settings tab after archiving activity, show check over completed activites (#3913)

* fix: remove dollar sign from copy (#3914)

* fix: update payload accessToken on new login (#3916)

* 3915 course chat view updates (#3919)

* Removes Proper Noun from default analytics morph list (#3918)

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Level up popup tweaks (#3917)

* Use L10n for 'Level up' text

* Replace drop down button with close button

---------

Co-authored-by: ggurdin <ggurdin@gmail.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* chore: update how activity summary description expansion button layout works (#3930)

* fix: add analytics listener to activity stats menu (#3931)

* fix: don't show join message when user dismisses activity role goal message (#3932)

* chore: hide activity role tooltip when it bar is open (#3933)

* fix: fix null check error in activity role tooltip (#3935)

* fix: when fetching translation, only consider a message to have included IT if the sent message body matches the message at the end of choreo (#3936)

* chore: update messaging in subscription management (#3937)

* feat: join activity session on open app via ping (#3944)

* chore: don't show ping unread badge (#3946)

* fix: Correctly fetch activity images (#3943)

* fix fetching images and parsing url

* small fix for getting activity image URLs

---------

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* Set thumbVisibility true for grammar activity scrolling (#3942)

* Set thumbVisibility true for grammar activity scrolling

* always show scrollbar

---------

Co-authored-by: ggurdin <ggurdin@gmail.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* reload space hierarchy on invite update (#3949)

* 3927 analytics tweaks (#3953)

* analytics page updates

* add back download buttons

* some activity / invite page tweaks (#3958)

* Wrap invite course avatar in MapClipper (#3957)

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Add period to end of languageLevelA2Desc (#3959)

* fix: put back pangea controller init in chat list (#3965)

* fix: show bot avatar in open roles indicator (#3966)

* fix: on cancel registration, pop future loading dialog (#3967)

* chore: adjust actvity participant text colot (#3968)

* fix: always reload course on ID change (#3969)

* chore: increase size of text in archived activity popup (#3970)

* feat: add edit course page (#3971)

* 3962 usability test todos (#3973)

* in new course pages, show images

* in space analytics, if no available languages, pick user's l2

* chore: add cooldown on ping participants

* replace image loading icon with shimmer

* update activity launch page buttons, sort activities in topics by number of participants (#3974)

* chore: topic is completed if user has finished number of activities equal to number of 2 person activities in topic (#3983)

* feat: always show new tokens with green underlines (#3984)

* 3873 add superlatives for most vocab grammar and xp (#3977)

* add grammar and vocab superlatives

- adds superlatives to the summary cards for each user
- WIP, doesn't include XP superlative yet and it continuously reinitializes state which reloads the superlatives

* get analytic superlatives from saved state event

Revert activity user summaries widget to stateless, get info from saved state event instead of awaiting it, and fix some spacing issues.

* add xp superlative

- simplify 3 loop logic into one
- change from constant updates to only generate superlatives on analytics save

* sort imports

* put analytics loading inside buttonControlledCarouselView

* delete commented out code

* return superlative map instead of setting value

* chore: on new token update, clear whole new token cache in case there are identical tokens (#3985)

* fix: fix calculation of completed activities (#3986)

* chore: collection seed always fades up and out (#3987)

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* 3988 activitycourse tweaks (#3989)

* chore: set course and activity descriptions

* chore: remove redundant results button

* 3921 display unsubscribed errors for users (#3991)

* url cleanup

* chore: display unsubscribed errors differently

* chore: show user menu on click participant item (#3992)

* fix: Reintroduce shared isolate (#3981)

* initial scripts n actions

* custom cshared isolate

* kitlin fixes

* integrate and token fix

* executable and gstreamer

* disable check dupes, fix gstreamer

* another linux update, removed 2 android builds

* new updates

* final android attempt

* formatting

---------

Co-authored-by: ggurdin <ggurdin@gmail.com>

* chore: add snackbar message after pinging course participants (#3995)

* fix: don't show green underlines on own messages (#3997)

* 3803 indented bullets displayed strangely (#3999)

* make markdown function the same as matrix sdk

* fix: fix newline issues in html messages

* fix: replace build-web script (#4000)

* fix: try to fix build again (#4001)

* chore: don't allow hover of non-selectable activity participants items (#4002)

* 3895 emoji sequence on clicking the words in a sentence of the target language (#4004)

* cleanup

* feat: toolbar emoji mode

* Add dark/light mode check for unassigned participant label color (#4006)

* chore: update emoji button color (#4015)

* chore: move analytics tooltips inside scrollviews (#4016)

* chore: update icon and border of find a course nav rail item (#4005)

* chore: Improve translation script and translate vi, es, et (#3555)

* improve translation script

* update translation script, more translates for es, et, vi

* chore: fix click cursor showing on hover of disabled activity participant widget (#4020)

* chore: add hint text to text fields in course edit page (#4022)

* chore: add placeholder to image in course editting page (#4024)

* chore: show snackbar on course edit save (#4025)

* 4017 usability test todos 91725 (#4026)

* chore: add ability to toggle show password in signup and login pages

* chore: update text in register popup

* chore: disable save edits button if no changes in course edit page (#4033)

* chore: don't animate in-chat tooltips (#4034)

* chore: add scrollbar to topic activities list (#4035)

* Morph analytics scroll (#4032)

* Move download button above scroll view

* Make morph analytics spacing consistent with vocab analytics spacing

* feat: add ability to add course to existing space (#4037)

* fix: don't attempt to load analytics until your is logged in (#4047)

* feat: integrate room preview endpoint (#4014)

* feat: integrate room preview endpoint

* initial work for intermediary activity page

* Update lib/pangea/activity_sessions/activity_session_start/activity_session_start_page.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update lib/pangea/activity_sessions/activity_session_start/activity_session_start_page.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update lib/pangea/chat_settings/utils/room_summary_extension.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* formatting

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* 3934 activity summary card visual changes (#4013)

* visual tweaks and confetti rain on results generation

* create star rain widget to trigger when activity finishes

* delete commented out lines

* use new star confetti widget in levelup

---------

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Set height of activity creation sized box to 0 (#4048)

* 4036 playtest 91825 (#4051)

* chore: improve constrast in message practice

* fix typo

* chore: disable learning settings save button until change is made

* show word card on click vocab in activity dropdown

* Playtest updates (#4054)

* update emoji mode icon and tooltip

* upload CMS url instead of uploading image bytes to matrix

* re-init subscription controller after setting account creation date

* fix: don't allow new users to steal roles (#4055)

* chore: render activity instruction markdown (#4056)

* chore: disable hover effect on loading span card icons (#4057)

* fix: fix needed participants copy (#4058)

* update course plan repo search to correctly query (#4065)

* chore: fix practice mode icon / border contrast (#4067)

* chore: only show emoji button for save-vocab tokens, fix alignment for non-token text (#4071)

* fix: fix button visibility in activity start page (#4073)

* chore: use synapse room_preview to determine which activities users have completed (#4078)

* fix: don't reset edits using the room's title and description (#4080)

* chore: on web, show analytics in course chat view (#4085)

* chore: show user menu on click avatar in topic participant list (#4086)

* fix: fix toolbar buttons on mobile (#4087)

* chore: on course load error, show option to add a different course plan to space (#4089)

* fix: check if can invite to course when deciding if show invite button in activity session in course without enough users, disable instead of hiding (#4095)

* chore: shuffle practice tokens before selecting the ones to include (#4097)

* feat: show instruction overlay on first gain points in activity pointing user to click activity stats button (#4099)

* chore: add descriptions for analytics categories (#4100)

* chore: fix copy issue (#4102)

* fix: make invite button go to course invite page (#4103)

* chore: make autoIGC true for new accounts (#4105)

* 4110 playtest 92325 (#4121)

* style activity role tooltip like instruction inline tooltips

* style updates to activity details

* don't show token underlines in practice mode

* show loading activity analytics

* use all construct types to calculate activity analytics, include audio messages in activity summary request

* update chat context menus for activities

* fix positioning on menu in main chat list

* chore: update activity session notification to open activity start page without joining activity (#4122)

* chore: add copy to describe writing analytics (#4123)

* feat: new onboarding flow (#4112)

* feat: new onboarding flow

* go to course details page on click course template in setup page

* update route redirects

* style tweaks

* chore: add gold shimmer to active token practice buttons (#4131)

* chore: remove unnecessary spacing (#4132)

* fix: don't show end activity button until activity has started (#4134)

* chore: add no courses found indicator (#4135)

* chore: update course edit saving logic (#4136)

* chore: add loading indicator to course settings page (#4137)

* fix: use outer context when navigating via course chat popup (#4139)

* chore: update some copy in filter dropdowns (#4140)

* chore: make terms and conditions links work (#4141)

* chore: remove unnecessary padding (#4143)

* fix: hide activity role tooltip during translation (#4145)

* fix: always allow show menu on click activity participant (#4146)

* chore: remove text scaling in emoji mode (#4147)

* chore: increase size of user activity summary widgets (#4149)

* chore: make whole upper acitivty summary clickable to expand (#4150)

* fix: always set vocab as default tab in analytics page (#4151)

* build: fix lints for new flutter version (#4154)

* chore: changes to chat list main view (#4158)

* chore: changes to chat list main view

* remove onboarding page

* Make underlines translucent so lower parts of letters can be seen (#4160)

* 4142-allow-giving-of-activity-feedback (#4144)

* feat: activity feedback repo

* add UI for giving activity feedback

---------

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* fix: don't dispose new word overlay animation early (#4168)

* 4152 onboarding tweaks (#4163)

* filter courses by short lang codes

* reduce padding in course details page

* update home / registration routes

* refactor: replace find your people page with new course page from onboarding

* chore: on course search, always load course IDs from server (#4174)

* fix: fix double analytics view in two column mode (#4175)

* feat: on create course, go to invite page while course creation loads (#4178)

* chore: give activity goal tooltip max width (#4179)

* chore: remove horizontal offset from pressable button widget (#4180)

* chore: in space analytics tab on small screens show language code in language dropdown (#4182)

* chore: in reading asssitance input bar, if all practice activities for message are completed, show all done message (#4183)

* 4181 japanese words grouped when should be separate (#4184)

* fix: only continue pickup up adjacent tokens while they are punctuation

* uncomment commented out code

* chore: when igc has matches, make send button color disabled instead of red (#4185)

* chore: don't show choreo error on timeout after canceling translation (#4189)

* consume image sizes from cms, surface course plan activity locations apis (#4187)

* 4152 onboarding tweaks (#4190)

* filter courses by short lang codes

* reduce padding in course details page

* update home / registration routes

* refactor: replace find your people page with new course page from onboarding

* chore: add redirect to onboarding course plan page if user not in course

* chore: re-style onboarding buttons (#4196)

* chore: match vocab lemma irrespective of case, use static message in activity stats dropdown (#4205)

* chore: show word card in click vocab word in activity summary (#4206)

* feat: integrate course translation group (#4209)

* integrate course translation group

* Update lib/pangea/payload_client/models/course_plan/cms_course_plan_translation_group.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* formatting

---------

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* chore: wait for user to send at least 3 text or audio messages before showing overlay with instructions about clicking activity status button

* fix: disable ping course participants button if there are no no-bot users in course to ping

* chore: show 'all done' message in practice activity bar for each activity type (#4212)

* Decrease unselected igc underline to 20% opacity (#4214)

* 4199 prevent activity menu tooltip from being interfered with my other overlays to ensure it always shows (#4215)

* don't show activity dropdown instructions if word card is open

* block other overlays from openning when tutorial overlay is open

* remove duplicate open overlay data, don't wait for construct banners to close if overlay fails to open

* chore: show selected archived activity, add tooltip to archived activity analytics view (#4217)

* feat: use cached space code to join space on create account (#4224)

* chore: hide course filters in onboarding pages (#4226)

* feat: show warning popup on l2/activity language mixup (#4229)

* chore: add some debugging statement for staging logout issue (#4234)

* fix: on SSO registration, pass langcode to onboarding pages (#4235)

* fix: refresh expired course cache (#4240)

* Adjust unread badge height to compensate for activity header height (#4213)

* Adjust unread badge height to compensate for activity header height

* Limit height instead of hardcoding values

* Hide course analytics download button on mobile (#4241)

* 4242 change course redirect (#4245)

* feat: connect with synapse public courses endpoint

* intergate course IDs into response model

* remove course redirect, update user's l2 on return to language selection page

* display on public courses page to go to page to make your own and display on make your on page to skip to rooms

* fix: hide activity finished status message for archived activities (#4246)

* fix: fix join with code redirect for non-spaces (#4248)

* 4172 color inconsistency of activity elements (#4247)

* activity menu color consistency

And some sizing changes, made the stats button box much smaller

* revert activity button size changes

Also make text bigger to fill box, and make menu/summary buttons solid colors so the shadow under the button works.

* feat: allow users to give token feedback in word card

* feat: set initial L2 via cached space code course target language if available (#4264)

* fix: fix onboarding redirect on login (#4265)

* Updating logo with Vector svg Image (#4263)

* Updated Logo with SVG image & adjusted margins to keep things center

* Un-formated the Index.html

* Remove invite option from participants widget in DM (#4256)

* chore: padding adjustment in selected course view (#4267)

* chore: on invite, also invite to course parent (#4268)

* fix: don't show language mismatch warning popup if activity lang matches L1 (#4269)

* fix: don't update profile until user controller initialized, redirect to rooms from SSO login, in create account page redirect to language selection page if no language available (#4274)

* feat: add selected course page for public courses, redirect there on click public course, filter out already-joined public courses (#4276)

* chore: remove l1 and CERF course filters from start course and public courses pages, update styling of l2 dropdown (#4278)

* integrate original course topic activity field (#4295)

* fix: fix start your own course link in public courses page (#4306)

* change seed to new vocab bubble (#4305)

* change seed to new vocab bubble

and tweak the animation to fade in, then rise/fade out since this looks better than spinning in.

* formatting

---------

Co-authored-by: ggurdin <ggurdin@gmail.com>

* Make users return to activity session when use invite back button (#4288)

* feat: add notification volume setting (#4310)

* chore: enable activity stats button if someone else finishes the activity (#4311)

* chore: on play with bot timeout, show warning popup (#4312)

* chore: show activity stats cutout tooltip on other user finish activity (#4316)

* 4307 bot in dms and activity chats only (#4319)

* remove bot settings files

* exclude bot in invite page

* listen to language / CERF level changes and update bot DM settings

* Update lib/pangea/common/controllers/pangea_controller.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: don't assume that list of IDs to fetch and list of fetched objects are the same length (#4322)

* chore: remove background color from activity goal tooltip (#4324)

* fix: prevent word card title from bouncing around (#4325)

* fix: on join activity with role, preload activity participants list to get accurate list of assigned roles (#4326)

* chore: give max width to activity participant indicator widgets (#4327)

* fix: add value key based on selected tab to course settings widget to force refresh on navigate from finished activity (#4331)

* fix: prevent overflows in token info feedback dialog on mobile, add more specific unsubscribed error in future loading dialog (#4333)

* fix: fix storage of selected language not working on mobile (#4334)

* chore: reduce padding around message in new trip page (#4335)

* chore: more specific error message on not found course with code (#4336)

* chore: dismiss last snackbar before show invite snackbar (#4337)

* chore: switch order of buttons in space delete dialog (#4338)

* chore: add custom map icons (#4339)

* chore: add create at and updated at fields to course plan model (#4340)

* chore: add leave space description (#4341)

* refactor: remove ability to directly edit lemma defintions and morph assignments (#4347)

* Organize course repos (#4262)

* integrate CoursePlansRepo.translateActivity, translateTopic, translateCoursePlan

* move translation functions to requisite files

* integrate translation endpoint

* refactor: reorganize course-related repos, add request and response model classes

* remove l2s from translation requests

* update translation request and response models, use translation endpoint to get course info, cache courses with L1s in cache key

* update topics repo to use translation endpoint

* use activity translation endpoint

* refactor: incremental loading of individual course info, account for discrepancy between translated IDs and original IDs

* incremental loading of course batches

* Update lib/pangea/course_plans/courses/course_plan_room_extension.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* cleanup

* cleanup

* fix: some name changes

* formatting

---------

Co-authored-by: WilsonLe <leanhminh2907@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: wcjord <32568597+wcjord@users.noreply.github.com>

* fix: use same context in show and hide token feedback snackbar to fix closing functionality (#4349)

* fix: filter courses only by short lang code (#4350)

* fix: filter courses only by short lang code

* Update lib/pangea/course_creation/course_search_provider.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update lib/pangea/login/pages/public_trip_page.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: always call setState on update target language filter

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Add select all button to the delete space dialog (#4353)

* Initial plan

* Add select all button to delete space dialog

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Style select all button as CheckboxListTile

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* update copy

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* 4354 room stuck indefinitely loading (#4357)

* fix: stop loading course if course plan provider if courseId is null

* don't allow padding of null string to loadCoursePlan

* fix: reload space course after updating course state event, wait for … (#4359)

* fix: reload space course after updating course state event, wait for course ID update in sync after returning from add course to space function

* Update lib/pangea/course_settings/course_settings.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: filter out public courses for which course ID failed to load (#4360)

* 3976 making emoji selection more of an activity (#4255)

* add shimmer in vocab page when no emoji selected

* fix shimmer in 2 column mode and add XP for first emoji selection

* add xp sparkle on emoji selection

* formatting, imports, widget name typo fix

* dont rebuild analytics page on every analytics stream update

* remove listener

* move animation and selection visual after slow function

for better visual flow and hopefully not noticeable stutter

* change transformTargetId into variable, update local display state before awaiting saving to analytics room

---------

Co-authored-by: ggurdin <ggurdin@gmail.com>

* Hide vocab analytics instructions when filtering or searching (#4362)

* Initial plan

* Hide instructions tooltip when searching or filtering vocabulary

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Hide activity end prompt text when activity is archived (#4364)

* Initial plan

* Hide activity end prompt when activity is archived

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* fix: stop rebuilding whole course settings tab on screen size change (#4368)

* Fix foreground notification navigation to activity sessions for course pings (#4369)

* Initial plan

* Fix foreground notification navigation to activity sessions

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Add clarifying comments to notification handling code

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Refactor to reduce duplicate code between _onOpenNotification and goToRoom

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* chore: fix foreground notif small icon

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* fix: show screen loading in course settings until activity roles are … (#4374)

* fix: show screen loading in course settings until activity roles are completly loaded

* show loading indicator over activity card on load course summary

* Update lib/pages/chat_details/chat_details.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: on load course topics, also load location media to get topic images (#4376)

* Add "Share course" tooltip to ShareRoomButton (#4375)

* Initial plan

* Add 'Share course' tooltip to ShareRoomButton

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Move shareCourse localization to end of intl_en.arb

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Remove L1 (base language) display from course info chips (#4378)

* Initial plan

* Remove L1 display from courses

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* chore: only show unlocalized language options in course search target language dropdowns (#4380)

* fix: after add course to existing space, push redirect route to refresh page (#4381)

* fix: update isActivityStarted to rely on assignedRoles instead of directly using state event (#4382)

* add XP animation on match activity tokens (#4373)

* 4379 show participants in public courses selection (#4383)

* chore: trip body / icons updates

* chore: display participant count in public courses page, update trip-related copy

* fix: add base language dropdown to language selection page on identic… (#4384)

* fix: add base language dropdown to language selection page on identical target and system language

* Update lib/pangea/login/utils/lang_code_repo.dart

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: add cms api url to activity image paths to load properly (#4385)

* fix: don't mutate activity JSON image_url (#4386)

* Update onboarding language selection text to "Choose a target language" (#4393)

* Initial plan

* Update chooseLanguage text to "Choose a target language"

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Update IT help message and remove unreferenced InstructionsEnum entries (#4391)

* Initial plan

* Update IT help message and remove unreferenced enum entries

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* Revert changes to non-English .arb files

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* remove unreferenced copy

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* fix: alway hide back button in add course page (#4404)

* Move word card feedback notification from bottom to top of screen (#4402)

* Initial plan

* Replace bottom SnackBar with top overlay notification for word card feedback

Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>

* auto-close top token feedback snackbar after delay

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ggurdin <46800240+ggurdin@users.noreply.github.com>
Co-authored-by: ggurdin <ggurdin@gmail.com>

* chore: add level bar / analytics to space details page on mobiel (#4405)

* chore: add skip button to add course page (#4407)

* chore: message on empty vocab filter (#4410)

* chore: add tooltip to describe vocab highlighting in activity dropdown menu (#4412)

* fix: don't delete archived activities on delete space (#4414)

* fix: don't delete archived activities on delete space

* use one list of futures in delete space function

* fix: refresh chat list on join with link (#4417)

* chore: make word card close and flag button the same styling and vertically aligned (#4419)

* fix: if a new user gets to account create page without target language in local storage or from course, direct them back to language selection (#4422)

* fix: handle room code on join with code (#4427)

* fix: push route on start to make add course page app bar back button work as expected (#4430)

* chore: update translations (#4188)

* translate more l1s

* Update translations for multiple languages (ar, bn, he, hi, id, ko, pt, ru, th, tr, zh)

* partial translations

* Add translations for Irish, Galician, Hungarian, Lithuanian, Slovenian, and Telugu

- Complete translations for 6 additional languages using OpenAI translation script
- Irish (ga): 1,612 translations added
- Galician (gl): 1,614 translations added
- Hungarian (hu): 1,615 translations added
- Lithuanian (lt): 1,927 translations added
- Slovenian (sl): 2,288 translations added
- Telugu (te): 2,388 translations added

These additions bring the total completed languages to 29 out of 47 (62% completion rate)

* Add translations for Estonian, Belarusian, and Greek

- Estonian (et): 164 translations added
- Belarusian (be): 2,392 translations added
- Greek (el): 2,342 translations added

These additions bring the total completed languages to 32 out of 47 (68% completion rate)

* Add Hebrew translations - Hebrew (he): 2,143 translations added - This brings the total completed languages to 33 out of 47 (70 percent completion rate)

* Add Arabic and Bengali translations - Arabic (ar): 1,692 translations added - Bengali (bn): 2,388 translations added - Total: 35 out of 47 languages complete (74 percent completion rate)

* Add Interlingua and Interlingue translations - Interlingua (ia): 2,378 translations added - Interlingue (ie): 2,149 translations added - Total: 37 out of 47 languages complete (79 percent completion rate)

* Add Georgian translations

* Add Esperanto translations

* Add Turkish translations

* Add Persian translations

* Add Romanian translations

* Improve translation script error handling

- Add JSON parsing error handling with retry logic
- Use simpler prompts on retry attempts
- Clean up markdown formatting from responses
- Skip failed chunks gracefully instead of crashing
- Successfully handle previously failing languages

* Update Georgian and add Romanian translations

* Add Serbian, Latvian, Slovak, Tamil and Basque translations

Successfully completed:
- Serbian (sr): 2062 translations
- Latvian (lv): 1614 translations
- Slovak (sk): 2158 translations
- Tamil (ta): 1696 translations
- Basque (eu): 1615 translations

Script improvements:
- Added metadata reconciliation error handling
- Successfully handles JSON parsing errors with retry logic

* fix needed translation generation script

* feat: translate missing keys for 49 languages and improve translation script

- Successfully translated 12,000+ keys across 49 languages (98% completion)
- Enhanced JSON error handling in translate script to recover from parsing errors
- Fixed metadata type issues for unreadChats placeholder in fil, pt_PT, and yue locales
- Added comprehensive run_all_translations.py script for batch translation
- Resolved duplicate yue locale conflicts
- Only Tibetan (bo) remains with 40 keys due to complex character encoding issues

Languages completed:
- Vietnamese, Portuguese (BR/PT), Romanian, Russian, Slovak, Slovenian
- Serbian, Swedish, Tamil, Telugu, Thai, Turkish, Ukrainian, Cantonese
- Chinese (Simplified/Traditional), and 34 other languages with 17 keys each

* fix not compilling error

* catch up with needed translations

* chore: on no courses found for language, log error (#4434)

* fix: fix scrolling in delete space dialog (#4436)

* build: bump version number

* chore: remove vocab tooltip from activity dropdown menu and update copy in end activity button (#4445)

* removed old code (#4446)

* change xp icon to star (#4431)

* fix: on login, don't open two separate databases (#4449)

* fix: register UIA listener on create login client, instead of on login (#4451)

* fix: on click space nav item use context.push to refresh course settings page (#4462)

* chore: add activity roles to activity summary request model (#4479)

* build: bump version number

---------

Co-authored-by: Kelrap <99418823+Kelrap@users.noreply.github.com>
Co-authored-by: Wilson <leanhminh2907@gmail.com>
Co-authored-by: avashilling <165050625+avashilling@users.noreply.github.com>
Co-authored-by: Brord van Wierst <brordvwierst@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: wcjord <32568597+wcjord@users.noreply.github.com>
Co-authored-by: Alexa "Tig" Harriss <alexa.harriss@gmail.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
2025-10-30 11:21:19 -04:00

2331 lines
68 KiB
Dart

import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:collection/collection.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:just_audio/just_audio.dart';
import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_html/html.dart' as html;
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/config/setting_keys.dart';
import 'package:fluffychat/config/themes.dart';
import 'package:fluffychat/l10n/l10n.dart';
import 'package:fluffychat/pages/chat/chat_view.dart';
import 'package:fluffychat/pages/chat/event_info_dialog.dart';
import 'package:fluffychat/pages/chat/events/audio_player.dart';
import 'package:fluffychat/pages/chat/recording_dialog.dart';
import 'package:fluffychat/pages/chat_details/chat_details.dart';
import 'package:fluffychat/pangea/activity_sessions/activity_role_model.dart';
import 'package:fluffychat/pangea/activity_sessions/activity_room_extension.dart';
import 'package:fluffychat/pangea/activity_sessions/activity_session_start/activity_session_start_page.dart';
import 'package:fluffychat/pangea/analytics_misc/construct_type_enum.dart';
import 'package:fluffychat/pangea/analytics_misc/constructs_model.dart';
import 'package:fluffychat/pangea/analytics_misc/gain_points_animation.dart';
import 'package:fluffychat/pangea/analytics_misc/level_up/level_up_banner.dart';
import 'package:fluffychat/pangea/analytics_misc/put_analytics_controller.dart';
import 'package:fluffychat/pangea/bot/utils/bot_name.dart';
import 'package:fluffychat/pangea/chat/utils/unlocked_morphs_snackbar.dart';
import 'package:fluffychat/pangea/chat/widgets/event_too_large_dialog.dart';
import 'package:fluffychat/pangea/choreographer/controllers/choreographer.dart';
import 'package:fluffychat/pangea/choreographer/enums/edit_type.dart';
import 'package:fluffychat/pangea/choreographer/models/choreo_record.dart';
import 'package:fluffychat/pangea/choreographer/utils/language_mismatch_repo.dart';
import 'package:fluffychat/pangea/choreographer/widgets/igc/language_mismatch_popup.dart';
import 'package:fluffychat/pangea/choreographer/widgets/igc/message_analytics_feedback.dart';
import 'package:fluffychat/pangea/choreographer/widgets/igc/pangea_text_controller.dart';
import 'package:fluffychat/pangea/common/constants/model_keys.dart';
import 'package:fluffychat/pangea/common/controllers/pangea_controller.dart';
import 'package:fluffychat/pangea/common/utils/error_handler.dart';
import 'package:fluffychat/pangea/common/utils/firebase_analytics.dart';
import 'package:fluffychat/pangea/common/utils/overlay.dart';
import 'package:fluffychat/pangea/events/event_wrappers/pangea_message_event.dart';
import 'package:fluffychat/pangea/events/extensions/pangea_event_extension.dart';
import 'package:fluffychat/pangea/events/models/pangea_token_model.dart';
import 'package:fluffychat/pangea/events/models/representation_content_model.dart';
import 'package:fluffychat/pangea/events/models/tokens_event_content_model.dart';
import 'package:fluffychat/pangea/extensions/pangea_room_extension.dart';
import 'package:fluffychat/pangea/instructions/instructions_enum.dart';
import 'package:fluffychat/pangea/learning_settings/constants/language_constants.dart';
import 'package:fluffychat/pangea/learning_settings/widgets/p_language_dialog.dart';
import 'package:fluffychat/pangea/message_token_text/tokens_util.dart';
import 'package:fluffychat/pangea/spaces/utils/load_participants_util.dart';
import 'package:fluffychat/pangea/toolbar/enums/message_mode_enum.dart';
import 'package:fluffychat/pangea/toolbar/widgets/message_selection_overlay.dart';
import 'package:fluffychat/utils/error_reporter.dart';
import 'package:fluffychat/utils/file_selector.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions/event_extension.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions/filtered_timeline_extension.dart';
import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart';
import 'package:fluffychat/utils/other_party_can_receive.dart';
import 'package:fluffychat/utils/platform_infos.dart';
import 'package:fluffychat/utils/show_scaffold_dialog.dart';
import 'package:fluffychat/widgets/adaptive_dialogs/show_modal_action_popup.dart';
import 'package:fluffychat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
import 'package:fluffychat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
import 'package:fluffychat/widgets/future_loading_dialog.dart';
import 'package:fluffychat/widgets/matrix.dart';
import 'package:fluffychat/widgets/share_scaffold_dialog.dart';
import '../../utils/account_bundles.dart';
import '../../utils/localized_exception_extension.dart';
import 'send_file_dialog.dart';
import 'send_location_dialog.dart';
class ChatPage extends StatelessWidget {
final String roomId;
final List<ShareItem>? shareItems;
final String? eventId;
// #Pangea
final Widget? backButton;
// Pangea#
const ChatPage({
super.key,
required this.roomId,
this.eventId,
this.shareItems,
// #Pangea
this.backButton,
// Pangea#
});
@override
Widget build(BuildContext context) {
final room = Matrix.of(context).client.getRoomById(roomId);
// #Pangea
if (room?.isSpace == true &&
GoRouterState.of(context).fullPath?.endsWith(":roomid") == true) {
ErrorHandler.logError(
e: "Space chat opened",
s: StackTrace.current,
data: {"roomId": roomId},
);
context.go("/rooms");
}
if (room == null || room.membership == Membership.leave) {
// if (room == null) {
// Pangea#
return Scaffold(
appBar: AppBar(title: Text(L10n.of(context).oopsSomethingWentWrong)),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(L10n.of(context).youAreNoLongerParticipatingInThisChat),
),
),
);
}
return ChatPageWithRoom(
key: Key('chat_page_${roomId}_$eventId'),
room: room,
shareItems: shareItems,
eventId: eventId,
// #Pangea
backButton: backButton,
// Pangea#
);
}
}
class ChatPageWithRoom extends StatefulWidget {
final Room room;
final List<ShareItem>? shareItems;
final String? eventId;
// #Pangea
final Widget? backButton;
// Pangea#
const ChatPageWithRoom({
super.key,
required this.room,
this.shareItems,
this.eventId,
// #Pangea
this.backButton,
// Pangea#
});
@override
ChatController createState() => ChatController();
}
class ChatController extends State<ChatPageWithRoom>
with WidgetsBindingObserver {
// #Pangea
final PangeaController pangeaController = MatrixState.pangeaController;
late Choreographer choreographer = Choreographer(pangeaController, this);
late GoRouter _router;
StreamSubscription? _levelSubscription;
StreamSubscription? _analyticsSubscription;
StreamSubscription? _botAudioSubscription;
// Pangea#
Room get room => sendingClient.getRoomById(roomId) ?? widget.room;
late Client sendingClient;
Timeline? timeline;
late final String readMarkerEventId;
String get roomId => widget.room.id;
final AutoScrollController scrollController = AutoScrollController();
late final FocusNode inputFocus;
StreamSubscription<html.Event>? onFocusSub;
Timer? typingCoolDown;
Timer? typingTimeout;
bool currentlyTyping = false;
// #Pangea
// bool dragging = false;
// void onDragEntered(_) => setState(() => dragging = true);
// void onDragExited(_) => setState(() => dragging = false);
// void onDragDone(DropDoneDetails details) async {
// setState(() => dragging = false);
// if (details.files.isEmpty) return;
// await showAdaptiveDialog(
// context: context,
// builder: (c) => SendFileDialog(
// files: details.files,
// room: room,
// outerContext: context,
// ),
// );
// }
// Pangea#
bool get canSaveSelectedEvent =>
selectedEvents.length == 1 &&
{
MessageTypes.Video,
MessageTypes.Image,
MessageTypes.Sticker,
MessageTypes.Audio,
MessageTypes.File,
}.contains(selectedEvents.single.messageType);
void saveSelectedEvent(context) => selectedEvents.single.saveFile(context);
List<Event> selectedEvents = [];
final Set<String> unfolded = {};
Event? replyEvent;
Event? editEvent;
bool _scrolledUp = false;
bool get showScrollDownButton =>
_scrolledUp || timeline?.allowNewEvent == false;
bool get selectMode => selectedEvents.isNotEmpty;
final int _loadHistoryCount = 100;
String pendingText = '';
bool showEmojiPicker = false;
void recreateChat() async {
final room = this.room;
final userId = room.directChatMatrixID;
if (userId == null) {
throw Exception(
'Try to recreate a room with is not a DM room. This should not be possible from the UI!',
);
}
await showFutureLoadingDialog(
context: context,
future: () => room.invite(userId),
);
}
void leaveChat() async {
final success = await showFutureLoadingDialog(
context: context,
future: room.leave,
);
if (success.error != null) return;
context.go('/rooms');
}
// #Pangea
// void requestHistory([_]) async {
Future<void> requestHistory() async {
if (timeline == null) return;
if (!timeline!.canRequestHistory) return;
// Pangea#
Logs().v('Requesting history...');
await timeline?.requestHistory(historyCount: _loadHistoryCount);
}
void requestFuture() async {
final timeline = this.timeline;
if (timeline == null) return;
Logs().v('Requesting future...');
final mostRecentEventId = timeline.events.first.eventId;
await timeline.requestFuture(historyCount: _loadHistoryCount);
setReadMarker(eventId: mostRecentEventId);
}
void _updateScrollController() {
if (!mounted) {
return;
}
if (!scrollController.hasClients) return;
if (timeline?.allowNewEvent == false ||
scrollController.position.pixels > 0 && _scrolledUp == false) {
setState(() => _scrolledUp = true);
} else if (scrollController.position.pixels <= 0 && _scrolledUp == true) {
setState(() => _scrolledUp = false);
setReadMarker();
}
if (scrollController.position.pixels == 0 ||
scrollController.position.pixels == 64) {
requestFuture();
}
}
void _loadDraft() async {
final prefs = await SharedPreferences.getInstance();
final draft = prefs.getString('draft_$roomId');
if (draft != null && draft.isNotEmpty) {
// #Pangea
// sendController.text = draft;
sendController.setSystemText(draft, EditType.other);
// Pangea#
}
}
void _shareItems([_]) {
final shareItems = widget.shareItems;
if (shareItems == null || shareItems.isEmpty) return;
if (!room.otherPartyCanReceiveMessages) {
final theme = Theme.of(context);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: theme.colorScheme.errorContainer,
closeIconColor: theme.colorScheme.onErrorContainer,
content: Text(
L10n.of(context).otherPartyNotLoggedIn,
style: TextStyle(
color: theme.colorScheme.onErrorContainer,
),
),
showCloseIcon: true,
),
);
return;
}
for (final item in shareItems) {
if (item is FileShareItem) continue;
if (item is TextShareItem) room.sendTextEvent(item.value);
if (item is ContentShareItem) room.sendEvent(item.value);
}
final files = shareItems
.whereType<FileShareItem>()
.map((item) => item.value)
.toList();
if (files.isEmpty) return;
showAdaptiveDialog(
context: context,
builder: (c) => SendFileDialog(
files: files,
room: room,
outerContext: context,
),
);
}
KeyEventResult _customEnterKeyHandling(FocusNode node, KeyEvent evt) {
if (!HardwareKeyboard.instance.isShiftPressed &&
evt.logicalKey.keyLabel == 'Enter' &&
(AppConfig.sendOnEnter ?? !PlatformInfos.isMobile)) {
if (evt is KeyDownEvent) {
// #Pangea
// send();
choreographer.send(context);
// Pangea#
}
return KeyEventResult.handled;
} else if (evt.logicalKey.keyLabel == 'Enter' && evt is KeyDownEvent) {
final currentLineNum = sendController.text
.substring(
0,
sendController.selection.baseOffset,
)
.split('\n')
.length -
1;
final currentLine = sendController.text.split('\n')[currentLineNum];
for (final pattern in [
'- [ ] ',
'- [x] ',
'* [ ] ',
'* [x] ',
'- ',
'* ',
'+ ',
]) {
if (currentLine.startsWith(pattern)) {
if (currentLine == pattern) {
return KeyEventResult.ignored;
}
sendController.text += '\n$pattern';
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
} else {
return KeyEventResult.ignored;
}
}
@override
void initState() {
inputFocus = FocusNode(onKeyEvent: _customEnterKeyHandling);
scrollController.addListener(_updateScrollController);
inputFocus.addListener(_inputFocusListener);
_loadDraft();
WidgetsBinding.instance.addPostFrameCallback(_shareItems);
super.initState();
_displayChatDetailsColumn = ValueNotifier(
AppSettings.displayChatDetailsColumn.getItem(Matrix.of(context).store),
);
sendingClient = Matrix.of(context).client;
readMarkerEventId = room.hasNewMessages ? room.fullyRead : '';
WidgetsBinding.instance.addObserver(this);
// #Pangea
if (!mounted) return;
Future.delayed(const Duration(seconds: 1), () async {
if (!mounted) return;
debugPrint(
"chat.dart l1 ${pangeaController.languageController.userL1?.langCode}",
);
debugPrint(
"chat.dart l2 ${pangeaController.languageController.userL2?.langCode}",
);
if (mounted) {
pangeaController.languageController.showDialogOnEmptyLanguage(
context,
() => Future.delayed(
Duration.zero,
() => setState(() {}),
),
);
}
});
_levelSubscription = pangeaController.getAnalytics.stateStream
.where(
(update) =>
update is Map<String, dynamic> &&
(update['level_up'] != null || update['unlocked_constructs'] != null),
)
.listen(
(update) {
if (update['level_up'] != null) {
LevelUpUtil.showLevelUpDialog(
update['upper_level'],
update['lower_level'],
context,
);
} else if (update['unlocked_constructs'] != null) {
ConstructNotificationUtil.addUnlockedConstruct(
List.from(update['unlocked_constructs']),
context,
);
}
},
);
_analyticsSubscription =
pangeaController.getAnalytics.analyticsStream.stream.listen((update) {
if (update.targetID == null) return;
OverlayUtil.showOverlay(
overlayKey: "${update.targetID ?? ""}_points",
followerAnchor: Alignment.bottomCenter,
targetAnchor: Alignment.bottomCenter,
context: context,
child: PointsGainedAnimation(
points: update.points,
targetID: update.targetID!,
),
transformTargetId: update.targetID ?? "",
closePrevOverlay: false,
backDropToDismiss: false,
ignorePointer: true,
);
});
_botAudioSubscription = room.client.onSync.stream
.where(
(update) => update.rooms?.join?[roomId]?.timeline?.events != null,
)
.listen((update) async {
final timeline = update.rooms!.join![roomId]!.timeline!;
final botAudioEvent = timeline.events!.firstWhereOrNull(
(e) =>
e.senderId == BotName.byEnvironment &&
e.content.tryGet<String>('msgtype') == MessageTypes.Audio &&
DateTime.now().difference(e.originServerTs) <
const Duration(seconds: 10),
);
if (botAudioEvent == null) return;
final matrix = Matrix.of(context);
matrix.voiceMessageEventId.value = botAudioEvent.eventId;
matrix.audioPlayer?.dispose();
matrix.audioPlayer = AudioPlayer();
final event = Event.fromMatrixEvent(botAudioEvent, room);
final audioFile = await event.getPangeaAudioFile();
debugPrint(
"audiofile: ${audioFile?.mimeType} ${audioFile?.bytes.length}",
);
if (audioFile == null) return;
if (!kIsWeb) {
final tempDir = await getTemporaryDirectory();
File? file;
file = File('${tempDir.path}/${audioFile.name}');
await file.writeAsBytes(audioFile.bytes);
matrix.audioPlayer!.setFilePath(file.path);
} else {
matrix.audioPlayer!.setAudioSource(
BytesAudioSource(
audioFile.bytes,
audioFile.mimeType,
),
);
}
matrix.audioPlayer!.play();
});
// Pangea#
_tryLoadTimeline();
if (kIsWeb) {
onFocusSub = html.window.onFocus.listen((_) => setReadMarker());
}
}
void _tryLoadTimeline() async {
final initialEventId = widget.eventId;
loadTimelineFuture = _getTimeline();
try {
await loadTimelineFuture;
if (initialEventId != null) scrollToEventId(initialEventId);
var readMarkerEventIndex = readMarkerEventId.isEmpty
? -1
: timeline!.events
.filterByVisibleInGui(exceptionEventId: readMarkerEventId)
.indexWhere((e) => e.eventId == readMarkerEventId);
// Read marker is existing but not found in first events. Try a single
// requestHistory call before opening timeline on event context:
if (readMarkerEventId.isNotEmpty && readMarkerEventIndex == -1) {
await timeline?.requestHistory(historyCount: _loadHistoryCount);
readMarkerEventIndex = timeline!.events
.filterByVisibleInGui(exceptionEventId: readMarkerEventId)
.indexWhere((e) => e.eventId == readMarkerEventId);
}
if (readMarkerEventIndex > 1) {
Logs().v('Scroll up to visible event', readMarkerEventId);
scrollToEventId(readMarkerEventId, highlightEvent: false);
return;
} else if (readMarkerEventId.isNotEmpty && readMarkerEventIndex == -1) {
_showScrollUpMaterialBanner(readMarkerEventId);
}
// Mark room as read on first visit if requirements are fulfilled
setReadMarker();
if (!mounted) return;
} catch (e, s) {
ErrorReporter(context, 'Unable to load timeline').onErrorCallback(e, s);
rethrow;
}
}
String? scrollUpBannerEventId;
void discardScrollUpBannerEventId() => setState(() {
scrollUpBannerEventId = null;
});
void _showScrollUpMaterialBanner(String eventId) => setState(() {
scrollUpBannerEventId = eventId;
});
void updateView() {
if (!mounted) return;
setReadMarker();
setState(() {});
}
Future<void>? loadTimelineFuture;
int? animateInEventIndex;
void onInsert(int i) {
// setState will be called by updateView() anyway
// #Pangea
// If fake event was sent, don't animate in the next event.
// It makes the replacement of the fake event jumpy.
if (_fakeEventIDs.isNotEmpty) {
animateInEventIndex = null;
return;
}
// Pangea#
animateInEventIndex = i;
}
// #Pangea
List<Event> get visibleEvents =>
timeline?.events
.where(
(x) => x.isVisibleInGui,
)
.toList() ??
<Event>[];
// Pangea#
Future<void> _getTimeline({
String? eventContextId,
}) async {
await Matrix.of(context).client.roomsLoading;
await Matrix.of(context).client.accountDataLoading;
if (eventContextId != null &&
(!eventContextId.isValidMatrixId || eventContextId.sigil != '\$')) {
eventContextId = null;
}
try {
timeline?.cancelSubscriptions();
timeline = await room.getTimeline(
onUpdate: updateView,
eventContextId: eventContextId,
onInsert: onInsert,
);
// #Pangea
if (visibleEvents.length < 10 && timeline != null) {
var prevNumEvents = timeline!.events.length;
await requestHistory();
var numRequests = 0;
while (timeline != null &&
timeline!.events.length > prevNumEvents &&
visibleEvents.length < 10 &&
numRequests <= 5) {
prevNumEvents = timeline!.events.length;
await requestHistory();
numRequests++;
}
}
// Pangea#
} catch (e, s) {
Logs().w('Unable to load timeline on event ID $eventContextId', e, s);
if (!mounted) return;
timeline = await room.getTimeline(
onUpdate: updateView,
onInsert: onInsert,
);
if (!mounted) return;
if (e is TimeoutException || e is IOException) {
_showScrollUpMaterialBanner(eventContextId!);
}
}
timeline!.requestKeys(onlineKeyBackupOnly: false);
if (room.markedUnread) room.markUnread(false);
return;
}
String? scrollToEventIdMarker;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// #Pangea
// On iOS, if the toolbar is open and the app is closed, then the user goes
// back to do more toolbar activities, the toolbar buttons / selection don't
// update properly. So, when the user closes the app, close the toolbar overlay.
if (state == AppLifecycleState.paused) {
clearSelectedEvents();
}
if (state == AppLifecycleState.hidden && !stopMediaStream.isClosed) {
stopMediaStream.add(null);
}
// Pangea#
if (state != AppLifecycleState.resumed) return;
if (!mounted) return;
setReadMarker();
}
Future<void>? _setReadMarkerFuture;
void setReadMarker({String? eventId}) {
// #Pangea
if (room.client.userID == null ||
eventId != null &&
(eventId.contains("web") ||
eventId.contains("android") ||
eventId.contains("ios"))) {
return;
}
// Pangea#
if (eventId?.isValidMatrixId == false) return;
if (_setReadMarkerFuture != null) return;
if (_scrolledUp) return;
if (scrollUpBannerEventId != null) return;
if (eventId == null &&
!room.hasNewMessages &&
room.notificationCount == 0) {
return;
}
// Do not send read markers when app is not in foreground
// #Pangea
try {
// Pangea#
if (kIsWeb && !Matrix.of(context).webHasFocus) return;
// #Pangea
} catch (err) {
return;
}
// Pangea#
if (!kIsWeb &&
WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed) {
return;
}
final timeline = this.timeline;
if (timeline == null || timeline.events.isEmpty) return;
Logs().d('Set read marker...', eventId);
// ignore: unawaited_futures
_setReadMarkerFuture = timeline
.setReadMarker(
eventId: eventId,
public: AppConfig.sendPublicReadReceipts,
)
.then((_) {
_setReadMarkerFuture = null;
})
// #Pangea
.catchError((e, s) {
ErrorHandler.logError(
e: PangeaWarningError("Failed to set read marker: $e"),
s: s,
data: {
'eventId': eventId,
'roomId': roomId,
},
);
Sentry.captureException(
e,
stackTrace: s,
withScope: (scope) {
scope.setTag('where', 'setReadMarker');
},
);
});
// Pangea#
if (eventId == null || eventId == timeline.room.lastEvent?.eventId) {
Matrix.of(context).backgroundPush?.cancelNotification(roomId);
}
}
@override
void dispose() {
timeline?.cancelSubscriptions();
timeline = null;
inputFocus.removeListener(_inputFocusListener);
onFocusSub?.cancel();
//#Pangea
choreographer.stateStream.close();
choreographer.dispose();
MatrixState.pAnyState.closeAllOverlays(force: true);
showToolbarStream.close();
stopMediaStream.close();
_levelSubscription?.cancel();
_analyticsSubscription?.cancel();
_botAudioSubscription?.cancel();
_router.routeInformationProvider.removeListener(_onRouteChanged);
carouselController.dispose();
TokensUtil.clearNewTokenCache();
//Pangea#
super.dispose();
}
// #Pangea
@override
void didChangeDependencies() {
super.didChangeDependencies();
_router = GoRouter.of(context);
_router.routeInformationProvider.addListener(_onRouteChanged);
if (room.isSpace && _router.state.path == ":roomid") {
ErrorHandler.logError(
e: "Space chat opened",
s: StackTrace.current,
data: {"roomId": roomId},
);
context.go("/rooms");
}
}
void _onRouteChanged() {
if (!stopMediaStream.isClosed) {
stopMediaStream.add(null);
}
MatrixState.pAnyState.closeAllOverlays();
}
// TextEditingController sendController = TextEditingController();
PangeaTextController get sendController => choreographer.textController;
// #Pangea
void setSendingClient(Client c) {
// first cancel typing with the old sending client
if (currentlyTyping) {
// no need to have the setting typing to false be blocking
typingCoolDown?.cancel();
typingCoolDown = null;
room.setTyping(false);
currentlyTyping = false;
}
// then cancel the old timeline
// fixes bug with read reciepts and quick switching
loadTimelineFuture = _getTimeline(eventContextId: room.fullyRead).onError(
ErrorReporter(
context,
'Unable to load timeline after changing sending Client',
).onErrorCallback,
);
// then set the new sending client
setState(() => sendingClient = c);
}
void setActiveClient(Client c) => setState(() {
Matrix.of(context).setActiveClient(c);
});
// #Pangea
Event? pangeaEditingEvent;
void clearEditingEvent() {
pangeaEditingEvent = null;
}
final List<String> _fakeEventIDs = [];
bool get obscureText => _fakeEventIDs.isNotEmpty;
/// Add a fake event to the timeline to visually indicate that a message is being sent.
/// Used when tokenizing after message send, specifically because tokenization for some
/// languages takes some time.
String? sendFakeMessage() {
if (sendController.text.trim().isEmpty) return null;
final eventID = room.sendFakeMessage(
text: sendController.text,
inReplyTo: replyEvent,
editEventId: editEvent?.eventId,
);
sendController.setSystemText("", EditType.other);
setState(() => _fakeEventIDs.add(eventID));
// wait for the next event to come through before clearing any fake event,
// to make the replacement look smooth
room.client.onTimelineEvent.stream
.firstWhere((event) => event.content[ModelKey.tempEventId] == eventID)
.then(
(_) => clearFakeEvent(eventID),
);
return eventID;
}
void clearFakeEvent(String? eventId) {
if (eventId == null) return;
final inTimeline = timeline != null &&
timeline!.events.any(
(e) => e.eventId == eventId,
);
if (!inTimeline) return;
timeline?.events.removeWhere((e) => e.eventId == eventId);
setState(() {
_fakeEventIDs.remove(eventId);
});
}
// Future<void> send() async {
// Original send function gets the tx id within the matrix lib,
// but for choero, the tx id is generated before the message send.
// Also, adding PangeaMessageData
Future<void> send({
required String message,
PangeaRepresentation? originalSent,
PangeaRepresentation? originalWritten,
PangeaMessageTokens? tokensSent,
PangeaMessageTokens? tokensWritten,
ChoreoRecord? choreo,
String? tempEventId,
}) async {
if (message.trim().isEmpty) return;
// if (sendController.text.trim().isEmpty) return;
// Pangea#
_storeInputTimeoutTimer?.cancel();
final prefs = await SharedPreferences.getInstance();
prefs.remove('draft_$roomId');
var parseCommands = true;
// #Pangea
// final commandMatch = RegExp(r'^\/(\w+)').firstMatch(sendController.text);
final commandMatch = RegExp(r'^\/(\w+)').firstMatch(message);
// Pangea#
if (commandMatch != null &&
!sendingClient.commands.keys.contains(commandMatch[1]!.toLowerCase())) {
// #Pangea
// final l10n = L10n.of(context);
// final dialogResult = await showOkCancelAlertDialog(
// context: context,
// title: l10n.commandInvalid,
// message: l10n.commandMissing(commandMatch[0]!),
// okLabel: l10n.sendAsText,
// cancelLabel: l10n.cancel,
// );
// if (dialogResult == OkCancelResult.cancel) return;
// Pangea#
parseCommands = false;
}
// ignore: unawaited_futures
// #Pangea
// room.sendTextEvent(
// sendController.text,
// inReplyTo: replyEvent,
// editEventId: editEvent?.eventId,
// parseCommands: parseCommands,
// );
// If the message and the sendController text don't match, it's possible
// that there was a delay in tokenization before send, and the user started
// typing a new message. We don't want to erase that, so only reset the input
// bar text if the message is the same as the sendController text.
if (message == sendController.text) {
sendController.setSystemText("", EditType.other);
}
final previousEdit = editEvent;
room
.pangeaSendTextEvent(
message,
inReplyTo: replyEvent,
editEventId: editEvent?.eventId,
parseCommands: parseCommands,
originalSent: originalSent,
originalWritten: originalWritten,
tokensSent: tokensSent,
tokensWritten: tokensWritten,
choreo: choreo,
tempEventId: tempEventId,
)
.then(
(String? msgEventId) async {
// #Pangea
// There's a listen in my_analytics_controller that decides when to auto-update
// analytics based on when / how many messages the logged in user send. This
// stream sends the data for newly sent messages.
_sendMessageAnalytics(
msgEventId,
originalSent: originalSent,
tokensSent: tokensSent,
choreo: choreo,
);
if (previousEdit != null) {
pangeaEditingEvent = previousEdit;
}
final spaceCode = room.classCode;
if (spaceCode != null) {
GoogleAnalytics.sendMessage(
room.id,
spaceCode,
);
}
if (msgEventId == null) {
ErrorHandler.logError(
e: Exception('msgEventId is null'),
s: StackTrace.current,
data: {
'roomId': roomId,
'text': message,
'inReplyTo': replyEvent?.eventId,
'editEventId': editEvent?.eventId,
},
);
return;
}
},
).catchError((err, s) {
clearFakeEvent(tempEventId);
if (err is EventTooLarge) {
showAdaptiveDialog(
context: context,
builder: (context) => const EventTooLargeDialog(),
);
return;
}
ErrorHandler.logError(
e: err,
s: s,
data: {
'roomId': roomId,
'text': message,
'inReplyTo': replyEvent?.eventId,
'editEventId': editEvent?.eventId,
},
);
});
// sendController.value = TextEditingValue(
// text: pendingText,
// selection: const TextSelection.collapsed(offset: 0),
// );
setState(() {
// #Pangea
// sendController.text = pendingText;
// Pangea#
_inputTextIsEmpty = pendingText.isEmpty;
replyEvent = null;
editEvent = null;
pendingText = '';
});
}
void sendFileAction({FileSelectorType type = FileSelectorType.any}) async {
final files = await selectFiles(
context,
allowMultiple: true,
type: type,
);
if (files.isEmpty) return;
await showAdaptiveDialog(
context: context,
builder: (c) => SendFileDialog(
files: files,
room: room,
outerContext: context,
),
);
}
void sendImageFromClipBoard(Uint8List? image) async {
if (image == null) return;
await showAdaptiveDialog(
context: context,
builder: (c) => SendFileDialog(
files: [XFile.fromData(image)],
room: room,
outerContext: context,
),
);
}
void openCameraAction() async {
// Make sure the textfield is unfocused before opening the camera
FocusScope.of(context).requestFocus(FocusNode());
final file = await ImagePicker().pickImage(source: ImageSource.camera);
if (file == null) return;
await showAdaptiveDialog(
context: context,
builder: (c) => SendFileDialog(
files: [file],
room: room,
outerContext: context,
),
);
}
void openVideoCameraAction() async {
// Make sure the textfield is unfocused before opening the camera
FocusScope.of(context).requestFocus(FocusNode());
final file = await ImagePicker().pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(minutes: 1),
);
if (file == null) return;
await showAdaptiveDialog(
context: context,
builder: (c) => SendFileDialog(
files: [file],
room: room,
outerContext: context,
),
);
}
void voiceMessageAction() async {
// #Pangea
stopMediaStream.add(null);
// Pangea#
room.client.getConfig(); // Preload server file configuration.
final scaffoldMessenger = ScaffoldMessenger.of(context);
if (PlatformInfos.isAndroid) {
final info = await DeviceInfoPlugin().androidInfo;
if (info.version.sdkInt < 19) {
showOkAlertDialog(
context: context,
title: L10n.of(context).unsupportedAndroidVersion,
message: L10n.of(context).unsupportedAndroidVersionLong,
okLabel: L10n.of(context).close,
);
return;
}
}
// #Pangea
// if (await AudioRecorder().hasPermission() == false) return;
// Pangea#
final result = await showDialog<RecordingResult>(
context: context,
barrierDismissible: false,
builder: (c) => const RecordingDialog(),
);
if (result == null) return;
final audioFile = XFile(result.path);
final bytesResult = await showFutureLoadingDialog(
context: context,
future: audioFile.readAsBytes,
);
final bytes = bytesResult.result;
if (bytes == null) return;
final file = MatrixAudioFile(
bytes: bytes,
name: result.fileName ?? audioFile.path,
);
await room
.sendFileEvent(
file,
inReplyTo: replyEvent,
extraContent: {
'info': {
...file.info,
'duration': result.duration,
},
'org.matrix.msc3245.voice': {},
'org.matrix.msc1767.audio': {
'duration': result.duration,
'waveform': result.waveform,
},
},
// #Pangea
)
.then(_sendVoiceMessageAnalytics)
.catchError((e, s) {
ErrorHandler.logError(
e: e,
s: s,
data: {
'roomId': roomId,
'file': file.name,
'duration': result.duration,
'waveform': result.waveform,
},
);
scaffoldMessenger.showSnackBar(
SnackBar(
content: Text(
(e as Object).toLocalizedString(context),
),
),
);
return null;
});
// ).catchError((e) {
// scaffoldMessenger.showSnackBar(
// SnackBar(
// content: Text(
// (e as Object).toLocalizedString(context),
// ),
// ),
// );
// return null;
// });
// setState(() {
// replyEvent = null;
// });
if (mounted) setState(() => replyEvent = null);
// Pangea#
}
void hideEmojiPicker() {
// #Pangea
clearSelectedEvents();
// Pangea#
setState(() => showEmojiPicker = false);
}
// #Pangea
void hideOverlayEmojiPicker() {
MatrixState.pAnyState.closeOverlay();
setState(() => showEmojiPicker = false);
}
// Pangea
void emojiPickerAction() {
if (showEmojiPicker) {
inputFocus.requestFocus();
} else {
inputFocus.unfocus();
}
setState(() => showEmojiPicker = !showEmojiPicker);
}
void _inputFocusListener() {
if (showEmojiPicker && inputFocus.hasFocus) {
setState(() => showEmojiPicker = false);
}
}
void sendLocationAction() async {
await showAdaptiveDialog(
context: context,
builder: (c) => SendLocationDialog(room: room),
);
}
String _getSelectedEventString() {
var copyString = '';
if (selectedEvents.length == 1) {
return selectedEvents.first
.getDisplayEvent(timeline!)
.calcLocalizedBodyFallback(MatrixLocals(L10n.of(context)));
}
for (final event in selectedEvents) {
if (copyString.isNotEmpty) copyString += '\n\n';
copyString += event.getDisplayEvent(timeline!).calcLocalizedBodyFallback(
MatrixLocals(L10n.of(context)),
withSenderNamePrefix: true,
);
}
return copyString;
}
void copyEventsAction() {
Clipboard.setData(ClipboardData(text: _getSelectedEventString()));
setState(() {
showEmojiPicker = false;
// #Pangea
// selectedEvents.clear();
clearSelectedEvents();
// Pangea#
});
}
void reportEventAction() async {
final event = selectedEvents.single;
final score = await showModalActionPopup<int>(
context: context,
title: L10n.of(context).reportMessage,
message: L10n.of(context).howOffensiveIsThisContent,
cancelLabel: L10n.of(context).cancel,
actions: [
AdaptiveModalAction(
value: -100,
label: L10n.of(context).extremeOffensive,
),
AdaptiveModalAction(
value: -50,
label: L10n.of(context).offensive,
),
AdaptiveModalAction(
value: 0,
label: L10n.of(context).inoffensive,
),
],
);
if (score == null) return;
final reason = await showTextInputDialog(
context: context,
title: L10n.of(context).whyDoYouWantToReportThis,
okLabel: L10n.of(context).ok,
cancelLabel: L10n.of(context).cancel,
hintText: L10n.of(context).reason,
);
if (reason == null || reason.isEmpty) return;
final result = await showFutureLoadingDialog(
context: context,
future: () => Matrix.of(context).client.reportEvent(
event.roomId!,
event.eventId,
reason: reason,
score: score,
),
);
if (result.error != null) return;
setState(() {
showEmojiPicker = false;
selectedEvents.clear();
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(L10n.of(context).contentHasBeenReported)),
);
}
void deleteErrorEventsAction() async {
try {
if (selectedEvents.any((event) => event.status != EventStatus.error)) {
throw Exception(
'Tried to delete failed to send events but one event is not failed to sent',
);
}
for (final event in selectedEvents) {
await event.cancelSend();
}
// #Pangea
// setState(selectedEvents.clear);
clearSelectedEvents();
// Pangea#
} catch (e, s) {
ErrorReporter(
context,
'Error while delete error events action',
).onErrorCallback(e, s);
}
}
void redactEventsAction() async {
final reasonInput = selectedEvents.any((event) => event.status.isSent)
? await showTextInputDialog(
context: context,
title: L10n.of(context).redactMessage,
message: L10n.of(context).redactMessageDescription,
isDestructive: true,
hintText: L10n.of(context).optionalRedactReason,
// #Pangea
maxLength: 255,
// Pangea#
okLabel: L10n.of(context).remove,
cancelLabel: L10n.of(context).cancel,
// #Pangea
autoSubmit: true,
// Pangea#
)
: null;
// #Pangea
// if (reasonInput == null) return;
if (reasonInput == null) {
clearSelectedEvents();
return;
}
// Pangea#
final reason = reasonInput.isEmpty ? null : reasonInput;
for (final event in selectedEvents) {
await showFutureLoadingDialog(
context: context,
future: () async {
if (event.status.isSent) {
if (event.canRedact) {
// #Pangea
// https://github.com/pangeachat/client/issues/3353
if (room.pinnedEventIds.contains(event.eventId) &&
room.canChangeStateEvent(EventTypes.RoomPinnedEvents)) {
final pinnedEvents = room.pinnedEventIds
.where((e) => e != event.eventId)
.toList();
await room.setPinnedEvents(pinnedEvents);
}
// Pangea#
await event.redactEvent(reason: reason);
} else {
final client = currentRoomBundle.firstWhere(
(cl) => selectedEvents.first.senderId == cl!.userID,
orElse: () => null,
);
if (client == null) {
return;
}
final room = client.getRoomById(roomId)!;
await Event.fromJson(event.toJson(), room).redactEvent(
reason: reason,
);
}
} else {
await event.cancelSend();
}
},
);
}
// #Pangea
clearSelectedEvents();
// Pangea#
setState(() {
showEmojiPicker = false;
selectedEvents.clear();
});
}
List<Client?> get currentRoomBundle {
final clients = Matrix.of(context).currentBundle!;
clients.removeWhere((c) => c!.getRoomById(roomId) == null);
return clients;
}
bool get canRedactSelectedEvents {
if (isArchived) return false;
final clients = Matrix.of(context).currentBundle;
for (final event in selectedEvents) {
if (!event.status.isSent) return false;
if (event.canRedact == false &&
!(clients!.any((cl) => event.senderId == cl!.userID))) {
return false;
}
}
return true;
}
bool get canPinSelectedEvents {
if (isArchived ||
!room.canChangeStateEvent(EventTypes.RoomPinnedEvents) ||
selectedEvents.length != 1 ||
!selectedEvents.single.status.isSent) {
return false;
}
return true;
}
bool get canEditSelectedEvents {
if (isArchived ||
selectedEvents.length != 1 ||
!selectedEvents.first.status.isSent) {
return false;
}
return currentRoomBundle
.any((cl) => selectedEvents.first.senderId == cl!.userID);
}
void forwardEventsAction() async {
if (selectedEvents.isEmpty) return;
final timeline = this.timeline;
if (timeline == null) return;
final forwardEvents = List<Event>.from(selectedEvents)
.map((event) => event.getDisplayEvent(timeline))
.toList();
await showScaffoldDialog(
context: context,
builder: (context) => ShareScaffoldDialog(
items: forwardEvents
// #Pangea
// .map((event) => ContentShareItem(event.content))
// .toList(),
.map((event) {
final content = Map<String, dynamic>.from(event.content);
content.remove("m.relates_to");
return ContentShareItem(content);
}).toList(),
// Pangea#
),
);
if (!mounted) return;
// #Pangea
// see https://github.com/pangeachat/client/issues/2536
// setState(() => selectedEvents.clear());
// Pangea#
}
void sendAgainAction() {
// #Pangea
if (selectedEvents.isEmpty) {
ErrorHandler.logError(
e: "No selected events in send again action",
s: StackTrace.current,
data: {"roomId": roomId},
);
clearSelectedEvents();
return;
}
// Pangea#
final event = selectedEvents.first;
// #Pangea
clearSelectedEvents();
// Pangea#
if (event.status.isError) {
event.sendAgain();
}
final allEditEvents = event
.aggregatedEvents(timeline!, RelationshipTypes.edit)
.where((e) => e.status.isError);
for (final e in allEditEvents) {
e.sendAgain();
}
setState(() => selectedEvents.clear());
}
void replyAction({Event? replyTo}) {
setState(() {
replyEvent = replyTo ?? selectedEvents.first;
selectedEvents.clear();
});
// #Pangea
clearSelectedEvents();
// Pangea
inputFocus.requestFocus();
}
void scrollToEventId(
String eventId, {
bool highlightEvent = true,
}) async {
final foundEvent =
timeline!.events.firstWhereOrNull((event) => event.eventId == eventId);
final eventIndex = foundEvent == null
? -1
: timeline!.events
.filterByVisibleInGui(exceptionEventId: eventId)
.indexOf(foundEvent);
if (eventIndex == -1) {
setState(() {
timeline = null;
_scrolledUp = false;
loadTimelineFuture = _getTimeline(eventContextId: eventId).onError(
ErrorReporter(context, 'Unable to load timeline after scroll to ID')
.onErrorCallback,
);
});
await loadTimelineFuture;
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
scrollToEventId(eventId);
});
return;
}
if (highlightEvent) {
setState(() {
scrollToEventIdMarker = eventId;
});
}
await scrollController.scrollToIndex(
eventIndex + 1,
duration: FluffyThemes.animationDuration,
preferPosition: AutoScrollPosition.middle,
);
_updateScrollController();
}
void scrollDown() async {
if (!timeline!.allowNewEvent) {
setState(() {
timeline = null;
_scrolledUp = false;
loadTimelineFuture = _getTimeline().onError(
ErrorReporter(context, 'Unable to load timeline after scroll down')
.onErrorCallback,
);
});
await loadTimelineFuture;
}
scrollController.jumpTo(0);
}
void onEmojiSelected(_, Emoji? emoji) {
typeEmoji(emoji);
onInputBarChanged(sendController.text);
}
void typeEmoji(Emoji? emoji) {
if (emoji == null) return;
final text = sendController.text;
// #Pangea
if (!sendController.selection.isValid) {
sendController.value = TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: text.length),
);
}
// Pangea#
final selection = sendController.selection;
final newText = sendController.text.isEmpty
? emoji.emoji
: text.replaceRange(selection.start, selection.end, emoji.emoji);
sendController.value = TextEditingValue(
text: newText,
selection: TextSelection.collapsed(
// don't forget an UTF-8 combined emoji might have a length > 1
offset: selection.baseOffset + emoji.emoji.length,
),
);
}
void emojiPickerBackspace() {
sendController
..text = sendController.text.characters.skipLast(1).toString()
..selection = TextSelection.fromPosition(
TextPosition(offset: sendController.text.length),
);
}
// #Pangea
// void clearSelectedEvents() => setState(() {
// selectedEvents.clear();
// showEmojiPicker = false;
// });
void clearSelectedEvents() {
if (!mounted) return;
setState(() {
MatrixState.pAnyState.closeAllOverlays();
selectedEvents.clear();
showEmojiPicker = false;
});
}
void setSelectedEvent(Event event) {
setState(() {
selectedEvents.clear();
selectedEvents.add(event);
});
}
void clearSingleSelectedEvent() {
if (selectedEvents.length <= 1) {
clearSelectedEvents();
}
}
void editSelectedEventAction() {
final client = currentRoomBundle.firstWhere(
(cl) => selectedEvents.first.senderId == cl!.userID,
orElse: () => null,
);
if (client == null) {
return;
}
setSendingClient(client);
setState(() {
pendingText = sendController.text;
editEvent = selectedEvents.first;
sendController.text =
editEvent!.getDisplayEvent(timeline!).calcLocalizedBodyFallback(
MatrixLocals(L10n.of(context)),
withSenderNamePrefix: false,
hideReply: true,
);
selectedEvents.clear();
});
inputFocus.requestFocus();
}
void goToNewRoomAction() async {
final newRoomId = room
.getState(EventTypes.RoomTombstone)!
.parsedTombstoneContent
.replacementRoom;
final result = await showFutureLoadingDialog(
context: context,
future: () => room.client.joinRoom(
room
.getState(EventTypes.RoomTombstone)!
.parsedTombstoneContent
.replacementRoom,
via: [newRoomId.domain!],
),
);
if (result.error != null) return;
if (!mounted) return;
context.go('/rooms/${result.result!}');
await showFutureLoadingDialog(
context: context,
future: room.leave,
);
}
void onSelectMessage(Event event) {
// #Pangea
if (choreographer.itController.willOpen) {
return;
}
// Pangea#
if (!event.redacted) {
// #Pangea
// if (selectedEvents.contains(event)) {
// setState(
// () => selectedEvents.remove(event),
// );
// }
// If delete first selected event with the selected eventID
final matches = selectedEvents.where((e) => e.eventId == event.eventId);
if (matches.isNotEmpty) {
setState(() => selectedEvents.remove(matches.first));
// Pangea#
} else {
setState(
() => selectedEvents.add(event),
);
}
selectedEvents.sort(
(a, b) => a.originServerTs.compareTo(b.originServerTs),
);
}
}
int? findChildIndexCallback(Key key, Map<String, int> thisEventsKeyMap) {
// this method is called very often. As such, it has to be optimized for speed.
if (key is! ValueKey) {
return null;
}
final eventId = key.value;
if (eventId is! String) {
return null;
}
// first fetch the last index the event was at
final index = thisEventsKeyMap[eventId];
if (index == null) {
return null;
}
// we need to +1 as 0 is the typing thing at the bottom
return index + 1;
}
// #Pangea
void onInputBarSubmitted(String _, BuildContext context) {
// void onInputBarSubmitted(_) {
// send();
choreographer.send(context);
// Pangea#
FocusScope.of(context).requestFocus(inputFocus);
}
void onAddPopupMenuButtonSelected(String choice) {
room.client.getConfig(); // Preload server file configuration.
if (choice == 'file') {
sendFileAction();
}
if (choice == 'image') {
sendFileAction(type: FileSelectorType.images);
}
if (choice == 'video') {
sendFileAction(type: FileSelectorType.videos);
}
if (choice == 'camera') {
openCameraAction();
}
if (choice == 'camera-video') {
openVideoCameraAction();
}
if (choice == 'location') {
sendLocationAction();
}
}
unpinEvent(String eventId) async {
final response = await showOkCancelAlertDialog(
context: context,
title: L10n.of(context).unpin,
// #Pangea
// message: L10n.of(context).confirmEventUnpin,
message: L10n.of(context).confirmMessageUnpin,
// Pangea#
okLabel: L10n.of(context).unpin,
cancelLabel: L10n.of(context).cancel,
);
if (response == OkCancelResult.ok) {
final events = room.pinnedEventIds
..removeWhere((oldEvent) => oldEvent == eventId);
// #Pangea
if (scrollToEventIdMarker == eventId) {
setState(() {
scrollToEventIdMarker = null;
});
}
// Pangea#
showFutureLoadingDialog(
context: context,
future: () => room.setPinnedEvents(events),
);
}
}
// #Pangea
// void pinEvent() {
Future<void> pinEvent() async {
// Pangea#
final pinnedEventIds = room.pinnedEventIds;
final selectedEventIds = selectedEvents.map((e) => e.eventId).toSet();
final unpin = selectedEventIds.length == 1 &&
pinnedEventIds.contains(selectedEventIds.single);
if (unpin) {
// #Pangea
//pinnedEventIds.removeWhere(selectedEventIds.contains);
unpinEvent(selectedEventIds.single);
// Pangea#
} else {
pinnedEventIds.addAll(selectedEventIds);
}
// #Pangea
// showFutureLoadingDialog(
// context: context,
// future: () => room.setPinnedEvents(pinnedEventIds),
// );
await showFutureLoadingDialog(
context: context,
future: () => room.setPinnedEvents(pinnedEventIds),
);
clearSelectedEvents();
// Pangea#
}
Timer? _storeInputTimeoutTimer;
static const Duration _storeInputTimeout = Duration(milliseconds: 500);
void onInputBarChanged(String text) {
if (_inputTextIsEmpty != text.isEmpty) {
setState(() {
_inputTextIsEmpty = text.isEmpty;
});
}
_storeInputTimeoutTimer?.cancel();
_storeInputTimeoutTimer = Timer(_storeInputTimeout, () async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('draft_$roomId', text);
});
if (text.endsWith(' ') && Matrix.of(context).hasComplexBundles) {
final clients = currentRoomBundle;
for (final client in clients) {
final prefix = client!.sendPrefix;
if ((prefix.isNotEmpty) &&
text.toLowerCase() == '${prefix.toLowerCase()} ') {
setSendingClient(client);
setState(() {
sendController.clear();
});
return;
}
}
}
if (AppConfig.sendTypingNotifications) {
typingCoolDown?.cancel();
typingCoolDown = Timer(const Duration(seconds: 2), () {
typingCoolDown = null;
currentlyTyping = false;
room.setTyping(false);
});
typingTimeout ??= Timer(const Duration(seconds: 30), () {
typingTimeout = null;
currentlyTyping = false;
});
if (!currentlyTyping) {
currentlyTyping = true;
room.setTyping(
true,
timeout: const Duration(seconds: 30).inMilliseconds,
);
}
}
}
bool _inputTextIsEmpty = true;
bool get isArchived =>
{Membership.leave, Membership.ban}.contains(room.membership);
// #Pangea
// void showEventInfo([Event? event]) =>
// (event ?? selectedEvents.single).showInfoDialog(context);
void showEventInfo([Event? event]) {
(event ?? selectedEvents.single).showInfoDialog(context);
clearSelectedEvents();
}
// Pangea#
void onPhoneButtonTap() async {
// VoIP required Android SDK 21
if (PlatformInfos.isAndroid) {
DeviceInfoPlugin().androidInfo.then((value) {
if (value.version.sdkInt < 21) {
Navigator.pop(context);
showOkAlertDialog(
context: context,
title: L10n.of(context).unsupportedAndroidVersion,
message: L10n.of(context).unsupportedAndroidVersionLong,
okLabel: L10n.of(context).close,
);
}
});
}
final callType = await showModalActionPopup<CallType>(
context: context,
title: L10n.of(context).warning,
message: L10n.of(context).videoCallsBetaWarning,
cancelLabel: L10n.of(context).cancel,
actions: [
AdaptiveModalAction(
label: L10n.of(context).voiceCall,
icon: const Icon(Icons.phone_outlined),
value: CallType.kVoice,
),
AdaptiveModalAction(
label: L10n.of(context).videoCall,
icon: const Icon(Icons.video_call_outlined),
value: CallType.kVideo,
),
],
);
if (callType == null) return;
final voipPlugin = Matrix.of(context).voipPlugin;
try {
await voipPlugin!.voip.inviteToCall(room, callType);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(e.toLocalizedString(context))),
);
}
}
void cancelReplyEventAction() => setState(() {
if (editEvent != null) {
// #Pangea
// sendController.text = pendingText;
sendController.setSystemText(pendingText, EditType.other);
// Pangea#
pendingText = '';
}
replyEvent = null;
editEvent = null;
});
// #Pangea
String? get buttonEventID => timeline!.events
.firstWhereOrNull(
(event) =>
event.isVisibleInGui &&
event.senderId != room.client.userID &&
!event.redacted,
)
?.eventId;
final StreamController<String> showToolbarStream =
StreamController.broadcast();
final StreamController<void> stopMediaStream = StreamController.broadcast();
void showToolbar(
Event event, {
PangeaMessageEvent? pangeaMessageEvent,
PangeaToken? selectedToken,
MessageMode? mode,
Event? nextEvent,
Event? prevEvent,
}) {
if (event.redacted || event.status == EventStatus.sending) return;
// Close keyboard, if open
if (inputFocus.hasFocus && PlatformInfos.isMobile) {
inputFocus.unfocus();
return;
}
// Close emoji picker, if open
if (showEmojiPicker) {
hideEmojiPicker();
return;
}
// Check if the user has set their languages. If not, prompt them to do so.
if (!MatrixState.pangeaController.languageController.languagesSet) {
pLanguageDialog(context, () {});
return;
}
Widget? overlayEntry;
try {
overlayEntry = MessageSelectionOverlay(
chatController: this,
event: event,
timeline: timeline!,
initialSelectedToken: selectedToken,
nextEvent: nextEvent,
prevEvent: prevEvent,
);
} catch (err) {
debugger(when: kDebugMode);
ErrorHandler.logError(
e: err,
s: StackTrace.current,
data: {
'roomId': roomId,
'event': event.toJson(),
'selectedToken': selectedToken?.toJson(),
'nextEvent': nextEvent?.toJson(),
'prevEvent': prevEvent?.toJson(),
},
);
return;
}
// you've clicked a message so lets turn this off
InstructionsEnum.clickMessage.setToggledOff(true);
showToolbarStream.add(event.eventId);
if (!kIsWeb) {
HapticFeedback.mediumImpact();
}
stopMediaStream.add(null);
Future.delayed(
Duration(milliseconds: buttonEventID == event.eventId ? 200 : 0), () {
if (_router.state.path != ':roomid') {
// The user has navigated away from the chat,
// so we don't want to show the overlay.
return;
}
OverlayUtil.showOverlay(
context: context,
child: overlayEntry!,
position: OverlayPositionEnum.centered,
onDismiss: clearSelectedEvents,
blurBackground: true,
backgroundColor: Colors.black,
);
// select the message
onSelectMessage(event);
});
}
double inputBarHeight = 64;
void updateInputBarHeight(double height) {
if (mounted && height != inputBarHeight) {
setState(() => inputBarHeight = height);
}
}
bool get displayChatDetailsColumn {
try {
return _displayChatDetailsColumn.value;
} catch (e) {
// if not set, default to false
return false;
}
}
void _sendMessageAnalytics(
String? eventId, {
PangeaRepresentation? originalSent,
PangeaMessageTokens? tokensSent,
ChoreoRecord? choreo,
}) {
// There's a listen in my_analytics_controller that decides when to auto-update
// analytics based on when / how many messages the logged in user send. This
// stream sends the data for newly sent messages.
if (originalSent?.langCode.split("-").first !=
choreographer.l2Lang?.langCodeShort) {
return;
}
final metadata = ConstructUseMetaData(
roomId: roomId,
timeStamp: DateTime.now(),
eventId: eventId,
);
if (eventId != null && originalSent != null && tokensSent != null) {
final List<OneConstructUse> constructs = [
...originalSent.vocabAndMorphUses(
choreo: choreo,
tokens: tokensSent.tokens,
metadata: metadata,
),
];
_showAnalyticsFeedback(constructs, eventId);
pangeaController.putAnalytics.setState(
AnalyticsStream(
eventId: eventId,
targetID: eventId,
roomId: room.id,
constructs: constructs,
),
);
}
}
Future<void> _sendVoiceMessageAnalytics(String? eventId) async {
if (eventId == null) {
ErrorHandler.logError(
e: Exception('eventID null in voiceMessageAction'),
s: StackTrace.current,
data: {
'roomId': roomId,
},
);
return;
}
final event = await room.getEventById(eventId);
if (event == null) {
ErrorHandler.logError(
e: Exception('Event not found after sending voice message'),
s: StackTrace.current,
data: {
'roomId': roomId,
},
);
return;
}
try {
final messageEvent = PangeaMessageEvent(
event: event,
timeline: timeline!,
ownMessage: true,
);
final stt = await messageEvent.getSpeechToText(
choreographer.l1Lang?.langCodeShort ?? LanguageKeys.unknownLanguage,
choreographer.l2Lang?.langCodeShort ?? LanguageKeys.unknownLanguage,
);
if (stt == null || stt.transcript.sttTokens.isEmpty) return;
final constructs = stt.constructs(roomId, eventId);
if (constructs.isEmpty) return;
_showAnalyticsFeedback(constructs, eventId);
MatrixState.pangeaController.putAnalytics.setState(
AnalyticsStream(
eventId: eventId,
targetID: eventId,
roomId: room.id,
constructs: constructs,
),
);
} catch (e, s) {
ErrorHandler.logError(
e: e,
s: s,
data: {
'roomId': roomId,
'eventId': eventId,
},
);
}
}
bool get shouldShowLanguageMismatchPopup {
if (!LanguageMismatchRepo.shouldShow) {
return false;
}
final l1 = choreographer.l1Lang?.langCodeShort;
final l2 = choreographer.l2Lang?.langCodeShort;
final activityLang = room.activityPlan?.req.targetLanguage.split('-').first;
return activityLang != null &&
l2 != null &&
l2 != activityLang &&
l1 != activityLang;
}
Future<void> showLanguageMismatchPopup() async {
if (!shouldShowLanguageMismatchPopup) {
return;
}
final targetLanguage = room.activityPlan!.req.targetLanguage;
LanguageMismatchRepo.set();
OverlayUtil.showPositionedCard(
context: context,
cardToShow: LanguageMismatchPopup(
targetLanguage: targetLanguage,
choreographer: choreographer,
onUpdate: () async {
await choreographer.getLanguageHelp(manual: true);
final matches = choreographer.igc.igcTextData?.matches;
if (matches?.isNotEmpty == true) {
choreographer.igc.showFirstMatch(context);
}
},
),
maxHeight: 325,
maxWidth: 325,
transformTargetId: choreographer.inputTransformTargetKey,
);
}
void _showAnalyticsFeedback(
List<OneConstructUse> constructs,
String eventId,
) {
final newGrammarConstructs =
pangeaController.getAnalytics.newConstructCount(
constructs,
ConstructTypeEnum.morph,
);
final newVocabConstructs = pangeaController.getAnalytics.newConstructCount(
constructs,
ConstructTypeEnum.vocab,
);
OverlayUtil.showOverlay(
overlayKey: "msg_analytics_feedback_$eventId",
followerAnchor: Alignment.bottomRight,
targetAnchor: Alignment.topRight,
context: context,
child: MessageAnalyticsFeedback(
overlayId: "msg_analytics_feedback_$eventId",
newGrammarConstructs: newGrammarConstructs,
newVocabConstructs: newVocabConstructs,
),
transformTargetId: eventId,
ignorePointer: true,
closePrevOverlay: false,
);
}
final ScrollController carouselController = ScrollController();
ActivityRoleModel? highlightedRole;
void highlightRole(ActivityRoleModel role) {
if (mounted) setState(() => highlightedRole = role);
}
bool showInstructions = false;
void toggleShowInstructions() {
if (mounted) setState(() => showInstructions = !showInstructions);
}
bool showActivityDropdown = false;
void setShowDropdown(bool show) async {
setState(() => showActivityDropdown = show);
}
bool hasRainedConfetti = false;
void setHasRainedConfetti(bool show) {
if (mounted) {
setState(() => hasRainedConfetti = show);
}
}
// Pangea#
late final ValueNotifier<bool> _displayChatDetailsColumn;
void toggleDisplayChatDetailsColumn() async {
await AppSettings.displayChatDetailsColumn.setItem(
Matrix.of(context).store,
!_displayChatDetailsColumn.value,
);
_displayChatDetailsColumn.value = !_displayChatDetailsColumn.value;
}
@override
Widget build(BuildContext context) {
// #Pangea
return LoadParticipantsBuilder(
room: room,
builder: (context, participants) {
if (!room.participantListComplete && participants.loading) {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
}
if (room.isActivitySession && !room.isActivityStarted) {
return ActivitySessionStartPage(
activityId: room.activityId!,
roomId: room.id,
parentId: room.courseParent?.id,
);
}
// Pangea#
final theme = Theme.of(context);
return Row(
children: [
Expanded(
child: ChatView(this),
),
ValueListenableBuilder(
valueListenable: _displayChatDetailsColumn,
builder: (context, displayChatDetailsColumn, _) =>
!FluffyThemes.isThreeColumnMode(context) ||
room.membership != Membership.join ||
!displayChatDetailsColumn
? const SizedBox(
height: double.infinity,
width: 0,
)
: Container(
width: FluffyThemes.columnWidth,
clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(
border: Border(
left: BorderSide(
width: 1,
color: theme.dividerColor,
),
),
),
child: ChatDetails(
roomId: roomId,
embeddedCloseButton: IconButton(
icon: const Icon(Icons.close),
onPressed: toggleDisplayChatDetailsColumn,
),
),
),
),
],
);
},
);
}
}