@bitsocial/bitsocial-react-hooks 0.1.29 → 0.1.31

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## [0.1.31](https://github.com/bitsocialnet/bitsocial-react-hooks/compare/v0.1.30...v0.1.31) (2026-07-23)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **comments:** show vote counts optimistically ([#75](https://github.com/bitsocialnet/bitsocial-react-hooks/issues/75)) ([cca63b2](https://github.com/bitsocialnet/bitsocial-react-hooks/commit/cca63b2a6d318a985fa24844d55925f11a615a28))
7
+
8
+
9
+ ### Features
10
+
11
+ * **communities:** expose sync lifecycle state ([#73](https://github.com/bitsocialnet/bitsocial-react-hooks/issues/73)) ([448ab3b](https://github.com/bitsocialnet/bitsocial-react-hooks/commit/448ab3b93793daae1fe591a139d3d9813d88d0e5))
12
+
13
+
14
+
1
15
  ## [0.1.29](https://github.com/bitsocialnet/bitsocial-react-hooks/compare/v0.1.28...v0.1.29) (2026-07-14)
2
16
 
3
17
 
package/README.md CHANGED
@@ -129,7 +129,7 @@ useValidateComment({comment: Comment, validateReplies?: boolean}): {valid: boole
129
129
  #### Communities Hooks
130
130
 
131
131
  ```
132
- useCommunity({community: {name?: string, publicKey?: string}, onlyIfCached?: boolean}): Community
132
+ useCommunity({community: {name?: string, publicKey?: string}, onlyIfCached?: boolean}): Community & {syncState: "initializing" | "loading" | "retrying" | "succeeded" | "failed" | "stopped", hasCachedData: boolean, lastFetchAttemptAt: number | undefined, lastSuccessfulFetchAt: number | undefined}
133
133
  useCommunities({communities?: CommunityIdentifier[], onlyIfCached?: boolean}): {communities: Communities[]}
134
134
  useCommunityStats({community: {name?: string, publicKey?: string}, onlyIfCached?: boolean}): CommunityStats
135
135
  useResolvedCommunityAddress({communityAddress: string, cache: boolean}): {resolvedAddress: string | undefined} // use {cache: false} when checking the user's own community address
@@ -139,6 +139,13 @@ Pass `{ publicKey, name }` when you have both so `pkc-js` can fetch through the
139
139
 
140
140
  `useCommunity` only exposes community error events that are not superseded by a later `update` event. Transient fetch errors are delayed briefly before surfacing through `error` or `errors`.
141
141
 
142
+ `useCommunity().state` remains `succeeded` when cached community data is available, even
143
+ while a refresh is running. Use `syncState` for the current refresh lifecycle:
144
+ `loading` covers active name, IPNS, and IPFS work, while `retrying` means a transient
145
+ failure is being retried. `lastFetchAttemptAt` and `lastSuccessfulFetchAt` are Unix
146
+ timestamps in seconds. A successful fetch only proves that a valid community record was
147
+ reachable; it does not prove that the community operator is currently online.
148
+
142
149
  #### Authors Hooks
143
150
 
144
151
  ```
@@ -409,6 +416,12 @@ const { authorComments, lastCommentCid, hasMore, loadMore } = useAuthorComments(
409
416
 
410
417
  ```jsx
411
418
  const community = useCommunity({ community: { name: communityAddress, publicKey: communityPublicKey } });
419
+ const {
420
+ syncState,
421
+ hasCachedData,
422
+ lastFetchAttemptAt,
423
+ lastSuccessfulFetchAt,
424
+ } = community;
412
425
  const communityStats = useCommunityStats({
413
426
  community: { name: communityAddress, publicKey: communityPublicKey },
414
427
  });
@@ -632,6 +645,10 @@ if (vote === 0) console.log("user voted 0");
632
645
  if (vote === undefined) console.log(`user didn't vote yet`);
633
646
  ```
634
647
 
648
+ `useComment`, `useComments`, and `useReplies` apply the selected account's pending vote to
649
+ `upvoteCount` and `downvoteCount` immediately. The optimistic adjustment is replaced by the next
650
+ canonical comment update.
651
+
635
652
  #### Create a comment edit
636
653
 
637
654
  ```jsx
@@ -1 +1 @@
1
- {"version":3,"file":"comments.d.ts","sourceRoot":"","sources":["../../src/hooks/comments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,OAAO,EACP,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACzB,MAAM,UAAU,CAAC;AAalB,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAGxE;AAED,wBAAgB,aAAa,CAC3B,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,OAAO,GAAG,SAAS,GAC7B,OAAO,GAAG,SAAS,CAIrB;AA0ED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,gBAAgB,CAuMxE;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,iBAAiB,CA0K3E;AAED,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,yBAAyB,GAAG,wBAAwB,CAmDhG"}
1
+ {"version":3,"file":"comments.d.ts","sourceRoot":"","sources":["../../src/hooks/comments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,OAAO,EACP,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACzB,MAAM,UAAU,CAAC;AAiBlB,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAGxE;AAED,wBAAgB,aAAa,CAC3B,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,OAAO,GAAG,SAAS,GAC7B,OAAO,GAAG,SAAS,CAIrB;AA0ED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,gBAAgB,CA2MxE;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,iBAAiB,CAgL3E;AAED,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,yBAAyB,GAAG,wBAAwB,CAmDhG"}
@@ -21,6 +21,7 @@ import useCommunitiesPagesStore from "../stores/communities-pages/index.js";
21
21
  import useRepliesPagesStore from "../stores/replies-pages/index.js";
22
22
  import shallow from "zustand/shallow";
23
23
  import { assertCommunityRef } from "../lib/community-ref.js";
24
+ import { addOptimisticVoteCounts, addOptimisticVoteCountsToComments, } from "../lib/utils/optimistic-vote-counts.js";
24
25
  export function getCommentFreshness(comment) {
25
26
  var _a, _b;
26
27
  if (!comment)
@@ -117,6 +118,7 @@ export function useComment(options) {
117
118
  var _a;
118
119
  return (_a = state.accountsComments[(accountCommentInfo === null || accountCommentInfo === void 0 ? void 0 : accountCommentInfo.accountId) || ""]) === null || _a === void 0 ? void 0 : _a[Number(accountCommentInfo === null || accountCommentInfo === void 0 ? void 0 : accountCommentInfo.accountCommentIndex)];
119
120
  });
121
+ const accountVote = useAccountsStore((state) => { var _a; return (account === null || account === void 0 ? void 0 : account.id) && commentCid ? (_a = state.accountsVotes[account.id]) === null || _a === void 0 ? void 0 : _a[commentCid] : undefined; });
120
122
  const createCommentData = useMemo(() => getCommentCreateCommentData(commentCid, community, communitiesPagesComment, repliesPagesComment), [
121
123
  commentCid,
122
124
  community === null || community === void 0 ? void 0 : community.name,
@@ -204,6 +206,7 @@ export function useComment(options) {
204
206
  ? frozenCommentForCurrentCid
205
207
  : frozenCommentForCurrentCid || selectedComment;
206
208
  comment = addCommentModeration(comment);
209
+ comment = addOptimisticVoteCounts(comment, accountVote);
207
210
  const { state, replyCount } = getCommentStateAndReplyCount(comment);
208
211
  if (account && commentCid) {
209
212
  log("useComment", {
@@ -247,6 +250,7 @@ export function useComments(options) {
247
250
  assert(!options || typeof options === "object", `useComments options argument '${options}' not an object`);
248
251
  const { commentCids = [], accountName, onlyIfCached, autoUpdate = true } = options !== null && options !== void 0 ? options : {};
249
252
  const account = useAccount({ accountName });
253
+ const accountVotes = useAccountsStore((state) => (account === null || account === void 0 ? void 0 : account.id) ? state.accountsVotes[account.id] : undefined);
250
254
  const commentsStoreComments = useCommentsStore((state) => commentCids.map((commentCid) => state.comments[commentCid || ""]), shallow);
251
255
  const communitiesPagesComments = useCommunitiesPagesStore((state) => commentCids.map((commentCid) => state.comments[commentCid || ""]), shallow);
252
256
  const addCommentToStore = useCommentsStore((state) => state.addCommentToStore);
@@ -331,7 +335,7 @@ export function useComments(options) {
331
335
  }, [autoUpdate, commentsKey, freezeSettledForCurrentKey, liveComments, liveCommentsSettled]);
332
336
  const frozenCommentsForCurrentSelection = frozenCommentsKey === commentsKey ? frozenComments : undefined;
333
337
  const comments = autoUpdate ? liveComments : frozenCommentsForCurrentSelection || liveComments;
334
- const normalizedComments = useMemo(() => addCommentModerationToComments(comments), [comments]);
338
+ const normalizedComments = useMemo(() => addOptimisticVoteCountsToComments(addCommentModerationToComments(comments), accountVotes), [comments, accountVotes]);
335
339
  // succeed if no comments are undefined
336
340
  const state = getCommentsState(normalizedComments);
337
341
  const refresh = useCallback(() => __awaiter(this, void 0, void 0, function* () {
@@ -1 +1 @@
1
- {"version":3,"file":"comments.js","sourceRoot":"","sources":["../../src/hooks/comments.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,SAAS,MAAM,kBAAkB,CAAC;AACzC,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,sCAAsC,CAAC,CAAC;AAC3D,OAAO,MAAM,MAAM,QAAQ,CAAC;AAU5B,OAAO,gBAAgB,MAAM,oBAAoB,CAAC;AAClD,OAAO,gBAAgB,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EACL,oBAAoB,EACpB,8BAA8B,GAC/B,MAAM,iCAAiC,CAAC;AACzC,OAAO,wBAAwB,MAAM,6BAA6B,CAAC;AACnE,OAAO,oBAAoB,MAAM,yBAAyB,CAAC;AAC3D,OAAO,OAAO,MAAM,iBAAiB,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AA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C;IACD,uEAAuE;IACvE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,KAAK,GAAG,KAAK,CAAC;IAChB,CAAC;IAED,OAAO,OAAO,CACZ,GAAG,EAAE,CAAC,CAAC;QACL,KAAK;QACL,KAAK;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QAChC,MAAM;KACP,CAAC,EACF,CAAC,KAAK,EAAE,KAAK,CAAC,CACf,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useAccount } from \"./accounts\";\nimport validator from \"../lib/validator\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:comments:hooks\");\nimport assert from \"assert\";\nimport {\n Comment,\n UseCommentsOptions,\n UseCommentsResult,\n UseCommentOptions,\n UseCommentResult,\n UseValidateCommentOptions,\n UseValidateCommentResult,\n} from \"../types\";\nimport useCommentsStore from \"../stores/comments\";\nimport useAccountsStore from \"../stores/accounts\";\nimport { commentIsValid } from \"../lib/utils\";\nimport {\n addCommentModeration,\n addCommentModerationToComments,\n} from \"../lib/utils/comment-moderation\";\nimport useCommunitiesPagesStore from \"../stores/communities-pages\";\nimport useRepliesPagesStore from \"../stores/replies-pages\";\nimport shallow from \"zustand/shallow\";\nimport { assertCommunityRef } from \"../lib/community-ref\";\n\nexport function getCommentFreshness(comment: Comment | undefined): number {\n if (!comment) return 0;\n return Math.max(comment.updatedAt ?? 0, comment.timestamp ?? 0, 0);\n}\n\nexport function preferFresher(\n current: Comment | undefined,\n candidate: Comment | undefined,\n): Comment | undefined {\n if (!candidate) return current;\n if (!current) return candidate;\n return getCommentFreshness(candidate) > getCommentFreshness(current) ? candidate : current;\n}\n\nconst getCommentStateAndReplyCount = (comment: Comment | undefined) => {\n let state = comment?.updatingState || \"initializing\";\n // force 'fetching-ipns' even if could be something else, so the frontend can use\n // the correct loading skeleton\n if (comment?.timestamp) {\n state = \"fetching-update-ipns\";\n }\n // force succeeded even if the comment is fecthing a new update\n if (comment?.updatedAt) {\n state = \"succeeded\";\n }\n\n // force succeeded if the comment is newer than 5 minutes, no need to display loading skeleton if comment was just created\n let replyCount = comment?.replyCount;\n if (\n comment?.replyCount === undefined &&\n comment?.timestamp &&\n comment?.timestamp > Date.now() / 1000 - 5 * 60\n ) {\n state = \"succeeded\";\n // set replyCount because some frontend are likely to check if replyCount === undefined to show a loading skeleton\n replyCount = 0;\n }\n\n return { state, replyCount };\n};\n\nconst getCommentsState = (comments: (Comment | undefined)[]) =>\n comments.every((comment) => getCommentStateAndReplyCount(comment).state === \"succeeded\")\n ? \"succeeded\"\n : \"fetching-ipfs\";\n\nlet commentAutoUpdateSubscriptionCount = 0;\nlet commentsAutoUpdateSubscriptionCount = 0;\n\nconst getCommentCreateCommentData = (\n commentCid: string | undefined,\n community: UseCommentOptions[\"community\"] | undefined,\n ...comments: (Comment | undefined)[]\n) => {\n if (!commentCid) {\n return undefined;\n }\n\n const createCommentData: Comment = { cid: commentCid };\n let hasCommunityData = false;\n for (const comment of comments) {\n if (!comment) {\n continue;\n }\n if (!createCommentData.communityPublicKey && comment.communityPublicKey) {\n createCommentData.communityPublicKey = comment.communityPublicKey;\n hasCommunityData = true;\n }\n if (!createCommentData.communityName && comment.communityName) {\n createCommentData.communityName = comment.communityName;\n hasCommunityData = true;\n }\n }\n\n if (community?.publicKey) {\n createCommentData.communityPublicKey = community.publicKey;\n hasCommunityData = true;\n }\n if (community?.name) {\n createCommentData.communityName = community.name;\n hasCommunityData = true;\n }\n\n return hasCommunityData ? createCommentData : undefined;\n};\n\n/**\n * @param commentCid - The IPFS CID of the comment to get\n * @param community - The community identifier, e.g. {name: 'memes.eth', publicKey: '12D3KooW...'}.\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useComment(options?: UseCommentOptions): UseCommentResult {\n assert(\n !options || typeof options === \"object\",\n `useComment options argument '${options}' not an object`,\n );\n const { commentCid, community, accountName, onlyIfCached, autoUpdate = true } = options ?? {};\n if (community !== undefined) {\n assertCommunityRef(community, \"useComment community\");\n }\n const account = useAccount({ accountName });\n const commentFromStore = useCommentsStore((state: any) => state.comments[commentCid || \"\"]);\n const addCommentToStore = useCommentsStore((state: any) => state.addCommentToStore);\n const startCommentAutoUpdate = useCommentsStore((state: any) => state.startCommentAutoUpdate);\n const stopCommentAutoUpdate = useCommentsStore((state: any) => state.stopCommentAutoUpdate);\n const refreshCommentInStore = useCommentsStore((state: any) => state.refreshComment);\n const communitiesPagesComment = useCommunitiesPagesStore(\n (state: any) => state.comments[commentCid || \"\"],\n );\n const repliesPagesComment = useRepliesPagesStore(\n (state: any) => state.comments[commentCid || \"\"],\n );\n const errors = useCommentsStore((state: any) => state.errors[commentCid || \"\"]);\n\n // get account comment of the cid if any\n const accountCommentInfo = useAccountsStore(\n (state: any) => state.commentCidsToAccountsComments[commentCid || \"\"],\n );\n const accountComment = useAccountsStore(\n (state: any) =>\n state.accountsComments[accountCommentInfo?.accountId || \"\"]?.[\n Number(accountCommentInfo?.accountCommentIndex)\n ],\n );\n const createCommentData = useMemo(\n () =>\n getCommentCreateCommentData(\n commentCid,\n community,\n communitiesPagesComment,\n repliesPagesComment,\n ),\n [\n commentCid,\n community?.name,\n community?.publicKey,\n communitiesPagesComment?.communityName,\n communitiesPagesComment?.communityPublicKey,\n repliesPagesComment?.communityName,\n repliesPagesComment?.communityPublicKey,\n ],\n );\n const autoUpdateSubscriptionId = useRef(`useComment-${++commentAutoUpdateSubscriptionCount}`);\n const currentCommentCidRef = useRef<string | undefined>(commentCid);\n currentCommentCidRef.current = commentCid;\n const [frozenComment, setFrozenComment] = useState<Comment | undefined>();\n const [freezeSettledCid, setFreezeSettledCid] = useState<string>();\n\n useEffect(() => {\n if (!commentCid || !account) {\n return;\n }\n validator.validateUseCommentArguments(commentCid, account);\n if (!commentFromStore && !onlyIfCached) {\n // if comment isn't already in store, add it\n const addCommentPromise = createCommentData\n ? addCommentToStore(commentCid, account, createCommentData)\n : addCommentToStore(commentCid, account);\n addCommentPromise.catch((error: unknown) =>\n log.error(\"useComment addCommentToStore error\", { commentCid, error }),\n );\n }\n }, [commentCid, account?.id, onlyIfCached, createCommentData]);\n\n useEffect(() => {\n if (!commentCid || !account || onlyIfCached || !autoUpdate) {\n return;\n }\n\n const startAutoUpdatePromise = createCommentData\n ? startCommentAutoUpdate(\n commentCid,\n autoUpdateSubscriptionId.current,\n account,\n createCommentData,\n )\n : startCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current, account);\n startAutoUpdatePromise.catch((error: unknown) =>\n log.error(\"useComment startCommentAutoUpdate error\", { commentCid, error }),\n );\n\n return () => {\n stopCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current).catch((error: unknown) =>\n log.error(\"useComment stopCommentAutoUpdate error\", { commentCid, error }),\n );\n };\n }, [commentCid, account?.id, onlyIfCached, autoUpdate, createCommentData]);\n\n let selectedComment = commentFromStore;\n\n if (commentCid && communitiesPagesComment) {\n selectedComment = preferFresher(selectedComment, communitiesPagesComment);\n }\n if (commentCid && repliesPagesComment) {\n selectedComment = preferFresher(selectedComment, repliesPagesComment);\n }\n\n // if comment is still not defined, but account comment is, use account comment\n // check `comment.timestamp` instead of `comment` in case comment exists but in a loading state\n const commentFromStoreNotLoaded = !selectedComment?.timestamp;\n if (commentCid && commentFromStoreNotLoaded && accountComment) {\n selectedComment = accountComment;\n }\n\n const selectedCommentState = getCommentStateAndReplyCount(selectedComment).state;\n const freezeSettledForCurrentCid = freezeSettledCid === commentCid;\n\n useEffect(() => {\n if (autoUpdate) {\n setFrozenComment(undefined);\n setFreezeSettledCid(undefined);\n return;\n }\n\n setFrozenComment(undefined);\n setFreezeSettledCid(undefined);\n }, [commentCid, autoUpdate]);\n\n useEffect(() => {\n if (autoUpdate) {\n return;\n }\n if (!commentCid) {\n setFrozenComment(undefined);\n setFreezeSettledCid(undefined);\n return;\n }\n if (freezeSettledForCurrentCid || !selectedComment) {\n return;\n }\n\n setFrozenComment(selectedComment);\n if (selectedCommentState === \"succeeded\") {\n setFreezeSettledCid(commentCid);\n }\n }, [autoUpdate, commentCid, selectedComment, selectedCommentState, freezeSettledForCurrentCid]);\n\n const frozenCommentForCurrentCid = frozenComment?.cid === commentCid ? frozenComment : undefined;\n let comment = autoUpdate\n ? selectedComment\n : freezeSettledForCurrentCid\n ? frozenCommentForCurrentCid\n : frozenCommentForCurrentCid || selectedComment;\n comment = addCommentModeration(comment);\n\n const { state, replyCount } = getCommentStateAndReplyCount(comment);\n\n if (account && commentCid) {\n log(\"useComment\", {\n commentCid,\n comment,\n replyCount,\n state,\n commentFromStore,\n communitiesPagesComment,\n repliesPagesComment,\n accountComment,\n commentsStore: useCommentsStore.getState().comments,\n account,\n onlyIfCached,\n autoUpdate,\n });\n }\n\n const refresh = useCallback(async () => {\n if (!commentCid || !account) {\n throw Error(\"useComment cannot refresh comment not initialized yet\");\n }\n\n const refreshCommentCid = commentCid;\n const refreshedComment = createCommentData\n ? await refreshCommentInStore(refreshCommentCid, account, createCommentData)\n : await refreshCommentInStore(refreshCommentCid, account);\n if (!autoUpdate && refreshedComment && currentCommentCidRef.current === refreshCommentCid) {\n setFrozenComment(refreshedComment);\n setFreezeSettledCid(refreshCommentCid);\n }\n }, [account, autoUpdate, commentCid, createCommentData, refreshCommentInStore]);\n\n return useMemo(\n () => ({\n ...comment,\n replyCount,\n state,\n refresh,\n error: errors?.[errors.length - 1],\n errors: errors || [],\n }),\n [comment, commentCid, errors, refresh, state, replyCount],\n );\n}\n\n/**\n * @param commentCids - The IPFS CIDs of the comments to get\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useComments(options?: UseCommentsOptions): UseCommentsResult {\n assert(\n !options || typeof options === \"object\",\n `useComments options argument '${options}' not an object`,\n );\n const { commentCids = [], accountName, onlyIfCached, autoUpdate = true } = options ?? {};\n const account = useAccount({ accountName });\n const commentsStoreComments: (Comment | undefined)[] = useCommentsStore(\n (state: any) => commentCids.map((commentCid) => state.comments[commentCid || \"\"]),\n shallow,\n );\n const communitiesPagesComments: (Comment | undefined)[] = useCommunitiesPagesStore(\n (state: any) => commentCids.map((commentCid) => state.comments[commentCid || \"\"]),\n shallow,\n );\n\n const addCommentToStore = useCommentsStore((state: any) => state.addCommentToStore);\n const startCommentAutoUpdate = useCommentsStore((state: any) => state.startCommentAutoUpdate);\n const stopCommentAutoUpdate = useCommentsStore((state: any) => state.stopCommentAutoUpdate);\n const refreshCommentInStore = useCommentsStore((state: any) => state.refreshComment);\n const autoUpdateSubscriptionId = useRef(`useComments-${++commentsAutoUpdateSubscriptionCount}`);\n const commentCidsKey = JSON.stringify(commentCids);\n const commentsKey = `${account?.id || \"\"}:${commentCidsKey}`;\n const currentCommentsKeyRef = useRef(commentsKey);\n currentCommentsKeyRef.current = commentsKey;\n const [frozenComments, setFrozenComments] = useState<(Comment | undefined)[]>([]);\n const [frozenCommentsKey, setFrozenCommentsKey] = useState<string>();\n const [freezeSettledKey, setFreezeSettledKey] = useState<string>();\n\n useEffect(() => {\n if (!commentCids || !account) {\n return;\n }\n validator.validateUseCommentsArguments(commentCids, account);\n if (onlyIfCached) {\n return;\n }\n const uniqueCommentCids = new Set(commentCids);\n for (const commentCid of uniqueCommentCids) {\n addCommentToStore(commentCid, account).catch((error: unknown) =>\n log.error(\"useComments addCommentToStore error\", { commentCid, error }),\n );\n }\n }, [commentCidsKey, account?.id, onlyIfCached]);\n\n useEffect(() => {\n if (!commentCids || !account || onlyIfCached || !autoUpdate) {\n return;\n }\n\n const uniqueCommentCids = [...new Set(commentCids)];\n for (const commentCid of uniqueCommentCids) {\n startCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current, account).catch(\n (error: unknown) =>\n log.error(\"useComments startCommentAutoUpdate error\", { commentCid, error }),\n );\n }\n\n return () => {\n for (const commentCid of uniqueCommentCids) {\n stopCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current).catch(\n (error: unknown) =>\n log.error(\"useComments stopCommentAutoUpdate error\", { commentCid, error }),\n );\n }\n };\n }, [commentCidsKey, account?.id, onlyIfCached, autoUpdate]);\n\n if (account && commentCids?.length) {\n log(\"useComments\", {\n commentCids,\n commentsStoreComments,\n commentsStore: useCommentsStore.getState().comments,\n account,\n });\n }\n\n // if comment from community pages exists and is fresher (or current missing), use it instead\n const liveComments = useMemo(() => {\n const result = [...commentsStoreComments];\n for (const i in result) {\n const candidate = communitiesPagesComments[i];\n if (candidate) result[i] = preferFresher(result[i], candidate);\n }\n return result;\n }, [commentsStoreComments, communitiesPagesComments]);\n\n const liveCommentsSettled = liveComments.every(\n (comment) => getCommentStateAndReplyCount(comment).state === \"succeeded\",\n );\n const freezeSettledForCurrentKey = freezeSettledKey === commentsKey;\n\n useEffect(() => {\n if (autoUpdate) {\n setFrozenComments([]);\n setFrozenCommentsKey(undefined);\n setFreezeSettledKey(undefined);\n return;\n }\n\n setFrozenComments([]);\n setFrozenCommentsKey(undefined);\n setFreezeSettledKey(undefined);\n }, [commentsKey, autoUpdate]);\n\n useEffect(() => {\n if (autoUpdate || freezeSettledForCurrentKey) {\n return;\n }\n\n setFrozenComments(liveComments);\n setFrozenCommentsKey(commentsKey);\n if (liveCommentsSettled) {\n setFreezeSettledKey(commentsKey);\n }\n }, [autoUpdate, commentsKey, freezeSettledForCurrentKey, liveComments, liveCommentsSettled]);\n\n const frozenCommentsForCurrentSelection =\n frozenCommentsKey === commentsKey ? frozenComments : undefined;\n const comments = autoUpdate ? liveComments : frozenCommentsForCurrentSelection || liveComments;\n const normalizedComments = useMemo(() => addCommentModerationToComments(comments), [comments]);\n\n // succeed if no comments are undefined\n const state = getCommentsState(normalizedComments);\n\n const refresh = useCallback(async () => {\n if (!account) {\n throw Error(\"useComments cannot refresh comments not initialized yet\");\n }\n const uniqueCommentCids = [...new Set(commentCids)];\n const refreshedComments = await Promise.all(\n uniqueCommentCids.map((commentCid) => refreshCommentInStore(commentCid, account)),\n );\n\n if (!autoUpdate && currentCommentsKeyRef.current === commentsKey) {\n const latestCommunitiesPagesComments = useCommunitiesPagesStore.getState().comments;\n const refreshedCommentsByCid = uniqueCommentCids.reduce(\n (\n refreshedCommentsMap: { [commentCid: string]: Comment | undefined },\n commentCid,\n index,\n ) => {\n refreshedCommentsMap[commentCid] = refreshedComments[index];\n return refreshedCommentsMap;\n },\n {},\n );\n setFrozenComments(\n commentCids.map((commentCid) =>\n preferFresher(\n refreshedCommentsByCid[commentCid || \"\"],\n latestCommunitiesPagesComments[commentCid || \"\"],\n ),\n ),\n );\n setFrozenCommentsKey(commentsKey);\n setFreezeSettledKey(commentsKey);\n }\n }, [account, autoUpdate, commentCids, commentsKey, refreshCommentInStore]);\n\n return useMemo(\n () => ({\n comments: normalizedComments,\n state,\n refresh,\n error: undefined,\n errors: [],\n }),\n [normalizedComments, commentsKey, refresh, state],\n );\n}\n\nexport function useValidateComment(options?: UseValidateCommentOptions): UseValidateCommentResult {\n assert(\n !options || typeof options === \"object\",\n `useValidateComment options argument '${options}' not an object`,\n );\n let { comment, validateReplies, accountName } = options ?? {};\n validateReplies = validateReplies ?? true;\n const [validated, setValidated] = useState<boolean | undefined>();\n const [errors] = useState([]);\n const account = useAccount({ accountName });\n\n useEffect(() => {\n if (!comment || !account?.pkc) {\n setValidated(undefined);\n return;\n }\n // don't automatically block community because what community it comes from\n // a malicious community could try to block other communities, etc\n const blockCommunity = false;\n commentIsValid(comment, { validateReplies, blockCommunity }, account.pkc).then((validated) =>\n setValidated(validated),\n );\n }, [comment, validateReplies, account?.pkc]);\n\n let state = \"initializing\";\n if (validated === true) {\n state = \"succeeded\";\n }\n if (validated === false) {\n state = \"failed\";\n }\n\n // start valid at true always because most of the time the value will be true and we dont want to cause a rerender\n let valid = true;\n if (validated == false) {\n valid = false;\n }\n // if comment isn't defined, it would be confusing for valid to be true\n if (!comment) {\n valid = false;\n }\n\n return useMemo(\n () => ({\n valid,\n state,\n error: errors[errors.length - 1],\n errors,\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,WAAW,CAAC;IACtB,CAAC;IACD,IAAI,SAAS,KAAK,KAAK,EAAE,CAAC;QACxB,KAAK,GAAG,QAAQ,CAAC;IACnB,CAAC;IAED,kHAAkH;IAClH,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,IAAI,SAAS,IAAI,KAAK,EAAE,CAAC;QACvB,KAAK,GAAG,KAAK,CAAC;IAChB,CAAC;IACD,uEAAuE;IACvE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,KAAK,GAAG,KAAK,CAAC;IAChB,CAAC;IAED,OAAO,OAAO,CACZ,GAAG,EAAE,CAAC,CAAC;QACL,KAAK;QACL,KAAK;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QAChC,MAAM;KACP,CAAC,EACF,CAAC,KAAK,EAAE,KAAK,CAAC,CACf,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useAccount } from \"./accounts\";\nimport validator from \"../lib/validator\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:comments:hooks\");\nimport assert from \"assert\";\nimport {\n Comment,\n UseCommentsOptions,\n UseCommentsResult,\n UseCommentOptions,\n UseCommentResult,\n UseValidateCommentOptions,\n UseValidateCommentResult,\n} from \"../types\";\nimport useCommentsStore from \"../stores/comments\";\nimport useAccountsStore from \"../stores/accounts\";\nimport { commentIsValid } from \"../lib/utils\";\nimport {\n addCommentModeration,\n addCommentModerationToComments,\n} from \"../lib/utils/comment-moderation\";\nimport useCommunitiesPagesStore from \"../stores/communities-pages\";\nimport useRepliesPagesStore from \"../stores/replies-pages\";\nimport shallow from \"zustand/shallow\";\nimport { assertCommunityRef } from \"../lib/community-ref\";\nimport {\n addOptimisticVoteCounts,\n addOptimisticVoteCountsToComments,\n} from \"../lib/utils/optimistic-vote-counts\";\n\nexport function getCommentFreshness(comment: Comment | undefined): number {\n if (!comment) return 0;\n return Math.max(comment.updatedAt ?? 0, comment.timestamp ?? 0, 0);\n}\n\nexport function preferFresher(\n current: Comment | undefined,\n candidate: Comment | undefined,\n): Comment | undefined {\n if (!candidate) return current;\n if (!current) return candidate;\n return getCommentFreshness(candidate) > getCommentFreshness(current) ? candidate : current;\n}\n\nconst getCommentStateAndReplyCount = (comment: Comment | undefined) => {\n let state = comment?.updatingState || \"initializing\";\n // force 'fetching-ipns' even if could be something else, so the frontend can use\n // the correct loading skeleton\n if (comment?.timestamp) {\n state = \"fetching-update-ipns\";\n }\n // force succeeded even if the comment is fecthing a new update\n if (comment?.updatedAt) {\n state = \"succeeded\";\n }\n\n // force succeeded if the comment is newer than 5 minutes, no need to display loading skeleton if comment was just created\n let replyCount = comment?.replyCount;\n if (\n comment?.replyCount === undefined &&\n comment?.timestamp &&\n comment?.timestamp > Date.now() / 1000 - 5 * 60\n ) {\n state = \"succeeded\";\n // set replyCount because some frontend are likely to check if replyCount === undefined to show a loading skeleton\n replyCount = 0;\n }\n\n return { state, replyCount };\n};\n\nconst getCommentsState = (comments: (Comment | undefined)[]) =>\n comments.every((comment) => getCommentStateAndReplyCount(comment).state === \"succeeded\")\n ? \"succeeded\"\n : \"fetching-ipfs\";\n\nlet commentAutoUpdateSubscriptionCount = 0;\nlet commentsAutoUpdateSubscriptionCount = 0;\n\nconst getCommentCreateCommentData = (\n commentCid: string | undefined,\n community: UseCommentOptions[\"community\"] | undefined,\n ...comments: (Comment | undefined)[]\n) => {\n if (!commentCid) {\n return undefined;\n }\n\n const createCommentData: Comment = { cid: commentCid };\n let hasCommunityData = false;\n for (const comment of comments) {\n if (!comment) {\n continue;\n }\n if (!createCommentData.communityPublicKey && comment.communityPublicKey) {\n createCommentData.communityPublicKey = comment.communityPublicKey;\n hasCommunityData = true;\n }\n if (!createCommentData.communityName && comment.communityName) {\n createCommentData.communityName = comment.communityName;\n hasCommunityData = true;\n }\n }\n\n if (community?.publicKey) {\n createCommentData.communityPublicKey = community.publicKey;\n hasCommunityData = true;\n }\n if (community?.name) {\n createCommentData.communityName = community.name;\n hasCommunityData = true;\n }\n\n return hasCommunityData ? createCommentData : undefined;\n};\n\n/**\n * @param commentCid - The IPFS CID of the comment to get\n * @param community - The community identifier, e.g. {name: 'memes.eth', publicKey: '12D3KooW...'}.\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useComment(options?: UseCommentOptions): UseCommentResult {\n assert(\n !options || typeof options === \"object\",\n `useComment options argument '${options}' not an object`,\n );\n const { commentCid, community, accountName, onlyIfCached, autoUpdate = true } = options ?? {};\n if (community !== undefined) {\n assertCommunityRef(community, \"useComment community\");\n }\n const account = useAccount({ accountName });\n const commentFromStore = useCommentsStore((state: any) => state.comments[commentCid || \"\"]);\n const addCommentToStore = useCommentsStore((state: any) => state.addCommentToStore);\n const startCommentAutoUpdate = useCommentsStore((state: any) => state.startCommentAutoUpdate);\n const stopCommentAutoUpdate = useCommentsStore((state: any) => state.stopCommentAutoUpdate);\n const refreshCommentInStore = useCommentsStore((state: any) => state.refreshComment);\n const communitiesPagesComment = useCommunitiesPagesStore(\n (state: any) => state.comments[commentCid || \"\"],\n );\n const repliesPagesComment = useRepliesPagesStore(\n (state: any) => state.comments[commentCid || \"\"],\n );\n const errors = useCommentsStore((state: any) => state.errors[commentCid || \"\"]);\n\n // get account comment of the cid if any\n const accountCommentInfo = useAccountsStore(\n (state: any) => state.commentCidsToAccountsComments[commentCid || \"\"],\n );\n const accountComment = useAccountsStore(\n (state: any) =>\n state.accountsComments[accountCommentInfo?.accountId || \"\"]?.[\n Number(accountCommentInfo?.accountCommentIndex)\n ],\n );\n const accountVote = useAccountsStore((state: any) =>\n account?.id && commentCid ? state.accountsVotes[account.id]?.[commentCid] : undefined,\n );\n const createCommentData = useMemo(\n () =>\n getCommentCreateCommentData(\n commentCid,\n community,\n communitiesPagesComment,\n repliesPagesComment,\n ),\n [\n commentCid,\n community?.name,\n community?.publicKey,\n communitiesPagesComment?.communityName,\n communitiesPagesComment?.communityPublicKey,\n repliesPagesComment?.communityName,\n repliesPagesComment?.communityPublicKey,\n ],\n );\n const autoUpdateSubscriptionId = useRef(`useComment-${++commentAutoUpdateSubscriptionCount}`);\n const currentCommentCidRef = useRef<string | undefined>(commentCid);\n currentCommentCidRef.current = commentCid;\n const [frozenComment, setFrozenComment] = useState<Comment | undefined>();\n const [freezeSettledCid, setFreezeSettledCid] = useState<string>();\n\n useEffect(() => {\n if (!commentCid || !account) {\n return;\n }\n validator.validateUseCommentArguments(commentCid, account);\n if (!commentFromStore && !onlyIfCached) {\n // if comment isn't already in store, add it\n const addCommentPromise = createCommentData\n ? addCommentToStore(commentCid, account, createCommentData)\n : addCommentToStore(commentCid, account);\n addCommentPromise.catch((error: unknown) =>\n log.error(\"useComment addCommentToStore error\", { commentCid, error }),\n );\n }\n }, [commentCid, account?.id, onlyIfCached, createCommentData]);\n\n useEffect(() => {\n if (!commentCid || !account || onlyIfCached || !autoUpdate) {\n return;\n }\n\n const startAutoUpdatePromise = createCommentData\n ? startCommentAutoUpdate(\n commentCid,\n autoUpdateSubscriptionId.current,\n account,\n createCommentData,\n )\n : startCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current, account);\n startAutoUpdatePromise.catch((error: unknown) =>\n log.error(\"useComment startCommentAutoUpdate error\", { commentCid, error }),\n );\n\n return () => {\n stopCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current).catch((error: unknown) =>\n log.error(\"useComment stopCommentAutoUpdate error\", { commentCid, error }),\n );\n };\n }, [commentCid, account?.id, onlyIfCached, autoUpdate, createCommentData]);\n\n let selectedComment = commentFromStore;\n\n if (commentCid && communitiesPagesComment) {\n selectedComment = preferFresher(selectedComment, communitiesPagesComment);\n }\n if (commentCid && repliesPagesComment) {\n selectedComment = preferFresher(selectedComment, repliesPagesComment);\n }\n\n // if comment is still not defined, but account comment is, use account comment\n // check `comment.timestamp` instead of `comment` in case comment exists but in a loading state\n const commentFromStoreNotLoaded = !selectedComment?.timestamp;\n if (commentCid && commentFromStoreNotLoaded && accountComment) {\n selectedComment = accountComment;\n }\n\n const selectedCommentState = getCommentStateAndReplyCount(selectedComment).state;\n const freezeSettledForCurrentCid = freezeSettledCid === commentCid;\n\n useEffect(() => {\n if (autoUpdate) {\n setFrozenComment(undefined);\n setFreezeSettledCid(undefined);\n return;\n }\n\n setFrozenComment(undefined);\n setFreezeSettledCid(undefined);\n }, [commentCid, autoUpdate]);\n\n useEffect(() => {\n if (autoUpdate) {\n return;\n }\n if (!commentCid) {\n setFrozenComment(undefined);\n setFreezeSettledCid(undefined);\n return;\n }\n if (freezeSettledForCurrentCid || !selectedComment) {\n return;\n }\n\n setFrozenComment(selectedComment);\n if (selectedCommentState === \"succeeded\") {\n setFreezeSettledCid(commentCid);\n }\n }, [autoUpdate, commentCid, selectedComment, selectedCommentState, freezeSettledForCurrentCid]);\n\n const frozenCommentForCurrentCid = frozenComment?.cid === commentCid ? frozenComment : undefined;\n let comment = autoUpdate\n ? selectedComment\n : freezeSettledForCurrentCid\n ? frozenCommentForCurrentCid\n : frozenCommentForCurrentCid || selectedComment;\n comment = addCommentModeration(comment);\n comment = addOptimisticVoteCounts(comment, accountVote);\n\n const { state, replyCount } = getCommentStateAndReplyCount(comment);\n\n if (account && commentCid) {\n log(\"useComment\", {\n commentCid,\n comment,\n replyCount,\n state,\n commentFromStore,\n communitiesPagesComment,\n repliesPagesComment,\n accountComment,\n commentsStore: useCommentsStore.getState().comments,\n account,\n onlyIfCached,\n autoUpdate,\n });\n }\n\n const refresh = useCallback(async () => {\n if (!commentCid || !account) {\n throw Error(\"useComment cannot refresh comment not initialized yet\");\n }\n\n const refreshCommentCid = commentCid;\n const refreshedComment = createCommentData\n ? await refreshCommentInStore(refreshCommentCid, account, createCommentData)\n : await refreshCommentInStore(refreshCommentCid, account);\n if (!autoUpdate && refreshedComment && currentCommentCidRef.current === refreshCommentCid) {\n setFrozenComment(refreshedComment);\n setFreezeSettledCid(refreshCommentCid);\n }\n }, [account, autoUpdate, commentCid, createCommentData, refreshCommentInStore]);\n\n return useMemo(\n () => ({\n ...comment,\n replyCount,\n state,\n refresh,\n error: errors?.[errors.length - 1],\n errors: errors || [],\n }),\n [comment, commentCid, errors, refresh, state, replyCount],\n );\n}\n\n/**\n * @param commentCids - The IPFS CIDs of the comments to get\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useComments(options?: UseCommentsOptions): UseCommentsResult {\n assert(\n !options || typeof options === \"object\",\n `useComments options argument '${options}' not an object`,\n );\n const { commentCids = [], accountName, onlyIfCached, autoUpdate = true } = options ?? {};\n const account = useAccount({ accountName });\n const accountVotes = useAccountsStore((state: any) =>\n account?.id ? state.accountsVotes[account.id] : undefined,\n );\n const commentsStoreComments: (Comment | undefined)[] = useCommentsStore(\n (state: any) => commentCids.map((commentCid) => state.comments[commentCid || \"\"]),\n shallow,\n );\n const communitiesPagesComments: (Comment | undefined)[] = useCommunitiesPagesStore(\n (state: any) => commentCids.map((commentCid) => state.comments[commentCid || \"\"]),\n shallow,\n );\n\n const addCommentToStore = useCommentsStore((state: any) => state.addCommentToStore);\n const startCommentAutoUpdate = useCommentsStore((state: any) => state.startCommentAutoUpdate);\n const stopCommentAutoUpdate = useCommentsStore((state: any) => state.stopCommentAutoUpdate);\n const refreshCommentInStore = useCommentsStore((state: any) => state.refreshComment);\n const autoUpdateSubscriptionId = useRef(`useComments-${++commentsAutoUpdateSubscriptionCount}`);\n const commentCidsKey = JSON.stringify(commentCids);\n const commentsKey = `${account?.id || \"\"}:${commentCidsKey}`;\n const currentCommentsKeyRef = useRef(commentsKey);\n currentCommentsKeyRef.current = commentsKey;\n const [frozenComments, setFrozenComments] = useState<(Comment | undefined)[]>([]);\n const [frozenCommentsKey, setFrozenCommentsKey] = useState<string>();\n const [freezeSettledKey, setFreezeSettledKey] = useState<string>();\n\n useEffect(() => {\n if (!commentCids || !account) {\n return;\n }\n validator.validateUseCommentsArguments(commentCids, account);\n if (onlyIfCached) {\n return;\n }\n const uniqueCommentCids = new Set(commentCids);\n for (const commentCid of uniqueCommentCids) {\n addCommentToStore(commentCid, account).catch((error: unknown) =>\n log.error(\"useComments addCommentToStore error\", { commentCid, error }),\n );\n }\n }, [commentCidsKey, account?.id, onlyIfCached]);\n\n useEffect(() => {\n if (!commentCids || !account || onlyIfCached || !autoUpdate) {\n return;\n }\n\n const uniqueCommentCids = [...new Set(commentCids)];\n for (const commentCid of uniqueCommentCids) {\n startCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current, account).catch(\n (error: unknown) =>\n log.error(\"useComments startCommentAutoUpdate error\", { commentCid, error }),\n );\n }\n\n return () => {\n for (const commentCid of uniqueCommentCids) {\n stopCommentAutoUpdate(commentCid, autoUpdateSubscriptionId.current).catch(\n (error: unknown) =>\n log.error(\"useComments stopCommentAutoUpdate error\", { commentCid, error }),\n );\n }\n };\n }, [commentCidsKey, account?.id, onlyIfCached, autoUpdate]);\n\n if (account && commentCids?.length) {\n log(\"useComments\", {\n commentCids,\n commentsStoreComments,\n commentsStore: useCommentsStore.getState().comments,\n account,\n });\n }\n\n // if comment from community pages exists and is fresher (or current missing), use it instead\n const liveComments = useMemo(() => {\n const result = [...commentsStoreComments];\n for (const i in result) {\n const candidate = communitiesPagesComments[i];\n if (candidate) result[i] = preferFresher(result[i], candidate);\n }\n return result;\n }, [commentsStoreComments, communitiesPagesComments]);\n\n const liveCommentsSettled = liveComments.every(\n (comment) => getCommentStateAndReplyCount(comment).state === \"succeeded\",\n );\n const freezeSettledForCurrentKey = freezeSettledKey === commentsKey;\n\n useEffect(() => {\n if (autoUpdate) {\n setFrozenComments([]);\n setFrozenCommentsKey(undefined);\n setFreezeSettledKey(undefined);\n return;\n }\n\n setFrozenComments([]);\n setFrozenCommentsKey(undefined);\n setFreezeSettledKey(undefined);\n }, [commentsKey, autoUpdate]);\n\n useEffect(() => {\n if (autoUpdate || freezeSettledForCurrentKey) {\n return;\n }\n\n setFrozenComments(liveComments);\n setFrozenCommentsKey(commentsKey);\n if (liveCommentsSettled) {\n setFreezeSettledKey(commentsKey);\n }\n }, [autoUpdate, commentsKey, freezeSettledForCurrentKey, liveComments, liveCommentsSettled]);\n\n const frozenCommentsForCurrentSelection =\n frozenCommentsKey === commentsKey ? frozenComments : undefined;\n const comments = autoUpdate ? liveComments : frozenCommentsForCurrentSelection || liveComments;\n const normalizedComments = useMemo(\n () => addOptimisticVoteCountsToComments(addCommentModerationToComments(comments), accountVotes),\n [comments, accountVotes],\n );\n\n // succeed if no comments are undefined\n const state = getCommentsState(normalizedComments);\n\n const refresh = useCallback(async () => {\n if (!account) {\n throw Error(\"useComments cannot refresh comments not initialized yet\");\n }\n const uniqueCommentCids = [...new Set(commentCids)];\n const refreshedComments = await Promise.all(\n uniqueCommentCids.map((commentCid) => refreshCommentInStore(commentCid, account)),\n );\n\n if (!autoUpdate && currentCommentsKeyRef.current === commentsKey) {\n const latestCommunitiesPagesComments = useCommunitiesPagesStore.getState().comments;\n const refreshedCommentsByCid = uniqueCommentCids.reduce(\n (\n refreshedCommentsMap: { [commentCid: string]: Comment | undefined },\n commentCid,\n index,\n ) => {\n refreshedCommentsMap[commentCid] = refreshedComments[index];\n return refreshedCommentsMap;\n },\n {},\n );\n setFrozenComments(\n commentCids.map((commentCid) =>\n preferFresher(\n refreshedCommentsByCid[commentCid || \"\"],\n latestCommunitiesPagesComments[commentCid || \"\"],\n ),\n ),\n );\n setFrozenCommentsKey(commentsKey);\n setFreezeSettledKey(commentsKey);\n }\n }, [account, autoUpdate, commentCids, commentsKey, refreshCommentInStore]);\n\n return useMemo(\n () => ({\n comments: normalizedComments,\n state,\n refresh,\n error: undefined,\n errors: [],\n }),\n [normalizedComments, commentsKey, refresh, state],\n );\n}\n\nexport function useValidateComment(options?: UseValidateCommentOptions): UseValidateCommentResult {\n assert(\n !options || typeof options === \"object\",\n `useValidateComment options argument '${options}' not an object`,\n );\n let { comment, validateReplies, accountName } = options ?? {};\n validateReplies = validateReplies ?? true;\n const [validated, setValidated] = useState<boolean | undefined>();\n const [errors] = useState([]);\n const account = useAccount({ accountName });\n\n useEffect(() => {\n if (!comment || !account?.pkc) {\n setValidated(undefined);\n return;\n }\n // don't automatically block community because what community it comes from\n // a malicious community could try to block other communities, etc\n const blockCommunity = false;\n commentIsValid(comment, { validateReplies, blockCommunity }, account.pkc).then((validated) =>\n setValidated(validated),\n );\n }, [comment, validateReplies, account?.pkc]);\n\n let state = \"initializing\";\n if (validated === true) {\n state = \"succeeded\";\n }\n if (validated === false) {\n state = \"failed\";\n }\n\n // start valid at true always because most of the time the value will be true and we dont want to cause a rerender\n let valid = true;\n if (validated == false) {\n valid = false;\n }\n // if comment isn't defined, it would be confusing for valid to be true\n if (!comment) {\n valid = false;\n }\n\n return useMemo(\n () => ({\n valid,\n state,\n error: errors[errors.length - 1],\n errors,\n }),\n [valid, state],\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"communities.d.ts","sourceRoot":"","sources":["../../src/hooks/communities.ts"],"names":[],"mappings":"AAMA,OAAO,EAGL,cAAc,EACd,kCAAkC,EAClC,iCAAiC,EACjC,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,wBAAwB,EACxB,uBAAuB,EACxB,MAAM,UAAU,CAAC;AAyClB;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,kBAAkB,CAgH9E;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE,wBAAwB,GAAG,uBAAuB,CAyF7F;AAeD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,oBAAoB,CA2EpF;AAGD;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,CAAC,EAAE,MAAM,YAqBtD;AAED;;;;GAIG;AAEH,wBAAgB,2BAA2B,CACzC,OAAO,CAAC,EAAE,kCAAkC,GAC3C,iCAAiC,CAgGnC;AAGD,eAAO,MAAM,uBAAuB,GAClC,kBAAkB,MAAM,EACxB,gBAAgB,cAAc,iBAe/B,CAAC"}
1
+ {"version":3,"file":"communities.d.ts","sourceRoot":"","sources":["../../src/hooks/communities.ts"],"names":[],"mappings":"AAMA,OAAO,EAGL,cAAc,EACd,kCAAkC,EAClC,iCAAiC,EACjC,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,wBAAwB,EACxB,uBAAuB,EACxB,MAAM,UAAU,CAAC;AAyClB;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,kBAAkB,CAqH9E;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE,wBAAwB,GAAG,uBAAuB,CAyF7F;AAeD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,oBAAoB,CA2EpF;AAGD;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,CAAC,EAAE,MAAM,YAqBtD;AAED;;;;GAIG;AAEH,wBAAgB,2BAA2B,CACzC,OAAO,CAAC,EAAE,kCAAkC,GAC3C,iCAAiC,CAgGnC;AAGD,eAAO,MAAM,uBAAuB,GAClC,kBAAkB,MAAM,EACxB,gBAAgB,cAAc,iBAe/B,CAAC"}
@@ -66,6 +66,7 @@ export function useCommunity(options) {
66
66
  const storedCommunity = useCommunitiesStore((state) => state.communities[communityKey]);
67
67
  const addCommunityToStore = useCommunitiesStore((state) => state.addCommunityToStore);
68
68
  const errors = useCommunitiesStore((state) => state.errors[communityKey]);
69
+ const syncStatus = useCommunitiesStore((state) => state.syncStatuses[communityKey]);
69
70
  const communityEditSummary = useAccountsStore((state) => {
70
71
  const accountEditsSummaries = state.accountsEditsSummaries[accountId] || {};
71
72
  const candidateCommunityKeys = [
@@ -129,7 +130,7 @@ export function useCommunity(options) {
129
130
  if (mergedCommunity === null || mergedCommunity === void 0 ? void 0 : mergedCommunity.updatedAt) {
130
131
  state = "succeeded";
131
132
  }
132
- return useMemo(() => (Object.assign(Object.assign({}, mergedCommunity), { state, error: errors === null || errors === void 0 ? void 0 : errors[errors.length - 1], errors: errors || [] })), [mergedCommunity, communityKey, errors]);
133
+ return useMemo(() => (Object.assign(Object.assign({}, mergedCommunity), { state, syncState: (syncStatus === null || syncStatus === void 0 ? void 0 : syncStatus.syncState) || (onlyIfCached ? "stopped" : "initializing"), hasCachedData: typeof (mergedCommunity === null || mergedCommunity === void 0 ? void 0 : mergedCommunity.updatedAt) === "number", lastFetchAttemptAt: syncStatus === null || syncStatus === void 0 ? void 0 : syncStatus.lastFetchAttemptAt, lastSuccessfulFetchAt: syncStatus === null || syncStatus === void 0 ? void 0 : syncStatus.lastSuccessfulFetchAt, error: errors === null || errors === void 0 ? void 0 : errors[errors.length - 1], errors: errors || [] })), [mergedCommunity, communityKey, errors, onlyIfCached, syncStatus]);
133
134
  }
134
135
  /**
135
136
  * @param community - The community identifier, e.g. {name: 'memes.eth'} or {publicKey: '12D3KooW...'}
@@ -1 +1 @@
1
- {"version":3,"file":"communities.js","sourceRoot":"","sources":["../../src/hooks/communities.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,SAAS,MAAM,kBAAkB,CAAC;AACzC,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,yCAAyC,CAAC,CAAC;AAC9D,OAAO,MAAM,MAAM,QAAQ,CAAC;AAc5B,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAC/C,OAAO,WAAW,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,mBAAmB,MAAM,uBAAuB,CAA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cAAc,aAAd,cAAc,uBAAd,cAAc,CAAG,KAAK,CAAC,0CAAE,IAAI,0CAAG,CAAC,CAAC,EAClC,MAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAG,KAAK,CAAC,0CAAE,OAAO,CACjC,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,CAAC,qDAAqD,gBAAgB,GAAG,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,wBAAwB,CAAC;AAClC,CAAC,CAAA,CAAC","sourcesContent":["import { useEffect, useState, useMemo } from \"react\";\nimport { useAccount } from \"./accounts\";\nimport validator from \"../lib/validator\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:communities:hooks\");\nimport assert from \"assert\";\nimport {\n Community,\n CommunityStats,\n ChainProviders,\n UseResolvedCommunityAddressOptions,\n UseResolvedCommunityAddressResult,\n UseCommunityOptions,\n UseCommunityResult,\n UseCommunitiesOptions,\n UseCommunitiesResult,\n UseCommunityStatsOptions,\n UseCommunityStatsResult,\n} from \"../types\";\nimport useInterval from \"./utils/use-interval\";\nimport createStore from \"zustand\";\nimport { resolveEnsTxtRecord } from \"../lib/chain\";\nimport useCommunitiesStore from \"../stores/communities\";\nimport useAccountsStore from \"../stores/accounts\";\nimport shallow from \"zustand/shallow\";\nimport { getChainProviders, getPkcCommunityAddresses } from \"../lib/pkc-compat\";\nimport { getCommunityRefKey, getUniqueSortedCommunityRefs } from \"../lib/community-ref\";\n\nconst parseMaybeJson = (value: unknown) => (typeof value === \"string\" ? JSON.parse(value) : value);\n\nconst tryParseMaybeJson = (value: unknown) => {\n try {\n return parseMaybeJson(value);\n } catch {\n return value;\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\";\n\nconst isCommunityStatsPayload = (value: unknown): value is CommunityStats =>\n isRecord(value) &&\n (\"hourActiveUserCount\" in value || \"weekActiveUserCount\" in value || \"allPostCount\" in value);\n\nconst parseFetchedCommunityStats = (fetchedCid: unknown): CommunityStats => {\n const parsedCid = parseMaybeJson(fetchedCid);\n if (isCommunityStatsPayload(parsedCid)) {\n return parsedCid;\n }\n if (isRecord(parsedCid) && \"content\" in parsedCid) {\n const parsedContent = tryParseMaybeJson(parsedCid.content);\n if (isCommunityStatsPayload(parsedContent)) {\n return parsedContent;\n }\n }\n return parsedCid as CommunityStats;\n};\n\n/**\n * @param community - The community identifier, e.g. {name: 'memes.eth'} or {publicKey: '12D3KooW...'}\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useCommunity(options?: UseCommunityOptions): UseCommunityResult {\n assert(\n !options || typeof options === \"object\",\n `useCommunity options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n const { community: communityInput, accountName, onlyIfCached } = opts;\n const account = useAccount({ accountName });\n const accountId = account?.id || \"\";\n validator.validateUseCommunityArguments({\n community: communityInput,\n communityAddress: (opts as any).communityAddress,\n account,\n });\n const communityKey = communityInput ? getCommunityRefKey(communityInput) : \"\";\n const storedCommunity = useCommunitiesStore((state: any) => state.communities[communityKey]);\n const addCommunityToStore = useCommunitiesStore((state: any) => state.addCommunityToStore);\n const errors = useCommunitiesStore((state: any) => state.errors[communityKey]);\n const communityEditSummary = useAccountsStore((state: any) => {\n const accountEditsSummaries = state.accountsEditsSummaries[accountId] || {};\n const candidateCommunityKeys = [\n storedCommunity?.address,\n storedCommunity?.name,\n storedCommunity?.publicKey,\n communityInput?.name,\n communityInput?.publicKey,\n ];\n for (const candidateCommunityKey of candidateCommunityKeys) {\n if (\n typeof candidateCommunityKey === \"string\" &&\n accountEditsSummaries[candidateCommunityKey]\n ) {\n return accountEditsSummaries[candidateCommunityKey];\n }\n }\n });\n\n useEffect(() => {\n if (!communityInput || !account) {\n return;\n }\n if (!storedCommunity && !onlyIfCached) {\n // if community isn't already in store, add it\n addCommunityToStore(communityInput, account).catch((error: unknown) =>\n log.error(\"useCommunity addCommunityToStore error\", { communityInput, error }),\n );\n }\n }, [communityKey, account?.id]);\n\n if (account && communityInput) {\n log(\"useCommunity\", {\n community: communityInput,\n communityKey,\n storedCommunity,\n account,\n });\n }\n\n const mergedCommunity = useMemo(() => {\n if (!communityEditSummary) {\n return storedCommunity;\n }\n const localCommunityAddresses = getPkcCommunityAddresses(account?.pkc);\n const editedCommunityAddress = communityEditSummary.address?.value;\n const inputCommunityIdentifiers = [communityInput?.name, communityInput?.publicKey].filter(\n (communityIdentifier): communityIdentifier is string =>\n typeof communityIdentifier === \"string\",\n );\n if (\n !storedCommunity &&\n editedCommunityAddress &&\n !inputCommunityIdentifiers.some((communityIdentifier) =>\n localCommunityAddresses.includes(communityIdentifier),\n ) &&\n !localCommunityAddresses.includes(editedCommunityAddress)\n ) {\n return storedCommunity;\n }\n if (\n storedCommunity?.address &&\n editedCommunityAddress &&\n storedCommunity.address !== editedCommunityAddress\n ) {\n return storedCommunity;\n }\n const summaryValues = Object.fromEntries(\n Object.entries(communityEditSummary).map(([propertyName, propertySummary]: [string, any]) => [\n propertyName,\n propertySummary?.value,\n ]),\n );\n return {\n ...(storedCommunity || { address: communityInput?.name || communityInput?.publicKey }),\n ...summaryValues,\n };\n }, [account?.pkc, storedCommunity, communityInput, communityEditSummary]);\n\n let state = mergedCommunity?.updatingState || \"initializing\";\n // force succeeded even if the community is fecthing a new update\n if (mergedCommunity?.updatedAt) {\n state = \"succeeded\";\n }\n\n return useMemo(\n () => ({\n ...mergedCommunity,\n state,\n error: errors?.[errors.length - 1],\n errors: errors || [],\n }),\n [mergedCommunity, communityKey, errors],\n );\n}\n\n/**\n * @param community - The community identifier, e.g. {name: 'memes.eth'} or {publicKey: '12D3KooW...'}\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useCommunityStats(options?: UseCommunityStatsOptions): UseCommunityStatsResult {\n assert(\n !options || typeof options === \"object\",\n `useCommunityStats options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n const { community, accountName, onlyIfCached } = opts;\n validator.validateUseCommunityStatsArguments({\n community,\n communityAddress: (opts as any).communityAddress,\n });\n const account = useAccount({ accountName });\n const communityKey = community ? getCommunityRefKey(community) : \"\";\n const fetchedCommunity = useCommunity({ community, onlyIfCached });\n const communityStatsCid = fetchedCommunity?.statsCid;\n const communityStats = useCommunitiesStatsStore(\n (state: CommunitiesStatsState) => state.communitiesStats[communityKey],\n );\n const setCommunityStats = useCommunitiesStatsStore(\n (state: CommunitiesStatsState) => state.setCommunityStats,\n );\n const [fetchError, setFetchError] = useState<Error | undefined>();\n\n useEffect(() => {\n setFetchError(undefined);\n if (!communityKey || !communityStatsCid || !account) {\n return;\n }\n let cancelled = false;\n (async () => {\n let fetchedCid;\n try {\n fetchedCid = await account.pkc.fetchCid({ cid: communityStatsCid });\n fetchedCid = parseFetchedCommunityStats(fetchedCid);\n if (cancelled) {\n return;\n }\n setCommunityStats(communityKey, fetchedCid);\n } catch (error) {\n const normalizedError =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : \"error\");\n if (cancelled) {\n return;\n }\n setFetchError(normalizedError);\n log.error(\"useCommunityStats pkc.fetchCid error\", {\n community,\n communityKey,\n communityStatsCid,\n fetchedCommunity,\n fetchedCid,\n error: normalizedError,\n });\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [communityStatsCid, account?.id, communityKey, setCommunityStats]);\n\n if (account && communityStatsCid) {\n log(\"useCommunityStats\", {\n community,\n communityKey,\n communityStatsCid,\n communityStats,\n fetchedCommunity,\n account,\n });\n }\n\n const state =\n !communityKey || !account || !communityStatsCid\n ? \"uninitialized\"\n : fetchError\n ? \"failed\"\n : communityStats\n ? \"succeeded\"\n : \"fetching-ipfs\";\n\n return useMemo(\n () => ({\n ...communityStats,\n state,\n error: fetchError,\n errors: fetchError ? [fetchError] : [],\n }),\n [communityStats, state, fetchError],\n );\n}\n\ntype CommunitiesStatsState = {\n communitiesStats: { [communityAddress: string]: CommunityStats };\n setCommunityStats: Function;\n};\n\nconst useCommunitiesStatsStore = createStore<CommunitiesStatsState>((setState: Function) => ({\n communitiesStats: {},\n setCommunityStats: (communityAddress: string, communityStats: CommunityStats) =>\n setState((state: CommunitiesStatsState) => ({\n communitiesStats: { ...state.communitiesStats, [communityAddress]: communityStats },\n })),\n}));\n\n/**\n * @param communities - The communities to fetch, e.g. [{name: 'memes.eth'}, {publicKey: '12D3KooW...'}]\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useCommunities(options?: UseCommunitiesOptions): UseCommunitiesResult {\n assert(\n !options || typeof options === \"object\",\n `useCommunities options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n const { communities: communitiesInput, accountName, onlyIfCached } = opts;\n const account = useAccount({ accountName });\n validator.validateUseCommunitiesArguments({\n communities: communitiesInput,\n communityRefs: (opts as any).communityRefs,\n communityAddresses: (opts as any).communityAddresses,\n account,\n });\n const normalizedCommunityRefs = useMemo(() => communitiesInput || [], [communitiesInput]);\n const communityKeys = useMemo(\n () => normalizedCommunityRefs.map(getCommunityRefKey),\n [normalizedCommunityRefs],\n );\n const communities: (Community | undefined)[] = useCommunitiesStore(\n (state: any) => communityKeys.map((communityKey) => state.communities[communityKey || \"\"]),\n shallow,\n );\n const communitiesErrors: (Error[] | undefined)[] = useCommunitiesStore(\n (state: any) => communityKeys.map((communityKey) => state.errors[communityKey || \"\"]),\n shallow,\n );\n const addCommunityToStore = useCommunitiesStore((state: any) => state.addCommunityToStore);\n\n useEffect(() => {\n if (!normalizedCommunityRefs.length || !account) {\n return;\n }\n if (onlyIfCached) {\n return;\n }\n const uniqueCommunityRefs = getUniqueSortedCommunityRefs(normalizedCommunityRefs);\n for (const communityRef of uniqueCommunityRefs) {\n addCommunityToStore(communityRef, account).catch((error: unknown) =>\n log.error(\"useCommunities addCommunityToStore error\", { communityRef, error }),\n );\n }\n }, [account?.id, communityKeys.toString(), onlyIfCached, normalizedCommunityRefs]);\n\n if (account && normalizedCommunityRefs.length) {\n log(\"useCommunities\", {\n requestedCommunities: normalizedCommunityRefs,\n communityKeys,\n communities,\n account,\n });\n }\n\n const errors = useMemo(\n () => communitiesErrors.flatMap((communityErrors) => communityErrors || []),\n [communitiesErrors],\n );\n const hasFailedCommunity = communities.some(\n (community, index) => !community && Boolean(communitiesErrors[index]?.length),\n );\n const state = hasFailedCommunity\n ? \"failed\"\n : communities.indexOf(undefined) === -1\n ? \"succeeded\"\n : \"fetching-ipns\";\n\n return useMemo(\n () => ({\n communities,\n state,\n error: errors[errors.length - 1],\n errors,\n }),\n [communities, state, errors, communityKeys.toString()],\n );\n}\n\n// TODO: pkc.listCommunities() has been removed, rename this and use event communitieschanged instead of polling\n/**\n * Returns all the owner communities created by pkc-js by calling pkc.listCommunities()\n */\nexport function useListCommunities(accountName?: string) {\n const account = useAccount({ accountName });\n const [communityAddresses, setCommunityAddresses] = useState<string[]>([]);\n\n const delay = 1000;\n const immediate = true;\n useInterval(\n () => {\n const pkc = account?.pkc;\n if (!pkc) return;\n const newAddrs = getPkcCommunityAddresses(pkc);\n if (newAddrs.toString() !== communityAddresses.toString()) {\n log(\"useListCommunities\", { communityAddresses });\n setCommunityAddresses(newAddrs);\n }\n },\n delay,\n immediate,\n );\n\n return communityAddresses;\n}\n\n/**\n * @param communityAddress - The community address to resolve to a public key, e.g. 'news.eth' resolves to '12D3KooW...'.\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\n// NOTE: useResolvedCommunityAddress tests are skipped, if changes are made they must be tested manually\nexport function useResolvedCommunityAddress(\n options?: UseResolvedCommunityAddressOptions,\n): UseResolvedCommunityAddressResult {\n assert(\n !options || typeof options === \"object\",\n `useResolvedCommunityAddress options argument '${options}' not an object`,\n );\n let { communityAddress, accountName, cache } = options ?? {};\n\n // cache by default\n if (typeof cache !== \"boolean\") {\n cache = true;\n }\n\n // poll every 15 seconds, about the duration of an eth block\n let interval = 15000;\n // no point in polling often if caching is on\n if (cache) {\n interval = 1000 * 60 * 60 * 25;\n }\n\n const account = useAccount({ accountName });\n const chainProviders = getChainProviders(account);\n const [resolvedAddress, setResolvedAddress] = useState<string>();\n const [errors, setErrors] = useState<Error[]>([]);\n const [state, setState] = useState<string>();\n\n let initialState = \"initializing\";\n // before those defined, nothing can happen\n if (options && account && communityAddress) {\n initialState = \"ready\";\n }\n\n useInterval(\n () => {\n if (!account || !communityAddress) {\n setResolvedAddress(undefined);\n setState(undefined);\n setErrors((prevErrors) => (prevErrors.length ? [] : prevErrors));\n return;\n }\n\n // address isn't a crypto domain, can't be resolved\n if (!communityAddress?.includes(\".\")) {\n if (state !== \"failed\") {\n setErrors([Error(\"not a crypto domain\")]);\n setState(\"failed\");\n setResolvedAddress(undefined);\n }\n return;\n }\n\n // only support resolving '.eth' for now\n if (!communityAddress?.endsWith(\".eth\")) {\n if (state !== \"failed\") {\n setErrors([Error(\"crypto domain type unsupported\")]);\n setState(\"failed\");\n setResolvedAddress(undefined);\n }\n return;\n }\n\n (async () => {\n try {\n setState(\"resolving\");\n const res = await resolveCommunityAddress(communityAddress, chainProviders);\n setState(\"succeeded\");\n if (res !== resolvedAddress) {\n setResolvedAddress(res);\n }\n } catch (error: any) {\n setErrors([...errors, error]);\n setState(\"failed\");\n setResolvedAddress(undefined);\n log.error(\"useResolvedCommunityAddress resolveCommunityAddress error\", {\n communityAddress,\n chainProviders,\n error,\n });\n }\n })();\n },\n interval,\n true,\n [communityAddress, chainProviders],\n );\n\n // only support ENS at the moment\n const chainProvider = chainProviders?.[\"eth\"];\n\n // log('useResolvedCommunityAddress', {communityAddress, state, errors, resolvedAddress, chainProviders})\n return {\n resolvedAddress,\n chainProvider,\n state: state || initialState,\n error: errors[errors.length - 1],\n errors,\n };\n}\n\n// NOTE: resolveCommunityAddress tests are skipped, if changes are made they must be tested manually\nexport const resolveCommunityAddress = async (\n communityAddress: string,\n chainProviders: ChainProviders,\n) => {\n let resolvedCommunityAddress;\n if (communityAddress.endsWith(\".eth\")) {\n resolvedCommunityAddress = await resolveEnsTxtRecord(\n communityAddress,\n \"community-address\",\n \"eth\",\n chainProviders?.[\"eth\"]?.urls?.[0],\n chainProviders?.[\"eth\"]?.chainId,\n );\n } else {\n throw Error(`resolveCommunityAddress invalid communityAddress '${communityAddress}'`);\n }\n return resolvedCommunityAddress;\n};\n"]}
1
+ {"version":3,"file":"communities.js","sourceRoot":"","sources":["../../src/hooks/communities.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,SAAS,MAAM,kBAAkB,CAAC;AACzC,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,yCAAyC,CAAC,CAAC;AAC9D,OAAO,MAAM,MAAM,QAAQ,CAAC;AAc5B,OAAO,WAAW,MAAM,sBAAsB,CAAC;AAC/C,OAAO,WAAW,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,mBAAmB,MAAM,uBAAuB,CAAC;AACxD,OAAO,gBAAgB,MAAM,oBAAoB,CAAC;AAClD,OAAO,OAAO,MAAM,iBAAiB,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAExF,MAAM,cAAc,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAEnG,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,EAAE;IAC3C,IAAI,CAAC;QACH,OAAO,cAAc,CAAC,KAA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,EACL,MAAA,MAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAG,KAAK,CAAC,0CAAE,IAAI,0CAAG,CAAC,CAAC,EAClC,MAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAG,KAAK,CAAC,0CAAE,OAAO,CACjC,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,CAAC,qDAAqD,gBAAgB,GAAG,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,wBAAwB,CAAC;AAClC,CAAC,CAAA,CAAC","sourcesContent":["import { useEffect, useState, useMemo } from \"react\";\nimport { useAccount } from \"./accounts\";\nimport validator from \"../lib/validator\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:communities:hooks\");\nimport assert from \"assert\";\nimport {\n Community,\n CommunityStats,\n ChainProviders,\n UseResolvedCommunityAddressOptions,\n UseResolvedCommunityAddressResult,\n UseCommunityOptions,\n UseCommunityResult,\n UseCommunitiesOptions,\n UseCommunitiesResult,\n UseCommunityStatsOptions,\n UseCommunityStatsResult,\n} from \"../types\";\nimport useInterval from \"./utils/use-interval\";\nimport createStore from \"zustand\";\nimport { resolveEnsTxtRecord } from \"../lib/chain\";\nimport useCommunitiesStore from \"../stores/communities\";\nimport useAccountsStore from \"../stores/accounts\";\nimport shallow from \"zustand/shallow\";\nimport { getChainProviders, getPkcCommunityAddresses } from \"../lib/pkc-compat\";\nimport { getCommunityRefKey, getUniqueSortedCommunityRefs } from \"../lib/community-ref\";\n\nconst parseMaybeJson = (value: unknown) => (typeof value === \"string\" ? JSON.parse(value) : value);\n\nconst tryParseMaybeJson = (value: unknown) => {\n try {\n return parseMaybeJson(value);\n } catch {\n return value;\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\";\n\nconst isCommunityStatsPayload = (value: unknown): value is CommunityStats =>\n isRecord(value) &&\n (\"hourActiveUserCount\" in value || \"weekActiveUserCount\" in value || \"allPostCount\" in value);\n\nconst parseFetchedCommunityStats = (fetchedCid: unknown): CommunityStats => {\n const parsedCid = parseMaybeJson(fetchedCid);\n if (isCommunityStatsPayload(parsedCid)) {\n return parsedCid;\n }\n if (isRecord(parsedCid) && \"content\" in parsedCid) {\n const parsedContent = tryParseMaybeJson(parsedCid.content);\n if (isCommunityStatsPayload(parsedContent)) {\n return parsedContent;\n }\n }\n return parsedCid as CommunityStats;\n};\n\n/**\n * @param community - The community identifier, e.g. {name: 'memes.eth'} or {publicKey: '12D3KooW...'}\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useCommunity(options?: UseCommunityOptions): UseCommunityResult {\n assert(\n !options || typeof options === \"object\",\n `useCommunity options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n const { community: communityInput, accountName, onlyIfCached } = opts;\n const account = useAccount({ accountName });\n const accountId = account?.id || \"\";\n validator.validateUseCommunityArguments({\n community: communityInput,\n communityAddress: (opts as any).communityAddress,\n account,\n });\n const communityKey = communityInput ? getCommunityRefKey(communityInput) : \"\";\n const storedCommunity = useCommunitiesStore((state: any) => state.communities[communityKey]);\n const addCommunityToStore = useCommunitiesStore((state: any) => state.addCommunityToStore);\n const errors = useCommunitiesStore((state: any) => state.errors[communityKey]);\n const syncStatus = useCommunitiesStore((state: any) => state.syncStatuses[communityKey]);\n const communityEditSummary = useAccountsStore((state: any) => {\n const accountEditsSummaries = state.accountsEditsSummaries[accountId] || {};\n const candidateCommunityKeys = [\n storedCommunity?.address,\n storedCommunity?.name,\n storedCommunity?.publicKey,\n communityInput?.name,\n communityInput?.publicKey,\n ];\n for (const candidateCommunityKey of candidateCommunityKeys) {\n if (\n typeof candidateCommunityKey === \"string\" &&\n accountEditsSummaries[candidateCommunityKey]\n ) {\n return accountEditsSummaries[candidateCommunityKey];\n }\n }\n });\n\n useEffect(() => {\n if (!communityInput || !account) {\n return;\n }\n if (!storedCommunity && !onlyIfCached) {\n // if community isn't already in store, add it\n addCommunityToStore(communityInput, account).catch((error: unknown) =>\n log.error(\"useCommunity addCommunityToStore error\", { communityInput, error }),\n );\n }\n }, [communityKey, account?.id]);\n\n if (account && communityInput) {\n log(\"useCommunity\", {\n community: communityInput,\n communityKey,\n storedCommunity,\n account,\n });\n }\n\n const mergedCommunity = useMemo(() => {\n if (!communityEditSummary) {\n return storedCommunity;\n }\n const localCommunityAddresses = getPkcCommunityAddresses(account?.pkc);\n const editedCommunityAddress = communityEditSummary.address?.value;\n const inputCommunityIdentifiers = [communityInput?.name, communityInput?.publicKey].filter(\n (communityIdentifier): communityIdentifier is string =>\n typeof communityIdentifier === \"string\",\n );\n if (\n !storedCommunity &&\n editedCommunityAddress &&\n !inputCommunityIdentifiers.some((communityIdentifier) =>\n localCommunityAddresses.includes(communityIdentifier),\n ) &&\n !localCommunityAddresses.includes(editedCommunityAddress)\n ) {\n return storedCommunity;\n }\n if (\n storedCommunity?.address &&\n editedCommunityAddress &&\n storedCommunity.address !== editedCommunityAddress\n ) {\n return storedCommunity;\n }\n const summaryValues = Object.fromEntries(\n Object.entries(communityEditSummary).map(([propertyName, propertySummary]: [string, any]) => [\n propertyName,\n propertySummary?.value,\n ]),\n );\n return {\n ...(storedCommunity || { address: communityInput?.name || communityInput?.publicKey }),\n ...summaryValues,\n };\n }, [account?.pkc, storedCommunity, communityInput, communityEditSummary]);\n\n let state = mergedCommunity?.updatingState || \"initializing\";\n // force succeeded even if the community is fecthing a new update\n if (mergedCommunity?.updatedAt) {\n state = \"succeeded\";\n }\n\n return useMemo(\n () => ({\n ...mergedCommunity,\n state,\n syncState: syncStatus?.syncState || (onlyIfCached ? \"stopped\" : \"initializing\"),\n hasCachedData: typeof mergedCommunity?.updatedAt === \"number\",\n lastFetchAttemptAt: syncStatus?.lastFetchAttemptAt,\n lastSuccessfulFetchAt: syncStatus?.lastSuccessfulFetchAt,\n error: errors?.[errors.length - 1],\n errors: errors || [],\n }),\n [mergedCommunity, communityKey, errors, onlyIfCached, syncStatus],\n );\n}\n\n/**\n * @param community - The community identifier, e.g. {name: 'memes.eth'} or {publicKey: '12D3KooW...'}\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useCommunityStats(options?: UseCommunityStatsOptions): UseCommunityStatsResult {\n assert(\n !options || typeof options === \"object\",\n `useCommunityStats options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n const { community, accountName, onlyIfCached } = opts;\n validator.validateUseCommunityStatsArguments({\n community,\n communityAddress: (opts as any).communityAddress,\n });\n const account = useAccount({ accountName });\n const communityKey = community ? getCommunityRefKey(community) : \"\";\n const fetchedCommunity = useCommunity({ community, onlyIfCached });\n const communityStatsCid = fetchedCommunity?.statsCid;\n const communityStats = useCommunitiesStatsStore(\n (state: CommunitiesStatsState) => state.communitiesStats[communityKey],\n );\n const setCommunityStats = useCommunitiesStatsStore(\n (state: CommunitiesStatsState) => state.setCommunityStats,\n );\n const [fetchError, setFetchError] = useState<Error | undefined>();\n\n useEffect(() => {\n setFetchError(undefined);\n if (!communityKey || !communityStatsCid || !account) {\n return;\n }\n let cancelled = false;\n (async () => {\n let fetchedCid;\n try {\n fetchedCid = await account.pkc.fetchCid({ cid: communityStatsCid });\n fetchedCid = parseFetchedCommunityStats(fetchedCid);\n if (cancelled) {\n return;\n }\n setCommunityStats(communityKey, fetchedCid);\n } catch (error) {\n const normalizedError =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : \"error\");\n if (cancelled) {\n return;\n }\n setFetchError(normalizedError);\n log.error(\"useCommunityStats pkc.fetchCid error\", {\n community,\n communityKey,\n communityStatsCid,\n fetchedCommunity,\n fetchedCid,\n error: normalizedError,\n });\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [communityStatsCid, account?.id, communityKey, setCommunityStats]);\n\n if (account && communityStatsCid) {\n log(\"useCommunityStats\", {\n community,\n communityKey,\n communityStatsCid,\n communityStats,\n fetchedCommunity,\n account,\n });\n }\n\n const state =\n !communityKey || !account || !communityStatsCid\n ? \"uninitialized\"\n : fetchError\n ? \"failed\"\n : communityStats\n ? \"succeeded\"\n : \"fetching-ipfs\";\n\n return useMemo(\n () => ({\n ...communityStats,\n state,\n error: fetchError,\n errors: fetchError ? [fetchError] : [],\n }),\n [communityStats, state, fetchError],\n );\n}\n\ntype CommunitiesStatsState = {\n communitiesStats: { [communityAddress: string]: CommunityStats };\n setCommunityStats: Function;\n};\n\nconst useCommunitiesStatsStore = createStore<CommunitiesStatsState>((setState: Function) => ({\n communitiesStats: {},\n setCommunityStats: (communityAddress: string, communityStats: CommunityStats) =>\n setState((state: CommunitiesStatsState) => ({\n communitiesStats: { ...state.communitiesStats, [communityAddress]: communityStats },\n })),\n}));\n\n/**\n * @param communities - The communities to fetch, e.g. [{name: 'memes.eth'}, {publicKey: '12D3KooW...'}]\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\nexport function useCommunities(options?: UseCommunitiesOptions): UseCommunitiesResult {\n assert(\n !options || typeof options === \"object\",\n `useCommunities options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n const { communities: communitiesInput, accountName, onlyIfCached } = opts;\n const account = useAccount({ accountName });\n validator.validateUseCommunitiesArguments({\n communities: communitiesInput,\n communityRefs: (opts as any).communityRefs,\n communityAddresses: (opts as any).communityAddresses,\n account,\n });\n const normalizedCommunityRefs = useMemo(() => communitiesInput || [], [communitiesInput]);\n const communityKeys = useMemo(\n () => normalizedCommunityRefs.map(getCommunityRefKey),\n [normalizedCommunityRefs],\n );\n const communities: (Community | undefined)[] = useCommunitiesStore(\n (state: any) => communityKeys.map((communityKey) => state.communities[communityKey || \"\"]),\n shallow,\n );\n const communitiesErrors: (Error[] | undefined)[] = useCommunitiesStore(\n (state: any) => communityKeys.map((communityKey) => state.errors[communityKey || \"\"]),\n shallow,\n );\n const addCommunityToStore = useCommunitiesStore((state: any) => state.addCommunityToStore);\n\n useEffect(() => {\n if (!normalizedCommunityRefs.length || !account) {\n return;\n }\n if (onlyIfCached) {\n return;\n }\n const uniqueCommunityRefs = getUniqueSortedCommunityRefs(normalizedCommunityRefs);\n for (const communityRef of uniqueCommunityRefs) {\n addCommunityToStore(communityRef, account).catch((error: unknown) =>\n log.error(\"useCommunities addCommunityToStore error\", { communityRef, error }),\n );\n }\n }, [account?.id, communityKeys.toString(), onlyIfCached, normalizedCommunityRefs]);\n\n if (account && normalizedCommunityRefs.length) {\n log(\"useCommunities\", {\n requestedCommunities: normalizedCommunityRefs,\n communityKeys,\n communities,\n account,\n });\n }\n\n const errors = useMemo(\n () => communitiesErrors.flatMap((communityErrors) => communityErrors || []),\n [communitiesErrors],\n );\n const hasFailedCommunity = communities.some(\n (community, index) => !community && Boolean(communitiesErrors[index]?.length),\n );\n const state = hasFailedCommunity\n ? \"failed\"\n : communities.indexOf(undefined) === -1\n ? \"succeeded\"\n : \"fetching-ipns\";\n\n return useMemo(\n () => ({\n communities,\n state,\n error: errors[errors.length - 1],\n errors,\n }),\n [communities, state, errors, communityKeys.toString()],\n );\n}\n\n// TODO: pkc.listCommunities() has been removed, rename this and use event communitieschanged instead of polling\n/**\n * Returns all the owner communities created by pkc-js by calling pkc.listCommunities()\n */\nexport function useListCommunities(accountName?: string) {\n const account = useAccount({ accountName });\n const [communityAddresses, setCommunityAddresses] = useState<string[]>([]);\n\n const delay = 1000;\n const immediate = true;\n useInterval(\n () => {\n const pkc = account?.pkc;\n if (!pkc) return;\n const newAddrs = getPkcCommunityAddresses(pkc);\n if (newAddrs.toString() !== communityAddresses.toString()) {\n log(\"useListCommunities\", { communityAddresses });\n setCommunityAddresses(newAddrs);\n }\n },\n delay,\n immediate,\n );\n\n return communityAddresses;\n}\n\n/**\n * @param communityAddress - The community address to resolve to a public key, e.g. 'news.eth' resolves to '12D3KooW...'.\n * @param acountName - The nickname of the account, e.g. 'Account 1'. If no accountName is provided, use\n * the active account.\n */\n// NOTE: useResolvedCommunityAddress tests are skipped, if changes are made they must be tested manually\nexport function useResolvedCommunityAddress(\n options?: UseResolvedCommunityAddressOptions,\n): UseResolvedCommunityAddressResult {\n assert(\n !options || typeof options === \"object\",\n `useResolvedCommunityAddress options argument '${options}' not an object`,\n );\n let { communityAddress, accountName, cache } = options ?? {};\n\n // cache by default\n if (typeof cache !== \"boolean\") {\n cache = true;\n }\n\n // poll every 15 seconds, about the duration of an eth block\n let interval = 15000;\n // no point in polling often if caching is on\n if (cache) {\n interval = 1000 * 60 * 60 * 25;\n }\n\n const account = useAccount({ accountName });\n const chainProviders = getChainProviders(account);\n const [resolvedAddress, setResolvedAddress] = useState<string>();\n const [errors, setErrors] = useState<Error[]>([]);\n const [state, setState] = useState<string>();\n\n let initialState = \"initializing\";\n // before those defined, nothing can happen\n if (options && account && communityAddress) {\n initialState = \"ready\";\n }\n\n useInterval(\n () => {\n if (!account || !communityAddress) {\n setResolvedAddress(undefined);\n setState(undefined);\n setErrors((prevErrors) => (prevErrors.length ? [] : prevErrors));\n return;\n }\n\n // address isn't a crypto domain, can't be resolved\n if (!communityAddress?.includes(\".\")) {\n if (state !== \"failed\") {\n setErrors([Error(\"not a crypto domain\")]);\n setState(\"failed\");\n setResolvedAddress(undefined);\n }\n return;\n }\n\n // only support resolving '.eth' for now\n if (!communityAddress?.endsWith(\".eth\")) {\n if (state !== \"failed\") {\n setErrors([Error(\"crypto domain type unsupported\")]);\n setState(\"failed\");\n setResolvedAddress(undefined);\n }\n return;\n }\n\n (async () => {\n try {\n setState(\"resolving\");\n const res = await resolveCommunityAddress(communityAddress, chainProviders);\n setState(\"succeeded\");\n if (res !== resolvedAddress) {\n setResolvedAddress(res);\n }\n } catch (error: any) {\n setErrors([...errors, error]);\n setState(\"failed\");\n setResolvedAddress(undefined);\n log.error(\"useResolvedCommunityAddress resolveCommunityAddress error\", {\n communityAddress,\n chainProviders,\n error,\n });\n }\n })();\n },\n interval,\n true,\n [communityAddress, chainProviders],\n );\n\n // only support ENS at the moment\n const chainProvider = chainProviders?.[\"eth\"];\n\n // log('useResolvedCommunityAddress', {communityAddress, state, errors, resolvedAddress, chainProviders})\n return {\n resolvedAddress,\n chainProvider,\n state: state || initialState,\n error: errors[errors.length - 1],\n errors,\n };\n}\n\n// NOTE: resolveCommunityAddress tests are skipped, if changes are made they must be tested manually\nexport const resolveCommunityAddress = async (\n communityAddress: string,\n chainProviders: ChainProviders,\n) => {\n let resolvedCommunityAddress;\n if (communityAddress.endsWith(\".eth\")) {\n resolvedCommunityAddress = await resolveEnsTxtRecord(\n communityAddress,\n \"community-address\",\n \"eth\",\n chainProviders?.[\"eth\"]?.urls?.[0],\n chainProviders?.[\"eth\"]?.chainId,\n );\n } else {\n throw Error(`resolveCommunityAddress invalid communityAddress '${communityAddress}'`);\n }\n return resolvedCommunityAddress;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"replies.d.ts","sourceRoot":"","sources":["../../src/hooks/replies.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAQ/D,yHAAyH;AACzH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,EAAE,CAE1E;AAED,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,gBAAgB,CAuLxE"}
1
+ {"version":3,"file":"replies.d.ts","sourceRoot":"","sources":["../../src/hooks/replies.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAU/D,yHAAyH;AACzH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,EAAE,CAE1E;AAED,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,gBAAgB,CAqMxE"}
@@ -15,6 +15,8 @@ const log = Logger("bitsocial-react-hooks:replies:hooks");
15
15
  import assert from "assert";
16
16
  import { addCommentModerationToComments } from "../lib/utils/comment-moderation.js";
17
17
  import useRepliesStore, { feedOptionsToFeedName, getRepliesFirstPageSkipValidation, } from "../stores/replies/index.js";
18
+ import useAccountsStore from "../stores/accounts/index.js";
19
+ import { addOptimisticVoteCountsToComments } from "../lib/utils/optimistic-vote-counts.js";
18
20
  /** Pure helper to append an error to the errors array; used for deterministic coverage of reset/loadMore catch paths. */
19
21
  export function appendErrorToErrors(prevErrors, e) {
20
22
  return [...prevErrors, e];
@@ -32,6 +34,7 @@ export function useReplies(options) {
32
34
  const [errors, setErrors] = useState([]);
33
35
  // add replies to store
34
36
  const account = useAccount({ accountName });
37
+ const accountVotes = useAccountsStore((state) => (account === null || account === void 0 ? void 0 : account.id) ? state.accountsVotes[account.id] : undefined);
35
38
  const feedOptions = {
36
39
  commentCid: comment === null || comment === void 0 ? void 0 : comment.cid,
37
40
  commentDepth: comment === null || comment === void 0 ? void 0 : comment.depth,
@@ -128,9 +131,9 @@ export function useReplies(options) {
128
131
  });
129
132
  }
130
133
  const state = !hasMore ? "succeeded" : "fetching";
131
- const normalizedReplies = useMemo(() => addCommentModerationToComments(replies), [replies]);
132
- const normalizedBufferedReplies = useMemo(() => addCommentModerationToComments(bufferedReplies), [bufferedReplies]);
133
- const normalizedUpdatedReplies = useMemo(() => addCommentModerationToComments(updatedReplies), [updatedReplies]);
134
+ const normalizedReplies = useMemo(() => addOptimisticVoteCountsToComments(addCommentModerationToComments(replies), accountVotes), [replies, accountVotes]);
135
+ const normalizedBufferedReplies = useMemo(() => addOptimisticVoteCountsToComments(addCommentModerationToComments(bufferedReplies), accountVotes), [bufferedReplies, accountVotes]);
136
+ const normalizedUpdatedReplies = useMemo(() => addOptimisticVoteCountsToComments(addCommentModerationToComments(updatedReplies), accountVotes), [updatedReplies, accountVotes]);
134
137
  return useMemo(() => ({
135
138
  replies: normalizedReplies,
136
139
  bufferedReplies: normalizedBufferedReplies,
@@ -1 +1 @@
1
- {"version":3,"file":"replies.js","sourceRoot":"","sources":["../../src/hooks/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wB,GAAG,OAAO,CACtC,GAAG,EAAE,CAAC,8BAA8B,CAAC,cAAc,CAAC,EACpD,CAAC,cAAc,CAAC,CACjB,CAAC;IAEF,OAAO,OAAO,CACZ,GAAG,EAAE,CAAC,CAAC;QACL,OAAO,EAAE,iBAAiB;QAC1B,eAAe,EAAE,yBAAyB;QAC1C,cAAc,EAAE,wBAAwB;QACxC,OAAO;QACP,QAAQ;QACR,KAAK;QACL,KAAK;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;QAChC,MAAM;KACP,CAAC,EACF;QACE,iBAAiB;QACjB,yBAAyB;QACzB,wBAAwB;QACxB,eAAe;QACf,OAAO;QACP,MAAM;KACP,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,GAAQ,EAAE,CAAC;AAC3B,MAAM,aAAa,GAAG,GAAS,EAAE,kDAAE,CAAC,CAAA,CAAC","sourcesContent":["import { useEffect, useState, useMemo } from \"react\";\nimport { useAccount } from \"./accounts\";\nimport validator from \"../lib/validator\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:replies:hooks\");\nimport assert from \"assert\";\nimport { UseRepliesOptions, UseRepliesResult } from \"../types\";\nimport { addCommentModerationToComments } from \"../lib/utils/comment-moderation\";\nimport useRepliesStore, {\n RepliesState,\n feedOptionsToFeedName,\n getRepliesFirstPageSkipValidation,\n} from \"../stores/replies\";\n\n/** Pure helper to append an error to the errors array; used for deterministic coverage of reset/loadMore catch paths. */\nexport function appendErrorToErrors(prevErrors: Error[], e: Error): Error[] {\n return [...prevErrors, e];\n}\n\nexport function useReplies(options?: UseRepliesOptions): UseRepliesResult {\n assert(\n !options || typeof options === \"object\",\n `useReplies options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n let {\n comment,\n sortType,\n accountName,\n onlyIfCached,\n flat,\n flatDepth,\n accountComments,\n repliesPerPage,\n filter,\n validateOptimistically,\n streamPage,\n } = opts;\n sortType = sortType || \"best\";\n flatDepth = typeof flatDepth === \"number\" ? flatDepth : 0;\n validateOptimistically = validateOptimistically !== false;\n const invalidFlatDepth =\n flat && typeof comment?.depth === \"number\" && flatDepth !== comment.depth;\n validator.validateUseRepliesArguments(\n comment,\n sortType,\n accountName,\n onlyIfCached,\n flat,\n accountComments,\n repliesPerPage,\n filter,\n );\n\n const [errors, setErrors] = useState<Error[]>([]);\n\n // add replies to store\n const account = useAccount({ accountName });\n const feedOptions = {\n commentCid: comment?.cid,\n commentDepth: comment?.depth,\n postCid: comment?.postCid,\n sortType,\n accountId: account?.id,\n onlyIfCached,\n repliesPerPage,\n flat,\n accountComments,\n filter,\n streamPage,\n };\n const repliesFeedName = feedOptionsToFeedName(feedOptions);\n const addFeedToStoreOrUpdateComment = useRepliesStore(\n (state: RepliesState) => state.addFeedToStoreOrUpdateComment,\n );\n useEffect(() => {\n if (!comment?.cid || !account || invalidFlatDepth) {\n return;\n }\n addFeedToStoreOrUpdateComment(comment, feedOptions).catch((error: unknown) =>\n log.error(\"useReplies addFeedToStoreOrUpdateComment error\", {\n repliesFeedName,\n comment,\n feedOptions,\n error,\n }),\n );\n }, [repliesFeedName, comment]);\n\n let replies = useRepliesStore((state: RepliesState) => state.loadedFeeds[repliesFeedName || \"\"]);\n let bufferedReplies = useRepliesStore(\n (state: RepliesState) => state.bufferedFeeds[repliesFeedName || \"\"],\n );\n let updatedReplies = useRepliesStore(\n (state: RepliesState) => state.updatedFeeds[repliesFeedName || \"\"],\n );\n let hasMore = useRepliesStore(\n (state: RepliesState) => state.feedsHaveMore[repliesFeedName || \"\"],\n );\n hasMore = comment\n ? repliesFeedName && typeof hasMore === \"boolean\"\n ? hasMore\n : !onlyIfCached\n : false;\n\n const incrementFeedPageNumber = useRepliesStore(\n (state: RepliesState) => state.incrementFeedPageNumber,\n );\n let loadMore = async () => {\n try {\n if (!comment?.cid || !account) {\n throw Error(\"useReplies cannot load more replies not initalized yet\");\n }\n incrementFeedPageNumber(repliesFeedName);\n } catch (e: any) {\n await new Promise((r) => setTimeout(r, 50));\n setErrors(appendErrorToErrors(errors, e));\n }\n };\n\n const resetFeed = useRepliesStore((state: RepliesState) => state.resetFeed);\n let reset = async () => {\n try {\n if (!comment?.cid || !account) {\n throw Error(\"useReplies cannot reset replies not initalized yet\");\n }\n resetFeed(repliesFeedName);\n } catch (e: any) {\n await new Promise((r) => setTimeout(r, 50));\n setErrors(appendErrorToErrors(errors, e));\n }\n };\n\n // optimistically avoid the initial validation delay by using skipped validation until validated feed is loaded\n const skipValidation = useMemo(() => {\n if (validateOptimistically && !replies && comment?.cid && account?.id) {\n return getRepliesFirstPageSkipValidation(comment, feedOptions);\n }\n }, [validateOptimistically, replies, comment?.cid, account?.id, comment, repliesFeedName]);\n if (validateOptimistically && !replies && skipValidation?.replies?.length) {\n replies = skipValidation.replies;\n hasMore = skipValidation.hasMore;\n }\n\n // don't display nested replies when flat\n // to start flat replies at a depth other than 0, e.g. a twitter reply thread, change flatDepth\n if (invalidFlatDepth) {\n replies = emptyArray;\n bufferedReplies = emptyArray;\n updatedReplies = emptyArray;\n hasMore = false;\n loadMore = emptyFunction;\n reset = emptyFunction;\n }\n\n if (account && comment?.cid) {\n log(\"useReplies\", {\n repliesLength: replies?.length || 0,\n hasMore,\n comment,\n sortType,\n onlyIfCached,\n flat,\n flatDepth,\n repliesStoreOptions: useRepliesStore.getState().feedsOptions,\n repliesStore: useRepliesStore.getState(),\n invalidFlatDepth,\n });\n }\n\n const state = !hasMore ? \"succeeded\" : \"fetching\";\n const normalizedReplies = useMemo(() => addCommentModerationToComments(replies), [replies]);\n const normalizedBufferedReplies = useMemo(\n () => addCommentModerationToComments(bufferedReplies),\n [bufferedReplies],\n );\n const normalizedUpdatedReplies = useMemo(\n () => addCommentModerationToComments(updatedReplies),\n [updatedReplies],\n );\n\n return useMemo(\n () => ({\n replies: normalizedReplies,\n bufferedReplies: normalizedBufferedReplies,\n updatedReplies: normalizedUpdatedReplies,\n hasMore,\n loadMore,\n reset,\n state,\n error: errors[errors.length - 1],\n errors,\n }),\n [\n normalizedReplies,\n normalizedBufferedReplies,\n normalizedUpdatedReplies,\n repliesFeedName,\n hasMore,\n errors,\n ],\n );\n}\n\nconst emptyArray: any = [];\nconst emptyFunction = async () => {};\n"]}
1
+ {"version":3,"file":"replies.js","sourceRoot":"","sources":["../../src/hooks/replies.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,SAAS,MAAM,kBAAkB,CAAC;AACzC,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,MAAM,GAAG,GAAG,MAAM,CAAC,qCAAqC,CAAC,CAAC;AAC1D,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AACjF,OAAO,eAAe,EAAE,EAEtB,qBAAqB,EACrB,iCAAiC,GAClC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,gBAAgB,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,iCAAiC,EAAE,MAAM,qCAAqC,CAAC;AAExF,yHAAyH;AACzH,MAAM,UAAU,mBAAmB,CAAC,UAAmB,EAAE,CAAQ;IAC/D,OAAO,CAAC,GAAG,UAAU,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,OAA2B;;IACpD,MAAM,CACJ,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EACvC,gCAAgC,OAAO,iBAAiB,CACzD,CAAC;IACF,MAAM,IAAI,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;IAC3B,IAAI,EACF,OAAO,EACP,QAAQ,EACR,WAAW,EACX,YAAY,EACZ,IAAI,EACJ,SAAS,EACT,eAAe,EACf,cAAc,EACd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A,CAAC","sourcesContent":["import { useEffect, useState, useMemo } from \"react\";\nimport { useAccount } from \"./accounts\";\nimport validator from \"../lib/validator\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\nconst log = Logger(\"bitsocial-react-hooks:replies:hooks\");\nimport assert from \"assert\";\nimport { UseRepliesOptions, UseRepliesResult } from \"../types\";\nimport { addCommentModerationToComments } from \"../lib/utils/comment-moderation\";\nimport useRepliesStore, {\n RepliesState,\n feedOptionsToFeedName,\n getRepliesFirstPageSkipValidation,\n} from \"../stores/replies\";\nimport useAccountsStore from \"../stores/accounts\";\nimport { addOptimisticVoteCountsToComments } from \"../lib/utils/optimistic-vote-counts\";\n\n/** Pure helper to append an error to the errors array; used for deterministic coverage of reset/loadMore catch paths. */\nexport function appendErrorToErrors(prevErrors: Error[], e: Error): Error[] {\n return [...prevErrors, e];\n}\n\nexport function useReplies(options?: UseRepliesOptions): UseRepliesResult {\n assert(\n !options || typeof options === \"object\",\n `useReplies options argument '${options}' not an object`,\n );\n const opts = options ?? {};\n let {\n comment,\n sortType,\n accountName,\n onlyIfCached,\n flat,\n flatDepth,\n accountComments,\n repliesPerPage,\n filter,\n validateOptimistically,\n streamPage,\n } = opts;\n sortType = sortType || \"best\";\n flatDepth = typeof flatDepth === \"number\" ? flatDepth : 0;\n validateOptimistically = validateOptimistically !== false;\n const invalidFlatDepth =\n flat && typeof comment?.depth === \"number\" && flatDepth !== comment.depth;\n validator.validateUseRepliesArguments(\n comment,\n sortType,\n accountName,\n onlyIfCached,\n flat,\n accountComments,\n repliesPerPage,\n filter,\n );\n\n const [errors, setErrors] = useState<Error[]>([]);\n\n // add replies to store\n const account = useAccount({ accountName });\n const accountVotes = useAccountsStore((state: any) =>\n account?.id ? state.accountsVotes[account.id] : undefined,\n );\n const feedOptions = {\n commentCid: comment?.cid,\n commentDepth: comment?.depth,\n postCid: comment?.postCid,\n sortType,\n accountId: account?.id,\n onlyIfCached,\n repliesPerPage,\n flat,\n accountComments,\n filter,\n streamPage,\n };\n const repliesFeedName = feedOptionsToFeedName(feedOptions);\n const addFeedToStoreOrUpdateComment = useRepliesStore(\n (state: RepliesState) => state.addFeedToStoreOrUpdateComment,\n );\n useEffect(() => {\n if (!comment?.cid || !account || invalidFlatDepth) {\n return;\n }\n addFeedToStoreOrUpdateComment(comment, feedOptions).catch((error: unknown) =>\n log.error(\"useReplies addFeedToStoreOrUpdateComment error\", {\n repliesFeedName,\n comment,\n feedOptions,\n error,\n }),\n );\n }, [repliesFeedName, comment]);\n\n let replies = useRepliesStore((state: RepliesState) => state.loadedFeeds[repliesFeedName || \"\"]);\n let bufferedReplies = useRepliesStore(\n (state: RepliesState) => state.bufferedFeeds[repliesFeedName || \"\"],\n );\n let updatedReplies = useRepliesStore(\n (state: RepliesState) => state.updatedFeeds[repliesFeedName || \"\"],\n );\n let hasMore = useRepliesStore(\n (state: RepliesState) => state.feedsHaveMore[repliesFeedName || \"\"],\n );\n hasMore = comment\n ? repliesFeedName && typeof hasMore === \"boolean\"\n ? hasMore\n : !onlyIfCached\n : false;\n\n const incrementFeedPageNumber = useRepliesStore(\n (state: RepliesState) => state.incrementFeedPageNumber,\n );\n let loadMore = async () => {\n try {\n if (!comment?.cid || !account) {\n throw Error(\"useReplies cannot load more replies not initalized yet\");\n }\n incrementFeedPageNumber(repliesFeedName);\n } catch (e: any) {\n await new Promise((r) => setTimeout(r, 50));\n setErrors(appendErrorToErrors(errors, e));\n }\n };\n\n const resetFeed = useRepliesStore((state: RepliesState) => state.resetFeed);\n let reset = async () => {\n try {\n if (!comment?.cid || !account) {\n throw Error(\"useReplies cannot reset replies not initalized yet\");\n }\n resetFeed(repliesFeedName);\n } catch (e: any) {\n await new Promise((r) => setTimeout(r, 50));\n setErrors(appendErrorToErrors(errors, e));\n }\n };\n\n // optimistically avoid the initial validation delay by using skipped validation until validated feed is loaded\n const skipValidation = useMemo(() => {\n if (validateOptimistically && !replies && comment?.cid && account?.id) {\n return getRepliesFirstPageSkipValidation(comment, feedOptions);\n }\n }, [validateOptimistically, replies, comment?.cid, account?.id, comment, repliesFeedName]);\n if (validateOptimistically && !replies && skipValidation?.replies?.length) {\n replies = skipValidation.replies;\n hasMore = skipValidation.hasMore;\n }\n\n // don't display nested replies when flat\n // to start flat replies at a depth other than 0, e.g. a twitter reply thread, change flatDepth\n if (invalidFlatDepth) {\n replies = emptyArray;\n bufferedReplies = emptyArray;\n updatedReplies = emptyArray;\n hasMore = false;\n loadMore = emptyFunction;\n reset = emptyFunction;\n }\n\n if (account && comment?.cid) {\n log(\"useReplies\", {\n repliesLength: replies?.length || 0,\n hasMore,\n comment,\n sortType,\n onlyIfCached,\n flat,\n flatDepth,\n repliesStoreOptions: useRepliesStore.getState().feedsOptions,\n repliesStore: useRepliesStore.getState(),\n invalidFlatDepth,\n });\n }\n\n const state = !hasMore ? \"succeeded\" : \"fetching\";\n const normalizedReplies = useMemo(\n () => addOptimisticVoteCountsToComments(addCommentModerationToComments(replies), accountVotes),\n [replies, accountVotes],\n );\n const normalizedBufferedReplies = useMemo(\n () =>\n addOptimisticVoteCountsToComments(\n addCommentModerationToComments(bufferedReplies),\n accountVotes,\n ),\n [bufferedReplies, accountVotes],\n );\n const normalizedUpdatedReplies = useMemo(\n () =>\n addOptimisticVoteCountsToComments(\n addCommentModerationToComments(updatedReplies),\n accountVotes,\n ),\n [updatedReplies, accountVotes],\n );\n\n return useMemo(\n () => ({\n replies: normalizedReplies,\n bufferedReplies: normalizedBufferedReplies,\n updatedReplies: normalizedUpdatedReplies,\n hasMore,\n loadMore,\n reset,\n state,\n error: errors[errors.length - 1],\n errors,\n }),\n [\n normalizedReplies,\n normalizedBufferedReplies,\n normalizedUpdatedReplies,\n repliesFeedName,\n hasMore,\n errors,\n ],\n );\n}\n\nconst emptyArray: any = [];\nconst emptyFunction = async () => {};\n"]}
@@ -0,0 +1,11 @@
1
+ import { AccountVote, Comment } from "../../types.js";
2
+ export declare const optimisticVoteBaseKey = "_optimisticVoteBase";
3
+ export declare const optimisticVoteObservedAtKey = "_optimisticVoteObservedAt";
4
+ export declare const optimisticVoteTransitionsKey = "_optimisticVoteTransitions";
5
+ export declare const getCommentVoteCountsVersion: (comment: Comment | undefined) => number;
6
+ export declare const addOptimisticVoteMetadata: (accountVote: AccountVote, previousAccountVote: AccountVote | undefined, comment: Comment | undefined) => AccountVote;
7
+ export declare const addOptimisticVoteCounts: (comment: Comment | undefined, accountVote: AccountVote | undefined) => Comment | undefined;
8
+ export declare const addOptimisticVoteCountsToComments: <T extends Comment | undefined>(comments: T[] | undefined, accountVotes: {
9
+ [commentCid: string]: AccountVote;
10
+ } | undefined) => T[];
11
+ //# sourceMappingURL=optimistic-vote-counts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"optimistic-vote-counts.d.ts","sourceRoot":"","sources":["../../../src/lib/utils/optimistic-vote-counts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEnD,eAAO,MAAM,qBAAqB,wBAAwB,CAAC;AAC3D,eAAO,MAAM,2BAA2B,8BAA8B,CAAC;AACvE,eAAO,MAAM,4BAA4B,+BAA+B,CAAC;AASzE,eAAO,MAAM,2BAA2B,GAAI,SAAS,OAAO,GAAG,SAAS,KAAG,MACZ,CAAC;AAEhE,eAAO,MAAM,yBAAyB,GACpC,aAAa,WAAW,EACxB,qBAAqB,WAAW,GAAG,SAAS,EAC5C,SAAS,OAAO,GAAG,SAAS,KAC3B,WAoDF,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAClC,SAAS,OAAO,GAAG,SAAS,EAC5B,aAAa,WAAW,GAAG,SAAS,KACnC,OAAO,GAAG,SAkCZ,CAAC;AAEF,eAAO,MAAM,iCAAiC,GAAI,CAAC,SAAS,OAAO,GAAG,SAAS,EAC7E,UAAU,CAAC,EAAE,GAAG,SAAS,EACzB,cAAc;IAAE,CAAC,UAAU,EAAE,MAAM,GAAG,WAAW,CAAA;CAAE,GAAG,SAAS,KAC9D,CAAC,EAGM,CAAC"}