@bitsocial/bitsocial-react-hooks 0.1.52 → 0.1.54

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.
Files changed (96) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +52 -1507
  3. package/dist/hooks/accounts/accounts.js +2 -2
  4. package/dist/hooks/accounts/accounts.js.map +1 -1
  5. package/dist/hooks/accounts/utils.d.ts.map +1 -1
  6. package/dist/hooks/accounts/utils.js +3 -12
  7. package/dist/hooks/accounts/utils.js.map +1 -1
  8. package/dist/hooks/actions/actions.js +1 -1
  9. package/dist/hooks/actions/actions.js.map +1 -1
  10. package/dist/hooks/authors/author-avatars.js +1 -1
  11. package/dist/hooks/authors/author-avatars.js.map +1 -1
  12. package/dist/hooks/authors/authors.js +1 -1
  13. package/dist/hooks/authors/authors.js.map +1 -1
  14. package/dist/hooks/authors/utils.js.map +1 -1
  15. package/dist/hooks/comments.js +1 -1
  16. package/dist/hooks/comments.js.map +1 -1
  17. package/dist/hooks/communities.js +1 -1
  18. package/dist/hooks/communities.js.map +1 -1
  19. package/dist/hooks/feeds/feeds.d.ts.map +1 -1
  20. package/dist/hooks/feeds/feeds.js +9 -1
  21. package/dist/hooks/feeds/feeds.js.map +1 -1
  22. package/dist/hooks/pkc-rpc.js +1 -1
  23. package/dist/hooks/pkc-rpc.js.map +1 -1
  24. package/dist/hooks/replies.js +1 -1
  25. package/dist/hooks/replies.js.map +1 -1
  26. package/dist/hooks/states.js +1 -1
  27. package/dist/hooks/states.js.map +1 -1
  28. package/dist/lib/assert.d.ts +6 -0
  29. package/dist/lib/assert.d.ts.map +1 -0
  30. package/dist/lib/assert.js +17 -0
  31. package/dist/lib/assert.js.map +1 -0
  32. package/dist/lib/chain/chain.js +1 -1
  33. package/dist/lib/chain/chain.js.map +1 -1
  34. package/dist/lib/community-ref.js +1 -1
  35. package/dist/lib/community-ref.js.map +1 -1
  36. package/dist/lib/crosspost.js +1 -1
  37. package/dist/lib/crosspost.js.map +1 -1
  38. package/dist/lib/is-equal.d.ts +6 -0
  39. package/dist/lib/is-equal.d.ts.map +1 -0
  40. package/dist/lib/is-equal.js +100 -0
  41. package/dist/lib/is-equal.js.map +1 -0
  42. package/dist/lib/memoize.d.ts +9 -0
  43. package/dist/lib/memoize.d.ts.map +1 -0
  44. package/dist/lib/memoize.js +24 -0
  45. package/dist/lib/memoize.js.map +1 -0
  46. package/dist/lib/pkc-compat.js +1 -1
  47. package/dist/lib/pkc-compat.js.map +1 -1
  48. package/dist/lib/pkc-js/index.d.ts.map +1 -1
  49. package/dist/lib/pkc-js/index.js +23 -12
  50. package/dist/lib/pkc-js/index.js.map +1 -1
  51. package/dist/lib/pkc-js/pkc-js-mock-content.js +1 -1
  52. package/dist/lib/pkc-js/pkc-js-mock-content.js.map +1 -1
  53. package/dist/lib/protocol-compat.js +1 -1
  54. package/dist/lib/protocol-compat.js.map +1 -1
  55. package/dist/lib/utils/utils.js +1 -1
  56. package/dist/lib/utils/utils.js.map +1 -1
  57. package/dist/lib/validator.js +1 -1
  58. package/dist/lib/validator.js.map +1 -1
  59. package/dist/stores/accounts/accounts-actions-internal.js +2 -2
  60. package/dist/stores/accounts/accounts-actions-internal.js.map +1 -1
  61. package/dist/stores/accounts/accounts-actions.js +2 -2
  62. package/dist/stores/accounts/accounts-actions.js.map +1 -1
  63. package/dist/stores/accounts/accounts-database.js +2 -2
  64. package/dist/stores/accounts/accounts-database.js.map +1 -1
  65. package/dist/stores/accounts/accounts-store.js +1 -1
  66. package/dist/stores/accounts/accounts-store.js.map +1 -1
  67. package/dist/stores/accounts/utils.js +1 -1
  68. package/dist/stores/accounts/utils.js.map +1 -1
  69. package/dist/stores/authors-comments/authors-comments-store.js +1 -1
  70. package/dist/stores/authors-comments/authors-comments-store.js.map +1 -1
  71. package/dist/stores/authors-comments/utils.js.map +1 -1
  72. package/dist/stores/communities/communities-store.js +1 -1
  73. package/dist/stores/communities/communities-store.js.map +1 -1
  74. package/dist/stores/communities-pages/communities-pages-store.js +1 -1
  75. package/dist/stores/communities-pages/communities-pages-store.js.map +1 -1
  76. package/dist/stores/feeds/feed-sorter.d.ts +4 -0
  77. package/dist/stores/feeds/feed-sorter.d.ts.map +1 -1
  78. package/dist/stores/feeds/feed-sorter.js +35 -1
  79. package/dist/stores/feeds/feed-sorter.js.map +1 -1
  80. package/dist/stores/feeds/feeds-store.d.ts +3 -0
  81. package/dist/stores/feeds/feeds-store.d.ts.map +1 -1
  82. package/dist/stores/feeds/feeds-store.js +27 -4
  83. package/dist/stores/feeds/feeds-store.js.map +1 -1
  84. package/dist/stores/feeds/utils.d.ts +9 -0
  85. package/dist/stores/feeds/utils.d.ts.map +1 -1
  86. package/dist/stores/feeds/utils.js +81 -66
  87. package/dist/stores/feeds/utils.js.map +1 -1
  88. package/dist/stores/replies/replies-store.js +1 -1
  89. package/dist/stores/replies/replies-store.js.map +1 -1
  90. package/dist/stores/replies/utils.js.map +1 -1
  91. package/dist/stores/replies-pages/replies-pages-store.js +1 -1
  92. package/dist/stores/replies-pages/replies-pages-store.js.map +1 -1
  93. package/dist/types.d.ts +1 -0
  94. package/dist/types.d.ts.map +1 -1
  95. package/dist/types.js.map +1 -1
  96. package/package.json +1 -6
@@ -15,7 +15,7 @@ import accountsStore from "../accounts/index.js";
15
15
  import communitiesStore from "../communities/index.js";
16
16
  import localForageLru from "../../lib/localforage-lru/index.js";
17
17
  import createStore from "zustand";
18
- import assert from "assert";
18
+ import assert from "../../lib/assert.js";
19
19
  import { createPkcCommunity, getPkcCreateCommunity, normalizeCommentCommunityAddress, } from "../../lib/pkc-compat.js";
20
20
  import { getPostPageSortType } from "../../lib/page-sorts.js";
