@jsb188/graphql 1.1.4 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,67 +1,4 @@
1
1
  import { gql } from 'graphql-tag';
2
- import { userAuthFragment } from '../fragments/userAuthFragments';
3
- import { emailFragment, phoneFragment } from '../fragments/otherFragments';
4
- import { plusFragment, userFragment, userPersonaFragment } from '../fragments/userFragments';
5
-
6
- const signInResultText = `...userAuthFragment
7
-
8
- user {
9
- ...userFragment
10
- lightMode
11
-
12
- plus {
13
- ...plusFragment
14
- }
15
-
16
- email {
17
- ...emailFragment
18
- }
19
-
20
- phone {
21
- ...phoneFragment
22
- }
23
-
24
- personas {
25
- ...userPersonaFragment
26
- }
27
- }`;
28
-
29
- const signInFragments = `
30
- ${userAuthFragment}
31
- ${userFragment}
32
- ${plusFragment}
33
- ${emailFragment}
34
- ${userPersonaFragment}
35
- ${phoneFragment}
36
- `;
37
-
38
- export const signInWithTokenMtn = gql`
39
- mutation signInWithToken (
40
- $token: Token!
41
- ) {
42
- signInWithToken (
43
- token: $token
44
- ) {
45
- ${signInResultText}
46
- }
47
- }
48
- ${signInFragments}
49
- `;
50
-
51
- export const checkUsernameOrEmailMtn = gql`
52
- mutation checkUsernameOrEmail (
53
- $usernameOrEmail: String!
54
- $authCheck: Boolean
55
- ) {
56
- checkUsernameOrEmail (
57
- usernameOrEmail: $usernameOrEmail
58
- authCheck: $authCheck
59
- ) {
60
- value
61
- type
62
- taken
63
- }
64
- }`;
65
2
 
66
3
  export const signOutMtn = gql`
67
4
  mutation signOut {
@@ -81,47 +18,6 @@ mutation updateAppSettings (
81
18
  }
82
19
  `;
83
20
 
84
- export const signInMtn = gql`
85
- mutation signIn (
86
- $usernameOrEmail: String!
87
- $password: String!
88
- ) {
89
- signIn (
90
- usernameOrEmail: $usernameOrEmail,
91
- password: $password
92
- ) {
93
- ${signInResultText}
94
- }
95
- }
96
- ${signInFragments}
97
- `;
98
-
99
- export const changePasswordMtn = gql`
100
- mutation changePassword (
101
- $currentPassword: String!
102
- $password: String!
103
- $passwordRepeat: String!
104
- $token: Token
105
- ) {
106
- changePassword (
107
- currentPassword: $currentPassword
108
- password: $password
109
- passwordRepeat: $passwordRepeat
110
- token: $token
111
- )
112
- }`;
113
-
114
- export const requestTokenizedEmailMtn = gql`
115
- mutation requestTokenizedEmail (
116
- $email: String!
117
- $requestType: TokenType!
118
- ) {
119
- requestTokenizedEmail (
120
- email: $email
121
- requestType: $requestType
122
- )
123
- }`;
124
-
125
21
  export const consumeTokenMtn = gql`
126
22
  mutation consumeToken (
127
23
  $token: Token!
@@ -9,6 +9,7 @@ query aiChat (
9
9
  aiChat (
10
10
  aiChatId: $aiChatId
11
11
  ) {
12
+ cursor
12
13
  ...aiChatFragment
13
14
 
14
15
  messages (
@@ -3,7 +3,8 @@ import { gql } from 'graphql-tag';
3
3
  export const updateNoteQry = gql`
