author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
129,187
06.08.2020 17:57:58
14,400
56edfcf6be7384d94c64fe8307d73a5a8efe5ae8
[server] Don't return threadInfo[s] from thread responders
[ { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -262,8 +262,8 @@ export type RoleChangeRequest = {|\n|};\nexport type ChangeThreadSettingsResult = {|\n- threadInfo: RawThreadInfo,\n- threadInfos: { [id: string]: RawThreadInfo },\n+ threadInfo?: RawThreadInfo,\n+ threadInfos?: { [id: string]: RawThreadInfo },\nupdatesResult: {\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n},\n@@ -282,7 +282,7 @@ export type LeaveThreadRequest = {|\nthreadID: string,\n|};\nexport type LeaveThreadResult = {|\n- threadInfos: { [id: string]: RawThreadInfo },\n+ threadInfos?: { [id: string]: RawThreadInfo },\nupdatesResult: {\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n},\n@@ -334,7 +334,7 @@ export type ClientThreadJoinRequest = {|\ncalendarQuery: CalendarQuery,\n|};\nexport type ThreadJoinResult = {|\n- threadInfos: { [id: string]: RawThreadInfo },\n+ threadInfos?: { [id: string]: RawThreadInfo },\nupdatesResult: {\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n},\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/thread-deleters.js", "new_path": "server/src/deleters/thread-deleters.js", "diff": "@@ -12,6 +12,7 @@ import bcrypt from 'twin-bcrypt';\nimport { ServerError } from 'lib/utils/errors';\nimport { permissionLookup } from 'lib/permissions/thread-permissions';\n+import { hasMinCodeVersion } from 'lib/shared/version-utils';\nimport { dbQuery, SQL } from '../database';\nimport {\n@@ -45,16 +46,17 @@ async function deleteThread(\nif (!permissionsBlob) {\n// This should only occur if the first request goes through but the client\n// never receives the response\n- const [{ threadInfos }, { updateInfos }] = await Promise.all([\n- fetchThreadInfos(viewer),\n+ const [{ updateInfos }, fetchThreadInfoResult] = await Promise.all([\nfetchUpdateInfoForThreadDeletion(viewer, threadID),\n+ hasMinCodeVersion(viewer.platformDetails, 62)\n+ ? undefined\n+ : fetchThreadInfos(viewer),\n]);\n- return {\n- threadInfos,\n- updatesResult: {\n- newUpdates: updateInfos,\n- },\n- };\n+ if (fetchThreadInfoResult) {\n+ const { threadInfos } = fetchThreadInfoResult;\n+ return { threadInfos, updatesResult: { newUpdates: updateInfos } };\n+ }\n+ return { updatesResult: { newUpdates: updateInfos } };\n}\nconst hasPermission = permissionLookup(\n@@ -120,6 +122,10 @@ async function deleteThread(\ndbQuery(query),\n]);\n+ if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ return { updatesResult: { newUpdates: viewerUpdates } };\n+ }\n+\nconst { threadInfos } = await fetchThreadInfos(viewer);\nreturn {\nthreadInfos,\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -24,6 +24,7 @@ import { ServerError } from 'lib/utils/errors';\nimport { promiseAll } from 'lib/utils/promises';\nimport { permissionLookup } from 'lib/permissions/thread-permissions';\nimport { filteredThreadIDs } from 'lib/selectors/calendar-filter-selectors';\n+import { hasMinCodeVersion } from 'lib/shared/version-utils';\nimport { dbQuery, SQL } from '../database';\nimport {\n@@ -108,6 +109,10 @@ async function updateRole(\ncommitMembershipChangeset(viewer, changeset),\n]);\n+ if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ return { updatesResult: { newUpdates: viewerUpdates }, newMessageInfos };\n+ }\n+\nreturn {\nthreadInfo: threadInfos[request.threadID],\nthreadInfos,\n@@ -190,6 +195,10 @@ async function removeMembers(\ncommitMembershipChangeset(viewer, changeset),\n]);\n+ if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ return { updatesResult: { newUpdates: viewerUpdates }, newMessageInfos };\n+ }\n+\nreturn {\nthreadInfo: threadInfos[request.threadID],\nthreadInfos,\n@@ -253,6 +262,10 @@ async function leaveThread(\ncreateMessages(viewer, [messageData]),\n]);\n+ if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ return { updatesResult: { newUpdates: viewerUpdates } };\n+ }\n+\nreturn {\nthreadInfos,\nupdatesResult: {\n@@ -520,6 +533,10 @@ async function updateThread(\n),\n]);\n+ if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ return { updatesResult: { newUpdates: viewerUpdates }, newMessageInfos };\n+ }\n+\nreturn {\nthreadInfo: threadInfos[request.threadID],\nthreadInfos,\n@@ -602,7 +619,6 @@ async function joinThread(\n}\nconst response: ThreadJoinResult = {\n- threadInfos: membershipResult.threadInfos,\nrawMessageInfos: fetchMessagesResult.rawMessageInfos,\ntruncationStatuses: fetchMessagesResult.truncationStatuses,\nuserInfos,\n@@ -610,6 +626,9 @@ async function joinThread(\nnewUpdates: membershipResult.viewerUpdates,\n},\n};\n+ if (!hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ response.threadInfos = membershipResult.threadInfos;\n+ }\nif (rawEntryInfos) {\nresponse.rawEntryInfos = rawEntryInfos;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Don't return threadInfo[s] from thread responders
129,187
06.08.2020 18:15:25
14,400
661f681ba859dd35069da5a7fc5e06a2e27a7bf6
Only return newThreadID instead of newThreadInfo on create_thread
[ { "change_type": "MODIFY", "old_path": "lib/actions/thread-actions.js", "new_path": "lib/actions/thread-actions.js", "diff": "@@ -110,7 +110,7 @@ async function newThread(\n): Promise<NewThreadResult> {\nconst response = await fetchJSON('create_thread', request);\nreturn {\n- newThreadInfo: response.newThreadInfo,\n+ newThreadID: response.newThreadID,\nupdatesResult: response.updatesResult,\nnewMessageInfos: response.newMessageInfos,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -545,7 +545,7 @@ function reduceMessageStore(\n) {\nreturn filterByNewThreadInfos(messageStore, newThreadInfos);\n} else if (action.type === newThreadActionTypes.success) {\n- const newThreadID = action.payload.newThreadInfo.id;\n+ const { newThreadID } = action.payload;\nconst truncationStatuses = {};\nfor (let messageInfo of action.payload.newMessageInfos) {\ntruncationStatuses[messageInfo.threadID] =\n" }, { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -317,12 +317,20 @@ export type NewThreadRequest = {|\nparentThreadID?: ?string,\ninitialMemberIDs?: ?$ReadOnlyArray<string>,\n|};\n+export type NewThreadResponse = {|\n+ updatesResult: {\n+ newUpdates: $ReadOnlyArray<UpdateInfo>,\n+ },\n+ newMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n+ newThreadInfo?: RawThreadInfo,\n+ newThreadID?: string,\n+|};\nexport type NewThreadResult = {|\n- newThreadInfo: RawThreadInfo,\nupdatesResult: {\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n},\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n+ newThreadID: string,\n|};\nexport type ServerThreadJoinRequest = {|\n" }, { "change_type": "MODIFY", "old_path": "server/src/bots/squadbot.js", "new_path": "server/src/bots/squadbot.js", "diff": "import { threadTypes } from 'lib/types/thread-types';\n+import invariant from 'invariant';\n+\nimport bots from 'lib/facts/bots';\nimport { createBotViewer } from '../session/bots';\n@@ -16,7 +18,12 @@ async function createSquadbotThread(userID: string): Promise<string> {\ninitialMemberIDs: [userID],\n};\nconst result = await createThread(squadbotViewer, newThreadRequest, true);\n- return result.newThreadInfo.id;\n+ const { newThreadID } = result;\n+ invariant(\n+ newThreadID,\n+ 'createThread should return newThreadID to bot viewer',\n+ );\n+ return newThreadID;\n}\nexport { createSquadbotThread };\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -9,6 +9,7 @@ import { threadTypes } from 'lib/types/thread-types';\nimport { messageTypes } from 'lib/types/message-types';\nimport bcrypt from 'twin-bcrypt';\n+import invariant from 'invariant';\nimport { validUsernameRegex, validEmailRegex } from 'lib/shared/account-utils';\nimport { ServerError } from 'lib/utils/errors';\n@@ -117,10 +118,18 @@ async function createAccount(\ntrue,\n),\n]);\n+ const ashoatThreadID = ashoatThreadResult.newThreadInfo\n+ ? ashoatThreadResult.newThreadInfo.id\n+ : ashoatThreadResult.newThreadID;\n+ invariant(\n+ ashoatThreadID,\n+ 'createThread should return either newThreadInfo or newThreadID',\n+ );\n+\nlet messageTime = Date.now();\nconst ashoatMessageDatas = ashoatMessages.map(message => ({\ntype: messageTypes.TEXT,\n- threadID: ashoatThreadResult.newThreadInfo.id,\n+ threadID: ashoatThreadID,\ncreatorID: ashoat.id,\ntime: messageTime++,\ntext: message,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "import {\ntype NewThreadRequest,\n- type NewThreadResult,\n+ type NewThreadResponse,\nthreadTypes,\nthreadPermissions,\n} from 'lib/types/thread-types';\n@@ -14,6 +14,7 @@ import invariant from 'invariant';\nimport { generateRandomColor } from 'lib/shared/thread-utils';\nimport { ServerError } from 'lib/utils/errors';\nimport { promiseAll } from 'lib/utils/promises';\n+import { hasMinCodeVersion } from 'lib/shared/version-utils';\nimport { dbQuery, SQL } from '../database';\nimport { checkThreadPermission } from '../fetchers/thread-fetchers';\n@@ -34,7 +35,7 @@ async function createThread(\nviewer: Viewer,\nrequest: NewThreadRequest,\ncreateRelationships?: boolean = false,\n-): Promise<NewThreadResult> {\n+): Promise<NewThreadResponse> {\nif (!viewer.loggedIn) {\nthrow new ServerError('not_logged_in');\n}\n@@ -205,6 +206,16 @@ async function createThread(\n]);\nconst { threadInfos, viewerUpdates } = commitResult;\n+ if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ return {\n+ newThreadID: id,\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n+ },\n+ newMessageInfos,\n+ };\n+ }\n+\nreturn {\nnewThreadInfo: threadInfos[id],\nupdatesResult: {\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/thread-responders.js", "new_path": "server/src/responders/thread-responders.js", "diff": "@@ -9,7 +9,7 @@ import {\ntype LeaveThreadResult,\ntype UpdateThreadRequest,\ntype NewThreadRequest,\n- type NewThreadResult,\n+ type NewThreadResponse,\ntype ServerThreadJoinRequest,\ntype ThreadJoinResult,\nassertThreadType,\n@@ -169,7 +169,7 @@ const newThreadRequestInputValidator = tShape({\nasync function threadCreationResponder(\nviewer: Viewer,\ninput: any,\n-): Promise<NewThreadResult> {\n+): Promise<NewThreadResponse> {\nawait validateInput(viewer, newThreadRequestInputValidator, input);\nlet request;\nif (\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -607,9 +607,9 @@ async function commitMembershipChangeset(\nupdateUndirectedRelationships(uniqueRelationshipRows),\n]);\n- // We fetch all threads here because clients still expect the full list of\n- // threads on most thread operations. We're in the process of switching them\n- // to just need the diff, but until then...\n+ // We fetch all threads here because old clients still expect the full list of\n+ // threads on most thread operations. Once verifyClientSupported gates on\n+ // codeVersion 62, we can add a WHERE clause on changedThreadIDs here\nconst serverThreadInfoFetchResult = await fetchServerThreadInfos();\nconst { threadInfos: serverThreadInfos } = serverThreadInfoFetchResult;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Only return newThreadID instead of newThreadInfo on create_thread
129,187
06.08.2020 18:17:04
14,400
1b524322c50c6b1a0edaf1474d1322d934bf4e00
[native] codeVersion -> 62 Probably won't actually release this one. I'm just bumping the `codeVersion` so the previous commit works as intended. Otherwise the server will think the client is an old v61 client and not return `newThreadID`, which will confuse the new client.
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -133,8 +133,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 61\n- versionName \"0.0.61\"\n+ versionCode 62\n+ versionName \"0.0.62\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.61</string>\n+ <string>0.0.62</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>61</string>\n+ <string>62</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.61</string>\n+ <string>0.0.62</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>61</string>\n+ <string>62</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -175,7 +175,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 61;\n+const codeVersion = 62;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 62 Probably won't actually release this one. I'm just bumping the `codeVersion` so the previous commit works as intended. Otherwise the server will think the client is an old v61 client and not return `newThreadID`, which will confuse the new client.
129,187
07.08.2020 12:27:30
14,400
d4fd188c7732ed22caaab09f1e32d72444c3e51b
[lib] Pass whole capture object to SharedMarkdown.jsonPrint
[ { "change_type": "MODIFY", "old_path": "lib/shared/markdown.js", "new_path": "lib/shared/markdown.js", "diff": "@@ -17,7 +17,11 @@ const blockQuoteStripFollowingNewlineRegex = /^( *>[^\\n]+(?:\\n[^\\n]+)*)(?:\\n|$){\nconst urlRegex = /^(https?:\\/\\/[^\\s<]+[^<.,:;\"')\\]\\s])/i;\n-function jsonMatch(source: string) {\n+type JSONCapture = {|\n+ +[0]: string,\n+ +json: Object,\n+|};\n+function jsonMatch(source: string): ?JSONCapture {\nif (!source.startsWith('{')) {\nreturn null;\n}\n@@ -56,8 +60,8 @@ function jsonMatch(source: string) {\n};\n}\n-function jsonPrint(json: Object): string {\n- return JSON.stringify(json, null, ' ');\n+function jsonPrint(capture: JSONCapture): string {\n+ return JSON.stringify(capture.json, null, ' ');\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "native/markdown/rules.react.js", "new_path": "native/markdown/rules.react.js", "diff": "@@ -302,7 +302,7 @@ function fullMarkdownRules(\n},\nparse: (capture: SimpleMarkdown.Capture) => ({\ntype: 'codeBlock',\n- content: SharedMarkdown.jsonPrint(capture.json),\n+ content: SharedMarkdown.jsonPrint(capture),\n}),\n},\n};\n" }, { "change_type": "MODIFY", "old_path": "web/markdown/rules.react.js", "new_path": "web/markdown/rules.react.js", "diff": "@@ -120,7 +120,7 @@ function markdownRules(): MarkdownRuleSpec {\n},\nparse: (capture: SimpleMarkdown.Capture) => ({\ntype: 'codeBlock',\n- content: SharedMarkdown.jsonPrint(capture.json),\n+ content: SharedMarkdown.jsonPrint(capture),\n}),\n},\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Pass whole capture object to SharedMarkdown.jsonPrint
129,187
07.08.2020 12:33:07
14,400
b3d1c20b730885938c5d786fe982a95107ed7c91
Adjust margin for Markdown blockQuote and codeBlock
[ { "change_type": "MODIFY", "old_path": "native/markdown/styles.js", "new_path": "native/markdown/styles.js", "diff": "@@ -65,12 +65,13 @@ const unboundStyles = {\nborderLeftWidth: 5,\npadding: 10,\nmarginBottom: 6,\n+ marginVertical: 6,\n},\ncodeBlock: {\nbackgroundColor: 'codeBackground',\npadding: 10,\nborderRadius: 5,\n- marginBottom: 6,\n+ marginVertical: 6,\n},\ncodeBlockText: {\nfontFamily: Platform.select({\n" }, { "change_type": "MODIFY", "old_path": "web/markdown/markdown.css", "new_path": "web/markdown/markdown.css", "diff": "@@ -17,6 +17,7 @@ div.markdown blockquote {\nmargin: 0 0 6px 0;\nbox-sizing: border-box;\nwidth: 100%;\n+ margin: 6px 0;\n}\ndiv.darkBackground blockquote {\nbackground: #A9A9A9;\n@@ -44,6 +45,7 @@ div.darkBackground code {\ndiv.markdown pre {\npadding: .5em 10px;\nborder-radius: 5px;\n+ margin: 6px 0;\n}\ndiv.lightBackground pre {\nbackground: #DCDCDC;\n@@ -58,6 +60,5 @@ div.markdown pre > code {\ndisplay: inline-block;\nbox-sizing: border-box;\ntab-size: 2;\n- margin: 0 0 6px 0;\noverflow-x: scroll;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Adjust margin for Markdown blockQuote and codeBlock
129,187
07.08.2020 15:32:06
14,400
908634e92b1035cf477e1d2c9631e262a220f593
[native] Introduce and fix wipeAndExit
[ { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -39,7 +39,8 @@ import { sanitizeAction, sanitizeState } from 'lib/utils/sanitization';\nimport { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport Button from './components/button.react';\n-import { persistConfig, codeVersion, getPersistor } from './redux/persist';\n+import { persistConfig, codeVersion } from './redux/persist';\n+import { wipeAndExit } from './utils/crash-utils';\nconst errorTitles = ['Oh no!!', 'Womp womp womp...'];\n@@ -183,8 +184,7 @@ class Crash extends React.PureComponent<Props, State> {\ntry {\nawait this.props.logOut(this.props.preRequestUserState);\n} catch (e) {}\n- getPersistor().purge();\n- ExitApp.exitApp();\n+ await wipeAndExit();\n}\nonCopyCrashReportID = () => {\n" }, { "change_type": "MODIFY", "old_path": "native/more/dev-tools.react.js", "new_path": "native/more/dev-tools.react.js", "diff": "@@ -10,14 +10,11 @@ import { View, Text, ScrollView, Platform } from 'react-native';\nimport ExitApp from 'react-native-exit-app';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport PropTypes from 'prop-types';\n-import AsyncStorage from '@react-native-community/async-storage';\nimport { connect } from 'lib/utils/redux-utils';\nimport { setURLPrefix } from 'lib/utils/url-utils';\n-import sleep from 'lib/utils/sleep';\nimport Button from '../components/button.react';\n-import { getPersistor } from '../redux/persist';\nimport { serverOptions } from '../utils/url-utils';\nimport { CustomServerModalRouteName } from '../navigation/route-names';\nimport {\n@@ -26,7 +23,7 @@ import {\ncolorsSelector,\nstyleSelector,\n} from '../themes/colors';\n-import { navStateAsyncStorageKey } from '../navigation/persistance';\n+import { wipeAndExit } from '../utils/crash-utils';\nconst ServerIcon = () => (\n<Icon name=\"md-checkmark\" size={20} color=\"#008800\" style={styles.icon} />\n@@ -166,12 +163,7 @@ class DevTools extends React.PureComponent<Props> {\n};\nonPressWipe = async () => {\n- await Promise.all([\n- getPersistor().purge(),\n- __DEV__ ? AsyncStorage.removeItem(navStateAsyncStorageKey) : null,\n- ]);\n- await sleep(50);\n- ExitApp.exitApp();\n+ await wipeAndExit();\n};\nonSelectServer = (server: string) => {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/utils/crash-utils.js", "diff": "+// @flow\n+\n+import ExitApp from 'react-native-exit-app';\n+import AsyncStorage from '@react-native-community/async-storage';\n+\n+import sleep from 'lib/utils/sleep';\n+\n+import { getPersistor } from '../redux/persist';\n+import { navStateAsyncStorageKey } from '../navigation/persistance';\n+\n+async function wipeAndExit() {\n+ await Promise.all([\n+ getPersistor().purge(),\n+ __DEV__ ? AsyncStorage.removeItem(navStateAsyncStorageKey) : null,\n+ ]);\n+ await sleep(50);\n+ ExitApp.exitApp();\n+}\n+\n+export { wipeAndExit };\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Introduce and fix wipeAndExit
129,187
07.08.2020 15:38:50
14,400
2f71e3bd45b95f53ea4ce1481af80e984df92648
[native] codeVersion -> 63
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -133,8 +133,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 62\n- versionName \"0.0.62\"\n+ versionCode 63\n+ versionName \"0.0.63\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.62</string>\n+ <string>0.0.63</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>62</string>\n+ <string>63</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.62</string>\n+ <string>0.0.63</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>62</string>\n+ <string>63</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -175,7 +175,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 62;\n+const codeVersion = 63;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 63
129,187
10.08.2020 10:38:45
14,400
30a850d7bc9e00782213720cf33cb276ecbcab52
[native] Move DisconnectedBar back to react-native-reanimated Reanimated let us drive the animation from the native thread, increasing frame rate. We previously couldn't use it because of But that's fixed now!
[ { "change_type": "MODIFY", "old_path": "native/navigation/disconnected-bar.react.js", "new_path": "native/navigation/disconnected-bar.react.js", "diff": "// @flow\nimport * as React from 'react';\n-import { Text, StyleSheet, Platform, Animated, Easing } from 'react-native';\n+import { Text, StyleSheet, Platform } from 'react-native';\nimport { useSelector } from 'react-redux';\n+import Animated, { Easing } from 'react-native-reanimated';\nconst expandedHeight = Platform.select({\nandroid: 29.5,\ndefault: 27,\n});\nconst timingConfig = {\n- useNativeDriver: false,\nduration: 200,\neasing: Easing.inOut(Easing.ease),\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move DisconnectedBar back to react-native-reanimated Reanimated let us drive the animation from the native thread, increasing frame rate. We previously couldn't use it because of https://github.com/software-mansion/react-native-reanimated/issues/857 But that's fixed now!
129,187
11.08.2020 15:25:45
14,400
c286c698c7cc889c1d0d4a9102009b67e8f6bf5b
Don't double-report beforeAction in inconsistency reports
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -605,7 +605,6 @@ function reduceEntryInfos(\n}\nconst newInconsistencies = findInconsistencies(\n- entryInfos,\naction,\nentryInfos,\nupdatedEntryInfos,\n@@ -650,42 +649,32 @@ function mergeUpdateEntryInfos(\nconst emptyArray = [];\nfunction findInconsistencies(\n- beforeAction: { [id: string]: RawEntryInfo },\naction: BaseAction,\n- oldResult: { [id: string]: RawEntryInfo },\n- newResult: { [id: string]: RawEntryInfo },\n+ beforeStateCheck: { [id: string]: RawEntryInfo },\n+ afterStateCheck: { [id: string]: RawEntryInfo },\ncalendarQuery: CalendarQuery,\n): ClientEntryInconsistencyReportCreationRequest[] {\n// We don't want to bother reporting an inconsistency if it's just because of\n// extraneous EntryInfos (not within the current calendarQuery) on either side\n- const filteredPollResult = filterRawEntryInfosByCalendarQuery(\n- serverEntryInfosObject(values(oldResult)),\n+ const filteredBeforeResult = filterRawEntryInfosByCalendarQuery(\n+ serverEntryInfosObject(values(beforeStateCheck)),\ncalendarQuery,\n);\n- const filteredPushResult = filterRawEntryInfosByCalendarQuery(\n- serverEntryInfosObject(values(newResult)),\n+ const filteredAfterResult = filterRawEntryInfosByCalendarQuery(\n+ serverEntryInfosObject(values(afterStateCheck)),\ncalendarQuery,\n);\n- if (_isEqual(filteredPollResult)(filteredPushResult)) {\n+ if (_isEqual(filteredBeforeResult)(filteredAfterResult)) {\nreturn emptyArray;\n}\n- if (action.type === 'SEND_REPORT_SUCCESS') {\n- // We can get a memory leak if we include a previous\n- // ClientEntryInconsistencyReportCreationRequest in this one\n- action = {\n- type: 'SEND_REPORT_SUCCESS',\n- loadingInfo: action.loadingInfo,\n- };\n- }\nreturn [\n{\ntype: reportTypes.ENTRY_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\n- beforeAction,\n+ beforeAction: beforeStateCheck,\naction: sanitizeAction(action),\ncalendarQuery,\n- pollResult: oldResult,\n- pushResult: newResult,\n+ pushResult: afterStateCheck,\nlastActions: actionLogger.interestingActionSummaries,\ntime: Date.now(),\n},\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -107,30 +107,20 @@ function reduceThreadUpdates(\nconst emptyArray = [];\nfunction findInconsistencies(\n- beforeAction: { [id: string]: RawThreadInfo },\naction: BaseAction,\n- oldResult: { [id: string]: RawThreadInfo },\n- newResult: { [id: string]: RawThreadInfo },\n+ beforeStateCheck: { [id: string]: RawThreadInfo },\n+ afterStateCheck: { [id: string]: RawThreadInfo },\n): ClientThreadInconsistencyReportCreationRequest[] {\n- if (_isEqual(oldResult)(newResult)) {\n+ if (_isEqual(beforeStateCheck)(afterStateCheck)) {\nreturn emptyArray;\n}\n- if (action.type === 'SEND_REPORT_SUCCESS') {\n- // We can get a memory leak if we include a previous\n- // ClientThreadInconsistencyReportCreationRequest in this one\n- action = {\n- type: 'SEND_REPORT_SUCCESS',\n- loadingInfo: action.loadingInfo,\n- };\n- }\nreturn [\n{\ntype: reportTypes.THREAD_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\n- beforeAction,\n+ beforeAction: beforeStateCheck,\naction: sanitizeAction(action),\n- pollResult: oldResult,\n- pushResult: newResult,\n+ pushResult: afterStateCheck,\nlastActions: actionLogger.interestingActionSummaries,\ntime: Date.now(),\n},\n@@ -276,7 +266,6 @@ export default function reduceThreadInfos(\n}\nconst newInconsistencies = findInconsistencies(\n- state.threadInfos,\naction,\nstate.threadInfos,\nnewThreadInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "@@ -50,7 +50,7 @@ export type ThreadInconsistencyReportShape = {|\nplatformDetails: PlatformDetails,\nbeforeAction: { [id: string]: RawThreadInfo },\naction: BaseAction,\n- pollResult: { [id: string]: RawThreadInfo },\n+ pollResult?: { [id: string]: RawThreadInfo },\npushResult: { [id: string]: RawThreadInfo },\nlastActionTypes?: $ReadOnlyArray<$PropertyType<BaseAction, 'type'>>,\nlastActions?: $ReadOnlyArray<ActionSummary>,\n@@ -61,7 +61,7 @@ export type EntryInconsistencyReportShape = {|\nbeforeAction: { [id: string]: RawEntryInfo },\naction: BaseAction,\ncalendarQuery: CalendarQuery,\n- pollResult: { [id: string]: RawEntryInfo },\n+ pollResult?: { [id: string]: RawEntryInfo },\npushResult: { [id: string]: RawEntryInfo },\nlastActionTypes?: $ReadOnlyArray<$PropertyType<BaseAction, 'type'>>,\nlastActions?: $ReadOnlyArray<ActionSummary>,\n@@ -105,7 +105,6 @@ export type ClientThreadInconsistencyReportShape = {|\nplatformDetails: PlatformDetails,\nbeforeAction: { [id: string]: RawThreadInfo },\naction: BaseAction,\n- pollResult: { [id: string]: RawThreadInfo },\npushResult: { [id: string]: RawThreadInfo },\nlastActions: $ReadOnlyArray<ActionSummary>,\ntime: number,\n@@ -115,7 +114,6 @@ export type ClientEntryInconsistencyReportShape = {|\nbeforeAction: { [id: string]: RawEntryInfo },\naction: BaseAction,\ncalendarQuery: CalendarQuery,\n- pollResult: { [id: string]: RawEntryInfo },\npushResult: { [id: string]: RawEntryInfo },\nlastActions: $ReadOnlyArray<ActionSummary>,\ntime: number,\n@@ -155,7 +153,7 @@ export const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\nplatformDetails: platformDetailsPropType.isRequired,\nbeforeAction: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\naction: PropTypes.object.isRequired,\n- pollResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ pollResult: PropTypes.objectOf(rawThreadInfoPropType),\npushResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\nlastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\ntime: PropTypes.number.isRequired,\n@@ -166,7 +164,7 @@ export const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\nbeforeAction: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\naction: PropTypes.object.isRequired,\ncalendarQuery: calendarQueryPropType.isRequired,\n- pollResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ pollResult: PropTypes.objectOf(rawEntryInfoPropType),\npushResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\nlastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\ntime: PropTypes.number.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/report-creator.js", "new_path": "server/src/creators/report-creator.js", "diff": "@@ -192,23 +192,23 @@ function findInconsistentObjectKeys(\nfunction getInconsistentThreadIDsFromReport(\nrequest: ThreadInconsistencyReportCreationRequest,\n): Set<string> {\n- const { pushResult, pollResult } = request;\n- return findInconsistentObjectKeys(pollResult, pushResult);\n+ const { pushResult, beforeAction } = request;\n+ return findInconsistentObjectKeys(beforeAction, pushResult);\n}\nfunction getInconsistentEntryIDsFromReport(\nrequest: EntryInconsistencyReportCreationRequest,\n): Set<string> {\n- const { pushResult, pollResult, calendarQuery } = request;\n- const filteredPollResult = filterRawEntryInfosByCalendarQuery(\n- serverEntryInfosObject(values(pollResult)),\n+ const { pushResult, beforeAction, calendarQuery } = request;\n+ const filteredBeforeAction = filterRawEntryInfosByCalendarQuery(\n+ serverEntryInfosObject(values(beforeAction)),\ncalendarQuery,\n);\n- const filteredPushResult = filterRawEntryInfosByCalendarQuery(\n+ const filteredAfterAction = filterRawEntryInfosByCalendarQuery(\nserverEntryInfosObject(values(pushResult)),\ncalendarQuery,\n);\n- return findInconsistentObjectKeys(filteredPollResult, filteredPushResult);\n+ return findInconsistentObjectKeys(filteredBeforeAction, filteredAfterAction);\n}\nexport default createReport;\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/report-responders.js", "new_path": "server/src/responders/report-responders.js", "diff": "@@ -36,7 +36,7 @@ const threadInconsistencyReportValidatorShape = {\nplatformDetails: tPlatformDetails,\nbeforeAction: t.Object,\naction: t.Object,\n- pollResult: t.Object,\n+ pollResult: t.maybe(t.Object),\npushResult: t.Object,\nlastActionTypes: t.maybe(t.list(t.String)),\nlastActions: t.maybe(t.list(tActionSummary)),\n@@ -47,7 +47,7 @@ const entryInconsistencyReportValidatorShape = {\nbeforeAction: t.Object,\naction: t.Object,\ncalendarQuery: newEntryQueryInputValidator,\n- pollResult: t.Object,\n+ pollResult: t.maybe(t.Object),\npushResult: t.Object,\nlastActionTypes: t.maybe(t.list(t.String)),\nlastActions: t.maybe(t.list(tActionSummary)),\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Don't double-report beforeAction in inconsistency reports
129,187
11.08.2020 15:29:32
14,400
4220f2cd370620319a6c9f5f817b45affbffd230
[native] Clear Search input on log out
[ { "change_type": "MODIFY", "old_path": "native/components/search.react.js", "new_path": "native/components/search.react.js", "diff": "@@ -9,6 +9,7 @@ import { View, ViewPropTypes, TouchableOpacity, TextInput } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport { connect } from 'lib/utils/redux-utils';\n+import { isLoggedIn } from 'lib/selectors/user-selectors';\nimport {\ntype Colors,\n@@ -26,6 +27,7 @@ type Props = {|\n// Redux state\ncolors: Colors,\nstyles: typeof styles,\n+ loggedIn: boolean,\n|};\nclass Search extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -35,8 +37,15 @@ class Search extends React.PureComponent<Props> {\ntextInputRef: PropTypes.func,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n+ loggedIn: PropTypes.bool.isRequired,\n};\n+ componentDidUpdate(prevProps: Props) {\n+ if (!this.props.loggedIn && prevProps.loggedIn) {\n+ this.clearSearch();\n+ }\n+ }\n+\nrender() {\nconst {\nsearchText,\n@@ -45,6 +54,7 @@ class Search extends React.PureComponent<Props> {\ntextInputRef,\ncolors,\nstyles,\n+ loggedIn,\n...rest\n} = this.props;\nconst { listSearchIcon: iconColor } = colors;\n@@ -105,9 +115,17 @@ const stylesSelector = styleSelector(styles);\nconst ConnectedSearch = connect((state: AppState) => ({\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n+ loggedIn: isLoggedIn(state),\n}))(Search);\n-type ConnectedProps = $Diff<Props, {| colors: Colors, styles: typeof styles |}>;\n+type ConnectedProps = $Diff<\n+ Props,\n+ {|\n+ colors: Colors,\n+ styles: typeof styles,\n+ loggedIn: boolean,\n+ |},\n+>;\nexport default React.forwardRef<ConnectedProps, typeof TextInput>(\nfunction ForwardedConnectedSearch(\nprops: ConnectedProps,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Clear Search input on log out
129,187
11.08.2020 15:51:24
14,400
d78c46659c2b0a8bc719d0a1a61fd821f277e7c9
[native] Use updated threadInfo ASAP
[ { "change_type": "MODIFY", "old_path": "native/chat/message-list-container.react.js", "new_path": "native/chat/message-list-container.react.js", "diff": "@@ -82,6 +82,10 @@ class MessageListContainer extends React.PureComponent<Props, State> {\n};\nstatic getThreadInfo(props: Props): ThreadInfo {\n+ const { threadInfo } = props;\n+ if (threadInfo) {\n+ return threadInfo;\n+ }\nreturn props.route.params.threadInfo;\n}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/delete-thread.react.js", "new_path": "native/chat/settings/delete-thread.react.js", "diff": "@@ -110,6 +110,10 @@ class DeleteThread extends React.PureComponent<Props, State> {\n}\nstatic getThreadInfo(props: Props): ThreadInfo {\n+ const { threadInfo } = props;\n+ if (threadInfo) {\n+ return threadInfo;\n+ }\nreturn props.route.params.threadInfo;\n}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -258,8 +258,14 @@ class ThreadSettings extends React.PureComponent<Props, State> {\n}\nstatic getThreadInfo(props: {\n+ threadInfo: ?ThreadInfo,\nroute: NavigationRoute<'ThreadSettings'>,\n+ ...\n}): ThreadInfo {\n+ const { threadInfo } = props;\n+ if (threadInfo) {\n+ return threadInfo;\n+ }\nreturn props.route.params.threadInfo;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use updated threadInfo ASAP
129,187
12.08.2020 23:05:40
14,400
102cc15a721cb55da4c6d448be8ebafc3ffa7d47
[server] Don't UPDATE threadType in recalculateAllPermissions We already set this correctly at both callsites
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -355,16 +355,10 @@ async function updateDescendantPermissions(\nreturn { membershipRows, relationshipRows };\n}\n-// Unlike changeRole and others, this doesn't just create a Changeset.\n-// It mutates the threads table by setting the type column.\n-// Caller still needs to save the resultant Changeset.\nasync function recalculateAllPermissions(\nthreadID: string,\n- newThreadType: ThreadType,\n+ threadType: ThreadType,\n): Promise<Changeset> {\n- const updateQuery = SQL`\n- UPDATE threads SET type = ${newThreadType} WHERE id = ${threadID}\n- `;\nconst selectQuery = SQL`\nSELECT m.user, m.role, m.permissions, m.permissions_for_children,\npm.permissions_for_children AS permissions_from_parent,\n@@ -383,10 +377,7 @@ async function recalculateAllPermissions(\nLEFT JOIN memberships m ON m.thread = t.id AND m.user = pm.user\nWHERE t.id = ${threadID} AND m.thread IS NULL\n`;\n- const [[selectResult]] = await Promise.all([\n- dbQuery(selectQuery),\n- dbQuery(updateQuery),\n- ]);\n+ const [selectResult] = await dbQuery(selectQuery);\nconst relationshipRows = [];\nconst membershipRows = [];\n@@ -415,7 +406,7 @@ async function recalculateAllPermissions(\nrolePermissions,\npermissionsFromParent,\nthreadID,\n- newThreadType,\n+ threadType,\n);\nif (_isEqual(permissions)(oldPermissions)) {\n// This thread and all of its children need no updates, since its\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Don't UPDATE threadType in recalculateAllPermissions We already set this correctly at both callsites
129,187
12.08.2020 23:10:51
14,400
9e1a3be7093281235c5126d25ca065ee36c709ca
[server] Set different role permissions for threadTypes.SIDEBAR
[ { "change_type": "MODIFY", "old_path": "server/src/creators/role-creator.js", "new_path": "server/src/creators/role-creator.js", "diff": "@@ -5,6 +5,8 @@ import {\nthreadPermissions,\nthreadPermissionPrefixes,\ntype ThreadRolePermissionsBlob,\n+ type ThreadType,\n+ threadTypes,\n} from 'lib/types/thread-types';\nimport { dbQuery, SQL } from '../database';\n@@ -16,11 +18,12 @@ type InitialRoles = {|\n|};\nasync function createInitialRolesForNewThread(\nthreadID: string,\n+ threadType: ThreadType,\n): Promise<InitialRoles> {\nconst {\ndefaultPermissions,\ncreatorPermissions,\n- } = getRolePermissionBlobsForChat();\n+ } = getRolePermissionBlobsForChat(threadType);\nconst [defaultRoleID, creatorRoleID] = await createIDs(\n'roles',\ncreatorPermissions ? 2 : 1,\n@@ -159,7 +162,24 @@ function getRolePermissionBlobsForOrg(): RolePermissionBlobs {\n};\n}\n-function getRolePermissionBlobsForChat(): RolePermissionBlobs {\n+function getRolePermissionBlobsForChat(\n+ threadType: ThreadType,\n+): RolePermissionBlobs {\n+ if (threadType === threadTypes.SIDEBAR) {\n+ const memberPermissions = {\n+ [threadPermissions.KNOW_OF]: true,\n+ [threadPermissions.VISIBLE]: true,\n+ [threadPermissions.VOICED]: true,\n+ [threadPermissions.EDIT_THREAD]: true,\n+ [threadPermissions.ADD_MEMBERS]: true,\n+ [threadPermissions.EDIT_PERMISSIONS]: true,\n+ [threadPermissions.REMOVE_MEMBERS]: true,\n+ };\n+ return {\n+ defaultPermissions: memberPermissions,\n+ };\n+ }\n+\nconst openDescendantKnowOf =\nthreadPermissionPrefixes.OPEN_DESCENDANT + threadPermissions.KNOW_OF;\nconst openDescendantVisible =\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -86,7 +86,7 @@ async function createThread(\n}\nconst [id] = await createIDs('threads', 1);\n- const newRoles = await createInitialRolesForNewThread(id);\n+ const newRoles = await createInitialRolesForNewThread(id, threadType);\nconst name = request.name ? request.name : null;\nconst description = request.description ? request.description : null;\n" }, { "change_type": "MODIFY", "old_path": "server/src/scripts/create-db.js", "new_path": "server/src/scripts/create-db.js", "diff": "@@ -329,8 +329,9 @@ async function createUsers() {\nasync function createThreads() {\nconst staffSquadbotThreadRoleID = 118821;\n- const defaultRolePermissions = getRolePermissionBlobsForChat()\n- .defaultPermissions;\n+ const defaultRolePermissions = getRolePermissionBlobsForChat(\n+ threadTypes.CHAT_SECRET,\n+ ).defaultPermissions;\nconst membershipPermissions = makePermissionsBlob(\ndefaultRolePermissions,\nnull,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Set different role permissions for threadTypes.SIDEBAR
129,187
12.08.2020 23:27:01
14,400
3997317ce75af64d23cbb680af91921fcc034e0e
[server] Key RolePermissionBlobs by role name
[ { "change_type": "MODIFY", "old_path": "server/src/creators/role-creator.js", "new_path": "server/src/creators/role-creator.js", "diff": "@@ -20,34 +20,19 @@ async function createInitialRolesForNewThread(\nthreadID: string,\nthreadType: ThreadType,\n): Promise<InitialRoles> {\n- const {\n- defaultPermissions,\n- creatorPermissions,\n- } = getRolePermissionBlobsForChat(threadType);\n- const [defaultRoleID, creatorRoleID] = await createIDs(\n- 'roles',\n- creatorPermissions ? 2 : 1,\n- );\n+ const rolePermissions = getRolePermissionBlobsForChat(threadType);\n+ const ids = await createIDs('roles', Object.values(rolePermissions).length);\nconst time = Date.now();\n- const newRows = [\n- [\n- defaultRoleID,\n- threadID,\n- 'Members',\n- JSON.stringify(defaultPermissions),\n- time,\n- ],\n- ];\n- if (creatorPermissions) {\n- newRows.push([\n- creatorRoleID,\n- threadID,\n- 'Admins',\n- JSON.stringify(creatorPermissions),\n- time,\n- ]);\n+ const newRows = [];\n+ const namesToIDs = {};\n+ for (const name in rolePermissions) {\n+ const id = ids.shift();\n+ namesToIDs[name] = id;\n+ const permissionsBlob = JSON.stringify(rolePermissions[name]);\n+ newRows.push([id, threadID, name, permissionsBlob, time]);\n}\n+\nconst query = SQL`\nINSERT INTO roles (id, thread, name, permissions, creation_time)\nVALUES ${newRows}\n@@ -55,32 +40,33 @@ async function createInitialRolesForNewThread(\nawait dbQuery(query);\nconst defaultRoleInfo = {\n- id: defaultRoleID,\n+ id: namesToIDs.Members,\nname: 'Members',\n- permissions: defaultPermissions,\n+ permissions: rolePermissions.Members,\nisDefault: true,\n};\n- if (creatorPermissions) {\n+ if (!rolePermissions.Admins) {\nreturn {\ndefault: defaultRoleInfo,\n- creator: {\n- id: creatorRoleID,\n+ creator: defaultRoleInfo,\n+ };\n+ }\n+\n+ const adminRoleInfo = {\n+ id: namesToIDs.Admins,\nname: 'Admins',\n- permissions: creatorPermissions,\n+ permissions: rolePermissions.Admins,\nisDefault: false,\n- },\n};\n- } else {\nreturn {\ndefault: defaultRoleInfo,\n- creator: defaultRoleInfo,\n+ creator: adminRoleInfo,\n};\n}\n-}\ntype RolePermissionBlobs = {|\n- defaultPermissions: ThreadRolePermissionsBlob,\n- creatorPermissions?: ThreadRolePermissionsBlob,\n+ Members: ThreadRolePermissionsBlob,\n+ Admins?: ThreadRolePermissionsBlob,\n|};\n// Originally all chat threads were orgs, but for the alpha launch I decided\n@@ -157,8 +143,8 @@ function getRolePermissionBlobsForOrg(): RolePermissionBlobs {\n[descendantChangeRole]: true,\n};\nreturn {\n- defaultPermissions: memberPermissions,\n- creatorPermissions: adminPermissions,\n+ Members: memberPermissions,\n+ Admins: adminPermissions,\n};\n}\n@@ -176,7 +162,7 @@ function getRolePermissionBlobsForChat(\n[threadPermissions.REMOVE_MEMBERS]: true,\n};\nreturn {\n- defaultPermissions: memberPermissions,\n+ Members: memberPermissions,\n};\n}\n@@ -202,7 +188,7 @@ function getRolePermissionBlobsForChat(\n[openDescendantJoinThread]: true,\n};\nreturn {\n- defaultPermissions: memberPermissions,\n+ Members: memberPermissions,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/scripts/create-db.js", "new_path": "server/src/scripts/create-db.js", "diff": "@@ -331,7 +331,7 @@ async function createThreads() {\nconst staffSquadbotThreadRoleID = 118821;\nconst defaultRolePermissions = getRolePermissionBlobsForChat(\nthreadTypes.CHAT_SECRET,\n- ).defaultPermissions;\n+ ).Members;\nconst membershipPermissions = makePermissionsBlob(\ndefaultRolePermissions,\nnull,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Key RolePermissionBlobs by role name
129,187
13.08.2020 00:18:02
14,400
05d4a4e7e76f6aafe8894aa6b641eb73b08b31c8
[server] updateRoles
[ { "change_type": "ADD", "old_path": null, "new_path": "server/src/fetchers/role-fetchers.js", "diff": "+// @flow\n+\n+import type { RoleInfo } from 'lib/types/thread-types';\n+\n+import { dbQuery, SQL } from '../database';\n+\n+async function fetchRoles(threadID: string): Promise<RoleInfo[]> {\n+ const query = SQL`\n+ SELECT r.id, r.name, r.permissions, r.id = t.default_role AS is_default\n+ FROM roles r\n+ LEFT JOIN threads t ON t.id = r.thread\n+ WHERE r.thread = ${threadID}\n+ `;\n+ const [result] = await dbQuery(query);\n+\n+ const roles = [];\n+ for (const row of result) {\n+ roles.push({\n+ id: row.id.toString(),\n+ name: row.name,\n+ permissions: row.permissions,\n+ isDefault: Boolean(row.is_default),\n+ });\n+ }\n+ return roles;\n+}\n+\n+export { fetchRoles };\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/updaters/role-updaters.js", "diff": "+// @flow\n+\n+import type { Viewer } from '../session/viewer';\n+import type { ThreadType } from 'lib/types/thread-types';\n+\n+import _isEqual from 'lodash/fp/isEqual';\n+import invariant from 'invariant';\n+\n+import { dbQuery, SQL } from '../database';\n+import { fetchRoles } from '../fetchers/role-fetchers';\n+import { getRolePermissionBlobsForChat } from '../creators/role-creator';\n+import createIDs from '../creators/id-creator';\n+\n+async function updateRoles(\n+ viewer: Viewer,\n+ threadID: string,\n+ threadType: ThreadType,\n+): Promise<void> {\n+ const currentRoles = await fetchRoles(threadID);\n+\n+ const currentRolePermissions = {};\n+ const currentRoleIDs = {};\n+ for (const roleInfo of currentRoles) {\n+ currentRolePermissions[roleInfo.name] = roleInfo.permissions;\n+ currentRoleIDs[roleInfo.name] = roleInfo.id;\n+ }\n+\n+ const rolePermissions = getRolePermissionBlobsForChat(threadType);\n+ if (_isEqual(rolePermissions)(currentRolePermissions)) {\n+ return;\n+ }\n+\n+ const promises = [];\n+\n+ if (rolePermissions.Admins && !currentRolePermissions.Admins) {\n+ const [id] = await createIDs('roles', 1);\n+ const newRow = [id, threadID, 'Admins', rolePermissions.Admins, Date.now()];\n+ const insertQuery = SQL`\n+ INSERT INTO roles (id, thread, name, permissions, creation_time)\n+ VALUES ${[newRow]}\n+ `;\n+ promises.push(dbQuery(insertQuery));\n+ const setAdminQuery = SQL`\n+ UPDATE memberships\n+ SET role = ${id}\n+ WHERE thread = ${threadID} AND user = ${viewer.userID}\n+ `;\n+ promises.push(dbQuery(setAdminQuery));\n+ } else if (!rolePermissions.Admins && currentRolePermissions.Admins) {\n+ invariant(\n+ currentRoleIDs.Admins && currentRoleIDs.Members,\n+ 'ids should exist for both Admins and Members roles',\n+ );\n+ const id = currentRoleIDs.Admins;\n+ const deleteQuery = SQL`\n+ DELETE r, i FROM roles r LEFT JOIN ids i ON i.id = r.id WHERE r.id = ${id}\n+ `;\n+ promises.push(dbQuery(deleteQuery));\n+ const updateMembershipsQuery = SQL`\n+ UPDATE memberships\n+ SET role = ${currentRoleIDs.Members}\n+ WHERE thread = ${threadID}\n+ `;\n+ promises.push(dbQuery(updateMembershipsQuery));\n+ }\n+\n+ const updatePermissions = {};\n+ for (const name in currentRoleIDs) {\n+ const currentPermissions = currentRolePermissions[name];\n+ const permissions = rolePermissions[name];\n+ if (\n+ !permissions ||\n+ !currentPermissions ||\n+ _isEqual(permissions)(currentPermissions)\n+ ) {\n+ continue;\n+ }\n+ const id = currentRoleIDs[name];\n+ updatePermissions[id] = permissions;\n+ }\n+ if (Object.values(updatePermissions).length > 0) {\n+ const updateQuery = SQL`\n+ UPDATE roles\n+ SET permissions = CASE id\n+ `;\n+ for (const id in updatePermissions) {\n+ const permissionsBlob = JSON.stringify(updatePermissions[id]);\n+ updateQuery.append(SQL`\n+ WHEN ${id} THEN ${permissionsBlob}\n+ `);\n+ }\n+ updateQuery.append(SQL`\n+ ELSE permissions\n+ END\n+ WHERE thread = ${threadID}\n+ `);\n+ promises.push(dbQuery(updateQuery));\n+ }\n+\n+ await Promise.all(promises);\n+}\n+\n+export { updateRoles };\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -48,6 +48,7 @@ import {\nimport createMessages from '../creators/message-creator';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\n+import { updateRoles } from './role-updaters';\nasync function updateRole(\nviewer: Viewer,\n@@ -451,10 +452,10 @@ async function updateThread(\nnextThreadType !== oldThreadType ||\nnextParentThreadID !== oldParentThreadID\n) {\n- intermediatePromises.recalculatePermissionsChangeset = recalculateAllPermissions(\n- request.threadID,\n- nextThreadType,\n- );\n+ intermediatePromises.recalculatePermissionsChangeset = (async () => {\n+ await updateRoles(viewer, request.threadID, nextThreadType);\n+ await recalculateAllPermissions(request.threadID, nextThreadType);\n+ })();\n}\nconst {\naddMembersChangeset,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] updateRoles
129,187
13.08.2020 10:37:16
14,400
1ccad9998dba6b0113e696417d8b0c0c074a7897
[server] Fix permission recalculation in updateThread
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -453,8 +453,10 @@ async function updateThread(\nnextParentThreadID !== oldParentThreadID\n) {\nintermediatePromises.recalculatePermissionsChangeset = (async () => {\n+ if (nextThreadType !== oldThreadType) {\nawait updateRoles(viewer, request.threadID, nextThreadType);\n- await recalculateAllPermissions(request.threadID, nextThreadType);\n+ }\n+ return await recalculateAllPermissions(request.threadID, nextThreadType);\n})();\n}\nconst {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix permission recalculation in updateThread
129,187
15.08.2020 19:27:33
14,400
24047d7e0a27358c6a4787a244b4ecdb19d79ad2
[server] Fix case where empty array passed to fetchKnownUserInfos throws exception It results in a SQL error around `IN ()`
[ { "change_type": "MODIFY", "old_path": "server/src/fetchers/user-fetchers.js", "new_path": "server/src/fetchers/user-fetchers.js", "diff": "@@ -48,6 +48,9 @@ async function fetchKnownUserInfos(\nif (!viewer.loggedIn) {\nthrow new ServerError('not_logged_in');\n}\n+ if (userIDs && userIDs.length === 0) {\n+ return {};\n+ }\nconst query = SQL`\nSELECT DISTINCT u.id, u.username FROM relationships_undirected r\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix case where empty array passed to fetchKnownUserInfos throws exception It results in a SQL error around `IN ()`
129,187
15.08.2020 19:33:20
14,400
7a9207f73c8db056ffc0ba380c18a00450b6d40a
[server] Still include newThreadInfo for create_thread Forgot to remove one callsite
[ { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -206,7 +206,7 @@ async function createThread(\n]);\nconst { threadInfos, viewerUpdates } = commitResult;\n- if (hasMinCodeVersion(viewer.platformDetails, 62)) {\n+ if (hasMinCodeVersion(viewer.platformDetails, 64)) {\nreturn {\nnewThreadID: id,\nupdatesResult: {\n@@ -217,6 +217,7 @@ async function createThread(\n}\nreturn {\n+ newThreadID: id,\nnewThreadInfo: threadInfos[id],\nupdatesResult: {\nnewUpdates: viewerUpdates,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Still include newThreadInfo for create_thread Forgot to remove one callsite
129,187
15.08.2020 19:39:21
14,400
2612dc72c26039301ce262aae3d6590874729c7e
[native] Don't expect RawThreadInfo in result from create_thread
[ { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -15,8 +15,6 @@ import {\nimport {\ntype AccountUserInfo,\naccountUserInfoPropType,\n- type UserInfo,\n- userInfoPropType,\n} from 'lib/types/user-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { UserSearchResult } from 'lib/types/search-types';\n@@ -41,11 +39,7 @@ import {\nuserSearchIndexForOtherMembersOfThread,\n} from 'lib/selectors/user-selectors';\nimport SearchIndex from 'lib/shared/search-index';\n-import {\n- threadInFilterList,\n- userIsMember,\n- threadInfoFromRawThreadInfo,\n-} from 'lib/shared/thread-utils';\n+import { threadInFilterList, userIsMember } from 'lib/shared/thread-utils';\nimport { getUserSearchResults } from 'lib/shared/search-utils';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\n@@ -85,8 +79,6 @@ type Props = {|\nthreadInfos: { [id: string]: ThreadInfo },\ncolors: Colors,\nstyles: typeof styles,\n- viewerID: ?string,\n- userInfos: { [id: string]: UserInfo },\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -120,8 +112,6 @@ class ComposeThread extends React.PureComponent<Props, State> {\nthreadInfos: PropTypes.objectOf(threadInfoPropType).isRequired,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n- viewerID: PropTypes.string,\n- userInfos: PropTypes.objectOf(userInfoPropType).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nnewThread: PropTypes.func.isRequired,\nsearchUsers: PropTypes.func.isRequired,\n@@ -132,6 +122,7 @@ class ComposeThread extends React.PureComponent<Props, State> {\n};\ntagInput: ?TagInput<AccountUserInfo>;\ncreateThreadPressed = false;\n+ waitingOnThreadID: ?string;\nconstructor(props: Props) {\nsuper(props);\n@@ -165,6 +156,15 @@ class ComposeThread extends React.PureComponent<Props, State> {\nparentThreadInfo: newReduxParentThreadInfo,\n});\n}\n+\n+ if (\n+ this.waitingOnThreadID &&\n+ this.props.threadInfos[this.waitingOnThreadID] &&\n+ !prevProps.threadInfos[this.waitingOnThreadID]\n+ ) {\n+ const threadInfo = this.props.threadInfos[this.waitingOnThreadID];\n+ this.props.navigation.pushNewThread(threadInfo);\n+ }\n}\nstatic getParentThreadInfo(props: {\n@@ -370,15 +370,10 @@ class ComposeThread extends React.PureComponent<Props, State> {\ndispatchNewChatThreadAction = async () => {\nthis.createThreadPressed = true;\n- const promise = this.newChatThreadAction();\n- this.props.dispatchActionPromise(newThreadActionTypes, promise);\n- const { newThreadInfo: rawThreadInfo } = await promise;\n- const threadInfo = threadInfoFromRawThreadInfo(\n- rawThreadInfo,\n- this.props.viewerID,\n- this.props.userInfos,\n+ this.props.dispatchActionPromise(\n+ newThreadActionTypes,\n+ this.newChatThreadAction(),\n);\n- this.props.navigation.pushNewThread(threadInfo);\n};\nasync newChatThreadAction() {\n@@ -392,12 +387,14 @@ class ComposeThread extends React.PureComponent<Props, State> {\n(userInfo: AccountUserInfo) => userInfo.id,\n);\nconst parentThreadInfo = ComposeThread.getParentThreadInfo(this.props);\n- return await this.props.newThread({\n+ const result = await this.props.newThread({\ntype: threadType,\nparentThreadID: parentThreadInfo ? parentThreadInfo.id : null,\ninitialMemberIDs,\ncolor: parentThreadInfo ? parentThreadInfo.color : null,\n});\n+ this.waitingOnThreadID = result.newThreadID;\n+ return result;\n} catch (e) {\nthis.createThreadPressed = false;\nthis.setLinkButton(true);\n@@ -527,8 +524,6 @@ export default connect(\nthreadInfos: threadInfoSelector(state),\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n- viewerID: state.currentUserInfo && state.currentUserInfo.id,\n- userInfos: state.userInfos,\n};\n},\n{ newThread, searchUsers },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't expect RawThreadInfo in result from create_thread
129,187
16.08.2020 11:10:20
14,400
13a1789a3b1914269aa73561f4a5d4503e79fa4b
[native] codeVersion -> 64
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -133,8 +133,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 63\n- versionName \"0.0.63\"\n+ versionCode 64\n+ versionName \"0.0.64\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.63</string>\n+ <string>0.0.64</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>63</string>\n+ <string>64</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.63</string>\n+ <string>0.0.64</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>63</string>\n+ <string>64</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -175,7 +175,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 63;\n+const codeVersion = 64;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 64
129,187
17.08.2020 10:33:21
14,400
f91b9ce1eac575a2cfb536fcc34d9edab70a493a
[native] Set dark-content StatusBar in Crash component
[ { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -41,6 +41,7 @@ import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport Button from './components/button.react';\nimport { persistConfig, codeVersion } from './redux/persist';\nimport { wipeAndExit } from './utils/crash-utils';\n+import ConnectedStatusBar from './connected-status-bar.react';\nconst errorTitles = ['Oh no!!', 'Womp womp womp...'];\n@@ -118,6 +119,7 @@ class Crash extends React.PureComponent<Props, State> {\nreturn (\n<View style={styles.container}>\n+ <ConnectedStatusBar barStyle=\"dark-content\" />\n<Icon name=\"bug\" size={32} color=\"red\" />\n<Text style={styles.header}>{this.errorTitle}</Text>\n<Text style={styles.text}>I&apos;m sorry, but the app crashed.</Text>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Set dark-content StatusBar in Crash component
129,187
18.08.2020 17:44:02
14,400
ae2bc5fa8503f5bf550b695140035a82f6e5a0c6
[web] Introduce FocusHandler Makes sure to only consider a browser window to be in foreground if it's both focused according to `window.onfocus` and visible according to the Visibility API
[ { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -12,7 +12,6 @@ import * as React from 'react';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\nimport PropTypes from 'prop-types';\n-import Visibility from 'visibilityjs';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faCalendar, faComments } from '@fortawesome/free-solid-svg-icons';\nimport { config as faConfig } from '@fortawesome/fontawesome-svg-core';\n@@ -34,10 +33,6 @@ import {\nmostRecentReadThreadSelector,\nunreadCount,\n} from 'lib/selectors/thread-selectors';\n-import {\n- backgroundActionType,\n- foregroundActionType,\n-} from 'lib/reducers/foreground-reducer';\nimport { isLoggedIn } from 'lib/selectors/user-selectors';\nimport { canonicalURLFromReduxState, navInfoFromURL } from './url-utils';\n@@ -56,6 +51,7 @@ import {\n} from './redux-setup';\nimport Splash from './splash/splash.react';\nimport Chat from './chat/chat.react';\n+import FocusHandler from './focus-handler.react';\n// We want Webpack's css-loader and style-loader to handle the Fontawesome CSS,\n// so we disable the autoAddCss logic and import the CSS file. Otherwise every\n@@ -140,17 +136,7 @@ class App extends React.PureComponent<Props, State> {\n} else if (this.props.location.pathname !== '/') {\nhistory.replace('/');\n}\n-\n- Visibility.change(this.onVisibilityChange);\n- }\n-\n- onVisibilityChange = (e, state: string) => {\n- if (state === 'visible') {\n- this.props.dispatchActionPayload(foregroundActionType, null);\n- } else {\n- this.props.dispatchActionPayload(backgroundActionType, null);\n}\n- };\ncomponentDidUpdate(prevProps: Props) {\nif (this.props.loggedIn) {\n@@ -230,6 +216,7 @@ class App extends React.PureComponent<Props, State> {\n}\nreturn (\n<DndProvider backend={HTML5Backend}>\n+ <FocusHandler />\n{content}\n{this.state.currentModal}\n</DndProvider>\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/focus-handler.react.js", "diff": "+// @flow\n+\n+import * as React from 'react';\n+import { useDispatch } from 'react-redux';\n+import Visibility from 'visibilityjs';\n+\n+import {\n+ backgroundActionType,\n+ foregroundActionType,\n+} from 'lib/reducers/foreground-reducer';\n+\n+function FocusHandler() {\n+ const [visible, setVisible] = React.useState(!Visibility.hidden());\n+ const onVisibilityChange = React.useCallback((event, state: string) => {\n+ setVisible(state === 'visible');\n+ }, []);\n+ React.useEffect(() => {\n+ const listener = Visibility.change(onVisibilityChange);\n+ return () => {\n+ Visibility.unbind(listener);\n+ };\n+ }, [onVisibilityChange]);\n+\n+ const [focused, setFocused] = React.useState(\n+ !window || !window.hasFocus || window.hasFocus(),\n+ );\n+ const onFocus = React.useCallback(() => {\n+ setFocused(true);\n+ }, []);\n+ const onBlur = React.useCallback(() => {\n+ setFocused(false);\n+ }, []);\n+ React.useEffect(() => {\n+ window.addEventListener('focus', onFocus);\n+ window.addEventListener('blur', onBlur);\n+ return () => {\n+ window.removeEventListener('focus', onFocus);\n+ window.removeEventListener('blur', onBlur);\n+ };\n+ }, [onFocus, onBlur]);\n+\n+ const foreground = visible && focused;\n+ const dispatch = useDispatch();\n+ const prevForegroundRef = React.useRef(true);\n+ React.useEffect(() => {\n+ const prevForeground = prevForegroundRef.current;\n+ if (foreground && !prevForeground) {\n+ dispatch({ type: foregroundActionType, payload: null });\n+ } else if (!foreground && prevForeground) {\n+ dispatch({ type: backgroundActionType, payload: null });\n+ }\n+ prevForegroundRef.current = foreground;\n+ }, [foreground, dispatch]);\n+\n+ return null;\n+}\n+\n+export default FocusHandler;\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -148,6 +148,9 @@ function validateState(oldState: AppState, state: AppState): AppState {\nif (\nactiveThread &&\n!Visibility.hidden() &&\n+ document &&\n+ document.hasFocus &&\n+ document.hasFocus() &&\nstate.threadStore.threadInfos[activeThread].currentUser.unread\n) {\n// Makes sure a currently focused thread is never unread\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Introduce FocusHandler Makes sure to only consider a browser window to be in foreground if it's both focused according to `window.onfocus` and visible according to the Visibility API
129,187
18.08.2020 17:59:33
14,400
70422c57e74896e8193739c4695265d731859dab
[web] Wait 2 seconds before confirming foreground event
[ { "change_type": "MODIFY", "old_path": "web/focus-handler.react.js", "new_path": "web/focus-handler.react.js", "diff": "// @flow\nimport * as React from 'react';\n-import { useDispatch } from 'react-redux';\n+import { useDispatch, useSelector } from 'react-redux';\nimport Visibility from 'visibilityjs';\nimport {\n@@ -39,18 +39,38 @@ function FocusHandler() {\n};\n}, [onFocus, onBlur]);\n- const foreground = visible && focused;\nconst dispatch = useDispatch();\n- const prevForegroundRef = React.useRef(true);\n+ const curForeground = useSelector(state => state.foreground);\n+ const updateRedux = React.useCallback(\n+ foreground => {\n+ if (foreground === curForeground) {\n+ return;\n+ }\n+ if (foreground) {\n+ dispatch({ type: foregroundActionType, payload: null });\n+ } else {\n+ dispatch({ type: backgroundActionType, payload: null });\n+ }\n+ },\n+ [dispatch, curForeground],\n+ );\n+\n+ const foreground = visible && focused;\n+ const prevForegroundRef = React.useRef(curForeground);\n+ const foregroundTimerRef = React.useRef();\nReact.useEffect(() => {\nconst prevForeground = prevForegroundRef.current;\nif (foreground && !prevForeground) {\n- dispatch({ type: foregroundActionType, payload: null });\n+ foregroundTimerRef.current = setTimeout(() => updateRedux(true), 2000);\n} else if (!foreground && prevForeground) {\n- dispatch({ type: backgroundActionType, payload: null });\n+ if (foregroundTimerRef.current) {\n+ clearTimeout(foregroundTimerRef.current);\n+ foregroundTimerRef.current = undefined;\n+ }\n+ updateRedux(false);\n}\nprevForegroundRef.current = foreground;\n- }, [foreground, dispatch]);\n+ }, [foreground, updateRedux]);\nreturn null;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Wait 2 seconds before confirming foreground event
129,187
19.08.2020 09:04:49
14,400
e40a678d07481b43f8babc0a6c4f382ce52d9842
[lib] Get rid of FETCH_ENTRIES_AND_APPEND_RANGE actions Forgot to remove this in
[ { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -16,7 +16,6 @@ import type {\nDeleteEntryResponse,\nRestoreEntryPayload,\nFetchEntryInfosResult,\n- CalendarResult,\nCalendarQueryUpdateResult,\nCalendarQueryUpdateStartingPayload,\n} from './entry-types';\n@@ -468,22 +467,6 @@ export type BaseAction =\ntype: 'SET_NEW_SESSION',\npayload: SetSessionPayload,\n|}\n- | {|\n- type: 'FETCH_ENTRIES_AND_APPEND_RANGE_STARTED',\n- payload?: void,\n- loadingInfo: LoadingInfo,\n- |}\n- | {|\n- type: 'FETCH_ENTRIES_AND_APPEND_RANGE_FAILED',\n- error: true,\n- payload: Error,\n- loadingInfo: LoadingInfo,\n- |}\n- | {|\n- type: 'FETCH_ENTRIES_AND_APPEND_RANGE_SUCCESS',\n- payload: CalendarResult,\n- loadingInfo: LoadingInfo,\n- |}\n| {|\ntype: 'persist/REHYDRATE',\npayload: ?BaseAppState<*>,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Get rid of FETCH_ENTRIES_AND_APPEND_RANGE actions Forgot to remove this in 005768511daeb30f4750ccd4f8a2dd52bd1bdafc
129,187
19.08.2020 13:20:52
14,400
9494675541b2e6a8ac91635c1683f7489cb67464
[server] Return void from sendPushNotifs
[ { "change_type": "MODIFY", "old_path": "server/src/push/send.js", "new_path": "server/src/push/send.js", "diff": "@@ -60,7 +60,7 @@ export type PushInfo = { [userID: string]: PushUserInfo };\nasync function sendPushNotifs(pushInfo: PushInfo) {\nif (Object.keys(pushInfo).length === 0) {\n- return [];\n+ return;\n}\nconst [\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Return void from sendPushNotifs
129,187
19.08.2020 13:49:58
14,400
8a930f24c2be8ce4855b72148c04f153b2abbfda
[web] Separate visibility and focus logic We'll start the socket if the window is visible, but we'll only consider a thread active if the window is focused as well
[ { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -291,6 +291,7 @@ async function websiteResponder(\ncookie: undefined,\ndeviceToken: undefined,\ndataLoaded: viewer.loggedIn,\n+ windowActive: true,\n};\nconst state = await promiseAll(statePromises);\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -51,6 +51,7 @@ import {\n} from './redux/redux-setup';\nimport Splash from './splash/splash.react';\nimport Chat from './chat/chat.react';\n+import VisibilityHandler from './redux/visibility-handler.react';\nimport FocusHandler from './redux/focus-handler.react';\n// We want Webpack's css-loader and style-loader to handle the Fontawesome CSS,\n@@ -217,6 +218,7 @@ class App extends React.PureComponent<Props, State> {\nreturn (\n<DndProvider backend={HTML5Backend}>\n<FocusHandler />\n+ <VisibilityHandler />\n{content}\n{this.state.currentModal}\n</DndProvider>\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/redux/action-types.js", "diff": "+// @flow\n+\n+export const updateWindowActiveActionType = 'UPDATE_WINDOW_ACTIVE';\n" }, { "change_type": "MODIFY", "old_path": "web/redux/focus-handler.react.js", "new_path": "web/redux/focus-handler.react.js", "diff": "import * as React from 'react';\nimport { useDispatch, useSelector } from 'react-redux';\n-import Visibility from 'visibilityjs';\n-import {\n- backgroundActionType,\n- foregroundActionType,\n-} from 'lib/reducers/foreground-reducer';\n+import { updateWindowActiveActionType } from './action-types';\nfunction FocusHandler() {\n- const [visible, setVisible] = React.useState(!Visibility.hidden());\n- const onVisibilityChange = React.useCallback((event, state: string) => {\n- setVisible(state === 'visible');\n- }, []);\n- React.useEffect(() => {\n- const listener = Visibility.change(onVisibilityChange);\n- return () => {\n- Visibility.unbind(listener);\n- };\n- }, [onVisibilityChange]);\n-\nconst [focused, setFocused] = React.useState(\n!window || !window.hasFocus || window.hasFocus(),\n);\n@@ -40,37 +25,32 @@ function FocusHandler() {\n}, [onFocus, onBlur]);\nconst dispatch = useDispatch();\n- const curForeground = useSelector(state => state.foreground);\n+ const curWindowActive = useSelector(state => state.windowActive);\nconst updateRedux = React.useCallback(\n- foreground => {\n- if (foreground === curForeground) {\n+ windowActive => {\n+ if (windowActive === curWindowActive) {\nreturn;\n}\n- if (foreground) {\n- dispatch({ type: foregroundActionType, payload: null });\n- } else {\n- dispatch({ type: backgroundActionType, payload: null });\n- }\n+ dispatch({ type: updateWindowActiveActionType, payload: windowActive });\n},\n- [dispatch, curForeground],\n+ [dispatch, curWindowActive],\n);\n- const foreground = visible && focused;\n- const prevForegroundRef = React.useRef(curForeground);\n- const foregroundTimerRef = React.useRef();\n+ const prevFocusedRef = React.useRef(curWindowActive);\n+ const timerRef = React.useRef();\nReact.useEffect(() => {\n- const prevForeground = prevForegroundRef.current;\n- if (foreground && !prevForeground) {\n- foregroundTimerRef.current = setTimeout(() => updateRedux(true), 2000);\n- } else if (!foreground && prevForeground) {\n- if (foregroundTimerRef.current) {\n- clearTimeout(foregroundTimerRef.current);\n- foregroundTimerRef.current = undefined;\n+ const prevFocused = prevFocusedRef.current;\n+ if (focused && !prevFocused) {\n+ timerRef.current = setTimeout(() => updateRedux(true), 2000);\n+ } else if (!focused && prevFocused) {\n+ if (timerRef.current) {\n+ clearTimeout(timerRef.current);\n+ timerRef.current = undefined;\n}\nupdateRedux(false);\n}\n- prevForegroundRef.current = foreground;\n- }, [foreground, updateRedux]);\n+ prevFocusedRef.current = focused;\n+ }, [focused, updateRedux]);\nreturn null;\n}\n" }, { "change_type": "MODIFY", "old_path": "web/redux/redux-setup.js", "new_path": "web/redux/redux-setup.js", "diff": "@@ -26,6 +26,7 @@ import {\n} from 'lib/actions/user-actions';\nimport { activeThreadSelector } from '../selectors/nav-selectors';\n+import { updateWindowActiveActionType } from './action-types';\nexport type NavInfo = {|\n...$Exact<BaseNavInfo>,\n@@ -68,6 +69,7 @@ export type AppState = {|\ntimeZone: ?string,\nuserAgent: ?string,\ndataLoaded: boolean,\n+ windowActive: boolean,\n|};\nexport const updateNavInfoActionType = 'UPDATE_NAV_INFO';\n@@ -79,6 +81,10 @@ export type Action =\n| {|\ntype: 'UPDATE_WINDOW_DIMENSIONS',\npayload: WindowDimensions,\n+ |}\n+ | {|\n+ type: 'UPDATE_WINDOW_ACTIVE',\n+ payload: boolean,\n|};\nexport function reducer(oldState: AppState | void, action: Action) {\n@@ -95,6 +101,11 @@ export function reducer(oldState: AppState | void, action: Action) {\n...state,\nwindowDimensions: action.payload,\n});\n+ } else if (action.type === updateWindowActiveActionType) {\n+ return validateState(oldState, {\n+ ...state,\n+ windowActive: action.payload,\n+ });\n} else if (action.type === setNewSessionActionType) {\nif (\ninvalidSessionDowngrade(\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/redux/visibility-handler.react.js", "diff": "+// @flow\n+\n+import * as React from 'react';\n+import { useDispatch, useSelector } from 'react-redux';\n+import Visibility from 'visibilityjs';\n+\n+import {\n+ backgroundActionType,\n+ foregroundActionType,\n+} from 'lib/reducers/foreground-reducer';\n+\n+function VisibilityHandler() {\n+ const [visible, setVisible] = React.useState(!Visibility.hidden());\n+ const onVisibilityChange = React.useCallback((event, state: string) => {\n+ setVisible(state === 'visible');\n+ }, []);\n+ React.useEffect(() => {\n+ const listener = Visibility.change(onVisibilityChange);\n+ return () => {\n+ Visibility.unbind(listener);\n+ };\n+ }, [onVisibilityChange]);\n+\n+ const dispatch = useDispatch();\n+ const curForeground = useSelector(state => state.foreground);\n+ const updateRedux = React.useCallback(\n+ foreground => {\n+ if (foreground === curForeground) {\n+ return;\n+ }\n+ if (foreground) {\n+ dispatch({ type: foregroundActionType, payload: null });\n+ } else {\n+ dispatch({ type: backgroundActionType, payload: null });\n+ }\n+ },\n+ [dispatch, curForeground],\n+ );\n+\n+ const prevVisibleRef = React.useRef(curForeground);\n+ React.useEffect(() => {\n+ const prevVisible = prevVisibleRef.current;\n+ if (visible && !prevVisible) {\n+ updateRedux(true);\n+ } else if (!visible && prevVisible) {\n+ updateRedux(false);\n+ }\n+ prevVisibleRef.current = visible;\n+ }, [visible, updateRedux]);\n+\n+ return null;\n+}\n+\n+export default VisibilityHandler;\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -24,11 +24,13 @@ export default connect(\nstate.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\nstate.foreground;\n+ const activeThread =\n+ active && state.windowActive ? activeThreadSelector(state) : null;\nreturn {\nactive,\nopenSocket: openSocketSelector(state),\ngetClientResponses: webGetClientResponsesSelector(state),\n- activeThread: active ? activeThreadSelector(state) : null,\n+ activeThread,\nsessionStateFunc: webSessionStateFuncSelector(state),\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Separate visibility and focus logic We'll start the socket if the window is visible, but we'll only consider a thread active if the window is focused as well
129,187
19.08.2020 14:33:59
14,400
e432acfb559ad3b77d4f50705e6ff3075442b918
[web] Limit image size
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.css", "new_path": "web/chat/chat-message-list.css", "diff": "@@ -233,7 +233,7 @@ div.messageBox {\ndisplay: flex;\nflex-wrap: wrap;\njustify-content: space-between;\n- max-width: 68%;\n+ max-width: calc(min(68%, 1000px));\n}\ndiv.fixedWidthMessageBox {\nwidth: 68%;\n@@ -302,7 +302,7 @@ div.messageBox span.multimedia > span.multimediaImage {\nmin-width: initial;\n}\ndiv.messageBox span.multimedia > span.multimediaImage > img {\n- max-height: initial;\n+ max-height: 600px;\n}\ndiv.imageGrid > span.multimedia {\n@@ -317,7 +317,7 @@ div.imageGrid > span.multimedia > span.multimediaImage {\ndiv.imageGrid > span.multimedia > span.multimediaImage:after {\ncontent: \"\";\ndisplay: block;\n- padding-bottom: 100%;\n+ padding-bottom: calc(min(600px, 100%));\n}\ndiv.imageGrid > span.multimedia > span.multimediaImage > img {\nposition: absolute;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Limit image size
129,187
19.08.2020 15:58:13
14,400
26396a19b726b1110d2f35d5cf978e8428a337c3
[native] Clean up legacy custom_notification code
[ { "change_type": "MODIFY", "old_path": "native/push/android.js", "new_path": "native/push/android.js", "diff": "@@ -32,25 +32,12 @@ function handleAndroidMessage(\nfirebase.notifications().setBadge(parseInt(badge, 10));\n}\n- const customNotification = data.custom_notification\n- ? JSON.parse(data.custom_notification)\n- : null;\n- let { messageInfos } = data;\n- if (!messageInfos && customNotification) {\n- messageInfos = customNotification.messageInfos;\n- }\n+ const { messageInfos } = data;\nif (messageInfos) {\nsaveMessageInfos(messageInfos, updatesCurrentAsOf);\n}\n- let { rescind, rescindID } = data;\n- let rescindActionPayload = null;\n- if (rescind) {\n- rescindActionPayload = { notifID: rescindID, threadID: data.threadID };\n- } else if (customNotification) {\n- ({ rescind, notifID: rescindID } = customNotification);\n- rescindActionPayload = { notifID: rescindID };\n- }\n+ const { rescind, rescindID } = data;\nif (rescind) {\ninvariant(rescindID, 'rescind message without notifID');\nfirebase\n@@ -58,15 +45,12 @@ function handleAndroidMessage(\n.android.removeDeliveredNotificationsByTag(rescindID);\ndispatch({\ntype: rescindAndroidNotificationActionType,\n- payload: rescindActionPayload,\n+ payload: { notifID: rescindID, threadID: data.threadID },\n});\nreturn;\n}\nlet { id, title, prefix, body, threadID } = data;\n- if (!id && customNotification) {\n- ({ id, body, threadID } = customNotification);\n- }\n({ body } = mergePrefixIntoBody({ body, title, prefix }));\nif (handleIfActive) {\n" }, { "change_type": "MODIFY", "old_path": "native/push/reducer.js", "new_path": "native/push/reducer.js", "diff": "@@ -18,7 +18,7 @@ type ClearAndroidNotificationsPayload = {|\ntype RescindAndroidNotificationPayload = {|\nnotifID: string,\n- threadID?: string,\n+ threadID: string,\n|};\nexport type AndroidNotificationActions =\n@@ -55,7 +55,7 @@ function reduceThreadIDsToNotifIDs(\nif (!state[action.payload.threadID]) {\nreturn state;\n}\n- for (let notifID of state[action.payload.threadID]) {\n+ for (const notifID of state[action.payload.threadID]) {\ngetFirebase()\n.notifications()\n.android.removeDeliveredNotificationsByTag(notifID);\n@@ -66,7 +66,6 @@ function reduceThreadIDsToNotifIDs(\n};\n} else if (action.type === rescindAndroidNotificationActionType) {\nconst { threadID, notifID } = action.payload;\n- if (threadID) {\nconst existingNotifIDs = state[threadID];\nif (!existingNotifIDs) {\nreturn state;\n@@ -76,15 +75,6 @@ function reduceThreadIDsToNotifIDs(\nreturn state;\n}\nreturn { ...state, [threadID]: filtered };\n- }\n- for (let candThreadID in state) {\n- const existingNotifIDs = state[candThreadID];\n- const filtered = existingNotifIDs.filter(id => id !== notifID);\n- if (filtered.length !== existingNotifIDs.length) {\n- return { ...state, [candThreadID]: filtered };\n- }\n- }\n- return state;\n} else {\nreturn state;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Clean up legacy custom_notification code
129,187
19.08.2020 17:58:40
14,400
a8ab8071e139f99e3618187af085b3737774c6d5
[server] Rescind push notifs when somebody leaves a thread
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -37,6 +37,7 @@ import {\nupdateDatasForUserPairs,\nupdateUndirectedRelationships,\n} from '../updaters/relationship-updaters';\n+import { rescindPushNotifs } from '../push/rescind';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n@@ -583,8 +584,21 @@ async function commitMembershipChangeset(\n}\nconst toSave = [],\n- toDelete = [];\n+ toDelete = [],\n+ rescindPromises = [];\nfor (let row of membershipRowMap.values()) {\n+ if (\n+ row.operation === 'delete' ||\n+ (row.operation === 'update' && Number(row.role) <= 0)\n+ ) {\n+ const { userID, threadID } = row;\n+ rescindPromises.push(\n+ rescindPushNotifs(\n+ SQL`n.thread = ${threadID} AND n.user = ${userID}`,\n+ SQL`IF(m.thread = ${threadID}, NULL, m.thread)`,\n+ ),\n+ );\n+ }\nif (row.operation === 'delete') {\ntoDelete.push(row);\n} else {\n@@ -596,6 +610,7 @@ async function commitMembershipChangeset(\nsaveMemberships(toSave),\ndeleteMemberships(toDelete),\nupdateUndirectedRelationships(uniqueRelationshipRows),\n+ ...rescindPromises,\n]);\n// We fetch all threads here because old clients still expect the full list of\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Rescind push notifs when somebody leaves a thread
129,187
19.08.2020 18:00:35
14,400
1950ecef3b9fc8953b5325e9294c6933a94a4e74
[server] Rescind all notifs when somebody deletes their account
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -17,6 +17,7 @@ import { createNewAnonymousCookie } from '../session/cookies';\nimport { fetchAllUserIDs } from '../fetchers/user-fetchers';\nimport { createUpdates } from '../creators/update-creator';\nimport { handleAsyncPromise } from '../responders/handlers';\n+import { rescindPushNotifs } from '../push/rescind';\nasync function deleteAccount(\nviewer: Viewer,\n@@ -38,8 +39,10 @@ async function deleteAccount(\n}\n}\n- // TODO: if this results in any orphaned orgs, convert them to chats\nconst deletedUserID = viewer.userID;\n+ await rescindPushNotifs(SQL`n.user = ${deletedUserID}`, SQL`NULL`);\n+\n+ // TODO: if this results in any orphaned orgs, convert them to chats\nconst deletionQuery = SQL`\nDELETE u, iu, v, iv, c, ic, m, f, n, ino, up, iup, s, si, ru, rd\nFROM users u\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Rescind all notifs when somebody deletes their account
129,187
19.08.2020 18:28:41
14,400
46201365f388fc221a3ecd3ad865a42e1359dd25
[server] Log notifs rescinds to notifications table
[ { "change_type": "MODIFY", "old_path": "server/src/push/rescind.js", "new_path": "server/src/push/rescind.js", "diff": "@@ -4,9 +4,13 @@ import { threadPermissions } from 'lib/types/thread-types';\nimport { threadSubscriptions } from 'lib/types/subscription-types';\nimport apn from 'apn';\n+import invariant from 'invariant';\n+\n+import { promiseAll } from 'lib/utils/promises';\nimport { dbQuery, SQL, SQLStatement } from '../database';\nimport { apnPush, fcmPush } from './utils';\n+import createIDs from '../creators/id-creator';\nasync function rescindPushNotifs(\nnotifCondition: SQLStatement,\n@@ -15,7 +19,7 @@ async function rescindPushNotifs(\nconst notificationExtractString = `$.${threadSubscriptions.home}`;\nconst visPermissionExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst fetchQuery = SQL`\n- SELECT n.id, n.delivery, n.collapse_key, n.thread, COUNT(\n+ SELECT n.id, n.user, n.thread, n.message, n.delivery, n.collapse_key, COUNT(\n`;\nfetchQuery.append(inputCountCondition ? inputCountCondition : SQL`m.thread`);\nfetchQuery.append(SQL`\n@@ -30,12 +34,20 @@ async function rescindPushNotifs(\nfetchQuery.append(SQL` GROUP BY n.id, m.user`);\nconst [fetchResult] = await dbQuery(fetchQuery);\n- const promises = [];\n+ const deliveryPromises = {};\n+ const notifInfo = {};\nconst rescindedIDs = [];\nfor (let row of fetchResult) {\nconst deliveries = Array.isArray(row.delivery)\n? row.delivery\n: [row.delivery];\n+ const id = row.id.toString();\n+ const threadID = row.thread.toString();\n+ notifInfo[id] = {\n+ userID: row.user.toString(),\n+ threadID,\n+ messageID: row.message.toString(),\n+ };\nfor (let delivery of deliveries) {\nif (delivery.iosID && delivery.iosDeviceTokens) {\n// Old iOS\n@@ -43,37 +55,45 @@ async function rescindPushNotifs(\ndelivery.iosID,\nrow.unread_count,\n);\n- promises.push(apnPush(notification, delivery.iosDeviceTokens));\n+ deliveryPromises[id] = apnPush(notification, delivery.iosDeviceTokens);\n} else if (delivery.androidID) {\n// Old Android\nconst notification = prepareAndroidNotification(\n- row.collapse_key ? row.collapse_key : row.id.toString(),\n+ row.collapse_key ? row.collapse_key : id,\nrow.unread_count,\n- row.thread.toString(),\n+ threadID,\nnull,\n);\n- promises.push(\n- fcmPush(notification, delivery.androidDeviceTokens, null),\n+ deliveryPromises[id] = fcmPush(\n+ notification,\n+ delivery.androidDeviceTokens,\n+ null,\n);\n} else if (delivery.deviceType === 'ios') {\n// New iOS\nconst { iosID, deviceTokens } = delivery;\nconst notification = prepareIOSNotification(iosID, row.unread_count);\n- promises.push(apnPush(notification, deviceTokens));\n+ deliveryPromises[id] = apnPush(notification, deviceTokens);\n} else if (delivery.deviceType === 'android') {\n// New Android\nconst { deviceTokens, codeVersion } = delivery;\nconst notification = prepareAndroidNotification(\n- row.collapse_key ? row.collapse_key : row.id.toString(),\n+ row.collapse_key ? row.collapse_key : id,\nrow.unread_count,\n- row.thread.toString(),\n+ threadID,\ncodeVersion,\n);\n- promises.push(fcmPush(notification, deviceTokens, null));\n+ deliveryPromises[id] = fcmPush(notification, deviceTokens, null);\n}\n}\nrescindedIDs.push(row.id);\n}\n+\n+ const numRescinds = Object.keys(deliveryPromises).length;\n+ const promises = [promiseAll(deliveryPromises)];\n+ if (numRescinds > 0) {\n+ promises.push(createIDs('notifications', numRescinds));\n+ }\nif (rescindedIDs.length > 0) {\nconst rescindQuery = SQL`\nUPDATE notifications SET rescinded = 1 WHERE id IN (${rescindedIDs})\n@@ -81,7 +101,39 @@ async function rescindPushNotifs(\npromises.push(dbQuery(rescindQuery));\n}\n- await Promise.all(promises);\n+ const [deliveryResults, dbIDs] = await Promise.all(promises);\n+ const newNotifRows = [];\n+ if (numRescinds > 0) {\n+ invariant(dbIDs, 'dbIDs should be set');\n+ for (const rescindedID in deliveryResults) {\n+ const delivery = {};\n+ delivery.type = 'rescind';\n+ delivery.rescindedID = rescindedID;\n+ const { errors } = deliveryResults[rescindedID];\n+ if (errors) {\n+ delivery.errors = errors;\n+ }\n+ const dbID = dbIDs.shift();\n+ const { userID, threadID, messageID } = notifInfo[rescindedID];\n+ newNotifRows.push([\n+ dbID,\n+ userID,\n+ threadID,\n+ messageID,\n+ null,\n+ JSON.stringify([delivery]),\n+ 1,\n+ ]);\n+ }\n+ }\n+ if (newNotifRows.length > 0) {\n+ const insertQuery = SQL`\n+ INSERT INTO notifications\n+ (id, user, thread, message, collapse_key, delivery, rescinded)\n+ VALUES ${newNotifRows}\n+ `;\n+ await dbQuery(insertQuery);\n+ }\n}\nfunction prepareIOSNotification(\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Log notifs rescinds to notifications table
129,187
19.08.2020 18:43:07
14,400
3f2bfe1db921e6305860dd9d85ad9d5f870992b5
[native] Clear all notifs on log out
[ { "change_type": "MODIFY", "old_path": "native/push/push-handler.react.js", "new_path": "native/push/push-handler.react.js", "diff": "@@ -281,6 +281,10 @@ class PushHandler extends React.PureComponent<Props, State> {\nthis.ensurePushNotifsEnabled();\n}\n+ if (!this.props.loggedIn && prevProps.loggedIn) {\n+ this.clearAllNotifs();\n+ }\n+\nif (\nthis.state.inAppNotifProps &&\nthis.state.inAppNotifProps !== prevState.inAppNotifProps\n@@ -305,6 +309,16 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\n}\n+ clearAllNotifs() {\n+ if (Platform.OS === 'ios') {\n+ NotificationsIOS.removeAllDeliveredNotifications();\n+ } else if (Platform.OS === 'android') {\n+ getFirebase()\n+ .notifications()\n+ .removeAllDeliveredNotifications();\n+ }\n+ }\n+\nclearNotifsOfThread() {\nconst { activeThread } = this.props;\nif (!activeThread) {\n" }, { "change_type": "MODIFY", "old_path": "native/push/reducer.js", "new_path": "native/push/reducer.js", "diff": "// @flow\n+import {\n+ logOutActionTypes,\n+ deleteAccountActionTypes,\n+} from 'lib/actions/user-actions';\n+import { setNewSessionActionType } from 'lib/utils/action-utils';\n+\nimport {\nrecordAndroidNotificationActionType,\nclearAndroidNotificationsActionType,\n@@ -75,6 +81,13 @@ function reduceThreadIDsToNotifIDs(\nreturn state;\n}\nreturn { ...state, [threadID]: filtered };\n+ } else if (\n+ action.type === logOutActionTypes.success ||\n+ action.type === deleteAccountActionTypes.success ||\n+ (action.type === setNewSessionActionType &&\n+ action.payload.sessionChange.cookieInvalidated)\n+ ) {\n+ return {};\n} else {\nreturn state;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Clear all notifs on log out
129,183
24.08.2020 14:33:36
-7,200
0c68f9e056b644d574ef148d2a731e3f8233145b
[web] Add list to markdown in web Reviewers: ashoat Subscribers: zrebcu411
[ { "change_type": "MODIFY", "old_path": "lib/shared/markdown.js", "new_path": "lib/shared/markdown.js", "diff": "// @flow\n+// simple-markdown types\n+type State = {|\n+ key?: string | number | void,\n+ inline?: ?boolean,\n+ [string]: any,\n+|};\n+\n+type Parser = (source: string, state?: ?State) => Array<SingleASTNode>;\n+\n+type Capture =\n+ | (Array<string> & { index: number })\n+ | (Array<string> & { index?: number });\n+\n+type SingleASTNode = {|\n+ type: string,\n+ [string]: any,\n+|};\n+\n+type UnTypedASTNode = {\n+ [string]: any,\n+ ...,\n+};\n+\nconst paragraphRegex = /^((?:[^\\n]*)(?:\\n|$))/;\nconst paragraphStripTrailingNewlineRegex = /^([^\\n]*)(?:\\n|$)/;\n@@ -64,6 +87,60 @@ function jsonPrint(capture: JSONCapture): string {\nreturn JSON.stringify(capture.json, null, ' ');\n}\n+const listRegex = /^( *)([*+-]|\\d+\\.) ([\\s\\S]+?)(?:\\n{3}|\\s*\\n*$)/;\n+const listItemRegex = /^( *)([*+-]|\\d+\\.) [^\\n]*(?:\\n(?!\\1(?:[*+-]|\\d+\\.) )[^\\n]*)*(\\n|$)/gm;\n+const listItemPrefixRegex = /^( *)([*+-]|\\d+\\.) /;\n+const listLookBehindRegex = /(?:^|\\n)( *)$/;\n+\n+function matchList(source: string, state: State) {\n+ if (state.inline) {\n+ return null;\n+ }\n+ const prevCaptureStr = state.prevCapture ? state.prevCapture[0] : '';\n+ const isStartOfLineCapture = listLookBehindRegex.exec(prevCaptureStr);\n+ if (!isStartOfLineCapture) {\n+ return null;\n+ }\n+ const fullSource = isStartOfLineCapture[1] + source;\n+ return listRegex.exec(fullSource);\n+}\n+\n+// We've defined our own parse function for lists because simple-markdown\n+// handles newlines differently. Outside of that our implementation is fairly\n+// similar. For more details about list parsing works, take a look at the\n+// comments in the simple-markdown package\n+function parseList(\n+ capture: Capture,\n+ parse: Parser,\n+ state: State,\n+): UnTypedASTNode {\n+ const bullet = capture[2];\n+ const ordered = bullet.length > 1;\n+ const start = ordered ? Number(bullet) : undefined;\n+ const items = capture[0].match(listItemRegex);\n+\n+ let itemContent = null;\n+ if (items) {\n+ itemContent = items.map((item: string) => {\n+ const prefixCapture = listItemPrefixRegex.exec(item);\n+ const space = prefixCapture ? prefixCapture[0].length : 0;\n+ const spaceRegex = new RegExp('^ {1,' + space + '}', 'gm');\n+ const content: string = item\n+ .replace(spaceRegex, '')\n+ .replace(listItemPrefixRegex, '');\n+ // We're handling this different than simple-markdown -\n+ // each item is a paragraph\n+ return parse(content, state);\n+ });\n+ }\n+\n+ return {\n+ ordered: ordered,\n+ start: start,\n+ items: itemContent,\n+ };\n+}\n+\nexport {\nparagraphRegex,\nparagraphStripTrailingNewlineRegex,\n@@ -78,4 +155,6 @@ export {\nfenceStripTrailingNewlineRegex,\njsonMatch,\njsonPrint,\n+ matchList,\n+ parseList,\n};\n" }, { "change_type": "MODIFY", "old_path": "web/markdown/markdown.css", "new_path": "web/markdown/markdown.css", "diff": "@@ -60,5 +60,11 @@ div.markdown pre > code {\ndisplay: inline-block;\nbox-sizing: border-box;\ntab-size: 2;\n- overflow-x: scroll;\n+ overflow-x: auto;\n+}\n+\n+div.markdown ol,\n+div.markdown ul {\n+ padding-left: 1em;\n+ margin-left: 0.5em;\n}\n" }, { "change_type": "MODIFY", "old_path": "web/markdown/rules.react.js", "new_path": "web/markdown/rules.react.js", "diff": "@@ -123,6 +123,12 @@ function markdownRules(): MarkdownRuleSpec {\ncontent: SharedMarkdown.jsonPrint(capture),\n}),\n},\n+ list: {\n+ ...SimpleMarkdown.defaultRules.list,\n+ match: SharedMarkdown.matchList,\n+ parse: SharedMarkdown.parseList,\n+ },\n+ escape: SimpleMarkdown.defaultRules.escape,\n};\nreturn {\n...linkMarkdownRules,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Add list to markdown in web Reviewers: ashoat Reviewed By: ashoat Subscribers: zrebcu411 Differential Revision: https://phabricator.ashoat.com/D10
129,183
24.08.2020 14:36:20
-7,200
8b9a34c5959ce9939d37bbe8d3dfe54158d7cef2
[native] Add list to markdown in native Reviewers: ashoat Subscribers: zrebcu411
[ { "change_type": "MODIFY", "old_path": "native/markdown/rules.react.js", "new_path": "native/markdown/rules.react.js", "diff": "@@ -305,6 +305,32 @@ function fullMarkdownRules(\ncontent: SharedMarkdown.jsonPrint(capture),\n}),\n},\n+ list: {\n+ ...SimpleMarkdown.defaultRules.list,\n+ match: SharedMarkdown.matchList,\n+ parse: SharedMarkdown.parseList,\n+ react(\n+ node: SimpleMarkdown.SingleASTNode,\n+ output: SimpleMarkdown.Output<SimpleMarkdown.ReactElement>,\n+ state: SimpleMarkdown.State,\n+ ) {\n+ const children = node.items.map((item, i) => {\n+ const content = output(item, state);\n+ const bulletValue = node.ordered ? node.start + i + '. ' : '\\u2022 ';\n+ return (\n+ <View key={i} style={styles.listRow}>\n+ <Text style={[state.textStyle, styles.listBulletStyle]}>\n+ {bulletValue}\n+ </Text>\n+ <View style={styles.insideListView}>{content}</View>\n+ </View>\n+ );\n+ });\n+\n+ return <View key={state.key}>{children}</View>;\n+ },\n+ },\n+ escape: SimpleMarkdown.defaultRules.escape,\n};\nreturn {\n...inlineRules,\n" }, { "change_type": "MODIFY", "old_path": "native/markdown/styles.js", "new_path": "native/markdown/styles.js", "diff": "@@ -83,6 +83,15 @@ const unboundStyles = {\ndefault: 18,\n}),\n},\n+ listBulletStyle: {\n+ fontWeight: 'bold',\n+ },\n+ listRow: {\n+ flexDirection: 'row',\n+ },\n+ insideListView: {\n+ flexShrink: 1,\n+ },\n};\nexport type MarkdownStyles = typeof unboundStyles;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Add list to markdown in native Reviewers: ashoat Reviewed By: ashoat Subscribers: zrebcu411 Differential Revision: https://phabricator.ashoat.com/D11
129,187
24.08.2020 12:32:46
14,400
d3385e8640d4bbcf2222b6e484103e609e40316f
[server] Only update memberships with role > 0 when creating/deleting roles Reviewers: zrebcu411 Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/role-updaters.js", "new_path": "server/src/updaters/role-updaters.js", "diff": "@@ -43,7 +43,7 @@ async function updateRoles(\nconst setAdminQuery = SQL`\nUPDATE memberships\nSET role = ${id}\n- WHERE thread = ${threadID} AND user = ${viewer.userID}\n+ WHERE thread = ${threadID} AND user = ${viewer.userID} AND role > 0\n`;\npromises.push(dbQuery(setAdminQuery));\n} else if (!rolePermissions.Admins && currentRolePermissions.Admins) {\n@@ -59,7 +59,7 @@ async function updateRoles(\nconst updateMembershipsQuery = SQL`\nUPDATE memberships\nSET role = ${currentRoleIDs.Members}\n- WHERE thread = ${threadID}\n+ WHERE thread = ${threadID} AND role > 0\n`;\npromises.push(dbQuery(updateMembershipsQuery));\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Only update memberships with role > 0 when creating/deleting roles Reviewers: zrebcu411 Reviewed By: zrebcu411 Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D22
129,186
11.08.2020 16:27:52
-7,200
c7e164f6e88f1ee3cacb2c15d87d06ad8ecafeeb
[server] Handle users who have left a thread Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/thread-deleters.js", "new_path": "server/src/deleters/thread-deleters.js", "diff": "@@ -140,10 +140,11 @@ async function deleteInaccessibleThreads(): Promise<void> {\n// that membership rows exist whenever a user can see a thread, even if they\n// are not technically a member (in which case role=0)\nawait dbQuery(SQL`\n- DELETE t, i, d, id, e, ie, re, ire, r, ir, ms, im, up, iu, f, n, ino\n+ DELETE t, i, m2, d, id, e, ie, re, ire, r, ir, ms, im, up, iu, f, n, ino\nFROM threads t\nLEFT JOIN ids i ON i.id = t.id\n- LEFT JOIN memberships m ON m.thread = t.id\n+ LEFT JOIN memberships m1 ON m1.thread = t.id AND m1.role > -1\n+ LEFT JOIN memberships m2 ON m2.thread = t.id\nLEFT JOIN days d ON d.thread = t.id\nLEFT JOIN ids id ON id.id = d.id\nLEFT JOIN entries e ON e.day = d.id\n@@ -159,7 +160,7 @@ async function deleteInaccessibleThreads(): Promise<void> {\nLEFT JOIN focused f ON f.thread = t.id\nLEFT JOIN notifications n ON n.thread = t.id\nLEFT JOIN ids ino ON ino.id = n.id\n- WHERE m.thread IS NULL\n+ WHERE m1.thread IS NULL\n`);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -114,7 +114,7 @@ async function changeRole(\nif (oldRole === roleThreadResult.roleColumnValue) {\n// If the old role is the same as the new one, we have nothing to update\ncontinue;\n- } else if (oldRole !== '0' && role === null) {\n+ } else if (Number(oldRole) > 0 && role === null) {\n// In the case where we're just trying to add somebody to a thread, if\n// they already have a role with a nonzero role then we don't need to do\n// anything\n@@ -137,7 +137,7 @@ async function changeRole(\nmembershipRows.push({\noperation:\nroleThreadResult.roleColumnValue !== '0' &&\n- (!userRoleInfo || userRoleInfo.oldRole === '0')\n+ (!userRoleInfo || Number(userRoleInfo.oldRole) <= 0)\n? 'join'\n: 'update',\nuserID,\n@@ -519,8 +519,8 @@ async function saveMemberships(toSave: $ReadOnlyArray<MembershipRowToSave>) {\nVALUES ${insertRows}\nON DUPLICATE KEY UPDATE\nsubscription = IF(\n- (role = 0 AND VALUES(role) != 0)\n- OR (role != 0 AND VALUES(role) = 0),\n+ (role <= 0 AND VALUES(role) > 0)\n+ OR (role > 0 AND VALUES(role) <= 0),\nVALUES(subscription),\nsubscription\n),\n@@ -542,7 +542,7 @@ async function deleteMemberships(\nSQL`(user = ${rowToDelete.userID} AND thread = ${rowToDelete.threadID})`,\n);\nconst conditions = mergeOrConditions(deleteRows);\n- const query = SQL`DELETE FROM memberships WHERE `;\n+ const query = SQL`UPDATE memberships SET role = -1 WHERE `;\nquery.append(conditions);\nawait dbQuery(query);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Handle users who have left a thread Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D12
129,186
11.08.2020 16:36:07
-7,200
2edc85c852f6128d09b188a7b50081d9724cf6ec
[server] Update state sync Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -66,7 +66,10 @@ import {\n} from '../fetchers/message-fetchers';\nimport { fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\n-import { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\n+import {\n+ fetchCurrentUserInfo,\n+ fetchKnownUserInfos,\n+} from '../fetchers/user-fetchers';\nimport { updateActivityTime } from '../updaters/activity-updaters';\nimport { deleteUpdatesBeforeTimeTargettingSession } from '../deleters/update-deleters';\nimport { fetchUpdateInfos } from '../fetchers/update-fetchers';\n@@ -433,24 +436,20 @@ class Socket {\nthreadsResult,\nentriesResult,\ncurrentUserInfo,\n+ knownUserInfos,\n] = await Promise.all([\nfetchThreadInfos(viewer),\nfetchEntryInfos(viewer, [calendarQuery]),\nfetchCurrentUserInfo(viewer),\n+ fetchKnownUserInfos(viewer),\n]);\n- // $FlowFixMe should be fixed in flow-bin@0.115 / react-native@0.63\n- const userInfos = values({\n- ...fetchMessagesResult.userInfos,\n- ...entriesResult.userInfos,\n- ...threadsResult.userInfos,\n- });\nconst payload: StateSyncFullSocketPayload = {\ntype: stateSyncPayloadTypes.FULL,\nmessagesResult,\nthreadInfos: threadsResult.threadInfos,\ncurrentUserInfo,\nrawEntryInfos: entriesResult.rawEntryInfos,\n- userInfos,\n+ userInfos: values(knownUserInfos),\nupdatesCurrentAsOf: oldUpdatesCurrentAsOf,\n};\nif (viewer.sessionChanged) {\n@@ -489,8 +488,7 @@ class Socket {\npromises.sessionUpdate = commitSessionUpdate(viewer, sessionUpdate);\nconst { fetchUpdateResult } = await promiseAll(promises);\n- const updateUserInfos = fetchUpdateResult.userInfos;\n- const { updateInfos } = fetchUpdateResult;\n+ const { updateInfos, userInfos } = fetchUpdateResult;\nconst newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n[...updateInfos],\noldUpdatesCurrentAsOf,\n@@ -509,11 +507,7 @@ class Socket {\nupdatesResult,\ndeltaEntryInfos: deltaEntryInfoResult.rawEntryInfos,\ndeletedEntryIDs: deltaEntryInfoResult.deletedEntryIDs,\n- userInfos: values({\n- ...fetchMessagesResult.userInfos,\n- ...updateUserInfos,\n- ...deltaEntryInfoResult.userInfos,\n- }),\n+ userInfos: values(userInfos),\n},\n});\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Update state sync Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D13
129,186
11.08.2020 16:44:10
-7,200
ac284eb442c7fb64c8a63e8d637b859e8e4af7b7
[server] Update updateInfosFromRawUpdateInfos Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -31,9 +31,6 @@ import _uniq from 'lodash/fp/uniq';\nimport _intersection from 'lodash/fp/intersection';\nimport { promiseAll } from 'lib/utils/promises';\n-import { usersInRawEntryInfos } from 'lib/shared/entry-utils';\n-import { usersInThreadInfo } from 'lib/shared/thread-utils';\n-import { usersInMessageInfos } from 'lib/shared/message-utils';\nimport { nonThreadCalendarFilters } from 'lib/selectors/calendar-filter-selectors';\nimport {\nkeyForUpdateData,\n@@ -56,7 +53,7 @@ import {\nfetchEntryInfosByID,\n} from '../fetchers/entry-fetchers';\nimport {\n- fetchUserInfos,\n+ fetchKnownUserInfos,\nfetchLoggedInUserInfos,\n} from '../fetchers/user-fetchers';\nimport { channelNameForUpdateTarget, publisher } from '../socket/redis';\n@@ -512,7 +509,7 @@ async function updateInfosFromRawUpdateInfos(\ncurrentUserInfosResult,\n} = rawData;\nconst updateInfos = [];\n- let userIDs = new Set();\n+ const userIDsToFetch = new Set();\nfor (let rawUpdateInfo of rawUpdateInfos) {\nif (rawUpdateInfo.type === updateTypes.DELETE_ACCOUNT) {\nupdateInfos.push({\n@@ -524,7 +521,6 @@ async function updateInfosFromRawUpdateInfos(\n} else if (rawUpdateInfo.type === updateTypes.UPDATE_THREAD) {\nconst threadInfo = threadInfosResult.threadInfos[rawUpdateInfo.threadID];\ninvariant(threadInfo, 'should be set');\n- userIDs = new Set([...userIDs, ...usersInThreadInfo(threadInfo)]);\nupdateInfos.push({\ntype: updateTypes.UPDATE_THREAD,\nid: rawUpdateInfo.id,\n@@ -563,12 +559,6 @@ async function updateInfosFromRawUpdateInfos(\nrawMessageInfos.push(messageInfo);\n}\n}\n- userIDs = new Set([\n- ...userIDs,\n- ...usersInThreadInfo(threadInfo),\n- ...usersInRawEntryInfos(rawEntryInfos),\n- ...usersInMessageInfos(rawMessageInfos),\n- ]);\nupdateInfos.push({\ntype: updateTypes.JOIN_THREAD,\nid: rawUpdateInfo.id,\n@@ -592,7 +582,6 @@ async function updateInfosFromRawUpdateInfos(\ncandidate => candidate.id === rawUpdateInfo.entryID,\n);\ninvariant(entryInfo, 'should be set');\n- userIDs = new Set([...userIDs, ...usersInRawEntryInfos([entryInfo])]);\nupdateInfos.push({\ntype: updateTypes.UPDATE_ENTRY,\nid: rawUpdateInfo.id,\n@@ -618,31 +607,15 @@ async function updateInfosFromRawUpdateInfos(\ntime: rawUpdateInfo.time,\nupdatedUserID: rawUpdateInfo.updatedUserID,\n});\n- userIDs = new Set([...userIDs, rawUpdateInfo.updatedUserID]);\n+ userIDsToFetch.add(rawUpdateInfo.updatedUserID);\n} else {\ninvariant(false, `unrecognized updateType ${rawUpdateInfo.type}`);\n}\n}\n- const userInfos = {};\n- const userIDsToFetch = [];\n- for (let userID of userIDs) {\n- const userInfo = threadInfosResult.userInfos[userID];\n- if (userInfo) {\n- userInfos[userID] = userInfo;\n- } else {\n- userIDsToFetch.push(userID);\n- }\n- }\n- if (userIDsToFetch.length > 0) {\n- const fetchedUserInfos = await fetchUserInfos(userIDsToFetch);\n- for (let userID in fetchedUserInfos) {\n- const userInfo = fetchedUserInfos[userID];\n- if (userInfo && userInfo.username) {\n- const { id, username } = userInfo;\n- userInfos[userID] = { id, username };\n- }\n- }\n+ let userInfos = {};\n+ if (userIDsToFetch.size > 0) {\n+ userInfos = await fetchKnownUserInfos(viewer, [...userIDsToFetch]);\n}\nupdateInfos.sort(sortFunction);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Update updateInfosFromRawUpdateInfos Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D14
129,186
12.08.2020 09:39:28
-7,200
52be307702650e38580febdcae010e0c7fb8b6ad
[server] Update MessagesServerSocketMessage Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -777,9 +777,8 @@ export type SaveMessagesPayload = {|\nupdatesCurrentAsOf: number,\n|};\n-export type MessagesResultWithUserInfos = {|\n+export type NewMessagesPayload = {|\nmessagesResult: MessagesResponse,\n- userInfos: $ReadOnlyArray<UserInfo>,\n|};\nexport type MessageStorePrunePayload = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -36,7 +36,7 @@ import type {\nFetchMessageInfosPayload,\nSendMessagePayload,\nSaveMessagesPayload,\n- MessagesResultWithUserInfos,\n+ NewMessagesPayload,\nMessageStorePrunePayload,\nLocallyComposedMessageInfo,\n} from './message-types';\n@@ -738,7 +738,7 @@ export type BaseAction =\n|}\n| {|\ntype: 'PROCESS_MESSAGES',\n- payload: MessagesResultWithUserInfos,\n+ payload: NewMessagesPayload,\n|}\n| {|\ntype: 'MESSAGE_STORE_PRUNE',\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -7,10 +7,7 @@ import type {\nClientClientResponse,\n} from './request-types';\nimport type { RawThreadInfo } from './thread-types';\n-import type {\n- MessagesResponse,\n- MessagesResultWithUserInfos,\n-} from './message-types';\n+import type { MessagesResponse, NewMessagesPayload } from './message-types';\nimport type { UpdatesResult, UpdatesResultWithUserInfos } from './update-types';\nimport type {\nUserInfo,\n@@ -245,7 +242,7 @@ export type UpdatesServerSocketMessage = {|\n|};\nexport type MessagesServerSocketMessage = {|\ntype: 7,\n- payload: MessagesResultWithUserInfos,\n+ payload: NewMessagesPayload,\n|};\nexport type APIResponseServerSocketMessage = {|\ntype: 8,\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/socket.js", "new_path": "server/src/socket/socket.js", "diff": "@@ -684,7 +684,6 @@ class Socket {\n0,\n),\n},\n- userInfos: values(messageFetchResult.userInfos),\n},\n});\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Update MessagesServerSocketMessage Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D15
129,186
13.08.2020 12:48:30
-7,200
fc1607a2691a0c48272e53960f77bb48191f6c07
Clean up actions/responders that currently deliver userInfos Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "lib/actions/entry-actions.js", "new_path": "lib/actions/entry-actions.js", "diff": "@@ -18,7 +18,6 @@ import type { FetchJSON } from '../utils/fetch-json';\nimport type { HistoryRevisionInfo } from '../types/history-types';\nimport { dateFromString } from '../utils/date-utils';\n-import { values } from '../utils/objects';\nconst fetchEntriesActionTypes = Object.freeze({\nstarted: 'FETCH_ENTRIES_STARTED',\n@@ -32,7 +31,6 @@ async function fetchEntries(\nconst response = await fetchJSON('fetch_entries', calendarQuery);\nreturn {\nrawEntryInfos: response.rawEntryInfos,\n- userInfos: values(response.userInfos),\n};\n}\n@@ -47,11 +45,10 @@ async function updateCalendarQuery(\nreduxAlreadyUpdated: boolean = false,\n): Promise<CalendarQueryUpdateResult> {\nconst response = await fetchJSON('update_calendar_query', calendarQuery);\n- const { rawEntryInfos, deletedEntryIDs, userInfos } = response;\n+ const { rawEntryInfos, deletedEntryIDs } = response;\nreturn {\nrawEntryInfos,\ndeletedEntryIDs,\n- userInfos,\ncalendarQuery,\ncalendarQueryAlreadyUpdated: reduxAlreadyUpdated,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/actions/message-actions.js", "new_path": "lib/actions/message-actions.js", "diff": "@@ -6,8 +6,6 @@ import type {\nSendMessageResult,\n} from '../types/message-types';\n-import { values } from '../utils/objects';\n-\nconst fetchMessagesBeforeCursorActionTypes = Object.freeze({\nstarted: 'FETCH_MESSAGES_BEFORE_CURSOR_STARTED',\nsuccess: 'FETCH_MESSAGES_BEFORE_CURSOR_SUCCESS',\n@@ -27,7 +25,6 @@ async function fetchMessagesBeforeCursor(\nthreadID,\nrawMessageInfos: response.rawMessageInfos,\ntruncationStatus: response.truncationStatuses[threadID],\n- userInfos: values(response.userInfos),\n};\n}\n@@ -49,7 +46,6 @@ async function fetchMostRecentMessages(\nthreadID,\nrawMessageInfos: response.rawMessageInfos,\ntruncationStatus: response.truncationStatuses[threadID],\n- userInfos: values(response.userInfos),\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/actions/thread-actions.js", "new_path": "lib/actions/thread-actions.js", "diff": "@@ -135,7 +135,6 @@ async function joinThread(\ncalendarResult: {\ncalendarQuery: request.calendarQuery,\nrawEntryInfos: response.rawEntryInfos,\n- userInfos,\n},\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -145,7 +145,6 @@ async function logIn(\ncalendarResult: {\ncalendarQuery: logInInfo.calendarQuery,\nrawEntryInfos: response.rawEntryInfos,\n- userInfos,\n},\nmessagesResult: {\nmessageInfos: response.rawMessageInfos,\n@@ -183,7 +182,6 @@ async function resetPassword(\ncalendarResult: {\ncalendarQuery: updatePasswordInfo.calendarQuery,\nrawEntryInfos: response.rawEntryInfos,\n- userInfos,\n},\nmessagesResult: {\nmessageInfos: response.rawMessageInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -22,8 +22,6 @@ import _isEqual from 'lodash/fp/isEqual';\nimport { setNewSessionActionType } from '../utils/action-utils';\nimport {\n- fetchEntriesActionTypes,\n- updateCalendarQueryActionTypes,\ncreateEntryActionTypes,\nsaveEntryActionTypes,\ndeleteEntryActionTypes,\n@@ -36,13 +34,8 @@ import {\nregisterActionTypes,\nresetPasswordActionTypes,\nchangeUserSettingsActionTypes,\n- searchUsersActionTypes,\n} from '../actions/user-actions';\nimport { joinThreadActionTypes } from '../actions/thread-actions';\n-import {\n- fetchMessagesBeforeCursorActionTypes,\n- fetchMostRecentMessagesActionTypes,\n-} from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\nimport { actionLogger } from '../utils/action-logger';\nimport { sanitizeAction } from '../utils/sanitization';\n@@ -139,14 +132,7 @@ function findInconsistencies(\n}\nfunction reduceUserInfos(state: UserStore, action: BaseAction): UserStore {\n- if (\n- action.type === joinThreadActionTypes.success ||\n- action.type === fetchMessagesBeforeCursorActionTypes.success ||\n- action.type === fetchMostRecentMessagesActionTypes.success ||\n- action.type === fetchEntriesActionTypes.success ||\n- action.type === updateCalendarQueryActionTypes.success ||\n- action.type === searchUsersActionTypes.success\n- ) {\n+ if (action.type === joinThreadActionTypes.success) {\nconst newUserInfos = _keyBy(userInfo => userInfo.id)(\naction.payload.userInfos,\n);\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/user-selectors.js", "new_path": "lib/selectors/user-selectors.js", "diff": "@@ -173,6 +173,7 @@ export {\nuserIDsToRelativeUserInfos,\nrelativeMemberInfoSelectorForMembersOfThread,\nuserInfoSelectorForOtherMembersOfThread,\n+ searchIndexFromUserInfos,\nuserSearchIndexForOtherMembersOfThread,\nisLoggedIn,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/entry-types.js", "new_path": "lib/types/entry-types.js", "diff": "// @flow\nimport type { RawMessageInfo } from './message-types';\n-import type { UserInfo, AccountUserInfo } from './user-types';\n+import type { AccountUserInfo } from './user-types';\nimport {\ntype CalendarFilter,\ncalendarFilterPropType,\n@@ -203,13 +203,11 @@ export type FetchEntryInfosResponse = {|\n|};\nexport type FetchEntryInfosResult = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n- userInfos: $ReadOnlyArray<AccountUserInfo>,\n|};\nexport type DeltaEntryInfosResponse = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\ndeletedEntryIDs: $ReadOnlyArray<string>,\n- userInfos: { [id: string]: AccountUserInfo },\n|};\nexport type DeltaEntryInfosResult = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n@@ -220,7 +218,6 @@ export type DeltaEntryInfosResult = {|\nexport type CalendarResult = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\ncalendarQuery: CalendarQuery,\n- userInfos: $ReadOnlyArray<UserInfo>,\n|};\nexport type CalendarQueryUpdateStartingPayload = {|\n@@ -229,7 +226,6 @@ export type CalendarQueryUpdateStartingPayload = {|\nexport type CalendarQueryUpdateResult = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\ndeletedEntryIDs: $ReadOnlyArray<string>,\n- userInfos: $ReadOnlyArray<AccountUserInfo>,\ncalendarQuery: CalendarQuery,\ncalendarQueryAlreadyUpdated: boolean,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -9,7 +9,6 @@ import {\nimport {\ntype RelativeUserInfo,\nrelativeUserInfoPropType,\n- type UserInfo,\ntype UserInfos,\n} from './user-types';\nimport { type Media, type Image, mediaPropType } from './media-types';\n@@ -730,7 +729,6 @@ export type FetchMessageInfosPayload = {|\nthreadID: string,\nrawMessageInfos: RawMessageInfo[],\ntruncationStatus: MessageTruncationStatus,\n- userInfos: UserInfo[],\n|};\nexport type MessagesResponse = {|\nrawMessageInfos: RawMessageInfo[],\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -17,7 +17,6 @@ import {\naccountUserInfoPropType,\n} from 'lib/types/user-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n-import type { UserSearchResult } from 'lib/types/search-types';\nimport type { ChatNavigationProp } from './chat.react';\nimport type { NavigationRoute } from '../navigation/route-names';\n@@ -32,7 +31,6 @@ import { createSelector } from 'reselect';\nimport { connect } from 'lib/utils/redux-utils';\nimport { newThreadActionTypes, newThread } from 'lib/actions/thread-actions';\n-import { searchUsersActionTypes, searchUsers } from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport {\nuserInfoSelectorForOtherMembersOfThread,\n@@ -41,7 +39,6 @@ import {\nimport SearchIndex from 'lib/shared/search-index';\nimport { threadInFilterList, userIsMember } from 'lib/shared/thread-utils';\nimport { getUserSearchResults } from 'lib/shared/search-utils';\n-import { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport TagInput from '../components/tag-input.react';\n@@ -83,7 +80,6 @@ type Props = {|\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\nnewThread: (request: NewThreadRequest) => Promise<NewThreadResult>,\n- searchUsers: (usernamePrefix: string) => Promise<UserSearchResult>,\n|};\ntype State = {|\nusernameInputText: string,\n@@ -114,7 +110,6 @@ class ComposeThread extends React.PureComponent<Props, State> {\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nnewThread: PropTypes.func.isRequired,\n- searchUsers: PropTypes.func.isRequired,\n};\nstate = {\nusernameInputText: '',\n@@ -141,10 +136,6 @@ class ComposeThread extends React.PureComponent<Props, State> {\n});\n}\n- componentDidMount() {\n- this.searchUsers('');\n- }\n-\ncomponentDidUpdate(prevProps: Props) {\nconst oldReduxParentThreadInfo = prevProps.parentThreadInfo;\nconst newReduxParentThreadInfo = this.props.parentThreadInfo;\n@@ -323,17 +314,9 @@ class ComposeThread extends React.PureComponent<Props, State> {\ntagDataLabelExtractor = (userInfo: AccountUserInfo) => userInfo.username;\nsetUsernameInputText = (text: string) => {\n- this.searchUsers(text);\nthis.setState({ usernameInputText: text });\n};\n- searchUsers(usernamePrefix: string) {\n- this.props.dispatchActionPromise(\n- searchUsersActionTypes,\n- this.props.searchUsers(usernamePrefix),\n- );\n- }\n-\nonUserSelect = (userID: string) => {\nfor (let existingUserInfo of this.state.userInfoInputArray) {\nif (userID === existingUserInfo.id) {\n@@ -500,7 +483,6 @@ const styles = {\nconst stylesSelector = styleSelector(styles);\nconst loadingStatusSelector = createLoadingStatusSelector(newThreadActionTypes);\n-registerFetchKey(searchUsersActionTypes);\nexport default connect(\n(\n@@ -527,5 +509,5 @@ export default connect(\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\n};\n},\n- { newThread, searchUsers },\n+ { newThread },\n)(ComposeThread);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/add-users-modal.react.js", "new_path": "native/chat/settings/add-users-modal.react.js", "diff": "@@ -12,7 +12,6 @@ import {\naccountUserInfoPropType,\n} from 'lib/types/user-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n-import type { UserSearchResult } from 'lib/types/search-types';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\nimport type { RootNavigationProp } from '../../navigation/root-navigator.react';\n@@ -35,9 +34,7 @@ import {\nchangeThreadSettingsActionTypes,\nchangeThreadSettings,\n} from 'lib/actions/thread-actions';\n-import { searchUsersActionTypes, searchUsers } from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n-import { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { threadActualMembers } from 'lib/shared/thread-utils';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\n@@ -73,7 +70,6 @@ type Props = {|\nchangeThreadSettings: (\nrequest: UpdateThreadRequest,\n) => Promise<ChangeThreadSettingsPayload>,\n- searchUsers: (usernamePrefix: string) => Promise<UserSearchResult>,\n|};\ntype State = {|\nusernameInputText: string,\n@@ -97,7 +93,6 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nchangeThreadSettings: PropTypes.func.isRequired,\n- searchUsers: PropTypes.func.isRequired,\n};\nstate = {\nusernameInputText: '',\n@@ -105,17 +100,6 @@ class AddUsersModal extends React.PureComponent<Props, State> {\n};\ntagInput: ?TagInput<AccountUserInfo> = null;\n- componentDidMount() {\n- this.searchUsers('');\n- }\n-\n- searchUsers(usernamePrefix: string) {\n- this.props.dispatchActionPromise(\n- searchUsersActionTypes,\n- this.props.searchUsers(usernamePrefix),\n- );\n- }\n-\nuserSearchResultsSelector = createSelector(\n(propsAndState: PropsAndState) => propsAndState.usernameInputText,\n(propsAndState: PropsAndState) => propsAndState.otherUserInfos,\n@@ -234,7 +218,6 @@ class AddUsersModal extends React.PureComponent<Props, State> {\nif (this.props.changeThreadSettingsLoadingStatus === 'loading') {\nreturn;\n}\n- this.searchUsers(text);\nthis.setState({ usernameInputText: text });\n};\n@@ -341,7 +324,6 @@ const stylesSelector = styleSelector(styles);\nconst changeThreadSettingsLoadingStatusSelector = createLoadingStatusSelector(\nchangeThreadSettingsActionTypes,\n);\n-registerFetchKey(searchUsersActionTypes);\nexport default connect(\n(\n@@ -367,5 +349,5 @@ export default connect(\nstyles: stylesSelector(state),\n};\n},\n- { changeThreadSettings, searchUsers },\n+ { changeThreadSettings },\n)(AddUsersModal);\n" }, { "change_type": "MODIFY", "old_path": "native/more/add-friends-modal.react.js", "new_path": "native/more/add-friends-modal.react.js", "diff": "@@ -11,14 +11,11 @@ import * as React from 'react';\nimport { Text, View } from 'react-native';\nimport { CommonActions } from '@react-navigation/native';\nimport { createSelector } from 'reselect';\n+import _keyBy from 'lodash/fp/keyBy';\n-import {\n- userInfoSelectorForOtherMembersOfThread,\n- userSearchIndexForOtherMembersOfThread,\n-} from 'lib/selectors/user-selectors';\n+import { searchIndexFromUserInfos } from 'lib/selectors/user-selectors';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { getUserSearchResults } from 'lib/shared/search-utils';\n-import SearchIndex from 'lib/shared/search-index';\nimport { connect } from 'lib/utils/redux-utils';\nimport { searchUsersActionTypes, searchUsers } from 'lib/actions/user-actions';\n@@ -38,8 +35,7 @@ type Props = {|\nnavigation: RootNavigationProp<'AddFriendsModal'>,\nroute: NavigationRoute<'AddFriendsModal'>,\n// Redux state\n- otherUserInfos: { [id: string]: AccountUserInfo },\n- userSearchIndex: SearchIndex,\n+ viewerID: ?string,\nstyles: typeof styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n@@ -51,6 +47,7 @@ type Props = {|\ntype State = {|\nusernameInputText: string,\nuserInfoInputArray: $ReadOnlyArray<AccountUserInfo>,\n+ userInfos: { [id: string]: AccountUserInfo },\n|};\ntype PropsAndState = {| ...Props, ...State |};\n@@ -59,6 +56,7 @@ class AddFriendsModal extends React.PureComponent<Props, State> {\nstate = {\nusernameInputText: '',\nuserInfoInputArray: [],\n+ userInfos: {},\n};\ntagInput: ?TagInput<AccountUserInfo> = null;\n@@ -66,26 +64,26 @@ class AddFriendsModal extends React.PureComponent<Props, State> {\nthis.searchUsers('');\n}\n- searchUsers(usernamePrefix: string) {\n- this.props.dispatchActionPromise(\n- searchUsersActionTypes,\n- this.props.searchUsers(usernamePrefix),\n- );\n+ async searchUsers(usernamePrefix: string) {\n+ const { userInfos } = await this.props.searchUsers(usernamePrefix);\n+ this.setState({ userInfos: _keyBy(userInfo => userInfo.id)(userInfos) });\n}\nuserSearchResultsSelector = createSelector(\n(propsAndState: PropsAndState) => propsAndState.usernameInputText,\n- (propsAndState: PropsAndState) => propsAndState.otherUserInfos,\n- (propsAndState: PropsAndState) => propsAndState.userSearchIndex,\n+ (propsAndState: PropsAndState) => propsAndState.userInfos,\n+ (propsAndState: PropsAndState) => propsAndState.viewerID,\n(propsAndState: PropsAndState) => propsAndState.userInfoInputArray,\n(\ntext: string,\nuserInfos: { [id: string]: AccountUserInfo },\n- searchIndex: SearchIndex,\n+ viewerID: ?string,\nuserInfoInputArray: $ReadOnlyArray<AccountUserInfo>,\n) => {\n- // TODO: exclude current and blocked friends\n- const excludeUserIDs = userInfoInputArray.map(userInfo => userInfo.id);\n+ const excludeUserIDs = userInfoInputArray\n+ .map(userInfo => userInfo.id)\n+ .concat(viewerID || []);\n+ const searchIndex = searchIndexFromUserInfos(userInfos);\nreturn getUserSearchResults(text, userInfos, searchIndex, excludeUserIDs);\n},\n);\n@@ -158,7 +156,7 @@ class AddFriendsModal extends React.PureComponent<Props, State> {\nreturn;\n}\n- const selectedUserInfo = this.props.otherUserInfos[userID];\n+ const selectedUserInfo = this.state.userInfos[userID];\nthis.setState(state => ({\nuserInfoInputArray: state.userInfoInputArray.concat(selectedUserInfo),\n@@ -224,8 +222,7 @@ registerFetchKey(searchUsersActionTypes);\nexport default connect(\n(state: AppState) => {\nreturn {\n- otherUserInfos: userInfoSelectorForOtherMembersOfThread(null)(state),\n- userSearchIndex: userSearchIndexForOtherMembersOfThread(null)(state),\n+ viewerID: state.currentUserInfo && state.currentUserInfo.id,\nstyles: stylesSelector(state),\n};\n},\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -45,7 +45,7 @@ async function createThread(\nconst initialMemberIDs =\nrequest.initialMemberIDs && request.initialMemberIDs.length > 0\n? request.initialMemberIDs\n- : [];\n+ : null;\nif (threadType !== threadTypes.CHAT_SECRET && !parentThreadID) {\nthrow new ServerError('invalid_parameters');\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/entry-fetchers.js", "new_path": "server/src/fetchers/entry-fetchers.js", "diff": "@@ -23,10 +23,7 @@ import {\nfilterExists,\nnonExcludeDeletedCalendarFilters,\n} from 'lib/selectors/calendar-filter-selectors';\n-import {\n- rawEntryInfoWithinCalendarQuery,\n- usersInRawEntryInfos,\n-} from 'lib/shared/entry-utils';\n+import { rawEntryInfoWithinCalendarQuery } from 'lib/shared/entry-utils';\nimport {\ndbQuery,\n@@ -138,18 +135,10 @@ async function fetchEntryInfos(\nconst [result] = await dbQuery(query);\nconst rawEntryInfos = [];\n- const userInfos = {};\nfor (let row of result) {\nrawEntryInfos.push(rawEntryInfoFromRow(row));\n- if (row.creator) {\n- const creatorID = row.creatorID.toString();\n- userInfos[creatorID] = {\n- id: creatorID,\n- username: row.creator,\n- };\n- }\n}\n- return { rawEntryInfos, userInfos };\n+ return { rawEntryInfos, userInfos: {} };\n}\nasync function checkThreadPermissionForEntry(\n@@ -260,7 +249,7 @@ async function fetchEntriesForSession(\n}));\n}\n- const { rawEntryInfos, userInfos } = await fetchEntryInfos(\n+ const { rawEntryInfos } = await fetchEntryInfos(\nviewer,\ncalendarQueriesForFetch,\n);\n@@ -286,18 +275,9 @@ async function fetchEntriesForSession(\n});\n}\n- const userIDs = new Set(usersInRawEntryInfos(filteredRawEntryInfos));\n- const filteredUserInfos = {};\n- for (let userID in userInfos) {\n- if (!userIDs.has(userID)) {\n- continue;\n- }\n- filteredUserInfos[userID] = userInfos[userID];\n- }\nreturn {\nrawEntryInfos: filteredRawEntryInfos,\ndeletedEntryIDs,\n- userInfos: filteredUserInfos,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/message-fetchers.js", "new_path": "server/src/fetchers/message-fetchers.js", "diff": "@@ -428,7 +428,7 @@ async function fetchMessageInfos(\n`);\nconst [result] = await dbQuery(query);\n- const { userInfos, messages } = parseMessageSQLResult(result, viewer);\n+ const { messages } = parseMessageSQLResult(result, viewer);\nconst rawMessageInfos = [];\nconst threadToMessageCount = new Map();\n@@ -476,7 +476,6 @@ async function fetchMessageInfos(\n}\n}\n- const allUserInfos = await fetchAllUsers(rawMessageInfos, userInfos);\nconst shimmedRawMessageInfos = shimUnsupportedRawMessageInfos(\nrawMessageInfos,\nviewer.platformDetails,\n@@ -485,7 +484,7 @@ async function fetchMessageInfos(\nreturn {\nrawMessageInfos: shimmedRawMessageInfos,\ntruncationStatuses,\n- userInfos: allUserInfos,\n+ userInfos: {},\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/entry-responders.js", "new_path": "server/src/responders/entry-responders.js", "diff": "@@ -23,7 +23,6 @@ import t from 'tcomb';\nimport { ServerError } from 'lib/utils/errors';\nimport { filteredThreadIDs } from 'lib/selectors/calendar-filter-selectors';\n-import { values } from 'lib/utils/objects';\nimport {\nvalidateInput,\n@@ -239,7 +238,8 @@ async function calendarQueryUpdateResponder(\nreturn {\nrawEntryInfos: response.rawEntryInfos,\ndeletedEntryIDs: response.deletedEntryIDs,\n- userInfos: values(response.userInfos),\n+ // Old clients expect userInfos object\n+ userInfos: [],\n};\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Clean up actions/responders that currently deliver userInfos Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D16
129,186
13.08.2020 12:56:12
-7,200
570063e4533af478845e064b68c5d412c3aded12
Clean up entry logic that currently delivers userInfos Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -21,12 +21,6 @@ import _keyBy from 'lodash/fp/keyBy';\nimport _isEqual from 'lodash/fp/isEqual';\nimport { setNewSessionActionType } from '../utils/action-utils';\n-import {\n- createEntryActionTypes,\n- saveEntryActionTypes,\n- deleteEntryActionTypes,\n- restoreEntryActionTypes,\n-} from '../actions/entry-actions';\nimport {\nlogOutActionTypes,\ndeleteAccountActionTypes,\n@@ -192,35 +186,6 @@ function reduceUserInfos(state: UserStore, action: BaseAction): UserStore {\ninconsistencyReports: state.inconsistencyReports,\n};\n}\n- } else if (\n- action.type === createEntryActionTypes.success ||\n- action.type === saveEntryActionTypes.success ||\n- action.type === restoreEntryActionTypes.success\n- ) {\n- const newUserInfos = _keyBy(userInfo => userInfo.id)(\n- action.payload.updatesResult.userInfos,\n- );\n- // $FlowFixMe should be fixed in flow-bin@0.115 / react-native@0.63\n- const updated = { ...state.userInfos, ...newUserInfos };\n- if (!_isEqual(state.userInfos)(updated)) {\n- return {\n- userInfos: updated,\n- inconsistencyReports: state.inconsistencyReports,\n- };\n- }\n- } else if (action.type === deleteEntryActionTypes.success && action.payload) {\n- const { updatesResult } = action.payload;\n- const newUserInfos = _keyBy(userInfo => userInfo.id)(\n- updatesResult.userInfos,\n- );\n- // $FlowFixMe should be fixed in flow-bin@0.115 / react-native@0.63\n- const updated = { ...state.userInfos, ...newUserInfos };\n- if (!_isEqual(state.userInfos)(updated)) {\n- return {\n- userInfos: updated,\n- inconsistencyReports: state.inconsistencyReports,\n- };\n- }\n} else if (action.type === processServerRequestsActionType) {\nconst checkStateRequest = action.payload.serverRequests.find(\ncandidate => candidate.type === serverRequestTypes.CHECK_STATE,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Clean up entry logic that currently delivers userInfos Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D17
129,186
13.08.2020 13:12:41
-7,200
cde17ce0ace0e502d12dba8ee4bd53a78a269bc5
[server] Update createAccountDeletionUpdates Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -5,16 +5,18 @@ import type {\nDeleteAccountRequest,\n} from 'lib/types/account-types';\nimport type { Viewer } from '../session/viewer';\n+import type { UserInfo } from 'lib/types/user-types';\nimport { updateTypes } from 'lib/types/update-types';\nimport bcrypt from 'twin-bcrypt';\nimport { ServerError } from 'lib/utils/errors';\nimport { promiseAll } from 'lib/utils/promises';\n+import { values } from 'lib/utils/objects';\nimport { dbQuery, SQL } from '../database';\nimport { createNewAnonymousCookie } from '../session/cookies';\n-import { fetchAllUserIDs } from '../fetchers/user-fetchers';\n+import { fetchKnownUserInfos } from '../fetchers/user-fetchers';\nimport { createUpdates } from '../creators/update-creator';\nimport { handleAsyncPromise } from '../responders/handlers';\nimport { rescindPushNotifs } from '../push/rescind';\n@@ -41,6 +43,10 @@ async function deleteAccount(\nconst deletedUserID = viewer.userID;\nawait rescindPushNotifs(SQL`n.user = ${deletedUserID}`, SQL`NULL`);\n+ const knownUserInfos = await fetchKnownUserInfos(viewer);\n+ const usersToUpdate = values(knownUserInfos).filter(\n+ userID => userID !== deletedUserID,\n+ );\n// TODO: if this results in any orphaned orgs, convert them to chats\nconst deletionQuery = SQL`\n@@ -77,7 +83,10 @@ async function deleteAccount(\nviewer.setNewCookie(anonymousViewerData);\n}\n- const deletionUpdatesPromise = createAccountDeletionUpdates(deletedUserID);\n+ const deletionUpdatesPromise = createAccountDeletionUpdates(\n+ usersToUpdate,\n+ deletedUserID,\n+ );\nif (request) {\nhandleAsyncPromise(deletionUpdatesPromise);\n} else {\n@@ -96,16 +105,20 @@ async function deleteAccount(\n}\nasync function createAccountDeletionUpdates(\n+ knownUserInfos: $ReadOnlyArray<UserInfo>,\ndeletedUserID: string,\n): Promise<void> {\n- const allUserIDs = await fetchAllUserIDs();\nconst time = Date.now();\n- const updateDatas = allUserIDs.map(userID => ({\n+ const updateDatas = [];\n+ for (const userInfo of knownUserInfos) {\n+ const { id: userID } = userInfo;\n+ updateDatas.push({\ntype: updateTypes.DELETE_ACCOUNT,\nuserID,\ntime,\ndeletedUserID,\n- }));\n+ });\n+ }\nawait createUpdates(updateDatas);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/user-fetchers.js", "new_path": "server/src/fetchers/user-fetchers.js", "diff": "@@ -44,7 +44,7 @@ async function fetchUserInfos(userIDs: string[]): Promise<UserInfos> {\nasync function fetchKnownUserInfos(\nviewer: Viewer,\nuserIDs?: $ReadOnlyArray<string>,\n-) {\n+): Promise<UserInfos> {\nif (!viewer.loggedIn) {\nthrow new ServerError('not_logged_in');\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Update createAccountDeletionUpdates Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D18
129,186
24.08.2020 16:19:04
-7,200
be068a050759c46397f3adbc8213e393c5cf46ae
Handle -1 roles in queries, update create relationships script Reviewers: ashoat Subscribers: KatPo
[ { "change_type": "MODIFY", "old_path": "server/src/bots/app-version-update.js", "new_path": "server/src/bots/app-version-update.js", "diff": "@@ -40,11 +40,11 @@ async function botherMonthlyActivesToUpdateAppVersion(): Promise<void> {\nSELECT t.id, m1.user, COUNT(m3.user) AS user_count\nFROM threads t\nLEFT JOIN memberships m1 ON m1.thread = t.id\n- AND m1.user != ${squadbot.userID}\n+ AND m1.user != ${squadbot.userID} AND m1.role >= 0\nLEFT JOIN memberships m2 ON m2.thread = t.id\n- AND m2.user = ${squadbot.userID}\n+ AND m2.user = ${squadbot.userID} AND m2.role >= 0\nLEFT JOIN memberships m3 ON m3.thread = t.id\n- WHERE m1.user IS NOT NULL AND m2.user IS NOT NULL\n+ WHERE m1.user IS NOT NULL AND m2.user IS NOT NULL AND m3.role >= 0\nGROUP BY t.id, m1.user\n) t ON t.user = x.user AND t.user_count = 2\nWHERE v.id IS NOT NULL AND x.max_code_version < v.code_version\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -200,7 +200,7 @@ async function postMessageSend(\n`);\nappendSQLArray(query, subthreadJoins, SQL` `);\nquery.append(SQL`\n- WHERE (m.role != 0 OR f.user IS NOT NULL) AND\n+ WHERE (m.role > 0 OR f.user IS NOT NULL) AND\nJSON_EXTRACT(m.permissions, ${visibleExtractString}) IS TRUE AND\nm.thread IN (${[...threadsToMessageIndices.keys()]})\n`);\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/session-fetchers.js", "new_path": "server/src/fetchers/session-fetchers.js", "diff": "@@ -17,7 +17,8 @@ async function fetchActiveSessionsForThread(\nSELECT s.id, s.user, s.query\nFROM memberships m\nLEFT JOIN sessions s ON s.user = m.user\n- WHERE m.thread = ${threadID} AND s.query IS NOT NULL\n+ WHERE m.thread = ${threadID} AND m.role >= 0\n+ AND s.query IS NOT NULL\n`;\nconst [result] = await dbQuery(query);\nconst filters = [];\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/thread-fetchers.js", "new_path": "server/src/fetchers/thread-fetchers.js", "diff": "@@ -37,7 +37,8 @@ async function fetchServerThreadInfos(\nUNION SELECT id AS thread, 0 AS id, NULL AS name, NULL AS permissions\nFROM threads\n) r ON r.thread = t.id\n- LEFT JOIN memberships m ON m.role = r.id AND m.thread = t.id\n+ LEFT JOIN memberships m ON m.role = r.id AND m.thread = t.id AND\n+ m.role >= 0\n`\n.append(whereClause)\n.append(SQL`ORDER BY m.user ASC`);\n@@ -212,7 +213,7 @@ async function viewerIsMember(\nreturn false;\n}\nconst row = result[0];\n- return !!row.role;\n+ return row.role > 0;\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/push/rescind.js", "new_path": "server/src/push/rescind.js", "diff": "@@ -25,7 +25,7 @@ async function rescindPushNotifs(\nfetchQuery.append(SQL`\n) AS unread_count\nFROM notifications n\n- LEFT JOIN memberships m ON m.user = n.user AND m.unread = 1 AND m.role != 0\n+ LEFT JOIN memberships m ON m.user = n.user AND m.unread = 1 AND m.role > 0\nAND JSON_EXTRACT(subscription, ${notificationExtractString})\nAND JSON_EXTRACT(permissions, ${visPermissionExtractString})\nWHERE n.rescinded = 0 AND\n" }, { "change_type": "MODIFY", "old_path": "server/src/push/utils.js", "new_path": "server/src/push/utils.js", "diff": "@@ -181,7 +181,7 @@ async function getUnreadCounts(\nconst query = SQL`\nSELECT user, COUNT(thread) AS unread_count\nFROM memberships\n- WHERE user IN (${userIDs}) AND unread = 1 AND role != 0\n+ WHERE user IN (${userIDs}) AND unread = 1 AND role > 0\nAND JSON_EXTRACT(permissions, ${visPermissionExtractString})\nAND JSON_EXTRACT(subscription, ${notificationExtractString})\nGROUP BY user\n" }, { "change_type": "MODIFY", "old_path": "server/src/scripts/create-db.js", "new_path": "server/src/scripts/create-db.js", "diff": "@@ -78,7 +78,7 @@ async function createTables() {\nthread bigint(20) NOT NULL,\nuser bigint(20) NOT NULL,\nrole bigint(20) NOT NULL,\n- permissions json NOT NULL,\n+ permissions json DEFAULT NULL,\npermissions_for_children json DEFAULT NULL,\ncreation_time bigint(20) NOT NULL,\nsubscription json NOT NULL,\n" }, { "change_type": "MODIFY", "old_path": "server/src/scripts/create-relationships.js", "new_path": "server/src/scripts/create-relationships.js", "diff": "@@ -14,11 +14,14 @@ import _isEqual from 'lodash/fp/isEqual';\nimport { getAllTuples } from 'lib/utils/array';\nimport { updateUndirectedRelationships } from '../updaters/relationship-updaters';\n+import { saveMemberships } from '../updaters/thread-permission-updaters';\nimport { dbQuery, SQL } from '../database';\nimport { endScript } from './utils';\nasync function main() {\ntry {\n+ await alterMemberships();\n+ await createMembershipsForFormerMembers();\nawait createKnowOfRelationships();\nendScript();\n} catch (e) {\n@@ -27,9 +30,42 @@ async function main() {\n}\n}\n+async function alterMemberships() {\n+ await dbQuery(\n+ SQL`ALTER TABLE memberships CHANGE permissions permissions json DEFAULT NULL`,\n+ );\n+}\n+\n+async function createMembershipsForFormerMembers() {\n+ const [result] = await dbQuery(SQL`\n+ SELECT DISTINCT thread, user\n+ FROM messages m\n+ WHERE NOT EXISTS (\n+ SELECT thread, user FROM memberships mm\n+ WHERE m.thread = mm.thread AND m.user = mm.user\n+ )\n+ `);\n+\n+ const rowsToSave = [];\n+ for (const row of result) {\n+ rowsToSave.push({\n+ operation: 'update',\n+ userID: row.user.toString(),\n+ threadID: row.thread.toString(),\n+ permissions: null,\n+ permissionsForChildren: null,\n+ role: '-1',\n+ });\n+ }\n+\n+ await saveMemberships(rowsToSave);\n+}\n+\nasync function createKnowOfRelationships() {\nconst [result] = await dbQuery(SQL`\n- SELECT thread, user FROM memberships ORDER BY user ASC\n+ SELECT thread, user FROM memberships\n+ UNION SELECT thread, user FROM messages\n+ ORDER BY user ASC\n`);\nconst changeset = _flow([\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -62,7 +62,7 @@ async function activityUpdater(\nconst membershipQuery = SQL`\nSELECT thread\nFROM memberships\n- WHERE role != 0\n+ WHERE role > 0\nAND thread IN (${verifiedThreadIDs})\nAND user = ${viewer.userID}\n`;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -42,11 +42,11 @@ import { rescindPushNotifs } from '../push/rescind';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n-type MembershipRowToSave = {|\n+export type MembershipRowToSave = {|\noperation: 'update' | 'join',\nuserID: string,\nthreadID: string,\n- permissions: ThreadPermissionsBlob,\n+ permissions: ?ThreadPermissionsBlob,\npermissionsForChildren: ?ThreadPermissionsBlob,\n// null role represents by \"0\"\nrole: string,\n@@ -498,7 +498,7 @@ async function saveMemberships(toSave: $ReadOnlyArray<MembershipRowToSave>) {\nrowToSave.role,\ntime,\nsubscription,\n- JSON.stringify(rowToSave.permissions),\n+ rowToSave.permissions ? JSON.stringify(rowToSave.permissions) : null,\nrowToSave.permissionsForChildren\n? JSON.stringify(rowToSave.permissionsForChildren)\n: null,\n@@ -543,7 +543,11 @@ async function deleteMemberships(\nSQL`(user = ${rowToDelete.userID} AND thread = ${rowToDelete.threadID})`,\n);\nconst conditions = mergeOrConditions(deleteRows);\n- const query = SQL`UPDATE memberships SET role = -1 WHERE `;\n+ const query = SQL`\n+ UPDATE memberships\n+ SET role = -1, permissions = NULL, permissions_for_children = NULL,\n+ unread = 0, subscription = ${defaultSubscriptionString}\n+ WHERE `;\nquery.append(conditions);\nawait dbQuery(query);\n}\n@@ -731,6 +735,7 @@ function getParentThreadRelationshipRowsForNewUsers(\nexport {\nchangeRole,\nrecalculateAllPermissions,\n+ saveMemberships,\ncommitMembershipChangeset,\nsetJoinsToUnread,\ngetRelationshipRowsForUsers,\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -83,7 +83,7 @@ async function updateRole(\nlet nonMemberUser = false;\nlet numResults = 0;\nfor (let row of result) {\n- if (!row.role) {\n+ if (row.role <= 0) {\nnonMemberUser = true;\nbreak;\n}\n@@ -159,7 +159,7 @@ async function removeMembers(\nlet nonDefaultRoleUser = false;\nconst actualMemberIDs = [];\nfor (let row of result) {\n- if (!row.role) {\n+ if (row.role <= 0) {\ncontinue;\n}\nactualMemberIDs.push(row.user.toString());\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Handle -1 roles in queries, update create relationships script Reviewers: ashoat Reviewed By: ashoat Subscribers: KatPo Differential Revision: https://phabricator.ashoat.com/D21
129,183
28.08.2020 09:09:39
-7,200
8dece4da73f81f7987ab4ce8142d12023e6ae0d4
[native] Fix nested blockQuotes on native Reviewers: ashoat Subscribers: zrebcu411, palys-swm, Adrian
[ { "change_type": "MODIFY", "old_path": "native/markdown/rules.react.js", "new_path": "native/markdown/rules.react.js", "diff": "@@ -245,7 +245,7 @@ function fullMarkdownRules(\n) {\nconst content = capture[1].replace(/^ *> ?/gm, '');\nreturn {\n- content: SimpleMarkdown.parseInline(parse, content, state),\n+ content: parse(content, state),\n};\n},\n// eslint-disable-next-line react/display-name\n@@ -255,7 +255,7 @@ function fullMarkdownRules(\nstate: SimpleMarkdown.State,\n) => (\n<View key={state.key} style={styles.blockQuote}>\n- <Text style={state.textStyle}>{output(node.content, state)}</Text>\n+ {output(node.content, state)}\n</View>\n),\n},\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix nested blockQuotes on native Reviewers: ashoat Reviewed By: ashoat Subscribers: zrebcu411, palys-swm, Adrian Differential Revision: https://phabricator.ashoat.com/D26
129,187
28.08.2020 13:11:21
14,400
d715ce938c46be349651a41660a54f77c37e0b6a
[native] codeVersion -> 65
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -133,8 +133,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 64\n- versionName \"0.0.64\"\n+ versionCode 65\n+ versionName \"0.0.65\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.64</string>\n+ <string>0.0.65</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>64</string>\n+ <string>65</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.64</string>\n+ <string>0.0.65</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>64</string>\n+ <string>65</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -190,7 +190,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 64;\n+const codeVersion = 65;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 65
129,187
30.08.2020 08:18:54
14,400
7b83c53e4341cbab2e4a1f34fe6ad6483ae48f50
[native] Disable bitcode on iOS debug build Summary: Otherwise `react-native@0.62` + `react-native-firebase@5` can't deploy a debug build to a physical device Context here: Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/ios/SquadCal.xcodeproj/project.pbxproj", "new_path": "native/ios/SquadCal.xcodeproj/project.pbxproj", "diff": "CURRENT_PROJECT_VERSION = 1;\nDEAD_CODE_STRIPPING = NO;\nDEVELOPMENT_TEAM = 6BF4H9TU5U;\n+ ENABLE_BITCODE = NO;\nHEADER_SEARCH_PATHS = (\n\"$(inherited)\",\n\"$(SRCROOT)/../node_modules/react-native/Libraries/LinkingIOS\",\n\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\";\nCURRENT_PROJECT_VERSION = 1;\nDEVELOPMENT_TEAM = 6BF4H9TU5U;\n+ ENABLE_BITCODE = YES;\nHEADER_SEARCH_PATHS = (\n\"$(inherited)\",\n\"$(SRCROOT)/../node_modules/react-native/Libraries/LinkingIOS\",\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Disable bitcode on iOS debug build Summary: Otherwise `react-native@0.62` + `react-native-firebase@5` can't deploy a debug build to a physical device Context here: https://github.com/invertase/react-native-firebase/issues/3384#issuecomment-607831629 Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: zrebcu411 Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D30
129,187
29.08.2020 19:37:51
14,400
15ebf1eeb2ebfb0291fb8a2f6eabff7cc64ecbc3
[native] Set textContentType on username/password TextInputs Summary: This lets us integrate better with iOS's native password manager integration Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -128,6 +128,7 @@ class LogInPanel extends React.PureComponent<Props> {\nautoCorrect={false}\nautoCapitalize=\"none\"\nkeyboardType=\"ascii-capable\"\n+ textContentType=\"username\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusPasswordInput}\n@@ -143,6 +144,7 @@ class LogInPanel extends React.PureComponent<Props> {\nonChangeText={this.onChangePasswordInputText}\nplaceholder=\"Password\"\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"go\"\nblurOnSubmit={false}\nonSubmitEditing={this.onSubmit}\n" }, { "change_type": "MODIFY", "old_path": "native/account/register-panel.react.js", "new_path": "native/account/register-panel.react.js", "diff": "@@ -103,6 +103,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nautoCorrect={false}\nautoCapitalize=\"none\"\nkeyboardType=\"ascii-capable\"\n+ textContentType=\"username\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusEmailInput}\n@@ -140,6 +141,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nonChangeText={this.onChangePasswordInputText}\nplaceholder=\"Password\"\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusConfirmPasswordInput}\n@@ -155,6 +157,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nonChangeText={this.onChangeConfirmPasswordInputText}\nplaceholder=\"Confirm password\"\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"go\"\nblurOnSubmit={false}\nonSubmitEditing={this.onSubmit}\n" }, { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "@@ -109,6 +109,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nplaceholder=\"New password\"\nautoFocus={true}\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusConfirmPasswordInput}\n@@ -124,6 +125,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nonChangeText={this.onChangeConfirmPasswordInputText}\nplaceholder=\"Confirm password\"\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"go\"\nblurOnSubmit={false}\nonSubmitEditing={this.onSubmit}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/delete-thread.react.js", "new_path": "native/chat/settings/delete-thread.react.js", "diff": "@@ -190,6 +190,7 @@ class DeleteThread extends React.PureComponent<Props, State> {\nplaceholder=\"Password\"\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitDeletion}\nref={this.passwordInputRef}\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -154,6 +154,7 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nplaceholder=\"Password\"\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitDeletion}\nref={this.passwordInputRef}\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-email.react.js", "new_path": "native/more/edit-email.react.js", "diff": "@@ -157,6 +157,7 @@ class EditEmail extends React.PureComponent<Props, State> {\nplaceholder=\"Password\"\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\n+ textContentType=\"password\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitEmail}\nref={this.passwordInputRef}\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-password.react.js", "new_path": "native/more/edit-password.react.js", "diff": "@@ -151,6 +151,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nplaceholder=\"Current password\"\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\n+ textContentType=\"password\"\nautoFocus={true}\nreturnKeyType=\"next\"\nonSubmitEditing={this.focusNewPassword}\n@@ -170,6 +171,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nplaceholder=\"New password\"\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\n+ textContentType=\"newPassword\"\nreturnKeyType=\"next\"\nonSubmitEditing={this.focusConfirmPassword}\nref={this.newPasswordRef}\n@@ -186,6 +188,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nplaceholder=\"Confirm password\"\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\n+ textContentType=\"newPassword\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitPassword}\nref={this.confirmPasswordRef}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Set textContentType on username/password TextInputs Summary: This lets us integrate better with iOS's native password manager integration Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D29
129,187
31.08.2020 11:15:12
14,400
8726e7c3d10d2ccf2adf116fef21ab6933a484e7
[native] Move LoggedOutModal buttonOpacity to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -32,6 +32,9 @@ import OnePassword from 'react-native-onepassword';\nimport PropTypes from 'prop-types';\nimport _isEqual from 'lodash/fp/isEqual';\nimport { SafeAreaView } from 'react-native-safe-area-context';\n+import Reanimated, {\n+ Easing as ReanimatedEasing,\n+} from 'react-native-reanimated';\nimport { fetchNewCookieFromNativeCredentials } from 'lib/utils/action-utils';\nimport {\n@@ -94,7 +97,6 @@ type State = {\nfooterPaddingTop: Animated.Value,\npanelOpacity: Animated.Value,\nforgotPasswordLinkOpacity: Animated.Value,\n- buttonOpacity: Animated.Value,\nonePasswordSupported: boolean,\nlogInState: StateContainer<LogInState>,\nregisterState: StateContainer<RegisterState>,\n@@ -126,6 +128,8 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nlastPanelPaddingTopValue: ?number = null;\nlogInPanelContainer: ?LogInPanelContainer = null;\n+ buttonOpacity: Reanimated.Value;\n+\nconstructor(props: Props) {\nsuper(props);\nthis.determineOnePasswordSupport();\n@@ -159,7 +163,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nfooterPaddingTop: new Animated.Value(this.calculateFooterPaddingTop(0)),\npanelOpacity: new Animated.Value(0),\nforgotPasswordLinkOpacity: new Animated.Value(0),\n- buttonOpacity: new Animated.Value(props.rehydrateConcluded ? 1 : 0),\nonePasswordSupported: false,\nlogInState: {\nstate: {\n@@ -181,6 +184,8 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nif (props.rehydrateConcluded) {\nthis.nextMode = 'prompt';\n}\n+\n+ this.buttonOpacity = new Reanimated.Value(props.rehydrateConcluded ? 1 : 0);\n}\nguardedSetState = (change: StateChange<State>) => {\n@@ -216,7 +221,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n}\n}\n- componentDidUpdate(prevProps: Props) {\n+ componentDidUpdate(prevProps: Props, prevState: State) {\nif (!prevProps.rehydrateConcluded && this.props.rehydrateConcluded) {\nthis.showPrompt();\nthis.onInitialAppLoad();\n@@ -226,6 +231,15 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n} else if (prevProps.isForeground && !this.props.isForeground) {\nthis.onBackground();\n}\n+\n+ if (this.state.mode === 'prompt' && prevState.mode !== 'prompt') {\n+ this.buttonOpacity.setValue(0);\n+ Reanimated.timing(this.buttonOpacity, {\n+ easing: ReanimatedEasing.out(ReanimatedEasing.ease),\n+ duration: 250,\n+ toValue: 1.0,\n+ }).start();\n+ }\n}\nonForeground() {\n@@ -288,11 +302,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nshowPrompt = () => {\nthis.nextMode = 'prompt';\nthis.guardedSetState({ mode: 'prompt' });\n- Animated.timing(this.state.buttonOpacity, {\n- ...animatedSpec,\n- duration: 250,\n- toValue: 1.0,\n- }).start();\n};\nhardwareBack = () => {\n@@ -528,9 +537,9 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n/>\n);\n} else if (this.state.mode === 'prompt') {\n- const opacityStyle = { opacity: this.state.buttonOpacity };\n+ const opacityStyle = { opacity: this.buttonOpacity };\nbuttons = (\n- <Animated.View style={[styles.buttonContainer, opacityStyle]}>\n+ <Reanimated.View style={[styles.buttonContainer, opacityStyle]}>\n<TouchableOpacity\nonPress={this.onPressLogIn}\nstyle={styles.button}\n@@ -545,7 +554,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n>\n<Text style={styles.buttonText}>SIGN UP</Text>\n</TouchableOpacity>\n- </Animated.View>\n+ </Reanimated.View>\n);\n} else if (this.state.mode === 'loading') {\npanel = (\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move LoggedOutModal buttonOpacity to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D31
129,187
31.08.2020 16:00:15
14,400
44c1b78ba741415fea8786489c30a86b06d4438c
[native] Extract runTiming Summary: I also made the animation config an optional parameter Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/media/multimedia-modal.react.js", "new_path": "native/media/multimedia-modal.react.js", "diff": "@@ -38,7 +38,7 @@ import {\nState as GestureState,\n} from 'react-native-gesture-handler';\nimport Orientation from 'react-native-orientation-locker';\n-import Animated, { Easing } from 'react-native-reanimated';\n+import Animated from 'react-native-reanimated';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport invariant from 'invariant';\n@@ -50,6 +50,7 @@ import {\nclamp,\ngestureJustStarted,\ngestureJustEnded,\n+ runTiming,\n} from '../utils/animation-utils';\nimport { intentionalSaveMedia } from './save-media';\nimport {\n@@ -87,7 +88,6 @@ const {\nstartClock,\nstopClock,\nclockRunning,\n- timing,\ndecay,\n} = Animated;\n/* eslint-enable import/no-named-as-default-member */\n@@ -120,38 +120,6 @@ function panDelta(value: Value, gestureActive: Value) {\n);\n}\n-function runTiming(\n- clock: Clock,\n- initialValue: Value | number,\n- finalValue: Value | number,\n- startStopClock: boolean = true,\n-): Value {\n- const state = {\n- finished: new Value(0),\n- position: new Value(0),\n- frameTime: new Value(0),\n- time: new Value(0),\n- };\n- const config = {\n- toValue: new Value(0),\n- duration: 250,\n- easing: Easing.out(Easing.ease),\n- };\n- return [\n- cond(not(clockRunning(clock)), [\n- set(state.finished, 0),\n- set(state.frameTime, 0),\n- set(state.time, 0),\n- set(state.position, initialValue),\n- set(config.toValue, finalValue),\n- startStopClock && startClock(clock),\n- ]),\n- timing(clock, state, config),\n- cond(state.finished, startStopClock && stopClock(clock)),\n- state.position,\n- ];\n-}\n-\nfunction runDecay(\nclock: Clock,\nvelocity: Value,\n" }, { "change_type": "MODIFY", "old_path": "native/utils/animation-utils.js", "new_path": "native/utils/animation-utils.js", "diff": "// @flow\n-import Animated from 'react-native-reanimated';\n+import Animated, { Easing } from 'react-native-reanimated';\nimport { State as GestureState } from 'react-native-gesture-handler';\n/* eslint-disable import/no-named-as-default-member */\n-const { Value, cond, greaterThan, eq, sub, set } = Animated;\n+const {\n+ Clock,\n+ Value,\n+ cond,\n+ not,\n+ greaterThan,\n+ eq,\n+ sub,\n+ set,\n+ startClock,\n+ stopClock,\n+ clockRunning,\n+ timing,\n+} = Animated;\n/* eslint-enable import/no-named-as-default-member */\nfunction clamp(value: Value, minValue: Value, maxValue: Value): Value {\n@@ -41,4 +54,43 @@ function gestureJustEnded(state: Value) {\n]);\n}\n-export { clamp, delta, gestureJustStarted, gestureJustEnded };\n+const defaultTimingConfig = {\n+ duration: 250,\n+ easing: Easing.out(Easing.ease),\n+};\n+\n+type TimingConfig = $Shape<typeof defaultTimingConfig>;\n+function runTiming(\n+ clock: Clock,\n+ initialValue: Value | number,\n+ finalValue: Value | number,\n+ startStopClock: boolean = true,\n+ config: TimingConfig = defaultTimingConfig,\n+): Value {\n+ const state = {\n+ finished: new Value(0),\n+ position: new Value(0),\n+ frameTime: new Value(0),\n+ time: new Value(0),\n+ };\n+ const timingConfig = {\n+ ...defaultTimingConfig,\n+ ...config,\n+ toValue: new Value(0),\n+ };\n+ return [\n+ cond(not(clockRunning(clock)), [\n+ set(state.finished, 0),\n+ set(state.frameTime, 0),\n+ set(state.time, 0),\n+ set(state.position, initialValue),\n+ set(timingConfig.toValue, finalValue),\n+ startStopClock && startClock(clock),\n+ ]),\n+ timing(clock, state, timingConfig),\n+ cond(state.finished, startStopClock && stopClock(clock)),\n+ state.position,\n+ ];\n+}\n+\n+export { clamp, delta, gestureJustStarted, gestureJustEnded, runTiming };\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Extract runTiming Summary: I also made the animation config an optional parameter Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D32
129,187
31.08.2020 16:07:51
14,400
6aa8c7f8768300ace9e6b90049d3aef5e282ca94
[native] Move LoggedOutModal panelPaddingTop to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -67,6 +67,7 @@ import {\ntype NavContextType,\nnavContextPropType,\n} from '../navigation/navigation-context';\n+import { runTiming } from '../utils/animation-utils';\nlet initialAppLoad = true;\nconst animatedSpec = {\n@@ -75,6 +76,26 @@ const animatedSpec = {\n};\nconst safeAreaEdges = ['top', 'bottom'];\n+/* eslint-disable import/no-named-as-default-member */\n+const {\n+ Clock,\n+ block,\n+ set,\n+ cond,\n+ and,\n+ eq,\n+ neq,\n+ greaterThan,\n+ lessThan,\n+ greaterOrEq,\n+ add,\n+ sub,\n+ divide,\n+ max,\n+ stopClock,\n+} = Reanimated;\n+/* eslint-enable import/no-named-as-default-member */\n+\ntype LoggedOutMode = 'loading' | 'prompt' | 'log-in' | 'register';\ntype Props = {\n// Navigation state\n@@ -93,7 +114,6 @@ type Props = {\n};\ntype State = {\nmode: LoggedOutMode,\n- panelPaddingTop: Animated.Value,\nfooterPaddingTop: Animated.Value,\npanelOpacity: Animated.Value,\nforgotPasswordLinkOpacity: Animated.Value,\n@@ -125,10 +145,14 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nactiveKeyboard = false;\nopacityChangeQueued = false;\nkeyboardHeight = 0;\n- lastPanelPaddingTopValue: ?number = null;\nlogInPanelContainer: ?LogInPanelContainer = null;\n+ contentHeight: Reanimated.Value;\n+ keyboardHeightValue = new Reanimated.Value(0);\n+ modeValue: Reanimated.Value;\n+\nbuttonOpacity: Reanimated.Value;\n+ panelPaddingTopValue: Reanimated.Value;\nconstructor(props: Props) {\nsuper(props);\n@@ -157,9 +181,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.state = {\nmode: props.rehydrateConcluded ? 'prompt' : 'loading',\n- panelPaddingTop: new Animated.Value(\n- this.calculatePanelPaddingTop('prompt', 0),\n- ),\nfooterPaddingTop: new Animated.Value(this.calculateFooterPaddingTop(0)),\npanelOpacity: new Animated.Value(0),\nforgotPasswordLinkOpacity: new Animated.Value(0),\n@@ -185,7 +206,16 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.nextMode = 'prompt';\n}\n+ const { height: windowHeight, topInset, bottomInset } = props.dimensions;\n+ this.contentHeight = new Reanimated.Value(\n+ windowHeight - topInset - bottomInset,\n+ );\n+ this.modeValue = new Reanimated.Value(\n+ LoggedOutModal.getModeNumber(this.nextMode),\n+ );\n+\nthis.buttonOpacity = new Reanimated.Value(props.rehydrateConcluded ? 1 : 0);\n+ this.panelPaddingTopValue = this.panelPaddingTop();\n}\nguardedSetState = (change: StateChange<State>) => {\n@@ -194,6 +224,25 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n}\n};\n+ setMode(newMode: LoggedOutMode) {\n+ this.nextMode = newMode;\n+ this.guardedSetState({ mode: newMode });\n+ this.modeValue.setValue(LoggedOutModal.getModeNumber(newMode));\n+ }\n+\n+ static getModeNumber(mode: LoggedOutMode) {\n+ if (mode === 'loading') {\n+ return 0;\n+ } else if (mode === 'prompt') {\n+ return 1;\n+ } else if (mode === 'log-in') {\n+ return 2;\n+ } else if (mode === 'register') {\n+ return 3;\n+ }\n+ invariant(false, `${mode} is not a valid LoggedOutMode`);\n+ }\n+\nasync determineOnePasswordSupport() {\nlet onePasswordSupported;\ntry {\n@@ -223,7 +272,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\ncomponentDidUpdate(prevProps: Props, prevState: State) {\nif (!prevProps.rehydrateConcluded && this.props.rehydrateConcluded) {\n- this.showPrompt();\n+ this.setMode('prompt');\nthis.onInitialAppLoad();\n}\nif (!prevProps.isForeground && this.props.isForeground) {\n@@ -240,6 +289,18 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\ntoValue: 1.0,\n}).start();\n}\n+\n+ const newContentHeight =\n+ this.props.dimensions.height -\n+ this.props.dimensions.topInset -\n+ this.props.dimensions.bottomInset;\n+ const oldContentHeight =\n+ prevProps.dimensions.height -\n+ prevProps.dimensions.topInset -\n+ prevProps.dimensions.bottomInset;\n+ if (newContentHeight !== oldContentHeight) {\n+ this.contentHeight.setValue(newContentHeight);\n+ }\n}\nonForeground() {\n@@ -299,11 +360,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n}\n}\n- showPrompt = () => {\n- this.nextMode = 'prompt';\n- this.guardedSetState({ mode: 'prompt' });\n- };\n-\nhardwareBack = () => {\nif (this.nextMode === 'log-in') {\ninvariant(this.logInPanelContainer, 'ref should be set');\n@@ -319,24 +375,63 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nreturn false;\n};\n- calculatePanelPaddingTop(mode: LoggedOutMode, keyboardHeight: number) {\n- const {\n- height: windowHeight,\n- topInset,\n- bottomInset,\n- } = this.props.dimensions;\n- let containerSize = Platform.OS === 'ios' ? 62.33 : 58.54; // header height\n- if (mode === 'log-in') {\n- // We need to make space for the reset password button on smaller devices\n- containerSize += windowHeight < 600 ? 195 : 165;\n- } else if (mode === 'register') {\n- // We need to make space for the password manager on smaller devices\n- containerSize += windowHeight < 600 ? 261 : 246;\n- } else {\n- containerSize += Platform.OS === 'ios' ? 40 : 61;\n- }\n- const contentHeight = windowHeight - bottomInset - topInset;\n- return (contentHeight - keyboardHeight - containerSize) / 2;\n+ panelPaddingTop() {\n+ const headerHeight = Platform.OS === 'ios' ? 62.33 : 58.54;\n+ const containerSize = add(\n+ headerHeight,\n+ cond(\n+ eq(this.modeValue, 2),\n+ // We make space for the reset password button on smaller devices\n+ cond(lessThan(this.contentHeight, 600), 195, 165),\n+ 0,\n+ ),\n+ cond(\n+ eq(this.modeValue, 3),\n+ // We make space for the password manager on smaller devices\n+ cond(lessThan(this.contentHeight, 600), 261, 246),\n+ 0,\n+ ),\n+ cond(lessThan(this.modeValue, 2), Platform.OS === 'ios' ? 40 : 61, 0),\n+ );\n+ const potentialPanelPaddingTop = divide(\n+ max(sub(this.contentHeight, this.keyboardHeightValue, containerSize), 0),\n+ 2,\n+ );\n+\n+ const panelPaddingTop = new Reanimated.Value(-1);\n+ const targetPanelPaddingTop = new Reanimated.Value(-1);\n+ const prevModeValue = new Reanimated.Value(\n+ LoggedOutModal.getModeNumber(this.nextMode),\n+ );\n+ const clock = new Clock();\n+ return block([\n+ cond(lessThan(panelPaddingTop, 0), [\n+ set(panelPaddingTop, potentialPanelPaddingTop),\n+ set(targetPanelPaddingTop, potentialPanelPaddingTop),\n+ ]),\n+ cond(\n+ and(\n+ greaterOrEq(this.keyboardHeightValue, 0),\n+ neq(prevModeValue, this.modeValue),\n+ ),\n+ [\n+ stopClock(clock),\n+ cond(\n+ neq(greaterThan(prevModeValue, 1), greaterThan(this.modeValue, 1)),\n+ set(targetPanelPaddingTop, potentialPanelPaddingTop),\n+ ),\n+ set(prevModeValue, this.modeValue),\n+ ],\n+ ),\n+ cond(\n+ neq(panelPaddingTop, targetPanelPaddingTop),\n+ set(\n+ panelPaddingTop,\n+ runTiming(clock, panelPaddingTop, targetPanelPaddingTop),\n+ ),\n+ ),\n+ panelPaddingTop,\n+ ]);\n}\ncalculateFooterPaddingTop(keyboardHeight: number) {\n@@ -350,34 +445,14 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nreturn contentHeight - keyboardHeight - textHeight - 15;\n}\n- animateToSecondMode(\n- inputDuration: ?number = null,\n- realKeyboardHeight: ?number = null,\n- ) {\n+ animateToSecondMode(inputDuration: ?number = null) {\nconst duration = inputDuration ? inputDuration : 150;\n- if (!realKeyboardHeight) {\n- realKeyboardHeight = this.keyboardHeight;\n- }\nconst animations = [];\n- const newPanelPaddingTopValue = this.calculatePanelPaddingTop(\n- this.state.mode,\n- this.keyboardHeight,\n- );\n- if (newPanelPaddingTopValue !== this.lastPanelPaddingTopValue) {\n- this.lastPanelPaddingTopValue = newPanelPaddingTopValue;\n- animations.push(\n- Animated.timing(this.state.panelPaddingTop, {\n- ...animatedSpec,\n- duration,\n- toValue: newPanelPaddingTopValue,\n- }),\n- );\n- }\nanimations.push(\nAnimated.timing(this.state.footerPaddingTop, {\n...animatedSpec,\nduration,\n- toValue: this.calculateFooterPaddingTop(realKeyboardHeight),\n+ toValue: this.calculateFooterPaddingTop(this.keyboardHeight),\n}),\n);\nif (this.opacityChangeQueued) {\n@@ -414,12 +489,9 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n0,\n),\n});\n- if (!this.activeKeyboard) {\n- // We do this because the Android keyboard can change in height and we\n- // don't want to bother moving the panel between those events\n+ this.keyboardHeightValue.setValue(keyboardHeight);\nthis.keyboardHeight = keyboardHeight;\n- }\n- this.animateToSecondMode(event.duration, keyboardHeight);\n+ this.animateToSecondMode(event.duration);\nif (!this.activeKeyboard) {\nthis.opacityChangeQueued = false;\n}\n@@ -428,17 +500,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nanimateKeyboardDownOrBackToPrompt(inputDuration: ?number) {\nconst duration = inputDuration ? inputDuration : 250;\n- const newLastPanelPaddingTopValue = this.calculatePanelPaddingTop(\n- this.nextMode,\n- 0,\n- );\n- this.lastPanelPaddingTopValue = newLastPanelPaddingTopValue;\nconst animations = [\n- Animated.timing(this.state.panelPaddingTop, {\n- ...animatedSpec,\n- duration,\n- toValue: newLastPanelPaddingTopValue,\n- }),\nAnimated.timing(this.state.footerPaddingTop, {\n...animatedSpec,\nduration,\n@@ -465,6 +527,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n}\nkeyboardHide = (event: ?KeyboardEvent) => {\n+ this.keyboardHeightValue.setValue(0);\nif (this.expectingKeyboardToAppear) {\n// On the iOS simulator, it's possible to disable the keyboard. In this\n// case, when a TextInput's autoFocus would normally cause keyboardShow\n@@ -503,6 +566,8 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.opacityChangeQueued = true;\nthis.nextMode = 'prompt';\n+ this.keyboardHeightValue.setValue(0);\n+ this.modeValue.setValue(LoggedOutModal.getModeNumber('prompt'));\nif (this.activeKeyboard) {\n// If keyboard is currently active, keyboardHide will handle the\n@@ -591,10 +656,10 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nopacity: this.state.panelOpacity,\nleft: windowWidth < 360 ? 28 : 40,\n};\n- const padding = { paddingTop: this.state.panelPaddingTop };\n+ const padding = { paddingTop: this.panelPaddingTopValue };\nconst animatedContent = (\n- <Animated.View style={[styles.animationContainer, padding]}>\n+ <Reanimated.View style={[styles.animationContainer, padding]}>\n<View>\n<Text style={styles.header}>SquadCal</Text>\n<Animated.View style={[styles.backButton, buttonStyle]}>\n@@ -604,7 +669,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n</Animated.View>\n</View>\n{panel}\n- </Animated.View>\n+ </Reanimated.View>\n);\nconst backgroundSource = { uri: splashBackgroundURI };\n@@ -631,9 +696,9 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n};\nonPressLogIn = () => {\n+ this.keyboardHeightValue.setValue(-1);\nthis.opacityChangeQueued = true;\n- this.nextMode = 'log-in';\n- this.guardedSetState({ mode: 'log-in' });\n+ this.setMode('log-in');\nif (this.activeKeyboard) {\n// If keyboard isn't currently active, keyboardShow will handle the\n// animation. This is so we can run all animations in parallel\n@@ -645,9 +710,9 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n};\nonPressRegister = () => {\n+ this.keyboardHeightValue.setValue(-1);\nthis.opacityChangeQueued = true;\n- this.nextMode = 'register';\n- this.guardedSetState({ mode: 'register' });\n+ this.setMode('register');\nif (this.activeKeyboard) {\n// If keyboard isn't currently active, keyboardShow will handle the\n// animation. This is so we can run all animations in parallel\n@@ -662,6 +727,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nif (!this.expectingKeyboardToAppear || !this.mounted) {\nreturn;\n}\n+ this.keyboardHeightValue.setValue(0);\nthis.expectingKeyboardToAppear = false;\nthis.animateToSecondMode();\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move LoggedOutModal panelPaddingTop to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D33
129,187
31.08.2020 18:51:46
14,400
65ca8a644aa0e08e3134b18ac54f095a5efe4f98
[native] Move LoggedOutModal footerPaddingTop to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -116,7 +116,6 @@ type Props = {\n};\ntype State = {\nmode: LoggedOutMode,\n- footerPaddingTop: Animated.Value,\npanelOpacity: Animated.Value,\nforgotPasswordLinkOpacity: Animated.Value,\nonePasswordSupported: boolean,\n@@ -155,6 +154,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nbuttonOpacity: Reanimated.Value;\npanelPaddingTopValue: Reanimated.Value;\n+ footerPaddingTopValue: Reanimated.Value;\nconstructor(props: Props) {\nsuper(props);\n@@ -183,7 +183,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.state = {\nmode: props.rehydrateConcluded ? 'prompt' : 'loading',\n- footerPaddingTop: new Animated.Value(this.calculateFooterPaddingTop(0)),\npanelOpacity: new Animated.Value(0),\nforgotPasswordLinkOpacity: new Animated.Value(0),\nonePasswordSupported: false,\n@@ -218,6 +217,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.buttonOpacity = new Reanimated.Value(props.rehydrateConcluded ? 1 : 0);\nthis.panelPaddingTopValue = this.panelPaddingTop();\n+ this.footerPaddingTopValue = this.footerPaddingTop();\n}\nguardedSetState = (change: StateChange<State>) => {\n@@ -448,27 +448,41 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n]);\n}\n- calculateFooterPaddingTop(keyboardHeight: number) {\n- const {\n- height: windowHeight,\n- topInset,\n- bottomInset,\n- } = this.props.dimensions;\n- const contentHeight = windowHeight - bottomInset - topInset;\n+ footerPaddingTop() {\nconst textHeight = Platform.OS === 'ios' ? 17 : 19;\n- return contentHeight - keyboardHeight - textHeight - 15;\n+ const targetFooterPaddingTop = max(\n+ sub(this.contentHeight, max(this.keyboardHeightValue, 0), textHeight, 15),\n+ 0,\n+ );\n+\n+ const footerPaddingTop = new Reanimated.Value(-1);\n+ const prevTargetFooterPaddingTop = new Reanimated.Value(-1);\n+ const clock = new Clock();\n+ return block([\n+ cond(lessThan(footerPaddingTop, 0), [\n+ set(footerPaddingTop, targetFooterPaddingTop),\n+ set(prevTargetFooterPaddingTop, targetFooterPaddingTop),\n+ ]),\n+ cond(greaterOrEq(this.keyboardHeightValue, 0), [\n+ cond(neq(targetFooterPaddingTop, prevTargetFooterPaddingTop), [\n+ stopClock(clock),\n+ set(prevTargetFooterPaddingTop, targetFooterPaddingTop),\n+ ]),\n+ cond(\n+ neq(footerPaddingTop, targetFooterPaddingTop),\n+ set(\n+ footerPaddingTop,\n+ runTiming(clock, footerPaddingTop, targetFooterPaddingTop),\n+ ),\n+ ),\n+ ]),\n+ footerPaddingTop,\n+ ]);\n}\nanimateToSecondMode(inputDuration: ?number = null) {\nconst duration = inputDuration ? inputDuration : 150;\nconst animations = [];\n- animations.push(\n- Animated.timing(this.state.footerPaddingTop, {\n- ...animatedSpec,\n- duration,\n- toValue: this.calculateFooterPaddingTop(this.keyboardHeight),\n- }),\n- );\nif (this.opacityChangeQueued) {\nanimations.push(\nAnimated.timing(this.state.panelOpacity, {\n@@ -514,13 +528,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nanimateKeyboardDownOrBackToPrompt(inputDuration: ?number) {\nconst duration = inputDuration ? inputDuration : 250;\n- const animations = [\n- Animated.timing(this.state.footerPaddingTop, {\n- ...animatedSpec,\n- duration,\n- toValue: this.calculateFooterPaddingTop(this.keyboardHeight),\n- }),\n- ];\n+ const animations = [];\nif (this.opacityChangeQueued) {\nanimations.push(\nAnimated.timing(this.state.panelOpacity, {\n@@ -647,14 +655,17 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nlet forgotPasswordLink = null;\nif (this.state.mode === 'log-in') {\n- const dynamicStyle = {\n+ const animatedStyle = {\nopacity: this.state.forgotPasswordLinkOpacity,\n- top: this.state.footerPaddingTop,\n+ };\n+ const reanimatedStyle = {\n+ top: this.footerPaddingTopValue,\n};\nforgotPasswordLink = (\n- <Animated.View\n- style={[styles.forgotPasswordTextContainer, dynamicStyle]}\n+ <Reanimated.View\n+ style={[styles.forgotPasswordTextContainer, reanimatedStyle]}\n>\n+ <Animated.View style={animatedStyle}>\n<TouchableOpacity\nactiveOpacity={0.6}\nonPress={this.onPressForgotPassword}\n@@ -662,6 +673,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n<Text style={styles.forgotPasswordText}>Forgot password?</Text>\n</TouchableOpacity>\n</Animated.View>\n+ </Reanimated.View>\n);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move LoggedOutModal footerPaddingTop to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D35
129,187
31.08.2020 21:15:59
14,400
78f7fbf4581939f8ac9ea8e0f4d486e9f4c6d916
[native] Move LoggedOutModal panelOpacity to Reanimated Summary: This one had some dependencies. For now I am having the `Panel` component support both animation libraries, but will simplify once `VerificationModal` is refactored Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/forgot-password-panel.react.js", "new_path": "native/account/forgot-password-panel.react.js", "diff": "@@ -5,10 +5,11 @@ import type { LoadingStatus } from 'lib/types/loading-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport React from 'react';\n-import { StyleSheet, View, Animated, Alert, Keyboard } from 'react-native';\n+import { StyleSheet, View, Alert, Keyboard } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n+import Animated from 'react-native-reanimated';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport {\n" }, { "change_type": "MODIFY", "old_path": "native/account/log-in-panel-container.react.js", "new_path": "native/account/log-in-panel-container.react.js", "diff": "@@ -12,6 +12,7 @@ import { View, Animated, Text, Easing, StyleSheet } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n+import Reanimated from 'react-native-reanimated';\nimport sleep from 'lib/utils/sleep';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -30,7 +31,7 @@ type LogInMode = 'log-in' | 'forgot-password' | 'forgot-password-success';\ntype Props = {|\nonePasswordSupported: boolean,\nsetActiveAlert: (activeAlert: boolean) => void,\n- opacityValue: Animated.Value,\n+ opacityValue: Reanimated.Value,\nforgotPasswordLinkOpacity: Animated.Value,\nlogInState: StateContainer<LogInState>,\ninnerRef: (container: ?LogInPanelContainer) => void,\n" }, { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -15,18 +15,12 @@ import {\n} from '../utils/state-container';\nimport React from 'react';\n-import {\n- View,\n- StyleSheet,\n- Alert,\n- Keyboard,\n- Animated,\n- Platform,\n-} from 'react-native';\n+import { View, StyleSheet, Alert, Keyboard, Platform } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport invariant from 'invariant';\nimport OnePassword from 'react-native-onepassword';\nimport PropTypes from 'prop-types';\n+import Animated from 'react-native-reanimated';\nimport { validUsernameRegex, validEmailRegex } from 'lib/shared/account-utils';\nimport { connect } from 'lib/utils/redux-utils';\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -81,6 +81,7 @@ const {\nClock,\nblock,\nset,\n+ call,\ncond,\nnot,\nand,\n@@ -116,7 +117,6 @@ type Props = {\n};\ntype State = {\nmode: LoggedOutMode,\n- panelOpacity: Animated.Value,\nforgotPasswordLinkOpacity: Animated.Value,\nonePasswordSupported: boolean,\nlogInState: StateContainer<LogInState>,\n@@ -155,6 +155,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nbuttonOpacity: Reanimated.Value;\npanelPaddingTopValue: Reanimated.Value;\nfooterPaddingTopValue: Reanimated.Value;\n+ panelOpacityValue: Reanimated.Value;\nconstructor(props: Props) {\nsuper(props);\n@@ -183,7 +184,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.state = {\nmode: props.rehydrateConcluded ? 'prompt' : 'loading',\n- panelOpacity: new Animated.Value(0),\nforgotPasswordLinkOpacity: new Animated.Value(0),\nonePasswordSupported: false,\nlogInState: {\n@@ -218,6 +218,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.buttonOpacity = new Reanimated.Value(props.rehydrateConcluded ? 1 : 0);\nthis.panelPaddingTopValue = this.panelPaddingTop();\nthis.footerPaddingTopValue = this.footerPaddingTop();\n+ this.panelOpacityValue = this.panelOpacity();\n}\nguardedSetState = (change: StateChange<State>) => {\n@@ -232,6 +233,10 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.modeValue.setValue(LoggedOutModal.getModeNumber(newMode));\n}\n+ proceedToNextMode = () => {\n+ this.guardedSetState({ mode: this.nextMode });\n+ };\n+\nstatic getModeNumber(mode: LoggedOutMode) {\nif (mode === 'loading') {\nreturn 0;\n@@ -480,17 +485,42 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n]);\n}\n+ panelOpacity() {\n+ const targetPanelOpacity = greaterThan(this.modeValue, 1);\n+\n+ const panelOpacity = new Reanimated.Value(-1);\n+ const prevPanelOpacity = new Reanimated.Value(-1);\n+ const prevTargetPanelOpacity = new Reanimated.Value(-1);\n+ const clock = new Clock();\n+ return block([\n+ cond(lessThan(panelOpacity, 0), [\n+ set(panelOpacity, targetPanelOpacity),\n+ set(prevPanelOpacity, targetPanelOpacity),\n+ set(prevTargetPanelOpacity, targetPanelOpacity),\n+ ]),\n+ cond(greaterOrEq(this.keyboardHeightValue, 0), [\n+ cond(neq(targetPanelOpacity, prevTargetPanelOpacity), [\n+ stopClock(clock),\n+ set(prevTargetPanelOpacity, targetPanelOpacity),\n+ ]),\n+ cond(\n+ neq(panelOpacity, targetPanelOpacity),\n+ set(panelOpacity, runTiming(clock, panelOpacity, targetPanelOpacity)),\n+ ),\n+ ]),\n+ cond(\n+ and(eq(panelOpacity, 0), neq(prevPanelOpacity, 0)),\n+ call([], this.proceedToNextMode),\n+ ),\n+ set(prevPanelOpacity, panelOpacity),\n+ panelOpacity,\n+ ]);\n+ }\n+\nanimateToSecondMode(inputDuration: ?number = null) {\nconst duration = inputDuration ? inputDuration : 150;\nconst animations = [];\nif (this.opacityChangeQueued) {\n- animations.push(\n- Animated.timing(this.state.panelOpacity, {\n- ...animatedSpec,\n- duration,\n- toValue: 1,\n- }),\n- );\nanimations.push(\nAnimated.timing(this.state.forgotPasswordLinkOpacity, {\n...animatedSpec,\n@@ -530,13 +560,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nconst duration = inputDuration ? inputDuration : 250;\nconst animations = [];\nif (this.opacityChangeQueued) {\n- animations.push(\n- Animated.timing(this.state.panelOpacity, {\n- ...animatedSpec,\n- duration,\n- toValue: 0,\n- }),\n- );\nanimations.push(\nAnimated.timing(this.state.forgotPasswordLinkOpacity, {\n...animatedSpec,\n@@ -576,16 +599,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n};\ngoBackToPrompt = () => {\n- let opacityListenerID: ?string = null;\n- const opacityListener = (animatedUpdate: { value: number }) => {\n- if (animatedUpdate.value === 0) {\n- this.guardedSetState({ mode: this.nextMode });\n- invariant(opacityListenerID, 'should be set');\n- this.state.panelOpacity.removeListener(opacityListenerID);\n- }\n- };\n- opacityListenerID = this.state.panelOpacity.addListener(opacityListener);\n-\nthis.opacityChangeQueued = true;\nthis.nextMode = 'prompt';\nthis.keyboardHeightValue.setValue(0);\n@@ -608,7 +621,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n<LogInPanelContainer\nonePasswordSupported={this.state.onePasswordSupported}\nsetActiveAlert={this.setActiveAlert}\n- opacityValue={this.state.panelOpacity}\n+ opacityValue={this.panelOpacityValue}\nforgotPasswordLinkOpacity={this.state.forgotPasswordLinkOpacity}\nlogInState={this.state.logInState}\ninnerRef={this.logInPanelContainerRef}\n@@ -618,7 +631,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\npanel = (\n<RegisterPanel\nsetActiveAlert={this.setActiveAlert}\n- opacityValue={this.state.panelOpacity}\n+ opacityValue={this.panelOpacityValue}\nonePasswordSupported={this.state.onePasswordSupported}\nstate={this.state.registerState}\n/>\n@@ -679,7 +692,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nconst windowWidth = this.props.dimensions.width;\nconst buttonStyle = {\n- opacity: this.state.panelOpacity,\n+ opacity: this.panelOpacityValue,\nleft: windowWidth < 360 ? 28 : 40,\n};\nconst padding = { paddingTop: this.panelPaddingTopValue };\n@@ -688,11 +701,11 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n<Reanimated.View style={[styles.animationContainer, padding]}>\n<View>\n<Text style={styles.header}>SquadCal</Text>\n- <Animated.View style={[styles.backButton, buttonStyle]}>\n+ <Reanimated.View style={[styles.backButton, buttonStyle]}>\n<TouchableOpacity activeOpacity={0.6} onPress={this.hardwareBack}>\n<Icon name=\"arrow-circle-o-left\" size={36} color=\"#FFFFFFAA\" />\n</TouchableOpacity>\n- </Animated.View>\n+ </Reanimated.View>\n</View>\n{panel}\n</Reanimated.View>\n" }, { "change_type": "MODIFY", "old_path": "native/account/panel-components.react.js", "new_path": "native/account/panel-components.react.js", "diff": "@@ -23,6 +23,7 @@ import {\n} from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport PropTypes from 'prop-types';\n+import Reanimated from 'react-native-reanimated';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -90,6 +91,7 @@ function PanelOnePasswordButton(props: {| onPress: () => Promise<void> |}) {\ntype PanelProps = {|\nopacityValue: Animated.Value,\n+ animationLibrary: 'react-native' | 'reanimated',\nchildren: React.Node,\nstyle?: ViewStyle,\ndimensions: DimensionsInfo,\n@@ -99,11 +101,15 @@ type PanelState = {|\n|};\nclass InnerPanel extends React.PureComponent<PanelProps, PanelState> {\nstatic propTypes = {\n- opacityValue: PropTypes.instanceOf(Animated.Value).isRequired,\n+ opacityValue: PropTypes.object.isRequired,\n+ animationLibrary: PropTypes.oneOf(['react-native', 'reanimated']),\nchildren: PropTypes.node.isRequired,\nstyle: ViewPropTypes.style,\ndimensions: dimensionsInfoPropType.isRequired,\n};\n+ static defaultProps = {\n+ animationLibrary: 'reanimated',\n+ };\nstate = {\nkeyboardHeight: 0,\n};\n@@ -157,12 +163,16 @@ class InnerPanel extends React.PureComponent<PanelProps, PanelState> {\nopacity: this.props.opacityValue,\nmarginTop: windowHeight < 600 ? 15 : 40,\n};\n+ const AnimatedView =\n+ this.props.animationLibrary === 'react-native'\n+ ? Animated.View\n+ : Reanimated.View;\nconst content = (\n- <Animated.View\n+ <AnimatedView\nstyle={[styles.container, containerStyle, this.props.style]}\n>\n{this.props.children}\n- </Animated.View>\n+ </AnimatedView>\n);\nif (windowHeight >= 568) {\nreturn content;\n" }, { "change_type": "MODIFY", "old_path": "native/account/register-panel.react.js", "new_path": "native/account/register-panel.react.js", "diff": "@@ -15,18 +15,12 @@ import {\n} from '../utils/state-container';\nimport React from 'react';\n-import {\n- View,\n- StyleSheet,\n- Platform,\n- Keyboard,\n- Alert,\n- Animated,\n-} from 'react-native';\n+import { View, StyleSheet, Platform, Keyboard, Alert } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport invariant from 'invariant';\nimport OnePassword from 'react-native-onepassword';\nimport PropTypes from 'prop-types';\n+import Animated from 'react-native-reanimated';\nimport { connect } from 'lib/utils/redux-utils';\nimport { registerActionTypes, register } from 'lib/actions/user-actions';\n" }, { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "@@ -93,7 +93,11 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\npasswordStyle = { paddingRight: 30 };\n}\nreturn (\n- <Panel opacityValue={this.props.opacityValue} style={styles.container}>\n+ <Panel\n+ opacityValue={this.props.opacityValue}\n+ style={styles.container}\n+ animationLibrary=\"react-native\"\n+ >\n<View>\n<Icon name=\"user\" size={22} color=\"#777\" style={styles.icon} />\n<View style={styles.usernameContainer}>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move LoggedOutModal panelOpacity to Reanimated Summary: This one had some dependencies. For now I am having the `Panel` component support both animation libraries, but will simplify once `VerificationModal` is refactored Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D36
129,187
31.08.2020 21:41:44
14,400
f1ca329350180f13d5dc3994c81f56c33fb56395
[native] Move LoggedOutModal forgotPasswordLinkOpacity to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel-container.react.js", "new_path": "native/account/log-in-panel-container.react.js", "diff": "@@ -32,7 +32,7 @@ type Props = {|\nonePasswordSupported: boolean,\nsetActiveAlert: (activeAlert: boolean) => void,\nopacityValue: Reanimated.Value,\n- forgotPasswordLinkOpacity: Animated.Value,\n+ hideForgotPasswordLink: Reanimated.Value,\nlogInState: StateContainer<LogInState>,\ninnerRef: (container: ?LogInPanelContainer) => void,\n// Redux state\n@@ -48,7 +48,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nonePasswordSupported: PropTypes.bool.isRequired,\nsetActiveAlert: PropTypes.func.isRequired,\nopacityValue: PropTypes.object.isRequired,\n- forgotPasswordLinkOpacity: PropTypes.object.isRequired,\n+ hideForgotPasswordLink: PropTypes.object.isRequired,\nlogInState: stateContainerPropType.isRequired,\ninnerRef: PropTypes.func.isRequired,\nwindowWidth: PropTypes.number.isRequired,\n@@ -164,16 +164,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nonPressForgotPassword = () => {\nthis.setState({ nextLogInMode: 'forgot-password' });\n- const animations = [\n- Animated.timing(this.props.forgotPasswordLinkOpacity, {\n- ...animatedSpec,\n- toValue: 0,\n- }),\n- Animated.timing(this.state.panelTransition, {\n- ...animatedSpec,\n- toValue: 1,\n- }),\n- ];\n+ this.props.hideForgotPasswordLink.setValue(1);\nlet listenerID = '';\nconst listener = (animatedUpdate: { value: number }) => {\n@@ -184,7 +175,10 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\n};\nlistenerID = this.state.panelTransition.addListener(listener);\n- Animated.parallel(animations).start();\n+ Animated.timing(this.state.panelTransition, {\n+ ...animatedSpec,\n+ toValue: 1,\n+ }).start();\n};\nbackFromLogInMode = () => {\n@@ -199,16 +193,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\ninvariant(this.logInPanel, 'ref should be set');\nthis.logInPanel.focusUsernameOrEmailInput();\n- const animations = [\n- Animated.timing(this.props.forgotPasswordLinkOpacity, {\n- ...animatedSpec,\n- toValue: 1,\n- }),\n- Animated.timing(this.state.panelTransition, {\n- ...animatedSpec,\n- toValue: 0,\n- }),\n- ];\n+ this.props.hideForgotPasswordLink.setValue(0);\nlet listenerID = '';\nconst listener = (animatedUpdate: { value: number }) => {\n@@ -219,7 +204,10 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\n};\nlistenerID = this.state.panelTransition.addListener(listener);\n- Animated.parallel(animations).start();\n+ Animated.timing(this.state.panelTransition, {\n+ ...animatedSpec,\n+ toValue: 0,\n+ }).start();\nreturn true;\n};\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -18,8 +18,6 @@ import {\nStyleSheet,\nText,\nTouchableOpacity,\n- Animated,\n- Easing,\nImage,\nKeyboard,\nPlatform,\n@@ -32,9 +30,7 @@ import OnePassword from 'react-native-onepassword';\nimport PropTypes from 'prop-types';\nimport _isEqual from 'lodash/fp/isEqual';\nimport { SafeAreaView } from 'react-native-safe-area-context';\n-import Reanimated, {\n- Easing as ReanimatedEasing,\n-} from 'react-native-reanimated';\n+import Animated, { Easing } from 'react-native-reanimated';\nimport { fetchNewCookieFromNativeCredentials } from 'lib/utils/action-utils';\nimport {\n@@ -70,14 +66,11 @@ import {\nimport { runTiming } from '../utils/animation-utils';\nlet initialAppLoad = true;\n-const animatedSpec = {\n- useNativeDriver: false,\n- easing: Easing.out(Easing.ease),\n-};\nconst safeAreaEdges = ['top', 'bottom'];\n/* eslint-disable import/no-named-as-default-member */\nconst {\n+ Value,\nClock,\nblock,\nset,\n@@ -96,7 +89,7 @@ const {\nmax,\nstopClock,\nclockRunning,\n-} = Reanimated;\n+} = Animated;\n/* eslint-enable import/no-named-as-default-member */\ntype LoggedOutMode = 'loading' | 'prompt' | 'log-in' | 'register';\n@@ -115,14 +108,12 @@ type Props = {\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n};\n-type State = {\n+type State = {|\nmode: LoggedOutMode,\n- forgotPasswordLinkOpacity: Animated.Value,\nonePasswordSupported: boolean,\nlogInState: StateContainer<LogInState>,\nregisterState: StateContainer<RegisterState>,\n-};\n-\n+|};\nclass LoggedOutModal extends React.PureComponent<Props, State> {\nstatic propTypes = {\nisForeground: PropTypes.bool.isRequired,\n@@ -138,24 +129,22 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nkeyboardShowListener: ?EmitterSubscription;\nkeyboardHideListener: ?EmitterSubscription;\n- expectingKeyboardToAppear = false;\nmounted = false;\nnextMode: LoggedOutMode = 'loading';\nactiveAlert = false;\n- activeKeyboard = false;\n- opacityChangeQueued = false;\n- keyboardHeight = 0;\nlogInPanelContainer: ?LogInPanelContainer = null;\n- contentHeight: Reanimated.Value;\n- keyboardHeightValue = new Reanimated.Value(0);\n- modeValue: Reanimated.Value;\n+ contentHeight: Value;\n+ keyboardHeightValue = new Value(0);\n+ modeValue: Value;\n+ hideForgotPasswordLink = new Value(0);\n- buttonOpacity: Reanimated.Value;\n- panelPaddingTopValue: Reanimated.Value;\n- footerPaddingTopValue: Reanimated.Value;\n- panelOpacityValue: Reanimated.Value;\n+ buttonOpacity: Value;\n+ panelPaddingTopValue: Value;\n+ footerPaddingTopValue: Value;\n+ panelOpacityValue: Value;\n+ forgotPasswordLinkOpacityValue: Value;\nconstructor(props: Props) {\nsuper(props);\n@@ -184,7 +173,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nthis.state = {\nmode: props.rehydrateConcluded ? 'prompt' : 'loading',\n- forgotPasswordLinkOpacity: new Animated.Value(0),\nonePasswordSupported: false,\nlogInState: {\nstate: {\n@@ -208,17 +196,14 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n}\nconst { height: windowHeight, topInset, bottomInset } = props.dimensions;\n- this.contentHeight = new Reanimated.Value(\n- windowHeight - topInset - bottomInset,\n- );\n- this.modeValue = new Reanimated.Value(\n- LoggedOutModal.getModeNumber(this.nextMode),\n- );\n+ this.contentHeight = new Value(windowHeight - topInset - bottomInset);\n+ this.modeValue = new Value(LoggedOutModal.getModeNumber(this.nextMode));\n- this.buttonOpacity = new Reanimated.Value(props.rehydrateConcluded ? 1 : 0);\n+ this.buttonOpacity = new Value(props.rehydrateConcluded ? 1 : 0);\nthis.panelPaddingTopValue = this.panelPaddingTop();\nthis.footerPaddingTopValue = this.footerPaddingTop();\nthis.panelOpacityValue = this.panelOpacity();\n+ this.forgotPasswordLinkOpacityValue = this.forgotPasswordLinkOpacity();\n}\nguardedSetState = (change: StateChange<State>) => {\n@@ -290,8 +275,8 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nif (this.state.mode === 'prompt' && prevState.mode !== 'prompt') {\nthis.buttonOpacity.setValue(0);\n- Reanimated.timing(this.buttonOpacity, {\n- easing: ReanimatedEasing.out(ReanimatedEasing.ease),\n+ Animated.timing(this.buttonOpacity, {\n+ easing: Easing.out(Easing.ease),\nduration: 250,\ntoValue: 1.0,\n}).start();\n@@ -405,9 +390,9 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n2,\n);\n- const panelPaddingTop = new Reanimated.Value(-1);\n- const targetPanelPaddingTop = new Reanimated.Value(-1);\n- const prevModeValue = new Reanimated.Value(\n+ const panelPaddingTop = new Value(-1);\n+ const targetPanelPaddingTop = new Value(-1);\n+ const prevModeValue = new Value(\nLoggedOutModal.getModeNumber(this.nextMode),\n);\nconst clock = new Clock();\n@@ -460,8 +445,8 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n0,\n);\n- const footerPaddingTop = new Reanimated.Value(-1);\n- const prevTargetFooterPaddingTop = new Reanimated.Value(-1);\n+ const footerPaddingTop = new Value(-1);\n+ const prevTargetFooterPaddingTop = new Value(-1);\nconst clock = new Clock();\nreturn block([\ncond(lessThan(footerPaddingTop, 0), [\n@@ -488,9 +473,9 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\npanelOpacity() {\nconst targetPanelOpacity = greaterThan(this.modeValue, 1);\n- const panelOpacity = new Reanimated.Value(-1);\n- const prevPanelOpacity = new Reanimated.Value(-1);\n- const prevTargetPanelOpacity = new Reanimated.Value(-1);\n+ const panelOpacity = new Value(-1);\n+ const prevPanelOpacity = new Value(-1);\n+ const prevTargetPanelOpacity = new Value(-1);\nconst clock = new Clock();\nreturn block([\ncond(lessThan(panelOpacity, 0), [\n@@ -517,28 +502,57 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n]);\n}\n- animateToSecondMode(inputDuration: ?number = null) {\n- const duration = inputDuration ? inputDuration : 150;\n- const animations = [];\n- if (this.opacityChangeQueued) {\n- animations.push(\n- Animated.timing(this.state.forgotPasswordLinkOpacity, {\n- ...animatedSpec,\n- duration,\n- toValue: 1,\n- }),\n+ forgotPasswordLinkOpacity() {\n+ const targetForgotPasswordLinkOpacity = and(\n+ eq(this.modeValue, 2),\n+ not(this.hideForgotPasswordLink),\n);\n- }\n- Animated.parallel(animations).start();\n+\n+ const forgotPasswordLinkOpacity = new Value(-1);\n+ const prevTargetForgotPasswordLinkOpacity = new Value(-1);\n+ const clock = new Clock();\n+ return block([\n+ cond(lessThan(forgotPasswordLinkOpacity, 0), [\n+ set(forgotPasswordLinkOpacity, targetForgotPasswordLinkOpacity),\n+ set(\n+ prevTargetForgotPasswordLinkOpacity,\n+ targetForgotPasswordLinkOpacity,\n+ ),\n+ ]),\n+ cond(greaterOrEq(this.keyboardHeightValue, 0), [\n+ cond(\n+ neq(\n+ targetForgotPasswordLinkOpacity,\n+ prevTargetForgotPasswordLinkOpacity,\n+ ),\n+ [\n+ stopClock(clock),\n+ set(\n+ prevTargetForgotPasswordLinkOpacity,\n+ targetForgotPasswordLinkOpacity,\n+ ),\n+ ],\n+ ),\n+ cond(\n+ neq(forgotPasswordLinkOpacity, targetForgotPasswordLinkOpacity),\n+ set(\n+ forgotPasswordLinkOpacity,\n+ runTiming(\n+ clock,\n+ forgotPasswordLinkOpacity,\n+ targetForgotPasswordLinkOpacity,\n+ ),\n+ ),\n+ ),\n+ ]),\n+ forgotPasswordLinkOpacity,\n+ ]);\n}\nkeyboardShow = (event: KeyboardEvent) => {\nif (_isEqual(event.startCoordinates)(event.endCoordinates)) {\nreturn;\n}\n- if (this.expectingKeyboardToAppear) {\n- this.expectingKeyboardToAppear = false;\n- }\nconst keyboardHeight = Platform.select({\n// Android doesn't include the bottomInset in this height measurement\nandroid: event.endCoordinates.height,\n@@ -548,50 +562,12 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n),\n});\nthis.keyboardHeightValue.setValue(keyboardHeight);\n- this.keyboardHeight = keyboardHeight;\n- this.animateToSecondMode(event.duration);\n- if (!this.activeKeyboard) {\n- this.opacityChangeQueued = false;\n- }\n- this.activeKeyboard = true;\n};\n- animateKeyboardDownOrBackToPrompt(inputDuration: ?number) {\n- const duration = inputDuration ? inputDuration : 250;\n- const animations = [];\n- if (this.opacityChangeQueued) {\n- animations.push(\n- Animated.timing(this.state.forgotPasswordLinkOpacity, {\n- ...animatedSpec,\n- duration,\n- toValue: 0,\n- }),\n- );\n- }\n- Animated.parallel(animations).start();\n- }\n-\n- keyboardHide = (event: ?KeyboardEvent) => {\n+ keyboardHide = () => {\n+ if (!this.activeAlert) {\nthis.keyboardHeightValue.setValue(0);\n- if (this.expectingKeyboardToAppear) {\n- // On the iOS simulator, it's possible to disable the keyboard. In this\n- // case, when a TextInput's autoFocus would normally cause keyboardShow\n- // to trigger, keyboardHide is instead triggered. Since the Apple app\n- // testers seem to use the iOS simulator, we need to support this case.\n- this.expectingKeyboardToAppear = false;\n- this.animateToSecondMode();\n- return;\n- }\n- if (event && _isEqual(event.startCoordinates)(event.endCoordinates)) {\n- return;\n- }\n- this.keyboardHeight = 0;\n- this.activeKeyboard = false;\n- if (this.activeAlert) {\n- return;\n}\n- this.animateKeyboardDownOrBackToPrompt(event && event.duration);\n- this.opacityChangeQueued = false;\n};\nsetActiveAlert = (activeAlert: boolean) => {\n@@ -599,18 +575,10 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n};\ngoBackToPrompt = () => {\n- this.opacityChangeQueued = true;\nthis.nextMode = 'prompt';\nthis.keyboardHeightValue.setValue(0);\nthis.modeValue.setValue(LoggedOutModal.getModeNumber('prompt'));\n-\n- if (this.activeKeyboard) {\n- // If keyboard is currently active, keyboardHide will handle the\n- // animation. This is so we can run all animations in parallel\nKeyboard.dismiss();\n- } else {\n- this.animateKeyboardDownOrBackToPrompt(null);\n- }\n};\nrender() {\n@@ -622,7 +590,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nonePasswordSupported={this.state.onePasswordSupported}\nsetActiveAlert={this.setActiveAlert}\nopacityValue={this.panelOpacityValue}\n- forgotPasswordLinkOpacity={this.state.forgotPasswordLinkOpacity}\n+ hideForgotPasswordLink={this.hideForgotPasswordLink}\nlogInState={this.state.logInState}\ninnerRef={this.logInPanelContainerRef}\n/>\n@@ -639,7 +607,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n} else if (this.state.mode === 'prompt') {\nconst opacityStyle = { opacity: this.buttonOpacity };\nbuttons = (\n- <Reanimated.View style={[styles.buttonContainer, opacityStyle]}>\n+ <Animated.View style={[styles.buttonContainer, opacityStyle]}>\n<TouchableOpacity\nonPress={this.onPressLogIn}\nstyle={styles.button}\n@@ -654,7 +622,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n>\n<Text style={styles.buttonText}>SIGN UP</Text>\n</TouchableOpacity>\n- </Reanimated.View>\n+ </Animated.View>\n);\n} else if (this.state.mode === 'loading') {\npanel = (\n@@ -668,17 +636,14 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nlet forgotPasswordLink = null;\nif (this.state.mode === 'log-in') {\n- const animatedStyle = {\n- opacity: this.state.forgotPasswordLinkOpacity,\n- };\nconst reanimatedStyle = {\ntop: this.footerPaddingTopValue,\n+ opacity: this.forgotPasswordLinkOpacityValue,\n};\nforgotPasswordLink = (\n- <Reanimated.View\n+ <Animated.View\nstyle={[styles.forgotPasswordTextContainer, reanimatedStyle]}\n>\n- <Animated.View style={animatedStyle}>\n<TouchableOpacity\nactiveOpacity={0.6}\nonPress={this.onPressForgotPassword}\n@@ -686,7 +651,6 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n<Text style={styles.forgotPasswordText}>Forgot password?</Text>\n</TouchableOpacity>\n</Animated.View>\n- </Reanimated.View>\n);\n}\n@@ -698,17 +662,17 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nconst padding = { paddingTop: this.panelPaddingTopValue };\nconst animatedContent = (\n- <Reanimated.View style={[styles.animationContainer, padding]}>\n+ <Animated.View style={[styles.animationContainer, padding]}>\n<View>\n<Text style={styles.header}>SquadCal</Text>\n- <Reanimated.View style={[styles.backButton, buttonStyle]}>\n+ <Animated.View style={[styles.backButton, buttonStyle]}>\n<TouchableOpacity activeOpacity={0.6} onPress={this.hardwareBack}>\n<Icon name=\"arrow-circle-o-left\" size={36} color=\"#FFFFFFAA\" />\n</TouchableOpacity>\n- </Reanimated.View>\n+ </Animated.View>\n</View>\n{panel}\n- </Reanimated.View>\n+ </Animated.View>\n);\nconst backgroundSource = { uri: splashBackgroundURI };\n@@ -736,38 +700,12 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nonPressLogIn = () => {\nthis.keyboardHeightValue.setValue(-1);\n- this.opacityChangeQueued = true;\nthis.setMode('log-in');\n- if (this.activeKeyboard) {\n- // If keyboard isn't currently active, keyboardShow will handle the\n- // animation. This is so we can run all animations in parallel\n- this.animateToSecondMode();\n- return;\n- }\n- this.expectingKeyboardToAppear = true;\n- setTimeout(this.animateToSecondIfKeyboardStillHidden, 500);\n};\nonPressRegister = () => {\nthis.keyboardHeightValue.setValue(-1);\n- this.opacityChangeQueued = true;\nthis.setMode('register');\n- if (this.activeKeyboard) {\n- // If keyboard isn't currently active, keyboardShow will handle the\n- // animation. This is so we can run all animations in parallel\n- this.animateToSecondMode();\n- return;\n- }\n- this.expectingKeyboardToAppear = true;\n- setTimeout(this.animateToSecondIfKeyboardStillHidden, 500);\n- };\n-\n- animateToSecondIfKeyboardStillHidden = () => {\n- if (!this.expectingKeyboardToAppear || !this.mounted) {\n- return;\n- }\n- this.expectingKeyboardToAppear = false;\n- this.animateToSecondMode();\n};\nonPressForgotPassword = () => {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move LoggedOutModal forgotPasswordLinkOpacity to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D37
129,187
31.08.2020 23:42:12
14,400
d1c29f31e326939432fbb640d09fa4b751c331c8
[native] Move VerificationModal paddingTop to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/verification-modal.react.js", "new_path": "native/account/verification-modal.react.js", "diff": "@@ -34,6 +34,7 @@ import invariant from 'invariant';\nimport OnePassword from 'react-native-onepassword';\nimport PropTypes from 'prop-types';\nimport { SafeAreaView } from 'react-native-safe-area-context';\n+import Reanimated from 'react-native-reanimated';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -58,6 +59,7 @@ import {\nconnectNav,\ntype NavContextType,\n} from '../navigation/navigation-context';\n+import { runTiming } from '../utils/animation-utils';\nconst animatedSpec = {\nuseNativeDriver: false,\n@@ -65,6 +67,26 @@ const animatedSpec = {\n};\nconst safeAreaEdges = ['top', 'bottom'];\n+/* eslint-disable import/no-named-as-default-member */\n+const {\n+ Clock,\n+ block,\n+ set,\n+ cond,\n+ not,\n+ and,\n+ eq,\n+ neq,\n+ lessThan,\n+ greaterOrEq,\n+ sub,\n+ divide,\n+ max,\n+ stopClock,\n+ clockRunning,\n+} = Reanimated;\n+/* eslint-enable import/no-named-as-default-member */\n+\nexport type VerificationModalParams = {|\nverifyCode: string,\n|};\n@@ -87,7 +109,6 @@ type Props = {\n};\ntype State = {\nmode: VerificationModalMode,\n- paddingTop: Animated.Value,\nverifyField: ?VerifyField,\nerrorMessage: ?string,\nresetPasswordUsername: ?string,\n@@ -111,16 +132,6 @@ class VerificationModal extends React.PureComponent<Props, State> {\nhandleVerificationCode: PropTypes.func.isRequired,\n};\n- state = {\n- mode: 'simple-text',\n- paddingTop: new Animated.Value(this.currentPaddingTop('simple-text', 0)),\n- verifyField: null,\n- errorMessage: null,\n- resetPasswordUsername: null,\n- resetPasswordPanelOpacityValue: new Animated.Value(0),\n- onePasswordSupported: false,\n- };\n-\nkeyboardShowListener: ?Object;\nkeyboardHideListener: ?Object;\nexpectingKeyboardToAppear = false;\n@@ -131,6 +142,99 @@ class VerificationModal extends React.PureComponent<Props, State> {\nkeyboardHeight = 0;\nnextMode: VerificationModalMode = 'simple-text';\n+ contentHeight: Reanimated.Value;\n+ keyboardHeightValue = new Reanimated.Value(0);\n+ modeValue: Reanimated.Value;\n+\n+ paddingTopValue: Reanimated.Value;\n+\n+ constructor(props: Props) {\n+ super(props);\n+ this.state = {\n+ mode: 'simple-text',\n+ verifyField: null,\n+ errorMessage: null,\n+ resetPasswordUsername: null,\n+ resetPasswordPanelOpacityValue: new Animated.Value(0),\n+ onePasswordSupported: false,\n+ };\n+ const { height: windowHeight, topInset, bottomInset } = props.dimensions;\n+\n+ this.contentHeight = new Reanimated.Value(\n+ windowHeight - topInset - bottomInset,\n+ );\n+ this.modeValue = new Reanimated.Value(\n+ VerificationModal.getModeNumber(this.nextMode),\n+ );\n+\n+ this.paddingTopValue = this.paddingTop();\n+ }\n+\n+ static getModeNumber(mode: VerificationModalMode) {\n+ if (mode === 'simple-text') {\n+ return 0;\n+ } else if (mode === 'reset-password') {\n+ return 1;\n+ }\n+ invariant(false, `${mode} is not a valid VerificationModalMode`);\n+ }\n+\n+ paddingTop() {\n+ const potentialPaddingTop = divide(\n+ max(\n+ sub(\n+ this.contentHeight,\n+ cond(eq(this.modeValue, 0), 90),\n+ cond(eq(this.modeValue, 1), 165),\n+ this.keyboardHeightValue,\n+ ),\n+ 0,\n+ ),\n+ 2,\n+ );\n+\n+ const paddingTop = new Reanimated.Value(-1);\n+ const targetPaddingTop = new Reanimated.Value(-1);\n+ const prevModeValue = new Reanimated.Value(\n+ VerificationModal.getModeNumber(this.nextMode),\n+ );\n+ const clock = new Clock();\n+ const keyboardTimeoutClock = new Clock();\n+ return block([\n+ cond(lessThan(paddingTop, 0), [\n+ set(paddingTop, potentialPaddingTop),\n+ set(targetPaddingTop, potentialPaddingTop),\n+ ]),\n+ cond(\n+ lessThan(this.keyboardHeightValue, 0),\n+ [\n+ runTiming(keyboardTimeoutClock, 0, 1, true, { duration: 500 }),\n+ cond(\n+ not(clockRunning(keyboardTimeoutClock)),\n+ set(this.keyboardHeightValue, 0),\n+ ),\n+ ],\n+ stopClock(keyboardTimeoutClock),\n+ ),\n+ cond(\n+ and(\n+ greaterOrEq(this.keyboardHeightValue, 0),\n+ neq(prevModeValue, this.modeValue),\n+ ),\n+ [\n+ stopClock(clock),\n+ set(targetPaddingTop, potentialPaddingTop),\n+ set(prevModeValue, this.modeValue),\n+ ],\n+ ),\n+ cond(\n+ neq(paddingTop, targetPaddingTop),\n+ set(paddingTop, runTiming(clock, paddingTop, targetPaddingTop)),\n+ ),\n+ paddingTop,\n+ ]);\n+ }\n+\nasync determineOnePasswordSupport() {\nlet onePasswordSupported;\ntry {\n@@ -168,11 +272,11 @@ class VerificationModal extends React.PureComponent<Props, State> {\nconst code = this.props.route.params.verifyCode;\nif (code !== prevCode) {\nKeyboard.dismiss();\n+ this.nextMode = 'simple-text';\n+ this.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\n+ this.keyboardHeightValue.setValue(0);\nthis.setState({\n- mode: 'simple-text',\n- paddingTop: new Animated.Value(\n- this.currentPaddingTop('simple-text', 0),\n- ),\n+ mode: this.nextMode,\nverifyField: null,\nerrorMessage: null,\nresetPasswordUsername: null,\n@@ -188,6 +292,18 @@ class VerificationModal extends React.PureComponent<Props, State> {\n} else if (!this.props.isForeground && prevProps.isForeground) {\nthis.onBackground();\n}\n+\n+ const newContentHeight =\n+ this.props.dimensions.height -\n+ this.props.dimensions.topInset -\n+ this.props.dimensions.bottomInset;\n+ const oldContentHeight =\n+ prevProps.dimensions.height -\n+ prevProps.dimensions.topInset -\n+ prevProps.dimensions.bottomInset;\n+ if (newContentHeight !== oldContentHeight) {\n+ this.contentHeight.setValue(newContentHeight);\n+ }\n}\nonForeground() {\n@@ -227,6 +343,8 @@ class VerificationModal extends React.PureComponent<Props, State> {\nthis.opacityChangeQueued = true;\nthis.nextMode = 'simple-text';\n+ this.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\n+ this.keyboardHeightValue.setValue(0);\nif (this.activeKeyboard) {\n// If keyboard is currently active, keyboardHide will handle the\n@@ -252,6 +370,8 @@ class VerificationModal extends React.PureComponent<Props, State> {\n} else if (result.verifyField === verifyField.RESET_PASSWORD) {\nthis.opacityChangeQueued = true;\nthis.nextMode = 'reset-password';\n+ this.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\n+ this.keyboardHeightValue.setValue(-1);\nthis.setState({\nverifyField: result.verifyField,\nmode: 'reset-password',\n@@ -275,27 +395,9 @@ class VerificationModal extends React.PureComponent<Props, State> {\n}\n}\n- currentPaddingTop(mode: VerificationModalMode, keyboardHeight: number) {\n- const { height, bottomInset, topInset } = this.props.dimensions;\n- const safeAreaHeight = height - bottomInset - topInset;\n- let containerSize = 0;\n- if (mode === 'simple-text') {\n- containerSize = 90;\n- } else if (mode === 'reset-password') {\n- containerSize = 165;\n- }\n- return (safeAreaHeight - containerSize - keyboardHeight) / 2;\n- }\n-\nanimateToResetPassword(inputDuration: ?number = null) {\nconst duration = inputDuration ? inputDuration : 150;\n- const animations = [\n- Animated.timing(this.state.paddingTop, {\n- ...animatedSpec,\n- duration,\n- toValue: this.currentPaddingTop(this.state.mode, this.keyboardHeight),\n- }),\n- ];\n+ const animations = [];\nif (this.opacityChangeQueued) {\nanimations.push(\nAnimated.timing(this.state.resetPasswordPanelOpacityValue, {\n@@ -320,6 +422,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\n0,\n),\n});\n+ this.keyboardHeightValue.setValue(this.keyboardHeight);\nif (this.activeKeyboard) {\n// We do this because the Android keyboard can change in height and we\n// don't want to bother animating between those events\n@@ -332,13 +435,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nanimateKeyboardDownOrBackToSimpleText(inputDuration: ?number) {\nconst duration = inputDuration ? inputDuration : 250;\n- const animations = [\n- Animated.timing(this.state.paddingTop, {\n- ...animatedSpec,\n- duration,\n- toValue: this.currentPaddingTop(this.nextMode, 0),\n- }),\n- ];\n+ const animations = [];\nif (this.opacityChangeQueued) {\nanimations.push(\nAnimated.timing(this.state.resetPasswordPanelOpacityValue, {\n@@ -352,6 +449,9 @@ class VerificationModal extends React.PureComponent<Props, State> {\n}\nkeyboardHide = (event: ?KeyboardEvent) => {\n+ if (!this.activeAlert) {\n+ this.keyboardHeightValue.setValue(0);\n+ }\nif (this.expectingKeyboardToAppear) {\n// On the iOS simulator, it's possible to disable the keyboard. In this\n// case, when a TextInput's autoFocus would normally cause keyboardShow\n@@ -448,9 +548,9 @@ class VerificationModal extends React.PureComponent<Props, State> {\n</View>\n);\n}\n- const padding = { paddingTop: this.state.paddingTop };\n+ const padding = { paddingTop: this.paddingTopValue };\nconst animatedContent = (\n- <Animated.View style={padding}>{content}</Animated.View>\n+ <Reanimated.View style={padding}>{content}</Reanimated.View>\n);\nreturn (\n<React.Fragment>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move VerificationModal paddingTop to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D38
129,187
31.08.2020 23:55:41
14,400
3d296b1df24cf22f2a7b64dbd67fa8497bd62a9a
[native] Move VerificationModal resetPasswordPanelOpacity to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/panel-components.react.js", "new_path": "native/account/panel-components.react.js", "diff": "@@ -16,14 +16,13 @@ import {\nActivityIndicator,\nText,\nStyleSheet,\n- Animated,\nScrollView,\nLayoutAnimation,\nViewPropTypes,\n} from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport PropTypes from 'prop-types';\n-import Reanimated from 'react-native-reanimated';\n+import Animated from 'react-native-reanimated';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -91,7 +90,6 @@ function PanelOnePasswordButton(props: {| onPress: () => Promise<void> |}) {\ntype PanelProps = {|\nopacityValue: Animated.Value,\n- animationLibrary: 'react-native' | 'reanimated',\nchildren: React.Node,\nstyle?: ViewStyle,\ndimensions: DimensionsInfo,\n@@ -102,14 +100,10 @@ type PanelState = {|\nclass InnerPanel extends React.PureComponent<PanelProps, PanelState> {\nstatic propTypes = {\nopacityValue: PropTypes.object.isRequired,\n- animationLibrary: PropTypes.oneOf(['react-native', 'reanimated']),\nchildren: PropTypes.node.isRequired,\nstyle: ViewPropTypes.style,\ndimensions: dimensionsInfoPropType.isRequired,\n};\n- static defaultProps = {\n- animationLibrary: 'reanimated',\n- };\nstate = {\nkeyboardHeight: 0,\n};\n@@ -163,16 +157,12 @@ class InnerPanel extends React.PureComponent<PanelProps, PanelState> {\nopacity: this.props.opacityValue,\nmarginTop: windowHeight < 600 ? 15 : 40,\n};\n- const AnimatedView =\n- this.props.animationLibrary === 'react-native'\n- ? Animated.View\n- : Reanimated.View;\nconst content = (\n- <AnimatedView\n+ <Animated.View\nstyle={[styles.container, containerStyle, this.props.style]}\n>\n{this.props.children}\n- </AnimatedView>\n+ </Animated.View>\n);\nif (windowHeight >= 568) {\nreturn content;\n" }, { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "@@ -14,7 +14,6 @@ import React from 'react';\nimport {\nAlert,\nStyleSheet,\n- Animated,\nKeyboard,\nView,\nText,\n@@ -24,6 +23,7 @@ import invariant from 'invariant';\nimport OnePassword from 'react-native-onepassword';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport PropTypes from 'prop-types';\n+import Animated from 'react-native-reanimated';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport {\n@@ -93,11 +93,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\npasswordStyle = { paddingRight: 30 };\n}\nreturn (\n- <Panel\n- opacityValue={this.props.opacityValue}\n- style={styles.container}\n- animationLibrary=\"react-native\"\n- >\n+ <Panel opacityValue={this.props.opacityValue} style={styles.container}>\n<View>\n<Icon name=\"user\" size={22} color=\"#777\" style={styles.icon} />\n<View style={styles.usernameContainer}>\n" }, { "change_type": "MODIFY", "old_path": "native/account/verification-modal.react.js", "new_path": "native/account/verification-modal.react.js", "diff": "@@ -23,18 +23,16 @@ import {\nView,\nStyleSheet,\nActivityIndicator,\n- Animated,\nPlatform,\nKeyboard,\nTouchableHighlight,\n- Easing,\n} from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport invariant from 'invariant';\nimport OnePassword from 'react-native-onepassword';\nimport PropTypes from 'prop-types';\nimport { SafeAreaView } from 'react-native-safe-area-context';\n-import Reanimated from 'react-native-reanimated';\n+import Animated from 'react-native-reanimated';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -61,22 +59,21 @@ import {\n} from '../navigation/navigation-context';\nimport { runTiming } from '../utils/animation-utils';\n-const animatedSpec = {\n- useNativeDriver: false,\n- easing: Easing.out(Easing.ease),\n-};\nconst safeAreaEdges = ['top', 'bottom'];\n/* eslint-disable import/no-named-as-default-member */\nconst {\n+ Value,\nClock,\nblock,\nset,\n+ call,\ncond,\nnot,\nand,\neq,\nneq,\n+ greaterThan,\nlessThan,\ngreaterOrEq,\nsub,\n@@ -84,7 +81,7 @@ const {\nmax,\nstopClock,\nclockRunning,\n-} = Reanimated;\n+} = Animated;\n/* eslint-enable import/no-named-as-default-member */\nexport type VerificationModalParams = {|\n@@ -107,14 +104,13 @@ type Props = {\ncode: string,\n) => Promise<HandleVerificationCodeResult>,\n};\n-type State = {\n+type State = {|\nmode: VerificationModalMode,\nverifyField: ?VerifyField,\nerrorMessage: ?string,\nresetPasswordUsername: ?string,\n- resetPasswordPanelOpacityValue: Animated.Value,\nonePasswordSupported: boolean,\n-};\n+|};\nclass VerificationModal extends React.PureComponent<Props, State> {\nstatic propTypes = {\nnavigation: PropTypes.shape({\n@@ -134,19 +130,16 @@ class VerificationModal extends React.PureComponent<Props, State> {\nkeyboardShowListener: ?Object;\nkeyboardHideListener: ?Object;\n- expectingKeyboardToAppear = false;\nactiveAlert = false;\n- activeKeyboard = false;\n- opacityChangeQueued = false;\n- keyboardHeight = 0;\nnextMode: VerificationModalMode = 'simple-text';\n- contentHeight: Reanimated.Value;\n- keyboardHeightValue = new Reanimated.Value(0);\n- modeValue: Reanimated.Value;\n+ contentHeight: Value;\n+ keyboardHeightValue = new Value(0);\n+ modeValue: Value;\n- paddingTopValue: Reanimated.Value;\n+ paddingTopValue: Value;\n+ resetPasswordPanelOpacityValue: Value;\nconstructor(props: Props) {\nsuper(props);\n@@ -155,21 +148,21 @@ class VerificationModal extends React.PureComponent<Props, State> {\nverifyField: null,\nerrorMessage: null,\nresetPasswordUsername: null,\n- resetPasswordPanelOpacityValue: new Animated.Value(0),\nonePasswordSupported: false,\n};\nconst { height: windowHeight, topInset, bottomInset } = props.dimensions;\n- this.contentHeight = new Reanimated.Value(\n- windowHeight - topInset - bottomInset,\n- );\n- this.modeValue = new Reanimated.Value(\n- VerificationModal.getModeNumber(this.nextMode),\n- );\n+ this.contentHeight = new Value(windowHeight - topInset - bottomInset);\n+ this.modeValue = new Value(VerificationModal.getModeNumber(this.nextMode));\nthis.paddingTopValue = this.paddingTop();\n+ this.resetPasswordPanelOpacityValue = this.resetPasswordPanelOpacity();\n}\n+ proceedToNextMode = () => {\n+ this.setState({ mode: this.nextMode });\n+ };\n+\nstatic getModeNumber(mode: VerificationModalMode) {\nif (mode === 'simple-text') {\nreturn 0;\n@@ -193,9 +186,9 @@ class VerificationModal extends React.PureComponent<Props, State> {\n2,\n);\n- const paddingTop = new Reanimated.Value(-1);\n- const targetPaddingTop = new Reanimated.Value(-1);\n- const prevModeValue = new Reanimated.Value(\n+ const paddingTop = new Value(-1);\n+ const targetPaddingTop = new Value(-1);\n+ const prevModeValue = new Value(\nVerificationModal.getModeNumber(this.nextMode),\n);\nconst clock = new Clock();\n@@ -235,6 +228,60 @@ class VerificationModal extends React.PureComponent<Props, State> {\n]);\n}\n+ resetPasswordPanelOpacity() {\n+ const targetResetPasswordPanelOpacity = greaterThan(this.modeValue, 0);\n+\n+ const resetPasswordPanelOpacity = new Value(-1);\n+ const prevResetPasswordPanelOpacity = new Value(-1);\n+ const prevTargetResetPasswordPanelOpacity = new Value(-1);\n+ const clock = new Clock();\n+ return block([\n+ cond(lessThan(resetPasswordPanelOpacity, 0), [\n+ set(resetPasswordPanelOpacity, targetResetPasswordPanelOpacity),\n+ set(prevResetPasswordPanelOpacity, targetResetPasswordPanelOpacity),\n+ set(\n+ prevTargetResetPasswordPanelOpacity,\n+ targetResetPasswordPanelOpacity,\n+ ),\n+ ]),\n+ cond(greaterOrEq(this.keyboardHeightValue, 0), [\n+ cond(\n+ neq(\n+ targetResetPasswordPanelOpacity,\n+ prevTargetResetPasswordPanelOpacity,\n+ ),\n+ [\n+ stopClock(clock),\n+ set(\n+ prevTargetResetPasswordPanelOpacity,\n+ targetResetPasswordPanelOpacity,\n+ ),\n+ ],\n+ ),\n+ cond(\n+ neq(resetPasswordPanelOpacity, targetResetPasswordPanelOpacity),\n+ set(\n+ resetPasswordPanelOpacity,\n+ runTiming(\n+ clock,\n+ resetPasswordPanelOpacity,\n+ targetResetPasswordPanelOpacity,\n+ ),\n+ ),\n+ ),\n+ ]),\n+ cond(\n+ and(\n+ eq(resetPasswordPanelOpacity, 0),\n+ neq(prevResetPasswordPanelOpacity, 0),\n+ ),\n+ call([], this.proceedToNextMode),\n+ ),\n+ set(prevResetPasswordPanelOpacity, resetPasswordPanelOpacity),\n+ resetPasswordPanelOpacity,\n+ ]);\n+ }\n+\nasync determineOnePasswordSupport() {\nlet onePasswordSupported;\ntry {\n@@ -327,32 +374,11 @@ class VerificationModal extends React.PureComponent<Props, State> {\n};\nonResetPasswordSuccess = async () => {\n- let opacityListenerID: ?string = null;\n- const opacityListener = (animatedUpdate: { value: number }) => {\n- if (animatedUpdate.value === 0) {\n- this.setState({ mode: this.nextMode });\n- invariant(opacityListenerID, 'should be set');\n- this.state.resetPasswordPanelOpacityValue.removeListener(\n- opacityListenerID,\n- );\n- }\n- };\n- opacityListenerID = this.state.resetPasswordPanelOpacityValue.addListener(\n- opacityListener,\n- );\n-\n- this.opacityChangeQueued = true;\nthis.nextMode = 'simple-text';\nthis.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\nthis.keyboardHeightValue.setValue(0);\n- if (this.activeKeyboard) {\n- // If keyboard is currently active, keyboardHide will handle the\n- // animation. This is so we can run all animations in parallel\nKeyboard.dismiss();\n- } else {\n- this.animateKeyboardDownOrBackToSimpleText(null);\n- }\n// Wait a couple seconds before letting the SUCCESS action propagate and\n// clear VerificationModal\n@@ -368,7 +394,6 @@ class VerificationModal extends React.PureComponent<Props, State> {\nif (result.verifyField === verifyField.EMAIL) {\nthis.setState({ verifyField: result.verifyField });\n} else if (result.verifyField === verifyField.RESET_PASSWORD) {\n- this.opacityChangeQueued = true;\nthis.nextMode = 'reset-password';\nthis.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\nthis.keyboardHeightValue.setValue(-1);\n@@ -377,13 +402,6 @@ class VerificationModal extends React.PureComponent<Props, State> {\nmode: 'reset-password',\nresetPasswordUsername: result.resetPasswordUsername,\n});\n- if (this.activeKeyboard) {\n- // If keyboard isn't currently active, keyboardShow will handle the\n- // animation. This is so we can run all animations in parallel\n- this.animateToResetPassword();\n- } else if (Platform.OS === 'ios') {\n- this.expectingKeyboardToAppear = true;\n- }\n}\n} catch (e) {\nif (e.message === 'invalid_code') {\n@@ -395,26 +413,8 @@ class VerificationModal extends React.PureComponent<Props, State> {\n}\n}\n- animateToResetPassword(inputDuration: ?number = null) {\n- const duration = inputDuration ? inputDuration : 150;\n- const animations = [];\n- if (this.opacityChangeQueued) {\n- animations.push(\n- Animated.timing(this.state.resetPasswordPanelOpacityValue, {\n- ...animatedSpec,\n- duration,\n- toValue: 1,\n- }),\n- );\n- }\n- Animated.parallel(animations).start();\n- }\n-\nkeyboardShow = (event: KeyboardEvent) => {\n- if (this.expectingKeyboardToAppear) {\n- this.expectingKeyboardToAppear = false;\n- }\n- this.keyboardHeight = Platform.select({\n+ const keyboardHeight = Platform.select({\n// Android doesn't include the bottomInset in this height measurement\nandroid: event.endCoordinates.height,\ndefault: Math.max(\n@@ -422,52 +422,13 @@ class VerificationModal extends React.PureComponent<Props, State> {\n0,\n),\n});\n- this.keyboardHeightValue.setValue(this.keyboardHeight);\n- if (this.activeKeyboard) {\n- // We do this because the Android keyboard can change in height and we\n- // don't want to bother animating between those events\n- return;\n- }\n- this.activeKeyboard = true;\n- this.animateToResetPassword(event.duration);\n- this.opacityChangeQueued = false;\n+ this.keyboardHeightValue.setValue(keyboardHeight);\n};\n- animateKeyboardDownOrBackToSimpleText(inputDuration: ?number) {\n- const duration = inputDuration ? inputDuration : 250;\n- const animations = [];\n- if (this.opacityChangeQueued) {\n- animations.push(\n- Animated.timing(this.state.resetPasswordPanelOpacityValue, {\n- ...animatedSpec,\n- duration,\n- toValue: 0,\n- }),\n- );\n- }\n- Animated.parallel(animations).start();\n- }\n-\n- keyboardHide = (event: ?KeyboardEvent) => {\n+ keyboardHide = () => {\nif (!this.activeAlert) {\nthis.keyboardHeightValue.setValue(0);\n}\n- if (this.expectingKeyboardToAppear) {\n- // On the iOS simulator, it's possible to disable the keyboard. In this\n- // case, when a TextInput's autoFocus would normally cause keyboardShow\n- // to trigger, keyboardHide is instead triggered. Since the Apple app\n- // testers seem to use the iOS simulator, we need to support this case.\n- this.expectingKeyboardToAppear = false;\n- this.animateToResetPassword();\n- return;\n- }\n- this.keyboardHeight = 0;\n- this.activeKeyboard = false;\n- if (this.activeAlert) {\n- return;\n- }\n- this.animateKeyboardDownOrBackToSimpleText(event && event.duration);\n- this.opacityChangeQueued = false;\n};\nsetActiveAlert = (activeAlert: boolean) => {\n@@ -507,7 +468,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nonePasswordSupported={this.state.onePasswordSupported}\nonSuccess={this.onResetPasswordSuccess}\nsetActiveAlert={this.setActiveAlert}\n- opacityValue={this.state.resetPasswordPanelOpacityValue}\n+ opacityValue={this.resetPasswordPanelOpacityValue}\n/>\n);\n} else if (this.state.errorMessage) {\n@@ -550,7 +511,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\n}\nconst padding = { paddingTop: this.paddingTopValue };\nconst animatedContent = (\n- <Reanimated.View style={padding}>{content}</Reanimated.View>\n+ <Animated.View style={padding}>{content}</Animated.View>\n);\nreturn (\n<React.Fragment>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move VerificationModal resetPasswordPanelOpacity to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D39
129,187
01.09.2020 00:25:32
14,400
c6c80dc59ffaa522722a0c8a365b5dea08d14b64
[native] Move LogInPanelContainer panelTransition to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel-container.react.js", "new_path": "native/account/log-in-panel-container.react.js", "diff": "@@ -8,38 +8,49 @@ import {\nimport type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\n-import { View, Animated, Text, Easing, StyleSheet } from 'react-native';\n+import { View, Text, StyleSheet } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n-import Reanimated from 'react-native-reanimated';\n+import Animated from 'react-native-reanimated';\nimport sleep from 'lib/utils/sleep';\nimport { connect } from 'lib/utils/redux-utils';\nimport LogInPanel from './log-in-panel.react';\nimport ForgotPasswordPanel from './forgot-password-panel.react';\n-\n-const animatedSpec = {\n- useNativeDriver: false,\n- duration: 350,\n- easing: Easing.out(Easing.ease),\n-};\n+import { runTiming } from '../utils/animation-utils';\ntype LogInMode = 'log-in' | 'forgot-password' | 'forgot-password-success';\n+/* eslint-disable import/no-named-as-default-member */\n+const {\n+ Value,\n+ Clock,\n+ block,\n+ set,\n+ call,\n+ cond,\n+ eq,\n+ neq,\n+ lessThan,\n+ modulo,\n+ stopClock,\n+ interpolate,\n+} = Animated;\n+/* eslint-enable import/no-named-as-default-member */\n+\ntype Props = {|\nonePasswordSupported: boolean,\nsetActiveAlert: (activeAlert: boolean) => void,\n- opacityValue: Reanimated.Value,\n- hideForgotPasswordLink: Reanimated.Value,\n+ opacityValue: Value,\n+ hideForgotPasswordLink: Value,\nlogInState: StateContainer<LogInState>,\ninnerRef: (container: ?LogInPanelContainer) => void,\n// Redux state\nwindowWidth: number,\n|};\ntype State = {|\n- panelTransition: Animated.Value,\nlogInMode: LogInMode,\nnextLogInMode: LogInMode,\n|};\n@@ -48,17 +59,67 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nonePasswordSupported: PropTypes.bool.isRequired,\nsetActiveAlert: PropTypes.func.isRequired,\nopacityValue: PropTypes.object.isRequired,\n- hideForgotPasswordLink: PropTypes.object.isRequired,\n+ hideForgotPasswordLink: PropTypes.instanceOf(Value).isRequired,\nlogInState: stateContainerPropType.isRequired,\ninnerRef: PropTypes.func.isRequired,\nwindowWidth: PropTypes.number.isRequired,\n};\n- state = {\n- panelTransition: new Animated.Value(0),\n+ logInPanel: ?InnerLogInPanel = null;\n+\n+ panelTransitionTarget: Value;\n+ panelTransitionValue: Value;\n+\n+ constructor(props: Props) {\n+ super(props);\n+ this.state = {\nlogInMode: 'log-in',\nnextLogInMode: 'log-in',\n};\n- logInPanel: ?InnerLogInPanel = null;\n+ this.panelTransitionTarget = new Value(\n+ LogInPanelContainer.getModeNumber('log-in'),\n+ );\n+ this.panelTransitionValue = this.panelTransition();\n+ }\n+\n+ proceedToNextMode = () => {\n+ this.setState({ logInMode: this.state.nextLogInMode });\n+ };\n+\n+ static getModeNumber(mode: LogInMode) {\n+ if (mode === 'log-in') {\n+ return 0;\n+ } else if (mode === 'forgot-password') {\n+ return 1;\n+ } else if (mode === 'forgot-password-success') {\n+ return 2;\n+ }\n+ invariant(false, `${mode} is not a valid LogInModalMode`);\n+ }\n+\n+ panelTransition() {\n+ const panelTransition = new Value(-1);\n+ const prevPanelTransitionTarget = new Value(-1);\n+ const clock = new Clock();\n+ return block([\n+ cond(lessThan(panelTransition, 0), [\n+ set(panelTransition, this.panelTransitionTarget),\n+ set(prevPanelTransitionTarget, this.panelTransitionTarget),\n+ ]),\n+ cond(neq(this.panelTransitionTarget, prevPanelTransitionTarget), [\n+ stopClock(clock),\n+ set(prevPanelTransitionTarget, this.panelTransitionTarget),\n+ ]),\n+ cond(\n+ neq(panelTransition, this.panelTransitionTarget),\n+ set(\n+ panelTransition,\n+ runTiming(clock, panelTransition, this.panelTransitionTarget),\n+ ),\n+ ),\n+ cond(eq(modulo(panelTransition, 1), 0), call([], this.proceedToNextMode)),\n+ panelTransition,\n+ ]);\n+ }\ncomponentDidMount() {\nthis.props.innerRef(this);\n@@ -71,11 +132,11 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nrender() {\nconst { windowWidth } = this.props;\nconst logInPanelDynamicStyle = {\n- left: this.state.panelTransition.interpolate({\n+ left: interpolate(this.panelTransitionValue, {\ninputRange: [0, 2],\noutputRange: [0, windowWidth * -2],\n}),\n- right: this.state.panelTransition.interpolate({\n+ right: interpolate(this.panelTransitionValue, {\ninputRange: [0, 2],\noutputRange: [0, windowWidth * 2],\n}),\n@@ -97,11 +158,11 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nthis.state.logInMode !== 'log-in'\n) {\nconst forgotPasswordPanelDynamicStyle = {\n- left: this.state.panelTransition.interpolate({\n+ left: interpolate(this.panelTransitionValue, {\ninputRange: [0, 2],\noutputRange: [windowWidth, windowWidth * -1],\n}),\n- right: this.state.panelTransition.interpolate({\n+ right: interpolate(this.panelTransitionValue, {\ninputRange: [0, 2],\noutputRange: [windowWidth * -1, windowWidth],\n}),\n@@ -122,11 +183,11 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nthis.state.logInMode === 'forgot-password-success'\n) {\nconst forgotPasswordSuccessDynamicStyle = {\n- left: this.state.panelTransition.interpolate({\n+ left: interpolate(this.panelTransitionValue, {\ninputRange: [0, 2],\noutputRange: [windowWidth * 2, 0],\n}),\n- right: this.state.panelTransition.interpolate({\n+ right: interpolate(this.panelTransitionValue, {\ninputRange: [0, 2],\noutputRange: [windowWidth * -2, 0],\n}),\n@@ -162,23 +223,11 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\n};\nonPressForgotPassword = () => {\n- this.setState({ nextLogInMode: 'forgot-password' });\n-\nthis.props.hideForgotPasswordLink.setValue(1);\n-\n- let listenerID = '';\n- const listener = (animatedUpdate: { value: number }) => {\n- if (animatedUpdate.value === 1) {\n- this.setState({ logInMode: this.state.nextLogInMode });\n- this.state.panelTransition.removeListener(listenerID);\n- }\n- };\n- listenerID = this.state.panelTransition.addListener(listener);\n-\n- Animated.timing(this.state.panelTransition, {\n- ...animatedSpec,\n- toValue: 1,\n- }).start();\n+ this.setState({ nextLogInMode: 'forgot-password' });\n+ this.panelTransitionTarget.setValue(\n+ LogInPanelContainer.getModeNumber('forgot-password'),\n+ );\n};\nbackFromLogInMode = () => {\n@@ -194,20 +243,10 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nthis.logInPanel.focusUsernameOrEmailInput();\nthis.props.hideForgotPasswordLink.setValue(0);\n+ this.panelTransitionTarget.setValue(\n+ LogInPanelContainer.getModeNumber('log-in'),\n+ );\n- let listenerID = '';\n- const listener = (animatedUpdate: { value: number }) => {\n- if (animatedUpdate.value === 0) {\n- this.setState({ logInMode: this.state.nextLogInMode });\n- this.state.panelTransition.removeListener(listenerID);\n- }\n- };\n- listenerID = this.state.panelTransition.addListener(listener);\n-\n- Animated.timing(this.state.panelTransition, {\n- ...animatedSpec,\n- toValue: 0,\n- }).start();\nreturn true;\n};\n@@ -217,20 +256,9 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\n}\nthis.setState({ nextLogInMode: 'forgot-password-success' });\n-\n- let listenerID = '';\n- const listener = (animatedUpdate: { value: number }) => {\n- if (animatedUpdate.value === 2) {\n- this.setState({ logInMode: this.state.nextLogInMode });\n- this.state.panelTransition.removeListener(listenerID);\n- }\n- };\n- listenerID = this.state.panelTransition.addListener(listener);\n-\n- Animated.timing(this.state.panelTransition, {\n- ...animatedSpec,\n- toValue: 2,\n- }).start();\n+ this.panelTransitionTarget.setValue(\n+ LogInPanelContainer.getModeNumber('forgot-password-success'),\n+ );\nthis.inCoupleSecondsNavigateToLogIn();\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move LogInPanelContainer panelTransition to Reanimated Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D40
129,187
01.09.2020 01:09:21
14,400
136d05722c27abbd4ceb2d8c81341ed36bcc019f
[native] Move to Summary: `Clipboard` has been extracted out of React Native core due to the Lean Core effort Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/chat/text-message-tooltip-modal.react.js", "new_path": "native/chat/text-message-tooltip-modal.react.js", "diff": "import type { ChatTextMessageInfoItemWithHeight } from './text-message.react';\n-import { Clipboard } from 'react-native';\n+import Clipboard from '@react-native-community/clipboard';\nimport {\ncreateTooltip,\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -22,13 +22,13 @@ import {\nStyleSheet,\nScrollView,\nActivityIndicator,\n- Clipboard,\n} from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport _shuffle from 'lodash/fp/shuffle';\nimport ExitApp from 'react-native-exit-app';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n+import Clipboard from '@react-native-community/clipboard';\nimport { connect } from 'lib/utils/redux-utils';\nimport { sendReportActionTypes, sendReport } from 'lib/actions/report-actions';\n" }, { "change_type": "MODIFY", "old_path": "native/ios/Podfile.lock", "new_path": "native/ios/Podfile.lock", "diff": "@@ -375,6 +375,8 @@ PODS:\n- React\n- RNCAsyncStorage (1.6.2):\n- React\n+ - RNCClipboard (1.2.3):\n+ - React\n- RNCMaskedView (0.1.10):\n- React\n- RNExitApp (1.1.0):\n@@ -495,6 +497,7 @@ DEPENDENCIES:\n- ReactNativeKeyboardInput (from `../../node_modules/react-native-keyboard-input`)\n- ReactNativeKeyboardTrackingView (from `../../node_modules/react-native-keyboard-tracking-view`)\n- \"RNCAsyncStorage (from `../../node_modules/@react-native-community/async-storage`)\"\n+ - \"RNCClipboard (from `../../node_modules/@react-native-community/clipboard`)\"\n- \"RNCMaskedView (from `../../node_modules/@react-native-community/masked-view`)\"\n- RNExitApp (from `../../node_modules/react-native-exit-app`)\n- RNFastImage (from `../../node_modules/react-native-fast-image`)\n@@ -640,6 +643,8 @@ EXTERNAL SOURCES:\n:path: \"../../node_modules/react-native-keyboard-tracking-view\"\nRNCAsyncStorage:\n:path: \"../../node_modules/@react-native-community/async-storage\"\n+ RNCClipboard:\n+ :path: \"../../node_modules/@react-native-community/clipboard\"\nRNCMaskedView:\n:path: \"../../node_modules/@react-native-community/masked-view\"\nRNExitApp:\n@@ -756,6 +761,7 @@ SPEC CHECKSUMS:\nReactNativeKeyboardInput: 266ba27a2e9921f5bdc0b4cc30289b2a2f46b157\nReactNativeKeyboardTrackingView: 02137fac3b2ebd330d74fa54ead48b14750a2306\nRNCAsyncStorage: 60a80e72d95bf02a01cace55d3697d9724f0d77f\n+ RNCClipboard: 48eaf27bea3de7c9a265529725434268d47a2ee9\nRNCMaskedView: 5a8ec07677aa885546a0d98da336457e2bea557f\nRNExitApp: c4e052df2568b43bec8a37c7cd61194d4cfee2c3\nRNFastImage: 9b0c22643872bb7494c8d87bbbb66cc4c0d9e7a2\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"dependencies\": {\n\"@react-native-community/art\": \"^1.1.2\",\n\"@react-native-community/async-storage\": \"^1.6.1\",\n+ \"@react-native-community/clipboard\": \"^1.2.3\",\n\"@react-native-community/masked-view\": \"^0.1.10\",\n\"@react-native-community/netinfo\": \"^4.4.0\",\n\"@react-navigation/bottom-tabs\": \"^5.6.1\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "sudo-prompt \"^9.0.0\"\nwcwidth \"^1.0.1\"\n+\"@react-native-community/clipboard@^1.2.3\":\n+ version \"1.2.3\"\n+ resolved \"https://registry.yarnpkg.com/@react-native-community/clipboard/-/clipboard-1.2.3.tgz#1590f6849d9c8a3bc14bbd1aa0f1f3945e4e60ca\"\n+ integrity sha512-X9dfG/JiLI5pNyAwg3VMd7O3l/PVbYoAy8m12fetLWkBFzgTVEUIwsP0vysZ/29lnlLVM+qJUywcJmat046fvw==\n+\n\"@react-native-community/masked-view@^0.1.10\":\nversion \"0.1.10\"\nresolved \"https://registry.yarnpkg.com/@react-native-community/masked-view/-/masked-view-0.1.10.tgz#5dda643e19e587793bc2034dd9bf7398ad43d401\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move to @react-native-community/clipboard Summary: `Clipboard` has been extracted out of React Native core due to the Lean Core effort Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D42
129,187
01.09.2020 01:46:57
14,400
2f30f2233be0742f73be843402fcbc47e2d7ca53
[native] Only use LayoutAnimation in Panel when rendering ScrollView Summary: This only happens on small screens, and is the only context in which `LayoutAnimation` is useful here. It can cause weird effects on iOS so let's only use it when necessary Reviewers: zrebcu411, KatPo, palys-swm Subscribers: Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/panel-components.react.js", "new_path": "native/account/panel-components.react.js", "diff": "@@ -77,6 +77,8 @@ class PanelButton extends React.PureComponent<ButtonProps> {\n}\n}\n+const scrollViewBelow = 568;\n+\ntype PanelProps = {|\nopacityValue: Animated.Value,\nchildren: React.Node,\n@@ -124,11 +126,13 @@ class InnerPanel extends React.PureComponent<PanelProps, PanelState> {\nif (keyboardHeight === this.state.keyboardHeight) {\nreturn;\n}\n- if (!event) {\n- this.setState({ keyboardHeight });\n- return;\n- }\n- if (event.duration && event.easing) {\n+ const windowHeight = this.props.dimensions.height;\n+ if (\n+ windowHeight < scrollViewBelow &&\n+ event &&\n+ event.duration &&\n+ event.easing\n+ ) {\nLayoutAnimation.configureNext({\nduration: event.duration,\nupdate: {\n@@ -153,7 +157,7 @@ class InnerPanel extends React.PureComponent<PanelProps, PanelState> {\n{this.props.children}\n</Animated.View>\n);\n- if (windowHeight >= 568) {\n+ if (windowHeight >= scrollViewBelow) {\nreturn content;\n}\nconst scrollViewStyle = {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Only use LayoutAnimation in Panel when rendering ScrollView Summary: This only happens on small screens, and is the only context in which `LayoutAnimation` is useful here. It can cause weird effects on iOS so let's only use it when necessary Reviewers: zrebcu411, KatPo, palys-swm Reviewed By: palys-swm Subscribers: Adrian Differential Revision: https://phabricator.ashoat.com/D44
129,187
02.09.2020 11:18:54
14,400
6144777b18b8ea522fb47527fb3dcec020644060
[server] Handle logged-out viewer in fetchKnownUserInfos Summary: This is to fix the web splash screen Subscribers: KatPo, zrebcu411, palys-swm, Adrian
[ { "change_type": "MODIFY", "old_path": "server/src/fetchers/user-fetchers.js", "new_path": "server/src/fetchers/user-fetchers.js", "diff": "@@ -46,7 +46,7 @@ async function fetchKnownUserInfos(\nuserIDs?: $ReadOnlyArray<string>,\n): Promise<UserInfos> {\nif (!viewer.loggedIn) {\n- throw new ServerError('not_logged_in');\n+ return {};\n}\nif (userIDs && userIDs.length === 0) {\nreturn {};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Handle logged-out viewer in fetchKnownUserInfos Summary: This is to fix the web splash screen Subscribers: KatPo, zrebcu411, palys-swm, Adrian Differential Revision: https://phabricator.ashoat.com/D48
129,187
02.09.2020 12:05:41
14,400
7cbacbe6f0a0a7343613a6799fbcdb2e8cca2d16
[native] Use object literals for mapping mode strings to numbers Summary: See context [here](https://phabricator.ashoat.com/D33?id=118#inline-351) Reviewers: palys-swm Subscribers: KatPo, zrebcu411, palys-swm, Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel-container.react.js", "new_path": "native/account/log-in-panel-container.react.js", "diff": "@@ -22,6 +22,11 @@ import ForgotPasswordPanel from './forgot-password-panel.react';\nimport { runTiming } from '../utils/animation-utils';\ntype LogInMode = 'log-in' | 'forgot-password' | 'forgot-password-success';\n+const modeNumbers: { [LogInMode]: number } = {\n+ 'log-in': 0,\n+ 'forgot-password': 1,\n+ 'forgot-password-success': 2,\n+};\n/* eslint-disable import/no-named-as-default-member */\nconst {\n@@ -73,9 +78,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nlogInMode: 'log-in',\nnextLogInMode: 'log-in',\n};\n- this.panelTransitionTarget = new Value(\n- LogInPanelContainer.getModeNumber('log-in'),\n- );\n+ this.panelTransitionTarget = new Value(modeNumbers['log-in']);\nthis.panelTransitionValue = this.panelTransition();\n}\n@@ -83,17 +86,6 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nthis.setState({ logInMode: this.state.nextLogInMode });\n};\n- static getModeNumber(mode: LogInMode) {\n- if (mode === 'log-in') {\n- return 0;\n- } else if (mode === 'forgot-password') {\n- return 1;\n- } else if (mode === 'forgot-password-success') {\n- return 2;\n- }\n- invariant(false, `${mode} is not a valid LogInModalMode`);\n- }\n-\npanelTransition() {\nconst panelTransition = new Value(-1);\nconst prevPanelTransitionTarget = new Value(-1);\n@@ -222,9 +214,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nonPressForgotPassword = () => {\nthis.props.hideForgotPasswordLink.setValue(1);\nthis.setState({ nextLogInMode: 'forgot-password' });\n- this.panelTransitionTarget.setValue(\n- LogInPanelContainer.getModeNumber('forgot-password'),\n- );\n+ this.panelTransitionTarget.setValue(modeNumbers['forgot-password']);\n};\nbackFromLogInMode = () => {\n@@ -240,9 +230,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\nthis.logInPanel.focusUsernameOrEmailInput();\nthis.props.hideForgotPasswordLink.setValue(0);\n- this.panelTransitionTarget.setValue(\n- LogInPanelContainer.getModeNumber('log-in'),\n- );\n+ this.panelTransitionTarget.setValue(modeNumbers['log-in']);\nreturn true;\n};\n@@ -253,9 +241,7 @@ class LogInPanelContainer extends React.PureComponent<Props, State> {\n}\nthis.setState({ nextLogInMode: 'forgot-password-success' });\n- this.panelTransitionTarget.setValue(\n- LogInPanelContainer.getModeNumber('forgot-password-success'),\n- );\n+ this.panelTransitionTarget.setValue(modeNumbers['forgot-password-success']);\nthis.inCoupleSecondsNavigateToLogIn();\n};\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -95,6 +95,13 @@ const {\n/* eslint-enable import/no-named-as-default-member */\ntype LoggedOutMode = 'loading' | 'prompt' | 'log-in' | 'register';\n+const modeNumbers: { [LoggedOutMode]: number } = {\n+ 'loading': 0,\n+ 'prompt': 1,\n+ 'log-in': 2,\n+ 'register': 3,\n+};\n+\ntype Props = {\n// Navigation state\nisForeground: boolean,\n@@ -196,7 +203,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nconst { height: windowHeight, topInset, bottomInset } = props.dimensions;\nthis.contentHeight = new Value(windowHeight - topInset - bottomInset);\n- this.modeValue = new Value(LoggedOutModal.getModeNumber(this.nextMode));\n+ this.modeValue = new Value(modeNumbers[this.nextMode]);\nthis.buttonOpacity = new Value(props.rehydrateConcluded ? 1 : 0);\nthis.panelPaddingTopValue = this.panelPaddingTop();\n@@ -214,26 +221,13 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nsetMode(newMode: LoggedOutMode) {\nthis.nextMode = newMode;\nthis.guardedSetState({ mode: newMode });\n- this.modeValue.setValue(LoggedOutModal.getModeNumber(newMode));\n+ this.modeValue.setValue(modeNumbers[newMode]);\n}\nproceedToNextMode = () => {\nthis.guardedSetState({ mode: this.nextMode });\n};\n- static getModeNumber(mode: LoggedOutMode) {\n- if (mode === 'loading') {\n- return 0;\n- } else if (mode === 'prompt') {\n- return 1;\n- } else if (mode === 'log-in') {\n- return 2;\n- } else if (mode === 'register') {\n- return 3;\n- }\n- invariant(false, `${mode} is not a valid LoggedOutMode`);\n- }\n-\ncomponentDidMount() {\nthis.mounted = true;\nif (this.props.rehydrateConcluded) {\n@@ -381,9 +375,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nconst panelPaddingTop = new Value(-1);\nconst targetPanelPaddingTop = new Value(-1);\n- const prevModeValue = new Value(\n- LoggedOutModal.getModeNumber(this.nextMode),\n- );\n+ const prevModeValue = new Value(modeNumbers[this.nextMode]);\nconst clock = new Clock();\nconst keyboardTimeoutClock = new Clock();\nreturn block([\n@@ -570,7 +562,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\ngoBackToPrompt = () => {\nthis.nextMode = 'prompt';\nthis.keyboardHeightValue.setValue(0);\n- this.modeValue.setValue(LoggedOutModal.getModeNumber('prompt'));\n+ this.modeValue.setValue(modeNumbers['prompt']);\nKeyboard.dismiss();\n};\n" }, { "change_type": "MODIFY", "old_path": "native/account/verification-modal.react.js", "new_path": "native/account/verification-modal.react.js", "diff": "@@ -91,6 +91,11 @@ export type VerificationModalParams = {|\n|};\ntype VerificationModalMode = 'simple-text' | 'reset-password';\n+const modeNumbers: { [VerificationModalMode]: number } = {\n+ 'simple-text': 0,\n+ 'reset-password': 1,\n+};\n+\ntype Props = {\nnavigation: RootNavigationProp<'VerificationModal'>,\nroute: NavigationRoute<'VerificationModal'>,\n@@ -153,7 +158,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nconst { height: windowHeight, topInset, bottomInset } = props.dimensions;\nthis.contentHeight = new Value(windowHeight - topInset - bottomInset);\n- this.modeValue = new Value(VerificationModal.getModeNumber(this.nextMode));\n+ this.modeValue = new Value(modeNumbers[this.nextMode]);\nthis.paddingTopValue = this.paddingTop();\nthis.resetPasswordPanelOpacityValue = this.resetPasswordPanelOpacity();\n@@ -163,15 +168,6 @@ class VerificationModal extends React.PureComponent<Props, State> {\nthis.setState({ mode: this.nextMode });\n};\n- static getModeNumber(mode: VerificationModalMode) {\n- if (mode === 'simple-text') {\n- return 0;\n- } else if (mode === 'reset-password') {\n- return 1;\n- }\n- invariant(false, `${mode} is not a valid VerificationModalMode`);\n- }\n-\npaddingTop() {\nconst potentialPaddingTop = divide(\nmax(\n@@ -188,9 +184,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nconst paddingTop = new Value(-1);\nconst targetPaddingTop = new Value(-1);\n- const prevModeValue = new Value(\n- VerificationModal.getModeNumber(this.nextMode),\n- );\n+ const prevModeValue = new Value(modeNumbers[this.nextMode]);\nconst clock = new Clock();\nconst keyboardTimeoutClock = new Clock();\nreturn block([\n@@ -312,7 +306,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nif (code !== prevCode) {\nKeyboard.dismiss();\nthis.nextMode = 'simple-text';\n- this.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\n+ this.modeValue.setValue(modeNumbers[this.nextMode]);\nthis.keyboardHeightValue.setValue(0);\nthis.setState({\nmode: this.nextMode,\n@@ -367,7 +361,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nonResetPasswordSuccess = async () => {\nthis.nextMode = 'simple-text';\n- this.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\n+ this.modeValue.setValue(modeNumbers[this.nextMode]);\nthis.keyboardHeightValue.setValue(0);\nKeyboard.dismiss();\n@@ -387,7 +381,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nthis.setState({ verifyField: result.verifyField });\n} else if (result.verifyField === verifyField.RESET_PASSWORD) {\nthis.nextMode = 'reset-password';\n- this.modeValue.setValue(VerificationModal.getModeNumber(this.nextMode));\n+ this.modeValue.setValue(modeNumbers[this.nextMode]);\nthis.keyboardHeightValue.setValue(-1);\nthis.setState({\nverifyField: result.verifyField,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use object literals for mapping mode strings to numbers Summary: See context [here](https://phabricator.ashoat.com/D33?id=118#inline-351) Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, palys-swm, Adrian Differential Revision: https://phabricator.ashoat.com/D49
129,187
02.09.2020 14:06:35
14,400
613439e13237409da4f3c250ce16314046510965
[native] Start forgotPasswordLinkOpacity at 0 Summary: This Reanimated node only gets processed for the first time when `LogInPanel` displays, at which point the `targetForgotPasswordLinkOpacity` is already 1. We want it to start at 0 and animate to 1 Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -493,17 +493,10 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nnot(this.hideForgotPasswordLink),\n);\n- const forgotPasswordLinkOpacity = new Value(-1);\n- const prevTargetForgotPasswordLinkOpacity = new Value(-1);\n+ const forgotPasswordLinkOpacity = new Value(0);\n+ const prevTargetForgotPasswordLinkOpacity = new Value(0);\nconst clock = new Clock();\nreturn block([\n- cond(lessThan(forgotPasswordLinkOpacity, 0), [\n- set(forgotPasswordLinkOpacity, targetForgotPasswordLinkOpacity),\n- set(\n- prevTargetForgotPasswordLinkOpacity,\n- targetForgotPasswordLinkOpacity,\n- ),\n- ]),\ncond(greaterOrEq(this.keyboardHeightValue, 0), [\ncond(\nneq(\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Start forgotPasswordLinkOpacity at 0 Summary: This Reanimated node only gets processed for the first time when `LogInPanel` displays, at which point the `targetForgotPasswordLinkOpacity` is already 1. We want it to start at 0 and animate to 1 Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D51
129,187
02.09.2020 14:15:55
14,400
b1be0953fee3ad16726b515d2d180e5294a3d6d8
[native] Fix iOS password management flow for login Summary: The code comment in this diff should explain what's going on here Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -103,7 +103,7 @@ class LogInPanel extends React.PureComponent<Props> {\nvalue={this.props.state.state.usernameOrEmailInputText}\nonChangeText={this.onChangeUsernameOrEmailInputText}\nplaceholder={this.props.usernamePlaceholder}\n- autoFocus={true}\n+ autoFocus={Platform.OS !== 'ios'}\nautoCorrect={false}\nautoCapitalize=\"none\"\nkeyboardType=\"ascii-capable\"\n@@ -142,6 +142,9 @@ class LogInPanel extends React.PureComponent<Props> {\nusernameOrEmailInputRef = (usernameOrEmailInput: ?TextInput) => {\nthis.usernameOrEmailInput = usernameOrEmailInput;\n+ if (Platform.OS === 'ios' && usernameOrEmailInput) {\n+ setTimeout(() => usernameOrEmailInput.focus());\n+ }\n};\nfocusUsernameOrEmailInput = () => {\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -675,7 +675,18 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n};\nonPressLogIn = () => {\n+ if (Platform.OS !== 'ios') {\n+ // For some strange reason, iOS's password management logic doesn't\n+ // realize that the username and password fields in LogInPanel are related\n+ // if the username field gets focused on mount. To avoid this issue we\n+ // need the username and password fields to both appear on-screen before\n+ // we focus the username field. However, when we set keyboardHeightValue\n+ // to -1 here, we are telling our Reanimated logic to wait until the\n+ // keyboard appears before showing LogInPanel. Since we need LogInPanel\n+ // to appear before the username field is focused, we need to avoid this\n+ // behavior on iOS.\nthis.keyboardHeightValue.setValue(-1);\n+ }\nthis.setMode('log-in');\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix iOS password management flow for login Summary: The code comment in this diff should explain what's going on here Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D52
129,187
02.09.2020 14:31:01
14,400
ccb9903b99e92729f16c9cd08cb259fc139c2985
[native] Make sure ratchetAlongWithKeyboardHeight resets when keyboard hides Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/utils/animation-utils.js", "new_path": "native/utils/animation-utils.js", "diff": "@@ -12,6 +12,7 @@ const {\ncond,\nnot,\nand,\n+ or,\ngreaterThan,\nlessThan,\neq,\n@@ -115,12 +116,16 @@ function ratchetAlongWithKeyboardHeight(\n// cases it can get quite big, in which case we don't want to update\ndefaut: and(eq(prevKeyboardHeightValue, 0), greaterThan(keyboardHeight, 0)),\n});\n+ const whenToReset = and(\n+ eq(keyboardHeight, 0),\n+ greaterThan(prevKeyboardHeightValue, 0),\n+ );\nreturn block([\ncond(\nlessThan(prevKeyboardHeightValue, 0),\nset(prevKeyboardHeightValue, keyboardHeight),\n),\n- cond(whenToUpdate, ratchetFunction),\n+ cond(or(whenToUpdate, whenToReset), ratchetFunction),\nset(prevKeyboardHeightValue, keyboardHeight),\n]);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Make sure ratchetAlongWithKeyboardHeight resets when keyboard hides Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D53
129,183
01.09.2020 15:07:28
-7,200
4ec81b0c8d2fbdf14084f1254737562a6391e1ba
[native] Add click to reply option Reviewers: ashoat Subscribers: zrebcu411, palys-swm, Adrian
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-bar.react.js", "new_path": "native/chat/chat-input-bar.react.js", "diff": "@@ -59,7 +59,10 @@ import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { trimMessage } from 'lib/shared/message-utils';\nimport Button from '../components/button.react';\n-import { nonThreadCalendarQuery } from '../navigation/nav-selectors';\n+import {\n+ nonThreadCalendarQuery,\n+ activeThreadSelector,\n+} from '../navigation/nav-selectors';\nimport { getKeyboardHeight } from '../keyboard/keyboard';\nimport {\ntype Colors,\n@@ -82,6 +85,7 @@ type Props = {|\nthreadInfo: ThreadInfo,\nnavigation: ChatNavigationProp<'MessageList'>,\nroute: NavigationRoute<'MessageList'>,\n+ isActive: boolean,\n// Redux state\nviewerID: ?string,\ndraft: string,\n@@ -109,6 +113,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nthreadInfo: threadInfoPropType.isRequired,\nnavigation: messageListNavPropType.isRequired,\nroute: messageListRoutePropType.isRequired,\n+ isActive: PropTypes.bool.isRequired,\nviewerID: PropTypes.string,\ndraft: PropTypes.string.isRequired,\njoinThreadLoadingStatus: loadingStatusPropType.isRequired,\n@@ -184,9 +189,28 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}).start();\n}\n+ componentDidMount() {\n+ if (this.props.isActive) {\n+ this.addReplyListener();\n+ }\n+ }\n+\n+ componentWillUnmount() {\n+ if (this.props.isActive) {\n+ this.removeReplyListener();\n+ }\n+ }\n+\ncomponentDidUpdate(prevProps: Props, prevState: State) {\n+ if (this.props.isActive && !prevProps.isActive) {\n+ this.addReplyListener();\n+ } else if (!this.props.isActive && prevProps.isActive) {\n+ this.removeReplyListener();\n+ }\n+\nconst currentText = trimMessage(this.state.text);\nconst prevText = trimMessage(prevState.text);\n+\nif (\n(currentText === '' && prevText !== '') ||\n(currentText !== '' && prevText === '')\n@@ -216,6 +240,22 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\n}\n+ addReplyListener() {\n+ invariant(\n+ this.props.inputState,\n+ 'inputState should be set in addReplyListener',\n+ );\n+ this.props.inputState.addReplyListener(this.focusAndUpdateText);\n+ }\n+\n+ removeReplyListener() {\n+ invariant(\n+ this.props.inputState,\n+ 'inputState should be set in removeReplyListener',\n+ );\n+ this.props.inputState.removeReplyListener(this.focusAndUpdateText);\n+ }\n+\nsetIOSKeyboardHeight() {\nif (Platform.OS !== 'ios') {\nreturn;\n@@ -445,6 +485,12 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n});\n}, 400);\n+ focusAndUpdateText = (text: string) => {\n+ this.updateText(text);\n+ invariant(this.textInput, 'textInput should be set in focusAndUpdateText');\n+ this.textInput.focus();\n+ };\n+\nonSend = async () => {\nif (!trimMessage(this.state.text)) {\nreturn;\n@@ -638,9 +684,12 @@ const joinThreadLoadingStatusSelector = createLoadingStatusSelector(\njoinThreadActionTypes,\n);\n-export default connectNav((context: ?NavContextType) => ({\n+export default connectNav(\n+ (context: ?NavContextType, ownProps: { threadInfo: ThreadInfo }) => ({\nnavContext: context,\n-}))(\n+ isActive: ownProps.threadInfo.id === activeThreadSelector(context),\n+ }),\n+)(\nconnect(\n(\nstate: AppState,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/text-message-tooltip-modal.react.js", "new_path": "native/chat/text-message-tooltip-modal.react.js", "diff": "// @flow\nimport type { ChatTextMessageInfoItemWithHeight } from './text-message.react';\n+import type {\n+ DispatchFunctions,\n+ ActionFunc,\n+ BoundServerCall,\n+} from 'lib/utils/action-utils';\n+import { type InputState } from '../input/input-state';\nimport Clipboard from '@react-native-community/clipboard';\n+import invariant from 'invariant';\nimport {\ncreateTooltip,\n@@ -25,8 +32,30 @@ function onPressCopy(props: CustomProps) {\nsetTimeout(confirmCopy);\n}\n+const createReply = (message: string) => {\n+ // add `>` to each line to include empty lines in the quote\n+ const quotedMessage = message.replace(/^/gm, '> ');\n+ return quotedMessage + '\\n\\n';\n+};\n+\n+function onPressReply(\n+ props: CustomProps,\n+ dispatchFunctions: DispatchFunctions,\n+ bindServerCall: (serverCall: ActionFunc) => BoundServerCall,\n+ inputState: ?InputState,\n+) {\n+ invariant(\n+ inputState,\n+ 'inputState should be set in TextMessageTooltipModal.onPressReply',\n+ );\n+ inputState.addReply(createReply(props.item.messageInfo.text));\n+}\n+\nconst spec = {\n- entries: [{ id: 'copy', text: 'Copy', onPress: onPressCopy }],\n+ entries: [\n+ { id: 'copy', text: 'Copy', onPress: onPressCopy },\n+ { id: 'reply', text: 'Reply', onPress: onPressReply },\n+ ],\n};\nconst TextMessageTooltipModal = createTooltip(TextMessageTooltipButton, spec);\n" }, { "change_type": "MODIFY", "old_path": "native/input/input-state-container.react.js", "new_path": "native/input/input-state-container.react.js", "diff": "@@ -133,6 +133,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n};\nsendCallbacks: Array<() => void> = [];\nactiveURIs = new Map();\n+ replyCallbacks: Array<(message: string) => void> = [];\nstatic getCompletedUploads(props: Props, state: State): CompletedUploads {\nconst completedUploads = {};\n@@ -300,6 +301,9 @@ class InputStateContainer extends React.PureComponent<Props, State> {\npendingUploads,\nsendTextMessage: this.sendTextMessage,\nsendMultimediaMessage: this.sendMultimediaMessage,\n+ addReply: this.addReply,\n+ addReplyListener: this.addReplyListener,\n+ removeReplyListener: this.removeReplyListener,\nmessageHasUploadFailure: this.messageHasUploadFailure,\nretryMultimediaMessage: this.retryMultimediaMessage,\nregisterSendCallback: this.registerSendCallback,\n@@ -809,6 +813,20 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nreturn false;\n};\n+ addReply = (message: string) => {\n+ this.replyCallbacks.forEach(addReplyCallback => addReplyCallback(message));\n+ };\n+\n+ addReplyListener = (callbackReply: (message: string) => void) => {\n+ this.replyCallbacks.push(callbackReply);\n+ };\n+\n+ removeReplyListener = (callbackReply: (message: string) => void) => {\n+ this.replyCallbacks = this.replyCallbacks.filter(\n+ candidate => candidate !== callbackReply,\n+ );\n+ };\n+\nretryMultimediaMessage = async (localMessageID: string) => {\nconst rawMessageInfo = this.props.messageStoreMessages[localMessageID];\ninvariant(rawMessageInfo, `rawMessageInfo ${localMessageID} should exist`);\n" }, { "change_type": "MODIFY", "old_path": "native/input/input-state.js", "new_path": "native/input/input-state.js", "diff": "@@ -39,6 +39,9 @@ export type InputState = {|\nthreadID: string,\nselections: $ReadOnlyArray<NativeMediaSelection>,\n) => Promise<void>,\n+ addReply: (text: string) => void,\n+ addReplyListener: ((message: string) => void) => void,\n+ removeReplyListener: ((message: string) => void) => void,\nmessageHasUploadFailure: (localMessageID: string) => boolean,\nretryMultimediaMessage: (localMessageID: string) => Promise<void>,\nregisterSendCallback: (() => void) => void,\n@@ -51,6 +54,9 @@ const inputStatePropType = PropTypes.shape({\npendingUploads: pendingMultimediaUploadsPropType.isRequired,\nsendTextMessage: PropTypes.func.isRequired,\nsendMultimediaMessage: PropTypes.func.isRequired,\n+ addReply: PropTypes.func.isRequired,\n+ addReplyListener: PropTypes.func.isRequired,\n+ removeReplyListener: PropTypes.func.isRequired,\nmessageHasUploadFailure: PropTypes.func.isRequired,\nretryMultimediaMessage: PropTypes.func.isRequired,\nuploadInProgress: PropTypes.func.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/tooltip-item.react.js", "new_path": "native/navigation/tooltip-item.react.js", "diff": "@@ -6,6 +6,7 @@ import type {\nActionFunc,\nBoundServerCall,\n} from 'lib/utils/action-utils';\n+import type { InputState } from '../input/input-state';\nimport * as React from 'react';\nimport {\n@@ -25,6 +26,7 @@ export type TooltipEntry<Params> = {|\nprops: Params,\ndispatchFunctions: DispatchFunctions,\nbindServerCall: (serverCall: ActionFunc) => BoundServerCall,\n+ inputState: ?InputState,\n) => mixed,\n|};\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/tooltip.react.js", "new_path": "native/navigation/tooltip.react.js", "diff": "@@ -23,6 +23,11 @@ import type { LayoutEvent } from '../types/react-native';\nimport type { AppNavigationProp } from './app-navigator.react';\nimport type { TooltipModalParamList } from './route-names';\nimport type { LeafRoute } from '@react-navigation/native';\n+import {\n+ type InputState,\n+ inputStatePropType,\n+ withInputState,\n+} from '../input/input-state';\nimport * as React from 'react';\nimport Animated from 'react-native-reanimated';\n@@ -99,6 +104,8 @@ type TooltipProps<Navigation, Route> = {\ndispatchActionPromise: DispatchActionPromise,\n// withOverlayContext\noverlayContext: ?OverlayContextType,\n+ // withInputState\n+ inputState: ?InputState,\n};\nfunction createTooltip<\nRouteName: $Keys<TooltipModalParamList>,\n@@ -129,6 +136,7 @@ function createTooltip<\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\noverlayContext: overlayContextPropType,\n+ inputState: inputStatePropType,\n};\nbackdropOpacity: Value;\ntooltipContainerOpacity: Value;\n@@ -382,6 +390,7 @@ function createTooltip<\nthis.props.route.params,\ndispatchFunctions,\nthis.bindServerCall,\n+ this.props.inputState,\n);\n};\n@@ -427,7 +436,7 @@ function createTooltip<\n}),\nnull,\ntrue,\n- )(withOverlayContext(Tooltip));\n+ )(withOverlayContext(withInputState(Tooltip)));\n}\nconst styles = StyleSheet.create({\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Add click to reply option Reviewers: ashoat Reviewed By: ashoat Subscribers: zrebcu411, palys-swm, Adrian Differential Revision: https://phabricator.ashoat.com/D46
129,187
03.09.2020 08:44:08
14,400
80cce0248d5807996472304af9b6e57827f35759
Address security advisory in bl package Summary: See Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -3651,9 +3651,9 @@ binary@~0.3.0:\nchainsaw \"~0.1.0\"\nbl@^3.0.0:\n- version \"3.0.0\"\n- resolved \"https://registry.yarnpkg.com/bl/-/bl-3.0.0.tgz#3611ec00579fd18561754360b21e9f784500ff88\"\n- integrity sha512-EUAyP5UHU5hxF8BPT0LKW8gjYLhq1DQIcneOX/pL/m2Alo+OYDQAJlHq+yseMP50Os2nHXOSic6Ss3vSQeyf4A==\n+ version \"3.0.1\"\n+ resolved \"https://registry.yarnpkg.com/bl/-/bl-3.0.1.tgz#1cbb439299609e419b5a74d7fce2f8b37d8e5c6f\"\n+ integrity sha512-jrCW5ZhfQ/Vt07WX1Ngs+yn9BDqPL/gw28S7s9H6QK/gupnizNzJAss5akW20ISgOrbLTlXOOCTJeNUQqruAWQ==\ndependencies:\nreadable-stream \"^3.0.1\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Address security advisory in bl package Summary: See https://github.com/advisories/GHSA-pp7h-53gx-mx7r Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D58
129,186
26.08.2020 16:27:36
-7,200
54c01931d7effbd60064073de23b0c238b4698b7
[server] Add relationshipStatus to userInfo Reviewers: ashoat Subscribers: Adrian, KatPo, palys-swm
[ { "change_type": "MODIFY", "old_path": "lib/types/relationship-types.js", "new_path": "lib/types/relationship-types.js", "diff": "@@ -14,6 +14,16 @@ export const directedStatus = Object.freeze({\n});\nexport type DirectedStatus = $Values<typeof directedStatus>;\n+export const userRelationshipStatus = Object.freeze({\n+ REQUEST_SENT: 1,\n+ REQUEST_RECEIVED: 2,\n+ FRIEND: 3,\n+ BLOCKED_BY_VIEWER: 4,\n+ BLOCKED_VIEWER: 5,\n+ BOTH_BLOCKED: 6,\n+});\n+export type UserRelationshipStatus = $Values<typeof userRelationshipStatus>;\n+\nexport const relationshipActions = Object.freeze({\nFRIEND: 'friend',\nUNFRIEND: 'unfriend',\n" }, { "change_type": "MODIFY", "old_path": "lib/types/user-types.js", "new_path": "lib/types/user-types.js", "diff": "// @flow\nimport type { UserInconsistencyReportCreationRequest } from './report-types';\n+import type { UserRelationshipStatus } from './relationship-types';\nimport PropTypes from 'prop-types';\nexport type UserInfo = {|\nid: string,\nusername: ?string,\n+ relationshipStatus?: UserRelationshipStatus,\n|};\nexport type UserInfos = { [id: string]: UserInfo };\nexport const userInfoPropType = PropTypes.shape({\nid: PropTypes.string.isRequired,\nusername: PropTypes.string,\n+ relationshipStatus: PropTypes.number,\n});\nexport type AccountUserInfo = {|\nid: string,\nusername: string,\n+ relationshipStatus?: UserRelationshipStatus,\n|} & UserInfo;\nexport const accountUserInfoPropType = PropTypes.shape({\nid: PropTypes.string.isRequired,\nusername: PropTypes.string.isRequired,\n+ relationshipStatus: PropTypes.number,\n});\nexport type UserStore = {|\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/user-fetchers.js", "new_path": "server/src/fetchers/user-fetchers.js", "diff": "@@ -5,6 +5,11 @@ import type {\nCurrentUserInfo,\nLoggedInUserInfo,\n} from 'lib/types/user-types';\n+import {\n+ undirectedStatus,\n+ directedStatus,\n+ userRelationshipStatus,\n+} from 'lib/types/relationship-types';\nimport type { Viewer } from '../session/viewer';\nimport { ServerError } from 'lib/utils/errors';\n@@ -53,28 +58,88 @@ async function fetchKnownUserInfos(\n}\nconst query = SQL`\n- SELECT DISTINCT u.id, u.username FROM relationships_undirected r\n- LEFT JOIN users u ON r.user1 = u.id OR r.user2 = u.id\n+ SELECT ru.user1, ru.user2, ru.status AS undirected_status,\n+ rd1.status AS user1_directed_status, rd2.status AS user2_directed_status,\n+ u.username\n+ FROM relationships_undirected ru\n+ LEFT JOIN relationships_directed rd1\n+ ON rd1.user1 = ru.user1 AND rd1.user2 = ru.user2\n+ LEFT JOIN relationships_directed rd2\n+ ON rd2.user1 = ru.user2 AND rd2.user2 = ru.user1\n+ LEFT JOIN users u\n+ ON u.id != ${viewer.userID} AND (u.id = ru.user1 OR u.id = ru.user2)\n`;\nif (userIDs) {\nquery.append(SQL`\n- WHERE (r.user1 = ${viewer.userID} AND r.user2 IN (${userIDs})) OR\n- (r.user1 IN (${userIDs}) AND r.user2 = ${viewer.userID})\n+ WHERE (ru.user1 = ${viewer.userID} AND ru.user2 IN (${userIDs})) OR\n+ (ru.user1 IN (${userIDs}) AND ru.user2 = ${viewer.userID})\n`);\n} else {\nquery.append(SQL`\n- WHERE r.user1 = ${viewer.userID} OR r.user2 = ${viewer.userID}\n+ WHERE ru.user1 = ${viewer.userID} OR ru.user2 = ${viewer.userID}\n`);\n}\n+ query.append(SQL`\n+ UNION SELECT id AS user1, NULL AS user2, NULL AS undirected_status,\n+ NULL AS user1_directed_status, NULL AS user2_directed_status,\n+ username\n+ FROM users\n+ WHERE id = ${viewer.userID}\n+ `);\nconst [result] = await dbQuery(query);\nconst userInfos = {};\n- for (let row of result) {\n- const id = row.id.toString();\n- userInfos[id] = {\n+ for (const row of result) {\n+ const user1 = row.user1.toString();\n+ const user2 = row.user2 ? row.user2.toString() : null;\n+ const id = user1 === viewer.userID && user2 ? user2 : user1;\n+ const userInfo = {\nid,\nusername: row.username,\n};\n+\n+ if (!user2) {\n+ userInfos[id] = userInfo;\n+ continue;\n+ }\n+\n+ let viewerDirectedStatus;\n+ let targetDirectedStatus;\n+ if (user1 === viewer.userID) {\n+ viewerDirectedStatus = row.user1_directed_status;\n+ targetDirectedStatus = row.user2_directed_status;\n+ } else {\n+ viewerDirectedStatus = row.user2_directed_status;\n+ targetDirectedStatus = row.user1_directed_status;\n+ }\n+\n+ const viewerBlockedTarget = viewerDirectedStatus === directedStatus.BLOCKED;\n+ const targetBlockedViewer = targetDirectedStatus === directedStatus.BLOCKED;\n+ const friendshipExists = row.undirected_status === undirectedStatus.FRIEND;\n+ const viewerRequestedTargetFriendship =\n+ viewerDirectedStatus === directedStatus.PENDING_FRIEND;\n+ const targetRequestedViewerFriendship =\n+ targetDirectedStatus === directedStatus.PENDING_FRIEND;\n+\n+ let relationshipStatus;\n+ if (viewerBlockedTarget && targetBlockedViewer) {\n+ relationshipStatus = userRelationshipStatus.BOTH_BLOCKED;\n+ } else if (targetBlockedViewer) {\n+ relationshipStatus = userRelationshipStatus.BLOCKED_VIEWER;\n+ } else if (viewerBlockedTarget) {\n+ relationshipStatus = userRelationshipStatus.BLOCKED_BY_VIEWER;\n+ } else if (friendshipExists) {\n+ relationshipStatus = userRelationshipStatus.FRIEND;\n+ } else if (targetRequestedViewerFriendship) {\n+ relationshipStatus = userRelationshipStatus.REQUEST_RECEIVED;\n+ } else if (viewerRequestedTargetFriendship) {\n+ relationshipStatus = userRelationshipStatus.REQUEST_SENT;\n+ }\n+\n+ userInfos[id] = userInfo;\n+ if (relationshipStatus) {\n+ userInfos[id].relationshipStatus = relationshipStatus;\n+ }\n}\nreturn userInfos;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Add relationshipStatus to userInfo Reviewers: ashoat Reviewed By: ashoat Subscribers: Adrian, KatPo, palys-swm Differential Revision: https://phabricator.ashoat.com/D24
129,186
04.09.2020 14:16:21
-7,200
bf382d2913b857333a450ed1f3449fc77970ab34
[native] Rename scrollBlockingChatModals to scrollBlockingModals Reviewers: ashoat, palys-swm Subscribers: KatPo, Adrian
[ { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -23,7 +23,7 @@ import {\nThreadPickerModalRouteName,\nActionResultModalRouteName,\naccountModals,\n- scrollBlockingChatModals,\n+ scrollBlockingModals,\nchatRootModals,\nthreadRoutes,\n} from './route-names';\n@@ -86,7 +86,7 @@ const createActiveTabSelector: (\nbaseCreateActiveTabSelector,\n);\n-const scrollBlockingChatModalsClosedSelector: (\n+const scrollBlockingModalsClosedSelector: (\ncontext: ?NavContextType,\n) => boolean = createSelector(\n(context: ?NavContextType) => context && context.state,\n@@ -101,7 +101,7 @@ const scrollBlockingChatModalsClosedSelector: (\nconst appState = getStateFromNavigatorRoute(currentRootSubroute);\nfor (let i = appState.index; i >= 0; i--) {\nconst route = appState.routes[i];\n- if (scrollBlockingChatModals.includes(route.name)) {\n+ if (scrollBlockingModals.includes(route.name)) {\nreturn false;\n}\n}\n@@ -128,7 +128,7 @@ function selectBackgroundIsDark(\nwhile (currentAppSubroute.name === ActionResultModalRouteName) {\ncurrentAppSubroute = appState.routes[--appIndex];\n}\n- if (scrollBlockingChatModals.includes(currentAppSubroute.name)) {\n+ if (scrollBlockingModals.includes(currentAppSubroute.name)) {\n// All the scroll-blocking chat modals have a dark background\nreturn true;\n}\n@@ -255,7 +255,7 @@ export {\ncreateIsForegroundSelector,\nuseIsAppLoggedIn,\ncreateActiveTabSelector,\n- scrollBlockingChatModalsClosedSelector,\n+ scrollBlockingModalsClosedSelector,\nselectBackgroundIsDark,\nactiveThreadSelector,\nactiveMessageListSelector,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/overlay-navigator.react.js", "new_path": "native/navigation/overlay-navigator.react.js", "diff": "@@ -21,7 +21,7 @@ import { values } from 'lib/utils/objects';\nimport OverlayRouter from './overlay-router';\nimport { OverlayContext } from './overlay-context';\n-import { scrollBlockingChatModals, TabNavigatorRouteName } from './route-names';\n+import { scrollBlockingModals, TabNavigatorRouteName } from './route-names';\n/* eslint-disable import/no-named-as-default-member */\nconst { Value, timing, cond, call, lessOrEq, block } = Animated;\n@@ -116,7 +116,7 @@ const OverlayNavigator = React.memo<Props>(\nconst getScrollBlockingModalStatus = data => {\nlet status = 'closed';\nfor (let scene of data) {\n- if (!scrollBlockingChatModals.includes(scene.route.name)) {\n+ if (!scrollBlockingModals.includes(scene.route.name)) {\ncontinue;\n}\nif (!scene.context.isDismissing) {\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -136,7 +136,7 @@ export const accountModals = [\nVerificationModalRouteName,\n];\n-export const scrollBlockingChatModals = [\n+export const scrollBlockingModals = [\nMultimediaModalRouteName,\nMultimediaTooltipModalRouteName,\nTextMessageTooltipModalRouteName,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Rename scrollBlockingChatModals to scrollBlockingModals Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: KatPo, Adrian Differential Revision: https://phabricator.ashoat.com/D61
129,187
04.09.2020 13:29:06
14,400
982244e9262d6340bde039954dbdb976095ca8c9
[native] Fix TooltipItem.onPress type error on RelationshipListItemTooltipModal Summary: The change in [D46](https://phabricator.ashoat.com/D46#change-pgdfH5OkaDaJ) caused an issue when [D45](https://phabricator.ashoat.com/D45#change-fhAu2faz5ErC) was rebased on top of it. Reviewers: KatPo, palys-swm Subscribers: zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/more/relationship-list-item-tooltip-modal.react.js", "new_path": "native/more/relationship-list-item-tooltip-modal.react.js", "diff": "@@ -69,14 +69,22 @@ const spec = {\n{\nid: 'unfriend',\ntext: 'Unfriend',\n- onPress: (props, ...rest) =>\n- onRemoveUser({ ...props, action: 'unfriend' }, ...rest),\n+ onPress: (props, dispatchFunctions, bindServerCall) =>\n+ onRemoveUser(\n+ { ...props, action: 'unfriend' },\n+ dispatchFunctions,\n+ bindServerCall,\n+ ),\n},\n{\nid: 'unblock',\ntext: 'Unblock',\n- onPress: (props, ...rest) =>\n- onRemoveUser({ ...props, action: 'unblock' }, ...rest),\n+ onPress: (props, dispatchFunctions, bindServerCall) =>\n+ onRemoveUser(\n+ { ...props, action: 'unblock' },\n+ dispatchFunctions,\n+ bindServerCall,\n+ ),\n},\n],\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix TooltipItem.onPress type error on RelationshipListItemTooltipModal Summary: The change in [D46](https://phabricator.ashoat.com/D46#change-pgdfH5OkaDaJ) caused an issue when [D45](https://phabricator.ashoat.com/D45#change-fhAu2faz5ErC) was rebased on top of it. Reviewers: KatPo, palys-swm Reviewed By: palys-swm Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D64
129,187
04.09.2020 14:42:25
14,400
9d8e3c386b271e55b3b22b3fa53d6b22cd694e03
[lib] Fix type of promiseAll Summary: I noticed that this was not typing the results correctly. It should be fixed now Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "lib/types/filter-types.js", "new_path": "lib/types/filter-types.js", "diff": "@@ -28,7 +28,7 @@ export const calendarFilterPropType = PropTypes.oneOfType([\n}),\n]);\n-export const defaultCalendarFilters = [\n+export const defaultCalendarFilters: $ReadOnlyArray<CalendarFilter> = [\n{ type: calendarThreadFilterTypes.NOT_DELETED },\n];\n" }, { "change_type": "MODIFY", "old_path": "lib/types/socket-types.js", "new_path": "lib/types/socket-types.js", "diff": "@@ -291,16 +291,14 @@ export const connectionInfoPropType = PropTypes.shape({\nlateResponses: PropTypes.arrayOf(PropTypes.number).isRequired,\nshowDisconnectedBar: PropTypes.bool.isRequired,\n});\n-export const defaultConnectionInfo = (\n- platform: Platform,\n- timeZone?: ?string,\n-) => ({\n+export const defaultConnectionInfo = (platform: Platform, timeZone?: ?string) =>\n+ ({\nstatus: 'connecting',\nqueuedActivityUpdates: [],\nactualizedCalendarQuery: defaultCalendarQuery(platform, timeZone),\nlateResponses: [],\nshowDisconnectedBar: false,\n-});\n+ }: ConnectionInfo);\nexport const updateConnectionStatusActionType = 'UPDATE_CONNECTION_STATUS';\nexport type UpdateConnectionStatusPayload = {|\nstatus: ConnectionStatus,\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/promises.js", "new_path": "lib/utils/promises.js", "diff": "// @flow\ntype Promisable<T> = Promise<T> | T;\n-type SpinPromise = <V>(promise: Promisable<V>) => V;\nasync function promiseAll<T: { [key: string]: Promisable<*> }>(\ninput: T,\n-): Promise<$ObjMap<T, SpinPromise>> {\n+): Promise<$ObjMap<T, typeof $await>> {\nconst promises = [];\nconst keys = Object.keys(input);\nfor (let i = 0; i < keys.length; i++) {\n" }, { "change_type": "MODIFY", "old_path": "native/media/save-media.js", "new_path": "native/media/save-media.js", "diff": "@@ -13,6 +13,7 @@ import {\nimport { Platform, PermissionsAndroid } from 'react-native';\nimport filesystem from 'react-native-fs';\nimport * as MediaLibrary from 'expo-media-library';\n+import invariant from 'invariant';\nimport { readableFilename, pathFromURI } from 'lib/media/file-utils';\nimport { promiseAll } from 'lib/utils/promises';\n@@ -406,6 +407,8 @@ async function copyToSortedDirectory(\nsteps,\n};\n}\n+ const { hash } = hashStep;\n+ invariant(hash, 'hash should be truthy if hashStep.success is truthy');\nif (fileInfoResult) {\nsteps.push(...fileInfoResult.steps);\n@@ -420,7 +423,7 @@ async function copyToSortedDirectory(\n};\n}\n- const name = readableFilename(hashStep.hash, mime);\n+ const name = readableFilename(hash, mime);\nif (!name) {\nreturn {\nresult: { success: false, reason: 'mime_check_failed', mime },\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -285,8 +285,10 @@ async function websiteResponder(\nwindowActive: true,\n};\n- const state = await promiseAll(statePromises);\n+ const stateResult = await promiseAll(statePromises);\n+ const state: AppState = { ...stateResult };\nconst store: Store<AppState, Action> = createStore(reducer, state);\n+\nconst routerContext = {};\nconst reactStream = renderToNodeStream(\n<Provider store={store}>\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/session-utils.js", "new_path": "server/src/socket/session-utils.js", "diff": "@@ -445,12 +445,16 @@ async function checkState(\nstateChanges.deleteUserInfoIDs = [];\n}\nstateChanges.deleteUserInfoIDs.push(userID);\n- continue;\n- }\n+ } else {\nif (!stateChanges.userInfos) {\nstateChanges.userInfos = [];\n}\n- stateChanges.userInfos.push(userInfo);\n+ stateChanges.userInfos.push({\n+ ...userInfo,\n+ // Flow gets confused if we don't do this\n+ username: userInfo.username,\n+ });\n+ }\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Fix type of promiseAll Summary: I noticed that this was not typing the results correctly. It should be fixed now Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D65
129,186
04.09.2020 12:27:35
14,400
6cf84ca051f1450b69e539fa18cf3d105320e68c
Add GlobalUserInfo type Reviewers: zrebcu411, palys-swm Subscribers: KatPo, palys-swm, Adrian
[ { "change_type": "MODIFY", "old_path": "lib/types/search-types.js", "new_path": "lib/types/search-types.js", "diff": "// @flow\n-import type { AccountUserInfo } from './user-types';\n+import type { GlobalAccountUserInfo } from './user-types';\nexport type UserSearchRequest = {|\nprefix?: string,\n|};\nexport type UserSearchResult = {|\n- userInfos: $ReadOnlyArray<AccountUserInfo>,\n+ userInfos: $ReadOnlyArray<GlobalAccountUserInfo>,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/user-types.js", "new_path": "lib/types/user-types.js", "diff": "@@ -5,6 +5,16 @@ import type { UserRelationshipStatus } from './relationship-types';\nimport PropTypes from 'prop-types';\n+export type GlobalUserInfo = {|\n+ id: string,\n+ username: ?string,\n+|};\n+\n+export type GlobalAccountUserInfo = {|\n+ id: string,\n+ username: string,\n+|};\n+\nexport type UserInfo = {|\nid: string,\nusername: ?string,\n" }, { "change_type": "MODIFY", "old_path": "native/more/relationship-update-modal.react.js", "new_path": "native/more/relationship-update-modal.react.js", "diff": "// @flow\n-import type { AccountUserInfo } from 'lib/types/user-types';\n+import type {\n+ GlobalAccountUserInfo,\n+ AccountUserInfo,\n+} from 'lib/types/user-types';\nimport type { UserSearchResult } from 'lib/types/search-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport {\n@@ -61,8 +64,8 @@ type Props = {|\ntype State = {|\nusernameInputText: string,\n- userInfoInputArray: $ReadOnlyArray<AccountUserInfo>,\n- searchUserInfos: { [id: string]: AccountUserInfo },\n+ userInfoInputArray: $ReadOnlyArray<GlobalAccountUserInfo>,\n+ searchUserInfos: { [id: string]: GlobalAccountUserInfo },\n|};\ntype PropsAndState = {| ...Props, ...State |};\n@@ -94,10 +97,10 @@ class RelationshipUpdateModal extends React.PureComponent<Props, State> {\n(propsAndState: PropsAndState) => propsAndState.userInfoInputArray,\n(\ntext: string,\n- searchUserInfos: { [id: string]: AccountUserInfo },\n+ searchUserInfos: { [id: string]: GlobalAccountUserInfo },\nuserInfos: { [id: string]: AccountUserInfo },\nviewerID: ?string,\n- userInfoInputArray: $ReadOnlyArray<AccountUserInfo>,\n+ userInfoInputArray: $ReadOnlyArray<GlobalAccountUserInfo>,\n) => {\nconst { target } = this.props.route.params;\nconst excludeStatuses = [];\n@@ -117,10 +120,12 @@ class RelationshipUpdateModal extends React.PureComponent<Props, State> {\n.map(userInfo => userInfo.id)\n.concat(viewerID || [])\n.concat(excludeBlockedAndFriendIDs);\n- const searchIndex = searchIndexFromUserInfos(searchUserInfos);\n+ // $FlowFixMe should be fixed in flow-bin@0.115 / react-native@0.63\n+ const mergedUserInfos = { ...searchUserInfos, ...userInfos };\n+ const searchIndex = searchIndexFromUserInfos(mergedUserInfos);\nconst results = getUserSearchResults(\ntext,\n- searchUserInfos,\n+ mergedUserInfos,\nsearchIndex,\nexcludeUserIDs,\n);\n@@ -208,7 +213,9 @@ class RelationshipUpdateModal extends React.PureComponent<Props, State> {\nthis.setState({ usernameInputText: text });\n};\n- onChangeTagInput = (userInfoInputArray: $ReadOnlyArray<AccountUserInfo>) => {\n+ onChangeTagInput = (\n+ userInfoInputArray: $ReadOnlyArray<GlobalAccountUserInfo>,\n+ ) => {\nthis.setState({ userInfoInputArray });\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/user-fetchers.js", "new_path": "server/src/fetchers/user-fetchers.js", "diff": "@@ -4,6 +4,7 @@ import type {\nUserInfos,\nCurrentUserInfo,\nLoggedInUserInfo,\n+ GlobalUserInfo,\n} from 'lib/types/user-types';\nimport {\nundirectedStatus,\n@@ -16,7 +17,9 @@ import { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL } from '../database';\n-async function fetchUserInfos(userIDs: string[]): Promise<UserInfos> {\n+async function fetchUserInfos(\n+ userIDs: string[],\n+): Promise<{ [id: string]: GlobalUserInfo }> {\nif (userIDs.length <= 0) {\nreturn {};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/search/users.js", "new_path": "server/src/search/users.js", "diff": "// @flow\n-import type { AccountUserInfo } from 'lib/types/user-types';\n+import type { GlobalAccountUserInfo } from 'lib/types/user-types';\nimport type { UserSearchRequest } from 'lib/types/search-types';\nimport { dbQuery, SQL } from '../database';\nasync function searchForUsers(\nquery: UserSearchRequest,\n-): Promise<AccountUserInfo[]> {\n+): Promise<GlobalAccountUserInfo[]> {\nconst sqlQuery = SQL`SELECT id, username FROM users `;\nconst prefix = query.prefix;\nif (prefix) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Add GlobalUserInfo type Reviewers: zrebcu411, palys-swm Reviewed By: palys-swm Subscribers: KatPo, palys-swm, Adrian Differential Revision: https://phabricator.ashoat.com/D60
129,187
04.09.2020 15:09:23
14,400
deda7324c9a698975f4b1ed90b8331aaa3b4c6dc
[native] Fix onUserSelect in RelationshipUpdateModal Summary: In D45 I asked to include search results from the `userStore`, but he neglected to update `onUserSelect` to handle selecting these results Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/more/relationship-update-modal.react.js", "new_path": "native/more/relationship-update-modal.react.js", "diff": "@@ -224,7 +224,12 @@ class RelationshipUpdateModal extends React.PureComponent<Props, State> {\nreturn;\n}\n- const selectedUserInfo = this.state.searchUserInfos[userID];\n+ let selectedUserInfo = this.state.searchUserInfos[userID];\n+ if (!selectedUserInfo) {\n+ const userInfo = this.props.userInfos[userID];\n+ selectedUserInfo = { id: userInfo.id, username: userInfo.username };\n+ }\n+ invariant(selectedUserInfo, `could not find selected userID ${userID}`);\nthis.setState(state => ({\nuserInfoInputArray: state.userInfoInputArray.concat(selectedUserInfo),\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix onUserSelect in RelationshipUpdateModal Summary: In D45 I asked @zrebcu411 to include search results from the `userStore`, but he neglected to update `onUserSelect` to handle selecting these results Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D66
129,187
09.09.2020 15:37:14
14,400
8288be5ca887254486cae6b4cf744121c5b2ed02
[web] Remove translateZ(0) no-op in MessageList Summary: I initially introduced this because of a ["weird glitch"](https://github.com/Ashoat/squadcal/commit/81ba46dd20646df2bc8e74950ae92c84733a7384), but I can't reproduce it anymore. I'm guessing the browser bug has been fixed Reviewers: KatPo, palys-swm Subscribers: zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.css", "new_path": "web/chat/chat-message-list.css", "diff": "@@ -21,11 +21,8 @@ div.firefoxMessageContainer {\nflex-direction: column !important;\ntransform: scaleY(-1);\n}\n-div.messageContainer > div {\n- transform: translateZ(0);\n-}\ndiv.firefoxMessageContainer > div {\n- transform: translateZ(0) scaleY(-1) !important;\n+ transform: scaleY(-1);\n}\ndiv.message {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Remove translateZ(0) no-op in MessageList Summary: I initially introduced this because of a ["weird glitch"](https://github.com/Ashoat/squadcal/commit/81ba46dd20646df2bc8e74950ae92c84733a7384), but I can't reproduce it anymore. I'm guessing the browser bug has been fixed Reviewers: KatPo, palys-swm Reviewed By: KatPo, palys-swm Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D79
129,183
03.09.2020 15:18:05
-7,200
5ea4e156834e47907c0e394908a6a78c82b5e07e
[web] Add option to click on message Reviewers: ashoat Subscribers: zrebcu411, palys-swm, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.css", "new_path": "web/chat/chat-message-list.css", "diff": "@@ -165,6 +165,22 @@ div.messageTimestampBottomRightTooltip:after {\nborder-color: transparent transparent black transparent;\n}\n+div.messageReplyTooltip {\n+ position: relative;\n+ color: gray;\n+ padding: 15px;\n+ font-size: 14px;\n+}\n+div.messageReplyTooltipIcon {\n+ position: absolute;\n+ top: 50%;\n+ left: 50%;\n+ transform: translate(-50%, -50%);\n+}\n+div.messageReplyTooltipIcon:hover {\n+ cursor: pointer;\n+}\n+\ndiv.textMessage {\npadding: 6px 12px;\nwhite-space: pre-wrap;\n@@ -225,16 +241,32 @@ div.iconContainer > svg {\nheight: 16px;\n}\n-div.messageBox {\n+div.messageBoxContainer {\n+ position: relative;\n+ display: flex;\n+ max-width: calc(min(68%, 1000px));\nmargin: 0 4px 0 12px;\n+}\n+div.nonViewerMessageBoxContainer {\n+ justify-content: flex-start;\n+}\n+div.viewerMessageBoxContainer {\n+ justify-content: flex-end;\n+}\n+div.fixedWidthMessageBoxContainer {\n+ width: 68%;\n+}\n+\n+div.messageBox {\noverflow: hidden;\ndisplay: flex;\nflex-wrap: wrap;\njustify-content: space-between;\n- max-width: calc(min(68%, 1000px));\n+ flex-shrink: 0;\n+ max-width: 100%;\n}\ndiv.fixedWidthMessageBox {\n- width: 68%;\n+ width: 100%;\n}\ndiv.failedSend {\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.react.js", "new_path": "web/chat/chat-message-list.react.js", "diff": "@@ -32,10 +32,11 @@ import { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { webMessageListData } from '../selectors/chat-selectors';\nimport ChatInputBar from './chat-input-bar.react';\n-import Message, {\n- type MessagePositionInfo,\n- type OnMessagePositionInfo,\n-} from './message.react';\n+import Message from './message.react';\n+import type {\n+ OnMessagePositionInfo,\n+ MessagePositionInfo,\n+} from './message-position-types';\nimport LoadingIndicator from '../loading-indicator.react';\nimport MessageTimestampTooltip from './message-timestamp-tooltip.react';\nimport {\n@@ -76,7 +77,7 @@ type Props = {|\n...ReactDnDProps,\n|};\ntype State = {|\n- messageMouseover: ?OnMessagePositionInfo,\n+ +mouseOverMessagePosition: ?OnMessagePositionInfo,\n|};\ntype Snapshot = {|\n+scrolledToBottom: boolean,\n@@ -96,7 +97,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\ninputState: inputStatePropType,\n};\nstate = {\n- messageMouseover: null,\n+ mouseOverMessagePosition: null,\n};\ncontainer: ?HTMLDivElement;\nmessageContainer: ?HTMLDivElement;\n@@ -219,7 +220,8 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n<Message\nitem={item}\nthreadInfo={threadInfo}\n- setMouseOver={this.setTimestampTooltip}\n+ setMouseOverMessagePosition={this.setMouseOverMessagePosition}\n+ mouseOverMessagePosition={this.state.mouseOverMessagePosition}\nsetModal={setModal}\ntimeZone={this.props.timeZone}\nkey={ChatMessageList.keyExtractor(item)}\n@@ -227,22 +229,16 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n);\n};\n- setTimestampTooltip = (messagePositionInfo: MessagePositionInfo) => {\n+ setMouseOverMessagePosition = (messagePositionInfo: MessagePositionInfo) => {\nif (!this.messageContainer) {\nreturn;\n}\nif (messagePositionInfo.type === 'off') {\n- if (\n- this.state.messageMouseover &&\n- ChatMessageList.keyExtractor(this.state.messageMouseover.item) ===\n- ChatMessageList.keyExtractor(messagePositionInfo.item)\n- ) {\n- this.setState({ messageMouseover: null });\n- }\n+ this.setState({ mouseOverMessagePosition: null });\nreturn;\n}\nconst containerTop = this.messageContainer.getBoundingClientRect().top;\n- const messageMouseover = {\n+ const mouseOverMessagePosition = {\n...messagePositionInfo,\nmessagePosition: {\n...messagePositionInfo.messagePosition,\n@@ -250,7 +246,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nbottom: messagePositionInfo.messagePosition.bottom - containerTop,\n},\n};\n- this.setState({ messageMouseover });\n+ this.setState({ mouseOverMessagePosition });\n};\nrender() {\n@@ -274,7 +270,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nconst tooltip = (\n<MessageTimestampTooltip\n- messagePositionInfo={this.state.messageMouseover}\n+ messagePositionInfo={this.state.mouseOverMessagePosition}\ntimeZone={this.props.timeZone}\n/>\n);\n@@ -332,8 +328,8 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nif (!this.messageContainer) {\nreturn;\n}\n- if (this.state.messageMouseover) {\n- this.setState({ messageMouseover: null });\n+ if (this.state.mouseOverMessagePosition) {\n+ this.setState({ mouseOverMessagePosition: null });\n}\nthis.possiblyLoadMoreMessages();\n};\n" }, { "change_type": "MODIFY", "old_path": "web/chat/composed-message.react.js", "new_path": "web/chat/composed-message.react.js", "diff": "@@ -6,7 +6,11 @@ import {\n} from 'lib/selectors/chat-selectors';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport { assertComposableMessageType } from 'lib/types/message-types';\n-import type { MessagePositionInfo } from './message.react';\n+import {\n+ type OnMessagePositionInfo,\n+ type MessagePositionInfo,\n+ onMessagePositionInfoPropType,\n+} from './message-position-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -21,14 +25,19 @@ import { stringForUser } from 'lib/shared/user-utils';\nimport FailedSend from './failed-send.react';\nimport css from './chat-message-list.css';\n+import MessageReplyTooltip from './message-reply-tooltip.react';\ntype Props = {|\nitem: ChatMessageInfoItem,\nthreadInfo: ThreadInfo,\nsendFailed: boolean,\n- setMouseOver: (messagePositionInfo: MessagePositionInfo) => void,\n+ setMouseOverMessagePosition: (\n+ messagePositionInfo: MessagePositionInfo,\n+ ) => void,\n+ mouseOverMessagePosition?: ?OnMessagePositionInfo,\n+ canReply: boolean,\nchildren: React.Node,\n- className?: ?string,\n+ fixedWidth?: boolean,\nborderRadius: number,\n|};\nclass ComposedMessage extends React.PureComponent<Props> {\n@@ -36,9 +45,11 @@ class ComposedMessage extends React.PureComponent<Props> {\nitem: chatMessageItemPropType.isRequired,\nthreadInfo: threadInfoPropType.isRequired,\nsendFailed: PropTypes.bool.isRequired,\n- setMouseOver: PropTypes.func.isRequired,\n+ setMouseOverMessagePosition: PropTypes.func.isRequired,\n+ mouseOverMessagePosition: onMessagePositionInfoPropType,\n+ canReply: PropTypes.bool.isRequired,\nchildren: PropTypes.node.isRequired,\n- className: PropTypes.string,\n+ fixedWidth: PropTypes.bool,\nborderRadius: PropTypes.number.isRequired,\n};\nstatic defaultProps = {\n@@ -57,6 +68,16 @@ class ComposedMessage extends React.PureComponent<Props> {\n[css.viewerContent]: isViewer,\n[css.nonViewerContent]: !isViewer,\n});\n+ const messageBoxContainerClassName = classNames({\n+ [css.messageBoxContainer]: true,\n+ [css.viewerMessageBoxContainer]: isViewer,\n+ [css.nonViewerMessageBoxContainer]: !isViewer,\n+ [css.fixedWidthMessageBoxContainer]: this.props.fixedWidth,\n+ });\n+ const messageBoxClassName = classNames({\n+ [css.messageBox]: true,\n+ [css.fixedWidthMessageBox]: this.props.fixedWidth,\n+ });\nconst messageBoxStyle = {\nborderTopRightRadius: isViewer && !item.startsCluster ? 0 : borderRadius,\nborderBottomRightRadius: isViewer && !item.endsCluster ? 0 : borderRadius,\n@@ -95,18 +116,40 @@ class ComposedMessage extends React.PureComponent<Props> {\n);\n}\n+ let viewerTooltip, nonViewerTooltip;\n+ if (\n+ this.props.mouseOverMessagePosition &&\n+ this.props.mouseOverMessagePosition.item.messageInfo.id === id &&\n+ this.props.canReply\n+ ) {\n+ const replyTooltip = (\n+ <MessageReplyTooltip\n+ messagePositionInfo={this.props.mouseOverMessagePosition}\n+ onReplyClick={this.onMouseLeave}\n+ />\n+ );\n+ if (isViewer) {\n+ viewerTooltip = replyTooltip;\n+ } else {\n+ nonViewerTooltip = replyTooltip;\n+ }\n+ }\n+\nreturn (\n<React.Fragment>\n{authorName}\n<div className={contentClassName}>\n<div\n- className={classNames(css.messageBox, this.props.className)}\n- style={messageBoxStyle}\n- onMouseOver={this.onMouseOver}\n- onMouseOut={this.onMouseOut}\n+ className={messageBoxContainerClassName}\n+ onMouseEnter={this.onMouseEnter}\n+ onMouseLeave={this.onMouseLeave}\n>\n+ {viewerTooltip}\n+ <div className={messageBoxClassName} style={messageBoxStyle}>\n{this.props.children}\n</div>\n+ {nonViewerTooltip}\n+ </div>\n{deliveryIcon}\n</div>\n{failedSendInfo}\n@@ -114,17 +157,21 @@ class ComposedMessage extends React.PureComponent<Props> {\n);\n}\n- onMouseOver = (event: SyntheticEvent<HTMLDivElement>) => {\n+ onMouseEnter = (event: SyntheticEvent<HTMLDivElement>) => {\nconst { item } = this.props;\nconst rect = event.currentTarget.getBoundingClientRect();\nconst { top, bottom, left, right, height, width } = rect;\nconst messagePosition = { top, bottom, left, right, height, width };\n- this.props.setMouseOver({ type: 'on', item, messagePosition });\n+ this.props.setMouseOverMessagePosition({\n+ type: 'on',\n+ item,\n+ messagePosition,\n+ });\n};\n- onMouseOut = () => {\n+ onMouseLeave = () => {\nconst { item } = this.props;\n- this.props.setMouseOver({ type: 'off', item });\n+ this.props.setMouseOverMessagePosition({ type: 'off', item });\n};\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/chat/message-position-types.js", "diff": "+// @flow\n+\n+import {\n+ type ChatMessageInfoItem,\n+ chatMessageItemPropType,\n+} from 'lib/selectors/chat-selectors';\n+\n+import PropTypes from 'prop-types';\n+\n+export const onMessagePositionInfoPropType = PropTypes.exact({\n+ type: PropTypes.oneOf(['on']).isRequired,\n+ item: chatMessageItemPropType.isRequired,\n+ messagePosition: PropTypes.exact({\n+ top: PropTypes.number.isRequired,\n+ bottom: PropTypes.number.isRequired,\n+ left: PropTypes.number.isRequired,\n+ right: PropTypes.number.isRequired,\n+ height: PropTypes.number.isRequired,\n+ width: PropTypes.number.isRequired,\n+ }),\n+});\n+\n+export type OnMessagePositionInfo = {|\n+ +type: 'on',\n+ +item: ChatMessageInfoItem,\n+ +messagePosition: {|\n+ +top: number,\n+ +bottom: number,\n+ +left: number,\n+ +right: number,\n+ +height: number,\n+ +width: number,\n+ |},\n+|};\n+\n+export type MessagePositionInfo =\n+ | OnMessagePositionInfo\n+ | {|\n+ +type: 'off',\n+ +item: ChatMessageInfoItem,\n+ |};\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/chat/message-reply-tooltip.react.js", "diff": "+// @flow\n+\n+import type { OnMessagePositionInfo } from './message-position-types';\n+\n+import * as React from 'react';\n+import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\n+import { faReply } from '@fortawesome/free-solid-svg-icons';\n+\n+import css from './chat-message-list.css';\n+\n+type Props = {|\n+ +messagePositionInfo: OnMessagePositionInfo,\n+ +onReplyClick: () => void,\n+|};\n+function MessageReplyTooltip(props: Props) {\n+ return (\n+ <div className={css.messageReplyTooltip}>\n+ <div className={css.messageReplyTooltipIcon} onClick={props.onReplyClick}>\n+ <FontAwesomeIcon icon={faReply} />\n+ </div>\n+ </div>\n+ );\n+}\n+\n+export default MessageReplyTooltip;\n" }, { "change_type": "MODIFY", "old_path": "web/chat/message-timestamp-tooltip.react.js", "new_path": "web/chat/message-timestamp-tooltip.react.js", "diff": "// @flow\n-import type { OnMessagePositionInfo } from './message.react';\n+import type { OnMessagePositionInfo } from './message-position-types';\nimport { isComposableMessageType } from 'lib/types/message-types';\nimport * as React from 'react';\n" }, { "change_type": "MODIFY", "old_path": "web/chat/message.react.js", "new_path": "web/chat/message.react.js", "diff": "@@ -6,6 +6,11 @@ import {\n} from 'lib/selectors/chat-selectors';\nimport { messageTypes } from 'lib/types/message-types';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n+import {\n+ type OnMessagePositionInfo,\n+ type MessagePositionInfo,\n+ onMessagePositionInfoPropType,\n+} from './message-position-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -18,28 +23,13 @@ import RobotextMessage from './robotext-message.react';\nimport MultimediaMessage from './multimedia-message.react';\nimport css from './chat-message-list.css';\n-export type OnMessagePositionInfo = {|\n- type: 'on',\n- item: ChatMessageInfoItem,\n- messagePosition: {|\n- top: number,\n- bottom: number,\n- left: number,\n- right: number,\n- height: number,\n- width: number,\n- |},\n-|};\n-export type MessagePositionInfo =\n- | OnMessagePositionInfo\n- | {|\n- type: 'off',\n- item: ChatMessageInfoItem,\n- |};\ntype Props = {|\nitem: ChatMessageInfoItem,\nthreadInfo: ThreadInfo,\n- setMouseOver: (messagePositionInfo: MessagePositionInfo) => void,\n+ setMouseOverMessagePosition: (\n+ messagePositionInfo: MessagePositionInfo,\n+ ) => void,\n+ mouseOverMessagePosition: ?OnMessagePositionInfo,\nsetModal: (modal: ?React.Node) => void,\ntimeZone: ?string,\n|};\n@@ -47,7 +37,8 @@ class Message extends React.PureComponent<Props> {\nstatic propTypes = {\nitem: chatMessageItemPropType.isRequired,\nthreadInfo: threadInfoPropType.isRequired,\n- setMouseOver: PropTypes.func.isRequired,\n+ setMouseOverMessagePosition: PropTypes.func.isRequired,\n+ mouseOverMessagePosition: onMessagePositionInfoPropType,\nsetModal: PropTypes.func.isRequired,\ntimeZone: PropTypes.string,\n};\n@@ -69,7 +60,8 @@ class Message extends React.PureComponent<Props> {\n<TextMessage\nitem={item}\nthreadInfo={this.props.threadInfo}\n- setMouseOver={this.props.setMouseOver}\n+ setMouseOverMessagePosition={this.props.setMouseOverMessagePosition}\n+ mouseOverMessagePosition={this.props.mouseOverMessagePosition}\n/>\n);\n} else if (\n@@ -80,14 +72,17 @@ class Message extends React.PureComponent<Props> {\n<MultimediaMessage\nitem={item}\nthreadInfo={this.props.threadInfo}\n- setMouseOver={this.props.setMouseOver}\n+ setMouseOverMessagePosition={this.props.setMouseOverMessagePosition}\nsetModal={this.props.setModal}\n/>\n);\n} else {\ninvariant(item.robotext, \"Flow can't handle our fancy types :(\");\nmessage = (\n- <RobotextMessage item={item} setMouseOver={this.props.setMouseOver} />\n+ <RobotextMessage\n+ item={item}\n+ setMouseOverMessagePosition={this.props.setMouseOverMessagePosition}\n+ />\n);\n}\nreturn (\n" }, { "change_type": "MODIFY", "old_path": "web/chat/multimedia-message.react.js", "new_path": "web/chat/multimedia-message.react.js", "diff": "@@ -5,7 +5,7 @@ import {\nchatMessageItemPropType,\n} from 'lib/selectors/chat-selectors';\nimport { messageTypes } from 'lib/types/message-types';\n-import type { MessagePositionInfo } from './message.react';\n+import type { MessagePositionInfo } from './message-position-types';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport * as React from 'react';\n@@ -25,7 +25,9 @@ import {\ntype Props = {|\nitem: ChatMessageInfoItem,\nthreadInfo: ThreadInfo,\n- setMouseOver: (messagePositionInfo: MessagePositionInfo) => void,\n+ setMouseOverMessagePosition: (\n+ messagePositionInfo: MessagePositionInfo,\n+ ) => void,\nsetModal: (modal: ?React.Node) => void,\n// withInputState\ninputState: InputState,\n@@ -34,7 +36,7 @@ class MultimediaMessage extends React.PureComponent<Props> {\nstatic propTypes = {\nitem: chatMessageItemPropType.isRequired,\nthreadInfo: threadInfoPropType.isRequired,\n- setMouseOver: PropTypes.func.isRequired,\n+ setMouseOverMessagePosition: PropTypes.func.isRequired,\nsetModal: PropTypes.func.isRequired,\ninputState: inputStatePropType.isRequired,\n};\n@@ -75,15 +77,15 @@ class MultimediaMessage extends React.PureComponent<Props> {\n) : (\nmultimedia\n);\n- const className = multimedia.length > 1 ? css.fixedWidthMessageBox : null;\nreturn (\n<ComposedMessage\nitem={item}\nthreadInfo={this.props.threadInfo}\nsendFailed={sendFailed(this.props.item, this.props.inputState)}\n- setMouseOver={this.props.setMouseOver}\n- className={className}\n+ setMouseOverMessagePosition={this.props.setMouseOverMessagePosition}\n+ canReply={false}\n+ fixedWidth={multimedia.length > 1}\nborderRadius={16}\n>\n{content}\n" }, { "change_type": "MODIFY", "old_path": "web/chat/robotext-message.react.js", "new_path": "web/chat/robotext-message.react.js", "diff": "@@ -12,7 +12,7 @@ import {\nupdateNavInfoActionType,\n} from '../redux/redux-setup';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type { MessagePositionInfo } from './message.react';\n+import type { MessagePositionInfo } from './message-position-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -27,18 +27,20 @@ import { linkRules } from '../markdown/rules.react';\ntype Props = {|\nitem: RobotextChatMessageInfoItem,\n- setMouseOver: (messagePositionInfo: MessagePositionInfo) => void,\n+ setMouseOverMessagePosition: (\n+ messagePositionInfo: MessagePositionInfo,\n+ ) => void,\n|};\nclass RobotextMessage extends React.PureComponent<Props> {\nstatic propTypes = {\nitem: chatMessageItemPropType.isRequired,\n- setMouseOver: PropTypes.func.isRequired,\n+ setMouseOverMessagePosition: PropTypes.func.isRequired,\n};\nrender() {\nreturn (\n<div className={css.robotext}>\n- <span onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut}>\n+ <span onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>\n{this.linkedRobotext()}\n</span>\n</div>\n@@ -79,17 +81,21 @@ class RobotextMessage extends React.PureComponent<Props> {\nreturn textParts;\n}\n- onMouseOver = (event: SyntheticEvent<HTMLDivElement>) => {\n+ onMouseEnter = (event: SyntheticEvent<HTMLDivElement>) => {\nconst { item } = this.props;\nconst rect = event.currentTarget.getBoundingClientRect();\nconst { top, bottom, left, right, height, width } = rect;\nconst messagePosition = { top, bottom, left, right, height, width };\n- this.props.setMouseOver({ type: 'on', item, messagePosition });\n+ this.props.setMouseOverMessagePosition({\n+ type: 'on',\n+ item,\n+ messagePosition,\n+ });\n};\n- onMouseOut = () => {\n+ onMouseLeave = () => {\nconst { item } = this.props;\n- this.props.setMouseOver({ type: 'off', item });\n+ this.props.setMouseOverMessagePosition({ type: 'off', item });\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "web/chat/text-message.react.js", "new_path": "web/chat/text-message.react.js", "diff": "@@ -6,7 +6,11 @@ import {\n} from 'lib/selectors/chat-selectors';\nimport { messageTypes } from 'lib/types/message-types';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type { MessagePositionInfo } from './message.react';\n+import {\n+ type MessagePositionInfo,\n+ type OnMessagePositionInfo,\n+ onMessagePositionInfoPropType,\n+} from './message-position-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -25,13 +29,17 @@ import { markdownRules } from '../markdown/rules.react';\ntype Props = {|\nitem: ChatMessageInfoItem,\nthreadInfo: ThreadInfo,\n- setMouseOver: (messagePositionInfo: MessagePositionInfo) => void,\n+ setMouseOverMessagePosition: (\n+ messagePositionInfo: MessagePositionInfo,\n+ ) => void,\n+ mouseOverMessagePosition: ?OnMessagePositionInfo,\n|};\nclass TextMessage extends React.PureComponent<Props> {\nstatic propTypes = {\nitem: chatMessageItemPropType.isRequired,\nthreadInfo: threadInfoPropType.isRequired,\n- setMouseOver: PropTypes.func.isRequired,\n+ setMouseOverMessagePosition: PropTypes.func.isRequired,\n+ mouseOverMessagePosition: onMessagePositionInfoPropType,\n};\nconstructor(props: Props) {\n@@ -83,7 +91,9 @@ class TextMessage extends React.PureComponent<Props> {\nitem={this.props.item}\nthreadInfo={this.props.threadInfo}\nsendFailed={textMessageSendFailed(this.props.item)}\n- setMouseOver={this.props.setMouseOver}\n+ setMouseOverMessagePosition={this.props.setMouseOverMessagePosition}\n+ mouseOverMessagePosition={this.props.mouseOverMessagePosition}\n+ canReply={true}\n>\n<div className={messageClassName} style={messageStyle}>\n<Markdown useDarkStyle={darkColor} rules={markdownRules}>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Add option to click on message Reviewers: ashoat Reviewed By: ashoat Subscribers: zrebcu411, palys-swm, Adrian Differential Revision: https://phabricator.ashoat.com/D59
129,183
04.09.2020 15:15:15
-7,200
39bcdbf0e069e192c039e095d120ee23843ca43e
Move createReply function Reviewers: ashoat, palys-swm Subscribers: zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "lib/shared/message-utils.js", "new_path": "lib/shared/message-utils.js", "diff": "@@ -881,6 +881,12 @@ function trimMessage(message: string) {\nreturn codeBlockRegex.exec(message) ? message.trimEnd() : message.trim();\n}\n+function createMessageReply(message: string) {\n+ // add `>` to each line to include empty lines in the quote\n+ const quotedMessage = message.replace(/^/gm, '> ');\n+ return quotedMessage + '\\n\\n';\n+}\n+\nexport {\nmessageKey,\nmessageID,\n@@ -901,4 +907,5 @@ export {\ncreateMediaMessageInfo,\nstripLocalIDs,\ntrimMessage,\n+ createMessageReply,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/chat/text-message-tooltip-modal.react.js", "new_path": "native/chat/text-message-tooltip-modal.react.js", "diff": "@@ -11,6 +11,8 @@ import { type InputState } from '../input/input-state';\nimport Clipboard from '@react-native-community/clipboard';\nimport invariant from 'invariant';\n+import { createMessageReply } from 'lib/shared/message-utils';\n+\nimport {\ncreateTooltip,\ntooltipHeight,\n@@ -32,12 +34,6 @@ function onPressCopy(props: CustomProps) {\nsetTimeout(confirmCopy);\n}\n-const createReply = (message: string) => {\n- // add `>` to each line to include empty lines in the quote\n- const quotedMessage = message.replace(/^/gm, '> ');\n- return quotedMessage + '\\n\\n';\n-};\n-\nfunction onPressReply(\nprops: CustomProps,\ndispatchFunctions: DispatchFunctions,\n@@ -48,7 +44,7 @@ function onPressReply(\ninputState,\n'inputState should be set in TextMessageTooltipModal.onPressReply',\n);\n- inputState.addReply(createReply(props.item.messageInfo.text));\n+ inputState.addReply(createMessageReply(props.item.messageInfo.text));\n}\nconst spec = {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Move createReply function Reviewers: ashoat, palys-swm Reviewed By: ashoat, palys-swm Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D62
129,183
04.09.2020 15:17:57
-7,200
705107688af075086ac343ac42518d101b6f080d
[web] Add reply to message on web Reviewers: ashoat, palys-swm Subscribers: zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-input-bar.react.js", "new_path": "web/chat/chat-input-bar.react.js", "diff": "@@ -50,6 +50,7 @@ type Props = {|\njoinThreadLoadingStatus: LoadingStatus,\ncalendarQuery: () => CalendarQuery,\nnextLocalID: number,\n+ isThreadActive: boolean,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\ndispatchActionPayload: DispatchActionPayload,\n@@ -64,6 +65,7 @@ class ChatInputBar extends React.PureComponent<Props> {\njoinThreadLoadingStatus: loadingStatusPropType.isRequired,\ncalendarQuery: PropTypes.func.isRequired,\nnextLocalID: PropTypes.number.isRequired,\n+ isThreadActive: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n@@ -73,9 +75,24 @@ class ChatInputBar extends React.PureComponent<Props> {\ncomponentDidMount() {\nthis.updateHeight();\n+ if (this.props.isThreadActive) {\n+ this.addReplyListener();\n+ }\n+ }\n+\n+ componentWillUnmount() {\n+ if (this.props.isThreadActive) {\n+ this.removeReplyListener();\n+ }\n}\ncomponentDidUpdate(prevProps: Props) {\n+ if (this.props.isThreadActive && !prevProps.isThreadActive) {\n+ this.addReplyListener();\n+ } else if (!this.props.isThreadActive && prevProps.isThreadActive) {\n+ this.removeReplyListener();\n+ }\n+\nconst { inputState } = this.props;\nconst prevInputState = prevProps.inputState;\nif (inputState.draft !== prevInputState.draft) {\n@@ -128,6 +145,22 @@ class ChatInputBar extends React.PureComponent<Props> {\n}\n}\n+ addReplyListener() {\n+ invariant(\n+ this.props.inputState,\n+ 'inputState should be set in addReplyListener',\n+ );\n+ this.props.inputState.addReplyListener(this.focusAndUpdateText);\n+ }\n+\n+ removeReplyListener() {\n+ invariant(\n+ this.props.inputState,\n+ 'inputState should be set in removeReplyListener',\n+ );\n+ this.props.inputState.removeReplyListener(this.focusAndUpdateText);\n+ }\n+\nrender() {\nconst isMember = viewerIsMember(this.props.threadInfo);\nlet joinButton = null;\n@@ -252,6 +285,15 @@ class ChatInputBar extends React.PureComponent<Props> {\nthis.props.inputState.setDraft(event.currentTarget.value);\n};\n+ focusAndUpdateText = (text: string) => {\n+ invariant(this.textarea, 'textarea should be set');\n+ this.textarea.focus();\n+ invariant(this.textarea, 'textarea should be set');\n+ this.textarea.value = text;\n+ this.updateHeight();\n+ this.props.inputState.setDraft(text);\n+ };\n+\nonKeyDown = (event: SyntheticKeyboardEvent<HTMLTextAreaElement>) => {\nif (event.keyCode === 13 && !event.shiftKey) {\nevent.preventDefault();\n@@ -341,11 +383,12 @@ const joinThreadLoadingStatusSelector = createLoadingStatusSelector(\n);\nexport default connect(\n- (state: AppState) => ({\n+ (state: AppState, ownProps: { threadInfo: ThreadInfo, ... }) => ({\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\njoinThreadLoadingStatus: joinThreadLoadingStatusSelector(state),\ncalendarQuery: nonThreadCalendarQuery(state),\nnextLocalID: state.nextLocalID,\n+ isThreadActive: ownProps.threadInfo.id === state.navInfo.activeChatThreadID,\n}),\n{ joinThread },\n)(ChatInputBar);\n" }, { "change_type": "MODIFY", "old_path": "web/chat/composed-message.react.js", "new_path": "web/chat/composed-message.react.js", "diff": "@@ -26,6 +26,11 @@ import { stringForUser } from 'lib/shared/user-utils';\nimport FailedSend from './failed-send.react';\nimport css from './chat-message-list.css';\nimport MessageReplyTooltip from './message-reply-tooltip.react';\n+import {\n+ inputStatePropType,\n+ type InputState,\n+ withInputState,\n+} from '../input/input-state';\ntype Props = {|\nitem: ChatMessageInfoItem,\n@@ -39,6 +44,8 @@ type Props = {|\nchildren: React.Node,\nfixedWidth?: boolean,\nborderRadius: number,\n+ // withInputState\n+ inputState: InputState,\n|};\nclass ComposedMessage extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -51,6 +58,7 @@ class ComposedMessage extends React.PureComponent<Props> {\nchildren: PropTypes.node.isRequired,\nfixedWidth: PropTypes.bool,\nborderRadius: PropTypes.number.isRequired,\n+ inputState: inputStatePropType.isRequired,\n};\nstatic defaultProps = {\nborderRadius: 8,\n@@ -126,6 +134,7 @@ class ComposedMessage extends React.PureComponent<Props> {\n<MessageReplyTooltip\nmessagePositionInfo={this.props.mouseOverMessagePosition}\nonReplyClick={this.onMouseLeave}\n+ inputState={this.props.inputState}\n/>\n);\nif (isViewer) {\n@@ -175,4 +184,4 @@ class ComposedMessage extends React.PureComponent<Props> {\n};\n}\n-export default ComposedMessage;\n+export default withInputState(ComposedMessage);\n" }, { "change_type": "MODIFY", "old_path": "web/chat/message-reply-tooltip.react.js", "new_path": "web/chat/message-reply-tooltip.react.js", "diff": "@@ -5,17 +5,31 @@ import type { OnMessagePositionInfo } from './message-position-types';\nimport * as React from 'react';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faReply } from '@fortawesome/free-solid-svg-icons';\n+import { createMessageReply } from 'lib/shared/message-utils';\n+import invariant from 'invariant';\nimport css from './chat-message-list.css';\n+import type { InputState } from '../input/input-state';\ntype Props = {|\n+messagePositionInfo: OnMessagePositionInfo,\n+onReplyClick: () => void,\n+ +inputState: InputState,\n|};\nfunction MessageReplyTooltip(props: Props) {\n+ const { inputState, onReplyClick, messagePositionInfo } = props;\n+ const { addReply } = inputState;\n+\n+ const replyClicked = React.useCallback(() => {\n+ const { item } = messagePositionInfo;\n+ invariant(item.messageInfo.text, 'text should be set in message clicked');\n+ addReply(createMessageReply(item.messageInfo.text));\n+ onReplyClick();\n+ }, [addReply, messagePositionInfo, onReplyClick]);\n+\nreturn (\n<div className={css.messageReplyTooltip}>\n- <div className={css.messageReplyTooltipIcon} onClick={props.onReplyClick}>\n+ <div className={css.messageReplyTooltipIcon} onClick={replyClicked}>\n<FontAwesomeIcon icon={faReply} />\n</div>\n</div>\n" }, { "change_type": "MODIFY", "old_path": "web/input/input-state-container.react.js", "new_path": "web/input/input-state-container.react.js", "diff": "@@ -116,6 +116,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\npendingUploads: {},\ndrafts: {},\n};\n+ replyCallbacks: Array<(message: string) => void> = [];\nstatic completedMessageIDs(state: State) {\nconst completed = new Map();\n@@ -374,6 +375,9 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nlocalMessageID,\nassignedUploads[localMessageID],\n),\n+ addReply: (message: string) => this.addReply(message),\n+ addReplyListener: this.addReplyListener,\n+ removeReplyListener: this.removeReplyListener,\n};\n},\n),\n@@ -992,6 +996,20 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nthis.uploadFiles(threadID, uploadsToRetry);\n}\n+ addReply = (message: string) => {\n+ this.replyCallbacks.forEach(addReplyCallback => addReplyCallback(message));\n+ };\n+\n+ addReplyListener = (callbackReply: (message: string) => void) => {\n+ this.replyCallbacks.push(callbackReply);\n+ };\n+\n+ removeReplyListener = (callbackReply: (message: string) => void) => {\n+ this.replyCallbacks = this.replyCallbacks.filter(\n+ candidate => candidate !== callbackReply,\n+ );\n+ };\n+\nrender() {\nconst { activeChatThreadID } = this.props;\nconst inputState = activeChatThreadID\n" }, { "change_type": "MODIFY", "old_path": "web/input/input-state.js", "new_path": "web/input/input-state.js", "diff": "@@ -67,6 +67,9 @@ export type InputState = {|\nsetDraft: (draft: string) => void,\nmessageHasUploadFailure: (localMessageID: string) => boolean,\nretryMultimediaMessage: (localMessageID: string) => void,\n+ addReply: (text: string) => void,\n+ addReplyListener: ((message: string) => void) => void,\n+ removeReplyListener: ((message: string) => void) => void,\n|};\nconst arrayOfUploadsPropType = PropTypes.arrayOf(\npendingMultimediaUploadPropType,\n@@ -82,6 +85,9 @@ const inputStatePropType = PropTypes.shape({\nsetDraft: PropTypes.func.isRequired,\nmessageHasUploadFailure: PropTypes.func.isRequired,\nretryMultimediaMessage: PropTypes.func.isRequired,\n+ addReply: PropTypes.func.isRequired,\n+ addReplyListener: PropTypes.func.isRequired,\n+ removeReplyListener: PropTypes.func.isRequired,\n});\nconst InputStateContext = React.createContext<?InputState>(null);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Add reply to message on web Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D63
129,187
12.09.2020 17:57:27
14,400
703fabbd37e6e95edb163376906841433008cb00
[native] Prevent multiple subsequent logouts Summary: This diff prevents the user from hitting the log out button multiple times in a row. Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/more/more-screen.react.js", "new_path": "native/more/more-screen.react.js", "diff": "import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { AppState } from '../redux/redux-setup';\nimport type { LogOutResult } from 'lib/types/account-types';\n-import type { LoadingStatus } from 'lib/types/loading-types';\n-import { loadingStatusPropType } from 'lib/types/loading-types';\nimport {\ntype CurrentUserInfo,\ncurrentUserPropType,\n@@ -28,7 +26,6 @@ import invariant from 'invariant';\nimport PropTypes from 'prop-types';\nimport Icon from 'react-native-vector-icons/Ionicons';\n-import { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nlogOutActionTypes,\n@@ -68,7 +65,8 @@ type Props = {\n// Redux state\ncurrentUserInfo: ?CurrentUserInfo,\npreRequestUserState: PreRequestUserState,\n- resendVerificationLoadingStatus: LoadingStatus,\n+ resendVerificationLoading: boolean,\n+ logOutLoading: boolean,\ncolors: Colors,\nstyles: typeof styles,\n// Redux dispatch functions\n@@ -84,7 +82,8 @@ class MoreScreen extends React.PureComponent<Props> {\n}).isRequired,\ncurrentUserInfo: currentUserPropType,\npreRequestUserState: preRequestUserStatePropType.isRequired,\n- resendVerificationLoadingStatus: loadingStatusPropType.isRequired,\n+ resendVerificationLoading: PropTypes.bool.isRequired,\n+ logOutLoading: PropTypes.bool.isRequired,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -110,6 +109,14 @@ class MoreScreen extends React.PureComponent<Props> {\n: undefined;\n}\n+ get loggedOutOrLoggingOut() {\n+ return (\n+ !this.props.currentUserInfo ||\n+ this.props.currentUserInfo.anonymous ||\n+ this.props.logOutLoading\n+ );\n+ }\n+\nrender() {\nconst { emailVerified } = this;\nlet emailVerifiedNode = null;\n@@ -127,7 +134,7 @@ class MoreScreen extends React.PureComponent<Props> {\n);\n} else if (emailVerified === false) {\nlet resendVerificationEmailSpinner;\n- if (this.props.resendVerificationLoadingStatus === 'loading') {\n+ if (this.props.resendVerificationLoading) {\nresendVerificationEmailSpinner = (\n<ActivityIndicator\nsize=\"small\"\n@@ -182,7 +189,10 @@ class MoreScreen extends React.PureComponent<Props> {\n{firstLine(this.username)}\n</Text>\n</Text>\n- <Button onPress={this.onPressLogOut}>\n+ <Button\n+ onPress={this.onPressLogOut}\n+ disabled={this.loggedOutOrLoggingOut}\n+ >\n<Text style={this.props.styles.logOutText}>Log out</Text>\n</Button>\n</View>\n@@ -288,6 +298,9 @@ class MoreScreen extends React.PureComponent<Props> {\n}\nonPressLogOut = () => {\n+ if (this.loggedOutOrLoggingOut) {\n+ return;\n+ }\nconst alertTitle =\nPlatform.OS === 'ios' ? 'Keep Login Info in Keychain' : 'Keep Login Info';\nconst sharedWebCredentials = getNativeSharedWebCredentials();\n@@ -308,10 +321,16 @@ class MoreScreen extends React.PureComponent<Props> {\n};\nlogOutButKeepNativeCredentialsWrapper = () => {\n+ if (this.loggedOutOrLoggingOut) {\n+ return;\n+ }\nthis.props.dispatchActionPromise(logOutActionTypes, this.logOut());\n};\nlogOutAndDeleteNativeCredentialsWrapper = () => {\n+ if (this.loggedOutOrLoggingOut) {\n+ return;\n+ }\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\nthis.logOutAndDeleteNativeCredentials(),\n@@ -505,7 +524,9 @@ const styles = {\n};\nconst stylesSelector = styleSelector(styles);\n-registerFetchKey(logOutActionTypes);\n+const logOutLoadingStatusSelector = createLoadingStatusSelector(\n+ logOutActionTypes,\n+);\nconst resendVerificationLoadingStatusSelector = createLoadingStatusSelector(\nresendVerificationEmailActionTypes,\n);\n@@ -514,9 +535,9 @@ export default connect(\n(state: AppState) => ({\ncurrentUserInfo: state.currentUserInfo,\npreRequestUserState: preRequestUserStateSelector(state),\n- resendVerificationLoadingStatus: resendVerificationLoadingStatusSelector(\n- state,\n- ),\n+ resendVerificationLoading:\n+ resendVerificationLoadingStatusSelector(state) === 'loading',\n+ logOutLoading: logOutLoadingStatusSelector(state) === 'loading',\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n}),\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Prevent multiple subsequent logouts Summary: This diff prevents the user from hitting the log out button multiple times in a row. Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D86
129,187
12.09.2020 20:58:02
14,400
81080f696dec8a508bc241b176e0ee743370a95d
[native][Android] Lock orientation to portrait when app boots Summary: This is the Android equivalent of D83. Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/android/app/src/main/AndroidManifest.xml", "new_path": "native/android/app/src/main/AndroidManifest.xml", "diff": "android:configChanges=\"keyboard|keyboardHidden|orientation|screenSize|uiMode\"\nandroid:windowSoftInputMode=\"adjustResize\"\nandroid:exported=\"true\"\n+ android:screenOrientation=\"portrait\"\n>\n<intent-filter android:autoVerify=\"true\">\n<action android:name=\"android.intent.action.VIEW\" />\nandroid:theme=\"@style/SplashTheme\"\nandroid:label=\"@string/app_name\"\nandroid:noHistory=\"true\"\n+ android:screenOrientation=\"portrait\"\n>\n<intent-filter>\n<action android:name=\"android.intent.action.MAIN\" />\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native][Android] Lock orientation to portrait when app boots Summary: This is the Android equivalent of D83. Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D90
129,187
12.09.2020 22:00:16
14,400
411d975a3275a6e83d14f399eb1fde45d7330c13
[native] Set autoCompleteType for integration with Android password managers Summary: See [documentation](https://reactnative.dev/docs/textinput#autocompletetype) Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -108,6 +108,7 @@ class LogInPanel extends React.PureComponent<Props> {\nautoCapitalize=\"none\"\nkeyboardType=\"ascii-capable\"\ntextContentType=\"username\"\n+ autoCompleteType=\"username\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusPasswordInput}\n@@ -124,6 +125,7 @@ class LogInPanel extends React.PureComponent<Props> {\nplaceholder=\"Password\"\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"go\"\nblurOnSubmit={false}\nonSubmitEditing={this.onSubmit}\n" }, { "change_type": "MODIFY", "old_path": "native/account/register-panel.react.js", "new_path": "native/account/register-panel.react.js", "diff": "@@ -83,6 +83,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nautoCapitalize=\"none\"\nkeyboardType=\"ascii-capable\"\ntextContentType=\"username\"\n+ autoCompleteType=\"username\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusEmailInput}\n@@ -105,6 +106,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nautoCorrect={false}\nautoCapitalize=\"none\"\nkeyboardType=\"email-address\"\n+ autoCompleteType=\"email\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusPasswordInput}\n@@ -121,6 +123,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nplaceholder=\"Password\"\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusConfirmPasswordInput}\n@@ -136,6 +139,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nplaceholder=\"Confirm password\"\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"go\"\nblurOnSubmit={false}\nonSubmitEditing={this.onSubmit}\n" }, { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "@@ -95,6 +95,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nautoFocus={true}\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"next\"\nblurOnSubmit={false}\nonSubmitEditing={this.focusConfirmPasswordInput}\n@@ -110,6 +111,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nplaceholder=\"Confirm password\"\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"go\"\nblurOnSubmit={false}\nonSubmitEditing={this.onSubmit}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/delete-thread.react.js", "new_path": "native/chat/settings/delete-thread.react.js", "diff": "@@ -161,6 +161,7 @@ class DeleteThread extends React.PureComponent<Props, State> {\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitDeletion}\nref={this.passwordInputRef}\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -123,6 +123,7 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitDeletion}\nref={this.passwordInputRef}\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-email.react.js", "new_path": "native/more/edit-email.react.js", "diff": "@@ -115,6 +115,9 @@ class EditEmail extends React.PureComponent<Props, State> {\nautoFocus={true}\nselectTextOnFocus={true}\nreturnKeyType=\"next\"\n+ autoCapitalize=\"none\"\n+ keyboardType=\"email-address\"\n+ autoCompleteType=\"email\"\nonSubmitEditing={this.focusPasswordInput}\nref={this.emailInputRef}\n/>\n@@ -130,6 +133,7 @@ class EditEmail extends React.PureComponent<Props, State> {\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitEmail}\nref={this.passwordInputRef}\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-password.react.js", "new_path": "native/more/edit-password.react.js", "diff": "@@ -112,6 +112,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nplaceholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\ntextContentType=\"password\"\n+ autoCompleteType=\"password\"\nautoFocus={true}\nreturnKeyType=\"next\"\nonSubmitEditing={this.focusNewPassword}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Set autoCompleteType for integration with Android password managers Summary: See [documentation](https://reactnative.dev/docs/textinput#autocompletetype) Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D91
129,187
12.09.2020 22:28:36
14,400
0cf98a0a6e47d174f05d162ecec85e828e727117
[native] Fix ratchetAlongWithKeyboardHeight on Android Summary: I noticed an animation bug where if `keyboardShow` triggered after `keyboardTimeoutClock`, `ratchetAlongWithKeyboardHeight` failed to correct the `panelPaddingTop` value. After some testing realized it was just a silly typo... Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/utils/animation-utils.js", "new_path": "native/utils/animation-utils.js", "diff": "@@ -114,7 +114,10 @@ function ratchetAlongWithKeyboardHeight(\nios: greaterThan(keyboardHeight, max(prevKeyboardHeightValue, 0)),\n// Android's keyboard can resize due to user interaction sometimes. In these\n// cases it can get quite big, in which case we don't want to update\n- defaut: and(eq(prevKeyboardHeightValue, 0), greaterThan(keyboardHeight, 0)),\n+ default: and(\n+ eq(prevKeyboardHeightValue, 0),\n+ greaterThan(keyboardHeight, 0),\n+ ),\n});\nconst whenToReset = and(\neq(keyboardHeight, 0),\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix ratchetAlongWithKeyboardHeight on Android Summary: I noticed an animation bug where if `keyboardShow` triggered after `keyboardTimeoutClock`, `ratchetAlongWithKeyboardHeight` failed to correct the `panelPaddingTop` value. After some testing realized it was just a silly typo... Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D92
129,187
13.09.2020 00:35:05
14,400
9c26e2cce54c919577e45d64eb4d1ccb882b1dac
[native] Focus password field after autofilling username field Summary: For some reason, iOS doesn't fill the password field here at the same time as the username. This diff reduces once click for the user Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -165,6 +165,12 @@ class LogInPanel extends React.PureComponent<Props> {\nonChangeUsernameOrEmailInputText = (text: string) => {\nthis.props.state.setState({ usernameOrEmailInputText: text });\n+ if (\n+ this.props.state.state.passwordInputText.length === 0 &&\n+ text.length > 1\n+ ) {\n+ this.focusPasswordInput();\n+ }\n};\nonChangePasswordInputText = (text: string) => {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Focus password field after autofilling username field Summary: For some reason, iOS doesn't fill the password field here at the same time as the username. This diff reduces once click for the user Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D93
129,187
14.09.2020 12:04:48
14,400
c6f52c0e1feca496ec1d6b58aaeea0cc3f4df355
[web] Maintain scroll position when scrolled up on ChatMessageList Summary: Chrome and Firefox do this automatically, but Safari does not Reviewers: palys-swm, KatPo Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.react.js", "new_path": "web/chat/chat-message-list.react.js", "diff": "@@ -80,7 +80,8 @@ type State = {|\n+mouseOverMessagePosition: ?OnMessagePositionInfo,\n|};\ntype Snapshot = {|\n- +scrolledToBottom: boolean,\n+ +scrollTop: number,\n+ +scrollHeight: number,\n|};\nclass ChatMessageList extends React.PureComponent<Props, State> {\nstatic propTypes = {\n@@ -129,9 +130,8 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nChatMessageList.hasNewMessage(this.props, prevProps) &&\nthis.messageContainer\n) {\n- const { scrollTop } = this.messageContainer;\n- const scrolledToBottom = Math.abs(scrollTop) <= 1;\n- return { scrolledToBottom };\n+ const { scrollTop, scrollHeight } = this.messageContainer;\n+ return { scrollTop, scrollHeight };\n}\nreturn null;\n}\n@@ -179,9 +179,23 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nmessageListData &&\nmessageListData[0].itemType === 'message' &&\nmessageListData[0].messageInfo.localID) ||\n- (hasNewMessage && snapshot && snapshot.scrolledToBottom)\n+ (hasNewMessage && snapshot && Math.abs(snapshot.scrollTop) <= 1)\n) {\nthis.scrollToBottom();\n+ } else if (hasNewMessage && messageContainer && snapshot) {\n+ const { scrollTop, scrollHeight } = messageContainer;\n+ if (\n+ scrollHeight > snapshot.scrollHeight &&\n+ scrollTop === snapshot.scrollTop\n+ ) {\n+ const newHeight = scrollHeight - snapshot.scrollHeight;\n+ const newScrollTop = Math.abs(scrollTop) + newHeight;\n+ if (this.props.firefox) {\n+ messageContainer.scrollTop = newScrollTop;\n+ } else {\n+ messageContainer.scrollTop = -1 * newScrollTop;\n+ }\n+ }\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Maintain scroll position when scrolled up on ChatMessageList Summary: Chrome and Firefox do this automatically, but Safari does not Reviewers: palys-swm, KatPo Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D96
129,187
14.09.2020 15:37:21
14,400
d6978f40468135dc2fad46cc3d58a14d9f533528
[server] Set SameSite option on cookie Summary: Context on this new option [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite). Firefox was complaining when I was testing my local instance that non-https cookies will soon not work unless they have `SameSite` set. Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -740,6 +740,7 @@ const cookieOptions = {\nhttpOnly: true,\nsecure: https,\nmaxAge: cookieLifetime,\n+ sameSite: 'Strict',\n};\nfunction addActualHTTPCookie(viewer: Viewer, res: $Response) {\nres.cookie(viewer.cookieName, viewer.cookieString, cookieOptions);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Set SameSite option on cookie Summary: Context on this new option [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite). Firefox was complaining when I was testing my local instance that non-https cookies will soon not work unless they have `SameSite` set. Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D102
129,187
14.09.2020 19:05:56
14,400
32b3f5b812fd30448ad7bf3fd48400c7d7342d1b
[native] Focus password field after autofilling username field (actually) Summary: I screwed up in D93. This now matches [the logic](https://github.com/Ashoat/squadcal/blob/master/native/account/register-panel.react.js#L245-L257) in `RegisterPanel`. Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -102,6 +102,7 @@ class LogInPanel extends React.PureComponent<Props> {\nstyle={styles.input}\nvalue={this.props.state.state.usernameOrEmailInputText}\nonChangeText={this.onChangeUsernameOrEmailInputText}\n+ onKeyPress={this.onUsernameOrEmailKeyPress}\nplaceholder={this.props.usernamePlaceholder}\nautoFocus={Platform.OS !== 'ios'}\nautoCorrect={false}\n@@ -165,9 +166,17 @@ class LogInPanel extends React.PureComponent<Props> {\nonChangeUsernameOrEmailInputText = (text: string) => {\nthis.props.state.setState({ usernameOrEmailInputText: text });\n+ };\n+\n+ onUsernameOrEmailKeyPress = (\n+ event: $ReadOnly<{ nativeEvent: $ReadOnly<{ key: string }> }>,\n+ ) => {\n+ const { key } = event.nativeEvent;\nif (\n- this.props.state.state.passwordInputText.length === 0 &&\n- text.length > 1\n+ key.length > 1 &&\n+ key !== 'Backspace' &&\n+ key !== 'Enter' &&\n+ this.props.state.state.passwordInputText.length === 0\n) {\nthis.focusPasswordInput();\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Focus password field after autofilling username field (actually) Summary: I screwed up in D93. This now matches [the logic](https://github.com/Ashoat/squadcal/blob/master/native/account/register-panel.react.js#L245-L257) in `RegisterPanel`. Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D103
129,187
14.09.2020 22:43:43
14,400
95bfb4341c284b08b60204d52ee4ca7f0730240b
[native] Extract ChatThreadListSidebar component Summary: Extracts `ChatThreadListSidebar` component from `ChatThreadListItem` Introduces `useColors` hook Makes button press on sidebar lead to that sidebar instead of to its parent thread Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list-item.react.js", "new_path": "native/chat/chat-thread-list-item.react.js", "diff": "@@ -10,7 +10,6 @@ import type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\nimport { View, Text } from 'react-native';\nimport PropTypes from 'prop-types';\n-import Icon from 'react-native-vector-icons/Entypo';\nimport { shortAbsoluteDate } from 'lib/utils/date-utils';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -25,6 +24,7 @@ import {\nstyleSelector,\n} from '../themes/colors';\nimport { SingleLine } from '../components/single-line.react';\n+import ChatThreadListSidebar from './chat-thread-list-sidebar.react';\ntype Props = {\ndata: ChatThreadItem,\n@@ -61,37 +61,13 @@ class ChatThreadListItem extends React.PureComponent<Props> {\nrender() {\nconst { listIosHighlightUnderlay } = this.props.colors;\n- const sidebars = this.props.data.sidebars.map(sidebar => {\n- const sidebarThreadInfo = sidebar.threadInfo;\n- const lastActivity = shortAbsoluteDate(sidebar.lastUpdatedTime);\n- const sidebarUnreadStyle = sidebarThreadInfo.currentUser.unread\n- ? this.props.styles.unread\n- : null;\n- return (\n- <Button\n- iosFormat=\"highlight\"\n- iosHighlightUnderlayColor={listIosHighlightUnderlay}\n- iosActiveOpacity={0.85}\n- style={this.props.styles.sidebar}\n- key={sidebarThreadInfo.id}\n- onPress={this.onPress}\n- >\n- <Icon\n- name=\"align-right\"\n- style={this.props.styles.sidebarIcon}\n- size={24}\n+ const sidebars = this.props.data.sidebars.map(sidebar => (\n+ <ChatThreadListSidebar\n+ {...sidebar}\n+ onPressItem={this.props.onPressItem}\n+ key={sidebar.threadInfo.id}\n/>\n- <SingleLine\n- style={[this.props.styles.sidebarName, sidebarUnreadStyle]}\n- >\n- {sidebarThreadInfo.uiName}\n- </SingleLine>\n- <Text style={[this.props.styles.sidebarLastActivity, unreadStyle]}>\n- {lastActivity}\n- </Text>\n- </Button>\n- );\n- });\n+ ));\nconst lastActivity = shortAbsoluteDate(this.props.data.lastUpdatedTime);\nconst unreadStyle = this.props.data.threadInfo.currentUser.unread\n@@ -173,29 +149,6 @@ const styles = {\ncolor: 'listForegroundLabel',\nfontWeight: 'bold',\n},\n- sidebar: {\n- height: 30,\n- flexDirection: 'row',\n- display: 'flex',\n- marginHorizontal: 20,\n- alignItems: 'center',\n- },\n- sidebarIcon: {\n- paddingLeft: 10,\n- color: 'listForegroundSecondaryLabel',\n- },\n- sidebarName: {\n- color: 'listForegroundSecondaryLabel',\n- flex: 1,\n- fontSize: 16,\n- paddingLeft: 5,\n- paddingBottom: 2,\n- },\n- sidebarLastActivity: {\n- color: 'listForegroundTertiaryLabel',\n- fontSize: 14,\n- marginLeft: 10,\n- },\n};\nconst stylesSelector = styleSelector(styles);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/chat/chat-thread-list-sidebar.react.js", "diff": "+// @flow\n+\n+import type { ThreadInfo } from 'lib/types/thread-types';\n+\n+import * as React from 'react';\n+import Icon from 'react-native-vector-icons/Entypo';\n+import { Text } from 'react-native';\n+\n+import { shortAbsoluteDate } from 'lib/utils/date-utils';\n+\n+import { useColors, useStyles } from '../themes/colors';\n+import Button from '../components/button.react';\n+import { SingleLine } from '../components/single-line.react';\n+\n+type Props = {|\n+ +threadInfo: ThreadInfo,\n+ +lastUpdatedTime: number,\n+ +onPressItem: (threadInfo: ThreadInfo) => void,\n+|};\n+function ChatThreadListSidebar(props: Props) {\n+ const colors = useColors();\n+ const styles = useStyles(unboundStyles);\n+\n+ const { threadInfo, lastUpdatedTime, onPressItem } = props;\n+ const lastActivity = shortAbsoluteDate(lastUpdatedTime);\n+ const unreadStyle = threadInfo.currentUser.unread ? styles.unread : null;\n+\n+ const onPress = React.useCallback(() => onPressItem(threadInfo), [\n+ threadInfo,\n+ onPressItem,\n+ ]);\n+\n+ return (\n+ <Button\n+ iosFormat=\"highlight\"\n+ iosHighlightUnderlayColor={colors.listIosHighlightUnderlay}\n+ iosActiveOpacity={0.85}\n+ style={styles.sidebar}\n+ key={threadInfo.id}\n+ onPress={onPress}\n+ >\n+ <Icon name=\"align-right\" style={styles.icon} size={24} />\n+ <SingleLine style={[styles.name, unreadStyle]}>\n+ {threadInfo.uiName}\n+ </SingleLine>\n+ <Text style={[styles.lastActivity, unreadStyle]}>{lastActivity}</Text>\n+ </Button>\n+ );\n+}\n+\n+const unboundStyles = {\n+ unread: {\n+ color: 'listForegroundLabel',\n+ fontWeight: 'bold',\n+ },\n+ sidebar: {\n+ height: 30,\n+ flexDirection: 'row',\n+ display: 'flex',\n+ marginHorizontal: 20,\n+ alignItems: 'center',\n+ },\n+ icon: {\n+ paddingLeft: 10,\n+ color: 'listForegroundSecondaryLabel',\n+ },\n+ name: {\n+ color: 'listForegroundSecondaryLabel',\n+ flex: 1,\n+ fontSize: 16,\n+ paddingLeft: 5,\n+ paddingBottom: 2,\n+ },\n+ lastActivity: {\n+ color: 'listForegroundTertiaryLabel',\n+ fontSize: 14,\n+ marginLeft: 10,\n+ },\n+};\n+\n+export default ChatThreadListSidebar;\n" }, { "change_type": "MODIFY", "old_path": "native/themes/colors.js", "new_path": "native/themes/colors.js", "diff": "@@ -194,13 +194,10 @@ function styleSelector<IS: Styles>(\n}\nfunction useStyles<IS: Styles>(obj: IS): StyleSheetOf<IS> {\n- const theme = useSelector(\n- (state: AppState) => state.globalThemeInfo.activeTheme,\n- );\n- const explicitTheme = theme ? theme : 'light';\n- return React.useMemo(() => stylesFromColors(obj, colors[explicitTheme]), [\n+ const ourColors = useColors();\n+ return React.useMemo(() => stylesFromColors(obj, ourColors), [\nobj,\n- explicitTheme,\n+ ourColors,\n]);\n}\n@@ -224,6 +221,10 @@ function useOverlayStyles<IS: Styles>(obj: IS): StyleSheetOf<IS> {\n]);\n}\n+function useColors(): Colors {\n+ return useSelector(colorsSelector);\n+}\n+\nfunction getStylesForTheme<IS: Styles>(\nobj: IS,\ntheme: GlobalTheme,\n@@ -255,6 +256,7 @@ export {\nstyleSelector,\nuseStyles,\nuseOverlayStyles,\n+ useColors,\ngetStylesForTheme,\nindicatorStylePropType,\nuseIndicatorStyle,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Extract ChatThreadListSidebar component Summary: - Extracts `ChatThreadListSidebar` component from `ChatThreadListItem` - Introduces `useColors` hook - Makes button press on sidebar lead to that sidebar instead of to its parent thread Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D105
129,187
14.09.2020 23:08:21
14,400
2f7e08544554ac106e6c971d661633bd082c6265
[lib] Order sidebars in chatListDataWithNestedSidebars Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "lib/selectors/chat-selectors.js", "new_path": "lib/selectors/chat-selectors.js", "diff": "@@ -108,7 +108,7 @@ function createChatThreadItem(\n);\nconst lastUpdatedTime = getLastUpdatedTime(threadInfo, mostRecentMessageInfo);\n- const sidebars = [];\n+ const unorderedSidebars = [];\nlet lastUpdatedTimeIncludingSidebars = lastUpdatedTime;\nif (childThreads) {\nfor (const childThreadInfo of childThreads) {\n@@ -122,12 +122,13 @@ function createChatThreadItem(\nif (sidebarLastUpdatedTime > lastUpdatedTimeIncludingSidebars) {\nlastUpdatedTimeIncludingSidebars = sidebarLastUpdatedTime;\n}\n- sidebars.push({\n+ unorderedSidebars.push({\nthreadInfo: childThreadInfo,\nlastUpdatedTime: sidebarLastUpdatedTime,\n});\n}\n}\n+ const sidebars = _orderBy('lastUpdatedTime')('desc')(unorderedSidebars);\nreturn {\ntype: 'chatThreadItem',\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Order sidebars in chatListDataWithNestedSidebars Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D107
129,187
14.09.2020 23:22:12
14,400
1c10ac4f73b73ec8b5311f8be69e75f91e5abc07
[native] Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/ios/Podfile.lock", "new_path": "native/ios/Podfile.lock", "diff": "@@ -293,7 +293,7 @@ PODS:\n- React\n- react-native-orientation-locker (1.1.6):\n- React\n- - react-native-safe-area-context (3.1.1):\n+ - react-native-safe-area-context (3.1.7):\n- React\n- react-native-video/Video (5.0.2):\n- React\n@@ -726,7 +726,7 @@ SPEC CHECKSUMS:\nreact-native-netinfo: 6bb847e64f45a2d69c6173741111cfd95c669301\nreact-native-notifications: bb042206ac7eab9323d528c780b3d6fe796c1f5e\nreact-native-orientation-locker: 23918c400376a7043e752c639c122fcf6bce8f1c\n- react-native-safe-area-context: 344b969c45af3d8464d36e8dea264942992ef033\n+ react-native-safe-area-context: 955ecfce672683b495d9294d2f154a9ad1d9796b\nreact-native-video: d01ed7ff1e38fa7dcc6c15c94cf505e661b7bfd0\nReact-RCTActionSheet: f41ea8a811aac770e0cc6e0ad6b270c644ea8b7c\nReact-RCTAnimation: 49ab98b1c1ff4445148b72a3d61554138565bad0\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"babel-plugin-transform-remove-console\": \"^6.8.5\",\n\"babel-plugin-transform-remove-strict-mode\": \"0.0.2\",\n\"flow-bin\": \"^0.113.0\",\n- \"flow-typed\": \"^3.2.1\",\n\"flow-mono-cli\": \"^1.5.0\",\n+ \"flow-typed\": \"^3.2.1\",\n\"fs-extra\": \"^8.1.0\",\n\"jest\": \"^24.9.0\",\n\"jetifier\": \"^1.6.4\",\n\"react-native-orientation-locker\": \"^1.1.6\",\n\"react-native-progress\": \"^4.0.3\",\n\"react-native-reanimated\": \"^1.13.0\",\n- \"react-native-safe-area-context\": \"^3.1.1\",\n+ \"react-native-safe-area-context\": \"^3.1.7\",\n\"react-native-safe-area-view\": \"^2.0.0\",\n\"react-native-screens\": \"^2.9.0\",\n\"react-native-tab-view\": \"^2.14.4\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -12245,10 +12245,10 @@ react-native-reanimated@^1.13.0:\ndependencies:\nfbjs \"^1.0.0\"\n-react-native-safe-area-context@^3.1.1:\n- version \"3.1.1\"\n- resolved \"https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-3.1.1.tgz#9b04d1154766e6c1132030aca8f4b0336f561ccd\"\n- integrity sha512-Iqb41OT5+QxFn0tpTbbHgz8+3VU/F9OH2fTeeoU7oZCzojOXQbC6sp6mN7BlsAoTKhngWoJLMcSosL58uRaLWQ==\n+react-native-safe-area-context@^3.1.7:\n+ version \"3.1.7\"\n+ resolved \"https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-3.1.7.tgz#fc9e636dfb168f992a2172d363509ce0611a8403\"\n+ integrity sha512-qSyg/pVMwVPgAy8yCvw349Q+uEUhtRBV33eVXHHkfoou1vCChJxI7SmNR47/6M3BLdjWcyc4lcd018Kx+jhQCw==\nreact-native-safe-area-view@^2.0.0:\nversion \"2.0.0\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] react-native-safe-area-context@3.1.7 Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D108
129,191
28.08.2020 15:23:15
-7,200
b86f3060e5e6305c7d06975a84e8cc2cc861df77
[native] Make thread list item a swipeable component Summary: Wrap thread list item with Swipeable. There are two temporary actions added to allow testing the implementation. Reviewers: ashoat, KatPo Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/.flowconfig", "new_path": "native/.flowconfig", "diff": ".*/node_modules/redux-persist/lib/index.js\n.*/node_modules/react-native-fast-image/src/index.js.flow\n.*/node_modules/react-native-fs/FS.common.js\n+.*/node_modules/react-native-gesture-handler/Swipeable.js\n; Flow doesn't support platforms\n.*/Libraries/Utilities/LoadingView.js\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list-item.react.js", "new_path": "native/chat/chat-thread-list-item.react.js", "diff": "@@ -8,8 +8,9 @@ import type { ThreadInfo } from 'lib/types/thread-types';\nimport type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\n-import { View, Text } from 'react-native';\n+import { View, Text, Animated } from 'react-native';\nimport PropTypes from 'prop-types';\n+import Swipeable from 'react-native-gesture-handler/Swipeable';\nimport { shortAbsoluteDate } from 'lib/utils/date-utils';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -32,6 +33,7 @@ type Props = {\n// Redux state\ncolors: Colors,\nstyles: typeof styles,\n+ windowWidth: number,\n};\nclass ChatThreadListItem extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -39,6 +41,7 @@ class ChatThreadListItem extends React.PureComponent<Props> {\nonPressItem: PropTypes.func.isRequired,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n+ windowWidth: PropTypes.number.isRequired,\n};\nlastMessage() {\n@@ -58,6 +61,86 @@ class ChatThreadListItem extends React.PureComponent<Props> {\n);\n}\n+ renderRightActions = progress => {\n+ const trans = progress.interpolate({\n+ inputRange: [0, 1],\n+ outputRange: [180, 0],\n+ });\n+ const trans2 = progress.interpolate({\n+ inputRange: [0, 1],\n+ outputRange: [120, 0],\n+ });\n+ const trans3 = progress.interpolate({\n+ inputRange: [0, 1],\n+ outputRange: [60, 0],\n+ });\n+\n+ const commonActionStyle = [\n+ this.props.styles.action,\n+ {\n+ width: this.props.windowWidth + 60,\n+ marginRight: -this.props.windowWidth,\n+ paddingRight: this.props.windowWidth,\n+ },\n+ ];\n+\n+ return (\n+ <View style={this.props.styles.actionsContainer}>\n+ <Animated.View\n+ style={{\n+ transform: [{ translateX: trans }],\n+ }}\n+ >\n+ <Button\n+ onPress={() => {}}\n+ style={[\n+ ...commonActionStyle,\n+ {\n+ backgroundColor: this.props.colors.greenButton,\n+ },\n+ ]}\n+ >\n+ <Text>Action1</Text>\n+ </Button>\n+ </Animated.View>\n+ <Animated.View\n+ style={{\n+ transform: [{ translateX: trans2 }],\n+ }}\n+ >\n+ <Button\n+ onPress={() => {}}\n+ style={[\n+ ...commonActionStyle,\n+ {\n+ backgroundColor: this.props.colors.redButton,\n+ },\n+ ]}\n+ >\n+ <Text>Action2</Text>\n+ </Button>\n+ </Animated.View>\n+ <Animated.View\n+ style={{\n+ transform: [{ translateX: trans3 }],\n+ }}\n+ >\n+ <Button\n+ onPress={() => {}}\n+ style={[\n+ ...commonActionStyle,\n+ {\n+ backgroundColor: this.props.colors.mintButton,\n+ },\n+ ]}\n+ >\n+ <Text>Action3</Text>\n+ </Button>\n+ </Animated.View>\n+ </View>\n+ );\n+ };\n+\nrender() {\nconst { listIosHighlightUnderlay } = this.props.colors;\n@@ -75,6 +158,7 @@ class ChatThreadListItem extends React.PureComponent<Props> {\n: null;\nreturn (\n<>\n+ <Swipeable renderRightActions={this.renderRightActions}>\n<Button\nonPress={this.onPress}\niosFormat=\"highlight\"\n@@ -101,6 +185,7 @@ class ChatThreadListItem extends React.PureComponent<Props> {\n</View>\n</View>\n</Button>\n+ </Swipeable>\n{sidebars}\n</>\n);\n@@ -112,6 +197,15 @@ class ChatThreadListItem extends React.PureComponent<Props> {\n}\nconst styles = {\n+ action: {\n+ height: '100%',\n+ alignItems: 'center',\n+ justifyContent: 'center',\n+ },\n+ actionsContainer: {\n+ height: 60,\n+ flexDirection: 'row',\n+ },\ncolorSplotch: {\nmarginLeft: 10,\nmarginTop: 2,\n@@ -121,6 +215,7 @@ const styles = {\npaddingLeft: 10,\npaddingRight: 10,\npaddingTop: 5,\n+ backgroundColor: 'listBackground',\n},\nlastActivity: {\ncolor: 'listForegroundTertiaryLabel',\n@@ -155,4 +250,5 @@ const stylesSelector = styleSelector(styles);\nexport default connect((state: AppState) => ({\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n+ windowWidth: state.dimensions.width,\n}))(ChatThreadListItem);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Make thread list item a swipeable component Summary: Wrap thread list item with Swipeable. There are two temporary actions added to allow testing the implementation. Reviewers: ashoat, KatPo Reviewed By: ashoat Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D27
129,191
03.09.2020 14:41:52
-7,200
7f87599c1ab416c0583540a1cf092cb3fa22fd89
[native] Close swipeables on blur Summary: Change ChatThreadListItem to functional component, use navigation hook, set navigation blur listener and close swipeable using ref Reviewers: ashoat, KatPo Subscribers: Adrian, zrebcu411, KatPo
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list-item.react.js", "new_path": "native/chat/chat-thread-list-item.react.js", "diff": "@@ -8,9 +8,10 @@ import type { ThreadInfo } from 'lib/types/thread-types';\nimport type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\n-import { View, Text, Animated } from 'react-native';\n+import { Text, View } from 'react-native';\nimport PropTypes from 'prop-types';\n-import Swipeable from 'react-native-gesture-handler/Swipeable';\n+import Swipeable from '../components/swipeable';\n+import { useNavigation } from '@react-navigation/native';\nimport { shortAbsoluteDate } from 'lib/utils/date-utils';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -33,22 +34,24 @@ type Props = {\n// Redux state\ncolors: Colors,\nstyles: typeof styles,\n- windowWidth: number,\n-};\n-class ChatThreadListItem extends React.PureComponent<Props> {\n- static propTypes = {\n- data: chatThreadItemPropType.isRequired,\n- onPressItem: PropTypes.func.isRequired,\n- colors: colorsPropType.isRequired,\n- styles: PropTypes.objectOf(PropTypes.object).isRequired,\n- windowWidth: PropTypes.number.isRequired,\n};\n+function ChatThreadListItem({ data, onPressItem, colors, ...props }: Props) {\n+ const swipeable = React.useRef<?Swipeable>();\n+ const navigation = useNavigation();\n+\n+ React.useEffect(() => {\n+ return navigation.addListener('blur', () => {\n+ if (swipeable.current) {\n+ swipeable.current.close();\n+ }\n+ });\n+ }, [navigation, swipeable]);\n- lastMessage() {\n- const mostRecentMessageInfo = this.props.data.mostRecentMessageInfo;\n+ const lastMessage = React.useCallback(() => {\n+ const mostRecentMessageInfo = data.mostRecentMessageInfo;\nif (!mostRecentMessageInfo) {\nreturn (\n- <Text style={this.props.styles.noMessages} numberOfLines={1}>\n+ <Text style={props.styles.noMessages} numberOfLines={1}>\nNo messages\n</Text>\n);\n@@ -56,130 +59,65 @@ class ChatThreadListItem extends React.PureComponent<Props> {\nreturn (\n<MessagePreview\nmessageInfo={mostRecentMessageInfo}\n- threadInfo={this.props.data.threadInfo}\n+ threadInfo={data.threadInfo}\n/>\n);\n- }\n-\n- renderRightActions = progress => {\n- const trans = progress.interpolate({\n- inputRange: [0, 1],\n- outputRange: [180, 0],\n- });\n- const trans2 = progress.interpolate({\n- inputRange: [0, 1],\n- outputRange: [120, 0],\n- });\n- const trans3 = progress.interpolate({\n- inputRange: [0, 1],\n- outputRange: [60, 0],\n- });\n-\n- const commonActionStyle = [\n- this.props.styles.action,\n- {\n- width: this.props.windowWidth + 60,\n- marginRight: -this.props.windowWidth,\n- paddingRight: this.props.windowWidth,\n- },\n- ];\n-\n- return (\n- <View style={this.props.styles.actionsContainer}>\n- <Animated.View\n- style={{\n- transform: [{ translateX: trans }],\n- }}\n- >\n- <Button\n- onPress={() => {}}\n- style={[\n- ...commonActionStyle,\n- {\n- backgroundColor: this.props.colors.greenButton,\n- },\n- ]}\n- >\n- <Text>Action1</Text>\n- </Button>\n- </Animated.View>\n- <Animated.View\n- style={{\n- transform: [{ translateX: trans2 }],\n- }}\n- >\n- <Button\n- onPress={() => {}}\n- style={[\n- ...commonActionStyle,\n- {\n- backgroundColor: this.props.colors.redButton,\n- },\n- ]}\n- >\n- <Text>Action2</Text>\n- </Button>\n- </Animated.View>\n- <Animated.View\n- style={{\n- transform: [{ translateX: trans3 }],\n- }}\n- >\n- <Button\n- onPress={() => {}}\n- style={[\n- ...commonActionStyle,\n- {\n- backgroundColor: this.props.colors.mintButton,\n- },\n- ]}\n- >\n- <Text>Action3</Text>\n- </Button>\n- </Animated.View>\n- </View>\n- );\n- };\n+ }, [data.mostRecentMessageInfo, data.threadInfo, props.styles]);\n- render() {\n- const { listIosHighlightUnderlay } = this.props.colors;\n-\n- const sidebars = this.props.data.sidebars.map(sidebar => (\n+ const sidebars = data.sidebars.map(sidebar => (\n<ChatThreadListSidebar\n{...sidebar}\n- onPressItem={this.props.onPressItem}\n+ onPressItem={onPressItem}\nkey={sidebar.threadInfo.id}\n/>\n));\n- const lastActivity = shortAbsoluteDate(this.props.data.lastUpdatedTime);\n- const unreadStyle = this.props.data.threadInfo.currentUser.unread\n- ? this.props.styles.unread\n+ const onPress = React.useCallback(() => {\n+ onPressItem(data.threadInfo);\n+ }, [onPressItem, data.threadInfo]);\n+\n+ const lastActivity = shortAbsoluteDate(data.lastUpdatedTime);\n+ const unreadStyle = data.threadInfo.currentUser.unread\n+ ? props.styles.unread\n: null;\nreturn (\n<>\n- <Swipeable renderRightActions={this.renderRightActions}>\n+ <Swipeable\n+ buttonWidth={60}\n+ innerRef={swipeable}\n+ rightActions={[\n+ {\n+ key: 'action1',\n+ onPress: () => console.log('action1'),\n+ color: colors.greenButton,\n+ content: <Text>action1</Text>,\n+ },\n+ {\n+ key: 'action2',\n+ onPress: () => console.log('action2'),\n+ color: colors.redButton,\n+ content: <Text>action2</Text>,\n+ },\n+ ]}\n+ >\n<Button\n- onPress={this.onPress}\n+ onPress={onPress}\niosFormat=\"highlight\"\n- iosHighlightUnderlayColor={listIosHighlightUnderlay}\n+ iosHighlightUnderlayColor={colors.listIosHighlightUnderlay}\niosActiveOpacity={0.85}\n>\n- <View style={this.props.styles.container}>\n- <View style={this.props.styles.row}>\n- <SingleLine style={[this.props.styles.threadName, unreadStyle]}>\n- {this.props.data.threadInfo.uiName}\n+ <View style={props.styles.container}>\n+ <View style={props.styles.row}>\n+ <SingleLine style={[props.styles.threadName, unreadStyle]}>\n+ {data.threadInfo.uiName}\n</SingleLine>\n- <View style={this.props.styles.colorSplotch}>\n- <ColorSplotch\n- color={this.props.data.threadInfo.color}\n- size=\"small\"\n- />\n+ <View style={props.styles.colorSplotch}>\n+ <ColorSplotch color={data.threadInfo.color} size=\"small\" />\n</View>\n</View>\n- <View style={this.props.styles.row}>\n- {this.lastMessage()}\n- <Text style={[this.props.styles.lastActivity, unreadStyle]}>\n+ <View style={props.styles.row}>\n+ {lastMessage()}\n+ <Text style={[props.styles.lastActivity, unreadStyle]}>\n{lastActivity}\n</Text>\n</View>\n@@ -191,21 +129,7 @@ class ChatThreadListItem extends React.PureComponent<Props> {\n);\n}\n- onPress = () => {\n- this.props.onPressItem(this.props.data.threadInfo);\n- };\n-}\n-\nconst styles = {\n- action: {\n- height: '100%',\n- alignItems: 'center',\n- justifyContent: 'center',\n- },\n- actionsContainer: {\n- height: 60,\n- flexDirection: 'row',\n- },\ncolorSplotch: {\nmarginLeft: 10,\nmarginTop: 2,\n@@ -247,8 +171,14 @@ const styles = {\n};\nconst stylesSelector = styleSelector(styles);\n+ChatThreadListItem.propTypes = {\n+ data: chatThreadItemPropType.isRequired,\n+ onPressItem: PropTypes.func.isRequired,\n+ colors: colorsPropType.isRequired,\n+ styles: PropTypes.objectOf(PropTypes.object).isRequired,\n+};\n+\nexport default connect((state: AppState) => ({\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n- windowWidth: state.dimensions.width,\n}))(ChatThreadListItem);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/components/swipeable.js", "diff": "+// @flow\n+\n+import type { AppState } from '../redux/redux-setup';\n+\n+import * as React from 'react';\n+import { Animated, View } from 'react-native';\n+import PropTypes from 'prop-types';\n+import SwipeableComponent from 'react-native-gesture-handler/Swipeable';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+\n+import Button from './button.react';\n+import {\n+ type Colors,\n+ colorsPropType,\n+ colorsSelector,\n+ styleSelector,\n+} from '../themes/colors';\n+\n+type Props = {\n+ +buttonWidth: number,\n+ +rightActions: $ReadOnlyArray<{|\n+ +key: string,\n+ +onPress: () => mixed,\n+ +color: ?string,\n+ +content: React.Node,\n+ |}>,\n+ +innerRef: {|\n+ current: ?SwipeableComponent,\n+ |},\n+ +children?: React.Node,\n+ // Redux state\n+ +windowWidth: number,\n+ +colors: Colors,\n+ +styles: typeof styles,\n+ ...\n+};\n+\n+class Swipeable extends React.PureComponent<Props> {\n+ static propTypes = {\n+ buttonWidth: PropTypes.number.isRequired,\n+ rightActions: PropTypes.arrayOf(\n+ PropTypes.exact({\n+ key: PropTypes.string.isRequired,\n+ onPress: PropTypes.func,\n+ color: PropTypes.string,\n+ content: PropTypes.node.isRequired,\n+ }),\n+ ),\n+ innerRef: PropTypes.exact({\n+ current: PropTypes.instanceOf(SwipeableComponent),\n+ }),\n+ children: PropTypes.node,\n+ windowWidth: PropTypes.number.isRequired,\n+ colors: colorsPropType.isRequired,\n+ styles: PropTypes.objectOf(PropTypes.object).isRequired,\n+ };\n+\n+ static defaultProps = {\n+ rightActions: [],\n+ };\n+\n+ renderRightActions = progress => {\n+ const actions = this.props.rightActions.map(\n+ ({ key, content, color, onPress }, i) => {\n+ const translation = progress.interpolate({\n+ inputRange: [0, 1],\n+ outputRange: [\n+ (this.props.rightActions.length - i) * this.props.buttonWidth,\n+ 0,\n+ ],\n+ });\n+ return (\n+ <Animated.View\n+ key={key}\n+ style={{\n+ transform: [{ translateX: translation }],\n+ }}\n+ >\n+ <Button\n+ onPress={onPress}\n+ style={[\n+ this.props.styles.action,\n+ {\n+ width: this.props.windowWidth + this.props.buttonWidth,\n+ marginRight: -this.props.windowWidth,\n+ paddingRight: this.props.windowWidth,\n+ backgroundColor: color,\n+ },\n+ ]}\n+ >\n+ {content}\n+ </Button>\n+ </Animated.View>\n+ );\n+ },\n+ );\n+\n+ return <View style={this.props.styles.actionsContainer}>{actions}</View>;\n+ };\n+\n+ render() {\n+ return (\n+ <SwipeableComponent\n+ renderRightActions={this.renderRightActions}\n+ ref={this.props.innerRef}\n+ >\n+ {this.props.children}\n+ </SwipeableComponent>\n+ );\n+ }\n+}\n+\n+const styles = {\n+ action: {\n+ height: '100%',\n+ alignItems: 'center',\n+ justifyContent: 'center',\n+ },\n+ actionsContainer: {\n+ flexDirection: 'row',\n+ },\n+};\n+const stylesSelector = styleSelector(styles);\n+\n+export default connect((state: AppState) => ({\n+ windowWidth: state.dimensions.width,\n+ colors: colorsSelector(state),\n+ styles: stylesSelector(state),\n+}))(Swipeable);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Close swipeables on blur Summary: Change ChatThreadListItem to functional component, use navigation hook, set navigation blur listener and close swipeable using ref Reviewers: ashoat, KatPo Reviewed By: ashoat Subscribers: Adrian, zrebcu411, KatPo Differential Revision: https://phabricator.ashoat.com/D47
129,191
07.09.2020 14:27:18
-7,200
324ae98c8a4360dcabcf1f85f0e9666d510e937e
[native] Close currently opened swipeable when another is being opened Summary: When swipeable is opened, thread's id is saved in list state. Then, it's passed to all the items and if it doesn't match item's id, the swipeable will be closed. Reviewers: ashoat, KatPo Subscribers: zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list-item.react.js", "new_path": "native/chat/chat-thread-list-item.react.js", "diff": "@@ -31,11 +31,20 @@ import ChatThreadListSidebar from './chat-thread-list-sidebar.react';\ntype Props = {\ndata: ChatThreadItem,\nonPressItem: (threadInfo: ThreadInfo) => void,\n+ onSwipeableWillOpen: (threadInfo: ThreadInfo) => void,\n+ currentlyOpenedSwipeableId?: string,\n// Redux state\ncolors: Colors,\nstyles: typeof styles,\n};\n-function ChatThreadListItem({ data, onPressItem, colors, ...props }: Props) {\n+function ChatThreadListItem({\n+ data,\n+ onPressItem,\n+ onSwipeableWillOpen,\n+ currentlyOpenedSwipeableId,\n+ colors,\n+ ...props\n+}: Props) {\nconst swipeable = React.useRef<?Swipeable>();\nconst navigation = useNavigation();\n@@ -47,6 +56,15 @@ function ChatThreadListItem({ data, onPressItem, colors, ...props }: Props) {\n});\n}, [navigation, swipeable]);\n+ React.useEffect(() => {\n+ if (\n+ swipeable.current &&\n+ data.threadInfo.id !== currentlyOpenedSwipeableId\n+ ) {\n+ swipeable.current.close();\n+ }\n+ }, [currentlyOpenedSwipeableId, swipeable, data.threadInfo.id]);\n+\nconst lastMessage = React.useCallback(() => {\nconst mostRecentMessageInfo = data.mostRecentMessageInfo;\nif (!mostRecentMessageInfo) {\n@@ -76,6 +94,10 @@ function ChatThreadListItem({ data, onPressItem, colors, ...props }: Props) {\nonPressItem(data.threadInfo);\n}, [onPressItem, data.threadInfo]);\n+ const onSwipeableRightWillOpen = React.useCallback(() => {\n+ onSwipeableWillOpen(data.threadInfo);\n+ }, [onSwipeableWillOpen, data.threadInfo]);\n+\nconst lastActivity = shortAbsoluteDate(data.lastUpdatedTime);\nconst unreadStyle = data.threadInfo.currentUser.unread\n? props.styles.unread\n@@ -85,6 +107,7 @@ function ChatThreadListItem({ data, onPressItem, colors, ...props }: Props) {\n<Swipeable\nbuttonWidth={60}\ninnerRef={swipeable}\n+ onSwipeableRightWillOpen={onSwipeableRightWillOpen}\nrightActions={[\n{\nkey: 'action1',\n@@ -174,6 +197,8 @@ const stylesSelector = styleSelector(styles);\nChatThreadListItem.propTypes = {\ndata: chatThreadItemPropType.isRequired,\nonPressItem: PropTypes.func.isRequired,\n+ onSwipeableWillOpen: PropTypes.func.isRequired,\n+ currentlyOpenedSwipeableId: PropTypes.string,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list.react.js", "new_path": "native/chat/chat-thread-list.react.js", "diff": "@@ -72,6 +72,7 @@ type Props = {|\ntype State = {|\nsearchText: string,\nsearchResults: Set<string>,\n+ openedSwipeableId: string,\n|};\ntype PropsAndState = {| ...Props, ...State |};\nclass ChatThreadList extends React.PureComponent<Props, State> {\n@@ -92,6 +93,7 @@ class ChatThreadList extends React.PureComponent<Props, State> {\nstate = {\nsearchText: '',\nsearchResults: new Set(),\n+ openedSwipeableId: '',\n};\nsearchInput: ?React.ElementRef<typeof TextInput>;\nflatList: ?FlatList<Item>;\n@@ -149,7 +151,14 @@ class ChatThreadList extends React.PureComponent<Props, State> {\nconst EmptyItem = item.emptyItem;\nreturn <EmptyItem />;\n}\n- return <ChatThreadListItem data={item} onPressItem={this.onPressItem} />;\n+ return (\n+ <ChatThreadListItem\n+ data={item}\n+ onPressItem={this.onPressItem}\n+ onSwipeableWillOpen={this.onSwipeableWillOpen}\n+ currentlyOpenedSwipeableId={this.state.openedSwipeableId}\n+ />\n+ );\n};\nsearchInputRef = (searchInput: ?React.ElementRef<typeof TextInput>) => {\n@@ -254,7 +263,9 @@ class ChatThreadList extends React.PureComponent<Props, State> {\nrenderItem={this.renderItem}\nkeyExtractor={ChatThreadList.keyExtractor}\ngetItemLayout={ChatThreadList.getItemLayout}\n- extraData={this.props.viewerID}\n+ extraData={`${this.props.viewerID || ''} ${\n+ this.state.openedSwipeableId\n+ }`}\ninitialNumToRender={11}\nkeyboardShouldPersistTaps=\"handled\"\nonScroll={this.onScroll}\n@@ -292,6 +303,10 @@ class ChatThreadList extends React.PureComponent<Props, State> {\n});\n};\n+ onSwipeableWillOpen = (threadInfo: ThreadInfo) => {\n+ this.setState(state => ({ ...state, openedSwipeableId: threadInfo.id }));\n+ };\n+\ncomposeThread = () => {\nthis.props.navigation.navigate({\nname: ComposeThreadRouteName,\n" }, { "change_type": "MODIFY", "old_path": "native/components/swipeable.js", "new_path": "native/components/swipeable.js", "diff": "@@ -25,6 +25,7 @@ type Props = {\n+color: ?string,\n+content: React.Node,\n|}>,\n+ +onSwipeableRightWillOpen?: () => void,\n+innerRef: {|\ncurrent: ?SwipeableComponent,\n|},\n@@ -42,11 +43,12 @@ class Swipeable extends React.PureComponent<Props> {\nrightActions: PropTypes.arrayOf(\nPropTypes.exact({\nkey: PropTypes.string.isRequired,\n- onPress: PropTypes.func,\n+ onPress: PropTypes.func.isRequired,\ncolor: PropTypes.string,\ncontent: PropTypes.node.isRequired,\n}),\n),\n+ onSwipeableRightWillOpen: PropTypes.func,\ninnerRef: PropTypes.exact({\ncurrent: PropTypes.instanceOf(SwipeableComponent),\n}),\n@@ -104,6 +106,7 @@ class Swipeable extends React.PureComponent<Props> {\n<SwipeableComponent\nrenderRightActions={this.renderRightActions}\nref={this.props.innerRef}\n+ onSwipeableRightWillOpen={this.props.onSwipeableRightWillOpen}\n>\n{this.props.children}\n</SwipeableComponent>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Close currently opened swipeable when another is being opened Summary: When swipeable is opened, thread's id is saved in list state. Then, it's passed to all the items and if it doesn't match item's id, the swipeable will be closed. Reviewers: ashoat, KatPo Reviewed By: ashoat Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D70
129,191
08.09.2020 10:29:09
-7,200
ad69606a760573ab41d3a655efd35a93bc170e6e
[native] Use hooks in chat thread list item Summary: Use hooks in chat thread list item Reviewers: ashoat, KatPo Subscribers: Adrian, zrebcu411
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list-item.react.js", "new_path": "native/chat/chat-thread-list-item.react.js", "diff": "@@ -5,7 +5,6 @@ import {\nchatThreadItemPropType,\n} from 'lib/selectors/chat-selectors';\nimport type { ThreadInfo } from 'lib/types/thread-types';\n-import type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\nimport { Text, View } from 'react-native';\n@@ -14,39 +13,29 @@ import Swipeable from '../components/swipeable';\nimport { useNavigation } from '@react-navigation/native';\nimport { shortAbsoluteDate } from 'lib/utils/date-utils';\n-import { connect } from 'lib/utils/redux-utils';\nimport Button from '../components/button.react';\nimport MessagePreview from './message-preview.react';\nimport ColorSplotch from '../components/color-splotch.react';\n-import {\n- type Colors,\n- colorsPropType,\n- colorsSelector,\n- styleSelector,\n-} from '../themes/colors';\n+import { useColors, useStyles } from '../themes/colors';\nimport { SingleLine } from '../components/single-line.react';\nimport ChatThreadListSidebar from './chat-thread-list-sidebar.react';\n-type Props = {\n- data: ChatThreadItem,\n- onPressItem: (threadInfo: ThreadInfo) => void,\n- onSwipeableWillOpen: (threadInfo: ThreadInfo) => void,\n- currentlyOpenedSwipeableId?: string,\n- // Redux state\n- colors: Colors,\n- styles: typeof styles,\n-};\n+type Props = {|\n+ +data: ChatThreadItem,\n+ +onPressItem: (threadInfo: ThreadInfo) => void,\n+ +onSwipeableWillOpen: (threadInfo: ThreadInfo) => void,\n+ +currentlyOpenedSwipeableId?: string,\n+|};\nfunction ChatThreadListItem({\ndata,\nonPressItem,\n- onSwipeableWillOpen,\ncurrentlyOpenedSwipeableId,\n- colors,\n- ...props\n}: Props) {\nconst swipeable = React.useRef<?Swipeable>();\nconst navigation = useNavigation();\n+ const styles = useStyles(unboundStyles);\n+ const colors = useColors();\nReact.useEffect(() => {\nreturn navigation.addListener('blur', () => {\n@@ -65,11 +54,11 @@ function ChatThreadListItem({\n}\n}, [currentlyOpenedSwipeableId, swipeable, data.threadInfo.id]);\n- const lastMessage = React.useCallback(() => {\n+ const lastMessage = React.useMemo(() => {\nconst mostRecentMessageInfo = data.mostRecentMessageInfo;\nif (!mostRecentMessageInfo) {\nreturn (\n- <Text style={props.styles.noMessages} numberOfLines={1}>\n+ <Text style={styles.noMessages} numberOfLines={1}>\nNo messages\n</Text>\n);\n@@ -80,7 +69,7 @@ function ChatThreadListItem({\nthreadInfo={data.threadInfo}\n/>\n);\n- }, [data.mostRecentMessageInfo, data.threadInfo, props.styles]);\n+ }, [data.mostRecentMessageInfo, data.threadInfo, styles]);\nconst sidebars = data.sidebars.map(sidebar => (\n<ChatThreadListSidebar\n@@ -94,65 +83,39 @@ function ChatThreadListItem({\nonPressItem(data.threadInfo);\n}, [onPressItem, data.threadInfo]);\n- const onSwipeableRightWillOpen = React.useCallback(() => {\n- onSwipeableWillOpen(data.threadInfo);\n- }, [onSwipeableWillOpen, data.threadInfo]);\n-\nconst lastActivity = shortAbsoluteDate(data.lastUpdatedTime);\n- const unreadStyle = data.threadInfo.currentUser.unread\n- ? props.styles.unread\n- : null;\n+ const unreadStyle = data.threadInfo.currentUser.unread ? styles.unread : null;\nreturn (\n<>\n- <Swipeable\n- buttonWidth={60}\n- innerRef={swipeable}\n- onSwipeableRightWillOpen={onSwipeableRightWillOpen}\n- rightActions={[\n- {\n- key: 'action1',\n- onPress: () => console.log('action1'),\n- color: colors.greenButton,\n- content: <Text>action1</Text>,\n- },\n- {\n- key: 'action2',\n- onPress: () => console.log('action2'),\n- color: colors.redButton,\n- content: <Text>action2</Text>,\n- },\n- ]}\n- >\n<Button\nonPress={onPress}\niosFormat=\"highlight\"\niosHighlightUnderlayColor={colors.listIosHighlightUnderlay}\niosActiveOpacity={0.85}\n>\n- <View style={props.styles.container}>\n- <View style={props.styles.row}>\n- <SingleLine style={[props.styles.threadName, unreadStyle]}>\n+ <View style={styles.container}>\n+ <View style={styles.row}>\n+ <SingleLine style={[styles.threadName, unreadStyle]}>\n{data.threadInfo.uiName}\n</SingleLine>\n- <View style={props.styles.colorSplotch}>\n+ <View style={styles.colorSplotch}>\n<ColorSplotch color={data.threadInfo.color} size=\"small\" />\n</View>\n</View>\n- <View style={props.styles.row}>\n- {lastMessage()}\n- <Text style={[props.styles.lastActivity, unreadStyle]}>\n+ <View style={styles.row}>\n+ {lastMessage}\n+ <Text style={[styles.lastActivity, unreadStyle]}>\n{lastActivity}\n</Text>\n</View>\n</View>\n</Button>\n- </Swipeable>\n{sidebars}\n</>\n);\n}\n-const styles = {\n+const unboundStyles = {\ncolorSplotch: {\nmarginLeft: 10,\nmarginTop: 2,\n@@ -192,18 +155,12 @@ const styles = {\nfontWeight: 'bold',\n},\n};\n-const stylesSelector = styleSelector(styles);\nChatThreadListItem.propTypes = {\ndata: chatThreadItemPropType.isRequired,\nonPressItem: PropTypes.func.isRequired,\nonSwipeableWillOpen: PropTypes.func.isRequired,\ncurrentlyOpenedSwipeableId: PropTypes.string,\n- colors: colorsPropType.isRequired,\n- styles: PropTypes.objectOf(PropTypes.object).isRequired,\n};\n-export default connect((state: AppState) => ({\n- colors: colorsSelector(state),\n- styles: stylesSelector(state),\n-}))(ChatThreadListItem);\n+export default ChatThreadListItem;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use hooks in chat thread list item Summary: Use hooks in chat thread list item Reviewers: ashoat, KatPo Reviewed By: ashoat Subscribers: Adrian, zrebcu411 Differential Revision: https://phabricator.ashoat.com/D72
129,187
15.09.2020 11:55:17
14,400
01ebc846bcd995fab9727075852ced82278fd2cf
[native] Use hook instead of connect functions and HOC in ChatInputBar Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-bar.react.js", "new_path": "native/chat/chat-input-bar.react.js", "diff": "// @flow\n-import type { AppState } from '../redux/redux-setup';\n-import type {\n- DispatchActionPayload,\n- DispatchActionPromise,\n-} from 'lib/utils/action-utils';\nimport { messageTypes } from 'lib/types/message-types';\nimport {\ntype ThreadInfo,\n@@ -19,7 +14,7 @@ import type { CalendarQuery } from 'lib/types/entry-types';\nimport {\ntype KeyboardState,\nkeyboardStatePropType,\n- withKeyboardState,\n+ KeyboardContext,\n} from '../keyboard/keyboard-state';\nimport {\nmessageListRoutePropType,\n@@ -28,10 +23,12 @@ import {\nimport {\ntype InputState,\ninputStatePropType,\n- withInputState,\n+ InputStateContext,\n} from '../input/input-state';\nimport type { ChatNavigationProp } from './chat.react';\nimport type { NavigationRoute } from '../navigation/route-names';\n+import { NavContext } from '../navigation/navigation-context';\n+import type { Dispatch } from 'lib/types/redux-types';\nimport * as React from 'react';\nimport {\n@@ -50,13 +47,18 @@ import invariant from 'invariant';\nimport Animated, { Easing } from 'react-native-reanimated';\nimport { TextInputKeyboardMangerIOS } from 'react-native-keyboard-input';\nimport _throttle from 'lodash/throttle';\n+import { useSelector, useDispatch } from 'react-redux';\n-import { connect } from 'lib/utils/redux-utils';\nimport { saveDraftActionType } from 'lib/actions/miscellaneous-action-types';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport { joinThreadActionTypes, joinThread } from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { trimMessage } from 'lib/shared/message-utils';\n+import {\n+ type DispatchActionPromise,\n+ useServerCall,\n+ useDispatchActionPromise,\n+} from 'lib/utils/action-utils';\nimport Button from '../components/button.react';\nimport {\n@@ -67,46 +69,46 @@ import { getKeyboardHeight } from '../keyboard/keyboard';\nimport {\ntype Colors,\ncolorsPropType,\n- colorsSelector,\n- styleSelector,\n+ useStyles,\n+ useColors,\n} from '../themes/colors';\nimport { CameraModalRouteName } from '../navigation/route-names';\nimport KeyboardInputHost from '../keyboard/keyboard-input-host.react';\n-import {\n- connectNav,\n- type NavContextType,\n-} from '../navigation/navigation-context';\nimport ClearableTextInput from '../components/clearable-text-input.react';\nconst draftKeyFromThreadID = (threadID: string) =>\n`${threadID}/message_composer`;\n+type BaseProps = {|\n+ +threadInfo: ThreadInfo,\n+ +navigation: ChatNavigationProp<'MessageList'>,\n+ +route: NavigationRoute<'MessageList'>,\n+|};\ntype Props = {|\n- threadInfo: ThreadInfo,\n- navigation: ChatNavigationProp<'MessageList'>,\n- route: NavigationRoute<'MessageList'>,\n- isActive: boolean,\n+ ...BaseProps,\n// Redux state\n- viewerID: ?string,\n- draft: string,\n- joinThreadLoadingStatus: LoadingStatus,\n- calendarQuery: () => CalendarQuery,\n- nextLocalID: number,\n- colors: Colors,\n- styles: typeof styles,\n+ +viewerID: ?string,\n+ +draft: string,\n+ +joinThreadLoadingStatus: LoadingStatus,\n+ +calendarQuery: () => CalendarQuery,\n+ +nextLocalID: number,\n+ +colors: Colors,\n+ +styles: typeof unboundStyles,\n+ // connectNav\n+ +isActive: boolean,\n// withKeyboardState\n- keyboardState: ?KeyboardState,\n+ +keyboardState: ?KeyboardState,\n// Redux dispatch functions\n- dispatchActionPayload: DispatchActionPayload,\n- dispatchActionPromise: DispatchActionPromise,\n+ +dispatch: Dispatch,\n+ +dispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- joinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n+ +joinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n// withInputState\n- inputState: ?InputState,\n+ +inputState: ?InputState,\n|};\ntype State = {|\n- text: string,\n- buttonsExpanded: boolean,\n+ +text: string,\n+ +buttonsExpanded: boolean,\n|};\nclass ChatInputBar extends React.PureComponent<Props, State> {\nstatic propTypes = {\n@@ -122,7 +124,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\nkeyboardState: keyboardStatePropType,\n- dispatchActionPayload: PropTypes.func.isRequired,\n+ dispatch: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\ninputState: inputStatePropType,\n@@ -479,9 +481,12 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n};\nsaveDraft = _throttle((text: string) => {\n- this.props.dispatchActionPayload(saveDraftActionType, {\n+ this.props.dispatch({\n+ type: saveDraftActionType,\n+ payload: {\nkey: draftKeyFromThreadID(this.props.threadInfo.id),\ndraft: text,\n+ },\n});\n}, 400);\n@@ -597,7 +602,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n};\n}\n-const styles = {\n+const unboundStyles = {\ncameraIcon: {\npaddingBottom: 10,\npaddingRight: 3,\n@@ -678,37 +683,61 @@ const styles = {\npaddingVertical: 5,\n},\n};\n-const stylesSelector = styleSelector(styles);\nconst joinThreadLoadingStatusSelector = createLoadingStatusSelector(\njoinThreadActionTypes,\n);\n-export default connectNav(\n- (context: ?NavContextType, ownProps: { threadInfo: ThreadInfo }) => ({\n- navContext: context,\n- isActive: ownProps.threadInfo.id === activeThreadSelector(context),\n- }),\n-)(\n- connect(\n- (\n- state: AppState,\n- ownProps: { threadInfo: ThreadInfo, navContext: ?NavContextType },\n- ) => {\n- const draft = state.drafts[draftKeyFromThreadID(ownProps.threadInfo.id)];\n- return {\n- viewerID: state.currentUserInfo && state.currentUserInfo.id,\n- draft: draft ? draft : '',\n- joinThreadLoadingStatus: joinThreadLoadingStatusSelector(state),\n- calendarQuery: nonThreadCalendarQuery({\n+export default React.memo<BaseProps>(function ConnectedChatInputBar(\n+ props: BaseProps,\n+) {\n+ const inputState = React.useContext(InputStateContext);\n+ const keyboardState = React.useContext(KeyboardContext);\n+ const navContext = React.useContext(NavContext);\n+\n+ const styles = useStyles(unboundStyles);\n+ const colors = useColors();\n+\n+ const isActive = React.useMemo(\n+ () => props.threadInfo.id === activeThreadSelector(navContext),\n+ [props.threadInfo.id, navContext],\n+ );\n+\n+ const draftKey = draftKeyFromThreadID(props.threadInfo.id);\n+ const draft = useSelector(state => state.drafts[draftKey] || '');\n+\n+ const viewerID = useSelector(\n+ state => state.currentUserInfo && state.currentUserInfo.id,\n+ );\n+ const joinThreadLoadingStatus = useSelector(joinThreadLoadingStatusSelector);\n+ const calendarQuery = useSelector(state =>\n+ nonThreadCalendarQuery({\nredux: state,\n- navContext: ownProps.navContext,\n+ navContext,\n}),\n- nextLocalID: state.nextLocalID,\n- colors: colorsSelector(state),\n- styles: stylesSelector(state),\n- };\n- },\n- { joinThread },\n- )(withKeyboardState(withInputState(ChatInputBar))),\n);\n+ const nextLocalID = useSelector(state => state.nextLocalID);\n+\n+ const dispatch = useDispatch();\n+ const dispatchActionPromise = useDispatchActionPromise();\n+ const callJoinThread = useServerCall(joinThread);\n+\n+ return (\n+ <ChatInputBar\n+ {...props}\n+ viewerID={viewerID}\n+ draft={draft}\n+ joinThreadLoadingStatus={joinThreadLoadingStatus}\n+ calendarQuery={calendarQuery}\n+ nextLocalID={nextLocalID}\n+ colors={colors}\n+ styles={styles}\n+ isActive={isActive}\n+ keyboardState={keyboardState}\n+ dispatch={dispatch}\n+ dispatchActionPromise={dispatchActionPromise}\n+ joinThread={callJoinThread}\n+ inputState={inputState}\n+ />\n+ );\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use hook instead of connect functions and HOC in ChatInputBar Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D111
129,187
15.09.2020 14:05:17
14,400
41184d171ffe5e7a1edac71ae7dbb90085ee867f
[lib] Use hook instead of connect functions and HOC in Socket Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -34,10 +34,7 @@ import {\nsetLateResponseActionType,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\n-import type {\n- DispatchActionPayload,\n- DispatchActionPromise,\n-} from '../utils/action-utils';\n+import type { DispatchActionPromise } from '../utils/action-utils';\nimport type { LogOutResult } from '../types/account-types';\nimport type { CalendarQuery } from '../types/entry-types';\n@@ -83,35 +80,37 @@ import sleep from '../utils/sleep';\nconst remainingTimeAfterVisualTimeout =\nclientRequestSocketTimeout - clientRequestVisualTimeout;\n-type Props = {|\n- detectUnsupervisedBackgroundRef?: (\n+export type BaseSocketProps = {|\n+ +detectUnsupervisedBackgroundRef?: (\ndetectUnsupervisedBackground: (alreadyClosed: boolean) => boolean,\n) => void,\n+|};\n+type Props = {|\n+ ...BaseSocketProps,\n// Redux state\n- active: boolean,\n- openSocket: () => WebSocket,\n- getClientResponses: (\n+ +active: boolean,\n+ +openSocket: () => WebSocket,\n+ +getClientResponses: (\nactiveServerRequests: $ReadOnlyArray<ServerRequest>,\n) => $ReadOnlyArray<ClientClientResponse>,\n- activeThread: ?string,\n- sessionStateFunc: () => SessionState,\n- sessionIdentification: SessionIdentification,\n- cookie: ?string,\n- urlPrefix: string,\n- connection: ConnectionInfo,\n- currentCalendarQuery: () => CalendarQuery,\n- canSendReports: boolean,\n- frozen: boolean,\n- preRequestUserState: PreRequestUserState,\n+ +activeThread: ?string,\n+ +sessionStateFunc: () => SessionState,\n+ +sessionIdentification: SessionIdentification,\n+ +cookie: ?string,\n+ +urlPrefix: string,\n+ +connection: ConnectionInfo,\n+ +currentCalendarQuery: () => CalendarQuery,\n+ +canSendReports: boolean,\n+ +frozen: boolean,\n+ +preRequestUserState: PreRequestUserState,\n// Redux dispatch functions\n- dispatch: Dispatch,\n- dispatchActionPayload: DispatchActionPayload,\n- dispatchActionPromise: DispatchActionPromise,\n+ +dispatch: Dispatch,\n+ +dispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: (preRequestUserState: PreRequestUserState) => Promise<LogOutResult>,\n+ +logOut: (preRequestUserState: PreRequestUserState) => Promise<LogOutResult>,\n|};\ntype State = {|\n- inflightRequests: ?InflightRequests,\n+ +inflightRequests: ?InflightRequests,\n|};\nclass Socket extends React.PureComponent<Props, State> {\nstatic propTypes = {\n@@ -130,7 +129,6 @@ class Socket extends React.PureComponent<Props, State> {\nfrozen: PropTypes.bool.isRequired,\npreRequestUserState: preRequestUserStatePropType.isRequired,\ndispatch: PropTypes.func.isRequired,\n- dispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nlogOut: PropTypes.func.isRequired,\n};\n@@ -182,8 +180,9 @@ class Socket extends React.PureComponent<Props, State> {\nconsole.log(`this.socket seems open, but Redux thinks it's ${status}`);\n}\n}\n- this.props.dispatchActionPayload(updateConnectionStatusActionType, {\n- status: newStatus,\n+ this.props.dispatch({\n+ type: updateConnectionStatusActionType,\n+ payload: { status: newStatus },\n});\nconst socket = this.props.openSocket();\n@@ -232,8 +231,9 @@ class Socket extends React.PureComponent<Props, State> {\n}\nmarkSocketInitialized() {\n- this.props.dispatchActionPayload(updateConnectionStatusActionType, {\n- status: 'connected',\n+ this.props.dispatch({\n+ type: updateConnectionStatusActionType,\n+ payload: { status: 'connected' },\n});\nthis.resetPing();\n}\n@@ -252,8 +252,9 @@ class Socket extends React.PureComponent<Props, State> {\nreturn;\n}\nthis.stopPing();\n- this.props.dispatchActionPayload(updateConnectionStatusActionType, {\n- status: 'disconnecting',\n+ this.props.dispatch({\n+ type: updateConnectionStatusActionType,\n+ payload: { status: 'disconnecting' },\n});\nif (!activityUpdatePending) {\nthis.finishClosingSocket();\n@@ -264,8 +265,9 @@ class Socket extends React.PureComponent<Props, State> {\nthis.stopPing();\nconst { status } = this.props.connection;\nif (status !== 'forcedDisconnecting' && status !== 'disconnected') {\n- this.props.dispatchActionPayload(updateConnectionStatusActionType, {\n- status: 'forcedDisconnecting',\n+ this.props.dispatch({\n+ type: updateConnectionStatusActionType,\n+ payload: { status: 'forcedDisconnecting' },\n});\n}\nthis.finishClosingSocket();\n@@ -286,8 +288,9 @@ class Socket extends React.PureComponent<Props, State> {\nthis.socket = null;\nthis.stopPing();\nif (this.props.connection.status !== 'disconnected') {\n- this.props.dispatchActionPayload(updateConnectionStatusActionType, {\n- status: 'disconnected',\n+ this.props.dispatch({\n+ type: updateConnectionStatusActionType,\n+ payload: { status: 'disconnected' },\n});\n}\nthis.setState({ inflightRequests: null });\n@@ -465,7 +468,9 @@ class Socket extends React.PureComponent<Props, State> {\n// This should only happen in the cookieSources.BODY (native) case when\n// the resolution attempt failed\nconst { cookie: newerCookie, currentUserInfo } = sessionChange;\n- this.props.dispatchActionPayload(setNewSessionActionType, {\n+ this.props.dispatch({\n+ type: setNewSessionActionType,\n+ payload: {\nsessionChange: {\ncookieInvalidated: true,\ncurrentUserInfo,\n@@ -473,6 +478,7 @@ class Socket extends React.PureComponent<Props, State> {\n},\npreRequestUserState: this.initializedWithUserState,\nerror: null,\n+ },\n});\n} else if (!recoverySessionChange) {\nthis.props.dispatchActionPromise(\n@@ -502,8 +508,9 @@ class Socket extends React.PureComponent<Props, State> {\n}\nconst handled = this.detectUnsupervisedBackground(true);\nif (!handled && status !== 'disconnected') {\n- this.props.dispatchActionPayload(updateConnectionStatusActionType, {\n- status: 'disconnected',\n+ this.props.dispatch({\n+ type: updateConnectionStatusActionType,\n+ payload: { status: 'disconnected' },\n});\n}\n};\n@@ -562,34 +569,46 @@ class Socket extends React.PureComponent<Props, State> {\n);\nif (activityUpdateMessage) {\n- this.props.dispatchActionPayload(updateActivityActionTypes.success, {\n+ this.props.dispatch({\n+ type: updateActivityActionTypes.success,\n+ payload: {\nactivityUpdates: queuedActivityUpdates,\nresult: activityUpdateMessage.payload,\n+ },\n});\n}\nif (stateSyncMessage.payload.type === stateSyncPayloadTypes.FULL) {\nconst { sessionID, type, ...actionPayload } = stateSyncMessage.payload;\n- this.props.dispatchActionPayload(fullStateSyncActionType, {\n+ this.props.dispatch({\n+ type: fullStateSyncActionType,\n+ payload: {\n...actionPayload,\ncalendarQuery: sessionState.calendarQuery,\n+ },\n});\nif (sessionID !== null && sessionID !== undefined) {\ninvariant(\nthis.initializedWithUserState,\n'initializedWithUserState should be set when state sync received',\n);\n- this.props.dispatchActionPayload(setNewSessionActionType, {\n+ this.props.dispatch({\n+ type: setNewSessionActionType,\n+ payload: {\nsessionChange: { cookieInvalidated: false, sessionID },\npreRequestUserState: this.initializedWithUserState,\nerror: null,\n+ },\n});\n}\n} else {\nconst { type, ...actionPayload } = stateSyncMessage.payload;\n- this.props.dispatchActionPayload(incrementalStateSyncActionType, {\n+ this.props.dispatch({\n+ type: incrementalStateSyncActionType,\n+ payload: {\n...actionPayload,\ncalendarQuery: sessionState.calendarQuery,\n+ },\n});\n}\n@@ -678,9 +697,9 @@ class Socket extends React.PureComponent<Props, State> {\n}\nsetLateResponse = (messageID: number, isLate: boolean) => {\n- this.props.dispatchActionPayload(setLateResponseActionType, {\n- messageID,\n- isLate,\n+ this.props.dispatch({\n+ type: setLateResponseActionType,\n+ payload: { messageID, isLate },\n});\n};\n@@ -711,7 +730,10 @@ class Socket extends React.PureComponent<Props, State> {\nif (!alreadyClosed) {\nthis.cleanUpServerTerminatedSocket();\n}\n- this.props.dispatchActionPayload(unsupervisedBackgroundActionType, null);\n+ this.props.dispatch({\n+ type: unsupervisedBackgroundActionType,\n+ payload: null,\n+ });\nreturn true;\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "// @flow\n-import type { AppState } from './redux/redux-setup';\n+import * as React from 'react';\n+import { useSelector, useDispatch } from 'react-redux';\n-import { connect } from 'lib/utils/redux-utils';\nimport { logOut } from 'lib/actions/user-actions';\n-import Socket from 'lib/socket/socket.react';\n+import Socket, { type BaseSocketProps } from 'lib/socket/socket.react';\nimport { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\n+import {\n+ useServerCall,\n+ useDispatchActionPromise,\n+} from 'lib/utils/action-utils';\nimport {\nopenSocketSelector,\n@@ -17,51 +21,86 @@ import {\nactiveMessageListSelector,\nnativeCalendarQuery,\n} from './navigation/nav-selectors';\n-import {\n- connectNav,\n- type NavContextType,\n-} from './navigation/navigation-context';\n-import { withInputState, type InputState } from './input/input-state';\n+import { NavContext } from './navigation/navigation-context';\n+import { InputStateContext } from './input/input-state';\n-export default connectNav((context: ?NavContextType) => ({\n- rawActiveThread: activeMessageListSelector(context),\n- navContext: context,\n-}))(\n- withInputState(\n- connect(\n- (\n- state: AppState,\n- ownProps: {\n- rawActiveThread: boolean,\n- navContext: ?NavContextType,\n- inputState: ?InputState,\n- },\n- ) => {\n- const active =\n+export default React.memo<BaseSocketProps>(function NativeSocket(\n+ props: BaseSocketProps,\n+) {\n+ const inputState = React.useContext(InputStateContext);\n+ const navContext = React.useContext(NavContext);\n+\n+ const cookie = useSelector(state => state.cookie);\n+ const urlPrefix = useSelector(state => state.urlPrefix);\n+ const connection = useSelector(state => state.connection);\n+ const frozen = useSelector(state => state.frozen);\n+ const active = useSelector(\n+ state =>\n!!state.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\n- state.foreground;\n- const navPlusRedux = { redux: state, navContext: ownProps.navContext };\n- return {\n- active,\n- openSocket: openSocketSelector(state),\n- getClientResponses: nativeGetClientResponsesSelector(navPlusRedux),\n- activeThread: active ? ownProps.rawActiveThread : null,\n- sessionStateFunc: nativeSessionStateFuncSelector(navPlusRedux),\n- sessionIdentification: sessionIdentificationSelector(state),\n- cookie: state.cookie,\n- urlPrefix: state.urlPrefix,\n- connection: state.connection,\n- currentCalendarQuery: nativeCalendarQuery(navPlusRedux),\n- canSendReports:\n+ state.foreground,\n+ );\n+\n+ const openSocket = useSelector(openSocketSelector);\n+ const sessionIdentification = useSelector(sessionIdentificationSelector);\n+ const preRequestUserState = useSelector(preRequestUserStateSelector);\n+\n+ const getClientResponses = useSelector(state =>\n+ nativeGetClientResponsesSelector({\n+ redux: state,\n+ navContext,\n+ }),\n+ );\n+ const sessionStateFunc = useSelector(state =>\n+ nativeSessionStateFuncSelector({\n+ redux: state,\n+ navContext,\n+ }),\n+ );\n+ const currentCalendarQuery = useSelector(state =>\n+ nativeCalendarQuery({\n+ redux: state,\n+ navContext,\n+ }),\n+ );\n+\n+ const canSendReports = useSelector(\n+ state =>\n!state.frozen &&\nstate.connectivity.hasWiFi &&\n- (!ownProps.inputState || !ownProps.inputState.uploadInProgress()),\n- frozen: state.frozen,\n- preRequestUserState: preRequestUserStateSelector(state),\n- };\n- },\n- { logOut },\n- )(Socket),\n- ),\n+ (!inputState || !inputState.uploadInProgress()),\n+ );\n+\n+ const activeThread = React.useMemo(() => {\n+ if (!active) {\n+ return null;\n+ }\n+ return activeMessageListSelector(navContext);\n+ }, [active, navContext]);\n+\n+ const dispatch = useDispatch();\n+ const dispatchActionPromise = useDispatchActionPromise();\n+ const callLogOut = useServerCall(logOut);\n+\n+ return (\n+ <Socket\n+ {...props}\n+ active={active}\n+ openSocket={openSocket}\n+ getClientResponses={getClientResponses}\n+ activeThread={activeThread}\n+ sessionStateFunc={sessionStateFunc}\n+ sessionIdentification={sessionIdentification}\n+ cookie={cookie}\n+ urlPrefix={urlPrefix}\n+ connection={connection}\n+ currentCalendarQuery={currentCalendarQuery}\n+ canSendReports={canSendReports}\n+ frozen={frozen}\n+ preRequestUserState={preRequestUserState}\n+ dispatch={dispatch}\n+ dispatchActionPromise={dispatchActionPromise}\n+ logOut={callLogOut}\n+ />\n);\n+});\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "// @flow\n-import type { AppState } from './redux/redux-setup';\n+import * as React from 'react';\n+import { useSelector, useDispatch } from 'react-redux';\n-import { connect } from 'lib/utils/redux-utils';\nimport { logOut } from 'lib/actions/user-actions';\n-import Socket from 'lib/socket/socket.react';\n+import Socket, { type BaseSocketProps } from 'lib/socket/socket.react';\nimport { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\n+import {\n+ useServerCall,\n+ useDispatchActionPromise,\n+} from 'lib/utils/action-utils';\nimport {\nopenSocketSelector,\n@@ -18,29 +22,58 @@ import {\nwebCalendarQuery,\n} from './selectors/nav-selectors';\n-export default connect(\n- (state: AppState) => {\n- const active =\n- state.currentUserInfo &&\n+export default React.memo<BaseSocketProps>(function WebSocket(\n+ props: BaseSocketProps,\n+) {\n+ const cookie = useSelector(state => state.cookie);\n+ const urlPrefix = useSelector(state => state.urlPrefix);\n+ const connection = useSelector(state => state.connection);\n+ const active = useSelector(\n+ state =>\n+ !!state.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\n- state.foreground;\n- const activeThread =\n- active && state.windowActive ? activeThreadSelector(state) : null;\n- return {\n- active,\n- openSocket: openSocketSelector(state),\n- getClientResponses: webGetClientResponsesSelector(state),\n- activeThread,\n- sessionStateFunc: webSessionStateFuncSelector(state),\n- sessionIdentification: sessionIdentificationSelector(state),\n- cookie: state.cookie,\n- urlPrefix: state.urlPrefix,\n- connection: state.connection,\n- currentCalendarQuery: webCalendarQuery(state),\n- canSendReports: true,\n- frozen: false,\n- preRequestUserState: preRequestUserStateSelector(state),\n- };\n- },\n- { logOut },\n-)(Socket);\n+ state.foreground,\n+ );\n+\n+ const openSocket = useSelector(openSocketSelector);\n+ const sessionIdentification = useSelector(sessionIdentificationSelector);\n+ const preRequestUserState = useSelector(preRequestUserStateSelector);\n+ const getClientResponses = useSelector(webGetClientResponsesSelector);\n+ const sessionStateFunc = useSelector(webSessionStateFuncSelector);\n+ const currentCalendarQuery = useSelector(webCalendarQuery);\n+\n+ const reduxActiveThread = useSelector(activeThreadSelector);\n+ const windowActive = useSelector(state => state.windowActive);\n+ const activeThread = React.useMemo(() => {\n+ if (!active || !windowActive) {\n+ return null;\n+ }\n+ return reduxActiveThread;\n+ }, [active, windowActive, reduxActiveThread]);\n+\n+ const dispatch = useDispatch();\n+ const dispatchActionPromise = useDispatchActionPromise();\n+ const callLogOut = useServerCall(logOut);\n+\n+ return (\n+ <Socket\n+ {...props}\n+ active={active}\n+ openSocket={openSocket}\n+ getClientResponses={getClientResponses}\n+ activeThread={activeThread}\n+ sessionStateFunc={sessionStateFunc}\n+ sessionIdentification={sessionIdentification}\n+ cookie={cookie}\n+ urlPrefix={urlPrefix}\n+ connection={connection}\n+ currentCalendarQuery={currentCalendarQuery}\n+ canSendReports={true}\n+ frozen={false}\n+ preRequestUserState={preRequestUserState}\n+ dispatch={dispatch}\n+ dispatchActionPromise={dispatchActionPromise}\n+ logOut={callLogOut}\n+ />\n+ );\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Use hook instead of connect functions and HOC in Socket Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D112
129,187
15.09.2020 14:10:56
14,400
2dd32dde29ad842b80ff4c3005d6ed666802b0f2
[web] Use hook instead of connect functions and HOC in ChatInputBar Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-input-bar.react.js", "new_path": "web/chat/chat-input-bar.react.js", "diff": "// @flow\n-import type { AppState } from '../redux/redux-setup';\n-import type {\n- DispatchActionPromise,\n- DispatchActionPayload,\n-} from 'lib/utils/action-utils';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\nimport type { CalendarQuery } from 'lib/types/entry-types';\n@@ -29,12 +24,17 @@ import { faChevronRight } from '@fortawesome/free-solid-svg-icons';\nimport { faFileImage } from '@fortawesome/free-regular-svg-icons';\nimport PropTypes from 'prop-types';\nimport _difference from 'lodash/fp/difference';\n+import { useSelector } from 'react-redux';\n-import { connect } from 'lib/utils/redux-utils';\nimport { joinThreadActionTypes, joinThread } from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport { trimMessage } from 'lib/shared/message-utils';\n+import {\n+ type DispatchActionPromise,\n+ useServerCall,\n+ useDispatchActionPromise,\n+} from 'lib/utils/action-utils';\nimport css from './chat-message-list.css';\nimport LoadingIndicator from '../loading-indicator.react';\n@@ -42,20 +42,22 @@ import { nonThreadCalendarQuery } from '../selectors/nav-selectors';\nimport { allowedMimeTypeString } from '../media/file-utils';\nimport Multimedia from '../media/multimedia.react';\n+type BaseProps = {|\n+ +threadInfo: ThreadInfo,\n+ +inputState: InputState,\n+|};\ntype Props = {|\n- threadInfo: ThreadInfo,\n- inputState: InputState,\n+ ...BaseProps,\n// Redux state\n- viewerID: ?string,\n- joinThreadLoadingStatus: LoadingStatus,\n- calendarQuery: () => CalendarQuery,\n- nextLocalID: number,\n- isThreadActive: boolean,\n+ +viewerID: ?string,\n+ +joinThreadLoadingStatus: LoadingStatus,\n+ +calendarQuery: () => CalendarQuery,\n+ +nextLocalID: number,\n+ +isThreadActive: boolean,\n// Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n- dispatchActionPayload: DispatchActionPayload,\n+ +dispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- joinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n+ +joinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n|};\nclass ChatInputBar extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -67,7 +69,6 @@ class ChatInputBar extends React.PureComponent<Props> {\nnextLocalID: PropTypes.number.isRequired,\nisThreadActive: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- dispatchActionPayload: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n};\ntextarea: ?HTMLTextAreaElement;\n@@ -382,13 +383,30 @@ const joinThreadLoadingStatusSelector = createLoadingStatusSelector(\njoinThreadActionTypes,\n);\n-export default connect(\n- (state: AppState, ownProps: { threadInfo: ThreadInfo, ... }) => ({\n- viewerID: state.currentUserInfo && state.currentUserInfo.id,\n- joinThreadLoadingStatus: joinThreadLoadingStatusSelector(state),\n- calendarQuery: nonThreadCalendarQuery(state),\n- nextLocalID: state.nextLocalID,\n- isThreadActive: ownProps.threadInfo.id === state.navInfo.activeChatThreadID,\n- }),\n- { joinThread },\n-)(ChatInputBar);\n+export default React.memo<BaseProps>(function ConnectedChatInputBar(\n+ props: BaseProps,\n+) {\n+ const viewerID = useSelector(\n+ state => state.currentUserInfo && state.currentUserInfo.id,\n+ );\n+ const nextLocalID = useSelector(state => state.nextLocalID);\n+ const isThreadActive = useSelector(\n+ state => props.threadInfo.id === state.navInfo.activeChatThreadID,\n+ );\n+ const joinThreadLoadingStatus = useSelector(joinThreadLoadingStatusSelector);\n+ const calendarQuery = useSelector(nonThreadCalendarQuery);\n+ const dispatchActionPromise = useDispatchActionPromise();\n+ const callJoinThread = useServerCall(joinThread);\n+ return (\n+ <ChatInputBar\n+ {...props}\n+ viewerID={viewerID}\n+ joinThreadLoadingStatus={joinThreadLoadingStatus}\n+ calendarQuery={calendarQuery}\n+ nextLocalID={nextLocalID}\n+ isThreadActive={isThreadActive}\n+ dispatchActionPromise={dispatchActionPromise}\n+ joinThread={callJoinThread}\n+ />\n+ );\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Use hook instead of connect functions and HOC in ChatInputBar Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D113
129,187
15.09.2020 14:48:11
14,400
f7f82380ca88cd40f3b85e921db42bfedfe78c70
[web] Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -16,7 +16,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faCalendar, faComments } from '@fortawesome/free-solid-svg-icons';\nimport { config as faConfig } from '@fortawesome/fontawesome-svg-core';\nimport classNames from 'classnames';\n-import HTML5Backend from 'react-dnd-html5-backend';\n+import { HTML5Backend } from 'react-dnd-html5-backend';\nimport { DndProvider } from 'react-dnd';\nimport {\n" }, { "change_type": "MODIFY", "old_path": "web/package.json", "new_path": "web/package.json", "diff": "\"react\": \"16.11.0\",\n\"react-circular-progressbar\": \"^2.0.2\",\n\"react-color\": \"^2.13.0\",\n- \"react-dnd\": \"^9.4.0\",\n- \"react-dnd-html5-backend\": \"^9.4.0\",\n+ \"react-dnd\": \"^11.1.3\",\n+ \"react-dnd-html5-backend\": \"^11.1.3\",\n\"react-dom\": \"16.11.0\",\n\"react-feather\": \"^2.0.3\",\n\"react-hot-loader\": \"^4.12.14\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "resolved \"https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570\"\nintegrity sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=\n+\"@react-dnd/asap@^4.0.0\":\n+ version \"4.0.0\"\n+ resolved \"https://registry.yarnpkg.com/@react-dnd/asap/-/asap-4.0.0.tgz#b300eeed83e9801f51bd66b0337c9a6f04548651\"\n+ integrity sha512-0XhqJSc6pPoNnf8DhdsPHtUhRzZALVzYMTzRwV4VI6DJNJ/5xxfL9OQUwb8IH5/2x7lSf7nAZrnzUD+16VyOVQ==\n+\n+\"@react-dnd/invariant@^2.0.0\":\n+ version \"2.0.0\"\n+ resolved \"https://registry.yarnpkg.com/@react-dnd/invariant/-/invariant-2.0.0.tgz#09d2e81cd39e0e767d7da62df9325860f24e517e\"\n+ integrity sha512-xL4RCQBCBDJ+GRwKTFhGUW8GXa4yoDfJrPbLblc3U09ciS+9ZJXJ3Qrcs/x2IODOdIE5kQxvMmE2UKyqUictUw==\n+\n+\"@react-dnd/shallowequal@^2.0.0\":\n+ version \"2.0.0\"\n+ resolved \"https://registry.yarnpkg.com/@react-dnd/shallowequal/-/shallowequal-2.0.0.tgz#a3031eb54129f2c66b2753f8404266ec7bf67f0a\"\n+ integrity sha512-Pc/AFTdwZwEKJxFJvlxrSmGe/di+aAOBn60sremrpLo6VI/6cmiUYNNwlI5KNYttg7uypzA3ILPMPgxB2GYZEg==\n+\n\"@react-native-community/art@^1.0.3\", \"@react-native-community/art@^1.1.2\":\nversion \"1.1.2\"\nresolved \"https://registry.yarnpkg.com/@react-native-community/art/-/art-1.1.2.tgz#8d365ad5a12f83a0570ef83590f883a201f8e723\"\nresolved \"https://registry.yarnpkg.com/@types/anymatch/-/anymatch-1.3.1.tgz#336badc1beecb9dacc38bea2cf32adf627a8421a\"\nintegrity sha512-/+CRPXpBDpo2RK9C68N3b2cOvO0Cf5B9aPijHsoDQTHivnGSObdOF2BRQOYjojWTDy6nQvMjmqRXIxH55VjxxA==\n-\"@types/asap@^2.0.0\":\n- version \"2.0.0\"\n- resolved \"https://registry.yarnpkg.com/@types/asap/-/asap-2.0.0.tgz#d529e9608c83499a62ae08c871c5e62271aa2963\"\n- integrity sha512-upIS0Gt9Mc8eEpCbYMZ1K8rhNosfKUtimNcINce+zLwJF5UpM3Vv7yz3S5l/1IX+DxTa8lTkUjqynvjRXyJzsg==\n-\n\"@types/babel__core@^7.1.0\":\nversion \"7.1.3\"\nresolved \"https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.3.tgz#e441ea7df63cd080dfcd02ab199e6d16a735fc30\"\nresolved \"https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz#9140779736aa2655635ee756e2467d787cfe8a2a\"\nintegrity sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A==\n-\"@types/invariant@^2.2.30\":\n- version \"2.2.30\"\n- resolved \"https://registry.yarnpkg.com/@types/invariant/-/invariant-2.2.30.tgz#20efa342807606ada5483731a8137cb1561e5fe9\"\n- integrity sha512-98fB+yo7imSD2F7PF7GIpELNgtLNgo5wjivu0W5V4jx+KVVJxo6p/qN4zdzSTBWy4/sN3pPyXwnhRSD28QX+ag==\n-\n\"@types/istanbul-lib-coverage@*\", \"@types/istanbul-lib-coverage@^2.0.0\":\nversion \"2.0.1\"\nresolved \"https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz#42995b446db9a48a11a07ec083499a860e9138ff\"\ndependencies:\n\"@types/node\" \"*\"\n-\"@types/shallowequal@^1.1.1\":\n- version \"1.1.1\"\n- resolved \"https://registry.yarnpkg.com/@types/shallowequal/-/shallowequal-1.1.1.tgz#aad262bb3f2b1257d94c71d545268d592575c9b1\"\n- integrity sha512-Lhni3aX80zbpdxRuWhnuYPm8j8UQaa571lHP/xI4W+7BAFhSIhRReXnqjEgT/XzPoXZTJkCqstFMJ8CZTK6IlQ==\n-\n\"@types/source-list-map@*\":\nversion \"0.1.2\"\nresolved \"https://registry.yarnpkg.com/@types/source-list-map/-/source-list-map-0.1.2.tgz#0078836063ffaf17412349bba364087e0ac02ec9\"\n@@ -3438,7 +3438,7 @@ art@^0.10.3:\nresolved \"https://registry.yarnpkg.com/art/-/art-0.10.3.tgz#b01d84a968ccce6208df55a733838c96caeeaea2\"\nintegrity sha512-HXwbdofRTiJT6qZX/FnchtldzJjS3vkLJxQilc3Xj+ma2MXjY4UAyQ0ls1XZYVnDvVIBiFZbC6QsvtW86TD6tQ==\n-asap@^2.0.6, asap@~2.0.3:\n+asap@~2.0.3:\nversion \"2.0.6\"\nresolved \"https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46\"\nintegrity sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=\n@@ -5509,15 +5509,13 @@ dir-glob@^2.0.0:\ndependencies:\npath-type \"^3.0.0\"\n-dnd-core@^9.4.0:\n- version \"9.4.0\"\n- resolved \"https://registry.yarnpkg.com/dnd-core/-/dnd-core-9.4.0.tgz#ccf605d36887f18cdde8fd5576ca3145d2e69fa8\"\n- integrity sha512-Kg+8VwU8s7TgdR/BUYGUHrvFiS+5ePMZ0Q0XD7p+cFVJvgKqykBaeQDuaziuauFMPm8QxtnUy8Pncey9flXW3Q==\n+dnd-core@^11.1.3:\n+ version \"11.1.3\"\n+ resolved \"https://registry.yarnpkg.com/dnd-core/-/dnd-core-11.1.3.tgz#f92099ba7245e49729d2433157031a6267afcc98\"\n+ integrity sha512-QugF55dNW+h+vzxVJ/LSJeTeUw9MCJ2cllhmVThVPEtF16ooBkxj0WBE5RB+AceFxMFo1rO6bJKXtqKl+JNnyA==\ndependencies:\n- \"@types/asap\" \"^2.0.0\"\n- \"@types/invariant\" \"^2.2.30\"\n- asap \"^2.0.6\"\n- invariant \"^2.2.4\"\n+ \"@react-dnd/asap\" \"^4.0.0\"\n+ \"@react-dnd/invariant\" \"^2.0.0\"\nredux \"^4.0.4\"\ndns-equal@^1.0.0:\n@@ -12050,23 +12048,22 @@ react-devtools-core@^4.0.6:\nshell-quote \"^1.6.1\"\nws \"^7\"\n-react-dnd-html5-backend@^9.4.0:\n- version \"9.4.0\"\n- resolved \"https://registry.yarnpkg.com/react-dnd-html5-backend/-/react-dnd-html5-backend-9.4.0.tgz#5b1d192f57d103298657cde1fe0eabdbf2726311\"\n- integrity sha512-gehPwLp505F6RoFkQiDX7Q4mbpbyfyT0TbIoZop/m4vkBw6yUE/QLrnxBQdNpDPSwL/9XkZxxd/PrbeMCQ+WrQ==\n+react-dnd-html5-backend@^11.1.3:\n+ version \"11.1.3\"\n+ resolved \"https://registry.yarnpkg.com/react-dnd-html5-backend/-/react-dnd-html5-backend-11.1.3.tgz#2749f04f416ec230ea193f5c1fbea2de7dffb8f7\"\n+ integrity sha512-/1FjNlJbW/ivkUxlxQd7o3trA5DE33QiRZgxent3zKme8DwF4Nbw3OFVhTRFGaYhHFNL1rZt6Rdj1D78BjnNLw==\ndependencies:\n- dnd-core \"^9.4.0\"\n+ dnd-core \"^11.1.3\"\n-react-dnd@^9.4.0:\n- version \"9.4.0\"\n- resolved \"https://registry.yarnpkg.com/react-dnd/-/react-dnd-9.4.0.tgz#eec87035c6360fb33a44932326b3369af011a41c\"\n- integrity sha512-jnLF8qKowCKTqSddfCiLx5+sb+HxO1qgdiAgbBeL8yuo5tRYNtKxZYn7+wVwNoyZuWEuM1Gw/Wsdhr+yb2RELQ==\n+react-dnd@^11.1.3:\n+ version \"11.1.3\"\n+ resolved \"https://registry.yarnpkg.com/react-dnd/-/react-dnd-11.1.3.tgz#f9844f5699ccc55dfc81462c2c19f726e670c1af\"\n+ integrity sha512-8rtzzT8iwHgdSC89VktwhqdKKtfXaAyC4wiqp0SywpHG12TTLvfOoL6xNEIUWXwIEWu+CFfDn4GZJyynCEuHIQ==\ndependencies:\n+ \"@react-dnd/shallowequal\" \"^2.0.0\"\n\"@types/hoist-non-react-statics\" \"^3.3.1\"\n- \"@types/shallowequal\" \"^1.1.1\"\n- dnd-core \"^9.4.0\"\n+ dnd-core \"^11.1.3\"\nhoist-non-react-statics \"^3.3.0\"\n- shallowequal \"^1.1.0\"\nreact-dom@16.11.0:\nversion \"16.11.0\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] react-dnd@11.1.3 Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D114
129,187
15.09.2020 15:05:38
14,400
148a59e4d9643226c1f4c2811c3c371d9bad6862
[web] Use hook instead of connect functions and HOC in ChatMessageList Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.react.js", "new_path": "web/chat/chat-message-list.react.js", "diff": "// @flow\n-import type { AppState } from '../redux/redux-setup';\nimport {\ntype ChatMessageItem,\nchatMessageItemPropType,\n} from 'lib/selectors/chat-selectors';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { FetchMessageInfosPayload } from 'lib/types/message-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n-import { DropTarget } from 'react-dnd';\n+import { useDrop } from 'react-dnd';\nimport { NativeTypes } from 'react-dnd-html5-backend';\nimport classNames from 'classnames';\nimport { detect as detectBrowser } from 'detect-browser';\n+import { useSelector } from 'react-redux';\n-import { connect } from 'lib/utils/redux-utils';\nimport { messageKey } from 'lib/shared/message-utils';\nimport { threadInChatList } from 'lib/shared/thread-utils';\nimport threadWatcher from 'lib/shared/thread-watcher';\n@@ -29,6 +27,11 @@ import {\nfetchMostRecentMessages,\n} from 'lib/actions/message-actions';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\n+import {\n+ type DispatchActionPromise,\n+ useServerCall,\n+ useDispatchActionPromise,\n+} from 'lib/utils/action-utils';\nimport { webMessageListData } from '../selectors/chat-selectors';\nimport ChatInputBar from './chat-input-bar.react';\n@@ -42,31 +45,34 @@ import MessageTimestampTooltip from './message-timestamp-tooltip.react';\nimport {\ninputStatePropType,\ntype InputState,\n- withInputState,\n+ InputStateContext,\n} from '../input/input-state';\nimport css from './chat-message-list.css';\n+type BaseProps = {|\n+ +setModal: (modal: ?React.Node) => void,\n+|};\ntype PassedProps = {|\n- setModal: (modal: ?React.Node) => void,\n+ ...BaseProps,\n// Redux state\n- activeChatThreadID: ?string,\n- threadInfo: ?ThreadInfo,\n- messageListData: ?$ReadOnlyArray<ChatMessageItem>,\n- startReached: boolean,\n- timeZone: ?string,\n- firefox: boolean,\n+ +activeChatThreadID: ?string,\n+ +threadInfo: ?ThreadInfo,\n+ +messageListData: ?$ReadOnlyArray<ChatMessageItem>,\n+ +startReached: boolean,\n+ +timeZone: ?string,\n+ +firefox: boolean,\n// Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n+ +dispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- fetchMessagesBeforeCursor: (\n+ +fetchMessagesBeforeCursor: (\nthreadID: string,\nbeforeMessageID: string,\n) => Promise<FetchMessageInfosPayload>,\n- fetchMostRecentMessages: (\n+ +fetchMostRecentMessages: (\nthreadID: string,\n) => Promise<FetchMessageInfosPayload>,\n// withInputState\n- inputState: ?InputState,\n+ +inputState: ?InputState,\n|};\ntype ReactDnDProps = {|\nisActive: boolean,\n@@ -379,42 +385,71 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nregisterFetchKey(fetchMessagesBeforeCursorActionTypes);\nregisterFetchKey(fetchMostRecentMessagesActionTypes);\n-const ReduxConnectedChatMessageList = connect(\n- (state: AppState) => {\n- const { activeChatThreadID } = state.navInfo;\n- const browser = detectBrowser(state.userAgent);\n- const firefox = browser && browser.name === 'firefox';\n- return {\n- activeChatThreadID,\n- threadInfo: activeChatThreadID\n- ? threadInfoSelector(state)[activeChatThreadID]\n- : null,\n- messageListData: webMessageListData(state),\n- startReached: !!(\n- activeChatThreadID &&\n- state.messageStore.threads[activeChatThreadID].startReached\n- ),\n- timeZone: state.timeZone,\n- firefox,\n- };\n- },\n- { fetchMessagesBeforeCursor, fetchMostRecentMessages },\n-)(ChatMessageList);\n-\n-export default withInputState(\n- DropTarget(\n- NativeTypes.FILE,\n- {\n- drop: (props: PassedProps, monitor) => {\n- const { files } = monitor.getItem();\n- if (props.inputState && files.length > 0) {\n- props.inputState.appendFiles(files);\n+export default React.memo<BaseProps>(function ConnectedChatMessageList(\n+ props: BaseProps,\n+) {\n+ const userAgent = useSelector(state => state.userAgent);\n+ const firefox = React.useMemo(() => {\n+ const browser = detectBrowser(userAgent);\n+ return browser && browser.name === 'firefox';\n+ }, [userAgent]);\n+\n+ const messageListData = useSelector(webMessageListData);\n+ const timeZone = useSelector(state => state.timeZone);\n+\n+ const activeChatThreadID = useSelector(\n+ state => state.navInfo.activeChatThreadID,\n+ );\n+ const threadInfo = useSelector(state => {\n+ const activeID = state.navInfo.activeChatThreadID;\n+ if (!activeID) {\n+ return null;\n+ }\n+ return threadInfoSelector(state)[activeID];\n+ });\n+ const startReached = useSelector(state => {\n+ const activeID = state.navInfo.activeChatThreadID;\n+ if (!activeID) {\n+ return null;\n+ }\n+ return state.messageStore.threads[activeID].startReached;\n+ });\n+\n+ const dispatchActionPromise = useDispatchActionPromise();\n+ const callFetchMessagesBeforeCursor = useServerCall(\n+ fetchMessagesBeforeCursor,\n+ );\n+ const callFetchMostRecentMessages = useServerCall(fetchMostRecentMessages);\n+\n+ const inputState = React.useContext(InputStateContext);\n+ const [dndProps, connectDropTarget] = useDrop({\n+ accept: NativeTypes.FILE,\n+ drop: item => {\n+ const { files } = item;\n+ if (inputState && files.length > 0) {\n+ inputState.appendFiles(files);\n}\n},\n- },\n- (connector, monitor) => ({\n- connectDropTarget: connector.dropTarget(),\n+ collect: monitor => ({\nisActive: monitor.isOver() && monitor.canDrop(),\n}),\n- )(ReduxConnectedChatMessageList),\n+ });\n+\n+ return (\n+ <ChatMessageList\n+ {...props}\n+ activeChatThreadID={activeChatThreadID}\n+ threadInfo={threadInfo}\n+ messageListData={messageListData}\n+ startReached={startReached}\n+ timeZone={timeZone}\n+ firefox={firefox}\n+ inputState={inputState}\n+ dispatchActionPromise={dispatchActionPromise}\n+ fetchMessagesBeforeCursor={callFetchMessagesBeforeCursor}\n+ fetchMostRecentMessages={callFetchMostRecentMessages}\n+ {...dndProps}\n+ connectDropTarget={connectDropTarget}\n+ />\n);\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Use hook instead of connect functions and HOC in ChatMessageList Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D115
129,187
15.09.2020 15:10:49
14,400
bd708118cd947d206a9bdda019781ddb045cf143
[web] Use hook instead of withInputState in ComposedMessage Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/composed-message.react.js", "new_path": "web/chat/composed-message.react.js", "diff": "@@ -20,6 +20,7 @@ import {\nCheckCircle as CheckCircleIcon,\nXCircle as XCircleIcon,\n} from 'react-feather';\n+import invariant from 'invariant';\nimport { stringForUser } from 'lib/shared/user-utils';\n@@ -29,23 +30,27 @@ import MessageReplyTooltip from './message-reply-tooltip.react';\nimport {\ninputStatePropType,\ntype InputState,\n- withInputState,\n+ InputStateContext,\n} from '../input/input-state';\n-type Props = {|\n- item: ChatMessageInfoItem,\n- threadInfo: ThreadInfo,\n- sendFailed: boolean,\n- setMouseOverMessagePosition: (\n+type BaseProps = {|\n+ +item: ChatMessageInfoItem,\n+ +threadInfo: ThreadInfo,\n+ +sendFailed: boolean,\n+ +setMouseOverMessagePosition: (\nmessagePositionInfo: MessagePositionInfo,\n) => void,\n- mouseOverMessagePosition?: ?OnMessagePositionInfo,\n- canReply: boolean,\n- children: React.Node,\n- fixedWidth?: boolean,\n- borderRadius: number,\n+ +mouseOverMessagePosition?: ?OnMessagePositionInfo,\n+ +canReply: boolean,\n+ +children: React.Node,\n+ +fixedWidth?: boolean,\n+ +borderRadius: number,\n+|};\n+type BaseConfig = React.Config<BaseProps, typeof ComposedMessage.defaultProps>;\n+type Props = {|\n+ ...BaseProps,\n// withInputState\n- inputState: InputState,\n+ +inputState: ?InputState,\n|};\nclass ComposedMessage extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -58,7 +63,7 @@ class ComposedMessage extends React.PureComponent<Props> {\nchildren: PropTypes.node.isRequired,\nfixedWidth: PropTypes.bool,\nborderRadius: PropTypes.number.isRequired,\n- inputState: inputStatePropType.isRequired,\n+ inputState: inputStatePropType,\n};\nstatic defaultProps = {\nborderRadius: 8,\n@@ -130,11 +135,13 @@ class ComposedMessage extends React.PureComponent<Props> {\nthis.props.mouseOverMessagePosition.item.messageInfo.id === id &&\nthis.props.canReply\n) {\n+ const { inputState } = this.props;\n+ invariant(inputState, 'inputState should be set in ComposedMessage');\nconst replyTooltip = (\n<MessageReplyTooltip\nmessagePositionInfo={this.props.mouseOverMessagePosition}\nonReplyClick={this.onMouseLeave}\n- inputState={this.props.inputState}\n+ inputState={inputState}\n/>\n);\nif (isViewer) {\n@@ -184,4 +191,9 @@ class ComposedMessage extends React.PureComponent<Props> {\n};\n}\n-export default withInputState(ComposedMessage);\n+export default React.memo<BaseConfig>(function ConnectedComposedMessage(\n+ props: BaseConfig,\n+) {\n+ const inputState = React.useContext(InputStateContext);\n+ return <ComposedMessage {...props} inputState={inputState} />;\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Use hook instead of withInputState in ComposedMessage Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D116
129,187
15.09.2020 15:15:45
14,400
020a39c0b38e92c84dc41d61dff752729b468bbf
[web] Use hook instead of connect functions and HOC in FailedSend Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/failed-send.react.js", "new_path": "web/chat/failed-send.react.js", "diff": "@@ -10,14 +10,13 @@ import {\nassertComposableMessageType,\n} from 'lib/types/message-types';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n+import { useSelector } from 'react-redux';\nimport { messageID } from 'lib/shared/message-utils';\n-import { connect } from 'lib/utils/redux-utils';\nimport css from './chat-message-list.css';\nimport multimediaMessageSendFailed from './multimedia-message-send-failed';\n@@ -25,23 +24,26 @@ import textMessageSendFailed from './text-message-send-failed';\nimport {\ninputStatePropType,\ntype InputState,\n- withInputState,\n+ InputStateContext,\n} from '../input/input-state';\n+type BaseProps = {|\n+ +item: ChatMessageInfoItem,\n+ +threadInfo: ThreadInfo,\n+|};\ntype Props = {|\n- item: ChatMessageInfoItem,\n- threadInfo: ThreadInfo,\n+ ...BaseProps,\n// Redux state\n- rawMessageInfo: RawComposableMessageInfo,\n+ +rawMessageInfo: RawComposableMessageInfo,\n// withInputState\n- inputState: InputState,\n+ +inputState: ?InputState,\n|};\nclass FailedSend extends React.PureComponent<Props> {\nstatic propTypes = {\nitem: chatMessageItemPropType.isRequired,\nthreadInfo: threadInfoPropType.isRequired,\nrawMessageInfo: PropTypes.object.isRequired,\n- inputState: inputStatePropType.isRequired,\n+ inputState: inputStatePropType,\n};\nretryingText = false;\nretryingMedia = false;\n@@ -53,13 +55,16 @@ class FailedSend extends React.PureComponent<Props> {\n(prevProps.rawMessageInfo.type === messageTypes.IMAGES ||\nprevProps.rawMessageInfo.type === messageTypes.MULTIMEDIA)\n) {\n- const isFailed = multimediaMessageSendFailed(\n- this.props.item,\n- this.props.inputState,\n+ const { inputState } = this.props;\n+ const prevInputState = prevProps.inputState;\n+ invariant(\n+ inputState && prevInputState,\n+ 'inputState should be set in FailedSend',\n);\n+ const isFailed = multimediaMessageSendFailed(this.props.item, inputState);\nconst wasFailed = multimediaMessageSendFailed(\nprevProps.item,\n- prevProps.inputState,\n+ prevInputState,\n);\nconst isDone =\nthis.props.item.messageInfo.id !== null &&\n@@ -102,13 +107,16 @@ class FailedSend extends React.PureComponent<Props> {\nretrySend = (event: SyntheticEvent<HTMLAnchorElement>) => {\nevent.stopPropagation();\n+ const { inputState } = this.props;\n+ invariant(inputState, 'inputState should be set in FailedSend');\n+\nconst { rawMessageInfo } = this.props;\nif (rawMessageInfo.type === messageTypes.TEXT) {\nif (this.retryingText) {\nreturn;\n}\nthis.retryingText = true;\n- this.props.inputState.sendTextMessage({\n+ inputState.sendTextMessage({\n...rawMessageInfo,\ntime: Date.now(),\n});\n@@ -122,17 +130,18 @@ class FailedSend extends React.PureComponent<Props> {\nreturn;\n}\nthis.retryingMedia = true;\n- this.props.inputState.retryMultimediaMessage(localID);\n+ inputState.retryMultimediaMessage(localID);\n}\n};\n}\n-export default connect(\n- (state: AppState, ownProps: { item: ChatMessageInfoItem }) => {\n- const { messageInfo } = ownProps.item;\n+export default React.memo<BaseProps>(function ConnectedFailedSend(\n+ props: BaseProps,\n+) {\n+ const { messageInfo } = props.item;\nassertComposableMessageType(messageInfo.type);\nconst id = messageID(messageInfo);\n- const rawMessageInfo = state.messageStore.messages[id];\n+ const rawMessageInfo = useSelector(state => state.messageStore.messages[id]);\nassertComposableMessageType(rawMessageInfo.type);\ninvariant(\nrawMessageInfo.type === messageTypes.TEXT ||\n@@ -140,6 +149,12 @@ export default connect(\nrawMessageInfo.type === messageTypes.MULTIMEDIA,\n'FailedSend should only be used for composable message types',\n);\n- return { rawMessageInfo };\n- },\n-)(withInputState(FailedSend));\n+ const inputState = React.useContext(InputStateContext);\n+ return (\n+ <FailedSend\n+ {...props}\n+ rawMessageInfo={rawMessageInfo}\n+ inputState={inputState}\n+ />\n+ );\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Use hook instead of connect functions and HOC in FailedSend Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D117
129,187
15.09.2020 15:19:23
14,400
5d1f49411a70e0bf1c047e47c6942c3cdaf6aad4
[web] Use hook instead of withInputState in MultimediaMessage Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/chat/multimedia-message.react.js", "new_path": "web/chat/multimedia-message.react.js", "diff": "@@ -19,18 +19,21 @@ import sendFailed from './multimedia-message-send-failed';\nimport {\ninputStatePropType,\ntype InputState,\n- withInputState,\n+ InputStateContext,\n} from '../input/input-state';\n-type Props = {|\n- item: ChatMessageInfoItem,\n- threadInfo: ThreadInfo,\n- setMouseOverMessagePosition: (\n+type BaseProps = {|\n+ +item: ChatMessageInfoItem,\n+ +threadInfo: ThreadInfo,\n+ +setMouseOverMessagePosition: (\nmessagePositionInfo: MessagePositionInfo,\n) => void,\n- setModal: (modal: ?React.Node) => void,\n+ +setModal: (modal: ?React.Node) => void,\n+|};\n+type Props = {|\n+ ...BaseProps,\n// withInputState\n- inputState: InputState,\n+ +inputState: ?InputState,\n|};\nclass MultimediaMessage extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -38,11 +41,11 @@ class MultimediaMessage extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nsetMouseOverMessagePosition: PropTypes.func.isRequired,\nsetModal: PropTypes.func.isRequired,\n- inputState: inputStatePropType.isRequired,\n+ inputState: inputStatePropType,\n};\nrender() {\n- const { item, setModal } = this.props;\n+ const { item, setModal, inputState } = this.props;\ninvariant(\nitem.messageInfo.type === messageTypes.IMAGES ||\nitem.messageInfo.type === messageTypes.MULTIMEDIA,\n@@ -50,9 +53,8 @@ class MultimediaMessage extends React.PureComponent<Props> {\n);\nconst { localID, media } = item.messageInfo;\n- const pendingUploads = localID\n- ? this.props.inputState.assignedUploads[localID]\n- : null;\n+ invariant(inputState, 'inputState should be set in MultimediaMessage');\n+ const pendingUploads = localID ? inputState.assignedUploads[localID] : null;\nconst multimedia = [];\nfor (let singleMedia of media) {\nconst pendingUpload = pendingUploads\n@@ -82,7 +84,7 @@ class MultimediaMessage extends React.PureComponent<Props> {\n<ComposedMessage\nitem={item}\nthreadInfo={this.props.threadInfo}\n- sendFailed={sendFailed(this.props.item, this.props.inputState)}\n+ sendFailed={sendFailed(item, inputState)}\nsetMouseOverMessagePosition={this.props.setMouseOverMessagePosition}\ncanReply={false}\nfixedWidth={multimedia.length > 1}\n@@ -94,4 +96,9 @@ class MultimediaMessage extends React.PureComponent<Props> {\n}\n}\n-export default withInputState(MultimediaMessage);\n+export default React.memo<BaseProps>(function ConnectedMultimediaMessage(\n+ props: BaseProps,\n+) {\n+ const inputState = React.useContext(InputStateContext);\n+ return <MultimediaMessage {...props} inputState={inputState} />;\n+});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Use hook instead of withInputState in MultimediaMessage Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D118
129,187
15.09.2020 15:20:17
14,400
5a113e274e4fa0c2ea31a26d600ba1112e5a6589
[web] Get rid of withInputState Summary: It's no longer used. Going forward, let's use hooks for data binding Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "web/input/input-state.js", "new_path": "web/input/input-state.js", "diff": "@@ -92,31 +92,8 @@ const inputStatePropType = PropTypes.shape({\nconst InputStateContext = React.createContext<?InputState>(null);\n-function withInputState<\n- AllProps: {},\n- ComponentType: React.ComponentType<AllProps>,\n->(\n- Component: ComponentType,\n-): React.ComponentType<\n- $Diff<React.ElementConfig<ComponentType>, { inputState: ?InputState }>,\n-> {\n- class InputStateHOC extends React.PureComponent<\n- $Diff<React.ElementConfig<ComponentType>, { inputState: ?InputState }>,\n- > {\n- render() {\n- return (\n- <InputStateContext.Consumer>\n- {value => <Component {...this.props} inputState={value} />}\n- </InputStateContext.Consumer>\n- );\n- }\n- }\n- return InputStateHOC;\n-}\n-\nexport {\npendingMultimediaUploadPropType,\ninputStatePropType,\nInputStateContext,\n- withInputState,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Get rid of withInputState Summary: It's no longer used. Going forward, let's use hooks for data binding Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D119
129,187
15.09.2020 15:52:02
14,400
3d85835e9a899e759f3122b0137811137b12ee91
[native] Use hook instead of connect functions and HOC in FailedSend Reviewers: palys-swm Subscribers: KatPo, zrebcu411, Adrian
[ { "change_type": "MODIFY", "old_path": "native/chat/failed-send.react.js", "new_path": "native/chat/failed-send.react.js", "diff": "import type { ChatMessageInfoItemWithHeight } from './message.react';\nimport { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport { messageTypes, type RawMessageInfo } from 'lib/types/message-types';\n-import type { AppState } from '../redux/redux-setup';\nimport {\ntype InputState,\ninputStatePropType,\n- withInputState,\n+ InputStateContext,\n} from '../input/input-state';\nimport * as React from 'react';\nimport { Text, View } from 'react-native';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n+import { useSelector } from 'react-redux';\nimport { messageID } from 'lib/shared/message-utils';\n-import { connect } from 'lib/utils/redux-utils';\nimport Button from '../components/button.react';\n-import { styleSelector } from '../themes/colors';\n+import { useStyles } from '../themes/colors';\nimport multimediaMessageSendFailed from './multimedia-message-send-failed';\nimport textMessageSendFailed from './text-message-send-failed';\nconst failedSendHeight = 22;\n+type BaseProps = {|\n+ +item: ChatMessageInfoItemWithHeight,\n+|};\ntype Props = {|\n- item: ChatMessageInfoItemWithHeight,\n+ ...BaseProps,\n// Redux state\n- rawMessageInfo: ?RawMessageInfo,\n- styles: typeof styles,\n+ +rawMessageInfo: ?RawMessageInfo,\n+ +styles: typeof unboundStyles,\n// withInputState\n- inputState: ?InputState,\n+ +inputState: ?InputState,\n|};\nclass FailedSend extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -129,7 +131,7 @@ class FailedSend extends React.PureComponent<Props> {\n};\n}\n-const styles = {\n+const unboundStyles = {\ndeliveryFailed: {\ncolor: 'listSeparatorLabel',\npaddingHorizontal: 3,\n@@ -146,16 +148,22 @@ const styles = {\npaddingHorizontal: 3,\n},\n};\n-const stylesSelector = styleSelector(styles);\n-const ConnectedFailedSend = connect(\n- (state: AppState, ownProps: { item: ChatMessageInfoItemWithHeight }) => {\n- const id = messageID(ownProps.item.messageInfo);\n- return {\n- rawMessageInfo: state.messageStore.messages[id],\n- styles: stylesSelector(state),\n- };\n- },\n-)(withInputState(FailedSend));\n+const ConnectedFailedSend = React.memo<BaseProps>(function ConnectedFailedSend(\n+ props: BaseProps,\n+) {\n+ const id = messageID(props.item.messageInfo);\n+ const rawMessageInfo = useSelector(state => state.messageStore.messages[id]);\n+ const styles = useStyles(unboundStyles);\n+ const inputState = React.useContext(InputStateContext);\n+ return (\n+ <FailedSend\n+ {...props}\n+ rawMessageInfo={rawMessageInfo}\n+ styles={styles}\n+ inputState={inputState}\n+ />\n+ );\n+});\nexport { ConnectedFailedSend as FailedSend, failedSendHeight };\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use hook instead of connect functions and HOC in FailedSend Reviewers: palys-swm Reviewed By: palys-swm Subscribers: KatPo, zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D120