21
21
  const communitiesPagesDatabase = localForageLru.createInstance({
@@ -1 +1 @@
1
- {"version":3,"file":"communities-pages-store.js","sourceRoot":"","sources":["../../../src/stores/communities-pages/communities-pages-store.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAC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AwF;IACxF,8FAA8F;AAChG,CAAC,CAAC;AAEF,+BAA+B;AAC/B,MAAM,aAAa,GAAG,qBAAqB,CAAC,QAAQ,EAAE,CAAC;AACvD,qDAAqD;AACrD,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAS,EAAE;IACnD,gBAAgB,GAAG,EAAE,CAAC;IACtB,KAAK,MAAM,SAAS,IAAI,oBAAoB,EAAE,CAAC;QAC7C,OAAO,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;IACD,6BAA6B;IAC7B,SAAS,CAAC,OAAO,CAAC,CAAC,QAAa,EAAE,EAAE,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,CAAC;IACpE,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;IACrB,mDAAmD;IACnD,qBAAqB,CAAC,OAAO,EAAE,CAAC;IAChC,yBAAyB;IACzB,qBAAqB,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;AAChD,CAAC,CAAA,CAAC;AAEF,4CAA4C;AAC5C,MAAM,CAAC,MAAM,qCAAqC,GAAG,GAAS,EAAE;IAC9D,MAAM,cAAc,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,sCAAsC,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC;IAC9F,MAAM,0BAA0B,EAAE,CAAC;AACrC,CAAC,CAAA,CAAC;AAEF,eAAe,qBAAqB,CAAC","sourcesContent":["import utils from \"../../lib/utils\";\nimport Logger from \"@pkcprotocol/pkc-logger\";\n// include communities pages store with feeds for debugging\nexport const log = Logger(\"bitsocial-react-hooks:feeds:stores\");\nimport {\n Community,\n CommunityPage,\n CommunitiesPages,\n Account,\n Comment,\n Comments,\n} from \"../../types\";\nimport accountsStore from \"../accounts\";\nimport communitiesStore, { CommunitiesState } from \"../communities\";\nimport localForageLru from \"../../lib/localforage-lru\";\nimport createStore from \"zustand\";\nimport assert from \"assert\";\nimport {\n createPkcCommunity,\n getPkcCreateCommunity,\n normalizeCommentCommunityAddress,\n} from \"../../lib/pkc-compat\";\nimport { getPostPageSortType } from \"../../lib/page-sorts\";\n\nconst communitiesPagesDatabase = localForageLru.createInstance({\n name: \"bitsocialReactHooks-communitiesPages\",\n size: 500,\n});\n\nconst getCommunityPageStoreKey = (pageCid: string, pageType: string, accountId?: string) => {\n if (pageType === \"modQueue\") {\n assert(\n accountId && typeof accountId === \"string\",\n `getCommunityPageStoreKey accountId '${accountId}' invalid for modQueue`,\n );\n return `${accountId}:${pageCid}`;\n }\n return pageCid;\n};\n\n/** Freshness for comparison: max(updatedAt, timestamp, 0). Used to decide add vs replace per CID. Exported for coverage. */\nexport const getCommentFreshness = (comment: Comment | undefined): number =>\n Math.max(comment?.updatedAt ?? 0, comment?.timestamp ?? 0, 0);\n\n// reset all event listeners in between tests\nconst listeners: any = [];\n\ntype CommunitiesPagesState = {\n communitiesPages: CommunitiesPages;\n comments: Comments;\n addNextCommunityPageToStore: Function;\n invalidateCommunityPages: Function;\n addCommunityPageCommentsToStore: Function;\n};\n\nconst communitiesPagesStore = createStore<CommunitiesPagesState>(\n (setState: Function, getState: Function) => ({\n // TODO: eventually clear old pages and comments from memory\n communitiesPages: {},\n comments: {},\n\n addNextCommunityPageToStore: async (\n community: Community,\n sortType: string | undefined,\n account: Account,\n modQueue?: string[],\n ) => {\n assert(\n community?.address && typeof community?.address === \"string\",\n `communitiesPagesStore.addNextCommunityPageToStore community '${community}' invalid`,\n );\n assert(\n sortType === undefined || (typeof sortType === \"string\" && sortType.length > 0),\n `communitiesPagesStore.addNextCommunityPageToStore sortType '${sortType}' invalid`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesPagesStore.addNextCommunityPageToStore account '${account}' invalid`,\n );\n assert(\n !modQueue || Array.isArray(modQueue),\n `communitiesPagesStore.addNextCommunityPageToStore modQueue '${modQueue}' invalid`,\n );\n\n let pageType = \"posts\";\n if (modQueue?.[0]) {\n // TODO: allow multiple modQueue at once, fow now only use first in array\n // TODO: fix 'sortType' is not accurate variable name when pageType is 'modQueue'\n sortType = modQueue[0];\n pageType = \"modQueue\";\n }\n\n // check the preloaded posts on community.posts.pages first, then the community.posts.pageCids\n const communityFirstPageCid = getCommunityFirstPageCid(community, sortType, pageType);\n if (!communityFirstPageCid) {\n log(\n `communitiesPagesStore.addNextCommunityPageToStore community '${community?.address}' sortType '${sortType}' no communityFirstPageCid`,\n );\n return;\n }\n\n // all communities pages in store\n const { communitiesPages } = getState();\n // only specific pages of the community+sortType\n const communityPages = getCommunityPages(\n community,\n sortType,\n communitiesPages,\n pageType,\n account.id,\n );\n\n // if no pages exist yet, add the first page\n let pageCidToAdd: string;\n if (!communityPages.length) {\n pageCidToAdd = communityFirstPageCid;\n } else {\n const nextCid = communityPages[communityPages.length - 1]?.nextCid;\n // if last nextCid is undefined, reached end of pages\n if (!nextCid) {\n log.trace(\"communitiesPagesStore.addNextCommunityPageToStore no more pages\", {\n communityAddress: community.address,\n sortType,\n account,\n });\n return;\n }\n\n pageCidToAdd = nextCid;\n }\n\n // page is already added or pending\n const pageStoreKeyToAdd = getCommunityPageStoreKey(pageCidToAdd, pageType, account.id);\n if (communitiesPages[pageStoreKeyToAdd] || fetchPagePending[pageStoreKeyToAdd]) {\n return;\n }\n\n fetchPagePending[pageStoreKeyToAdd] = true;\n let page: CommunityPage;\n try {\n page = await fetchPage(pageCidToAdd, community.address, account, pageType);\n log.trace(\"communitiesPagesStore.addNextCommunityPageToStore community.posts.getPage\", {\n pageCid: pageCidToAdd,\n communityAddress: community.address,\n account,\n });\n } catch (e) {\n throw e;\n } finally {\n fetchPagePending[pageStoreKeyToAdd] = false;\n }\n\n // find new comments in the page\n const flattenedComments = utils.flattenCommentsPages(page);\n const { comments } = getState();\n let hasNewComments = false;\n const newComments: Comments = {};\n if (pageType !== \"modQueue\") {\n for (const comment of flattenedComments) {\n const normalizedComment = normalizeCommentCommunityAddress(comment) as Comment;\n const existing = comments[normalizedComment.cid];\n if (\n normalizedComment.cid &&\n (!existing || getCommentFreshness(normalizedComment) > getCommentFreshness(existing))\n ) {\n // don't clone the comment to save memory, comments remain a pointer to the page object\n newComments[normalizedComment.cid] = normalizedComment;\n hasNewComments = true;\n }\n }\n }\n\n setState(({ communitiesPages, comments }: any) => {\n const newState: any = {\n communitiesPages: { ...communitiesPages, [pageStoreKeyToAdd]: page },\n };\n if (hasNewComments) {\n newState.comments = { ...comments, ...newComments };\n }\n return newState;\n });\n log(\"communitiesPagesStore.addNextCommunityPageToStore\", {\n pageCid: pageCidToAdd,\n communityAddress: community.address,\n sortType,\n page,\n account,\n });\n\n // when publishing a comment, you don't yet know its CID\n // so when a new comment is fetched, check to see if it's your own\n // comment, and if yes, add the CID to your account comments database\n for (const comment of flattenedComments) {\n accountsStore\n .getState()\n .accountsActionsInternal.addCidToAccountComment(\n normalizeCommentCommunityAddress(comment) as Comment,\n )\n .catch((error: unknown) =>\n log.error(\n \"communitiesPagesStore.addNextCommunityPageToStore addCidToAccountComment error\",\n { comment, error },\n ),\n );\n }\n },\n\n invalidateCommunityPages: async (\n community: Community,\n sortType: string | undefined,\n modQueue?: string[],\n accountId?: string,\n ) => {\n assert(\n community?.address && typeof community?.address === \"string\",\n `communitiesPagesStore.invalidateCommunityPages community '${community}' invalid`,\n );\n assert(\n sortType === undefined || (typeof sortType === \"string\" && sortType.length > 0),\n `communitiesPagesStore.invalidateCommunityPages sortType '${sortType}' invalid`,\n );\n assert(\n !modQueue || Array.isArray(modQueue),\n `communitiesPagesStore.invalidateCommunityPages modQueue '${modQueue}' invalid`,\n );\n\n let pageType = \"posts\";\n if (modQueue?.[0]) {\n // TODO: allow multiple modQueue at once, for now only use first in array\n // TODO: fix 'sortType' is not accurate variable name when pageType is 'modQueue'\n sortType = modQueue[0];\n pageType = \"modQueue\";\n }\n\n const firstPageCid = getCommunityFirstPageCid(community, sortType, pageType);\n if (!firstPageCid) {\n return;\n }\n\n const { communitiesPages } = getState();\n const firstPageKey = getCommunityPageStoreKey(firstPageCid, pageType, accountId);\n const pageKeysToInvalidate = new Set<string>([firstPageKey]);\n let nextPageCid = communitiesPages[firstPageKey]?.nextCid;\n while (nextPageCid) {\n const nextPageKey = getCommunityPageStoreKey(nextPageCid, pageType, accountId);\n pageKeysToInvalidate.add(nextPageKey);\n nextPageCid = communitiesPages[nextPageKey]?.nextCid;\n }\n\n await Promise.all(\n [...pageKeysToInvalidate].map((pageKey) => communitiesPagesDatabase.removeItem(pageKey)),\n );\n\n setState(({ communitiesPages }: any) => {\n const nextCommunitiesPages = { ...communitiesPages };\n for (const pageKey of pageKeysToInvalidate) {\n delete nextCommunitiesPages[pageKey];\n }\n return { communitiesPages: nextCommunitiesPages };\n });\n },\n\n // communities contain preloaded pages, those page comments must be added separately\n addCommunityPageCommentsToStore: (community: Community) => {\n if (!community.posts?.pages) {\n return;\n }\n\n // find new comments in the page\n const flattenedComments = utils.flattenCommentsPages(community.posts.pages);\n const { comments } = getState();\n let hasNewComments = false;\n const newComments: Comments = {};\n for (const comment of flattenedComments) {\n const existing = comments[comment.cid];\n if (\n comment.cid &&\n (!existing || getCommentFreshness(comment) > getCommentFreshness(existing))\n ) {\n // don't clone the comment to save memory, comments remain a pointer to the page object\n newComments[comment.cid] = comment;\n hasNewComments = true;\n }\n }\n\n if (!hasNewComments) {\n return;\n }\n\n setState(({ comments }: any) => {\n return { comments: { ...comments, ...newComments } };\n });\n log(\"communitiesPagesStore.addCommunityPageCommentsToStore\", { community, newComments });\n },\n }),\n);\n\n// set clients states on communities store so the frontend can display it, dont persist in db because a reload cancels updating\nconst onCommunityPostsClientsStateChange =\n (communityAddress: string) =>\n (clientState: string, clientType: string, sortType: string, clientUrl: string) => {\n communitiesStore.setState((state: CommunitiesState) => {\n // make sure not undefined, sometimes happens in e2e tests\n if (!state.communities[communityAddress]) {\n return {};\n }\n const client = { state: clientState };\n const community = { ...state.communities[communityAddress] };\n community.posts = { ...community.posts };\n community.posts.clients = { ...community.posts.clients };\n community.posts.clients[clientType] = { ...community.posts.clients[clientType] };\n community.posts.clients[clientType][sortType] = {\n ...community.posts.clients[clientType][sortType],\n };\n community.posts.clients[clientType][sortType][clientUrl] = client;\n return { communities: { ...state.communities, [community.address]: community } };\n });\n };\n\nconst fetchPageCommunities: {\n [accountId: string]: { pkc: any; communities: { [communityAddress: string]: any } };\n} = {}; // cache created community clients per account because creating them can be slow\nlet fetchPagePending: { [key: string]: boolean } = {};\nconst fetchPage = async (\n pageCid: string,\n communityAddress: string,\n account: Account,\n pageType: string,\n) => {\n // community page is cached\n const pageStoreKey = getCommunityPageStoreKey(pageCid, pageType, account.id);\n const cachedCommunityPage = await communitiesPagesDatabase.getItem(pageStoreKey);\n if (cachedCommunityPage) {\n return cachedCommunityPage;\n }\n if (!fetchPageCommunities[account.id] || fetchPageCommunities[account.id].pkc !== account.pkc) {\n fetchPageCommunities[account.id] = { pkc: account.pkc, communities: {} };\n }\n const accountCommunities = fetchPageCommunities[account.id].communities;\n if (!accountCommunities[communityAddress]) {\n accountCommunities[communityAddress] = await createPkcCommunity(account.pkc, {\n address: communityAddress,\n });\n listeners.push(accountCommunities[communityAddress]);\n\n // set clients states on communities store so the frontend can display it\n utils.pageClientsOnStateChange(\n accountCommunities[communityAddress][pageType]?.clients,\n onCommunityPostsClientsStateChange(communityAddress),\n );\n }\n\n const onError = (error: any) =>\n log.error(\n `communitiesPagesStore community '${communityAddress}' failed community.posts.getPage page cid '${pageCid}':`,\n error,\n );\n const fetchedCommunityPage = await utils.retryInfinity(\n () => accountCommunities[communityAddress][pageType].getPage({ cid: pageCid }),\n { onError },\n );\n await communitiesPagesDatabase.setItem(pageStoreKey, utils.clone(fetchedCommunityPage));\n return fetchedCommunityPage;\n};\n\n/**\n * Util function to get all pages in the store for a\n * specific community+sortType using `CommunityPage.nextCid`\n */\nexport const getCommunityPages = (\n community: Community,\n sortType: string | undefined,\n communitiesPages: CommunitiesPages,\n pageType: string,\n accountId?: string,\n) => {\n assert(\n communitiesPages && typeof communitiesPages === \"object\",\n `getCommunityPages communitiesPages '${communitiesPages}' invalid`,\n );\n const pages: CommunityPage[] = [];\n const firstPageCid = getCommunityFirstPageCid(community, sortType, pageType);\n // community has no pages\n // TODO: if a loaded community doesn't have a first page, it's unclear what we should do\n // should we try to use another sort type by default, like 'hot', or should we just ignore it?\n // 'return pages' to ignore it for now\n if (!firstPageCid) {\n return pages;\n }\n const firstPage = communitiesPages[getCommunityPageStoreKey(firstPageCid, pageType, accountId)];\n if (!firstPage) {\n return pages;\n }\n pages.push(firstPage);\n while (true) {\n const nextCid = pages[pages.length - 1]?.nextCid;\n const nextPageKey = nextCid && getCommunityPageStoreKey(nextCid, pageType, accountId);\n const communityPage = nextPageKey && communitiesPages[nextPageKey];\n if (!communityPage) {\n return pages;\n }\n pages.push(communityPage);\n }\n};\n\nexport const getCommunityFirstPageCid = (\n community: Community,\n sortType: string | undefined,\n pageType = \"posts\",\n) => {\n assert(\n community && typeof community === \"object\",\n `getCommunityFirstPageCid community '${community}' invalid`,\n );\n assert(\n sortType === undefined || (typeof sortType === \"string\" && sortType.length > 0),\n `getCommunityFirstPageCid sortType '${sortType}' invalid`,\n );\n // posts served client-side from a complete preloaded page read that page instead of their own\n const pageSortType = pageType === \"posts\" ? getPostPageSortType(community, sortType) : sortType;\n if (!pageSortType) {\n return;\n }\n // community has preloaded posts for sort type\n if (community[pageType]?.pages?.[pageSortType]?.comments) {\n return community[pageType]?.pages?.[pageSortType]?.nextCid;\n }\n return community[pageType]?.pageCids?.[pageSortType];\n\n // TODO: if a loaded community doesn't have a first page, it's unclear what we should do\n // should we try to use another sort type by default, like 'hot', or should we just ignore it?\n};\n\n// reset store in between tests\nconst originalState = communitiesPagesStore.getState();\n// async function because some stores have async init\nexport const resetCommunitiesPagesStore = async () => {\n fetchPagePending = {};\n for (const accountId in fetchPageCommunities) {\n delete fetchPageCommunities[accountId];\n }\n // remove all event listeners\n listeners.forEach((listener: any) => listener.removeAllListeners());\n listeners.length = 0;\n // destroy all component subscriptions to the store\n communitiesPagesStore.destroy();\n // restore original state\n communitiesPagesStore.setState(originalState);\n};\n\n// reset database and store in between tests\nexport const resetCommunitiesPagesDatabaseAndStore = async () => {\n await localForageLru.createInstance({ name: \"bitsocialReactHooks-communitiesPages\" }).clear();\n await resetCommunitiesPagesStore();\n};\n\nexport default communitiesPagesStore;\n"]}
1
+ {"version":3,"file":"communities-pages-store.js","sourceRoot":"","sources":["../../../src/stores/communities-pages/communities-pages-store.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,KAAK,MAAM,iBAAiB,CAAC;AACpC,OAAO,MAAM,MAAM,yBAAyB,CAAC;AAC7C,2DAA2D;AAC3D,MAAM,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC,oCAAoC,CAAC,CAAC;AAShE,OAAO,aAAa,MAAM,aAAa,CAAC;AACxC,OAAO,gBAAsC,MAAM,gBAAgB,CAAC;AACpE,OAAO,cAAc,MAAM,2BAA2B,CAAC;AACvD,OAAO,WAAW,MAAM,SAAS,CAAC;AAClC,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,gCAAgC,GACjC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,MAAM,wBAAwB,GAAG,cAAc,CAAC,cAAc,CAAC;IAC7D,IAAI,EAAE,sCAAsC;IAC5C,IAAI,EAAE,GAAG;CACV,CAAC,CAAC;AAEH,MAAM,wBAAwB,GAAG,CAAC,OAAe,EAAE,QAAgB,EAAE,SAAkB,EAAE,EAAE;IACzF,IAAI,QAAQ,KAAK,UAAU,EAAE,CAAC;QAC5B,MAAM,CACJ,SAAS,IAAI,OAAO,SAAS,KAAK,QAAQ,EAC1C,uCAAuC,SAAS,wBAAwB,CACzE,CAAC;QACF,OAAO,GAAG,SAAS,IAAI,OAAO,EAAE,CAAC;IACnC,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEF,4HAA4H;AAC5H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pkcprotocol/pkc-logger\";\n// include communities pages store with feeds for debugging\nexport const log = Logger(\"bitsocial-react-hooks:feeds:stores\");\nimport {\n Community,\n CommunityPage,\n CommunitiesPages,\n Account,\n Comment,\n Comments,\n} from \"../../types\";\nimport accountsStore from \"../accounts\";\nimport communitiesStore, { CommunitiesState } from \"../communities\";\nimport localForageLru from \"../../lib/localforage-lru\";\nimport createStore from \"zustand\";\nimport assert from \"../../lib/assert\";\nimport {\n createPkcCommunity,\n getPkcCreateCommunity,\n normalizeCommentCommunityAddress,\n} from \"../../lib/pkc-compat\";\nimport { getPostPageSortType } from \"../../lib/page-sorts\";\n\nconst communitiesPagesDatabase = localForageLru.createInstance({\n name: \"bitsocialReactHooks-communitiesPages\",\n size: 500,\n});\n\nconst getCommunityPageStoreKey = (pageCid: string, pageType: string, accountId?: string) => {\n if (pageType === \"modQueue\") {\n assert(\n accountId && typeof accountId === \"string\",\n `getCommunityPageStoreKey accountId '${accountId}' invalid for modQueue`,\n );\n return `${accountId}:${pageCid}`;\n }\n return pageCid;\n};\n\n/** Freshness for comparison: max(updatedAt, timestamp, 0). Used to decide add vs replace per CID. Exported for coverage. */\nexport const getCommentFreshness = (comment: Comment | undefined): number =>\n Math.max(comment?.updatedAt ?? 0, comment?.timestamp ?? 0, 0);\n\n// reset all event listeners in between tests\nconst listeners: any = [];\n\ntype CommunitiesPagesState = {\n communitiesPages: CommunitiesPages;\n comments: Comments;\n addNextCommunityPageToStore: Function;\n invalidateCommunityPages: Function;\n addCommunityPageCommentsToStore: Function;\n};\n\nconst communitiesPagesStore = createStore<CommunitiesPagesState>(\n (setState: Function, getState: Function) => ({\n // TODO: eventually clear old pages and comments from memory\n communitiesPages: {},\n comments: {},\n\n addNextCommunityPageToStore: async (\n community: Community,\n sortType: string | undefined,\n account: Account,\n modQueue?: string[],\n ) => {\n assert(\n community?.address && typeof community?.address === \"string\",\n `communitiesPagesStore.addNextCommunityPageToStore community '${community}' invalid`,\n );\n assert(\n sortType === undefined || (typeof sortType === \"string\" && sortType.length > 0),\n `communitiesPagesStore.addNextCommunityPageToStore sortType '${sortType}' invalid`,\n );\n assert(\n typeof getPkcCreateCommunity(account?.pkc) === \"function\",\n `communitiesPagesStore.addNextCommunityPageToStore account '${account}' invalid`,\n );\n assert(\n !modQueue || Array.isArray(modQueue),\n `communitiesPagesStore.addNextCommunityPageToStore modQueue '${modQueue}' invalid`,\n );\n\n let pageType = \"posts\";\n if (modQueue?.[0]) {\n // TODO: allow multiple modQueue at once, fow now only use first in array\n // TODO: fix 'sortType' is not accurate variable name when pageType is 'modQueue'\n sortType = modQueue[0];\n pageType = \"modQueue\";\n }\n\n // check the preloaded posts on community.posts.pages first, then the community.posts.pageCids\n const communityFirstPageCid = getCommunityFirstPageCid(community, sortType, pageType);\n if (!communityFirstPageCid) {\n log(\n `communitiesPagesStore.addNextCommunityPageToStore community '${community?.address}' sortType '${sortType}' no communityFirstPageCid`,\n );\n return;\n }\n\n // all communities pages in store\n const { communitiesPages } = getState();\n // only specific pages of the community+sortType\n const communityPages = getCommunityPages(\n community,\n sortType,\n communitiesPages,\n pageType,\n account.id,\n );\n\n // if no pages exist yet, add the first page\n let pageCidToAdd: string;\n if (!communityPages.length) {\n pageCidToAdd = communityFirstPageCid;\n } else {\n const nextCid = communityPages[communityPages.length - 1]?.nextCid;\n // if last nextCid is undefined, reached end of pages\n if (!nextCid) {\n log.trace(\"communitiesPagesStore.addNextCommunityPageToStore no more pages\", {\n communityAddress: community.address,\n sortType,\n account,\n });\n return;\n }\n\n pageCidToAdd = nextCid;\n }\n\n // page is already added or pending\n const pageStoreKeyToAdd = getCommunityPageStoreKey(pageCidToAdd, pageType, account.id);\n if (communitiesPages[pageStoreKeyToAdd] || fetchPagePending[pageStoreKeyToAdd]) {\n return;\n }\n\n fetchPagePending[pageStoreKeyToAdd] = true;\n let page: CommunityPage;\n try {\n page = await fetchPage(pageCidToAdd, community.address, account, pageType);\n log.trace(\"communitiesPagesStore.addNextCommunityPageToStore community.posts.getPage\", {\n pageCid: pageCidToAdd,\n communityAddress: community.address,\n account,\n });\n } catch (e) {\n throw e;\n } finally {\n fetchPagePending[pageStoreKeyToAdd] = false;\n }\n\n // find new comments in the page\n const flattenedComments = utils.flattenCommentsPages(page);\n const { comments } = getState();\n let hasNewComments = false;\n const newComments: Comments = {};\n if (pageType !== \"modQueue\") {\n for (const comment of flattenedComments) {\n const normalizedComment = normalizeCommentCommunityAddress(comment) as Comment;\n const existing = comments[normalizedComment.cid];\n if (\n normalizedComment.cid &&\n (!existing || getCommentFreshness(normalizedComment) > getCommentFreshness(existing))\n ) {\n // don't clone the comment to save memory, comments remain a pointer to the page object\n newComments[normalizedComment.cid] = normalizedComment;\n hasNewComments = true;\n }\n }\n }\n\n setState(({ communitiesPages, comments }: any) => {\n const newState: any = {\n communitiesPages: { ...communitiesPages, [pageStoreKeyToAdd]: page },\n };\n if (hasNewComments) {\n newState.comments = { ...comments, ...newComments };\n }\n return newState;\n });\n log(\"communitiesPagesStore.addNextCommunityPageToStore\", {\n pageCid: pageCidToAdd,\n communityAddress: community.address,\n sortType,\n page,\n account,\n });\n\n // when publishing a comment, you don't yet know its CID\n // so when a new comment is fetched, check to see if it's your own\n // comment, and if yes, add the CID to your account comments database\n for (const comment of flattenedComments) {\n accountsStore\n .getState()\n .accountsActionsInternal.addCidToAccountComment(\n normalizeCommentCommunityAddress(comment) as Comment,\n )\n .catch((error: unknown) =>\n log.error(\n \"communitiesPagesStore.addNextCommunityPageToStore addCidToAccountComment error\",\n { comment, error },\n ),\n );\n }\n },\n\n invalidateCommunityPages: async (\n community: Community,\n sortType: string | undefined,\n modQueue?: string[],\n accountId?: string,\n ) => {\n assert(\n community?.address && typeof community?.address === \"string\",\n `communitiesPagesStore.invalidateCommunityPages community '${community}' invalid`,\n );\n assert(\n sortType === undefined || (typeof sortType === \"string\" && sortType.length > 0),\n `communitiesPagesStore.invalidateCommunityPages sortType '${sortType}' invalid`,\n );\n assert(\n !modQueue || Array.isArray(modQueue),\n `communitiesPagesStore.invalidateCommunityPages modQueue '${modQueue}' invalid`,\n );\n\n let pageType = \"posts\";\n if (modQueue?.[0]) {\n // TODO: allow multiple modQueue at once, for now only use first in array\n // TODO: fix 'sortType' is not accurate variable name when pageType is 'modQueue'\n sortType = modQueue[0];\n pageType = \"modQueue\";\n }\n\n const firstPageCid = getCommunityFirstPageCid(community, sortType, pageType);\n if (!firstPageCid) {\n return;\n }\n\n const { communitiesPages } = getState();\n const firstPageKey = getCommunityPageStoreKey(firstPageCid, pageType, accountId);\n const pageKeysToInvalidate = new Set<string>([firstPageKey]);\n let nextPageCid = communitiesPages[firstPageKey]?.nextCid;\n while (nextPageCid) {\n const nextPageKey = getCommunityPageStoreKey(nextPageCid, pageType, accountId);\n pageKeysToInvalidate.add(nextPageKey);\n nextPageCid = communitiesPages[nextPageKey]?.nextCid;\n }\n\n await Promise.all(\n [...pageKeysToInvalidate].map((pageKey) => communitiesPagesDatabase.removeItem(pageKey)),\n );\n\n setState(({ communitiesPages }: any) => {\n const nextCommunitiesPages = { ...communitiesPages };\n for (const pageKey of pageKeysToInvalidate) {\n delete nextCommunitiesPages[pageKey];\n }\n return { communitiesPages: nextCommunitiesPages };\n });\n },\n\n // communities contain preloaded pages, those page comments must be added separately\n addCommunityPageCommentsToStore: (community: Community) => {\n if (!community.posts?.pages) {\n return;\n }\n\n // find new comments in the page\n const flattenedComments = utils.flattenCommentsPages(community.posts.pages);\n const { comments } = getState();\n let hasNewComments = false;\n const newComments: Comments = {};\n for (const comment of flattenedComments) {\n const existing = comments[comment.cid];\n if (\n comment.cid &&\n (!existing || getCommentFreshness(comment) > getCommentFreshness(existing))\n ) {\n // don't clone the comment to save memory, comments remain a pointer to the page object\n newComments[comment.cid] = comment;\n hasNewComments = true;\n }\n }\n\n if (!hasNewComments) {\n return;\n }\n\n setState(({ comments }: any) => {\n return { comments: { ...comments, ...newComments } };\n });\n log(\"communitiesPagesStore.addCommunityPageCommentsToStore\", { community, newComments });\n },\n }),\n);\n\n// set clients states on communities store so the frontend can display it, dont persist in db because a reload cancels updating\nconst onCommunityPostsClientsStateChange =\n (communityAddress: string) =>\n (clientState: string, clientType: string, sortType: string, clientUrl: string) => {\n communitiesStore.setState((state: CommunitiesState) => {\n // make sure not undefined, sometimes happens in e2e tests\n if (!state.communities[communityAddress]) {\n return {};\n }\n const client = { state: clientState };\n const community = { ...state.communities[communityAddress] };\n community.posts = { ...community.posts };\n community.posts.clients = { ...community.posts.clients };\n community.posts.clients[clientType] = { ...community.posts.clients[clientType] };\n community.posts.clients[clientType][sortType] = {\n ...community.posts.clients[clientType][sortType],\n };\n community.posts.clients[clientType][sortType][clientUrl] = client;\n return { communities: { ...state.communities, [community.address]: community } };\n });\n };\n\nconst fetchPageCommunities: {\n [accountId: string]: { pkc: any; communities: { [communityAddress: string]: any } };\n} = {}; // cache created community clients per account because creating them can be slow\nlet fetchPagePending: { [key: string]: boolean } = {};\nconst fetchPage = async (\n pageCid: string,\n communityAddress: string,\n account: Account,\n pageType: string,\n) => {\n // community page is cached\n const pageStoreKey = getCommunityPageStoreKey(pageCid, pageType, account.id);\n const cachedCommunityPage = await communitiesPagesDatabase.getItem(pageStoreKey);\n if (cachedCommunityPage) {\n return cachedCommunityPage;\n }\n if (!fetchPageCommunities[account.id] || fetchPageCommunities[account.id].pkc !== account.pkc) {\n fetchPageCommunities[account.id] = { pkc: account.pkc, communities: {} };\n }\n const accountCommunities = fetchPageCommunities[account.id].communities;\n if (!accountCommunities[communityAddress]) {\n accountCommunities[communityAddress] = await createPkcCommunity(account.pkc, {\n address: communityAddress,\n });\n listeners.push(accountCommunities[communityAddress]);\n\n // set clients states on communities store so the frontend can display it\n utils.pageClientsOnStateChange(\n accountCommunities[communityAddress][pageType]?.clients,\n onCommunityPostsClientsStateChange(communityAddress),\n );\n }\n\n const onError = (error: any) =>\n log.error(\n `communitiesPagesStore community '${communityAddress}' failed community.posts.getPage page cid '${pageCid}':`,\n error,\n );\n const fetchedCommunityPage = await utils.retryInfinity(\n () => accountCommunities[communityAddress][pageType].getPage({ cid: pageCid }),\n { onError },\n );\n await communitiesPagesDatabase.setItem(pageStoreKey, utils.clone(fetchedCommunityPage));\n return fetchedCommunityPage;\n};\n\n/**\n * Util function to get all pages in the store for a\n * specific community+sortType using `CommunityPage.nextCid`\n */\nexport const getCommunityPages = (\n community: Community,\n sortType: string | undefined,\n communitiesPages: CommunitiesPages,\n pageType: string,\n accountId?: string,\n) => {\n assert(\n communitiesPages && typeof communitiesPages === \"object\",\n `getCommunityPages communitiesPages '${communitiesPages}' invalid`,\n );\n const pages: CommunityPage[] = [];\n const firstPageCid = getCommunityFirstPageCid(community, sortType, pageType);\n // community has no pages\n // TODO: if a loaded community doesn't have a first page, it's unclear what we should do\n // should we try to use another sort type by default, like 'hot', or should we just ignore it?\n // 'return pages' to ignore it for now\n if (!firstPageCid) {\n return pages;\n }\n const firstPage = communitiesPages[getCommunityPageStoreKey(firstPageCid, pageType, accountId)];\n if (!firstPage) {\n return pages;\n }\n pages.push(firstPage);\n while (true) {\n const nextCid = pages[pages.length - 1]?.nextCid;\n const nextPageKey = nextCid && getCommunityPageStoreKey(nextCid, pageType, accountId);\n const communityPage = nextPageKey && communitiesPages[nextPageKey];\n if (!communityPage) {\n return pages;\n }\n pages.push(communityPage);\n }\n};\n\nexport const getCommunityFirstPageCid = (\n community: Community,\n sortType: string | undefined,\n pageType = \"posts\",\n) => {\n assert(\n community && typeof community === \"object\",\n `getCommunityFirstPageCid community '${community}' invalid`,\n );\n assert(\n sortType === undefined || (typeof sortType === \"string\" && sortType.length > 0),\n `getCommunityFirstPageCid sortType '${sortType}' invalid`,\n );\n // posts served client-side from a complete preloaded page read that page instead of their own\n const pageSortType = pageType === \"posts\" ? getPostPageSortType(community, sortType) : sortType;\n if (!pageSortType) {\n return;\n }\n // community has preloaded posts for sort type\n if (community[pageType]?.pages?.[pageSortType]?.comments) {\n return community[pageType]?.pages?.[pageSortType]?.nextCid;\n }\n return community[pageType]?.pageCids?.[pageSortType];\n\n // TODO: if a loaded community doesn't have a first page, it's unclear what we should do\n // should we try to use another sort type by default, like 'hot', or should we just ignore it?\n};\n\n// reset store in between tests\nconst originalState = communitiesPagesStore.getState();\n// async function because some stores have async init\nexport const resetCommunitiesPagesStore = async () => {\n fetchPagePending = {};\n for (const accountId in fetchPageCommunities) {\n delete fetchPageCommunities[accountId];\n }\n // remove all event listeners\n listeners.forEach((listener: any) => listener.removeAllListeners());\n listeners.length = 0;\n // destroy all component subscriptions to the store\n communitiesPagesStore.destroy();\n // restore original state\n communitiesPagesStore.setState(originalState);\n};\n\n// reset database and store in between tests\nexport const resetCommunitiesPagesDatabaseAndStore = async () => {\n await localForageLru.createInstance({ name: \"bitsocialReactHooks-communitiesPages\" }).clear();\n await resetCommunitiesPagesStore();\n};\n\nexport default communitiesPagesStore;\n"]}
@@ -1,5 +1,9 @@
1
1
  declare const _default: {
2
2
  sort: (sortType: string | undefined, feed: any[]) => any[];
3
+ merge: (sortType: string | undefined, feeds: {
4
+ posts: any[];
5
+ keepOrder: boolean;
6
+ }[]) => any[];
3
7
  };
4
8
  export default _default;
5
9
  //# sourceMappingURL=feed-sorter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"feed-sorter.d.ts","sourceRoot":"","sources":["../../../src/stores/feeds/feed-sorter.ts"],"names":[],"mappings":";qBA8IwB,MAAM,GAAG,SAAS,QAAQ,GAAG,EAAE;;AAavD,wBAAwB"}
1
+ {"version":3,"file":"feed-sorter.d.ts","sourceRoot":"","sources":["../../../src/stores/feeds/feed-sorter.ts"],"names":[],"mappings":";qBA8IwB,MAAM,GAAG,SAAS,QAAQ,GAAG,EAAE;sBAmB9B,MAAM,GAAG,SAAS,SAAS;QAAE,KAAK,EAAE,GAAG,EAAE,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,EAAE;;AAoC1F,wBAA+B"}
@@ -137,5 +137,39 @@ const sort = (sortType, feed) => {
137
137
  feed = feed.filter((post) => !post.pinned);
138
138
  return [...pinnedPosts, ...sorter(feed)];
139
139
  };
140
- export default { sort };
140
+ /**
141
+ * Interleave several communities' posts. A feed that keeps its order (a community's sort file, which
142
+ * the client cannot reproduce) is never reordered and the others get the built-in sort. The next post
143
+ * is whichever feed's next post the built-in sorter ranks first, so a thread never rises above one
144
+ * its own community ranks higher, and feeds that all use the built-in sort merge as one sort.
145
+ */
146
+ const merge = (sortType, feeds) => {
147
+ const nonEmptyFeeds = feeds.filter(({ posts }) => posts.length > 0);
148
+ if (nonEmptyFeeds.length === 1 && nonEmptyFeeds[0].keepOrder) {
149
+ return nonEmptyFeeds[0].posts;
150
+ }
151
+ const ranks = new Map();
152
+ sort(sortType, nonEmptyFeeds.flatMap(({ posts }) => posts)).forEach((post, index) => ranks.set(post, index));
153
+ const rankOf = (post) => ranks.get(post);
154
+ const orderedFeeds = nonEmptyFeeds.map(({ posts, keepOrder }) => keepOrder ? posts : [...posts].sort((a, b) => rankOf(a) - rankOf(b)));
155
+ const nextIndexes = orderedFeeds.map(() => 0);
156
+ const postCount = orderedFeeds.reduce((count, posts) => count + posts.length, 0);
157
+ const merged = [];
158
+ while (merged.length < postCount) {
159
+ let nextFeedIndex = -1;
160
+ for (const [feedIndex, posts] of orderedFeeds.entries()) {
161
+ if (nextIndexes[feedIndex] === posts.length) {
162
+ continue;
163
+ }
164
+ if (nextFeedIndex === -1 ||
165
+ rankOf(posts[nextIndexes[feedIndex]]) <
166
+ rankOf(orderedFeeds[nextFeedIndex][nextIndexes[nextFeedIndex]])) {
167
+ nextFeedIndex = feedIndex;
168
+ }
169
+ }
170
+ merged.push(orderedFeeds[nextFeedIndex][nextIndexes[nextFeedIndex]++]);
171
+ }
172
+ return merged;
173
+ };
174
+ export default { sort, merge };
141
175
  //# sourceMappingURL=feed-sorter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"feed-sorter.js","sourceRoot":"","sources":["../../../src/stores/feeds/feed-sorter.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,MAAM,CAAC,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,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAEvD,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,OAAO,CAAC,GAAG,WAAW,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AAC3C,CAAC,CAAC;AAEF,eAAe,EAAE,IAAI,EAAE,CAAC","sourcesContent":["/** Single fallback for numeric values to reduce Istanbul branch sites */\nconst n = (v: unknown): number => (typeof v === \"number\" && !Number.isNaN(v) ? v : 0);\n\nconst sortByTop = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n for (const post of feed) {\n const score = post.upvoteCount - post.downvoteCount || 0;\n postScores[post.cid] = score;\n }\n return feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\n/**\n * Sort by controversial is made using relative score, to encourage small communities to grow\n * and to not incentivize communities to inflate their vote counts\n */\nconst sortByControversial = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n for (const post of feed) {\n let upvoteCount = n(post.upvoteCount) + 1; // reddit initial upvotes is 1, pkc is 0\n const downvoteCount = n(post.downvoteCount);\n const magnitude = upvoteCount + downvoteCount;\n const balance =\n upvoteCount > downvoteCount\n ? downvoteCount / upvoteCount\n : upvoteCount / (downvoteCount || 1);\n postScores[post.cid] = Math.pow(magnitude, balance);\n }\n return feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\n/**\n * Sort by hot is made using relative score, to encourage small communities to grow\n * and to not incentivize communities to inflate their vote counts\n * Note: a sub with not many posts will be given very high priority\n */\nconst sortByHot = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n const round = (number: number, decimalPlaces: number) => {\n const factorOfTen = Math.pow(10, decimalPlaces);\n return Math.round(number * factorOfTen) / factorOfTen;\n };\n for (const post of feed) {\n let score = n(post.upvoteCount) - n(post.downvoteCount) + 1;\n const order = Math.log10(Math.max(Math.abs(score), 1));\n let sign = 0;\n if (score > 0) sign = 1;\n else if (score < 0) sign = -1;\n const seconds = n(post.timestamp) - 1134028003;\n postScores[post.cid] = round(sign * order + seconds / 45000, 7);\n }\n return feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\n/**\n * Sort by new is made using relative timestamp score, to encourage small communities to grow\n * and to not incentivize communities to inflate their timestamp\n */\nconst sortByNew = (feed: any[]) =>\n feed\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(b.timestamp) - n(a.timestamp));\n\n/**\n * Sort by active is made using relative lastReplyTimestamp score, to encourage small communities to grow\n * and to not incentivize communities to inflate their lastReplyTimestamp\n */\nconst sortByActive = (feed: any[]) =>\n feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort(\n (a, b) => n(b.lastReplyTimestamp ?? b.timestamp) - n(a.lastReplyTimestamp ?? a.timestamp),\n );\n\nconst sortByOld = (feed: any[]) =>\n feed\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(a.timestamp) - n(b.timestamp));\n\n// \"best\" sort from reddit replies\n// https://web.archive.org/web/20100305052116/http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html\n// https://medium.com/hacking-and-gonzo/how-reddit-ranking-algorithms-work-ef111e33d0d9\n// http://www.evanmiller.org/how-not-to-sort-by-average-rating.html\n// https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/lib/db/_sorts.pyx#L70\nconst sortByBest = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n for (const post of feed) {\n const upvoteCount = n(post.upvoteCount) + 1;\n const downvoteCount = n(post.downvoteCount);\n const total = upvoteCount + downvoteCount;\n const score =\n total === 0\n ? 0\n : (() => {\n const z = 1.281551565545;\n const p = upvoteCount / total;\n const left = p + (1 / (2 * total)) * z * z;\n const right = z * Math.sqrt((p * (1 - p)) / total + (z * z) / (4 * total * total));\n const under = 1 + (1 / total) * z * z;\n return (left - right) / under;\n })();\n postScores[post.cid] = score;\n }\n return feed\n .sort((a, b) => n(a.timestamp) - n(b.timestamp))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\nconst sorters: Record<string, (feed: any[]) => any[]> = {\n new: sortByNew,\n newFlat: sortByNew,\n hot: sortByHot,\n top: sortByTop,\n topHour: sortByTop,\n topDay: sortByTop,\n topWeek: sortByTop,\n topMonth: sortByTop,\n topYear: sortByTop,\n topAll: sortByTop,\n controversial: sortByControversial,\n controversialHour: sortByControversial,\n controversialDay: sortByControversial,\n controversialWeek: sortByControversial,\n controversialMonth: sortByControversial,\n controversialYear: sortByControversial,\n controversialAll: sortByControversial,\n active: sortByActive,\n old: sortByOld,\n oldFlat: sortByOld,\n best: sortByBest,\n};\n\nconst sort = (sortType: string | undefined, feed: any[]) => {\n const sorter = sortType && sorters[sortType];\n if (!sorter) {\n return feed;\n }\n // NOTE: pinned posts are not sorted, maybe in a future version we can sort them based on something\n // NOTE: with useReplies({flat: true}), nested pins are at the top, unclear yet what we should do with them\n const pinnedPosts = feed.filter((post) => post.pinned);\n\n feed = feed.filter((post) => !post.pinned);\n return [...pinnedPosts, ...sorter(feed)];\n};\n\nexport default { sort };\n"]}
1
+ {"version":3,"file":"feed-sorter.js","sourceRoot":"","sources":["../../../src/stores/feeds/feed-sorter.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,MAAM,CAAC,GAAG,CAAC,CAAU,EAAU,EAAE,CAAC,CAAC,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C,CAAC,CAAC,CAAC,CACrE,CAAC;IACF,MAAM,WAAW,GAAG,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IAC9C,MAAM,SAAS,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACjF,MAAM,MAAM,GAAU,EAAE,CAAC;IACzB,OAAO,MAAM,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;QACjC,IAAI,aAAa,GAAG,CAAC,CAAC,CAAC;QACvB,KAAK,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,YAAY,CAAC,OAAO,EAAE,EAAE,CAAC;YACxD,IAAI,WAAW,CAAC,SAAS,CAAC,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC;gBAC5C,SAAS;YACX,CAAC;YACD,IACE,aAAa,KAAK,CAAC,CAAC;gBACpB,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC;oBACnC,MAAM,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,CAAC,EACjE,CAAC;gBACD,aAAa,GAAG,SAAS,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAEF,eAAe,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC","sourcesContent":["/** Single fallback for numeric values to reduce Istanbul branch sites */\nconst n = (v: unknown): number => (typeof v === \"number\" && !Number.isNaN(v) ? v : 0);\n\nconst sortByTop = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n for (const post of feed) {\n const score = post.upvoteCount - post.downvoteCount || 0;\n postScores[post.cid] = score;\n }\n return feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\n/**\n * Sort by controversial is made using relative score, to encourage small communities to grow\n * and to not incentivize communities to inflate their vote counts\n */\nconst sortByControversial = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n for (const post of feed) {\n let upvoteCount = n(post.upvoteCount) + 1; // reddit initial upvotes is 1, pkc is 0\n const downvoteCount = n(post.downvoteCount);\n const magnitude = upvoteCount + downvoteCount;\n const balance =\n upvoteCount > downvoteCount\n ? downvoteCount / upvoteCount\n : upvoteCount / (downvoteCount || 1);\n postScores[post.cid] = Math.pow(magnitude, balance);\n }\n return feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\n/**\n * Sort by hot is made using relative score, to encourage small communities to grow\n * and to not incentivize communities to inflate their vote counts\n * Note: a sub with not many posts will be given very high priority\n */\nconst sortByHot = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n const round = (number: number, decimalPlaces: number) => {\n const factorOfTen = Math.pow(10, decimalPlaces);\n return Math.round(number * factorOfTen) / factorOfTen;\n };\n for (const post of feed) {\n let score = n(post.upvoteCount) - n(post.downvoteCount) + 1;\n const order = Math.log10(Math.max(Math.abs(score), 1));\n let sign = 0;\n if (score > 0) sign = 1;\n else if (score < 0) sign = -1;\n const seconds = n(post.timestamp) - 1134028003;\n postScores[post.cid] = round(sign * order + seconds / 45000, 7);\n }\n return feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\n/**\n * Sort by new is made using relative timestamp score, to encourage small communities to grow\n * and to not incentivize communities to inflate their timestamp\n */\nconst sortByNew = (feed: any[]) =>\n feed\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(b.timestamp) - n(a.timestamp));\n\n/**\n * Sort by active is made using relative lastReplyTimestamp score, to encourage small communities to grow\n * and to not incentivize communities to inflate their lastReplyTimestamp\n */\nconst sortByActive = (feed: any[]) =>\n feed\n .sort((a, b) => n(b.timestamp) - n(a.timestamp))\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort(\n (a, b) => n(b.lastReplyTimestamp ?? b.timestamp) - n(a.lastReplyTimestamp ?? a.timestamp),\n );\n\nconst sortByOld = (feed: any[]) =>\n feed\n .sort((a, b) => n(b.upvoteCount) - n(a.upvoteCount))\n .sort((a, b) => n(a.timestamp) - n(b.timestamp));\n\n// \"best\" sort from reddit replies\n// https://web.archive.org/web/20100305052116/http://blog.reddit.com/2009/10/reddits-new-comment-sorting-system.html\n// https://medium.com/hacking-and-gonzo/how-reddit-ranking-algorithms-work-ef111e33d0d9\n// http://www.evanmiller.org/how-not-to-sort-by-average-rating.html\n// https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/lib/db/_sorts.pyx#L70\nconst sortByBest = (feed: any[]) => {\n const postScores: { [key: string]: number } = {};\n for (const post of feed) {\n const upvoteCount = n(post.upvoteCount) + 1;\n const downvoteCount = n(post.downvoteCount);\n const total = upvoteCount + downvoteCount;\n const score =\n total === 0\n ? 0\n : (() => {\n const z = 1.281551565545;\n const p = upvoteCount / total;\n const left = p + (1 / (2 * total)) * z * z;\n const right = z * Math.sqrt((p * (1 - p)) / total + (z * z) / (4 * total * total));\n const under = 1 + (1 / total) * z * z;\n return (left - right) / under;\n })();\n postScores[post.cid] = score;\n }\n return feed\n .sort((a, b) => n(a.timestamp) - n(b.timestamp))\n .sort((a, b) => n(postScores[b.cid]) - n(postScores[a.cid]));\n};\n\nconst sorters: Record<string, (feed: any[]) => any[]> = {\n new: sortByNew,\n newFlat: sortByNew,\n hot: sortByHot,\n top: sortByTop,\n topHour: sortByTop,\n topDay: sortByTop,\n topWeek: sortByTop,\n topMonth: sortByTop,\n topYear: sortByTop,\n topAll: sortByTop,\n controversial: sortByControversial,\n controversialHour: sortByControversial,\n controversialDay: sortByControversial,\n controversialWeek: sortByControversial,\n controversialMonth: sortByControversial,\n controversialYear: sortByControversial,\n controversialAll: sortByControversial,\n active: sortByActive,\n old: sortByOld,\n oldFlat: sortByOld,\n best: sortByBest,\n};\n\nconst sort = (sortType: string | undefined, feed: any[]) => {\n const sorter = sortType && sorters[sortType];\n if (!sorter) {\n return feed;\n }\n // NOTE: pinned posts are not sorted, maybe in a future version we can sort them based on something\n // NOTE: with useReplies({flat: true}), nested pins are at the top, unclear yet what we should do with them\n const pinnedPosts = feed.filter((post) => post.pinned);\n\n feed = feed.filter((post) => !post.pinned);\n return [...pinnedPosts, ...sorter(feed)];\n};\n\n/**\n * Interleave several communities' posts. A feed that keeps its order (a community's sort file, which\n * the client cannot reproduce) is never reordered and the others get the built-in sort. The next post\n * is whichever feed's next post the built-in sorter ranks first, so a thread never rises above one\n * its own community ranks higher, and feeds that all use the built-in sort merge as one sort.\n */\nconst merge = (sortType: string | undefined, feeds: { posts: any[]; keepOrder: boolean }[]) => {\n const nonEmptyFeeds = feeds.filter(({ posts }) => posts.length > 0);\n if (nonEmptyFeeds.length === 1 && nonEmptyFeeds[0].keepOrder) {\n return nonEmptyFeeds[0].posts;\n }\n const ranks = new Map<any, number>();\n sort(\n sortType,\n nonEmptyFeeds.flatMap(({ posts }) => posts),\n ).forEach((post, index) => ranks.set(post, index));\n const rankOf = (post: any) => ranks.get(post) as number;\n const orderedFeeds = nonEmptyFeeds.map(({ posts, keepOrder }) =>\n keepOrder ? posts : [...posts].sort((a, b) => rankOf(a) - rankOf(b)),\n );\n const nextIndexes = orderedFeeds.map(() => 0);\n const postCount = orderedFeeds.reduce((count, posts) => count + posts.length, 0);\n const merged: any[] = [];\n while (merged.length < postCount) {\n let nextFeedIndex = -1;\n for (const [feedIndex, posts] of orderedFeeds.entries()) {\n if (nextIndexes[feedIndex] === posts.length) {\n continue;\n }\n if (\n nextFeedIndex === -1 ||\n rankOf(posts[nextIndexes[feedIndex]]) <\n rankOf(orderedFeeds[nextFeedIndex][nextIndexes[nextFeedIndex]])\n ) {\n nextFeedIndex = feedIndex;\n }\n }\n merged.push(orderedFeeds[nextFeedIndex][nextIndexes[nextFeedIndex]++]);\n }\n return merged;\n};\n\nexport default { sort, merge };\n"]}
@@ -12,6 +12,9 @@ type FeedsState = {
12
12
  feedsCommunityKeysWithNewerPosts: {
13
13
  [feedName: string]: string[];
14
14
  };
15
+ feedsCommunityKeysWithMore: {
16
+ [feedName: string]: string[];
17
+ };
15
18
  addFeedToStore: Function;
16
19
  incrementFeedPageNumber: Function;
17
20
  expandFeedTimeWindow: Function;
@@ -1 +1 @@
1
- {"version":3,"file":"feeds-store.d.ts","sourceRoot":"","sources":["../../../src/stores/feeds/feeds-store.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,EAIL,YAAY,EAEZ,0BAA0B,EAI3B,MAAM,aAAa,CAAC;AAgCrB,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAKtC,KAAK,UAAU,GAAG;IAChB,YAAY,EAAE,YAAY,CAAC;IAC3B,aAAa,EAAE,KAAK,CAAC;IACrB,WAAW,EAAE,KAAK,CAAC;IACnB,YAAY,EAAE,KAAK,CAAC;IACpB,kCAAkC,EAAE,0BAA0B,CAAC;IAC/D,aAAa,EAAE;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;IAC/C,gCAAgC,EAAE;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;KAAE,CAAC;IACnE,cAAc,EAAE,QAAQ,CAAC;IACzB,uBAAuB,EAAE,QAAQ,CAAC;IAClC,oBAAoB,EAAE,QAAQ,CAAC;IAC/B,SAAS,EAAE,QAAQ,CAAC;IACpB,WAAW,EAAE,QAAQ,CAAC;CACvB,CAAC;AAOF,QAAA,MAAM,UAAU,yEA+Vb,CAAC;AAuSJ,eAAO,MAAM,eAAe,qBAsB3B,CAAC;AAGF,eAAO,MAAM,0BAA0B,qBAGtC,CAAC;AAEF,eAAe,UAAU,CAAC"}
1
+ {"version":3,"file":"feeds-store.d.ts","sourceRoot":"","sources":["../../../src/stores/feeds/feeds-store.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,EAIL,YAAY,EAEZ,0BAA0B,EAI3B,MAAM,aAAa,CAAC;AAiCrB,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAKtC,KAAK,UAAU,GAAG;IAChB,YAAY,EAAE,YAAY,CAAC;IAC3B,aAAa,EAAE,KAAK,CAAC;IACrB,WAAW,EAAE,KAAK,CAAC;IACnB,YAAY,EAAE,KAAK,CAAC;IACpB,kCAAkC,EAAE,0BAA0B,CAAC;IAC/D,aAAa,EAAE;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;IAC/C,gCAAgC,EAAE;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;KAAE,CAAC;IACnE,0BAA0B,EAAE;QAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;KAAE,CAAC;IAC7D,cAAc,EAAE,QAAQ,CAAC;IACzB,uBAAuB,EAAE,QAAQ,CAAC;IAClC,oBAAoB,EAAE,QAAQ,CAAC;IAC/B,SAAS,EAAE,QAAQ,CAAC;IACpB,WAAW,EAAE,QAAQ,CAAC;CACvB,CAAC;AAcF,QAAA,MAAM,UAAU,yEA4Wb,CAAC;AAuSJ,eAAO,MAAM,eAAe,qBAsB3B,CAAC;AAGF,eAAO,MAAM,0BAA0B,qBAGtC,CAAC;AAEF,eAAe,UAAU,CAAC"}
@@ -7,7 +7,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import assert from "assert";
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ import assert from "../../lib/assert.js";
11
22
  import Logger from "@pkcprotocol/pkc-logger";
12
23
  const log = Logger("bitsocial-react-hooks:feeds:stores");
13
24
  import createStore from "zustand";
@@ -18,7 +29,7 @@ import { getCommunityRefKeys } from "../../lib/community-ref.js";
18
29
  import accountsStore from "../accounts/index.js";
19
30
  import communitiesStore from "../communities/index.js";
20
31
  import communitiesPagesStore from "../communities-pages/index.js";
21
- import { getFeedsCommunitiesFirstPageCids, getLoadedFeeds, getUpdatedFeeds, getBufferedFeedsWithoutLoadedFeeds, getFeedsCommunitiesPostCounts, getFeedsHaveMore, getAccountsBlockedAddresses, feedsHaveChangedBlockedAddresses, accountsBlockedAddressesChanged, getAccountsBlockedCids, feedsHaveChangedBlockedCids, accountsBlockedCidsChanged, feedsCommunitiesChanged, getFeedsCommunities, getFeedsCommunitiesLoadedCount, getFeedsCommunitiesPostsPagesFirstUpdatedAts, getFilteredSortedFeeds, getFeedsCommunityKeysWithNewerPosts, } from "./utils.js";
32
+ import { getFeedsCommunitiesFirstPageCids, getLoadedFeeds, getUpdatedFeeds, getBufferedFeedsWithoutLoadedFeeds, getFeedsCommunitiesPostCounts, getFeedsHaveMore, getAccountsBlockedAddresses, feedsHaveChangedBlockedAddresses, accountsBlockedAddressesChanged, getAccountsBlockedCids, feedsHaveChangedBlockedCids, accountsBlockedCidsChanged, feedsCommunitiesChanged, getFeedsCommunities, getFeedsCommunitiesLoadedCount, getFeedsCommunitiesPostsPagesFirstUpdatedAts, getFilteredSortedFeeds, getFeedsCommunityKeysWithNewerPosts, getFeedsCommunityKeysWithMore, } from "./utils.js";
22
33
  // reddit loads approximately 25 posts per page
23
34
  // while infinite scrolling
24
35
  export const defaultPostsPerPage = 25;
@@ -28,6 +39,12 @@ const communityPostsLeftBeforeNextPage = 50;
28
39
  let updateFeedsPending = false;
29
40
  let updateFeedsAgain = false;
30
41
  const updateFeedsMinIntervalTime = 100;
42
+ // a feed whose options changed has no community keys with more until it is calculated again, so
43
+ // useFeed reports every community as still loading instead of the previous options' result
44
+ const withoutFeed = (feedsCommunityKeys, feedName) => {
45
+ const _a = feedsCommunityKeys, _b = feedName, _removedFeedCommunityKeys = _a[_b], otherFeedsCommunityKeys = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
46
+ return otherFeedsCommunityKeys;
47
+ };
31
48
  const feedsStore = createStore((setState, getState) => ({
32
49
  feedsOptions: {},
33
50
  bufferedFeeds: {},
@@ -36,6 +53,7 @@ const feedsStore = createStore((setState, getState) => ({
36
53
  bufferedFeedsCommunitiesPostCounts: {},
37
54
  feedsHaveMore: {},
38
55
  feedsCommunityKeysWithNewerPosts: {},
56
+ feedsCommunityKeysWithMore: {},
39
57
  addFeedToStore(feedName, communities, communityKeys, sortType, account, isBufferedFeed, postsPerPage, filter, newerThan, accountComments, modQueue) {
40
58
  return __awaiter(this, void 0, void 0, function* () {
41
59
  // init here because must be called after async accounts store finished initializing
@@ -118,10 +136,11 @@ const feedsStore = createStore((setState, getState) => ({
118
136
  const loadedFeed = loadedFeeds[feedName] || [];
119
137
  const shouldPrefetchExpandedPage = currentFeedOptions.pageNumber > 0 &&
120
138
  loadedFeed.length >= currentFeedOptions.pageNumber * currentFeedOptions.postsPerPage;
121
- setState(({ feedsOptions }) => ({
139
+ setState(({ feedsOptions, feedsCommunityKeysWithMore }) => ({
122
140
  feedsOptions: Object.assign(Object.assign({}, feedsOptions), { [feedName]: Object.assign(Object.assign({}, currentFeedOptions), { newerThan, pageNumber: shouldPrefetchExpandedPage
123
141
  ? currentFeedOptions.pageNumber + 1
124
142
  : currentFeedOptions.pageNumber }) }),
143
+ feedsCommunityKeysWithMore: withoutFeed(feedsCommunityKeysWithMore, feedName),
125
144
  }));
126
145
  updateFeeds();
127
146
  },
@@ -134,12 +153,13 @@ const feedsStore = createStore((setState, getState) => ({
134
153
  const { modQueue, sortType, communities, communityKeys, accountId } = feedsOptions[feedName];
135
154
  const account = accountsStore.getState().accounts[accountId];
136
155
  assert(account, `feedsActions.resetFeed account id '${accountId}' does not exist in accounts store`);
137
- setState(({ feedsOptions, loadedFeeds, updatedFeeds }) => {
156
+ setState(({ feedsOptions, loadedFeeds, updatedFeeds, feedsCommunityKeysWithMore }) => {
138
157
  const feedOptions = Object.assign(Object.assign({}, feedsOptions[feedName]), { pageNumber: 1 });
139
158
  return {
140
159
  feedsOptions: Object.assign(Object.assign({}, feedsOptions), { [feedName]: feedOptions }),
141
160
  loadedFeeds: Object.assign(Object.assign({}, loadedFeeds), { [feedName]: [] }),
142
161
  updatedFeeds: Object.assign(Object.assign({}, updatedFeeds), { [feedName]: [] }),
162
+ feedsCommunityKeysWithMore: withoutFeed(feedsCommunityKeysWithMore, feedName),
143
163
  };
144
164
  });
145
165
  if (modQueue === null || modQueue === void 0 ? void 0 : modQueue[0]) {
@@ -186,6 +206,7 @@ const feedsStore = createStore((setState, getState) => ({
186
206
  const bufferedFeeds = getBufferedFeedsWithoutLoadedFeeds(bufferedFeedsWithoutPreviousLoadedFeeds, loadedFeeds);
187
207
  const bufferedFeedsCommunitiesPostCounts = getFeedsCommunitiesPostCounts(feedsOptions, bufferedFeeds);
188
208
  const feedsHaveMore = getFeedsHaveMore(feedsOptions, bufferedFeeds, communities, communitiesPages, accounts);
209
+ const feedsCommunityKeysWithMore = getFeedsCommunityKeysWithMore(feedsOptions, bufferedFeedsCommunitiesPostCounts, communities, communitiesPages, accounts, previousState.feedsCommunityKeysWithMore);
189
210
  const feedsCommunityKeysWithNewerPosts = getFeedsCommunityKeysWithNewerPosts(feedsOptions, filteredSortedFeeds, loadedFeeds, previousState.feedsCommunityKeysWithNewerPosts);
190
211
  const updatedFeeds = yield getUpdatedFeeds(feedsOptions, filteredSortedFeeds, previousState.updatedFeeds, loadedFeeds, accounts);
191
212
  // set new feeds
@@ -196,6 +217,7 @@ const feedsStore = createStore((setState, getState) => ({
196
217
  bufferedFeedsCommunitiesPostCounts,
197
218
  feedsHaveMore,
198
219
  feedsCommunityKeysWithNewerPosts,
220
+ feedsCommunityKeysWithMore,
199
221
  }));
200
222
  log.trace("feedsStore.updateFeeds", {
201
223
  feedsOptions,
@@ -204,6 +226,7 @@ const feedsStore = createStore((setState, getState) => ({
204
226
  updatedFeeds,
205
227
  bufferedFeedsCommunitiesPostCounts,
206
228
  feedsHaveMore,
229
+ feedsCommunityKeysWithMore,
207
230
  communities,
208
231
  communitiesPages,
209
232
  feedsCommunityKeysWithNewerPosts,