@bitsocial/bitsocial-react-hooks 0.1.51 → 0.1.53
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 +30 -0
- package/README.md +52 -1506
- package/dist/hooks/accounts/accounts.d.ts.map +1 -1
- package/dist/hooks/accounts/accounts.js +3 -1
- package/dist/hooks/accounts/accounts.js.map +1 -1
- package/dist/hooks/feeds/feeds.d.ts.map +1 -1
- package/dist/hooks/feeds/feeds.js +8 -0
- package/dist/hooks/feeds/feeds.js.map +1 -1
- package/dist/stores/accounts/accounts-actions.d.ts.map +1 -1
- package/dist/stores/accounts/accounts-actions.js +17 -2
- package/dist/stores/accounts/accounts-actions.js.map +1 -1
- package/dist/stores/feeds/feed-sorter.d.ts +4 -0
- package/dist/stores/feeds/feed-sorter.d.ts.map +1 -1
- package/dist/stores/feeds/feed-sorter.js +35 -1
- package/dist/stores/feeds/feed-sorter.js.map +1 -1
- package/dist/stores/feeds/feeds-store.d.ts +3 -0
- package/dist/stores/feeds/feeds-store.d.ts.map +1 -1
- package/dist/stores/feeds/feeds-store.js +26 -3
- package/dist/stores/feeds/feeds-store.js.map +1 -1
- package/dist/stores/feeds/utils.d.ts +9 -0
- package/dist/stores/feeds/utils.d.ts.map +1 -1
- package/dist/stores/feeds/utils.js +81 -66
- package/dist/stores/feeds/utils.js.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,1543 +1,89 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
[](https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/LICENSE)
|
|
4
|
-
[](http://commitizen.github.io/cz-cli/)
|
|
5
|
-
|
|
6
|
-
<p align="left">
|
|
7
|
-
<img src="./docs/assets/readme/react-hooks-banner.jpg" alt="React Hooks banner" width="340" />
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/assets/readme/social-preview.png" alt="Bitsocial React Hooks — Build decentralized, serverless social apps with React using a familiar hooks API." width="640" />
|
|
8
3
|
</p>
|
|
9
4
|
|
|
10
5
|
# Bitsocial React Hooks
|
|
11
6
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
This package is published as [`@bitsocial/bitsocial-react-hooks`](https://www.npmjs.com/package/@bitsocial/bitsocial-react-hooks) and is used by [5chan](https://github.com/bitsocialnet/5chan) and other Bitsocial clients.
|
|
15
|
-
|
|
16
|
-
## Installation
|
|
17
|
-
|
|
18
|
-
```bash
|
|
19
|
-
yarn add @bitsocial/bitsocial-react-hooks
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
The published build is self-contained ESM, so consumers should not need postinstall import-rewrite patches.
|
|
23
|
-
|
|
24
|
-
## Development Setup
|
|
25
|
-
|
|
26
|
-
```bash
|
|
27
|
-
nvm install
|
|
28
|
-
nvm use
|
|
29
|
-
corepack enable
|
|
30
|
-
yarn install
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
Run `corepack enable` once per machine so plain `yarn` resolves to the pinned Yarn 4 release.
|
|
34
|
-
|
|
35
|
-
AI contributor guidance starts in [AGENTS.md](AGENTS.md). Edit shared skills and roles in `.agents/`, then run `yarn ai-workflow:sync`, `yarn ai-workflow:check`, and `yarn ai-workflow:test`; commit generated native app files with their sources. See [skills and tools](docs/agent-playbooks/skills-and-tools.md) for discovery paths and [verification](docs/agent-playbooks/verification.md) for checks appropriate to each change.
|
|
36
|
-
|
|
37
|
-
---
|
|
38
|
-
|
|
39
|
-
## Table of Contents
|
|
40
|
-
|
|
41
|
-
- [Installation](#installation)
|
|
42
|
-
- [Documentation Links](#documentation-links)
|
|
43
|
-
- [API Reference](#api-reference)
|
|
44
|
-
- [Hooks](#hooks)
|
|
45
|
-
- [Accounts Hooks](#accounts-hooks)
|
|
46
|
-
- [Comments Hooks](#comments-hooks)
|
|
47
|
-
- [Communities Hooks](#communities-hooks)
|
|
48
|
-
- [Authors Hooks](#authors-hooks)
|
|
49
|
-
- [Feeds Hooks](#feeds-hooks)
|
|
50
|
-
- [Actions Hooks](#actions-hooks)
|
|
51
|
-
- [States Hooks](#states-hooks)
|
|
52
|
-
- [RPC Hooks](#rpc-hooks)
|
|
53
|
-
- [Actions with no hooks implementations yet](#actions-with-no-hooks-implementations-yet)
|
|
54
|
-
- [Utility functions](#utility-functions)
|
|
55
|
-
- [Recipes](#recipes)
|
|
56
|
-
- [Getting started](#getting-started)
|
|
57
|
-
- [Get the active account, if none exist in browser database, a default account is generated](#get-the-active-account-if-none-exist-in-browser-database-a-default-account-is-generated)
|
|
58
|
-
- [Create accounts and change active account](#create-accounts-and-change-active-account)
|
|
59
|
-
- [Get a post](#get-a-post)
|
|
60
|
-
- [Get a comment](#get-a-comment)
|
|
61
|
-
- [Get author avatar](#get-author-avatar)
|
|
62
|
-
- [Get author profile page](#get-author-profile-page)
|
|
63
|
-
- [Get a community](#get-a-community)
|
|
64
|
-
- [Create a post or comment using callbacks](#create-a-post-or-comment-using-callbacks)
|
|
65
|
-
- [Create a post or comment using hooks](#create-a-post-or-comment-using-hooks)
|
|
66
|
-
- [Create a post or comment anonymously (without account.signer or account.author)](#create-a-post-or-comment-anonymously-without-accountsigner-or-accountauthor)
|
|
67
|
-
- [Create a vote](#create-a-vote)
|
|
68
|
-
- [Create a comment edit](#create-a-comment-edit)
|
|
69
|
-
- [Create a comment moderation](#create-a-comment-moderation)
|
|
70
|
-
- [Delete a comment](#delete-a-comment)
|
|
71
|
-
- [Subscribe to a community](#subscribe-to-a-community)
|
|
72
|
-
- [Get feed](#get-feed)
|
|
73
|
-
- [Get mod queue (pending approval)](#get-mod-queue-pending-approval)
|
|
74
|
-
- [Approve a pending approval comment](#approve-a-pending-approval-comment)
|
|
75
|
-
- [Edit an account](#edit-an-account)
|
|
76
|
-
- [Delete account](#delete-account)
|
|
77
|
-
- [Get your own comments and votes](#get-your-own-comments-and-votes)
|
|
78
|
-
- [Determine if a comment is your own](#determine-if-a-comment-is-your-own)
|
|
79
|
-
- [Get account notifications](#get-account-notifications)
|
|
80
|
-
- [Block an address (author, community or multisub)](#block-an-address-author-community-or-multisub)
|
|
81
|
-
- [Block a cid (hide a comment)](#block-a-cid-hide-a-comment)
|
|
82
|
-
- [(Desktop only) Create a community](#desktop-only-create-a-community)
|
|
83
|
-
- [(Desktop only) List the communities you created](#desktop-only-list-the-communities-you-created)
|
|
84
|
-
- [(Desktop only) Edit your community settings](#desktop-only-edit-your-community-settings)
|
|
85
|
-
- [Export and import account](#export-and-import-account)
|
|
86
|
-
- [View the status of a comment edit](#view-the-status-of-a-comment-edit)
|
|
87
|
-
- [View the status of a specific comment edit property](#view-the-status-of-a-specific-comment-edit-property)
|
|
88
|
-
- [List all comment and community edits the account has performed](#list-all-comment-and-community-edits-the-account-has-performed)
|
|
89
|
-
- [Get replies to a post (nested or flat)](#get-replies-to-a-post-nested-or-flat)
|
|
90
|
-
- [Format short CIDs and addresses](#format-short-cids-and-addresses)
|
|
91
|
-
- [useBufferedFeeds with concurrency](#usebufferedfeeds-with-concurrency)
|
|
92
|
-
|
|
93
|
-
## Documentation Links
|
|
94
|
-
|
|
95
|
-
- [Hooks API](#hooks)
|
|
96
|
-
- [Getting started](#getting-started)
|
|
97
|
-
- Install, testing and building: https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/docs/testing.md
|
|
98
|
-
- Mock content (for UI development): https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/docs/mock-content.md
|
|
99
|
-
- Algorithms: https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/docs/algorithms.md
|
|
100
|
-
- Schema (Types, IndexedDb and state management): https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/docs/schema.md
|
|
101
|
-
- Types: https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/src/types.ts
|
|
102
|
-
|
|
103
|
-
## API Reference
|
|
104
|
-
|
|
105
|
-
### Hooks
|
|
106
|
-
|
|
107
|
-
#### Accounts Hooks
|
|
108
|
-
|
|
109
|
-
```
|
|
110
|
-
useAccount(): Account | undefined
|
|
111
|
-
useAccountComment({commentIndex?: number, commentCid?: string}): Comment // get one own comment by index or cid
|
|
112
|
-
useAccountComments({filter?: AccountPublicationsFilter, commentCid?: string, commentIndices?: number[], communityAddress?: string, parentCid?: string, newerThan?: number, page?: number, pageSize?: number, sortType?: "new" | "old"}): {accountComments: Comment[]} // export or display list of own comments
|
|
113
|
-
useAccountVotes({filter?: AccountPublicationsFilter, vote?: number, commentCid?: string, communityAddress?: string, newerThan?: number, page?: number, pageSize?: number, sortType?: "new" | "old"}): {accountVotes: Vote[]} // export or display list of own votes
|
|
114
|
-
useAccountVote({commentCid: string}): Vote // know if you already voted on some comment
|
|
115
|
-
useAccountEdits({filer: AccountPublicationsFilter}): {accountEdits: AccountEdit[]}
|
|
116
|
-
useAccountCommunities(): {accountCommunities: {[communityAddress: string]: AccountCommunity}, onlyIfCached?: boolean}
|
|
117
|
-
useAccounts(): Account[]
|
|
118
|
-
useNotifications(): {notifications: Notification[], markAsRead: Function}
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
#### Comments Hooks
|
|
122
|
-
|
|
123
|
-
```
|
|
124
|
-
useComment({commentCid: string, community?: CommunityIdentifier, initialComment?: Comment, onlyIfCached?: boolean, autoUpdate?: boolean}): Comment & {refresh: Function}
|
|
125
|
-
useCrosspost({crosspost: Crosspost, autoUpdate?: boolean}): Comment & {isCommunityVerified: boolean, refresh: Function}
|
|
126
|
-
useReplies({comment: Comment, onlyIfCached?: boolean, sortType?: string, flat?: boolean, repliesPerPage?: number, filter?: CommentsFilter, accountComments?: {newerThan: number, append?: boolean}}): {replies: Comment[], hasMore: boolean, loadMore: function, reset: function, updatedReplies: Comment[], bufferedReplies: Comment[]}
|
|
127
|
-
useComments({commentCids: string[], onlyIfCached?: boolean, autoUpdate?: boolean}): {comments: Comment[], refresh: Function}
|
|
128
|
-
useEditedComment({comment: Comment}): {editedComment: Comment | undefined}
|
|
129
|
-
useValidateComment({comment: Comment, validateReplies?: boolean}): {valid: boolean}
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
#### Communities Hooks
|
|
133
|
-
|
|
134
|
-
```
|
|
135
|
-
useCommunity({community: {name?: string, publicKey?: string}, onlyIfCached?: boolean}): Community & {syncState: "initializing" | "loading" | "retrying" | "succeeded" | "failed" | "stopped", hasCachedData: boolean, lastFetchAttemptAt: number | undefined, lastSuccessfulFetchAt: number | undefined}
|
|
136
|
-
useCommunities({communities?: CommunityIdentifier[], onlyIfCached?: boolean}): {communities: Communities[]}
|
|
137
|
-
useCommunityStats({community: {name?: string, publicKey?: string}, onlyIfCached?: boolean}): CommunityStats
|
|
138
|
-
useResolvedCommunityAddress({communityAddress: string, cache: boolean}): {resolvedAddress: string | undefined} // use {cache: false} when checking the user's own community address
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
Pass `{ publicKey, name }` when you have both so `pkc-js` can fetch through the public key and resolve the name in the background. `communityAddress`, `communityAddresses`, and `communityRefs` are no longer accepted by these hooks.
|
|
142
|
-
|
|
143
|
-
`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`.
|
|
144
|
-
|
|
145
|
-
`useCommunity().state` remains `succeeded` when cached community data is available, even
|
|
146
|
-
while a refresh is running. Use `syncState` for the current refresh lifecycle:
|
|
147
|
-
`loading` covers active name, IPNS, and IPFS work, while `retrying` means a transient
|
|
148
|
-
failure is being retried. `lastFetchAttemptAt` and `lastSuccessfulFetchAt` are Unix
|
|
149
|
-
timestamps in seconds. A successful fetch only proves that a valid community record was
|
|
150
|
-
reachable; it does not prove that the community operator is currently online.
|
|
151
|
-
|
|
152
|
-
#### Authors Hooks
|
|
153
|
-
|
|
154
|
-
```
|
|
155
|
-
useAuthor({authorAddress: string, commentCid: string}): {author: Author | undefined}
|
|
156
|
-
useAuthorAddress({comment: Comment}): {authorAddress: string | undefined, shortAuthorAddress: string | undefined, authorAddressChanged: boolean}
|
|
157
|
-
useAuthorComments({authorAddress: string, commentCid: string, filter?: CommentsFilter}): {authorComments: Comment[], hasMore: boolean, loadMore: Promise<void>}
|
|
158
|
-
useResolvedAuthorAddress({author?: Author, cache?: boolean}): {resolvedAddress: string | undefined, nameResolver: NameResolverInfo | undefined} // supports .eth/.bso aliases; use {cache: false} when checking the user's own author address
|
|
159
|
-
useAuthorAvatar({author?: Author}): {imageUrl: string | undefined}
|
|
160
|
-
setAuthorAvatarsWhitelistedTokenAddresses(tokenAddresses: string[])
|
|
161
|
-
```
|
|
162
|
-
|
|
163
|
-
#### Feeds Hooks
|
|
164
|
-
|
|
165
|
-
```
|
|
166
|
-
useFeed({communities?: CommunityIdentifier[], sortType?: string, postsPerPage?: number, filter?: CommentsFilter, newerThan?: number, accountComments?: {newerThan: number, append?: boolean}, modQueue: ['pendingApproval']}): {feed: Comment[], loadMore: function, expandTimeWindow: function, hasMore: boolean, reset: function, updatedFeed: Comment[], bufferedFeed: Comment[], communityKeysWithNewerPosts: string[]}
|
|
167
|
-
useBufferedFeeds({feedsOptions: UseFeedOptions[]}) // preload or buffer feeds in the background, so they load faster when you call `useFeed`
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
`useFeed().reset()` clears the current feed and refreshes the latest community snapshots before rebuilding it.
|
|
171
|
-
`useFeed().expandTimeWindow(newerThan)` broadens `newerThan` in place without constructing a different sort name, so older posts can be appended without replacing the feed instance.
|
|
172
|
-
|
|
173
|
-
Feed and reply sort names are defined by each community record, not by a fixed hooks allowlist. Omit `sortType` to use the preloaded page, or discover the requestable names with `getAvailablePostSortTypes(community)` and `getAvailableReplySortTypes(comment)`. pkc-js preloads a single sort and only publishes `pageCids` once that page overflows, so when every post or reply fits in the preloaded page the standard sorts (`hot`, `new`, `active` and `top*` for posts; `best`, `new`, `old`, `newFlat` and `oldFlat` for replies) are also requestable and are sorted client-side from that page, including the time window of `top*` timeframe sorts. `getPostPageSortType(community, sortType)` and `getReplyPageSortType(comment, sortType)` return the page that serves a sort. A requested sort that is neither published nor computable client-side is not silently replaced with another sort. Hooks preserve protocol page order for unknown custom sorts because their scoring algorithm is not available to the client. The same applies to a sort file that a community publishes under a built-in name (for example a keyword no-bump `active`), which `community.pageSorts.posts[sortType]` reveals through a different `name` or options of its own: a single-community feed reading that sort's pages keeps the community's page order, while a feed merging several communities still orders them with the built-in sorter of that name.
|
|
174
|
-
|
|
175
|
-
#### Actions Hooks
|
|
176
|
-
|
|
177
|
-
```
|
|
178
|
-
useSubscribe({communityAddress: string}): {subscribed: boolean | undefined, subscribe: Function, unsubscribe: Function}
|
|
179
|
-
useBlock({address?: string, cid?: string}): {blocked: boolean | undefined, block: Function, unblock: Function}
|
|
180
|
-
useSaveComment({commentCid: string}): {saved: boolean | undefined, saveComment: Function, unsaveComment: Function}
|
|
181
|
-
usePublishComment(options: UsePublishCommentOptions): {index: number, abandonPublish: () => Promise<void>, ...UsePublishCommentResult}
|
|
182
|
-
usePublishVote(options: UsePublishVoteOptions): {abandonPublish: () => Promise<void>, ...UsePublishVoteResult}
|
|
183
|
-
usePublishCommentEdit(options: UsePublishCommentEditOptions): UsePublishCommentEditResult
|
|
184
|
-
usePublishCommentModeration(options: UsePublishCommentModerationOptions): UsePublishCommentModerationResult
|
|
185
|
-
usePublishCommunityEdit(options: UsePublishCommunityEditOptions): UsePublishCommunityEditResult
|
|
186
|
-
useCreateCommunity(options: CreateCommunityOptions): {createdCommunity: Community | undefined, createCommunity: Function}
|
|
187
|
-
useExportCommunity(options?: UseExportCommunityOptions): {
|
|
188
|
-
communityExports: {communityAddress: string, exportId: string}[],
|
|
189
|
-
exportCommunity: () => Promise<void>,
|
|
190
|
-
state: string,
|
|
191
|
-
error: Error | undefined,
|
|
192
|
-
errors: Error[]
|
|
193
|
-
}
|
|
194
|
-
```
|
|
195
|
-
|
|
196
|
-
Before `publishComment`, `publishCommentEdit`, `publishVote`, `publishCommentModeration`, or `publishCommunityEdit` signs a publication, hooks load the community challenge configuration and apply compatible wordfilters. The current `@bitsocial/wordfilter-challenge` contract uses a JSON array of `{src, dst}` objects in `wordfilter/v1/rules` and an optional JSON array of dot-notation paths in `wordfilter/v1/fieldNames`, both published through `publicOptions`. Every path starts with the publication type and is resolved against the publication being signed, so a path for another type is simply skipped. Without configured paths the defaults apply: `comment.content`, `comment.title`, `comment.author.displayName`, `commentEdit.content`, `commentEdit.reason`, `commentEdit.author.displayName`, and `vote.author.displayName`. Moderator and owner text is opt-in through configured paths (`commentModeration.commentModeration.reason`, `communityEdit.communityEdit.title`, `communityEdit.communityEdit.description`); structural and signing fields are never rewritten by community configuration. Matching is literal and case-insensitive, not regular-expression or Unicode-evasion matching. The transformed values are the values signed, published, and stored as the pending account publication. If composed rule sets do not stabilize within eight passes, publication stops before signing.
|
|
197
|
-
|
|
198
|
-
#### States Hooks
|
|
199
|
-
|
|
200
|
-
```
|
|
201
|
-
useClientsStates({comment?: Comment, community?: Community}): {states, peers}
|
|
202
|
-
useCommunitiesStates({communities?: CommunityIdentifier[]}): {states, peers}
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
#### RPC Hooks
|
|
206
|
-
|
|
207
|
-
```
|
|
208
|
-
usePkcRpcSettings(): {pkcRpcSettings: {pkcOptions, challenges}, setPkcRpcSettings: Function}
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
Community edits preserve challenge `publicOptions` arrays, remote community records expose their published option values, and `usePkcRpcSettings` exposes each installed challenge's `optionInputs` metadata so clients can build challenge-specific configuration without hooks knowing each challenge schema.
|
|
212
|
-
|
|
213
|
-
#### Actions with no hooks implementations yet
|
|
214
|
-
|
|
215
|
-
```
|
|
216
|
-
createAccount(account: Account)
|
|
217
|
-
deleteAccount(accountName: string)
|
|
218
|
-
setAccount(account: Account)
|
|
219
|
-
setActiveAccount(accountName: string)
|
|
220
|
-
setAccountsOrder(accountNames: string[])
|
|
221
|
-
importAccount(serializedAccount: string)
|
|
222
|
-
exportAccount(accountName: string): string // don't allow undefined to prevent catastrophic bugs
|
|
223
|
-
deleteCommunity(communityAddress: string, accountName?: string)
|
|
224
|
-
deleteComment(commentCidOrAccountCommentIndex: string | number, accountName?: string): Promise<void>
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
#### Utility functions
|
|
228
|
-
|
|
229
|
-
```
|
|
230
|
-
setPkcJs(PKC) // swap the underlying protocol client implementation, e.g. for mocks or Electron
|
|
231
|
-
deleteDatabases() // delete all databases, including all caches and accounts data
|
|
232
|
-
deleteCaches() // delete the cached comments, cached communities and cached pages only, no accounts data
|
|
233
|
-
createCrosspost(comment: Comment): Crosspost // build the immutable payload accepted by pkc-js
|
|
234
|
-
getAvailablePostSortTypes(community: Community): string[]
|
|
235
|
-
getAvailableReplySortTypes(comment: Comment): string[]
|
|
236
|
-
getPreloadedPostSortType(community: Community): string | undefined
|
|
237
|
-
getPreloadedReplySortType(comment: Comment): string | undefined
|
|
238
|
-
resolvePostSortType(community: Community, requestedSortType?: string): string | undefined
|
|
239
|
-
resolveReplySortType(comment: Comment, requestedSortType?: string): string | undefined
|
|
240
|
-
getPostPageSortType(community: Community, requestedSortType?: string): string | undefined // page sort serving the request, e.g. the preloaded page a single-page community re-sorts client-side
|
|
241
|
-
getReplyPageSortType(comment: Comment, requestedSortType?: string): string | undefined
|
|
242
|
-
getSortTimeframeSeconds(sortType?: string): number | undefined // time window of top*/controversial* timeframe sorts
|
|
243
|
-
isFlatSortType(sortType?: string): boolean
|
|
244
|
-
```
|
|
245
|
-
|
|
246
|
-
`createCrosspost` requires a fully loaded comment with `comment.cid` and
|
|
247
|
-
`comment.raw.comment`. Publish the returned payload through the existing action hook:
|
|
248
|
-
|
|
249
|
-
```jsx
|
|
250
|
-
const crosspost = createCrosspost(sourceComment);
|
|
251
|
-
const { publishComment } = usePublishComment({
|
|
252
|
-
communityAddress: targetCommunityAddress,
|
|
253
|
-
title: sourceComment.title,
|
|
254
|
-
crosspost,
|
|
255
|
-
});
|
|
256
|
-
await publishComment();
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
Render the author-signed embedded record immediately with `useCrosspost`. The referenced
|
|
260
|
-
community is only confirmed after its signed `CommentUpdate` has loaded, exposed as
|
|
261
|
-
`isCommunityVerified`:
|
|
262
|
-
|
|
263
|
-
```jsx
|
|
264
|
-
const original = useCrosspost({ crosspost: post.crosspost });
|
|
265
|
-
|
|
266
|
-
return <CrosspostCard comment={original} verified={original.isCommunityVerified} />;
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
## Recipes
|
|
270
|
-
|
|
271
|
-
#### Getting started
|
|
272
|
-
|
|
273
|
-
```jsx
|
|
274
|
-
import { useComment, useAccount } from "@bitsocial/bitsocial-react-hooks";
|
|
275
|
-
|
|
276
|
-
const account = useAccount();
|
|
277
|
-
const comment = useComment({ commentCid });
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
#### Get the active account, if none exist in browser database, a default account is generated
|
|
281
|
-
|
|
282
|
-
```jsx
|
|
283
|
-
const account = useAccount();
|
|
284
|
-
```
|
|
285
|
-
|
|
286
|
-
#### Create accounts and change active account
|
|
287
|
-
|
|
288
|
-
```jsx
|
|
289
|
-
import {
|
|
290
|
-
useAccount,
|
|
291
|
-
useAccounts,
|
|
292
|
-
createAccount,
|
|
293
|
-
setActiveAccount,
|
|
294
|
-
} from "@bitsocial/bitsocial-react-hooks";
|
|
295
|
-
|
|
296
|
-
const account = useAccount();
|
|
297
|
-
const { accounts } = useAccounts();
|
|
298
|
-
|
|
299
|
-
// on first render
|
|
300
|
-
console.log(accounts.length); // 1
|
|
301
|
-
console.log(account.name); // e.g. 'Account KoXpxTwfnjA5'
|
|
302
|
-
console.log(account.name === `Account ${account.author.shortAddress}`); // true
|
|
303
|
-
|
|
304
|
-
await createAccount(); // creates another uniquely named account
|
|
305
|
-
await createAccount();
|
|
306
|
-
const thirdAccountName = accounts[2].name;
|
|
307
|
-
await setActiveAccount(thirdAccountName);
|
|
308
|
-
|
|
309
|
-
// on render after updates
|
|
310
|
-
console.log(accounts.length); // 3
|
|
311
|
-
console.log(account.name); // thirdAccountName
|
|
312
|
-
|
|
313
|
-
// you are now publishing from the third account because it is active
|
|
314
|
-
const { publishComment } = usePublishComment(publishCommentOptions);
|
|
315
|
-
await publishComment();
|
|
316
|
-
```
|
|
317
|
-
|
|
318
|
-
#### Get a post
|
|
319
|
-
|
|
320
|
-
```jsx
|
|
321
|
-
const post = useComment({ commentCid, community: { name: communityAddress, publicKey: communityPublicKey } });
|
|
322
|
-
|
|
323
|
-
// manual refresh is always available
|
|
324
|
-
await post.refresh();
|
|
325
|
-
|
|
326
|
-
// post.author.address should not be used directly, it needs to be verified asynchronously using useAuthorAddress
|
|
327
|
-
const { authorAddress, shortAuthorAddress } = useAuthorAddress({ comment: post });
|
|
328
|
-
// exception: when linking to an author profile page, /u/${comment.author.address}/c/${comment.cid} should be used, not useAuthorAddress({comment}).authorAddress
|
|
329
|
-
|
|
330
|
-
// use many times in a page without affecting performance
|
|
331
|
-
const post = useComment({ commentCid, onlyIfCached: true });
|
|
332
|
-
|
|
333
|
-
// disable background polling and refresh on demand
|
|
334
|
-
const post = useComment({ commentCid, autoUpdate: false });
|
|
335
|
-
// the initial load includes the first community update (including moderation)
|
|
336
|
-
// before freezing; a recent creation timestamp alone does not settle the snapshot
|
|
337
|
-
// resolves after one update cycle, also when no newer CommentUpdate exists, and right
|
|
338
|
-
// away when another instance (e.g. your own reply) already keeps the comment updating
|
|
339
|
-
await post.refresh();
|
|
340
|
-
// newly published comments still absorb canonical number, postNumber, and
|
|
341
|
-
// author shortAddress metadata as it arrives; later live updates stay frozen
|
|
342
|
-
|
|
343
|
-
// post.replies are not validated, to show replies
|
|
344
|
-
const { replies, hasMore, loadMore } = useReplies({ comment: post });
|
|
345
|
-
|
|
346
|
-
// only use the comment's preloaded replies plus any reply pages already cached in memory
|
|
347
|
-
// won't fetch missing reply pages; hasMore only reflects cached replies still available to load
|
|
348
|
-
const cachedReplies = useReplies({ comment: post, onlyIfCached: true });
|
|
349
|
-
|
|
350
|
-
// to show a preloaded reply without rerenders, validate manually
|
|
351
|
-
const { valid } = useValidateComment({ comment: post.replies.pages.best.comments[0] });
|
|
352
|
-
if (valid === false) {
|
|
353
|
-
// don't show this reply, it's malicious
|
|
354
|
-
}
|
|
355
|
-
// won't cause any rerenders if true
|
|
356
|
-
```
|
|
357
|
-
|
|
358
|
-
#### Get a comment
|
|
359
|
-
|
|
360
|
-
```jsx
|
|
361
|
-
const comment = useComment({ commentCid, community: { name: communityAddress, publicKey: communityPublicKey } });
|
|
362
|
-
const { comments, refresh } = useComments({ commentCids: [commentCid1, commentCid2, commentCid3] });
|
|
363
|
-
await refresh();
|
|
364
|
-
|
|
365
|
-
// content
|
|
366
|
-
console.log(comment.content || comment.link || comment.title);
|
|
367
|
-
|
|
368
|
-
// comment.author.address should not be used directly, it needs to be verified asynchronously using useAuthorAddress
|
|
369
|
-
const { authorAddress, shortAuthorAddress } = useAuthorAddress({ comment });
|
|
370
|
-
// exception: when linking to an author profile page, /u/${comment.author.address}/c/${comment.cid} should be used, not useAuthorAddress({comment}).authorAddress
|
|
371
|
-
|
|
372
|
-
// use without affecting performance
|
|
373
|
-
const { comments } = useComments({ commentCids, onlyIfCached: true });
|
|
374
|
-
|
|
375
|
-
// disable background polling and refresh this list on demand
|
|
376
|
-
const frozenComments = useComments({ commentCids, autoUpdate: false });
|
|
377
|
-
await frozenComments.refresh();
|
|
378
|
-
```
|
|
379
|
-
|
|
380
|
-
#### Get author avatar
|
|
381
|
-
|
|
382
|
-
```jsx
|
|
383
|
-
const comment = useComment({ commentCid });
|
|
384
|
-
|
|
385
|
-
// get the nft avatar image url of the comment author
|
|
386
|
-
const { imageUrl, state, error, chainProvider, metadataUrl } = useAuthorAvatar({
|
|
387
|
-
author: comment.author,
|
|
388
|
-
});
|
|
389
|
-
|
|
390
|
-
// result
|
|
391
|
-
if (state === "succeeded") {
|
|
392
|
-
console.log("Succeeded getting avatar image URL", imageUrl);
|
|
393
|
-
}
|
|
394
|
-
if (state === "failed") {
|
|
395
|
-
console.log("Failed getting avatar image URL", error.message);
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
// pending
|
|
399
|
-
if (state === "fetching-owner") {
|
|
400
|
-
console.log("Fetching NFT owner address from chain provider", chainProvider.urls);
|
|
401
|
-
}
|
|
402
|
-
if (state === "fetching-uri") {
|
|
403
|
-
console.log("Fetching NFT URI from chain provider URL", chainProvider.urls);
|
|
404
|
-
}
|
|
405
|
-
if (state === "fetching-metadata") {
|
|
406
|
-
console.log("Fetching NFT URI from", metadataUrl);
|
|
407
|
-
}
|
|
408
|
-
```
|
|
409
|
-
|
|
410
|
-
#### Get author profile page
|
|
411
|
-
|
|
412
|
-
```jsx
|
|
413
|
-
// NOTE: you must have a comment cid from the author to load his profile page
|
|
414
|
-
// e.g. the page url would be /#/u/<authorAddress>/c/<commentCid>
|
|
415
|
-
const authorResult = useAuthor({ commentCid, authorAddress });
|
|
416
|
-
const { imageUrl } = useAuthorAvatar({ author: authorResult.author });
|
|
417
|
-
const { authorComments, lastCommentCid, hasMore, loadMore } = useAuthorComments({
|
|
418
|
-
commentCid,
|
|
419
|
-
authorAddress,
|
|
420
|
-
});
|
|
421
|
-
|
|
422
|
-
// result
|
|
423
|
-
if (authorResult.state === "succeeded") {
|
|
424
|
-
console.log("Succeeded getting author", authorResult.author);
|
|
425
|
-
}
|
|
426
|
-
if (state === "failed") {
|
|
427
|
-
console.log("Failed getting author", authorResult.error.message);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
// listing the author comments with infinite scroll
|
|
431
|
-
import { Virtuoso } from "react-virtuoso";
|
|
432
|
-
|
|
433
|
-
<Virtuoso
|
|
434
|
-
data={authorComments}
|
|
435
|
-
itemContent={(index, comment) => <Comment index={index} comment={comment} />}
|
|
436
|
-
useWindowScroll={true}
|
|
437
|
-
components={{ Footer: hasMore ? () => <Loading /> : undefined }}
|
|
438
|
-
endReached={loadMore}
|
|
439
|
-
increaseViewportBy={{ bottom: 600, top: 600 }}
|
|
440
|
-
/>;
|
|
441
|
-
|
|
442
|
-
// it is recommended to always redirect the user to the last known comment cid
|
|
443
|
-
// in case they want to share the url with someone, the author's comments
|
|
444
|
-
// will load faster when using the last comment cid
|
|
445
|
-
import { useParams } from "react-router-dom";
|
|
446
|
-
const params = useParams();
|
|
447
|
-
|
|
448
|
-
useEffect(() => {
|
|
449
|
-
if (lastCommentCid && params.comentCid !== lastCommentCid) {
|
|
450
|
-
history.push(`/u/${params.authorAddress}/c/${lastCommentCid}`);
|
|
451
|
-
}
|
|
452
|
-
}, [lastCommentCid]);
|
|
453
|
-
|
|
454
|
-
// search an author's comments
|
|
455
|
-
const createSearchFilter = (searchTerm) => ({
|
|
456
|
-
filter: (comment) => comment.title?.includes(searchTerm) || comment.content?.includes(searchTerm),
|
|
457
|
-
key: `includes-${searchTerm}`, // required key to cache the filter
|
|
458
|
-
});
|
|
459
|
-
const filter = createSearchFilter("bitcoin");
|
|
460
|
-
const { authorComments, lastCommentCid, hasMore, loadMore } = useAuthorComments({
|
|
461
|
-
commentCid,
|
|
462
|
-
authorAddress,
|
|
463
|
-
filter,
|
|
464
|
-
});
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
#### Get a community
|
|
468
|
-
|
|
469
|
-
```jsx
|
|
470
|
-
const community = useCommunity({ community: { name: communityAddress, publicKey: communityPublicKey } });
|
|
471
|
-
const {
|
|
472
|
-
syncState,
|
|
473
|
-
hasCachedData,
|
|
474
|
-
lastFetchAttemptAt,
|
|
475
|
-
lastSuccessfulFetchAt,
|
|
476
|
-
} = community;
|
|
477
|
-
const communityStats = useCommunityStats({
|
|
478
|
-
community: { name: communityAddress, publicKey: communityPublicKey },
|
|
479
|
-
});
|
|
480
|
-
const { communities } = useCommunities({
|
|
481
|
-
communities: [
|
|
482
|
-
{ name: communityAddress, publicKey: communityPublicKey },
|
|
483
|
-
{ name: communityAddress2, publicKey: communityPublicKey2 },
|
|
484
|
-
{ name: communityAddress3, publicKey: communityPublicKey3 },
|
|
485
|
-
],
|
|
486
|
-
});
|
|
487
|
-
|
|
488
|
-
// fetched communities are refreshed immediately and then every 15 minutes
|
|
489
|
-
// so long-lived tabs keep following community IPNS updates
|
|
490
|
-
|
|
491
|
-
// use without affecting performance
|
|
492
|
-
const { communities: cachedCommunities } = useCommunities({
|
|
493
|
-
communities: [
|
|
494
|
-
{ name: communityAddress, publicKey: communityPublicKey },
|
|
495
|
-
{ name: communityAddress2, publicKey: communityPublicKey2 },
|
|
496
|
-
{ name: communityAddress3, publicKey: communityPublicKey3 },
|
|
497
|
-
],
|
|
498
|
-
onlyIfCached: true,
|
|
499
|
-
});
|
|
500
|
-
|
|
501
|
-
// community.posts are not validated, to show posts
|
|
502
|
-
const { feed, hasMore, loadMore } = useFeed({
|
|
503
|
-
communities: [{ name: communityAddress, publicKey: communityPublicKey }],
|
|
504
|
-
});
|
|
505
|
-
|
|
506
|
-
// to show a preloaded post without rerenders, validate manually
|
|
507
|
-
const { valid } = useValidateComment({ comment: community.posts.pages.topAll.comments[0] });
|
|
508
|
-
if (valid === false) {
|
|
509
|
-
// don't show this post, it's malicious
|
|
510
|
-
}
|
|
511
|
-
// won't cause any rerenders if true
|
|
512
|
-
```
|
|
513
|
-
|
|
514
|
-
#### Create a post or comment using callbacks
|
|
515
|
-
|
|
516
|
-
```jsx
|
|
517
|
-
const onChallenge = async (challenges: Challenge[], comment: Comment) => {
|
|
518
|
-
let challengeAnswers: string[]
|
|
519
|
-
try {
|
|
520
|
-
// ask the user to complete the challenges in a modal window
|
|
521
|
-
challengeAnswers = await getChallengeAnswersFromUser(challenges)
|
|
522
|
-
}
|
|
523
|
-
catch (e) {
|
|
524
|
-
// if he declines, throw error and don't get a challenge answer
|
|
525
|
-
}
|
|
526
|
-
if (challengeAnswers) {
|
|
527
|
-
// if user declines, publishChallengeAnswers is not called, retry loop stops
|
|
528
|
-
await comment.publishChallengeAnswers(challengeAnswers)
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
const onChallengeVerification = (challengeVerification, comment) => {
|
|
533
|
-
// if the challengeVerification fails, a new challenge request will be sent automatically
|
|
534
|
-
// to break the loop, the user must decline to send a challenge answer
|
|
535
|
-
// if the community owner sends more than 1 challenge for the same challenge request, subsequents will be ignored
|
|
536
|
-
if (challengeVerification.challengeSuccess === true) {
|
|
537
|
-
console.log('challenge success', {publishedCid: challengeVerification.publication.cid})
|
|
538
|
-
}
|
|
539
|
-
else if (challengeVerification.challengeSuccess === false) {
|
|
540
|
-
console.error('challenge failed', {reason: challengeVerification.reason, errors: challengeVerification.errors})
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
const onError = (error, comment) => console.error(error)
|
|
545
|
-
|
|
546
|
-
const onPendingComment = (accountCommentIndex, pendingComment) => {
|
|
547
|
-
// render or navigate to the pending comment immediately, before local persistence finishes
|
|
548
|
-
// this runs again with the corrected index if another local deletion shifts the comment while saving
|
|
549
|
-
history.push(`/profile/c/${accountCommentIndex}`, {pendingComment})
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
const publishCommentOptions = {
|
|
553
|
-
content: 'hello',
|
|
554
|
-
title: 'hello',
|
|
555
|
-
communityAddress: '12D3KooW...',
|
|
556
|
-
// partial author overrides keep the active account's author identity
|
|
557
|
-
author: {displayName: 'Alice'},
|
|
558
|
-
onPendingComment,
|
|
559
|
-
onChallenge,
|
|
560
|
-
onChallengeVerification,
|
|
561
|
-
onError
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
const {index, state, publishComment, abandonPublish} = usePublishComment(publishCommentOptions)
|
|
565
|
-
|
|
566
|
-
// create post
|
|
567
|
-
await publishComment()
|
|
568
|
-
// pending comment index
|
|
569
|
-
console.log(index)
|
|
570
|
-
// pending comment state
|
|
571
|
-
console.log(state)
|
|
572
|
-
|
|
573
|
-
// onPendingComment is called as soon as the provisional comment and index exist,
|
|
574
|
-
// and again with a corrected index if another local deletion shifts it while saving.
|
|
575
|
-
// Use it to immediately redirect the user to a page displaying the comment
|
|
576
|
-
// with a "pending" label. The index result is also defined after the pending
|
|
577
|
-
// comment has been stored locally.
|
|
578
|
-
if (index !== undefined) {
|
|
579
|
-
// on the "pending" comment page, you can get the pending comment by doing
|
|
580
|
-
// const accountComment = useAccountComment({commentIndex: index})
|
|
581
|
-
// after accountComment.cid gets defined, it means the comment was published successfully
|
|
582
|
-
// it is recommended to immediately redirect to `/p/${accountComment.communityAddress}/c/${useAccountComment.cid}`
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
// if the user closes the challenge modal and wants to cancel publishing:
|
|
586
|
-
await abandonPublish()
|
|
587
|
-
// the pending local account comment is removed from accountComments
|
|
588
|
-
// this works even if called immediately from onChallenge before publishComment() resolves
|
|
589
|
-
|
|
590
|
-
// reply to a post or comment
|
|
591
|
-
const publishReplyOptions = {
|
|
592
|
-
content: 'hello',
|
|
593
|
-
parentCid: 'Qm...', // the cid of the comment to reply to
|
|
594
|
-
communityAddress: '12D3KooW...',
|
|
595
|
-
onChallenge,
|
|
596
|
-
onChallengeVerification,
|
|
597
|
-
onError
|
|
598
|
-
}
|
|
599
|
-
const {publishComment} = usePublishComment(publishReplyOptions)
|
|
600
|
-
await publishComment()
|
|
601
|
-
|
|
602
|
-
// when displaying replies, it is recommended to include the user's pending replies
|
|
603
|
-
// https://github.com/bitsocialnet/bitsocial-react-hooks/#get-replies-to-a-post-nested (nested)
|
|
604
|
-
// https://github.com/bitsocialnet/bitsocial-react-hooks/#get-replies-to-a-post-flattened-not-nested (not nested)
|
|
605
|
-
```
|
|
606
|
-
|
|
607
|
-
#### Create a post or comment using hooks
|
|
608
|
-
|
|
609
|
-
```jsx
|
|
610
|
-
const publishCommentOptions = {
|
|
611
|
-
content: "hello",
|
|
612
|
-
title: "hello",
|
|
613
|
-
communityAddress: "12D3KooW...",
|
|
614
|
-
};
|
|
615
|
-
|
|
616
|
-
const {
|
|
617
|
-
index,
|
|
618
|
-
state,
|
|
619
|
-
publishComment,
|
|
620
|
-
challenge,
|
|
621
|
-
challengeVerification,
|
|
622
|
-
publishChallengeAnswers,
|
|
623
|
-
abandonPublish,
|
|
624
|
-
error,
|
|
625
|
-
} = usePublishComment(publishCommentOptions);
|
|
626
|
-
|
|
627
|
-
if (challenge) {
|
|
628
|
-
// display challenges to user and call publishChallengeAnswers(challengeAnswers)
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
if (challengeVerification) {
|
|
632
|
-
// display challengeVerification.challengeSuccess to user
|
|
633
|
-
// redirect to challengeVerification.publication.cid
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
if (error) {
|
|
637
|
-
// display error to user
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
// if the user closes your challenge modal:
|
|
641
|
-
if (challenge && challengeModalClosedByUser) {
|
|
642
|
-
await abandonPublish();
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
// after publishComment is called, the account comment index gets defined
|
|
646
|
-
// it is recommended to immediately redirect the user to a page displaying
|
|
647
|
-
// the user's comment with a "pending" label
|
|
648
|
-
if (index !== undefined) {
|
|
649
|
-
history.push(`/profile/c/${index}`);
|
|
650
|
-
// on the "pending" comment page, you can get the pending comment by doing
|
|
651
|
-
// const accountComment = useAccountComment({commentIndex: index})
|
|
652
|
-
// after accountComment.cid gets defined, it means the comment was published successfully
|
|
653
|
-
// it is recommended to immediately redirect to `/p/${accountComment.communityAddress}/c/${useAccountComment.cid}`
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
// create post
|
|
657
|
-
await publishComment();
|
|
658
|
-
```
|
|
659
|
-
|
|
660
|
-
#### Create a post or comment anonymously (without account.signer or account.author)
|
|
661
|
-
|
|
662
|
-
```jsx
|
|
663
|
-
const account = useAccount();
|
|
664
|
-
const signer = await account.pkc.createSigner();
|
|
665
|
-
|
|
666
|
-
const publishCommentOptions = {
|
|
667
|
-
content: "hello",
|
|
668
|
-
title: "hello",
|
|
669
|
-
communityAddress: "12D3KooW...",
|
|
670
|
-
// use a newly generated author address (optional)
|
|
671
|
-
signer,
|
|
672
|
-
// use a different display name (optional)
|
|
673
|
-
author: {
|
|
674
|
-
displayName: "Esteban",
|
|
675
|
-
address: signer.address,
|
|
676
|
-
},
|
|
677
|
-
};
|
|
678
|
-
|
|
679
|
-
const { publishComment } = usePublishComment(publishCommentOptions);
|
|
680
|
-
await publishComment();
|
|
681
|
-
```
|
|
682
|
-
|
|
683
|
-
#### Create a vote
|
|
684
|
-
|
|
685
|
-
```jsx
|
|
686
|
-
const commentCid = "QmZVYzLChjKrYDVty6e5JokKffGDZivmEJz9318EYfp2ui";
|
|
687
|
-
const publishVoteOptions = {
|
|
688
|
-
commentCid,
|
|
689
|
-
vote: 1,
|
|
690
|
-
communityAddress: "news.eth",
|
|
691
|
-
onChallenge,
|
|
692
|
-
onChallengeVerification,
|
|
693
|
-
onError,
|
|
694
|
-
};
|
|
695
|
-
const { state, error, publishVote, abandonPublish } = usePublishVote(publishVoteOptions);
|
|
696
|
-
|
|
697
|
-
await publishVote();
|
|
698
|
-
console.log(state);
|
|
699
|
-
console.log(error);
|
|
700
|
-
|
|
701
|
-
// if the user closes the challenge modal and wants to cancel voting:
|
|
702
|
-
await abandonPublish();
|
|
703
|
-
// the vote publication is stopped and the account vote goes back to what it was
|
|
704
|
-
// before publishVote(), so the optimistic vote does not survive a cancelled challenge
|
|
705
|
-
|
|
706
|
-
// display the user's vote
|
|
707
|
-
const { vote } = useAccountVote({ commentCid });
|
|
708
|
-
|
|
709
|
-
if (vote === 1) console.log("user voted 1");
|
|
710
|
-
if (vote === -1) console.log("user voted -1");
|
|
711
|
-
if (vote === 0) console.log("user voted 0");
|
|
712
|
-
if (vote === undefined) console.log(`user didn't vote yet`);
|
|
713
|
-
```
|
|
714
|
-
|
|
715
|
-
`useComment`, `useComments`, `useReplies`, and `useFeed` apply the selected account's pending vote
|
|
716
|
-
to `upvoteCount` and `downvoteCount` immediately, so a score updates the same way whether the vote
|
|
717
|
-
was cast from a feed or from a comment page. The optimistic adjustment is replaced by the next
|
|
718
|
-
canonical comment update.
|
|
719
|
-
|
|
720
|
-
#### Create a comment edit
|
|
721
|
-
|
|
722
|
-
```jsx
|
|
723
|
-
const publishCommentEditOptions = {
|
|
724
|
-
commentCid: "QmZVYzLChjKrYDVty6e5JokKffGDZivmEJz9318EYfp2ui",
|
|
725
|
-
content: "edited content",
|
|
726
|
-
communityAddress: "news.eth",
|
|
727
|
-
onChallenge,
|
|
728
|
-
onChallengeVerification,
|
|
729
|
-
onError,
|
|
730
|
-
};
|
|
731
|
-
const { state, error, publishCommentEdit } = usePublishCommentEdit(publishCommentEditOptions);
|
|
732
|
-
|
|
733
|
-
await publishCommentEdit();
|
|
734
|
-
console.log(state);
|
|
735
|
-
console.log(error);
|
|
736
|
-
|
|
737
|
-
// view the status of a comment edit instantly
|
|
738
|
-
let comment = useComment({ commentCid: publishCommentEditOptions.commentCid });
|
|
739
|
-
const { state: editedCommentState, editedComment } = useEditedComment({ comment });
|
|
740
|
-
|
|
741
|
-
// if the comment has a succeeded, failed or pending edit, use the edited comment
|
|
742
|
-
if (editedComment) {
|
|
743
|
-
comment = editedComment;
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
let editLabel;
|
|
747
|
-
if (editedCommentState === "succeeded") {
|
|
748
|
-
editLabel = { text: "EDITED", color: "green" };
|
|
749
|
-
}
|
|
750
|
-
if (editedCommentState === "pending") {
|
|
751
|
-
editLabel = { text: "PENDING EDIT", color: "orange" };
|
|
752
|
-
}
|
|
753
|
-
if (editedCommentState === "failed") {
|
|
754
|
-
editLabel = { text: "FAILED EDIT", color: "red" };
|
|
755
|
-
}
|
|
756
|
-
```
|
|
757
|
-
|
|
758
|
-
#### Create a comment moderation
|
|
759
|
-
|
|
760
|
-
```jsx
|
|
761
|
-
const publishCommentModerationOptions = {
|
|
762
|
-
commentCid: "QmZVYzLChjKrYDVty6e5JokKffGDZivmEJz9318EYfp2ui",
|
|
763
|
-
communityAddress: "news.eth",
|
|
764
|
-
commentModeration: { locked: true },
|
|
765
|
-
onChallenge,
|
|
766
|
-
onChallengeVerification,
|
|
767
|
-
onError,
|
|
768
|
-
};
|
|
769
|
-
const { state, error, publishCommentModeration } = usePublishCommentModeration(
|
|
770
|
-
publishCommentModerationOptions,
|
|
771
|
-
);
|
|
772
|
-
|
|
773
|
-
await publishCommentModeration();
|
|
774
|
-
console.log(state);
|
|
775
|
-
console.log(error);
|
|
776
|
-
|
|
777
|
-
// view the status of a comment moderation instantly
|
|
778
|
-
let comment = useComment({ commentCid: publishCommentModerationOptions.commentCid });
|
|
779
|
-
const { state: editedCommentState, editedComment } = useEditedComment({ comment });
|
|
780
|
-
|
|
781
|
-
// if the comment has a succeeded, failed or pending edit, use the edited comment
|
|
782
|
-
if (editedComment) {
|
|
783
|
-
comment = editedComment;
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
let editLabel;
|
|
787
|
-
if (editedCommentState === "succeeded") {
|
|
788
|
-
editLabel = { text: "EDITED", color: "green" };
|
|
789
|
-
}
|
|
790
|
-
if (editedCommentState === "pending") {
|
|
791
|
-
editLabel = { text: "PENDING EDIT", color: "orange" };
|
|
792
|
-
}
|
|
793
|
-
if (editedCommentState === "failed") {
|
|
794
|
-
editLabel = { text: "FAILED EDIT", color: "red" };
|
|
795
|
-
}
|
|
796
|
-
```
|
|
797
|
-
|
|
798
|
-
#### Delete a comment
|
|
799
|
-
|
|
800
|
-
You can remove comments from your local account database (local JSON export / IndexedDB state) in two ways.
|
|
801
|
-
This only removes local account history entries; it does not delete already-published network comments.
|
|
802
|
-
|
|
803
|
-
**1. Abandon a pending publish** — if you just published and want to cancel before it propagates:
|
|
804
|
-
|
|
805
|
-
```jsx
|
|
806
|
-
const { publishComment, abandonPublish } = usePublishComment(publishCommentOptions);
|
|
807
|
-
|
|
808
|
-
await publishComment();
|
|
809
|
-
// User changes mind — abandon the pending comment
|
|
810
|
-
await abandonPublish();
|
|
811
|
-
// Hook state returns to ready; the comment is removed from accountComments
|
|
812
|
-
```
|
|
813
|
-
|
|
814
|
-
**2. Delete by index or CID** — remove any of your comments (pending or published):
|
|
815
|
-
|
|
816
|
-
```jsx
|
|
817
|
-
import { deleteComment, useAccountComments } from "@bitsocial/bitsocial-react-hooks";
|
|
818
|
-
|
|
819
|
-
// By account comment index (from usePublishComment or useAccountComment)
|
|
820
|
-
const { index, publishComment } = usePublishComment(publishCommentOptions);
|
|
821
|
-
await publishComment();
|
|
822
|
-
await deleteComment(index);
|
|
823
|
-
|
|
824
|
-
// By comment CID (from useAccountComments or useAccountComment)
|
|
825
|
-
const { accountComments } = useAccountComments();
|
|
826
|
-
const accountComment = accountComments[0];
|
|
827
|
-
await deleteComment(accountComment.cid);
|
|
828
|
-
```
|
|
829
|
-
|
|
830
|
-
> **Note:** `accountComment.index` can change after deletions. If you delete a comment, indices of comments after it may shift. Prefer using `commentCid` when you need a stable identifier, or re-fetch `accountComments` after deletions.
|
|
831
|
-
|
|
832
|
-
**Common cleanup pattern (remove failed UI clutter):**
|
|
833
|
-
|
|
834
|
-
```jsx
|
|
835
|
-
import { deleteComment, useAccountComments } from "@bitsocial/bitsocial-react-hooks";
|
|
836
|
-
|
|
837
|
-
const { accountComments } = useAccountComments();
|
|
838
|
-
const failedComments = accountComments.filter((comment) => comment.state === "failed");
|
|
839
|
-
|
|
840
|
-
for (const failedComment of failedComments) {
|
|
841
|
-
// failed pending comments may not have a cid yet, so fallback to index
|
|
842
|
-
await deleteComment(failedComment.cid || failedComment.index);
|
|
843
|
-
}
|
|
844
|
-
```
|
|
845
|
-
|
|
846
|
-
#### Subscribe to a community
|
|
847
|
-
|
|
848
|
-
```jsx
|
|
849
|
-
let communityAddress = "news.eth";
|
|
850
|
-
communityAddress = "12D3KooWANwdyPERMQaCgiMnTT1t3Lr4XLFbK1z4ptFVhW2ozg1z";
|
|
851
|
-
communityAddress = "tech.eth";
|
|
852
|
-
const { subscribed, subscribe, unsubscribe } = useSubscribe({ communityAddress });
|
|
853
|
-
await subscribe();
|
|
854
|
-
console.log(subscribed); // true
|
|
855
|
-
|
|
856
|
-
// view subscriptions
|
|
857
|
-
const account = useAccount();
|
|
858
|
-
console.log(account.subscriptions); // ['news.eth', '12D3KooWANwdyPERMQaCgiMnTT1t3Lr4XLFbK1z4ptFVhW2ozg1z', 'tech.eth']
|
|
859
|
-
|
|
860
|
-
// unsubscribe
|
|
861
|
-
await unsubscribe();
|
|
862
|
-
|
|
863
|
-
// get a feed of subscriptions
|
|
864
|
-
const communities = account.subscriptions.map((communityAddress) => ({ name: communityAddress }));
|
|
865
|
-
const { feed, hasMore, loadMore } = useFeed({
|
|
866
|
-
communities,
|
|
867
|
-
sortType: "topAll",
|
|
868
|
-
});
|
|
869
|
-
console.log(feed);
|
|
870
|
-
```
|
|
871
|
-
|
|
872
|
-
#### Get feed
|
|
873
|
-
|
|
874
|
-
```jsx
|
|
875
|
-
import {Virtuoso} from 'react-virtuoso'
|
|
876
|
-
const topAllCommunities = [
|
|
877
|
-
{name: 'memes.eth', publicKey: '12D3KooWMemes...'},
|
|
878
|
-
{publicKey: '12D3KooWNews...'},
|
|
879
|
-
{publicKey: '12D3KooWTech...'},
|
|
880
|
-
]
|
|
881
|
-
const {feed, hasMore, loadMore} = useFeed({communities: topAllCommunities, sortType: 'topAll'})
|
|
882
|
-
|
|
883
|
-
<Virtuoso
|
|
884
|
-
data={feed}
|
|
885
|
-
itemContent={(index, post) => <Post index={index} post={post}/>}
|
|
886
|
-
useWindowScroll={true}
|
|
887
|
-
components={{Footer: hasMore ? () => <Loading/> : undefined}}
|
|
888
|
-
endReached={loadMore}
|
|
889
|
-
increaseViewportBy={{bottom: 600, top: 600}}
|
|
890
|
-
/>
|
|
891
|
-
|
|
892
|
-
// you probably will want to buffer some feeds in the background so they are already loaded
|
|
893
|
-
// when you need them
|
|
894
|
-
useBufferedFeeds({
|
|
895
|
-
feedsOptions: [
|
|
896
|
-
{communities: [{name: 'news.eth'}, {name: 'crypto.eth'}], sortType: 'new'},
|
|
897
|
-
{communities: [{name: 'memes.eth', publicKey: '12D3KooWMemes...'}], sortType: 'topWeek'},
|
|
898
|
-
{communities: [{publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}], sortType: 'hot'}
|
|
899
|
-
]
|
|
900
|
-
})
|
|
901
|
-
|
|
902
|
-
// search a feed
|
|
903
|
-
const createSearchFilter = (searchTerm) => ({
|
|
904
|
-
filter: (comment) => comment.title?.includes(searchTerm) || comment.content?.includes(searchTerm),
|
|
905
|
-
key: `includes-${searchTerm}` // required key to cache the filter
|
|
906
|
-
})
|
|
907
|
-
const searchFilter = createSearchFilter('bitcoin')
|
|
908
|
-
const searchedCommunities = communityAddresses.map((communityAddress) => ({ name: communityAddress }))
|
|
909
|
-
const {feed, hasMore, loadMore} = useFeed({communities: searchedCommunities, filter: searchFilter})
|
|
910
|
-
|
|
911
|
-
// image only feed
|
|
912
|
-
const imageOnlyFilter = {
|
|
913
|
-
filter: (comment) => getCommentLinkMediaType(comment?.link) === 'image',
|
|
914
|
-
key: 'image-only' // required key to cache the filter
|
|
915
|
-
}
|
|
916
|
-
const {feed, hasMore, loadMore} = useFeed({
|
|
917
|
-
communities: searchedCommunities,
|
|
918
|
-
filter: imageOnlyFilter,
|
|
919
|
-
})
|
|
920
|
-
|
|
921
|
-
// widen a freshness window without replacing the current feed instance
|
|
922
|
-
const {feed, expandTimeWindow} = useFeed({
|
|
923
|
-
communities: [{name: 'news.eth'}],
|
|
924
|
-
sortType: 'active',
|
|
925
|
-
newerThan: 60 * 60 * 24,
|
|
926
|
-
})
|
|
7
|
+
<p><strong>Build your corner of the internet.</strong></p>
|
|
927
8
|
|
|
928
|
-
|
|
929
|
-
```
|
|
930
|
-
|
|
931
|
-
#### Get mod queue (pending approval)
|
|
9
|
+
React hooks for communities, feeds, conversations, profiles, accounts, and publishing on the [Bitsocial protocol](https://bitsocial.net). Bring your own interface; the hooks connect it to shared protocol state through Zustand stores.
|
|
932
10
|
|
|
933
|
-
|
|
934
|
-
import {Virtuoso} from 'react-virtuoso'
|
|
935
|
-
const {feed, hasMore, loadMore} = useFeed({
|
|
936
|
-
communities: [{name: 'memes.eth'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}],
|
|
937
|
-
modQueue: ['pendingApproval']
|
|
938
|
-
})
|
|
11
|
+
[**Documentation**](https://hooks.bitsocial.net/) · [**Try the playground**](https://hooks.bitsocial.net/#playground) · [API & recipes](docs/reference.md) · [npm](https://www.npmjs.com/package/@bitsocial/bitsocial-react-hooks)
|
|
939
12
|
|
|
940
|
-
|
|
941
|
-
data={feed}
|
|
942
|
-
itemContent={(index, post) => <Post index={index} post={post}/>}
|
|
943
|
-
useWindowScroll={true}
|
|
944
|
-
components={{Footer: hasMore ? () => <Loading/> : undefined}}
|
|
945
|
-
endReached={loadMore}
|
|
946
|
-
increaseViewportBy={{bottom: 600, top: 600}}
|
|
947
|
-
/>
|
|
948
|
-
```
|
|
13
|
+
[](https://hooks.bitsocial.net/#playground)
|
|
949
14
|
|
|
950
|
-
|
|
15
|
+
*Edit a component and see the result. The playground uses simulated content and publishes nothing.*
|
|
951
16
|
|
|
952
|
-
|
|
17
|
+
Supports **React 16.8+**. Used by [5chan](https://github.com/bitsocialnet/5chan).
|
|
953
18
|
|
|
954
|
-
|
|
955
|
-
const publishCommentModerationOptions = {
|
|
956
|
-
commentCid: "QmZVYzLChjKrYDVty6e5JokKffGDZivmEJz9318EYfp2ui",
|
|
957
|
-
communityAddress: "news.eth",
|
|
958
|
-
commentModeration: { approved: true },
|
|
959
|
-
onChallenge,
|
|
960
|
-
onChallengeVerification,
|
|
961
|
-
onError,
|
|
962
|
-
};
|
|
963
|
-
const { state, error, publishCommentModeration } = usePublishCommentModeration(
|
|
964
|
-
publishCommentModerationOptions,
|
|
965
|
-
);
|
|
966
|
-
|
|
967
|
-
await publishCommentModeration();
|
|
968
|
-
console.log(state);
|
|
969
|
-
console.log(error);
|
|
970
|
-
```
|
|
19
|
+
## Start building
|
|
971
20
|
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
```jsx
|
|
975
|
-
import {useAccount, setAccount, useResolvedAuthorAddress} from '@bitsocial/bitsocial-react-hooks'
|
|
976
|
-
const account = useAccount() // or useAccount('Account KoXpxTwfnjA5') to use an account by name
|
|
977
|
-
|
|
978
|
-
// `account.author.wallets` only auto-generates an `eth` wallet by default.
|
|
979
|
-
// `account.chainProviders` is the canonical chain config for wallets, NFT lookups, and other chain reads.
|
|
980
|
-
// Defaults use multiple explicit Ethereum RPCs for `.eth` / `.bso` author-name resolution.
|
|
981
|
-
// Web defaults run a browser libp2p client and use multiple HTTP routers to discover peers.
|
|
982
|
-
// IPFS gateways and HTTP pubsub providers remain available as explicit account or app overrides.
|
|
983
|
-
// `account.nameResolversChainProviders` optionally overrides only the RPCs used for that resolution.
|
|
984
|
-
console.log(account.author.wallets.eth)
|
|
985
|
-
|
|
986
|
-
const ethResolverRpcUrls = [
|
|
987
|
-
'https://ethereum-rpc.publicnode.com',
|
|
988
|
-
'https://eth.drpc.org',
|
|
989
|
-
'https://ethereum.publicnode.com',
|
|
990
|
-
'https://rpc.mevblocker.io',
|
|
991
|
-
'https://1rpc.io/eth',
|
|
992
|
-
'https://eth-pokt.nodies.app',
|
|
993
|
-
]
|
|
994
|
-
|
|
995
|
-
const httpRoutersOptions = [
|
|
996
|
-
'https://peers.pleb.bot',
|
|
997
|
-
'https://routing.lol',
|
|
998
|
-
'https://peers.forumindex.com',
|
|
999
|
-
'https://peers.plebpubsub.xyz',
|
|
1000
|
-
'https://routerofbitsocial.xyz',
|
|
1001
|
-
'https://bsotracker.online',
|
|
1002
|
-
]
|
|
1003
|
-
|
|
1004
|
-
const author: {...account.author, displayName: 'John'}
|
|
1005
|
-
const editedAccount = {
|
|
1006
|
-
...account,
|
|
1007
|
-
author,
|
|
1008
|
-
chainProviders: {
|
|
1009
|
-
...account.chainProviders,
|
|
1010
|
-
eth: { urls: [...ethResolverRpcUrls, 'ethers.js'], chainId: 1 },
|
|
1011
|
-
},
|
|
1012
|
-
pkcOptions: {
|
|
1013
|
-
...account.pkcOptions,
|
|
1014
|
-
httpRoutersOptions,
|
|
1015
|
-
},
|
|
1016
|
-
nameResolversChainProviders: {
|
|
1017
|
-
eth: { urls: ethResolverRpcUrls, chainId: 1 },
|
|
1018
|
-
},
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
await setAccount(editedAccount)
|
|
1022
|
-
|
|
1023
|
-
// check if the user has set their .eth or .bso author name properly, use {cache: false} or it won't update
|
|
1024
|
-
const author = {...account.author, address: 'username.bso'} // or 'username.eth'
|
|
1025
|
-
// authorAddress should equal to account.signer.address
|
|
1026
|
-
const {resolvedAddress, state, error, chainProvider, nameResolver} = useResolvedAuthorAddress({author, cache: false})
|
|
1027
|
-
|
|
1028
|
-
// result
|
|
1029
|
-
if (state === 'succeeded') {
|
|
1030
|
-
console.log('Succeeded resolving address', resolvedAddress)
|
|
1031
|
-
}
|
|
1032
|
-
if (state === 'failed') {
|
|
1033
|
-
console.log('Failed resolving address', error.message)
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
// pending
|
|
1037
|
-
if (state === 'resolving' && nameResolver) {
|
|
1038
|
-
console.log(`Resolving ${nameResolver.nameSystem} address from ${nameResolver.providerLabel}`)
|
|
1039
|
-
console.log('Matching chain provider URLs', chainProvider?.urls)
|
|
1040
|
-
}
|
|
1041
|
-
```
|
|
1042
|
-
|
|
1043
|
-
#### Delete account
|
|
1044
|
-
|
|
1045
|
-
> Note: deleting account is unrecoverable, warn the user to export/backup his account before deleting
|
|
1046
|
-
|
|
1047
|
-
```jsx
|
|
1048
|
-
import { deleteAccount } from "@bitsocial/bitsocial-react-hooks";
|
|
1049
|
-
|
|
1050
|
-
// delete active account
|
|
1051
|
-
await deleteAccount();
|
|
1052
|
-
|
|
1053
|
-
// delete account by name
|
|
1054
|
-
await deleteAccount("Account KoXpxTwfnjA5");
|
|
1055
|
-
```
|
|
1056
|
-
|
|
1057
|
-
#### Get your own comments and votes
|
|
1058
|
-
|
|
1059
|
-
```jsx
|
|
1060
|
-
// all my own comments
|
|
1061
|
-
const { accountComments } = useAccountComments();
|
|
1062
|
-
for (const accountComment of accountComments) {
|
|
1063
|
-
// it is recommended to show a label in the UI if accountComment.state is 'pending' or 'failed'
|
|
1064
|
-
console.log("comment", accountComment.index, "is status", accountComment.state);
|
|
1065
|
-
}
|
|
1066
|
-
// `state` becomes `failed` as soon as a pending local publish records terminal failure (`publishingState === "failed"` and `state === "stopped"`) or a publish error, instead of waiting for the 20-minute fallback.
|
|
1067
|
-
// local account comments returned by useAccountComment and useAccountComments include the account author's address and shortAddress when an older cached account comment is missing author identity fields.
|
|
1068
|
-
// note: accountComment.index can change after deletions; prefer commentCid for stable identifiers
|
|
1069
|
-
|
|
1070
|
-
// all my own votes
|
|
1071
|
-
const { accountVotes } = useAccountVotes();
|
|
1072
|
-
|
|
1073
|
-
// my own comments in memes.eth
|
|
1074
|
-
const communityAddress = "memes.eth";
|
|
1075
|
-
const myCommentsInMemesEth = useAccountComments({ communityAddress });
|
|
1076
|
-
|
|
1077
|
-
// my own posts in memes.eth
|
|
1078
|
-
const filter = useCallback(
|
|
1079
|
-
(comment) => comment.communityAddress === communityAddress && !comment.parentCid,
|
|
1080
|
-
[communityAddress],
|
|
1081
|
-
);
|
|
1082
|
-
const myPostsInMemesEth = useAccountComments({ filter });
|
|
1083
|
-
|
|
1084
|
-
// my own replies in a post with cid 'Qm...'
|
|
1085
|
-
const postCid = "Qm...";
|
|
1086
|
-
const filter = useCallback((comment) => comment.postCid === postCid, [postCid]);
|
|
1087
|
-
const myCommentsInSomePost = useAccountComments({ filter });
|
|
1088
|
-
|
|
1089
|
-
// my own replies to a comment with cid 'Qm...'
|
|
1090
|
-
const parentCommentCid = "Qm...";
|
|
1091
|
-
const myRepliesToSomeComment = useAccountComments({ parentCid: parentCommentCid });
|
|
1092
|
-
|
|
1093
|
-
// recent own comments in memes.eth, newest first, one page at a time
|
|
1094
|
-
const recentMyCommentsInMemesEth = useAccountComments({
|
|
1095
|
-
communityAddress,
|
|
1096
|
-
newerThan: 60 * 60 * 24 * 30,
|
|
1097
|
-
sortType: "new",
|
|
1098
|
-
page: 0,
|
|
1099
|
-
pageSize: 20,
|
|
1100
|
-
});
|
|
1101
|
-
|
|
1102
|
-
// get one own comment directly by cid
|
|
1103
|
-
const accountComment = useAccountComment({ commentCid: "Qm..." });
|
|
1104
|
-
|
|
1105
|
-
// get a specific set of own comments by account comment index
|
|
1106
|
-
const replacementReplies = useAccountComments({ commentIndices: [5, 7, 9] });
|
|
1107
|
-
|
|
1108
|
-
// voted profile tab helpers
|
|
1109
|
-
const recentUpvotes = useAccountVotes({
|
|
1110
|
-
vote: 1,
|
|
1111
|
-
newerThan: 60 * 60 * 24 * 30,
|
|
1112
|
-
sortType: "new",
|
|
1113
|
-
page: 0,
|
|
1114
|
-
pageSize: 20,
|
|
1115
|
-
});
|
|
1116
|
-
|
|
1117
|
-
// know if you upvoted a comment already with cid 'Qm...'
|
|
1118
|
-
const { vote } = useAccountVote({ commentCid: "Qm..." });
|
|
1119
|
-
console.log(vote); // 1, -1 or 0
|
|
1120
|
-
|
|
1121
|
-
// my own pending posts in a feed
|
|
1122
|
-
const { feed } = useFeed({
|
|
1123
|
-
communities: [{ name: communityAddress }],
|
|
1124
|
-
accountComments: { newerThan: Infinity, append: false },
|
|
1125
|
-
});
|
|
1126
|
-
|
|
1127
|
-
// my own pending replies in a replies feed
|
|
1128
|
-
const { replies } = useReplies({
|
|
1129
|
-
comment: post,
|
|
1130
|
-
accountComments: { newerThan: Infinity, append: false },
|
|
1131
|
-
});
|
|
1132
|
-
|
|
1133
|
-
// pending local account comments are reconciled with their approved network version
|
|
1134
|
-
// so the same post or reply is not shown twice after moderation approval
|
|
1135
|
-
// published account replies stay visible and are deduplicated by cid while
|
|
1136
|
-
// canonical replies propagate; explicitly purged replies are hidden after an
|
|
1137
|
-
// exhausted canonical feed refreshes past their timestamp
|
|
1138
|
-
```
|
|
1139
|
-
|
|
1140
|
-
#### Determine if a comment is your own
|
|
1141
|
-
|
|
1142
|
-
```jsx
|
|
1143
|
-
const account = useAccount();
|
|
1144
|
-
const comment = useComment({ commentCid });
|
|
1145
|
-
const isMyOwnComment = account?.author.address === comment?.author.address;
|
|
1146
|
-
```
|
|
1147
|
-
|
|
1148
|
-
#### Get account notifications
|
|
1149
|
-
|
|
1150
|
-
```jsx
|
|
1151
|
-
const { notifications, markAsRead } = useNotifications();
|
|
1152
|
-
for (const notification of notifications) {
|
|
1153
|
-
console.log(notification);
|
|
1154
|
-
}
|
|
1155
|
-
await markAsRead();
|
|
1156
|
-
|
|
1157
|
-
const johnsNotifications = useNotifications({ accountName: "John" });
|
|
1158
|
-
for (const notification of johnsNotifications.notifications) {
|
|
1159
|
-
console.log(notification);
|
|
1160
|
-
}
|
|
1161
|
-
await johnsNotifications.markAsRead();
|
|
1162
|
-
|
|
1163
|
-
// get the unread notification counts for all accounts
|
|
1164
|
-
const { accounts } = useAccounts();
|
|
1165
|
-
const accountsUnreadNotificationsCounts = accounts?.map(
|
|
1166
|
-
(account) => account.unreadNotificationCount,
|
|
1167
|
-
);
|
|
1168
|
-
```
|
|
1169
|
-
|
|
1170
|
-
#### Block an address (author, community or multisub)
|
|
1171
|
-
|
|
1172
|
-
```jsx
|
|
1173
|
-
const address: 'community-address.eth' // or 'author-address.eth' or '12D3KooW...'
|
|
1174
|
-
const {blocked, unblock, block} = useBlock({address})
|
|
21
|
+
Add the package to an existing React app:
|
|
1175
22
|
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
}
|
|
1179
|
-
else {
|
|
1180
|
-
console.log(`'${address}' is not blocked`)
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
// to block
|
|
1184
|
-
block()
|
|
1185
|
-
|
|
1186
|
-
// to unblock
|
|
1187
|
-
unblock()
|
|
1188
|
-
```
|
|
1189
|
-
|
|
1190
|
-
#### Block a cid (hide a comment)
|
|
1191
|
-
|
|
1192
|
-
```jsx
|
|
1193
|
-
const { blocked, unblock, block } = useBlock({ cid: "Qm..." });
|
|
1194
|
-
|
|
1195
|
-
if (blocked) {
|
|
1196
|
-
console.log(`'${cid}' is blocked`);
|
|
1197
|
-
} else {
|
|
1198
|
-
console.log(`'${cid}' is not blocked`);
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
// to block
|
|
1202
|
-
block();
|
|
1203
|
-
|
|
1204
|
-
// to unblock
|
|
1205
|
-
unblock();
|
|
1206
|
-
```
|
|
1207
|
-
|
|
1208
|
-
#### Save a comment
|
|
1209
|
-
|
|
1210
|
-
Saved comments are kept in the account's `savedComments` list and are included when the account is exported.
|
|
1211
|
-
|
|
1212
|
-
```jsx
|
|
1213
|
-
const { saved, saveComment, unsaveComment } = useSaveComment({ commentCid: "Qm..." });
|
|
1214
|
-
|
|
1215
|
-
if (saved) {
|
|
1216
|
-
await unsaveComment();
|
|
1217
|
-
} else {
|
|
1218
|
-
await saveComment();
|
|
1219
|
-
}
|
|
1220
|
-
```
|
|
1221
|
-
|
|
1222
|
-
#### (Desktop only) Create a community
|
|
1223
|
-
|
|
1224
|
-
```jsx
|
|
1225
|
-
const createCommunityOptions = { title: "My community title" };
|
|
1226
|
-
const { createdCommunity, createCommunity } = useCreateCommunity(createCommunityOptions);
|
|
1227
|
-
await createCommunity();
|
|
1228
|
-
|
|
1229
|
-
// it is recommended to redirect to `p/${createdCommunity.address}` after creation
|
|
1230
|
-
if (createdCommunity?.address) {
|
|
1231
|
-
console.log("created community with title", createdCommunity.title);
|
|
1232
|
-
history.push(`/p/${createdCommunity.address}`);
|
|
1233
|
-
}
|
|
1234
|
-
|
|
1235
|
-
// after the community is created, fetch it using
|
|
1236
|
-
const { accountCommunities } = useAccountCommunities();
|
|
1237
|
-
const accountCommunityAddresses = Object.keys(accountCommunities);
|
|
1238
|
-
const communities = useCommunities({
|
|
1239
|
-
communities: accountCommunityAddresses.map((communityAddress) => ({ name: communityAddress })),
|
|
1240
|
-
});
|
|
1241
|
-
// or
|
|
1242
|
-
const _community = useCommunity({ community: { name: createdCommunity.address } });
|
|
1243
|
-
```
|
|
1244
|
-
|
|
1245
|
-
#### (Desktop only) Export communities
|
|
1246
|
-
|
|
1247
|
-
```jsx
|
|
1248
|
-
// Export one community.
|
|
1249
|
-
const { communityExports, exportCommunity, state, error } = useExportCommunity({
|
|
1250
|
-
communityAddress: "your-community-address.eth",
|
|
1251
|
-
});
|
|
1252
|
-
await exportCommunity();
|
|
1253
|
-
|
|
1254
|
-
// Export several communities at the same time.
|
|
1255
|
-
const exportMany = useExportCommunity({
|
|
1256
|
-
communityAddresses: ["community-1.eth", "community-2.eth"],
|
|
1257
|
-
});
|
|
1258
|
-
await exportMany.exportCommunity();
|
|
1259
|
-
|
|
1260
|
-
// Export every community listed by the active account's pkc client.
|
|
1261
|
-
const exportAll = useExportCommunity();
|
|
1262
|
-
await exportAll.exportCommunity();
|
|
1263
|
-
|
|
1264
|
-
if (state === "succeeded") {
|
|
1265
|
-
console.log("started exports", communityExports);
|
|
1266
|
-
}
|
|
1267
|
-
if (state === "failed") {
|
|
1268
|
-
console.log("failed to start export", error.message);
|
|
1269
|
-
}
|
|
23
|
+
```bash
|
|
24
|
+
yarn add @bitsocial/bitsocial-react-hooks
|
|
1270
25
|
```
|
|
1271
26
|
|
|
1272
|
-
|
|
27
|
+
Render this component in the browser with an existing community name:
|
|
1273
28
|
|
|
1274
29
|
```jsx
|
|
1275
|
-
|
|
1276
|
-
const ownerCommunityAddresses = Object.keys(accountCommunities).filter(
|
|
1277
|
-
(communityAddress) => accountCommunities[communityAddress].role?.role === "owner",
|
|
1278
|
-
);
|
|
1279
|
-
const communities = useCommunities({
|
|
1280
|
-
communities: ownerCommunityAddresses.map((communityAddress) => ({ name: communityAddress })),
|
|
1281
|
-
});
|
|
1282
|
-
```
|
|
1283
|
-
|
|
1284
|
-
#### (Desktop only) Edit your community settings
|
|
30
|
+
import { useCommunity } from "@bitsocial/bitsocial-react-hooks";
|
|
1285
31
|
|
|
1286
|
-
|
|
32
|
+
export default function CommunityCard({ name }) {
|
|
33
|
+
const community = useCommunity({ community: { name } });
|
|
1287
34
|
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
catch (e) {}
|
|
1295
|
-
if (challengeAnswers) {
|
|
1296
|
-
await communityEdit.publishChallengeAnswers(challengeAnswers)
|
|
35
|
+
if (!community.hasCachedData) {
|
|
36
|
+
return (
|
|
37
|
+
<p role="status">
|
|
38
|
+
{community.error?.message || "Loading community…"}
|
|
39
|
+
</p>
|
|
40
|
+
);
|
|
1297
41
|
}
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
const onChallengeVerification = (challengeVerification, communityEdit) => {
|
|
1301
|
-
console.log('challenge verified', challengeVerification)
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
const onError = (error, communityEdit) => console.error(error)
|
|
1305
|
-
|
|
1306
|
-
// add ENS to your community
|
|
1307
|
-
const editCommunityOptions = {
|
|
1308
|
-
communityAddress: '12D3KooWANwdyPERMQaCgiMnTT1t3Lr4XLFbK1z4ptFVhW2ozg1z', // the previous address before changing it
|
|
1309
|
-
address: 'your-community-address.eth', // the new address to change to
|
|
1310
|
-
onChallenge,
|
|
1311
|
-
onChallengeVerification,
|
|
1312
|
-
onError
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
await publishCommunityEdit()
|
|
1316
|
-
|
|
1317
|
-
// edit other community settings
|
|
1318
|
-
const editCommunityOptions = {
|
|
1319
|
-
communityAddress: 'your-community-address.eth', // the address of the community to change
|
|
1320
|
-
title: 'Your title',
|
|
1321
|
-
description: 'Your description',
|
|
1322
|
-
onChallenge,
|
|
1323
|
-
onChallengeVerification,
|
|
1324
|
-
onError
|
|
1325
|
-
}
|
|
1326
|
-
const {publishCommunityEdit} = usePublishCommunityEdit(editCommunityOptions)
|
|
1327
|
-
await publishCommunityEdit()
|
|
1328
|
-
|
|
1329
|
-
// verify if ENS was set correctly, use {cache: false} or it won't update
|
|
1330
|
-
const {resolvedAddress} = useResolvedCommunityAddress({communityAddress: 'your-community-address.eth', cache: false})
|
|
1331
|
-
|
|
1332
|
-
// result
|
|
1333
|
-
if (state === 'succeeded') {
|
|
1334
|
-
console.log('Succeeded resolving address', resolvedAddress)
|
|
1335
|
-
console.log('ENS set correctly', resolvedAddress === community.signer.address)
|
|
1336
|
-
}
|
|
1337
|
-
if (state === 'failed') {
|
|
1338
|
-
console.log('Failed resolving address', error.message)
|
|
1339
|
-
}
|
|
1340
|
-
|
|
1341
|
-
// pending
|
|
1342
|
-
if (state === 'resolving') {
|
|
1343
|
-
console.log('Resolving address from chain provider URL', chainProvider.urls)
|
|
1344
|
-
}
|
|
1345
|
-
```
|
|
1346
|
-
|
|
1347
|
-
#### Export and import account
|
|
1348
|
-
|
|
1349
|
-
```jsx
|
|
1350
|
-
import {
|
|
1351
|
-
exportAccount,
|
|
1352
|
-
importAccount,
|
|
1353
|
-
setActiveAccount,
|
|
1354
|
-
setAccountsOrder,
|
|
1355
|
-
} from "@bitsocial/bitsocial-react-hooks";
|
|
1356
|
-
|
|
1357
|
-
// New accounts default to `Account {author short address}`, while custom and legacy names are preserved.
|
|
1358
|
-
const activeAccount = useAccount();
|
|
1359
|
-
const activeAccountName = activeAccount.name;
|
|
1360
|
-
|
|
1361
|
-
// export active account, tell user to copy or download this json
|
|
1362
|
-
const activeAccountJson = await exportAccount();
|
|
1363
|
-
|
|
1364
|
-
// import account
|
|
1365
|
-
await importAccount(activeAccountJson);
|
|
1366
|
-
|
|
1367
|
-
// Importing the same identity again uses the next available numeric suffix.
|
|
1368
|
-
const importedAccountName = `${activeAccountName} 2`;
|
|
1369
|
-
const importedAccount = useAccount(importedAccountName);
|
|
1370
|
-
|
|
1371
|
-
// make imported account active account
|
|
1372
|
-
await setActiveAccount(importedAccountName);
|
|
1373
|
-
|
|
1374
|
-
// reorder the accounts list
|
|
1375
|
-
await setAccountsOrder([importedAccountName, activeAccountName]);
|
|
1376
|
-
```
|
|
1377
|
-
|
|
1378
|
-
#### View the status of a comment edit
|
|
1379
|
-
|
|
1380
|
-
```jsx
|
|
1381
|
-
let comment = useComment({ commentCid });
|
|
1382
|
-
const { state: editedCommentState, editedComment } = useEditedComment({ comment });
|
|
1383
|
-
|
|
1384
|
-
// if the comment has a succeeded, failed or pending edit, use the edited comment
|
|
1385
|
-
if (editedComment) {
|
|
1386
|
-
comment = editedComment;
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1389
|
-
let editLabel;
|
|
1390
|
-
if (editedCommentState === "succeeded") {
|
|
1391
|
-
editLabel = { text: "EDITED", color: "green" };
|
|
1392
|
-
}
|
|
1393
|
-
if (editedCommentState === "pending") {
|
|
1394
|
-
editLabel = { text: "PENDING EDIT", color: "orange" };
|
|
1395
|
-
}
|
|
1396
|
-
if (editedCommentState === "failed") {
|
|
1397
|
-
editLabel = { text: "FAILED EDIT", color: "red" };
|
|
1398
|
-
}
|
|
1399
|
-
```
|
|
1400
|
-
|
|
1401
|
-
#### View the status of a specific comment edit property
|
|
1402
|
-
|
|
1403
|
-
```jsx
|
|
1404
|
-
const comment = useComment({ commentCid });
|
|
1405
|
-
const editedComment = useEditedComment({ comment });
|
|
1406
|
-
if (editedComment.failedEdits.removed !== undefined) {
|
|
1407
|
-
console.log("failed editing comment.removed property");
|
|
1408
|
-
}
|
|
1409
|
-
if (editedComment.succeededEdits.removed !== undefined) {
|
|
1410
|
-
console.log("succeeded editing comment.removed property");
|
|
1411
|
-
}
|
|
1412
|
-
if (editedCommentResult.pendingEdits.removed !== undefined) {
|
|
1413
|
-
console.log("pending editing comment.removed property");
|
|
1414
|
-
}
|
|
1415
42
|
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
```
|
|
1423
|
-
|
|
1424
|
-
Moderation fields are mirrored on both the top-level keys like `comment.removed` and the nested `comment.commentModeration.removed` shape.
|
|
1425
|
-
|
|
1426
|
-
#### List all comment and community edits the account has performed
|
|
1427
|
-
|
|
1428
|
-
```jsx
|
|
1429
|
-
const { accountEdits } = useAccountEdits();
|
|
1430
|
-
for (const accountEdit of accountEdits) {
|
|
1431
|
-
console.log(accountEdit);
|
|
43
|
+
return (
|
|
44
|
+
<article>
|
|
45
|
+
<h1>{community.title || name}</h1>
|
|
46
|
+
<p>{community.description}</p>
|
|
47
|
+
</article>
|
|
48
|
+
);
|
|
1432
49
|
}
|
|
1433
|
-
console.log(`there's ${accountEdits.length} account edits`);
|
|
1434
|
-
|
|
1435
|
-
// get only the account edits of a specific comment
|
|
1436
|
-
const commentCid = "Qm...";
|
|
1437
|
-
const filter = useCallback((edit) => edit.commentCid === commentCid, [commentCid]); // important to use useMemo or the same function or will cause rerenders
|
|
1438
|
-
const { accountEdits } = useAccountEdits({ filter });
|
|
1439
|
-
|
|
1440
|
-
// only get account edits in a specific community
|
|
1441
|
-
const communityAddress = "news.eth";
|
|
1442
|
-
const filter = useCallback(
|
|
1443
|
-
(edit) => edit.communityAddress === communityAddress,
|
|
1444
|
-
[communityAddress],
|
|
1445
|
-
);
|
|
1446
|
-
const { accountEdits } = useAccountEdits({ filter });
|
|
1447
50
|
```
|
|
1448
51
|
|
|
1449
|
-
|
|
52
|
+
The package initializes a local account automatically. You can also identify a community with `{ publicKey }`, or pass both `{ name, publicKey }`. Hooks share cached data and subscriptions; use `syncState` when you need to show background refresh progress.
|
|
1450
53
|
|
|
1451
|
-
|
|
1452
|
-
import { useReplies, useComment, useAccountComment } from "@bitsocial/bitsocial-react-hooks";
|
|
54
|
+
## Explore the docs
|
|
1453
55
|
|
|
1454
|
-
|
|
1455
|
-
const useRepliesOptions = {
|
|
1456
|
-
sortType: "best",
|
|
1457
|
-
flat: false,
|
|
1458
|
-
repliesPerPage: 20,
|
|
1459
|
-
onlyIfCached: false,
|
|
1460
|
-
accountComments: { newerThan: Infinity, append: false },
|
|
1461
|
-
};
|
|
56
|
+
Read the guides at [hooks.bitsocial.net](https://hooks.bitsocial.net/), or browse their source here:
|
|
1462
57
|
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
58
|
+
- [Quickstart](website/content/quickstart.md) — build your first feed.
|
|
59
|
+
- [Core concepts](website/content/concepts.md) — communities, accounts, state, and publishing.
|
|
60
|
+
- [Full API and recipes](docs/reference.md) — the complete hook reference and practical examples.
|
|
61
|
+
- [Mock content](docs/mock-content.md) — develop a UI with sample data.
|
|
62
|
+
- [AI context](website/content/ai.md), [llms.txt](llms.txt), and [llms-full.txt](llms-full.txt) — documentation for your coding assistant.
|
|
1466
63
|
|
|
1467
|
-
|
|
1468
|
-
const { replies, updatedReplies, bufferedReplies, hasMore, loadMore } = useReplies({
|
|
1469
|
-
...useRepliesOptions,
|
|
1470
|
-
comment: reply,
|
|
1471
|
-
});
|
|
64
|
+
### Run the website locally
|
|
1472
65
|
|
|
1473
|
-
|
|
1474
|
-
const score = (updatedReply?.upvoteCount || 0) - (updatedReply?.downvoteCount || 0);
|
|
66
|
+
The site lives in [`website/`](website/README.md). To open the playground and docs in your browser:
|
|
1475
67
|
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
// publishing states exist only on account comment
|
|
1481
|
-
const accountReply = useAccountComment({ commentIndex: reply.index });
|
|
1482
|
-
const state = accountReply?.state;
|
|
1483
|
-
const publishingStateString = useStateString(accountReply);
|
|
1484
|
-
|
|
1485
|
-
return (
|
|
1486
|
-
<div>
|
|
1487
|
-
<div>
|
|
1488
|
-
{score} {reply.author.address} {reply.timestamp} {moreReplies}
|
|
1489
|
-
</div>
|
|
1490
|
-
{state === "pending" && <div>PENDING ({publishingStateString})</div>}
|
|
1491
|
-
{state === "failed" && <div>FAILED</div>}
|
|
1492
|
-
<div>{reply.content}</div>
|
|
1493
|
-
<div style={{ marginLeft: 4 }}>
|
|
1494
|
-
{replies.map((reply, index) => (
|
|
1495
|
-
<Reply
|
|
1496
|
-
key={reply?.index || reply?.cid}
|
|
1497
|
-
reply={reply}
|
|
1498
|
-
updatedReply={updatedReplies[index]}
|
|
1499
|
-
/>
|
|
1500
|
-
))}
|
|
1501
|
-
</div>
|
|
1502
|
-
</div>
|
|
1503
|
-
);
|
|
1504
|
-
};
|
|
1505
|
-
|
|
1506
|
-
const comment = useComment({ commentCid });
|
|
1507
|
-
const { replies, updatedReplies, hasMore, loadMore } = useReplies({
|
|
1508
|
-
...useRepliesOptions,
|
|
1509
|
-
comment,
|
|
1510
|
-
});
|
|
1511
|
-
const repliesComponents = replies.map((reply, index) => (
|
|
1512
|
-
<Reply key={reply?.index || reply?.cid} reply={reply} updatedReply={updatedReplies[index]} />
|
|
1513
|
-
));
|
|
68
|
+
```bash
|
|
69
|
+
cd website
|
|
70
|
+
corepack yarn install --immutable
|
|
71
|
+
corepack yarn start
|
|
1514
72
|
```
|
|
1515
73
|
|
|
1516
|
-
|
|
74
|
+
## Contribute
|
|
1517
75
|
|
|
1518
|
-
|
|
1519
|
-
import { useShortAddress, useShortCid } from "@bitsocial/bitsocial-react-hooks";
|
|
76
|
+
Use Node 22 and the repository's pinned Yarn 4 release:
|
|
1520
77
|
|
|
1521
|
-
|
|
1522
|
-
|
|
78
|
+
```bash
|
|
79
|
+
nvm install
|
|
80
|
+
nvm use
|
|
81
|
+
corepack yarn install
|
|
82
|
+
corepack yarn build
|
|
1523
83
|
```
|
|
1524
84
|
|
|
1525
|
-
|
|
85
|
+
Read [testing and development](docs/testing.md), [contributor guidance](AGENTS.md), and [verification](docs/agent-playbooks/verification.md) for focused checks. Keep API examples aligned with the public exports and types; after documentation changes, run `corepack yarn llms:generate`.
|
|
1526
86
|
|
|
1527
|
-
|
|
1528
|
-
const useBufferedFeedsWithConcurrency = ({feedOptions}) => {
|
|
1529
|
-
|
|
1530
|
-
const communities = useCommunities()
|
|
1531
|
-
|
|
1532
|
-
return useBufferedFeeds({feedsOptions})
|
|
1533
|
-
}
|
|
1534
|
-
|
|
1535
|
-
const feedOptions = [
|
|
1536
|
-
{communities: [{name: 'news.eth'}, {name: 'crypto.eth'}], sortType: 'new'},
|
|
1537
|
-
{communities: [{name: 'memes.eth'}], sortType: 'topWeek'},
|
|
1538
|
-
{communities: [{publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}], sortType: 'hot'},
|
|
1539
|
-
...
|
|
1540
|
-
]
|
|
87
|
+
## License
|
|
1541
88
|
|
|
1542
|
-
|
|
1543
|
-
```
|
|
89
|
+
[GPL-3.0-or-later](LICENSE).
|