4
4
  query updateNote {
5
5
  updateNote {
6
- version
6
+ webVersion
7
+ mobileVersion
7
8
  emoji
8
9
  title
9
10
  at
@@ -28,6 +28,7 @@ query organizationRelationship (
28
28
 
29
29
  organization {
30
30
  ...organizationFragment
31
+ membersCount
31
32
  }
32
33
  }
33
34
  }
package/hooks/index.ts CHANGED
@@ -7,8 +7,8 @@ import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverVa
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
8
  import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache';
9
9
  import { QUERY_EXPIRE_TIMES } from '../cache/config';
10
- import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
11
10
  import { graphqlRequest } from '../client/request';
11
+ import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
12
12
 
13
13
 
14
14
  /**
@@ -34,6 +34,7 @@ type GraphQLMutationResult = {
34
34
  variables: Record<string, any> | null;
35
35
  saving: boolean;
36
36
  error: ServerErrorObj | null;
37
+ mutationCount: number;
37
38
  };
38
39
 
39
40
  type GraphQLMutation = [
@@ -41,7 +42,7 @@ type GraphQLMutation = [
41
42
  GraphQLMutationResult,
42
43
  GraphQLHandlers,
43
44
  UpdateObserversFn,
44
- React.MutableRefObject<boolean>
45
+ React.MutableRefObject<Record<string, any>>
45
46
  ];
46
47
 
47
48
  /**
@@ -161,21 +162,48 @@ export function useWatchQuery(
161
162
  */
162
163
 
163
164
  export function useReactiveFragment(
164
- data_: any,
165
- observe: Array<string | string[]>,
166
- qryObsCount?: number,
165
+ data: any,
166
+ observe: Array<string | [string, string | null]>,
167
+ qryObsCount?: number | boolean,
167
168
  otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
168
169
  ignoreIDWarning?: boolean,
169
170
  // doTest?: boolean
170
171
  ) {
171
172
 
172
- const data = data_ || {};
173
173
  const fragmentObserver = useFragmentObserverValue();
174
174
  const frgObsCount = fragmentObserver.count;
175
- const [changedData, setChangedData] = useState<any>({
176
- fragmentUpdatedCount: frgObsCount,
177
- queryUpdatedCount: qryObsCount,
178
- data
175
+ const dataId = data?.id;
176
+
177
+ const [changedData, setChangedData] = useState<any>(() => {
178
+ // This allows initial data to *not* be null even when data param is null
179
+ let initialData = data;
180
+
181
+ observe.forEach((key) => {
182
+ const isMapped = Array.isArray(key);
183
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
184
+
185
+ if (fragmentData) {
186
+ if (isMapped) {
187
+ if (key[1]) {
188
+ initialData = {
189
+ ...initialData!,
190
+ [key[1]]: fragmentData,
191
+ };
192
+ }
193
+ } else {
194
+ initialData = {
195
+ ...initialData!,
196
+ ...fragmentData,
197
+ };
198
+ }
199
+ }
200
+ });
201
+
202
+ return {
203
+ fragmentUpdatedCount: frgObsCount,
204
+ queryUpdatedCount: qryObsCount,
205
+ data: initialData
206
+ };
179
207
  });
180
208
 
181
209
  if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
@@ -184,21 +212,22 @@ export function useReactiveFragment(
184
212
  useEffect(() => {
185
213
  if (
186
214
  // getENVVariable('NODE_ENV') === 'development' &&
187
- data.id && changedData.data?.id &&
188
- data.id !== changedData.data?.id
215
+ dataId && changedData.data?.id &&
216
+ dataId !== changedData.data?.id
189
217
  ) {
190
- console.warn(`WARNING: useReactiveFragment() data.id changed from ${data.id} to ${changedData.data?.id}`);
218
+ console.warn(`WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`);
191
219
  console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
192
220
  }
193
221
  }, [changedData.data?.id]);
194
222
  }
195
223
 
196
224
  useEffect(() => {
197
- // NOTE: I tried this with effect()
225
+ // NOTE: I tried this with Preact's effect()
198
226
  // But that caused the render to happen 3 times more, I don't know why.
199
227
  // I only solved it by using useEffect()
200
228
  const idsChanged = (
201
- changedData.data.id !== data.id ||
229
+ !dataId ||
230
+ changedData.data.id !== dataId ||
202
231
  (
203
232
  // This is absolutely needed for the chat clientId system to work properly;
204
233
  // Otherwise messages will be stuck in "not sent" state.
@@ -220,48 +249,52 @@ export function useReactiveFragment(
220
249
  )
221
250
  ) {
222
251
 
223
- // if (doTest) {
224
- // console.log('DO TEST:');
225
- // console.log(observe);
226
- // console.log(fragmentObserver);
227
- // }
252
+ const dataUpdated = (
253
+ idsChanged ||
254
+ forceReactive ||
255
+ observe.some((key) => {
256
+ const isMapped = Array.isArray(key);
257
+ return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
258
+ })
259
+ )
228
260
 
229
261
  let newData;
230
- for (const key of observe) {
231
- const isMapped = Array.isArray(key);
232
- if (
233
- key && (
234
- idsChanged ||
235
- forceReactive ||
236
- (isMapped && fragmentObserver.list.includes(key[0])) ||
237
- (!isMapped && fragmentObserver.list.includes(key))
238
- )
239
- ) {
240
- if (!newData) {
241
- if (idsChanged) {
242
- newData = data;
243
- } else if (data) {
244
- newData = {
245
- ...data,
246
- ...changedData.data,
247
- };
248
- } else {
249
- newData = changedData.data;
262
+ if (dataUpdated) {
263
+ for (const key of observe) {
264
+ const isMapped = Array.isArray(key);
265
+
266
+ if (key) {
267
+ if (!newData) {
268
+ if (idsChanged) {
269
+ newData = data;
270
+ } else if (data) {
271
+ newData = {
272
+ ...data,
273
+ ...changedData.data,
274
+ };
275
+ } else {
276
+ newData = changedData.data;
277
+ }
250
278
  }
251
- }
252
279
 
253
- const fragmentData = loadFragment(isMapped ? key[0] : key);
254
- if (fragmentData) {
255
- if (isMapped) {
256
- newData = {
257
- ...newData,
258
- [key[1]]: fragmentData,
259
- };
260
- } else {
261
- newData = {
262
- ...newData,
263
- ...fragmentData,
264
- };
280
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
281
+ // console.log('fragmentKey', key);
282
+ // console.log('fragmentData', fragmentData);
283
+
284
+ if (fragmentData) {
285
+ if (isMapped) {
286
+ if (key[1]) {
287
+ newData = {
288
+ ...newData,
289
+ [key[1]]: fragmentData,
290
+ };
291
+ }
292
+ } else {
293
+ newData = {
294
+ ...newData,
295
+ ...fragmentData,
296
+ };
297
+ }
265
298
  }
266
299
  }
267
300
  }
@@ -275,7 +308,7 @@ export function useReactiveFragment(
275
308
  });
276
309
  }
277
310
  }
278
- }, [data.id, qryObsCount, frgObsCount]);
311
+ }, [dataId, qryObsCount, frgObsCount]);
279
312
 
280
313
  // This is not needed now, I think
281
314
  // useEffect(() => {
@@ -384,19 +417,27 @@ export function useMutation(
384
417
  // But bring it back if you want ability to "cancel"
385
418
  // const controller = useRef();
386
419
 
387
- const mounted = useRef(true);
420
+ const tracker = useRef({
421
+ mounted: true,
422
+ timer: null as NodeJS.Timeout | null,
423
+ });
424
+
388
425
  const [mtnValues, setMtnValues] = useState({
389
426
  variables: null as Record<string, any> | null,
390
427
  saving: false,
391
428
  data: null,
392
- error: initialError || null as ServerErrorObj | null
429
+ error: initialError || null as ServerErrorObj | null,
430
+ mutationCount: 0,
393
431
  });
394
432
 
395
433
  // Mounted hook
396
434
 
397
435
  useEffect(() => {
398
436
  return () => {
399
- mounted.current = false;
437
+ tracker.current.mounted = false;
438
+ if (tracker.current.timer) {
439
+ clearTimeout(tracker.current.timer);
440
+ }
400
441
  };
401
442
  }, []);
402
443
 
@@ -429,9 +470,10 @@ export function useMutation(
429
470
  {
430
471
  openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
431
472
  onCompleted: (data: any | null, error: ServerErrorObj | null) => {
432
- if (mounted.current) {
473
+ if (tracker.current.mounted) {
433
474
  setMtnValues({
434
475
  ...mtnValues,
476
+ mutationCount: mtnValues.mutationCount + 1,
435
477
  saving: false,
436
478
  data: data.data || null,
437
479
  error,
@@ -439,14 +481,14 @@ export function useMutation(
439
481
  }
440
482
 
441
483
  if (data.data) {
442
- if (onCompleted && (mounted.current || !checkMountedBeforeCallback)) {
484
+ if (onCompleted && (tracker.current.mounted || !checkMountedBeforeCallback)) {
443
485
  // Do separate {mounted.current} check from outside
444
486
  onCompleted(data.data, error, graphqlOptions?.variables);
445
487
  }
446
488
  }
447
489
  },
448
490
  onError: (error: ServerErrorObj | null) => {
449
- if (mounted.current) {
491
+ if (tracker.current.mounted) {
450
492
  setMtnValues({
451
493
  ...mtnValues,
452
494
  saving: retryCount > triedCount,
@@ -454,7 +496,7 @@ export function useMutation(
454
496
  });
455
497
  }
456
498
 
457
- if (onError && retryCount <= triedCount && (mounted.current || !checkMountedBeforeCallback)) {
499
+ if (onError && retryCount <= triedCount && (tracker.current.mounted || !checkMountedBeforeCallback)) {
458
500
  onError(error, graphqlOptions?.variables);
459
501
  }
460
502
  },
@@ -486,13 +528,13 @@ export function useMutation(
486
528
  };
487
529
 
488
530
  const mtnHandlers: GraphQLHandlers = {
489
- resetErrors: function () {
531
+ resetErrors: () => {
490
532
  setMtnValues({
491
533
  ...mtnValues,
492
534
  error: null,
493
535
  });
494
536
  },
495
- setError: function (errorObj: SimpleErrorType) {
537
+ setError: (errorObj: SimpleErrorType) => {
496
538
  setMtnValues({
497
539
  ...mtnValues,
498
540
  error: {
@@ -502,21 +544,32 @@ export function useMutation(
502
544
  },
503
545
  });
504
546
  },
505
- refetch: function () {
547
+ refetch: () => {
506
548
  const lastVariables = mtnValues.variables;
507
549
  return doMutate(lastVariables ? { variables: lastVariables } : undefined);
508
550
  },
551
+ setSaving: (nextSaving: boolean, resetInMS?: number) => {
552
+ setMtnValues({
553
+ ...mtnValues,
554
+ saving: nextSaving,
555
+ });
556
+
557
+ if (nextSaving && resetInMS) {
558
+ if (tracker.current.timer) {
559
+ clearTimeout(tracker.current.timer);
560
+ }
561
+
562
+ tracker.current.timer = setTimeout(() => {
563
+ setMtnValues({
564
+ ...mtnValues,
565
+ saving: false,
566
+ });
567
+ }, resetInMS);
568
+ }
569
+ }
509
570
  };
510
571
 
511
- // useEffect(() => {
512
- // return () => {
513
- // if (controller.current) {
514
- // controller.current.abort();
515
- // }
516
- // };
517
- // }, []);
518
-
519
- return [doMutate, mtnValues, mtnHandlers, updateObservers, mounted];
572
+ return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
520
573
  }
521
574
 
522
575
  /**
@@ -673,7 +726,12 @@ export function useQuery(
673
726
 
674
727
  return () => {
675
728
  unsetQueryTracker(queryKey, tracker.current.unique);
729
+ };
730
+ }, [queryKey]);
731
+
676
732
 
733
+ useEffect(() => {
734
+ return () => {
677
735
  if (tracker.current.abortCtrl) {
678
736
  // console.log('UMOUNTED:', queryKey, tracker.current.unique);
679
737
  tracker.current.abortCtrl.abort({
@@ -682,7 +740,7 @@ export function useQuery(
682
740
  });
683
741
  }
684
742
  };
685
- }, [queryKey]);
743
+ }, []);
686
744
 
687
745
  // Refetch when variables, skip status or query observer changes
688
746
 
@@ -695,6 +753,7 @@ export function useQuery(
695
753
  )
696
754
  ) {
697
755
  const cachedResult = fetchCachedData(query, variablesKey, updateObservers);
756
+
698
757
  if (cachedResult) {
699
758
  setQryValues({
700
759
  ...qryValues,
@@ -0,0 +1,43 @@
1
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
+ import { OpenModalPopUpFn, useCurrentAccount } from '@jsb188/react/states';
3
+ import { editAccountMtn } from '../gql/mutations/accountMutations';
4
+ import { useMutation } from './index';
5
+
6
+ /**
7
+ * Edit logged in user's account
8
+ */
9
+
10
+ export function useEditAccount(
11
+ params?: UseMutationParams | null,
12
+ openModalPopUp?: OpenModalPopUpFn
13
+ ) {
14
+
15
+ const { account, settings, dispatchApp } = useCurrentAccount();
16
+ const [editAccount, mtnValues, mtnHandlers] = useMutation(
17
+ editAccountMtn,
18
+ {
19
+ // checkMountedBeforeCallback: true,
20
+ openModalPopUp,
21
+ ...params,
22
+ onCompleted: (data, error) => {
23
+ params?.onCompleted?.(data, error);
24
+
25
+ const updatedData = data.editAccount;
26
+ if (updatedData) {
27
+ dispatchApp({
28
+ __type: 'APP_EDIT_ACCOUNT',
29
+ data: updatedData,
30
+ });
31
+ }
32
+ }
33
+ },
34
+ );
35
+
36
+ return {
37
+ account,
38
+ settings,
39
+ editAccount,
40
+ ...mtnValues,
41
+ ...mtnHandlers,
42
+ };
43
+ }
@@ -0,0 +1,96 @@
1
+ import { updateQuery } from '../cache/';
2
+ import { useMutation } from '../client';
3
+ import { updateAIChats } from './use-aiChat-qry';
4
+ import { sendAIChatMessageMtn, startAIChatMtn, stopAIChatMessageMtn } from '../gql/mutations/aiChatMutations';
5
+ import type { UseMutationParams } from '../types.d';
6
+ import { useOpenModalPopUp } from '@jsb188/react/states';
7
+
8
+ /**
9
+ * Start AI chat
10
+ */
11
+
12
+ export function useStartAIChat(params: UseMutationParams = {}) {
13
+
14
+ const { onCompleted, onError } = params;
15
+ const openModalPopUp = useOpenModalPopUp();
16
+
17
+ const [startAIChat, mtnValues,, updateObservers] = useMutation(
18
+ startAIChatMtn,
19
+ {
20
+ openModalPopUp,
21
+ onCompleted: (data: any, err: any, variables: any) => {
22
+ onCompleted?.(data, err, variables);
23
+
24
+ const aiChat = data.startAIChat?.node;
25
+ updateAIChats(aiChat, updateObservers);
26
+ },
27
+ onError,
28
+ },
29
+ );
30
+
31
+ return {
32
+ startAIChat,
33
+ ...mtnValues,
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Send a new message to AI Chat
39
+ */
40
+
41
+ export function useAIChatTextarea(variablesKey: string, params: UseMutationParams = {}) {
42
+
43
+ const { onCompleted, onError } = params;
44
+ const openModalPopUp = useOpenModalPopUp();
45
+
46
+ // Send AI chat message
47
+
48
+ const [sendAIChatMessage, mtnValues1,, updateObservers] = useMutation(
49
+ sendAIChatMessageMtn,
50
+ {
51
+ openModalPopUp,
52
+ onCompleted: (data: any, err: any, variables: any) => {
53
+ onCompleted?.(data, err, variables);
54
+
55
+ const aiChatId = variables.aiChatId;
56
+ const messageId = data.sendAIChatMessage?.node?.id;
57
+
58
+ if (messageId && aiChatId && variablesKey) {
59
+ updateQuery(`#aiChat:${variablesKey}`, (currentData: any) => {
60
+ if (Array.isArray(currentData.messages?.data)) {
61
+ currentData.messages.data.push([`$aiChatMessageFragment:${messageId}`]);
62
+ }
63
+ return currentData;
64
+ }, false, updateObservers);
65
+ } else if (data && !err) {
66
+ console.dev(`Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`, 'warning');
67
+ }
68
+ },
69
+ onError,
70
+ },
71
+ );
72
+
73
+ // Stop AI chat message
74
+
75
+ const [stopAIChatMessage, mtnValues2] = useMutation(
76
+ stopAIChatMessageMtn,
77
+ {
78
+ openModalPopUp,
79
+ onCompleted: (data: any, err: any, variables: any) => {
80
+ onCompleted?.(data, err, variables);
81
+ },
82
+ onError,
83
+ },
84
+ );
85
+
86
+ return {
87
+ send: {
88
+ sendAIChatMessage,
89
+ ...mtnValues1,
90
+ },
91
+ stop: {
92
+ stopAIChatMessage,
93
+ ...mtnValues2,
94
+ }
95
+ };
96
+ }